diff --git a/docs/compiled/artplayer-proxy-mediabunny.js b/docs/compiled/artplayer-proxy-mediabunny.js index e6fe6ae99..8aa19f7fa 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=e=>{throw TypeError(e)},i=(e,i,r)=>i.has(e)||t("Cannot "+r),r=(e,t,r)=>(i(e,t,"read from private field"),r?r.call(e):t.get(e));function a(e,t){const i=new Map;return e.filter(e=>{const r=e[t];return void 0===r||!i.has(r)&&i.set(r,1)})}class s{constructor(){var i,r,a;i=this,a=!1,(r=e).has(i)?t("Cannot add the same private member more than once"):r instanceof WeakSet?r.add(i):r.set(i,a),this.listeners=new Map}addEventListener(t,i){r(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(r(this,e))return;const a=Object.assign(new Event(t),{detail:i});this.listeners.get(t)?.forEach(t=>{r(this,e)||t(a)})}destroy(){var t,r,a,s;a=!0,i(t=this,r=e,"write to private field"),s?s.call(t,a):r.set(t,a),this.listeners.clear()}}function n(e){if(!e)throw new Error("Assertion failed.")}e=new WeakMap;const o=e=>{const t=(e%360+360)%360;if(0===t||90===t||180===t||270===t)return t;throw new Error(`Invalid rotation ${e}.`)},c=e=>e&&e[e.length-1],l=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)},d=e=>{const t=l(e);return 0===(1&t)?-(t>>1):t+1>>1},h=e=>e.constructor===Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),f=e=>e.constructor===DataView?e:ArrayBuffer.isView(e)?new DataView(e.buffer,e.byteOffset,e.byteLength):new DataView(e),m=new TextDecoder,p=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])),g={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},k=p(g),y={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},b=p(y),w={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},T=p(w),S=e=>!!e&&!!e.primaries&&!!e.transfer&&!!e.matrix&&void 0!==e.fullRange,v={primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0},P=e=>e instanceof ArrayBuffer||"undefined"!==typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e);class I{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 x=/^[0-9a-fA-F]+$/,C=e=>[...e].map(e=>e.toString(16).padStart(2,"0")).join(""),B=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,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},R=(e,t,i)=>{const r=_(e,i(t),i);e.splice(r+1,0,t)},F=()=>{let e,t;return{promise:new Promise((i,r)=>{e=i,t=r}),resolve:e,reject:t}},A=(e,t)=>{const i=e.indexOf(t);-1!==i&&e.splice(i,1)},D=(e,t)=>{for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},M=(e,t)=>{for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},N=e=>{throw new Error(`Unexpected value: ${e}`)},O=(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},L=(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)},z=(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}}),U=(e,t,i)=>Math.max(t,Math.min(i,e)),q="und",W=e=>{const t=Math.round(e);return Math.abs(e/t-1)<10*Number.EPSILON?t:e},H=(e,t)=>Math.round(e/t)*t,V=(e,t)=>Math.round(e*t)/t,j=(e,t)=>Math.floor(e/t)*t,K=e=>{let t=0;for(;0!==e;)e&=e-1,t++;return t},X=/^[a-z]{3}$/,$=e=>X.test(e),G=1e6*(1+Number.EPSILON),Q=(e,t)=>{const i={...e,...t};if(e.headers||t.headers){const r=e.headers?Y(e.headers):{},a=t.headers?Y(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},Y=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},J=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(ve._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 be(1e3*e),a())throw n}};class Z{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}let ee=null;const te=()=>null!==ee?ee:ee=!("undefined"===typeof navigator||!(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent)));let ie=null;const re=()=>null!==ie?ie:ie="undefined"!==typeof navigator&&navigator.userAgent?.includes("Firefox");let ae=null;const se=()=>null!==ae?ae:ae=!("undefined"===typeof navigator||!navigator.vendor?.includes("Google Inc")&&!/Chrome/.test(navigator.userAgent)),ne=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.`,oe=(async()=>{})().constructor,ce=e=>e instanceof oe||e instanceof Promise||"function"===typeof e?.then,le=(e,t)=>-1!==e?e:t,ue=(e,t,i,r)=>e<=r&&i<=t,de=e=>{const t=atob(e),i=new Uint8Array(t.length);for(let r=0;r{Symbol.dispose??(Symbol.dispose=Symbol("Symbol.dispose"))},fe=e=>"number"===typeof e&&!Number.isNaN(e),me=(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("/")},pe=(e,t)=>{let i=0;for(let r=0;r{let i=-1,r=1/0;for(let a=0;a{n(Number.isInteger(e.num)),n(Number.isInteger(e.den)),n(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}},ye=(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.`)},be=e=>new Promise(t=>setTimeout(t,e));class we{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 Te,Se;(Se=Te||(Te={}))[Se.Silent=0]="Silent",Se[Se.Errors=1]="Errors",Se[Se.Warnings=2]="Warnings",Se[Se.Info=3]="Info";class ve{constructor(){}static get level(){return ve._level}static set level(e){if(e!==Te.Silent&&e!==Te.Errors&&e!==Te.Warnings&&e!==Te.Info)throw new TypeError("Invalid log level. Use one of the values of the LogLevel enum.");ve._level=e}static get _emitter(){return ve._emitterInstance??(ve._emitterInstance=new we)}static on(e,t,i){return ve._emitter.on(e,t,i)}static _error(...e){ve._emitter._emit("error",e),ve._level>=Te.Errors&&console.error(...e)}static _warn(...e){ve._emitter._emit("warn",e),ve._level>=Te.Warnings&&console.warn(...e)}static _info(...e){ve._emitter._emit("info",e),ve._level>=Te.Info&&console.info(...e)}}ve._level=Te.Info,ve._emitterInstance=null;class Pe{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 Ie{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 xe={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1};class Ce{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 Ce(this.bytes);return e.pos=this.pos,e}}const Be=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],Ee=[-1,1,2,3,4,5,6,8],_e=e=>{if(!e||e.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");const t=new Ce(e),i=Re(t),{frequencyIndex:r,sampleRate:a}=Fe(t),s=t.readBits(4);let n=null;s>=1&&s<=7&&(n=Ee[s]);let o=i,c=!1,l=a;if(5===i||29===i)c=29===i,l=Fe(t).sampleRate,o=Re(t),22===o&&t.skipBits(4);else for(;t.getBitsLeft()>15;){const e=t.pos;if(695===t.readBits(11)){5===Re(t)&&t.readBits(1)&&(l=Fe(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}},Re=e=>{const t=e.readBits(5);return 31===t?32+e.readBits(6):t},Fe=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&h(t.description)[4];return Ue(e,i+1)}return ze(e)},We=e=>31&e,He=e=>{const t=[],i=e.length;for(let r=0;r{const t=e.reduce((e,t)=>e+Ve.byteLength+t.byteLength,0),i=new Uint8Array(t);let r=0;for(const a of e)i.set(Ve,r),r+=Ve.byteLength,i.set(a,r),r+=a.byteLength;return i},Ke=(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:L(e,a,s.byteLength);break;case 4:e.setUint32(a,s.byteLength,!1)}a+=t,r.set(s,a),a+=s.byteLength}return r},Xe=e=>{try{const t=[],i=[],r=[];for(const n of ze(e)){const a=e.subarray(n.offset,n.offset+n.length),s=We(a[0]);s===Me.SPS?t.push(a):s===Me.PPS?i.push(a):s===Me.SPS_EXT&&r.push(a)}if(0===t.length)return null;if(0===i.length)return null;const a=t[0],s=Ye(a);n(null!==s);const o=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:o?s.chromaFormatIdc:null,bitDepthLumaMinus8:o?s.bitDepthLumaMinus8:null,bitDepthChromaMinus8:o?s.bitDepthChromaMinus8:null,sequenceParameterSetExt:o?r:null}}catch(t){return ve._error("Error building AVC Decoder Configuration Record:",t),null}},$e=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=f(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=He(e),i=new Ce(t);i.skipBits(1),i.skipBits(2);if(7!==i.readBits(5))return null;const r=i.readAlignedByte(),a=i.readAlignedByte(),s=i.readAlignedByte();l(i);let o=1,u=0,h=0,f=0;if(100===r||110===r||122===r||244===r||44===r||83===r||86===r||118===r||128===r){o=l(i),3===o&&(f=i.readBits(1)),u=l(i),h=l(i),i.skipBits(1);if(i.readBits(1))for(let e=0;e<(3!==o?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)??c($t),r=Math.min(Math.floor(i.maxDpbMbs/(e*t)),16);C=r,B=r}else C=0,B=0}return n(null!==B),{emulationUnpreventedBytes:t,profileIdc:r,constraintFlags:a,levelIdc:s,frameMbsOnlyFlag:T,chromaFormatIdc:o,bitDepthLumaMinus8:u,bitDepthChromaMinus8:h,codedWidth:k,codedHeight:y,displayWidth:b,displayHeight:w,pixelAspectRatio:x,colourPrimaries:S,matrixCoefficients:P,transferCharacteristics:v,fullRangeFlag:I,numReorderFrames:C,maxDecFrameBuffering:B,vuiParametersFlagBitOffset:R,bitstreamRestrictionFlagBitOffset:E,bitstreamRestrictionFlag:_}}catch(t){return ve._error("Error parsing AVC SPS:",t),null}},Je=e=>{const t=l(e);e.skipBits(4),e.skipBits(4);for(let i=0;i<=t;i++)l(e),l(e),e.skipBits(1);e.skipBits(5),e.skipBits(5),e.skipBits(5),e.skipBits(5)},Ze=e=>{n(1!==e.bitstreamRestrictionFlag);const t=new Uint8Array(e.emulationUnpreventedBytes.byteLength+64),i=new Ce(e.emulationUnpreventedBytes),r=new Ce(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)):(n(null!==e.bitstreamRestrictionFlagBitOffset),r.copyBits(e.bitstreamRestrictionFlagBitOffset,i)),r.writeBits(1,1),r.writeBits(1,1),u(r,2),u(r,1),u(r,16),u(r,16),u(r,e.numReorderFrames),u(r,e.maxDecFrameBuffering),r.writeBits(1,1),r.writeBits((8-r.pos%8)%8,0);const a=r.pos/8;return n(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))},et=(e,t)=>{if(t.description){const i=3&h(t.description)[21];return Ue(e,i+1)}return ze(e)},tt=e=>e>>1&63,it=e=>{try{const t=new Ce(He(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:u}=at(t,i);l(t);const d=l(t);let h=0;3===d&&(h=t.readBits(1));const f=l(t),m=l(t);let p=f,g=m;if(t.readBits(1)){const e=l(t),i=l(t),r=l(t),a=l(t);let s=1,n=1;const o=0===h?d:0;1===o?(s=2,n=2):2===o&&(s=2,n=1),p-=(e+i)*s,g-=(r+a)*n}const k=l(t),y=l(t);l(t);const b=t.readBits(1);let w=0;for(let e=b?0:i;e<=i;e++)l(t),w=l(t),l(t);l(t),l(t),l(t),l(t),l(t),l(t),t.readBits(1)&&t.readBits(1)&&st(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(4),t.skipBits(4),l(t),l(t),t.skipBits(1));const T=l(t);if(nt(t,T),t.readBits(1)){const e=l(t);for(let i=0;i{try{const t=[],i=[],r=[],a=[];for(const c of ze(e)){const s=e.subarray(c.offset,c.offset+c.length),n=tt(s[0]);n===Oe.VPS_NUT?t.push(s):n===Oe.SPS_NUT?i.push(s):n===Oe.PPS_NUT?r.push(s):n!==Oe.PREFIX_SEI_NUT&&n!==Oe.SUFFIX_SEI_NUT||a.push(s)}if(0===i.length||0===r.length)return null;const s=it(i[0]);if(!s)return null;let n=0;if(r.length>0){const e=r[0],t=new Ce(He(e));t.skipBits(16),l(t),l(t),t.skipBits(1),t.skipBits(1),t.skipBits(3),t.skipBits(1),t.skipBits(1),l(t),l(t),d(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&l(t),d(t),d(t),t.skipBits(1),t.skipBits(1),t.skipBits(1),t.skipBits(1);const i=t.readBits(1),a=t.readBits(1);n=i||a?i&&!a?2:!i&&a?3:0:0}const o=[...t.length?[{arrayCompleteness:1,nalUnitType:Oe.VPS_NUT,nalUnits:t}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:Oe.SPS_NUT,nalUnits:i}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:Oe.PPS_NUT,nalUnits:r}]:[],...a.length?[{arrayCompleteness:1,nalUnitType:tt(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 ve._error("Error building HEVC Decoder Configuration Record:",t),null}},at=(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&&d(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-(l(e)+1)}else n=t-1;e.readBits(1),l(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=l(e),i=l(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=Qe[t];e&&(o=e)}}return e.readBits(1)&&e.readBits(1),e.readBits(1)&&(e.readBits(3),s=e.readBits(1),e.readBits(1)&&(i=e.readBits(8),r=e.readBits(8),a=e.readBits(8))),e.readBits(1)&&(l(e),l(e)),e.readBits(1),e.readBits(1),e.readBits(1),e.readBits(1)&&(l(e),l(e),l(e),l(e)),e.readBits(1)&&(e.readBits(32),e.readBits(32),e.readBits(1)&&l(e),e.readBits(1)&<(e,!0,t)),e.readBits(1)&&(e.readBits(1),e.readBits(1),e.readBits(1),n=l(e),l(e),l(e),l(e),l(e)),{pixelAspectRatio:o,colourPrimaries:i,transferCharacteristics:r,matrixCoefficients:a,fullRangeFlag:s,minSpatialSegmentationIdc:n}},lt=(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?l(e):i=1===e.readBits(1);let n=1;if(!i){n=l(e)+1}r&&ut(e,n,s),a&&ut(e,n,s)}},ut=(e,t,i)=>{for(let r=0;r{const i=new Set;let r=dt.audAllowed;for(const s of et(e,t)){if(r===dt.noMoreDataAllowed){i.add(s.offset);continue}const t=tt(e[s.offset]);if(r===dt.eoBitstreamAllowed&&37!==t){i.add(s.offset);continue}let a=!1;35===t?r>dt.audAllowed?a=!0:r=dt.beforeFirstVcl:t<=31?r>dt.afterFirstVcl?a=!0:r=dt.afterFirstVcl:36===t?r!==dt.afterFirstVcl?a=!0:r=dt.eoBitstreamAllowed:37===t?r=41&&t<=44||t>=48&&t<=55?r>dt.beforeFirstVcl?a=!0:r=dt.beforeFirstVcl:(38===t||40===t||t>=45&&t<=47||t>=56&&t<=63)&&r{if(t.description){const i=3&h(t.description)[21];return Ke(e,i+1)}return je(e)})(a,t)},mt={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}},pt=e=>{const t=new Ce(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 l=(t.readBits(16)+1)*(t.readBits(16)+1);let u=c(Gt).level;for(const c of Gt)if(l<=c.maxPictureSize){u=c.level;break}const d=mt[s];return{profile:r,level:u,bitDepth:a,chromaSubsampling:n,videoFullRangeFlag:o,colourPrimaries:d?.colourPrimaries??2,transferCharacteristics:d?.transferCharacteristics??2,matrixCoefficients:d?.matrixCoefficients??2}},gt=function*(e){const t=new Ce(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 o;if(t.skipBits(1),a&&t.skipBits(8),s){const e=i();if(null===e)return;o=e}else o=Math.floor(t.getBitsLeft()/8);n(t.pos%8===0),yield{type:r,data:e.subarray(t.pos/8,t.pos/8+o)},t.skipBits(8*o)}},kt=e=>{for(const{type:t,data:i}of gt(e)){if(1!==t)continue;const e=new Ce(i),r=e.readBits(3);e.readBits(1);const a=e.readBits(1);let s=0,n=0,o=0;if(a)s=e.readBits(5);else{let t=0;if(e.readBits(1)){e.skipBits(32),e.skipBits(32);if(e.readBits(1)){let t=0;for(;t<32&&!e.readBits(1);)t++;t<32&&e.skipBits(t)}t=e.readBits(1),t&&(o=e.readBits(5),e.skipBits(32),e.skipBits(5),e.skipBits(5))}const i=e.readBits(1),r=e.readBits(5);for(let a=0;a<=r;a++){e.skipBits(12);const r=e.readBits(5);if(0===a&&(s=r),r>7){const t=e.readBits(1);0===a&&(n=t)}if(t){if(e.readBits(1)){const t=o+1;e.skipBits(t),e.skipBits(t),e.skipBits(1)}}if(i){e.readBits(1)&&e.skipBits(4)}}}const c=e.readBits(4),l=e.readBits(4),u=c+1;e.skipBits(u);const d=l+1;e.skipBits(d);let h=0;if(h=a?0:e.readBits(1),h&&(e.skipBits(4),e.skipBits(3)),e.skipBits(1),e.skipBits(1),e.skipBits(1),!a){e.skipBits(1),e.skipBits(1),e.skipBits(1),e.skipBits(1);const t=e.readBits(1);t&&(e.skipBits(1),e.skipBits(1));let i=0;if(i=e.readBits(1)?2:e.readBits(1),i>0){e.readBits(1)||e.skipBits(1)}t&&e.skipBits(3)}e.skipBits(1),e.skipBits(1),e.skipBits(1);const f=e.readBits(1);let m=8;if(2===r&&f){m=e.readBits(1)?12:10}else r<=2&&(m=f?10:8);let p=0;1!==r&&(p=e.readBits(1));let g=2,k=2,y=2;e.readBits(1)&&(g=e.readBits(8),k=e.readBits(8),y=e.readBits(8));let b=0,w=1,T=1,S=0;return p?b=e.readBits(1):1===g&&13===k&&0===y?(b=1,w=0,T=0):(b=e.readBits(1),0===r?(w=1,T=1):1===r?(w=0,T=0):12===m?(w=e.readBits(1),T=w?e.readBits(1):0):(w=1,T=0),w&&T&&(S=e.readBits(2))),{profile:r,level:s,tier:n,bitDepth:m,monochrome:p,chromaSubsamplingX:w,chromaSubsamplingY:T,chromaSamplePosition:S,videoFullRangeFlag:b,colourPrimaries:g,transferCharacteristics:k,matrixCoefficients:y}}return null},yt=e=>{if(e.length<36)return null;const t=f(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)}},bt=[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],wt=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}},Tt=(e,t,i)=>{switch(e){case"avc":for(const e of qe(i,t)){const t=i[e.offset],r=We(t);if(r>=Me.NON_IDR_SLICE&&r<=Me.SLICE_DPC)return"delta";if(r===Me.IDR)return"key";if(r===Me.SEI&&!se()){const t=i.subarray(e.offset,e.offset+e.length),r=He(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 Ce(r);e.pos=8*a;const t=l(e),i=e.readBits(1);if(0===t&&1===i)return"key"}a+=t}while(a{var i,r;const a=f(e);let s=0;const n=a.getUint32(s,!0);s+=4;const o=m.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=de(l),i=f(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=m.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})}}}},It=[2,1,2,3,3,4,4,5],xt=e=>{if(e.length<7)return null;if(11!==e[0]||119!==e[1])return null;const t=new Ce(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)}},Ct=[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],Bt=[1,2,3,6],Et=e=>{if(e.length<6)return null;if(11!==e[0]||119!==e[1])return null;const t=new Ce(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=Bt[s];let d;d=a<3?Ae[a]/1e3:De[n]/1e3;return{dataRate:Math.round((r+1)*d/(16*u)),substreams:[{fscod:a,fscod2:n,bsid:l,bsmod:0,acmod:o,lfeon:c,numDepSub:0,chanLoc:0}]}},_t=e=>{const t=e.substreams[0];return n(t),t.fscod<3?Ae[t.fscod]:null!==t.fscod2&&t.fscod2<3?De[t.fscod2]:null},Rt=e=>{const t=e.substreams[0];n(t);let i=It[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},Ft=[0,8e3,16e3,32e3,0,0,11025,22050,44100,0,0,12e3,24e3,48e3,96e3,192e3],At=[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],Dt=[16,16,20,20,0,24,24,0],Mt=[1,2,2,2,2,3,3,4,4,5,6,6,6,7,8,8],Nt=[1,2,2,2,2,3,18,19,6,7,518,323,83,519,582,535],Ot=[32e3,44100,48e3,0],Lt=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],zt=[512,1024,2048,4096],Ut=e=>{const t=Wt(e),i=f(e);let r=t?4*Math.ceil(t.frameSize/4):0,a=null;for(;r+4<=e.length&&1683496997===i.getUint32(r);){const t=Ht(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}},qt=e=>{const t=Ut(e);return t?.core?t.hasExtensions?"dtsh":"dtsc":null},Wt=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 Ce(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>=Mt.length)return null;const n=Ft[t.readBits(4)];if(0===n)return null;const o=At[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=Dt[t.readBits(3)];if(0===l)return null;const u=0!==c;return{frameSize:a,sampleRate:n,numberOfChannels:Mt[s]+(u?1:0),sampleCount:32*r,channelLayout:Nt[s]|(u?8:0),amode:s,lfePresent:u,bitRate:o,pcmResolution:l}},Ht=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 Ce(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=Ot[t.readBits(2)],l=512*(t.readBits(3)+1);t.readBits(1)&&t.skipBits(36);const u=t.readBits(3)+1,d=t.readBits(3)+1,h=[];for(let k=0;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}}},Vt=e=>K(e)+K(44646&e),jt=["avc","hevc","vp9","av1","vp8","prores"],Kt=["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"],Xt=["aac","opus","mp3","vorbis","flac","ac3","eac3","dts",...Kt],$t=[{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}],Gt=[{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}],Qt=".01.01.01.01.00",Yt=".0.110.01.01.01.0",Jt=["ap4x","ap4h","apch","apcn","apcs","apco"],Zt=["dtsc","dtsh","dtsl","dtse"],ei=e=>{const{codec:t,codecDescription:i,colorSpace:r,avcCodecInfo:a,hevcCodecInfo:s,vp9CodecInfo:o,av1CodecInfo:l,proresFormat:u}=e;if("avc"===t){if(n(null!==e.avcType),a){const t=new Uint8Array([a.avcProfileIndication,a.profileCompatibility,a.avcLevelIndication]);return`avc${e.avcType}.${C(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}.${C(i.subarray(1,4))}`}if("hevc"===t){let e,t,r,a,n,o;if(s)e=s.generalProfileSpace,t=s.generalProfileIdc,r=B(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=f(i),c=s.getUint8(1);e=c>>6&3,t=31&c,r=B(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(!o){const t=e.width*e.height;let i=c(Gt).level;for(const e of Gt)if(t<=e.maxPictureSize){i=e.level;break}return`vp09.00.${i.toString().padStart(2,"0")}.08`}let t=`vp09.${o.profile.toString().padStart(2,"0")}.${o.level.toString().padStart(2,"0")}.${o.bitDepth.toString().padStart(2,"0")}.${o.chromaSubsampling.toString().padStart(2,"0")}`;return t+=`.${o.colourPrimaries.toString().padStart(2,"0")}.${o.transferCharacteristics.toString().padStart(2,"0")}.${o.matrixCoefficients.toString().padStart(2,"0")}.${o.videoFullRangeFlag.toString().padStart(2,"0")}`,t.endsWith(Qt)&&(t=t.slice(0,-15)),t}if("av1"===t){if(!l){const t=e.width*e.height;let i=c(Gt).level;for(const e of Gt)if(t<=e.maxPictureSize){i=e.level;break}return`av01.0.${i.toString().padStart(2,"0")}M.08`}const t=l.profile,i=l.level.toString().padStart(2,"0"),a=l.tier?"H":"M",s=l.bitDepth.toString().padStart(2,"0"),n=l.monochrome?"1":"0",o=100*l.chromaSubsamplingX+10*l.chromaSubsamplingY+1*(l.chromaSubsamplingX&&l.chromaSubsamplingY?l.chromaSamplePosition:0),u=r?.primaries?g[r.primaries]:1,d=r?.transfer?y[r.transfer]:1,h=r?.matrix?w[r.matrix]:1,f=r?.fullRange?1:0;let m=`av01.${t}.${i}${a}.${s}`;return m+=`.${n}.${o.toString().padStart(3,"0")}`,m+=`.${u.toString().padStart(2,"0")}`,m+=`.${d.toString().padStart(2,"0")}`,m+=`.${h.toString().padStart(2,"0")}`,m+=`.${f}`,m.endsWith(Yt)&&(m=m.slice(0,-17)),m}if("prores"===t)return u??"apch";throw null!==t&&N(t),new TypeError(`Unhandled codec '${t}'.`)},ti=e=>{switch(e.codec){case"avc":{let t=e.avcCodecInfo?.sequenceParameterSets[0];if(!t&&e.codecDescription&&(t=Ge(e.codecDescription)?.sequenceParameterSets[0]),t){const e=Ye(t);if(e)return{primaries:k[e.colourPrimaries],transfer:b[e.transferCharacteristics],matrix:T[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case"hevc":{let t=e.hevcCodecInfo?.arrays.find(e=>e.nalUnitType===Oe.SPS_NUT)?.nalUnits[0];if(!t&&e.codecDescription&&(t=(e=>{try{const t=f(e);let i=0;const r=t.getUint8(i++),a=t.getUint8(i++),s=a>>6&3,n=a>>5&1,o=31&a,c=t.getUint32(i,!1);i+=4;const l=e.subarray(i,i+6);i+=6;const u=t.getUint8(i++),d=(15&t.getUint8(i++))<<8|t.getUint8(i++),h=3&t.getUint8(i++),m=3&t.getUint8(i++),p=7&t.getUint8(i++),g=7&t.getUint8(i++),k=t.getUint16(i,!1);i+=2;const y=t.getUint8(i++),b=y>>6&3,w=y>>3&7,T=y>>2&1,S=3&y,v=t.getUint8(i++),P=[];for(let f=0;f>7&1,s=63&r,n=t.getUint16(i,!1);i+=2;const o=[];for(let c=0;ce.nalUnitType===Oe.SPS_NUT)?.nalUnits[0]),t){const e=it(t);if(e)return{primaries:k[e.colourPrimaries],transfer:b[e.transferCharacteristics],matrix:T[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case"vp8":break;case"vp9":if(e.vp9CodecInfo)return{primaries:k[e.vp9CodecInfo.colourPrimaries],transfer:b[e.vp9CodecInfo.transferCharacteristics],matrix:T[e.vp9CodecInfo.matrixCoefficients],fullRange:!!e.vp9CodecInfo.videoFullRangeFlag};break;case"av1":if(e.av1CodecInfo)return{primaries:k[e.av1CodecInfo.colourPrimaries],transfer:b[e.av1CodecInfo.transferCharacteristics],matrix:T[e.av1CodecInfo.matrixCoefficients],fullRange:!!e.av1CodecInfo.videoFullRangeFlag};break;case"prores":if(e.proresCodecInfo)return{primaries:k[e.proresCodecInfo.colourPrimaries],transfer:b[e.proresCodecInfo.transferCharacteristics],matrix:T[e.proresCodecInfo.matrixCoefficients],fullRange:e.proresCodecInfo.fullRange}}return{primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0}},ii=e=>{const{codec:t,codecDescription:i,aacCodecInfo:r,dtsFormat:a}=e;if("aac"===t){if(!r)throw new TypeError("AAC codec info must be provided.");if(r.isMpeg2)return"mp4a.67";{let e;if(null!==r.objectType)e=r.objectType;else{e=_e(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&&Kt.includes(t))return t;throw new TypeError(`Unhandled codec '${t}'.`)},ri=48e3,ai=/^pcm-([usf])(\d+)(be)?$/,si=e=>{if(n(Kt.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=ai.exec(e);let i;n(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}},ni=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":Jt.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":Zt.includes(e)?"dts":"ulaw"===e?"ulaw":"alaw"===e?"alaw":ai.test(e)?e:"webvtt"===e?"webvtt":null,oi=[44100,48e3,32e3],ci=[-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],li=1483304551,ui=1231971951,di=(e,t)=>3===e?3===t?21:36:3===t?13:21,hi=(e,t)=>{const i=e>>>24,r=e>>>16&255,a=e>>>8&255,s=255&e;if(255!==i&&255!==r&&255!==a&&255!==s)return{header:null,bytesAdvanced:4};if(255!==i)return{header:null,bytesAdvanced:1};if(224!==(224&r))return{header:null,bytesAdvanced:1};let n=0,o=0;16&r?n=8&r?0:1:(n=1,o=1);const c=r>>3&3,l=r>>1&3,u=(a>>2&3)%3,d=s>>6&3,h=s>>4&3,f=s>>3&1,m=s>>2&1,p=3&s,g=ci[16*n*4+16*l+(a>>4&15)];if(-1===g)return{header:null,bytesAdvanced:1};const k=1e3*g,y=oi[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 mi,pi;(pi=mi||(mi={}))[pi.FrameCount=1]="FrameCount",pi[pi.FileSize=2]="FileSize",pi[pi.Toc=4]="Toc";const gi=e=>3===e?1:2;class ki{constructor(e){this.input=e}dispose(){}}const yi=new Uint8Array(0);class bi{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===yi&&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===yi}get microsecondTimestamp(){return Math.trunc(G*this.timestamp)}get microsecondDuration(){return Math.trunc(G*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 bi(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 bi(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 wi=e=>{const t=f(e);let i=0;const r=t.getUint8(i);i+=1,i+=3;const a=C(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=Io(e);const i=Do(e,4);let r=8;1===t&&(t=Eo(e),r=16);const a=t-r;return a<0?null:{name:i,totalSize:t,headerSize:r,contentSize:a}},vi=e=>Co(e)/65536,Pi=e=>Co(e)/1073741824,Ii=e=>{let t=0;for(let i=0;i<4;i++){t<<=7;const i=bo(e);if(t|=127&i,0===(128&i))break}return t},xi=e=>{let t=To(e);return e.skip(2),t=Math.min(t,e.remainingLength),m.decode(yo(e,t))},Ci=e=>{const t=Si(e);if(!t||"data"!==t.name)return null;if(e.remainingLength<8)return null;const i=Io(e);e.skip(4);const r=yo(e,t.contentSize-8);switch(i){case 1:return m.decode(r);case 2:return new TextDecoder("utf-16be").decode(r);case 13:return new Pe(r,"image/jpeg");case 14:return new Pe(r,"image/png");case 27:return new Pe(r,"image/bmp");default:return r}},Bi=16,Ei=new Uint32Array(256),_i=new Uint32Array(256),Ri=new Uint32Array(256),Fi=new Uint32Array(256),Ai=new Uint32Array(256),Di=new Uint32Array(256),Mi=new Uint32Array(10);let Ni=!1;class Oi{constructor(){this.roundkey=new Uint32Array(44),this.iv=new Uint32Array(Bi/Uint32Array.BYTES_PER_ELEMENT),this.in=new Uint8Array(Bi),this.out=new Uint8Array(Bi),this.inView=new DataView(this.in.buffer),this.outView=new DataView(this.out.buffer)}init({key:e,iv:t}){n(16===e.byteLength),n(16===t.byteLength),Ni||(()=>{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);Ei[s]=t<<24|t<<16|t<<8|t,Di[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);_i[s]=a,Ri[s]=a>>>8|a<<24,Fi[s]=a>>>16|a<<16,Ai[s]=a>>>24|a<<8}let a=1;for(let s=0;s<10;s++)Mi[s]=a<<24,a=a<<1^(128&a?283:0);Ni=!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&Ei[e>>>16&255]^16711680&Ei[e>>>8&255]^65280&Ei[e>>>0&255]^255&Ei[e>>>24&255]^Mi[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]]^Ri[255&Ei[t>>>16&255]]^Fi[255&Ei[t>>>8&255]]^Ai[255&Ei[t>>>0&255]]}}decrypt(){let e=this.inView.getUint32(0,!1)^this.roundkey[0],t=this.inView.getUint32(4,!1)^this.roundkey[1],i=this.inView.getUint32(8,!1)^this.roundkey[2],r=this.inView.getUint32(12,!1)^this.roundkey[3];const a=this.inView.getUint32(0,!1),s=this.inView.getUint32(4,!1),n=this.inView.getUint32(8,!1),o=this.inView.getUint32(12,!1);let c,l,u,d;for(let g=1;g<10;g++){const a=4*g;c=_i[e>>>24]^Ri[r>>>16&255]^Fi[i>>>8&255]^Ai[255&t]^this.roundkey[a],l=_i[t>>>24]^Ri[e>>>16&255]^Fi[r>>>8&255]^Ai[255&i]^this.roundkey[a+1],u=_i[i>>>24]^Ri[t>>>16&255]^Fi[e>>>8&255]^Ai[255&r]^this.roundkey[a+2],d=_i[r>>>24]^Ri[i>>>16&255]^Fi[t>>>8&255]^Ai[255&e]^this.roundkey[a+3],e=c,t=l,i=u,r=d}const h=4278190080&Di[e>>>24&255]^16711680&Di[r>>>16&255]^65280&Di[i>>>8&255]^255&Di[t>>>0&255]^this.roundkey[40],f=4278190080&Di[t>>>24&255]^16711680&Di[e>>>16&255]^65280&Di[r>>>8&255]^255&Di[i>>>0&255]^this.roundkey[41],m=4278190080&Di[i>>>24&255]^16711680&Di[t>>>16&255]^65280&Di[e>>>8&255]^255&Di[r>>>0&255]^this.roundkey[42],p=4278190080&Di[r>>>24&255]^16711680&Di[i>>>16&255]^65280&Di[t>>>8&255]^255&Di[e>>>0&255]^this.roundkey[43];this.outView.setUint32(0,h^this.iv[0],!1),this.outView.setUint32(4,f^this.iv[1],!1),this.outView.setUint32(8,m^this.iv[2],!1),this.outView.setUint32(12,p^this.iv[3],!1),this.iv[0]=a,this.iv[1]=s,this.iv[2]=n,this.iv[3]=o}}class Li extends ki{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(ce(r)&&(r=await r),!r)break;const a=e,s=Si(r);if(!s)break;if("ftyp"===s.name||"styp"===s.name){const e=Do(r,4);this.isQuickTime="qt "===e}else{if("moov"===s.name){let e=this.reader.requestSlice(r.filePos,s.contentSize);if(ce(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){n(null!==this.reader.fileSize);let e=this.reader.requestSlice(this.reader.fileSize-4,4);ce(e)&&(e=await e),n(e);const t=Io(e),i=this.reader.fileSize-t;if(i>=0&&i<=this.reader.fileSize-16){let e=this.reader.requestSliceRange(i,8,16);if(ce(e)&&(e=await e),e){const t=Si(e);if(t&&"mfra"===t.name){let i=this.reader.requestSlice(e.filePos,t.contentSize);ce(i)&&(i=await i),i&&this.readContiguousBoxes(i)}}}}})())}async copyMetadataFromInitInput(e){const t=await e._getDemuxer();if(t.constructor!==Li)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(n(e.info),"video"===e.info.type&&-1!==e.info.width){const t=e;e.trackBacking=new Ui(t),this.tracks.push(e)}else if("audio"===e.info.type&&-1!==e.info.numberOfChannels){const t=e;e.trackBacking=new qi(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;n(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&&Kt.includes(e.info.codec)&&0===t.sampleCompositionTimeOffsets.length){n("audio"===e.info?.type);const i=si(e.info.codec),r=[],a=[];for(let s=0;se.startIndex),d=t.sampleTimingEntries[u],h=_(t.sampleTimingEntries,l,e=>e.startIndex),f=t.sampleTimingEntries[h],m=d.startDecodeTimestamp+(o-d.startIndex)*d.delta,p=f.startDecodeTimestamp+(l-f.startIndex)*f.delta-m,g=c(r);g&&g.delta===p?g.count++:r.push({startIndex:n.startChunkIndex+s,startDecodeTimestamp:m,count:1,delta:p});const k=n.samplesPerChunk*i.sampleSize*e.info.numberOfChannels;a.push(k)}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)Ki(s,i.timestamp);else{const e=_(t,a.moofOffset-1,e=>e.moofOffset);if(-1!==e){const i=t[e];Ki(s,i.endTimestamp)}}s.startTimestampIsFinal=!0}const i=_(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 Qi(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;$(t.languageCode)||(t.languageCode=q)}}break;case"hdlr":{const t=this.currentTrack;if(!t)break;e.skip(8);const i=Do(e,4);"vide"===i?t.info={type:"video",width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:{...v},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=K,this.readContiguousBoxes(e.slice(G,X.contentSize))}break;case"stsd":{const t=this.currentTrack;if(!t)break;if(null===t.info||t.sampleTable)break;const i=bo(e);e.skip(3);const r=Io(e);for(let a=0;a0&&(1===n?(e.skip(4),c=8*Io(e),e.skip(8)):2===n&&(e.skip(4),l=Ao(e),o=Io(e),e.skip(4),c=Io(e),u=Io(e),e.skip(8))),t.info.numberOfChannels=o,t.info.sampleRate=l,t.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,r+a.totalSize-e.filePos));const d="enca"===s?t.frmaCodecString:s;if(t.frmaCodecString=null,"mp4a"===d);else if("opus"===d)t.info.codec="opus",t.info.sampleRate=ri;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(Zt.includes(d))t.info.codec="dts",t.info.dtsFormat=d;else if("twos"===d)8===c?t.info.codec="pcm-s8":16===c?t.info.codec=t.info.pcmLittleEndian?"pcm-s16":"pcm-s16be":(ve._warn(`Unsupported sample size ${c} for codec 'twos'.`),t.info.codec=null);else if("sowt"===d)8===c?t.info.codec="pcm-s8":16===c?t.info.codec="pcm-s16":(ve._warn(`Unsupported sample size ${c} for codec 'sowt'.`),t.info.codec=null);else if("raw "===d)t.info.codec="pcm-u8";else if("in24"===d)t.info.codec=t.info.pcmLittleEndian?"pcm-s24":"pcm-s24be";else if("in32"===d)t.info.codec=t.info.pcmLittleEndian?"pcm-s32":"pcm-s32be";else if("fl32"===d)t.info.codec=t.info.pcmLittleEndian?"pcm-f32":"pcm-f32be";else if("fl64"===d)t.info.codec=t.info.pcmLittleEndian?"pcm-f64":"pcm-f64be";else if("ipcm"===d){const e=t.info.pcmSampleSize;t.info.pcmLittleEndian?16===e?t.info.codec="pcm-s16":24===e?t.info.codec="pcm-s24":32===e?t.info.codec="pcm-s32":(ve._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":(ve._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":(ve._warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null):32===e?t.info.codec="pcm-f32be":64===e?t.info.codec="pcm-f64be":(ve._warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null)}else if("lpcm"===d&&null!==u){const e=c+7>>3,i=Boolean(1&u),r=Boolean(2&u),a=4&u?-1:0;c>0&&c<=64&&(i?32===c&&(t.info.codec=r?"pcm-f32be":"pcm-f32"):a&1<0?(t.encryptionInfo.defaultCryptByteBlock=r>>4,t.encryptionInfo.defaultSkipByteBlock=15&r):(t.encryptionInfo.defaultCryptByteBlock=0,t.encryptionInfo.defaultSkipByteBlock=0),t.encryptionInfo.defaultIsProtected=0!==bo(e),t.encryptionInfo.defaultPerSampleIvSize=bo(e),t.encryptionInfo.defaultKid=C(yo(e,16)),t.encryptionInfo.defaultIsProtected&&0===t.encryptionInfo.defaultPerSampleIvSize){const i=bo(e),r=new Uint8Array(16);r.set(yo(e,i),0),t.encryptionInfo.defaultConstantIv=r}}break;case"avcC":{const t=this.currentTrack;if(!t)break;if(n(t.info),0===X.contentSize)break;t.info.codecDescription=yo(e,X.contentSize)}break;case"hvcC":{const t=this.currentTrack;if(!t)break;if(n(t.info),0===X.contentSize)break;t.info.codecDescription=yo(e,X.contentSize)}break;case"vpcC":{const t=this.currentTrack;if(!t)break;n("video"===t.info?.type),e.skip(4);const i=bo(e),r=bo(e),a=bo(e),s=a>>4,o=a>>1&7,c=1&a,l=bo(e),u=bo(e),d=bo(e);t.info.vp9CodecInfo={profile:i,level:r,bitDepth:s,chromaSubsampling:o,videoFullRangeFlag:c,colourPrimaries:l,transferCharacteristics:u,matrixCoefficients:d}}break;case"av1C":{const t=this.currentTrack;if(!t)break;n("video"===t.info?.type),e.skip(1);const i=bo(e),r=i>>5,a=31&i,s=bo(e),o=s>>7,c=s>>6&1,l=s>>4&1,u=s>>3&1,d=s>>2&1,h=3&s,f=2===r&&c?s>>5&1?12:10:c?10:8;e.skip(1);const m=yo(e,X.contentSize-4),p=kt(m);t.info.av1CodecInfo={profile:r,level:a,tier:o,bitDepth:f,monochrome:l,chromaSubsamplingX:u,chromaSubsamplingY:d,chromaSamplePosition:h,videoFullRangeFlag:p?.videoFullRangeFlag??0,colourPrimaries:p?.colourPrimaries??2,transferCharacteristics:p?.transferCharacteristics??2,matrixCoefficients:p?.matrixCoefficients??2}}break;case"colr":{const t=this.currentTrack;if(!t)break;n("video"===t.info?.type);const i=Do(e,4);if("nclx"!==i&&"nclc"!==i)break;const r=To(e),a=To(e),s=To(e);let o;"nclx"===i&&(o=Boolean(128&bo(e))),t.info.colorSpace={primaries:k[r],transfer:b[a],matrix:T[s],fullRange:o}}break;case"pasp":{const t=this.currentTrack;if(!t)break;n("video"===t.info?.type);const i=Io(e),r=Io(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);n(3===bo(e)),Ii(e),e.skip(2);const i=bo(e),r=0!==(64&i),a=0!==(32&i);if(0!==(128&i)&&e.skip(2),r){const t=bo(e);e.skip(t)}a&&e.skip(2);n(4===bo(e));const s=Ii(e),o=e.filePos,c=bo(e);if(64===c||103===c?(t.info.codec="aac",t.info.aacCodecInfo={isMpeg2:103===c,objectType:null}):105===c||107===c?t.info.codec="mp3":221===c?t.info.codec="vorbis":169===c?t.info.codec="dts":ve._warn(`Unsupported audio codec (objectTypeIndication ${c}) - discarding track.`),e.skip(12),s>e.filePos-o){n(5===bo(e));const i=Ii(e);if(t.info.codecDescription=yo(e,i),"aac"===t.info.codec){const e=_e(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;n("audio"===t.info?.type),t.info.pcmLittleEndian=!!(255&To(e))}break;case"pcmC":{const t=this.currentTrack;if(!t)break;n("audio"===t.info?.type),e.skip(4);const i=bo(e);t.info.pcmLittleEndian=Boolean(1&i),t.info.pcmSampleSize=bo(e)}break;case"dOps":{const t=this.currentTrack;if(!t)break;n("audio"===t.info?.type),e.skip(1);const i=bo(e),r=To(e),a=Io(e),s=vo(e),o=bo(e);let c;c=0!==o?yo(e,2+i):new Uint8Array(0);const l=new Uint8Array(19+c.byteLength),u=new DataView(l.buffer);u.setUint32(0,1332770163,!1),u.setUint32(4,1214603620,!1),u.setUint8(8,1),u.setUint8(9,i),u.setUint16(10,r,!0),u.setUint32(12,a,!0),u.setInt16(16,s,!0),u.setUint8(18,o),l.set(c,19),t.info.codecDescription=l,t.info.numberOfChannels=i}break;case"dfLa":{const t=this.currentTrack;if(!t)break;n("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 o=yo(e,s-a),c=new Uint8Array(4+o.byteLength);new DataView(c.buffer).setUint32(0,1716281667,!1),c.set(o,4),t.info.codecDescription=c}break;case"dac3":{const t=this.currentTrack;if(!t)break;n("audio"===t.info?.type);const i=yo(e,3),r=new Ce(i),a=r.readBits(2);r.skipBits(8);const s=r.readBits(3),o=r.readBits(1);a<3&&(t.info.sampleRate=Ae[a]),t.info.numberOfChannels=It[s]+o}break;case"dec3":{const t=this.currentTrack;if(!t)break;n("audio"===t.info?.type);const i=(e=>{if(e.length<2)return null;const t=new Ce(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}})(yo(e,X.contentSize));if(!i){ve._warn("Invalid dec3 box contents, ignoring.");break}const r=_t(i);null!==r&&(t.info.sampleRate=r),t.info.numberOfChannels=Rt(i)}break;case"ddts":{const t=this.currentTrack;if(!t)break;n("audio"===t.info?.type);const i=(e=>{if(e.length<20)return null;const t=f(e),i=t.getUint32(0);if(0===i)return null;const r=new Ce(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=Vt(o):ne.id===i);if(!r)break;const a=Io(e),s=(12&a)>>2,n=3&a,o=[bo,To,So,Io],c=o[(48&a)>>4],l=o[s],u=o[n],d=Io(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 a=0;ae.id===u);if(!d)break;const h=this.fragmentTrackDefaults.find(e=>e.trackId===u);this.currentTrack=d,d.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?d.currentFragmentState.baseDataOffset=Eo(e):l&&(d.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),r&&(d.currentFragmentState.sampleDescriptionIndex=Io(e)),a&&(d.currentFragmentState.defaultSampleDuration=Io(e)),s&&(d.currentFragmentState.defaultSampleSize=Io(e)),o&&(d.currentFragmentState.defaultSampleFlags=Io(e)),c&&(d.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{const t=this.currentTrack;if(!t)break;n(t.currentFragmentState);const i=bo(e);e.skip(3);const r=0===i?Io(e):Eo(e);t.currentFragmentState.startTimestamp=r}break;case"trun":{const t=this.currentTrack;if(!t)break;n(this.currentFragment),n(t.currentFragmentState);const i=bo(e),r=So(e),a=Boolean(1&r),s=Boolean(4&r),o=Boolean(256&r),c=Boolean(512&r),l=Boolean(1024&r),u=Boolean(2048&r),d=Io(e);let h=null;a&&(h=Co(e));let f,m=null;s&&(m=Io(e)),this.currentFragment.trackData.has(t.id)?(f=this.currentFragment.trackData.get(t.id),null!==h&&(f.currentOffset=t.currentFragmentState.baseDataOffset+h)):(f={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,f));for(let p=0;p0&&(a=yo(e,r));const s=Gi(t);s.defaultSampleInfoSize=i,s.sampleSizes=a,s.sampleCount=r}break;case"saio":{const t=this.currentTrack;if(!t||!t.encryptionInfo)break;const i=bo(e);if(1&So(e)){const i=Do(e,4),r=Io(e);if(i!==t.encryptionInfo.scheme||0!==r)break}const r=Io(e);if(0===r)break;r>1&&ve._warn("Multiple saio entries are not supported; using the first offset only.");let a=0===i?Io(e):Number(Eo(e));this.currentFragment&&(a+=this.currentFragment.moofOffset);Gi(t).offset=a}break;case"senc":{const t=this.currentTrack;if(!t||!t.encryptionInfo)break;n(this.currentFragment);const i=this.currentFragment.trackData.get(t.id);if(!i)break;e.skip(1);const r=So(e),a=Boolean(2&r),s=Io(e),o=t.encryptionInfo.defaultPerSampleIvSize;n(null!==o);for(let n=0;n0?r.set(yo(e,o),0):r.set(t.encryptionInfo.defaultConstantIv,0);let s=null;if(a){const t=To(e);s=[];for(let i=0;i0&&((L=this.metadataTags).trackNumber??(L.trackNumber=t)),i&&Number.isInteger(i)&&i>0&&((z=this.metadataTags).tracksTotal??(z.tracksTotal=i))}break;case"trkn":if(a instanceof Uint8Array&&a.length>=6){const e=f(a),t=e.getUint16(2,!1),i=e.getUint16(4,!1);t>0&&((U=this.metadataTags).trackNumber??(U.trackNumber=t)),i>0&&((W=this.metadataTags).tracksTotal??(W.tracksTotal=i))}break;case"disc":case"disk":if(a instanceof Uint8Array&&a.length>=6){const e=f(a),t=e.getUint16(2,!1),i=e.getUint16(4,!1);t>0&&((V=this.metadataTags).discNumber??(V.discNumber=t)),i>0&&((j=this.metadataTags).discsTotal??(j.discsTotal=i))}}}}}return e.filePos=Q,!0}}class zi{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;n(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 W(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,t){const i=this.mapTimestampIntoTimescale(e),r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=Wi(r,i),s=await this.fetchPacketForSampleIndex(a,t);return $i(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=_(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=M(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 n(-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=Vi(i,e);if(!r)return null;let a;if(t.metadataOnly)a=yi;else{let t=this.internalTrack.demuxer.reader.requestSlice(r.sampleOffset,r.sampleSize);if(ce(t)&&(t=await t),!t)return null;if(a=yo(t,r.sampleSize),this.internalTrack.encryptionInfo){let t=null;if(this.internalTrack.encryptionAuxInfo){const i=await Qi(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);ee.timestamp),d=-1!==u?this.internalTrack.fragmentLookupTable[u]:null,h=_(this.internalTrack.fragmentPositionCache,i,e=>e.startTimestamp),f=-1!==h?this.internalTrack.fragmentPositionCache[h]:null,m=Math.max(d?.moofOffset??0,f?.moofOffset??0)||null;let p;for(e?null===m||e.moofOffset>=m?(p=e.moofOffset+e.moofSize,o=e):p=m:p=m??0;;){if(o){const e=o.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>r)break}let e=s.reader.requestSliceRange(p,8,16);if(ce(e)&&(e=await e),!e)break;const i=p,n=Si(e);if(!n)break;if("moof"===n.name){o=await s.readFragment(i);const{sampleIndex:e,correctSampleFound:r}=t(o);if(r)return this.fetchPacketInFragment(o,e,a);-1!==e&&(c=o,l=e)}p=i+n.totalSize}if(d&&(!c||c.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&&yt(e.data)}}else{const e=await this.getFirstPacket({}),t=e&&kt(e.data);t&&(this.internalTrack.info.av1CodecInfo=t)}else{const e=await this.getFirstPacket({}),t=e&&pt(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&&rt(e.data)}else{const e=await this.getFirstPacket({});this.internalTrack.info.avcCodecInfo=e&&Xe(e.data)}if(!S(this.internalTrack.info.colorSpace)){const a=ti(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:ei(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 qi extends zi{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&&qt(e.data)}return{codec:ii(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}})()):null}}const Wi=(e,t)=>{if(e.presentationTimestamps){const i=_(e.presentationTimestamps,t,e=>e.presentationTimestamp);return-1===i?-1:e.presentationTimestamps[i].sampleIndex}{const i=_(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)}},Hi=(e,t)=>{if(!e.keySampleIndices)return Wi(e,t);if(e.presentationTimestamps){const i=_(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 i=Wi(e,t),r=_(e.keySampleIndices,i,e=>e);return e.keySampleIndices[r]??-1}},Vi=(e,t)=>{const i=_(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=_(e.sampleCompositionTimeOffsets,t,e=>e.startIndex),o=e.sampleCompositionTimeOffsets[s];o&&t-o.startIndexe.startSampleIndex),u=e.sampleToChunk[l];n(u);const d=u.startChunkIndex+Math.floor((t-u.startSampleIndex)/u.samplesPerChunk),h=e.chunkOffsets[d],f=u.startSampleIndex+(d-u.startChunkIndex)*u.samplesPerChunk;let m=0,p=h;if(1===e.sampleSizes.length)p+=c*(t-f),m+=c*u.samplesPerChunk;else for(let n=f;ne)}},ji=(e,t)=>{if(!e.keySampleIndices)return t+1;const i=_(e.keySampleIndices,t,e=>e);return e.keySampleIndices[i+1]??-1},Ki=(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},Xi=e=>{const[t,i]=e,r=Math.atan2(i,t);return Number.isFinite(r)?r*(180/Math.PI):0},$i=e=>0===e.sampleSizes.length,Gi=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})},Qi=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{n(i.sampleSizes);for(let e=0;e0?i.defaultSampleInfoSize:i.sampleSizes[n],r=new Uint8Array(16);s>0?r.set(yo(a,s),0):r.set(t.defaultConstantIv,0);let c=null;if(e>s){const e=To(a);c=[];for(let t=0;te.defaultConstantIv?{iv:e.defaultConstantIv,subsamples:null}:null,Ji=async(e,t,i,r)=>{n(e.encryptionInfo);const a=e.encryptionInfo;n(null!==a.defaultKid);const s=a.defaultKid;let o;const c=e.demuxer.decryptionKeyCache.get(s);if(c)o=await c;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{n(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"]),o=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 o(r);n(null!==t.defaultCryptByteBlock&&null!==t.defaultSkipByteBlock);const c=tr(i.subsamples,t.defaultCryptByteBlock,t.defaultSkipByteBlock);let l=0;for(const n of c)for(const e of n.perSubsample)l+=e.length;const u=new Uint8Array(l);let d=0;for(const n of c)for(const e of n.perSubsample)u.set(r.subarray(e.offset,e.offset+e.length),d),d+=e.length;const h=await o(u),f=new Uint8Array(r);let m=0;for(const n of c)for(const e of n.perSubsample)f.set(h.subarray(m,m+e.length),e.offset),m+=e.length;return f},er=(e,t,i,r)=>{const a=new Oi;a.init({key:e,iv:i.iv});const s=t.defaultCryptByteBlock,o=t.defaultSkipByteBlock;if(n(null!==s&&null!==o),!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 ir,rr;(rr=ir||(ir={}))[rr.EBML=440786851]="EBML",rr[rr.EBMLVersion=17030]="EBMLVersion",rr[rr.EBMLReadVersion=17143]="EBMLReadVersion",rr[rr.EBMLMaxIDLength=17138]="EBMLMaxIDLength",rr[rr.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",rr[rr.DocType=17026]="DocType",rr[rr.DocTypeVersion=17031]="DocTypeVersion",rr[rr.DocTypeReadVersion=17029]="DocTypeReadVersion",rr[rr.Void=236]="Void",rr[rr.Segment=408125543]="Segment",rr[rr.SeekHead=290298740]="SeekHead",rr[rr.Seek=19899]="Seek",rr[rr.SeekID=21419]="SeekID",rr[rr.SeekPosition=21420]="SeekPosition",rr[rr.Duration=17545]="Duration",rr[rr.Info=357149030]="Info",rr[rr.TimestampScale=2807729]="TimestampScale",rr[rr.MuxingApp=19840]="MuxingApp",rr[rr.WritingApp=22337]="WritingApp",rr[rr.Tracks=374648427]="Tracks",rr[rr.TrackEntry=174]="TrackEntry",rr[rr.TrackNumber=215]="TrackNumber",rr[rr.TrackUID=29637]="TrackUID",rr[rr.TrackType=131]="TrackType",rr[rr.FlagEnabled=185]="FlagEnabled",rr[rr.FlagDefault=136]="FlagDefault",rr[rr.FlagForced=21930]="FlagForced",rr[rr.FlagOriginal=21934]="FlagOriginal",rr[rr.FlagHearingImpaired=21931]="FlagHearingImpaired",rr[rr.FlagVisualImpaired=21932]="FlagVisualImpaired",rr[rr.FlagCommentary=21935]="FlagCommentary",rr[rr.FlagLacing=156]="FlagLacing",rr[rr.Name=21358]="Name",rr[rr.Language=2274716]="Language",rr[rr.LanguageBCP47=2274717]="LanguageBCP47",rr[rr.CodecID=134]="CodecID",rr[rr.CodecPrivate=25506]="CodecPrivate",rr[rr.CodecDelay=22186]="CodecDelay",rr[rr.SeekPreRoll=22203]="SeekPreRoll",rr[rr.DefaultDuration=2352003]="DefaultDuration",rr[rr.Video=224]="Video",rr[rr.PixelWidth=176]="PixelWidth",rr[rr.PixelHeight=186]="PixelHeight",rr[rr.DisplayWidth=21680]="DisplayWidth",rr[rr.DisplayHeight=21690]="DisplayHeight",rr[rr.DisplayUnit=21682]="DisplayUnit",rr[rr.AlphaMode=21440]="AlphaMode",rr[rr.Audio=225]="Audio",rr[rr.SamplingFrequency=181]="SamplingFrequency",rr[rr.Channels=159]="Channels",rr[rr.BitDepth=25188]="BitDepth",rr[rr.SimpleBlock=163]="SimpleBlock",rr[rr.BlockGroup=160]="BlockGroup",rr[rr.Block=161]="Block",rr[rr.BlockAdditions=30113]="BlockAdditions",rr[rr.BlockMore=166]="BlockMore",rr[rr.BlockAdditional=165]="BlockAdditional",rr[rr.BlockAddID=238]="BlockAddID",rr[rr.BlockDuration=155]="BlockDuration",rr[rr.ReferenceBlock=251]="ReferenceBlock",rr[rr.Cluster=524531317]="Cluster",rr[rr.Timestamp=231]="Timestamp",rr[rr.Cues=475249515]="Cues",rr[rr.CuePoint=187]="CuePoint",rr[rr.CueTime=179]="CueTime",rr[rr.CueTrackPositions=183]="CueTrackPositions",rr[rr.CueTrack=247]="CueTrack",rr[rr.CueClusterPosition=241]="CueClusterPosition",rr[rr.Colour=21936]="Colour",rr[rr.MatrixCoefficients=21937]="MatrixCoefficients",rr[rr.TransferCharacteristics=21946]="TransferCharacteristics",rr[rr.Primaries=21947]="Primaries",rr[rr.Range=21945]="Range",rr[rr.Projection=30320]="Projection",rr[rr.ProjectionType=30321]="ProjectionType",rr[rr.ProjectionPoseRoll=30325]="ProjectionPoseRoll",rr[rr.Attachments=423732329]="Attachments",rr[rr.AttachedFile=24999]="AttachedFile",rr[rr.FileDescription=18046]="FileDescription",rr[rr.FileName=18030]="FileName",rr[rr.FileMediaType=18016]="FileMediaType",rr[rr.FileData=18012]="FileData",rr[rr.FileUID=18094]="FileUID",rr[rr.Chapters=272869232]="Chapters",rr[rr.Tags=307544935]="Tags",rr[rr.Tag=29555]="Tag",rr[rr.Targets=25536]="Targets",rr[rr.TargetTypeValue=26826]="TargetTypeValue",rr[rr.TargetType=25546]="TargetType",rr[rr.TagTrackUID=25541]="TagTrackUID",rr[rr.TagEditionUID=25545]="TagEditionUID",rr[rr.TagChapterUID=25540]="TagChapterUID",rr[rr.TagAttachmentUID=25542]="TagAttachmentUID",rr[rr.SimpleTag=26568]="SimpleTag",rr[rr.TagName=17827]="TagName",rr[rr.TagLanguage=17530]="TagLanguage",rr[rr.TagString=17543]="TagString",rr[rr.TagBinary=17541]="TagBinary",rr[rr.ContentEncodings=28032]="ContentEncodings",rr[rr.ContentEncoding=25152]="ContentEncoding",rr[rr.ContentEncodingOrder=20529]="ContentEncodingOrder",rr[rr.ContentEncodingScope=20530]="ContentEncodingScope",rr[rr.ContentCompression=20532]="ContentCompression",rr[rr.ContentCompAlgo=16980]="ContentCompAlgo",rr[rr.ContentCompSettings=16981]="ContentCompSettings",rr[rr.ContentEncryption=20533]="ContentEncryption";const ar=[ir.EBML,ir.Segment],sr=[ir.SeekHead,ir.Info,ir.Cluster,ir.Tracks,ir.Cues,ir.Attachments,ir.Chapters,ir.Tags],nr=[...ar,...sr],or=16,cr=e=>{if(e.remainingLength<1)return null;const t=bo(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=bo(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=cr(e);if(null===t)return null;if(e.remainingLength{if(e.remainingLength<1)return null;if(255===bo(e))return;e.skip(-1);const t=lr(e);return null===t?null:72057594037927940!==t?t:void 0},fr=e=>{n(e.remainingLength>=2);const t=dr(e);if(null===t)return null;const i=hr(e);return null===i?null:{id:t,size:i}},mr=(e,t)=>{const i=yo(e,t);let r=0;for(;r{const i=yo(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?Fo(e):Ao(e)},kr=async(e,t,i,r)=>{const a=new Set(i);let s=t;for(;null===r||ss?r:s,found:!1}},yr=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,or);if(ce(t)&&(t=await t),!t)break;const i=fr(t);if(!i)break;const r=i.id;let a=i.size;const s=t.filePos;if(r===ir.EBML){Ar(a);let e=this.reader.requestSlice(s,a);if(ce(e)&&(e=await e),!e)break;this.readContiguousElements(e)}else if(r===ir.Segment){if(await this.readSegment(s,a),void 0===a)break;if(null===this.reader.fileSize)break}else if(r===ir.Cluster){if(null===this.reader.fileSize)break;if(void 0===a){a=(await kr(this.reader,s,nr,this.reader.fileSize)).pos-s}const e=c(this.segments);e&&(e.elementEndPos=s+a)}Ar(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=Ur[o].flag;this.currentSegment[e]=!0,Ar(s);let t=this.reader.requestSlice(n,s);ce(t)&&(t=await t),t&&this.readContiguousElements(t)}else if(a===ir.Tags||a===ir.Attachments){a===ir.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,Ar(s);let e=this.reader.requestSlice(n,s);ce(e)&&(e=await e),e&&this.readContiguousElements(e)}else if(a===ir.Cluster){this.currentSegment.clusterSeekStartPos=t;break}if(void 0===s)break;i=n+s}if(this.currentSegment.seekEntries.sort((e,t)=>e.segmentPosition-t.segmentPosition),null!==this.reader.fileSize)for(const n of this.currentSegment.seekEntries){const t=Ur.find(e=>e.id===n.id);if(!t)continue;if(this.currentSegment[t.flag])continue;let i=this.reader.requestSliceRange(e+n.segmentPosition,2,or);if(ce(i)&&(i=await i),!i)continue;const r=fr(i);if(!r)continue;const{id:a,size:s}=r;if(a!==t.id)continue;Ar(s),this.currentSegment[t.flag]=!0;let o=this.reader.requestSlice(i.filePos,s);ce(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,or);ce(i)&&(i=await i),n(i);const r=e,a=fr(i);n(a);n(a.id===ir.Cluster);let s=a.size;const o=i.filePos;if(void 0===s){s=(await kr(this.reader,o,nr,t.elementEndPos)).pos-o}let l=this.reader.requestSlice(o,s);ce(l)&&(l=await l);const u={segment:t,elementStartPos:r,elementEndPos:o+s,dataStartPos:o,timestamp:-1,trackData:new Map};if(this.currentCluster=u,l){const e=this.readContiguousElements(l,nr);u.elementEndPos=e}for(const[,d]of u.trackData){const e=d.track;n(d.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=d.blocks[d.presentationTimestamps[0].blockIndex],a=d.blocks[c(d.presentationTimestamps).blockIndex];d.startTimestamp=i.timestamp,d.endTimestamp=a.timestamp+a.duration;const s=_(e.clusterPositionCache,d.startTimestamp,e=>e.startTimestamp);-1!==s&&e.clusterPositionCache[s].elementStartPos===r||e.clusterPositionCache.splice(s+1,0,{elementStartPos:u.elementStartPos,startTimestamp:d.startTimestamp})}return t.lastReadCluster=u,u}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=fr(e);if(!i)return!1;if(t&&t.includes(i.id))return!1;const{id:r,size:a}=i,s=e.filePos;switch(Ar(a),r){case ir.DocType:this.isWebM="webm"===mr(e,a);break;case ir.Seek:{if(!this.currentSegment)break;const t={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(t),this.readContiguousElements(e.slice(s,a)),-1!==t.id&&-1!==t.segmentPosition||this.currentSegment.seekEntries.pop()}break;case ir.SeekID:{const t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.id=ur(e,a)}break;case ir.SeekPosition:{const t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.segmentPosition=ur(e,a)}break;case ir.TimestampScale:if(!this.currentSegment)break;this.currentSegment.timestampScale=ur(e,a),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale;break;case ir.Duration:if(!this.currentSegment)break;this.currentSegment.duration=gr(e,a);break;case ir.TrackEntry:if(!this.currentSegment)break;if(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...xe,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!==Nr.Block||e.data.algorithm!==Lr.HeaderStripping)&&(ve._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===br)this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(this.currentTrack.codecId===wr)this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(t===Tr)this.currentTrack.info.codec="vp8";else if(t===Sr)this.currentTrack.info.codec="vp9";else if(t===vr)this.currentTrack.info.codec="av1";else if(t===Pr){const e=this.currentTrack.codecPrivate?m.decode(this.currentTrack.codecPrivate):"";Jt.includes(e)&&(this.currentTrack.info.codec="prores",this.currentTrack.info.proresFormat=e)}const e=this.currentTrack;this.currentTrack.trackBacking=new Vr(e),this.currentSegment.tracks.push(this.currentTrack)}else if("audio"===this.currentTrack.info.type){t===Ir?(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===xr?this.currentTrack.info.codec="mp3":t===Cr?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=ri):t===Br?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Er?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===_r?(this.currentTrack.info.codec="ac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Rr?(this.currentTrack.info.codec="eac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Fr?(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 jr(e),this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null;break;case ir.TrackNumber:if(!this.currentTrack)break;this.currentTrack.id=ur(e,a);break;case ir.TrackType:{if(!this.currentTrack)break;const t=ur(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:{...v},alphaMode:!1,proresFormat:null}:2===t&&(this.currentTrack.info={type:"audio",numberOfChannels:1,sampleRate:8e3,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null,dtsFormat:null})}break;case ir.FlagEnabled:if(!this.currentTrack)break;ur(e,a)||(this.currentTrack=null);break;case ir.FlagDefault:if(!this.currentTrack)break;this.currentTrack.disposition.default=!!ur(e,a);break;case ir.FlagForced:if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!ur(e,a);break;case ir.FlagOriginal:if(!this.currentTrack)break;this.currentTrack.disposition.original=!!ur(e,a);break;case ir.FlagHearingImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!ur(e,a);break;case ir.FlagVisualImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!ur(e,a);break;case ir.FlagCommentary:if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!ur(e,a);break;case ir.CodecID:if(!this.currentTrack)break;this.currentTrack.codecId=mr(e,a);break;case ir.CodecPrivate:if(!this.currentTrack)break;this.currentTrack.codecPrivate=yo(e,a);break;case ir.DefaultDuration:if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=ur(e,a);break;case ir.Name:if(!this.currentTrack)break;this.currentTrack.name=pr(e,a);break;case ir.Language:if(!this.currentTrack)break;if(this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=mr(e,a),$(this.currentTrack.languageCode)||(this.currentTrack.languageCode=q);break;case ir.LanguageBCP47:{if(!this.currentTrack)break;const t=mr(e,a).split("-")[0];this.currentTrack.languageCode=t||q,this.currentTrack.hasLanguageBcp47=!0}break;case ir.Video:if("video"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(s,a));break;case ir.PixelWidth:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.width=ur(e,a);break;case ir.PixelHeight:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.height=ur(e,a);break;case ir.DisplayWidth:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.displayWidth=ur(e,a);break;case ir.DisplayHeight:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.displayHeight=ur(e,a);break;case ir.DisplayUnit:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.displayUnit=ur(e,a);break;case ir.AlphaMode:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.alphaMode=1===ur(e,a);break;case ir.Colour:if("video"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(s,a));break;case ir.MatrixCoefficients:{if("video"!==this.currentTrack?.info?.type)break;const t=ur(e,a),i=T[t];this.currentTrack.info.colorSpace.matrix=i}break;case ir.Range:{if("video"!==this.currentTrack?.info?.type)break;const t=ur(e,a);this.currentTrack.info.colorSpace.fullRange=1===t||2===t?2===t:void 0}break;case ir.TransferCharacteristics:{if("video"!==this.currentTrack?.info?.type)break;const t=ur(e,a),i=b[t];this.currentTrack.info.colorSpace.transfer=i}break;case ir.Primaries:{if("video"!==this.currentTrack?.info?.type)break;const t=ur(e,a),i=k[t];this.currentTrack.info.colorSpace.primaries=i}break;case ir.Projection:if("video"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(s,a));break;case ir.ProjectionPoseRoll:{if("video"!==this.currentTrack?.info?.type)break;const t=-gr(e,a);try{this.currentTrack.info.rotation=o(t)}catch{}}break;case ir.Audio:if("audio"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(s,a));break;case ir.SamplingFrequency:if("audio"!==this.currentTrack?.info?.type)break;this.currentTrack.info.sampleRate=gr(e,a);break;case ir.Channels:if("audio"!==this.currentTrack?.info?.type)break;this.currentTrack.info.numberOfChannels=ur(e,a);break;case ir.BitDepth:if("audio"!==this.currentTrack?.info?.type)break;this.currentTrack.info.bitDepth=ur(e,a);break;case ir.CuePoint:if(!this.currentSegment)break;this.readContiguousElements(e.slice(s,a)),this.currentCueTime=null;break;case ir.CueTime:this.currentCueTime=ur(e,a);break;case ir.CueTrackPositions:{if(null===this.currentCueTime)break;n(this.currentSegment);const t={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(t),this.readContiguousElements(e.slice(s,a)),-1!==t.trackId&&-1!==t.clusterPosition||this.currentSegment.cuePoints.pop()}break;case ir.CueTrack:{const t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;t.trackId=ur(e,a)}break;case ir.CueClusterPosition:{const t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;n(this.currentSegment),t.clusterPosition=this.currentSegment.dataStartPos+ur(e,a)}break;case ir.Timestamp:if(!this.currentCluster)break;this.currentCluster.timestamp=ur(e,a);break;case ir.SimpleBlock:{if(!this.currentCluster)break;const t=lr(e);if(null===t)break;const i=this.getTrackDataInCluster(this.currentCluster,t);if(!i)break;const r=vo(e),n=bo(e),o=n>>1&3;let c=!!(128&n);"audio"===i.track.info?.type&&i.track.info.codec&&(c=!0);const l=yo(e,a-(e.filePos-s)),u=i.track.decodingInstructions.length>0;i.blocks.push({timestamp:r,duration:0,isKeyFrame:c,data:l,lacing:o,decoded:!u,postProcessed:!1,mainAdditional:null})}break;case ir.BlockGroup:if(!this.currentCluster)break;this.readContiguousElements(e.slice(s,a)),this.currentBlock=null;break;case ir.Block:{if(!this.currentCluster)break;const t=lr(e);if(null===t)break;const i=this.getTrackDataInCluster(this.currentCluster,t);if(!i)break;const r=vo(e),n=bo(e)>>1&3,o=yo(e,a-(e.filePos-s)),c=i.track.decodingInstructions.length>0;this.currentBlock={timestamp:r,duration:0,isKeyFrame:!0,data:o,lacing:n,decoded:!c,postProcessed:!1,mainAdditional:null},i.blocks.push(this.currentBlock)}break;case ir.BlockAdditions:this.readContiguousElements(e.slice(s,a));break;case ir.BlockMore:if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(s,a)),this.currentBlockAdditional.data&&1===this.currentBlockAdditional.addId&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null;break;case ir.BlockAdditional:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=yo(e,a);break;case ir.BlockAddID:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=ur(e,a);break;case ir.BlockDuration:if(!this.currentBlock)break;this.currentBlock.duration=ur(e,a);break;case ir.ReferenceBlock:if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1;break;case ir.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(s,a));break;case ir.Targets:this.readContiguousElements(e.slice(s,a));break;case ir.TargetTypeValue:50!==ur(e,a)&&(this.currentTagTargetIsMovie=!1);break;case ir.TagTrackUID:case ir.TagEditionUID:case ir.TagChapterUID:case ir.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case ir.SimpleTag:if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(s,a));break;case ir.TagName:this.currentSimpleTagName=pr(e,a);break;case ir.TagString:{if(!this.currentSimpleTagName)break;const t=pr(e,a);this.processTagValue(this.currentSimpleTagName,t)}break;case ir.TagBinary:{if(!this.currentSimpleTagName)break;const t=yo(e,a);this.processTagValue(this.currentSimpleTagName,t)}break;case ir.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(s,a));const t=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(t.raw??(t.raw={}),t.raw[this.currentAttachedFile.fileUid.toString()]=new Ie(this.currentAttachedFile.fileData,this.currentAttachedFile.fileMediaType??void 0,this.currentAttachedFile.fileName??void 0,this.currentAttachedFile.fileDescription??void 0)),this.currentAttachedFile.fileMediaType?.startsWith("image/")&&this.currentAttachedFile.fileData){const e=this.currentAttachedFile.fileName;let i="unknown";if(e){const t=e.toLowerCase();t.startsWith("cover.")?i="coverFront":t.startsWith("back.")&&(i="coverBack")}t.images??(t.images=[]),t.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:i,name:this.currentAttachedFile.fileName??void 0,description:this.currentAttachedFile.fileDescription??void 0})}this.currentAttachedFile=null}break;case ir.FileUID:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=((e,t)=>{if(t<1)throw new Error("Bad unsigned int size "+t);let i=0n;for(let r=0;rt.order-e.order);break;case ir.ContentEncoding:this.currentDecodingInstruction={order:0,scope:Nr.Block,data:null},this.readContiguousElements(e.slice(s,a)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case ir.ContentEncodingOrder:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=ur(e,a);break;case ir.ContentEncodingScope:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=ur(e,a);break;case ir.ContentCompression:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:Lr.Zlib,settings:null},this.readContiguousElements(e.slice(s,a));break;case ir.ContentCompAlgo:if("decompress"!==this.currentDecodingInstruction?.data?.type)break;this.currentDecodingInstruction.data.algorithm=ur(e,a);break;case ir.ContentCompSettings:if("decompress"!==this.currentDecodingInstruction?.data?.type)break;this.currentDecodingInstruction.data.settings=yo(e,a);break;case ir.ContentEncryption:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}return e.filePos=s+a,!0}decodeBlockData(e,t){n(e.decodingInstructions.length>0);let i=t;for(const r of e.decodingInstructions)if(n(r.data),"decompress"===r.data.type)if(r.data.algorithm===Lr.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){n(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 Hr{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 W(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=_(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=M(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 n(-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(n(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);f(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?yi:r.data,s=r.timestamp/this.internalTrack.segment.timestampFactor,o=r.duration/this.internalTrack.segment.timestampFactor,c={};r.mainAdditional&&"video"===this.internalTrack.info?.type&&this.internalTrack.info.alphaMode&&(c.alpha=i.metadataOnly?yi:r.mainAdditional,c.alphaByteLength=r.mainAdditional.byteLength);const l=new bi(a,r.isKeyFrame?"key":"delta",s,o,e.dataStartPos+t,r.data.byteLength,c);return this.packetToClusterLocation.set(l,{cluster:e,blockIndex:t}),l}async performClusterLookup(e,t,i,r,a){const{demuxer:s,segment:o}=this.internalTrack;let c=null,l=null,u=-1;if(e){const{blockIndex:i,correctBlockFound:r}=t(e);if(r)return this.fetchPacketInCluster(e,i,a);-1!==i&&(l=e,u=i)}const d=_(this.internalTrack.cuePoints,i,e=>e.time),h=-1!==d?this.internalTrack.cuePoints[d]:null,f=_(this.internalTrack.clusterPositionCache,i,e=>e.startTimestamp),m=-1!==f?this.internalTrack.clusterPositionCache[f]:null,p=Math.max(h?.clusterPosition??0,m?.elementStartPos??0)||null;let g;for(e?null===p||e.elementStartPos>=p?(g=e.elementEndPos,c=e):g=p:g=p??o.clusterSeekStartPos;null===o.elementEndPos||g<=o.elementEndPos-2;){if(c){const e=c.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>r)break}let e=s.reader.requestSliceRange(g,2,or);if(ce(e)&&(e=await e),!e)break;const i=g,d=fr(e);if(!d||!sr.includes(d.id)&&d.id!==ir.Void){const e=await yr(s.reader,i,sr,Math.min(o.elementEndPos??1/0,i+qr));if(e){g=e;continue}break}const h=d.id;let f=d.size;const m=e.filePos;if(h===ir.Cluster){c=await s.readCluster(i,o),f=c.elementEndPos-m;const{blockIndex:e,correctBlockFound:r}=t(c);if(r)return this.fetchPacketInCluster(c,e,a);-1!==e&&(l=c,u=e)}if(void 0===f){n(h!==ir.Cluster);f=(await kr(s.reader,m,nr,o.elementEndPos)).pos-m}const p=m+f;if(null===o.elementEndPos){let e=s.reader.requestSliceRange(p,2,or);if(ce(e)&&(e=await e),!e)break;if(dr(e)===ir.Segment){o.elementEndPos=p;break}}g=p}if(h&&(!l||l.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?Xe(a.data):null,hevcCodecInfo:"hevc"===this.internalTrack.info.codec&&a?rt(a.data):null,vp9CodecInfo:"vp9"===this.internalTrack.info.codec&&a?pt(a.data):null,av1CodecInfo:"av1"===this.internalTrack.info.codec&&a?kt(a.data):null,proresCodecInfo:"prores"===this.internalTrack.info.codec&&a?yt(a.data):null,proresFormat:this.internalTrack.info.proresFormat};if(!S(this.internalTrack.info.colorSpace)){const a=ti(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:ei(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 jr extends Hr{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&&qt(e.data)}return{codec:ii({codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,aacCodecInfo:this.internalTrack.info.aacCodecInfo,dtsFormat:this.internalTrack.info.dtsFormat}),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}})()):null}}const Kr=async(e,t,i,r=null)=>{let a=t;for(;null===i||a=4;){const t=s.filePos,i=Io(s),n=null!==e.fileSize?e.fileSize-a:null,o=hi(i,n);if(o.header&&(!r||o.header.sampleRate===r.sampleRate&&o.header.mpegVersionId===r.mpegVersionId&&o.header.layer===r.layer&&gi(o.header.channel)===gi(r.channel)))return{header:o.header,startPos:a};s.filePos=t+o.bytesAdvanced,a=s.filePos}}return null};class Xr extends ki{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 I,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 $r(this)]})())}async advanceReader(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,qo);if(ce(e)&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const t=jo(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}const e=await Kr(this.reader,this.lastLoadedPos,this.reader.fileSize,this.firstFrameHeader);if(!e)return void(this.lastSampleLoaded=!0);const t=e.header;this.lastLoadedPos=e.startPos+t.totalSize-1;const i=di(t.mpegVersionId,t.channel);let r=this.reader.requestSlice(e.startPos+i,4);if(ce(r)&&(r=await r),r){const a=Io(r);if(a===li||a===ui){if(this.xingFrameHeader||(this.xingFrameHeader=t,this.xingFrameHeaderPos=e.startPos),!this.xingData){let t=this.reader.requestSlice(e.startPos+i+4,12);if(ce(t)&&(t=await t),t){const e=yo(t,12),i=f(e),r=i.getUint32(0,!1);this.xingData={frameCount:r&mi.FrameCount?i.getUint32(4,!1):null,fileSize:r&mi.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,qo);if(ce(i)&&(i=await i),!i)break;const r=jo(i);if(!r)break;t=!0;let a=this.reader.requestSlice(i.filePos,r.size);if(ce(a)&&(a=await a),!a)break;Ko(a,r,this.metadataTags),e=i.filePos+r.size}if(!t&&null!==this.reader.fileSize&&this.reader.fileSize>=Uo){let e=this.reader.requestSlice(this.reader.fileSize-Uo,Uo);ce(e)&&(e=await e),n(e);"TAG"===Do(e,3)&&Ho(e,this.metadataTags)}return this.metadataTags}finally{e()}}}class $r{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return n(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(n(null!==e.firstFrameHeader),n(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=_(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 Yr=e=>{const t=f(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},Jr=(e,t,i)=>{let r=0,a=null;if(e.length>0)if("vorbis"===t.codec){n(t.vorbisInfo);const s=(1<<(e=>{let t=0;for(;e;)t++,e>>=1;return t})(t.vorbisInfo.modeBlockflags.length-1))-1<<1,o=(e[0]&s)>>1;if(o>=t.vorbisInfo.modeBlockflags.length)throw new Error("Invalid mode number.");let c=i;const l=t.vorbisInfo.modeBlockflags[o];if(a=t.vorbisInfo.blocksizes[l],1===l){const i=1+(1|s),r=e[0]&i?1:0;c=t.vorbisInfo.blocksizes[r]}r=null!==c?c+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:bt[t]*r}})(e).durationInSamples}return{durationInSamples:r,vorbisBlockSize:a}},Zr=27,ea=282,ta=e=>{const t=e.filePos;if(xo(e)!==Gr)return null;e.skip(1);const i=bo(e),r=Ro(e),a=xo(e),s=xo(e),n=xo(e),o=bo(e),c=new Uint8Array(o);for(let d=0;de+t,0);return{headerStartPos:t,totalSize:l+u,dataStartPos:t+l,dataSize:u,headerType:i,granulePosition:r,serialNumber:a,sequenceNumber:s,checksum:n,lacingValues:c}},ia=(e,t)=>{for(;e.filePos>>8&255)===i||(t>>>16&255)===i||(t>>>24&255)===i){if(e.skip(-4),t===Gr)return!0;e.skip(1)}}return!1};class ra extends ki{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,Zr,ea);if(ce(t)&&(t=await t),!t)break;const i=ta(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 aa(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=f(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:wt(a.data).modeBlockflags},Pt(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=f(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=ri,t.codecInfo.opusInfo={preSkip:a.preSkip},Pt(r.data.subarray(8),this.metadataTags)}async readPacket(e,t){n(te+t.length,0);if(0===c)return null;const l=new Uint8Array(c);let u=0;for(let n=0;n{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 aa{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new I,this.internalSampleRate="opus"===e.codecInfo.codec?ri:e.sampleRate}getType(){return"audio"}getId(){return this.bitstream.serialNumber}getNumber(){const e=this.demuxer.trackBackings.findIndex(e=>e.bitstream===this.bitstream);return n(-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 n(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 q}getDisposition(){return{...xe,primary:!1}}granulePositionToTimestampInSamples(e){return"opus"===this.bitstream.codecInfo.codec?(n(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,i){if(!e)return null;const{durationInSamples:r,vorbisBlockSize:a}=Jr(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),s=new bi(i.metadataOnly?yi: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){n(this.bitstream.lastMetadataPacket);const t=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let i=0;"opus"===this.bitstream.codecInfo.codec&&(n(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=W(e*this.internalSampleRate);if(0===i)return this.getFirstPacket(t);if(i<0)return null;n(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 o=[a];e:for(;a.headerStartPos+a.totalSizei?s=u.headerStartPos:(a=u,o.push(u));continue e}r=u.headerStartPos+u.totalSize}}let c=r.startPage;for(const n of o){if(n.granulePosition===a.granulePosition)break;(!c||n.headerStartPos>c.headerStartPos)&&(c=n)}let l=c;const u=[l];for(;l.serialNumber!==this.bitstream.serialNumber||l.granulePosition!==a.granulePosition;){const e=l.headerStartPos+l.totalSize;let t=this.demuxer.reader.requestSliceRange(e,Zr,ea);ce(t)&&(t=await t),n(t);const i=ta(t);n(i),l=i,l.serialNumber===this.bitstream.serialNumber&&u.push(l)}n(-1!==l.granulePosition);let d,h,f=null,m=l,p=0;if(l.headerStartPos===r.startPage.headerStartPos)d=this.granulePositionToTimestampInSamples(0),h=!0,f=0;else{d=0,h=!1;for(let t=l.lacingValues.length-1;t>=0;t--){if(l.lacingValues[t]<255){f=t+1;break}}if(null===f)throw new Error("Invalid page with granule position: no packets end on this page.");p=f-1;const e={data:yi,endPage:m,endSegmentIndex:p};if(await this.demuxer.findNextPacketStart(e)){const e=na(u,l,f);n(e);const t=sa(u,e.page,e.segmentIndex);t&&(l=t.page,f=t.segmentIndex)}else for(;;){const e=na(u,l,f);if(!e)break;const t=sa(u,e.page,e.segmentIndex);if(!t)break;if(l=t.page,f=t.segmentIndex,e.page.headerStartPos!==m.headerStartPos){m=e.page,p=e.segmentIndex;break}}}let g=null,k=null;for(;null!==l;){n(null!==f);const e=await this.demuxer.readPacket(l,f);if(!e)break;if(!(l.headerStartPos===r.startPage.headerStartPos&&fi||Math.max(a.timestampInSamples,0)===i))break}const a=await this.demuxer.findNextPacketStart(e);if(!a)break;l=a.startPage,f=a.startSegmentIndex}return g}async getPacketSequential(e,t){const i=await this.sequentialScanMutex.acquire();try{const i=W(e*this.internalSampleRate);e=i/this.internalSampleRate;const r=_(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);n(e),this.sequentialScanCache.length>0&&n(c(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 sa=(e,t,i)=>{let r=t,a=i;e:for(;;){for(a--;a>=0;a--){if(r.lacingValues[a]<255){a++;break e}}n(-1===a);if(!(1&r.headerType)){a=0;break}const t=D(e,e=>e.headerStartPos{if(i>0)return{page:t,segmentIndex:i-1};const r=D(e,e=>e.headerStartPos{let e=this.reader.requestSlice(0,12);ce(e)&&(e=await e),n(e);const t=Do(e,4),i="RIFX"!==t,r="RF64"===t,a=Po(e,i);let s=r?this.reader.fileSize:Math.min(a+8,this.reader.fileSize??1/0);if("WAVE"!==Do(e,4))throw new Error("Invalid WAVE file - wrong format");let o=0,c=null,l=e.filePos;for(;null===s||l=18&&357!==a){const e=wo(r,i),s=t-18;if(Math.min(s,e)>=22&&a===oa.EXTENSIBLE){r.skip(6);const e=yo(r,16);a=e[0]|e[1]<<8}}if(a!==oa.MULAW&&a!==oa.ALAW||(c=8),a!==oa.PCM&&a!==oa.IEEE_FLOAT&&a!==oa.ALAW&&a!==oa.MULAW)throw new Error(`Unsupported WAVE codec (format tag ${a}). Only integer/float PCM, A-law, and \u03bc-law are supported.`);if(a===oa.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===oa.IEEE_FLOAT&&![32,64].includes(c))throw new Error(`Unsupported WAVE float bit depth (${c}). Only 32 and 64 bits are supported.`);this.audioInfo={format:a,numberOfChannels:s,sampleRate:n,sampleSizeInBytes:Math.ceil(c/8),blockSizeInBytes:o}}async parseListChunk(e,t,i){var r,a,s,n,o,c,l,u,d,h,f;let m=this.reader.requestSlice(e,t);if(ce(m)&&(m=await m),!m)return;const p=Do(m,4);if("INFO"!==p&&"INF0"!==p)return;let g=m.filePos;for(;g<=e+t-8;){m.filePos=g;const e=Do(m,4),t=Po(m,i),p=yo(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&&((d=this.metadataTags).date??(d.date=new Date(e,0,1)))}break;case"IGNR":case"GENR":(h=this.metadataTags).genre??(h.genre=y);break;case"ICMT":case"CMNT":case"COMM":(f=this.metadataTags).comment??(f.comment=y)}g+=8+t+(1&t)}}async parseId3Chunk(e,t){let i=this.reader.requestSlice(e,t);if(ce(i)&&(i=await i),!i)return;const r=jo(i);if(r){const a=t-qo;if(r.size=Math.min(r.size,a),r.size>0){const t=i.slice(e+qo,r.size);Ko(t,r,this.metadataTags)}}}getCodec(){if(n(this.audioInfo),this.audioInfo.format===oa.MULAW)return"ulaw";if(this.audioInfo.format===oa.ALAW)return"alaw";if(this.audioInfo.format===oa.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===oa.IEEE_FLOAT){if(4===this.audioInfo.sampleSizeInBytes)return"pcm-f32";if(8===this.audioInfo.sampleSizeInBytes)return"pcm-f64"}n(!1)}async getMimeType(){return"audio/wav"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}const ua=2048;class da{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return n(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){const e=this.demuxer.getCodec();return e?(n(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null}getNumberOfChannels(){return n(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return n(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return n(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 n(-1!==this.demuxer.dataSize),this.demuxer.dataSize/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return q}getDisposition(){return{...xe}}async getPacketAtIndex(e,t){n(e>=0),n(this.demuxer.audioInfo);const i=e*ua*this.demuxer.audioInfo.blockSizeInBytes;if(i>=this.demuxer.dataSize)return null;const r=Math.min(ua*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(ce(e)&&(e=await e),!e)return null}let a;if(t.metadataOnly)a=yi;else{let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+i,r);ce(e)&&(e=await e),n(e),a=yo(e,r)}const s=e*ua/this.demuxer.audioInfo.sampleRate,o=r/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(e,this.demuxer.lastKnownPacketIndex),new bi(a,"key",s,o,e,r)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,t){n(this.demuxer.audioInfo);const i=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/ua,(this.demuxer.dataSize-1)/(ua*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;n(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){n(this.demuxer.audioInfo);const i=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/ua);return this.getPacketAtIndex(i+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const ha=e=>{const t=e.filePos,i=yo(e,9),r=new Ce(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}},fa=1024;class ma extends ki{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.trackBackings=[],this.readingMutex=new I,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();n(this.firstFrameHeader),this.trackBackings=[new pa(this)]})())}async advanceReader(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,qo);if(ce(e)&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const t=jo(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}let e=this.reader.requestSliceRange(this.lastLoadedPos,7,9);if(ce(e)&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const t=ha(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=Be[t.samplingFrequencyIndex];n(void 0!==i);const r=fa/i,a={timestamp:this.nextTimestampInSamples/i,duration:r,dataStart:t.startPos,dataSize:t.frameLength};this.loadedSamples.push(a),this.nextTimestampInSamples+=fa,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,qo);if(ce(t)&&(t=await t),!t)break;const i=jo(t);if(!i)break;let r=this.reader.requestSlice(t.filePos,i.size);if(ce(r)&&(r=await r),!r)break;Ko(r,i,this.metadataTags),e=t.filePos+i.size}return this.metadataTags}finally{e()}}}class pa{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return this.getSampleRate()/fa}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 q}getCodec(){return"aac"}getInternalCodecId(){return n(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){n(this.demuxer.firstFrameHeader);const e=Ee[this.demuxer.firstFrameHeader.channelConfiguration];return n(void 0!==e),e}getSampleRate(){n(this.demuxer.firstFrameHeader);const e=Be[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return n(void 0!==e),e}getDisposition(){return{...xe}}async getDecoderConfig(){return n(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=yi;else{let e=this.demuxer.reader.requestSlice(i.dataStart,i.dataSize);if(ce(e)&&(e=await e),!e)return null;r=yo(e,i.dataSize)}return new bi(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=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;)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=_(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,qo);if(ce(e)&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const i=jo(e);if(!i)break;let r=this.reader.requestSlice(e.filePos,i.size);ce(r)&&(r=await r),n(r),Ko(r,i,this.metadataTags),t=e.filePos+i.size}for(t+=4;null===this.reader.fileSize||ts.end-6)return{num:o.num,blockSize:o.blockSize,sampleRate:o.sampleRate,size:s.end-e,isLastFrame:!0};if(255===bo(s)){const t=s.filePos;if(bo(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-o.num!==1){s.filePos=t;continue}}else if(r.num-o.num!==o.blockSize){s.filePos=t;continue}return{num:o.num,blockSize:o.blockSize,sampleRate:o.sampleRate,size:i,isLastFrame:!1}}}}readFlacFrameHeader({slice:e,isFirstPacket:t}){const i=e.filePos,r=yo(e,4),a=new Ce(r);if(32764!==a.readBits(15))return null;if(null===this.blockingBit){n(t);const e=a.readBits(1);this.blockingBit=e}else if(1===this.blockingBit){n(!t);if(1!==a.readBits(1))return null}else{if(0!==this.blockingBit)throw new Error("Invalid blocking bit");n(!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;n(this.audioInfo);const o=((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(!o)return null;a.readBits(4),a.readBits(3);if(0!==a.readBits(1))return null;const c=(e=>{let t=0;const i=new Ce(yo(e,1));for(;1===i.readBits(1);)t++;if(0===t)return i.readBits(7);const r=[],a=t-1,s=new Ce(yo(e,a)),n=8-t-1;for(let o=0;oe|t<"uncommon-u16"===t?To(e)+1:"uncommon-u8"===t?bo(e)+1:"number"===typeof t?t:(N(t),void n(!1)))(e,s),u=((e,t)=>"uncommon-u16"===t?To(e):"uncommon-u16-10"===t?10*To(e):"uncommon-u8"===t?bo(e):"number"===typeof t?t:null)(e,o);if(null===u)return null;if(u!==this.audioInfo.sampleRate)return null;const d=e.filePos-i,h=bo(e);e.skip(-d),e.skip(-1);const f=(e=>{let t=0;for(const i of e){t^=i;for(let e=0;e<8;e++)0!==(128&t)?t=t<<1^7:t<<=1,t&=255}return t})(yo(e,d));return h!==f?null:{num:c,blockSize:l,sampleRate:u}}async advanceReader(){await this.readMetadata(),n(null!==this.lastLoadedPos),n(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 ka{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return n(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return n(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return q}getTimeResolution(){return n(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 n(this.demuxer.audioInfo),0===this.demuxer.audioInfo.totalSamples?null:this.demuxer.audioInfo.totalSamples/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getDisposition(){return{...xe}}async getDecoderConfig(){return n(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(n(this.demuxer.audioInfo),e<0)return null;const i=await this.demuxer.readingMutex.acquire();try{for(;;){const i=_(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=yi;else{let e=this.demuxer.reader.requestSlice(i.byteOffset,i.byteSize);if(ce(e)&&(e=await e),!e)return null;r=yo(e,i.byteSize)}n(this.demuxer.audioInfo);const a=i.blockOffset/this.demuxer.audioInfo.sampleRate,s=i.blockSize/this.demuxer.audioInfo.sampleRate;return new bi(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 ya=9e4,ba=2**33,wa=188,Ta="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.",Sa=new Set([133,134,162]),va=new Set;class Pa extends ki{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);ce(e)&&(e=await e),n(e);const t=yo(e,205);if(71===t[0]&&71===t[188])this.packetOffset=0,this.packetStride=wa;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 o=3,c=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 Ce(t.payload),i=e.readAlignedByte();e.skipBits(8*i);l=2===e.readBits(8)}}if(0!==t.pid||a)if(t.pid!==r&&!l||s){const e=this.elementaryStreams.find(e=>e.pid===t.pid);e:if(e&&!e.initialized){const i=xa(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 Ra(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=Xe(r.suppliedPacket.data),!e.info.avcCodecInfo)continue;const t=e.info.avcCodecInfo.sequenceParameterSets[0];n(t);const i=Ye(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:k[i.colourPrimaries],transfer:b[i.transferCharacteristics],matrix:T[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=rt(r.suppliedPacket.data),!e.info.hevcCodecInfo)continue;const t=e.info.hevcCodecInfo.arrays.find(e=>e.nalUnitType===Oe.SPS_NUT).nalUnits[0];n(t);const i=it(t);e.info.width=i.displayWidth,e.info.height=i.displayHeight,i.pixelAspectRatio.num>i.pixelAspectRatio.den?(e.info.squarePixelWidth=Math.round(e.info.width*i.pixelAspectRatio.num/i.pixelAspectRatio.den),e.info.squarePixelHeight=e.info.height):(e.info.squarePixelWidth=e.info.width,e.info.squarePixelHeight=Math.round(e.info.height*i.pixelAspectRatio.den/i.pixelAspectRatio.num)),e.info.colorSpace={primaries:k[i.colourPrimaries],transfer:b[i.transferCharacteristics],matrix:T[i.matrixCoefficients],fullRange:!!i.fullRangeFlag},e.info.reorderSize=i.maxDecFrameBuffering;break}throw new Error("Unhandled.")}e.info.decoderConfig={codec:ei({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=go.tempFromBytes(r.suppliedPacket.data),i=ha(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=Ee[i.channelConfiguration],e.info.sampleRate=Be[i.samplingFrequencyIndex]}else if("mp3"===e.info.codec){const t=Io(go.tempFromBytes(r.suppliedPacket.data)),i=hi(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=gi(i.header.channel),e.info.sampleRate=i.header.sampleRate}else if("ac3"===e.info.codec){const t=xt(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=It[t.acmod]+t.lfeon,e.info.sampleRate=Ae[t.fscod]}else if("eac3"===e.info.codec){const t=Et(r.suppliedPacket.data);if(!t)throw new Error("Invalid E-AC-3 audio stream; could not read sync frame from first packet.");const i=_t(t);if(null===i)throw new Error("Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.");e.info.numberOfChannels=Rt(t),e.info.sampleRate=i}else{if("dts"!==e.info.codec)throw new Error("Unhandled.");{const t=Ut(r.suppliedPacket.data);if(!t)throw new Error("Invalid DTS audio stream; could not read frame header from first packet.");e.info.numberOfChannels=t.numberOfChannels,e.info.sampleRate=t.sampleRate,t.core&&(e.info.dtsFormat=t.hasExtensions?"dtsh":"dtsc")}}e.info.decoderConfig={codec:ii({codec:e.info.codec,codecDescription:null,aacCodecInfo:e.info.aacCodecInfo,dtsFormat:e.info.dtsFormat}),numberOfChannels:e.info.numberOfChannels,sampleRate:e.info.sampleRate},e.initialized=!0}}}else{const e=new Ce(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),n=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=n;8*(r+o)-e.pos>c;){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&&Sa.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:va.has(t)||(ve._warn(`Note: MPEG-TS streams with stream_type 0x${t.toString(16)} are not currently supported.`),va.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 Ce(t.payload),i=e.readAlignedByte();e.skipBits(8*i),e.skipBits(14);const s=e.readBits(10);for(e.skipBits(40);8*(s+o)-e.pos>c;){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 Ba(n)):this.trackBackingEntries.push(new Ea(n)))})())}async getTrackBackings(){return await this.readMetadata(),this.trackBackingEntries}async getMetadataTags(){return{}}async getMimeType(){await this.readMetadata();return(e=>{let t="video/MP2T";const i=[...new Set(e.filter(Boolean))];return i.length>0&&(t+=`; codecs="${i.join(", ")}"`),t})(await Promise.all(this.trackBackingEntries.map(e=>e.getDecoderConfig().then(e=>e?.codec??null))))}async readSection(e,t,i=!1){let r=e,a=e;const s=[];let n,o=0,c=null,l=!0,u=0;for(;;){const e=await this.readPacket(a);if(a+=this.packetStride,!e)break;if(c){if(e.pid!==c.pid){if(i)break;continue}if(1===e.payloadUnitStartIndicator)break}else{if(0===e.payloadUnitStartIndicator)break;c=e}const n=!!(2&e.adaptationFieldControl),d=!!(1&e.adaptationFieldControl);let h=0;if(n&&(h=1+e.body[0],e===c&&h>1&&(u=e.body[1]>>6&1)),d&&(0===h?(s.push(e.body),o+=e.body.byteLength):(s.push(e.body.subarray(h)),o+=e.body.byteLength-h)),r=a,!t&&o>=64){l=!1;break}if(-1!==E(this.sectionEndPositions,r,e=>e)){l=!1;break}}if(l){const e=_(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(ce(t)&&(t=await t),!t)return null;if(71!==bo(t))throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");const i=To(t);return{payloadUnitStartIndicator:i>>14&1,pid:8191&i,adaptationFieldControl:bo(t)>>4&3}}async readPacket(e){let t=this.reader.requestSlice(e,wa);if(ce(t)&&(t=await t),!t)return null;const i=yo(t,wa);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>=ba-t?-8589934592:ba}}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 Ce(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(Ta);return{sectionStartPos:t.startPos,sectionEndPos:t.endPos,pts:n,randomAccessIndicator:t.randomAccessIndicator}},xa=(e,t,i)=>{n(null!==t.endPos);const r=Ia(e,t,i);if(!r)return null;const a=new Ce(t.payload);a.skipBits(32);const s=a.readBits(16);a.skipBits(16);const o=a.readBits(8),c=a.pos+8*o;a.pos=c;const l=c/8;n(Number.isInteger(l));const u=t.payload.subarray(l,s>0?6+s:t.payload.byteLength);return{...r,data:u}};class Ca{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++,n(r instanceof Ca),r.elementaryStream===this.elementaryStream)break;return i}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.elementaryStream.streamType}getName(){return null}getLanguageCode(){return q}getDisposition(){return{...xe,primary:!1}}getTimeResolution(){return ya}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 bi(i.metadataOnly?yi:e.data,r,e.pts/ya,Math.max(t/ya,0),e.sequenceNumber,e.data.byteLength)}async getFirstPacket(e){const t=this.elementaryStream.firstSection;n(t);const i=xa(this.elementaryStream.demuxer,t,!0);n(i);const r=new Ra(this.elementaryStream,i),a=new Fa(this,r),s=await a.readNext();if(!s)return null;const o=this.createEncodedPacket(s.packet,s.duration,e);return this.packetBuffers.set(o,a),this.packetSectionStarts.set(o,s.packet.sectionStartPos),o}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);n(s);const o=xa(a,s,!0);n(o);const c=new Ra(this.elementaryStream,o);i=new Fa(this,c);const l=e.sequenceNumber;for(;;){const e=await 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}}}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=W(e*ya),a=this.elementaryStream.demuxer,{reader:s,seekChunkSize:o}=a,l=this.elementaryStream.pid,u=async(e,t,i)=>{let r=e;for(;re.pts),g=-1!==p?m[p]:null;if(g&&r-g.pts<45e3)f=g.sectionStartPos;else{let e=0;if(null!==s.fileSize){const t=Math.ceil(s.fileSize/o);if(t>1){let i=0,s=t-1;for(e=i;i<=s;){const t=Math.floor((i+s)/2),n=j(t*o,a.packetStride)+h.sectionStartPos,c=n+o,l=await u(n,c,!1);l?l.pesPacketHeader.pts<=r?(e=t,i=t+1):s=t-1:s=t-1}}}f=j(e*o,a.packetStride)+h.sectionStartPos}const k=await u(f,s.fileSize??1/0,!1);let y=k?.pesPacketHeader??null;y||(y=h);const b=this.getReorderSize(),w=async(e,t)=>{const s=await a.readSection(e,!0);n(s);const o=xa(a,s,!0);n(o);const l=new Ra(this.elementaryStream,o),u=new Fa(this,l);for(;;){if((c(u.presentationOrderPackets)?.pts??-1/0)>=r)break;if(!(await u.readNextPacket()))break}const d=M(u.presentationOrderPackets,t);if(-1===d)return null;const h=u.presentationOrderPackets[d],f=0===d?0:h.pts-u.presentationOrderPackets[d-1].pts;for(;u.decodeOrderPackets[0]!==h;)u.decodeOrderPackets.shift();u.lastDuration=f;const m=await u.readNext();n(m);const p=this.createEncodedPacket(m.packet,m.duration,i);return this.packetBuffers.set(p,u),this.packetSectionStarts.set(p,m.packet.sectionStartPos),p};if(!t||this.allPacketsAreKeyPackets()){e:for(;;){let e=y.sectionStartPos+a.packetStride;for(;;){const t=await a.readPacketHeader(e);if(!t)break e;if(t.pid===l&&1===t.payloadUnitStartIndicator){const t=await a.readSection(e,!1);if(t){const e=Ia(a,t,!1);if(e&&null!==e.pts){if(e.pts>r)break e;y=e,_a(this.elementaryStream,y);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===l&&1===t.payloadUnitStartIndicator){const t=await a.readSection(e,!1);if(t){const e=Ia(a,t,!1);if(e&&null!==e.pts){y=e;break}}}e-=a.packetStride}}return w(y.sectionStartPos,e=>e.pts<=r)}{let e=f,t=null;const i=!this.elementaryStream.canBeTrustedWithKeyPackets;for(;;){let c=null;const f=e<=h.sectionStartPos;let m,p=null;if(f)m=h,p=d;else{const t=await u(e,s.fileSize??1/0,i);m=t?.pesPacketHeader??null,p=t?.section??null}let g=!1,k=0;e:for(;m&&!(null!==t&&m.sectionStartPos>=t);){if(m.pts<=r){let e;if(this.elementaryStream.canBeTrustedWithKeyPackets)e=1===m.randomAccessIndicator;else{n(p);const t=xa(a,p,!0);n(t);const i=new Ra(this.elementaryStream,t);await i.markNextPacket(),e=1===i.suppliedPacket?.randomAccessIndicator}e&&(c=m)}if(m.pts>r&&(g=!0),g&&(k++,k>b))break;let e=m.sectionStartPos+a.packetStride;for(;;){const t=await a.readPacketHeader(e);if(!t)break e;if(t.pid===l&&1===t.payloadUnitStartIndicator){const t=await a.readSection(e,i);if(t){const e=Ia(a,t,!1);if(e&&null!==e.pts){m=e,p=t,_a(this.elementaryStream,m);break}}}e+=a.packetStride}}if(c){let e=c;if(0===k)e:for(let r=0;r=a.packetOffset;){const r=await a.readPacketHeader(t);if(!r)break e;if(r.pid===l&&1===r.payloadUnitStartIndicator){const r=await a.readSection(t,i);if(r){const t=Ia(a,r,!1);if(t&&null!==t.pts){e=t;break}}}t-=a.packetStride}}const t=await w(e.sectionStartPos,e=>e.pts<=r&&1===e.randomAccessIndicator);return n(t),t}if(f)return null;t=e,e=Math.max(j(e-h.sectionStartPos-o,a.packetStride)+h.sectionStartPos,h.sectionStartPos)}}}}class Ba extends Ca{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 n(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}}class Ea extends Ca{getType(){return"audio"}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}async getDecoderConfig(){return n(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 0}}const _a=(e,t)=>{const i=e.referencePesPackets,r=_(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 n(e),e}async bufferData(e){const t=this.endPos+e;for(;this.endPos=u)break;d=e;const i=o+d;if(d+3>=u){this.seekTo(i);break}const h=c[d+1],f=c[d+2],m=c[d+3];let p=0;if(0===h&&0===f&&1===m?p=4:0===h&&1===f&&(p=3),0===p){d++;continue}const g=i;a??(a=g);const k=d+p,y=k+r,b=6;if(y+("avc"===t?b:1)>u){this.seekTo(i);break}const w=c[k];let T,S,v;if("avc"===t)T=We(w),S=T===Me.NON_IDR_SLICE||T===Me.SLICE_DPA||T===Me.IDR,v=T===Me.SEI||T===Me.SPS||T===Me.PPS||T===Me.AUD;else{T=tt(w);if(((1&w)<<5|c[k+1]>>3)>0){d+=p;continue}S=T<=Oe.RASL_R||T>=Oe.BLA_W_LP&&T<=21,v=T>=Oe.VPS_NUT&&T<=37||T===Oe.PREFIX_SEI_NUT||T>=41&&T<=44||T>=48&&T<=55}let P=!1;if(S){let e;if("avc"===t){const t=c.subarray(y,y+b),i=l(new Ce(t));e=!s||i<=n,n=i}else e=c[y]>>7===1;e&&(s?P=!0:s=!0)}else v&&s&&(P=!0);if(P){const e=g-a;return this.seekTo(a),this.supplyPacket(e,0)}d+=p}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);ce(r)&&(r=await r);const a=this.currentPos;for(;this.currentPos-a>6,o=63&a[4];if(3===s||o>37){this.seekTo(t+1);continue}const c=Ct[3*o+s];n(void 0!==c),this.seekTo(t),r=this.ensureBuffered(c),ce(r)&&(r=await r);const l=Math.round(13824e4/e.info.sampleRate);return this.supplyPacket(r,l)}if("eac3"===t){if(11!==i)continue;this.skip(-1);const t=this.currentPos;let r=this.ensureBuffered(5);if(ce(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=Bt[n];this.seekTo(t),r=this.ensureBuffered(s),ce(r)&&(r=await r);const c=256*o,l=Math.round(c*ya/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(ce(r)&&(r=await r),r<18)return;const a=this.readBytes(18),s=Wt(a);let n=s?null:Ht(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);ce(i)&&(i=await i),n=Ht(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(ce(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(n(-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(n(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 Aa="application/vnd.apple.mpegurl",Da="#EXT-X-STREAM-INF:",Ma="#EXT-X-I-FRAME-STREAM-INF:",Na="#EXT-X-MEDIA:",Oa="#EXTINF:",La="#EXT-X-MAP:",za="#EXT-X-KEY:",Ua="#EXT-X-MEDIA-SEQUENCE:",qa="#EXT-X-BYTERANGE:",Wa="#EXT-X-PROGRAM-DATE-TIME:",Ha="#EXT-X-TARGETDURATION:",Va="#EXT-X-PLAYLIST-TYPE:",ja=e=>0===e.length||e.startsWith("#")&&!e.startsWith("#EXT");class Ka{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=pe(e,e=>"video"===e.getType())+1;e.push(new Ga(this,t,i))}else if("audio"===t.type){const i=pe(e,e=>"audio"===e.getType())+1;e.push(new Qa(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=pe(e,e=>"video"===e.getType())+1;e.push(new Ga(this,{id:e.length+1,type:"video"},t))}else if("audio"===r.type){const t=pe(e,e=>"audio"===e.getType())+1;e.push(new Qa(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 $a{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(),n(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){n(e.sequenceNumber>=0),n(this.segmentedInput.firstSegment);const r=await this.segmentedInput.getMediaOffset(t,i.input),a=t.timestamp-this.segmentedInput.firstSegment.timestamp,s=e.clone({timestamp:V(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(),n(this.firstInputTrack),n(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 Ga extends $a{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 Qa extends $a{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())}}he();const Ya=1/0;"undefined"!==typeof FinalizationRegistry&&new FinalizationRegistry(e=>{e()});class Ja extends we{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 mo;return this._sizePromise??(this._sizePromise=(async()=>{let e=this._getFileSize();return void 0!==e||(await this._read(0,1,0,Ya),e=this._getFileSize(),n(void 0!==e)),e})())}async getSize(){if(this._disposed)throw new mo;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 fs(this,e,t)}_dispatchRead(e,t){this.onread?.(e,t),this._emit("read",{start:e,end:t})}ref(){return new Za(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){this._refCount--,0===this._refCount&&(this._dispose(),this._disposed=!0)}}class Za{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;n(e._refCount>0),e._decrementRefCount(),e._refFinalizationRegistry?.unregister(this),this._freed=!0,this._source=null}[Symbol.dispose](){this.freed||this.free()}}class es extends Ja{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 Ja||e instanceof Za))throw new TypeError("requestHandler must return or resolve to a Source or SourceRef.");const i=e instanceof Ja?e.ref():e;return(t=i.source)._usedForHls||(t._usedForHls=this._usedForHls),i};return ce(t)?t.then(i):i(t)}}const ts=(e,t)=>e.path===t.path;class is extends es{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 Ja?e.ref():e;return this._root=t,this._rootRequest=null,t};ce(e)?this._rootRequest=e.then(t):(t(e),n(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 rs="undefined"!==typeof FinalizationRegistry?new FinalizationRegistry(e=>{e.cancel().catch(()=>{})}):null;class as extends Ja{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&&(!fe(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 hs({maxCacheSize:t.maxCacheSize??8388608,maxWorkerCount:4,runWorker:this._runWorker.bind(this),onIdleWorkerRemoved:e=>{const t=this._readers.get(e);t&&(this._readers.delete(e),rs?.unregister(e),t.cancel().catch(()=>{}))},prefetchProfile:ds.fileSystem,handleUnhandledError:t.handleUnhandledError}),this._orchestrator.fileSize=e.size}_getFileSize(){return this._orchestrator.fileSize}_read(e,t,i,r){return this._orchestrator.read(e,t,i,r)}async _runWorker(e){n(e.strictTarget);let t=this._readers.get(e);if(void 0===t){if("stream"in this._blob&&!te()&&!1!==this._options.useStreamReader){t=this._blob.slice(e.currentPos).stream().getReader(),rs?.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 ve._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)},ns=new Set;class os extends es{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&&(!fe(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 os(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??ss,this._requestInit={...t.requestInit};let i=null;if(t.requestInit?.headers){const e={...Y(t.requestInit.headers)},r=Object.keys(e).find(e=>"range"===e.toLowerCase());void 0!==r&&(i=e[r],delete e[r],this._requestInit.headers=e)}if(e instanceof Request){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=ls(i);e&&(this._offset=e.offset,this._length=e.length)}this._orchestrator=new hs({maxCacheSize:t.maxCacheSize??67108864,maxWorkerCount:t.parallelism??2,runWorker:this._runWorker.bind(this),prefetchProfile:ds.network,handleUnhandledError:t.handleUnhandledError})}_getFileSize(){if(!this._fileSizeDetermined)return null!==this._length?this._length:void 0;const e=this._sequentialBacking?this._sequentialBacking._endIndex:this._orchestrator.fileSize;return null===e?null!==this._length?this._length:null:U(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 ce(s)?s.then(n):n(s)}async _runWorker(e){for(;;){const i=new AbortController,r=await J(this._options.fetchFn??fetch,this._url,Q(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")||ns.has(e.origin)||(ve._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.`),ns.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){ve._error("Error while reading response stream. Attempting to resume.",t),await be(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;ve._error("Error while reading response stream. Attempting to resume.",a),await be(1e3*e);const s=await J(this._options.fetchFn??fetch,this._url,Q(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 us(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 o=new Set;for(const n of this._orchestrator.workers){for(const e of n.pendingSlices)o.add(e);n.aborted=!0,n.pendingSlices.length=0}for(const n of this._orchestrator.queuedReads)for(const e of n.pendingSlices)o.add(e);this._orchestrator.workers.length=0,this._orchestrator.queuedReads.length=0;for(const c of o){const e=s._read(c.start,c.start+c.bytes.length);ce(e)?e.then(e=>{e?(n(e.offset===c.start),c.resolve(e.bytes)):c.resolve(null)},e=>c.reject(e)):(n(null===e),c.resolve(null))}}_dispose(){this._orchestrator.dispose(),this._sequentialBacking&&(this._sequentialBacking._disposed=!0,this._sequentialBacking._dispose())}}const cs=/^bytes=(\d+)-(\d*)$/,ls=e=>{const t=cs.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=_(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}=F();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 mo);this._pendingSlices.length=0,this._cache.length=0,this._reader?.cancel()}}const ds={fileSystem:(e,t)=>{const i=65536;return{start:e=Math.floor((e-i)/i)*i,end:t=Math.ceil((t+i)/i)*i}},network:(e,t,i)=>{const r=65536;e=Math.max(0,Math.floor((e-r)/r)*r);for(const a of i){const i=8388608,r=Math.max((a.startPos+a.targetPos)/2,a.targetPos-i);if(ue(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 hs{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){n(!this.disposed);const a=this.options.prefetchProfile(e,t,this.workers),s=Math.max(a.start,i),o=Math.min(a.end,this.fileSize??1/0,r);n(s<=e&&t<=o);let c=null;const l=_(this.cache,e,e=>e.start),u=-1!==l?this.cache[l]:null;u&&u.start<=e&&t<=u.end&&(u.age=this.nextAge++,c={bytes:u.bytes,view:u.view,offset:u.start});const d=_(this.cache,s,e=>e.start),h=c?null:new Uint8Array(t-e);let m=0,p=s;const g=[];if(-1!==d){for(let i=d;i=o)break;if(r.end<=s)continue;const a=Math.max(s,r.start),c=Math.min(o,r.end);if(n(a<=c),p=h.length&&(c={bytes:h,view:f(h),offset:e}),0===g.length)return n(c),c;const{promise:k,resolve:y,reject:b}=F(),w=[];for(const n of g){const i=Math.max(e,n.start),r=Math.min(t,n.end);i===n.start&&r===n.end?w.push(n):ie.hole.start),i=-1!==t?this.queuedReads[t]:null;for(i&&n.start<=i.hole.end?(i.hole.end=Math.max(i.hole.end,n.end),i.strictTarget&&(i.strictTarget=e),T&&i.pendingSlices.push(T)):(t++,i={hole:{start:n.start,end:n.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 c?k.catch(e=>{if(!this.disposed){if(!this.options.handleUnhandledError)throw e;this.options.handleUnhandledError(e)}}):(n(h),c=k.then(t=>t&&{bytes:t,view:f(t),offset:e})),c}checkHoleAgainstWorker(e,t,i){if(ue(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);n(-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=_(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=f(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=f(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 ce(a)?a.then(s):s(a)}_dispose(){this._ref?.free()}ref(){return this._ref??(this._ref=this._baseSource.ref()),super.ref()}}var ms=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},ps=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 gs=/^0[xX][0-9a-fA-F]+$/,ks=/^data:.*;base64,/i;class ys extends Xa{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 be(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=ms(t,await this.demuxer.input._getSourceUncached({path:this.rootPath,isRoot:!1}),!1),r=new po(i.source),a=await r.requestEntireFile();n(a),e=Mo(a,a.length,{ignore:ja}),i.source instanceof es&&(this.rootPath=i.source.rootPath)}catch(T){t.error=T,t.hasError=!0}finally{ps(t)}}const t=!1!==this.input._formatOptions.hls?.offsetTimestampsByDateTime;let i=!1,r=0,a=null,s=null,o=null,l=0,u=null,d=null,h=null,m=null,p=null,g=null,k=!1,y=c(this.segments)??null;const b=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}},w=e=>{l=e,y&&(n(null!==y.sequenceNumber),y.sequenceNumber0&&null!==g&&(r=l*g),k=!0);const e=T.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(T.startsWith(La)){const e=new Ka(T.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 n=null;if(null!==i&&(n=b(i)),n&&null===n.offset)throw new Error("Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset.");if(!y){const e={path:me(this.rootPath,t),offset:n?.offset??0,length:n?.length??null};if("AES-128"===o?.method&&!o.iv)throw new Error("IV attribute must be set on #EXT-X-KEY tag preceding the #EXT-X-MAP tag.");d={timestamp:r,unixEpochTimestamp:a,firstSegment:null,sequenceNumber:null,location:e,duration:0,encryption:o,initSegment:null,lastProgramDateTimeSeconds:p}}s=null,null===m?h=null:m=null}else if(T.startsWith(za)){const e=new Ka(T.slice(11)),t=e.get("method");if("NONE"===t)o=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(!gs.test(r))throw new Error(`Unsupported IV format '${r}'.`);let e=r.slice(2);e=e.padStart(32,"0"),i=new Uint8Array(Bi);for(let t=0;t=8&&112===t[4]&&115===t[5]&&115===t[6]&&104===t[7]){const e=f(t).getUint32(0);r=wi(t.subarray(8,Math.min(e,t.length)))}}o={method:t,psshBox:r}}}}else if(T.startsWith(Ua)){const e=T.slice(22),t=Number(e);if(!Number.isInteger(t)||t<0)throw new Error(`Invalid EXT-X-MEDIA-SEQUENCE value '${e}'.`);w(t)}else if(T.startsWith(qa)){const e=b(T.slice(17));if(null===e.offset){if(null===h)throw new Error("Invalid M3U8 file; #EXT-X-BYTERANGE without offset requires a previous byte range.");e.offset=h}m=e,h=e.offset+e.length}else if(T.startsWith(Wa)){if(y)continue;const e=T.slice(25),i=Date.parse(e);if(!Number.isFinite(i))continue;const s=i/1e3;if(p===s)continue;if(null===p&&this.segments.length>0){const e=c(this.segments),i=s-(e.timestamp+e.duration);for(const r of this.segments)r.unixEpochTimestamp=r.timestamp+i,t&&(r.timestamp=r.unixEpochTimestamp)}p=s,a=s,t&&(r=s)}else if("#EXT-X-DISCONTINUITY"===T)u=null;else if(T.startsWith(Ha)){const e=T.slice(22),t=Number(e);if(!Number.isFinite(t)||t<0)throw new Error(`Invalid EXT-X-TARGETDURATION value '${e}'.`);this.refreshInterval=t,g=t}else{if("#EXT-X-ENDLIST"===T){this.streamHasEnded=!0;break}if(T.startsWith(Va)){"vod"===T.slice(21).toLowerCase()&&(this.streamHasEnded=!0)}}}else{if("#EXTM3U"!==T)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=_(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=>Ti(e,r))||(i=[...i,r]),this.input._formatOptions.isobmff.resolveKeyId({...e,psshBoxes:i})})}},s=new ho({source:new is(t.location.path,async e=>{n(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;n(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 o=((e,t,i)=>{let r=!1,a=0;const s=new Oi;return new ReadableStream({pull:async n=>{r||(s.init(await t()),r=!0);let o=e.requestSliceRange(a,0,65552);if(ce(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=yo(o,l),d=new Uint8Array(l);for(let e=0;e16)throw new Error("Invalid PKCS#7 padding. Incorrect key or corrupted data.");const t=d.subarray(0,l-e);n.enqueue(t),n.close(),i()}},cancel:()=>{i()}})})(new po(s.source),async()=>{const t={stack:[],error:void 0,hasError:!1};try{const i=ms(t,await this.input._getSourceCached({path:e.keyUri,isRoot:!1},uo),!1),r=new po(i.source),a=await r.requestSlice(0,Bi);if(!a)throw new Error("Invalid AES-128 key; expected at least 16 bytes of data.");return{key:yo(a,Bi),iv:e.iv}}catch(i){t.error=i,t.hasError=!0}finally{ps(t)}},()=>{s.free()});r=new us(o).ref()}else n(!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 Ls)),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=ge(this.inputCache,e=>e.age);n(-1!==e),this.inputCache.splice(e,1)}return s}async getLiveRefreshInterval(){return 0===this.getRemainingWaitTimeMs()&&await this.runUpdateSegments(),this.streamHasEnded?null:this.refreshInterval}}class bs extends ki{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()=>{n(this.input._rootSource instanceof es);const e=await this.input._reader.requestEntireFile();n(e);const t=Mo(e,e.length,{ignore:ja}),{rootPath:i}=this.input._rootSource,r=[],a=[];for(let n=1;n"video"===e.attributes.get("type").toLowerCase()).map(e=>e.attributes.get("group-id")))],o=[...new Set(a.filter(e=>"audio"===e.attributes.get("type").toLowerCase()).map(e=>e.attributes.get("group-id")))],c=await Promise.all(r.map(async(e,t)=>{const r=[],c=e.attributes.get("codecs");let l;if(c)l=c.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()})));l=await Promise.all(r.filter(e=>null!==e.codec).map(e=>e.track.getDecoderConfig().then(e=>e.codec)))}const u=e.attributes.get("video"),d=e.attributes.get("audio"),h=l.some(e=>jt.includes(ni(e))),f=l.some(e=>Xt.includes(ni(e)));if(null!==u&&!h){if(!s.includes(u))throw new Error(`Invalid M3U8 file; variant stream references video 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&&"video"===i.toLowerCase()});e:if(e){const t=e.attributes.get("uri");if(null===t)break e;const r=me(i,t),a=this.getSegmentedInputForPath(r),s=(await a.getTrackBackings()).find(e=>"video"===e.getType());if(!s||null===await s.getCodec())break e;const o=await s.getDecoderConfig().then(e=>e?.codec??null);n(null!==o),l.push(o)}}if(null!==d&&!f){if(!o.includes(d))throw new Error(`Invalid M3U8 file; variant stream references audio group "${d}" 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===d&&"audio"===i.toLowerCase()});e:if(e){const t=e.attributes.get("uri");if(null===t)break e;const r=me(i,t),a=this.getSegmentedInputForPath(r),s=(await a.getTrackBackings()).find(e=>"audio"===e.getType());if(!s||null===await s.getCodec())break e;const o=await s.getDecoderConfig().then(e=>e?.codec??null);n(null!==o),l.push(o)}}l=[...new Set(l)];let m=null,p=null;const g=e.attributes.getAsNumber("bandwidth");n(null!==g);const k=e.attributes.getAsNumber("average-bandwidth"),y=e.attributes.get("name");for(const i of l){const n=ni(i);if(null!==n)if(jt.includes(n)){if(null!==m)throw new Error("Unsupported M3U8 file; multiple video codecs found in the CODECS attribute of a variant stream.");m=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:q,lineNumber:e.lineNumber,fullPath:e.fullPath,fullCodecString:m,pairingMask:1n<0?a:null}})}else{if(!o.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:vs(i.attributes),autoselect:vs(i.attributes)||Ps(i.attributes),languageCode:Is(i.attributes.get("language")),lineNumber:i.lineNumber,fullPath:i.fullPath??e.fullPath,fullCodecString:p,pairingMask:1n<0?c:null}})}}}}return r})),l=[],u=e=>{const t=l.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===q&&(t.languageCode=e.languageCode)):(e.id=l.length+1,l.push(e))};for(const n of c)for(const e of n)u(e);l.sort((e,t)=>e.lineNumber-t.lineNumber),this.trackBackings=[];for(const n of l)"video"===n.info.type?this.trackBackings.push(new Ts(n)):this.trackBackings.push(new Ss(n));this.internalTracks=l})())}async getTrackBackings(){return await this.readMetadata(),n(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 ys(this,e,i,null),this.segmentedInputs.push(t),t}async getMetadataTags(){return{}}async getMimeType(){return Aa}dispose(){if(this.segmentedInputs){for(const e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}}class ws{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 Ts){for(const r of i)if(await r.getCodec()===this.getCodec()){t=r;break}}else{n(this instanceof Ss);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{...xe,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(){n(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 Ts extends ws{constructor(e){super(e)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return"video"}getCodec(){return ni(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 Ss extends ws{constructor(e){super(e)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return"audio"}getCodec(){return ni(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 vs=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}".`)},Ps=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}".`)},Is=e=>{if(null===e)return q;const t=e.split("-")[0];return t||q};class xs{constructor(){this._isIsobmff=!1}}class Cs extends xs{constructor(){super(...arguments),this._isIsobmff=!0}async _getMajorBrand(e){let t=e._reader.requestSlice(0,12);if(ce(t)&&(t=await t),!t)return null;t.skip(4);const i=Do(t,4);return"ftyp"!==i&&"styp"!==i?null:Do(t,4)}_createDemuxer(e){return new Li(e)}}class Bs extends Cs{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(ce(t)&&(t=await t),!t)return!1;let r=Io(t),a=8;if(1===r){let t=e._reader.requestSlice(i+8,8);if(ce(t)&&(t=await t),!t)return!1;r=Eo(t),a=16}if(r8)return!1;if(ur(i,r)!==ir.EBML)return!1;const a=hr(i);if("number"!==typeof a)return!1;let s=e._reader.requestSlice(i.filePos,a);if(ce(s)&&(s=await s),!s)return!1;const n=i.filePos;for(;s.filePos<=n+a-2;){const e=fr(s);if(!e)break;const{id:i,size:r}=e,a=s.filePos;if(void 0===r)return!1;switch(i){case ir.EBMLVersion:if(1!==ur(s,r))return!1;break;case ir.EBMLReadVersion:if(1!==ur(s,r))return!1;break;case ir.DocType:if(mr(s,r)!==t)return!1;break;case ir.DocTypeVersion:if(ur(s,r)>4)return!1}s.filePos=a+r}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new Wr(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}}class Rs extends _s{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}}class Fs extends xs{async _canReadInput(e){let t=0;for(;;){let i=e._reader.requestSlice(t,qo);if(ce(i)&&(i=await i),!i)break;const r=jo(i);if(!r)break;t=i.filePos+r.size}const i=await Kr(e._reader,t,t+4096);if(!i)return!1;const r=i.header,a=di(r.mpegVersionId,r.channel);let s=e._reader.requestSlice(i.startPos+a,4);if(ce(s)&&(s=await s),!s)return!1;const n=Io(s);if(n===li||n===ui)return!0;t=i.startPos+i.header.totalSize;const o=await Kr(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 Xr(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}}class As extends xs{async _canReadInput(e){let t=e._reader.requestSlice(0,12);if(ce(t)&&(t=await t),!t)return!1;const i=Do(t,4);if("RIFF"!==i&&"RIFX"!==i&&"RF64"!==i)return!1;t.skip(4);return"WAVE"===Do(t,4)}_createDemuxer(e){return new la(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}}class Ds extends xs{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return ce(t)&&(t=await t),!!t&&"OggS"===Do(t,4)}_createDemuxer(e){return new ra(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}}class Ms extends xs{async _canReadInput(e){let t=0;for(;;){let i=e._reader.requestSlice(t,qo);if(ce(i)&&(i=await i),!i)break;const r=jo(i);if(!r)break;t=i.filePos+r.size}let i=e._reader.requestSlice(t,4);return ce(i)&&(i=await i),!!i&&"fLaC"===Do(i,4)}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new ga(e)}}class Ns extends xs{async _canReadInput(e){let t=0;for(;;){let i=e._reader.requestSlice(t,qo);if(ce(i)&&(i=await i),!i)break;const r=jo(i);if(!r)break;t=i.filePos+r.size}let i=e._reader.requestSliceRange(t,7,9);if(ce(i)&&(i=await i),!i)return!1;const r=ha(i);if(!r)return!1;if(t+=r.frameLength,i=e._reader.requestSliceRange(t,7,9),ce(i)&&(i=await i),!i)return!1;const a=ha(i);return!!a&&(r.objectType===a.objectType&&r.samplingFrequencyIndex===a.samplingFrequencyIndex&&r.channelConfiguration===a.channelConfiguration)}_createDemuxer(e){return new ma(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}}class Os extends xs{async _canReadInput(e){let t=e._reader.requestSlice(0,205);if(ce(t)&&(t=await t),!t)return!1;const i=yo(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 Pa(e)}get name(){return"MPEG Transport Stream"}get mimeType(){return"video/MP2T"}}class Ls extends xs{async _canReadInput(e){let t=e._reader.requestSlice(0,7);if(ce(t)&&(t=await t),!t)return!1;if(!("#EXTM3U"===Do(t,7)))return!1;if(!(e._rootSource instanceof es))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 bs(e)}get name(){return"HTTP Live Streaming (HLS)"}get mimeType(){return Aa}}const zs=new Bs,Us=new Es,qs=new _s,Ws=new Rs,Hs=new Fs,Vs=new As,js=new Ds,Ks=new Ns,Xs=new Ms,$s=new Os,Gs=new Ls,Qs=[Gs,zs,Us,qs,Ws,Vs,js,Xs,Hs,Ks,$s],Ys=[Gs,zs,Us,Hs,Ks,$s];var Js=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});he();let Zs=-1/0,en=-1/0,tn=null;"undefined"!==typeof FinalizationRegistry&&(tn=new FinalizationRegistry(e=>{const t=performance.now();"video"===e.type?(t-Zs>=1e3&&(ve._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."),Zs=t),"undefined"!==typeof VideoFrame&&e.data instanceof VideoFrame&&e.data.close()):(t-en>=1e3&&(ve._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."),en=t),"undefined"!==typeof AudioData&&e.data instanceof AudioData&&e.data.close())}));class rn{constructor(){this._referenceCount=0,this._lastAllocationBuffer=null}}const an=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],sn=new Set(an);class nn{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(G*this.timestamp)}get microsecondDuration(){return Math.trunc(G*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||!sn.has(t.format))throw new TypeError("init.format must be one of: "+an.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&&ye(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??gn(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?h(e):h(e).slice(),this._layout=i,this.colorSpace=new dn(r)}else if("undefined"!==typeof VideoFrame&&e instanceof VideoFrame){if(void 0!==t?.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(void 0!==t?.timestamp&&!Number.isFinite(t?.timestamp))throw new TypeError("init.timestamp, when provided, must be a number.");if(void 0!==t?.duration&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");void 0!==t?.visibleRect&&ye(t.visibleRect,"init.visibleRect"),this._data=e,this._layout=null,this.format=e.format,this.visibleRect={left:e.visibleRect?.x??0,top:e.visibleRect?.y??0,width:e.visibleRect?.width??e.codedWidth,height:e.visibleRect?.height??e.codedHeight},this.rotation=t?.rotation??0,this.squarePixelWidth=e.displayWidth,this.squarePixelHeight=e.displayHeight,this.timestamp=t?.timestamp??e.timestamp/1e6,this.duration=t?.duration??(e.duration??0)/1e6,this.colorSpace=new dn(e.colorSpace)}else if("undefined"!==typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!==typeof SVGImageElement&&e instanceof SVGImageElement||"undefined"!==typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!==typeof HTMLVideoElement&&e instanceof HTMLVideoElement||"undefined"!==typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!==typeof OffscreenCanvas&&e instanceof OffscreenCanvas){if(!t||"object"!==typeof t)throw new TypeError("init must be an object.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(void 0!==t.duration&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(void 0!==t.visibleRect&&ye(t.visibleRect,"init.visibleRect"),"undefined"!==typeof VideoFrame)return new nn(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*G),duration:Math.trunc((t.duration??0)*G)||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:re(),willReadFrequently:!0});if(!n)throw new Error("OffscreenCanvas must have support for the '2d' context in order to create a VideoSample from this data.");n.drawImage(e,-a.left,-a.top),this._data=s,this._layout=null,this.format="RGBX",this.visibleRect={left:0,top:0,width:a.width,height:a.height},this.squarePixelWidth=a.width,this.squarePixelHeight=a.height,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=new dn({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else{if(!(e instanceof rn))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&&!an.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=ke({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),tn?.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return n(null!==this._data),this._data instanceof rn?new nn(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):hn(this._data)?new nn(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):this._data instanceof Uint8Array?(n(this._layout),new nn(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 nn(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||(tn?.unregister(this),this._data instanceof rn?(this._data._referenceCount--,0===this._data._referenceCount&&this._data.close()):hn(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(pn(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(hn(this._data))return this._data.allocationSize(e);return yn(this,e).allocationSize}async copyTo(e,t={}){if(!P(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(pn(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(n(null!==this._data),hn(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 rn)){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 nn))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(l){i.error=l,i.hasError=!0}finally{Js(i)}}}const i=yn(this,t);n(this.format);const r=h(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)n(this._layout),n(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");n(e);const t=e.getImageData(0,0,this.codedWidth,this.codedHeight);s=[{data:h(t.data),stride:4*this.codedWidth}]}const o=[],c=a.length;for(let n=0;na.byteLength)throw new Error("Source buffer OOB read.");if(l+u>r.byteLength)throw new Error("Destination buffer OOB write.");const i=a.subarray(c,c+u);r.set(i,l),c+=t,l+=e.destinationStride}o.push(d)}if(void 0!==t.format){const e=this.format.startsWith("RGB")!==t.format.startsWith("RGB"),a=this.format.includes("X")&&t.format.includes("A");if(e||a)for(let t=0;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 hn(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?(n(this._layout),new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,layout:this._layout,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,t,i,r,a,s,n,o,c){let l=0,u=0,d=this.displayWidth,h=this.displayHeight,f=0,m=0,p=this.displayWidth,g=this.displayHeight;if(void 0!==s?(l=t,u=i,d=r,h=a,f=s,m=n,void 0!==o?(p=o,g=c):(p=d,g=h)):(f=t,m=i,void 0!==r&&(p=r,g=a)),!("undefined"!==typeof CanvasRenderingContext2D&&e instanceof CanvasRenderingContext2D||"undefined"!==typeof OffscreenCanvasRenderingContext2D&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(l))throw new TypeError("sx must be a number.");if(!Number.isFinite(u))throw new TypeError("sy must be a number.");if(!Number.isFinite(d)||d<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(h)||h<0)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(f))throw new TypeError("dx must be a number.");if(!Number.isFinite(m))throw new TypeError("dy must be a number.");if(!Number.isFinite(p)||p<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(g)||g<0)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw new Error("VideoSample is closed.");({sx:l,sy:u,sWidth:d,sHeight:h}=this._rotateSourceRegion(l,u,d,h,this.rotation));const k=this.toCanvasImageSource();e.save();const y=f+p/2,b=m+g/2;e.translate(y,b),e.rotate(this.rotation*Math.PI/180);const w=this.rotation%180===0?1:p/g;e.scale(1/w,w),e.drawImage(k,l,u,d,h,-p/2,-g/2,p,g),e.restore()}drawWithFit(e,t){if(!("undefined"!==typeof CanvasRenderingContext2D&&e instanceof CanvasRenderingContext2D||"undefined"!==typeof OffscreenCanvasRenderingContext2D&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!t||"object"!==typeof t)throw new TypeError("options must be an object.");if(!["fill","contain","cover"].includes(t.fit))throw new TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");void 0!==t.crop&&mn(t.crop,"options.");const i=e.canvas.width,r=e.canvas.height,a=t.rotation??this.rotation,[s,n]=a%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let o,c,l,u,d=t.crop;d&&(d=fn(d,s,n));const{sx:h,sy:f,sWidth:m,sHeight:p}=this._rotateSourceRegion(t.crop?.left??0,t.crop?.top??0,t.crop?.width??s,t.crop?.height??n,a);if("fill"===t.fit)o=0,c=0,l=i,u=r;else{const[e,a]=t.crop?[t.crop.width,t.crop.height]:[s,n],d="contain"===t.fit?Math.min(i/e,r/a):Math.max(i/e,r/a);l=e*d,u=a*d,o=(i-l)/2,c=(r-u)/2}e.save();const g=a%180===0?1:l/u;e.translate(i/2,r/2),e.rotate(a*Math.PI/180),e.scale(1/g,g),e.translate(-i/2,-r/2),e.drawImage(this.toCanvasImageSource(),h,f,m,p,o,c,l,u),e.restore()}_rotateSourceRegion(e,t,i,r,a){return 90===a?[e,t,i,r]=[t,this.squarePixelHeight-e-i,r,i]:180===a?[e,t]=[this.squarePixelWidth-e-i,this.squarePixelHeight-t-r]:270===a&&([e,t,i,r]=[this.squarePixelWidth-t-r,e,r,i]),{sx:e,sy:t,sWidth:i,sHeight:r}}_drawWithFitAndMipmapping(e,t,i){const r=e.width,a=e.height,[s,n]=i.rotation%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],o=i.crop?i.crop.width:s,c=i.crop?i.crop.height:n;let l=0;2*r0?un(u,d):{canvas:e,context:t,isNew:i.targetIsFresh};f.imageSmoothingQuality="high",i.fillBlack?(f.fillStyle="black",f.fillRect(0,0,u,d)):m||f.clearRect(0,0,u,d),this.drawWithFit(f,{fit:i.fit,rotation:i.rotation,crop:i.crop}),f.globalCompositeOperation="copy";for(let p=l;p>1;p--){const e=r*2**p,t=a*2**p;f.drawImage(h,0,0,e,t,0,0,e/2,t/2)}f.globalCompositeOperation="source-over",l>0&&(t.imageSmoothingQuality="high",t.globalCompositeOperation="copy",t.drawImage(h,0,0,2*r,2*a,0,0,r,a),t.globalCompositeOperation="source-over")}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(n(null!==this._data),this._data instanceof rn||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&&mn(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=o(this.rotation+(e.rotate??0)),[i,r]=t%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let a=e.crop;a&&(a=fn(a,i,r));const s=a?a.width:i,n=a?a.height:r,c=s/n;let l,u;void 0!==e.width&&void 0===e.height?(l=e.width,u=l/c):void 0===e.width&&void 0!==e.height?(u=e.height,l=u*c):void 0!==e.width&&void 0!==e.height?(l=e.width,u=e.height):(l=s,u=n),l=H(l,e.roundDimensionsTo??1),u=H(u,e.roundDimensionsTo??1);const d={width:l,height:u,fit:e.fit??"fill",rotation:t,crop:a??{left:0,top:0,width:i,height:r},alpha:e.alpha??"keep"};for(const o of on){let e=o(this,d);if(ce(e)&&(e=await e),null!==e)return e}const{canvas:h,context:f,isNew:m}=un(d.width,d.height);return this._drawWithFitAndMipmapping(h,f,{fit:d.fit,rotation:d.rotation,crop:d.crop,targetIsFresh:m,fillBlack:"discard"===d.alpha}),new nn(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 on=[],cn=[];let ln=0;const un=(e,t)=>{for(const a of cn)if(a.canvas.width===e&&a.canvas.height===t)return a.age=ln++,{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 cn.length>=3&&cn.splice(ge(cn,e=>e.age),1),cn.push({canvas:i,context:r,age:ln++}),{canvas:i,context:r,isNew:!0}};class dn{constructor(e){if(void 0!==e){if(!e||"object"!==typeof e)throw new TypeError("init.colorSpace, when provided, must be an object.");const t=Object.keys(g);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(y);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(w);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 hn=e=>"undefined"!==typeof VideoFrame&&e instanceof VideoFrame,fn=(e,t,i)=>{const r=Math.min(e.left,t),a=Math.min(e.top,i),s=Math.min(e.width,t-r),o=Math.min(e.height,i-a);return n(s>=0),n(o>=0),{left:r,top:a,width:s,height:o}},mn=(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.")},pn=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.")}},gn=(e,t,i)=>{const r=kn(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},kn=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:N(e),n(!1)}},yn=(e,t)=>{const i={left:0,top:0,width:e.codedWidth,height:e.codedHeight},r=t.rect,a=bn(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 Tn(a,n,s)},bn=(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(!wn(a,s))throw new TypeError("visibleRect alignment is invalid for the format.");return s},wn=(e,t)=>{if(null===e)return!0;const i=kn(e);for(let r=0;r{const r=kn(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(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(e?.timestamp))throw new TypeError("init.timestamp must be a number.");const t=e.data.byteLength/(In(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*In(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=In(t),s=xn(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(!P(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&&!Sn.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,o=this.format;const c=i??this.format;if(!c)throw new Error("Destination format not determined");const l=this.numberOfFrames,u=this.numberOfChannels,d=a??0;if(d>=l)throw new RangeError("frameOffset out of range");const h=void 0!==r?r:l-d;if(h>l-d)throw new RangeError("frameCount out of range");const m=In(c),p=xn(c);if(p&&s>=u)throw new RangeError("planeIndex out of range");if(!p&&0!==s)throw new RangeError("planeIndex out of range");const g=(p?h:h*u)*m;if(e.byteLength2&&c!==o)return void _n(this._data,k,o,c,u,s,d,h);try{return void this._data.copyTo(e,{planeIndex:s,frameOffset:d,frameCount:h,format:c})}catch(I){if("f32-planar"===c)throw I;o="f32-planar"}}const b=Cn(o),w=In(o),T=xn(o);let S;if(this._data instanceof vn){const e=e=>{const t=this._data.getDataPlane(e);if(!(t instanceof Uint8Array))throw new TypeError("getDataPlane() must return a Uint8Array.");const i=l*w*(T?1:u);if(t.byteLength!==i)throw new TypeError(`Data plane ${e} has invalid size. Expected exactly ${i} bytes, got ${t.byteLength} bytes.`);return t};if(T)if(p)S=e(s),s=0;else{S=new Uint8Array(l*w*u);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 Pn({data:a,format:this.format,sampleRate:this.sampleRate,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp+e/this.sampleRate})}close(){this._closed||(tn?.unregister(this),this._data instanceof vn?(this._data._referenceCount--,0===this._data._referenceCount&&this._data.close()):En(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 vn?this._createAudioDataFromData():En(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(xn(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")}},xn=e=>{switch(e){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},Cn=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)}},Bn=e=>{switch(e){case"u8":case"u8-planar":return(e,t,i)=>e.setUint8(t,U(127.5*(i+1),0,255));case"s16":case"s16-planar":return(e,t,i)=>e.setInt16(t,U(Math.round(32767*i),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,i)=>e.setInt32(t,U(Math.round(2147483647*i),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,i)=>e.setFloat32(t,i,!0)}},En=e=>"undefined"!==typeof AudioData&&e instanceof AudioData,_n=(e,t,i,r,a,s,n,o)=>{const c=Cn(i),l=Bn(r),u=In(i),d=In(r),h=xn(i);if(xn(r))if(h){const r=new ArrayBuffer(o*u),a=f(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.")},Dn=e=>{if(!fe(e))throw new TypeError("timestamp must be a number.")},Mn=(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 Nn{constructor(e){if(!(e instanceof Yn))throw new TypeError("track must be an InputTrack.");this._track=e}async getFirstPacket(e={}){if(An(e),this._track.input._disposed)throw new mo;return Mn(this._track,this._track._backing.getFirstPacket(e),e)}async getFirstKeyPacket(e={}){An(e);const t=await this.getFirstPacket(e);return t?"key"===t.type?t:this.getNextKeyPacket(t,e):null}async getPacket(e,t={}){if(Dn(e),An(t),this._track.input._disposed)throw new mo;return Mn(this._track,this._track._backing.getPacket(e,t),t)}async getNextPacket(e,t={}){if(!(e instanceof bi))throw new TypeError("packet must be an EncodedPacket.");if(An(t),this._track.input._disposed)throw new mo;return Mn(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(Dn(e),An(t),this._track.input._disposed)throw new mo;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);const i=await this._track._backing.getKeyPacket(e,t);if(!i)return i;n("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 bi))throw new TypeError("packet must be an EncodedPacket.");if(An(t),this._track.input._disposed)throw new mo;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);const i=await this._track._backing.getNextKeyPacket(e,t);if(!i)return i;n("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 bi))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 bi))throw new TypeError("endPacket must be an EncodedPacket.");if(An(i),this._track.input._disposed)throw new mo;const r=[];let{promise:a,resolve:s}=F(),{promise:n,resolve:o}=F(),c=!1,l=!1,u=null,d=!1;const h=[],f=()=>Math.max(2,h.length);(async()=>{let u=e??await this.getFirstPacket(i);for(;u&&!l&&!this._track.input._disposed&&!(t&&u.sequenceNumber>=t?.sequenceNumber);)r.length>f()?(({promise:n,resolve:o}=F()),await n):(r.push(u),s(),({promise:a,resolve:s}=F()),u=await this.getNextPacket(u,i));c=!0,s()})().catch(e=>{d||(u=e,d=!0,s())});const m=this._track;return{async next(){for(;;){if(m.input._disposed)throw new mo;if(l)return{value:void 0,done:!0};if(d)throw u;if(r.length>0){const e=r.shift(),t=performance.now();for(h.push(t);h.length>0&&t-h[0]>=1e3;)h.shift();return o(),{value:e,done:!1}}if(c)return{value:void 0,done:!0};await a}},return:async()=>(l=!0,o(),s(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}}class On{constructor(e,t){this.onSample=e,this.onError=t}}class Ln{mediaSamplesInRange(e=-1/0,t=1/0,i){Dn(e),Dn(t);const r=[];let a=!1,s=null,{promise:n,resolve:o}=F(),{promise:c,resolve:l}=F(),u=!1,d=!1,h=!1,f=null,m=null,p=!1;const g={...i,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{f=await this._createDecoder(i=>{l(),i.timestamp>=t&&(d=!0),d?i.close():(s&&(i.timestamp>e?(r.push(s),a=!0):s.close()),i.timestamp>=e&&(r.push(i),a=!0),s=a?null:i,r.length>0&&(o(),({promise:n,resolve:o}=F())))},e=>{p||(m=e,p=!0,o())});const i=this._createPacketSink(),k=await i.getKeyPacket(e,g)??await i.getFirstKeyPacket(g);let y=k;const b=i.packets(k??void 0,void 0,g);for(await b.next();y&&!d&&!this._track.input._disposed;){const e=zn(r.length);if(r.length+f.getDecodeQueueSize()>e){({promise:c,resolve:l}=F()),await c;continue}f.decode(y);const t=await b.next();if(t.done)break;y=t.value}await b.return(),h||this._track.input._disposed||await f.flush(),!a&&s&&r.push(s),u=!0,o()})().catch(e=>{p||(m=e,p=!0,o())}).finally(()=>{f?.close()});const k=this._track,y=()=>{s?.close();for(const e of r)e.close()};return{async next(){for(;;){if(k.input._disposed)throw h=!0,d=!0,y(),new mo;if(h)return{value:void 0,done:!0};if(p)throw h=!0,d=!0,y(),m;if(r.length>0){const e=r.shift();return l(),{value:e,done:!1}}if(u)return{value:void 0,done:!0};await n}},return:async()=>(h=!0,d=!0,l(),o(),y(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e,t){(e=>{if(!(Symbol.iterator in e)&&!(Symbol.asyncIterator in e))throw new TypeError("Argument must be an iterable or async iterable.")})(e);const i=async function*(e){Symbol.iterator in e?yield*e[Symbol.iterator]():yield*e[Symbol.asyncIterator]()}(e),r=[],a=[];let{promise:s,resolve:o}=F(),{promise:c,resolve:l}=F(),u=!1,d=!1,h=null,f=null,m=!1;const p=e=>{a.push(e),o(),({promise:s,resolve:o}=F())},g={...t,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{h=await this._createDecoder(e=>{if(l(),d)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{m||(f=e,m=!0,o())});const e=this._createPacketSink();let t=null,s=null,k=-1;const y=async()=>{n(s),n(h);let t=s;for(h.decode(t);t.sequenceNumberi&&!d;)({promise:c,resolve:l}=F()),await c;if(d)break;const r=await e.getNextPacket(t,g);n(r),h.decode(r),t=r}k=-1},b=async()=>{n(h),await h.flush();for(let e=0;e{m||(f=e,m=!0,o())}).finally(()=>{h?.close()});const k=this._track,y=()=>{for(const e of a)e?.close()};return{async next(){for(;;){if(k.input._disposed)throw d=!0,y(),new mo;if(d)return{value:void 0,done:!0};if(m)throw d=!0,y(),f;if(a.length>0){const e=a.shift();return n(void 0!==e),l(),{value:e,done:!1}}if(u)return{value:void 0,done:!0};await s}},return:async()=>(d=!0,l(),o(),y(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}}const zn=e=>0===e?40:8;class Un extends On{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 Z,this.customDecoderQueueSize=0,this.inputTimestamps=[],this.sampleQueue=[],this.currentPacketIndex=0,this.raslSkipped=!1,this.alphaDecoder=null,this.alphaHadKeyframe=!1,this.colorQueue=[],this.alphaQueue=[],this.merger=null,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue=[],this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1,this.finalSamples=[],this.mergeAlphaPromises=[];const o=Rn.find(e=>e.supports(i,r));if(o)this.customDecoder=new o,this.customDecoder.codec=i,this.customDecoder.config=r,this.customDecoder.onSample=e=>{if(!(e instanceof nn))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();n(void 0!==t),this.mergeAlpha(e,t)}else this.colorQueue.push(e)};if(se()){if("avc"===i&&this.decoderConfig.description){const e=Ge(h(this.decoderConfig.description));if(e&&e.sequenceParameterSets.length>0){const t=Ye(e.sequenceParameterSets[0]);t&&(0===t.frameMbsOnlyFlag&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"}),0!==t.maxDecFrameBuffering&&1!==t.bitstreamRestrictionFlag&&(e.sequenceParameterSets[0]=Ze(t),this.decoderConfig={...this.decoderConfig,description:$e(e)}))}}S(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:(n(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(n(this.decoder),te()||R(this.inputTimestamps,e.timestamp,e=>e),se()&&0===this.currentPacketIndex)if("avc"===this.codec){const t=[];let i=!1;for(const a of qe(e.data,this.decoderConfig)){const r=We(e.data[a.offset]);if(i||(i=r>=1&&r<=5),r===Me.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&h(t.description)[4];return Ke(e,i+1)}return je(e)})(t,this.decoderConfig);e=new bi(r,e.type,e.timestamp,e.duration)}else if("hevc"===this.codec){const t=ft(e.data,this.decoderConfig);t&&(e=new bi(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 Wn),!this.alphaDecoder){const e=e=>{if(this.colorQueue.length>0){const t=this.colorQueue.shift();n(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();n(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=Tt(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 et(e,this.decoderConfig)){const i=tt(e[t.offset]);if(i===Oe.RASL_N||i===Oe.RASL_R)return!0}return!1}sampleHandler(e){if(te()){if(this.sampleQueue.length>0&&e.timestamp>=c(this.sampleQueue).timestamp){for(const e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}R(this.sampleQueue,e,e=>e.timestamp)}else{const t=this.inputTimestamps.shift();n(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=F();this.mergeAlphaPromises.push(i.promise);const r={sample:null};this.finalSamples.push(r);try{if(t){n(this.merger);const i=await this.merger.merge(e,t);r.sample=new nn(i)}else r.sample=new nn(e);for(;this.finalSamples.length>0&&null!==this.finalSamples[0].sample;){const e=this.finalSamples.shift();this.sampleHandler(e.sample)}}catch(a){A(this.finalSamples,r),this.onError(a)}finally{A(this.mergeAlphaPromises,i.promise),i.resolve()}}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(n(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),te()){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()):(n(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 qn=null;class Wn{constructor(){this.workers=[],this.nextWorkerIndex=0,this.pendingRequests=new Map,this.nextRequestId=0}merge(e,t){if(0===this.workers.length){if(!qn){const e=new Blob([`(${Hn.toString()})()`],{type:"application/javascript"});qn=URL.createObjectURL(e)}const e=U(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=F();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 Hn=()=>{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 d=r*a,h=d*c,f=l*u*c,m=new Uint8Array(h+2*f+d*c);await e.copyTo(m);const p=await o(t,r,a,c),g=h+2*f;m.set(p,g);const k={format:i.slice(0,4)+"A"+i.slice(4),codedWidth:r,codedHeight:a,timestamp:e.timestamp,duration:e.duration??void 0,transfer:[m.buffer]};return new VideoFrame(m,k)},n=async(e,i)=>{const r=e.visibleRect?.width??e.codedWidth,a=e.visibleRect?.height??e.codedHeight,s=r*a,n=Math.ceil(r/2)*Math.ceil(a/2),c=e.allocationSize();t&&t.byteLength===c||(t=new Uint8Array(c)),await e.copyTo(t);const l=new Uint8Array(s+2*n+s);l.set(t.subarray(0,s),0);const u=s,d=s+n,h=s;for(let o=0;o{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 jn extends Ln{constructor(e,t={}){if(!(e instanceof eo))throw new TypeError("videoTrack must be an InputVideoTrack.");Vn(t),super(),this._track=e,this._decoderOptions=t}async _createDecoder(e,t){if(!(await this._track.canDecode())){if("undefined"===typeof VideoDecoder)throw new Error(ne("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 n(i&&a),a={...a,hardwareAcceleration:this._decoderOptions.hardwareAcceleration,optimizeForLatency:this._decoderOptions.optimizeForLatency},new Un(e,t,i,a,r,s)}_createPacketSink(){return new Nn(this._track)}async getSample(e,t={}){Dn(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 Kn{constructor(e,t={}){if(this._rotation=0,this._initPromise=null,this._nextCanvasIndex=0,!(e instanceof eo))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&&mn(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&&Vn(t.decoderOptions),this._videoTrack=e,this._alpha=t.alpha??!1,this._options=t,this._fit=t.fit??"fill",this._videoSampleSink=new jn(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=fn(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||re()});n(s),e._drawWithFitAndMipmapping(r,s,{fit:this._fit,rotation:this._rotation,crop:this._crop,targetIsFresh:a,fillBlack:!this._alpha&&re()});const o={canvas:r,timestamp:e.timestamp,duration:e.duration};return e.close(),o}async getCanvas(e,t){Dn(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*z(this._videoSampleSink.samples(e,t,i),e=>this._videoSampleToWrappedCanvas(e))}async*canvasesAtTimestamps(e,t){await this._ensureInit(),yield*z(this._videoSampleSink.samplesAtTimestamps(e,t),e=>e&&this._videoSampleToWrappedCanvas(e))}}class Xn extends On{constructor(e,t,i,r){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new Z,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=Fn.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 Pn))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 Pn(e))}catch(t){this.onError(t)}},error:t=>{t.stack=e,this.onError(t)}}),this.decoder.configure(r)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(n(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--)):(n(this.decoder),this.expectedFirstTimestamp??(this.expectedFirstTimestamp=e.timestamp),this.decoder.decode(e.toEncodedAudioChunk()))}async flush(){this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(n(this.decoder),await this.decoder.flush()),this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(n(this.decoder),"closed"!==this.decoder.state&&this.decoder.close())}}class $n extends On{constructor(e,t,i){super(e,t),this.decoderConfig=i,this.currentTimestamp=null,n(Kt.includes(i.codec)),this.codec=i.codec;const{dataType:r,sampleSize:a,littleEndian:s}=si(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):n(!1);break;case 3:"unsigned"===r?this.readInputValue=(e,t)=>O(e,t,s)-2**23:"signed"===r?this.readInputValue=(e,t)=>((e,t,i)=>O(e,t,i)<<8>>8)(e,t,s):n(!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):n(!1);break;case 8:"float"===r?this.readInputValue=(e,t)=>e.getFloat64(t,s):n(!1);break;default:N(a),n(!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:N(a),n(!1)}}getDecodeQueueSize(){return 0}decode(e){const t=f(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 Pn({format:this.outputFormat,data:a,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:i,timestamp:o});this.onSample(c)}async flush(){}close(){}}class Gn extends Ln{constructor(e){if(!(e instanceof to))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(ne("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 n(i&&r),Kt.includes(r.codec)?new $n(e,t,r):new Xn(e,t,i,r)}_createPacketSink(){return new Nn(this._track)}async getSample(e,t={}){Dn(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 Qn{constructor(e){if(!(e instanceof to))throw new TypeError("audioTrack must be an InputAudioTrack.");this._audioSampleSink=new Gn(e)}_audioSampleToWrappedArrayBuffer(e){const t={buffer:e.toAudioBuffer(),timestamp:e.timestamp,duration:e.duration};return e.close(),t}async getBuffer(e,t){Dn(e);const i=await this._audioSampleSink.getSample(e,t);return i&&this._audioSampleToWrappedArrayBuffer(i)}buffers(e,t,i){return z(this._audioSampleSink.samples(e,t,i),e=>this._audioSampleToWrappedArrayBuffer(e))}buffersAtTimestamps(e,t){return z(this._audioSampleSink.samplesAtTimestamps(e,t),e=>e&&this._audioSampleToWrappedArrayBuffer(e))}}class Yn{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof eo}isAudioTrack(){return this instanceof to}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}async getInternalCodecId(){return this._backing.getInternalCodecId()}get internalCodecId(){return Jn(this._backing.getInternalCodecId(),"internalCodecId","getInternalCodecId")}async getLanguageCode(){return this._backing.getLanguageCode()}get languageCode(){return Jn(this._backing.getLanguageCode(),"languageCode","getLanguageCode")}async getName(){return this._backing.getName()}get name(){return Jn(this._backing.getName(),"name","getName")}async getTimeResolution(){return this._backing.getTimeResolution()}get timeResolution(){return Jn(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 Jn(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 V((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 Nn(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 Yn))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(so({filter:e=>e.canBePairedWith(this)},e))}async getPairableVideoTracks(e){return this.input.getVideoTracks(so({filter:e=>e.canBePairedWith(this)},e))}async getPairableAudioTracks(e){return this.input.getAudioTracks(so({filter:e=>e.canBePairedWith(this)},e))}async getPrimaryPairableVideoTrack(e){return this.input.getPrimaryVideoTrack(so({filter:e=>e.canBePairedWith(this)},e))}async getPrimaryPairableAudioTrack(e){return this.input.getPrimaryAudioTrack(so({filter:e=>e.canBePairedWith(this)},e))}async hasPairableTrack(e){e&&(e=Zn(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=Zn(e)),this.hasPairableTrack(async t=>t.isVideoTrack()&&(!e||await e(t)))}hasPairableAudioTrack(e){return e&&(e=Zn(e)),this.hasPairableTrack(async t=>t.isAudioTrack()&&(!e||await e(t)))}}const Jn=(e,t,i)=>{if(ce(e))throw new Error(`'${t}' is deprecated and not available synchronously for this track. Use the preferred '${i}()' instead.`);return e},Zn=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 ce(r)?r.then(i):i(r)}:void 0};class eo extends Yn{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 Jn(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 Jn(this._backing.getCodedWidth(),"codedWidth","getCodedWidth")}async getCodedHeight(){return this._backing.getCodedHeight()}get codedHeight(){return Jn(this._backing.getCodedHeight(),"codedHeight","getCodedHeight")}async getRotation(){return this._backing.getRotation()}get rotation(){return Jn(this._backing.getRotation(),"rotation","getRotation")}async getSquarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelWidth(){return Jn(this._backing.getSquarePixelWidth(),"squarePixelWidth","getSquarePixelWidth")}async getSquarePixelHeight(){return this._backing.getSquarePixelHeight()}get squarePixelHeight(){return Jn(this._backing.getSquarePixelHeight(),"squarePixelHeight","getSquarePixelHeight")}async getPixelAspectRatio(){return this._pixelAspectRatioCache??(this._pixelAspectRatioCache=ke({num:await this.getSquarePixelWidth()*await this.getCodedHeight(),den:await this.getSquarePixelHeight()*await this.getCodedWidth()}))}get pixelAspectRatio(){return this._pixelAspectRatioCache??(this._pixelAspectRatioCache=ke({num:Jn(this._backing.getSquarePixelWidth(),"pixelAspectRatio","getPixelAspectRatio")*Jn(this._backing.getCodedHeight(),"pixelAspectRatio","getPixelAspectRatio"),den:Jn(this._backing.getSquarePixelHeight(),"pixelAspectRatio","getPixelAspectRatio")*Jn(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=Jn(e,"displayWidth","getDisplayWidth");if(null!==t)return t}const t=Jn(this._backing.getRotation(),"displayWidth","getDisplayWidth")%180===0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight();return Jn(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=Jn(e,"displayHeight","getDisplayHeight");if(null!==t)return t}const t=Jn(this._backing.getRotation(),"displayHeight","getDisplayHeight")%180===0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth();return Jn(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(n(null!==t),Rn.some(i=>i.supports(t,e)))return!0;if("undefined"===typeof VideoDecoder)return!1;return!0===(await VideoDecoder.isConfigSupported(e)).supported}catch(e){return ve._error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof bi))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 n(i),Tt(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&&(!fe(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 Nn(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=(d/T+d/S)/2;return{underlyingFrameRate:u,bestGuessFrameRate:null!==u?u:lo(P),minFrameRate:d/p,maxFrameRate:d/m,averageFrameRate:d*k/g,medianFrameRate:P,frameRateIsConstant:null!==u&&1===m&&1===p,probedPacketCount:n}}}class to extends Yn{constructor(e,t){super(e,t),this._backing=t}get type(){return"audio"}async getCodec(){return this._backing.getCodec()}get codec(){return Jn(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){return await(this._backing.getHasOnlyKeyPackets?.())??!0}async getNumberOfChannels(){return this._backing.getNumberOfChannels()}get numberOfChannels(){return Jn(this._backing.getNumberOfChannels(),"numberOfChannels","getNumberOfChannels")}async getSampleRate(){return this._backing.getSampleRate()}get sampleRate(){return Jn(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(n(null!==t),Fn.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 ve._error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof bi))throw new TypeError("packet must be an EncodedPacket.");return null===await this.getCodec()?null:"key"}}const io=e=>-(e??-1/0),ro=e=>-e,ao=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 ce(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 ce(r)?r.then(i):i(r)}:void 0}},so=(e,t)=>({filter:e?.filter||t?.filter?i=>{const r=e?.filter?.(i)??!0,a=e=>!1!==e&&(t?.filter?.(i)??!0);return ce(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 ce(r)||ce(a)?Promise.all([r,a]).then(([e,t])=>s(e,t)):s(r,a)}:void 0}),no=async(e,t)=>{let i=e;if(t?.filter){const r=e.map(e=>t.filter(e));if(r.some(e=>ce(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=>ce(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)},oo=(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 d=1/Math.min(u,1e3),h=Math.max(Number.EPSILON,o-d),f=o+d,m=t/f,p=t/h,g=t/o;let k=null,y=1/0;for(const T of a){if(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 xs)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof Ja||e.source instanceof Za))throw new TypeError("options.source must be a Source or SourceRef.");if(e.source instanceof Ja&&e.source._disposed)throw new TypeError("options.source must not be a disposed Source.");if(void 0!==e.initInput&&!(e.initInput instanceof ho))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 Ja?this._rootRef=e.source.ref():this._rootRef=e.source,this._sourceRefs.push(this._rootRef)}get _rootSource(){return this._rootRef.source}async _getSourceUncached(e){n(this._rootSource instanceof es);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&&ts(i.request,e));if(i)return i.age++,Promise.resolve(i.sourceRef.source.ref());const r=this._sourceCachePromises.find(i=>i.cacheGroup===t&&ts(i.request,e));if(r)return r.promise.then(e=>e.sourceRef.source.ref());const a=(async()=>{const i=await this._getSourceUncached(e);if(pe(this._sourceCache,e=>e.cacheGroup===t&&1===e.sourceRef.source._refCount)>=4){const e=ge(this._sourceCache,e=>e.cacheGroup===t&&1===e.sourceRef.source._refCount?e.age:1/0);n(-1!==e);const i=this._sourceCache[e];this._sourceCache.splice(e,1),i.sourceRef.free(),A(this._sourceRefs,i.sourceRef)}this._sourceRefs.push(i);const r=this._sourceCachePromises.findIndex(t=>t.request===e);n(-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 po(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 fo})())}get source(){return this._rootSource}async getFormat(){return await this._getDemuxer(),n(this._format),this._format}async canRead(){try{return await this._getDemuxer(),!0}catch(e){if(e instanceof fo)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=ao(e));const t=(await this._getTrackBackings()).map(e=>this._wrapBackingAsTrack(e));return no(t,e)}async getVideoTracks(e){e&&(e=ao(e));const t=(await this.getTracks()).filter(e=>e.isVideoTrack());return no(t,e)}async getAudioTracks(e){e&&(e=ao(e));const t=(await this.getTracks()).filter(e=>e.isAudioTrack());return no(t,e)}async getPrimaryVideoTrack(e){e&&(e=ao(e));const t=so(e,{sortBy:async e=>[ro((await e.getDisposition()).default),ro(await e.hasPairableAudioTrack()),ro(!(await e.hasOnlyKeyPackets())),io(await e.getBitrate())]});return(await this.getVideoTracks(t))[0]??null}async getPrimaryAudioTrack(e){e&&(e=ao(e));const t=await this.getPrimaryVideoTrack(),i=so(e,{sortBy:async e=>[ro(!t||e.canBePairedWith(t)),ro((await e.getDisposition()).default),io(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 eo(this,e):new to(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 fo extends Error{constructor(e="Input has an unsupported or unrecognizable format."){super(e),this.name="UnsupportedInputFormatError"}}class mo extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}}class po{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 mo;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 go(t,f(t),0,e,e)}const i=e+t,r=this.source._read(e,i,0,Ya);return ce(r)?r.then(t=>t?new go(t.bytes,t.view,t.offset,e,i):null):r?new go(r.bytes,r.view,r.offset,e,i):null}requestSliceRange(e,t,i){if(this.source._disposed)throw new mo;if(e<0)return null;if(null!==this.fileSizeNonStrict)return this.requestSlice(e,U(this.fileSizeNonStrict-e,t,i));{const r=this.requestSlice(e,i),a=r=>r||(n(null!==this.fileSizeNonStrict),this.requestSlice(e,U(this.fileSizeNonStrict-e,t,i)));return ce(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(ce(i)&&(i=await i),!i||0===i.length)break;const r=yo(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 go(i,f(i),0,0,t)})()}}class go{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 go(e,f(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 go(this.bytes,this.view,this.offset,e,e+t)}}const ko=(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.`)},yo=(e,t)=>{ko(e,t);const i=e.bytes.subarray(e.bufferPos,e.bufferPos+t);return e.bufferPos+=t,i},bo=e=>(ko(e,1),e.view.getUint8(e.bufferPos++)),wo=(e,t)=>{ko(e,2);const i=e.view.getUint16(e.bufferPos,t);return e.bufferPos+=2,i},To=e=>{ko(e,2);const t=e.view.getUint16(e.bufferPos,!1);return e.bufferPos+=2,t},So=e=>{ko(e,3);const t=O(e.view,e.bufferPos,!1);return e.bufferPos+=3,t},vo=e=>{ko(e,2);const t=e.view.getInt16(e.bufferPos,!1);return e.bufferPos+=2,t},Po=(e,t)=>{ko(e,4);const i=e.view.getUint32(e.bufferPos,t);return e.bufferPos+=4,i},Io=e=>{ko(e,4);const t=e.view.getUint32(e.bufferPos,!1);return e.bufferPos+=4,t},xo=e=>{ko(e,4);const t=e.view.getUint32(e.bufferPos,!0);return e.bufferPos+=4,t},Co=e=>{ko(e,4);const t=e.view.getInt32(e.bufferPos,!1);return e.bufferPos+=4,t},Bo=(e,t)=>{let i,r;return t?(i=Po(e,!0),r=Po(e,!0)):(r=Po(e,!1),i=Po(e,!1)),4294967296*r+i},Eo=e=>4294967296*Io(e)+Io(e),_o=e=>4294967296*Co(e)+Io(e),Ro=e=>{const t=xo(e),i=(e=>{ko(e,4);const t=e.view.getInt32(e.bufferPos,!0);return e.bufferPos+=4,t})(e);return 4294967296*i+t},Fo=e=>{ko(e,4);const t=e.view.getFloat32(e.bufferPos,!1);return e.bufferPos+=4,t},Ao=e=>{ko(e,8);const t=e.view.getFloat64(e.bufferPos,!1);return e.bufferPos+=8,t},Do=(e,t)=>{ko(e,t);let i="";for(let r=0;rm.decode(yo(e,t)).split("\n").map(e=>e.trim()).filter(e=>e.length>0&&!i?.ignore?.(e));var No,Oo,Lo,zo;(Oo=No||(No={}))[Oo.Unsynchronisation=128]="Unsynchronisation",Oo[Oo.ExtendedHeader=64]="ExtendedHeader",Oo[Oo.ExperimentalIndicator=32]="ExperimentalIndicator",Oo[Oo.Footer=16]="Footer",(zo=Lo||(Lo={}))[zo.ISO_8859_1=0]="ISO_8859_1",zo[zo.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",zo[zo.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",zo[zo.UTF_8=3]="UTF_8";const Uo=128,qo=10,Wo=["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"],Ho=(e,t)=>{var i;const r=e.filePos;t.raw??(t.raw={}),(i=t.raw).TAG??(i.TAG=yo(e,Uo-3)),e.filePos=r;const a=Vo(e,30);a&&(t.title??(t.title=a));const s=Vo(e,30);s&&(t.artist??(t.artist=s));const n=Vo(e,30);n&&(t.album??(t.album=n));const o=Vo(e,4),c=Number.parseInt(o,10);Number.isInteger(c)&&c>0&&(t.date??(t.date=new Date(String(c))));const l=yo(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=Vo(e,28),e.skip(2)}else e.skip(-30),u=Vo(e,30);u&&(t.comment??(t.comment=u));const d=bo(e);d{const i=yo(e,t),r=le(i.indexOf(0),i.length),a=i.subarray(0,r);let s="";for(let n=0;n{const t=e.filePos,i=Do(e,3),r=bo(e),a=bo(e),s=bo(e),n=Io(e);if("ID3"!==i||255===r||255===a||0!==(2155905152&n))return e.filePos=t,null;let o=fi(n);return s&No.Footer&&(o+=qo),{majorVersion:r,revision:a,flags:s,size:o}},Ko=(e,t,i)=>{var r,a,s,n,o;if(![2,3,4].includes(t.majorVersion))return void ve._warn(`Unsupported ID3v2 major version: ${t.majorVersion}`);const c=t.flags&No.Footer?t.size-qo:t.size,l=yo(e,c),u=new Xo(t,l);if(t.flags&No.Unsynchronisation&&3===t.majorVersion&&u.ununsynchronizeAll(),t.flags&No.ExtendedHeader){const e=u.readU32();3===t.majorVersion?u.pos+=e:u.pos+=e-4}for(;u.pos<=u.bytes.length-u.frameHeaderSize();){const e=u.readId3V2Frame();if(!e)break;const c=u.pos,l=u.pos+e.size;let d=!1,h=!1,f=!1;if(3===t.majorVersion?(d=!!(64&e.flags),h=!!(128&e.flags)):4===t.majorVersion&&(d=!!(4&e.flags),h=!!(8&e.flags),f=!!(2&e.flags)||!!(t.flags&No.Unsynchronisation)),d)ve._warn(`Skipping encrypted ID3v2 frame ${e.id}`),u.pos=l;else if(h)ve._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!==Wo[e]){i.genre??(i.genre=Wo[e]);break}}if(t=/^\d+$/.exec(e),t){const e=Number.parseInt(t[0]);if(void 0!==Wo[e]){i.genre??(i.genre=Wo[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 Xo{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:fi(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 Lo.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=le(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=le(r.findIndex(e=>0===e),r.length);return this.pos=i+Math.min(e+1,r.length),m.decode(r.subarray(0,e))}case Lo.UTF_16_BE_NO_BOM:{const e=new TextDecoder("utf-16be"),t=le(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 Lo.UTF_8:{const e=le(r.findIndex(e=>0===e),r.length);return this.pos=i+Math.min(e+1,r.length),m.decode(r.subarray(0,e))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";const t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}}class $o{constructor(e){this.events=e,this.input=null,this.audioSink=null,this.audioIterator=null,this.audioContext=null,this.gainNode=null,this.audioContextStartTime=0,this.playbackTimeAtStart=0,this.latestScheduledEndTime=0,this.duration=Number.NaN,this.paused=!0,this.volume=.7,this.muted=!1,this.playbackRate=1,this.asyncId=0,this.queuedNodes=new Set}get currentTime(){return this.paused?this.playbackTimeAtStart:(this.audioContext.currentTime-this.audioContextStartTime)*this.playbackRate+this.playbackTimeAtStart}ensureAudioContext(e){if(this.audioContext)return;const t=window.AudioContext||window.webkitAudioContext;try{this.audioContext=new t({sampleRate:e})}catch{this.audioContext=new t}this.gainNode=this.audioContext.createGain(),this.gainNode.connect(this.audioContext.destination),this.updateGain()}updateGain(){if(!this.gainNode)return;const e=this.muted?0:this.volume;this.gainNode.gain.value=e*e}stopQueuedNodes(){this.queuedNodes.forEach(e=>e.stop()),this.queuedNodes.clear()}async stopIterator(){await(this.audioIterator?.return()),this.audioIterator=null}handleNoAudioTrack(){this.audioSink=null,this.ensureAudioContext()}async load(e,t){++this.asyncId,await this.stopIterator(),this.stopQueuedNodes(),this.paused=!0,this.playbackTimeAtStart=0,this.audioContextStartTime=0;const{input:i,audioTrack:r,duration:a}=e;return this.input=i,this.duration=a,r?null!==r.codec&&await r.canDecode()?(this.ensureAudioContext(r.sampleRate),this.audioSink=new Qn(r),void t?.()):(this.audioSink=null,this.ensureAudioContext(),void t?.()):(this.handleNoAudioTrack(),void t?.())}async runIterator(e){if(!this.audioSink)return;await this.stopIterator(),this.audioIterator=this.audioSink.buffers(this.currentTime);for(;;){if(e!==this.asyncId||this.paused)return;const i=[];let r=!1;try{for(let e=0;e<16;e++){const e=await this.audioIterator.next();if(e.done){r=!0;break}i.push(e.value)}}catch(t){console.error("Audio iterator error:",t),r=!0}if(e!==this.asyncId||this.paused)return;i.length>0&&"suspended"===this.audioContext.state&&(await this.audioContext.resume(),this.events.emit("canplay"),this.events.emit("playing"));for(const{buffer:e,timestamp:t}of i){const i=this.audioContext.createBufferSource();i.buffer=e,i.connect(this.gainNode),i.playbackRate.value=this.playbackRate;const r=this.audioContextStartTime+(t-this.playbackTimeAtStart)/this.playbackRate,a=(r+e.duration/this.playbackRate-this.audioContextStartTime)*this.playbackRate+this.playbackTimeAtStart;a>this.latestScheduledEndTime&&(this.latestScheduledEndTime=a),r>=this.audioContext.currentTime?i.start(r):i.start(this.audioContext.currentTime,(this.audioContext.currentTime-r)*this.playbackRate),this.queuedNodes.add(i),i.onended=()=>this.queuedNodes.delete(i)}if(r)break;await new Promise(e=>setTimeout(e,0));const a=1;for(;this.latestScheduledEndTime-this.currentTime>a;){if(e!==this.asyncId||this.paused)return;await new Promise(e=>setTimeout(e,50))}}}async play(){if(!this.paused)return;this.audioContext||this.ensureAudioContext(),"suspended"===this.audioContext.state&&await this.audioContext.resume(),this.audioContextStartTime=this.audioContext.currentTime,this.latestScheduledEndTime=this.playbackTimeAtStart,this.paused=!1;const e=++this.asyncId;this.runIterator(e)}pause(){this.paused||(this.playbackTimeAtStart=this.currentTime,this.paused=!0,this.stopIterator(),this.stopQueuedNodes())}async seek(e){this.playbackTimeAtStart=Math.max(0,e),this.audioContextStartTime=this.audioContext.currentTime,this.latestScheduledEndTime=this.playbackTimeAtStart;const t=++this.asyncId;this.paused||this.runIterator(t)}setVolume(e,t){this.volume=e,this.muted=t,this.updateGain()}setPlaybackRate(e){if(e!==this.playbackRate&&(this.paused||(this.playbackTimeAtStart=this.currentTime,this.audioContextStartTime=this.audioContext.currentTime),this.playbackRate=e,!this.paused)){const e=++this.asyncId;this.runIterator(e)}}destroy(){this.asyncId++,this.pause(),this.audioContext?.close(),this.audioContext=null,this.input=null,this.audioSink=null}}async function Go(e){return await e.getAverageBitrate()??await e.getBitrate()??0}const Qo=/\.m3u8(?:$|[?#])/i;function Yo(e){return"string"===typeof e&&Qo.test(e)}function Jo(e){const t=function(e){return"string"===typeof e?new os(e):e instanceof Blob?new as(e):"undefined"!==typeof ReadableStream&&e instanceof ReadableStream?new us(e):e??null}(e);return t?new ho({source:t,formats:Yo(e)?Ys:Qs}):null}class Zo{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 ec({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}class tc{constructor({canvas:e,ctx:t,events:i,timeupdateInterval:r=250,avSyncTolerance:a=.12,dropLateFrames:s=!1,poster:n="",preflightRange:o=!1}){this.canvas=e,this.ctx=t,this.events=i,this.timeupdateInterval=r,this.avSyncTolerance=a,this.dropLateFrames=s,this.poster=n,this.preflightRange=o,this.input=null,this.videoSink=null,this.videoIterator=null,this.nextFrame=null,this.rafId=0,this.asyncId=0,this.width=0,this.height=0,this.duration=Number.NaN,this.audioClock=null,this.lastTimeUpdate=0,this.stalled=!1,this.playbackRate=1,this.posterDrawn=!1,this.isFetching=!1}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||Yo(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(!this.poster||this.posterDrawn)return;const e=new Image;e.onload=()=>{this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.canvas.width=e.naturalWidth||this.canvas.width,this.canvas.height=e.naturalHeight||this.canvas.height,this.ctx.drawImage(e,0,0,this.canvas.width,this.canvas.height),this.posterDrawn=!0},e.src=this.poster}async stopIterator(){await(this.videoIterator?.return()),this.videoIterator=null}clear(){this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height)}async load(e,t){++this.asyncId,await this.stopIterator(),this.clear(),this.posterDrawn=!1;const{input:i,videoTrack:r,duration:a}=e;if(this.input=i,this.duration=a,!r)return this.handleNoVideoTrack(),void t?.();if(null===r.codec||!(await r.canDecode()))return this.handleNoVideoTrack(),void t?.();const s=await r.canBeTransparent();this.videoSink=new Kn(r,{poolSize:2,fit:"contain",alpha:s}),this.width=r.displayWidth,this.height=r.displayHeight,this.canvas.width=this.width,this.canvas.height=this.height,t?.(),await this.resetIterator(0)}handleNoVideoTrack(){this.videoSink=null,this.width=0,this.height=0,this.canvas.width=0,this.canvas.height=0,this.clear(),this.drawPoster()}async resetIterator(e){if(await this.stopIterator(),!this.videoSink)return;this.videoIterator=this.videoSink.canvases(e);const t=(await this.videoIterator.next()).value??null,i=(await this.videoIterator.next()).value??null;this.nextFrame=i,t?this.ctx.drawImage(t.canvas,0,0):this.drawPoster()}async updateNextFrame(e){if(this.videoIterator&&!this.isFetching){this.isFetching=!0;try{for(;;){const t=(await this.videoIterator.next()).value??null;if(!t||e!==this.asyncId)return;const i=this.audioClock.currentTime,r=this.dropLateFrames?Math.max(.06,this.avSyncTolerance/Math.max(1,this.playbackRate)):0;if(!(this.dropLateFrames&&t.timestampi)return void(this.nextFrame=null)}}}finally{this.isFetching=!1}}}render(){if(!this.audioClock)return;const e=this.audioClock.currentTime,t=Date.now();if(t-this.lastTimeUpdate>=this.timeupdateInterval&&(this.events.emit("timeupdate"),this.lastTimeUpdate=t),Number.isFinite(this.duration)&&e>=this.duration)return this.stop(),this.stalled=!1,this.events.emit("ended"),this.events.emit("pause"),void this.events.emit("canplay");this.nextFrame&&this.nextFrame.timestamp<=e?(this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.ctx.drawImage(this.nextFrame.canvas,0,0),this.nextFrame=null,this.updateNextFrame(this.asyncId),this.stalled&&(this.events.emit("canplay"),this.events.emit("playing"),this.stalled=!1)):this.nextFrame||(this.updateNextFrame(this.asyncId),!this.nextFrame&&Number.isFinite(this.duration)&&ethis.render())}start(e){this.audioClock=e,this.asyncId++,this.stalled=!1,this.updateNextFrame(this.asyncId),this.rafId=requestAnimationFrame(()=>this.render())}stop(){cancelAnimationFrame(this.rafId)}async seek(e){this.asyncId++,await this.resetIterator(e)}setPlaybackRate(e){this.playbackRate=Math.max(.1,Number(e)||1)}destroy(){this.asyncId++,this.stop(),this.stopIterator(),this.posterDrawn=!1,this.videoSink=null,this.input=null}}class ic{constructor({canvas:e,ctx:t,events:i,option:r={}}){this.events=i,this.option=r,this.audio=new $o(i),this.video=new tc({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}),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,i.addEventListener?.("ended",()=>{this.ended=!0,this.paused=!0})}async load(e){if(this.destroyed)return;const t=++this.loadSeq;if(this.loadSession?.cancel(),t!==this.loadSeq||this.destroyed)return;if(this.pause(),t!==this.loadSeq||this.destroyed)return;this.disposeInput();const i=new Zo;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;try{await i.wait(this.performLoad(e,t,i),r)}catch(a){if(t!==this.loadSeq)return;const e=++this.loadSeq;if(i.cancel(),e!==this.loadSeq||this.destroyed)return;this.disposeInput(),this.error={code:4,message:a.message},this.networkState=3,this.events.emit("error")}}async performLoad(e,t,i=this.loadSession){if(!(await this.video.preflight(e,i?.signal,()=>t===this.loadSeq))||t!==this.loadSeq)return;const r=Jo(e);if(!r)return this.video.handleNoVideoTrack(),void this.audio.handleNoAudioTrack();i.own(r);const a=await async function(e,t){const i=await e.getPrimaryVideoTrack(),r=i?await i.getPrimaryPairableAudioTrack():await e.getPrimaryAudioTrack(),a=await ec({input:e,videoTrack:i,audioTrack:r}),s=i||r,n=Yo(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"}}(r,e);if(t!==this.loadSeq)return;this.input=r,this.media=a;let s=!a.videoTrack,n=!a.audioTrack;const o=()=>{s&&n&&(this.readyState=1,this.events.emit("loadedmetadata"),this.events.emit("durationchange"),this.events.emit("progress"))};try{if(await Promise.all([this.video.load(a,()=>{t===this.loadSeq&&(s=!0,o())}),this.audio.load(a,()=>{t===this.loadSeq&&(n=!0,o())})]),t!==this.loadSeq)return;this.readyState=4,this.networkState=1,this.events.emit("loadeddata"),this.events.emit("canplay"),this.events.emit("canplaythrough"),this.events.emit("progress")}catch(c){if(t!==this.loadSeq)return;throw console.error("MediaBunny load error:",c),c}}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({videoTrack:e,audioTrack:t,videoMode:i,audioMode:r}){if(!this.media)return;const a={...this.media,videoTrack:e,audioTrack:t,videoMode:i,audioMode:r},s=!this.paused,n=this.currentTime;this.pause(),this.ended=!1,this.seeking=!0,this.events.emit("seeking"),this.events.emit("waiting"),a.duration=await ec(a),this.media=a,await Promise.all([this.video.load(a),this.audio.load(a)]),await Promise.all([this.video.seek(n),this.audio.seek(n)]),this.readyState=4,this.networkState=1,this.seeking=!1,this.events.emit("loadedmetadata"),this.events.emit("durationchange"),this.events.emit("progress"),this.events.emit("loadeddata"),this.events.emit("canplay"),this.events.emit("canplaythrough"),this.events.emit("seeked"),s&&await this.play()}async selectHlsQuality(e){if(!this.media?.isHls||!this.input)return;const t=await this.input.getVideoTracks(),i="auto"===e?await this.input.getPrimaryVideoTrack():t.find(t=>t.id===e)??this.media.videoTrack;if(!i)return;let r=this.media.audioTrack,a=this.media.audioMode;r&&i.canBePairedWith(r)||(r=await i.getPrimaryPairableAudioTrack(),a="auto"),await this.replaceTracks({videoTrack:i,audioTrack:r,videoMode:"auto"===e?"auto":"manual",audioMode:a})}async selectHlsAudio(e){if(!this.media?.isHls||!this.input)return;const t=await this.input.getAudioTracks(),i="auto"===e?this.media.videoTrack?await this.media.videoTrack.getPrimaryPairableAudioTrack():await this.input.getPrimaryAudioTrack():t.find(t=>t.id===e)??this.media.audioTrack;if(!i)return;let r=this.media.videoTrack,a=this.media.videoMode;r&&i.canBePairedWith(r)||(r=await i.getPrimaryPairableVideoTrack(),a="auto"),await this.replaceTracks({videoTrack:r,audioTrack:i,videoMode:a,audioMode:"auto"===e?"auto":"manual"})}getHlsState(){return 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 Go(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 Go(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"}}(this.media)}async play(){this.paused&&(this.ended&&(this.ended=!1,await this.seek(0)),this.paused=!1,await this.audio.play(),this.video.start(this.audio),this.events.emit("play"),this.events.emit("playing"))}pause(){this.paused||(this.paused=!0,this.audio.pause(),this.video.stop(),this.events.emit("pause"))}async seek(e){const t=!this.paused;this.ended=!1,this.seeking=!0,this.events.emit("seeking"),this.events.emit("waiting"),this.pause(),await Promise.all([this.audio.seek(e),this.video.seek(e)]),this.seeking=!1,this.events.emit("seeked"),t&&!this.ended&&await this.play()}setVolume(e,t){this.audio.setVolume(e,t)}setPlaybackRate(e){this.audio.setPlaybackRate(e),this.video.setPlaybackRate(e)}destroy(){this.destroyed||(this.destroyed=!0,this.loadSeq++,this.loadSession?.cancel(),this.pause(),this.disposeInput(),this.audio.destroy(),this.video.destroy())}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}}const rc=new WeakMap;function ac(e){let t=rc.get(e);return t||(t={closed:!1,frames:new Set},rc.set(e,t)),t}class sc{constructor({art:e,canvas:t,ctx:i,option:r}){this.art=e,this.canvas=t,this.option=r,this.events=new s,this.engine=new ic({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){this.engine.seek(Number(e)||0)}get duration(){return this.engine.duration}get buffered(){return this.createTimeRanges(0,this.engine.duration)}get played(){return this.createTimeRanges(0,this.engine.currentTime)}get seekable(){return this.createTimeRanges(0,this.engine.duration)}createTimeRanges(e,t){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=ac(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){ac(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=ac(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,s=r("canvas"),n=s.getContext("2d"),o=new sc({art:t,canvas:s,ctx:n,option:e});t.mediabunny=o;const c={};for(const e in s)"function"===typeof s[e]&&(c[e]=s[e].bind(s));const l=new Set([...Object.getOwnPropertyNames(o),...Object.getOwnPropertyNames(Object.getPrototypeOf(o))]);for(const e of l)"constructor"!==e&&(e in s||Object.defineProperty(s,e,{get(){const t=o[e];return"function"===typeof t?t.bind(o):t},set(t){o[e]=t},configurable:!0,enumerable:!0}));for(const e in c)s[e]=(...t)=>c[e](...t);function u(){const e=t.template?.$player;e&&!t.option.autoSize&&Object.assign(s.style,{width:"100%",height:"100%",objectFit:"contain"})}return t.on("resize",u),t.on("video:loadedmetadata",u),function({art:e,shim:t,option:i}){if(i.m3u8)return e.on("video:loadedmetadata",d),e.on("restart",d),{update:d};function r(t){e.controls.cache.has(t)&&e.controls.remove(t)}function s(t){e.setting.find(t)&&e.setting.remove(t)}function n(){r("mediabunny-quality"),s("mediabunny-quality")}function o(){r("mediabunny-audio"),s("mediabunny-audio")}function c(e={}){return e.control||e.setting}async function l(r){const s=i.m3u8?.quality||{};if(!c(s)||!r?.levels.length)return void n();const o=s.auto||"Auto",l=s.title||"Quality",u=s.getName||(e=>e.name||`${e.height}P`),h=r.currentLevel?u(r.currentLevel):o,f=a(r.levels.map(e=>({html:u(e),value:e.id,default:r.currentLevel?.id===e.id})),"html").sort((e,t)=>{const i=r.levels.find(t=>t.id===e.value),a=r.levels.find(e=>e.id===t.value);return(a?.height||0)-(i?.height||0)});f.push({html:o,value:"auto",default:!r.currentLevel});const m=async i=>(await t.switchM3u8Quality(i.value),e.notice.show=`${l}: ${i.html}`,await d(),i.html);s.control&&e.controls.update({name:"mediabunny-quality",position:"right",html:h,style:{padding:"0 10px"},selector:f,onSelect:m}),s.setting&&e.setting.update({name:"mediabunny-quality",tooltip:h,html:l,icon:'',width:200,selector:f,onSelect:m})}async function u(r){const s=i.m3u8?.audio||{};if(!c(s)||!r?.audios.length||r.audios.length<2)return void o();const n=s.auto||"Auto",l=s.title||"Audio",u=s.getName||(e=>e.name||e.lang||e.language),h=r.currentAudio?u(r.currentAudio):n,f=a(r.audios.map(e=>({html:u(e),value:e.id,default:r.currentAudio?.id===e.id})),"html");f.push({html:n,value:"auto",default:!r.currentAudio});const m=async i=>(await t.switchM3u8Audio(i.value),e.notice.show=`${l}: ${i.html}`,await d(),i.html);s.control&&e.controls.update({name:"mediabunny-audio",position:"right",html:h,style:{padding:"0 10px"},selector:f,onSelect:m}),s.setting&&e.setting.update({name:"mediabunny-audio",tooltip:h,html:l,icon:'',width:200,selector:f,onSelect:m})}async function d(){const e=await t.getM3u8State();if(!e)return n(),void o();await Promise.all([l(e),u(e)])}}({art:t,shim:o,option:e}),t.on("destroy",()=>{delete t.mediabunny,o.destroy()}),s}}}); +!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=e=>{throw TypeError(e)},r=(e,t,r)=>t.has(e)||i("Cannot "+r),a=(e,t,i)=>(r(e,t,"read from private field"),i?i.call(e):t.get(e)),s=(e,t,r)=>t.has(e)?i("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),n=(e,t,i,a)=>(r(e,t,"write to private field"),a?a.call(e,i):t.set(e,i),i);function o(e,t){const i=new Map;return e.filter(e=>{const r=e[t];return void 0===r||!i.has(r)&&i.set(r,1)})}class c{constructor(){s(this,e,!1),this.listeners=new Map}addEventListener(t,i){a(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(a(this,e))return;const r=Object.assign(new Event(t),{detail:i});this.listeners.get(t)?.forEach(t=>{a(this,e)||t(r)})}destroy(){n(this,e,!0),this.listeners.clear()}}function l(e){if(!e)throw new Error("Assertion failed.")}e=new WeakMap;const u=e=>{const t=(e%360+360)%360;if(0===t||90===t||180===t||270===t)return t;throw new Error(`Invalid rotation ${e}.`)},d=e=>e&&e[e.length-1],h=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)},m=e=>{const t=h(e);return 0===(1&t)?-(t>>1):t+1>>1},p=e=>e.constructor===Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),g=e=>e.constructor===DataView?e:ArrayBuffer.isView(e)?new DataView(e.buffer,e.byteOffset,e.byteLength):new DataView(e),k=new TextDecoder,y=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])),b={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},w=y(b),T={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},S=y(T),v={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},P=y(v),I=e=>!!e&&!!e.primaries&&!!e.transfer&&!!e.matrix&&void 0!==e.fullRange,x={primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0},C=e=>e instanceof ArrayBuffer||"undefined"!==typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e);class B{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 E=/^[0-9a-fA-F]+$/,_=e=>[...e].map(e=>e.toString(16).padStart(2,"0")).join(""),R=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,F=(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},D=(e,t,i)=>{const r=A(e,i(t),i);e.splice(r+1,0,t)},M=()=>{let e,t;return{promise:new Promise((i,r)=>{e=i,t=r}),resolve:e,reject:t}},N=(e,t)=>{const i=e.indexOf(t);-1!==i&&e.splice(i,1)},O=(e,t)=>{for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},L=(e,t)=>{for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},z=e=>{throw new Error(`Unexpected value: ${e}`)},U=(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},q=(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)},W=(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}}),H=(e,t,i)=>Math.max(t,Math.min(i,e)),V="und",j=e=>{const t=Math.round(e);return Math.abs(e/t-1)<10*Number.EPSILON?t:e},K=(e,t)=>Math.round(e/t)*t,X=(e,t)=>Math.round(e*t)/t,$=(e,t)=>Math.floor(e/t)*t,G=e=>{let t=0;for(;0!==e;)e&=e-1,t++;return t},Q=/^[a-z]{3}$/,Y=e=>Q.test(e),J=1e6*(1+Number.EPSILON),Z=(e,t)=>{const i={...e,...t};if(e.headers||t.headers){const r=e.headers?ee(e.headers):{},a=t.headers?ee(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},ee=e=>{if(e instanceof Headers){const t={};return e.forEach((e,i)=>{t[i]=e}),t}if(Array.isArray(e)){const t={};return e.forEach(([e,i])=>{t[e]=i}),t}return e},te=async(e,t,i,r,a)=>{let s=0;for(;;)try{return await e(t,i)}catch(n){if(a())throw n;s++;const e=r(s,n,t);if(null===e)throw n;if(xe._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 Se(1e3*e),a())throw n}};class ie{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}let re=null;const ae=()=>null!==re?re:re=!("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 se=null;const ne=()=>null!==se?se:se="undefined"!==typeof navigator&&navigator.userAgent?.includes("Firefox");let oe=null;const ce=()=>null!==oe?oe:oe=!("undefined"===typeof navigator||!navigator.vendor?.includes("Google Inc")&&!/Chrome/.test(navigator.userAgent)),le=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.`,ue=(async()=>{})().constructor,de=e=>e instanceof ue||e instanceof Promise||"function"===typeof e?.then,he=(e,t)=>-1!==e?e:t,fe=(e,t,i,r)=>e<=r&&i<=t,me=e=>{const t=atob(e),i=new Uint8Array(t.length);for(let r=0;r{Symbol.dispose??(Symbol.dispose=Symbol("Symbol.dispose"))},ge=e=>"number"===typeof e&&!Number.isNaN(e),ke=(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("/")},ye=(e,t)=>{let i=0;for(let r=0;r{let i=-1,r=1/0;for(let a=0;a{l(Number.isInteger(e.num)),l(Number.isInteger(e.den)),l(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}},Te=(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.`)},Se=e=>new Promise(t=>setTimeout(t,e));class ve{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 Pe,Ie;(Ie=Pe||(Pe={}))[Ie.Silent=0]="Silent",Ie[Ie.Errors=1]="Errors",Ie[Ie.Warnings=2]="Warnings",Ie[Ie.Info=3]="Info";class xe{constructor(){}static get level(){return xe._level}static set level(e){if(e!==Pe.Silent&&e!==Pe.Errors&&e!==Pe.Warnings&&e!==Pe.Info)throw new TypeError("Invalid log level. Use one of the values of the LogLevel enum.");xe._level=e}static get _emitter(){return xe._emitterInstance??(xe._emitterInstance=new ve)}static on(e,t,i){return xe._emitter.on(e,t,i)}static _error(...e){xe._emitter._emit("error",e),xe._level>=Pe.Errors&&console.error(...e)}static _warn(...e){xe._emitter._emit("warn",e),xe._level>=Pe.Warnings&&console.warn(...e)}static _info(...e){xe._emitter._emit("info",e),xe._level>=Pe.Info&&console.info(...e)}}xe._level=Pe.Info,xe._emitterInstance=null;class Ce{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 Be{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 Ee={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1};class _e{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 _e(this.bytes);return e.pos=this.pos,e}}const Re=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],Fe=[-1,1,2,3,4,5,6,8],Ae=e=>{if(!e||e.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");const t=new _e(e),i=De(t),{frequencyIndex:r,sampleRate:a}=Me(t),s=t.readBits(4);let n=null;s>=1&&s<=7&&(n=Fe[s]);let o=i,c=!1,l=a;if(5===i||29===i)c=29===i,l=Me(t).sampleRate,o=De(t),22===o&&t.skipBits(4);else for(;t.getBitsLeft()>15;){const e=t.pos;if(695===t.readBits(11)){5===De(t)&&t.readBits(1)&&(l=Me(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}},De=e=>{const t=e.readBits(5);return 31===t?32+e.readBits(6):t},Me=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&p(t.description)[4];return He(e,i+1)}return We(e)},je=e=>31&e,Ke=e=>{const t=[],i=e.length;for(let r=0;r{const t=e.reduce((e,t)=>e+Xe.byteLength+t.byteLength,0),i=new Uint8Array(t);let r=0;for(const a of e)i.set(Xe,r),r+=Xe.byteLength,i.set(a,r),r+=a.byteLength;return i},Ge=(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:q(e,a,s.byteLength);break;case 4:e.setUint32(a,s.byteLength,!1)}a+=t,r.set(s,a),a+=s.byteLength}return r},Qe=e=>{try{const t=[],i=[],r=[];for(const o of We(e)){const a=e.subarray(o.offset,o.offset+o.length),s=je(a[0]);s===Le.SPS?t.push(a):s===Le.PPS?i.push(a):s===Le.SPS_EXT&&r.push(a)}if(0===t.length)return null;if(0===i.length)return null;const a=t[0],s=et(a);l(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 xe._error("Error building AVC Decoder Configuration Record:",t),null}},Ye=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=g(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=Ke(e),i=new _e(t);i.skipBits(1),i.skipBits(2);if(7!==i.readBits(5))return null;const r=i.readAlignedByte(),a=i.readAlignedByte(),s=i.readAlignedByte();h(i);let n=1,o=0,c=0,u=0;if(100===r||110===r||122===r||244===r||44===r||83===r||86===r||118===r||128===r){n=h(i),3===n&&(u=i.readBits(1)),o=h(i),c=h(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)??d(Yt),r=Math.min(Math.floor(i.maxDpbMbs/(e*t)),16);C=r,B=r}else C=0,B=0}return l(null!==B),{emulationUnpreventedBytes:t,profileIdc:r,constraintFlags:a,levelIdc:s,frameMbsOnlyFlag:T,chromaFormatIdc:n,bitDepthLumaMinus8:o,bitDepthChromaMinus8:c,codedWidth:k,codedHeight:y,displayWidth:b,displayHeight:w,pixelAspectRatio:x,colourPrimaries:S,matrixCoefficients:P,transferCharacteristics:v,fullRangeFlag:I,numReorderFrames:C,maxDecFrameBuffering:B,vuiParametersFlagBitOffset:R,bitstreamRestrictionFlagBitOffset:E,bitstreamRestrictionFlag:_}}catch(t){return xe._error("Error parsing AVC SPS:",t),null}},tt=e=>{const t=h(e);e.skipBits(4),e.skipBits(4);for(let i=0;i<=t;i++)h(e),h(e),e.skipBits(1);e.skipBits(5),e.skipBits(5),e.skipBits(5),e.skipBits(5)},it=e=>{l(1!==e.bitstreamRestrictionFlag);const t=new Uint8Array(e.emulationUnpreventedBytes.byteLength+64),i=new _e(e.emulationUnpreventedBytes),r=new _e(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)):(l(null!==e.bitstreamRestrictionFlagBitOffset),r.copyBits(e.bitstreamRestrictionFlagBitOffset,i)),r.writeBits(1,1),r.writeBits(1,1),f(r,2),f(r,1),f(r,16),f(r,16),f(r,e.numReorderFrames),f(r,e.maxDecFrameBuffering),r.writeBits(1,1),r.writeBits((8-r.pos%8)%8,0);const a=r.pos/8;return l(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))},rt=(e,t)=>{if(t.description){const i=3&p(t.description)[21];return He(e,i+1)}return We(e)},at=e=>e>>1&63,st=e=>{try{const t=new _e(Ke(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}=ot(t,i);h(t);const u=h(t);let d=0;3===u&&(d=t.readBits(1));const f=h(t),m=h(t);let p=f,g=m;if(t.readBits(1)){const e=h(t),i=h(t),r=h(t),a=h(t);let s=1,n=1;const o=0===d?u:0;1===o?(s=2,n=2):2===o&&(s=2,n=1),p-=(e+i)*s,g-=(r+a)*n}const k=h(t),y=h(t);h(t);const b=t.readBits(1);let w=0;for(let e=b?0:i;e<=i;e++)h(t),w=h(t),h(t);h(t),h(t),h(t),h(t),h(t),h(t),t.readBits(1)&&t.readBits(1)&&ct(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(4),t.skipBits(4),h(t),h(t),t.skipBits(1));const T=h(t);if(lt(t,T),t.readBits(1)){const e=h(t);for(let i=0;i{try{const t=[],i=[],r=[],a=[];for(const c of We(e)){const s=e.subarray(c.offset,c.offset+c.length),n=at(s[0]);n===Ue.VPS_NUT?t.push(s):n===Ue.SPS_NUT?i.push(s):n===Ue.PPS_NUT?r.push(s):n!==Ue.PREFIX_SEI_NUT&&n!==Ue.SUFFIX_SEI_NUT||a.push(s)}if(0===i.length||0===r.length)return null;const s=st(i[0]);if(!s)return null;let n=0;if(r.length>0){const e=r[0],t=new _e(Ke(e));t.skipBits(16),h(t),h(t),t.skipBits(1),t.skipBits(1),t.skipBits(3),t.skipBits(1),t.skipBits(1),h(t),h(t),m(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&h(t),m(t),m(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:Ue.VPS_NUT,nalUnits:t}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:Ue.SPS_NUT,nalUnits:i}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:Ue.PPS_NUT,nalUnits:r}]:[],...a.length?[{arrayCompleteness:1,nalUnitType:at(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 xe._error("Error building HEVC Decoder Configuration Record:",t),null}},ot=(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&&m(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-(h(e)+1)}else n=t-1;e.readBits(1),h(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=h(e),i=h(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=Ze[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)&&(h(e),h(e)),e.readBits(1),e.readBits(1),e.readBits(1),e.readBits(1)&&(h(e),h(e),h(e),h(e)),e.readBits(1)&&(e.readBits(32),e.readBits(32),e.readBits(1)&&h(e),e.readBits(1)&&ht(e,!0,t)),e.readBits(1)&&(e.readBits(1),e.readBits(1),e.readBits(1),n=h(e),h(e),h(e),h(e),h(e)),{pixelAspectRatio:o,colourPrimaries:i,transferCharacteristics:r,matrixCoefficients:a,fullRangeFlag:s,minSpatialSegmentationIdc:n}},ht=(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?h(e):i=1===e.readBits(1);let n=1;if(!i){n=h(e)+1}r&&ft(e,n,s),a&&ft(e,n,s)}},ft=(e,t,i)=>{for(let r=0;r{const i=new Set;let r=mt.audAllowed;for(const s of rt(e,t)){if(r===mt.noMoreDataAllowed){i.add(s.offset);continue}const t=at(e[s.offset]);if(r===mt.eoBitstreamAllowed&&37!==t){i.add(s.offset);continue}let a=!1;35===t?r>mt.audAllowed?a=!0:r=mt.beforeFirstVcl:t<=31?r>mt.afterFirstVcl?a=!0:r=mt.afterFirstVcl:36===t?r!==mt.afterFirstVcl?a=!0:r=mt.eoBitstreamAllowed:37===t?r=41&&t<=44||t>=48&&t<=55?r>mt.beforeFirstVcl?a=!0:r=mt.beforeFirstVcl:(38===t||40===t||t>=45&&t<=47||t>=56&&t<=63)&&r{if(t.description){const i=3&p(t.description)[21];return Ge(e,i+1)}return $e(e)})(a,t)},kt={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}},yt=e=>{const t=new _e(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=d(Jt).level;for(const d of Jt)if(c<=d.maxPictureSize){l=d.level;break}const u=kt[s];return{profile:r,level:l,bitDepth:a,chromaSubsampling:n,videoFullRangeFlag:o,colourPrimaries:u?.colourPrimaries??2,transferCharacteristics:u?.transferCharacteristics??2,matrixCoefficients:u?.matrixCoefficients??2}},bt=function*(e){const t=new _e(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);l(t.pos%8===0),yield{type:r,data:e.subarray(t.pos/8,t.pos/8+n)},t.skipBits(8*n)}},wt=e=>{for(const{type:t,data:i}of bt(e)){if(1!==t)continue;const e=new _e(i),r=e.readBits(3);e.readBits(1);const a=e.readBits(1);let s=0,n=0,o=0;if(a)s=e.readBits(5);else{let t=0;if(e.readBits(1)){e.skipBits(32),e.skipBits(32);if(e.readBits(1)){let t=0;for(;t<32&&!e.readBits(1);)t++;t<32&&e.skipBits(t)}t=e.readBits(1),t&&(o=e.readBits(5),e.skipBits(32),e.skipBits(5),e.skipBits(5))}const i=e.readBits(1),r=e.readBits(5);for(let a=0;a<=r;a++){e.skipBits(12);const r=e.readBits(5);if(0===a&&(s=r),r>7){const t=e.readBits(1);0===a&&(n=t)}if(t){if(e.readBits(1)){const t=o+1;e.skipBits(t),e.skipBits(t),e.skipBits(1)}}if(i){e.readBits(1)&&e.skipBits(4)}}}const c=e.readBits(4),l=e.readBits(4),u=c+1;e.skipBits(u);const d=l+1;e.skipBits(d);let h=0;if(h=a?0:e.readBits(1),h&&(e.skipBits(4),e.skipBits(3)),e.skipBits(1),e.skipBits(1),e.skipBits(1),!a){e.skipBits(1),e.skipBits(1),e.skipBits(1),e.skipBits(1);const t=e.readBits(1);t&&(e.skipBits(1),e.skipBits(1));let i=0;if(i=e.readBits(1)?2:e.readBits(1),i>0){e.readBits(1)||e.skipBits(1)}t&&e.skipBits(3)}e.skipBits(1),e.skipBits(1),e.skipBits(1);const f=e.readBits(1);let m=8;if(2===r&&f){m=e.readBits(1)?12:10}else r<=2&&(m=f?10:8);let p=0;1!==r&&(p=e.readBits(1));let g=2,k=2,y=2;e.readBits(1)&&(g=e.readBits(8),k=e.readBits(8),y=e.readBits(8));let b=0,w=1,T=1,S=0;return p?b=e.readBits(1):1===g&&13===k&&0===y?(b=1,w=0,T=0):(b=e.readBits(1),0===r?(w=1,T=1):1===r?(w=0,T=0):12===m?(w=e.readBits(1),T=w?e.readBits(1):0):(w=1,T=0),w&&T&&(S=e.readBits(2))),{profile:r,level:s,tier:n,bitDepth:m,monochrome:p,chromaSubsamplingX:w,chromaSubsamplingY:T,chromaSamplePosition:S,videoFullRangeFlag:b,colourPrimaries:g,transferCharacteristics:k,matrixCoefficients:y}}return null},Tt=e=>{if(e.length<36)return null;const t=g(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)}},St=[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],vt=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}},Pt=(e,t,i)=>{switch(e){case"avc":for(const e of Ve(i,t)){const t=i[e.offset],r=je(t);if(r>=Le.NON_IDR_SLICE&&r<=Le.SLICE_DPC)return"delta";if(r===Le.IDR)return"key";if(r===Le.SEI&&!ce()){const t=i.subarray(e.offset,e.offset+e.length),r=Ke(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 _e(r);e.pos=8*a;const t=h(e),i=e.readBits(1);if(0===t&&1===i)return"key"}a+=t}while(a{var i,r;const a=g(e);let s=0;const n=a.getUint32(s,!0);s+=4;const o=k.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=me(l),i=g(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=k.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})}}}},Bt=[2,1,2,3,3,4,4,5],Et=e=>{if(e.length<7)return null;if(11!==e[0]||119!==e[1])return null;const t=new _e(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)}},_t=[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],Rt=[1,2,3,6],Ft=e=>{if(e.length<6)return null;if(11!==e[0]||119!==e[1])return null;const t=new _e(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=Rt[s];let d;d=a<3?Ne[a]/1e3:Oe[n]/1e3;return{dataRate:Math.round((r+1)*d/(16*u)),substreams:[{fscod:a,fscod2:n,bsid:l,bsmod:0,acmod:o,lfeon:c,numDepSub:0,chanLoc:0}]}},At=e=>{const t=e.substreams[0];return l(t),t.fscod<3?Ne[t.fscod]:null!==t.fscod2&&t.fscod2<3?Oe[t.fscod2]:null},Dt=e=>{const t=e.substreams[0];l(t);let i=Bt[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},Mt=[0,8e3,16e3,32e3,0,0,11025,22050,44100,0,0,12e3,24e3,48e3,96e3,192e3],Nt=[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],Ot=[16,16,20,20,0,24,24,0],Lt=[1,2,2,2,2,3,3,4,4,5,6,6,6,7,8,8],zt=[1,2,2,2,2,3,18,19,6,7,518,323,83,519,582,535],Ut=[32e3,44100,48e3,0],qt=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],Wt=[512,1024,2048,4096],Ht=e=>{const t=jt(e),i=g(e);let r=t?4*Math.ceil(t.frameSize/4):0,a=null;for(;r+4<=e.length&&1683496997===i.getUint32(r);){const t=Kt(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}},Vt=e=>{const t=Ht(e);return t?.core?t.hasExtensions?"dtsh":"dtsc":null},jt=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 _e(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>=Lt.length)return null;const n=Mt[t.readBits(4)];if(0===n)return null;const o=Nt[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=Ot[t.readBits(3)];if(0===l)return null;const u=0!==c;return{frameSize:a,sampleRate:n,numberOfChannels:Lt[s]+(u?1:0),sampleCount:32*r,channelLayout:zt[s]|(u?8:0),amode:s,lfePresent:u,bitRate:o,pcmResolution:l}},Kt=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 _e(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=Ut[t.readBits(2)],l=512*(t.readBits(3)+1);t.readBits(1)&&t.skipBits(36);const u=t.readBits(3)+1,d=t.readBits(3)+1,h=[];for(let k=0;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}}},Xt=e=>G(e)+G(44646&e),$t=["avc","hevc","vp9","av1","vp8","prores"],Gt=["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"],Qt=["aac","opus","mp3","vorbis","flac","ac3","eac3","dts",...Gt],Yt=[{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}],Jt=[{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}],Zt=".01.01.01.01.00",ei=".0.110.01.01.01.0",ti=["ap4x","ap4h","apch","apcn","apcs","apco"],ii=["dtsc","dtsh","dtsl","dtse"],ri=e=>{const{codec:t,codecDescription:i,colorSpace:r,avcCodecInfo:a,hevcCodecInfo:s,vp9CodecInfo:n,av1CodecInfo:o,proresFormat:c}=e;if("avc"===t){if(l(null!==e.avcType),a){const t=new Uint8Array([a.avcProfileIndication,a.profileCompatibility,a.avcLevelIndication]);return`avc${e.avcType}.${_(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}.${_(i.subarray(1,4))}`}if("hevc"===t){let e,t,r,a,n,o;if(s)e=s.generalProfileSpace,t=s.generalProfileIdc,r=R(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=g(i),c=s.getUint8(1);e=c>>6&3,t=31&c,r=R(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=d(Jt).level;for(const e of Jt)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(Zt)&&(t=t.slice(0,-15)),t}if("av1"===t){if(!o){const t=e.width*e.height;let i=d(Jt).level;for(const e of Jt)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?b[r.primaries]:1,u=r?.transfer?T[r.transfer]:1,h=r?.matrix?v[r.matrix]:1,f=r?.fullRange?1:0;let m=`av01.${t}.${i}${a}.${s}`;return m+=`.${n}.${c.toString().padStart(3,"0")}`,m+=`.${l.toString().padStart(2,"0")}`,m+=`.${u.toString().padStart(2,"0")}`,m+=`.${h.toString().padStart(2,"0")}`,m+=`.${f}`,m.endsWith(ei)&&(m=m.slice(0,-17)),m}if("prores"===t)return c??"apch";throw null!==t&&z(t),new TypeError(`Unhandled codec '${t}'.`)},ai=e=>{switch(e.codec){case"avc":{let t=e.avcCodecInfo?.sequenceParameterSets[0];if(!t&&e.codecDescription&&(t=Je(e.codecDescription)?.sequenceParameterSets[0]),t){const e=et(t);if(e)return{primaries:w[e.colourPrimaries],transfer:S[e.transferCharacteristics],matrix:P[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case"hevc":{let t=e.hevcCodecInfo?.arrays.find(e=>e.nalUnitType===Ue.SPS_NUT)?.nalUnits[0];if(!t&&e.codecDescription&&(t=(e=>{try{const t=g(e);let i=0;const r=t.getUint8(i++),a=t.getUint8(i++),s=a>>6&3,n=a>>5&1,o=31&a,c=t.getUint32(i,!1);i+=4;const l=e.subarray(i,i+6);i+=6;const u=t.getUint8(i++),d=(15&t.getUint8(i++))<<8|t.getUint8(i++),h=3&t.getUint8(i++),f=3&t.getUint8(i++),m=7&t.getUint8(i++),p=7&t.getUint8(i++),k=t.getUint16(i,!1);i+=2;const y=t.getUint8(i++),b=y>>6&3,w=y>>3&7,T=y>>2&1,S=3&y,v=t.getUint8(i++),P=[];for(let g=0;g>7&1,s=63&r,n=t.getUint16(i,!1);i+=2;const o=[];for(let c=0;ce.nalUnitType===Ue.SPS_NUT)?.nalUnits[0]),t){const e=st(t);if(e)return{primaries:w[e.colourPrimaries],transfer:S[e.transferCharacteristics],matrix:P[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case"vp8":break;case"vp9":if(e.vp9CodecInfo)return{primaries:w[e.vp9CodecInfo.colourPrimaries],transfer:S[e.vp9CodecInfo.transferCharacteristics],matrix:P[e.vp9CodecInfo.matrixCoefficients],fullRange:!!e.vp9CodecInfo.videoFullRangeFlag};break;case"av1":if(e.av1CodecInfo)return{primaries:w[e.av1CodecInfo.colourPrimaries],transfer:S[e.av1CodecInfo.transferCharacteristics],matrix:P[e.av1CodecInfo.matrixCoefficients],fullRange:!!e.av1CodecInfo.videoFullRangeFlag};break;case"prores":if(e.proresCodecInfo)return{primaries:w[e.proresCodecInfo.colourPrimaries],transfer:S[e.proresCodecInfo.transferCharacteristics],matrix:P[e.proresCodecInfo.matrixCoefficients],fullRange:e.proresCodecInfo.fullRange}}return{primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0}},si=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=Ae(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&&Gt.includes(t))return t;throw new TypeError(`Unhandled codec '${t}'.`)},ni=48e3,oi=/^pcm-([usf])(\d+)(be)?$/,ci=e=>{if(l(Gt.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=oi.exec(e);let i;l(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}},li=e=>e.startsWith("avc1")||e.startsWith("avc3")?"avc":e.startsWith("hev1")||e.startsWith("hvc1")?"hevc":"vp8"===e?"vp8":e.startsWith("vp09")?"vp9":e.startsWith("av01")?"av1":ti.includes(e)?"prores":"mp3"===e||"mp4a.69"===e||"mp4a.6B"===e||"mp4a.6b"===e||"mp4a.40.34"===e?"mp3":e.startsWith("mp4a.40.")||"mp4a.67"===e?"aac":"opus"===e?"opus":"vorbis"===e?"vorbis":"flac"===e?"flac":"ac-3"===e||"ac3"===e?"ac3":"ec-3"===e||"eac3"===e?"eac3":ii.includes(e)?"dts":"ulaw"===e?"ulaw":"alaw"===e?"alaw":oi.test(e)?e:"webvtt"===e?"webvtt":null,ui=[44100,48e3,32e3],di=[-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],hi=1483304551,fi=1231971951,mi=(e,t)=>3===e?3===t?21:36:3===t?13:21,pi=(e,t)=>{const i=e>>>24,r=e>>>16&255,a=e>>>8&255,s=255&e;if(255!==i&&255!==r&&255!==a&&255!==s)return{header:null,bytesAdvanced:4};if(255!==i)return{header:null,bytesAdvanced:1};if(224!==(224&r))return{header:null,bytesAdvanced:1};let n=0,o=0;16&r?n=8&r?0:1:(n=1,o=1);const c=r>>3&3,l=r>>1&3,u=(a>>2&3)%3,d=s>>6&3,h=s>>4&3,f=s>>3&1,m=s>>2&1,p=3&s,g=di[16*n*4+16*l+(a>>4&15)];if(-1===g)return{header:null,bytesAdvanced:1};const k=1e3*g,y=ui[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 ki,yi;(yi=ki||(ki={}))[yi.FrameCount=1]="FrameCount",yi[yi.FileSize=2]="FileSize",yi[yi.Toc=4]="Toc";const bi=e=>3===e?1:2;class wi{constructor(e){this.input=e}dispose(){}}const Ti=new Uint8Array(0);class Si{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===Ti&&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===Ti}get microsecondTimestamp(){return Math.trunc(J*this.timestamp)}get microsecondDuration(){return Math.trunc(J*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 Si(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 Si(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 vi=e=>{const t=g(e);let i=0;const r=t.getUint8(i);i+=1,i+=3;const a=_(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=Bo(e);const i=Oo(e,4);let r=8;1===t&&(t=Fo(e),r=16);const a=t-r;return a<0?null:{name:i,totalSize:t,headerSize:r,contentSize:a}},xi=e=>_o(e)/65536,Ci=e=>_o(e)/1073741824,Bi=e=>{let t=0;for(let i=0;i<4;i++){t<<=7;const i=So(e);if(t|=127&i,0===(128&i))break}return t},Ei=e=>{let t=Po(e);return e.skip(2),t=Math.min(t,e.remainingLength),k.decode(To(e,t))},_i=e=>{const t=Ii(e);if(!t||"data"!==t.name)return null;if(e.remainingLength<8)return null;const i=Bo(e);e.skip(4);const r=To(e,t.contentSize-8);switch(i){case 1:return k.decode(r);case 2:return new TextDecoder("utf-16be").decode(r);case 13:return new Ce(r,"image/jpeg");case 14:return new Ce(r,"image/png");case 27:return new Ce(r,"image/bmp");default:return r}},Ri=16,Fi=new Uint32Array(256),Ai=new Uint32Array(256),Di=new Uint32Array(256),Mi=new Uint32Array(256),Ni=new Uint32Array(256),Oi=new Uint32Array(256),Li=new Uint32Array(10);let zi=!1;class Ui{constructor(){this.roundkey=new Uint32Array(44),this.iv=new Uint32Array(Ri/Uint32Array.BYTES_PER_ELEMENT),this.in=new Uint8Array(Ri),this.out=new Uint8Array(Ri),this.inView=new DataView(this.in.buffer),this.outView=new DataView(this.out.buffer)}init({key:e,iv:t}){l(16===e.byteLength),l(16===t.byteLength),zi||(()=>{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);Fi[s]=t<<24|t<<16|t<<8|t,Oi[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);Ai[s]=a,Di[s]=a>>>8|a<<24,Mi[s]=a>>>16|a<<16,Ni[s]=a>>>24|a<<8}let a=1;for(let s=0;s<10;s++)Li[s]=a<<24,a=a<<1^(128&a?283:0);zi=!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&Fi[e>>>16&255]^16711680&Fi[e>>>8&255]^65280&Fi[e>>>0&255]^255&Fi[e>>>24&255]^Li[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]]^Di[255&Fi[t>>>16&255]]^Mi[255&Fi[t>>>8&255]]^Ni[255&Fi[t>>>0&255]]}}decrypt(){let e=this.inView.getUint32(0,!1)^this.roundkey[0],t=this.inView.getUint32(4,!1)^this.roundkey[1],i=this.inView.getUint32(8,!1)^this.roundkey[2],r=this.inView.getUint32(12,!1)^this.roundkey[3];const a=this.inView.getUint32(0,!1),s=this.inView.getUint32(4,!1),n=this.inView.getUint32(8,!1),o=this.inView.getUint32(12,!1);let c,l,u,d;for(let g=1;g<10;g++){const a=4*g;c=Ai[e>>>24]^Di[r>>>16&255]^Mi[i>>>8&255]^Ni[255&t]^this.roundkey[a],l=Ai[t>>>24]^Di[e>>>16&255]^Mi[r>>>8&255]^Ni[255&i]^this.roundkey[a+1],u=Ai[i>>>24]^Di[t>>>16&255]^Mi[e>>>8&255]^Ni[255&r]^this.roundkey[a+2],d=Ai[r>>>24]^Di[i>>>16&255]^Mi[t>>>8&255]^Ni[255&e]^this.roundkey[a+3],e=c,t=l,i=u,r=d}const h=4278190080&Oi[e>>>24&255]^16711680&Oi[r>>>16&255]^65280&Oi[i>>>8&255]^255&Oi[t>>>0&255]^this.roundkey[40],f=4278190080&Oi[t>>>24&255]^16711680&Oi[e>>>16&255]^65280&Oi[r>>>8&255]^255&Oi[i>>>0&255]^this.roundkey[41],m=4278190080&Oi[i>>>24&255]^16711680&Oi[t>>>16&255]^65280&Oi[e>>>8&255]^255&Oi[r>>>0&255]^this.roundkey[42],p=4278190080&Oi[r>>>24&255]^16711680&Oi[i>>>16&255]^65280&Oi[t>>>8&255]^255&Oi[e>>>0&255]^this.roundkey[43];this.outView.setUint32(0,h^this.iv[0],!1),this.outView.setUint32(4,f^this.iv[1],!1),this.outView.setUint32(8,m^this.iv[2],!1),this.outView.setUint32(12,p^this.iv[3],!1),this.iv[0]=a,this.iv[1]=s,this.iv[2]=n,this.iv[3]=o}}class qi extends wi{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(de(r)&&(r=await r),!r)break;const a=e,s=Ii(r);if(!s)break;if("ftyp"===s.name||"styp"===s.name){const e=Oo(r,4);this.isQuickTime="qt "===e}else{if("moov"===s.name){let e=this.reader.requestSlice(r.filePos,s.contentSize);if(de(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){l(null!==this.reader.fileSize);let e=this.reader.requestSlice(this.reader.fileSize-4,4);de(e)&&(e=await e),l(e);const t=Bo(e),i=this.reader.fileSize-t;if(i>=0&&i<=this.reader.fileSize-16){let e=this.reader.requestSliceRange(i,8,16);if(de(e)&&(e=await e),e){const t=Ii(e);if(t&&"mfra"===t.name){let i=this.reader.requestSlice(e.filePos,t.contentSize);de(i)&&(i=await i),i&&this.readContiguousBoxes(i)}}}}})())}async copyMetadataFromInitInput(e){const t=await e._getDemuxer();if(t.constructor!==qi)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(l(e.info),"video"===e.info.type&&-1!==e.info.width){const t=e;e.trackBacking=new Hi(t),this.tracks.push(e)}else if("audio"===e.info.type&&-1!==e.info.numberOfChannels){const t=e;e.trackBacking=new Vi(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;l(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&&Gt.includes(e.info.codec)&&0===t.sampleCompositionTimeOffsets.length){l("audio"===e.info?.type);const i=ci(e.info.codec),r=[],a=[];for(let s=0;se.startIndex),u=t.sampleTimingEntries[l],h=A(t.sampleTimingEntries,c,e=>e.startIndex),f=t.sampleTimingEntries[h],m=u.startDecodeTimestamp+(o-u.startIndex)*u.delta,p=f.startDecodeTimestamp+(c-f.startIndex)*f.delta-m,g=d(r);g&&g.delta===p?g.count++:r.push({startIndex:n.startChunkIndex+s,startDecodeTimestamp:m,count:1,delta:p});const k=n.samplesPerChunk*i.sampleSize*e.info.numberOfChannels;a.push(k)}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)Gi(s,i.timestamp);else{const e=A(t,a.moofOffset-1,e=>e.moofOffset);if(-1!==e){const i=t[e];Gi(s,i.endTimestamp)}}s.startTimestampIsFinal=!0}const i=A(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 Zi(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;Y(t.languageCode)||(t.languageCode=V)}}break;case"hdlr":{const t=this.currentTrack;if(!t)break;e.skip(8);const i=Oo(e,4);"vide"===i?t.info={type:"video",width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:{...x},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=j,this.readContiguousBoxes(e.slice($,X.contentSize))}break;case"stsd":{const t=this.currentTrack;if(!t)break;if(null===t.info||t.sampleTable)break;const i=So(e);e.skip(3);const r=Bo(e);for(let a=0;a0&&(1===n?(e.skip(4),c=8*Bo(e),e.skip(8)):2===n&&(e.skip(4),l=No(e),o=Bo(e),e.skip(4),c=Bo(e),u=Bo(e),e.skip(8))),t.info.numberOfChannels=o,t.info.sampleRate=l,t.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,r+a.totalSize-e.filePos));const d="enca"===s?t.frmaCodecString:s;if(t.frmaCodecString=null,"mp4a"===d);else if("opus"===d)t.info.codec="opus",t.info.sampleRate=ni;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(ii.includes(d))t.info.codec="dts",t.info.dtsFormat=d;else if("twos"===d)8===c?t.info.codec="pcm-s8":16===c?t.info.codec=t.info.pcmLittleEndian?"pcm-s16":"pcm-s16be":(xe._warn(`Unsupported sample size ${c} for codec 'twos'.`),t.info.codec=null);else if("sowt"===d)8===c?t.info.codec="pcm-s8":16===c?t.info.codec="pcm-s16":(xe._warn(`Unsupported sample size ${c} for codec 'sowt'.`),t.info.codec=null);else if("raw "===d)t.info.codec="pcm-u8";else if("in24"===d)t.info.codec=t.info.pcmLittleEndian?"pcm-s24":"pcm-s24be";else if("in32"===d)t.info.codec=t.info.pcmLittleEndian?"pcm-s32":"pcm-s32be";else if("fl32"===d)t.info.codec=t.info.pcmLittleEndian?"pcm-f32":"pcm-f32be";else if("fl64"===d)t.info.codec=t.info.pcmLittleEndian?"pcm-f64":"pcm-f64be";else if("ipcm"===d){const e=t.info.pcmSampleSize;t.info.pcmLittleEndian?16===e?t.info.codec="pcm-s16":24===e?t.info.codec="pcm-s24":32===e?t.info.codec="pcm-s32":(xe._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":(xe._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":(xe._warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null):32===e?t.info.codec="pcm-f32be":64===e?t.info.codec="pcm-f64be":(xe._warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null)}else if("lpcm"===d&&null!==u){const e=c+7>>3,i=Boolean(1&u),r=Boolean(2&u),a=4&u?-1:0;c>0&&c<=64&&(i?32===c&&(t.info.codec=r?"pcm-f32be":"pcm-f32"):a&1<0?(t.encryptionInfo.defaultCryptByteBlock=r>>4,t.encryptionInfo.defaultSkipByteBlock=15&r):(t.encryptionInfo.defaultCryptByteBlock=0,t.encryptionInfo.defaultSkipByteBlock=0),t.encryptionInfo.defaultIsProtected=0!==So(e),t.encryptionInfo.defaultPerSampleIvSize=So(e),t.encryptionInfo.defaultKid=_(To(e,16)),t.encryptionInfo.defaultIsProtected&&0===t.encryptionInfo.defaultPerSampleIvSize){const i=So(e),r=new Uint8Array(16);r.set(To(e,i),0),t.encryptionInfo.defaultConstantIv=r}}break;case"avcC":{const t=this.currentTrack;if(!t)break;if(l(t.info),0===X.contentSize)break;t.info.codecDescription=To(e,X.contentSize)}break;case"hvcC":{const t=this.currentTrack;if(!t)break;if(l(t.info),0===X.contentSize)break;t.info.codecDescription=To(e,X.contentSize)}break;case"vpcC":{const t=this.currentTrack;if(!t)break;l("video"===t.info?.type),e.skip(4);const i=So(e),r=So(e),a=So(e),s=a>>4,n=a>>1&7,o=1&a,c=So(e),u=So(e),d=So(e);t.info.vp9CodecInfo={profile:i,level:r,bitDepth:s,chromaSubsampling:n,videoFullRangeFlag:o,colourPrimaries:c,transferCharacteristics:u,matrixCoefficients:d}}break;case"av1C":{const t=this.currentTrack;if(!t)break;l("video"===t.info?.type),e.skip(1);const i=So(e),r=i>>5,a=31&i,s=So(e),n=s>>7,o=s>>6&1,c=s>>4&1,u=s>>3&1,d=s>>2&1,h=3&s,f=2===r&&o?s>>5&1?12:10:o?10:8;e.skip(1);const m=To(e,X.contentSize-4),p=wt(m);t.info.av1CodecInfo={profile:r,level:a,tier:n,bitDepth:f,monochrome:c,chromaSubsamplingX:u,chromaSubsamplingY:d,chromaSamplePosition:h,videoFullRangeFlag:p?.videoFullRangeFlag??0,colourPrimaries:p?.colourPrimaries??2,transferCharacteristics:p?.transferCharacteristics??2,matrixCoefficients:p?.matrixCoefficients??2}}break;case"colr":{const t=this.currentTrack;if(!t)break;l("video"===t.info?.type);const i=Oo(e,4);if("nclx"!==i&&"nclc"!==i)break;const r=Po(e),a=Po(e),s=Po(e);let n;"nclx"===i&&(n=Boolean(128&So(e))),t.info.colorSpace={primaries:w[r],transfer:S[a],matrix:P[s],fullRange:n}}break;case"pasp":{const t=this.currentTrack;if(!t)break;l("video"===t.info?.type);const i=Bo(e),r=Bo(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);l(3===So(e)),Bi(e),e.skip(2);const i=So(e),r=0!==(64&i),a=0!==(32&i);if(0!==(128&i)&&e.skip(2),r){const t=So(e);e.skip(t)}a&&e.skip(2);l(4===So(e));const s=Bi(e),n=e.filePos,o=So(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":xe._warn(`Unsupported audio codec (objectTypeIndication ${o}) - discarding track.`),e.skip(12),s>e.filePos-n){l(5===So(e));const i=Bi(e);if(t.info.codecDescription=To(e,i),"aac"===t.info.codec){const e=Ae(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;l("audio"===t.info?.type),t.info.pcmLittleEndian=!!(255&Po(e))}break;case"pcmC":{const t=this.currentTrack;if(!t)break;l("audio"===t.info?.type),e.skip(4);const i=So(e);t.info.pcmLittleEndian=Boolean(1&i),t.info.pcmSampleSize=So(e)}break;case"dOps":{const t=this.currentTrack;if(!t)break;l("audio"===t.info?.type),e.skip(1);const i=So(e),r=Po(e),a=Bo(e),s=xo(e),n=So(e);let o;o=0!==n?To(e,2+i):new Uint8Array(0);const c=new Uint8Array(19+o.byteLength),u=new DataView(c.buffer);u.setUint32(0,1332770163,!1),u.setUint32(4,1214603620,!1),u.setUint8(8,1),u.setUint8(9,i),u.setUint16(10,r,!0),u.setUint32(12,a,!0),u.setInt16(16,s,!0),u.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;l("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=To(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;l("audio"===t.info?.type);const i=To(e,3),r=new _e(i),a=r.readBits(2);r.skipBits(8);const s=r.readBits(3),n=r.readBits(1);a<3&&(t.info.sampleRate=Ne[a]),t.info.numberOfChannels=Bt[s]+n}break;case"dec3":{const t=this.currentTrack;if(!t)break;l("audio"===t.info?.type);const i=(e=>{if(e.length<2)return null;const t=new _e(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}})(To(e,X.contentSize));if(!i){xe._warn("Invalid dec3 box contents, ignoring.");break}const r=At(i);null!==r&&(t.info.sampleRate=r),t.info.numberOfChannels=Dt(i)}break;case"ddts":{const t=this.currentTrack;if(!t)break;l("audio"===t.info?.type);const i=(e=>{if(e.length<20)return null;const t=g(e),i=t.getUint32(0);if(0===i)return null;const r=new _e(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=Xt(o):ne.id===i);if(!r)break;const a=Bo(e),s=(12&a)>>2,n=3&a,o=[So,Po,Io,Bo],c=o[(48&a)>>4],l=o[s],u=o[n],d=Bo(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 a=0;ae.id===u);if(!d)break;const h=this.fragmentTrackDefaults.find(e=>e.trackId===u);this.currentTrack=d,d.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?d.currentFragmentState.baseDataOffset=Fo(e):c&&(d.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),r&&(d.currentFragmentState.sampleDescriptionIndex=Bo(e)),a&&(d.currentFragmentState.defaultSampleDuration=Bo(e)),s&&(d.currentFragmentState.defaultSampleSize=Bo(e)),n&&(d.currentFragmentState.defaultSampleFlags=Bo(e)),o&&(d.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{const t=this.currentTrack;if(!t)break;l(t.currentFragmentState);const i=So(e);e.skip(3);const r=0===i?Bo(e):Fo(e);t.currentFragmentState.startTimestamp=r}break;case"trun":{const t=this.currentTrack;if(!t)break;l(this.currentFragment),l(t.currentFragmentState);const i=So(e),r=Io(e),a=Boolean(1&r),s=Boolean(4&r),n=Boolean(256&r),o=Boolean(512&r),c=Boolean(1024&r),u=Boolean(2048&r),d=Bo(e);let h=null;a&&(h=_o(e));let f,m=null;s&&(m=Bo(e)),this.currentFragment.trackData.has(t.id)?(f=this.currentFragment.trackData.get(t.id),null!==h&&(f.currentOffset=t.currentFragmentState.baseDataOffset+h)):(f={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,f));for(let p=0;p0&&(a=To(e,r));const s=Ji(t);s.defaultSampleInfoSize=i,s.sampleSizes=a,s.sampleCount=r}break;case"saio":{const t=this.currentTrack;if(!t||!t.encryptionInfo)break;const i=So(e);if(1&Io(e)){const i=Oo(e,4),r=Bo(e);if(i!==t.encryptionInfo.scheme||0!==r)break}const r=Bo(e);if(0===r)break;r>1&&xe._warn("Multiple saio entries are not supported; using the first offset only.");let a=0===i?Bo(e):Number(Fo(e));this.currentFragment&&(a+=this.currentFragment.moofOffset);Ji(t).offset=a}break;case"senc":{const t=this.currentTrack;if(!t||!t.encryptionInfo)break;l(this.currentFragment);const i=this.currentFragment.trackData.get(t.id);if(!i)break;e.skip(1);const r=Io(e),a=Boolean(2&r),s=Bo(e),n=t.encryptionInfo.defaultPerSampleIvSize;l(null!==n);for(let o=0;o0?r.set(To(e,n),0):r.set(t.encryptionInfo.defaultConstantIv,0);let s=null;if(a){const t=Po(e);s=[];for(let i=0;i0&&((L=this.metadataTags).trackNumber??(L.trackNumber=t)),i&&Number.isInteger(i)&&i>0&&((z=this.metadataTags).tracksTotal??(z.tracksTotal=i))}break;case"trkn":if(a instanceof Uint8Array&&a.length>=6){const e=g(a),t=e.getUint16(2,!1),i=e.getUint16(4,!1);t>0&&((U=this.metadataTags).trackNumber??(U.trackNumber=t)),i>0&&((q=this.metadataTags).tracksTotal??(q.tracksTotal=i))}break;case"disc":case"disk":if(a instanceof Uint8Array&&a.length>=6){const e=g(a),t=e.getUint16(2,!1),i=e.getUint16(4,!1);t>0&&((W=this.metadataTags).discNumber??(W.discNumber=t)),i>0&&((H=this.metadataTags).discsTotal??(H.discsTotal=i))}}}}}return e.filePos=G,!0}}class Wi{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;l(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 j(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,t){const i=this.mapTimestampIntoTimescale(e),r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=ji(r,i),s=await this.fetchPacketForSampleIndex(a,t);return Yi(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=A(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=L(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 l(-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=Xi(i,e);if(!r)return null;let a;if(t.metadataOnly)a=Ti;else{let t=this.internalTrack.demuxer.reader.requestSlice(r.sampleOffset,r.sampleSize);if(de(t)&&(t=await t),!t)return null;if(a=To(t,r.sampleSize),this.internalTrack.encryptionInfo){let t=null;if(this.internalTrack.encryptionAuxInfo){const i=await Zi(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);ee.timestamp),d=-1!==u?this.internalTrack.fragmentLookupTable[u]:null,h=A(this.internalTrack.fragmentPositionCache,i,e=>e.startTimestamp),f=-1!==h?this.internalTrack.fragmentPositionCache[h]:null,m=Math.max(d?.moofOffset??0,f?.moofOffset??0)||null;let p;for(e?null===m||e.moofOffset>=m?(p=e.moofOffset+e.moofSize,n=e):p=m:p=m??0;;){if(n){const e=n.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>r)break}let e=s.reader.requestSliceRange(p,8,16);if(de(e)&&(e=await e),!e)break;const i=p,l=Ii(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)}p=i+l.totalSize}if(d&&(!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&&Tt(e.data)}}else{const e=await this.getFirstPacket({}),t=e&&wt(e.data);t&&(this.internalTrack.info.av1CodecInfo=t)}else{const e=await this.getFirstPacket({}),t=e&&yt(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&&nt(e.data)}else{const e=await this.getFirstPacket({});this.internalTrack.info.avcCodecInfo=e&&Qe(e.data)}if(!I(this.internalTrack.info.colorSpace)){const a=ai(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:ri(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 Vi extends Wi{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&&Vt(e.data)}return{codec:si(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}})()):null}}const ji=(e,t)=>{if(e.presentationTimestamps){const i=A(e.presentationTimestamps,t,e=>e.presentationTimestamp);return-1===i?-1:e.presentationTimestamps[i].sampleIndex}{const i=A(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)}},Ki=(e,t)=>{if(!e.keySampleIndices)return ji(e,t);if(e.presentationTimestamps){const i=A(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!==F(e.keySampleIndices,i,e=>e))return i}return-1}{const i=ji(e,t),r=A(e.keySampleIndices,i,e=>e);return e.keySampleIndices[r]??-1}},Xi=(e,t)=>{const i=A(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=A(e.sampleCompositionTimeOffsets,t,e=>e.startIndex),n=e.sampleCompositionTimeOffsets[s];n&&t-n.startIndexe.startSampleIndex),u=e.sampleToChunk[c];l(u);const d=u.startChunkIndex+Math.floor((t-u.startSampleIndex)/u.samplesPerChunk),h=e.chunkOffsets[d],f=u.startSampleIndex+(d-u.startChunkIndex)*u.samplesPerChunk;let m=0,p=h;if(1===e.sampleSizes.length)p+=o*(t-f),m+=o*u.samplesPerChunk;else for(let l=f;le)}},$i=(e,t)=>{if(!e.keySampleIndices)return t+1;const i=A(e.keySampleIndices,t,e=>e);return e.keySampleIndices[i+1]??-1},Gi=(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},Qi=e=>{const[t,i]=e,r=Math.atan2(i,t);return Number.isFinite(r)?r*(180/Math.PI):0},Yi=e=>0===e.sampleSizes.length,Ji=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})},Zi=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{l(i.sampleSizes);for(let e=0;e0?i.defaultSampleInfoSize:i.sampleSizes[o],r=new Uint8Array(16);s>0?r.set(To(a,s),0):r.set(t.defaultConstantIv,0);let c=null;if(e>s){const e=Po(a);c=[];for(let t=0;te.defaultConstantIv?{iv:e.defaultConstantIv,subsamples:null}:null,tr=async(e,t,i,r)=>{l(e.encryptionInfo);const a=e.encryptionInfo;l(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{l(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);l(null!==t.defaultCryptByteBlock&&null!==t.defaultSkipByteBlock);const o=ar(i.subsamples,t.defaultCryptByteBlock,t.defaultSkipByteBlock);let c=0;for(const l of o)for(const e of l.perSubsample)c+=e.length;const u=new Uint8Array(c);let d=0;for(const l of o)for(const e of l.perSubsample)u.set(r.subarray(e.offset,e.offset+e.length),d),d+=e.length;const h=await n(u),f=new Uint8Array(r);let m=0;for(const l of o)for(const e of l.perSubsample)f.set(h.subarray(m,m+e.length),e.offset),m+=e.length;return f},rr=(e,t,i,r)=>{const a=new Ui;a.init({key:e,iv:i.iv});const s=t.defaultCryptByteBlock,n=t.defaultSkipByteBlock;if(l(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 sr,nr;(nr=sr||(sr={}))[nr.EBML=440786851]="EBML",nr[nr.EBMLVersion=17030]="EBMLVersion",nr[nr.EBMLReadVersion=17143]="EBMLReadVersion",nr[nr.EBMLMaxIDLength=17138]="EBMLMaxIDLength",nr[nr.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",nr[nr.DocType=17026]="DocType",nr[nr.DocTypeVersion=17031]="DocTypeVersion",nr[nr.DocTypeReadVersion=17029]="DocTypeReadVersion",nr[nr.Void=236]="Void",nr[nr.Segment=408125543]="Segment",nr[nr.SeekHead=290298740]="SeekHead",nr[nr.Seek=19899]="Seek",nr[nr.SeekID=21419]="SeekID",nr[nr.SeekPosition=21420]="SeekPosition",nr[nr.Duration=17545]="Duration",nr[nr.Info=357149030]="Info",nr[nr.TimestampScale=2807729]="TimestampScale",nr[nr.MuxingApp=19840]="MuxingApp",nr[nr.WritingApp=22337]="WritingApp",nr[nr.Tracks=374648427]="Tracks",nr[nr.TrackEntry=174]="TrackEntry",nr[nr.TrackNumber=215]="TrackNumber",nr[nr.TrackUID=29637]="TrackUID",nr[nr.TrackType=131]="TrackType",nr[nr.FlagEnabled=185]="FlagEnabled",nr[nr.FlagDefault=136]="FlagDefault",nr[nr.FlagForced=21930]="FlagForced",nr[nr.FlagOriginal=21934]="FlagOriginal",nr[nr.FlagHearingImpaired=21931]="FlagHearingImpaired",nr[nr.FlagVisualImpaired=21932]="FlagVisualImpaired",nr[nr.FlagCommentary=21935]="FlagCommentary",nr[nr.FlagLacing=156]="FlagLacing",nr[nr.Name=21358]="Name",nr[nr.Language=2274716]="Language",nr[nr.LanguageBCP47=2274717]="LanguageBCP47",nr[nr.CodecID=134]="CodecID",nr[nr.CodecPrivate=25506]="CodecPrivate",nr[nr.CodecDelay=22186]="CodecDelay",nr[nr.SeekPreRoll=22203]="SeekPreRoll",nr[nr.DefaultDuration=2352003]="DefaultDuration",nr[nr.Video=224]="Video",nr[nr.PixelWidth=176]="PixelWidth",nr[nr.PixelHeight=186]="PixelHeight",nr[nr.DisplayWidth=21680]="DisplayWidth",nr[nr.DisplayHeight=21690]="DisplayHeight",nr[nr.DisplayUnit=21682]="DisplayUnit",nr[nr.AlphaMode=21440]="AlphaMode",nr[nr.Audio=225]="Audio",nr[nr.SamplingFrequency=181]="SamplingFrequency",nr[nr.Channels=159]="Channels",nr[nr.BitDepth=25188]="BitDepth",nr[nr.SimpleBlock=163]="SimpleBlock",nr[nr.BlockGroup=160]="BlockGroup",nr[nr.Block=161]="Block",nr[nr.BlockAdditions=30113]="BlockAdditions",nr[nr.BlockMore=166]="BlockMore",nr[nr.BlockAdditional=165]="BlockAdditional",nr[nr.BlockAddID=238]="BlockAddID",nr[nr.BlockDuration=155]="BlockDuration",nr[nr.ReferenceBlock=251]="ReferenceBlock",nr[nr.Cluster=524531317]="Cluster",nr[nr.Timestamp=231]="Timestamp",nr[nr.Cues=475249515]="Cues",nr[nr.CuePoint=187]="CuePoint",nr[nr.CueTime=179]="CueTime",nr[nr.CueTrackPositions=183]="CueTrackPositions",nr[nr.CueTrack=247]="CueTrack",nr[nr.CueClusterPosition=241]="CueClusterPosition",nr[nr.Colour=21936]="Colour",nr[nr.MatrixCoefficients=21937]="MatrixCoefficients",nr[nr.TransferCharacteristics=21946]="TransferCharacteristics",nr[nr.Primaries=21947]="Primaries",nr[nr.Range=21945]="Range",nr[nr.Projection=30320]="Projection",nr[nr.ProjectionType=30321]="ProjectionType",nr[nr.ProjectionPoseRoll=30325]="ProjectionPoseRoll",nr[nr.Attachments=423732329]="Attachments",nr[nr.AttachedFile=24999]="AttachedFile",nr[nr.FileDescription=18046]="FileDescription",nr[nr.FileName=18030]="FileName",nr[nr.FileMediaType=18016]="FileMediaType",nr[nr.FileData=18012]="FileData",nr[nr.FileUID=18094]="FileUID",nr[nr.Chapters=272869232]="Chapters",nr[nr.Tags=307544935]="Tags",nr[nr.Tag=29555]="Tag",nr[nr.Targets=25536]="Targets",nr[nr.TargetTypeValue=26826]="TargetTypeValue",nr[nr.TargetType=25546]="TargetType",nr[nr.TagTrackUID=25541]="TagTrackUID",nr[nr.TagEditionUID=25545]="TagEditionUID",nr[nr.TagChapterUID=25540]="TagChapterUID",nr[nr.TagAttachmentUID=25542]="TagAttachmentUID",nr[nr.SimpleTag=26568]="SimpleTag",nr[nr.TagName=17827]="TagName",nr[nr.TagLanguage=17530]="TagLanguage",nr[nr.TagString=17543]="TagString",nr[nr.TagBinary=17541]="TagBinary",nr[nr.ContentEncodings=28032]="ContentEncodings",nr[nr.ContentEncoding=25152]="ContentEncoding",nr[nr.ContentEncodingOrder=20529]="ContentEncodingOrder",nr[nr.ContentEncodingScope=20530]="ContentEncodingScope",nr[nr.ContentCompression=20532]="ContentCompression",nr[nr.ContentCompAlgo=16980]="ContentCompAlgo",nr[nr.ContentCompSettings=16981]="ContentCompSettings",nr[nr.ContentEncryption=20533]="ContentEncryption";const or=[sr.EBML,sr.Segment],cr=[sr.SeekHead,sr.Info,sr.Cluster,sr.Tracks,sr.Cues,sr.Attachments,sr.Chapters,sr.Tags],lr=[...or,...cr],ur=16,dr=e=>{if(e.remainingLength<1)return null;const t=So(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=So(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=dr(e);if(null===t)return null;if(e.remainingLength{if(e.remainingLength<1)return null;if(255===So(e))return;e.skip(-1);const t=hr(e);return null===t?null:72057594037927940!==t?t:void 0},gr=e=>{l(e.remainingLength>=2);const t=mr(e);if(null===t)return null;const i=pr(e);return null===i?null:{id:t,size:i}},kr=(e,t)=>{const i=To(e,t);let r=0;for(;r{const i=To(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?Mo(e):No(e)},wr=async(e,t,i,r)=>{const a=new Set(i);let s=t;for(;null===r||ss?r:s,found:!1}},Tr=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,ur);if(de(t)&&(t=await t),!t)break;const i=gr(t);if(!i)break;const r=i.id;let a=i.size;const s=t.filePos;if(r===sr.EBML){Nr(a);let e=this.reader.requestSlice(s,a);if(de(e)&&(e=await e),!e)break;this.readContiguousElements(e)}else if(r===sr.Segment){if(await this.readSegment(s,a),void 0===a)break;if(null===this.reader.fileSize)break}else if(r===sr.Cluster){if(null===this.reader.fileSize)break;if(void 0===a){a=(await wr(this.reader,s,lr,this.reader.fileSize)).pos-s}const e=d(this.segments);e&&(e.elementEndPos=s+a)}Nr(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=Hr[o].flag;this.currentSegment[e]=!0,Nr(s);let t=this.reader.requestSlice(n,s);de(t)&&(t=await t),t&&this.readContiguousElements(t)}else if(a===sr.Tags||a===sr.Attachments){a===sr.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,Nr(s);let e=this.reader.requestSlice(n,s);de(e)&&(e=await e),e&&this.readContiguousElements(e)}else if(a===sr.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=Hr.find(e=>e.id===n.id);if(!t)continue;if(this.currentSegment[t.flag])continue;let i=this.reader.requestSliceRange(e+n.segmentPosition,2,ur);if(de(i)&&(i=await i),!i)continue;const r=gr(i);if(!r)continue;const{id:a,size:s}=r;if(a!==t.id)continue;Nr(s),this.currentSegment[t.flag]=!0;let o=this.reader.requestSlice(i.filePos,s);de(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,ur);de(i)&&(i=await i),l(i);const r=e,a=gr(i);l(a);l(a.id===sr.Cluster);let s=a.size;const n=i.filePos;if(void 0===s){s=(await wr(this.reader,n,lr,t.elementEndPos)).pos-n}let o=this.reader.requestSlice(n,s);de(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,lr);c.elementEndPos=e}for(const[,u]of c.trackData){const e=u.track;l(u.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=u.blocks[u.presentationTimestamps[0].blockIndex],a=u.blocks[d(u.presentationTimestamps).blockIndex];u.startTimestamp=i.timestamp,u.endTimestamp=a.timestamp+a.duration;const s=A(e.clusterPositionCache,u.startTimestamp,e=>e.startTimestamp);-1!==s&&e.clusterPositionCache[s].elementStartPos===r||e.clusterPositionCache.splice(s+1,0,{elementStartPos:c.elementStartPos,startTimestamp:u.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=gr(e);if(!i)return!1;if(t&&t.includes(i.id))return!1;const{id:r,size:a}=i,s=e.filePos;switch(Nr(a),r){case sr.DocType:this.isWebM="webm"===kr(e,a);break;case sr.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 sr.SeekID:{const t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.id=fr(e,a)}break;case sr.SeekPosition:{const t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.segmentPosition=fr(e,a)}break;case sr.TimestampScale:if(!this.currentSegment)break;this.currentSegment.timestampScale=fr(e,a),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale;break;case sr.Duration:if(!this.currentSegment)break;this.currentSegment.duration=br(e,a);break;case sr.TrackEntry:if(!this.currentSegment)break;if(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...Ee,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!==zr.Block||e.data.algorithm!==qr.HeaderStripping)&&(xe._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===Sr)this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(this.currentTrack.codecId===vr)this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(t===Pr)this.currentTrack.info.codec="vp8";else if(t===Ir)this.currentTrack.info.codec="vp9";else if(t===xr)this.currentTrack.info.codec="av1";else if(t===Cr){const e=this.currentTrack.codecPrivate?k.decode(this.currentTrack.codecPrivate):"";ti.includes(e)&&(this.currentTrack.info.codec="prores",this.currentTrack.info.proresFormat=e)}const e=this.currentTrack;this.currentTrack.trackBacking=new Xr(e),this.currentSegment.tracks.push(this.currentTrack)}else if("audio"===this.currentTrack.info.type){t===Br?(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===Er?this.currentTrack.info.codec="mp3":t===_r?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=ni):t===Rr?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Fr?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Ar?(this.currentTrack.info.codec="ac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Dr?(this.currentTrack.info.codec="eac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Mr?(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 $r(e),this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null;break;case sr.TrackNumber:if(!this.currentTrack)break;this.currentTrack.id=fr(e,a);break;case sr.TrackType:{if(!this.currentTrack)break;const t=fr(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:{...x},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 sr.FlagEnabled:if(!this.currentTrack)break;fr(e,a)||(this.currentTrack=null);break;case sr.FlagDefault:if(!this.currentTrack)break;this.currentTrack.disposition.default=!!fr(e,a);break;case sr.FlagForced:if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!fr(e,a);break;case sr.FlagOriginal:if(!this.currentTrack)break;this.currentTrack.disposition.original=!!fr(e,a);break;case sr.FlagHearingImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!fr(e,a);break;case sr.FlagVisualImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!fr(e,a);break;case sr.FlagCommentary:if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!fr(e,a);break;case sr.CodecID:if(!this.currentTrack)break;this.currentTrack.codecId=kr(e,a);break;case sr.CodecPrivate:if(!this.currentTrack)break;this.currentTrack.codecPrivate=To(e,a);break;case sr.DefaultDuration:if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=fr(e,a);break;case sr.Name:if(!this.currentTrack)break;this.currentTrack.name=yr(e,a);break;case sr.Language:if(!this.currentTrack)break;if(this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=kr(e,a),Y(this.currentTrack.languageCode)||(this.currentTrack.languageCode=V);break;case sr.LanguageBCP47:{if(!this.currentTrack)break;const t=kr(e,a).split("-")[0];this.currentTrack.languageCode=t||V,this.currentTrack.hasLanguageBcp47=!0}break;case sr.Video:if("video"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(s,a));break;case sr.PixelWidth:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.width=fr(e,a);break;case sr.PixelHeight:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.height=fr(e,a);break;case sr.DisplayWidth:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.displayWidth=fr(e,a);break;case sr.DisplayHeight:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.displayHeight=fr(e,a);break;case sr.DisplayUnit:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.displayUnit=fr(e,a);break;case sr.AlphaMode:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.alphaMode=1===fr(e,a);break;case sr.Colour:if("video"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(s,a));break;case sr.MatrixCoefficients:{if("video"!==this.currentTrack?.info?.type)break;const t=fr(e,a),i=P[t];this.currentTrack.info.colorSpace.matrix=i}break;case sr.Range:{if("video"!==this.currentTrack?.info?.type)break;const t=fr(e,a);this.currentTrack.info.colorSpace.fullRange=1===t||2===t?2===t:void 0}break;case sr.TransferCharacteristics:{if("video"!==this.currentTrack?.info?.type)break;const t=fr(e,a),i=S[t];this.currentTrack.info.colorSpace.transfer=i}break;case sr.Primaries:{if("video"!==this.currentTrack?.info?.type)break;const t=fr(e,a),i=w[t];this.currentTrack.info.colorSpace.primaries=i}break;case sr.Projection:if("video"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(s,a));break;case sr.ProjectionPoseRoll:{if("video"!==this.currentTrack?.info?.type)break;const t=-br(e,a);try{this.currentTrack.info.rotation=u(t)}catch{}}break;case sr.Audio:if("audio"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(s,a));break;case sr.SamplingFrequency:if("audio"!==this.currentTrack?.info?.type)break;this.currentTrack.info.sampleRate=br(e,a);break;case sr.Channels:if("audio"!==this.currentTrack?.info?.type)break;this.currentTrack.info.numberOfChannels=fr(e,a);break;case sr.BitDepth:if("audio"!==this.currentTrack?.info?.type)break;this.currentTrack.info.bitDepth=fr(e,a);break;case sr.CuePoint:if(!this.currentSegment)break;this.readContiguousElements(e.slice(s,a)),this.currentCueTime=null;break;case sr.CueTime:this.currentCueTime=fr(e,a);break;case sr.CueTrackPositions:{if(null===this.currentCueTime)break;l(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 sr.CueTrack:{const t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;t.trackId=fr(e,a)}break;case sr.CueClusterPosition:{const t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;l(this.currentSegment),t.clusterPosition=this.currentSegment.dataStartPos+fr(e,a)}break;case sr.Timestamp:if(!this.currentCluster)break;this.currentCluster.timestamp=fr(e,a);break;case sr.SimpleBlock:{if(!this.currentCluster)break;const t=hr(e);if(null===t)break;const i=this.getTrackDataInCluster(this.currentCluster,t);if(!i)break;const r=xo(e),n=So(e),o=n>>1&3;let c=!!(128&n);"audio"===i.track.info?.type&&i.track.info.codec&&(c=!0);const l=To(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 sr.BlockGroup:if(!this.currentCluster)break;this.readContiguousElements(e.slice(s,a)),this.currentBlock=null;break;case sr.Block:{if(!this.currentCluster)break;const t=hr(e);if(null===t)break;const i=this.getTrackDataInCluster(this.currentCluster,t);if(!i)break;const r=xo(e),n=So(e)>>1&3,o=To(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 sr.BlockAdditions:this.readContiguousElements(e.slice(s,a));break;case sr.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 sr.BlockAdditional:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=To(e,a);break;case sr.BlockAddID:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=fr(e,a);break;case sr.BlockDuration:if(!this.currentBlock)break;this.currentBlock.duration=fr(e,a);break;case sr.ReferenceBlock:if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1;break;case sr.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(s,a));break;case sr.Targets:this.readContiguousElements(e.slice(s,a));break;case sr.TargetTypeValue:50!==fr(e,a)&&(this.currentTagTargetIsMovie=!1);break;case sr.TagTrackUID:case sr.TagEditionUID:case sr.TagChapterUID:case sr.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case sr.SimpleTag:if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(s,a));break;case sr.TagName:this.currentSimpleTagName=yr(e,a);break;case sr.TagString:{if(!this.currentSimpleTagName)break;const t=yr(e,a);this.processTagValue(this.currentSimpleTagName,t)}break;case sr.TagBinary:{if(!this.currentSimpleTagName)break;const t=To(e,a);this.processTagValue(this.currentSimpleTagName,t)}break;case sr.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 Be(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 sr.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 sr.ContentEncoding:this.currentDecodingInstruction={order:0,scope:zr.Block,data:null},this.readContiguousElements(e.slice(s,a)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case sr.ContentEncodingOrder:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=fr(e,a);break;case sr.ContentEncodingScope:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=fr(e,a);break;case sr.ContentCompression:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:qr.Zlib,settings:null},this.readContiguousElements(e.slice(s,a));break;case sr.ContentCompAlgo:if("decompress"!==this.currentDecodingInstruction?.data?.type)break;this.currentDecodingInstruction.data.algorithm=fr(e,a);break;case sr.ContentCompSettings:if("decompress"!==this.currentDecodingInstruction?.data?.type)break;this.currentDecodingInstruction.data.settings=To(e,a);break;case sr.ContentEncryption:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}return e.filePos=s+a,!0}decodeBlockData(e,t){l(e.decodingInstructions.length>0);let i=t;for(const r of e.decodingInstructions)if(l(r.data),"decompress"===r.data.type)if(r.data.algorithm===qr.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){l(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 Kr{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 j(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=A(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=L(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 l(-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(l(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);g(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?Ti: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?Ti:r.mainAdditional,o.alphaByteLength=r.mainAdditional.byteLength);const c=new Si(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,u=-1;if(e){const{blockIndex:i,correctBlockFound:r}=t(e);if(r)return this.fetchPacketInCluster(e,i,a);-1!==i&&(c=e,u=i)}const d=A(this.internalTrack.cuePoints,i,e=>e.time),h=-1!==d?this.internalTrack.cuePoints[d]:null,f=A(this.internalTrack.clusterPositionCache,i,e=>e.startTimestamp),m=-1!==f?this.internalTrack.clusterPositionCache[f]:null,p=Math.max(h?.clusterPosition??0,m?.elementStartPos??0)||null;let g;for(e?null===p||e.elementStartPos>=p?(g=e.elementEndPos,o=e):g=p:g=p??n.clusterSeekStartPos;null===n.elementEndPos||g<=n.elementEndPos-2;){if(o){const e=o.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>r)break}let e=s.reader.requestSliceRange(g,2,ur);if(de(e)&&(e=await e),!e)break;const i=g,d=gr(e);if(!d||!cr.includes(d.id)&&d.id!==sr.Void){const e=await Tr(s.reader,i,cr,Math.min(n.elementEndPos??1/0,i+Vr));if(e){g=e;continue}break}const h=d.id;let f=d.size;const m=e.filePos;if(h===sr.Cluster){o=await s.readCluster(i,n),f=o.elementEndPos-m;const{blockIndex:e,correctBlockFound:r}=t(o);if(r)return this.fetchPacketInCluster(o,e,a);-1!==e&&(c=o,u=e)}if(void 0===f){l(h!==sr.Cluster);f=(await wr(s.reader,m,lr,n.elementEndPos)).pos-m}const p=m+f;if(null===n.elementEndPos){let e=s.reader.requestSliceRange(p,2,ur);if(de(e)&&(e=await e),!e)break;if(mr(e)===sr.Segment){n.elementEndPos=p;break}}g=p}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?Qe(a.data):null,hevcCodecInfo:"hevc"===this.internalTrack.info.codec&&a?nt(a.data):null,vp9CodecInfo:"vp9"===this.internalTrack.info.codec&&a?yt(a.data):null,av1CodecInfo:"av1"===this.internalTrack.info.codec&&a?wt(a.data):null,proresCodecInfo:"prores"===this.internalTrack.info.codec&&a?Tt(a.data):null,proresFormat:this.internalTrack.info.proresFormat};if(!I(this.internalTrack.info.colorSpace)){const a=ai(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:ri(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 $r extends Kr{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&&Vt(e.data)}return{codec:si({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 Gr=async(e,t,i,r=null)=>{let a=t;for(;null===i||a=4;){const t=s.filePos,i=Bo(s),n=null!==e.fileSize?e.fileSize-a:null,o=pi(i,n);if(o.header&&(!r||o.header.sampleRate===r.sampleRate&&o.header.mpegVersionId===r.mpegVersionId&&o.header.layer===r.layer&&bi(o.header.channel)===bi(r.channel)))return{header:o.header,startPos:a};s.filePos=t+o.bytesAdvanced,a=s.filePos}}return null};class Qr extends wi{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 B,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 Yr(this)]})())}async advanceReader(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,Vo);if(de(e)&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const t=$o(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}const e=await Gr(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=mi(t.mpegVersionId,t.channel);let r=this.reader.requestSlice(e.startPos+i,4);if(de(r)&&(r=await r),r){const a=Bo(r);if(a===hi||a===fi){if(this.xingFrameHeader||(this.xingFrameHeader=t,this.xingFrameHeaderPos=e.startPos),!this.xingData){let t=this.reader.requestSlice(e.startPos+i+4,12);if(de(t)&&(t=await t),t){const e=To(t,12),i=g(e),r=i.getUint32(0,!1);this.xingData={frameCount:r&ki.FrameCount?i.getUint32(4,!1):null,fileSize:r&ki.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,Vo);if(de(i)&&(i=await i),!i)break;const r=$o(i);if(!r)break;t=!0;let a=this.reader.requestSlice(i.filePos,r.size);if(de(a)&&(a=await a),!a)break;Go(a,r,this.metadataTags),e=i.filePos+r.size}if(!t&&null!==this.reader.fileSize&&this.reader.fileSize>=Ho){let e=this.reader.requestSlice(this.reader.fileSize-Ho,Ho);de(e)&&(e=await e),l(e);"TAG"===Oo(e,3)&&Ko(e,this.metadataTags)}return this.metadataTags}finally{e()}}}class Yr{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return l(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(l(null!==e.firstFrameHeader),l(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=A(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 ea=e=>{const t=g(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},ta=(e,t,i)=>{let r=0,a=null;if(e.length>0)if("vorbis"===t.codec){l(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:St[t]*r}})(e).durationInSamples}return{durationInSamples:r,vorbisBlockSize:a}},ia=27,ra=282,aa=e=>{const t=e.filePos;if(Eo(e)!==Jr)return null;e.skip(1);const i=So(e),r=Do(e),a=Eo(e),s=Eo(e),n=Eo(e),o=So(e),c=new Uint8Array(o);for(let d=0;de+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}},sa=(e,t)=>{for(;e.filePos>>8&255)===i||(t>>>16&255)===i||(t>>>24&255)===i){if(e.skip(-4),t===Jr)return!0;e.skip(1)}}return!1};class na extends wi{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,ia,ra);if(de(t)&&(t=await t),!t)break;const i=aa(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 oa(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=g(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:vt(a.data).modeBlockflags},Ct(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=g(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=ni,t.codecInfo.opusInfo={preSkip:a.preSkip},Ct(r.data.subarray(8),this.metadataTags)}async readPacket(e,t){l(te+t.length,0);if(0===o)return null;const c=new Uint8Array(o);let u=0;for(let l=0;l{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 oa{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new B,this.internalSampleRate="opus"===e.codecInfo.codec?ni:e.sampleRate}getType(){return"audio"}getId(){return this.bitstream.serialNumber}getNumber(){const e=this.demuxer.trackBackings.findIndex(e=>e.bitstream===this.bitstream);return l(-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 l(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 V}getDisposition(){return{...Ee,primary:!1}}granulePositionToTimestampInSamples(e){return"opus"===this.bitstream.codecInfo.codec?(l(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,i){if(!e)return null;const{durationInSamples:r,vorbisBlockSize:a}=ta(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),s=new Si(i.metadataOnly?Ti: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){l(this.bitstream.lastMetadataPacket);const t=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let i=0;"opus"===this.bitstream.codecInfo.codec&&(l(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=j(e*this.internalSampleRate);if(0===i)return this.getFirstPacket(t);if(i<0)return null;l(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=u.headerStartPos:(a=u,n.push(u));continue e}r=u.headerStartPos+u.totalSize}}let o=r.startPage;for(const l of n){if(l.granulePosition===a.granulePosition)break;(!o||l.headerStartPos>o.headerStartPos)&&(o=l)}let c=o;const u=[c];for(;c.serialNumber!==this.bitstream.serialNumber||c.granulePosition!==a.granulePosition;){const e=c.headerStartPos+c.totalSize;let t=this.demuxer.reader.requestSliceRange(e,ia,ra);de(t)&&(t=await t),l(t);const i=aa(t);l(i),c=i,c.serialNumber===this.bitstream.serialNumber&&u.push(c)}l(-1!==c.granulePosition);let d,h,f=null,m=c,p=0;if(c.headerStartPos===r.startPage.headerStartPos)d=this.granulePositionToTimestampInSamples(0),h=!0,f=0;else{d=0,h=!1;for(let t=c.lacingValues.length-1;t>=0;t--){if(c.lacingValues[t]<255){f=t+1;break}}if(null===f)throw new Error("Invalid page with granule position: no packets end on this page.");p=f-1;const e={data:Ti,endPage:m,endSegmentIndex:p};if(await this.demuxer.findNextPacketStart(e)){const e=la(u,c,f);l(e);const t=ca(u,e.page,e.segmentIndex);t&&(c=t.page,f=t.segmentIndex)}else for(;;){const e=la(u,c,f);if(!e)break;const t=ca(u,e.page,e.segmentIndex);if(!t)break;if(c=t.page,f=t.segmentIndex,e.page.headerStartPos!==m.headerStartPos){m=e.page,p=e.segmentIndex;break}}}let g=null,k=null;for(;null!==c;){l(null!==f);const e=await this.demuxer.readPacket(c,f);if(!e)break;if(!(c.headerStartPos===r.startPage.headerStartPos&&fi||Math.max(a.timestampInSamples,0)===i))break}const a=await this.demuxer.findNextPacketStart(e);if(!a)break;c=a.startPage,f=a.startSegmentIndex}return g}async getPacketSequential(e,t){const i=await this.sequentialScanMutex.acquire();try{const i=j(e*this.internalSampleRate);e=i/this.internalSampleRate;const r=A(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);l(e),this.sequentialScanCache.length>0&&l(d(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 ca=(e,t,i)=>{let r=t,a=i;e:for(;;){for(a--;a>=0;a--){if(r.lacingValues[a]<255){a++;break e}}l(-1===a);if(!(1&r.headerType)){a=0;break}const t=O(e,e=>e.headerStartPos{if(i>0)return{page:t,segmentIndex:i-1};const r=O(e,e=>e.headerStartPos{let e=this.reader.requestSlice(0,12);de(e)&&(e=await e),l(e);const t=Oo(e,4),i="RIFX"!==t,r="RF64"===t,a=Co(e,i);let s=r?this.reader.fileSize:Math.min(a+8,this.reader.fileSize??1/0);if("WAVE"!==Oo(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=vo(r,i),s=t-18;if(Math.min(s,e)>=22&&a===ua.EXTENSIBLE){r.skip(6);const e=To(r,16);a=e[0]|e[1]<<8}}if(a!==ua.MULAW&&a!==ua.ALAW||(c=8),a!==ua.PCM&&a!==ua.IEEE_FLOAT&&a!==ua.ALAW&&a!==ua.MULAW)throw new Error(`Unsupported WAVE codec (format tag ${a}). Only integer/float PCM, A-law, and \u03bc-law are supported.`);if(a===ua.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===ua.IEEE_FLOAT&&![32,64].includes(c))throw new Error(`Unsupported WAVE float bit depth (${c}). Only 32 and 64 bits are supported.`);this.audioInfo={format:a,numberOfChannels:s,sampleRate:n,sampleSizeInBytes:Math.ceil(c/8),blockSizeInBytes:o}}async parseListChunk(e,t,i){var r,a,s,n,o,c,l,u,d,h,f;let m=this.reader.requestSlice(e,t);if(de(m)&&(m=await m),!m)return;const p=Oo(m,4);if("INFO"!==p&&"INF0"!==p)return;let g=m.filePos;for(;g<=e+t-8;){m.filePos=g;const e=Oo(m,4),t=Co(m,i),p=To(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&&((d=this.metadataTags).date??(d.date=new Date(e,0,1)))}break;case"IGNR":case"GENR":(h=this.metadataTags).genre??(h.genre=y);break;case"ICMT":case"CMNT":case"COMM":(f=this.metadataTags).comment??(f.comment=y)}g+=8+t+(1&t)}}async parseId3Chunk(e,t){let i=this.reader.requestSlice(e,t);if(de(i)&&(i=await i),!i)return;const r=$o(i);if(r){const a=t-Vo;if(r.size=Math.min(r.size,a),r.size>0){const t=i.slice(e+Vo,r.size);Go(t,r,this.metadataTags)}}}getCodec(){if(l(this.audioInfo),this.audioInfo.format===ua.MULAW)return"ulaw";if(this.audioInfo.format===ua.ALAW)return"alaw";if(this.audioInfo.format===ua.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===ua.IEEE_FLOAT){if(4===this.audioInfo.sampleSizeInBytes)return"pcm-f32";if(8===this.audioInfo.sampleSizeInBytes)return"pcm-f64"}l(!1)}async getMimeType(){return"audio/wav"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}const fa=2048;class ma{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return l(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){const e=this.demuxer.getCodec();return e?(l(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null}getNumberOfChannels(){return l(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return l(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return l(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 l(-1!==this.demuxer.dataSize),this.demuxer.dataSize/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return V}getDisposition(){return{...Ee}}async getPacketAtIndex(e,t){l(e>=0),l(this.demuxer.audioInfo);const i=e*fa*this.demuxer.audioInfo.blockSizeInBytes;if(i>=this.demuxer.dataSize)return null;const r=Math.min(fa*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(de(e)&&(e=await e),!e)return null}let a;if(t.metadataOnly)a=Ti;else{let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+i,r);de(e)&&(e=await e),l(e),a=To(e,r)}const s=e*fa/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 Si(a,"key",s,n,e,r)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,t){l(this.demuxer.audioInfo);const i=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/fa,(this.demuxer.dataSize-1)/(fa*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;l(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){l(this.demuxer.audioInfo);const i=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/fa);return this.getPacketAtIndex(i+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const pa=e=>{const t=e.filePos,i=To(e,9),r=new _e(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}},ga=1024;class ka extends wi{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.trackBackings=[],this.readingMutex=new B,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();l(this.firstFrameHeader),this.trackBackings=[new ya(this)]})())}async advanceReader(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,Vo);if(de(e)&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const t=$o(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}let e=this.reader.requestSliceRange(this.lastLoadedPos,7,9);if(de(e)&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const t=pa(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=Re[t.samplingFrequencyIndex];l(void 0!==i);const r=ga/i,a={timestamp:this.nextTimestampInSamples/i,duration:r,dataStart:t.startPos,dataSize:t.frameLength};this.loadedSamples.push(a),this.nextTimestampInSamples+=ga,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,Vo);if(de(t)&&(t=await t),!t)break;const i=$o(t);if(!i)break;let r=this.reader.requestSlice(t.filePos,i.size);if(de(r)&&(r=await r),!r)break;Go(r,i,this.metadataTags),e=t.filePos+i.size}return this.metadataTags}finally{e()}}}class ya{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return this.getSampleRate()/ga}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 V}getCodec(){return"aac"}getInternalCodecId(){return l(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){l(this.demuxer.firstFrameHeader);const e=Fe[this.demuxer.firstFrameHeader.channelConfiguration];return l(void 0!==e),e}getSampleRate(){l(this.demuxer.firstFrameHeader);const e=Re[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return l(void 0!==e),e}getDisposition(){return{...Ee}}async getDecoderConfig(){return l(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=Ti;else{let e=this.demuxer.reader.requestSlice(i.dataStart,i.dataSize);if(de(e)&&(e=await e),!e)return null;r=To(e,i.dataSize)}return new Si(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=F(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=A(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,Vo);if(de(e)&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const i=$o(e);if(!i)break;let r=this.reader.requestSlice(e.filePos,i.size);de(r)&&(r=await r),l(r),Go(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===So(s)){const t=s.filePos;if(So(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=To(e,4),a=new _e(r);if(32764!==a.readBits(15))return null;if(null===this.blockingBit){l(t);const e=a.readBits(1);this.blockingBit=e}else if(1===this.blockingBit){l(!t);if(1!==a.readBits(1))return null}else{if(0!==this.blockingBit)throw new Error("Invalid blocking bit");l(!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;l(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 _e(To(e,1));for(;1===i.readBits(1);)t++;if(0===t)return i.readBits(7);const r=[],a=t-1,s=new _e(To(e,a)),n=8-t-1;for(let o=0;oe|t<"uncommon-u16"===t?Po(e)+1:"uncommon-u8"===t?So(e)+1:"number"===typeof t?t:(z(t),void l(!1)))(e,s),u=((e,t)=>"uncommon-u16"===t?Po(e):"uncommon-u16-10"===t?10*Po(e):"uncommon-u8"===t?So(e):"number"===typeof t?t:null)(e,n);if(null===u)return null;if(u!==this.audioInfo.sampleRate)return null;const d=e.filePos-i,h=So(e);e.skip(-d),e.skip(-1);const f=(e=>{let t=0;for(const i of e){t^=i;for(let e=0;e<8;e++)0!==(128&t)?t=t<<1^7:t<<=1,t&=255}return t})(To(e,d));return h!==f?null:{num:o,blockSize:c,sampleRate:u}}async advanceReader(){await this.readMetadata(),l(null!==this.lastLoadedPos),l(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 wa{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return l(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return l(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return V}getTimeResolution(){return l(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 l(this.demuxer.audioInfo),0===this.demuxer.audioInfo.totalSamples?null:this.demuxer.audioInfo.totalSamples/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getDisposition(){return{...Ee}}async getDecoderConfig(){return l(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(l(this.demuxer.audioInfo),e<0)return null;const i=await this.demuxer.readingMutex.acquire();try{for(;;){const i=A(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=Ti;else{let e=this.demuxer.reader.requestSlice(i.byteOffset,i.byteSize);if(de(e)&&(e=await e),!e)return null;r=To(e,i.byteSize)}l(this.demuxer.audioInfo);const a=i.blockOffset/this.demuxer.audioInfo.sampleRate,s=i.blockSize/this.demuxer.audioInfo.sampleRate;return new Si(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 Ta=9e4,Sa=2**33,va=188,Pa="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.",Ia=new Set([133,134,162]),xa=new Set;class Ca extends wi{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);de(e)&&(e=await e),l(e);const t=To(e,205);if(71===t[0]&&71===t[188])this.packetOffset=0,this.packetStride=va;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 _e(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=Ea(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 Da(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=Qe(r.suppliedPacket.data),!e.info.avcCodecInfo)continue;const t=e.info.avcCodecInfo.sequenceParameterSets[0];l(t);const i=et(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:w[i.colourPrimaries],transfer:S[i.transferCharacteristics],matrix:P[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=nt(r.suppliedPacket.data),!e.info.hevcCodecInfo)continue;const t=e.info.hevcCodecInfo.arrays.find(e=>e.nalUnitType===Ue.SPS_NUT).nalUnits[0];l(t);const i=st(t);e.info.width=i.displayWidth,e.info.height=i.displayHeight,i.pixelAspectRatio.num>i.pixelAspectRatio.den?(e.info.squarePixelWidth=Math.round(e.info.width*i.pixelAspectRatio.num/i.pixelAspectRatio.den),e.info.squarePixelHeight=e.info.height):(e.info.squarePixelWidth=e.info.width,e.info.squarePixelHeight=Math.round(e.info.height*i.pixelAspectRatio.den/i.pixelAspectRatio.num)),e.info.colorSpace={primaries:w[i.colourPrimaries],transfer:S[i.transferCharacteristics],matrix:P[i.matrixCoefficients],fullRange:!!i.fullRangeFlag},e.info.reorderSize=i.maxDecFrameBuffering;break}throw new Error("Unhandled.")}e.info.decoderConfig={codec:ri({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=bo.tempFromBytes(r.suppliedPacket.data),i=pa(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=Fe[i.channelConfiguration],e.info.sampleRate=Re[i.samplingFrequencyIndex]}else if("mp3"===e.info.codec){const t=Bo(bo.tempFromBytes(r.suppliedPacket.data)),i=pi(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=bi(i.header.channel),e.info.sampleRate=i.header.sampleRate}else if("ac3"===e.info.codec){const t=Et(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=Bt[t.acmod]+t.lfeon,e.info.sampleRate=Ne[t.fscod]}else if("eac3"===e.info.codec){const t=Ft(r.suppliedPacket.data);if(!t)throw new Error("Invalid E-AC-3 audio stream; could not read sync frame from first packet.");const i=At(t);if(null===i)throw new Error("Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.");e.info.numberOfChannels=Dt(t),e.info.sampleRate=i}else{if("dts"!==e.info.codec)throw new Error("Unhandled.");{const t=Ht(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:si({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 _e(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&&Ia.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:xa.has(t)||(xe._warn(`Note: MPEG-TS streams with stream_type 0x${t.toString(16)} are not currently supported.`),xa.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 _e(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 Ra(n)):this.trackBackingEntries.push(new Fa(n)))})())}async getTrackBackings(){return await this.readMetadata(),this.trackBackingEntries}async getMetadataTags(){return{}}async getMimeType(){await this.readMetadata();return(e=>{let t="video/MP2T";const i=[...new Set(e.filter(Boolean))];return i.length>0&&(t+=`; codecs="${i.join(", ")}"`),t})(await Promise.all(this.trackBackingEntries.map(e=>e.getDecoderConfig().then(e=>e?.codec??null))))}async readSection(e,t,i=!1){let r=e,a=e;const s=[];let n,o=0,c=null,l=!0,u=0;for(;;){const e=await this.readPacket(a);if(a+=this.packetStride,!e)break;if(c){if(e.pid!==c.pid){if(i)break;continue}if(1===e.payloadUnitStartIndicator)break}else{if(0===e.payloadUnitStartIndicator)break;c=e}const n=!!(2&e.adaptationFieldControl),d=!!(1&e.adaptationFieldControl);let h=0;if(n&&(h=1+e.body[0],e===c&&h>1&&(u=e.body[1]>>6&1)),d&&(0===h?(s.push(e.body),o+=e.body.byteLength):(s.push(e.body.subarray(h)),o+=e.body.byteLength-h)),r=a,!t&&o>=64){l=!1;break}if(-1!==F(this.sectionEndPositions,r,e=>e)){l=!1;break}}if(l){const e=A(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(de(t)&&(t=await t),!t)return null;if(71!==So(t))throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");const i=Po(t);return{payloadUnitStartIndicator:i>>14&1,pid:8191&i,adaptationFieldControl:So(t)>>4&3}}async readPacket(e){let t=this.reader.requestSlice(e,va);if(de(t)&&(t=await t),!t)return null;const i=To(t,va);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>=Sa-t?-8589934592:Sa}}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 _e(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(Pa);return{sectionStartPos:t.startPos,sectionEndPos:t.endPos,pts:n,randomAccessIndicator:t.randomAccessIndicator}},Ea=(e,t,i)=>{l(null!==t.endPos);const r=Ba(e,t,i);if(!r)return null;const a=new _e(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;l(Number.isInteger(c));const u=t.payload.subarray(c,s>0?6+s:t.payload.byteLength);return{...r,data:u}};class _a{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++,l(r instanceof _a),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 V}getDisposition(){return{...Ee,primary:!1}}getTimeResolution(){return Ta}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 Si(i.metadataOnly?Ti:e.data,r,e.pts/Ta,Math.max(t/Ta,0),e.sequenceNumber,e.data.byteLength)}async getFirstPacket(e){const t=this.elementaryStream.firstSection;l(t);const i=Ea(this.elementaryStream.demuxer,t,!0);l(i);const r=new Da(this.elementaryStream,i),a=new Ma(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);l(s);const n=Ea(a,s,!0);l(n);const o=new Da(this.elementaryStream,n);i=new Ma(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=j(e*Ta),a=this.elementaryStream.demuxer,{reader:s,seekChunkSize:n}=a,o=this.elementaryStream.pid,c=async(e,t,i)=>{let r=e;for(;re.pts),g=-1!==p?m[p]:null;if(g&&r-g.pts<45e3)f=g.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=$(t*n,a.packetStride)+h.sectionStartPos,l=o+n,u=await c(o,l,!1);u?u.pesPacketHeader.pts<=r?(e=t,i=t+1):s=t-1:s=t-1}}}f=$(e*n,a.packetStride)+h.sectionStartPos}const k=await c(f,s.fileSize??1/0,!1);let y=k?.pesPacketHeader??null;y||(y=h);const b=this.getReorderSize(),w=async(e,t)=>{const s=await a.readSection(e,!0);l(s);const n=Ea(a,s,!0);l(n);const o=new Da(this.elementaryStream,n),c=new Ma(this,o);for(;;){if((d(c.presentationOrderPackets)?.pts??-1/0)>=r)break;if(!(await c.readNextPacket()))break}const u=L(c.presentationOrderPackets,t);if(-1===u)return null;const h=c.presentationOrderPackets[u],f=0===u?0:h.pts-c.presentationOrderPackets[u-1].pts;for(;c.decodeOrderPackets[0]!==h;)c.decodeOrderPackets.shift();c.lastDuration=f;const m=await c.readNext();l(m);const p=this.createEncodedPacket(m.packet,m.duration,i);return this.packetBuffers.set(p,c),this.packetSectionStarts.set(p,m.packet.sectionStartPos),p};if(!t||this.allPacketsAreKeyPackets()){e:for(;;){let e=y.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=Ba(a,t,!1);if(e&&null!==e.pts){if(e.pts>r)break e;y=e,Aa(this.elementaryStream,y);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=Ba(a,t,!1);if(e&&null!==e.pts){y=e;break}}}e-=a.packetStride}}return w(y.sectionStartPos,e=>e.pts<=r)}{let e=f,t=null;const i=!this.elementaryStream.canBeTrustedWithKeyPackets;for(;;){let d=null;const f=e<=h.sectionStartPos;let m,p=null;if(f)m=h,p=u;else{const t=await c(e,s.fileSize??1/0,i);m=t?.pesPacketHeader??null,p=t?.section??null}let g=!1,k=0;e:for(;m&&!(null!==t&&m.sectionStartPos>=t);){if(m.pts<=r){let e;if(this.elementaryStream.canBeTrustedWithKeyPackets)e=1===m.randomAccessIndicator;else{l(p);const t=Ea(a,p,!0);l(t);const i=new Da(this.elementaryStream,t);await i.markNextPacket(),e=1===i.suppliedPacket?.randomAccessIndicator}e&&(d=m)}if(m.pts>r&&(g=!0),g&&(k++,k>b))break;let e=m.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=Ba(a,t,!1);if(e&&null!==e.pts){m=e,p=t,Aa(this.elementaryStream,m);break}}}e+=a.packetStride}}if(d){let e=d;if(0===k)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=Ba(a,r,!1);if(t&&null!==t.pts){e=t;break}}}t-=a.packetStride}}const t=await w(e.sectionStartPos,e=>e.pts<=r&&1===e.randomAccessIndicator);return l(t),t}if(f)return null;t=e,e=Math.max($(e-h.sectionStartPos-n,a.packetStride)+h.sectionStartPos,h.sectionStartPos)}}}}class Ra extends _a{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 l(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}}class Fa extends _a{getType(){return"audio"}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}async getDecoderConfig(){return l(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 0}}const Aa=(e,t)=>{const i=e.referencePesPackets,r=A(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 l(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 d=c[u+1],f=c[u+2],m=c[u+3];let p=0;if(0===d&&0===f&&1===m?p=4:0===d&&1===f&&(p=3),0===p){u++;continue}const g=i;a??(a=g);const k=u+p,y=k+r,b=6;if(y+("avc"===t?b:1)>l){this.seekTo(i);break}const w=c[k];let T,S,v;if("avc"===t)T=je(w),S=T===Le.NON_IDR_SLICE||T===Le.SLICE_DPA||T===Le.IDR,v=T===Le.SEI||T===Le.SPS||T===Le.PPS||T===Le.AUD;else{T=at(w);if(((1&w)<<5|c[k+1]>>3)>0){u+=p;continue}S=T<=Ue.RASL_R||T>=Ue.BLA_W_LP&&T<=21,v=T>=Ue.VPS_NUT&&T<=37||T===Ue.PREFIX_SEI_NUT||T>=41&&T<=44||T>=48&&T<=55}let P=!1;if(S){let e;if("avc"===t){const t=c.subarray(y,y+b),i=h(new _e(t));e=!s||i<=n,n=i}else e=c[y]>>7===1;e&&(s?P=!0:s=!0)}else v&&s&&(P=!0);if(P){const e=g-a;return this.seekTo(a),this.supplyPacket(e,0)}u+=p}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);de(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=_t[3*n+s];l(void 0!==o),this.seekTo(t),r=this.ensureBuffered(o),de(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(de(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=Rt[n];this.seekTo(t),r=this.ensureBuffered(s),de(r)&&(r=await r);const c=256*o,l=Math.round(c*Ta/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(de(r)&&(r=await r),r<18)return;const a=this.readBytes(18),s=jt(a);let n=s?null:Kt(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);de(i)&&(i=await i),n=Kt(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(de(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(l(-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(l(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 Na="application/vnd.apple.mpegurl",Oa="#EXT-X-STREAM-INF:",La="#EXT-X-I-FRAME-STREAM-INF:",za="#EXT-X-MEDIA:",Ua="#EXTINF:",qa="#EXT-X-MAP:",Wa="#EXT-X-KEY:",Ha="#EXT-X-MEDIA-SEQUENCE:",Va="#EXT-X-BYTERANGE:",ja="#EXT-X-PROGRAM-DATE-TIME:",Ka="#EXT-X-TARGETDURATION:",Xa="#EXT-X-PLAYLIST-TYPE:",$a=e=>0===e.length||e.startsWith("#")&&!e.startsWith("#EXT");class Ga{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=ye(e,e=>"video"===e.getType())+1;e.push(new Ja(this,t,i))}else if("audio"===t.type){const i=ye(e,e=>"audio"===e.getType())+1;e.push(new Za(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=ye(e,e=>"video"===e.getType())+1;e.push(new Ja(this,{id:e.length+1,type:"video"},t))}else if("audio"===r.type){const t=ye(e,e=>"audio"===e.getType())+1;e.push(new Za(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 Ya{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(),l(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){l(e.sequenceNumber>=0),l(this.segmentedInput.firstSegment);const r=await this.segmentedInput.getMediaOffset(t,i.input),a=t.timestamp-this.segmentedInput.firstSegment.timestamp,s=e.clone({timestamp:X(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(),l(this.firstInputTrack),l(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 Ja extends Ya{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 Za extends Ya{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())}}pe();const es=1/0;"undefined"!==typeof FinalizationRegistry&&new FinalizationRegistry(e=>{e()});class ts extends ve{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 ko;return this._sizePromise??(this._sizePromise=(async()=>{let e=this._getFileSize();return void 0!==e||(await this._read(0,1,0,es),e=this._getFileSize(),l(void 0!==e)),e})())}async getSize(){if(this._disposed)throw new ko;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 gs(this,e,t)}_dispatchRead(e,t){this.onread?.(e,t),this._emit("read",{start:e,end:t})}ref(){return new is(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){this._refCount--,0===this._refCount&&(this._dispose(),this._disposed=!0)}}class is{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;l(e._refCount>0),e._decrementRefCount(),e._refFinalizationRegistry?.unregister(this),this._freed=!0,this._source=null}[Symbol.dispose](){this.freed||this.free()}}class rs extends ts{constructor(e,t){if("string"!==typeof e)throw new TypeError("rootPath must be a string.");if("function"!==typeof t)throw new TypeError("requestHandler must be a function.");super(),this.rootPath=e,this.requestHandler=t}_resolveRequest(e){const t=this.requestHandler(e),i=e=>{var t;if(!(e instanceof ts||e instanceof is))throw new TypeError("requestHandler must return or resolve to a Source or SourceRef.");const i=e instanceof ts?e.ref():e;return(t=i.source)._usedForHls||(t._usedForHls=this._usedForHls),i};return de(t)?t.then(i):i(t)}}const as=(e,t)=>e.path===t.path;class ss extends rs{constructor(){super(...arguments),this._root=null,this._rootRequest=null}_read(e,t,i,r){if(!this._root){if(!this._rootRequest){const e=this._resolveRequest({path:this.rootPath,isRoot:!0}),t=e=>{const t=e instanceof ts?e.ref():e;return this._root=t,this._rootRequest=null,t};de(e)?this._rootRequest=e.then(t):(t(e),l(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 ns="undefined"!==typeof FinalizationRegistry?new FinalizationRegistry(e=>{e.cancel().catch(()=>{})}):null;class os extends ts{constructor(e,t={}){if(!(e instanceof Blob))throw new TypeError("blob must be a Blob.");if(!t||"object"!==typeof t)throw new TypeError("options must be an object.");if(void 0!==t.maxCacheSize&&(!ge(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 ps({maxCacheSize:t.maxCacheSize??8388608,maxWorkerCount:4,runWorker:this._runWorker.bind(this),onIdleWorkerRemoved:e=>{const t=this._readers.get(e);t&&(this._readers.delete(e),ns?.unregister(e),t.cancel().catch(()=>{}))},prefetchProfile:ms.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){l(e.strictTarget);let t=this._readers.get(e);if(void 0===t){if("stream"in this._blob&&!ae()&&!1!==this._options.useStreamReader){t=this._blob.slice(e.currentPos).stream().getReader(),ns?.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 xe._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)},ls=new Set;class us extends rs{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&&(!ge(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 us(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??cs,this._requestInit={...t.requestInit};let i=null;if(t.requestInit?.headers){const e={...ee(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=hs(i);e&&(this._offset=e.offset,this._length=e.length)}this._orchestrator=new ps({maxCacheSize:t.maxCacheSize??67108864,maxWorkerCount:t.parallelism??2,runWorker:this._runWorker.bind(this),prefetchProfile:ms.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:H(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 de(s)?s.then(n):n(s)}async _runWorker(e){for(;;){const i=new AbortController,r=await te(this._options.fetchFn??fetch,this._url,Z(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")||ls.has(e.origin)||(xe._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.`),ls.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){xe._error("Error while reading response stream. Attempting to resume.",t),await Se(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;xe._error("Error while reading response stream. Attempting to resume.",a),await Se(1e3*e);const s=await te(this._options.fetchFn??fetch,this._url,Z(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 fs(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);de(e)?e.then(e=>{e?(l(e.offset===o.start),o.resolve(e.bytes)):o.resolve(null)},e=>o.reject(e)):(l(null===e),o.resolve(null))}}_dispose(){this._orchestrator.dispose(),this._sequentialBacking&&(this._sequentialBacking._disposed=!0,this._sequentialBacking._dispose())}}const ds=/^bytes=(\d+)-(\d*)$/,hs=e=>{const t=ds.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=A(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}=M();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 ko);this._pendingSlices.length=0,this._cache.length=0,this._reader?.cancel()}}const ms={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(fe(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 ps{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){l(!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);l(s<=e&&t<=n);let o=null;const c=A(this.cache,e,e=>e.start),u=-1!==c?this.cache[c]:null;u&&u.start<=e&&t<=u.end&&(u.age=this.nextAge++,o={bytes:u.bytes,view:u.view,offset:u.start});const d=A(this.cache,s,e=>e.start),h=o?null:new Uint8Array(t-e);let f=0,m=s;const p=[];if(-1!==d){for(let i=d;i=n)break;if(r.end<=s)continue;const a=Math.max(s,r.start),o=Math.min(n,r.end);if(l(a<=o),m=h.length&&(o={bytes:h,view:g(h),offset:e}),0===p.length)return l(o),o;const{promise:k,resolve:y,reject:b}=M(),w=[];for(const l of p){const i=Math.max(e,l.start),r=Math.min(t,l.end);i===l.start&&r===l.end?w.push(l):ie.hole.start),i=-1!==t?this.queuedReads[t]:null;for(i&&l.start<=i.hole.end?(i.hole.end=Math.max(i.hole.end,l.end),i.strictTarget&&(i.strictTarget=e),T&&i.pendingSlices.push(T)):(t++,i={hole:{start:l.start,end:l.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 o?k.catch(e=>{if(!this.disposed){if(!this.options.handleUnhandledError)throw e;this.options.handleUnhandledError(e)}}):(l(h),o=k.then(t=>t&&{bytes:t,view:g(t),offset:e})),o}checkHoleAgainstWorker(e,t,i){if(fe(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);l(-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=A(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=g(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=g(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 de(a)?a.then(s):s(a)}_dispose(){this._ref?.free()}ref(){return this._ref??(this._ref=this._baseSource.ref()),super.ref()}}var ks=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},ys=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 bs=/^0[xX][0-9a-fA-F]+$/,ws=/^data:.*;base64,/i;class Ts extends Qa{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 Se(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=ks(t,await this.demuxer.input._getSourceUncached({path:this.rootPath,isRoot:!1}),!1),r=new yo(i.source),a=await r.requestEntireFile();l(a),e=Lo(a,a.length,{ignore:$a}),i.source instanceof rs&&(this.rootPath=i.source.rootPath)}catch(T){t.error=T,t.hasError=!0}finally{ys(t)}}const t=!1!==this.input._formatOptions.hls?.offsetTimestampsByDateTime;let i=!1,r=0,a=null,s=null,n=null,o=0,c=null,u=null,h=null,f=null,m=null,p=null,k=!1,y=d(this.segments)??null;const b=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}},w=e=>{o=e,y&&(l(null!==y.sequenceNumber),y.sequenceNumber0&&null!==p&&(r=o*p),k=!0);const e=T.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(T.startsWith(qa)){const e=new Ga(T.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=b(i)),o&&null===o.offset)throw new Error("Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset.");if(!y){const e={path:ke(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.");u={timestamp:r,unixEpochTimestamp:a,firstSegment:null,sequenceNumber:null,location:e,duration:0,encryption:n,initSegment:null,lastProgramDateTimeSeconds:m}}s=null,null===f?h=null:f=null}else if(T.startsWith(Wa)){const e=new Ga(T.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(!bs.test(r))throw new Error(`Unsupported IV format '${r}'.`);let e=r.slice(2);e=e.padStart(32,"0"),i=new Uint8Array(Ri);for(let t=0;t=8&&112===t[4]&&115===t[5]&&115===t[6]&&104===t[7]){const e=g(t).getUint32(0);r=vi(t.subarray(8,Math.min(e,t.length)))}}n={method:t,psshBox:r}}}}else if(T.startsWith(Ha)){const e=T.slice(22),t=Number(e);if(!Number.isInteger(t)||t<0)throw new Error(`Invalid EXT-X-MEDIA-SEQUENCE value '${e}'.`);w(t)}else if(T.startsWith(Va)){const e=b(T.slice(17));if(null===e.offset){if(null===h)throw new Error("Invalid M3U8 file; #EXT-X-BYTERANGE without offset requires a previous byte range.");e.offset=h}f=e,h=e.offset+e.length}else if(T.startsWith(ja)){if(y)continue;const e=T.slice(25),i=Date.parse(e);if(!Number.isFinite(i))continue;const s=i/1e3;if(m===s)continue;if(null===m&&this.segments.length>0){const e=d(this.segments),i=s-(e.timestamp+e.duration);for(const r of this.segments)r.unixEpochTimestamp=r.timestamp+i,t&&(r.timestamp=r.unixEpochTimestamp)}m=s,a=s,t&&(r=s)}else if("#EXT-X-DISCONTINUITY"===T)c=null;else if(T.startsWith(Ka)){const e=T.slice(22),t=Number(e);if(!Number.isFinite(t)||t<0)throw new Error(`Invalid EXT-X-TARGETDURATION value '${e}'.`);this.refreshInterval=t,p=t}else{if("#EXT-X-ENDLIST"===T){this.streamHasEnded=!0;break}if(T.startsWith(Xa)){"vod"===T.slice(21).toLowerCase()&&(this.streamHasEnded=!0)}}}else{if("#EXTM3U"!==T)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=A(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=>Pi(e,r))||(i=[...i,r]),this.input._formatOptions.isobmff.resolveKeyId({...e,psshBoxes:i})})}},s=new po({source:new ss(t.location.path,async e=>{l(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;l(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 Ui;return new ReadableStream({pull:async n=>{r||(s.init(await t()),r=!0);let o=e.requestSliceRange(a,0,65552);if(de(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=To(o,l),d=new Uint8Array(l);for(let e=0;e16)throw new Error("Invalid PKCS#7 padding. Incorrect key or corrupted data.");const t=d.subarray(0,l-e);n.enqueue(t),n.close(),i()}},cancel:()=>{i()}})})(new yo(s.source),async()=>{const t={stack:[],error:void 0,hasError:!1};try{const i=ks(t,await this.input._getSourceCached({path:e.keyUri,isRoot:!1},mo),!1),r=new yo(i.source),a=await r.requestSlice(0,Ri);if(!a)throw new Error("Invalid AES-128 key; expected at least 16 bytes of data.");return{key:To(a,Ri),iv:e.iv}}catch(i){t.error=i,t.hasError=!0}finally{ys(t)}},()=>{s.free()});r=new fs(n).ref()}else l(!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 qs)),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=be(this.inputCache,e=>e.age);l(-1!==e),this.inputCache.splice(e,1)}return s}async getLiveRefreshInterval(){return 0===this.getRemainingWaitTimeMs()&&await this.runUpdateSegments(),this.streamHasEnded?null:this.refreshInterval}}class Ss extends wi{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()=>{l(this.input._rootSource instanceof rs);const e=await this.input._reader.requestEntireFile();l(e);const t=Lo(e,e.length,{ignore:$a}),{rootPath:i}=this.input._rootSource,r=[],a=[];for(let l=1;l"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 u=e.attributes.get("video"),d=e.attributes.get("audio"),h=c.some(e=>$t.includes(li(e))),f=c.some(e=>Qt.includes(li(e)));if(null!==u&&!h){if(!s.includes(u))throw new Error(`Invalid M3U8 file; variant stream references video 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&&"video"===i.toLowerCase()});e:if(e){const t=e.attributes.get("uri");if(null===t)break e;const r=ke(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);l(null!==n),c.push(n)}}if(null!==d&&!f){if(!n.includes(d))throw new Error(`Invalid M3U8 file; variant stream references audio group "${d}" 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===d&&"audio"===i.toLowerCase()});e:if(e){const t=e.attributes.get("uri");if(null===t)break e;const r=ke(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);l(null!==n),c.push(n)}}c=[...new Set(c)];let m=null,p=null;const g=e.attributes.getAsNumber("bandwidth");l(null!==g);const k=e.attributes.getAsNumber("average-bandwidth"),y=e.attributes.get("name");for(const i of c){const o=li(i);if(null!==o)if($t.includes(o)){if(null!==m)throw new Error("Unsupported M3U8 file; multiple video codecs found in the CODECS attribute of a variant stream.");m=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:V,lineNumber:e.lineNumber,fullPath:e.fullPath,fullCodecString:m,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:xs(i.attributes),autoselect:xs(i.attributes)||Cs(i.attributes),languageCode:Bs(i.attributes.get("language")),lineNumber:i.lineNumber,fullPath:i.fullPath??e.fullPath,fullCodecString:p,pairingMask:1n<0?c:null}})}}}}return r})),c=[],u=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===V&&(t.languageCode=e.languageCode)):(e.id=c.length+1,c.push(e))};for(const l of o)for(const e of l)u(e);c.sort((e,t)=>e.lineNumber-t.lineNumber),this.trackBackings=[];for(const l of c)"video"===l.info.type?this.trackBackings.push(new Ps(l)):this.trackBackings.push(new Is(l));this.internalTracks=c})())}async getTrackBackings(){return await this.readMetadata(),l(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 Ts(this,e,i,null),this.segmentedInputs.push(t),t}async getMetadataTags(){return{}}async getMimeType(){return Na}dispose(){if(this.segmentedInputs){for(const e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}}class vs{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 Ps){for(const r of i)if(await r.getCodec()===this.getCodec()){t=r;break}}else{l(this instanceof Is);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{...Ee,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(){l(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 Ps extends vs{constructor(e){super(e)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return"video"}getCodec(){return li(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 Is extends vs{constructor(e){super(e)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return"audio"}getCodec(){return li(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 xs=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}".`)},Cs=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}".`)},Bs=e=>{if(null===e)return V;const t=e.split("-")[0];return t||V};class Es{constructor(){this._isIsobmff=!1}}class _s extends Es{constructor(){super(...arguments),this._isIsobmff=!0}async _getMajorBrand(e){let t=e._reader.requestSlice(0,12);if(de(t)&&(t=await t),!t)return null;t.skip(4);const i=Oo(t,4);return"ftyp"!==i&&"styp"!==i?null:Oo(t,4)}_createDemuxer(e){return new qi(e)}}class Rs extends _s{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(de(t)&&(t=await t),!t)return!1;let r=Bo(t),a=8;if(1===r){let t=e._reader.requestSlice(i+8,8);if(de(t)&&(t=await t),!t)return!1;r=Fo(t),a=16}if(r8)return!1;if(fr(i,r)!==sr.EBML)return!1;const a=pr(i);if("number"!==typeof a)return!1;let s=e._reader.requestSlice(i.filePos,a);if(de(s)&&(s=await s),!s)return!1;const n=i.filePos;for(;s.filePos<=n+a-2;){const e=gr(s);if(!e)break;const{id:i,size:r}=e,a=s.filePos;if(void 0===r)return!1;switch(i){case sr.EBMLVersion:if(1!==fr(s,r))return!1;break;case sr.EBMLReadVersion:if(1!==fr(s,r))return!1;break;case sr.DocType:if(kr(s,r)!==t)return!1;break;case sr.DocTypeVersion:if(fr(s,r)>4)return!1}s.filePos=a+r}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new jr(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}}class Ds extends As{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}}class Ms extends Es{async _canReadInput(e){let t=0;for(;;){let i=e._reader.requestSlice(t,Vo);if(de(i)&&(i=await i),!i)break;const r=$o(i);if(!r)break;t=i.filePos+r.size}const i=await Gr(e._reader,t,t+4096);if(!i)return!1;const r=i.header,a=mi(r.mpegVersionId,r.channel);let s=e._reader.requestSlice(i.startPos+a,4);if(de(s)&&(s=await s),!s)return!1;const n=Bo(s);if(n===hi||n===fi)return!0;t=i.startPos+i.header.totalSize;const o=await Gr(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 Qr(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}}class Ns extends Es{async _canReadInput(e){let t=e._reader.requestSlice(0,12);if(de(t)&&(t=await t),!t)return!1;const i=Oo(t,4);if("RIFF"!==i&&"RIFX"!==i&&"RF64"!==i)return!1;t.skip(4);return"WAVE"===Oo(t,4)}_createDemuxer(e){return new ha(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}}class Os extends Es{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return de(t)&&(t=await t),!!t&&"OggS"===Oo(t,4)}_createDemuxer(e){return new na(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}}class Ls extends Es{async _canReadInput(e){let t=0;for(;;){let i=e._reader.requestSlice(t,Vo);if(de(i)&&(i=await i),!i)break;const r=$o(i);if(!r)break;t=i.filePos+r.size}let i=e._reader.requestSlice(t,4);return de(i)&&(i=await i),!!i&&"fLaC"===Oo(i,4)}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new ba(e)}}class zs extends Es{async _canReadInput(e){let t=0;for(;;){let i=e._reader.requestSlice(t,Vo);if(de(i)&&(i=await i),!i)break;const r=$o(i);if(!r)break;t=i.filePos+r.size}let i=e._reader.requestSliceRange(t,7,9);if(de(i)&&(i=await i),!i)return!1;const r=pa(i);if(!r)return!1;if(t+=r.frameLength,i=e._reader.requestSliceRange(t,7,9),de(i)&&(i=await i),!i)return!1;const a=pa(i);return!!a&&(r.objectType===a.objectType&&r.samplingFrequencyIndex===a.samplingFrequencyIndex&&r.channelConfiguration===a.channelConfiguration)}_createDemuxer(e){return new ka(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}}class Us extends Es{async _canReadInput(e){let t=e._reader.requestSlice(0,205);if(de(t)&&(t=await t),!t)return!1;const i=To(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 Ca(e)}get name(){return"MPEG Transport Stream"}get mimeType(){return"video/MP2T"}}class qs extends Es{async _canReadInput(e){let t=e._reader.requestSlice(0,7);if(de(t)&&(t=await t),!t)return!1;if(!("#EXTM3U"===Oo(t,7)))return!1;if(!(e._rootSource instanceof rs))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 Ss(e)}get name(){return"HTTP Live Streaming (HLS)"}get mimeType(){return Na}}const Ws=new Rs,Hs=new Fs,Vs=new As,js=new Ds,Ks=new Ms,Xs=new Ns,$s=new Os,Gs=new zs,Qs=new Ls,Ys=new Us,Js=new qs,Zs=[Js,Ws,Hs,Vs,js,Xs,$s,Qs,Ks,Gs,Ys],en=[Js,Ws,Hs,Ks,Gs,Ys];var tn=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});pe();let rn=-1/0,an=-1/0,sn=null;"undefined"!==typeof FinalizationRegistry&&(sn=new FinalizationRegistry(e=>{const t=performance.now();"video"===e.type?(t-rn>=1e3&&(xe._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."),rn=t),"undefined"!==typeof VideoFrame&&e.data instanceof VideoFrame&&e.data.close()):(t-an>=1e3&&(xe._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."),an=t),"undefined"!==typeof AudioData&&e.data instanceof AudioData&&e.data.close())}));class nn{constructor(){this._referenceCount=0,this._lastAllocationBuffer=null}}const on=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],cn=new Set(on);class ln{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(J*this.timestamp)}get microsecondDuration(){return Math.trunc(J*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||!cn.has(t.format))throw new TypeError("init.format must be one of: "+on.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&&Te(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??bn(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?p(e):p(e).slice(),this._layout=i,this.colorSpace=new mn(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&&Te(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 mn(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&&Te(t.visibleRect,"init.visibleRect"),"undefined"!==typeof VideoFrame)return new ln(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*J),duration:Math.trunc((t.duration??0)*J)||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:ne(),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 mn({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else{if(!(e instanceof nn))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&&!on.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=we({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),sn?.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return l(null!==this._data),this._data instanceof nn?new ln(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):pn(this._data)?new ln(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):this._data instanceof Uint8Array?(l(this._layout),new ln(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 ln(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||(sn?.unregister(this),this._data instanceof nn?(this._data._referenceCount--,0===this._data._referenceCount&&this._data.close()):pn(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(yn(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(pn(this._data))return this._data.allocationSize(e);return Tn(this,e).allocationSize}async copyTo(e,t={}){if(!C(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(yn(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(l(null!==this._data),pn(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 nn)){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 ln))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{tn(i)}}}const i=Tn(this,t);l(this.format);const r=p(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)l(this._layout),l(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");l(e);const t=e.getImageData(0,0,this.codedWidth,this.codedHeight);s=[{data:p(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(d)}if(void 0!==t.format){const e=this.format.startsWith("RGB")!==t.format.startsWith("RGB"),a=this.format.includes("X")&&t.format.includes("A");if(e||a)for(let t=0;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 pn(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?(l(this._layout),new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,layout:this._layout,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,t,i,r,a,s,n,o,c){let l=0,u=0,d=this.displayWidth,h=this.displayHeight,f=0,m=0,p=this.displayWidth,g=this.displayHeight;if(void 0!==s?(l=t,u=i,d=r,h=a,f=s,m=n,void 0!==o?(p=o,g=c):(p=d,g=h)):(f=t,m=i,void 0!==r&&(p=r,g=a)),!("undefined"!==typeof CanvasRenderingContext2D&&e instanceof CanvasRenderingContext2D||"undefined"!==typeof OffscreenCanvasRenderingContext2D&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(l))throw new TypeError("sx must be a number.");if(!Number.isFinite(u))throw new TypeError("sy must be a number.");if(!Number.isFinite(d)||d<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(h)||h<0)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(f))throw new TypeError("dx must be a number.");if(!Number.isFinite(m))throw new TypeError("dy must be a number.");if(!Number.isFinite(p)||p<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(g)||g<0)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw new Error("VideoSample is closed.");({sx:l,sy:u,sWidth:d,sHeight:h}=this._rotateSourceRegion(l,u,d,h,this.rotation));const k=this.toCanvasImageSource();e.save();const y=f+p/2,b=m+g/2;e.translate(y,b),e.rotate(this.rotation*Math.PI/180);const w=this.rotation%180===0?1:p/g;e.scale(1/w,w),e.drawImage(k,l,u,d,h,-p/2,-g/2,p,g),e.restore()}drawWithFit(e,t){if(!("undefined"!==typeof CanvasRenderingContext2D&&e instanceof CanvasRenderingContext2D||"undefined"!==typeof OffscreenCanvasRenderingContext2D&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!t||"object"!==typeof t)throw new TypeError("options must be an object.");if(!["fill","contain","cover"].includes(t.fit))throw new TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");void 0!==t.crop&&kn(t.crop,"options.");const i=e.canvas.width,r=e.canvas.height,a=t.rotation??this.rotation,[s,n]=a%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let o,c,l,u,d=t.crop;d&&(d=gn(d,s,n));const{sx:h,sy:f,sWidth:m,sHeight:p}=this._rotateSourceRegion(t.crop?.left??0,t.crop?.top??0,t.crop?.width??s,t.crop?.height??n,a);if("fill"===t.fit)o=0,c=0,l=i,u=r;else{const[e,a]=t.crop?[t.crop.width,t.crop.height]:[s,n],d="contain"===t.fit?Math.min(i/e,r/a):Math.max(i/e,r/a);l=e*d,u=a*d,o=(i-l)/2,c=(r-u)/2}e.save();const g=a%180===0?1:l/u;e.translate(i/2,r/2),e.rotate(a*Math.PI/180),e.scale(1/g,g),e.translate(-i/2,-r/2),e.drawImage(this.toCanvasImageSource(),h,f,m,p,o,c,l,u),e.restore()}_rotateSourceRegion(e,t,i,r,a){return 90===a?[e,t,i,r]=[t,this.squarePixelHeight-e-i,r,i]:180===a?[e,t]=[this.squarePixelWidth-e-i,this.squarePixelHeight-t-r]:270===a&&([e,t,i,r]=[this.squarePixelWidth-t-r,e,r,i]),{sx:e,sy:t,sWidth:i,sHeight:r}}_drawWithFitAndMipmapping(e,t,i){const r=e.width,a=e.height,[s,n]=i.rotation%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],o=i.crop?i.crop.width:s,c=i.crop?i.crop.height:n;let l=0;2*r0?fn(u,d):{canvas:e,context:t,isNew:i.targetIsFresh};f.imageSmoothingQuality="high",i.fillBlack?(f.fillStyle="black",f.fillRect(0,0,u,d)):m||f.clearRect(0,0,u,d),this.drawWithFit(f,{fit:i.fit,rotation:i.rotation,crop:i.crop}),f.globalCompositeOperation="copy";for(let p=l;p>1;p--){const e=r*2**p,t=a*2**p;f.drawImage(h,0,0,e,t,0,0,e/2,t/2)}f.globalCompositeOperation="source-over",l>0&&(t.imageSmoothingQuality="high",t.globalCompositeOperation="copy",t.drawImage(h,0,0,2*r,2*a,0,0,r,a),t.globalCompositeOperation="source-over")}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(l(null!==this._data),this._data instanceof nn||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&&kn(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=u(this.rotation+(e.rotate??0)),[i,r]=t%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let a=e.crop;a&&(a=gn(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=K(c,e.roundDimensionsTo??1),l=K(l,e.roundDimensionsTo??1);const d={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 u of un){let e=u(this,d);if(de(e)&&(e=await e),null!==e)return e}const{canvas:h,context:f,isNew:m}=fn(d.width,d.height);return this._drawWithFitAndMipmapping(h,f,{fit:d.fit,rotation:d.rotation,crop:d.crop,targetIsFresh:m,fillBlack:"discard"===d.alpha}),new ln(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 un=[],dn=[];let hn=0;const fn=(e,t)=>{for(const a of dn)if(a.canvas.width===e&&a.canvas.height===t)return a.age=hn++,{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 dn.length>=3&&dn.splice(be(dn,e=>e.age),1),dn.push({canvas:i,context:r,age:hn++}),{canvas:i,context:r,isNew:!0}};class mn{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(b);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(T);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(v);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 pn=e=>"undefined"!==typeof VideoFrame&&e instanceof VideoFrame,gn=(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 l(s>=0),l(n>=0),{left:r,top:a,width:s,height:n}},kn=(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.")},yn=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.")}},bn=(e,t,i)=>{const r=wn(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},wn=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:z(e),l(!1)}},Tn=(e,t)=>{const i={left:0,top:0,width:e.codedWidth,height:e.codedHeight},r=t.rect,a=Sn(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 Pn(a,n,s)},Sn=(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(!vn(a,s))throw new TypeError("visibleRect alignment is invalid for the format.");return s},vn=(e,t)=>{if(null===e)return!0;const i=wn(e);for(let r=0;r{const r=wn(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(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(e?.timestamp))throw new TypeError("init.timestamp must be a number.");const t=e.data.byteLength/(Bn(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*Bn(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=Bn(t),s=En(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(!C(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&&!In.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,u=this.numberOfChannels,d=a??0;if(d>=c)throw new RangeError("frameOffset out of range");const h=void 0!==r?r:c-d;if(h>c-d)throw new RangeError("frameCount out of range");const f=Bn(o),m=En(o);if(m&&s>=u)throw new RangeError("planeIndex out of range");if(!m&&0!==s)throw new RangeError("planeIndex out of range");const p=(m?h:h*u)*f;if(e.byteLength2&&o!==n)return void An(this._data,k,n,o,u,s,d,h);try{return void this._data.copyTo(e,{planeIndex:s,frameOffset:d,frameCount:h,format:o})}catch(P){if("f32-planar"===o)throw P;n="f32-planar"}}const b=_n(n),w=Bn(n),T=En(n);let S;if(this._data instanceof xn){const e=e=>{const t=this._data.getDataPlane(e);if(!(t instanceof Uint8Array))throw new TypeError("getDataPlane() must return a Uint8Array.");const i=c*w*(T?1:u);if(t.byteLength!==i)throw new TypeError(`Data plane ${e} has invalid size. Expected exactly ${i} bytes, got ${t.byteLength} bytes.`);return t};if(T)if(m)S=e(s),s=0;else{S=new Uint8Array(c*w*u);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 Cn({data:a,format:this.format,sampleRate:this.sampleRate,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp+e/this.sampleRate})}close(){this._closed||(sn?.unregister(this),this._data instanceof xn?(this._data._referenceCount--,0===this._data._referenceCount&&this._data.close()):Fn(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 xn?this._createAudioDataFromData():Fn(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(En(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")}},En=e=>{switch(e){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},_n=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)}},Rn=e=>{switch(e){case"u8":case"u8-planar":return(e,t,i)=>e.setUint8(t,H(127.5*(i+1),0,255));case"s16":case"s16-planar":return(e,t,i)=>e.setInt16(t,H(Math.round(32767*i),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,i)=>e.setInt32(t,H(Math.round(2147483647*i),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,i)=>e.setFloat32(t,i,!0)}},Fn=e=>"undefined"!==typeof AudioData&&e instanceof AudioData,An=(e,t,i,r,a,s,n,o)=>{const c=_n(i),l=Rn(r),u=Bn(i),d=Bn(r),h=En(i);if(En(r))if(h){const r=new ArrayBuffer(o*u),a=g(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.")},On=e=>{if(!ge(e))throw new TypeError("timestamp must be a number.")},Ln=(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 zn{constructor(e){if(!(e instanceof eo))throw new TypeError("track must be an InputTrack.");this._track=e}async getFirstPacket(e={}){if(Nn(e),this._track.input._disposed)throw new ko;return Ln(this._track,this._track._backing.getFirstPacket(e),e)}async getFirstKeyPacket(e={}){Nn(e);const t=await this.getFirstPacket(e);return t?"key"===t.type?t:this.getNextKeyPacket(t,e):null}async getPacket(e,t={}){if(On(e),Nn(t),this._track.input._disposed)throw new ko;return Ln(this._track,this._track._backing.getPacket(e,t),t)}async getNextPacket(e,t={}){if(!(e instanceof Si))throw new TypeError("packet must be an EncodedPacket.");if(Nn(t),this._track.input._disposed)throw new ko;return Ln(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(On(e),Nn(t),this._track.input._disposed)throw new ko;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);const i=await this._track._backing.getKeyPacket(e,t);if(!i)return i;l("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 Si))throw new TypeError("packet must be an EncodedPacket.");if(Nn(t),this._track.input._disposed)throw new ko;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);const i=await this._track._backing.getNextKeyPacket(e,t);if(!i)return i;l("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 Si))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 Si))throw new TypeError("endPacket must be an EncodedPacket.");if(Nn(i),this._track.input._disposed)throw new ko;const r=[];let{promise:a,resolve:s}=M(),{promise:n,resolve:o}=M(),c=!1,l=!1,u=null,d=!1;const h=[],f=()=>Math.max(2,h.length);(async()=>{let u=e??await this.getFirstPacket(i);for(;u&&!l&&!this._track.input._disposed&&!(t&&u.sequenceNumber>=t?.sequenceNumber);)r.length>f()?(({promise:n,resolve:o}=M()),await n):(r.push(u),s(),({promise:a,resolve:s}=M()),u=await this.getNextPacket(u,i));c=!0,s()})().catch(e=>{d||(u=e,d=!0,s())});const m=this._track;return{async next(){for(;;){if(m.input._disposed)throw new ko;if(l)return{value:void 0,done:!0};if(d)throw u;if(r.length>0){const e=r.shift(),t=performance.now();for(h.push(t);h.length>0&&t-h[0]>=1e3;)h.shift();return o(),{value:e,done:!1}}if(c)return{value:void 0,done:!0};await a}},return:async()=>(l=!0,o(),s(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}}class Un{constructor(e,t){this.onSample=e,this.onError=t}}class qn{mediaSamplesInRange(e=-1/0,t=1/0,i){On(e),On(t);const r=[];let a=!1,s=null,{promise:n,resolve:o}=M(),{promise:c,resolve:l}=M(),u=!1,d=!1,h=!1,f=null,m=null,p=!1;const g={...i,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{f=await this._createDecoder(i=>{l(),i.timestamp>=t&&(d=!0),d?i.close():(s&&(i.timestamp>e?(r.push(s),a=!0):s.close()),i.timestamp>=e&&(r.push(i),a=!0),s=a?null:i,r.length>0&&(o(),({promise:n,resolve:o}=M())))},e=>{p||(m=e,p=!0,o())});const i=this._createPacketSink(),k=await i.getKeyPacket(e,g)??await i.getFirstKeyPacket(g);let y=k;const b=i.packets(k??void 0,void 0,g);for(await b.next();y&&!d&&!this._track.input._disposed;){const e=Wn(r.length);if(r.length+f.getDecodeQueueSize()>e){({promise:c,resolve:l}=M()),await c;continue}f.decode(y);const t=await b.next();if(t.done)break;y=t.value}await b.return(),h||this._track.input._disposed||await f.flush(),!a&&s&&r.push(s),u=!0,o()})().catch(e=>{p||(m=e,p=!0,o())}).finally(()=>{f?.close()});const k=this._track,y=()=>{s?.close();for(const e of r)e.close()};return{async next(){for(;;){if(k.input._disposed)throw h=!0,d=!0,y(),new ko;if(h)return{value:void 0,done:!0};if(p)throw h=!0,d=!0,y(),m;if(r.length>0){const e=r.shift();return l(),{value:e,done:!1}}if(u)return{value:void 0,done:!0};await n}},return:async()=>(h=!0,d=!0,l(),o(),y(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e,t){(e=>{if(!(Symbol.iterator in e)&&!(Symbol.asyncIterator in e))throw new TypeError("Argument must be an iterable or async iterable.")})(e);const i=async function*(e){Symbol.iterator in e?yield*e[Symbol.iterator]():yield*e[Symbol.asyncIterator]()}(e),r=[],a=[];let{promise:s,resolve:n}=M(),{promise:o,resolve:c}=M(),u=!1,d=!1,h=null,f=null,m=!1;const p=e=>{a.push(e),n(),({promise:s,resolve:n}=M())},g={...t,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{h=await this._createDecoder(e=>{if(c(),d)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{m||(f=e,m=!0,n())});const e=this._createPacketSink();let t=null,s=null,k=-1;const y=async()=>{l(s),l(h);let t=s;for(h.decode(t);t.sequenceNumberi&&!d;)({promise:o,resolve:c}=M()),await o;if(d)break;const r=await e.getNextPacket(t,g);l(r),h.decode(r),t=r}k=-1},b=async()=>{l(h),await h.flush();for(let e=0;e{m||(f=e,m=!0,n())}).finally(()=>{h?.close()});const k=this._track,y=()=>{for(const e of a)e?.close()};return{async next(){for(;;){if(k.input._disposed)throw d=!0,y(),new ko;if(d)return{value:void 0,done:!0};if(m)throw d=!0,y(),f;if(a.length>0){const e=a.shift();return l(void 0!==e),c(),{value:e,done:!1}}if(u)return{value:void 0,done:!0};await s}},return:async()=>(d=!0,c(),n(),y(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}}const Wn=e=>0===e?40:8;class Hn extends Un{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 ie,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=Dn.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 ln))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();l(void 0!==t),this.mergeAlpha(e,t)}else this.colorQueue.push(e)};if(ce()){if("avc"===i&&this.decoderConfig.description){const e=Je(p(this.decoderConfig.description));if(e&&e.sequenceParameterSets.length>0){const t=et(e.sequenceParameterSets[0]);t&&(0===t.frameMbsOnlyFlag&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"}),0!==t.maxDecFrameBuffering&&1!==t.bitstreamRestrictionFlag&&(e.sequenceParameterSets[0]=it(t),this.decoderConfig={...this.decoderConfig,description:Ye(e)}))}}I(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:(l(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(l(this.decoder),ae()||D(this.inputTimestamps,e.timestamp,e=>e),ce()&&0===this.currentPacketIndex)if("avc"===this.codec){const t=[];let i=!1;for(const a of Ve(e.data,this.decoderConfig)){const r=je(e.data[a.offset]);if(i||(i=r>=1&&r<=5),r===Le.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&p(t.description)[4];return Ge(e,i+1)}return $e(e)})(t,this.decoderConfig);e=new Si(r,e.type,e.timestamp,e.duration)}else if("hevc"===this.codec){const t=gt(e.data,this.decoderConfig);t&&(e=new Si(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 jn),!this.alphaDecoder){const e=e=>{if(this.colorQueue.length>0){const t=this.colorQueue.shift();l(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();l(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=Pt(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 rt(e,this.decoderConfig)){const i=at(e[t.offset]);if(i===Ue.RASL_N||i===Ue.RASL_R)return!0}return!1}sampleHandler(e){if(ae()){if(this.sampleQueue.length>0&&e.timestamp>=d(this.sampleQueue).timestamp){for(const e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}D(this.sampleQueue,e,e=>e.timestamp)}else{const t=this.inputTimestamps.shift();l(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=M();this.mergeAlphaPromises.push(i.promise);const r={sample:null};this.finalSamples.push(r);try{if(t){l(this.merger);const i=await this.merger.merge(e,t);r.sample=new ln(i)}else r.sample=new ln(e);for(;this.finalSamples.length>0&&null!==this.finalSamples[0].sample;){const e=this.finalSamples.shift();this.sampleHandler(e.sample)}}catch(a){N(this.finalSamples,r),this.onError(a)}finally{N(this.mergeAlphaPromises,i.promise),i.resolve()}}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(l(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),ae()){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()):(l(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 Vn=null;class jn{constructor(){this.workers=[],this.nextWorkerIndex=0,this.pendingRequests=new Map,this.nextRequestId=0}merge(e,t){if(0===this.workers.length){if(!Vn){const e=new Blob([`(${Kn.toString()})()`],{type:"application/javascript"});Vn=URL.createObjectURL(e)}const e=H(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=M();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 Kn=()=>{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 d=r*a,h=d*c,f=l*u*c,m=new Uint8Array(h+2*f+d*c);await e.copyTo(m);const p=await o(t,r,a,c),g=h+2*f;m.set(p,g);const k={format:i.slice(0,4)+"A"+i.slice(4),codedWidth:r,codedHeight:a,timestamp:e.timestamp,duration:e.duration??void 0,transfer:[m.buffer]};return new VideoFrame(m,k)},n=async(e,i)=>{const r=e.visibleRect?.width??e.codedWidth,a=e.visibleRect?.height??e.codedHeight,s=r*a,n=Math.ceil(r/2)*Math.ceil(a/2),c=e.allocationSize();t&&t.byteLength===c||(t=new Uint8Array(c)),await e.copyTo(t);const l=new Uint8Array(s+2*n+s);l.set(t.subarray(0,s),0);const u=s,d=s+n,h=s;for(let o=0;o{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 $n extends qn{constructor(e,t={}){if(!(e instanceof ro))throw new TypeError("videoTrack must be an InputVideoTrack.");Xn(t),super(),this._track=e,this._decoderOptions=t}async _createDecoder(e,t){if(!(await this._track.canDecode())){if("undefined"===typeof VideoDecoder)throw new Error(le("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 l(i&&a),a={...a,hardwareAcceleration:this._decoderOptions.hardwareAcceleration,optimizeForLatency:this._decoderOptions.optimizeForLatency},new Hn(e,t,i,a,r,s)}_createPacketSink(){return new zn(this._track)}async getSample(e,t={}){On(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 Gn{constructor(e,t={}){if(this._rotation=0,this._initPromise=null,this._nextCanvasIndex=0,!(e instanceof ro))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&&kn(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&&Xn(t.decoderOptions),this._videoTrack=e,this._alpha=t.alpha??!1,this._options=t,this._fit=t.fit??"fill",this._videoSampleSink=new $n(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=gn(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||ne()});l(s),e._drawWithFitAndMipmapping(r,s,{fit:this._fit,rotation:this._rotation,crop:this._crop,targetIsFresh:a,fillBlack:!this._alpha&&ne()});const n={canvas:r,timestamp:e.timestamp,duration:e.duration};return e.close(),n}async getCanvas(e,t){On(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*W(this._videoSampleSink.samples(e,t,i),e=>this._videoSampleToWrappedCanvas(e))}async*canvasesAtTimestamps(e,t){await this._ensureInit(),yield*W(this._videoSampleSink.samplesAtTimestamps(e,t),e=>e&&this._videoSampleToWrappedCanvas(e))}}class Qn extends Un{constructor(e,t,i,r){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new ie,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=Mn.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 Cn))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 Cn(e))}catch(t){this.onError(t)}},error:t=>{t.stack=e,this.onError(t)}}),this.decoder.configure(r)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(l(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--)):(l(this.decoder),this.expectedFirstTimestamp??(this.expectedFirstTimestamp=e.timestamp),this.decoder.decode(e.toEncodedAudioChunk()))}async flush(){this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(l(this.decoder),await this.decoder.flush()),this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(l(this.decoder),"closed"!==this.decoder.state&&this.decoder.close())}}class Yn extends Un{constructor(e,t,i){super(e,t),this.decoderConfig=i,this.currentTimestamp=null,l(Gt.includes(i.codec)),this.codec=i.codec;const{dataType:r,sampleSize:a,littleEndian:s}=ci(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):l(!1);break;case 3:"unsigned"===r?this.readInputValue=(e,t)=>U(e,t,s)-2**23:"signed"===r?this.readInputValue=(e,t)=>((e,t,i)=>U(e,t,i)<<8>>8)(e,t,s):l(!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):l(!1);break;case 8:"float"===r?this.readInputValue=(e,t)=>e.getFloat64(t,s):l(!1);break;default:z(a),l(!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:z(a),l(!1)}}getDecodeQueueSize(){return 0}decode(e){const t=g(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 Cn({format:this.outputFormat,data:a,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:i,timestamp:o});this.onSample(c)}async flush(){}close(){}}class Jn extends qn{constructor(e){if(!(e instanceof ao))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(le("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 l(i&&r),Gt.includes(r.codec)?new Yn(e,t,r):new Qn(e,t,i,r)}_createPacketSink(){return new zn(this._track)}async getSample(e,t={}){On(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 Zn{constructor(e){if(!(e instanceof ao))throw new TypeError("audioTrack must be an InputAudioTrack.");this._audioSampleSink=new Jn(e)}_audioSampleToWrappedArrayBuffer(e){const t={buffer:e.toAudioBuffer(),timestamp:e.timestamp,duration:e.duration};return e.close(),t}async getBuffer(e,t){On(e);const i=await this._audioSampleSink.getSample(e,t);return i&&this._audioSampleToWrappedArrayBuffer(i)}buffers(e,t,i){return W(this._audioSampleSink.samples(e,t,i),e=>this._audioSampleToWrappedArrayBuffer(e))}buffersAtTimestamps(e,t){return W(this._audioSampleSink.samplesAtTimestamps(e,t),e=>e&&this._audioSampleToWrappedArrayBuffer(e))}}class eo{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof ro}isAudioTrack(){return this instanceof ao}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}async getInternalCodecId(){return this._backing.getInternalCodecId()}get internalCodecId(){return to(this._backing.getInternalCodecId(),"internalCodecId","getInternalCodecId")}async getLanguageCode(){return this._backing.getLanguageCode()}get languageCode(){return to(this._backing.getLanguageCode(),"languageCode","getLanguageCode")}async getName(){return this._backing.getName()}get name(){return to(this._backing.getName(),"name","getName")}async getTimeResolution(){return this._backing.getTimeResolution()}get timeResolution(){return to(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 to(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 X((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 zn(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 eo))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(co({filter:e=>e.canBePairedWith(this)},e))}async getPairableVideoTracks(e){return this.input.getVideoTracks(co({filter:e=>e.canBePairedWith(this)},e))}async getPairableAudioTracks(e){return this.input.getAudioTracks(co({filter:e=>e.canBePairedWith(this)},e))}async getPrimaryPairableVideoTrack(e){return this.input.getPrimaryVideoTrack(co({filter:e=>e.canBePairedWith(this)},e))}async getPrimaryPairableAudioTrack(e){return this.input.getPrimaryAudioTrack(co({filter:e=>e.canBePairedWith(this)},e))}async hasPairableTrack(e){e&&(e=io(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=io(e)),this.hasPairableTrack(async t=>t.isVideoTrack()&&(!e||await e(t)))}hasPairableAudioTrack(e){return e&&(e=io(e)),this.hasPairableTrack(async t=>t.isAudioTrack()&&(!e||await e(t)))}}const to=(e,t,i)=>{if(de(e))throw new Error(`'${t}' is deprecated and not available synchronously for this track. Use the preferred '${i}()' instead.`);return e},io=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 de(r)?r.then(i):i(r)}:void 0};class ro extends eo{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 to(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 to(this._backing.getCodedWidth(),"codedWidth","getCodedWidth")}async getCodedHeight(){return this._backing.getCodedHeight()}get codedHeight(){return to(this._backing.getCodedHeight(),"codedHeight","getCodedHeight")}async getRotation(){return this._backing.getRotation()}get rotation(){return to(this._backing.getRotation(),"rotation","getRotation")}async getSquarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelWidth(){return to(this._backing.getSquarePixelWidth(),"squarePixelWidth","getSquarePixelWidth")}async getSquarePixelHeight(){return this._backing.getSquarePixelHeight()}get squarePixelHeight(){return to(this._backing.getSquarePixelHeight(),"squarePixelHeight","getSquarePixelHeight")}async getPixelAspectRatio(){return this._pixelAspectRatioCache??(this._pixelAspectRatioCache=we({num:await this.getSquarePixelWidth()*await this.getCodedHeight(),den:await this.getSquarePixelHeight()*await this.getCodedWidth()}))}get pixelAspectRatio(){return this._pixelAspectRatioCache??(this._pixelAspectRatioCache=we({num:to(this._backing.getSquarePixelWidth(),"pixelAspectRatio","getPixelAspectRatio")*to(this._backing.getCodedHeight(),"pixelAspectRatio","getPixelAspectRatio"),den:to(this._backing.getSquarePixelHeight(),"pixelAspectRatio","getPixelAspectRatio")*to(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=to(e,"displayWidth","getDisplayWidth");if(null!==t)return t}const t=to(this._backing.getRotation(),"displayWidth","getDisplayWidth")%180===0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight();return to(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=to(e,"displayHeight","getDisplayHeight");if(null!==t)return t}const t=to(this._backing.getRotation(),"displayHeight","getDisplayHeight")%180===0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth();return to(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(l(null!==t),Dn.some(i=>i.supports(t,e)))return!0;if("undefined"===typeof VideoDecoder)return!1;return!0===(await VideoDecoder.isConfigSupported(e)).supported}catch(e){return xe._error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof Si))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 l(i),Pt(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&&(!ge(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 zn(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=(d/T+d/S)/2;return{underlyingFrameRate:u,bestGuessFrameRate:null!==u?u:fo(P),minFrameRate:d/p,maxFrameRate:d/m,averageFrameRate:d*k/g,medianFrameRate:P,frameRateIsConstant:null!==u&&1===m&&1===p,probedPacketCount:n}}}class ao extends eo{constructor(e,t){super(e,t),this._backing=t}get type(){return"audio"}async getCodec(){return this._backing.getCodec()}get codec(){return to(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){return await(this._backing.getHasOnlyKeyPackets?.())??!0}async getNumberOfChannels(){return this._backing.getNumberOfChannels()}get numberOfChannels(){return to(this._backing.getNumberOfChannels(),"numberOfChannels","getNumberOfChannels")}async getSampleRate(){return this._backing.getSampleRate()}get sampleRate(){return to(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(l(null!==t),Mn.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 xe._error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof Si))throw new TypeError("packet must be an EncodedPacket.");return null===await this.getCodec()?null:"key"}}const so=e=>-(e??-1/0),no=e=>-e,oo=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 de(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 de(r)?r.then(i):i(r)}:void 0}},co=(e,t)=>({filter:e?.filter||t?.filter?i=>{const r=e?.filter?.(i)??!0,a=e=>!1!==e&&(t?.filter?.(i)??!0);return de(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 de(r)||de(a)?Promise.all([r,a]).then(([e,t])=>s(e,t)):s(r,a)}:void 0}),lo=async(e,t)=>{let i=e;if(t?.filter){const r=e.map(e=>t.filter(e));if(r.some(e=>de(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=>de(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)},uo=(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 d=1/Math.min(u,1e3),h=Math.max(Number.EPSILON,o-d),f=o+d,m=t/f,p=t/h,g=t/o;let k=null,y=1/0;for(const T of a){if(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 Es)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof ts||e.source instanceof is))throw new TypeError("options.source must be a Source or SourceRef.");if(e.source instanceof ts&&e.source._disposed)throw new TypeError("options.source must not be a disposed Source.");if(void 0!==e.initInput&&!(e.initInput instanceof po))throw new TypeError("options.initInput, when provided, must be an Input.");void 0!==e.formatOptions&&((e,t)=>{if(!e||"object"!==typeof e)throw new TypeError(`${t}, when provided, must be an object.`);if(void 0!==e.isobmff){if(!e.isobmff||"object"!==typeof e.isobmff)throw new TypeError(`${t}.isobmff, when provided, must be an object.`);if(void 0!==e.isobmff.resolveKeyId&&"function"!==typeof e.isobmff.resolveKeyId)throw new TypeError(`${t}.isobmff.resolveKeyId, when provided, must be a function.`)}if(void 0!==e.hls){if(!e.hls||"object"!==typeof e.hls)throw new TypeError(`${t}.hls, when provided, must be an object.`);if(void 0!==e.hls.offsetTimestampsByDateTime&&"boolean"!==typeof e.hls.offsetTimestampsByDateTime)throw new TypeError(`${t}.hls.offsetTimestampsByDateTime, when provided, must be a boolean.`)}})(e.formatOptions,"formatOptions"),this._formats=e.formats,this._initInput=e.initInput??null,this._formatOptions=e.formatOptions??{},e.source instanceof ts?this._rootRef=e.source.ref():this._rootRef=e.source,this._sourceRefs.push(this._rootRef)}get _rootSource(){return this._rootRef.source}async _getSourceUncached(e){l(this._rootSource instanceof rs);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&&as(i.request,e));if(i)return i.age++,Promise.resolve(i.sourceRef.source.ref());const r=this._sourceCachePromises.find(i=>i.cacheGroup===t&&as(i.request,e));if(r)return r.promise.then(e=>e.sourceRef.source.ref());const a=(async()=>{const i=await this._getSourceUncached(e);if(ye(this._sourceCache,e=>e.cacheGroup===t&&1===e.sourceRef.source._refCount)>=4){const e=be(this._sourceCache,e=>e.cacheGroup===t&&1===e.sourceRef.source._refCount?e.age:1/0);l(-1!==e);const i=this._sourceCache[e];this._sourceCache.splice(e,1),i.sourceRef.free(),N(this._sourceRefs,i.sourceRef)}this._sourceRefs.push(i);const r=this._sourceCachePromises.findIndex(t=>t.request===e);l(-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 yo(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 go})())}get source(){return this._rootSource}async getFormat(){return await this._getDemuxer(),l(this._format),this._format}async canRead(){try{return await this._getDemuxer(),!0}catch(e){if(e instanceof go)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=oo(e));const t=(await this._getTrackBackings()).map(e=>this._wrapBackingAsTrack(e));return lo(t,e)}async getVideoTracks(e){e&&(e=oo(e));const t=(await this.getTracks()).filter(e=>e.isVideoTrack());return lo(t,e)}async getAudioTracks(e){e&&(e=oo(e));const t=(await this.getTracks()).filter(e=>e.isAudioTrack());return lo(t,e)}async getPrimaryVideoTrack(e){e&&(e=oo(e));const t=co(e,{sortBy:async e=>[no((await e.getDisposition()).default),no(await e.hasPairableAudioTrack()),no(!(await e.hasOnlyKeyPackets())),so(await e.getBitrate())]});return(await this.getVideoTracks(t))[0]??null}async getPrimaryAudioTrack(e){e&&(e=oo(e));const t=await this.getPrimaryVideoTrack(),i=co(e,{sortBy:async e=>[no(!t||e.canBePairedWith(t)),no((await e.getDisposition()).default),so(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 ro(this,e):new ao(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 go extends Error{constructor(e="Input has an unsupported or unrecognizable format."){super(e),this.name="UnsupportedInputFormatError"}}class ko extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}}class yo{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 ko;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 bo(t,g(t),0,e,e)}const i=e+t,r=this.source._read(e,i,0,es);return de(r)?r.then(t=>t?new bo(t.bytes,t.view,t.offset,e,i):null):r?new bo(r.bytes,r.view,r.offset,e,i):null}requestSliceRange(e,t,i){if(this.source._disposed)throw new ko;if(e<0)return null;if(null!==this.fileSizeNonStrict)return this.requestSlice(e,H(this.fileSizeNonStrict-e,t,i));{const r=this.requestSlice(e,i),a=r=>r||(l(null!==this.fileSizeNonStrict),this.requestSlice(e,H(this.fileSizeNonStrict-e,t,i)));return de(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(de(i)&&(i=await i),!i||0===i.length)break;const r=To(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 bo(i,g(i),0,0,t)})()}}class bo{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 bo(e,g(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 bo(this.bytes,this.view,this.offset,e,e+t)}}const wo=(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.`)},To=(e,t)=>{wo(e,t);const i=e.bytes.subarray(e.bufferPos,e.bufferPos+t);return e.bufferPos+=t,i},So=e=>(wo(e,1),e.view.getUint8(e.bufferPos++)),vo=(e,t)=>{wo(e,2);const i=e.view.getUint16(e.bufferPos,t);return e.bufferPos+=2,i},Po=e=>{wo(e,2);const t=e.view.getUint16(e.bufferPos,!1);return e.bufferPos+=2,t},Io=e=>{wo(e,3);const t=U(e.view,e.bufferPos,!1);return e.bufferPos+=3,t},xo=e=>{wo(e,2);const t=e.view.getInt16(e.bufferPos,!1);return e.bufferPos+=2,t},Co=(e,t)=>{wo(e,4);const i=e.view.getUint32(e.bufferPos,t);return e.bufferPos+=4,i},Bo=e=>{wo(e,4);const t=e.view.getUint32(e.bufferPos,!1);return e.bufferPos+=4,t},Eo=e=>{wo(e,4);const t=e.view.getUint32(e.bufferPos,!0);return e.bufferPos+=4,t},_o=e=>{wo(e,4);const t=e.view.getInt32(e.bufferPos,!1);return e.bufferPos+=4,t},Ro=(e,t)=>{let i,r;return t?(i=Co(e,!0),r=Co(e,!0)):(r=Co(e,!1),i=Co(e,!1)),4294967296*r+i},Fo=e=>4294967296*Bo(e)+Bo(e),Ao=e=>4294967296*_o(e)+Bo(e),Do=e=>{const t=Eo(e),i=(e=>{wo(e,4);const t=e.view.getInt32(e.bufferPos,!0);return e.bufferPos+=4,t})(e);return 4294967296*i+t},Mo=e=>{wo(e,4);const t=e.view.getFloat32(e.bufferPos,!1);return e.bufferPos+=4,t},No=e=>{wo(e,8);const t=e.view.getFloat64(e.bufferPos,!1);return e.bufferPos+=8,t},Oo=(e,t)=>{wo(e,t);let i="";for(let r=0;rk.decode(To(e,t)).split("\n").map(e=>e.trim()).filter(e=>e.length>0&&!i?.ignore?.(e));var zo,Uo,qo,Wo;(Uo=zo||(zo={}))[Uo.Unsynchronisation=128]="Unsynchronisation",Uo[Uo.ExtendedHeader=64]="ExtendedHeader",Uo[Uo.ExperimentalIndicator=32]="ExperimentalIndicator",Uo[Uo.Footer=16]="Footer",(Wo=qo||(qo={}))[Wo.ISO_8859_1=0]="ISO_8859_1",Wo[Wo.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",Wo[Wo.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",Wo[Wo.UTF_8=3]="UTF_8";const Ho=128,Vo=10,jo=["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"],Ko=(e,t)=>{var i;const r=e.filePos;t.raw??(t.raw={}),(i=t.raw).TAG??(i.TAG=To(e,Ho-3)),e.filePos=r;const a=Xo(e,30);a&&(t.title??(t.title=a));const s=Xo(e,30);s&&(t.artist??(t.artist=s));const n=Xo(e,30);n&&(t.album??(t.album=n));const o=Xo(e,4),c=Number.parseInt(o,10);Number.isInteger(c)&&c>0&&(t.date??(t.date=new Date(String(c))));const l=To(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=Xo(e,28),e.skip(2)}else e.skip(-30),u=Xo(e,30);u&&(t.comment??(t.comment=u));const d=So(e);d{const i=To(e,t),r=he(i.indexOf(0),i.length),a=i.subarray(0,r);let s="";for(let n=0;n{const t=e.filePos,i=Oo(e,3),r=So(e),a=So(e),s=So(e),n=Bo(e);if("ID3"!==i||255===r||255===a||0!==(2155905152&n))return e.filePos=t,null;let o=gi(n);return s&zo.Footer&&(o+=Vo),{majorVersion:r,revision:a,flags:s,size:o}},Go=(e,t,i)=>{var r,a,s,n,o;if(![2,3,4].includes(t.majorVersion))return void xe._warn(`Unsupported ID3v2 major version: ${t.majorVersion}`);const c=t.flags&zo.Footer?t.size-Vo:t.size,l=To(e,c),u=new Qo(t,l);if(t.flags&zo.Unsynchronisation&&3===t.majorVersion&&u.ununsynchronizeAll(),t.flags&zo.ExtendedHeader){const e=u.readU32();3===t.majorVersion?u.pos+=e:u.pos+=e-4}for(;u.pos<=u.bytes.length-u.frameHeaderSize();){const e=u.readId3V2Frame();if(!e)break;const c=u.pos,l=u.pos+e.size;let d=!1,h=!1,f=!1;if(3===t.majorVersion?(d=!!(64&e.flags),h=!!(128&e.flags)):4===t.majorVersion&&(d=!!(4&e.flags),h=!!(8&e.flags),f=!!(2&e.flags)||!!(t.flags&zo.Unsynchronisation)),d)xe._warn(`Skipping encrypted ID3v2 frame ${e.id}`),u.pos=l;else if(h)xe._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!==jo[e]){i.genre??(i.genre=jo[e]);break}}if(t=/^\d+$/.exec(e),t){const e=Number.parseInt(t[0]);if(void 0!==jo[e]){i.genre??(i.genre=jo[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 Qo{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:gi(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 qo.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=he(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=he(r.findIndex(e=>0===e),r.length);return this.pos=i+Math.min(e+1,r.length),k.decode(r.subarray(0,e))}case qo.UTF_16_BE_NO_BOM:{const e=new TextDecoder("utf-16be"),t=he(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 qo.UTF_8:{const e=he(r.findIndex(e=>0===e),r.length);return this.pos=i+Math.min(e+1,r.length),k.decode(r.subarray(0,e))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";const t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}}class Yo{constructor(e){this.events=e,this.input=null,this.audioSink=null,this.audioIterator=null,this.audioContext=null,this.gainNode=null,this.audioContextStartTime=0,this.playbackTimeAtStart=0,this.latestScheduledEndTime=0,this.duration=Number.NaN,this.paused=!0,this.volume=.7,this.muted=!1,this.playbackRate=1,this.asyncId=0,this.queuedNodes=new Set}get currentTime(){return this.paused?this.playbackTimeAtStart:(this.audioContext.currentTime-this.audioContextStartTime)*this.playbackRate+this.playbackTimeAtStart}ensureAudioContext(e){if(this.audioContext)return;const t=window.AudioContext||window.webkitAudioContext;try{this.audioContext=new t({sampleRate:e})}catch{this.audioContext=new t}this.gainNode=this.audioContext.createGain(),this.gainNode.connect(this.audioContext.destination),this.updateGain()}updateGain(){if(!this.gainNode)return;const e=this.muted?0:this.volume;this.gainNode.gain.value=e*e}stopQueuedNodes(){this.queuedNodes.forEach(e=>e.stop()),this.queuedNodes.clear()}async stopIterator(){await(this.audioIterator?.return()),this.audioIterator=null}handleNoAudioTrack(){this.audioSink=null,this.ensureAudioContext()}async load(e,t){++this.asyncId,await this.stopIterator(),this.stopQueuedNodes(),this.paused=!0,this.playbackTimeAtStart=0,this.audioContextStartTime=0;const{input:i,audioTrack:r,duration:a}=e;return this.input=i,this.duration=a,r?null!==r.codec&&await r.canDecode()?(this.ensureAudioContext(r.sampleRate),this.audioSink=new Zn(r),void t?.()):(this.audioSink=null,this.ensureAudioContext(),void t?.()):(this.handleNoAudioTrack(),void t?.())}async runIterator(e){if(!this.audioSink)return;await this.stopIterator(),this.audioIterator=this.audioSink.buffers(this.currentTime);for(;;){if(e!==this.asyncId||this.paused)return;const i=[];let r=!1;try{for(let e=0;e<16;e++){const e=await this.audioIterator.next();if(e.done){r=!0;break}i.push(e.value)}}catch(t){console.error("Audio iterator error:",t),r=!0}if(e!==this.asyncId||this.paused)return;i.length>0&&"suspended"===this.audioContext.state&&(await this.audioContext.resume(),this.events.emit("canplay"),this.events.emit("playing"));for(const{buffer:e,timestamp:t}of i){const i=this.audioContext.createBufferSource();i.buffer=e,i.connect(this.gainNode),i.playbackRate.value=this.playbackRate;const r=this.audioContextStartTime+(t-this.playbackTimeAtStart)/this.playbackRate,a=(r+e.duration/this.playbackRate-this.audioContextStartTime)*this.playbackRate+this.playbackTimeAtStart;a>this.latestScheduledEndTime&&(this.latestScheduledEndTime=a),r>=this.audioContext.currentTime?i.start(r):i.start(this.audioContext.currentTime,(this.audioContext.currentTime-r)*this.playbackRate),this.queuedNodes.add(i),i.onended=()=>this.queuedNodes.delete(i)}if(r)break;await new Promise(e=>setTimeout(e,0));const a=1;for(;this.latestScheduledEndTime-this.currentTime>a;){if(e!==this.asyncId||this.paused)return;await new Promise(e=>setTimeout(e,50))}}}async play(){if(!this.paused)return;this.audioContext||this.ensureAudioContext(),"suspended"===this.audioContext.state&&await this.audioContext.resume(),this.audioContextStartTime=this.audioContext.currentTime,this.latestScheduledEndTime=this.playbackTimeAtStart,this.paused=!1;const e=++this.asyncId;this.runIterator(e)}pause(){this.paused||(this.playbackTimeAtStart=this.currentTime,this.paused=!0,this.stopIterator(),this.stopQueuedNodes())}async seek(e){this.playbackTimeAtStart=Math.max(0,e),this.audioContextStartTime=this.audioContext.currentTime,this.latestScheduledEndTime=this.playbackTimeAtStart;const t=++this.asyncId;this.paused||this.runIterator(t)}setVolume(e,t){this.volume=e,this.muted=t,this.updateGain()}setPlaybackRate(e){if(e!==this.playbackRate&&(this.paused||(this.playbackTimeAtStart=this.currentTime,this.audioContextStartTime=this.audioContext.currentTime),this.playbackRate=e,!this.paused)){const e=++this.asyncId;this.runIterator(e)}}destroy(){this.asyncId++,this.pause(),this.audioContext?.close(),this.audioContext=null,this.input=null,this.audioSink=null}}async function Jo(e){return await e.getAverageBitrate()??await e.getBitrate()??0}const Zo=/\.m3u8(?:$|[?#])/i;function ec(e){return"string"===typeof e&&Zo.test(e)}function tc(e){const t=function(e){return"string"===typeof e?new us(e):e instanceof Blob?new os(e):"undefined"!==typeof ReadableStream&&e instanceof ReadableStream?new fs(e):e??null}(e);return t?new po({source:t,formats:ec(e)?en:Zs}):null}class ic{constructor(){this.active=!0,this.input=null,this.timers=new Set,this.controller="undefined"===typeof AbortController?void 0:new AbortController,this.cancellation=new Promise(e=>{this.resolveCancellation=e})}get signal(){return this.controller?.signal}own(e){this.active?this.input=e:e.dispose()}defer(e){if(!this.active)return;const t=setTimeout(()=>{this.timers.delete(t),this.active&&e()},0);this.timers.add(t)}async wait(e,t){try{await Promise.race([e,this.cancellation,t>0?this.timeout(t):new Promise(()=>{})])}finally{void 0!==this.deadline&&(clearTimeout(this.deadline),this.deadline=void 0)}}timeout(e){return new Promise((t,i)=>{this.deadline=setTimeout(()=>i(new Error("Load timeout")),e)})}disposeInput(){const e=this.input;this.input=null,e?.dispose()}cancel(){if(this.active){this.active=!1;for(const e of this.timers)clearTimeout(e);this.timers.clear(),void 0!==this.deadline&&(clearTimeout(this.deadline),this.deadline=void 0),this.resolveCancellation(),this.controller?.abort(),this.disposeInput()}}}function rc(e,t,i){for(const r of i){if(!t())return;e.emit(r)}}async function ac({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 sc(){let e,t;return{promise:new Promise((i,r)=>{e=i,t=r}),resolve:e,reject:t}}class nc{constructor(e){this.host=e,this.wanted=!1,this.playing=null,this.seeking=null,this.audioStart=null}operation(){return{...sc(),source:this.host.loadSeq,complete:sc()}}current(e,t){return!this.host.destroyed&&e.source===this.host.loadSeq&&this[t]===e}cancelPlay(){const e=this.playing;this.playing=null,e?.resolve()}invalidate(){this.cancelPlay(),this.wanted=!1;const e=this.seeking;this.seeking=null,e?.complete.resolve(),e?.resolve(),this.host.seeking=!1}ended(){this.wanted=!1,this.cancelPlay()}stop(){this.host.paused||(this.host.paused=!0,this.stopEngines(),this.host.events.emit("pause"))}stopEngines(){const e=[];for(const i of[()=>this.host.audio.pause(),()=>this.host.video.stop()])try{i()}catch(t){e.push(t)}if(e.length)throw e[0]}pause(){this.wanted=!1,this.cancelPlay(),this.stop()}play(){if(this.host.destroyed)return Promise.resolve();if(this.wanted=!0,this.playing)return this.playing.promise;if(this.host.ended)return this.seek(0,!0);if(!this.host.paused&&!this.seeking)return Promise.resolve();const e=this.operation();return this.playing=e,this.runPlay(e).then(e.resolve,e.reject),e.promise}async startAudio(){this.audioStart||(this.audioStart=this.host.audio.play());const e=this.audioStart;try{await e}finally{this.audioStart===e&&(this.audioStart=null)}}async runPlay(e){const t=()=>this.current(e,"playing")&&this.wanted;try{for(;this.seeking;)if(await this.seeking.complete.promise,!t())return;if(!t())return;if(this.host.paused=!1,await this.startAudio(),!t())return void(this.wanted&&!this.host.destroyed||this.host.audio.pause());this.host.video.start(this.host.audio),rc(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 ac(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,rc(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(),rc(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()}}class oc{constructor({canvas:e,ctx:t,events:i,timeupdateInterval:r=250,avSyncTolerance:a=.12,dropLateFrames:s=!1,poster:n="",preflightRange:o=!1}){this.canvas=e,this.ctx=t,this.events=i,this.timeupdateInterval=r,this.avSyncTolerance=a,this.dropLateFrames=s,this.poster=n,this.preflightRange=o,this.input=null,this.videoSink=null,this.videoIterator=null,this.nextFrame=null,this.rafId=0,this.asyncId=0,this.width=0,this.height=0,this.duration=Number.NaN,this.audioClock=null,this.lastTimeUpdate=0,this.stalled=!1,this.playbackRate=1,this.posterDrawn=!1,this.isFetching=!1}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||ec(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(!this.poster||this.posterDrawn)return;const e=new Image;e.onload=()=>{this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.canvas.width=e.naturalWidth||this.canvas.width,this.canvas.height=e.naturalHeight||this.canvas.height,this.ctx.drawImage(e,0,0,this.canvas.width,this.canvas.height),this.posterDrawn=!0},e.src=this.poster}async stopIterator(){await(this.videoIterator?.return()),this.videoIterator=null}clear(){this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height)}async load(e,t){++this.asyncId,await this.stopIterator(),this.clear(),this.posterDrawn=!1;const{input:i,videoTrack:r,duration:a}=e;if(this.input=i,this.duration=a,!r)return this.handleNoVideoTrack(),void t?.();if(null===r.codec||!(await r.canDecode()))return this.handleNoVideoTrack(),void t?.();const s=await r.canBeTransparent();this.videoSink=new Gn(r,{poolSize:2,fit:"contain",alpha:s}),this.width=r.displayWidth,this.height=r.displayHeight,this.canvas.width=this.width,this.canvas.height=this.height,t?.(),await this.resetIterator(0)}handleNoVideoTrack(){this.videoSink=null,this.width=0,this.height=0,this.canvas.width=0,this.canvas.height=0,this.clear(),this.drawPoster()}async resetIterator(e){if(await this.stopIterator(),!this.videoSink)return;this.videoIterator=this.videoSink.canvases(e);const t=(await this.videoIterator.next()).value??null,i=(await this.videoIterator.next()).value??null;this.nextFrame=i,t?this.ctx.drawImage(t.canvas,0,0):this.drawPoster()}async updateNextFrame(e){if(this.videoIterator&&!this.isFetching){this.isFetching=!0;try{for(;;){const t=(await this.videoIterator.next()).value??null;if(!t||e!==this.asyncId)return;const i=this.audioClock.currentTime,r=this.dropLateFrames?Math.max(.06,this.avSyncTolerance/Math.max(1,this.playbackRate)):0;if(!(this.dropLateFrames&&t.timestampi)return void(this.nextFrame=null)}}}finally{this.isFetching=!1}}}render(){if(!this.audioClock)return;const e=this.audioClock.currentTime,t=Date.now();if(t-this.lastTimeUpdate>=this.timeupdateInterval&&(this.events.emit("timeupdate"),this.lastTimeUpdate=t),Number.isFinite(this.duration)&&e>=this.duration)return this.stop(),this.stalled=!1,this.events.emit("ended"),this.events.emit("pause"),void this.events.emit("canplay");this.nextFrame&&this.nextFrame.timestamp<=e?(this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.ctx.drawImage(this.nextFrame.canvas,0,0),this.nextFrame=null,this.updateNextFrame(this.asyncId),this.stalled&&(this.events.emit("canplay"),this.events.emit("playing"),this.stalled=!1)):this.nextFrame||(this.updateNextFrame(this.asyncId),!this.nextFrame&&Number.isFinite(this.duration)&&ethis.render())}start(e){this.audioClock=e,this.asyncId++,this.stalled=!1,this.updateNextFrame(this.asyncId),this.rafId=requestAnimationFrame(()=>this.render())}stop(){cancelAnimationFrame(this.rafId)}async seek(e){this.asyncId++,await this.resetIterator(e)}setPlaybackRate(e){this.playbackRate=Math.max(.1,Number(e)||1)}destroy(){this.asyncId++,this.stop(),this.stopIterator(),this.posterDrawn=!1,this.videoSink=null,this.input=null}}class cc{constructor({canvas:e,ctx:i,events:r,option:o={}}){s(this,t),this.events=r,this.option=o,this.audio=new Yo(r),this.video=new oc({canvas:e,ctx:i,events:r,timeupdateInterval:o.timeupdateInterval??250,avSyncTolerance:o.avSyncTolerance??.12,dropLateFrames:o.dropLateFrames??!1,poster:o.poster??"",preflightRange:o.preflightRange??!1}),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,n(this,t,new nc(this)),r.addEventListener("ended",()=>{this.destroyed||(this.ended=!0,this.paused=!0,a(this,t).ended())})}async load(e){if(this.destroyed)return;const i=++this.loadSeq;if(a(this,t).invalidate(),this.loadSession?.cancel(),i!==this.loadSeq||this.destroyed)return;if(this.pause(),i!==this.loadSeq||this.destroyed)return;this.disposeInput();const r=new ic;this.loadSession=r,this.ended=!1,this.error=null,this.networkState=2,this.readyState=0,r.defer(()=>this.events.emit("waiting")),r.defer(()=>this.events.emit("loadstart"));const s=Number.isFinite(this.option.loadTimeout)?this.option.loadTimeout??0:0;try{await r.wait(this.performLoad(e,i,r),s)}catch(n){if(i!==this.loadSeq)return;const e=++this.loadSeq;if(a(this,t).invalidate(),r.cancel(),e!==this.loadSeq||this.destroyed)return;this.disposeInput(),this.reportError(n)}}async performLoad(e,t,i=this.loadSession){const r=()=>!this.destroyed&&t===this.loadSeq;if(!i||!(await this.video.preflight(e,i.signal,r))||!r())return;const a=tc(e);if(!a)return this.video.handleNoVideoTrack(),void(r()&&this.audio.handleNoAudioTrack());i.own(a);const s=await async function(e,t){const i=await e.getPrimaryVideoTrack(),r=i?await i.getPrimaryPairableAudioTrack():await e.getPrimaryAudioTrack(),a=await ac({input:e,videoTrack:i,audioTrack:r}),s=i||r,n=ec(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,rc(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,rc(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 a(this,t).replace({...this.media,...e},this.currentTime)}async selectHlsQuality(e){return async function(e,t){const{input:i,media:r,loadSeq:a}=e;if(!r?.isHls||!i||e.destroyed)return;const s=()=>!e.destroyed&&e.loadSeq===a&&e.input===i&&e.media===r;let n;try{const e=await i.getVideoTracks();if(!s())return;const a="auto"===t?await i.getPrimaryVideoTrack():e.find(e=>e.id===t)??r.videoTrack;if(!s()||!a)return;let o=r.audioTrack,c=r.audioMode;o&&a.canBePairedWith(o)||(o=await a.getPrimaryPairableAudioTrack(),c="auto"),n={videoTrack:a,audioTrack:o,videoMode:"auto"===t?"auto":"manual",audioMode:c}}catch(o){if(!s())return;throw o}s()&&await e.replaceTracks(n)}(this,e)}async selectHlsAudio(e){return async function(e,t){const{input:i,media:r,loadSeq:a}=e;if(!r?.isHls||!i||e.destroyed)return;const s=()=>!e.destroyed&&e.loadSeq===a&&e.input===i&&e.media===r;let n;try{const e=await i.getAudioTracks();if(!s())return;const a="auto"===t?r.videoTrack?await r.videoTrack.getPrimaryPairableAudioTrack():await i.getPrimaryAudioTrack():e.find(e=>e.id===t)??r.audioTrack;if(!s()||!a)return;let o=r.videoTrack,c=r.videoMode;o&&a.canBePairedWith(o)||(o=await a.getPrimaryPairableVideoTrack(),c="auto"),n={videoTrack:o,audioTrack:a,videoMode:c,audioMode:"auto"===t?"auto":"manual"}}catch(o){if(!s())return;throw o}s()&&await e.replaceTracks(n)}(this,e)}async getHlsState(){const e=this.media;if(this.destroyed)return null;try{const t=await async function(e){if(!e?.isHls||!e.input)return null;const[t,i]=await Promise.all([e.input.getVideoTracks(),e.videoTrack?e.videoTrack.getPairableAudioTracks():[]]),[r,a]=await Promise.all([Promise.all(t.map(async(e,t)=>({id:e.id,track:e,index:t,name:await e.getName(),height:await e.getDisplayHeight(),bitrate:await Jo(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 Jo(e)}}))]);return{levels:r,audios:a,currentLevel:e.videoTrack?r.find(t=>t.id===e.videoTrack?.id)??null:null,currentAudio:e.audioTrack?a.find(t=>t.id===e.audioTrack?.id)??null:null,videoMode:e.videoMode??"auto",audioMode:e.audioMode??"auto"}}(e);return this.destroyed||this.media!==e?null:t}catch(t){if(this.destroyed||this.media!==e)return null;throw t}}async play(){return a(this,t).play()}pause(){a(this,t).pause()}async seek(e){return a(this,t).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++,a(this,t).invalidate();const e=[];for(const t of[()=>this.loadSession?.cancel(),()=>this.pause(),()=>this.disposeInput(),()=>this.audio.destroy(),()=>this.video.destroy()])try{t()}catch(i){e.push(i)}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}}t=new WeakMap;const lc=new WeakMap;function uc(e){let t=lc.get(e);return t||(t={closed:!1,frames:new Set},lc.set(e,t)),t}class dc{constructor({art:e,canvas:t,ctx:i,option:r}){this.art=e,this.canvas=t,this.option=r,this.events=new c,this.engine=new cc({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=uc(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){uc(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=uc(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 dc({art:t,canvas:a,ctx:s,option:e});t.mediabunny=n;const c={};for(const e in a)"function"===typeof a[e]&&(c[e]=a[e].bind(a));const l=new Set([...Object.getOwnPropertyNames(n),...Object.getOwnPropertyNames(Object.getPrototypeOf(n))]);for(const e of l)"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 c)a[e]=(...t)=>c[e](...t);function u(){const e=t.template?.$player;e&&!t.option.autoSize&&Object.assign(a.style,{width:"100%",height:"100%",objectFit:"contain"})}return t.on("resize",u),t.on("video:loadedmetadata",u),function({art:e,shim:t,option:i}){if(i.m3u8)return e.on("video:loadedmetadata",d),e.on("restart",d),{update:d};function r(t){e.controls.cache.has(t)&&e.controls.remove(t)}function a(t){e.setting.find(t)&&e.setting.remove(t)}function s(){r("mediabunny-quality"),a("mediabunny-quality")}function n(){r("mediabunny-audio"),a("mediabunny-audio")}function c(e={}){return e.control||e.setting}async function l(r){const a=i.m3u8?.quality||{};if(!c(a)||!r?.levels.length)return void s();const n=a.auto||"Auto",l=a.title||"Quality",u=a.getName||(e=>e.name||`${e.height}P`),h=r.currentLevel?u(r.currentLevel):n,f=o(r.levels.map(e=>({html:u(e),value:e.id,default:r.currentLevel?.id===e.id})),"html").sort((e,t)=>{const i=r.levels.find(t=>t.id===e.value),a=r.levels.find(e=>e.id===t.value);return(a?.height||0)-(i?.height||0)});f.push({html:n,value:"auto",default:!r.currentLevel});const m=async i=>(await t.switchM3u8Quality(i.value),e.notice.show=`${l}: ${i.html}`,await d(),i.html);a.control&&e.controls.update({name:"mediabunny-quality",position:"right",html:h,style:{padding:"0 10px"},selector:f,onSelect:m}),a.setting&&e.setting.update({name:"mediabunny-quality",tooltip:h,html:l,icon:'',width:200,selector:f,onSelect:m})}async function u(r){const a=i.m3u8?.audio||{};if(!c(a)||!r?.audios.length||r.audios.length<2)return void n();const s=a.auto||"Auto",l=a.title||"Audio",u=a.getName||(e=>e.name||e.lang||e.language),h=r.currentAudio?u(r.currentAudio):s,f=o(r.audios.map(e=>({html:u(e),value:e.id,default:r.currentAudio?.id===e.id})),"html");f.push({html:s,value:"auto",default:!r.currentAudio});const m=async i=>(await t.switchM3u8Audio(i.value),e.notice.show=`${l}: ${i.html}`,await d(),i.html);a.control&&e.controls.update({name:"mediabunny-audio",position:"right",html:h,style:{padding:"0 10px"},selector:f,onSelect:m}),a.setting&&e.setting.update({name:"mediabunny-audio",tooltip:h,html:l,icon:'',width:200,selector:f,onSelect:m})}async function d(){const e=await t.getM3u8State();if(!e)return s(),void n();await Promise.all([l(e),u(e)])}}({art:t,shim:n,option:e}),t.on("destroy",()=>{delete t.mediabunny,n.destroy()}),a}}}); diff --git a/docs/compiled/artplayer-proxy-mediabunny.legacy.js b/docs/compiled/artplayer-proxy-mediabunny.legacy.js index 4553fb5d8..3968b5b32 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=Object.defineProperty,i=Object.defineProperties,r=Object.getOwnPropertyDescriptors,n=Object.getOwnPropertySymbols,s=Object.prototype.hasOwnProperty,a=Object.prototype.propertyIsEnumerable,o=(e,t)=>(t=Symbol[e])?t:Symbol.for("Symbol."+e),l=e=>{throw TypeError(e)},c=Math.pow,u=(e,i,r)=>i in e?t(e,i,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[i]=r,d=(e,t)=>{for(var i in t||(t={}))s.call(t,i)&&u(e,i,t[i]);if(n)for(var i of n(t))a.call(t,i)&&u(e,i,t[i]);return e},h=(e,t)=>i(e,r(t)),f=(e,t,i)=>t.has(e)||l("Cannot "+i),m=(e,t,i)=>(f(e,t,"read from private field"),i?i.call(e):t.get(e)),p=(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())}),g=function(e,t){this[0]=e,this[1]=t},k=(e,t,i)=>{var r,n=(e,t,r,s)=>{try{var a=i[e](t),o=(t=a.value)instanceof g,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[o("asyncIterator")]=()=>a,s("next"),s("throw"),s("return"),a},y=e=>{var t,i=e[o("asyncIterator")],r=!1,n={};return null==i?(i=e[o("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 g(new Promise(r=>{var n=i[e](t);n instanceof Object||l("Object expected"),r(n)}),1)}}),n[o("iterator")]=()=>n,t("next"),"throw"in i?t("throw"):n.throw=e=>{throw e},"return"in i&&t("return"),n},b=(e,t,i)=>(t=e[o("asyncIterator")])?t.call(e):(e=e[o("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 T(e,t){const i=new Map;return e.filter(e=>{const r=e[t];return void 0===r||!i.has(r)&&i.set(r,1)})}class v{constructor(){var t,i,r;t=this,r=!1,(i=e).has(t)?l("Cannot add the same private member more than once"):i instanceof WeakSet?i.add(t):i.set(t,r),this.listeners=new Map}addEventListener(t,i){var r;m(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(m(this,e))return;const n=Object.assign(new Event(t),{detail:i});null==(r=this.listeners.get(t))||r.forEach(t=>{m(this,e)||t(n)})}destroy(){var t,i,r,n;r=!0,f(t=this,i=e,"write to private field"),n?n.call(t,r):i.set(t,r),this.listeners.clear()}}function S(e){if(!e)throw new Error("Assertion failed.")}e=new WeakMap;const w=e=>{const t=(e%360+360)%360;if(0===t||90===t||180===t||270===t)return t;throw new Error(`Invalid rotation ${e}.`)},P=e=>e&&e[e.length-1],I=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-c(2,r))},C=e=>{const t=I(e);return 0===(1&t)?-(t>>1):t+1>>1},B=e=>e.constructor===Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),E=e=>e.constructor===DataView?e:ArrayBuffer.isView(e)?new DataView(e.buffer,e.byteOffset,e.byteLength):new DataView(e),_=new TextDecoder,R=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])),F={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},A=R(F),D={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},M=R(D),N={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},O=R(N),L=e=>!!e&&!!e.primaries&&!!e.transfer&&!!e.matrix&&void 0!==e.fullRange,z={primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0},U=e=>e instanceof ArrayBuffer||"undefined"!==typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e);class q{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}acquire(){return p(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 W=/^[0-9a-fA-F]+$/,H=e=>[...e].map(e=>e.toString(16).padStart(2,"0")).join(""),V=e=>(e=(e=(e=(e=(e=e>>1&1431655765|(1431655765&e)<<1)>>2&858993459|(858993459&e)<<2)>>4&252645135|(252645135&e)<<4)>>8&16711935|(16711935&e)<<8)>>16&65535|(65535&e)<<16)>>>0,j=(e,t,i)=>{let r=0,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},X=(e,t,i)=>{const r=K(e,i(t),i);e.splice(r+1,0,t)},$=()=>{let e,t;return{promise:new Promise((i,r)=>{e=i,t=r}),resolve:e,reject:t}},G=(e,t)=>{const i=e.indexOf(t);-1!==i&&e.splice(i,1)},Q=(e,t)=>{for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},Y=(e,t)=>{for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},J=e=>{throw new Error(`Unexpected value: ${e}`)},Z=(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},ee=(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)},te=(e,t)=>({next(){return p(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}}),ie=(e,t,i)=>Math.max(t,Math.min(i,e)),re="und",ne=e=>{const t=Math.round(e);return Math.abs(e/t-1)<10*Number.EPSILON?t:e},se=(e,t)=>Math.round(e/t)*t,ae=(e,t)=>Math.round(e*t)/t,oe=(e,t)=>Math.floor(e/t)*t,le=e=>{let t=0;for(;0!==e;)e&=e-1,t++;return t},ce=/^[a-z]{3}$/,ue=e=>ce.test(e),de=1e6*(1+Number.EPSILON),he=(e,t)=>{const i=d(d({},e),t);if(e.headers||t.headers){const r=e.headers?fe(e.headers):{},n=t.headers?fe(t.headers):{},s=d({},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},fe=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},me=(e,t,i,r,n)=>p(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(ze._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 Me(1e3*e)),n())throw a}});class pe{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}let ge=null;const ke=()=>{var e;return null!==ge?ge:ge=!("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 ye=null;const be=()=>{var e;return null!==ye?ye:ye="undefined"!==typeof navigator&&(null==(e=navigator.userAgent)?void 0:e.includes("Firefox"))};let Te=null;const ve=()=>{var e;return null!==Te?Te:Te=!("undefined"===typeof navigator||!(null==(e=navigator.vendor)?void 0:e.includes("Google Inc"))&&!/Chrome/.test(navigator.userAgent))},Se=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.`,we=p(null,null,function*(){}).constructor,Pe=e=>e instanceof we||e instanceof Promise||"function"===typeof(null==e?void 0:e.then),Ie=(e,t)=>-1!==e?e:t,xe=(e,t,i,r)=>e<=r&&i<=t,Ce=e=>{const t=atob(e),i=new Uint8Array(t.length);for(let r=0;r{null!=Symbol.dispose||(Symbol.dispose=Symbol("Symbol.dispose"))},Ee=e=>"number"===typeof e&&!Number.isNaN(e),_e=(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("/")},Re=(e,t)=>{let i=0;for(let r=0;r{let i=-1,r=1/0;for(let n=0;n{S(Number.isInteger(e.num)),S(Number.isInteger(e.den)),S(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}},De=(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.`)},Me=e=>new Promise(t=>setTimeout(t,e));class Ne{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 Oe,Le;(Le=Oe||(Oe={}))[Le.Silent=0]="Silent",Le[Le.Errors=1]="Errors",Le[Le.Warnings=2]="Warnings",Le[Le.Info=3]="Info";class ze{constructor(){}static get level(){return ze._level}static set level(e){if(e!==Oe.Silent&&e!==Oe.Errors&&e!==Oe.Warnings&&e!==Oe.Info)throw new TypeError("Invalid log level. Use one of the values of the LogLevel enum.");ze._level=e}static get _emitter(){var e;return null!=(e=ze._emitterInstance)?e:ze._emitterInstance=new Ne}static on(e,t,i){return ze._emitter.on(e,t,i)}static _error(...e){ze._emitter._emit("error",e),ze._level>=Oe.Errors&&console.error(...e)}static _warn(...e){ze._emitter._emit("warn",e),ze._level>=Oe.Warnings&&console.warn(...e)}static _info(...e){ze._emitter._emit("info",e),ze._level>=Oe.Info&&console.info(...e)}}ze._level=Oe.Info,ze._emitterInstance=null;class Ue{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 qe{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 We={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1};class He{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 He(this.bytes);return e.pos=this.pos,e}}const Ve=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],je=[-1,1,2,3,4,5,6,8],Ke=e=>{if(!e||e.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");const t=new He(e),i=Xe(t),{frequencyIndex:r,sampleRate:n}=$e(t),s=t.readBits(4);let a=null;s>=1&&s<=7&&(a=je[s]);let o=i,l=!1,c=n;if(5===i||29===i)l=29===i,c=$e(t).sampleRate,o=Xe(t),22===o&&t.skipBits(4);else for(;t.getBitsLeft()>15;){const e=t.pos;if(695===t.readBits(11)){5===Xe(t)&&t.readBits(1)&&(c=$e(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}},Xe=e=>{const t=e.readBits(5);return 31===t?32+e.readBits(6):t},$e=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&B(t.description)[4];return it(e,i+1)}return tt(e)},nt=e=>31&e,st=e=>{const t=[],i=e.length;for(let r=0;r{const t=e.reduce((e,t)=>e+at.byteLength+t.byteLength,0),i=new Uint8Array(t);let r=0;for(const n of e)i.set(at,r),r+=at.byteLength,i.set(n,r),r+=n.byteLength;return i},lt=(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:ee(e,n,s.byteLength);break;case 4:e.setUint32(n,s.byteLength,!1)}n+=t,r.set(s,n),n+=s.byteLength}return r},ct=e=>{try{const t=[],i=[],r=[];for(const o of tt(e)){const n=e.subarray(o.offset,o.offset+o.length),s=nt(n[0]);s===Ye.SPS?t.push(n):s===Ye.PPS?i.push(n):s===Ye.SPS_EXT&&r.push(n)}if(0===t.length)return null;if(0===i.length)return null;const n=t[0],s=ft(n);S(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 ze._error("Error building AVC Decoder Configuration Record:",t),null}},ut=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=E(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=st(e),r=new He(i);r.skipBits(1),r.skipBits(2);if(7!==r.readBits(5))return null;const n=r.readAlignedByte(),s=r.readAlignedByte(),a=r.readAlignedByte();I(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=I(r),3===o&&(u=r.readBits(1)),l=I(r),c=I(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:P(ui),n=Math.min(Math.floor(r.maxDpbMbs/(e*i)),16);B=n,E=n}else B=0,E=0}return S(null!==E),{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:x,colourPrimaries:b,matrixCoefficients:v,transferCharacteristics:T,fullRangeFlag:w,numReorderFrames:B,maxDecFrameBuffering:E,vuiParametersFlagBitOffset:F,bitstreamRestrictionFlagBitOffset:_,bitstreamRestrictionFlag:R}}catch(i){return ze._error("Error parsing AVC SPS:",i),null}},mt=e=>{const t=I(e);e.skipBits(4),e.skipBits(4);for(let i=0;i<=t;i++)I(e),I(e),e.skipBits(1);e.skipBits(5),e.skipBits(5),e.skipBits(5),e.skipBits(5)},pt=e=>{S(1!==e.bitstreamRestrictionFlag);const t=new Uint8Array(e.emulationUnpreventedBytes.byteLength+64),i=new He(e.emulationUnpreventedBytes),r=new He(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)):(S(null!==e.bitstreamRestrictionFlagBitOffset),r.copyBits(e.bitstreamRestrictionFlagBitOffset,i)),r.writeBits(1,1),r.writeBits(1,1),x(r,2),x(r,1),x(r,16),x(r,16),x(r,e.numReorderFrames),x(r,e.maxDecFrameBuffering),r.writeBits(1,1),r.writeBits((8-r.pos%8)%8,0);const n=r.pos/8;return S(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))},gt=(e,t)=>{if(t.description){const i=3&B(t.description)[21];return it(e,i+1)}return tt(e)},kt=e=>e>>1&63,yt=e=>{try{const t=new He(st(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}=Tt(t,i);I(t);const u=I(t);let d=0;3===u&&(d=t.readBits(1));const h=I(t),f=I(t);let m=h,p=f;if(t.readBits(1)){const e=I(t),i=I(t),r=I(t),n=I(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=I(t),k=I(t);I(t);const y=t.readBits(1);let b=0;for(let e=y?0:i;e<=i;e++)I(t),b=I(t),I(t);I(t),I(t),I(t),I(t),I(t),I(t),t.readBits(1)&&t.readBits(1)&&vt(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(4),t.skipBits(4),I(t),I(t),t.skipBits(1));const T=I(t);if(St(t,T),t.readBits(1)){const e=I(t);for(let i=0;i{try{const t=[],i=[],r=[],n=[];for(const l of tt(e)){const s=e.subarray(l.offset,l.offset+l.length),a=kt(s[0]);a===Ze.VPS_NUT?t.push(s):a===Ze.SPS_NUT?i.push(s):a===Ze.PPS_NUT?r.push(s):a!==Ze.PREFIX_SEI_NUT&&a!==Ze.SUFFIX_SEI_NUT||n.push(s)}if(0===i.length||0===r.length)return null;const s=yt(i[0]);if(!s)return null;let a=0;if(r.length>0){const e=r[0],t=new He(st(e));t.skipBits(16),I(t),I(t),t.skipBits(1),t.skipBits(1),t.skipBits(3),t.skipBits(1),t.skipBits(1),I(t),I(t),C(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&I(t),C(t),C(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:Ze.VPS_NUT,nalUnits:t}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:Ze.SPS_NUT,nalUnits:i}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:Ze.PPS_NUT,nalUnits:r}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:kt(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 ze._error("Error building HEVC Decoder Configuration Record:",t),null}},Tt=(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&&C(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-(I(e)+1)}else o=t-1;e.readBits(1),I(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=I(e),i=I(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=ht[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)&&(I(e),I(e)),e.readBits(1),e.readBits(1),e.readBits(1),e.readBits(1)&&(I(e),I(e),I(e),I(e)),e.readBits(1)&&(e.readBits(32),e.readBits(32),e.readBits(1)&&I(e),e.readBits(1)&&It(e,!0,t)),e.readBits(1)&&(e.readBits(1),e.readBits(1),e.readBits(1),a=I(e),I(e),I(e),I(e),I(e)),{pixelAspectRatio:o,colourPrimaries:i,transferCharacteristics:r,matrixCoefficients:n,fullRangeFlag:s,minSpatialSegmentationIdc:a}},It=(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?I(e):i=1===e.readBits(1);let a=1;if(!i){a=I(e)+1}r&&xt(e,a,s),n&&xt(e,a,s)}},xt=(e,t,i)=>{for(let r=0;r{const i=new Set;let r=Ct.audAllowed;for(const s of gt(e,t)){if(r===Ct.noMoreDataAllowed){i.add(s.offset);continue}const t=kt(e[s.offset]);if(r===Ct.eoBitstreamAllowed&&37!==t){i.add(s.offset);continue}let n=!1;35===t?r>Ct.audAllowed?n=!0:r=Ct.beforeFirstVcl:t<=31?r>Ct.afterFirstVcl?n=!0:r=Ct.afterFirstVcl:36===t?r!==Ct.afterFirstVcl?n=!0:r=Ct.eoBitstreamAllowed:37===t?r=41&&t<=44||t>=48&&t<=55?r>Ct.beforeFirstVcl?n=!0:r=Ct.beforeFirstVcl:(38===t||40===t||t>=45&&t<=47||t>=56&&t<=63)&&r{if(t.description){const i=3&B(t.description)[21];return lt(e,i+1)}return ot(e)})(n,t)},_t={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}},Rt=e=>{var t,i,r;const n=new He(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=P(di).level;for(const m of di)if(d<=m.maxPictureSize){h=m.level;break}const f=_t[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}},Ft=function*(e){const t=new He(e),i=()=>{let e=0;for(let i=0;i<8;i++){const r=t.readAlignedByte();if(e+=(127&r)*c(2,7*i),!(128&r))break;if(7===i&&128&r)return null}return e>c(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);S(t.pos%8===0),yield{type:r,data:e.subarray(t.pos/8,t.pos/8+a)},t.skipBits(8*a)}},At=e=>{for(const{type:t,data:i}of Ft(e)){if(1!==t)continue;const e=new He(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,S=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&&(S=e.readBits(2))),{profile:r,level:s,tier:a,bitDepth:m,monochrome:p,chromaSubsamplingX:T,chromaSubsamplingY:v,chromaSamplePosition:S,videoFullRangeFlag:b,colourPrimaries:g,transferCharacteristics:k,matrixCoefficients:y}}return null},Dt=e=>{if(e.length<36)return null;const t=E(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)}},Mt=[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],Nt=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}},Ot=(e,t,i)=>{switch(e){case"avc":for(const e of rt(i,t)){const t=i[e.offset],r=nt(t);if(r>=Ye.NON_IDR_SLICE&&r<=Ye.SLICE_DPC)return"delta";if(r===Ye.IDR)return"key";if(r===Ye.SEI&&!ve()){const t=i.subarray(e.offset,e.offset+e.length),r=st(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 He(r);e.pos=8*n;const t=I(e),i=e.readBits(1);if(0===t&&1===i)return"key"}n+=t}while(n{var i,r;const n=E(e);let s=0;const a=n.getUint32(s,!0);s+=4;const o=_.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=Ce(c),i=E(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=_.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})}}}},qt=[2,1,2,3,3,4,4,5],Wt=e=>{if(e.length<7)return null;if(11!==e[0]||119!==e[1])return null;const t=new He(e);t.skipBits(16),t.skipBits(16);const i=t.readBits(2);if(3===i)return null;const r=t.readBits(6),n=t.readBits(5);if(n>8)return null;const s=t.readBits(3),a=t.readBits(3);0!==(1&a)&&1!==a&&t.skipBits(2),0!==(4&a)&&t.skipBits(2),2===a&&t.skipBits(2);return{fscod:i,bsid:n,bsmod:s,acmod:a,lfeon:t.readBits(1),bitRateCode:Math.floor(r/2)}},Ht=[128,138,192,128,140,192,160,174,240,160,176,240,192,208,288,192,210,288,224,242,336,224,244,336,256,278,384,256,280,384,320,348,480,320,350,480,384,416,576,384,418,576,448,486,672,448,488,672,512,556,768,512,558,768,640,696,960,640,698,960,768,834,1152,768,836,1152,896,974,1344,896,976,1344,1024,1114,1536,1024,1116,1536,1280,1392,1920,1280,1394,1920,1536,1670,2304,1536,1672,2304,1792,1950,2688,1792,1952,2688,2048,2228,3072,2048,2230,3072,2304,2506,3456,2304,2508,3456,2560,2786,3840,2560,2788,3840],Vt=[1,2,3,6],jt=e=>{if(e.length<6)return null;if(11!==e[0]||119!==e[1])return null;const t=new He(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=Vt[s];let d;d=n<3?Ge[n]/1e3:Qe[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}]}},Kt=e=>{const t=e.substreams[0];return S(t),t.fscod<3?Ge[t.fscod]:null!==t.fscod2&&t.fscod2<3?Qe[t.fscod2]:null},Xt=e=>{const t=e.substreams[0];S(t);let i=qt[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},$t=[0,8e3,16e3,32e3,0,0,11025,22050,44100,0,0,12e3,24e3,48e3,96e3,192e3],Gt=[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],Qt=[16,16,20,20,0,24,24,0],Yt=[1,2,2,2,2,3,3,4,4,5,6,6,6,7,8,8],Jt=[1,2,2,2,2,3,18,19,6,7,518,323,83,519,582,535],Zt=[32e3,44100,48e3,0],ei=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],ti=[512,1024,2048,4096],ii=e=>{const t=ni(e),i=E(e);let r=t?4*Math.ceil(t.frameSize/4):0,n=null;for(;r+4<=e.length&&1683496997===i.getUint32(r);){const t=si(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}},ri=e=>{const t=ii(e);return(null==t?void 0:t.core)?t.hasExtensions?"dtsh":"dtsc":null},ni=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 He(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>=Yt.length)return null;const a=$t[t.readBits(4)];if(0===a)return null;const o=Gt[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=Qt[t.readBits(3)];if(0===c)return null;const u=0!==l;return{frameSize:n,sampleRate:a,numberOfChannels:Yt[s]+(u?1:0),sampleCount:32*r,channelLayout:Jt[s]|(u?8:0),amode:s,lfePresent:u,bitRate:o,pcmResolution:c}},si=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 He(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=Zt[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}}},ai=e=>le(e)+le(44646&e),oi=["avc","hevc","vp9","av1","vp8","prores"],li=["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"],ci=["aac","opus","mp3","vorbis","flac","ac3","eac3","dts",...li],ui=[{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}],di=[{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}],hi=".01.01.01.01.00",fi=".0.110.01.01.01.0",mi=["ap4x","ap4h","apch","apcn","apcs","apco"],pi=["dtsc","dtsh","dtsl","dtse"],gi=e=>{const{codec:t,codecDescription:i,colorSpace:r,avcCodecInfo:n,hevcCodecInfo:s,vp9CodecInfo:a,av1CodecInfo:o,proresFormat:l}=e;if("avc"===t){if(S(null!==e.avcType),n){const t=new Uint8Array([n.avcProfileIndication,n.profileCompatibility,n.avcLevelIndication]);return`avc${e.avcType}.${H(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}.${H(i.subarray(1,4))}`}if("hevc"===t){let e,t,r,n,a,o;if(s)e=s.generalProfileSpace,t=s.generalProfileIdc,r=V(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=E(i),l=s.getUint8(1);e=l>>6&3,t=31&l,r=V(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=P(di).level;for(const e of di)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(hi)&&(t=t.slice(0,-15)),t}if("av1"===t){if(!o){const t=e.width*e.height;let i=P(di).level;for(const e of di)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)?F[r.primaries]:1,u=(null==r?void 0:r.transfer)?D[r.transfer]:1,d=(null==r?void 0:r.matrix)?N[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(fi)&&(f=f.slice(0,-17)),f}if("prores"===t)return null!=l?l:"apch";throw null!==t&&J(t),new TypeError(`Unhandled codec '${t}'.`)},ki=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=dt(e.codecDescription))?void 0:i.sequenceParameterSets[0]),r){const e=ft(r);if(e)return{primaries:A[e.colourPrimaries],transfer:M[e.transferCharacteristics],matrix:O[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case"hevc":{let t=null==(n=null==(r=e.hevcCodecInfo)?void 0:r.arrays.find(e=>e.nalUnitType===Ze.SPS_NUT))?void 0:n.nalUnits[0];if(!t&&e.codecDescription&&(t=null==(a=null==(s=(e=>{try{const t=E(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,S=t.getUint8(i++),w=[];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===Ze.SPS_NUT))?void 0:a.nalUnits[0]),t){const e=yt(t);if(e)return{primaries:A[e.colourPrimaries],transfer:M[e.transferCharacteristics],matrix:O[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case"vp8":break;case"vp9":if(e.vp9CodecInfo)return{primaries:A[e.vp9CodecInfo.colourPrimaries],transfer:M[e.vp9CodecInfo.transferCharacteristics],matrix:O[e.vp9CodecInfo.matrixCoefficients],fullRange:!!e.vp9CodecInfo.videoFullRangeFlag};break;case"av1":if(e.av1CodecInfo)return{primaries:A[e.av1CodecInfo.colourPrimaries],transfer:M[e.av1CodecInfo.transferCharacteristics],matrix:O[e.av1CodecInfo.matrixCoefficients],fullRange:!!e.av1CodecInfo.videoFullRangeFlag};break;case"prores":if(e.proresCodecInfo)return{primaries:A[e.proresCodecInfo.colourPrimaries],transfer:M[e.proresCodecInfo.transferCharacteristics],matrix:O[e.proresCodecInfo.matrixCoefficients],fullRange:e.proresCodecInfo.fullRange}}return{primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0}},yi=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=Ke(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&&li.includes(t))return t;throw new TypeError(`Unhandled codec '${t}'.`)},bi=48e3,Ti=/^pcm-([usf])(\d+)(be)?$/,vi=e=>{if(S(li.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=Ti.exec(e);let i;S(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?c(2,7):0}},Si=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":mi.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":pi.includes(e)?"dts":"ulaw"===e?"ulaw":"alaw"===e?"alaw":Ti.test(e)?e:"webvtt"===e?"webvtt":null,wi=[44100,48e3,32e3],Pi=[-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],Ii=1483304551,xi=1231971951,Ci=(e,t)=>3===e?3===t?21:36:3===t?13:21,Bi=(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=Pi[16*a*4+16*c+(n>>4&15)];if(-1===g)return{header:null,bytesAdvanced:1};const k=1e3*g,y=wi[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 _i,Ri;(Ri=_i||(_i={}))[Ri.FrameCount=1]="FrameCount",Ri[Ri.FileSize=2]="FileSize",Ri[Ri.Toc=4]="Toc";const Fi=e=>3===e?1:2;class Ai{constructor(e){this.input=e}dispose(){}}const Di=new Uint8Array(0);class Mi{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===Di&&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===Di}get microsecondTimestamp(){return Math.trunc(de*this.timestamp)}get microsecondDuration(){return Math.trunc(de*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 Mi(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 Mi(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 Ni=e=>{const t=E(e);let i=0;const r=t.getUint8(i);i+=1,i+=3;const n=H(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=Wo(e);const i=Yo(e,4);let r=8;1===t&&(t=Ko(e),r=16);const n=t-r;return n<0?null:{name:i,totalSize:t,headerSize:r,contentSize:n}},zi=e=>Vo(e)/65536,Ui=e=>Vo(e)/1073741824,qi=e=>{let t=0;for(let i=0;i<4;i++){t<<=7;const i=No(e);if(t|=127&i,0===(128&i))break}return t},Wi=e=>{let t=Lo(e);return e.skip(2),t=Math.min(t,e.remainingLength),_.decode(Mo(e,t))},Hi=e=>{const t=Li(e);if(!t||"data"!==t.name)return null;if(e.remainingLength<8)return null;const i=Wo(e);e.skip(4);const r=Mo(e,t.contentSize-8);switch(i){case 1:return _.decode(r);case 2:return new TextDecoder("utf-16be").decode(r);case 13:return new Ue(r,"image/jpeg");case 14:return new Ue(r,"image/png");case 27:return new Ue(r,"image/bmp");default:return r}},Vi=16,ji=new Uint32Array(256),Ki=new Uint32Array(256),Xi=new Uint32Array(256),$i=new Uint32Array(256),Gi=new Uint32Array(256),Qi=new Uint32Array(256),Yi=new Uint32Array(10);let Ji=!1;class Zi{constructor(){this.roundkey=new Uint32Array(44),this.iv=new Uint32Array(Vi/Uint32Array.BYTES_PER_ELEMENT),this.in=new Uint8Array(Vi),this.out=new Uint8Array(Vi),this.inView=new DataView(this.in.buffer),this.outView=new DataView(this.out.buffer)}init({key:e,iv:t}){S(16===e.byteLength),S(16===t.byteLength),Ji||(()=>{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);ji[s]=t<<24|t<<16|t<<8|t,Qi[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);Ki[s]=n,Xi[s]=n>>>8|n<<24,$i[s]=n>>>16|n<<16,Gi[s]=n>>>24|n<<8}let n=1;for(let s=0;s<10;s++)Yi[s]=n<<24,n=n<<1^(128&n?283:0);Ji=!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&ji[e>>>16&255]^16711680&ji[e>>>8&255]^65280&ji[e>>>0&255]^255&ji[e>>>24&255]^Yi[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]]^Xi[255&ji[t>>>16&255]]^$i[255&ji[t>>>8&255]]^Gi[255&ji[t>>>0&255]]}}decrypt(){let e=this.inView.getUint32(0,!1)^this.roundkey[0],t=this.inView.getUint32(4,!1)^this.roundkey[1],i=this.inView.getUint32(8,!1)^this.roundkey[2],r=this.inView.getUint32(12,!1)^this.roundkey[3];const 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=Ki[e>>>24]^Xi[r>>>16&255]^$i[i>>>8&255]^Gi[255&t]^this.roundkey[n],c=Ki[t>>>24]^Xi[e>>>16&255]^$i[r>>>8&255]^Gi[255&i]^this.roundkey[n+1],u=Ki[i>>>24]^Xi[t>>>16&255]^$i[e>>>8&255]^Gi[255&r]^this.roundkey[n+2],d=Ki[r>>>24]^Xi[i>>>16&255]^$i[t>>>8&255]^Gi[255&e]^this.roundkey[n+3],e=l,t=c,i=u,r=d}const h=4278190080&Qi[e>>>24&255]^16711680&Qi[r>>>16&255]^65280&Qi[i>>>8&255]^255&Qi[t>>>0&255]^this.roundkey[40],f=4278190080&Qi[t>>>24&255]^16711680&Qi[e>>>16&255]^65280&Qi[r>>>8&255]^255&Qi[i>>>0&255]^this.roundkey[41],m=4278190080&Qi[i>>>24&255]^16711680&Qi[t>>>16&255]^65280&Qi[e>>>8&255]^255&Qi[r>>>0&255]^this.roundkey[42],p=4278190080&Qi[r>>>24&255]^16711680&Qi[i>>>16&255]^65280&Qi[t>>>8&255]^255&Qi[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 er extends Ai{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 p(this,null,function*(){return yield this.readMetadata(),this.tracks.map(e=>e.trackBacking)})}getMimeType(){return p(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 p(this,null,function*(){return yield this.readMetadata(),this.metadataTags})}readMetadata(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>p(this,null,function*(){let e=0,t=!1,i=!1;for(;;){let r=this.reader.requestSliceRange(e,8,16);if(Pe(r)&&(r=yield r),!r)break;const n=e,s=Li(r);if(!s)break;if("ftyp"===s.name||"styp"===s.name){const e=Yo(r,4);this.isQuickTime="qt "===e}else{if("moov"===s.name){let e=this.reader.requestSlice(r.filePos,s.contentSize);if(Pe(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){S(null!==this.reader.fileSize);let e=this.reader.requestSlice(this.reader.fileSize-4,4);Pe(e)&&(e=yield e),S(e);const t=Wo(e),i=this.reader.fileSize-t;if(i>=0&&i<=this.reader.fileSize-16){let e=this.reader.requestSliceRange(i,8,16);if(Pe(e)&&(e=yield e),e){const t=Li(e);if(t&&"mfra"===t.name){let i=this.reader.requestSlice(e.filePos,t.contentSize);Pe(i)&&(i=yield i),i&&this.readContiguousBoxes(i)}}}}}))()}copyMetadataFromInitInput(e){return p(this,null,function*(){const t=yield e._getDemuxer();if(t.constructor!==er)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(S(t.info),"video"===t.info.type&&-1!==t.info.width){const e=t;t.trackBacking=new ir(e),this.tracks.push(t)}else if("audio"===t.info.type&&-1!==t.info.numberOfChannels){const e=t;t.trackBacking=new rr(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;S(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&&li.includes(e.info.codec)&&0===r.sampleCompositionTimeOffsets.length){S("audio"===(null==(i=e.info)?void 0:i.type));const t=vi(e.info.codec),n=[],s=[];for(let i=0;ie.startIndex),u=r.sampleTimingEntries[c],d=K(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=P(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)lr(e,r.timestamp);else{const t=K(i,s.moofOffset-1,e=>e.moofOffset);if(-1!==t){const r=i[t];lr(e,r.endTimestamp)}}e.startTimestampIsFinal=!0}const r=K(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 hr(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;ue(t.languageCode)||(t.languageCode=re)}}break;case"hdlr":{const t=this.currentTrack;if(!t)break;e.skip(8);const i=Yo(e,4);"vide"===i?t.info={type:"video",width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:d({},z),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=ge,this.readContiguousBoxes(e.slice(ye,ke.contentSize))}break;case"stsd":{const t=this.currentTrack;if(!t)break;if(null===t.info||t.sampleTable)break;const i=No(e);e.skip(3);const r=Wo(e);for(let n=0;n0&&(1===a?(e.skip(4),l=8*Wo(e),e.skip(8)):2===a&&(e.skip(4),c=Qo(e),o=Wo(e),e.skip(4),l=Wo(e),u=Wo(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=bi;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(pi.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":(ze._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":(ze._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":(ze._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":(ze._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":(ze._warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null):32===e?t.info.codec="pcm-f32be":64===e?t.info.codec="pcm-f64be":(ze._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!==No(e),t.encryptionInfo.defaultPerSampleIvSize=No(e),t.encryptionInfo.defaultKid=H(Mo(e,16)),t.encryptionInfo.defaultIsProtected&&0===t.encryptionInfo.defaultPerSampleIvSize){const i=No(e),r=new Uint8Array(16);r.set(Mo(e,i),0),t.encryptionInfo.defaultConstantIv=r}}break;case"avcC":{const t=this.currentTrack;if(!t)break;if(S(t.info),0===ke.contentSize)break;t.info.codecDescription=Mo(e,ke.contentSize)}break;case"hvcC":{const t=this.currentTrack;if(!t)break;if(S(t.info),0===ke.contentSize)break;t.info.codecDescription=Mo(e,ke.contentSize)}break;case"vpcC":{const i=this.currentTrack;if(!i)break;S("video"===(null==(t=i.info)?void 0:t.type)),e.skip(4);const r=No(e),n=No(e),s=No(e),a=s>>4,o=s>>1&7,l=1&s,c=No(e),u=No(e),d=No(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;S("video"===(null==(i=t.info)?void 0:i.type)),e.skip(1);const o=No(e),l=o>>5,c=31&o,u=No(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=Mo(e,ke.contentSize-4),b=At(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;S("video"===(null==(o=t.info)?void 0:o.type));const i=Yo(e,4);if("nclx"!==i&&"nclc"!==i)break;const r=Lo(e),n=Lo(e),s=Lo(e);let a;"nclx"===i&&(a=Boolean(128&No(e))),t.info.colorSpace={primaries:A[r],transfer:M[n],matrix:O[s],fullRange:a}}break;case"pasp":{const t=this.currentTrack;if(!t)break;S("video"===(null==(l=t.info)?void 0:l.type));const i=Wo(e),r=Wo(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);S(3===No(e)),qi(e),e.skip(2);const i=No(e),r=0!==(64&i),n=0!==(32&i);if(0!==(128&i)&&e.skip(2),r){const t=No(e);e.skip(t)}n&&e.skip(2);S(4===No(e));const s=qi(e),a=e.filePos,o=No(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":ze._warn(`Unsupported audio codec (objectTypeIndication ${o}) - discarding track.`),e.skip(12),s>e.filePos-a){S(5===No(e));const i=qi(e);if(t.info.codecDescription=Mo(e,i),"aac"===t.info.codec){const e=Ke(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;S("audio"===(null==(u=t.info)?void 0:u.type)),t.info.pcmLittleEndian=!!(255&Lo(e))}break;case"pcmC":{const t=this.currentTrack;if(!t)break;S("audio"===(null==(f=t.info)?void 0:f.type)),e.skip(4);const i=No(e);t.info.pcmLittleEndian=Boolean(1&i),t.info.pcmSampleSize=No(e)}break;case"dOps":{const t=this.currentTrack;if(!t)break;S("audio"===(null==(m=t.info)?void 0:m.type)),e.skip(1);const i=No(e),r=Lo(e),n=Wo(e),s=Uo(e),a=No(e);let o;o=0!==a?Mo(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;S("audio"===(null==(p=t.info)?void 0:p.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=Mo(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;S("audio"===(null==(g=t.info)?void 0:g.type));const i=Mo(e,3),r=new He(i),n=r.readBits(2);r.skipBits(8);const s=r.readBits(3),a=r.readBits(1);n<3&&(t.info.sampleRate=Ge[n]),t.info.numberOfChannels=qt[s]+a}break;case"dec3":{const t=this.currentTrack;if(!t)break;S("audio"===(null==(k=t.info)?void 0:k.type));const i=(e=>{if(e.length<2)return null;const t=new He(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}})(Mo(e,ke.contentSize));if(!i){ze._warn("Invalid dec3 box contents, ignoring.");break}const r=Kt(i);null!==r&&(t.info.sampleRate=r),t.info.numberOfChannels=Xt(i)}break;case"ddts":{const t=this.currentTrack;if(!t)break;S("audio"===(null==(y=t.info)?void 0:y.type));const i=(e=>{if(e.length<20)return null;const t=E(e),i=t.getUint32(0);if(0===i)return null;const r=new He(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=ai(o):ae.id===i);if(!r)break;const n=Wo(e),s=(12&n)>>2,a=3&n,o=[No,Lo,zo,Wo],l=o[(48&n)>>4],c=o[s],u=o[a],d=Wo(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!=(T=null==d?void 0:d.defaultSampleDescriptionIndex)?T:null,defaultSampleDuration:null!=(v=null==d?void 0:d.defaultSampleDuration)?v:null,defaultSampleSize:null!=(I=null==d?void 0:d.defaultSampleSize)?I:null,defaultSampleFlags:null!=(x=null==d?void 0:d.defaultSampleFlags)?x:null,startTimestamp:null,encryptionAuxInfo:null},i?u.currentFragmentState.baseDataOffset=Ko(e):l&&(u.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),r&&(u.currentFragmentState.sampleDescriptionIndex=Wo(e)),n&&(u.currentFragmentState.defaultSampleDuration=Wo(e)),s&&(u.currentFragmentState.defaultSampleSize=Wo(e)),a&&(u.currentFragmentState.defaultSampleFlags=Wo(e)),o&&(u.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{const t=this.currentTrack;if(!t)break;S(t.currentFragmentState);const i=No(e);e.skip(3);const r=0===i?Wo(e):Ko(e);t.currentFragmentState.startTimestamp=r}break;case"trun":{const t=this.currentTrack;if(!t)break;S(this.currentFragment),S(t.currentFragmentState);const i=No(e),r=zo(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=Wo(e);let d=null;n&&(d=Vo(e));let h,f=null;s&&(f=Wo(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=Mo(e,r));const s=dr(t);s.defaultSampleInfoSize=i,s.sampleSizes=n,s.sampleCount=r}break;case"saio":{const t=this.currentTrack;if(!t||!t.encryptionInfo)break;const i=No(e);if(1&zo(e)){const i=Yo(e,4),r=Wo(e);if(i!==t.encryptionInfo.scheme||0!==r)break}const r=Wo(e);if(0===r)break;r>1&&ze._warn("Multiple saio entries are not supported; using the first offset only.");let n=0===i?Wo(e):Number(Ko(e));this.currentFragment&&(n+=this.currentFragment.moofOffset);dr(t).offset=n}break;case"senc":{const t=this.currentTrack;if(!t||!t.encryptionInfo)break;S(this.currentFragment);const i=this.currentFragment.trackData.get(t.id);if(!i)break;e.skip(1);const r=zo(e),n=Boolean(2&r),s=Wo(e),a=t.encryptionInfo.defaultPerSampleIvSize;S(null!==a);for(let o=0;o0?r.set(Mo(e,a),0):r.set(t.encryptionInfo.defaultConstantIv,0);let s=null;if(n){const t=Lo(e);s=[];for(let i=0;i0&&(null!=(ce=this.metadataTags).trackNumber||(ce.trackNumber=t)),i&&Number.isInteger(i)&&i>0&&(null!=(de=this.metadataTags).tracksTotal||(de.tracksTotal=i))}break;case"trkn":if(n instanceof Uint8Array&&n.length>=6){const e=E(n),t=e.getUint16(2,!1),i=e.getUint16(4,!1);t>0&&(null!=(he=this.metadataTags).trackNumber||(he.trackNumber=t)),i>0&&(null!=(fe=this.metadataTags).tracksTotal||(fe.tracksTotal=i))}break;case"disc":case"disk":if(n instanceof Uint8Array&&n.length>=6){const e=E(n),t=e.getUint16(2,!1),i=e.getUint16(4,!1);t>0&&(null!=(me=this.metadataTags).discNumber||(me.discNumber=t)),i>0&&(null!=(pe=this.metadataTags).discsTotal||(pe.discsTotal=i))}}}}}return e.filePos=be,!0}}class tr{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 p(this,null,function*(){var e;const t=this.internalTrack;if(t.durationInMediaTimescale<=0)return null;S(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 p(this,null,function*(){return null})}getFirstPacket(e){return p(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 ne(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}getPacket(e,t){return p(this,null,function*(){const i=this.mapTimestampIntoTimescale(e),r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),n=nr(r,i),s=yield this.fetchPacketForSampleIndex(n,t);return ur(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=K(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=Y(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 S(-1!==e),{sampleIndex:e,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)})}fetchPacketForSampleIndex(e,t){return p(this,null,function*(){if(-1===e)return null;const i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),r=ar(i,e);if(!r)return null;let n;if(t.metadataOnly)n=Di;else{let t=this.internalTrack.demuxer.reader.requestSlice(r.sampleOffset,r.sampleSize);if(Pe(t)&&(t=yield t),!t)return null;if(n=Mo(t,r.sampleSize),this.internalTrack.encryptionInfo){let t=null;if(this.internalTrack.encryptionAuxInfo){const i=yield hr(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);ee.timestamp),f=-1!==h?this.internalTrack.fragmentLookupTable[h]:null,m=K(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(Pe(e)&&(e=yield e),!e)break;const i=k,s=Li(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.moofOffsetp(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&&Dt(e.data)}}else{const e=yield this.getFirstPacket({}),t=e&&At(e.data);t&&(this.internalTrack.info.av1CodecInfo=t)}else{const t=yield this.getFirstPacket({}),i=t&&Rt(t.data);i&&(this.internalTrack.info.vp9CodecInfo=h(d({},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&&bt(e.data)}else{const e=yield this.getFirstPacket({});this.internalTrack.info.avcCodecInfo=e&&ct(e.data)}if(!L(this.internalTrack.info.colorSpace)){const e=ki(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:gi(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 rr extends tr{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 p(this,null,function*(){var e;return this.internalTrack.info.codec?null!=(e=this.decoderConfigPromise)?e:this.decoderConfigPromise=(()=>p(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&&ri(e.data)}return{codec:yi(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 nr=(e,t)=>{if(e.presentationTimestamps){const i=K(e.presentationTimestamps,t,e=>e.presentationTimestamp);return-1===i?-1:e.presentationTimestamps[i].sampleIndex}{const i=K(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)}},sr=(e,t)=>{var i;if(!e.keySampleIndices)return nr(e,t);if(e.presentationTimestamps){const i=K(e.presentationTimestamps,t,e=>e.presentationTimestamp);if(-1===i)return-1;for(let t=i;t>=0;t--){const i=e.presentationTimestamps[t].sampleIndex;if(-1!==j(e.keySampleIndices,i,e=>e))return i}return-1}{const r=nr(e,t),n=K(e.keySampleIndices,r,e=>e);return null!=(i=e.keySampleIndices[n])?i:-1}},ar=(e,t)=>{const i=K(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=K(e.sampleCompositionTimeOffsets,t,e=>e.startIndex),a=e.sampleCompositionTimeOffsets[s];a&&t-a.startIndexe.startSampleIndex),c=e.sampleToChunk[l];S(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)}},or=(e,t)=>{var i;if(!e.keySampleIndices)return t+1;const r=K(e.keySampleIndices,t,e=>e);return null!=(i=e.keySampleIndices[r+1])?i:-1},lr=(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},cr=e=>{const[t,i]=e,r=Math.atan2(i,t);return Number.isFinite(r)?r*(180/Math.PI):0},ur=e=>0===e.sampleSizes.length,dr=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}},hr=(e,t,i)=>p(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{S(i.sampleSizes);for(let e=0;e0?i.defaultSampleInfoSize:i.sampleSizes[e],o=new Uint8Array(16);s>0?o.set(Mo(n,s),0):o.set(t.defaultConstantIv,0);let l=null;if(r>s){const e=Lo(n);l=[];for(let t=0;te.defaultConstantIv?{iv:e.defaultConstantIv,subsamples:null}:null,mr=(e,t,i,r)=>p(null,null,function*(){var n;S(e.encryptionInfo);const s=e.encryptionInfo;S(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=p(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{S(e.length%2===0);const t=new Uint8Array(e.length/2);for(let i=0;ip(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=>p(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);S(null!==t.defaultCryptByteBlock&&null!==t.defaultSkipByteBlock);const o=kr(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}),gr=(e,t,i,r)=>{const n=new Zi;n.init({key:e,iv:i.iv});const s=t.defaultCryptByteBlock,a=t.defaultSkipByteBlock;if(S(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 yr,br;(br=yr||(yr={}))[br.EBML=440786851]="EBML",br[br.EBMLVersion=17030]="EBMLVersion",br[br.EBMLReadVersion=17143]="EBMLReadVersion",br[br.EBMLMaxIDLength=17138]="EBMLMaxIDLength",br[br.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",br[br.DocType=17026]="DocType",br[br.DocTypeVersion=17031]="DocTypeVersion",br[br.DocTypeReadVersion=17029]="DocTypeReadVersion",br[br.Void=236]="Void",br[br.Segment=408125543]="Segment",br[br.SeekHead=290298740]="SeekHead",br[br.Seek=19899]="Seek",br[br.SeekID=21419]="SeekID",br[br.SeekPosition=21420]="SeekPosition",br[br.Duration=17545]="Duration",br[br.Info=357149030]="Info",br[br.TimestampScale=2807729]="TimestampScale",br[br.MuxingApp=19840]="MuxingApp",br[br.WritingApp=22337]="WritingApp",br[br.Tracks=374648427]="Tracks",br[br.TrackEntry=174]="TrackEntry",br[br.TrackNumber=215]="TrackNumber",br[br.TrackUID=29637]="TrackUID",br[br.TrackType=131]="TrackType",br[br.FlagEnabled=185]="FlagEnabled",br[br.FlagDefault=136]="FlagDefault",br[br.FlagForced=21930]="FlagForced",br[br.FlagOriginal=21934]="FlagOriginal",br[br.FlagHearingImpaired=21931]="FlagHearingImpaired",br[br.FlagVisualImpaired=21932]="FlagVisualImpaired",br[br.FlagCommentary=21935]="FlagCommentary",br[br.FlagLacing=156]="FlagLacing",br[br.Name=21358]="Name",br[br.Language=2274716]="Language",br[br.LanguageBCP47=2274717]="LanguageBCP47",br[br.CodecID=134]="CodecID",br[br.CodecPrivate=25506]="CodecPrivate",br[br.CodecDelay=22186]="CodecDelay",br[br.SeekPreRoll=22203]="SeekPreRoll",br[br.DefaultDuration=2352003]="DefaultDuration",br[br.Video=224]="Video",br[br.PixelWidth=176]="PixelWidth",br[br.PixelHeight=186]="PixelHeight",br[br.DisplayWidth=21680]="DisplayWidth",br[br.DisplayHeight=21690]="DisplayHeight",br[br.DisplayUnit=21682]="DisplayUnit",br[br.AlphaMode=21440]="AlphaMode",br[br.Audio=225]="Audio",br[br.SamplingFrequency=181]="SamplingFrequency",br[br.Channels=159]="Channels",br[br.BitDepth=25188]="BitDepth",br[br.SimpleBlock=163]="SimpleBlock",br[br.BlockGroup=160]="BlockGroup",br[br.Block=161]="Block",br[br.BlockAdditions=30113]="BlockAdditions",br[br.BlockMore=166]="BlockMore",br[br.BlockAdditional=165]="BlockAdditional",br[br.BlockAddID=238]="BlockAddID",br[br.BlockDuration=155]="BlockDuration",br[br.ReferenceBlock=251]="ReferenceBlock",br[br.Cluster=524531317]="Cluster",br[br.Timestamp=231]="Timestamp",br[br.Cues=475249515]="Cues",br[br.CuePoint=187]="CuePoint",br[br.CueTime=179]="CueTime",br[br.CueTrackPositions=183]="CueTrackPositions",br[br.CueTrack=247]="CueTrack",br[br.CueClusterPosition=241]="CueClusterPosition",br[br.Colour=21936]="Colour",br[br.MatrixCoefficients=21937]="MatrixCoefficients",br[br.TransferCharacteristics=21946]="TransferCharacteristics",br[br.Primaries=21947]="Primaries",br[br.Range=21945]="Range",br[br.Projection=30320]="Projection",br[br.ProjectionType=30321]="ProjectionType",br[br.ProjectionPoseRoll=30325]="ProjectionPoseRoll",br[br.Attachments=423732329]="Attachments",br[br.AttachedFile=24999]="AttachedFile",br[br.FileDescription=18046]="FileDescription",br[br.FileName=18030]="FileName",br[br.FileMediaType=18016]="FileMediaType",br[br.FileData=18012]="FileData",br[br.FileUID=18094]="FileUID",br[br.Chapters=272869232]="Chapters",br[br.Tags=307544935]="Tags",br[br.Tag=29555]="Tag",br[br.Targets=25536]="Targets",br[br.TargetTypeValue=26826]="TargetTypeValue",br[br.TargetType=25546]="TargetType",br[br.TagTrackUID=25541]="TagTrackUID",br[br.TagEditionUID=25545]="TagEditionUID",br[br.TagChapterUID=25540]="TagChapterUID",br[br.TagAttachmentUID=25542]="TagAttachmentUID",br[br.SimpleTag=26568]="SimpleTag",br[br.TagName=17827]="TagName",br[br.TagLanguage=17530]="TagLanguage",br[br.TagString=17543]="TagString",br[br.TagBinary=17541]="TagBinary",br[br.ContentEncodings=28032]="ContentEncodings",br[br.ContentEncoding=25152]="ContentEncoding",br[br.ContentEncodingOrder=20529]="ContentEncodingOrder",br[br.ContentEncodingScope=20530]="ContentEncodingScope",br[br.ContentCompression=20532]="ContentCompression",br[br.ContentCompAlgo=16980]="ContentCompAlgo",br[br.ContentCompSettings=16981]="ContentCompSettings",br[br.ContentEncryption=20533]="ContentEncryption";const Tr=[yr.EBML,yr.Segment],vr=[yr.SeekHead,yr.Info,yr.Cluster,yr.Tracks,yr.Cues,yr.Attachments,yr.Chapters,yr.Tags],Sr=[...Tr,...vr],wr=16,Pr=e=>{if(e.remainingLength<1)return null;const t=No(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=No(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=Pr(e);if(null===t)return null;if(e.remainingLength{if(e.remainingLength<1)return null;if(255===No(e))return;e.skip(-1);const t=Ir(e);return null===t?null:72057594037927940!==t?t:void 0},Er=e=>{S(e.remainingLength>=2);const t=Cr(e);if(null===t)return null;const i=Br(e);return null===i?null:{id:t,size:i}},_r=(e,t)=>{const i=Mo(e,t);let r=0;for(;r{const i=Mo(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?Go(e):Qo(e)},Ar=(e,t,i,r)=>p(null,null,function*(){const n=new Set(i);let s=t;for(;null===r||ss?r:s,found:!1}}),Dr=(e,t,i,r)=>p(null,null,function*(){const n=c(2,16),s=new Set(i);let a=t;for(;ae.tracks.map(e=>e.trackBacking))})}getMimeType(){return p(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 p(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=d(d({},e),t.metadataTags);return e})}readMetadata(){var e;return null!=(e=this.readMetadataPromise)?e:this.readMetadataPromise=(()=>p(this,null,function*(){let e=0;for(;;){let t=this.reader.requestSliceRange(e,2,wr);if(Pe(t)&&(t=yield t),!t)break;const i=Er(t);if(!i)break;const r=i.id;let n=i.size;const s=t.filePos;if(r===yr.EBML){Gr(n);let e=this.reader.requestSlice(s,n);if(Pe(e)&&(e=yield e),!e)break;this.readContiguousElements(e)}else if(r===yr.Segment){if(yield this.readSegment(s,n),void 0===n)break;if(null===this.reader.fileSize)break}else if(r===yr.Cluster){if(null===this.reader.fileSize)break;if(void 0===n){n=(yield Ar(this.reader,s,Sr,this.reader.fileSize)).pos-s}const e=P(this.segments);e&&(e.elementEndPos=s+n)}Gr(n),e=s+n}}))()}readSegment(e,t){return p(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=rn[l].flag;this.currentSegment[e]=!0,Gr(a);let t=this.reader.requestSlice(o,a);Pe(t)&&(t=yield t),t&&this.readContiguousElements(t)}else if(s===yr.Tags||s===yr.Attachments){s===yr.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,Gr(a);let e=this.reader.requestSlice(o,a);Pe(e)&&(e=yield e),e&&this.readContiguousElements(e)}else if(s===yr.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=rn.find(e=>e.id===t.id);if(!i)continue;if(this.currentSegment[i.flag])continue;let r=this.reader.requestSliceRange(e+t.segmentPosition,2,wr);if(Pe(r)&&(r=yield r),!r)continue;const n=Er(r);if(!n)continue;const{id:s,size:a}=n;if(s!==i.id)continue;Gr(a),this.currentSegment[i.flag]=!0;let o=this.reader.requestSlice(r.filePos,a);Pe(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 p(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,wr);Pe(r)&&(r=yield r),S(r);const n=e,s=Er(r);S(s);S(s.id===yr.Cluster);let a=s.size;const o=r.filePos;if(void 0===a){a=(yield Ar(this.reader,o,Sr,t.elementEndPos)).pos-o}let l=this.reader.requestSlice(o,a);Pe(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,Sr);c.elementEndPos=e}for(const[,e]of c.trackData){const t=e.track;S(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[P(e.presentationTimestamps).blockIndex];e.startTimestamp=r.timestamp,e.endTimestamp=s.timestamp+s.duration;const a=K(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,f,m,p,g,k,y,b,T,v,P,I,x,C,B,E,R,F,D,N,L,U,q,W,H,V,j,K,X,$,G,Q,Y,J,Z,ee,te,ie,ne,se,ae,oe,le;const ce=Er(e);if(!ce)return!1;if(t&&t.includes(ce.id))return!1;const{id:de,size:he}=ce,fe=e.filePos;switch(Gr(he),de){case yr.DocType:this.isWebM="webm"===_r(e,he);break;case yr.Seek:{if(!this.currentSegment)break;const t={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(t),this.readContiguousElements(e.slice(fe,he)),-1!==t.id&&-1!==t.segmentPosition||this.currentSegment.seekEntries.pop()}break;case yr.SeekID:{const t=null==(i=this.currentSegment)?void 0:i.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.id=xr(e,he)}break;case yr.SeekPosition:{const t=null==(r=this.currentSegment)?void 0:r.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.segmentPosition=xr(e,he)}break;case yr.TimestampScale:if(!this.currentSegment)break;this.currentSegment.timestampScale=xr(e,he),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale;break;case yr.Duration:if(!this.currentSegment)break;this.currentSegment.duration=Fr(e,he);break;case yr.TrackEntry:if(!this.currentSegment)break;if(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:h(d({},We),{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(fe,he)),!this.currentTrack)break;if(this.currentTrack.decodingInstructions.some(e=>{var t;return"decompress"!==(null==(t=e.data)?void 0:t.type)||e.scope!==Jr.Block||e.data.algorithm!==en.HeaderStripping})&&(ze._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===Mr)this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(this.currentTrack.codecId===Nr)this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(t===Or)this.currentTrack.info.codec="vp8";else if(t===Lr)this.currentTrack.info.codec="vp9";else if(t===zr)this.currentTrack.info.codec="av1";else if(t===Ur){const e=this.currentTrack.codecPrivate?_.decode(this.currentTrack.codecPrivate):"";mi.includes(e)&&(this.currentTrack.info.codec="prores",this.currentTrack.info.proresFormat=e)}const e=this.currentTrack;this.currentTrack.trackBacking=new on(e),this.currentSegment.tracks.push(this.currentTrack)}else if("audio"===this.currentTrack.info.type){t===qr?(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===Wr?this.currentTrack.info.codec="mp3":t===Hr?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=bi):t===Vr?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===jr?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Kr?(this.currentTrack.info.codec="ac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Xr?(this.currentTrack.info.codec="eac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===$r?(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 ln(e),this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null;break;case yr.TrackNumber:if(!this.currentTrack)break;this.currentTrack.id=xr(e,he);break;case yr.TrackType:{if(!this.currentTrack)break;const t=xr(e,he);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:d({},z),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 yr.FlagEnabled:if(!this.currentTrack)break;xr(e,he)||(this.currentTrack=null);break;case yr.FlagDefault:if(!this.currentTrack)break;this.currentTrack.disposition.default=!!xr(e,he);break;case yr.FlagForced:if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!xr(e,he);break;case yr.FlagOriginal:if(!this.currentTrack)break;this.currentTrack.disposition.original=!!xr(e,he);break;case yr.FlagHearingImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!xr(e,he);break;case yr.FlagVisualImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!xr(e,he);break;case yr.FlagCommentary:if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!xr(e,he);break;case yr.CodecID:if(!this.currentTrack)break;this.currentTrack.codecId=_r(e,he);break;case yr.CodecPrivate:if(!this.currentTrack)break;this.currentTrack.codecPrivate=Mo(e,he);break;case yr.DefaultDuration:if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=xr(e,he);break;case yr.Name:if(!this.currentTrack)break;this.currentTrack.name=Rr(e,he);break;case yr.Language:if(!this.currentTrack)break;if(this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=_r(e,he),ue(this.currentTrack.languageCode)||(this.currentTrack.languageCode=re);break;case yr.LanguageBCP47:{if(!this.currentTrack)break;const t=_r(e,he).split("-")[0];this.currentTrack.languageCode=t||re,this.currentTrack.hasLanguageBcp47=!0}break;case yr.Video:if("video"!==(null==(s=null==(n=this.currentTrack)?void 0:n.info)?void 0:s.type))break;this.readContiguousElements(e.slice(fe,he));break;case yr.PixelWidth:if("video"!==(null==(o=null==(a=this.currentTrack)?void 0:a.info)?void 0:o.type))break;this.currentTrack.info.width=xr(e,he);break;case yr.PixelHeight:if("video"!==(null==(c=null==(l=this.currentTrack)?void 0:l.info)?void 0:c.type))break;this.currentTrack.info.height=xr(e,he);break;case yr.DisplayWidth:if("video"!==(null==(f=null==(u=this.currentTrack)?void 0:u.info)?void 0:f.type))break;this.currentTrack.info.displayWidth=xr(e,he);break;case yr.DisplayHeight:if("video"!==(null==(p=null==(m=this.currentTrack)?void 0:m.info)?void 0:p.type))break;this.currentTrack.info.displayHeight=xr(e,he);break;case yr.DisplayUnit:if("video"!==(null==(k=null==(g=this.currentTrack)?void 0:g.info)?void 0:k.type))break;this.currentTrack.info.displayUnit=xr(e,he);break;case yr.AlphaMode:if("video"!==(null==(b=null==(y=this.currentTrack)?void 0:y.info)?void 0:b.type))break;this.currentTrack.info.alphaMode=1===xr(e,he);break;case yr.Colour:if("video"!==(null==(v=null==(T=this.currentTrack)?void 0:T.info)?void 0:v.type))break;this.readContiguousElements(e.slice(fe,he));break;case yr.MatrixCoefficients:{if("video"!==(null==(I=null==(P=this.currentTrack)?void 0:P.info)?void 0:I.type))break;const t=xr(e,he),i=O[t];this.currentTrack.info.colorSpace.matrix=i}break;case yr.Range:{if("video"!==(null==(C=null==(x=this.currentTrack)?void 0:x.info)?void 0:C.type))break;const t=xr(e,he);this.currentTrack.info.colorSpace.fullRange=1===t||2===t?2===t:void 0}break;case yr.TransferCharacteristics:{if("video"!==(null==(E=null==(B=this.currentTrack)?void 0:B.info)?void 0:E.type))break;const t=xr(e,he),i=M[t];this.currentTrack.info.colorSpace.transfer=i}break;case yr.Primaries:{if("video"!==(null==(F=null==(R=this.currentTrack)?void 0:R.info)?void 0:F.type))break;const t=xr(e,he),i=A[t];this.currentTrack.info.colorSpace.primaries=i}break;case yr.Projection:if("video"!==(null==(N=null==(D=this.currentTrack)?void 0:D.info)?void 0:N.type))break;this.readContiguousElements(e.slice(fe,he));break;case yr.ProjectionPoseRoll:{if("video"!==(null==(U=null==(L=this.currentTrack)?void 0:L.info)?void 0:U.type))break;const t=-Fr(e,he);try{this.currentTrack.info.rotation=w(t)}catch(me){}}break;case yr.Audio:if("audio"!==(null==(W=null==(q=this.currentTrack)?void 0:q.info)?void 0:W.type))break;this.readContiguousElements(e.slice(fe,he));break;case yr.SamplingFrequency:if("audio"!==(null==(V=null==(H=this.currentTrack)?void 0:H.info)?void 0:V.type))break;this.currentTrack.info.sampleRate=Fr(e,he);break;case yr.Channels:if("audio"!==(null==(K=null==(j=this.currentTrack)?void 0:j.info)?void 0:K.type))break;this.currentTrack.info.numberOfChannels=xr(e,he);break;case yr.BitDepth:if("audio"!==(null==($=null==(X=this.currentTrack)?void 0:X.info)?void 0:$.type))break;this.currentTrack.info.bitDepth=xr(e,he);break;case yr.CuePoint:if(!this.currentSegment)break;this.readContiguousElements(e.slice(fe,he)),this.currentCueTime=null;break;case yr.CueTime:this.currentCueTime=xr(e,he);break;case yr.CueTrackPositions:{if(null===this.currentCueTime)break;S(this.currentSegment);const t={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(t),this.readContiguousElements(e.slice(fe,he)),-1!==t.trackId&&-1!==t.clusterPosition||this.currentSegment.cuePoints.pop()}break;case yr.CueTrack:{const t=null==(G=this.currentSegment)?void 0:G.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;t.trackId=xr(e,he)}break;case yr.CueClusterPosition:{const t=null==(Q=this.currentSegment)?void 0:Q.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;S(this.currentSegment),t.clusterPosition=this.currentSegment.dataStartPos+xr(e,he)}break;case yr.Timestamp:if(!this.currentCluster)break;this.currentCluster.timestamp=xr(e,he);break;case yr.SimpleBlock:{if(!this.currentCluster)break;const t=Ir(e);if(null===t)break;const i=this.getTrackDataInCluster(this.currentCluster,t);if(!i)break;const r=Uo(e),n=No(e),s=n>>1&3;let a=!!(128&n);"audio"===(null==(Y=i.track.info)?void 0:Y.type)&&i.track.info.codec&&(a=!0);const o=Mo(e,he-(e.filePos-fe)),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 yr.BlockGroup:if(!this.currentCluster)break;this.readContiguousElements(e.slice(fe,he)),this.currentBlock=null;break;case yr.Block:{if(!this.currentCluster)break;const t=Ir(e);if(null===t)break;const i=this.getTrackDataInCluster(this.currentCluster,t);if(!i)break;const r=Uo(e),n=No(e)>>1&3,s=Mo(e,he-(e.filePos-fe)),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 yr.BlockAdditions:this.readContiguousElements(e.slice(fe,he));break;case yr.BlockMore:if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(fe,he)),this.currentBlockAdditional.data&&1===this.currentBlockAdditional.addId&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null;break;case yr.BlockAdditional:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=Mo(e,he);break;case yr.BlockAddID:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=xr(e,he);break;case yr.BlockDuration:if(!this.currentBlock)break;this.currentBlock.duration=xr(e,he);break;case yr.ReferenceBlock:if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1;break;case yr.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(fe,he));break;case yr.Targets:this.readContiguousElements(e.slice(fe,he));break;case yr.TargetTypeValue:50!==xr(e,he)&&(this.currentTagTargetIsMovie=!1);break;case yr.TagTrackUID:case yr.TagEditionUID:case yr.TagChapterUID:case yr.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case yr.SimpleTag:if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(fe,he));break;case yr.TagName:this.currentSimpleTagName=Rr(e,he);break;case yr.TagString:{if(!this.currentSimpleTagName)break;const t=Rr(e,he);this.processTagValue(this.currentSimpleTagName,t)}break;case yr.TagBinary:{if(!this.currentSimpleTagName)break;const t=Mo(e,he);this.processTagValue(this.currentSimpleTagName,t)}break;case yr.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(fe,he));const t=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(null!=t.raw||(t.raw={}),t.raw[this.currentAttachedFile.fileUid.toString()]=new qe(this.currentAttachedFile.fileData,null!=(J=this.currentAttachedFile.fileMediaType)?J:void 0,null!=(Z=this.currentAttachedFile.fileName)?Z:void 0,null!=(ee=this.currentAttachedFile.fileDescription)?ee:void 0)),(null==(te=this.currentAttachedFile.fileMediaType)?void 0:te.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!=(ie=this.currentAttachedFile.fileName)?ie:void 0,description:null!=(ne=this.currentAttachedFile.fileDescription)?ne:void 0})}this.currentAttachedFile=null}break;case yr.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 yr.ContentEncoding:this.currentDecodingInstruction={order:0,scope:Jr.Block,data:null},this.readContiguousElements(e.slice(fe,he)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case yr.ContentEncodingOrder:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=xr(e,he);break;case yr.ContentEncodingScope:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=xr(e,he);break;case yr.ContentCompression:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:en.Zlib,settings:null},this.readContiguousElements(e.slice(fe,he));break;case yr.ContentCompAlgo:if("decompress"!==(null==(ae=null==(se=this.currentDecodingInstruction)?void 0:se.data)?void 0:ae.type))break;this.currentDecodingInstruction.data.algorithm=xr(e,he);break;case yr.ContentCompSettings:if("decompress"!==(null==(le=null==(oe=this.currentDecodingInstruction)?void 0:oe.data)?void 0:le.type))break;this.currentDecodingInstruction.data.settings=Mo(e,he);break;case yr.ContentEncryption:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}return e.filePos=fe+he,!0}decodeBlockData(e,t){S(e.decodingInstructions.length>0);let i=t;for(const r of e.decodingInstructions)if(S(r.data),"decompress"===r.data.type)if(r.data.algorithm===en.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 p(this,null,function*(){if(e.duration<=0)return null;let t=null;for(const r of e.tracks){S(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 an{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 p(this,null,function*(){return this.internalTrack.demuxer.getDurationFromMetadata(this.internalTrack.segment)})}getLiveRefreshInterval(){return p(this,null,function*(){return null})}getFirstPacket(e){return p(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 ne(e*this.internalTrack.segment.timestampFactor)}getPacket(e,t){return p(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=K(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=Y(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 S(-1!==e),{blockIndex:e,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)})}fetchPacketInCluster(e,t,i){return p(this,null,function*(){var r,n;if(-1===t)return null;const s=e.trackData.get(this.internalTrack.id).blocks[t];if(S(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);E(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?Di: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?Di:s.mainAdditional,c.alphaByteLength=s.mainAdditional.byteLength);const u=new Mi(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 p(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=K(this.internalTrack.cuePoints,i,e=>e.time),p=-1!==m?this.internalTrack.cuePoints[m]:null,g=K(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,wr);if(Pe(e)&&(e=yield e),!e)break;const i=b,s=Er(e);if(!s||!vr.includes(s.id)&&s.id!==yr.Void){const e=yield Dr(c.reader,i,vr,Math.min(null!=(o=u.elementEndPos)?o:1/0,i+nn));if(e){b=e;continue}break}const a=s.id;let l=s.size;const m=e.filePos;if(a===yr.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){S(a!==yr.Cluster);l=(yield Ar(c.reader,m,Sr,u.elementEndPos)).pos-m}const p=m+l;if(null===u.elementEndPos){let e=c.reader.requestSliceRange(p,2,wr);if(Pe(e)&&(e=yield e),!e)break;if(Cr(e)===yr.Segment){u.elementEndPos=p;break}}b=p}if(p&&(!h||h.elementStartPosp(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?ct(s.data):null,hevcCodecInfo:"hevc"===this.internalTrack.info.codec&&s?bt(s.data):null,vp9CodecInfo:"vp9"===this.internalTrack.info.codec&&s?Rt(s.data):null,av1CodecInfo:"av1"===this.internalTrack.info.codec&&s?At(s.data):null,proresCodecInfo:"prores"===this.internalTrack.info.codec&&s?Dt(s.data):null,proresFormat:this.internalTrack.info.proresFormat};if(!L(this.internalTrack.info.colorSpace)){const n=ki(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:gi(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 ln extends an{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 p(this,null,function*(){var e;return this.internalTrack.info.codec?null!=(e=this.decoderConfigPromise)?e:this.decoderConfigPromise=(()=>p(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&&ri(e.data)}return{codec:yi({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 cn=(e,t,i,r=null)=>p(null,null,function*(){const n=c(2,16);let s=t;for(;null===i||s=4;){const t=a.filePos,i=Wo(a),n=null!==e.fileSize?e.fileSize-s:null,o=Bi(i,n);if(o.header&&(!r||o.header.sampleRate===r.sampleRate&&o.header.mpegVersionId===r.mpegVersionId&&o.header.layer===r.layer&&Fi(o.header.channel)===Fi(r.channel)))return{header:o.header,startPos:s};a.filePos=t+o.bytesAdvanced,s=a.filePos}}return null});class un extends Ai{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 q,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}readMetadata(){return p(this,null,function*(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>p(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 dn(this)]}))()})}advanceReader(){return p(this,null,function*(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,nl);if(Pe(e)&&(e=yield e),!e)return void(this.lastSampleLoaded=!0);const t=ll(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}const e=yield cn(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=Ci(t.mpegVersionId,t.channel);let r=this.reader.requestSlice(e.startPos+i,4);if(Pe(r)&&(r=yield r),r){const n=Wo(r);if(n===Ii||n===xi){if(this.xingFrameHeader||(this.xingFrameHeader=t,this.xingFrameHeaderPos=e.startPos),!this.xingData){let t=this.reader.requestSlice(e.startPos+i+4,12);if(Pe(t)&&(t=yield t),t){const e=Mo(t,12),i=E(e),r=i.getUint32(0,!1);this.xingData={frameCount:r&_i.FrameCount?i.getUint32(4,!1):null,fileSize:r&_i.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 p(this,null,function*(){return"audio/mpeg"})}getTrackBackings(){return p(this,null,function*(){return yield this.readMetadata(),this.trackBackings})}getMetadataTags(){return p(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,nl);if(Pe(i)&&(i=yield i),!i)break;const r=ll(i);if(!r)break;t=!0;let n=this.reader.requestSlice(i.filePos,r.size);if(Pe(n)&&(n=yield n),!n)break;cl(n,r,this.metadataTags),e=i.filePos+r.size}if(!t&&null!==this.reader.fileSize&&this.reader.fileSize>=rl){let e=this.reader.requestSlice(this.reader.fileSize-rl,rl);Pe(e)&&(e=yield e),S(e);"TAG"===Yo(e,3)&&al(e,this.metadataTags)}return this.metadataTags}finally{e()}})}}class dn{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return S(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 p(this,null,function*(){const e=this.demuxer;if(S(null!==e.firstFrameHeader),S(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 p(this,null,function*(){const i=yield this.demuxer.readingMutex.acquire();try{for(;;){const i=K(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 mn=e=>{const t=E(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},pn=(e,t,i)=>{let r=0,n=null;if(e.length>0)if("vorbis"===t.codec){S(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:Mt[t]*r}})(e).durationInSamples}return{durationInSamples:r,vorbisBlockSize:n}},gn=27,kn=282,yn=e=>{const t=e.filePos;if(Ho(e)!==hn)return null;e.skip(1);const i=No(e),r=$o(e),n=Ho(e),s=Ho(e),a=Ho(e),o=No(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}},bn=(e,t)=>{for(;e.filePos>>8&255)===i||(t>>>16&255)===i||(t>>>24&255)===i){if(e.skip(-4),t===hn)return!0;e.skip(1)}}return!1};class Tn extends Ai{constructor(e){super(e),this.metadataPromise=null,this.bitstreams=[],this.trackBackings=[],this.metadataTags={},this.reader=e._reader}readMetadata(){return p(this,null,function*(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>p(this,null,function*(){let e=0;for(;;){let t=this.reader.requestSliceRange(e,gn,kn);if(Pe(t)&&(t=yield t),!t)break;const i=yn(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 vn(t,this)))}}))()})}readVorbisMetadata(e,t){return p(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=E(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:Nt(n.data).modeBlockflags},Ut(r.data.subarray(7),this.metadataTags)})}readOpusMetadata(e,t){return p(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=E(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=bi,t.codecInfo.opusInfo={preSkip:n.preSkip},Ut(r.data.subarray(8),this.metadataTags)})}readPacket(e,t){return p(this,null,function*(){S(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 p(this,null,function*(){return yield this.readMetadata(),this.trackBackings})}getMetadataTags(){return p(this,null,function*(){return yield this.readMetadata(),this.metadataTags})}}class vn{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new q,this.internalSampleRate="opus"===e.codecInfo.codec?bi:e.sampleRate}getType(){return"audio"}getId(){return this.bitstream.serialNumber}getNumber(){const e=this.demuxer.trackBackings.findIndex(e=>e.bitstream===this.bitstream);return S(-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 p(this,null,function*(){return null})}getLiveRefreshInterval(){return p(this,null,function*(){return null})}getCodec(){return this.bitstream.codecInfo.codec}getInternalCodecId(){return null}getDecoderConfig(){return p(this,null,function*(){var e;return S(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 re}getDisposition(){return h(d({},We),{primary:!1})}granulePositionToTimestampInSamples(e){return"opus"===this.bitstream.codecInfo.codec?(S(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,i){if(!e)return null;const{durationInSamples:r,vorbisBlockSize:n}=pn(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),s=new Mi(i.metadataOnly?Di: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 p(this,null,function*(){S(this.bitstream.lastMetadataPacket);const t=yield this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let i=0;"opus"===this.bitstream.codecInfo.codec&&(S(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 p(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 p(this,null,function*(){var i,r;if(null===this.demuxer.reader.fileSize)return this.getPacketSequential(e,t);const n=ne(e*this.internalSampleRate);if(0===n)return this.getFirstPacket(t);if(n<0)return null;S(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,gn,kn);Pe(t)&&(t=yield t),S(t);const i=yn(t);S(i),u=i,u.serialNumber===this.bitstream.serialNumber&&d.push(u)}S(-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:Di,endPage:p,endSegmentIndex:g};if(yield this.demuxer.findNextPacketStart(e)){const e=wn(d,u,m);S(e);const t=Sn(d,e.page,e.segmentIndex);t&&(u=t.page,m=t.segmentIndex)}else for(;;){const e=wn(d,u,m);if(!e)break;const t=Sn(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;){S(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 p(this,null,function*(){const i=yield this.sequentialScanMutex.acquire();try{const i=ne(e*this.internalSampleRate);e=i/this.internalSampleRate;const r=K(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);S(e),this.sequentialScanCache.length>0&&S(P(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 Sn=(e,t,i)=>{let r=t,n=i;e:for(;;){for(n--;n>=0;n--){if(r.lacingValues[n]<255){n++;break e}}S(-1===n);if(!(1&r.headerType)){n=0;break}const t=Q(e,e=>e.headerStartPos{if(i>0)return{page:t,segmentIndex:i-1};const r=Q(e,e=>e.headerStartPosp(this,null,function*(){var e,t;let i=this.reader.requestSlice(0,12);Pe(i)&&(i=yield i),S(i);const r=Yo(i,4),n="RIFX"!==r,s="RF64"===r,a=qo(i,n);let o=s?this.reader.fileSize:Math.min(a+8,null!=(e=this.reader.fileSize)?e:1/0);if("WAVE"!==Yo(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=Oo(r,i),s=t-18;if(Math.min(s,e)>=22&&n===Pn.EXTENSIBLE){r.skip(6);const e=Mo(r,16);n=e[0]|e[1]<<8}}if(n!==Pn.MULAW&&n!==Pn.ALAW||(l=8),n!==Pn.PCM&&n!==Pn.IEEE_FLOAT&&n!==Pn.ALAW&&n!==Pn.MULAW)throw new Error(`Unsupported WAVE codec (format tag ${n}). Only integer/float PCM, A-law, and \u03bc-law are supported.`);if(n===Pn.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===Pn.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 p(this,null,function*(){var r,n,s,a,o,l,c,u,d,h,f;let m=this.reader.requestSlice(e,t);if(Pe(m)&&(m=yield m),!m)return;const p=Yo(m,4);if("INFO"!==p&&"INF0"!==p)return;let g=m.filePos;for(;g<=e+t-8;){m.filePos=g;const e=Yo(m,4),t=qo(m,i),p=Mo(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 p(this,null,function*(){let i=this.reader.requestSlice(e,t);if(Pe(i)&&(i=yield i),!i)return;const r=ll(i);if(r){const n=t-nl;if(r.size=Math.min(r.size,n),r.size>0){const t=i.slice(e+nl,r.size);cl(t,r,this.metadataTags)}}})}getCodec(){if(S(this.audioInfo),this.audioInfo.format===Pn.MULAW)return"ulaw";if(this.audioInfo.format===Pn.ALAW)return"alaw";if(this.audioInfo.format===Pn.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===Pn.IEEE_FLOAT){if(4===this.audioInfo.sampleSizeInBytes)return"pcm-f32";if(8===this.audioInfo.sampleSizeInBytes)return"pcm-f64"}S(!1)}getMimeType(){return p(this,null,function*(){return"audio/wav"})}getTrackBackings(){return p(this,null,function*(){return yield this.readMetadata(),this.trackBackings})}getMetadataTags(){return p(this,null,function*(){return yield this.readMetadata(),this.metadataTags})}}const Cn=2048;class Bn{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return S(this.demuxer.audioInfo),this.demuxer.audioInfo.format}getDecoderConfig(){return p(this,null,function*(){const e=this.demuxer.getCodec();return e?(S(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null})}getNumberOfChannels(){return S(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return S(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return S(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 p(this,null,function*(){return S(-1!==this.demuxer.dataSize),this.demuxer.dataSize/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate})}getLiveRefreshInterval(){return p(this,null,function*(){return null})}getName(){return null}getLanguageCode(){return re}getDisposition(){return d({},We)}getPacketAtIndex(e,t){return p(this,null,function*(){S(e>=0),S(this.demuxer.audioInfo);const i=e*Cn*this.demuxer.audioInfo.blockSizeInBytes;if(i>=this.demuxer.dataSize)return null;const r=Math.min(Cn*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(Pe(e)&&(e=yield e),!e)return null}let n;if(t.metadataOnly)n=Di;else{let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+i,r);Pe(e)&&(e=yield e),S(e),n=Mo(e,r)}const s=e*Cn/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 Mi(n,"key",s,a,e,r)})}getFirstPacket(e){return this.getPacketAtIndex(0,e)}getPacket(e,t){return p(this,null,function*(){S(this.demuxer.audioInfo);const i=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/Cn,(this.demuxer.dataSize-1)/(Cn*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;S(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){S(this.demuxer.audioInfo);const i=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/Cn);return this.getPacketAtIndex(i+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const En=e=>{const t=e.filePos,i=Mo(e,9),r=new He(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}},_n=1024;class Rn extends Ai{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.trackBackings=[],this.readingMutex=new q,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}readMetadata(){return p(this,null,function*(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>p(this,null,function*(){for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)yield this.advanceReader();S(this.firstFrameHeader),this.trackBackings=[new Fn(this)]}))()})}advanceReader(){return p(this,null,function*(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,nl);if(Pe(e)&&(e=yield e),!e)return void(this.lastSampleLoaded=!0);const t=ll(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}let e=this.reader.requestSliceRange(this.lastLoadedPos,7,9);if(Pe(e)&&(e=yield e),!e)return void(this.lastSampleLoaded=!0);const t=En(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=Ve[t.samplingFrequencyIndex];S(void 0!==i);const r=_n/i,n={timestamp:this.nextTimestampInSamples/i,duration:r,dataStart:t.startPos,dataSize:t.frameLength};this.loadedSamples.push(n),this.nextTimestampInSamples+=_n,this.lastLoadedPos=t.startPos+t.frameLength})}getMimeType(){return p(this,null,function*(){return"audio/aac"})}getTrackBackings(){return p(this,null,function*(){return yield this.readMetadata(),this.trackBackings})}getMetadataTags(){return p(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,nl);if(Pe(t)&&(t=yield t),!t)break;const i=ll(t);if(!i)break;let r=this.reader.requestSlice(t.filePos,i.size);if(Pe(r)&&(r=yield r),!r)break;cl(r,i,this.metadataTags),e=t.filePos+i.size}return this.metadataTags}finally{e()}})}}class Fn{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return this.getSampleRate()/_n}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return p(this,null,function*(){return null})}getLiveRefreshInterval(){return p(this,null,function*(){return null})}getName(){return null}getLanguageCode(){return re}getCodec(){return"aac"}getInternalCodecId(){return S(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){S(this.demuxer.firstFrameHeader);const e=je[this.demuxer.firstFrameHeader.channelConfiguration];return S(void 0!==e),e}getSampleRate(){S(this.demuxer.firstFrameHeader);const e=Ve[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return S(void 0!==e),e}getDisposition(){return d({},We)}getDecoderConfig(){return p(this,null,function*(){return S(this.demuxer.firstFrameHeader),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate()}})}getPacketAtIndex(e,t){return p(this,null,function*(){if(-1===e)return null;const i=this.demuxer.loadedSamples[e];if(!i)return null;let r;if(t.metadataOnly)r=Di;else{let e=this.demuxer.reader.requestSlice(i.dataStart,i.dataSize);if(Pe(e)&&(e=yield e),!e)return null;r=Mo(e,i.dataSize)}return new Mi(r,"key",i.timestamp,i.duration,e,i.dataSize)})}getFirstPacket(e){return this.getPacketAtIndex(0,e)}getNextPacket(e,t){return p(this,null,function*(){const i=yield this.demuxer.readingMutex.acquire();try{const i=j(this.demuxer.loadedSamples,e.timestamp,e=>e.timestamp);if(-1===i)throw new Error("Packet was not created from this track.");const r=i+1;for(;r>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)yield this.demuxer.advanceReader();return this.getPacketAtIndex(r,t)}finally{i()}})}getPacket(e,t){return p(this,null,function*(){const i=yield this.demuxer.readingMutex.acquire();try{for(;;){const i=K(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+1p(this,null,function*(){var e;let t=0;for(;;){let e=this.reader.requestSlice(t,nl);if(Pe(e)&&(e=yield e),!e)return void(this.lastSampleLoaded=!0);const i=ll(e);if(!i)break;let r=this.reader.requestSlice(e.filePos,i.size);Pe(r)&&(r=yield r),S(r),cl(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===No(s)){const t=s.filePos;if(No(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=Mo(e,4),n=new He(r);if(32764!==n.readBits(15))return null;if(null===this.blockingBit){S(t);const e=n.readBits(1);this.blockingBit=e}else if(1===this.blockingBit){S(!t);if(1!==n.readBits(1))return null}else{if(0!==this.blockingBit)throw new Error("Invalid blocking bit");S(!t);if(0!==n.readBits(1))return null}const s=(e=>0===e?null:1===e?192:e>=2&&e<=5?144*c(2,e):6===e?"uncommon-u8":7===e?"uncommon-u16":e>=8&&e<=15?c(2,e):null)(n.readBits(4));if(!s)return null;S(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 He(Mo(e,1));for(;1===i.readBits(1);)t++;if(0===t)return i.readBits(7);const r=[],n=t-1,s=new He(Mo(e,n)),a=8-t-1;for(let o=0;oe|t<"uncommon-u16"===t?Lo(e)+1:"uncommon-u8"===t?No(e)+1:"number"===typeof t?t:(J(t),void S(!1)))(e,s),u=((e,t)=>"uncommon-u16"===t?Lo(e):"uncommon-u16-10"===t?10*Lo(e):"uncommon-u8"===t?No(e):"number"===typeof t?t:null)(e,a);if(null===u)return null;if(u!==this.audioInfo.sampleRate)return null;const d=e.filePos-i,h=No(e);e.skip(-d),e.skip(-1);const f=(e=>{let t=0;for(const i of e){t^=i;for(let e=0;e<8;e++)0!==(128&t)?t=t<<1^7:t<<=1,t&=255}return t})(Mo(e,d));return h!==f?null:{num:o,blockSize:l,sampleRate:u}}advanceReader(){return p(this,null,function*(){yield this.readMetadata(),S(null!==this.lastLoadedPos),S(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 Dn{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return S(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return S(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return re}getTimeResolution(){return S(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 p(this,null,function*(){return S(this.demuxer.audioInfo),0===this.demuxer.audioInfo.totalSamples?null:this.demuxer.audioInfo.totalSamples/this.demuxer.audioInfo.sampleRate})}getLiveRefreshInterval(){return p(this,null,function*(){return null})}getDisposition(){return d({},We)}getDecoderConfig(){return p(this,null,function*(){return S(this.demuxer.audioInfo),{codec:"flac",numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}})}getPacket(e,t){return p(this,null,function*(){if(S(this.demuxer.audioInfo),e<0)return null;const i=yield this.demuxer.readingMutex.acquire();try{for(;;){const i=K(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 p(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 p(this,null,function*(){const i=this.demuxer.loadedSamples[e];if(!i)return null;let r;if(t.metadataOnly)r=Di;else{let e=this.demuxer.reader.requestSlice(i.byteOffset,i.byteSize);if(Pe(e)&&(e=yield e),!e)return null;r=Mo(e,i.byteSize)}S(this.demuxer.audioInfo);const n=i.blockOffset/this.demuxer.audioInfo.sampleRate,s=i.blockSize/this.demuxer.audioInfo.sampleRate;return new Mi(r,"key",n,s,e,i.byteSize)})}getFirstPacket(e){return p(this,null,function*(){for(;0===this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)yield this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)})}}const Mn=9e4,Nn=c(2,33),On=188,Ln="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.",zn=new Set([133,134,162]),Un=new Set;class qn extends Ai{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 p(this,null,function*(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>p(this,null,function*(){let e=this.reader.requestSlice(0,205);Pe(e)&&(e=yield e),S(e);const t=Mo(e,205);if(71===t[0]&&71===t[188])this.packetOffset=0,this.packetStride=On;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 He(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=Hn(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 $n(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=ct(r.suppliedPacket.data),!e.info.avcCodecInfo)continue;const t=e.info.avcCodecInfo.sequenceParameterSets[0];S(t);const i=ft(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:A[i.colourPrimaries],transfer:M[i.transferCharacteristics],matrix:O[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=bt(r.suppliedPacket.data),!e.info.hevcCodecInfo)continue;const t=e.info.hevcCodecInfo.arrays.find(e=>e.nalUnitType===Ze.SPS_NUT).nalUnits[0];S(t);const i=yt(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:A[i.colourPrimaries],transfer:M[i.transferCharacteristics],matrix:O[i.matrixCoefficients],fullRange:!!i.fullRangeFlag},e.info.reorderSize=i.maxDecFrameBuffering;break}throw new Error("Unhandled.")}e.info.decoderConfig={codec:gi({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=Ao.tempFromBytes(r.suppliedPacket.data),i=En(t);if(!i)throw new Error("Invalid AAC audio stream; could not read ADTS frame header from first packet.");e.info.aacCodecInfo={isMpeg2:!1,objectType:i.objectType},e.info.numberOfChannels=je[i.channelConfiguration],e.info.sampleRate=Ve[i.samplingFrequencyIndex]}else if("mp3"===e.info.codec){const t=Wo(Ao.tempFromBytes(r.suppliedPacket.data)),i=Bi(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=Fi(i.header.channel),e.info.sampleRate=i.header.sampleRate}else if("ac3"===e.info.codec){const t=Wt(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=qt[t.acmod]+t.lfeon,e.info.sampleRate=Ge[t.fscod]}else if("eac3"===e.info.codec){const t=jt(r.suppliedPacket.data);if(!t)throw new Error("Invalid E-AC-3 audio stream; could not read sync frame from first packet.");const i=Kt(t);if(null===i)throw new Error("Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.");e.info.numberOfChannels=Xt(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:yi({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 He(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&&zn.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:Un.has(t)||(ze._warn(`Note: MPEG-TS streams with stream_type 0x${t.toString(16)} are not currently supported.`),Un.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 He(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 jn(a)):this.trackBackingEntries.push(new Kn(a)))}))()})}getTrackBackings(){return p(this,null,function*(){return yield this.readMetadata(),this.trackBackingEntries})}getMetadataTags(){return p(this,null,function*(){return{}})}getMimeType(){return p(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 p(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!==j(this.sectionEndPositions,r,e=>e)){c=!1;break}}if(c){const e=K(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 p(this,null,function*(){let t=this.reader.requestSlice(e,4);if(Pe(t)&&(t=yield t),!t)return null;if(71!==No(t))throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");const i=Lo(t);return{payloadUnitStartIndicator:i>>14&1,pid:8191&i,adaptationFieldControl:No(t)>>4&3}})}readPacket(e){return p(this,null,function*(){let t=this.reader.requestSlice(e,On);if(Pe(t)&&(t=yield t),!t)return null;const i=Mo(t,On);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>=Nn-t?-Nn:Nn}}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 He(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(Ln);return{sectionStartPos:t.startPos,sectionEndPos:t.endPos,pts:a,randomAccessIndicator:t.randomAccessIndicator}},Hn=(e,t,i)=>{S(null!==t.endPos);const r=Wn(e,t,i);if(!r)return null;const n=new He(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;S(Number.isInteger(l));const c=t.payload.subarray(l,s>0?6+s:t.payload.byteLength);return h(d({},r),{data:c})};class Vn{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++,S(r instanceof Vn),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 re}getDisposition(){return h(d({},We),{primary:!1})}getTimeResolution(){return Mn}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return p(this,null,function*(){return null})}getLiveRefreshInterval(){return p(this,null,function*(){return null})}createEncodedPacket(e,t,i){let r;return r=this.allPacketsAreKeyPackets()||1===e.randomAccessIndicator?"key":"delta",new Mi(i.metadataOnly?Di:e.data,r,e.pts/Mn,Math.max(t/Mn,0),e.sequenceNumber,e.data.byteLength)}getFirstPacket(e){return p(this,null,function*(){const t=this.elementaryStream.firstSection;S(t);const i=Hn(this.elementaryStream.demuxer,t,!0);S(i);const r=new $n(this.elementaryStream,i),n=new Gn(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 p(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);S(s);const a=Hn(n,s,!0);S(a);const o=new $n(this.elementaryStream,a);i=new Gn(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 p(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 p(this,null,function*(){var r,n,s,a,o,l;const c=ne(e*Mn),u=this.elementaryStream.demuxer,{reader:d,seekChunkSize:h}=u,f=this.elementaryStream.pid,m=(e,t,i)=>p(this,null,function*(){let r=e;for(;re.pts),v=-1!==T?b[T]:null;if(v&&c-v.pts<45e3)y=v.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=oe(t*h,u.packetStride)+k.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}}}y=oe(e*h,u.packetStride)+k.sectionStartPos}const w=yield m(y,null!=(r=d.fileSize)?r:1/0,!1);let I=null!=(n=null==w?void 0:w.pesPacketHeader)?n:null;I||(I=k);const x=this.getReorderSize(),C=(e,t)=>p(this,null,function*(){var r,n;const s=yield u.readSection(e,!0);S(s);const a=Hn(u,s,!0);S(a);const o=new $n(this.elementaryStream,a),l=new Gn(this,o);for(;;){if((null!=(n=null==(r=P(l.presentationOrderPackets))?void 0:r.pts)?n:-1/0)>=c)break;if(!(yield l.readNextPacket()))break}const d=Y(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();S(m);const p=this.createEncodedPacket(m.packet,m.duration,i);return this.packetBuffers.set(p,l),this.packetSectionStarts.set(p,m.packet.sectionStartPos),p});if(!t||this.allPacketsAreKeyPackets()){e:for(;;){let e=I.sectionStartPos+u.packetStride;for(;;){const t=yield u.readPacketHeader(e);if(!t)break e;if(t.pid===f&&1===t.payloadUnitStartIndicator){const t=yield u.readSection(e,!1);if(t){const e=Wn(u,t,!1);if(e&&null!==e.pts){if(e.pts>c)break e;I=e,Xn(this.elementaryStream,I);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=Wn(u,t,!1);if(e&&null!==e.pts){I=e;break}}}e-=u.packetStride}}return C(I.sectionStartPos,e=>e.pts<=c)}{let e=y,t=null;const i=!this.elementaryStream.canBeTrustedWithKeyPackets;for(;;){let r=null;const n=e<=k.sectionStartPos;let p,y=null;if(n)p=k,y=g;else{const t=yield m(e,null!=(s=d.fileSize)?s:1/0,i);p=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(;p&&!(null!==t&&p.sectionStartPos>=t);){if(p.pts<=c){let e;if(this.elementaryStream.canBeTrustedWithKeyPackets)e=1===p.randomAccessIndicator;else{S(y);const t=Hn(u,y,!0);S(t);const i=new $n(this.elementaryStream,t);yield i.markNextPacket(),e=1===(null==(l=i.suppliedPacket)?void 0:l.randomAccessIndicator)}e&&(r=p)}if(p.pts>c&&(b=!0),b&&(T++,T>x))break;let e=p.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=Wn(u,t,!1);if(e&&null!==e.pts){p=e,y=t,Xn(this.elementaryStream,p);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=Wn(u,r,!1);if(t&&null!==t.pts){e=t;break}}}t-=u.packetStride}}const t=yield C(e.sectionStartPos,e=>e.pts<=c&&1===e.randomAccessIndicator);return S(t),t}if(n)return null;t=e,e=Math.max(oe(e-k.sectionStartPos-h,u.packetStride)+k.sectionStartPos,k.sectionStartPos)}}})}}class jn extends Vn{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 p(this,null,function*(){return this.elementaryStream.info.colorSpace})}canBeTransparent(){return p(this,null,function*(){return!1})}getDecoderConfig(){return p(this,null,function*(){return S(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig})}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}}class Kn extends Vn{getType(){return"audio"}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}getDecoderConfig(){return p(this,null,function*(){return S(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig})}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 0}}const Xn=(e,t)=>{const i=e.referencePesPackets,r=K(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 S(e),e}bufferData(e){return p(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,S;if("avc"===e)T=nt(b),v=T===Ye.NON_IDR_SLICE||T===Ye.SLICE_DPA||T===Ye.IDR,S=T===Ye.SEI||T===Ye.SPS||T===Ye.PPS||T===Ye.AUD;else{T=kt(b);if(((1&b)<<5|l[g+1]>>3)>0){u+=m;continue}v=T<=Ze.RASL_R||T>=Ze.BLA_W_LP&&T<=21,S=T>=Ze.VPS_NUT&&T<=37||T===Ze.PREFIX_SEI_NUT||T>=41&&T<=44||T>=48&&T<=55}let w=!1;if(v){let t;if("avc"===e){const e=l.subarray(k,k+y),i=I(new He(e));t=!s||i<=a,a=i}else t=l[k]>>7===1;t&&(s?w=!0:s=!0)}else S&&s&&(w=!0);if(w){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);Pe(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=Ht[3*a+n];S(void 0!==o),this.seekTo(e),t=this.ensureBuffered(o),Pe(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(Pe(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=Vt[a];this.seekTo(e),t=this.ensureBuffered(n),Pe(t)&&(t=yield t);const l=256*o,c=Math.round(l*Mn/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(Pe(a)&&(a=yield a),a<18)return;const o=this.readBytes(18),l=ni(o);let c=l?null:si(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);Pe(i)&&(i=yield i),c=null!=(e=si(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(Pe(i)&&(i=yield i),i=0)}readNext(){return p(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(S(-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 p(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 p(this,null,function*(){const e=this.decodeOrderPackets[0];for(S(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 Qn="application/vnd.apple.mpegurl",Yn="#EXT-X-STREAM-INF:",Jn="#EXT-X-I-FRAME-STREAM-INF:",Zn="#EXT-X-MEDIA:",es="#EXTINF:",ts="#EXT-X-MAP:",is="#EXT-X-KEY:",rs="#EXT-X-MEDIA-SEQUENCE:",ns="#EXT-X-BYTERANGE:",ss="#EXT-X-PROGRAM-DATE-TIME:",as="#EXT-X-TARGETDURATION:",os="#EXT-X-PLAYLIST-TYPE:",ls=e=>0===e.length||e.startsWith("#")&&!e.startsWith("#EXT");class cs{constructor(e){this._attributes={};let t="",i="",r=!1,n=!1;for(let s=0;sp(this,null,function*(){const e=[];if(this.trackDeclarations){for(const t of this.trackDeclarations)if("video"===t.type){const i=Re(e,e=>"video"===e.getType())+1;e.push(new hs(this,t,i))}else if("audio"===t.type){const i=Re(e,e=>"audio"===e.getType())+1;e.push(new fs(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=Re(e,e=>"video"===e.getType())+1;e.push(new hs(this,{id:e.length+1,type:"video"},t))}else if("audio"===r.type){const t=Re(e,e=>"audio"===e.getType())+1;e.push(new fs(this,{id:e.length+1,type:"audio"},t))}}return e}))()})}getFirstTimestampForInput(e){return p(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 p(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 ds{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=(()=>p(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 p(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 p(this,null,function*(){return yield this.hydrate(),S(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 p(this,null,function*(){S(e.sequenceNumber>=0),S(this.segmentedInput.firstSegment);const r=yield this.segmentedInput.getMediaOffset(t,i.input),n=t.timestamp-this.segmentedInput.firstSegment.timestamp,s=e.clone({timestamp:ae(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 p(this,null,function*(){var t;yield this.hydrate(),S(this.firstInputTrack),S(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 p(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 p(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 hs extends ds{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 p(this,null,function*(){return this.delegate(()=>this.firstInputTrack._backing.getColorSpace())})}canBeTransparent(){return p(this,null,function*(){return this.delegate(()=>this.firstInputTrack._backing.canBeTransparent())})}getDecoderConfig(){return p(this,null,function*(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())})}}class fs extends ds{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 p(this,null,function*(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())})}}Be();const ms=1/0;"undefined"!==typeof FinalizationRegistry&&new FinalizationRegistry(e=>{e()});class ps extends Ne{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 p(this,null,function*(){var e;if(this._disposed)throw new Ro;return null!=(e=this._sizePromise)?e:this._sizePromise=(()=>p(this,null,function*(){let e=this._getFileSize();return void 0!==e||(yield this._read(0,1,0,ms),e=this._getFileSize(),S(void 0!==e)),e}))()})}getSize(){return p(this,null,function*(){if(this._disposed)throw new Ro;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 Rs(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 gs(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){this._refCount--,0===this._refCount&&(this._dispose(),this._disposed=!0)}}class gs{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;S(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 ks extends ps{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 ps||e instanceof gs))throw new TypeError("requestHandler must return or resolve to a Source or SourceRef.");const i=e instanceof ps?e.ref():e;return(t=i.source)._usedForHls||(t._usedForHls=this._usedForHls),i};return Pe(t)?t.then(i):i(t)}}const ys=(e,t)=>e.path===t.path;class bs extends ks{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 ps?e.ref():e;return this._root=t,this._rootRequest=null,t};Pe(e)?this._rootRequest=e.then(t):(t(e),S(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 Ts="undefined"!==typeof FinalizationRegistry?new FinalizationRegistry(e=>{e.cancel().catch(()=>{})}):null;class vs extends ps{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&&(!Ee(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 _s({maxCacheSize:null!=(i=t.maxCacheSize)?i:8*c(2,20),maxWorkerCount:4,runWorker:this._runWorker.bind(this),onIdleWorkerRemoved:e=>{const t=this._readers.get(e);t&&(this._readers.delete(e),null==Ts||Ts.unregister(e),t.cancel().catch(()=>{}))},prefetchProfile:Es.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 p(this,null,function*(){S(e.strictTarget);let t=this._readers.get(e);if(void 0===t){if("stream"in this._blob&&!ke()&&!1!==this._options.useStreamReader){t=this._blob.slice(e.currentPos).stream().getReader(),null==Ts||Ts.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 ze._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(c(2,e-2),16)},Ps=new Set;class Is extends ks{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&&(!Ee(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 Is(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:ws,this._requestInit=d({},t.requestInit);let a=null;if(null==(r=t.requestInit)?void 0:r.headers){const e=d({},fe(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=Cs(a);e&&(this._offset=e.offset,this._length=e.length)}this._orchestrator=new _s({maxCacheSize:null!=(n=t.maxCacheSize)?n:64*c(2,20),maxWorkerCount:null!=(s=t.parallelism)?s:2,runWorker:this._runWorker.bind(this),prefetchProfile:Es.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:ie(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 Pe(a)?a.then(o):o(a)}_runWorker(e){return p(this,null,function*(){for(var t;;){const r=new AbortController,n=yield me(null!=(t=this._options.fetchFn)?t:fetch,this._url,he(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")||Ps.has(e.origin)||(ze._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.`),Ps.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){ze._error("Error while reading response stream. Attempting to resume.",i),yield Me(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=>p(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;ze._error("Error while reading response stream. Attempting to resume.",s),yield Me(1e3*e);const a=yield me(null!=(n=this._options.fetchFn)?n:fetch,this._url,he(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 Bs(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);Pe(e)?e.then(e=>{e?(S(e.offset===o.start),o.resolve(e.bytes)):o.resolve(null)},e=>o.reject(e)):(S(null===e),o.resolve(null))}}_dispose(){this._orchestrator.dispose(),this._sequentialBacking&&(this._sequentialBacking._disposed=!0,this._sequentialBacking._dispose())}}const xs=/^bytes=(\d+)-(\d*)$/,Cs=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=K(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}=$();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 p(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 Ro);this._pendingSlices.length=0,this._cache.length=0,null==(e=this._reader)||e.cancel()}}const Es={fileSystem:(e,t)=>{const i=c(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=c(2,16);e=Math.max(0,Math.floor((e-r)/r)*r);for(const n of i){const i=8*c(2,20),r=Math.max((n.startPos+n.targetPos)/2,n.targetPos-i);if(xe(e,t,r,n.targetPos)){const e=n.targetPos-n.startPos,r=Math.ceil((e+1)/i)*i,s=c(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+Ss)}}};class _s{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;S(!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);S(a<=e&&t<=o);let l=null;const c=K(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=K(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(S(n<=s),m=h.length&&(l={bytes:h,view:E(h),offset:e}),0===p.length)return S(l),l;const{promise:g,resolve:k,reject:y}=$(),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)}}):(S(h),l=g.then(t=>t&&{bytes:t,view:E(t),offset:e})),l}checkHoleAgainstWorker(e,t,i){const r=c(2,17);if(xe(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);S(-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=K(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=E(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=E(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 Pe(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 Fs=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},As=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 Ds=/^0[xX][0-9a-fA-F]+$/,Ms=/^data:.*;base64,/i;class Ns extends us{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=(()=>p(this,null,function*(){try{const e=this.getRemainingWaitTimeMs();e>0&&(yield Me(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 p(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=Fs(e,yield this.demuxer.input._getSourceUncached({path:this.rootPath,isRoot:!1}),!1),i=new Fo(t.source),r=yield i.requestEntireFile();S(r),l=Jo(r,r.length,{ignore:ls}),t.source instanceof ks&&(this.rootPath=t.source.rootPath)}catch(F){e.error=F,e.hasError=!0}finally{As(e)}}const u=!1!==(null==(e=this.input._formatOptions.hls)?void 0:e.offsetTimestampsByDateTime);let f=!1,m=0,p=null,g=null,k=null,y=0,b=null,T=null,v=null,w=null,I=null,x=null,C=!1,B=null!=(t=P(this.segments))?t:null;const _=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}},R=e=>{y=e,B&&(S(null!==B.sequenceNumber),B.sequenceNumber0&&null!==x&&(m=y*x),C=!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}'.`);g=n}else if(e.startsWith(ts)){const t=new cs(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=_(r)),a&&null===a.offset)throw new Error("Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset.");if(!B){const e={path:_e(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==k?void 0:k.method)&&!k.iv)throw new Error("IV attribute must be set on #EXT-X-KEY tag preceding the #EXT-X-MAP tag.");T={timestamp:m,unixEpochTimestamp:p,firstSegment:null,sequenceNumber:null,location:e,duration:0,encryption:k,initSegment:null,lastProgramDateTimeSeconds:I}}g=null,null===w?v=null:w=null}else if(e.startsWith(is)){const t=new cs(e.slice(11)),i=t.get("method");if("NONE"===i)k=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(!Ds.test(r))throw new Error(`Unsupported IV format '${r}'.`);let e=r.slice(2);e=e.padStart(32,"0"),i=new Uint8Array(Vi);for(let t=0;t=8&&112===i[4]&&115===i[5]&&115===i[6]&&104===i[7]){const e=E(i).getUint32(0);r=Ni(i.subarray(8,Math.min(e,i.length)))}}k={method:i,psshBox:r}}}}else if(e.startsWith(rs)){const t=e.slice(22),i=Number(t);if(!Number.isInteger(i)||i<0)throw new Error(`Invalid EXT-X-MEDIA-SEQUENCE value '${t}'.`);R(i)}else if(e.startsWith(ns)){const t=_(e.slice(17));if(null===t.offset){if(null===v)throw new Error("Invalid M3U8 file; #EXT-X-BYTERANGE without offset requires a previous byte range.");t.offset=v}w=t,v=t.offset+t.length}else if(e.startsWith(ss)){if(B)continue;const t=e.slice(25),i=Date.parse(t);if(!Number.isFinite(i))continue;const r=i/1e3;if(I===r)continue;if(null===I&&this.segments.length>0){const e=P(this.segments),t=r-(e.timestamp+e.duration);for(const i of this.segments)i.unixEpochTimestamp=i.timestamp+t,u&&(i.timestamp=i.unixEpochTimestamp)}I=r,p=r,u&&(m=r)}else if("#EXT-X-DISCONTINUITY"===e)b=null;else if(e.startsWith(as)){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,x=i}else{if("#EXT-X-ENDLIST"===e){this.streamHasEnded=!0;break}if(e.startsWith(os)){"vod"===e.slice(21).toLowerCase()&&(this.streamHasEnded=!0)}}}else{if("#EXTM3U"!==e)throw new Error("Invalid M3U8 file; expected first line to be #EXTM3U.");f=!0}}if(!f)throw new Error("Invalid M3U8 file; no #EXTM3U header.")})}getFirstSegment(){return p(this,null,function*(){var e;return 0===this.segments.length&&(yield this.runUpdateSegments()),null!=(e=this.segments[0])?e:null})}getSegmentAt(e,t){return p(this,null,function*(){0===this.segments.length&&(yield this.runUpdateSegments());let i=!!t.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){const r=K(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=h(d({},this.input._formatOptions),{isobmff:h(d({},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=>Oi(e,i))||(t=[...t,i]),this.input._formatOptions.isobmff.resolveKeyId(h(d({},e),{psshBoxes:t}))})})}),o=new Eo({source:new bs(r.location.path,e=>p(this,null,function*(){var t,i;S(e.isRoot);const n=h(d({},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;S(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=c(2,16),a=new Zi;return new ReadableStream({pull:o=>p(null,null,function*(){r||(a.init(yield t()),r=!0);const l=s+16;let c=e.requestSliceRange(n,0,l);if(Pe(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=Mo(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 Fo(t.source),()=>p(this,null,function*(){const t={stack:[],error:void 0,hasError:!1};try{const i=Fs(t,yield this.input._getSourceCached({path:e.keyUri,isRoot:!1},Bo),!1),r=new Fo(i.source),n=yield r.requestSlice(0,Vi);if(!n)throw new Error("Invalid AES-128 key; expected at least 16 bytes of data.");return{key:Mo(n,Vi),iv:e.iv}}catch(i){t.error=i,t.hasError=!0}finally{As(t)}}),()=>{t.free()});s=new Bs(o).ref()}else S(!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 ia)),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=Fe(this.inputCache,e=>e.age);S(-1!==e),this.inputCache.splice(e,1)}return o}getLiveRefreshInterval(){return p(this,null,function*(){return 0===this.getRemainingWaitTimeMs()&&(yield this.runUpdateSegments()),this.streamHasEnded?null:this.refreshInterval})}}class Os extends Ai{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=(()=>p(this,null,function*(){S(this.input._rootSource instanceof ks);const e=yield this.input._reader.requestEntireFile();S(e);const t=Jo(e,e.length,{ignore:ls}),{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)=>p(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=>p(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"),g=h.some(e=>oi.includes(Si(e))),k=h.some(e=>ci.includes(Si(e)));if(null!==f&&!g){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=_e(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});S(null!==a),h.push(a)}}if(null!==m&&!k){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=_e(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});S(null!==a),h.push(a)}}h=[...new Set(h)];let y=null,b=null;const T=e.attributes.getAsNumber("bandwidth");S(null!==T);const v=e.attributes.getAsNumber("average-bandwidth"),w=e.attributes.get("name");for(const i of h){const d=Si(i);if(null!==d)if(oi.includes(d)){if(null!==y)throw new Error("Unsupported M3U8 file; multiple video codecs found in the CODECS attribute of a variant stream.");y=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:re,lineNumber:e.lineNumber,fullPath:e.fullPath,fullCodecString:y,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:qs(i.attributes),autoselect:qs(i.attributes)||Ws(i.attributes),languageCode:Hs(i.attributes.get("language")),lineNumber:i.lineNumber,fullPath:null!=(c=i.fullPath)?c:e.fullPath,fullCodecString:b,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===re&&(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 zs(u)):this.trackBackings.push(new Us(u));this.internalTracks=l}))()}getTrackBackings(){return p(this,null,function*(){return yield this.readMetadata(),S(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 Ns(this,e,i,null),this.segmentedInputs.push(t),t}getMetadataTags(){return p(this,null,function*(){return{}})}getMimeType(){return p(this,null,function*(){return Qn})}dispose(){if(this.segmentedInputs){for(const e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}}class Ls{constructor(e){this.internalTrack=e,this.hydrationPromise=null}hydrate(){var e;return null!=(e=this.hydrationPromise)?e:this.hydrationPromise=(()=>p(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 zs){for(const r of i)if((yield r.getCodec())===this.getCodec()){t=r;break}}else{S(this instanceof Us);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 h(d({},We),{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(){S(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 p(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getDurationFromMetadata(e)})}getLiveRefreshInterval(){return p(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getLiveRefreshInterval()})}getHasOnlyKeyPackets(){return this.internalTrack.hasOnlyKeyPackets||null}getFirstPacket(e){return p(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getFirstPacket(e)})}getPacket(e,t){return p(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getPacket(e,t)})}getKeyPacket(e,t){return p(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getKeyPacket(e,t)})}getNextPacket(e,t){return p(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getNextPacket(e,t)})}getNextKeyPacket(e,t){return p(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getNextKeyPacket(e,t)})}}class zs extends Ls{constructor(e){super(e)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return"video"}getCodec(){return Si(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 p(this,null,function*(){return yield this.hydrate(),this.backingVideoTrack.getColorSpace()})}canBeTransparent(){return p(this,null,function*(){return yield this.hydrate(),this.backingVideoTrack.canBeTransparent()})}getMetadataCodecParameterString(){return this.backingVideoTrack?null:this.internalTrack.fullCodecString}getDecoderConfig(){return p(this,null,function*(){return yield this.hydrate(),this.backingVideoTrack.getDecoderConfig()})}}class Us extends Ls{constructor(e){super(e)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return"audio"}getCodec(){return Si(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 p(this,null,function*(){return yield this.hydrate(),this.backingAudioTrack.getDecoderConfig()})}}const qs=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}".`)},Ws=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}".`)},Hs=e=>{if(null===e)return re;const t=e.split("-")[0];return t||re};class Vs{constructor(){this._isIsobmff=!1}}class js extends Vs{constructor(){super(...arguments),this._isIsobmff=!0}_getMajorBrand(e){return p(this,null,function*(){let t=e._reader.requestSlice(0,12);if(Pe(t)&&(t=yield t),!t)return null;t.skip(4);const i=Yo(t,4);return"ftyp"!==i&&"styp"!==i?null:Yo(t,4)})}_createDemuxer(e){return new er(e)}}class Ks extends js{_canReadInput(e){return p(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(Pe(t)&&(t=yield t),!t)return!1;let r=Wo(t),n=8;if(1===r){let t=e._reader.requestSlice(i+8,8);if(Pe(t)&&(t=yield t),!t)return!1;r=Ko(t),n=16}if(r8)return!1;if(xr(i,r)!==yr.EBML)return!1;const n=Br(i);if("number"!==typeof n)return!1;let s=e._reader.requestSlice(i.filePos,n);if(Pe(s)&&(s=yield s),!s)return!1;const a=i.filePos;for(;s.filePos<=a+n-2;){const e=Er(s);if(!e)break;const{id:i,size:r}=e,n=s.filePos;if(void 0===r)return!1;switch(i){case yr.EBMLVersion:if(1!==xr(s,r))return!1;break;case yr.EBMLReadVersion:if(1!==xr(s,r))return!1;break;case yr.DocType:if(_r(s,r)!==t)return!1;break;case yr.DocTypeVersion:if(xr(s,r)>4)return!1}s.filePos=n+r}return!0})}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new sn(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}}class Gs extends $s{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}}class Qs extends Vs{_canReadInput(e){return p(this,null,function*(){let t=0;for(;;){let i=e._reader.requestSlice(t,nl);if(Pe(i)&&(i=yield i),!i)break;const r=ll(i);if(!r)break;t=i.filePos+r.size}const i=yield cn(e._reader,t,t+4096);if(!i)return!1;const r=i.header,n=Ci(r.mpegVersionId,r.channel);let s=e._reader.requestSlice(i.startPos+n,4);if(Pe(s)&&(s=yield s),!s)return!1;const a=Wo(s);if(a===Ii||a===xi)return!0;t=i.startPos+i.header.totalSize;const o=yield cn(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 un(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}}class Ys extends Vs{_canReadInput(e){return p(this,null,function*(){let t=e._reader.requestSlice(0,12);if(Pe(t)&&(t=yield t),!t)return!1;const i=Yo(t,4);if("RIFF"!==i&&"RIFX"!==i&&"RF64"!==i)return!1;t.skip(4);return"WAVE"===Yo(t,4)})}_createDemuxer(e){return new xn(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}}class Js extends Vs{_canReadInput(e){return p(this,null,function*(){let t=e._reader.requestSlice(0,4);return Pe(t)&&(t=yield t),!!t&&"OggS"===Yo(t,4)})}_createDemuxer(e){return new Tn(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}}class Zs extends Vs{_canReadInput(e){return p(this,null,function*(){let t=0;for(;;){let i=e._reader.requestSlice(t,nl);if(Pe(i)&&(i=yield i),!i)break;const r=ll(i);if(!r)break;t=i.filePos+r.size}let i=e._reader.requestSlice(t,4);return Pe(i)&&(i=yield i),!!i&&"fLaC"===Yo(i,4)})}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new An(e)}}class ea extends Vs{_canReadInput(e){return p(this,null,function*(){let t=0;for(;;){let i=e._reader.requestSlice(t,nl);if(Pe(i)&&(i=yield i),!i)break;const r=ll(i);if(!r)break;t=i.filePos+r.size}let i=e._reader.requestSliceRange(t,7,9);if(Pe(i)&&(i=yield i),!i)return!1;const r=En(i);if(!r)return!1;if(t+=r.frameLength,i=e._reader.requestSliceRange(t,7,9),Pe(i)&&(i=yield i),!i)return!1;const n=En(i);return!!n&&(r.objectType===n.objectType&&r.samplingFrequencyIndex===n.samplingFrequencyIndex&&r.channelConfiguration===n.channelConfiguration)})}_createDemuxer(e){return new Rn(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}}class ta extends Vs{_canReadInput(e){return p(this,null,function*(){let t=e._reader.requestSlice(0,205);if(Pe(t)&&(t=yield t),!t)return!1;const i=Mo(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 qn(e)}get name(){return"MPEG Transport Stream"}get mimeType(){return"video/MP2T"}}class ia extends Vs{_canReadInput(e){return p(this,null,function*(){let t=e._reader.requestSlice(0,7);if(Pe(t)&&(t=yield t),!t)return!1;if(!("#EXTM3U"===Yo(t,7)))return!1;if(!(e._rootSource instanceof ks))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 Os(e)}get name(){return"HTTP Live Streaming (HLS)"}get mimeType(){return Qn}}const ra=new Ks,na=new Xs,sa=new $s,aa=new Gs,oa=new Qs,la=new Ys,ca=new Js,ua=new ea,da=new Zs,ha=new ta,fa=new ia,ma=[fa,ra,na,sa,aa,la,ca,da,oa,ua,ha],pa=[fa,ra,na,oa,ua,ha];var ga=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});Be();let ka=-1/0,ya=-1/0,ba=null;"undefined"!==typeof FinalizationRegistry&&(ba=new FinalizationRegistry(e=>{const t=performance.now();"video"===e.type?(t-ka>=1e3&&(ze._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."),ka=t),"undefined"!==typeof VideoFrame&&e.data instanceof VideoFrame&&e.data.close()):(t-ya>=1e3&&(ze._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."),ya=t),"undefined"!==typeof AudioData&&e.data instanceof AudioData&&e.data.close())}));class Ta{constructor(){this._referenceCount=0,this._lastAllocationBuffer=null}}const va=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],Sa=new Set(va);class wa{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(de*this.timestamp)}get microsecondDuration(){return Math.trunc(de*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,S,w,P,I,x,C,E,_,R,F,A;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||!Sa.has(t.format))throw new TypeError("init.format must be one of: "+va.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&&De(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:Aa(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?B(e):B(e).slice(),this._layout=m,this.colorSpace=new Ba(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)&&De(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!=(S=null==t?void 0:t.rotation)?S:0,this.squarePixelWidth=e.displayWidth,this.squarePixelHeight=e.displayHeight,this.timestamp=null!=(w=null==t?void 0:t.timestamp)?w:e.timestamp/1e6,this.duration=null!=(I=null==t?void 0:t.duration)?I:(null!=(P=e.duration)?P:0)/1e6,this.colorSpace=new Ba(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&&De(t.visibleRect,"init.visibleRect"),"undefined"!==typeof VideoFrame)return new wa(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*de),duration:Math.trunc((null!=(x=t.duration)?x:0)*de)||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:be(),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!=(E=t.rotation)?E:0,this.timestamp=t.timestamp,this.duration=null!=(_=t.duration)?_:0,this.colorSpace=new Ba({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else{if(!(e instanceof Ta))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&&!va.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!=(R=t.rotation)?R:0,this.timestamp=t.timestamp,this.duration=null!=(F=t.duration)?F:0,this.colorSpace=e.getColorSpace()}this.encodeOptions=null!=(A=null==t?void 0:t.encodeOptions)?A:{},this.pixelAspectRatio=Ae({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),null==ba||ba.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return S(null!==this._data),this._data instanceof Ta?new wa(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):Ea(this._data)?new wa(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):this._data instanceof Uint8Array?(S(this._layout),new wa(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 wa(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==ba||ba.unregister(this),this._data instanceof Ta?(this._data._referenceCount--,0===this._data._referenceCount&&this._data.close()):Ea(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){var t;if(Fa(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(Ea(this._data))return this._data.allocationSize(e);return Ma(this,e).allocationSize}copyTo(e){return p(this,arguments,function*(e,t={}){var i,r;if(!U(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(Fa(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(S(null!==this._data),Ea(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 Ta)){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 wa))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{ga(i)}}}const n=Ma(this,t);S(this.format);const s=B(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)S(this._layout),S(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");S(e);const t=e.getImageData(0,0,this.codedWidth,this.codedHeight);o=[{data:B(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 Ea(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?(S(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&&Ra(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=_a(T,m,p));const{sx:v,sy:S,sWidth:w,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,S,w,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 u=0;2*r0?Ca(d,h):{canvas:e,context:t,isNew:i.targetIsFresh};m.imageSmoothingQuality="high",i.fillBlack?(m.fillStyle="black",m.fillRect(0,0,d,h)):p||m.clearRect(0,0,d,h),this.drawWithFit(m,{fit:i.fit,rotation:i.rotation,crop:i.crop}),m.globalCompositeOperation="copy";for(let g=u;g>1;g--){const e=r*c(2,g),t=n*c(2,g);m.drawImage(f,0,0,e,t,0,0,e/2,t/2)}m.globalCompositeOperation="source-over",u>0&&(t.imageSmoothingQuality="high",t.globalCompositeOperation="copy",t.drawImage(f,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(S(null!==this._data),this._data instanceof Ta||this._data instanceof Uint8Array){const e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}return this._data}transform(e){return p(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&&Ra(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=w(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=_a(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=se(f,null!=(i=e.roundDimensionsTo)?i:1),m=se(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 Pa){let t=e(this,p);if(Pe(t)&&(t=yield t),null!==t)return t}const{canvas:g,context:k,isNew:y}=Ca(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 wa(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 Pa=[],Ia=[];let xa=0;const Ca=(e,t)=>{for(const n of Ia)if(n.canvas.width===e&&n.canvas.height===t)return n.age=xa++,{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 Ia.length>=3&&Ia.splice(Fe(Ia,e=>e.age),1),Ia.push({canvas:i,context:r,age:xa++}),{canvas:i,context:r,isNew:!0}};class Ba{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(F);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(D);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(N);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 Ea=e=>"undefined"!==typeof VideoFrame&&e instanceof VideoFrame,_a=(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 S(s>=0),S(a>=0),{left:r,top:n,width:s,height:a}},Ra=(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.")},Fa=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.")}},Aa=(e,t,i)=>{const r=Da(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},Da=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:J(e),S(!1)}},Ma=(e,t)=>{const i={left:0,top:0,width:e.codedWidth,height:e.codedHeight},r=t.rect,n=Na(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 La(n,a,s)},Na=(e,t,i,r,n)=>{const s=d({},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(!Oa(n,s))throw new TypeError("visibleRect alignment is invalid for the format.");return s},Oa=(e,t)=>{if(null===e)return!0;const i=Da(e);for(let r=0;r{const r=Da(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/(Wa(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*Wa(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=Wa(r),o=Ha(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(!U(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&&!za.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=Wa(o),f=Ha(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 Xa(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=Va(a),y=Wa(a),b=Ha(a);let T;if(this._data instanceof Ua){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 qa({data:n,format:this.format,sampleRate:this.sampleRate,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp+e/this.sampleRate})}close(){this._closed||(null==ba||ba.unregister(this),this._data instanceof Ua?(this._data._referenceCount--,0===this._data._referenceCount&&this._data.close()):Ka(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 Ua?this._createAudioDataFromData():Ka(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(Ha(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")}},Ha=e=>{switch(e){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},Va=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)}},ja=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)}},Ka=e=>"undefined"!==typeof AudioData&&e instanceof AudioData,Xa=(e,t,i,r,n,s,a,o)=>{const l=Va(i),c=ja(r),u=Wa(i),d=Wa(r),h=Ha(i);if(Ha(r))if(h){const r=new ArrayBuffer(o*u),n=E(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.")},Ya=e=>{if(!Ee(e))throw new TypeError("timestamp must be a number.")},Ja=(e,t,i)=>i.verifyKeyPackets?t.then(t=>p(null,null,function*(){if(!t||"delta"===t.type)return t;const i=yield e.determinePacketType(t);return i&&(t.type=i),t})):t;class Za{constructor(e){if(!(e instanceof po))throw new TypeError("track must be an InputTrack.");this._track=e}getFirstPacket(){return p(this,arguments,function*(e={}){if(Qa(e),this._track.input._disposed)throw new Ro;return Ja(this._track,this._track._backing.getFirstPacket(e),e)})}getFirstKeyPacket(){return p(this,arguments,function*(e={}){Qa(e);const t=yield this.getFirstPacket(e);return t?"key"===t.type?t:this.getNextKeyPacket(t,e):null})}getPacket(e){return p(this,arguments,function*(e,t={}){if(Ya(e),Qa(t),this._track.input._disposed)throw new Ro;return Ja(this._track,this._track._backing.getPacket(e,t),t)})}getNextPacket(e){return p(this,arguments,function*(e,t={}){if(!(e instanceof Mi))throw new TypeError("packet must be an EncodedPacket.");if(Qa(t),this._track.input._disposed)throw new Ro;return Ja(this._track,this._track._backing.getNextPacket(e,t),t)})}getKeyPacket(e){return p(this,arguments,function*(e,t={}){if(Ya(e),Qa(t),this._track.input._disposed)throw new Ro;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);const i=yield this._track._backing.getKeyPacket(e,t);if(!i)return i;S("key"===i.type);return"delta"===(yield this._track.determinePacketType(i))?this.getKeyPacket(i.timestamp-1/(yield this._track.getTimeResolution()),t):i})}getNextKeyPacket(e){return p(this,arguments,function*(e,t={}){if(!(e instanceof Mi))throw new TypeError("packet must be an EncodedPacket.");if(Qa(t),this._track.input._disposed)throw new Ro;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);const i=yield this._track._backing.getNextKeyPacket(e,t);if(!i)return i;S("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 Mi))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 Mi))throw new TypeError("endPacket must be an EncodedPacket.");if(Qa(i),this._track.input._disposed)throw new Ro;const r=[];let{promise:n,resolve:s}=$(),{promise:a,resolve:o}=$(),l=!1,c=!1,u=null,d=!1;const h=[],f=()=>Math.max(2,h.length);(()=>p(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}=$()),yield a):(r.push(u),s(),({promise:n,resolve:s}=$()),u=yield this.getNextPacket(u,i));l=!0,s()}))().catch(e=>{d||(u=e,d=!0,s())});const m=this._track;return{next(){return p(this,null,function*(){for(;;){if(m.input._disposed)throw new Ro;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 p(this,null,function*(){return c=!0,o(),s(),{value:void 0,done:!0}})},throw(e){return p(this,null,function*(){throw e})},[Symbol.asyncIterator](){return this}}}}class eo{constructor(e,t){this.onSample=e,this.onError=t}}class to{mediaSamplesInRange(e=-1/0,t=1/0,i){Ya(e),Ya(t);const r=[];let n=!1,s=null,{promise:a,resolve:o}=$(),{promise:l,resolve:c}=$(),u=!1,f=!1,m=!1,g=null,k=null,y=!1;const b=h(d({},i),{verifyKeyPackets:!0,metadataOnly:!1});(()=>p(this,null,function*(){var i;g=yield this._createDecoder(i=>{c(),i.timestamp>=t&&(f=!0),f?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}=$())))},e=>{y||(k=e,y=!0,o())});const d=this._createPacketSink(),h=null!=(i=yield d.getKeyPacket(e,b))?i:yield d.getFirstKeyPacket(b);let p=h;const T=d.packets(null!=h?h:void 0,void 0,b);for(yield T.next();p&&!f&&!this._track.input._disposed;){const e=io(r.length);if(r.length+g.getDecodeQueueSize()>e){({promise:l,resolve:c}=$()),yield l;continue}g.decode(p);const t=yield T.next();if(t.done)break;p=t.value}yield T.return(),m||this._track.input._disposed||(yield g.flush()),!n&&s&&r.push(s),u=!0,o()}))().catch(e=>{y||(k=e,y=!0,o())}).finally(()=>{null==g||g.close()});const T=this._track,v=()=>{null==s||s.close();for(const e of r)e.close()};return{next(){return p(this,null,function*(){for(;;){if(T.input._disposed)throw m=!0,f=!0,v(),new Ro;if(m)return{value:void 0,done:!0};if(y)throw m=!0,f=!0,v(),k;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 p(this,null,function*(){return m=!0,f=!0,c(),o(),v(),{value:void 0,done:!0}})},throw(e){return p(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 k(this,null,function*(){Symbol.iterator in e?yield*y(e[Symbol.iterator]()):yield*y(e[Symbol.asyncIterator]())})}(e),r=[],n=[];let{promise:s,resolve:a}=$(),{promise:o,resolve:l}=$(),c=!1,u=!1,f=null,m=null,g=!1;const T=e=>{n.push(e),a(),({promise:s,resolve:a}=$())},v=h(d({},t),{verifyKeyPackets:!0,metadataOnly:!1});(()=>p(this,null,function*(){f=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{g||(m=e,g=!0,a())});const e=this._createPacketSink();let t=null,s=null,d=-1;const h=()=>p(this,null,function*(){S(s),S(f);let t=s;for(f.decode(t);t.sequenceNumberi&&!u;)({promise:o,resolve:l}=$()),yield o;if(u)break;const r=yield e.getNextPacket(t,v);S(r),f.decode(r),t=r}d=-1}),k=()=>p(this,null,function*(){S(f),yield f.flush();for(let e=0;e{g||(m=e,g=!0,a())}).finally(()=>{null==f||f.close()});const w=this._track,P=()=>{for(const e of n)null==e||e.close()};return{next(){return p(this,null,function*(){for(;;){if(w.input._disposed)throw u=!0,P(),new Ro;if(u)return{value:void 0,done:!0};if(g)throw u=!0,P(),m;if(n.length>0){const e=n.shift();return S(void 0!==e),l(),{value:e,done:!1}}if(c)return{value:void 0,done:!0};yield s}})},return(){return p(this,null,function*(){return u=!0,l(),a(),P(),{value:void 0,done:!0}})},throw(e){return p(this,null,function*(){throw e})},[Symbol.asyncIterator](){return this}}}}const io=e=>0===e?40:8;class ro extends eo{constructor(e,t,i,r,n,s){var a,o,l,c,u,f,m,p;super(e,t),this.codec=i,this.decoderConfig=r,this.rotation=n,this.timeResolution=s,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new pe,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 g=$a.find(e=>e.supports(i,r));if(g)this.customDecoder=new g,this.customDecoder.codec=i,this.customDecoder.config=r,this.customDecoder.onSample=e=>{if(!(e instanceof wa))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();S(void 0!==t),this.mergeAlpha(e,t)}else this.colorQueue.push(e)};if(ve()){if("avc"===i&&this.decoderConfig.description){const e=dt(B(this.decoderConfig.description));if(e&&e.sequenceParameterSets.length>0){const t=ft(e.sequenceParameterSets[0]);t&&(0===t.frameMbsOnlyFlag&&(this.decoderConfig=h(d({},this.decoderConfig),{hardwareAcceleration:"prefer-software"})),0!==t.maxDecFrameBuffering&&1!==t.bitstreamRestrictionFlag&&(e.sequenceParameterSets[0]=pt(t),this.decoderConfig=h(d({},this.decoderConfig),{description:ut(e)})))}}L(this.decoderConfig.colorSpace)||(this.decoderConfig=h(d({},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!=(f=null==(u=this.decoderConfig.colorSpace)?void 0:u.transfer)?f:"bt709",fullRange:null!=(p=null==(m=this.decoderConfig.colorSpace)?void 0:m.fullRange)&&p}}))}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:(S(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(S(this.decoder),ke()||X(this.inputTimestamps,e.timestamp,e=>e),ve()&&0===this.currentPacketIndex)if("avc"===this.codec){const t=[];let i=!1;for(const n of rt(e.data,this.decoderConfig)){const r=nt(e.data[n.offset]);if(i||(i=r>=1&&r<=5),r===Ye.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&B(t.description)[4];return lt(e,i+1)}return ot(e)})(t,this.decoderConfig);e=new Mi(r,e.type,e.timestamp,e.duration)}else if("hevc"===this.codec){const t=Et(e.data,this.decoderConfig);t&&(e=new Mi(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 so),!this.alphaDecoder){const e=e=>{if(this.colorQueue.length>0){const t=this.colorQueue.shift();S(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();S(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=Ot(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 gt(e,this.decoderConfig)){const i=kt(e[t.offset]);if(i===Ze.RASL_N||i===Ze.RASL_R)return!0}return!1}sampleHandler(e){if(ke()){if(this.sampleQueue.length>0&&e.timestamp>=P(this.sampleQueue).timestamp){for(const e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}X(this.sampleQueue,e,e=>e.timestamp)}else{const t=this.inputTimestamps.shift();S(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 p(this,null,function*(){const i=$();this.mergeAlphaPromises.push(i.promise);const r={sample:null};this.finalSamples.push(r);try{if(t){S(this.merger);const i=yield this.merger.merge(e,t);r.sample=new wa(i)}else r.sample=new wa(e);for(;this.finalSamples.length>0&&null!==this.finalSamples[0].sample;){const e=this.finalSamples.shift();this.sampleHandler(e.sample)}}catch(n){G(this.finalSamples,r),this.onError(n)}finally{G(this.mergeAlphaPromises,i.promise),i.resolve()}})}flush(){return p(this,null,function*(){var e;if(this.customDecoder?yield this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(S(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),ke()){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()):(S(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 no=null;class so{constructor(){this.workers=[],this.nextWorkerIndex=0,this.pendingRequests=new Map,this.nextRequestId=0}merge(e,t){if(0===this.workers.length){if(!no){const e=new Blob([`(${ao.toString()})()`],{type:"application/javascript"});no=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=$();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 ao=()=>{let e=null,t=null,i=Promise.resolve();self.addEventListener("message",e=>{const{id:t,color:n,alpha:s}=e.data;i=i.then(()=>p(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)=>p(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)=>p(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;ep(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 S={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,S)}),a=(e,i)=>p(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;ep(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 lo extends to{constructor(e,t={}){if(!(e instanceof yo))throw new TypeError("videoTrack must be an InputVideoTrack.");oo(t),super(),this._track=e,this._decoderOptions=t}_createDecoder(e,t){return p(this,null,function*(){if(!(yield this._track.canDecode())){if("undefined"===typeof VideoDecoder)throw new Error(Se("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 S(i&&n),n=h(d({},n),{hardwareAcceleration:this._decoderOptions.hardwareAcceleration,optimizeForLatency:this._decoderOptions.optimizeForLatency}),new ro(e,t,i,n,r,s)})}_createPacketSink(){return new Za(this._track)}getSample(e){return p(this,arguments,function*(e,t={}){Ya(e);try{for(var i,r,n,s=b(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 co{constructor(e,t={}){var i,r,n;if(this._rotation=0,this._initPromise=null,this._nextCanvasIndex=0,!(e instanceof yo))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&&Ra(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&&oo(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 lo(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=(()=>p(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=_a(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||be()});S(s),e._drawWithFitAndMipmapping(r,s,{fit:this._fit,rotation:this._rotation,crop:this._crop,targetIsFresh:n,fillBlack:!this._alpha&&be()});const a={canvas:r,timestamp:e.timestamp,duration:e.duration};return e.close(),a}getCanvas(e,t){return p(this,null,function*(){Ya(e),yield this._ensureInit();const i=yield this._videoSampleSink.getSample(e,t);return i&&this._videoSampleToWrappedCanvas(i)})}canvases(e,t,i){return k(this,null,function*(){yield new g(this._ensureInit()),yield*y(te(this._videoSampleSink.samples(e,t,i),e=>this._videoSampleToWrappedCanvas(e)))})}canvasesAtTimestamps(e,t){return k(this,null,function*(){yield new g(this._ensureInit()),yield*y(te(this._videoSampleSink.samplesAtTimestamps(e,t),e=>e&&this._videoSampleToWrappedCanvas(e)))})}}class uo extends eo{constructor(e,t,i,r){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new pe,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=Ga.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 qa))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 qa(e))}catch(t){this.onError(t)}},error:t=>{t.stack=e,this.onError(t)}}),this.decoder.configure(r)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(S(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--)):(S(this.decoder),null!=this.expectedFirstTimestamp||(this.expectedFirstTimestamp=e.timestamp),this.decoder.decode(e.toEncodedAudioChunk()))}flush(){return p(this,null,function*(){this.customDecoder?yield this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(S(this.decoder),yield this.decoder.flush()),this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0})}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(S(this.decoder),"closed"!==this.decoder.state&&this.decoder.close())}}class ho extends eo{constructor(e,t,i){super(e,t),this.decoderConfig=i,this.currentTimestamp=null,S(li.includes(i.codec)),this.codec=i.codec;const{dataType:r,sampleSize:n,littleEndian:s}=vi(this.codec);switch(this.inputSampleSize=n,n){case 1:"unsigned"===r?this.readInputValue=(e,t)=>e.getUint8(t)-c(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)-c(2,15):"signed"===r?this.readInputValue=(e,t)=>e.getInt16(t,s):S(!1);break;case 3:"unsigned"===r?this.readInputValue=(e,t)=>Z(e,t,s)-c(2,23):"signed"===r?this.readInputValue=(e,t)=>((e,t,i)=>Z(e,t,i)<<8>>8)(e,t,s):S(!1);break;case 4:"unsigned"===r?this.readInputValue=(e,t)=>e.getUint32(t,s)-c(2,31):"signed"===r?this.readInputValue=(e,t)=>e.getInt32(t,s):"float"===r?this.readInputValue=(e,t)=>e.getFloat32(t,s):S(!1);break;case 8:"float"===r?this.readInputValue=(e,t)=>e.getFloat64(t,s):S(!1);break;default:J(n),S(!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+c(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:J(n),S(!1)}}getDecodeQueueSize(){return 0}decode(e){const t=E(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 qa({format:this.outputFormat,data:n,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:i,timestamp:o});this.onSample(l)}flush(){return p(this,null,function*(){})}close(){}}class fo extends to{constructor(e){if(!(e instanceof bo))throw new TypeError("audioTrack must be an InputAudioTrack.");super(),this._track=e}_createDecoder(e,t){return p(this,null,function*(){if(!(yield this._track.canDecode())){if("undefined"===typeof AudioDecoder)throw new Error(Se("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 S(i&&r),li.includes(r.codec)?new ho(e,t,r):new uo(e,t,i,r)})}_createPacketSink(){return new Za(this._track)}getSample(e){return p(this,arguments,function*(e,t={}){Ya(e);try{for(var i,r,n,s=b(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 mo{constructor(e){if(!(e instanceof bo))throw new TypeError("audioTrack must be an InputAudioTrack.");this._audioSampleSink=new fo(e)}_audioSampleToWrappedArrayBuffer(e){const t={buffer:e.toAudioBuffer(),timestamp:e.timestamp,duration:e.duration};return e.close(),t}getBuffer(e,t){return p(this,null,function*(){Ya(e);const i=yield this._audioSampleSink.getSample(e,t);return i&&this._audioSampleToWrappedArrayBuffer(i)})}buffers(e,t,i){return te(this._audioSampleSink.samples(e,t,i),e=>this._audioSampleToWrappedArrayBuffer(e))}buffersAtTimestamps(e,t){return te(this._audioSampleSink.samplesAtTimestamps(e,t),e=>e&&this._audioSampleToWrappedArrayBuffer(e))}}class po{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof yo}isAudioTrack(){return this instanceof bo}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}getInternalCodecId(){return p(this,null,function*(){return this._backing.getInternalCodecId()})}get internalCodecId(){return go(this._backing.getInternalCodecId(),"internalCodecId","getInternalCodecId")}getLanguageCode(){return p(this,null,function*(){return this._backing.getLanguageCode()})}get languageCode(){return go(this._backing.getLanguageCode(),"languageCode","getLanguageCode")}getName(){return p(this,null,function*(){return this._backing.getName()})}get name(){return go(this._backing.getName(),"name","getName")}getTimeResolution(){return p(this,null,function*(){return this._backing.getTimeResolution()})}get timeResolution(){return go(this._backing.getTimeResolution(),"timeResolution","getTimeResolution")}isRelativeToUnixEpoch(){return p(this,null,function*(){return this._backing.isRelativeToUnixEpoch()})}getUnixTimeForTimestamp(e){return p(this,null,function*(){return this._backing.getUnixTimeForTimestamp(e)})}hasUnixTimeMapping(){return p(this,null,function*(){return null!==(yield this._backing.getUnixTimeForTimestamp(yield this.getFirstTimestamp()))})}getDisposition(){return p(this,null,function*(){return this._backing.getDisposition()})}get disposition(){return go(this._backing.getDisposition(),"disposition","getDisposition")}getBitrate(){return p(this,null,function*(){return this._backing.getBitrate()})}getAverageBitrate(){return p(this,null,function*(){return this._backing.getAverageBitrate()})}getFirstTimestamp(){return p(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 p(this,null,function*(){var t,i;const r=yield this._backing.getPacket(1/0,d({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 ae(n,yield this.getTimeResolution())})}getDurationFromMetadata(){return p(this,arguments,function*(e={}){return this._backing.getDurationFromMetadata(e)})}computePacketStats(e=1/0,t){return p(this,null,function*(){const i=new Za(this);let r=1/0,n=-1/0,s=0,a=0;try{for(var o,l,c,u=b(i.packets(void 0,void 0,d({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 p(this,null,function*(){return null!==(yield this._backing.getLiveRefreshInterval())})}getLiveRefreshInterval(){return p(this,null,function*(){return this._backing.getLiveRefreshInterval()})}canBePairedWith(e){if(!(e instanceof po))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 p(this,null,function*(){return this.input.getTracks(wo({filter:e=>e.canBePairedWith(this)},e))})}getPairableVideoTracks(e){return p(this,null,function*(){return this.input.getVideoTracks(wo({filter:e=>e.canBePairedWith(this)},e))})}getPairableAudioTracks(e){return p(this,null,function*(){return this.input.getAudioTracks(wo({filter:e=>e.canBePairedWith(this)},e))})}getPrimaryPairableVideoTrack(e){return p(this,null,function*(){return this.input.getPrimaryVideoTrack(wo({filter:e=>e.canBePairedWith(this)},e))})}getPrimaryPairableAudioTrack(e){return p(this,null,function*(){return this.input.getPrimaryAudioTrack(wo({filter:e=>e.canBePairedWith(this)},e))})}hasPairableTrack(e){return p(this,null,function*(){e&&(e=ko(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=ko(e)),this.hasPairableTrack(t=>p(this,null,function*(){return t.isVideoTrack()&&(!e||(yield e(t)))}))}hasPairableAudioTrack(e){return e&&(e=ko(e)),this.hasPairableTrack(t=>p(this,null,function*(){return t.isAudioTrack()&&(!e||(yield e(t)))}))}}const go=(e,t,i)=>{if(Pe(e))throw new Error(`'${t}' is deprecated and not available synchronously for this track. Use the preferred '${i}()' instead.`);return e},ko=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 Pe(r)?r.then(i):i(r)}:void 0};class yo extends po{constructor(e,t){super(e,t),this._pixelAspectRatioCache=null,this._backing=t}get type(){return"video"}getCodec(){return p(this,null,function*(){return this._backing.getCodec()})}get codec(){return go(this._backing.getCodec(),"codec","getCodec")}hasOnlyKeyPackets(){return p(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 p(this,null,function*(){return this._backing.getCodedWidth()})}get codedWidth(){return go(this._backing.getCodedWidth(),"codedWidth","getCodedWidth")}getCodedHeight(){return p(this,null,function*(){return this._backing.getCodedHeight()})}get codedHeight(){return go(this._backing.getCodedHeight(),"codedHeight","getCodedHeight")}getRotation(){return p(this,null,function*(){return this._backing.getRotation()})}get rotation(){return go(this._backing.getRotation(),"rotation","getRotation")}getSquarePixelWidth(){return p(this,null,function*(){return this._backing.getSquarePixelWidth()})}get squarePixelWidth(){return go(this._backing.getSquarePixelWidth(),"squarePixelWidth","getSquarePixelWidth")}getSquarePixelHeight(){return p(this,null,function*(){return this._backing.getSquarePixelHeight()})}get squarePixelHeight(){return go(this._backing.getSquarePixelHeight(),"squarePixelHeight","getSquarePixelHeight")}getPixelAspectRatio(){return p(this,null,function*(){var e;return null!=(e=this._pixelAspectRatioCache)?e:this._pixelAspectRatioCache=Ae({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=Ae({num:go(this._backing.getSquarePixelWidth(),"pixelAspectRatio","getPixelAspectRatio")*go(this._backing.getCodedHeight(),"pixelAspectRatio","getPixelAspectRatio"),den:go(this._backing.getSquarePixelHeight(),"pixelAspectRatio","getPixelAspectRatio")*go(this._backing.getCodedWidth(),"pixelAspectRatio","getPixelAspectRatio")})}getDisplayWidth(){return p(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=go(i,"displayWidth","getDisplayWidth");if(null!==e)return e}const r=go(this._backing.getRotation(),"displayWidth","getDisplayWidth")%180===0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight();return go(r,"displayWidth","getDisplayWidth")}getDisplayHeight(){return p(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=go(i,"displayHeight","getDisplayHeight");if(null!==e)return e}const r=go(this._backing.getRotation(),"displayHeight","getDisplayHeight")%180===0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth();return go(r,"displayHeight","getDisplayHeight")}getColorSpace(){return p(this,null,function*(){return this._backing.getColorSpace()})}hasHighDynamicRange(){return p(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 p(this,null,function*(){return this._backing.canBeTransparent()})}getDecoderConfig(){return p(this,null,function*(){return this._backing.getDecoderConfig()})}getCodecParameterString(){return p(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 p(this,null,function*(){try{const e=yield this._backing.getDecoderConfig();if(!e)return!1;const t=yield this._backing.getCodec();if(S(null!==t),$a.some(i=>i.supports(t,e)))return!0;if("undefined"===typeof VideoDecoder)return!1;return!0===(yield VideoDecoder.isConfigSupported(e)).supported}catch(e){return ze._error("Error during decodability check:",e),!1}})}determinePacketType(e){return p(this,null,function*(){if(!(e instanceof Mi))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 S(i),Ot(t,i,e.data)})}computeFrameRateMetrics(){return p(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&&(!Ee(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 Za(this),a=[];let o=-1/0,l=0;try{for(var c,u,d,h=b(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 b=0;be-t),x=P-1>>1,C=P>>1;let B=0,E=0,_=0;for(const b of I)if(_+=T.get(b),0===B&&_>x&&(B=b),_>C){E=b;break}const R=(k/B+k/E)/2;return{underlyingFrameRate:g,bestGuessFrameRate:null!==g?g:Co(R),minFrameRate:k/S,maxFrameRate:k/v,averageFrameRate:k*P/w,medianFrameRate:R,frameRateIsConstant:null!==g&&1===v&&1===S,probedPacketCount:l}})}}class bo extends po{constructor(e,t){super(e,t),this._backing=t}get type(){return"audio"}getCodec(){return p(this,null,function*(){return this._backing.getCodec()})}get codec(){return go(this._backing.getCodec(),"codec","getCodec")}hasOnlyKeyPackets(){return p(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 p(this,null,function*(){return this._backing.getNumberOfChannels()})}get numberOfChannels(){return go(this._backing.getNumberOfChannels(),"numberOfChannels","getNumberOfChannels")}getSampleRate(){return p(this,null,function*(){return this._backing.getSampleRate()})}get sampleRate(){return go(this._backing.getSampleRate(),"sampleRate","getSampleRate")}getDecoderConfig(){return p(this,null,function*(){return this._backing.getDecoderConfig()})}getCodecParameterString(){return p(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 p(this,null,function*(){try{const e=yield this._backing.getDecoderConfig();if(!e)return!1;const t=yield this._backing.getCodec();if(S(null!==t),Ga.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 ze._error("Error during decodability check:",e),!1}})}determinePacketType(e){return p(this,null,function*(){if(!(e instanceof Mi))throw new TypeError("packet must be an EncodedPacket.");return null===(yield this.getCodec())?null:"key"})}}const To=e=>-(null!=e?e:-1/0),vo=e=>-e,So=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 Pe(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 Pe(r)?r.then(i):i(r)}:void 0}},wo=(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 Pe(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 Pe(o)||Pe(l)?Promise.all([o,l]).then(([e,t])=>c(e,t)):c(o,l)}:void 0}),Po=(e,t)=>p(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=>Pe(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=>Pe(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)}),Io=(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 Vs)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof ps||e.source instanceof gs))throw new TypeError("options.source must be a Source or SourceRef.");if(e.source instanceof ps&&e.source._disposed)throw new TypeError("options.source must not be a disposed Source.");if(void 0!==e.initInput&&!(e.initInput instanceof Eo))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 ps?this._rootRef=e.source.ref():this._rootRef=e.source,this._sourceRefs.push(this._rootRef)}get _rootSource(){return this._rootRef.source}_getSourceUncached(e){return p(this,null,function*(){S(this._rootSource instanceof ks);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&&ys(i.request,e));if(i)return i.age++,Promise.resolve(i.sourceRef.source.ref());const r=this._sourceCachePromises.find(i=>i.cacheGroup===t&&ys(i.request,e));if(r)return r.promise.then(e=>e.sourceRef.source.ref());const n=(()=>p(this,null,function*(){const i=yield this._getSourceUncached(e);if(Re(this._sourceCache,e=>e.cacheGroup===t&&1===e.sourceRef.source._refCount)>=4){const e=Fe(this._sourceCache,e=>e.cacheGroup===t&&1===e.sourceRef.source._refCount?e.age:1/0);S(-1!==e);const i=this._sourceCache[e];this._sourceCache.splice(e,1),i.sourceRef.free(),G(this._sourceRefs,i.sourceRef)}this._sourceRefs.push(i);const r=this._sourceCachePromises.findIndex(t=>t.request===e);S(-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=(()=>p(this,null,function*(){var e;this._reader=new Fo(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 _o}))()}get source(){return this._rootSource}getFormat(){return p(this,null,function*(){return yield this._getDemuxer(),S(this._format),this._format})}canRead(){return p(this,null,function*(){try{return yield this._getDemuxer(),!0}catch(e){if(e instanceof _o)return!1;throw e}})}getFirstTimestamp(e){return p(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 p(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 p(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 p(this,null,function*(){e&&(e=So(e));const t=(yield this._getTrackBackings()).map(e=>this._wrapBackingAsTrack(e));return Po(t,e)})}getVideoTracks(e){return p(this,null,function*(){e&&(e=So(e));const t=(yield this.getTracks()).filter(e=>e.isVideoTrack());return Po(t,e)})}getAudioTracks(e){return p(this,null,function*(){e&&(e=So(e));const t=(yield this.getTracks()).filter(e=>e.isAudioTrack());return Po(t,e)})}getPrimaryVideoTrack(e){return p(this,null,function*(){var t;e&&(e=So(e));const i=wo(e,{sortBy:e=>p(null,null,function*(){return[vo((yield e.getDisposition()).default),vo(yield e.hasPairableAudioTrack()),vo(!(yield e.hasOnlyKeyPackets())),To(yield e.getBitrate())]})});return null!=(t=(yield this.getVideoTracks(i))[0])?t:null})}getPrimaryAudioTrack(e){return p(this,null,function*(){var t;e&&(e=So(e));const i=yield this.getPrimaryVideoTrack(),r=wo(e,{sortBy:e=>p(this,null,function*(){return[vo(!i||e.canBePairedWith(i)),vo((yield e.getDisposition()).default),To(yield e.getBitrate())]})});return null!=(t=(yield this.getAudioTracks(r))[0])?t:null})}_getTrackBackings(){return p(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 yo(this,e):new bo(this,e);return this._backingToTrack.set(e,i),i}getMimeType(){return p(this,null,function*(){return(yield this._getDemuxer()).getMimeType()})}getMetadataTags(){return p(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 _o extends Error{constructor(e="Input has an unsupported or unrecognizable format."){super(e),this.name="UnsupportedInputFormatError"}}class Ro extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}}class Fo{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 Ro;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 Ao(t,E(t),0,e,e)}const i=e+t,r=this.source._read(e,i,0,ms);return Pe(r)?r.then(t=>t?new Ao(t.bytes,t.view,t.offset,e,i):null):r?new Ao(r.bytes,r.view,r.offset,e,i):null}requestSliceRange(e,t,i){if(this.source._disposed)throw new Ro;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),n=r=>r||(S(null!==this.fileSizeNonStrict),this.requestSlice(e,ie(this.fileSizeNonStrict-e,t,i)));return Pe(r)?r.then(n):n(r)}}requestEntireFile(){if(null!==this.fileSizeNonStrict)return this.requestSlice(0,this.fileSizeNonStrict);return(()=>p(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(Pe(i)&&(i=yield i),!i||0===i.length)break;const r=Mo(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 Ao(i,E(i),0,0,t)}))()}}class Ao{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 Ao(e,E(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 Ao(this.bytes,this.view,this.offset,e,e+t)}}const Do=(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.`)},Mo=(e,t)=>{Do(e,t);const i=e.bytes.subarray(e.bufferPos,e.bufferPos+t);return e.bufferPos+=t,i},No=e=>(Do(e,1),e.view.getUint8(e.bufferPos++)),Oo=(e,t)=>{Do(e,2);const i=e.view.getUint16(e.bufferPos,t);return e.bufferPos+=2,i},Lo=e=>{Do(e,2);const t=e.view.getUint16(e.bufferPos,!1);return e.bufferPos+=2,t},zo=e=>{Do(e,3);const t=Z(e.view,e.bufferPos,!1);return e.bufferPos+=3,t},Uo=e=>{Do(e,2);const t=e.view.getInt16(e.bufferPos,!1);return e.bufferPos+=2,t},qo=(e,t)=>{Do(e,4);const i=e.view.getUint32(e.bufferPos,t);return e.bufferPos+=4,i},Wo=e=>{Do(e,4);const t=e.view.getUint32(e.bufferPos,!1);return e.bufferPos+=4,t},Ho=e=>{Do(e,4);const t=e.view.getUint32(e.bufferPos,!0);return e.bufferPos+=4,t},Vo=e=>{Do(e,4);const t=e.view.getInt32(e.bufferPos,!1);return e.bufferPos+=4,t},jo=(e,t)=>{let i,r;return t?(i=qo(e,!0),r=qo(e,!0)):(r=qo(e,!1),i=qo(e,!1)),4294967296*r+i},Ko=e=>4294967296*Wo(e)+Wo(e),Xo=e=>4294967296*Vo(e)+Wo(e),$o=e=>{const t=Ho(e),i=(e=>{Do(e,4);const t=e.view.getInt32(e.bufferPos,!0);return e.bufferPos+=4,t})(e);return 4294967296*i+t},Go=e=>{Do(e,4);const t=e.view.getFloat32(e.bufferPos,!1);return e.bufferPos+=4,t},Qo=e=>{Do(e,8);const t=e.view.getFloat64(e.bufferPos,!1);return e.bufferPos+=8,t},Yo=(e,t)=>{Do(e,t);let i="";for(let r=0;r_.decode(Mo(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 Zo,el,tl,il;(el=Zo||(Zo={}))[el.Unsynchronisation=128]="Unsynchronisation",el[el.ExtendedHeader=64]="ExtendedHeader",el[el.ExperimentalIndicator=32]="ExperimentalIndicator",el[el.Footer=16]="Footer",(il=tl||(tl={}))[il.ISO_8859_1=0]="ISO_8859_1",il[il.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",il[il.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",il[il.UTF_8=3]="UTF_8";const rl=128,nl=10,sl=["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"],al=(e,t)=>{var i;const r=e.filePos;null!=t.raw||(t.raw={}),null!=(i=t.raw).TAG||(i.TAG=Mo(e,rl-3)),e.filePos=r;const n=ol(e,30);n&&(null!=t.title||(t.title=n));const s=ol(e,30);s&&(null!=t.artist||(t.artist=s));const a=ol(e,30);a&&(null!=t.album||(t.album=a));const o=ol(e,4),l=Number.parseInt(o,10);Number.isInteger(l)&&l>0&&(null!=t.date||(t.date=new Date(String(l))));const c=Mo(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=ol(e,28),e.skip(2)}else e.skip(-30),u=ol(e,30);u&&(null!=t.comment||(t.comment=u));const d=No(e);d{const i=Mo(e,t),r=Ie(i.indexOf(0),i.length),n=i.subarray(0,r);let s="";for(let a=0;a{const t=e.filePos,i=Yo(e,3),r=No(e),n=No(e),s=No(e),a=Wo(e);if("ID3"!==i||255===r||255===n||0!==(2155905152&a))return e.filePos=t,null;let o=Ei(a);return s&Zo.Footer&&(o+=nl),{majorVersion:r,revision:n,flags:s,size:o}},cl=(e,t,i)=>{var r,n,s,a,o,l;if(![2,3,4].includes(t.majorVersion))return void ze._warn(`Unsupported ID3v2 major version: ${t.majorVersion}`);const c=t.flags&Zo.Footer?t.size-nl:t.size,u=Mo(e,c),d=new ul(t,u);if(t.flags&Zo.Unsynchronisation&&3===t.majorVersion&&d.ununsynchronizeAll(),t.flags&Zo.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&Zo.Unsynchronisation)),h)ze._warn(`Skipping encrypted ID3v2 frame ${e.id}`),d.pos=u;else if(f)ze._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!==sl[e]){null!=i.genre||(i.genre=sl[e]);break}}if(t=/^\d+$/.exec(e),t){const e=Number.parseInt(t[0]);if(void 0!==sl[e]){null!=i.genre||(i.genre=sl[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 ul{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:Ei(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 tl.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=Ie(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=Ie(r.findIndex(e=>0===e),r.length);return this.pos=i+Math.min(e+1,r.length),_.decode(r.subarray(0,e))}case tl.UTF_16_BE_NO_BOM:{const e=new TextDecoder("utf-16be"),t=Ie(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 tl.UTF_8:{const e=Ie(r.findIndex(e=>0===e),r.length);return this.pos=i+Math.min(e+1,r.length),_.decode(r.subarray(0,e))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";const t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}}class dl{constructor(e){this.events=e,this.input=null,this.audioSink=null,this.audioIterator=null,this.audioContext=null,this.gainNode=null,this.audioContextStartTime=0,this.playbackTimeAtStart=0,this.latestScheduledEndTime=0,this.duration=Number.NaN,this.paused=!0,this.volume=.7,this.muted=!1,this.playbackRate=1,this.asyncId=0,this.queuedNodes=new Set}get currentTime(){return this.paused?this.playbackTimeAtStart:(this.audioContext.currentTime-this.audioContextStartTime)*this.playbackRate+this.playbackTimeAtStart}ensureAudioContext(e){if(this.audioContext)return;const t=window.AudioContext||window.webkitAudioContext;try{this.audioContext=new t({sampleRate:e})}catch(i){this.audioContext=new t}this.gainNode=this.audioContext.createGain(),this.gainNode.connect(this.audioContext.destination),this.updateGain()}updateGain(){if(!this.gainNode)return;const e=this.muted?0:this.volume;this.gainNode.gain.value=e*e}stopQueuedNodes(){this.queuedNodes.forEach(e=>e.stop()),this.queuedNodes.clear()}stopIterator(){return p(this,null,function*(){var e;yield null==(e=this.audioIterator)?void 0:e.return(),this.audioIterator=null})}handleNoAudioTrack(){this.audioSink=null,this.ensureAudioContext()}load(e,t){return p(this,null,function*(){++this.asyncId,yield this.stopIterator(),this.stopQueuedNodes(),this.paused=!0,this.playbackTimeAtStart=0,this.audioContextStartTime=0;const{input:i,audioTrack:r,duration:n}=e;return this.input=i,this.duration=n,r?null!==r.codec&&(yield r.canDecode())?(this.ensureAudioContext(r.sampleRate),this.audioSink=new mo(r),void(null==t||t())):(this.audioSink=null,this.ensureAudioContext(),void(null==t||t())):(this.handleNoAudioTrack(),void(null==t||t()))})}runIterator(e){return p(this,null,function*(){if(!this.audioSink)return;yield this.stopIterator(),this.audioIterator=this.audioSink.buffers(this.currentTime);for(;;){if(e!==this.asyncId||this.paused)return;const i=[];let r=!1;try{for(let e=0;e<16;e++){const e=yield this.audioIterator.next();if(e.done){r=!0;break}i.push(e.value)}}catch(t){console.error("Audio iterator error:",t),r=!0}if(e!==this.asyncId||this.paused)return;i.length>0&&"suspended"===this.audioContext.state&&(yield this.audioContext.resume(),this.events.emit("canplay"),this.events.emit("playing"));for(const{buffer:e,timestamp:t}of i){const i=this.audioContext.createBufferSource();i.buffer=e,i.connect(this.gainNode),i.playbackRate.value=this.playbackRate;const r=this.audioContextStartTime+(t-this.playbackTimeAtStart)/this.playbackRate,n=(r+e.duration/this.playbackRate-this.audioContextStartTime)*this.playbackRate+this.playbackTimeAtStart;n>this.latestScheduledEndTime&&(this.latestScheduledEndTime=n),r>=this.audioContext.currentTime?i.start(r):i.start(this.audioContext.currentTime,(this.audioContext.currentTime-r)*this.playbackRate),this.queuedNodes.add(i),i.onended=()=>this.queuedNodes.delete(i)}if(r)break;yield new Promise(e=>setTimeout(e,0));const n=1;for(;this.latestScheduledEndTime-this.currentTime>n;){if(e!==this.asyncId||this.paused)return;yield new Promise(e=>setTimeout(e,50))}}})}play(){return p(this,null,function*(){if(!this.paused)return;this.audioContext||this.ensureAudioContext(),"suspended"===this.audioContext.state&&(yield this.audioContext.resume()),this.audioContextStartTime=this.audioContext.currentTime,this.latestScheduledEndTime=this.playbackTimeAtStart,this.paused=!1;const e=++this.asyncId;this.runIterator(e)})}pause(){this.paused||(this.playbackTimeAtStart=this.currentTime,this.paused=!0,this.stopIterator(),this.stopQueuedNodes())}seek(e){return p(this,null,function*(){this.playbackTimeAtStart=Math.max(0,e),this.audioContextStartTime=this.audioContext.currentTime,this.latestScheduledEndTime=this.playbackTimeAtStart;const t=++this.asyncId;this.paused||this.runIterator(t)})}setVolume(e,t){this.volume=e,this.muted=t,this.updateGain()}setPlaybackRate(e){if(e!==this.playbackRate&&(this.paused||(this.playbackTimeAtStart=this.currentTime,this.audioContextStartTime=this.audioContext.currentTime),this.playbackRate=e,!this.paused)){const e=++this.asyncId;this.runIterator(e)}}destroy(){var e;this.asyncId++,this.pause(),null==(e=this.audioContext)||e.close(),this.audioContext=null,this.input=null,this.audioSink=null}}function hl(e){return p(this,null,function*(){var t,i;return null!=(i=null!=(t=yield e.getAverageBitrate())?t:yield e.getBitrate())?i:0})}const fl=/\.m3u8(?:$|[?#])/i;function ml(e){return"string"===typeof e&&fl.test(e)}function pl(e){const t=function(e){return"string"===typeof e?new Is(e):e instanceof Blob?new vs(e):"undefined"!==typeof ReadableStream&&e instanceof ReadableStream?new Bs(e):null!=e?e:null}(e);return t?new Eo({source:t,formats:ml(e)?pa:ma}):null}class gl{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 p(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 kl(e){return p(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})}class yl{constructor({canvas:e,ctx:t,events:i,timeupdateInterval:r=250,avSyncTolerance:n=.12,dropLateFrames:s=!1,poster:a="",preflightRange:o=!1}){this.canvas=e,this.ctx=t,this.events=i,this.timeupdateInterval=r,this.avSyncTolerance=n,this.dropLateFrames=s,this.poster=a,this.preflightRange=o,this.input=null,this.videoSink=null,this.videoIterator=null,this.nextFrame=null,this.rafId=0,this.asyncId=0,this.width=0,this.height=0,this.duration=Number.NaN,this.audioClock=null,this.lastTimeUpdate=0,this.stalled=!1,this.playbackRate=1,this.posterDrawn=!1,this.isFetching=!1}preflight(e,t,i){return p(this,null,function*(){return function(e,t,i,r,n=()=>!0){return p(this,null,function*(){if((null==r?void 0:r.aborted)||!n())return!1;if(!t||"string"!==typeof e||ml(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(!this.poster||this.posterDrawn)return;const e=new Image;e.onload=()=>{this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.canvas.width=e.naturalWidth||this.canvas.width,this.canvas.height=e.naturalHeight||this.canvas.height,this.ctx.drawImage(e,0,0,this.canvas.width,this.canvas.height),this.posterDrawn=!0},e.src=this.poster}stopIterator(){return p(this,null,function*(){var e;yield null==(e=this.videoIterator)?void 0:e.return(),this.videoIterator=null})}clear(){this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height)}load(e,t){return p(this,null,function*(){++this.asyncId,yield this.stopIterator(),this.clear(),this.posterDrawn=!1;const{input:i,videoTrack:r,duration:n}=e;if(this.input=i,this.duration=n,!r)return this.handleNoVideoTrack(),void(null==t||t());if(null===r.codec||!(yield r.canDecode()))return this.handleNoVideoTrack(),void(null==t||t());const s=yield r.canBeTransparent();this.videoSink=new co(r,{poolSize:2,fit:"contain",alpha:s}),this.width=r.displayWidth,this.height=r.displayHeight,this.canvas.width=this.width,this.canvas.height=this.height,null==t||t(),yield this.resetIterator(0)})}handleNoVideoTrack(){this.videoSink=null,this.width=0,this.height=0,this.canvas.width=0,this.canvas.height=0,this.clear(),this.drawPoster()}resetIterator(e){return p(this,null,function*(){var t,i;if(yield this.stopIterator(),!this.videoSink)return;this.videoIterator=this.videoSink.canvases(e);const r=null!=(t=(yield this.videoIterator.next()).value)?t:null,n=null!=(i=(yield this.videoIterator.next()).value)?i:null;this.nextFrame=n,r?this.ctx.drawImage(r.canvas,0,0):this.drawPoster()})}updateNextFrame(e){return p(this,null,function*(){var t;if(this.videoIterator&&!this.isFetching){this.isFetching=!0;try{for(;;){const i=null!=(t=(yield this.videoIterator.next()).value)?t:null;if(!i||e!==this.asyncId)return;const r=this.audioClock.currentTime,n=this.dropLateFrames?Math.max(.06,this.avSyncTolerance/Math.max(1,this.playbackRate)):0;if(!(this.dropLateFrames&&i.timestampr)return void(this.nextFrame=null)}}}finally{this.isFetching=!1}}})}render(){if(!this.audioClock)return;const e=this.audioClock.currentTime,t=Date.now();if(t-this.lastTimeUpdate>=this.timeupdateInterval&&(this.events.emit("timeupdate"),this.lastTimeUpdate=t),Number.isFinite(this.duration)&&e>=this.duration)return this.stop(),this.stalled=!1,this.events.emit("ended"),this.events.emit("pause"),void this.events.emit("canplay");this.nextFrame&&this.nextFrame.timestamp<=e?(this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.ctx.drawImage(this.nextFrame.canvas,0,0),this.nextFrame=null,this.updateNextFrame(this.asyncId),this.stalled&&(this.events.emit("canplay"),this.events.emit("playing"),this.stalled=!1)):this.nextFrame||(this.updateNextFrame(this.asyncId),!this.nextFrame&&Number.isFinite(this.duration)&&ethis.render())}start(e){this.audioClock=e,this.asyncId++,this.stalled=!1,this.updateNextFrame(this.asyncId),this.rafId=requestAnimationFrame(()=>this.render())}stop(){cancelAnimationFrame(this.rafId)}seek(e){return p(this,null,function*(){this.asyncId++,yield this.resetIterator(e)})}setPlaybackRate(e){this.playbackRate=Math.max(.1,Number(e)||1)}destroy(){this.asyncId++,this.stop(),this.stopIterator(),this.posterDrawn=!1,this.videoSink=null,this.input=null}}class bl{constructor({canvas:e,ctx:t,events:i,option:r={}}){var n,s,a,o,l,c;this.events=i,this.option=r,this.audio=new dl(i),this.video=new yl({canvas:e,ctx:t,events:i,timeupdateInterval:null!=(n=r.timeupdateInterval)?n:250,avSyncTolerance:null!=(s=r.avSyncTolerance)?s:.12,dropLateFrames:null!=(a=r.dropLateFrames)&&a,poster:null!=(o=r.poster)?o:"",preflightRange:null!=(l=r.preflightRange)&&l}),this.paused=!0,this.ended=!1,this.readyState=0,this.networkState=0,this.error=null,this.seeking=!1,this.loadSeq=0,this.input=null,this.media=null,this.loadSession=null,this.destroyed=!1,null==(c=i.addEventListener)||c.call(i,"ended",()=>{this.ended=!0,this.paused=!0})}load(e){return p(this,null,function*(){var t;if(this.destroyed)return;const i=++this.loadSeq;if(null==(t=this.loadSession)||t.cancel(),i!==this.loadSeq||this.destroyed)return;if(this.pause(),i!==this.loadSeq||this.destroyed)return;this.disposeInput();const r=new gl;this.loadSession=r,this.ended=!1,this.error=null,this.networkState=2,this.readyState=0,r.defer(()=>this.events.emit("waiting")),r.defer(()=>this.events.emit("loadstart"));const n=Number.isFinite(this.option.loadTimeout)?this.option.loadTimeout:0;try{yield r.wait(this.performLoad(e,i,r),n)}catch(s){if(i!==this.loadSeq)return;const e=++this.loadSeq;if(r.cancel(),e!==this.loadSeq||this.destroyed)return;this.disposeInput(),this.error={code:4,message:s.message},this.networkState=3,this.events.emit("error")}})}performLoad(e,t){return p(this,arguments,function*(e,t,i=this.loadSession){if(!(yield this.video.preflight(e,null==i?void 0:i.signal,()=>t===this.loadSeq))||t!==this.loadSeq)return;const r=pl(e);if(!r)return this.video.handleNoVideoTrack(),void this.audio.handleNoAudioTrack();i.own(r);const n=yield function(e,t){return p(this,null,function*(){const i=yield e.getPrimaryVideoTrack(),r=i?yield i.getPrimaryPairableAudioTrack():yield e.getPrimaryAudioTrack(),n=yield kl({input:e,videoTrack:i,audioTrack:r}),s=i||r,a=ml(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"}})}(r,e);if(t!==this.loadSeq)return;this.input=r,this.media=n;let s=!n.videoTrack,a=!n.audioTrack;const o=()=>{s&&a&&(this.readyState=1,this.events.emit("loadedmetadata"),this.events.emit("durationchange"),this.events.emit("progress"))};try{if(yield Promise.all([this.video.load(n,()=>{t===this.loadSeq&&(s=!0,o())}),this.audio.load(n,()=>{t===this.loadSeq&&(a=!0,o())})]),t!==this.loadSeq)return;this.readyState=4,this.networkState=1,this.events.emit("loadeddata"),this.events.emit("canplay"),this.events.emit("canplaythrough"),this.events.emit("progress")}catch(l){if(t!==this.loadSeq)return;throw console.error("MediaBunny load error:",l),l}})}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 p(this,arguments,function*({videoTrack:e,audioTrack:t,videoMode:i,audioMode:r}){if(!this.media)return;const n=h(d({},this.media),{videoTrack:e,audioTrack:t,videoMode:i,audioMode:r}),s=!this.paused,a=this.currentTime;this.pause(),this.ended=!1,this.seeking=!0,this.events.emit("seeking"),this.events.emit("waiting"),n.duration=yield kl(n),this.media=n,yield Promise.all([this.video.load(n),this.audio.load(n)]),yield Promise.all([this.video.seek(a),this.audio.seek(a)]),this.readyState=4,this.networkState=1,this.seeking=!1,this.events.emit("loadedmetadata"),this.events.emit("durationchange"),this.events.emit("progress"),this.events.emit("loadeddata"),this.events.emit("canplay"),this.events.emit("canplaythrough"),this.events.emit("seeked"),s&&(yield this.play())})}selectHlsQuality(e){return p(this,null,function*(){var t,i;if(!(null==(t=this.media)?void 0:t.isHls)||!this.input)return;const r=yield this.input.getVideoTracks(),n="auto"===e?yield this.input.getPrimaryVideoTrack():null!=(i=r.find(t=>t.id===e))?i:this.media.videoTrack;if(!n)return;let s=this.media.audioTrack,a=this.media.audioMode;s&&n.canBePairedWith(s)||(s=yield n.getPrimaryPairableAudioTrack(),a="auto"),yield this.replaceTracks({videoTrack:n,audioTrack:s,videoMode:"auto"===e?"auto":"manual",audioMode:a})})}selectHlsAudio(e){return p(this,null,function*(){var t,i;if(!(null==(t=this.media)?void 0:t.isHls)||!this.input)return;const r=yield this.input.getAudioTracks(),n="auto"===e?this.media.videoTrack?yield this.media.videoTrack.getPrimaryPairableAudioTrack():yield this.input.getPrimaryAudioTrack():null!=(i=r.find(t=>t.id===e))?i:this.media.audioTrack;if(!n)return;let s=this.media.videoTrack,a=this.media.videoMode;s&&n.canBePairedWith(s)||(s=yield n.getPrimaryPairableVideoTrack(),a="auto"),yield this.replaceTracks({videoTrack:s,audioTrack:n,videoMode:a,audioMode:"auto"===e?"auto":"manual"})})}getHlsState(){return function(e){return p(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)=>p(null,null,function*(){return{id:e.id,track:e,index:t,name:yield e.getName(),height:yield e.getDisplayHeight(),bitrate:yield hl(e)}}))),Promise.all(a.map((e,t)=>p(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 hl(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"}})}(this.media)}play(){return p(this,null,function*(){this.paused&&(this.ended&&(this.ended=!1,yield this.seek(0)),this.paused=!1,yield this.audio.play(),this.video.start(this.audio),this.events.emit("play"),this.events.emit("playing"))})}pause(){this.paused||(this.paused=!0,this.audio.pause(),this.video.stop(),this.events.emit("pause"))}seek(e){return p(this,null,function*(){const t=!this.paused;this.ended=!1,this.seeking=!0,this.events.emit("seeking"),this.events.emit("waiting"),this.pause(),yield Promise.all([this.audio.seek(e),this.video.seek(e)]),this.seeking=!1,this.events.emit("seeked"),t&&!this.ended&&(yield this.play())})}setVolume(e,t){this.audio.setVolume(e,t)}setPlaybackRate(e){this.audio.setPlaybackRate(e),this.video.setPlaybackRate(e)}destroy(){var e;this.destroyed||(this.destroyed=!0,this.loadSeq++,null==(e=this.loadSession)||e.cancel(),this.pause(),this.disposeInput(),this.audio.destroy(),this.video.destroy())}get currentTime(){return this.audio.currentTime}get duration(){var e,t,i;return null!=(i=null!=(t=null==(e=this.media)?void 0:e.duration)?t:this.audio.duration)?i:this.video.duration}get videoWidth(){return this.video.width}get videoHeight(){return this.video.height}}const Tl=new WeakMap;function vl(e){let t=Tl.get(e);return t||(t={closed:!1,frames:new Set},Tl.set(e,t)),t}class Sl{constructor({art:e,canvas:t,ctx:i,option:r}){var n,s;this.art=e,this.canvas=t,this.option=r,this.events=new v,this.engine=new bl({canvas:t,ctx:i,events:this.events,option:r}),this._src=null,this._volume=null!=(n=r.volume)?n:.7,this._muted=!!r.muted,this._playbackRate=1,this.engine.setVolume(this._volume,this._muted),this.setupEventForwarding(),r.source?this.src=r.source:(null==(s=e.option)?void 0:s.url)&&(this.src=e.option.url)}setupEventForwarding(){const{events:e}=this.art.constructor.config;e.forEach(e=>{this.events.addEventListener(e,e=>{this.art.emit(`video:${e.type}`,e)})})}addEventListener(e,t){this.events.addEventListener(e,t)}removeEventListener(e,t){this.events.removeEventListener(e,t)}get src(){return this._src}set src(e){this._src=e,e&&this.engine.load(e)}get currentSrc(){return this._src}get currentTime(){return this.engine.currentTime}set currentTime(e){this.engine.seek(Number(e)||0)}get duration(){return this.engine.duration}get buffered(){return this.createTimeRanges(0,this.engine.duration)}get played(){return this.createTimeRanges(0,this.engine.currentTime)}get seekable(){return this.createTimeRanges(0,this.engine.duration)}createTimeRanges(e,t){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=vl(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){vl(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=vl(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 Sl({art:t,canvas:n,ctx:s,option:e});t.mediabunny=a;const o={};for(const e in n)"function"===typeof n[e]&&(o[e]=n[e].bind(n));const l=new Set([...Object.getOwnPropertyNames(a),...Object.getOwnPropertyNames(Object.getPrototypeOf(a))]);for(const e of l)"constructor"!==e&&(e in n||Object.defineProperty(n,e,{get(){const t=a[e];return"function"===typeof t?t.bind(a):t},set(t){a[e]=t},configurable:!0,enumerable:!0}));for(const e in o)n[e]=(...t)=>o[e](...t);function c(){var e;(null==(e=t.template)?void 0:e.$player)&&!t.option.autoSize&&Object.assign(n.style,{width:"100%",height:"100%",objectFit:"contain"})}return t.on("resize",c),t.on("video:loadedmetadata",c),function({art:e,shim:t,option:i}){if(i.m3u8)return e.on("video:loadedmetadata",u),e.on("restart",u),{update:u};function r(t){e.controls.cache.has(t)&&e.controls.remove(t)}function n(t){e.setting.find(t)&&e.setting.remove(t)}function s(){r("mediabunny-quality"),n("mediabunny-quality")}function a(){r("mediabunny-audio"),n("mediabunny-audio")}function o(e={}){return e.control||e.setting}function l(r){return p(this,null,function*(){var n;const a=(null==(n=i.m3u8)?void 0:n.quality)||{};if(!o(a)||!(null==r?void 0:r.levels.length))return void s();const l=a.auto||"Auto",c=a.title||"Quality",d=a.getName||(e=>e.name||`${e.height}P`),h=r.currentLevel?d(r.currentLevel):l,f=T(r.levels.map(e=>{var t;return{html:d(e),value:e.id,default:(null==(t=r.currentLevel)?void 0:t.id)===e.id}}),"html").sort((e,t)=>{const i=r.levels.find(t=>t.id===e.value),n=r.levels.find(e=>e.id===t.value);return((null==n?void 0:n.height)||0)-((null==i?void 0:i.height)||0)});f.push({html:l,value:"auto",default:!r.currentLevel});const m=i=>p(null,null,function*(){return yield t.switchM3u8Quality(i.value),e.notice.show=`${c}: ${i.html}`,yield u(),i.html});a.control&&e.controls.update({name:"mediabunny-quality",position:"right",html:h,style:{padding:"0 10px"},selector:f,onSelect:m}),a.setting&&e.setting.update({name:"mediabunny-quality",tooltip:h,html:c,icon:'',width:200,selector:f,onSelect:m})})}function c(r){return p(this,null,function*(){var n;const s=(null==(n=i.m3u8)?void 0:n.audio)||{};if(!o(s)||!(null==r?void 0:r.audios.length)||r.audios.length<2)return void a();const l=s.auto||"Auto",c=s.title||"Audio",d=s.getName||(e=>e.name||e.lang||e.language),h=r.currentAudio?d(r.currentAudio):l,f=T(r.audios.map(e=>{var t;return{html:d(e),value:e.id,default:(null==(t=r.currentAudio)?void 0:t.id)===e.id}}),"html");f.push({html:l,value:"auto",default:!r.currentAudio});const m=i=>p(null,null,function*(){return yield t.switchM3u8Audio(i.value),e.notice.show=`${c}: ${i.html}`,yield u(),i.html});s.control&&e.controls.update({name:"mediabunny-audio",position:"right",html:h,style:{padding:"0 10px"},selector:f,onSelect:m}),s.setting&&e.setting.update({name:"mediabunny-audio",tooltip:h,html:c,icon:'',width:200,selector:f,onSelect:m})})}function u(){return p(this,null,function*(){const e=yield t.getM3u8State();if(!e)return s(),void a();yield Promise.all([l(e),c(e)])})}}({art:t,shim:a,option:e}),t.on("destroy",()=>{delete t.mediabunny,a.destroy()}),n}}}); +!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=Object.defineProperty,r=Object.defineProperties,n=Object.getOwnPropertyDescriptors,s=Object.getOwnPropertySymbols,a=Object.prototype.hasOwnProperty,o=Object.prototype.propertyIsEnumerable,l=(e,t)=>(t=Symbol[e])?t:Symbol.for("Symbol."+e),c=e=>{throw TypeError(e)},u=Math.pow,d=(e,t,r)=>t in e?i(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,h=(e,t)=>{for(var i in t||(t={}))a.call(t,i)&&d(e,i,t[i]);if(s)for(var i of s(t))o.call(t,i)&&d(e,i,t[i]);return e},f=(e,t)=>r(e,n(t)),m=(e,t,i)=>t.has(e)||c("Cannot "+i),p=(e,t,i)=>(m(e,t,"read from private field"),i?i.call(e):t.get(e)),g=(e,t,i)=>t.has(e)?c("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,i),k=(e,t,i,r)=>(m(e,t,"write to private field"),r?r.call(e,i):t.set(e,i),i),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())}),b=function(e,t){this[0]=e,this[1]=t},T=(e,t,i)=>{var r,n=(e,t,r,s)=>{try{var a=i[e](t),o=(t=a.value)instanceof b,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[l("asyncIterator")]=()=>a,s("next"),s("throw"),s("return"),a},v=e=>{var t,i=e[l("asyncIterator")],r=!1,n={};return null==i?(i=e[l("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 b(new Promise(r=>{var n=i[e](t);n instanceof Object||c("Object expected"),r(n)}),1)}}),n[l("iterator")]=()=>n,t("next"),"throw"in i?t("throw"):n.throw=e=>{throw e},"return"in i&&t("return"),n},S=(e,t,i)=>(t=e[l("asyncIterator")])?t.call(e):(e=e[l("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 w(e,t){const i=new Map;return e.filter(e=>{const r=e[t];return void 0===r||!i.has(r)&&i.set(r,1)})}class P{constructor(){g(this,e,!1),this.listeners=new Map}addEventListener(t,i){var r;p(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(p(this,e))return;const n=Object.assign(new Event(t),{detail:i});null==(r=this.listeners.get(t))||r.forEach(t=>{p(this,e)||t(n)})}destroy(){k(this,e,!0),this.listeners.clear()}}function I(e){if(!e)throw new Error("Assertion failed.")}e=new WeakMap;const x=e=>{const t=(e%360+360)%360;if(0===t||90===t||180===t||270===t)return t;throw new Error(`Invalid rotation ${e}.`)},C=e=>e&&e[e.length-1],B=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-u(2,r))},_=e=>{const t=B(e);return 0===(1&t)?-(t>>1):t+1>>1},R=e=>e.constructor===Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),F=e=>e.constructor===DataView?e:ArrayBuffer.isView(e)?new DataView(e.buffer,e.byteOffset,e.byteLength):new DataView(e),A=new TextDecoder,D=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])),M={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},N=D(M),O={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},L=D(O),z={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},U=D(z),q=e=>!!e&&!!e.primaries&&!!e.transfer&&!!e.matrix&&void 0!==e.fullRange,W={primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0},H=e=>e instanceof ArrayBuffer||"undefined"!==typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e);class V{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 j=/^[0-9a-fA-F]+$/,K=e=>[...e].map(e=>e.toString(16).padStart(2,"0")).join(""),X=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,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},Q=(e,t,i)=>{const r=G(e,i(t),i);e.splice(r+1,0,t)},Y=()=>{let e,t;return{promise:new Promise((i,r)=>{e=i,t=r}),resolve:e,reject:t}},J=(e,t)=>{const i=e.indexOf(t);-1!==i&&e.splice(i,1)},Z=(e,t)=>{for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},ee=(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}`)},ie=(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},re=(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)},ne=(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}}),se=(e,t,i)=>Math.max(t,Math.min(i,e)),ae="und",oe=e=>{const t=Math.round(e);return Math.abs(e/t-1)<10*Number.EPSILON?t:e},le=(e,t)=>Math.round(e/t)*t,ce=(e,t)=>Math.round(e*t)/t,ue=(e,t)=>Math.floor(e/t)*t,de=e=>{let t=0;for(;0!==e;)e&=e-1,t++;return t},he=/^[a-z]{3}$/,fe=e=>he.test(e),me=1e6*(1+Number.EPSILON),pe=(e,t)=>{const i=h(h({},e),t);if(e.headers||t.headers){const r=e.headers?ge(e.headers):{},n=t.headers?ge(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},ge=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},ke=(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(We._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 Le(1e3*e)),n())throw a}});class ye{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}let be=null;const Te=()=>{var e;return null!==be?be:be=!("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 ve=null;const Se=()=>{var e;return null!==ve?ve:ve="undefined"!==typeof navigator&&(null==(e=navigator.userAgent)?void 0:e.includes("Firefox"))};let we=null;const Pe=()=>{var e;return null!==we?we:we=!("undefined"===typeof navigator||!(null==(e=navigator.vendor)?void 0:e.includes("Google Inc"))&&!/Chrome/.test(navigator.userAgent))},Ie=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.`,xe=y(null,null,function*(){}).constructor,Ce=e=>e instanceof xe||e instanceof Promise||"function"===typeof(null==e?void 0:e.then),Be=(e,t)=>-1!==e?e:t,Ee=(e,t,i,r)=>e<=r&&i<=t,_e=e=>{const t=atob(e),i=new Uint8Array(t.length);for(let r=0;r{null!=Symbol.dispose||(Symbol.dispose=Symbol("Symbol.dispose"))},Fe=e=>"number"===typeof e&&!Number.isNaN(e),Ae=(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("/")},De=(e,t)=>{let i=0;for(let r=0;r{let i=-1,r=1/0;for(let n=0;n{I(Number.isInteger(e.num)),I(Number.isInteger(e.den)),I(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}},Oe=(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.`)},Le=e=>new Promise(t=>setTimeout(t,e));class ze{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 Ue,qe;(qe=Ue||(Ue={}))[qe.Silent=0]="Silent",qe[qe.Errors=1]="Errors",qe[qe.Warnings=2]="Warnings",qe[qe.Info=3]="Info";class We{constructor(){}static get level(){return We._level}static set level(e){if(e!==Ue.Silent&&e!==Ue.Errors&&e!==Ue.Warnings&&e!==Ue.Info)throw new TypeError("Invalid log level. Use one of the values of the LogLevel enum.");We._level=e}static get _emitter(){var e;return null!=(e=We._emitterInstance)?e:We._emitterInstance=new ze}static on(e,t,i){return We._emitter.on(e,t,i)}static _error(...e){We._emitter._emit("error",e),We._level>=Ue.Errors&&console.error(...e)}static _warn(...e){We._emitter._emit("warn",e),We._level>=Ue.Warnings&&console.warn(...e)}static _info(...e){We._emitter._emit("info",e),We._level>=Ue.Info&&console.info(...e)}}We._level=Ue.Info,We._emitterInstance=null;class He{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 Ve{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 je={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1};class Ke{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 Ke(this.bytes);return e.pos=this.pos,e}}const Xe=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],$e=[-1,1,2,3,4,5,6,8],Ge=e=>{if(!e||e.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");const t=new Ke(e),i=Qe(t),{frequencyIndex:r,sampleRate:n}=Ye(t),s=t.readBits(4);let a=null;s>=1&&s<=7&&(a=$e[s]);let o=i,l=!1,c=n;if(5===i||29===i)l=29===i,c=Ye(t).sampleRate,o=Qe(t),22===o&&t.skipBits(4);else for(;t.getBitsLeft()>15;){const e=t.pos;if(695===t.readBits(11)){5===Qe(t)&&t.readBits(1)&&(c=Ye(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}},Qe=e=>{const t=e.readBits(5);return 31===t?32+e.readBits(6):t},Ye=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&R(t.description)[4];return st(e,i+1)}return nt(e)},ot=e=>31&e,lt=e=>{const t=[],i=e.length;for(let r=0;r{const t=e.reduce((e,t)=>e+ct.byteLength+t.byteLength,0),i=new Uint8Array(t);let r=0;for(const n of e)i.set(ct,r),r+=ct.byteLength,i.set(n,r),r+=n.byteLength;return i},dt=(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:re(e,n,s.byteLength);break;case 4:e.setUint32(n,s.byteLength,!1)}n+=t,r.set(s,n),n+=s.byteLength}return r},ht=e=>{try{const t=[],i=[],r=[];for(const o of nt(e)){const n=e.subarray(o.offset,o.offset+o.length),s=ot(n[0]);s===et.SPS?t.push(n):s===et.PPS?i.push(n):s===et.SPS_EXT&&r.push(n)}if(0===t.length)return null;if(0===i.length)return null;const n=t[0],s=gt(n);I(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 We._error("Error building AVC Decoder Configuration Record:",t),null}},ft=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=F(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=lt(e),r=new Ke(i);r.skipBits(1),r.skipBits(2);if(7!==r.readBits(5))return null;const n=r.readAlignedByte(),s=r.readAlignedByte(),a=r.readAlignedByte();B(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=B(r),3===o&&(u=r.readBits(1)),l=B(r),c=B(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:C(fi),n=Math.min(Math.floor(r.maxDpbMbs/(e*i)),16);P=n,x=n}else P=0,x=0}return I(null!==x),{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:w,colourPrimaries:b,matrixCoefficients:v,transferCharacteristics:T,fullRangeFlag:S,numReorderFrames:P,maxDecFrameBuffering:x,vuiParametersFlagBitOffset:F,bitstreamRestrictionFlagBitOffset:E,bitstreamRestrictionFlag:R}}catch(i){return We._error("Error parsing AVC SPS:",i),null}},kt=e=>{const t=B(e);e.skipBits(4),e.skipBits(4);for(let i=0;i<=t;i++)B(e),B(e),e.skipBits(1);e.skipBits(5),e.skipBits(5),e.skipBits(5),e.skipBits(5)},yt=e=>{I(1!==e.bitstreamRestrictionFlag);const t=new Uint8Array(e.emulationUnpreventedBytes.byteLength+64),i=new Ke(e.emulationUnpreventedBytes),r=new Ke(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)):(I(null!==e.bitstreamRestrictionFlagBitOffset),r.copyBits(e.bitstreamRestrictionFlagBitOffset,i)),r.writeBits(1,1),r.writeBits(1,1),E(r,2),E(r,1),E(r,16),E(r,16),E(r,e.numReorderFrames),E(r,e.maxDecFrameBuffering),r.writeBits(1,1),r.writeBits((8-r.pos%8)%8,0);const n=r.pos/8;return I(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))},bt=(e,t)=>{if(t.description){const i=3&R(t.description)[21];return st(e,i+1)}return nt(e)},Tt=e=>e>>1&63,vt=e=>{try{const t=new Ke(lt(e));t.skipBits(16),t.readBits(4);const i=t.readBits(3),r=t.readBits(1),{general_profile_space:n,general_tier_flag:s,general_profile_idc:a,general_profile_compatibility_flags:o,general_constraint_indicator_flags:l,general_level_idc:c}=wt(t,i);B(t);const u=B(t);let d=0;3===u&&(d=t.readBits(1));const h=B(t),f=B(t);let m=h,p=f;if(t.readBits(1)){const e=B(t),i=B(t),r=B(t),n=B(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=B(t),k=B(t);B(t);const y=t.readBits(1);let b=0;for(let e=y?0:i;e<=i;e++)B(t),b=B(t),B(t);B(t),B(t),B(t),B(t),B(t),B(t),t.readBits(1)&&t.readBits(1)&&Pt(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(4),t.skipBits(4),B(t),B(t),t.skipBits(1));const T=B(t);if(It(t,T),t.readBits(1)){const e=B(t);for(let i=0;i{try{const t=[],i=[],r=[],n=[];for(const l of nt(e)){const s=e.subarray(l.offset,l.offset+l.length),a=Tt(s[0]);a===it.VPS_NUT?t.push(s):a===it.SPS_NUT?i.push(s):a===it.PPS_NUT?r.push(s):a!==it.PREFIX_SEI_NUT&&a!==it.SUFFIX_SEI_NUT||n.push(s)}if(0===i.length||0===r.length)return null;const s=vt(i[0]);if(!s)return null;let a=0;if(r.length>0){const e=r[0],t=new Ke(lt(e));t.skipBits(16),B(t),B(t),t.skipBits(1),t.skipBits(1),t.skipBits(3),t.skipBits(1),t.skipBits(1),B(t),B(t),_(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&B(t),_(t),_(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:it.VPS_NUT,nalUnits:t}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:it.SPS_NUT,nalUnits:i}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:it.PPS_NUT,nalUnits:r}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:Tt(n[0][0]),nalUnits:n}]:[]];return{configurationVersion:1,generalProfileSpace:s.generalProfileSpace,generalTierFlag:s.generalTierFlag,generalProfileIdc:s.generalProfileIdc,generalProfileCompatibilityFlags:s.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:s.generalConstraintIndicatorFlags,generalLevelIdc:s.generalLevelIdc,minSpatialSegmentationIdc:s.minSpatialSegmentationIdc,parallelismType:a,chromaFormatIdc:s.chromaFormatIdc,bitDepthLumaMinus8:s.bitDepthLumaMinus8,bitDepthChromaMinus8:s.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:s.spsMaxSubLayersMinus1+1,temporalIdNested:s.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:o}}catch(t){return We._error("Error building HEVC Decoder Configuration Record:",t),null}},wt=(e,t)=>{const i=e.readBits(2),r=e.readBits(1),n=e.readBits(5);let s=0;for(let u=0;u<32;u++)s=s<<1|e.readBits(1);const a=new Uint8Array(6);for(let u=0;u<6;u++)a[u]=e.readBits(8);const o=e.readBits(8),l=[],c=[];for(let u=0;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&&_(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-(B(e)+1)}else o=t-1;e.readBits(1),B(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=B(e),i=B(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=pt[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)&&(B(e),B(e)),e.readBits(1),e.readBits(1),e.readBits(1),e.readBits(1)&&(B(e),B(e),B(e),B(e)),e.readBits(1)&&(e.readBits(32),e.readBits(32),e.readBits(1)&&B(e),e.readBits(1)&&Bt(e,!0,t)),e.readBits(1)&&(e.readBits(1),e.readBits(1),e.readBits(1),a=B(e),B(e),B(e),B(e),B(e)),{pixelAspectRatio:o,colourPrimaries:i,transferCharacteristics:r,matrixCoefficients:n,fullRangeFlag:s,minSpatialSegmentationIdc:a}},Bt=(e,t,i)=>{let r=!1,n=!1,s=!1;r=1===e.readBits(1),n=1===e.readBits(1),(r||n)&&(s=1===e.readBits(1),s&&(e.readBits(8),e.readBits(5),e.readBits(1),e.readBits(5)),e.readBits(4),e.readBits(4),s&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5));for(let a=0;a<=i;a++){let t=!0;1===e.readBits(1)||(t=1===e.readBits(1));let i=!1;t?B(e):i=1===e.readBits(1);let a=1;if(!i){a=B(e)+1}r&&Et(e,a,s),n&&Et(e,a,s)}},Et=(e,t,i)=>{for(let r=0;r{const i=new Set;let r=_t.audAllowed;for(const s of bt(e,t)){if(r===_t.noMoreDataAllowed){i.add(s.offset);continue}const t=Tt(e[s.offset]);if(r===_t.eoBitstreamAllowed&&37!==t){i.add(s.offset);continue}let n=!1;35===t?r>_t.audAllowed?n=!0:r=_t.beforeFirstVcl:t<=31?r>_t.afterFirstVcl?n=!0:r=_t.afterFirstVcl:36===t?r!==_t.afterFirstVcl?n=!0:r=_t.eoBitstreamAllowed:37===t?r<_t.afterFirstVcl?n=!0:r=_t.noMoreDataAllowed:32===t||33===t||34===t||39===t||t>=41&&t<=44||t>=48&&t<=55?r>_t.beforeFirstVcl?n=!0:r=_t.beforeFirstVcl:(38===t||40===t||t>=45&&t<=47||t>=56&&t<=63)&&r<_t.afterFirstVcl&&(n=!0),n&&i.add(s.offset)}if(0===i.size)return null;const n=[];for(const s of bt(e,t))i.has(s.offset)||n.push(e.subarray(s.offset,s.offset+s.length));return((e,t)=>{if(t.description){const i=3&R(t.description)[21];return dt(e,i+1)}return ut(e)})(n,t)},At={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}},Dt=e=>{var t,i,r;const n=new Ke(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=C(mi).level;for(const m of mi)if(d<=m.maxPictureSize){h=m.level;break}const f=At[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}},Mt=function*(e){const t=new Ke(e),i=()=>{let e=0;for(let i=0;i<8;i++){const r=t.readAlignedByte();if(e+=(127&r)*u(2,7*i),!(128&r))break;if(7===i&&128&r)return null}return e>u(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);I(t.pos%8===0),yield{type:r,data:e.subarray(t.pos/8,t.pos/8+a)},t.skipBits(8*a)}},Nt=e=>{for(const{type:t,data:i}of Mt(e)){if(1!==t)continue;const e=new Ke(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,S=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&&(S=e.readBits(2))),{profile:r,level:s,tier:a,bitDepth:m,monochrome:p,chromaSubsamplingX:T,chromaSubsamplingY:v,chromaSamplePosition:S,videoFullRangeFlag:b,colourPrimaries:g,transferCharacteristics:k,matrixCoefficients:y}}return null},Ot=e=>{if(e.length<36)return null;const t=F(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)}},Lt=[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],zt=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}},Ut=(e,t,i)=>{switch(e){case"avc":for(const e of at(i,t)){const t=i[e.offset],r=ot(t);if(r>=et.NON_IDR_SLICE&&r<=et.SLICE_DPC)return"delta";if(r===et.IDR)return"key";if(r===et.SEI&&!Pe()){const t=i.subarray(e.offset,e.offset+e.length),r=lt(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 Ke(r);e.pos=8*n;const t=B(e),i=e.readBits(1);if(0===t&&1===i)return"key"}n+=t}while(n{var i,r;const n=F(e);let s=0;const a=n.getUint32(s,!0);s+=4;const o=A.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=_e(c),i=F(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=A.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})}}}},Vt=[2,1,2,3,3,4,4,5],jt=e=>{if(e.length<7)return null;if(11!==e[0]||119!==e[1])return null;const t=new Ke(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)}},Kt=[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],Xt=[1,2,3,6],$t=e=>{if(e.length<6)return null;if(11!==e[0]||119!==e[1])return null;const t=new Ke(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=Xt[s];let d;d=n<3?Je[n]/1e3:Ze[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}]}},Gt=e=>{const t=e.substreams[0];return I(t),t.fscod<3?Je[t.fscod]:null!==t.fscod2&&t.fscod2<3?Ze[t.fscod2]:null},Qt=e=>{const t=e.substreams[0];I(t);let i=Vt[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},Yt=[0,8e3,16e3,32e3,0,0,11025,22050,44100,0,0,12e3,24e3,48e3,96e3,192e3],Jt=[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],Zt=[16,16,20,20,0,24,24,0],ei=[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],ii=[32e3,44100,48e3,0],ri=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],ni=[512,1024,2048,4096],si=e=>{const t=oi(e),i=F(e);let r=t?4*Math.ceil(t.frameSize/4):0,n=null;for(;r+4<=e.length&&1683496997===i.getUint32(r);){const t=li(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}},ai=e=>{const t=si(e);return(null==t?void 0:t.core)?t.hasExtensions?"dtsh":"dtsc":null},oi=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 Ke(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>=ei.length)return null;const a=Yt[t.readBits(4)];if(0===a)return null;const o=Jt[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=Zt[t.readBits(3)];if(0===c)return null;const u=0!==l;return{frameSize:n,sampleRate:a,numberOfChannels:ei[s]+(u?1:0),sampleCount:32*r,channelLayout:ti[s]|(u?8:0),amode:s,lfePresent:u,bitRate:o,pcmResolution:c}},li=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 Ke(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=ii[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}}},ci=e=>de(e)+de(44646&e),ui=["avc","hevc","vp9","av1","vp8","prores"],di=["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"],hi=["aac","opus","mp3","vorbis","flac","ac3","eac3","dts",...di],fi=[{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}],pi=".01.01.01.01.00",gi=".0.110.01.01.01.0",ki=["ap4x","ap4h","apch","apcn","apcs","apco"],yi=["dtsc","dtsh","dtsl","dtse"],bi=e=>{const{codec:t,codecDescription:i,colorSpace:r,avcCodecInfo:n,hevcCodecInfo:s,vp9CodecInfo:a,av1CodecInfo:o,proresFormat:l}=e;if("avc"===t){if(I(null!==e.avcType),n){const t=new Uint8Array([n.avcProfileIndication,n.profileCompatibility,n.avcLevelIndication]);return`avc${e.avcType}.${K(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}.${K(i.subarray(1,4))}`}if("hevc"===t){let e,t,r,n,a,o;if(s)e=s.generalProfileSpace,t=s.generalProfileIdc,r=X(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=F(i),l=s.getUint8(1);e=l>>6&3,t=31&l,r=X(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=C(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.${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(pi)&&(t=t.slice(0,-15)),t}if("av1"===t){if(!o){const t=e.width*e.height;let i=C(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"),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)?M[r.primaries]:1,u=(null==r?void 0:r.transfer)?O[r.transfer]:1,d=(null==r?void 0:r.matrix)?z[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(gi)&&(f=f.slice(0,-17)),f}if("prores"===t)return null!=l?l:"apch";throw null!==t&&te(t),new TypeError(`Unhandled codec '${t}'.`)},Ti=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=mt(e.codecDescription))?void 0:i.sequenceParameterSets[0]),r){const e=gt(r);if(e)return{primaries:N[e.colourPrimaries],transfer:L[e.transferCharacteristics],matrix:U[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case"hevc":{let t=null==(n=null==(r=e.hevcCodecInfo)?void 0:r.arrays.find(e=>e.nalUnitType===it.SPS_NUT))?void 0:n.nalUnits[0];if(!t&&e.codecDescription&&(t=null==(a=null==(s=(e=>{try{const t=F(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,S=t.getUint8(i++),w=[];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===it.SPS_NUT))?void 0:a.nalUnits[0]),t){const e=vt(t);if(e)return{primaries:N[e.colourPrimaries],transfer:L[e.transferCharacteristics],matrix:U[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case"vp8":break;case"vp9":if(e.vp9CodecInfo)return{primaries:N[e.vp9CodecInfo.colourPrimaries],transfer:L[e.vp9CodecInfo.transferCharacteristics],matrix:U[e.vp9CodecInfo.matrixCoefficients],fullRange:!!e.vp9CodecInfo.videoFullRangeFlag};break;case"av1":if(e.av1CodecInfo)return{primaries:N[e.av1CodecInfo.colourPrimaries],transfer:L[e.av1CodecInfo.transferCharacteristics],matrix:U[e.av1CodecInfo.matrixCoefficients],fullRange:!!e.av1CodecInfo.videoFullRangeFlag};break;case"prores":if(e.proresCodecInfo)return{primaries:N[e.proresCodecInfo.colourPrimaries],transfer:L[e.proresCodecInfo.transferCharacteristics],matrix:U[e.proresCodecInfo.matrixCoefficients],fullRange:e.proresCodecInfo.fullRange}}return{primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0}},vi=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=Ge(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&&di.includes(t))return t;throw new TypeError(`Unhandled codec '${t}'.`)},Si=48e3,wi=/^pcm-([usf])(\d+)(be)?$/,Pi=e=>{if(I(di.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=wi.exec(e);let i;I(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?u(2,7):0}},Ii=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":ki.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":yi.includes(e)?"dts":"ulaw"===e?"ulaw":"alaw"===e?"alaw":wi.test(e)?e:"webvtt"===e?"webvtt":null,xi=[44100,48e3,32e3],Ci=[-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],Bi=1483304551,Ei=1231971951,_i=(e,t)=>3===e?3===t?21:36:3===t?13:21,Ri=(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=Ci[16*a*4+16*c+(n>>4&15)];if(-1===g)return{header:null,bytesAdvanced:1};const k=1e3*g,y=xi[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 Ai,Di;(Di=Ai||(Ai={}))[Di.FrameCount=1]="FrameCount",Di[Di.FileSize=2]="FileSize",Di[Di.Toc=4]="Toc";const Mi=e=>3===e?1:2;class Ni{constructor(e){this.input=e}dispose(){}}const Oi=new Uint8Array(0);class Li{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===Oi&&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===Oi}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){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 Li(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 Li(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 zi=e=>{const t=F(e);let i=0;const r=t.getUint8(i);i+=1,i+=3;const n=K(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=jo(e);const i=el(e,4);let r=8;1===t&&(t=Go(e),r=16);const n=t-r;return n<0?null:{name:i,totalSize:t,headerSize:r,contentSize:n}},Wi=e=>Xo(e)/65536,Hi=e=>Xo(e)/1073741824,Vi=e=>{let t=0;for(let i=0;i<4;i++){t<<=7;const i=zo(e);if(t|=127&i,0===(128&i))break}return t},ji=e=>{let t=qo(e);return e.skip(2),t=Math.min(t,e.remainingLength),A.decode(Lo(e,t))},Ki=e=>{const t=qi(e);if(!t||"data"!==t.name)return null;if(e.remainingLength<8)return null;const i=jo(e);e.skip(4);const r=Lo(e,t.contentSize-8);switch(i){case 1:return A.decode(r);case 2:return new TextDecoder("utf-16be").decode(r);case 13:return new He(r,"image/jpeg");case 14:return new He(r,"image/png");case 27:return new He(r,"image/bmp");default:return r}},Xi=16,$i=new Uint32Array(256),Gi=new Uint32Array(256),Qi=new Uint32Array(256),Yi=new Uint32Array(256),Ji=new Uint32Array(256),Zi=new Uint32Array(256),er=new Uint32Array(10);let tr=!1;class ir{constructor(){this.roundkey=new Uint32Array(44),this.iv=new Uint32Array(Xi/Uint32Array.BYTES_PER_ELEMENT),this.in=new Uint8Array(Xi),this.out=new Uint8Array(Xi),this.inView=new DataView(this.in.buffer),this.outView=new DataView(this.out.buffer)}init({key:e,iv:t}){I(16===e.byteLength),I(16===t.byteLength),tr||(()=>{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);$i[s]=t<<24|t<<16|t<<8|t,Zi[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);Gi[s]=n,Qi[s]=n>>>8|n<<24,Yi[s]=n>>>16|n<<16,Ji[s]=n>>>24|n<<8}let n=1;for(let s=0;s<10;s++)er[s]=n<<24,n=n<<1^(128&n?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 n=4;n<44;n+=4){const e=this.roundkey[n-1];this.roundkey[n]=this.roundkey[n-4]^4278190080&$i[e>>>16&255]^16711680&$i[e>>>8&255]^65280&$i[e>>>0&255]^255&$i[e>>>24&255]^er[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]]^Qi[255&$i[t>>>16&255]]^Yi[255&$i[t>>>8&255]]^Ji[255&$i[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=Gi[e>>>24]^Qi[r>>>16&255]^Yi[i>>>8&255]^Ji[255&t]^this.roundkey[n],c=Gi[t>>>24]^Qi[e>>>16&255]^Yi[r>>>8&255]^Ji[255&i]^this.roundkey[n+1],u=Gi[i>>>24]^Qi[t>>>16&255]^Yi[e>>>8&255]^Ji[255&r]^this.roundkey[n+2],d=Gi[r>>>24]^Qi[i>>>16&255]^Yi[t>>>8&255]^Ji[255&e]^this.roundkey[n+3],e=l,t=c,i=u,r=d}const h=4278190080&Zi[e>>>24&255]^16711680&Zi[r>>>16&255]^65280&Zi[i>>>8&255]^255&Zi[t>>>0&255]^this.roundkey[40],f=4278190080&Zi[t>>>24&255]^16711680&Zi[e>>>16&255]^65280&Zi[r>>>8&255]^255&Zi[i>>>0&255]^this.roundkey[41],m=4278190080&Zi[i>>>24&255]^16711680&Zi[t>>>16&255]^65280&Zi[e>>>8&255]^255&Zi[r>>>0&255]^this.roundkey[42],p=4278190080&Zi[r>>>24&255]^16711680&Zi[i>>>16&255]^65280&Zi[t>>>8&255]^255&Zi[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 rr extends Ni{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(Ce(r)&&(r=yield r),!r)break;const n=e,s=qi(r);if(!s)break;if("ftyp"===s.name||"styp"===s.name){const e=el(r,4);this.isQuickTime="qt "===e}else{if("moov"===s.name){let e=this.reader.requestSlice(r.filePos,s.contentSize);if(Ce(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){I(null!==this.reader.fileSize);let e=this.reader.requestSlice(this.reader.fileSize-4,4);Ce(e)&&(e=yield e),I(e);const t=jo(e),i=this.reader.fileSize-t;if(i>=0&&i<=this.reader.fileSize-16){let e=this.reader.requestSliceRange(i,8,16);if(Ce(e)&&(e=yield e),e){const t=qi(e);if(t&&"mfra"===t.name){let i=this.reader.requestSlice(e.filePos,t.contentSize);Ce(i)&&(i=yield i),i&&this.readContiguousBoxes(i)}}}}}))()}copyMetadataFromInitInput(e){return y(this,null,function*(){const t=yield e._getDemuxer();if(t.constructor!==rr)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(I(t.info),"video"===t.info.type&&-1!==t.info.width){const e=t;t.trackBacking=new sr(e),this.tracks.push(t)}else if("audio"===t.info.type&&-1!==t.info.numberOfChannels){const e=t;t.trackBacking=new ar(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;I(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&&di.includes(e.info.codec)&&0===r.sampleCompositionTimeOffsets.length){I("audio"===(null==(i=e.info)?void 0:i.type));const t=Pi(e.info.codec),n=[],s=[];for(let i=0;ie.startIndex),u=r.sampleTimingEntries[c],d=G(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=C(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)dr(e,r.timestamp);else{const t=G(i,s.moofOffset-1,e=>e.moofOffset);if(-1!==t){const r=i[t];dr(e,r.endTimestamp)}}e.startTimestampIsFinal=!0}const r=G(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 pr(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;fe(t.languageCode)||(t.languageCode=ae)}}break;case"hdlr":{const t=this.currentTrack;if(!t)break;e.skip(8);const i=el(e,4);"vide"===i?t.info={type:"video",width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:h({},W),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=ge,this.readContiguousBoxes(e.slice(ye,ke.contentSize))}break;case"stsd":{const t=this.currentTrack;if(!t)break;if(null===t.info||t.sampleTable)break;const i=zo(e);e.skip(3);const r=jo(e);for(let n=0;n0&&(1===a?(e.skip(4),l=8*jo(e),e.skip(8)):2===a&&(e.skip(4),c=Zo(e),o=jo(e),e.skip(4),l=jo(e),u=jo(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=Si;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(yi.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":(We._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":(We._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":(We._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":(We._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":(We._warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null):32===e?t.info.codec="pcm-f32be":64===e?t.info.codec="pcm-f64be":(We._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!==zo(e),t.encryptionInfo.defaultPerSampleIvSize=zo(e),t.encryptionInfo.defaultKid=K(Lo(e,16)),t.encryptionInfo.defaultIsProtected&&0===t.encryptionInfo.defaultPerSampleIvSize){const i=zo(e),r=new Uint8Array(16);r.set(Lo(e,i),0),t.encryptionInfo.defaultConstantIv=r}}break;case"avcC":{const t=this.currentTrack;if(!t)break;if(I(t.info),0===ke.contentSize)break;t.info.codecDescription=Lo(e,ke.contentSize)}break;case"hvcC":{const t=this.currentTrack;if(!t)break;if(I(t.info),0===ke.contentSize)break;t.info.codecDescription=Lo(e,ke.contentSize)}break;case"vpcC":{const i=this.currentTrack;if(!i)break;I("video"===(null==(t=i.info)?void 0:t.type)),e.skip(4);const r=zo(e),n=zo(e),s=zo(e),a=s>>4,o=s>>1&7,l=1&s,c=zo(e),u=zo(e),d=zo(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;I("video"===(null==(i=t.info)?void 0:i.type)),e.skip(1);const o=zo(e),l=o>>5,c=31&o,u=zo(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=Lo(e,ke.contentSize-4),b=Nt(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;I("video"===(null==(o=t.info)?void 0:o.type));const i=el(e,4);if("nclx"!==i&&"nclc"!==i)break;const r=qo(e),n=qo(e),s=qo(e);let a;"nclx"===i&&(a=Boolean(128&zo(e))),t.info.colorSpace={primaries:N[r],transfer:L[n],matrix:U[s],fullRange:a}}break;case"pasp":{const t=this.currentTrack;if(!t)break;I("video"===(null==(l=t.info)?void 0:l.type));const i=jo(e),r=jo(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);I(3===zo(e)),Vi(e),e.skip(2);const i=zo(e),r=0!==(64&i),n=0!==(32&i);if(0!==(128&i)&&e.skip(2),r){const t=zo(e);e.skip(t)}n&&e.skip(2);I(4===zo(e));const s=Vi(e),a=e.filePos,o=zo(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":We._warn(`Unsupported audio codec (objectTypeIndication ${o}) - discarding track.`),e.skip(12),s>e.filePos-a){I(5===zo(e));const i=Vi(e);if(t.info.codecDescription=Lo(e,i),"aac"===t.info.codec){const e=Ge(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;I("audio"===(null==(u=t.info)?void 0:u.type)),t.info.pcmLittleEndian=!!(255&qo(e))}break;case"pcmC":{const t=this.currentTrack;if(!t)break;I("audio"===(null==(d=t.info)?void 0:d.type)),e.skip(4);const i=zo(e);t.info.pcmLittleEndian=Boolean(1&i),t.info.pcmSampleSize=zo(e)}break;case"dOps":{const t=this.currentTrack;if(!t)break;I("audio"===(null==(m=t.info)?void 0:m.type)),e.skip(1);const i=zo(e),r=qo(e),n=jo(e),s=Ho(e),a=zo(e);let o;o=0!==a?Lo(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;I("audio"===(null==(p=t.info)?void 0:p.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=Lo(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;I("audio"===(null==(g=t.info)?void 0:g.type));const i=Lo(e,3),r=new Ke(i),n=r.readBits(2);r.skipBits(8);const s=r.readBits(3),a=r.readBits(1);n<3&&(t.info.sampleRate=Je[n]),t.info.numberOfChannels=Vt[s]+a}break;case"dec3":{const t=this.currentTrack;if(!t)break;I("audio"===(null==(k=t.info)?void 0:k.type));const i=(e=>{if(e.length<2)return null;const t=new Ke(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}})(Lo(e,ke.contentSize));if(!i){We._warn("Invalid dec3 box contents, ignoring.");break}const r=Gt(i);null!==r&&(t.info.sampleRate=r),t.info.numberOfChannels=Qt(i)}break;case"ddts":{const t=this.currentTrack;if(!t)break;I("audio"===(null==(y=t.info)?void 0:y.type));const i=(e=>{if(e.length<20)return null;const t=F(e),i=t.getUint32(0);if(0===i)return null;const r=new Ke(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=ci(o):ae.id===i);if(!r)break;const n=jo(e),s=(12&n)>>2,a=3&n,o=[zo,qo,Wo,jo],l=o[(48&n)>>4],c=o[s],u=o[a],d=jo(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!=(T=null==d?void 0:d.defaultSampleDescriptionIndex)?T:null,defaultSampleDuration:null!=(v=null==d?void 0:d.defaultSampleDuration)?v:null,defaultSampleSize:null!=(S=null==d?void 0:d.defaultSampleSize)?S:null,defaultSampleFlags:null!=(w=null==d?void 0:d.defaultSampleFlags)?w:null,startTimestamp:null,encryptionAuxInfo:null},i?u.currentFragmentState.baseDataOffset=Go(e):l&&(u.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),r&&(u.currentFragmentState.sampleDescriptionIndex=jo(e)),n&&(u.currentFragmentState.defaultSampleDuration=jo(e)),s&&(u.currentFragmentState.defaultSampleSize=jo(e)),a&&(u.currentFragmentState.defaultSampleFlags=jo(e)),o&&(u.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{const t=this.currentTrack;if(!t)break;I(t.currentFragmentState);const i=zo(e);e.skip(3);const r=0===i?jo(e):Go(e);t.currentFragmentState.startTimestamp=r}break;case"trun":{const t=this.currentTrack;if(!t)break;I(this.currentFragment),I(t.currentFragmentState);const i=zo(e),r=Wo(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=jo(e);let d=null;n&&(d=Xo(e));let h,f=null;s&&(f=jo(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=Lo(e,r));const s=mr(t);s.defaultSampleInfoSize=i,s.sampleSizes=n,s.sampleCount=r}break;case"saio":{const t=this.currentTrack;if(!t||!t.encryptionInfo)break;const i=zo(e);if(1&Wo(e)){const i=el(e,4),r=jo(e);if(i!==t.encryptionInfo.scheme||0!==r)break}const r=jo(e);if(0===r)break;r>1&&We._warn("Multiple saio entries are not supported; using the first offset only.");let n=0===i?jo(e):Number(Go(e));this.currentFragment&&(n+=this.currentFragment.moofOffset);mr(t).offset=n}break;case"senc":{const t=this.currentTrack;if(!t||!t.encryptionInfo)break;I(this.currentFragment);const i=this.currentFragment.trackData.get(t.id);if(!i)break;e.skip(1);const r=Wo(e),n=Boolean(2&r),s=jo(e),a=t.encryptionInfo.defaultPerSampleIvSize;I(null!==a);for(let o=0;o0?r.set(Lo(e,a),0):r.set(t.encryptionInfo.defaultConstantIv,0);let s=null;if(n){const t=qo(e);s=[];for(let i=0;i0&&(null!=(ce=this.metadataTags).trackNumber||(ce.trackNumber=t)),i&&Number.isInteger(i)&&i>0&&(null!=(ue=this.metadataTags).tracksTotal||(ue.tracksTotal=i))}break;case"trkn":if(n instanceof Uint8Array&&n.length>=6){const e=F(n),t=e.getUint16(2,!1),i=e.getUint16(4,!1);t>0&&(null!=(de=this.metadataTags).trackNumber||(de.trackNumber=t)),i>0&&(null!=(he=this.metadataTags).tracksTotal||(he.tracksTotal=i))}break;case"disc":case"disk":if(n instanceof Uint8Array&&n.length>=6){const e=F(n),t=e.getUint16(2,!1),i=e.getUint16(4,!1);t>0&&(null!=(me=this.metadataTags).discNumber||(me.discNumber=t)),i>0&&(null!=(pe=this.metadataTags).discsTotal||(pe.discsTotal=i))}}}}}return e.filePos=be,!0}}class nr{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;I(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 oe(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=or(r,i),s=yield this.fetchPacketForSampleIndex(n,t);return fr(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=G(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=ee(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 I(-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=cr(i,e);if(!r)return null;let n;if(t.metadataOnly)n=Oi;else{let t=this.internalTrack.demuxer.reader.requestSlice(r.sampleOffset,r.sampleSize);if(Ce(t)&&(t=yield t),!t)return null;if(n=Lo(t,r.sampleSize),this.internalTrack.encryptionInfo){let t=null;if(this.internalTrack.encryptionAuxInfo){const i=yield pr(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);ee.timestamp),f=-1!==h?this.internalTrack.fragmentLookupTable[h]:null,m=G(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(Ce(e)&&(e=yield e),!e)break;const i=k,s=qi(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&&Ot(e.data)}}else{const e=yield this.getFirstPacket({}),t=e&&Nt(e.data);t&&(this.internalTrack.info.av1CodecInfo=t)}else{const t=yield this.getFirstPacket({}),i=t&&Dt(t.data);i&&(this.internalTrack.info.vp9CodecInfo=f(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&&St(e.data)}else{const e=yield this.getFirstPacket({});this.internalTrack.info.avcCodecInfo=e&&ht(e.data)}if(!q(this.internalTrack.info.colorSpace)){const e=Ti(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:bi(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 ar extends nr{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&&ai(e.data)}return{codec:vi(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 or=(e,t)=>{if(e.presentationTimestamps){const i=G(e.presentationTimestamps,t,e=>e.presentationTimestamp);return-1===i?-1:e.presentationTimestamps[i].sampleIndex}{const i=G(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)}},lr=(e,t)=>{var i;if(!e.keySampleIndices)return or(e,t);if(e.presentationTimestamps){const i=G(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.keySampleIndices,i,e=>e))return i}return-1}{const r=or(e,t),n=G(e.keySampleIndices,r,e=>e);return null!=(i=e.keySampleIndices[n])?i:-1}},cr=(e,t)=>{const i=G(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=G(e.sampleCompositionTimeOffsets,t,e=>e.startIndex),a=e.sampleCompositionTimeOffsets[s];a&&t-a.startIndexe.startSampleIndex),c=e.sampleToChunk[l];I(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)}},ur=(e,t)=>{var i;if(!e.keySampleIndices)return t+1;const r=G(e.keySampleIndices,t,e=>e);return null!=(i=e.keySampleIndices[r+1])?i:-1},dr=(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},hr=e=>{const[t,i]=e,r=Math.atan2(i,t);return Number.isFinite(r)?r*(180/Math.PI):0},fr=e=>0===e.sampleSizes.length,mr=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}},pr=(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{I(i.sampleSizes);for(let e=0;e0?i.defaultSampleInfoSize:i.sampleSizes[e],o=new Uint8Array(16);s>0?o.set(Lo(n,s),0):o.set(t.defaultConstantIv,0);let l=null;if(r>s){const e=qo(n);l=[];for(let t=0;te.defaultConstantIv?{iv:e.defaultConstantIv,subsamples:null}:null,kr=(e,t,i,r)=>y(null,null,function*(){var n;I(e.encryptionInfo);const s=e.encryptionInfo;I(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{I(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);I(null!==t.defaultCryptByteBlock&&null!==t.defaultSkipByteBlock);const o=Tr(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}),br=(e,t,i,r)=>{const n=new ir;n.init({key:e,iv:i.iv});const s=t.defaultCryptByteBlock,a=t.defaultSkipByteBlock;if(I(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 vr,Sr;(Sr=vr||(vr={}))[Sr.EBML=440786851]="EBML",Sr[Sr.EBMLVersion=17030]="EBMLVersion",Sr[Sr.EBMLReadVersion=17143]="EBMLReadVersion",Sr[Sr.EBMLMaxIDLength=17138]="EBMLMaxIDLength",Sr[Sr.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",Sr[Sr.DocType=17026]="DocType",Sr[Sr.DocTypeVersion=17031]="DocTypeVersion",Sr[Sr.DocTypeReadVersion=17029]="DocTypeReadVersion",Sr[Sr.Void=236]="Void",Sr[Sr.Segment=408125543]="Segment",Sr[Sr.SeekHead=290298740]="SeekHead",Sr[Sr.Seek=19899]="Seek",Sr[Sr.SeekID=21419]="SeekID",Sr[Sr.SeekPosition=21420]="SeekPosition",Sr[Sr.Duration=17545]="Duration",Sr[Sr.Info=357149030]="Info",Sr[Sr.TimestampScale=2807729]="TimestampScale",Sr[Sr.MuxingApp=19840]="MuxingApp",Sr[Sr.WritingApp=22337]="WritingApp",Sr[Sr.Tracks=374648427]="Tracks",Sr[Sr.TrackEntry=174]="TrackEntry",Sr[Sr.TrackNumber=215]="TrackNumber",Sr[Sr.TrackUID=29637]="TrackUID",Sr[Sr.TrackType=131]="TrackType",Sr[Sr.FlagEnabled=185]="FlagEnabled",Sr[Sr.FlagDefault=136]="FlagDefault",Sr[Sr.FlagForced=21930]="FlagForced",Sr[Sr.FlagOriginal=21934]="FlagOriginal",Sr[Sr.FlagHearingImpaired=21931]="FlagHearingImpaired",Sr[Sr.FlagVisualImpaired=21932]="FlagVisualImpaired",Sr[Sr.FlagCommentary=21935]="FlagCommentary",Sr[Sr.FlagLacing=156]="FlagLacing",Sr[Sr.Name=21358]="Name",Sr[Sr.Language=2274716]="Language",Sr[Sr.LanguageBCP47=2274717]="LanguageBCP47",Sr[Sr.CodecID=134]="CodecID",Sr[Sr.CodecPrivate=25506]="CodecPrivate",Sr[Sr.CodecDelay=22186]="CodecDelay",Sr[Sr.SeekPreRoll=22203]="SeekPreRoll",Sr[Sr.DefaultDuration=2352003]="DefaultDuration",Sr[Sr.Video=224]="Video",Sr[Sr.PixelWidth=176]="PixelWidth",Sr[Sr.PixelHeight=186]="PixelHeight",Sr[Sr.DisplayWidth=21680]="DisplayWidth",Sr[Sr.DisplayHeight=21690]="DisplayHeight",Sr[Sr.DisplayUnit=21682]="DisplayUnit",Sr[Sr.AlphaMode=21440]="AlphaMode",Sr[Sr.Audio=225]="Audio",Sr[Sr.SamplingFrequency=181]="SamplingFrequency",Sr[Sr.Channels=159]="Channels",Sr[Sr.BitDepth=25188]="BitDepth",Sr[Sr.SimpleBlock=163]="SimpleBlock",Sr[Sr.BlockGroup=160]="BlockGroup",Sr[Sr.Block=161]="Block",Sr[Sr.BlockAdditions=30113]="BlockAdditions",Sr[Sr.BlockMore=166]="BlockMore",Sr[Sr.BlockAdditional=165]="BlockAdditional",Sr[Sr.BlockAddID=238]="BlockAddID",Sr[Sr.BlockDuration=155]="BlockDuration",Sr[Sr.ReferenceBlock=251]="ReferenceBlock",Sr[Sr.Cluster=524531317]="Cluster",Sr[Sr.Timestamp=231]="Timestamp",Sr[Sr.Cues=475249515]="Cues",Sr[Sr.CuePoint=187]="CuePoint",Sr[Sr.CueTime=179]="CueTime",Sr[Sr.CueTrackPositions=183]="CueTrackPositions",Sr[Sr.CueTrack=247]="CueTrack",Sr[Sr.CueClusterPosition=241]="CueClusterPosition",Sr[Sr.Colour=21936]="Colour",Sr[Sr.MatrixCoefficients=21937]="MatrixCoefficients",Sr[Sr.TransferCharacteristics=21946]="TransferCharacteristics",Sr[Sr.Primaries=21947]="Primaries",Sr[Sr.Range=21945]="Range",Sr[Sr.Projection=30320]="Projection",Sr[Sr.ProjectionType=30321]="ProjectionType",Sr[Sr.ProjectionPoseRoll=30325]="ProjectionPoseRoll",Sr[Sr.Attachments=423732329]="Attachments",Sr[Sr.AttachedFile=24999]="AttachedFile",Sr[Sr.FileDescription=18046]="FileDescription",Sr[Sr.FileName=18030]="FileName",Sr[Sr.FileMediaType=18016]="FileMediaType",Sr[Sr.FileData=18012]="FileData",Sr[Sr.FileUID=18094]="FileUID",Sr[Sr.Chapters=272869232]="Chapters",Sr[Sr.Tags=307544935]="Tags",Sr[Sr.Tag=29555]="Tag",Sr[Sr.Targets=25536]="Targets",Sr[Sr.TargetTypeValue=26826]="TargetTypeValue",Sr[Sr.TargetType=25546]="TargetType",Sr[Sr.TagTrackUID=25541]="TagTrackUID",Sr[Sr.TagEditionUID=25545]="TagEditionUID",Sr[Sr.TagChapterUID=25540]="TagChapterUID",Sr[Sr.TagAttachmentUID=25542]="TagAttachmentUID",Sr[Sr.SimpleTag=26568]="SimpleTag",Sr[Sr.TagName=17827]="TagName",Sr[Sr.TagLanguage=17530]="TagLanguage",Sr[Sr.TagString=17543]="TagString",Sr[Sr.TagBinary=17541]="TagBinary",Sr[Sr.ContentEncodings=28032]="ContentEncodings",Sr[Sr.ContentEncoding=25152]="ContentEncoding",Sr[Sr.ContentEncodingOrder=20529]="ContentEncodingOrder",Sr[Sr.ContentEncodingScope=20530]="ContentEncodingScope",Sr[Sr.ContentCompression=20532]="ContentCompression",Sr[Sr.ContentCompAlgo=16980]="ContentCompAlgo",Sr[Sr.ContentCompSettings=16981]="ContentCompSettings",Sr[Sr.ContentEncryption=20533]="ContentEncryption";const wr=[vr.EBML,vr.Segment],Pr=[vr.SeekHead,vr.Info,vr.Cluster,vr.Tracks,vr.Cues,vr.Attachments,vr.Chapters,vr.Tags],Ir=[...wr,...Pr],xr=16,Cr=e=>{if(e.remainingLength<1)return null;const t=zo(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=zo(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=Cr(e);if(null===t)return null;if(e.remainingLength{if(e.remainingLength<1)return null;if(255===zo(e))return;e.skip(-1);const t=Br(e);return null===t?null:72057594037927940!==t?t:void 0},Fr=e=>{I(e.remainingLength>=2);const t=_r(e);if(null===t)return null;const i=Rr(e);return null===i?null:{id:t,size:i}},Ar=(e,t)=>{const i=Lo(e,t);let r=0;for(;r{const i=Lo(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?Jo(e):Zo(e)},Nr=(e,t,i,r)=>y(null,null,function*(){const n=new Set(i);let s=t;for(;null===r||ss?r:s,found:!1}}),Or=(e,t,i,r)=>y(null,null,function*(){const n=u(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,xr);if(Ce(t)&&(t=yield t),!t)break;const i=Fr(t);if(!i)break;const r=i.id;let n=i.size;const s=t.filePos;if(r===vr.EBML){Jr(n);let e=this.reader.requestSlice(s,n);if(Ce(e)&&(e=yield e),!e)break;this.readContiguousElements(e)}else if(r===vr.Segment){if(yield this.readSegment(s,n),void 0===n)break;if(null===this.reader.fileSize)break}else if(r===vr.Cluster){if(null===this.reader.fileSize)break;if(void 0===n){n=(yield Nr(this.reader,s,Ir,this.reader.fileSize)).pos-s}const e=C(this.segments);e&&(e.elementEndPos=s+n)}Jr(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=an[l].flag;this.currentSegment[e]=!0,Jr(a);let t=this.reader.requestSlice(o,a);Ce(t)&&(t=yield t),t&&this.readContiguousElements(t)}else if(s===vr.Tags||s===vr.Attachments){s===vr.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,Jr(a);let e=this.reader.requestSlice(o,a);Ce(e)&&(e=yield e),e&&this.readContiguousElements(e)}else if(s===vr.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=an.find(e=>e.id===t.id);if(!i)continue;if(this.currentSegment[i.flag])continue;let r=this.reader.requestSliceRange(e+t.segmentPosition,2,xr);if(Ce(r)&&(r=yield r),!r)continue;const n=Fr(r);if(!n)continue;const{id:s,size:a}=n;if(s!==i.id)continue;Jr(a),this.currentSegment[i.flag]=!0;let o=this.reader.requestSlice(r.filePos,a);Ce(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,xr);Ce(r)&&(r=yield r),I(r);const n=e,s=Fr(r);I(s);I(s.id===vr.Cluster);let a=s.size;const o=r.filePos;if(void 0===a){a=(yield Nr(this.reader,o,Ir,t.elementEndPos)).pos-o}let l=this.reader.requestSlice(o,a);Ce(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,Ir);c.elementEndPos=e}for(const[,e]of c.trackData){const t=e.track;I(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[C(e.presentationTimestamps).blockIndex];e.startTimestamp=r.timestamp,e.endTimestamp=s.timestamp+s.duration;const a=G(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,m,p,g,k,y,b,T,v,S,w,P,C,B,E,_,R,F,D,M,O,z,q,H,V,j,K,X,$,G,Q,Y,J,Z,ee,te,ie,re,ne,se,oe,le;const ce=Fr(e);if(!ce)return!1;if(t&&t.includes(ce.id))return!1;const{id:ue,size:de}=ce,he=e.filePos;switch(Jr(de),ue){case vr.DocType:this.isWebM="webm"===Ar(e,de);break;case vr.Seek:{if(!this.currentSegment)break;const t={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(t),this.readContiguousElements(e.slice(he,de)),-1!==t.id&&-1!==t.segmentPosition||this.currentSegment.seekEntries.pop()}break;case vr.SeekID:{const t=null==(i=this.currentSegment)?void 0:i.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.id=Er(e,de)}break;case vr.SeekPosition:{const t=null==(r=this.currentSegment)?void 0:r.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.segmentPosition=Er(e,de)}break;case vr.TimestampScale:if(!this.currentSegment)break;this.currentSegment.timestampScale=Er(e,de),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale;break;case vr.Duration:if(!this.currentSegment)break;this.currentSegment.duration=Mr(e,de);break;case vr.TrackEntry:if(!this.currentSegment)break;if(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:f(h({},je),{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(he,de)),!this.currentTrack)break;if(this.currentTrack.decodingInstructions.some(e=>{var t;return"decompress"!==(null==(t=e.data)?void 0:t.type)||e.scope!==tn.Block||e.data.algorithm!==nn.HeaderStripping})&&(We._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===Lr)this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(this.currentTrack.codecId===zr)this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(t===Ur)this.currentTrack.info.codec="vp8";else if(t===qr)this.currentTrack.info.codec="vp9";else if(t===Wr)this.currentTrack.info.codec="av1";else if(t===Hr){const e=this.currentTrack.codecPrivate?A.decode(this.currentTrack.codecPrivate):"";ki.includes(e)&&(this.currentTrack.info.codec="prores",this.currentTrack.info.proresFormat=e)}const e=this.currentTrack;this.currentTrack.trackBacking=new un(e),this.currentSegment.tracks.push(this.currentTrack)}else if("audio"===this.currentTrack.info.type){t===Vr?(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===jr?this.currentTrack.info.codec="mp3":t===Kr?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=Si):t===Xr?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===$r?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Gr?(this.currentTrack.info.codec="ac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Qr?(this.currentTrack.info.codec="eac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Yr?(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 dn(e),this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null;break;case vr.TrackNumber:if(!this.currentTrack)break;this.currentTrack.id=Er(e,de);break;case vr.TrackType:{if(!this.currentTrack)break;const t=Er(e,de);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({},W),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 vr.FlagEnabled:if(!this.currentTrack)break;Er(e,de)||(this.currentTrack=null);break;case vr.FlagDefault:if(!this.currentTrack)break;this.currentTrack.disposition.default=!!Er(e,de);break;case vr.FlagForced:if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!Er(e,de);break;case vr.FlagOriginal:if(!this.currentTrack)break;this.currentTrack.disposition.original=!!Er(e,de);break;case vr.FlagHearingImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!Er(e,de);break;case vr.FlagVisualImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!Er(e,de);break;case vr.FlagCommentary:if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!Er(e,de);break;case vr.CodecID:if(!this.currentTrack)break;this.currentTrack.codecId=Ar(e,de);break;case vr.CodecPrivate:if(!this.currentTrack)break;this.currentTrack.codecPrivate=Lo(e,de);break;case vr.DefaultDuration:if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=Er(e,de);break;case vr.Name:if(!this.currentTrack)break;this.currentTrack.name=Dr(e,de);break;case vr.Language:if(!this.currentTrack)break;if(this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=Ar(e,de),fe(this.currentTrack.languageCode)||(this.currentTrack.languageCode=ae);break;case vr.LanguageBCP47:{if(!this.currentTrack)break;const t=Ar(e,de).split("-")[0];this.currentTrack.languageCode=t||ae,this.currentTrack.hasLanguageBcp47=!0}break;case vr.Video:if("video"!==(null==(s=null==(n=this.currentTrack)?void 0:n.info)?void 0:s.type))break;this.readContiguousElements(e.slice(he,de));break;case vr.PixelWidth:if("video"!==(null==(o=null==(a=this.currentTrack)?void 0:a.info)?void 0:o.type))break;this.currentTrack.info.width=Er(e,de);break;case vr.PixelHeight:if("video"!==(null==(c=null==(l=this.currentTrack)?void 0:l.info)?void 0:c.type))break;this.currentTrack.info.height=Er(e,de);break;case vr.DisplayWidth:if("video"!==(null==(d=null==(u=this.currentTrack)?void 0:u.info)?void 0:d.type))break;this.currentTrack.info.displayWidth=Er(e,de);break;case vr.DisplayHeight:if("video"!==(null==(p=null==(m=this.currentTrack)?void 0:m.info)?void 0:p.type))break;this.currentTrack.info.displayHeight=Er(e,de);break;case vr.DisplayUnit:if("video"!==(null==(k=null==(g=this.currentTrack)?void 0:g.info)?void 0:k.type))break;this.currentTrack.info.displayUnit=Er(e,de);break;case vr.AlphaMode:if("video"!==(null==(b=null==(y=this.currentTrack)?void 0:y.info)?void 0:b.type))break;this.currentTrack.info.alphaMode=1===Er(e,de);break;case vr.Colour:if("video"!==(null==(v=null==(T=this.currentTrack)?void 0:T.info)?void 0:v.type))break;this.readContiguousElements(e.slice(he,de));break;case vr.MatrixCoefficients:{if("video"!==(null==(w=null==(S=this.currentTrack)?void 0:S.info)?void 0:w.type))break;const t=Er(e,de),i=U[t];this.currentTrack.info.colorSpace.matrix=i}break;case vr.Range:{if("video"!==(null==(C=null==(P=this.currentTrack)?void 0:P.info)?void 0:C.type))break;const t=Er(e,de);this.currentTrack.info.colorSpace.fullRange=1===t||2===t?2===t:void 0}break;case vr.TransferCharacteristics:{if("video"!==(null==(E=null==(B=this.currentTrack)?void 0:B.info)?void 0:E.type))break;const t=Er(e,de),i=L[t];this.currentTrack.info.colorSpace.transfer=i}break;case vr.Primaries:{if("video"!==(null==(R=null==(_=this.currentTrack)?void 0:_.info)?void 0:R.type))break;const t=Er(e,de),i=N[t];this.currentTrack.info.colorSpace.primaries=i}break;case vr.Projection:if("video"!==(null==(D=null==(F=this.currentTrack)?void 0:F.info)?void 0:D.type))break;this.readContiguousElements(e.slice(he,de));break;case vr.ProjectionPoseRoll:{if("video"!==(null==(O=null==(M=this.currentTrack)?void 0:M.info)?void 0:O.type))break;const t=-Mr(e,de);try{this.currentTrack.info.rotation=x(t)}catch(me){}}break;case vr.Audio:if("audio"!==(null==(q=null==(z=this.currentTrack)?void 0:z.info)?void 0:q.type))break;this.readContiguousElements(e.slice(he,de));break;case vr.SamplingFrequency:if("audio"!==(null==(V=null==(H=this.currentTrack)?void 0:H.info)?void 0:V.type))break;this.currentTrack.info.sampleRate=Mr(e,de);break;case vr.Channels:if("audio"!==(null==(K=null==(j=this.currentTrack)?void 0:j.info)?void 0:K.type))break;this.currentTrack.info.numberOfChannels=Er(e,de);break;case vr.BitDepth:if("audio"!==(null==($=null==(X=this.currentTrack)?void 0:X.info)?void 0:$.type))break;this.currentTrack.info.bitDepth=Er(e,de);break;case vr.CuePoint:if(!this.currentSegment)break;this.readContiguousElements(e.slice(he,de)),this.currentCueTime=null;break;case vr.CueTime:this.currentCueTime=Er(e,de);break;case vr.CueTrackPositions:{if(null===this.currentCueTime)break;I(this.currentSegment);const t={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(t),this.readContiguousElements(e.slice(he,de)),-1!==t.trackId&&-1!==t.clusterPosition||this.currentSegment.cuePoints.pop()}break;case vr.CueTrack:{const t=null==(G=this.currentSegment)?void 0:G.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;t.trackId=Er(e,de)}break;case vr.CueClusterPosition:{const t=null==(Q=this.currentSegment)?void 0:Q.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;I(this.currentSegment),t.clusterPosition=this.currentSegment.dataStartPos+Er(e,de)}break;case vr.Timestamp:if(!this.currentCluster)break;this.currentCluster.timestamp=Er(e,de);break;case vr.SimpleBlock:{if(!this.currentCluster)break;const t=Br(e);if(null===t)break;const i=this.getTrackDataInCluster(this.currentCluster,t);if(!i)break;const r=Ho(e),n=zo(e),s=n>>1&3;let a=!!(128&n);"audio"===(null==(Y=i.track.info)?void 0:Y.type)&&i.track.info.codec&&(a=!0);const o=Lo(e,de-(e.filePos-he)),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 vr.BlockGroup:if(!this.currentCluster)break;this.readContiguousElements(e.slice(he,de)),this.currentBlock=null;break;case vr.Block:{if(!this.currentCluster)break;const t=Br(e);if(null===t)break;const i=this.getTrackDataInCluster(this.currentCluster,t);if(!i)break;const r=Ho(e),n=zo(e)>>1&3,s=Lo(e,de-(e.filePos-he)),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 vr.BlockAdditions:this.readContiguousElements(e.slice(he,de));break;case vr.BlockMore:if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(he,de)),this.currentBlockAdditional.data&&1===this.currentBlockAdditional.addId&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null;break;case vr.BlockAdditional:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=Lo(e,de);break;case vr.BlockAddID:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=Er(e,de);break;case vr.BlockDuration:if(!this.currentBlock)break;this.currentBlock.duration=Er(e,de);break;case vr.ReferenceBlock:if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1;break;case vr.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(he,de));break;case vr.Targets:this.readContiguousElements(e.slice(he,de));break;case vr.TargetTypeValue:50!==Er(e,de)&&(this.currentTagTargetIsMovie=!1);break;case vr.TagTrackUID:case vr.TagEditionUID:case vr.TagChapterUID:case vr.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case vr.SimpleTag:if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(he,de));break;case vr.TagName:this.currentSimpleTagName=Dr(e,de);break;case vr.TagString:{if(!this.currentSimpleTagName)break;const t=Dr(e,de);this.processTagValue(this.currentSimpleTagName,t)}break;case vr.TagBinary:{if(!this.currentSimpleTagName)break;const t=Lo(e,de);this.processTagValue(this.currentSimpleTagName,t)}break;case vr.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(he,de));const t=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(null!=t.raw||(t.raw={}),t.raw[this.currentAttachedFile.fileUid.toString()]=new Ve(this.currentAttachedFile.fileData,null!=(J=this.currentAttachedFile.fileMediaType)?J:void 0,null!=(Z=this.currentAttachedFile.fileName)?Z:void 0,null!=(ee=this.currentAttachedFile.fileDescription)?ee:void 0)),(null==(te=this.currentAttachedFile.fileMediaType)?void 0:te.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!=(ie=this.currentAttachedFile.fileName)?ie:void 0,description:null!=(re=this.currentAttachedFile.fileDescription)?re:void 0})}this.currentAttachedFile=null}break;case vr.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 vr.ContentEncoding:this.currentDecodingInstruction={order:0,scope:tn.Block,data:null},this.readContiguousElements(e.slice(he,de)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case vr.ContentEncodingOrder:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=Er(e,de);break;case vr.ContentEncodingScope:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=Er(e,de);break;case vr.ContentCompression:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:nn.Zlib,settings:null},this.readContiguousElements(e.slice(he,de));break;case vr.ContentCompAlgo:if("decompress"!==(null==(se=null==(ne=this.currentDecodingInstruction)?void 0:ne.data)?void 0:se.type))break;this.currentDecodingInstruction.data.algorithm=Er(e,de);break;case vr.ContentCompSettings:if("decompress"!==(null==(le=null==(oe=this.currentDecodingInstruction)?void 0:oe.data)?void 0:le.type))break;this.currentDecodingInstruction.data.settings=Lo(e,de);break;case vr.ContentEncryption:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}return e.filePos=he+de,!0}decodeBlockData(e,t){I(e.decodingInstructions.length>0);let i=t;for(const r of e.decodingInstructions)if(I(r.data),"decompress"===r.data.type)if(r.data.algorithm===nn.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){I(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 cn{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 oe(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=G(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=ee(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 I(-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(I(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);F(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?Oi: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?Oi:s.mainAdditional,c.alphaByteLength=s.mainAdditional.byteLength);const u=new Li(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=G(this.internalTrack.cuePoints,i,e=>e.time),p=-1!==m?this.internalTrack.cuePoints[m]:null,g=G(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,xr);if(Ce(e)&&(e=yield e),!e)break;const i=b,s=Fr(e);if(!s||!Pr.includes(s.id)&&s.id!==vr.Void){const e=yield Or(c.reader,i,Pr,Math.min(null!=(o=u.elementEndPos)?o:1/0,i+on));if(e){b=e;continue}break}const a=s.id;let l=s.size;const m=e.filePos;if(a===vr.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){I(a!==vr.Cluster);l=(yield Nr(c.reader,m,Ir,u.elementEndPos)).pos-m}const p=m+l;if(null===u.elementEndPos){let e=c.reader.requestSliceRange(p,2,xr);if(Ce(e)&&(e=yield e),!e)break;if(_r(e)===vr.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?ht(s.data):null,hevcCodecInfo:"hevc"===this.internalTrack.info.codec&&s?St(s.data):null,vp9CodecInfo:"vp9"===this.internalTrack.info.codec&&s?Dt(s.data):null,av1CodecInfo:"av1"===this.internalTrack.info.codec&&s?Nt(s.data):null,proresCodecInfo:"prores"===this.internalTrack.info.codec&&s?Ot(s.data):null,proresFormat:this.internalTrack.info.proresFormat};if(!q(this.internalTrack.info.colorSpace)){const n=Ti(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:bi(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 dn extends cn{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&&ai(e.data)}return{codec:vi({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 hn=(e,t,i,r=null)=>y(null,null,function*(){const n=u(2,16);let s=t;for(;null===i||s=4;){const t=a.filePos,i=jo(a),n=null!==e.fileSize?e.fileSize-s:null,o=Ri(i,n);if(o.header&&(!r||o.header.sampleRate===r.sampleRate&&o.header.mpegVersionId===r.mpegVersionId&&o.header.layer===r.layer&&Mi(o.header.channel)===Mi(r.channel)))return{header:o.header,startPos:s};a.filePos=t+o.bytesAdvanced,s=a.filePos}}return null});class fn extends Ni{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.firstFrameHeaderPos=null,this.xingFrameHeader=null,this.xingFrameHeaderPos=null,this.loadedSamples=[],this.metadataTags=null,this.xingData=null,this.trackBackings=[],this.readingMutex=new V,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}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 mn(this)]}))()})}advanceReader(){return y(this,null,function*(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,ol);if(Ce(e)&&(e=yield e),!e)return void(this.lastSampleLoaded=!0);const t=dl(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}const e=yield hn(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=_i(t.mpegVersionId,t.channel);let r=this.reader.requestSlice(e.startPos+i,4);if(Ce(r)&&(r=yield r),r){const n=jo(r);if(n===Bi||n===Ei){if(this.xingFrameHeader||(this.xingFrameHeader=t,this.xingFrameHeaderPos=e.startPos),!this.xingData){let t=this.reader.requestSlice(e.startPos+i+4,12);if(Ce(t)&&(t=yield t),t){const e=Lo(t,12),i=F(e),r=i.getUint32(0,!1);this.xingData={frameCount:r&Ai.FrameCount?i.getUint32(4,!1):null,fileSize:r&Ai.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,ol);if(Ce(i)&&(i=yield i),!i)break;const r=dl(i);if(!r)break;t=!0;let n=this.reader.requestSlice(i.filePos,r.size);if(Ce(n)&&(n=yield n),!n)break;hl(n,r,this.metadataTags),e=i.filePos+r.size}if(!t&&null!==this.reader.fileSize&&this.reader.fileSize>=al){let e=this.reader.requestSlice(this.reader.fileSize-al,al);Ce(e)&&(e=yield e),I(e);"TAG"===el(e,3)&&cl(e,this.metadataTags)}return this.metadataTags}finally{e()}})}}class mn{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return I(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate/this.demuxer.firstFrameHeader.audioSamplesInFrame}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return y(this,null,function*(){const e=this.demuxer;if(I(null!==e.firstFrameHeader),I(null!==e.firstFrameHeaderPos),e.xingData){if(null!==e.xingData.frameCount)return e.xingData.frameCount*e.firstFrameHeader.audioSamplesInFrame/e.firstFrameHeader.sampleRate}else if(null!==e.reader.fileSize){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=G(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 kn=e=>{const t=F(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},yn=(e,t,i)=>{let r=0,n=null;if(e.length>0)if("vorbis"===t.codec){I(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:Lt[t]*r}})(e).durationInSamples}return{durationInSamples:r,vorbisBlockSize:n}},bn=27,Tn=282,vn=e=>{const t=e.filePos;if(Ko(e)!==pn)return null;e.skip(1);const i=zo(e),r=Yo(e),n=Ko(e),s=Ko(e),a=Ko(e),o=zo(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}},Sn=(e,t)=>{for(;e.filePos>>8&255)===i||(t>>>16&255)===i||(t>>>24&255)===i){if(e.skip(-4),t===pn)return!0;e.skip(1)}}return!1};class wn extends Ni{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,bn,Tn);if(Ce(t)&&(t=yield t),!t)break;const i=vn(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 Pn(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=F(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:zt(n.data).modeBlockflags},Ht(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=F(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=Si,t.codecInfo.opusInfo={preSkip:n.preSkip},Ht(r.data.subarray(8),this.metadataTags)})}readPacket(e,t){return y(this,null,function*(){I(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 Pn{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new V,this.internalSampleRate="opus"===e.codecInfo.codec?Si:e.sampleRate}getType(){return"audio"}getId(){return this.bitstream.serialNumber}getNumber(){const e=this.demuxer.trackBackings.findIndex(e=>e.bitstream===this.bitstream);return I(-1!==e),e+1}getNumberOfChannels(){return this.bitstream.numberOfChannels}getSampleRate(){return this.bitstream.sampleRate}getTimeResolution(){return this.bitstream.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 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 I(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 ae}getDisposition(){return f(h({},je),{primary:!1})}granulePositionToTimestampInSamples(e){return"opus"===this.bitstream.codecInfo.codec?(I(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,i){if(!e)return null;const{durationInSamples:r,vorbisBlockSize:n}=yn(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),s=new Li(i.metadataOnly?Oi: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*(){I(this.bitstream.lastMetadataPacket);const t=yield this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let i=0;"opus"===this.bitstream.codecInfo.codec&&(I(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=oe(e*this.internalSampleRate);if(0===n)return this.getFirstPacket(t);if(n<0)return null;I(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,bn,Tn);Ce(t)&&(t=yield t),I(t);const i=vn(t);I(i),u=i,u.serialNumber===this.bitstream.serialNumber&&d.push(u)}I(-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:Oi,endPage:p,endSegmentIndex:g};if(yield this.demuxer.findNextPacketStart(e)){const e=xn(d,u,m);I(e);const t=In(d,e.page,e.segmentIndex);t&&(u=t.page,m=t.segmentIndex)}else for(;;){const e=xn(d,u,m);if(!e)break;const t=In(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;){I(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=oe(e*this.internalSampleRate);e=i/this.internalSampleRate;const r=G(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);I(e),this.sequentialScanCache.length>0&&I(C(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 In=(e,t,i)=>{let r=t,n=i;e:for(;;){for(n--;n>=0;n--){if(r.lacingValues[n]<255){n++;break e}}I(-1===n);if(!(1&r.headerType)){n=0;break}const t=Z(e,e=>e.headerStartPos{if(i>0)return{page:t,segmentIndex:i-1};const r=Z(e,e=>e.headerStartPosy(this,null,function*(){var e,t;let i=this.reader.requestSlice(0,12);Ce(i)&&(i=yield i),I(i);const r=el(i,4),n="RIFX"!==r,s="RF64"===r,a=Vo(i,n);let o=s?this.reader.fileSize:Math.min(a+8,null!=(e=this.reader.fileSize)?e:1/0);if("WAVE"!==el(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=Uo(r,i),s=t-18;if(Math.min(s,e)>=22&&n===Cn.EXTENSIBLE){r.skip(6);const e=Lo(r,16);n=e[0]|e[1]<<8}}if(n!==Cn.MULAW&&n!==Cn.ALAW||(l=8),n!==Cn.PCM&&n!==Cn.IEEE_FLOAT&&n!==Cn.ALAW&&n!==Cn.MULAW)throw new Error(`Unsupported WAVE codec (format tag ${n}). Only integer/float PCM, A-law, and \u03bc-law are supported.`);if(n===Cn.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===Cn.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(Ce(m)&&(m=yield m),!m)return;const p=el(m,4);if("INFO"!==p&&"INF0"!==p)return;let g=m.filePos;for(;g<=e+t-8;){m.filePos=g;const e=el(m,4),t=Vo(m,i),p=Lo(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(Ce(i)&&(i=yield i),!i)return;const r=dl(i);if(r){const n=t-ol;if(r.size=Math.min(r.size,n),r.size>0){const t=i.slice(e+ol,r.size);hl(t,r,this.metadataTags)}}})}getCodec(){if(I(this.audioInfo),this.audioInfo.format===Cn.MULAW)return"ulaw";if(this.audioInfo.format===Cn.ALAW)return"alaw";if(this.audioInfo.format===Cn.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===Cn.IEEE_FLOAT){if(4===this.audioInfo.sampleSizeInBytes)return"pcm-f32";if(8===this.audioInfo.sampleSizeInBytes)return"pcm-f64"}I(!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 _n=2048;class Rn{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return I(this.demuxer.audioInfo),this.demuxer.audioInfo.format}getDecoderConfig(){return y(this,null,function*(){const e=this.demuxer.getCodec();return e?(I(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null})}getNumberOfChannels(){return I(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return I(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return I(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return y(this,null,function*(){return I(-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 ae}getDisposition(){return h({},je)}getPacketAtIndex(e,t){return y(this,null,function*(){I(e>=0),I(this.demuxer.audioInfo);const i=e*_n*this.demuxer.audioInfo.blockSizeInBytes;if(i>=this.demuxer.dataSize)return null;const r=Math.min(_n*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(Ce(e)&&(e=yield e),!e)return null}let n;if(t.metadataOnly)n=Oi;else{let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+i,r);Ce(e)&&(e=yield e),I(e),n=Lo(e,r)}const s=e*_n/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 Li(n,"key",s,a,e,r)})}getFirstPacket(e){return this.getPacketAtIndex(0,e)}getPacket(e,t){return y(this,null,function*(){I(this.demuxer.audioInfo);const i=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/_n,(this.demuxer.dataSize-1)/(_n*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;I(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){I(this.demuxer.audioInfo);const i=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/_n);return this.getPacketAtIndex(i+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const Fn=e=>{const t=e.filePos,i=Lo(e,9),r=new Ke(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}},An=1024;class Dn extends Ni{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.trackBackings=[],this.readingMutex=new V,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}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();I(this.firstFrameHeader),this.trackBackings=[new Mn(this)]}))()})}advanceReader(){return y(this,null,function*(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,ol);if(Ce(e)&&(e=yield e),!e)return void(this.lastSampleLoaded=!0);const t=dl(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}let e=this.reader.requestSliceRange(this.lastLoadedPos,7,9);if(Ce(e)&&(e=yield e),!e)return void(this.lastSampleLoaded=!0);const t=Fn(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=Xe[t.samplingFrequencyIndex];I(void 0!==i);const r=An/i,n={timestamp:this.nextTimestampInSamples/i,duration:r,dataStart:t.startPos,dataSize:t.frameLength};this.loadedSamples.push(n),this.nextTimestampInSamples+=An,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,ol);if(Ce(t)&&(t=yield t),!t)break;const i=dl(t);if(!i)break;let r=this.reader.requestSlice(t.filePos,i.size);if(Ce(r)&&(r=yield r),!r)break;hl(r,i,this.metadataTags),e=t.filePos+i.size}return this.metadataTags}finally{e()}})}}class Mn{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return this.getSampleRate()/An}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 ae}getCodec(){return"aac"}getInternalCodecId(){return I(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){I(this.demuxer.firstFrameHeader);const e=$e[this.demuxer.firstFrameHeader.channelConfiguration];return I(void 0!==e),e}getSampleRate(){I(this.demuxer.firstFrameHeader);const e=Xe[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return I(void 0!==e),e}getDisposition(){return h({},je)}getDecoderConfig(){return y(this,null,function*(){return I(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=Oi;else{let e=this.demuxer.reader.requestSlice(i.dataStart,i.dataSize);if(Ce(e)&&(e=yield e),!e)return null;r=Lo(e,i.dataSize)}return new Li(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=$(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=G(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,ol);if(Ce(e)&&(e=yield e),!e)return void(this.lastSampleLoaded=!0);const i=dl(e);if(!i)break;let r=this.reader.requestSlice(e.filePos,i.size);Ce(r)&&(r=yield r),I(r),hl(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===zo(s)){const t=s.filePos;if(zo(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=Lo(e,4),n=new Ke(r);if(32764!==n.readBits(15))return null;if(null===this.blockingBit){I(t);const e=n.readBits(1);this.blockingBit=e}else if(1===this.blockingBit){I(!t);if(1!==n.readBits(1))return null}else{if(0!==this.blockingBit)throw new Error("Invalid blocking bit");I(!t);if(0!==n.readBits(1))return null}const s=(e=>0===e?null:1===e?192:e>=2&&e<=5?144*u(2,e):6===e?"uncommon-u8":7===e?"uncommon-u16":e>=8&&e<=15?u(2,e):null)(n.readBits(4));if(!s)return null;I(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 Ke(Lo(e,1));for(;1===i.readBits(1);)t++;if(0===t)return i.readBits(7);const r=[],n=t-1,s=new Ke(Lo(e,n)),a=8-t-1;for(let o=0;oe|t<"uncommon-u16"===t?qo(e)+1:"uncommon-u8"===t?zo(e)+1:"number"===typeof t?t:(te(t),void I(!1)))(e,s),c=((e,t)=>"uncommon-u16"===t?qo(e):"uncommon-u16-10"===t?10*qo(e):"uncommon-u8"===t?zo(e):"number"===typeof t?t:null)(e,a);if(null===c)return null;if(c!==this.audioInfo.sampleRate)return null;const d=e.filePos-i,h=zo(e);e.skip(-d),e.skip(-1);const f=(e=>{let t=0;for(const i of e){t^=i;for(let e=0;e<8;e++)0!==(128&t)?t=t<<1^7:t<<=1,t&=255}return t})(Lo(e,d));return h!==f?null:{num:o,blockSize:l,sampleRate:c}}advanceReader(){return y(this,null,function*(){yield this.readMetadata(),I(null!==this.lastLoadedPos),I(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 On{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return I(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return I(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return ae}getTimeResolution(){return I(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 I(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({},je)}getDecoderConfig(){return y(this,null,function*(){return I(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(I(this.demuxer.audioInfo),e<0)return null;const i=yield this.demuxer.readingMutex.acquire();try{for(;;){const i=G(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=Oi;else{let e=this.demuxer.reader.requestSlice(i.byteOffset,i.byteSize);if(Ce(e)&&(e=yield e),!e)return null;r=Lo(e,i.byteSize)}I(this.demuxer.audioInfo);const n=i.blockOffset/this.demuxer.audioInfo.sampleRate,s=i.blockSize/this.demuxer.audioInfo.sampleRate;return new Li(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 Ln=9e4,zn=u(2,33),Un=188,qn="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.",Wn=new Set([133,134,162]),Hn=new Set;class Vn extends Ni{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);Ce(e)&&(e=yield e),I(e);const t=Lo(e,205);if(71===t[0]&&71===t[188])this.packetOffset=0,this.packetStride=Un;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 Ke(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=Kn(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 Yn(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=ht(r.suppliedPacket.data),!e.info.avcCodecInfo)continue;const t=e.info.avcCodecInfo.sequenceParameterSets[0];I(t);const i=gt(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:N[i.colourPrimaries],transfer:L[i.transferCharacteristics],matrix:U[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=St(r.suppliedPacket.data),!e.info.hevcCodecInfo)continue;const t=e.info.hevcCodecInfo.arrays.find(e=>e.nalUnitType===it.SPS_NUT).nalUnits[0];I(t);const i=vt(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:N[i.colourPrimaries],transfer:L[i.transferCharacteristics],matrix:U[i.matrixCoefficients],fullRange:!!i.fullRangeFlag},e.info.reorderSize=i.maxDecFrameBuffering;break}throw new Error("Unhandled.")}e.info.decoderConfig={codec:bi({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=No.tempFromBytes(r.suppliedPacket.data),i=Fn(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=$e[i.channelConfiguration],e.info.sampleRate=Xe[i.samplingFrequencyIndex]}else if("mp3"===e.info.codec){const t=jo(No.tempFromBytes(r.suppliedPacket.data)),i=Ri(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=Mi(i.header.channel),e.info.sampleRate=i.header.sampleRate}else if("ac3"===e.info.codec){const t=jt(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=Vt[t.acmod]+t.lfeon,e.info.sampleRate=Je[t.fscod]}else if("eac3"===e.info.codec){const t=$t(r.suppliedPacket.data);if(!t)throw new Error("Invalid E-AC-3 audio stream; could not read sync frame from first packet.");const i=Gt(t);if(null===i)throw new Error("Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.");e.info.numberOfChannels=Qt(t),e.info.sampleRate=i}else{if("dts"!==e.info.codec)throw new Error("Unhandled.");{const t=si(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:vi({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 Ke(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&&Wn.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:Hn.has(t)||(We._warn(`Note: MPEG-TS streams with stream_type 0x${t.toString(16)} are not currently supported.`),Hn.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 Ke(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 $n(a)):this.trackBackingEntries.push(new Gn(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!==$(this.sectionEndPositions,r,e=>e)){c=!1;break}}if(c){const e=G(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(Ce(t)&&(t=yield t),!t)return null;if(71!==zo(t))throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");const i=qo(t);return{payloadUnitStartIndicator:i>>14&1,pid:8191&i,adaptationFieldControl:zo(t)>>4&3}})}readPacket(e){return y(this,null,function*(){let t=this.reader.requestSlice(e,Un);if(Ce(t)&&(t=yield t),!t)return null;const i=Lo(t,Un);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>=zn-t?-zn:zn}}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 Ke(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(qn);return{sectionStartPos:t.startPos,sectionEndPos:t.endPos,pts:a,randomAccessIndicator:t.randomAccessIndicator}},Kn=(e,t,i)=>{I(null!==t.endPos);const r=jn(e,t,i);if(!r)return null;const n=new Ke(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;I(Number.isInteger(l));const c=t.payload.subarray(l,s>0?6+s:t.payload.byteLength);return f(h({},r),{data:c})};class Xn{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++,I(r instanceof Xn),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 ae}getDisposition(){return f(h({},je),{primary:!1})}getTimeResolution(){return Ln}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 Li(i.metadataOnly?Oi:e.data,r,e.pts/Ln,Math.max(t/Ln,0),e.sequenceNumber,e.data.byteLength)}getFirstPacket(e){return y(this,null,function*(){const t=this.elementaryStream.firstSection;I(t);const i=Kn(this.elementaryStream.demuxer,t,!0);I(i);const r=new Yn(this.elementaryStream,i),n=new Jn(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);I(s);const a=Kn(n,s,!0);I(a);const o=new Yn(this.elementaryStream,a);i=new Jn(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=oe(e*Ln),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),v=-1!==T?b[T]:null;if(v&&c-v.pts<45e3)k=v.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=ue(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=ue(e*h,u.packetStride)+g.sectionStartPos}const S=yield m(k,null!=(r=d.fileSize)?r:1/0,!1);let w=null!=(n=null==S?void 0:S.pesPacketHeader)?n:null;w||(w=g);const P=this.getReorderSize(),x=(e,t)=>y(this,null,function*(){var r,n;const s=yield u.readSection(e,!0);I(s);const a=Kn(u,s,!0);I(a);const o=new Yn(this.elementaryStream,a),l=new Jn(this,o);for(;;){if((null!=(n=null==(r=C(l.presentationOrderPackets))?void 0:r.pts)?n:-1/0)>=c)break;if(!(yield l.readNextPacket()))break}const d=ee(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();I(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=jn(u,t,!1);if(e&&null!==e.pts){if(e.pts>c)break e;w=e,Qn(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=jn(u,t,!1);if(e&&null!==e.pts){w=e;break}}}e-=u.packetStride}}return x(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{I(y);const t=Kn(u,y,!0);I(t);const i=new Yn(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>P))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=jn(u,t,!1);if(e&&null!==e.pts){k=e,y=t,Qn(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=jn(u,r,!1);if(t&&null!==t.pts){e=t;break}}}t-=u.packetStride}}const t=yield x(e.sectionStartPos,e=>e.pts<=c&&1===e.randomAccessIndicator);return I(t),t}if(n)return null;t=e,e=Math.max(ue(e-g.sectionStartPos-h,u.packetStride)+g.sectionStartPos,g.sectionStartPos)}}})}}class $n extends Xn{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 I(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig})}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}}class Gn extends Xn{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 I(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig})}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 0}}const Qn=(e,t)=>{const i=e.referencePesPackets,r=G(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 I(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,S;if("avc"===e)T=ot(b),v=T===et.NON_IDR_SLICE||T===et.SLICE_DPA||T===et.IDR,S=T===et.SEI||T===et.SPS||T===et.PPS||T===et.AUD;else{T=Tt(b);if(((1&b)<<5|l[g+1]>>3)>0){u+=m;continue}v=T<=it.RASL_R||T>=it.BLA_W_LP&&T<=21,S=T>=it.VPS_NUT&&T<=37||T===it.PREFIX_SEI_NUT||T>=41&&T<=44||T>=48&&T<=55}let w=!1;if(v){let t;if("avc"===e){const e=l.subarray(k,k+y),i=B(new Ke(e));t=!s||i<=a,a=i}else t=l[k]>>7===1;t&&(s?w=!0:s=!0)}else S&&s&&(w=!0);if(w){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);Ce(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=Kt[3*a+n];I(void 0!==o),this.seekTo(e),t=this.ensureBuffered(o),Ce(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(Ce(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=Xt[a];this.seekTo(e),t=this.ensureBuffered(n),Ce(t)&&(t=yield t);const l=256*o,c=Math.round(l*Ln/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(Ce(a)&&(a=yield a),a<18)return;const o=this.readBytes(18),l=oi(o);let c=l?null:li(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);Ce(i)&&(i=yield i),c=null!=(e=li(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(Ce(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(I(-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(I(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 Zn="application/vnd.apple.mpegurl",es="#EXT-X-STREAM-INF:",ts="#EXT-X-I-FRAME-STREAM-INF:",is="#EXT-X-MEDIA:",rs="#EXTINF:",ns="#EXT-X-MAP:",ss="#EXT-X-KEY:",as="#EXT-X-MEDIA-SEQUENCE:",os="#EXT-X-BYTERANGE:",ls="#EXT-X-PROGRAM-DATE-TIME:",cs="#EXT-X-TARGETDURATION:",us="#EXT-X-PLAYLIST-TYPE:",ds=e=>0===e.length||e.startsWith("#")&&!e.startsWith("#EXT");class hs{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=De(e,e=>"video"===e.getType())+1;e.push(new ps(this,t,i))}else if("audio"===t.type){const i=De(e,e=>"audio"===e.getType())+1;e.push(new gs(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=De(e,e=>"video"===e.getType())+1;e.push(new ps(this,{id:e.length+1,type:"video"},t))}else if("audio"===r.type){const t=De(e,e=>"audio"===e.getType())+1;e.push(new gs(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 ms{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(),I(this.segmentedInput.firstSegment),this.segmentedInput.firstSegment.unixEpochTimestamp===this.segmentedInput.firstSegment.timestamp})}getUnixTimeForTimestamp(e){return this.segmentedInput.getUnixTimeForTimestamp(e)}getBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getBitrate())}getAverageBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getAverageBitrate())}getDurationFromMetadata(e){return this.segmentedInput.getDurationFromMetadata(e)}getLiveRefreshInterval(){return this.segmentedInput.getLiveRefreshInterval()}createAdjustedPacket(e,t,i){return y(this,null,function*(){I(e.sequenceNumber>=0),I(this.segmentedInput.firstSegment);const r=yield this.segmentedInput.getMediaOffset(t,i.input),n=t.timestamp-this.segmentedInput.firstSegment.timestamp,s=e.clone({timestamp:ce(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(),I(this.firstInputTrack),I(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 ps extends ms{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 gs extends ms{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())})}}Re();const ks=1/0;"undefined"!==typeof FinalizationRegistry&&new FinalizationRegistry(e=>{e()});class ys extends ze{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 Do;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,ks),e=this._getFileSize(),I(void 0!==e)),e}))()})}getSize(){return y(this,null,function*(){if(this._disposed)throw new Do;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 Ds(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 bs(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){this._refCount--,0===this._refCount&&(this._dispose(),this._disposed=!0)}}class bs{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;I(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 Ts extends ys{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 ys||e instanceof bs))throw new TypeError("requestHandler must return or resolve to a Source or SourceRef.");const i=e instanceof ys?e.ref():e;return(t=i.source)._usedForHls||(t._usedForHls=this._usedForHls),i};return Ce(t)?t.then(i):i(t)}}const vs=(e,t)=>e.path===t.path;class Ss extends Ts{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 ys?e.ref():e;return this._root=t,this._rootRequest=null,t};Ce(e)?this._rootRequest=e.then(t):(t(e),I(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 ws="undefined"!==typeof FinalizationRegistry?new FinalizationRegistry(e=>{e.cancel().catch(()=>{})}):null;class Ps extends ys{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&&(!Fe(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 As({maxCacheSize:null!=(i=t.maxCacheSize)?i:8*u(2,20),maxWorkerCount:4,runWorker:this._runWorker.bind(this),onIdleWorkerRemoved:e=>{const t=this._readers.get(e);t&&(this._readers.delete(e),null==ws||ws.unregister(e),t.cancel().catch(()=>{}))},prefetchProfile:Fs.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*(){I(e.strictTarget);let t=this._readers.get(e);if(void 0===t){if("stream"in this._blob&&!Te()&&!1!==this._options.useStreamReader){t=this._blob.slice(e.currentPos).stream().getReader(),null==ws||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(r){}if(("undefined"===typeof navigator||"boolean"!==typeof navigator.onLine||navigator.onLine)&&null!==e&&e!==window.location.origin)return We._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(u(2,e-2),16)},Cs=new Set;class Bs extends Ts{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&&(!Fe(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 Bs(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:xs,this._requestInit=h({},t.requestInit);let a=null;if(null==(r=t.requestInit)?void 0:r.headers){const e=h({},ge(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=_s(a);e&&(this._offset=e.offset,this._length=e.length)}this._orchestrator=new As({maxCacheSize:null!=(n=t.maxCacheSize)?n:64*u(2,20),maxWorkerCount:null!=(s=t.parallelism)?s:2,runWorker:this._runWorker.bind(this),prefetchProfile:Fs.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:se(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 Ce(a)?a.then(o):o(a)}_runWorker(e){return y(this,null,function*(){for(var t;;){const r=new AbortController,n=yield ke(null!=(t=this._options.fetchFn)?t:fetch,this._url,pe(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")||Cs.has(e.origin)||(We._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.`),Cs.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){We._error("Error while reading response stream. Attempting to resume.",i),yield Le(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;We._error("Error while reading response stream. Attempting to resume.",s),yield Le(1e3*e);const a=yield ke(null!=(n=this._options.fetchFn)?n:fetch,this._url,pe(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 Rs(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);Ce(e)?e.then(e=>{e?(I(e.offset===o.start),o.resolve(e.bytes)):o.resolve(null)},e=>o.reject(e)):(I(null===e),o.resolve(null))}}_dispose(){this._orchestrator.dispose(),this._sequentialBacking&&(this._sequentialBacking._disposed=!0,this._sequentialBacking._dispose())}}const Es=/^bytes=(\d+)-(\d*)$/,_s=e=>{const t=Es.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=G(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}=Y();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 Do);this._pendingSlices.length=0,this._cache.length=0,null==(e=this._reader)||e.cancel()}}const Fs={fileSystem:(e,t)=>{const i=u(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=u(2,16);e=Math.max(0,Math.floor((e-r)/r)*r);for(const n of i){const i=8*u(2,20),r=Math.max((n.startPos+n.targetPos)/2,n.targetPos-i);if(Ee(e,t,r,n.targetPos)){const e=n.targetPos-n.startPos,r=Math.ceil((e+1)/i)*i,s=u(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+Is)}}};class As{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;I(!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);I(a<=e&&t<=o);let l=null;const c=G(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=G(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(I(n<=s),m=h.length&&(l={bytes:h,view:F(h),offset:e}),0===p.length)return I(l),l;const{promise:g,resolve:k,reject:y}=Y(),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)}}):(I(h),l=g.then(t=>t&&{bytes:t,view:F(t),offset:e})),l}checkHoleAgainstWorker(e,t,i){const r=u(2,17);if(Ee(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);I(-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=G(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=F(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=F(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 Ce(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 Ms=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},Ns=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 Os=/^0[xX][0-9a-fA-F]+$/,Ls=/^data:.*;base64,/i;class zs 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(){var e;return null!=(e=this.currentUpdateSegmentsPromise)?e:this.currentUpdateSegmentsPromise=(()=>y(this,null,function*(){try{const e=this.getRemainingWaitTimeMs();e>0&&(yield Le(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=Ms(e,yield this.demuxer.input._getSourceUncached({path:this.rootPath,isRoot:!1}),!1),i=new Mo(t.source),r=yield i.requestEntireFile();I(r),l=tl(r,r.length,{ignore:ds}),t.source instanceof Ts&&(this.rootPath=t.source.rootPath)}catch(R){e.error=R,e.hasError=!0}finally{Ns(e)}}const c=!1!==(null==(e=this.input._formatOptions.hls)?void 0:e.offsetTimestampsByDateTime);let d=!1,m=0,p=null,g=null,k=null,y=0,b=null,T=null,v=null,S=null,w=null,P=null,x=!1,B=null!=(t=C(this.segments))?t:null;const E=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}},_=e=>{y=e,B&&(I(null!==B.sequenceNumber),B.sequenceNumber0&&null!==P&&(m=y*P),x=!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}'.`);g=n}else if(e.startsWith(ns)){const t=new hs(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=E(r)),a&&null===a.offset)throw new Error("Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset.");if(!B){const e={path:Ae(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==k?void 0:k.method)&&!k.iv)throw new Error("IV attribute must be set on #EXT-X-KEY tag preceding the #EXT-X-MAP tag.");T={timestamp:m,unixEpochTimestamp:p,firstSegment:null,sequenceNumber:null,location:e,duration:0,encryption:k,initSegment:null,lastProgramDateTimeSeconds:w}}g=null,null===S?v=null:S=null}else if(e.startsWith(ss)){const t=new hs(e.slice(11)),i=t.get("method");if("NONE"===i)k=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(!Os.test(r))throw new Error(`Unsupported IV format '${r}'.`);let e=r.slice(2);e=e.padStart(32,"0"),i=new Uint8Array(Xi);for(let t=0;t=8&&112===i[4]&&115===i[5]&&115===i[6]&&104===i[7]){const e=F(i).getUint32(0);r=zi(i.subarray(8,Math.min(e,i.length)))}}k={method:i,psshBox:r}}}}else if(e.startsWith(as)){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)}else if(e.startsWith(os)){const t=E(e.slice(17));if(null===t.offset){if(null===v)throw new Error("Invalid M3U8 file; #EXT-X-BYTERANGE without offset requires a previous byte range.");t.offset=v}S=t,v=t.offset+t.length}else if(e.startsWith(ls)){if(B)continue;const t=e.slice(25),i=Date.parse(t);if(!Number.isFinite(i))continue;const r=i/1e3;if(w===r)continue;if(null===w&&this.segments.length>0){const e=C(this.segments),t=r-(e.timestamp+e.duration);for(const i of this.segments)i.unixEpochTimestamp=i.timestamp+t,c&&(i.timestamp=i.unixEpochTimestamp)}w=r,p=r,c&&(m=r)}else if("#EXT-X-DISCONTINUITY"===e)b=null;else if(e.startsWith(cs)){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,P=i}else{if("#EXT-X-ENDLIST"===e){this.streamHasEnded=!0;break}if(e.startsWith(us)){"vod"===e.slice(21).toLowerCase()&&(this.streamHasEnded=!0)}}}else{if("#EXTM3U"!==e)throw new Error("Invalid M3U8 file; expected first line to be #EXTM3U.");d=!0}}if(!d)throw new Error("Invalid M3U8 file; no #EXTM3U header.")})}getFirstSegment(){return 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=G(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=f(h({},this.input._formatOptions),{isobmff:f(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=>Ui(e,i))||(t=[...t,i]),this.input._formatOptions.isobmff.resolveKeyId(f(h({},e),{psshBoxes:t}))})})}),o=new Fo({source:new Ss(r.location.path,e=>y(this,null,function*(){var t,i;I(e.isRoot);const n=f(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;I(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=u(2,16),a=new ir;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(Ce(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=Lo(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 Mo(t.source),()=>y(this,null,function*(){const t={stack:[],error:void 0,hasError:!1};try{const i=Ms(t,yield this.input._getSourceCached({path:e.keyUri,isRoot:!1},Ro),!1),r=new Mo(i.source),n=yield r.requestSlice(0,Xi);if(!n)throw new Error("Invalid AES-128 key; expected at least 16 bytes of data.");return{key:Lo(n,Xi),iv:e.iv}}catch(i){t.error=i,t.hasError=!0}finally{Ns(t)}}),()=>{t.free()});s=new Rs(o).ref()}else I(!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 sa)),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=Me(this.inputCache,e=>e.age);I(-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 Us extends Ni{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*(){I(this.input._rootSource instanceof Ts);const e=yield this.input._reader.requestEntireFile();I(e);const t=tl(e,e.length,{ignore:ds}),{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=>ui.includes(Ii(e))),g=h.some(e=>hi.includes(Ii(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=Ae(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});I(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=Ae(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});I(null!==a),h.push(a)}}h=[...new Set(h)];let k=null,b=null;const T=e.attributes.getAsNumber("bandwidth");I(null!==T);const v=e.attributes.getAsNumber("average-bandwidth"),S=e.attributes.get("name");for(const i of h){const d=Ii(i);if(null!==d)if(ui.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:ae,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:Vs(i.attributes),autoselect:Vs(i.attributes)||js(i.attributes),languageCode:Ks(i.attributes.get("language")),lineNumber:i.lineNumber,fullPath:null!=(c=i.fullPath)?c:e.fullPath,fullCodecString:b,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===ae&&(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 Ws(u)):this.trackBackings.push(new Hs(u));this.internalTracks=l}))()}getTrackBackings(){return y(this,null,function*(){return yield this.readMetadata(),I(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 zs(this,e,i,null),this.segmentedInputs.push(t),t}getMetadataTags(){return y(this,null,function*(){return{}})}getMimeType(){return y(this,null,function*(){return Zn})}dispose(){if(this.segmentedInputs){for(const e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}}class qs{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 Ws){for(const r of i)if((yield r.getCodec())===this.getCodec()){t=r;break}}else{I(this instanceof Hs);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 f(h({},je),{default:this.internalTrack.autoselect,primary:this.internalTrack.default})}getId(){return this.internalTrack.id}getPairingMask(){return this.internalTrack.pairingMask}getInternalCodecId(){return null}getLanguageCode(){return this.internalTrack.languageCode}getName(){return this.internalTrack.name}getNumber(){I(this.internalTrack.demuxer.internalTracks);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 Ws extends qs{constructor(e){super(e)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return"video"}getCodec(){return Ii(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 Hs extends qs{constructor(e){super(e)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return"audio"}getCodec(){return Ii(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 Vs=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}".`)},js=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}".`)},Ks=e=>{if(null===e)return ae;const t=e.split("-")[0];return t||ae};class Xs{constructor(){this._isIsobmff=!1}}class $s extends Xs{constructor(){super(...arguments),this._isIsobmff=!0}_getMajorBrand(e){return y(this,null,function*(){let t=e._reader.requestSlice(0,12);if(Ce(t)&&(t=yield t),!t)return null;t.skip(4);const i=el(t,4);return"ftyp"!==i&&"styp"!==i?null:el(t,4)})}_createDemuxer(e){return new rr(e)}}class Gs extends $s{_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(Ce(t)&&(t=yield t),!t)return!1;let r=jo(t),n=8;if(1===r){let t=e._reader.requestSlice(i+8,8);if(Ce(t)&&(t=yield t),!t)return!1;r=Go(t),n=16}if(r8)return!1;if(Er(i,r)!==vr.EBML)return!1;const n=Rr(i);if("number"!==typeof n)return!1;let s=e._reader.requestSlice(i.filePos,n);if(Ce(s)&&(s=yield s),!s)return!1;const a=i.filePos;for(;s.filePos<=a+n-2;){const e=Fr(s);if(!e)break;const{id:i,size:r}=e,n=s.filePos;if(void 0===r)return!1;switch(i){case vr.EBMLVersion:if(1!==Er(s,r))return!1;break;case vr.EBMLReadVersion:if(1!==Er(s,r))return!1;break;case vr.DocType:if(Ar(s,r)!==t)return!1;break;case vr.DocTypeVersion:if(Er(s,r)>4)return!1}s.filePos=n+r}return!0})}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new ln(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}}class Js extends Ys{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}}class Zs extends Xs{_canReadInput(e){return y(this,null,function*(){let t=0;for(;;){let i=e._reader.requestSlice(t,ol);if(Ce(i)&&(i=yield i),!i)break;const r=dl(i);if(!r)break;t=i.filePos+r.size}const i=yield hn(e._reader,t,t+4096);if(!i)return!1;const r=i.header,n=_i(r.mpegVersionId,r.channel);let s=e._reader.requestSlice(i.startPos+n,4);if(Ce(s)&&(s=yield s),!s)return!1;const a=jo(s);if(a===Bi||a===Ei)return!0;t=i.startPos+i.header.totalSize;const o=yield hn(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 fn(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}}class ea extends Xs{_canReadInput(e){return y(this,null,function*(){let t=e._reader.requestSlice(0,12);if(Ce(t)&&(t=yield t),!t)return!1;const i=el(t,4);if("RIFF"!==i&&"RIFX"!==i&&"RF64"!==i)return!1;t.skip(4);return"WAVE"===el(t,4)})}_createDemuxer(e){return new En(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}}class ta extends Xs{_canReadInput(e){return y(this,null,function*(){let t=e._reader.requestSlice(0,4);return Ce(t)&&(t=yield t),!!t&&"OggS"===el(t,4)})}_createDemuxer(e){return new wn(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}}class ia extends Xs{_canReadInput(e){return y(this,null,function*(){let t=0;for(;;){let i=e._reader.requestSlice(t,ol);if(Ce(i)&&(i=yield i),!i)break;const r=dl(i);if(!r)break;t=i.filePos+r.size}let i=e._reader.requestSlice(t,4);return Ce(i)&&(i=yield i),!!i&&"fLaC"===el(i,4)})}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new Nn(e)}}class ra extends Xs{_canReadInput(e){return y(this,null,function*(){let t=0;for(;;){let i=e._reader.requestSlice(t,ol);if(Ce(i)&&(i=yield i),!i)break;const r=dl(i);if(!r)break;t=i.filePos+r.size}let i=e._reader.requestSliceRange(t,7,9);if(Ce(i)&&(i=yield i),!i)return!1;const r=Fn(i);if(!r)return!1;if(t+=r.frameLength,i=e._reader.requestSliceRange(t,7,9),Ce(i)&&(i=yield i),!i)return!1;const n=Fn(i);return!!n&&(r.objectType===n.objectType&&r.samplingFrequencyIndex===n.samplingFrequencyIndex&&r.channelConfiguration===n.channelConfiguration)})}_createDemuxer(e){return new Dn(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}}class na extends Xs{_canReadInput(e){return y(this,null,function*(){let t=e._reader.requestSlice(0,205);if(Ce(t)&&(t=yield t),!t)return!1;const i=Lo(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 Vn(e)}get name(){return"MPEG Transport Stream"}get mimeType(){return"video/MP2T"}}class sa extends Xs{_canReadInput(e){return y(this,null,function*(){let t=e._reader.requestSlice(0,7);if(Ce(t)&&(t=yield t),!t)return!1;if(!("#EXTM3U"===el(t,7)))return!1;if(!(e._rootSource instanceof Ts))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 Us(e)}get name(){return"HTTP Live Streaming (HLS)"}get mimeType(){return Zn}}const aa=new Gs,oa=new Qs,la=new Ys,ca=new Js,ua=new Zs,da=new ea,ha=new ta,fa=new ra,ma=new ia,pa=new na,ga=new sa,ka=[ga,aa,oa,la,ca,da,ha,ma,ua,fa,pa],ya=[ga,aa,oa,ua,fa,pa];var ba=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});Re();let Ta=-1/0,va=-1/0,Sa=null;"undefined"!==typeof FinalizationRegistry&&(Sa=new FinalizationRegistry(e=>{const t=performance.now();"video"===e.type?(t-Ta>=1e3&&(We._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."),Ta=t),"undefined"!==typeof VideoFrame&&e.data instanceof VideoFrame&&e.data.close()):(t-va>=1e3&&(We._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."),va=t),"undefined"!==typeof AudioData&&e.data instanceof AudioData&&e.data.close())}));class wa{constructor(){this._referenceCount=0,this._lastAllocationBuffer=null}}const Pa=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],Ia=new Set(Pa);class xa{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){var i,r,n,s,a,o,l,c,u,d,h,f,m,p,g,k,y,b,T,v,S,w,P,I,x,C,B,E,_,F,A;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||!Ia.has(t.format))throw new TypeError("init.format must be one of: "+Pa.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&&Oe(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:Na(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?R(e):R(e).slice(),this._layout=m,this.colorSpace=new Ra(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)&&Oe(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!=(S=null==t?void 0:t.rotation)?S:0,this.squarePixelWidth=e.displayWidth,this.squarePixelHeight=e.displayHeight,this.timestamp=null!=(w=null==t?void 0:t.timestamp)?w:e.timestamp/1e6,this.duration=null!=(I=null==t?void 0:t.duration)?I:(null!=(P=e.duration)?P:0)/1e6,this.colorSpace=new Ra(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&&Oe(t.visibleRect,"init.visibleRect"),"undefined"!==typeof VideoFrame)return new xa(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*me),duration:Math.trunc((null!=(x=t.duration)?x: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 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:Se(),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 Ra({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else{if(!(e instanceof wa))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&&!Pa.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!=(F=t.duration)?F:0,this.colorSpace=e.getColorSpace()}this.encodeOptions=null!=(A=null==t?void 0:t.encodeOptions)?A:{},this.pixelAspectRatio=Ne({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),null==Sa||Sa.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return I(null!==this._data),this._data instanceof wa?new xa(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):Fa(this._data)?new xa(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):this._data instanceof Uint8Array?(I(this._layout),new xa(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 xa(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==Sa||Sa.unregister(this),this._data instanceof wa?(this._data._referenceCount--,0===this._data._referenceCount&&this._data.close()):Fa(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){var t;if(Ma(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(Fa(this._data))return this._data.allocationSize(e);return La(this,e).allocationSize}copyTo(e){return y(this,arguments,function*(e,t={}){var i,r;if(!H(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(Ma(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(I(null!==this._data),Fa(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 wa)){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 xa))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{ba(i)}}}const n=La(this,t);I(this.format);const s=R(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)I(this._layout),I(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");I(e);const t=e.getImageData(0,0,this.codedWidth,this.codedHeight);o=[{data:R(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 Fa(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?(I(this._layout),new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,layout:this._layout,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,t,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&&Da(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=Aa(T,m,p));const{sx:v,sy:S,sWidth:w,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,S,w,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?_a(d,h):{canvas:e,context:t,isNew:i.targetIsFresh};m.imageSmoothingQuality="high",i.fillBlack?(m.fillStyle="black",m.fillRect(0,0,d,h)):p||m.clearRect(0,0,d,h),this.drawWithFit(m,{fit:i.fit,rotation:i.rotation,crop:i.crop}),m.globalCompositeOperation="copy";for(let g=c;g>1;g--){const e=r*u(2,g),t=n*u(2,g);m.drawImage(f,0,0,e,t,0,0,e/2,t/2)}m.globalCompositeOperation="source-over",c>0&&(t.imageSmoothingQuality="high",t.globalCompositeOperation="copy",t.drawImage(f,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(I(null!==this._data),this._data instanceof wa||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&&Da(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=x(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=Aa(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=le(f,null!=(i=e.roundDimensionsTo)?i:1),m=le(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 Ca){let t=e(this,p);if(Ce(t)&&(t=yield t),null!==t)return t}const{canvas:g,context:k,isNew:y}=_a(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 xa(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 Ca=[],Ba=[];let Ea=0;const _a=(e,t)=>{for(const n of Ba)if(n.canvas.width===e&&n.canvas.height===t)return n.age=Ea++,{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 Ba.length>=3&&Ba.splice(Me(Ba,e=>e.age),1),Ba.push({canvas:i,context:r,age:Ea++}),{canvas:i,context:r,isNew:!0}};class Ra{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(M);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(O);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(z);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 Fa=e=>"undefined"!==typeof VideoFrame&&e instanceof VideoFrame,Aa=(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 I(s>=0),I(a>=0),{left:r,top:n,width:s,height:a}},Da=(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.")},Ma=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.")}},Na=(e,t,i)=>{const r=Oa(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},Oa=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:te(e),I(!1)}},La=(e,t)=>{const i={left:0,top:0,width:e.codedWidth,height:e.codedHeight},r=t.rect,n=za(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 qa(n,a,s)},za=(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(!Ua(n,s))throw new TypeError("visibleRect alignment is invalid for the format.");return s},Ua=(e,t)=>{if(null===e)return!0;const i=Oa(e);for(let r=0;r{const r=Oa(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/(ja(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*ja(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=ja(r),o=Ka(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(!H(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&&!Wa.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=ja(o),f=Ka(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 Qa(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(S){if("f32-planar"===o)throw S;a="f32-planar"}}const k=Xa(a),y=ja(a),b=Ka(a);let T;if(this._data instanceof Ha){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 Va({data:n,format:this.format,sampleRate:this.sampleRate,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp+e/this.sampleRate})}close(){this._closed||(null==Sa||Sa.unregister(this),this._data instanceof Ha?(this._data._referenceCount--,0===this._data._referenceCount&&this._data.close()):Ga(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 Ha?this._createAudioDataFromData():Ga(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(Ka(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")}},Ka=e=>{switch(e){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},Xa=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)}},$a=e=>{switch(e){case"u8":case"u8-planar":return(e,t,i)=>e.setUint8(t,se(127.5*(i+1),0,255));case"s16":case"s16-planar":return(e,t,i)=>e.setInt16(t,se(Math.round(32767*i),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,i)=>e.setInt32(t,se(Math.round(2147483647*i),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,i)=>e.setFloat32(t,i,!0)}},Ga=e=>"undefined"!==typeof AudioData&&e instanceof AudioData,Qa=(e,t,i,r,n,s,a,o)=>{const l=Xa(i),c=$a(r),u=ja(i),d=ja(r),h=Ka(i);if(Ka(r))if(h){const r=new ArrayBuffer(o*u),n=F(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.")},eo=e=>{if(!Fe(e))throw new TypeError("timestamp must be a number.")},to=(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 io{constructor(e){if(!(e instanceof yo))throw new TypeError("track must be an InputTrack.");this._track=e}getFirstPacket(){return y(this,arguments,function*(e={}){if(Za(e),this._track.input._disposed)throw new Do;return to(this._track,this._track._backing.getFirstPacket(e),e)})}getFirstKeyPacket(){return y(this,arguments,function*(e={}){Za(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(eo(e),Za(t),this._track.input._disposed)throw new Do;return to(this._track,this._track._backing.getPacket(e,t),t)})}getNextPacket(e){return y(this,arguments,function*(e,t={}){if(!(e instanceof Li))throw new TypeError("packet must be an EncodedPacket.");if(Za(t),this._track.input._disposed)throw new Do;return to(this._track,this._track._backing.getNextPacket(e,t),t)})}getKeyPacket(e){return y(this,arguments,function*(e,t={}){if(eo(e),Za(t),this._track.input._disposed)throw new Do;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);const i=yield this._track._backing.getKeyPacket(e,t);if(!i)return i;I("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 Li))throw new TypeError("packet must be an EncodedPacket.");if(Za(t),this._track.input._disposed)throw new Do;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);const i=yield this._track._backing.getNextKeyPacket(e,t);if(!i)return i;I("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 Li))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 Li))throw new TypeError("endPacket must be an EncodedPacket.");if(Za(i),this._track.input._disposed)throw new Do;const r=[];let{promise:n,resolve:s}=Y(),{promise:a,resolve:o}=Y(),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}=Y()),yield a):(r.push(u),s(),({promise:n,resolve:s}=Y()),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 Do;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 ro{constructor(e,t){this.onSample=e,this.onError=t}}class no{mediaSamplesInRange(e=-1/0,t=1/0,i){eo(e),eo(t);const r=[];let n=!1,s=null,{promise:a,resolve:o}=Y(),{promise:l,resolve:c}=Y(),u=!1,d=!1,m=!1,p=null,g=null,k=!1;const b=f(h({},i),{verifyKeyPackets:!0,metadataOnly:!1});(()=>y(this,null,function*(){var i;p=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}=Y())))},e=>{k||(g=e,k=!0,o())});const h=this._createPacketSink(),f=null!=(i=yield h.getKeyPacket(e,b))?i:yield h.getFirstKeyPacket(b);let y=f;const T=h.packets(null!=f?f:void 0,void 0,b);for(yield T.next();y&&!d&&!this._track.input._disposed;){const e=so(r.length);if(r.length+p.getDecodeQueueSize()>e){({promise:l,resolve:c}=Y()),yield l;continue}p.decode(y);const t=yield T.next();if(t.done)break;y=t.value}yield T.return(),m||this._track.input._disposed||(yield p.flush()),!n&&s&&r.push(s),u=!0,o()}))().catch(e=>{k||(g=e,k=!0,o())}).finally(()=>{null==p||p.close()});const T=this._track,v=()=>{null==s||s.close();for(const e of r)e.close()};return{next(){return y(this,null,function*(){for(;;){if(T.input._disposed)throw m=!0,d=!0,v(),new Do;if(m)return{value:void 0,done:!0};if(k)throw m=!0,d=!0,v(),g;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 m=!0,d=!0,c(),o(),v(),{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 T(this,null,function*(){Symbol.iterator in e?yield*v(e[Symbol.iterator]()):yield*v(e[Symbol.asyncIterator]())})}(e),r=[],n=[];let{promise:s,resolve:a}=Y(),{promise:o,resolve:l}=Y(),c=!1,u=!1,d=null,m=null,p=!1;const g=e=>{n.push(e),a(),({promise:s,resolve:a}=Y())},k=f(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{p||(m=e,p=!0,a())});const e=this._createPacketSink();let t=null,s=null,h=-1;const f=()=>y(this,null,function*(){I(s),I(d);let t=s;for(d.decode(t);t.sequenceNumberi&&!u;)({promise:o,resolve:l}=Y()),yield o;if(u)break;const r=yield e.getNextPacket(t,k);I(r),d.decode(r),t=r}h=-1}),b=()=>y(this,null,function*(){I(d),yield d.flush();for(let e=0;e{p||(m=e,p=!0,a())}).finally(()=>{null==d||d.close()});const b=this._track,w=()=>{for(const e of n)null==e||e.close()};return{next(){return y(this,null,function*(){for(;;){if(b.input._disposed)throw u=!0,w(),new Do;if(u)return{value:void 0,done:!0};if(p)throw u=!0,w(),m;if(n.length>0){const e=n.shift();return I(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(),w(),{value:void 0,done:!0}})},throw(e){return y(this,null,function*(){throw e})},[Symbol.asyncIterator](){return this}}}}const so=e=>0===e?40:8;class ao extends ro{constructor(e,t,i,r,n,s){var a,o,l,c,u,d,m,p;super(e,t),this.codec=i,this.decoderConfig=r,this.rotation=n,this.timeResolution=s,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new ye,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 g=Ya.find(e=>e.supports(i,r));if(g)this.customDecoder=new g,this.customDecoder.codec=i,this.customDecoder.config=r,this.customDecoder.onSample=e=>{if(!(e instanceof xa))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();I(void 0!==t),this.mergeAlpha(e,t)}else this.colorQueue.push(e)};if(Pe()){if("avc"===i&&this.decoderConfig.description){const e=mt(R(this.decoderConfig.description));if(e&&e.sequenceParameterSets.length>0){const t=gt(e.sequenceParameterSets[0]);t&&(0===t.frameMbsOnlyFlag&&(this.decoderConfig=f(h({},this.decoderConfig),{hardwareAcceleration:"prefer-software"})),0!==t.maxDecFrameBuffering&&1!==t.bitstreamRestrictionFlag&&(e.sequenceParameterSets[0]=yt(t),this.decoderConfig=f(h({},this.decoderConfig),{description:ft(e)})))}}q(this.decoderConfig.colorSpace)||(this.decoderConfig=f(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!=(p=null==(m=this.decoderConfig.colorSpace)?void 0:m.fullRange)&&p}}))}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:(I(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(I(this.decoder),Te()||Q(this.inputTimestamps,e.timestamp,e=>e),Pe()&&0===this.currentPacketIndex)if("avc"===this.codec){const t=[];let i=!1;for(const n of at(e.data,this.decoderConfig)){const r=ot(e.data[n.offset]);if(i||(i=r>=1&&r<=5),r===et.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&R(t.description)[4];return dt(e,i+1)}return ut(e)})(t,this.decoderConfig);e=new Li(r,e.type,e.timestamp,e.duration)}else if("hevc"===this.codec){const t=Ft(e.data,this.decoderConfig);t&&(e=new Li(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 lo),!this.alphaDecoder){const e=e=>{if(this.colorQueue.length>0){const t=this.colorQueue.shift();I(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();I(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=Ut(this.codec,this.decoderConfig,e.sideData.alpha);if(this.alphaHadKeyframe||(this.alphaHadKeyframe="key"===t),this.alphaHadKeyframe){if("hevc"===this.codec&&this.currentAlphaPacketIndex>0&&!this.alphaRaslSkipped){if(this.hasHevcRaslPicture(e.sideData.alpha))return void this.pushNullAlphaFrame();this.alphaRaslSkipped=!0}this.currentAlphaPacketIndex++,this.alphaDecoder.decode(e.alphaToEncodedVideoChunk(null!=t?t:e.type)),this.alphaDecoderQueueSize++}else this.pushNullAlphaFrame()}pushNullAlphaFrame(){0===this.alphaDecoderQueueSize?this.alphaQueue.push(null):this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture(e){for(const t of bt(e,this.decoderConfig)){const i=Tt(e[t.offset]);if(i===it.RASL_N||i===it.RASL_R)return!0}return!1}sampleHandler(e){if(Te()){if(this.sampleQueue.length>0&&e.timestamp>=C(this.sampleQueue).timestamp){for(const e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}Q(this.sampleQueue,e,e=>e.timestamp)}else{const t=this.inputTimestamps.shift();I(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=Y();this.mergeAlphaPromises.push(i.promise);const r={sample:null};this.finalSamples.push(r);try{if(t){I(this.merger);const i=yield this.merger.merge(e,t);r.sample=new xa(i)}else r.sample=new xa(e);for(;this.finalSamples.length>0&&null!==this.finalSamples[0].sample;){const e=this.finalSamples.shift();this.sampleHandler(e.sample)}}catch(n){J(this.finalSamples,r),this.onError(n)}finally{J(this.mergeAlphaPromises,i.promise),i.resolve()}})}flush(){return y(this,null,function*(){var e;if(this.customDecoder?yield this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(I(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),Te()){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()):(I(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 oo=null;class lo{constructor(){this.workers=[],this.nextWorkerIndex=0,this.pendingRequests=new Map,this.nextRequestId=0}merge(e,t){if(0===this.workers.length){if(!oo){const e=new Blob([`(${co.toString()})()`],{type:"application/javascript"});oo=URL.createObjectURL(e)}const e=se(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=Y();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 co=()=>{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 S={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,S)}),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 ho extends no{constructor(e,t={}){if(!(e instanceof vo))throw new TypeError("videoTrack must be an InputVideoTrack.");uo(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(Ie("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 I(i&&n),n=f(h({},n),{hardwareAcceleration:this._decoderOptions.hardwareAcceleration,optimizeForLatency:this._decoderOptions.optimizeForLatency}),new ao(e,t,i,n,r,s)})}_createPacketSink(){return new io(this._track)}getSample(e){return y(this,arguments,function*(e,t={}){eo(e);try{for(var i,r,n,s=S(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 fo{constructor(e,t={}){var i,r,n;if(this._rotation=0,this._initPromise=null,this._nextCanvasIndex=0,!(e instanceof vo))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&&Da(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&&uo(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 ho(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=Aa(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||Se()});I(s),e._drawWithFitAndMipmapping(r,s,{fit:this._fit,rotation:this._rotation,crop:this._crop,targetIsFresh:n,fillBlack:!this._alpha&&Se()});const a={canvas:r,timestamp:e.timestamp,duration:e.duration};return e.close(),a}getCanvas(e,t){return y(this,null,function*(){eo(e),yield this._ensureInit();const i=yield this._videoSampleSink.getSample(e,t);return i&&this._videoSampleToWrappedCanvas(i)})}canvases(e,t,i){return T(this,null,function*(){yield new b(this._ensureInit()),yield*v(ne(this._videoSampleSink.samples(e,t,i),e=>this._videoSampleToWrappedCanvas(e)))})}canvasesAtTimestamps(e,t){return T(this,null,function*(){yield new b(this._ensureInit()),yield*v(ne(this._videoSampleSink.samplesAtTimestamps(e,t),e=>e&&this._videoSampleToWrappedCanvas(e)))})}}class mo extends ro{constructor(e,t,i,r){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new ye,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=Ja.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 Va))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 Va(e))}catch(t){this.onError(t)}},error:t=>{t.stack=e,this.onError(t)}}),this.decoder.configure(r)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(I(this.decoder),this.decoder.decodeQueueSize)}decode(e){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).catch(e=>this.onError(e)).finally(()=>this.customDecoderQueueSize--)):(I(this.decoder),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()):(I(this.decoder),yield this.decoder.flush()),this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0})}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(I(this.decoder),"closed"!==this.decoder.state&&this.decoder.close())}}class po extends ro{constructor(e,t,i){super(e,t),this.decoderConfig=i,this.currentTimestamp=null,I(di.includes(i.codec)),this.codec=i.codec;const{dataType:r,sampleSize:n,littleEndian:s}=Pi(this.codec);switch(this.inputSampleSize=n,n){case 1:"unsigned"===r?this.readInputValue=(e,t)=>e.getUint8(t)-u(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)-u(2,15):"signed"===r?this.readInputValue=(e,t)=>e.getInt16(t,s):I(!1);break;case 3:"unsigned"===r?this.readInputValue=(e,t)=>ie(e,t,s)-u(2,23):"signed"===r?this.readInputValue=(e,t)=>((e,t,i)=>ie(e,t,i)<<8>>8)(e,t,s):I(!1);break;case 4:"unsigned"===r?this.readInputValue=(e,t)=>e.getUint32(t,s)-u(2,31):"signed"===r?this.readInputValue=(e,t)=>e.getInt32(t,s):"float"===r?this.readInputValue=(e,t)=>e.getFloat32(t,s):I(!1);break;case 8:"float"===r?this.readInputValue=(e,t)=>e.getFloat64(t,s):I(!1);break;default:te(n),I(!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+u(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:te(n),I(!1)}}getDecodeQueueSize(){return 0}decode(e){const t=F(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 Va({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 go extends no{constructor(e){if(!(e instanceof So))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(Ie("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 I(i&&r),di.includes(r.codec)?new po(e,t,r):new mo(e,t,i,r)})}_createPacketSink(){return new io(this._track)}getSample(e){return y(this,arguments,function*(e,t={}){eo(e);try{for(var i,r,n,s=S(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 ko{constructor(e){if(!(e instanceof So))throw new TypeError("audioTrack must be an InputAudioTrack.");this._audioSampleSink=new go(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*(){eo(e);const i=yield this._audioSampleSink.getSample(e,t);return i&&this._audioSampleToWrappedArrayBuffer(i)})}buffers(e,t,i){return ne(this._audioSampleSink.samples(e,t,i),e=>this._audioSampleToWrappedArrayBuffer(e))}buffersAtTimestamps(e,t){return ne(this._audioSampleSink.samplesAtTimestamps(e,t),e=>e&&this._audioSampleToWrappedArrayBuffer(e))}}class yo{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof vo}isAudioTrack(){return this instanceof So}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 bo(this._backing.getInternalCodecId(),"internalCodecId","getInternalCodecId")}getLanguageCode(){return y(this,null,function*(){return this._backing.getLanguageCode()})}get languageCode(){return bo(this._backing.getLanguageCode(),"languageCode","getLanguageCode")}getName(){return y(this,null,function*(){return this._backing.getName()})}get name(){return bo(this._backing.getName(),"name","getName")}getTimeResolution(){return y(this,null,function*(){return this._backing.getTimeResolution()})}get timeResolution(){return bo(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 bo(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 ce(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 io(this);let r=1/0,n=-1/0,s=0,a=0;try{for(var o,l,c,u=S(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 yo))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(xo({filter:e=>e.canBePairedWith(this)},e))})}getPairableVideoTracks(e){return y(this,null,function*(){return this.input.getVideoTracks(xo({filter:e=>e.canBePairedWith(this)},e))})}getPairableAudioTracks(e){return y(this,null,function*(){return this.input.getAudioTracks(xo({filter:e=>e.canBePairedWith(this)},e))})}getPrimaryPairableVideoTrack(e){return y(this,null,function*(){return this.input.getPrimaryVideoTrack(xo({filter:e=>e.canBePairedWith(this)},e))})}getPrimaryPairableAudioTrack(e){return y(this,null,function*(){return this.input.getPrimaryAudioTrack(xo({filter:e=>e.canBePairedWith(this)},e))})}hasPairableTrack(e){return y(this,null,function*(){e&&(e=To(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=To(e)),this.hasPairableTrack(t=>y(this,null,function*(){return t.isVideoTrack()&&(!e||(yield e(t)))}))}hasPairableAudioTrack(e){return e&&(e=To(e)),this.hasPairableTrack(t=>y(this,null,function*(){return t.isAudioTrack()&&(!e||(yield e(t)))}))}}const bo=(e,t,i)=>{if(Ce(e))throw new Error(`'${t}' is deprecated and not available synchronously for this track. Use the preferred '${i}()' instead.`);return e},To=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 Ce(r)?r.then(i):i(r)}:void 0};class vo extends yo{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 bo(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 bo(this._backing.getCodedWidth(),"codedWidth","getCodedWidth")}getCodedHeight(){return y(this,null,function*(){return this._backing.getCodedHeight()})}get codedHeight(){return bo(this._backing.getCodedHeight(),"codedHeight","getCodedHeight")}getRotation(){return y(this,null,function*(){return this._backing.getRotation()})}get rotation(){return bo(this._backing.getRotation(),"rotation","getRotation")}getSquarePixelWidth(){return y(this,null,function*(){return this._backing.getSquarePixelWidth()})}get squarePixelWidth(){return bo(this._backing.getSquarePixelWidth(),"squarePixelWidth","getSquarePixelWidth")}getSquarePixelHeight(){return y(this,null,function*(){return this._backing.getSquarePixelHeight()})}get squarePixelHeight(){return bo(this._backing.getSquarePixelHeight(),"squarePixelHeight","getSquarePixelHeight")}getPixelAspectRatio(){return y(this,null,function*(){var e;return null!=(e=this._pixelAspectRatioCache)?e:this._pixelAspectRatioCache=Ne({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=Ne({num:bo(this._backing.getSquarePixelWidth(),"pixelAspectRatio","getPixelAspectRatio")*bo(this._backing.getCodedHeight(),"pixelAspectRatio","getPixelAspectRatio"),den:bo(this._backing.getSquarePixelHeight(),"pixelAspectRatio","getPixelAspectRatio")*bo(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=bo(i,"displayWidth","getDisplayWidth");if(null!==e)return e}const r=bo(this._backing.getRotation(),"displayWidth","getDisplayWidth")%180===0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight();return bo(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=bo(i,"displayHeight","getDisplayHeight");if(null!==e)return e}const r=bo(this._backing.getRotation(),"displayHeight","getDisplayHeight")%180===0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth();return bo(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(I(null!==t),Ya.some(i=>i.supports(t,e)))return!0;if("undefined"===typeof VideoDecoder)return!1;return!0===(yield VideoDecoder.isConfigSupported(e)).supported}catch(e){return We._error("Error during decodability check:",e),!1}})}determinePacketType(e){return y(this,null,function*(){if(!(e instanceof Li))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 I(i),Ut(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&&(!Fe(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 io(this),a=[];let o=-1/0,l=0;try{for(var c,u,d,h=S(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 S=0;Se-t),x=P-1>>1,C=P>>1;let B=0,E=0,_=0;for(const S of I)if(_+=b.get(S),0===B&&_>x&&(B=S),_>C){E=S;break}const R=(k/B+k/E)/2;return{underlyingFrameRate:g,bestGuessFrameRate:null!==g?g:_o(R),minFrameRate:k/v,maxFrameRate:k/T,averageFrameRate:k*P/w,medianFrameRate:R,frameRateIsConstant:null!==g&&1===T&&1===v,probedPacketCount:l}})}}class So extends yo{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 bo(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 bo(this._backing.getNumberOfChannels(),"numberOfChannels","getNumberOfChannels")}getSampleRate(){return y(this,null,function*(){return this._backing.getSampleRate()})}get sampleRate(){return bo(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(I(null!==t),Ja.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 We._error("Error during decodability check:",e),!1}})}determinePacketType(e){return y(this,null,function*(){if(!(e instanceof Li))throw new TypeError("packet must be an EncodedPacket.");return null===(yield this.getCodec())?null:"key"})}}const wo=e=>-(null!=e?e:-1/0),Po=e=>-e,Io=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 Ce(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 Ce(r)?r.then(i):i(r)}:void 0}},xo=(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 Ce(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 Ce(o)||Ce(l)?Promise.all([o,l]).then(([e,t])=>c(e,t)):c(o,l)}:void 0}),Co=(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=>Ce(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=>Ce(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)}),Bo=(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 Xs)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof ys||e.source instanceof bs))throw new TypeError("options.source must be a Source or SourceRef.");if(e.source instanceof ys&&e.source._disposed)throw new TypeError("options.source must not be a disposed Source.");if(void 0!==e.initInput&&!(e.initInput instanceof Fo))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 ys?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*(){I(this._rootSource instanceof Ts);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&&vs(i.request,e));if(i)return i.age++,Promise.resolve(i.sourceRef.source.ref());const r=this._sourceCachePromises.find(i=>i.cacheGroup===t&&vs(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(De(this._sourceCache,e=>e.cacheGroup===t&&1===e.sourceRef.source._refCount)>=4){const e=Me(this._sourceCache,e=>e.cacheGroup===t&&1===e.sourceRef.source._refCount?e.age:1/0);I(-1!==e);const i=this._sourceCache[e];this._sourceCache.splice(e,1),i.sourceRef.free(),J(this._sourceRefs,i.sourceRef)}this._sourceRefs.push(i);const r=this._sourceCachePromises.findIndex(t=>t.request===e);I(-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 Mo(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 Ao}))()}get source(){return this._rootSource}getFormat(){return y(this,null,function*(){return yield this._getDemuxer(),I(this._format),this._format})}canRead(){return y(this,null,function*(){try{return yield this._getDemuxer(),!0}catch(e){if(e instanceof Ao)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=Io(e));const t=(yield this._getTrackBackings()).map(e=>this._wrapBackingAsTrack(e));return Co(t,e)})}getVideoTracks(e){return y(this,null,function*(){e&&(e=Io(e));const t=(yield this.getTracks()).filter(e=>e.isVideoTrack());return Co(t,e)})}getAudioTracks(e){return y(this,null,function*(){e&&(e=Io(e));const t=(yield this.getTracks()).filter(e=>e.isAudioTrack());return Co(t,e)})}getPrimaryVideoTrack(e){return y(this,null,function*(){var t;e&&(e=Io(e));const i=xo(e,{sortBy:e=>y(null,null,function*(){return[Po((yield e.getDisposition()).default),Po(yield e.hasPairableAudioTrack()),Po(!(yield e.hasOnlyKeyPackets())),wo(yield e.getBitrate())]})});return null!=(t=(yield this.getVideoTracks(i))[0])?t:null})}getPrimaryAudioTrack(e){return y(this,null,function*(){var t;e&&(e=Io(e));const i=yield this.getPrimaryVideoTrack(),r=xo(e,{sortBy:e=>y(this,null,function*(){return[Po(!i||e.canBePairedWith(i)),Po((yield e.getDisposition()).default),wo(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 vo(this,e):new So(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 Ao extends Error{constructor(e="Input has an unsupported or unrecognizable format."){super(e),this.name="UnsupportedInputFormatError"}}class Do extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}}class Mo{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 Do;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 No(t,F(t),0,e,e)}const i=e+t,r=this.source._read(e,i,0,ks);return Ce(r)?r.then(t=>t?new No(t.bytes,t.view,t.offset,e,i):null):r?new No(r.bytes,r.view,r.offset,e,i):null}requestSliceRange(e,t,i){if(this.source._disposed)throw new Do;if(e<0)return null;if(null!==this.fileSizeNonStrict)return this.requestSlice(e,se(this.fileSizeNonStrict-e,t,i));{const r=this.requestSlice(e,i),n=r=>r||(I(null!==this.fileSizeNonStrict),this.requestSlice(e,se(this.fileSizeNonStrict-e,t,i)));return Ce(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(Ce(i)&&(i=yield i),!i||0===i.length)break;const r=Lo(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 No(i,F(i),0,0,t)}))()}}class No{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 No(e,F(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 No(this.bytes,this.view,this.offset,e,e+t)}}const Oo=(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.`)},Lo=(e,t)=>{Oo(e,t);const i=e.bytes.subarray(e.bufferPos,e.bufferPos+t);return e.bufferPos+=t,i},zo=e=>(Oo(e,1),e.view.getUint8(e.bufferPos++)),Uo=(e,t)=>{Oo(e,2);const i=e.view.getUint16(e.bufferPos,t);return e.bufferPos+=2,i},qo=e=>{Oo(e,2);const t=e.view.getUint16(e.bufferPos,!1);return e.bufferPos+=2,t},Wo=e=>{Oo(e,3);const t=ie(e.view,e.bufferPos,!1);return e.bufferPos+=3,t},Ho=e=>{Oo(e,2);const t=e.view.getInt16(e.bufferPos,!1);return e.bufferPos+=2,t},Vo=(e,t)=>{Oo(e,4);const i=e.view.getUint32(e.bufferPos,t);return e.bufferPos+=4,i},jo=e=>{Oo(e,4);const t=e.view.getUint32(e.bufferPos,!1);return e.bufferPos+=4,t},Ko=e=>{Oo(e,4);const t=e.view.getUint32(e.bufferPos,!0);return e.bufferPos+=4,t},Xo=e=>{Oo(e,4);const t=e.view.getInt32(e.bufferPos,!1);return e.bufferPos+=4,t},$o=(e,t)=>{let i,r;return t?(i=Vo(e,!0),r=Vo(e,!0)):(r=Vo(e,!1),i=Vo(e,!1)),4294967296*r+i},Go=e=>4294967296*jo(e)+jo(e),Qo=e=>4294967296*Xo(e)+jo(e),Yo=e=>{const t=Ko(e),i=(e=>{Oo(e,4);const t=e.view.getInt32(e.bufferPos,!0);return e.bufferPos+=4,t})(e);return 4294967296*i+t},Jo=e=>{Oo(e,4);const t=e.view.getFloat32(e.bufferPos,!1);return e.bufferPos+=4,t},Zo=e=>{Oo(e,8);const t=e.view.getFloat64(e.bufferPos,!1);return e.bufferPos+=8,t},el=(e,t)=>{Oo(e,t);let i="";for(let r=0;rA.decode(Lo(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 il,rl,nl,sl;(rl=il||(il={}))[rl.Unsynchronisation=128]="Unsynchronisation",rl[rl.ExtendedHeader=64]="ExtendedHeader",rl[rl.ExperimentalIndicator=32]="ExperimentalIndicator",rl[rl.Footer=16]="Footer",(sl=nl||(nl={}))[sl.ISO_8859_1=0]="ISO_8859_1",sl[sl.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",sl[sl.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",sl[sl.UTF_8=3]="UTF_8";const al=128,ol=10,ll=["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"],cl=(e,t)=>{var i;const r=e.filePos;null!=t.raw||(t.raw={}),null!=(i=t.raw).TAG||(i.TAG=Lo(e,al-3)),e.filePos=r;const n=ul(e,30);n&&(null!=t.title||(t.title=n));const s=ul(e,30);s&&(null!=t.artist||(t.artist=s));const a=ul(e,30);a&&(null!=t.album||(t.album=a));const o=ul(e,4),l=Number.parseInt(o,10);Number.isInteger(l)&&l>0&&(null!=t.date||(t.date=new Date(String(l))));const c=Lo(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=ul(e,28),e.skip(2)}else e.skip(-30),u=ul(e,30);u&&(null!=t.comment||(t.comment=u));const d=zo(e);d{const i=Lo(e,t),r=Be(i.indexOf(0),i.length),n=i.subarray(0,r);let s="";for(let a=0;a{const t=e.filePos,i=el(e,3),r=zo(e),n=zo(e),s=zo(e),a=jo(e);if("ID3"!==i||255===r||255===n||0!==(2155905152&a))return e.filePos=t,null;let o=Fi(a);return s&il.Footer&&(o+=ol),{majorVersion:r,revision:n,flags:s,size:o}},hl=(e,t,i)=>{var r,n,s,a,o,l;if(![2,3,4].includes(t.majorVersion))return void We._warn(`Unsupported ID3v2 major version: ${t.majorVersion}`);const c=t.flags&il.Footer?t.size-ol:t.size,u=Lo(e,c),d=new fl(t,u);if(t.flags&il.Unsynchronisation&&3===t.majorVersion&&d.ununsynchronizeAll(),t.flags&il.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&il.Unsynchronisation)),h)We._warn(`Skipping encrypted ID3v2 frame ${e.id}`),d.pos=u;else if(f)We._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!==ll[e]){null!=i.genre||(i.genre=ll[e]);break}}if(t=/^\d+$/.exec(e),t){const e=Number.parseInt(t[0]);if(void 0!==ll[e]){null!=i.genre||(i.genre=ll[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 fl{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:Fi(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 nl.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=Be(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=Be(r.findIndex(e=>0===e),r.length);return this.pos=i+Math.min(e+1,r.length),A.decode(r.subarray(0,e))}case nl.UTF_16_BE_NO_BOM:{const e=new TextDecoder("utf-16be"),t=Be(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 nl.UTF_8:{const e=Be(r.findIndex(e=>0===e),r.length);return this.pos=i+Math.min(e+1,r.length),A.decode(r.subarray(0,e))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";const t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}}class ml{constructor(e){this.events=e,this.input=null,this.audioSink=null,this.audioIterator=null,this.audioContext=null,this.gainNode=null,this.audioContextStartTime=0,this.playbackTimeAtStart=0,this.latestScheduledEndTime=0,this.duration=Number.NaN,this.paused=!0,this.volume=.7,this.muted=!1,this.playbackRate=1,this.asyncId=0,this.queuedNodes=new Set}get currentTime(){return this.paused?this.playbackTimeAtStart:(this.audioContext.currentTime-this.audioContextStartTime)*this.playbackRate+this.playbackTimeAtStart}ensureAudioContext(e){if(this.audioContext)return;const t=window.AudioContext||window.webkitAudioContext;try{this.audioContext=new t({sampleRate:e})}catch(i){this.audioContext=new t}this.gainNode=this.audioContext.createGain(),this.gainNode.connect(this.audioContext.destination),this.updateGain()}updateGain(){if(!this.gainNode)return;const e=this.muted?0:this.volume;this.gainNode.gain.value=e*e}stopQueuedNodes(){this.queuedNodes.forEach(e=>e.stop()),this.queuedNodes.clear()}stopIterator(){return y(this,null,function*(){var e;yield null==(e=this.audioIterator)?void 0:e.return(),this.audioIterator=null})}handleNoAudioTrack(){this.audioSink=null,this.ensureAudioContext()}load(e,t){return y(this,null,function*(){++this.asyncId,yield this.stopIterator(),this.stopQueuedNodes(),this.paused=!0,this.playbackTimeAtStart=0,this.audioContextStartTime=0;const{input:i,audioTrack:r,duration:n}=e;return this.input=i,this.duration=n,r?null!==r.codec&&(yield r.canDecode())?(this.ensureAudioContext(r.sampleRate),this.audioSink=new ko(r),void(null==t||t())):(this.audioSink=null,this.ensureAudioContext(),void(null==t||t())):(this.handleNoAudioTrack(),void(null==t||t()))})}runIterator(e){return y(this,null,function*(){if(!this.audioSink)return;yield this.stopIterator(),this.audioIterator=this.audioSink.buffers(this.currentTime);for(;;){if(e!==this.asyncId||this.paused)return;const i=[];let r=!1;try{for(let e=0;e<16;e++){const e=yield this.audioIterator.next();if(e.done){r=!0;break}i.push(e.value)}}catch(t){console.error("Audio iterator error:",t),r=!0}if(e!==this.asyncId||this.paused)return;i.length>0&&"suspended"===this.audioContext.state&&(yield this.audioContext.resume(),this.events.emit("canplay"),this.events.emit("playing"));for(const{buffer:e,timestamp:t}of i){const i=this.audioContext.createBufferSource();i.buffer=e,i.connect(this.gainNode),i.playbackRate.value=this.playbackRate;const r=this.audioContextStartTime+(t-this.playbackTimeAtStart)/this.playbackRate,n=(r+e.duration/this.playbackRate-this.audioContextStartTime)*this.playbackRate+this.playbackTimeAtStart;n>this.latestScheduledEndTime&&(this.latestScheduledEndTime=n),r>=this.audioContext.currentTime?i.start(r):i.start(this.audioContext.currentTime,(this.audioContext.currentTime-r)*this.playbackRate),this.queuedNodes.add(i),i.onended=()=>this.queuedNodes.delete(i)}if(r)break;yield new Promise(e=>setTimeout(e,0));const n=1;for(;this.latestScheduledEndTime-this.currentTime>n;){if(e!==this.asyncId||this.paused)return;yield new Promise(e=>setTimeout(e,50))}}})}play(){return y(this,null,function*(){if(!this.paused)return;this.audioContext||this.ensureAudioContext(),"suspended"===this.audioContext.state&&(yield this.audioContext.resume()),this.audioContextStartTime=this.audioContext.currentTime,this.latestScheduledEndTime=this.playbackTimeAtStart,this.paused=!1;const e=++this.asyncId;this.runIterator(e)})}pause(){this.paused||(this.playbackTimeAtStart=this.currentTime,this.paused=!0,this.stopIterator(),this.stopQueuedNodes())}seek(e){return y(this,null,function*(){this.playbackTimeAtStart=Math.max(0,e),this.audioContextStartTime=this.audioContext.currentTime,this.latestScheduledEndTime=this.playbackTimeAtStart;const t=++this.asyncId;this.paused||this.runIterator(t)})}setVolume(e,t){this.volume=e,this.muted=t,this.updateGain()}setPlaybackRate(e){if(e!==this.playbackRate&&(this.paused||(this.playbackTimeAtStart=this.currentTime,this.audioContextStartTime=this.audioContext.currentTime),this.playbackRate=e,!this.paused)){const e=++this.asyncId;this.runIterator(e)}}destroy(){var e;this.asyncId++,this.pause(),null==(e=this.audioContext)||e.close(),this.audioContext=null,this.input=null,this.audioSink=null}}function pl(e){return y(this,null,function*(){var t,i;return null!=(i=null!=(t=yield e.getAverageBitrate())?t:yield e.getBitrate())?i:0})}const gl=/\.m3u8(?:$|[?#])/i;function kl(e){return"string"===typeof e&&gl.test(e)}function yl(e){const t=function(e){return"string"===typeof e?new Bs(e):e instanceof Blob?new Ps(e):"undefined"!==typeof ReadableStream&&e instanceof ReadableStream?new Rs(e):null!=e?e:null}(e);return t?new Fo({source:t,formats:kl(e)?ya:ka}):null}class bl{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 Tl(e,t,i){for(const r of i){if(!t())return;e.emit(r)}}function vl(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 Sl(){let e,t;return{promise:new Promise((i,r)=>{e=i,t=r}),resolve:e,reject:t}}class wl{constructor(e){this.host=e,this.wanted=!1,this.playing=null,this.seeking=null,this.audioStart=null}operation(){return f(h({},Sl()),{source:this.host.loadSeq,complete:Sl()})}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}startAudio(){return y(this,null,function*(){this.audioStart||(this.audioStart=this.host.audio.play());const e=this.audioStart;try{yield e}finally{this.audioStart===e&&(this.audioStart=null)}})}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.startAudio(),!t())return void(this.wanted&&!this.host.destroyed||this.host.audio.pause());this.host.video.start(this.host.audio),Tl(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 vl(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,Tl(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(),Tl(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())})}}class Pl{constructor({canvas:e,ctx:t,events:i,timeupdateInterval:r=250,avSyncTolerance:n=.12,dropLateFrames:s=!1,poster:a="",preflightRange:o=!1}){this.canvas=e,this.ctx=t,this.events=i,this.timeupdateInterval=r,this.avSyncTolerance=n,this.dropLateFrames=s,this.poster=a,this.preflightRange=o,this.input=null,this.videoSink=null,this.videoIterator=null,this.nextFrame=null,this.rafId=0,this.asyncId=0,this.width=0,this.height=0,this.duration=Number.NaN,this.audioClock=null,this.lastTimeUpdate=0,this.stalled=!1,this.playbackRate=1,this.posterDrawn=!1,this.isFetching=!1}preflight(e,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||kl(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(!this.poster||this.posterDrawn)return;const e=new Image;e.onload=()=>{this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.canvas.width=e.naturalWidth||this.canvas.width,this.canvas.height=e.naturalHeight||this.canvas.height,this.ctx.drawImage(e,0,0,this.canvas.width,this.canvas.height),this.posterDrawn=!0},e.src=this.poster}stopIterator(){return y(this,null,function*(){var e;yield null==(e=this.videoIterator)?void 0:e.return(),this.videoIterator=null})}clear(){this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height)}load(e,t){return y(this,null,function*(){++this.asyncId,yield this.stopIterator(),this.clear(),this.posterDrawn=!1;const{input:i,videoTrack:r,duration:n}=e;if(this.input=i,this.duration=n,!r)return this.handleNoVideoTrack(),void(null==t||t());if(null===r.codec||!(yield r.canDecode()))return this.handleNoVideoTrack(),void(null==t||t());const s=yield r.canBeTransparent();this.videoSink=new fo(r,{poolSize:2,fit:"contain",alpha:s}),this.width=r.displayWidth,this.height=r.displayHeight,this.canvas.width=this.width,this.canvas.height=this.height,null==t||t(),yield this.resetIterator(0)})}handleNoVideoTrack(){this.videoSink=null,this.width=0,this.height=0,this.canvas.width=0,this.canvas.height=0,this.clear(),this.drawPoster()}resetIterator(e){return y(this,null,function*(){var t,i;if(yield this.stopIterator(),!this.videoSink)return;this.videoIterator=this.videoSink.canvases(e);const r=null!=(t=(yield this.videoIterator.next()).value)?t:null,n=null!=(i=(yield this.videoIterator.next()).value)?i:null;this.nextFrame=n,r?this.ctx.drawImage(r.canvas,0,0):this.drawPoster()})}updateNextFrame(e){return y(this,null,function*(){var t;if(this.videoIterator&&!this.isFetching){this.isFetching=!0;try{for(;;){const i=null!=(t=(yield this.videoIterator.next()).value)?t:null;if(!i||e!==this.asyncId)return;const r=this.audioClock.currentTime,n=this.dropLateFrames?Math.max(.06,this.avSyncTolerance/Math.max(1,this.playbackRate)):0;if(!(this.dropLateFrames&&i.timestampr)return void(this.nextFrame=null)}}}finally{this.isFetching=!1}}})}render(){if(!this.audioClock)return;const e=this.audioClock.currentTime,t=Date.now();if(t-this.lastTimeUpdate>=this.timeupdateInterval&&(this.events.emit("timeupdate"),this.lastTimeUpdate=t),Number.isFinite(this.duration)&&e>=this.duration)return this.stop(),this.stalled=!1,this.events.emit("ended"),this.events.emit("pause"),void this.events.emit("canplay");this.nextFrame&&this.nextFrame.timestamp<=e?(this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.ctx.drawImage(this.nextFrame.canvas,0,0),this.nextFrame=null,this.updateNextFrame(this.asyncId),this.stalled&&(this.events.emit("canplay"),this.events.emit("playing"),this.stalled=!1)):this.nextFrame||(this.updateNextFrame(this.asyncId),!this.nextFrame&&Number.isFinite(this.duration)&&ethis.render())}start(e){this.audioClock=e,this.asyncId++,this.stalled=!1,this.updateNextFrame(this.asyncId),this.rafId=requestAnimationFrame(()=>this.render())}stop(){cancelAnimationFrame(this.rafId)}seek(e){return y(this,null,function*(){this.asyncId++,yield this.resetIterator(e)})}setPlaybackRate(e){this.playbackRate=Math.max(.1,Number(e)||1)}destroy(){this.asyncId++,this.stop(),this.stopIterator(),this.posterDrawn=!1,this.videoSink=null,this.input=null}}class Il{constructor({canvas:e,ctx:i,events:r,option:n={}}){var s,a,o,l,c;g(this,t),this.events=r,this.option=n,this.audio=new ml(r),this.video=new Pl({canvas:e,ctx:i,events:r,timeupdateInterval:null!=(s=n.timeupdateInterval)?s:250,avSyncTolerance:null!=(a=n.avSyncTolerance)?a:.12,dropLateFrames:null!=(o=n.dropLateFrames)&&o,poster:null!=(l=n.poster)?l:"",preflightRange:null!=(c=n.preflightRange)&&c}),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,k(this,t,new wl(this)),r.addEventListener("ended",()=>{this.destroyed||(this.ended=!0,this.paused=!0,p(this,t).ended())})}load(e){return y(this,null,function*(){var i,r;if(this.destroyed)return;const n=++this.loadSeq;if(p(this,t).invalidate(),null==(i=this.loadSession)||i.cancel(),n!==this.loadSeq||this.destroyed)return;if(this.pause(),n!==this.loadSeq||this.destroyed)return;this.disposeInput();const s=new bl;this.loadSession=s,this.ended=!1,this.error=null,this.networkState=2,this.readyState=0,s.defer(()=>this.events.emit("waiting")),s.defer(()=>this.events.emit("loadstart"));const a=Number.isFinite(this.option.loadTimeout)&&null!=(r=this.option.loadTimeout)?r:0;try{yield s.wait(this.performLoad(e,n,s),a)}catch(o){if(n!==this.loadSeq)return;const e=++this.loadSeq;if(p(this,t).invalidate(),s.cancel(),e!==this.loadSeq||this.destroyed)return;this.disposeInput(),this.reportError(o)}})}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=yl(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 vl({input:e,videoTrack:i,audioTrack:r}),s=i||r,a=kl(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,Tl(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,Tl(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 p(this,t).replace(h(h({},this.media),e),this.currentTime)})}selectHlsQuality(e){return y(this,null,function*(){return function(e,t){return y(this,null,function*(){var i;const{input:r,media:n,loadSeq:s}=e;if(!(null==n?void 0:n.isHls)||!r||e.destroyed)return;const a=()=>!e.destroyed&&e.loadSeq===s&&e.input===r&&e.media===n;let o;try{const e=yield r.getVideoTracks();if(!a())return;const s="auto"===t?yield r.getPrimaryVideoTrack():null!=(i=e.find(e=>e.id===t))?i:n.videoTrack;if(!a()||!s)return;let l=n.audioTrack,c=n.audioMode;l&&s.canBePairedWith(l)||(l=yield s.getPrimaryPairableAudioTrack(),c="auto"),o={videoTrack:s,audioTrack:l,videoMode:"auto"===t?"auto":"manual",audioMode:c}}catch(l){if(!a())return;throw l}a()&&(yield e.replaceTracks(o))})}(this,e)})}selectHlsAudio(e){return y(this,null,function*(){return function(e,t){return y(this,null,function*(){var i;const{input:r,media:n,loadSeq:s}=e;if(!(null==n?void 0:n.isHls)||!r||e.destroyed)return;const a=()=>!e.destroyed&&e.loadSeq===s&&e.input===r&&e.media===n;let o;try{const e=yield r.getAudioTracks();if(!a())return;const s="auto"===t?n.videoTrack?yield n.videoTrack.getPrimaryPairableAudioTrack():yield r.getPrimaryAudioTrack():null!=(i=e.find(e=>e.id===t))?i:n.audioTrack;if(!a()||!s)return;let l=n.videoTrack,c=n.videoMode;l&&s.canBePairedWith(l)||(l=yield s.getPrimaryPairableVideoTrack(),c="auto"),o={videoTrack:l,audioTrack:s,videoMode:c,audioMode:"auto"===t?"auto":"manual"}}catch(l){if(!a())return;throw l}a()&&(yield e.replaceTracks(o))})}(this,e)})}getHlsState(){return y(this,null,function*(){const e=this.media;if(this.destroyed)return null;try{const t=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 pl(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 pl(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.media!==e?null:t}catch(t){if(this.destroyed||this.media!==e)return null;throw t}})}play(){return y(this,null,function*(){return p(this,t).play()})}pause(){p(this,t).pause()}seek(e){return y(this,null,function*(){return p(this,t).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++,p(this,t).invalidate();const e=[];for(const t of[()=>{var e;return null==(e=this.loadSession)?void 0:e.cancel()},()=>this.pause(),()=>this.disposeInput(),()=>this.audio.destroy(),()=>this.video.destroy()])try{t()}catch(i){e.push(i)}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}}t=new WeakMap;const xl=new WeakMap;function Cl(e){let t=xl.get(e);return t||(t={closed:!1,frames:new Set},xl.set(e,t)),t}class Bl{constructor({art:e,canvas:t,ctx:i,option:r}){var n,s;this.art=e,this.canvas=t,this.option=r,this.events=new P,this.engine=new Il({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=Cl(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){Cl(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=Cl(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 Bl({art:t,canvas:n,ctx:s,option:e});t.mediabunny=a;const o={};for(const e in n)"function"===typeof n[e]&&(o[e]=n[e].bind(n));const l=new Set([...Object.getOwnPropertyNames(a),...Object.getOwnPropertyNames(Object.getPrototypeOf(a))]);for(const e of l)"constructor"!==e&&(e in n||Object.defineProperty(n,e,{get(){const t=a[e];return"function"===typeof t?t.bind(a):t},set(t){a[e]=t},configurable:!0,enumerable:!0}));for(const e in o)n[e]=(...t)=>o[e](...t);function c(){var e;(null==(e=t.template)?void 0:e.$player)&&!t.option.autoSize&&Object.assign(n.style,{width:"100%",height:"100%",objectFit:"contain"})}return t.on("resize",c),t.on("video:loadedmetadata",c),function({art:e,shim:t,option:i}){if(i.m3u8)return e.on("video:loadedmetadata",u),e.on("restart",u),{update:u};function r(t){e.controls.cache.has(t)&&e.controls.remove(t)}function n(t){e.setting.find(t)&&e.setting.remove(t)}function s(){r("mediabunny-quality"),n("mediabunny-quality")}function a(){r("mediabunny-audio"),n("mediabunny-audio")}function o(e={}){return e.control||e.setting}function l(r){return y(this,null,function*(){var n;const a=(null==(n=i.m3u8)?void 0:n.quality)||{};if(!o(a)||!(null==r?void 0:r.levels.length))return void s();const l=a.auto||"Auto",c=a.title||"Quality",d=a.getName||(e=>e.name||`${e.height}P`),h=r.currentLevel?d(r.currentLevel):l,f=w(r.levels.map(e=>{var t;return{html:d(e),value:e.id,default:(null==(t=r.currentLevel)?void 0:t.id)===e.id}}),"html").sort((e,t)=>{const i=r.levels.find(t=>t.id===e.value),n=r.levels.find(e=>e.id===t.value);return((null==n?void 0:n.height)||0)-((null==i?void 0:i.height)||0)});f.push({html:l,value:"auto",default:!r.currentLevel});const m=i=>y(null,null,function*(){return yield t.switchM3u8Quality(i.value),e.notice.show=`${c}: ${i.html}`,yield u(),i.html});a.control&&e.controls.update({name:"mediabunny-quality",position:"right",html:h,style:{padding:"0 10px"},selector:f,onSelect:m}),a.setting&&e.setting.update({name:"mediabunny-quality",tooltip:h,html:c,icon:'',width:200,selector:f,onSelect:m})})}function c(r){return y(this,null,function*(){var n;const s=(null==(n=i.m3u8)?void 0:n.audio)||{};if(!o(s)||!(null==r?void 0:r.audios.length)||r.audios.length<2)return void a();const l=s.auto||"Auto",c=s.title||"Audio",d=s.getName||(e=>e.name||e.lang||e.language),h=r.currentAudio?d(r.currentAudio):l,f=w(r.audios.map(e=>{var t;return{html:d(e),value:e.id,default:(null==(t=r.currentAudio)?void 0:t.id)===e.id}}),"html");f.push({html:l,value:"auto",default:!r.currentAudio});const m=i=>y(null,null,function*(){return yield t.switchM3u8Audio(i.value),e.notice.show=`${c}: ${i.html}`,yield u(),i.html});s.control&&e.controls.update({name:"mediabunny-audio",position:"right",html:h,style:{padding:"0 10px"},selector:f,onSelect:m}),s.setting&&e.setting.update({name:"mediabunny-audio",tooltip:h,html:c,icon:'',width:200,selector:f,onSelect:m})})}function u(){return y(this,null,function*(){const e=yield t.getM3u8State();if(!e)return s(),void a();yield Promise.all([l(e),c(e)])})}}({art:t,shim:a,option:e}),t.on("destroy",()=>{delete t.mediabunny,a.destroy()}),n}}}); diff --git a/docs/compiled/artplayer-proxy-mediabunny.mjs b/docs/compiled/artplayer-proxy-mediabunny.mjs index bc85640b8..ab7fa87c5 100644 --- a/docs/compiled/artplayer-proxy-mediabunny.mjs +++ b/docs/compiled/artplayer-proxy-mediabunny.mjs @@ -11,7 +11,7 @@ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj)); var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value); var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value); -var _closed; +var _closed, _playback; const $audio = ''; const $quality = ''; function uniqBy(array, property) { @@ -24271,6 +24271,62 @@ class AudioEngine { this.audioSink = null; } } +async function selectQuality(host, value) { + const { input, media, loadSeq } = host; + if (!media?.isHls || !input || host.destroyed) + return; + const current = () => !host.destroyed && host.loadSeq === loadSeq && host.input === input && host.media === media; + let selection; + try { + const tracks = await input.getVideoTracks(); + if (!current()) + return; + const videoTrack = value === "auto" ? await input.getPrimaryVideoTrack() : tracks.find((track) => track.id === value) ?? media.videoTrack; + if (!current() || !videoTrack) + return; + let audioTrack = media.audioTrack; + let audioMode = media.audioMode; + if (!audioTrack || !videoTrack.canBePairedWith(audioTrack)) { + audioTrack = await videoTrack.getPrimaryPairableAudioTrack(); + audioMode = "auto"; + } + selection = { videoTrack, audioTrack, videoMode: value === "auto" ? "auto" : "manual", audioMode }; + } catch (error) { + if (!current()) + return; + throw error; + } + if (current()) + await host.replaceTracks(selection); +} +async function selectAudio(host, value) { + const { input, media, loadSeq } = host; + if (!media?.isHls || !input || host.destroyed) + return; + const current = () => !host.destroyed && host.loadSeq === loadSeq && host.input === input && host.media === media; + let selection; + try { + const tracks = await input.getAudioTracks(); + if (!current()) + return; + const audioTrack = value === "auto" ? media.videoTrack ? await media.videoTrack.getPrimaryPairableAudioTrack() : await input.getPrimaryAudioTrack() : tracks.find((track) => track.id === value) ?? media.audioTrack; + if (!current() || !audioTrack) + return; + let videoTrack = media.videoTrack; + let videoMode = media.videoMode; + if (!videoTrack || !audioTrack.canBePairedWith(videoTrack)) { + videoTrack = await audioTrack.getPrimaryPairableVideoTrack(); + videoMode = "auto"; + } + selection = { videoTrack, audioTrack, videoMode, audioMode: value === "auto" ? "auto" : "manual" }; + } catch (error) { + if (!current()) + return; + throw error; + } + if (current()) + await host.replaceTracks(selection); +} async function getTrackBitrate(track) { return await track.getAverageBitrate() ?? await track.getBitrate() ?? 0; } @@ -24404,6 +24460,30 @@ class LoadSession { this.disposeInput(); } } +function publish(events, current, names) { + for (const name of names) { + if (!current()) + return; + events.emit(name); + } +} +function metadataBarrier(ready, current) { + let video = false; + let audio = false; + let published = false; + function complete(part) { + if (!current() || published) + return; + if (part === "video") + video = true; + else audio = true; + if (video && audio) { + published = true; + ready(); + } + } + return { video: () => complete("video"), audio: () => complete("audio") }; +} async function resolveDuration({ input, videoTrack, audioTrack }) { const tracks = [videoTrack, audioTrack].filter((track) => track !== null); const referenceTrack = videoTrack || audioTrack; @@ -24433,6 +24513,212 @@ async function selectPlaybackTracks(input, src) { audioMode: isHls ? "auto" : "manual" }; } +function completion() { + let resolve; + let reject; + const promise = new Promise((yes, no) => { + resolve = yes; + reject = no; + }); + return { promise, resolve, reject }; +} +class Playback { + constructor(host) { + this.host = host; + this.wanted = false; + this.playing = null; + this.seeking = null; + this.audioStart = null; + } + operation() { + return { ...completion(), source: this.host.loadSeq, complete: completion() }; + } + current(operation, kind) { + return !this.host.destroyed && operation.source === this.host.loadSeq && this[kind] === operation; + } + cancelPlay() { + const previous = this.playing; + this.playing = null; + previous?.resolve(); + } + invalidate() { + this.cancelPlay(); + this.wanted = false; + const previous = this.seeking; + this.seeking = null; + previous?.complete.resolve(); + previous?.resolve(); + this.host.seeking = false; + } + ended() { + this.wanted = false; + this.cancelPlay(); + } + stop() { + if (this.host.paused) + return; + this.host.paused = true; + this.stopEngines(); + this.host.events.emit("pause"); + } + stopEngines() { + const failures = []; + for (const stop of [() => this.host.audio.pause(), () => this.host.video.stop()]) { + try { + stop(); + } catch (error) { + failures.push(error); + } + } + if (failures.length) + throw failures[0]; + } + pause() { + this.wanted = false; + this.cancelPlay(); + this.stop(); + } + play() { + if (this.host.destroyed) + return Promise.resolve(); + this.wanted = true; + if (this.playing) + return this.playing.promise; + if (this.host.ended) + return this.seek(0, true); + if (!this.host.paused && !this.seeking) + return Promise.resolve(); + const operation = this.operation(); + this.playing = operation; + this.runPlay(operation).then(operation.resolve, operation.reject); + return operation.promise; + } + async startAudio() { + if (!this.audioStart) + this.audioStart = this.host.audio.play(); + const pending = this.audioStart; + try { + await pending; + } finally { + if (this.audioStart === pending) + this.audioStart = null; + } + } + async runPlay(operation) { + const current = () => this.current(operation, "playing") && this.wanted; + try { + while (this.seeking) { + await this.seeking.complete.promise; + if (!current()) + return; + } + if (!current()) + return; + this.host.paused = false; + await this.startAudio(); + if (!current()) { + if (!this.wanted || this.host.destroyed) + this.host.audio.pause(); + return; + } + this.host.video.start(this.host.audio); + publish(this.host.events, current, ["play", "playing"]); + } catch (error) { + if (!current()) + return; + this.wanted = false; + this.host.paused = true; + try { + this.stopEngines(); + } catch (failure) { + console.warn("MediaBunny play cleanup error:", failure); + } + throw error; + } finally { + if (this.playing === operation) + this.playing = null; + } + } + seek(time, resume) { + return this.position(async (current) => { + const audio = this.host.audio.seek(time); + const video = current() ? this.host.video.seek(time) : Promise.resolve(); + await Promise.all([audio, video]); + }, ["seeked"], false, resume); + } + replace(media, time) { + return this.position(async (current) => { + media.duration = await resolveDuration(media); + if (!current()) + return; + this.host.media = media; + await Promise.all([this.host.video.load(media), this.host.audio.load(media)]); + if (!current()) + return; + await Promise.all([this.host.video.seek(time), this.host.audio.seek(time)]); + if (current()) { + this.host.readyState = 4; + this.host.networkState = 1; + } + }, ["loadedmetadata", "durationchange", "progress", "loadeddata", "canplay", "canplaythrough", "seeked"], true); + } + position(work, events, pauseFirst, resume) { + if (this.host.destroyed) + return Promise.resolve(); + this.wanted = resume ?? (this.seeking ? this.wanted : !this.host.paused); + this.cancelPlay(); + const previous = this.seeking; + const operation = this.operation(); + this.seeking = operation; + previous?.complete.resolve(); + previous?.resolve(); + this.runPosition(operation, work, events, pauseFirst).then(operation.resolve, operation.reject); + return operation.promise; + } + async runPosition(operation, work, events, pauseFirst) { + const current = () => this.current(operation, "seeking"); + let resume = false; + try { + if (pauseFirst) + this.stop(); + if (!current()) + return; + this.host.ended = false; + this.host.seeking = true; + publish(this.host.events, current, ["seeking", "waiting"]); + if (!current()) + return; + if (!pauseFirst) + this.stop(); + if (!current()) + return; + await work(current); + if (!current()) + return; + this.host.seeking = false; + operation.complete.resolve(); + publish(this.host.events, current, events); + if (!current()) + return; + this.seeking = null; + resume = this.wanted; + } catch (error) { + if (!current()) + return; + this.host.seeking = false; + this.wanted = false; + this.cancelPlay(); + this.host.reportError(error); + throw error; + } finally { + operation.complete.resolve(); + if (this.seeking === operation) + this.seeking = null; + } + if (resume) + await this.play(); + } +} async function preflightRange(url, enabled, events, signal, isCurrent = () => true) { if (signal?.aborted || !isCurrent()) return false; @@ -24661,6 +24947,7 @@ class VideoEngine { } class MediaBunnyEngine { constructor({ canvas, ctx, events, option = {} }) { + __privateAdd(this, _playback); this.events = events; this.option = option; this.audio = new AudioEngine(events); @@ -24685,15 +24972,20 @@ class MediaBunnyEngine { this.media = null; this.loadSession = null; this.destroyed = false; - events.addEventListener?.("ended", () => { + __privateSet(this, _playback, new Playback(this)); + events.addEventListener("ended", () => { + if (this.destroyed) + return; this.ended = true; this.paused = true; + __privateGet(this, _playback).ended(); }); } async load(src) { if (this.destroyed) return; const id = ++this.loadSeq; + __privateGet(this, _playback).invalidate(); this.loadSession?.cancel(); if (id !== this.loadSeq || this.destroyed) return; @@ -24709,75 +25001,62 @@ class MediaBunnyEngine { this.readyState = 0; session.defer(() => this.events.emit("waiting")); session.defer(() => this.events.emit("loadstart")); - const loadTimeout = Number.isFinite(this.option.loadTimeout) ? this.option.loadTimeout : 0; + const timeout = Number.isFinite(this.option.loadTimeout) ? this.option.loadTimeout ?? 0 : 0; try { - await session.wait(this.performLoad(src, id, session), loadTimeout); - } catch (err) { + await session.wait(this.performLoad(src, id, session), timeout); + } catch (error) { if (id !== this.loadSeq) return; const failed = ++this.loadSeq; + __privateGet(this, _playback).invalidate(); session.cancel(); if (failed !== this.loadSeq || this.destroyed) return; this.disposeInput(); - this.error = { code: 4, message: err.message }; - this.networkState = 3; - this.events.emit("error"); + this.reportError(error); } } async performLoad(src, id, session = this.loadSession) { - if (!await this.video.preflight(src, session?.signal, () => id === this.loadSeq) || id !== this.loadSeq) + const current = () => !this.destroyed && id === this.loadSeq; + if (!session || !await this.video.preflight(src, session.signal, current) || !current()) return; const input = createInput(src); if (!input) { this.video.handleNoVideoTrack(); - this.audio.handleNoAudioTrack(); + if (current()) + this.audio.handleNoAudioTrack(); return; } session.own(input); const media = await selectPlaybackTracks(input, src); - if (id !== this.loadSeq) + if (!current()) return; + if (!media.videoTrack && !media.audioTrack) { + this.video.handleNoVideoTrack(); + this.video.duration = Number.NaN; + this.audio.duration = Number.NaN; + throw new Error("Input has no audio or video tracks."); + } this.input = input; this.media = media; - let videoMetadataLoaded = !media.videoTrack; - let audioMetadataLoaded = !media.audioTrack; - const checkMetadata = () => { - if (videoMetadataLoaded && audioMetadataLoaded) { - this.readyState = 1; - this.events.emit("loadedmetadata"); - this.events.emit("durationchange"); - this.events.emit("progress"); - } - }; + const metadata = metadataBarrier(() => { + this.readyState = 1; + publish(this.events, current, ["loadedmetadata", "durationchange", "progress"]); + }, current); try { - await Promise.all([ - this.video.load(media, () => { - if (id !== this.loadSeq) - return; - videoMetadataLoaded = true; - checkMetadata(); - }), - this.audio.load(media, () => { - if (id !== this.loadSeq) - return; - audioMetadataLoaded = true; - checkMetadata(); - }) - ]); - if (id !== this.loadSeq) + const video = this.video.load(media, metadata.video); + const audio = current() ? this.audio.load(media, metadata.audio) : Promise.resolve(); + await Promise.all([video, audio]); + if (!current()) return; this.readyState = 4; this.networkState = 1; - this.events.emit("loadeddata"); - this.events.emit("canplay"); - this.events.emit("canplaythrough"); - this.events.emit("progress"); - } catch (err) { - if (id !== this.loadSeq) + publish(this.events, current, ["loadeddata", "canplay", "canplaythrough", "progress"]); + } catch (error) { + if (!current()) return; - console.error("MediaBunny load error:", err); - throw err; + console.error("MediaBunny load error:", error); + throw error; } } createTimeout(ms) { @@ -24790,127 +25069,38 @@ class MediaBunnyEngine { this.input = null; this.media = null; } - async replaceTracks({ videoTrack, audioTrack, videoMode, audioMode }) { - if (!this.media) + async replaceTracks(tracks) { + if (!this.media || this.destroyed) return; - const nextMedia = { - ...this.media, - videoTrack, - audioTrack, - videoMode, - audioMode - }; - const shouldResume = !this.paused; - const currentTime = this.currentTime; - this.pause(); - this.ended = false; - this.seeking = true; - this.events.emit("seeking"); - this.events.emit("waiting"); - nextMedia.duration = await resolveDuration(nextMedia); - this.media = nextMedia; - await Promise.all([ - this.video.load(nextMedia), - this.audio.load(nextMedia) - ]); - await Promise.all([ - this.video.seek(currentTime), - this.audio.seek(currentTime) - ]); - this.readyState = 4; - this.networkState = 1; - this.seeking = false; - this.events.emit("loadedmetadata"); - this.events.emit("durationchange"); - this.events.emit("progress"); - this.events.emit("loadeddata"); - this.events.emit("canplay"); - this.events.emit("canplaythrough"); - this.events.emit("seeked"); - if (shouldResume) { - await this.play(); - } + return __privateGet(this, _playback).replace({ ...this.media, ...tracks }, this.currentTime); } async selectHlsQuality(value) { - if (!this.media?.isHls || !this.input) - return; - const videoTracks = await this.input.getVideoTracks(); - const videoTrack = value === "auto" ? await this.input.getPrimaryVideoTrack() : videoTracks.find((track) => track.id === value) ?? this.media.videoTrack; - if (!videoTrack) - return; - let audioTrack = this.media.audioTrack; - let audioMode = this.media.audioMode; - if (!audioTrack || !videoTrack.canBePairedWith(audioTrack)) { - audioTrack = await videoTrack.getPrimaryPairableAudioTrack(); - audioMode = "auto"; - } - await this.replaceTracks({ - videoTrack, - audioTrack, - videoMode: value === "auto" ? "auto" : "manual", - audioMode - }); + return selectQuality(this, value); } async selectHlsAudio(value) { - if (!this.media?.isHls || !this.input) - return; - const audioTracks = await this.input.getAudioTracks(); - const audioTrack = value === "auto" ? this.media.videoTrack ? await this.media.videoTrack.getPrimaryPairableAudioTrack() : await this.input.getPrimaryAudioTrack() : audioTracks.find((track) => track.id === value) ?? this.media.audioTrack; - if (!audioTrack) - return; - let videoTrack = this.media.videoTrack; - let videoMode = this.media.videoMode; - if (!videoTrack || !audioTrack.canBePairedWith(videoTrack)) { - videoTrack = await audioTrack.getPrimaryPairableVideoTrack(); - videoMode = "auto"; - } - await this.replaceTracks({ - videoTrack, - audioTrack, - videoMode, - audioMode: value === "auto" ? "auto" : "manual" - }); + return selectAudio(this, value); } - getHlsState() { - return getHlsState(this.media); + async getHlsState() { + const media = this.media; + if (this.destroyed) + return null; + try { + const state2 = await getHlsState(media); + return !this.destroyed && this.media === media ? state2 : null; + } catch (error) { + if (this.destroyed || this.media !== media) + return null; + throw error; + } } async play() { - if (!this.paused) - return; - if (this.ended) { - this.ended = false; - await this.seek(0); - } - this.paused = false; - await this.audio.play(); - this.video.start(this.audio); - this.events.emit("play"); - this.events.emit("playing"); + return __privateGet(this, _playback).play(); } pause() { - if (this.paused) - return; - this.paused = true; - this.audio.pause(); - this.video.stop(); - this.events.emit("pause"); + __privateGet(this, _playback).pause(); } async seek(time) { - const shouldResume = !this.paused; - this.ended = false; - this.seeking = true; - this.events.emit("seeking"); - this.events.emit("waiting"); - this.pause(); - await Promise.all([ - this.audio.seek(time), - this.video.seek(time) - ]); - this.seeking = false; - this.events.emit("seeked"); - if (shouldResume && !this.ended) { - await this.play(); - } + return __privateGet(this, _playback).seek(time); } setVolume(volume, muted) { this.audio.setVolume(volume, muted); @@ -24919,18 +25109,31 @@ class MediaBunnyEngine { this.audio.setPlaybackRate(rate); this.video.setPlaybackRate(rate); } + reportError(error) { + if (this.destroyed) + return; + const message = error && typeof error === "object" ? Reflect.get(error, "message") : void 0; + this.error = { code: 4, message: typeof message === "string" ? message : String(error) }; + this.networkState = 3; + this.events.emit("error"); + } destroy() { if (this.destroyed) return; this.destroyed = true; this.loadSeq++; - this.loadSession?.cancel(); - this.pause(); - this.disposeInput(); - this.audio.destroy(); - this.video.destroy(); + __privateGet(this, _playback).invalidate(); + const failures = []; + for (const release of [() => this.loadSession?.cancel(), () => this.pause(), () => this.disposeInput(), () => this.audio.destroy(), () => this.video.destroy()]) { + try { + release(); + } catch (error) { + failures.push(error); + } + } + if (failures.length) + throw failures[0]; } - // Getters get currentTime() { return this.audio.currentTime; } @@ -24944,6 +25147,7 @@ class MediaBunnyEngine { return this.video.height; } } +_playback = new WeakMap(); const states = /* @__PURE__ */ new WeakMap(); function state(owner) { let value = states.get(owner); @@ -25049,7 +25253,8 @@ class VideoShim { return this.engine.currentTime; } set currentTime(t) { - this.engine.seek(Number(t) || 0); + void Promise.resolve(this.engine.seek(Number(t) || 0)).catch(() => { + }); } get duration() { return this.engine.duration; diff --git a/package.json b/package.json index 4b996bb3b..1f67dcf71 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-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-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,7 @@ "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-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-load.test.js test/mediabunny-input.test.js" }, "browserslist": "last 1 Chrome version", "devDependencies": { diff --git a/packages/artplayer-proxy-mediabunny/ARCHITECTURE.md b/packages/artplayer-proxy-mediabunny/ARCHITECTURE.md index 00c011a3f..51133a204 100644 --- a/packages/artplayer-proxy-mediabunny/ARCHITECTURE.md +++ b/packages/artplayer-proxy-mediabunny/ARCHITECTURE.md @@ -15,19 +15,22 @@ declarations, the factory signature, canvas forwarding, or package entrypoints. | `hls-state.ts` | HLS track snapshots, bitrate/name/language values and actual selected track identity | | `preflight.ts` | Optional HEAD Range check, historical warning/error policy, cancellation and stale-result guard | | `load-session.ts` | Ownership of the pending/active SDK Input, HEAD AbortController, deferred load events and deadline | -| `MediaBunnyEngine.js` | Current coordinator; connects session cancellation to load, source replacement, errors and destroy | +| `MediaBunnyEngine.ts` | Load/readiness coordinator, source identity, errors and terminal teardown | +| `playback.ts` | Playback intent, cancellable play/seek/replacement operations and shared pending audio resume | +| `readiness.ts` | One metadata publication after both participants, guarded event sequences | +| `hls-selection.ts` | Source-bound track queries, pairing and active replacement errors | | `VideoEngine.js` / `AudioEngine.js` | Current native decoding, rendering, seeking, Web Audio clock and scheduling | | `VideoShim.ts` / `EventTarget.ts` | Video-like descriptors, synchronous/Promise forwarding and owned event lifecycle | | `shim-values.ts` | Existing volume coercion and synthetic TimeRanges values | | `shim-frames.ts` | Synthetic frame callbacks, per-instance RAF ownership and terminal cleanup | -| `engine-types.ts` / `MediaBunnyEngine.d.ts` | Explicit temporary coordinator boundary while its JavaScript implementation is migrated in MB-04 | +| `engine-types.ts` / `engine-ports.ts` | Internal shim, coordinator and decoder interfaces | +| `AudioEngine.d.ts` / `VideoEngine.d.ts` | Temporary boundaries for JS decoders, removed in MB-06/05 | | `m3u8.js` | Current ArtPlayer control/setting integration | -The eleven TypeScript modules use strict checking with `skipLibCheck: false` and no -ambient Node types. The adjacent coordinator declaration is a transitional boundary, -not proof that the JavaScript coordinator has been checked. Replace it with the actual -strict implementation before completing MB-04. Remaining JavaScript is explicitly -scheduled in PKG-MB-04/05/06/07/08. +The sixteen production TypeScript modules use strict checking with `skipLibCheck: false` +and no ambient Node types. The coordinator is an actual checked implementation. The two +adjacent decoder declarations are temporary boundaries, not checking of their JavaScript +implementations. Remaining JavaScript is scheduled in PKG-MB-05/06/07/08. Do not describe the whole package as migrated yet. The shim keeps its existing own-property order and direct prototype surface because @@ -40,7 +43,8 @@ EventTarget retains duplicate listeners, first-match removal, live-array `forEac mutation semantics, detail identity and listener exceptions during normal dispatch. Its terminal state stops callbacks later in a dispatch when a listener destroys the shim. Shim teardown closes events in `finally`, even if engine cleanup throws, and -subsequent teardown is inert. Engine playback/readiness race fixes remain in progress. +subsequent teardown is inert. Engine teardown attempts input, audio and video cleanup +even when an earlier release throws, then preserves the first failure. ## Input and cancellation flow @@ -69,6 +73,32 @@ HLS matching preserves the old case-insensitive `.m3u8` suffix/query/hash rule. One explicit InputOptions assertion leaves unsupported values to SDK validation, preserving the old error owner rather than silently converting arbitrary inputs. +## Playback and readiness ownership + +Playback intent is separate from the temporary paused state during seek. Explicit pause +cancels pending play and prevents automatic resume; a newer seek settles the old operation +without allowing its completion or rejection to overwrite current state. Pending play waits +for the seek completion signal, resolved before optional resume to avoid a cycle. +A pending AudioContext resume is shared across play-pause-play; only the current operation +starts video and emits play/playing. Source change and destroy invalidate both operations. +Cancellation settles the public operation while observing the underlying late result; +actual late decoder work still belongs to MB-05/06. + +Normal play, pause, seek/resume and HLS replacement event order is retained. Before each +event the coordinator rechecks ownership, since a listener may synchronously pause, seek, +load another source or destroy. Active play errors reject their Promise and restore paused +state; active seek errors additionally publish one media error. The synchronous currentTime +setter observes its otherwise unreturnable rejection; direct engine.seek still rejects. +Active replacement errors remain visible even after the media object changes. Stale HLS query +errors are ignored only when their captured source no longer owns the result. + +Metadata publishes once after both audio/video participants report; repeated or obsolete +callbacks cannot ready the current source. A parsed container with neither track fails with +code 4 and message `Input has no audio or video tracks.` before decoder/AudioContext setup. +This corrects the old false-ready state; normal valid input event order is preserved. +Existing-track unsupported-codec handling remains a decoder capability task, not evidence +that every capability failure has been fixed. + ## Types and dependencies The locked runtime SDK remains MediaBunny 1.56.1. Its pinned WebCodecs declaration @@ -101,7 +131,7 @@ The source of historical truth is `refactor/baselines/mb-release.json` and its G inputs, not a rebuilt dist. Package-specific evidence and remaining tasks are in `refactor/mb-validation.md`. The full refactor plan is at the repository root. -PKG-MB-04 still owns duplicate/trackless readiness, reentrant event sequences and +PKG-MB-04 covers duplicate/trackless readiness, reentrant event sequences and pending play/seek coordination. PKG-MB-05/06 own late frame and audio callbacks, including operations already inside decoders at cancellation; releasing Input alone does not prove those resources are fully handled. PKG-MB-07 owns HLS UI/selection diff --git a/packages/artplayer-proxy-mediabunny/dist/artplayer-proxy-mediabunny.js b/packages/artplayer-proxy-mediabunny/dist/artplayer-proxy-mediabunny.js index e6fe6ae99..8aa19f7fa 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=e=>{throw TypeError(e)},i=(e,i,r)=>i.has(e)||t("Cannot "+r),r=(e,t,r)=>(i(e,t,"read from private field"),r?r.call(e):t.get(e));function a(e,t){const i=new Map;return e.filter(e=>{const r=e[t];return void 0===r||!i.has(r)&&i.set(r,1)})}class s{constructor(){var i,r,a;i=this,a=!1,(r=e).has(i)?t("Cannot add the same private member more than once"):r instanceof WeakSet?r.add(i):r.set(i,a),this.listeners=new Map}addEventListener(t,i){r(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(r(this,e))return;const a=Object.assign(new Event(t),{detail:i});this.listeners.get(t)?.forEach(t=>{r(this,e)||t(a)})}destroy(){var t,r,a,s;a=!0,i(t=this,r=e,"write to private field"),s?s.call(t,a):r.set(t,a),this.listeners.clear()}}function n(e){if(!e)throw new Error("Assertion failed.")}e=new WeakMap;const o=e=>{const t=(e%360+360)%360;if(0===t||90===t||180===t||270===t)return t;throw new Error(`Invalid rotation ${e}.`)},c=e=>e&&e[e.length-1],l=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)},d=e=>{const t=l(e);return 0===(1&t)?-(t>>1):t+1>>1},h=e=>e.constructor===Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),f=e=>e.constructor===DataView?e:ArrayBuffer.isView(e)?new DataView(e.buffer,e.byteOffset,e.byteLength):new DataView(e),m=new TextDecoder,p=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])),g={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},k=p(g),y={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},b=p(y),w={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},T=p(w),S=e=>!!e&&!!e.primaries&&!!e.transfer&&!!e.matrix&&void 0!==e.fullRange,v={primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0},P=e=>e instanceof ArrayBuffer||"undefined"!==typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e);class I{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 x=/^[0-9a-fA-F]+$/,C=e=>[...e].map(e=>e.toString(16).padStart(2,"0")).join(""),B=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,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},R=(e,t,i)=>{const r=_(e,i(t),i);e.splice(r+1,0,t)},F=()=>{let e,t;return{promise:new Promise((i,r)=>{e=i,t=r}),resolve:e,reject:t}},A=(e,t)=>{const i=e.indexOf(t);-1!==i&&e.splice(i,1)},D=(e,t)=>{for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},M=(e,t)=>{for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},N=e=>{throw new Error(`Unexpected value: ${e}`)},O=(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},L=(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)},z=(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}}),U=(e,t,i)=>Math.max(t,Math.min(i,e)),q="und",W=e=>{const t=Math.round(e);return Math.abs(e/t-1)<10*Number.EPSILON?t:e},H=(e,t)=>Math.round(e/t)*t,V=(e,t)=>Math.round(e*t)/t,j=(e,t)=>Math.floor(e/t)*t,K=e=>{let t=0;for(;0!==e;)e&=e-1,t++;return t},X=/^[a-z]{3}$/,$=e=>X.test(e),G=1e6*(1+Number.EPSILON),Q=(e,t)=>{const i={...e,...t};if(e.headers||t.headers){const r=e.headers?Y(e.headers):{},a=t.headers?Y(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},Y=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},J=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(ve._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 be(1e3*e),a())throw n}};class Z{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}let ee=null;const te=()=>null!==ee?ee:ee=!("undefined"===typeof navigator||!(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent)));let ie=null;const re=()=>null!==ie?ie:ie="undefined"!==typeof navigator&&navigator.userAgent?.includes("Firefox");let ae=null;const se=()=>null!==ae?ae:ae=!("undefined"===typeof navigator||!navigator.vendor?.includes("Google Inc")&&!/Chrome/.test(navigator.userAgent)),ne=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.`,oe=(async()=>{})().constructor,ce=e=>e instanceof oe||e instanceof Promise||"function"===typeof e?.then,le=(e,t)=>-1!==e?e:t,ue=(e,t,i,r)=>e<=r&&i<=t,de=e=>{const t=atob(e),i=new Uint8Array(t.length);for(let r=0;r{Symbol.dispose??(Symbol.dispose=Symbol("Symbol.dispose"))},fe=e=>"number"===typeof e&&!Number.isNaN(e),me=(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("/")},pe=(e,t)=>{let i=0;for(let r=0;r{let i=-1,r=1/0;for(let a=0;a{n(Number.isInteger(e.num)),n(Number.isInteger(e.den)),n(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}},ye=(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.`)},be=e=>new Promise(t=>setTimeout(t,e));class we{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 Te,Se;(Se=Te||(Te={}))[Se.Silent=0]="Silent",Se[Se.Errors=1]="Errors",Se[Se.Warnings=2]="Warnings",Se[Se.Info=3]="Info";class ve{constructor(){}static get level(){return ve._level}static set level(e){if(e!==Te.Silent&&e!==Te.Errors&&e!==Te.Warnings&&e!==Te.Info)throw new TypeError("Invalid log level. Use one of the values of the LogLevel enum.");ve._level=e}static get _emitter(){return ve._emitterInstance??(ve._emitterInstance=new we)}static on(e,t,i){return ve._emitter.on(e,t,i)}static _error(...e){ve._emitter._emit("error",e),ve._level>=Te.Errors&&console.error(...e)}static _warn(...e){ve._emitter._emit("warn",e),ve._level>=Te.Warnings&&console.warn(...e)}static _info(...e){ve._emitter._emit("info",e),ve._level>=Te.Info&&console.info(...e)}}ve._level=Te.Info,ve._emitterInstance=null;class Pe{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 Ie{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 xe={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1};class Ce{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 Ce(this.bytes);return e.pos=this.pos,e}}const Be=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],Ee=[-1,1,2,3,4,5,6,8],_e=e=>{if(!e||e.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");const t=new Ce(e),i=Re(t),{frequencyIndex:r,sampleRate:a}=Fe(t),s=t.readBits(4);let n=null;s>=1&&s<=7&&(n=Ee[s]);let o=i,c=!1,l=a;if(5===i||29===i)c=29===i,l=Fe(t).sampleRate,o=Re(t),22===o&&t.skipBits(4);else for(;t.getBitsLeft()>15;){const e=t.pos;if(695===t.readBits(11)){5===Re(t)&&t.readBits(1)&&(l=Fe(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}},Re=e=>{const t=e.readBits(5);return 31===t?32+e.readBits(6):t},Fe=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&h(t.description)[4];return Ue(e,i+1)}return ze(e)},We=e=>31&e,He=e=>{const t=[],i=e.length;for(let r=0;r{const t=e.reduce((e,t)=>e+Ve.byteLength+t.byteLength,0),i=new Uint8Array(t);let r=0;for(const a of e)i.set(Ve,r),r+=Ve.byteLength,i.set(a,r),r+=a.byteLength;return i},Ke=(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:L(e,a,s.byteLength);break;case 4:e.setUint32(a,s.byteLength,!1)}a+=t,r.set(s,a),a+=s.byteLength}return r},Xe=e=>{try{const t=[],i=[],r=[];for(const n of ze(e)){const a=e.subarray(n.offset,n.offset+n.length),s=We(a[0]);s===Me.SPS?t.push(a):s===Me.PPS?i.push(a):s===Me.SPS_EXT&&r.push(a)}if(0===t.length)return null;if(0===i.length)return null;const a=t[0],s=Ye(a);n(null!==s);const o=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:o?s.chromaFormatIdc:null,bitDepthLumaMinus8:o?s.bitDepthLumaMinus8:null,bitDepthChromaMinus8:o?s.bitDepthChromaMinus8:null,sequenceParameterSetExt:o?r:null}}catch(t){return ve._error("Error building AVC Decoder Configuration Record:",t),null}},$e=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=f(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=He(e),i=new Ce(t);i.skipBits(1),i.skipBits(2);if(7!==i.readBits(5))return null;const r=i.readAlignedByte(),a=i.readAlignedByte(),s=i.readAlignedByte();l(i);let o=1,u=0,h=0,f=0;if(100===r||110===r||122===r||244===r||44===r||83===r||86===r||118===r||128===r){o=l(i),3===o&&(f=i.readBits(1)),u=l(i),h=l(i),i.skipBits(1);if(i.readBits(1))for(let e=0;e<(3!==o?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)??c($t),r=Math.min(Math.floor(i.maxDpbMbs/(e*t)),16);C=r,B=r}else C=0,B=0}return n(null!==B),{emulationUnpreventedBytes:t,profileIdc:r,constraintFlags:a,levelIdc:s,frameMbsOnlyFlag:T,chromaFormatIdc:o,bitDepthLumaMinus8:u,bitDepthChromaMinus8:h,codedWidth:k,codedHeight:y,displayWidth:b,displayHeight:w,pixelAspectRatio:x,colourPrimaries:S,matrixCoefficients:P,transferCharacteristics:v,fullRangeFlag:I,numReorderFrames:C,maxDecFrameBuffering:B,vuiParametersFlagBitOffset:R,bitstreamRestrictionFlagBitOffset:E,bitstreamRestrictionFlag:_}}catch(t){return ve._error("Error parsing AVC SPS:",t),null}},Je=e=>{const t=l(e);e.skipBits(4),e.skipBits(4);for(let i=0;i<=t;i++)l(e),l(e),e.skipBits(1);e.skipBits(5),e.skipBits(5),e.skipBits(5),e.skipBits(5)},Ze=e=>{n(1!==e.bitstreamRestrictionFlag);const t=new Uint8Array(e.emulationUnpreventedBytes.byteLength+64),i=new Ce(e.emulationUnpreventedBytes),r=new Ce(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)):(n(null!==e.bitstreamRestrictionFlagBitOffset),r.copyBits(e.bitstreamRestrictionFlagBitOffset,i)),r.writeBits(1,1),r.writeBits(1,1),u(r,2),u(r,1),u(r,16),u(r,16),u(r,e.numReorderFrames),u(r,e.maxDecFrameBuffering),r.writeBits(1,1),r.writeBits((8-r.pos%8)%8,0);const a=r.pos/8;return n(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))},et=(e,t)=>{if(t.description){const i=3&h(t.description)[21];return Ue(e,i+1)}return ze(e)},tt=e=>e>>1&63,it=e=>{try{const t=new Ce(He(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:u}=at(t,i);l(t);const d=l(t);let h=0;3===d&&(h=t.readBits(1));const f=l(t),m=l(t);let p=f,g=m;if(t.readBits(1)){const e=l(t),i=l(t),r=l(t),a=l(t);let s=1,n=1;const o=0===h?d:0;1===o?(s=2,n=2):2===o&&(s=2,n=1),p-=(e+i)*s,g-=(r+a)*n}const k=l(t),y=l(t);l(t);const b=t.readBits(1);let w=0;for(let e=b?0:i;e<=i;e++)l(t),w=l(t),l(t);l(t),l(t),l(t),l(t),l(t),l(t),t.readBits(1)&&t.readBits(1)&&st(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(4),t.skipBits(4),l(t),l(t),t.skipBits(1));const T=l(t);if(nt(t,T),t.readBits(1)){const e=l(t);for(let i=0;i{try{const t=[],i=[],r=[],a=[];for(const c of ze(e)){const s=e.subarray(c.offset,c.offset+c.length),n=tt(s[0]);n===Oe.VPS_NUT?t.push(s):n===Oe.SPS_NUT?i.push(s):n===Oe.PPS_NUT?r.push(s):n!==Oe.PREFIX_SEI_NUT&&n!==Oe.SUFFIX_SEI_NUT||a.push(s)}if(0===i.length||0===r.length)return null;const s=it(i[0]);if(!s)return null;let n=0;if(r.length>0){const e=r[0],t=new Ce(He(e));t.skipBits(16),l(t),l(t),t.skipBits(1),t.skipBits(1),t.skipBits(3),t.skipBits(1),t.skipBits(1),l(t),l(t),d(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&l(t),d(t),d(t),t.skipBits(1),t.skipBits(1),t.skipBits(1),t.skipBits(1);const i=t.readBits(1),a=t.readBits(1);n=i||a?i&&!a?2:!i&&a?3:0:0}const o=[...t.length?[{arrayCompleteness:1,nalUnitType:Oe.VPS_NUT,nalUnits:t}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:Oe.SPS_NUT,nalUnits:i}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:Oe.PPS_NUT,nalUnits:r}]:[],...a.length?[{arrayCompleteness:1,nalUnitType:tt(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 ve._error("Error building HEVC Decoder Configuration Record:",t),null}},at=(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&&d(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-(l(e)+1)}else n=t-1;e.readBits(1),l(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=l(e),i=l(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=Qe[t];e&&(o=e)}}return e.readBits(1)&&e.readBits(1),e.readBits(1)&&(e.readBits(3),s=e.readBits(1),e.readBits(1)&&(i=e.readBits(8),r=e.readBits(8),a=e.readBits(8))),e.readBits(1)&&(l(e),l(e)),e.readBits(1),e.readBits(1),e.readBits(1),e.readBits(1)&&(l(e),l(e),l(e),l(e)),e.readBits(1)&&(e.readBits(32),e.readBits(32),e.readBits(1)&&l(e),e.readBits(1)&<(e,!0,t)),e.readBits(1)&&(e.readBits(1),e.readBits(1),e.readBits(1),n=l(e),l(e),l(e),l(e),l(e)),{pixelAspectRatio:o,colourPrimaries:i,transferCharacteristics:r,matrixCoefficients:a,fullRangeFlag:s,minSpatialSegmentationIdc:n}},lt=(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?l(e):i=1===e.readBits(1);let n=1;if(!i){n=l(e)+1}r&&ut(e,n,s),a&&ut(e,n,s)}},ut=(e,t,i)=>{for(let r=0;r{const i=new Set;let r=dt.audAllowed;for(const s of et(e,t)){if(r===dt.noMoreDataAllowed){i.add(s.offset);continue}const t=tt(e[s.offset]);if(r===dt.eoBitstreamAllowed&&37!==t){i.add(s.offset);continue}let a=!1;35===t?r>dt.audAllowed?a=!0:r=dt.beforeFirstVcl:t<=31?r>dt.afterFirstVcl?a=!0:r=dt.afterFirstVcl:36===t?r!==dt.afterFirstVcl?a=!0:r=dt.eoBitstreamAllowed:37===t?r=41&&t<=44||t>=48&&t<=55?r>dt.beforeFirstVcl?a=!0:r=dt.beforeFirstVcl:(38===t||40===t||t>=45&&t<=47||t>=56&&t<=63)&&r{if(t.description){const i=3&h(t.description)[21];return Ke(e,i+1)}return je(e)})(a,t)},mt={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}},pt=e=>{const t=new Ce(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 l=(t.readBits(16)+1)*(t.readBits(16)+1);let u=c(Gt).level;for(const c of Gt)if(l<=c.maxPictureSize){u=c.level;break}const d=mt[s];return{profile:r,level:u,bitDepth:a,chromaSubsampling:n,videoFullRangeFlag:o,colourPrimaries:d?.colourPrimaries??2,transferCharacteristics:d?.transferCharacteristics??2,matrixCoefficients:d?.matrixCoefficients??2}},gt=function*(e){const t=new Ce(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 o;if(t.skipBits(1),a&&t.skipBits(8),s){const e=i();if(null===e)return;o=e}else o=Math.floor(t.getBitsLeft()/8);n(t.pos%8===0),yield{type:r,data:e.subarray(t.pos/8,t.pos/8+o)},t.skipBits(8*o)}},kt=e=>{for(const{type:t,data:i}of gt(e)){if(1!==t)continue;const e=new Ce(i),r=e.readBits(3);e.readBits(1);const a=e.readBits(1);let s=0,n=0,o=0;if(a)s=e.readBits(5);else{let t=0;if(e.readBits(1)){e.skipBits(32),e.skipBits(32);if(e.readBits(1)){let t=0;for(;t<32&&!e.readBits(1);)t++;t<32&&e.skipBits(t)}t=e.readBits(1),t&&(o=e.readBits(5),e.skipBits(32),e.skipBits(5),e.skipBits(5))}const i=e.readBits(1),r=e.readBits(5);for(let a=0;a<=r;a++){e.skipBits(12);const r=e.readBits(5);if(0===a&&(s=r),r>7){const t=e.readBits(1);0===a&&(n=t)}if(t){if(e.readBits(1)){const t=o+1;e.skipBits(t),e.skipBits(t),e.skipBits(1)}}if(i){e.readBits(1)&&e.skipBits(4)}}}const c=e.readBits(4),l=e.readBits(4),u=c+1;e.skipBits(u);const d=l+1;e.skipBits(d);let h=0;if(h=a?0:e.readBits(1),h&&(e.skipBits(4),e.skipBits(3)),e.skipBits(1),e.skipBits(1),e.skipBits(1),!a){e.skipBits(1),e.skipBits(1),e.skipBits(1),e.skipBits(1);const t=e.readBits(1);t&&(e.skipBits(1),e.skipBits(1));let i=0;if(i=e.readBits(1)?2:e.readBits(1),i>0){e.readBits(1)||e.skipBits(1)}t&&e.skipBits(3)}e.skipBits(1),e.skipBits(1),e.skipBits(1);const f=e.readBits(1);let m=8;if(2===r&&f){m=e.readBits(1)?12:10}else r<=2&&(m=f?10:8);let p=0;1!==r&&(p=e.readBits(1));let g=2,k=2,y=2;e.readBits(1)&&(g=e.readBits(8),k=e.readBits(8),y=e.readBits(8));let b=0,w=1,T=1,S=0;return p?b=e.readBits(1):1===g&&13===k&&0===y?(b=1,w=0,T=0):(b=e.readBits(1),0===r?(w=1,T=1):1===r?(w=0,T=0):12===m?(w=e.readBits(1),T=w?e.readBits(1):0):(w=1,T=0),w&&T&&(S=e.readBits(2))),{profile:r,level:s,tier:n,bitDepth:m,monochrome:p,chromaSubsamplingX:w,chromaSubsamplingY:T,chromaSamplePosition:S,videoFullRangeFlag:b,colourPrimaries:g,transferCharacteristics:k,matrixCoefficients:y}}return null},yt=e=>{if(e.length<36)return null;const t=f(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)}},bt=[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],wt=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}},Tt=(e,t,i)=>{switch(e){case"avc":for(const e of qe(i,t)){const t=i[e.offset],r=We(t);if(r>=Me.NON_IDR_SLICE&&r<=Me.SLICE_DPC)return"delta";if(r===Me.IDR)return"key";if(r===Me.SEI&&!se()){const t=i.subarray(e.offset,e.offset+e.length),r=He(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 Ce(r);e.pos=8*a;const t=l(e),i=e.readBits(1);if(0===t&&1===i)return"key"}a+=t}while(a{var i,r;const a=f(e);let s=0;const n=a.getUint32(s,!0);s+=4;const o=m.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=de(l),i=f(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=m.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})}}}},It=[2,1,2,3,3,4,4,5],xt=e=>{if(e.length<7)return null;if(11!==e[0]||119!==e[1])return null;const t=new Ce(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)}},Ct=[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],Bt=[1,2,3,6],Et=e=>{if(e.length<6)return null;if(11!==e[0]||119!==e[1])return null;const t=new Ce(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=Bt[s];let d;d=a<3?Ae[a]/1e3:De[n]/1e3;return{dataRate:Math.round((r+1)*d/(16*u)),substreams:[{fscod:a,fscod2:n,bsid:l,bsmod:0,acmod:o,lfeon:c,numDepSub:0,chanLoc:0}]}},_t=e=>{const t=e.substreams[0];return n(t),t.fscod<3?Ae[t.fscod]:null!==t.fscod2&&t.fscod2<3?De[t.fscod2]:null},Rt=e=>{const t=e.substreams[0];n(t);let i=It[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},Ft=[0,8e3,16e3,32e3,0,0,11025,22050,44100,0,0,12e3,24e3,48e3,96e3,192e3],At=[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],Dt=[16,16,20,20,0,24,24,0],Mt=[1,2,2,2,2,3,3,4,4,5,6,6,6,7,8,8],Nt=[1,2,2,2,2,3,18,19,6,7,518,323,83,519,582,535],Ot=[32e3,44100,48e3,0],Lt=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],zt=[512,1024,2048,4096],Ut=e=>{const t=Wt(e),i=f(e);let r=t?4*Math.ceil(t.frameSize/4):0,a=null;for(;r+4<=e.length&&1683496997===i.getUint32(r);){const t=Ht(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}},qt=e=>{const t=Ut(e);return t?.core?t.hasExtensions?"dtsh":"dtsc":null},Wt=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 Ce(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>=Mt.length)return null;const n=Ft[t.readBits(4)];if(0===n)return null;const o=At[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=Dt[t.readBits(3)];if(0===l)return null;const u=0!==c;return{frameSize:a,sampleRate:n,numberOfChannels:Mt[s]+(u?1:0),sampleCount:32*r,channelLayout:Nt[s]|(u?8:0),amode:s,lfePresent:u,bitRate:o,pcmResolution:l}},Ht=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 Ce(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=Ot[t.readBits(2)],l=512*(t.readBits(3)+1);t.readBits(1)&&t.skipBits(36);const u=t.readBits(3)+1,d=t.readBits(3)+1,h=[];for(let k=0;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}}},Vt=e=>K(e)+K(44646&e),jt=["avc","hevc","vp9","av1","vp8","prores"],Kt=["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"],Xt=["aac","opus","mp3","vorbis","flac","ac3","eac3","dts",...Kt],$t=[{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}],Gt=[{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}],Qt=".01.01.01.01.00",Yt=".0.110.01.01.01.0",Jt=["ap4x","ap4h","apch","apcn","apcs","apco"],Zt=["dtsc","dtsh","dtsl","dtse"],ei=e=>{const{codec:t,codecDescription:i,colorSpace:r,avcCodecInfo:a,hevcCodecInfo:s,vp9CodecInfo:o,av1CodecInfo:l,proresFormat:u}=e;if("avc"===t){if(n(null!==e.avcType),a){const t=new Uint8Array([a.avcProfileIndication,a.profileCompatibility,a.avcLevelIndication]);return`avc${e.avcType}.${C(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}.${C(i.subarray(1,4))}`}if("hevc"===t){let e,t,r,a,n,o;if(s)e=s.generalProfileSpace,t=s.generalProfileIdc,r=B(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=f(i),c=s.getUint8(1);e=c>>6&3,t=31&c,r=B(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(!o){const t=e.width*e.height;let i=c(Gt).level;for(const e of Gt)if(t<=e.maxPictureSize){i=e.level;break}return`vp09.00.${i.toString().padStart(2,"0")}.08`}let t=`vp09.${o.profile.toString().padStart(2,"0")}.${o.level.toString().padStart(2,"0")}.${o.bitDepth.toString().padStart(2,"0")}.${o.chromaSubsampling.toString().padStart(2,"0")}`;return t+=`.${o.colourPrimaries.toString().padStart(2,"0")}.${o.transferCharacteristics.toString().padStart(2,"0")}.${o.matrixCoefficients.toString().padStart(2,"0")}.${o.videoFullRangeFlag.toString().padStart(2,"0")}`,t.endsWith(Qt)&&(t=t.slice(0,-15)),t}if("av1"===t){if(!l){const t=e.width*e.height;let i=c(Gt).level;for(const e of Gt)if(t<=e.maxPictureSize){i=e.level;break}return`av01.0.${i.toString().padStart(2,"0")}M.08`}const t=l.profile,i=l.level.toString().padStart(2,"0"),a=l.tier?"H":"M",s=l.bitDepth.toString().padStart(2,"0"),n=l.monochrome?"1":"0",o=100*l.chromaSubsamplingX+10*l.chromaSubsamplingY+1*(l.chromaSubsamplingX&&l.chromaSubsamplingY?l.chromaSamplePosition:0),u=r?.primaries?g[r.primaries]:1,d=r?.transfer?y[r.transfer]:1,h=r?.matrix?w[r.matrix]:1,f=r?.fullRange?1:0;let m=`av01.${t}.${i}${a}.${s}`;return m+=`.${n}.${o.toString().padStart(3,"0")}`,m+=`.${u.toString().padStart(2,"0")}`,m+=`.${d.toString().padStart(2,"0")}`,m+=`.${h.toString().padStart(2,"0")}`,m+=`.${f}`,m.endsWith(Yt)&&(m=m.slice(0,-17)),m}if("prores"===t)return u??"apch";throw null!==t&&N(t),new TypeError(`Unhandled codec '${t}'.`)},ti=e=>{switch(e.codec){case"avc":{let t=e.avcCodecInfo?.sequenceParameterSets[0];if(!t&&e.codecDescription&&(t=Ge(e.codecDescription)?.sequenceParameterSets[0]),t){const e=Ye(t);if(e)return{primaries:k[e.colourPrimaries],transfer:b[e.transferCharacteristics],matrix:T[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case"hevc":{let t=e.hevcCodecInfo?.arrays.find(e=>e.nalUnitType===Oe.SPS_NUT)?.nalUnits[0];if(!t&&e.codecDescription&&(t=(e=>{try{const t=f(e);let i=0;const r=t.getUint8(i++),a=t.getUint8(i++),s=a>>6&3,n=a>>5&1,o=31&a,c=t.getUint32(i,!1);i+=4;const l=e.subarray(i,i+6);i+=6;const u=t.getUint8(i++),d=(15&t.getUint8(i++))<<8|t.getUint8(i++),h=3&t.getUint8(i++),m=3&t.getUint8(i++),p=7&t.getUint8(i++),g=7&t.getUint8(i++),k=t.getUint16(i,!1);i+=2;const y=t.getUint8(i++),b=y>>6&3,w=y>>3&7,T=y>>2&1,S=3&y,v=t.getUint8(i++),P=[];for(let f=0;f>7&1,s=63&r,n=t.getUint16(i,!1);i+=2;const o=[];for(let c=0;ce.nalUnitType===Oe.SPS_NUT)?.nalUnits[0]),t){const e=it(t);if(e)return{primaries:k[e.colourPrimaries],transfer:b[e.transferCharacteristics],matrix:T[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case"vp8":break;case"vp9":if(e.vp9CodecInfo)return{primaries:k[e.vp9CodecInfo.colourPrimaries],transfer:b[e.vp9CodecInfo.transferCharacteristics],matrix:T[e.vp9CodecInfo.matrixCoefficients],fullRange:!!e.vp9CodecInfo.videoFullRangeFlag};break;case"av1":if(e.av1CodecInfo)return{primaries:k[e.av1CodecInfo.colourPrimaries],transfer:b[e.av1CodecInfo.transferCharacteristics],matrix:T[e.av1CodecInfo.matrixCoefficients],fullRange:!!e.av1CodecInfo.videoFullRangeFlag};break;case"prores":if(e.proresCodecInfo)return{primaries:k[e.proresCodecInfo.colourPrimaries],transfer:b[e.proresCodecInfo.transferCharacteristics],matrix:T[e.proresCodecInfo.matrixCoefficients],fullRange:e.proresCodecInfo.fullRange}}return{primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0}},ii=e=>{const{codec:t,codecDescription:i,aacCodecInfo:r,dtsFormat:a}=e;if("aac"===t){if(!r)throw new TypeError("AAC codec info must be provided.");if(r.isMpeg2)return"mp4a.67";{let e;if(null!==r.objectType)e=r.objectType;else{e=_e(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&&Kt.includes(t))return t;throw new TypeError(`Unhandled codec '${t}'.`)},ri=48e3,ai=/^pcm-([usf])(\d+)(be)?$/,si=e=>{if(n(Kt.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=ai.exec(e);let i;n(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}},ni=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":Jt.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":Zt.includes(e)?"dts":"ulaw"===e?"ulaw":"alaw"===e?"alaw":ai.test(e)?e:"webvtt"===e?"webvtt":null,oi=[44100,48e3,32e3],ci=[-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],li=1483304551,ui=1231971951,di=(e,t)=>3===e?3===t?21:36:3===t?13:21,hi=(e,t)=>{const i=e>>>24,r=e>>>16&255,a=e>>>8&255,s=255&e;if(255!==i&&255!==r&&255!==a&&255!==s)return{header:null,bytesAdvanced:4};if(255!==i)return{header:null,bytesAdvanced:1};if(224!==(224&r))return{header:null,bytesAdvanced:1};let n=0,o=0;16&r?n=8&r?0:1:(n=1,o=1);const c=r>>3&3,l=r>>1&3,u=(a>>2&3)%3,d=s>>6&3,h=s>>4&3,f=s>>3&1,m=s>>2&1,p=3&s,g=ci[16*n*4+16*l+(a>>4&15)];if(-1===g)return{header:null,bytesAdvanced:1};const k=1e3*g,y=oi[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 mi,pi;(pi=mi||(mi={}))[pi.FrameCount=1]="FrameCount",pi[pi.FileSize=2]="FileSize",pi[pi.Toc=4]="Toc";const gi=e=>3===e?1:2;class ki{constructor(e){this.input=e}dispose(){}}const yi=new Uint8Array(0);class bi{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===yi&&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===yi}get microsecondTimestamp(){return Math.trunc(G*this.timestamp)}get microsecondDuration(){return Math.trunc(G*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 bi(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 bi(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 wi=e=>{const t=f(e);let i=0;const r=t.getUint8(i);i+=1,i+=3;const a=C(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=Io(e);const i=Do(e,4);let r=8;1===t&&(t=Eo(e),r=16);const a=t-r;return a<0?null:{name:i,totalSize:t,headerSize:r,contentSize:a}},vi=e=>Co(e)/65536,Pi=e=>Co(e)/1073741824,Ii=e=>{let t=0;for(let i=0;i<4;i++){t<<=7;const i=bo(e);if(t|=127&i,0===(128&i))break}return t},xi=e=>{let t=To(e);return e.skip(2),t=Math.min(t,e.remainingLength),m.decode(yo(e,t))},Ci=e=>{const t=Si(e);if(!t||"data"!==t.name)return null;if(e.remainingLength<8)return null;const i=Io(e);e.skip(4);const r=yo(e,t.contentSize-8);switch(i){case 1:return m.decode(r);case 2:return new TextDecoder("utf-16be").decode(r);case 13:return new Pe(r,"image/jpeg");case 14:return new Pe(r,"image/png");case 27:return new Pe(r,"image/bmp");default:return r}},Bi=16,Ei=new Uint32Array(256),_i=new Uint32Array(256),Ri=new Uint32Array(256),Fi=new Uint32Array(256),Ai=new Uint32Array(256),Di=new Uint32Array(256),Mi=new Uint32Array(10);let Ni=!1;class Oi{constructor(){this.roundkey=new Uint32Array(44),this.iv=new Uint32Array(Bi/Uint32Array.BYTES_PER_ELEMENT),this.in=new Uint8Array(Bi),this.out=new Uint8Array(Bi),this.inView=new DataView(this.in.buffer),this.outView=new DataView(this.out.buffer)}init({key:e,iv:t}){n(16===e.byteLength),n(16===t.byteLength),Ni||(()=>{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);Ei[s]=t<<24|t<<16|t<<8|t,Di[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);_i[s]=a,Ri[s]=a>>>8|a<<24,Fi[s]=a>>>16|a<<16,Ai[s]=a>>>24|a<<8}let a=1;for(let s=0;s<10;s++)Mi[s]=a<<24,a=a<<1^(128&a?283:0);Ni=!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&Ei[e>>>16&255]^16711680&Ei[e>>>8&255]^65280&Ei[e>>>0&255]^255&Ei[e>>>24&255]^Mi[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]]^Ri[255&Ei[t>>>16&255]]^Fi[255&Ei[t>>>8&255]]^Ai[255&Ei[t>>>0&255]]}}decrypt(){let e=this.inView.getUint32(0,!1)^this.roundkey[0],t=this.inView.getUint32(4,!1)^this.roundkey[1],i=this.inView.getUint32(8,!1)^this.roundkey[2],r=this.inView.getUint32(12,!1)^this.roundkey[3];const a=this.inView.getUint32(0,!1),s=this.inView.getUint32(4,!1),n=this.inView.getUint32(8,!1),o=this.inView.getUint32(12,!1);let c,l,u,d;for(let g=1;g<10;g++){const a=4*g;c=_i[e>>>24]^Ri[r>>>16&255]^Fi[i>>>8&255]^Ai[255&t]^this.roundkey[a],l=_i[t>>>24]^Ri[e>>>16&255]^Fi[r>>>8&255]^Ai[255&i]^this.roundkey[a+1],u=_i[i>>>24]^Ri[t>>>16&255]^Fi[e>>>8&255]^Ai[255&r]^this.roundkey[a+2],d=_i[r>>>24]^Ri[i>>>16&255]^Fi[t>>>8&255]^Ai[255&e]^this.roundkey[a+3],e=c,t=l,i=u,r=d}const h=4278190080&Di[e>>>24&255]^16711680&Di[r>>>16&255]^65280&Di[i>>>8&255]^255&Di[t>>>0&255]^this.roundkey[40],f=4278190080&Di[t>>>24&255]^16711680&Di[e>>>16&255]^65280&Di[r>>>8&255]^255&Di[i>>>0&255]^this.roundkey[41],m=4278190080&Di[i>>>24&255]^16711680&Di[t>>>16&255]^65280&Di[e>>>8&255]^255&Di[r>>>0&255]^this.roundkey[42],p=4278190080&Di[r>>>24&255]^16711680&Di[i>>>16&255]^65280&Di[t>>>8&255]^255&Di[e>>>0&255]^this.roundkey[43];this.outView.setUint32(0,h^this.iv[0],!1),this.outView.setUint32(4,f^this.iv[1],!1),this.outView.setUint32(8,m^this.iv[2],!1),this.outView.setUint32(12,p^this.iv[3],!1),this.iv[0]=a,this.iv[1]=s,this.iv[2]=n,this.iv[3]=o}}class Li extends ki{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(ce(r)&&(r=await r),!r)break;const a=e,s=Si(r);if(!s)break;if("ftyp"===s.name||"styp"===s.name){const e=Do(r,4);this.isQuickTime="qt "===e}else{if("moov"===s.name){let e=this.reader.requestSlice(r.filePos,s.contentSize);if(ce(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){n(null!==this.reader.fileSize);let e=this.reader.requestSlice(this.reader.fileSize-4,4);ce(e)&&(e=await e),n(e);const t=Io(e),i=this.reader.fileSize-t;if(i>=0&&i<=this.reader.fileSize-16){let e=this.reader.requestSliceRange(i,8,16);if(ce(e)&&(e=await e),e){const t=Si(e);if(t&&"mfra"===t.name){let i=this.reader.requestSlice(e.filePos,t.contentSize);ce(i)&&(i=await i),i&&this.readContiguousBoxes(i)}}}}})())}async copyMetadataFromInitInput(e){const t=await e._getDemuxer();if(t.constructor!==Li)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(n(e.info),"video"===e.info.type&&-1!==e.info.width){const t=e;e.trackBacking=new Ui(t),this.tracks.push(e)}else if("audio"===e.info.type&&-1!==e.info.numberOfChannels){const t=e;e.trackBacking=new qi(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;n(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&&Kt.includes(e.info.codec)&&0===t.sampleCompositionTimeOffsets.length){n("audio"===e.info?.type);const i=si(e.info.codec),r=[],a=[];for(let s=0;se.startIndex),d=t.sampleTimingEntries[u],h=_(t.sampleTimingEntries,l,e=>e.startIndex),f=t.sampleTimingEntries[h],m=d.startDecodeTimestamp+(o-d.startIndex)*d.delta,p=f.startDecodeTimestamp+(l-f.startIndex)*f.delta-m,g=c(r);g&&g.delta===p?g.count++:r.push({startIndex:n.startChunkIndex+s,startDecodeTimestamp:m,count:1,delta:p});const k=n.samplesPerChunk*i.sampleSize*e.info.numberOfChannels;a.push(k)}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)Ki(s,i.timestamp);else{const e=_(t,a.moofOffset-1,e=>e.moofOffset);if(-1!==e){const i=t[e];Ki(s,i.endTimestamp)}}s.startTimestampIsFinal=!0}const i=_(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 Qi(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;$(t.languageCode)||(t.languageCode=q)}}break;case"hdlr":{const t=this.currentTrack;if(!t)break;e.skip(8);const i=Do(e,4);"vide"===i?t.info={type:"video",width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:{...v},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=K,this.readContiguousBoxes(e.slice(G,X.contentSize))}break;case"stsd":{const t=this.currentTrack;if(!t)break;if(null===t.info||t.sampleTable)break;const i=bo(e);e.skip(3);const r=Io(e);for(let a=0;a0&&(1===n?(e.skip(4),c=8*Io(e),e.skip(8)):2===n&&(e.skip(4),l=Ao(e),o=Io(e),e.skip(4),c=Io(e),u=Io(e),e.skip(8))),t.info.numberOfChannels=o,t.info.sampleRate=l,t.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,r+a.totalSize-e.filePos));const d="enca"===s?t.frmaCodecString:s;if(t.frmaCodecString=null,"mp4a"===d);else if("opus"===d)t.info.codec="opus",t.info.sampleRate=ri;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(Zt.includes(d))t.info.codec="dts",t.info.dtsFormat=d;else if("twos"===d)8===c?t.info.codec="pcm-s8":16===c?t.info.codec=t.info.pcmLittleEndian?"pcm-s16":"pcm-s16be":(ve._warn(`Unsupported sample size ${c} for codec 'twos'.`),t.info.codec=null);else if("sowt"===d)8===c?t.info.codec="pcm-s8":16===c?t.info.codec="pcm-s16":(ve._warn(`Unsupported sample size ${c} for codec 'sowt'.`),t.info.codec=null);else if("raw "===d)t.info.codec="pcm-u8";else if("in24"===d)t.info.codec=t.info.pcmLittleEndian?"pcm-s24":"pcm-s24be";else if("in32"===d)t.info.codec=t.info.pcmLittleEndian?"pcm-s32":"pcm-s32be";else if("fl32"===d)t.info.codec=t.info.pcmLittleEndian?"pcm-f32":"pcm-f32be";else if("fl64"===d)t.info.codec=t.info.pcmLittleEndian?"pcm-f64":"pcm-f64be";else if("ipcm"===d){const e=t.info.pcmSampleSize;t.info.pcmLittleEndian?16===e?t.info.codec="pcm-s16":24===e?t.info.codec="pcm-s24":32===e?t.info.codec="pcm-s32":(ve._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":(ve._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":(ve._warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null):32===e?t.info.codec="pcm-f32be":64===e?t.info.codec="pcm-f64be":(ve._warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null)}else if("lpcm"===d&&null!==u){const e=c+7>>3,i=Boolean(1&u),r=Boolean(2&u),a=4&u?-1:0;c>0&&c<=64&&(i?32===c&&(t.info.codec=r?"pcm-f32be":"pcm-f32"):a&1<0?(t.encryptionInfo.defaultCryptByteBlock=r>>4,t.encryptionInfo.defaultSkipByteBlock=15&r):(t.encryptionInfo.defaultCryptByteBlock=0,t.encryptionInfo.defaultSkipByteBlock=0),t.encryptionInfo.defaultIsProtected=0!==bo(e),t.encryptionInfo.defaultPerSampleIvSize=bo(e),t.encryptionInfo.defaultKid=C(yo(e,16)),t.encryptionInfo.defaultIsProtected&&0===t.encryptionInfo.defaultPerSampleIvSize){const i=bo(e),r=new Uint8Array(16);r.set(yo(e,i),0),t.encryptionInfo.defaultConstantIv=r}}break;case"avcC":{const t=this.currentTrack;if(!t)break;if(n(t.info),0===X.contentSize)break;t.info.codecDescription=yo(e,X.contentSize)}break;case"hvcC":{const t=this.currentTrack;if(!t)break;if(n(t.info),0===X.contentSize)break;t.info.codecDescription=yo(e,X.contentSize)}break;case"vpcC":{const t=this.currentTrack;if(!t)break;n("video"===t.info?.type),e.skip(4);const i=bo(e),r=bo(e),a=bo(e),s=a>>4,o=a>>1&7,c=1&a,l=bo(e),u=bo(e),d=bo(e);t.info.vp9CodecInfo={profile:i,level:r,bitDepth:s,chromaSubsampling:o,videoFullRangeFlag:c,colourPrimaries:l,transferCharacteristics:u,matrixCoefficients:d}}break;case"av1C":{const t=this.currentTrack;if(!t)break;n("video"===t.info?.type),e.skip(1);const i=bo(e),r=i>>5,a=31&i,s=bo(e),o=s>>7,c=s>>6&1,l=s>>4&1,u=s>>3&1,d=s>>2&1,h=3&s,f=2===r&&c?s>>5&1?12:10:c?10:8;e.skip(1);const m=yo(e,X.contentSize-4),p=kt(m);t.info.av1CodecInfo={profile:r,level:a,tier:o,bitDepth:f,monochrome:l,chromaSubsamplingX:u,chromaSubsamplingY:d,chromaSamplePosition:h,videoFullRangeFlag:p?.videoFullRangeFlag??0,colourPrimaries:p?.colourPrimaries??2,transferCharacteristics:p?.transferCharacteristics??2,matrixCoefficients:p?.matrixCoefficients??2}}break;case"colr":{const t=this.currentTrack;if(!t)break;n("video"===t.info?.type);const i=Do(e,4);if("nclx"!==i&&"nclc"!==i)break;const r=To(e),a=To(e),s=To(e);let o;"nclx"===i&&(o=Boolean(128&bo(e))),t.info.colorSpace={primaries:k[r],transfer:b[a],matrix:T[s],fullRange:o}}break;case"pasp":{const t=this.currentTrack;if(!t)break;n("video"===t.info?.type);const i=Io(e),r=Io(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);n(3===bo(e)),Ii(e),e.skip(2);const i=bo(e),r=0!==(64&i),a=0!==(32&i);if(0!==(128&i)&&e.skip(2),r){const t=bo(e);e.skip(t)}a&&e.skip(2);n(4===bo(e));const s=Ii(e),o=e.filePos,c=bo(e);if(64===c||103===c?(t.info.codec="aac",t.info.aacCodecInfo={isMpeg2:103===c,objectType:null}):105===c||107===c?t.info.codec="mp3":221===c?t.info.codec="vorbis":169===c?t.info.codec="dts":ve._warn(`Unsupported audio codec (objectTypeIndication ${c}) - discarding track.`),e.skip(12),s>e.filePos-o){n(5===bo(e));const i=Ii(e);if(t.info.codecDescription=yo(e,i),"aac"===t.info.codec){const e=_e(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;n("audio"===t.info?.type),t.info.pcmLittleEndian=!!(255&To(e))}break;case"pcmC":{const t=this.currentTrack;if(!t)break;n("audio"===t.info?.type),e.skip(4);const i=bo(e);t.info.pcmLittleEndian=Boolean(1&i),t.info.pcmSampleSize=bo(e)}break;case"dOps":{const t=this.currentTrack;if(!t)break;n("audio"===t.info?.type),e.skip(1);const i=bo(e),r=To(e),a=Io(e),s=vo(e),o=bo(e);let c;c=0!==o?yo(e,2+i):new Uint8Array(0);const l=new Uint8Array(19+c.byteLength),u=new DataView(l.buffer);u.setUint32(0,1332770163,!1),u.setUint32(4,1214603620,!1),u.setUint8(8,1),u.setUint8(9,i),u.setUint16(10,r,!0),u.setUint32(12,a,!0),u.setInt16(16,s,!0),u.setUint8(18,o),l.set(c,19),t.info.codecDescription=l,t.info.numberOfChannels=i}break;case"dfLa":{const t=this.currentTrack;if(!t)break;n("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 o=yo(e,s-a),c=new Uint8Array(4+o.byteLength);new DataView(c.buffer).setUint32(0,1716281667,!1),c.set(o,4),t.info.codecDescription=c}break;case"dac3":{const t=this.currentTrack;if(!t)break;n("audio"===t.info?.type);const i=yo(e,3),r=new Ce(i),a=r.readBits(2);r.skipBits(8);const s=r.readBits(3),o=r.readBits(1);a<3&&(t.info.sampleRate=Ae[a]),t.info.numberOfChannels=It[s]+o}break;case"dec3":{const t=this.currentTrack;if(!t)break;n("audio"===t.info?.type);const i=(e=>{if(e.length<2)return null;const t=new Ce(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}})(yo(e,X.contentSize));if(!i){ve._warn("Invalid dec3 box contents, ignoring.");break}const r=_t(i);null!==r&&(t.info.sampleRate=r),t.info.numberOfChannels=Rt(i)}break;case"ddts":{const t=this.currentTrack;if(!t)break;n("audio"===t.info?.type);const i=(e=>{if(e.length<20)return null;const t=f(e),i=t.getUint32(0);if(0===i)return null;const r=new Ce(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=Vt(o):ne.id===i);if(!r)break;const a=Io(e),s=(12&a)>>2,n=3&a,o=[bo,To,So,Io],c=o[(48&a)>>4],l=o[s],u=o[n],d=Io(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 a=0;ae.id===u);if(!d)break;const h=this.fragmentTrackDefaults.find(e=>e.trackId===u);this.currentTrack=d,d.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?d.currentFragmentState.baseDataOffset=Eo(e):l&&(d.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),r&&(d.currentFragmentState.sampleDescriptionIndex=Io(e)),a&&(d.currentFragmentState.defaultSampleDuration=Io(e)),s&&(d.currentFragmentState.defaultSampleSize=Io(e)),o&&(d.currentFragmentState.defaultSampleFlags=Io(e)),c&&(d.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{const t=this.currentTrack;if(!t)break;n(t.currentFragmentState);const i=bo(e);e.skip(3);const r=0===i?Io(e):Eo(e);t.currentFragmentState.startTimestamp=r}break;case"trun":{const t=this.currentTrack;if(!t)break;n(this.currentFragment),n(t.currentFragmentState);const i=bo(e),r=So(e),a=Boolean(1&r),s=Boolean(4&r),o=Boolean(256&r),c=Boolean(512&r),l=Boolean(1024&r),u=Boolean(2048&r),d=Io(e);let h=null;a&&(h=Co(e));let f,m=null;s&&(m=Io(e)),this.currentFragment.trackData.has(t.id)?(f=this.currentFragment.trackData.get(t.id),null!==h&&(f.currentOffset=t.currentFragmentState.baseDataOffset+h)):(f={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,f));for(let p=0;p0&&(a=yo(e,r));const s=Gi(t);s.defaultSampleInfoSize=i,s.sampleSizes=a,s.sampleCount=r}break;case"saio":{const t=this.currentTrack;if(!t||!t.encryptionInfo)break;const i=bo(e);if(1&So(e)){const i=Do(e,4),r=Io(e);if(i!==t.encryptionInfo.scheme||0!==r)break}const r=Io(e);if(0===r)break;r>1&&ve._warn("Multiple saio entries are not supported; using the first offset only.");let a=0===i?Io(e):Number(Eo(e));this.currentFragment&&(a+=this.currentFragment.moofOffset);Gi(t).offset=a}break;case"senc":{const t=this.currentTrack;if(!t||!t.encryptionInfo)break;n(this.currentFragment);const i=this.currentFragment.trackData.get(t.id);if(!i)break;e.skip(1);const r=So(e),a=Boolean(2&r),s=Io(e),o=t.encryptionInfo.defaultPerSampleIvSize;n(null!==o);for(let n=0;n0?r.set(yo(e,o),0):r.set(t.encryptionInfo.defaultConstantIv,0);let s=null;if(a){const t=To(e);s=[];for(let i=0;i0&&((L=this.metadataTags).trackNumber??(L.trackNumber=t)),i&&Number.isInteger(i)&&i>0&&((z=this.metadataTags).tracksTotal??(z.tracksTotal=i))}break;case"trkn":if(a instanceof Uint8Array&&a.length>=6){const e=f(a),t=e.getUint16(2,!1),i=e.getUint16(4,!1);t>0&&((U=this.metadataTags).trackNumber??(U.trackNumber=t)),i>0&&((W=this.metadataTags).tracksTotal??(W.tracksTotal=i))}break;case"disc":case"disk":if(a instanceof Uint8Array&&a.length>=6){const e=f(a),t=e.getUint16(2,!1),i=e.getUint16(4,!1);t>0&&((V=this.metadataTags).discNumber??(V.discNumber=t)),i>0&&((j=this.metadataTags).discsTotal??(j.discsTotal=i))}}}}}return e.filePos=Q,!0}}class zi{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;n(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 W(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,t){const i=this.mapTimestampIntoTimescale(e),r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=Wi(r,i),s=await this.fetchPacketForSampleIndex(a,t);return $i(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=_(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=M(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 n(-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=Vi(i,e);if(!r)return null;let a;if(t.metadataOnly)a=yi;else{let t=this.internalTrack.demuxer.reader.requestSlice(r.sampleOffset,r.sampleSize);if(ce(t)&&(t=await t),!t)return null;if(a=yo(t,r.sampleSize),this.internalTrack.encryptionInfo){let t=null;if(this.internalTrack.encryptionAuxInfo){const i=await Qi(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);ee.timestamp),d=-1!==u?this.internalTrack.fragmentLookupTable[u]:null,h=_(this.internalTrack.fragmentPositionCache,i,e=>e.startTimestamp),f=-1!==h?this.internalTrack.fragmentPositionCache[h]:null,m=Math.max(d?.moofOffset??0,f?.moofOffset??0)||null;let p;for(e?null===m||e.moofOffset>=m?(p=e.moofOffset+e.moofSize,o=e):p=m:p=m??0;;){if(o){const e=o.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>r)break}let e=s.reader.requestSliceRange(p,8,16);if(ce(e)&&(e=await e),!e)break;const i=p,n=Si(e);if(!n)break;if("moof"===n.name){o=await s.readFragment(i);const{sampleIndex:e,correctSampleFound:r}=t(o);if(r)return this.fetchPacketInFragment(o,e,a);-1!==e&&(c=o,l=e)}p=i+n.totalSize}if(d&&(!c||c.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&&yt(e.data)}}else{const e=await this.getFirstPacket({}),t=e&&kt(e.data);t&&(this.internalTrack.info.av1CodecInfo=t)}else{const e=await this.getFirstPacket({}),t=e&&pt(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&&rt(e.data)}else{const e=await this.getFirstPacket({});this.internalTrack.info.avcCodecInfo=e&&Xe(e.data)}if(!S(this.internalTrack.info.colorSpace)){const a=ti(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:ei(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 qi extends zi{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&&qt(e.data)}return{codec:ii(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}})()):null}}const Wi=(e,t)=>{if(e.presentationTimestamps){const i=_(e.presentationTimestamps,t,e=>e.presentationTimestamp);return-1===i?-1:e.presentationTimestamps[i].sampleIndex}{const i=_(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)}},Hi=(e,t)=>{if(!e.keySampleIndices)return Wi(e,t);if(e.presentationTimestamps){const i=_(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 i=Wi(e,t),r=_(e.keySampleIndices,i,e=>e);return e.keySampleIndices[r]??-1}},Vi=(e,t)=>{const i=_(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=_(e.sampleCompositionTimeOffsets,t,e=>e.startIndex),o=e.sampleCompositionTimeOffsets[s];o&&t-o.startIndexe.startSampleIndex),u=e.sampleToChunk[l];n(u);const d=u.startChunkIndex+Math.floor((t-u.startSampleIndex)/u.samplesPerChunk),h=e.chunkOffsets[d],f=u.startSampleIndex+(d-u.startChunkIndex)*u.samplesPerChunk;let m=0,p=h;if(1===e.sampleSizes.length)p+=c*(t-f),m+=c*u.samplesPerChunk;else for(let n=f;ne)}},ji=(e,t)=>{if(!e.keySampleIndices)return t+1;const i=_(e.keySampleIndices,t,e=>e);return e.keySampleIndices[i+1]??-1},Ki=(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},Xi=e=>{const[t,i]=e,r=Math.atan2(i,t);return Number.isFinite(r)?r*(180/Math.PI):0},$i=e=>0===e.sampleSizes.length,Gi=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})},Qi=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{n(i.sampleSizes);for(let e=0;e0?i.defaultSampleInfoSize:i.sampleSizes[n],r=new Uint8Array(16);s>0?r.set(yo(a,s),0):r.set(t.defaultConstantIv,0);let c=null;if(e>s){const e=To(a);c=[];for(let t=0;te.defaultConstantIv?{iv:e.defaultConstantIv,subsamples:null}:null,Ji=async(e,t,i,r)=>{n(e.encryptionInfo);const a=e.encryptionInfo;n(null!==a.defaultKid);const s=a.defaultKid;let o;const c=e.demuxer.decryptionKeyCache.get(s);if(c)o=await c;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{n(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"]),o=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 o(r);n(null!==t.defaultCryptByteBlock&&null!==t.defaultSkipByteBlock);const c=tr(i.subsamples,t.defaultCryptByteBlock,t.defaultSkipByteBlock);let l=0;for(const n of c)for(const e of n.perSubsample)l+=e.length;const u=new Uint8Array(l);let d=0;for(const n of c)for(const e of n.perSubsample)u.set(r.subarray(e.offset,e.offset+e.length),d),d+=e.length;const h=await o(u),f=new Uint8Array(r);let m=0;for(const n of c)for(const e of n.perSubsample)f.set(h.subarray(m,m+e.length),e.offset),m+=e.length;return f},er=(e,t,i,r)=>{const a=new Oi;a.init({key:e,iv:i.iv});const s=t.defaultCryptByteBlock,o=t.defaultSkipByteBlock;if(n(null!==s&&null!==o),!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 ir,rr;(rr=ir||(ir={}))[rr.EBML=440786851]="EBML",rr[rr.EBMLVersion=17030]="EBMLVersion",rr[rr.EBMLReadVersion=17143]="EBMLReadVersion",rr[rr.EBMLMaxIDLength=17138]="EBMLMaxIDLength",rr[rr.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",rr[rr.DocType=17026]="DocType",rr[rr.DocTypeVersion=17031]="DocTypeVersion",rr[rr.DocTypeReadVersion=17029]="DocTypeReadVersion",rr[rr.Void=236]="Void",rr[rr.Segment=408125543]="Segment",rr[rr.SeekHead=290298740]="SeekHead",rr[rr.Seek=19899]="Seek",rr[rr.SeekID=21419]="SeekID",rr[rr.SeekPosition=21420]="SeekPosition",rr[rr.Duration=17545]="Duration",rr[rr.Info=357149030]="Info",rr[rr.TimestampScale=2807729]="TimestampScale",rr[rr.MuxingApp=19840]="MuxingApp",rr[rr.WritingApp=22337]="WritingApp",rr[rr.Tracks=374648427]="Tracks",rr[rr.TrackEntry=174]="TrackEntry",rr[rr.TrackNumber=215]="TrackNumber",rr[rr.TrackUID=29637]="TrackUID",rr[rr.TrackType=131]="TrackType",rr[rr.FlagEnabled=185]="FlagEnabled",rr[rr.FlagDefault=136]="FlagDefault",rr[rr.FlagForced=21930]="FlagForced",rr[rr.FlagOriginal=21934]="FlagOriginal",rr[rr.FlagHearingImpaired=21931]="FlagHearingImpaired",rr[rr.FlagVisualImpaired=21932]="FlagVisualImpaired",rr[rr.FlagCommentary=21935]="FlagCommentary",rr[rr.FlagLacing=156]="FlagLacing",rr[rr.Name=21358]="Name",rr[rr.Language=2274716]="Language",rr[rr.LanguageBCP47=2274717]="LanguageBCP47",rr[rr.CodecID=134]="CodecID",rr[rr.CodecPrivate=25506]="CodecPrivate",rr[rr.CodecDelay=22186]="CodecDelay",rr[rr.SeekPreRoll=22203]="SeekPreRoll",rr[rr.DefaultDuration=2352003]="DefaultDuration",rr[rr.Video=224]="Video",rr[rr.PixelWidth=176]="PixelWidth",rr[rr.PixelHeight=186]="PixelHeight",rr[rr.DisplayWidth=21680]="DisplayWidth",rr[rr.DisplayHeight=21690]="DisplayHeight",rr[rr.DisplayUnit=21682]="DisplayUnit",rr[rr.AlphaMode=21440]="AlphaMode",rr[rr.Audio=225]="Audio",rr[rr.SamplingFrequency=181]="SamplingFrequency",rr[rr.Channels=159]="Channels",rr[rr.BitDepth=25188]="BitDepth",rr[rr.SimpleBlock=163]="SimpleBlock",rr[rr.BlockGroup=160]="BlockGroup",rr[rr.Block=161]="Block",rr[rr.BlockAdditions=30113]="BlockAdditions",rr[rr.BlockMore=166]="BlockMore",rr[rr.BlockAdditional=165]="BlockAdditional",rr[rr.BlockAddID=238]="BlockAddID",rr[rr.BlockDuration=155]="BlockDuration",rr[rr.ReferenceBlock=251]="ReferenceBlock",rr[rr.Cluster=524531317]="Cluster",rr[rr.Timestamp=231]="Timestamp",rr[rr.Cues=475249515]="Cues",rr[rr.CuePoint=187]="CuePoint",rr[rr.CueTime=179]="CueTime",rr[rr.CueTrackPositions=183]="CueTrackPositions",rr[rr.CueTrack=247]="CueTrack",rr[rr.CueClusterPosition=241]="CueClusterPosition",rr[rr.Colour=21936]="Colour",rr[rr.MatrixCoefficients=21937]="MatrixCoefficients",rr[rr.TransferCharacteristics=21946]="TransferCharacteristics",rr[rr.Primaries=21947]="Primaries",rr[rr.Range=21945]="Range",rr[rr.Projection=30320]="Projection",rr[rr.ProjectionType=30321]="ProjectionType",rr[rr.ProjectionPoseRoll=30325]="ProjectionPoseRoll",rr[rr.Attachments=423732329]="Attachments",rr[rr.AttachedFile=24999]="AttachedFile",rr[rr.FileDescription=18046]="FileDescription",rr[rr.FileName=18030]="FileName",rr[rr.FileMediaType=18016]="FileMediaType",rr[rr.FileData=18012]="FileData",rr[rr.FileUID=18094]="FileUID",rr[rr.Chapters=272869232]="Chapters",rr[rr.Tags=307544935]="Tags",rr[rr.Tag=29555]="Tag",rr[rr.Targets=25536]="Targets",rr[rr.TargetTypeValue=26826]="TargetTypeValue",rr[rr.TargetType=25546]="TargetType",rr[rr.TagTrackUID=25541]="TagTrackUID",rr[rr.TagEditionUID=25545]="TagEditionUID",rr[rr.TagChapterUID=25540]="TagChapterUID",rr[rr.TagAttachmentUID=25542]="TagAttachmentUID",rr[rr.SimpleTag=26568]="SimpleTag",rr[rr.TagName=17827]="TagName",rr[rr.TagLanguage=17530]="TagLanguage",rr[rr.TagString=17543]="TagString",rr[rr.TagBinary=17541]="TagBinary",rr[rr.ContentEncodings=28032]="ContentEncodings",rr[rr.ContentEncoding=25152]="ContentEncoding",rr[rr.ContentEncodingOrder=20529]="ContentEncodingOrder",rr[rr.ContentEncodingScope=20530]="ContentEncodingScope",rr[rr.ContentCompression=20532]="ContentCompression",rr[rr.ContentCompAlgo=16980]="ContentCompAlgo",rr[rr.ContentCompSettings=16981]="ContentCompSettings",rr[rr.ContentEncryption=20533]="ContentEncryption";const ar=[ir.EBML,ir.Segment],sr=[ir.SeekHead,ir.Info,ir.Cluster,ir.Tracks,ir.Cues,ir.Attachments,ir.Chapters,ir.Tags],nr=[...ar,...sr],or=16,cr=e=>{if(e.remainingLength<1)return null;const t=bo(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=bo(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=cr(e);if(null===t)return null;if(e.remainingLength{if(e.remainingLength<1)return null;if(255===bo(e))return;e.skip(-1);const t=lr(e);return null===t?null:72057594037927940!==t?t:void 0},fr=e=>{n(e.remainingLength>=2);const t=dr(e);if(null===t)return null;const i=hr(e);return null===i?null:{id:t,size:i}},mr=(e,t)=>{const i=yo(e,t);let r=0;for(;r{const i=yo(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?Fo(e):Ao(e)},kr=async(e,t,i,r)=>{const a=new Set(i);let s=t;for(;null===r||ss?r:s,found:!1}},yr=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,or);if(ce(t)&&(t=await t),!t)break;const i=fr(t);if(!i)break;const r=i.id;let a=i.size;const s=t.filePos;if(r===ir.EBML){Ar(a);let e=this.reader.requestSlice(s,a);if(ce(e)&&(e=await e),!e)break;this.readContiguousElements(e)}else if(r===ir.Segment){if(await this.readSegment(s,a),void 0===a)break;if(null===this.reader.fileSize)break}else if(r===ir.Cluster){if(null===this.reader.fileSize)break;if(void 0===a){a=(await kr(this.reader,s,nr,this.reader.fileSize)).pos-s}const e=c(this.segments);e&&(e.elementEndPos=s+a)}Ar(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=Ur[o].flag;this.currentSegment[e]=!0,Ar(s);let t=this.reader.requestSlice(n,s);ce(t)&&(t=await t),t&&this.readContiguousElements(t)}else if(a===ir.Tags||a===ir.Attachments){a===ir.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,Ar(s);let e=this.reader.requestSlice(n,s);ce(e)&&(e=await e),e&&this.readContiguousElements(e)}else if(a===ir.Cluster){this.currentSegment.clusterSeekStartPos=t;break}if(void 0===s)break;i=n+s}if(this.currentSegment.seekEntries.sort((e,t)=>e.segmentPosition-t.segmentPosition),null!==this.reader.fileSize)for(const n of this.currentSegment.seekEntries){const t=Ur.find(e=>e.id===n.id);if(!t)continue;if(this.currentSegment[t.flag])continue;let i=this.reader.requestSliceRange(e+n.segmentPosition,2,or);if(ce(i)&&(i=await i),!i)continue;const r=fr(i);if(!r)continue;const{id:a,size:s}=r;if(a!==t.id)continue;Ar(s),this.currentSegment[t.flag]=!0;let o=this.reader.requestSlice(i.filePos,s);ce(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,or);ce(i)&&(i=await i),n(i);const r=e,a=fr(i);n(a);n(a.id===ir.Cluster);let s=a.size;const o=i.filePos;if(void 0===s){s=(await kr(this.reader,o,nr,t.elementEndPos)).pos-o}let l=this.reader.requestSlice(o,s);ce(l)&&(l=await l);const u={segment:t,elementStartPos:r,elementEndPos:o+s,dataStartPos:o,timestamp:-1,trackData:new Map};if(this.currentCluster=u,l){const e=this.readContiguousElements(l,nr);u.elementEndPos=e}for(const[,d]of u.trackData){const e=d.track;n(d.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=d.blocks[d.presentationTimestamps[0].blockIndex],a=d.blocks[c(d.presentationTimestamps).blockIndex];d.startTimestamp=i.timestamp,d.endTimestamp=a.timestamp+a.duration;const s=_(e.clusterPositionCache,d.startTimestamp,e=>e.startTimestamp);-1!==s&&e.clusterPositionCache[s].elementStartPos===r||e.clusterPositionCache.splice(s+1,0,{elementStartPos:u.elementStartPos,startTimestamp:d.startTimestamp})}return t.lastReadCluster=u,u}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=fr(e);if(!i)return!1;if(t&&t.includes(i.id))return!1;const{id:r,size:a}=i,s=e.filePos;switch(Ar(a),r){case ir.DocType:this.isWebM="webm"===mr(e,a);break;case ir.Seek:{if(!this.currentSegment)break;const t={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(t),this.readContiguousElements(e.slice(s,a)),-1!==t.id&&-1!==t.segmentPosition||this.currentSegment.seekEntries.pop()}break;case ir.SeekID:{const t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.id=ur(e,a)}break;case ir.SeekPosition:{const t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.segmentPosition=ur(e,a)}break;case ir.TimestampScale:if(!this.currentSegment)break;this.currentSegment.timestampScale=ur(e,a),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale;break;case ir.Duration:if(!this.currentSegment)break;this.currentSegment.duration=gr(e,a);break;case ir.TrackEntry:if(!this.currentSegment)break;if(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...xe,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!==Nr.Block||e.data.algorithm!==Lr.HeaderStripping)&&(ve._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===br)this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(this.currentTrack.codecId===wr)this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(t===Tr)this.currentTrack.info.codec="vp8";else if(t===Sr)this.currentTrack.info.codec="vp9";else if(t===vr)this.currentTrack.info.codec="av1";else if(t===Pr){const e=this.currentTrack.codecPrivate?m.decode(this.currentTrack.codecPrivate):"";Jt.includes(e)&&(this.currentTrack.info.codec="prores",this.currentTrack.info.proresFormat=e)}const e=this.currentTrack;this.currentTrack.trackBacking=new Vr(e),this.currentSegment.tracks.push(this.currentTrack)}else if("audio"===this.currentTrack.info.type){t===Ir?(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===xr?this.currentTrack.info.codec="mp3":t===Cr?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=ri):t===Br?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Er?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===_r?(this.currentTrack.info.codec="ac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Rr?(this.currentTrack.info.codec="eac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Fr?(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 jr(e),this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null;break;case ir.TrackNumber:if(!this.currentTrack)break;this.currentTrack.id=ur(e,a);break;case ir.TrackType:{if(!this.currentTrack)break;const t=ur(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:{...v},alphaMode:!1,proresFormat:null}:2===t&&(this.currentTrack.info={type:"audio",numberOfChannels:1,sampleRate:8e3,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null,dtsFormat:null})}break;case ir.FlagEnabled:if(!this.currentTrack)break;ur(e,a)||(this.currentTrack=null);break;case ir.FlagDefault:if(!this.currentTrack)break;this.currentTrack.disposition.default=!!ur(e,a);break;case ir.FlagForced:if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!ur(e,a);break;case ir.FlagOriginal:if(!this.currentTrack)break;this.currentTrack.disposition.original=!!ur(e,a);break;case ir.FlagHearingImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!ur(e,a);break;case ir.FlagVisualImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!ur(e,a);break;case ir.FlagCommentary:if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!ur(e,a);break;case ir.CodecID:if(!this.currentTrack)break;this.currentTrack.codecId=mr(e,a);break;case ir.CodecPrivate:if(!this.currentTrack)break;this.currentTrack.codecPrivate=yo(e,a);break;case ir.DefaultDuration:if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=ur(e,a);break;case ir.Name:if(!this.currentTrack)break;this.currentTrack.name=pr(e,a);break;case ir.Language:if(!this.currentTrack)break;if(this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=mr(e,a),$(this.currentTrack.languageCode)||(this.currentTrack.languageCode=q);break;case ir.LanguageBCP47:{if(!this.currentTrack)break;const t=mr(e,a).split("-")[0];this.currentTrack.languageCode=t||q,this.currentTrack.hasLanguageBcp47=!0}break;case ir.Video:if("video"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(s,a));break;case ir.PixelWidth:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.width=ur(e,a);break;case ir.PixelHeight:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.height=ur(e,a);break;case ir.DisplayWidth:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.displayWidth=ur(e,a);break;case ir.DisplayHeight:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.displayHeight=ur(e,a);break;case ir.DisplayUnit:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.displayUnit=ur(e,a);break;case ir.AlphaMode:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.alphaMode=1===ur(e,a);break;case ir.Colour:if("video"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(s,a));break;case ir.MatrixCoefficients:{if("video"!==this.currentTrack?.info?.type)break;const t=ur(e,a),i=T[t];this.currentTrack.info.colorSpace.matrix=i}break;case ir.Range:{if("video"!==this.currentTrack?.info?.type)break;const t=ur(e,a);this.currentTrack.info.colorSpace.fullRange=1===t||2===t?2===t:void 0}break;case ir.TransferCharacteristics:{if("video"!==this.currentTrack?.info?.type)break;const t=ur(e,a),i=b[t];this.currentTrack.info.colorSpace.transfer=i}break;case ir.Primaries:{if("video"!==this.currentTrack?.info?.type)break;const t=ur(e,a),i=k[t];this.currentTrack.info.colorSpace.primaries=i}break;case ir.Projection:if("video"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(s,a));break;case ir.ProjectionPoseRoll:{if("video"!==this.currentTrack?.info?.type)break;const t=-gr(e,a);try{this.currentTrack.info.rotation=o(t)}catch{}}break;case ir.Audio:if("audio"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(s,a));break;case ir.SamplingFrequency:if("audio"!==this.currentTrack?.info?.type)break;this.currentTrack.info.sampleRate=gr(e,a);break;case ir.Channels:if("audio"!==this.currentTrack?.info?.type)break;this.currentTrack.info.numberOfChannels=ur(e,a);break;case ir.BitDepth:if("audio"!==this.currentTrack?.info?.type)break;this.currentTrack.info.bitDepth=ur(e,a);break;case ir.CuePoint:if(!this.currentSegment)break;this.readContiguousElements(e.slice(s,a)),this.currentCueTime=null;break;case ir.CueTime:this.currentCueTime=ur(e,a);break;case ir.CueTrackPositions:{if(null===this.currentCueTime)break;n(this.currentSegment);const t={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(t),this.readContiguousElements(e.slice(s,a)),-1!==t.trackId&&-1!==t.clusterPosition||this.currentSegment.cuePoints.pop()}break;case ir.CueTrack:{const t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;t.trackId=ur(e,a)}break;case ir.CueClusterPosition:{const t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;n(this.currentSegment),t.clusterPosition=this.currentSegment.dataStartPos+ur(e,a)}break;case ir.Timestamp:if(!this.currentCluster)break;this.currentCluster.timestamp=ur(e,a);break;case ir.SimpleBlock:{if(!this.currentCluster)break;const t=lr(e);if(null===t)break;const i=this.getTrackDataInCluster(this.currentCluster,t);if(!i)break;const r=vo(e),n=bo(e),o=n>>1&3;let c=!!(128&n);"audio"===i.track.info?.type&&i.track.info.codec&&(c=!0);const l=yo(e,a-(e.filePos-s)),u=i.track.decodingInstructions.length>0;i.blocks.push({timestamp:r,duration:0,isKeyFrame:c,data:l,lacing:o,decoded:!u,postProcessed:!1,mainAdditional:null})}break;case ir.BlockGroup:if(!this.currentCluster)break;this.readContiguousElements(e.slice(s,a)),this.currentBlock=null;break;case ir.Block:{if(!this.currentCluster)break;const t=lr(e);if(null===t)break;const i=this.getTrackDataInCluster(this.currentCluster,t);if(!i)break;const r=vo(e),n=bo(e)>>1&3,o=yo(e,a-(e.filePos-s)),c=i.track.decodingInstructions.length>0;this.currentBlock={timestamp:r,duration:0,isKeyFrame:!0,data:o,lacing:n,decoded:!c,postProcessed:!1,mainAdditional:null},i.blocks.push(this.currentBlock)}break;case ir.BlockAdditions:this.readContiguousElements(e.slice(s,a));break;case ir.BlockMore:if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(s,a)),this.currentBlockAdditional.data&&1===this.currentBlockAdditional.addId&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null;break;case ir.BlockAdditional:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=yo(e,a);break;case ir.BlockAddID:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=ur(e,a);break;case ir.BlockDuration:if(!this.currentBlock)break;this.currentBlock.duration=ur(e,a);break;case ir.ReferenceBlock:if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1;break;case ir.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(s,a));break;case ir.Targets:this.readContiguousElements(e.slice(s,a));break;case ir.TargetTypeValue:50!==ur(e,a)&&(this.currentTagTargetIsMovie=!1);break;case ir.TagTrackUID:case ir.TagEditionUID:case ir.TagChapterUID:case ir.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case ir.SimpleTag:if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(s,a));break;case ir.TagName:this.currentSimpleTagName=pr(e,a);break;case ir.TagString:{if(!this.currentSimpleTagName)break;const t=pr(e,a);this.processTagValue(this.currentSimpleTagName,t)}break;case ir.TagBinary:{if(!this.currentSimpleTagName)break;const t=yo(e,a);this.processTagValue(this.currentSimpleTagName,t)}break;case ir.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(s,a));const t=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(t.raw??(t.raw={}),t.raw[this.currentAttachedFile.fileUid.toString()]=new Ie(this.currentAttachedFile.fileData,this.currentAttachedFile.fileMediaType??void 0,this.currentAttachedFile.fileName??void 0,this.currentAttachedFile.fileDescription??void 0)),this.currentAttachedFile.fileMediaType?.startsWith("image/")&&this.currentAttachedFile.fileData){const e=this.currentAttachedFile.fileName;let i="unknown";if(e){const t=e.toLowerCase();t.startsWith("cover.")?i="coverFront":t.startsWith("back.")&&(i="coverBack")}t.images??(t.images=[]),t.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:i,name:this.currentAttachedFile.fileName??void 0,description:this.currentAttachedFile.fileDescription??void 0})}this.currentAttachedFile=null}break;case ir.FileUID:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=((e,t)=>{if(t<1)throw new Error("Bad unsigned int size "+t);let i=0n;for(let r=0;rt.order-e.order);break;case ir.ContentEncoding:this.currentDecodingInstruction={order:0,scope:Nr.Block,data:null},this.readContiguousElements(e.slice(s,a)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case ir.ContentEncodingOrder:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=ur(e,a);break;case ir.ContentEncodingScope:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=ur(e,a);break;case ir.ContentCompression:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:Lr.Zlib,settings:null},this.readContiguousElements(e.slice(s,a));break;case ir.ContentCompAlgo:if("decompress"!==this.currentDecodingInstruction?.data?.type)break;this.currentDecodingInstruction.data.algorithm=ur(e,a);break;case ir.ContentCompSettings:if("decompress"!==this.currentDecodingInstruction?.data?.type)break;this.currentDecodingInstruction.data.settings=yo(e,a);break;case ir.ContentEncryption:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}return e.filePos=s+a,!0}decodeBlockData(e,t){n(e.decodingInstructions.length>0);let i=t;for(const r of e.decodingInstructions)if(n(r.data),"decompress"===r.data.type)if(r.data.algorithm===Lr.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){n(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 Hr{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 W(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=_(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=M(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 n(-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(n(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);f(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?yi:r.data,s=r.timestamp/this.internalTrack.segment.timestampFactor,o=r.duration/this.internalTrack.segment.timestampFactor,c={};r.mainAdditional&&"video"===this.internalTrack.info?.type&&this.internalTrack.info.alphaMode&&(c.alpha=i.metadataOnly?yi:r.mainAdditional,c.alphaByteLength=r.mainAdditional.byteLength);const l=new bi(a,r.isKeyFrame?"key":"delta",s,o,e.dataStartPos+t,r.data.byteLength,c);return this.packetToClusterLocation.set(l,{cluster:e,blockIndex:t}),l}async performClusterLookup(e,t,i,r,a){const{demuxer:s,segment:o}=this.internalTrack;let c=null,l=null,u=-1;if(e){const{blockIndex:i,correctBlockFound:r}=t(e);if(r)return this.fetchPacketInCluster(e,i,a);-1!==i&&(l=e,u=i)}const d=_(this.internalTrack.cuePoints,i,e=>e.time),h=-1!==d?this.internalTrack.cuePoints[d]:null,f=_(this.internalTrack.clusterPositionCache,i,e=>e.startTimestamp),m=-1!==f?this.internalTrack.clusterPositionCache[f]:null,p=Math.max(h?.clusterPosition??0,m?.elementStartPos??0)||null;let g;for(e?null===p||e.elementStartPos>=p?(g=e.elementEndPos,c=e):g=p:g=p??o.clusterSeekStartPos;null===o.elementEndPos||g<=o.elementEndPos-2;){if(c){const e=c.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>r)break}let e=s.reader.requestSliceRange(g,2,or);if(ce(e)&&(e=await e),!e)break;const i=g,d=fr(e);if(!d||!sr.includes(d.id)&&d.id!==ir.Void){const e=await yr(s.reader,i,sr,Math.min(o.elementEndPos??1/0,i+qr));if(e){g=e;continue}break}const h=d.id;let f=d.size;const m=e.filePos;if(h===ir.Cluster){c=await s.readCluster(i,o),f=c.elementEndPos-m;const{blockIndex:e,correctBlockFound:r}=t(c);if(r)return this.fetchPacketInCluster(c,e,a);-1!==e&&(l=c,u=e)}if(void 0===f){n(h!==ir.Cluster);f=(await kr(s.reader,m,nr,o.elementEndPos)).pos-m}const p=m+f;if(null===o.elementEndPos){let e=s.reader.requestSliceRange(p,2,or);if(ce(e)&&(e=await e),!e)break;if(dr(e)===ir.Segment){o.elementEndPos=p;break}}g=p}if(h&&(!l||l.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?Xe(a.data):null,hevcCodecInfo:"hevc"===this.internalTrack.info.codec&&a?rt(a.data):null,vp9CodecInfo:"vp9"===this.internalTrack.info.codec&&a?pt(a.data):null,av1CodecInfo:"av1"===this.internalTrack.info.codec&&a?kt(a.data):null,proresCodecInfo:"prores"===this.internalTrack.info.codec&&a?yt(a.data):null,proresFormat:this.internalTrack.info.proresFormat};if(!S(this.internalTrack.info.colorSpace)){const a=ti(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:ei(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 jr extends Hr{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&&qt(e.data)}return{codec:ii({codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,aacCodecInfo:this.internalTrack.info.aacCodecInfo,dtsFormat:this.internalTrack.info.dtsFormat}),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}})()):null}}const Kr=async(e,t,i,r=null)=>{let a=t;for(;null===i||a=4;){const t=s.filePos,i=Io(s),n=null!==e.fileSize?e.fileSize-a:null,o=hi(i,n);if(o.header&&(!r||o.header.sampleRate===r.sampleRate&&o.header.mpegVersionId===r.mpegVersionId&&o.header.layer===r.layer&&gi(o.header.channel)===gi(r.channel)))return{header:o.header,startPos:a};s.filePos=t+o.bytesAdvanced,a=s.filePos}}return null};class Xr extends ki{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 I,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 $r(this)]})())}async advanceReader(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,qo);if(ce(e)&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const t=jo(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}const e=await Kr(this.reader,this.lastLoadedPos,this.reader.fileSize,this.firstFrameHeader);if(!e)return void(this.lastSampleLoaded=!0);const t=e.header;this.lastLoadedPos=e.startPos+t.totalSize-1;const i=di(t.mpegVersionId,t.channel);let r=this.reader.requestSlice(e.startPos+i,4);if(ce(r)&&(r=await r),r){const a=Io(r);if(a===li||a===ui){if(this.xingFrameHeader||(this.xingFrameHeader=t,this.xingFrameHeaderPos=e.startPos),!this.xingData){let t=this.reader.requestSlice(e.startPos+i+4,12);if(ce(t)&&(t=await t),t){const e=yo(t,12),i=f(e),r=i.getUint32(0,!1);this.xingData={frameCount:r&mi.FrameCount?i.getUint32(4,!1):null,fileSize:r&mi.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,qo);if(ce(i)&&(i=await i),!i)break;const r=jo(i);if(!r)break;t=!0;let a=this.reader.requestSlice(i.filePos,r.size);if(ce(a)&&(a=await a),!a)break;Ko(a,r,this.metadataTags),e=i.filePos+r.size}if(!t&&null!==this.reader.fileSize&&this.reader.fileSize>=Uo){let e=this.reader.requestSlice(this.reader.fileSize-Uo,Uo);ce(e)&&(e=await e),n(e);"TAG"===Do(e,3)&&Ho(e,this.metadataTags)}return this.metadataTags}finally{e()}}}class $r{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return n(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(n(null!==e.firstFrameHeader),n(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=_(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 Yr=e=>{const t=f(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},Jr=(e,t,i)=>{let r=0,a=null;if(e.length>0)if("vorbis"===t.codec){n(t.vorbisInfo);const s=(1<<(e=>{let t=0;for(;e;)t++,e>>=1;return t})(t.vorbisInfo.modeBlockflags.length-1))-1<<1,o=(e[0]&s)>>1;if(o>=t.vorbisInfo.modeBlockflags.length)throw new Error("Invalid mode number.");let c=i;const l=t.vorbisInfo.modeBlockflags[o];if(a=t.vorbisInfo.blocksizes[l],1===l){const i=1+(1|s),r=e[0]&i?1:0;c=t.vorbisInfo.blocksizes[r]}r=null!==c?c+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:bt[t]*r}})(e).durationInSamples}return{durationInSamples:r,vorbisBlockSize:a}},Zr=27,ea=282,ta=e=>{const t=e.filePos;if(xo(e)!==Gr)return null;e.skip(1);const i=bo(e),r=Ro(e),a=xo(e),s=xo(e),n=xo(e),o=bo(e),c=new Uint8Array(o);for(let d=0;de+t,0);return{headerStartPos:t,totalSize:l+u,dataStartPos:t+l,dataSize:u,headerType:i,granulePosition:r,serialNumber:a,sequenceNumber:s,checksum:n,lacingValues:c}},ia=(e,t)=>{for(;e.filePos>>8&255)===i||(t>>>16&255)===i||(t>>>24&255)===i){if(e.skip(-4),t===Gr)return!0;e.skip(1)}}return!1};class ra extends ki{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,Zr,ea);if(ce(t)&&(t=await t),!t)break;const i=ta(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 aa(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=f(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:wt(a.data).modeBlockflags},Pt(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=f(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=ri,t.codecInfo.opusInfo={preSkip:a.preSkip},Pt(r.data.subarray(8),this.metadataTags)}async readPacket(e,t){n(te+t.length,0);if(0===c)return null;const l=new Uint8Array(c);let u=0;for(let n=0;n{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 aa{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new I,this.internalSampleRate="opus"===e.codecInfo.codec?ri:e.sampleRate}getType(){return"audio"}getId(){return this.bitstream.serialNumber}getNumber(){const e=this.demuxer.trackBackings.findIndex(e=>e.bitstream===this.bitstream);return n(-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 n(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 q}getDisposition(){return{...xe,primary:!1}}granulePositionToTimestampInSamples(e){return"opus"===this.bitstream.codecInfo.codec?(n(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,i){if(!e)return null;const{durationInSamples:r,vorbisBlockSize:a}=Jr(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),s=new bi(i.metadataOnly?yi: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){n(this.bitstream.lastMetadataPacket);const t=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let i=0;"opus"===this.bitstream.codecInfo.codec&&(n(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=W(e*this.internalSampleRate);if(0===i)return this.getFirstPacket(t);if(i<0)return null;n(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 o=[a];e:for(;a.headerStartPos+a.totalSizei?s=u.headerStartPos:(a=u,o.push(u));continue e}r=u.headerStartPos+u.totalSize}}let c=r.startPage;for(const n of o){if(n.granulePosition===a.granulePosition)break;(!c||n.headerStartPos>c.headerStartPos)&&(c=n)}let l=c;const u=[l];for(;l.serialNumber!==this.bitstream.serialNumber||l.granulePosition!==a.granulePosition;){const e=l.headerStartPos+l.totalSize;let t=this.demuxer.reader.requestSliceRange(e,Zr,ea);ce(t)&&(t=await t),n(t);const i=ta(t);n(i),l=i,l.serialNumber===this.bitstream.serialNumber&&u.push(l)}n(-1!==l.granulePosition);let d,h,f=null,m=l,p=0;if(l.headerStartPos===r.startPage.headerStartPos)d=this.granulePositionToTimestampInSamples(0),h=!0,f=0;else{d=0,h=!1;for(let t=l.lacingValues.length-1;t>=0;t--){if(l.lacingValues[t]<255){f=t+1;break}}if(null===f)throw new Error("Invalid page with granule position: no packets end on this page.");p=f-1;const e={data:yi,endPage:m,endSegmentIndex:p};if(await this.demuxer.findNextPacketStart(e)){const e=na(u,l,f);n(e);const t=sa(u,e.page,e.segmentIndex);t&&(l=t.page,f=t.segmentIndex)}else for(;;){const e=na(u,l,f);if(!e)break;const t=sa(u,e.page,e.segmentIndex);if(!t)break;if(l=t.page,f=t.segmentIndex,e.page.headerStartPos!==m.headerStartPos){m=e.page,p=e.segmentIndex;break}}}let g=null,k=null;for(;null!==l;){n(null!==f);const e=await this.demuxer.readPacket(l,f);if(!e)break;if(!(l.headerStartPos===r.startPage.headerStartPos&&fi||Math.max(a.timestampInSamples,0)===i))break}const a=await this.demuxer.findNextPacketStart(e);if(!a)break;l=a.startPage,f=a.startSegmentIndex}return g}async getPacketSequential(e,t){const i=await this.sequentialScanMutex.acquire();try{const i=W(e*this.internalSampleRate);e=i/this.internalSampleRate;const r=_(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);n(e),this.sequentialScanCache.length>0&&n(c(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 sa=(e,t,i)=>{let r=t,a=i;e:for(;;){for(a--;a>=0;a--){if(r.lacingValues[a]<255){a++;break e}}n(-1===a);if(!(1&r.headerType)){a=0;break}const t=D(e,e=>e.headerStartPos{if(i>0)return{page:t,segmentIndex:i-1};const r=D(e,e=>e.headerStartPos{let e=this.reader.requestSlice(0,12);ce(e)&&(e=await e),n(e);const t=Do(e,4),i="RIFX"!==t,r="RF64"===t,a=Po(e,i);let s=r?this.reader.fileSize:Math.min(a+8,this.reader.fileSize??1/0);if("WAVE"!==Do(e,4))throw new Error("Invalid WAVE file - wrong format");let o=0,c=null,l=e.filePos;for(;null===s||l=18&&357!==a){const e=wo(r,i),s=t-18;if(Math.min(s,e)>=22&&a===oa.EXTENSIBLE){r.skip(6);const e=yo(r,16);a=e[0]|e[1]<<8}}if(a!==oa.MULAW&&a!==oa.ALAW||(c=8),a!==oa.PCM&&a!==oa.IEEE_FLOAT&&a!==oa.ALAW&&a!==oa.MULAW)throw new Error(`Unsupported WAVE codec (format tag ${a}). Only integer/float PCM, A-law, and \u03bc-law are supported.`);if(a===oa.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===oa.IEEE_FLOAT&&![32,64].includes(c))throw new Error(`Unsupported WAVE float bit depth (${c}). Only 32 and 64 bits are supported.`);this.audioInfo={format:a,numberOfChannels:s,sampleRate:n,sampleSizeInBytes:Math.ceil(c/8),blockSizeInBytes:o}}async parseListChunk(e,t,i){var r,a,s,n,o,c,l,u,d,h,f;let m=this.reader.requestSlice(e,t);if(ce(m)&&(m=await m),!m)return;const p=Do(m,4);if("INFO"!==p&&"INF0"!==p)return;let g=m.filePos;for(;g<=e+t-8;){m.filePos=g;const e=Do(m,4),t=Po(m,i),p=yo(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&&((d=this.metadataTags).date??(d.date=new Date(e,0,1)))}break;case"IGNR":case"GENR":(h=this.metadataTags).genre??(h.genre=y);break;case"ICMT":case"CMNT":case"COMM":(f=this.metadataTags).comment??(f.comment=y)}g+=8+t+(1&t)}}async parseId3Chunk(e,t){let i=this.reader.requestSlice(e,t);if(ce(i)&&(i=await i),!i)return;const r=jo(i);if(r){const a=t-qo;if(r.size=Math.min(r.size,a),r.size>0){const t=i.slice(e+qo,r.size);Ko(t,r,this.metadataTags)}}}getCodec(){if(n(this.audioInfo),this.audioInfo.format===oa.MULAW)return"ulaw";if(this.audioInfo.format===oa.ALAW)return"alaw";if(this.audioInfo.format===oa.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===oa.IEEE_FLOAT){if(4===this.audioInfo.sampleSizeInBytes)return"pcm-f32";if(8===this.audioInfo.sampleSizeInBytes)return"pcm-f64"}n(!1)}async getMimeType(){return"audio/wav"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}const ua=2048;class da{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return n(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){const e=this.demuxer.getCodec();return e?(n(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null}getNumberOfChannels(){return n(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return n(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return n(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 n(-1!==this.demuxer.dataSize),this.demuxer.dataSize/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return q}getDisposition(){return{...xe}}async getPacketAtIndex(e,t){n(e>=0),n(this.demuxer.audioInfo);const i=e*ua*this.demuxer.audioInfo.blockSizeInBytes;if(i>=this.demuxer.dataSize)return null;const r=Math.min(ua*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(ce(e)&&(e=await e),!e)return null}let a;if(t.metadataOnly)a=yi;else{let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+i,r);ce(e)&&(e=await e),n(e),a=yo(e,r)}const s=e*ua/this.demuxer.audioInfo.sampleRate,o=r/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(e,this.demuxer.lastKnownPacketIndex),new bi(a,"key",s,o,e,r)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,t){n(this.demuxer.audioInfo);const i=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/ua,(this.demuxer.dataSize-1)/(ua*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;n(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){n(this.demuxer.audioInfo);const i=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/ua);return this.getPacketAtIndex(i+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const ha=e=>{const t=e.filePos,i=yo(e,9),r=new Ce(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}},fa=1024;class ma extends ki{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.trackBackings=[],this.readingMutex=new I,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();n(this.firstFrameHeader),this.trackBackings=[new pa(this)]})())}async advanceReader(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,qo);if(ce(e)&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const t=jo(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}let e=this.reader.requestSliceRange(this.lastLoadedPos,7,9);if(ce(e)&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const t=ha(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=Be[t.samplingFrequencyIndex];n(void 0!==i);const r=fa/i,a={timestamp:this.nextTimestampInSamples/i,duration:r,dataStart:t.startPos,dataSize:t.frameLength};this.loadedSamples.push(a),this.nextTimestampInSamples+=fa,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,qo);if(ce(t)&&(t=await t),!t)break;const i=jo(t);if(!i)break;let r=this.reader.requestSlice(t.filePos,i.size);if(ce(r)&&(r=await r),!r)break;Ko(r,i,this.metadataTags),e=t.filePos+i.size}return this.metadataTags}finally{e()}}}class pa{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return this.getSampleRate()/fa}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 q}getCodec(){return"aac"}getInternalCodecId(){return n(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){n(this.demuxer.firstFrameHeader);const e=Ee[this.demuxer.firstFrameHeader.channelConfiguration];return n(void 0!==e),e}getSampleRate(){n(this.demuxer.firstFrameHeader);const e=Be[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return n(void 0!==e),e}getDisposition(){return{...xe}}async getDecoderConfig(){return n(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=yi;else{let e=this.demuxer.reader.requestSlice(i.dataStart,i.dataSize);if(ce(e)&&(e=await e),!e)return null;r=yo(e,i.dataSize)}return new bi(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=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;)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=_(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,qo);if(ce(e)&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const i=jo(e);if(!i)break;let r=this.reader.requestSlice(e.filePos,i.size);ce(r)&&(r=await r),n(r),Ko(r,i,this.metadataTags),t=e.filePos+i.size}for(t+=4;null===this.reader.fileSize||ts.end-6)return{num:o.num,blockSize:o.blockSize,sampleRate:o.sampleRate,size:s.end-e,isLastFrame:!0};if(255===bo(s)){const t=s.filePos;if(bo(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-o.num!==1){s.filePos=t;continue}}else if(r.num-o.num!==o.blockSize){s.filePos=t;continue}return{num:o.num,blockSize:o.blockSize,sampleRate:o.sampleRate,size:i,isLastFrame:!1}}}}readFlacFrameHeader({slice:e,isFirstPacket:t}){const i=e.filePos,r=yo(e,4),a=new Ce(r);if(32764!==a.readBits(15))return null;if(null===this.blockingBit){n(t);const e=a.readBits(1);this.blockingBit=e}else if(1===this.blockingBit){n(!t);if(1!==a.readBits(1))return null}else{if(0!==this.blockingBit)throw new Error("Invalid blocking bit");n(!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;n(this.audioInfo);const o=((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(!o)return null;a.readBits(4),a.readBits(3);if(0!==a.readBits(1))return null;const c=(e=>{let t=0;const i=new Ce(yo(e,1));for(;1===i.readBits(1);)t++;if(0===t)return i.readBits(7);const r=[],a=t-1,s=new Ce(yo(e,a)),n=8-t-1;for(let o=0;oe|t<"uncommon-u16"===t?To(e)+1:"uncommon-u8"===t?bo(e)+1:"number"===typeof t?t:(N(t),void n(!1)))(e,s),u=((e,t)=>"uncommon-u16"===t?To(e):"uncommon-u16-10"===t?10*To(e):"uncommon-u8"===t?bo(e):"number"===typeof t?t:null)(e,o);if(null===u)return null;if(u!==this.audioInfo.sampleRate)return null;const d=e.filePos-i,h=bo(e);e.skip(-d),e.skip(-1);const f=(e=>{let t=0;for(const i of e){t^=i;for(let e=0;e<8;e++)0!==(128&t)?t=t<<1^7:t<<=1,t&=255}return t})(yo(e,d));return h!==f?null:{num:c,blockSize:l,sampleRate:u}}async advanceReader(){await this.readMetadata(),n(null!==this.lastLoadedPos),n(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 ka{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return n(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return n(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return q}getTimeResolution(){return n(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 n(this.demuxer.audioInfo),0===this.demuxer.audioInfo.totalSamples?null:this.demuxer.audioInfo.totalSamples/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getDisposition(){return{...xe}}async getDecoderConfig(){return n(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(n(this.demuxer.audioInfo),e<0)return null;const i=await this.demuxer.readingMutex.acquire();try{for(;;){const i=_(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=yi;else{let e=this.demuxer.reader.requestSlice(i.byteOffset,i.byteSize);if(ce(e)&&(e=await e),!e)return null;r=yo(e,i.byteSize)}n(this.demuxer.audioInfo);const a=i.blockOffset/this.demuxer.audioInfo.sampleRate,s=i.blockSize/this.demuxer.audioInfo.sampleRate;return new bi(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 ya=9e4,ba=2**33,wa=188,Ta="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.",Sa=new Set([133,134,162]),va=new Set;class Pa extends ki{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);ce(e)&&(e=await e),n(e);const t=yo(e,205);if(71===t[0]&&71===t[188])this.packetOffset=0,this.packetStride=wa;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 o=3,c=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 Ce(t.payload),i=e.readAlignedByte();e.skipBits(8*i);l=2===e.readBits(8)}}if(0!==t.pid||a)if(t.pid!==r&&!l||s){const e=this.elementaryStreams.find(e=>e.pid===t.pid);e:if(e&&!e.initialized){const i=xa(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 Ra(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=Xe(r.suppliedPacket.data),!e.info.avcCodecInfo)continue;const t=e.info.avcCodecInfo.sequenceParameterSets[0];n(t);const i=Ye(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:k[i.colourPrimaries],transfer:b[i.transferCharacteristics],matrix:T[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=rt(r.suppliedPacket.data),!e.info.hevcCodecInfo)continue;const t=e.info.hevcCodecInfo.arrays.find(e=>e.nalUnitType===Oe.SPS_NUT).nalUnits[0];n(t);const i=it(t);e.info.width=i.displayWidth,e.info.height=i.displayHeight,i.pixelAspectRatio.num>i.pixelAspectRatio.den?(e.info.squarePixelWidth=Math.round(e.info.width*i.pixelAspectRatio.num/i.pixelAspectRatio.den),e.info.squarePixelHeight=e.info.height):(e.info.squarePixelWidth=e.info.width,e.info.squarePixelHeight=Math.round(e.info.height*i.pixelAspectRatio.den/i.pixelAspectRatio.num)),e.info.colorSpace={primaries:k[i.colourPrimaries],transfer:b[i.transferCharacteristics],matrix:T[i.matrixCoefficients],fullRange:!!i.fullRangeFlag},e.info.reorderSize=i.maxDecFrameBuffering;break}throw new Error("Unhandled.")}e.info.decoderConfig={codec:ei({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=go.tempFromBytes(r.suppliedPacket.data),i=ha(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=Ee[i.channelConfiguration],e.info.sampleRate=Be[i.samplingFrequencyIndex]}else if("mp3"===e.info.codec){const t=Io(go.tempFromBytes(r.suppliedPacket.data)),i=hi(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=gi(i.header.channel),e.info.sampleRate=i.header.sampleRate}else if("ac3"===e.info.codec){const t=xt(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=It[t.acmod]+t.lfeon,e.info.sampleRate=Ae[t.fscod]}else if("eac3"===e.info.codec){const t=Et(r.suppliedPacket.data);if(!t)throw new Error("Invalid E-AC-3 audio stream; could not read sync frame from first packet.");const i=_t(t);if(null===i)throw new Error("Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.");e.info.numberOfChannels=Rt(t),e.info.sampleRate=i}else{if("dts"!==e.info.codec)throw new Error("Unhandled.");{const t=Ut(r.suppliedPacket.data);if(!t)throw new Error("Invalid DTS audio stream; could not read frame header from first packet.");e.info.numberOfChannels=t.numberOfChannels,e.info.sampleRate=t.sampleRate,t.core&&(e.info.dtsFormat=t.hasExtensions?"dtsh":"dtsc")}}e.info.decoderConfig={codec:ii({codec:e.info.codec,codecDescription:null,aacCodecInfo:e.info.aacCodecInfo,dtsFormat:e.info.dtsFormat}),numberOfChannels:e.info.numberOfChannels,sampleRate:e.info.sampleRate},e.initialized=!0}}}else{const e=new Ce(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),n=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=n;8*(r+o)-e.pos>c;){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&&Sa.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:va.has(t)||(ve._warn(`Note: MPEG-TS streams with stream_type 0x${t.toString(16)} are not currently supported.`),va.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 Ce(t.payload),i=e.readAlignedByte();e.skipBits(8*i),e.skipBits(14);const s=e.readBits(10);for(e.skipBits(40);8*(s+o)-e.pos>c;){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 Ba(n)):this.trackBackingEntries.push(new Ea(n)))})())}async getTrackBackings(){return await this.readMetadata(),this.trackBackingEntries}async getMetadataTags(){return{}}async getMimeType(){await this.readMetadata();return(e=>{let t="video/MP2T";const i=[...new Set(e.filter(Boolean))];return i.length>0&&(t+=`; codecs="${i.join(", ")}"`),t})(await Promise.all(this.trackBackingEntries.map(e=>e.getDecoderConfig().then(e=>e?.codec??null))))}async readSection(e,t,i=!1){let r=e,a=e;const s=[];let n,o=0,c=null,l=!0,u=0;for(;;){const e=await this.readPacket(a);if(a+=this.packetStride,!e)break;if(c){if(e.pid!==c.pid){if(i)break;continue}if(1===e.payloadUnitStartIndicator)break}else{if(0===e.payloadUnitStartIndicator)break;c=e}const n=!!(2&e.adaptationFieldControl),d=!!(1&e.adaptationFieldControl);let h=0;if(n&&(h=1+e.body[0],e===c&&h>1&&(u=e.body[1]>>6&1)),d&&(0===h?(s.push(e.body),o+=e.body.byteLength):(s.push(e.body.subarray(h)),o+=e.body.byteLength-h)),r=a,!t&&o>=64){l=!1;break}if(-1!==E(this.sectionEndPositions,r,e=>e)){l=!1;break}}if(l){const e=_(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(ce(t)&&(t=await t),!t)return null;if(71!==bo(t))throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");const i=To(t);return{payloadUnitStartIndicator:i>>14&1,pid:8191&i,adaptationFieldControl:bo(t)>>4&3}}async readPacket(e){let t=this.reader.requestSlice(e,wa);if(ce(t)&&(t=await t),!t)return null;const i=yo(t,wa);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>=ba-t?-8589934592:ba}}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 Ce(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(Ta);return{sectionStartPos:t.startPos,sectionEndPos:t.endPos,pts:n,randomAccessIndicator:t.randomAccessIndicator}},xa=(e,t,i)=>{n(null!==t.endPos);const r=Ia(e,t,i);if(!r)return null;const a=new Ce(t.payload);a.skipBits(32);const s=a.readBits(16);a.skipBits(16);const o=a.readBits(8),c=a.pos+8*o;a.pos=c;const l=c/8;n(Number.isInteger(l));const u=t.payload.subarray(l,s>0?6+s:t.payload.byteLength);return{...r,data:u}};class Ca{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++,n(r instanceof Ca),r.elementaryStream===this.elementaryStream)break;return i}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.elementaryStream.streamType}getName(){return null}getLanguageCode(){return q}getDisposition(){return{...xe,primary:!1}}getTimeResolution(){return ya}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 bi(i.metadataOnly?yi:e.data,r,e.pts/ya,Math.max(t/ya,0),e.sequenceNumber,e.data.byteLength)}async getFirstPacket(e){const t=this.elementaryStream.firstSection;n(t);const i=xa(this.elementaryStream.demuxer,t,!0);n(i);const r=new Ra(this.elementaryStream,i),a=new Fa(this,r),s=await a.readNext();if(!s)return null;const o=this.createEncodedPacket(s.packet,s.duration,e);return this.packetBuffers.set(o,a),this.packetSectionStarts.set(o,s.packet.sectionStartPos),o}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);n(s);const o=xa(a,s,!0);n(o);const c=new Ra(this.elementaryStream,o);i=new Fa(this,c);const l=e.sequenceNumber;for(;;){const e=await 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}}}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=W(e*ya),a=this.elementaryStream.demuxer,{reader:s,seekChunkSize:o}=a,l=this.elementaryStream.pid,u=async(e,t,i)=>{let r=e;for(;re.pts),g=-1!==p?m[p]:null;if(g&&r-g.pts<45e3)f=g.sectionStartPos;else{let e=0;if(null!==s.fileSize){const t=Math.ceil(s.fileSize/o);if(t>1){let i=0,s=t-1;for(e=i;i<=s;){const t=Math.floor((i+s)/2),n=j(t*o,a.packetStride)+h.sectionStartPos,c=n+o,l=await u(n,c,!1);l?l.pesPacketHeader.pts<=r?(e=t,i=t+1):s=t-1:s=t-1}}}f=j(e*o,a.packetStride)+h.sectionStartPos}const k=await u(f,s.fileSize??1/0,!1);let y=k?.pesPacketHeader??null;y||(y=h);const b=this.getReorderSize(),w=async(e,t)=>{const s=await a.readSection(e,!0);n(s);const o=xa(a,s,!0);n(o);const l=new Ra(this.elementaryStream,o),u=new Fa(this,l);for(;;){if((c(u.presentationOrderPackets)?.pts??-1/0)>=r)break;if(!(await u.readNextPacket()))break}const d=M(u.presentationOrderPackets,t);if(-1===d)return null;const h=u.presentationOrderPackets[d],f=0===d?0:h.pts-u.presentationOrderPackets[d-1].pts;for(;u.decodeOrderPackets[0]!==h;)u.decodeOrderPackets.shift();u.lastDuration=f;const m=await u.readNext();n(m);const p=this.createEncodedPacket(m.packet,m.duration,i);return this.packetBuffers.set(p,u),this.packetSectionStarts.set(p,m.packet.sectionStartPos),p};if(!t||this.allPacketsAreKeyPackets()){e:for(;;){let e=y.sectionStartPos+a.packetStride;for(;;){const t=await a.readPacketHeader(e);if(!t)break e;if(t.pid===l&&1===t.payloadUnitStartIndicator){const t=await a.readSection(e,!1);if(t){const e=Ia(a,t,!1);if(e&&null!==e.pts){if(e.pts>r)break e;y=e,_a(this.elementaryStream,y);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===l&&1===t.payloadUnitStartIndicator){const t=await a.readSection(e,!1);if(t){const e=Ia(a,t,!1);if(e&&null!==e.pts){y=e;break}}}e-=a.packetStride}}return w(y.sectionStartPos,e=>e.pts<=r)}{let e=f,t=null;const i=!this.elementaryStream.canBeTrustedWithKeyPackets;for(;;){let c=null;const f=e<=h.sectionStartPos;let m,p=null;if(f)m=h,p=d;else{const t=await u(e,s.fileSize??1/0,i);m=t?.pesPacketHeader??null,p=t?.section??null}let g=!1,k=0;e:for(;m&&!(null!==t&&m.sectionStartPos>=t);){if(m.pts<=r){let e;if(this.elementaryStream.canBeTrustedWithKeyPackets)e=1===m.randomAccessIndicator;else{n(p);const t=xa(a,p,!0);n(t);const i=new Ra(this.elementaryStream,t);await i.markNextPacket(),e=1===i.suppliedPacket?.randomAccessIndicator}e&&(c=m)}if(m.pts>r&&(g=!0),g&&(k++,k>b))break;let e=m.sectionStartPos+a.packetStride;for(;;){const t=await a.readPacketHeader(e);if(!t)break e;if(t.pid===l&&1===t.payloadUnitStartIndicator){const t=await a.readSection(e,i);if(t){const e=Ia(a,t,!1);if(e&&null!==e.pts){m=e,p=t,_a(this.elementaryStream,m);break}}}e+=a.packetStride}}if(c){let e=c;if(0===k)e:for(let r=0;r=a.packetOffset;){const r=await a.readPacketHeader(t);if(!r)break e;if(r.pid===l&&1===r.payloadUnitStartIndicator){const r=await a.readSection(t,i);if(r){const t=Ia(a,r,!1);if(t&&null!==t.pts){e=t;break}}}t-=a.packetStride}}const t=await w(e.sectionStartPos,e=>e.pts<=r&&1===e.randomAccessIndicator);return n(t),t}if(f)return null;t=e,e=Math.max(j(e-h.sectionStartPos-o,a.packetStride)+h.sectionStartPos,h.sectionStartPos)}}}}class Ba extends Ca{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 n(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}}class Ea extends Ca{getType(){return"audio"}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}async getDecoderConfig(){return n(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 0}}const _a=(e,t)=>{const i=e.referencePesPackets,r=_(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 n(e),e}async bufferData(e){const t=this.endPos+e;for(;this.endPos=u)break;d=e;const i=o+d;if(d+3>=u){this.seekTo(i);break}const h=c[d+1],f=c[d+2],m=c[d+3];let p=0;if(0===h&&0===f&&1===m?p=4:0===h&&1===f&&(p=3),0===p){d++;continue}const g=i;a??(a=g);const k=d+p,y=k+r,b=6;if(y+("avc"===t?b:1)>u){this.seekTo(i);break}const w=c[k];let T,S,v;if("avc"===t)T=We(w),S=T===Me.NON_IDR_SLICE||T===Me.SLICE_DPA||T===Me.IDR,v=T===Me.SEI||T===Me.SPS||T===Me.PPS||T===Me.AUD;else{T=tt(w);if(((1&w)<<5|c[k+1]>>3)>0){d+=p;continue}S=T<=Oe.RASL_R||T>=Oe.BLA_W_LP&&T<=21,v=T>=Oe.VPS_NUT&&T<=37||T===Oe.PREFIX_SEI_NUT||T>=41&&T<=44||T>=48&&T<=55}let P=!1;if(S){let e;if("avc"===t){const t=c.subarray(y,y+b),i=l(new Ce(t));e=!s||i<=n,n=i}else e=c[y]>>7===1;e&&(s?P=!0:s=!0)}else v&&s&&(P=!0);if(P){const e=g-a;return this.seekTo(a),this.supplyPacket(e,0)}d+=p}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);ce(r)&&(r=await r);const a=this.currentPos;for(;this.currentPos-a>6,o=63&a[4];if(3===s||o>37){this.seekTo(t+1);continue}const c=Ct[3*o+s];n(void 0!==c),this.seekTo(t),r=this.ensureBuffered(c),ce(r)&&(r=await r);const l=Math.round(13824e4/e.info.sampleRate);return this.supplyPacket(r,l)}if("eac3"===t){if(11!==i)continue;this.skip(-1);const t=this.currentPos;let r=this.ensureBuffered(5);if(ce(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=Bt[n];this.seekTo(t),r=this.ensureBuffered(s),ce(r)&&(r=await r);const c=256*o,l=Math.round(c*ya/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(ce(r)&&(r=await r),r<18)return;const a=this.readBytes(18),s=Wt(a);let n=s?null:Ht(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);ce(i)&&(i=await i),n=Ht(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(ce(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(n(-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(n(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 Aa="application/vnd.apple.mpegurl",Da="#EXT-X-STREAM-INF:",Ma="#EXT-X-I-FRAME-STREAM-INF:",Na="#EXT-X-MEDIA:",Oa="#EXTINF:",La="#EXT-X-MAP:",za="#EXT-X-KEY:",Ua="#EXT-X-MEDIA-SEQUENCE:",qa="#EXT-X-BYTERANGE:",Wa="#EXT-X-PROGRAM-DATE-TIME:",Ha="#EXT-X-TARGETDURATION:",Va="#EXT-X-PLAYLIST-TYPE:",ja=e=>0===e.length||e.startsWith("#")&&!e.startsWith("#EXT");class Ka{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=pe(e,e=>"video"===e.getType())+1;e.push(new Ga(this,t,i))}else if("audio"===t.type){const i=pe(e,e=>"audio"===e.getType())+1;e.push(new Qa(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=pe(e,e=>"video"===e.getType())+1;e.push(new Ga(this,{id:e.length+1,type:"video"},t))}else if("audio"===r.type){const t=pe(e,e=>"audio"===e.getType())+1;e.push(new Qa(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 $a{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(),n(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){n(e.sequenceNumber>=0),n(this.segmentedInput.firstSegment);const r=await this.segmentedInput.getMediaOffset(t,i.input),a=t.timestamp-this.segmentedInput.firstSegment.timestamp,s=e.clone({timestamp:V(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(),n(this.firstInputTrack),n(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 Ga extends $a{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 Qa extends $a{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())}}he();const Ya=1/0;"undefined"!==typeof FinalizationRegistry&&new FinalizationRegistry(e=>{e()});class Ja extends we{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 mo;return this._sizePromise??(this._sizePromise=(async()=>{let e=this._getFileSize();return void 0!==e||(await this._read(0,1,0,Ya),e=this._getFileSize(),n(void 0!==e)),e})())}async getSize(){if(this._disposed)throw new mo;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 fs(this,e,t)}_dispatchRead(e,t){this.onread?.(e,t),this._emit("read",{start:e,end:t})}ref(){return new Za(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){this._refCount--,0===this._refCount&&(this._dispose(),this._disposed=!0)}}class Za{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;n(e._refCount>0),e._decrementRefCount(),e._refFinalizationRegistry?.unregister(this),this._freed=!0,this._source=null}[Symbol.dispose](){this.freed||this.free()}}class es extends Ja{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 Ja||e instanceof Za))throw new TypeError("requestHandler must return or resolve to a Source or SourceRef.");const i=e instanceof Ja?e.ref():e;return(t=i.source)._usedForHls||(t._usedForHls=this._usedForHls),i};return ce(t)?t.then(i):i(t)}}const ts=(e,t)=>e.path===t.path;class is extends es{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 Ja?e.ref():e;return this._root=t,this._rootRequest=null,t};ce(e)?this._rootRequest=e.then(t):(t(e),n(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 rs="undefined"!==typeof FinalizationRegistry?new FinalizationRegistry(e=>{e.cancel().catch(()=>{})}):null;class as extends Ja{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&&(!fe(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 hs({maxCacheSize:t.maxCacheSize??8388608,maxWorkerCount:4,runWorker:this._runWorker.bind(this),onIdleWorkerRemoved:e=>{const t=this._readers.get(e);t&&(this._readers.delete(e),rs?.unregister(e),t.cancel().catch(()=>{}))},prefetchProfile:ds.fileSystem,handleUnhandledError:t.handleUnhandledError}),this._orchestrator.fileSize=e.size}_getFileSize(){return this._orchestrator.fileSize}_read(e,t,i,r){return this._orchestrator.read(e,t,i,r)}async _runWorker(e){n(e.strictTarget);let t=this._readers.get(e);if(void 0===t){if("stream"in this._blob&&!te()&&!1!==this._options.useStreamReader){t=this._blob.slice(e.currentPos).stream().getReader(),rs?.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 ve._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)},ns=new Set;class os extends es{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&&(!fe(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 os(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??ss,this._requestInit={...t.requestInit};let i=null;if(t.requestInit?.headers){const e={...Y(t.requestInit.headers)},r=Object.keys(e).find(e=>"range"===e.toLowerCase());void 0!==r&&(i=e[r],delete e[r],this._requestInit.headers=e)}if(e instanceof Request){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=ls(i);e&&(this._offset=e.offset,this._length=e.length)}this._orchestrator=new hs({maxCacheSize:t.maxCacheSize??67108864,maxWorkerCount:t.parallelism??2,runWorker:this._runWorker.bind(this),prefetchProfile:ds.network,handleUnhandledError:t.handleUnhandledError})}_getFileSize(){if(!this._fileSizeDetermined)return null!==this._length?this._length:void 0;const e=this._sequentialBacking?this._sequentialBacking._endIndex:this._orchestrator.fileSize;return null===e?null!==this._length?this._length:null:U(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 ce(s)?s.then(n):n(s)}async _runWorker(e){for(;;){const i=new AbortController,r=await J(this._options.fetchFn??fetch,this._url,Q(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")||ns.has(e.origin)||(ve._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.`),ns.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){ve._error("Error while reading response stream. Attempting to resume.",t),await be(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;ve._error("Error while reading response stream. Attempting to resume.",a),await be(1e3*e);const s=await J(this._options.fetchFn??fetch,this._url,Q(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 us(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 o=new Set;for(const n of this._orchestrator.workers){for(const e of n.pendingSlices)o.add(e);n.aborted=!0,n.pendingSlices.length=0}for(const n of this._orchestrator.queuedReads)for(const e of n.pendingSlices)o.add(e);this._orchestrator.workers.length=0,this._orchestrator.queuedReads.length=0;for(const c of o){const e=s._read(c.start,c.start+c.bytes.length);ce(e)?e.then(e=>{e?(n(e.offset===c.start),c.resolve(e.bytes)):c.resolve(null)},e=>c.reject(e)):(n(null===e),c.resolve(null))}}_dispose(){this._orchestrator.dispose(),this._sequentialBacking&&(this._sequentialBacking._disposed=!0,this._sequentialBacking._dispose())}}const cs=/^bytes=(\d+)-(\d*)$/,ls=e=>{const t=cs.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=_(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}=F();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 mo);this._pendingSlices.length=0,this._cache.length=0,this._reader?.cancel()}}const ds={fileSystem:(e,t)=>{const i=65536;return{start:e=Math.floor((e-i)/i)*i,end:t=Math.ceil((t+i)/i)*i}},network:(e,t,i)=>{const r=65536;e=Math.max(0,Math.floor((e-r)/r)*r);for(const a of i){const i=8388608,r=Math.max((a.startPos+a.targetPos)/2,a.targetPos-i);if(ue(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 hs{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){n(!this.disposed);const a=this.options.prefetchProfile(e,t,this.workers),s=Math.max(a.start,i),o=Math.min(a.end,this.fileSize??1/0,r);n(s<=e&&t<=o);let c=null;const l=_(this.cache,e,e=>e.start),u=-1!==l?this.cache[l]:null;u&&u.start<=e&&t<=u.end&&(u.age=this.nextAge++,c={bytes:u.bytes,view:u.view,offset:u.start});const d=_(this.cache,s,e=>e.start),h=c?null:new Uint8Array(t-e);let m=0,p=s;const g=[];if(-1!==d){for(let i=d;i=o)break;if(r.end<=s)continue;const a=Math.max(s,r.start),c=Math.min(o,r.end);if(n(a<=c),p=h.length&&(c={bytes:h,view:f(h),offset:e}),0===g.length)return n(c),c;const{promise:k,resolve:y,reject:b}=F(),w=[];for(const n of g){const i=Math.max(e,n.start),r=Math.min(t,n.end);i===n.start&&r===n.end?w.push(n):ie.hole.start),i=-1!==t?this.queuedReads[t]:null;for(i&&n.start<=i.hole.end?(i.hole.end=Math.max(i.hole.end,n.end),i.strictTarget&&(i.strictTarget=e),T&&i.pendingSlices.push(T)):(t++,i={hole:{start:n.start,end:n.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 c?k.catch(e=>{if(!this.disposed){if(!this.options.handleUnhandledError)throw e;this.options.handleUnhandledError(e)}}):(n(h),c=k.then(t=>t&&{bytes:t,view:f(t),offset:e})),c}checkHoleAgainstWorker(e,t,i){if(ue(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);n(-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=_(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=f(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=f(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 ce(a)?a.then(s):s(a)}_dispose(){this._ref?.free()}ref(){return this._ref??(this._ref=this._baseSource.ref()),super.ref()}}var ms=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},ps=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 gs=/^0[xX][0-9a-fA-F]+$/,ks=/^data:.*;base64,/i;class ys extends Xa{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 be(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=ms(t,await this.demuxer.input._getSourceUncached({path:this.rootPath,isRoot:!1}),!1),r=new po(i.source),a=await r.requestEntireFile();n(a),e=Mo(a,a.length,{ignore:ja}),i.source instanceof es&&(this.rootPath=i.source.rootPath)}catch(T){t.error=T,t.hasError=!0}finally{ps(t)}}const t=!1!==this.input._formatOptions.hls?.offsetTimestampsByDateTime;let i=!1,r=0,a=null,s=null,o=null,l=0,u=null,d=null,h=null,m=null,p=null,g=null,k=!1,y=c(this.segments)??null;const b=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}},w=e=>{l=e,y&&(n(null!==y.sequenceNumber),y.sequenceNumber0&&null!==g&&(r=l*g),k=!0);const e=T.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(T.startsWith(La)){const e=new Ka(T.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 n=null;if(null!==i&&(n=b(i)),n&&null===n.offset)throw new Error("Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset.");if(!y){const e={path:me(this.rootPath,t),offset:n?.offset??0,length:n?.length??null};if("AES-128"===o?.method&&!o.iv)throw new Error("IV attribute must be set on #EXT-X-KEY tag preceding the #EXT-X-MAP tag.");d={timestamp:r,unixEpochTimestamp:a,firstSegment:null,sequenceNumber:null,location:e,duration:0,encryption:o,initSegment:null,lastProgramDateTimeSeconds:p}}s=null,null===m?h=null:m=null}else if(T.startsWith(za)){const e=new Ka(T.slice(11)),t=e.get("method");if("NONE"===t)o=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(!gs.test(r))throw new Error(`Unsupported IV format '${r}'.`);let e=r.slice(2);e=e.padStart(32,"0"),i=new Uint8Array(Bi);for(let t=0;t=8&&112===t[4]&&115===t[5]&&115===t[6]&&104===t[7]){const e=f(t).getUint32(0);r=wi(t.subarray(8,Math.min(e,t.length)))}}o={method:t,psshBox:r}}}}else if(T.startsWith(Ua)){const e=T.slice(22),t=Number(e);if(!Number.isInteger(t)||t<0)throw new Error(`Invalid EXT-X-MEDIA-SEQUENCE value '${e}'.`);w(t)}else if(T.startsWith(qa)){const e=b(T.slice(17));if(null===e.offset){if(null===h)throw new Error("Invalid M3U8 file; #EXT-X-BYTERANGE without offset requires a previous byte range.");e.offset=h}m=e,h=e.offset+e.length}else if(T.startsWith(Wa)){if(y)continue;const e=T.slice(25),i=Date.parse(e);if(!Number.isFinite(i))continue;const s=i/1e3;if(p===s)continue;if(null===p&&this.segments.length>0){const e=c(this.segments),i=s-(e.timestamp+e.duration);for(const r of this.segments)r.unixEpochTimestamp=r.timestamp+i,t&&(r.timestamp=r.unixEpochTimestamp)}p=s,a=s,t&&(r=s)}else if("#EXT-X-DISCONTINUITY"===T)u=null;else if(T.startsWith(Ha)){const e=T.slice(22),t=Number(e);if(!Number.isFinite(t)||t<0)throw new Error(`Invalid EXT-X-TARGETDURATION value '${e}'.`);this.refreshInterval=t,g=t}else{if("#EXT-X-ENDLIST"===T){this.streamHasEnded=!0;break}if(T.startsWith(Va)){"vod"===T.slice(21).toLowerCase()&&(this.streamHasEnded=!0)}}}else{if("#EXTM3U"!==T)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=_(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=>Ti(e,r))||(i=[...i,r]),this.input._formatOptions.isobmff.resolveKeyId({...e,psshBoxes:i})})}},s=new ho({source:new is(t.location.path,async e=>{n(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;n(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 o=((e,t,i)=>{let r=!1,a=0;const s=new Oi;return new ReadableStream({pull:async n=>{r||(s.init(await t()),r=!0);let o=e.requestSliceRange(a,0,65552);if(ce(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=yo(o,l),d=new Uint8Array(l);for(let e=0;e16)throw new Error("Invalid PKCS#7 padding. Incorrect key or corrupted data.");const t=d.subarray(0,l-e);n.enqueue(t),n.close(),i()}},cancel:()=>{i()}})})(new po(s.source),async()=>{const t={stack:[],error:void 0,hasError:!1};try{const i=ms(t,await this.input._getSourceCached({path:e.keyUri,isRoot:!1},uo),!1),r=new po(i.source),a=await r.requestSlice(0,Bi);if(!a)throw new Error("Invalid AES-128 key; expected at least 16 bytes of data.");return{key:yo(a,Bi),iv:e.iv}}catch(i){t.error=i,t.hasError=!0}finally{ps(t)}},()=>{s.free()});r=new us(o).ref()}else n(!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 Ls)),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=ge(this.inputCache,e=>e.age);n(-1!==e),this.inputCache.splice(e,1)}return s}async getLiveRefreshInterval(){return 0===this.getRemainingWaitTimeMs()&&await this.runUpdateSegments(),this.streamHasEnded?null:this.refreshInterval}}class bs extends ki{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()=>{n(this.input._rootSource instanceof es);const e=await this.input._reader.requestEntireFile();n(e);const t=Mo(e,e.length,{ignore:ja}),{rootPath:i}=this.input._rootSource,r=[],a=[];for(let n=1;n"video"===e.attributes.get("type").toLowerCase()).map(e=>e.attributes.get("group-id")))],o=[...new Set(a.filter(e=>"audio"===e.attributes.get("type").toLowerCase()).map(e=>e.attributes.get("group-id")))],c=await Promise.all(r.map(async(e,t)=>{const r=[],c=e.attributes.get("codecs");let l;if(c)l=c.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()})));l=await Promise.all(r.filter(e=>null!==e.codec).map(e=>e.track.getDecoderConfig().then(e=>e.codec)))}const u=e.attributes.get("video"),d=e.attributes.get("audio"),h=l.some(e=>jt.includes(ni(e))),f=l.some(e=>Xt.includes(ni(e)));if(null!==u&&!h){if(!s.includes(u))throw new Error(`Invalid M3U8 file; variant stream references video 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&&"video"===i.toLowerCase()});e:if(e){const t=e.attributes.get("uri");if(null===t)break e;const r=me(i,t),a=this.getSegmentedInputForPath(r),s=(await a.getTrackBackings()).find(e=>"video"===e.getType());if(!s||null===await s.getCodec())break e;const o=await s.getDecoderConfig().then(e=>e?.codec??null);n(null!==o),l.push(o)}}if(null!==d&&!f){if(!o.includes(d))throw new Error(`Invalid M3U8 file; variant stream references audio group "${d}" 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===d&&"audio"===i.toLowerCase()});e:if(e){const t=e.attributes.get("uri");if(null===t)break e;const r=me(i,t),a=this.getSegmentedInputForPath(r),s=(await a.getTrackBackings()).find(e=>"audio"===e.getType());if(!s||null===await s.getCodec())break e;const o=await s.getDecoderConfig().then(e=>e?.codec??null);n(null!==o),l.push(o)}}l=[...new Set(l)];let m=null,p=null;const g=e.attributes.getAsNumber("bandwidth");n(null!==g);const k=e.attributes.getAsNumber("average-bandwidth"),y=e.attributes.get("name");for(const i of l){const n=ni(i);if(null!==n)if(jt.includes(n)){if(null!==m)throw new Error("Unsupported M3U8 file; multiple video codecs found in the CODECS attribute of a variant stream.");m=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:q,lineNumber:e.lineNumber,fullPath:e.fullPath,fullCodecString:m,pairingMask:1n<0?a:null}})}else{if(!o.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:vs(i.attributes),autoselect:vs(i.attributes)||Ps(i.attributes),languageCode:Is(i.attributes.get("language")),lineNumber:i.lineNumber,fullPath:i.fullPath??e.fullPath,fullCodecString:p,pairingMask:1n<0?c:null}})}}}}return r})),l=[],u=e=>{const t=l.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===q&&(t.languageCode=e.languageCode)):(e.id=l.length+1,l.push(e))};for(const n of c)for(const e of n)u(e);l.sort((e,t)=>e.lineNumber-t.lineNumber),this.trackBackings=[];for(const n of l)"video"===n.info.type?this.trackBackings.push(new Ts(n)):this.trackBackings.push(new Ss(n));this.internalTracks=l})())}async getTrackBackings(){return await this.readMetadata(),n(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 ys(this,e,i,null),this.segmentedInputs.push(t),t}async getMetadataTags(){return{}}async getMimeType(){return Aa}dispose(){if(this.segmentedInputs){for(const e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}}class ws{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 Ts){for(const r of i)if(await r.getCodec()===this.getCodec()){t=r;break}}else{n(this instanceof Ss);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{...xe,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(){n(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 Ts extends ws{constructor(e){super(e)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return"video"}getCodec(){return ni(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 Ss extends ws{constructor(e){super(e)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return"audio"}getCodec(){return ni(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 vs=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}".`)},Ps=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}".`)},Is=e=>{if(null===e)return q;const t=e.split("-")[0];return t||q};class xs{constructor(){this._isIsobmff=!1}}class Cs extends xs{constructor(){super(...arguments),this._isIsobmff=!0}async _getMajorBrand(e){let t=e._reader.requestSlice(0,12);if(ce(t)&&(t=await t),!t)return null;t.skip(4);const i=Do(t,4);return"ftyp"!==i&&"styp"!==i?null:Do(t,4)}_createDemuxer(e){return new Li(e)}}class Bs extends Cs{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(ce(t)&&(t=await t),!t)return!1;let r=Io(t),a=8;if(1===r){let t=e._reader.requestSlice(i+8,8);if(ce(t)&&(t=await t),!t)return!1;r=Eo(t),a=16}if(r8)return!1;if(ur(i,r)!==ir.EBML)return!1;const a=hr(i);if("number"!==typeof a)return!1;let s=e._reader.requestSlice(i.filePos,a);if(ce(s)&&(s=await s),!s)return!1;const n=i.filePos;for(;s.filePos<=n+a-2;){const e=fr(s);if(!e)break;const{id:i,size:r}=e,a=s.filePos;if(void 0===r)return!1;switch(i){case ir.EBMLVersion:if(1!==ur(s,r))return!1;break;case ir.EBMLReadVersion:if(1!==ur(s,r))return!1;break;case ir.DocType:if(mr(s,r)!==t)return!1;break;case ir.DocTypeVersion:if(ur(s,r)>4)return!1}s.filePos=a+r}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new Wr(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}}class Rs extends _s{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}}class Fs extends xs{async _canReadInput(e){let t=0;for(;;){let i=e._reader.requestSlice(t,qo);if(ce(i)&&(i=await i),!i)break;const r=jo(i);if(!r)break;t=i.filePos+r.size}const i=await Kr(e._reader,t,t+4096);if(!i)return!1;const r=i.header,a=di(r.mpegVersionId,r.channel);let s=e._reader.requestSlice(i.startPos+a,4);if(ce(s)&&(s=await s),!s)return!1;const n=Io(s);if(n===li||n===ui)return!0;t=i.startPos+i.header.totalSize;const o=await Kr(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 Xr(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}}class As extends xs{async _canReadInput(e){let t=e._reader.requestSlice(0,12);if(ce(t)&&(t=await t),!t)return!1;const i=Do(t,4);if("RIFF"!==i&&"RIFX"!==i&&"RF64"!==i)return!1;t.skip(4);return"WAVE"===Do(t,4)}_createDemuxer(e){return new la(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}}class Ds extends xs{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return ce(t)&&(t=await t),!!t&&"OggS"===Do(t,4)}_createDemuxer(e){return new ra(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}}class Ms extends xs{async _canReadInput(e){let t=0;for(;;){let i=e._reader.requestSlice(t,qo);if(ce(i)&&(i=await i),!i)break;const r=jo(i);if(!r)break;t=i.filePos+r.size}let i=e._reader.requestSlice(t,4);return ce(i)&&(i=await i),!!i&&"fLaC"===Do(i,4)}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new ga(e)}}class Ns extends xs{async _canReadInput(e){let t=0;for(;;){let i=e._reader.requestSlice(t,qo);if(ce(i)&&(i=await i),!i)break;const r=jo(i);if(!r)break;t=i.filePos+r.size}let i=e._reader.requestSliceRange(t,7,9);if(ce(i)&&(i=await i),!i)return!1;const r=ha(i);if(!r)return!1;if(t+=r.frameLength,i=e._reader.requestSliceRange(t,7,9),ce(i)&&(i=await i),!i)return!1;const a=ha(i);return!!a&&(r.objectType===a.objectType&&r.samplingFrequencyIndex===a.samplingFrequencyIndex&&r.channelConfiguration===a.channelConfiguration)}_createDemuxer(e){return new ma(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}}class Os extends xs{async _canReadInput(e){let t=e._reader.requestSlice(0,205);if(ce(t)&&(t=await t),!t)return!1;const i=yo(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 Pa(e)}get name(){return"MPEG Transport Stream"}get mimeType(){return"video/MP2T"}}class Ls extends xs{async _canReadInput(e){let t=e._reader.requestSlice(0,7);if(ce(t)&&(t=await t),!t)return!1;if(!("#EXTM3U"===Do(t,7)))return!1;if(!(e._rootSource instanceof es))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 bs(e)}get name(){return"HTTP Live Streaming (HLS)"}get mimeType(){return Aa}}const zs=new Bs,Us=new Es,qs=new _s,Ws=new Rs,Hs=new Fs,Vs=new As,js=new Ds,Ks=new Ns,Xs=new Ms,$s=new Os,Gs=new Ls,Qs=[Gs,zs,Us,qs,Ws,Vs,js,Xs,Hs,Ks,$s],Ys=[Gs,zs,Us,Hs,Ks,$s];var Js=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});he();let Zs=-1/0,en=-1/0,tn=null;"undefined"!==typeof FinalizationRegistry&&(tn=new FinalizationRegistry(e=>{const t=performance.now();"video"===e.type?(t-Zs>=1e3&&(ve._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."),Zs=t),"undefined"!==typeof VideoFrame&&e.data instanceof VideoFrame&&e.data.close()):(t-en>=1e3&&(ve._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."),en=t),"undefined"!==typeof AudioData&&e.data instanceof AudioData&&e.data.close())}));class rn{constructor(){this._referenceCount=0,this._lastAllocationBuffer=null}}const an=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],sn=new Set(an);class nn{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(G*this.timestamp)}get microsecondDuration(){return Math.trunc(G*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||!sn.has(t.format))throw new TypeError("init.format must be one of: "+an.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&&ye(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??gn(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?h(e):h(e).slice(),this._layout=i,this.colorSpace=new dn(r)}else if("undefined"!==typeof VideoFrame&&e instanceof VideoFrame){if(void 0!==t?.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(void 0!==t?.timestamp&&!Number.isFinite(t?.timestamp))throw new TypeError("init.timestamp, when provided, must be a number.");if(void 0!==t?.duration&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");void 0!==t?.visibleRect&&ye(t.visibleRect,"init.visibleRect"),this._data=e,this._layout=null,this.format=e.format,this.visibleRect={left:e.visibleRect?.x??0,top:e.visibleRect?.y??0,width:e.visibleRect?.width??e.codedWidth,height:e.visibleRect?.height??e.codedHeight},this.rotation=t?.rotation??0,this.squarePixelWidth=e.displayWidth,this.squarePixelHeight=e.displayHeight,this.timestamp=t?.timestamp??e.timestamp/1e6,this.duration=t?.duration??(e.duration??0)/1e6,this.colorSpace=new dn(e.colorSpace)}else if("undefined"!==typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!==typeof SVGImageElement&&e instanceof SVGImageElement||"undefined"!==typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!==typeof HTMLVideoElement&&e instanceof HTMLVideoElement||"undefined"!==typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!==typeof OffscreenCanvas&&e instanceof OffscreenCanvas){if(!t||"object"!==typeof t)throw new TypeError("init must be an object.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(void 0!==t.duration&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(void 0!==t.visibleRect&&ye(t.visibleRect,"init.visibleRect"),"undefined"!==typeof VideoFrame)return new nn(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*G),duration:Math.trunc((t.duration??0)*G)||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:re(),willReadFrequently:!0});if(!n)throw new Error("OffscreenCanvas must have support for the '2d' context in order to create a VideoSample from this data.");n.drawImage(e,-a.left,-a.top),this._data=s,this._layout=null,this.format="RGBX",this.visibleRect={left:0,top:0,width:a.width,height:a.height},this.squarePixelWidth=a.width,this.squarePixelHeight=a.height,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=new dn({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else{if(!(e instanceof rn))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&&!an.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=ke({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),tn?.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return n(null!==this._data),this._data instanceof rn?new nn(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):hn(this._data)?new nn(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):this._data instanceof Uint8Array?(n(this._layout),new nn(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 nn(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||(tn?.unregister(this),this._data instanceof rn?(this._data._referenceCount--,0===this._data._referenceCount&&this._data.close()):hn(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(pn(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(hn(this._data))return this._data.allocationSize(e);return yn(this,e).allocationSize}async copyTo(e,t={}){if(!P(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(pn(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(n(null!==this._data),hn(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 rn)){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 nn))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(l){i.error=l,i.hasError=!0}finally{Js(i)}}}const i=yn(this,t);n(this.format);const r=h(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)n(this._layout),n(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");n(e);const t=e.getImageData(0,0,this.codedWidth,this.codedHeight);s=[{data:h(t.data),stride:4*this.codedWidth}]}const o=[],c=a.length;for(let n=0;na.byteLength)throw new Error("Source buffer OOB read.");if(l+u>r.byteLength)throw new Error("Destination buffer OOB write.");const i=a.subarray(c,c+u);r.set(i,l),c+=t,l+=e.destinationStride}o.push(d)}if(void 0!==t.format){const e=this.format.startsWith("RGB")!==t.format.startsWith("RGB"),a=this.format.includes("X")&&t.format.includes("A");if(e||a)for(let t=0;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 hn(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?(n(this._layout),new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,layout:this._layout,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,t,i,r,a,s,n,o,c){let l=0,u=0,d=this.displayWidth,h=this.displayHeight,f=0,m=0,p=this.displayWidth,g=this.displayHeight;if(void 0!==s?(l=t,u=i,d=r,h=a,f=s,m=n,void 0!==o?(p=o,g=c):(p=d,g=h)):(f=t,m=i,void 0!==r&&(p=r,g=a)),!("undefined"!==typeof CanvasRenderingContext2D&&e instanceof CanvasRenderingContext2D||"undefined"!==typeof OffscreenCanvasRenderingContext2D&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(l))throw new TypeError("sx must be a number.");if(!Number.isFinite(u))throw new TypeError("sy must be a number.");if(!Number.isFinite(d)||d<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(h)||h<0)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(f))throw new TypeError("dx must be a number.");if(!Number.isFinite(m))throw new TypeError("dy must be a number.");if(!Number.isFinite(p)||p<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(g)||g<0)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw new Error("VideoSample is closed.");({sx:l,sy:u,sWidth:d,sHeight:h}=this._rotateSourceRegion(l,u,d,h,this.rotation));const k=this.toCanvasImageSource();e.save();const y=f+p/2,b=m+g/2;e.translate(y,b),e.rotate(this.rotation*Math.PI/180);const w=this.rotation%180===0?1:p/g;e.scale(1/w,w),e.drawImage(k,l,u,d,h,-p/2,-g/2,p,g),e.restore()}drawWithFit(e,t){if(!("undefined"!==typeof CanvasRenderingContext2D&&e instanceof CanvasRenderingContext2D||"undefined"!==typeof OffscreenCanvasRenderingContext2D&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!t||"object"!==typeof t)throw new TypeError("options must be an object.");if(!["fill","contain","cover"].includes(t.fit))throw new TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");void 0!==t.crop&&mn(t.crop,"options.");const i=e.canvas.width,r=e.canvas.height,a=t.rotation??this.rotation,[s,n]=a%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let o,c,l,u,d=t.crop;d&&(d=fn(d,s,n));const{sx:h,sy:f,sWidth:m,sHeight:p}=this._rotateSourceRegion(t.crop?.left??0,t.crop?.top??0,t.crop?.width??s,t.crop?.height??n,a);if("fill"===t.fit)o=0,c=0,l=i,u=r;else{const[e,a]=t.crop?[t.crop.width,t.crop.height]:[s,n],d="contain"===t.fit?Math.min(i/e,r/a):Math.max(i/e,r/a);l=e*d,u=a*d,o=(i-l)/2,c=(r-u)/2}e.save();const g=a%180===0?1:l/u;e.translate(i/2,r/2),e.rotate(a*Math.PI/180),e.scale(1/g,g),e.translate(-i/2,-r/2),e.drawImage(this.toCanvasImageSource(),h,f,m,p,o,c,l,u),e.restore()}_rotateSourceRegion(e,t,i,r,a){return 90===a?[e,t,i,r]=[t,this.squarePixelHeight-e-i,r,i]:180===a?[e,t]=[this.squarePixelWidth-e-i,this.squarePixelHeight-t-r]:270===a&&([e,t,i,r]=[this.squarePixelWidth-t-r,e,r,i]),{sx:e,sy:t,sWidth:i,sHeight:r}}_drawWithFitAndMipmapping(e,t,i){const r=e.width,a=e.height,[s,n]=i.rotation%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],o=i.crop?i.crop.width:s,c=i.crop?i.crop.height:n;let l=0;2*r0?un(u,d):{canvas:e,context:t,isNew:i.targetIsFresh};f.imageSmoothingQuality="high",i.fillBlack?(f.fillStyle="black",f.fillRect(0,0,u,d)):m||f.clearRect(0,0,u,d),this.drawWithFit(f,{fit:i.fit,rotation:i.rotation,crop:i.crop}),f.globalCompositeOperation="copy";for(let p=l;p>1;p--){const e=r*2**p,t=a*2**p;f.drawImage(h,0,0,e,t,0,0,e/2,t/2)}f.globalCompositeOperation="source-over",l>0&&(t.imageSmoothingQuality="high",t.globalCompositeOperation="copy",t.drawImage(h,0,0,2*r,2*a,0,0,r,a),t.globalCompositeOperation="source-over")}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(n(null!==this._data),this._data instanceof rn||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&&mn(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=o(this.rotation+(e.rotate??0)),[i,r]=t%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let a=e.crop;a&&(a=fn(a,i,r));const s=a?a.width:i,n=a?a.height:r,c=s/n;let l,u;void 0!==e.width&&void 0===e.height?(l=e.width,u=l/c):void 0===e.width&&void 0!==e.height?(u=e.height,l=u*c):void 0!==e.width&&void 0!==e.height?(l=e.width,u=e.height):(l=s,u=n),l=H(l,e.roundDimensionsTo??1),u=H(u,e.roundDimensionsTo??1);const d={width:l,height:u,fit:e.fit??"fill",rotation:t,crop:a??{left:0,top:0,width:i,height:r},alpha:e.alpha??"keep"};for(const o of on){let e=o(this,d);if(ce(e)&&(e=await e),null!==e)return e}const{canvas:h,context:f,isNew:m}=un(d.width,d.height);return this._drawWithFitAndMipmapping(h,f,{fit:d.fit,rotation:d.rotation,crop:d.crop,targetIsFresh:m,fillBlack:"discard"===d.alpha}),new nn(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 on=[],cn=[];let ln=0;const un=(e,t)=>{for(const a of cn)if(a.canvas.width===e&&a.canvas.height===t)return a.age=ln++,{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 cn.length>=3&&cn.splice(ge(cn,e=>e.age),1),cn.push({canvas:i,context:r,age:ln++}),{canvas:i,context:r,isNew:!0}};class dn{constructor(e){if(void 0!==e){if(!e||"object"!==typeof e)throw new TypeError("init.colorSpace, when provided, must be an object.");const t=Object.keys(g);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(y);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(w);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 hn=e=>"undefined"!==typeof VideoFrame&&e instanceof VideoFrame,fn=(e,t,i)=>{const r=Math.min(e.left,t),a=Math.min(e.top,i),s=Math.min(e.width,t-r),o=Math.min(e.height,i-a);return n(s>=0),n(o>=0),{left:r,top:a,width:s,height:o}},mn=(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.")},pn=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.")}},gn=(e,t,i)=>{const r=kn(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},kn=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:N(e),n(!1)}},yn=(e,t)=>{const i={left:0,top:0,width:e.codedWidth,height:e.codedHeight},r=t.rect,a=bn(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 Tn(a,n,s)},bn=(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(!wn(a,s))throw new TypeError("visibleRect alignment is invalid for the format.");return s},wn=(e,t)=>{if(null===e)return!0;const i=kn(e);for(let r=0;r{const r=kn(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(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(e?.timestamp))throw new TypeError("init.timestamp must be a number.");const t=e.data.byteLength/(In(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*In(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=In(t),s=xn(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(!P(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&&!Sn.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,o=this.format;const c=i??this.format;if(!c)throw new Error("Destination format not determined");const l=this.numberOfFrames,u=this.numberOfChannels,d=a??0;if(d>=l)throw new RangeError("frameOffset out of range");const h=void 0!==r?r:l-d;if(h>l-d)throw new RangeError("frameCount out of range");const m=In(c),p=xn(c);if(p&&s>=u)throw new RangeError("planeIndex out of range");if(!p&&0!==s)throw new RangeError("planeIndex out of range");const g=(p?h:h*u)*m;if(e.byteLength2&&c!==o)return void _n(this._data,k,o,c,u,s,d,h);try{return void this._data.copyTo(e,{planeIndex:s,frameOffset:d,frameCount:h,format:c})}catch(I){if("f32-planar"===c)throw I;o="f32-planar"}}const b=Cn(o),w=In(o),T=xn(o);let S;if(this._data instanceof vn){const e=e=>{const t=this._data.getDataPlane(e);if(!(t instanceof Uint8Array))throw new TypeError("getDataPlane() must return a Uint8Array.");const i=l*w*(T?1:u);if(t.byteLength!==i)throw new TypeError(`Data plane ${e} has invalid size. Expected exactly ${i} bytes, got ${t.byteLength} bytes.`);return t};if(T)if(p)S=e(s),s=0;else{S=new Uint8Array(l*w*u);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 Pn({data:a,format:this.format,sampleRate:this.sampleRate,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp+e/this.sampleRate})}close(){this._closed||(tn?.unregister(this),this._data instanceof vn?(this._data._referenceCount--,0===this._data._referenceCount&&this._data.close()):En(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 vn?this._createAudioDataFromData():En(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(xn(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")}},xn=e=>{switch(e){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},Cn=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)}},Bn=e=>{switch(e){case"u8":case"u8-planar":return(e,t,i)=>e.setUint8(t,U(127.5*(i+1),0,255));case"s16":case"s16-planar":return(e,t,i)=>e.setInt16(t,U(Math.round(32767*i),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,i)=>e.setInt32(t,U(Math.round(2147483647*i),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,i)=>e.setFloat32(t,i,!0)}},En=e=>"undefined"!==typeof AudioData&&e instanceof AudioData,_n=(e,t,i,r,a,s,n,o)=>{const c=Cn(i),l=Bn(r),u=In(i),d=In(r),h=xn(i);if(xn(r))if(h){const r=new ArrayBuffer(o*u),a=f(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.")},Dn=e=>{if(!fe(e))throw new TypeError("timestamp must be a number.")},Mn=(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 Nn{constructor(e){if(!(e instanceof Yn))throw new TypeError("track must be an InputTrack.");this._track=e}async getFirstPacket(e={}){if(An(e),this._track.input._disposed)throw new mo;return Mn(this._track,this._track._backing.getFirstPacket(e),e)}async getFirstKeyPacket(e={}){An(e);const t=await this.getFirstPacket(e);return t?"key"===t.type?t:this.getNextKeyPacket(t,e):null}async getPacket(e,t={}){if(Dn(e),An(t),this._track.input._disposed)throw new mo;return Mn(this._track,this._track._backing.getPacket(e,t),t)}async getNextPacket(e,t={}){if(!(e instanceof bi))throw new TypeError("packet must be an EncodedPacket.");if(An(t),this._track.input._disposed)throw new mo;return Mn(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(Dn(e),An(t),this._track.input._disposed)throw new mo;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);const i=await this._track._backing.getKeyPacket(e,t);if(!i)return i;n("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 bi))throw new TypeError("packet must be an EncodedPacket.");if(An(t),this._track.input._disposed)throw new mo;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);const i=await this._track._backing.getNextKeyPacket(e,t);if(!i)return i;n("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 bi))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 bi))throw new TypeError("endPacket must be an EncodedPacket.");if(An(i),this._track.input._disposed)throw new mo;const r=[];let{promise:a,resolve:s}=F(),{promise:n,resolve:o}=F(),c=!1,l=!1,u=null,d=!1;const h=[],f=()=>Math.max(2,h.length);(async()=>{let u=e??await this.getFirstPacket(i);for(;u&&!l&&!this._track.input._disposed&&!(t&&u.sequenceNumber>=t?.sequenceNumber);)r.length>f()?(({promise:n,resolve:o}=F()),await n):(r.push(u),s(),({promise:a,resolve:s}=F()),u=await this.getNextPacket(u,i));c=!0,s()})().catch(e=>{d||(u=e,d=!0,s())});const m=this._track;return{async next(){for(;;){if(m.input._disposed)throw new mo;if(l)return{value:void 0,done:!0};if(d)throw u;if(r.length>0){const e=r.shift(),t=performance.now();for(h.push(t);h.length>0&&t-h[0]>=1e3;)h.shift();return o(),{value:e,done:!1}}if(c)return{value:void 0,done:!0};await a}},return:async()=>(l=!0,o(),s(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}}class On{constructor(e,t){this.onSample=e,this.onError=t}}class Ln{mediaSamplesInRange(e=-1/0,t=1/0,i){Dn(e),Dn(t);const r=[];let a=!1,s=null,{promise:n,resolve:o}=F(),{promise:c,resolve:l}=F(),u=!1,d=!1,h=!1,f=null,m=null,p=!1;const g={...i,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{f=await this._createDecoder(i=>{l(),i.timestamp>=t&&(d=!0),d?i.close():(s&&(i.timestamp>e?(r.push(s),a=!0):s.close()),i.timestamp>=e&&(r.push(i),a=!0),s=a?null:i,r.length>0&&(o(),({promise:n,resolve:o}=F())))},e=>{p||(m=e,p=!0,o())});const i=this._createPacketSink(),k=await i.getKeyPacket(e,g)??await i.getFirstKeyPacket(g);let y=k;const b=i.packets(k??void 0,void 0,g);for(await b.next();y&&!d&&!this._track.input._disposed;){const e=zn(r.length);if(r.length+f.getDecodeQueueSize()>e){({promise:c,resolve:l}=F()),await c;continue}f.decode(y);const t=await b.next();if(t.done)break;y=t.value}await b.return(),h||this._track.input._disposed||await f.flush(),!a&&s&&r.push(s),u=!0,o()})().catch(e=>{p||(m=e,p=!0,o())}).finally(()=>{f?.close()});const k=this._track,y=()=>{s?.close();for(const e of r)e.close()};return{async next(){for(;;){if(k.input._disposed)throw h=!0,d=!0,y(),new mo;if(h)return{value:void 0,done:!0};if(p)throw h=!0,d=!0,y(),m;if(r.length>0){const e=r.shift();return l(),{value:e,done:!1}}if(u)return{value:void 0,done:!0};await n}},return:async()=>(h=!0,d=!0,l(),o(),y(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e,t){(e=>{if(!(Symbol.iterator in e)&&!(Symbol.asyncIterator in e))throw new TypeError("Argument must be an iterable or async iterable.")})(e);const i=async function*(e){Symbol.iterator in e?yield*e[Symbol.iterator]():yield*e[Symbol.asyncIterator]()}(e),r=[],a=[];let{promise:s,resolve:o}=F(),{promise:c,resolve:l}=F(),u=!1,d=!1,h=null,f=null,m=!1;const p=e=>{a.push(e),o(),({promise:s,resolve:o}=F())},g={...t,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{h=await this._createDecoder(e=>{if(l(),d)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{m||(f=e,m=!0,o())});const e=this._createPacketSink();let t=null,s=null,k=-1;const y=async()=>{n(s),n(h);let t=s;for(h.decode(t);t.sequenceNumberi&&!d;)({promise:c,resolve:l}=F()),await c;if(d)break;const r=await e.getNextPacket(t,g);n(r),h.decode(r),t=r}k=-1},b=async()=>{n(h),await h.flush();for(let e=0;e{m||(f=e,m=!0,o())}).finally(()=>{h?.close()});const k=this._track,y=()=>{for(const e of a)e?.close()};return{async next(){for(;;){if(k.input._disposed)throw d=!0,y(),new mo;if(d)return{value:void 0,done:!0};if(m)throw d=!0,y(),f;if(a.length>0){const e=a.shift();return n(void 0!==e),l(),{value:e,done:!1}}if(u)return{value:void 0,done:!0};await s}},return:async()=>(d=!0,l(),o(),y(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}}const zn=e=>0===e?40:8;class Un extends On{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 Z,this.customDecoderQueueSize=0,this.inputTimestamps=[],this.sampleQueue=[],this.currentPacketIndex=0,this.raslSkipped=!1,this.alphaDecoder=null,this.alphaHadKeyframe=!1,this.colorQueue=[],this.alphaQueue=[],this.merger=null,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue=[],this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1,this.finalSamples=[],this.mergeAlphaPromises=[];const o=Rn.find(e=>e.supports(i,r));if(o)this.customDecoder=new o,this.customDecoder.codec=i,this.customDecoder.config=r,this.customDecoder.onSample=e=>{if(!(e instanceof nn))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();n(void 0!==t),this.mergeAlpha(e,t)}else this.colorQueue.push(e)};if(se()){if("avc"===i&&this.decoderConfig.description){const e=Ge(h(this.decoderConfig.description));if(e&&e.sequenceParameterSets.length>0){const t=Ye(e.sequenceParameterSets[0]);t&&(0===t.frameMbsOnlyFlag&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"}),0!==t.maxDecFrameBuffering&&1!==t.bitstreamRestrictionFlag&&(e.sequenceParameterSets[0]=Ze(t),this.decoderConfig={...this.decoderConfig,description:$e(e)}))}}S(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:(n(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(n(this.decoder),te()||R(this.inputTimestamps,e.timestamp,e=>e),se()&&0===this.currentPacketIndex)if("avc"===this.codec){const t=[];let i=!1;for(const a of qe(e.data,this.decoderConfig)){const r=We(e.data[a.offset]);if(i||(i=r>=1&&r<=5),r===Me.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&h(t.description)[4];return Ke(e,i+1)}return je(e)})(t,this.decoderConfig);e=new bi(r,e.type,e.timestamp,e.duration)}else if("hevc"===this.codec){const t=ft(e.data,this.decoderConfig);t&&(e=new bi(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 Wn),!this.alphaDecoder){const e=e=>{if(this.colorQueue.length>0){const t=this.colorQueue.shift();n(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();n(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=Tt(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 et(e,this.decoderConfig)){const i=tt(e[t.offset]);if(i===Oe.RASL_N||i===Oe.RASL_R)return!0}return!1}sampleHandler(e){if(te()){if(this.sampleQueue.length>0&&e.timestamp>=c(this.sampleQueue).timestamp){for(const e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}R(this.sampleQueue,e,e=>e.timestamp)}else{const t=this.inputTimestamps.shift();n(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=F();this.mergeAlphaPromises.push(i.promise);const r={sample:null};this.finalSamples.push(r);try{if(t){n(this.merger);const i=await this.merger.merge(e,t);r.sample=new nn(i)}else r.sample=new nn(e);for(;this.finalSamples.length>0&&null!==this.finalSamples[0].sample;){const e=this.finalSamples.shift();this.sampleHandler(e.sample)}}catch(a){A(this.finalSamples,r),this.onError(a)}finally{A(this.mergeAlphaPromises,i.promise),i.resolve()}}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(n(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),te()){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()):(n(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 qn=null;class Wn{constructor(){this.workers=[],this.nextWorkerIndex=0,this.pendingRequests=new Map,this.nextRequestId=0}merge(e,t){if(0===this.workers.length){if(!qn){const e=new Blob([`(${Hn.toString()})()`],{type:"application/javascript"});qn=URL.createObjectURL(e)}const e=U(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=F();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 Hn=()=>{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 d=r*a,h=d*c,f=l*u*c,m=new Uint8Array(h+2*f+d*c);await e.copyTo(m);const p=await o(t,r,a,c),g=h+2*f;m.set(p,g);const k={format:i.slice(0,4)+"A"+i.slice(4),codedWidth:r,codedHeight:a,timestamp:e.timestamp,duration:e.duration??void 0,transfer:[m.buffer]};return new VideoFrame(m,k)},n=async(e,i)=>{const r=e.visibleRect?.width??e.codedWidth,a=e.visibleRect?.height??e.codedHeight,s=r*a,n=Math.ceil(r/2)*Math.ceil(a/2),c=e.allocationSize();t&&t.byteLength===c||(t=new Uint8Array(c)),await e.copyTo(t);const l=new Uint8Array(s+2*n+s);l.set(t.subarray(0,s),0);const u=s,d=s+n,h=s;for(let o=0;o{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 jn extends Ln{constructor(e,t={}){if(!(e instanceof eo))throw new TypeError("videoTrack must be an InputVideoTrack.");Vn(t),super(),this._track=e,this._decoderOptions=t}async _createDecoder(e,t){if(!(await this._track.canDecode())){if("undefined"===typeof VideoDecoder)throw new Error(ne("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 n(i&&a),a={...a,hardwareAcceleration:this._decoderOptions.hardwareAcceleration,optimizeForLatency:this._decoderOptions.optimizeForLatency},new Un(e,t,i,a,r,s)}_createPacketSink(){return new Nn(this._track)}async getSample(e,t={}){Dn(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 Kn{constructor(e,t={}){if(this._rotation=0,this._initPromise=null,this._nextCanvasIndex=0,!(e instanceof eo))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&&mn(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&&Vn(t.decoderOptions),this._videoTrack=e,this._alpha=t.alpha??!1,this._options=t,this._fit=t.fit??"fill",this._videoSampleSink=new jn(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=fn(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||re()});n(s),e._drawWithFitAndMipmapping(r,s,{fit:this._fit,rotation:this._rotation,crop:this._crop,targetIsFresh:a,fillBlack:!this._alpha&&re()});const o={canvas:r,timestamp:e.timestamp,duration:e.duration};return e.close(),o}async getCanvas(e,t){Dn(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*z(this._videoSampleSink.samples(e,t,i),e=>this._videoSampleToWrappedCanvas(e))}async*canvasesAtTimestamps(e,t){await this._ensureInit(),yield*z(this._videoSampleSink.samplesAtTimestamps(e,t),e=>e&&this._videoSampleToWrappedCanvas(e))}}class Xn extends On{constructor(e,t,i,r){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new Z,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=Fn.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 Pn))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 Pn(e))}catch(t){this.onError(t)}},error:t=>{t.stack=e,this.onError(t)}}),this.decoder.configure(r)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(n(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--)):(n(this.decoder),this.expectedFirstTimestamp??(this.expectedFirstTimestamp=e.timestamp),this.decoder.decode(e.toEncodedAudioChunk()))}async flush(){this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(n(this.decoder),await this.decoder.flush()),this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(n(this.decoder),"closed"!==this.decoder.state&&this.decoder.close())}}class $n extends On{constructor(e,t,i){super(e,t),this.decoderConfig=i,this.currentTimestamp=null,n(Kt.includes(i.codec)),this.codec=i.codec;const{dataType:r,sampleSize:a,littleEndian:s}=si(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):n(!1);break;case 3:"unsigned"===r?this.readInputValue=(e,t)=>O(e,t,s)-2**23:"signed"===r?this.readInputValue=(e,t)=>((e,t,i)=>O(e,t,i)<<8>>8)(e,t,s):n(!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):n(!1);break;case 8:"float"===r?this.readInputValue=(e,t)=>e.getFloat64(t,s):n(!1);break;default:N(a),n(!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:N(a),n(!1)}}getDecodeQueueSize(){return 0}decode(e){const t=f(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 Pn({format:this.outputFormat,data:a,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:i,timestamp:o});this.onSample(c)}async flush(){}close(){}}class Gn extends Ln{constructor(e){if(!(e instanceof to))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(ne("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 n(i&&r),Kt.includes(r.codec)?new $n(e,t,r):new Xn(e,t,i,r)}_createPacketSink(){return new Nn(this._track)}async getSample(e,t={}){Dn(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 Qn{constructor(e){if(!(e instanceof to))throw new TypeError("audioTrack must be an InputAudioTrack.");this._audioSampleSink=new Gn(e)}_audioSampleToWrappedArrayBuffer(e){const t={buffer:e.toAudioBuffer(),timestamp:e.timestamp,duration:e.duration};return e.close(),t}async getBuffer(e,t){Dn(e);const i=await this._audioSampleSink.getSample(e,t);return i&&this._audioSampleToWrappedArrayBuffer(i)}buffers(e,t,i){return z(this._audioSampleSink.samples(e,t,i),e=>this._audioSampleToWrappedArrayBuffer(e))}buffersAtTimestamps(e,t){return z(this._audioSampleSink.samplesAtTimestamps(e,t),e=>e&&this._audioSampleToWrappedArrayBuffer(e))}}class Yn{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof eo}isAudioTrack(){return this instanceof to}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}async getInternalCodecId(){return this._backing.getInternalCodecId()}get internalCodecId(){return Jn(this._backing.getInternalCodecId(),"internalCodecId","getInternalCodecId")}async getLanguageCode(){return this._backing.getLanguageCode()}get languageCode(){return Jn(this._backing.getLanguageCode(),"languageCode","getLanguageCode")}async getName(){return this._backing.getName()}get name(){return Jn(this._backing.getName(),"name","getName")}async getTimeResolution(){return this._backing.getTimeResolution()}get timeResolution(){return Jn(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 Jn(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 V((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 Nn(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 Yn))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(so({filter:e=>e.canBePairedWith(this)},e))}async getPairableVideoTracks(e){return this.input.getVideoTracks(so({filter:e=>e.canBePairedWith(this)},e))}async getPairableAudioTracks(e){return this.input.getAudioTracks(so({filter:e=>e.canBePairedWith(this)},e))}async getPrimaryPairableVideoTrack(e){return this.input.getPrimaryVideoTrack(so({filter:e=>e.canBePairedWith(this)},e))}async getPrimaryPairableAudioTrack(e){return this.input.getPrimaryAudioTrack(so({filter:e=>e.canBePairedWith(this)},e))}async hasPairableTrack(e){e&&(e=Zn(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=Zn(e)),this.hasPairableTrack(async t=>t.isVideoTrack()&&(!e||await e(t)))}hasPairableAudioTrack(e){return e&&(e=Zn(e)),this.hasPairableTrack(async t=>t.isAudioTrack()&&(!e||await e(t)))}}const Jn=(e,t,i)=>{if(ce(e))throw new Error(`'${t}' is deprecated and not available synchronously for this track. Use the preferred '${i}()' instead.`);return e},Zn=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 ce(r)?r.then(i):i(r)}:void 0};class eo extends Yn{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 Jn(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 Jn(this._backing.getCodedWidth(),"codedWidth","getCodedWidth")}async getCodedHeight(){return this._backing.getCodedHeight()}get codedHeight(){return Jn(this._backing.getCodedHeight(),"codedHeight","getCodedHeight")}async getRotation(){return this._backing.getRotation()}get rotation(){return Jn(this._backing.getRotation(),"rotation","getRotation")}async getSquarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelWidth(){return Jn(this._backing.getSquarePixelWidth(),"squarePixelWidth","getSquarePixelWidth")}async getSquarePixelHeight(){return this._backing.getSquarePixelHeight()}get squarePixelHeight(){return Jn(this._backing.getSquarePixelHeight(),"squarePixelHeight","getSquarePixelHeight")}async getPixelAspectRatio(){return this._pixelAspectRatioCache??(this._pixelAspectRatioCache=ke({num:await this.getSquarePixelWidth()*await this.getCodedHeight(),den:await this.getSquarePixelHeight()*await this.getCodedWidth()}))}get pixelAspectRatio(){return this._pixelAspectRatioCache??(this._pixelAspectRatioCache=ke({num:Jn(this._backing.getSquarePixelWidth(),"pixelAspectRatio","getPixelAspectRatio")*Jn(this._backing.getCodedHeight(),"pixelAspectRatio","getPixelAspectRatio"),den:Jn(this._backing.getSquarePixelHeight(),"pixelAspectRatio","getPixelAspectRatio")*Jn(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=Jn(e,"displayWidth","getDisplayWidth");if(null!==t)return t}const t=Jn(this._backing.getRotation(),"displayWidth","getDisplayWidth")%180===0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight();return Jn(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=Jn(e,"displayHeight","getDisplayHeight");if(null!==t)return t}const t=Jn(this._backing.getRotation(),"displayHeight","getDisplayHeight")%180===0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth();return Jn(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(n(null!==t),Rn.some(i=>i.supports(t,e)))return!0;if("undefined"===typeof VideoDecoder)return!1;return!0===(await VideoDecoder.isConfigSupported(e)).supported}catch(e){return ve._error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof bi))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 n(i),Tt(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&&(!fe(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 Nn(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=(d/T+d/S)/2;return{underlyingFrameRate:u,bestGuessFrameRate:null!==u?u:lo(P),minFrameRate:d/p,maxFrameRate:d/m,averageFrameRate:d*k/g,medianFrameRate:P,frameRateIsConstant:null!==u&&1===m&&1===p,probedPacketCount:n}}}class to extends Yn{constructor(e,t){super(e,t),this._backing=t}get type(){return"audio"}async getCodec(){return this._backing.getCodec()}get codec(){return Jn(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){return await(this._backing.getHasOnlyKeyPackets?.())??!0}async getNumberOfChannels(){return this._backing.getNumberOfChannels()}get numberOfChannels(){return Jn(this._backing.getNumberOfChannels(),"numberOfChannels","getNumberOfChannels")}async getSampleRate(){return this._backing.getSampleRate()}get sampleRate(){return Jn(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(n(null!==t),Fn.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 ve._error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof bi))throw new TypeError("packet must be an EncodedPacket.");return null===await this.getCodec()?null:"key"}}const io=e=>-(e??-1/0),ro=e=>-e,ao=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 ce(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 ce(r)?r.then(i):i(r)}:void 0}},so=(e,t)=>({filter:e?.filter||t?.filter?i=>{const r=e?.filter?.(i)??!0,a=e=>!1!==e&&(t?.filter?.(i)??!0);return ce(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 ce(r)||ce(a)?Promise.all([r,a]).then(([e,t])=>s(e,t)):s(r,a)}:void 0}),no=async(e,t)=>{let i=e;if(t?.filter){const r=e.map(e=>t.filter(e));if(r.some(e=>ce(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=>ce(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)},oo=(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 d=1/Math.min(u,1e3),h=Math.max(Number.EPSILON,o-d),f=o+d,m=t/f,p=t/h,g=t/o;let k=null,y=1/0;for(const T of a){if(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 xs)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof Ja||e.source instanceof Za))throw new TypeError("options.source must be a Source or SourceRef.");if(e.source instanceof Ja&&e.source._disposed)throw new TypeError("options.source must not be a disposed Source.");if(void 0!==e.initInput&&!(e.initInput instanceof ho))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 Ja?this._rootRef=e.source.ref():this._rootRef=e.source,this._sourceRefs.push(this._rootRef)}get _rootSource(){return this._rootRef.source}async _getSourceUncached(e){n(this._rootSource instanceof es);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&&ts(i.request,e));if(i)return i.age++,Promise.resolve(i.sourceRef.source.ref());const r=this._sourceCachePromises.find(i=>i.cacheGroup===t&&ts(i.request,e));if(r)return r.promise.then(e=>e.sourceRef.source.ref());const a=(async()=>{const i=await this._getSourceUncached(e);if(pe(this._sourceCache,e=>e.cacheGroup===t&&1===e.sourceRef.source._refCount)>=4){const e=ge(this._sourceCache,e=>e.cacheGroup===t&&1===e.sourceRef.source._refCount?e.age:1/0);n(-1!==e);const i=this._sourceCache[e];this._sourceCache.splice(e,1),i.sourceRef.free(),A(this._sourceRefs,i.sourceRef)}this._sourceRefs.push(i);const r=this._sourceCachePromises.findIndex(t=>t.request===e);n(-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 po(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 fo})())}get source(){return this._rootSource}async getFormat(){return await this._getDemuxer(),n(this._format),this._format}async canRead(){try{return await this._getDemuxer(),!0}catch(e){if(e instanceof fo)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=ao(e));const t=(await this._getTrackBackings()).map(e=>this._wrapBackingAsTrack(e));return no(t,e)}async getVideoTracks(e){e&&(e=ao(e));const t=(await this.getTracks()).filter(e=>e.isVideoTrack());return no(t,e)}async getAudioTracks(e){e&&(e=ao(e));const t=(await this.getTracks()).filter(e=>e.isAudioTrack());return no(t,e)}async getPrimaryVideoTrack(e){e&&(e=ao(e));const t=so(e,{sortBy:async e=>[ro((await e.getDisposition()).default),ro(await e.hasPairableAudioTrack()),ro(!(await e.hasOnlyKeyPackets())),io(await e.getBitrate())]});return(await this.getVideoTracks(t))[0]??null}async getPrimaryAudioTrack(e){e&&(e=ao(e));const t=await this.getPrimaryVideoTrack(),i=so(e,{sortBy:async e=>[ro(!t||e.canBePairedWith(t)),ro((await e.getDisposition()).default),io(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 eo(this,e):new to(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 fo extends Error{constructor(e="Input has an unsupported or unrecognizable format."){super(e),this.name="UnsupportedInputFormatError"}}class mo extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}}class po{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 mo;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 go(t,f(t),0,e,e)}const i=e+t,r=this.source._read(e,i,0,Ya);return ce(r)?r.then(t=>t?new go(t.bytes,t.view,t.offset,e,i):null):r?new go(r.bytes,r.view,r.offset,e,i):null}requestSliceRange(e,t,i){if(this.source._disposed)throw new mo;if(e<0)return null;if(null!==this.fileSizeNonStrict)return this.requestSlice(e,U(this.fileSizeNonStrict-e,t,i));{const r=this.requestSlice(e,i),a=r=>r||(n(null!==this.fileSizeNonStrict),this.requestSlice(e,U(this.fileSizeNonStrict-e,t,i)));return ce(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(ce(i)&&(i=await i),!i||0===i.length)break;const r=yo(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 go(i,f(i),0,0,t)})()}}class go{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 go(e,f(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 go(this.bytes,this.view,this.offset,e,e+t)}}const ko=(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.`)},yo=(e,t)=>{ko(e,t);const i=e.bytes.subarray(e.bufferPos,e.bufferPos+t);return e.bufferPos+=t,i},bo=e=>(ko(e,1),e.view.getUint8(e.bufferPos++)),wo=(e,t)=>{ko(e,2);const i=e.view.getUint16(e.bufferPos,t);return e.bufferPos+=2,i},To=e=>{ko(e,2);const t=e.view.getUint16(e.bufferPos,!1);return e.bufferPos+=2,t},So=e=>{ko(e,3);const t=O(e.view,e.bufferPos,!1);return e.bufferPos+=3,t},vo=e=>{ko(e,2);const t=e.view.getInt16(e.bufferPos,!1);return e.bufferPos+=2,t},Po=(e,t)=>{ko(e,4);const i=e.view.getUint32(e.bufferPos,t);return e.bufferPos+=4,i},Io=e=>{ko(e,4);const t=e.view.getUint32(e.bufferPos,!1);return e.bufferPos+=4,t},xo=e=>{ko(e,4);const t=e.view.getUint32(e.bufferPos,!0);return e.bufferPos+=4,t},Co=e=>{ko(e,4);const t=e.view.getInt32(e.bufferPos,!1);return e.bufferPos+=4,t},Bo=(e,t)=>{let i,r;return t?(i=Po(e,!0),r=Po(e,!0)):(r=Po(e,!1),i=Po(e,!1)),4294967296*r+i},Eo=e=>4294967296*Io(e)+Io(e),_o=e=>4294967296*Co(e)+Io(e),Ro=e=>{const t=xo(e),i=(e=>{ko(e,4);const t=e.view.getInt32(e.bufferPos,!0);return e.bufferPos+=4,t})(e);return 4294967296*i+t},Fo=e=>{ko(e,4);const t=e.view.getFloat32(e.bufferPos,!1);return e.bufferPos+=4,t},Ao=e=>{ko(e,8);const t=e.view.getFloat64(e.bufferPos,!1);return e.bufferPos+=8,t},Do=(e,t)=>{ko(e,t);let i="";for(let r=0;rm.decode(yo(e,t)).split("\n").map(e=>e.trim()).filter(e=>e.length>0&&!i?.ignore?.(e));var No,Oo,Lo,zo;(Oo=No||(No={}))[Oo.Unsynchronisation=128]="Unsynchronisation",Oo[Oo.ExtendedHeader=64]="ExtendedHeader",Oo[Oo.ExperimentalIndicator=32]="ExperimentalIndicator",Oo[Oo.Footer=16]="Footer",(zo=Lo||(Lo={}))[zo.ISO_8859_1=0]="ISO_8859_1",zo[zo.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",zo[zo.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",zo[zo.UTF_8=3]="UTF_8";const Uo=128,qo=10,Wo=["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"],Ho=(e,t)=>{var i;const r=e.filePos;t.raw??(t.raw={}),(i=t.raw).TAG??(i.TAG=yo(e,Uo-3)),e.filePos=r;const a=Vo(e,30);a&&(t.title??(t.title=a));const s=Vo(e,30);s&&(t.artist??(t.artist=s));const n=Vo(e,30);n&&(t.album??(t.album=n));const o=Vo(e,4),c=Number.parseInt(o,10);Number.isInteger(c)&&c>0&&(t.date??(t.date=new Date(String(c))));const l=yo(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=Vo(e,28),e.skip(2)}else e.skip(-30),u=Vo(e,30);u&&(t.comment??(t.comment=u));const d=bo(e);d{const i=yo(e,t),r=le(i.indexOf(0),i.length),a=i.subarray(0,r);let s="";for(let n=0;n{const t=e.filePos,i=Do(e,3),r=bo(e),a=bo(e),s=bo(e),n=Io(e);if("ID3"!==i||255===r||255===a||0!==(2155905152&n))return e.filePos=t,null;let o=fi(n);return s&No.Footer&&(o+=qo),{majorVersion:r,revision:a,flags:s,size:o}},Ko=(e,t,i)=>{var r,a,s,n,o;if(![2,3,4].includes(t.majorVersion))return void ve._warn(`Unsupported ID3v2 major version: ${t.majorVersion}`);const c=t.flags&No.Footer?t.size-qo:t.size,l=yo(e,c),u=new Xo(t,l);if(t.flags&No.Unsynchronisation&&3===t.majorVersion&&u.ununsynchronizeAll(),t.flags&No.ExtendedHeader){const e=u.readU32();3===t.majorVersion?u.pos+=e:u.pos+=e-4}for(;u.pos<=u.bytes.length-u.frameHeaderSize();){const e=u.readId3V2Frame();if(!e)break;const c=u.pos,l=u.pos+e.size;let d=!1,h=!1,f=!1;if(3===t.majorVersion?(d=!!(64&e.flags),h=!!(128&e.flags)):4===t.majorVersion&&(d=!!(4&e.flags),h=!!(8&e.flags),f=!!(2&e.flags)||!!(t.flags&No.Unsynchronisation)),d)ve._warn(`Skipping encrypted ID3v2 frame ${e.id}`),u.pos=l;else if(h)ve._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!==Wo[e]){i.genre??(i.genre=Wo[e]);break}}if(t=/^\d+$/.exec(e),t){const e=Number.parseInt(t[0]);if(void 0!==Wo[e]){i.genre??(i.genre=Wo[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 Xo{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:fi(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 Lo.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=le(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=le(r.findIndex(e=>0===e),r.length);return this.pos=i+Math.min(e+1,r.length),m.decode(r.subarray(0,e))}case Lo.UTF_16_BE_NO_BOM:{const e=new TextDecoder("utf-16be"),t=le(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 Lo.UTF_8:{const e=le(r.findIndex(e=>0===e),r.length);return this.pos=i+Math.min(e+1,r.length),m.decode(r.subarray(0,e))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";const t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}}class $o{constructor(e){this.events=e,this.input=null,this.audioSink=null,this.audioIterator=null,this.audioContext=null,this.gainNode=null,this.audioContextStartTime=0,this.playbackTimeAtStart=0,this.latestScheduledEndTime=0,this.duration=Number.NaN,this.paused=!0,this.volume=.7,this.muted=!1,this.playbackRate=1,this.asyncId=0,this.queuedNodes=new Set}get currentTime(){return this.paused?this.playbackTimeAtStart:(this.audioContext.currentTime-this.audioContextStartTime)*this.playbackRate+this.playbackTimeAtStart}ensureAudioContext(e){if(this.audioContext)return;const t=window.AudioContext||window.webkitAudioContext;try{this.audioContext=new t({sampleRate:e})}catch{this.audioContext=new t}this.gainNode=this.audioContext.createGain(),this.gainNode.connect(this.audioContext.destination),this.updateGain()}updateGain(){if(!this.gainNode)return;const e=this.muted?0:this.volume;this.gainNode.gain.value=e*e}stopQueuedNodes(){this.queuedNodes.forEach(e=>e.stop()),this.queuedNodes.clear()}async stopIterator(){await(this.audioIterator?.return()),this.audioIterator=null}handleNoAudioTrack(){this.audioSink=null,this.ensureAudioContext()}async load(e,t){++this.asyncId,await this.stopIterator(),this.stopQueuedNodes(),this.paused=!0,this.playbackTimeAtStart=0,this.audioContextStartTime=0;const{input:i,audioTrack:r,duration:a}=e;return this.input=i,this.duration=a,r?null!==r.codec&&await r.canDecode()?(this.ensureAudioContext(r.sampleRate),this.audioSink=new Qn(r),void t?.()):(this.audioSink=null,this.ensureAudioContext(),void t?.()):(this.handleNoAudioTrack(),void t?.())}async runIterator(e){if(!this.audioSink)return;await this.stopIterator(),this.audioIterator=this.audioSink.buffers(this.currentTime);for(;;){if(e!==this.asyncId||this.paused)return;const i=[];let r=!1;try{for(let e=0;e<16;e++){const e=await this.audioIterator.next();if(e.done){r=!0;break}i.push(e.value)}}catch(t){console.error("Audio iterator error:",t),r=!0}if(e!==this.asyncId||this.paused)return;i.length>0&&"suspended"===this.audioContext.state&&(await this.audioContext.resume(),this.events.emit("canplay"),this.events.emit("playing"));for(const{buffer:e,timestamp:t}of i){const i=this.audioContext.createBufferSource();i.buffer=e,i.connect(this.gainNode),i.playbackRate.value=this.playbackRate;const r=this.audioContextStartTime+(t-this.playbackTimeAtStart)/this.playbackRate,a=(r+e.duration/this.playbackRate-this.audioContextStartTime)*this.playbackRate+this.playbackTimeAtStart;a>this.latestScheduledEndTime&&(this.latestScheduledEndTime=a),r>=this.audioContext.currentTime?i.start(r):i.start(this.audioContext.currentTime,(this.audioContext.currentTime-r)*this.playbackRate),this.queuedNodes.add(i),i.onended=()=>this.queuedNodes.delete(i)}if(r)break;await new Promise(e=>setTimeout(e,0));const a=1;for(;this.latestScheduledEndTime-this.currentTime>a;){if(e!==this.asyncId||this.paused)return;await new Promise(e=>setTimeout(e,50))}}}async play(){if(!this.paused)return;this.audioContext||this.ensureAudioContext(),"suspended"===this.audioContext.state&&await this.audioContext.resume(),this.audioContextStartTime=this.audioContext.currentTime,this.latestScheduledEndTime=this.playbackTimeAtStart,this.paused=!1;const e=++this.asyncId;this.runIterator(e)}pause(){this.paused||(this.playbackTimeAtStart=this.currentTime,this.paused=!0,this.stopIterator(),this.stopQueuedNodes())}async seek(e){this.playbackTimeAtStart=Math.max(0,e),this.audioContextStartTime=this.audioContext.currentTime,this.latestScheduledEndTime=this.playbackTimeAtStart;const t=++this.asyncId;this.paused||this.runIterator(t)}setVolume(e,t){this.volume=e,this.muted=t,this.updateGain()}setPlaybackRate(e){if(e!==this.playbackRate&&(this.paused||(this.playbackTimeAtStart=this.currentTime,this.audioContextStartTime=this.audioContext.currentTime),this.playbackRate=e,!this.paused)){const e=++this.asyncId;this.runIterator(e)}}destroy(){this.asyncId++,this.pause(),this.audioContext?.close(),this.audioContext=null,this.input=null,this.audioSink=null}}async function Go(e){return await e.getAverageBitrate()??await e.getBitrate()??0}const Qo=/\.m3u8(?:$|[?#])/i;function Yo(e){return"string"===typeof e&&Qo.test(e)}function Jo(e){const t=function(e){return"string"===typeof e?new os(e):e instanceof Blob?new as(e):"undefined"!==typeof ReadableStream&&e instanceof ReadableStream?new us(e):e??null}(e);return t?new ho({source:t,formats:Yo(e)?Ys:Qs}):null}class Zo{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 ec({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}class tc{constructor({canvas:e,ctx:t,events:i,timeupdateInterval:r=250,avSyncTolerance:a=.12,dropLateFrames:s=!1,poster:n="",preflightRange:o=!1}){this.canvas=e,this.ctx=t,this.events=i,this.timeupdateInterval=r,this.avSyncTolerance=a,this.dropLateFrames=s,this.poster=n,this.preflightRange=o,this.input=null,this.videoSink=null,this.videoIterator=null,this.nextFrame=null,this.rafId=0,this.asyncId=0,this.width=0,this.height=0,this.duration=Number.NaN,this.audioClock=null,this.lastTimeUpdate=0,this.stalled=!1,this.playbackRate=1,this.posterDrawn=!1,this.isFetching=!1}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||Yo(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(!this.poster||this.posterDrawn)return;const e=new Image;e.onload=()=>{this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.canvas.width=e.naturalWidth||this.canvas.width,this.canvas.height=e.naturalHeight||this.canvas.height,this.ctx.drawImage(e,0,0,this.canvas.width,this.canvas.height),this.posterDrawn=!0},e.src=this.poster}async stopIterator(){await(this.videoIterator?.return()),this.videoIterator=null}clear(){this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height)}async load(e,t){++this.asyncId,await this.stopIterator(),this.clear(),this.posterDrawn=!1;const{input:i,videoTrack:r,duration:a}=e;if(this.input=i,this.duration=a,!r)return this.handleNoVideoTrack(),void t?.();if(null===r.codec||!(await r.canDecode()))return this.handleNoVideoTrack(),void t?.();const s=await r.canBeTransparent();this.videoSink=new Kn(r,{poolSize:2,fit:"contain",alpha:s}),this.width=r.displayWidth,this.height=r.displayHeight,this.canvas.width=this.width,this.canvas.height=this.height,t?.(),await this.resetIterator(0)}handleNoVideoTrack(){this.videoSink=null,this.width=0,this.height=0,this.canvas.width=0,this.canvas.height=0,this.clear(),this.drawPoster()}async resetIterator(e){if(await this.stopIterator(),!this.videoSink)return;this.videoIterator=this.videoSink.canvases(e);const t=(await this.videoIterator.next()).value??null,i=(await this.videoIterator.next()).value??null;this.nextFrame=i,t?this.ctx.drawImage(t.canvas,0,0):this.drawPoster()}async updateNextFrame(e){if(this.videoIterator&&!this.isFetching){this.isFetching=!0;try{for(;;){const t=(await this.videoIterator.next()).value??null;if(!t||e!==this.asyncId)return;const i=this.audioClock.currentTime,r=this.dropLateFrames?Math.max(.06,this.avSyncTolerance/Math.max(1,this.playbackRate)):0;if(!(this.dropLateFrames&&t.timestampi)return void(this.nextFrame=null)}}}finally{this.isFetching=!1}}}render(){if(!this.audioClock)return;const e=this.audioClock.currentTime,t=Date.now();if(t-this.lastTimeUpdate>=this.timeupdateInterval&&(this.events.emit("timeupdate"),this.lastTimeUpdate=t),Number.isFinite(this.duration)&&e>=this.duration)return this.stop(),this.stalled=!1,this.events.emit("ended"),this.events.emit("pause"),void this.events.emit("canplay");this.nextFrame&&this.nextFrame.timestamp<=e?(this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.ctx.drawImage(this.nextFrame.canvas,0,0),this.nextFrame=null,this.updateNextFrame(this.asyncId),this.stalled&&(this.events.emit("canplay"),this.events.emit("playing"),this.stalled=!1)):this.nextFrame||(this.updateNextFrame(this.asyncId),!this.nextFrame&&Number.isFinite(this.duration)&&ethis.render())}start(e){this.audioClock=e,this.asyncId++,this.stalled=!1,this.updateNextFrame(this.asyncId),this.rafId=requestAnimationFrame(()=>this.render())}stop(){cancelAnimationFrame(this.rafId)}async seek(e){this.asyncId++,await this.resetIterator(e)}setPlaybackRate(e){this.playbackRate=Math.max(.1,Number(e)||1)}destroy(){this.asyncId++,this.stop(),this.stopIterator(),this.posterDrawn=!1,this.videoSink=null,this.input=null}}class ic{constructor({canvas:e,ctx:t,events:i,option:r={}}){this.events=i,this.option=r,this.audio=new $o(i),this.video=new tc({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}),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,i.addEventListener?.("ended",()=>{this.ended=!0,this.paused=!0})}async load(e){if(this.destroyed)return;const t=++this.loadSeq;if(this.loadSession?.cancel(),t!==this.loadSeq||this.destroyed)return;if(this.pause(),t!==this.loadSeq||this.destroyed)return;this.disposeInput();const i=new Zo;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;try{await i.wait(this.performLoad(e,t,i),r)}catch(a){if(t!==this.loadSeq)return;const e=++this.loadSeq;if(i.cancel(),e!==this.loadSeq||this.destroyed)return;this.disposeInput(),this.error={code:4,message:a.message},this.networkState=3,this.events.emit("error")}}async performLoad(e,t,i=this.loadSession){if(!(await this.video.preflight(e,i?.signal,()=>t===this.loadSeq))||t!==this.loadSeq)return;const r=Jo(e);if(!r)return this.video.handleNoVideoTrack(),void this.audio.handleNoAudioTrack();i.own(r);const a=await async function(e,t){const i=await e.getPrimaryVideoTrack(),r=i?await i.getPrimaryPairableAudioTrack():await e.getPrimaryAudioTrack(),a=await ec({input:e,videoTrack:i,audioTrack:r}),s=i||r,n=Yo(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"}}(r,e);if(t!==this.loadSeq)return;this.input=r,this.media=a;let s=!a.videoTrack,n=!a.audioTrack;const o=()=>{s&&n&&(this.readyState=1,this.events.emit("loadedmetadata"),this.events.emit("durationchange"),this.events.emit("progress"))};try{if(await Promise.all([this.video.load(a,()=>{t===this.loadSeq&&(s=!0,o())}),this.audio.load(a,()=>{t===this.loadSeq&&(n=!0,o())})]),t!==this.loadSeq)return;this.readyState=4,this.networkState=1,this.events.emit("loadeddata"),this.events.emit("canplay"),this.events.emit("canplaythrough"),this.events.emit("progress")}catch(c){if(t!==this.loadSeq)return;throw console.error("MediaBunny load error:",c),c}}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({videoTrack:e,audioTrack:t,videoMode:i,audioMode:r}){if(!this.media)return;const a={...this.media,videoTrack:e,audioTrack:t,videoMode:i,audioMode:r},s=!this.paused,n=this.currentTime;this.pause(),this.ended=!1,this.seeking=!0,this.events.emit("seeking"),this.events.emit("waiting"),a.duration=await ec(a),this.media=a,await Promise.all([this.video.load(a),this.audio.load(a)]),await Promise.all([this.video.seek(n),this.audio.seek(n)]),this.readyState=4,this.networkState=1,this.seeking=!1,this.events.emit("loadedmetadata"),this.events.emit("durationchange"),this.events.emit("progress"),this.events.emit("loadeddata"),this.events.emit("canplay"),this.events.emit("canplaythrough"),this.events.emit("seeked"),s&&await this.play()}async selectHlsQuality(e){if(!this.media?.isHls||!this.input)return;const t=await this.input.getVideoTracks(),i="auto"===e?await this.input.getPrimaryVideoTrack():t.find(t=>t.id===e)??this.media.videoTrack;if(!i)return;let r=this.media.audioTrack,a=this.media.audioMode;r&&i.canBePairedWith(r)||(r=await i.getPrimaryPairableAudioTrack(),a="auto"),await this.replaceTracks({videoTrack:i,audioTrack:r,videoMode:"auto"===e?"auto":"manual",audioMode:a})}async selectHlsAudio(e){if(!this.media?.isHls||!this.input)return;const t=await this.input.getAudioTracks(),i="auto"===e?this.media.videoTrack?await this.media.videoTrack.getPrimaryPairableAudioTrack():await this.input.getPrimaryAudioTrack():t.find(t=>t.id===e)??this.media.audioTrack;if(!i)return;let r=this.media.videoTrack,a=this.media.videoMode;r&&i.canBePairedWith(r)||(r=await i.getPrimaryPairableVideoTrack(),a="auto"),await this.replaceTracks({videoTrack:r,audioTrack:i,videoMode:a,audioMode:"auto"===e?"auto":"manual"})}getHlsState(){return 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 Go(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 Go(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"}}(this.media)}async play(){this.paused&&(this.ended&&(this.ended=!1,await this.seek(0)),this.paused=!1,await this.audio.play(),this.video.start(this.audio),this.events.emit("play"),this.events.emit("playing"))}pause(){this.paused||(this.paused=!0,this.audio.pause(),this.video.stop(),this.events.emit("pause"))}async seek(e){const t=!this.paused;this.ended=!1,this.seeking=!0,this.events.emit("seeking"),this.events.emit("waiting"),this.pause(),await Promise.all([this.audio.seek(e),this.video.seek(e)]),this.seeking=!1,this.events.emit("seeked"),t&&!this.ended&&await this.play()}setVolume(e,t){this.audio.setVolume(e,t)}setPlaybackRate(e){this.audio.setPlaybackRate(e),this.video.setPlaybackRate(e)}destroy(){this.destroyed||(this.destroyed=!0,this.loadSeq++,this.loadSession?.cancel(),this.pause(),this.disposeInput(),this.audio.destroy(),this.video.destroy())}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}}const rc=new WeakMap;function ac(e){let t=rc.get(e);return t||(t={closed:!1,frames:new Set},rc.set(e,t)),t}class sc{constructor({art:e,canvas:t,ctx:i,option:r}){this.art=e,this.canvas=t,this.option=r,this.events=new s,this.engine=new ic({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){this.engine.seek(Number(e)||0)}get duration(){return this.engine.duration}get buffered(){return this.createTimeRanges(0,this.engine.duration)}get played(){return this.createTimeRanges(0,this.engine.currentTime)}get seekable(){return this.createTimeRanges(0,this.engine.duration)}createTimeRanges(e,t){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=ac(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){ac(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=ac(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,s=r("canvas"),n=s.getContext("2d"),o=new sc({art:t,canvas:s,ctx:n,option:e});t.mediabunny=o;const c={};for(const e in s)"function"===typeof s[e]&&(c[e]=s[e].bind(s));const l=new Set([...Object.getOwnPropertyNames(o),...Object.getOwnPropertyNames(Object.getPrototypeOf(o))]);for(const e of l)"constructor"!==e&&(e in s||Object.defineProperty(s,e,{get(){const t=o[e];return"function"===typeof t?t.bind(o):t},set(t){o[e]=t},configurable:!0,enumerable:!0}));for(const e in c)s[e]=(...t)=>c[e](...t);function u(){const e=t.template?.$player;e&&!t.option.autoSize&&Object.assign(s.style,{width:"100%",height:"100%",objectFit:"contain"})}return t.on("resize",u),t.on("video:loadedmetadata",u),function({art:e,shim:t,option:i}){if(i.m3u8)return e.on("video:loadedmetadata",d),e.on("restart",d),{update:d};function r(t){e.controls.cache.has(t)&&e.controls.remove(t)}function s(t){e.setting.find(t)&&e.setting.remove(t)}function n(){r("mediabunny-quality"),s("mediabunny-quality")}function o(){r("mediabunny-audio"),s("mediabunny-audio")}function c(e={}){return e.control||e.setting}async function l(r){const s=i.m3u8?.quality||{};if(!c(s)||!r?.levels.length)return void n();const o=s.auto||"Auto",l=s.title||"Quality",u=s.getName||(e=>e.name||`${e.height}P`),h=r.currentLevel?u(r.currentLevel):o,f=a(r.levels.map(e=>({html:u(e),value:e.id,default:r.currentLevel?.id===e.id})),"html").sort((e,t)=>{const i=r.levels.find(t=>t.id===e.value),a=r.levels.find(e=>e.id===t.value);return(a?.height||0)-(i?.height||0)});f.push({html:o,value:"auto",default:!r.currentLevel});const m=async i=>(await t.switchM3u8Quality(i.value),e.notice.show=`${l}: ${i.html}`,await d(),i.html);s.control&&e.controls.update({name:"mediabunny-quality",position:"right",html:h,style:{padding:"0 10px"},selector:f,onSelect:m}),s.setting&&e.setting.update({name:"mediabunny-quality",tooltip:h,html:l,icon:'',width:200,selector:f,onSelect:m})}async function u(r){const s=i.m3u8?.audio||{};if(!c(s)||!r?.audios.length||r.audios.length<2)return void o();const n=s.auto||"Auto",l=s.title||"Audio",u=s.getName||(e=>e.name||e.lang||e.language),h=r.currentAudio?u(r.currentAudio):n,f=a(r.audios.map(e=>({html:u(e),value:e.id,default:r.currentAudio?.id===e.id})),"html");f.push({html:n,value:"auto",default:!r.currentAudio});const m=async i=>(await t.switchM3u8Audio(i.value),e.notice.show=`${l}: ${i.html}`,await d(),i.html);s.control&&e.controls.update({name:"mediabunny-audio",position:"right",html:h,style:{padding:"0 10px"},selector:f,onSelect:m}),s.setting&&e.setting.update({name:"mediabunny-audio",tooltip:h,html:l,icon:'',width:200,selector:f,onSelect:m})}async function d(){const e=await t.getM3u8State();if(!e)return n(),void o();await Promise.all([l(e),u(e)])}}({art:t,shim:o,option:e}),t.on("destroy",()=>{delete t.mediabunny,o.destroy()}),s}}}); +!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=e=>{throw TypeError(e)},r=(e,t,r)=>t.has(e)||i("Cannot "+r),a=(e,t,i)=>(r(e,t,"read from private field"),i?i.call(e):t.get(e)),s=(e,t,r)=>t.has(e)?i("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),n=(e,t,i,a)=>(r(e,t,"write to private field"),a?a.call(e,i):t.set(e,i),i);function o(e,t){const i=new Map;return e.filter(e=>{const r=e[t];return void 0===r||!i.has(r)&&i.set(r,1)})}class c{constructor(){s(this,e,!1),this.listeners=new Map}addEventListener(t,i){a(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(a(this,e))return;const r=Object.assign(new Event(t),{detail:i});this.listeners.get(t)?.forEach(t=>{a(this,e)||t(r)})}destroy(){n(this,e,!0),this.listeners.clear()}}function l(e){if(!e)throw new Error("Assertion failed.")}e=new WeakMap;const u=e=>{const t=(e%360+360)%360;if(0===t||90===t||180===t||270===t)return t;throw new Error(`Invalid rotation ${e}.`)},d=e=>e&&e[e.length-1],h=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)},m=e=>{const t=h(e);return 0===(1&t)?-(t>>1):t+1>>1},p=e=>e.constructor===Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),g=e=>e.constructor===DataView?e:ArrayBuffer.isView(e)?new DataView(e.buffer,e.byteOffset,e.byteLength):new DataView(e),k=new TextDecoder,y=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])),b={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},w=y(b),T={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},S=y(T),v={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},P=y(v),I=e=>!!e&&!!e.primaries&&!!e.transfer&&!!e.matrix&&void 0!==e.fullRange,x={primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0},C=e=>e instanceof ArrayBuffer||"undefined"!==typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e);class B{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 E=/^[0-9a-fA-F]+$/,_=e=>[...e].map(e=>e.toString(16).padStart(2,"0")).join(""),R=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,F=(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},D=(e,t,i)=>{const r=A(e,i(t),i);e.splice(r+1,0,t)},M=()=>{let e,t;return{promise:new Promise((i,r)=>{e=i,t=r}),resolve:e,reject:t}},N=(e,t)=>{const i=e.indexOf(t);-1!==i&&e.splice(i,1)},O=(e,t)=>{for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},L=(e,t)=>{for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},z=e=>{throw new Error(`Unexpected value: ${e}`)},U=(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},q=(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)},W=(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}}),H=(e,t,i)=>Math.max(t,Math.min(i,e)),V="und",j=e=>{const t=Math.round(e);return Math.abs(e/t-1)<10*Number.EPSILON?t:e},K=(e,t)=>Math.round(e/t)*t,X=(e,t)=>Math.round(e*t)/t,$=(e,t)=>Math.floor(e/t)*t,G=e=>{let t=0;for(;0!==e;)e&=e-1,t++;return t},Q=/^[a-z]{3}$/,Y=e=>Q.test(e),J=1e6*(1+Number.EPSILON),Z=(e,t)=>{const i={...e,...t};if(e.headers||t.headers){const r=e.headers?ee(e.headers):{},a=t.headers?ee(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},ee=e=>{if(e instanceof Headers){const t={};return e.forEach((e,i)=>{t[i]=e}),t}if(Array.isArray(e)){const t={};return e.forEach(([e,i])=>{t[e]=i}),t}return e},te=async(e,t,i,r,a)=>{let s=0;for(;;)try{return await e(t,i)}catch(n){if(a())throw n;s++;const e=r(s,n,t);if(null===e)throw n;if(xe._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 Se(1e3*e),a())throw n}};class ie{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}let re=null;const ae=()=>null!==re?re:re=!("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 se=null;const ne=()=>null!==se?se:se="undefined"!==typeof navigator&&navigator.userAgent?.includes("Firefox");let oe=null;const ce=()=>null!==oe?oe:oe=!("undefined"===typeof navigator||!navigator.vendor?.includes("Google Inc")&&!/Chrome/.test(navigator.userAgent)),le=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.`,ue=(async()=>{})().constructor,de=e=>e instanceof ue||e instanceof Promise||"function"===typeof e?.then,he=(e,t)=>-1!==e?e:t,fe=(e,t,i,r)=>e<=r&&i<=t,me=e=>{const t=atob(e),i=new Uint8Array(t.length);for(let r=0;r{Symbol.dispose??(Symbol.dispose=Symbol("Symbol.dispose"))},ge=e=>"number"===typeof e&&!Number.isNaN(e),ke=(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("/")},ye=(e,t)=>{let i=0;for(let r=0;r{let i=-1,r=1/0;for(let a=0;a{l(Number.isInteger(e.num)),l(Number.isInteger(e.den)),l(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}},Te=(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.`)},Se=e=>new Promise(t=>setTimeout(t,e));class ve{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 Pe,Ie;(Ie=Pe||(Pe={}))[Ie.Silent=0]="Silent",Ie[Ie.Errors=1]="Errors",Ie[Ie.Warnings=2]="Warnings",Ie[Ie.Info=3]="Info";class xe{constructor(){}static get level(){return xe._level}static set level(e){if(e!==Pe.Silent&&e!==Pe.Errors&&e!==Pe.Warnings&&e!==Pe.Info)throw new TypeError("Invalid log level. Use one of the values of the LogLevel enum.");xe._level=e}static get _emitter(){return xe._emitterInstance??(xe._emitterInstance=new ve)}static on(e,t,i){return xe._emitter.on(e,t,i)}static _error(...e){xe._emitter._emit("error",e),xe._level>=Pe.Errors&&console.error(...e)}static _warn(...e){xe._emitter._emit("warn",e),xe._level>=Pe.Warnings&&console.warn(...e)}static _info(...e){xe._emitter._emit("info",e),xe._level>=Pe.Info&&console.info(...e)}}xe._level=Pe.Info,xe._emitterInstance=null;class Ce{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 Be{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 Ee={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1};class _e{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 _e(this.bytes);return e.pos=this.pos,e}}const Re=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],Fe=[-1,1,2,3,4,5,6,8],Ae=e=>{if(!e||e.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");const t=new _e(e),i=De(t),{frequencyIndex:r,sampleRate:a}=Me(t),s=t.readBits(4);let n=null;s>=1&&s<=7&&(n=Fe[s]);let o=i,c=!1,l=a;if(5===i||29===i)c=29===i,l=Me(t).sampleRate,o=De(t),22===o&&t.skipBits(4);else for(;t.getBitsLeft()>15;){const e=t.pos;if(695===t.readBits(11)){5===De(t)&&t.readBits(1)&&(l=Me(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}},De=e=>{const t=e.readBits(5);return 31===t?32+e.readBits(6):t},Me=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&p(t.description)[4];return He(e,i+1)}return We(e)},je=e=>31&e,Ke=e=>{const t=[],i=e.length;for(let r=0;r{const t=e.reduce((e,t)=>e+Xe.byteLength+t.byteLength,0),i=new Uint8Array(t);let r=0;for(const a of e)i.set(Xe,r),r+=Xe.byteLength,i.set(a,r),r+=a.byteLength;return i},Ge=(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:q(e,a,s.byteLength);break;case 4:e.setUint32(a,s.byteLength,!1)}a+=t,r.set(s,a),a+=s.byteLength}return r},Qe=e=>{try{const t=[],i=[],r=[];for(const o of We(e)){const a=e.subarray(o.offset,o.offset+o.length),s=je(a[0]);s===Le.SPS?t.push(a):s===Le.PPS?i.push(a):s===Le.SPS_EXT&&r.push(a)}if(0===t.length)return null;if(0===i.length)return null;const a=t[0],s=et(a);l(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 xe._error("Error building AVC Decoder Configuration Record:",t),null}},Ye=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=g(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=Ke(e),i=new _e(t);i.skipBits(1),i.skipBits(2);if(7!==i.readBits(5))return null;const r=i.readAlignedByte(),a=i.readAlignedByte(),s=i.readAlignedByte();h(i);let n=1,o=0,c=0,u=0;if(100===r||110===r||122===r||244===r||44===r||83===r||86===r||118===r||128===r){n=h(i),3===n&&(u=i.readBits(1)),o=h(i),c=h(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)??d(Yt),r=Math.min(Math.floor(i.maxDpbMbs/(e*t)),16);C=r,B=r}else C=0,B=0}return l(null!==B),{emulationUnpreventedBytes:t,profileIdc:r,constraintFlags:a,levelIdc:s,frameMbsOnlyFlag:T,chromaFormatIdc:n,bitDepthLumaMinus8:o,bitDepthChromaMinus8:c,codedWidth:k,codedHeight:y,displayWidth:b,displayHeight:w,pixelAspectRatio:x,colourPrimaries:S,matrixCoefficients:P,transferCharacteristics:v,fullRangeFlag:I,numReorderFrames:C,maxDecFrameBuffering:B,vuiParametersFlagBitOffset:R,bitstreamRestrictionFlagBitOffset:E,bitstreamRestrictionFlag:_}}catch(t){return xe._error("Error parsing AVC SPS:",t),null}},tt=e=>{const t=h(e);e.skipBits(4),e.skipBits(4);for(let i=0;i<=t;i++)h(e),h(e),e.skipBits(1);e.skipBits(5),e.skipBits(5),e.skipBits(5),e.skipBits(5)},it=e=>{l(1!==e.bitstreamRestrictionFlag);const t=new Uint8Array(e.emulationUnpreventedBytes.byteLength+64),i=new _e(e.emulationUnpreventedBytes),r=new _e(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)):(l(null!==e.bitstreamRestrictionFlagBitOffset),r.copyBits(e.bitstreamRestrictionFlagBitOffset,i)),r.writeBits(1,1),r.writeBits(1,1),f(r,2),f(r,1),f(r,16),f(r,16),f(r,e.numReorderFrames),f(r,e.maxDecFrameBuffering),r.writeBits(1,1),r.writeBits((8-r.pos%8)%8,0);const a=r.pos/8;return l(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))},rt=(e,t)=>{if(t.description){const i=3&p(t.description)[21];return He(e,i+1)}return We(e)},at=e=>e>>1&63,st=e=>{try{const t=new _e(Ke(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}=ot(t,i);h(t);const u=h(t);let d=0;3===u&&(d=t.readBits(1));const f=h(t),m=h(t);let p=f,g=m;if(t.readBits(1)){const e=h(t),i=h(t),r=h(t),a=h(t);let s=1,n=1;const o=0===d?u:0;1===o?(s=2,n=2):2===o&&(s=2,n=1),p-=(e+i)*s,g-=(r+a)*n}const k=h(t),y=h(t);h(t);const b=t.readBits(1);let w=0;for(let e=b?0:i;e<=i;e++)h(t),w=h(t),h(t);h(t),h(t),h(t),h(t),h(t),h(t),t.readBits(1)&&t.readBits(1)&&ct(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(4),t.skipBits(4),h(t),h(t),t.skipBits(1));const T=h(t);if(lt(t,T),t.readBits(1)){const e=h(t);for(let i=0;i{try{const t=[],i=[],r=[],a=[];for(const c of We(e)){const s=e.subarray(c.offset,c.offset+c.length),n=at(s[0]);n===Ue.VPS_NUT?t.push(s):n===Ue.SPS_NUT?i.push(s):n===Ue.PPS_NUT?r.push(s):n!==Ue.PREFIX_SEI_NUT&&n!==Ue.SUFFIX_SEI_NUT||a.push(s)}if(0===i.length||0===r.length)return null;const s=st(i[0]);if(!s)return null;let n=0;if(r.length>0){const e=r[0],t=new _e(Ke(e));t.skipBits(16),h(t),h(t),t.skipBits(1),t.skipBits(1),t.skipBits(3),t.skipBits(1),t.skipBits(1),h(t),h(t),m(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&h(t),m(t),m(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:Ue.VPS_NUT,nalUnits:t}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:Ue.SPS_NUT,nalUnits:i}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:Ue.PPS_NUT,nalUnits:r}]:[],...a.length?[{arrayCompleteness:1,nalUnitType:at(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 xe._error("Error building HEVC Decoder Configuration Record:",t),null}},ot=(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&&m(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-(h(e)+1)}else n=t-1;e.readBits(1),h(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=h(e),i=h(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=Ze[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)&&(h(e),h(e)),e.readBits(1),e.readBits(1),e.readBits(1),e.readBits(1)&&(h(e),h(e),h(e),h(e)),e.readBits(1)&&(e.readBits(32),e.readBits(32),e.readBits(1)&&h(e),e.readBits(1)&&ht(e,!0,t)),e.readBits(1)&&(e.readBits(1),e.readBits(1),e.readBits(1),n=h(e),h(e),h(e),h(e),h(e)),{pixelAspectRatio:o,colourPrimaries:i,transferCharacteristics:r,matrixCoefficients:a,fullRangeFlag:s,minSpatialSegmentationIdc:n}},ht=(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?h(e):i=1===e.readBits(1);let n=1;if(!i){n=h(e)+1}r&&ft(e,n,s),a&&ft(e,n,s)}},ft=(e,t,i)=>{for(let r=0;r{const i=new Set;let r=mt.audAllowed;for(const s of rt(e,t)){if(r===mt.noMoreDataAllowed){i.add(s.offset);continue}const t=at(e[s.offset]);if(r===mt.eoBitstreamAllowed&&37!==t){i.add(s.offset);continue}let a=!1;35===t?r>mt.audAllowed?a=!0:r=mt.beforeFirstVcl:t<=31?r>mt.afterFirstVcl?a=!0:r=mt.afterFirstVcl:36===t?r!==mt.afterFirstVcl?a=!0:r=mt.eoBitstreamAllowed:37===t?r=41&&t<=44||t>=48&&t<=55?r>mt.beforeFirstVcl?a=!0:r=mt.beforeFirstVcl:(38===t||40===t||t>=45&&t<=47||t>=56&&t<=63)&&r{if(t.description){const i=3&p(t.description)[21];return Ge(e,i+1)}return $e(e)})(a,t)},kt={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}},yt=e=>{const t=new _e(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=d(Jt).level;for(const d of Jt)if(c<=d.maxPictureSize){l=d.level;break}const u=kt[s];return{profile:r,level:l,bitDepth:a,chromaSubsampling:n,videoFullRangeFlag:o,colourPrimaries:u?.colourPrimaries??2,transferCharacteristics:u?.transferCharacteristics??2,matrixCoefficients:u?.matrixCoefficients??2}},bt=function*(e){const t=new _e(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);l(t.pos%8===0),yield{type:r,data:e.subarray(t.pos/8,t.pos/8+n)},t.skipBits(8*n)}},wt=e=>{for(const{type:t,data:i}of bt(e)){if(1!==t)continue;const e=new _e(i),r=e.readBits(3);e.readBits(1);const a=e.readBits(1);let s=0,n=0,o=0;if(a)s=e.readBits(5);else{let t=0;if(e.readBits(1)){e.skipBits(32),e.skipBits(32);if(e.readBits(1)){let t=0;for(;t<32&&!e.readBits(1);)t++;t<32&&e.skipBits(t)}t=e.readBits(1),t&&(o=e.readBits(5),e.skipBits(32),e.skipBits(5),e.skipBits(5))}const i=e.readBits(1),r=e.readBits(5);for(let a=0;a<=r;a++){e.skipBits(12);const r=e.readBits(5);if(0===a&&(s=r),r>7){const t=e.readBits(1);0===a&&(n=t)}if(t){if(e.readBits(1)){const t=o+1;e.skipBits(t),e.skipBits(t),e.skipBits(1)}}if(i){e.readBits(1)&&e.skipBits(4)}}}const c=e.readBits(4),l=e.readBits(4),u=c+1;e.skipBits(u);const d=l+1;e.skipBits(d);let h=0;if(h=a?0:e.readBits(1),h&&(e.skipBits(4),e.skipBits(3)),e.skipBits(1),e.skipBits(1),e.skipBits(1),!a){e.skipBits(1),e.skipBits(1),e.skipBits(1),e.skipBits(1);const t=e.readBits(1);t&&(e.skipBits(1),e.skipBits(1));let i=0;if(i=e.readBits(1)?2:e.readBits(1),i>0){e.readBits(1)||e.skipBits(1)}t&&e.skipBits(3)}e.skipBits(1),e.skipBits(1),e.skipBits(1);const f=e.readBits(1);let m=8;if(2===r&&f){m=e.readBits(1)?12:10}else r<=2&&(m=f?10:8);let p=0;1!==r&&(p=e.readBits(1));let g=2,k=2,y=2;e.readBits(1)&&(g=e.readBits(8),k=e.readBits(8),y=e.readBits(8));let b=0,w=1,T=1,S=0;return p?b=e.readBits(1):1===g&&13===k&&0===y?(b=1,w=0,T=0):(b=e.readBits(1),0===r?(w=1,T=1):1===r?(w=0,T=0):12===m?(w=e.readBits(1),T=w?e.readBits(1):0):(w=1,T=0),w&&T&&(S=e.readBits(2))),{profile:r,level:s,tier:n,bitDepth:m,monochrome:p,chromaSubsamplingX:w,chromaSubsamplingY:T,chromaSamplePosition:S,videoFullRangeFlag:b,colourPrimaries:g,transferCharacteristics:k,matrixCoefficients:y}}return null},Tt=e=>{if(e.length<36)return null;const t=g(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)}},St=[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],vt=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}},Pt=(e,t,i)=>{switch(e){case"avc":for(const e of Ve(i,t)){const t=i[e.offset],r=je(t);if(r>=Le.NON_IDR_SLICE&&r<=Le.SLICE_DPC)return"delta";if(r===Le.IDR)return"key";if(r===Le.SEI&&!ce()){const t=i.subarray(e.offset,e.offset+e.length),r=Ke(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 _e(r);e.pos=8*a;const t=h(e),i=e.readBits(1);if(0===t&&1===i)return"key"}a+=t}while(a{var i,r;const a=g(e);let s=0;const n=a.getUint32(s,!0);s+=4;const o=k.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=me(l),i=g(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=k.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})}}}},Bt=[2,1,2,3,3,4,4,5],Et=e=>{if(e.length<7)return null;if(11!==e[0]||119!==e[1])return null;const t=new _e(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)}},_t=[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],Rt=[1,2,3,6],Ft=e=>{if(e.length<6)return null;if(11!==e[0]||119!==e[1])return null;const t=new _e(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=Rt[s];let d;d=a<3?Ne[a]/1e3:Oe[n]/1e3;return{dataRate:Math.round((r+1)*d/(16*u)),substreams:[{fscod:a,fscod2:n,bsid:l,bsmod:0,acmod:o,lfeon:c,numDepSub:0,chanLoc:0}]}},At=e=>{const t=e.substreams[0];return l(t),t.fscod<3?Ne[t.fscod]:null!==t.fscod2&&t.fscod2<3?Oe[t.fscod2]:null},Dt=e=>{const t=e.substreams[0];l(t);let i=Bt[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},Mt=[0,8e3,16e3,32e3,0,0,11025,22050,44100,0,0,12e3,24e3,48e3,96e3,192e3],Nt=[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],Ot=[16,16,20,20,0,24,24,0],Lt=[1,2,2,2,2,3,3,4,4,5,6,6,6,7,8,8],zt=[1,2,2,2,2,3,18,19,6,7,518,323,83,519,582,535],Ut=[32e3,44100,48e3,0],qt=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],Wt=[512,1024,2048,4096],Ht=e=>{const t=jt(e),i=g(e);let r=t?4*Math.ceil(t.frameSize/4):0,a=null;for(;r+4<=e.length&&1683496997===i.getUint32(r);){const t=Kt(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}},Vt=e=>{const t=Ht(e);return t?.core?t.hasExtensions?"dtsh":"dtsc":null},jt=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 _e(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>=Lt.length)return null;const n=Mt[t.readBits(4)];if(0===n)return null;const o=Nt[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=Ot[t.readBits(3)];if(0===l)return null;const u=0!==c;return{frameSize:a,sampleRate:n,numberOfChannels:Lt[s]+(u?1:0),sampleCount:32*r,channelLayout:zt[s]|(u?8:0),amode:s,lfePresent:u,bitRate:o,pcmResolution:l}},Kt=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 _e(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=Ut[t.readBits(2)],l=512*(t.readBits(3)+1);t.readBits(1)&&t.skipBits(36);const u=t.readBits(3)+1,d=t.readBits(3)+1,h=[];for(let k=0;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}}},Xt=e=>G(e)+G(44646&e),$t=["avc","hevc","vp9","av1","vp8","prores"],Gt=["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"],Qt=["aac","opus","mp3","vorbis","flac","ac3","eac3","dts",...Gt],Yt=[{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}],Jt=[{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}],Zt=".01.01.01.01.00",ei=".0.110.01.01.01.0",ti=["ap4x","ap4h","apch","apcn","apcs","apco"],ii=["dtsc","dtsh","dtsl","dtse"],ri=e=>{const{codec:t,codecDescription:i,colorSpace:r,avcCodecInfo:a,hevcCodecInfo:s,vp9CodecInfo:n,av1CodecInfo:o,proresFormat:c}=e;if("avc"===t){if(l(null!==e.avcType),a){const t=new Uint8Array([a.avcProfileIndication,a.profileCompatibility,a.avcLevelIndication]);return`avc${e.avcType}.${_(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}.${_(i.subarray(1,4))}`}if("hevc"===t){let e,t,r,a,n,o;if(s)e=s.generalProfileSpace,t=s.generalProfileIdc,r=R(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=g(i),c=s.getUint8(1);e=c>>6&3,t=31&c,r=R(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=d(Jt).level;for(const e of Jt)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(Zt)&&(t=t.slice(0,-15)),t}if("av1"===t){if(!o){const t=e.width*e.height;let i=d(Jt).level;for(const e of Jt)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?b[r.primaries]:1,u=r?.transfer?T[r.transfer]:1,h=r?.matrix?v[r.matrix]:1,f=r?.fullRange?1:0;let m=`av01.${t}.${i}${a}.${s}`;return m+=`.${n}.${c.toString().padStart(3,"0")}`,m+=`.${l.toString().padStart(2,"0")}`,m+=`.${u.toString().padStart(2,"0")}`,m+=`.${h.toString().padStart(2,"0")}`,m+=`.${f}`,m.endsWith(ei)&&(m=m.slice(0,-17)),m}if("prores"===t)return c??"apch";throw null!==t&&z(t),new TypeError(`Unhandled codec '${t}'.`)},ai=e=>{switch(e.codec){case"avc":{let t=e.avcCodecInfo?.sequenceParameterSets[0];if(!t&&e.codecDescription&&(t=Je(e.codecDescription)?.sequenceParameterSets[0]),t){const e=et(t);if(e)return{primaries:w[e.colourPrimaries],transfer:S[e.transferCharacteristics],matrix:P[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case"hevc":{let t=e.hevcCodecInfo?.arrays.find(e=>e.nalUnitType===Ue.SPS_NUT)?.nalUnits[0];if(!t&&e.codecDescription&&(t=(e=>{try{const t=g(e);let i=0;const r=t.getUint8(i++),a=t.getUint8(i++),s=a>>6&3,n=a>>5&1,o=31&a,c=t.getUint32(i,!1);i+=4;const l=e.subarray(i,i+6);i+=6;const u=t.getUint8(i++),d=(15&t.getUint8(i++))<<8|t.getUint8(i++),h=3&t.getUint8(i++),f=3&t.getUint8(i++),m=7&t.getUint8(i++),p=7&t.getUint8(i++),k=t.getUint16(i,!1);i+=2;const y=t.getUint8(i++),b=y>>6&3,w=y>>3&7,T=y>>2&1,S=3&y,v=t.getUint8(i++),P=[];for(let g=0;g>7&1,s=63&r,n=t.getUint16(i,!1);i+=2;const o=[];for(let c=0;ce.nalUnitType===Ue.SPS_NUT)?.nalUnits[0]),t){const e=st(t);if(e)return{primaries:w[e.colourPrimaries],transfer:S[e.transferCharacteristics],matrix:P[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case"vp8":break;case"vp9":if(e.vp9CodecInfo)return{primaries:w[e.vp9CodecInfo.colourPrimaries],transfer:S[e.vp9CodecInfo.transferCharacteristics],matrix:P[e.vp9CodecInfo.matrixCoefficients],fullRange:!!e.vp9CodecInfo.videoFullRangeFlag};break;case"av1":if(e.av1CodecInfo)return{primaries:w[e.av1CodecInfo.colourPrimaries],transfer:S[e.av1CodecInfo.transferCharacteristics],matrix:P[e.av1CodecInfo.matrixCoefficients],fullRange:!!e.av1CodecInfo.videoFullRangeFlag};break;case"prores":if(e.proresCodecInfo)return{primaries:w[e.proresCodecInfo.colourPrimaries],transfer:S[e.proresCodecInfo.transferCharacteristics],matrix:P[e.proresCodecInfo.matrixCoefficients],fullRange:e.proresCodecInfo.fullRange}}return{primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0}},si=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=Ae(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&&Gt.includes(t))return t;throw new TypeError(`Unhandled codec '${t}'.`)},ni=48e3,oi=/^pcm-([usf])(\d+)(be)?$/,ci=e=>{if(l(Gt.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=oi.exec(e);let i;l(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}},li=e=>e.startsWith("avc1")||e.startsWith("avc3")?"avc":e.startsWith("hev1")||e.startsWith("hvc1")?"hevc":"vp8"===e?"vp8":e.startsWith("vp09")?"vp9":e.startsWith("av01")?"av1":ti.includes(e)?"prores":"mp3"===e||"mp4a.69"===e||"mp4a.6B"===e||"mp4a.6b"===e||"mp4a.40.34"===e?"mp3":e.startsWith("mp4a.40.")||"mp4a.67"===e?"aac":"opus"===e?"opus":"vorbis"===e?"vorbis":"flac"===e?"flac":"ac-3"===e||"ac3"===e?"ac3":"ec-3"===e||"eac3"===e?"eac3":ii.includes(e)?"dts":"ulaw"===e?"ulaw":"alaw"===e?"alaw":oi.test(e)?e:"webvtt"===e?"webvtt":null,ui=[44100,48e3,32e3],di=[-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],hi=1483304551,fi=1231971951,mi=(e,t)=>3===e?3===t?21:36:3===t?13:21,pi=(e,t)=>{const i=e>>>24,r=e>>>16&255,a=e>>>8&255,s=255&e;if(255!==i&&255!==r&&255!==a&&255!==s)return{header:null,bytesAdvanced:4};if(255!==i)return{header:null,bytesAdvanced:1};if(224!==(224&r))return{header:null,bytesAdvanced:1};let n=0,o=0;16&r?n=8&r?0:1:(n=1,o=1);const c=r>>3&3,l=r>>1&3,u=(a>>2&3)%3,d=s>>6&3,h=s>>4&3,f=s>>3&1,m=s>>2&1,p=3&s,g=di[16*n*4+16*l+(a>>4&15)];if(-1===g)return{header:null,bytesAdvanced:1};const k=1e3*g,y=ui[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 ki,yi;(yi=ki||(ki={}))[yi.FrameCount=1]="FrameCount",yi[yi.FileSize=2]="FileSize",yi[yi.Toc=4]="Toc";const bi=e=>3===e?1:2;class wi{constructor(e){this.input=e}dispose(){}}const Ti=new Uint8Array(0);class Si{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===Ti&&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===Ti}get microsecondTimestamp(){return Math.trunc(J*this.timestamp)}get microsecondDuration(){return Math.trunc(J*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 Si(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 Si(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 vi=e=>{const t=g(e);let i=0;const r=t.getUint8(i);i+=1,i+=3;const a=_(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=Bo(e);const i=Oo(e,4);let r=8;1===t&&(t=Fo(e),r=16);const a=t-r;return a<0?null:{name:i,totalSize:t,headerSize:r,contentSize:a}},xi=e=>_o(e)/65536,Ci=e=>_o(e)/1073741824,Bi=e=>{let t=0;for(let i=0;i<4;i++){t<<=7;const i=So(e);if(t|=127&i,0===(128&i))break}return t},Ei=e=>{let t=Po(e);return e.skip(2),t=Math.min(t,e.remainingLength),k.decode(To(e,t))},_i=e=>{const t=Ii(e);if(!t||"data"!==t.name)return null;if(e.remainingLength<8)return null;const i=Bo(e);e.skip(4);const r=To(e,t.contentSize-8);switch(i){case 1:return k.decode(r);case 2:return new TextDecoder("utf-16be").decode(r);case 13:return new Ce(r,"image/jpeg");case 14:return new Ce(r,"image/png");case 27:return new Ce(r,"image/bmp");default:return r}},Ri=16,Fi=new Uint32Array(256),Ai=new Uint32Array(256),Di=new Uint32Array(256),Mi=new Uint32Array(256),Ni=new Uint32Array(256),Oi=new Uint32Array(256),Li=new Uint32Array(10);let zi=!1;class Ui{constructor(){this.roundkey=new Uint32Array(44),this.iv=new Uint32Array(Ri/Uint32Array.BYTES_PER_ELEMENT),this.in=new Uint8Array(Ri),this.out=new Uint8Array(Ri),this.inView=new DataView(this.in.buffer),this.outView=new DataView(this.out.buffer)}init({key:e,iv:t}){l(16===e.byteLength),l(16===t.byteLength),zi||(()=>{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);Fi[s]=t<<24|t<<16|t<<8|t,Oi[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);Ai[s]=a,Di[s]=a>>>8|a<<24,Mi[s]=a>>>16|a<<16,Ni[s]=a>>>24|a<<8}let a=1;for(let s=0;s<10;s++)Li[s]=a<<24,a=a<<1^(128&a?283:0);zi=!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&Fi[e>>>16&255]^16711680&Fi[e>>>8&255]^65280&Fi[e>>>0&255]^255&Fi[e>>>24&255]^Li[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]]^Di[255&Fi[t>>>16&255]]^Mi[255&Fi[t>>>8&255]]^Ni[255&Fi[t>>>0&255]]}}decrypt(){let e=this.inView.getUint32(0,!1)^this.roundkey[0],t=this.inView.getUint32(4,!1)^this.roundkey[1],i=this.inView.getUint32(8,!1)^this.roundkey[2],r=this.inView.getUint32(12,!1)^this.roundkey[3];const a=this.inView.getUint32(0,!1),s=this.inView.getUint32(4,!1),n=this.inView.getUint32(8,!1),o=this.inView.getUint32(12,!1);let c,l,u,d;for(let g=1;g<10;g++){const a=4*g;c=Ai[e>>>24]^Di[r>>>16&255]^Mi[i>>>8&255]^Ni[255&t]^this.roundkey[a],l=Ai[t>>>24]^Di[e>>>16&255]^Mi[r>>>8&255]^Ni[255&i]^this.roundkey[a+1],u=Ai[i>>>24]^Di[t>>>16&255]^Mi[e>>>8&255]^Ni[255&r]^this.roundkey[a+2],d=Ai[r>>>24]^Di[i>>>16&255]^Mi[t>>>8&255]^Ni[255&e]^this.roundkey[a+3],e=c,t=l,i=u,r=d}const h=4278190080&Oi[e>>>24&255]^16711680&Oi[r>>>16&255]^65280&Oi[i>>>8&255]^255&Oi[t>>>0&255]^this.roundkey[40],f=4278190080&Oi[t>>>24&255]^16711680&Oi[e>>>16&255]^65280&Oi[r>>>8&255]^255&Oi[i>>>0&255]^this.roundkey[41],m=4278190080&Oi[i>>>24&255]^16711680&Oi[t>>>16&255]^65280&Oi[e>>>8&255]^255&Oi[r>>>0&255]^this.roundkey[42],p=4278190080&Oi[r>>>24&255]^16711680&Oi[i>>>16&255]^65280&Oi[t>>>8&255]^255&Oi[e>>>0&255]^this.roundkey[43];this.outView.setUint32(0,h^this.iv[0],!1),this.outView.setUint32(4,f^this.iv[1],!1),this.outView.setUint32(8,m^this.iv[2],!1),this.outView.setUint32(12,p^this.iv[3],!1),this.iv[0]=a,this.iv[1]=s,this.iv[2]=n,this.iv[3]=o}}class qi extends wi{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(de(r)&&(r=await r),!r)break;const a=e,s=Ii(r);if(!s)break;if("ftyp"===s.name||"styp"===s.name){const e=Oo(r,4);this.isQuickTime="qt "===e}else{if("moov"===s.name){let e=this.reader.requestSlice(r.filePos,s.contentSize);if(de(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){l(null!==this.reader.fileSize);let e=this.reader.requestSlice(this.reader.fileSize-4,4);de(e)&&(e=await e),l(e);const t=Bo(e),i=this.reader.fileSize-t;if(i>=0&&i<=this.reader.fileSize-16){let e=this.reader.requestSliceRange(i,8,16);if(de(e)&&(e=await e),e){const t=Ii(e);if(t&&"mfra"===t.name){let i=this.reader.requestSlice(e.filePos,t.contentSize);de(i)&&(i=await i),i&&this.readContiguousBoxes(i)}}}}})())}async copyMetadataFromInitInput(e){const t=await e._getDemuxer();if(t.constructor!==qi)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(l(e.info),"video"===e.info.type&&-1!==e.info.width){const t=e;e.trackBacking=new Hi(t),this.tracks.push(e)}else if("audio"===e.info.type&&-1!==e.info.numberOfChannels){const t=e;e.trackBacking=new Vi(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;l(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&&Gt.includes(e.info.codec)&&0===t.sampleCompositionTimeOffsets.length){l("audio"===e.info?.type);const i=ci(e.info.codec),r=[],a=[];for(let s=0;se.startIndex),u=t.sampleTimingEntries[l],h=A(t.sampleTimingEntries,c,e=>e.startIndex),f=t.sampleTimingEntries[h],m=u.startDecodeTimestamp+(o-u.startIndex)*u.delta,p=f.startDecodeTimestamp+(c-f.startIndex)*f.delta-m,g=d(r);g&&g.delta===p?g.count++:r.push({startIndex:n.startChunkIndex+s,startDecodeTimestamp:m,count:1,delta:p});const k=n.samplesPerChunk*i.sampleSize*e.info.numberOfChannels;a.push(k)}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)Gi(s,i.timestamp);else{const e=A(t,a.moofOffset-1,e=>e.moofOffset);if(-1!==e){const i=t[e];Gi(s,i.endTimestamp)}}s.startTimestampIsFinal=!0}const i=A(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 Zi(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;Y(t.languageCode)||(t.languageCode=V)}}break;case"hdlr":{const t=this.currentTrack;if(!t)break;e.skip(8);const i=Oo(e,4);"vide"===i?t.info={type:"video",width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:{...x},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=j,this.readContiguousBoxes(e.slice($,X.contentSize))}break;case"stsd":{const t=this.currentTrack;if(!t)break;if(null===t.info||t.sampleTable)break;const i=So(e);e.skip(3);const r=Bo(e);for(let a=0;a0&&(1===n?(e.skip(4),c=8*Bo(e),e.skip(8)):2===n&&(e.skip(4),l=No(e),o=Bo(e),e.skip(4),c=Bo(e),u=Bo(e),e.skip(8))),t.info.numberOfChannels=o,t.info.sampleRate=l,t.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,r+a.totalSize-e.filePos));const d="enca"===s?t.frmaCodecString:s;if(t.frmaCodecString=null,"mp4a"===d);else if("opus"===d)t.info.codec="opus",t.info.sampleRate=ni;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(ii.includes(d))t.info.codec="dts",t.info.dtsFormat=d;else if("twos"===d)8===c?t.info.codec="pcm-s8":16===c?t.info.codec=t.info.pcmLittleEndian?"pcm-s16":"pcm-s16be":(xe._warn(`Unsupported sample size ${c} for codec 'twos'.`),t.info.codec=null);else if("sowt"===d)8===c?t.info.codec="pcm-s8":16===c?t.info.codec="pcm-s16":(xe._warn(`Unsupported sample size ${c} for codec 'sowt'.`),t.info.codec=null);else if("raw "===d)t.info.codec="pcm-u8";else if("in24"===d)t.info.codec=t.info.pcmLittleEndian?"pcm-s24":"pcm-s24be";else if("in32"===d)t.info.codec=t.info.pcmLittleEndian?"pcm-s32":"pcm-s32be";else if("fl32"===d)t.info.codec=t.info.pcmLittleEndian?"pcm-f32":"pcm-f32be";else if("fl64"===d)t.info.codec=t.info.pcmLittleEndian?"pcm-f64":"pcm-f64be";else if("ipcm"===d){const e=t.info.pcmSampleSize;t.info.pcmLittleEndian?16===e?t.info.codec="pcm-s16":24===e?t.info.codec="pcm-s24":32===e?t.info.codec="pcm-s32":(xe._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":(xe._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":(xe._warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null):32===e?t.info.codec="pcm-f32be":64===e?t.info.codec="pcm-f64be":(xe._warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null)}else if("lpcm"===d&&null!==u){const e=c+7>>3,i=Boolean(1&u),r=Boolean(2&u),a=4&u?-1:0;c>0&&c<=64&&(i?32===c&&(t.info.codec=r?"pcm-f32be":"pcm-f32"):a&1<0?(t.encryptionInfo.defaultCryptByteBlock=r>>4,t.encryptionInfo.defaultSkipByteBlock=15&r):(t.encryptionInfo.defaultCryptByteBlock=0,t.encryptionInfo.defaultSkipByteBlock=0),t.encryptionInfo.defaultIsProtected=0!==So(e),t.encryptionInfo.defaultPerSampleIvSize=So(e),t.encryptionInfo.defaultKid=_(To(e,16)),t.encryptionInfo.defaultIsProtected&&0===t.encryptionInfo.defaultPerSampleIvSize){const i=So(e),r=new Uint8Array(16);r.set(To(e,i),0),t.encryptionInfo.defaultConstantIv=r}}break;case"avcC":{const t=this.currentTrack;if(!t)break;if(l(t.info),0===X.contentSize)break;t.info.codecDescription=To(e,X.contentSize)}break;case"hvcC":{const t=this.currentTrack;if(!t)break;if(l(t.info),0===X.contentSize)break;t.info.codecDescription=To(e,X.contentSize)}break;case"vpcC":{const t=this.currentTrack;if(!t)break;l("video"===t.info?.type),e.skip(4);const i=So(e),r=So(e),a=So(e),s=a>>4,n=a>>1&7,o=1&a,c=So(e),u=So(e),d=So(e);t.info.vp9CodecInfo={profile:i,level:r,bitDepth:s,chromaSubsampling:n,videoFullRangeFlag:o,colourPrimaries:c,transferCharacteristics:u,matrixCoefficients:d}}break;case"av1C":{const t=this.currentTrack;if(!t)break;l("video"===t.info?.type),e.skip(1);const i=So(e),r=i>>5,a=31&i,s=So(e),n=s>>7,o=s>>6&1,c=s>>4&1,u=s>>3&1,d=s>>2&1,h=3&s,f=2===r&&o?s>>5&1?12:10:o?10:8;e.skip(1);const m=To(e,X.contentSize-4),p=wt(m);t.info.av1CodecInfo={profile:r,level:a,tier:n,bitDepth:f,monochrome:c,chromaSubsamplingX:u,chromaSubsamplingY:d,chromaSamplePosition:h,videoFullRangeFlag:p?.videoFullRangeFlag??0,colourPrimaries:p?.colourPrimaries??2,transferCharacteristics:p?.transferCharacteristics??2,matrixCoefficients:p?.matrixCoefficients??2}}break;case"colr":{const t=this.currentTrack;if(!t)break;l("video"===t.info?.type);const i=Oo(e,4);if("nclx"!==i&&"nclc"!==i)break;const r=Po(e),a=Po(e),s=Po(e);let n;"nclx"===i&&(n=Boolean(128&So(e))),t.info.colorSpace={primaries:w[r],transfer:S[a],matrix:P[s],fullRange:n}}break;case"pasp":{const t=this.currentTrack;if(!t)break;l("video"===t.info?.type);const i=Bo(e),r=Bo(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);l(3===So(e)),Bi(e),e.skip(2);const i=So(e),r=0!==(64&i),a=0!==(32&i);if(0!==(128&i)&&e.skip(2),r){const t=So(e);e.skip(t)}a&&e.skip(2);l(4===So(e));const s=Bi(e),n=e.filePos,o=So(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":xe._warn(`Unsupported audio codec (objectTypeIndication ${o}) - discarding track.`),e.skip(12),s>e.filePos-n){l(5===So(e));const i=Bi(e);if(t.info.codecDescription=To(e,i),"aac"===t.info.codec){const e=Ae(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;l("audio"===t.info?.type),t.info.pcmLittleEndian=!!(255&Po(e))}break;case"pcmC":{const t=this.currentTrack;if(!t)break;l("audio"===t.info?.type),e.skip(4);const i=So(e);t.info.pcmLittleEndian=Boolean(1&i),t.info.pcmSampleSize=So(e)}break;case"dOps":{const t=this.currentTrack;if(!t)break;l("audio"===t.info?.type),e.skip(1);const i=So(e),r=Po(e),a=Bo(e),s=xo(e),n=So(e);let o;o=0!==n?To(e,2+i):new Uint8Array(0);const c=new Uint8Array(19+o.byteLength),u=new DataView(c.buffer);u.setUint32(0,1332770163,!1),u.setUint32(4,1214603620,!1),u.setUint8(8,1),u.setUint8(9,i),u.setUint16(10,r,!0),u.setUint32(12,a,!0),u.setInt16(16,s,!0),u.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;l("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=To(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;l("audio"===t.info?.type);const i=To(e,3),r=new _e(i),a=r.readBits(2);r.skipBits(8);const s=r.readBits(3),n=r.readBits(1);a<3&&(t.info.sampleRate=Ne[a]),t.info.numberOfChannels=Bt[s]+n}break;case"dec3":{const t=this.currentTrack;if(!t)break;l("audio"===t.info?.type);const i=(e=>{if(e.length<2)return null;const t=new _e(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}})(To(e,X.contentSize));if(!i){xe._warn("Invalid dec3 box contents, ignoring.");break}const r=At(i);null!==r&&(t.info.sampleRate=r),t.info.numberOfChannels=Dt(i)}break;case"ddts":{const t=this.currentTrack;if(!t)break;l("audio"===t.info?.type);const i=(e=>{if(e.length<20)return null;const t=g(e),i=t.getUint32(0);if(0===i)return null;const r=new _e(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=Xt(o):ne.id===i);if(!r)break;const a=Bo(e),s=(12&a)>>2,n=3&a,o=[So,Po,Io,Bo],c=o[(48&a)>>4],l=o[s],u=o[n],d=Bo(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 a=0;ae.id===u);if(!d)break;const h=this.fragmentTrackDefaults.find(e=>e.trackId===u);this.currentTrack=d,d.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?d.currentFragmentState.baseDataOffset=Fo(e):c&&(d.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),r&&(d.currentFragmentState.sampleDescriptionIndex=Bo(e)),a&&(d.currentFragmentState.defaultSampleDuration=Bo(e)),s&&(d.currentFragmentState.defaultSampleSize=Bo(e)),n&&(d.currentFragmentState.defaultSampleFlags=Bo(e)),o&&(d.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{const t=this.currentTrack;if(!t)break;l(t.currentFragmentState);const i=So(e);e.skip(3);const r=0===i?Bo(e):Fo(e);t.currentFragmentState.startTimestamp=r}break;case"trun":{const t=this.currentTrack;if(!t)break;l(this.currentFragment),l(t.currentFragmentState);const i=So(e),r=Io(e),a=Boolean(1&r),s=Boolean(4&r),n=Boolean(256&r),o=Boolean(512&r),c=Boolean(1024&r),u=Boolean(2048&r),d=Bo(e);let h=null;a&&(h=_o(e));let f,m=null;s&&(m=Bo(e)),this.currentFragment.trackData.has(t.id)?(f=this.currentFragment.trackData.get(t.id),null!==h&&(f.currentOffset=t.currentFragmentState.baseDataOffset+h)):(f={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,f));for(let p=0;p0&&(a=To(e,r));const s=Ji(t);s.defaultSampleInfoSize=i,s.sampleSizes=a,s.sampleCount=r}break;case"saio":{const t=this.currentTrack;if(!t||!t.encryptionInfo)break;const i=So(e);if(1&Io(e)){const i=Oo(e,4),r=Bo(e);if(i!==t.encryptionInfo.scheme||0!==r)break}const r=Bo(e);if(0===r)break;r>1&&xe._warn("Multiple saio entries are not supported; using the first offset only.");let a=0===i?Bo(e):Number(Fo(e));this.currentFragment&&(a+=this.currentFragment.moofOffset);Ji(t).offset=a}break;case"senc":{const t=this.currentTrack;if(!t||!t.encryptionInfo)break;l(this.currentFragment);const i=this.currentFragment.trackData.get(t.id);if(!i)break;e.skip(1);const r=Io(e),a=Boolean(2&r),s=Bo(e),n=t.encryptionInfo.defaultPerSampleIvSize;l(null!==n);for(let o=0;o0?r.set(To(e,n),0):r.set(t.encryptionInfo.defaultConstantIv,0);let s=null;if(a){const t=Po(e);s=[];for(let i=0;i0&&((L=this.metadataTags).trackNumber??(L.trackNumber=t)),i&&Number.isInteger(i)&&i>0&&((z=this.metadataTags).tracksTotal??(z.tracksTotal=i))}break;case"trkn":if(a instanceof Uint8Array&&a.length>=6){const e=g(a),t=e.getUint16(2,!1),i=e.getUint16(4,!1);t>0&&((U=this.metadataTags).trackNumber??(U.trackNumber=t)),i>0&&((q=this.metadataTags).tracksTotal??(q.tracksTotal=i))}break;case"disc":case"disk":if(a instanceof Uint8Array&&a.length>=6){const e=g(a),t=e.getUint16(2,!1),i=e.getUint16(4,!1);t>0&&((W=this.metadataTags).discNumber??(W.discNumber=t)),i>0&&((H=this.metadataTags).discsTotal??(H.discsTotal=i))}}}}}return e.filePos=G,!0}}class Wi{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;l(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 j(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,t){const i=this.mapTimestampIntoTimescale(e),r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=ji(r,i),s=await this.fetchPacketForSampleIndex(a,t);return Yi(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=A(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=L(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 l(-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=Xi(i,e);if(!r)return null;let a;if(t.metadataOnly)a=Ti;else{let t=this.internalTrack.demuxer.reader.requestSlice(r.sampleOffset,r.sampleSize);if(de(t)&&(t=await t),!t)return null;if(a=To(t,r.sampleSize),this.internalTrack.encryptionInfo){let t=null;if(this.internalTrack.encryptionAuxInfo){const i=await Zi(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);ee.timestamp),d=-1!==u?this.internalTrack.fragmentLookupTable[u]:null,h=A(this.internalTrack.fragmentPositionCache,i,e=>e.startTimestamp),f=-1!==h?this.internalTrack.fragmentPositionCache[h]:null,m=Math.max(d?.moofOffset??0,f?.moofOffset??0)||null;let p;for(e?null===m||e.moofOffset>=m?(p=e.moofOffset+e.moofSize,n=e):p=m:p=m??0;;){if(n){const e=n.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>r)break}let e=s.reader.requestSliceRange(p,8,16);if(de(e)&&(e=await e),!e)break;const i=p,l=Ii(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)}p=i+l.totalSize}if(d&&(!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&&Tt(e.data)}}else{const e=await this.getFirstPacket({}),t=e&&wt(e.data);t&&(this.internalTrack.info.av1CodecInfo=t)}else{const e=await this.getFirstPacket({}),t=e&&yt(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&&nt(e.data)}else{const e=await this.getFirstPacket({});this.internalTrack.info.avcCodecInfo=e&&Qe(e.data)}if(!I(this.internalTrack.info.colorSpace)){const a=ai(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:ri(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 Vi extends Wi{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&&Vt(e.data)}return{codec:si(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}})()):null}}const ji=(e,t)=>{if(e.presentationTimestamps){const i=A(e.presentationTimestamps,t,e=>e.presentationTimestamp);return-1===i?-1:e.presentationTimestamps[i].sampleIndex}{const i=A(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)}},Ki=(e,t)=>{if(!e.keySampleIndices)return ji(e,t);if(e.presentationTimestamps){const i=A(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!==F(e.keySampleIndices,i,e=>e))return i}return-1}{const i=ji(e,t),r=A(e.keySampleIndices,i,e=>e);return e.keySampleIndices[r]??-1}},Xi=(e,t)=>{const i=A(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=A(e.sampleCompositionTimeOffsets,t,e=>e.startIndex),n=e.sampleCompositionTimeOffsets[s];n&&t-n.startIndexe.startSampleIndex),u=e.sampleToChunk[c];l(u);const d=u.startChunkIndex+Math.floor((t-u.startSampleIndex)/u.samplesPerChunk),h=e.chunkOffsets[d],f=u.startSampleIndex+(d-u.startChunkIndex)*u.samplesPerChunk;let m=0,p=h;if(1===e.sampleSizes.length)p+=o*(t-f),m+=o*u.samplesPerChunk;else for(let l=f;le)}},$i=(e,t)=>{if(!e.keySampleIndices)return t+1;const i=A(e.keySampleIndices,t,e=>e);return e.keySampleIndices[i+1]??-1},Gi=(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},Qi=e=>{const[t,i]=e,r=Math.atan2(i,t);return Number.isFinite(r)?r*(180/Math.PI):0},Yi=e=>0===e.sampleSizes.length,Ji=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})},Zi=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{l(i.sampleSizes);for(let e=0;e0?i.defaultSampleInfoSize:i.sampleSizes[o],r=new Uint8Array(16);s>0?r.set(To(a,s),0):r.set(t.defaultConstantIv,0);let c=null;if(e>s){const e=Po(a);c=[];for(let t=0;te.defaultConstantIv?{iv:e.defaultConstantIv,subsamples:null}:null,tr=async(e,t,i,r)=>{l(e.encryptionInfo);const a=e.encryptionInfo;l(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{l(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);l(null!==t.defaultCryptByteBlock&&null!==t.defaultSkipByteBlock);const o=ar(i.subsamples,t.defaultCryptByteBlock,t.defaultSkipByteBlock);let c=0;for(const l of o)for(const e of l.perSubsample)c+=e.length;const u=new Uint8Array(c);let d=0;for(const l of o)for(const e of l.perSubsample)u.set(r.subarray(e.offset,e.offset+e.length),d),d+=e.length;const h=await n(u),f=new Uint8Array(r);let m=0;for(const l of o)for(const e of l.perSubsample)f.set(h.subarray(m,m+e.length),e.offset),m+=e.length;return f},rr=(e,t,i,r)=>{const a=new Ui;a.init({key:e,iv:i.iv});const s=t.defaultCryptByteBlock,n=t.defaultSkipByteBlock;if(l(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 sr,nr;(nr=sr||(sr={}))[nr.EBML=440786851]="EBML",nr[nr.EBMLVersion=17030]="EBMLVersion",nr[nr.EBMLReadVersion=17143]="EBMLReadVersion",nr[nr.EBMLMaxIDLength=17138]="EBMLMaxIDLength",nr[nr.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",nr[nr.DocType=17026]="DocType",nr[nr.DocTypeVersion=17031]="DocTypeVersion",nr[nr.DocTypeReadVersion=17029]="DocTypeReadVersion",nr[nr.Void=236]="Void",nr[nr.Segment=408125543]="Segment",nr[nr.SeekHead=290298740]="SeekHead",nr[nr.Seek=19899]="Seek",nr[nr.SeekID=21419]="SeekID",nr[nr.SeekPosition=21420]="SeekPosition",nr[nr.Duration=17545]="Duration",nr[nr.Info=357149030]="Info",nr[nr.TimestampScale=2807729]="TimestampScale",nr[nr.MuxingApp=19840]="MuxingApp",nr[nr.WritingApp=22337]="WritingApp",nr[nr.Tracks=374648427]="Tracks",nr[nr.TrackEntry=174]="TrackEntry",nr[nr.TrackNumber=215]="TrackNumber",nr[nr.TrackUID=29637]="TrackUID",nr[nr.TrackType=131]="TrackType",nr[nr.FlagEnabled=185]="FlagEnabled",nr[nr.FlagDefault=136]="FlagDefault",nr[nr.FlagForced=21930]="FlagForced",nr[nr.FlagOriginal=21934]="FlagOriginal",nr[nr.FlagHearingImpaired=21931]="FlagHearingImpaired",nr[nr.FlagVisualImpaired=21932]="FlagVisualImpaired",nr[nr.FlagCommentary=21935]="FlagCommentary",nr[nr.FlagLacing=156]="FlagLacing",nr[nr.Name=21358]="Name",nr[nr.Language=2274716]="Language",nr[nr.LanguageBCP47=2274717]="LanguageBCP47",nr[nr.CodecID=134]="CodecID",nr[nr.CodecPrivate=25506]="CodecPrivate",nr[nr.CodecDelay=22186]="CodecDelay",nr[nr.SeekPreRoll=22203]="SeekPreRoll",nr[nr.DefaultDuration=2352003]="DefaultDuration",nr[nr.Video=224]="Video",nr[nr.PixelWidth=176]="PixelWidth",nr[nr.PixelHeight=186]="PixelHeight",nr[nr.DisplayWidth=21680]="DisplayWidth",nr[nr.DisplayHeight=21690]="DisplayHeight",nr[nr.DisplayUnit=21682]="DisplayUnit",nr[nr.AlphaMode=21440]="AlphaMode",nr[nr.Audio=225]="Audio",nr[nr.SamplingFrequency=181]="SamplingFrequency",nr[nr.Channels=159]="Channels",nr[nr.BitDepth=25188]="BitDepth",nr[nr.SimpleBlock=163]="SimpleBlock",nr[nr.BlockGroup=160]="BlockGroup",nr[nr.Block=161]="Block",nr[nr.BlockAdditions=30113]="BlockAdditions",nr[nr.BlockMore=166]="BlockMore",nr[nr.BlockAdditional=165]="BlockAdditional",nr[nr.BlockAddID=238]="BlockAddID",nr[nr.BlockDuration=155]="BlockDuration",nr[nr.ReferenceBlock=251]="ReferenceBlock",nr[nr.Cluster=524531317]="Cluster",nr[nr.Timestamp=231]="Timestamp",nr[nr.Cues=475249515]="Cues",nr[nr.CuePoint=187]="CuePoint",nr[nr.CueTime=179]="CueTime",nr[nr.CueTrackPositions=183]="CueTrackPositions",nr[nr.CueTrack=247]="CueTrack",nr[nr.CueClusterPosition=241]="CueClusterPosition",nr[nr.Colour=21936]="Colour",nr[nr.MatrixCoefficients=21937]="MatrixCoefficients",nr[nr.TransferCharacteristics=21946]="TransferCharacteristics",nr[nr.Primaries=21947]="Primaries",nr[nr.Range=21945]="Range",nr[nr.Projection=30320]="Projection",nr[nr.ProjectionType=30321]="ProjectionType",nr[nr.ProjectionPoseRoll=30325]="ProjectionPoseRoll",nr[nr.Attachments=423732329]="Attachments",nr[nr.AttachedFile=24999]="AttachedFile",nr[nr.FileDescription=18046]="FileDescription",nr[nr.FileName=18030]="FileName",nr[nr.FileMediaType=18016]="FileMediaType",nr[nr.FileData=18012]="FileData",nr[nr.FileUID=18094]="FileUID",nr[nr.Chapters=272869232]="Chapters",nr[nr.Tags=307544935]="Tags",nr[nr.Tag=29555]="Tag",nr[nr.Targets=25536]="Targets",nr[nr.TargetTypeValue=26826]="TargetTypeValue",nr[nr.TargetType=25546]="TargetType",nr[nr.TagTrackUID=25541]="TagTrackUID",nr[nr.TagEditionUID=25545]="TagEditionUID",nr[nr.TagChapterUID=25540]="TagChapterUID",nr[nr.TagAttachmentUID=25542]="TagAttachmentUID",nr[nr.SimpleTag=26568]="SimpleTag",nr[nr.TagName=17827]="TagName",nr[nr.TagLanguage=17530]="TagLanguage",nr[nr.TagString=17543]="TagString",nr[nr.TagBinary=17541]="TagBinary",nr[nr.ContentEncodings=28032]="ContentEncodings",nr[nr.ContentEncoding=25152]="ContentEncoding",nr[nr.ContentEncodingOrder=20529]="ContentEncodingOrder",nr[nr.ContentEncodingScope=20530]="ContentEncodingScope",nr[nr.ContentCompression=20532]="ContentCompression",nr[nr.ContentCompAlgo=16980]="ContentCompAlgo",nr[nr.ContentCompSettings=16981]="ContentCompSettings",nr[nr.ContentEncryption=20533]="ContentEncryption";const or=[sr.EBML,sr.Segment],cr=[sr.SeekHead,sr.Info,sr.Cluster,sr.Tracks,sr.Cues,sr.Attachments,sr.Chapters,sr.Tags],lr=[...or,...cr],ur=16,dr=e=>{if(e.remainingLength<1)return null;const t=So(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=So(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=dr(e);if(null===t)return null;if(e.remainingLength{if(e.remainingLength<1)return null;if(255===So(e))return;e.skip(-1);const t=hr(e);return null===t?null:72057594037927940!==t?t:void 0},gr=e=>{l(e.remainingLength>=2);const t=mr(e);if(null===t)return null;const i=pr(e);return null===i?null:{id:t,size:i}},kr=(e,t)=>{const i=To(e,t);let r=0;for(;r{const i=To(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?Mo(e):No(e)},wr=async(e,t,i,r)=>{const a=new Set(i);let s=t;for(;null===r||ss?r:s,found:!1}},Tr=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,ur);if(de(t)&&(t=await t),!t)break;const i=gr(t);if(!i)break;const r=i.id;let a=i.size;const s=t.filePos;if(r===sr.EBML){Nr(a);let e=this.reader.requestSlice(s,a);if(de(e)&&(e=await e),!e)break;this.readContiguousElements(e)}else if(r===sr.Segment){if(await this.readSegment(s,a),void 0===a)break;if(null===this.reader.fileSize)break}else if(r===sr.Cluster){if(null===this.reader.fileSize)break;if(void 0===a){a=(await wr(this.reader,s,lr,this.reader.fileSize)).pos-s}const e=d(this.segments);e&&(e.elementEndPos=s+a)}Nr(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=Hr[o].flag;this.currentSegment[e]=!0,Nr(s);let t=this.reader.requestSlice(n,s);de(t)&&(t=await t),t&&this.readContiguousElements(t)}else if(a===sr.Tags||a===sr.Attachments){a===sr.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,Nr(s);let e=this.reader.requestSlice(n,s);de(e)&&(e=await e),e&&this.readContiguousElements(e)}else if(a===sr.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=Hr.find(e=>e.id===n.id);if(!t)continue;if(this.currentSegment[t.flag])continue;let i=this.reader.requestSliceRange(e+n.segmentPosition,2,ur);if(de(i)&&(i=await i),!i)continue;const r=gr(i);if(!r)continue;const{id:a,size:s}=r;if(a!==t.id)continue;Nr(s),this.currentSegment[t.flag]=!0;let o=this.reader.requestSlice(i.filePos,s);de(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,ur);de(i)&&(i=await i),l(i);const r=e,a=gr(i);l(a);l(a.id===sr.Cluster);let s=a.size;const n=i.filePos;if(void 0===s){s=(await wr(this.reader,n,lr,t.elementEndPos)).pos-n}let o=this.reader.requestSlice(n,s);de(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,lr);c.elementEndPos=e}for(const[,u]of c.trackData){const e=u.track;l(u.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=u.blocks[u.presentationTimestamps[0].blockIndex],a=u.blocks[d(u.presentationTimestamps).blockIndex];u.startTimestamp=i.timestamp,u.endTimestamp=a.timestamp+a.duration;const s=A(e.clusterPositionCache,u.startTimestamp,e=>e.startTimestamp);-1!==s&&e.clusterPositionCache[s].elementStartPos===r||e.clusterPositionCache.splice(s+1,0,{elementStartPos:c.elementStartPos,startTimestamp:u.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=gr(e);if(!i)return!1;if(t&&t.includes(i.id))return!1;const{id:r,size:a}=i,s=e.filePos;switch(Nr(a),r){case sr.DocType:this.isWebM="webm"===kr(e,a);break;case sr.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 sr.SeekID:{const t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.id=fr(e,a)}break;case sr.SeekPosition:{const t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.segmentPosition=fr(e,a)}break;case sr.TimestampScale:if(!this.currentSegment)break;this.currentSegment.timestampScale=fr(e,a),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale;break;case sr.Duration:if(!this.currentSegment)break;this.currentSegment.duration=br(e,a);break;case sr.TrackEntry:if(!this.currentSegment)break;if(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...Ee,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!==zr.Block||e.data.algorithm!==qr.HeaderStripping)&&(xe._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===Sr)this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(this.currentTrack.codecId===vr)this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(t===Pr)this.currentTrack.info.codec="vp8";else if(t===Ir)this.currentTrack.info.codec="vp9";else if(t===xr)this.currentTrack.info.codec="av1";else if(t===Cr){const e=this.currentTrack.codecPrivate?k.decode(this.currentTrack.codecPrivate):"";ti.includes(e)&&(this.currentTrack.info.codec="prores",this.currentTrack.info.proresFormat=e)}const e=this.currentTrack;this.currentTrack.trackBacking=new Xr(e),this.currentSegment.tracks.push(this.currentTrack)}else if("audio"===this.currentTrack.info.type){t===Br?(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===Er?this.currentTrack.info.codec="mp3":t===_r?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=ni):t===Rr?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Fr?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Ar?(this.currentTrack.info.codec="ac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Dr?(this.currentTrack.info.codec="eac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Mr?(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 $r(e),this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null;break;case sr.TrackNumber:if(!this.currentTrack)break;this.currentTrack.id=fr(e,a);break;case sr.TrackType:{if(!this.currentTrack)break;const t=fr(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:{...x},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 sr.FlagEnabled:if(!this.currentTrack)break;fr(e,a)||(this.currentTrack=null);break;case sr.FlagDefault:if(!this.currentTrack)break;this.currentTrack.disposition.default=!!fr(e,a);break;case sr.FlagForced:if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!fr(e,a);break;case sr.FlagOriginal:if(!this.currentTrack)break;this.currentTrack.disposition.original=!!fr(e,a);break;case sr.FlagHearingImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!fr(e,a);break;case sr.FlagVisualImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!fr(e,a);break;case sr.FlagCommentary:if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!fr(e,a);break;case sr.CodecID:if(!this.currentTrack)break;this.currentTrack.codecId=kr(e,a);break;case sr.CodecPrivate:if(!this.currentTrack)break;this.currentTrack.codecPrivate=To(e,a);break;case sr.DefaultDuration:if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=fr(e,a);break;case sr.Name:if(!this.currentTrack)break;this.currentTrack.name=yr(e,a);break;case sr.Language:if(!this.currentTrack)break;if(this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=kr(e,a),Y(this.currentTrack.languageCode)||(this.currentTrack.languageCode=V);break;case sr.LanguageBCP47:{if(!this.currentTrack)break;const t=kr(e,a).split("-")[0];this.currentTrack.languageCode=t||V,this.currentTrack.hasLanguageBcp47=!0}break;case sr.Video:if("video"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(s,a));break;case sr.PixelWidth:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.width=fr(e,a);break;case sr.PixelHeight:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.height=fr(e,a);break;case sr.DisplayWidth:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.displayWidth=fr(e,a);break;case sr.DisplayHeight:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.displayHeight=fr(e,a);break;case sr.DisplayUnit:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.displayUnit=fr(e,a);break;case sr.AlphaMode:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.alphaMode=1===fr(e,a);break;case sr.Colour:if("video"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(s,a));break;case sr.MatrixCoefficients:{if("video"!==this.currentTrack?.info?.type)break;const t=fr(e,a),i=P[t];this.currentTrack.info.colorSpace.matrix=i}break;case sr.Range:{if("video"!==this.currentTrack?.info?.type)break;const t=fr(e,a);this.currentTrack.info.colorSpace.fullRange=1===t||2===t?2===t:void 0}break;case sr.TransferCharacteristics:{if("video"!==this.currentTrack?.info?.type)break;const t=fr(e,a),i=S[t];this.currentTrack.info.colorSpace.transfer=i}break;case sr.Primaries:{if("video"!==this.currentTrack?.info?.type)break;const t=fr(e,a),i=w[t];this.currentTrack.info.colorSpace.primaries=i}break;case sr.Projection:if("video"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(s,a));break;case sr.ProjectionPoseRoll:{if("video"!==this.currentTrack?.info?.type)break;const t=-br(e,a);try{this.currentTrack.info.rotation=u(t)}catch{}}break;case sr.Audio:if("audio"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(s,a));break;case sr.SamplingFrequency:if("audio"!==this.currentTrack?.info?.type)break;this.currentTrack.info.sampleRate=br(e,a);break;case sr.Channels:if("audio"!==this.currentTrack?.info?.type)break;this.currentTrack.info.numberOfChannels=fr(e,a);break;case sr.BitDepth:if("audio"!==this.currentTrack?.info?.type)break;this.currentTrack.info.bitDepth=fr(e,a);break;case sr.CuePoint:if(!this.currentSegment)break;this.readContiguousElements(e.slice(s,a)),this.currentCueTime=null;break;case sr.CueTime:this.currentCueTime=fr(e,a);break;case sr.CueTrackPositions:{if(null===this.currentCueTime)break;l(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 sr.CueTrack:{const t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;t.trackId=fr(e,a)}break;case sr.CueClusterPosition:{const t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;l(this.currentSegment),t.clusterPosition=this.currentSegment.dataStartPos+fr(e,a)}break;case sr.Timestamp:if(!this.currentCluster)break;this.currentCluster.timestamp=fr(e,a);break;case sr.SimpleBlock:{if(!this.currentCluster)break;const t=hr(e);if(null===t)break;const i=this.getTrackDataInCluster(this.currentCluster,t);if(!i)break;const r=xo(e),n=So(e),o=n>>1&3;let c=!!(128&n);"audio"===i.track.info?.type&&i.track.info.codec&&(c=!0);const l=To(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 sr.BlockGroup:if(!this.currentCluster)break;this.readContiguousElements(e.slice(s,a)),this.currentBlock=null;break;case sr.Block:{if(!this.currentCluster)break;const t=hr(e);if(null===t)break;const i=this.getTrackDataInCluster(this.currentCluster,t);if(!i)break;const r=xo(e),n=So(e)>>1&3,o=To(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 sr.BlockAdditions:this.readContiguousElements(e.slice(s,a));break;case sr.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 sr.BlockAdditional:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=To(e,a);break;case sr.BlockAddID:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=fr(e,a);break;case sr.BlockDuration:if(!this.currentBlock)break;this.currentBlock.duration=fr(e,a);break;case sr.ReferenceBlock:if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1;break;case sr.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(s,a));break;case sr.Targets:this.readContiguousElements(e.slice(s,a));break;case sr.TargetTypeValue:50!==fr(e,a)&&(this.currentTagTargetIsMovie=!1);break;case sr.TagTrackUID:case sr.TagEditionUID:case sr.TagChapterUID:case sr.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case sr.SimpleTag:if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(s,a));break;case sr.TagName:this.currentSimpleTagName=yr(e,a);break;case sr.TagString:{if(!this.currentSimpleTagName)break;const t=yr(e,a);this.processTagValue(this.currentSimpleTagName,t)}break;case sr.TagBinary:{if(!this.currentSimpleTagName)break;const t=To(e,a);this.processTagValue(this.currentSimpleTagName,t)}break;case sr.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 Be(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 sr.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 sr.ContentEncoding:this.currentDecodingInstruction={order:0,scope:zr.Block,data:null},this.readContiguousElements(e.slice(s,a)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case sr.ContentEncodingOrder:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=fr(e,a);break;case sr.ContentEncodingScope:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=fr(e,a);break;case sr.ContentCompression:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:qr.Zlib,settings:null},this.readContiguousElements(e.slice(s,a));break;case sr.ContentCompAlgo:if("decompress"!==this.currentDecodingInstruction?.data?.type)break;this.currentDecodingInstruction.data.algorithm=fr(e,a);break;case sr.ContentCompSettings:if("decompress"!==this.currentDecodingInstruction?.data?.type)break;this.currentDecodingInstruction.data.settings=To(e,a);break;case sr.ContentEncryption:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}return e.filePos=s+a,!0}decodeBlockData(e,t){l(e.decodingInstructions.length>0);let i=t;for(const r of e.decodingInstructions)if(l(r.data),"decompress"===r.data.type)if(r.data.algorithm===qr.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){l(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 Kr{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 j(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=A(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=L(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 l(-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(l(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);g(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?Ti: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?Ti:r.mainAdditional,o.alphaByteLength=r.mainAdditional.byteLength);const c=new Si(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,u=-1;if(e){const{blockIndex:i,correctBlockFound:r}=t(e);if(r)return this.fetchPacketInCluster(e,i,a);-1!==i&&(c=e,u=i)}const d=A(this.internalTrack.cuePoints,i,e=>e.time),h=-1!==d?this.internalTrack.cuePoints[d]:null,f=A(this.internalTrack.clusterPositionCache,i,e=>e.startTimestamp),m=-1!==f?this.internalTrack.clusterPositionCache[f]:null,p=Math.max(h?.clusterPosition??0,m?.elementStartPos??0)||null;let g;for(e?null===p||e.elementStartPos>=p?(g=e.elementEndPos,o=e):g=p:g=p??n.clusterSeekStartPos;null===n.elementEndPos||g<=n.elementEndPos-2;){if(o){const e=o.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>r)break}let e=s.reader.requestSliceRange(g,2,ur);if(de(e)&&(e=await e),!e)break;const i=g,d=gr(e);if(!d||!cr.includes(d.id)&&d.id!==sr.Void){const e=await Tr(s.reader,i,cr,Math.min(n.elementEndPos??1/0,i+Vr));if(e){g=e;continue}break}const h=d.id;let f=d.size;const m=e.filePos;if(h===sr.Cluster){o=await s.readCluster(i,n),f=o.elementEndPos-m;const{blockIndex:e,correctBlockFound:r}=t(o);if(r)return this.fetchPacketInCluster(o,e,a);-1!==e&&(c=o,u=e)}if(void 0===f){l(h!==sr.Cluster);f=(await wr(s.reader,m,lr,n.elementEndPos)).pos-m}const p=m+f;if(null===n.elementEndPos){let e=s.reader.requestSliceRange(p,2,ur);if(de(e)&&(e=await e),!e)break;if(mr(e)===sr.Segment){n.elementEndPos=p;break}}g=p}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?Qe(a.data):null,hevcCodecInfo:"hevc"===this.internalTrack.info.codec&&a?nt(a.data):null,vp9CodecInfo:"vp9"===this.internalTrack.info.codec&&a?yt(a.data):null,av1CodecInfo:"av1"===this.internalTrack.info.codec&&a?wt(a.data):null,proresCodecInfo:"prores"===this.internalTrack.info.codec&&a?Tt(a.data):null,proresFormat:this.internalTrack.info.proresFormat};if(!I(this.internalTrack.info.colorSpace)){const a=ai(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:ri(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 $r extends Kr{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&&Vt(e.data)}return{codec:si({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 Gr=async(e,t,i,r=null)=>{let a=t;for(;null===i||a=4;){const t=s.filePos,i=Bo(s),n=null!==e.fileSize?e.fileSize-a:null,o=pi(i,n);if(o.header&&(!r||o.header.sampleRate===r.sampleRate&&o.header.mpegVersionId===r.mpegVersionId&&o.header.layer===r.layer&&bi(o.header.channel)===bi(r.channel)))return{header:o.header,startPos:a};s.filePos=t+o.bytesAdvanced,a=s.filePos}}return null};class Qr extends wi{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 B,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 Yr(this)]})())}async advanceReader(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,Vo);if(de(e)&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const t=$o(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}const e=await Gr(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=mi(t.mpegVersionId,t.channel);let r=this.reader.requestSlice(e.startPos+i,4);if(de(r)&&(r=await r),r){const a=Bo(r);if(a===hi||a===fi){if(this.xingFrameHeader||(this.xingFrameHeader=t,this.xingFrameHeaderPos=e.startPos),!this.xingData){let t=this.reader.requestSlice(e.startPos+i+4,12);if(de(t)&&(t=await t),t){const e=To(t,12),i=g(e),r=i.getUint32(0,!1);this.xingData={frameCount:r&ki.FrameCount?i.getUint32(4,!1):null,fileSize:r&ki.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,Vo);if(de(i)&&(i=await i),!i)break;const r=$o(i);if(!r)break;t=!0;let a=this.reader.requestSlice(i.filePos,r.size);if(de(a)&&(a=await a),!a)break;Go(a,r,this.metadataTags),e=i.filePos+r.size}if(!t&&null!==this.reader.fileSize&&this.reader.fileSize>=Ho){let e=this.reader.requestSlice(this.reader.fileSize-Ho,Ho);de(e)&&(e=await e),l(e);"TAG"===Oo(e,3)&&Ko(e,this.metadataTags)}return this.metadataTags}finally{e()}}}class Yr{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return l(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(l(null!==e.firstFrameHeader),l(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=A(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 ea=e=>{const t=g(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},ta=(e,t,i)=>{let r=0,a=null;if(e.length>0)if("vorbis"===t.codec){l(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:St[t]*r}})(e).durationInSamples}return{durationInSamples:r,vorbisBlockSize:a}},ia=27,ra=282,aa=e=>{const t=e.filePos;if(Eo(e)!==Jr)return null;e.skip(1);const i=So(e),r=Do(e),a=Eo(e),s=Eo(e),n=Eo(e),o=So(e),c=new Uint8Array(o);for(let d=0;de+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}},sa=(e,t)=>{for(;e.filePos>>8&255)===i||(t>>>16&255)===i||(t>>>24&255)===i){if(e.skip(-4),t===Jr)return!0;e.skip(1)}}return!1};class na extends wi{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,ia,ra);if(de(t)&&(t=await t),!t)break;const i=aa(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 oa(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=g(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:vt(a.data).modeBlockflags},Ct(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=g(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=ni,t.codecInfo.opusInfo={preSkip:a.preSkip},Ct(r.data.subarray(8),this.metadataTags)}async readPacket(e,t){l(te+t.length,0);if(0===o)return null;const c=new Uint8Array(o);let u=0;for(let l=0;l{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 oa{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new B,this.internalSampleRate="opus"===e.codecInfo.codec?ni:e.sampleRate}getType(){return"audio"}getId(){return this.bitstream.serialNumber}getNumber(){const e=this.demuxer.trackBackings.findIndex(e=>e.bitstream===this.bitstream);return l(-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 l(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 V}getDisposition(){return{...Ee,primary:!1}}granulePositionToTimestampInSamples(e){return"opus"===this.bitstream.codecInfo.codec?(l(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,i){if(!e)return null;const{durationInSamples:r,vorbisBlockSize:a}=ta(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),s=new Si(i.metadataOnly?Ti: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){l(this.bitstream.lastMetadataPacket);const t=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let i=0;"opus"===this.bitstream.codecInfo.codec&&(l(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=j(e*this.internalSampleRate);if(0===i)return this.getFirstPacket(t);if(i<0)return null;l(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=u.headerStartPos:(a=u,n.push(u));continue e}r=u.headerStartPos+u.totalSize}}let o=r.startPage;for(const l of n){if(l.granulePosition===a.granulePosition)break;(!o||l.headerStartPos>o.headerStartPos)&&(o=l)}let c=o;const u=[c];for(;c.serialNumber!==this.bitstream.serialNumber||c.granulePosition!==a.granulePosition;){const e=c.headerStartPos+c.totalSize;let t=this.demuxer.reader.requestSliceRange(e,ia,ra);de(t)&&(t=await t),l(t);const i=aa(t);l(i),c=i,c.serialNumber===this.bitstream.serialNumber&&u.push(c)}l(-1!==c.granulePosition);let d,h,f=null,m=c,p=0;if(c.headerStartPos===r.startPage.headerStartPos)d=this.granulePositionToTimestampInSamples(0),h=!0,f=0;else{d=0,h=!1;for(let t=c.lacingValues.length-1;t>=0;t--){if(c.lacingValues[t]<255){f=t+1;break}}if(null===f)throw new Error("Invalid page with granule position: no packets end on this page.");p=f-1;const e={data:Ti,endPage:m,endSegmentIndex:p};if(await this.demuxer.findNextPacketStart(e)){const e=la(u,c,f);l(e);const t=ca(u,e.page,e.segmentIndex);t&&(c=t.page,f=t.segmentIndex)}else for(;;){const e=la(u,c,f);if(!e)break;const t=ca(u,e.page,e.segmentIndex);if(!t)break;if(c=t.page,f=t.segmentIndex,e.page.headerStartPos!==m.headerStartPos){m=e.page,p=e.segmentIndex;break}}}let g=null,k=null;for(;null!==c;){l(null!==f);const e=await this.demuxer.readPacket(c,f);if(!e)break;if(!(c.headerStartPos===r.startPage.headerStartPos&&fi||Math.max(a.timestampInSamples,0)===i))break}const a=await this.demuxer.findNextPacketStart(e);if(!a)break;c=a.startPage,f=a.startSegmentIndex}return g}async getPacketSequential(e,t){const i=await this.sequentialScanMutex.acquire();try{const i=j(e*this.internalSampleRate);e=i/this.internalSampleRate;const r=A(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);l(e),this.sequentialScanCache.length>0&&l(d(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 ca=(e,t,i)=>{let r=t,a=i;e:for(;;){for(a--;a>=0;a--){if(r.lacingValues[a]<255){a++;break e}}l(-1===a);if(!(1&r.headerType)){a=0;break}const t=O(e,e=>e.headerStartPos{if(i>0)return{page:t,segmentIndex:i-1};const r=O(e,e=>e.headerStartPos{let e=this.reader.requestSlice(0,12);de(e)&&(e=await e),l(e);const t=Oo(e,4),i="RIFX"!==t,r="RF64"===t,a=Co(e,i);let s=r?this.reader.fileSize:Math.min(a+8,this.reader.fileSize??1/0);if("WAVE"!==Oo(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=vo(r,i),s=t-18;if(Math.min(s,e)>=22&&a===ua.EXTENSIBLE){r.skip(6);const e=To(r,16);a=e[0]|e[1]<<8}}if(a!==ua.MULAW&&a!==ua.ALAW||(c=8),a!==ua.PCM&&a!==ua.IEEE_FLOAT&&a!==ua.ALAW&&a!==ua.MULAW)throw new Error(`Unsupported WAVE codec (format tag ${a}). Only integer/float PCM, A-law, and \u03bc-law are supported.`);if(a===ua.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===ua.IEEE_FLOAT&&![32,64].includes(c))throw new Error(`Unsupported WAVE float bit depth (${c}). Only 32 and 64 bits are supported.`);this.audioInfo={format:a,numberOfChannels:s,sampleRate:n,sampleSizeInBytes:Math.ceil(c/8),blockSizeInBytes:o}}async parseListChunk(e,t,i){var r,a,s,n,o,c,l,u,d,h,f;let m=this.reader.requestSlice(e,t);if(de(m)&&(m=await m),!m)return;const p=Oo(m,4);if("INFO"!==p&&"INF0"!==p)return;let g=m.filePos;for(;g<=e+t-8;){m.filePos=g;const e=Oo(m,4),t=Co(m,i),p=To(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&&((d=this.metadataTags).date??(d.date=new Date(e,0,1)))}break;case"IGNR":case"GENR":(h=this.metadataTags).genre??(h.genre=y);break;case"ICMT":case"CMNT":case"COMM":(f=this.metadataTags).comment??(f.comment=y)}g+=8+t+(1&t)}}async parseId3Chunk(e,t){let i=this.reader.requestSlice(e,t);if(de(i)&&(i=await i),!i)return;const r=$o(i);if(r){const a=t-Vo;if(r.size=Math.min(r.size,a),r.size>0){const t=i.slice(e+Vo,r.size);Go(t,r,this.metadataTags)}}}getCodec(){if(l(this.audioInfo),this.audioInfo.format===ua.MULAW)return"ulaw";if(this.audioInfo.format===ua.ALAW)return"alaw";if(this.audioInfo.format===ua.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===ua.IEEE_FLOAT){if(4===this.audioInfo.sampleSizeInBytes)return"pcm-f32";if(8===this.audioInfo.sampleSizeInBytes)return"pcm-f64"}l(!1)}async getMimeType(){return"audio/wav"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}const fa=2048;class ma{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return l(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){const e=this.demuxer.getCodec();return e?(l(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null}getNumberOfChannels(){return l(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return l(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return l(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 l(-1!==this.demuxer.dataSize),this.demuxer.dataSize/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return V}getDisposition(){return{...Ee}}async getPacketAtIndex(e,t){l(e>=0),l(this.demuxer.audioInfo);const i=e*fa*this.demuxer.audioInfo.blockSizeInBytes;if(i>=this.demuxer.dataSize)return null;const r=Math.min(fa*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(de(e)&&(e=await e),!e)return null}let a;if(t.metadataOnly)a=Ti;else{let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+i,r);de(e)&&(e=await e),l(e),a=To(e,r)}const s=e*fa/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 Si(a,"key",s,n,e,r)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,t){l(this.demuxer.audioInfo);const i=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/fa,(this.demuxer.dataSize-1)/(fa*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;l(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){l(this.demuxer.audioInfo);const i=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/fa);return this.getPacketAtIndex(i+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const pa=e=>{const t=e.filePos,i=To(e,9),r=new _e(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}},ga=1024;class ka extends wi{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.trackBackings=[],this.readingMutex=new B,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();l(this.firstFrameHeader),this.trackBackings=[new ya(this)]})())}async advanceReader(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,Vo);if(de(e)&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const t=$o(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}let e=this.reader.requestSliceRange(this.lastLoadedPos,7,9);if(de(e)&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const t=pa(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=Re[t.samplingFrequencyIndex];l(void 0!==i);const r=ga/i,a={timestamp:this.nextTimestampInSamples/i,duration:r,dataStart:t.startPos,dataSize:t.frameLength};this.loadedSamples.push(a),this.nextTimestampInSamples+=ga,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,Vo);if(de(t)&&(t=await t),!t)break;const i=$o(t);if(!i)break;let r=this.reader.requestSlice(t.filePos,i.size);if(de(r)&&(r=await r),!r)break;Go(r,i,this.metadataTags),e=t.filePos+i.size}return this.metadataTags}finally{e()}}}class ya{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return this.getSampleRate()/ga}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 V}getCodec(){return"aac"}getInternalCodecId(){return l(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){l(this.demuxer.firstFrameHeader);const e=Fe[this.demuxer.firstFrameHeader.channelConfiguration];return l(void 0!==e),e}getSampleRate(){l(this.demuxer.firstFrameHeader);const e=Re[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return l(void 0!==e),e}getDisposition(){return{...Ee}}async getDecoderConfig(){return l(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=Ti;else{let e=this.demuxer.reader.requestSlice(i.dataStart,i.dataSize);if(de(e)&&(e=await e),!e)return null;r=To(e,i.dataSize)}return new Si(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=F(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=A(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,Vo);if(de(e)&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const i=$o(e);if(!i)break;let r=this.reader.requestSlice(e.filePos,i.size);de(r)&&(r=await r),l(r),Go(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===So(s)){const t=s.filePos;if(So(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=To(e,4),a=new _e(r);if(32764!==a.readBits(15))return null;if(null===this.blockingBit){l(t);const e=a.readBits(1);this.blockingBit=e}else if(1===this.blockingBit){l(!t);if(1!==a.readBits(1))return null}else{if(0!==this.blockingBit)throw new Error("Invalid blocking bit");l(!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;l(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 _e(To(e,1));for(;1===i.readBits(1);)t++;if(0===t)return i.readBits(7);const r=[],a=t-1,s=new _e(To(e,a)),n=8-t-1;for(let o=0;oe|t<"uncommon-u16"===t?Po(e)+1:"uncommon-u8"===t?So(e)+1:"number"===typeof t?t:(z(t),void l(!1)))(e,s),u=((e,t)=>"uncommon-u16"===t?Po(e):"uncommon-u16-10"===t?10*Po(e):"uncommon-u8"===t?So(e):"number"===typeof t?t:null)(e,n);if(null===u)return null;if(u!==this.audioInfo.sampleRate)return null;const d=e.filePos-i,h=So(e);e.skip(-d),e.skip(-1);const f=(e=>{let t=0;for(const i of e){t^=i;for(let e=0;e<8;e++)0!==(128&t)?t=t<<1^7:t<<=1,t&=255}return t})(To(e,d));return h!==f?null:{num:o,blockSize:c,sampleRate:u}}async advanceReader(){await this.readMetadata(),l(null!==this.lastLoadedPos),l(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 wa{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return l(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return l(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return V}getTimeResolution(){return l(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 l(this.demuxer.audioInfo),0===this.demuxer.audioInfo.totalSamples?null:this.demuxer.audioInfo.totalSamples/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getDisposition(){return{...Ee}}async getDecoderConfig(){return l(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(l(this.demuxer.audioInfo),e<0)return null;const i=await this.demuxer.readingMutex.acquire();try{for(;;){const i=A(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=Ti;else{let e=this.demuxer.reader.requestSlice(i.byteOffset,i.byteSize);if(de(e)&&(e=await e),!e)return null;r=To(e,i.byteSize)}l(this.demuxer.audioInfo);const a=i.blockOffset/this.demuxer.audioInfo.sampleRate,s=i.blockSize/this.demuxer.audioInfo.sampleRate;return new Si(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 Ta=9e4,Sa=2**33,va=188,Pa="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.",Ia=new Set([133,134,162]),xa=new Set;class Ca extends wi{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);de(e)&&(e=await e),l(e);const t=To(e,205);if(71===t[0]&&71===t[188])this.packetOffset=0,this.packetStride=va;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 _e(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=Ea(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 Da(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=Qe(r.suppliedPacket.data),!e.info.avcCodecInfo)continue;const t=e.info.avcCodecInfo.sequenceParameterSets[0];l(t);const i=et(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:w[i.colourPrimaries],transfer:S[i.transferCharacteristics],matrix:P[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=nt(r.suppliedPacket.data),!e.info.hevcCodecInfo)continue;const t=e.info.hevcCodecInfo.arrays.find(e=>e.nalUnitType===Ue.SPS_NUT).nalUnits[0];l(t);const i=st(t);e.info.width=i.displayWidth,e.info.height=i.displayHeight,i.pixelAspectRatio.num>i.pixelAspectRatio.den?(e.info.squarePixelWidth=Math.round(e.info.width*i.pixelAspectRatio.num/i.pixelAspectRatio.den),e.info.squarePixelHeight=e.info.height):(e.info.squarePixelWidth=e.info.width,e.info.squarePixelHeight=Math.round(e.info.height*i.pixelAspectRatio.den/i.pixelAspectRatio.num)),e.info.colorSpace={primaries:w[i.colourPrimaries],transfer:S[i.transferCharacteristics],matrix:P[i.matrixCoefficients],fullRange:!!i.fullRangeFlag},e.info.reorderSize=i.maxDecFrameBuffering;break}throw new Error("Unhandled.")}e.info.decoderConfig={codec:ri({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=bo.tempFromBytes(r.suppliedPacket.data),i=pa(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=Fe[i.channelConfiguration],e.info.sampleRate=Re[i.samplingFrequencyIndex]}else if("mp3"===e.info.codec){const t=Bo(bo.tempFromBytes(r.suppliedPacket.data)),i=pi(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=bi(i.header.channel),e.info.sampleRate=i.header.sampleRate}else if("ac3"===e.info.codec){const t=Et(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=Bt[t.acmod]+t.lfeon,e.info.sampleRate=Ne[t.fscod]}else if("eac3"===e.info.codec){const t=Ft(r.suppliedPacket.data);if(!t)throw new Error("Invalid E-AC-3 audio stream; could not read sync frame from first packet.");const i=At(t);if(null===i)throw new Error("Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.");e.info.numberOfChannels=Dt(t),e.info.sampleRate=i}else{if("dts"!==e.info.codec)throw new Error("Unhandled.");{const t=Ht(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:si({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 _e(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&&Ia.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:xa.has(t)||(xe._warn(`Note: MPEG-TS streams with stream_type 0x${t.toString(16)} are not currently supported.`),xa.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 _e(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 Ra(n)):this.trackBackingEntries.push(new Fa(n)))})())}async getTrackBackings(){return await this.readMetadata(),this.trackBackingEntries}async getMetadataTags(){return{}}async getMimeType(){await this.readMetadata();return(e=>{let t="video/MP2T";const i=[...new Set(e.filter(Boolean))];return i.length>0&&(t+=`; codecs="${i.join(", ")}"`),t})(await Promise.all(this.trackBackingEntries.map(e=>e.getDecoderConfig().then(e=>e?.codec??null))))}async readSection(e,t,i=!1){let r=e,a=e;const s=[];let n,o=0,c=null,l=!0,u=0;for(;;){const e=await this.readPacket(a);if(a+=this.packetStride,!e)break;if(c){if(e.pid!==c.pid){if(i)break;continue}if(1===e.payloadUnitStartIndicator)break}else{if(0===e.payloadUnitStartIndicator)break;c=e}const n=!!(2&e.adaptationFieldControl),d=!!(1&e.adaptationFieldControl);let h=0;if(n&&(h=1+e.body[0],e===c&&h>1&&(u=e.body[1]>>6&1)),d&&(0===h?(s.push(e.body),o+=e.body.byteLength):(s.push(e.body.subarray(h)),o+=e.body.byteLength-h)),r=a,!t&&o>=64){l=!1;break}if(-1!==F(this.sectionEndPositions,r,e=>e)){l=!1;break}}if(l){const e=A(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(de(t)&&(t=await t),!t)return null;if(71!==So(t))throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");const i=Po(t);return{payloadUnitStartIndicator:i>>14&1,pid:8191&i,adaptationFieldControl:So(t)>>4&3}}async readPacket(e){let t=this.reader.requestSlice(e,va);if(de(t)&&(t=await t),!t)return null;const i=To(t,va);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>=Sa-t?-8589934592:Sa}}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 _e(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(Pa);return{sectionStartPos:t.startPos,sectionEndPos:t.endPos,pts:n,randomAccessIndicator:t.randomAccessIndicator}},Ea=(e,t,i)=>{l(null!==t.endPos);const r=Ba(e,t,i);if(!r)return null;const a=new _e(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;l(Number.isInteger(c));const u=t.payload.subarray(c,s>0?6+s:t.payload.byteLength);return{...r,data:u}};class _a{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++,l(r instanceof _a),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 V}getDisposition(){return{...Ee,primary:!1}}getTimeResolution(){return Ta}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 Si(i.metadataOnly?Ti:e.data,r,e.pts/Ta,Math.max(t/Ta,0),e.sequenceNumber,e.data.byteLength)}async getFirstPacket(e){const t=this.elementaryStream.firstSection;l(t);const i=Ea(this.elementaryStream.demuxer,t,!0);l(i);const r=new Da(this.elementaryStream,i),a=new Ma(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);l(s);const n=Ea(a,s,!0);l(n);const o=new Da(this.elementaryStream,n);i=new Ma(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=j(e*Ta),a=this.elementaryStream.demuxer,{reader:s,seekChunkSize:n}=a,o=this.elementaryStream.pid,c=async(e,t,i)=>{let r=e;for(;re.pts),g=-1!==p?m[p]:null;if(g&&r-g.pts<45e3)f=g.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=$(t*n,a.packetStride)+h.sectionStartPos,l=o+n,u=await c(o,l,!1);u?u.pesPacketHeader.pts<=r?(e=t,i=t+1):s=t-1:s=t-1}}}f=$(e*n,a.packetStride)+h.sectionStartPos}const k=await c(f,s.fileSize??1/0,!1);let y=k?.pesPacketHeader??null;y||(y=h);const b=this.getReorderSize(),w=async(e,t)=>{const s=await a.readSection(e,!0);l(s);const n=Ea(a,s,!0);l(n);const o=new Da(this.elementaryStream,n),c=new Ma(this,o);for(;;){if((d(c.presentationOrderPackets)?.pts??-1/0)>=r)break;if(!(await c.readNextPacket()))break}const u=L(c.presentationOrderPackets,t);if(-1===u)return null;const h=c.presentationOrderPackets[u],f=0===u?0:h.pts-c.presentationOrderPackets[u-1].pts;for(;c.decodeOrderPackets[0]!==h;)c.decodeOrderPackets.shift();c.lastDuration=f;const m=await c.readNext();l(m);const p=this.createEncodedPacket(m.packet,m.duration,i);return this.packetBuffers.set(p,c),this.packetSectionStarts.set(p,m.packet.sectionStartPos),p};if(!t||this.allPacketsAreKeyPackets()){e:for(;;){let e=y.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=Ba(a,t,!1);if(e&&null!==e.pts){if(e.pts>r)break e;y=e,Aa(this.elementaryStream,y);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=Ba(a,t,!1);if(e&&null!==e.pts){y=e;break}}}e-=a.packetStride}}return w(y.sectionStartPos,e=>e.pts<=r)}{let e=f,t=null;const i=!this.elementaryStream.canBeTrustedWithKeyPackets;for(;;){let d=null;const f=e<=h.sectionStartPos;let m,p=null;if(f)m=h,p=u;else{const t=await c(e,s.fileSize??1/0,i);m=t?.pesPacketHeader??null,p=t?.section??null}let g=!1,k=0;e:for(;m&&!(null!==t&&m.sectionStartPos>=t);){if(m.pts<=r){let e;if(this.elementaryStream.canBeTrustedWithKeyPackets)e=1===m.randomAccessIndicator;else{l(p);const t=Ea(a,p,!0);l(t);const i=new Da(this.elementaryStream,t);await i.markNextPacket(),e=1===i.suppliedPacket?.randomAccessIndicator}e&&(d=m)}if(m.pts>r&&(g=!0),g&&(k++,k>b))break;let e=m.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=Ba(a,t,!1);if(e&&null!==e.pts){m=e,p=t,Aa(this.elementaryStream,m);break}}}e+=a.packetStride}}if(d){let e=d;if(0===k)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=Ba(a,r,!1);if(t&&null!==t.pts){e=t;break}}}t-=a.packetStride}}const t=await w(e.sectionStartPos,e=>e.pts<=r&&1===e.randomAccessIndicator);return l(t),t}if(f)return null;t=e,e=Math.max($(e-h.sectionStartPos-n,a.packetStride)+h.sectionStartPos,h.sectionStartPos)}}}}class Ra extends _a{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 l(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}}class Fa extends _a{getType(){return"audio"}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}async getDecoderConfig(){return l(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 0}}const Aa=(e,t)=>{const i=e.referencePesPackets,r=A(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 l(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 d=c[u+1],f=c[u+2],m=c[u+3];let p=0;if(0===d&&0===f&&1===m?p=4:0===d&&1===f&&(p=3),0===p){u++;continue}const g=i;a??(a=g);const k=u+p,y=k+r,b=6;if(y+("avc"===t?b:1)>l){this.seekTo(i);break}const w=c[k];let T,S,v;if("avc"===t)T=je(w),S=T===Le.NON_IDR_SLICE||T===Le.SLICE_DPA||T===Le.IDR,v=T===Le.SEI||T===Le.SPS||T===Le.PPS||T===Le.AUD;else{T=at(w);if(((1&w)<<5|c[k+1]>>3)>0){u+=p;continue}S=T<=Ue.RASL_R||T>=Ue.BLA_W_LP&&T<=21,v=T>=Ue.VPS_NUT&&T<=37||T===Ue.PREFIX_SEI_NUT||T>=41&&T<=44||T>=48&&T<=55}let P=!1;if(S){let e;if("avc"===t){const t=c.subarray(y,y+b),i=h(new _e(t));e=!s||i<=n,n=i}else e=c[y]>>7===1;e&&(s?P=!0:s=!0)}else v&&s&&(P=!0);if(P){const e=g-a;return this.seekTo(a),this.supplyPacket(e,0)}u+=p}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);de(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=_t[3*n+s];l(void 0!==o),this.seekTo(t),r=this.ensureBuffered(o),de(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(de(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=Rt[n];this.seekTo(t),r=this.ensureBuffered(s),de(r)&&(r=await r);const c=256*o,l=Math.round(c*Ta/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(de(r)&&(r=await r),r<18)return;const a=this.readBytes(18),s=jt(a);let n=s?null:Kt(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);de(i)&&(i=await i),n=Kt(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(de(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(l(-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(l(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 Na="application/vnd.apple.mpegurl",Oa="#EXT-X-STREAM-INF:",La="#EXT-X-I-FRAME-STREAM-INF:",za="#EXT-X-MEDIA:",Ua="#EXTINF:",qa="#EXT-X-MAP:",Wa="#EXT-X-KEY:",Ha="#EXT-X-MEDIA-SEQUENCE:",Va="#EXT-X-BYTERANGE:",ja="#EXT-X-PROGRAM-DATE-TIME:",Ka="#EXT-X-TARGETDURATION:",Xa="#EXT-X-PLAYLIST-TYPE:",$a=e=>0===e.length||e.startsWith("#")&&!e.startsWith("#EXT");class Ga{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=ye(e,e=>"video"===e.getType())+1;e.push(new Ja(this,t,i))}else if("audio"===t.type){const i=ye(e,e=>"audio"===e.getType())+1;e.push(new Za(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=ye(e,e=>"video"===e.getType())+1;e.push(new Ja(this,{id:e.length+1,type:"video"},t))}else if("audio"===r.type){const t=ye(e,e=>"audio"===e.getType())+1;e.push(new Za(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 Ya{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(),l(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){l(e.sequenceNumber>=0),l(this.segmentedInput.firstSegment);const r=await this.segmentedInput.getMediaOffset(t,i.input),a=t.timestamp-this.segmentedInput.firstSegment.timestamp,s=e.clone({timestamp:X(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(),l(this.firstInputTrack),l(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 Ja extends Ya{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 Za extends Ya{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())}}pe();const es=1/0;"undefined"!==typeof FinalizationRegistry&&new FinalizationRegistry(e=>{e()});class ts extends ve{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 ko;return this._sizePromise??(this._sizePromise=(async()=>{let e=this._getFileSize();return void 0!==e||(await this._read(0,1,0,es),e=this._getFileSize(),l(void 0!==e)),e})())}async getSize(){if(this._disposed)throw new ko;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 gs(this,e,t)}_dispatchRead(e,t){this.onread?.(e,t),this._emit("read",{start:e,end:t})}ref(){return new is(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){this._refCount--,0===this._refCount&&(this._dispose(),this._disposed=!0)}}class is{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;l(e._refCount>0),e._decrementRefCount(),e._refFinalizationRegistry?.unregister(this),this._freed=!0,this._source=null}[Symbol.dispose](){this.freed||this.free()}}class rs extends ts{constructor(e,t){if("string"!==typeof e)throw new TypeError("rootPath must be a string.");if("function"!==typeof t)throw new TypeError("requestHandler must be a function.");super(),this.rootPath=e,this.requestHandler=t}_resolveRequest(e){const t=this.requestHandler(e),i=e=>{var t;if(!(e instanceof ts||e instanceof is))throw new TypeError("requestHandler must return or resolve to a Source or SourceRef.");const i=e instanceof ts?e.ref():e;return(t=i.source)._usedForHls||(t._usedForHls=this._usedForHls),i};return de(t)?t.then(i):i(t)}}const as=(e,t)=>e.path===t.path;class ss extends rs{constructor(){super(...arguments),this._root=null,this._rootRequest=null}_read(e,t,i,r){if(!this._root){if(!this._rootRequest){const e=this._resolveRequest({path:this.rootPath,isRoot:!0}),t=e=>{const t=e instanceof ts?e.ref():e;return this._root=t,this._rootRequest=null,t};de(e)?this._rootRequest=e.then(t):(t(e),l(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 ns="undefined"!==typeof FinalizationRegistry?new FinalizationRegistry(e=>{e.cancel().catch(()=>{})}):null;class os extends ts{constructor(e,t={}){if(!(e instanceof Blob))throw new TypeError("blob must be a Blob.");if(!t||"object"!==typeof t)throw new TypeError("options must be an object.");if(void 0!==t.maxCacheSize&&(!ge(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 ps({maxCacheSize:t.maxCacheSize??8388608,maxWorkerCount:4,runWorker:this._runWorker.bind(this),onIdleWorkerRemoved:e=>{const t=this._readers.get(e);t&&(this._readers.delete(e),ns?.unregister(e),t.cancel().catch(()=>{}))},prefetchProfile:ms.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){l(e.strictTarget);let t=this._readers.get(e);if(void 0===t){if("stream"in this._blob&&!ae()&&!1!==this._options.useStreamReader){t=this._blob.slice(e.currentPos).stream().getReader(),ns?.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 xe._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)},ls=new Set;class us extends rs{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&&(!ge(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 us(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??cs,this._requestInit={...t.requestInit};let i=null;if(t.requestInit?.headers){const e={...ee(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=hs(i);e&&(this._offset=e.offset,this._length=e.length)}this._orchestrator=new ps({maxCacheSize:t.maxCacheSize??67108864,maxWorkerCount:t.parallelism??2,runWorker:this._runWorker.bind(this),prefetchProfile:ms.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:H(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 de(s)?s.then(n):n(s)}async _runWorker(e){for(;;){const i=new AbortController,r=await te(this._options.fetchFn??fetch,this._url,Z(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")||ls.has(e.origin)||(xe._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.`),ls.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){xe._error("Error while reading response stream. Attempting to resume.",t),await Se(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;xe._error("Error while reading response stream. Attempting to resume.",a),await Se(1e3*e);const s=await te(this._options.fetchFn??fetch,this._url,Z(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 fs(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);de(e)?e.then(e=>{e?(l(e.offset===o.start),o.resolve(e.bytes)):o.resolve(null)},e=>o.reject(e)):(l(null===e),o.resolve(null))}}_dispose(){this._orchestrator.dispose(),this._sequentialBacking&&(this._sequentialBacking._disposed=!0,this._sequentialBacking._dispose())}}const ds=/^bytes=(\d+)-(\d*)$/,hs=e=>{const t=ds.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=A(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}=M();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 ko);this._pendingSlices.length=0,this._cache.length=0,this._reader?.cancel()}}const ms={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(fe(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 ps{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){l(!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);l(s<=e&&t<=n);let o=null;const c=A(this.cache,e,e=>e.start),u=-1!==c?this.cache[c]:null;u&&u.start<=e&&t<=u.end&&(u.age=this.nextAge++,o={bytes:u.bytes,view:u.view,offset:u.start});const d=A(this.cache,s,e=>e.start),h=o?null:new Uint8Array(t-e);let f=0,m=s;const p=[];if(-1!==d){for(let i=d;i=n)break;if(r.end<=s)continue;const a=Math.max(s,r.start),o=Math.min(n,r.end);if(l(a<=o),m=h.length&&(o={bytes:h,view:g(h),offset:e}),0===p.length)return l(o),o;const{promise:k,resolve:y,reject:b}=M(),w=[];for(const l of p){const i=Math.max(e,l.start),r=Math.min(t,l.end);i===l.start&&r===l.end?w.push(l):ie.hole.start),i=-1!==t?this.queuedReads[t]:null;for(i&&l.start<=i.hole.end?(i.hole.end=Math.max(i.hole.end,l.end),i.strictTarget&&(i.strictTarget=e),T&&i.pendingSlices.push(T)):(t++,i={hole:{start:l.start,end:l.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 o?k.catch(e=>{if(!this.disposed){if(!this.options.handleUnhandledError)throw e;this.options.handleUnhandledError(e)}}):(l(h),o=k.then(t=>t&&{bytes:t,view:g(t),offset:e})),o}checkHoleAgainstWorker(e,t,i){if(fe(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);l(-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=A(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=g(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=g(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 de(a)?a.then(s):s(a)}_dispose(){this._ref?.free()}ref(){return this._ref??(this._ref=this._baseSource.ref()),super.ref()}}var ks=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},ys=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 bs=/^0[xX][0-9a-fA-F]+$/,ws=/^data:.*;base64,/i;class Ts extends Qa{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 Se(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=ks(t,await this.demuxer.input._getSourceUncached({path:this.rootPath,isRoot:!1}),!1),r=new yo(i.source),a=await r.requestEntireFile();l(a),e=Lo(a,a.length,{ignore:$a}),i.source instanceof rs&&(this.rootPath=i.source.rootPath)}catch(T){t.error=T,t.hasError=!0}finally{ys(t)}}const t=!1!==this.input._formatOptions.hls?.offsetTimestampsByDateTime;let i=!1,r=0,a=null,s=null,n=null,o=0,c=null,u=null,h=null,f=null,m=null,p=null,k=!1,y=d(this.segments)??null;const b=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}},w=e=>{o=e,y&&(l(null!==y.sequenceNumber),y.sequenceNumber0&&null!==p&&(r=o*p),k=!0);const e=T.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(T.startsWith(qa)){const e=new Ga(T.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=b(i)),o&&null===o.offset)throw new Error("Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset.");if(!y){const e={path:ke(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.");u={timestamp:r,unixEpochTimestamp:a,firstSegment:null,sequenceNumber:null,location:e,duration:0,encryption:n,initSegment:null,lastProgramDateTimeSeconds:m}}s=null,null===f?h=null:f=null}else if(T.startsWith(Wa)){const e=new Ga(T.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(!bs.test(r))throw new Error(`Unsupported IV format '${r}'.`);let e=r.slice(2);e=e.padStart(32,"0"),i=new Uint8Array(Ri);for(let t=0;t=8&&112===t[4]&&115===t[5]&&115===t[6]&&104===t[7]){const e=g(t).getUint32(0);r=vi(t.subarray(8,Math.min(e,t.length)))}}n={method:t,psshBox:r}}}}else if(T.startsWith(Ha)){const e=T.slice(22),t=Number(e);if(!Number.isInteger(t)||t<0)throw new Error(`Invalid EXT-X-MEDIA-SEQUENCE value '${e}'.`);w(t)}else if(T.startsWith(Va)){const e=b(T.slice(17));if(null===e.offset){if(null===h)throw new Error("Invalid M3U8 file; #EXT-X-BYTERANGE without offset requires a previous byte range.");e.offset=h}f=e,h=e.offset+e.length}else if(T.startsWith(ja)){if(y)continue;const e=T.slice(25),i=Date.parse(e);if(!Number.isFinite(i))continue;const s=i/1e3;if(m===s)continue;if(null===m&&this.segments.length>0){const e=d(this.segments),i=s-(e.timestamp+e.duration);for(const r of this.segments)r.unixEpochTimestamp=r.timestamp+i,t&&(r.timestamp=r.unixEpochTimestamp)}m=s,a=s,t&&(r=s)}else if("#EXT-X-DISCONTINUITY"===T)c=null;else if(T.startsWith(Ka)){const e=T.slice(22),t=Number(e);if(!Number.isFinite(t)||t<0)throw new Error(`Invalid EXT-X-TARGETDURATION value '${e}'.`);this.refreshInterval=t,p=t}else{if("#EXT-X-ENDLIST"===T){this.streamHasEnded=!0;break}if(T.startsWith(Xa)){"vod"===T.slice(21).toLowerCase()&&(this.streamHasEnded=!0)}}}else{if("#EXTM3U"!==T)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=A(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=>Pi(e,r))||(i=[...i,r]),this.input._formatOptions.isobmff.resolveKeyId({...e,psshBoxes:i})})}},s=new po({source:new ss(t.location.path,async e=>{l(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;l(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 Ui;return new ReadableStream({pull:async n=>{r||(s.init(await t()),r=!0);let o=e.requestSliceRange(a,0,65552);if(de(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=To(o,l),d=new Uint8Array(l);for(let e=0;e16)throw new Error("Invalid PKCS#7 padding. Incorrect key or corrupted data.");const t=d.subarray(0,l-e);n.enqueue(t),n.close(),i()}},cancel:()=>{i()}})})(new yo(s.source),async()=>{const t={stack:[],error:void 0,hasError:!1};try{const i=ks(t,await this.input._getSourceCached({path:e.keyUri,isRoot:!1},mo),!1),r=new yo(i.source),a=await r.requestSlice(0,Ri);if(!a)throw new Error("Invalid AES-128 key; expected at least 16 bytes of data.");return{key:To(a,Ri),iv:e.iv}}catch(i){t.error=i,t.hasError=!0}finally{ys(t)}},()=>{s.free()});r=new fs(n).ref()}else l(!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 qs)),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=be(this.inputCache,e=>e.age);l(-1!==e),this.inputCache.splice(e,1)}return s}async getLiveRefreshInterval(){return 0===this.getRemainingWaitTimeMs()&&await this.runUpdateSegments(),this.streamHasEnded?null:this.refreshInterval}}class Ss extends wi{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()=>{l(this.input._rootSource instanceof rs);const e=await this.input._reader.requestEntireFile();l(e);const t=Lo(e,e.length,{ignore:$a}),{rootPath:i}=this.input._rootSource,r=[],a=[];for(let l=1;l"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 u=e.attributes.get("video"),d=e.attributes.get("audio"),h=c.some(e=>$t.includes(li(e))),f=c.some(e=>Qt.includes(li(e)));if(null!==u&&!h){if(!s.includes(u))throw new Error(`Invalid M3U8 file; variant stream references video 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&&"video"===i.toLowerCase()});e:if(e){const t=e.attributes.get("uri");if(null===t)break e;const r=ke(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);l(null!==n),c.push(n)}}if(null!==d&&!f){if(!n.includes(d))throw new Error(`Invalid M3U8 file; variant stream references audio group "${d}" 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===d&&"audio"===i.toLowerCase()});e:if(e){const t=e.attributes.get("uri");if(null===t)break e;const r=ke(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);l(null!==n),c.push(n)}}c=[...new Set(c)];let m=null,p=null;const g=e.attributes.getAsNumber("bandwidth");l(null!==g);const k=e.attributes.getAsNumber("average-bandwidth"),y=e.attributes.get("name");for(const i of c){const o=li(i);if(null!==o)if($t.includes(o)){if(null!==m)throw new Error("Unsupported M3U8 file; multiple video codecs found in the CODECS attribute of a variant stream.");m=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:V,lineNumber:e.lineNumber,fullPath:e.fullPath,fullCodecString:m,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:xs(i.attributes),autoselect:xs(i.attributes)||Cs(i.attributes),languageCode:Bs(i.attributes.get("language")),lineNumber:i.lineNumber,fullPath:i.fullPath??e.fullPath,fullCodecString:p,pairingMask:1n<0?c:null}})}}}}return r})),c=[],u=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===V&&(t.languageCode=e.languageCode)):(e.id=c.length+1,c.push(e))};for(const l of o)for(const e of l)u(e);c.sort((e,t)=>e.lineNumber-t.lineNumber),this.trackBackings=[];for(const l of c)"video"===l.info.type?this.trackBackings.push(new Ps(l)):this.trackBackings.push(new Is(l));this.internalTracks=c})())}async getTrackBackings(){return await this.readMetadata(),l(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 Ts(this,e,i,null),this.segmentedInputs.push(t),t}async getMetadataTags(){return{}}async getMimeType(){return Na}dispose(){if(this.segmentedInputs){for(const e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}}class vs{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 Ps){for(const r of i)if(await r.getCodec()===this.getCodec()){t=r;break}}else{l(this instanceof Is);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{...Ee,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(){l(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 Ps extends vs{constructor(e){super(e)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return"video"}getCodec(){return li(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 Is extends vs{constructor(e){super(e)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return"audio"}getCodec(){return li(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 xs=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}".`)},Cs=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}".`)},Bs=e=>{if(null===e)return V;const t=e.split("-")[0];return t||V};class Es{constructor(){this._isIsobmff=!1}}class _s extends Es{constructor(){super(...arguments),this._isIsobmff=!0}async _getMajorBrand(e){let t=e._reader.requestSlice(0,12);if(de(t)&&(t=await t),!t)return null;t.skip(4);const i=Oo(t,4);return"ftyp"!==i&&"styp"!==i?null:Oo(t,4)}_createDemuxer(e){return new qi(e)}}class Rs extends _s{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(de(t)&&(t=await t),!t)return!1;let r=Bo(t),a=8;if(1===r){let t=e._reader.requestSlice(i+8,8);if(de(t)&&(t=await t),!t)return!1;r=Fo(t),a=16}if(r8)return!1;if(fr(i,r)!==sr.EBML)return!1;const a=pr(i);if("number"!==typeof a)return!1;let s=e._reader.requestSlice(i.filePos,a);if(de(s)&&(s=await s),!s)return!1;const n=i.filePos;for(;s.filePos<=n+a-2;){const e=gr(s);if(!e)break;const{id:i,size:r}=e,a=s.filePos;if(void 0===r)return!1;switch(i){case sr.EBMLVersion:if(1!==fr(s,r))return!1;break;case sr.EBMLReadVersion:if(1!==fr(s,r))return!1;break;case sr.DocType:if(kr(s,r)!==t)return!1;break;case sr.DocTypeVersion:if(fr(s,r)>4)return!1}s.filePos=a+r}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new jr(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}}class Ds extends As{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}}class Ms extends Es{async _canReadInput(e){let t=0;for(;;){let i=e._reader.requestSlice(t,Vo);if(de(i)&&(i=await i),!i)break;const r=$o(i);if(!r)break;t=i.filePos+r.size}const i=await Gr(e._reader,t,t+4096);if(!i)return!1;const r=i.header,a=mi(r.mpegVersionId,r.channel);let s=e._reader.requestSlice(i.startPos+a,4);if(de(s)&&(s=await s),!s)return!1;const n=Bo(s);if(n===hi||n===fi)return!0;t=i.startPos+i.header.totalSize;const o=await Gr(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 Qr(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}}class Ns extends Es{async _canReadInput(e){let t=e._reader.requestSlice(0,12);if(de(t)&&(t=await t),!t)return!1;const i=Oo(t,4);if("RIFF"!==i&&"RIFX"!==i&&"RF64"!==i)return!1;t.skip(4);return"WAVE"===Oo(t,4)}_createDemuxer(e){return new ha(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}}class Os extends Es{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return de(t)&&(t=await t),!!t&&"OggS"===Oo(t,4)}_createDemuxer(e){return new na(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}}class Ls extends Es{async _canReadInput(e){let t=0;for(;;){let i=e._reader.requestSlice(t,Vo);if(de(i)&&(i=await i),!i)break;const r=$o(i);if(!r)break;t=i.filePos+r.size}let i=e._reader.requestSlice(t,4);return de(i)&&(i=await i),!!i&&"fLaC"===Oo(i,4)}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new ba(e)}}class zs extends Es{async _canReadInput(e){let t=0;for(;;){let i=e._reader.requestSlice(t,Vo);if(de(i)&&(i=await i),!i)break;const r=$o(i);if(!r)break;t=i.filePos+r.size}let i=e._reader.requestSliceRange(t,7,9);if(de(i)&&(i=await i),!i)return!1;const r=pa(i);if(!r)return!1;if(t+=r.frameLength,i=e._reader.requestSliceRange(t,7,9),de(i)&&(i=await i),!i)return!1;const a=pa(i);return!!a&&(r.objectType===a.objectType&&r.samplingFrequencyIndex===a.samplingFrequencyIndex&&r.channelConfiguration===a.channelConfiguration)}_createDemuxer(e){return new ka(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}}class Us extends Es{async _canReadInput(e){let t=e._reader.requestSlice(0,205);if(de(t)&&(t=await t),!t)return!1;const i=To(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 Ca(e)}get name(){return"MPEG Transport Stream"}get mimeType(){return"video/MP2T"}}class qs extends Es{async _canReadInput(e){let t=e._reader.requestSlice(0,7);if(de(t)&&(t=await t),!t)return!1;if(!("#EXTM3U"===Oo(t,7)))return!1;if(!(e._rootSource instanceof rs))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 Ss(e)}get name(){return"HTTP Live Streaming (HLS)"}get mimeType(){return Na}}const Ws=new Rs,Hs=new Fs,Vs=new As,js=new Ds,Ks=new Ms,Xs=new Ns,$s=new Os,Gs=new zs,Qs=new Ls,Ys=new Us,Js=new qs,Zs=[Js,Ws,Hs,Vs,js,Xs,$s,Qs,Ks,Gs,Ys],en=[Js,Ws,Hs,Ks,Gs,Ys];var tn=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});pe();let rn=-1/0,an=-1/0,sn=null;"undefined"!==typeof FinalizationRegistry&&(sn=new FinalizationRegistry(e=>{const t=performance.now();"video"===e.type?(t-rn>=1e3&&(xe._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."),rn=t),"undefined"!==typeof VideoFrame&&e.data instanceof VideoFrame&&e.data.close()):(t-an>=1e3&&(xe._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."),an=t),"undefined"!==typeof AudioData&&e.data instanceof AudioData&&e.data.close())}));class nn{constructor(){this._referenceCount=0,this._lastAllocationBuffer=null}}const on=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],cn=new Set(on);class ln{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(J*this.timestamp)}get microsecondDuration(){return Math.trunc(J*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||!cn.has(t.format))throw new TypeError("init.format must be one of: "+on.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&&Te(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??bn(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?p(e):p(e).slice(),this._layout=i,this.colorSpace=new mn(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&&Te(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 mn(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&&Te(t.visibleRect,"init.visibleRect"),"undefined"!==typeof VideoFrame)return new ln(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*J),duration:Math.trunc((t.duration??0)*J)||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:ne(),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 mn({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else{if(!(e instanceof nn))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&&!on.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=we({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),sn?.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return l(null!==this._data),this._data instanceof nn?new ln(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):pn(this._data)?new ln(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):this._data instanceof Uint8Array?(l(this._layout),new ln(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 ln(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||(sn?.unregister(this),this._data instanceof nn?(this._data._referenceCount--,0===this._data._referenceCount&&this._data.close()):pn(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(yn(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(pn(this._data))return this._data.allocationSize(e);return Tn(this,e).allocationSize}async copyTo(e,t={}){if(!C(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(yn(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(l(null!==this._data),pn(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 nn)){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 ln))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{tn(i)}}}const i=Tn(this,t);l(this.format);const r=p(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)l(this._layout),l(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");l(e);const t=e.getImageData(0,0,this.codedWidth,this.codedHeight);s=[{data:p(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(d)}if(void 0!==t.format){const e=this.format.startsWith("RGB")!==t.format.startsWith("RGB"),a=this.format.includes("X")&&t.format.includes("A");if(e||a)for(let t=0;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 pn(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?(l(this._layout),new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,layout:this._layout,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,t,i,r,a,s,n,o,c){let l=0,u=0,d=this.displayWidth,h=this.displayHeight,f=0,m=0,p=this.displayWidth,g=this.displayHeight;if(void 0!==s?(l=t,u=i,d=r,h=a,f=s,m=n,void 0!==o?(p=o,g=c):(p=d,g=h)):(f=t,m=i,void 0!==r&&(p=r,g=a)),!("undefined"!==typeof CanvasRenderingContext2D&&e instanceof CanvasRenderingContext2D||"undefined"!==typeof OffscreenCanvasRenderingContext2D&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(l))throw new TypeError("sx must be a number.");if(!Number.isFinite(u))throw new TypeError("sy must be a number.");if(!Number.isFinite(d)||d<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(h)||h<0)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(f))throw new TypeError("dx must be a number.");if(!Number.isFinite(m))throw new TypeError("dy must be a number.");if(!Number.isFinite(p)||p<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(g)||g<0)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw new Error("VideoSample is closed.");({sx:l,sy:u,sWidth:d,sHeight:h}=this._rotateSourceRegion(l,u,d,h,this.rotation));const k=this.toCanvasImageSource();e.save();const y=f+p/2,b=m+g/2;e.translate(y,b),e.rotate(this.rotation*Math.PI/180);const w=this.rotation%180===0?1:p/g;e.scale(1/w,w),e.drawImage(k,l,u,d,h,-p/2,-g/2,p,g),e.restore()}drawWithFit(e,t){if(!("undefined"!==typeof CanvasRenderingContext2D&&e instanceof CanvasRenderingContext2D||"undefined"!==typeof OffscreenCanvasRenderingContext2D&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!t||"object"!==typeof t)throw new TypeError("options must be an object.");if(!["fill","contain","cover"].includes(t.fit))throw new TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");void 0!==t.crop&&kn(t.crop,"options.");const i=e.canvas.width,r=e.canvas.height,a=t.rotation??this.rotation,[s,n]=a%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let o,c,l,u,d=t.crop;d&&(d=gn(d,s,n));const{sx:h,sy:f,sWidth:m,sHeight:p}=this._rotateSourceRegion(t.crop?.left??0,t.crop?.top??0,t.crop?.width??s,t.crop?.height??n,a);if("fill"===t.fit)o=0,c=0,l=i,u=r;else{const[e,a]=t.crop?[t.crop.width,t.crop.height]:[s,n],d="contain"===t.fit?Math.min(i/e,r/a):Math.max(i/e,r/a);l=e*d,u=a*d,o=(i-l)/2,c=(r-u)/2}e.save();const g=a%180===0?1:l/u;e.translate(i/2,r/2),e.rotate(a*Math.PI/180),e.scale(1/g,g),e.translate(-i/2,-r/2),e.drawImage(this.toCanvasImageSource(),h,f,m,p,o,c,l,u),e.restore()}_rotateSourceRegion(e,t,i,r,a){return 90===a?[e,t,i,r]=[t,this.squarePixelHeight-e-i,r,i]:180===a?[e,t]=[this.squarePixelWidth-e-i,this.squarePixelHeight-t-r]:270===a&&([e,t,i,r]=[this.squarePixelWidth-t-r,e,r,i]),{sx:e,sy:t,sWidth:i,sHeight:r}}_drawWithFitAndMipmapping(e,t,i){const r=e.width,a=e.height,[s,n]=i.rotation%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],o=i.crop?i.crop.width:s,c=i.crop?i.crop.height:n;let l=0;2*r0?fn(u,d):{canvas:e,context:t,isNew:i.targetIsFresh};f.imageSmoothingQuality="high",i.fillBlack?(f.fillStyle="black",f.fillRect(0,0,u,d)):m||f.clearRect(0,0,u,d),this.drawWithFit(f,{fit:i.fit,rotation:i.rotation,crop:i.crop}),f.globalCompositeOperation="copy";for(let p=l;p>1;p--){const e=r*2**p,t=a*2**p;f.drawImage(h,0,0,e,t,0,0,e/2,t/2)}f.globalCompositeOperation="source-over",l>0&&(t.imageSmoothingQuality="high",t.globalCompositeOperation="copy",t.drawImage(h,0,0,2*r,2*a,0,0,r,a),t.globalCompositeOperation="source-over")}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(l(null!==this._data),this._data instanceof nn||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&&kn(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=u(this.rotation+(e.rotate??0)),[i,r]=t%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let a=e.crop;a&&(a=gn(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=K(c,e.roundDimensionsTo??1),l=K(l,e.roundDimensionsTo??1);const d={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 u of un){let e=u(this,d);if(de(e)&&(e=await e),null!==e)return e}const{canvas:h,context:f,isNew:m}=fn(d.width,d.height);return this._drawWithFitAndMipmapping(h,f,{fit:d.fit,rotation:d.rotation,crop:d.crop,targetIsFresh:m,fillBlack:"discard"===d.alpha}),new ln(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 un=[],dn=[];let hn=0;const fn=(e,t)=>{for(const a of dn)if(a.canvas.width===e&&a.canvas.height===t)return a.age=hn++,{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 dn.length>=3&&dn.splice(be(dn,e=>e.age),1),dn.push({canvas:i,context:r,age:hn++}),{canvas:i,context:r,isNew:!0}};class mn{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(b);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(T);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(v);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 pn=e=>"undefined"!==typeof VideoFrame&&e instanceof VideoFrame,gn=(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 l(s>=0),l(n>=0),{left:r,top:a,width:s,height:n}},kn=(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.")},yn=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.")}},bn=(e,t,i)=>{const r=wn(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},wn=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:z(e),l(!1)}},Tn=(e,t)=>{const i={left:0,top:0,width:e.codedWidth,height:e.codedHeight},r=t.rect,a=Sn(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 Pn(a,n,s)},Sn=(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(!vn(a,s))throw new TypeError("visibleRect alignment is invalid for the format.");return s},vn=(e,t)=>{if(null===e)return!0;const i=wn(e);for(let r=0;r{const r=wn(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(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(e?.timestamp))throw new TypeError("init.timestamp must be a number.");const t=e.data.byteLength/(Bn(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*Bn(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=Bn(t),s=En(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(!C(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&&!In.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,u=this.numberOfChannels,d=a??0;if(d>=c)throw new RangeError("frameOffset out of range");const h=void 0!==r?r:c-d;if(h>c-d)throw new RangeError("frameCount out of range");const f=Bn(o),m=En(o);if(m&&s>=u)throw new RangeError("planeIndex out of range");if(!m&&0!==s)throw new RangeError("planeIndex out of range");const p=(m?h:h*u)*f;if(e.byteLength2&&o!==n)return void An(this._data,k,n,o,u,s,d,h);try{return void this._data.copyTo(e,{planeIndex:s,frameOffset:d,frameCount:h,format:o})}catch(P){if("f32-planar"===o)throw P;n="f32-planar"}}const b=_n(n),w=Bn(n),T=En(n);let S;if(this._data instanceof xn){const e=e=>{const t=this._data.getDataPlane(e);if(!(t instanceof Uint8Array))throw new TypeError("getDataPlane() must return a Uint8Array.");const i=c*w*(T?1:u);if(t.byteLength!==i)throw new TypeError(`Data plane ${e} has invalid size. Expected exactly ${i} bytes, got ${t.byteLength} bytes.`);return t};if(T)if(m)S=e(s),s=0;else{S=new Uint8Array(c*w*u);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 Cn({data:a,format:this.format,sampleRate:this.sampleRate,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp+e/this.sampleRate})}close(){this._closed||(sn?.unregister(this),this._data instanceof xn?(this._data._referenceCount--,0===this._data._referenceCount&&this._data.close()):Fn(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 xn?this._createAudioDataFromData():Fn(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(En(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")}},En=e=>{switch(e){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},_n=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)}},Rn=e=>{switch(e){case"u8":case"u8-planar":return(e,t,i)=>e.setUint8(t,H(127.5*(i+1),0,255));case"s16":case"s16-planar":return(e,t,i)=>e.setInt16(t,H(Math.round(32767*i),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,i)=>e.setInt32(t,H(Math.round(2147483647*i),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,i)=>e.setFloat32(t,i,!0)}},Fn=e=>"undefined"!==typeof AudioData&&e instanceof AudioData,An=(e,t,i,r,a,s,n,o)=>{const c=_n(i),l=Rn(r),u=Bn(i),d=Bn(r),h=En(i);if(En(r))if(h){const r=new ArrayBuffer(o*u),a=g(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.")},On=e=>{if(!ge(e))throw new TypeError("timestamp must be a number.")},Ln=(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 zn{constructor(e){if(!(e instanceof eo))throw new TypeError("track must be an InputTrack.");this._track=e}async getFirstPacket(e={}){if(Nn(e),this._track.input._disposed)throw new ko;return Ln(this._track,this._track._backing.getFirstPacket(e),e)}async getFirstKeyPacket(e={}){Nn(e);const t=await this.getFirstPacket(e);return t?"key"===t.type?t:this.getNextKeyPacket(t,e):null}async getPacket(e,t={}){if(On(e),Nn(t),this._track.input._disposed)throw new ko;return Ln(this._track,this._track._backing.getPacket(e,t),t)}async getNextPacket(e,t={}){if(!(e instanceof Si))throw new TypeError("packet must be an EncodedPacket.");if(Nn(t),this._track.input._disposed)throw new ko;return Ln(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(On(e),Nn(t),this._track.input._disposed)throw new ko;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);const i=await this._track._backing.getKeyPacket(e,t);if(!i)return i;l("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 Si))throw new TypeError("packet must be an EncodedPacket.");if(Nn(t),this._track.input._disposed)throw new ko;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);const i=await this._track._backing.getNextKeyPacket(e,t);if(!i)return i;l("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 Si))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 Si))throw new TypeError("endPacket must be an EncodedPacket.");if(Nn(i),this._track.input._disposed)throw new ko;const r=[];let{promise:a,resolve:s}=M(),{promise:n,resolve:o}=M(),c=!1,l=!1,u=null,d=!1;const h=[],f=()=>Math.max(2,h.length);(async()=>{let u=e??await this.getFirstPacket(i);for(;u&&!l&&!this._track.input._disposed&&!(t&&u.sequenceNumber>=t?.sequenceNumber);)r.length>f()?(({promise:n,resolve:o}=M()),await n):(r.push(u),s(),({promise:a,resolve:s}=M()),u=await this.getNextPacket(u,i));c=!0,s()})().catch(e=>{d||(u=e,d=!0,s())});const m=this._track;return{async next(){for(;;){if(m.input._disposed)throw new ko;if(l)return{value:void 0,done:!0};if(d)throw u;if(r.length>0){const e=r.shift(),t=performance.now();for(h.push(t);h.length>0&&t-h[0]>=1e3;)h.shift();return o(),{value:e,done:!1}}if(c)return{value:void 0,done:!0};await a}},return:async()=>(l=!0,o(),s(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}}class Un{constructor(e,t){this.onSample=e,this.onError=t}}class qn{mediaSamplesInRange(e=-1/0,t=1/0,i){On(e),On(t);const r=[];let a=!1,s=null,{promise:n,resolve:o}=M(),{promise:c,resolve:l}=M(),u=!1,d=!1,h=!1,f=null,m=null,p=!1;const g={...i,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{f=await this._createDecoder(i=>{l(),i.timestamp>=t&&(d=!0),d?i.close():(s&&(i.timestamp>e?(r.push(s),a=!0):s.close()),i.timestamp>=e&&(r.push(i),a=!0),s=a?null:i,r.length>0&&(o(),({promise:n,resolve:o}=M())))},e=>{p||(m=e,p=!0,o())});const i=this._createPacketSink(),k=await i.getKeyPacket(e,g)??await i.getFirstKeyPacket(g);let y=k;const b=i.packets(k??void 0,void 0,g);for(await b.next();y&&!d&&!this._track.input._disposed;){const e=Wn(r.length);if(r.length+f.getDecodeQueueSize()>e){({promise:c,resolve:l}=M()),await c;continue}f.decode(y);const t=await b.next();if(t.done)break;y=t.value}await b.return(),h||this._track.input._disposed||await f.flush(),!a&&s&&r.push(s),u=!0,o()})().catch(e=>{p||(m=e,p=!0,o())}).finally(()=>{f?.close()});const k=this._track,y=()=>{s?.close();for(const e of r)e.close()};return{async next(){for(;;){if(k.input._disposed)throw h=!0,d=!0,y(),new ko;if(h)return{value:void 0,done:!0};if(p)throw h=!0,d=!0,y(),m;if(r.length>0){const e=r.shift();return l(),{value:e,done:!1}}if(u)return{value:void 0,done:!0};await n}},return:async()=>(h=!0,d=!0,l(),o(),y(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e,t){(e=>{if(!(Symbol.iterator in e)&&!(Symbol.asyncIterator in e))throw new TypeError("Argument must be an iterable or async iterable.")})(e);const i=async function*(e){Symbol.iterator in e?yield*e[Symbol.iterator]():yield*e[Symbol.asyncIterator]()}(e),r=[],a=[];let{promise:s,resolve:n}=M(),{promise:o,resolve:c}=M(),u=!1,d=!1,h=null,f=null,m=!1;const p=e=>{a.push(e),n(),({promise:s,resolve:n}=M())},g={...t,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{h=await this._createDecoder(e=>{if(c(),d)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{m||(f=e,m=!0,n())});const e=this._createPacketSink();let t=null,s=null,k=-1;const y=async()=>{l(s),l(h);let t=s;for(h.decode(t);t.sequenceNumberi&&!d;)({promise:o,resolve:c}=M()),await o;if(d)break;const r=await e.getNextPacket(t,g);l(r),h.decode(r),t=r}k=-1},b=async()=>{l(h),await h.flush();for(let e=0;e{m||(f=e,m=!0,n())}).finally(()=>{h?.close()});const k=this._track,y=()=>{for(const e of a)e?.close()};return{async next(){for(;;){if(k.input._disposed)throw d=!0,y(),new ko;if(d)return{value:void 0,done:!0};if(m)throw d=!0,y(),f;if(a.length>0){const e=a.shift();return l(void 0!==e),c(),{value:e,done:!1}}if(u)return{value:void 0,done:!0};await s}},return:async()=>(d=!0,c(),n(),y(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}}const Wn=e=>0===e?40:8;class Hn extends Un{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 ie,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=Dn.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 ln))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();l(void 0!==t),this.mergeAlpha(e,t)}else this.colorQueue.push(e)};if(ce()){if("avc"===i&&this.decoderConfig.description){const e=Je(p(this.decoderConfig.description));if(e&&e.sequenceParameterSets.length>0){const t=et(e.sequenceParameterSets[0]);t&&(0===t.frameMbsOnlyFlag&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"}),0!==t.maxDecFrameBuffering&&1!==t.bitstreamRestrictionFlag&&(e.sequenceParameterSets[0]=it(t),this.decoderConfig={...this.decoderConfig,description:Ye(e)}))}}I(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:(l(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(l(this.decoder),ae()||D(this.inputTimestamps,e.timestamp,e=>e),ce()&&0===this.currentPacketIndex)if("avc"===this.codec){const t=[];let i=!1;for(const a of Ve(e.data,this.decoderConfig)){const r=je(e.data[a.offset]);if(i||(i=r>=1&&r<=5),r===Le.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&p(t.description)[4];return Ge(e,i+1)}return $e(e)})(t,this.decoderConfig);e=new Si(r,e.type,e.timestamp,e.duration)}else if("hevc"===this.codec){const t=gt(e.data,this.decoderConfig);t&&(e=new Si(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 jn),!this.alphaDecoder){const e=e=>{if(this.colorQueue.length>0){const t=this.colorQueue.shift();l(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();l(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=Pt(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 rt(e,this.decoderConfig)){const i=at(e[t.offset]);if(i===Ue.RASL_N||i===Ue.RASL_R)return!0}return!1}sampleHandler(e){if(ae()){if(this.sampleQueue.length>0&&e.timestamp>=d(this.sampleQueue).timestamp){for(const e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}D(this.sampleQueue,e,e=>e.timestamp)}else{const t=this.inputTimestamps.shift();l(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=M();this.mergeAlphaPromises.push(i.promise);const r={sample:null};this.finalSamples.push(r);try{if(t){l(this.merger);const i=await this.merger.merge(e,t);r.sample=new ln(i)}else r.sample=new ln(e);for(;this.finalSamples.length>0&&null!==this.finalSamples[0].sample;){const e=this.finalSamples.shift();this.sampleHandler(e.sample)}}catch(a){N(this.finalSamples,r),this.onError(a)}finally{N(this.mergeAlphaPromises,i.promise),i.resolve()}}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(l(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),ae()){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()):(l(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 Vn=null;class jn{constructor(){this.workers=[],this.nextWorkerIndex=0,this.pendingRequests=new Map,this.nextRequestId=0}merge(e,t){if(0===this.workers.length){if(!Vn){const e=new Blob([`(${Kn.toString()})()`],{type:"application/javascript"});Vn=URL.createObjectURL(e)}const e=H(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=M();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 Kn=()=>{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 d=r*a,h=d*c,f=l*u*c,m=new Uint8Array(h+2*f+d*c);await e.copyTo(m);const p=await o(t,r,a,c),g=h+2*f;m.set(p,g);const k={format:i.slice(0,4)+"A"+i.slice(4),codedWidth:r,codedHeight:a,timestamp:e.timestamp,duration:e.duration??void 0,transfer:[m.buffer]};return new VideoFrame(m,k)},n=async(e,i)=>{const r=e.visibleRect?.width??e.codedWidth,a=e.visibleRect?.height??e.codedHeight,s=r*a,n=Math.ceil(r/2)*Math.ceil(a/2),c=e.allocationSize();t&&t.byteLength===c||(t=new Uint8Array(c)),await e.copyTo(t);const l=new Uint8Array(s+2*n+s);l.set(t.subarray(0,s),0);const u=s,d=s+n,h=s;for(let o=0;o{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 $n extends qn{constructor(e,t={}){if(!(e instanceof ro))throw new TypeError("videoTrack must be an InputVideoTrack.");Xn(t),super(),this._track=e,this._decoderOptions=t}async _createDecoder(e,t){if(!(await this._track.canDecode())){if("undefined"===typeof VideoDecoder)throw new Error(le("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 l(i&&a),a={...a,hardwareAcceleration:this._decoderOptions.hardwareAcceleration,optimizeForLatency:this._decoderOptions.optimizeForLatency},new Hn(e,t,i,a,r,s)}_createPacketSink(){return new zn(this._track)}async getSample(e,t={}){On(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 Gn{constructor(e,t={}){if(this._rotation=0,this._initPromise=null,this._nextCanvasIndex=0,!(e instanceof ro))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&&kn(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&&Xn(t.decoderOptions),this._videoTrack=e,this._alpha=t.alpha??!1,this._options=t,this._fit=t.fit??"fill",this._videoSampleSink=new $n(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=gn(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||ne()});l(s),e._drawWithFitAndMipmapping(r,s,{fit:this._fit,rotation:this._rotation,crop:this._crop,targetIsFresh:a,fillBlack:!this._alpha&&ne()});const n={canvas:r,timestamp:e.timestamp,duration:e.duration};return e.close(),n}async getCanvas(e,t){On(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*W(this._videoSampleSink.samples(e,t,i),e=>this._videoSampleToWrappedCanvas(e))}async*canvasesAtTimestamps(e,t){await this._ensureInit(),yield*W(this._videoSampleSink.samplesAtTimestamps(e,t),e=>e&&this._videoSampleToWrappedCanvas(e))}}class Qn extends Un{constructor(e,t,i,r){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new ie,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=Mn.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 Cn))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 Cn(e))}catch(t){this.onError(t)}},error:t=>{t.stack=e,this.onError(t)}}),this.decoder.configure(r)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(l(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--)):(l(this.decoder),this.expectedFirstTimestamp??(this.expectedFirstTimestamp=e.timestamp),this.decoder.decode(e.toEncodedAudioChunk()))}async flush(){this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(l(this.decoder),await this.decoder.flush()),this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(l(this.decoder),"closed"!==this.decoder.state&&this.decoder.close())}}class Yn extends Un{constructor(e,t,i){super(e,t),this.decoderConfig=i,this.currentTimestamp=null,l(Gt.includes(i.codec)),this.codec=i.codec;const{dataType:r,sampleSize:a,littleEndian:s}=ci(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):l(!1);break;case 3:"unsigned"===r?this.readInputValue=(e,t)=>U(e,t,s)-2**23:"signed"===r?this.readInputValue=(e,t)=>((e,t,i)=>U(e,t,i)<<8>>8)(e,t,s):l(!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):l(!1);break;case 8:"float"===r?this.readInputValue=(e,t)=>e.getFloat64(t,s):l(!1);break;default:z(a),l(!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:z(a),l(!1)}}getDecodeQueueSize(){return 0}decode(e){const t=g(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 Cn({format:this.outputFormat,data:a,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:i,timestamp:o});this.onSample(c)}async flush(){}close(){}}class Jn extends qn{constructor(e){if(!(e instanceof ao))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(le("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 l(i&&r),Gt.includes(r.codec)?new Yn(e,t,r):new Qn(e,t,i,r)}_createPacketSink(){return new zn(this._track)}async getSample(e,t={}){On(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 Zn{constructor(e){if(!(e instanceof ao))throw new TypeError("audioTrack must be an InputAudioTrack.");this._audioSampleSink=new Jn(e)}_audioSampleToWrappedArrayBuffer(e){const t={buffer:e.toAudioBuffer(),timestamp:e.timestamp,duration:e.duration};return e.close(),t}async getBuffer(e,t){On(e);const i=await this._audioSampleSink.getSample(e,t);return i&&this._audioSampleToWrappedArrayBuffer(i)}buffers(e,t,i){return W(this._audioSampleSink.samples(e,t,i),e=>this._audioSampleToWrappedArrayBuffer(e))}buffersAtTimestamps(e,t){return W(this._audioSampleSink.samplesAtTimestamps(e,t),e=>e&&this._audioSampleToWrappedArrayBuffer(e))}}class eo{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof ro}isAudioTrack(){return this instanceof ao}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}async getInternalCodecId(){return this._backing.getInternalCodecId()}get internalCodecId(){return to(this._backing.getInternalCodecId(),"internalCodecId","getInternalCodecId")}async getLanguageCode(){return this._backing.getLanguageCode()}get languageCode(){return to(this._backing.getLanguageCode(),"languageCode","getLanguageCode")}async getName(){return this._backing.getName()}get name(){return to(this._backing.getName(),"name","getName")}async getTimeResolution(){return this._backing.getTimeResolution()}get timeResolution(){return to(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 to(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 X((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 zn(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 eo))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(co({filter:e=>e.canBePairedWith(this)},e))}async getPairableVideoTracks(e){return this.input.getVideoTracks(co({filter:e=>e.canBePairedWith(this)},e))}async getPairableAudioTracks(e){return this.input.getAudioTracks(co({filter:e=>e.canBePairedWith(this)},e))}async getPrimaryPairableVideoTrack(e){return this.input.getPrimaryVideoTrack(co({filter:e=>e.canBePairedWith(this)},e))}async getPrimaryPairableAudioTrack(e){return this.input.getPrimaryAudioTrack(co({filter:e=>e.canBePairedWith(this)},e))}async hasPairableTrack(e){e&&(e=io(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=io(e)),this.hasPairableTrack(async t=>t.isVideoTrack()&&(!e||await e(t)))}hasPairableAudioTrack(e){return e&&(e=io(e)),this.hasPairableTrack(async t=>t.isAudioTrack()&&(!e||await e(t)))}}const to=(e,t,i)=>{if(de(e))throw new Error(`'${t}' is deprecated and not available synchronously for this track. Use the preferred '${i}()' instead.`);return e},io=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 de(r)?r.then(i):i(r)}:void 0};class ro extends eo{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 to(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 to(this._backing.getCodedWidth(),"codedWidth","getCodedWidth")}async getCodedHeight(){return this._backing.getCodedHeight()}get codedHeight(){return to(this._backing.getCodedHeight(),"codedHeight","getCodedHeight")}async getRotation(){return this._backing.getRotation()}get rotation(){return to(this._backing.getRotation(),"rotation","getRotation")}async getSquarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelWidth(){return to(this._backing.getSquarePixelWidth(),"squarePixelWidth","getSquarePixelWidth")}async getSquarePixelHeight(){return this._backing.getSquarePixelHeight()}get squarePixelHeight(){return to(this._backing.getSquarePixelHeight(),"squarePixelHeight","getSquarePixelHeight")}async getPixelAspectRatio(){return this._pixelAspectRatioCache??(this._pixelAspectRatioCache=we({num:await this.getSquarePixelWidth()*await this.getCodedHeight(),den:await this.getSquarePixelHeight()*await this.getCodedWidth()}))}get pixelAspectRatio(){return this._pixelAspectRatioCache??(this._pixelAspectRatioCache=we({num:to(this._backing.getSquarePixelWidth(),"pixelAspectRatio","getPixelAspectRatio")*to(this._backing.getCodedHeight(),"pixelAspectRatio","getPixelAspectRatio"),den:to(this._backing.getSquarePixelHeight(),"pixelAspectRatio","getPixelAspectRatio")*to(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=to(e,"displayWidth","getDisplayWidth");if(null!==t)return t}const t=to(this._backing.getRotation(),"displayWidth","getDisplayWidth")%180===0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight();return to(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=to(e,"displayHeight","getDisplayHeight");if(null!==t)return t}const t=to(this._backing.getRotation(),"displayHeight","getDisplayHeight")%180===0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth();return to(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(l(null!==t),Dn.some(i=>i.supports(t,e)))return!0;if("undefined"===typeof VideoDecoder)return!1;return!0===(await VideoDecoder.isConfigSupported(e)).supported}catch(e){return xe._error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof Si))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 l(i),Pt(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&&(!ge(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 zn(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=(d/T+d/S)/2;return{underlyingFrameRate:u,bestGuessFrameRate:null!==u?u:fo(P),minFrameRate:d/p,maxFrameRate:d/m,averageFrameRate:d*k/g,medianFrameRate:P,frameRateIsConstant:null!==u&&1===m&&1===p,probedPacketCount:n}}}class ao extends eo{constructor(e,t){super(e,t),this._backing=t}get type(){return"audio"}async getCodec(){return this._backing.getCodec()}get codec(){return to(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){return await(this._backing.getHasOnlyKeyPackets?.())??!0}async getNumberOfChannels(){return this._backing.getNumberOfChannels()}get numberOfChannels(){return to(this._backing.getNumberOfChannels(),"numberOfChannels","getNumberOfChannels")}async getSampleRate(){return this._backing.getSampleRate()}get sampleRate(){return to(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(l(null!==t),Mn.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 xe._error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof Si))throw new TypeError("packet must be an EncodedPacket.");return null===await this.getCodec()?null:"key"}}const so=e=>-(e??-1/0),no=e=>-e,oo=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 de(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 de(r)?r.then(i):i(r)}:void 0}},co=(e,t)=>({filter:e?.filter||t?.filter?i=>{const r=e?.filter?.(i)??!0,a=e=>!1!==e&&(t?.filter?.(i)??!0);return de(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 de(r)||de(a)?Promise.all([r,a]).then(([e,t])=>s(e,t)):s(r,a)}:void 0}),lo=async(e,t)=>{let i=e;if(t?.filter){const r=e.map(e=>t.filter(e));if(r.some(e=>de(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=>de(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)},uo=(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 d=1/Math.min(u,1e3),h=Math.max(Number.EPSILON,o-d),f=o+d,m=t/f,p=t/h,g=t/o;let k=null,y=1/0;for(const T of a){if(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 Es)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof ts||e.source instanceof is))throw new TypeError("options.source must be a Source or SourceRef.");if(e.source instanceof ts&&e.source._disposed)throw new TypeError("options.source must not be a disposed Source.");if(void 0!==e.initInput&&!(e.initInput instanceof po))throw new TypeError("options.initInput, when provided, must be an Input.");void 0!==e.formatOptions&&((e,t)=>{if(!e||"object"!==typeof e)throw new TypeError(`${t}, when provided, must be an object.`);if(void 0!==e.isobmff){if(!e.isobmff||"object"!==typeof e.isobmff)throw new TypeError(`${t}.isobmff, when provided, must be an object.`);if(void 0!==e.isobmff.resolveKeyId&&"function"!==typeof e.isobmff.resolveKeyId)throw new TypeError(`${t}.isobmff.resolveKeyId, when provided, must be a function.`)}if(void 0!==e.hls){if(!e.hls||"object"!==typeof e.hls)throw new TypeError(`${t}.hls, when provided, must be an object.`);if(void 0!==e.hls.offsetTimestampsByDateTime&&"boolean"!==typeof e.hls.offsetTimestampsByDateTime)throw new TypeError(`${t}.hls.offsetTimestampsByDateTime, when provided, must be a boolean.`)}})(e.formatOptions,"formatOptions"),this._formats=e.formats,this._initInput=e.initInput??null,this._formatOptions=e.formatOptions??{},e.source instanceof ts?this._rootRef=e.source.ref():this._rootRef=e.source,this._sourceRefs.push(this._rootRef)}get _rootSource(){return this._rootRef.source}async _getSourceUncached(e){l(this._rootSource instanceof rs);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&&as(i.request,e));if(i)return i.age++,Promise.resolve(i.sourceRef.source.ref());const r=this._sourceCachePromises.find(i=>i.cacheGroup===t&&as(i.request,e));if(r)return r.promise.then(e=>e.sourceRef.source.ref());const a=(async()=>{const i=await this._getSourceUncached(e);if(ye(this._sourceCache,e=>e.cacheGroup===t&&1===e.sourceRef.source._refCount)>=4){const e=be(this._sourceCache,e=>e.cacheGroup===t&&1===e.sourceRef.source._refCount?e.age:1/0);l(-1!==e);const i=this._sourceCache[e];this._sourceCache.splice(e,1),i.sourceRef.free(),N(this._sourceRefs,i.sourceRef)}this._sourceRefs.push(i);const r=this._sourceCachePromises.findIndex(t=>t.request===e);l(-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 yo(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 go})())}get source(){return this._rootSource}async getFormat(){return await this._getDemuxer(),l(this._format),this._format}async canRead(){try{return await this._getDemuxer(),!0}catch(e){if(e instanceof go)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=oo(e));const t=(await this._getTrackBackings()).map(e=>this._wrapBackingAsTrack(e));return lo(t,e)}async getVideoTracks(e){e&&(e=oo(e));const t=(await this.getTracks()).filter(e=>e.isVideoTrack());return lo(t,e)}async getAudioTracks(e){e&&(e=oo(e));const t=(await this.getTracks()).filter(e=>e.isAudioTrack());return lo(t,e)}async getPrimaryVideoTrack(e){e&&(e=oo(e));const t=co(e,{sortBy:async e=>[no((await e.getDisposition()).default),no(await e.hasPairableAudioTrack()),no(!(await e.hasOnlyKeyPackets())),so(await e.getBitrate())]});return(await this.getVideoTracks(t))[0]??null}async getPrimaryAudioTrack(e){e&&(e=oo(e));const t=await this.getPrimaryVideoTrack(),i=co(e,{sortBy:async e=>[no(!t||e.canBePairedWith(t)),no((await e.getDisposition()).default),so(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 ro(this,e):new ao(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 go extends Error{constructor(e="Input has an unsupported or unrecognizable format."){super(e),this.name="UnsupportedInputFormatError"}}class ko extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}}class yo{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 ko;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 bo(t,g(t),0,e,e)}const i=e+t,r=this.source._read(e,i,0,es);return de(r)?r.then(t=>t?new bo(t.bytes,t.view,t.offset,e,i):null):r?new bo(r.bytes,r.view,r.offset,e,i):null}requestSliceRange(e,t,i){if(this.source._disposed)throw new ko;if(e<0)return null;if(null!==this.fileSizeNonStrict)return this.requestSlice(e,H(this.fileSizeNonStrict-e,t,i));{const r=this.requestSlice(e,i),a=r=>r||(l(null!==this.fileSizeNonStrict),this.requestSlice(e,H(this.fileSizeNonStrict-e,t,i)));return de(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(de(i)&&(i=await i),!i||0===i.length)break;const r=To(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 bo(i,g(i),0,0,t)})()}}class bo{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 bo(e,g(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 bo(this.bytes,this.view,this.offset,e,e+t)}}const wo=(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.`)},To=(e,t)=>{wo(e,t);const i=e.bytes.subarray(e.bufferPos,e.bufferPos+t);return e.bufferPos+=t,i},So=e=>(wo(e,1),e.view.getUint8(e.bufferPos++)),vo=(e,t)=>{wo(e,2);const i=e.view.getUint16(e.bufferPos,t);return e.bufferPos+=2,i},Po=e=>{wo(e,2);const t=e.view.getUint16(e.bufferPos,!1);return e.bufferPos+=2,t},Io=e=>{wo(e,3);const t=U(e.view,e.bufferPos,!1);return e.bufferPos+=3,t},xo=e=>{wo(e,2);const t=e.view.getInt16(e.bufferPos,!1);return e.bufferPos+=2,t},Co=(e,t)=>{wo(e,4);const i=e.view.getUint32(e.bufferPos,t);return e.bufferPos+=4,i},Bo=e=>{wo(e,4);const t=e.view.getUint32(e.bufferPos,!1);return e.bufferPos+=4,t},Eo=e=>{wo(e,4);const t=e.view.getUint32(e.bufferPos,!0);return e.bufferPos+=4,t},_o=e=>{wo(e,4);const t=e.view.getInt32(e.bufferPos,!1);return e.bufferPos+=4,t},Ro=(e,t)=>{let i,r;return t?(i=Co(e,!0),r=Co(e,!0)):(r=Co(e,!1),i=Co(e,!1)),4294967296*r+i},Fo=e=>4294967296*Bo(e)+Bo(e),Ao=e=>4294967296*_o(e)+Bo(e),Do=e=>{const t=Eo(e),i=(e=>{wo(e,4);const t=e.view.getInt32(e.bufferPos,!0);return e.bufferPos+=4,t})(e);return 4294967296*i+t},Mo=e=>{wo(e,4);const t=e.view.getFloat32(e.bufferPos,!1);return e.bufferPos+=4,t},No=e=>{wo(e,8);const t=e.view.getFloat64(e.bufferPos,!1);return e.bufferPos+=8,t},Oo=(e,t)=>{wo(e,t);let i="";for(let r=0;rk.decode(To(e,t)).split("\n").map(e=>e.trim()).filter(e=>e.length>0&&!i?.ignore?.(e));var zo,Uo,qo,Wo;(Uo=zo||(zo={}))[Uo.Unsynchronisation=128]="Unsynchronisation",Uo[Uo.ExtendedHeader=64]="ExtendedHeader",Uo[Uo.ExperimentalIndicator=32]="ExperimentalIndicator",Uo[Uo.Footer=16]="Footer",(Wo=qo||(qo={}))[Wo.ISO_8859_1=0]="ISO_8859_1",Wo[Wo.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",Wo[Wo.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",Wo[Wo.UTF_8=3]="UTF_8";const Ho=128,Vo=10,jo=["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"],Ko=(e,t)=>{var i;const r=e.filePos;t.raw??(t.raw={}),(i=t.raw).TAG??(i.TAG=To(e,Ho-3)),e.filePos=r;const a=Xo(e,30);a&&(t.title??(t.title=a));const s=Xo(e,30);s&&(t.artist??(t.artist=s));const n=Xo(e,30);n&&(t.album??(t.album=n));const o=Xo(e,4),c=Number.parseInt(o,10);Number.isInteger(c)&&c>0&&(t.date??(t.date=new Date(String(c))));const l=To(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=Xo(e,28),e.skip(2)}else e.skip(-30),u=Xo(e,30);u&&(t.comment??(t.comment=u));const d=So(e);d{const i=To(e,t),r=he(i.indexOf(0),i.length),a=i.subarray(0,r);let s="";for(let n=0;n{const t=e.filePos,i=Oo(e,3),r=So(e),a=So(e),s=So(e),n=Bo(e);if("ID3"!==i||255===r||255===a||0!==(2155905152&n))return e.filePos=t,null;let o=gi(n);return s&zo.Footer&&(o+=Vo),{majorVersion:r,revision:a,flags:s,size:o}},Go=(e,t,i)=>{var r,a,s,n,o;if(![2,3,4].includes(t.majorVersion))return void xe._warn(`Unsupported ID3v2 major version: ${t.majorVersion}`);const c=t.flags&zo.Footer?t.size-Vo:t.size,l=To(e,c),u=new Qo(t,l);if(t.flags&zo.Unsynchronisation&&3===t.majorVersion&&u.ununsynchronizeAll(),t.flags&zo.ExtendedHeader){const e=u.readU32();3===t.majorVersion?u.pos+=e:u.pos+=e-4}for(;u.pos<=u.bytes.length-u.frameHeaderSize();){const e=u.readId3V2Frame();if(!e)break;const c=u.pos,l=u.pos+e.size;let d=!1,h=!1,f=!1;if(3===t.majorVersion?(d=!!(64&e.flags),h=!!(128&e.flags)):4===t.majorVersion&&(d=!!(4&e.flags),h=!!(8&e.flags),f=!!(2&e.flags)||!!(t.flags&zo.Unsynchronisation)),d)xe._warn(`Skipping encrypted ID3v2 frame ${e.id}`),u.pos=l;else if(h)xe._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!==jo[e]){i.genre??(i.genre=jo[e]);break}}if(t=/^\d+$/.exec(e),t){const e=Number.parseInt(t[0]);if(void 0!==jo[e]){i.genre??(i.genre=jo[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 Qo{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:gi(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 qo.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=he(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=he(r.findIndex(e=>0===e),r.length);return this.pos=i+Math.min(e+1,r.length),k.decode(r.subarray(0,e))}case qo.UTF_16_BE_NO_BOM:{const e=new TextDecoder("utf-16be"),t=he(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 qo.UTF_8:{const e=he(r.findIndex(e=>0===e),r.length);return this.pos=i+Math.min(e+1,r.length),k.decode(r.subarray(0,e))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";const t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}}class Yo{constructor(e){this.events=e,this.input=null,this.audioSink=null,this.audioIterator=null,this.audioContext=null,this.gainNode=null,this.audioContextStartTime=0,this.playbackTimeAtStart=0,this.latestScheduledEndTime=0,this.duration=Number.NaN,this.paused=!0,this.volume=.7,this.muted=!1,this.playbackRate=1,this.asyncId=0,this.queuedNodes=new Set}get currentTime(){return this.paused?this.playbackTimeAtStart:(this.audioContext.currentTime-this.audioContextStartTime)*this.playbackRate+this.playbackTimeAtStart}ensureAudioContext(e){if(this.audioContext)return;const t=window.AudioContext||window.webkitAudioContext;try{this.audioContext=new t({sampleRate:e})}catch{this.audioContext=new t}this.gainNode=this.audioContext.createGain(),this.gainNode.connect(this.audioContext.destination),this.updateGain()}updateGain(){if(!this.gainNode)return;const e=this.muted?0:this.volume;this.gainNode.gain.value=e*e}stopQueuedNodes(){this.queuedNodes.forEach(e=>e.stop()),this.queuedNodes.clear()}async stopIterator(){await(this.audioIterator?.return()),this.audioIterator=null}handleNoAudioTrack(){this.audioSink=null,this.ensureAudioContext()}async load(e,t){++this.asyncId,await this.stopIterator(),this.stopQueuedNodes(),this.paused=!0,this.playbackTimeAtStart=0,this.audioContextStartTime=0;const{input:i,audioTrack:r,duration:a}=e;return this.input=i,this.duration=a,r?null!==r.codec&&await r.canDecode()?(this.ensureAudioContext(r.sampleRate),this.audioSink=new Zn(r),void t?.()):(this.audioSink=null,this.ensureAudioContext(),void t?.()):(this.handleNoAudioTrack(),void t?.())}async runIterator(e){if(!this.audioSink)return;await this.stopIterator(),this.audioIterator=this.audioSink.buffers(this.currentTime);for(;;){if(e!==this.asyncId||this.paused)return;const i=[];let r=!1;try{for(let e=0;e<16;e++){const e=await this.audioIterator.next();if(e.done){r=!0;break}i.push(e.value)}}catch(t){console.error("Audio iterator error:",t),r=!0}if(e!==this.asyncId||this.paused)return;i.length>0&&"suspended"===this.audioContext.state&&(await this.audioContext.resume(),this.events.emit("canplay"),this.events.emit("playing"));for(const{buffer:e,timestamp:t}of i){const i=this.audioContext.createBufferSource();i.buffer=e,i.connect(this.gainNode),i.playbackRate.value=this.playbackRate;const r=this.audioContextStartTime+(t-this.playbackTimeAtStart)/this.playbackRate,a=(r+e.duration/this.playbackRate-this.audioContextStartTime)*this.playbackRate+this.playbackTimeAtStart;a>this.latestScheduledEndTime&&(this.latestScheduledEndTime=a),r>=this.audioContext.currentTime?i.start(r):i.start(this.audioContext.currentTime,(this.audioContext.currentTime-r)*this.playbackRate),this.queuedNodes.add(i),i.onended=()=>this.queuedNodes.delete(i)}if(r)break;await new Promise(e=>setTimeout(e,0));const a=1;for(;this.latestScheduledEndTime-this.currentTime>a;){if(e!==this.asyncId||this.paused)return;await new Promise(e=>setTimeout(e,50))}}}async play(){if(!this.paused)return;this.audioContext||this.ensureAudioContext(),"suspended"===this.audioContext.state&&await this.audioContext.resume(),this.audioContextStartTime=this.audioContext.currentTime,this.latestScheduledEndTime=this.playbackTimeAtStart,this.paused=!1;const e=++this.asyncId;this.runIterator(e)}pause(){this.paused||(this.playbackTimeAtStart=this.currentTime,this.paused=!0,this.stopIterator(),this.stopQueuedNodes())}async seek(e){this.playbackTimeAtStart=Math.max(0,e),this.audioContextStartTime=this.audioContext.currentTime,this.latestScheduledEndTime=this.playbackTimeAtStart;const t=++this.asyncId;this.paused||this.runIterator(t)}setVolume(e,t){this.volume=e,this.muted=t,this.updateGain()}setPlaybackRate(e){if(e!==this.playbackRate&&(this.paused||(this.playbackTimeAtStart=this.currentTime,this.audioContextStartTime=this.audioContext.currentTime),this.playbackRate=e,!this.paused)){const e=++this.asyncId;this.runIterator(e)}}destroy(){this.asyncId++,this.pause(),this.audioContext?.close(),this.audioContext=null,this.input=null,this.audioSink=null}}async function Jo(e){return await e.getAverageBitrate()??await e.getBitrate()??0}const Zo=/\.m3u8(?:$|[?#])/i;function ec(e){return"string"===typeof e&&Zo.test(e)}function tc(e){const t=function(e){return"string"===typeof e?new us(e):e instanceof Blob?new os(e):"undefined"!==typeof ReadableStream&&e instanceof ReadableStream?new fs(e):e??null}(e);return t?new po({source:t,formats:ec(e)?en:Zs}):null}class ic{constructor(){this.active=!0,this.input=null,this.timers=new Set,this.controller="undefined"===typeof AbortController?void 0:new AbortController,this.cancellation=new Promise(e=>{this.resolveCancellation=e})}get signal(){return this.controller?.signal}own(e){this.active?this.input=e:e.dispose()}defer(e){if(!this.active)return;const t=setTimeout(()=>{this.timers.delete(t),this.active&&e()},0);this.timers.add(t)}async wait(e,t){try{await Promise.race([e,this.cancellation,t>0?this.timeout(t):new Promise(()=>{})])}finally{void 0!==this.deadline&&(clearTimeout(this.deadline),this.deadline=void 0)}}timeout(e){return new Promise((t,i)=>{this.deadline=setTimeout(()=>i(new Error("Load timeout")),e)})}disposeInput(){const e=this.input;this.input=null,e?.dispose()}cancel(){if(this.active){this.active=!1;for(const e of this.timers)clearTimeout(e);this.timers.clear(),void 0!==this.deadline&&(clearTimeout(this.deadline),this.deadline=void 0),this.resolveCancellation(),this.controller?.abort(),this.disposeInput()}}}function rc(e,t,i){for(const r of i){if(!t())return;e.emit(r)}}async function ac({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 sc(){let e,t;return{promise:new Promise((i,r)=>{e=i,t=r}),resolve:e,reject:t}}class nc{constructor(e){this.host=e,this.wanted=!1,this.playing=null,this.seeking=null,this.audioStart=null}operation(){return{...sc(),source:this.host.loadSeq,complete:sc()}}current(e,t){return!this.host.destroyed&&e.source===this.host.loadSeq&&this[t]===e}cancelPlay(){const e=this.playing;this.playing=null,e?.resolve()}invalidate(){this.cancelPlay(),this.wanted=!1;const e=this.seeking;this.seeking=null,e?.complete.resolve(),e?.resolve(),this.host.seeking=!1}ended(){this.wanted=!1,this.cancelPlay()}stop(){this.host.paused||(this.host.paused=!0,this.stopEngines(),this.host.events.emit("pause"))}stopEngines(){const e=[];for(const i of[()=>this.host.audio.pause(),()=>this.host.video.stop()])try{i()}catch(t){e.push(t)}if(e.length)throw e[0]}pause(){this.wanted=!1,this.cancelPlay(),this.stop()}play(){if(this.host.destroyed)return Promise.resolve();if(this.wanted=!0,this.playing)return this.playing.promise;if(this.host.ended)return this.seek(0,!0);if(!this.host.paused&&!this.seeking)return Promise.resolve();const e=this.operation();return this.playing=e,this.runPlay(e).then(e.resolve,e.reject),e.promise}async startAudio(){this.audioStart||(this.audioStart=this.host.audio.play());const e=this.audioStart;try{await e}finally{this.audioStart===e&&(this.audioStart=null)}}async runPlay(e){const t=()=>this.current(e,"playing")&&this.wanted;try{for(;this.seeking;)if(await this.seeking.complete.promise,!t())return;if(!t())return;if(this.host.paused=!1,await this.startAudio(),!t())return void(this.wanted&&!this.host.destroyed||this.host.audio.pause());this.host.video.start(this.host.audio),rc(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 ac(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,rc(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(),rc(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()}}class oc{constructor({canvas:e,ctx:t,events:i,timeupdateInterval:r=250,avSyncTolerance:a=.12,dropLateFrames:s=!1,poster:n="",preflightRange:o=!1}){this.canvas=e,this.ctx=t,this.events=i,this.timeupdateInterval=r,this.avSyncTolerance=a,this.dropLateFrames=s,this.poster=n,this.preflightRange=o,this.input=null,this.videoSink=null,this.videoIterator=null,this.nextFrame=null,this.rafId=0,this.asyncId=0,this.width=0,this.height=0,this.duration=Number.NaN,this.audioClock=null,this.lastTimeUpdate=0,this.stalled=!1,this.playbackRate=1,this.posterDrawn=!1,this.isFetching=!1}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||ec(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(!this.poster||this.posterDrawn)return;const e=new Image;e.onload=()=>{this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.canvas.width=e.naturalWidth||this.canvas.width,this.canvas.height=e.naturalHeight||this.canvas.height,this.ctx.drawImage(e,0,0,this.canvas.width,this.canvas.height),this.posterDrawn=!0},e.src=this.poster}async stopIterator(){await(this.videoIterator?.return()),this.videoIterator=null}clear(){this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height)}async load(e,t){++this.asyncId,await this.stopIterator(),this.clear(),this.posterDrawn=!1;const{input:i,videoTrack:r,duration:a}=e;if(this.input=i,this.duration=a,!r)return this.handleNoVideoTrack(),void t?.();if(null===r.codec||!(await r.canDecode()))return this.handleNoVideoTrack(),void t?.();const s=await r.canBeTransparent();this.videoSink=new Gn(r,{poolSize:2,fit:"contain",alpha:s}),this.width=r.displayWidth,this.height=r.displayHeight,this.canvas.width=this.width,this.canvas.height=this.height,t?.(),await this.resetIterator(0)}handleNoVideoTrack(){this.videoSink=null,this.width=0,this.height=0,this.canvas.width=0,this.canvas.height=0,this.clear(),this.drawPoster()}async resetIterator(e){if(await this.stopIterator(),!this.videoSink)return;this.videoIterator=this.videoSink.canvases(e);const t=(await this.videoIterator.next()).value??null,i=(await this.videoIterator.next()).value??null;this.nextFrame=i,t?this.ctx.drawImage(t.canvas,0,0):this.drawPoster()}async updateNextFrame(e){if(this.videoIterator&&!this.isFetching){this.isFetching=!0;try{for(;;){const t=(await this.videoIterator.next()).value??null;if(!t||e!==this.asyncId)return;const i=this.audioClock.currentTime,r=this.dropLateFrames?Math.max(.06,this.avSyncTolerance/Math.max(1,this.playbackRate)):0;if(!(this.dropLateFrames&&t.timestampi)return void(this.nextFrame=null)}}}finally{this.isFetching=!1}}}render(){if(!this.audioClock)return;const e=this.audioClock.currentTime,t=Date.now();if(t-this.lastTimeUpdate>=this.timeupdateInterval&&(this.events.emit("timeupdate"),this.lastTimeUpdate=t),Number.isFinite(this.duration)&&e>=this.duration)return this.stop(),this.stalled=!1,this.events.emit("ended"),this.events.emit("pause"),void this.events.emit("canplay");this.nextFrame&&this.nextFrame.timestamp<=e?(this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.ctx.drawImage(this.nextFrame.canvas,0,0),this.nextFrame=null,this.updateNextFrame(this.asyncId),this.stalled&&(this.events.emit("canplay"),this.events.emit("playing"),this.stalled=!1)):this.nextFrame||(this.updateNextFrame(this.asyncId),!this.nextFrame&&Number.isFinite(this.duration)&&ethis.render())}start(e){this.audioClock=e,this.asyncId++,this.stalled=!1,this.updateNextFrame(this.asyncId),this.rafId=requestAnimationFrame(()=>this.render())}stop(){cancelAnimationFrame(this.rafId)}async seek(e){this.asyncId++,await this.resetIterator(e)}setPlaybackRate(e){this.playbackRate=Math.max(.1,Number(e)||1)}destroy(){this.asyncId++,this.stop(),this.stopIterator(),this.posterDrawn=!1,this.videoSink=null,this.input=null}}class cc{constructor({canvas:e,ctx:i,events:r,option:o={}}){s(this,t),this.events=r,this.option=o,this.audio=new Yo(r),this.video=new oc({canvas:e,ctx:i,events:r,timeupdateInterval:o.timeupdateInterval??250,avSyncTolerance:o.avSyncTolerance??.12,dropLateFrames:o.dropLateFrames??!1,poster:o.poster??"",preflightRange:o.preflightRange??!1}),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,n(this,t,new nc(this)),r.addEventListener("ended",()=>{this.destroyed||(this.ended=!0,this.paused=!0,a(this,t).ended())})}async load(e){if(this.destroyed)return;const i=++this.loadSeq;if(a(this,t).invalidate(),this.loadSession?.cancel(),i!==this.loadSeq||this.destroyed)return;if(this.pause(),i!==this.loadSeq||this.destroyed)return;this.disposeInput();const r=new ic;this.loadSession=r,this.ended=!1,this.error=null,this.networkState=2,this.readyState=0,r.defer(()=>this.events.emit("waiting")),r.defer(()=>this.events.emit("loadstart"));const s=Number.isFinite(this.option.loadTimeout)?this.option.loadTimeout??0:0;try{await r.wait(this.performLoad(e,i,r),s)}catch(n){if(i!==this.loadSeq)return;const e=++this.loadSeq;if(a(this,t).invalidate(),r.cancel(),e!==this.loadSeq||this.destroyed)return;this.disposeInput(),this.reportError(n)}}async performLoad(e,t,i=this.loadSession){const r=()=>!this.destroyed&&t===this.loadSeq;if(!i||!(await this.video.preflight(e,i.signal,r))||!r())return;const a=tc(e);if(!a)return this.video.handleNoVideoTrack(),void(r()&&this.audio.handleNoAudioTrack());i.own(a);const s=await async function(e,t){const i=await e.getPrimaryVideoTrack(),r=i?await i.getPrimaryPairableAudioTrack():await e.getPrimaryAudioTrack(),a=await ac({input:e,videoTrack:i,audioTrack:r}),s=i||r,n=ec(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,rc(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,rc(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 a(this,t).replace({...this.media,...e},this.currentTime)}async selectHlsQuality(e){return async function(e,t){const{input:i,media:r,loadSeq:a}=e;if(!r?.isHls||!i||e.destroyed)return;const s=()=>!e.destroyed&&e.loadSeq===a&&e.input===i&&e.media===r;let n;try{const e=await i.getVideoTracks();if(!s())return;const a="auto"===t?await i.getPrimaryVideoTrack():e.find(e=>e.id===t)??r.videoTrack;if(!s()||!a)return;let o=r.audioTrack,c=r.audioMode;o&&a.canBePairedWith(o)||(o=await a.getPrimaryPairableAudioTrack(),c="auto"),n={videoTrack:a,audioTrack:o,videoMode:"auto"===t?"auto":"manual",audioMode:c}}catch(o){if(!s())return;throw o}s()&&await e.replaceTracks(n)}(this,e)}async selectHlsAudio(e){return async function(e,t){const{input:i,media:r,loadSeq:a}=e;if(!r?.isHls||!i||e.destroyed)return;const s=()=>!e.destroyed&&e.loadSeq===a&&e.input===i&&e.media===r;let n;try{const e=await i.getAudioTracks();if(!s())return;const a="auto"===t?r.videoTrack?await r.videoTrack.getPrimaryPairableAudioTrack():await i.getPrimaryAudioTrack():e.find(e=>e.id===t)??r.audioTrack;if(!s()||!a)return;let o=r.videoTrack,c=r.videoMode;o&&a.canBePairedWith(o)||(o=await a.getPrimaryPairableVideoTrack(),c="auto"),n={videoTrack:o,audioTrack:a,videoMode:c,audioMode:"auto"===t?"auto":"manual"}}catch(o){if(!s())return;throw o}s()&&await e.replaceTracks(n)}(this,e)}async getHlsState(){const e=this.media;if(this.destroyed)return null;try{const t=await async function(e){if(!e?.isHls||!e.input)return null;const[t,i]=await Promise.all([e.input.getVideoTracks(),e.videoTrack?e.videoTrack.getPairableAudioTracks():[]]),[r,a]=await Promise.all([Promise.all(t.map(async(e,t)=>({id:e.id,track:e,index:t,name:await e.getName(),height:await e.getDisplayHeight(),bitrate:await Jo(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 Jo(e)}}))]);return{levels:r,audios:a,currentLevel:e.videoTrack?r.find(t=>t.id===e.videoTrack?.id)??null:null,currentAudio:e.audioTrack?a.find(t=>t.id===e.audioTrack?.id)??null:null,videoMode:e.videoMode??"auto",audioMode:e.audioMode??"auto"}}(e);return this.destroyed||this.media!==e?null:t}catch(t){if(this.destroyed||this.media!==e)return null;throw t}}async play(){return a(this,t).play()}pause(){a(this,t).pause()}async seek(e){return a(this,t).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++,a(this,t).invalidate();const e=[];for(const t of[()=>this.loadSession?.cancel(),()=>this.pause(),()=>this.disposeInput(),()=>this.audio.destroy(),()=>this.video.destroy()])try{t()}catch(i){e.push(i)}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}}t=new WeakMap;const lc=new WeakMap;function uc(e){let t=lc.get(e);return t||(t={closed:!1,frames:new Set},lc.set(e,t)),t}class dc{constructor({art:e,canvas:t,ctx:i,option:r}){this.art=e,this.canvas=t,this.option=r,this.events=new c,this.engine=new cc({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=uc(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){uc(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=uc(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 dc({art:t,canvas:a,ctx:s,option:e});t.mediabunny=n;const c={};for(const e in a)"function"===typeof a[e]&&(c[e]=a[e].bind(a));const l=new Set([...Object.getOwnPropertyNames(n),...Object.getOwnPropertyNames(Object.getPrototypeOf(n))]);for(const e of l)"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 c)a[e]=(...t)=>c[e](...t);function u(){const e=t.template?.$player;e&&!t.option.autoSize&&Object.assign(a.style,{width:"100%",height:"100%",objectFit:"contain"})}return t.on("resize",u),t.on("video:loadedmetadata",u),function({art:e,shim:t,option:i}){if(i.m3u8)return e.on("video:loadedmetadata",d),e.on("restart",d),{update:d};function r(t){e.controls.cache.has(t)&&e.controls.remove(t)}function a(t){e.setting.find(t)&&e.setting.remove(t)}function s(){r("mediabunny-quality"),a("mediabunny-quality")}function n(){r("mediabunny-audio"),a("mediabunny-audio")}function c(e={}){return e.control||e.setting}async function l(r){const a=i.m3u8?.quality||{};if(!c(a)||!r?.levels.length)return void s();const n=a.auto||"Auto",l=a.title||"Quality",u=a.getName||(e=>e.name||`${e.height}P`),h=r.currentLevel?u(r.currentLevel):n,f=o(r.levels.map(e=>({html:u(e),value:e.id,default:r.currentLevel?.id===e.id})),"html").sort((e,t)=>{const i=r.levels.find(t=>t.id===e.value),a=r.levels.find(e=>e.id===t.value);return(a?.height||0)-(i?.height||0)});f.push({html:n,value:"auto",default:!r.currentLevel});const m=async i=>(await t.switchM3u8Quality(i.value),e.notice.show=`${l}: ${i.html}`,await d(),i.html);a.control&&e.controls.update({name:"mediabunny-quality",position:"right",html:h,style:{padding:"0 10px"},selector:f,onSelect:m}),a.setting&&e.setting.update({name:"mediabunny-quality",tooltip:h,html:l,icon:'',width:200,selector:f,onSelect:m})}async function u(r){const a=i.m3u8?.audio||{};if(!c(a)||!r?.audios.length||r.audios.length<2)return void n();const s=a.auto||"Auto",l=a.title||"Audio",u=a.getName||(e=>e.name||e.lang||e.language),h=r.currentAudio?u(r.currentAudio):s,f=o(r.audios.map(e=>({html:u(e),value:e.id,default:r.currentAudio?.id===e.id})),"html");f.push({html:s,value:"auto",default:!r.currentAudio});const m=async i=>(await t.switchM3u8Audio(i.value),e.notice.show=`${l}: ${i.html}`,await d(),i.html);a.control&&e.controls.update({name:"mediabunny-audio",position:"right",html:h,style:{padding:"0 10px"},selector:f,onSelect:m}),a.setting&&e.setting.update({name:"mediabunny-audio",tooltip:h,html:l,icon:'',width:200,selector:f,onSelect:m})}async function d(){const e=await t.getM3u8State();if(!e)return s(),void n();await Promise.all([l(e),u(e)])}}({art:t,shim:n,option:e}),t.on("destroy",()=>{delete t.mediabunny,n.destroy()}),a}}}); 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 4553fb5d8..3968b5b32 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=Object.defineProperty,i=Object.defineProperties,r=Object.getOwnPropertyDescriptors,n=Object.getOwnPropertySymbols,s=Object.prototype.hasOwnProperty,a=Object.prototype.propertyIsEnumerable,o=(e,t)=>(t=Symbol[e])?t:Symbol.for("Symbol."+e),l=e=>{throw TypeError(e)},c=Math.pow,u=(e,i,r)=>i in e?t(e,i,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[i]=r,d=(e,t)=>{for(var i in t||(t={}))s.call(t,i)&&u(e,i,t[i]);if(n)for(var i of n(t))a.call(t,i)&&u(e,i,t[i]);return e},h=(e,t)=>i(e,r(t)),f=(e,t,i)=>t.has(e)||l("Cannot "+i),m=(e,t,i)=>(f(e,t,"read from private field"),i?i.call(e):t.get(e)),p=(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())}),g=function(e,t){this[0]=e,this[1]=t},k=(e,t,i)=>{var r,n=(e,t,r,s)=>{try{var a=i[e](t),o=(t=a.value)instanceof g,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[o("asyncIterator")]=()=>a,s("next"),s("throw"),s("return"),a},y=e=>{var t,i=e[o("asyncIterator")],r=!1,n={};return null==i?(i=e[o("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 g(new Promise(r=>{var n=i[e](t);n instanceof Object||l("Object expected"),r(n)}),1)}}),n[o("iterator")]=()=>n,t("next"),"throw"in i?t("throw"):n.throw=e=>{throw e},"return"in i&&t("return"),n},b=(e,t,i)=>(t=e[o("asyncIterator")])?t.call(e):(e=e[o("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 T(e,t){const i=new Map;return e.filter(e=>{const r=e[t];return void 0===r||!i.has(r)&&i.set(r,1)})}class v{constructor(){var t,i,r;t=this,r=!1,(i=e).has(t)?l("Cannot add the same private member more than once"):i instanceof WeakSet?i.add(t):i.set(t,r),this.listeners=new Map}addEventListener(t,i){var r;m(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(m(this,e))return;const n=Object.assign(new Event(t),{detail:i});null==(r=this.listeners.get(t))||r.forEach(t=>{m(this,e)||t(n)})}destroy(){var t,i,r,n;r=!0,f(t=this,i=e,"write to private field"),n?n.call(t,r):i.set(t,r),this.listeners.clear()}}function S(e){if(!e)throw new Error("Assertion failed.")}e=new WeakMap;const w=e=>{const t=(e%360+360)%360;if(0===t||90===t||180===t||270===t)return t;throw new Error(`Invalid rotation ${e}.`)},P=e=>e&&e[e.length-1],I=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-c(2,r))},C=e=>{const t=I(e);return 0===(1&t)?-(t>>1):t+1>>1},B=e=>e.constructor===Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),E=e=>e.constructor===DataView?e:ArrayBuffer.isView(e)?new DataView(e.buffer,e.byteOffset,e.byteLength):new DataView(e),_=new TextDecoder,R=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])),F={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},A=R(F),D={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},M=R(D),N={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},O=R(N),L=e=>!!e&&!!e.primaries&&!!e.transfer&&!!e.matrix&&void 0!==e.fullRange,z={primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0},U=e=>e instanceof ArrayBuffer||"undefined"!==typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e);class q{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}acquire(){return p(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 W=/^[0-9a-fA-F]+$/,H=e=>[...e].map(e=>e.toString(16).padStart(2,"0")).join(""),V=e=>(e=(e=(e=(e=(e=e>>1&1431655765|(1431655765&e)<<1)>>2&858993459|(858993459&e)<<2)>>4&252645135|(252645135&e)<<4)>>8&16711935|(16711935&e)<<8)>>16&65535|(65535&e)<<16)>>>0,j=(e,t,i)=>{let r=0,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},X=(e,t,i)=>{const r=K(e,i(t),i);e.splice(r+1,0,t)},$=()=>{let e,t;return{promise:new Promise((i,r)=>{e=i,t=r}),resolve:e,reject:t}},G=(e,t)=>{const i=e.indexOf(t);-1!==i&&e.splice(i,1)},Q=(e,t)=>{for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},Y=(e,t)=>{for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},J=e=>{throw new Error(`Unexpected value: ${e}`)},Z=(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},ee=(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)},te=(e,t)=>({next(){return p(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}}),ie=(e,t,i)=>Math.max(t,Math.min(i,e)),re="und",ne=e=>{const t=Math.round(e);return Math.abs(e/t-1)<10*Number.EPSILON?t:e},se=(e,t)=>Math.round(e/t)*t,ae=(e,t)=>Math.round(e*t)/t,oe=(e,t)=>Math.floor(e/t)*t,le=e=>{let t=0;for(;0!==e;)e&=e-1,t++;return t},ce=/^[a-z]{3}$/,ue=e=>ce.test(e),de=1e6*(1+Number.EPSILON),he=(e,t)=>{const i=d(d({},e),t);if(e.headers||t.headers){const r=e.headers?fe(e.headers):{},n=t.headers?fe(t.headers):{},s=d({},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},fe=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},me=(e,t,i,r,n)=>p(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(ze._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 Me(1e3*e)),n())throw a}});class pe{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}let ge=null;const ke=()=>{var e;return null!==ge?ge:ge=!("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 ye=null;const be=()=>{var e;return null!==ye?ye:ye="undefined"!==typeof navigator&&(null==(e=navigator.userAgent)?void 0:e.includes("Firefox"))};let Te=null;const ve=()=>{var e;return null!==Te?Te:Te=!("undefined"===typeof navigator||!(null==(e=navigator.vendor)?void 0:e.includes("Google Inc"))&&!/Chrome/.test(navigator.userAgent))},Se=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.`,we=p(null,null,function*(){}).constructor,Pe=e=>e instanceof we||e instanceof Promise||"function"===typeof(null==e?void 0:e.then),Ie=(e,t)=>-1!==e?e:t,xe=(e,t,i,r)=>e<=r&&i<=t,Ce=e=>{const t=atob(e),i=new Uint8Array(t.length);for(let r=0;r{null!=Symbol.dispose||(Symbol.dispose=Symbol("Symbol.dispose"))},Ee=e=>"number"===typeof e&&!Number.isNaN(e),_e=(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("/")},Re=(e,t)=>{let i=0;for(let r=0;r{let i=-1,r=1/0;for(let n=0;n{S(Number.isInteger(e.num)),S(Number.isInteger(e.den)),S(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}},De=(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.`)},Me=e=>new Promise(t=>setTimeout(t,e));class Ne{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 Oe,Le;(Le=Oe||(Oe={}))[Le.Silent=0]="Silent",Le[Le.Errors=1]="Errors",Le[Le.Warnings=2]="Warnings",Le[Le.Info=3]="Info";class ze{constructor(){}static get level(){return ze._level}static set level(e){if(e!==Oe.Silent&&e!==Oe.Errors&&e!==Oe.Warnings&&e!==Oe.Info)throw new TypeError("Invalid log level. Use one of the values of the LogLevel enum.");ze._level=e}static get _emitter(){var e;return null!=(e=ze._emitterInstance)?e:ze._emitterInstance=new Ne}static on(e,t,i){return ze._emitter.on(e,t,i)}static _error(...e){ze._emitter._emit("error",e),ze._level>=Oe.Errors&&console.error(...e)}static _warn(...e){ze._emitter._emit("warn",e),ze._level>=Oe.Warnings&&console.warn(...e)}static _info(...e){ze._emitter._emit("info",e),ze._level>=Oe.Info&&console.info(...e)}}ze._level=Oe.Info,ze._emitterInstance=null;class Ue{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 qe{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 We={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1};class He{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 He(this.bytes);return e.pos=this.pos,e}}const Ve=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],je=[-1,1,2,3,4,5,6,8],Ke=e=>{if(!e||e.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");const t=new He(e),i=Xe(t),{frequencyIndex:r,sampleRate:n}=$e(t),s=t.readBits(4);let a=null;s>=1&&s<=7&&(a=je[s]);let o=i,l=!1,c=n;if(5===i||29===i)l=29===i,c=$e(t).sampleRate,o=Xe(t),22===o&&t.skipBits(4);else for(;t.getBitsLeft()>15;){const e=t.pos;if(695===t.readBits(11)){5===Xe(t)&&t.readBits(1)&&(c=$e(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}},Xe=e=>{const t=e.readBits(5);return 31===t?32+e.readBits(6):t},$e=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&B(t.description)[4];return it(e,i+1)}return tt(e)},nt=e=>31&e,st=e=>{const t=[],i=e.length;for(let r=0;r{const t=e.reduce((e,t)=>e+at.byteLength+t.byteLength,0),i=new Uint8Array(t);let r=0;for(const n of e)i.set(at,r),r+=at.byteLength,i.set(n,r),r+=n.byteLength;return i},lt=(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:ee(e,n,s.byteLength);break;case 4:e.setUint32(n,s.byteLength,!1)}n+=t,r.set(s,n),n+=s.byteLength}return r},ct=e=>{try{const t=[],i=[],r=[];for(const o of tt(e)){const n=e.subarray(o.offset,o.offset+o.length),s=nt(n[0]);s===Ye.SPS?t.push(n):s===Ye.PPS?i.push(n):s===Ye.SPS_EXT&&r.push(n)}if(0===t.length)return null;if(0===i.length)return null;const n=t[0],s=ft(n);S(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 ze._error("Error building AVC Decoder Configuration Record:",t),null}},ut=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=E(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=st(e),r=new He(i);r.skipBits(1),r.skipBits(2);if(7!==r.readBits(5))return null;const n=r.readAlignedByte(),s=r.readAlignedByte(),a=r.readAlignedByte();I(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=I(r),3===o&&(u=r.readBits(1)),l=I(r),c=I(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:P(ui),n=Math.min(Math.floor(r.maxDpbMbs/(e*i)),16);B=n,E=n}else B=0,E=0}return S(null!==E),{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:x,colourPrimaries:b,matrixCoefficients:v,transferCharacteristics:T,fullRangeFlag:w,numReorderFrames:B,maxDecFrameBuffering:E,vuiParametersFlagBitOffset:F,bitstreamRestrictionFlagBitOffset:_,bitstreamRestrictionFlag:R}}catch(i){return ze._error("Error parsing AVC SPS:",i),null}},mt=e=>{const t=I(e);e.skipBits(4),e.skipBits(4);for(let i=0;i<=t;i++)I(e),I(e),e.skipBits(1);e.skipBits(5),e.skipBits(5),e.skipBits(5),e.skipBits(5)},pt=e=>{S(1!==e.bitstreamRestrictionFlag);const t=new Uint8Array(e.emulationUnpreventedBytes.byteLength+64),i=new He(e.emulationUnpreventedBytes),r=new He(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)):(S(null!==e.bitstreamRestrictionFlagBitOffset),r.copyBits(e.bitstreamRestrictionFlagBitOffset,i)),r.writeBits(1,1),r.writeBits(1,1),x(r,2),x(r,1),x(r,16),x(r,16),x(r,e.numReorderFrames),x(r,e.maxDecFrameBuffering),r.writeBits(1,1),r.writeBits((8-r.pos%8)%8,0);const n=r.pos/8;return S(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))},gt=(e,t)=>{if(t.description){const i=3&B(t.description)[21];return it(e,i+1)}return tt(e)},kt=e=>e>>1&63,yt=e=>{try{const t=new He(st(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}=Tt(t,i);I(t);const u=I(t);let d=0;3===u&&(d=t.readBits(1));const h=I(t),f=I(t);let m=h,p=f;if(t.readBits(1)){const e=I(t),i=I(t),r=I(t),n=I(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=I(t),k=I(t);I(t);const y=t.readBits(1);let b=0;for(let e=y?0:i;e<=i;e++)I(t),b=I(t),I(t);I(t),I(t),I(t),I(t),I(t),I(t),t.readBits(1)&&t.readBits(1)&&vt(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(4),t.skipBits(4),I(t),I(t),t.skipBits(1));const T=I(t);if(St(t,T),t.readBits(1)){const e=I(t);for(let i=0;i{try{const t=[],i=[],r=[],n=[];for(const l of tt(e)){const s=e.subarray(l.offset,l.offset+l.length),a=kt(s[0]);a===Ze.VPS_NUT?t.push(s):a===Ze.SPS_NUT?i.push(s):a===Ze.PPS_NUT?r.push(s):a!==Ze.PREFIX_SEI_NUT&&a!==Ze.SUFFIX_SEI_NUT||n.push(s)}if(0===i.length||0===r.length)return null;const s=yt(i[0]);if(!s)return null;let a=0;if(r.length>0){const e=r[0],t=new He(st(e));t.skipBits(16),I(t),I(t),t.skipBits(1),t.skipBits(1),t.skipBits(3),t.skipBits(1),t.skipBits(1),I(t),I(t),C(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&I(t),C(t),C(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:Ze.VPS_NUT,nalUnits:t}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:Ze.SPS_NUT,nalUnits:i}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:Ze.PPS_NUT,nalUnits:r}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:kt(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 ze._error("Error building HEVC Decoder Configuration Record:",t),null}},Tt=(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&&C(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-(I(e)+1)}else o=t-1;e.readBits(1),I(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=I(e),i=I(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=ht[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)&&(I(e),I(e)),e.readBits(1),e.readBits(1),e.readBits(1),e.readBits(1)&&(I(e),I(e),I(e),I(e)),e.readBits(1)&&(e.readBits(32),e.readBits(32),e.readBits(1)&&I(e),e.readBits(1)&&It(e,!0,t)),e.readBits(1)&&(e.readBits(1),e.readBits(1),e.readBits(1),a=I(e),I(e),I(e),I(e),I(e)),{pixelAspectRatio:o,colourPrimaries:i,transferCharacteristics:r,matrixCoefficients:n,fullRangeFlag:s,minSpatialSegmentationIdc:a}},It=(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?I(e):i=1===e.readBits(1);let a=1;if(!i){a=I(e)+1}r&&xt(e,a,s),n&&xt(e,a,s)}},xt=(e,t,i)=>{for(let r=0;r{const i=new Set;let r=Ct.audAllowed;for(const s of gt(e,t)){if(r===Ct.noMoreDataAllowed){i.add(s.offset);continue}const t=kt(e[s.offset]);if(r===Ct.eoBitstreamAllowed&&37!==t){i.add(s.offset);continue}let n=!1;35===t?r>Ct.audAllowed?n=!0:r=Ct.beforeFirstVcl:t<=31?r>Ct.afterFirstVcl?n=!0:r=Ct.afterFirstVcl:36===t?r!==Ct.afterFirstVcl?n=!0:r=Ct.eoBitstreamAllowed:37===t?r=41&&t<=44||t>=48&&t<=55?r>Ct.beforeFirstVcl?n=!0:r=Ct.beforeFirstVcl:(38===t||40===t||t>=45&&t<=47||t>=56&&t<=63)&&r{if(t.description){const i=3&B(t.description)[21];return lt(e,i+1)}return ot(e)})(n,t)},_t={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}},Rt=e=>{var t,i,r;const n=new He(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=P(di).level;for(const m of di)if(d<=m.maxPictureSize){h=m.level;break}const f=_t[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}},Ft=function*(e){const t=new He(e),i=()=>{let e=0;for(let i=0;i<8;i++){const r=t.readAlignedByte();if(e+=(127&r)*c(2,7*i),!(128&r))break;if(7===i&&128&r)return null}return e>c(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);S(t.pos%8===0),yield{type:r,data:e.subarray(t.pos/8,t.pos/8+a)},t.skipBits(8*a)}},At=e=>{for(const{type:t,data:i}of Ft(e)){if(1!==t)continue;const e=new He(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,S=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&&(S=e.readBits(2))),{profile:r,level:s,tier:a,bitDepth:m,monochrome:p,chromaSubsamplingX:T,chromaSubsamplingY:v,chromaSamplePosition:S,videoFullRangeFlag:b,colourPrimaries:g,transferCharacteristics:k,matrixCoefficients:y}}return null},Dt=e=>{if(e.length<36)return null;const t=E(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)}},Mt=[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],Nt=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}},Ot=(e,t,i)=>{switch(e){case"avc":for(const e of rt(i,t)){const t=i[e.offset],r=nt(t);if(r>=Ye.NON_IDR_SLICE&&r<=Ye.SLICE_DPC)return"delta";if(r===Ye.IDR)return"key";if(r===Ye.SEI&&!ve()){const t=i.subarray(e.offset,e.offset+e.length),r=st(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 He(r);e.pos=8*n;const t=I(e),i=e.readBits(1);if(0===t&&1===i)return"key"}n+=t}while(n{var i,r;const n=E(e);let s=0;const a=n.getUint32(s,!0);s+=4;const o=_.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=Ce(c),i=E(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=_.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})}}}},qt=[2,1,2,3,3,4,4,5],Wt=e=>{if(e.length<7)return null;if(11!==e[0]||119!==e[1])return null;const t=new He(e);t.skipBits(16),t.skipBits(16);const i=t.readBits(2);if(3===i)return null;const r=t.readBits(6),n=t.readBits(5);if(n>8)return null;const s=t.readBits(3),a=t.readBits(3);0!==(1&a)&&1!==a&&t.skipBits(2),0!==(4&a)&&t.skipBits(2),2===a&&t.skipBits(2);return{fscod:i,bsid:n,bsmod:s,acmod:a,lfeon:t.readBits(1),bitRateCode:Math.floor(r/2)}},Ht=[128,138,192,128,140,192,160,174,240,160,176,240,192,208,288,192,210,288,224,242,336,224,244,336,256,278,384,256,280,384,320,348,480,320,350,480,384,416,576,384,418,576,448,486,672,448,488,672,512,556,768,512,558,768,640,696,960,640,698,960,768,834,1152,768,836,1152,896,974,1344,896,976,1344,1024,1114,1536,1024,1116,1536,1280,1392,1920,1280,1394,1920,1536,1670,2304,1536,1672,2304,1792,1950,2688,1792,1952,2688,2048,2228,3072,2048,2230,3072,2304,2506,3456,2304,2508,3456,2560,2786,3840,2560,2788,3840],Vt=[1,2,3,6],jt=e=>{if(e.length<6)return null;if(11!==e[0]||119!==e[1])return null;const t=new He(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=Vt[s];let d;d=n<3?Ge[n]/1e3:Qe[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}]}},Kt=e=>{const t=e.substreams[0];return S(t),t.fscod<3?Ge[t.fscod]:null!==t.fscod2&&t.fscod2<3?Qe[t.fscod2]:null},Xt=e=>{const t=e.substreams[0];S(t);let i=qt[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},$t=[0,8e3,16e3,32e3,0,0,11025,22050,44100,0,0,12e3,24e3,48e3,96e3,192e3],Gt=[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],Qt=[16,16,20,20,0,24,24,0],Yt=[1,2,2,2,2,3,3,4,4,5,6,6,6,7,8,8],Jt=[1,2,2,2,2,3,18,19,6,7,518,323,83,519,582,535],Zt=[32e3,44100,48e3,0],ei=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],ti=[512,1024,2048,4096],ii=e=>{const t=ni(e),i=E(e);let r=t?4*Math.ceil(t.frameSize/4):0,n=null;for(;r+4<=e.length&&1683496997===i.getUint32(r);){const t=si(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}},ri=e=>{const t=ii(e);return(null==t?void 0:t.core)?t.hasExtensions?"dtsh":"dtsc":null},ni=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 He(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>=Yt.length)return null;const a=$t[t.readBits(4)];if(0===a)return null;const o=Gt[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=Qt[t.readBits(3)];if(0===c)return null;const u=0!==l;return{frameSize:n,sampleRate:a,numberOfChannels:Yt[s]+(u?1:0),sampleCount:32*r,channelLayout:Jt[s]|(u?8:0),amode:s,lfePresent:u,bitRate:o,pcmResolution:c}},si=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 He(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=Zt[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}}},ai=e=>le(e)+le(44646&e),oi=["avc","hevc","vp9","av1","vp8","prores"],li=["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"],ci=["aac","opus","mp3","vorbis","flac","ac3","eac3","dts",...li],ui=[{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}],di=[{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}],hi=".01.01.01.01.00",fi=".0.110.01.01.01.0",mi=["ap4x","ap4h","apch","apcn","apcs","apco"],pi=["dtsc","dtsh","dtsl","dtse"],gi=e=>{const{codec:t,codecDescription:i,colorSpace:r,avcCodecInfo:n,hevcCodecInfo:s,vp9CodecInfo:a,av1CodecInfo:o,proresFormat:l}=e;if("avc"===t){if(S(null!==e.avcType),n){const t=new Uint8Array([n.avcProfileIndication,n.profileCompatibility,n.avcLevelIndication]);return`avc${e.avcType}.${H(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}.${H(i.subarray(1,4))}`}if("hevc"===t){let e,t,r,n,a,o;if(s)e=s.generalProfileSpace,t=s.generalProfileIdc,r=V(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=E(i),l=s.getUint8(1);e=l>>6&3,t=31&l,r=V(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=P(di).level;for(const e of di)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(hi)&&(t=t.slice(0,-15)),t}if("av1"===t){if(!o){const t=e.width*e.height;let i=P(di).level;for(const e of di)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)?F[r.primaries]:1,u=(null==r?void 0:r.transfer)?D[r.transfer]:1,d=(null==r?void 0:r.matrix)?N[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(fi)&&(f=f.slice(0,-17)),f}if("prores"===t)return null!=l?l:"apch";throw null!==t&&J(t),new TypeError(`Unhandled codec '${t}'.`)},ki=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=dt(e.codecDescription))?void 0:i.sequenceParameterSets[0]),r){const e=ft(r);if(e)return{primaries:A[e.colourPrimaries],transfer:M[e.transferCharacteristics],matrix:O[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case"hevc":{let t=null==(n=null==(r=e.hevcCodecInfo)?void 0:r.arrays.find(e=>e.nalUnitType===Ze.SPS_NUT))?void 0:n.nalUnits[0];if(!t&&e.codecDescription&&(t=null==(a=null==(s=(e=>{try{const t=E(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,S=t.getUint8(i++),w=[];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===Ze.SPS_NUT))?void 0:a.nalUnits[0]),t){const e=yt(t);if(e)return{primaries:A[e.colourPrimaries],transfer:M[e.transferCharacteristics],matrix:O[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case"vp8":break;case"vp9":if(e.vp9CodecInfo)return{primaries:A[e.vp9CodecInfo.colourPrimaries],transfer:M[e.vp9CodecInfo.transferCharacteristics],matrix:O[e.vp9CodecInfo.matrixCoefficients],fullRange:!!e.vp9CodecInfo.videoFullRangeFlag};break;case"av1":if(e.av1CodecInfo)return{primaries:A[e.av1CodecInfo.colourPrimaries],transfer:M[e.av1CodecInfo.transferCharacteristics],matrix:O[e.av1CodecInfo.matrixCoefficients],fullRange:!!e.av1CodecInfo.videoFullRangeFlag};break;case"prores":if(e.proresCodecInfo)return{primaries:A[e.proresCodecInfo.colourPrimaries],transfer:M[e.proresCodecInfo.transferCharacteristics],matrix:O[e.proresCodecInfo.matrixCoefficients],fullRange:e.proresCodecInfo.fullRange}}return{primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0}},yi=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=Ke(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&&li.includes(t))return t;throw new TypeError(`Unhandled codec '${t}'.`)},bi=48e3,Ti=/^pcm-([usf])(\d+)(be)?$/,vi=e=>{if(S(li.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=Ti.exec(e);let i;S(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?c(2,7):0}},Si=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":mi.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":pi.includes(e)?"dts":"ulaw"===e?"ulaw":"alaw"===e?"alaw":Ti.test(e)?e:"webvtt"===e?"webvtt":null,wi=[44100,48e3,32e3],Pi=[-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],Ii=1483304551,xi=1231971951,Ci=(e,t)=>3===e?3===t?21:36:3===t?13:21,Bi=(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=Pi[16*a*4+16*c+(n>>4&15)];if(-1===g)return{header:null,bytesAdvanced:1};const k=1e3*g,y=wi[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 _i,Ri;(Ri=_i||(_i={}))[Ri.FrameCount=1]="FrameCount",Ri[Ri.FileSize=2]="FileSize",Ri[Ri.Toc=4]="Toc";const Fi=e=>3===e?1:2;class Ai{constructor(e){this.input=e}dispose(){}}const Di=new Uint8Array(0);class Mi{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===Di&&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===Di}get microsecondTimestamp(){return Math.trunc(de*this.timestamp)}get microsecondDuration(){return Math.trunc(de*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 Mi(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 Mi(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 Ni=e=>{const t=E(e);let i=0;const r=t.getUint8(i);i+=1,i+=3;const n=H(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=Wo(e);const i=Yo(e,4);let r=8;1===t&&(t=Ko(e),r=16);const n=t-r;return n<0?null:{name:i,totalSize:t,headerSize:r,contentSize:n}},zi=e=>Vo(e)/65536,Ui=e=>Vo(e)/1073741824,qi=e=>{let t=0;for(let i=0;i<4;i++){t<<=7;const i=No(e);if(t|=127&i,0===(128&i))break}return t},Wi=e=>{let t=Lo(e);return e.skip(2),t=Math.min(t,e.remainingLength),_.decode(Mo(e,t))},Hi=e=>{const t=Li(e);if(!t||"data"!==t.name)return null;if(e.remainingLength<8)return null;const i=Wo(e);e.skip(4);const r=Mo(e,t.contentSize-8);switch(i){case 1:return _.decode(r);case 2:return new TextDecoder("utf-16be").decode(r);case 13:return new Ue(r,"image/jpeg");case 14:return new Ue(r,"image/png");case 27:return new Ue(r,"image/bmp");default:return r}},Vi=16,ji=new Uint32Array(256),Ki=new Uint32Array(256),Xi=new Uint32Array(256),$i=new Uint32Array(256),Gi=new Uint32Array(256),Qi=new Uint32Array(256),Yi=new Uint32Array(10);let Ji=!1;class Zi{constructor(){this.roundkey=new Uint32Array(44),this.iv=new Uint32Array(Vi/Uint32Array.BYTES_PER_ELEMENT),this.in=new Uint8Array(Vi),this.out=new Uint8Array(Vi),this.inView=new DataView(this.in.buffer),this.outView=new DataView(this.out.buffer)}init({key:e,iv:t}){S(16===e.byteLength),S(16===t.byteLength),Ji||(()=>{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);ji[s]=t<<24|t<<16|t<<8|t,Qi[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);Ki[s]=n,Xi[s]=n>>>8|n<<24,$i[s]=n>>>16|n<<16,Gi[s]=n>>>24|n<<8}let n=1;for(let s=0;s<10;s++)Yi[s]=n<<24,n=n<<1^(128&n?283:0);Ji=!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&ji[e>>>16&255]^16711680&ji[e>>>8&255]^65280&ji[e>>>0&255]^255&ji[e>>>24&255]^Yi[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]]^Xi[255&ji[t>>>16&255]]^$i[255&ji[t>>>8&255]]^Gi[255&ji[t>>>0&255]]}}decrypt(){let e=this.inView.getUint32(0,!1)^this.roundkey[0],t=this.inView.getUint32(4,!1)^this.roundkey[1],i=this.inView.getUint32(8,!1)^this.roundkey[2],r=this.inView.getUint32(12,!1)^this.roundkey[3];const 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=Ki[e>>>24]^Xi[r>>>16&255]^$i[i>>>8&255]^Gi[255&t]^this.roundkey[n],c=Ki[t>>>24]^Xi[e>>>16&255]^$i[r>>>8&255]^Gi[255&i]^this.roundkey[n+1],u=Ki[i>>>24]^Xi[t>>>16&255]^$i[e>>>8&255]^Gi[255&r]^this.roundkey[n+2],d=Ki[r>>>24]^Xi[i>>>16&255]^$i[t>>>8&255]^Gi[255&e]^this.roundkey[n+3],e=l,t=c,i=u,r=d}const h=4278190080&Qi[e>>>24&255]^16711680&Qi[r>>>16&255]^65280&Qi[i>>>8&255]^255&Qi[t>>>0&255]^this.roundkey[40],f=4278190080&Qi[t>>>24&255]^16711680&Qi[e>>>16&255]^65280&Qi[r>>>8&255]^255&Qi[i>>>0&255]^this.roundkey[41],m=4278190080&Qi[i>>>24&255]^16711680&Qi[t>>>16&255]^65280&Qi[e>>>8&255]^255&Qi[r>>>0&255]^this.roundkey[42],p=4278190080&Qi[r>>>24&255]^16711680&Qi[i>>>16&255]^65280&Qi[t>>>8&255]^255&Qi[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 er extends Ai{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 p(this,null,function*(){return yield this.readMetadata(),this.tracks.map(e=>e.trackBacking)})}getMimeType(){return p(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 p(this,null,function*(){return yield this.readMetadata(),this.metadataTags})}readMetadata(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>p(this,null,function*(){let e=0,t=!1,i=!1;for(;;){let r=this.reader.requestSliceRange(e,8,16);if(Pe(r)&&(r=yield r),!r)break;const n=e,s=Li(r);if(!s)break;if("ftyp"===s.name||"styp"===s.name){const e=Yo(r,4);this.isQuickTime="qt "===e}else{if("moov"===s.name){let e=this.reader.requestSlice(r.filePos,s.contentSize);if(Pe(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){S(null!==this.reader.fileSize);let e=this.reader.requestSlice(this.reader.fileSize-4,4);Pe(e)&&(e=yield e),S(e);const t=Wo(e),i=this.reader.fileSize-t;if(i>=0&&i<=this.reader.fileSize-16){let e=this.reader.requestSliceRange(i,8,16);if(Pe(e)&&(e=yield e),e){const t=Li(e);if(t&&"mfra"===t.name){let i=this.reader.requestSlice(e.filePos,t.contentSize);Pe(i)&&(i=yield i),i&&this.readContiguousBoxes(i)}}}}}))()}copyMetadataFromInitInput(e){return p(this,null,function*(){const t=yield e._getDemuxer();if(t.constructor!==er)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(S(t.info),"video"===t.info.type&&-1!==t.info.width){const e=t;t.trackBacking=new ir(e),this.tracks.push(t)}else if("audio"===t.info.type&&-1!==t.info.numberOfChannels){const e=t;t.trackBacking=new rr(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;S(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&&li.includes(e.info.codec)&&0===r.sampleCompositionTimeOffsets.length){S("audio"===(null==(i=e.info)?void 0:i.type));const t=vi(e.info.codec),n=[],s=[];for(let i=0;ie.startIndex),u=r.sampleTimingEntries[c],d=K(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=P(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)lr(e,r.timestamp);else{const t=K(i,s.moofOffset-1,e=>e.moofOffset);if(-1!==t){const r=i[t];lr(e,r.endTimestamp)}}e.startTimestampIsFinal=!0}const r=K(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 hr(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;ue(t.languageCode)||(t.languageCode=re)}}break;case"hdlr":{const t=this.currentTrack;if(!t)break;e.skip(8);const i=Yo(e,4);"vide"===i?t.info={type:"video",width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:d({},z),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=ge,this.readContiguousBoxes(e.slice(ye,ke.contentSize))}break;case"stsd":{const t=this.currentTrack;if(!t)break;if(null===t.info||t.sampleTable)break;const i=No(e);e.skip(3);const r=Wo(e);for(let n=0;n0&&(1===a?(e.skip(4),l=8*Wo(e),e.skip(8)):2===a&&(e.skip(4),c=Qo(e),o=Wo(e),e.skip(4),l=Wo(e),u=Wo(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=bi;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(pi.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":(ze._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":(ze._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":(ze._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":(ze._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":(ze._warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null):32===e?t.info.codec="pcm-f32be":64===e?t.info.codec="pcm-f64be":(ze._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!==No(e),t.encryptionInfo.defaultPerSampleIvSize=No(e),t.encryptionInfo.defaultKid=H(Mo(e,16)),t.encryptionInfo.defaultIsProtected&&0===t.encryptionInfo.defaultPerSampleIvSize){const i=No(e),r=new Uint8Array(16);r.set(Mo(e,i),0),t.encryptionInfo.defaultConstantIv=r}}break;case"avcC":{const t=this.currentTrack;if(!t)break;if(S(t.info),0===ke.contentSize)break;t.info.codecDescription=Mo(e,ke.contentSize)}break;case"hvcC":{const t=this.currentTrack;if(!t)break;if(S(t.info),0===ke.contentSize)break;t.info.codecDescription=Mo(e,ke.contentSize)}break;case"vpcC":{const i=this.currentTrack;if(!i)break;S("video"===(null==(t=i.info)?void 0:t.type)),e.skip(4);const r=No(e),n=No(e),s=No(e),a=s>>4,o=s>>1&7,l=1&s,c=No(e),u=No(e),d=No(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;S("video"===(null==(i=t.info)?void 0:i.type)),e.skip(1);const o=No(e),l=o>>5,c=31&o,u=No(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=Mo(e,ke.contentSize-4),b=At(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;S("video"===(null==(o=t.info)?void 0:o.type));const i=Yo(e,4);if("nclx"!==i&&"nclc"!==i)break;const r=Lo(e),n=Lo(e),s=Lo(e);let a;"nclx"===i&&(a=Boolean(128&No(e))),t.info.colorSpace={primaries:A[r],transfer:M[n],matrix:O[s],fullRange:a}}break;case"pasp":{const t=this.currentTrack;if(!t)break;S("video"===(null==(l=t.info)?void 0:l.type));const i=Wo(e),r=Wo(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);S(3===No(e)),qi(e),e.skip(2);const i=No(e),r=0!==(64&i),n=0!==(32&i);if(0!==(128&i)&&e.skip(2),r){const t=No(e);e.skip(t)}n&&e.skip(2);S(4===No(e));const s=qi(e),a=e.filePos,o=No(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":ze._warn(`Unsupported audio codec (objectTypeIndication ${o}) - discarding track.`),e.skip(12),s>e.filePos-a){S(5===No(e));const i=qi(e);if(t.info.codecDescription=Mo(e,i),"aac"===t.info.codec){const e=Ke(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;S("audio"===(null==(u=t.info)?void 0:u.type)),t.info.pcmLittleEndian=!!(255&Lo(e))}break;case"pcmC":{const t=this.currentTrack;if(!t)break;S("audio"===(null==(f=t.info)?void 0:f.type)),e.skip(4);const i=No(e);t.info.pcmLittleEndian=Boolean(1&i),t.info.pcmSampleSize=No(e)}break;case"dOps":{const t=this.currentTrack;if(!t)break;S("audio"===(null==(m=t.info)?void 0:m.type)),e.skip(1);const i=No(e),r=Lo(e),n=Wo(e),s=Uo(e),a=No(e);let o;o=0!==a?Mo(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;S("audio"===(null==(p=t.info)?void 0:p.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=Mo(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;S("audio"===(null==(g=t.info)?void 0:g.type));const i=Mo(e,3),r=new He(i),n=r.readBits(2);r.skipBits(8);const s=r.readBits(3),a=r.readBits(1);n<3&&(t.info.sampleRate=Ge[n]),t.info.numberOfChannels=qt[s]+a}break;case"dec3":{const t=this.currentTrack;if(!t)break;S("audio"===(null==(k=t.info)?void 0:k.type));const i=(e=>{if(e.length<2)return null;const t=new He(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}})(Mo(e,ke.contentSize));if(!i){ze._warn("Invalid dec3 box contents, ignoring.");break}const r=Kt(i);null!==r&&(t.info.sampleRate=r),t.info.numberOfChannels=Xt(i)}break;case"ddts":{const t=this.currentTrack;if(!t)break;S("audio"===(null==(y=t.info)?void 0:y.type));const i=(e=>{if(e.length<20)return null;const t=E(e),i=t.getUint32(0);if(0===i)return null;const r=new He(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=ai(o):ae.id===i);if(!r)break;const n=Wo(e),s=(12&n)>>2,a=3&n,o=[No,Lo,zo,Wo],l=o[(48&n)>>4],c=o[s],u=o[a],d=Wo(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!=(T=null==d?void 0:d.defaultSampleDescriptionIndex)?T:null,defaultSampleDuration:null!=(v=null==d?void 0:d.defaultSampleDuration)?v:null,defaultSampleSize:null!=(I=null==d?void 0:d.defaultSampleSize)?I:null,defaultSampleFlags:null!=(x=null==d?void 0:d.defaultSampleFlags)?x:null,startTimestamp:null,encryptionAuxInfo:null},i?u.currentFragmentState.baseDataOffset=Ko(e):l&&(u.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),r&&(u.currentFragmentState.sampleDescriptionIndex=Wo(e)),n&&(u.currentFragmentState.defaultSampleDuration=Wo(e)),s&&(u.currentFragmentState.defaultSampleSize=Wo(e)),a&&(u.currentFragmentState.defaultSampleFlags=Wo(e)),o&&(u.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{const t=this.currentTrack;if(!t)break;S(t.currentFragmentState);const i=No(e);e.skip(3);const r=0===i?Wo(e):Ko(e);t.currentFragmentState.startTimestamp=r}break;case"trun":{const t=this.currentTrack;if(!t)break;S(this.currentFragment),S(t.currentFragmentState);const i=No(e),r=zo(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=Wo(e);let d=null;n&&(d=Vo(e));let h,f=null;s&&(f=Wo(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=Mo(e,r));const s=dr(t);s.defaultSampleInfoSize=i,s.sampleSizes=n,s.sampleCount=r}break;case"saio":{const t=this.currentTrack;if(!t||!t.encryptionInfo)break;const i=No(e);if(1&zo(e)){const i=Yo(e,4),r=Wo(e);if(i!==t.encryptionInfo.scheme||0!==r)break}const r=Wo(e);if(0===r)break;r>1&&ze._warn("Multiple saio entries are not supported; using the first offset only.");let n=0===i?Wo(e):Number(Ko(e));this.currentFragment&&(n+=this.currentFragment.moofOffset);dr(t).offset=n}break;case"senc":{const t=this.currentTrack;if(!t||!t.encryptionInfo)break;S(this.currentFragment);const i=this.currentFragment.trackData.get(t.id);if(!i)break;e.skip(1);const r=zo(e),n=Boolean(2&r),s=Wo(e),a=t.encryptionInfo.defaultPerSampleIvSize;S(null!==a);for(let o=0;o0?r.set(Mo(e,a),0):r.set(t.encryptionInfo.defaultConstantIv,0);let s=null;if(n){const t=Lo(e);s=[];for(let i=0;i0&&(null!=(ce=this.metadataTags).trackNumber||(ce.trackNumber=t)),i&&Number.isInteger(i)&&i>0&&(null!=(de=this.metadataTags).tracksTotal||(de.tracksTotal=i))}break;case"trkn":if(n instanceof Uint8Array&&n.length>=6){const e=E(n),t=e.getUint16(2,!1),i=e.getUint16(4,!1);t>0&&(null!=(he=this.metadataTags).trackNumber||(he.trackNumber=t)),i>0&&(null!=(fe=this.metadataTags).tracksTotal||(fe.tracksTotal=i))}break;case"disc":case"disk":if(n instanceof Uint8Array&&n.length>=6){const e=E(n),t=e.getUint16(2,!1),i=e.getUint16(4,!1);t>0&&(null!=(me=this.metadataTags).discNumber||(me.discNumber=t)),i>0&&(null!=(pe=this.metadataTags).discsTotal||(pe.discsTotal=i))}}}}}return e.filePos=be,!0}}class tr{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 p(this,null,function*(){var e;const t=this.internalTrack;if(t.durationInMediaTimescale<=0)return null;S(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 p(this,null,function*(){return null})}getFirstPacket(e){return p(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 ne(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}getPacket(e,t){return p(this,null,function*(){const i=this.mapTimestampIntoTimescale(e),r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),n=nr(r,i),s=yield this.fetchPacketForSampleIndex(n,t);return ur(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=K(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=Y(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 S(-1!==e),{sampleIndex:e,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)})}fetchPacketForSampleIndex(e,t){return p(this,null,function*(){if(-1===e)return null;const i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),r=ar(i,e);if(!r)return null;let n;if(t.metadataOnly)n=Di;else{let t=this.internalTrack.demuxer.reader.requestSlice(r.sampleOffset,r.sampleSize);if(Pe(t)&&(t=yield t),!t)return null;if(n=Mo(t,r.sampleSize),this.internalTrack.encryptionInfo){let t=null;if(this.internalTrack.encryptionAuxInfo){const i=yield hr(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);ee.timestamp),f=-1!==h?this.internalTrack.fragmentLookupTable[h]:null,m=K(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(Pe(e)&&(e=yield e),!e)break;const i=k,s=Li(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.moofOffsetp(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&&Dt(e.data)}}else{const e=yield this.getFirstPacket({}),t=e&&At(e.data);t&&(this.internalTrack.info.av1CodecInfo=t)}else{const t=yield this.getFirstPacket({}),i=t&&Rt(t.data);i&&(this.internalTrack.info.vp9CodecInfo=h(d({},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&&bt(e.data)}else{const e=yield this.getFirstPacket({});this.internalTrack.info.avcCodecInfo=e&&ct(e.data)}if(!L(this.internalTrack.info.colorSpace)){const e=ki(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:gi(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 rr extends tr{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 p(this,null,function*(){var e;return this.internalTrack.info.codec?null!=(e=this.decoderConfigPromise)?e:this.decoderConfigPromise=(()=>p(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&&ri(e.data)}return{codec:yi(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 nr=(e,t)=>{if(e.presentationTimestamps){const i=K(e.presentationTimestamps,t,e=>e.presentationTimestamp);return-1===i?-1:e.presentationTimestamps[i].sampleIndex}{const i=K(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)}},sr=(e,t)=>{var i;if(!e.keySampleIndices)return nr(e,t);if(e.presentationTimestamps){const i=K(e.presentationTimestamps,t,e=>e.presentationTimestamp);if(-1===i)return-1;for(let t=i;t>=0;t--){const i=e.presentationTimestamps[t].sampleIndex;if(-1!==j(e.keySampleIndices,i,e=>e))return i}return-1}{const r=nr(e,t),n=K(e.keySampleIndices,r,e=>e);return null!=(i=e.keySampleIndices[n])?i:-1}},ar=(e,t)=>{const i=K(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=K(e.sampleCompositionTimeOffsets,t,e=>e.startIndex),a=e.sampleCompositionTimeOffsets[s];a&&t-a.startIndexe.startSampleIndex),c=e.sampleToChunk[l];S(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)}},or=(e,t)=>{var i;if(!e.keySampleIndices)return t+1;const r=K(e.keySampleIndices,t,e=>e);return null!=(i=e.keySampleIndices[r+1])?i:-1},lr=(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},cr=e=>{const[t,i]=e,r=Math.atan2(i,t);return Number.isFinite(r)?r*(180/Math.PI):0},ur=e=>0===e.sampleSizes.length,dr=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}},hr=(e,t,i)=>p(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{S(i.sampleSizes);for(let e=0;e0?i.defaultSampleInfoSize:i.sampleSizes[e],o=new Uint8Array(16);s>0?o.set(Mo(n,s),0):o.set(t.defaultConstantIv,0);let l=null;if(r>s){const e=Lo(n);l=[];for(let t=0;te.defaultConstantIv?{iv:e.defaultConstantIv,subsamples:null}:null,mr=(e,t,i,r)=>p(null,null,function*(){var n;S(e.encryptionInfo);const s=e.encryptionInfo;S(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=p(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{S(e.length%2===0);const t=new Uint8Array(e.length/2);for(let i=0;ip(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=>p(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);S(null!==t.defaultCryptByteBlock&&null!==t.defaultSkipByteBlock);const o=kr(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}),gr=(e,t,i,r)=>{const n=new Zi;n.init({key:e,iv:i.iv});const s=t.defaultCryptByteBlock,a=t.defaultSkipByteBlock;if(S(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 yr,br;(br=yr||(yr={}))[br.EBML=440786851]="EBML",br[br.EBMLVersion=17030]="EBMLVersion",br[br.EBMLReadVersion=17143]="EBMLReadVersion",br[br.EBMLMaxIDLength=17138]="EBMLMaxIDLength",br[br.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",br[br.DocType=17026]="DocType",br[br.DocTypeVersion=17031]="DocTypeVersion",br[br.DocTypeReadVersion=17029]="DocTypeReadVersion",br[br.Void=236]="Void",br[br.Segment=408125543]="Segment",br[br.SeekHead=290298740]="SeekHead",br[br.Seek=19899]="Seek",br[br.SeekID=21419]="SeekID",br[br.SeekPosition=21420]="SeekPosition",br[br.Duration=17545]="Duration",br[br.Info=357149030]="Info",br[br.TimestampScale=2807729]="TimestampScale",br[br.MuxingApp=19840]="MuxingApp",br[br.WritingApp=22337]="WritingApp",br[br.Tracks=374648427]="Tracks",br[br.TrackEntry=174]="TrackEntry",br[br.TrackNumber=215]="TrackNumber",br[br.TrackUID=29637]="TrackUID",br[br.TrackType=131]="TrackType",br[br.FlagEnabled=185]="FlagEnabled",br[br.FlagDefault=136]="FlagDefault",br[br.FlagForced=21930]="FlagForced",br[br.FlagOriginal=21934]="FlagOriginal",br[br.FlagHearingImpaired=21931]="FlagHearingImpaired",br[br.FlagVisualImpaired=21932]="FlagVisualImpaired",br[br.FlagCommentary=21935]="FlagCommentary",br[br.FlagLacing=156]="FlagLacing",br[br.Name=21358]="Name",br[br.Language=2274716]="Language",br[br.LanguageBCP47=2274717]="LanguageBCP47",br[br.CodecID=134]="CodecID",br[br.CodecPrivate=25506]="CodecPrivate",br[br.CodecDelay=22186]="CodecDelay",br[br.SeekPreRoll=22203]="SeekPreRoll",br[br.DefaultDuration=2352003]="DefaultDuration",br[br.Video=224]="Video",br[br.PixelWidth=176]="PixelWidth",br[br.PixelHeight=186]="PixelHeight",br[br.DisplayWidth=21680]="DisplayWidth",br[br.DisplayHeight=21690]="DisplayHeight",br[br.DisplayUnit=21682]="DisplayUnit",br[br.AlphaMode=21440]="AlphaMode",br[br.Audio=225]="Audio",br[br.SamplingFrequency=181]="SamplingFrequency",br[br.Channels=159]="Channels",br[br.BitDepth=25188]="BitDepth",br[br.SimpleBlock=163]="SimpleBlock",br[br.BlockGroup=160]="BlockGroup",br[br.Block=161]="Block",br[br.BlockAdditions=30113]="BlockAdditions",br[br.BlockMore=166]="BlockMore",br[br.BlockAdditional=165]="BlockAdditional",br[br.BlockAddID=238]="BlockAddID",br[br.BlockDuration=155]="BlockDuration",br[br.ReferenceBlock=251]="ReferenceBlock",br[br.Cluster=524531317]="Cluster",br[br.Timestamp=231]="Timestamp",br[br.Cues=475249515]="Cues",br[br.CuePoint=187]="CuePoint",br[br.CueTime=179]="CueTime",br[br.CueTrackPositions=183]="CueTrackPositions",br[br.CueTrack=247]="CueTrack",br[br.CueClusterPosition=241]="CueClusterPosition",br[br.Colour=21936]="Colour",br[br.MatrixCoefficients=21937]="MatrixCoefficients",br[br.TransferCharacteristics=21946]="TransferCharacteristics",br[br.Primaries=21947]="Primaries",br[br.Range=21945]="Range",br[br.Projection=30320]="Projection",br[br.ProjectionType=30321]="ProjectionType",br[br.ProjectionPoseRoll=30325]="ProjectionPoseRoll",br[br.Attachments=423732329]="Attachments",br[br.AttachedFile=24999]="AttachedFile",br[br.FileDescription=18046]="FileDescription",br[br.FileName=18030]="FileName",br[br.FileMediaType=18016]="FileMediaType",br[br.FileData=18012]="FileData",br[br.FileUID=18094]="FileUID",br[br.Chapters=272869232]="Chapters",br[br.Tags=307544935]="Tags",br[br.Tag=29555]="Tag",br[br.Targets=25536]="Targets",br[br.TargetTypeValue=26826]="TargetTypeValue",br[br.TargetType=25546]="TargetType",br[br.TagTrackUID=25541]="TagTrackUID",br[br.TagEditionUID=25545]="TagEditionUID",br[br.TagChapterUID=25540]="TagChapterUID",br[br.TagAttachmentUID=25542]="TagAttachmentUID",br[br.SimpleTag=26568]="SimpleTag",br[br.TagName=17827]="TagName",br[br.TagLanguage=17530]="TagLanguage",br[br.TagString=17543]="TagString",br[br.TagBinary=17541]="TagBinary",br[br.ContentEncodings=28032]="ContentEncodings",br[br.ContentEncoding=25152]="ContentEncoding",br[br.ContentEncodingOrder=20529]="ContentEncodingOrder",br[br.ContentEncodingScope=20530]="ContentEncodingScope",br[br.ContentCompression=20532]="ContentCompression",br[br.ContentCompAlgo=16980]="ContentCompAlgo",br[br.ContentCompSettings=16981]="ContentCompSettings",br[br.ContentEncryption=20533]="ContentEncryption";const Tr=[yr.EBML,yr.Segment],vr=[yr.SeekHead,yr.Info,yr.Cluster,yr.Tracks,yr.Cues,yr.Attachments,yr.Chapters,yr.Tags],Sr=[...Tr,...vr],wr=16,Pr=e=>{if(e.remainingLength<1)return null;const t=No(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=No(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=Pr(e);if(null===t)return null;if(e.remainingLength{if(e.remainingLength<1)return null;if(255===No(e))return;e.skip(-1);const t=Ir(e);return null===t?null:72057594037927940!==t?t:void 0},Er=e=>{S(e.remainingLength>=2);const t=Cr(e);if(null===t)return null;const i=Br(e);return null===i?null:{id:t,size:i}},_r=(e,t)=>{const i=Mo(e,t);let r=0;for(;r{const i=Mo(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?Go(e):Qo(e)},Ar=(e,t,i,r)=>p(null,null,function*(){const n=new Set(i);let s=t;for(;null===r||ss?r:s,found:!1}}),Dr=(e,t,i,r)=>p(null,null,function*(){const n=c(2,16),s=new Set(i);let a=t;for(;ae.tracks.map(e=>e.trackBacking))})}getMimeType(){return p(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 p(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=d(d({},e),t.metadataTags);return e})}readMetadata(){var e;return null!=(e=this.readMetadataPromise)?e:this.readMetadataPromise=(()=>p(this,null,function*(){let e=0;for(;;){let t=this.reader.requestSliceRange(e,2,wr);if(Pe(t)&&(t=yield t),!t)break;const i=Er(t);if(!i)break;const r=i.id;let n=i.size;const s=t.filePos;if(r===yr.EBML){Gr(n);let e=this.reader.requestSlice(s,n);if(Pe(e)&&(e=yield e),!e)break;this.readContiguousElements(e)}else if(r===yr.Segment){if(yield this.readSegment(s,n),void 0===n)break;if(null===this.reader.fileSize)break}else if(r===yr.Cluster){if(null===this.reader.fileSize)break;if(void 0===n){n=(yield Ar(this.reader,s,Sr,this.reader.fileSize)).pos-s}const e=P(this.segments);e&&(e.elementEndPos=s+n)}Gr(n),e=s+n}}))()}readSegment(e,t){return p(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=rn[l].flag;this.currentSegment[e]=!0,Gr(a);let t=this.reader.requestSlice(o,a);Pe(t)&&(t=yield t),t&&this.readContiguousElements(t)}else if(s===yr.Tags||s===yr.Attachments){s===yr.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,Gr(a);let e=this.reader.requestSlice(o,a);Pe(e)&&(e=yield e),e&&this.readContiguousElements(e)}else if(s===yr.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=rn.find(e=>e.id===t.id);if(!i)continue;if(this.currentSegment[i.flag])continue;let r=this.reader.requestSliceRange(e+t.segmentPosition,2,wr);if(Pe(r)&&(r=yield r),!r)continue;const n=Er(r);if(!n)continue;const{id:s,size:a}=n;if(s!==i.id)continue;Gr(a),this.currentSegment[i.flag]=!0;let o=this.reader.requestSlice(r.filePos,a);Pe(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 p(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,wr);Pe(r)&&(r=yield r),S(r);const n=e,s=Er(r);S(s);S(s.id===yr.Cluster);let a=s.size;const o=r.filePos;if(void 0===a){a=(yield Ar(this.reader,o,Sr,t.elementEndPos)).pos-o}let l=this.reader.requestSlice(o,a);Pe(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,Sr);c.elementEndPos=e}for(const[,e]of c.trackData){const t=e.track;S(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[P(e.presentationTimestamps).blockIndex];e.startTimestamp=r.timestamp,e.endTimestamp=s.timestamp+s.duration;const a=K(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,f,m,p,g,k,y,b,T,v,P,I,x,C,B,E,R,F,D,N,L,U,q,W,H,V,j,K,X,$,G,Q,Y,J,Z,ee,te,ie,ne,se,ae,oe,le;const ce=Er(e);if(!ce)return!1;if(t&&t.includes(ce.id))return!1;const{id:de,size:he}=ce,fe=e.filePos;switch(Gr(he),de){case yr.DocType:this.isWebM="webm"===_r(e,he);break;case yr.Seek:{if(!this.currentSegment)break;const t={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(t),this.readContiguousElements(e.slice(fe,he)),-1!==t.id&&-1!==t.segmentPosition||this.currentSegment.seekEntries.pop()}break;case yr.SeekID:{const t=null==(i=this.currentSegment)?void 0:i.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.id=xr(e,he)}break;case yr.SeekPosition:{const t=null==(r=this.currentSegment)?void 0:r.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.segmentPosition=xr(e,he)}break;case yr.TimestampScale:if(!this.currentSegment)break;this.currentSegment.timestampScale=xr(e,he),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale;break;case yr.Duration:if(!this.currentSegment)break;this.currentSegment.duration=Fr(e,he);break;case yr.TrackEntry:if(!this.currentSegment)break;if(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:h(d({},We),{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(fe,he)),!this.currentTrack)break;if(this.currentTrack.decodingInstructions.some(e=>{var t;return"decompress"!==(null==(t=e.data)?void 0:t.type)||e.scope!==Jr.Block||e.data.algorithm!==en.HeaderStripping})&&(ze._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===Mr)this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(this.currentTrack.codecId===Nr)this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(t===Or)this.currentTrack.info.codec="vp8";else if(t===Lr)this.currentTrack.info.codec="vp9";else if(t===zr)this.currentTrack.info.codec="av1";else if(t===Ur){const e=this.currentTrack.codecPrivate?_.decode(this.currentTrack.codecPrivate):"";mi.includes(e)&&(this.currentTrack.info.codec="prores",this.currentTrack.info.proresFormat=e)}const e=this.currentTrack;this.currentTrack.trackBacking=new on(e),this.currentSegment.tracks.push(this.currentTrack)}else if("audio"===this.currentTrack.info.type){t===qr?(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===Wr?this.currentTrack.info.codec="mp3":t===Hr?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=bi):t===Vr?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===jr?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Kr?(this.currentTrack.info.codec="ac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Xr?(this.currentTrack.info.codec="eac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===$r?(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 ln(e),this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null;break;case yr.TrackNumber:if(!this.currentTrack)break;this.currentTrack.id=xr(e,he);break;case yr.TrackType:{if(!this.currentTrack)break;const t=xr(e,he);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:d({},z),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 yr.FlagEnabled:if(!this.currentTrack)break;xr(e,he)||(this.currentTrack=null);break;case yr.FlagDefault:if(!this.currentTrack)break;this.currentTrack.disposition.default=!!xr(e,he);break;case yr.FlagForced:if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!xr(e,he);break;case yr.FlagOriginal:if(!this.currentTrack)break;this.currentTrack.disposition.original=!!xr(e,he);break;case yr.FlagHearingImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!xr(e,he);break;case yr.FlagVisualImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!xr(e,he);break;case yr.FlagCommentary:if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!xr(e,he);break;case yr.CodecID:if(!this.currentTrack)break;this.currentTrack.codecId=_r(e,he);break;case yr.CodecPrivate:if(!this.currentTrack)break;this.currentTrack.codecPrivate=Mo(e,he);break;case yr.DefaultDuration:if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=xr(e,he);break;case yr.Name:if(!this.currentTrack)break;this.currentTrack.name=Rr(e,he);break;case yr.Language:if(!this.currentTrack)break;if(this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=_r(e,he),ue(this.currentTrack.languageCode)||(this.currentTrack.languageCode=re);break;case yr.LanguageBCP47:{if(!this.currentTrack)break;const t=_r(e,he).split("-")[0];this.currentTrack.languageCode=t||re,this.currentTrack.hasLanguageBcp47=!0}break;case yr.Video:if("video"!==(null==(s=null==(n=this.currentTrack)?void 0:n.info)?void 0:s.type))break;this.readContiguousElements(e.slice(fe,he));break;case yr.PixelWidth:if("video"!==(null==(o=null==(a=this.currentTrack)?void 0:a.info)?void 0:o.type))break;this.currentTrack.info.width=xr(e,he);break;case yr.PixelHeight:if("video"!==(null==(c=null==(l=this.currentTrack)?void 0:l.info)?void 0:c.type))break;this.currentTrack.info.height=xr(e,he);break;case yr.DisplayWidth:if("video"!==(null==(f=null==(u=this.currentTrack)?void 0:u.info)?void 0:f.type))break;this.currentTrack.info.displayWidth=xr(e,he);break;case yr.DisplayHeight:if("video"!==(null==(p=null==(m=this.currentTrack)?void 0:m.info)?void 0:p.type))break;this.currentTrack.info.displayHeight=xr(e,he);break;case yr.DisplayUnit:if("video"!==(null==(k=null==(g=this.currentTrack)?void 0:g.info)?void 0:k.type))break;this.currentTrack.info.displayUnit=xr(e,he);break;case yr.AlphaMode:if("video"!==(null==(b=null==(y=this.currentTrack)?void 0:y.info)?void 0:b.type))break;this.currentTrack.info.alphaMode=1===xr(e,he);break;case yr.Colour:if("video"!==(null==(v=null==(T=this.currentTrack)?void 0:T.info)?void 0:v.type))break;this.readContiguousElements(e.slice(fe,he));break;case yr.MatrixCoefficients:{if("video"!==(null==(I=null==(P=this.currentTrack)?void 0:P.info)?void 0:I.type))break;const t=xr(e,he),i=O[t];this.currentTrack.info.colorSpace.matrix=i}break;case yr.Range:{if("video"!==(null==(C=null==(x=this.currentTrack)?void 0:x.info)?void 0:C.type))break;const t=xr(e,he);this.currentTrack.info.colorSpace.fullRange=1===t||2===t?2===t:void 0}break;case yr.TransferCharacteristics:{if("video"!==(null==(E=null==(B=this.currentTrack)?void 0:B.info)?void 0:E.type))break;const t=xr(e,he),i=M[t];this.currentTrack.info.colorSpace.transfer=i}break;case yr.Primaries:{if("video"!==(null==(F=null==(R=this.currentTrack)?void 0:R.info)?void 0:F.type))break;const t=xr(e,he),i=A[t];this.currentTrack.info.colorSpace.primaries=i}break;case yr.Projection:if("video"!==(null==(N=null==(D=this.currentTrack)?void 0:D.info)?void 0:N.type))break;this.readContiguousElements(e.slice(fe,he));break;case yr.ProjectionPoseRoll:{if("video"!==(null==(U=null==(L=this.currentTrack)?void 0:L.info)?void 0:U.type))break;const t=-Fr(e,he);try{this.currentTrack.info.rotation=w(t)}catch(me){}}break;case yr.Audio:if("audio"!==(null==(W=null==(q=this.currentTrack)?void 0:q.info)?void 0:W.type))break;this.readContiguousElements(e.slice(fe,he));break;case yr.SamplingFrequency:if("audio"!==(null==(V=null==(H=this.currentTrack)?void 0:H.info)?void 0:V.type))break;this.currentTrack.info.sampleRate=Fr(e,he);break;case yr.Channels:if("audio"!==(null==(K=null==(j=this.currentTrack)?void 0:j.info)?void 0:K.type))break;this.currentTrack.info.numberOfChannels=xr(e,he);break;case yr.BitDepth:if("audio"!==(null==($=null==(X=this.currentTrack)?void 0:X.info)?void 0:$.type))break;this.currentTrack.info.bitDepth=xr(e,he);break;case yr.CuePoint:if(!this.currentSegment)break;this.readContiguousElements(e.slice(fe,he)),this.currentCueTime=null;break;case yr.CueTime:this.currentCueTime=xr(e,he);break;case yr.CueTrackPositions:{if(null===this.currentCueTime)break;S(this.currentSegment);const t={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(t),this.readContiguousElements(e.slice(fe,he)),-1!==t.trackId&&-1!==t.clusterPosition||this.currentSegment.cuePoints.pop()}break;case yr.CueTrack:{const t=null==(G=this.currentSegment)?void 0:G.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;t.trackId=xr(e,he)}break;case yr.CueClusterPosition:{const t=null==(Q=this.currentSegment)?void 0:Q.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;S(this.currentSegment),t.clusterPosition=this.currentSegment.dataStartPos+xr(e,he)}break;case yr.Timestamp:if(!this.currentCluster)break;this.currentCluster.timestamp=xr(e,he);break;case yr.SimpleBlock:{if(!this.currentCluster)break;const t=Ir(e);if(null===t)break;const i=this.getTrackDataInCluster(this.currentCluster,t);if(!i)break;const r=Uo(e),n=No(e),s=n>>1&3;let a=!!(128&n);"audio"===(null==(Y=i.track.info)?void 0:Y.type)&&i.track.info.codec&&(a=!0);const o=Mo(e,he-(e.filePos-fe)),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 yr.BlockGroup:if(!this.currentCluster)break;this.readContiguousElements(e.slice(fe,he)),this.currentBlock=null;break;case yr.Block:{if(!this.currentCluster)break;const t=Ir(e);if(null===t)break;const i=this.getTrackDataInCluster(this.currentCluster,t);if(!i)break;const r=Uo(e),n=No(e)>>1&3,s=Mo(e,he-(e.filePos-fe)),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 yr.BlockAdditions:this.readContiguousElements(e.slice(fe,he));break;case yr.BlockMore:if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(fe,he)),this.currentBlockAdditional.data&&1===this.currentBlockAdditional.addId&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null;break;case yr.BlockAdditional:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=Mo(e,he);break;case yr.BlockAddID:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=xr(e,he);break;case yr.BlockDuration:if(!this.currentBlock)break;this.currentBlock.duration=xr(e,he);break;case yr.ReferenceBlock:if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1;break;case yr.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(fe,he));break;case yr.Targets:this.readContiguousElements(e.slice(fe,he));break;case yr.TargetTypeValue:50!==xr(e,he)&&(this.currentTagTargetIsMovie=!1);break;case yr.TagTrackUID:case yr.TagEditionUID:case yr.TagChapterUID:case yr.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case yr.SimpleTag:if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(fe,he));break;case yr.TagName:this.currentSimpleTagName=Rr(e,he);break;case yr.TagString:{if(!this.currentSimpleTagName)break;const t=Rr(e,he);this.processTagValue(this.currentSimpleTagName,t)}break;case yr.TagBinary:{if(!this.currentSimpleTagName)break;const t=Mo(e,he);this.processTagValue(this.currentSimpleTagName,t)}break;case yr.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(fe,he));const t=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(null!=t.raw||(t.raw={}),t.raw[this.currentAttachedFile.fileUid.toString()]=new qe(this.currentAttachedFile.fileData,null!=(J=this.currentAttachedFile.fileMediaType)?J:void 0,null!=(Z=this.currentAttachedFile.fileName)?Z:void 0,null!=(ee=this.currentAttachedFile.fileDescription)?ee:void 0)),(null==(te=this.currentAttachedFile.fileMediaType)?void 0:te.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!=(ie=this.currentAttachedFile.fileName)?ie:void 0,description:null!=(ne=this.currentAttachedFile.fileDescription)?ne:void 0})}this.currentAttachedFile=null}break;case yr.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 yr.ContentEncoding:this.currentDecodingInstruction={order:0,scope:Jr.Block,data:null},this.readContiguousElements(e.slice(fe,he)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case yr.ContentEncodingOrder:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=xr(e,he);break;case yr.ContentEncodingScope:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=xr(e,he);break;case yr.ContentCompression:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:en.Zlib,settings:null},this.readContiguousElements(e.slice(fe,he));break;case yr.ContentCompAlgo:if("decompress"!==(null==(ae=null==(se=this.currentDecodingInstruction)?void 0:se.data)?void 0:ae.type))break;this.currentDecodingInstruction.data.algorithm=xr(e,he);break;case yr.ContentCompSettings:if("decompress"!==(null==(le=null==(oe=this.currentDecodingInstruction)?void 0:oe.data)?void 0:le.type))break;this.currentDecodingInstruction.data.settings=Mo(e,he);break;case yr.ContentEncryption:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}return e.filePos=fe+he,!0}decodeBlockData(e,t){S(e.decodingInstructions.length>0);let i=t;for(const r of e.decodingInstructions)if(S(r.data),"decompress"===r.data.type)if(r.data.algorithm===en.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 p(this,null,function*(){if(e.duration<=0)return null;let t=null;for(const r of e.tracks){S(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 an{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 p(this,null,function*(){return this.internalTrack.demuxer.getDurationFromMetadata(this.internalTrack.segment)})}getLiveRefreshInterval(){return p(this,null,function*(){return null})}getFirstPacket(e){return p(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 ne(e*this.internalTrack.segment.timestampFactor)}getPacket(e,t){return p(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=K(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=Y(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 S(-1!==e),{blockIndex:e,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)})}fetchPacketInCluster(e,t,i){return p(this,null,function*(){var r,n;if(-1===t)return null;const s=e.trackData.get(this.internalTrack.id).blocks[t];if(S(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);E(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?Di: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?Di:s.mainAdditional,c.alphaByteLength=s.mainAdditional.byteLength);const u=new Mi(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 p(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=K(this.internalTrack.cuePoints,i,e=>e.time),p=-1!==m?this.internalTrack.cuePoints[m]:null,g=K(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,wr);if(Pe(e)&&(e=yield e),!e)break;const i=b,s=Er(e);if(!s||!vr.includes(s.id)&&s.id!==yr.Void){const e=yield Dr(c.reader,i,vr,Math.min(null!=(o=u.elementEndPos)?o:1/0,i+nn));if(e){b=e;continue}break}const a=s.id;let l=s.size;const m=e.filePos;if(a===yr.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){S(a!==yr.Cluster);l=(yield Ar(c.reader,m,Sr,u.elementEndPos)).pos-m}const p=m+l;if(null===u.elementEndPos){let e=c.reader.requestSliceRange(p,2,wr);if(Pe(e)&&(e=yield e),!e)break;if(Cr(e)===yr.Segment){u.elementEndPos=p;break}}b=p}if(p&&(!h||h.elementStartPosp(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?ct(s.data):null,hevcCodecInfo:"hevc"===this.internalTrack.info.codec&&s?bt(s.data):null,vp9CodecInfo:"vp9"===this.internalTrack.info.codec&&s?Rt(s.data):null,av1CodecInfo:"av1"===this.internalTrack.info.codec&&s?At(s.data):null,proresCodecInfo:"prores"===this.internalTrack.info.codec&&s?Dt(s.data):null,proresFormat:this.internalTrack.info.proresFormat};if(!L(this.internalTrack.info.colorSpace)){const n=ki(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:gi(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 ln extends an{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 p(this,null,function*(){var e;return this.internalTrack.info.codec?null!=(e=this.decoderConfigPromise)?e:this.decoderConfigPromise=(()=>p(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&&ri(e.data)}return{codec:yi({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 cn=(e,t,i,r=null)=>p(null,null,function*(){const n=c(2,16);let s=t;for(;null===i||s=4;){const t=a.filePos,i=Wo(a),n=null!==e.fileSize?e.fileSize-s:null,o=Bi(i,n);if(o.header&&(!r||o.header.sampleRate===r.sampleRate&&o.header.mpegVersionId===r.mpegVersionId&&o.header.layer===r.layer&&Fi(o.header.channel)===Fi(r.channel)))return{header:o.header,startPos:s};a.filePos=t+o.bytesAdvanced,s=a.filePos}}return null});class un extends Ai{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 q,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}readMetadata(){return p(this,null,function*(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>p(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 dn(this)]}))()})}advanceReader(){return p(this,null,function*(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,nl);if(Pe(e)&&(e=yield e),!e)return void(this.lastSampleLoaded=!0);const t=ll(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}const e=yield cn(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=Ci(t.mpegVersionId,t.channel);let r=this.reader.requestSlice(e.startPos+i,4);if(Pe(r)&&(r=yield r),r){const n=Wo(r);if(n===Ii||n===xi){if(this.xingFrameHeader||(this.xingFrameHeader=t,this.xingFrameHeaderPos=e.startPos),!this.xingData){let t=this.reader.requestSlice(e.startPos+i+4,12);if(Pe(t)&&(t=yield t),t){const e=Mo(t,12),i=E(e),r=i.getUint32(0,!1);this.xingData={frameCount:r&_i.FrameCount?i.getUint32(4,!1):null,fileSize:r&_i.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 p(this,null,function*(){return"audio/mpeg"})}getTrackBackings(){return p(this,null,function*(){return yield this.readMetadata(),this.trackBackings})}getMetadataTags(){return p(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,nl);if(Pe(i)&&(i=yield i),!i)break;const r=ll(i);if(!r)break;t=!0;let n=this.reader.requestSlice(i.filePos,r.size);if(Pe(n)&&(n=yield n),!n)break;cl(n,r,this.metadataTags),e=i.filePos+r.size}if(!t&&null!==this.reader.fileSize&&this.reader.fileSize>=rl){let e=this.reader.requestSlice(this.reader.fileSize-rl,rl);Pe(e)&&(e=yield e),S(e);"TAG"===Yo(e,3)&&al(e,this.metadataTags)}return this.metadataTags}finally{e()}})}}class dn{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return S(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 p(this,null,function*(){const e=this.demuxer;if(S(null!==e.firstFrameHeader),S(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 p(this,null,function*(){const i=yield this.demuxer.readingMutex.acquire();try{for(;;){const i=K(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 mn=e=>{const t=E(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},pn=(e,t,i)=>{let r=0,n=null;if(e.length>0)if("vorbis"===t.codec){S(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:Mt[t]*r}})(e).durationInSamples}return{durationInSamples:r,vorbisBlockSize:n}},gn=27,kn=282,yn=e=>{const t=e.filePos;if(Ho(e)!==hn)return null;e.skip(1);const i=No(e),r=$o(e),n=Ho(e),s=Ho(e),a=Ho(e),o=No(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}},bn=(e,t)=>{for(;e.filePos>>8&255)===i||(t>>>16&255)===i||(t>>>24&255)===i){if(e.skip(-4),t===hn)return!0;e.skip(1)}}return!1};class Tn extends Ai{constructor(e){super(e),this.metadataPromise=null,this.bitstreams=[],this.trackBackings=[],this.metadataTags={},this.reader=e._reader}readMetadata(){return p(this,null,function*(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>p(this,null,function*(){let e=0;for(;;){let t=this.reader.requestSliceRange(e,gn,kn);if(Pe(t)&&(t=yield t),!t)break;const i=yn(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 vn(t,this)))}}))()})}readVorbisMetadata(e,t){return p(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=E(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:Nt(n.data).modeBlockflags},Ut(r.data.subarray(7),this.metadataTags)})}readOpusMetadata(e,t){return p(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=E(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=bi,t.codecInfo.opusInfo={preSkip:n.preSkip},Ut(r.data.subarray(8),this.metadataTags)})}readPacket(e,t){return p(this,null,function*(){S(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 p(this,null,function*(){return yield this.readMetadata(),this.trackBackings})}getMetadataTags(){return p(this,null,function*(){return yield this.readMetadata(),this.metadataTags})}}class vn{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new q,this.internalSampleRate="opus"===e.codecInfo.codec?bi:e.sampleRate}getType(){return"audio"}getId(){return this.bitstream.serialNumber}getNumber(){const e=this.demuxer.trackBackings.findIndex(e=>e.bitstream===this.bitstream);return S(-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 p(this,null,function*(){return null})}getLiveRefreshInterval(){return p(this,null,function*(){return null})}getCodec(){return this.bitstream.codecInfo.codec}getInternalCodecId(){return null}getDecoderConfig(){return p(this,null,function*(){var e;return S(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 re}getDisposition(){return h(d({},We),{primary:!1})}granulePositionToTimestampInSamples(e){return"opus"===this.bitstream.codecInfo.codec?(S(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,i){if(!e)return null;const{durationInSamples:r,vorbisBlockSize:n}=pn(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),s=new Mi(i.metadataOnly?Di: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 p(this,null,function*(){S(this.bitstream.lastMetadataPacket);const t=yield this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let i=0;"opus"===this.bitstream.codecInfo.codec&&(S(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 p(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 p(this,null,function*(){var i,r;if(null===this.demuxer.reader.fileSize)return this.getPacketSequential(e,t);const n=ne(e*this.internalSampleRate);if(0===n)return this.getFirstPacket(t);if(n<0)return null;S(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,gn,kn);Pe(t)&&(t=yield t),S(t);const i=yn(t);S(i),u=i,u.serialNumber===this.bitstream.serialNumber&&d.push(u)}S(-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:Di,endPage:p,endSegmentIndex:g};if(yield this.demuxer.findNextPacketStart(e)){const e=wn(d,u,m);S(e);const t=Sn(d,e.page,e.segmentIndex);t&&(u=t.page,m=t.segmentIndex)}else for(;;){const e=wn(d,u,m);if(!e)break;const t=Sn(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;){S(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 p(this,null,function*(){const i=yield this.sequentialScanMutex.acquire();try{const i=ne(e*this.internalSampleRate);e=i/this.internalSampleRate;const r=K(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);S(e),this.sequentialScanCache.length>0&&S(P(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 Sn=(e,t,i)=>{let r=t,n=i;e:for(;;){for(n--;n>=0;n--){if(r.lacingValues[n]<255){n++;break e}}S(-1===n);if(!(1&r.headerType)){n=0;break}const t=Q(e,e=>e.headerStartPos{if(i>0)return{page:t,segmentIndex:i-1};const r=Q(e,e=>e.headerStartPosp(this,null,function*(){var e,t;let i=this.reader.requestSlice(0,12);Pe(i)&&(i=yield i),S(i);const r=Yo(i,4),n="RIFX"!==r,s="RF64"===r,a=qo(i,n);let o=s?this.reader.fileSize:Math.min(a+8,null!=(e=this.reader.fileSize)?e:1/0);if("WAVE"!==Yo(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=Oo(r,i),s=t-18;if(Math.min(s,e)>=22&&n===Pn.EXTENSIBLE){r.skip(6);const e=Mo(r,16);n=e[0]|e[1]<<8}}if(n!==Pn.MULAW&&n!==Pn.ALAW||(l=8),n!==Pn.PCM&&n!==Pn.IEEE_FLOAT&&n!==Pn.ALAW&&n!==Pn.MULAW)throw new Error(`Unsupported WAVE codec (format tag ${n}). Only integer/float PCM, A-law, and \u03bc-law are supported.`);if(n===Pn.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===Pn.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 p(this,null,function*(){var r,n,s,a,o,l,c,u,d,h,f;let m=this.reader.requestSlice(e,t);if(Pe(m)&&(m=yield m),!m)return;const p=Yo(m,4);if("INFO"!==p&&"INF0"!==p)return;let g=m.filePos;for(;g<=e+t-8;){m.filePos=g;const e=Yo(m,4),t=qo(m,i),p=Mo(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 p(this,null,function*(){let i=this.reader.requestSlice(e,t);if(Pe(i)&&(i=yield i),!i)return;const r=ll(i);if(r){const n=t-nl;if(r.size=Math.min(r.size,n),r.size>0){const t=i.slice(e+nl,r.size);cl(t,r,this.metadataTags)}}})}getCodec(){if(S(this.audioInfo),this.audioInfo.format===Pn.MULAW)return"ulaw";if(this.audioInfo.format===Pn.ALAW)return"alaw";if(this.audioInfo.format===Pn.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===Pn.IEEE_FLOAT){if(4===this.audioInfo.sampleSizeInBytes)return"pcm-f32";if(8===this.audioInfo.sampleSizeInBytes)return"pcm-f64"}S(!1)}getMimeType(){return p(this,null,function*(){return"audio/wav"})}getTrackBackings(){return p(this,null,function*(){return yield this.readMetadata(),this.trackBackings})}getMetadataTags(){return p(this,null,function*(){return yield this.readMetadata(),this.metadataTags})}}const Cn=2048;class Bn{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return S(this.demuxer.audioInfo),this.demuxer.audioInfo.format}getDecoderConfig(){return p(this,null,function*(){const e=this.demuxer.getCodec();return e?(S(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null})}getNumberOfChannels(){return S(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return S(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return S(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 p(this,null,function*(){return S(-1!==this.demuxer.dataSize),this.demuxer.dataSize/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate})}getLiveRefreshInterval(){return p(this,null,function*(){return null})}getName(){return null}getLanguageCode(){return re}getDisposition(){return d({},We)}getPacketAtIndex(e,t){return p(this,null,function*(){S(e>=0),S(this.demuxer.audioInfo);const i=e*Cn*this.demuxer.audioInfo.blockSizeInBytes;if(i>=this.demuxer.dataSize)return null;const r=Math.min(Cn*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(Pe(e)&&(e=yield e),!e)return null}let n;if(t.metadataOnly)n=Di;else{let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+i,r);Pe(e)&&(e=yield e),S(e),n=Mo(e,r)}const s=e*Cn/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 Mi(n,"key",s,a,e,r)})}getFirstPacket(e){return this.getPacketAtIndex(0,e)}getPacket(e,t){return p(this,null,function*(){S(this.demuxer.audioInfo);const i=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/Cn,(this.demuxer.dataSize-1)/(Cn*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;S(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){S(this.demuxer.audioInfo);const i=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/Cn);return this.getPacketAtIndex(i+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const En=e=>{const t=e.filePos,i=Mo(e,9),r=new He(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}},_n=1024;class Rn extends Ai{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.trackBackings=[],this.readingMutex=new q,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}readMetadata(){return p(this,null,function*(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>p(this,null,function*(){for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)yield this.advanceReader();S(this.firstFrameHeader),this.trackBackings=[new Fn(this)]}))()})}advanceReader(){return p(this,null,function*(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,nl);if(Pe(e)&&(e=yield e),!e)return void(this.lastSampleLoaded=!0);const t=ll(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}let e=this.reader.requestSliceRange(this.lastLoadedPos,7,9);if(Pe(e)&&(e=yield e),!e)return void(this.lastSampleLoaded=!0);const t=En(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=Ve[t.samplingFrequencyIndex];S(void 0!==i);const r=_n/i,n={timestamp:this.nextTimestampInSamples/i,duration:r,dataStart:t.startPos,dataSize:t.frameLength};this.loadedSamples.push(n),this.nextTimestampInSamples+=_n,this.lastLoadedPos=t.startPos+t.frameLength})}getMimeType(){return p(this,null,function*(){return"audio/aac"})}getTrackBackings(){return p(this,null,function*(){return yield this.readMetadata(),this.trackBackings})}getMetadataTags(){return p(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,nl);if(Pe(t)&&(t=yield t),!t)break;const i=ll(t);if(!i)break;let r=this.reader.requestSlice(t.filePos,i.size);if(Pe(r)&&(r=yield r),!r)break;cl(r,i,this.metadataTags),e=t.filePos+i.size}return this.metadataTags}finally{e()}})}}class Fn{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return this.getSampleRate()/_n}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return p(this,null,function*(){return null})}getLiveRefreshInterval(){return p(this,null,function*(){return null})}getName(){return null}getLanguageCode(){return re}getCodec(){return"aac"}getInternalCodecId(){return S(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){S(this.demuxer.firstFrameHeader);const e=je[this.demuxer.firstFrameHeader.channelConfiguration];return S(void 0!==e),e}getSampleRate(){S(this.demuxer.firstFrameHeader);const e=Ve[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return S(void 0!==e),e}getDisposition(){return d({},We)}getDecoderConfig(){return p(this,null,function*(){return S(this.demuxer.firstFrameHeader),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate()}})}getPacketAtIndex(e,t){return p(this,null,function*(){if(-1===e)return null;const i=this.demuxer.loadedSamples[e];if(!i)return null;let r;if(t.metadataOnly)r=Di;else{let e=this.demuxer.reader.requestSlice(i.dataStart,i.dataSize);if(Pe(e)&&(e=yield e),!e)return null;r=Mo(e,i.dataSize)}return new Mi(r,"key",i.timestamp,i.duration,e,i.dataSize)})}getFirstPacket(e){return this.getPacketAtIndex(0,e)}getNextPacket(e,t){return p(this,null,function*(){const i=yield this.demuxer.readingMutex.acquire();try{const i=j(this.demuxer.loadedSamples,e.timestamp,e=>e.timestamp);if(-1===i)throw new Error("Packet was not created from this track.");const r=i+1;for(;r>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)yield this.demuxer.advanceReader();return this.getPacketAtIndex(r,t)}finally{i()}})}getPacket(e,t){return p(this,null,function*(){const i=yield this.demuxer.readingMutex.acquire();try{for(;;){const i=K(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+1p(this,null,function*(){var e;let t=0;for(;;){let e=this.reader.requestSlice(t,nl);if(Pe(e)&&(e=yield e),!e)return void(this.lastSampleLoaded=!0);const i=ll(e);if(!i)break;let r=this.reader.requestSlice(e.filePos,i.size);Pe(r)&&(r=yield r),S(r),cl(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===No(s)){const t=s.filePos;if(No(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=Mo(e,4),n=new He(r);if(32764!==n.readBits(15))return null;if(null===this.blockingBit){S(t);const e=n.readBits(1);this.blockingBit=e}else if(1===this.blockingBit){S(!t);if(1!==n.readBits(1))return null}else{if(0!==this.blockingBit)throw new Error("Invalid blocking bit");S(!t);if(0!==n.readBits(1))return null}const s=(e=>0===e?null:1===e?192:e>=2&&e<=5?144*c(2,e):6===e?"uncommon-u8":7===e?"uncommon-u16":e>=8&&e<=15?c(2,e):null)(n.readBits(4));if(!s)return null;S(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 He(Mo(e,1));for(;1===i.readBits(1);)t++;if(0===t)return i.readBits(7);const r=[],n=t-1,s=new He(Mo(e,n)),a=8-t-1;for(let o=0;oe|t<"uncommon-u16"===t?Lo(e)+1:"uncommon-u8"===t?No(e)+1:"number"===typeof t?t:(J(t),void S(!1)))(e,s),u=((e,t)=>"uncommon-u16"===t?Lo(e):"uncommon-u16-10"===t?10*Lo(e):"uncommon-u8"===t?No(e):"number"===typeof t?t:null)(e,a);if(null===u)return null;if(u!==this.audioInfo.sampleRate)return null;const d=e.filePos-i,h=No(e);e.skip(-d),e.skip(-1);const f=(e=>{let t=0;for(const i of e){t^=i;for(let e=0;e<8;e++)0!==(128&t)?t=t<<1^7:t<<=1,t&=255}return t})(Mo(e,d));return h!==f?null:{num:o,blockSize:l,sampleRate:u}}advanceReader(){return p(this,null,function*(){yield this.readMetadata(),S(null!==this.lastLoadedPos),S(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 Dn{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return S(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return S(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return re}getTimeResolution(){return S(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 p(this,null,function*(){return S(this.demuxer.audioInfo),0===this.demuxer.audioInfo.totalSamples?null:this.demuxer.audioInfo.totalSamples/this.demuxer.audioInfo.sampleRate})}getLiveRefreshInterval(){return p(this,null,function*(){return null})}getDisposition(){return d({},We)}getDecoderConfig(){return p(this,null,function*(){return S(this.demuxer.audioInfo),{codec:"flac",numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}})}getPacket(e,t){return p(this,null,function*(){if(S(this.demuxer.audioInfo),e<0)return null;const i=yield this.demuxer.readingMutex.acquire();try{for(;;){const i=K(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 p(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 p(this,null,function*(){const i=this.demuxer.loadedSamples[e];if(!i)return null;let r;if(t.metadataOnly)r=Di;else{let e=this.demuxer.reader.requestSlice(i.byteOffset,i.byteSize);if(Pe(e)&&(e=yield e),!e)return null;r=Mo(e,i.byteSize)}S(this.demuxer.audioInfo);const n=i.blockOffset/this.demuxer.audioInfo.sampleRate,s=i.blockSize/this.demuxer.audioInfo.sampleRate;return new Mi(r,"key",n,s,e,i.byteSize)})}getFirstPacket(e){return p(this,null,function*(){for(;0===this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)yield this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)})}}const Mn=9e4,Nn=c(2,33),On=188,Ln="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.",zn=new Set([133,134,162]),Un=new Set;class qn extends Ai{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 p(this,null,function*(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>p(this,null,function*(){let e=this.reader.requestSlice(0,205);Pe(e)&&(e=yield e),S(e);const t=Mo(e,205);if(71===t[0]&&71===t[188])this.packetOffset=0,this.packetStride=On;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 He(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=Hn(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 $n(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=ct(r.suppliedPacket.data),!e.info.avcCodecInfo)continue;const t=e.info.avcCodecInfo.sequenceParameterSets[0];S(t);const i=ft(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:A[i.colourPrimaries],transfer:M[i.transferCharacteristics],matrix:O[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=bt(r.suppliedPacket.data),!e.info.hevcCodecInfo)continue;const t=e.info.hevcCodecInfo.arrays.find(e=>e.nalUnitType===Ze.SPS_NUT).nalUnits[0];S(t);const i=yt(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:A[i.colourPrimaries],transfer:M[i.transferCharacteristics],matrix:O[i.matrixCoefficients],fullRange:!!i.fullRangeFlag},e.info.reorderSize=i.maxDecFrameBuffering;break}throw new Error("Unhandled.")}e.info.decoderConfig={codec:gi({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=Ao.tempFromBytes(r.suppliedPacket.data),i=En(t);if(!i)throw new Error("Invalid AAC audio stream; could not read ADTS frame header from first packet.");e.info.aacCodecInfo={isMpeg2:!1,objectType:i.objectType},e.info.numberOfChannels=je[i.channelConfiguration],e.info.sampleRate=Ve[i.samplingFrequencyIndex]}else if("mp3"===e.info.codec){const t=Wo(Ao.tempFromBytes(r.suppliedPacket.data)),i=Bi(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=Fi(i.header.channel),e.info.sampleRate=i.header.sampleRate}else if("ac3"===e.info.codec){const t=Wt(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=qt[t.acmod]+t.lfeon,e.info.sampleRate=Ge[t.fscod]}else if("eac3"===e.info.codec){const t=jt(r.suppliedPacket.data);if(!t)throw new Error("Invalid E-AC-3 audio stream; could not read sync frame from first packet.");const i=Kt(t);if(null===i)throw new Error("Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.");e.info.numberOfChannels=Xt(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:yi({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 He(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&&zn.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:Un.has(t)||(ze._warn(`Note: MPEG-TS streams with stream_type 0x${t.toString(16)} are not currently supported.`),Un.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 He(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 jn(a)):this.trackBackingEntries.push(new Kn(a)))}))()})}getTrackBackings(){return p(this,null,function*(){return yield this.readMetadata(),this.trackBackingEntries})}getMetadataTags(){return p(this,null,function*(){return{}})}getMimeType(){return p(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 p(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!==j(this.sectionEndPositions,r,e=>e)){c=!1;break}}if(c){const e=K(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 p(this,null,function*(){let t=this.reader.requestSlice(e,4);if(Pe(t)&&(t=yield t),!t)return null;if(71!==No(t))throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");const i=Lo(t);return{payloadUnitStartIndicator:i>>14&1,pid:8191&i,adaptationFieldControl:No(t)>>4&3}})}readPacket(e){return p(this,null,function*(){let t=this.reader.requestSlice(e,On);if(Pe(t)&&(t=yield t),!t)return null;const i=Mo(t,On);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>=Nn-t?-Nn:Nn}}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 He(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(Ln);return{sectionStartPos:t.startPos,sectionEndPos:t.endPos,pts:a,randomAccessIndicator:t.randomAccessIndicator}},Hn=(e,t,i)=>{S(null!==t.endPos);const r=Wn(e,t,i);if(!r)return null;const n=new He(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;S(Number.isInteger(l));const c=t.payload.subarray(l,s>0?6+s:t.payload.byteLength);return h(d({},r),{data:c})};class Vn{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++,S(r instanceof Vn),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 re}getDisposition(){return h(d({},We),{primary:!1})}getTimeResolution(){return Mn}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return p(this,null,function*(){return null})}getLiveRefreshInterval(){return p(this,null,function*(){return null})}createEncodedPacket(e,t,i){let r;return r=this.allPacketsAreKeyPackets()||1===e.randomAccessIndicator?"key":"delta",new Mi(i.metadataOnly?Di:e.data,r,e.pts/Mn,Math.max(t/Mn,0),e.sequenceNumber,e.data.byteLength)}getFirstPacket(e){return p(this,null,function*(){const t=this.elementaryStream.firstSection;S(t);const i=Hn(this.elementaryStream.demuxer,t,!0);S(i);const r=new $n(this.elementaryStream,i),n=new Gn(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 p(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);S(s);const a=Hn(n,s,!0);S(a);const o=new $n(this.elementaryStream,a);i=new Gn(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 p(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 p(this,null,function*(){var r,n,s,a,o,l;const c=ne(e*Mn),u=this.elementaryStream.demuxer,{reader:d,seekChunkSize:h}=u,f=this.elementaryStream.pid,m=(e,t,i)=>p(this,null,function*(){let r=e;for(;re.pts),v=-1!==T?b[T]:null;if(v&&c-v.pts<45e3)y=v.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=oe(t*h,u.packetStride)+k.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}}}y=oe(e*h,u.packetStride)+k.sectionStartPos}const w=yield m(y,null!=(r=d.fileSize)?r:1/0,!1);let I=null!=(n=null==w?void 0:w.pesPacketHeader)?n:null;I||(I=k);const x=this.getReorderSize(),C=(e,t)=>p(this,null,function*(){var r,n;const s=yield u.readSection(e,!0);S(s);const a=Hn(u,s,!0);S(a);const o=new $n(this.elementaryStream,a),l=new Gn(this,o);for(;;){if((null!=(n=null==(r=P(l.presentationOrderPackets))?void 0:r.pts)?n:-1/0)>=c)break;if(!(yield l.readNextPacket()))break}const d=Y(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();S(m);const p=this.createEncodedPacket(m.packet,m.duration,i);return this.packetBuffers.set(p,l),this.packetSectionStarts.set(p,m.packet.sectionStartPos),p});if(!t||this.allPacketsAreKeyPackets()){e:for(;;){let e=I.sectionStartPos+u.packetStride;for(;;){const t=yield u.readPacketHeader(e);if(!t)break e;if(t.pid===f&&1===t.payloadUnitStartIndicator){const t=yield u.readSection(e,!1);if(t){const e=Wn(u,t,!1);if(e&&null!==e.pts){if(e.pts>c)break e;I=e,Xn(this.elementaryStream,I);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=Wn(u,t,!1);if(e&&null!==e.pts){I=e;break}}}e-=u.packetStride}}return C(I.sectionStartPos,e=>e.pts<=c)}{let e=y,t=null;const i=!this.elementaryStream.canBeTrustedWithKeyPackets;for(;;){let r=null;const n=e<=k.sectionStartPos;let p,y=null;if(n)p=k,y=g;else{const t=yield m(e,null!=(s=d.fileSize)?s:1/0,i);p=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(;p&&!(null!==t&&p.sectionStartPos>=t);){if(p.pts<=c){let e;if(this.elementaryStream.canBeTrustedWithKeyPackets)e=1===p.randomAccessIndicator;else{S(y);const t=Hn(u,y,!0);S(t);const i=new $n(this.elementaryStream,t);yield i.markNextPacket(),e=1===(null==(l=i.suppliedPacket)?void 0:l.randomAccessIndicator)}e&&(r=p)}if(p.pts>c&&(b=!0),b&&(T++,T>x))break;let e=p.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=Wn(u,t,!1);if(e&&null!==e.pts){p=e,y=t,Xn(this.elementaryStream,p);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=Wn(u,r,!1);if(t&&null!==t.pts){e=t;break}}}t-=u.packetStride}}const t=yield C(e.sectionStartPos,e=>e.pts<=c&&1===e.randomAccessIndicator);return S(t),t}if(n)return null;t=e,e=Math.max(oe(e-k.sectionStartPos-h,u.packetStride)+k.sectionStartPos,k.sectionStartPos)}}})}}class jn extends Vn{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 p(this,null,function*(){return this.elementaryStream.info.colorSpace})}canBeTransparent(){return p(this,null,function*(){return!1})}getDecoderConfig(){return p(this,null,function*(){return S(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig})}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}}class Kn extends Vn{getType(){return"audio"}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}getDecoderConfig(){return p(this,null,function*(){return S(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig})}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 0}}const Xn=(e,t)=>{const i=e.referencePesPackets,r=K(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 S(e),e}bufferData(e){return p(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,S;if("avc"===e)T=nt(b),v=T===Ye.NON_IDR_SLICE||T===Ye.SLICE_DPA||T===Ye.IDR,S=T===Ye.SEI||T===Ye.SPS||T===Ye.PPS||T===Ye.AUD;else{T=kt(b);if(((1&b)<<5|l[g+1]>>3)>0){u+=m;continue}v=T<=Ze.RASL_R||T>=Ze.BLA_W_LP&&T<=21,S=T>=Ze.VPS_NUT&&T<=37||T===Ze.PREFIX_SEI_NUT||T>=41&&T<=44||T>=48&&T<=55}let w=!1;if(v){let t;if("avc"===e){const e=l.subarray(k,k+y),i=I(new He(e));t=!s||i<=a,a=i}else t=l[k]>>7===1;t&&(s?w=!0:s=!0)}else S&&s&&(w=!0);if(w){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);Pe(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=Ht[3*a+n];S(void 0!==o),this.seekTo(e),t=this.ensureBuffered(o),Pe(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(Pe(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=Vt[a];this.seekTo(e),t=this.ensureBuffered(n),Pe(t)&&(t=yield t);const l=256*o,c=Math.round(l*Mn/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(Pe(a)&&(a=yield a),a<18)return;const o=this.readBytes(18),l=ni(o);let c=l?null:si(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);Pe(i)&&(i=yield i),c=null!=(e=si(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(Pe(i)&&(i=yield i),i=0)}readNext(){return p(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(S(-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 p(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 p(this,null,function*(){const e=this.decodeOrderPackets[0];for(S(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 Qn="application/vnd.apple.mpegurl",Yn="#EXT-X-STREAM-INF:",Jn="#EXT-X-I-FRAME-STREAM-INF:",Zn="#EXT-X-MEDIA:",es="#EXTINF:",ts="#EXT-X-MAP:",is="#EXT-X-KEY:",rs="#EXT-X-MEDIA-SEQUENCE:",ns="#EXT-X-BYTERANGE:",ss="#EXT-X-PROGRAM-DATE-TIME:",as="#EXT-X-TARGETDURATION:",os="#EXT-X-PLAYLIST-TYPE:",ls=e=>0===e.length||e.startsWith("#")&&!e.startsWith("#EXT");class cs{constructor(e){this._attributes={};let t="",i="",r=!1,n=!1;for(let s=0;sp(this,null,function*(){const e=[];if(this.trackDeclarations){for(const t of this.trackDeclarations)if("video"===t.type){const i=Re(e,e=>"video"===e.getType())+1;e.push(new hs(this,t,i))}else if("audio"===t.type){const i=Re(e,e=>"audio"===e.getType())+1;e.push(new fs(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=Re(e,e=>"video"===e.getType())+1;e.push(new hs(this,{id:e.length+1,type:"video"},t))}else if("audio"===r.type){const t=Re(e,e=>"audio"===e.getType())+1;e.push(new fs(this,{id:e.length+1,type:"audio"},t))}}return e}))()})}getFirstTimestampForInput(e){return p(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 p(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 ds{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=(()=>p(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 p(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 p(this,null,function*(){return yield this.hydrate(),S(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 p(this,null,function*(){S(e.sequenceNumber>=0),S(this.segmentedInput.firstSegment);const r=yield this.segmentedInput.getMediaOffset(t,i.input),n=t.timestamp-this.segmentedInput.firstSegment.timestamp,s=e.clone({timestamp:ae(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 p(this,null,function*(){var t;yield this.hydrate(),S(this.firstInputTrack),S(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 p(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 p(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 hs extends ds{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 p(this,null,function*(){return this.delegate(()=>this.firstInputTrack._backing.getColorSpace())})}canBeTransparent(){return p(this,null,function*(){return this.delegate(()=>this.firstInputTrack._backing.canBeTransparent())})}getDecoderConfig(){return p(this,null,function*(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())})}}class fs extends ds{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 p(this,null,function*(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())})}}Be();const ms=1/0;"undefined"!==typeof FinalizationRegistry&&new FinalizationRegistry(e=>{e()});class ps extends Ne{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 p(this,null,function*(){var e;if(this._disposed)throw new Ro;return null!=(e=this._sizePromise)?e:this._sizePromise=(()=>p(this,null,function*(){let e=this._getFileSize();return void 0!==e||(yield this._read(0,1,0,ms),e=this._getFileSize(),S(void 0!==e)),e}))()})}getSize(){return p(this,null,function*(){if(this._disposed)throw new Ro;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 Rs(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 gs(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){this._refCount--,0===this._refCount&&(this._dispose(),this._disposed=!0)}}class gs{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;S(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 ks extends ps{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 ps||e instanceof gs))throw new TypeError("requestHandler must return or resolve to a Source or SourceRef.");const i=e instanceof ps?e.ref():e;return(t=i.source)._usedForHls||(t._usedForHls=this._usedForHls),i};return Pe(t)?t.then(i):i(t)}}const ys=(e,t)=>e.path===t.path;class bs extends ks{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 ps?e.ref():e;return this._root=t,this._rootRequest=null,t};Pe(e)?this._rootRequest=e.then(t):(t(e),S(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 Ts="undefined"!==typeof FinalizationRegistry?new FinalizationRegistry(e=>{e.cancel().catch(()=>{})}):null;class vs extends ps{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&&(!Ee(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 _s({maxCacheSize:null!=(i=t.maxCacheSize)?i:8*c(2,20),maxWorkerCount:4,runWorker:this._runWorker.bind(this),onIdleWorkerRemoved:e=>{const t=this._readers.get(e);t&&(this._readers.delete(e),null==Ts||Ts.unregister(e),t.cancel().catch(()=>{}))},prefetchProfile:Es.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 p(this,null,function*(){S(e.strictTarget);let t=this._readers.get(e);if(void 0===t){if("stream"in this._blob&&!ke()&&!1!==this._options.useStreamReader){t=this._blob.slice(e.currentPos).stream().getReader(),null==Ts||Ts.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 ze._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(c(2,e-2),16)},Ps=new Set;class Is extends ks{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&&(!Ee(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 Is(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:ws,this._requestInit=d({},t.requestInit);let a=null;if(null==(r=t.requestInit)?void 0:r.headers){const e=d({},fe(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=Cs(a);e&&(this._offset=e.offset,this._length=e.length)}this._orchestrator=new _s({maxCacheSize:null!=(n=t.maxCacheSize)?n:64*c(2,20),maxWorkerCount:null!=(s=t.parallelism)?s:2,runWorker:this._runWorker.bind(this),prefetchProfile:Es.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:ie(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 Pe(a)?a.then(o):o(a)}_runWorker(e){return p(this,null,function*(){for(var t;;){const r=new AbortController,n=yield me(null!=(t=this._options.fetchFn)?t:fetch,this._url,he(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")||Ps.has(e.origin)||(ze._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.`),Ps.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){ze._error("Error while reading response stream. Attempting to resume.",i),yield Me(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=>p(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;ze._error("Error while reading response stream. Attempting to resume.",s),yield Me(1e3*e);const a=yield me(null!=(n=this._options.fetchFn)?n:fetch,this._url,he(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 Bs(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);Pe(e)?e.then(e=>{e?(S(e.offset===o.start),o.resolve(e.bytes)):o.resolve(null)},e=>o.reject(e)):(S(null===e),o.resolve(null))}}_dispose(){this._orchestrator.dispose(),this._sequentialBacking&&(this._sequentialBacking._disposed=!0,this._sequentialBacking._dispose())}}const xs=/^bytes=(\d+)-(\d*)$/,Cs=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=K(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}=$();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 p(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 Ro);this._pendingSlices.length=0,this._cache.length=0,null==(e=this._reader)||e.cancel()}}const Es={fileSystem:(e,t)=>{const i=c(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=c(2,16);e=Math.max(0,Math.floor((e-r)/r)*r);for(const n of i){const i=8*c(2,20),r=Math.max((n.startPos+n.targetPos)/2,n.targetPos-i);if(xe(e,t,r,n.targetPos)){const e=n.targetPos-n.startPos,r=Math.ceil((e+1)/i)*i,s=c(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+Ss)}}};class _s{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;S(!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);S(a<=e&&t<=o);let l=null;const c=K(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=K(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(S(n<=s),m=h.length&&(l={bytes:h,view:E(h),offset:e}),0===p.length)return S(l),l;const{promise:g,resolve:k,reject:y}=$(),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)}}):(S(h),l=g.then(t=>t&&{bytes:t,view:E(t),offset:e})),l}checkHoleAgainstWorker(e,t,i){const r=c(2,17);if(xe(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);S(-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=K(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=E(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=E(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 Pe(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 Fs=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},As=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 Ds=/^0[xX][0-9a-fA-F]+$/,Ms=/^data:.*;base64,/i;class Ns extends us{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=(()=>p(this,null,function*(){try{const e=this.getRemainingWaitTimeMs();e>0&&(yield Me(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 p(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=Fs(e,yield this.demuxer.input._getSourceUncached({path:this.rootPath,isRoot:!1}),!1),i=new Fo(t.source),r=yield i.requestEntireFile();S(r),l=Jo(r,r.length,{ignore:ls}),t.source instanceof ks&&(this.rootPath=t.source.rootPath)}catch(F){e.error=F,e.hasError=!0}finally{As(e)}}const u=!1!==(null==(e=this.input._formatOptions.hls)?void 0:e.offsetTimestampsByDateTime);let f=!1,m=0,p=null,g=null,k=null,y=0,b=null,T=null,v=null,w=null,I=null,x=null,C=!1,B=null!=(t=P(this.segments))?t:null;const _=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}},R=e=>{y=e,B&&(S(null!==B.sequenceNumber),B.sequenceNumber0&&null!==x&&(m=y*x),C=!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}'.`);g=n}else if(e.startsWith(ts)){const t=new cs(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=_(r)),a&&null===a.offset)throw new Error("Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset.");if(!B){const e={path:_e(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==k?void 0:k.method)&&!k.iv)throw new Error("IV attribute must be set on #EXT-X-KEY tag preceding the #EXT-X-MAP tag.");T={timestamp:m,unixEpochTimestamp:p,firstSegment:null,sequenceNumber:null,location:e,duration:0,encryption:k,initSegment:null,lastProgramDateTimeSeconds:I}}g=null,null===w?v=null:w=null}else if(e.startsWith(is)){const t=new cs(e.slice(11)),i=t.get("method");if("NONE"===i)k=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(!Ds.test(r))throw new Error(`Unsupported IV format '${r}'.`);let e=r.slice(2);e=e.padStart(32,"0"),i=new Uint8Array(Vi);for(let t=0;t=8&&112===i[4]&&115===i[5]&&115===i[6]&&104===i[7]){const e=E(i).getUint32(0);r=Ni(i.subarray(8,Math.min(e,i.length)))}}k={method:i,psshBox:r}}}}else if(e.startsWith(rs)){const t=e.slice(22),i=Number(t);if(!Number.isInteger(i)||i<0)throw new Error(`Invalid EXT-X-MEDIA-SEQUENCE value '${t}'.`);R(i)}else if(e.startsWith(ns)){const t=_(e.slice(17));if(null===t.offset){if(null===v)throw new Error("Invalid M3U8 file; #EXT-X-BYTERANGE without offset requires a previous byte range.");t.offset=v}w=t,v=t.offset+t.length}else if(e.startsWith(ss)){if(B)continue;const t=e.slice(25),i=Date.parse(t);if(!Number.isFinite(i))continue;const r=i/1e3;if(I===r)continue;if(null===I&&this.segments.length>0){const e=P(this.segments),t=r-(e.timestamp+e.duration);for(const i of this.segments)i.unixEpochTimestamp=i.timestamp+t,u&&(i.timestamp=i.unixEpochTimestamp)}I=r,p=r,u&&(m=r)}else if("#EXT-X-DISCONTINUITY"===e)b=null;else if(e.startsWith(as)){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,x=i}else{if("#EXT-X-ENDLIST"===e){this.streamHasEnded=!0;break}if(e.startsWith(os)){"vod"===e.slice(21).toLowerCase()&&(this.streamHasEnded=!0)}}}else{if("#EXTM3U"!==e)throw new Error("Invalid M3U8 file; expected first line to be #EXTM3U.");f=!0}}if(!f)throw new Error("Invalid M3U8 file; no #EXTM3U header.")})}getFirstSegment(){return p(this,null,function*(){var e;return 0===this.segments.length&&(yield this.runUpdateSegments()),null!=(e=this.segments[0])?e:null})}getSegmentAt(e,t){return p(this,null,function*(){0===this.segments.length&&(yield this.runUpdateSegments());let i=!!t.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){const r=K(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=h(d({},this.input._formatOptions),{isobmff:h(d({},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=>Oi(e,i))||(t=[...t,i]),this.input._formatOptions.isobmff.resolveKeyId(h(d({},e),{psshBoxes:t}))})})}),o=new Eo({source:new bs(r.location.path,e=>p(this,null,function*(){var t,i;S(e.isRoot);const n=h(d({},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;S(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=c(2,16),a=new Zi;return new ReadableStream({pull:o=>p(null,null,function*(){r||(a.init(yield t()),r=!0);const l=s+16;let c=e.requestSliceRange(n,0,l);if(Pe(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=Mo(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 Fo(t.source),()=>p(this,null,function*(){const t={stack:[],error:void 0,hasError:!1};try{const i=Fs(t,yield this.input._getSourceCached({path:e.keyUri,isRoot:!1},Bo),!1),r=new Fo(i.source),n=yield r.requestSlice(0,Vi);if(!n)throw new Error("Invalid AES-128 key; expected at least 16 bytes of data.");return{key:Mo(n,Vi),iv:e.iv}}catch(i){t.error=i,t.hasError=!0}finally{As(t)}}),()=>{t.free()});s=new Bs(o).ref()}else S(!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 ia)),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=Fe(this.inputCache,e=>e.age);S(-1!==e),this.inputCache.splice(e,1)}return o}getLiveRefreshInterval(){return p(this,null,function*(){return 0===this.getRemainingWaitTimeMs()&&(yield this.runUpdateSegments()),this.streamHasEnded?null:this.refreshInterval})}}class Os extends Ai{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=(()=>p(this,null,function*(){S(this.input._rootSource instanceof ks);const e=yield this.input._reader.requestEntireFile();S(e);const t=Jo(e,e.length,{ignore:ls}),{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)=>p(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=>p(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"),g=h.some(e=>oi.includes(Si(e))),k=h.some(e=>ci.includes(Si(e)));if(null!==f&&!g){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=_e(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});S(null!==a),h.push(a)}}if(null!==m&&!k){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=_e(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});S(null!==a),h.push(a)}}h=[...new Set(h)];let y=null,b=null;const T=e.attributes.getAsNumber("bandwidth");S(null!==T);const v=e.attributes.getAsNumber("average-bandwidth"),w=e.attributes.get("name");for(const i of h){const d=Si(i);if(null!==d)if(oi.includes(d)){if(null!==y)throw new Error("Unsupported M3U8 file; multiple video codecs found in the CODECS attribute of a variant stream.");y=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:re,lineNumber:e.lineNumber,fullPath:e.fullPath,fullCodecString:y,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:qs(i.attributes),autoselect:qs(i.attributes)||Ws(i.attributes),languageCode:Hs(i.attributes.get("language")),lineNumber:i.lineNumber,fullPath:null!=(c=i.fullPath)?c:e.fullPath,fullCodecString:b,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===re&&(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 zs(u)):this.trackBackings.push(new Us(u));this.internalTracks=l}))()}getTrackBackings(){return p(this,null,function*(){return yield this.readMetadata(),S(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 Ns(this,e,i,null),this.segmentedInputs.push(t),t}getMetadataTags(){return p(this,null,function*(){return{}})}getMimeType(){return p(this,null,function*(){return Qn})}dispose(){if(this.segmentedInputs){for(const e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}}class Ls{constructor(e){this.internalTrack=e,this.hydrationPromise=null}hydrate(){var e;return null!=(e=this.hydrationPromise)?e:this.hydrationPromise=(()=>p(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 zs){for(const r of i)if((yield r.getCodec())===this.getCodec()){t=r;break}}else{S(this instanceof Us);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 h(d({},We),{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(){S(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 p(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getDurationFromMetadata(e)})}getLiveRefreshInterval(){return p(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getLiveRefreshInterval()})}getHasOnlyKeyPackets(){return this.internalTrack.hasOnlyKeyPackets||null}getFirstPacket(e){return p(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getFirstPacket(e)})}getPacket(e,t){return p(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getPacket(e,t)})}getKeyPacket(e,t){return p(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getKeyPacket(e,t)})}getNextPacket(e,t){return p(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getNextPacket(e,t)})}getNextKeyPacket(e,t){return p(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getNextKeyPacket(e,t)})}}class zs extends Ls{constructor(e){super(e)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return"video"}getCodec(){return Si(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 p(this,null,function*(){return yield this.hydrate(),this.backingVideoTrack.getColorSpace()})}canBeTransparent(){return p(this,null,function*(){return yield this.hydrate(),this.backingVideoTrack.canBeTransparent()})}getMetadataCodecParameterString(){return this.backingVideoTrack?null:this.internalTrack.fullCodecString}getDecoderConfig(){return p(this,null,function*(){return yield this.hydrate(),this.backingVideoTrack.getDecoderConfig()})}}class Us extends Ls{constructor(e){super(e)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return"audio"}getCodec(){return Si(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 p(this,null,function*(){return yield this.hydrate(),this.backingAudioTrack.getDecoderConfig()})}}const qs=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}".`)},Ws=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}".`)},Hs=e=>{if(null===e)return re;const t=e.split("-")[0];return t||re};class Vs{constructor(){this._isIsobmff=!1}}class js extends Vs{constructor(){super(...arguments),this._isIsobmff=!0}_getMajorBrand(e){return p(this,null,function*(){let t=e._reader.requestSlice(0,12);if(Pe(t)&&(t=yield t),!t)return null;t.skip(4);const i=Yo(t,4);return"ftyp"!==i&&"styp"!==i?null:Yo(t,4)})}_createDemuxer(e){return new er(e)}}class Ks extends js{_canReadInput(e){return p(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(Pe(t)&&(t=yield t),!t)return!1;let r=Wo(t),n=8;if(1===r){let t=e._reader.requestSlice(i+8,8);if(Pe(t)&&(t=yield t),!t)return!1;r=Ko(t),n=16}if(r8)return!1;if(xr(i,r)!==yr.EBML)return!1;const n=Br(i);if("number"!==typeof n)return!1;let s=e._reader.requestSlice(i.filePos,n);if(Pe(s)&&(s=yield s),!s)return!1;const a=i.filePos;for(;s.filePos<=a+n-2;){const e=Er(s);if(!e)break;const{id:i,size:r}=e,n=s.filePos;if(void 0===r)return!1;switch(i){case yr.EBMLVersion:if(1!==xr(s,r))return!1;break;case yr.EBMLReadVersion:if(1!==xr(s,r))return!1;break;case yr.DocType:if(_r(s,r)!==t)return!1;break;case yr.DocTypeVersion:if(xr(s,r)>4)return!1}s.filePos=n+r}return!0})}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new sn(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}}class Gs extends $s{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}}class Qs extends Vs{_canReadInput(e){return p(this,null,function*(){let t=0;for(;;){let i=e._reader.requestSlice(t,nl);if(Pe(i)&&(i=yield i),!i)break;const r=ll(i);if(!r)break;t=i.filePos+r.size}const i=yield cn(e._reader,t,t+4096);if(!i)return!1;const r=i.header,n=Ci(r.mpegVersionId,r.channel);let s=e._reader.requestSlice(i.startPos+n,4);if(Pe(s)&&(s=yield s),!s)return!1;const a=Wo(s);if(a===Ii||a===xi)return!0;t=i.startPos+i.header.totalSize;const o=yield cn(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 un(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}}class Ys extends Vs{_canReadInput(e){return p(this,null,function*(){let t=e._reader.requestSlice(0,12);if(Pe(t)&&(t=yield t),!t)return!1;const i=Yo(t,4);if("RIFF"!==i&&"RIFX"!==i&&"RF64"!==i)return!1;t.skip(4);return"WAVE"===Yo(t,4)})}_createDemuxer(e){return new xn(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}}class Js extends Vs{_canReadInput(e){return p(this,null,function*(){let t=e._reader.requestSlice(0,4);return Pe(t)&&(t=yield t),!!t&&"OggS"===Yo(t,4)})}_createDemuxer(e){return new Tn(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}}class Zs extends Vs{_canReadInput(e){return p(this,null,function*(){let t=0;for(;;){let i=e._reader.requestSlice(t,nl);if(Pe(i)&&(i=yield i),!i)break;const r=ll(i);if(!r)break;t=i.filePos+r.size}let i=e._reader.requestSlice(t,4);return Pe(i)&&(i=yield i),!!i&&"fLaC"===Yo(i,4)})}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new An(e)}}class ea extends Vs{_canReadInput(e){return p(this,null,function*(){let t=0;for(;;){let i=e._reader.requestSlice(t,nl);if(Pe(i)&&(i=yield i),!i)break;const r=ll(i);if(!r)break;t=i.filePos+r.size}let i=e._reader.requestSliceRange(t,7,9);if(Pe(i)&&(i=yield i),!i)return!1;const r=En(i);if(!r)return!1;if(t+=r.frameLength,i=e._reader.requestSliceRange(t,7,9),Pe(i)&&(i=yield i),!i)return!1;const n=En(i);return!!n&&(r.objectType===n.objectType&&r.samplingFrequencyIndex===n.samplingFrequencyIndex&&r.channelConfiguration===n.channelConfiguration)})}_createDemuxer(e){return new Rn(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}}class ta extends Vs{_canReadInput(e){return p(this,null,function*(){let t=e._reader.requestSlice(0,205);if(Pe(t)&&(t=yield t),!t)return!1;const i=Mo(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 qn(e)}get name(){return"MPEG Transport Stream"}get mimeType(){return"video/MP2T"}}class ia extends Vs{_canReadInput(e){return p(this,null,function*(){let t=e._reader.requestSlice(0,7);if(Pe(t)&&(t=yield t),!t)return!1;if(!("#EXTM3U"===Yo(t,7)))return!1;if(!(e._rootSource instanceof ks))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 Os(e)}get name(){return"HTTP Live Streaming (HLS)"}get mimeType(){return Qn}}const ra=new Ks,na=new Xs,sa=new $s,aa=new Gs,oa=new Qs,la=new Ys,ca=new Js,ua=new ea,da=new Zs,ha=new ta,fa=new ia,ma=[fa,ra,na,sa,aa,la,ca,da,oa,ua,ha],pa=[fa,ra,na,oa,ua,ha];var ga=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});Be();let ka=-1/0,ya=-1/0,ba=null;"undefined"!==typeof FinalizationRegistry&&(ba=new FinalizationRegistry(e=>{const t=performance.now();"video"===e.type?(t-ka>=1e3&&(ze._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."),ka=t),"undefined"!==typeof VideoFrame&&e.data instanceof VideoFrame&&e.data.close()):(t-ya>=1e3&&(ze._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."),ya=t),"undefined"!==typeof AudioData&&e.data instanceof AudioData&&e.data.close())}));class Ta{constructor(){this._referenceCount=0,this._lastAllocationBuffer=null}}const va=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],Sa=new Set(va);class wa{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(de*this.timestamp)}get microsecondDuration(){return Math.trunc(de*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,S,w,P,I,x,C,E,_,R,F,A;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||!Sa.has(t.format))throw new TypeError("init.format must be one of: "+va.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&&De(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:Aa(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?B(e):B(e).slice(),this._layout=m,this.colorSpace=new Ba(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)&&De(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!=(S=null==t?void 0:t.rotation)?S:0,this.squarePixelWidth=e.displayWidth,this.squarePixelHeight=e.displayHeight,this.timestamp=null!=(w=null==t?void 0:t.timestamp)?w:e.timestamp/1e6,this.duration=null!=(I=null==t?void 0:t.duration)?I:(null!=(P=e.duration)?P:0)/1e6,this.colorSpace=new Ba(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&&De(t.visibleRect,"init.visibleRect"),"undefined"!==typeof VideoFrame)return new wa(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*de),duration:Math.trunc((null!=(x=t.duration)?x:0)*de)||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:be(),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!=(E=t.rotation)?E:0,this.timestamp=t.timestamp,this.duration=null!=(_=t.duration)?_:0,this.colorSpace=new Ba({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else{if(!(e instanceof Ta))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&&!va.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!=(R=t.rotation)?R:0,this.timestamp=t.timestamp,this.duration=null!=(F=t.duration)?F:0,this.colorSpace=e.getColorSpace()}this.encodeOptions=null!=(A=null==t?void 0:t.encodeOptions)?A:{},this.pixelAspectRatio=Ae({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),null==ba||ba.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return S(null!==this._data),this._data instanceof Ta?new wa(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):Ea(this._data)?new wa(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):this._data instanceof Uint8Array?(S(this._layout),new wa(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 wa(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==ba||ba.unregister(this),this._data instanceof Ta?(this._data._referenceCount--,0===this._data._referenceCount&&this._data.close()):Ea(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){var t;if(Fa(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(Ea(this._data))return this._data.allocationSize(e);return Ma(this,e).allocationSize}copyTo(e){return p(this,arguments,function*(e,t={}){var i,r;if(!U(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(Fa(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(S(null!==this._data),Ea(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 Ta)){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 wa))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{ga(i)}}}const n=Ma(this,t);S(this.format);const s=B(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)S(this._layout),S(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");S(e);const t=e.getImageData(0,0,this.codedWidth,this.codedHeight);o=[{data:B(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 Ea(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?(S(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&&Ra(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=_a(T,m,p));const{sx:v,sy:S,sWidth:w,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,S,w,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 u=0;2*r0?Ca(d,h):{canvas:e,context:t,isNew:i.targetIsFresh};m.imageSmoothingQuality="high",i.fillBlack?(m.fillStyle="black",m.fillRect(0,0,d,h)):p||m.clearRect(0,0,d,h),this.drawWithFit(m,{fit:i.fit,rotation:i.rotation,crop:i.crop}),m.globalCompositeOperation="copy";for(let g=u;g>1;g--){const e=r*c(2,g),t=n*c(2,g);m.drawImage(f,0,0,e,t,0,0,e/2,t/2)}m.globalCompositeOperation="source-over",u>0&&(t.imageSmoothingQuality="high",t.globalCompositeOperation="copy",t.drawImage(f,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(S(null!==this._data),this._data instanceof Ta||this._data instanceof Uint8Array){const e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}return this._data}transform(e){return p(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&&Ra(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=w(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=_a(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=se(f,null!=(i=e.roundDimensionsTo)?i:1),m=se(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 Pa){let t=e(this,p);if(Pe(t)&&(t=yield t),null!==t)return t}const{canvas:g,context:k,isNew:y}=Ca(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 wa(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 Pa=[],Ia=[];let xa=0;const Ca=(e,t)=>{for(const n of Ia)if(n.canvas.width===e&&n.canvas.height===t)return n.age=xa++,{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 Ia.length>=3&&Ia.splice(Fe(Ia,e=>e.age),1),Ia.push({canvas:i,context:r,age:xa++}),{canvas:i,context:r,isNew:!0}};class Ba{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(F);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(D);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(N);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 Ea=e=>"undefined"!==typeof VideoFrame&&e instanceof VideoFrame,_a=(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 S(s>=0),S(a>=0),{left:r,top:n,width:s,height:a}},Ra=(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.")},Fa=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.")}},Aa=(e,t,i)=>{const r=Da(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},Da=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:J(e),S(!1)}},Ma=(e,t)=>{const i={left:0,top:0,width:e.codedWidth,height:e.codedHeight},r=t.rect,n=Na(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 La(n,a,s)},Na=(e,t,i,r,n)=>{const s=d({},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(!Oa(n,s))throw new TypeError("visibleRect alignment is invalid for the format.");return s},Oa=(e,t)=>{if(null===e)return!0;const i=Da(e);for(let r=0;r{const r=Da(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/(Wa(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*Wa(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=Wa(r),o=Ha(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(!U(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&&!za.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=Wa(o),f=Ha(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 Xa(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=Va(a),y=Wa(a),b=Ha(a);let T;if(this._data instanceof Ua){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 qa({data:n,format:this.format,sampleRate:this.sampleRate,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp+e/this.sampleRate})}close(){this._closed||(null==ba||ba.unregister(this),this._data instanceof Ua?(this._data._referenceCount--,0===this._data._referenceCount&&this._data.close()):Ka(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 Ua?this._createAudioDataFromData():Ka(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(Ha(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")}},Ha=e=>{switch(e){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},Va=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)}},ja=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)}},Ka=e=>"undefined"!==typeof AudioData&&e instanceof AudioData,Xa=(e,t,i,r,n,s,a,o)=>{const l=Va(i),c=ja(r),u=Wa(i),d=Wa(r),h=Ha(i);if(Ha(r))if(h){const r=new ArrayBuffer(o*u),n=E(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.")},Ya=e=>{if(!Ee(e))throw new TypeError("timestamp must be a number.")},Ja=(e,t,i)=>i.verifyKeyPackets?t.then(t=>p(null,null,function*(){if(!t||"delta"===t.type)return t;const i=yield e.determinePacketType(t);return i&&(t.type=i),t})):t;class Za{constructor(e){if(!(e instanceof po))throw new TypeError("track must be an InputTrack.");this._track=e}getFirstPacket(){return p(this,arguments,function*(e={}){if(Qa(e),this._track.input._disposed)throw new Ro;return Ja(this._track,this._track._backing.getFirstPacket(e),e)})}getFirstKeyPacket(){return p(this,arguments,function*(e={}){Qa(e);const t=yield this.getFirstPacket(e);return t?"key"===t.type?t:this.getNextKeyPacket(t,e):null})}getPacket(e){return p(this,arguments,function*(e,t={}){if(Ya(e),Qa(t),this._track.input._disposed)throw new Ro;return Ja(this._track,this._track._backing.getPacket(e,t),t)})}getNextPacket(e){return p(this,arguments,function*(e,t={}){if(!(e instanceof Mi))throw new TypeError("packet must be an EncodedPacket.");if(Qa(t),this._track.input._disposed)throw new Ro;return Ja(this._track,this._track._backing.getNextPacket(e,t),t)})}getKeyPacket(e){return p(this,arguments,function*(e,t={}){if(Ya(e),Qa(t),this._track.input._disposed)throw new Ro;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);const i=yield this._track._backing.getKeyPacket(e,t);if(!i)return i;S("key"===i.type);return"delta"===(yield this._track.determinePacketType(i))?this.getKeyPacket(i.timestamp-1/(yield this._track.getTimeResolution()),t):i})}getNextKeyPacket(e){return p(this,arguments,function*(e,t={}){if(!(e instanceof Mi))throw new TypeError("packet must be an EncodedPacket.");if(Qa(t),this._track.input._disposed)throw new Ro;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);const i=yield this._track._backing.getNextKeyPacket(e,t);if(!i)return i;S("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 Mi))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 Mi))throw new TypeError("endPacket must be an EncodedPacket.");if(Qa(i),this._track.input._disposed)throw new Ro;const r=[];let{promise:n,resolve:s}=$(),{promise:a,resolve:o}=$(),l=!1,c=!1,u=null,d=!1;const h=[],f=()=>Math.max(2,h.length);(()=>p(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}=$()),yield a):(r.push(u),s(),({promise:n,resolve:s}=$()),u=yield this.getNextPacket(u,i));l=!0,s()}))().catch(e=>{d||(u=e,d=!0,s())});const m=this._track;return{next(){return p(this,null,function*(){for(;;){if(m.input._disposed)throw new Ro;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 p(this,null,function*(){return c=!0,o(),s(),{value:void 0,done:!0}})},throw(e){return p(this,null,function*(){throw e})},[Symbol.asyncIterator](){return this}}}}class eo{constructor(e,t){this.onSample=e,this.onError=t}}class to{mediaSamplesInRange(e=-1/0,t=1/0,i){Ya(e),Ya(t);const r=[];let n=!1,s=null,{promise:a,resolve:o}=$(),{promise:l,resolve:c}=$(),u=!1,f=!1,m=!1,g=null,k=null,y=!1;const b=h(d({},i),{verifyKeyPackets:!0,metadataOnly:!1});(()=>p(this,null,function*(){var i;g=yield this._createDecoder(i=>{c(),i.timestamp>=t&&(f=!0),f?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}=$())))},e=>{y||(k=e,y=!0,o())});const d=this._createPacketSink(),h=null!=(i=yield d.getKeyPacket(e,b))?i:yield d.getFirstKeyPacket(b);let p=h;const T=d.packets(null!=h?h:void 0,void 0,b);for(yield T.next();p&&!f&&!this._track.input._disposed;){const e=io(r.length);if(r.length+g.getDecodeQueueSize()>e){({promise:l,resolve:c}=$()),yield l;continue}g.decode(p);const t=yield T.next();if(t.done)break;p=t.value}yield T.return(),m||this._track.input._disposed||(yield g.flush()),!n&&s&&r.push(s),u=!0,o()}))().catch(e=>{y||(k=e,y=!0,o())}).finally(()=>{null==g||g.close()});const T=this._track,v=()=>{null==s||s.close();for(const e of r)e.close()};return{next(){return p(this,null,function*(){for(;;){if(T.input._disposed)throw m=!0,f=!0,v(),new Ro;if(m)return{value:void 0,done:!0};if(y)throw m=!0,f=!0,v(),k;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 p(this,null,function*(){return m=!0,f=!0,c(),o(),v(),{value:void 0,done:!0}})},throw(e){return p(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 k(this,null,function*(){Symbol.iterator in e?yield*y(e[Symbol.iterator]()):yield*y(e[Symbol.asyncIterator]())})}(e),r=[],n=[];let{promise:s,resolve:a}=$(),{promise:o,resolve:l}=$(),c=!1,u=!1,f=null,m=null,g=!1;const T=e=>{n.push(e),a(),({promise:s,resolve:a}=$())},v=h(d({},t),{verifyKeyPackets:!0,metadataOnly:!1});(()=>p(this,null,function*(){f=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{g||(m=e,g=!0,a())});const e=this._createPacketSink();let t=null,s=null,d=-1;const h=()=>p(this,null,function*(){S(s),S(f);let t=s;for(f.decode(t);t.sequenceNumberi&&!u;)({promise:o,resolve:l}=$()),yield o;if(u)break;const r=yield e.getNextPacket(t,v);S(r),f.decode(r),t=r}d=-1}),k=()=>p(this,null,function*(){S(f),yield f.flush();for(let e=0;e{g||(m=e,g=!0,a())}).finally(()=>{null==f||f.close()});const w=this._track,P=()=>{for(const e of n)null==e||e.close()};return{next(){return p(this,null,function*(){for(;;){if(w.input._disposed)throw u=!0,P(),new Ro;if(u)return{value:void 0,done:!0};if(g)throw u=!0,P(),m;if(n.length>0){const e=n.shift();return S(void 0!==e),l(),{value:e,done:!1}}if(c)return{value:void 0,done:!0};yield s}})},return(){return p(this,null,function*(){return u=!0,l(),a(),P(),{value:void 0,done:!0}})},throw(e){return p(this,null,function*(){throw e})},[Symbol.asyncIterator](){return this}}}}const io=e=>0===e?40:8;class ro extends eo{constructor(e,t,i,r,n,s){var a,o,l,c,u,f,m,p;super(e,t),this.codec=i,this.decoderConfig=r,this.rotation=n,this.timeResolution=s,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new pe,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 g=$a.find(e=>e.supports(i,r));if(g)this.customDecoder=new g,this.customDecoder.codec=i,this.customDecoder.config=r,this.customDecoder.onSample=e=>{if(!(e instanceof wa))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();S(void 0!==t),this.mergeAlpha(e,t)}else this.colorQueue.push(e)};if(ve()){if("avc"===i&&this.decoderConfig.description){const e=dt(B(this.decoderConfig.description));if(e&&e.sequenceParameterSets.length>0){const t=ft(e.sequenceParameterSets[0]);t&&(0===t.frameMbsOnlyFlag&&(this.decoderConfig=h(d({},this.decoderConfig),{hardwareAcceleration:"prefer-software"})),0!==t.maxDecFrameBuffering&&1!==t.bitstreamRestrictionFlag&&(e.sequenceParameterSets[0]=pt(t),this.decoderConfig=h(d({},this.decoderConfig),{description:ut(e)})))}}L(this.decoderConfig.colorSpace)||(this.decoderConfig=h(d({},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!=(f=null==(u=this.decoderConfig.colorSpace)?void 0:u.transfer)?f:"bt709",fullRange:null!=(p=null==(m=this.decoderConfig.colorSpace)?void 0:m.fullRange)&&p}}))}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:(S(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(S(this.decoder),ke()||X(this.inputTimestamps,e.timestamp,e=>e),ve()&&0===this.currentPacketIndex)if("avc"===this.codec){const t=[];let i=!1;for(const n of rt(e.data,this.decoderConfig)){const r=nt(e.data[n.offset]);if(i||(i=r>=1&&r<=5),r===Ye.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&B(t.description)[4];return lt(e,i+1)}return ot(e)})(t,this.decoderConfig);e=new Mi(r,e.type,e.timestamp,e.duration)}else if("hevc"===this.codec){const t=Et(e.data,this.decoderConfig);t&&(e=new Mi(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 so),!this.alphaDecoder){const e=e=>{if(this.colorQueue.length>0){const t=this.colorQueue.shift();S(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();S(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=Ot(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 gt(e,this.decoderConfig)){const i=kt(e[t.offset]);if(i===Ze.RASL_N||i===Ze.RASL_R)return!0}return!1}sampleHandler(e){if(ke()){if(this.sampleQueue.length>0&&e.timestamp>=P(this.sampleQueue).timestamp){for(const e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}X(this.sampleQueue,e,e=>e.timestamp)}else{const t=this.inputTimestamps.shift();S(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 p(this,null,function*(){const i=$();this.mergeAlphaPromises.push(i.promise);const r={sample:null};this.finalSamples.push(r);try{if(t){S(this.merger);const i=yield this.merger.merge(e,t);r.sample=new wa(i)}else r.sample=new wa(e);for(;this.finalSamples.length>0&&null!==this.finalSamples[0].sample;){const e=this.finalSamples.shift();this.sampleHandler(e.sample)}}catch(n){G(this.finalSamples,r),this.onError(n)}finally{G(this.mergeAlphaPromises,i.promise),i.resolve()}})}flush(){return p(this,null,function*(){var e;if(this.customDecoder?yield this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(S(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),ke()){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()):(S(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 no=null;class so{constructor(){this.workers=[],this.nextWorkerIndex=0,this.pendingRequests=new Map,this.nextRequestId=0}merge(e,t){if(0===this.workers.length){if(!no){const e=new Blob([`(${ao.toString()})()`],{type:"application/javascript"});no=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=$();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 ao=()=>{let e=null,t=null,i=Promise.resolve();self.addEventListener("message",e=>{const{id:t,color:n,alpha:s}=e.data;i=i.then(()=>p(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)=>p(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)=>p(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;ep(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 S={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,S)}),a=(e,i)=>p(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;ep(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 lo extends to{constructor(e,t={}){if(!(e instanceof yo))throw new TypeError("videoTrack must be an InputVideoTrack.");oo(t),super(),this._track=e,this._decoderOptions=t}_createDecoder(e,t){return p(this,null,function*(){if(!(yield this._track.canDecode())){if("undefined"===typeof VideoDecoder)throw new Error(Se("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 S(i&&n),n=h(d({},n),{hardwareAcceleration:this._decoderOptions.hardwareAcceleration,optimizeForLatency:this._decoderOptions.optimizeForLatency}),new ro(e,t,i,n,r,s)})}_createPacketSink(){return new Za(this._track)}getSample(e){return p(this,arguments,function*(e,t={}){Ya(e);try{for(var i,r,n,s=b(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 co{constructor(e,t={}){var i,r,n;if(this._rotation=0,this._initPromise=null,this._nextCanvasIndex=0,!(e instanceof yo))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&&Ra(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&&oo(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 lo(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=(()=>p(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=_a(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||be()});S(s),e._drawWithFitAndMipmapping(r,s,{fit:this._fit,rotation:this._rotation,crop:this._crop,targetIsFresh:n,fillBlack:!this._alpha&&be()});const a={canvas:r,timestamp:e.timestamp,duration:e.duration};return e.close(),a}getCanvas(e,t){return p(this,null,function*(){Ya(e),yield this._ensureInit();const i=yield this._videoSampleSink.getSample(e,t);return i&&this._videoSampleToWrappedCanvas(i)})}canvases(e,t,i){return k(this,null,function*(){yield new g(this._ensureInit()),yield*y(te(this._videoSampleSink.samples(e,t,i),e=>this._videoSampleToWrappedCanvas(e)))})}canvasesAtTimestamps(e,t){return k(this,null,function*(){yield new g(this._ensureInit()),yield*y(te(this._videoSampleSink.samplesAtTimestamps(e,t),e=>e&&this._videoSampleToWrappedCanvas(e)))})}}class uo extends eo{constructor(e,t,i,r){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new pe,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=Ga.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 qa))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 qa(e))}catch(t){this.onError(t)}},error:t=>{t.stack=e,this.onError(t)}}),this.decoder.configure(r)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(S(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--)):(S(this.decoder),null!=this.expectedFirstTimestamp||(this.expectedFirstTimestamp=e.timestamp),this.decoder.decode(e.toEncodedAudioChunk()))}flush(){return p(this,null,function*(){this.customDecoder?yield this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(S(this.decoder),yield this.decoder.flush()),this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0})}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(S(this.decoder),"closed"!==this.decoder.state&&this.decoder.close())}}class ho extends eo{constructor(e,t,i){super(e,t),this.decoderConfig=i,this.currentTimestamp=null,S(li.includes(i.codec)),this.codec=i.codec;const{dataType:r,sampleSize:n,littleEndian:s}=vi(this.codec);switch(this.inputSampleSize=n,n){case 1:"unsigned"===r?this.readInputValue=(e,t)=>e.getUint8(t)-c(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)-c(2,15):"signed"===r?this.readInputValue=(e,t)=>e.getInt16(t,s):S(!1);break;case 3:"unsigned"===r?this.readInputValue=(e,t)=>Z(e,t,s)-c(2,23):"signed"===r?this.readInputValue=(e,t)=>((e,t,i)=>Z(e,t,i)<<8>>8)(e,t,s):S(!1);break;case 4:"unsigned"===r?this.readInputValue=(e,t)=>e.getUint32(t,s)-c(2,31):"signed"===r?this.readInputValue=(e,t)=>e.getInt32(t,s):"float"===r?this.readInputValue=(e,t)=>e.getFloat32(t,s):S(!1);break;case 8:"float"===r?this.readInputValue=(e,t)=>e.getFloat64(t,s):S(!1);break;default:J(n),S(!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+c(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:J(n),S(!1)}}getDecodeQueueSize(){return 0}decode(e){const t=E(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 qa({format:this.outputFormat,data:n,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:i,timestamp:o});this.onSample(l)}flush(){return p(this,null,function*(){})}close(){}}class fo extends to{constructor(e){if(!(e instanceof bo))throw new TypeError("audioTrack must be an InputAudioTrack.");super(),this._track=e}_createDecoder(e,t){return p(this,null,function*(){if(!(yield this._track.canDecode())){if("undefined"===typeof AudioDecoder)throw new Error(Se("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 S(i&&r),li.includes(r.codec)?new ho(e,t,r):new uo(e,t,i,r)})}_createPacketSink(){return new Za(this._track)}getSample(e){return p(this,arguments,function*(e,t={}){Ya(e);try{for(var i,r,n,s=b(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 mo{constructor(e){if(!(e instanceof bo))throw new TypeError("audioTrack must be an InputAudioTrack.");this._audioSampleSink=new fo(e)}_audioSampleToWrappedArrayBuffer(e){const t={buffer:e.toAudioBuffer(),timestamp:e.timestamp,duration:e.duration};return e.close(),t}getBuffer(e,t){return p(this,null,function*(){Ya(e);const i=yield this._audioSampleSink.getSample(e,t);return i&&this._audioSampleToWrappedArrayBuffer(i)})}buffers(e,t,i){return te(this._audioSampleSink.samples(e,t,i),e=>this._audioSampleToWrappedArrayBuffer(e))}buffersAtTimestamps(e,t){return te(this._audioSampleSink.samplesAtTimestamps(e,t),e=>e&&this._audioSampleToWrappedArrayBuffer(e))}}class po{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof yo}isAudioTrack(){return this instanceof bo}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}getInternalCodecId(){return p(this,null,function*(){return this._backing.getInternalCodecId()})}get internalCodecId(){return go(this._backing.getInternalCodecId(),"internalCodecId","getInternalCodecId")}getLanguageCode(){return p(this,null,function*(){return this._backing.getLanguageCode()})}get languageCode(){return go(this._backing.getLanguageCode(),"languageCode","getLanguageCode")}getName(){return p(this,null,function*(){return this._backing.getName()})}get name(){return go(this._backing.getName(),"name","getName")}getTimeResolution(){return p(this,null,function*(){return this._backing.getTimeResolution()})}get timeResolution(){return go(this._backing.getTimeResolution(),"timeResolution","getTimeResolution")}isRelativeToUnixEpoch(){return p(this,null,function*(){return this._backing.isRelativeToUnixEpoch()})}getUnixTimeForTimestamp(e){return p(this,null,function*(){return this._backing.getUnixTimeForTimestamp(e)})}hasUnixTimeMapping(){return p(this,null,function*(){return null!==(yield this._backing.getUnixTimeForTimestamp(yield this.getFirstTimestamp()))})}getDisposition(){return p(this,null,function*(){return this._backing.getDisposition()})}get disposition(){return go(this._backing.getDisposition(),"disposition","getDisposition")}getBitrate(){return p(this,null,function*(){return this._backing.getBitrate()})}getAverageBitrate(){return p(this,null,function*(){return this._backing.getAverageBitrate()})}getFirstTimestamp(){return p(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 p(this,null,function*(){var t,i;const r=yield this._backing.getPacket(1/0,d({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 ae(n,yield this.getTimeResolution())})}getDurationFromMetadata(){return p(this,arguments,function*(e={}){return this._backing.getDurationFromMetadata(e)})}computePacketStats(e=1/0,t){return p(this,null,function*(){const i=new Za(this);let r=1/0,n=-1/0,s=0,a=0;try{for(var o,l,c,u=b(i.packets(void 0,void 0,d({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 p(this,null,function*(){return null!==(yield this._backing.getLiveRefreshInterval())})}getLiveRefreshInterval(){return p(this,null,function*(){return this._backing.getLiveRefreshInterval()})}canBePairedWith(e){if(!(e instanceof po))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 p(this,null,function*(){return this.input.getTracks(wo({filter:e=>e.canBePairedWith(this)},e))})}getPairableVideoTracks(e){return p(this,null,function*(){return this.input.getVideoTracks(wo({filter:e=>e.canBePairedWith(this)},e))})}getPairableAudioTracks(e){return p(this,null,function*(){return this.input.getAudioTracks(wo({filter:e=>e.canBePairedWith(this)},e))})}getPrimaryPairableVideoTrack(e){return p(this,null,function*(){return this.input.getPrimaryVideoTrack(wo({filter:e=>e.canBePairedWith(this)},e))})}getPrimaryPairableAudioTrack(e){return p(this,null,function*(){return this.input.getPrimaryAudioTrack(wo({filter:e=>e.canBePairedWith(this)},e))})}hasPairableTrack(e){return p(this,null,function*(){e&&(e=ko(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=ko(e)),this.hasPairableTrack(t=>p(this,null,function*(){return t.isVideoTrack()&&(!e||(yield e(t)))}))}hasPairableAudioTrack(e){return e&&(e=ko(e)),this.hasPairableTrack(t=>p(this,null,function*(){return t.isAudioTrack()&&(!e||(yield e(t)))}))}}const go=(e,t,i)=>{if(Pe(e))throw new Error(`'${t}' is deprecated and not available synchronously for this track. Use the preferred '${i}()' instead.`);return e},ko=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 Pe(r)?r.then(i):i(r)}:void 0};class yo extends po{constructor(e,t){super(e,t),this._pixelAspectRatioCache=null,this._backing=t}get type(){return"video"}getCodec(){return p(this,null,function*(){return this._backing.getCodec()})}get codec(){return go(this._backing.getCodec(),"codec","getCodec")}hasOnlyKeyPackets(){return p(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 p(this,null,function*(){return this._backing.getCodedWidth()})}get codedWidth(){return go(this._backing.getCodedWidth(),"codedWidth","getCodedWidth")}getCodedHeight(){return p(this,null,function*(){return this._backing.getCodedHeight()})}get codedHeight(){return go(this._backing.getCodedHeight(),"codedHeight","getCodedHeight")}getRotation(){return p(this,null,function*(){return this._backing.getRotation()})}get rotation(){return go(this._backing.getRotation(),"rotation","getRotation")}getSquarePixelWidth(){return p(this,null,function*(){return this._backing.getSquarePixelWidth()})}get squarePixelWidth(){return go(this._backing.getSquarePixelWidth(),"squarePixelWidth","getSquarePixelWidth")}getSquarePixelHeight(){return p(this,null,function*(){return this._backing.getSquarePixelHeight()})}get squarePixelHeight(){return go(this._backing.getSquarePixelHeight(),"squarePixelHeight","getSquarePixelHeight")}getPixelAspectRatio(){return p(this,null,function*(){var e;return null!=(e=this._pixelAspectRatioCache)?e:this._pixelAspectRatioCache=Ae({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=Ae({num:go(this._backing.getSquarePixelWidth(),"pixelAspectRatio","getPixelAspectRatio")*go(this._backing.getCodedHeight(),"pixelAspectRatio","getPixelAspectRatio"),den:go(this._backing.getSquarePixelHeight(),"pixelAspectRatio","getPixelAspectRatio")*go(this._backing.getCodedWidth(),"pixelAspectRatio","getPixelAspectRatio")})}getDisplayWidth(){return p(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=go(i,"displayWidth","getDisplayWidth");if(null!==e)return e}const r=go(this._backing.getRotation(),"displayWidth","getDisplayWidth")%180===0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight();return go(r,"displayWidth","getDisplayWidth")}getDisplayHeight(){return p(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=go(i,"displayHeight","getDisplayHeight");if(null!==e)return e}const r=go(this._backing.getRotation(),"displayHeight","getDisplayHeight")%180===0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth();return go(r,"displayHeight","getDisplayHeight")}getColorSpace(){return p(this,null,function*(){return this._backing.getColorSpace()})}hasHighDynamicRange(){return p(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 p(this,null,function*(){return this._backing.canBeTransparent()})}getDecoderConfig(){return p(this,null,function*(){return this._backing.getDecoderConfig()})}getCodecParameterString(){return p(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 p(this,null,function*(){try{const e=yield this._backing.getDecoderConfig();if(!e)return!1;const t=yield this._backing.getCodec();if(S(null!==t),$a.some(i=>i.supports(t,e)))return!0;if("undefined"===typeof VideoDecoder)return!1;return!0===(yield VideoDecoder.isConfigSupported(e)).supported}catch(e){return ze._error("Error during decodability check:",e),!1}})}determinePacketType(e){return p(this,null,function*(){if(!(e instanceof Mi))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 S(i),Ot(t,i,e.data)})}computeFrameRateMetrics(){return p(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&&(!Ee(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 Za(this),a=[];let o=-1/0,l=0;try{for(var c,u,d,h=b(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 b=0;be-t),x=P-1>>1,C=P>>1;let B=0,E=0,_=0;for(const b of I)if(_+=T.get(b),0===B&&_>x&&(B=b),_>C){E=b;break}const R=(k/B+k/E)/2;return{underlyingFrameRate:g,bestGuessFrameRate:null!==g?g:Co(R),minFrameRate:k/S,maxFrameRate:k/v,averageFrameRate:k*P/w,medianFrameRate:R,frameRateIsConstant:null!==g&&1===v&&1===S,probedPacketCount:l}})}}class bo extends po{constructor(e,t){super(e,t),this._backing=t}get type(){return"audio"}getCodec(){return p(this,null,function*(){return this._backing.getCodec()})}get codec(){return go(this._backing.getCodec(),"codec","getCodec")}hasOnlyKeyPackets(){return p(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 p(this,null,function*(){return this._backing.getNumberOfChannels()})}get numberOfChannels(){return go(this._backing.getNumberOfChannels(),"numberOfChannels","getNumberOfChannels")}getSampleRate(){return p(this,null,function*(){return this._backing.getSampleRate()})}get sampleRate(){return go(this._backing.getSampleRate(),"sampleRate","getSampleRate")}getDecoderConfig(){return p(this,null,function*(){return this._backing.getDecoderConfig()})}getCodecParameterString(){return p(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 p(this,null,function*(){try{const e=yield this._backing.getDecoderConfig();if(!e)return!1;const t=yield this._backing.getCodec();if(S(null!==t),Ga.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 ze._error("Error during decodability check:",e),!1}})}determinePacketType(e){return p(this,null,function*(){if(!(e instanceof Mi))throw new TypeError("packet must be an EncodedPacket.");return null===(yield this.getCodec())?null:"key"})}}const To=e=>-(null!=e?e:-1/0),vo=e=>-e,So=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 Pe(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 Pe(r)?r.then(i):i(r)}:void 0}},wo=(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 Pe(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 Pe(o)||Pe(l)?Promise.all([o,l]).then(([e,t])=>c(e,t)):c(o,l)}:void 0}),Po=(e,t)=>p(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=>Pe(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=>Pe(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)}),Io=(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 Vs)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof ps||e.source instanceof gs))throw new TypeError("options.source must be a Source or SourceRef.");if(e.source instanceof ps&&e.source._disposed)throw new TypeError("options.source must not be a disposed Source.");if(void 0!==e.initInput&&!(e.initInput instanceof Eo))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 ps?this._rootRef=e.source.ref():this._rootRef=e.source,this._sourceRefs.push(this._rootRef)}get _rootSource(){return this._rootRef.source}_getSourceUncached(e){return p(this,null,function*(){S(this._rootSource instanceof ks);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&&ys(i.request,e));if(i)return i.age++,Promise.resolve(i.sourceRef.source.ref());const r=this._sourceCachePromises.find(i=>i.cacheGroup===t&&ys(i.request,e));if(r)return r.promise.then(e=>e.sourceRef.source.ref());const n=(()=>p(this,null,function*(){const i=yield this._getSourceUncached(e);if(Re(this._sourceCache,e=>e.cacheGroup===t&&1===e.sourceRef.source._refCount)>=4){const e=Fe(this._sourceCache,e=>e.cacheGroup===t&&1===e.sourceRef.source._refCount?e.age:1/0);S(-1!==e);const i=this._sourceCache[e];this._sourceCache.splice(e,1),i.sourceRef.free(),G(this._sourceRefs,i.sourceRef)}this._sourceRefs.push(i);const r=this._sourceCachePromises.findIndex(t=>t.request===e);S(-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=(()=>p(this,null,function*(){var e;this._reader=new Fo(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 _o}))()}get source(){return this._rootSource}getFormat(){return p(this,null,function*(){return yield this._getDemuxer(),S(this._format),this._format})}canRead(){return p(this,null,function*(){try{return yield this._getDemuxer(),!0}catch(e){if(e instanceof _o)return!1;throw e}})}getFirstTimestamp(e){return p(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 p(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 p(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 p(this,null,function*(){e&&(e=So(e));const t=(yield this._getTrackBackings()).map(e=>this._wrapBackingAsTrack(e));return Po(t,e)})}getVideoTracks(e){return p(this,null,function*(){e&&(e=So(e));const t=(yield this.getTracks()).filter(e=>e.isVideoTrack());return Po(t,e)})}getAudioTracks(e){return p(this,null,function*(){e&&(e=So(e));const t=(yield this.getTracks()).filter(e=>e.isAudioTrack());return Po(t,e)})}getPrimaryVideoTrack(e){return p(this,null,function*(){var t;e&&(e=So(e));const i=wo(e,{sortBy:e=>p(null,null,function*(){return[vo((yield e.getDisposition()).default),vo(yield e.hasPairableAudioTrack()),vo(!(yield e.hasOnlyKeyPackets())),To(yield e.getBitrate())]})});return null!=(t=(yield this.getVideoTracks(i))[0])?t:null})}getPrimaryAudioTrack(e){return p(this,null,function*(){var t;e&&(e=So(e));const i=yield this.getPrimaryVideoTrack(),r=wo(e,{sortBy:e=>p(this,null,function*(){return[vo(!i||e.canBePairedWith(i)),vo((yield e.getDisposition()).default),To(yield e.getBitrate())]})});return null!=(t=(yield this.getAudioTracks(r))[0])?t:null})}_getTrackBackings(){return p(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 yo(this,e):new bo(this,e);return this._backingToTrack.set(e,i),i}getMimeType(){return p(this,null,function*(){return(yield this._getDemuxer()).getMimeType()})}getMetadataTags(){return p(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 _o extends Error{constructor(e="Input has an unsupported or unrecognizable format."){super(e),this.name="UnsupportedInputFormatError"}}class Ro extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}}class Fo{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 Ro;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 Ao(t,E(t),0,e,e)}const i=e+t,r=this.source._read(e,i,0,ms);return Pe(r)?r.then(t=>t?new Ao(t.bytes,t.view,t.offset,e,i):null):r?new Ao(r.bytes,r.view,r.offset,e,i):null}requestSliceRange(e,t,i){if(this.source._disposed)throw new Ro;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),n=r=>r||(S(null!==this.fileSizeNonStrict),this.requestSlice(e,ie(this.fileSizeNonStrict-e,t,i)));return Pe(r)?r.then(n):n(r)}}requestEntireFile(){if(null!==this.fileSizeNonStrict)return this.requestSlice(0,this.fileSizeNonStrict);return(()=>p(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(Pe(i)&&(i=yield i),!i||0===i.length)break;const r=Mo(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 Ao(i,E(i),0,0,t)}))()}}class Ao{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 Ao(e,E(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 Ao(this.bytes,this.view,this.offset,e,e+t)}}const Do=(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.`)},Mo=(e,t)=>{Do(e,t);const i=e.bytes.subarray(e.bufferPos,e.bufferPos+t);return e.bufferPos+=t,i},No=e=>(Do(e,1),e.view.getUint8(e.bufferPos++)),Oo=(e,t)=>{Do(e,2);const i=e.view.getUint16(e.bufferPos,t);return e.bufferPos+=2,i},Lo=e=>{Do(e,2);const t=e.view.getUint16(e.bufferPos,!1);return e.bufferPos+=2,t},zo=e=>{Do(e,3);const t=Z(e.view,e.bufferPos,!1);return e.bufferPos+=3,t},Uo=e=>{Do(e,2);const t=e.view.getInt16(e.bufferPos,!1);return e.bufferPos+=2,t},qo=(e,t)=>{Do(e,4);const i=e.view.getUint32(e.bufferPos,t);return e.bufferPos+=4,i},Wo=e=>{Do(e,4);const t=e.view.getUint32(e.bufferPos,!1);return e.bufferPos+=4,t},Ho=e=>{Do(e,4);const t=e.view.getUint32(e.bufferPos,!0);return e.bufferPos+=4,t},Vo=e=>{Do(e,4);const t=e.view.getInt32(e.bufferPos,!1);return e.bufferPos+=4,t},jo=(e,t)=>{let i,r;return t?(i=qo(e,!0),r=qo(e,!0)):(r=qo(e,!1),i=qo(e,!1)),4294967296*r+i},Ko=e=>4294967296*Wo(e)+Wo(e),Xo=e=>4294967296*Vo(e)+Wo(e),$o=e=>{const t=Ho(e),i=(e=>{Do(e,4);const t=e.view.getInt32(e.bufferPos,!0);return e.bufferPos+=4,t})(e);return 4294967296*i+t},Go=e=>{Do(e,4);const t=e.view.getFloat32(e.bufferPos,!1);return e.bufferPos+=4,t},Qo=e=>{Do(e,8);const t=e.view.getFloat64(e.bufferPos,!1);return e.bufferPos+=8,t},Yo=(e,t)=>{Do(e,t);let i="";for(let r=0;r_.decode(Mo(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 Zo,el,tl,il;(el=Zo||(Zo={}))[el.Unsynchronisation=128]="Unsynchronisation",el[el.ExtendedHeader=64]="ExtendedHeader",el[el.ExperimentalIndicator=32]="ExperimentalIndicator",el[el.Footer=16]="Footer",(il=tl||(tl={}))[il.ISO_8859_1=0]="ISO_8859_1",il[il.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",il[il.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",il[il.UTF_8=3]="UTF_8";const rl=128,nl=10,sl=["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"],al=(e,t)=>{var i;const r=e.filePos;null!=t.raw||(t.raw={}),null!=(i=t.raw).TAG||(i.TAG=Mo(e,rl-3)),e.filePos=r;const n=ol(e,30);n&&(null!=t.title||(t.title=n));const s=ol(e,30);s&&(null!=t.artist||(t.artist=s));const a=ol(e,30);a&&(null!=t.album||(t.album=a));const o=ol(e,4),l=Number.parseInt(o,10);Number.isInteger(l)&&l>0&&(null!=t.date||(t.date=new Date(String(l))));const c=Mo(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=ol(e,28),e.skip(2)}else e.skip(-30),u=ol(e,30);u&&(null!=t.comment||(t.comment=u));const d=No(e);d{const i=Mo(e,t),r=Ie(i.indexOf(0),i.length),n=i.subarray(0,r);let s="";for(let a=0;a{const t=e.filePos,i=Yo(e,3),r=No(e),n=No(e),s=No(e),a=Wo(e);if("ID3"!==i||255===r||255===n||0!==(2155905152&a))return e.filePos=t,null;let o=Ei(a);return s&Zo.Footer&&(o+=nl),{majorVersion:r,revision:n,flags:s,size:o}},cl=(e,t,i)=>{var r,n,s,a,o,l;if(![2,3,4].includes(t.majorVersion))return void ze._warn(`Unsupported ID3v2 major version: ${t.majorVersion}`);const c=t.flags&Zo.Footer?t.size-nl:t.size,u=Mo(e,c),d=new ul(t,u);if(t.flags&Zo.Unsynchronisation&&3===t.majorVersion&&d.ununsynchronizeAll(),t.flags&Zo.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&Zo.Unsynchronisation)),h)ze._warn(`Skipping encrypted ID3v2 frame ${e.id}`),d.pos=u;else if(f)ze._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!==sl[e]){null!=i.genre||(i.genre=sl[e]);break}}if(t=/^\d+$/.exec(e),t){const e=Number.parseInt(t[0]);if(void 0!==sl[e]){null!=i.genre||(i.genre=sl[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 ul{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:Ei(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 tl.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=Ie(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=Ie(r.findIndex(e=>0===e),r.length);return this.pos=i+Math.min(e+1,r.length),_.decode(r.subarray(0,e))}case tl.UTF_16_BE_NO_BOM:{const e=new TextDecoder("utf-16be"),t=Ie(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 tl.UTF_8:{const e=Ie(r.findIndex(e=>0===e),r.length);return this.pos=i+Math.min(e+1,r.length),_.decode(r.subarray(0,e))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";const t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}}class dl{constructor(e){this.events=e,this.input=null,this.audioSink=null,this.audioIterator=null,this.audioContext=null,this.gainNode=null,this.audioContextStartTime=0,this.playbackTimeAtStart=0,this.latestScheduledEndTime=0,this.duration=Number.NaN,this.paused=!0,this.volume=.7,this.muted=!1,this.playbackRate=1,this.asyncId=0,this.queuedNodes=new Set}get currentTime(){return this.paused?this.playbackTimeAtStart:(this.audioContext.currentTime-this.audioContextStartTime)*this.playbackRate+this.playbackTimeAtStart}ensureAudioContext(e){if(this.audioContext)return;const t=window.AudioContext||window.webkitAudioContext;try{this.audioContext=new t({sampleRate:e})}catch(i){this.audioContext=new t}this.gainNode=this.audioContext.createGain(),this.gainNode.connect(this.audioContext.destination),this.updateGain()}updateGain(){if(!this.gainNode)return;const e=this.muted?0:this.volume;this.gainNode.gain.value=e*e}stopQueuedNodes(){this.queuedNodes.forEach(e=>e.stop()),this.queuedNodes.clear()}stopIterator(){return p(this,null,function*(){var e;yield null==(e=this.audioIterator)?void 0:e.return(),this.audioIterator=null})}handleNoAudioTrack(){this.audioSink=null,this.ensureAudioContext()}load(e,t){return p(this,null,function*(){++this.asyncId,yield this.stopIterator(),this.stopQueuedNodes(),this.paused=!0,this.playbackTimeAtStart=0,this.audioContextStartTime=0;const{input:i,audioTrack:r,duration:n}=e;return this.input=i,this.duration=n,r?null!==r.codec&&(yield r.canDecode())?(this.ensureAudioContext(r.sampleRate),this.audioSink=new mo(r),void(null==t||t())):(this.audioSink=null,this.ensureAudioContext(),void(null==t||t())):(this.handleNoAudioTrack(),void(null==t||t()))})}runIterator(e){return p(this,null,function*(){if(!this.audioSink)return;yield this.stopIterator(),this.audioIterator=this.audioSink.buffers(this.currentTime);for(;;){if(e!==this.asyncId||this.paused)return;const i=[];let r=!1;try{for(let e=0;e<16;e++){const e=yield this.audioIterator.next();if(e.done){r=!0;break}i.push(e.value)}}catch(t){console.error("Audio iterator error:",t),r=!0}if(e!==this.asyncId||this.paused)return;i.length>0&&"suspended"===this.audioContext.state&&(yield this.audioContext.resume(),this.events.emit("canplay"),this.events.emit("playing"));for(const{buffer:e,timestamp:t}of i){const i=this.audioContext.createBufferSource();i.buffer=e,i.connect(this.gainNode),i.playbackRate.value=this.playbackRate;const r=this.audioContextStartTime+(t-this.playbackTimeAtStart)/this.playbackRate,n=(r+e.duration/this.playbackRate-this.audioContextStartTime)*this.playbackRate+this.playbackTimeAtStart;n>this.latestScheduledEndTime&&(this.latestScheduledEndTime=n),r>=this.audioContext.currentTime?i.start(r):i.start(this.audioContext.currentTime,(this.audioContext.currentTime-r)*this.playbackRate),this.queuedNodes.add(i),i.onended=()=>this.queuedNodes.delete(i)}if(r)break;yield new Promise(e=>setTimeout(e,0));const n=1;for(;this.latestScheduledEndTime-this.currentTime>n;){if(e!==this.asyncId||this.paused)return;yield new Promise(e=>setTimeout(e,50))}}})}play(){return p(this,null,function*(){if(!this.paused)return;this.audioContext||this.ensureAudioContext(),"suspended"===this.audioContext.state&&(yield this.audioContext.resume()),this.audioContextStartTime=this.audioContext.currentTime,this.latestScheduledEndTime=this.playbackTimeAtStart,this.paused=!1;const e=++this.asyncId;this.runIterator(e)})}pause(){this.paused||(this.playbackTimeAtStart=this.currentTime,this.paused=!0,this.stopIterator(),this.stopQueuedNodes())}seek(e){return p(this,null,function*(){this.playbackTimeAtStart=Math.max(0,e),this.audioContextStartTime=this.audioContext.currentTime,this.latestScheduledEndTime=this.playbackTimeAtStart;const t=++this.asyncId;this.paused||this.runIterator(t)})}setVolume(e,t){this.volume=e,this.muted=t,this.updateGain()}setPlaybackRate(e){if(e!==this.playbackRate&&(this.paused||(this.playbackTimeAtStart=this.currentTime,this.audioContextStartTime=this.audioContext.currentTime),this.playbackRate=e,!this.paused)){const e=++this.asyncId;this.runIterator(e)}}destroy(){var e;this.asyncId++,this.pause(),null==(e=this.audioContext)||e.close(),this.audioContext=null,this.input=null,this.audioSink=null}}function hl(e){return p(this,null,function*(){var t,i;return null!=(i=null!=(t=yield e.getAverageBitrate())?t:yield e.getBitrate())?i:0})}const fl=/\.m3u8(?:$|[?#])/i;function ml(e){return"string"===typeof e&&fl.test(e)}function pl(e){const t=function(e){return"string"===typeof e?new Is(e):e instanceof Blob?new vs(e):"undefined"!==typeof ReadableStream&&e instanceof ReadableStream?new Bs(e):null!=e?e:null}(e);return t?new Eo({source:t,formats:ml(e)?pa:ma}):null}class gl{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 p(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 kl(e){return p(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})}class yl{constructor({canvas:e,ctx:t,events:i,timeupdateInterval:r=250,avSyncTolerance:n=.12,dropLateFrames:s=!1,poster:a="",preflightRange:o=!1}){this.canvas=e,this.ctx=t,this.events=i,this.timeupdateInterval=r,this.avSyncTolerance=n,this.dropLateFrames=s,this.poster=a,this.preflightRange=o,this.input=null,this.videoSink=null,this.videoIterator=null,this.nextFrame=null,this.rafId=0,this.asyncId=0,this.width=0,this.height=0,this.duration=Number.NaN,this.audioClock=null,this.lastTimeUpdate=0,this.stalled=!1,this.playbackRate=1,this.posterDrawn=!1,this.isFetching=!1}preflight(e,t,i){return p(this,null,function*(){return function(e,t,i,r,n=()=>!0){return p(this,null,function*(){if((null==r?void 0:r.aborted)||!n())return!1;if(!t||"string"!==typeof e||ml(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(!this.poster||this.posterDrawn)return;const e=new Image;e.onload=()=>{this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.canvas.width=e.naturalWidth||this.canvas.width,this.canvas.height=e.naturalHeight||this.canvas.height,this.ctx.drawImage(e,0,0,this.canvas.width,this.canvas.height),this.posterDrawn=!0},e.src=this.poster}stopIterator(){return p(this,null,function*(){var e;yield null==(e=this.videoIterator)?void 0:e.return(),this.videoIterator=null})}clear(){this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height)}load(e,t){return p(this,null,function*(){++this.asyncId,yield this.stopIterator(),this.clear(),this.posterDrawn=!1;const{input:i,videoTrack:r,duration:n}=e;if(this.input=i,this.duration=n,!r)return this.handleNoVideoTrack(),void(null==t||t());if(null===r.codec||!(yield r.canDecode()))return this.handleNoVideoTrack(),void(null==t||t());const s=yield r.canBeTransparent();this.videoSink=new co(r,{poolSize:2,fit:"contain",alpha:s}),this.width=r.displayWidth,this.height=r.displayHeight,this.canvas.width=this.width,this.canvas.height=this.height,null==t||t(),yield this.resetIterator(0)})}handleNoVideoTrack(){this.videoSink=null,this.width=0,this.height=0,this.canvas.width=0,this.canvas.height=0,this.clear(),this.drawPoster()}resetIterator(e){return p(this,null,function*(){var t,i;if(yield this.stopIterator(),!this.videoSink)return;this.videoIterator=this.videoSink.canvases(e);const r=null!=(t=(yield this.videoIterator.next()).value)?t:null,n=null!=(i=(yield this.videoIterator.next()).value)?i:null;this.nextFrame=n,r?this.ctx.drawImage(r.canvas,0,0):this.drawPoster()})}updateNextFrame(e){return p(this,null,function*(){var t;if(this.videoIterator&&!this.isFetching){this.isFetching=!0;try{for(;;){const i=null!=(t=(yield this.videoIterator.next()).value)?t:null;if(!i||e!==this.asyncId)return;const r=this.audioClock.currentTime,n=this.dropLateFrames?Math.max(.06,this.avSyncTolerance/Math.max(1,this.playbackRate)):0;if(!(this.dropLateFrames&&i.timestampr)return void(this.nextFrame=null)}}}finally{this.isFetching=!1}}})}render(){if(!this.audioClock)return;const e=this.audioClock.currentTime,t=Date.now();if(t-this.lastTimeUpdate>=this.timeupdateInterval&&(this.events.emit("timeupdate"),this.lastTimeUpdate=t),Number.isFinite(this.duration)&&e>=this.duration)return this.stop(),this.stalled=!1,this.events.emit("ended"),this.events.emit("pause"),void this.events.emit("canplay");this.nextFrame&&this.nextFrame.timestamp<=e?(this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.ctx.drawImage(this.nextFrame.canvas,0,0),this.nextFrame=null,this.updateNextFrame(this.asyncId),this.stalled&&(this.events.emit("canplay"),this.events.emit("playing"),this.stalled=!1)):this.nextFrame||(this.updateNextFrame(this.asyncId),!this.nextFrame&&Number.isFinite(this.duration)&&ethis.render())}start(e){this.audioClock=e,this.asyncId++,this.stalled=!1,this.updateNextFrame(this.asyncId),this.rafId=requestAnimationFrame(()=>this.render())}stop(){cancelAnimationFrame(this.rafId)}seek(e){return p(this,null,function*(){this.asyncId++,yield this.resetIterator(e)})}setPlaybackRate(e){this.playbackRate=Math.max(.1,Number(e)||1)}destroy(){this.asyncId++,this.stop(),this.stopIterator(),this.posterDrawn=!1,this.videoSink=null,this.input=null}}class bl{constructor({canvas:e,ctx:t,events:i,option:r={}}){var n,s,a,o,l,c;this.events=i,this.option=r,this.audio=new dl(i),this.video=new yl({canvas:e,ctx:t,events:i,timeupdateInterval:null!=(n=r.timeupdateInterval)?n:250,avSyncTolerance:null!=(s=r.avSyncTolerance)?s:.12,dropLateFrames:null!=(a=r.dropLateFrames)&&a,poster:null!=(o=r.poster)?o:"",preflightRange:null!=(l=r.preflightRange)&&l}),this.paused=!0,this.ended=!1,this.readyState=0,this.networkState=0,this.error=null,this.seeking=!1,this.loadSeq=0,this.input=null,this.media=null,this.loadSession=null,this.destroyed=!1,null==(c=i.addEventListener)||c.call(i,"ended",()=>{this.ended=!0,this.paused=!0})}load(e){return p(this,null,function*(){var t;if(this.destroyed)return;const i=++this.loadSeq;if(null==(t=this.loadSession)||t.cancel(),i!==this.loadSeq||this.destroyed)return;if(this.pause(),i!==this.loadSeq||this.destroyed)return;this.disposeInput();const r=new gl;this.loadSession=r,this.ended=!1,this.error=null,this.networkState=2,this.readyState=0,r.defer(()=>this.events.emit("waiting")),r.defer(()=>this.events.emit("loadstart"));const n=Number.isFinite(this.option.loadTimeout)?this.option.loadTimeout:0;try{yield r.wait(this.performLoad(e,i,r),n)}catch(s){if(i!==this.loadSeq)return;const e=++this.loadSeq;if(r.cancel(),e!==this.loadSeq||this.destroyed)return;this.disposeInput(),this.error={code:4,message:s.message},this.networkState=3,this.events.emit("error")}})}performLoad(e,t){return p(this,arguments,function*(e,t,i=this.loadSession){if(!(yield this.video.preflight(e,null==i?void 0:i.signal,()=>t===this.loadSeq))||t!==this.loadSeq)return;const r=pl(e);if(!r)return this.video.handleNoVideoTrack(),void this.audio.handleNoAudioTrack();i.own(r);const n=yield function(e,t){return p(this,null,function*(){const i=yield e.getPrimaryVideoTrack(),r=i?yield i.getPrimaryPairableAudioTrack():yield e.getPrimaryAudioTrack(),n=yield kl({input:e,videoTrack:i,audioTrack:r}),s=i||r,a=ml(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"}})}(r,e);if(t!==this.loadSeq)return;this.input=r,this.media=n;let s=!n.videoTrack,a=!n.audioTrack;const o=()=>{s&&a&&(this.readyState=1,this.events.emit("loadedmetadata"),this.events.emit("durationchange"),this.events.emit("progress"))};try{if(yield Promise.all([this.video.load(n,()=>{t===this.loadSeq&&(s=!0,o())}),this.audio.load(n,()=>{t===this.loadSeq&&(a=!0,o())})]),t!==this.loadSeq)return;this.readyState=4,this.networkState=1,this.events.emit("loadeddata"),this.events.emit("canplay"),this.events.emit("canplaythrough"),this.events.emit("progress")}catch(l){if(t!==this.loadSeq)return;throw console.error("MediaBunny load error:",l),l}})}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 p(this,arguments,function*({videoTrack:e,audioTrack:t,videoMode:i,audioMode:r}){if(!this.media)return;const n=h(d({},this.media),{videoTrack:e,audioTrack:t,videoMode:i,audioMode:r}),s=!this.paused,a=this.currentTime;this.pause(),this.ended=!1,this.seeking=!0,this.events.emit("seeking"),this.events.emit("waiting"),n.duration=yield kl(n),this.media=n,yield Promise.all([this.video.load(n),this.audio.load(n)]),yield Promise.all([this.video.seek(a),this.audio.seek(a)]),this.readyState=4,this.networkState=1,this.seeking=!1,this.events.emit("loadedmetadata"),this.events.emit("durationchange"),this.events.emit("progress"),this.events.emit("loadeddata"),this.events.emit("canplay"),this.events.emit("canplaythrough"),this.events.emit("seeked"),s&&(yield this.play())})}selectHlsQuality(e){return p(this,null,function*(){var t,i;if(!(null==(t=this.media)?void 0:t.isHls)||!this.input)return;const r=yield this.input.getVideoTracks(),n="auto"===e?yield this.input.getPrimaryVideoTrack():null!=(i=r.find(t=>t.id===e))?i:this.media.videoTrack;if(!n)return;let s=this.media.audioTrack,a=this.media.audioMode;s&&n.canBePairedWith(s)||(s=yield n.getPrimaryPairableAudioTrack(),a="auto"),yield this.replaceTracks({videoTrack:n,audioTrack:s,videoMode:"auto"===e?"auto":"manual",audioMode:a})})}selectHlsAudio(e){return p(this,null,function*(){var t,i;if(!(null==(t=this.media)?void 0:t.isHls)||!this.input)return;const r=yield this.input.getAudioTracks(),n="auto"===e?this.media.videoTrack?yield this.media.videoTrack.getPrimaryPairableAudioTrack():yield this.input.getPrimaryAudioTrack():null!=(i=r.find(t=>t.id===e))?i:this.media.audioTrack;if(!n)return;let s=this.media.videoTrack,a=this.media.videoMode;s&&n.canBePairedWith(s)||(s=yield n.getPrimaryPairableVideoTrack(),a="auto"),yield this.replaceTracks({videoTrack:s,audioTrack:n,videoMode:a,audioMode:"auto"===e?"auto":"manual"})})}getHlsState(){return function(e){return p(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)=>p(null,null,function*(){return{id:e.id,track:e,index:t,name:yield e.getName(),height:yield e.getDisplayHeight(),bitrate:yield hl(e)}}))),Promise.all(a.map((e,t)=>p(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 hl(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"}})}(this.media)}play(){return p(this,null,function*(){this.paused&&(this.ended&&(this.ended=!1,yield this.seek(0)),this.paused=!1,yield this.audio.play(),this.video.start(this.audio),this.events.emit("play"),this.events.emit("playing"))})}pause(){this.paused||(this.paused=!0,this.audio.pause(),this.video.stop(),this.events.emit("pause"))}seek(e){return p(this,null,function*(){const t=!this.paused;this.ended=!1,this.seeking=!0,this.events.emit("seeking"),this.events.emit("waiting"),this.pause(),yield Promise.all([this.audio.seek(e),this.video.seek(e)]),this.seeking=!1,this.events.emit("seeked"),t&&!this.ended&&(yield this.play())})}setVolume(e,t){this.audio.setVolume(e,t)}setPlaybackRate(e){this.audio.setPlaybackRate(e),this.video.setPlaybackRate(e)}destroy(){var e;this.destroyed||(this.destroyed=!0,this.loadSeq++,null==(e=this.loadSession)||e.cancel(),this.pause(),this.disposeInput(),this.audio.destroy(),this.video.destroy())}get currentTime(){return this.audio.currentTime}get duration(){var e,t,i;return null!=(i=null!=(t=null==(e=this.media)?void 0:e.duration)?t:this.audio.duration)?i:this.video.duration}get videoWidth(){return this.video.width}get videoHeight(){return this.video.height}}const Tl=new WeakMap;function vl(e){let t=Tl.get(e);return t||(t={closed:!1,frames:new Set},Tl.set(e,t)),t}class Sl{constructor({art:e,canvas:t,ctx:i,option:r}){var n,s;this.art=e,this.canvas=t,this.option=r,this.events=new v,this.engine=new bl({canvas:t,ctx:i,events:this.events,option:r}),this._src=null,this._volume=null!=(n=r.volume)?n:.7,this._muted=!!r.muted,this._playbackRate=1,this.engine.setVolume(this._volume,this._muted),this.setupEventForwarding(),r.source?this.src=r.source:(null==(s=e.option)?void 0:s.url)&&(this.src=e.option.url)}setupEventForwarding(){const{events:e}=this.art.constructor.config;e.forEach(e=>{this.events.addEventListener(e,e=>{this.art.emit(`video:${e.type}`,e)})})}addEventListener(e,t){this.events.addEventListener(e,t)}removeEventListener(e,t){this.events.removeEventListener(e,t)}get src(){return this._src}set src(e){this._src=e,e&&this.engine.load(e)}get currentSrc(){return this._src}get currentTime(){return this.engine.currentTime}set currentTime(e){this.engine.seek(Number(e)||0)}get duration(){return this.engine.duration}get buffered(){return this.createTimeRanges(0,this.engine.duration)}get played(){return this.createTimeRanges(0,this.engine.currentTime)}get seekable(){return this.createTimeRanges(0,this.engine.duration)}createTimeRanges(e,t){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=vl(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){vl(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=vl(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 Sl({art:t,canvas:n,ctx:s,option:e});t.mediabunny=a;const o={};for(const e in n)"function"===typeof n[e]&&(o[e]=n[e].bind(n));const l=new Set([...Object.getOwnPropertyNames(a),...Object.getOwnPropertyNames(Object.getPrototypeOf(a))]);for(const e of l)"constructor"!==e&&(e in n||Object.defineProperty(n,e,{get(){const t=a[e];return"function"===typeof t?t.bind(a):t},set(t){a[e]=t},configurable:!0,enumerable:!0}));for(const e in o)n[e]=(...t)=>o[e](...t);function c(){var e;(null==(e=t.template)?void 0:e.$player)&&!t.option.autoSize&&Object.assign(n.style,{width:"100%",height:"100%",objectFit:"contain"})}return t.on("resize",c),t.on("video:loadedmetadata",c),function({art:e,shim:t,option:i}){if(i.m3u8)return e.on("video:loadedmetadata",u),e.on("restart",u),{update:u};function r(t){e.controls.cache.has(t)&&e.controls.remove(t)}function n(t){e.setting.find(t)&&e.setting.remove(t)}function s(){r("mediabunny-quality"),n("mediabunny-quality")}function a(){r("mediabunny-audio"),n("mediabunny-audio")}function o(e={}){return e.control||e.setting}function l(r){return p(this,null,function*(){var n;const a=(null==(n=i.m3u8)?void 0:n.quality)||{};if(!o(a)||!(null==r?void 0:r.levels.length))return void s();const l=a.auto||"Auto",c=a.title||"Quality",d=a.getName||(e=>e.name||`${e.height}P`),h=r.currentLevel?d(r.currentLevel):l,f=T(r.levels.map(e=>{var t;return{html:d(e),value:e.id,default:(null==(t=r.currentLevel)?void 0:t.id)===e.id}}),"html").sort((e,t)=>{const i=r.levels.find(t=>t.id===e.value),n=r.levels.find(e=>e.id===t.value);return((null==n?void 0:n.height)||0)-((null==i?void 0:i.height)||0)});f.push({html:l,value:"auto",default:!r.currentLevel});const m=i=>p(null,null,function*(){return yield t.switchM3u8Quality(i.value),e.notice.show=`${c}: ${i.html}`,yield u(),i.html});a.control&&e.controls.update({name:"mediabunny-quality",position:"right",html:h,style:{padding:"0 10px"},selector:f,onSelect:m}),a.setting&&e.setting.update({name:"mediabunny-quality",tooltip:h,html:c,icon:'',width:200,selector:f,onSelect:m})})}function c(r){return p(this,null,function*(){var n;const s=(null==(n=i.m3u8)?void 0:n.audio)||{};if(!o(s)||!(null==r?void 0:r.audios.length)||r.audios.length<2)return void a();const l=s.auto||"Auto",c=s.title||"Audio",d=s.getName||(e=>e.name||e.lang||e.language),h=r.currentAudio?d(r.currentAudio):l,f=T(r.audios.map(e=>{var t;return{html:d(e),value:e.id,default:(null==(t=r.currentAudio)?void 0:t.id)===e.id}}),"html");f.push({html:l,value:"auto",default:!r.currentAudio});const m=i=>p(null,null,function*(){return yield t.switchM3u8Audio(i.value),e.notice.show=`${c}: ${i.html}`,yield u(),i.html});s.control&&e.controls.update({name:"mediabunny-audio",position:"right",html:h,style:{padding:"0 10px"},selector:f,onSelect:m}),s.setting&&e.setting.update({name:"mediabunny-audio",tooltip:h,html:c,icon:'',width:200,selector:f,onSelect:m})})}function u(){return p(this,null,function*(){const e=yield t.getM3u8State();if(!e)return s(),void a();yield Promise.all([l(e),c(e)])})}}({art:t,shim:a,option:e}),t.on("destroy",()=>{delete t.mediabunny,a.destroy()}),n}}}); +!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=Object.defineProperty,r=Object.defineProperties,n=Object.getOwnPropertyDescriptors,s=Object.getOwnPropertySymbols,a=Object.prototype.hasOwnProperty,o=Object.prototype.propertyIsEnumerable,l=(e,t)=>(t=Symbol[e])?t:Symbol.for("Symbol."+e),c=e=>{throw TypeError(e)},u=Math.pow,d=(e,t,r)=>t in e?i(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,h=(e,t)=>{for(var i in t||(t={}))a.call(t,i)&&d(e,i,t[i]);if(s)for(var i of s(t))o.call(t,i)&&d(e,i,t[i]);return e},f=(e,t)=>r(e,n(t)),m=(e,t,i)=>t.has(e)||c("Cannot "+i),p=(e,t,i)=>(m(e,t,"read from private field"),i?i.call(e):t.get(e)),g=(e,t,i)=>t.has(e)?c("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,i),k=(e,t,i,r)=>(m(e,t,"write to private field"),r?r.call(e,i):t.set(e,i),i),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())}),b=function(e,t){this[0]=e,this[1]=t},T=(e,t,i)=>{var r,n=(e,t,r,s)=>{try{var a=i[e](t),o=(t=a.value)instanceof b,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[l("asyncIterator")]=()=>a,s("next"),s("throw"),s("return"),a},v=e=>{var t,i=e[l("asyncIterator")],r=!1,n={};return null==i?(i=e[l("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 b(new Promise(r=>{var n=i[e](t);n instanceof Object||c("Object expected"),r(n)}),1)}}),n[l("iterator")]=()=>n,t("next"),"throw"in i?t("throw"):n.throw=e=>{throw e},"return"in i&&t("return"),n},S=(e,t,i)=>(t=e[l("asyncIterator")])?t.call(e):(e=e[l("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 w(e,t){const i=new Map;return e.filter(e=>{const r=e[t];return void 0===r||!i.has(r)&&i.set(r,1)})}class P{constructor(){g(this,e,!1),this.listeners=new Map}addEventListener(t,i){var r;p(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(p(this,e))return;const n=Object.assign(new Event(t),{detail:i});null==(r=this.listeners.get(t))||r.forEach(t=>{p(this,e)||t(n)})}destroy(){k(this,e,!0),this.listeners.clear()}}function I(e){if(!e)throw new Error("Assertion failed.")}e=new WeakMap;const x=e=>{const t=(e%360+360)%360;if(0===t||90===t||180===t||270===t)return t;throw new Error(`Invalid rotation ${e}.`)},C=e=>e&&e[e.length-1],B=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-u(2,r))},_=e=>{const t=B(e);return 0===(1&t)?-(t>>1):t+1>>1},R=e=>e.constructor===Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),F=e=>e.constructor===DataView?e:ArrayBuffer.isView(e)?new DataView(e.buffer,e.byteOffset,e.byteLength):new DataView(e),A=new TextDecoder,D=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])),M={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},N=D(M),O={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},L=D(O),z={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},U=D(z),q=e=>!!e&&!!e.primaries&&!!e.transfer&&!!e.matrix&&void 0!==e.fullRange,W={primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0},H=e=>e instanceof ArrayBuffer||"undefined"!==typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e);class V{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 j=/^[0-9a-fA-F]+$/,K=e=>[...e].map(e=>e.toString(16).padStart(2,"0")).join(""),X=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,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},Q=(e,t,i)=>{const r=G(e,i(t),i);e.splice(r+1,0,t)},Y=()=>{let e,t;return{promise:new Promise((i,r)=>{e=i,t=r}),resolve:e,reject:t}},J=(e,t)=>{const i=e.indexOf(t);-1!==i&&e.splice(i,1)},Z=(e,t)=>{for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},ee=(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}`)},ie=(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},re=(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)},ne=(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}}),se=(e,t,i)=>Math.max(t,Math.min(i,e)),ae="und",oe=e=>{const t=Math.round(e);return Math.abs(e/t-1)<10*Number.EPSILON?t:e},le=(e,t)=>Math.round(e/t)*t,ce=(e,t)=>Math.round(e*t)/t,ue=(e,t)=>Math.floor(e/t)*t,de=e=>{let t=0;for(;0!==e;)e&=e-1,t++;return t},he=/^[a-z]{3}$/,fe=e=>he.test(e),me=1e6*(1+Number.EPSILON),pe=(e,t)=>{const i=h(h({},e),t);if(e.headers||t.headers){const r=e.headers?ge(e.headers):{},n=t.headers?ge(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},ge=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},ke=(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(We._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 Le(1e3*e)),n())throw a}});class ye{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}let be=null;const Te=()=>{var e;return null!==be?be:be=!("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 ve=null;const Se=()=>{var e;return null!==ve?ve:ve="undefined"!==typeof navigator&&(null==(e=navigator.userAgent)?void 0:e.includes("Firefox"))};let we=null;const Pe=()=>{var e;return null!==we?we:we=!("undefined"===typeof navigator||!(null==(e=navigator.vendor)?void 0:e.includes("Google Inc"))&&!/Chrome/.test(navigator.userAgent))},Ie=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.`,xe=y(null,null,function*(){}).constructor,Ce=e=>e instanceof xe||e instanceof Promise||"function"===typeof(null==e?void 0:e.then),Be=(e,t)=>-1!==e?e:t,Ee=(e,t,i,r)=>e<=r&&i<=t,_e=e=>{const t=atob(e),i=new Uint8Array(t.length);for(let r=0;r{null!=Symbol.dispose||(Symbol.dispose=Symbol("Symbol.dispose"))},Fe=e=>"number"===typeof e&&!Number.isNaN(e),Ae=(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("/")},De=(e,t)=>{let i=0;for(let r=0;r{let i=-1,r=1/0;for(let n=0;n{I(Number.isInteger(e.num)),I(Number.isInteger(e.den)),I(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}},Oe=(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.`)},Le=e=>new Promise(t=>setTimeout(t,e));class ze{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 Ue,qe;(qe=Ue||(Ue={}))[qe.Silent=0]="Silent",qe[qe.Errors=1]="Errors",qe[qe.Warnings=2]="Warnings",qe[qe.Info=3]="Info";class We{constructor(){}static get level(){return We._level}static set level(e){if(e!==Ue.Silent&&e!==Ue.Errors&&e!==Ue.Warnings&&e!==Ue.Info)throw new TypeError("Invalid log level. Use one of the values of the LogLevel enum.");We._level=e}static get _emitter(){var e;return null!=(e=We._emitterInstance)?e:We._emitterInstance=new ze}static on(e,t,i){return We._emitter.on(e,t,i)}static _error(...e){We._emitter._emit("error",e),We._level>=Ue.Errors&&console.error(...e)}static _warn(...e){We._emitter._emit("warn",e),We._level>=Ue.Warnings&&console.warn(...e)}static _info(...e){We._emitter._emit("info",e),We._level>=Ue.Info&&console.info(...e)}}We._level=Ue.Info,We._emitterInstance=null;class He{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 Ve{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 je={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1};class Ke{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 Ke(this.bytes);return e.pos=this.pos,e}}const Xe=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],$e=[-1,1,2,3,4,5,6,8],Ge=e=>{if(!e||e.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");const t=new Ke(e),i=Qe(t),{frequencyIndex:r,sampleRate:n}=Ye(t),s=t.readBits(4);let a=null;s>=1&&s<=7&&(a=$e[s]);let o=i,l=!1,c=n;if(5===i||29===i)l=29===i,c=Ye(t).sampleRate,o=Qe(t),22===o&&t.skipBits(4);else for(;t.getBitsLeft()>15;){const e=t.pos;if(695===t.readBits(11)){5===Qe(t)&&t.readBits(1)&&(c=Ye(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}},Qe=e=>{const t=e.readBits(5);return 31===t?32+e.readBits(6):t},Ye=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&R(t.description)[4];return st(e,i+1)}return nt(e)},ot=e=>31&e,lt=e=>{const t=[],i=e.length;for(let r=0;r{const t=e.reduce((e,t)=>e+ct.byteLength+t.byteLength,0),i=new Uint8Array(t);let r=0;for(const n of e)i.set(ct,r),r+=ct.byteLength,i.set(n,r),r+=n.byteLength;return i},dt=(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:re(e,n,s.byteLength);break;case 4:e.setUint32(n,s.byteLength,!1)}n+=t,r.set(s,n),n+=s.byteLength}return r},ht=e=>{try{const t=[],i=[],r=[];for(const o of nt(e)){const n=e.subarray(o.offset,o.offset+o.length),s=ot(n[0]);s===et.SPS?t.push(n):s===et.PPS?i.push(n):s===et.SPS_EXT&&r.push(n)}if(0===t.length)return null;if(0===i.length)return null;const n=t[0],s=gt(n);I(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 We._error("Error building AVC Decoder Configuration Record:",t),null}},ft=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=F(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=lt(e),r=new Ke(i);r.skipBits(1),r.skipBits(2);if(7!==r.readBits(5))return null;const n=r.readAlignedByte(),s=r.readAlignedByte(),a=r.readAlignedByte();B(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=B(r),3===o&&(u=r.readBits(1)),l=B(r),c=B(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:C(fi),n=Math.min(Math.floor(r.maxDpbMbs/(e*i)),16);P=n,x=n}else P=0,x=0}return I(null!==x),{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:w,colourPrimaries:b,matrixCoefficients:v,transferCharacteristics:T,fullRangeFlag:S,numReorderFrames:P,maxDecFrameBuffering:x,vuiParametersFlagBitOffset:F,bitstreamRestrictionFlagBitOffset:E,bitstreamRestrictionFlag:R}}catch(i){return We._error("Error parsing AVC SPS:",i),null}},kt=e=>{const t=B(e);e.skipBits(4),e.skipBits(4);for(let i=0;i<=t;i++)B(e),B(e),e.skipBits(1);e.skipBits(5),e.skipBits(5),e.skipBits(5),e.skipBits(5)},yt=e=>{I(1!==e.bitstreamRestrictionFlag);const t=new Uint8Array(e.emulationUnpreventedBytes.byteLength+64),i=new Ke(e.emulationUnpreventedBytes),r=new Ke(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)):(I(null!==e.bitstreamRestrictionFlagBitOffset),r.copyBits(e.bitstreamRestrictionFlagBitOffset,i)),r.writeBits(1,1),r.writeBits(1,1),E(r,2),E(r,1),E(r,16),E(r,16),E(r,e.numReorderFrames),E(r,e.maxDecFrameBuffering),r.writeBits(1,1),r.writeBits((8-r.pos%8)%8,0);const n=r.pos/8;return I(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))},bt=(e,t)=>{if(t.description){const i=3&R(t.description)[21];return st(e,i+1)}return nt(e)},Tt=e=>e>>1&63,vt=e=>{try{const t=new Ke(lt(e));t.skipBits(16),t.readBits(4);const i=t.readBits(3),r=t.readBits(1),{general_profile_space:n,general_tier_flag:s,general_profile_idc:a,general_profile_compatibility_flags:o,general_constraint_indicator_flags:l,general_level_idc:c}=wt(t,i);B(t);const u=B(t);let d=0;3===u&&(d=t.readBits(1));const h=B(t),f=B(t);let m=h,p=f;if(t.readBits(1)){const e=B(t),i=B(t),r=B(t),n=B(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=B(t),k=B(t);B(t);const y=t.readBits(1);let b=0;for(let e=y?0:i;e<=i;e++)B(t),b=B(t),B(t);B(t),B(t),B(t),B(t),B(t),B(t),t.readBits(1)&&t.readBits(1)&&Pt(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(4),t.skipBits(4),B(t),B(t),t.skipBits(1));const T=B(t);if(It(t,T),t.readBits(1)){const e=B(t);for(let i=0;i{try{const t=[],i=[],r=[],n=[];for(const l of nt(e)){const s=e.subarray(l.offset,l.offset+l.length),a=Tt(s[0]);a===it.VPS_NUT?t.push(s):a===it.SPS_NUT?i.push(s):a===it.PPS_NUT?r.push(s):a!==it.PREFIX_SEI_NUT&&a!==it.SUFFIX_SEI_NUT||n.push(s)}if(0===i.length||0===r.length)return null;const s=vt(i[0]);if(!s)return null;let a=0;if(r.length>0){const e=r[0],t=new Ke(lt(e));t.skipBits(16),B(t),B(t),t.skipBits(1),t.skipBits(1),t.skipBits(3),t.skipBits(1),t.skipBits(1),B(t),B(t),_(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&B(t),_(t),_(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:it.VPS_NUT,nalUnits:t}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:it.SPS_NUT,nalUnits:i}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:it.PPS_NUT,nalUnits:r}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:Tt(n[0][0]),nalUnits:n}]:[]];return{configurationVersion:1,generalProfileSpace:s.generalProfileSpace,generalTierFlag:s.generalTierFlag,generalProfileIdc:s.generalProfileIdc,generalProfileCompatibilityFlags:s.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:s.generalConstraintIndicatorFlags,generalLevelIdc:s.generalLevelIdc,minSpatialSegmentationIdc:s.minSpatialSegmentationIdc,parallelismType:a,chromaFormatIdc:s.chromaFormatIdc,bitDepthLumaMinus8:s.bitDepthLumaMinus8,bitDepthChromaMinus8:s.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:s.spsMaxSubLayersMinus1+1,temporalIdNested:s.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:o}}catch(t){return We._error("Error building HEVC Decoder Configuration Record:",t),null}},wt=(e,t)=>{const i=e.readBits(2),r=e.readBits(1),n=e.readBits(5);let s=0;for(let u=0;u<32;u++)s=s<<1|e.readBits(1);const a=new Uint8Array(6);for(let u=0;u<6;u++)a[u]=e.readBits(8);const o=e.readBits(8),l=[],c=[];for(let u=0;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&&_(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-(B(e)+1)}else o=t-1;e.readBits(1),B(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=B(e),i=B(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=pt[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)&&(B(e),B(e)),e.readBits(1),e.readBits(1),e.readBits(1),e.readBits(1)&&(B(e),B(e),B(e),B(e)),e.readBits(1)&&(e.readBits(32),e.readBits(32),e.readBits(1)&&B(e),e.readBits(1)&&Bt(e,!0,t)),e.readBits(1)&&(e.readBits(1),e.readBits(1),e.readBits(1),a=B(e),B(e),B(e),B(e),B(e)),{pixelAspectRatio:o,colourPrimaries:i,transferCharacteristics:r,matrixCoefficients:n,fullRangeFlag:s,minSpatialSegmentationIdc:a}},Bt=(e,t,i)=>{let r=!1,n=!1,s=!1;r=1===e.readBits(1),n=1===e.readBits(1),(r||n)&&(s=1===e.readBits(1),s&&(e.readBits(8),e.readBits(5),e.readBits(1),e.readBits(5)),e.readBits(4),e.readBits(4),s&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5));for(let a=0;a<=i;a++){let t=!0;1===e.readBits(1)||(t=1===e.readBits(1));let i=!1;t?B(e):i=1===e.readBits(1);let a=1;if(!i){a=B(e)+1}r&&Et(e,a,s),n&&Et(e,a,s)}},Et=(e,t,i)=>{for(let r=0;r{const i=new Set;let r=_t.audAllowed;for(const s of bt(e,t)){if(r===_t.noMoreDataAllowed){i.add(s.offset);continue}const t=Tt(e[s.offset]);if(r===_t.eoBitstreamAllowed&&37!==t){i.add(s.offset);continue}let n=!1;35===t?r>_t.audAllowed?n=!0:r=_t.beforeFirstVcl:t<=31?r>_t.afterFirstVcl?n=!0:r=_t.afterFirstVcl:36===t?r!==_t.afterFirstVcl?n=!0:r=_t.eoBitstreamAllowed:37===t?r<_t.afterFirstVcl?n=!0:r=_t.noMoreDataAllowed:32===t||33===t||34===t||39===t||t>=41&&t<=44||t>=48&&t<=55?r>_t.beforeFirstVcl?n=!0:r=_t.beforeFirstVcl:(38===t||40===t||t>=45&&t<=47||t>=56&&t<=63)&&r<_t.afterFirstVcl&&(n=!0),n&&i.add(s.offset)}if(0===i.size)return null;const n=[];for(const s of bt(e,t))i.has(s.offset)||n.push(e.subarray(s.offset,s.offset+s.length));return((e,t)=>{if(t.description){const i=3&R(t.description)[21];return dt(e,i+1)}return ut(e)})(n,t)},At={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}},Dt=e=>{var t,i,r;const n=new Ke(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=C(mi).level;for(const m of mi)if(d<=m.maxPictureSize){h=m.level;break}const f=At[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}},Mt=function*(e){const t=new Ke(e),i=()=>{let e=0;for(let i=0;i<8;i++){const r=t.readAlignedByte();if(e+=(127&r)*u(2,7*i),!(128&r))break;if(7===i&&128&r)return null}return e>u(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);I(t.pos%8===0),yield{type:r,data:e.subarray(t.pos/8,t.pos/8+a)},t.skipBits(8*a)}},Nt=e=>{for(const{type:t,data:i}of Mt(e)){if(1!==t)continue;const e=new Ke(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,S=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&&(S=e.readBits(2))),{profile:r,level:s,tier:a,bitDepth:m,monochrome:p,chromaSubsamplingX:T,chromaSubsamplingY:v,chromaSamplePosition:S,videoFullRangeFlag:b,colourPrimaries:g,transferCharacteristics:k,matrixCoefficients:y}}return null},Ot=e=>{if(e.length<36)return null;const t=F(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)}},Lt=[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],zt=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}},Ut=(e,t,i)=>{switch(e){case"avc":for(const e of at(i,t)){const t=i[e.offset],r=ot(t);if(r>=et.NON_IDR_SLICE&&r<=et.SLICE_DPC)return"delta";if(r===et.IDR)return"key";if(r===et.SEI&&!Pe()){const t=i.subarray(e.offset,e.offset+e.length),r=lt(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 Ke(r);e.pos=8*n;const t=B(e),i=e.readBits(1);if(0===t&&1===i)return"key"}n+=t}while(n{var i,r;const n=F(e);let s=0;const a=n.getUint32(s,!0);s+=4;const o=A.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=_e(c),i=F(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=A.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})}}}},Vt=[2,1,2,3,3,4,4,5],jt=e=>{if(e.length<7)return null;if(11!==e[0]||119!==e[1])return null;const t=new Ke(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)}},Kt=[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],Xt=[1,2,3,6],$t=e=>{if(e.length<6)return null;if(11!==e[0]||119!==e[1])return null;const t=new Ke(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=Xt[s];let d;d=n<3?Je[n]/1e3:Ze[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}]}},Gt=e=>{const t=e.substreams[0];return I(t),t.fscod<3?Je[t.fscod]:null!==t.fscod2&&t.fscod2<3?Ze[t.fscod2]:null},Qt=e=>{const t=e.substreams[0];I(t);let i=Vt[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},Yt=[0,8e3,16e3,32e3,0,0,11025,22050,44100,0,0,12e3,24e3,48e3,96e3,192e3],Jt=[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],Zt=[16,16,20,20,0,24,24,0],ei=[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],ii=[32e3,44100,48e3,0],ri=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],ni=[512,1024,2048,4096],si=e=>{const t=oi(e),i=F(e);let r=t?4*Math.ceil(t.frameSize/4):0,n=null;for(;r+4<=e.length&&1683496997===i.getUint32(r);){const t=li(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}},ai=e=>{const t=si(e);return(null==t?void 0:t.core)?t.hasExtensions?"dtsh":"dtsc":null},oi=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 Ke(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>=ei.length)return null;const a=Yt[t.readBits(4)];if(0===a)return null;const o=Jt[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=Zt[t.readBits(3)];if(0===c)return null;const u=0!==l;return{frameSize:n,sampleRate:a,numberOfChannels:ei[s]+(u?1:0),sampleCount:32*r,channelLayout:ti[s]|(u?8:0),amode:s,lfePresent:u,bitRate:o,pcmResolution:c}},li=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 Ke(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=ii[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}}},ci=e=>de(e)+de(44646&e),ui=["avc","hevc","vp9","av1","vp8","prores"],di=["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"],hi=["aac","opus","mp3","vorbis","flac","ac3","eac3","dts",...di],fi=[{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}],pi=".01.01.01.01.00",gi=".0.110.01.01.01.0",ki=["ap4x","ap4h","apch","apcn","apcs","apco"],yi=["dtsc","dtsh","dtsl","dtse"],bi=e=>{const{codec:t,codecDescription:i,colorSpace:r,avcCodecInfo:n,hevcCodecInfo:s,vp9CodecInfo:a,av1CodecInfo:o,proresFormat:l}=e;if("avc"===t){if(I(null!==e.avcType),n){const t=new Uint8Array([n.avcProfileIndication,n.profileCompatibility,n.avcLevelIndication]);return`avc${e.avcType}.${K(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}.${K(i.subarray(1,4))}`}if("hevc"===t){let e,t,r,n,a,o;if(s)e=s.generalProfileSpace,t=s.generalProfileIdc,r=X(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=F(i),l=s.getUint8(1);e=l>>6&3,t=31&l,r=X(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=C(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.${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(pi)&&(t=t.slice(0,-15)),t}if("av1"===t){if(!o){const t=e.width*e.height;let i=C(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"),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)?M[r.primaries]:1,u=(null==r?void 0:r.transfer)?O[r.transfer]:1,d=(null==r?void 0:r.matrix)?z[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(gi)&&(f=f.slice(0,-17)),f}if("prores"===t)return null!=l?l:"apch";throw null!==t&&te(t),new TypeError(`Unhandled codec '${t}'.`)},Ti=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=mt(e.codecDescription))?void 0:i.sequenceParameterSets[0]),r){const e=gt(r);if(e)return{primaries:N[e.colourPrimaries],transfer:L[e.transferCharacteristics],matrix:U[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case"hevc":{let t=null==(n=null==(r=e.hevcCodecInfo)?void 0:r.arrays.find(e=>e.nalUnitType===it.SPS_NUT))?void 0:n.nalUnits[0];if(!t&&e.codecDescription&&(t=null==(a=null==(s=(e=>{try{const t=F(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,S=t.getUint8(i++),w=[];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===it.SPS_NUT))?void 0:a.nalUnits[0]),t){const e=vt(t);if(e)return{primaries:N[e.colourPrimaries],transfer:L[e.transferCharacteristics],matrix:U[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case"vp8":break;case"vp9":if(e.vp9CodecInfo)return{primaries:N[e.vp9CodecInfo.colourPrimaries],transfer:L[e.vp9CodecInfo.transferCharacteristics],matrix:U[e.vp9CodecInfo.matrixCoefficients],fullRange:!!e.vp9CodecInfo.videoFullRangeFlag};break;case"av1":if(e.av1CodecInfo)return{primaries:N[e.av1CodecInfo.colourPrimaries],transfer:L[e.av1CodecInfo.transferCharacteristics],matrix:U[e.av1CodecInfo.matrixCoefficients],fullRange:!!e.av1CodecInfo.videoFullRangeFlag};break;case"prores":if(e.proresCodecInfo)return{primaries:N[e.proresCodecInfo.colourPrimaries],transfer:L[e.proresCodecInfo.transferCharacteristics],matrix:U[e.proresCodecInfo.matrixCoefficients],fullRange:e.proresCodecInfo.fullRange}}return{primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0}},vi=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=Ge(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&&di.includes(t))return t;throw new TypeError(`Unhandled codec '${t}'.`)},Si=48e3,wi=/^pcm-([usf])(\d+)(be)?$/,Pi=e=>{if(I(di.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=wi.exec(e);let i;I(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?u(2,7):0}},Ii=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":ki.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":yi.includes(e)?"dts":"ulaw"===e?"ulaw":"alaw"===e?"alaw":wi.test(e)?e:"webvtt"===e?"webvtt":null,xi=[44100,48e3,32e3],Ci=[-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],Bi=1483304551,Ei=1231971951,_i=(e,t)=>3===e?3===t?21:36:3===t?13:21,Ri=(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=Ci[16*a*4+16*c+(n>>4&15)];if(-1===g)return{header:null,bytesAdvanced:1};const k=1e3*g,y=xi[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 Ai,Di;(Di=Ai||(Ai={}))[Di.FrameCount=1]="FrameCount",Di[Di.FileSize=2]="FileSize",Di[Di.Toc=4]="Toc";const Mi=e=>3===e?1:2;class Ni{constructor(e){this.input=e}dispose(){}}const Oi=new Uint8Array(0);class Li{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===Oi&&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===Oi}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){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 Li(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 Li(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 zi=e=>{const t=F(e);let i=0;const r=t.getUint8(i);i+=1,i+=3;const n=K(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=jo(e);const i=el(e,4);let r=8;1===t&&(t=Go(e),r=16);const n=t-r;return n<0?null:{name:i,totalSize:t,headerSize:r,contentSize:n}},Wi=e=>Xo(e)/65536,Hi=e=>Xo(e)/1073741824,Vi=e=>{let t=0;for(let i=0;i<4;i++){t<<=7;const i=zo(e);if(t|=127&i,0===(128&i))break}return t},ji=e=>{let t=qo(e);return e.skip(2),t=Math.min(t,e.remainingLength),A.decode(Lo(e,t))},Ki=e=>{const t=qi(e);if(!t||"data"!==t.name)return null;if(e.remainingLength<8)return null;const i=jo(e);e.skip(4);const r=Lo(e,t.contentSize-8);switch(i){case 1:return A.decode(r);case 2:return new TextDecoder("utf-16be").decode(r);case 13:return new He(r,"image/jpeg");case 14:return new He(r,"image/png");case 27:return new He(r,"image/bmp");default:return r}},Xi=16,$i=new Uint32Array(256),Gi=new Uint32Array(256),Qi=new Uint32Array(256),Yi=new Uint32Array(256),Ji=new Uint32Array(256),Zi=new Uint32Array(256),er=new Uint32Array(10);let tr=!1;class ir{constructor(){this.roundkey=new Uint32Array(44),this.iv=new Uint32Array(Xi/Uint32Array.BYTES_PER_ELEMENT),this.in=new Uint8Array(Xi),this.out=new Uint8Array(Xi),this.inView=new DataView(this.in.buffer),this.outView=new DataView(this.out.buffer)}init({key:e,iv:t}){I(16===e.byteLength),I(16===t.byteLength),tr||(()=>{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);$i[s]=t<<24|t<<16|t<<8|t,Zi[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);Gi[s]=n,Qi[s]=n>>>8|n<<24,Yi[s]=n>>>16|n<<16,Ji[s]=n>>>24|n<<8}let n=1;for(let s=0;s<10;s++)er[s]=n<<24,n=n<<1^(128&n?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 n=4;n<44;n+=4){const e=this.roundkey[n-1];this.roundkey[n]=this.roundkey[n-4]^4278190080&$i[e>>>16&255]^16711680&$i[e>>>8&255]^65280&$i[e>>>0&255]^255&$i[e>>>24&255]^er[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]]^Qi[255&$i[t>>>16&255]]^Yi[255&$i[t>>>8&255]]^Ji[255&$i[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=Gi[e>>>24]^Qi[r>>>16&255]^Yi[i>>>8&255]^Ji[255&t]^this.roundkey[n],c=Gi[t>>>24]^Qi[e>>>16&255]^Yi[r>>>8&255]^Ji[255&i]^this.roundkey[n+1],u=Gi[i>>>24]^Qi[t>>>16&255]^Yi[e>>>8&255]^Ji[255&r]^this.roundkey[n+2],d=Gi[r>>>24]^Qi[i>>>16&255]^Yi[t>>>8&255]^Ji[255&e]^this.roundkey[n+3],e=l,t=c,i=u,r=d}const h=4278190080&Zi[e>>>24&255]^16711680&Zi[r>>>16&255]^65280&Zi[i>>>8&255]^255&Zi[t>>>0&255]^this.roundkey[40],f=4278190080&Zi[t>>>24&255]^16711680&Zi[e>>>16&255]^65280&Zi[r>>>8&255]^255&Zi[i>>>0&255]^this.roundkey[41],m=4278190080&Zi[i>>>24&255]^16711680&Zi[t>>>16&255]^65280&Zi[e>>>8&255]^255&Zi[r>>>0&255]^this.roundkey[42],p=4278190080&Zi[r>>>24&255]^16711680&Zi[i>>>16&255]^65280&Zi[t>>>8&255]^255&Zi[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 rr extends Ni{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(Ce(r)&&(r=yield r),!r)break;const n=e,s=qi(r);if(!s)break;if("ftyp"===s.name||"styp"===s.name){const e=el(r,4);this.isQuickTime="qt "===e}else{if("moov"===s.name){let e=this.reader.requestSlice(r.filePos,s.contentSize);if(Ce(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){I(null!==this.reader.fileSize);let e=this.reader.requestSlice(this.reader.fileSize-4,4);Ce(e)&&(e=yield e),I(e);const t=jo(e),i=this.reader.fileSize-t;if(i>=0&&i<=this.reader.fileSize-16){let e=this.reader.requestSliceRange(i,8,16);if(Ce(e)&&(e=yield e),e){const t=qi(e);if(t&&"mfra"===t.name){let i=this.reader.requestSlice(e.filePos,t.contentSize);Ce(i)&&(i=yield i),i&&this.readContiguousBoxes(i)}}}}}))()}copyMetadataFromInitInput(e){return y(this,null,function*(){const t=yield e._getDemuxer();if(t.constructor!==rr)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(I(t.info),"video"===t.info.type&&-1!==t.info.width){const e=t;t.trackBacking=new sr(e),this.tracks.push(t)}else if("audio"===t.info.type&&-1!==t.info.numberOfChannels){const e=t;t.trackBacking=new ar(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;I(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&&di.includes(e.info.codec)&&0===r.sampleCompositionTimeOffsets.length){I("audio"===(null==(i=e.info)?void 0:i.type));const t=Pi(e.info.codec),n=[],s=[];for(let i=0;ie.startIndex),u=r.sampleTimingEntries[c],d=G(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=C(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)dr(e,r.timestamp);else{const t=G(i,s.moofOffset-1,e=>e.moofOffset);if(-1!==t){const r=i[t];dr(e,r.endTimestamp)}}e.startTimestampIsFinal=!0}const r=G(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 pr(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;fe(t.languageCode)||(t.languageCode=ae)}}break;case"hdlr":{const t=this.currentTrack;if(!t)break;e.skip(8);const i=el(e,4);"vide"===i?t.info={type:"video",width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:h({},W),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=ge,this.readContiguousBoxes(e.slice(ye,ke.contentSize))}break;case"stsd":{const t=this.currentTrack;if(!t)break;if(null===t.info||t.sampleTable)break;const i=zo(e);e.skip(3);const r=jo(e);for(let n=0;n0&&(1===a?(e.skip(4),l=8*jo(e),e.skip(8)):2===a&&(e.skip(4),c=Zo(e),o=jo(e),e.skip(4),l=jo(e),u=jo(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=Si;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(yi.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":(We._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":(We._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":(We._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":(We._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":(We._warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null):32===e?t.info.codec="pcm-f32be":64===e?t.info.codec="pcm-f64be":(We._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!==zo(e),t.encryptionInfo.defaultPerSampleIvSize=zo(e),t.encryptionInfo.defaultKid=K(Lo(e,16)),t.encryptionInfo.defaultIsProtected&&0===t.encryptionInfo.defaultPerSampleIvSize){const i=zo(e),r=new Uint8Array(16);r.set(Lo(e,i),0),t.encryptionInfo.defaultConstantIv=r}}break;case"avcC":{const t=this.currentTrack;if(!t)break;if(I(t.info),0===ke.contentSize)break;t.info.codecDescription=Lo(e,ke.contentSize)}break;case"hvcC":{const t=this.currentTrack;if(!t)break;if(I(t.info),0===ke.contentSize)break;t.info.codecDescription=Lo(e,ke.contentSize)}break;case"vpcC":{const i=this.currentTrack;if(!i)break;I("video"===(null==(t=i.info)?void 0:t.type)),e.skip(4);const r=zo(e),n=zo(e),s=zo(e),a=s>>4,o=s>>1&7,l=1&s,c=zo(e),u=zo(e),d=zo(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;I("video"===(null==(i=t.info)?void 0:i.type)),e.skip(1);const o=zo(e),l=o>>5,c=31&o,u=zo(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=Lo(e,ke.contentSize-4),b=Nt(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;I("video"===(null==(o=t.info)?void 0:o.type));const i=el(e,4);if("nclx"!==i&&"nclc"!==i)break;const r=qo(e),n=qo(e),s=qo(e);let a;"nclx"===i&&(a=Boolean(128&zo(e))),t.info.colorSpace={primaries:N[r],transfer:L[n],matrix:U[s],fullRange:a}}break;case"pasp":{const t=this.currentTrack;if(!t)break;I("video"===(null==(l=t.info)?void 0:l.type));const i=jo(e),r=jo(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);I(3===zo(e)),Vi(e),e.skip(2);const i=zo(e),r=0!==(64&i),n=0!==(32&i);if(0!==(128&i)&&e.skip(2),r){const t=zo(e);e.skip(t)}n&&e.skip(2);I(4===zo(e));const s=Vi(e),a=e.filePos,o=zo(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":We._warn(`Unsupported audio codec (objectTypeIndication ${o}) - discarding track.`),e.skip(12),s>e.filePos-a){I(5===zo(e));const i=Vi(e);if(t.info.codecDescription=Lo(e,i),"aac"===t.info.codec){const e=Ge(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;I("audio"===(null==(u=t.info)?void 0:u.type)),t.info.pcmLittleEndian=!!(255&qo(e))}break;case"pcmC":{const t=this.currentTrack;if(!t)break;I("audio"===(null==(d=t.info)?void 0:d.type)),e.skip(4);const i=zo(e);t.info.pcmLittleEndian=Boolean(1&i),t.info.pcmSampleSize=zo(e)}break;case"dOps":{const t=this.currentTrack;if(!t)break;I("audio"===(null==(m=t.info)?void 0:m.type)),e.skip(1);const i=zo(e),r=qo(e),n=jo(e),s=Ho(e),a=zo(e);let o;o=0!==a?Lo(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;I("audio"===(null==(p=t.info)?void 0:p.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=Lo(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;I("audio"===(null==(g=t.info)?void 0:g.type));const i=Lo(e,3),r=new Ke(i),n=r.readBits(2);r.skipBits(8);const s=r.readBits(3),a=r.readBits(1);n<3&&(t.info.sampleRate=Je[n]),t.info.numberOfChannels=Vt[s]+a}break;case"dec3":{const t=this.currentTrack;if(!t)break;I("audio"===(null==(k=t.info)?void 0:k.type));const i=(e=>{if(e.length<2)return null;const t=new Ke(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}})(Lo(e,ke.contentSize));if(!i){We._warn("Invalid dec3 box contents, ignoring.");break}const r=Gt(i);null!==r&&(t.info.sampleRate=r),t.info.numberOfChannels=Qt(i)}break;case"ddts":{const t=this.currentTrack;if(!t)break;I("audio"===(null==(y=t.info)?void 0:y.type));const i=(e=>{if(e.length<20)return null;const t=F(e),i=t.getUint32(0);if(0===i)return null;const r=new Ke(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=ci(o):ae.id===i);if(!r)break;const n=jo(e),s=(12&n)>>2,a=3&n,o=[zo,qo,Wo,jo],l=o[(48&n)>>4],c=o[s],u=o[a],d=jo(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!=(T=null==d?void 0:d.defaultSampleDescriptionIndex)?T:null,defaultSampleDuration:null!=(v=null==d?void 0:d.defaultSampleDuration)?v:null,defaultSampleSize:null!=(S=null==d?void 0:d.defaultSampleSize)?S:null,defaultSampleFlags:null!=(w=null==d?void 0:d.defaultSampleFlags)?w:null,startTimestamp:null,encryptionAuxInfo:null},i?u.currentFragmentState.baseDataOffset=Go(e):l&&(u.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),r&&(u.currentFragmentState.sampleDescriptionIndex=jo(e)),n&&(u.currentFragmentState.defaultSampleDuration=jo(e)),s&&(u.currentFragmentState.defaultSampleSize=jo(e)),a&&(u.currentFragmentState.defaultSampleFlags=jo(e)),o&&(u.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{const t=this.currentTrack;if(!t)break;I(t.currentFragmentState);const i=zo(e);e.skip(3);const r=0===i?jo(e):Go(e);t.currentFragmentState.startTimestamp=r}break;case"trun":{const t=this.currentTrack;if(!t)break;I(this.currentFragment),I(t.currentFragmentState);const i=zo(e),r=Wo(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=jo(e);let d=null;n&&(d=Xo(e));let h,f=null;s&&(f=jo(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=Lo(e,r));const s=mr(t);s.defaultSampleInfoSize=i,s.sampleSizes=n,s.sampleCount=r}break;case"saio":{const t=this.currentTrack;if(!t||!t.encryptionInfo)break;const i=zo(e);if(1&Wo(e)){const i=el(e,4),r=jo(e);if(i!==t.encryptionInfo.scheme||0!==r)break}const r=jo(e);if(0===r)break;r>1&&We._warn("Multiple saio entries are not supported; using the first offset only.");let n=0===i?jo(e):Number(Go(e));this.currentFragment&&(n+=this.currentFragment.moofOffset);mr(t).offset=n}break;case"senc":{const t=this.currentTrack;if(!t||!t.encryptionInfo)break;I(this.currentFragment);const i=this.currentFragment.trackData.get(t.id);if(!i)break;e.skip(1);const r=Wo(e),n=Boolean(2&r),s=jo(e),a=t.encryptionInfo.defaultPerSampleIvSize;I(null!==a);for(let o=0;o0?r.set(Lo(e,a),0):r.set(t.encryptionInfo.defaultConstantIv,0);let s=null;if(n){const t=qo(e);s=[];for(let i=0;i0&&(null!=(ce=this.metadataTags).trackNumber||(ce.trackNumber=t)),i&&Number.isInteger(i)&&i>0&&(null!=(ue=this.metadataTags).tracksTotal||(ue.tracksTotal=i))}break;case"trkn":if(n instanceof Uint8Array&&n.length>=6){const e=F(n),t=e.getUint16(2,!1),i=e.getUint16(4,!1);t>0&&(null!=(de=this.metadataTags).trackNumber||(de.trackNumber=t)),i>0&&(null!=(he=this.metadataTags).tracksTotal||(he.tracksTotal=i))}break;case"disc":case"disk":if(n instanceof Uint8Array&&n.length>=6){const e=F(n),t=e.getUint16(2,!1),i=e.getUint16(4,!1);t>0&&(null!=(me=this.metadataTags).discNumber||(me.discNumber=t)),i>0&&(null!=(pe=this.metadataTags).discsTotal||(pe.discsTotal=i))}}}}}return e.filePos=be,!0}}class nr{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;I(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 oe(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=or(r,i),s=yield this.fetchPacketForSampleIndex(n,t);return fr(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=G(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=ee(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 I(-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=cr(i,e);if(!r)return null;let n;if(t.metadataOnly)n=Oi;else{let t=this.internalTrack.demuxer.reader.requestSlice(r.sampleOffset,r.sampleSize);if(Ce(t)&&(t=yield t),!t)return null;if(n=Lo(t,r.sampleSize),this.internalTrack.encryptionInfo){let t=null;if(this.internalTrack.encryptionAuxInfo){const i=yield pr(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);ee.timestamp),f=-1!==h?this.internalTrack.fragmentLookupTable[h]:null,m=G(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(Ce(e)&&(e=yield e),!e)break;const i=k,s=qi(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&&Ot(e.data)}}else{const e=yield this.getFirstPacket({}),t=e&&Nt(e.data);t&&(this.internalTrack.info.av1CodecInfo=t)}else{const t=yield this.getFirstPacket({}),i=t&&Dt(t.data);i&&(this.internalTrack.info.vp9CodecInfo=f(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&&St(e.data)}else{const e=yield this.getFirstPacket({});this.internalTrack.info.avcCodecInfo=e&&ht(e.data)}if(!q(this.internalTrack.info.colorSpace)){const e=Ti(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:bi(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 ar extends nr{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&&ai(e.data)}return{codec:vi(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 or=(e,t)=>{if(e.presentationTimestamps){const i=G(e.presentationTimestamps,t,e=>e.presentationTimestamp);return-1===i?-1:e.presentationTimestamps[i].sampleIndex}{const i=G(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)}},lr=(e,t)=>{var i;if(!e.keySampleIndices)return or(e,t);if(e.presentationTimestamps){const i=G(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.keySampleIndices,i,e=>e))return i}return-1}{const r=or(e,t),n=G(e.keySampleIndices,r,e=>e);return null!=(i=e.keySampleIndices[n])?i:-1}},cr=(e,t)=>{const i=G(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=G(e.sampleCompositionTimeOffsets,t,e=>e.startIndex),a=e.sampleCompositionTimeOffsets[s];a&&t-a.startIndexe.startSampleIndex),c=e.sampleToChunk[l];I(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)}},ur=(e,t)=>{var i;if(!e.keySampleIndices)return t+1;const r=G(e.keySampleIndices,t,e=>e);return null!=(i=e.keySampleIndices[r+1])?i:-1},dr=(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},hr=e=>{const[t,i]=e,r=Math.atan2(i,t);return Number.isFinite(r)?r*(180/Math.PI):0},fr=e=>0===e.sampleSizes.length,mr=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}},pr=(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{I(i.sampleSizes);for(let e=0;e0?i.defaultSampleInfoSize:i.sampleSizes[e],o=new Uint8Array(16);s>0?o.set(Lo(n,s),0):o.set(t.defaultConstantIv,0);let l=null;if(r>s){const e=qo(n);l=[];for(let t=0;te.defaultConstantIv?{iv:e.defaultConstantIv,subsamples:null}:null,kr=(e,t,i,r)=>y(null,null,function*(){var n;I(e.encryptionInfo);const s=e.encryptionInfo;I(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{I(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);I(null!==t.defaultCryptByteBlock&&null!==t.defaultSkipByteBlock);const o=Tr(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}),br=(e,t,i,r)=>{const n=new ir;n.init({key:e,iv:i.iv});const s=t.defaultCryptByteBlock,a=t.defaultSkipByteBlock;if(I(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 vr,Sr;(Sr=vr||(vr={}))[Sr.EBML=440786851]="EBML",Sr[Sr.EBMLVersion=17030]="EBMLVersion",Sr[Sr.EBMLReadVersion=17143]="EBMLReadVersion",Sr[Sr.EBMLMaxIDLength=17138]="EBMLMaxIDLength",Sr[Sr.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",Sr[Sr.DocType=17026]="DocType",Sr[Sr.DocTypeVersion=17031]="DocTypeVersion",Sr[Sr.DocTypeReadVersion=17029]="DocTypeReadVersion",Sr[Sr.Void=236]="Void",Sr[Sr.Segment=408125543]="Segment",Sr[Sr.SeekHead=290298740]="SeekHead",Sr[Sr.Seek=19899]="Seek",Sr[Sr.SeekID=21419]="SeekID",Sr[Sr.SeekPosition=21420]="SeekPosition",Sr[Sr.Duration=17545]="Duration",Sr[Sr.Info=357149030]="Info",Sr[Sr.TimestampScale=2807729]="TimestampScale",Sr[Sr.MuxingApp=19840]="MuxingApp",Sr[Sr.WritingApp=22337]="WritingApp",Sr[Sr.Tracks=374648427]="Tracks",Sr[Sr.TrackEntry=174]="TrackEntry",Sr[Sr.TrackNumber=215]="TrackNumber",Sr[Sr.TrackUID=29637]="TrackUID",Sr[Sr.TrackType=131]="TrackType",Sr[Sr.FlagEnabled=185]="FlagEnabled",Sr[Sr.FlagDefault=136]="FlagDefault",Sr[Sr.FlagForced=21930]="FlagForced",Sr[Sr.FlagOriginal=21934]="FlagOriginal",Sr[Sr.FlagHearingImpaired=21931]="FlagHearingImpaired",Sr[Sr.FlagVisualImpaired=21932]="FlagVisualImpaired",Sr[Sr.FlagCommentary=21935]="FlagCommentary",Sr[Sr.FlagLacing=156]="FlagLacing",Sr[Sr.Name=21358]="Name",Sr[Sr.Language=2274716]="Language",Sr[Sr.LanguageBCP47=2274717]="LanguageBCP47",Sr[Sr.CodecID=134]="CodecID",Sr[Sr.CodecPrivate=25506]="CodecPrivate",Sr[Sr.CodecDelay=22186]="CodecDelay",Sr[Sr.SeekPreRoll=22203]="SeekPreRoll",Sr[Sr.DefaultDuration=2352003]="DefaultDuration",Sr[Sr.Video=224]="Video",Sr[Sr.PixelWidth=176]="PixelWidth",Sr[Sr.PixelHeight=186]="PixelHeight",Sr[Sr.DisplayWidth=21680]="DisplayWidth",Sr[Sr.DisplayHeight=21690]="DisplayHeight",Sr[Sr.DisplayUnit=21682]="DisplayUnit",Sr[Sr.AlphaMode=21440]="AlphaMode",Sr[Sr.Audio=225]="Audio",Sr[Sr.SamplingFrequency=181]="SamplingFrequency",Sr[Sr.Channels=159]="Channels",Sr[Sr.BitDepth=25188]="BitDepth",Sr[Sr.SimpleBlock=163]="SimpleBlock",Sr[Sr.BlockGroup=160]="BlockGroup",Sr[Sr.Block=161]="Block",Sr[Sr.BlockAdditions=30113]="BlockAdditions",Sr[Sr.BlockMore=166]="BlockMore",Sr[Sr.BlockAdditional=165]="BlockAdditional",Sr[Sr.BlockAddID=238]="BlockAddID",Sr[Sr.BlockDuration=155]="BlockDuration",Sr[Sr.ReferenceBlock=251]="ReferenceBlock",Sr[Sr.Cluster=524531317]="Cluster",Sr[Sr.Timestamp=231]="Timestamp",Sr[Sr.Cues=475249515]="Cues",Sr[Sr.CuePoint=187]="CuePoint",Sr[Sr.CueTime=179]="CueTime",Sr[Sr.CueTrackPositions=183]="CueTrackPositions",Sr[Sr.CueTrack=247]="CueTrack",Sr[Sr.CueClusterPosition=241]="CueClusterPosition",Sr[Sr.Colour=21936]="Colour",Sr[Sr.MatrixCoefficients=21937]="MatrixCoefficients",Sr[Sr.TransferCharacteristics=21946]="TransferCharacteristics",Sr[Sr.Primaries=21947]="Primaries",Sr[Sr.Range=21945]="Range",Sr[Sr.Projection=30320]="Projection",Sr[Sr.ProjectionType=30321]="ProjectionType",Sr[Sr.ProjectionPoseRoll=30325]="ProjectionPoseRoll",Sr[Sr.Attachments=423732329]="Attachments",Sr[Sr.AttachedFile=24999]="AttachedFile",Sr[Sr.FileDescription=18046]="FileDescription",Sr[Sr.FileName=18030]="FileName",Sr[Sr.FileMediaType=18016]="FileMediaType",Sr[Sr.FileData=18012]="FileData",Sr[Sr.FileUID=18094]="FileUID",Sr[Sr.Chapters=272869232]="Chapters",Sr[Sr.Tags=307544935]="Tags",Sr[Sr.Tag=29555]="Tag",Sr[Sr.Targets=25536]="Targets",Sr[Sr.TargetTypeValue=26826]="TargetTypeValue",Sr[Sr.TargetType=25546]="TargetType",Sr[Sr.TagTrackUID=25541]="TagTrackUID",Sr[Sr.TagEditionUID=25545]="TagEditionUID",Sr[Sr.TagChapterUID=25540]="TagChapterUID",Sr[Sr.TagAttachmentUID=25542]="TagAttachmentUID",Sr[Sr.SimpleTag=26568]="SimpleTag",Sr[Sr.TagName=17827]="TagName",Sr[Sr.TagLanguage=17530]="TagLanguage",Sr[Sr.TagString=17543]="TagString",Sr[Sr.TagBinary=17541]="TagBinary",Sr[Sr.ContentEncodings=28032]="ContentEncodings",Sr[Sr.ContentEncoding=25152]="ContentEncoding",Sr[Sr.ContentEncodingOrder=20529]="ContentEncodingOrder",Sr[Sr.ContentEncodingScope=20530]="ContentEncodingScope",Sr[Sr.ContentCompression=20532]="ContentCompression",Sr[Sr.ContentCompAlgo=16980]="ContentCompAlgo",Sr[Sr.ContentCompSettings=16981]="ContentCompSettings",Sr[Sr.ContentEncryption=20533]="ContentEncryption";const wr=[vr.EBML,vr.Segment],Pr=[vr.SeekHead,vr.Info,vr.Cluster,vr.Tracks,vr.Cues,vr.Attachments,vr.Chapters,vr.Tags],Ir=[...wr,...Pr],xr=16,Cr=e=>{if(e.remainingLength<1)return null;const t=zo(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=zo(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=Cr(e);if(null===t)return null;if(e.remainingLength{if(e.remainingLength<1)return null;if(255===zo(e))return;e.skip(-1);const t=Br(e);return null===t?null:72057594037927940!==t?t:void 0},Fr=e=>{I(e.remainingLength>=2);const t=_r(e);if(null===t)return null;const i=Rr(e);return null===i?null:{id:t,size:i}},Ar=(e,t)=>{const i=Lo(e,t);let r=0;for(;r{const i=Lo(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?Jo(e):Zo(e)},Nr=(e,t,i,r)=>y(null,null,function*(){const n=new Set(i);let s=t;for(;null===r||ss?r:s,found:!1}}),Or=(e,t,i,r)=>y(null,null,function*(){const n=u(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,xr);if(Ce(t)&&(t=yield t),!t)break;const i=Fr(t);if(!i)break;const r=i.id;let n=i.size;const s=t.filePos;if(r===vr.EBML){Jr(n);let e=this.reader.requestSlice(s,n);if(Ce(e)&&(e=yield e),!e)break;this.readContiguousElements(e)}else if(r===vr.Segment){if(yield this.readSegment(s,n),void 0===n)break;if(null===this.reader.fileSize)break}else if(r===vr.Cluster){if(null===this.reader.fileSize)break;if(void 0===n){n=(yield Nr(this.reader,s,Ir,this.reader.fileSize)).pos-s}const e=C(this.segments);e&&(e.elementEndPos=s+n)}Jr(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=an[l].flag;this.currentSegment[e]=!0,Jr(a);let t=this.reader.requestSlice(o,a);Ce(t)&&(t=yield t),t&&this.readContiguousElements(t)}else if(s===vr.Tags||s===vr.Attachments){s===vr.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,Jr(a);let e=this.reader.requestSlice(o,a);Ce(e)&&(e=yield e),e&&this.readContiguousElements(e)}else if(s===vr.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=an.find(e=>e.id===t.id);if(!i)continue;if(this.currentSegment[i.flag])continue;let r=this.reader.requestSliceRange(e+t.segmentPosition,2,xr);if(Ce(r)&&(r=yield r),!r)continue;const n=Fr(r);if(!n)continue;const{id:s,size:a}=n;if(s!==i.id)continue;Jr(a),this.currentSegment[i.flag]=!0;let o=this.reader.requestSlice(r.filePos,a);Ce(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,xr);Ce(r)&&(r=yield r),I(r);const n=e,s=Fr(r);I(s);I(s.id===vr.Cluster);let a=s.size;const o=r.filePos;if(void 0===a){a=(yield Nr(this.reader,o,Ir,t.elementEndPos)).pos-o}let l=this.reader.requestSlice(o,a);Ce(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,Ir);c.elementEndPos=e}for(const[,e]of c.trackData){const t=e.track;I(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[C(e.presentationTimestamps).blockIndex];e.startTimestamp=r.timestamp,e.endTimestamp=s.timestamp+s.duration;const a=G(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,m,p,g,k,y,b,T,v,S,w,P,C,B,E,_,R,F,D,M,O,z,q,H,V,j,K,X,$,G,Q,Y,J,Z,ee,te,ie,re,ne,se,oe,le;const ce=Fr(e);if(!ce)return!1;if(t&&t.includes(ce.id))return!1;const{id:ue,size:de}=ce,he=e.filePos;switch(Jr(de),ue){case vr.DocType:this.isWebM="webm"===Ar(e,de);break;case vr.Seek:{if(!this.currentSegment)break;const t={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(t),this.readContiguousElements(e.slice(he,de)),-1!==t.id&&-1!==t.segmentPosition||this.currentSegment.seekEntries.pop()}break;case vr.SeekID:{const t=null==(i=this.currentSegment)?void 0:i.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.id=Er(e,de)}break;case vr.SeekPosition:{const t=null==(r=this.currentSegment)?void 0:r.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.segmentPosition=Er(e,de)}break;case vr.TimestampScale:if(!this.currentSegment)break;this.currentSegment.timestampScale=Er(e,de),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale;break;case vr.Duration:if(!this.currentSegment)break;this.currentSegment.duration=Mr(e,de);break;case vr.TrackEntry:if(!this.currentSegment)break;if(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:f(h({},je),{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(he,de)),!this.currentTrack)break;if(this.currentTrack.decodingInstructions.some(e=>{var t;return"decompress"!==(null==(t=e.data)?void 0:t.type)||e.scope!==tn.Block||e.data.algorithm!==nn.HeaderStripping})&&(We._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===Lr)this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(this.currentTrack.codecId===zr)this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(t===Ur)this.currentTrack.info.codec="vp8";else if(t===qr)this.currentTrack.info.codec="vp9";else if(t===Wr)this.currentTrack.info.codec="av1";else if(t===Hr){const e=this.currentTrack.codecPrivate?A.decode(this.currentTrack.codecPrivate):"";ki.includes(e)&&(this.currentTrack.info.codec="prores",this.currentTrack.info.proresFormat=e)}const e=this.currentTrack;this.currentTrack.trackBacking=new un(e),this.currentSegment.tracks.push(this.currentTrack)}else if("audio"===this.currentTrack.info.type){t===Vr?(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===jr?this.currentTrack.info.codec="mp3":t===Kr?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=Si):t===Xr?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===$r?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Gr?(this.currentTrack.info.codec="ac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Qr?(this.currentTrack.info.codec="eac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Yr?(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 dn(e),this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null;break;case vr.TrackNumber:if(!this.currentTrack)break;this.currentTrack.id=Er(e,de);break;case vr.TrackType:{if(!this.currentTrack)break;const t=Er(e,de);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({},W),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 vr.FlagEnabled:if(!this.currentTrack)break;Er(e,de)||(this.currentTrack=null);break;case vr.FlagDefault:if(!this.currentTrack)break;this.currentTrack.disposition.default=!!Er(e,de);break;case vr.FlagForced:if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!Er(e,de);break;case vr.FlagOriginal:if(!this.currentTrack)break;this.currentTrack.disposition.original=!!Er(e,de);break;case vr.FlagHearingImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!Er(e,de);break;case vr.FlagVisualImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!Er(e,de);break;case vr.FlagCommentary:if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!Er(e,de);break;case vr.CodecID:if(!this.currentTrack)break;this.currentTrack.codecId=Ar(e,de);break;case vr.CodecPrivate:if(!this.currentTrack)break;this.currentTrack.codecPrivate=Lo(e,de);break;case vr.DefaultDuration:if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=Er(e,de);break;case vr.Name:if(!this.currentTrack)break;this.currentTrack.name=Dr(e,de);break;case vr.Language:if(!this.currentTrack)break;if(this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=Ar(e,de),fe(this.currentTrack.languageCode)||(this.currentTrack.languageCode=ae);break;case vr.LanguageBCP47:{if(!this.currentTrack)break;const t=Ar(e,de).split("-")[0];this.currentTrack.languageCode=t||ae,this.currentTrack.hasLanguageBcp47=!0}break;case vr.Video:if("video"!==(null==(s=null==(n=this.currentTrack)?void 0:n.info)?void 0:s.type))break;this.readContiguousElements(e.slice(he,de));break;case vr.PixelWidth:if("video"!==(null==(o=null==(a=this.currentTrack)?void 0:a.info)?void 0:o.type))break;this.currentTrack.info.width=Er(e,de);break;case vr.PixelHeight:if("video"!==(null==(c=null==(l=this.currentTrack)?void 0:l.info)?void 0:c.type))break;this.currentTrack.info.height=Er(e,de);break;case vr.DisplayWidth:if("video"!==(null==(d=null==(u=this.currentTrack)?void 0:u.info)?void 0:d.type))break;this.currentTrack.info.displayWidth=Er(e,de);break;case vr.DisplayHeight:if("video"!==(null==(p=null==(m=this.currentTrack)?void 0:m.info)?void 0:p.type))break;this.currentTrack.info.displayHeight=Er(e,de);break;case vr.DisplayUnit:if("video"!==(null==(k=null==(g=this.currentTrack)?void 0:g.info)?void 0:k.type))break;this.currentTrack.info.displayUnit=Er(e,de);break;case vr.AlphaMode:if("video"!==(null==(b=null==(y=this.currentTrack)?void 0:y.info)?void 0:b.type))break;this.currentTrack.info.alphaMode=1===Er(e,de);break;case vr.Colour:if("video"!==(null==(v=null==(T=this.currentTrack)?void 0:T.info)?void 0:v.type))break;this.readContiguousElements(e.slice(he,de));break;case vr.MatrixCoefficients:{if("video"!==(null==(w=null==(S=this.currentTrack)?void 0:S.info)?void 0:w.type))break;const t=Er(e,de),i=U[t];this.currentTrack.info.colorSpace.matrix=i}break;case vr.Range:{if("video"!==(null==(C=null==(P=this.currentTrack)?void 0:P.info)?void 0:C.type))break;const t=Er(e,de);this.currentTrack.info.colorSpace.fullRange=1===t||2===t?2===t:void 0}break;case vr.TransferCharacteristics:{if("video"!==(null==(E=null==(B=this.currentTrack)?void 0:B.info)?void 0:E.type))break;const t=Er(e,de),i=L[t];this.currentTrack.info.colorSpace.transfer=i}break;case vr.Primaries:{if("video"!==(null==(R=null==(_=this.currentTrack)?void 0:_.info)?void 0:R.type))break;const t=Er(e,de),i=N[t];this.currentTrack.info.colorSpace.primaries=i}break;case vr.Projection:if("video"!==(null==(D=null==(F=this.currentTrack)?void 0:F.info)?void 0:D.type))break;this.readContiguousElements(e.slice(he,de));break;case vr.ProjectionPoseRoll:{if("video"!==(null==(O=null==(M=this.currentTrack)?void 0:M.info)?void 0:O.type))break;const t=-Mr(e,de);try{this.currentTrack.info.rotation=x(t)}catch(me){}}break;case vr.Audio:if("audio"!==(null==(q=null==(z=this.currentTrack)?void 0:z.info)?void 0:q.type))break;this.readContiguousElements(e.slice(he,de));break;case vr.SamplingFrequency:if("audio"!==(null==(V=null==(H=this.currentTrack)?void 0:H.info)?void 0:V.type))break;this.currentTrack.info.sampleRate=Mr(e,de);break;case vr.Channels:if("audio"!==(null==(K=null==(j=this.currentTrack)?void 0:j.info)?void 0:K.type))break;this.currentTrack.info.numberOfChannels=Er(e,de);break;case vr.BitDepth:if("audio"!==(null==($=null==(X=this.currentTrack)?void 0:X.info)?void 0:$.type))break;this.currentTrack.info.bitDepth=Er(e,de);break;case vr.CuePoint:if(!this.currentSegment)break;this.readContiguousElements(e.slice(he,de)),this.currentCueTime=null;break;case vr.CueTime:this.currentCueTime=Er(e,de);break;case vr.CueTrackPositions:{if(null===this.currentCueTime)break;I(this.currentSegment);const t={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(t),this.readContiguousElements(e.slice(he,de)),-1!==t.trackId&&-1!==t.clusterPosition||this.currentSegment.cuePoints.pop()}break;case vr.CueTrack:{const t=null==(G=this.currentSegment)?void 0:G.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;t.trackId=Er(e,de)}break;case vr.CueClusterPosition:{const t=null==(Q=this.currentSegment)?void 0:Q.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;I(this.currentSegment),t.clusterPosition=this.currentSegment.dataStartPos+Er(e,de)}break;case vr.Timestamp:if(!this.currentCluster)break;this.currentCluster.timestamp=Er(e,de);break;case vr.SimpleBlock:{if(!this.currentCluster)break;const t=Br(e);if(null===t)break;const i=this.getTrackDataInCluster(this.currentCluster,t);if(!i)break;const r=Ho(e),n=zo(e),s=n>>1&3;let a=!!(128&n);"audio"===(null==(Y=i.track.info)?void 0:Y.type)&&i.track.info.codec&&(a=!0);const o=Lo(e,de-(e.filePos-he)),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 vr.BlockGroup:if(!this.currentCluster)break;this.readContiguousElements(e.slice(he,de)),this.currentBlock=null;break;case vr.Block:{if(!this.currentCluster)break;const t=Br(e);if(null===t)break;const i=this.getTrackDataInCluster(this.currentCluster,t);if(!i)break;const r=Ho(e),n=zo(e)>>1&3,s=Lo(e,de-(e.filePos-he)),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 vr.BlockAdditions:this.readContiguousElements(e.slice(he,de));break;case vr.BlockMore:if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(he,de)),this.currentBlockAdditional.data&&1===this.currentBlockAdditional.addId&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null;break;case vr.BlockAdditional:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=Lo(e,de);break;case vr.BlockAddID:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=Er(e,de);break;case vr.BlockDuration:if(!this.currentBlock)break;this.currentBlock.duration=Er(e,de);break;case vr.ReferenceBlock:if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1;break;case vr.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(he,de));break;case vr.Targets:this.readContiguousElements(e.slice(he,de));break;case vr.TargetTypeValue:50!==Er(e,de)&&(this.currentTagTargetIsMovie=!1);break;case vr.TagTrackUID:case vr.TagEditionUID:case vr.TagChapterUID:case vr.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case vr.SimpleTag:if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(he,de));break;case vr.TagName:this.currentSimpleTagName=Dr(e,de);break;case vr.TagString:{if(!this.currentSimpleTagName)break;const t=Dr(e,de);this.processTagValue(this.currentSimpleTagName,t)}break;case vr.TagBinary:{if(!this.currentSimpleTagName)break;const t=Lo(e,de);this.processTagValue(this.currentSimpleTagName,t)}break;case vr.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(he,de));const t=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(null!=t.raw||(t.raw={}),t.raw[this.currentAttachedFile.fileUid.toString()]=new Ve(this.currentAttachedFile.fileData,null!=(J=this.currentAttachedFile.fileMediaType)?J:void 0,null!=(Z=this.currentAttachedFile.fileName)?Z:void 0,null!=(ee=this.currentAttachedFile.fileDescription)?ee:void 0)),(null==(te=this.currentAttachedFile.fileMediaType)?void 0:te.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!=(ie=this.currentAttachedFile.fileName)?ie:void 0,description:null!=(re=this.currentAttachedFile.fileDescription)?re:void 0})}this.currentAttachedFile=null}break;case vr.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 vr.ContentEncoding:this.currentDecodingInstruction={order:0,scope:tn.Block,data:null},this.readContiguousElements(e.slice(he,de)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case vr.ContentEncodingOrder:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=Er(e,de);break;case vr.ContentEncodingScope:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=Er(e,de);break;case vr.ContentCompression:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:nn.Zlib,settings:null},this.readContiguousElements(e.slice(he,de));break;case vr.ContentCompAlgo:if("decompress"!==(null==(se=null==(ne=this.currentDecodingInstruction)?void 0:ne.data)?void 0:se.type))break;this.currentDecodingInstruction.data.algorithm=Er(e,de);break;case vr.ContentCompSettings:if("decompress"!==(null==(le=null==(oe=this.currentDecodingInstruction)?void 0:oe.data)?void 0:le.type))break;this.currentDecodingInstruction.data.settings=Lo(e,de);break;case vr.ContentEncryption:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}return e.filePos=he+de,!0}decodeBlockData(e,t){I(e.decodingInstructions.length>0);let i=t;for(const r of e.decodingInstructions)if(I(r.data),"decompress"===r.data.type)if(r.data.algorithm===nn.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){I(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 cn{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 oe(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=G(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=ee(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 I(-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(I(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);F(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?Oi: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?Oi:s.mainAdditional,c.alphaByteLength=s.mainAdditional.byteLength);const u=new Li(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=G(this.internalTrack.cuePoints,i,e=>e.time),p=-1!==m?this.internalTrack.cuePoints[m]:null,g=G(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,xr);if(Ce(e)&&(e=yield e),!e)break;const i=b,s=Fr(e);if(!s||!Pr.includes(s.id)&&s.id!==vr.Void){const e=yield Or(c.reader,i,Pr,Math.min(null!=(o=u.elementEndPos)?o:1/0,i+on));if(e){b=e;continue}break}const a=s.id;let l=s.size;const m=e.filePos;if(a===vr.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){I(a!==vr.Cluster);l=(yield Nr(c.reader,m,Ir,u.elementEndPos)).pos-m}const p=m+l;if(null===u.elementEndPos){let e=c.reader.requestSliceRange(p,2,xr);if(Ce(e)&&(e=yield e),!e)break;if(_r(e)===vr.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?ht(s.data):null,hevcCodecInfo:"hevc"===this.internalTrack.info.codec&&s?St(s.data):null,vp9CodecInfo:"vp9"===this.internalTrack.info.codec&&s?Dt(s.data):null,av1CodecInfo:"av1"===this.internalTrack.info.codec&&s?Nt(s.data):null,proresCodecInfo:"prores"===this.internalTrack.info.codec&&s?Ot(s.data):null,proresFormat:this.internalTrack.info.proresFormat};if(!q(this.internalTrack.info.colorSpace)){const n=Ti(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:bi(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 dn extends cn{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&&ai(e.data)}return{codec:vi({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 hn=(e,t,i,r=null)=>y(null,null,function*(){const n=u(2,16);let s=t;for(;null===i||s=4;){const t=a.filePos,i=jo(a),n=null!==e.fileSize?e.fileSize-s:null,o=Ri(i,n);if(o.header&&(!r||o.header.sampleRate===r.sampleRate&&o.header.mpegVersionId===r.mpegVersionId&&o.header.layer===r.layer&&Mi(o.header.channel)===Mi(r.channel)))return{header:o.header,startPos:s};a.filePos=t+o.bytesAdvanced,s=a.filePos}}return null});class fn extends Ni{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.firstFrameHeaderPos=null,this.xingFrameHeader=null,this.xingFrameHeaderPos=null,this.loadedSamples=[],this.metadataTags=null,this.xingData=null,this.trackBackings=[],this.readingMutex=new V,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}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 mn(this)]}))()})}advanceReader(){return y(this,null,function*(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,ol);if(Ce(e)&&(e=yield e),!e)return void(this.lastSampleLoaded=!0);const t=dl(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}const e=yield hn(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=_i(t.mpegVersionId,t.channel);let r=this.reader.requestSlice(e.startPos+i,4);if(Ce(r)&&(r=yield r),r){const n=jo(r);if(n===Bi||n===Ei){if(this.xingFrameHeader||(this.xingFrameHeader=t,this.xingFrameHeaderPos=e.startPos),!this.xingData){let t=this.reader.requestSlice(e.startPos+i+4,12);if(Ce(t)&&(t=yield t),t){const e=Lo(t,12),i=F(e),r=i.getUint32(0,!1);this.xingData={frameCount:r&Ai.FrameCount?i.getUint32(4,!1):null,fileSize:r&Ai.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,ol);if(Ce(i)&&(i=yield i),!i)break;const r=dl(i);if(!r)break;t=!0;let n=this.reader.requestSlice(i.filePos,r.size);if(Ce(n)&&(n=yield n),!n)break;hl(n,r,this.metadataTags),e=i.filePos+r.size}if(!t&&null!==this.reader.fileSize&&this.reader.fileSize>=al){let e=this.reader.requestSlice(this.reader.fileSize-al,al);Ce(e)&&(e=yield e),I(e);"TAG"===el(e,3)&&cl(e,this.metadataTags)}return this.metadataTags}finally{e()}})}}class mn{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return I(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate/this.demuxer.firstFrameHeader.audioSamplesInFrame}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return y(this,null,function*(){const e=this.demuxer;if(I(null!==e.firstFrameHeader),I(null!==e.firstFrameHeaderPos),e.xingData){if(null!==e.xingData.frameCount)return e.xingData.frameCount*e.firstFrameHeader.audioSamplesInFrame/e.firstFrameHeader.sampleRate}else if(null!==e.reader.fileSize){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=G(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 kn=e=>{const t=F(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},yn=(e,t,i)=>{let r=0,n=null;if(e.length>0)if("vorbis"===t.codec){I(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:Lt[t]*r}})(e).durationInSamples}return{durationInSamples:r,vorbisBlockSize:n}},bn=27,Tn=282,vn=e=>{const t=e.filePos;if(Ko(e)!==pn)return null;e.skip(1);const i=zo(e),r=Yo(e),n=Ko(e),s=Ko(e),a=Ko(e),o=zo(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}},Sn=(e,t)=>{for(;e.filePos>>8&255)===i||(t>>>16&255)===i||(t>>>24&255)===i){if(e.skip(-4),t===pn)return!0;e.skip(1)}}return!1};class wn extends Ni{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,bn,Tn);if(Ce(t)&&(t=yield t),!t)break;const i=vn(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 Pn(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=F(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:zt(n.data).modeBlockflags},Ht(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=F(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=Si,t.codecInfo.opusInfo={preSkip:n.preSkip},Ht(r.data.subarray(8),this.metadataTags)})}readPacket(e,t){return y(this,null,function*(){I(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 Pn{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new V,this.internalSampleRate="opus"===e.codecInfo.codec?Si:e.sampleRate}getType(){return"audio"}getId(){return this.bitstream.serialNumber}getNumber(){const e=this.demuxer.trackBackings.findIndex(e=>e.bitstream===this.bitstream);return I(-1!==e),e+1}getNumberOfChannels(){return this.bitstream.numberOfChannels}getSampleRate(){return this.bitstream.sampleRate}getTimeResolution(){return this.bitstream.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 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 I(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 ae}getDisposition(){return f(h({},je),{primary:!1})}granulePositionToTimestampInSamples(e){return"opus"===this.bitstream.codecInfo.codec?(I(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,i){if(!e)return null;const{durationInSamples:r,vorbisBlockSize:n}=yn(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),s=new Li(i.metadataOnly?Oi: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*(){I(this.bitstream.lastMetadataPacket);const t=yield this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let i=0;"opus"===this.bitstream.codecInfo.codec&&(I(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=oe(e*this.internalSampleRate);if(0===n)return this.getFirstPacket(t);if(n<0)return null;I(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,bn,Tn);Ce(t)&&(t=yield t),I(t);const i=vn(t);I(i),u=i,u.serialNumber===this.bitstream.serialNumber&&d.push(u)}I(-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:Oi,endPage:p,endSegmentIndex:g};if(yield this.demuxer.findNextPacketStart(e)){const e=xn(d,u,m);I(e);const t=In(d,e.page,e.segmentIndex);t&&(u=t.page,m=t.segmentIndex)}else for(;;){const e=xn(d,u,m);if(!e)break;const t=In(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;){I(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=oe(e*this.internalSampleRate);e=i/this.internalSampleRate;const r=G(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);I(e),this.sequentialScanCache.length>0&&I(C(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 In=(e,t,i)=>{let r=t,n=i;e:for(;;){for(n--;n>=0;n--){if(r.lacingValues[n]<255){n++;break e}}I(-1===n);if(!(1&r.headerType)){n=0;break}const t=Z(e,e=>e.headerStartPos{if(i>0)return{page:t,segmentIndex:i-1};const r=Z(e,e=>e.headerStartPosy(this,null,function*(){var e,t;let i=this.reader.requestSlice(0,12);Ce(i)&&(i=yield i),I(i);const r=el(i,4),n="RIFX"!==r,s="RF64"===r,a=Vo(i,n);let o=s?this.reader.fileSize:Math.min(a+8,null!=(e=this.reader.fileSize)?e:1/0);if("WAVE"!==el(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=Uo(r,i),s=t-18;if(Math.min(s,e)>=22&&n===Cn.EXTENSIBLE){r.skip(6);const e=Lo(r,16);n=e[0]|e[1]<<8}}if(n!==Cn.MULAW&&n!==Cn.ALAW||(l=8),n!==Cn.PCM&&n!==Cn.IEEE_FLOAT&&n!==Cn.ALAW&&n!==Cn.MULAW)throw new Error(`Unsupported WAVE codec (format tag ${n}). Only integer/float PCM, A-law, and \u03bc-law are supported.`);if(n===Cn.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===Cn.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(Ce(m)&&(m=yield m),!m)return;const p=el(m,4);if("INFO"!==p&&"INF0"!==p)return;let g=m.filePos;for(;g<=e+t-8;){m.filePos=g;const e=el(m,4),t=Vo(m,i),p=Lo(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(Ce(i)&&(i=yield i),!i)return;const r=dl(i);if(r){const n=t-ol;if(r.size=Math.min(r.size,n),r.size>0){const t=i.slice(e+ol,r.size);hl(t,r,this.metadataTags)}}})}getCodec(){if(I(this.audioInfo),this.audioInfo.format===Cn.MULAW)return"ulaw";if(this.audioInfo.format===Cn.ALAW)return"alaw";if(this.audioInfo.format===Cn.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===Cn.IEEE_FLOAT){if(4===this.audioInfo.sampleSizeInBytes)return"pcm-f32";if(8===this.audioInfo.sampleSizeInBytes)return"pcm-f64"}I(!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 _n=2048;class Rn{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return I(this.demuxer.audioInfo),this.demuxer.audioInfo.format}getDecoderConfig(){return y(this,null,function*(){const e=this.demuxer.getCodec();return e?(I(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null})}getNumberOfChannels(){return I(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return I(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return I(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return y(this,null,function*(){return I(-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 ae}getDisposition(){return h({},je)}getPacketAtIndex(e,t){return y(this,null,function*(){I(e>=0),I(this.demuxer.audioInfo);const i=e*_n*this.demuxer.audioInfo.blockSizeInBytes;if(i>=this.demuxer.dataSize)return null;const r=Math.min(_n*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(Ce(e)&&(e=yield e),!e)return null}let n;if(t.metadataOnly)n=Oi;else{let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+i,r);Ce(e)&&(e=yield e),I(e),n=Lo(e,r)}const s=e*_n/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 Li(n,"key",s,a,e,r)})}getFirstPacket(e){return this.getPacketAtIndex(0,e)}getPacket(e,t){return y(this,null,function*(){I(this.demuxer.audioInfo);const i=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/_n,(this.demuxer.dataSize-1)/(_n*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;I(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){I(this.demuxer.audioInfo);const i=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/_n);return this.getPacketAtIndex(i+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const Fn=e=>{const t=e.filePos,i=Lo(e,9),r=new Ke(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}},An=1024;class Dn extends Ni{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.trackBackings=[],this.readingMutex=new V,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}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();I(this.firstFrameHeader),this.trackBackings=[new Mn(this)]}))()})}advanceReader(){return y(this,null,function*(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,ol);if(Ce(e)&&(e=yield e),!e)return void(this.lastSampleLoaded=!0);const t=dl(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}let e=this.reader.requestSliceRange(this.lastLoadedPos,7,9);if(Ce(e)&&(e=yield e),!e)return void(this.lastSampleLoaded=!0);const t=Fn(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=Xe[t.samplingFrequencyIndex];I(void 0!==i);const r=An/i,n={timestamp:this.nextTimestampInSamples/i,duration:r,dataStart:t.startPos,dataSize:t.frameLength};this.loadedSamples.push(n),this.nextTimestampInSamples+=An,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,ol);if(Ce(t)&&(t=yield t),!t)break;const i=dl(t);if(!i)break;let r=this.reader.requestSlice(t.filePos,i.size);if(Ce(r)&&(r=yield r),!r)break;hl(r,i,this.metadataTags),e=t.filePos+i.size}return this.metadataTags}finally{e()}})}}class Mn{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return this.getSampleRate()/An}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 ae}getCodec(){return"aac"}getInternalCodecId(){return I(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){I(this.demuxer.firstFrameHeader);const e=$e[this.demuxer.firstFrameHeader.channelConfiguration];return I(void 0!==e),e}getSampleRate(){I(this.demuxer.firstFrameHeader);const e=Xe[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return I(void 0!==e),e}getDisposition(){return h({},je)}getDecoderConfig(){return y(this,null,function*(){return I(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=Oi;else{let e=this.demuxer.reader.requestSlice(i.dataStart,i.dataSize);if(Ce(e)&&(e=yield e),!e)return null;r=Lo(e,i.dataSize)}return new Li(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=$(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=G(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,ol);if(Ce(e)&&(e=yield e),!e)return void(this.lastSampleLoaded=!0);const i=dl(e);if(!i)break;let r=this.reader.requestSlice(e.filePos,i.size);Ce(r)&&(r=yield r),I(r),hl(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===zo(s)){const t=s.filePos;if(zo(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=Lo(e,4),n=new Ke(r);if(32764!==n.readBits(15))return null;if(null===this.blockingBit){I(t);const e=n.readBits(1);this.blockingBit=e}else if(1===this.blockingBit){I(!t);if(1!==n.readBits(1))return null}else{if(0!==this.blockingBit)throw new Error("Invalid blocking bit");I(!t);if(0!==n.readBits(1))return null}const s=(e=>0===e?null:1===e?192:e>=2&&e<=5?144*u(2,e):6===e?"uncommon-u8":7===e?"uncommon-u16":e>=8&&e<=15?u(2,e):null)(n.readBits(4));if(!s)return null;I(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 Ke(Lo(e,1));for(;1===i.readBits(1);)t++;if(0===t)return i.readBits(7);const r=[],n=t-1,s=new Ke(Lo(e,n)),a=8-t-1;for(let o=0;oe|t<"uncommon-u16"===t?qo(e)+1:"uncommon-u8"===t?zo(e)+1:"number"===typeof t?t:(te(t),void I(!1)))(e,s),c=((e,t)=>"uncommon-u16"===t?qo(e):"uncommon-u16-10"===t?10*qo(e):"uncommon-u8"===t?zo(e):"number"===typeof t?t:null)(e,a);if(null===c)return null;if(c!==this.audioInfo.sampleRate)return null;const d=e.filePos-i,h=zo(e);e.skip(-d),e.skip(-1);const f=(e=>{let t=0;for(const i of e){t^=i;for(let e=0;e<8;e++)0!==(128&t)?t=t<<1^7:t<<=1,t&=255}return t})(Lo(e,d));return h!==f?null:{num:o,blockSize:l,sampleRate:c}}advanceReader(){return y(this,null,function*(){yield this.readMetadata(),I(null!==this.lastLoadedPos),I(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 On{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return I(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return I(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return ae}getTimeResolution(){return I(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 I(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({},je)}getDecoderConfig(){return y(this,null,function*(){return I(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(I(this.demuxer.audioInfo),e<0)return null;const i=yield this.demuxer.readingMutex.acquire();try{for(;;){const i=G(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=Oi;else{let e=this.demuxer.reader.requestSlice(i.byteOffset,i.byteSize);if(Ce(e)&&(e=yield e),!e)return null;r=Lo(e,i.byteSize)}I(this.demuxer.audioInfo);const n=i.blockOffset/this.demuxer.audioInfo.sampleRate,s=i.blockSize/this.demuxer.audioInfo.sampleRate;return new Li(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 Ln=9e4,zn=u(2,33),Un=188,qn="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.",Wn=new Set([133,134,162]),Hn=new Set;class Vn extends Ni{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);Ce(e)&&(e=yield e),I(e);const t=Lo(e,205);if(71===t[0]&&71===t[188])this.packetOffset=0,this.packetStride=Un;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 Ke(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=Kn(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 Yn(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=ht(r.suppliedPacket.data),!e.info.avcCodecInfo)continue;const t=e.info.avcCodecInfo.sequenceParameterSets[0];I(t);const i=gt(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:N[i.colourPrimaries],transfer:L[i.transferCharacteristics],matrix:U[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=St(r.suppliedPacket.data),!e.info.hevcCodecInfo)continue;const t=e.info.hevcCodecInfo.arrays.find(e=>e.nalUnitType===it.SPS_NUT).nalUnits[0];I(t);const i=vt(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:N[i.colourPrimaries],transfer:L[i.transferCharacteristics],matrix:U[i.matrixCoefficients],fullRange:!!i.fullRangeFlag},e.info.reorderSize=i.maxDecFrameBuffering;break}throw new Error("Unhandled.")}e.info.decoderConfig={codec:bi({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=No.tempFromBytes(r.suppliedPacket.data),i=Fn(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=$e[i.channelConfiguration],e.info.sampleRate=Xe[i.samplingFrequencyIndex]}else if("mp3"===e.info.codec){const t=jo(No.tempFromBytes(r.suppliedPacket.data)),i=Ri(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=Mi(i.header.channel),e.info.sampleRate=i.header.sampleRate}else if("ac3"===e.info.codec){const t=jt(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=Vt[t.acmod]+t.lfeon,e.info.sampleRate=Je[t.fscod]}else if("eac3"===e.info.codec){const t=$t(r.suppliedPacket.data);if(!t)throw new Error("Invalid E-AC-3 audio stream; could not read sync frame from first packet.");const i=Gt(t);if(null===i)throw new Error("Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.");e.info.numberOfChannels=Qt(t),e.info.sampleRate=i}else{if("dts"!==e.info.codec)throw new Error("Unhandled.");{const t=si(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:vi({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 Ke(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&&Wn.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:Hn.has(t)||(We._warn(`Note: MPEG-TS streams with stream_type 0x${t.toString(16)} are not currently supported.`),Hn.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 Ke(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 $n(a)):this.trackBackingEntries.push(new Gn(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!==$(this.sectionEndPositions,r,e=>e)){c=!1;break}}if(c){const e=G(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(Ce(t)&&(t=yield t),!t)return null;if(71!==zo(t))throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");const i=qo(t);return{payloadUnitStartIndicator:i>>14&1,pid:8191&i,adaptationFieldControl:zo(t)>>4&3}})}readPacket(e){return y(this,null,function*(){let t=this.reader.requestSlice(e,Un);if(Ce(t)&&(t=yield t),!t)return null;const i=Lo(t,Un);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>=zn-t?-zn:zn}}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 Ke(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(qn);return{sectionStartPos:t.startPos,sectionEndPos:t.endPos,pts:a,randomAccessIndicator:t.randomAccessIndicator}},Kn=(e,t,i)=>{I(null!==t.endPos);const r=jn(e,t,i);if(!r)return null;const n=new Ke(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;I(Number.isInteger(l));const c=t.payload.subarray(l,s>0?6+s:t.payload.byteLength);return f(h({},r),{data:c})};class Xn{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++,I(r instanceof Xn),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 ae}getDisposition(){return f(h({},je),{primary:!1})}getTimeResolution(){return Ln}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 Li(i.metadataOnly?Oi:e.data,r,e.pts/Ln,Math.max(t/Ln,0),e.sequenceNumber,e.data.byteLength)}getFirstPacket(e){return y(this,null,function*(){const t=this.elementaryStream.firstSection;I(t);const i=Kn(this.elementaryStream.demuxer,t,!0);I(i);const r=new Yn(this.elementaryStream,i),n=new Jn(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);I(s);const a=Kn(n,s,!0);I(a);const o=new Yn(this.elementaryStream,a);i=new Jn(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=oe(e*Ln),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),v=-1!==T?b[T]:null;if(v&&c-v.pts<45e3)k=v.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=ue(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=ue(e*h,u.packetStride)+g.sectionStartPos}const S=yield m(k,null!=(r=d.fileSize)?r:1/0,!1);let w=null!=(n=null==S?void 0:S.pesPacketHeader)?n:null;w||(w=g);const P=this.getReorderSize(),x=(e,t)=>y(this,null,function*(){var r,n;const s=yield u.readSection(e,!0);I(s);const a=Kn(u,s,!0);I(a);const o=new Yn(this.elementaryStream,a),l=new Jn(this,o);for(;;){if((null!=(n=null==(r=C(l.presentationOrderPackets))?void 0:r.pts)?n:-1/0)>=c)break;if(!(yield l.readNextPacket()))break}const d=ee(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();I(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=jn(u,t,!1);if(e&&null!==e.pts){if(e.pts>c)break e;w=e,Qn(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=jn(u,t,!1);if(e&&null!==e.pts){w=e;break}}}e-=u.packetStride}}return x(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{I(y);const t=Kn(u,y,!0);I(t);const i=new Yn(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>P))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=jn(u,t,!1);if(e&&null!==e.pts){k=e,y=t,Qn(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=jn(u,r,!1);if(t&&null!==t.pts){e=t;break}}}t-=u.packetStride}}const t=yield x(e.sectionStartPos,e=>e.pts<=c&&1===e.randomAccessIndicator);return I(t),t}if(n)return null;t=e,e=Math.max(ue(e-g.sectionStartPos-h,u.packetStride)+g.sectionStartPos,g.sectionStartPos)}}})}}class $n extends Xn{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 I(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig})}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}}class Gn extends Xn{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 I(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig})}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 0}}const Qn=(e,t)=>{const i=e.referencePesPackets,r=G(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 I(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,S;if("avc"===e)T=ot(b),v=T===et.NON_IDR_SLICE||T===et.SLICE_DPA||T===et.IDR,S=T===et.SEI||T===et.SPS||T===et.PPS||T===et.AUD;else{T=Tt(b);if(((1&b)<<5|l[g+1]>>3)>0){u+=m;continue}v=T<=it.RASL_R||T>=it.BLA_W_LP&&T<=21,S=T>=it.VPS_NUT&&T<=37||T===it.PREFIX_SEI_NUT||T>=41&&T<=44||T>=48&&T<=55}let w=!1;if(v){let t;if("avc"===e){const e=l.subarray(k,k+y),i=B(new Ke(e));t=!s||i<=a,a=i}else t=l[k]>>7===1;t&&(s?w=!0:s=!0)}else S&&s&&(w=!0);if(w){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);Ce(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=Kt[3*a+n];I(void 0!==o),this.seekTo(e),t=this.ensureBuffered(o),Ce(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(Ce(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=Xt[a];this.seekTo(e),t=this.ensureBuffered(n),Ce(t)&&(t=yield t);const l=256*o,c=Math.round(l*Ln/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(Ce(a)&&(a=yield a),a<18)return;const o=this.readBytes(18),l=oi(o);let c=l?null:li(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);Ce(i)&&(i=yield i),c=null!=(e=li(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(Ce(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(I(-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(I(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 Zn="application/vnd.apple.mpegurl",es="#EXT-X-STREAM-INF:",ts="#EXT-X-I-FRAME-STREAM-INF:",is="#EXT-X-MEDIA:",rs="#EXTINF:",ns="#EXT-X-MAP:",ss="#EXT-X-KEY:",as="#EXT-X-MEDIA-SEQUENCE:",os="#EXT-X-BYTERANGE:",ls="#EXT-X-PROGRAM-DATE-TIME:",cs="#EXT-X-TARGETDURATION:",us="#EXT-X-PLAYLIST-TYPE:",ds=e=>0===e.length||e.startsWith("#")&&!e.startsWith("#EXT");class hs{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=De(e,e=>"video"===e.getType())+1;e.push(new ps(this,t,i))}else if("audio"===t.type){const i=De(e,e=>"audio"===e.getType())+1;e.push(new gs(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=De(e,e=>"video"===e.getType())+1;e.push(new ps(this,{id:e.length+1,type:"video"},t))}else if("audio"===r.type){const t=De(e,e=>"audio"===e.getType())+1;e.push(new gs(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 ms{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(),I(this.segmentedInput.firstSegment),this.segmentedInput.firstSegment.unixEpochTimestamp===this.segmentedInput.firstSegment.timestamp})}getUnixTimeForTimestamp(e){return this.segmentedInput.getUnixTimeForTimestamp(e)}getBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getBitrate())}getAverageBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getAverageBitrate())}getDurationFromMetadata(e){return this.segmentedInput.getDurationFromMetadata(e)}getLiveRefreshInterval(){return this.segmentedInput.getLiveRefreshInterval()}createAdjustedPacket(e,t,i){return y(this,null,function*(){I(e.sequenceNumber>=0),I(this.segmentedInput.firstSegment);const r=yield this.segmentedInput.getMediaOffset(t,i.input),n=t.timestamp-this.segmentedInput.firstSegment.timestamp,s=e.clone({timestamp:ce(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(),I(this.firstInputTrack),I(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 ps extends ms{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 gs extends ms{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())})}}Re();const ks=1/0;"undefined"!==typeof FinalizationRegistry&&new FinalizationRegistry(e=>{e()});class ys extends ze{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 Do;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,ks),e=this._getFileSize(),I(void 0!==e)),e}))()})}getSize(){return y(this,null,function*(){if(this._disposed)throw new Do;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 Ds(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 bs(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){this._refCount--,0===this._refCount&&(this._dispose(),this._disposed=!0)}}class bs{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;I(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 Ts extends ys{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 ys||e instanceof bs))throw new TypeError("requestHandler must return or resolve to a Source or SourceRef.");const i=e instanceof ys?e.ref():e;return(t=i.source)._usedForHls||(t._usedForHls=this._usedForHls),i};return Ce(t)?t.then(i):i(t)}}const vs=(e,t)=>e.path===t.path;class Ss extends Ts{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 ys?e.ref():e;return this._root=t,this._rootRequest=null,t};Ce(e)?this._rootRequest=e.then(t):(t(e),I(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 ws="undefined"!==typeof FinalizationRegistry?new FinalizationRegistry(e=>{e.cancel().catch(()=>{})}):null;class Ps extends ys{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&&(!Fe(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 As({maxCacheSize:null!=(i=t.maxCacheSize)?i:8*u(2,20),maxWorkerCount:4,runWorker:this._runWorker.bind(this),onIdleWorkerRemoved:e=>{const t=this._readers.get(e);t&&(this._readers.delete(e),null==ws||ws.unregister(e),t.cancel().catch(()=>{}))},prefetchProfile:Fs.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*(){I(e.strictTarget);let t=this._readers.get(e);if(void 0===t){if("stream"in this._blob&&!Te()&&!1!==this._options.useStreamReader){t=this._blob.slice(e.currentPos).stream().getReader(),null==ws||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(r){}if(("undefined"===typeof navigator||"boolean"!==typeof navigator.onLine||navigator.onLine)&&null!==e&&e!==window.location.origin)return We._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(u(2,e-2),16)},Cs=new Set;class Bs extends Ts{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&&(!Fe(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 Bs(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:xs,this._requestInit=h({},t.requestInit);let a=null;if(null==(r=t.requestInit)?void 0:r.headers){const e=h({},ge(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=_s(a);e&&(this._offset=e.offset,this._length=e.length)}this._orchestrator=new As({maxCacheSize:null!=(n=t.maxCacheSize)?n:64*u(2,20),maxWorkerCount:null!=(s=t.parallelism)?s:2,runWorker:this._runWorker.bind(this),prefetchProfile:Fs.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:se(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 Ce(a)?a.then(o):o(a)}_runWorker(e){return y(this,null,function*(){for(var t;;){const r=new AbortController,n=yield ke(null!=(t=this._options.fetchFn)?t:fetch,this._url,pe(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")||Cs.has(e.origin)||(We._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.`),Cs.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){We._error("Error while reading response stream. Attempting to resume.",i),yield Le(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;We._error("Error while reading response stream. Attempting to resume.",s),yield Le(1e3*e);const a=yield ke(null!=(n=this._options.fetchFn)?n:fetch,this._url,pe(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 Rs(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);Ce(e)?e.then(e=>{e?(I(e.offset===o.start),o.resolve(e.bytes)):o.resolve(null)},e=>o.reject(e)):(I(null===e),o.resolve(null))}}_dispose(){this._orchestrator.dispose(),this._sequentialBacking&&(this._sequentialBacking._disposed=!0,this._sequentialBacking._dispose())}}const Es=/^bytes=(\d+)-(\d*)$/,_s=e=>{const t=Es.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=G(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}=Y();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 Do);this._pendingSlices.length=0,this._cache.length=0,null==(e=this._reader)||e.cancel()}}const Fs={fileSystem:(e,t)=>{const i=u(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=u(2,16);e=Math.max(0,Math.floor((e-r)/r)*r);for(const n of i){const i=8*u(2,20),r=Math.max((n.startPos+n.targetPos)/2,n.targetPos-i);if(Ee(e,t,r,n.targetPos)){const e=n.targetPos-n.startPos,r=Math.ceil((e+1)/i)*i,s=u(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+Is)}}};class As{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;I(!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);I(a<=e&&t<=o);let l=null;const c=G(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=G(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(I(n<=s),m=h.length&&(l={bytes:h,view:F(h),offset:e}),0===p.length)return I(l),l;const{promise:g,resolve:k,reject:y}=Y(),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)}}):(I(h),l=g.then(t=>t&&{bytes:t,view:F(t),offset:e})),l}checkHoleAgainstWorker(e,t,i){const r=u(2,17);if(Ee(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);I(-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=G(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=F(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=F(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 Ce(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 Ms=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},Ns=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 Os=/^0[xX][0-9a-fA-F]+$/,Ls=/^data:.*;base64,/i;class zs 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(){var e;return null!=(e=this.currentUpdateSegmentsPromise)?e:this.currentUpdateSegmentsPromise=(()=>y(this,null,function*(){try{const e=this.getRemainingWaitTimeMs();e>0&&(yield Le(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=Ms(e,yield this.demuxer.input._getSourceUncached({path:this.rootPath,isRoot:!1}),!1),i=new Mo(t.source),r=yield i.requestEntireFile();I(r),l=tl(r,r.length,{ignore:ds}),t.source instanceof Ts&&(this.rootPath=t.source.rootPath)}catch(R){e.error=R,e.hasError=!0}finally{Ns(e)}}const c=!1!==(null==(e=this.input._formatOptions.hls)?void 0:e.offsetTimestampsByDateTime);let d=!1,m=0,p=null,g=null,k=null,y=0,b=null,T=null,v=null,S=null,w=null,P=null,x=!1,B=null!=(t=C(this.segments))?t:null;const E=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}},_=e=>{y=e,B&&(I(null!==B.sequenceNumber),B.sequenceNumber0&&null!==P&&(m=y*P),x=!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}'.`);g=n}else if(e.startsWith(ns)){const t=new hs(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=E(r)),a&&null===a.offset)throw new Error("Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset.");if(!B){const e={path:Ae(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==k?void 0:k.method)&&!k.iv)throw new Error("IV attribute must be set on #EXT-X-KEY tag preceding the #EXT-X-MAP tag.");T={timestamp:m,unixEpochTimestamp:p,firstSegment:null,sequenceNumber:null,location:e,duration:0,encryption:k,initSegment:null,lastProgramDateTimeSeconds:w}}g=null,null===S?v=null:S=null}else if(e.startsWith(ss)){const t=new hs(e.slice(11)),i=t.get("method");if("NONE"===i)k=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(!Os.test(r))throw new Error(`Unsupported IV format '${r}'.`);let e=r.slice(2);e=e.padStart(32,"0"),i=new Uint8Array(Xi);for(let t=0;t=8&&112===i[4]&&115===i[5]&&115===i[6]&&104===i[7]){const e=F(i).getUint32(0);r=zi(i.subarray(8,Math.min(e,i.length)))}}k={method:i,psshBox:r}}}}else if(e.startsWith(as)){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)}else if(e.startsWith(os)){const t=E(e.slice(17));if(null===t.offset){if(null===v)throw new Error("Invalid M3U8 file; #EXT-X-BYTERANGE without offset requires a previous byte range.");t.offset=v}S=t,v=t.offset+t.length}else if(e.startsWith(ls)){if(B)continue;const t=e.slice(25),i=Date.parse(t);if(!Number.isFinite(i))continue;const r=i/1e3;if(w===r)continue;if(null===w&&this.segments.length>0){const e=C(this.segments),t=r-(e.timestamp+e.duration);for(const i of this.segments)i.unixEpochTimestamp=i.timestamp+t,c&&(i.timestamp=i.unixEpochTimestamp)}w=r,p=r,c&&(m=r)}else if("#EXT-X-DISCONTINUITY"===e)b=null;else if(e.startsWith(cs)){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,P=i}else{if("#EXT-X-ENDLIST"===e){this.streamHasEnded=!0;break}if(e.startsWith(us)){"vod"===e.slice(21).toLowerCase()&&(this.streamHasEnded=!0)}}}else{if("#EXTM3U"!==e)throw new Error("Invalid M3U8 file; expected first line to be #EXTM3U.");d=!0}}if(!d)throw new Error("Invalid M3U8 file; no #EXTM3U header.")})}getFirstSegment(){return 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=G(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=f(h({},this.input._formatOptions),{isobmff:f(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=>Ui(e,i))||(t=[...t,i]),this.input._formatOptions.isobmff.resolveKeyId(f(h({},e),{psshBoxes:t}))})})}),o=new Fo({source:new Ss(r.location.path,e=>y(this,null,function*(){var t,i;I(e.isRoot);const n=f(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;I(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=u(2,16),a=new ir;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(Ce(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=Lo(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 Mo(t.source),()=>y(this,null,function*(){const t={stack:[],error:void 0,hasError:!1};try{const i=Ms(t,yield this.input._getSourceCached({path:e.keyUri,isRoot:!1},Ro),!1),r=new Mo(i.source),n=yield r.requestSlice(0,Xi);if(!n)throw new Error("Invalid AES-128 key; expected at least 16 bytes of data.");return{key:Lo(n,Xi),iv:e.iv}}catch(i){t.error=i,t.hasError=!0}finally{Ns(t)}}),()=>{t.free()});s=new Rs(o).ref()}else I(!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 sa)),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=Me(this.inputCache,e=>e.age);I(-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 Us extends Ni{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*(){I(this.input._rootSource instanceof Ts);const e=yield this.input._reader.requestEntireFile();I(e);const t=tl(e,e.length,{ignore:ds}),{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=>ui.includes(Ii(e))),g=h.some(e=>hi.includes(Ii(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=Ae(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});I(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=Ae(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});I(null!==a),h.push(a)}}h=[...new Set(h)];let k=null,b=null;const T=e.attributes.getAsNumber("bandwidth");I(null!==T);const v=e.attributes.getAsNumber("average-bandwidth"),S=e.attributes.get("name");for(const i of h){const d=Ii(i);if(null!==d)if(ui.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:ae,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:Vs(i.attributes),autoselect:Vs(i.attributes)||js(i.attributes),languageCode:Ks(i.attributes.get("language")),lineNumber:i.lineNumber,fullPath:null!=(c=i.fullPath)?c:e.fullPath,fullCodecString:b,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===ae&&(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 Ws(u)):this.trackBackings.push(new Hs(u));this.internalTracks=l}))()}getTrackBackings(){return y(this,null,function*(){return yield this.readMetadata(),I(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 zs(this,e,i,null),this.segmentedInputs.push(t),t}getMetadataTags(){return y(this,null,function*(){return{}})}getMimeType(){return y(this,null,function*(){return Zn})}dispose(){if(this.segmentedInputs){for(const e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}}class qs{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 Ws){for(const r of i)if((yield r.getCodec())===this.getCodec()){t=r;break}}else{I(this instanceof Hs);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 f(h({},je),{default:this.internalTrack.autoselect,primary:this.internalTrack.default})}getId(){return this.internalTrack.id}getPairingMask(){return this.internalTrack.pairingMask}getInternalCodecId(){return null}getLanguageCode(){return this.internalTrack.languageCode}getName(){return this.internalTrack.name}getNumber(){I(this.internalTrack.demuxer.internalTracks);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 Ws extends qs{constructor(e){super(e)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return"video"}getCodec(){return Ii(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 Hs extends qs{constructor(e){super(e)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return"audio"}getCodec(){return Ii(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 Vs=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}".`)},js=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}".`)},Ks=e=>{if(null===e)return ae;const t=e.split("-")[0];return t||ae};class Xs{constructor(){this._isIsobmff=!1}}class $s extends Xs{constructor(){super(...arguments),this._isIsobmff=!0}_getMajorBrand(e){return y(this,null,function*(){let t=e._reader.requestSlice(0,12);if(Ce(t)&&(t=yield t),!t)return null;t.skip(4);const i=el(t,4);return"ftyp"!==i&&"styp"!==i?null:el(t,4)})}_createDemuxer(e){return new rr(e)}}class Gs extends $s{_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(Ce(t)&&(t=yield t),!t)return!1;let r=jo(t),n=8;if(1===r){let t=e._reader.requestSlice(i+8,8);if(Ce(t)&&(t=yield t),!t)return!1;r=Go(t),n=16}if(r8)return!1;if(Er(i,r)!==vr.EBML)return!1;const n=Rr(i);if("number"!==typeof n)return!1;let s=e._reader.requestSlice(i.filePos,n);if(Ce(s)&&(s=yield s),!s)return!1;const a=i.filePos;for(;s.filePos<=a+n-2;){const e=Fr(s);if(!e)break;const{id:i,size:r}=e,n=s.filePos;if(void 0===r)return!1;switch(i){case vr.EBMLVersion:if(1!==Er(s,r))return!1;break;case vr.EBMLReadVersion:if(1!==Er(s,r))return!1;break;case vr.DocType:if(Ar(s,r)!==t)return!1;break;case vr.DocTypeVersion:if(Er(s,r)>4)return!1}s.filePos=n+r}return!0})}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new ln(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}}class Js extends Ys{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}}class Zs extends Xs{_canReadInput(e){return y(this,null,function*(){let t=0;for(;;){let i=e._reader.requestSlice(t,ol);if(Ce(i)&&(i=yield i),!i)break;const r=dl(i);if(!r)break;t=i.filePos+r.size}const i=yield hn(e._reader,t,t+4096);if(!i)return!1;const r=i.header,n=_i(r.mpegVersionId,r.channel);let s=e._reader.requestSlice(i.startPos+n,4);if(Ce(s)&&(s=yield s),!s)return!1;const a=jo(s);if(a===Bi||a===Ei)return!0;t=i.startPos+i.header.totalSize;const o=yield hn(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 fn(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}}class ea extends Xs{_canReadInput(e){return y(this,null,function*(){let t=e._reader.requestSlice(0,12);if(Ce(t)&&(t=yield t),!t)return!1;const i=el(t,4);if("RIFF"!==i&&"RIFX"!==i&&"RF64"!==i)return!1;t.skip(4);return"WAVE"===el(t,4)})}_createDemuxer(e){return new En(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}}class ta extends Xs{_canReadInput(e){return y(this,null,function*(){let t=e._reader.requestSlice(0,4);return Ce(t)&&(t=yield t),!!t&&"OggS"===el(t,4)})}_createDemuxer(e){return new wn(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}}class ia extends Xs{_canReadInput(e){return y(this,null,function*(){let t=0;for(;;){let i=e._reader.requestSlice(t,ol);if(Ce(i)&&(i=yield i),!i)break;const r=dl(i);if(!r)break;t=i.filePos+r.size}let i=e._reader.requestSlice(t,4);return Ce(i)&&(i=yield i),!!i&&"fLaC"===el(i,4)})}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new Nn(e)}}class ra extends Xs{_canReadInput(e){return y(this,null,function*(){let t=0;for(;;){let i=e._reader.requestSlice(t,ol);if(Ce(i)&&(i=yield i),!i)break;const r=dl(i);if(!r)break;t=i.filePos+r.size}let i=e._reader.requestSliceRange(t,7,9);if(Ce(i)&&(i=yield i),!i)return!1;const r=Fn(i);if(!r)return!1;if(t+=r.frameLength,i=e._reader.requestSliceRange(t,7,9),Ce(i)&&(i=yield i),!i)return!1;const n=Fn(i);return!!n&&(r.objectType===n.objectType&&r.samplingFrequencyIndex===n.samplingFrequencyIndex&&r.channelConfiguration===n.channelConfiguration)})}_createDemuxer(e){return new Dn(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}}class na extends Xs{_canReadInput(e){return y(this,null,function*(){let t=e._reader.requestSlice(0,205);if(Ce(t)&&(t=yield t),!t)return!1;const i=Lo(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 Vn(e)}get name(){return"MPEG Transport Stream"}get mimeType(){return"video/MP2T"}}class sa extends Xs{_canReadInput(e){return y(this,null,function*(){let t=e._reader.requestSlice(0,7);if(Ce(t)&&(t=yield t),!t)return!1;if(!("#EXTM3U"===el(t,7)))return!1;if(!(e._rootSource instanceof Ts))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 Us(e)}get name(){return"HTTP Live Streaming (HLS)"}get mimeType(){return Zn}}const aa=new Gs,oa=new Qs,la=new Ys,ca=new Js,ua=new Zs,da=new ea,ha=new ta,fa=new ra,ma=new ia,pa=new na,ga=new sa,ka=[ga,aa,oa,la,ca,da,ha,ma,ua,fa,pa],ya=[ga,aa,oa,ua,fa,pa];var ba=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});Re();let Ta=-1/0,va=-1/0,Sa=null;"undefined"!==typeof FinalizationRegistry&&(Sa=new FinalizationRegistry(e=>{const t=performance.now();"video"===e.type?(t-Ta>=1e3&&(We._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."),Ta=t),"undefined"!==typeof VideoFrame&&e.data instanceof VideoFrame&&e.data.close()):(t-va>=1e3&&(We._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."),va=t),"undefined"!==typeof AudioData&&e.data instanceof AudioData&&e.data.close())}));class wa{constructor(){this._referenceCount=0,this._lastAllocationBuffer=null}}const Pa=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],Ia=new Set(Pa);class xa{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){var i,r,n,s,a,o,l,c,u,d,h,f,m,p,g,k,y,b,T,v,S,w,P,I,x,C,B,E,_,F,A;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||!Ia.has(t.format))throw new TypeError("init.format must be one of: "+Pa.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&&Oe(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:Na(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?R(e):R(e).slice(),this._layout=m,this.colorSpace=new Ra(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)&&Oe(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!=(S=null==t?void 0:t.rotation)?S:0,this.squarePixelWidth=e.displayWidth,this.squarePixelHeight=e.displayHeight,this.timestamp=null!=(w=null==t?void 0:t.timestamp)?w:e.timestamp/1e6,this.duration=null!=(I=null==t?void 0:t.duration)?I:(null!=(P=e.duration)?P:0)/1e6,this.colorSpace=new Ra(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&&Oe(t.visibleRect,"init.visibleRect"),"undefined"!==typeof VideoFrame)return new xa(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*me),duration:Math.trunc((null!=(x=t.duration)?x: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 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:Se(),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 Ra({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else{if(!(e instanceof wa))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&&!Pa.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!=(F=t.duration)?F:0,this.colorSpace=e.getColorSpace()}this.encodeOptions=null!=(A=null==t?void 0:t.encodeOptions)?A:{},this.pixelAspectRatio=Ne({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),null==Sa||Sa.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return I(null!==this._data),this._data instanceof wa?new xa(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):Fa(this._data)?new xa(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):this._data instanceof Uint8Array?(I(this._layout),new xa(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 xa(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==Sa||Sa.unregister(this),this._data instanceof wa?(this._data._referenceCount--,0===this._data._referenceCount&&this._data.close()):Fa(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){var t;if(Ma(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(Fa(this._data))return this._data.allocationSize(e);return La(this,e).allocationSize}copyTo(e){return y(this,arguments,function*(e,t={}){var i,r;if(!H(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(Ma(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(I(null!==this._data),Fa(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 wa)){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 xa))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{ba(i)}}}const n=La(this,t);I(this.format);const s=R(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)I(this._layout),I(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");I(e);const t=e.getImageData(0,0,this.codedWidth,this.codedHeight);o=[{data:R(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 Fa(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?(I(this._layout),new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,layout:this._layout,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,t,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&&Da(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=Aa(T,m,p));const{sx:v,sy:S,sWidth:w,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,S,w,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?_a(d,h):{canvas:e,context:t,isNew:i.targetIsFresh};m.imageSmoothingQuality="high",i.fillBlack?(m.fillStyle="black",m.fillRect(0,0,d,h)):p||m.clearRect(0,0,d,h),this.drawWithFit(m,{fit:i.fit,rotation:i.rotation,crop:i.crop}),m.globalCompositeOperation="copy";for(let g=c;g>1;g--){const e=r*u(2,g),t=n*u(2,g);m.drawImage(f,0,0,e,t,0,0,e/2,t/2)}m.globalCompositeOperation="source-over",c>0&&(t.imageSmoothingQuality="high",t.globalCompositeOperation="copy",t.drawImage(f,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(I(null!==this._data),this._data instanceof wa||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&&Da(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=x(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=Aa(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=le(f,null!=(i=e.roundDimensionsTo)?i:1),m=le(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 Ca){let t=e(this,p);if(Ce(t)&&(t=yield t),null!==t)return t}const{canvas:g,context:k,isNew:y}=_a(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 xa(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 Ca=[],Ba=[];let Ea=0;const _a=(e,t)=>{for(const n of Ba)if(n.canvas.width===e&&n.canvas.height===t)return n.age=Ea++,{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 Ba.length>=3&&Ba.splice(Me(Ba,e=>e.age),1),Ba.push({canvas:i,context:r,age:Ea++}),{canvas:i,context:r,isNew:!0}};class Ra{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(M);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(O);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(z);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 Fa=e=>"undefined"!==typeof VideoFrame&&e instanceof VideoFrame,Aa=(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 I(s>=0),I(a>=0),{left:r,top:n,width:s,height:a}},Da=(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.")},Ma=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.")}},Na=(e,t,i)=>{const r=Oa(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},Oa=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:te(e),I(!1)}},La=(e,t)=>{const i={left:0,top:0,width:e.codedWidth,height:e.codedHeight},r=t.rect,n=za(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 qa(n,a,s)},za=(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(!Ua(n,s))throw new TypeError("visibleRect alignment is invalid for the format.");return s},Ua=(e,t)=>{if(null===e)return!0;const i=Oa(e);for(let r=0;r{const r=Oa(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/(ja(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*ja(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=ja(r),o=Ka(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(!H(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&&!Wa.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=ja(o),f=Ka(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 Qa(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(S){if("f32-planar"===o)throw S;a="f32-planar"}}const k=Xa(a),y=ja(a),b=Ka(a);let T;if(this._data instanceof Ha){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 Va({data:n,format:this.format,sampleRate:this.sampleRate,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp+e/this.sampleRate})}close(){this._closed||(null==Sa||Sa.unregister(this),this._data instanceof Ha?(this._data._referenceCount--,0===this._data._referenceCount&&this._data.close()):Ga(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 Ha?this._createAudioDataFromData():Ga(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(Ka(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")}},Ka=e=>{switch(e){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},Xa=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)}},$a=e=>{switch(e){case"u8":case"u8-planar":return(e,t,i)=>e.setUint8(t,se(127.5*(i+1),0,255));case"s16":case"s16-planar":return(e,t,i)=>e.setInt16(t,se(Math.round(32767*i),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,i)=>e.setInt32(t,se(Math.round(2147483647*i),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,i)=>e.setFloat32(t,i,!0)}},Ga=e=>"undefined"!==typeof AudioData&&e instanceof AudioData,Qa=(e,t,i,r,n,s,a,o)=>{const l=Xa(i),c=$a(r),u=ja(i),d=ja(r),h=Ka(i);if(Ka(r))if(h){const r=new ArrayBuffer(o*u),n=F(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.")},eo=e=>{if(!Fe(e))throw new TypeError("timestamp must be a number.")},to=(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 io{constructor(e){if(!(e instanceof yo))throw new TypeError("track must be an InputTrack.");this._track=e}getFirstPacket(){return y(this,arguments,function*(e={}){if(Za(e),this._track.input._disposed)throw new Do;return to(this._track,this._track._backing.getFirstPacket(e),e)})}getFirstKeyPacket(){return y(this,arguments,function*(e={}){Za(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(eo(e),Za(t),this._track.input._disposed)throw new Do;return to(this._track,this._track._backing.getPacket(e,t),t)})}getNextPacket(e){return y(this,arguments,function*(e,t={}){if(!(e instanceof Li))throw new TypeError("packet must be an EncodedPacket.");if(Za(t),this._track.input._disposed)throw new Do;return to(this._track,this._track._backing.getNextPacket(e,t),t)})}getKeyPacket(e){return y(this,arguments,function*(e,t={}){if(eo(e),Za(t),this._track.input._disposed)throw new Do;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);const i=yield this._track._backing.getKeyPacket(e,t);if(!i)return i;I("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 Li))throw new TypeError("packet must be an EncodedPacket.");if(Za(t),this._track.input._disposed)throw new Do;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);const i=yield this._track._backing.getNextKeyPacket(e,t);if(!i)return i;I("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 Li))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 Li))throw new TypeError("endPacket must be an EncodedPacket.");if(Za(i),this._track.input._disposed)throw new Do;const r=[];let{promise:n,resolve:s}=Y(),{promise:a,resolve:o}=Y(),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}=Y()),yield a):(r.push(u),s(),({promise:n,resolve:s}=Y()),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 Do;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 ro{constructor(e,t){this.onSample=e,this.onError=t}}class no{mediaSamplesInRange(e=-1/0,t=1/0,i){eo(e),eo(t);const r=[];let n=!1,s=null,{promise:a,resolve:o}=Y(),{promise:l,resolve:c}=Y(),u=!1,d=!1,m=!1,p=null,g=null,k=!1;const b=f(h({},i),{verifyKeyPackets:!0,metadataOnly:!1});(()=>y(this,null,function*(){var i;p=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}=Y())))},e=>{k||(g=e,k=!0,o())});const h=this._createPacketSink(),f=null!=(i=yield h.getKeyPacket(e,b))?i:yield h.getFirstKeyPacket(b);let y=f;const T=h.packets(null!=f?f:void 0,void 0,b);for(yield T.next();y&&!d&&!this._track.input._disposed;){const e=so(r.length);if(r.length+p.getDecodeQueueSize()>e){({promise:l,resolve:c}=Y()),yield l;continue}p.decode(y);const t=yield T.next();if(t.done)break;y=t.value}yield T.return(),m||this._track.input._disposed||(yield p.flush()),!n&&s&&r.push(s),u=!0,o()}))().catch(e=>{k||(g=e,k=!0,o())}).finally(()=>{null==p||p.close()});const T=this._track,v=()=>{null==s||s.close();for(const e of r)e.close()};return{next(){return y(this,null,function*(){for(;;){if(T.input._disposed)throw m=!0,d=!0,v(),new Do;if(m)return{value:void 0,done:!0};if(k)throw m=!0,d=!0,v(),g;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 m=!0,d=!0,c(),o(),v(),{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 T(this,null,function*(){Symbol.iterator in e?yield*v(e[Symbol.iterator]()):yield*v(e[Symbol.asyncIterator]())})}(e),r=[],n=[];let{promise:s,resolve:a}=Y(),{promise:o,resolve:l}=Y(),c=!1,u=!1,d=null,m=null,p=!1;const g=e=>{n.push(e),a(),({promise:s,resolve:a}=Y())},k=f(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{p||(m=e,p=!0,a())});const e=this._createPacketSink();let t=null,s=null,h=-1;const f=()=>y(this,null,function*(){I(s),I(d);let t=s;for(d.decode(t);t.sequenceNumberi&&!u;)({promise:o,resolve:l}=Y()),yield o;if(u)break;const r=yield e.getNextPacket(t,k);I(r),d.decode(r),t=r}h=-1}),b=()=>y(this,null,function*(){I(d),yield d.flush();for(let e=0;e{p||(m=e,p=!0,a())}).finally(()=>{null==d||d.close()});const b=this._track,w=()=>{for(const e of n)null==e||e.close()};return{next(){return y(this,null,function*(){for(;;){if(b.input._disposed)throw u=!0,w(),new Do;if(u)return{value:void 0,done:!0};if(p)throw u=!0,w(),m;if(n.length>0){const e=n.shift();return I(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(),w(),{value:void 0,done:!0}})},throw(e){return y(this,null,function*(){throw e})},[Symbol.asyncIterator](){return this}}}}const so=e=>0===e?40:8;class ao extends ro{constructor(e,t,i,r,n,s){var a,o,l,c,u,d,m,p;super(e,t),this.codec=i,this.decoderConfig=r,this.rotation=n,this.timeResolution=s,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new ye,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 g=Ya.find(e=>e.supports(i,r));if(g)this.customDecoder=new g,this.customDecoder.codec=i,this.customDecoder.config=r,this.customDecoder.onSample=e=>{if(!(e instanceof xa))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();I(void 0!==t),this.mergeAlpha(e,t)}else this.colorQueue.push(e)};if(Pe()){if("avc"===i&&this.decoderConfig.description){const e=mt(R(this.decoderConfig.description));if(e&&e.sequenceParameterSets.length>0){const t=gt(e.sequenceParameterSets[0]);t&&(0===t.frameMbsOnlyFlag&&(this.decoderConfig=f(h({},this.decoderConfig),{hardwareAcceleration:"prefer-software"})),0!==t.maxDecFrameBuffering&&1!==t.bitstreamRestrictionFlag&&(e.sequenceParameterSets[0]=yt(t),this.decoderConfig=f(h({},this.decoderConfig),{description:ft(e)})))}}q(this.decoderConfig.colorSpace)||(this.decoderConfig=f(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!=(p=null==(m=this.decoderConfig.colorSpace)?void 0:m.fullRange)&&p}}))}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:(I(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(I(this.decoder),Te()||Q(this.inputTimestamps,e.timestamp,e=>e),Pe()&&0===this.currentPacketIndex)if("avc"===this.codec){const t=[];let i=!1;for(const n of at(e.data,this.decoderConfig)){const r=ot(e.data[n.offset]);if(i||(i=r>=1&&r<=5),r===et.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&R(t.description)[4];return dt(e,i+1)}return ut(e)})(t,this.decoderConfig);e=new Li(r,e.type,e.timestamp,e.duration)}else if("hevc"===this.codec){const t=Ft(e.data,this.decoderConfig);t&&(e=new Li(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 lo),!this.alphaDecoder){const e=e=>{if(this.colorQueue.length>0){const t=this.colorQueue.shift();I(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();I(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=Ut(this.codec,this.decoderConfig,e.sideData.alpha);if(this.alphaHadKeyframe||(this.alphaHadKeyframe="key"===t),this.alphaHadKeyframe){if("hevc"===this.codec&&this.currentAlphaPacketIndex>0&&!this.alphaRaslSkipped){if(this.hasHevcRaslPicture(e.sideData.alpha))return void this.pushNullAlphaFrame();this.alphaRaslSkipped=!0}this.currentAlphaPacketIndex++,this.alphaDecoder.decode(e.alphaToEncodedVideoChunk(null!=t?t:e.type)),this.alphaDecoderQueueSize++}else this.pushNullAlphaFrame()}pushNullAlphaFrame(){0===this.alphaDecoderQueueSize?this.alphaQueue.push(null):this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture(e){for(const t of bt(e,this.decoderConfig)){const i=Tt(e[t.offset]);if(i===it.RASL_N||i===it.RASL_R)return!0}return!1}sampleHandler(e){if(Te()){if(this.sampleQueue.length>0&&e.timestamp>=C(this.sampleQueue).timestamp){for(const e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}Q(this.sampleQueue,e,e=>e.timestamp)}else{const t=this.inputTimestamps.shift();I(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=Y();this.mergeAlphaPromises.push(i.promise);const r={sample:null};this.finalSamples.push(r);try{if(t){I(this.merger);const i=yield this.merger.merge(e,t);r.sample=new xa(i)}else r.sample=new xa(e);for(;this.finalSamples.length>0&&null!==this.finalSamples[0].sample;){const e=this.finalSamples.shift();this.sampleHandler(e.sample)}}catch(n){J(this.finalSamples,r),this.onError(n)}finally{J(this.mergeAlphaPromises,i.promise),i.resolve()}})}flush(){return y(this,null,function*(){var e;if(this.customDecoder?yield this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(I(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),Te()){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()):(I(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 oo=null;class lo{constructor(){this.workers=[],this.nextWorkerIndex=0,this.pendingRequests=new Map,this.nextRequestId=0}merge(e,t){if(0===this.workers.length){if(!oo){const e=new Blob([`(${co.toString()})()`],{type:"application/javascript"});oo=URL.createObjectURL(e)}const e=se(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=Y();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 co=()=>{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 S={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,S)}),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 ho extends no{constructor(e,t={}){if(!(e instanceof vo))throw new TypeError("videoTrack must be an InputVideoTrack.");uo(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(Ie("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 I(i&&n),n=f(h({},n),{hardwareAcceleration:this._decoderOptions.hardwareAcceleration,optimizeForLatency:this._decoderOptions.optimizeForLatency}),new ao(e,t,i,n,r,s)})}_createPacketSink(){return new io(this._track)}getSample(e){return y(this,arguments,function*(e,t={}){eo(e);try{for(var i,r,n,s=S(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 fo{constructor(e,t={}){var i,r,n;if(this._rotation=0,this._initPromise=null,this._nextCanvasIndex=0,!(e instanceof vo))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&&Da(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&&uo(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 ho(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=Aa(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||Se()});I(s),e._drawWithFitAndMipmapping(r,s,{fit:this._fit,rotation:this._rotation,crop:this._crop,targetIsFresh:n,fillBlack:!this._alpha&&Se()});const a={canvas:r,timestamp:e.timestamp,duration:e.duration};return e.close(),a}getCanvas(e,t){return y(this,null,function*(){eo(e),yield this._ensureInit();const i=yield this._videoSampleSink.getSample(e,t);return i&&this._videoSampleToWrappedCanvas(i)})}canvases(e,t,i){return T(this,null,function*(){yield new b(this._ensureInit()),yield*v(ne(this._videoSampleSink.samples(e,t,i),e=>this._videoSampleToWrappedCanvas(e)))})}canvasesAtTimestamps(e,t){return T(this,null,function*(){yield new b(this._ensureInit()),yield*v(ne(this._videoSampleSink.samplesAtTimestamps(e,t),e=>e&&this._videoSampleToWrappedCanvas(e)))})}}class mo extends ro{constructor(e,t,i,r){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new ye,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=Ja.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 Va))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 Va(e))}catch(t){this.onError(t)}},error:t=>{t.stack=e,this.onError(t)}}),this.decoder.configure(r)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(I(this.decoder),this.decoder.decodeQueueSize)}decode(e){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).catch(e=>this.onError(e)).finally(()=>this.customDecoderQueueSize--)):(I(this.decoder),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()):(I(this.decoder),yield this.decoder.flush()),this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0})}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(I(this.decoder),"closed"!==this.decoder.state&&this.decoder.close())}}class po extends ro{constructor(e,t,i){super(e,t),this.decoderConfig=i,this.currentTimestamp=null,I(di.includes(i.codec)),this.codec=i.codec;const{dataType:r,sampleSize:n,littleEndian:s}=Pi(this.codec);switch(this.inputSampleSize=n,n){case 1:"unsigned"===r?this.readInputValue=(e,t)=>e.getUint8(t)-u(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)-u(2,15):"signed"===r?this.readInputValue=(e,t)=>e.getInt16(t,s):I(!1);break;case 3:"unsigned"===r?this.readInputValue=(e,t)=>ie(e,t,s)-u(2,23):"signed"===r?this.readInputValue=(e,t)=>((e,t,i)=>ie(e,t,i)<<8>>8)(e,t,s):I(!1);break;case 4:"unsigned"===r?this.readInputValue=(e,t)=>e.getUint32(t,s)-u(2,31):"signed"===r?this.readInputValue=(e,t)=>e.getInt32(t,s):"float"===r?this.readInputValue=(e,t)=>e.getFloat32(t,s):I(!1);break;case 8:"float"===r?this.readInputValue=(e,t)=>e.getFloat64(t,s):I(!1);break;default:te(n),I(!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+u(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:te(n),I(!1)}}getDecodeQueueSize(){return 0}decode(e){const t=F(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 Va({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 go extends no{constructor(e){if(!(e instanceof So))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(Ie("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 I(i&&r),di.includes(r.codec)?new po(e,t,r):new mo(e,t,i,r)})}_createPacketSink(){return new io(this._track)}getSample(e){return y(this,arguments,function*(e,t={}){eo(e);try{for(var i,r,n,s=S(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 ko{constructor(e){if(!(e instanceof So))throw new TypeError("audioTrack must be an InputAudioTrack.");this._audioSampleSink=new go(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*(){eo(e);const i=yield this._audioSampleSink.getSample(e,t);return i&&this._audioSampleToWrappedArrayBuffer(i)})}buffers(e,t,i){return ne(this._audioSampleSink.samples(e,t,i),e=>this._audioSampleToWrappedArrayBuffer(e))}buffersAtTimestamps(e,t){return ne(this._audioSampleSink.samplesAtTimestamps(e,t),e=>e&&this._audioSampleToWrappedArrayBuffer(e))}}class yo{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof vo}isAudioTrack(){return this instanceof So}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 bo(this._backing.getInternalCodecId(),"internalCodecId","getInternalCodecId")}getLanguageCode(){return y(this,null,function*(){return this._backing.getLanguageCode()})}get languageCode(){return bo(this._backing.getLanguageCode(),"languageCode","getLanguageCode")}getName(){return y(this,null,function*(){return this._backing.getName()})}get name(){return bo(this._backing.getName(),"name","getName")}getTimeResolution(){return y(this,null,function*(){return this._backing.getTimeResolution()})}get timeResolution(){return bo(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 bo(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 ce(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 io(this);let r=1/0,n=-1/0,s=0,a=0;try{for(var o,l,c,u=S(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 yo))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(xo({filter:e=>e.canBePairedWith(this)},e))})}getPairableVideoTracks(e){return y(this,null,function*(){return this.input.getVideoTracks(xo({filter:e=>e.canBePairedWith(this)},e))})}getPairableAudioTracks(e){return y(this,null,function*(){return this.input.getAudioTracks(xo({filter:e=>e.canBePairedWith(this)},e))})}getPrimaryPairableVideoTrack(e){return y(this,null,function*(){return this.input.getPrimaryVideoTrack(xo({filter:e=>e.canBePairedWith(this)},e))})}getPrimaryPairableAudioTrack(e){return y(this,null,function*(){return this.input.getPrimaryAudioTrack(xo({filter:e=>e.canBePairedWith(this)},e))})}hasPairableTrack(e){return y(this,null,function*(){e&&(e=To(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=To(e)),this.hasPairableTrack(t=>y(this,null,function*(){return t.isVideoTrack()&&(!e||(yield e(t)))}))}hasPairableAudioTrack(e){return e&&(e=To(e)),this.hasPairableTrack(t=>y(this,null,function*(){return t.isAudioTrack()&&(!e||(yield e(t)))}))}}const bo=(e,t,i)=>{if(Ce(e))throw new Error(`'${t}' is deprecated and not available synchronously for this track. Use the preferred '${i}()' instead.`);return e},To=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 Ce(r)?r.then(i):i(r)}:void 0};class vo extends yo{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 bo(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 bo(this._backing.getCodedWidth(),"codedWidth","getCodedWidth")}getCodedHeight(){return y(this,null,function*(){return this._backing.getCodedHeight()})}get codedHeight(){return bo(this._backing.getCodedHeight(),"codedHeight","getCodedHeight")}getRotation(){return y(this,null,function*(){return this._backing.getRotation()})}get rotation(){return bo(this._backing.getRotation(),"rotation","getRotation")}getSquarePixelWidth(){return y(this,null,function*(){return this._backing.getSquarePixelWidth()})}get squarePixelWidth(){return bo(this._backing.getSquarePixelWidth(),"squarePixelWidth","getSquarePixelWidth")}getSquarePixelHeight(){return y(this,null,function*(){return this._backing.getSquarePixelHeight()})}get squarePixelHeight(){return bo(this._backing.getSquarePixelHeight(),"squarePixelHeight","getSquarePixelHeight")}getPixelAspectRatio(){return y(this,null,function*(){var e;return null!=(e=this._pixelAspectRatioCache)?e:this._pixelAspectRatioCache=Ne({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=Ne({num:bo(this._backing.getSquarePixelWidth(),"pixelAspectRatio","getPixelAspectRatio")*bo(this._backing.getCodedHeight(),"pixelAspectRatio","getPixelAspectRatio"),den:bo(this._backing.getSquarePixelHeight(),"pixelAspectRatio","getPixelAspectRatio")*bo(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=bo(i,"displayWidth","getDisplayWidth");if(null!==e)return e}const r=bo(this._backing.getRotation(),"displayWidth","getDisplayWidth")%180===0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight();return bo(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=bo(i,"displayHeight","getDisplayHeight");if(null!==e)return e}const r=bo(this._backing.getRotation(),"displayHeight","getDisplayHeight")%180===0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth();return bo(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(I(null!==t),Ya.some(i=>i.supports(t,e)))return!0;if("undefined"===typeof VideoDecoder)return!1;return!0===(yield VideoDecoder.isConfigSupported(e)).supported}catch(e){return We._error("Error during decodability check:",e),!1}})}determinePacketType(e){return y(this,null,function*(){if(!(e instanceof Li))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 I(i),Ut(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&&(!Fe(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 io(this),a=[];let o=-1/0,l=0;try{for(var c,u,d,h=S(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 S=0;Se-t),x=P-1>>1,C=P>>1;let B=0,E=0,_=0;for(const S of I)if(_+=b.get(S),0===B&&_>x&&(B=S),_>C){E=S;break}const R=(k/B+k/E)/2;return{underlyingFrameRate:g,bestGuessFrameRate:null!==g?g:_o(R),minFrameRate:k/v,maxFrameRate:k/T,averageFrameRate:k*P/w,medianFrameRate:R,frameRateIsConstant:null!==g&&1===T&&1===v,probedPacketCount:l}})}}class So extends yo{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 bo(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 bo(this._backing.getNumberOfChannels(),"numberOfChannels","getNumberOfChannels")}getSampleRate(){return y(this,null,function*(){return this._backing.getSampleRate()})}get sampleRate(){return bo(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(I(null!==t),Ja.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 We._error("Error during decodability check:",e),!1}})}determinePacketType(e){return y(this,null,function*(){if(!(e instanceof Li))throw new TypeError("packet must be an EncodedPacket.");return null===(yield this.getCodec())?null:"key"})}}const wo=e=>-(null!=e?e:-1/0),Po=e=>-e,Io=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 Ce(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 Ce(r)?r.then(i):i(r)}:void 0}},xo=(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 Ce(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 Ce(o)||Ce(l)?Promise.all([o,l]).then(([e,t])=>c(e,t)):c(o,l)}:void 0}),Co=(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=>Ce(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=>Ce(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)}),Bo=(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 Xs)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof ys||e.source instanceof bs))throw new TypeError("options.source must be a Source or SourceRef.");if(e.source instanceof ys&&e.source._disposed)throw new TypeError("options.source must not be a disposed Source.");if(void 0!==e.initInput&&!(e.initInput instanceof Fo))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 ys?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*(){I(this._rootSource instanceof Ts);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&&vs(i.request,e));if(i)return i.age++,Promise.resolve(i.sourceRef.source.ref());const r=this._sourceCachePromises.find(i=>i.cacheGroup===t&&vs(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(De(this._sourceCache,e=>e.cacheGroup===t&&1===e.sourceRef.source._refCount)>=4){const e=Me(this._sourceCache,e=>e.cacheGroup===t&&1===e.sourceRef.source._refCount?e.age:1/0);I(-1!==e);const i=this._sourceCache[e];this._sourceCache.splice(e,1),i.sourceRef.free(),J(this._sourceRefs,i.sourceRef)}this._sourceRefs.push(i);const r=this._sourceCachePromises.findIndex(t=>t.request===e);I(-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 Mo(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 Ao}))()}get source(){return this._rootSource}getFormat(){return y(this,null,function*(){return yield this._getDemuxer(),I(this._format),this._format})}canRead(){return y(this,null,function*(){try{return yield this._getDemuxer(),!0}catch(e){if(e instanceof Ao)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=Io(e));const t=(yield this._getTrackBackings()).map(e=>this._wrapBackingAsTrack(e));return Co(t,e)})}getVideoTracks(e){return y(this,null,function*(){e&&(e=Io(e));const t=(yield this.getTracks()).filter(e=>e.isVideoTrack());return Co(t,e)})}getAudioTracks(e){return y(this,null,function*(){e&&(e=Io(e));const t=(yield this.getTracks()).filter(e=>e.isAudioTrack());return Co(t,e)})}getPrimaryVideoTrack(e){return y(this,null,function*(){var t;e&&(e=Io(e));const i=xo(e,{sortBy:e=>y(null,null,function*(){return[Po((yield e.getDisposition()).default),Po(yield e.hasPairableAudioTrack()),Po(!(yield e.hasOnlyKeyPackets())),wo(yield e.getBitrate())]})});return null!=(t=(yield this.getVideoTracks(i))[0])?t:null})}getPrimaryAudioTrack(e){return y(this,null,function*(){var t;e&&(e=Io(e));const i=yield this.getPrimaryVideoTrack(),r=xo(e,{sortBy:e=>y(this,null,function*(){return[Po(!i||e.canBePairedWith(i)),Po((yield e.getDisposition()).default),wo(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 vo(this,e):new So(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 Ao extends Error{constructor(e="Input has an unsupported or unrecognizable format."){super(e),this.name="UnsupportedInputFormatError"}}class Do extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}}class Mo{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 Do;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 No(t,F(t),0,e,e)}const i=e+t,r=this.source._read(e,i,0,ks);return Ce(r)?r.then(t=>t?new No(t.bytes,t.view,t.offset,e,i):null):r?new No(r.bytes,r.view,r.offset,e,i):null}requestSliceRange(e,t,i){if(this.source._disposed)throw new Do;if(e<0)return null;if(null!==this.fileSizeNonStrict)return this.requestSlice(e,se(this.fileSizeNonStrict-e,t,i));{const r=this.requestSlice(e,i),n=r=>r||(I(null!==this.fileSizeNonStrict),this.requestSlice(e,se(this.fileSizeNonStrict-e,t,i)));return Ce(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(Ce(i)&&(i=yield i),!i||0===i.length)break;const r=Lo(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 No(i,F(i),0,0,t)}))()}}class No{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 No(e,F(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 No(this.bytes,this.view,this.offset,e,e+t)}}const Oo=(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.`)},Lo=(e,t)=>{Oo(e,t);const i=e.bytes.subarray(e.bufferPos,e.bufferPos+t);return e.bufferPos+=t,i},zo=e=>(Oo(e,1),e.view.getUint8(e.bufferPos++)),Uo=(e,t)=>{Oo(e,2);const i=e.view.getUint16(e.bufferPos,t);return e.bufferPos+=2,i},qo=e=>{Oo(e,2);const t=e.view.getUint16(e.bufferPos,!1);return e.bufferPos+=2,t},Wo=e=>{Oo(e,3);const t=ie(e.view,e.bufferPos,!1);return e.bufferPos+=3,t},Ho=e=>{Oo(e,2);const t=e.view.getInt16(e.bufferPos,!1);return e.bufferPos+=2,t},Vo=(e,t)=>{Oo(e,4);const i=e.view.getUint32(e.bufferPos,t);return e.bufferPos+=4,i},jo=e=>{Oo(e,4);const t=e.view.getUint32(e.bufferPos,!1);return e.bufferPos+=4,t},Ko=e=>{Oo(e,4);const t=e.view.getUint32(e.bufferPos,!0);return e.bufferPos+=4,t},Xo=e=>{Oo(e,4);const t=e.view.getInt32(e.bufferPos,!1);return e.bufferPos+=4,t},$o=(e,t)=>{let i,r;return t?(i=Vo(e,!0),r=Vo(e,!0)):(r=Vo(e,!1),i=Vo(e,!1)),4294967296*r+i},Go=e=>4294967296*jo(e)+jo(e),Qo=e=>4294967296*Xo(e)+jo(e),Yo=e=>{const t=Ko(e),i=(e=>{Oo(e,4);const t=e.view.getInt32(e.bufferPos,!0);return e.bufferPos+=4,t})(e);return 4294967296*i+t},Jo=e=>{Oo(e,4);const t=e.view.getFloat32(e.bufferPos,!1);return e.bufferPos+=4,t},Zo=e=>{Oo(e,8);const t=e.view.getFloat64(e.bufferPos,!1);return e.bufferPos+=8,t},el=(e,t)=>{Oo(e,t);let i="";for(let r=0;rA.decode(Lo(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 il,rl,nl,sl;(rl=il||(il={}))[rl.Unsynchronisation=128]="Unsynchronisation",rl[rl.ExtendedHeader=64]="ExtendedHeader",rl[rl.ExperimentalIndicator=32]="ExperimentalIndicator",rl[rl.Footer=16]="Footer",(sl=nl||(nl={}))[sl.ISO_8859_1=0]="ISO_8859_1",sl[sl.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",sl[sl.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",sl[sl.UTF_8=3]="UTF_8";const al=128,ol=10,ll=["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"],cl=(e,t)=>{var i;const r=e.filePos;null!=t.raw||(t.raw={}),null!=(i=t.raw).TAG||(i.TAG=Lo(e,al-3)),e.filePos=r;const n=ul(e,30);n&&(null!=t.title||(t.title=n));const s=ul(e,30);s&&(null!=t.artist||(t.artist=s));const a=ul(e,30);a&&(null!=t.album||(t.album=a));const o=ul(e,4),l=Number.parseInt(o,10);Number.isInteger(l)&&l>0&&(null!=t.date||(t.date=new Date(String(l))));const c=Lo(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=ul(e,28),e.skip(2)}else e.skip(-30),u=ul(e,30);u&&(null!=t.comment||(t.comment=u));const d=zo(e);d{const i=Lo(e,t),r=Be(i.indexOf(0),i.length),n=i.subarray(0,r);let s="";for(let a=0;a{const t=e.filePos,i=el(e,3),r=zo(e),n=zo(e),s=zo(e),a=jo(e);if("ID3"!==i||255===r||255===n||0!==(2155905152&a))return e.filePos=t,null;let o=Fi(a);return s&il.Footer&&(o+=ol),{majorVersion:r,revision:n,flags:s,size:o}},hl=(e,t,i)=>{var r,n,s,a,o,l;if(![2,3,4].includes(t.majorVersion))return void We._warn(`Unsupported ID3v2 major version: ${t.majorVersion}`);const c=t.flags&il.Footer?t.size-ol:t.size,u=Lo(e,c),d=new fl(t,u);if(t.flags&il.Unsynchronisation&&3===t.majorVersion&&d.ununsynchronizeAll(),t.flags&il.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&il.Unsynchronisation)),h)We._warn(`Skipping encrypted ID3v2 frame ${e.id}`),d.pos=u;else if(f)We._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!==ll[e]){null!=i.genre||(i.genre=ll[e]);break}}if(t=/^\d+$/.exec(e),t){const e=Number.parseInt(t[0]);if(void 0!==ll[e]){null!=i.genre||(i.genre=ll[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 fl{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:Fi(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 nl.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=Be(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=Be(r.findIndex(e=>0===e),r.length);return this.pos=i+Math.min(e+1,r.length),A.decode(r.subarray(0,e))}case nl.UTF_16_BE_NO_BOM:{const e=new TextDecoder("utf-16be"),t=Be(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 nl.UTF_8:{const e=Be(r.findIndex(e=>0===e),r.length);return this.pos=i+Math.min(e+1,r.length),A.decode(r.subarray(0,e))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";const t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}}class ml{constructor(e){this.events=e,this.input=null,this.audioSink=null,this.audioIterator=null,this.audioContext=null,this.gainNode=null,this.audioContextStartTime=0,this.playbackTimeAtStart=0,this.latestScheduledEndTime=0,this.duration=Number.NaN,this.paused=!0,this.volume=.7,this.muted=!1,this.playbackRate=1,this.asyncId=0,this.queuedNodes=new Set}get currentTime(){return this.paused?this.playbackTimeAtStart:(this.audioContext.currentTime-this.audioContextStartTime)*this.playbackRate+this.playbackTimeAtStart}ensureAudioContext(e){if(this.audioContext)return;const t=window.AudioContext||window.webkitAudioContext;try{this.audioContext=new t({sampleRate:e})}catch(i){this.audioContext=new t}this.gainNode=this.audioContext.createGain(),this.gainNode.connect(this.audioContext.destination),this.updateGain()}updateGain(){if(!this.gainNode)return;const e=this.muted?0:this.volume;this.gainNode.gain.value=e*e}stopQueuedNodes(){this.queuedNodes.forEach(e=>e.stop()),this.queuedNodes.clear()}stopIterator(){return y(this,null,function*(){var e;yield null==(e=this.audioIterator)?void 0:e.return(),this.audioIterator=null})}handleNoAudioTrack(){this.audioSink=null,this.ensureAudioContext()}load(e,t){return y(this,null,function*(){++this.asyncId,yield this.stopIterator(),this.stopQueuedNodes(),this.paused=!0,this.playbackTimeAtStart=0,this.audioContextStartTime=0;const{input:i,audioTrack:r,duration:n}=e;return this.input=i,this.duration=n,r?null!==r.codec&&(yield r.canDecode())?(this.ensureAudioContext(r.sampleRate),this.audioSink=new ko(r),void(null==t||t())):(this.audioSink=null,this.ensureAudioContext(),void(null==t||t())):(this.handleNoAudioTrack(),void(null==t||t()))})}runIterator(e){return y(this,null,function*(){if(!this.audioSink)return;yield this.stopIterator(),this.audioIterator=this.audioSink.buffers(this.currentTime);for(;;){if(e!==this.asyncId||this.paused)return;const i=[];let r=!1;try{for(let e=0;e<16;e++){const e=yield this.audioIterator.next();if(e.done){r=!0;break}i.push(e.value)}}catch(t){console.error("Audio iterator error:",t),r=!0}if(e!==this.asyncId||this.paused)return;i.length>0&&"suspended"===this.audioContext.state&&(yield this.audioContext.resume(),this.events.emit("canplay"),this.events.emit("playing"));for(const{buffer:e,timestamp:t}of i){const i=this.audioContext.createBufferSource();i.buffer=e,i.connect(this.gainNode),i.playbackRate.value=this.playbackRate;const r=this.audioContextStartTime+(t-this.playbackTimeAtStart)/this.playbackRate,n=(r+e.duration/this.playbackRate-this.audioContextStartTime)*this.playbackRate+this.playbackTimeAtStart;n>this.latestScheduledEndTime&&(this.latestScheduledEndTime=n),r>=this.audioContext.currentTime?i.start(r):i.start(this.audioContext.currentTime,(this.audioContext.currentTime-r)*this.playbackRate),this.queuedNodes.add(i),i.onended=()=>this.queuedNodes.delete(i)}if(r)break;yield new Promise(e=>setTimeout(e,0));const n=1;for(;this.latestScheduledEndTime-this.currentTime>n;){if(e!==this.asyncId||this.paused)return;yield new Promise(e=>setTimeout(e,50))}}})}play(){return y(this,null,function*(){if(!this.paused)return;this.audioContext||this.ensureAudioContext(),"suspended"===this.audioContext.state&&(yield this.audioContext.resume()),this.audioContextStartTime=this.audioContext.currentTime,this.latestScheduledEndTime=this.playbackTimeAtStart,this.paused=!1;const e=++this.asyncId;this.runIterator(e)})}pause(){this.paused||(this.playbackTimeAtStart=this.currentTime,this.paused=!0,this.stopIterator(),this.stopQueuedNodes())}seek(e){return y(this,null,function*(){this.playbackTimeAtStart=Math.max(0,e),this.audioContextStartTime=this.audioContext.currentTime,this.latestScheduledEndTime=this.playbackTimeAtStart;const t=++this.asyncId;this.paused||this.runIterator(t)})}setVolume(e,t){this.volume=e,this.muted=t,this.updateGain()}setPlaybackRate(e){if(e!==this.playbackRate&&(this.paused||(this.playbackTimeAtStart=this.currentTime,this.audioContextStartTime=this.audioContext.currentTime),this.playbackRate=e,!this.paused)){const e=++this.asyncId;this.runIterator(e)}}destroy(){var e;this.asyncId++,this.pause(),null==(e=this.audioContext)||e.close(),this.audioContext=null,this.input=null,this.audioSink=null}}function pl(e){return y(this,null,function*(){var t,i;return null!=(i=null!=(t=yield e.getAverageBitrate())?t:yield e.getBitrate())?i:0})}const gl=/\.m3u8(?:$|[?#])/i;function kl(e){return"string"===typeof e&&gl.test(e)}function yl(e){const t=function(e){return"string"===typeof e?new Bs(e):e instanceof Blob?new Ps(e):"undefined"!==typeof ReadableStream&&e instanceof ReadableStream?new Rs(e):null!=e?e:null}(e);return t?new Fo({source:t,formats:kl(e)?ya:ka}):null}class bl{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 Tl(e,t,i){for(const r of i){if(!t())return;e.emit(r)}}function vl(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 Sl(){let e,t;return{promise:new Promise((i,r)=>{e=i,t=r}),resolve:e,reject:t}}class wl{constructor(e){this.host=e,this.wanted=!1,this.playing=null,this.seeking=null,this.audioStart=null}operation(){return f(h({},Sl()),{source:this.host.loadSeq,complete:Sl()})}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}startAudio(){return y(this,null,function*(){this.audioStart||(this.audioStart=this.host.audio.play());const e=this.audioStart;try{yield e}finally{this.audioStart===e&&(this.audioStart=null)}})}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.startAudio(),!t())return void(this.wanted&&!this.host.destroyed||this.host.audio.pause());this.host.video.start(this.host.audio),Tl(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 vl(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,Tl(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(),Tl(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())})}}class Pl{constructor({canvas:e,ctx:t,events:i,timeupdateInterval:r=250,avSyncTolerance:n=.12,dropLateFrames:s=!1,poster:a="",preflightRange:o=!1}){this.canvas=e,this.ctx=t,this.events=i,this.timeupdateInterval=r,this.avSyncTolerance=n,this.dropLateFrames=s,this.poster=a,this.preflightRange=o,this.input=null,this.videoSink=null,this.videoIterator=null,this.nextFrame=null,this.rafId=0,this.asyncId=0,this.width=0,this.height=0,this.duration=Number.NaN,this.audioClock=null,this.lastTimeUpdate=0,this.stalled=!1,this.playbackRate=1,this.posterDrawn=!1,this.isFetching=!1}preflight(e,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||kl(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(!this.poster||this.posterDrawn)return;const e=new Image;e.onload=()=>{this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.canvas.width=e.naturalWidth||this.canvas.width,this.canvas.height=e.naturalHeight||this.canvas.height,this.ctx.drawImage(e,0,0,this.canvas.width,this.canvas.height),this.posterDrawn=!0},e.src=this.poster}stopIterator(){return y(this,null,function*(){var e;yield null==(e=this.videoIterator)?void 0:e.return(),this.videoIterator=null})}clear(){this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height)}load(e,t){return y(this,null,function*(){++this.asyncId,yield this.stopIterator(),this.clear(),this.posterDrawn=!1;const{input:i,videoTrack:r,duration:n}=e;if(this.input=i,this.duration=n,!r)return this.handleNoVideoTrack(),void(null==t||t());if(null===r.codec||!(yield r.canDecode()))return this.handleNoVideoTrack(),void(null==t||t());const s=yield r.canBeTransparent();this.videoSink=new fo(r,{poolSize:2,fit:"contain",alpha:s}),this.width=r.displayWidth,this.height=r.displayHeight,this.canvas.width=this.width,this.canvas.height=this.height,null==t||t(),yield this.resetIterator(0)})}handleNoVideoTrack(){this.videoSink=null,this.width=0,this.height=0,this.canvas.width=0,this.canvas.height=0,this.clear(),this.drawPoster()}resetIterator(e){return y(this,null,function*(){var t,i;if(yield this.stopIterator(),!this.videoSink)return;this.videoIterator=this.videoSink.canvases(e);const r=null!=(t=(yield this.videoIterator.next()).value)?t:null,n=null!=(i=(yield this.videoIterator.next()).value)?i:null;this.nextFrame=n,r?this.ctx.drawImage(r.canvas,0,0):this.drawPoster()})}updateNextFrame(e){return y(this,null,function*(){var t;if(this.videoIterator&&!this.isFetching){this.isFetching=!0;try{for(;;){const i=null!=(t=(yield this.videoIterator.next()).value)?t:null;if(!i||e!==this.asyncId)return;const r=this.audioClock.currentTime,n=this.dropLateFrames?Math.max(.06,this.avSyncTolerance/Math.max(1,this.playbackRate)):0;if(!(this.dropLateFrames&&i.timestampr)return void(this.nextFrame=null)}}}finally{this.isFetching=!1}}})}render(){if(!this.audioClock)return;const e=this.audioClock.currentTime,t=Date.now();if(t-this.lastTimeUpdate>=this.timeupdateInterval&&(this.events.emit("timeupdate"),this.lastTimeUpdate=t),Number.isFinite(this.duration)&&e>=this.duration)return this.stop(),this.stalled=!1,this.events.emit("ended"),this.events.emit("pause"),void this.events.emit("canplay");this.nextFrame&&this.nextFrame.timestamp<=e?(this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.ctx.drawImage(this.nextFrame.canvas,0,0),this.nextFrame=null,this.updateNextFrame(this.asyncId),this.stalled&&(this.events.emit("canplay"),this.events.emit("playing"),this.stalled=!1)):this.nextFrame||(this.updateNextFrame(this.asyncId),!this.nextFrame&&Number.isFinite(this.duration)&&ethis.render())}start(e){this.audioClock=e,this.asyncId++,this.stalled=!1,this.updateNextFrame(this.asyncId),this.rafId=requestAnimationFrame(()=>this.render())}stop(){cancelAnimationFrame(this.rafId)}seek(e){return y(this,null,function*(){this.asyncId++,yield this.resetIterator(e)})}setPlaybackRate(e){this.playbackRate=Math.max(.1,Number(e)||1)}destroy(){this.asyncId++,this.stop(),this.stopIterator(),this.posterDrawn=!1,this.videoSink=null,this.input=null}}class Il{constructor({canvas:e,ctx:i,events:r,option:n={}}){var s,a,o,l,c;g(this,t),this.events=r,this.option=n,this.audio=new ml(r),this.video=new Pl({canvas:e,ctx:i,events:r,timeupdateInterval:null!=(s=n.timeupdateInterval)?s:250,avSyncTolerance:null!=(a=n.avSyncTolerance)?a:.12,dropLateFrames:null!=(o=n.dropLateFrames)&&o,poster:null!=(l=n.poster)?l:"",preflightRange:null!=(c=n.preflightRange)&&c}),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,k(this,t,new wl(this)),r.addEventListener("ended",()=>{this.destroyed||(this.ended=!0,this.paused=!0,p(this,t).ended())})}load(e){return y(this,null,function*(){var i,r;if(this.destroyed)return;const n=++this.loadSeq;if(p(this,t).invalidate(),null==(i=this.loadSession)||i.cancel(),n!==this.loadSeq||this.destroyed)return;if(this.pause(),n!==this.loadSeq||this.destroyed)return;this.disposeInput();const s=new bl;this.loadSession=s,this.ended=!1,this.error=null,this.networkState=2,this.readyState=0,s.defer(()=>this.events.emit("waiting")),s.defer(()=>this.events.emit("loadstart"));const a=Number.isFinite(this.option.loadTimeout)&&null!=(r=this.option.loadTimeout)?r:0;try{yield s.wait(this.performLoad(e,n,s),a)}catch(o){if(n!==this.loadSeq)return;const e=++this.loadSeq;if(p(this,t).invalidate(),s.cancel(),e!==this.loadSeq||this.destroyed)return;this.disposeInput(),this.reportError(o)}})}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=yl(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 vl({input:e,videoTrack:i,audioTrack:r}),s=i||r,a=kl(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,Tl(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,Tl(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 p(this,t).replace(h(h({},this.media),e),this.currentTime)})}selectHlsQuality(e){return y(this,null,function*(){return function(e,t){return y(this,null,function*(){var i;const{input:r,media:n,loadSeq:s}=e;if(!(null==n?void 0:n.isHls)||!r||e.destroyed)return;const a=()=>!e.destroyed&&e.loadSeq===s&&e.input===r&&e.media===n;let o;try{const e=yield r.getVideoTracks();if(!a())return;const s="auto"===t?yield r.getPrimaryVideoTrack():null!=(i=e.find(e=>e.id===t))?i:n.videoTrack;if(!a()||!s)return;let l=n.audioTrack,c=n.audioMode;l&&s.canBePairedWith(l)||(l=yield s.getPrimaryPairableAudioTrack(),c="auto"),o={videoTrack:s,audioTrack:l,videoMode:"auto"===t?"auto":"manual",audioMode:c}}catch(l){if(!a())return;throw l}a()&&(yield e.replaceTracks(o))})}(this,e)})}selectHlsAudio(e){return y(this,null,function*(){return function(e,t){return y(this,null,function*(){var i;const{input:r,media:n,loadSeq:s}=e;if(!(null==n?void 0:n.isHls)||!r||e.destroyed)return;const a=()=>!e.destroyed&&e.loadSeq===s&&e.input===r&&e.media===n;let o;try{const e=yield r.getAudioTracks();if(!a())return;const s="auto"===t?n.videoTrack?yield n.videoTrack.getPrimaryPairableAudioTrack():yield r.getPrimaryAudioTrack():null!=(i=e.find(e=>e.id===t))?i:n.audioTrack;if(!a()||!s)return;let l=n.videoTrack,c=n.videoMode;l&&s.canBePairedWith(l)||(l=yield s.getPrimaryPairableVideoTrack(),c="auto"),o={videoTrack:l,audioTrack:s,videoMode:c,audioMode:"auto"===t?"auto":"manual"}}catch(l){if(!a())return;throw l}a()&&(yield e.replaceTracks(o))})}(this,e)})}getHlsState(){return y(this,null,function*(){const e=this.media;if(this.destroyed)return null;try{const t=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 pl(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 pl(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.media!==e?null:t}catch(t){if(this.destroyed||this.media!==e)return null;throw t}})}play(){return y(this,null,function*(){return p(this,t).play()})}pause(){p(this,t).pause()}seek(e){return y(this,null,function*(){return p(this,t).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++,p(this,t).invalidate();const e=[];for(const t of[()=>{var e;return null==(e=this.loadSession)?void 0:e.cancel()},()=>this.pause(),()=>this.disposeInput(),()=>this.audio.destroy(),()=>this.video.destroy()])try{t()}catch(i){e.push(i)}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}}t=new WeakMap;const xl=new WeakMap;function Cl(e){let t=xl.get(e);return t||(t={closed:!1,frames:new Set},xl.set(e,t)),t}class Bl{constructor({art:e,canvas:t,ctx:i,option:r}){var n,s;this.art=e,this.canvas=t,this.option=r,this.events=new P,this.engine=new Il({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=Cl(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){Cl(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=Cl(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 Bl({art:t,canvas:n,ctx:s,option:e});t.mediabunny=a;const o={};for(const e in n)"function"===typeof n[e]&&(o[e]=n[e].bind(n));const l=new Set([...Object.getOwnPropertyNames(a),...Object.getOwnPropertyNames(Object.getPrototypeOf(a))]);for(const e of l)"constructor"!==e&&(e in n||Object.defineProperty(n,e,{get(){const t=a[e];return"function"===typeof t?t.bind(a):t},set(t){a[e]=t},configurable:!0,enumerable:!0}));for(const e in o)n[e]=(...t)=>o[e](...t);function c(){var e;(null==(e=t.template)?void 0:e.$player)&&!t.option.autoSize&&Object.assign(n.style,{width:"100%",height:"100%",objectFit:"contain"})}return t.on("resize",c),t.on("video:loadedmetadata",c),function({art:e,shim:t,option:i}){if(i.m3u8)return e.on("video:loadedmetadata",u),e.on("restart",u),{update:u};function r(t){e.controls.cache.has(t)&&e.controls.remove(t)}function n(t){e.setting.find(t)&&e.setting.remove(t)}function s(){r("mediabunny-quality"),n("mediabunny-quality")}function a(){r("mediabunny-audio"),n("mediabunny-audio")}function o(e={}){return e.control||e.setting}function l(r){return y(this,null,function*(){var n;const a=(null==(n=i.m3u8)?void 0:n.quality)||{};if(!o(a)||!(null==r?void 0:r.levels.length))return void s();const l=a.auto||"Auto",c=a.title||"Quality",d=a.getName||(e=>e.name||`${e.height}P`),h=r.currentLevel?d(r.currentLevel):l,f=w(r.levels.map(e=>{var t;return{html:d(e),value:e.id,default:(null==(t=r.currentLevel)?void 0:t.id)===e.id}}),"html").sort((e,t)=>{const i=r.levels.find(t=>t.id===e.value),n=r.levels.find(e=>e.id===t.value);return((null==n?void 0:n.height)||0)-((null==i?void 0:i.height)||0)});f.push({html:l,value:"auto",default:!r.currentLevel});const m=i=>y(null,null,function*(){return yield t.switchM3u8Quality(i.value),e.notice.show=`${c}: ${i.html}`,yield u(),i.html});a.control&&e.controls.update({name:"mediabunny-quality",position:"right",html:h,style:{padding:"0 10px"},selector:f,onSelect:m}),a.setting&&e.setting.update({name:"mediabunny-quality",tooltip:h,html:c,icon:'',width:200,selector:f,onSelect:m})})}function c(r){return y(this,null,function*(){var n;const s=(null==(n=i.m3u8)?void 0:n.audio)||{};if(!o(s)||!(null==r?void 0:r.audios.length)||r.audios.length<2)return void a();const l=s.auto||"Auto",c=s.title||"Audio",d=s.getName||(e=>e.name||e.lang||e.language),h=r.currentAudio?d(r.currentAudio):l,f=w(r.audios.map(e=>{var t;return{html:d(e),value:e.id,default:(null==(t=r.currentAudio)?void 0:t.id)===e.id}}),"html");f.push({html:l,value:"auto",default:!r.currentAudio});const m=i=>y(null,null,function*(){return yield t.switchM3u8Audio(i.value),e.notice.show=`${c}: ${i.html}`,yield u(),i.html});s.control&&e.controls.update({name:"mediabunny-audio",position:"right",html:h,style:{padding:"0 10px"},selector:f,onSelect:m}),s.setting&&e.setting.update({name:"mediabunny-audio",tooltip:h,html:c,icon:'',width:200,selector:f,onSelect:m})})}function u(){return y(this,null,function*(){const e=yield t.getM3u8State();if(!e)return s(),void a();yield Promise.all([l(e),c(e)])})}}({art:t,shim:a,option:e}),t.on("destroy",()=>{delete t.mediabunny,a.destroy()}),n}}}); diff --git a/packages/artplayer-proxy-mediabunny/dist/artplayer-proxy-mediabunny.mjs b/packages/artplayer-proxy-mediabunny/dist/artplayer-proxy-mediabunny.mjs index bc85640b8..ab7fa87c5 100644 --- a/packages/artplayer-proxy-mediabunny/dist/artplayer-proxy-mediabunny.mjs +++ b/packages/artplayer-proxy-mediabunny/dist/artplayer-proxy-mediabunny.mjs @@ -11,7 +11,7 @@ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj)); var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value); var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value); -var _closed; +var _closed, _playback; const $audio = ''; const $quality = ''; function uniqBy(array, property) { @@ -24271,6 +24271,62 @@ class AudioEngine { this.audioSink = null; } } +async function selectQuality(host, value) { + const { input, media, loadSeq } = host; + if (!media?.isHls || !input || host.destroyed) + return; + const current = () => !host.destroyed && host.loadSeq === loadSeq && host.input === input && host.media === media; + let selection; + try { + const tracks = await input.getVideoTracks(); + if (!current()) + return; + const videoTrack = value === "auto" ? await input.getPrimaryVideoTrack() : tracks.find((track) => track.id === value) ?? media.videoTrack; + if (!current() || !videoTrack) + return; + let audioTrack = media.audioTrack; + let audioMode = media.audioMode; + if (!audioTrack || !videoTrack.canBePairedWith(audioTrack)) { + audioTrack = await videoTrack.getPrimaryPairableAudioTrack(); + audioMode = "auto"; + } + selection = { videoTrack, audioTrack, videoMode: value === "auto" ? "auto" : "manual", audioMode }; + } catch (error) { + if (!current()) + return; + throw error; + } + if (current()) + await host.replaceTracks(selection); +} +async function selectAudio(host, value) { + const { input, media, loadSeq } = host; + if (!media?.isHls || !input || host.destroyed) + return; + const current = () => !host.destroyed && host.loadSeq === loadSeq && host.input === input && host.media === media; + let selection; + try { + const tracks = await input.getAudioTracks(); + if (!current()) + return; + const audioTrack = value === "auto" ? media.videoTrack ? await media.videoTrack.getPrimaryPairableAudioTrack() : await input.getPrimaryAudioTrack() : tracks.find((track) => track.id === value) ?? media.audioTrack; + if (!current() || !audioTrack) + return; + let videoTrack = media.videoTrack; + let videoMode = media.videoMode; + if (!videoTrack || !audioTrack.canBePairedWith(videoTrack)) { + videoTrack = await audioTrack.getPrimaryPairableVideoTrack(); + videoMode = "auto"; + } + selection = { videoTrack, audioTrack, videoMode, audioMode: value === "auto" ? "auto" : "manual" }; + } catch (error) { + if (!current()) + return; + throw error; + } + if (current()) + await host.replaceTracks(selection); +} async function getTrackBitrate(track) { return await track.getAverageBitrate() ?? await track.getBitrate() ?? 0; } @@ -24404,6 +24460,30 @@ class LoadSession { this.disposeInput(); } } +function publish(events, current, names) { + for (const name of names) { + if (!current()) + return; + events.emit(name); + } +} +function metadataBarrier(ready, current) { + let video = false; + let audio = false; + let published = false; + function complete(part) { + if (!current() || published) + return; + if (part === "video") + video = true; + else audio = true; + if (video && audio) { + published = true; + ready(); + } + } + return { video: () => complete("video"), audio: () => complete("audio") }; +} async function resolveDuration({ input, videoTrack, audioTrack }) { const tracks = [videoTrack, audioTrack].filter((track) => track !== null); const referenceTrack = videoTrack || audioTrack; @@ -24433,6 +24513,212 @@ async function selectPlaybackTracks(input, src) { audioMode: isHls ? "auto" : "manual" }; } +function completion() { + let resolve; + let reject; + const promise = new Promise((yes, no) => { + resolve = yes; + reject = no; + }); + return { promise, resolve, reject }; +} +class Playback { + constructor(host) { + this.host = host; + this.wanted = false; + this.playing = null; + this.seeking = null; + this.audioStart = null; + } + operation() { + return { ...completion(), source: this.host.loadSeq, complete: completion() }; + } + current(operation, kind) { + return !this.host.destroyed && operation.source === this.host.loadSeq && this[kind] === operation; + } + cancelPlay() { + const previous = this.playing; + this.playing = null; + previous?.resolve(); + } + invalidate() { + this.cancelPlay(); + this.wanted = false; + const previous = this.seeking; + this.seeking = null; + previous?.complete.resolve(); + previous?.resolve(); + this.host.seeking = false; + } + ended() { + this.wanted = false; + this.cancelPlay(); + } + stop() { + if (this.host.paused) + return; + this.host.paused = true; + this.stopEngines(); + this.host.events.emit("pause"); + } + stopEngines() { + const failures = []; + for (const stop of [() => this.host.audio.pause(), () => this.host.video.stop()]) { + try { + stop(); + } catch (error) { + failures.push(error); + } + } + if (failures.length) + throw failures[0]; + } + pause() { + this.wanted = false; + this.cancelPlay(); + this.stop(); + } + play() { + if (this.host.destroyed) + return Promise.resolve(); + this.wanted = true; + if (this.playing) + return this.playing.promise; + if (this.host.ended) + return this.seek(0, true); + if (!this.host.paused && !this.seeking) + return Promise.resolve(); + const operation = this.operation(); + this.playing = operation; + this.runPlay(operation).then(operation.resolve, operation.reject); + return operation.promise; + } + async startAudio() { + if (!this.audioStart) + this.audioStart = this.host.audio.play(); + const pending = this.audioStart; + try { + await pending; + } finally { + if (this.audioStart === pending) + this.audioStart = null; + } + } + async runPlay(operation) { + const current = () => this.current(operation, "playing") && this.wanted; + try { + while (this.seeking) { + await this.seeking.complete.promise; + if (!current()) + return; + } + if (!current()) + return; + this.host.paused = false; + await this.startAudio(); + if (!current()) { + if (!this.wanted || this.host.destroyed) + this.host.audio.pause(); + return; + } + this.host.video.start(this.host.audio); + publish(this.host.events, current, ["play", "playing"]); + } catch (error) { + if (!current()) + return; + this.wanted = false; + this.host.paused = true; + try { + this.stopEngines(); + } catch (failure) { + console.warn("MediaBunny play cleanup error:", failure); + } + throw error; + } finally { + if (this.playing === operation) + this.playing = null; + } + } + seek(time, resume) { + return this.position(async (current) => { + const audio = this.host.audio.seek(time); + const video = current() ? this.host.video.seek(time) : Promise.resolve(); + await Promise.all([audio, video]); + }, ["seeked"], false, resume); + } + replace(media, time) { + return this.position(async (current) => { + media.duration = await resolveDuration(media); + if (!current()) + return; + this.host.media = media; + await Promise.all([this.host.video.load(media), this.host.audio.load(media)]); + if (!current()) + return; + await Promise.all([this.host.video.seek(time), this.host.audio.seek(time)]); + if (current()) { + this.host.readyState = 4; + this.host.networkState = 1; + } + }, ["loadedmetadata", "durationchange", "progress", "loadeddata", "canplay", "canplaythrough", "seeked"], true); + } + position(work, events, pauseFirst, resume) { + if (this.host.destroyed) + return Promise.resolve(); + this.wanted = resume ?? (this.seeking ? this.wanted : !this.host.paused); + this.cancelPlay(); + const previous = this.seeking; + const operation = this.operation(); + this.seeking = operation; + previous?.complete.resolve(); + previous?.resolve(); + this.runPosition(operation, work, events, pauseFirst).then(operation.resolve, operation.reject); + return operation.promise; + } + async runPosition(operation, work, events, pauseFirst) { + const current = () => this.current(operation, "seeking"); + let resume = false; + try { + if (pauseFirst) + this.stop(); + if (!current()) + return; + this.host.ended = false; + this.host.seeking = true; + publish(this.host.events, current, ["seeking", "waiting"]); + if (!current()) + return; + if (!pauseFirst) + this.stop(); + if (!current()) + return; + await work(current); + if (!current()) + return; + this.host.seeking = false; + operation.complete.resolve(); + publish(this.host.events, current, events); + if (!current()) + return; + this.seeking = null; + resume = this.wanted; + } catch (error) { + if (!current()) + return; + this.host.seeking = false; + this.wanted = false; + this.cancelPlay(); + this.host.reportError(error); + throw error; + } finally { + operation.complete.resolve(); + if (this.seeking === operation) + this.seeking = null; + } + if (resume) + await this.play(); + } +} async function preflightRange(url, enabled, events, signal, isCurrent = () => true) { if (signal?.aborted || !isCurrent()) return false; @@ -24661,6 +24947,7 @@ class VideoEngine { } class MediaBunnyEngine { constructor({ canvas, ctx, events, option = {} }) { + __privateAdd(this, _playback); this.events = events; this.option = option; this.audio = new AudioEngine(events); @@ -24685,15 +24972,20 @@ class MediaBunnyEngine { this.media = null; this.loadSession = null; this.destroyed = false; - events.addEventListener?.("ended", () => { + __privateSet(this, _playback, new Playback(this)); + events.addEventListener("ended", () => { + if (this.destroyed) + return; this.ended = true; this.paused = true; + __privateGet(this, _playback).ended(); }); } async load(src) { if (this.destroyed) return; const id = ++this.loadSeq; + __privateGet(this, _playback).invalidate(); this.loadSession?.cancel(); if (id !== this.loadSeq || this.destroyed) return; @@ -24709,75 +25001,62 @@ class MediaBunnyEngine { this.readyState = 0; session.defer(() => this.events.emit("waiting")); session.defer(() => this.events.emit("loadstart")); - const loadTimeout = Number.isFinite(this.option.loadTimeout) ? this.option.loadTimeout : 0; + const timeout = Number.isFinite(this.option.loadTimeout) ? this.option.loadTimeout ?? 0 : 0; try { - await session.wait(this.performLoad(src, id, session), loadTimeout); - } catch (err) { + await session.wait(this.performLoad(src, id, session), timeout); + } catch (error) { if (id !== this.loadSeq) return; const failed = ++this.loadSeq; + __privateGet(this, _playback).invalidate(); session.cancel(); if (failed !== this.loadSeq || this.destroyed) return; this.disposeInput(); - this.error = { code: 4, message: err.message }; - this.networkState = 3; - this.events.emit("error"); + this.reportError(error); } } async performLoad(src, id, session = this.loadSession) { - if (!await this.video.preflight(src, session?.signal, () => id === this.loadSeq) || id !== this.loadSeq) + const current = () => !this.destroyed && id === this.loadSeq; + if (!session || !await this.video.preflight(src, session.signal, current) || !current()) return; const input = createInput(src); if (!input) { this.video.handleNoVideoTrack(); - this.audio.handleNoAudioTrack(); + if (current()) + this.audio.handleNoAudioTrack(); return; } session.own(input); const media = await selectPlaybackTracks(input, src); - if (id !== this.loadSeq) + if (!current()) return; + if (!media.videoTrack && !media.audioTrack) { + this.video.handleNoVideoTrack(); + this.video.duration = Number.NaN; + this.audio.duration = Number.NaN; + throw new Error("Input has no audio or video tracks."); + } this.input = input; this.media = media; - let videoMetadataLoaded = !media.videoTrack; - let audioMetadataLoaded = !media.audioTrack; - const checkMetadata = () => { - if (videoMetadataLoaded && audioMetadataLoaded) { - this.readyState = 1; - this.events.emit("loadedmetadata"); - this.events.emit("durationchange"); - this.events.emit("progress"); - } - }; + const metadata = metadataBarrier(() => { + this.readyState = 1; + publish(this.events, current, ["loadedmetadata", "durationchange", "progress"]); + }, current); try { - await Promise.all([ - this.video.load(media, () => { - if (id !== this.loadSeq) - return; - videoMetadataLoaded = true; - checkMetadata(); - }), - this.audio.load(media, () => { - if (id !== this.loadSeq) - return; - audioMetadataLoaded = true; - checkMetadata(); - }) - ]); - if (id !== this.loadSeq) + const video = this.video.load(media, metadata.video); + const audio = current() ? this.audio.load(media, metadata.audio) : Promise.resolve(); + await Promise.all([video, audio]); + if (!current()) return; this.readyState = 4; this.networkState = 1; - this.events.emit("loadeddata"); - this.events.emit("canplay"); - this.events.emit("canplaythrough"); - this.events.emit("progress"); - } catch (err) { - if (id !== this.loadSeq) + publish(this.events, current, ["loadeddata", "canplay", "canplaythrough", "progress"]); + } catch (error) { + if (!current()) return; - console.error("MediaBunny load error:", err); - throw err; + console.error("MediaBunny load error:", error); + throw error; } } createTimeout(ms) { @@ -24790,127 +25069,38 @@ class MediaBunnyEngine { this.input = null; this.media = null; } - async replaceTracks({ videoTrack, audioTrack, videoMode, audioMode }) { - if (!this.media) + async replaceTracks(tracks) { + if (!this.media || this.destroyed) return; - const nextMedia = { - ...this.media, - videoTrack, - audioTrack, - videoMode, - audioMode - }; - const shouldResume = !this.paused; - const currentTime = this.currentTime; - this.pause(); - this.ended = false; - this.seeking = true; - this.events.emit("seeking"); - this.events.emit("waiting"); - nextMedia.duration = await resolveDuration(nextMedia); - this.media = nextMedia; - await Promise.all([ - this.video.load(nextMedia), - this.audio.load(nextMedia) - ]); - await Promise.all([ - this.video.seek(currentTime), - this.audio.seek(currentTime) - ]); - this.readyState = 4; - this.networkState = 1; - this.seeking = false; - this.events.emit("loadedmetadata"); - this.events.emit("durationchange"); - this.events.emit("progress"); - this.events.emit("loadeddata"); - this.events.emit("canplay"); - this.events.emit("canplaythrough"); - this.events.emit("seeked"); - if (shouldResume) { - await this.play(); - } + return __privateGet(this, _playback).replace({ ...this.media, ...tracks }, this.currentTime); } async selectHlsQuality(value) { - if (!this.media?.isHls || !this.input) - return; - const videoTracks = await this.input.getVideoTracks(); - const videoTrack = value === "auto" ? await this.input.getPrimaryVideoTrack() : videoTracks.find((track) => track.id === value) ?? this.media.videoTrack; - if (!videoTrack) - return; - let audioTrack = this.media.audioTrack; - let audioMode = this.media.audioMode; - if (!audioTrack || !videoTrack.canBePairedWith(audioTrack)) { - audioTrack = await videoTrack.getPrimaryPairableAudioTrack(); - audioMode = "auto"; - } - await this.replaceTracks({ - videoTrack, - audioTrack, - videoMode: value === "auto" ? "auto" : "manual", - audioMode - }); + return selectQuality(this, value); } async selectHlsAudio(value) { - if (!this.media?.isHls || !this.input) - return; - const audioTracks = await this.input.getAudioTracks(); - const audioTrack = value === "auto" ? this.media.videoTrack ? await this.media.videoTrack.getPrimaryPairableAudioTrack() : await this.input.getPrimaryAudioTrack() : audioTracks.find((track) => track.id === value) ?? this.media.audioTrack; - if (!audioTrack) - return; - let videoTrack = this.media.videoTrack; - let videoMode = this.media.videoMode; - if (!videoTrack || !audioTrack.canBePairedWith(videoTrack)) { - videoTrack = await audioTrack.getPrimaryPairableVideoTrack(); - videoMode = "auto"; - } - await this.replaceTracks({ - videoTrack, - audioTrack, - videoMode, - audioMode: value === "auto" ? "auto" : "manual" - }); + return selectAudio(this, value); } - getHlsState() { - return getHlsState(this.media); + async getHlsState() { + const media = this.media; + if (this.destroyed) + return null; + try { + const state2 = await getHlsState(media); + return !this.destroyed && this.media === media ? state2 : null; + } catch (error) { + if (this.destroyed || this.media !== media) + return null; + throw error; + } } async play() { - if (!this.paused) - return; - if (this.ended) { - this.ended = false; - await this.seek(0); - } - this.paused = false; - await this.audio.play(); - this.video.start(this.audio); - this.events.emit("play"); - this.events.emit("playing"); + return __privateGet(this, _playback).play(); } pause() { - if (this.paused) - return; - this.paused = true; - this.audio.pause(); - this.video.stop(); - this.events.emit("pause"); + __privateGet(this, _playback).pause(); } async seek(time) { - const shouldResume = !this.paused; - this.ended = false; - this.seeking = true; - this.events.emit("seeking"); - this.events.emit("waiting"); - this.pause(); - await Promise.all([ - this.audio.seek(time), - this.video.seek(time) - ]); - this.seeking = false; - this.events.emit("seeked"); - if (shouldResume && !this.ended) { - await this.play(); - } + return __privateGet(this, _playback).seek(time); } setVolume(volume, muted) { this.audio.setVolume(volume, muted); @@ -24919,18 +25109,31 @@ class MediaBunnyEngine { this.audio.setPlaybackRate(rate); this.video.setPlaybackRate(rate); } + reportError(error) { + if (this.destroyed) + return; + const message = error && typeof error === "object" ? Reflect.get(error, "message") : void 0; + this.error = { code: 4, message: typeof message === "string" ? message : String(error) }; + this.networkState = 3; + this.events.emit("error"); + } destroy() { if (this.destroyed) return; this.destroyed = true; this.loadSeq++; - this.loadSession?.cancel(); - this.pause(); - this.disposeInput(); - this.audio.destroy(); - this.video.destroy(); + __privateGet(this, _playback).invalidate(); + const failures = []; + for (const release of [() => this.loadSession?.cancel(), () => this.pause(), () => this.disposeInput(), () => this.audio.destroy(), () => this.video.destroy()]) { + try { + release(); + } catch (error) { + failures.push(error); + } + } + if (failures.length) + throw failures[0]; } - // Getters get currentTime() { return this.audio.currentTime; } @@ -24944,6 +25147,7 @@ class MediaBunnyEngine { return this.video.height; } } +_playback = new WeakMap(); const states = /* @__PURE__ */ new WeakMap(); function state(owner) { let value = states.get(owner); @@ -25049,7 +25253,8 @@ class VideoShim { return this.engine.currentTime; } set currentTime(t) { - this.engine.seek(Number(t) || 0); + void Promise.resolve(this.engine.seek(Number(t) || 0)).catch(() => { + }); } get duration() { return this.engine.duration; diff --git a/packages/artplayer-proxy-mediabunny/src/AudioEngine.d.ts b/packages/artplayer-proxy-mediabunny/src/AudioEngine.d.ts new file mode 100644 index 000000000..5730564d7 --- /dev/null +++ b/packages/artplayer-proxy-mediabunny/src/AudioEngine.d.ts @@ -0,0 +1,6 @@ +import type { AudioPort } from './engine-ports' +import type EventTarget from './EventTarget' + +// Exact coordinator-facing port; implementation migration and decoder ownership are MB-06. +declare const AudioEngine: new (events: EventTarget) => AudioPort +export default AudioEngine diff --git a/packages/artplayer-proxy-mediabunny/src/MediaBunnyEngine.d.ts b/packages/artplayer-proxy-mediabunny/src/MediaBunnyEngine.d.ts deleted file mode 100644 index 171822c30..000000000 --- a/packages/artplayer-proxy-mediabunny/src/MediaBunnyEngine.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -import type { EngineOptions, EnginePort } from './engine-types' - -declare const MediaBunnyEngine: new (options: EngineOptions) => EnginePort -export default MediaBunnyEngine diff --git a/packages/artplayer-proxy-mediabunny/src/MediaBunnyEngine.js b/packages/artplayer-proxy-mediabunny/src/MediaBunnyEngine.js deleted file mode 100644 index ba8af946d..000000000 --- a/packages/artplayer-proxy-mediabunny/src/MediaBunnyEngine.js +++ /dev/null @@ -1,372 +0,0 @@ -/** - * Main MediaBunny Engine - * Coordinates audio and video playback - */ -import AudioEngine from './AudioEngine.js' -import { getHlsState } from './hls-state' -import { createInput } from './input' -import LoadSession from './load-session' -import { resolveDuration, selectPlaybackTracks } from './tracks' -import VideoEngine from './VideoEngine.js' - -export default class MediaBunnyEngine { - constructor({ canvas, ctx, events, option = {} }) { - this.events = events - this.option = option - - // Create audio and video engines - this.audio = new AudioEngine(events) - this.video = new VideoEngine({ - canvas, - ctx, - events, - timeupdateInterval: option.timeupdateInterval ?? 250, - avSyncTolerance: option.avSyncTolerance ?? 0.12, - dropLateFrames: option.dropLateFrames ?? false, - poster: option.poster ?? '', - preflightRange: option.preflightRange ?? false, - }) - - // Playback state - this.paused = true - this.ended = false - this.readyState = 0 - this.networkState = 0 - this.error = null - this.seeking = false - this.loadSeq = 0 - this.input = null - this.media = null - this.loadSession = null - this.destroyed = false - - // Listen to ended event - events.addEventListener?.('ended', () => { - this.ended = true - this.paused = true - }) - } - - async load(src) { - if (this.destroyed) - return - const id = ++this.loadSeq - this.loadSession?.cancel() - if (id !== this.loadSeq || this.destroyed) - return - this.pause() - if (id !== this.loadSeq || this.destroyed) - return - this.disposeInput() - const session = new LoadSession() - this.loadSession = session - this.ended = false - this.error = null - this.networkState = 2 // NETWORK_LOADING - this.readyState = 0 // HAVE_NOTHING - - session.defer(() => this.events.emit('waiting')) - session.defer(() => this.events.emit('loadstart')) - - const loadTimeout = Number.isFinite(this.option.loadTimeout) - ? this.option.loadTimeout - : 0 - - try { - await session.wait(this.performLoad(src, id, session), loadTimeout) - } - catch (err) { - if (id !== this.loadSeq) - return - - const failed = ++this.loadSeq - session.cancel() - if (failed !== this.loadSeq || this.destroyed) - return - this.disposeInput() - this.error = { code: 4, message: err.message } - this.networkState = 3 // NETWORK_NO_SOURCE - this.events.emit('error') - } - } - - async performLoad(src, id, session = this.loadSession) { - if (!(await this.video.preflight(src, session?.signal, () => id === this.loadSeq)) || id !== this.loadSeq) - return - - const input = createInput(src) - if (!input) { - this.video.handleNoVideoTrack() - this.audio.handleNoAudioTrack() - return - } - session.own(input) - const media = await selectPlaybackTracks(input, src) - if (id !== this.loadSeq) - return - this.input = input - this.media = media - - let videoMetadataLoaded = !media.videoTrack - let audioMetadataLoaded = !media.audioTrack - - const checkMetadata = () => { - if (videoMetadataLoaded && audioMetadataLoaded) { - this.readyState = 1 // HAVE_METADATA - this.events.emit('loadedmetadata') - this.events.emit('durationchange') - this.events.emit('progress') - } - } - - try { - await Promise.all([ - this.video.load(media, () => { - if (id !== this.loadSeq) - return - videoMetadataLoaded = true - checkMetadata() - }), - this.audio.load(media, () => { - if (id !== this.loadSeq) - return - audioMetadataLoaded = true - checkMetadata() - }), - ]) - - if (id !== this.loadSeq) - return - - this.readyState = 4 // HAVE_ENOUGH_DATA - this.networkState = 1 // NETWORK_IDLE - this.events.emit('loadeddata') - this.events.emit('canplay') - this.events.emit('canplaythrough') - this.events.emit('progress') - } - catch (err) { - if (id !== this.loadSeq) - return - - console.error('MediaBunny load error:', err) - throw err - } - } - - createTimeout(ms) { - return new Promise((_, reject) => { - setTimeout(() => reject(new Error('Load timeout')), ms) - }) - } - - disposeInput() { - this.loadSession?.disposeInput() - this.input = null - this.media = null - } - - async replaceTracks({ videoTrack, audioTrack, videoMode, audioMode }) { - if (!this.media) - return - - const nextMedia = { - ...this.media, - videoTrack, - audioTrack, - videoMode, - audioMode, - } - - const shouldResume = !this.paused - const currentTime = this.currentTime - - this.pause() - this.ended = false - this.seeking = true - this.events.emit('seeking') - this.events.emit('waiting') - - nextMedia.duration = await resolveDuration(nextMedia) - this.media = nextMedia - - await Promise.all([ - this.video.load(nextMedia), - this.audio.load(nextMedia), - ]) - - await Promise.all([ - this.video.seek(currentTime), - this.audio.seek(currentTime), - ]) - - this.readyState = 4 - this.networkState = 1 - this.seeking = false - this.events.emit('loadedmetadata') - this.events.emit('durationchange') - this.events.emit('progress') - this.events.emit('loadeddata') - this.events.emit('canplay') - this.events.emit('canplaythrough') - this.events.emit('seeked') - - if (shouldResume) { - await this.play() - } - } - - async selectHlsQuality(value) { - if (!this.media?.isHls || !this.input) - return - - const videoTracks = await this.input.getVideoTracks() - const videoTrack = value === 'auto' - ? await this.input.getPrimaryVideoTrack() - : videoTracks.find(track => track.id === value) ?? this.media.videoTrack - - if (!videoTrack) - return - - let audioTrack = this.media.audioTrack - let audioMode = this.media.audioMode - - if (!audioTrack || !videoTrack.canBePairedWith(audioTrack)) { - audioTrack = await videoTrack.getPrimaryPairableAudioTrack() - audioMode = 'auto' - } - - await this.replaceTracks({ - videoTrack, - audioTrack, - videoMode: value === 'auto' ? 'auto' : 'manual', - audioMode, - }) - } - - async selectHlsAudio(value) { - if (!this.media?.isHls || !this.input) - return - - const audioTracks = await this.input.getAudioTracks() - const audioTrack = value === 'auto' - ? this.media.videoTrack - ? await this.media.videoTrack.getPrimaryPairableAudioTrack() - : await this.input.getPrimaryAudioTrack() - : audioTracks.find(track => track.id === value) ?? this.media.audioTrack - - if (!audioTrack) - return - - let videoTrack = this.media.videoTrack - let videoMode = this.media.videoMode - - if (!videoTrack || !audioTrack.canBePairedWith(videoTrack)) { - videoTrack = await audioTrack.getPrimaryPairableVideoTrack() - videoMode = 'auto' - } - - await this.replaceTracks({ - videoTrack, - audioTrack, - videoMode, - audioMode: value === 'auto' ? 'auto' : 'manual', - }) - } - - getHlsState() { - return getHlsState(this.media) - } - - async play() { - if (!this.paused) - return - - if (this.ended) { - this.ended = false - await this.seek(0) - } - - this.paused = false - - await this.audio.play() - this.video.start(this.audio) - - this.events.emit('play') - this.events.emit('playing') - } - - pause() { - if (this.paused) - return - - this.paused = true - - this.audio.pause() - this.video.stop() - - this.events.emit('pause') - } - - async seek(time) { - const shouldResume = !this.paused - - this.ended = false - this.seeking = true - - this.events.emit('seeking') - this.events.emit('waiting') - - this.pause() - - await Promise.all([ - this.audio.seek(time), - this.video.seek(time), - ]) - - this.seeking = false - this.events.emit('seeked') - - if (shouldResume && !this.ended) { - await this.play() - } - } - - setVolume(volume, muted) { - this.audio.setVolume(volume, muted) - } - - setPlaybackRate(rate) { - this.audio.setPlaybackRate(rate) - this.video.setPlaybackRate(rate) - } - - destroy() { - if (this.destroyed) - return - this.destroyed = true - this.loadSeq++ - this.loadSession?.cancel() - this.pause() - this.disposeInput() - this.audio.destroy() - this.video.destroy() - } - - // Getters - 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 - } -} diff --git a/packages/artplayer-proxy-mediabunny/src/MediaBunnyEngine.ts b/packages/artplayer-proxy-mediabunny/src/MediaBunnyEngine.ts new file mode 100644 index 000000000..6a0785c9d --- /dev/null +++ b/packages/artplayer-proxy-mediabunny/src/MediaBunnyEngine.ts @@ -0,0 +1,255 @@ +import type { Input } from 'mediabunny' +import type { AudioPort, VideoPort } from './engine-ports' +import type { EngineOptions, EnginePort, ProxyOptions } from './engine-types' +import type EventTarget from './EventTarget' +import type { SelectedTracks } from './hls-selection' +import type { PlaybackMedia } from './media' +import AudioEngine from './AudioEngine.js' +import { selectAudio, selectQuality } from './hls-selection' +import { getHlsState } from './hls-state' +import { createInput } from './input' +import LoadSession from './load-session' +import Playback from './playback' +import { metadataBarrier, publish } from './readiness' +import { selectPlaybackTracks } from './tracks' +import VideoEngine from './VideoEngine.js' + +export default class MediaBunnyEngine implements EnginePort { + declare events: EventTarget + declare option: ProxyOptions + declare audio: AudioPort + declare video: VideoPort + declare paused: boolean + declare ended: boolean + declare readyState: number + declare networkState: number + declare error: { code: number, message: string } | null + declare seeking: boolean + declare loadSeq: number + declare input: Input | null + declare media: PlaybackMedia | null + declare loadSession: LoadSession | null + declare destroyed: boolean + #playback: Playback + + constructor({ canvas, ctx, events, option = {} }: EngineOptions) { + this.events = events + this.option = option + this.audio = new AudioEngine(events) + this.video = new VideoEngine({ + canvas, + ctx, + events, + timeupdateInterval: option.timeupdateInterval ?? 250, + avSyncTolerance: option.avSyncTolerance ?? 0.12, + dropLateFrames: option.dropLateFrames ?? false, + poster: option.poster ?? '', + preflightRange: option.preflightRange ?? false, + }) + this.paused = true + this.ended = false + this.readyState = 0 + this.networkState = 0 + this.error = null + this.seeking = false + this.loadSeq = 0 + this.input = null + this.media = null + this.loadSession = null + this.destroyed = false + this.#playback = new Playback(this) + events.addEventListener('ended', () => { + if (this.destroyed) + return + this.ended = true + this.paused = true + this.#playback.ended() + }) + } + + async load(src: unknown): Promise { + if (this.destroyed) + return + const id = ++this.loadSeq + this.#playback.invalidate() + this.loadSession?.cancel() + if (id !== this.loadSeq || this.destroyed) + return + this.pause() + if (id !== this.loadSeq || this.destroyed) + return + this.disposeInput() + const session = new LoadSession() + this.loadSession = session + this.ended = false + this.error = null + this.networkState = 2 + this.readyState = 0 + session.defer(() => this.events.emit('waiting')) + session.defer(() => this.events.emit('loadstart')) + const timeout = Number.isFinite(this.option.loadTimeout) ? this.option.loadTimeout ?? 0 : 0 + try { + await session.wait(this.performLoad(src, id, session), timeout) + } + catch (error) { + if (id !== this.loadSeq) + return + const failed = ++this.loadSeq + this.#playback.invalidate() + session.cancel() + if (failed !== this.loadSeq || this.destroyed) + return + this.disposeInput() + this.reportError(error) + } + } + + async performLoad(src: unknown, id: number, session = this.loadSession): Promise { + const current = () => !this.destroyed && id === this.loadSeq + if (!session || !(await this.video.preflight(src, session.signal, current)) || !current()) + return + const input = createInput(src) + if (!input) { + this.video.handleNoVideoTrack() + if (current()) + this.audio.handleNoAudioTrack() + return + } + session.own(input) + const media = await selectPlaybackTracks(input, src) + if (!current()) + return + if (!media.videoTrack && !media.audioTrack) { + this.video.handleNoVideoTrack() + this.video.duration = Number.NaN + this.audio.duration = Number.NaN + throw new Error('Input has no audio or video tracks.') + } + this.input = input + this.media = media + const metadata = metadataBarrier(() => { + this.readyState = 1 + publish(this.events, current, ['loadedmetadata', 'durationchange', 'progress']) + }, current) + try { + const video = this.video.load(media, metadata.video) + const audio = current() ? this.audio.load(media, metadata.audio) : Promise.resolve() + await Promise.all([video, audio]) + if (!current()) + return + this.readyState = 4 + this.networkState = 1 + publish(this.events, current, ['loadeddata', 'canplay', 'canplaythrough', 'progress']) + } + catch (error) { + if (!current()) + return + console.error('MediaBunny load error:', error) + throw error + } + } + + createTimeout(ms: number): Promise { + return new Promise((_, reject) => { + setTimeout(() => reject(new Error('Load timeout')), ms) + }) + } + + disposeInput(): void { + this.loadSession?.disposeInput() + this.input = null + this.media = null + } + + async replaceTracks(tracks: SelectedTracks): Promise { + if (!this.media || this.destroyed) + return + return this.#playback.replace({ ...this.media, ...tracks }, this.currentTime) + } + + async selectHlsQuality(value: unknown): Promise { + return selectQuality(this, value) + } + + async selectHlsAudio(value: unknown): Promise { + return selectAudio(this, value) + } + + async getHlsState() { + const media = this.media + if (this.destroyed) + return null + try { + const state = await getHlsState(media) + return !this.destroyed && this.media === media ? state : null + } + catch (error) { + if (this.destroyed || this.media !== media) + return null + throw error + } + } + + async play(): Promise { + return this.#playback.play() + } + + pause(): void { + this.#playback.pause() + } + + async seek(time: number): Promise { + return this.#playback.seek(time) + } + + setVolume(volume: number, muted: boolean): void { + this.audio.setVolume(volume, muted) + } + + setPlaybackRate(rate: number): void { + this.audio.setPlaybackRate(rate) + this.video.setPlaybackRate(rate) + } + + reportError(error: unknown): void { + if (this.destroyed) + return + const message: unknown = error && typeof error === 'object' ? Reflect.get(error, 'message') : undefined + this.error = { code: 4, message: typeof message === 'string' ? message : String(error) } + this.networkState = 3 + this.events.emit('error') + } + + destroy(): void { + if (this.destroyed) + return + this.destroyed = true + this.loadSeq++ + this.#playback.invalidate() + const failures: unknown[] = [] + for (const release of [() => this.loadSession?.cancel(), () => this.pause(), () => this.disposeInput(), () => this.audio.destroy(), () => this.video.destroy()]) { + try { + release() + } + catch (error) { failures.push(error) } + } + if (failures.length) + throw failures[0] + } + + get currentTime(): number { + return this.audio.currentTime + } + + get duration(): number { + return this.media?.duration ?? this.audio.duration ?? this.video.duration + } + + get videoWidth(): number { + return this.video.width + } + + get videoHeight(): number { + return this.video.height + } +} diff --git a/packages/artplayer-proxy-mediabunny/src/VideoEngine.d.ts b/packages/artplayer-proxy-mediabunny/src/VideoEngine.d.ts new file mode 100644 index 000000000..fab3cd13c --- /dev/null +++ b/packages/artplayer-proxy-mediabunny/src/VideoEngine.d.ts @@ -0,0 +1,5 @@ +import type { VideoOptions, VideoPort } from './engine-ports' + +// Exact coordinator-facing port; implementation migration and frame ownership are MB-05. +declare const VideoEngine: new (options: VideoOptions) => VideoPort +export default VideoEngine diff --git a/packages/artplayer-proxy-mediabunny/src/VideoShim.ts b/packages/artplayer-proxy-mediabunny/src/VideoShim.ts index b3a74a351..46d3215e5 100644 --- a/packages/artplayer-proxy-mediabunny/src/VideoShim.ts +++ b/packages/artplayer-proxy-mediabunny/src/VideoShim.ts @@ -87,7 +87,8 @@ export default class VideoShim { } set currentTime(t: unknown) { - this.engine.seek(Number(t) || 0) + // The coordinator reports active failures; the synchronous setter must observe rejection. + void Promise.resolve(this.engine.seek(Number(t) || 0)).catch(() => {}) } get duration() { diff --git a/packages/artplayer-proxy-mediabunny/src/engine-ports.ts b/packages/artplayer-proxy-mediabunny/src/engine-ports.ts new file mode 100644 index 000000000..49d036ff3 --- /dev/null +++ b/packages/artplayer-proxy-mediabunny/src/engine-ports.ts @@ -0,0 +1,60 @@ +import type { Input } from 'mediabunny' +import type { ProxyOptions } from './engine-types' +import type EventTarget from './EventTarget' +import type { PlaybackMedia } from './media' + +export interface AudioPort { + readonly currentTime: number + duration: number + paused: boolean + load: (media: PlaybackMedia, metadata?: () => void) => Promise + play: () => Promise + pause: () => void + seek: (time: number) => Promise + setVolume: (volume: number, muted: boolean) => void + setPlaybackRate: (rate: number) => void + handleNoAudioTrack: () => void + destroy: () => void +} + +export interface VideoPort { + width: number + height: number + duration: number + preflight: (source: unknown, signal?: AbortSignal, current?: () => boolean) => Promise + load: (media: PlaybackMedia, metadata?: () => void) => Promise + start: (clock: AudioPort) => void + stop: () => void + seek: (time: number) => Promise + setPlaybackRate: (rate: number) => void + handleNoVideoTrack: () => void + destroy: () => void +} + +export interface VideoOptions { + canvas: HTMLCanvasElement + ctx: CanvasRenderingContext2D | null + events: EventTarget + timeupdateInterval: number + avSyncTolerance: number + dropLateFrames: boolean + poster: string + preflightRange: boolean +} + +export interface PlaybackHost { + audio: AudioPort + video: VideoPort + events: EventTarget + readonly destroyed: boolean + readonly loadSeq: number + paused: boolean + ended: boolean + seeking: boolean + readyState: number + networkState: number + media: PlaybackMedia | null + input: Input | null + option: ProxyOptions + reportError: (error: unknown) => void +} diff --git a/packages/artplayer-proxy-mediabunny/src/engine-types.ts b/packages/artplayer-proxy-mediabunny/src/engine-types.ts index f594d51bb..5de42f8e5 100644 --- a/packages/artplayer-proxy-mediabunny/src/engine-types.ts +++ b/packages/artplayer-proxy-mediabunny/src/engine-types.ts @@ -19,7 +19,7 @@ export interface EngineOptions { option?: ProxyOptions } -// Transitional boundary for the coordinator; replaced by its strict implementation in MB-04. +// Stable coordinator-facing surface used by the public shim. export interface EnginePort { readonly currentTime: number readonly duration: number diff --git a/packages/artplayer-proxy-mediabunny/src/hls-selection.ts b/packages/artplayer-proxy-mediabunny/src/hls-selection.ts new file mode 100644 index 000000000..2f63e95ae --- /dev/null +++ b/packages/artplayer-proxy-mediabunny/src/hls-selection.ts @@ -0,0 +1,74 @@ +import type { Input } from 'mediabunny' +import type { PlaybackMedia } from './media' + +export type SelectedTracks = Pick + +interface SelectionHost { + input: Input | null + media: PlaybackMedia | null + destroyed: boolean + loadSeq: number + replaceTracks: (tracks: SelectedTracks) => Promise +} + +export async function selectQuality(host: SelectionHost, value: unknown): Promise { + const { input, media, loadSeq } = host + if (!media?.isHls || !input || host.destroyed) + return + const current = () => !host.destroyed && host.loadSeq === loadSeq && host.input === input && host.media === media + let selection: SelectedTracks + try { + const tracks = await input.getVideoTracks() + if (!current()) + return + const videoTrack = value === 'auto' ? await input.getPrimaryVideoTrack() : tracks.find(track => track.id === value) ?? media.videoTrack + if (!current() || !videoTrack) + return + let audioTrack = media.audioTrack + let audioMode = media.audioMode + if (!audioTrack || !videoTrack.canBePairedWith(audioTrack)) { + audioTrack = await videoTrack.getPrimaryPairableAudioTrack() + audioMode = 'auto' + } + selection = { videoTrack, audioTrack, videoMode: value === 'auto' ? 'auto' : 'manual', audioMode } + } + catch (error) { + if (!current()) + return + throw error + } + if (current()) + await host.replaceTracks(selection) +} + +export async function selectAudio(host: SelectionHost, value: unknown): Promise { + const { input, media, loadSeq } = host + if (!media?.isHls || !input || host.destroyed) + return + const current = () => !host.destroyed && host.loadSeq === loadSeq && host.input === input && host.media === media + let selection: SelectedTracks + try { + const tracks = await input.getAudioTracks() + if (!current()) + return + const audioTrack = value === 'auto' + ? media.videoTrack ? await media.videoTrack.getPrimaryPairableAudioTrack() : await input.getPrimaryAudioTrack() + : tracks.find(track => track.id === value) ?? media.audioTrack + if (!current() || !audioTrack) + return + let videoTrack = media.videoTrack + let videoMode = media.videoMode + if (!videoTrack || !audioTrack.canBePairedWith(videoTrack)) { + videoTrack = await audioTrack.getPrimaryPairableVideoTrack() + videoMode = 'auto' + } + selection = { videoTrack, audioTrack, videoMode, audioMode: value === 'auto' ? 'auto' : 'manual' } + } + catch (error) { + if (!current()) + return + throw error + } + if (current()) + await host.replaceTracks(selection) +} diff --git a/packages/artplayer-proxy-mediabunny/src/playback.ts b/packages/artplayer-proxy-mediabunny/src/playback.ts new file mode 100644 index 000000000..53f972ca2 --- /dev/null +++ b/packages/artplayer-proxy-mediabunny/src/playback.ts @@ -0,0 +1,240 @@ +import type { PlaybackHost } from './engine-ports' +import type { PlaybackMedia } from './media' +import { publish } from './readiness' +import { resolveDuration } from './tracks' + +interface Completion { + promise: Promise + resolve: () => void + reject: (error: unknown) => void +} + +interface Operation extends Completion { + source: number + complete: Completion +} + +function completion(): Completion { + let resolve!: () => void + let reject!: (error: unknown) => void + const promise = new Promise((yes, no) => { + resolve = yes + reject = no + }) + return { promise, resolve, reject } +} + +export default class Playback { + private wanted = false + private playing: Operation | null = null + private seeking: Operation | null = null + private audioStart: Promise | null = null + + constructor(private host: PlaybackHost) {} + + private operation(): Operation { + return { ...completion(), source: this.host.loadSeq, complete: completion() } + } + + private current(operation: Operation, kind: 'playing' | 'seeking'): boolean { + return !this.host.destroyed && operation.source === this.host.loadSeq && this[kind] === operation + } + + private cancelPlay(): void { + const previous = this.playing + this.playing = null + previous?.resolve() + } + + invalidate(): void { + this.cancelPlay() + this.wanted = false + const previous = this.seeking + this.seeking = null + previous?.complete.resolve() + previous?.resolve() + this.host.seeking = false + } + + ended(): void { + this.wanted = false + this.cancelPlay() + } + + private stop(): void { + if (this.host.paused) + return + this.host.paused = true + this.stopEngines() + this.host.events.emit('pause') + } + + private stopEngines(): void { + const failures: unknown[] = [] + for (const stop of [() => this.host.audio.pause(), () => this.host.video.stop()]) { + try { + stop() + } + catch (error) { failures.push(error) } + } + if (failures.length) + throw failures[0] + } + + pause(): void { + this.wanted = false + this.cancelPlay() + this.stop() + } + + play(): Promise { + if (this.host.destroyed) + return Promise.resolve() + this.wanted = true + if (this.playing) + return this.playing.promise + if (this.host.ended) + return this.seek(0, true) + if (!this.host.paused && !this.seeking) + return Promise.resolve() + const operation = this.operation() + this.playing = operation + this.runPlay(operation).then(operation.resolve, operation.reject) + return operation.promise + } + + private async startAudio(): Promise { + if (!this.audioStart) + this.audioStart = this.host.audio.play() + const pending = this.audioStart + try { + await pending + } + finally { + if (this.audioStart === pending) + this.audioStart = null + } + } + + private async runPlay(operation: Operation): Promise { + const current = () => this.current(operation, 'playing') && this.wanted + try { + while (this.seeking) { + await this.seeking.complete.promise + if (!current()) + return + } + if (!current()) + return + this.host.paused = false + await this.startAudio() + if (!current()) { + if (!this.wanted || this.host.destroyed) + this.host.audio.pause() + return + } + this.host.video.start(this.host.audio) + publish(this.host.events, current, ['play', 'playing']) + } + catch (error) { + if (!current()) + return + this.wanted = false + this.host.paused = true + try { + this.stopEngines() + } + catch (failure) { console.warn('MediaBunny play cleanup error:', failure) } + throw error + } + finally { + if (this.playing === operation) + this.playing = null + } + } + + seek(time: number, resume?: boolean): Promise { + return this.position(async (current) => { + const audio = this.host.audio.seek(time) + const video = current() ? this.host.video.seek(time) : Promise.resolve() + await Promise.all([audio, video]) + }, ['seeked'], false, resume) + } + + replace(media: PlaybackMedia, time: number): Promise { + return this.position(async (current) => { + media.duration = await resolveDuration(media) + if (!current()) + return + this.host.media = media + await Promise.all([this.host.video.load(media), this.host.audio.load(media)]) + if (!current()) + return + await Promise.all([this.host.video.seek(time), this.host.audio.seek(time)]) + if (current()) { + this.host.readyState = 4 + this.host.networkState = 1 + } + }, ['loadedmetadata', 'durationchange', 'progress', 'loadeddata', 'canplay', 'canplaythrough', 'seeked'], true) + } + + private position(work: (current: () => boolean) => Promise, events: readonly string[], pauseFirst: boolean, resume?: boolean): Promise { + if (this.host.destroyed) + return Promise.resolve() + this.wanted = resume ?? (this.seeking ? this.wanted : !this.host.paused) + this.cancelPlay() + const previous = this.seeking + const operation = this.operation() + this.seeking = operation + previous?.complete.resolve() + previous?.resolve() + this.runPosition(operation, work, events, pauseFirst).then(operation.resolve, operation.reject) + return operation.promise + } + + private async runPosition(operation: Operation, work: (current: () => boolean) => Promise, events: readonly string[], pauseFirst: boolean): Promise { + const current = () => this.current(operation, 'seeking') + let resume = false + try { + if (pauseFirst) + this.stop() + if (!current()) + return + this.host.ended = false + this.host.seeking = true + publish(this.host.events, current, ['seeking', 'waiting']) + if (!current()) + return + if (!pauseFirst) + this.stop() + if (!current()) + return + await work(current) + if (!current()) + return + this.host.seeking = false + operation.complete.resolve() + publish(this.host.events, current, events) + if (!current()) + return + this.seeking = null + resume = this.wanted + } + catch (error) { + if (!current()) + return + this.host.seeking = false + this.wanted = false + this.cancelPlay() + this.host.reportError(error) + throw error + } + finally { + operation.complete.resolve() + if (this.seeking === operation) + this.seeking = null + } + if (resume) + await this.play() + } +} diff --git a/packages/artplayer-proxy-mediabunny/src/readiness.ts b/packages/artplayer-proxy-mediabunny/src/readiness.ts new file mode 100644 index 000000000..c092da643 --- /dev/null +++ b/packages/artplayer-proxy-mediabunny/src/readiness.ts @@ -0,0 +1,27 @@ +import type EventTarget from './EventTarget' + +export function publish(events: EventTarget, current: () => boolean, names: readonly string[]): void { + for (const name of names) { + if (!current()) + return + events.emit(name) + } +} + +export function metadataBarrier(ready: () => void, current: () => boolean) { + let video = false + let audio = false + let published = false + function complete(part: 'audio' | 'video'): void { + if (!current() || published) + return + if (part === 'video') + video = true + else audio = true + if (video && audio) { + published = true + ready() + } + } + return { video: () => complete('video'), audio: () => complete('audio') } +} diff --git a/refactor/baselines/mb-coordination-validation.json b/refactor/baselines/mb-coordination-validation.json new file mode 100644 index 000000000..4f1b5a6e7 --- /dev/null +++ b/refactor/baselines/mb-coordination-validation.json @@ -0,0 +1,728 @@ +{ + "task": "PKG-MB-04", + "status": "done", + "parentCommit": "9af253a5a9db9c10062f7552f4e084582d5f6e94", + "sourceSha256LF": { + "packages/artplayer-proxy-mediabunny/src/AudioEngine.d.ts": "2d59216f234173253b87e2b3ab8710efd25666f6cadbb2d1052b5c1cb829635a", + "packages/artplayer-proxy-mediabunny/src/AudioEngine.js": "910d6831372e4895d55dec78010f281a199bc88f99735630a5a3b621f192ac35", + "packages/artplayer-proxy-mediabunny/src/engine-ports.ts": "43a5b9277f2b52a537c522f1cf2a2c92ce4cfb1d2fb6c91e73519371a92940a2", + "packages/artplayer-proxy-mediabunny/src/engine-types.ts": "857a61f1fa3531bd737626658981eaab1b83eb369266fb45528676b9f57a293a", + "packages/artplayer-proxy-mediabunny/src/EventTarget.ts": "4cea57e59b0a1118744a55b0a87c1df28cb0d69c26c50f9275039fe7540c9720", + "packages/artplayer-proxy-mediabunny/src/hls-selection.ts": "a8632c0ea7d0c59434de005eee81bbf8d1dea8ae73c690673b603e5d6fa3cfd6", + "packages/artplayer-proxy-mediabunny/src/hls-state.ts": "ff9ffd742f9763349df1f50eac6b6bd488a80d05aaab8ca198f387f0d17d5e25", + "packages/artplayer-proxy-mediabunny/src/index.js": "4e1be8937908ff6e6ef8a4e863e22b4468312cf31d66ac299322e475757773bb", + "packages/artplayer-proxy-mediabunny/src/input.ts": "d25b1c4ee4aee358c86fd8c554b8b36bfc23fdbd3c27fa21d2cd7e812c98bf9c", + "packages/artplayer-proxy-mediabunny/src/load-session.ts": "560fbd5935fc787bde5f413fcaa41b8829506179c5328ce3cb51e734bbba8cec", + "packages/artplayer-proxy-mediabunny/src/m3u8.js": "4639f09e0c743dc2b24078f48ca1e58eaaedaa3f5e6b863583cbd4bc4a7d3142", + "packages/artplayer-proxy-mediabunny/src/media.ts": "e745cd8e750e05d0fcfa4bc588f7eb5a5576f3be20f5e67b65b704f57d539ae9", + "packages/artplayer-proxy-mediabunny/src/MediaBunnyEngine.ts": "d13bdd700399b57a4ff90a0fa9bdedf10206609e994ff07326a37c6838be135c", + "packages/artplayer-proxy-mediabunny/src/playback.ts": "0512f6a1b253d754b6644266327e368e0e18cce1cf9a3af62b6747ed55d691f7", + "packages/artplayer-proxy-mediabunny/src/preflight.ts": "d296234312f23b97a1e0a054f1d7dbbc988d5240c5fd5089c36df1677c7b7348", + "packages/artplayer-proxy-mediabunny/src/readiness.ts": "9aa24b5e994006b45bda9eafad602785c3e0e334cef54ff45a4939e386c4aceb", + "packages/artplayer-proxy-mediabunny/src/shim-frames.ts": "172b222f997a711c2cc7741f189f05127a4ac5099c1cbe2729e903b36b4ce24a", + "packages/artplayer-proxy-mediabunny/src/shim-values.ts": "a93ee17e87cc7db24f4b02d866af8af206d3007d01def446906fb769c20de17d", + "packages/artplayer-proxy-mediabunny/src/tracks.ts": "6da68530c1fc7105ab17ed742d87d93e84447e822e84386591f9c3e6d0bec733", + "packages/artplayer-proxy-mediabunny/src/VideoEngine.d.ts": "172fd4d30fa98a3eaa540ac8e5b653ae321c4ad8f376f3954550e2298bff5a9d", + "packages/artplayer-proxy-mediabunny/src/VideoEngine.js": "5ac862b0fd9c196dc6656f8908a214c1b3a0a53a7e85ff845d9068888831986b", + "packages/artplayer-proxy-mediabunny/src/VideoShim.ts": "1fef3028a3937182c31503129655efdb88118ea0f6d3be96e9be99dcbcc5fdc7", + "packages/artplayer-proxy-mediabunny/dist/artplayer-proxy-mediabunny.js": "01b88c915804e1c42b90c8c37aa948029472c7f47f6eb3a266629ed945be9fb1", + "packages/artplayer-proxy-mediabunny/dist/artplayer-proxy-mediabunny.legacy.js": "7c39173fdc56ce9089542191f8e0d731d825967244828e4a358d951421889cfc", + "packages/artplayer-proxy-mediabunny/dist/artplayer-proxy-mediabunny.mjs": "aed179b85002f5ddab3f26a02b20ad5e0fae203bc865cb0a241a003aa22c8a9e", + "packages/artplayer-proxy-mediabunny/ARCHITECTURE.md": "9bd639cab075ac3e5c333b509c016614ad64e14fd58b3f308e0656e325662a43", + "package.json": "f91ece4140c07c5bcec06556d088cd98b0d368471df7b129999e3239d5960334", + "test/mediabunny-coordination.test.js": "1ce97e02492c0b85e041f3bf33b75ec9915af160d7fd7550bef84408e034cba9", + "test/browser/mediabunny-inputs.spec.js": "561fbb9316691210c239831aa9f87ec5f2b6adaa5a7cde7b5830b721bd9d56de", + "test/browser/mediabunny.spec.js": "59491aa2007e1816fb8561f3feaf4d149c74667994ed2632ea3d37cf10891364" + }, + "node": { + "total": 108, + "coordinator": 40, + "sameCoordinatorAssertionsOnPreviousMain": { + "passed": 8, + "failed": 32 + }, + "main": 72, + "legacy": 72, + "artifactScope": "Each 72-case command includes 68 candidate assertions and four frozen normal-event controls." + }, + "browser": { + "total": 39, + "outcomes": { + "native-input-playback-and-seek": 10, + "trackless-rejected-before-decoder-setup": 3, + "unsupported-capability-control": 5, + "native-pending-stream-cancellation": 9, + "native-synthetic-raf": 9, + "native-mp4-playback-observed": 2, + "verified-unsupported-capability-control": 1 + }, + "records": [ + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "01b88c915804e1c42b90c8c37aa948029472c7f47f6eb3a266629ed945be9fb1", + "input": "webm", + "outcome": "native-input-playback-and-seek", + "cleanup": { + "audioContext": "closed", + "pendingFrames": 0, + "streamCancelled": false + }, + "reentrantPlay": { + "paused": true, + "events": [ + "video:play", + "video:pause" + ] + }, + "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": "01b88c915804e1c42b90c8c37aa948029472c7f47f6eb3a266629ed945be9fb1", + "input": "blob", + "outcome": "native-input-playback-and-seek", + "cleanup": { + "audioContext": "closed", + "pendingFrames": 0, + "streamCancelled": false + }, + "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": "01b88c915804e1c42b90c8c37aa948029472c7f47f6eb3a266629ed945be9fb1", + "input": "stream", + "outcome": "native-input-playback-and-seek", + "cleanup": { + "audioContext": "closed", + "pendingFrames": 0, + "streamCancelled": true + }, + "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": "01b88c915804e1c42b90c8c37aa948029472c7f47f6eb3a266629ed945be9fb1", + "input": "audio", + "outcome": "native-input-playback-and-seek", + "cleanup": { + "audioContext": "closed", + "pendingFrames": 0, + "streamCancelled": false + }, + "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": "01b88c915804e1c42b90c8c37aa948029472c7f47f6eb3a266629ed945be9fb1", + "input": "hls", + "outcome": "native-input-playback-and-seek", + "cleanup": { + "audioContext": "closed", + "pendingFrames": 0, + "streamCancelled": false + }, + "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": "01b88c915804e1c42b90c8c37aa948029472c7f47f6eb3a266629ed945be9fb1", + "input": "trackless", + "outcome": "trackless-rejected-before-decoder-setup", + "cleanup": { + "audioContext": "not-created", + "pendingFrames": 0, + "streamCancelled": false + }, + "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": "01b88c915804e1c42b90c8c37aa948029472c7f47f6eb3a266629ed945be9fb1", + "input": "webm", + "outcome": "native-input-playback-and-seek", + "cleanup": { + "audioContext": "closed", + "pendingFrames": 0, + "streamCancelled": false + }, + "reentrantPlay": { + "paused": true, + "events": [ + "video:play", + "video:pause" + ] + }, + "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": "01b88c915804e1c42b90c8c37aa948029472c7f47f6eb3a266629ed945be9fb1", + "input": "blob", + "outcome": "native-input-playback-and-seek", + "cleanup": { + "audioContext": "closed", + "pendingFrames": 0, + "streamCancelled": false + }, + "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": "01b88c915804e1c42b90c8c37aa948029472c7f47f6eb3a266629ed945be9fb1", + "input": "stream", + "outcome": "native-input-playback-and-seek", + "cleanup": { + "audioContext": "closed", + "pendingFrames": 0, + "streamCancelled": true + }, + "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": "01b88c915804e1c42b90c8c37aa948029472c7f47f6eb3a266629ed945be9fb1", + "input": "audio", + "outcome": "native-input-playback-and-seek", + "cleanup": { + "audioContext": "closed", + "pendingFrames": 0, + "streamCancelled": false + }, + "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": "01b88c915804e1c42b90c8c37aa948029472c7f47f6eb3a266629ed945be9fb1", + "input": "hls", + "outcome": "native-input-playback-and-seek", + "cleanup": { + "audioContext": "closed", + "pendingFrames": 0, + "streamCancelled": false + }, + "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": "01b88c915804e1c42b90c8c37aa948029472c7f47f6eb3a266629ed945be9fb1", + "input": "trackless", + "outcome": "trackless-rejected-before-decoder-setup", + "cleanup": { + "audioContext": "not-created", + "pendingFrames": 0, + "streamCancelled": false + }, + "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": "01b88c915804e1c42b90c8c37aa948029472c7f47f6eb3a266629ed945be9fb1", + "input": "webm", + "outcome": "unsupported-capability-control", + "cleanup": { + "audioContext": "not-created", + "pendingFrames": 0, + "streamCancelled": false + }, + "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": "01b88c915804e1c42b90c8c37aa948029472c7f47f6eb3a266629ed945be9fb1", + "input": "blob", + "outcome": "unsupported-capability-control", + "cleanup": { + "audioContext": "not-created", + "pendingFrames": 0, + "streamCancelled": false + }, + "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": "01b88c915804e1c42b90c8c37aa948029472c7f47f6eb3a266629ed945be9fb1", + "input": "stream", + "outcome": "unsupported-capability-control", + "cleanup": { + "audioContext": "not-created", + "pendingFrames": 0, + "streamCancelled": true + }, + "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": "01b88c915804e1c42b90c8c37aa948029472c7f47f6eb3a266629ed945be9fb1", + "input": "audio", + "outcome": "unsupported-capability-control", + "cleanup": { + "audioContext": "not-created", + "pendingFrames": 0, + "streamCancelled": false + }, + "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": "01b88c915804e1c42b90c8c37aa948029472c7f47f6eb3a266629ed945be9fb1", + "input": "hls", + "outcome": "unsupported-capability-control", + "cleanup": { + "audioContext": "not-created", + "pendingFrames": 0, + "streamCancelled": false + }, + "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": "01b88c915804e1c42b90c8c37aa948029472c7f47f6eb3a266629ed945be9fb1", + "input": "trackless", + "outcome": "trackless-rejected-before-decoder-setup", + "cleanup": { + "audioContext": "not-created", + "pendingFrames": 0, + "streamCancelled": false + }, + "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": "01b88c915804e1c42b90c8c37aa948029472c7f47f6eb3a266629ed945be9fb1", + "ending": "destroy", + "outcome": "native-pending-stream-cancellation", + "cancellations": [ + "old" + ], + "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": "01b88c915804e1c42b90c8c37aa948029472c7f47f6eb3a266629ed945be9fb1", + "ending": "source", + "outcome": "native-pending-stream-cancellation", + "cancellations": [ + "old", + "new" + ], + "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": "01b88c915804e1c42b90c8c37aa948029472c7f47f6eb3a266629ed945be9fb1", + "ending": "timeout", + "outcome": "native-pending-stream-cancellation", + "cancellations": [ + "old" + ], + "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": "01b88c915804e1c42b90c8c37aa948029472c7f47f6eb3a266629ed945be9fb1", + "ending": "destroy", + "outcome": "native-pending-stream-cancellation", + "cancellations": [ + "old" + ], + "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": "01b88c915804e1c42b90c8c37aa948029472c7f47f6eb3a266629ed945be9fb1", + "ending": "source", + "outcome": "native-pending-stream-cancellation", + "cancellations": [ + "old", + "new" + ], + "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": "01b88c915804e1c42b90c8c37aa948029472c7f47f6eb3a266629ed945be9fb1", + "ending": "timeout", + "outcome": "native-pending-stream-cancellation", + "cancellations": [ + "old" + ], + "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": "01b88c915804e1c42b90c8c37aa948029472c7f47f6eb3a266629ed945be9fb1", + "ending": "destroy", + "outcome": "native-pending-stream-cancellation", + "cancellations": [ + "old" + ], + "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": "01b88c915804e1c42b90c8c37aa948029472c7f47f6eb3a266629ed945be9fb1", + "ending": "source", + "outcome": "native-pending-stream-cancellation", + "cancellations": [ + "old", + "new" + ], + "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": "01b88c915804e1c42b90c8c37aa948029472c7f47f6eb3a266629ed945be9fb1", + "ending": "timeout", + "outcome": "native-pending-stream-cancellation", + "cancellations": [ + "old" + ], + "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": "01b88c915804e1c42b90c8c37aa948029472c7f47f6eb3a266629ed945be9fb1", + "scenario": "callback", + "outcome": "native-synthetic-raf", + "result": { + "idType": "number", + "calls": [ + { + "owner": "first", + "time": "number", + "mediaTime": 0, + "presentedFrames": 0 + } + ], + "listeners": 0 + }, + "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": "01b88c915804e1c42b90c8c37aa948029472c7f47f6eb3a266629ed945be9fb1", + "scenario": "destroy", + "outcome": "native-synthetic-raf", + "result": { + "idType": "number", + "calls": [], + "listeners": 0 + }, + "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": "01b88c915804e1c42b90c8c37aa948029472c7f47f6eb3a266629ed945be9fb1", + "scenario": "independent", + "outcome": "native-synthetic-raf", + "result": { + "idType": "number", + "calls": [ + { + "owner": "second" + } + ], + "listeners": 0 + }, + "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": "01b88c915804e1c42b90c8c37aa948029472c7f47f6eb3a266629ed945be9fb1", + "scenario": "callback", + "outcome": "native-synthetic-raf", + "result": { + "idType": "number", + "calls": [ + { + "owner": "first", + "time": "number", + "mediaTime": 0, + "presentedFrames": 0 + } + ], + "listeners": 0 + }, + "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": "01b88c915804e1c42b90c8c37aa948029472c7f47f6eb3a266629ed945be9fb1", + "scenario": "destroy", + "outcome": "native-synthetic-raf", + "result": { + "idType": "number", + "calls": [], + "listeners": 0 + }, + "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": "01b88c915804e1c42b90c8c37aa948029472c7f47f6eb3a266629ed945be9fb1", + "scenario": "independent", + "outcome": "native-synthetic-raf", + "result": { + "idType": "number", + "calls": [ + { + "owner": "second" + } + ], + "listeners": 0 + }, + "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": "01b88c915804e1c42b90c8c37aa948029472c7f47f6eb3a266629ed945be9fb1", + "scenario": "callback", + "outcome": "native-synthetic-raf", + "result": { + "idType": "number", + "calls": [ + { + "owner": "first", + "time": "number", + "mediaTime": 0, + "presentedFrames": 0 + } + ], + "listeners": 0 + }, + "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": "01b88c915804e1c42b90c8c37aa948029472c7f47f6eb3a266629ed945be9fb1", + "scenario": "destroy", + "outcome": "native-synthetic-raf", + "result": { + "idType": "number", + "calls": [], + "listeners": 0 + }, + "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": "01b88c915804e1c42b90c8c37aa948029472c7f47f6eb3a266629ed945be9fb1", + "scenario": "independent", + "outcome": "native-synthetic-raf", + "result": { + "idType": "number", + "calls": [ + { + "owner": "second" + } + ], + "listeners": 0 + }, + "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": "01b88c915804e1c42b90c8c37aa948029472c7f47f6eb3a266629ed945be9fb1", + "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": "01b88c915804e1c42b90c8c37aa948029472c7f47f6eb3a266629ed945be9fb1", + "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": "01b88c915804e1c42b90c8c37aa948029472c7f47f6eb3a266629ed945be9fb1", + "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/mb04-coordination-results/report.json", + "reportSha256": "17dbd77680e414f0b27e94e278b24d46cd6cde443ed1bb96dcc2f3d285a6557f", + "results": "refactor/.cache/mb04-coordination-results/results" + }, + "checks": [ + { + "command": "yarn test:mediabunny", + "result": "pass", + "tests": 108 + }, + { + "command": "main/legacy shim, load and coordinator tests", + "result": "pass", + "eachRun": 72 + }, + { + "command": "same 40 coordinator assertions on adba8a3d main", + "result": "expected historical failures", + "passed": 8, + "failed": 32 + }, + { + "command": "package strict tsc and focused eslint --no-fix", + "result": "pass", + "productionModules": 16, + "temporaryDecoderDeclarationBridges": 2 + }, + { + "command": "yarn build artplayer-proxy-mediabunny", + "result": "pass", + "formats": [ + "main", + "legacy", + "esm" + ] + }, + { + "command": "four browser specs with built main", + "result": "pass", + "tests": 39 + }, + { + "command": "yarn ci:check", + "result": "pass", + "tests": { + "unit": 1114, + "engineering": 14, + "baseline": 141, + "mainTotal": 1269, + "repeatedContractExecutions": 44 + }, + "strictProductionTypeScriptFiles": 306, + "log": "refactor/.cache/mb04-coordination-ci.log" + }, + { + "command": "built ESM default export and source function name", + "result": "pass", + "log": "refactor/.cache/mb04-coordination-esm.log" + } + ], + "limitations": [ + "AudioEngine and VideoEngine remain JS behind explicit temporary declarations; their late internal work is MB-05/06.", + "Six Windows WebKit capability controls are not successful playback.", + "Trackless false readiness is corrected; existing-track unsupported codec behavior remains a capability/decoder task.", + "Synthetic RAF is not decoded frame accuracy; native sampled frames and short clocks are not long-run AV sync.", + "HLS query source ownership is guarded; full concurrent selection/UI topology remains MB-07.", + "No npm release or next-major approval is implied." + ] +} diff --git a/refactor/changes/2026-09-12-PKG-MB-04-coordination.md b/refactor/changes/2026-09-12-PKG-MB-04-coordination.md new file mode 100644 index 000000000..ee78b1afa --- /dev/null +++ b/refactor/changes/2026-09-12-PKG-MB-04-coordination.md @@ -0,0 +1,56 @@ +# PKG-MB-04:VideoShim、事件与主协调器 + +任务通过完整CI后标记done,并立即以专用本地提交交付。前置shim检查点为9af253a5;本轮将 +MediaBunnyEngine.js实际迁移为严格TS,删除其临时声明桥。包内现在16个生产TS模块, +AudioEngine/VideoEngine两个显式临时声明桥不计作实现迁移,分别留给MB-06/05。 +文件职责、状态归属、错误传播和继续维护入口见包内ARCHITECTURE.md。 + +## 行为修复与兼容性 + +- playback.ts独立管理播放意图和操作完成信号;pause能够阻止pending play或seek恢复, + 新操作使旧结果失效。取消可先结束公开Promise,底层晚结果仍被观察。 +- seek完成信号先于可选恢复播放,避免play等待seek而seek又等待play的死锁。 + play-pause-play共享尚未结束的audio resume,只有当前操作启动video和发送play/playing。 +- 每次就绪/播放事件前重新检查归属,允许用户在回调中同步切源、销毁或改变播放状态。 + 正常play/pause、seek/resume和HLS replacement事件顺序由对照测试保持。 +- 两个metadata参与者均完成才发布一次metadata;无轨道容器提前报code 4,信息为 + `Input has no audio or video tracks.`,不再错误地readyState 4。有效媒体行为保持。 +- 活动play失败保留原始Promise拒绝并恢复paused;活动seek失败报告一次error并拒绝。 + currentTime同步setter观察无法返回的拒绝,直接调用engine.seek仍能捕获错误。 +- HLS旧source查询失败不污染新source,当前查询失败继续拒绝;replacement改变media对象 + 后的活动错误也不能被误认为旧查询并吞掉。 +- destroy尽力执行所有input/audio/video释放步骤,之后保留首个异常;shim仍以finally + 清理事件和synthetic RAF。事件安静不等于底层解码器晚操作已完全停止。 + +工厂签名、公开声明、canvas描述符和同步/Promise接口保持。正常事件顺序、方法转发及 +描述符对照继续纳入验证。非正常行为差异是以上明确的竞态/错误修复,不宣称逐字节行为不变。 +旧createTimeout帮助方法保持原样,受管理的load路径不使用它;不要称所有手动调用的内部 +帮助方法也都具备自动取消。 + +## 验证 + +新增40项协调器测试,使用实际构建代理、受控异步音视频操作和实际SDK解析输入。 +同一断言对adba8a3d冻结main为8通过/32失败,候选全部通过。包专项108项通过。 +main与legacy各72项通过,其中68候选产物断言、4冻结正常事件对照。三格式构建通过。 + +初轮main产物测试有一条断言把新source合法waiting/loadstart误当作旧replacement事件。 +已缩小到旧seek/readiness结果并保留完整禁止列表,重新运行main/legacy均72通过;未修改 +生产代码来消除新来源合法事件。历史同断言仍32失败,修复回归证据没有被放宽掉。 + +浏览器报告及整个results归档后记录到mb-coordination-validation.json。39项候选检查区分 +12真实播放、9原生Stream取消、9synthetic RAF、6Windows WebKit能力对照及3无轨道拒绝。 +WebM在Chromium/Firefox另验证真实播放的play回调内pause后不会再发playing。 +此断言附属于现有播放用例,不增加测试数量。长播放、听觉输出和AV同步仍为MB-09。 + +## 后续边界 + +MB-05/06继续实际视频帧、解码器迭代器和Web Audio调度迁移;两处声明桥必须移除。 +MB-07继续HLS控件拓扑与并发选轨;MB-08完整公开类型/工厂兼容矩阵;MB-09/10完成组合、 +长播放、demo、真实安装包与许可通知。MB-LIFE-01/MB-READY-01保持open并更新已修复范围, +既有轨道但不支持codec的路径仍需要解码器验证。此任务不构成npm发布验收。 + +最终完整CI1269项(1114单元+14工程+141基线)通过,另44重复契约;306生产TS。 +所有记录的源码/测试/产物及报告哈希已核验,三格式docs/compiled与dist一致。ESM默认工厂 +及实际源码名称artplayerProxyMediabunny保持;首次临时检查误写大小写,已按实际入口修正。 +回退本任务可revert专用提交;旧shim检查点9af253a5与更早adba8a3d基线仍可对照。 +未推送、打tag或发布;下一项PKG-MB-05处理视频迭代器、晚帧与seek释放。 diff --git a/refactor/mb-validation.md b/refactor/mb-validation.md index b4d015ead..f998abfa0 100644 --- a/refactor/mb-validation.md +++ b/refactor/mb-validation.md @@ -45,3 +45,12 @@ MB-03实施将input分离为六个strict TS模块,接入加载session、Range Chrome连接不可用时可使用内置浏览器;CLI自动化也按现有Playwright三引擎流程执行。 保留report.json及整个results目录。受控输入不能替代真实解码,iframe不能替代原生Document PiP。 VAST脚本VPN豁免不适用于本包。 + +## MB-04 coordinator implementation + +VideoShim/EventTarget与主协调器已拆为严格TS模块,详情见 +[协调器变更](changes/2026-09-12-PKG-MB-04-coordination.md)及 +[验证记录](baselines/mb-coordination-validation.json)。包专项命令已包含新的协调器回归用例。 +无轨道容器由历史readyState 4改为code 4错误;有效媒体的正常顺序保持,重复就绪和 +失效操作结果被阻止。不要把synthetic RAF、受控竞态或Windows WebKit能力对照计为真实播放。 +音视频解码器仍通过两个显式声明桥连接,MB-05/06继续实际实现迁移和底层晚操作清理。 diff --git a/refactor/plan.md b/refactor/plan.md index 0f5cea3c6..0bcc32b03 100644 --- a/refactor/plan.md +++ b/refactor/plan.md @@ -4,7 +4,7 @@ 基线:`40fcda6a37d0049d42e49c1e64e70d4fd9ba5f7f`。总任务 222 项,范围 22 个包及工作区/示例。 -状态:todo 114 / doing 8 / blocked 0 / done 100 / deferred 0。风险 L/M/H 表示兼容风险,不表示工期。 +状态:todo 114 / doing 7 / blocked 0 / done 101 / deferred 0。风险 L/M/H 表示兼容风险,不表示工期。 前置依赖是启动条件;验收是完成条件。任务可以继续拆分,但不能复用或悄悄删除旧 ID。 @@ -332,7 +332,7 @@ | PKG-MB-01 | artplayer-proxy-mediabunny
核对 shim 与媒体契约 | BASE-05 | 全部 option、art.mediabunny、canvas/shim 属性及事件表 | 公开暴露成员和实际发布依赖/资源范围明确;核实 third-party.json 所记录依赖 MPL-2.0 元数据与实际 bundle 的许可/通知范围,不从根 MIT 推断 | H | done | | PKG-MB-02 | artplayer-proxy-mediabunny
建立真实媒体与事件基线 | PKG-MB-01, ENG-05, ENG-08 | MP4/WebM/HLS/Blob/Stream、seek/错误/轨道切换样本 | ready 事件顺序、音画同步、超时和释放可重跑 | H | done | | PKG-MB-03 | artplayer-proxy-mediabunny
整理 input 与加载取消 | PKG-MB-02, CORE-09 | input.js 源检测、输入资源、Range 与取消 | HLS 检测在 input 边界,旧来源类型和超时保持 | H | done | -| PKG-MB-04 | artplayer-proxy-mediabunny
整理 VideoShim/EventTarget/Engine 协调 | PKG-MB-03, CORE-06, CORE-11 | shim 描述符、事件桥、加载状态和操作隔离 | 公开属性/同步异步返回与事件重入顺序保持 | H | doing | +| PKG-MB-04 | artplayer-proxy-mediabunny
整理 VideoShim/EventTarget/Engine 协调 | PKG-MB-03, CORE-06, CORE-11 | shim 描述符、事件桥、加载状态和操作隔离 | 公开属性/同步异步返回与事件重入顺序保持 | H | done | | PKG-MB-05 | artplayer-proxy-mediabunny
整理视频解码、seek 和帧释放 | PKG-MB-04 | VideoEngine 调度、队列、晚帧处理和资源释放 | 暂停/seek/切源无旧帧覆盖,默认丢帧策略不变 | H | todo | | PKG-MB-06 | artplayer-proxy-mediabunny
整理音频解码、时钟与同步 | PKG-MB-04 | AudioEngine 时钟、缓冲和 AudioContext 归属 | AV sync、倍速、无音轨、静音/音量和暂停恢复通过 | H | todo | | PKG-MB-07 | artplayer-proxy-mediabunny
整理 HLS 配对轨道与 selector | PKG-MB-05, PKG-MB-06, CORE-14 | m3u8 配对、质量/音频选择及拓扑清理 | 实际选择高亮、切到无轨道来源清理、无重复 readiness | H | todo | @@ -523,5 +523,5 @@ - PKG-MB-01: [记录](baselines/mb-release.json) [记录](baselines/mb-surface.json) [记录](baselines/mb-contract.md) [记录](baselines/mb-contract-validation.json) [记录](mb-validation.md) [记录](changes/2026-09-12-PKG-MB-01-contract.md) - PKG-MB-02: [记录](changes/2026-09-12-PKG-MB-02-checkpoint.md) [记录](baselines/mb-media-checkpoint.json) [记录](mb-validation.md) [记录](changes/2026-09-12-PKG-MB-02-baseline.md) [记录](baselines/mb-behavior-validation.json) - PKG-MB-03: [记录](changes/2026-09-12-PKG-MB-03-input.md) [记录](baselines/mb-input-validation.json) -- PKG-MB-04: [记录](baselines/mb-coordination-source.json) [记录](changes/2026-09-12-PKG-MB-04-shim-checkpoint.md) [记录](baselines/mb-shim-checkpoint.json) +- PKG-MB-04: [记录](baselines/mb-coordination-source.json) [记录](changes/2026-09-12-PKG-MB-04-shim-checkpoint.md) [记录](baselines/mb-shim-checkpoint.json) [记录](changes/2026-09-12-PKG-MB-04-coordination.md) [记录](baselines/mb-coordination-validation.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 fb96903b1..c506aa6fd 100644 --- a/refactor/progress.md +++ b/refactor/progress.md @@ -1,5 +1,17 @@ # 进度与证据 +## PKG-MB-04完成:主协调器TS与操作隔离 + +MediaBunnyEngine实际迁移TS,并拆分playback/readiness/HLS查询职责;正常接口和事件顺序 +保持,修复旧play/seek覆盖、错误吞掉、重复就绪及无轨道假就绪。新增40项测试在旧main上 +8通过/32失败,候选全通过;包专项108通过、main/legacy各72通过。最终39项浏览器 +包括12真实播放、9Stream取消、9synthetic RAF、6能力对照及3无轨道拒绝;另在已有 +Chromium/Firefox播放用例内验证play回调同步pause后无playing。完整CI1269通过, +另44重复契约,306生产TS;包内16生产TS和2个未迁移解码器声明桥明确区分。 +见[变更](changes/2026-09-12-PKG-MB-04-coordination.md)及[证据](baselines/mb-coordination-validation.json)。 +222项:101 done、7 doing、114 todo;立即专用本地提交,下一项MB-05视频帧资源。 +MB-LIFE-01/MB-READY-01剩余解码器/能力与组合范围仍open;不构成npm发布验收。 + ## 当前检查点:PKG-MB-04 VideoShim、事件与RAF资源 新增五个生产TS模块,保持shim/canvas布局和正常事件/Promise/属性契约;修复销毁后的RAF、 diff --git a/refactor/risks.json b/refactor/risks.json index 5f9473200..2db8fb710 100644 --- a/refactor/risks.json +++ b/refactor/risks.json @@ -3648,7 +3648,7 @@ "PKG-MB-07", "PKG-MB-09" ], - "compatibleResolution": "Reproduce pending operations and destroy/source-switch races before migrating each owner; preserve public event and promise behavior while preventing stale resource use. MB-02 now reproduces late load rejection and uncancelled waiting/loadstart timers after destroy in all three historical implementations using a controlled host. Other interleavings and full-core native behavior are not yet verified. Expanded MB-02 baseline reproduces play-after-pause/destroy, rejected-play false state, seek-after-destroy and retained successful-load timeout timers in all three actual historical implementations; Range and active-timeout normal controls remain separate. MB-03 candidate owns pending Input before track selection and cancels load/HEAD/timers on source replacement, timeout and destroy; source/main/legacy regressions pass. Pending play/seek, late decoder work and full readiness coordination remain MB-04/05/06, so this risk stays open. MB-04 shim checkpoint fixes synthetic RAF retention and terminal event-listener cleanup, including engine cleanup exceptions. Closing the event bridge does not prove pending engine operations stopped; coordination remains in progress.", + "compatibleResolution": "Reproduce pending operations and destroy/source-switch races before migrating each owner; preserve public event and promise behavior while preventing stale resource use. MB-02 now reproduces late load rejection and uncancelled waiting/loadstart timers after destroy in all three historical implementations using a controlled host. Other interleavings and full-core native behavior are not yet verified. Expanded MB-02 baseline reproduces play-after-pause/destroy, rejected-play false state, seek-after-destroy and retained successful-load timeout timers in all three actual historical implementations; Range and active-timeout normal controls remain separate. MB-03 candidate owns pending Input before track selection and cancels load/HEAD/timers on source replacement, timeout and destroy; source/main/legacy regressions pass. Pending play/seek, late decoder work and full readiness coordination remain MB-04/05/06, so this risk stays open. MB-04 shim checkpoint fixes synthetic RAF retention and terminal event-listener cleanup, including engine cleanup exceptions. Closing the event bridge does not prove pending engine operations stopped; coordination remains in progress. MB-04 now guards play/seek/replacement completion, preserves explicit pause, observes stale failures and isolates reentrant event sequences. Decoder-internal late frames/audio and HLS UI races remain MB-05/06/07; risk stays open.", "closureCriteria": "Historical failing interleavings and candidate cancellation/cleanup pass with real media and event evidence, including long playback and track topology.", "status": "open", "evidence": [ @@ -3660,7 +3660,9 @@ "refactor/changes/2026-09-12-PKG-MB-02-baseline.md", "refactor/baselines/mb-behavior-validation.json", "refactor/changes/2026-09-12-PKG-MB-03-input.md", - "refactor/changes/2026-09-12-PKG-MB-04-shim-checkpoint.md" + "refactor/changes/2026-09-12-PKG-MB-04-shim-checkpoint.md", + "refactor/changes/2026-09-12-PKG-MB-04-coordination.md", + "refactor/baselines/mb-coordination-validation.json" ] }, { @@ -3707,11 +3709,13 @@ "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.", + "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.", "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/baselines/mb-behavior-validation.json", + "refactor/changes/2026-09-12-PKG-MB-04-coordination.md", + "refactor/baselines/mb-coordination-validation.json" ] } ] diff --git a/refactor/tasks.json b/refactor/tasks.json index 47b441877..d62558e1c 100644 --- a/refactor/tasks.json +++ b/refactor/tasks.json @@ -3460,14 +3460,16 @@ "CORE-06", "CORE-11" ], - "status": "doing", + "status": "done", "risk": "H", "deliverable": "shim 描述符、事件桥、加载状态和操作隔离", "acceptance": "公开属性/同步异步返回与事件重入顺序保持", "evidence": [ "baselines/mb-coordination-source.json", "changes/2026-09-12-PKG-MB-04-shim-checkpoint.md", - "baselines/mb-shim-checkpoint.json" + "baselines/mb-shim-checkpoint.json", + "changes/2026-09-12-PKG-MB-04-coordination.md", + "baselines/mb-coordination-validation.json" ] }, { diff --git a/test/browser/mediabunny-inputs.spec.js b/test/browser/mediabunny-inputs.spec.js index 832315f92..7e6e615e0 100644 --- a/test/browser/mediabunny-inputs.spec.js +++ b/test/browser/mediabunny-inputs.spec.js @@ -95,6 +95,13 @@ for (const implementation of implementations) { expect(loaded.dimensions).toEqual([0, 0]) outcome = input === 'hls' ? 'historical-unsupported-hls-control' : 'historical-stream-lock-control' } + else if (implementation.name.startsWith('candidate') && input === 'trackless') { + expect(loaded.error).toEqual({ code: 4, message: 'Input has no audio or video tracks.' }) + expect(loaded.readyState).toBe(0) + expect(loaded.dimensions).toEqual([0, 0]) + expect(await page.evaluate(() => window.mbEvents.filter(item => ['video:loadedmetadata', 'video:loadeddata', 'video:canplay'].includes(item.name)))).toEqual([]) + outcome = 'trackless-rejected-before-decoder-setup' + } else if (capabilities.AudioContext === 'undefined' && capabilities.webkitAudioContext === 'undefined') { expect(browserName).toBe('webkit') expect(capabilities).toEqual({ VideoDecoder: 'undefined', AudioDecoder: 'undefined', AudioContext: 'undefined', webkitAudioContext: 'undefined' }) @@ -115,7 +122,7 @@ for (const implementation of implementations) { expect(loaded.dimensions).toEqual([0, 0]) expect(await page.evaluate(() => window.mbEvents.filter(item => item.name === 'video:loadedmetadata').length)).toBe(implementation.name === 'published-1.0.0' ? 1 : 2) expect(await page.evaluate(() => window.mbEvents.filter(item => item.name === 'video:canplay').length)).toBe(1) - outcome = implementation.name.startsWith('candidate') ? 'candidate-trackless-readiness-gap' : 'historical-trackless-readiness-control' + outcome = 'historical-trackless-readiness-control' return } const readiness = await page.evaluate(() => window.mbEvents.map(item => item.name).filter(name => ['video:loadedmetadata', 'video:loadeddata', 'video:canplay', 'video:canplaythrough'].includes(name))) @@ -177,6 +184,21 @@ for (const implementation of implementations) { await expect.poll(() => page.evaluate(() => window.mbFrameClockSamples.filter(sample => !sample.paused).length)).toBeGreaterThan(2) await page.evaluate(() => window.mbCanvas.pause()) } + if (implementation.name.startsWith('candidate') && input === 'webm') { + await page.evaluate(() => { + const canvas = window.mbCanvas + window.mbReentrantStart = window.mbEvents.length + const pause = () => { + canvas.events.removeEventListener('play', pause) + canvas.pause() + } + canvas.events.addEventListener('play', pause) + }) + await page.click('#play') + await expect.poll(() => page.evaluate(() => window.mbEvents.slice(window.mbReentrantStart).filter(item => ['video:play', 'video:pause', 'video:playing'].includes(item.name)).map(item => item.name))).toEqual(['video:play', 'video:pause']) + expect(await page.evaluate(() => window.mbCanvas.paused)).toBe(true) + await page.evaluate(() => window.mbReentrantPlay = { paused: window.mbCanvas.paused, events: window.mbEvents.slice(window.mbReentrantStart).filter(item => ['video:play', 'video:pause', 'video:playing'].includes(item.name)).map(item => item.name) }) + } if (input === 'hls') { const tracks = await page.evaluate(async () => { const canvas = window.mbCanvas @@ -205,7 +227,7 @@ for (const implementation of implementations) { if (!canvas) return null const hls = canvas.getM3u8State ? await canvas.getM3u8State().catch(error => ({ error: error.message })) : null - return { events: window.mbEvents, actions: window.mbActions, dimensions: [canvas.width, canvas.height, canvas.videoWidth, canvas.videoHeight], currentTime: canvas.currentTime, duration: canvas.duration, error: canvas.error, readyState: canvas.readyState, audioState: canvas.engine.audio.audioContext?.state, frameClockSamples: window.mbFrameClockSamples, tracks: window.mbTrackTransitions, hls: hls && { levels: hls.levels?.map(({ id, height }) => ({ id, height })), audios: hls.audios?.map(({ id, lang }) => ({ id, lang })), error: hls.error }, inputBytes: window.mbInputBytes } + return { events: window.mbEvents, actions: window.mbActions, dimensions: [canvas.width, canvas.height, canvas.videoWidth, canvas.videoHeight], currentTime: canvas.currentTime, duration: canvas.duration, error: canvas.error, readyState: canvas.readyState, audioState: canvas.engine.audio.audioContext?.state, frameClockSamples: window.mbFrameClockSamples, tracks: window.mbTrackTransitions, reentrantPlay: window.mbReentrantPlay, hls: hls && { levels: hls.levels?.map(({ id, height }) => ({ id, height })), audios: hls.audios?.map(({ id, lang }) => ({ id, lang })), error: hls.error }, inputBytes: window.mbInputBytes } }).catch(error => ({ error: error.message })) await page.evaluate(() => { window.mbContext = window.mbCanvas?.engine.audio.audioContext @@ -214,7 +236,7 @@ for (const implementation of implementations) { await expect.poll(() => page.evaluate(() => window.mbContext?.state || 'not-created')).toMatch(/^(?:closed|not-created)$/) expect(await page.evaluate(() => window.mbPendingFrames.size)).toBe(0) const cleanup = await page.evaluate(() => ({ audioContext: window.mbContext?.state || 'not-created', pendingFrames: window.mbPendingFrames.size, streamCancelled: window.mbStreamCancelled || false })) - await testInfo.attach('mediabunny-native-input', { contentType: 'application/json', body: JSON.stringify({ implementation: implementation.name, sha256: hash(implementation.code), input, capabilities, outcome, state, cleanup, hlsManifest: input === 'hls' ? manifest : null, tracklessFixture: input === 'trackless' ? { parentSha256: hash(pattern), sha256: hash(trackless) } : null, 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 readiness remains MB-READY-01, not release acceptance.' }) }) + await testInfo.attach('mediabunny-native-input', { contentType: 'application/json', body: JSON.stringify({ implementation: implementation.name, sha256: hash(implementation.code), input, capabilities, outcome, state, cleanup, hlsManifest: input === 'hls' ? manifest : null, tracklessFixture: input === 'trackless' ? { parentSha256: hash(pattern), sha256: hash(trackless) } : null, 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.' }) }) } }) } diff --git a/test/browser/mediabunny.spec.js b/test/browser/mediabunny.spec.js index b801421b9..a1f2900ab 100644 --- a/test/browser/mediabunny.spec.js +++ b/test/browser/mediabunny.spec.js @@ -65,7 +65,7 @@ for (const implementation of implementations) { const canvas = window.art.video return { events: window.mbEvents, actions: window.mbActions, ready: window.art.isReady, dimensions: [canvas.width, canvas.height, canvas.videoWidth, canvas.videoHeight], paused: canvas.paused, currentTime: canvas.currentTime, error: canvas.error, readyState: canvas.readyState, audioState: canvas.engine?.audio?.audioContext?.state } }) - await testInfo.attach('mediabunny-input', { contentType: 'application/json', body: JSON.stringify({ implementation: implementation.name, sha256: hash(implementation.code), capabilities, outcome, state, scope: 'Two actual published proxies with actual core5.4.0; native MP4 pixels/clock or explicitly unsupported Windows WebKit APIs. No candidate, HLS or AV-sync acceptance.' }) }) + await testInfo.attach('mediabunny-input', { contentType: 'application/json', body: JSON.stringify({ implementation: implementation.name, sha256: hash(implementation.code), capabilities, outcome, state, 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.' }) }) await page.evaluate(() => window.art.destroy(false)) } }) diff --git a/test/mediabunny-coordination.test.js b/test/mediabunny-coordination.test.js new file mode 100644 index 000000000..90387f720 --- /dev/null +++ b/test/mediabunny-coordination.test.js @@ -0,0 +1,550 @@ +import assert from 'node:assert/strict' +import fs from 'node:fs' +// eslint-disable-next-line test/no-import-node-test -- Verify the actual coordinator with controlled asynchronous operations. +import test from 'node:test' +import { mbCandidate, mbEnvironment } from './helpers/mediabunny.js' +import { tracklessMp4 } from './helpers/trackless-mp4.js' + +const implementation = await mbCandidate() +const flush = () => new Promise(resolve => setImmediate(resolve)) +const media = new Blob([fs.readFileSync(new URL('./browser/media/pattern.mp4', import.meta.url))]) +function deferred() { + let resolve, reject + const promise = new Promise((yes, no) => { + resolve = yes + reject = no + }) + return { promise, resolve, reject } +} + +function environment() { + const env = mbEnvironment(implementation) + for (const name of ['playing', 'seeking', 'seeked', 'waiting', 'loadstart', 'loadeddata', 'canplay', 'canplaythrough', 'durationchange', 'progress', 'ended']) { + if (!env.eventNames.includes(name)) + env.eventNames.push(name) + } + const canvas = env.factory()(env.art) + const engine = canvas.engine + const calls = [] + for (const name of env.eventNames) canvas.events.addEventListener(name, () => calls.push(name)) + engine.audio.play = async () => calls.push('audio:play') + engine.audio.pause = () => calls.push('audio:pause') + engine.audio.seek = async time => calls.push(`audio:seek:${time}`) + engine.video.start = () => calls.push('video:start') + engine.video.stop = () => calls.push('video:stop') + engine.video.seek = async time => calls.push(`video:seek:${time}`) + env.globals.console = { log() {}, warn() {}, error() {}, debug() {} } + return { ...env, canvas, engine, calls } +} + +test('MediaBunny coordinator preserves ordinary play, seek-resume and synchronous pause ordering', async () => { + const env = environment() + await env.engine.play() + assert.deepEqual(env.calls, ['audio:play', 'video:start', 'play', 'playing']) + env.calls.length = 0 + await env.engine.seek(3) + assert.deepEqual(env.calls, ['seeking', 'waiting', 'audio:pause', 'video:stop', 'pause', 'audio:seek:3', 'video:seek:3', 'seeked', 'audio:play', 'video:start', 'play', 'playing']) + env.calls.length = 0 + assert.equal(env.engine.pause(), undefined) + assert.deepEqual(env.calls, ['audio:pause', 'video:stop', 'pause']) + env.art.emit('destroy') +}) + +for (const operation of ['pause', 'destroy', 'source']) { + test(`MediaBunny coordinator discards pending play after ${operation}`, async () => { + const env = environment() + const audio = deferred() + env.engine.audio.play = () => audio.promise + const playing = env.engine.play() + if (operation === 'pause') { + env.engine.pause() + } + else if (operation === 'destroy') { + env.art.emit('destroy') + } + else { + env.engine.performLoad = async () => {} + await env.engine.load('new.mp4') + } + env.calls.length = 0 + audio.resolve() + await playing + assert.equal(env.engine.paused, true) + assert.equal(env.calls.includes('video:start'), false) + assert.equal(env.calls.includes('play'), false) + assert.equal(env.calls.includes('playing'), false) + env.art.emit('destroy') + }) +} + +test('MediaBunny coordinator restores paused state after a play rejection and allows retry', async () => { + const env = environment() + const error = new Error('resume denied') + let attempts = 0 + env.engine.audio.play = async () => { + if (++attempts === 1) + throw error + } + await assert.rejects(env.engine.play(), value => value === error) + assert.equal(env.engine.paused, true) + await env.engine.play() + assert.equal(attempts, 2) + assert.equal(env.engine.paused, false) + assert.equal(env.calls.filter(name => name === 'video:start').length, 1) + env.art.emit('destroy') +}) + +test('MediaBunny coordinator shares delayed audio resume across play-pause-play and starts video once', async () => { + const env = environment() + const audio = deferred() + let attempts = 0 + env.engine.audio.play = () => { + attempts++ + return audio.promise + } + const first = env.engine.play() + env.engine.pause() + const second = env.engine.play() + audio.resolve() + await Promise.all([first, second]) + assert.equal(attempts, 1) + assert.equal(env.engine.paused, false) + assert.equal(env.calls.filter(name => name === 'video:start').length, 1) + assert.equal(env.calls.filter(name => name === 'play').length, 1) + env.art.emit('destroy') +}) + +test('MediaBunny coordinator stops the play event sequence when a listener pauses', async () => { + const env = environment() + env.canvas.events.addEventListener('play', () => env.engine.pause()) + await env.engine.play() + assert.equal(env.engine.paused, true) + assert.equal(env.calls.includes('playing'), false) + env.art.emit('destroy') +}) + +test('MediaBunny coordinator honors an explicit pause while a playing seek is pending', async () => { + const env = environment() + await env.engine.play() + const video = deferred() + env.engine.video.seek = () => video.promise + const seeking = env.engine.seek(4) + env.engine.pause() + env.calls.length = 0 + video.resolve() + await seeking + assert.equal(env.engine.paused, true) + assert.equal(env.engine.seeking, false) + assert.deepEqual(env.calls.filter(name => ['seeked', 'video:start', 'play'].includes(name)), ['seeked']) + env.art.emit('destroy') +}) + +test('MediaBunny coordinator keeps the newest seek active when an earlier seek finishes first', async () => { + const env = environment() + const first = deferred() + const second = deferred() + env.engine.video.seek = time => time === 1 ? first.promise : second.promise + const a = env.engine.seek(1) + const b = env.engine.seek(2) + first.resolve() + await a + assert.equal(env.engine.seeking, true) + assert.equal(env.calls.includes('seeked'), false) + second.resolve() + await b + assert.equal(env.engine.seeking, false) + assert.equal(env.calls.filter(name => name === 'seeked').length, 1) + env.art.emit('destroy') +}) + +test('MediaBunny coordinator drops an older seek result after the newest result and preserves playing intent', async () => { + const env = environment() + await env.engine.play() + const first = deferred() + const second = deferred() + env.engine.video.seek = time => time === 1 ? first.promise : second.promise + const a = env.engine.seek(1) + const b = env.engine.seek(2) + env.calls.length = 0 + second.resolve() + await b + assert.equal(env.engine.paused, false) + first.resolve() + await a + assert.equal(env.calls.filter(name => name === 'seeked').length, 1) + assert.equal(env.calls.filter(name => name === 'video:start').length, 1) + env.art.emit('destroy') +}) + +for (const operation of ['destroy', 'source']) { + test(`MediaBunny coordinator prevents pending seek completion and resume after ${operation}`, async () => { + const env = environment() + await env.engine.play() + const video = deferred() + env.engine.video.seek = () => video.promise + const seeking = env.engine.seek(4) + if (operation === 'destroy') { + env.art.emit('destroy') + } + else { + env.engine.performLoad = async () => {} + await env.engine.load('new.mp4') + } + env.calls.length = 0 + video.resolve() + await seeking + assert.equal(env.calls.includes('video:start'), false) + assert.equal(env.calls.includes('audio:play'), false) + assert.equal(env.calls.includes('seeked'), false) + env.art.emit('destroy') + }) +} + +test('MediaBunny coordinator does not continue old seek after a seeking listener requests another position', async () => { + const env = environment() + let replacement + let first = true + env.canvas.events.addEventListener('seeking', () => { + if (first) { + first = false + replacement = env.engine.seek(7) + } + }) + await env.engine.seek(2) + await replacement + assert.equal(env.calls.includes('audio:seek:2'), false) + assert.equal(env.calls.includes('video:seek:2'), false) + assert.equal(env.calls.filter(name => name === 'seeked').length, 1) + env.art.emit('destroy') +}) + +test('MediaBunny coordinator waits for pending seek when play is requested, without a resume deadlock', { timeout: 3000 }, async () => { + const env = environment() + const video = deferred() + env.engine.video.seek = () => video.promise + const seeking = env.engine.seek(3) + const playing = env.engine.play() + await flush() + assert.equal(env.calls.includes('audio:play'), false) + video.resolve() + await Promise.all([seeking, playing]) + assert.equal(env.engine.paused, false) + assert.equal(env.calls.filter(name => name === 'video:start').length, 1) + env.art.emit('destroy') +}) + +test('MediaBunny coordinator resets seeking after an active failure and permits another seek', async () => { + const env = environment() + const error = new Error('seek failed') + let attempts = 0 + env.engine.video.seek = async () => { + if (++attempts === 1) + throw error + } + await assert.rejects(env.engine.seek(2), value => value === error) + assert.equal(env.engine.seeking, false) + await env.engine.seek(3) + assert.equal(attempts, 2) + assert.equal(env.engine.seeking, false) + env.art.emit('destroy') +}) + +test('MediaBunny coordinator replay after ended seeks to zero then starts normally', async () => { + const env = environment() + env.engine.ended = true + await env.engine.play() + assert.equal(env.engine.ended, false) + assert.equal(env.engine.paused, false) + assert.deepEqual(env.calls, ['seeking', 'waiting', 'audio:seek:0', 'video:seek:0', 'seeked', 'audio:play', 'video:start', 'play', 'playing']) + env.art.emit('destroy') +}) + +test('MediaBunny coordinator preserves a resume-play rejection from the seek Promise', async () => { + const env = environment() + await env.engine.play() + const failure = new Error('resume failed') + env.engine.audio.play = async () => { + throw failure + } + await assert.rejects(env.engine.seek(3), error => error === failure) + assert.equal(env.engine.paused, true) + assert.equal(env.engine.seeking, false) + env.art.emit('destroy') +}) + +test('MediaBunny coordinator keeps original play rejection when cleanup fails and still stops video', async () => { + const env = environment() + const failure = new Error('resume failed') + env.engine.audio.play = async () => { + throw failure + } + env.engine.audio.pause = () => { + throw new Error('cleanup failed') + } + await assert.rejects(env.engine.play(), error => error === failure) + assert.equal(env.calls.includes('video:stop'), true) + assert.equal(env.engine.paused, true) + env.engine.audio.pause = () => {} + env.art.emit('destroy') +}) + +test('MediaBunny coordinator attempts both decoder cleanups when audio teardown throws', () => { + const env = environment() + const failure = new Error('audio teardown failed') + let videoDestroyed = 0 + env.engine.audio.destroy = () => { + throw failure + } + env.engine.video.destroy = () => videoDestroyed++ + assert.throws(() => env.art.emit('destroy'), error => error === failure) + assert.equal(videoDestroyed, 1) + assert.equal(env.canvas.events.listeners.size, 0) + assert.doesNotThrow(() => env.engine.destroy()) + assert.equal(videoDestroyed, 1) +}) + +test('MediaBunny coordinator does not resume if a seeked listener pauses', async () => { + const env = environment() + await env.engine.play() + env.canvas.events.addEventListener('seeked', () => env.engine.pause()) + env.calls.length = 0 + await env.engine.seek(3) + assert.equal(env.engine.paused, true) + assert.equal(env.calls.includes('video:start'), false) + env.art.emit('destroy') +}) + +test('MediaBunny coordinator settles canceled play before audio resume returns and observes its late rejection', async () => { + const env = environment() + const audio = deferred() + env.engine.audio.play = () => audio.promise + let settled = false + const playing = env.engine.play().then(() => settled = true) + env.art.emit('destroy') + await flush() + assert.equal(settled, true) + audio.reject(new Error('late resume failure')) + await playing + await flush() + assert.equal(env.calls.includes('video:start'), false) +}) + +test('MediaBunny coordinator ignores stale seek failure after a newer seek succeeds', async () => { + const env = environment() + const first = deferred() + env.engine.video.seek = time => time === 1 ? first.promise : Promise.resolve() + const a = env.engine.seek(1) + await env.engine.seek(2) + first.reject(new Error('obsolete seek error')) + await a + await flush() + assert.equal(env.engine.error, null) + assert.equal(env.engine.seeking, false) + assert.equal(env.calls.includes('error'), false) + env.art.emit('destroy') +}) + +test('MediaBunny synchronous currentTime setter observes an active seek rejection after one error event', async () => { + const env = environment() + env.engine.video.seek = async () => { + throw new Error('seek rejected') + } + assert.equal(Reflect.set(env.canvas, 'currentTime', 3), true) + await flush() + assert.equal(env.engine.error.message, 'seek rejected') + assert.equal(env.engine.seeking, false) + assert.equal(env.calls.filter(name => name === 'error').length, 1) + env.art.emit('destroy') +}) + +async function loadingEnvironment() { + const env = environment() + const video = deferred() + const audio = deferred() + const metadata = {} + env.engine.video.load = (media, callback) => { + metadata.video = callback + return video.promise + } + env.engine.audio.load = (media, callback) => { + metadata.audio = callback + return audio.promise + } + const loading = env.engine.load(media) + await flush() + assert.equal(typeof metadata.video, 'function') + assert.equal(typeof metadata.audio, 'function') + return { ...env, video, audio, metadata, loading } +} + +test('MediaBunny coordinator waits for both metadata participants and publishes readiness once', async () => { + const env = await loadingEnvironment() + env.metadata.video() + assert.equal(env.calls.includes('loadedmetadata'), false) + env.metadata.audio() + env.metadata.video() + env.metadata.audio() + env.video.resolve() + env.audio.resolve() + await env.loading + assert.deepEqual(env.calls.filter(name => ['loadedmetadata', 'durationchange', 'loadeddata', 'canplay', 'canplaythrough'].includes(name)), ['loadedmetadata', 'durationchange', 'loadeddata', 'canplay', 'canplaythrough']) + assert.equal(env.engine.readyState, 4) + env.art.emit('destroy') +}) + +for (const event of ['loadedmetadata', 'loadeddata']) { + test(`MediaBunny coordinator stops the old readiness sequence when ${event} starts another source`, async () => { + const env = await loadingEnvironment() + let replacement + env.canvas.events.addEventListener(event, () => { + env.engine.performLoad = async () => {} + replacement = env.engine.load('new.mp4') + }) + env.metadata.video() + env.metadata.audio() + env.video.resolve() + env.audio.resolve() + await env.loading + await replacement + const cursor = env.calls.indexOf(event) + assert(cursor >= 0) + assert.equal(env.calls.slice(cursor + 1).includes('canplay'), false) + if (event === 'loadedmetadata') + assert.equal(env.calls.slice(cursor + 1).includes('durationchange'), false) + assert.equal(env.engine.readyState, 0) + env.art.emit('destroy') + }) +} + +test('MediaBunny coordinator keeps failed decoder setup from becoming ready through a later metadata callback', async () => { + const env = await loadingEnvironment() + env.video.reject(new Error('decoder unavailable')) + await env.loading + const cursor = env.calls.length + env.metadata.audio() + env.audio.resolve() + await flush() + assert.equal(env.engine.error.message, 'decoder unavailable') + assert.equal(env.engine.readyState, 0) + assert.deepEqual(env.calls.slice(cursor), []) + env.art.emit('destroy') +}) + +test('MediaBunny coordinator rejects a real trackless container before decoder or AudioContext setup', async () => { + const env = environment() + const bytes = tracklessMp4(fs.readFileSync(new URL('./browser/media/pattern.mp4', import.meta.url))) + let setups = 0 + env.engine.video.load = async () => setups++ + env.engine.audio.load = async () => setups++ + await env.engine.load(new Blob([bytes])) + assert.equal(setups, 0) + assert.deepEqual({ ...env.engine.error }, { code: 4, message: 'Input has no audio or video tracks.' }) + assert.equal(env.engine.readyState, 0) + assert.equal(env.calls.includes('loadedmetadata'), false) + assert.equal(env.calls.includes('canplay'), false) + env.art.emit('destroy') +}) + +for (const [method, query] of [['selectHlsQuality', 'getVideoTracks'], ['selectHlsAudio', 'getAudioTracks']]) { + for (const ending of ['source', 'destroy', 'active']) { + test(`MediaBunny ${method} ${ending} query rejection respects source ownership`, async () => { + const env = environment() + const pending = deferred() + const failure = new Error('track query failed') + env.engine.input = { [query]: () => pending.promise } + env.engine.media = { isHls: true } + let replaced = 0 + env.engine.replaceTracks = async () => replaced++ + const selecting = env.engine[method]('auto') + if (ending === 'source') { + env.engine.performLoad = async () => {} + await env.engine.load('new.mp4') + } + else if (ending === 'destroy') { + env.art.emit('destroy') + } + pending.reject(failure) + if (ending === 'active') + await assert.rejects(selecting, error => error === failure) + else await selecting + assert.equal(replaced, 0) + assert.equal(env.engine.error, null) + env.art.emit('destroy') + }) + } + + test(`MediaBunny ${method} retains active replacement rejection after media identity changes`, async () => { + const env = environment() + const track = { id: 1, canBePairedWith: () => true } + env.engine.input = { [query]: async () => [track] } + env.engine.media = { isHls: true, videoTrack: track, audioTrack: track } + const failure = new Error('replacement failed') + env.engine.replaceTracks = async () => { + env.engine.media = { ...env.engine.media } + throw failure + } + await assert.rejects(env.engine[method](1), error => error === failure) + env.art.emit('destroy') + }) +} + +function replacementEnvironment() { + const env = environment() + const track = { isLive: async () => false } + const input = { getDurationFromMetadata: async () => 8 } + env.engine.media = { input, videoTrack: track, audioTrack: null, isHls: true, videoMode: 'auto', audioMode: 'auto', duration: 8 } + env.engine.video.load = async () => env.calls.push('video:load') + env.engine.audio.load = async () => env.calls.push('audio:load') + return env +} + +test('MediaBunny track replacement preserves normal pause, readiness, seek and resume ordering', async () => { + const env = replacementEnvironment() + await env.engine.play() + env.calls.length = 0 + await env.engine.replaceTracks({ videoMode: 'manual' }) + assert.deepEqual(env.calls, ['audio:pause', 'video:stop', 'pause', 'seeking', 'waiting', 'video:load', 'audio:load', 'video:seek:0', 'audio:seek:0', 'loadedmetadata', 'durationchange', 'progress', 'loadeddata', 'canplay', 'canplaythrough', 'seeked', 'audio:play', 'video:start', 'play', 'playing']) + assert.equal(env.engine.readyState, 4) + assert.equal(env.engine.media.videoMode, 'manual') + env.art.emit('destroy') +}) + +test('MediaBunny track replacement honors pause during delayed decoder setup', async () => { + const env = replacementEnvironment() + await env.engine.play() + const loading = deferred() + env.engine.video.load = () => loading.promise + const replacing = env.engine.replaceTracks({ videoMode: 'manual' }) + await flush() + env.engine.pause() + env.calls.length = 0 + loading.resolve() + await replacing + assert.equal(env.engine.paused, true) + assert.equal(env.calls.includes('video:start'), false) + assert.equal(env.calls.includes('seeked'), true) + env.art.emit('destroy') +}) + +for (const ending of ['source', 'destroy']) { + test(`MediaBunny track replacement cannot seek or publish readiness after ${ending}`, async () => { + const env = replacementEnvironment() + const loading = deferred() + env.engine.video.load = () => loading.promise + const replacing = env.engine.replaceTracks({ videoMode: 'manual' }) + await flush() + if (ending === 'destroy') { + env.art.emit('destroy') + } + else { + env.engine.performLoad = async () => {} + await env.engine.load('new.mp4') + } + env.calls.length = 0 + loading.resolve() + await replacing + await flush() + assert.deepEqual(env.calls.filter(name => !['waiting', 'loadstart'].includes(name)), []) + env.art.emit('destroy') + }) +}