diff --git a/docs/compiled/artplayer-proxy-mediabunny.js b/docs/compiled/artplayer-proxy-mediabunny.js index d2213fb12..dd37b8f40 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?(t.artplayerProxyMediabunny=t(),define(function(){return t.artplayerProxyMediabunny})):(e="undefined"!==typeof globalThis?globalThis:e||self).artplayerProxyMediabunny=t()}(this,function(){"use strict";function e(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 t{constructor(){this.listeners=new Map}addEventListener(e,t){this.listeners.has(e)||this.listeners.set(e,[]),this.listeners.get(e).push(t)}removeEventListener(e,t){const i=this.listeners.get(e);if(!i)return;const r=i.indexOf(t);r>=0&&i.splice(r,1)}emit(e,t){const i=new Event(e);i.detail=t;const r=this.listeners.get(e);r&&r.forEach(e=>e(i))}}function i(e){if(!e)throw new Error("Assertion failed.")}const r=e=>{const t=(e%360+360)%360;if(0===t||90===t||180===t||270===t)return t;throw new Error(`Invalid rotation ${e}.`)},a=e=>e&&e[e.length-1],s=e=>{let t=0;for(;0===e.readBits(1)&&t<32;)t++;if(t>=32)throw new Error("Invalid exponential-Golomb code.");return(1<{const t=s(e);return 0===(1&t)?-(t>>1):t+1>>1},o=e=>e.constructor===Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),c=e=>e.constructor===DataView?e:ArrayBuffer.isView(e)?new DataView(e.buffer,e.byteOffset,e.byteLength):new DataView(e),l=new TextDecoder,u=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])),d={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},h=u(d),f={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},m=u(f),p={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},g=u(p),k=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 y=/^[0-9a-fA-F]+$/,w=e=>[...e].map(e=>e.toString(16).padStart(2,"0")).join(""),T=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,S=(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},v=(e,t,i)=>{const r=P(e,i(t),i);e.splice(r+1,0,t)},I=()=>{let e,t;return{promise:new Promise((i,r)=>{e=i,t=r}),resolve:e,reject:t}},x=(e,t)=>{for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},C=(e,t)=>{for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},B=e=>{throw new Error(`Unexpected value: ${e}`)},E=(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},_=(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)},A=(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}}),F=(e,t,i)=>Math.max(t,Math.min(i,e)),R="und",D=e=>{const t=Math.round(e);return Math.abs(e/t-1)<10*Number.EPSILON?t:e},M=(e,t)=>Math.round(e*t)/t,N=(e,t)=>Math.floor(e/t)*t,O=/^[a-z]{3}$/,L=e=>O.test(e),z=1e6*(1+Number.EPSILON),U=(e,t)=>{const i={...e,...t};if(e.headers||t.headers){const r=e.headers?q(e.headers):{},a=t.headers?q(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},q=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},W=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(console.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 ce(1e3*e),a())throw n}};class V{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}let H=null;const K=()=>null!==H?H:H=!("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 j=null;const X=()=>null!==j?j:j="undefined"!==typeof navigator&&navigator.userAgent?.includes("Firefox");let $=null;const Q=()=>null!==$?$:$=!("undefined"===typeof navigator||!navigator.vendor?.includes("Google Inc")&&!/Chrome/.test(navigator.userAgent));let G=null;const Y=()=>{if(null!==G)return G;if("undefined"===typeof navigator)return null;const e=/\bChrome\/(\d+)/.exec(navigator.userAgent);return e?G=Number(e[1]):null},J=(e,t)=>-1!==e?e:t,Z=(e,t,i,r)=>e<=r&&i<=t,ee=e=>{const t=atob(e),i=new Uint8Array(t.length);for(let r=0;r{Symbol.dispose??(Symbol.dispose=Symbol("Symbol.dispose"))},ie=e=>"number"===typeof e&&!Number.isNaN(e),re=(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("/")},ae=(e,t)=>{let i=0;for(let r=0;r{let i=-1,r=1/0;for(let a=0;a{i(Number.isInteger(e.num)),i(Number.isInteger(e.den)),i(0!==e.den);let t=Math.abs(e.num),r=Math.abs(e.den);for(;0!==r;){const e=t%r;t=r,r=e}const a=t||1;return{num:e.num/a,den:e.den/a}},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.`)},ce=e=>new Promise(t=>setTimeout(t,e));class le{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)}}}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 de{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 he={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1};class fe{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<{if(!e||e.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");const t=new fe(e);let i=t.readBits(5);31===i&&(i=32+t.readBits(6));const r=t.readBits(4);let a=null;15===r?a=t.readBits(24):r=1&&s<=7&&(n=pe[s]),{objectType:i,frequencyIndex:r,sampleRate:a,channelConfiguration:s,numberOfChannels:n}},ke=["avc","hevc","vp9","av1","vp8"],be=["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"],ye=["aac","opus","mp3","vorbis","flac","ac3","eac3",...be],we=[{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}],Te=[{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}],Se=".01.01.01.01.00",Pe=".0.110.01.01.01.0",ve=e=>{const{codec:t,codecDescription:r,colorSpace:s,avcCodecInfo:n,hevcCodecInfo:o,vp9CodecInfo:l,av1CodecInfo:u}=e;if("avc"===t){if(i(null!==e.avcType),n){const t=new Uint8Array([n.avcProfileIndication,n.profileCompatibility,n.avcLevelIndication]);return`avc${e.avcType}.${w(t)}`}if(!r||r.byteLength<4)throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${e.avcType}.${w(r.subarray(1,4))}`}if("hevc"===t){let e,t,i,a,s,n;if(o)e=o.generalProfileSpace,t=o.generalProfileIdc,i=T(o.generalProfileCompatibilityFlags),a=o.generalTierFlag,s=o.generalLevelIdc,n=[...o.generalConstraintIndicatorFlags];else{if(!r||r.byteLength<23)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");const o=c(r),l=o.getUint8(1);e=l>>6&3,t=31&l,i=T(o.getUint32(2)),a=l>>5&1,s=o.getUint8(12),n=[];for(let e=0;e<6;e++)n.push(o.getUint8(6+e))}let l="hev1.";for(l+=["","A","B","C"][e]+t,l+=".",l+=i.toString(16).toUpperCase(),l+=".",l+=0===a?"L":"H",l+=s;n.length>0&&0===n[n.length-1];)n.pop();return n.length>0&&(l+=".",l+=n.map(e=>e.toString(16).toUpperCase()).join(".")),l}if("vp8"===t)return"vp8";if("vp9"===t){if(!l){const t=e.width*e.height;let i=a(Te).level;for(const e of Te)if(t<=e.maxPictureSize){i=e.level;break}return`vp09.00.${i.toString().padStart(2,"0")}.08`}let t=`vp09.${l.profile.toString().padStart(2,"0")}.${l.level.toString().padStart(2,"0")}.${l.bitDepth.toString().padStart(2,"0")}.${l.chromaSubsampling.toString().padStart(2,"0")}`;return t+=`.${l.colourPrimaries.toString().padStart(2,"0")}.${l.transferCharacteristics.toString().padStart(2,"0")}.${l.matrixCoefficients.toString().padStart(2,"0")}.${l.videoFullRangeFlag.toString().padStart(2,"0")}`,t.endsWith(Se)&&(t=t.slice(0,-15)),t}if("av1"===t){if(!u){const t=e.width*e.height;let i=a(Te).level;for(const e of Te)if(t<=e.maxPictureSize){i=e.level;break}return`av01.0.${i.toString().padStart(2,"0")}M.08`}const t=u.profile,i=u.level.toString().padStart(2,"0"),r=u.tier?"H":"M",n=u.bitDepth.toString().padStart(2,"0"),o=u.monochrome?"1":"0",c=100*u.chromaSubsamplingX+10*u.chromaSubsamplingY+1*(u.chromaSubsamplingX&&u.chromaSubsamplingY?u.chromaSamplePosition:0),l=s?.primaries?d[s.primaries]:1,h=s?.transfer?f[s.transfer]:1,m=s?.matrix?p[s.matrix]:1,g=s?.fullRange?1:0;let k=`av01.${t}.${i}${r}.${n}`;return k+=`.${o}.${c.toString().padStart(3,"0")}`,k+=`.${l.toString().padStart(2,"0")}`,k+=`.${h.toString().padStart(2,"0")}`,k+=`.${m.toString().padStart(2,"0")}`,k+=`.${g}`,k.endsWith(Pe)&&(k=k.slice(0,-17)),k}throw new TypeError(`Unhandled codec '${t}'.`)},Ie=e=>{const{codec:t,codecDescription:i,aacCodecInfo:r}=e;if("aac"===t){if(!r)throw new TypeError("AAC codec info must be provided.");if(r.isMpeg2)return"mp4a.67";{let e;if(null!==r.objectType)e=r.objectType;else{e=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(t&&be.includes(t))return t;throw new TypeError(`Unhandled codec '${t}'.`)},xe=48e3,Ce=/^pcm-([usf])(\d+)+(be)?$/,Be=e=>{if(i(be.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=Ce.exec(e);let r;i(t),r="u"===t[1]?"unsigned":"s"===t[1]?"signed":"float";return{dataType:r,sampleSize:Number(t[2])/8,littleEndian:"be"!==t[3],silentValue:"pcm-u8"===e?128:0}},Ee=e=>e.startsWith("avc1")||e.startsWith("avc3")?"avc":e.startsWith("hev1")||e.startsWith("hvc1")?"hevc":"vp8"===e?"vp8":e.startsWith("vp09")?"vp9":e.startsWith("av01")?"av1":"mp3"===e||"mp4a.69"===e||"mp4a.6B"===e||"mp4a.6b"===e||"mp4a.40.34"===e?"mp3":e.startsWith("mp4a.40.")||"mp4a.67"===e?"aac":"opus"===e?"opus":"vorbis"===e?"vorbis":"flac"===e?"flac":"ac-3"===e||"ac3"===e?"ac3":"ec-3"===e||"eac3"===e?"eac3":"ulaw"===e?"ulaw":"alaw"===e?"alaw":Ce.test(e)?e:"webvtt"===e?"webvtt":null,_e=[44100,48e3,32e3],Ae=[-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],Fe=1483304551,Re=1231971951,De=(e,t)=>3===e?3===t?21:36:3===t?13:21,Me=(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=Ae[16*n*4+16*l+(a>>4&15)];if(-1===g)return{header:null,bytesAdvanced:1};const k=1e3*g,b=_e[u]>>n+o,y=((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 Oe,Le;(Le=Oe||(Oe={}))[Le.FrameCount=1]="FrameCount",Le[Le.FileSize=2]="FileSize",Le[Le.Toc=4]="Toc";const ze=[48e3,44100,32e3],Ue=[24e3,22050,16e3];var qe,We,Ve,He;(We=qe||(qe={}))[We.NON_IDR_SLICE=1]="NON_IDR_SLICE",We[We.SLICE_DPA=2]="SLICE_DPA",We[We.SLICE_DPB=3]="SLICE_DPB",We[We.SLICE_DPC=4]="SLICE_DPC",We[We.IDR=5]="IDR",We[We.SEI=6]="SEI",We[We.SPS=7]="SPS",We[We.PPS=8]="PPS",We[We.AUD=9]="AUD",We[We.SPS_EXT=13]="SPS_EXT",(He=Ve||(Ve={}))[He.RASL_N=8]="RASL_N",He[He.RASL_R=9]="RASL_R",He[He.BLA_W_LP=16]="BLA_W_LP",He[He.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",He[He.VPS_NUT=32]="VPS_NUT",He[He.SPS_NUT=33]="SPS_NUT",He[He.PPS_NUT=34]="PPS_NUT",He[He.AUD_NUT=35]="AUD_NUT",He[He.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",He[He.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT";const Ke=function*(e){let t=0,i=-1;for(;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&o(t.description)[4];return je(e,i+1)}return Ke(e)},$e=e=>31&e,Qe=e=>{const t=[],i=e.length;for(let r=0;r{const t=e.reduce((e,t)=>e+Ge.byteLength+t.byteLength,0),i=new Uint8Array(t);let r=0;for(const a of e)i.set(Ge,r),r+=Ge.byteLength,i.set(a,r),r+=a.byteLength;return i},Je=(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:_(e,a,s.byteLength);break;case 4:e.setUint32(a,s.byteLength,!1)}a+=t,r.set(s,a),a+=s.byteLength}return r},Ze=e=>{try{const t=[],r=[],a=[];for(const i of Ke(e)){const s=e.subarray(i.offset,i.offset+i.length),n=$e(s[0]);n===qe.SPS?t.push(s):n===qe.PPS?r.push(s):n===qe.SPS_EXT&&a.push(s)}if(0===t.length)return null;if(0===r.length)return null;const s=t[0],n=tt(s);i(null!==n);const o=100===n.profileIdc||110===n.profileIdc||122===n.profileIdc||144===n.profileIdc;return{configurationVersion:1,avcProfileIndication:n.profileIdc,profileCompatibility:n.constraintFlags,avcLevelIndication:n.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:t,pictureParameterSets:r,chromaFormat:o?n.chromaFormatIdc:null,bitDepthLumaMinus8:o?n.bitDepthLumaMinus8:null,bitDepthChromaMinus8:o?n.bitDepthChromaMinus8:null,sequenceParameterSetExt:o?a:null}}catch(t){return console.error("Error building AVC Decoder Configuration Record:",t),null}},et={1:{num:1,den:1},2:{num:12,den:11},3:{num:10,den:11},4:{num:16,den:11},5:{num:40,den:33},6:{num:24,den:11},7:{num:20,den:11},8:{num:32,den:11},9:{num:80,den:33},10:{num:18,den:11},11:{num:15,den:11},12:{num:64,den:33},13:{num:160,den:99},14:{num:4,den:3},15:{num:3,den:2},16:{num:2,den:1}},tt=e=>{try{const t=new fe(Qe(e));t.skipBits(1),t.skipBits(2);if(7!==t.readBits(5))return null;const r=t.readAlignedByte(),o=t.readAlignedByte(),c=t.readAlignedByte();s(t);let l=1,u=0,d=0,h=0;if(100===r||110===r||122===r||244===r||44===r||83===r||86===r||118===r||128===r){l=s(t),3===l&&(h=t.readBits(1)),u=s(t),d=s(t),t.skipBits(1);if(t.readBits(1))for(let e=0;e<(3!==l?8:12);e++){if(t.readBits(1)){const i=e<6?16:64;let r=8,a=8;for(let e=0;ee.level>=c)??a(we),r=Math.min(Math.floor(i.maxDpbMbs/(e*t)),16);x=r,C=r}else x=0,C=0}return i(null!==C),{profileIdc:r,constraintFlags:o,levelIdc:c,frameMbsOnlyFlag:w,chromaFormatIdc:l,bitDepthLumaMinus8:u,bitDepthChromaMinus8:d,codedWidth:g,codedHeight:k,displayWidth:b,displayHeight:y,pixelAspectRatio:I,colourPrimaries:T,matrixCoefficients:P,transferCharacteristics:S,fullRangeFlag:v,numReorderFrames:x,maxDecFrameBuffering:C}}catch(t){return console.error("Error parsing AVC SPS:",t),null}},it=e=>{const t=s(e);e.skipBits(4),e.skipBits(4);for(let i=0;i<=t;i++)s(e),s(e),e.skipBits(1);e.skipBits(5),e.skipBits(5),e.skipBits(5),e.skipBits(5)},rt=(e,t)=>{if(t.description){const i=3&o(t.description)[21];return je(e,i+1)}return Ke(e)},at=e=>e>>1&63,st=e=>{try{const t=new fe(Qe(e));t.skipBits(16),t.readBits(4);const i=t.readBits(3),r=t.readBits(1),{general_profile_space:a,general_tier_flag:n,general_profile_idc:o,general_profile_compatibility_flags:c,general_constraint_indicator_flags:l,general_level_idc:u}=ot(t,i);s(t);const d=s(t);let h=0;3===d&&(h=t.readBits(1));const f=s(t),m=s(t);let p=f,g=m;if(t.readBits(1)){const e=s(t),i=s(t),r=s(t),a=s(t);let n=1,o=1;const c=0===h?d:0;1===c?(n=2,o=2):2===c&&(n=2,o=1),p-=(e+i)*n,g-=(r+a)*o}const k=s(t),b=s(t);s(t);const y=t.readBits(1);let w=0;for(let e=y?0:i;e<=i;e++)s(t),w=s(t),s(t);s(t),s(t),s(t),s(t),s(t),s(t),t.readBits(1)&&t.readBits(1)&&ct(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(4),t.skipBits(4),s(t),s(t),t.skipBits(1));const T=s(t);if(lt(t,T),t.readBits(1)){const e=s(t);for(let i=0;i{try{const t=[],i=[],r=[],a=[];for(const s of Ke(e)){const n=e.subarray(s.offset,s.offset+s.length),o=at(n[0]);o===Ve.VPS_NUT?t.push(n):o===Ve.SPS_NUT?i.push(n):o===Ve.PPS_NUT?r.push(n):o!==Ve.PREFIX_SEI_NUT&&o!==Ve.SUFFIX_SEI_NUT||a.push(n)}if(0===i.length||0===r.length)return null;const o=st(i[0]);if(!o)return null;let c=0;if(r.length>0){const e=r[0],t=new fe(Qe(e));t.skipBits(16),s(t),s(t),t.skipBits(1),t.skipBits(1),t.skipBits(3),t.skipBits(1),t.skipBits(1),s(t),s(t),n(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&s(t),n(t),n(t),t.skipBits(1),t.skipBits(1),t.skipBits(1),t.skipBits(1);const i=t.readBits(1),a=t.readBits(1);c=i||a?i&&!a?2:!i&&a?3:0:0}const l=[...t.length?[{arrayCompleteness:1,nalUnitType:Ve.VPS_NUT,nalUnits:t}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:Ve.SPS_NUT,nalUnits:i}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:Ve.PPS_NUT,nalUnits:r}]:[],...a.length?[{arrayCompleteness:1,nalUnitType:at(a[0][0]),nalUnits:a}]:[]];return{configurationVersion:1,generalProfileSpace:o.generalProfileSpace,generalTierFlag:o.generalTierFlag,generalProfileIdc:o.generalProfileIdc,generalProfileCompatibilityFlags:o.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:o.generalConstraintIndicatorFlags,generalLevelIdc:o.generalLevelIdc,minSpatialSegmentationIdc:o.minSpatialSegmentationIdc,parallelismType:c,chromaFormatIdc:o.chromaFormatIdc,bitDepthLumaMinus8:o.bitDepthLumaMinus8,bitDepthChromaMinus8:o.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:o.spsMaxSubLayersMinus1+1,temporalIdNested:o.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:l}}catch(t){return console.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&&n(e);for(let t=0;t{const i=[];for(let r=0;r{let a=0,n=0,o=0;if(0!==t&&(n=e.readBits(1)),n){if(t===i){o=t-(s(e)+1)}else o=t-1;e.readBits(1),s(e);const n=r[o]??0;for(let t=0;t<=n;t++){e.readBits(1)||e.readBits(1)}a=r[o]}else{const t=s(e),i=s(e);for(let r=0;r{let i=2,r=2,a=2,n=0,o=0,c={num:1,den:1};if(e.readBits(1)){const t=e.readBits(8);if(255===t)c={num:e.readBits(16),den:e.readBits(16)};else{const e=et[t];e&&(c=e)}}return e.readBits(1)&&e.readBits(1),e.readBits(1)&&(e.readBits(3),n=e.readBits(1),e.readBits(1)&&(i=e.readBits(8),r=e.readBits(8),a=e.readBits(8))),e.readBits(1)&&(s(e),s(e)),e.readBits(1),e.readBits(1),e.readBits(1),e.readBits(1)&&(s(e),s(e),s(e),s(e)),e.readBits(1)&&(e.readBits(32),e.readBits(32),e.readBits(1)&&s(e),e.readBits(1)&&ht(e,!0,t)),e.readBits(1)&&(e.readBits(1),e.readBits(1),e.readBits(1),o=s(e),s(e),s(e),s(e),s(e)),{pixelAspectRatio:c,colourPrimaries:i,transferCharacteristics:r,matrixCoefficients:a,fullRangeFlag:n,minSpatialSegmentationIdc:o}},ht=(e,t,i)=>{let r=!1,a=!1,n=!1;r=1===e.readBits(1),a=1===e.readBits(1),(r||a)&&(n=1===e.readBits(1),n&&(e.readBits(8),e.readBits(5),e.readBits(1),e.readBits(5)),e.readBits(4),e.readBits(4),n&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5));for(let o=0;o<=i;o++){let t=!0;1===e.readBits(1)||(t=1===e.readBits(1));let i=!1;t?s(e):i=1===e.readBits(1);let o=1;if(!i){o=s(e)+1}r&&ft(e,o,n),a&&ft(e,o,n)}},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&o(t.description)[21];return Je(e,i+1)}return Ye(e)})(a,t)},kt=e=>{const t=new fe(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 s=8;if(r>=2){s=t.readBits(1)?12:10}const n=t.readBits(3);let o=0,c=0;if(7!==n){if(c=t.readBits(1),1===r||3===r){const e=t.readBits(1),i=t.readBits(1);o=e||i?e&&!i?2:1:3,t.skipBits(1)}else o=1}else o=3,c=1;const l=(t.readBits(16)+1)*(t.readBits(16)+1);let u=a(Te).level;for(const a of Te)if(l<=a.maxPictureSize){u=a.level;break}return{profile:r,level:u,bitDepth:s,chromaSubsampling:o,videoFullRangeFlag:c,colourPrimaries:2===n?1:1===n?6:2,transferCharacteristics:2===n?1:1===n?6:2,matrixCoefficients:7===n?0:2===n?1:1===n?6:2}},bt=function*(e){const t=new fe(e),r=()=>{let e=0;for(let i=0;i<8;i++){const r=t.readAlignedByte();if(e|=(127&r)<<7*i,!(128&r))break;if(7===i&&128&r)return null}return e>=2**32-1?null:e};for(;t.getBitsLeft()>=8;){t.skipBits(1);const a=t.readBits(4),s=t.readBits(1),n=t.readBits(1);let o;if(t.skipBits(1),s&&t.skipBits(8),n){const e=r();if(null===e)return;o=e}else o=Math.floor(t.getBitsLeft()/8);i(t.pos%8===0),yield{type:a,data:e.subarray(t.pos/8,t.pos/8+o)},t.skipBits(8*o)}},yt=e=>{for(const{type:t,data:i}of bt(e)){if(1!==t)continue;const e=new fe(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{if(e.readBits(1)){e.skipBits(32),e.skipBits(32);if(e.readBits(1))return null}const t=e.readBits(1);t&&(o=e.readBits(5),e.skipBits(32),e.skipBits(5),e.skipBits(5));const i=e.readBits(5);for(let r=0;r<=i;r++){e.skipBits(12);const i=e.readBits(5);if(0===r&&(s=i),i>7){const t=e.readBits(1);0===r&&(n=t)}if(t){if(e.readBits(1)){const t=o+1;e.skipBits(t),e.skipBits(t),e.skipBits(1)}}e.readBits(1)&&e.skipBits(4)}}const 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=1,k=1,b=0;return p||(0===r?(g=1,k=1):1===r?(g=0,k=0):12===m&&(g=e.readBits(1),g&&(k=e.readBits(1))),g&&k&&(b=e.readBits(2))),{profile:r,level:s,tier:n,bitDepth:m,monochrome:p,chromaSubsamplingX:g,chromaSubsamplingY:k,chromaSamplePosition:b}}return null},wt=[480,960,1920,2880,480,960,1920,2880,480,960,1920,2880,480,960,480,960,120,240,480,960,120,240,480,960,120,240,480,960,120,240,480,960],Tt=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}},St=(e,t,r)=>{switch(e){case"avc":for(const e of Xe(r,t)){const t=r[e.offset],i=$e(t);if(i>=qe.NON_IDR_SLICE&&i<=qe.SLICE_DPC)return"delta";if(i===qe.IDR)return"key";if(i===qe.SEI&&(!Q()||Y()>=144)){const t=r.subarray(e.offset,e.offset+e.length),i=Qe(t);let a=1;do{let e=0;for(;;){const t=i[a++];if(void 0===t)break;if(e+=t,t<255)break}let t=0;for(;;){const e=i[a++];if(void 0===e)break;if(t+=e,e<255)break}if(e===6){const e=new fe(i);e.pos=8*a;const t=s(e),r=e.readBits(1);if(0===t&&1===r)return"key"}a+=t}while(a{var i,r;const a=c(e);let s=0;const n=a.getUint32(s,!0);s+=4;const o=l.decode(e.subarray(s,s+n));s+=n,n>0&&(t.raw??(t.raw={}),(i=t.raw).vendor??(i.vendor=o));const u=a.getUint32(s,!0);s+=4;for(let d=0;d0&&(t.trackNumber??(t.trackNumber=i)),r&&Number.isInteger(r)&&r>0&&(t.tracksTotal??(t.tracksTotal=r))}break;case"TRACKTOTAL":{const e=Number.parseInt(d,10);Number.isInteger(e)&&e>0&&(t.tracksTotal??(t.tracksTotal=e))}break;case"DISCNUMBER":{const e=d.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(d,10);Number.isInteger(e)&&e>0&&(t.discsTotal??(t.discsTotal=e))}break;case"DATE":{const e=new Date(d);Number.isNaN(e.getTime())||(t.date??(t.date=e))}break;case"GENRE":t.genre??(t.genre=d);break;case"METADATA_BLOCK_PICTURE":{const e=ee(d),i=c(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=l.decode(e.subarray(12+a,12+a+n)),u=i.getUint32(a+n+28),h=e.subarray(a+n+32,a+n+32+u);t.images??(t.images=[]),t.images.push({data:h,mimeType:s,kind:3===r?"coverFront":4===r?"coverBack":"unknown",name:void 0,description:o||void 0})}}}},xt=[2,1,2,3,3,4,4,5],Ct=e=>{if(e.length<7)return null;if(11!==e[0]||119!==e[1])return null;const t=new fe(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)}},Bt=[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],Et=[1,2,3,6],_t=e=>{if(e.length<6)return null;if(11!==e[0]||119!==e[1])return null;const t=new fe(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=Et[s];let d;d=a<3?ze[a]/1e3:Ue[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 i(t),t.fscod<3?ze[t.fscod]:null!==t.fscod2&&t.fscod2<3?Ue[t.fscod2]:null},Ft=e=>{const t=e.substreams[0];i(t);let r=xt[t.acmod]+t.lfeon;if(t.numDepSub>0){const e=[2,2,1,1,2,2,2,1,1];for(let i=0;i<9;i++)t.chanLoc&1<<8-i&&(r+=e[i])}return r};class Rt{constructor(e){this.input=e}dispose(){}}const Dt=new Uint8Array(0);class Mt{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===Dt&&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===Dt}get microsecondTimestamp(){return Math.trunc(z*this.timestamp)}get microsecondDuration(){return Math.trunc(z*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if("undefined"===typeof EncodedVideoChunk)throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw new TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if("undefined"===typeof EncodedVideoChunk)throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to an audio chunk.");if("undefined"===typeof EncodedAudioChunk)throw new Error("Your browser does not support EncodedAudioChunk.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(e,t){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 Mt(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 Mt(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 Nt=e=>{const t=c(e);let i=0;const r=t.getUint8(i);i+=1,i+=3;const a=w(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=gn(e);const i=In(e,4);let r=8;1===t&&(t=wn(e),r=16);const a=t-r;return a<0?null:{name:i,totalSize:t,headerSize:r,contentSize:a}},zt=e=>bn(e)/65536,Ut=e=>bn(e)/1073741824,qt=e=>{let t=0;for(let i=0;i<4;i++){t<<=7;const i=un(e);if(t|=127&i,0===(128&i))break}return t},Wt=e=>{let t=hn(e);return e.skip(2),t=Math.min(t,e.remainingLength),l.decode(ln(e,t))},Vt=e=>{const t=Lt(e);if(!t||"data"!==t.name)return null;if(e.remainingLength<8)return null;const i=gn(e);e.skip(4);const r=ln(e,t.contentSize-8);switch(i){case 1:return l.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}},Ht=16,Kt=new Uint32Array(256),jt=new Uint32Array(256),Xt=new Uint32Array(256),$t=new Uint32Array(256),Qt=new Uint32Array(256),Gt=new Uint32Array(256),Yt=new Uint32Array(10);let Jt=!1;class Zt{constructor(){this.roundkey=new Uint32Array(44),this.iv=new Uint32Array(Ht/Uint32Array.BYTES_PER_ELEMENT),this.in=new Uint8Array(Ht),this.out=new Uint8Array(Ht),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),Jt||(()=>{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);Kt[s]=t<<24|t<<16|t<<8|t,Gt[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);jt[s]=a,Xt[s]=a>>>8|a<<24,$t[s]=a>>>16|a<<16,Qt[s]=a>>>24|a<<8}let a=1;for(let s=0;s<10;s++)Yt[s]=a<<24,a=a<<1^(128&a?283:0);Jt=!0})();const r=new DataView(e.buffer,e.byteOffset,e.byteLength),a=new DataView(t.buffer,t.byteOffset,t.byteLength);this.roundkey[0]=r.getUint32(0,!1),this.roundkey[1]=r.getUint32(4,!1),this.roundkey[2]=r.getUint32(8,!1),this.roundkey[3]=r.getUint32(12,!1),this.iv[0]=a.getUint32(0,!1),this.iv[1]=a.getUint32(4,!1),this.iv[2]=a.getUint32(8,!1),this.iv[3]=a.getUint32(12,!1);for(let i=4;i<44;i+=4){const e=this.roundkey[i-1];this.roundkey[i]=this.roundkey[i-4]^4278190080&Kt[e>>>16&255]^16711680&Kt[e>>>8&255]^65280&Kt[e>>>0&255]^255&Kt[e>>>24&255]^Yt[i/4-1],this.roundkey[i+1]=this.roundkey[i-3]^this.roundkey[i],this.roundkey[i+2]=this.roundkey[i-2]^this.roundkey[i+1],this.roundkey[i+3]=this.roundkey[i-1]^this.roundkey[i+2]}for(let i=0,s=40;i>>24&255]]^Xt[255&Kt[t>>>16&255]]^$t[255&Kt[t>>>8&255]]^Qt[255&Kt[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=jt[e>>>24]^Xt[r>>>16&255]^$t[i>>>8&255]^Qt[255&t]^this.roundkey[a],l=jt[t>>>24]^Xt[e>>>16&255]^$t[r>>>8&255]^Qt[255&i]^this.roundkey[a+1],u=jt[i>>>24]^Xt[t>>>16&255]^$t[e>>>8&255]^Qt[255&r]^this.roundkey[a+2],d=jt[r>>>24]^Xt[i>>>16&255]^$t[t>>>8&255]^Qt[255&e]^this.roundkey[a+3],e=c,t=l,i=u,r=d}const h=4278190080&Gt[e>>>24&255]^16711680&Gt[r>>>16&255]^65280&Gt[i>>>8&255]^255&Gt[t>>>0&255]^this.roundkey[40],f=4278190080&Gt[t>>>24&255]^16711680&Gt[e>>>16&255]^65280&Gt[r>>>8&255]^255&Gt[i>>>0&255]^this.roundkey[41],m=4278190080&Gt[i>>>24&255]^16711680&Gt[t>>>16&255]^65280&Gt[e>>>8&255]^255&Gt[r>>>0&255]^this.roundkey[42],p=4278190080&Gt[r>>>24&255]^16711680&Gt[i>>>16&255]^65280&Gt[t>>>8&255]^255&Gt[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 ei extends Rt{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;for(;;){let r=this.reader.requestSliceRange(e,8,16);if(r instanceof Promise&&(r=await r),!r)break;const a=e,s=Lt(r);if(!s)break;if("ftyp"===s.name||"styp"===s.name){const e=In(r,4);this.isQuickTime="qt "===e}else{if("moov"===s.name){let e=this.reader.requestSlice(r.filePos,s.contentSize);if(e instanceof Promise&&(e=await e),!e)break;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;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.');const e=await this.input._initInput._getDemuxer();if(e.constructor!==ei)throw new Error("Init input must match the input's format.");await e.readMetadata(),this.movieTimescale=e.movieTimescale,this.movieDurationInTimescale=e.movieDurationInTimescale,this.metadataTags=e.metadataTags,this.isFragmented=!0,this.fragmentTrackDefaults=e.fragmentTrackDefaults,this.psshBoxes=e.psshBoxes;for(const t of e.tracks){const e={id:t.id,demuxer:this,trackBacking:null,disposition:t.disposition,timescale:t.timescale,durationInMediaTimescale:t.durationInMediaTimescale,durationInMovieTimescale:t.durationInMovieTimescale,rotation:t.rotation,internalCodecId:t.internalCodecId,name:t.name,languageCode:t.languageCode,sampleTableByteOffset:null,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:t.editListPreviousSegmentDurations,editListOffset:t.editListOffset,encryptionInfo:t.encryptionInfo,encryptionAuxInfo:null,frmaCodecString:null,info:t.info};if(t.trackBacking)if(i(e.info),"video"===e.info.type&&-1!==e.info.width){const t=e;e.trackBacking=new ii(t),this.tracks.push(e)}else if("audio"===e.info.type&&-1!==e.info.numberOfChannels){const t=e;e.trackBacking=new ri(t),this.tracks.push(e)}}t=!1;break}}e=a+s.totalSize}if(t){i(null!==this.reader.fileSize);let e=this.reader.requestSlice(this.reader.fileSize-4,4);e instanceof Promise&&(e=await e),i(e);const t=gn(e),r=this.reader.fileSize-t;if(r>=0&&r<=this.reader.fileSize-16){let e=this.reader.requestSliceRange(r,8,16);if(e instanceof Promise&&(e=await e),e){const t=Lt(e);if(t&&"mfra"===t.name){let i=this.reader.requestSlice(e.filePos,t.contentSize);i instanceof Promise&&(i=await i),i&&this.readContiguousBoxes(i)}}}}})())}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;i(this.moovSlice);const r=this.moovSlice.slice(e.sampleTableByteOffset);this.currentTrack=e,this.traverseBox(r),this.currentTrack=null;if("audio"===e.info?.type&&e.info.codec&&be.includes(e.info.codec)&&0===t.sampleCompositionTimeOffsets.length){i("audio"===e.info?.type);const r=Be(e.info.codec),s=[],n=[];for(let i=0;ie.startIndex),d=t.sampleTimingEntries[u],h=P(t.sampleTimingEntries,l,e=>e.startIndex),f=t.sampleTimingEntries[h],m=d.startDecodeTimestamp+(c-d.startIndex)*d.delta,p=f.startDecodeTimestamp+(l-f.startIndex)*f.delta-m,g=a(s);g&&g.delta===p?g.count++:s.push({startIndex:o.startChunkIndex+i,startDecodeTimestamp:m,count:1,delta:p});const k=o.samplesPerChunk*r.sampleSize*e.info.numberOfChannels;n.push(k)}o.startSampleIndex=o.startChunkIndex,o.samplesPerChunk=1}t.sampleTimingEntries=s,t.sampleSizes=n}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===s.moofOffset);if(r)ci(i,r.timestamp);else{const e=P(t,s.moofOffset-1,e=>e.moofOffset);if(-1!==e){const r=t[e];ci(i,r.endTimestamp)}}i.startTimestampIsFinal=!0}const r=P(t,i.startTimestamp,e=>e.startTimestamp);if(-1!==r&&t[r].moofOffset===s.moofOffset||t.splice(r+1,0,{moofOffset:s.moofOffset,startTimestamp:i.startTimestamp,endTimestamp:i.endTimestamp}),i.encryptionAuxInfo&&e.encryptionInfo){const t=await hi(this.reader,e.encryptionInfo,i.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;L(t.languageCode)||(t.languageCode=R)}}break;case"hdlr":{const t=this.currentTrack;if(!t)break;e.skip(8);const i=In(e,4);"vide"===i?t.info={type:"video",width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:null,avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null}:"soun"===i&&(t.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null,pcmLittleEndian:!1,pcmSampleSize:null})}break;case"stbl":{const t=this.currentTrack;if(!t)break;t.sampleTableByteOffset=K,this.readContiguousBoxes(e.slice(X,j.contentSize))}break;case"stsd":{const t=this.currentTrack;if(!t)break;if(null===t.info||t.sampleTable)break;const i=un(e);e.skip(3);const r=gn(e);for(let a=0;a0&&(1===n?(e.skip(4),c=8*gn(e),e.skip(8)):2===n&&(e.skip(4),l=vn(e),o=gn(e),e.skip(4),c=gn(e),u=gn(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=xe;else if("flac"===d)t.info.codec="flac";else if("ulaw"===d)t.info.codec="ulaw";else if("alaw"===d)t.info.codec="alaw";else if("ac-3"===d)t.info.codec="ac3";else if("ec-3"===d)t.info.codec="eac3";else if("twos"===d)8===c?t.info.codec="pcm-s8":16===c?t.info.codec=t.info.pcmLittleEndian?"pcm-s16":"pcm-s16be":(console.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":(console.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":(console.warn(`Invalid ipcm sample size ${e}.`),t.info.codec=null):16===e?t.info.codec="pcm-s16be":24===e?t.info.codec="pcm-s24be":32===e?t.info.codec="pcm-s32be":(console.warn(`Invalid ipcm sample size ${e}.`),t.info.codec=null)}else if("fpcm"===d){const e=t.info.pcmSampleSize;t.info.pcmLittleEndian?32===e?t.info.codec="pcm-f32":64===e?t.info.codec="pcm-f64":(console.warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null):32===e?t.info.codec="pcm-f32be":64===e?t.info.codec="pcm-f64be":(console.warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null)}else if("lpcm"===d&&null!==u){const e=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!==un(e),t.encryptionInfo.defaultPerSampleIvSize=un(e),t.encryptionInfo.defaultKid=w(ln(e,16)),t.encryptionInfo.defaultIsProtected&&0===t.encryptionInfo.defaultPerSampleIvSize){const i=un(e),r=new Uint8Array(16);r.set(ln(e,i),0),t.encryptionInfo.defaultConstantIv=r}}break;case"avcC":{const t=this.currentTrack;if(!t)break;i(t.info),t.info.codecDescription=ln(e,j.contentSize)}break;case"hvcC":{const t=this.currentTrack;if(!t)break;i(t.info),t.info.codecDescription=ln(e,j.contentSize)}break;case"vpcC":{const t=this.currentTrack;if(!t)break;i("video"===t.info?.type),e.skip(4);const r=un(e),a=un(e),s=un(e),n=s>>4,o=s>>1&7,c=1&s,l=un(e),u=un(e),d=un(e);t.info.vp9CodecInfo={profile:r,level:a,bitDepth:n,chromaSubsampling:o,videoFullRangeFlag:c,colourPrimaries:l,transferCharacteristics:u,matrixCoefficients:d}}break;case"av1C":{const t=this.currentTrack;if(!t)break;i("video"===t.info?.type),e.skip(1);const r=un(e),a=r>>5,s=31&r,n=un(e),o=n>>7,c=n>>6&1,l=n>>4&1,u=n>>3&1,d=n>>2&1,h=3&n,f=2===a&&c?n>>5&1?12:10:c?10:8;t.info.av1CodecInfo={profile:a,level:s,tier:o,bitDepth:f,monochrome:l,chromaSubsamplingX:u,chromaSubsamplingY:d,chromaSamplePosition:h}}break;case"colr":{const t=this.currentTrack;if(!t)break;i("video"===t.info?.type);if("nclx"!==In(e,4))break;const r=hn(e),a=hn(e),s=hn(e),n=Boolean(128&un(e));t.info.colorSpace={primaries:h[r],transfer:m[a],matrix:g[s],fullRange:n}}break;case"pasp":{const t=this.currentTrack;if(!t)break;i("video"===t.info?.type);const r=gn(e),a=gn(e);r>0&&a>0&&(r>a?t.info.squarePixelWidth=Math.round(t.info.width*r/a):t.info.squarePixelHeight=Math.round(t.info.height*a/r))}break;case"esds":{const t=this.currentTrack;if(!t)break;i("audio"===t.info?.type),e.skip(4);i(3===un(e)),qt(e),e.skip(2);const r=un(e),a=0!==(64&r),s=0!==(32&r);if(0!==(128&r)&&e.skip(2),a){const t=un(e);e.skip(t)}s&&e.skip(2);i(4===un(e));const n=qt(e),o=e.filePos,c=un(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":console.warn(`Unsupported audio codec (objectTypeIndication ${c}) - discarding track.`),e.skip(12),n>e.filePos-o){i(5===un(e));const r=qt(e);if(t.info.codecDescription=ln(e,r),"aac"===t.info.codec){const e=ge(t.info.codecDescription);null!==e.numberOfChannels&&(t.info.numberOfChannels=e.numberOfChannels),null!==e.sampleRate&&(t.info.sampleRate=e.sampleRate)}}}break;case"enda":{const t=this.currentTrack;if(!t)break;i("audio"===t.info?.type),t.info.pcmLittleEndian=!!(255&hn(e))}break;case"pcmC":{const t=this.currentTrack;if(!t)break;i("audio"===t.info?.type),e.skip(4);const r=un(e);t.info.pcmLittleEndian=Boolean(1&r),t.info.pcmSampleSize=un(e)}break;case"dOps":{const t=this.currentTrack;if(!t)break;i("audio"===t.info?.type),e.skip(1);const r=un(e),a=hn(e),s=gn(e),n=mn(e),o=un(e);let c;c=0!==o?ln(e,2+r):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,r),u.setUint16(10,a,!0),u.setUint32(12,s,!0),u.setInt16(16,n,!0),u.setUint8(18,o),l.set(c,19),t.info.codecDescription=l,t.info.numberOfChannels=r}break;case"dfLa":{const t=this.currentTrack;if(!t)break;i("audio"===t.info?.type),e.skip(4);const r=127,a=128,s=e.filePos;for(;e.filePos<$;){const i=un(e),s=fn(e);if((i&r)===Pt.STREAMINFO){e.skip(10);const i=gn(e),r=i>>>12,a=1+(i>>9&7);t.info.sampleRate=r,t.info.numberOfChannels=a,e.skip(20)}else e.skip(s);if(i&a)break}const n=e.filePos;e.filePos=s;const o=ln(e,n-s),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;i("audio"===t.info?.type);const r=ln(e,3),a=new fe(r),s=a.readBits(2);a.skipBits(8);const n=a.readBits(3),o=a.readBits(1);s<3&&(t.info.sampleRate=ze[s]),t.info.numberOfChannels=xt[n]+o}break;case"dec3":{const t=this.currentTrack;if(!t)break;i("audio"===t.info?.type);const r=(e=>{if(e.length<2)return null;const t=new fe(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}})(ln(e,j.contentSize));if(!r){console.warn("Invalid dec3 box contents, ignoring.");break}const a=At(r);null!==a&&(t.info.sampleRate=a),t.info.numberOfChannels=Ft(r)}break;case"stts":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4);const i=gn(e);let r=0,a=0;for(let s=0;se.id===i);if(!r)break;const a=gn(e),s=(12&a)>>2,n=3&a,o=[un,hn,fn,gn],c=o[(48&a)>>4],l=o[s],u=o[n],d=gn(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 i=0;ie.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},r?d.currentFragmentState.baseDataOffset=wn(e):l&&(d.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),a&&(d.currentFragmentState.sampleDescriptionIndex=gn(e)),s&&(d.currentFragmentState.defaultSampleDuration=gn(e)),n&&(d.currentFragmentState.defaultSampleSize=gn(e)),o&&(d.currentFragmentState.defaultSampleFlags=gn(e)),c&&(d.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{const t=this.currentTrack;if(!t)break;i(t.currentFragmentState);const r=un(e);e.skip(3);const a=0===r?gn(e):wn(e);t.currentFragmentState.startTimestamp=a}break;case"trun":{const t=this.currentTrack;if(!t)break;i(this.currentFragment),i(t.currentFragmentState);const r=un(e),a=fn(e),s=Boolean(1&a),n=Boolean(4&a),o=Boolean(256&a),c=Boolean(512&a),l=Boolean(1024&a),u=Boolean(2048&a),d=gn(e);let h=null;s&&(h=bn(e));let f,m=null;if(n&&(m=gn(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)),0===d){this.currentFragment.implicitBaseDataOffset=f.currentOffset;break}for(let p=0;p0&&(a=ln(e,r));const s=di(t);s.defaultSampleInfoSize=i,s.sampleSizes=a,s.sampleCount=r}break;case"saio":{const t=this.currentTrack;if(!t||!t.encryptionInfo)break;const i=un(e);if(1&fn(e)){const i=In(e,4),r=gn(e);if(i!==t.encryptionInfo.scheme||0!==r)break}const r=gn(e);if(0===r)break;r>1&&console.warn("Multiple saio entries are not supported; using the first offset only.");let a=0===i?gn(e):Number(wn(e));this.currentFragment&&(a+=this.currentFragment.moofOffset);di(t).offset=a}break;case"senc":{const t=this.currentTrack;if(!t||!t.encryptionInfo)break;i(this.currentFragment);const r=this.currentFragment.trackData.get(t.id);if(!r)break;e.skip(1);const a=fn(e),s=Boolean(2&a),n=gn(e),o=t.encryptionInfo.defaultPerSampleIvSize;i(null!==o);for(let i=0;i0?a.set(ln(e,o),0):a.set(t.encryptionInfo.defaultConstantIv,0);let n=null;if(s){const t=hn(e);n=[];for(let i=0;i0&&((z=this.metadataTags).trackNumber??(z.trackNumber=t)),i&&Number.isInteger(i)&&i>0&&((U=this.metadataTags).tracksTotal??(U.tracksTotal=i))}break;case"trkn":if(a instanceof Uint8Array&&a.length>=6){const e=c(a),t=e.getUint16(2,!1),i=e.getUint16(4,!1);t>0&&((q=this.metadataTags).trackNumber??(q.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=c(a),t=e.getUint16(2,!1),i=e.getUint16(4,!1);t>0&&((V=this.metadataTags).discNumber??(V.discNumber=t)),i>0&&((H=this.metadataTags).discsTotal??(H.discsTotal=i))}}}}}var Q,G;return e.filePos=$,!0}}class ti{constructor(e){this.internalTrack=e,this.packetToSampleIndex=new WeakMap,this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){const e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType();let i=0;for(const r of e.tracks)if(r.trackBacking.getType()===t&&i++,r===this.internalTrack)break;return i}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.internalCodecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}isRelativeToUnixEpoch(){return!1}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){const e=this.internalTrack;if(e.durationInMediaTimescale<=0)return null;i(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 D(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,t){const i=this.mapTimestampIntoTimescale(e),r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=ai(r,i),s=await this.fetchPacketForSampleIndex(a,t);return ui(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=P(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=C(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===a.fragment){const t=e.trackData.get(this.internalTrack.id).samples.findIndex((e,t)=>e.isKeyFrame&&t>a.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)}async fetchPacketForSampleIndex(e,t){if(-1===e)return null;const r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=ni(r,e);if(!a)return null;let s;if(t.metadataOnly)s=Dt;else{let t=this.internalTrack.demuxer.reader.requestSlice(a.sampleOffset,a.sampleSize);if(t instanceof Promise&&(t=await t),!t)return null;if(s=ln(t,a.sampleSize),this.internalTrack.encryptionAuxInfo){i(this.internalTrack.encryptionInfo);const t=await hi(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);ee.timestamp),d=-1!==u?this.internalTrack.fragmentLookupTable[u]:null,h=P(this.internalTrack.fragmentPositionCache,r,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>a)break}let e=n.reader.requestSliceRange(p,8,16);if(e instanceof Promise&&(e=await e),!e)break;const i=p,r=Lt(e);if(!r)break;if("moof"===r.name){o=await n.readFragment(i);const{sampleIndex:e,correctSampleFound:r}=t(o);if(r)return this.fetchPacketInFragment(o,e,s);-1!==e&&(c=o,l=e)}p=i+r.totalSize}if(d&&(!c||c.moofOffset{if("vp9"!==this.internalTrack.info.codec||this.internalTrack.info.vp9CodecInfo){if("av1"===this.internalTrack.info.codec&&!this.internalTrack.info.av1CodecInfo){const e=await this.getFirstPacket({});this.internalTrack.info.av1CodecInfo=e&&yt(e.data)}}else{const e=await this.getFirstPacket({});this.internalTrack.info.vp9CodecInfo=e&&kt(e.data)}const e={codec:ve(this.internalTrack.info),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0};return this.internalTrack.info.width===this.internalTrack.info.squarePixelWidth&&this.internalTrack.info.height===this.internalTrack.info.squarePixelHeight||(e.displayAspectWidth=this.internalTrack.info.squarePixelWidth,e.displayAspectHeight=this.internalTrack.info.squarePixelHeight),e})()):null}}class ri extends ti{constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getType(){return"audio"}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfig??(this.decoderConfig={codec:Ie(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}):null}}const ai=(e,t)=>{if(e.presentationTimestamps){const i=P(e.presentationTimestamps,t,e=>e.presentationTimestamp);return-1===i?-1:e.presentationTimestamps[i].sampleIndex}{const i=P(e.sampleTimingEntries,t,e=>e.startDecodeTimestamp);if(-1===i)return-1;const r=e.sampleTimingEntries[i];return r.startIndex+Math.min(Math.floor((t-r.startDecodeTimestamp)/r.delta),r.count-1)}},si=(e,t)=>{if(!e.keySampleIndices)return ai(e,t);if(e.presentationTimestamps){const i=P(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!==S(e.keySampleIndices,i,e=>e))return i}return-1}{const i=ai(e,t),r=P(e.keySampleIndices,i,e=>e);return e.keySampleIndices[r]??-1}},ni=(e,t)=>{const r=P(e.sampleTimingEntries,t,e=>e.startIndex),a=e.sampleTimingEntries[r];if(!a||a.startIndex+a.count<=t)return null;let s=a.startDecodeTimestamp+(t-a.startIndex)*a.delta;const n=P(e.sampleCompositionTimeOffsets,t,e=>e.startIndex),o=e.sampleCompositionTimeOffsets[n];o&&t-o.startIndexe.startSampleIndex),u=e.sampleToChunk[l];i(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 i=f;ie)}},oi=(e,t)=>{if(!e.keySampleIndices)return t+1;const i=P(e.keySampleIndices,t,e=>e);return e.keySampleIndices[i+1]??-1},ci=(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},li=e=>{const[t,i]=e,r=Math.atan2(i,t);return Number.isFinite(r)?r*(180/Math.PI):0},ui=e=>0===e.sampleSizes.length,di=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})},hi=async(e,t,r)=>{if(r.resolved)return r.resolved;if(null===r.offset||0===r.sampleCount)throw new Error("Incomplete saiz/saio info; cannot resolve encryption data.");let a=0;if(r.defaultSampleInfoSize>0)a=r.defaultSampleInfoSize*r.sampleCount;else{i(r.sampleSizes);for(let e=0;e0?r.defaultSampleInfoSize:r.sampleSizes[i],a=new Uint8Array(16);n>0?a.set(ln(s,n),0):a.set(t.defaultConstantIv,0);let c=null;if(e>n){const e=hn(s);c=[];for(let t=0;t{i(e.encryptionInfo);const s=e.encryptionInfo;i(null!==s.defaultKid);const n=s.defaultKid;let o;const c=e.demuxer.decryptionKeyCache.get(n);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(a){t=[...t,...a.psshBoxes].filter(e=>null===e.keyIds||e.keyIds.includes(n));for(let e=0;e{i(e.length%2===0);const t=new Uint8Array(e.length/2);for(let i=0;i{const s=new Uint8Array(16);s.set(r.iv,0);const n=await crypto.subtle.importKey("raw",e,{name:"AES-CTR"},!1,["decrypt"]),o=async e=>{const t=await crypto.subtle.decrypt({name:"AES-CTR",counter:s,length:64},n,e);return new Uint8Array(t)};if(!r.subsamples)return o(a);i(null!==t.defaultCryptByteBlock&&null!==t.defaultSkipByteBlock);const c=gi(r.subsamples,t.defaultCryptByteBlock,t.defaultSkipByteBlock);let l=0;for(const i of c)for(const e of i.perSubsample)l+=e.length;const u=new Uint8Array(l);let d=0;for(const i of c)for(const e of i.perSubsample)u.set(a.subarray(e.offset,e.offset+e.length),d),d+=e.length;const h=await o(u),f=new Uint8Array(a);let m=0;for(const i of c)for(const e of i.perSubsample)f.set(h.subarray(m,m+e.length),e.offset),m+=e.length;return f},pi=(e,t,r,a)=>{const s=new Zt;s.init({key:e,iv:r.iv});const n=t.defaultCryptByteBlock,o=t.defaultSkipByteBlock;if(i(null!==n&&null!==o),!r.subsamples){const e=new Uint8Array(a),t=Math.floor(a.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 ki,bi;(bi=ki||(ki={}))[bi.EBML=440786851]="EBML",bi[bi.EBMLVersion=17030]="EBMLVersion",bi[bi.EBMLReadVersion=17143]="EBMLReadVersion",bi[bi.EBMLMaxIDLength=17138]="EBMLMaxIDLength",bi[bi.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",bi[bi.DocType=17026]="DocType",bi[bi.DocTypeVersion=17031]="DocTypeVersion",bi[bi.DocTypeReadVersion=17029]="DocTypeReadVersion",bi[bi.Void=236]="Void",bi[bi.Segment=408125543]="Segment",bi[bi.SeekHead=290298740]="SeekHead",bi[bi.Seek=19899]="Seek",bi[bi.SeekID=21419]="SeekID",bi[bi.SeekPosition=21420]="SeekPosition",bi[bi.Duration=17545]="Duration",bi[bi.Info=357149030]="Info",bi[bi.TimestampScale=2807729]="TimestampScale",bi[bi.MuxingApp=19840]="MuxingApp",bi[bi.WritingApp=22337]="WritingApp",bi[bi.Tracks=374648427]="Tracks",bi[bi.TrackEntry=174]="TrackEntry",bi[bi.TrackNumber=215]="TrackNumber",bi[bi.TrackUID=29637]="TrackUID",bi[bi.TrackType=131]="TrackType",bi[bi.FlagEnabled=185]="FlagEnabled",bi[bi.FlagDefault=136]="FlagDefault",bi[bi.FlagForced=21930]="FlagForced",bi[bi.FlagOriginal=21934]="FlagOriginal",bi[bi.FlagHearingImpaired=21931]="FlagHearingImpaired",bi[bi.FlagVisualImpaired=21932]="FlagVisualImpaired",bi[bi.FlagCommentary=21935]="FlagCommentary",bi[bi.FlagLacing=156]="FlagLacing",bi[bi.Name=21358]="Name",bi[bi.Language=2274716]="Language",bi[bi.LanguageBCP47=2274717]="LanguageBCP47",bi[bi.CodecID=134]="CodecID",bi[bi.CodecPrivate=25506]="CodecPrivate",bi[bi.CodecDelay=22186]="CodecDelay",bi[bi.SeekPreRoll=22203]="SeekPreRoll",bi[bi.DefaultDuration=2352003]="DefaultDuration",bi[bi.Video=224]="Video",bi[bi.PixelWidth=176]="PixelWidth",bi[bi.PixelHeight=186]="PixelHeight",bi[bi.DisplayWidth=21680]="DisplayWidth",bi[bi.DisplayHeight=21690]="DisplayHeight",bi[bi.DisplayUnit=21682]="DisplayUnit",bi[bi.AlphaMode=21440]="AlphaMode",bi[bi.Audio=225]="Audio",bi[bi.SamplingFrequency=181]="SamplingFrequency",bi[bi.Channels=159]="Channels",bi[bi.BitDepth=25188]="BitDepth",bi[bi.SimpleBlock=163]="SimpleBlock",bi[bi.BlockGroup=160]="BlockGroup",bi[bi.Block=161]="Block",bi[bi.BlockAdditions=30113]="BlockAdditions",bi[bi.BlockMore=166]="BlockMore",bi[bi.BlockAdditional=165]="BlockAdditional",bi[bi.BlockAddID=238]="BlockAddID",bi[bi.BlockDuration=155]="BlockDuration",bi[bi.ReferenceBlock=251]="ReferenceBlock",bi[bi.Cluster=524531317]="Cluster",bi[bi.Timestamp=231]="Timestamp",bi[bi.Cues=475249515]="Cues",bi[bi.CuePoint=187]="CuePoint",bi[bi.CueTime=179]="CueTime",bi[bi.CueTrackPositions=183]="CueTrackPositions",bi[bi.CueTrack=247]="CueTrack",bi[bi.CueClusterPosition=241]="CueClusterPosition",bi[bi.Colour=21936]="Colour",bi[bi.MatrixCoefficients=21937]="MatrixCoefficients",bi[bi.TransferCharacteristics=21946]="TransferCharacteristics",bi[bi.Primaries=21947]="Primaries",bi[bi.Range=21945]="Range",bi[bi.Projection=30320]="Projection",bi[bi.ProjectionType=30321]="ProjectionType",bi[bi.ProjectionPoseRoll=30325]="ProjectionPoseRoll",bi[bi.Attachments=423732329]="Attachments",bi[bi.AttachedFile=24999]="AttachedFile",bi[bi.FileDescription=18046]="FileDescription",bi[bi.FileName=18030]="FileName",bi[bi.FileMediaType=18016]="FileMediaType",bi[bi.FileData=18012]="FileData",bi[bi.FileUID=18094]="FileUID",bi[bi.Chapters=272869232]="Chapters",bi[bi.Tags=307544935]="Tags",bi[bi.Tag=29555]="Tag",bi[bi.Targets=25536]="Targets",bi[bi.TargetTypeValue=26826]="TargetTypeValue",bi[bi.TargetType=25546]="TargetType",bi[bi.TagTrackUID=25541]="TagTrackUID",bi[bi.TagEditionUID=25545]="TagEditionUID",bi[bi.TagChapterUID=25540]="TagChapterUID",bi[bi.TagAttachmentUID=25542]="TagAttachmentUID",bi[bi.SimpleTag=26568]="SimpleTag",bi[bi.TagName=17827]="TagName",bi[bi.TagLanguage=17530]="TagLanguage",bi[bi.TagString=17543]="TagString",bi[bi.TagBinary=17541]="TagBinary",bi[bi.ContentEncodings=28032]="ContentEncodings",bi[bi.ContentEncoding=25152]="ContentEncoding",bi[bi.ContentEncodingOrder=20529]="ContentEncodingOrder",bi[bi.ContentEncodingScope=20530]="ContentEncodingScope",bi[bi.ContentCompression=20532]="ContentCompression",bi[bi.ContentCompAlgo=16980]="ContentCompAlgo",bi[bi.ContentCompSettings=16981]="ContentCompSettings",bi[bi.ContentEncryption=20533]="ContentEncryption";const yi=[ki.EBML,ki.Segment],wi=[ki.SeekHead,ki.Info,ki.Cluster,ki.Tracks,ki.Cues,ki.Attachments,ki.Chapters,ki.Tags],Ti=[...yi,...wi],Si=16,Pi=e=>{if(e.remainingLength<1)return null;const t=un(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=un(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=Pi(e);if(null===t)return null;if(e.remainingLength{if(e.remainingLength<1)return null;if(255===un(e))return;e.skip(-1);const t=vi(e);return null===t?null:72057594037927940!==t?t:void 0},Bi=e=>{i(e.remainingLength>=2);const t=xi(e);if(null===t)return null;const r=Ci(e);return null===r?null:{id:t,size:r}},Ei=(e,t)=>{const i=ln(e,t);let r=0;for(;r{const i=ln(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?Pn(e):vn(e)},Fi=async(e,t,i,r)=>{const a=new Set(i);let s=t;for(;null===r||ss?r:s,found:!1}},Ri=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,Si);if(t instanceof Promise&&(t=await t),!t)break;const i=Bi(t);if(!i)break;const r=i.id;let s=i.size;const n=t.filePos;if(r===ki.EBML){ji(s);let e=this.reader.requestSlice(n,s);if(e instanceof Promise&&(e=await e),!e)break;this.readContiguousElements(e)}else if(r===ki.Segment){if(await this.readSegment(n,s),void 0===s)break;if(null===this.reader.fileSize)break}else if(r===ki.Cluster){if(null===this.reader.fileSize)break;if(void 0===s){s=(await Fi(this.reader,n,Ti,this.reader.fileSize)).pos-n}const e=a(this.segments);e&&(e.elementEndPos=n+s)}ji(s),e=n+s}})())}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=Zi[o].flag;this.currentSegment[e]=!0,ji(s);let t=this.reader.requestSlice(n,s);t instanceof Promise&&(t=await t),t&&this.readContiguousElements(t)}else if(a===ki.Tags||a===ki.Attachments){a===ki.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,ji(s);let e=this.reader.requestSlice(n,s);e instanceof Promise&&(e=await e),e&&this.readContiguousElements(e)}else if(a===ki.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=Zi.find(e=>e.id===n.id);if(!t)continue;if(this.currentSegment[t.flag])continue;let i=this.reader.requestSliceRange(e+n.segmentPosition,2,Si);if(i instanceof Promise&&(i=await i),!i)continue;const r=Bi(i);if(!r)continue;const{id:a,size:s}=r;if(a!==t.id)continue;ji(s),this.currentSegment[t.flag]=!0;let o=this.reader.requestSlice(i.filePos,s);o instanceof Promise&&(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 r=this.reader.requestSliceRange(e,2,Si);r instanceof Promise&&(r=await r),i(r);const s=e,n=Bi(r);i(n);i(n.id===ki.Cluster);let o=n.size;const c=r.filePos;if(void 0===o){o=(await Fi(this.reader,c,Ti,t.elementEndPos)).pos-c}let l=this.reader.requestSlice(c,o);l instanceof Promise&&(l=await l);const u={segment:t,elementStartPos:s,elementEndPos:c+o,dataStartPos:c,timestamp:-1,trackData:new Map};if(this.currentCluster=u,l){const e=this.readContiguousElements(l,Ti);u.elementEndPos=e}for(const[,d]of u.trackData){const e=d.track;i(d.blocks.length>0);let t=!1;for(let i=0;i({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp);for(let i=0;i({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp));const r=d.blocks[d.presentationTimestamps[0].blockIndex],n=d.blocks[a(d.presentationTimestamps).blockIndex];d.startTimestamp=r.timestamp,d.endTimestamp=n.timestamp+n.duration;const o=P(e.clusterPositionCache,d.startTimestamp,e=>e.startTimestamp);-1!==o&&e.clusterPositionCache[o].elementStartPos===s||e.clusterPositionCache.splice(o+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 r=0;r=2;){const i=e.filePos;if(!this.traverseElement(e,t))return i}return e.filePos}traverseElement(e,t){const a=Bi(e);if(!a)return!1;if(t&&t.includes(a.id))return!1;const{id:s,size:n}=a,o=e.filePos;switch(ji(n),s){case ki.DocType:this.isWebM="webm"===Ei(e,n);break;case ki.Seek:{if(!this.currentSegment)break;const t={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(t),this.readContiguousElements(e.slice(o,n)),-1!==t.id&&-1!==t.segmentPosition||this.currentSegment.seekEntries.pop()}break;case ki.SeekID:{const t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.id=Ii(e,n)}break;case ki.SeekPosition:{const t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.segmentPosition=Ii(e,n)}break;case ki.TimestampScale:if(!this.currentSegment)break;this.currentSegment.timestampScale=Ii(e,n),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale;break;case ki.Duration:if(!this.currentSegment)break;this.currentSegment.duration=Ai(e,n);break;case ki.TrackEntry:if(!this.currentSegment)break;if(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...he,primary:!1},trackBacking:null,codecId:null,codecPrivate:null,defaultDuration:null,defaultDurationNs:null,name:null,languageCode:"eng",hasLanguageBcp47:!1,decodingInstructions:[],info:null},this.readContiguousElements(e.slice(o,n)),!this.currentTrack)break;if(this.currentTrack.decodingInstructions.some(e=>"decompress"!==e.data?.type||e.scope!==Qi.Block||e.data.algorithm!==Yi.HeaderStripping)&&(console.warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`),this.currentTrack=null),this.currentTrack&&-1!==this.currentTrack.id&&this.currentTrack.codecId&&this.currentTrack.info){const e=this.currentTrack.codecId.indexOf("/"),t=-1===e?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,e);if("video"===this.currentTrack.info.type&&-1!==this.currentTrack.info.width&&-1!==this.currentTrack.info.height){if(this.currentTrack.info.squarePixelWidth=this.currentTrack.info.width,this.currentTrack.info.squarePixelHeight=this.currentTrack.info.height,null!==this.currentTrack.info.displayWidth&&null!==this.currentTrack.info.displayHeight){const e=this.currentTrack.info.displayWidth*this.currentTrack.info.height,t=this.currentTrack.info.displayHeight*this.currentTrack.info.width;e>0&&t>0&&(e>t?this.currentTrack.info.squarePixelWidth=Math.round(this.currentTrack.info.width*e/t):this.currentTrack.info.squarePixelHeight=Math.round(this.currentTrack.info.height*t/e))}this.currentTrack.codecId===Di?(this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===Mi?(this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Ni?this.currentTrack.info.codec="vp8":t===Oi?this.currentTrack.info.codec="vp9":t===Li&&(this.currentTrack.info.codec="av1");const e=this.currentTrack;this.currentTrack.trackBacking=new rr(e),this.currentSegment.tracks.push(this.currentTrack)}else if("audio"===this.currentTrack.info.type){t===zi?(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===Ui?this.currentTrack.info.codec="mp3":t===qi?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=xe):t===Wi?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Vi?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Hi?(this.currentTrack.info.codec="ac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Ki?(this.currentTrack.info.codec="eac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):"A_PCM/INT/LIT"===this.currentTrack.codecId?8===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-u8":16===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s16":24===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s24":32===this.currentTrack.info.bitDepth&&(this.currentTrack.info.codec="pcm-s32"):"A_PCM/INT/BIG"===this.currentTrack.codecId?8===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-u8":16===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s16be":24===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s24be":32===this.currentTrack.info.bitDepth&&(this.currentTrack.info.codec="pcm-s32be"):"A_PCM/FLOAT/IEEE"===this.currentTrack.codecId&&(32===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-f32":64===this.currentTrack.info.bitDepth&&(this.currentTrack.info.codec="pcm-f64"));const e=this.currentTrack;this.currentTrack.trackBacking=new ar(e),this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null;break;case ki.TrackNumber:if(!this.currentTrack)break;this.currentTrack.id=Ii(e,n);break;case ki.TrackType:{if(!this.currentTrack)break;const t=Ii(e,n);1===t?this.currentTrack.info={type:"video",width:-1,height:-1,displayWidth:null,displayHeight:null,displayUnit:null,squarePixelWidth:-1,squarePixelHeight:-1,rotation:0,codec:null,codecDescription:null,colorSpace:null,alphaMode:!1}:2===t&&(this.currentTrack.info={type:"audio",numberOfChannels:1,sampleRate:8e3,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case ki.FlagEnabled:if(!this.currentTrack)break;Ii(e,n)||(this.currentTrack=null);break;case ki.FlagDefault:if(!this.currentTrack)break;this.currentTrack.disposition.default=!!Ii(e,n);break;case ki.FlagForced:if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!Ii(e,n);break;case ki.FlagOriginal:if(!this.currentTrack)break;this.currentTrack.disposition.original=!!Ii(e,n);break;case ki.FlagHearingImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!Ii(e,n);break;case ki.FlagVisualImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!Ii(e,n);break;case ki.FlagCommentary:if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!Ii(e,n);break;case ki.CodecID:if(!this.currentTrack)break;this.currentTrack.codecId=Ei(e,n);break;case ki.CodecPrivate:if(!this.currentTrack)break;this.currentTrack.codecPrivate=ln(e,n);break;case ki.DefaultDuration:if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=Ii(e,n);break;case ki.Name:if(!this.currentTrack)break;this.currentTrack.name=_i(e,n);break;case ki.Language:if(!this.currentTrack)break;if(this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=Ei(e,n),L(this.currentTrack.languageCode)||(this.currentTrack.languageCode=R);break;case ki.LanguageBCP47:{if(!this.currentTrack)break;const t=Ei(e,n).split("-")[0];this.currentTrack.languageCode=t||R,this.currentTrack.hasLanguageBcp47=!0}break;case ki.Video:if("video"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(o,n));break;case ki.PixelWidth:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.width=Ii(e,n);break;case ki.PixelHeight:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.height=Ii(e,n);break;case ki.DisplayWidth:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.displayWidth=Ii(e,n);break;case ki.DisplayHeight:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.displayHeight=Ii(e,n);break;case ki.DisplayUnit:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.displayUnit=Ii(e,n);break;case ki.AlphaMode:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.alphaMode=1===Ii(e,n);break;case ki.Colour:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.colorSpace={},this.readContiguousElements(e.slice(o,n));break;case ki.MatrixCoefficients:{if("video"!==this.currentTrack?.info?.type||!this.currentTrack.info.colorSpace)break;const t=Ii(e,n),i=g[t]??null;this.currentTrack.info.colorSpace.matrix=i}break;case ki.Range:if("video"!==this.currentTrack?.info?.type||!this.currentTrack.info.colorSpace)break;this.currentTrack.info.colorSpace.fullRange=2===Ii(e,n);break;case ki.TransferCharacteristics:{if("video"!==this.currentTrack?.info?.type||!this.currentTrack.info.colorSpace)break;const t=Ii(e,n),i=m[t]??null;this.currentTrack.info.colorSpace.transfer=i}break;case ki.Primaries:{if("video"!==this.currentTrack?.info?.type||!this.currentTrack.info.colorSpace)break;const t=Ii(e,n),i=h[t]??null;this.currentTrack.info.colorSpace.primaries=i}break;case ki.Projection:if("video"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(o,n));break;case ki.ProjectionPoseRoll:{if("video"!==this.currentTrack?.info?.type)break;const t=-Ai(e,n);try{this.currentTrack.info.rotation=r(t)}catch{}}break;case ki.Audio:if("audio"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(o,n));break;case ki.SamplingFrequency:if("audio"!==this.currentTrack?.info?.type)break;this.currentTrack.info.sampleRate=Ai(e,n);break;case ki.Channels:if("audio"!==this.currentTrack?.info?.type)break;this.currentTrack.info.numberOfChannels=Ii(e,n);break;case ki.BitDepth:if("audio"!==this.currentTrack?.info?.type)break;this.currentTrack.info.bitDepth=Ii(e,n);break;case ki.CuePoint:if(!this.currentSegment)break;this.readContiguousElements(e.slice(o,n)),this.currentCueTime=null;break;case ki.CueTime:this.currentCueTime=Ii(e,n);break;case ki.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(o,n)),-1!==t.trackId&&-1!==t.clusterPosition||this.currentSegment.cuePoints.pop()}break;case ki.CueTrack:{const t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;t.trackId=Ii(e,n)}break;case ki.CueClusterPosition:{const t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;i(this.currentSegment),t.clusterPosition=this.currentSegment.dataStartPos+Ii(e,n)}break;case ki.Timestamp:if(!this.currentCluster)break;this.currentCluster.timestamp=Ii(e,n);break;case ki.SimpleBlock:{if(!this.currentCluster)break;const t=vi(e);if(null===t)break;const i=this.getTrackDataInCluster(this.currentCluster,t);if(!i)break;const r=mn(e),a=un(e),s=a>>1&3;let c=!!(128&a);"audio"===i.track.info?.type&&i.track.info.codec&&(c=!0);const l=ln(e,n-(e.filePos-o)),u=i.track.decodingInstructions.length>0;i.blocks.push({timestamp:r,duration:0,isKeyFrame:c,data:l,lacing:s,decoded:!u,mainAdditional:null})}break;case ki.BlockGroup:if(!this.currentCluster)break;this.readContiguousElements(e.slice(o,n)),this.currentBlock=null;break;case ki.Block:{if(!this.currentCluster)break;const t=vi(e);if(null===t)break;const i=this.getTrackDataInCluster(this.currentCluster,t);if(!i)break;const r=mn(e),a=un(e)>>1&3,s=ln(e,n-(e.filePos-o)),c=i.track.decodingInstructions.length>0;this.currentBlock={timestamp:r,duration:0,isKeyFrame:!0,data:s,lacing:a,decoded:!c,mainAdditional:null},i.blocks.push(this.currentBlock)}break;case ki.BlockAdditions:this.readContiguousElements(e.slice(o,n));break;case ki.BlockMore:if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(o,n)),this.currentBlockAdditional.data&&1===this.currentBlockAdditional.addId&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null;break;case ki.BlockAdditional:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=ln(e,n);break;case ki.BlockAddID:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=Ii(e,n);break;case ki.BlockDuration:if(!this.currentBlock)break;this.currentBlock.duration=Ii(e,n);break;case ki.ReferenceBlock:if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1;break;case ki.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(o,n));break;case ki.Targets:this.readContiguousElements(e.slice(o,n));break;case ki.TargetTypeValue:50!==Ii(e,n)&&(this.currentTagTargetIsMovie=!1);break;case ki.TagTrackUID:case ki.TagEditionUID:case ki.TagChapterUID:case ki.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case ki.SimpleTag:if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(o,n));break;case ki.TagName:this.currentSimpleTagName=_i(e,n);break;case ki.TagString:{if(!this.currentSimpleTagName)break;const t=_i(e,n);this.processTagValue(this.currentSimpleTagName,t)}break;case ki.TagBinary:{if(!this.currentSimpleTagName)break;const t=ln(e,n);this.processTagValue(this.currentSimpleTagName,t)}break;case ki.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(o,n));const t=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(t.raw??(t.raw={}),t.raw[this.currentAttachedFile.fileUid.toString()]=new de(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 ki.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 ki.ContentEncoding:this.currentDecodingInstruction={order:0,scope:Qi.Block,data:null},this.readContiguousElements(e.slice(o,n)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case ki.ContentEncodingOrder:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=Ii(e,n);break;case ki.ContentEncodingScope:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=Ii(e,n);break;case ki.ContentCompression:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:Yi.Zlib,settings:null},this.readContiguousElements(e.slice(o,n));break;case ki.ContentCompAlgo:if("decompress"!==this.currentDecodingInstruction?.data?.type)break;this.currentDecodingInstruction.data.algorithm=Ii(e,n);break;case ki.ContentCompSettings:if("decompress"!==this.currentDecodingInstruction?.data?.type)break;this.currentDecodingInstruction.data.settings=ln(e,n);break;case ki.ContentEncryption:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}return e.filePos=o+n,!0}decodeBlockData(e,t){i(e.decodingInstructions.length>0);let r=t;for(const a of e.decodingInstructions)if(i(a.data),"decompress"===a.data.type)if(a.data.algorithm===Yi.HeaderStripping)if(a.data.settings&&a.data.settings.length>0){const e=a.data.settings,t=new Uint8Array(e.length+r.length);t.set(e,0),t.set(r,e.length),r=t}return r}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))}}}}class ir{constructor(e){this.internalTrack=e,this.packetToClusterLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){const e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType();let i=0;for(const r of e.segments)for(const e of r.tracks)if(e.trackBacking.getType()===t&&i++,e===this.internalTrack)break;return i}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.codecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.segment.timestampFactor}isRelativeToUnixEpoch(){return!1}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){const e=this.internalTrack.segment;if(e.duration<=0)return null;let t=e.duration/e.timestampFactor;const i=await this.getFirstPacket({metadataOnly:!0});return t+=i?.timestamp??0,t}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 D(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=P(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=C(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===r.cluster){const t=e.trackData.get(this.internalTrack.id).blocks.findIndex((e,t)=>e.isKeyFrame&&t>r.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)}async fetchPacketInCluster(e,t,r){if(-1===t)return null;const a=e.trackData.get(this.internalTrack.id).blocks[t];i(a),a.decoded||(a.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,a.data),a.decoded=!0);const s=r.metadataOnly?Dt:a.data,n=a.timestamp/this.internalTrack.segment.timestampFactor,o=a.duration/this.internalTrack.segment.timestampFactor,c={};a.mainAdditional&&"video"===this.internalTrack.info?.type&&this.internalTrack.info.alphaMode&&(c.alpha=r.metadataOnly?Dt:a.mainAdditional,c.alphaByteLength=a.mainAdditional.byteLength);const l=new Mt(s,a.isKeyFrame?"key":"delta",n,o,e.dataStartPos+t,a.data.byteLength,c);return this.packetToClusterLocation.set(l,{cluster:e,blockIndex:t}),l}async performClusterLookup(e,t,r,a,s){const{demuxer:n,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,s);-1!==i&&(l=e,u=i)}const d=P(this.internalTrack.cuePoints,r,e=>e.time),h=-1!==d?this.internalTrack.cuePoints[d]:null,f=P(this.internalTrack.clusterPositionCache,r,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>a)break}let e=n.reader.requestSliceRange(g,2,Si);if(e instanceof Promise&&(e=await e),!e)break;const r=g,d=Bi(e);if(!d||!wi.includes(d.id)&&d.id!==ki.Void){const e=await Ri(n.reader,r,wi,Math.min(o.elementEndPos??1/0,r+er));if(e){g=e;continue}break}const h=d.id;let f=d.size;const m=e.filePos;if(h===ki.Cluster){c=await n.readCluster(r,o),f=c.elementEndPos-m;const{blockIndex:e,correctBlockFound:i}=t(c);if(i)return this.fetchPacketInCluster(c,e,s);-1!==e&&(l=c,u=e)}if(void 0===f){i(h!==ki.Cluster);f=(await Fi(n.reader,m,Ti,o.elementEndPos)).pos-m}const p=m+f;if(null===o.elementEndPos){let e=n.reader.requestSliceRange(p,2,Si);if(e instanceof Promise&&(e=await e),!e)break;if(xi(e)===ki.Segment){o.elementEndPos=p;break}}g=p}if(h&&(!l||l.elementStartPos{let e=null;("vp9"===this.internalTrack.info.codec||"av1"===this.internalTrack.info.codec||"avc"===this.internalTrack.info.codec&&!this.internalTrack.info.codecDescription||"hevc"===this.internalTrack.info.codec&&!this.internalTrack.info.codecDescription)&&(e=await this.getFirstPacket({}));const t={codec:ve({width:this.internalTrack.info.width,height:this.internalTrack.info.height,codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,colorSpace:this.internalTrack.info.colorSpace,avcType:1,avcCodecInfo:"avc"===this.internalTrack.info.codec&&e?Ze(e.data):null,hevcCodecInfo:"hevc"===this.internalTrack.info.codec&&e?nt(e.data):null,vp9CodecInfo:"vp9"===this.internalTrack.info.codec&&e?kt(e.data):null,av1CodecInfo:"av1"===this.internalTrack.info.codec&&e?yt(e.data):null}),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0};return this.internalTrack.info.width===this.internalTrack.info.squarePixelWidth&&this.internalTrack.info.height===this.internalTrack.info.squarePixelHeight||(t.displayAspectWidth=this.internalTrack.info.squarePixelWidth,t.displayAspectHeight=this.internalTrack.info.squarePixelHeight),t})()):null}}class ar extends ir{constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getType(){return"audio"}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfig??(this.decoderConfig={codec:Ie({codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,aacCodecInfo:this.internalTrack.info.aacCodecInfo}),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}):null}}const sr=async(e,t,i)=>{let r=t;for(;null===i||r=4;){const t=a.filePos,i=gn(a),s=null!==e.fileSize?e.fileSize-r:null,n=Me(i,s);if(n.header)return{header:n.header,startPos:r};a.filePos=t+n.bytesAdvanced,r=a.filePos}}return null};class nr extends Rt{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.firstFrameHeaderPos=null,this.loadedSamples=[],this.metadataTags=null,this.xingData=null,this.trackBackings=[],this.readingMutex=new 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)throw new Error("No valid MP3 frame found.");this.trackBackings=[new or(this)]})())}async advanceReader(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,Fn);if(e instanceof Promise&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const t=Nn(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}const e=await sr(this.reader,this.lastLoadedPos,this.reader.fileSize);if(!e)return void(this.lastSampleLoaded=!0);const t=e.header;this.lastLoadedPos=e.startPos+t.totalSize-1;const i=De(t.mpegVersionId,t.channel);let r=this.reader.requestSlice(e.startPos+i,4);if(r instanceof Promise&&(r=await r),r){const t=gn(r);if(t===Fe||t===Re){if(!this.xingData){let t=this.reader.requestSlice(e.startPos+i+4,12);if(t instanceof Promise&&(t=await t),t){const e=ln(t,12),i=c(e),r=i.getUint32(0,!1);this.xingData={frameCount:r&Oe.FrameCount?i.getUint32(4,!1):null,fileSize:r&Oe.FileSize?i.getUint32(8,!1):null}}}return}}this.firstFrameHeader||(this.firstFrameHeader=t,this.firstFrameHeaderPos=e.startPos),t.sampleRate!==this.firstFrameHeader.sampleRate&&console.warn(`MP3 changed sample rate mid-file: ${this.firstFrameHeader.sampleRate} Hz to ${t.sampleRate} Hz. Might be a bug, so please report this file.`);const 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,Fn);if(i instanceof Promise&&(i=await i),!i)break;const r=Nn(i);if(!r)break;t=!0;let a=this.reader.requestSlice(i.filePos,r.size);if(a instanceof Promise&&(a=await a),!a)break;On(a,r,this.metadataTags),e=i.filePos+r.size}if(!t&&null!==this.reader.fileSize&&this.reader.fileSize>=An){let e=this.reader.requestSlice(this.reader.fileSize-An,An);e instanceof Promise&&(e=await e),i(e);"TAG"===In(e,3)&&Dn(e,this.metadataTags)}return this.metadataTags}finally{e()}}}class or{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}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){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 i=(t=e.firstFrameHeader.lowSamplingFrequency,r=e.firstFrameHeader.layer,a=e.firstFrameHeader.bitrate,s=e.firstFrameHeader.sampleRate,0===r?0:1===r?144*a/(s<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=P(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 ur=e=>{const t=c(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},dr=(e,t,r)=>{let a=0,s=null;if(e.length>0)if("vorbis"===t.codec){i(t.vorbisInfo);const n=(1<<(e=>{let t=0;for(;e;)t++,e>>=1;return t})(t.vorbisInfo.modeBlockflags.length-1))-1<<1,o=(e[0]&n)>>1;if(o>=t.vorbisInfo.modeBlockflags.length)throw new Error("Invalid mode number.");let c=r;const l=t.vorbisInfo.modeBlockflags[o];if(s=t.vorbisInfo.blocksizes[l],1===l){const i=1+(1|n),r=e[0]&i?1:0;c=t.vorbisInfo.blocksizes[r]}a=null!==c?c+s>>2:0}else if("opus"===t.codec){a=(e=>{const t=e[0]>>3;return{durationInSamples:wt[t]}})(e).durationInSamples}return{durationInSamples:a,vorbisBlockSize:s}},hr=27,fr=282,mr=e=>{const t=e.filePos;if(kn(e)!==cr)return null;e.skip(1);const i=un(e),r=Sn(e),a=kn(e),s=kn(e),n=kn(e),o=un(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}},pr=(e,t)=>{for(;e.filePos>>8&255)===i||(t>>>16&255)===i||(t>>>24&255)===i){if(e.skip(-4),t===cr)return!0;e.skip(1)}}return!1};class gr extends Rt{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,hr,fr);if(t instanceof Promise&&(t=await t),!t)break;const i=mr(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 kr(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 l=c(e.data);t.numberOfChannels=l.getUint8(11),t.sampleRate=l.getUint32(12,!0);const u=l.getUint8(28);t.codecInfo.vorbisInfo={blocksizes:[1<<(15&u),1<<(u>>4)],modeBlockflags:Tt(a.data).modeBlockflags},It(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=c(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=xe,t.codecInfo.opusInfo={preSkip:a.preSkip},It(r.data.subarray(8),this.metadataTags)}async readPacket(e,t){i(te+t.length,0);if(0===c)return null;const l=new Uint8Array(c);let u=0;for(let i=0;i{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 kr{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?xe: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}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 i(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 R}getDisposition(){return{...he,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:a}=dr(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),s=new Mt(i.metadataOnly?Dt: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){i(this.bitstream.lastMetadataPacket);const t=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let r=0;"opus"===this.bitstream.codecInfo.codec&&(i(this.bitstream.codecInfo.opusInfo),r-=this.bitstream.codecInfo.opusInfo.preSkip);const a=await this.demuxer.readPacket(t.startPage,t.startSegmentIndex);return this.createEncodedPacketFromOggPacket(a,{timestampInSamples:r,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 r=D(e*this.internalSampleRate);if(0===r)return this.getFirstPacket(t);if(r<0)return null;i(this.bitstream.lastMetadataPacket);const a=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!a)return null;let s=a.startPage,n=this.demuxer.reader.fileSize;const o=[s];e:for(;s.headerStartPos+s.totalSizer?n=u.headerStartPos:(s=u,o.push(u));continue e}a=u.headerStartPos+u.totalSize}}let c=a.startPage;for(const i of o){if(i.granulePosition===s.granulePosition)break;(!c||i.headerStartPos>c.headerStartPos)&&(c=i)}let l=c;const u=[l];for(;l.serialNumber!==this.bitstream.serialNumber||l.granulePosition!==s.granulePosition;){const e=l.headerStartPos+l.totalSize;let t=this.demuxer.reader.requestSliceRange(e,hr,fr);t instanceof Promise&&(t=await t),i(t);const r=mr(t);i(r),l=r,l.serialNumber===this.bitstream.serialNumber&&u.push(l)}i(-1!==l.granulePosition);let d,h,f=null,m=l,p=0;if(l.headerStartPos===a.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:Dt,endPage:m,endSegmentIndex:p};if(await this.demuxer.findNextPacketStart(e)){const e=yr(u,l,f);i(e);const t=br(u,e.page,e.segmentIndex);t&&(l=t.page,f=t.segmentIndex)}else for(;;){const e=yr(u,l,f);if(!e)break;const t=br(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;){i(null!==f);const e=await this.demuxer.readPacket(l,f);if(!e)break;if(!(l.headerStartPos===a.startPage.headerStartPos&&fr||Math.max(s.timestampInSamples,0)===r))break}const s=await this.demuxer.findNextPacketStart(e);if(!s)break;l=s.startPage,f=s.startSegmentIndex}return g}async getPacketSequential(e,t){const r=await this.sequentialScanMutex.acquire();try{const r=D(e*this.internalSampleRate);e=r/this.internalSampleRate;const s=P(this.sequentialScanCache,r,e=>e.timestampInSamples);let n;if(-1!==s){const e=this.sequentialScanCache[s];n=this.createEncodedPacketFromOggPacket(e.packet,{timestampInSamples:e.timestampInSamples,vorbisLastBlocksize:e.vorbisLastBlockSize},t)}else n=await this.getFirstPacket(t);let o=0;for(;n&&n.timestampe)break;if(n=r,o++,100===o){o=0;const e=this.encodedPacketToMetadata.get(n);i(e),this.sequentialScanCache.length>0&&i(a(this.sequentialScanCache).timestampInSamples<=e.timestampInSamples),this.sequentialScanCache.push(e)}}return n}finally{r()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const br=(e,t,r)=>{let a=t,s=r;e:for(;;){for(s--;s>=0;s--){if(a.lacingValues[s]<255){s++;break e}}i(-1===s);if(!(1&a.headerType)){s=0;break}const t=x(e,e=>e.headerStartPos{if(i>0)return{page:t,segmentIndex:i-1};const r=x(e,e=>e.headerStartPos{let e=this.reader.requestSlice(0,12);e instanceof Promise&&(e=await e),i(e);const t=In(e,4),r="RIFX"!==t,a="RF64"===t,s=pn(e,r);let n=a?this.reader.fileSize:Math.min(s+8,this.reader.fileSize??1/0);if("WAVE"!==In(e,4))throw new Error("Invalid WAVE file - wrong format");let o=0,c=null,l=e.filePos;for(;null===n||l=18&&357!==a){const e=dn(r,i),s=t-18;if(Math.min(s,e)>=22&&a===wr.EXTENSIBLE){r.skip(6);const e=ln(r,16);a=e[0]|e[1]<<8}}a!==wr.MULAW&&a!==wr.ALAW||(c=8),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(m instanceof Promise&&(m=await m),!m)return;const p=In(m,4);if("INFO"!==p&&"INF0"!==p)return;let g=m.filePos;for(;g<=e+t-8;){m.filePos=g;const e=In(m,4),t=pn(m,i),p=ln(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(b);Number.isNaN(e.getTime())||((u=this.metadataTags).date??(u.date=e))}break;case"YEAR":{const e=Number.parseInt(b,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=b);break;case"ICMT":case"CMNT":case"COMM":(f=this.metadataTags).comment??(f.comment=b)}g+=8+t+(1&t)}}async parseId3Chunk(e,t){let i=this.reader.requestSlice(e,t);if(i instanceof Promise&&(i=await i),!i)return;const r=Nn(i);if(r){const a=t-Fn;if(r.size=Math.min(r.size,a),r.size>0){const t=i.slice(e+Fn,r.size);On(t,r,this.metadataTags)}}}getCodec(){if(i(this.audioInfo),this.audioInfo.format===wr.MULAW)return"ulaw";if(this.audioInfo.format===wr.ALAW)return"alaw";if(this.audioInfo.format===wr.PCM){if(1===this.audioInfo.sampleSizeInBytes)return"pcm-u8";if(2===this.audioInfo.sampleSizeInBytes)return"pcm-s16";if(3===this.audioInfo.sampleSizeInBytes)return"pcm-s24";if(4===this.audioInfo.sampleSizeInBytes)return"pcm-s32"}return this.audioInfo.format===wr.IEEE_FLOAT&&4===this.audioInfo.sampleSizeInBytes?"pcm-f32":null}async getMimeType(){return"audio/wav"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}const Pr=2048;class vr{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}async getDecoderConfig(){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}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return i(-1!==this.demuxer.dataSize),this.demuxer.dataSize/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return R}getDisposition(){return{...he}}async getPacketAtIndex(e,t){i(e>=0),i(this.demuxer.audioInfo);const r=e*Pr*this.demuxer.audioInfo.blockSizeInBytes;if(r>=this.demuxer.dataSize)return null;const a=Math.min(Pr*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-r);if(null===this.demuxer.reader.fileSize){let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+r,a);if(e instanceof Promise&&(e=await e),!e)return null}let s;if(t.metadataOnly)s=Dt;else{let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+r,a);e instanceof Promise&&(e=await e),i(e),s=ln(e,a)}const n=e*Pr/this.demuxer.audioInfo.sampleRate,o=a/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(e,this.demuxer.lastKnownPacketIndex),new Mt(s,"key",n,o,e,a)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,t){i(this.demuxer.audioInfo);const r=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/Pr,(this.demuxer.dataSize-1)/(Pr*this.demuxer.audioInfo.blockSizeInBytes)));if(r<0)return null;const a=await this.getPacketAtIndex(r,t);if(a)return a;if(0===r)return null;i(null===this.demuxer.reader.fileSize);let s=await this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,t);for(;s;){const e=await this.getNextPacket(s,t);if(!e)break;s=e}return s}getNextPacket(e,t){i(this.demuxer.audioInfo);const r=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/Pr);return this.getPacketAtIndex(r+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const Ir=e=>{const t=e.filePos,i=ln(e,9),r=new fe(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}},xr=1024;class Cr extends Rt{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();i(this.firstFrameHeader),this.trackBackings=[new Br(this)]})())}async advanceReader(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,Fn);if(e instanceof Promise&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const t=Nn(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}let e=this.reader.requestSliceRange(this.lastLoadedPos,7,9);if(e instanceof Promise&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const t=Ir(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 r=me[t.samplingFrequencyIndex];i(void 0!==r);const a=xr/r,s={timestamp:this.nextTimestampInSamples/r,duration:a,dataStart:t.startPos,dataSize:t.frameLength};this.loadedSamples.push(s),this.nextTimestampInSamples+=xr,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,Fn);if(t instanceof Promise&&(t=await t),!t)break;const i=Nn(t);if(!i)break;let r=this.reader.requestSlice(t.filePos,i.size);if(r instanceof Promise&&(r=await r),!r)break;On(r,i,this.metadataTags),e=t.filePos+i.size}return this.metadataTags}finally{e()}}}class Br{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return this.getSampleRate()/xr}isRelativeToUnixEpoch(){return!1}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return R}getCodec(){return"aac"}getInternalCodecId(){return i(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){i(this.demuxer.firstFrameHeader);const e=pe[this.demuxer.firstFrameHeader.channelConfiguration];return i(void 0!==e),e}getSampleRate(){i(this.demuxer.firstFrameHeader);const e=me[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return i(void 0!==e),e}getDisposition(){return{...he}}async getDecoderConfig(){return i(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=Dt;else{let e=this.demuxer.reader.requestSlice(i.dataStart,i.dataSize);if(e instanceof Promise&&(e=await e),!e)return null;r=ln(e,i.dataSize)}return new Mt(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=S(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=P(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{for(var t;null===this.reader.fileSize||en.end-6)return{num:o.num,blockSize:o.blockSize,sampleRate:o.sampleRate,size:n.end-e,isLastFrame:!0};if(255===un(n)){const t=n.filePos;if(un(n)!==(1===this.blockingBit?249:248)){n.filePos=t;continue}n.skip(-2);const i=n.filePos-e,r=this.readFlacFrameHeader({slice:n,isFirstPacket:!1});if(!r){n.filePos=t;continue}if(0===this.blockingBit){if(r.num-o.num!==1){n.filePos=t;continue}}else if(r.num-o.num!==o.blockSize){n.filePos=t;continue}return{num:o.num,blockSize:o.blockSize,sampleRate:o.sampleRate,size:i,isLastFrame:!1}}}}readFlacFrameHeader({slice:e,isFirstPacket:t}){const r=e.filePos,a=ln(e,4),s=new fe(a);if(32764!==s.readBits(15))return null;if(null===this.blockingBit){i(t);const e=s.readBits(1);this.blockingBit=e}else if(1===this.blockingBit){i(!t);if(1!==s.readBits(1))return null}else{if(0!==this.blockingBit)throw new Error("Invalid blocking bit");i(!t);if(0!==s.readBits(1))return null}const n=(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)(s.readBits(4));if(!n)return null;i(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}})(s.readBits(4),this.audioInfo.sampleRate);if(!o)return null;s.readBits(4),s.readBits(3);if(0!==s.readBits(1))return null;const c=(e=>{let t=0;const i=new fe(ln(e,1));for(;1===i.readBits(1);)t++;if(0===t)return i.readBits(7);const r=[],a=t-1,s=new fe(ln(e,a)),n=8-t-1;for(let o=0;oe|t<"uncommon-u16"===t?hn(e)+1:"uncommon-u8"===t?un(e)+1:"number"===typeof t?t:(B(t),void i(!1)))(e,n),u=((e,t)=>"uncommon-u16"===t?hn(e):"uncommon-u16-10"===t?10*hn(e):"uncommon-u8"===t?un(e):"number"===typeof t?t:null)(e,o);if(null===u)return null;if(u!==this.audioInfo.sampleRate)return null;const d=e.filePos-r,h=un(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})(ln(e,d));return h!==f?null:{num:c,blockSize:l,sampleRate:u}}async advanceReader(){await this.readMetadata(),i(null!==this.lastLoadedPos),i(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 r=this.loadedSamples[this.loadedSamples.length-1],a={blockOffset:r?r.blockOffset+r.blockSize:0,blockSize:t.blockSize,byteOffset:e,byteSize:t.size};this.lastLoadedPos=this.lastLoadedPos+t.size,this.loadedSamples.push(a),t.isLastFrame&&(this.lastSampleLoaded=!0)}}class _r{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 R}getTimeResolution(){return i(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return i(this.demuxer.audioInfo),0===this.demuxer.audioInfo.totalSamples?null:this.demuxer.audioInfo.totalSamples/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getDisposition(){return{...he}}async getDecoderConfig(){return i(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(i(this.demuxer.audioInfo),e<0)throw new Error("Timestamp cannot be negative");const r=await this.demuxer.readingMutex.acquire();try{for(;;){const i=P(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{r()}}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 r=this.demuxer.loadedSamples[e];if(!r)return null;let a;if(t.metadataOnly)a=Dt;else{let e=this.demuxer.reader.requestSlice(r.byteOffset,r.byteSize);if(e instanceof Promise&&(e=await e),!e)return null;a=ln(e,r.byteSize)}i(this.demuxer.audioInfo);const s=r.blockOffset/this.demuxer.audioInfo.sampleRate,n=r.blockSize/this.demuxer.audioInfo.sampleRate;return new Mt(a,"key",s,n,e,r.byteSize)}async getFirstPacket(e){for(;0===this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)}}const Ar=9e4,Fr=188,Rr="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.",Dr=new Set;class Mr extends Rt{constructor(e){super(e),this.metadataPromise=null,this.elementaryStreams=[],this.trackBackingEntries=[],this.packetOffset=0,this.packetStride=-1,this.sectionEndPositions=[],this.seekChunkSize=5242880,this.minReferencePointByteDistance=-1,this.reader=e._reader}async readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{let e=this.reader.requestSlice(0,205);e instanceof Promise&&(e=await e),i(e);const t=ln(e,205);if(71===t[0]&&71===t[188])this.packetOffset=0,this.packetStride=Fr;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 r=this.packetOffset,a=null,s=!1,n=!1;for(;;){const e=await this.readPacketHeader(r);if(!e)break;if(0===e.payloadUnitStartIndicator){r+=this.packetStride;continue}const t=await this.readSection(r,!0,!n);if(!t)break;const o=3,c=32;let l=!1;if(!n&&0!==t.pid){if(!(0===t.payload[0]&&0===t.payload[1]&&1===t.payload[2])){const e=new fe(t.payload),i=e.readAlignedByte();e.skipBits(8*i);l=2===e.readBits(8)}}if(0!==t.pid||s)if(t.pid!==a&&!l||n){const e=this.elementaryStreams.find(e=>e.pid===t.pid);e:if(e&&!e.initialized){const r=Or(t,!0);if(!r)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 a=new Wr(e,r);if("video"===e.info.type){for(;;){if(a.suppliedPacket=null,await a.markNextPacket(),"avc"===e.info.codec){if(!a.suppliedPacket)throw new Error("Invalid AVC video stream; could not extract AVCDecoderConfigurationRecord from any packet.");if(e.info.avcCodecInfo=Ze(a.suppliedPacket.data),!e.info.avcCodecInfo)continue;const t=e.info.avcCodecInfo.sequenceParameterSets[0];i(t);const r=tt(t);e.info.width=r.displayWidth,e.info.height=r.displayHeight;const s=r.pixelAspectRatio.num,n=r.pixelAspectRatio.den;s>0&&n>0&&(s>n?(e.info.squarePixelWidth=Math.round(e.info.width*s/n),e.info.squarePixelHeight=e.info.height):(e.info.squarePixelWidth=e.info.width,e.info.squarePixelHeight=Math.round(e.info.height*n/s))),e.info.colorSpace={primaries:h[r.colourPrimaries],transfer:m[r.transferCharacteristics],matrix:g[r.matrixCoefficients],fullRange:!!r.fullRangeFlag},e.info.reorderSize=r.maxDecFrameBuffering;break}if("hevc"===e.info.codec){if(!a.suppliedPacket)throw new Error("Invalid HEVC video stream; could not extract HVCDecoderConfigurationRecord from first packet.");if(e.info.hevcCodecInfo=nt(a.suppliedPacket.data),!e.info.hevcCodecInfo)continue;const t=e.info.hevcCodecInfo.arrays.find(e=>e.nalUnitType===Ve.SPS_NUT).nalUnits[0];i(t);const r=st(t);e.info.width=r.displayWidth,e.info.height=r.displayHeight,r.pixelAspectRatio.num>r.pixelAspectRatio.den?(e.info.squarePixelWidth=Math.round(e.info.width*r.pixelAspectRatio.num/r.pixelAspectRatio.den),e.info.squarePixelHeight=e.info.height):(e.info.squarePixelWidth=e.info.width,e.info.squarePixelHeight=Math.round(e.info.height*r.pixelAspectRatio.den/r.pixelAspectRatio.num)),e.info.colorSpace={primaries:h[r.colourPrimaries],transfer:m[r.transferCharacteristics],matrix:g[r.matrixCoefficients],fullRange:!!r.fullRangeFlag},e.info.reorderSize=r.maxDecFrameBuffering;break}throw new Error("Unhandled.")}e.info.decoderConfig={codec:ve({width:e.info.width,height:e.info.height,codec:e.info.codec,codecDescription:null,colorSpace:e.info.colorSpace,avcType:1,avcCodecInfo:e.info.avcCodecInfo,hevcCodecInfo:e.info.hevcCodecInfo,vp9CodecInfo:null,av1CodecInfo:null}),codedWidth:e.info.width,codedHeight:e.info.height,colorSpace:e.info.colorSpace},e.info.width===e.info.squarePixelWidth&&e.info.height===e.info.squarePixelHeight||(e.info.decoderConfig.displayAspectWidth=e.info.squarePixelWidth,e.info.decoderConfig.displayAspectHeight=e.info.squarePixelHeight),e.initialized=!0}else{if(await a.markNextPacket(),!a.suppliedPacket)throw new Error(`Couldn't parse first media packet for Elementary Stream with PID ${e.pid}`);if("aac"===e.info.codec){const t=on.tempFromBytes(a.suppliedPacket.data),i=Ir(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=pe[i.channelConfiguration],e.info.sampleRate=me[i.samplingFrequencyIndex]}else if("mp3"===e.info.codec){const t=gn(on.tempFromBytes(a.suppliedPacket.data)),i=Me(t,a.suppliedPacket.data.byteLength);if(!i.header)throw new Error("Invalid MP3 audio stream; could not read frame header from first packet.");e.info.numberOfChannels=3===i.header.channel?1:2,e.info.sampleRate=i.header.sampleRate}else if("ac3"===e.info.codec){const t=Ct(a.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=xt[t.acmod]+t.lfeon,e.info.sampleRate=ze[t.fscod]}else{if("eac3"!==e.info.codec)throw new Error("Unhandled.");{const t=_t(a.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=Ft(t),e.info.sampleRate=i}}e.info.decoderConfig={codec:Ie({codec:e.info.codec,codecDescription:null,aacCodecInfo:e.info.aacCodecInfo}),numberOfChannels:e.info.numberOfChannels,sampleRate:e.info.sampleRate},e.initialized=!0}}}else{const e=new fe(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);for(e.skipBits(8*a);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;for(;e.posc;){const t=e.readBits(16);e.skipBits(3);const i=e.readBits(13);if(0!==t){if(null!==a)throw new Error("Only files with a single program are supported.");a=i}}if(null===a)throw new Error("Program Association Table must link to a Program Map Table.");s=!0}if(n&&this.elementaryStreams.every(e=>e.initialized))break;r+=this.packetStride}if(!n){if(!s)throw new Error("No Program Association Table found in the file.");throw new Error("No Program Map Table found in the file.")}for(const i of this.elementaryStreams)"video"===i.info.type?this.trackBackingEntries.push(new zr(i)):this.trackBackingEntries.push(new Ur(i))})())}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!==S(this.sectionEndPositions,r,e=>e)){l=!1;break}}if(l){const e=P(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(t instanceof Promise&&(t=await t),!t)return null;if(71!==un(t))throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");const i=hn(t);return{payloadUnitStartIndicator:i>>14&1,pid:8191&i,adaptationFieldControl:un(t)>>4&3}}async readPacket(e){let t=this.reader.requestSlice(e,Fr);if(t instanceof Promise&&(t=await t),!t)return null;const i=ln(t,Fr);if(71!==i[0])throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");const r=(i[1]<<8)+i[2];return{payloadUnitStartIndicator:r>>14&1,pid:8191&r,adaptationFieldControl:i[3]>>4&3,body:i.subarray(4)}}}const Nr=(e,t)=>{if(e.payload.byteLength<3)return null;const i=new fe(e.payload);if(1!==i.readBits(24))return null;const r=i.readBits(8);if(i.skipBits(16),188===r||190===r||191===r||240===r||241===r||255===r||242===r||248===r)return null;i.skipBits(8);const a=i.readBits(2);i.skipBits(14);let s=null;if(2===a||3===a)s=0,i.skipBits(4),s+=i.readBits(3)*(1<<30),i.skipBits(1),s+=32768*i.readBits(15),i.skipBits(1),s+=i.readBits(15);else if(t)throw new Error(Rr);return{sectionStartPos:e.startPos,sectionEndPos:e.endPos,pts:s,randomAccessIndicator:e.randomAccessIndicator}},Or=(e,t)=>{i(null!==e.endPos);const r=Nr(e,t);if(!r)return null;const a=new fe(e.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;i(Number.isInteger(c));const l=e.payload.subarray(c,s>0?6+s:e.payload.byteLength);return{...r,data:l}};class Lr{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 r=0;for(const a of e.trackBackingEntries)if(a.getType()===t&&r++,i(a instanceof Lr),a.elementaryStream===this.elementaryStream)break;return r}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.elementaryStream.streamType}getName(){return null}getLanguageCode(){return R}getDisposition(){return{...he,primary:!1}}getTimeResolution(){return Ar}isRelativeToUnixEpoch(){return!1}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 Mt(i.metadataOnly?Dt:e.data,r,e.pts/Ar,Math.max(t/Ar,0),e.sequenceNumber,e.data.byteLength)}async getFirstPacket(e){const t=this.elementaryStream.firstSection;i(t);const r=Or(t,!0);i(r);const a=new Wr(this.elementaryStream,r),s=new Vr(this,a),n=await s.readNext();if(!n)return null;const o=this.createEncodedPacket(n.packet,n.duration,e);return this.packetBuffers.set(o,s),this.packetSectionStarts.set(o,n.packet.sectionStartPos),o}async getNextPacket(e,t){let r=this.packetBuffers.get(e);if(r){const i=await r.readNext();if(!i)return null;this.packetBuffers.delete(e);const a=this.createEncodedPacket(i.packet,i.duration,t);return this.packetBuffers.set(a,r),this.packetSectionStarts.set(a,i.packet.sectionStartPos),a}const a=this.packetSectionStarts.get(e);if(void 0===a)throw new Error("Packet was not created from this track.");const s=this.elementaryStream.demuxer,n=await s.readSection(a,!0);i(n);const o=Or(n,!0);i(o);const c=new Wr(this.elementaryStream,o);r=new Vr(this,c);const l=e.sequenceNumber;for(;;){const e=await r.readNext();if(!e)return null;if(e.packet.sequenceNumber>l){const i=this.createEncodedPacket(e.packet,e.duration,t);return this.packetBuffers.set(i,r),this.packetSectionStarts.set(i,e.packet.sectionStartPos),i}}}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,r){const s=D(e*Ar),n=this.elementaryStream.demuxer,{reader:o,seekChunkSize:c}=n,l=this.elementaryStream.pid,u=async(e,t,i)=>{let r=e;for(;re.pts),g=-1!==p?m[p]:null;if(g&&s-g.pts<45e3)f=g.sectionStartPos;else{let e=0;if(null!==o.fileSize){const t=Math.ceil(o.fileSize/c);if(t>1){let i=0,r=t-1;for(e=i;i<=r;){const t=Math.floor((i+r)/2),a=N(t*c,n.packetStride)+h.sectionStartPos,o=a+c,l=await u(a,o,!1);l?l.pesPacketHeader.pts<=s?(e=t,i=t+1):r=t-1:r=t-1}}}f=N(e*c,n.packetStride)+h.sectionStartPos}const k=await u(f,o.fileSize??1/0,!1);let b=k?.pesPacketHeader??null;b||(b=h);const y=this.getReorderSize(),w=async(e,t)=>{const o=await n.readSection(e,!0);i(o);const c=Or(o,!0);i(c);const l=new Wr(this.elementaryStream,c),u=new Vr(this,l);for(;;){if((a(u.presentationOrderPackets)?.pts??-1/0)>=s)break;if(!(await u.readNextPacket()))break}const d=C(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();i(m);const p=this.createEncodedPacket(m.packet,m.duration,r);return this.packetBuffers.set(p,u),this.packetSectionStarts.set(p,m.packet.sectionStartPos),p};if(!t||this.allPacketsAreKeyPackets()){e:for(;;){let e=b.sectionStartPos+n.packetStride;for(;;){const t=await n.readPacketHeader(e);if(!t)break e;if(t.pid===l&&1===t.payloadUnitStartIndicator){const t=await n.readSection(e,!1);if(t){const e=Nr(t,!1);if(e&&null!==e.pts){if(e.pts>s)break e;b=e,qr(this.elementaryStream,b);break}}}e+=n.packetStride}}e:for(let e=0;e=n.packetOffset;){const t=await n.readPacketHeader(e);if(!t)break e;if(t.pid===l&&1===t.payloadUnitStartIndicator){const t=await n.readSection(e,!1);if(t){const e=Nr(t,!1);if(e&&null!==e.pts){b=e;break}}}e-=n.packetStride}}return w(b.sectionStartPos,e=>e.pts<=s)}{let e=f,t=null;const r=!this.elementaryStream.canBeTrustedWithKeyPackets;for(;;){let a=null;const f=e<=h.sectionStartPos;let m,p=null;if(f)m=h,p=d;else{const t=await u(e,o.fileSize??1/0,r);m=t?.pesPacketHeader??null,p=t?.section??null}let g=!1,k=0;e:for(;m&&!(null!==t&&m.sectionStartPos>=t);){if(m.pts<=s){let e;if(this.elementaryStream.canBeTrustedWithKeyPackets)e=1===m.randomAccessIndicator;else{i(p);const t=Or(p,!0);i(t);const r=new Wr(this.elementaryStream,t);await r.markNextPacket(),e=1===r.suppliedPacket?.randomAccessIndicator}e&&(a=m)}if(m.pts>s&&(g=!0),g&&(k++,k>y))break;let e=m.sectionStartPos+n.packetStride;for(;;){const t=await n.readPacketHeader(e);if(!t)break e;if(t.pid===l&&1===t.payloadUnitStartIndicator){const t=await n.readSection(e,r);if(t){const e=Nr(t,!1);if(e&&null!==e.pts){m=e,p=t,qr(this.elementaryStream,m);break}}}e+=n.packetStride}}if(a){let e=a;if(0===k)e:for(let i=0;i=n.packetOffset;){const i=await n.readPacketHeader(t);if(!i)break e;if(i.pid===l&&1===i.payloadUnitStartIndicator){const i=await n.readSection(t,r);if(i){const t=Nr(i,!1);if(t&&null!==t.pts){e=t;break}}}t-=n.packetStride}}const t=await w(e.sectionStartPos,e=>e.pts<=s&&1===e.randomAccessIndicator);return i(t),t}if(f)return null;t=e,e=Math.max(N(e-h.sectionStartPos-c,n.packetStride)+h.sectionStartPos,h.sectionStartPos)}}}}class zr extends Lr{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 i(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}}class Ur extends Lr{getType(){return"audio"}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}async getDecoderConfig(){return i(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 0}}const qr=(e,t)=>{const i=e.referencePesPackets,r=P(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 i(e),e}async bufferData(e){const t=this.endPos+e;for(;this.endPos=n)break;o=e;const i=a+o;if(o+4>=n){this.seekTo(i);break}const c=s[o+1],l=s[o+2],u=s[o+3];let d=0,h=null;if(0===c&&0===l&&1===u?(d=4,h=s[o+4]):0===c&&1===l&&(d=3,h=u),0===d){o++;continue}const f=i;if(null!==r){if(null!==h){const e="avc"===t?$e(h):at(h);if("avc"===t?e===qe.AUD:e===Ve.AUD_NUT){const e=f-r;return this.seekTo(r),this.supplyPacket(e,0)}}o+=d}else r=f,o+=d}if(e>6,o=63&s[4];if(3===n||o>37){this.seekTo(t+1);continue}const c=Bt[3*o+n];i(void 0!==c),this.seekTo(t),a=this.ensureBuffered(c),a instanceof Promise&&(a=await a);const l=Math.round(13824e4/e.info.sampleRate);return this.supplyPacket(a,l)}if("eac3"===t){if(11!==r)continue;this.skip(-1);const t=this.currentPos;let i=this.ensureBuffered(5);if(i instanceof Promise&&(i=await i),i<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=Et[n];this.seekTo(t),i=this.ensureBuffered(s),i instanceof Promise&&(i=await i);const c=256*o,l=Math.round(c*Ar/e.info.sampleRate);return this.supplyPacket(i,l)}throw new Error("Unhandled.")}{if(255!==r)continue;this.skip(-1);const t=this.currentPos;let i=this.ensureBuffered(4);if(i instanceof Promise&&(i=await i),i<4)return;const a=this.readBytes(4),s=c(a).getUint32(0),n=Me(s,null);if(n.header){this.seekTo(t);let i=this.ensureBuffered(n.header.totalSize);i instanceof Promise&&(i=await i);const r=n.header.audioSamplesInFrame*Ar/e.info.sampleRate;return this.supplyPacket(i,Math.round(r))}this.seekTo(t+1)}}}if(a=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 r;if(i(-1!==t),t===this.presentationOrderPackets.length-1)r=this.lastDuration;else{r=this.presentationOrderPackets[t+1].pts-e.pts,this.lastDuration=r}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:r}}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(i(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 Hr="application/vnd.apple.mpegurl",Kr="#EXT-X-STREAM-INF:",jr="#EXT-X-I-FRAME-STREAM-INF:",Xr="#EXT-X-MEDIA:",$r="#EXTINF:",Qr="#EXT-X-MAP:",Gr="#EXT-X-KEY:",Yr="#EXT-X-MEDIA-SEQUENCE:",Jr="#EXT-X-BYTERANGE:",Zr="#EXT-X-PROGRAM-DATE-TIME:",ea="#EXT-X-TARGETDURATION:",ta="#EXT-X-PLAYLIST-TYPE:",ia=e=>0===e.length||e.startsWith("#")&&!e.startsWith("#EXT");class ra{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=ae(e,e=>"video"===e.getType())+1;e.push(new na(this,t,i))}else if("audio"===t.type){const i=ae(e,e=>"audio"===e.getType())+1;e.push(new oa(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=ae(e,e=>"video"===e.getType())+1;e.push(new na(this,{id:e.length+1,type:"video"},t))}else if("audio"===r.type){const t=ae(e,e=>"audio"===e.getType())+1;e.push(new oa(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 sa{constructor(e,t,i){this.packetInfos=new WeakMap,this.hydrationPromise=null,this.firstInputTrack=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.");const t=this.segmentedInput.getInputForSegment(this.segmentedInput.firstSegment),i=(await t.getTracks()).find(e=>e.type===this.decl.type&&e.number===this.number);if(!i)throw new Error("No matching track found in underlying media data.");this.firstInputTrack=i})())}getId(){return this.decl.id}getType(){return this.decl.type}getNumber(){return this.number}delegate(e){return this.firstInputTrack?e():this.hydrate().then(e)}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(),i(this.segmentedInput.firstSegment),this.segmentedInput.firstSegment.relativeToUnixEpoch}getBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getBitrate())}getAverageBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getAverageBitrate())}getDurationFromMetadata(e){return this.segmentedInput.getDurationFromMetadata(e)}getLiveRefreshInterval(){return this.segmentedInput.getLiveRefreshInterval()}async createAdjustedPacket(e,t,r){i(e.sequenceNumber>=0),i(this.segmentedInput.firstSegment);const a=await this.segmentedInput.getMediaOffset(t,r.input),s=t.timestamp-this.segmentedInput.firstSegment.timestamp,n=e.clone({timestamp:M(e.timestamp+a,await r.getTimeResolution()),sequenceNumber:Math.floor(1e8*s)+e.sequenceNumber});return this.packetInfos.set(n,{segment:t,track:r,sourcePacket:e}),n}async getFirstPacket(e){await this.hydrate(),i(this.segmentedInput.firstSegment),i(this.firstInputTrack);const t=await this.firstInputTrack._backing.getFirstPacket(e);return t?this.createAdjustedPacket(t,this.segmentedInput.firstSegment,this.firstInputTrack):null}getNextPacket(e,t){return this._getNextInternal(e,t,!1)}getNextKeyPacket(e,t){return this._getNextInternal(e,t,!0)}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 na extends sa{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 oa extends sa{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())}}te();const ca=1/0;class la extends le{constructor(){super(...arguments),this._disposed=!1,this._refCount=0,this._usedForHls=!1,this._sizePromise=null,this.onread=null}async getSizeOrNull(){if(this._disposed)throw new sn;return this._sizePromise??(this._sizePromise=(async()=>{let e=this._getFileSize();return void 0!==e||(await this._read(0,1,0,ca),e=this._getFileSize(),i(void 0!==e)),e})())}async getSize(){if(this._disposed)throw new sn;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 Ta(this,e,t)}_dispatchRead(e,t){this.onread?.(e,t),this._emit("read",{start:e,end:t})}ref(){return new ua(this)}}class ua{constructor(e){if(this._freed=!1,e._disposed)throw new Error("Cannot ref a disposed source.");e._refCount++,this._source=e}get source(){if(!this._source)throw new Error("Can't get source; ref has already been freed.");return this._source}get freed(){return this._freed}free(){if(this._freed)throw new Error("Illegal operation: double free on SourceRef.");const e=this.source;i(e._refCount>0),e._refCount--,0===e._refCount&&(e._dispose(),e._disposed=!0),this._freed=!0,this._source=null}[Symbol.dispose](){this.freed||this.free()}}class da extends la{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 la||e instanceof ua))throw new TypeError("requestHandler must return or resolve to a Source or SourceRef.");const i=e instanceof la?e.ref():e;return(t=i.source)._usedForHls||(t._usedForHls=this._usedForHls),i};return t instanceof Promise?t.then(i):i(t)}}const ha=(e,t)=>e.path===t.path;class fa extends da{constructor(){super(...arguments),this._root=null,this._rootRequest=null}_read(e,t,r,a){if(!this._root){if(!this._rootRequest){const e=this._resolveRequest({path:this.rootPath,isRoot:!0}),t=e=>{const t=e instanceof la?e.ref():e;return this._root=t,this._rootRequest=null,t};e instanceof Promise?this._rootRequest=e.then(t):(t(e),i(this._root))}if(this._rootRequest)return this._rootRequest.then(i=>i.source._read(e,t,r,a))}return this._root.source._read(e,t,r,a)}_getFileSize(){if(this._root)return this._root.source._getFileSize()}_dispose(){this._root?this._root.free():this._rootRequest&&this._rootRequest.then(e=>e.free())}}class ma extends la{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&&(!ie(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");super(),this._readers=new WeakMap,this._blob=e,this._orchestrator=new wa({maxCacheSize:t.maxCacheSize??8388608,maxWorkerCount:4,runWorker:this._runWorker.bind(this),prefetchProfile:ya.fileSystem}),this._orchestrator.fileSize=e.size}_getFileSize(){return this._orchestrator.fileSize}_read(e,t,i,r){return this._orchestrator.read(e,t,i,r)}async _runWorker(e){i(e.strictTarget);let t=this._readers.get(e);if(void 0===t){if("stream"in this._blob&&!K()){t=this._blob.slice(e.currentPos).stream().getReader()}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"))){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 console.warn("Request will not be retried because a CORS error was suspected due to different origins. You can modify this behavior by providing your own function for the 'getRetryDelay' option."),null}return Math.min(2**(e-2),16)},ga=new Set;class ka extends da{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&&(!ie(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(void 0!==t.parallelism&&(!Number.isInteger(t.parallelism)||t.parallelism<1))throw new TypeError("options.parallelism, when provided, must be a positive number.");if(void 0!==t.fetchFn&&"function"!==typeof t.fetchFn)throw new TypeError("options.fetchFn, when provided, must be a function.");super(e instanceof Request?e.url:e instanceof URL?e.href:e,e=>new ka(e.path,this._options)),this._fileSizeDetermined=!1,this._url=e,this._options=t,this._getRetryDelay=t.getRetryDelay??pa;this._orchestrator=new wa({maxCacheSize:t.maxCacheSize??67108864,maxWorkerCount:t.parallelism??2,runWorker:this._runWorker.bind(this),prefetchProfile:ya.network})}_getFileSize(){return this._fileSizeDetermined?this._orchestrator.fileSize:void 0}_read(e,t,i,r){return this._orchestrator.read(e,t,i,r)}async _runWorker(e){for(;;){const i=new AbortController,r=await W(this._options.fetchFn??fetch,this._url,U(this._options.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}`);e:if(null===this._orchestrator.fileSize){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");i&&this._orchestrator.supplyFileSize(e.currentPos+Number(i))}if(this._fileSizeDetermined=!0,206!==r.status){if(!this._usedForHls){const e=new URL(this._url instanceof Request?this._url.url:this._url,"undefined"!==typeof window?window.location.href:void 0);"null"===e.origin||e.pathname.endsWith(".m3u8")||e.pathname.endsWith(".m3u")||ga.has(e.origin)||(console.log(this._usedForHls,this._url,e.pathname),console.warn(`HTTP server (origin ${e.origin}) did not respond to a range request with 206 Partial Content, meaning the entire resource will now be downloaded. To enable efficient media file streaming across a network, please make sure your server supports range requests.`),ga.add(e.origin))}e.currentPos=0,this._orchestrator.options.maxCacheSize=1/0,null!==this._orchestrator.fileSize?e.targetPos=this._orchestrator.fileSize:(e.targetPos=1/0,e.strictTarget=!1),this._orchestrator.consolidateEverythingIntoOneWorker(e)}if(!r.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");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){console.error("Error while reading response stream. Attempting to resume.",t),await ce(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)}}}_dispose(){this._orchestrator.dispose()}}class ba extends la{constructor(e,t={}){if(!(e instanceof ReadableStream))throw new TypeError("stream must be a ReadableStream.");if(!t||"object"!==typeof t)throw new TypeError("options must be an object.");if(void 0!==t.maxCacheSize&&(!ie(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");super(),this._reader=null,this._cache=[],this._pendingSlices=[],this._currentIndex=0,this._targetIndex=0,this._maxRequestedIndex=0,this._endIndex=null,this._pulling=!1,this._stream=e,this._maxCacheSize=t.maxCacheSize??16777216}_getFileSize(){return this._endIndex}_read(e,t){if(null!==this._endIndex&&t>this._endIndex)return null;this._maxRequestedIndex=Math.max(this._maxRequestedIndex,t);const i=P(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 c=i;c=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:l}=I();return this._pendingSlices.push({start:e,end:t,bytes:s,resolve:o,reject:l}),this._targetIndex=Math.max(this._targetIndex,t),this._pulling||(this._pulling=!0,this._pull().catch(e=>{if(this._pulling=!1,!(this._pendingSlices.length>0))throw e;this._pendingSlices.forEach(t=>t.reject(e)),this._pendingSlices.length=0})),n}_throwDueToCacheMiss(){throw new Error("Read is before the cached region. With ReadableStreamSource, you must access the data more sequentially or increase the size of its cache.")}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(){this._pendingSlices.length=0,this._cache.length=0,this._reader?.cancel()}}const ya={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(Z(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 wa{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,r,a){i(!this.disposed);const s=this.options.prefetchProfile(e,t,this.workers),n=Math.max(s.start,r),o=Math.min(s.end,this.fileSize??1/0,a);i(n<=e&&t<=o);let l=null;const u=P(this.cache,e,e=>e.start),d=-1!==u?this.cache[u]:null;d&&d.start<=e&&t<=d.end&&(d.age=this.nextAge++,l={bytes:d.bytes,view:d.view,offset:d.start});const h=P(this.cache,n,e=>e.start),f=l?null:new Uint8Array(t-e);let m=0,p=n;const g=[];if(-1!==h){for(let r=h;r=o)break;if(a.end<=n)continue;const s=Math.max(n,a.start),c=Math.min(o,a.end);if(i(s<=c),p=f.length&&(l={bytes:f,view:c(f),offset:e}),0===g.length)return i(l),l;const{promise:k,resolve:b,reject:y}=I(),w=[];for(const i of g){const r=Math.max(e,i.start),a=Math.min(t,i.end);r===i.start&&a===i.end?w.push(i):re.hole.start),r=-1!==t?this.queuedReads[t]:null;for(r&&i.start<=r.hole.end?(r.hole.end=Math.max(r.hole.end,i.end),r.strictTarget&&(r.strictTarget=e),T&&r.pendingSlices.push(T)):(t++,r={hole:{start:i.start,end:i.end},strictTarget:e,pendingSlices:T?[T]:[],age:this.nextAge++},this.queuedReads.splice(t,0,r));t+1r.hole.end)break;r.hole.end=Math.max(r.hole.end,e.hole.end),r.pendingSlices.push(...e.pendingSlices),r.strictTarget&&(r.strictTarget=e.strictTarget),r.age=Math.min(r.age,e.age),this.queuedReads.splice(t+1,1)}}}return l||(i(f),l=k.then(t=>t&&{bytes:t,view:c(t),offset:e})),l}checkHoleAgainstWorker(e,t,i){if(Z(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))throw t;e.pendingSlices.forEach(e=>e.reject(t)),e.pendingSlices.length=0}).finally(()=>{if(!e.running&&this.queuedReads.length>0){let e=0;for(let i=1;ie.targetPos&&(e.targetPos=e.currentPos,this.checkQueuedReadsAgainstWorker(e));for(let i=0;it.start&&(t.start=a),t.end<=t.start&&(s.holes.splice(e,1),e--)}0===s.holes.length&&(s.resolve(s.bytes),e.pendingSlices.splice(i,1),i--)}for(let i=0;ie){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.pendingSlices.length=0}onWorkerFinished(e){const t=this.workers.indexOf(e);i(-1!==t),e.running=!1,this.workers.splice(t,1),null===this.fileSize&&this.supplyFileSize(e.currentPos);for(const i of e.pendingSlices)i.resolve(null)}insertIntoCache(e){if(0===this.options.maxCacheSize)return;let t=P(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=c(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=c(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);return a instanceof Promise?a.then(e=>e?(e.offset-=this._offset,e):null):a?(a.offset-=this._offset,a):null}_dispose(){this._ref?.free()}ref(){return this._ref??(this._ref=this._baseSource.ref()),super.ref()}}var Sa=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},Pa=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 va=/^0[xX][0-9a-fA-F]+$/,Ia=/^data:.*;base64,/i;class xa extends aa{constructor(e,t,i,r){super(e.input,t,i),this.segments=[],this.nextLines=null,this.currentUpdateSegmentsPromise=null,this.streamHasEnded=!1,this.lastSegmentUpdateTime=-1/0,this.refreshInterval=5,this.demuxer=e,this.nextLines=r}runUpdateSegments(){return this.currentUpdateSegmentsPromise??(this.currentUpdateSegmentsPromise=(async()=>{try{const e=this.getRemainingWaitTimeMs();e>0&&await ce(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 r=Sa(t,await this.demuxer.input._getSourceUncached({path:this.path,isRoot:!1}),!1),a=new nn(r.source),s=await a.requestEntireFile();i(s),e=xn(s,s.length,{ignore:ia})}catch(y){t.error=y,t.hasError=!0}finally{Pa(t)}}let t=!1,r=0,s=null,n=null,o=0,l=null,u=null,d=null,h=null,f=null,m=null,p=!1,g=a(this.segments)??null;const k=e=>{const t=e.indexOf("@"),i=Number(-1===t?e:e.slice(0,t));if(!Number.isInteger(i)||i<0)throw new Error(`Invalid #EXT-X-BYTERANGE length '${e}'.`);let r=null;if(-1!==t&&(r=Number(e.slice(t+1)),!Number.isInteger(r)||r<0))throw new Error(`Invalid #EXT-X-BYTERANGE offset '${e}'.`);return{length:i,offset:r}},b=e=>{o=e,g&&(i(null!==g.sequenceNumber),g.sequenceNumber0&&null!==m&&(r=o*m),p=!0);const e=y.slice(8),t=e.indexOf(","),i=-1===t?e:e.slice(0,t),a=Number(i);if(!Number.isFinite(a)||a<0)throw new Error(`Invalid #EXTINF tag duration '${i}'.`);s=a}else if(y.startsWith(Qr)){const e=new ra(y.slice(11)),t=e.get("uri");if(!t)throw new Error("Invalid #EXT-X-MAP tag; missing URI attribute.");const i=e.get("byterange");let a=null;if(null!==i&&(a=k(i)),a&&null===a.offset)throw new Error("Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset.");if(!g){const e={path:re(this.path,t),offset:a?.offset??0,length:a?.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,relativeToUnixEpoch:null!==f,firstSegment:null,sequenceNumber:null,location:e,duration:0,encryption:n,initSegment:null,lastProgramDateTimeSeconds:f}}s=null,null===h?d=null:h=null}else if(y.startsWith(Gr)){const e=new ra(y.slice(11)),t=e.get("method");if("NONE"===t)n=null;else if("AES-128"===t){const t=e.get("uri");if(!t)throw new Error("Invalid #EXT-X-KEY: AES-128 requires a URI attribute.");let i=null;const r=e.get("iv");if(r){if(!va.test(r))throw new Error(`Unsupported IV format '${r}'.`);let e=r.slice(2);e=e.padStart(32,"0"),i=new Uint8Array(Ht);for(let t=0;t=8&&112===t[4]&&115===t[5]&&115===t[6]&&104===t[7]){const e=c(t).getUint32(0);r=Nt(t.subarray(8,Math.min(e,t.length)))}}n={method:t,psshBox:r}}}}else if(y.startsWith(Yr)){const e=y.slice(22),t=Number(e);if(!Number.isInteger(t)||t<0)throw new Error(`Invalid EXT-X-MEDIA-SEQUENCE value '${e}'.`);b(t)}else if(y.startsWith(Jr)){const e=k(y.slice(17));if(null===e.offset){if(null===d)throw new Error("Invalid M3U8 file; #EXT-X-BYTERANGE without offset requires a previous byte range.");e.offset=d}h=e,d=e.offset+e.length}else if(y.startsWith(Zr)){if(g)continue;const e=y.slice(25),t=Date.parse(e);if(!Number.isFinite(t))continue;const i=t/1e3;if(f===i)continue;if(null===f&&this.segments.length>0){const e=a(this.segments),t=i-(e.timestamp+e.duration);for(const i of this.segments)i.timestamp+=t,i.relativeToUnixEpoch=!0;r+=t}f=i,r=i}else if("#EXT-X-DISCONTINUITY"===y)l=null;else if(y.startsWith(ea)){const e=y.slice(22),t=Number(e);if(!Number.isFinite(t)||t<0)throw new Error(`Invalid EXT-X-TARGETDURATION value '${e}'.`);this.refreshInterval=t,m=t}else{if("#EXT-X-ENDLIST"===y){this.streamHasEnded=!0;break}if(y.startsWith(ta)){"vod"===y.slice(21).toLowerCase()&&(this.streamHasEnded=!0)}}}else{if("#EXTM3U"!==y)throw new Error("Invalid M3U8 file; expected first line to be #EXTM3U.");t=!0}}if(!t)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=P(this.segments,e,e=>e.timestamp);if(-1===r)return null;if(r0;for(;;){if(ae.segment===t);if(r)return r.age=this.nextInputCacheAge++,r.input;let a=null;(t.initSegment||t.firstSegment)&&(a=this.getInputForSegment(t.initSegment??t.firstSegment));const s={...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=>Ot(e,r))||(i=[...i,r]),this.input._formatOptions.isobmff.resolveKeyId({...e,psshBoxes:i})})}},n=new rn({source:new fa(t.location.path,async e=>{i(e.isRoot);const r={...e,isRoot:!1};let a;const s=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;i(e.iv);let n=await this.input._getSourceCached(r);if(s){const e=n.source.slice(t.location.offset,t.location.length??void 0).ref();n.free(),n=e}const o=((e,t,i)=>{let r=!1,a=0;const s=new Zt;return new ReadableStream({pull:async n=>{r||(s.init(await t()),r=!0);let o=e.requestSliceRange(a,0,65552);if(o instanceof Promise&&(o=await o),!o||0===o.length)throw 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=ln(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 nn(n.source),async()=>{const t={stack:[],error:void 0,hasError:!1};try{const i=Sa(t,await this.input._getSourceCached({path:e.keyUri,isRoot:!1},en),!1),r=new nn(i.source),a=await r.requestSlice(0,Ht);if(!a)throw new Error("Invalid AES-128 key; expected at least 16 bytes of data.");return{key:ln(a,Ht),iv:e.iv}}catch(i){t.error=i,t.hasError=!0}finally{Pa(t)}},()=>{n.free()});a=new ba(o).ref()}else i(!1);else if(a=await this.input._getSourceCached(r),s){const e=a.source.slice(t.location.offset,t.location.length??void 0).ref();a.free(),a=e}return a}),formats:this.input._formats.filter(e=>!(e instanceof ja)),initInput:a??void 0,formatOptions:s});n._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:n,age:this.nextInputCacheAge++});if(this.inputCache.length>4){const e=se(this.inputCache,e=>e.age);i(-1!==e),this.inputCache.splice(e,1)}return n}async getLiveRefreshInterval(){return 0===this.getRemainingWaitTimeMs()&&await this.runUpdateSegments(),this.streamHasEnded?null:this.refreshInterval}}class Ca extends Rt{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()=>{i(this.input._rootSource instanceof da);const{rootPath:e}=this.input._rootSource,t=await this.input._reader.requestEntireFile();i(t);const r=xn(t,t.length,{ignore:ia}),a=[],s=[];for(let i=1;i"video"===e.attributes.get("type").toLowerCase()).map(e=>e.attributes.get("group-id")))],o=[...new Set(s.filter(e=>"audio"===e.attributes.get("type").toLowerCase()).map(e=>e.attributes.get("group-id")))],c=await Promise.all(a.map(async(t,r)=>{const a=[],c=t.attributes.get("codecs");let l;if(c)l=c.split(",").map(e=>e.trim());else{const e=this.getSegmentedInputForPath(t.fullPath),i=await e.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=t.attributes.get("video"),d=t.attributes.get("audio"),h=l.some(e=>ke.includes(Ee(e))),f=l.some(e=>ye.includes(Ee(e)));if(null!==u&&!h){if(!n.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 t=s.find(e=>{const t=e.attributes.get("group-id"),i=e.attributes.get("type");return t===u&&"video"===i.toLowerCase()});e:if(t){const r=t.attributes.get("uri");if(null===r)break e;const a=re(e,r),s=this.getSegmentedInputForPath(a),n=(await s.getTrackBackings()).find(e=>"video"===e.getType());if(!n||null===await n.getCodec())break e;const o=await n.getDecoderConfig().then(e=>e?.codec??null);i(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 t=s.find(e=>{const t=e.attributes.get("group-id"),i=e.attributes.get("type");return t===d&&"audio"===i.toLowerCase()});e:if(t){const r=t.attributes.get("uri");if(null===r)break e;const a=re(e,r),s=this.getSegmentedInputForPath(a),n=(await s.getTrackBackings()).find(e=>"audio"===e.getType());if(!n||null===await n.getCodec())break e;const o=await n.getDecoderConfig().then(e=>e?.codec??null);i(null!==o),l.push(o)}}l=[...new Set(l)];let m=null,p=null;const g=t.attributes.getAsNumber("bandwidth");i(null!==g);const k=t.attributes.getAsNumber("average-bandwidth"),b=t.attributes.get("name");for(const e of l){const i=Ee(e);if(null!==i)if(ke.includes(i)){if(null!==m)throw new Error("Unsupported M3U8 file; multiple video codecs found in the CODECS attribute of a variant stream.");m=e;const i=t.attributes.get("video");if(null===i){const e=t.attributes.get("resolution");let i=null,s=null;if(e){const t=e.match(/^(\d+)x(\d+)$/);t&&(i=Number(t[1]),s=Number(t[2]))}a.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:R,lineNumber:t.lineNumber,fullPath:t.fullPath,fullCodecString:m,pairingMask:1n<0?i:null}})}else{if(!o.includes(i))throw new Error(`Invalid M3U8 file; variant stream references audio group "${i}" which is not defined in any #EXT-X-MEDIA tags.`);for(const e of s){const s=e.attributes.get("group-id"),n=e.attributes.get("type");if(s!==i||"audio"!==n.toLowerCase())continue;const o=e.attributes.get("channels")??t.attributes.get("channels"),c=null!==o?Number(o.split("/")[0]):null;a.push({id:-1,demuxer:this,backingTrack:null,default:Aa(e.attributes),autoselect:Aa(e.attributes)||Fa(e.attributes),languageCode:Ra(e.attributes.get("language")),lineNumber:e.lineNumber,fullPath:e.fullPath??t.fullPath,fullCodecString:p,pairingMask:1n<0?c:null}})}}}}return a})),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===R&&(t.languageCode=e.languageCode)):(e.id=l.length+1,l.push(e))};for(const i of c)for(const e of i)u(e);l.sort((e,t)=>e.lineNumber-t.lineNumber),this.trackBackings=[];for(const i of l)"video"===i.info.type?this.trackBackings.push(new Ea(i)):this.trackBackings.push(new _a(i));this.internalTracks=l})())}async getTrackBackings(){return await 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 xa(this,e,i,null),this.segmentedInputs.push(t),t}async getMetadataTags(){return{}}async getMimeType(){return Hr}dispose(){if(this.segmentedInputs){for(const e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}}class Ba{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 r=(await e.getTrackBackings()).filter(e=>e.getType()===this.getType());if(1===r.length)t=r[0];else if(this instanceof Ea){for(const i of r)if(await i.getCodec()===this.getCodec()){t=i;break}}else{i(this instanceof _a);for(const e of r)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{...he,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())}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 Ea extends Ba{constructor(e){super(e)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return"video"}getCodec(){return Ee(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 _a extends Ba{constructor(e){super(e)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return"audio"}getCodec(){return Ee(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 Aa=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}".`)},Fa=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}".`)},Ra=e=>{if(null===e)return R;const t=e.split("-")[0];return t||R};class Da{constructor(){this._isIsobmff=!1}}class Ma extends Da{constructor(){super(...arguments),this._isIsobmff=!0}async _getMajorBrand(e){let t=e._reader.requestSlice(0,12);if(t instanceof Promise&&(t=await t),!t)return null;t.skip(4);const i=In(t,4);return"ftyp"!==i&&"styp"!==i?null:In(t,4)}_createDemuxer(e){return new ei(e)}}class Na extends Ma{async _canReadInput(e){const t=await this._getMajorBrand(e);if(null!==t)return"qt "!==t;let i=e._reader.requestSlice(4,4);return i instanceof Promise&&(i=await i),!!i&&"moof"===In(i,4)}get name(){return"MP4"}get mimeType(){return"video/mp4"}}class Oa extends Ma{async _canReadInput(e){return"qt "===await this._getMajorBrand(e)}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}}class La extends Da{async isSupportedEBMLOfDocType(e,t){let i=e._reader.requestSlice(0,Si);if(i instanceof Promise&&(i=await i),!i)return!1;const r=Pi(i);if(null===r)return!1;if(r<1||r>8)return!1;if(Ii(i,r)!==ki.EBML)return!1;const a=Ci(i);if("number"!==typeof a)return!1;let s=e._reader.requestSlice(i.filePos,a);if(s instanceof Promise&&(s=await s),!s)return!1;const n=i.filePos;for(;s.filePos<=n+a-2;){const e=Bi(s);if(!e)break;const{id:i,size:r}=e,a=s.filePos;if(void 0===r)return!1;switch(i){case ki.EBMLVersion:if(1!==Ii(s,r))return!1;break;case ki.EBMLReadVersion:if(1!==Ii(s,r))return!1;break;case ki.DocType:if(Ei(s,r)!==t)return!1;break;case ki.DocTypeVersion:if(Ii(s,r)>4)return!1}s.filePos=a+r}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new tr(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}}class za extends La{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}}class Ua extends Da{async _canReadInput(e){let t=0;for(;;){let i=e._reader.requestSlice(t,Fn);if(i instanceof Promise&&(i=await i),!i)break;const r=Nn(i);if(!r)break;t=i.filePos+r.size}const i=await sr(e._reader,t,t+4096);if(!i)return!1;const r=i.header,a=De(r.mpegVersionId,r.channel);let s=e._reader.requestSlice(i.startPos+a,4);if(s instanceof Promise&&(s=await s),!s)return!1;const n=gn(s);if(n===Fe||n===Re)return!0;t=i.startPos+i.header.totalSize;const o=await sr(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 nr(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}}class qa extends Da{async _canReadInput(e){let t=e._reader.requestSlice(0,12);if(t instanceof Promise&&(t=await t),!t)return!1;const i=In(t,4);if("RIFF"!==i&&"RIFX"!==i&&"RF64"!==i)return!1;t.skip(4);return"WAVE"===In(t,4)}_createDemuxer(e){return new Sr(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}}class Wa extends Da{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=await t),!!t&&"OggS"===In(t,4)}_createDemuxer(e){return new gr(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}}class Va extends Da{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=await t),!!t&&"fLaC"===In(t,4)}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new Er(e)}}class Ha extends Da{async _canReadInput(e){let t=0;for(;;){let i=e._reader.requestSlice(t,Fn);if(i instanceof Promise&&(i=await i),!i)break;const r=Nn(i);if(!r)break;t=i.filePos+r.size}let i=e._reader.requestSliceRange(t,7,9);if(i instanceof Promise&&(i=await i),!i)return!1;const r=Ir(i);if(!r)return!1;if(t+=r.frameLength,i=e._reader.requestSliceRange(t,7,9),i instanceof Promise&&(i=await i),!i)return!1;const a=Ir(i);return!!a&&(r.objectType===a.objectType&&r.samplingFrequencyIndex===a.samplingFrequencyIndex&&r.channelConfiguration===a.channelConfiguration)}_createDemuxer(e){return new Cr(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}}class Ka extends Da{async _canReadInput(e){let t=e._reader.requestSlice(0,205);if(t instanceof Promise&&(t=await t),!t)return!1;const i=ln(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 Mr(e)}get name(){return"MPEG Transport Stream"}get mimeType(){return"video/MP2T"}}class ja extends Da{async _canReadInput(e){let t=e._reader.requestSlice(0,7);if(t instanceof Promise&&(t=await t),!t)return!1;if(!("#EXTM3U"===In(t,7)))return!1;if(!(e._rootSource instanceof da))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 Ca(e)}get name(){return"HTTP Live Streaming (HLS)"}get mimeType(){return Hr}}const Xa=new Na,$a=new Oa,Qa=new La,Ga=new za,Ya=new Ua,Ja=new qa,Za=new Wa,es=new Ha,ts=new Va,is=new Ka,rs=new ja,as=[rs,Xa,$a,Qa,Ga,Ja,Za,ts,Ya,es,is],ss=[rs,Xa,$a,Ya,es,is];te();let ns=-1/0,os=-1/0,cs=null;"undefined"!==typeof FinalizationRegistry&&(cs=new FinalizationRegistry(e=>{const t=performance.now();"video"===e.type?(t-ns>=1e3&&(console.error("A VideoSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your VideoSamples as soon as you're done using them."),ns=t),"undefined"!==typeof VideoFrame&&e.data instanceof VideoFrame&&e.data.close()):(t-os>=1e3&&(console.error("An AudioSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your AudioSamples as soon as you're done using them."),os=t),"undefined"!==typeof AudioData&&e.data instanceof AudioData&&e.data.close())}));const ls=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],us=new Set(ls);class ds{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(z*this.timestamp)}get microsecondDuration(){return Math.trunc(z*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||!us.has(t.format))throw new TypeError("init.format must be one of: "+ls.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._data=o(e).slice(),this._layout=t.layout??ks(t.format,t.codedWidth,t.codedHeight),this.format=t.format,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=new hs(t.colorSpace),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.codedWidth,this.squarePixelHeight=this.codedHeight)}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&&oe(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 hs(e.colorSpace)}else{if(!("undefined"!==typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!==typeof SVGImageElement&&e instanceof SVGImageElement||"undefined"!==typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!==typeof HTMLVideoElement&&e instanceof HTMLVideoElement||"undefined"!==typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!==typeof OffscreenCanvas&&e instanceof OffscreenCanvas))throw new TypeError("Invalid data type: Must be a BufferSource or CanvasImageSource.");{if(!t||"object"!==typeof t)throw new TypeError("init must be an object.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(void 0!==t.duration&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if("undefined"!==typeof VideoFrame)return new ds(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*z),duration:Math.trunc((t.duration??0)*z)||void 0}),t);let r=0,a=0;if("naturalWidth"in e?(r=e.naturalWidth,a=e.naturalHeight):"videoWidth"in e?(r=e.videoWidth,a=e.videoHeight):"width"in e&&(r=Number(e.width),a=Number(e.height)),!r||!a)throw new TypeError("Could not determine dimensions.");const s=new OffscreenCanvas(r,a),n=s.getContext("2d",{alpha:X(),willReadFrequently:!0});i(n),n.drawImage(e,0,0),this._data=s,this._layout=null,this.format="RGBX",this.visibleRect={left:0,top:0,width:r,height:a},this.squarePixelWidth=r,this.squarePixelHeight=a,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=new hs({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}}this.pixelAspectRatio=ne({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),cs?.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return i(null!==this._data),fs(this._data)?new ds(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation}):this._data instanceof Uint8Array?(i(this._layout),new ds(this._data,{format:this.format,layout:this._layout,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight})):new ds(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight})}close(){this._closed||(cs?.unregister(this),fs(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(gs(e),this._closed)throw new Error("VideoSample is closed.");if(null===this.format)throw new Error("Cannot get allocation size when format is null. Sorry!");if(i(null!==this._data),!fs(this._data)&&(e.colorSpace||e.format&&e.format!==this.format||e.layout||e.rect)){const t=this.toVideoFrame(),i=t.allocationSize(e);return t.close(),i}return fs(this._data)?this._data.allocationSize(e):this._data instanceof Uint8Array?this._data.byteLength:this.codedWidth*this.codedHeight*4}async copyTo(e,t={}){if(!k(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(gs(t),this._closed)throw new Error("VideoSample is closed.");if(null===this.format)throw new Error("Cannot copy video sample data when format is null. Sorry!");if(i(null!==this._data),!fs(this._data)&&(t.colorSpace||t.format&&t.format!==this.format||t.layout||t.rect)){const i=this.toVideoFrame(),r=await i.copyTo(e,t);return i.close(),r}if(fs(this._data))return this._data.copyTo(e,t);if(this._data instanceof Uint8Array){i(this._layout);return o(e).set(this._data),this._layout}{const t=this._data.getContext("2d");i(t);const r=t.getImageData(0,0,this.codedWidth,this.codedHeight);return o(e).set(r.data),[{offset:0,stride:4*this.codedWidth}]}}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");return i(null!==this._data),fs(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace}):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,t,i,r,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 b=f+p/2,y=m+g/2;e.translate(b,y),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&&ps(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;t.crop&&ms(t.crop,s,n);const{sx:d,sy:h,sWidth:f,sHeight:m}=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 p=a%180===0?1:l/u;e.translate(i/2,r/2),e.rotate(a*Math.PI/180),e.scale(1/p,p),e.translate(-i/2,-r/2),e.drawImage(this.toCanvasImageSource(),d,h,f,m,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}}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(i(null!==this._data),this._data instanceof Uint8Array){const e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}return this._data}setRotation(e){if(![0,90,180,270].includes(e))throw new TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}setDuration(e){if(!Number.isFinite(e)||e<0)throw new TypeError("newDuration must be a non-negative number.");this.duration=e}[Symbol.dispose](){this.close()}}class hs{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(d);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(f);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(p);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 fs=e=>"undefined"!==typeof VideoFrame&&e instanceof VideoFrame,ms=(e,t,r)=>{const a=Math.min(e.left,t),s=Math.min(e.top,r),n=Math.min(e.width,t-a),o=Math.min(e.height,r-s);return i(n>=0),i(o>=0),{left:a,top:s,width:n,height:o}},ps=(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.")},gs=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.")}},ks=(e,t,i)=>{const r=bs(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},bs=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:B(e),i(!1)}},ys=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]);class ws{get microsecondTimestamp(){return Math.trunc(z*this.timestamp)}get microsecondDuration(){return Math.trunc(z*this.duration)}constructor(e){if(this._closed=!1,Is(e)){if(null===e.format)throw new TypeError("AudioData with null format is not supported.");this._data=e,this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=e.numberOfFrames,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp/1e6,this.duration=e.numberOfFrames/e.sampleRate}else{if(!e||"object"!==typeof e)throw new TypeError("Invalid AudioDataInit: must be an object.");if(!ys.has(e.format))throw new TypeError("Invalid AudioDataInit: invalid format.");if(!Number.isFinite(e.sampleRate)||e.sampleRate<=0)throw new TypeError("Invalid AudioDataInit: sampleRate must be > 0.");if(!Number.isInteger(e.numberOfChannels)||0===e.numberOfChannels)throw new TypeError("Invalid AudioDataInit: numberOfChannels must be an integer > 0.");if(!Number.isFinite(e?.timestamp))throw new TypeError("init.timestamp must be a number.");const t=e.data.byteLength/(Ts(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*Ts(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=Ts(t),s=Ss(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(!k(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&&!ys.has(t.format))throw new TypeError("Invalid format.");if(void 0!==t.frameOffset&&(!Number.isInteger(t.frameOffset)||t.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(void 0!==t.frameCount&&(!Number.isInteger(t.frameCount)||t.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");const{planeIndex:i,format:r,frameCount:a,frameOffset:s}=t,n=this.format,o=r??this.format;if(!o)throw new Error("Destination format not determined");const l=this.numberOfFrames,u=this.numberOfChannels,d=s??0;if(d>=l)throw new RangeError("frameOffset out of range");const h=void 0!==a?a:l-d;if(h>l-d)throw new RangeError("frameCount out of range");const f=Ts(o),m=Ss(o);if(m&&i>=u)throw new RangeError("planeIndex out of range");if(!m&&0!==i)throw new RangeError("planeIndex out of range");const p=(m?h:h*u)*f;if(e.byteLength2&&o!==n?xs(this._data,g,n,o,u,i,d,h):this._data.copyTo(e,{planeIndex:i,frameOffset:d,frameCount:h,format:o});else{const e=this._data,t=c(e),r=Ps(n),a=Ts(n),s=Ss(n);for(let n=0;n0;){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")}},Ss=e=>{switch(e){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},Ps=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)}},vs=e=>{switch(e){case"u8":case"u8-planar":return(e,t,i)=>e.setUint8(t,F(127.5*(i+1),0,255));case"s16":case"s16-planar":return(e,t,i)=>e.setInt16(t,F(Math.round(32767*i),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,i)=>e.setInt32(t,F(Math.round(2147483647*i),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,i)=>e.setFloat32(t,i,!0)}},Is=e=>"undefined"!==typeof AudioData&&e instanceof AudioData,xs=(e,t,i,r,a,s,n,o)=>{const l=Ps(i),u=vs(r),d=Ts(i),h=Ts(r),f=Ss(i);if(Ss(r))if(f){const r=new ArrayBuffer(o*d),a=c(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.")},_s=e=>{if(!ie(e))throw new TypeError("timestamp must be a number.")},As=(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 Fs{constructor(e){if(!(e instanceof Hs))throw new TypeError("track must be an InputTrack.");this._track=e}async getFirstPacket(e={}){if(Es(e),this._track.input._disposed)throw new sn;return As(this._track,this._track._backing.getFirstPacket(e),e)}async getFirstKeyPacket(e={}){Es(e);const t=await this.getFirstPacket(e);return t?"key"===t.type?t:this.getNextKeyPacket(t,e):null}async getPacket(e,t={}){if(_s(e),Es(t),this._track.input._disposed)throw new sn;return As(this._track,this._track._backing.getPacket(e,t),t)}async getNextPacket(e,t={}){if(!(e instanceof Mt))throw new TypeError("packet must be an EncodedPacket.");if(Es(t),this._track.input._disposed)throw new sn;return As(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(_s(e),Es(t),this._track.input._disposed)throw new sn;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);const r=await this._track._backing.getKeyPacket(e,t);if(!r)return r;i("key"===r.type);return"delta"===await this._track.determinePacketType(r)?this.getKeyPacket(r.timestamp-1/await this._track.getTimeResolution(),t):r}async getNextKeyPacket(e,t={}){if(!(e instanceof Mt))throw new TypeError("packet must be an EncodedPacket.");if(Es(t),this._track.input._disposed)throw new sn;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);const r=await this._track._backing.getNextKeyPacket(e,t);if(!r)return r;i("key"===r.type);return"delta"===await this._track.determinePacketType(r)?this.getNextKeyPacket(r,t):r}packets(e,t,i={}){if(void 0!==e&&!(e instanceof Mt))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 Mt))throw new TypeError("endPacket must be an EncodedPacket.");if(Es(i),this._track.input._disposed)throw new sn;const r=[];let{promise:a,resolve:s}=I(),{promise:n,resolve:o}=I(),c=!1,l=!1,u=null;const d=[],h=()=>Math.max(2,d.length);(async()=>{let u=e??await this.getFirstPacket(i);for(;u&&!l&&!this._track.input._disposed&&!(t&&u.sequenceNumber>=t?.sequenceNumber);)r.length>h()?(({promise:n,resolve:o}=I()),await n):(r.push(u),s(),({promise:a,resolve:s}=I()),u=await this.getNextPacket(u,i));c=!0,s()})().catch(e=>{u||(u=e,s())});const f=this._track;return{async next(){for(;;){if(f.input._disposed)throw new sn;if(l)return{value:void 0,done:!0};if(u)throw u;if(r.length>0){const e=r.shift(),t=performance.now();for(d.push(t);d.length>0&&t-d[0]>=1e3;)d.shift();return o(),{value:e,done:!1}}if(c)return{value:void 0,done:!0};await a}},return:async()=>(l=!0,o(),s(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}}class Rs{constructor(e,t){this.onSample=e,this.onError=t}}class Ds{mediaSamplesInRange(e=0,t=1/0,i){_s(e),_s(t);const r=[];let a=!1,s=null,{promise:n,resolve:o}=I(),{promise:c,resolve:l}=I(),u=!1,d=!1,h=!1,f=null;const m={...i,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{const i=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}=I())))},e=>{f||(f=e,o())}),p=this._createPacketSink(),g=await p.getKeyPacket(e,m)??await p.getFirstKeyPacket(m);let k=g;const b=p.packets(g??void 0,void 0,m);for(await b.next();k&&!d&&!this._track.input._disposed;){const e=Ms(r.length);if(r.length+i.getDecodeQueueSize()>e){({promise:c,resolve:l}=I()),await c;continue}i.decode(k);const t=await b.next();if(t.done)break;k=t.value}await b.return(),h||this._track.input._disposed||await i.flush(),i.close(),!a&&s&&r.push(s),u=!0,o()})().catch(e=>{f||(f=e,o())});const p=this._track,g=()=>{s?.close();for(const e of r)e.close()};return{async next(){for(;;){if(p.input._disposed)throw g(),new sn;if(h)return{value:void 0,done:!0};if(f)throw g(),f;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(),g(),{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 r=async function*(e){Symbol.iterator in e?yield*e[Symbol.iterator]():yield*e[Symbol.asyncIterator]()}(e),a=[],s=[];let{promise:n,resolve:o}=I(),{promise:c,resolve:l}=I(),u=!1,d=!1,h=null;const f=e=>{s.push(e),o(),({promise:n,resolve:o}=I())},m={...t,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{const e=await this._createDecoder(e=>{if(l(),d)return void e.close();let t=0;for(;a.length>0&&e.timestamp-a[0]>-1e-10;)t++,a.shift();if(t>0)for(let i=0;i{h||(h=e,o())}),t=this._createPacketSink();let n=null,p=null,g=-1;const k=async()=>{i(p);let r=p;for(e.decode(r);r.sequenceNumbera&&!d;)({promise:c,resolve:l}=I()),await c;if(d)break;const n=await t.getNextPacket(r,m);i(n),e.decode(n),r=n}g=-1},b=async()=>{await e.flush();for(let e=0;e{h||(h=e,o())});const p=this._track,g=()=>{for(const e of s)e?.close()};return{async next(){for(;;){if(p.input._disposed)throw g(),new sn;if(d)return{value:void 0,done:!0};if(h)throw g(),h;if(s.length>0){const e=s.shift();return i(void 0!==e),l(),{value:e,done:!1}}if(u)return{value:void 0,done:!0};await n}},return:async()=>(d=!0,l(),o(),g(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}}const Ms=e=>0===e?40:8;class Ns extends Rs{constructor(e,t,r,a,s,n){super(e,t),this.codec=r,this.decoderConfig=a,this.rotation=s,this.timeResolution=n,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new V,this.customDecoderQueueSize=0,this.inputTimestamps=[],this.sampleQueue=[],this.currentPacketIndex=0,this.raslSkipped=!1,this.alphaDecoder=null,this.alphaHadKeyframe=!1,this.colorQueue=[],this.alphaQueue=[],this.merger=null,this.mergerCreationFailed=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue=[],this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1;const l=Cs.find(e=>e.supports(r,a));if(l)this.customDecoder=new l,this.customDecoder.codec=r,this.customDecoder.config=a,this.customDecoder.onSample=e=>{if(!(e instanceof ds))throw new TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(e)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{const e=e=>{if(this.alphaQueue.length>0){const t=this.alphaQueue.shift();i(void 0!==t),this.mergeAlpha(e,t)}else this.colorQueue.push(e)};if("avc"===r&&this.decoderConfig.description&&Q()){const e=(e=>{try{const t=c(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++),l=31&t.getUint8(i++),u=[];for(let c=0;c0){const t=tt(e.sequenceParameterSets[0]);t&&0===t.frameMbsOnlyFlag&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"})}}const t=new Error("Decoding error").stack;this.decoder=new VideoDecoder({output:t=>{try{e(t)}catch(i){this.onError(i)}},error:e=>{e.stack=t,this.onError(e)}}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(i(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)).then(()=>this.customDecoderQueueSize--);else{if(i(this.decoder),K()||v(this.inputTimestamps,e.timestamp,e=>e),Q()&&0===this.currentPacketIndex)if("avc"===this.codec){const t=[];for(const r of Xe(e.data,this.decoderConfig)){const i=$e(e.data[r.offset]);i>=20&&i<=31||t.push(e.data.subarray(r.offset,r.offset+r.length))}const i=((e,t)=>{if(t.description){const i=3&o(t.description)[4];return Je(e,i+1)}return Ye(e)})(t,this.decoderConfig);e=new Mt(i,e.type,e.timestamp,e.duration)}else if("hevc"===this.codec){const t=gt(e.data,this.decoderConfig);t&&(e=new Mt(t,e.type,e.timestamp,e.duration))}this.decoder.decode(e.toEncodedVideoChunk()),this.decodeAlphaData(e)}this.currentPacketIndex++}decodeAlphaData(e){if(!e.sideData.alpha||this.mergerCreationFailed)return void this.pushNullAlphaFrame();if(!this.merger)try{this.merger=new Os}catch(r){return console.error("Due to an error, only color data will be decoded.",r),this.mergerCreationFailed=!0,void this.decodeAlphaData(e)}if(!this.alphaDecoder){const e=e=>{if(this.alphaDecoderQueueSize--,this.colorQueue.length>0){const t=this.colorQueue.shift();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)},t=new Error("Decoding error").stack;this.alphaDecoder=new VideoDecoder({output:t=>{try{e(t)}catch(r){this.onError(r)}},error:e=>{e.stack=t,this.onError(e)}}),this.alphaDecoder.configure(this.decoderConfig)}const t=St(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===Ve.RASL_N||i===Ve.RASL_R)return!0}return!1}sampleHandler(e){if(K()){if(this.sampleQueue.length>0&&e.timestamp>=a(this.sampleQueue).timestamp){for(const e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}v(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){if(!t){const t=new ds(e);return void this.sampleHandler(t)}i(this.merger),this.merger.update(e,t),e.close(),t.close();const r=new VideoFrame(this.merger.canvas,{timestamp:e.timestamp,duration:e.duration??void 0}),a=new ds(r);this.sampleHandler(a)}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(i(this.decoder),await Promise.all([this.decoder.flush(),this.alphaDecoder?.flush()]),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),K()){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()):(i(this.decoder),this.decoder.close(),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}}class Os{constructor(){"undefined"!==typeof OffscreenCanvas?this.canvas=new OffscreenCanvas(300,150):this.canvas=document.createElement("canvas");const e=this.canvas.getContext("webgl2",{premultipliedAlpha:!1});if(!e)throw new Error("Couldn't acquire WebGL 2 context.");this.gl=e,this.program=this.createProgram(),this.vao=this.createVAO(),this.colorTexture=this.createTexture(),this.alphaTexture=this.createTexture(),this.gl.useProgram(this.program),this.gl.uniform1i(this.gl.getUniformLocation(this.program,"u_colorTexture"),0),this.gl.uniform1i(this.gl.getUniformLocation(this.program,"u_alphaTexture"),1)}createProgram(){const e=this.createShader(this.gl.VERTEX_SHADER,"#version 300 es\n\t\t\tin vec2 a_position;\n\t\t\tin vec2 a_texCoord;\n\t\t\tout vec2 v_texCoord;\n\t\t\t\n\t\t\tvoid main() {\n\t\t\t\tgl_Position = vec4(a_position, 0.0, 1.0);\n\t\t\t\tv_texCoord = a_texCoord;\n\t\t\t}\n\t\t"),t=this.createShader(this.gl.FRAGMENT_SHADER,"#version 300 es\n\t\t\tprecision highp float;\n\t\t\t\n\t\t\tuniform sampler2D u_colorTexture;\n\t\t\tuniform sampler2D u_alphaTexture;\n\t\t\tin vec2 v_texCoord;\n\t\t\tout vec4 fragColor;\n\t\t\t\n\t\t\tvoid main() {\n\t\t\t\tvec3 color = texture(u_colorTexture, v_texCoord).rgb;\n\t\t\t\tfloat alpha = texture(u_alphaTexture, v_texCoord).r;\n\t\t\t\tfragColor = vec4(color, alpha);\n\t\t\t}\n\t\t"),i=this.gl.createProgram();return this.gl.attachShader(i,e),this.gl.attachShader(i,t),this.gl.linkProgram(i),i}createShader(e,t){const i=this.gl.createShader(e);return this.gl.shaderSource(i,t),this.gl.compileShader(i),i}createVAO(){const e=this.gl.createVertexArray();this.gl.bindVertexArray(e);const t=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),i=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,i),this.gl.bufferData(this.gl.ARRAY_BUFFER,t,this.gl.STATIC_DRAW);const r=this.gl.getAttribLocation(this.program,"a_position"),a=this.gl.getAttribLocation(this.program,"a_texCoord");return this.gl.enableVertexAttribArray(r),this.gl.vertexAttribPointer(r,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(a),this.gl.vertexAttribPointer(a,2,this.gl.FLOAT,!1,16,8),e}createTexture(){const e=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),e}update(e,t){e.displayWidth===this.canvas.width&&e.displayHeight===this.canvas.height||(this.canvas.width=e.displayWidth,this.canvas.height=e.displayHeight),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.colorTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),this.gl.activeTexture(this.gl.TEXTURE1),this.gl.bindTexture(this.gl.TEXTURE_2D,this.alphaTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,t),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4)}close(){this.gl.getExtension("WEBGL_lose_context")?.loseContext(),this.gl=null}}class Ls extends Ds{constructor(e){if(!(e instanceof Xs))throw new TypeError("videoTrack must be an InputVideoTrack.");super(),this._track=e}async _createDecoder(e,t){if(!(await this._track.canDecode()))throw new Error("This video track cannot be decoded by this browser. Make sure to check decodability before using a track.");const r=await this._track.getCodec(),a=await this._track.getRotation(),s=await this._track.getDecoderConfig(),n=await this._track.getTimeResolution();return i(r&&s),new Ns(e,t,r,s,a,n)}_createPacketSink(){return new Fs(this._track)}async getSample(e,t={}){_s(e);for await(const i of this.mediaSamplesAtTimestamps([e],t))return i;throw new Error("Internal error: Iterator returned nothing.")}samples(e=0,t=1/0,i={}){return this.mediaSamplesInRange(e,t,i)}samplesAtTimestamps(e,t={}){return this.mediaSamplesAtTimestamps(e,t)}}class zs{constructor(e,t={}){if(this._rotation=0,this._initPromise=null,this._nextCanvasIndex=0,!(e instanceof Xs))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&&ps(t.crop,"options."),void 0!==t.poolSize&&("number"!==typeof t.poolSize||!Number.isInteger(t.poolSize)||t.poolSize<0))throw new TypeError("poolSize must be a non-negative integer.");this._videoTrack=e,this._alpha=t.alpha??!1,this._options=t,this._fit=t.fit??"fill",this._videoSampleSink=new Ls(e),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=ms(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,r=this._height;let a=this._canvasPool[this._nextCanvasIndex],s=!1;a||("undefined"!==typeof document?(a=document.createElement("canvas"),a.width=t,a.height=r):a=new OffscreenCanvas(t,r),this._canvasPool.length>0&&(this._canvasPool[this._nextCanvasIndex]=a),s=!0),this._canvasPool.length>0&&(this._nextCanvasIndex=(this._nextCanvasIndex+1)%this._canvasPool.length);const n=a.getContext("2d",{alpha:this._alpha||X()});i(n),n.resetTransform(),s||(!this._alpha&&X()?(n.fillStyle="black",n.fillRect(0,0,t,r)):n.clearRect(0,0,t,r)),e.drawWithFit(n,{fit:this._fit,rotation:this._rotation,crop:this._crop});const o={canvas:a,timestamp:e.timestamp,duration:e.duration};return e.close(),o}async getCanvas(e,t){_s(e),await this._ensureInit();const i=await this._videoSampleSink.getSample(e,t);return i&&this._videoSampleToWrappedCanvas(i)}async*canvases(e=0,t=1/0,i){await this._ensureInit(),yield*A(this._videoSampleSink.samples(e,t,i),e=>this._videoSampleToWrappedCanvas(e))}async*canvasesAtTimestamps(e,t){await this._ensureInit(),yield*A(this._videoSampleSink.samplesAtTimestamps(e,t),e=>e&&this._videoSampleToWrappedCanvas(e))}}class Us extends Rs{constructor(e,t,i,r){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new V,this.customDecoderQueueSize=0,this.currentTimestamp=null;const a=t=>{(null===this.currentTimestamp||Math.abs(t.timestamp-this.currentTimestamp)>=t.duration)&&(this.currentTimestamp=t.timestamp);const i=this.currentTimestamp;if(this.currentTimestamp+=t.duration,0===t.numberOfFrames)return void t.close();const a=r.sampleRate;t.setTimestamp(Math.round(i*a)/a),e(t)},s=Bs.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 ws))throw new TypeError("The argument passed to onSample must be an AudioSample.");a(e)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{const e=new Error("Decoding error").stack;this.decoder=new AudioDecoder({output:e=>{try{a(new ws(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)).then(()=>this.customDecoderQueueSize--)):(i(this.decoder),this.decoder.decode(e.toEncodedAudioChunk()))}flush(){return this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(i(this.decoder),this.decoder.flush())}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(i(this.decoder),this.decoder.close())}}class qs extends Rs{constructor(e,t,r){super(e,t),this.decoderConfig=r,this.currentTimestamp=null,i(be.includes(r.codec)),this.codec=r.codec;const{dataType:a,sampleSize:s,littleEndian:n}=Be(this.codec);switch(this.inputSampleSize=s,s){case 1:"unsigned"===a?this.readInputValue=(e,t)=>e.getUint8(t)-128:"signed"===a?this.readInputValue=(e,t)=>e.getInt8(t):"ulaw"===a?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,n)-32768:"signed"===a?this.readInputValue=(e,t)=>e.getInt16(t,n):i(!1);break;case 3:"unsigned"===a?this.readInputValue=(e,t)=>E(e,t,n)-2**23:"signed"===a?this.readInputValue=(e,t)=>((e,t,i)=>E(e,t,i)<<8>>8)(e,t,n):i(!1);break;case 4:"unsigned"===a?this.readInputValue=(e,t)=>e.getUint32(t,n)-2**31:"signed"===a?this.readInputValue=(e,t)=>e.getInt32(t,n):"float"===a?this.readInputValue=(e,t)=>e.getFloat32(t,n):i(!1);break;case 8:"float"===a?this.readInputValue=(e,t)=>e.getFloat64(t,n):i(!1);break;default:B(s),i(!1)}switch(s){case 1:"ulaw"===a||"alaw"===a?(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"===a?(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:B(s),i(!1)}}getDecodeQueueSize(){return 0}decode(e){const t=c(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 c=0;c=n)&&(this.currentTimestamp=e.timestamp);const o=this.currentTimestamp;this.currentTimestamp+=n;const l=new ws({format:this.outputFormat,data:a,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:i,timestamp:o});this.onSample(l)}async flush(){}close(){}}class Ws extends Ds{constructor(e){if(!(e instanceof $s))throw new TypeError("audioTrack must be an InputAudioTrack.");super(),this._track=e}async _createDecoder(e,t){if(!(await this._track.canDecode()))throw new Error("This audio track cannot be decoded by this browser. Make sure to check decodability before using a track.");const r=await this._track.getCodec(),a=await this._track.getDecoderConfig();return i(r&&a),be.includes(a.codec)?new qs(e,t,a):new Us(e,t,r,a)}_createPacketSink(){return new Fs(this._track)}async getSample(e,t={}){_s(e);for await(const i of this.mediaSamplesAtTimestamps([e],t))return i;throw new Error("Internal error: Iterator returned nothing.")}samples(e=0,t=1/0,i={}){return this.mediaSamplesInRange(e,t,i)}samplesAtTimestamps(e,t={}){return this.mediaSamplesAtTimestamps(e,t)}}class Vs{constructor(e){if(!(e instanceof $s))throw new TypeError("audioTrack must be an InputAudioTrack.");this._audioSampleSink=new Ws(e)}_audioSampleToWrappedArrayBuffer(e){const t={buffer:e.toAudioBuffer(),timestamp:e.timestamp,duration:e.duration};return e.close(),t}async getBuffer(e,t){_s(e);const i=await this._audioSampleSink.getSample(e,t);return i&&this._audioSampleToWrappedArrayBuffer(i)}buffers(e=0,t=1/0,i){return A(this._audioSampleSink.samples(e,t,i),e=>this._audioSampleToWrappedArrayBuffer(e))}buffersAtTimestamps(e,t){return A(this._audioSampleSink.samplesAtTimestamps(e,t),e=>e&&this._audioSampleToWrappedArrayBuffer(e))}}class Hs{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof Xs}isAudioTrack(){return this instanceof $s}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}async getInternalCodecId(){return this._backing.getInternalCodecId()}get internalCodecId(){return Ks(this._backing.getInternalCodecId(),"internalCodecId","getInternalCodecId")}async getLanguageCode(){return this._backing.getLanguageCode()}get languageCode(){return Ks(this._backing.getLanguageCode(),"languageCode","getLanguageCode")}async getName(){return this._backing.getName()}get name(){return Ks(this._backing.getName(),"name","getName")}async getTimeResolution(){return this._backing.getTimeResolution()}get timeResolution(){return Ks(this._backing.getTimeResolution(),"timeResolution","getTimeResolution")}async isRelativeToUnixEpoch(){return this._backing.isRelativeToUnixEpoch()}async getDisposition(){return this._backing.getDisposition()}get disposition(){return Ks(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 M((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 Fs(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 Hs))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(Js({filter:e=>e.canBePairedWith(this)},e))}async getPairableVideoTracks(e){return this.input.getVideoTracks(Js({filter:e=>e.canBePairedWith(this)},e))}async getPairableAudioTracks(e){return this.input.getAudioTracks(Js({filter:e=>e.canBePairedWith(this)},e))}async getPrimaryPairableVideoTrack(e){return this.input.getPrimaryVideoTrack(Js({filter:e=>e.canBePairedWith(this)},e))}async getPrimaryPairableAudioTrack(e){return this.input.getPrimaryAudioTrack(Js({filter:e=>e.canBePairedWith(this)},e))}async hasPairableTrack(e){e&&(e=js(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=js(e)),this.hasPairableTrack(async t=>t.isVideoTrack()&&(!e||await e(t)))}hasPairableAudioTrack(e){return e&&(e=js(e)),this.hasPairableTrack(async t=>t.isAudioTrack()&&(!e||await e(t)))}}const Ks=(e,t,i)=>{if(e instanceof Promise)throw new Error(`'${t}' is deprecated and not available synchronously for this track. Use the preferred '${i}()' instead.`);return e},js=e=>{if(void 0!==e&&"function"!==typeof e)throw new TypeError("predicate, when provided, must be a function.");return e?t=>{const i=e=>{if("boolean"!==typeof e)throw new TypeError("predicate must return or resolve to a boolean value.");return e},r=e(t);return r instanceof Promise?r.then(i):i(r)}:void 0};class Xs extends Hs{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 Ks(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){return await(this._backing.getHasOnlyKeyPackets?.())??!1}async getCodedWidth(){return this._backing.getCodedWidth()}get codedWidth(){return Ks(this._backing.getCodedWidth(),"codedWidth","getCodedWidth")}async getCodedHeight(){return this._backing.getCodedHeight()}get codedHeight(){return Ks(this._backing.getCodedHeight(),"codedHeight","getCodedHeight")}async getRotation(){return this._backing.getRotation()}get rotation(){return Ks(this._backing.getRotation(),"rotation","getRotation")}async getSquarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelWidth(){return Ks(this._backing.getSquarePixelWidth(),"squarePixelWidth","getSquarePixelWidth")}async getSquarePixelHeight(){return this._backing.getSquarePixelHeight()}get squarePixelHeight(){return Ks(this._backing.getSquarePixelHeight(),"squarePixelHeight","getSquarePixelHeight")}async getPixelAspectRatio(){return this._pixelAspectRatioCache??(this._pixelAspectRatioCache=ne({num:await this.getSquarePixelWidth()*await this.getCodedHeight(),den:await this.getSquarePixelHeight()*await this.getCodedWidth()}))}get pixelAspectRatio(){return this._pixelAspectRatioCache??(this._pixelAspectRatioCache=ne({num:Ks(this._backing.getSquarePixelWidth(),"pixelAspectRatio","getPixelAspectRatio")*Ks(this._backing.getCodedHeight(),"pixelAspectRatio","getPixelAspectRatio"),den:Ks(this._backing.getSquarePixelHeight(),"pixelAspectRatio","getPixelAspectRatio")*Ks(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=Ks(e,"displayWidth","getDisplayWidth");if(null!==t)return t}const t=Ks(this._backing.getRotation(),"displayWidth","getDisplayWidth")%180===0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight();return Ks(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=Ks(e,"displayHeight","getDisplayHeight");if(null!==t)return t}const t=Ks(this._backing.getRotation(),"displayHeight","getDisplayHeight")%180===0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth();return Ks(t,"displayHeight","getDisplayHeight")}async getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){const e=await this._backing.getColorSpace();return"bt2020"===e.primaries||"smpte432"===e.primaries||"pg"===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(i(null!==t),Cs.some(i=>i.supports(t,e)))return!0;if("undefined"===typeof VideoDecoder)return!1;return!0===(await VideoDecoder.isConfigSupported(e)).supported}catch(e){return console.error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof Mt))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 r=await this.getDecoderConfig();return i(r),St(t,r,e.data)}}class $s extends Hs{constructor(e,t){super(e,t),this._backing=t}get type(){return"audio"}async getCodec(){return this._backing.getCodec()}get codec(){return Ks(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){return await(this._backing.getHasOnlyKeyPackets?.())??!0}async getNumberOfChannels(){return this._backing.getNumberOfChannels()}get numberOfChannels(){return Ks(this._backing.getNumberOfChannels(),"numberOfChannels","getNumberOfChannels")}async getSampleRate(){return this._backing.getSampleRate()}get sampleRate(){return Ks(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(i(null!==t),Bs.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 console.error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof Mt))throw new TypeError("packet must be an EncodedPacket.");return null===await this.getCodec()?null:"key"}}const Qs=e=>-(e??-1/0),Gs=e=>-e,Ys=e=>{if("object"!==typeof e||!e)throw new TypeError("query must be an object.");if(void 0!==e.filter&&"function"!==typeof e.filter)throw new TypeError("query.filter, when provided, must be a function.");if(void 0!==e.sortBy&&"function"!==typeof e.sortBy)throw new TypeError("query.sortBy, when provided, must be a function.");return{filter:e.filter?t=>{const i=e=>{if("boolean"!==typeof e)throw new TypeError("query.filter must return or resolve to a boolean.");return e},r=e.filter(t);return r instanceof Promise?r.then(i):i(r)}:void 0,sortBy:e.sortBy?t=>{const i=e=>{if("number"!==typeof e&&(!Array.isArray(e)||!e.every(e=>"number"===typeof e)))throw new TypeError("query.sortBy must return or resolve to a number or an array of numbers.");return e},r=e.sortBy(t);return r instanceof Promise?r.then(i):i(r)}:void 0}},Js=(e,t)=>({filter:e?.filter||t?.filter?i=>{const r=e?.filter?.(i)??!0,a=e=>!1!==e&&(t?.filter?.(i)??!0);return r instanceof Promise?r.then(a):a(r)}:void 0,sortBy:e?.sortBy||t?.sortBy?i=>{const r=e?.sortBy?.(i)??[],a=t?.sortBy?.(i)??[],s=(e,t)=>[...Array.isArray(e)?e:[e],...Array.isArray(t)?t:[t]];return r instanceof Promise||a instanceof Promise?Promise.all([r,a]).then(([e,t])=>s(e,t)):s(r,a)}:void 0}),Zs=async(e,t)=>{let i=e;if(t?.filter){const r=e.map(e=>t.filter(e));if(r.some(e=>e instanceof Promise)){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=>e instanceof Promise)?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)};te();const en=2;let tn=null;"undefined"!==typeof FinalizationRegistry&&(tn=new FinalizationRegistry(e=>{for(const t of e)t.freed||t.free()}));class rn extends le{get disposed(){return this._disposed}constructor(e){if(super(),this._demuxerPromise=null,this._format=null,this._trackBackingsCache=null,this._backingToTrack=new Map,this._disposed=!1,this._nextSourceCacheAge=0,this._sourceRefs=[],this._sourceCache=[],this._sourceCachePromises=[],this._onFormatDetermined=null,!e||"object"!==typeof e)throw new TypeError("options must be an object.");if(!Array.isArray(e.formats)||e.formats.some(e=>!(e instanceof Da)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof la||e.source instanceof ua))throw new TypeError("options.source must be a Source or SourceRef.");if(e.source instanceof la&&e.source._disposed)throw new TypeError("options.source must not be a disposed Source.");if(void 0!==e.initInput&&!(e.initInput instanceof rn))throw new TypeError("options.initInput, when provided, must be an Input.");void 0!==e.formatOptions&&((e,t)=>{if(!e||"object"!==typeof e)throw new TypeError(`${t}, when provided, must be an object.`);if(void 0!==e.isobmff){if(!e.isobmff||"object"!==typeof e.isobmff)throw new TypeError(`${t}.isobmff, when provided, must be an object.`);if(void 0!==e.isobmff.resolveKeyId&&"function"!==typeof e.isobmff.resolveKeyId)throw new TypeError(`${t}.isobmff.resolveKeyId, when provided, must be a function.`)}})(e.formatOptions,"formatOptions"),this._formats=e.formats,this._initInput=e.initInput??null,this._formatOptions=e.formatOptions??{},e.source instanceof la?this._rootRef=e.source.ref():this._rootRef=e.source,this._sourceRefs.push(this._rootRef),tn?.register(this,this._sourceRefs,this)}get _rootSource(){return this._rootRef.source}async _getSourceUncached(e){i(this._rootSource instanceof da);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 r=this._sourceCache.find(i=>i.cacheGroup===t&&ha(i.request,e));if(r)return r.age++,Promise.resolve(r.sourceRef.source.ref());const a=this._sourceCachePromises.find(i=>i.cacheGroup===t&&ha(i.request,e));if(a)return a.promise.then(e=>e.sourceRef.source.ref());const s=(async()=>{const r=await this._getSourceUncached(e);if(ae(this._sourceCache,e=>e.cacheGroup===t&&1===e.sourceRef.source._refCount)>=4){const e=se(this._sourceCache,e=>e.cacheGroup===t&&1===e.sourceRef.source._refCount?e.age:1/0);i(-1!==e);const r=this._sourceCache[e];this._sourceCache.splice(e,1),r.sourceRef.free(),((e,t)=>{const i=e.indexOf(t);-1!==i&&e.splice(i,1)})(this._sourceRefs,r.sourceRef)}this._sourceRefs.push(r);const a=this._sourceCachePromises.findIndex(t=>t.request===e);i(-1!==a),this._sourceCachePromises.splice(a,1);return{request:e,sourceRef:r,age:this._nextSourceCacheAge++,cacheGroup:t}})();return this._sourceCachePromises.push({request:e,cacheGroup:t,promise:s}),s.then(e=>{const t=e.sourceRef.source.ref();return this._sourceCache.push(e),t})}_getDemuxer(){return this._demuxerPromise??(this._demuxerPromise=(async()=>{this._reader=new nn(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 an})())}get source(){return this._rootSource}async getFormat(){return await this._getDemuxer(),i(this._format),this._format}async canRead(){try{return await this._getDemuxer(),!0}catch(e){if(e instanceof an)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.getFirstTimestamp()));return Math.min(...i)}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=Ys(e));const t=(await this._getTrackBackings()).map(e=>this._wrapBackingAsTrack(e));return Zs(t,e)}async getVideoTracks(e){e&&(e=Ys(e));const t=(await this.getTracks()).filter(e=>e.isVideoTrack());return Zs(t,e)}async getAudioTracks(e){e&&(e=Ys(e));const t=(await this.getTracks()).filter(e=>e.isAudioTrack());return Zs(t,e)}async getPrimaryVideoTrack(e){e&&(e=Ys(e));const t=Js(e,{sortBy:async e=>[Gs((await e.getDisposition()).default),Gs(await e.hasPairableAudioTrack()),Gs(!(await e.hasOnlyKeyPackets())),Qs(await e.getBitrate())]});return(await this.getVideoTracks(t))[0]??null}async getPrimaryAudioTrack(e){e&&(e=Ys(e));const t=await this.getPrimaryVideoTrack(),i=Js(e,{sortBy:async e=>[Gs(!t||e.canBePairedWith(t)),Gs((await e.getDisposition()).default),Qs(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 Xs(this,e):new $s(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,tn?.unregister(this),this._demuxerPromise?.then(e=>e.dispose())}}[Symbol.dispose](){this.dispose()}}class an extends Error{constructor(e="Input has an unsupported or unrecognizable format."){super(e),this.name="UnsupportedInputFormatError"}}class sn extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}}class nn{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 sn;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 on(t,c(t),0,e,e)}const i=e+t,r=this.source._read(e,i,0,ca);return r instanceof Promise?r.then(t=>t?new on(t.bytes,t.view,t.offset,e,i):null):r?new on(r.bytes,r.view,r.offset,e,i):null}requestSliceRange(e,t,r){if(this.source._disposed)throw new sn;if(e<0)return null;if(null!==this.fileSizeNonStrict)return this.requestSlice(e,F(this.fileSizeNonStrict-e,t,r));{const a=this.requestSlice(e,r),s=a=>a||(i(null!==this.fileSizeNonStrict),this.requestSlice(e,F(this.fileSizeNonStrict-e,t,r)));return a instanceof Promise?a.then(s):s(a)}}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);const i=1024*e.length;let r=this.requestSliceRange(i,0,1024);if(r instanceof Promise&&(r=await r),!r)break;e.push(ln(r,r.length)),t+=r.length}const i=new Uint8Array(t);let r=0;for(const a of e)i.set(a,r),r+=a.length;return new on(i,c(i),0,0,t)})()}}class on{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 on(e,c(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 on(this.bytes,this.view,this.offset,e,e+t)}}const cn=(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.`)},ln=(e,t)=>{cn(e,t);const i=e.bytes.subarray(e.bufferPos,e.bufferPos+t);return e.bufferPos+=t,i},un=e=>(cn(e,1),e.view.getUint8(e.bufferPos++)),dn=(e,t)=>{cn(e,2);const i=e.view.getUint16(e.bufferPos,t);return e.bufferPos+=2,i},hn=e=>{cn(e,2);const t=e.view.getUint16(e.bufferPos,!1);return e.bufferPos+=2,t},fn=e=>{cn(e,3);const t=E(e.view,e.bufferPos,!1);return e.bufferPos+=3,t},mn=e=>{cn(e,2);const t=e.view.getInt16(e.bufferPos,!1);return e.bufferPos+=2,t},pn=(e,t)=>{cn(e,4);const i=e.view.getUint32(e.bufferPos,t);return e.bufferPos+=4,i},gn=e=>{cn(e,4);const t=e.view.getUint32(e.bufferPos,!1);return e.bufferPos+=4,t},kn=e=>{cn(e,4);const t=e.view.getUint32(e.bufferPos,!0);return e.bufferPos+=4,t},bn=e=>{cn(e,4);const t=e.view.getInt32(e.bufferPos,!1);return e.bufferPos+=4,t},yn=(e,t)=>{let i,r;return t?(i=pn(e,!0),r=pn(e,!0)):(r=pn(e,!1),i=pn(e,!1)),4294967296*r+i},wn=e=>4294967296*gn(e)+gn(e),Tn=e=>4294967296*bn(e)+gn(e),Sn=e=>{const t=kn(e),i=(e=>{cn(e,4);const t=e.view.getInt32(e.bufferPos,!0);return e.bufferPos+=4,t})(e);return 4294967296*i+t},Pn=e=>{cn(e,4);const t=e.view.getFloat32(e.bufferPos,!1);return e.bufferPos+=4,t},vn=e=>{cn(e,8);const t=e.view.getFloat64(e.bufferPos,!1);return e.bufferPos+=8,t},In=(e,t)=>{cn(e,t);let i="";for(let r=0;rl.decode(ln(e,t)).split("\n").map(e=>e.trim()).filter(e=>e.length>0&&!i?.ignore?.(e));var Cn,Bn,En,_n;(Bn=Cn||(Cn={}))[Bn.Unsynchronisation=128]="Unsynchronisation",Bn[Bn.ExtendedHeader=64]="ExtendedHeader",Bn[Bn.ExperimentalIndicator=32]="ExperimentalIndicator",Bn[Bn.Footer=16]="Footer",(_n=En||(En={}))[_n.ISO_8859_1=0]="ISO_8859_1",_n[_n.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",_n[_n.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",_n[_n.UTF_8=3]="UTF_8";const An=128,Fn=10,Rn=["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"],Dn=(e,t)=>{var i;const r=e.filePos;t.raw??(t.raw={}),(i=t.raw).TAG??(i.TAG=ln(e,An-3)),e.filePos=r;const a=Mn(e,30);a&&(t.title??(t.title=a));const s=Mn(e,30);s&&(t.artist??(t.artist=s));const n=Mn(e,30);n&&(t.album??(t.album=n));const o=Mn(e,4),c=Number.parseInt(o,10);Number.isInteger(c)&&c>0&&(t.date??(t.date=new Date(c,0,1)));const l=ln(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=Mn(e,28),e.skip(2)}else e.skip(-30),u=Mn(e,30);u&&(t.comment??(t.comment=u));const d=un(e);d{const i=ln(e,t),r=J(i.indexOf(0),i.length),a=i.subarray(0,r);let s="";for(let n=0;n{const t=e.filePos,i=In(e,3),r=un(e),a=un(e),s=un(e),n=gn(e);if("ID3"!==i||255===r||255===a||0!==(2155905152&n))return e.filePos=t,null;return{majorVersion:r,revision:a,flags:s,size:Ne(n)}},On=(e,t,i)=>{var r,a,s,n,o;if(![2,3,4].includes(t.majorVersion))return void console.warn(`Unsupported ID3v2 major version: ${t.majorVersion}`);const c=ln(e,t.size),l=new Ln(t,c);if(t.flags&Cn.Footer&&l.removeFooter(),t.flags&Cn.Unsynchronisation&&3===t.majorVersion&&l.ununsynchronizeAll(),t.flags&Cn.ExtendedHeader){const e=l.readU32();3===t.majorVersion?l.pos+=e:l.pos+=e-4}for(;l.pos<=l.bytes.length-l.frameHeaderSize();){const e=l.readId3V2Frame();if(!e)break;const c=l.pos,u=l.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&Cn.Unsynchronisation)),d)console.warn(`Skipping encrypted ID3v2 frame ${e.id}`),l.pos=u;else if(h)console.warn(`Skipping compressed ID3v2 frame ${e.id}`),l.pos=u;else{if(f&&l.ununsynchronizeRegion(l.pos,u),i.raw??(i.raw={}),"TXXX"===e.id){const e=(r=i.raw).TXXX??(r.TXXX={}),t=l.readId3V2TextEncoding(),a=l.readId3V2Text(t,u),s=l.readId3V2Text(t,u);e[a]??(e[a]=s)}else"T"===e.id[0]?(a=i.raw)[s=e.id]??(a[s]=l.readId3V2EncodingAndText(u)):(n=i.raw)[o=e.id]??(n[o]=l.readBytes(e.size));switch(l.pos=c,e.id){case"TIT2":case"TT2":i.title??(i.title=l.readId3V2EncodingAndText(u));break;case"TIT3":case"TT3":i.description??(i.description=l.readId3V2EncodingAndText(u));break;case"TPE1":case"TP1":i.artist??(i.artist=l.readId3V2EncodingAndText(u));break;case"TALB":case"TAL":i.album??(i.album=l.readId3V2EncodingAndText(u));break;case"TPE2":case"TP2":i.albumArtist??(i.albumArtist=l.readId3V2EncodingAndText(u));break;case"TRCK":case"TRK":{const e=l.readId3V2EncodingAndText(u).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=l.readId3V2EncodingAndText(u).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=l.readId3V2EncodingAndText(u);let t=/^\((\d+)\)/.exec(e);if(t){const e=Number.parseInt(t[1]);if(void 0!==Rn[e]){i.genre??(i.genre=Rn[e]);break}}if(t=/^\d+$/.exec(e),t){const e=Number.parseInt(t[0]);if(void 0!==Rn[e]){i.genre??(i.genre=Rn[e]);break}}i.genre??(i.genre=e)}break;case"TDRC":case"TDAT":{const e=l.readId3V2EncodingAndText(u),t=new Date(e);Number.isNaN(t.getTime())||(i.date??(i.date=t))}break;case"TYER":case"TYE":{const e=l.readId3V2EncodingAndText(u),t=Number.parseInt(e,10);Number.isInteger(t)&&(i.date??(i.date=new Date(t,0,1)))}break;case"USLT":case"ULT":{const e=l.readU8();l.pos+=3,l.readId3V2Text(e,u),i.lyrics??(i.lyrics=l.readId3V2Text(e,u))}break;case"COMM":case"COM":{const e=l.readU8();l.pos+=3,l.readId3V2Text(e,u),i.comment??(i.comment=l.readId3V2Text(e,u))}break;case"APIC":case"PIC":{const e=l.readId3V2TextEncoding();let r;if(2===t.majorVersion){const e=l.readAscii(3);r="PNG"===e?"image/png":"JPG"===e?"image/jpeg":"image/*"}else r=l.readId3V2Text(e,u);const a=l.readU8(),s=l.readId3V2Text(e,u).trimEnd(),n=u-l.pos;if(n>=0){const e=l.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:l.pos+=e.size}l.pos=u}}};class Ln{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:Ne(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 En.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=J(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=J(r.findIndex(e=>0===e),r.length);return this.pos=i+Math.min(e+1,r.length),l.decode(r.subarray(0,e))}case En.UTF_16_BE_NO_BOM:{const e=new TextDecoder("utf-16be"),t=J(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 En.UTF_8:{const e=J(r.findIndex(e=>0===e),r.length);return this.pos=i+Math.min(e+1,r.length),l.decode(r.subarray(0,e))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";const t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}}class zn{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 Vs(r),void t?.()):(this.audioSink=null,this.ensureAudioContext(),void t?.()):(this.handleNoAudioTrack(),void t?.())}async runIterator(e){if(this.audioSink)for(await this.stopIterator(),this.audioIterator=this.audioSink.buffers(this.currentTime);;){if(e!==this.asyncId||this.paused)return;const i=this.audioIterator.next(),r=setInterval(()=>{e!==this.asyncId||this.paused?clearInterval(r):"running"===this.audioContext.state&&this.audioContext.currentTime>=this.latestScheduledEndTime-.2&&(this.audioContext.suspend(),this.events.emit("waiting"))},50);let a;try{a=await i}catch(t){console.error("Audio iterator error:",t);break}finally{clearInterval(r)}if(e!==this.asyncId||this.paused)return;if("suspended"===this.audioContext.state&&(await this.audioContext.resume(),this.events.emit("canplay"),this.events.emit("playing")),a.done)break;const{buffer:s,timestamp:n}=a.value,o=this.audioContext.createBufferSource();o.buffer=s,o.connect(this.gainNode),o.playbackRate.value=this.playbackRate;const c=this.audioContextStartTime+(n-this.playbackTimeAtStart)/this.playbackRate,l=c+s.duration/this.playbackRate;l>this.latestScheduledEndTime&&(this.latestScheduledEndTime=l),c>=this.audioContext.currentTime?o.start(c):o.start(this.audioContext.currentTime,(this.audioContext.currentTime-c)*this.playbackRate),this.queuedNodes.add(o),o.onended=()=>this.queuedNodes.delete(o)}}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.audioContextStartTime,this.paused=!1;const e=++this.asyncId;this.runIterator(e)}pause(){this.paused||(this.playbackTimeAtStart=this.currentTime,this.paused=!0,this.stopIterator(),this.stopQueuedNodes())}async seek(e){this.playbackTimeAtStart=Math.max(0,e),this.audioContextStartTime=this.audioContext.currentTime,this.latestScheduledEndTime=this.audioContextStartTime;const t=++this.asyncId;this.paused||this.runIterator(t)}setVolume(e,t){this.volume=e,this.muted=t,this.updateGain()}setPlaybackRate(e){if(e!==this.playbackRate&&(this.paused||(this.playbackTimeAtStart=this.currentTime,this.audioContextStartTime=this.audioContext.currentTime),this.playbackRate=e,!this.paused)){const e=++this.asyncId;this.runIterator(e)}}destroy(){this.asyncId++,this.pause(),this.audioContext?.close(),this.audioContext=null,this.input=null,this.audioSink=null}}const Un=/\.m3u8(?:$|[?#])/i;function qn(e){return"string"===typeof e&&Un.test(e)}function Wn(e){const t=function(e){return"string"===typeof e?new ka(e):e instanceof Blob?new ma(e):"undefined"!==typeof ReadableStream&&e instanceof ReadableStream?new ba(e):e??null}(e);return t?new rn({source:t,formats:qn(e)?ss:as}):null}async function Vn({input:e,videoTrack:t,audioTrack:i}){const r=[t,i].filter(Boolean),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}async function Hn(e){return await e.getAverageBitrate()??await e.getBitrate()??0}class Kn{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){if(!this.preflightRange||"string"!==typeof e||qn(e))return!0;try{const t=(await fetch(e,{method:"HEAD"})).headers.get("accept-ranges");return!(!t||"none"===t)||(this.events.emit("error",new Event("RangeNotSupported")),!1)}catch(t){return console.warn("Preflight check failed:",t),!0}}drawPoster(){if(!this.poster||this.posterDrawn)return;const e=new Image;e.onload=()=>{this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.canvas.width=e.naturalWidth||this.canvas.width,this.canvas.height=e.naturalHeight||this.canvas.height,this.ctx.drawImage(e,0,0,this.canvas.width,this.canvas.height),this.posterDrawn=!0},e.src=this.poster}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 zs(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 jn{constructor({canvas:e,ctx:t,events:i,option:r={}}){this.events=i,this.option=r,this.audio=new zn(i),this.video=new Kn({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,i.addEventListener?.("ended",()=>{this.ended=!0,this.paused=!0})}async load(e){const t=++this.loadSeq;this.pause(),this.disposeInput(),this.ended=!1,this.error=null,this.networkState=2,this.readyState=0,setTimeout(()=>this.events.emit("waiting"),0),setTimeout(()=>this.events.emit("loadstart"),0);const i=Number.isFinite(this.option.loadTimeout)?this.option.loadTimeout:0;try{await Promise.race([this.performLoad(e,t),i>0?this.createTimeout(i):new Promise(()=>{})])}catch(r){if(t!==this.loadSeq)return;this.loadSeq++,this.error={code:4,message:r.message},this.networkState=3,this.events.emit("error")}}async performLoad(e,t){if(!(await this.video.preflight(e)))return;const i=Wn(e);if(!i)return this.video.handleNoVideoTrack(),void this.audio.handleNoAudioTrack();const r=await async function(e,t){const i=await e.getPrimaryVideoTrack(),r=i?await i.getPrimaryPairableAudioTrack():await e.getPrimaryAudioTrack(),a=await Vn({input:e,videoTrack:i,audioTrack:r});return{input:e,videoTrack:i,audioTrack:r,duration:a,isLive:!Number.isFinite(a)&&Boolean((i||r)&&await(i||r).isLive()),isHls:qn(t),videoMode:qn(t)?"auto":"manual",audioMode:qn(t)?"auto":"manual"}}(i,e);if(t!==this.loadSeq)return void i.dispose();this.disposeInput(),this.input=i,this.media=r;let a=!r.videoTrack,s=!r.audioTrack;const n=()=>{a&&s&&(this.readyState=1,this.events.emit("loadedmetadata"),this.events.emit("durationchange"),this.events.emit("progress"))};try{if(await Promise.all([this.video.load(r,()=>{t===this.loadSeq&&(a=!0,n())}),this.audio.load(r,()=>{t===this.loadSeq&&(s=!0,n())})]),t!==this.loadSeq)return;this.readyState=4,this.networkState=1,this.events.emit("loadeddata"),this.events.emit("canplay"),this.events.emit("canplaythrough"),this.events.emit("progress")}catch(o){if(t!==this.loadSeq)return;this.error={code:4,message:o.message},this.networkState=3,this.events.emit("error"),console.error("MediaBunny load error:",o)}}createTimeout(e){return new Promise((t,i)=>{setTimeout(()=>i(new Error("Load timeout")),e)})}disposeInput(){this.input?.dispose(),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 Vn(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 Hn(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 Hn(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.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}}class Xn{constructor({art:e,canvas:i,ctx:r,option:a}){this.art=e,this.canvas=i,this.option=a,this.events=new t,this.engine=new jn({canvas:i,ctx:r,events:this.events,option:a}),this._src=null,this._volume=a.volume??.7,this._muted=!!a.muted,this._playbackRate=1,this.engine.setVolume(this._volume,this._muted),this.setupEventForwarding(),a.source?this.src=a.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){const i=this.engine.duration;return!i||Number.isNaN(i)||t<=0?{length:0,start:()=>0,end:()=>0}:{length:1,start:()=>e,end:()=>t}}get paused(){return this.engine.paused}get playing(){return!this.engine.paused&&!this.engine.ended}get ended(){return this.engine.ended}get seeking(){return this.engine.seeking}get readyState(){return this.engine.readyState}get networkState(){return this.engine.networkState}get error(){return this.engine.error}get playbackRate(){return this._playbackRate}set playbackRate(e){const t=Number(e);Number.isNaN(t)||t<=0||(this._playbackRate=t,this.engine.setPlaybackRate(t),this.events.emit("ratechange"))}get volume(){return this._volume}set volume(e){this._volume=function(e,t,i){return Math.max(t,Math.min(i,Number(e)||0))}(e,0,1),this._muted=!1,this.engine.setVolume(this._volume,this._muted),this.events.emit("volumechange")}get muted(){return this._muted}set muted(e){this._muted=!!e,this.engine.setVolume(this._volume,this._muted),this.events.emit("volumechange")}play(){return this.engine.play()}pause(){this.engine.pause()}load(){this._src&&this.engine.load(this._src)}getM3u8State(){return this.engine.getHlsState()}switchM3u8Quality(e){return this.engine.selectHlsQuality(e)}switchM3u8Audio(e){return this.engine.selectHlsAudio(e)}get videoWidth(){return this.engine.videoWidth}get videoHeight(){return this.engine.videoHeight}get poster(){return this.option.poster||""}set poster(e){this.option.poster=e}get autoplay(){return this.option.autoplay||!1}set autoplay(e){}get loop(){return this.option.loop||!1}set loop(e){}get controls(){return!1}set controls(e){}get playsInline(){return!0}set playsInline(e){}get crossOrigin(){return this.option.crossOrigin||""}set crossOrigin(e){}get preload(){return"auto"}set preload(e){}get defaultMuted(){return!1}set defaultMuted(e){}get defaultPlaybackRate(){return 1}set defaultPlaybackRate(e){}canPlayType(e){return"maybe"}getBoundingClientRect(){return this.canvas.getBoundingClientRect()}requestVideoFrameCallback(e){return requestAnimationFrame(t=>{e(t,{presentationTime:this.engine.currentTime,expectedDisplayTime:t+16.6,width:this.engine.videoWidth,height:this.engine.videoHeight,mediaTime:this.engine.currentTime,presentedFrames:0,processingDuration:0,captureTime:t,receiveTime:t,rtpTimestamp:0})})}cancelVideoFrameCallback(e){cancelAnimationFrame(e)}setAttribute(e,t){"src"===e?this.src=t:"autoplay"===e?this.autoplay=t:"loop"===e?this.loop=t:"muted"===e?this.muted=!0:this.canvas.setAttribute(e,t)}destroy(){this.engine.destroy()}}return function(t={}){return i=>{const{constructor:r}=i,{createElement:a}=r.utils,s=a("canvas"),n=s.getContext("2d"),o=new Xn({art:i,canvas:s,ctx:n,option:t});i.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=i.template?.$player;e&&!i.option.autoSize&&Object.assign(s.style,{width:"100%",height:"100%",objectFit:"contain"})}return i.on("resize",u),i.on("video:loadedmetadata",u),function({art:t,shim:i,option:r}){if(r.m3u8)return t.on("video:loadedmetadata",d),t.on("restart",d),{update:d};function a(e){t.controls.cache.has(e)&&t.controls.remove(e)}function s(e){t.setting.find(e)&&t.setting.remove(e)}function n(){a("mediabunny-quality"),s("mediabunny-quality")}function o(){a("mediabunny-audio"),s("mediabunny-audio")}function c(e={}){return e.control||e.setting}async function l(a){const s=r.m3u8?.quality||{};if(!c(s)||!a?.levels.length)return void n();const o=s.auto||"Auto",l=s.title||"Quality",u=s.getName||(e=>e.name||`${e.height}P`),h=a.currentLevel?u(a.currentLevel):o,f=e(a.levels.map(e=>({html:u(e),value:e.id,default:a.currentLevel?.id===e.id})),"html").sort((e,t)=>{const i=a.levels.find(t=>t.id===e.value),r=a.levels.find(e=>e.id===t.value);return(r?.height||0)-(i?.height||0)});f.push({html:o,value:"auto",default:!a.currentLevel});const m=async e=>(await i.switchM3u8Quality(e.value),t.notice.show=`${l}: ${e.html}`,await d(),e.html);s.control&&t.controls.update({name:"mediabunny-quality",position:"right",html:h,style:{padding:"0 10px"},selector:f,onSelect:m}),s.setting&&t.setting.update({name:"mediabunny-quality",tooltip:h,html:l,icon:'',width:200,selector:f,onSelect:m})}async function u(a){const s=r.m3u8?.audio||{};if(!c(s)||!a?.audios.length||a.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=a.currentAudio?u(a.currentAudio):n,f=e(a.audios.map(e=>({html:u(e),value:e.id,default:a.currentAudio?.id===e.id})),"html");f.push({html:n,value:"auto",default:!a.currentAudio});const m=async e=>(await i.switchM3u8Audio(e.value),t.notice.show=`${l}: ${e.html}`,await d(),e.html);s.control&&t.controls.update({name:"mediabunny-audio",position:"right",html:h,style:{padding:"0 10px"},selector:f,onSelect:m}),s.setting&&t.setting.update({name:"mediabunny-audio",tooltip:h,html:l,icon:'',width:200,selector:f,onSelect:m})}async function d(){const e=await i.getM3u8State();if(!e)return n(),void o();await Promise.all([l(e),u(e)])}}({art:i,shim:o,option:t}),i.on("destroy",()=>{delete i.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";function e(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 t{constructor(){this.listeners=new Map}addEventListener(e,t){this.listeners.has(e)||this.listeners.set(e,[]),this.listeners.get(e).push(t)}removeEventListener(e,t){const i=this.listeners.get(e);if(!i)return;const r=i.indexOf(t);r>=0&&i.splice(r,1)}emit(e,t){const i=new Event(e);i.detail=t;const r=this.listeners.get(e);r&&r.forEach(e=>e(i))}}function i(e){if(!e)throw new Error("Assertion failed.")}const r=e=>{const t=(e%360+360)%360;if(0===t||90===t||180===t||270===t)return t;throw new Error(`Invalid rotation ${e}.`)},a=e=>e&&e[e.length-1],s=e=>{let t=0;for(;0===e.readBits(1)&&t<32;)t++;if(t>=32)throw new Error("Invalid exponential-Golomb code.");return(1<{const i=t+1,r=Math.floor(Math.log2(i));e.writeBits(r,0),e.writeBits(1,1),e.writeBits(r,i-2**r)},o=e=>{const t=s(e);return 0===(1&t)?-(t>>1):t+1>>1},c=e=>e.constructor===Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),l=e=>e.constructor===DataView?e:ArrayBuffer.isView(e)?new DataView(e.buffer,e.byteOffset,e.byteLength):new DataView(e),u=new TextDecoder,d=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])),h={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},f=d(h),m={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},p=d(m),g={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},k=d(g),y=e=>!!e&&!!e.primaries&&!!e.transfer&&!!e.matrix&&void 0!==e.fullRange,b={primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0},w=e=>e instanceof ArrayBuffer||"undefined"!==typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e);class T{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 S=/^[0-9a-fA-F]+$/,v=e=>[...e].map(e=>e.toString(16).padStart(2,"0")).join(""),P=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,I=(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},C=(e,t,i)=>{const r=x(e,i(t),i);e.splice(r+1,0,t)},B=()=>{let e,t;return{promise:new Promise((i,r)=>{e=i,t=r}),resolve:e,reject:t}},E=(e,t)=>{const i=e.indexOf(t);-1!==i&&e.splice(i,1)},_=(e,t)=>{for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},R=(e,t)=>{for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},F=e=>{throw new Error(`Unexpected value: ${e}`)},A=(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},D=(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)},M=(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}}),N=(e,t,i)=>Math.max(t,Math.min(i,e)),O="und",L=e=>{const t=Math.round(e);return Math.abs(e/t-1)<10*Number.EPSILON?t:e},z=(e,t)=>Math.round(e/t)*t,U=(e,t)=>Math.round(e*t)/t,q=(e,t)=>Math.floor(e/t)*t,W=e=>{let t=0;for(;0!==e;)e&=e-1,t++;return t},H=/^[a-z]{3}$/,V=e=>H.test(e),j=1e6*(1+Number.EPSILON),K=(e,t)=>{const i={...e,...t};if(e.headers||t.headers){const r=e.headers?X(e.headers):{},a=t.headers?X(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},X=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},$=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(be._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 pe(1e3*e),a())throw n}};class G{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}let Q=null;const Y=()=>null!==Q?Q:Q=!("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 J=null;const Z=()=>null!==J?J:J="undefined"!==typeof navigator&&navigator.userAgent?.includes("Firefox");let ee=null;const te=()=>null!==ee?ee:ee=!("undefined"===typeof navigator||!navigator.vendor?.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.`,re=(async()=>{})().constructor,ae=e=>e instanceof re||e instanceof Promise||"function"===typeof e?.then,se=(e,t)=>-1!==e?e:t,ne=(e,t,i,r)=>e<=r&&i<=t,oe=e=>{const t=atob(e),i=new Uint8Array(t.length);for(let r=0;r{Symbol.dispose??(Symbol.dispose=Symbol("Symbol.dispose"))},le=e=>"number"===typeof e&&!Number.isNaN(e),ue=(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("/")},de=(e,t)=>{let i=0;for(let r=0;r{let i=-1,r=1/0;for(let a=0;a{i(Number.isInteger(e.num)),i(Number.isInteger(e.den)),i(0!==e.den);let t=Math.abs(e.num),r=Math.abs(e.den);for(;0!==r;){const e=t%r;t=r,r=e}const a=t||1;return{num:e.num/a,den:e.den/a}},me=(e,t)=>{if("object"!==typeof e||!e)throw new TypeError(`${t} must be an object.`);if(!Number.isInteger(e.left)||e.left<0)throw new TypeError(`${t}.left must be a non-negative integer.`);if(!Number.isInteger(e.top)||e.top<0)throw new TypeError(`${t}.top must be a non-negative integer.`);if(!Number.isInteger(e.width)||e.width<0)throw new TypeError(`${t}.width must be a non-negative integer.`);if(!Number.isInteger(e.height)||e.height<0)throw new TypeError(`${t}.height must be a non-negative integer.`)},pe=e=>new Promise(t=>setTimeout(t,e));class ge{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 ke,ye;(ye=ke||(ke={}))[ye.Silent=0]="Silent",ye[ye.Errors=1]="Errors",ye[ye.Warnings=2]="Warnings",ye[ye.Info=3]="Info";class be{constructor(){}static get level(){return be._level}static set level(e){if(e!==ke.Silent&&e!==ke.Errors&&e!==ke.Warnings&&e!==ke.Info)throw new TypeError("Invalid log level. Use one of the values of the LogLevel enum.");be._level=e}static get _emitter(){return be._emitterInstance??(be._emitterInstance=new ge)}static on(e,t,i){return be._emitter.on(e,t,i)}static _error(...e){be._emitter._emit("error",e),be._level>=ke.Errors&&console.error(...e)}static _warn(...e){be._emitter._emit("warn",e),be._level>=ke.Warnings&&console.warn(...e)}static _info(...e){be._emitter._emit("info",e),be._level>=ke.Info&&console.info(...e)}}be._level=ke.Info,be._emitterInstance=null;class we{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 Te{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 Se={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1};class ve{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 ve(this.bytes);return e.pos=this.pos,e}}const Pe=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],Ie=[-1,1,2,3,4,5,6,8],xe=e=>{if(!e||e.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");const t=new ve(e),i=Ce(t),{frequencyIndex:r,sampleRate:a}=Be(t),s=t.readBits(4);let n=null;s>=1&&s<=7&&(n=Ie[s]);let o=i,c=!1,l=a;if(5===i||29===i)c=29===i,l=Be(t).sampleRate,o=Ce(t),22===o&&t.skipBits(4);else for(;t.getBitsLeft()>15;){const e=t.pos;if(695===t.readBits(11)){5===Ce(t)&&t.readBits(1)&&(l=Be(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}},Ce=e=>{const t=e.readBits(5);return 31===t?32+e.readBits(6):t},Be=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&c(t.description)[4];return Ne(e,i+1)}return Me(e)},Le=e=>31&e,ze=e=>{const t=[],i=e.length;for(let r=0;r{const t=e.reduce((e,t)=>e+Ue.byteLength+t.byteLength,0),i=new Uint8Array(t);let r=0;for(const a of e)i.set(Ue,r),r+=Ue.byteLength,i.set(a,r),r+=a.byteLength;return i},We=(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:D(e,a,s.byteLength);break;case 4:e.setUint32(a,s.byteLength,!1)}a+=t,r.set(s,a),a+=s.byteLength}return r},He=e=>{try{const t=[],r=[],a=[];for(const i of Me(e)){const s=e.subarray(i.offset,i.offset+i.length),n=Le(s[0]);n===Re.SPS?t.push(s):n===Re.PPS?r.push(s):n===Re.SPS_EXT&&a.push(s)}if(0===t.length)return null;if(0===r.length)return null;const s=t[0],n=Xe(s);i(null!==n);const o=100===n.profileIdc||110===n.profileIdc||122===n.profileIdc||144===n.profileIdc;return{configurationVersion:1,avcProfileIndication:n.profileIdc,profileCompatibility:n.constraintFlags,avcLevelIndication:n.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:t,pictureParameterSets:r,chromaFormat:o?n.chromaFormatIdc:null,bitDepthLumaMinus8:o?n.bitDepthLumaMinus8:null,bitDepthChromaMinus8:o?n.bitDepthChromaMinus8:null,sequenceParameterSetExt:o?a:null}}catch(t){return be._error("Error building AVC Decoder Configuration Record:",t),null}},Ve=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=l(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++),u=[];for(let l=0;l{try{const t=ze(e),r=new ve(t);r.skipBits(1),r.skipBits(2);if(7!==r.readBits(5))return null;const n=r.readAlignedByte(),c=r.readAlignedByte(),l=r.readAlignedByte();s(r);let u=1,d=0,h=0,f=0;if(100===n||110===n||122===n||244===n||44===n||83===n||86===n||118===n||128===n){u=s(r),3===u&&(f=r.readBits(1)),d=s(r),h=s(r),r.skipBits(1);if(r.readBits(1))for(let e=0;e<(3!==u?8:12);e++){if(r.readBits(1)){const t=e<6?16:64;let i=8,a=8;for(let e=0;ee.level>=l)??a(Vt),r=Math.min(Math.floor(i.maxDpbMbs/(e*t)),16);C=r,B=r}else C=0,B=0}return i(null!==B),{emulationUnpreventedBytes:t,profileIdc:n,constraintFlags:c,levelIdc:l,frameMbsOnlyFlag:T,chromaFormatIdc:u,bitDepthLumaMinus8:d,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 be._error("Error parsing AVC SPS:",t),null}},$e=e=>{const t=s(e);e.skipBits(4),e.skipBits(4);for(let i=0;i<=t;i++)s(e),s(e),e.skipBits(1);e.skipBits(5),e.skipBits(5),e.skipBits(5),e.skipBits(5)},Ge=e=>{i(1!==e.bitstreamRestrictionFlag);const t=new Uint8Array(e.emulationUnpreventedBytes.byteLength+64),r=new ve(e.emulationUnpreventedBytes),a=new ve(t);null===e.bitstreamRestrictionFlag?(a.copyBits(e.vuiParametersFlagBitOffset,r),a.writeBits(1,1),a.writeBits(1,0),a.writeBits(1,0),a.writeBits(1,0),a.writeBits(1,0),a.writeBits(1,0),a.writeBits(1,0),a.writeBits(1,0),a.writeBits(1,0)):(i(null!==e.bitstreamRestrictionFlagBitOffset),a.copyBits(e.bitstreamRestrictionFlagBitOffset,r)),a.writeBits(1,1),a.writeBits(1,1),n(a,2),n(a,1),n(a,16),n(a,16),n(a,e.numReorderFrames),n(a,e.maxDecFrameBuffering),a.writeBits(1,1),a.writeBits((8-a.pos%8)%8,0);const s=a.pos/8;return i(Number.isInteger(s)),(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,s))},Qe=(e,t)=>{if(t.description){const i=3&c(t.description)[21];return Ne(e,i+1)}return Me(e)},Ye=e=>e>>1&63,Je=e=>{try{const t=new ve(ze(e));t.skipBits(16),t.readBits(4);const i=t.readBits(3),r=t.readBits(1),{general_profile_space:a,general_tier_flag:n,general_profile_idc:o,general_profile_compatibility_flags:c,general_constraint_indicator_flags:l,general_level_idc:u}=et(t,i);s(t);const d=s(t);let h=0;3===d&&(h=t.readBits(1));const f=s(t),m=s(t);let p=f,g=m;if(t.readBits(1)){const e=s(t),i=s(t),r=s(t),a=s(t);let n=1,o=1;const c=0===h?d:0;1===c?(n=2,o=2):2===c&&(n=2,o=1),p-=(e+i)*n,g-=(r+a)*o}const k=s(t),y=s(t);s(t);const b=t.readBits(1);let w=0;for(let e=b?0:i;e<=i;e++)s(t),w=s(t),s(t);s(t),s(t),s(t),s(t),s(t),s(t),t.readBits(1)&&t.readBits(1)&&tt(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(4),t.skipBits(4),s(t),s(t),t.skipBits(1));const T=s(t);if(it(t,T),t.readBits(1)){const e=s(t);for(let i=0;i{try{const t=[],i=[],r=[],a=[];for(const s of Me(e)){const n=e.subarray(s.offset,s.offset+s.length),o=Ye(n[0]);o===Ae.VPS_NUT?t.push(n):o===Ae.SPS_NUT?i.push(n):o===Ae.PPS_NUT?r.push(n):o!==Ae.PREFIX_SEI_NUT&&o!==Ae.SUFFIX_SEI_NUT||a.push(n)}if(0===i.length||0===r.length)return null;const n=Je(i[0]);if(!n)return null;let c=0;if(r.length>0){const e=r[0],t=new ve(ze(e));t.skipBits(16),s(t),s(t),t.skipBits(1),t.skipBits(1),t.skipBits(3),t.skipBits(1),t.skipBits(1),s(t),s(t),o(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&s(t),o(t),o(t),t.skipBits(1),t.skipBits(1),t.skipBits(1),t.skipBits(1);const i=t.readBits(1),a=t.readBits(1);c=i||a?i&&!a?2:!i&&a?3:0:0}const l=[...t.length?[{arrayCompleteness:1,nalUnitType:Ae.VPS_NUT,nalUnits:t}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:Ae.SPS_NUT,nalUnits:i}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:Ae.PPS_NUT,nalUnits:r}]:[],...a.length?[{arrayCompleteness:1,nalUnitType:Ye(a[0][0]),nalUnits:a}]:[]];return{configurationVersion:1,generalProfileSpace:n.generalProfileSpace,generalTierFlag:n.generalTierFlag,generalProfileIdc:n.generalProfileIdc,generalProfileCompatibilityFlags:n.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:n.generalConstraintIndicatorFlags,generalLevelIdc:n.generalLevelIdc,minSpatialSegmentationIdc:n.minSpatialSegmentationIdc,parallelismType:c,chromaFormatIdc:n.chromaFormatIdc,bitDepthLumaMinus8:n.bitDepthLumaMinus8,bitDepthChromaMinus8:n.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:n.spsMaxSubLayersMinus1+1,temporalIdNested:n.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:l}}catch(t){return be._error("Error building HEVC Decoder Configuration Record:",t),null}},et=(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&&o(e);for(let t=0;t{const i=[];for(let r=0;r{let a=0,n=0,o=0;if(0!==t&&(n=e.readBits(1)),n){if(t===i){o=t-(s(e)+1)}else o=t-1;e.readBits(1),s(e);const n=r[o]??0;for(let t=0;t<=n;t++){e.readBits(1)||e.readBits(1)}a=r[o]}else{const t=s(e),i=s(e);for(let r=0;r{let i=2,r=2,a=2,n=0,o=0,c={num:1,den:1};if(e.readBits(1)){const t=e.readBits(8);if(255===t)c={num:e.readBits(16),den:e.readBits(16)};else{const e=Ke[t];e&&(c=e)}}return e.readBits(1)&&e.readBits(1),e.readBits(1)&&(e.readBits(3),n=e.readBits(1),e.readBits(1)&&(i=e.readBits(8),r=e.readBits(8),a=e.readBits(8))),e.readBits(1)&&(s(e),s(e)),e.readBits(1),e.readBits(1),e.readBits(1),e.readBits(1)&&(s(e),s(e),s(e),s(e)),e.readBits(1)&&(e.readBits(32),e.readBits(32),e.readBits(1)&&s(e),e.readBits(1)&&st(e,!0,t)),e.readBits(1)&&(e.readBits(1),e.readBits(1),e.readBits(1),o=s(e),s(e),s(e),s(e),s(e)),{pixelAspectRatio:c,colourPrimaries:i,transferCharacteristics:r,matrixCoefficients:a,fullRangeFlag:n,minSpatialSegmentationIdc:o}},st=(e,t,i)=>{let r=!1,a=!1,n=!1;r=1===e.readBits(1),a=1===e.readBits(1),(r||a)&&(n=1===e.readBits(1),n&&(e.readBits(8),e.readBits(5),e.readBits(1),e.readBits(5)),e.readBits(4),e.readBits(4),n&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5));for(let o=0;o<=i;o++){let t=!0;1===e.readBits(1)||(t=1===e.readBits(1));let i=!1;t?s(e):i=1===e.readBits(1);let o=1;if(!i){o=s(e)+1}r&&nt(e,o,n),a&&nt(e,o,n)}},nt=(e,t,i)=>{for(let r=0;r{const i=new Set;let r=ot.audAllowed;for(const s of Qe(e,t)){if(r===ot.noMoreDataAllowed){i.add(s.offset);continue}const t=Ye(e[s.offset]);if(r===ot.eoBitstreamAllowed&&37!==t){i.add(s.offset);continue}let a=!1;35===t?r>ot.audAllowed?a=!0:r=ot.beforeFirstVcl:t<=31?r>ot.afterFirstVcl?a=!0:r=ot.afterFirstVcl:36===t?r!==ot.afterFirstVcl?a=!0:r=ot.eoBitstreamAllowed:37===t?r=41&&t<=44||t>=48&&t<=55?r>ot.beforeFirstVcl?a=!0:r=ot.beforeFirstVcl:(38===t||40===t||t>=45&&t<=47||t>=56&&t<=63)&&r{if(t.description){const i=3&c(t.description)[21];return We(e,i+1)}return qe(e)})(a,t)},ut={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=>{const t=new ve(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 s=8;if(r>=2){s=t.readBits(1)?12:10}const n=t.readBits(3);let o=0,c=0;if(7!==n){if(c=t.readBits(1),1===r||3===r){const e=t.readBits(1),i=t.readBits(1);o=e||i?e&&!i?2:1:3,t.skipBits(1)}else o=1}else o=3,c=1;const l=(t.readBits(16)+1)*(t.readBits(16)+1);let u=a(jt).level;for(const a of jt)if(l<=a.maxPictureSize){u=a.level;break}const d=ut[n];return{profile:r,level:u,bitDepth:s,chromaSubsampling:o,videoFullRangeFlag:c,colourPrimaries:d?.colourPrimaries??2,transferCharacteristics:d?.transferCharacteristics??2,matrixCoefficients:d?.matrixCoefficients??2}},ht=function*(e){const t=new ve(e),r=()=>{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 a=t.readBits(4),s=t.readBits(1),n=t.readBits(1);let o;if(t.skipBits(1),s&&t.skipBits(8),n){const e=r();if(null===e)return;o=e}else o=Math.floor(t.getBitsLeft()/8);i(t.pos%8===0),yield{type:a,data:e.subarray(t.pos/8,t.pos/8+o)},t.skipBits(8*o)}},ft=e=>{for(const{type:t,data:i}of ht(e)){if(1!==t)continue;const e=new ve(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},mt=e=>{if(e.length<36)return null;const t=l(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)}},pt=[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],gt=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}},kt=(e,t,r)=>{switch(e){case"avc":for(const e of Oe(r,t)){const t=r[e.offset],i=Le(t);if(i>=Re.NON_IDR_SLICE&&i<=Re.SLICE_DPC)return"delta";if(i===Re.IDR)return"key";if(i===Re.SEI&&!te()){const t=r.subarray(e.offset,e.offset+e.length),i=ze(t);let a=1;do{let e=0;for(;;){const t=i[a++];if(void 0===t)break;if(e+=t,t<255)break}let t=0;for(;;){const e=i[a++];if(void 0===e)break;if(t+=e,e<255)break}if(e===6){const e=new ve(i);e.pos=8*a;const t=s(e),r=e.readBits(1);if(0===t&&1===r)return"key"}a+=t}while(a{var i,r;const a=l(e);let s=0;const n=a.getUint32(s,!0);s+=4;const o=u.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 d=0;d0&&(t.trackNumber??(t.trackNumber=i)),r&&Number.isInteger(r)&&r>0&&(t.tracksTotal??(t.tracksTotal=r))}break;case"TRACKTOTAL":{const e=Number.parseInt(d,10);Number.isInteger(e)&&e>0&&(t.tracksTotal??(t.tracksTotal=e))}break;case"DISCNUMBER":{const e=d.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(d,10);Number.isInteger(e)&&e>0&&(t.discsTotal??(t.discsTotal=e))}break;case"DATE":{const e=new Date(d);Number.isNaN(e.getTime())||(t.date??(t.date=e))}break;case"GENRE":t.genre??(t.genre=d);break;case"METADATA_BLOCK_PICTURE":{const e=oe(d),i=l(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=u.decode(e.subarray(12+a,12+a+n)),c=i.getUint32(a+n+28),h=e.subarray(a+n+32,a+n+32+c);t.images??(t.images=[]),t.images.push({data:h,mimeType:s,kind:3===r?"coverFront":4===r?"coverBack":"unknown",name:void 0,description:o||void 0})}}}},Tt=[2,1,2,3,3,4,4,5],St=e=>{if(e.length<7)return null;if(11!==e[0]||119!==e[1])return null;const t=new ve(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)}},vt=[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],Pt=[1,2,3,6],It=e=>{if(e.length<6)return null;if(11!==e[0]||119!==e[1])return null;const t=new ve(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=Pt[s];let d;d=a<3?Ee[a]/1e3:_e[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}]}},xt=e=>{const t=e.substreams[0];return i(t),t.fscod<3?Ee[t.fscod]:null!==t.fscod2&&t.fscod2<3?_e[t.fscod2]:null},Ct=e=>{const t=e.substreams[0];i(t);let r=Tt[t.acmod]+t.lfeon;if(t.numDepSub>0){const e=[2,2,1,1,2,2,2,1,1];for(let i=0;i<9;i++)t.chanLoc&1<<8-i&&(r+=e[i])}return r},Bt=[0,8e3,16e3,32e3,0,0,11025,22050,44100,0,0,12e3,24e3,48e3,96e3,192e3],Et=[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],_t=[16,16,20,20,0,24,24,0],Rt=[1,2,2,2,2,3,3,4,4,5,6,6,6,7,8,8],Ft=[1,2,2,2,2,3,18,19,6,7,518,323,83,519,582,535],At=[32e3,44100,48e3,0],Dt=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],Mt=[512,1024,2048,4096],Nt=e=>{const t=Lt(e),i=l(e);let r=t?4*Math.ceil(t.frameSize/4):0,a=null;for(;r+4<=e.length&&1683496997===i.getUint32(r);){const t=zt(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}},Ot=e=>{const t=Nt(e);return t?.core?t.hasExtensions?"dtsh":"dtsc":null},Lt=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 ve(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>=Rt.length)return null;const n=Bt[t.readBits(4)];if(0===n)return null;const o=Et[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=_t[t.readBits(3)];if(0===l)return null;const u=0!==c;return{frameSize:a,sampleRate:n,numberOfChannels:Rt[s]+(u?1:0),sampleCount:32*r,channelLayout:Ft[s]|(u?8:0),amode:s,lfePresent:u,bitRate:o,pcmResolution:l}},zt=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 ve(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=At[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}}},Ut=e=>W(e)+W(44646&e),qt=["avc","hevc","vp9","av1","vp8","prores"],Wt=["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"],Ht=["aac","opus","mp3","vorbis","flac","ac3","eac3","dts",...Wt],Vt=[{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}],Kt=".01.01.01.01.00",Xt=".0.110.01.01.01.0",$t=["ap4x","ap4h","apch","apcn","apcs","apco"],Gt=["dtsc","dtsh","dtsl","dtse"],Qt=e=>{const{codec:t,codecDescription:r,colorSpace:s,avcCodecInfo:n,hevcCodecInfo:o,vp9CodecInfo:c,av1CodecInfo:u,proresFormat:d}=e;if("avc"===t){if(i(null!==e.avcType),n){const t=new Uint8Array([n.avcProfileIndication,n.profileCompatibility,n.avcLevelIndication]);return`avc${e.avcType}.${v(t)}`}if(!r||r.byteLength<4)throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${e.avcType}.${v(r.subarray(1,4))}`}if("hevc"===t){let e,t,i,a,s,n;if(o)e=o.generalProfileSpace,t=o.generalProfileIdc,i=P(o.generalProfileCompatibilityFlags),a=o.generalTierFlag,s=o.generalLevelIdc,n=[...o.generalConstraintIndicatorFlags];else{if(!r||r.byteLength<23)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");const o=l(r),c=o.getUint8(1);e=c>>6&3,t=31&c,i=P(o.getUint32(2)),a=c>>5&1,s=o.getUint8(12),n=[];for(let e=0;e<6;e++)n.push(o.getUint8(6+e))}let c="hev1.";for(c+=["","A","B","C"][e]+t,c+=".",c+=i.toString(16).toUpperCase(),c+=".",c+=0===a?"L":"H",c+=s;n.length>0&&0===n[n.length-1];)n.pop();return n.length>0&&(c+=".",c+=n.map(e=>e.toString(16).toUpperCase()).join(".")),c}if("vp8"===t)return"vp8";if("vp9"===t){if(!c){const t=e.width*e.height;let i=a(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.${c.profile.toString().padStart(2,"0")}.${c.level.toString().padStart(2,"0")}.${c.bitDepth.toString().padStart(2,"0")}.${c.chromaSubsampling.toString().padStart(2,"0")}`;return t+=`.${c.colourPrimaries.toString().padStart(2,"0")}.${c.transferCharacteristics.toString().padStart(2,"0")}.${c.matrixCoefficients.toString().padStart(2,"0")}.${c.videoFullRangeFlag.toString().padStart(2,"0")}`,t.endsWith(Kt)&&(t=t.slice(0,-15)),t}if("av1"===t){if(!u){const t=e.width*e.height;let i=a(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=u.profile,i=u.level.toString().padStart(2,"0"),r=u.tier?"H":"M",n=u.bitDepth.toString().padStart(2,"0"),o=u.monochrome?"1":"0",c=100*u.chromaSubsamplingX+10*u.chromaSubsamplingY+1*(u.chromaSubsamplingX&&u.chromaSubsamplingY?u.chromaSamplePosition:0),l=s?.primaries?h[s.primaries]:1,d=s?.transfer?m[s.transfer]:1,f=s?.matrix?g[s.matrix]:1,p=s?.fullRange?1:0;let k=`av01.${t}.${i}${r}.${n}`;return k+=`.${o}.${c.toString().padStart(3,"0")}`,k+=`.${l.toString().padStart(2,"0")}`,k+=`.${d.toString().padStart(2,"0")}`,k+=`.${f.toString().padStart(2,"0")}`,k+=`.${p}`,k.endsWith(Xt)&&(k=k.slice(0,-17)),k}if("prores"===t)return d??"apch";throw null!==t&&F(t),new TypeError(`Unhandled codec '${t}'.`)},Yt=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=Xe(t);if(e)return{primaries:f[e.colourPrimaries],transfer:p[e.transferCharacteristics],matrix:k[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case"hevc":{let t=e.hevcCodecInfo?.arrays.find(e=>e.nalUnitType===Ae.SPS_NUT)?.nalUnits[0];if(!t&&e.codecDescription&&(t=(e=>{try{const t=l(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 u=e.subarray(i,i+6);i+=6;const d=t.getUint8(i++),h=(15&t.getUint8(i++))<<8|t.getUint8(i++),f=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 l=0;l>7&1,s=63&r,n=t.getUint16(i,!1);i+=2;const o=[];for(let c=0;ce.nalUnitType===Ae.SPS_NUT)?.nalUnits[0]),t){const e=Je(t);if(e)return{primaries:f[e.colourPrimaries],transfer:p[e.transferCharacteristics],matrix:k[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case"vp8":break;case"vp9":if(e.vp9CodecInfo)return{primaries:f[e.vp9CodecInfo.colourPrimaries],transfer:p[e.vp9CodecInfo.transferCharacteristics],matrix:k[e.vp9CodecInfo.matrixCoefficients],fullRange:!!e.vp9CodecInfo.videoFullRangeFlag};break;case"av1":if(e.av1CodecInfo)return{primaries:f[e.av1CodecInfo.colourPrimaries],transfer:p[e.av1CodecInfo.transferCharacteristics],matrix:k[e.av1CodecInfo.matrixCoefficients],fullRange:!!e.av1CodecInfo.videoFullRangeFlag};break;case"prores":if(e.proresCodecInfo)return{primaries:f[e.proresCodecInfo.colourPrimaries],transfer:p[e.proresCodecInfo.transferCharacteristics],matrix:k[e.proresCodecInfo.matrixCoefficients],fullRange:e.proresCodecInfo.fullRange}}return{primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0}},Jt=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=xe(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&&Wt.includes(t))return t;throw new TypeError(`Unhandled codec '${t}'.`)},Zt=48e3,ei=/^pcm-([usf])(\d+)(be)?$/,ti=e=>{if(i(Wt.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=ei.exec(e);let r;i(t),r="u"===t[1]?"unsigned":"s"===t[1]?"signed":"float";return{dataType:r,sampleSize:Number(t[2])/8,littleEndian:"be"!==t[3],silentValue:"pcm-u8"===e?128: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":$t.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":Gt.includes(e)?"dts":"ulaw"===e?"ulaw":"alaw"===e?"alaw":ei.test(e)?e:"webvtt"===e?"webvtt":null,ri=[44100,48e3,32e3],ai=[-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],si=1483304551,ni=1231971951,oi=(e,t)=>3===e?3===t?21:36:3===t?13:21,ci=(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=ai[16*n*4+16*l+(a>>4&15)];if(-1===g)return{header:null,bytesAdvanced:1};const k=1e3*g,y=ri[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 ui,di;(di=ui||(ui={}))[di.FrameCount=1]="FrameCount",di[di.FileSize=2]="FileSize",di[di.Toc=4]="Toc";const hi=e=>3===e?1:2;class fi{constructor(e){this.input=e}dispose(){}}const mi=new Uint8Array(0);class pi{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===mi&&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===mi}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 pi(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 pi(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 gi=e=>{const t=l(e);let i=0;const r=t.getUint8(i);i+=1,i+=3;const a=v(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=To(e);const i=_o(e,4);let r=8;1===t&&(t=Io(e),r=16);const a=t-r;return a<0?null:{name:i,totalSize:t,headerSize:r,contentSize:a}},bi=e=>vo(e)/65536,wi=e=>vo(e)/1073741824,Ti=e=>{let t=0;for(let i=0;i<4;i++){t<<=7;const i=po(e);if(t|=127&i,0===(128&i))break}return t},Si=e=>{let t=ko(e);return e.skip(2),t=Math.min(t,e.remainingLength),u.decode(mo(e,t))},vi=e=>{const t=yi(e);if(!t||"data"!==t.name)return null;if(e.remainingLength<8)return null;const i=To(e);e.skip(4);const r=mo(e,t.contentSize-8);switch(i){case 1:return u.decode(r);case 2:return new TextDecoder("utf-16be").decode(r);case 13:return new we(r,"image/jpeg");case 14:return new we(r,"image/png");case 27:return new we(r,"image/bmp");default:return r}},Pi=16,Ii=new Uint32Array(256),xi=new Uint32Array(256),Ci=new Uint32Array(256),Bi=new Uint32Array(256),Ei=new Uint32Array(256),_i=new Uint32Array(256),Ri=new Uint32Array(10);let Fi=!1;class Ai{constructor(){this.roundkey=new Uint32Array(44),this.iv=new Uint32Array(Pi/Uint32Array.BYTES_PER_ELEMENT),this.in=new Uint8Array(Pi),this.out=new Uint8Array(Pi),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),Fi||(()=>{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);Ii[s]=t<<24|t<<16|t<<8|t,_i[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);xi[s]=a,Ci[s]=a>>>8|a<<24,Bi[s]=a>>>16|a<<16,Ei[s]=a>>>24|a<<8}let a=1;for(let s=0;s<10;s++)Ri[s]=a<<24,a=a<<1^(128&a?283:0);Fi=!0})();const r=new DataView(e.buffer,e.byteOffset,e.byteLength),a=new DataView(t.buffer,t.byteOffset,t.byteLength);this.roundkey[0]=r.getUint32(0,!1),this.roundkey[1]=r.getUint32(4,!1),this.roundkey[2]=r.getUint32(8,!1),this.roundkey[3]=r.getUint32(12,!1),this.iv[0]=a.getUint32(0,!1),this.iv[1]=a.getUint32(4,!1),this.iv[2]=a.getUint32(8,!1),this.iv[3]=a.getUint32(12,!1);for(let i=4;i<44;i+=4){const e=this.roundkey[i-1];this.roundkey[i]=this.roundkey[i-4]^4278190080&Ii[e>>>16&255]^16711680&Ii[e>>>8&255]^65280&Ii[e>>>0&255]^255&Ii[e>>>24&255]^Ri[i/4-1],this.roundkey[i+1]=this.roundkey[i-3]^this.roundkey[i],this.roundkey[i+2]=this.roundkey[i-2]^this.roundkey[i+1],this.roundkey[i+3]=this.roundkey[i-1]^this.roundkey[i+2]}for(let i=0,s=40;i>>24&255]]^Ci[255&Ii[t>>>16&255]]^Bi[255&Ii[t>>>8&255]]^Ei[255&Ii[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=xi[e>>>24]^Ci[r>>>16&255]^Bi[i>>>8&255]^Ei[255&t]^this.roundkey[a],l=xi[t>>>24]^Ci[e>>>16&255]^Bi[r>>>8&255]^Ei[255&i]^this.roundkey[a+1],u=xi[i>>>24]^Ci[t>>>16&255]^Bi[e>>>8&255]^Ei[255&r]^this.roundkey[a+2],d=xi[r>>>24]^Ci[i>>>16&255]^Bi[t>>>8&255]^Ei[255&e]^this.roundkey[a+3],e=c,t=l,i=u,r=d}const h=4278190080&_i[e>>>24&255]^16711680&_i[r>>>16&255]^65280&_i[i>>>8&255]^255&_i[t>>>0&255]^this.roundkey[40],f=4278190080&_i[t>>>24&255]^16711680&_i[e>>>16&255]^65280&_i[r>>>8&255]^255&_i[i>>>0&255]^this.roundkey[41],m=4278190080&_i[i>>>24&255]^16711680&_i[t>>>16&255]^65280&_i[e>>>8&255]^255&_i[r>>>0&255]^this.roundkey[42],p=4278190080&_i[r>>>24&255]^16711680&_i[i>>>16&255]^65280&_i[t>>>8&255]^255&_i[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 Di extends fi{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,r=!1;for(;;){let i=this.reader.requestSliceRange(e,8,16);if(ae(i)&&(i=await i),!i)break;const a=e,s=yi(i);if(!s)break;if("ftyp"===s.name||"styp"===s.name){const e=_o(i,4);this.isQuickTime="qt "===e}else{if("moov"===s.name){let e=this.reader.requestSlice(i.filePos,s.contentSize);if(ae(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,r=!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,r=!0;break}}e=a+s.totalSize}if(!r&&this.input._initInput&&await this.copyMetadataFromInitInput(this.input._initInput),t){i(null!==this.reader.fileSize);let e=this.reader.requestSlice(this.reader.fileSize-4,4);ae(e)&&(e=await e),i(e);const t=To(e),r=this.reader.fileSize-t;if(r>=0&&r<=this.reader.fileSize-16){let e=this.reader.requestSliceRange(r,8,16);if(ae(e)&&(e=await e),e){const t=yi(e);if(t&&"mfra"===t.name){let i=this.reader.requestSlice(e.filePos,t.contentSize);ae(i)&&(i=await i),i&&this.readContiguousBoxes(i)}}}}})())}async copyMetadataFromInitInput(e){const t=await e._getDemuxer();if(t.constructor!==Di)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 r of t.tracks){const e={id:r.id,demuxer:this,trackBacking:null,disposition:r.disposition,timescale:r.timescale,durationInMediaTimescale:r.durationInMediaTimescale,durationInMovieTimescale:r.durationInMovieTimescale,rotation:r.rotation,internalCodecId:r.internalCodecId,name:r.name,languageCode:r.languageCode,sampleTableByteOffset:null,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:r.editListPreviousSegmentDurations,editListOffset:r.editListOffset,encryptionInfo:r.encryptionInfo,encryptionAuxInfo:null,frmaCodecString:null,info:r.info};if(r.trackBacking)if(i(e.info),"video"===e.info.type&&-1!==e.info.width){const t=e;e.trackBacking=new Ni(t),this.tracks.push(e)}else if("audio"===e.info.type&&-1!==e.info.numberOfChannels){const t=e;e.trackBacking=new Oi(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;i(this.moovSlice);const r=this.moovSlice.slice(e.sampleTableByteOffset);this.currentTrack=e,this.traverseBox(r),this.currentTrack=null;if("audio"===e.info?.type&&e.info.codec&&Wt.includes(e.info.codec)&&0===t.sampleCompositionTimeOffsets.length){i("audio"===e.info?.type);const r=ti(e.info.codec),s=[],n=[];for(let i=0;ie.startIndex),d=t.sampleTimingEntries[u],h=x(t.sampleTimingEntries,l,e=>e.startIndex),f=t.sampleTimingEntries[h],m=d.startDecodeTimestamp+(c-d.startIndex)*d.delta,p=f.startDecodeTimestamp+(l-f.startIndex)*f.delta-m,g=a(s);g&&g.delta===p?g.count++:s.push({startIndex:o.startChunkIndex+i,startDecodeTimestamp:m,count:1,delta:p});const k=o.samplesPerChunk*r.sampleSize*e.info.numberOfChannels;n.push(k)}o.startSampleIndex=o.startChunkIndex,o.samplesPerChunk=1}t.sampleTimingEntries=s,t.sampleSizes=n}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===s.moofOffset);if(r)Wi(i,r.timestamp);else{const e=x(t,s.moofOffset-1,e=>e.moofOffset);if(-1!==e){const r=t[e];Wi(i,r.endTimestamp)}}i.startTimestampIsFinal=!0}const r=x(t,i.startTimestamp,e=>e.startTimestamp);if(-1!==r&&t[r].moofOffset===s.moofOffset||t.splice(r+1,0,{moofOffset:s.moofOffset,startTimestamp:i.startTimestamp,endTimestamp:i.endTimestamp}),i.encryptionAuxInfo&&e.encryptionInfo){const t=await Ki(this.reader,e.encryptionInfo,i.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;V(t.languageCode)||(t.languageCode=O)}}break;case"hdlr":{const t=this.currentTrack;if(!t)break;e.skip(8);const i=_o(e,4);"vide"===i?t.info={type:"video",width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:{...b},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=X,this.readContiguousBoxes(e.slice(G,$.contentSize))}break;case"stsd":{const t=this.currentTrack;if(!t)break;if(null===t.info||t.sampleTable)break;const i=po(e);e.skip(3);const r=To(e);for(let a=0;a0&&(1===n?(e.skip(4),c=8*To(e),e.skip(8)):2===n&&(e.skip(4),l=Eo(e),o=To(e),e.skip(4),c=To(e),u=To(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=Zt;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(Gt.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":(be._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":(be._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":(be._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":(be._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":(be._warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null):32===e?t.info.codec="pcm-f32be":64===e?t.info.codec="pcm-f64be":(be._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!==po(e),t.encryptionInfo.defaultPerSampleIvSize=po(e),t.encryptionInfo.defaultKid=v(mo(e,16)),t.encryptionInfo.defaultIsProtected&&0===t.encryptionInfo.defaultPerSampleIvSize){const i=po(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(i(t.info),0===$.contentSize)break;t.info.codecDescription=mo(e,$.contentSize)}break;case"hvcC":{const t=this.currentTrack;if(!t)break;if(i(t.info),0===$.contentSize)break;t.info.codecDescription=mo(e,$.contentSize)}break;case"vpcC":{const t=this.currentTrack;if(!t)break;i("video"===t.info?.type),e.skip(4);const r=po(e),a=po(e),s=po(e),n=s>>4,o=s>>1&7,c=1&s,l=po(e),u=po(e),d=po(e);t.info.vp9CodecInfo={profile:r,level:a,bitDepth:n,chromaSubsampling:o,videoFullRangeFlag:c,colourPrimaries:l,transferCharacteristics:u,matrixCoefficients:d}}break;case"av1C":{const t=this.currentTrack;if(!t)break;i("video"===t.info?.type),e.skip(1);const r=po(e),a=r>>5,s=31&r,n=po(e),o=n>>7,c=n>>6&1,l=n>>4&1,u=n>>3&1,d=n>>2&1,h=3&n,f=2===a&&c?n>>5&1?12:10:c?10:8;e.skip(1);const m=mo(e,$.contentSize-4),p=ft(m);t.info.av1CodecInfo={profile:a,level:s,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;i("video"===t.info?.type);const r=_o(e,4);if("nclx"!==r&&"nclc"!==r)break;const a=ko(e),s=ko(e),n=ko(e);let o;"nclx"===r&&(o=Boolean(128&po(e))),t.info.colorSpace={primaries:f[a],transfer:p[s],matrix:k[n],fullRange:o}}break;case"pasp":{const t=this.currentTrack;if(!t)break;i("video"===t.info?.type);const r=To(e),a=To(e);r>0&&a>0&&(r>a?t.info.squarePixelWidth=Math.round(t.info.width*r/a):t.info.squarePixelHeight=Math.round(t.info.height*a/r))}break;case"esds":{const t=this.currentTrack;if(!t||"audio"!==t.info?.type)break;e.skip(4);i(3===po(e)),Ti(e),e.skip(2);const r=po(e),a=0!==(64&r),s=0!==(32&r);if(0!==(128&r)&&e.skip(2),a){const t=po(e);e.skip(t)}s&&e.skip(2);i(4===po(e));const n=Ti(e),o=e.filePos,c=po(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":be._warn(`Unsupported audio codec (objectTypeIndication ${c}) - discarding track.`),e.skip(12),n>e.filePos-o){i(5===po(e));const r=Ti(e);if(t.info.codecDescription=mo(e,r),"aac"===t.info.codec){const e=xe(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"===t.info?.type),t.info.pcmLittleEndian=!!(255&ko(e))}break;case"pcmC":{const t=this.currentTrack;if(!t)break;i("audio"===t.info?.type),e.skip(4);const r=po(e);t.info.pcmLittleEndian=Boolean(1&r),t.info.pcmSampleSize=po(e)}break;case"dOps":{const t=this.currentTrack;if(!t)break;i("audio"===t.info?.type),e.skip(1);const r=po(e),a=ko(e),s=To(e),n=bo(e),o=po(e);let c;c=0!==o?mo(e,2+r):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,r),u.setUint16(10,a,!0),u.setUint32(12,s,!0),u.setInt16(16,n,!0),u.setUint8(18,o),l.set(c,19),t.info.codecDescription=l,t.info.numberOfChannels=r}break;case"dfLa":{const t=this.currentTrack;if(!t)break;i("audio"===t.info?.type),e.skip(4);const r=127,a=128,s=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(i&a)break}const n=e.filePos;e.filePos=s;const o=mo(e,n-s),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;i("audio"===t.info?.type);const r=mo(e,3),a=new ve(r),s=a.readBits(2);a.skipBits(8);const n=a.readBits(3),o=a.readBits(1);s<3&&(t.info.sampleRate=Ee[s]),t.info.numberOfChannels=Tt[n]+o}break;case"dec3":{const t=this.currentTrack;if(!t)break;i("audio"===t.info?.type);const r=(e=>{if(e.length<2)return null;const t=new ve(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}})(mo(e,$.contentSize));if(!r){be._warn("Invalid dec3 box contents, ignoring.");break}const a=xt(r);null!==a&&(t.info.sampleRate=a),t.info.numberOfChannels=Ct(r)}break;case"ddts":{const t=this.currentTrack;if(!t)break;i("audio"===t.info?.type);const r=(e=>{if(e.length<20)return null;const t=l(e),i=t.getUint32(0);if(0===i)return null;const r=new ve(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=Ut(o):ne.id===i);if(!r)break;const a=To(e),s=(12&a)>>2,n=3&a,o=[po,ko,yo,To],c=o[(48&a)>>4],l=o[s],u=o[n],d=To(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 i=0;ie.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},r?d.currentFragmentState.baseDataOffset=Io(e):l&&(d.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),a&&(d.currentFragmentState.sampleDescriptionIndex=To(e)),s&&(d.currentFragmentState.defaultSampleDuration=To(e)),n&&(d.currentFragmentState.defaultSampleSize=To(e)),o&&(d.currentFragmentState.defaultSampleFlags=To(e)),c&&(d.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{const t=this.currentTrack;if(!t)break;i(t.currentFragmentState);const r=po(e);e.skip(3);const a=0===r?To(e):Io(e);t.currentFragmentState.startTimestamp=a}break;case"trun":{const t=this.currentTrack;if(!t)break;i(this.currentFragment),i(t.currentFragmentState);const r=po(e),a=yo(e),s=Boolean(1&a),n=Boolean(4&a),o=Boolean(256&a),c=Boolean(512&a),l=Boolean(1024&a),u=Boolean(2048&a),d=To(e);let h=null;s&&(h=vo(e));let f,m=null;n&&(m=To(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=mo(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=po(e);if(1&yo(e)){const i=_o(e,4),r=To(e);if(i!==t.encryptionInfo.scheme||0!==r)break}const r=To(e);if(0===r)break;r>1&&be._warn("Multiple saio entries are not supported; using the first offset only.");let a=0===i?To(e):Number(Io(e));this.currentFragment&&(a+=this.currentFragment.moofOffset);ji(t).offset=a}break;case"senc":{const t=this.currentTrack;if(!t||!t.encryptionInfo)break;i(this.currentFragment);const r=this.currentFragment.trackData.get(t.id);if(!r)break;e.skip(1);const a=yo(e),s=Boolean(2&a),n=To(e),o=t.encryptionInfo.defaultPerSampleIvSize;i(null!==o);for(let i=0;i0?a.set(mo(e,o),0):a.set(t.encryptionInfo.defaultConstantIv,0);let n=null;if(s){const t=ko(e);n=[];for(let i=0;i0&&((U=this.metadataTags).trackNumber??(U.trackNumber=t)),i&&Number.isInteger(i)&&i>0&&((q=this.metadataTags).tracksTotal??(q.tracksTotal=i))}break;case"trkn":if(a instanceof Uint8Array&&a.length>=6){const e=l(a),t=e.getUint16(2,!1),i=e.getUint16(4,!1);t>0&&((W=this.metadataTags).trackNumber??(W.trackNumber=t)),i>0&&((H=this.metadataTags).tracksTotal??(H.tracksTotal=i))}break;case"disc":case"disk":if(a instanceof Uint8Array&&a.length>=6){const e=l(a),t=e.getUint16(2,!1),i=e.getUint16(4,!1);t>0&&((j=this.metadataTags).discNumber??(j.discNumber=t)),i>0&&((K=this.metadataTags).discsTotal??(K.discsTotal=i))}}}}}return e.filePos=Q,!0}}class Mi{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;i(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 L(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,t){const i=this.mapTimestampIntoTimescale(e),r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=Li(r,i),s=await this.fetchPacketForSampleIndex(a,t);return Vi(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=x(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=R(t.presentationTimestamps,e=>t.samples[e.sampleIndex].isKeyFrame&&e.presentationTimestamp<=i);return{sampleIndex:-1!==r?t.presentationTimestamps[r].sampleIndex:-1,correctSampleFound:-1!==r&&i{if(e===a.fragment){const t=e.trackData.get(this.internalTrack.id).samples.findIndex((e,t)=>e.isKeyFrame&&t>a.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)}async fetchPacketForSampleIndex(e,t){if(-1===e)return null;const i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),r=Ui(i,e);if(!r)return null;let a;if(t.metadataOnly)a=mi;else{let t=this.internalTrack.demuxer.reader.requestSlice(r.sampleOffset,r.sampleSize);if(ae(t)&&(t=await t),!t)return null;if(a=mo(t,r.sampleSize),this.internalTrack.encryptionInfo){let t=null;if(this.internalTrack.encryptionAuxInfo){const i=await Ki(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);ee.timestamp),d=-1!==u?this.internalTrack.fragmentLookupTable[u]:null,h=x(this.internalTrack.fragmentPositionCache,r,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>a)break}let e=n.reader.requestSliceRange(p,8,16);if(ae(e)&&(e=await e),!e)break;const i=p,r=yi(e);if(!r)break;if("moof"===r.name){o=await n.readFragment(i);const{sampleIndex:e,correctSampleFound:r}=t(o);if(r)return this.fetchPacketInFragment(o,e,s);-1!==e&&(c=o,l=e)}p=i+r.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&&mt(e.data)}}else{const e=await this.getFirstPacket({}),t=e&&ft(e.data);t&&(this.internalTrack.info.av1CodecInfo=t)}else{const e=await this.getFirstPacket({}),t=e&&dt(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&&Ze(e.data)}else{const e=await this.getFirstPacket({});this.internalTrack.info.avcCodecInfo=e&&He(e.data)}if(!y(this.internalTrack.info.colorSpace)){const a=Yt(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:Qt(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 Oi extends Mi{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&&Ot(e.data)}return{codec:Jt(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}})()):null}}const Li=(e,t)=>{if(e.presentationTimestamps){const i=x(e.presentationTimestamps,t,e=>e.presentationTimestamp);return-1===i?-1:e.presentationTimestamps[i].sampleIndex}{const i=x(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)}},zi=(e,t)=>{if(!e.keySampleIndices)return Li(e,t);if(e.presentationTimestamps){const i=x(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!==I(e.keySampleIndices,i,e=>e))return i}return-1}{const i=Li(e,t),r=x(e.keySampleIndices,i,e=>e);return e.keySampleIndices[r]??-1}},Ui=(e,t)=>{const r=x(e.sampleTimingEntries,t,e=>e.startIndex),a=e.sampleTimingEntries[r];if(!a||a.startIndex+a.count<=t)return null;let s=a.startDecodeTimestamp+(t-a.startIndex)*a.delta;const n=x(e.sampleCompositionTimeOffsets,t,e=>e.startIndex),o=e.sampleCompositionTimeOffsets[n];o&&t-o.startIndexe.startSampleIndex),u=e.sampleToChunk[l];i(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 i=f;ie)}},qi=(e,t)=>{if(!e.keySampleIndices)return t+1;const i=x(e.keySampleIndices,t,e=>e);return e.keySampleIndices[i+1]??-1},Wi=(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},Hi=e=>{const[t,i]=e,r=Math.atan2(i,t);return Number.isFinite(r)?r*(180/Math.PI):0},Vi=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})},Ki=async(e,t,r)=>{if(r.resolved)return r.resolved;if(null===r.offset||0===r.sampleCount)throw new Error("Incomplete saiz/saio info; cannot resolve encryption data.");let a=0;if(r.defaultSampleInfoSize>0)a=r.defaultSampleInfoSize*r.sampleCount;else{i(r.sampleSizes);for(let e=0;e0?r.defaultSampleInfoSize:r.sampleSizes[i],a=new Uint8Array(16);n>0?a.set(mo(s,n),0):a.set(t.defaultConstantIv,0);let c=null;if(e>n){const e=ko(s);c=[];for(let t=0;te.defaultConstantIv?{iv:e.defaultConstantIv,subsamples:null}:null,$i=async(e,t,r,a)=>{i(e.encryptionInfo);const s=e.encryptionInfo;i(null!==s.defaultKid);const n=s.defaultKid;let o;const c=e.demuxer.decryptionKeyCache.get(n);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(a){t=[...t,...a.psshBoxes].filter(e=>null===e.keyIds||e.keyIds.includes(n));for(let e=0;e{i(e.length%2===0);const t=new Uint8Array(e.length/2);for(let i=0;i{const s=new Uint8Array(16);s.set(r.iv,0);const n=await crypto.subtle.importKey("raw",e,{name:"AES-CTR"},!1,["decrypt"]),o=async e=>{const t=await crypto.subtle.decrypt({name:"AES-CTR",counter:s,length:64},n,e);return new Uint8Array(t)};if(!r.subsamples)return o(a);i(null!==t.defaultCryptByteBlock&&null!==t.defaultSkipByteBlock);const c=Yi(r.subsamples,t.defaultCryptByteBlock,t.defaultSkipByteBlock);let l=0;for(const i of c)for(const e of i.perSubsample)l+=e.length;const u=new Uint8Array(l);let d=0;for(const i of c)for(const e of i.perSubsample)u.set(a.subarray(e.offset,e.offset+e.length),d),d+=e.length;const h=await o(u),f=new Uint8Array(a);let m=0;for(const i of c)for(const e of i.perSubsample)f.set(h.subarray(m,m+e.length),e.offset),m+=e.length;return f},Qi=(e,t,r,a)=>{const s=new Ai;s.init({key:e,iv:r.iv});const n=t.defaultCryptByteBlock,o=t.defaultSkipByteBlock;if(i(null!==n&&null!==o),!r.subsamples){const e=new Uint8Array(a),t=Math.floor(a.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 Ji,Zi;(Zi=Ji||(Ji={}))[Zi.EBML=440786851]="EBML",Zi[Zi.EBMLVersion=17030]="EBMLVersion",Zi[Zi.EBMLReadVersion=17143]="EBMLReadVersion",Zi[Zi.EBMLMaxIDLength=17138]="EBMLMaxIDLength",Zi[Zi.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",Zi[Zi.DocType=17026]="DocType",Zi[Zi.DocTypeVersion=17031]="DocTypeVersion",Zi[Zi.DocTypeReadVersion=17029]="DocTypeReadVersion",Zi[Zi.Void=236]="Void",Zi[Zi.Segment=408125543]="Segment",Zi[Zi.SeekHead=290298740]="SeekHead",Zi[Zi.Seek=19899]="Seek",Zi[Zi.SeekID=21419]="SeekID",Zi[Zi.SeekPosition=21420]="SeekPosition",Zi[Zi.Duration=17545]="Duration",Zi[Zi.Info=357149030]="Info",Zi[Zi.TimestampScale=2807729]="TimestampScale",Zi[Zi.MuxingApp=19840]="MuxingApp",Zi[Zi.WritingApp=22337]="WritingApp",Zi[Zi.Tracks=374648427]="Tracks",Zi[Zi.TrackEntry=174]="TrackEntry",Zi[Zi.TrackNumber=215]="TrackNumber",Zi[Zi.TrackUID=29637]="TrackUID",Zi[Zi.TrackType=131]="TrackType",Zi[Zi.FlagEnabled=185]="FlagEnabled",Zi[Zi.FlagDefault=136]="FlagDefault",Zi[Zi.FlagForced=21930]="FlagForced",Zi[Zi.FlagOriginal=21934]="FlagOriginal",Zi[Zi.FlagHearingImpaired=21931]="FlagHearingImpaired",Zi[Zi.FlagVisualImpaired=21932]="FlagVisualImpaired",Zi[Zi.FlagCommentary=21935]="FlagCommentary",Zi[Zi.FlagLacing=156]="FlagLacing",Zi[Zi.Name=21358]="Name",Zi[Zi.Language=2274716]="Language",Zi[Zi.LanguageBCP47=2274717]="LanguageBCP47",Zi[Zi.CodecID=134]="CodecID",Zi[Zi.CodecPrivate=25506]="CodecPrivate",Zi[Zi.CodecDelay=22186]="CodecDelay",Zi[Zi.SeekPreRoll=22203]="SeekPreRoll",Zi[Zi.DefaultDuration=2352003]="DefaultDuration",Zi[Zi.Video=224]="Video",Zi[Zi.PixelWidth=176]="PixelWidth",Zi[Zi.PixelHeight=186]="PixelHeight",Zi[Zi.DisplayWidth=21680]="DisplayWidth",Zi[Zi.DisplayHeight=21690]="DisplayHeight",Zi[Zi.DisplayUnit=21682]="DisplayUnit",Zi[Zi.AlphaMode=21440]="AlphaMode",Zi[Zi.Audio=225]="Audio",Zi[Zi.SamplingFrequency=181]="SamplingFrequency",Zi[Zi.Channels=159]="Channels",Zi[Zi.BitDepth=25188]="BitDepth",Zi[Zi.SimpleBlock=163]="SimpleBlock",Zi[Zi.BlockGroup=160]="BlockGroup",Zi[Zi.Block=161]="Block",Zi[Zi.BlockAdditions=30113]="BlockAdditions",Zi[Zi.BlockMore=166]="BlockMore",Zi[Zi.BlockAdditional=165]="BlockAdditional",Zi[Zi.BlockAddID=238]="BlockAddID",Zi[Zi.BlockDuration=155]="BlockDuration",Zi[Zi.ReferenceBlock=251]="ReferenceBlock",Zi[Zi.Cluster=524531317]="Cluster",Zi[Zi.Timestamp=231]="Timestamp",Zi[Zi.Cues=475249515]="Cues",Zi[Zi.CuePoint=187]="CuePoint",Zi[Zi.CueTime=179]="CueTime",Zi[Zi.CueTrackPositions=183]="CueTrackPositions",Zi[Zi.CueTrack=247]="CueTrack",Zi[Zi.CueClusterPosition=241]="CueClusterPosition",Zi[Zi.Colour=21936]="Colour",Zi[Zi.MatrixCoefficients=21937]="MatrixCoefficients",Zi[Zi.TransferCharacteristics=21946]="TransferCharacteristics",Zi[Zi.Primaries=21947]="Primaries",Zi[Zi.Range=21945]="Range",Zi[Zi.Projection=30320]="Projection",Zi[Zi.ProjectionType=30321]="ProjectionType",Zi[Zi.ProjectionPoseRoll=30325]="ProjectionPoseRoll",Zi[Zi.Attachments=423732329]="Attachments",Zi[Zi.AttachedFile=24999]="AttachedFile",Zi[Zi.FileDescription=18046]="FileDescription",Zi[Zi.FileName=18030]="FileName",Zi[Zi.FileMediaType=18016]="FileMediaType",Zi[Zi.FileData=18012]="FileData",Zi[Zi.FileUID=18094]="FileUID",Zi[Zi.Chapters=272869232]="Chapters",Zi[Zi.Tags=307544935]="Tags",Zi[Zi.Tag=29555]="Tag",Zi[Zi.Targets=25536]="Targets",Zi[Zi.TargetTypeValue=26826]="TargetTypeValue",Zi[Zi.TargetType=25546]="TargetType",Zi[Zi.TagTrackUID=25541]="TagTrackUID",Zi[Zi.TagEditionUID=25545]="TagEditionUID",Zi[Zi.TagChapterUID=25540]="TagChapterUID",Zi[Zi.TagAttachmentUID=25542]="TagAttachmentUID",Zi[Zi.SimpleTag=26568]="SimpleTag",Zi[Zi.TagName=17827]="TagName",Zi[Zi.TagLanguage=17530]="TagLanguage",Zi[Zi.TagString=17543]="TagString",Zi[Zi.TagBinary=17541]="TagBinary",Zi[Zi.ContentEncodings=28032]="ContentEncodings",Zi[Zi.ContentEncoding=25152]="ContentEncoding",Zi[Zi.ContentEncodingOrder=20529]="ContentEncodingOrder",Zi[Zi.ContentEncodingScope=20530]="ContentEncodingScope",Zi[Zi.ContentCompression=20532]="ContentCompression",Zi[Zi.ContentCompAlgo=16980]="ContentCompAlgo",Zi[Zi.ContentCompSettings=16981]="ContentCompSettings",Zi[Zi.ContentEncryption=20533]="ContentEncryption";const er=[Ji.EBML,Ji.Segment],tr=[Ji.SeekHead,Ji.Info,Ji.Cluster,Ji.Tracks,Ji.Cues,Ji.Attachments,Ji.Chapters,Ji.Tags],ir=[...er,...tr],rr=16,ar=e=>{if(e.remainingLength<1)return null;const t=po(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=po(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=ar(e);if(null===t)return null;if(e.remainingLength{if(e.remainingLength<1)return null;if(255===po(e))return;e.skip(-1);const t=sr(e);return null===t?null:72057594037927940!==t?t:void 0},lr=e=>{i(e.remainingLength>=2);const t=or(e);if(null===t)return null;const r=cr(e);return null===r?null:{id:t,size:r}},ur=(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?Bo(e):Eo(e)},fr=async(e,t,i,r)=>{const a=new Set(i);let s=t;for(;null===r||ss?r:s,found:!1}},mr=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,rr);if(ae(t)&&(t=await t),!t)break;const i=lr(t);if(!i)break;const r=i.id;let s=i.size;const n=t.filePos;if(r===Ji.EBML){Er(s);let e=this.reader.requestSlice(n,s);if(ae(e)&&(e=await e),!e)break;this.readContiguousElements(e)}else if(r===Ji.Segment){if(await this.readSegment(n,s),void 0===s)break;if(null===this.reader.fileSize)break}else if(r===Ji.Cluster){if(null===this.reader.fileSize)break;if(void 0===s){s=(await fr(this.reader,n,ir,this.reader.fileSize)).pos-n}const e=a(this.segments);e&&(e.elementEndPos=n+s)}Er(s),e=n+s}})())}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=Nr[o].flag;this.currentSegment[e]=!0,Er(s);let t=this.reader.requestSlice(n,s);ae(t)&&(t=await t),t&&this.readContiguousElements(t)}else if(a===Ji.Tags||a===Ji.Attachments){a===Ji.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,Er(s);let e=this.reader.requestSlice(n,s);ae(e)&&(e=await e),e&&this.readContiguousElements(e)}else if(a===Ji.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=Nr.find(e=>e.id===n.id);if(!t)continue;if(this.currentSegment[t.flag])continue;let i=this.reader.requestSliceRange(e+n.segmentPosition,2,rr);if(ae(i)&&(i=await i),!i)continue;const r=lr(i);if(!r)continue;const{id:a,size:s}=r;if(a!==t.id)continue;Er(s),this.currentSegment[t.flag]=!0;let o=this.reader.requestSlice(i.filePos,s);ae(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 r=this.reader.requestSliceRange(e,2,rr);ae(r)&&(r=await r),i(r);const s=e,n=lr(r);i(n);i(n.id===Ji.Cluster);let o=n.size;const c=r.filePos;if(void 0===o){o=(await fr(this.reader,c,ir,t.elementEndPos)).pos-c}let l=this.reader.requestSlice(c,o);ae(l)&&(l=await l);const u={segment:t,elementStartPos:s,elementEndPos:c+o,dataStartPos:c,timestamp:-1,trackData:new Map};if(this.currentCluster=u,l){const e=this.readContiguousElements(l,ir);u.elementEndPos=e}for(const[,d]of u.trackData){const e=d.track;i(d.blocks.length>0);let t=!1;for(let i=0;i({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp);for(let i=0;i({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp));const r=d.blocks[d.presentationTimestamps[0].blockIndex],n=d.blocks[a(d.presentationTimestamps).blockIndex];d.startTimestamp=r.timestamp,d.endTimestamp=n.timestamp+n.duration;const o=x(e.clusterPositionCache,d.startTimestamp,e=>e.startTimestamp);-1!==o&&e.clusterPositionCache[o].elementStartPos===s||e.clusterPositionCache.splice(o+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 r=0;r=2;){const i=e.filePos;if(!this.traverseElement(e,t))return i}return e.filePos}traverseElement(e,t){const a=lr(e);if(!a)return!1;if(t&&t.includes(a.id))return!1;const{id:s,size:n}=a,o=e.filePos;switch(Er(n),s){case Ji.DocType:this.isWebM="webm"===ur(e,n);break;case Ji.Seek:{if(!this.currentSegment)break;const t={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(t),this.readContiguousElements(e.slice(o,n)),-1!==t.id&&-1!==t.segmentPosition||this.currentSegment.seekEntries.pop()}break;case Ji.SeekID:{const t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.id=nr(e,n)}break;case Ji.SeekPosition:{const t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.segmentPosition=nr(e,n)}break;case Ji.TimestampScale:if(!this.currentSegment)break;this.currentSegment.timestampScale=nr(e,n),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale;break;case Ji.Duration:if(!this.currentSegment)break;this.currentSegment.duration=hr(e,n);break;case Ji.TrackEntry:if(!this.currentSegment)break;if(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...Se,primary:!1},trackBacking:null,codecId:null,codecPrivate:null,defaultDuration:null,defaultDurationNs:null,name:null,languageCode:"eng",hasLanguageBcp47:!1,decodingInstructions:[],info:null},this.readContiguousElements(e.slice(o,n)),!this.currentTrack)break;if(this.currentTrack.decodingInstructions.some(e=>"decompress"!==e.data?.type||e.scope!==Fr.Block||e.data.algorithm!==Dr.HeaderStripping)&&(be._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===pr)this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(this.currentTrack.codecId===gr)this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(t===kr)this.currentTrack.info.codec="vp8";else if(t===yr)this.currentTrack.info.codec="vp9";else if(t===br)this.currentTrack.info.codec="av1";else if(t===wr){const e=this.currentTrack.codecPrivate?u.decode(this.currentTrack.codecPrivate):"";$t.includes(e)&&(this.currentTrack.info.codec="prores",this.currentTrack.info.proresFormat=e)}const e=this.currentTrack;this.currentTrack.trackBacking=new Ur(e),this.currentSegment.tracks.push(this.currentTrack)}else if("audio"===this.currentTrack.info.type){t===Tr?(this.currentTrack.info.codec="aac",this.currentTrack.info.aacCodecInfo={isMpeg2:this.currentTrack.codecId.includes("MPEG2"),objectType:null},this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===Sr?this.currentTrack.info.codec="mp3":t===vr?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=Zt):t===Pr?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Ir?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===xr?(this.currentTrack.info.codec="ac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Cr?(this.currentTrack.info.codec="eac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Br?(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 qr(e),this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null;break;case Ji.TrackNumber:if(!this.currentTrack)break;this.currentTrack.id=nr(e,n);break;case Ji.TrackType:{if(!this.currentTrack)break;const t=nr(e,n);1===t?this.currentTrack.info={type:"video",width:-1,height:-1,displayWidth:null,displayHeight:null,displayUnit:null,squarePixelWidth:-1,squarePixelHeight:-1,rotation:0,codec:null,codecDescription:null,colorSpace:{...b},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 Ji.FlagEnabled:if(!this.currentTrack)break;nr(e,n)||(this.currentTrack=null);break;case Ji.FlagDefault:if(!this.currentTrack)break;this.currentTrack.disposition.default=!!nr(e,n);break;case Ji.FlagForced:if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!nr(e,n);break;case Ji.FlagOriginal:if(!this.currentTrack)break;this.currentTrack.disposition.original=!!nr(e,n);break;case Ji.FlagHearingImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!nr(e,n);break;case Ji.FlagVisualImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!nr(e,n);break;case Ji.FlagCommentary:if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!nr(e,n);break;case Ji.CodecID:if(!this.currentTrack)break;this.currentTrack.codecId=ur(e,n);break;case Ji.CodecPrivate:if(!this.currentTrack)break;this.currentTrack.codecPrivate=mo(e,n);break;case Ji.DefaultDuration:if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=nr(e,n);break;case Ji.Name:if(!this.currentTrack)break;this.currentTrack.name=dr(e,n);break;case Ji.Language:if(!this.currentTrack)break;if(this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=ur(e,n),V(this.currentTrack.languageCode)||(this.currentTrack.languageCode=O);break;case Ji.LanguageBCP47:{if(!this.currentTrack)break;const t=ur(e,n).split("-")[0];this.currentTrack.languageCode=t||O,this.currentTrack.hasLanguageBcp47=!0}break;case Ji.Video:if("video"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(o,n));break;case Ji.PixelWidth:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.width=nr(e,n);break;case Ji.PixelHeight:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.height=nr(e,n);break;case Ji.DisplayWidth:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.displayWidth=nr(e,n);break;case Ji.DisplayHeight:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.displayHeight=nr(e,n);break;case Ji.DisplayUnit:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.displayUnit=nr(e,n);break;case Ji.AlphaMode:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.alphaMode=1===nr(e,n);break;case Ji.Colour:if("video"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(o,n));break;case Ji.MatrixCoefficients:{if("video"!==this.currentTrack?.info?.type)break;const t=nr(e,n),i=k[t];this.currentTrack.info.colorSpace.matrix=i}break;case Ji.Range:{if("video"!==this.currentTrack?.info?.type)break;const t=nr(e,n);this.currentTrack.info.colorSpace.fullRange=1===t||2===t?2===t:void 0}break;case Ji.TransferCharacteristics:{if("video"!==this.currentTrack?.info?.type)break;const t=nr(e,n),i=p[t];this.currentTrack.info.colorSpace.transfer=i}break;case Ji.Primaries:{if("video"!==this.currentTrack?.info?.type)break;const t=nr(e,n),i=f[t];this.currentTrack.info.colorSpace.primaries=i}break;case Ji.Projection:if("video"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(o,n));break;case Ji.ProjectionPoseRoll:{if("video"!==this.currentTrack?.info?.type)break;const t=-hr(e,n);try{this.currentTrack.info.rotation=r(t)}catch{}}break;case Ji.Audio:if("audio"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(o,n));break;case Ji.SamplingFrequency:if("audio"!==this.currentTrack?.info?.type)break;this.currentTrack.info.sampleRate=hr(e,n);break;case Ji.Channels:if("audio"!==this.currentTrack?.info?.type)break;this.currentTrack.info.numberOfChannels=nr(e,n);break;case Ji.BitDepth:if("audio"!==this.currentTrack?.info?.type)break;this.currentTrack.info.bitDepth=nr(e,n);break;case Ji.CuePoint:if(!this.currentSegment)break;this.readContiguousElements(e.slice(o,n)),this.currentCueTime=null;break;case Ji.CueTime:this.currentCueTime=nr(e,n);break;case Ji.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(o,n)),-1!==t.trackId&&-1!==t.clusterPosition||this.currentSegment.cuePoints.pop()}break;case Ji.CueTrack:{const t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;t.trackId=nr(e,n)}break;case Ji.CueClusterPosition:{const t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;i(this.currentSegment),t.clusterPosition=this.currentSegment.dataStartPos+nr(e,n)}break;case Ji.Timestamp:if(!this.currentCluster)break;this.currentCluster.timestamp=nr(e,n);break;case Ji.SimpleBlock:{if(!this.currentCluster)break;const t=sr(e);if(null===t)break;const i=this.getTrackDataInCluster(this.currentCluster,t);if(!i)break;const r=bo(e),a=po(e),s=a>>1&3;let c=!!(128&a);"audio"===i.track.info?.type&&i.track.info.codec&&(c=!0);const l=mo(e,n-(e.filePos-o)),u=i.track.decodingInstructions.length>0;i.blocks.push({timestamp:r,duration:0,isKeyFrame:c,data:l,lacing:s,decoded:!u,postProcessed:!1,mainAdditional:null})}break;case Ji.BlockGroup:if(!this.currentCluster)break;this.readContiguousElements(e.slice(o,n)),this.currentBlock=null;break;case Ji.Block:{if(!this.currentCluster)break;const t=sr(e);if(null===t)break;const i=this.getTrackDataInCluster(this.currentCluster,t);if(!i)break;const r=bo(e),a=po(e)>>1&3,s=mo(e,n-(e.filePos-o)),c=i.track.decodingInstructions.length>0;this.currentBlock={timestamp:r,duration:0,isKeyFrame:!0,data:s,lacing:a,decoded:!c,postProcessed:!1,mainAdditional:null},i.blocks.push(this.currentBlock)}break;case Ji.BlockAdditions:this.readContiguousElements(e.slice(o,n));break;case Ji.BlockMore:if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(o,n)),this.currentBlockAdditional.data&&1===this.currentBlockAdditional.addId&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null;break;case Ji.BlockAdditional:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=mo(e,n);break;case Ji.BlockAddID:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=nr(e,n);break;case Ji.BlockDuration:if(!this.currentBlock)break;this.currentBlock.duration=nr(e,n);break;case Ji.ReferenceBlock:if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1;break;case Ji.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(o,n));break;case Ji.Targets:this.readContiguousElements(e.slice(o,n));break;case Ji.TargetTypeValue:50!==nr(e,n)&&(this.currentTagTargetIsMovie=!1);break;case Ji.TagTrackUID:case Ji.TagEditionUID:case Ji.TagChapterUID:case Ji.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case Ji.SimpleTag:if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(o,n));break;case Ji.TagName:this.currentSimpleTagName=dr(e,n);break;case Ji.TagString:{if(!this.currentSimpleTagName)break;const t=dr(e,n);this.processTagValue(this.currentSimpleTagName,t)}break;case Ji.TagBinary:{if(!this.currentSimpleTagName)break;const t=mo(e,n);this.processTagValue(this.currentSimpleTagName,t)}break;case Ji.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(o,n));const t=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(t.raw??(t.raw={}),t.raw[this.currentAttachedFile.fileUid.toString()]=new Te(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 Ji.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 Ji.ContentEncoding:this.currentDecodingInstruction={order:0,scope:Fr.Block,data:null},this.readContiguousElements(e.slice(o,n)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case Ji.ContentEncodingOrder:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=nr(e,n);break;case Ji.ContentEncodingScope:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=nr(e,n);break;case Ji.ContentCompression:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:Dr.Zlib,settings:null},this.readContiguousElements(e.slice(o,n));break;case Ji.ContentCompAlgo:if("decompress"!==this.currentDecodingInstruction?.data?.type)break;this.currentDecodingInstruction.data.algorithm=nr(e,n);break;case Ji.ContentCompSettings:if("decompress"!==this.currentDecodingInstruction?.data?.type)break;this.currentDecodingInstruction.data.settings=mo(e,n);break;case Ji.ContentEncryption:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}return e.filePos=o+n,!0}decodeBlockData(e,t){i(e.decodingInstructions.length>0);let r=t;for(const a of e.decodingInstructions)if(i(a.data),"decompress"===a.data.type)if(a.data.algorithm===Dr.HeaderStripping)if(a.data.settings&&a.data.settings.length>0){const e=a.data.settings,t=new Uint8Array(e.length+r.length);t.set(e,0),t.set(r,e.length),r=t}return r}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 a of e.tracks){i(a.trackBacking);const e=await a.trackBacking.getFirstPacket({metadataOnly:!0});e&&(t=Math.min(t??1/0,e.timestamp))}let r=e.duration/e.timestampFactor;return r+=t??0,r}}class zr{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 L(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=x(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=R(t.presentationTimestamps,e=>t.blocks[e.blockIndex].isKeyFrame&&e.timestamp<=i);return{blockIndex:-1!==r?t.presentationTimestamps[r].blockIndex:-1,correctBlockFound:-1!==r&&i{if(e===r.cluster){const t=e.trackData.get(this.internalTrack.id).blocks.findIndex((e,t)=>e.isKeyFrame&&t>r.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)}async fetchPacketInCluster(e,t,r){if(-1===t)return null;const a=e.trackData.get(this.internalTrack.id).blocks[t];if(i(a),a.decoded||(a.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,a.data),a.decoded=!0),!a.postProcessed){if("prores"===this.internalTrack.info?.codec){if(!(a.data.length>=8&&105===a.data[4]&&99===a.data[5]&&112===a.data[6]&&102===a.data[7])){const e=new Uint8Array(a.data.length+8);l(e).setUint32(0,e.length,!1),e[4]=105,e[5]=99,e[6]=112,e[7]=102,e.set(a.data,8),a.data=e}}a.postProcessed=!0}const s=r.metadataOnly?mi:a.data,n=a.timestamp/this.internalTrack.segment.timestampFactor,o=a.duration/this.internalTrack.segment.timestampFactor,c={};a.mainAdditional&&"video"===this.internalTrack.info?.type&&this.internalTrack.info.alphaMode&&(c.alpha=r.metadataOnly?mi:a.mainAdditional,c.alphaByteLength=a.mainAdditional.byteLength);const u=new pi(s,a.isKeyFrame?"key":"delta",n,o,e.dataStartPos+t,a.data.byteLength,c);return this.packetToClusterLocation.set(u,{cluster:e,blockIndex:t}),u}async performClusterLookup(e,t,r,a,s){const{demuxer:n,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,s);-1!==i&&(l=e,u=i)}const d=x(this.internalTrack.cuePoints,r,e=>e.time),h=-1!==d?this.internalTrack.cuePoints[d]:null,f=x(this.internalTrack.clusterPositionCache,r,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>a)break}let e=n.reader.requestSliceRange(g,2,rr);if(ae(e)&&(e=await e),!e)break;const r=g,d=lr(e);if(!d||!tr.includes(d.id)&&d.id!==Ji.Void){const e=await mr(n.reader,r,tr,Math.min(o.elementEndPos??1/0,r+Or));if(e){g=e;continue}break}const h=d.id;let f=d.size;const m=e.filePos;if(h===Ji.Cluster){c=await n.readCluster(r,o),f=c.elementEndPos-m;const{blockIndex:e,correctBlockFound:i}=t(c);if(i)return this.fetchPacketInCluster(c,e,s);-1!==e&&(l=c,u=e)}if(void 0===f){i(h!==Ji.Cluster);f=(await fr(n.reader,m,ir,o.elementEndPos)).pos-m}const p=m+f;if(null===o.elementEndPos){let e=n.reader.requestSliceRange(p,2,rr);if(ae(e)&&(e=await e),!e)break;if(or(e)===Ji.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?He(a.data):null,hevcCodecInfo:"hevc"===this.internalTrack.info.codec&&a?Ze(a.data):null,vp9CodecInfo:"vp9"===this.internalTrack.info.codec&&a?dt(a.data):null,av1CodecInfo:"av1"===this.internalTrack.info.codec&&a?ft(a.data):null,proresCodecInfo:"prores"===this.internalTrack.info.codec&&a?mt(a.data):null,proresFormat:this.internalTrack.info.proresFormat};if(!y(this.internalTrack.info.colorSpace)){const a=Yt(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:Qt(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 qr extends zr{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&&Ot(e.data)}return{codec:Jt({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 Wr=async(e,t,i,r=null)=>{let a=t;for(;null===i||a=4;){const t=s.filePos,i=To(s),n=null!==e.fileSize?e.fileSize-a:null,o=ci(i,n);if(o.header&&(!r||o.header.sampleRate===r.sampleRate&&o.header.mpegVersionId===r.mpegVersionId&&o.header.layer===r.layer&&hi(o.header.channel)===hi(r.channel)))return{header:o.header,startPos:a};s.filePos=t+o.bytesAdvanced,a=s.filePos}}return null};class Hr extends fi{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 T,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 Vr(this)]})())}async advanceReader(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,Oo);if(ae(e)&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const t=qo(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}const e=await Wr(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=oi(t.mpegVersionId,t.channel);let r=this.reader.requestSlice(e.startPos+i,4);if(ae(r)&&(r=await r),r){const a=To(r);if(a===si||a===ni){if(this.xingFrameHeader||(this.xingFrameHeader=t,this.xingFrameHeaderPos=e.startPos),!this.xingData){let t=this.reader.requestSlice(e.startPos+i+4,12);if(ae(t)&&(t=await t),t){const e=mo(t,12),i=l(e),r=i.getUint32(0,!1);this.xingData={frameCount:r&ui.FrameCount?i.getUint32(4,!1):null,fileSize:r&ui.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,Oo);if(ae(i)&&(i=await i),!i)break;const r=qo(i);if(!r)break;t=!0;let a=this.reader.requestSlice(i.filePos,r.size);if(ae(a)&&(a=await a),!a)break;Wo(a,r,this.metadataTags),e=i.filePos+r.size}if(!t&&null!==this.reader.fileSize&&this.reader.fileSize>=No){let e=this.reader.requestSlice(this.reader.fileSize-No,No);ae(e)&&(e=await e),i(e);"TAG"===_o(e,3)&&zo(e,this.metadataTags)}return this.metadataTags}finally{e()}}}class Vr{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 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){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 i=(t=e.firstFrameHeader.lowSamplingFrequency,r=e.firstFrameHeader.layer,a=e.firstFrameHeader.bitrate,s=e.firstFrameHeader.sampleRate,0===r?0:1===r?144*a/(s<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=x(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 Xr=e=>{const t=l(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},$r=(e,t,r)=>{let a=0,s=null;if(e.length>0)if("vorbis"===t.codec){i(t.vorbisInfo);const n=(1<<(e=>{let t=0;for(;e;)t++,e>>=1;return t})(t.vorbisInfo.modeBlockflags.length-1))-1<<1,o=(e[0]&n)>>1;if(o>=t.vorbisInfo.modeBlockflags.length)throw new Error("Invalid mode number.");let c=r;const l=t.vorbisInfo.modeBlockflags[o];if(s=t.vorbisInfo.blocksizes[l],1===l){const i=1+(1|n),r=e[0]&i?1:0;c=t.vorbisInfo.blocksizes[r]}a=null!==c?c+s>>2:0}else if("opus"===t.codec){a=(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:pt[t]*r}})(e).durationInSamples}return{durationInSamples:a,vorbisBlockSize:s}},Gr=27,Qr=282,Yr=e=>{const t=e.filePos;if(So(e)!==jr)return null;e.skip(1);const i=po(e),r=Co(e),a=So(e),s=So(e),n=So(e),o=po(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}},Jr=(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 Zr extends fi{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,Gr,Qr);if(ae(t)&&(t=await t),!t)break;const i=Yr(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 ea(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=l(e.data);t.numberOfChannels=c.getUint8(11),t.sampleRate=c.getUint32(12,!0);const u=c.getUint8(28);t.codecInfo.vorbisInfo={blocksizes:[1<<(15&u),1<<(u>>4)],modeBlockflags:gt(a.data).modeBlockflags},wt(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=l(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=Zt,t.codecInfo.opusInfo={preSkip:a.preSkip},wt(r.data.subarray(8),this.metadataTags)}async readPacket(e,t){i(te+t.length,0);if(0===c)return null;const l=new Uint8Array(c);let u=0;for(let i=0;i{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 ea{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new T,this.internalSampleRate="opus"===e.codecInfo.codec?Zt: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 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 i(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 O}getDisposition(){return{...Se,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:a}=$r(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),s=new pi(i.metadataOnly?mi: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){i(this.bitstream.lastMetadataPacket);const t=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let r=0;"opus"===this.bitstream.codecInfo.codec&&(i(this.bitstream.codecInfo.opusInfo),r-=this.bitstream.codecInfo.opusInfo.preSkip);const a=await this.demuxer.readPacket(t.startPage,t.startSegmentIndex);return this.createEncodedPacketFromOggPacket(a,{timestampInSamples:r,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 r=L(e*this.internalSampleRate);if(0===r)return this.getFirstPacket(t);if(r<0)return null;i(this.bitstream.lastMetadataPacket);const a=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!a)return null;let s=a.startPage,n=this.demuxer.reader.fileSize;const o=[s];e:for(;s.headerStartPos+s.totalSizer?n=u.headerStartPos:(s=u,o.push(u));continue e}a=u.headerStartPos+u.totalSize}}let c=a.startPage;for(const i of o){if(i.granulePosition===s.granulePosition)break;(!c||i.headerStartPos>c.headerStartPos)&&(c=i)}let l=c;const u=[l];for(;l.serialNumber!==this.bitstream.serialNumber||l.granulePosition!==s.granulePosition;){const e=l.headerStartPos+l.totalSize;let t=this.demuxer.reader.requestSliceRange(e,Gr,Qr);ae(t)&&(t=await t),i(t);const r=Yr(t);i(r),l=r,l.serialNumber===this.bitstream.serialNumber&&u.push(l)}i(-1!==l.granulePosition);let d,h,f=null,m=l,p=0;if(l.headerStartPos===a.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:mi,endPage:m,endSegmentIndex:p};if(await this.demuxer.findNextPacketStart(e)){const e=ia(u,l,f);i(e);const t=ta(u,e.page,e.segmentIndex);t&&(l=t.page,f=t.segmentIndex)}else for(;;){const e=ia(u,l,f);if(!e)break;const t=ta(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;){i(null!==f);const e=await this.demuxer.readPacket(l,f);if(!e)break;if(!(l.headerStartPos===a.startPage.headerStartPos&&fr||Math.max(s.timestampInSamples,0)===r))break}const s=await this.demuxer.findNextPacketStart(e);if(!s)break;l=s.startPage,f=s.startSegmentIndex}return g}async getPacketSequential(e,t){const r=await this.sequentialScanMutex.acquire();try{const r=L(e*this.internalSampleRate);e=r/this.internalSampleRate;const s=x(this.sequentialScanCache,r,e=>e.timestampInSamples);let n;if(-1!==s){const e=this.sequentialScanCache[s];n=this.createEncodedPacketFromOggPacket(e.packet,{timestampInSamples:e.timestampInSamples,vorbisLastBlocksize:e.vorbisLastBlockSize},t)}else n=await this.getFirstPacket(t);let o=0;for(;n&&n.timestampe)break;if(n=r,o++,100===o){o=0;const e=this.encodedPacketToMetadata.get(n);i(e),this.sequentialScanCache.length>0&&i(a(this.sequentialScanCache).timestampInSamples<=e.timestampInSamples),this.sequentialScanCache.push(e)}}return n}finally{r()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const ta=(e,t,r)=>{let a=t,s=r;e:for(;;){for(s--;s>=0;s--){if(a.lacingValues[s]<255){s++;break e}}i(-1===s);if(!(1&a.headerType)){s=0;break}const t=_(e,e=>e.headerStartPos{if(i>0)return{page:t,segmentIndex:i-1};const r=_(e,e=>e.headerStartPos{let e=this.reader.requestSlice(0,12);ae(e)&&(e=await e),i(e);const t=_o(e,4),r="RIFX"!==t,a="RF64"===t,s=wo(e,r);let n=a?this.reader.fileSize:Math.min(s+8,this.reader.fileSize??1/0);if("WAVE"!==_o(e,4))throw new Error("Invalid WAVE file - wrong format");let o=0,c=null,l=e.filePos;for(;null===n||l=18&&357!==a){const e=go(r,i),s=t-18;if(Math.min(s,e)>=22&&a===ra.EXTENSIBLE){r.skip(6);const e=mo(r,16);a=e[0]|e[1]<<8}}if(a!==ra.MULAW&&a!==ra.ALAW||(c=8),a!==ra.PCM&&a!==ra.IEEE_FLOAT&&a!==ra.ALAW&&a!==ra.MULAW)throw new Error(`Unsupported WAVE codec (format tag ${a}). Only integer/float PCM, A-law, and \u03bc-law are supported.`);if(a===ra.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===ra.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(ae(m)&&(m=await m),!m)return;const p=_o(m,4);if("INFO"!==p&&"INF0"!==p)return;let g=m.filePos;for(;g<=e+t-8;){m.filePos=g;const e=_o(m,4),t=wo(m,i),p=mo(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(ae(i)&&(i=await i),!i)return;const r=qo(i);if(r){const a=t-Oo;if(r.size=Math.min(r.size,a),r.size>0){const t=i.slice(e+Oo,r.size);Wo(t,r,this.metadataTags)}}}getCodec(){if(i(this.audioInfo),this.audioInfo.format===ra.MULAW)return"ulaw";if(this.audioInfo.format===ra.ALAW)return"alaw";if(this.audioInfo.format===ra.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===ra.IEEE_FLOAT){if(4===this.audioInfo.sampleSizeInBytes)return"pcm-f32";if(8===this.audioInfo.sampleSizeInBytes)return"pcm-f64"}i(!1)}async getMimeType(){return"audio/wav"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}const na=2048;class oa{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}async getDecoderConfig(){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 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return i(-1!==this.demuxer.dataSize),this.demuxer.dataSize/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return O}getDisposition(){return{...Se}}async getPacketAtIndex(e,t){i(e>=0),i(this.demuxer.audioInfo);const r=e*na*this.demuxer.audioInfo.blockSizeInBytes;if(r>=this.demuxer.dataSize)return null;const a=Math.min(na*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-r);if(null===this.demuxer.reader.fileSize){let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+r,a);if(ae(e)&&(e=await e),!e)return null}let s;if(t.metadataOnly)s=mi;else{let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+r,a);ae(e)&&(e=await e),i(e),s=mo(e,a)}const n=e*na/this.demuxer.audioInfo.sampleRate,o=a/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(e,this.demuxer.lastKnownPacketIndex),new pi(s,"key",n,o,e,a)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,t){i(this.demuxer.audioInfo);const r=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/na,(this.demuxer.dataSize-1)/(na*this.demuxer.audioInfo.blockSizeInBytes)));if(r<0)return null;const a=await this.getPacketAtIndex(r,t);if(a)return a;if(0===r)return null;i(null===this.demuxer.reader.fileSize);let s=await this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,t);for(;s;){const e=await this.getNextPacket(s,t);if(!e)break;s=e}return s}getNextPacket(e,t){i(this.demuxer.audioInfo);const r=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/na);return this.getPacketAtIndex(r+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const ca=e=>{const t=e.filePos,i=mo(e,9),r=new ve(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}},la=1024;class ua extends fi{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.trackBackings=[],this.readingMutex=new T,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();i(this.firstFrameHeader),this.trackBackings=[new da(this)]})())}async advanceReader(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,Oo);if(ae(e)&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const t=qo(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}let e=this.reader.requestSliceRange(this.lastLoadedPos,7,9);if(ae(e)&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const t=ca(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 r=Pe[t.samplingFrequencyIndex];i(void 0!==r);const a=la/r,s={timestamp:this.nextTimestampInSamples/r,duration:a,dataStart:t.startPos,dataSize:t.frameLength};this.loadedSamples.push(s),this.nextTimestampInSamples+=la,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,Oo);if(ae(t)&&(t=await t),!t)break;const i=qo(t);if(!i)break;let r=this.reader.requestSlice(t.filePos,i.size);if(ae(r)&&(r=await r),!r)break;Wo(r,i,this.metadataTags),e=t.filePos+i.size}return this.metadataTags}finally{e()}}}class da{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return this.getSampleRate()/la}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 O}getCodec(){return"aac"}getInternalCodecId(){return i(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){i(this.demuxer.firstFrameHeader);const e=Ie[this.demuxer.firstFrameHeader.channelConfiguration];return i(void 0!==e),e}getSampleRate(){i(this.demuxer.firstFrameHeader);const e=Pe[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return i(void 0!==e),e}getDisposition(){return{...Se}}async getDecoderConfig(){return i(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=mi;else{let e=this.demuxer.reader.requestSlice(i.dataStart,i.dataSize);if(ae(e)&&(e=await e),!e)return null;r=mo(e,i.dataSize)}return new pi(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=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;)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=x(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,Oo);if(ae(e)&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const r=qo(e);if(!r)break;let a=this.reader.requestSlice(e.filePos,r.size);ae(a)&&(a=await a),i(a),Wo(a,r,this.metadataTags),t=e.filePos+r.size}for(t+=4;null===this.reader.fileSize||tn.end-6)return{num:o.num,blockSize:o.blockSize,sampleRate:o.sampleRate,size:n.end-e,isLastFrame:!0};if(255===po(n)){const t=n.filePos;if(po(n)!==(1===this.blockingBit?249:248)){n.filePos=t;continue}n.skip(-2);const i=n.filePos-e,r=this.readFlacFrameHeader({slice:n,isFirstPacket:!1});if(!r){n.filePos=t;continue}if(0===this.blockingBit){if(r.num-o.num!==1){n.filePos=t;continue}}else if(r.num-o.num!==o.blockSize){n.filePos=t;continue}return{num:o.num,blockSize:o.blockSize,sampleRate:o.sampleRate,size:i,isLastFrame:!1}}}}readFlacFrameHeader({slice:e,isFirstPacket:t}){const r=e.filePos,a=mo(e,4),s=new ve(a);if(32764!==s.readBits(15))return null;if(null===this.blockingBit){i(t);const e=s.readBits(1);this.blockingBit=e}else if(1===this.blockingBit){i(!t);if(1!==s.readBits(1))return null}else{if(0!==this.blockingBit)throw new Error("Invalid blocking bit");i(!t);if(0!==s.readBits(1))return null}const n=(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)(s.readBits(4));if(!n)return null;i(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}})(s.readBits(4),this.audioInfo.sampleRate);if(!o)return null;s.readBits(4),s.readBits(3);if(0!==s.readBits(1))return null;const c=(e=>{let t=0;const i=new ve(mo(e,1));for(;1===i.readBits(1);)t++;if(0===t)return i.readBits(7);const r=[],a=t-1,s=new ve(mo(e,a)),n=8-t-1;for(let o=0;oe|t<"uncommon-u16"===t?ko(e)+1:"uncommon-u8"===t?po(e)+1:"number"===typeof t?t:(F(t),void i(!1)))(e,n),u=((e,t)=>"uncommon-u16"===t?ko(e):"uncommon-u16-10"===t?10*ko(e):"uncommon-u8"===t?po(e):"number"===typeof t?t:null)(e,o);if(null===u)return null;if(u!==this.audioInfo.sampleRate)return null;const d=e.filePos-r,h=po(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:c,blockSize:l,sampleRate:u}}async advanceReader(){await this.readMetadata(),i(null!==this.lastLoadedPos),i(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 r=this.loadedSamples[this.loadedSamples.length-1],a={blockOffset:r?r.blockOffset+r.blockSize:0,blockSize:t.blockSize,byteOffset:e,byteSize:t.size};this.lastLoadedPos=this.lastLoadedPos+t.size,this.loadedSamples.push(a),t.isLastFrame&&(this.lastSampleLoaded=!0)}}class fa{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 O}getTimeResolution(){return i(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 i(this.demuxer.audioInfo),0===this.demuxer.audioInfo.totalSamples?null:this.demuxer.audioInfo.totalSamples/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getDisposition(){return{...Se}}async getDecoderConfig(){return i(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(i(this.demuxer.audioInfo),e<0)return null;const r=await this.demuxer.readingMutex.acquire();try{for(;;){const i=x(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{r()}}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 r=this.demuxer.loadedSamples[e];if(!r)return null;let a;if(t.metadataOnly)a=mi;else{let e=this.demuxer.reader.requestSlice(r.byteOffset,r.byteSize);if(ae(e)&&(e=await e),!e)return null;a=mo(e,r.byteSize)}i(this.demuxer.audioInfo);const s=r.blockOffset/this.demuxer.audioInfo.sampleRate,n=r.blockSize/this.demuxer.audioInfo.sampleRate;return new pi(a,"key",s,n,e,r.byteSize)}async getFirstPacket(e){for(;0===this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)}}const ma=9e4,pa=2**33,ga=188,ka="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.",ya=new Set([133,134,162]),ba=new Set;class wa extends fi{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);ae(e)&&(e=await e),i(e);const t=mo(e,205);if(71===t[0]&&71===t[188])this.packetOffset=0,this.packetStride=ga;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 r=this.packetOffset,a=null,s=!1,n=!1;for(;;){const e=await this.readPacketHeader(r);if(!e)break;if(0===e.payloadUnitStartIndicator){r+=this.packetStride;continue}if(n&&!this.elementaryStreams.some(t=>t.pid===e.pid)){r+=this.packetStride;continue}const t=await this.readSection(r,!0,!n);if(!t)break;const o=3,c=32;let l=!1;if(!n&&0!==t.pid){if(!(0===t.payload[0]&&0===t.payload[1]&&1===t.payload[2])){const e=new ve(t.payload),i=e.readAlignedByte();e.skipBits(8*i);l=2===e.readBits(8)}}if(0!==t.pid||s)if(t.pid!==a&&!l||n){const e=this.elementaryStreams.find(e=>e.pid===t.pid);e:if(e&&!e.initialized){const r=Sa(this,t,!0);if(!r)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 a=new Ca(e,r);if("video"===e.info.type){for(;;){if(a.suppliedPacket=null,await a.markNextPacket(),"avc"===e.info.codec){if(!a.suppliedPacket)throw new Error("Invalid AVC video stream; could not extract AVCDecoderConfigurationRecord from any packet.");if(e.info.avcCodecInfo=He(a.suppliedPacket.data),!e.info.avcCodecInfo)continue;const t=e.info.avcCodecInfo.sequenceParameterSets[0];i(t);const r=Xe(t);e.info.width=r.displayWidth,e.info.height=r.displayHeight;const s=r.pixelAspectRatio.num,n=r.pixelAspectRatio.den;s>0&&n>0&&(s>n?(e.info.squarePixelWidth=Math.round(e.info.width*s/n),e.info.squarePixelHeight=e.info.height):(e.info.squarePixelWidth=e.info.width,e.info.squarePixelHeight=Math.round(e.info.height*n/s))),e.info.colorSpace={primaries:f[r.colourPrimaries],transfer:p[r.transferCharacteristics],matrix:k[r.matrixCoefficients],fullRange:!!r.fullRangeFlag},e.info.reorderSize=r.maxDecFrameBuffering;break}if("hevc"===e.info.codec){if(!a.suppliedPacket)throw new Error("Invalid HEVC video stream; could not extract HVCDecoderConfigurationRecord from first packet.");if(e.info.hevcCodecInfo=Ze(a.suppliedPacket.data),!e.info.hevcCodecInfo)continue;const t=e.info.hevcCodecInfo.arrays.find(e=>e.nalUnitType===Ae.SPS_NUT).nalUnits[0];i(t);const r=Je(t);e.info.width=r.displayWidth,e.info.height=r.displayHeight,r.pixelAspectRatio.num>r.pixelAspectRatio.den?(e.info.squarePixelWidth=Math.round(e.info.width*r.pixelAspectRatio.num/r.pixelAspectRatio.den),e.info.squarePixelHeight=e.info.height):(e.info.squarePixelWidth=e.info.width,e.info.squarePixelHeight=Math.round(e.info.height*r.pixelAspectRatio.den/r.pixelAspectRatio.num)),e.info.colorSpace={primaries:f[r.colourPrimaries],transfer:p[r.transferCharacteristics],matrix:k[r.matrixCoefficients],fullRange:!!r.fullRangeFlag},e.info.reorderSize=r.maxDecFrameBuffering;break}throw new Error("Unhandled.")}e.info.decoderConfig={codec:Qt({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 a.markNextPacket(),!a.suppliedPacket)throw new Error(`Couldn't parse first media packet for Elementary Stream with PID ${e.pid}`);if("aac"===e.info.codec){const t=ho.tempFromBytes(a.suppliedPacket.data),i=ca(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=Ie[i.channelConfiguration],e.info.sampleRate=Pe[i.samplingFrequencyIndex]}else if("mp3"===e.info.codec){const t=To(ho.tempFromBytes(a.suppliedPacket.data)),i=ci(t,a.suppliedPacket.data.byteLength);if(!i.header)throw new Error("Invalid MP3 audio stream; could not read frame header from first packet.");e.info.numberOfChannels=hi(i.header.channel),e.info.sampleRate=i.header.sampleRate}else if("ac3"===e.info.codec){const t=St(a.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=Tt[t.acmod]+t.lfeon,e.info.sampleRate=Ee[t.fscod]}else if("eac3"===e.info.codec){const t=It(a.suppliedPacket.data);if(!t)throw new Error("Invalid E-AC-3 audio stream; could not read sync frame from first packet.");const i=xt(t);if(null===i)throw new Error("Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.");e.info.numberOfChannels=Ct(t),e.info.sampleRate=i}else{if("dts"!==e.info.codec)throw new Error("Unhandled.");{const t=Nt(a.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:Jt({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 ve(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),s=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=s;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&&ya.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:ba.has(t)||(be._warn(`Note: MPEG-TS streams with stream_type 0x${t.toString(16)} are not currently supported.`),ba.add(t))}c&&this.elementaryStreams.push({demuxer:this,pid:i,streamType:t,initialized:!1,firstSection:null,canBeTrustedWithKeyPackets:!1,info:c,referencePesPackets:[]})}n=!0}else{const e=new ve(t.payload),i=e.readAlignedByte();e.skipBits(8*i),e.skipBits(14);const r=e.readBits(10);for(e.skipBits(40);8*(r+o)-e.pos>c;){const t=e.readBits(16);e.skipBits(3);const i=e.readBits(13);if(0!==t){if(null!==a)throw new Error("Only files with a single program are supported.");a=i}}if(null===a)throw new Error("Program Association Table must link to a Program Map Table.");s=!0}if(n&&this.elementaryStreams.every(e=>e.initialized))break;r+=this.packetStride}if(!n){if(!s)throw new Error("No Program Association Table found in the file.");throw new Error("No Program Map Table found in the file.")}for(const i of this.elementaryStreams)i.initialized&&("video"===i.info.type?this.trackBackingEntries.push(new Pa(i)):this.trackBackingEntries.push(new Ia(i)))})())}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!==I(this.sectionEndPositions,r,e=>e)){l=!1;break}}if(l){const e=x(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(ae(t)&&(t=await t),!t)return null;if(71!==po(t))throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");const i=ko(t);return{payloadUnitStartIndicator:i>>14&1,pid:8191&i,adaptationFieldControl:po(t)>>4&3}}async readPacket(e){let t=this.reader.requestSlice(e,ga);if(ae(t)&&(t=await t),!t)return null;const i=mo(t,ga);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>=pa-t?-8589934592:pa}}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 ve(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(ka);return{sectionStartPos:t.startPos,sectionEndPos:t.endPos,pts:n,randomAccessIndicator:t.randomAccessIndicator}},Sa=(e,t,r)=>{i(null!==t.endPos);const a=Ta(e,t,r);if(!a)return null;const s=new ve(t.payload);s.skipBits(32);const n=s.readBits(16);s.skipBits(16);const o=s.readBits(8),c=s.pos+8*o;s.pos=c;const l=c/8;i(Number.isInteger(l));const u=t.payload.subarray(l,n>0?6+n:t.payload.byteLength);return{...a,data:u}};class va{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 r=0;for(const a of e.trackBackingEntries)if(a.getType()===t&&r++,i(a instanceof va),a.elementaryStream===this.elementaryStream)break;return r}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.elementaryStream.streamType}getName(){return null}getLanguageCode(){return O}getDisposition(){return{...Se,primary:!1}}getTimeResolution(){return ma}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 pi(i.metadataOnly?mi:e.data,r,e.pts/ma,Math.max(t/ma,0),e.sequenceNumber,e.data.byteLength)}async getFirstPacket(e){const t=this.elementaryStream.firstSection;i(t);const r=Sa(this.elementaryStream.demuxer,t,!0);i(r);const a=new Ca(this.elementaryStream,r),s=new Ba(this,a),n=await s.readNext();if(!n)return null;const o=this.createEncodedPacket(n.packet,n.duration,e);return this.packetBuffers.set(o,s),this.packetSectionStarts.set(o,n.packet.sectionStartPos),o}async getNextPacket(e,t){let r=this.packetBuffers.get(e);if(r){const i=await r.readNext();if(!i)return null;this.packetBuffers.delete(e);const a=this.createEncodedPacket(i.packet,i.duration,t);return this.packetBuffers.set(a,r),this.packetSectionStarts.set(a,i.packet.sectionStartPos),a}const a=this.packetSectionStarts.get(e);if(void 0===a)throw new Error("Packet was not created from this track.");const s=this.elementaryStream.demuxer,n=await s.readSection(a,!0);i(n);const o=Sa(s,n,!0);i(o);const c=new Ca(this.elementaryStream,o);r=new Ba(this,c);const l=e.sequenceNumber;for(;;){const e=await r.readNext();if(!e)return null;if(e.packet.sequenceNumber>l){const i=this.createEncodedPacket(e.packet,e.duration,t);return this.packetBuffers.set(i,r),this.packetSectionStarts.set(i,e.packet.sectionStartPos),i}}}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,r){const s=L(e*ma),n=this.elementaryStream.demuxer,{reader:o,seekChunkSize:c}=n,l=this.elementaryStream.pid,u=async(e,t,i)=>{let r=e;for(;re.pts),g=-1!==p?m[p]:null;if(g&&s-g.pts<45e3)f=g.sectionStartPos;else{let e=0;if(null!==o.fileSize){const t=Math.ceil(o.fileSize/c);if(t>1){let i=0,r=t-1;for(e=i;i<=r;){const t=Math.floor((i+r)/2),a=q(t*c,n.packetStride)+h.sectionStartPos,o=a+c,l=await u(a,o,!1);l?l.pesPacketHeader.pts<=s?(e=t,i=t+1):r=t-1:r=t-1}}}f=q(e*c,n.packetStride)+h.sectionStartPos}const k=await u(f,o.fileSize??1/0,!1);let y=k?.pesPacketHeader??null;y||(y=h);const b=this.getReorderSize(),w=async(e,t)=>{const o=await n.readSection(e,!0);i(o);const c=Sa(n,o,!0);i(c);const l=new Ca(this.elementaryStream,c),u=new Ba(this,l);for(;;){if((a(u.presentationOrderPackets)?.pts??-1/0)>=s)break;if(!(await u.readNextPacket()))break}const d=R(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();i(m);const p=this.createEncodedPacket(m.packet,m.duration,r);return this.packetBuffers.set(p,u),this.packetSectionStarts.set(p,m.packet.sectionStartPos),p};if(!t||this.allPacketsAreKeyPackets()){e:for(;;){let e=y.sectionStartPos+n.packetStride;for(;;){const t=await n.readPacketHeader(e);if(!t)break e;if(t.pid===l&&1===t.payloadUnitStartIndicator){const t=await n.readSection(e,!1);if(t){const e=Ta(n,t,!1);if(e&&null!==e.pts){if(e.pts>s)break e;y=e,xa(this.elementaryStream,y);break}}}e+=n.packetStride}}e:for(let e=0;e=n.packetOffset;){const t=await n.readPacketHeader(e);if(!t)break e;if(t.pid===l&&1===t.payloadUnitStartIndicator){const t=await n.readSection(e,!1);if(t){const e=Ta(n,t,!1);if(e&&null!==e.pts){y=e;break}}}e-=n.packetStride}}return w(y.sectionStartPos,e=>e.pts<=s)}{let e=f,t=null;const r=!this.elementaryStream.canBeTrustedWithKeyPackets;for(;;){let a=null;const f=e<=h.sectionStartPos;let m,p=null;if(f)m=h,p=d;else{const t=await u(e,o.fileSize??1/0,r);m=t?.pesPacketHeader??null,p=t?.section??null}let g=!1,k=0;e:for(;m&&!(null!==t&&m.sectionStartPos>=t);){if(m.pts<=s){let e;if(this.elementaryStream.canBeTrustedWithKeyPackets)e=1===m.randomAccessIndicator;else{i(p);const t=Sa(n,p,!0);i(t);const r=new Ca(this.elementaryStream,t);await r.markNextPacket(),e=1===r.suppliedPacket?.randomAccessIndicator}e&&(a=m)}if(m.pts>s&&(g=!0),g&&(k++,k>b))break;let e=m.sectionStartPos+n.packetStride;for(;;){const t=await n.readPacketHeader(e);if(!t)break e;if(t.pid===l&&1===t.payloadUnitStartIndicator){const t=await n.readSection(e,r);if(t){const e=Ta(n,t,!1);if(e&&null!==e.pts){m=e,p=t,xa(this.elementaryStream,m);break}}}e+=n.packetStride}}if(a){let e=a;if(0===k)e:for(let i=0;i=n.packetOffset;){const i=await n.readPacketHeader(t);if(!i)break e;if(i.pid===l&&1===i.payloadUnitStartIndicator){const i=await n.readSection(t,r);if(i){const t=Ta(n,i,!1);if(t&&null!==t.pts){e=t;break}}}t-=n.packetStride}}const t=await w(e.sectionStartPos,e=>e.pts<=s&&1===e.randomAccessIndicator);return i(t),t}if(f)return null;t=e,e=Math.max(q(e-h.sectionStartPos-c,n.packetStride)+h.sectionStartPos,h.sectionStartPos)}}}}class Pa extends va{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 i(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}}class Ia extends va{getType(){return"audio"}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}async getDecoderConfig(){return i(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 0}}const xa=(e,t)=>{const i=e.referencePesPackets,r=x(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 i(e),e}async bufferData(e){const t=this.endPos+e;for(;this.endPos=u)break;d=e;const i=c+d;if(d+3>=u){this.seekTo(i);break}const h=l[d+1],f=l[d+2],m=l[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=l[k];let T,S,v;if("avc"===t)T=Le(w),S=T===Re.NON_IDR_SLICE||T===Re.SLICE_DPA||T===Re.IDR,v=T===Re.SEI||T===Re.SPS||T===Re.PPS||T===Re.AUD;else{T=Ye(w);if(((1&w)<<5|l[k+1]>>3)>0){d+=p;continue}S=T<=Ae.RASL_R||T>=Ae.BLA_W_LP&&T<=21,v=T>=Ae.VPS_NUT&&T<=37||T===Ae.PREFIX_SEI_NUT||T>=41&&T<=44||T>=48&&T<=55}let P=!1;if(S){let e;if("avc"===t){const t=l.subarray(y,y+b),i=s(new ve(t));e=!n||i<=o,o=i}else e=l[y]>>7===1;e&&(n?P=!0:n=!0)}else v&&n&&(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,r=128;for(;;){let a=this.ensureBuffered(r);ae(a)&&(a=await a);const s=this.currentPos;for(;this.currentPos-s>6,o=63&s[4];if(3===n||o>37){this.seekTo(t+1);continue}const c=vt[3*o+n];i(void 0!==c),this.seekTo(t),a=this.ensureBuffered(c),ae(a)&&(a=await a);const l=Math.round(13824e4/e.info.sampleRate);return this.supplyPacket(a,l)}if("eac3"===t){if(11!==r)continue;this.skip(-1);const t=this.currentPos;let i=this.ensureBuffered(5);if(ae(i)&&(i=await i),i<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=Pt[n];this.seekTo(t),i=this.ensureBuffered(s),ae(i)&&(i=await i);const c=256*o,l=Math.round(c*ma/e.info.sampleRate);return this.supplyPacket(i,l)}if("dts"===t){if(127!==r&&100!==r)continue;this.skip(-1);const t=this.currentPos;let i=this.ensureBuffered(18);if(ae(i)&&(i=await i),i<18)return;const a=this.readBytes(18),s=Lt(a);let n=s?null:zt(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);ae(i)&&(i=await i),n=zt(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(ae(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 r;if(i(-1!==t),t===this.presentationOrderPackets.length-1)r=this.lastDuration;else{r=this.presentationOrderPackets[t+1].pts-e.pts,this.lastDuration=r}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:r}}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(i(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 Ea="application/vnd.apple.mpegurl",_a="#EXT-X-STREAM-INF:",Ra="#EXT-X-I-FRAME-STREAM-INF:",Fa="#EXT-X-MEDIA:",Aa="#EXTINF:",Da="#EXT-X-MAP:",Ma="#EXT-X-KEY:",Na="#EXT-X-MEDIA-SEQUENCE:",Oa="#EXT-X-BYTERANGE:",La="#EXT-X-PROGRAM-DATE-TIME:",za="#EXT-X-TARGETDURATION:",Ua="#EXT-X-PLAYLIST-TYPE:",qa=e=>0===e.length||e.startsWith("#")&&!e.startsWith("#EXT");class Wa{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=de(e,e=>"video"===e.getType())+1;e.push(new ja(this,t,i))}else if("audio"===t.type){const i=de(e,e=>"audio"===e.getType())+1;e.push(new Ka(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=de(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=de(e,e=>"audio"===e.getType())+1;e.push(new Ka(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 Va{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(),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()}async createAdjustedPacket(e,t,r){i(e.sequenceNumber>=0),i(this.segmentedInput.firstSegment);const a=await this.segmentedInput.getMediaOffset(t,r.input),s=t.timestamp-this.segmentedInput.firstSegment.timestamp,n=e.clone({timestamp:U(e.timestamp+a,await r.getTimeResolution()),sequenceNumber:Math.floor(1e8*s)+e.sequenceNumber});return this.packetInfos.set(n,{segment:t,track:r,sourcePacket:e}),n}async getFirstPacket(e){await this.hydrate(),i(this.firstInputTrack),i(this.firstSegment);let t=this.firstInputTrack,r=this.firstSegment;for(;;){if(t){const i=await t._backing.getFirstPacket(e);if(i)return this.createAdjustedPacket(i,r,t)}if(r=await this.segmentedInput.getNextSegment(r,{skipLiveWait:e.skipLiveWait}),!r)break;const i=this.segmentedInput.getInputForSegment(r);t=(await i.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 Va{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 Ka extends Va{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())}}ce();const Xa=1/0;"undefined"!==typeof FinalizationRegistry&&new FinalizationRegistry(e=>{e()});class $a extends ge{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 lo;return this._sizePromise??(this._sizePromise=(async()=>{let e=this._getFileSize();return void 0!==e||(await this._read(0,1,0,Xa),e=this._getFileSize(),i(void 0!==e)),e})())}async getSize(){if(this._disposed)throw new lo;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 ls(this,e,t)}_dispatchRead(e,t){this.onread?.(e,t),this._emit("read",{start:e,end:t})}ref(){return new Ga(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){this._refCount--,0===this._refCount&&(this._dispose(),this._disposed=!0)}}class Ga{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;i(e._refCount>0),e._decrementRefCount(),e._refFinalizationRegistry?.unregister(this),this._freed=!0,this._source=null}[Symbol.dispose](){this.freed||this.free()}}class Qa extends $a{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 $a||e instanceof Ga))throw new TypeError("requestHandler must return or resolve to a Source or SourceRef.");const i=e instanceof $a?e.ref():e;return(t=i.source)._usedForHls||(t._usedForHls=this._usedForHls),i};return ae(t)?t.then(i):i(t)}}const Ya=(e,t)=>e.path===t.path;class Ja extends Qa{constructor(){super(...arguments),this._root=null,this._rootRequest=null}_read(e,t,r,a){if(!this._root){if(!this._rootRequest){const e=this._resolveRequest({path:this.rootPath,isRoot:!0}),t=e=>{const t=e instanceof $a?e.ref():e;return this._root=t,this._rootRequest=null,t};ae(e)?this._rootRequest=e.then(t):(t(e),i(this._root))}if(this._rootRequest)return this._rootRequest.then(i=>i.source._read(e,t,r,a))}return this._root.source._read(e,t,r,a)}_getFileSize(){if(this._root)return this._root.source._getFileSize()}_dispose(){this._root?this._root.free():this._rootRequest&&this._rootRequest.then(e=>e.free())}}const Za="undefined"!==typeof FinalizationRegistry?new FinalizationRegistry(e=>{e.cancel().catch(()=>{})}):null;class es extends $a{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&&(!le(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 cs({maxCacheSize:t.maxCacheSize??8388608,maxWorkerCount:4,runWorker:this._runWorker.bind(this),onIdleWorkerRemoved:e=>{const t=this._readers.get(e);t&&(this._readers.delete(e),Za?.unregister(e),t.cancel().catch(()=>{}))},prefetchProfile:os.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){i(e.strictTarget);let t=this._readers.get(e);if(void 0===t){if("stream"in this._blob&&!Y()&&!1!==this._options.useStreamReader){t=this._blob.slice(e.currentPos).stream().getReader(),Za?.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 be._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)},is=new Set;class rs extends Qa{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&&(!le(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 rs(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??ts,this._requestInit={...t.requestInit};let i=null;if(t.requestInit?.headers){const e={...X(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=ss(i);e&&(this._offset=e.offset,this._length=e.length)}this._orchestrator=new cs({maxCacheSize:t.maxCacheSize??67108864,maxWorkerCount:t.parallelism??2,runWorker:this._runWorker.bind(this),prefetchProfile:os.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:N(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 ae(s)?s.then(n):n(s)}async _runWorker(e){for(;;){const i=new AbortController,r=await $(this._options.fetchFn??fetch,this._url,K(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")||is.has(e.origin)||(be._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.`),is.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){be._error("Error while reading response stream. Attempting to resume.",t),await pe(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(),r=0,a=0;const s=new ReadableStream({pull:async e=>{for(;;){let s;try{s=await t.read()}catch(i){if(this._disposed)throw i;const e=this._getRetryDelay(1,i,this._url);if(null===e)throw i;be._error("Error while reading response stream. Attempting to resume.",i),await pe(1e3*e);const s=await $(this._options.fetchFn??fetch,this._url,K(this._requestInit,{headers:{Range:`bytes=${r}-`}}),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(),a=206===s.status?0:r;continue}if(s.done)return void e.close();let n=s.value;if(a>0){const e=Math.min(a,n.length);a-=e,n=n.subarray(e)}if(0!==n.length)return r+=n.length,void e.enqueue(n)}},cancel:()=>t.cancel()}),n=new ns(s,{maxCacheSize:this._orchestrator.options.maxCacheSize,handleUnhandledError:this._options.handleUnhandledError});n._endIndex=this._orchestrator.fileSize,n._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.",n.on("read",({start:e,end:t})=>this._dispatchRead(e,t)),this._sequentialBacking=n;const o=new Set;for(const i of this._orchestrator.workers){for(const e of i.pendingSlices)o.add(e);i.aborted=!0,i.pendingSlices.length=0}for(const i of this._orchestrator.queuedReads)for(const e of i.pendingSlices)o.add(e);this._orchestrator.workers.length=0,this._orchestrator.queuedReads.length=0;for(const c of o){const e=n._read(c.start,c.start+c.bytes.length);ae(e)?e.then(e=>{e?(i(e.offset===c.start),c.resolve(e.bytes)):c.resolve(null)},e=>c.reject(e)):(i(null===e),c.resolve(null))}}_dispose(){this._orchestrator.dispose(),this._sequentialBacking&&(this._sequentialBacking._disposed=!0,this._sequentialBacking._dispose())}}const as=/^bytes=(\d+)-(\d*)$/,ss=e=>{const t=as.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=x(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}=B();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 lo);this._pendingSlices.length=0,this._cache.length=0,this._reader?.cancel()}}const os={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(ne(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 cs{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,r,a){i(!this.disposed);const s=this.options.prefetchProfile(e,t,this.workers),n=Math.max(s.start,r),o=Math.min(s.end,this.fileSize??1/0,a);i(n<=e&&t<=o);let c=null;const u=x(this.cache,e,e=>e.start),d=-1!==u?this.cache[u]:null;d&&d.start<=e&&t<=d.end&&(d.age=this.nextAge++,c={bytes:d.bytes,view:d.view,offset:d.start});const h=x(this.cache,n,e=>e.start),f=c?null:new Uint8Array(t-e);let m=0,p=n;const g=[];if(-1!==h){for(let r=h;r=o)break;if(a.end<=n)continue;const s=Math.max(n,a.start),c=Math.min(o,a.end);if(i(s<=c),p=f.length&&(c={bytes:f,view:l(f),offset:e}),0===g.length)return i(c),c;const{promise:k,resolve:y,reject:b}=B(),w=[];for(const i of g){const r=Math.max(e,i.start),a=Math.min(t,i.end);r===i.start&&a===i.end?w.push(i):re.hole.start),r=-1!==t?this.queuedReads[t]:null;for(r&&i.start<=r.hole.end?(r.hole.end=Math.max(r.hole.end,i.end),r.strictTarget&&(r.strictTarget=e),T&&r.pendingSlices.push(T)):(t++,r={hole:{start:i.start,end:i.end},strictTarget:e,pendingSlices:T?[T]:[],age:this.nextAge++},this.queuedReads.splice(t,0,r));t+1r.hole.end)break;r.hole.end=Math.max(r.hole.end,e.hole.end),r.pendingSlices.push(...e.pendingSlices),r.strictTarget&&(r.strictTarget=e.strictTarget),r.age=Math.min(r.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)}}):(i(f),c=k.then(t=>t&&{bytes:t,view:l(t),offset:e})),c}checkHoleAgainstWorker(e,t,i){if(ne(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 i=0;it.start&&(t.start=a),t.end<=t.start&&(s.holes.splice(e,1),e--)}0===s.holes.length&&(s.resolve(s.bytes),e.pendingSlices.splice(i,1),i--)}for(let i=0;ie){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);i(-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=x(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=l(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=l(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 ae(a)?a.then(s):s(a)}_dispose(){this._ref?.free()}ref(){return this._ref??(this._ref=this._baseSource.ref()),super.ref()}}var us=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},ds=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 hs=/^0[xX][0-9a-fA-F]+$/,fs=/^data:.*;base64,/i;class ms extends Ha{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 pe(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 r=us(t,await this.demuxer.input._getSourceUncached({path:this.rootPath,isRoot:!1}),!1),a=new uo(r.source),s=await a.requestEntireFile();i(s),e=Ro(s,s.length,{ignore:qa}),r.source instanceof Qa&&(this.rootPath=r.source.rootPath)}catch(T){t.error=T,t.hasError=!0}finally{ds(t)}}const t=!1!==this.input._formatOptions.hls?.offsetTimestampsByDateTime;let r=!1,s=0,n=null,o=null,c=null,u=0,d=null,h=null,f=null,m=null,p=null,g=null,k=!1,y=a(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=>{u=e,y&&(i(null!==y.sequenceNumber),y.sequenceNumber0&&null!==g&&(s=u*g),k=!0);const e=T.slice(8),t=e.indexOf(","),i=-1===t?e:e.slice(0,t),r=Number(i);if(!Number.isFinite(r)||r<0)throw new Error(`Invalid #EXTINF tag duration '${i}'.`);o=r}else if(T.startsWith(Da)){const e=new Wa(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 r=null;if(null!==i&&(r=b(i)),r&&null===r.offset)throw new Error("Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset.");if(!y){const e={path:ue(this.rootPath,t),offset:r?.offset??0,length:r?.length??null};if("AES-128"===c?.method&&!c.iv)throw new Error("IV attribute must be set on #EXT-X-KEY tag preceding the #EXT-X-MAP tag.");h={timestamp:s,unixEpochTimestamp:n,firstSegment:null,sequenceNumber:null,location:e,duration:0,encryption:c,initSegment:null,lastProgramDateTimeSeconds:p}}o=null,null===m?f=null:m=null}else if(T.startsWith(Ma)){const e=new Wa(T.slice(11)),t=e.get("method");if("NONE"===t)c=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(!hs.test(r))throw new Error(`Unsupported IV format '${r}'.`);let e=r.slice(2);e=e.padStart(32,"0"),i=new Uint8Array(Pi);for(let t=0;t=8&&112===t[4]&&115===t[5]&&115===t[6]&&104===t[7]){const e=l(t).getUint32(0);r=gi(t.subarray(8,Math.min(e,t.length)))}}c={method:t,psshBox:r}}}}else if(T.startsWith(Na)){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(Oa)){const e=b(T.slice(17));if(null===e.offset){if(null===f)throw new Error("Invalid M3U8 file; #EXT-X-BYTERANGE without offset requires a previous byte range.");e.offset=f}m=e,f=e.offset+e.length}else if(T.startsWith(La)){if(y)continue;const e=T.slice(25),i=Date.parse(e);if(!Number.isFinite(i))continue;const r=i/1e3;if(p===r)continue;if(null===p&&this.segments.length>0){const e=a(this.segments),i=r-(e.timestamp+e.duration);for(const r of this.segments)r.unixEpochTimestamp=r.timestamp+i,t&&(r.timestamp=r.unixEpochTimestamp)}p=r,n=r,t&&(s=r)}else if("#EXT-X-DISCONTINUITY"===T)d=null;else if(T.startsWith(za)){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(Ua)){"vod"===T.slice(21).toLowerCase()&&(this.streamHasEnded=!0)}}}else{if("#EXTM3U"!==T)throw new Error("Invalid M3U8 file; expected first line to be #EXTM3U.");r=!0}}if(!r)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=x(this.segments,e,e=>e.timestamp);if(-1===r)return null;if(r0;for(;;){if(ae.segment===t);if(r)return r.age=this.nextInputCacheAge++,r.input;let a=null;(t.initSegment||t.firstSegment)&&(a=this.getInputForSegment(t.initSegment??t.firstSegment));const s={...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=>ki(e,r))||(i=[...i,r]),this.input._formatOptions.isobmff.resolveKeyId({...e,psshBoxes:i})})}},n=new oo({source:new Ja(t.location.path,async e=>{i(e.isRoot);const r={...e,isRoot:!1};let a;const s=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;i(e.iv);let n=await this.input._getSourceCached(r);if(s){const e=n.source.slice(t.location.offset,t.location.length??void 0).ref();n.free(),n=e}const o=((e,t,i)=>{let r=!1,a=0;const s=new Ai;return new ReadableStream({pull:async n=>{r||(s.init(await t()),r=!0);let o=e.requestSliceRange(a,0,65552);if(ae(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=mo(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 uo(n.source),async()=>{const t={stack:[],error:void 0,hasError:!1};try{const i=us(t,await this.input._getSourceCached({path:e.keyUri,isRoot:!1},no),!1),r=new uo(i.source),a=await r.requestSlice(0,Pi);if(!a)throw new Error("Invalid AES-128 key; expected at least 16 bytes of data.");return{key:mo(a,Pi),iv:e.iv}}catch(i){t.error=i,t.hasError=!0}finally{ds(t)}},()=>{n.free()});a=new ns(o).ref()}else i(!1);else if(a=await this.input._getSourceCached(r),s){const e=a.source.slice(t.location.offset,t.location.length??void 0).ref();a.free(),a=e}return a}),formats:this.input._formats.filter(e=>!(e instanceof Ds)),initInput:a??void 0,formatOptions:s});n._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:n,age:this.nextInputCacheAge++});if(this.inputCache.length>4){const e=he(this.inputCache,e=>e.age);i(-1!==e),this.inputCache.splice(e,1)}return n}async getLiveRefreshInterval(){return 0===this.getRemainingWaitTimeMs()&&await this.runUpdateSegments(),this.streamHasEnded?null:this.refreshInterval}}class ps extends fi{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()=>{i(this.input._rootSource instanceof Qa);const e=await this.input._reader.requestEntireFile();i(e);const t=Ro(e,e.length,{ignore:qa}),{rootPath:r}=this.input._rootSource,a=[],s=[];for(let i=1;i"video"===e.attributes.get("type").toLowerCase()).map(e=>e.attributes.get("group-id")))],o=[...new Set(s.filter(e=>"audio"===e.attributes.get("type").toLowerCase()).map(e=>e.attributes.get("group-id")))],c=await Promise.all(a.map(async(e,t)=>{const a=[],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=>qt.includes(ii(e))),f=l.some(e=>Ht.includes(ii(e)));if(null!==u&&!h){if(!n.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=s.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 a=ue(r,t),s=this.getSegmentedInputForPath(a),n=(await s.getTrackBackings()).find(e=>"video"===e.getType());if(!n||null===await n.getCodec())break e;const o=await n.getDecoderConfig().then(e=>e?.codec??null);i(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=s.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 a=ue(r,t),s=this.getSegmentedInputForPath(a),n=(await s.getTrackBackings()).find(e=>"audio"===e.getType());if(!n||null===await n.getCodec())break e;const o=await n.getDecoderConfig().then(e=>e?.codec??null);i(null!==o),l.push(o)}}l=[...new Set(l)];let m=null,p=null;const g=e.attributes.getAsNumber("bandwidth");i(null!==g);const k=e.attributes.getAsNumber("average-bandwidth"),y=e.attributes.get("name");for(const i of l){const r=ii(i);if(null!==r)if(qt.includes(r)){if(null!==m)throw new Error("Unsupported M3U8 file; multiple video codecs found in the CODECS attribute of a variant stream.");m=i;const r=e.attributes.get("video");if(null===r){const i=e.attributes.get("resolution");let r=null,s=null;if(i){const e=i.match(/^(\d+)x(\d+)$/);e&&(r=Number(e[1]),s=Number(e[2]))}a.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:O,lineNumber:e.lineNumber,fullPath:e.fullPath,fullCodecString:m,pairingMask:1n<0?r:null}})}else{if(!o.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 s){const s=i.attributes.get("group-id"),n=i.attributes.get("type");if(s!==r||"audio"!==n.toLowerCase())continue;const o=i.attributes.get("channels")??e.attributes.get("channels"),c=null!==o?Number(o.split("/")[0]):null;a.push({id:-1,demuxer:this,backingTrack:null,default:bs(i.attributes),autoselect:bs(i.attributes)||ws(i.attributes),languageCode:Ts(i.attributes.get("language")),lineNumber:i.lineNumber,fullPath:i.fullPath??e.fullPath,fullCodecString:p,pairingMask:1n<0?c:null}})}}}}return a})),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===O&&(t.languageCode=e.languageCode)):(e.id=l.length+1,l.push(e))};for(const i of c)for(const e of i)u(e);l.sort((e,t)=>e.lineNumber-t.lineNumber),this.trackBackings=[];for(const i of l)"video"===i.info.type?this.trackBackings.push(new ks(i)):this.trackBackings.push(new ys(i));this.internalTracks=l})())}async getTrackBackings(){return await 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 ms(this,e,i,null),this.segmentedInputs.push(t),t}async getMetadataTags(){return{}}async getMimeType(){return Ea}dispose(){if(this.segmentedInputs){for(const e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}}class gs{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 r=(await e.getTrackBackings()).filter(e=>e.getType()===this.getType());if(1===r.length)t=r[0];else if(this instanceof ks){for(const i of r)if(await i.getCodec()===this.getCodec()){t=i;break}}else{i(this instanceof ys);for(const e of r)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{...Se,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}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 ks extends gs{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())}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 ys extends gs{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}async getDecoderConfig(){return await this.hydrate(),this.backingAudioTrack.getDecoderConfig()}}const bs=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}".`)},Ts=e=>{if(null===e)return O;const t=e.split("-")[0];return t||O};class Ss{constructor(){this._isIsobmff=!1}}class vs extends Ss{constructor(){super(...arguments),this._isIsobmff=!0}async _getMajorBrand(e){let t=e._reader.requestSlice(0,12);if(ae(t)&&(t=await t),!t)return null;t.skip(4);const i=_o(t,4);return"ftyp"!==i&&"styp"!==i?null:_o(t,4)}_createDemuxer(e){return new Di(e)}}class Ps extends vs{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(ae(t)&&(t=await t),!t)return!1;let r=To(t),a=8;if(1===r){let t=e._reader.requestSlice(i+8,8);if(ae(t)&&(t=await t),!t)return!1;r=Io(t),a=16}if(r8)return!1;if(nr(i,r)!==Ji.EBML)return!1;const a=cr(i);if("number"!==typeof a)return!1;let s=e._reader.requestSlice(i.filePos,a);if(ae(s)&&(s=await s),!s)return!1;const n=i.filePos;for(;s.filePos<=n+a-2;){const e=lr(s);if(!e)break;const{id:i,size:r}=e,a=s.filePos;if(void 0===r)return!1;switch(i){case Ji.EBMLVersion:if(1!==nr(s,r))return!1;break;case Ji.EBMLReadVersion:if(1!==nr(s,r))return!1;break;case Ji.DocType:if(ur(s,r)!==t)return!1;break;case Ji.DocTypeVersion:if(nr(s,r)>4)return!1}s.filePos=a+r}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new Lr(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}}class Cs extends xs{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}}class Bs extends Ss{async _canReadInput(e){let t=0;for(;;){let i=e._reader.requestSlice(t,Oo);if(ae(i)&&(i=await i),!i)break;const r=qo(i);if(!r)break;t=i.filePos+r.size}const i=await Wr(e._reader,t,t+4096);if(!i)return!1;const r=i.header,a=oi(r.mpegVersionId,r.channel);let s=e._reader.requestSlice(i.startPos+a,4);if(ae(s)&&(s=await s),!s)return!1;const n=To(s);if(n===si||n===ni)return!0;t=i.startPos+i.header.totalSize;const o=await Wr(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 Hr(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}}class Es extends Ss{async _canReadInput(e){let t=e._reader.requestSlice(0,12);if(ae(t)&&(t=await t),!t)return!1;const i=_o(t,4);if("RIFF"!==i&&"RIFX"!==i&&"RF64"!==i)return!1;t.skip(4);return"WAVE"===_o(t,4)}_createDemuxer(e){return new sa(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}}class _s extends Ss{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return ae(t)&&(t=await t),!!t&&"OggS"===_o(t,4)}_createDemuxer(e){return new Zr(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}}class Rs extends Ss{async _canReadInput(e){let t=0;for(;;){let i=e._reader.requestSlice(t,Oo);if(ae(i)&&(i=await i),!i)break;const r=qo(i);if(!r)break;t=i.filePos+r.size}let i=e._reader.requestSlice(t,4);return ae(i)&&(i=await i),!!i&&"fLaC"===_o(i,4)}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new ha(e)}}class Fs extends Ss{async _canReadInput(e){let t=0;for(;;){let i=e._reader.requestSlice(t,Oo);if(ae(i)&&(i=await i),!i)break;const r=qo(i);if(!r)break;t=i.filePos+r.size}let i=e._reader.requestSliceRange(t,7,9);if(ae(i)&&(i=await i),!i)return!1;const r=ca(i);if(!r)return!1;if(t+=r.frameLength,i=e._reader.requestSliceRange(t,7,9),ae(i)&&(i=await i),!i)return!1;const a=ca(i);return!!a&&(r.objectType===a.objectType&&r.samplingFrequencyIndex===a.samplingFrequencyIndex&&r.channelConfiguration===a.channelConfiguration)}_createDemuxer(e){return new ua(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}}class As extends Ss{async _canReadInput(e){let t=e._reader.requestSlice(0,205);if(ae(t)&&(t=await 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 wa(e)}get name(){return"MPEG Transport Stream"}get mimeType(){return"video/MP2T"}}class Ds extends Ss{async _canReadInput(e){let t=e._reader.requestSlice(0,7);if(ae(t)&&(t=await t),!t)return!1;if(!("#EXTM3U"===_o(t,7)))return!1;if(!(e._rootSource instanceof Qa))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 ps(e)}get name(){return"HTTP Live Streaming (HLS)"}get mimeType(){return Ea}}const Ms=new Ps,Ns=new Is,Os=new xs,Ls=new Cs,zs=new Bs,Us=new Es,qs=new _s,Ws=new Fs,Hs=new Rs,Vs=new As,js=new Ds,Ks=[js,Ms,Ns,Os,Ls,Us,qs,Hs,zs,Ws,Vs],Xs=[js,Ms,Ns,zs,Ws,Vs];var $s=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});ce();let Gs=-1/0,Qs=-1/0,Ys=null;"undefined"!==typeof FinalizationRegistry&&(Ys=new FinalizationRegistry(e=>{const t=performance.now();"video"===e.type?(t-Gs>=1e3&&(be._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."),Gs=t),"undefined"!==typeof VideoFrame&&e.data instanceof VideoFrame&&e.data.close()):(t-Qs>=1e3&&(be._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."),Qs=t),"undefined"!==typeof AudioData&&e.data instanceof AudioData&&e.data.close())}));class Js{constructor(){this._referenceCount=0,this._lastAllocationBuffer=null}}const Zs=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],en=new Set(Zs);class tn{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||!en.has(t.format))throw new TypeError("init.format must be one of: "+Zs.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&&me(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??hn(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?c(e):c(e).slice(),this._layout=i,this.colorSpace=new on(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&&me(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 on(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&&me(t.visibleRect,"init.visibleRect"),"undefined"!==typeof VideoFrame)return new tn(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:Z(),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 on({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else{if(!(e instanceof Js))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&&!Zs.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=fe({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),Ys?.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 Js?new tn(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):cn(this._data)?new tn(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):this._data instanceof Uint8Array?(i(this._layout),new tn(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 tn(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||(Ys?.unregister(this),this._data instanceof Js?(this._data._referenceCount--,0===this._data._referenceCount&&this._data.close()):cn(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(dn(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(cn(this._data))return this._data.allocationSize(e);return mn(this,e).allocationSize}async copyTo(e,t={}){if(!w(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(dn(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(i(null!==this._data),cn(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 Js)){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 tn))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(u){i.error=u,i.hasError=!0}finally{$s(i)}}}const r=mn(this,t);i(this.format);const a=c(e);if(a.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.');n=e}else if(this._data instanceof Uint8Array)i(this._layout),i(this._layout.length===s.length),n=this._layout.map((e,t)=>{const i=Math.ceil(this.codedHeight/s[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);n=[{data:c(t.data),stride:4*this.codedWidth}]}const o=[],l=s.length;for(let i=0;is.byteLength)throw new Error("Source buffer OOB read.");if(l+u>a.byteLength)throw new Error("Destination buffer OOB write.");const i=s.subarray(c,c+u);a.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"),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 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 cn(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,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&&un(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=ln(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?nn(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(i(null!==this._data),this._data instanceof Js||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&&un(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=r(this.rotation+(e.rotate??0)),[i,a]=t%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let s=e.crop;s&&(s=ln(s,i,a));const n=s?s.width:i,o=s?s.height:a,c=n/o;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=n,u=o),l=z(l,e.roundDimensionsTo??1),u=z(u,e.roundDimensionsTo??1);const d={width:l,height:u,fit:e.fit??"fill",rotation:t,crop:s??{left:0,top:0,width:i,height:a},alpha:e.alpha??"keep"};for(const r of rn){let e=r(this,d);if(ae(e)&&(e=await e),null!==e)return e}const{canvas:h,context:f,isNew:m}=nn(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 tn(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 rn=[],an=[];let sn=0;const nn=(e,t)=>{for(const a of an)if(a.canvas.width===e&&a.canvas.height===t)return a.age=sn++,{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 an.length>=3&&an.splice(he(an,e=>e.age),1),an.push({canvas:i,context:r,age:sn++}),{canvas:i,context:r,isNew:!0}};class on{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(h);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(m);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(g);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 cn=e=>"undefined"!==typeof VideoFrame&&e instanceof VideoFrame,ln=(e,t,r)=>{const a=Math.min(e.left,t),s=Math.min(e.top,r),n=Math.min(e.width,t-a),o=Math.min(e.height,r-s);return i(n>=0),i(o>=0),{left:a,top:s,width:n,height:o}},un=(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.")},dn=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.")}},hn=(e,t,i)=>{const r=fn(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},fn=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:F(e),i(!1)}},mn=(e,t)=>{const i={left:0,top:0,width:e.codedWidth,height:e.codedHeight},r=t.rect,a=pn(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 kn(a,n,s)},pn=(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(!gn(a,s))throw new TypeError("visibleRect alignment is invalid for the format.");return s},gn=(e,t)=>{if(null===e)return!0;const i=fn(e);for(let r=0;r{const r=fn(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/(Tn(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*Tn(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=Tn(t),s=Sn(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(!w(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&&!yn.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:r,frameCount:a,frameOffset:s}=t;let{planeIndex:n}=t,o=this.format;const c=r??this.format;if(!c)throw new Error("Destination format not determined");const u=this.numberOfFrames,d=this.numberOfChannels,h=s??0;if(h>=u)throw new RangeError("frameOffset out of range");const f=void 0!==a?a:u-h;if(f>u-h)throw new RangeError("frameCount out of range");const m=Tn(c),p=Sn(c);if(p&&n>=d)throw new RangeError("planeIndex out of range");if(!p&&0!==n)throw new RangeError("planeIndex out of range");const g=(p?f:f*d)*m;if(e.byteLength2&&c!==o)return void xn(this._data,k,o,c,d,n,h,f);try{return void this._data.copyTo(e,{planeIndex:n,frameOffset:h,frameCount:f,format:c})}catch(I){if("f32-planar"===c)throw I;o="f32-planar"}}const b=vn(o),T=Tn(o),S=Sn(o);let v;if(this._data instanceof bn){const e=e=>{const t=this._data.getDataPlane(e);if(!(t instanceof Uint8Array))throw new TypeError("getDataPlane() must return a Uint8Array.");const i=u*T*(S?1:d);if(t.byteLength!==i)throw new TypeError(`Data plane ${e} has invalid size. Expected exactly ${i} bytes, got ${t.byteLength} bytes.`);return t};if(S)if(p)v=e(n),n=0;else{v=new Uint8Array(u*T*d);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 wn({data:a,format:this.format,sampleRate:this.sampleRate,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp+e/this.sampleRate})}close(){this._closed||(Ys?.unregister(this),this._data instanceof bn?(this._data._referenceCount--,0===this._data._referenceCount&&this._data.close()):In(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 bn?this._createAudioDataFromData():In(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(Sn(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")}},Sn=e=>{switch(e){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},vn=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)}},Pn=e=>{switch(e){case"u8":case"u8-planar":return(e,t,i)=>e.setUint8(t,N(127.5*(i+1),0,255));case"s16":case"s16-planar":return(e,t,i)=>e.setInt16(t,N(Math.round(32767*i),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,i)=>e.setInt32(t,N(Math.round(2147483647*i),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,i)=>e.setFloat32(t,i,!0)}},In=e=>"undefined"!==typeof AudioData&&e instanceof AudioData,xn=(e,t,i,r,a,s,n,o)=>{const c=vn(i),u=Pn(r),d=Tn(i),h=Tn(r),f=Sn(i);if(Sn(r))if(f){const r=new ArrayBuffer(o*d),a=l(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.")},_n=e=>{if(!le(e))throw new TypeError("timestamp must be a number.")},Rn=(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 Fn{constructor(e){if(!(e instanceof Xn))throw new TypeError("track must be an InputTrack.");this._track=e}async getFirstPacket(e={}){if(En(e),this._track.input._disposed)throw new lo;return Rn(this._track,this._track._backing.getFirstPacket(e),e)}async getFirstKeyPacket(e={}){En(e);const t=await this.getFirstPacket(e);return t?"key"===t.type?t:this.getNextKeyPacket(t,e):null}async getPacket(e,t={}){if(_n(e),En(t),this._track.input._disposed)throw new lo;return Rn(this._track,this._track._backing.getPacket(e,t),t)}async getNextPacket(e,t={}){if(!(e instanceof pi))throw new TypeError("packet must be an EncodedPacket.");if(En(t),this._track.input._disposed)throw new lo;return Rn(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(_n(e),En(t),this._track.input._disposed)throw new lo;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);const r=await this._track._backing.getKeyPacket(e,t);if(!r)return r;i("key"===r.type);return"delta"===await this._track.determinePacketType(r)?this.getKeyPacket(r.timestamp-1/await this._track.getTimeResolution(),t):r}async getNextKeyPacket(e,t={}){if(!(e instanceof pi))throw new TypeError("packet must be an EncodedPacket.");if(En(t),this._track.input._disposed)throw new lo;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);const r=await this._track._backing.getNextKeyPacket(e,t);if(!r)return r;i("key"===r.type);return"delta"===await this._track.determinePacketType(r)?this.getNextKeyPacket(r,t):r}packets(e,t,i={}){if(void 0!==e&&!(e instanceof pi))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 pi))throw new TypeError("endPacket must be an EncodedPacket.");if(En(i),this._track.input._disposed)throw new lo;const r=[];let{promise:a,resolve:s}=B(),{promise:n,resolve:o}=B(),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}=B()),await n):(r.push(u),s(),({promise:a,resolve:s}=B()),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 lo;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 An{constructor(e,t){this.onSample=e,this.onError=t}}class Dn{mediaSamplesInRange(e=-1/0,t=1/0,i){_n(e),_n(t);const r=[];let a=!1,s=null,{promise:n,resolve:o}=B(),{promise:c,resolve:l}=B(),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}=B())))},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=Mn(r.length);if(r.length+f.getDecodeQueueSize()>e){({promise:c,resolve:l}=B()),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 lo;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 r=async function*(e){Symbol.iterator in e?yield*e[Symbol.iterator]():yield*e[Symbol.asyncIterator]()}(e),a=[],s=[];let{promise:n,resolve:o}=B(),{promise:c,resolve:l}=B(),u=!1,d=!1,h=null,f=null,m=!1;const p=e=>{s.push(e),o(),({promise:n,resolve:o}=B())},g={...t,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{h=await this._createDecoder(e=>{if(l(),d)return void e.close();let t=0;for(;a.length>0&&e.timestamp-a[0]>-1e-10;)t++,a.shift();if(t>0)for(let i=0;i{m||(f=e,m=!0,o())});const e=this._createPacketSink();let t=null,n=null,k=-1;const y=async()=>{i(n),i(h);let t=n;for(h.decode(t);t.sequenceNumberr&&!d;)({promise:c,resolve:l}=B()),await c;if(d)break;const a=await e.getNextPacket(t,g);i(a),h.decode(a),t=a}k=-1},b=async()=>{i(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 s)e?.close()};return{async next(){for(;;){if(k.input._disposed)throw d=!0,y(),new lo;if(d)return{value:void 0,done:!0};if(m)throw d=!0,y(),f;if(s.length>0){const e=s.shift();return i(void 0!==e),l(),{value:e,done:!1}}if(u)return{value:void 0,done:!0};await n}},return:async()=>(d=!0,l(),o(),y(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}}const Mn=e=>0===e?40:8;class Nn extends An{constructor(e,t,r,a,s,n){super(e,t),this.codec=r,this.decoderConfig=a,this.rotation=s,this.timeResolution=n,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new G,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=Cn.find(e=>e.supports(r,a));if(o)this.customDecoder=new o,this.customDecoder.codec=r,this.customDecoder.config=a,this.customDecoder.onSample=e=>{if(!(e instanceof tn))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(te()){if("avc"===r&&this.decoderConfig.description){const e=je(c(this.decoderConfig.description));if(e&&e.sequenceParameterSets.length>0){const t=Xe(e.sequenceParameterSets[0]);t&&(0===t.frameMbsOnlyFlag&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"}),0!==t.maxDecFrameBuffering&&1!==t.bitstreamRestrictionFlag&&(e.sequenceParameterSets[0]=Ge(t),this.decoderConfig={...this.decoderConfig,description:Ve(e)}))}}y(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:(i(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(i(this.decoder),Y()||C(this.inputTimestamps,e.timestamp,e=>e),te()&&0===this.currentPacketIndex)if("avc"===this.codec){const t=[];let i=!1;for(const a of Oe(e.data,this.decoderConfig)){const r=Le(e.data[a.offset]);if(i||(i=r>=1&&r<=5),r===Re.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&c(t.description)[4];return We(e,i+1)}return qe(e)})(t,this.decoderConfig);e=new pi(r,e.type,e.timestamp,e.duration)}else if("hevc"===this.codec){const t=lt(e.data,this.decoderConfig);t&&(e=new pi(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 Ln),!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=kt(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 Qe(e,this.decoderConfig)){const i=Ye(e[t.offset]);if(i===Ae.RASL_N||i===Ae.RASL_R)return!0}return!1}sampleHandler(e){if(Y()){if(this.sampleQueue.length>0&&e.timestamp>=a(this.sampleQueue).timestamp){for(const e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}C(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)}async mergeAlpha(e,t){const r=B();this.mergeAlphaPromises.push(r.promise);const a={sample:null};this.finalSamples.push(a);try{if(t){i(this.merger);const r=await this.merger.merge(e,t);a.sample=new tn(r)}else a.sample=new tn(e);for(;this.finalSamples.length>0&&null!==this.finalSamples[0].sample;){const e=this.finalSamples.shift();this.sampleHandler(e.sample)}}catch(s){E(this.finalSamples,a),this.onError(s)}finally{E(this.mergeAlphaPromises,r.promise),r.resolve()}}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(i(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),Y()){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()):(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=>e?.close()),this.alphaQueue.length=0,this.merger?.close());for(const e of this.sampleQueue)e.close();this.sampleQueue.length=0}}let On=null;class Ln{constructor(){this.workers=[],this.nextWorkerIndex=0,this.pendingRequests=new Map,this.nextRequestId=0}merge(e,t){if(0===this.workers.length){if(!On){const e=new Blob([`(${zn.toString()})()`],{type:"application/javascript"});On=URL.createObjectURL(e)}const e=N(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=B();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 zn=()=>{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 qn extends Dn{constructor(e,t={}){if(!(e instanceof Qn))throw new TypeError("videoTrack must be an InputVideoTrack.");Un(t),super(),this._track=e,this._decoderOptions=t}async _createDecoder(e,t){if(!(await 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 r=await this._track.getCodec(),a=await this._track.getRotation();let s=await this._track.getDecoderConfig();const n=await this._track.getTimeResolution();return i(r&&s),s={...s,hardwareAcceleration:this._decoderOptions.hardwareAcceleration,optimizeForLatency:this._decoderOptions.optimizeForLatency},new Nn(e,t,r,s,a,n)}_createPacketSink(){return new Fn(this._track)}async getSample(e,t={}){_n(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 Wn{constructor(e,t={}){if(this._rotation=0,this._initPromise=null,this._nextCanvasIndex=0,!(e instanceof Qn))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&&un(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&&Un(t.decoderOptions),this._videoTrack=e,this._alpha=t.alpha??!1,this._options=t,this._fit=t.fit??"fill",this._videoSampleSink=new qn(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=ln(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,r=this._height;let a=this._canvasPool[this._nextCanvasIndex],s=!1;a||("undefined"!==typeof document?(a=document.createElement("canvas"),a.width=t,a.height=r):a=new OffscreenCanvas(t,r),this._canvasPool.length>0&&(this._canvasPool[this._nextCanvasIndex]=a),s=!0),this._canvasPool.length>0&&(this._nextCanvasIndex=(this._nextCanvasIndex+1)%this._canvasPool.length);const n=a.getContext("2d",{alpha:this._alpha||Z()});i(n),e._drawWithFitAndMipmapping(a,n,{fit:this._fit,rotation:this._rotation,crop:this._crop,targetIsFresh:s,fillBlack:!this._alpha&&Z()});const o={canvas:a,timestamp:e.timestamp,duration:e.duration};return e.close(),o}async getCanvas(e,t){_n(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*M(this._videoSampleSink.samples(e,t,i),e=>this._videoSampleToWrappedCanvas(e))}async*canvasesAtTimestamps(e,t){await this._ensureInit(),yield*M(this._videoSampleSink.samplesAtTimestamps(e,t),e=>e&&this._videoSampleToWrappedCanvas(e))}}class Hn extends An{constructor(e,t,i,r){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new G,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=Bn.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 wn))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 wn(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),this.expectedFirstTimestamp??(this.expectedFirstTimestamp=e.timestamp),this.decoder.decode(e.toEncodedAudioChunk()))}async flush(){this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(i(this.decoder),await 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 Vn extends An{constructor(e,t,r){super(e,t),this.decoderConfig=r,this.currentTimestamp=null,i(Wt.includes(r.codec)),this.codec=r.codec;const{dataType:a,sampleSize:s,littleEndian:n}=ti(this.codec);switch(this.inputSampleSize=s,s){case 1:"unsigned"===a?this.readInputValue=(e,t)=>e.getUint8(t)-128:"signed"===a?this.readInputValue=(e,t)=>e.getInt8(t):"ulaw"===a?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,n)-32768:"signed"===a?this.readInputValue=(e,t)=>e.getInt16(t,n):i(!1);break;case 3:"unsigned"===a?this.readInputValue=(e,t)=>A(e,t,n)-2**23:"signed"===a?this.readInputValue=(e,t)=>((e,t,i)=>A(e,t,i)<<8>>8)(e,t,n):i(!1);break;case 4:"unsigned"===a?this.readInputValue=(e,t)=>e.getUint32(t,n)-2**31:"signed"===a?this.readInputValue=(e,t)=>e.getInt32(t,n):"float"===a?this.readInputValue=(e,t)=>e.getFloat32(t,n):i(!1);break;case 8:"float"===a?this.readInputValue=(e,t)=>e.getFloat64(t,n):i(!1);break;default:F(s),i(!1)}switch(s){case 1:"ulaw"===a||"alaw"===a?(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"===a?(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:F(s),i(!1)}}getDecodeQueueSize(){return 0}decode(e){const t=l(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 wn({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 Dn{constructor(e){if(!(e instanceof Yn))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(ie("AudioDecoder"));throw new Error("This audio track cannot be decoded in this environment. Make sure to check decodability before using a track.")}const r=await this._track.getCodec(),a=await this._track.getDecoderConfig();return i(r&&a),Wt.includes(a.codec)?new Vn(e,t,a):new Hn(e,t,r,a)}_createPacketSink(){return new Fn(this._track)}async getSample(e,t={}){_n(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){if(!(e instanceof Yn))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){_n(e);const i=await this._audioSampleSink.getSample(e,t);return i&&this._audioSampleToWrappedArrayBuffer(i)}buffers(e,t,i){return M(this._audioSampleSink.samples(e,t,i),e=>this._audioSampleToWrappedArrayBuffer(e))}buffersAtTimestamps(e,t){return M(this._audioSampleSink.samplesAtTimestamps(e,t),e=>e&&this._audioSampleToWrappedArrayBuffer(e))}}class Xn{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof Qn}isAudioTrack(){return this instanceof Yn}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}async getInternalCodecId(){return this._backing.getInternalCodecId()}get internalCodecId(){return $n(this._backing.getInternalCodecId(),"internalCodecId","getInternalCodecId")}async getLanguageCode(){return this._backing.getLanguageCode()}get languageCode(){return $n(this._backing.getLanguageCode(),"languageCode","getLanguageCode")}async getName(){return this._backing.getName()}get name(){return $n(this._backing.getName(),"name","getName")}async getTimeResolution(){return this._backing.getTimeResolution()}get timeResolution(){return $n(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 $n(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 U((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 Fn(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 Xn))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(to({filter:e=>e.canBePairedWith(this)},e))}async getPairableVideoTracks(e){return this.input.getVideoTracks(to({filter:e=>e.canBePairedWith(this)},e))}async getPairableAudioTracks(e){return this.input.getAudioTracks(to({filter:e=>e.canBePairedWith(this)},e))}async getPrimaryPairableVideoTrack(e){return this.input.getPrimaryVideoTrack(to({filter:e=>e.canBePairedWith(this)},e))}async getPrimaryPairableAudioTrack(e){return this.input.getPrimaryAudioTrack(to({filter:e=>e.canBePairedWith(this)},e))}async hasPairableTrack(e){e&&(e=Gn(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=Gn(e)),this.hasPairableTrack(async t=>t.isVideoTrack()&&(!e||await e(t)))}hasPairableAudioTrack(e){return e&&(e=Gn(e)),this.hasPairableTrack(async t=>t.isAudioTrack()&&(!e||await e(t)))}}const $n=(e,t,i)=>{if(ae(e))throw new Error(`'${t}' is deprecated and not available synchronously for this track. Use the preferred '${i}()' instead.`);return e},Gn=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 ae(r)?r.then(i):i(r)}:void 0};class Qn extends Xn{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 $n(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 $n(this._backing.getCodedWidth(),"codedWidth","getCodedWidth")}async getCodedHeight(){return this._backing.getCodedHeight()}get codedHeight(){return $n(this._backing.getCodedHeight(),"codedHeight","getCodedHeight")}async getRotation(){return this._backing.getRotation()}get rotation(){return $n(this._backing.getRotation(),"rotation","getRotation")}async getSquarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelWidth(){return $n(this._backing.getSquarePixelWidth(),"squarePixelWidth","getSquarePixelWidth")}async getSquarePixelHeight(){return this._backing.getSquarePixelHeight()}get squarePixelHeight(){return $n(this._backing.getSquarePixelHeight(),"squarePixelHeight","getSquarePixelHeight")}async getPixelAspectRatio(){return this._pixelAspectRatioCache??(this._pixelAspectRatioCache=fe({num:await this.getSquarePixelWidth()*await this.getCodedHeight(),den:await this.getSquarePixelHeight()*await this.getCodedWidth()}))}get pixelAspectRatio(){return this._pixelAspectRatioCache??(this._pixelAspectRatioCache=fe({num:$n(this._backing.getSquarePixelWidth(),"pixelAspectRatio","getPixelAspectRatio")*$n(this._backing.getCodedHeight(),"pixelAspectRatio","getPixelAspectRatio"),den:$n(this._backing.getSquarePixelHeight(),"pixelAspectRatio","getPixelAspectRatio")*$n(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=$n(e,"displayWidth","getDisplayWidth");if(null!==t)return t}const t=$n(this._backing.getRotation(),"displayWidth","getDisplayWidth")%180===0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight();return $n(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=$n(e,"displayHeight","getDisplayHeight");if(null!==t)return t}const t=$n(this._backing.getRotation(),"displayHeight","getDisplayHeight")%180===0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth();return $n(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(i(null!==t),Cn.some(i=>i.supports(t,e)))return!0;if("undefined"===typeof VideoDecoder)return!1;return!0===(await VideoDecoder.isConfigSupported(e)).supported}catch(e){return be._error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof pi))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 r=await this.getDecoderConfig();return i(r),kt(t,r,e.data)}async computeFrameRateMetrics(e={}){if(!e||"object"!==typeof e)throw new TypeError("options must be an object.");if(void 0!==e.targetPacketCount&&(!le(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 Fn(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:so(P),minFrameRate:d/p,maxFrameRate:d/m,averageFrameRate:d*k/g,medianFrameRate:P,frameRateIsConstant:null!==u&&1===m&&1===p,probedPacketCount:n}}}class Yn extends Xn{constructor(e,t){super(e,t),this._backing=t}get type(){return"audio"}async getCodec(){return this._backing.getCodec()}get codec(){return $n(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){return await(this._backing.getHasOnlyKeyPackets?.())??!0}async getNumberOfChannels(){return this._backing.getNumberOfChannels()}get numberOfChannels(){return $n(this._backing.getNumberOfChannels(),"numberOfChannels","getNumberOfChannels")}async getSampleRate(){return this._backing.getSampleRate()}get sampleRate(){return $n(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(i(null!==t),Bn.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 be._error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof pi))throw new TypeError("packet must be an EncodedPacket.");return null===await this.getCodec()?null:"key"}}const Jn=e=>-(e??-1/0),Zn=e=>-e,eo=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 ae(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 ae(r)?r.then(i):i(r)}:void 0}},to=(e,t)=>({filter:e?.filter||t?.filter?i=>{const r=e?.filter?.(i)??!0,a=e=>!1!==e&&(t?.filter?.(i)??!0);return ae(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 ae(r)||ae(a)?Promise.all([r,a]).then(([e,t])=>s(e,t)):s(r,a)}:void 0}),io=async(e,t)=>{let i=e;if(t?.filter){const r=e.map(e=>t.filter(e));if(r.some(e=>ae(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=>ae(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)},ro=(e,t)=>{const i=1e6,r=1+1e-9,a=[12,15,20,24e3/1001,24,25,3e4/1001,30,48,50,6e4/1001,60,100,12e4/1001,120,144,240];if(e.length<2)return null;const s=new Float64Array(e.length-1);for(let T=1;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 Ss)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof $a||e.source instanceof Ga))throw new TypeError("options.source must be a Source or SourceRef.");if(e.source instanceof $a&&e.source._disposed)throw new TypeError("options.source must not be a disposed Source.");if(void 0!==e.initInput&&!(e.initInput instanceof oo))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 $a?this._rootRef=e.source.ref():this._rootRef=e.source,this._sourceRefs.push(this._rootRef)}get _rootSource(){return this._rootRef.source}async _getSourceUncached(e){i(this._rootSource instanceof Qa);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 r=this._sourceCache.find(i=>i.cacheGroup===t&&Ya(i.request,e));if(r)return r.age++,Promise.resolve(r.sourceRef.source.ref());const a=this._sourceCachePromises.find(i=>i.cacheGroup===t&&Ya(i.request,e));if(a)return a.promise.then(e=>e.sourceRef.source.ref());const s=(async()=>{const r=await this._getSourceUncached(e);if(de(this._sourceCache,e=>e.cacheGroup===t&&1===e.sourceRef.source._refCount)>=4){const e=he(this._sourceCache,e=>e.cacheGroup===t&&1===e.sourceRef.source._refCount?e.age:1/0);i(-1!==e);const r=this._sourceCache[e];this._sourceCache.splice(e,1),r.sourceRef.free(),E(this._sourceRefs,r.sourceRef)}this._sourceRefs.push(r);const a=this._sourceCachePromises.findIndex(t=>t.request===e);i(-1!==a),this._sourceCachePromises.splice(a,1);return{request:e,sourceRef:r,age:this._nextSourceCacheAge++,cacheGroup:t}})();return this._sourceCachePromises.push({request:e,cacheGroup:t,promise:s}),s.then(e=>{const t=e.sourceRef.source.ref();return this._sourceCache.push(e),t})}_getDemuxer(){return this._demuxerPromise??(this._demuxerPromise=(async()=>{this._reader=new uo(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 co})())}get source(){return this._rootSource}async getFormat(){return await this._getDemuxer(),i(this._format),this._format}async canRead(){try{return await this._getDemuxer(),!0}catch(e){if(e instanceof co)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=eo(e));const t=(await this._getTrackBackings()).map(e=>this._wrapBackingAsTrack(e));return io(t,e)}async getVideoTracks(e){e&&(e=eo(e));const t=(await this.getTracks()).filter(e=>e.isVideoTrack());return io(t,e)}async getAudioTracks(e){e&&(e=eo(e));const t=(await this.getTracks()).filter(e=>e.isAudioTrack());return io(t,e)}async getPrimaryVideoTrack(e){e&&(e=eo(e));const t=to(e,{sortBy:async e=>[Zn((await e.getDisposition()).default),Zn(await e.hasPairableAudioTrack()),Zn(!(await e.hasOnlyKeyPackets())),Jn(await e.getBitrate())]});return(await this.getVideoTracks(t))[0]??null}async getPrimaryAudioTrack(e){e&&(e=eo(e));const t=await this.getPrimaryVideoTrack(),i=to(e,{sortBy:async e=>[Zn(!t||e.canBePairedWith(t)),Zn((await e.getDisposition()).default),Jn(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 Qn(this,e):new Yn(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 co extends Error{constructor(e="Input has an unsupported or unrecognizable format."){super(e),this.name="UnsupportedInputFormatError"}}class lo extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}}class uo{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 lo;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 ho(t,l(t),0,e,e)}const i=e+t,r=this.source._read(e,i,0,Xa);return ae(r)?r.then(t=>t?new ho(t.bytes,t.view,t.offset,e,i):null):r?new ho(r.bytes,r.view,r.offset,e,i):null}requestSliceRange(e,t,r){if(this.source._disposed)throw new lo;if(e<0)return null;if(null!==this.fileSizeNonStrict)return this.requestSlice(e,N(this.fileSizeNonStrict-e,t,r));{const a=this.requestSlice(e,r),s=a=>a||(i(null!==this.fileSizeNonStrict),this.requestSlice(e,N(this.fileSizeNonStrict-e,t,r)));return ae(a)?a.then(s):s(a)}}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(ae(i)&&(i=await 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 a of e)i.set(a,r),r+=a.length;return new ho(i,l(i),0,0,t)})()}}class ho{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 ho(e,l(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 ho(this.bytes,this.view,this.offset,e,e+t)}}const fo=(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)=>{fo(e,t);const i=e.bytes.subarray(e.bufferPos,e.bufferPos+t);return e.bufferPos+=t,i},po=e=>(fo(e,1),e.view.getUint8(e.bufferPos++)),go=(e,t)=>{fo(e,2);const i=e.view.getUint16(e.bufferPos,t);return e.bufferPos+=2,i},ko=e=>{fo(e,2);const t=e.view.getUint16(e.bufferPos,!1);return e.bufferPos+=2,t},yo=e=>{fo(e,3);const t=A(e.view,e.bufferPos,!1);return e.bufferPos+=3,t},bo=e=>{fo(e,2);const t=e.view.getInt16(e.bufferPos,!1);return e.bufferPos+=2,t},wo=(e,t)=>{fo(e,4);const i=e.view.getUint32(e.bufferPos,t);return e.bufferPos+=4,i},To=e=>{fo(e,4);const t=e.view.getUint32(e.bufferPos,!1);return e.bufferPos+=4,t},So=e=>{fo(e,4);const t=e.view.getUint32(e.bufferPos,!0);return e.bufferPos+=4,t},vo=e=>{fo(e,4);const t=e.view.getInt32(e.bufferPos,!1);return e.bufferPos+=4,t},Po=(e,t)=>{let i,r;return t?(i=wo(e,!0),r=wo(e,!0)):(r=wo(e,!1),i=wo(e,!1)),4294967296*r+i},Io=e=>4294967296*To(e)+To(e),xo=e=>4294967296*vo(e)+To(e),Co=e=>{const t=So(e),i=(e=>{fo(e,4);const t=e.view.getInt32(e.bufferPos,!0);return e.bufferPos+=4,t})(e);return 4294967296*i+t},Bo=e=>{fo(e,4);const t=e.view.getFloat32(e.bufferPos,!1);return e.bufferPos+=4,t},Eo=e=>{fo(e,8);const t=e.view.getFloat64(e.bufferPos,!1);return e.bufferPos+=8,t},_o=(e,t)=>{fo(e,t);let i="";for(let r=0;ru.decode(mo(e,t)).split("\n").map(e=>e.trim()).filter(e=>e.length>0&&!i?.ignore?.(e));var Fo,Ao,Do,Mo;(Ao=Fo||(Fo={}))[Ao.Unsynchronisation=128]="Unsynchronisation",Ao[Ao.ExtendedHeader=64]="ExtendedHeader",Ao[Ao.ExperimentalIndicator=32]="ExperimentalIndicator",Ao[Ao.Footer=16]="Footer",(Mo=Do||(Do={}))[Mo.ISO_8859_1=0]="ISO_8859_1",Mo[Mo.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",Mo[Mo.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",Mo[Mo.UTF_8=3]="UTF_8";const No=128,Oo=10,Lo=["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"],zo=(e,t)=>{var i;const r=e.filePos;t.raw??(t.raw={}),(i=t.raw).TAG??(i.TAG=mo(e,No-3)),e.filePos=r;const a=Uo(e,30);a&&(t.title??(t.title=a));const s=Uo(e,30);s&&(t.artist??(t.artist=s));const n=Uo(e,30);n&&(t.album??(t.album=n));const o=Uo(e,4),c=Number.parseInt(o,10);Number.isInteger(c)&&c>0&&(t.date??(t.date=new Date(String(c))));const l=mo(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=Uo(e,28),e.skip(2)}else e.skip(-30),u=Uo(e,30);u&&(t.comment??(t.comment=u));const d=po(e);d{const i=mo(e,t),r=se(i.indexOf(0),i.length),a=i.subarray(0,r);let s="";for(let n=0;n{const t=e.filePos,i=_o(e,3),r=po(e),a=po(e),s=po(e),n=To(e);if("ID3"!==i||255===r||255===a||0!==(2155905152&n))return e.filePos=t,null;let o=li(n);return s&Fo.Footer&&(o+=Oo),{majorVersion:r,revision:a,flags:s,size:o}},Wo=(e,t,i)=>{var r,a,s,n,o;if(![2,3,4].includes(t.majorVersion))return void be._warn(`Unsupported ID3v2 major version: ${t.majorVersion}`);const c=t.flags&Fo.Footer?t.size-Oo:t.size,l=mo(e,c),u=new Ho(t,l);if(t.flags&Fo.Unsynchronisation&&3===t.majorVersion&&u.ununsynchronizeAll(),t.flags&Fo.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&Fo.Unsynchronisation)),d)be._warn(`Skipping encrypted ID3v2 frame ${e.id}`),u.pos=l;else if(h)be._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!==Lo[e]){i.genre??(i.genre=Lo[e]);break}}if(t=/^\d+$/.exec(e),t){const e=Number.parseInt(t[0]);if(void 0!==Lo[e]){i.genre??(i.genre=Lo[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 Ho{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:li(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 Do.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=se(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=se(r.findIndex(e=>0===e),r.length);return this.pos=i+Math.min(e+1,r.length),u.decode(r.subarray(0,e))}case Do.UTF_16_BE_NO_BOM:{const e=new TextDecoder("utf-16be"),t=se(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 Do.UTF_8:{const e=se(r.findIndex(e=>0===e),r.length);return this.pos=i+Math.min(e+1,r.length),u.decode(r.subarray(0,e))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";const t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}}class Vo{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 Kn(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 Ko=/\.m3u8(?:$|[?#])/i;function Xo(e){return"string"===typeof e&&Ko.test(e)}function $o(e){const t=function(e){return"string"===typeof e?new rs(e):e instanceof Blob?new es(e):"undefined"!==typeof ReadableStream&&e instanceof ReadableStream?new ns(e):e??null}(e);return t?new oo({source:t,formats:Xo(e)?Xs:Ks}):null}class Go{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 Qo({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 Yo{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||Xo(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 Wn(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 Jo{constructor({canvas:e,ctx:t,events:i,option:r={}}){this.events=i,this.option=r,this.audio=new Vo(i),this.video=new Yo({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 Go;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=$o(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 Qo({input:e,videoTrack:i,audioTrack:r}),s=i||r,n=Xo(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 Qo(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 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"}}(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}}class Zo{constructor({art:e,canvas:i,ctx:r,option:a}){this.art=e,this.canvas=i,this.option=a,this.events=new t,this.engine=new Jo({canvas:i,ctx:r,events:this.events,option:a}),this._src=null,this._volume=a.volume??.7,this._muted=!!a.muted,this._playbackRate=1,this.engine.setVolume(this._volume,this._muted),this.setupEventForwarding(),a.source?this.src=a.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){const i=this.engine.duration;return!i||Number.isNaN(i)||t<=0?{length:0,start:()=>0,end:()=>0}:{length:1,start:()=>e,end:()=>t}}get paused(){return this.engine.paused}get playing(){return!this.engine.paused&&!this.engine.ended}get ended(){return this.engine.ended}get seeking(){return this.engine.seeking}get readyState(){return this.engine.readyState}get networkState(){return this.engine.networkState}get error(){return this.engine.error}get playbackRate(){return this._playbackRate}set playbackRate(e){const t=Number(e);Number.isNaN(t)||t<=0||(this._playbackRate=t,this.engine.setPlaybackRate(t),this.events.emit("ratechange"))}get volume(){return this._volume}set volume(e){this._volume=function(e,t,i){return Math.max(t,Math.min(i,Number(e)||0))}(e,0,1),this._muted=!1,this.engine.setVolume(this._volume,this._muted),this.events.emit("volumechange")}get muted(){return this._muted}set muted(e){this._muted=!!e,this.engine.setVolume(this._volume,this._muted),this.events.emit("volumechange")}play(){return this.engine.play()}pause(){this.engine.pause()}load(){this._src&&this.engine.load(this._src)}getM3u8State(){return this.engine.getHlsState()}switchM3u8Quality(e){return this.engine.selectHlsQuality(e)}switchM3u8Audio(e){return this.engine.selectHlsAudio(e)}get videoWidth(){return this.engine.videoWidth}get videoHeight(){return this.engine.videoHeight}get poster(){return this.option.poster||""}set poster(e){this.option.poster=e}get autoplay(){return this.option.autoplay||!1}set autoplay(e){}get loop(){return this.option.loop||!1}set loop(e){}get controls(){return!1}set controls(e){}get playsInline(){return!0}set playsInline(e){}get crossOrigin(){return this.option.crossOrigin||""}set crossOrigin(e){}get preload(){return"auto"}set preload(e){}get defaultMuted(){return!1}set defaultMuted(e){}get defaultPlaybackRate(){return 1}set defaultPlaybackRate(e){}canPlayType(e){return"maybe"}getBoundingClientRect(){return this.canvas.getBoundingClientRect()}requestVideoFrameCallback(e){return requestAnimationFrame(t=>{e(t,{presentationTime:this.engine.currentTime,expectedDisplayTime:t+16.6,width:this.engine.videoWidth,height:this.engine.videoHeight,mediaTime:this.engine.currentTime,presentedFrames:0,processingDuration:0,captureTime:t,receiveTime:t,rtpTimestamp:0})})}cancelVideoFrameCallback(e){cancelAnimationFrame(e)}setAttribute(e,t){"src"===e?this.src=t:"autoplay"===e?this.autoplay=t:"loop"===e?this.loop=t:"muted"===e?this.muted=!0:this.canvas.setAttribute(e,t)}destroy(){this.engine.destroy()}}return function(t={}){return i=>{const{constructor:r}=i,{createElement:a}=r.utils,s=a("canvas"),n=s.getContext("2d"),o=new Zo({art:i,canvas:s,ctx:n,option:t});i.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=i.template?.$player;e&&!i.option.autoSize&&Object.assign(s.style,{width:"100%",height:"100%",objectFit:"contain"})}return i.on("resize",u),i.on("video:loadedmetadata",u),function({art:t,shim:i,option:r}){if(r.m3u8)return t.on("video:loadedmetadata",d),t.on("restart",d),{update:d};function a(e){t.controls.cache.has(e)&&t.controls.remove(e)}function s(e){t.setting.find(e)&&t.setting.remove(e)}function n(){a("mediabunny-quality"),s("mediabunny-quality")}function o(){a("mediabunny-audio"),s("mediabunny-audio")}function c(e={}){return e.control||e.setting}async function l(a){const s=r.m3u8?.quality||{};if(!c(s)||!a?.levels.length)return void n();const o=s.auto||"Auto",l=s.title||"Quality",u=s.getName||(e=>e.name||`${e.height}P`),h=a.currentLevel?u(a.currentLevel):o,f=e(a.levels.map(e=>({html:u(e),value:e.id,default:a.currentLevel?.id===e.id})),"html").sort((e,t)=>{const i=a.levels.find(t=>t.id===e.value),r=a.levels.find(e=>e.id===t.value);return(r?.height||0)-(i?.height||0)});f.push({html:o,value:"auto",default:!a.currentLevel});const m=async e=>(await i.switchM3u8Quality(e.value),t.notice.show=`${l}: ${e.html}`,await d(),e.html);s.control&&t.controls.update({name:"mediabunny-quality",position:"right",html:h,style:{padding:"0 10px"},selector:f,onSelect:m}),s.setting&&t.setting.update({name:"mediabunny-quality",tooltip:h,html:l,icon:'',width:200,selector:f,onSelect:m})}async function u(a){const s=r.m3u8?.audio||{};if(!c(s)||!a?.audios.length||a.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=a.currentAudio?u(a.currentAudio):n,f=e(a.audios.map(e=>({html:u(e),value:e.id,default:a.currentAudio?.id===e.id})),"html");f.push({html:n,value:"auto",default:!a.currentAudio});const m=async e=>(await i.switchM3u8Audio(e.value),t.notice.show=`${l}: ${e.html}`,await d(),e.html);s.control&&t.controls.update({name:"mediabunny-audio",position:"right",html:h,style:{padding:"0 10px"},selector:f,onSelect:m}),s.setting&&t.setting.update({name:"mediabunny-audio",tooltip:h,html:l,icon:'',width:200,selector:f,onSelect:m})}async function d(){const e=await i.getM3u8State();if(!e)return n(),void o();await Promise.all([l(e),u(e)])}}({art:i,shim:o,option:t}),i.on("destroy",()=>{delete i.mediabunny,o.destroy()}),s}}}); diff --git a/docs/compiled/artplayer-proxy-mediabunny.legacy.js b/docs/compiled/artplayer-proxy-mediabunny.legacy.js index 7e89ad8c9..e376a5616 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?(t.artplayerProxyMediabunny=t(),define(function(){return t.artplayerProxyMediabunny})):(e="undefined"!==typeof globalThis?globalThis:e||self).artplayerProxyMediabunny=t()}(this,function(){"use strict";var e=Object.defineProperty,t=Object.defineProperties,i=Object.getOwnPropertyDescriptors,r=Object.getOwnPropertySymbols,n=Object.prototype.hasOwnProperty,s=Object.prototype.propertyIsEnumerable,a=(e,t)=>(t=Symbol[e])?t:Symbol.for("Symbol."+e),o=Math.pow,l=(t,i,r)=>i in t?e(t,i,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[i]=r,c=(e,t)=>{for(var i in t||(t={}))n.call(t,i)&&l(e,i,t[i]);if(r)for(var i of r(t))s.call(t,i)&&l(e,i,t[i]);return e},u=(e,r)=>t(e,i(r)),d=(e,t,i)=>new Promise((r,n)=>{var s=e=>{try{o(i.next(e))}catch(t){n(t)}},a=e=>{try{o(i.throw(e))}catch(t){n(t)}},o=e=>e.done?r(e.value):Promise.resolve(e.value).then(s,a);o((i=i.apply(e,t)).next())}),h=function(e,t){this[0]=e,this[1]=t},f=(e,t,i)=>{var r=(e,t,n,s)=>{try{var a=i[e](t),o=(t=a.value)instanceof h,l=a.done;Promise.resolve(o?t[0]:t).then(i=>o?r("return"===e?e:"next",t[1]?{done:i.done,value:i.value}:i,n,s):n({value:i,done:l})).catch(e=>r("throw",e,n,s))}catch(c){s(c)}},n=e=>s[e]=t=>new Promise((i,n)=>r(e,t,i,n)),s={};return i=i.apply(e,t),s[a("asyncIterator")]=()=>s,n("next"),n("throw"),n("return"),s},m=e=>{var t,i=e[a("asyncIterator")],r=!1,n={};return null==i?(i=e[a("iterator")](),t=e=>n[e]=t=>i[e](t)):(i=i.call(e),t=e=>n[e]=t=>{if(r){if(r=!1,"throw"===e)throw t;return t}return r=!0,{done:!1,value:new h(new Promise(r=>{var n=i[e](t);n instanceof Object||(e=>{throw TypeError(e)})("Object expected"),r(n)}),1)}}),n[a("iterator")]=()=>n,t("next"),"throw"in i?t("throw"):n.throw=e=>{throw e},"return"in i&&t("return"),n},p=(e,t,i)=>(t=e[a("asyncIterator")])?t.call(e):(e=e[a("iterator")](),t={},(i=(i,r)=>(r=e[i])&&(t[i]=t=>new Promise((i,n,s)=>(t=r.call(e,t),s=t.done,Promise.resolve(t.value).then(e=>i({value:e,done:s}),n)))))("next"),i("return"),t);function g(e,t){const i=new Map;return e.filter(e=>{const r=e[t];return void 0===r||!i.has(r)&&i.set(r,1)})}class k{constructor(){this.listeners=new Map}addEventListener(e,t){this.listeners.has(e)||this.listeners.set(e,[]),this.listeners.get(e).push(t)}removeEventListener(e,t){const i=this.listeners.get(e);if(!i)return;const r=i.indexOf(t);r>=0&&i.splice(r,1)}emit(e,t){const i=new Event(e);i.detail=t;const r=this.listeners.get(e);r&&r.forEach(e=>e(i))}}function y(e){if(!e)throw new Error("Assertion failed.")}const b=e=>{const t=(e%360+360)%360;if(0===t||90===t||180===t||270===t)return t;throw new Error(`Invalid rotation ${e}.`)},T=e=>e&&e[e.length-1],S=e=>{let t=0;for(;0===e.readBits(1)&&t<32;)t++;if(t>=32)throw new Error("Invalid exponential-Golomb code.");return(1<{const t=S(e);return 0===(1&t)?-(t>>1):t+1>>1},w=e=>e.constructor===Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),P=e=>e.constructor===DataView?e:ArrayBuffer.isView(e)?new DataView(e.buffer,e.byteOffset,e.byteLength):new DataView(e),I=new TextDecoder,x=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])),C={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},B=x(C),E={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},_=x(E),A={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},F=x(A),R=e=>e instanceof ArrayBuffer||"undefined"!==typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e);class D{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}acquire(){return d(this,null,function*(){let e;const t=new Promise(t=>{let i=!1;e=()=>{i||(t(),this.pending--,i=!0)}}),i=this.currentPromise;return this.currentPromise=t,this.pending++,yield i,e})}}const M=/^[0-9a-fA-F]+$/,N=e=>[...e].map(e=>e.toString(16).padStart(2,"0")).join(""),O=e=>(e=(e=(e=(e=(e=e>>1&1431655765|(1431655765&e)<<1)>>2&858993459|(858993459&e)<<2)>>4&252645135|(252645135&e)<<4)>>8&16711935|(16711935&e)<<8)>>16&65535|(65535&e)<<16)>>>0,L=(e,t,i)=>{let r=0,n=e.length-1,s=-1;for(;r<=n;){const a=r+n>>1,o=i(e[a]);o===t?(s=a,n=a-1):o{let r=0,n=e.length-1,s=-1;for(;r<=n;){const a=r+(n-r+1)/2|0;i(e[a])<=t?(s=a,r=a+1):n=a-1}return s},U=(e,t,i)=>{const r=z(e,i(t),i);e.splice(r+1,0,t)},q=()=>{let e,t;return{promise:new Promise((i,r)=>{e=i,t=r}),resolve:e,reject:t}},W=(e,t)=>{for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},V=(e,t)=>{for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},H=e=>{throw new Error(`Unexpected value: ${e}`)},K=(e,t,i)=>{const r=e.getUint8(t),n=e.getUint8(t+1),s=e.getUint8(t+2);return i?r|n<<8|s<<16:r<<16|n<<8|s},j=(e,t,i,r)=>{i>>>=0,i&=16777215,e.setUint8(t,i>>>16&255),e.setUint8(t+1,i>>>8&255),e.setUint8(t+2,255&i)},X=(e,t)=>({next(){return d(this,null,function*(){const i=yield e.next();return i.done?{value:void 0,done:!0}:{value:t(i.value),done:!1}})},return:()=>e.return(),throw:t=>e.throw(t),[Symbol.asyncIterator](){return this}}),$=(e,t,i)=>Math.max(t,Math.min(i,e)),Q="und",G=e=>{const t=Math.round(e);return Math.abs(e/t-1)<10*Number.EPSILON?t:e},Y=(e,t)=>Math.round(e*t)/t,J=(e,t)=>Math.floor(e/t)*t,Z=/^[a-z]{3}$/,ee=e=>Z.test(e),te=1e6*(1+Number.EPSILON),ie=(e,t)=>{const i=c(c({},e),t);if(e.headers||t.headers){const r=e.headers?re(e.headers):{},n=t.headers?re(t.headers):{},s=c({},r);Object.entries(n).forEach(([e,t])=>{const i=Object.keys(s).find(t=>t.toLowerCase()===e.toLowerCase());i&&delete s[i],s[e]=t}),i.headers=s}return i},re=e=>{if(e instanceof Headers){const t={};return e.forEach((e,i)=>{t[i]=e}),t}if(Array.isArray(e)){const t={};return e.forEach(([e,i])=>{t[e]=i}),t}return e},ne=(e,t,i,r,n)=>d(null,null,function*(){let s=0;for(;;)try{return yield e(t,i)}catch(a){if(n())throw a;s++;const e=r(s,a,t);if(null===e)throw a;if(console.error("Retrying failed fetch. Error:",a),!Number.isFinite(e)||e<0)throw new TypeError("Retry delay must be a non-negative finite number.");if(e>0&&(yield Pe(1e3*e)),n())throw a}});class se{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}let ae=null;const oe=()=>{var e;return null!==ae?ae:ae=!("undefined"===typeof navigator||!((null==(e=navigator.vendor)?void 0:e.match(/apple/i))||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent)))};let le=null;const ce=()=>{var e;return null!==le?le:le="undefined"!==typeof navigator&&(null==(e=navigator.userAgent)?void 0:e.includes("Firefox"))};let ue=null;const de=()=>{var e;return null!==ue?ue:ue=!("undefined"===typeof navigator||!(null==(e=navigator.vendor)?void 0:e.includes("Google Inc"))&&!/Chrome/.test(navigator.userAgent))};let he=null;const fe=()=>{if(null!==he)return he;if("undefined"===typeof navigator)return null;const e=/\bChrome\/(\d+)/.exec(navigator.userAgent);return e?he=Number(e[1]):null},me=(e,t)=>-1!==e?e:t,pe=(e,t,i,r)=>e<=r&&i<=t,ge=e=>{const t=atob(e),i=new Uint8Array(t.length);for(let r=0;r{null!=Symbol.dispose||(Symbol.dispose=Symbol("Symbol.dispose"))},ye=e=>"number"===typeof e&&!Number.isNaN(e),be=(e,t)=>{if(t.includes("://"))return t;if(e.includes("://")){const t=e.indexOf("?");-1!==t&&(e=e.slice(0,t))}let i;if(t.startsWith("/")){const r=e.indexOf("://");if(-1===r)i=t;else{const n=e.indexOf("/",r+3);i=-1===n?e+t:e.slice(0,n)+t}}else{const r=e.lastIndexOf("/");i=-1===r?t:e.slice(0,r+1)+t}let r="";const n=i.indexOf("://");if(-1!==n){const e=i.indexOf("/",n+3);-1!==e&&(r=i.slice(0,e),i=i.slice(e))}const s=i.split("/"),a=[];for(const o of s)".."===o?a.pop():"."!==o&&a.push(o);return r+a.join("/")},Te=(e,t)=>{let i=0;for(let r=0;r{let i=-1,r=1/0;for(let n=0;n{y(Number.isInteger(e.num)),y(Number.isInteger(e.den)),y(0!==e.den);let t=Math.abs(e.num),i=Math.abs(e.den);for(;0!==i;){const e=t%i;t=i,i=e}const r=t||1;return{num:e.num/r,den:e.den/r}},we=(e,t)=>{if("object"!==typeof e||!e)throw new TypeError(`${t} must be an object.`);if(!Number.isInteger(e.left)||e.left<0)throw new TypeError(`${t}.left must be a non-negative integer.`);if(!Number.isInteger(e.top)||e.top<0)throw new TypeError(`${t}.top must be a non-negative integer.`);if(!Number.isInteger(e.width)||e.width<0)throw new TypeError(`${t}.width must be a non-negative integer.`);if(!Number.isInteger(e.height)||e.height<0)throw new TypeError(`${t}.height must be a non-negative integer.`)},Pe=e=>new Promise(t=>setTimeout(t,e));class Ie{constructor(){this._listeners=new Map}on(e,t,i){var r;this._listeners.has(e)||this._listeners.set(e,new Set);const n={fn:t,once:null!=(r=null==i?void 0:i.once)&&r};return this._listeners.get(e).add(n),()=>{var t;null==(t=this._listeners.get(e))||t.delete(n)}}_emit(...e){const[t,i]=e,r=this._listeners.get(t);if(r)for(const s of r){try{s.fn(i)}catch(n){console.error(n)}s.once&&r.delete(s)}}}class xe{constructor(e,t){if(this.data=e,this.mimeType=t,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if("string"!==typeof t)throw new TypeError("mimeType must be a string.")}}class Ce{constructor(e,t,i,r){if(this.data=e,this.mimeType=t,this.name=i,this.description=r,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(void 0!==t&&"string"!==typeof t)throw new TypeError("mimeType, when provided, must be a string.");if(void 0!==i&&"string"!==typeof i)throw new TypeError("name, when provided, must be a string.");if(void 0!==r&&"string"!==typeof r)throw new TypeError("description, when provided, must be a string.")}}const Be={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1};class Ee{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){var e;const t=Math.floor(this.pos/8),i=null!=(e=this.bytes[t])?e:0,r=7-(7&this.pos),n=(i&1<>r;return this.pos++,n}readBits(e){if(1===e)return this.readBit();let t=0;for(let i=0;i>i-r-1<{if(!e||e.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");const t=new Ee(e);let i=t.readBits(5);31===i&&(i=32+t.readBits(6));const r=t.readBits(4);let n=null;15===r?n=t.readBits(24):r<_e.length&&(n=_e[r]);const s=t.readBits(4);let a=null;return s>=1&&s<=7&&(a=Ae[s]),{objectType:i,frequencyIndex:r,sampleRate:n,channelConfiguration:s,numberOfChannels:a}},Re=["avc","hevc","vp9","av1","vp8"],De=["pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be","pcm-u8","pcm-s8","ulaw","alaw"],Me=["aac","opus","mp3","vorbis","flac","ac3","eac3",...De],Ne=[{maxMacroblocks:99,maxBitrate:64e3,maxDpbMbs:396,level:10},{maxMacroblocks:396,maxBitrate:192e3,maxDpbMbs:900,level:11},{maxMacroblocks:396,maxBitrate:384e3,maxDpbMbs:2376,level:12},{maxMacroblocks:396,maxBitrate:768e3,maxDpbMbs:2376,level:13},{maxMacroblocks:396,maxBitrate:2e6,maxDpbMbs:2376,level:20},{maxMacroblocks:792,maxBitrate:4e6,maxDpbMbs:4752,level:21},{maxMacroblocks:1620,maxBitrate:4e6,maxDpbMbs:8100,level:22},{maxMacroblocks:1620,maxBitrate:1e7,maxDpbMbs:8100,level:30},{maxMacroblocks:3600,maxBitrate:14e6,maxDpbMbs:18e3,level:31},{maxMacroblocks:5120,maxBitrate:2e7,maxDpbMbs:20480,level:32},{maxMacroblocks:8192,maxBitrate:2e7,maxDpbMbs:32768,level:40},{maxMacroblocks:8192,maxBitrate:5e7,maxDpbMbs:32768,level:41},{maxMacroblocks:8704,maxBitrate:5e7,maxDpbMbs:34816,level:42},{maxMacroblocks:22080,maxBitrate:135e6,maxDpbMbs:110400,level:50},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:51},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:52},{maxMacroblocks:139264,maxBitrate:24e7,maxDpbMbs:696320,level:60},{maxMacroblocks:139264,maxBitrate:48e7,maxDpbMbs:696320,level:61},{maxMacroblocks:139264,maxBitrate:8e8,maxDpbMbs:696320,level:62}],Oe=[{maxPictureSize:36864,maxBitrate:2e5,level:10},{maxPictureSize:73728,maxBitrate:8e5,level:11},{maxPictureSize:122880,maxBitrate:18e5,level:20},{maxPictureSize:245760,maxBitrate:36e5,level:21},{maxPictureSize:552960,maxBitrate:72e5,level:30},{maxPictureSize:983040,maxBitrate:12e6,level:31},{maxPictureSize:2228224,maxBitrate:18e6,level:40},{maxPictureSize:2228224,maxBitrate:3e7,level:41},{maxPictureSize:8912896,maxBitrate:6e7,level:50},{maxPictureSize:8912896,maxBitrate:12e7,level:51},{maxPictureSize:8912896,maxBitrate:18e7,level:52},{maxPictureSize:35651584,maxBitrate:18e7,level:60},{maxPictureSize:35651584,maxBitrate:24e7,level:61},{maxPictureSize:35651584,maxBitrate:48e7,level:62}],Le=".01.01.01.01.00",ze=".0.110.01.01.01.0",Ue=e=>{const{codec:t,codecDescription:i,colorSpace:r,avcCodecInfo:n,hevcCodecInfo:s,vp9CodecInfo:a,av1CodecInfo:o}=e;if("avc"===t){if(y(null!==e.avcType),n){const t=new Uint8Array([n.avcProfileIndication,n.profileCompatibility,n.avcLevelIndication]);return`avc${e.avcType}.${N(t)}`}if(!i||i.byteLength<4)throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${e.avcType}.${N(i.subarray(1,4))}`}if("hevc"===t){let e,t,r,n,a,o;if(s)e=s.generalProfileSpace,t=s.generalProfileIdc,r=O(s.generalProfileCompatibilityFlags),n=s.generalTierFlag,a=s.generalLevelIdc,o=[...s.generalConstraintIndicatorFlags];else{if(!i||i.byteLength<23)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");const s=P(i),l=s.getUint8(1);e=l>>6&3,t=31&l,r=O(s.getUint32(2)),n=l>>5&1,a=s.getUint8(12),o=[];for(let e=0;e<6;e++)o.push(s.getUint8(6+e))}let l="hev1.";for(l+=["","A","B","C"][e]+t,l+=".",l+=r.toString(16).toUpperCase(),l+=".",l+=0===n?"L":"H",l+=a;o.length>0&&0===o[o.length-1];)o.pop();return o.length>0&&(l+=".",l+=o.map(e=>e.toString(16).toUpperCase()).join(".")),l}if("vp8"===t)return"vp8";if("vp9"===t){if(!a){const t=e.width*e.height;let i=T(Oe).level;for(const e of Oe)if(t<=e.maxPictureSize){i=e.level;break}return`vp09.00.${i.toString().padStart(2,"0")}.08`}let t=`vp09.${a.profile.toString().padStart(2,"0")}.${a.level.toString().padStart(2,"0")}.${a.bitDepth.toString().padStart(2,"0")}.${a.chromaSubsampling.toString().padStart(2,"0")}`;return t+=`.${a.colourPrimaries.toString().padStart(2,"0")}.${a.transferCharacteristics.toString().padStart(2,"0")}.${a.matrixCoefficients.toString().padStart(2,"0")}.${a.videoFullRangeFlag.toString().padStart(2,"0")}`,t.endsWith(Le)&&(t=t.slice(0,-15)),t}if("av1"===t){if(!o){const t=e.width*e.height;let i=T(Oe).level;for(const e of Oe)if(t<=e.maxPictureSize){i=e.level;break}return`av01.0.${i.toString().padStart(2,"0")}M.08`}const t=o.profile,i=o.level.toString().padStart(2,"0"),n=o.tier?"H":"M",s=o.bitDepth.toString().padStart(2,"0"),a=o.monochrome?"1":"0",l=100*o.chromaSubsamplingX+10*o.chromaSubsamplingY+1*(o.chromaSubsamplingX&&o.chromaSubsamplingY?o.chromaSamplePosition:0),c=(null==r?void 0:r.primaries)?C[r.primaries]:1,u=(null==r?void 0:r.transfer)?E[r.transfer]:1,d=(null==r?void 0:r.matrix)?A[r.matrix]:1,h=(null==r?void 0:r.fullRange)?1:0;let f=`av01.${t}.${i}${n}.${s}`;return f+=`.${a}.${l.toString().padStart(3,"0")}`,f+=`.${c.toString().padStart(2,"0")}`,f+=`.${u.toString().padStart(2,"0")}`,f+=`.${d.toString().padStart(2,"0")}`,f+=`.${h}`,f.endsWith(ze)&&(f=f.slice(0,-17)),f}throw new TypeError(`Unhandled codec '${t}'.`)},qe=e=>{const{codec:t,codecDescription:i,aacCodecInfo:r}=e;if("aac"===t){if(!r)throw new TypeError("AAC codec info must be provided.");if(r.isMpeg2)return"mp4a.67";{let e;if(null!==r.objectType)e=r.objectType;else{e=Fe(i).objectType}return`mp4a.40.${e}`}}if("mp3"===t)return"mp3";if("opus"===t)return"opus";if("vorbis"===t)return"vorbis";if("flac"===t)return"flac";if("ac3"===t)return"ac-3";if("eac3"===t)return"ec-3";if(t&&De.includes(t))return t;throw new TypeError(`Unhandled codec '${t}'.`)},We=48e3,Ve=/^pcm-([usf])(\d+)+(be)?$/,He=e=>{if(y(De.includes(e)),"ulaw"===e)return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if("alaw"===e)return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};const t=Ve.exec(e);let i;y(t),i="u"===t[1]?"unsigned":"s"===t[1]?"signed":"float";return{dataType:i,sampleSize:Number(t[2])/8,littleEndian:"be"!==t[3],silentValue:"pcm-u8"===e?o(2,7):0}},Ke=e=>e.startsWith("avc1")||e.startsWith("avc3")?"avc":e.startsWith("hev1")||e.startsWith("hvc1")?"hevc":"vp8"===e?"vp8":e.startsWith("vp09")?"vp9":e.startsWith("av01")?"av1":"mp3"===e||"mp4a.69"===e||"mp4a.6B"===e||"mp4a.6b"===e||"mp4a.40.34"===e?"mp3":e.startsWith("mp4a.40.")||"mp4a.67"===e?"aac":"opus"===e?"opus":"vorbis"===e?"vorbis":"flac"===e?"flac":"ac-3"===e||"ac3"===e?"ac3":"ec-3"===e||"eac3"===e?"eac3":"ulaw"===e?"ulaw":"alaw"===e?"alaw":Ve.test(e)?e:"webvtt"===e?"webvtt":null,je=[44100,48e3,32e3],Xe=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,32,40,48,56,64,80,96,112,128,160,192,224,256,320,-1,-1,32,48,56,64,80,96,112,128,160,192,224,256,320,384,-1,-1,32,64,96,128,160,192,224,256,288,320,352,384,416,448,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1,-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1,-1,32,48,56,64,80,96,112,128,144,160,176,192,224,256,-1],$e=1483304551,Qe=1231971951,Ge=(e,t)=>3===e?3===t?21:36:3===t?13:21,Ye=(e,t)=>{const i=e>>>24,r=e>>>16&255,n=e>>>8&255,s=255&e;if(255!==i&&255!==r&&255!==n&&255!==s)return{header:null,bytesAdvanced:4};if(255!==i)return{header:null,bytesAdvanced:1};if(224!==(224&r))return{header:null,bytesAdvanced:1};let a=0,o=0;16&r?a=8&r?0:1:(a=1,o=1);const l=r>>3&3,c=r>>1&3,u=(n>>2&3)%3,d=s>>6&3,h=s>>4&3,f=s>>3&1,m=s>>2&1,p=3&s,g=Xe[16*a*4+16*c+(n>>4&15)];if(-1===g)return{header:null,bytesAdvanced:1};const k=1e3*g,y=je[u]>>a+o,b=((e,t,i,r,n)=>0===t?0:1===t?Math.floor(144*i/(r<>1&1);if(null!==t&&t{let t=2130706432,i=0;for(;0!==t;)i>>=1,i|=e&t,t>>=8;return i};var Ze,et;(et=Ze||(Ze={}))[et.FrameCount=1]="FrameCount",et[et.FileSize=2]="FileSize",et[et.Toc=4]="Toc";const tt=[48e3,44100,32e3],it=[24e3,22050,16e3];var rt,nt,st,at;(nt=rt||(rt={}))[nt.NON_IDR_SLICE=1]="NON_IDR_SLICE",nt[nt.SLICE_DPA=2]="SLICE_DPA",nt[nt.SLICE_DPB=3]="SLICE_DPB",nt[nt.SLICE_DPC=4]="SLICE_DPC",nt[nt.IDR=5]="IDR",nt[nt.SEI=6]="SEI",nt[nt.SPS=7]="SPS",nt[nt.PPS=8]="PPS",nt[nt.AUD=9]="AUD",nt[nt.SPS_EXT=13]="SPS_EXT",(at=st||(st={}))[at.RASL_N=8]="RASL_N",at[at.RASL_R=9]="RASL_R",at[at.BLA_W_LP=16]="BLA_W_LP",at[at.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",at[at.VPS_NUT=32]="VPS_NUT",at[at.SPS_NUT=33]="SPS_NUT",at[at.PPS_NUT=34]="PPS_NUT",at[at.AUD_NUT=35]="AUD_NUT",at[at.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",at[at.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT";const ot=function*(e){let t=0,i=-1;for(;t=e.length-2)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&w(t.description)[4];return lt(e,i+1)}return ot(e)},ut=e=>31&e,dt=e=>{const t=[],i=e.length;for(let r=0;r{const t=e.reduce((e,t)=>e+ht.byteLength+t.byteLength,0),i=new Uint8Array(t);let r=0;for(const n of e)i.set(ht,r),r+=ht.byteLength,i.set(n,r),r+=n.byteLength;return i},mt=(e,t)=>{const i=e.reduce((e,i)=>e+t+i.byteLength,0),r=new Uint8Array(i);let n=0;for(const s of e){const e=new DataView(r.buffer,r.byteOffset,r.byteLength);switch(t){case 1:e.setUint8(n,s.byteLength);break;case 2:e.setUint16(n,s.byteLength,!1);break;case 3:j(e,n,s.byteLength);break;case 4:e.setUint32(n,s.byteLength,!1)}n+=t,r.set(s,n),n+=s.byteLength}return r},pt=e=>{try{const t=[],i=[],r=[];for(const o of ot(e)){const n=e.subarray(o.offset,o.offset+o.length),s=ut(n[0]);s===rt.SPS?t.push(n):s===rt.PPS?i.push(n):s===rt.SPS_EXT&&r.push(n)}if(0===t.length)return null;if(0===i.length)return null;const n=t[0],s=kt(n);y(null!==s);const a=100===s.profileIdc||110===s.profileIdc||122===s.profileIdc||144===s.profileIdc;return{configurationVersion:1,avcProfileIndication:s.profileIdc,profileCompatibility:s.constraintFlags,avcLevelIndication:s.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:t,pictureParameterSets:i,chromaFormat:a?s.chromaFormatIdc:null,bitDepthLumaMinus8:a?s.bitDepthLumaMinus8:null,bitDepthChromaMinus8:a?s.bitDepthChromaMinus8:null,sequenceParameterSetExt:a?r:null}}catch(t){return console.error("Error building AVC Decoder Configuration Record:",t),null}},gt={1:{num:1,den:1},2:{num:12,den:11},3:{num:10,den:11},4:{num:16,den:11},5:{num:40,den:33},6:{num:24,den:11},7:{num:20,den:11},8:{num:32,den:11},9:{num:80,den:33},10:{num:18,den:11},11:{num:15,den:11},12:{num:64,den:33},13:{num:160,den:99},14:{num:4,den:3},15:{num:3,den:2},16:{num:2,den:1}},kt=e=>{var t;try{const i=new Ee(dt(e));i.skipBits(1),i.skipBits(2);if(7!==i.readBits(5))return null;const r=i.readAlignedByte(),n=i.readAlignedByte(),s=i.readAlignedByte();S(i);let a=1,o=0,l=0,c=0;if(100===r||110===r||122===r||244===r||44===r||83===r||86===r||118===r||128===r){a=S(i),3===a&&(c=i.readBits(1)),o=S(i),l=S(i),i.skipBits(1);if(i.readBits(1))for(let e=0;e<(3!==a?8:12);e++){if(i.readBits(1)){const t=e<6?16:64;let r=8,n=8;for(let e=0;ee.level>=s))?t:T(Ne),n=Math.min(Math.floor(r.maxDpbMbs/(e*i)),16);C=n,B=n}else C=0,B=0}return y(null!==B),{profileIdc:r,constraintFlags:n,levelIdc:s,frameMbsOnlyFlag:k,chromaFormatIdc:a,bitDepthLumaMinus8:o,bitDepthChromaMinus8:l,codedWidth:f,codedHeight:m,displayWidth:p,displayHeight:g,pixelAspectRatio:x,colourPrimaries:b,matrixCoefficients:P,transferCharacteristics:w,fullRangeFlag:I,numReorderFrames:C,maxDecFrameBuffering:B}}catch(i){return console.error("Error parsing AVC SPS:",i),null}},yt=e=>{const t=S(e);e.skipBits(4),e.skipBits(4);for(let i=0;i<=t;i++)S(e),S(e),e.skipBits(1);e.skipBits(5),e.skipBits(5),e.skipBits(5),e.skipBits(5)},bt=(e,t)=>{if(t.description){const i=3&w(t.description)[21];return lt(e,i+1)}return ot(e)},Tt=e=>e>>1&63,St=e=>{try{const t=new Ee(dt(e));t.skipBits(16),t.readBits(4);const i=t.readBits(3),r=t.readBits(1),{general_profile_space:n,general_tier_flag:s,general_profile_idc:a,general_profile_compatibility_flags:o,general_constraint_indicator_flags:l,general_level_idc:c}=wt(t,i);S(t);const u=S(t);let d=0;3===u&&(d=t.readBits(1));const h=S(t),f=S(t);let m=h,p=f;if(t.readBits(1)){const e=S(t),i=S(t),r=S(t),n=S(t);let s=1,a=1;const o=0===d?u:0;1===o?(s=2,a=2):2===o&&(s=2,a=1),m-=(e+i)*s,p-=(r+n)*a}const g=S(t),k=S(t);S(t);const y=t.readBits(1);let b=0;for(let e=y?0:i;e<=i;e++)S(t),b=S(t),S(t);S(t),S(t),S(t),S(t),S(t),S(t),t.readBits(1)&&t.readBits(1)&&Pt(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(4),t.skipBits(4),S(t),S(t),t.skipBits(1));const T=S(t);if(It(t,T),t.readBits(1)){const e=S(t);for(let i=0;i{try{const t=[],i=[],r=[],n=[];for(const l of ot(e)){const s=e.subarray(l.offset,l.offset+l.length),a=Tt(s[0]);a===st.VPS_NUT?t.push(s):a===st.SPS_NUT?i.push(s):a===st.PPS_NUT?r.push(s):a!==st.PREFIX_SEI_NUT&&a!==st.SUFFIX_SEI_NUT||n.push(s)}if(0===i.length||0===r.length)return null;const s=St(i[0]);if(!s)return null;let a=0;if(r.length>0){const e=r[0],t=new Ee(dt(e));t.skipBits(16),S(t),S(t),t.skipBits(1),t.skipBits(1),t.skipBits(3),t.skipBits(1),t.skipBits(1),S(t),S(t),v(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&S(t),v(t),v(t),t.skipBits(1),t.skipBits(1),t.skipBits(1),t.skipBits(1);const i=t.readBits(1),n=t.readBits(1);a=i||n?i&&!n?2:!i&&n?3:0:0}const o=[...t.length?[{arrayCompleteness:1,nalUnitType:st.VPS_NUT,nalUnits:t}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:st.SPS_NUT,nalUnits:i}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:st.PPS_NUT,nalUnits:r}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:Tt(n[0][0]),nalUnits:n}]:[]];return{configurationVersion:1,generalProfileSpace:s.generalProfileSpace,generalTierFlag:s.generalTierFlag,generalProfileIdc:s.generalProfileIdc,generalProfileCompatibilityFlags:s.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:s.generalConstraintIndicatorFlags,generalLevelIdc:s.generalLevelIdc,minSpatialSegmentationIdc:s.minSpatialSegmentationIdc,parallelismType:a,chromaFormatIdc:s.chromaFormatIdc,bitDepthLumaMinus8:s.bitDepthLumaMinus8,bitDepthChromaMinus8:s.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:s.spsMaxSubLayersMinus1+1,temporalIdNested:s.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:o}}catch(t){return console.error("Error building HEVC Decoder Configuration Record:",t),null}},wt=(e,t)=>{const i=e.readBits(2),r=e.readBits(1),n=e.readBits(5);let s=0;for(let u=0;u<32;u++)s=s<<1|e.readBits(1);const a=new Uint8Array(6);for(let u=0;u<6;u++)a[u]=e.readBits(8);const o=e.readBits(8),l=[],c=[];for(let u=0;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&&v(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-(S(e)+1)}else o=t-1;e.readBits(1),S(e);const a=null!=(n=r[o])?n:0;for(let t=0;t<=a;t++){e.readBits(1)||e.readBits(1)}s=r[o]}else{const t=S(e),i=S(e);for(let r=0;r{let i=2,r=2,n=2,s=0,a=0,o={num:1,den:1};if(e.readBits(1)){const t=e.readBits(8);if(255===t)o={num:e.readBits(16),den:e.readBits(16)};else{const e=gt[t];e&&(o=e)}}return e.readBits(1)&&e.readBits(1),e.readBits(1)&&(e.readBits(3),s=e.readBits(1),e.readBits(1)&&(i=e.readBits(8),r=e.readBits(8),n=e.readBits(8))),e.readBits(1)&&(S(e),S(e)),e.readBits(1),e.readBits(1),e.readBits(1),e.readBits(1)&&(S(e),S(e),S(e),S(e)),e.readBits(1)&&(e.readBits(32),e.readBits(32),e.readBits(1)&&S(e),e.readBits(1)&&Bt(e,!0,t)),e.readBits(1)&&(e.readBits(1),e.readBits(1),e.readBits(1),a=S(e),S(e),S(e),S(e),S(e)),{pixelAspectRatio:o,colourPrimaries:i,transferCharacteristics:r,matrixCoefficients:n,fullRangeFlag:s,minSpatialSegmentationIdc:a}},Bt=(e,t,i)=>{let r=!1,n=!1,s=!1;r=1===e.readBits(1),n=1===e.readBits(1),(r||n)&&(s=1===e.readBits(1),s&&(e.readBits(8),e.readBits(5),e.readBits(1),e.readBits(5)),e.readBits(4),e.readBits(4),s&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5));for(let a=0;a<=i;a++){let t=!0;1===e.readBits(1)||(t=1===e.readBits(1));let i=!1;t?S(e):i=1===e.readBits(1);let a=1;if(!i){a=S(e)+1}r&&Et(e,a,s),n&&Et(e,a,s)}},Et=(e,t,i)=>{for(let r=0;r{const i=new Set;let r=_t.audAllowed;for(const s of bt(e,t)){if(r===_t.noMoreDataAllowed){i.add(s.offset);continue}const t=Tt(e[s.offset]);if(r===_t.eoBitstreamAllowed&&37!==t){i.add(s.offset);continue}let n=!1;35===t?r>_t.audAllowed?n=!0:r=_t.beforeFirstVcl:t<=31?r>_t.afterFirstVcl?n=!0:r=_t.afterFirstVcl:36===t?r!==_t.afterFirstVcl?n=!0:r=_t.eoBitstreamAllowed:37===t?r<_t.afterFirstVcl?n=!0:r=_t.noMoreDataAllowed:32===t||33===t||34===t||39===t||t>=41&&t<=44||t>=48&&t<=55?r>_t.beforeFirstVcl?n=!0:r=_t.beforeFirstVcl:(38===t||40===t||t>=45&&t<=47||t>=56&&t<=63)&&r<_t.afterFirstVcl&&(n=!0),n&&i.add(s.offset)}if(0===i.size)return null;const n=[];for(const s of bt(e,t))i.has(s.offset)||n.push(e.subarray(s.offset,s.offset+s.length));return((e,t)=>{if(t.description){const i=3&w(t.description)[21];return mt(e,i+1)}return ft(e)})(n,t)},Rt=e=>{const t=new Ee(e);if(2!==t.readBits(2))return null;const i=t.readBits(1),r=(t.readBits(1)<<1)+i;3===r&&t.skipBits(1);if(1===t.readBits(1))return null;if(0!==t.readBits(1))return null;t.skipBits(2);if(4817730!==t.readBits(24))return null;let n=8;if(r>=2){n=t.readBits(1)?12:10}const s=t.readBits(3);let a=0,o=0;if(7!==s){if(o=t.readBits(1),1===r||3===r){const e=t.readBits(1),i=t.readBits(1);a=e||i?e&&!i?2:1:3,t.skipBits(1)}else a=1}else a=3,o=1;const l=(t.readBits(16)+1)*(t.readBits(16)+1);let c=T(Oe).level;for(const u of Oe)if(l<=u.maxPictureSize){c=u.level;break}return{profile:r,level:c,bitDepth:n,chromaSubsampling:a,videoFullRangeFlag:o,colourPrimaries:2===s?1:1===s?6:2,transferCharacteristics:2===s?1:1===s?6:2,matrixCoefficients:7===s?0:2===s?1:1===s?6:2}},Dt=function*(e){const t=new Ee(e),i=()=>{let e=0;for(let i=0;i<8;i++){const r=t.readAlignedByte();if(e|=(127&r)<<7*i,!(128&r))break;if(7===i&&128&r)return null}return e>=o(2,32)-1?null:e};for(;t.getBitsLeft()>=8;){t.skipBits(1);const r=t.readBits(4),n=t.readBits(1),s=t.readBits(1);let a;if(t.skipBits(1),n&&t.skipBits(8),s){const e=i();if(null===e)return;a=e}else a=Math.floor(t.getBitsLeft()/8);y(t.pos%8===0),yield{type:r,data:e.subarray(t.pos/8,t.pos/8+a)},t.skipBits(8*a)}},Mt=e=>{for(const{type:t,data:i}of Dt(e)){if(1!==t)continue;const e=new Ee(i),r=e.readBits(3);e.readBits(1);const n=e.readBits(1);let s=0,a=0,o=0;if(n)s=e.readBits(5);else{if(e.readBits(1)){e.skipBits(32),e.skipBits(32);if(e.readBits(1))return null}const t=e.readBits(1);t&&(o=e.readBits(5),e.skipBits(32),e.skipBits(5),e.skipBits(5));const i=e.readBits(5);for(let r=0;r<=i;r++){e.skipBits(12);const i=e.readBits(5);if(0===r&&(s=i),i>7){const t=e.readBits(1);0===r&&(a=t)}if(t){if(e.readBits(1)){const t=o+1;e.skipBits(t),e.skipBits(t),e.skipBits(1)}}e.readBits(1)&&e.skipBits(4)}}const l=e.readBits(4),c=e.readBits(4),u=l+1;e.skipBits(u);const d=c+1;e.skipBits(d);let h=0;if(h=n?0:e.readBits(1),h&&(e.skipBits(4),e.skipBits(3)),e.skipBits(1),e.skipBits(1),e.skipBits(1),!n){e.skipBits(1),e.skipBits(1),e.skipBits(1),e.skipBits(1);const t=e.readBits(1);t&&(e.skipBits(1),e.skipBits(1));let i=0;if(i=e.readBits(1)?2:e.readBits(1),i>0){e.readBits(1)||e.skipBits(1)}t&&e.skipBits(3)}e.skipBits(1),e.skipBits(1),e.skipBits(1);const f=e.readBits(1);let m=8;if(2===r&&f){m=e.readBits(1)?12:10}else r<=2&&(m=f?10:8);let p=0;1!==r&&(p=e.readBits(1));let g=1,k=1,y=0;return p||(0===r?(g=1,k=1):1===r?(g=0,k=0):12===m&&(g=e.readBits(1),g&&(k=e.readBits(1))),g&&k&&(y=e.readBits(2))),{profile:r,level:s,tier:a,bitDepth:m,monochrome:p,chromaSubsamplingX:g,chromaSubsamplingY:k,chromaSamplePosition:y}}return null},Nt=[480,960,1920,2880,480,960,1920,2880,480,960,1920,2880,480,960,480,960,120,240,480,960,120,240,480,960,120,240,480,960,120,240,480,960],Ot=e=>{if(e.length<7)throw new Error("Setup header is too short.");if(5!==e[0])throw new Error("Wrong packet type in Setup header.");if("vorbis"!==String.fromCharCode(...e.slice(1,7)))throw new Error("Invalid packet signature in Setup header.");const t=e.length,i=new Uint8Array(t);for(let u=0;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}},Lt=(e,t,i)=>{switch(e){case"avc":for(const e of ct(i,t)){const t=i[e.offset],r=ut(t);if(r>=rt.NON_IDR_SLICE&&r<=rt.SLICE_DPC)return"delta";if(r===rt.IDR)return"key";if(r===rt.SEI&&(!de()||fe()>=144)){const t=i.subarray(e.offset,e.offset+e.length),r=dt(t);let n=1;do{let e=0;for(;;){const t=r[n++];if(void 0===t)break;if(e+=t,t<255)break}let t=0;for(;;){const e=r[n++];if(void 0===e)break;if(t+=e,e<255)break}if(e===6){const e=new Ee(r);e.pos=8*n;const t=S(e),i=e.readBits(1);if(0===t&&1===i)return"key"}n+=t}while(n{var i,r;const n=P(e);let s=0;const a=n.getUint32(s,!0);s+=4;const o=I.decode(e.subarray(s,s+a));s+=a,a>0&&(null!=t.raw||(t.raw={}),null!=(i=t.raw).vendor||(i.vendor=o));const l=n.getUint32(s,!0);s+=4;for(let c=0;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=ge(c),i=P(e),r=i.getUint32(0,!1),n=i.getUint32(4,!1),s=String.fromCharCode(...e.subarray(8,8+n)),a=i.getUint32(8+n,!1),o=I.decode(e.subarray(12+n,12+n+a)),l=i.getUint32(n+a+28),u=e.subarray(n+a+32,n+a+32+l);null!=t.images||(t.images=[]),t.images.push({data:u,mimeType:s,kind:3===r?"coverFront":4===r?"coverBack":"unknown",name:void 0,description:o||void 0})}}}},Wt=[2,1,2,3,3,4,4,5],Vt=e=>{if(e.length<7)return null;if(11!==e[0]||119!==e[1])return null;const t=new Ee(e);t.skipBits(16),t.skipBits(16);const i=t.readBits(2);if(3===i)return null;const r=t.readBits(6),n=t.readBits(5);if(n>8)return null;const s=t.readBits(3),a=t.readBits(3);0!==(1&a)&&1!==a&&t.skipBits(2),0!==(4&a)&&t.skipBits(2),2===a&&t.skipBits(2);return{fscod:i,bsid:n,bsmod:s,acmod:a,lfeon:t.readBits(1),bitRateCode:Math.floor(r/2)}},Ht=[128,138,192,128,140,192,160,174,240,160,176,240,192,208,288,192,210,288,224,242,336,224,244,336,256,278,384,256,280,384,320,348,480,320,350,480,384,416,576,384,418,576,448,486,672,448,488,672,512,556,768,512,558,768,640,696,960,640,698,960,768,834,1152,768,836,1152,896,974,1344,896,976,1344,1024,1114,1536,1024,1116,1536,1280,1392,1920,1280,1394,1920,1536,1670,2304,1536,1672,2304,1792,1950,2688,1792,1952,2688,2048,2228,3072,2048,2230,3072,2304,2506,3456,2304,2508,3456,2560,2786,3840,2560,2788,3840],Kt=[1,2,3,6],jt=e=>{if(e.length<6)return null;if(11!==e[0]||119!==e[1])return null;const t=new Ee(e);t.skipBits(16);const i=t.readBits(2);if(t.skipBits(3),0!==i&&2!==i)return null;const r=t.readBits(11),n=t.readBits(2);let s,a=0;3===n?(a=t.readBits(2),s=3):s=t.readBits(2);const o=t.readBits(3),l=t.readBits(1),c=t.readBits(5);if(c<11||c>16)return null;const u=Kt[s];let d;d=n<3?tt[n]/1e3:it[a]/1e3;return{dataRate:Math.round((r+1)*d/(16*u)),substreams:[{fscod:n,fscod2:a,bsid:c,bsmod:0,acmod:o,lfeon:l,numDepSub:0,chanLoc:0}]}},Xt=e=>{const t=e.substreams[0];return y(t),t.fscod<3?tt[t.fscod]:null!==t.fscod2&&t.fscod2<3?it[t.fscod2]:null},$t=e=>{const t=e.substreams[0];y(t);let i=Wt[t.acmod]+t.lfeon;if(t.numDepSub>0){const e=[2,2,1,1,2,2,2,1,1];for(let r=0;r<9;r++)t.chanLoc&1<<8-r&&(i+=e[r])}return i};class Qt{constructor(e){this.input=e}dispose(){}}const Gt=new Uint8Array(0);class Yt{constructor(e,t,i,r,n=-1,s,a){if(this.data=e,this.type=t,this.timestamp=i,this.duration=r,this.sequenceNumber=n,e===Gt&&void 0===s)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(void 0===s&&(s=e.byteLength),!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if("key"!==t&&"delta"!==t)throw new TypeError('type must be either "key" or "delta".');if(!Number.isFinite(i))throw new TypeError("timestamp must be a number.");if(!Number.isFinite(r)||r<0)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(n))throw new TypeError("sequenceNumber must be a number.");if(!Number.isInteger(s)||s<0)throw new TypeError("byteLength must be a non-negative integer.");if(void 0!==a&&("object"!==typeof a||!a))throw new TypeError("sideData, when provided, must be an object.");if(void 0!==(null==a?void 0:a.alpha)&&!(a.alpha instanceof Uint8Array))throw new TypeError("sideData.alpha, when provided, must be a Uint8Array.");if(void 0!==(null==a?void 0:a.alphaByteLength)&&(!Number.isInteger(a.alphaByteLength)||a.alphaByteLength<0))throw new TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=s,this.sideData=null!=a?a:{},this.sideData.alpha&&void 0===this.sideData.alphaByteLength&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===Gt}get microsecondTimestamp(){return Math.trunc(te*this.timestamp)}get microsecondDuration(){return Math.trunc(te*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if("undefined"===typeof EncodedVideoChunk)throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw new TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if("undefined"===typeof EncodedVideoChunk)throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to an audio chunk.");if("undefined"===typeof EncodedAudioChunk)throw new Error("Your browser does not support EncodedAudioChunk.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(e,t){var i;if(!(e instanceof EncodedVideoChunk||e instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");const r=new Uint8Array(e.byteLength);return e.copyTo(r),new Yt(r,e.type,e.timestamp/1e6,(null!=(i=e.duration)?i:0)/1e6,void 0,void 0,t)}clone(e){var t,i,r,n,s,a;if(void 0!==e&&("object"!==typeof e||null===e))throw new TypeError("options, when provided, must be an object.");if(void 0!==(null==e?void 0:e.data)&&!(e.data instanceof Uint8Array))throw new TypeError("options.data, when provided, must be a Uint8Array.");if(void 0!==(null==e?void 0:e.type)&&"key"!==e.type&&"delta"!==e.type)throw new TypeError('options.type, when provided, must be either "key" or "delta".');if(void 0!==(null==e?void 0:e.timestamp)&&!Number.isFinite(e.timestamp))throw new TypeError("options.timestamp, when provided, must be a number.");if(void 0!==(null==e?void 0:e.duration)&&!Number.isFinite(e.duration))throw new TypeError("options.duration, when provided, must be a number.");if(void 0!==(null==e?void 0:e.sequenceNumber)&&!Number.isFinite(e.sequenceNumber))throw new TypeError("options.sequenceNumber, when provided, must be a number.");if(void 0!==(null==e?void 0:e.sideData)&&("object"!==typeof e.sideData||null===e.sideData))throw new TypeError("options.sideData, when provided, must be an object.");return new Yt(null!=(t=null==e?void 0:e.data)?t:this.data,null!=(i=null==e?void 0:e.type)?i:this.type,null!=(r=null==e?void 0:e.timestamp)?r:this.timestamp,null!=(n=null==e?void 0:e.duration)?n:this.duration,null!=(s=null==e?void 0:e.sequenceNumber)?s:this.sequenceNumber,this.byteLength,null!=(a=null==e?void 0:e.sideData)?a:this.sideData)}}const Jt=e=>{const t=P(e);let i=0;const r=t.getUint8(i);i+=1,i+=3;const n=N(e.subarray(i,i+16));i+=16;let s=null;if(r>0){const r=t.getUint32(i);if(i+=4,r>0){s=[];for(let t=0;te.systemId===t.systemId&&((e,t)=>{if(e.length!==t.length)return!1;for(let i=0;i{let t=Ra(e);const i=Wa(e,4);let r=8;1===t&&(t=Oa(e),r=16);const n=t-r;return n<0?null:{name:i,totalSize:t,headerSize:r,contentSize:n}},ti=e=>Ma(e)/65536,ii=e=>Ma(e)/1073741824,ri=e=>{let t=0;for(let i=0;i<4;i++){t<<=7;const i=Ca(e);if(t|=127&i,0===(128&i))break}return t},ni=e=>{let t=Ea(e);return e.skip(2),t=Math.min(t,e.remainingLength),I.decode(xa(e,t))},si=e=>{const t=ei(e);if(!t||"data"!==t.name)return null;if(e.remainingLength<8)return null;const i=Ra(e);e.skip(4);const r=xa(e,t.contentSize-8);switch(i){case 1:return I.decode(r);case 2:return new TextDecoder("utf-16be").decode(r);case 13:return new xe(r,"image/jpeg");case 14:return new xe(r,"image/png");case 27:return new xe(r,"image/bmp");default:return r}},ai=16,oi=new Uint32Array(256),li=new Uint32Array(256),ci=new Uint32Array(256),ui=new Uint32Array(256),di=new Uint32Array(256),hi=new Uint32Array(256),fi=new Uint32Array(10);let mi=!1;class pi{constructor(){this.roundkey=new Uint32Array(44),this.iv=new Uint32Array(ai/Uint32Array.BYTES_PER_ELEMENT),this.in=new Uint8Array(ai),this.out=new Uint8Array(ai),this.inView=new DataView(this.in.buffer),this.outView=new DataView(this.out.buffer)}init({key:e,iv:t}){y(16===e.byteLength),y(16===t.byteLength),mi||(()=>{const e=new Uint8Array(256),t=new Uint8Array(256),i=new Uint8Array(256);for(let s=0,a=1;s<256;s++)i[s]=a,t[a]=s,a=a^a<<1^(128&a?283:0);const r=(e,r)=>e&&r?i[(t[e]+t[r])%255]:0;e[0]=99;for(let s=1;s<256;s++){const r=i[255-t[s]];let n=r^r<<1^r<<2^r<<3^r<<4;n=n>>>8^255&n^99,e[s]=n}for(let s=0;s<256;s++){const t=e[s],i=e.indexOf(s);oi[s]=t<<24|t<<16|t<<8|t,hi[s]=i<<24|i<<16|i<<8|i;const n=r(i,14)<<24|r(i,9)<<16|r(i,13)<<8|r(i,11);li[s]=n,ci[s]=n>>>8|n<<24,ui[s]=n>>>16|n<<16,di[s]=n>>>24|n<<8}let n=1;for(let s=0;s<10;s++)fi[s]=n<<24,n=n<<1^(128&n?283:0);mi=!0})();const i=new DataView(e.buffer,e.byteOffset,e.byteLength),r=new DataView(t.buffer,t.byteOffset,t.byteLength);this.roundkey[0]=i.getUint32(0,!1),this.roundkey[1]=i.getUint32(4,!1),this.roundkey[2]=i.getUint32(8,!1),this.roundkey[3]=i.getUint32(12,!1),this.iv[0]=r.getUint32(0,!1),this.iv[1]=r.getUint32(4,!1),this.iv[2]=r.getUint32(8,!1),this.iv[3]=r.getUint32(12,!1);for(let n=4;n<44;n+=4){const e=this.roundkey[n-1];this.roundkey[n]=this.roundkey[n-4]^4278190080&oi[e>>>16&255]^16711680&oi[e>>>8&255]^65280&oi[e>>>0&255]^255&oi[e>>>24&255]^fi[n/4-1],this.roundkey[n+1]=this.roundkey[n-3]^this.roundkey[n],this.roundkey[n+2]=this.roundkey[n-2]^this.roundkey[n+1],this.roundkey[n+3]=this.roundkey[n-1]^this.roundkey[n+2]}for(let n=0,s=40;n>>24&255]]^ci[255&oi[t>>>16&255]]^ui[255&oi[t>>>8&255]]^di[255&oi[t>>>0&255]]}}decrypt(){let e=this.inView.getUint32(0,!1)^this.roundkey[0],t=this.inView.getUint32(4,!1)^this.roundkey[1],i=this.inView.getUint32(8,!1)^this.roundkey[2],r=this.inView.getUint32(12,!1)^this.roundkey[3];const n=this.inView.getUint32(0,!1),s=this.inView.getUint32(4,!1),a=this.inView.getUint32(8,!1),o=this.inView.getUint32(12,!1);let l,c,u,d;for(let g=1;g<10;g++){const n=4*g;l=li[e>>>24]^ci[r>>>16&255]^ui[i>>>8&255]^di[255&t]^this.roundkey[n],c=li[t>>>24]^ci[e>>>16&255]^ui[r>>>8&255]^di[255&i]^this.roundkey[n+1],u=li[i>>>24]^ci[t>>>16&255]^ui[e>>>8&255]^di[255&r]^this.roundkey[n+2],d=li[r>>>24]^ci[i>>>16&255]^ui[t>>>8&255]^di[255&e]^this.roundkey[n+3],e=l,t=c,i=u,r=d}const h=4278190080&hi[e>>>24&255]^16711680&hi[r>>>16&255]^65280&hi[i>>>8&255]^255&hi[t>>>0&255]^this.roundkey[40],f=4278190080&hi[t>>>24&255]^16711680&hi[e>>>16&255]^65280&hi[r>>>8&255]^255&hi[i>>>0&255]^this.roundkey[41],m=4278190080&hi[i>>>24&255]^16711680&hi[t>>>16&255]^65280&hi[e>>>8&255]^255&hi[r>>>0&255]^this.roundkey[42],p=4278190080&hi[r>>>24&255]^16711680&hi[i>>>16&255]^65280&hi[t>>>8&255]^255&hi[e>>>0&255]^this.roundkey[43];this.outView.setUint32(0,h^this.iv[0],!1),this.outView.setUint32(4,f^this.iv[1],!1),this.outView.setUint32(8,m^this.iv[2],!1),this.outView.setUint32(12,p^this.iv[3],!1),this.iv[0]=n,this.iv[1]=s,this.iv[2]=a,this.iv[3]=o}}class gi extends Qt{constructor(e){super(e),this.moovSlice=null,this.currentTrack=null,this.tracks=[],this.metadataPromise=null,this.movieTimescale=-1,this.movieDurationInTimescale=-1,this.isQuickTime=!1,this.metadataTags={},this.currentMetadataKeys=null,this.isFragmented=!1,this.fragmentTrackDefaults=[],this.psshBoxes=[],this.currentFragment=null,this.lastReadFragment=null,this.decryptionKeyCache=new Map,this.reader=e._reader}getTrackBackings(){return d(this,null,function*(){return yield this.readMetadata(),this.tracks.map(e=>e.trackBacking)})}getMimeType(){return d(this,null,function*(){yield this.readMetadata();const e=yield this.getTrackBackings(),t=yield Promise.all(e.map(e=>e.getDecoderConfig().then(e=>{var t;return null!=(t=null==e?void 0:e.codec)?t:null})));return(e=>{let t=(e.hasVideo?"video/":e.hasAudio?"audio/":"application/")+(e.isQuickTime?"quicktime":"mp4");e.codecStrings.length>0&&(t+=`; codecs="${[...new Set(e.codecStrings)].join(", ")}"`);return t})({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some(e=>{var t;return"video"===(null==(t=e.info)?void 0:t.type)}),hasAudio:this.tracks.some(e=>{var t;return"audio"===(null==(t=e.info)?void 0:t.type)}),codecStrings:t.filter(Boolean)})})}getMetadataTags(){return d(this,null,function*(){return yield this.readMetadata(),this.metadataTags})}readMetadata(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>d(this,null,function*(){let e=0,t=!1;for(;;){let i=this.reader.requestSliceRange(e,8,16);if(i instanceof Promise&&(i=yield i),!i)break;const r=e,n=ei(i);if(!n)break;if("ftyp"===n.name||"styp"===n.name){const e=Wa(i,4);this.isQuickTime="qt "===e}else{if("moov"===n.name){let e=this.reader.requestSlice(i.filePos,n.contentSize);if(e instanceof Promise&&(e=yield e),!e)break;this.moovSlice=e,this.readContiguousBoxes(this.moovSlice);for(const t of this.tracks){const e=t.editListPreviousSegmentDurations/this.movieTimescale;t.editListOffset-=Math.round(e*t.timescale)}t=this.isFragmented&&null!==this.reader.fileSize&&this.reader.fileSize>r+n.totalSize;break}if("moof"===n.name){if(!this.input._initInput)throw new Error('"moof" box encountered with no "moov" box present; this file is likely a Segment as described in ISO/IEC 14496-12 Section 8.16. A separate init file that contains a "moov" box is required to read this file, please provide it using InputOptions.initInput.');const e=yield this.input._initInput._getDemuxer();if(e.constructor!==gi)throw new Error("Init input must match the input's format.");yield e.readMetadata(),this.movieTimescale=e.movieTimescale,this.movieDurationInTimescale=e.movieDurationInTimescale,this.metadataTags=e.metadataTags,this.isFragmented=!0,this.fragmentTrackDefaults=e.fragmentTrackDefaults,this.psshBoxes=e.psshBoxes;for(const t of e.tracks){const e={id:t.id,demuxer:this,trackBacking:null,disposition:t.disposition,timescale:t.timescale,durationInMediaTimescale:t.durationInMediaTimescale,durationInMovieTimescale:t.durationInMovieTimescale,rotation:t.rotation,internalCodecId:t.internalCodecId,name:t.name,languageCode:t.languageCode,sampleTableByteOffset:null,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:t.editListPreviousSegmentDurations,editListOffset:t.editListOffset,encryptionInfo:t.encryptionInfo,encryptionAuxInfo:null,frmaCodecString:null,info:t.info};if(t.trackBacking)if(y(e.info),"video"===e.info.type&&-1!==e.info.width){const t=e;e.trackBacking=new yi(t),this.tracks.push(e)}else if("audio"===e.info.type&&-1!==e.info.numberOfChannels){const t=e;e.trackBacking=new bi(t),this.tracks.push(e)}}t=!1;break}}e=r+n.totalSize}if(t){y(null!==this.reader.fileSize);let e=this.reader.requestSlice(this.reader.fileSize-4,4);e instanceof Promise&&(e=yield e),y(e);const t=Ra(e),i=this.reader.fileSize-t;if(i>=0&&i<=this.reader.fileSize-16){let e=this.reader.requestSliceRange(i,8,16);if(e instanceof Promise&&(e=yield e),e){const t=ei(e);if(t&&"mfra"===t.name){let i=this.reader.requestSlice(e.filePos,t.contentSize);i instanceof Promise&&(i=yield i),i&&this.readContiguousBoxes(i)}}}}}))()}getSampleTableForTrack(e){var t,i;if(e.sampleTable)return e.sampleTable;const r={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};if(e.sampleTable=r,null===e.sampleTableByteOffset)return r;y(this.moovSlice);const n=this.moovSlice.slice(e.sampleTableByteOffset);this.currentTrack=e,this.traverseBox(n),this.currentTrack=null;if("audio"===(null==(t=e.info)?void 0:t.type)&&e.info.codec&&De.includes(e.info.codec)&&0===r.sampleCompositionTimeOffsets.length){y("audio"===(null==(i=e.info)?void 0:i.type));const t=He(e.info.codec),n=[],s=[];for(let i=0;ie.startIndex),u=r.sampleTimingEntries[c],d=z(r.sampleTimingEntries,l,e=>e.startIndex),h=r.sampleTimingEntries[d],f=u.startDecodeTimestamp+(o-u.startIndex)*u.delta,m=h.startDecodeTimestamp+(l-h.startIndex)*h.delta-f,p=T(n);p&&p.delta===m?p.count++:n.push({startIndex:a.startChunkIndex+i,startDecodeTimestamp:f,count:1,delta:m});const g=a.samplesPerChunk*t.sampleSize*e.info.numberOfChannels;s.push(g)}a.startSampleIndex=a.startChunkIndex,a.samplesPerChunk=1}r.sampleTimingEntries=n,r.sampleSizes=s}if(r.sampleCompositionTimeOffsets.length>0){r.presentationTimestamps=[];for(const e of r.sampleTimingEntries)for(let t=0;te.presentationTimestamp-t.presentationTimestamp),r.presentationTimestampIndexMap=Array(r.presentationTimestamps.length).fill(-1);for(let e=0;ee.moofOffset===s.moofOffset);if(r)Pi(e,r.timestamp);else{const t=z(i,s.moofOffset-1,e=>e.moofOffset);if(-1!==t){const r=i[t];Pi(e,r.endTimestamp)}}e.startTimestampIsFinal=!0}const r=z(i,e.startTimestamp,e=>e.startTimestamp);if(-1!==r&&i[r].moofOffset===s.moofOffset||i.splice(r+1,0,{moofOffset:s.moofOffset,startTimestamp:e.startTimestamp,endTimestamp:e.endTimestamp}),e.encryptionAuxInfo&&t.encryptionInfo){const i=yield Bi(this.reader,t.encryptionInfo,e.encryptionAuxInfo);for(let t=0;t0){t.languageCode="";for(let e=0;e<3;e++)t.languageCode=String.fromCharCode(96+(31&r))+t.languageCode,r>>=5;ee(t.languageCode)||(t.languageCode=Q)}}break;case"hdlr":{const t=this.currentTrack;if(!t)break;e.skip(8);const i=Wa(e,4);"vide"===i?t.info={type:"video",width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:null,avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null}:"soun"===i&&(t.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null,pcmLittleEndian:!1,pcmSampleSize:null})}break;case"stbl":{const t=this.currentTrack;if(!t)break;t.sampleTableByteOffset=ce,this.readContiguousBoxes(e.slice(de,ue.contentSize))}break;case"stsd":{const t=this.currentTrack;if(!t)break;if(null===t.info||t.sampleTable)break;const i=Ca(e);e.skip(3);const r=Ra(e);for(let n=0;n0&&(1===a?(e.skip(4),l=8*Ra(e),e.skip(8)):2===a&&(e.skip(4),c=qa(e),o=Ra(e),e.skip(4),l=Ra(e),u=Ra(e),e.skip(8))),t.info.numberOfChannels=o,t.info.sampleRate=c,t.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,r+n.totalSize-e.filePos));const d="enca"===s?t.frmaCodecString:s;if(t.frmaCodecString=null,"mp4a"===d);else if("opus"===d)t.info.codec="opus",t.info.sampleRate=We;else if("flac"===d)t.info.codec="flac";else if("ulaw"===d)t.info.codec="ulaw";else if("alaw"===d)t.info.codec="alaw";else if("ac-3"===d)t.info.codec="ac3";else if("ec-3"===d)t.info.codec="eac3";else if("twos"===d)8===l?t.info.codec="pcm-s8":16===l?t.info.codec=t.info.pcmLittleEndian?"pcm-s16":"pcm-s16be":(console.warn(`Unsupported sample size ${l} for codec 'twos'.`),t.info.codec=null);else if("sowt"===d)8===l?t.info.codec="pcm-s8":16===l?t.info.codec="pcm-s16":(console.warn(`Unsupported sample size ${l} for codec 'sowt'.`),t.info.codec=null);else if("raw "===d)t.info.codec="pcm-u8";else if("in24"===d)t.info.codec=t.info.pcmLittleEndian?"pcm-s24":"pcm-s24be";else if("in32"===d)t.info.codec=t.info.pcmLittleEndian?"pcm-s32":"pcm-s32be";else if("fl32"===d)t.info.codec=t.info.pcmLittleEndian?"pcm-f32":"pcm-f32be";else if("fl64"===d)t.info.codec=t.info.pcmLittleEndian?"pcm-f64":"pcm-f64be";else if("ipcm"===d){const e=t.info.pcmSampleSize;t.info.pcmLittleEndian?16===e?t.info.codec="pcm-s16":24===e?t.info.codec="pcm-s24":32===e?t.info.codec="pcm-s32":(console.warn(`Invalid ipcm sample size ${e}.`),t.info.codec=null):16===e?t.info.codec="pcm-s16be":24===e?t.info.codec="pcm-s24be":32===e?t.info.codec="pcm-s32be":(console.warn(`Invalid ipcm sample size ${e}.`),t.info.codec=null)}else if("fpcm"===d){const e=t.info.pcmSampleSize;t.info.pcmLittleEndian?32===e?t.info.codec="pcm-f32":64===e?t.info.codec="pcm-f64":(console.warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null):32===e?t.info.codec="pcm-f32be":64===e?t.info.codec="pcm-f64be":(console.warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null)}else if("lpcm"===d&&null!==u){const e=l+7>>3,i=Boolean(1&u),r=Boolean(2&u),n=4&u?-1:0;l>0&&l<=64&&(i?32===l&&(t.info.codec=r?"pcm-f32be":"pcm-f32"):n&1<0?(t.encryptionInfo.defaultCryptByteBlock=r>>4,t.encryptionInfo.defaultSkipByteBlock=15&r):(t.encryptionInfo.defaultCryptByteBlock=0,t.encryptionInfo.defaultSkipByteBlock=0),t.encryptionInfo.defaultIsProtected=0!==Ca(e),t.encryptionInfo.defaultPerSampleIvSize=Ca(e),t.encryptionInfo.defaultKid=N(xa(e,16)),t.encryptionInfo.defaultIsProtected&&0===t.encryptionInfo.defaultPerSampleIvSize){const i=Ca(e),r=new Uint8Array(16);r.set(xa(e,i),0),t.encryptionInfo.defaultConstantIv=r}}break;case"avcC":{const t=this.currentTrack;if(!t)break;y(t.info),t.info.codecDescription=xa(e,ue.contentSize)}break;case"hvcC":{const t=this.currentTrack;if(!t)break;y(t.info),t.info.codecDescription=xa(e,ue.contentSize)}break;case"vpcC":{const i=this.currentTrack;if(!i)break;y("video"===(null==(t=i.info)?void 0:t.type)),e.skip(4);const r=Ca(e),n=Ca(e),s=Ca(e),a=s>>4,o=s>>1&7,l=1&s,c=Ca(e),u=Ca(e),d=Ca(e);i.info.vp9CodecInfo={profile:r,level:n,bitDepth:a,chromaSubsampling:o,videoFullRangeFlag:l,colourPrimaries:c,transferCharacteristics:u,matrixCoefficients:d}}break;case"av1C":{const t=this.currentTrack;if(!t)break;y("video"===(null==(i=t.info)?void 0:i.type)),e.skip(1);const r=Ca(e),n=r>>5,s=31&r,a=Ca(e),o=a>>7,l=a>>6&1,c=a>>4&1,u=a>>3&1,d=a>>2&1,h=3&a,f=2===n&&l?a>>5&1?12:10:l?10:8;t.info.av1CodecInfo={profile:n,level:s,tier:o,bitDepth:f,monochrome:c,chromaSubsamplingX:u,chromaSubsamplingY:d,chromaSamplePosition:h}}break;case"colr":{const t=this.currentTrack;if(!t)break;y("video"===(null==(r=t.info)?void 0:r.type));if("nclx"!==Wa(e,4))break;const i=Ea(e),n=Ea(e),s=Ea(e),a=Boolean(128&Ca(e));t.info.colorSpace={primaries:B[i],transfer:_[n],matrix:F[s],fullRange:a}}break;case"pasp":{const t=this.currentTrack;if(!t)break;y("video"===(null==(n=t.info)?void 0:n.type));const i=Ra(e),r=Ra(e);i>0&&r>0&&(i>r?t.info.squarePixelWidth=Math.round(t.info.width*i/r):t.info.squarePixelHeight=Math.round(t.info.height*r/i))}break;case"esds":{const t=this.currentTrack;if(!t)break;y("audio"===(null==(s=t.info)?void 0:s.type)),e.skip(4);y(3===Ca(e)),ri(e),e.skip(2);const i=Ca(e),r=0!==(64&i),n=0!==(32&i);if(0!==(128&i)&&e.skip(2),r){const t=Ca(e);e.skip(t)}n&&e.skip(2);y(4===Ca(e));const a=ri(e),o=e.filePos,l=Ca(e);if(64===l||103===l?(t.info.codec="aac",t.info.aacCodecInfo={isMpeg2:103===l,objectType:null}):105===l||107===l?t.info.codec="mp3":221===l?t.info.codec="vorbis":console.warn(`Unsupported audio codec (objectTypeIndication ${l}) - discarding track.`),e.skip(12),a>e.filePos-o){y(5===Ca(e));const i=ri(e);if(t.info.codecDescription=xa(e,i),"aac"===t.info.codec){const e=Fe(t.info.codecDescription);null!==e.numberOfChannels&&(t.info.numberOfChannels=e.numberOfChannels),null!==e.sampleRate&&(t.info.sampleRate=e.sampleRate)}}}break;case"enda":{const t=this.currentTrack;if(!t)break;y("audio"===(null==(a=t.info)?void 0:a.type)),t.info.pcmLittleEndian=!!(255&Ea(e))}break;case"pcmC":{const t=this.currentTrack;if(!t)break;y("audio"===(null==(o=t.info)?void 0:o.type)),e.skip(4);const i=Ca(e);t.info.pcmLittleEndian=Boolean(1&i),t.info.pcmSampleSize=Ca(e)}break;case"dOps":{const t=this.currentTrack;if(!t)break;y("audio"===(null==(l=t.info)?void 0:l.type)),e.skip(1);const i=Ca(e),r=Ea(e),n=Ra(e),s=Aa(e),a=Ca(e);let o;o=0!==a?xa(e,2+i):new Uint8Array(0);const c=new Uint8Array(19+o.byteLength),u=new DataView(c.buffer);u.setUint32(0,1332770163,!1),u.setUint32(4,1214603620,!1),u.setUint8(8,1),u.setUint8(9,i),u.setUint16(10,r,!0),u.setUint32(12,n,!0),u.setInt16(16,s,!0),u.setUint8(18,a),c.set(o,19),t.info.codecDescription=c,t.info.numberOfChannels=i}break;case"dfLa":{const t=this.currentTrack;if(!t)break;y("audio"===(null==(d=t.info)?void 0:d.type)),e.skip(4);const i=127,r=128,n=e.filePos;for(;e.filePos>>12,n=1+(i>>9&7);t.info.sampleRate=r,t.info.numberOfChannels=n,e.skip(20)}else e.skip(s);if(n&r)break}const s=e.filePos;e.filePos=n;const a=xa(e,s-n),o=new Uint8Array(4+a.byteLength);new DataView(o.buffer).setUint32(0,1716281667,!1),o.set(a,4),t.info.codecDescription=o}break;case"dac3":{const t=this.currentTrack;if(!t)break;y("audio"===(null==(h=t.info)?void 0:h.type));const i=xa(e,3),r=new Ee(i),n=r.readBits(2);r.skipBits(8);const s=r.readBits(3),a=r.readBits(1);n<3&&(t.info.sampleRate=tt[n]),t.info.numberOfChannels=Wt[s]+a}break;case"dec3":{const t=this.currentTrack;if(!t)break;y("audio"===(null==(f=t.info)?void 0:f.type));const i=(e=>{if(e.length<2)return null;const t=new Ee(e),i=t.readBits(13),r=t.readBits(3),n=[];for(let s=0;s<=r&&!(Math.ceil(t.pos/8)+3>e.length);s++){const e=t.readBits(2),i=t.readBits(5);t.skipBits(1),t.skipBits(1);const r=t.readBits(3),s=t.readBits(3),a=t.readBits(1);t.skipBits(3);const o=t.readBits(4);let l=0;o>0?l=t.readBits(9):t.skipBits(1),n.push({fscod:e,fscod2:null,bsid:i,bsmod:r,acmod:s,lfeon:a,numDepSub:o,chanLoc:l})}return 0===n.length?null:{dataRate:i,substreams:n}})(xa(e,ue.contentSize));if(!i){console.warn("Invalid dec3 box contents, ignoring.");break}const r=Xt(i);null!==r&&(t.info.sampleRate=r),t.info.numberOfChannels=$t(i)}break;case"stts":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4);const i=Ra(e);let r=0,n=0;for(let s=0;se.id===i);if(!r)break;const n=Ra(e),s=(12&n)>>2,a=3&n,o=[Ca,Ea,_a,Ra],l=o[(48&n)>>4],c=o[s],u=o[a],d=Ra(e);for(let h=0;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!=(p=null==d?void 0:d.defaultSampleDescriptionIndex)?p:null,defaultSampleDuration:null!=(g=null==d?void 0:d.defaultSampleDuration)?g:null,defaultSampleSize:null!=(k=null==d?void 0:d.defaultSampleSize)?k:null,defaultSampleFlags:null!=(S=null==d?void 0:d.defaultSampleFlags)?S:null,startTimestamp:null,encryptionAuxInfo:null},i?u.currentFragmentState.baseDataOffset=Oa(e):l&&(u.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),r&&(u.currentFragmentState.sampleDescriptionIndex=Ra(e)),n&&(u.currentFragmentState.defaultSampleDuration=Ra(e)),s&&(u.currentFragmentState.defaultSampleSize=Ra(e)),a&&(u.currentFragmentState.defaultSampleFlags=Ra(e)),o&&(u.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{const t=this.currentTrack;if(!t)break;y(t.currentFragmentState);const i=Ca(e);e.skip(3);const r=0===i?Ra(e):Oa(e);t.currentFragmentState.startTimestamp=r}break;case"trun":{const t=this.currentTrack;if(!t)break;y(this.currentFragment),y(t.currentFragmentState);const i=Ca(e),r=_a(e),n=Boolean(1&r),s=Boolean(4&r),a=Boolean(256&r),o=Boolean(512&r),l=Boolean(1024&r),c=Boolean(2048&r),u=Ra(e);let d=null;n&&(d=Ma(e));let h,f=null;if(s&&(f=Ra(e)),this.currentFragment.trackData.has(t.id)?(h=this.currentFragment.trackData.get(t.id),null!==d&&(h.currentOffset=t.currentFragmentState.baseDataOffset+d)):(h={track:t,currentTimestamp:0,currentOffset:t.currentFragmentState.baseDataOffset+(null!=d?d:0),startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1,encryptionAuxInfo:null},this.currentFragment.trackData.set(t.id,h)),0===u){this.currentFragment.implicitBaseDataOffset=h.currentOffset;break}for(let m=0;m0&&(n=xa(e,r));const s=Ci(t);s.defaultSampleInfoSize=i,s.sampleSizes=n,s.sampleCount=r}break;case"saio":{const t=this.currentTrack;if(!t||!t.encryptionInfo)break;const i=Ca(e);if(1&_a(e)){const i=Wa(e,4),r=Ra(e);if(i!==t.encryptionInfo.scheme||0!==r)break}const r=Ra(e);if(0===r)break;r>1&&console.warn("Multiple saio entries are not supported; using the first offset only.");let n=0===i?Ra(e):Number(Oa(e));this.currentFragment&&(n+=this.currentFragment.moofOffset);Ci(t).offset=n}break;case"senc":{const t=this.currentTrack;if(!t||!t.encryptionInfo)break;y(this.currentFragment);const i=this.currentFragment.trackData.get(t.id);if(!i)break;e.skip(1);const r=_a(e),n=Boolean(2&r),s=Ra(e),a=t.encryptionInfo.defaultPerSampleIvSize;y(null!==a);for(let o=0;o0?r.set(xa(e,a),0):r.set(t.encryptionInfo.defaultConstantIv,0);let s=null;if(n){const t=Ea(e);s=[];for(let i=0;i0&&(null!=(re=this.metadataTags).trackNumber||(re.trackNumber=t)),i&&Number.isInteger(i)&&i>0&&(null!=(ne=this.metadataTags).tracksTotal||(ne.tracksTotal=i))}break;case"trkn":if(n instanceof Uint8Array&&n.length>=6){const e=P(n),t=e.getUint16(2,!1),i=e.getUint16(4,!1);t>0&&(null!=(se=this.metadataTags).trackNumber||(se.trackNumber=t)),i>0&&(null!=(ae=this.metadataTags).tracksTotal||(ae.tracksTotal=i))}break;case"disc":case"disk":if(n instanceof Uint8Array&&n.length>=6){const e=P(n),t=e.getUint16(2,!1),i=e.getUint16(4,!1);t>0&&(null!=(oe=this.metadataTags).discNumber||(oe.discNumber=t)),i>0&&(null!=(le=this.metadataTags).discsTotal||(le.discsTotal=i))}}}}}var fe,me;return e.filePos=he,!0}}class ki{constructor(e){this.internalTrack=e,this.packetToSampleIndex=new WeakMap,this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){const e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType();let i=0;for(const r of e.tracks)if(r.trackBacking.getType()===t&&i++,r===this.internalTrack)break;return i}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.internalCodecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}isRelativeToUnixEpoch(){return!1}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return d(this,null,function*(){var e;const t=this.internalTrack;if(t.durationInMediaTimescale<=0)return null;y(t.trackBacking);const i=yield t.trackBacking.getFirstPacket({metadataOnly:!0});return(null!=(e=null==i?void 0:i.timestamp)?e:0)+t.durationInMediaTimescale/t.timescale})}getLiveRefreshInterval(){return d(this,null,function*(){return null})}getFirstPacket(e){return d(this,null,function*(){const t=yield this.fetchPacketForSampleIndex(0,e);return t||!this.internalTrack.demuxer.isFragmented?t:this.performFragmentedLookup(null,e=>e.trackData.get(this.internalTrack.id)?{sampleIndex:0,correctSampleFound:!0}:{sampleIndex:-1,correctSampleFound:!1},-1/0,1/0,e)})}mapTimestampIntoTimescale(e){return G(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}getPacket(e,t){return d(this,null,function*(){const i=this.mapTimestampIntoTimescale(e),r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),n=Ti(r,i),s=yield this.fetchPacketForSampleIndex(n,t);return xi(r)&&this.internalTrack.demuxer.isFragmented?this.performFragmentedLookup(null,e=>{const t=e.trackData.get(this.internalTrack.id);if(!t)return{sampleIndex:-1,correctSampleFound:!1};const r=z(t.presentationTimestamps,i,e=>e.presentationTimestamp);return{sampleIndex:-1!==r?t.presentationTimestamps[r].sampleIndex:-1,correctSampleFound:-1!==r&&i{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=V(t.presentationTimestamps,e=>t.samples[e.sampleIndex].isKeyFrame&&e.presentationTimestamp<=i);return{sampleIndex:-1!==r?t.presentationTimestamps[r].sampleIndex:-1,correctSampleFound:-1!==r&&i{if(e===r.fragment){const t=e.trackData.get(this.internalTrack.id).samples.findIndex((e,t)=>e.isKeyFrame&&t>r.sampleIndex);if(-1!==t)return{sampleIndex:t,correctSampleFound:!0}}else{const t=e.trackData.get(this.internalTrack.id);if(t&&null!==t.firstKeyFrameTimestamp){const e=t.samples.findIndex(e=>e.isKeyFrame);return y(-1!==e),{sampleIndex:e,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)})}fetchPacketForSampleIndex(e,t){return d(this,null,function*(){if(-1===e)return null;const i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),r=vi(i,e);if(!r)return null;let n;if(t.metadataOnly)n=Gt;else{let t=this.internalTrack.demuxer.reader.requestSlice(r.sampleOffset,r.sampleSize);if(t instanceof Promise&&(t=yield t),!t)return null;if(n=xa(t,r.sampleSize),this.internalTrack.encryptionAuxInfo){y(this.internalTrack.encryptionInfo);const t=yield Bi(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);ee.timestamp),f=-1!==h?this.internalTrack.fragmentLookupTable[h]:null,m=z(this.internalTrack.fragmentPositionCache,i,e=>e.startTimestamp),p=-1!==m?this.internalTrack.fragmentPositionCache[m]:null,g=Math.max(null!=(s=null==f?void 0:f.moofOffset)?s:0,null!=(a=null==p?void 0:p.moofOffset)?a:0)||null;let k;for(e?null===g||e.moofOffset>=g?(k=e.moofOffset+e.moofSize,c=e):k=g:k=null!=g?g:0;;){if(c){const e=c.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>r)break}let e=l.reader.requestSliceRange(k,8,16);if(e instanceof Promise&&(e=yield e),!e)break;const i=k,s=ei(e);if(!s)break;if("moof"===s.name){c=yield l.readFragment(i);const{sampleIndex:e,correctSampleFound:r}=t(c);if(r)return this.fetchPacketInFragment(c,e,n);-1!==e&&(u=c,d=e)}k=i+s.totalSize}if(f&&(!u||u.moofOffsetd(this,null,function*(){var e,t;if("vp9"!==this.internalTrack.info.codec||this.internalTrack.info.vp9CodecInfo){if("av1"===this.internalTrack.info.codec&&!this.internalTrack.info.av1CodecInfo){const e=yield this.getFirstPacket({});this.internalTrack.info.av1CodecInfo=e&&Mt(e.data)}}else{const e=yield this.getFirstPacket({});this.internalTrack.info.vp9CodecInfo=e&&Rt(e.data)}const i={codec:Ue(this.internalTrack.info),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:null!=(e=this.internalTrack.info.codecDescription)?e:void 0,colorSpace:null!=(t=this.internalTrack.info.colorSpace)?t:void 0};return this.internalTrack.info.width===this.internalTrack.info.squarePixelWidth&&this.internalTrack.info.height===this.internalTrack.info.squarePixelHeight||(i.displayAspectWidth=this.internalTrack.info.squarePixelWidth,i.displayAspectHeight=this.internalTrack.info.squarePixelHeight),i}))():null})}}class bi extends ki{constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getType(){return"audio"}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}getDecoderConfig(){return d(this,null,function*(){var e,t;return this.internalTrack.info.codec?null!=(t=this.decoderConfig)?t:this.decoderConfig={codec:qe(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:null!=(e=this.internalTrack.info.codecDescription)?e:void 0}:null})}}const Ti=(e,t)=>{if(e.presentationTimestamps){const i=z(e.presentationTimestamps,t,e=>e.presentationTimestamp);return-1===i?-1:e.presentationTimestamps[i].sampleIndex}{const i=z(e.sampleTimingEntries,t,e=>e.startDecodeTimestamp);if(-1===i)return-1;const r=e.sampleTimingEntries[i];return r.startIndex+Math.min(Math.floor((t-r.startDecodeTimestamp)/r.delta),r.count-1)}},Si=(e,t)=>{var i;if(!e.keySampleIndices)return Ti(e,t);if(e.presentationTimestamps){const i=z(e.presentationTimestamps,t,e=>e.presentationTimestamp);if(-1===i)return-1;for(let t=i;t>=0;t--){const i=e.presentationTimestamps[t].sampleIndex;if(-1!==L(e.keySampleIndices,i,e=>e))return i}return-1}{const r=Ti(e,t),n=z(e.keySampleIndices,r,e=>e);return null!=(i=e.keySampleIndices[n])?i:-1}},vi=(e,t)=>{const i=z(e.sampleTimingEntries,t,e=>e.startIndex),r=e.sampleTimingEntries[i];if(!r||r.startIndex+r.count<=t)return null;let n=r.startDecodeTimestamp+(t-r.startIndex)*r.delta;const s=z(e.sampleCompositionTimeOffsets,t,e=>e.startIndex),a=e.sampleCompositionTimeOffsets[s];a&&t-a.startIndexe.startSampleIndex),c=e.sampleToChunk[l];y(c);const u=c.startChunkIndex+Math.floor((t-c.startSampleIndex)/c.samplesPerChunk),d=e.chunkOffsets[u],h=c.startSampleIndex+(u-c.startChunkIndex)*c.samplesPerChunk;let f=0,m=d;if(1===e.sampleSizes.length)m+=o*(t-h),f+=o*c.samplesPerChunk;else for(let g=h;ge)}},wi=(e,t)=>{var i;if(!e.keySampleIndices)return t+1;const r=z(e.keySampleIndices,t,e=>e);return null!=(i=e.keySampleIndices[r+1])?i:-1},Pi=(e,t)=>{e.startTimestamp+=t,e.endTimestamp+=t;for(const i of e.samples)i.presentationTimestamp+=t;for(const i of e.presentationTimestamps)i.presentationTimestamp+=t},Ii=e=>{const[t,i]=e,r=Math.atan2(i,t);return Number.isFinite(r)?r*(180/Math.PI):0},xi=e=>0===e.sampleSizes.length,Ci=e=>{var t,i,r;return e.currentFragmentState?null!=(i=(t=e.currentFragmentState).encryptionAuxInfo)?i:t.encryptionAuxInfo={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null}:null!=(r=e.encryptionAuxInfo)?r:e.encryptionAuxInfo={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null}},Bi=(e,t,i)=>d(null,null,function*(){if(i.resolved)return i.resolved;if(null===i.offset||0===i.sampleCount)throw new Error("Incomplete saiz/saio info; cannot resolve encryption data.");let r=0;if(i.defaultSampleInfoSize>0)r=i.defaultSampleInfoSize*i.sampleCount;else{y(i.sampleSizes);for(let e=0;e0?i.defaultSampleInfoSize:i.sampleSizes[e],o=new Uint8Array(16);s>0?o.set(xa(n,s),0):o.set(t.defaultConstantIv,0);let l=null;if(r>s){const e=Ea(n);l=[];for(let t=0;td(null,null,function*(){var n;y(e.encryptionInfo);const s=e.encryptionInfo;y(null!==s.defaultKid);const a=s.defaultKid;let o;const l=e.demuxer.decryptionKeyCache.get(a);if(l)o=yield l;else{if(!(null==(n=e.demuxer.input._formatOptions.isobmff)?void 0:n.resolveKeyId))throw new Error("Encrypted media samples encountered. To decrypt them, please provide a callback for InputOptions.formatOptions.isobmff.resolveKeyId.");const t=d(null,null,function*(){let t=e.demuxer.psshBoxes;if(r){t=[...t,...r.psshBoxes].filter(e=>null===e.keyIds||e.keyIds.includes(a));for(let e=0;e{y(e.length%2===0);const t=new Uint8Array(e.length/2);for(let i=0;id(null,null,function*(){const n=new Uint8Array(16);n.set(i.iv,0);const s=yield crypto.subtle.importKey("raw",e,{name:"AES-CTR"},!1,["decrypt"]),a=e=>d(null,null,function*(){const t=yield crypto.subtle.decrypt({name:"AES-CTR",counter:n,length:64},s,e);return new Uint8Array(t)});if(!i.subsamples)return a(r);y(null!==t.defaultCryptByteBlock&&null!==t.defaultSkipByteBlock);const o=Fi(i.subsamples,t.defaultCryptByteBlock,t.defaultSkipByteBlock);let l=0;for(const e of o)for(const t of e.perSubsample)l+=t.length;const c=new Uint8Array(l);let u=0;for(const e of o)for(const t of e.perSubsample)c.set(r.subarray(t.offset,t.offset+t.length),u),u+=t.length;const h=yield a(c),f=new Uint8Array(r);let m=0;for(const e of o)for(const t of e.perSubsample)f.set(h.subarray(m,m+t.length),t.offset),m+=t.length;return f}),Ai=(e,t,i,r)=>{const n=new pi;n.init({key:e,iv:i.iv});const s=t.defaultCryptByteBlock,a=t.defaultSkipByteBlock;if(y(null!==s&&null!==a),!i.subsamples){const e=new Uint8Array(r),t=Math.floor(r.length/16);for(let i=0;i{const r=[],n=0!==t||0!==i;let s=0;for(const a of e){s+=a.clearLen;const e=[];if(n){let r=a.protectedLen,n=s;for(;r>0&&!(r<16*t);){const s=16*t;e.push({offset:n,length:s}),n+=s,r-=s;const a=Math.min(16*i,r);n+=a,r-=a}s+=a.protectedLen}else a.protectedLen>0&&e.push({offset:s,length:a.protectedLen}),s+=a.protectedLen;r.push({perSubsample:e})}return r};var Ri,Di;(Di=Ri||(Ri={}))[Di.EBML=440786851]="EBML",Di[Di.EBMLVersion=17030]="EBMLVersion",Di[Di.EBMLReadVersion=17143]="EBMLReadVersion",Di[Di.EBMLMaxIDLength=17138]="EBMLMaxIDLength",Di[Di.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",Di[Di.DocType=17026]="DocType",Di[Di.DocTypeVersion=17031]="DocTypeVersion",Di[Di.DocTypeReadVersion=17029]="DocTypeReadVersion",Di[Di.Void=236]="Void",Di[Di.Segment=408125543]="Segment",Di[Di.SeekHead=290298740]="SeekHead",Di[Di.Seek=19899]="Seek",Di[Di.SeekID=21419]="SeekID",Di[Di.SeekPosition=21420]="SeekPosition",Di[Di.Duration=17545]="Duration",Di[Di.Info=357149030]="Info",Di[Di.TimestampScale=2807729]="TimestampScale",Di[Di.MuxingApp=19840]="MuxingApp",Di[Di.WritingApp=22337]="WritingApp",Di[Di.Tracks=374648427]="Tracks",Di[Di.TrackEntry=174]="TrackEntry",Di[Di.TrackNumber=215]="TrackNumber",Di[Di.TrackUID=29637]="TrackUID",Di[Di.TrackType=131]="TrackType",Di[Di.FlagEnabled=185]="FlagEnabled",Di[Di.FlagDefault=136]="FlagDefault",Di[Di.FlagForced=21930]="FlagForced",Di[Di.FlagOriginal=21934]="FlagOriginal",Di[Di.FlagHearingImpaired=21931]="FlagHearingImpaired",Di[Di.FlagVisualImpaired=21932]="FlagVisualImpaired",Di[Di.FlagCommentary=21935]="FlagCommentary",Di[Di.FlagLacing=156]="FlagLacing",Di[Di.Name=21358]="Name",Di[Di.Language=2274716]="Language",Di[Di.LanguageBCP47=2274717]="LanguageBCP47",Di[Di.CodecID=134]="CodecID",Di[Di.CodecPrivate=25506]="CodecPrivate",Di[Di.CodecDelay=22186]="CodecDelay",Di[Di.SeekPreRoll=22203]="SeekPreRoll",Di[Di.DefaultDuration=2352003]="DefaultDuration",Di[Di.Video=224]="Video",Di[Di.PixelWidth=176]="PixelWidth",Di[Di.PixelHeight=186]="PixelHeight",Di[Di.DisplayWidth=21680]="DisplayWidth",Di[Di.DisplayHeight=21690]="DisplayHeight",Di[Di.DisplayUnit=21682]="DisplayUnit",Di[Di.AlphaMode=21440]="AlphaMode",Di[Di.Audio=225]="Audio",Di[Di.SamplingFrequency=181]="SamplingFrequency",Di[Di.Channels=159]="Channels",Di[Di.BitDepth=25188]="BitDepth",Di[Di.SimpleBlock=163]="SimpleBlock",Di[Di.BlockGroup=160]="BlockGroup",Di[Di.Block=161]="Block",Di[Di.BlockAdditions=30113]="BlockAdditions",Di[Di.BlockMore=166]="BlockMore",Di[Di.BlockAdditional=165]="BlockAdditional",Di[Di.BlockAddID=238]="BlockAddID",Di[Di.BlockDuration=155]="BlockDuration",Di[Di.ReferenceBlock=251]="ReferenceBlock",Di[Di.Cluster=524531317]="Cluster",Di[Di.Timestamp=231]="Timestamp",Di[Di.Cues=475249515]="Cues",Di[Di.CuePoint=187]="CuePoint",Di[Di.CueTime=179]="CueTime",Di[Di.CueTrackPositions=183]="CueTrackPositions",Di[Di.CueTrack=247]="CueTrack",Di[Di.CueClusterPosition=241]="CueClusterPosition",Di[Di.Colour=21936]="Colour",Di[Di.MatrixCoefficients=21937]="MatrixCoefficients",Di[Di.TransferCharacteristics=21946]="TransferCharacteristics",Di[Di.Primaries=21947]="Primaries",Di[Di.Range=21945]="Range",Di[Di.Projection=30320]="Projection",Di[Di.ProjectionType=30321]="ProjectionType",Di[Di.ProjectionPoseRoll=30325]="ProjectionPoseRoll",Di[Di.Attachments=423732329]="Attachments",Di[Di.AttachedFile=24999]="AttachedFile",Di[Di.FileDescription=18046]="FileDescription",Di[Di.FileName=18030]="FileName",Di[Di.FileMediaType=18016]="FileMediaType",Di[Di.FileData=18012]="FileData",Di[Di.FileUID=18094]="FileUID",Di[Di.Chapters=272869232]="Chapters",Di[Di.Tags=307544935]="Tags",Di[Di.Tag=29555]="Tag",Di[Di.Targets=25536]="Targets",Di[Di.TargetTypeValue=26826]="TargetTypeValue",Di[Di.TargetType=25546]="TargetType",Di[Di.TagTrackUID=25541]="TagTrackUID",Di[Di.TagEditionUID=25545]="TagEditionUID",Di[Di.TagChapterUID=25540]="TagChapterUID",Di[Di.TagAttachmentUID=25542]="TagAttachmentUID",Di[Di.SimpleTag=26568]="SimpleTag",Di[Di.TagName=17827]="TagName",Di[Di.TagLanguage=17530]="TagLanguage",Di[Di.TagString=17543]="TagString",Di[Di.TagBinary=17541]="TagBinary",Di[Di.ContentEncodings=28032]="ContentEncodings",Di[Di.ContentEncoding=25152]="ContentEncoding",Di[Di.ContentEncodingOrder=20529]="ContentEncodingOrder",Di[Di.ContentEncodingScope=20530]="ContentEncodingScope",Di[Di.ContentCompression=20532]="ContentCompression",Di[Di.ContentCompAlgo=16980]="ContentCompAlgo",Di[Di.ContentCompSettings=16981]="ContentCompSettings",Di[Di.ContentEncryption=20533]="ContentEncryption";const Mi=[Ri.EBML,Ri.Segment],Ni=[Ri.SeekHead,Ri.Info,Ri.Cluster,Ri.Tracks,Ri.Cues,Ri.Attachments,Ri.Chapters,Ri.Tags],Oi=[...Mi,...Ni],Li=16,zi=e=>{if(e.remainingLength<1)return null;const t=Ca(e);if(e.skip(-1),0===t)return null;let i=1,r=128;for(;0===(t&r);)i++,r>>=1;return e.remainingLength{if(e.remainingLength<1)return null;const t=Ca(e);if(0===t)return null;let i=1,r=128;for(;0===(t&r);)i++,r>>=1;if(e.remainingLength{if(t<1||t>8)throw new Error("Bad unsigned int size "+t);let i=0;for(let r=0;r{const t=zi(e);if(null===t)return null;if(e.remainingLength{if(e.remainingLength<1)return null;if(255===Ca(e))return;e.skip(-1);const t=Ui(e);return null===t?null:72057594037927940!==t?t:void 0},Hi=e=>{y(e.remainingLength>=2);const t=Wi(e);if(null===t)return null;const i=Vi(e);return null===i?null:{id:t,size:i}},Ki=(e,t)=>{const i=xa(e,t);let r=0;for(;r{const i=xa(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?Ua(e):qa(e)},$i=(e,t,i,r)=>d(null,null,function*(){const n=new Set(i);let s=t;for(;null===r||ss?r:s,found:!1}}),Qi=(e,t,i,r)=>d(null,null,function*(){const n=o(2,16),s=new Set(i);let a=t;for(;ae.tracks.map(e=>e.trackBacking))})}getMimeType(){return d(this,null,function*(){yield this.readMetadata();const e=yield this.getTrackBackings(),t=yield Promise.all(e.map(e=>e.getDecoderConfig().then(e=>{var t;return null!=(t=null==e?void 0:e.codec)?t:null})));return(e=>{let t=(e.hasVideo?"video/":e.hasAudio?"audio/":"application/")+(e.isWebM?"webm":"x-matroska");e.codecStrings.length>0&&(t+=`; codecs="${[...new Set(e.codecStrings.filter(Boolean))].join(", ")}"`);return t})({isWebM:this.isWebM,hasVideo:this.segments.some(e=>e.tracks.some(e=>{var t;return"video"===(null==(t=e.info)?void 0:t.type)})),hasAudio:this.segments.some(e=>e.tracks.some(e=>{var t;return"audio"===(null==(t=e.info)?void 0:t.type)})),codecStrings:t.filter(Boolean)})})}getMetadataTags(){return d(this,null,function*(){yield this.readMetadata();for(const t of this.segments)t.metadataTagsCollected||(null!==this.reader.fileSize&&(yield this.loadSegmentMetadata(t)),t.metadataTagsCollected=!0);let e={};for(const t of this.segments)e=c(c({},e),t.metadataTags);return e})}readMetadata(){var e;return null!=(e=this.readMetadataPromise)?e:this.readMetadataPromise=(()=>d(this,null,function*(){let e=0;for(;;){let t=this.reader.requestSliceRange(e,2,Li);if(t instanceof Promise&&(t=yield t),!t)break;const i=Hi(t);if(!i)break;const r=i.id;let n=i.size;const s=t.filePos;if(r===Ri.EBML){lr(n);let e=this.reader.requestSlice(s,n);if(e instanceof Promise&&(e=yield e),!e)break;this.readContiguousElements(e)}else if(r===Ri.Segment){if(yield this.readSegment(s,n),void 0===n)break;if(null===this.reader.fileSize)break}else if(r===Ri.Cluster){if(null===this.reader.fileSize)break;if(void 0===n){n=(yield $i(this.reader,s,Oi,this.reader.fileSize)).pos-s}const e=T(this.segments);e&&(e.elementEndPos=s+n)}lr(n),e=s+n}}))()}readSegment(e,t){return d(this,null,function*(){var i;this.currentSegment={seekHeadSeen:!1,infoSeen:!1,tracksSeen:!1,cuesSeen:!1,tagsSeen:!1,attachmentsSeen:!1,timestampScale:-1,timestampFactor:-1,duration:-1,seekEntries:[],tracks:[],cuePoints:[],dataStartPos:e,elementEndPos:void 0===t?null:e+t,clusterSeekStartPos:e,lastReadCluster:null,metadataTags:{},metadataTagsCollected:!1},this.segments.push(this.currentSegment);let r=e;for(;null===this.currentSegment.elementEndPos||re.id===s);if(-1!==l){const e=pr[l].flag;this.currentSegment[e]=!0,lr(a);let t=this.reader.requestSlice(o,a);t instanceof Promise&&(t=yield t),t&&this.readContiguousElements(t)}else if(s===Ri.Tags||s===Ri.Attachments){s===Ri.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,lr(a);let e=this.reader.requestSlice(o,a);e instanceof Promise&&(e=yield e),e&&this.readContiguousElements(e)}else if(s===Ri.Cluster){this.currentSegment.clusterSeekStartPos=t;break}if(void 0===a)break;r=o+a}if(this.currentSegment.seekEntries.sort((e,t)=>e.segmentPosition-t.segmentPosition),null!==this.reader.fileSize)for(const t of this.currentSegment.seekEntries){const i=pr.find(e=>e.id===t.id);if(!i)continue;if(this.currentSegment[i.flag])continue;let r=this.reader.requestSliceRange(e+t.segmentPosition,2,Li);if(r instanceof Promise&&(r=yield r),!r)continue;const n=Hi(r);if(!n)continue;const{id:s,size:a}=n;if(s!==i.id)continue;lr(a),this.currentSegment[i.flag]=!0;let o=this.reader.requestSlice(r.filePos,a);o instanceof Promise&&(o=yield o),o&&this.readContiguousElements(o)}-1===this.currentSegment.timestampScale&&(this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1e3);for(const e of this.currentSegment.tracks)null!==e.defaultDurationNs&&(e.defaultDuration=this.currentSegment.timestampFactor*e.defaultDurationNs/1e9);const n=new Map(this.currentSegment.tracks.map(e=>[e.id,e]));for(const e of this.currentSegment.cuePoints){const t=n.get(e.trackId);t&&t.cuePoints.push(e)}for(const e of this.currentSegment.tracks){e.cuePoints.sort((e,t)=>e.time-t.time);for(let t=0;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 d(this,null,function*(){var i;if((null==(i=t.lastReadCluster)?void 0:i.elementStartPos)===e)return t.lastReadCluster;let r=this.reader.requestSliceRange(e,2,Li);r instanceof Promise&&(r=yield r),y(r);const n=e,s=Hi(r);y(s);y(s.id===Ri.Cluster);let a=s.size;const o=r.filePos;if(void 0===a){a=(yield $i(this.reader,o,Oi,t.elementEndPos)).pos-o}let l=this.reader.requestSlice(o,a);l instanceof Promise&&(l=yield l);const c={segment:t,elementStartPos:n,elementEndPos:o+a,dataStartPos:o,timestamp:-1,trackData:new Map};if(this.currentCluster=c,l){const e=this.readContiguousElements(l,Oi);c.elementEndPos=e}for(const[,e]of c.trackData){const t=e.track;y(e.blocks.length>0);let i=!1;for(let n=0;n({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[T(e.presentationTimestamps).blockIndex];e.startTimestamp=r.timestamp,e.endTimestamp=s.timestamp+s.duration;const a=z(t.clusterPositionCache,e.startTimestamp,e=>e.startTimestamp);-1!==a&&t.clusterPositionCache[a].elementStartPos===n||t.clusterPositionCache.splice(a+1,0,{elementStartPos:c.elementStartPos,startTimestamp:e.startTimestamp})}return t.lastReadCluster=c,c})}getTrackDataInCluster(e,t){let i=e.trackData.get(t);if(!i){const r=e.segment.tracks.find(e=>e.id===t);if(!r)return null;i={track:r,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},e.trackData.set(t,i)}return i}expandLacedBlocks(e,t){var i;for(let r=0;r=2;){const i=e.filePos;if(!this.traverseElement(e,t))return i}return e.filePos}traverseElement(e,t){var i,r,n,s,a,o,l,d,h,f,m,p,g,k,T,S,v,w,P,I,x,C,E,A,R,D,M,N,O,L,z,U,q,W,V,H,K,j,X,$,G,Y,J,Z,te,ie,re,ne,se,ae,oe,le,ce,ue;const de=Hi(e);if(!de)return!1;if(t&&t.includes(de.id))return!1;const{id:he,size:fe}=de,me=e.filePos;switch(lr(fe),he){case Ri.DocType:this.isWebM="webm"===Ki(e,fe);break;case Ri.Seek:{if(!this.currentSegment)break;const t={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(t),this.readContiguousElements(e.slice(me,fe)),-1!==t.id&&-1!==t.segmentPosition||this.currentSegment.seekEntries.pop()}break;case Ri.SeekID:{const t=null==(i=this.currentSegment)?void 0:i.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.id=qi(e,fe)}break;case Ri.SeekPosition:{const t=null==(r=this.currentSegment)?void 0:r.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.segmentPosition=qi(e,fe)}break;case Ri.TimestampScale:if(!this.currentSegment)break;this.currentSegment.timestampScale=qi(e,fe),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale;break;case Ri.Duration:if(!this.currentSegment)break;this.currentSegment.duration=Xi(e,fe);break;case Ri.TrackEntry:if(!this.currentSegment)break;if(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:u(c({},Be),{primary:!1}),trackBacking:null,codecId:null,codecPrivate:null,defaultDuration:null,defaultDurationNs:null,name:null,languageCode:"eng",hasLanguageBcp47:!1,decodingInstructions:[],info:null},this.readContiguousElements(e.slice(me,fe)),!this.currentTrack)break;if(this.currentTrack.decodingInstructions.some(e=>{var t;return"decompress"!==(null==(t=e.data)?void 0:t.type)||e.scope!==dr.Block||e.data.algorithm!==fr.HeaderStripping})&&(console.warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`),this.currentTrack=null),this.currentTrack&&-1!==this.currentTrack.id&&this.currentTrack.codecId&&this.currentTrack.info){const e=this.currentTrack.codecId.indexOf("/"),t=-1===e?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,e);if("video"===this.currentTrack.info.type&&-1!==this.currentTrack.info.width&&-1!==this.currentTrack.info.height){if(this.currentTrack.info.squarePixelWidth=this.currentTrack.info.width,this.currentTrack.info.squarePixelHeight=this.currentTrack.info.height,null!==this.currentTrack.info.displayWidth&&null!==this.currentTrack.info.displayHeight){const e=this.currentTrack.info.displayWidth*this.currentTrack.info.height,t=this.currentTrack.info.displayHeight*this.currentTrack.info.width;e>0&&t>0&&(e>t?this.currentTrack.info.squarePixelWidth=Math.round(this.currentTrack.info.width*e/t):this.currentTrack.info.squarePixelHeight=Math.round(this.currentTrack.info.height*t/e))}this.currentTrack.codecId===Gi?(this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===Yi?(this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Ji?this.currentTrack.info.codec="vp8":t===Zi?this.currentTrack.info.codec="vp9":t===er&&(this.currentTrack.info.codec="av1");const e=this.currentTrack;this.currentTrack.trackBacking=new br(e),this.currentSegment.tracks.push(this.currentTrack)}else if("audio"===this.currentTrack.info.type){t===tr?(this.currentTrack.info.codec="aac",this.currentTrack.info.aacCodecInfo={isMpeg2:this.currentTrack.codecId.includes("MPEG2"),objectType:null},this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===ir?this.currentTrack.info.codec="mp3":t===rr?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=We):t===nr?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===sr?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===ar?(this.currentTrack.info.codec="ac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===or?(this.currentTrack.info.codec="eac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):"A_PCM/INT/LIT"===this.currentTrack.codecId?8===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-u8":16===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s16":24===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s24":32===this.currentTrack.info.bitDepth&&(this.currentTrack.info.codec="pcm-s32"):"A_PCM/INT/BIG"===this.currentTrack.codecId?8===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-u8":16===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s16be":24===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s24be":32===this.currentTrack.info.bitDepth&&(this.currentTrack.info.codec="pcm-s32be"):"A_PCM/FLOAT/IEEE"===this.currentTrack.codecId&&(32===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-f32":64===this.currentTrack.info.bitDepth&&(this.currentTrack.info.codec="pcm-f64"));const e=this.currentTrack;this.currentTrack.trackBacking=new Tr(e),this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null;break;case Ri.TrackNumber:if(!this.currentTrack)break;this.currentTrack.id=qi(e,fe);break;case Ri.TrackType:{if(!this.currentTrack)break;const t=qi(e,fe);1===t?this.currentTrack.info={type:"video",width:-1,height:-1,displayWidth:null,displayHeight:null,displayUnit:null,squarePixelWidth:-1,squarePixelHeight:-1,rotation:0,codec:null,codecDescription:null,colorSpace:null,alphaMode:!1}:2===t&&(this.currentTrack.info={type:"audio",numberOfChannels:1,sampleRate:8e3,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case Ri.FlagEnabled:if(!this.currentTrack)break;qi(e,fe)||(this.currentTrack=null);break;case Ri.FlagDefault:if(!this.currentTrack)break;this.currentTrack.disposition.default=!!qi(e,fe);break;case Ri.FlagForced:if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!qi(e,fe);break;case Ri.FlagOriginal:if(!this.currentTrack)break;this.currentTrack.disposition.original=!!qi(e,fe);break;case Ri.FlagHearingImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!qi(e,fe);break;case Ri.FlagVisualImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!qi(e,fe);break;case Ri.FlagCommentary:if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!qi(e,fe);break;case Ri.CodecID:if(!this.currentTrack)break;this.currentTrack.codecId=Ki(e,fe);break;case Ri.CodecPrivate:if(!this.currentTrack)break;this.currentTrack.codecPrivate=xa(e,fe);break;case Ri.DefaultDuration:if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=qi(e,fe);break;case Ri.Name:if(!this.currentTrack)break;this.currentTrack.name=ji(e,fe);break;case Ri.Language:if(!this.currentTrack)break;if(this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=Ki(e,fe),ee(this.currentTrack.languageCode)||(this.currentTrack.languageCode=Q);break;case Ri.LanguageBCP47:{if(!this.currentTrack)break;const t=Ki(e,fe).split("-")[0];this.currentTrack.languageCode=t||Q,this.currentTrack.hasLanguageBcp47=!0}break;case Ri.Video:if("video"!==(null==(s=null==(n=this.currentTrack)?void 0:n.info)?void 0:s.type))break;this.readContiguousElements(e.slice(me,fe));break;case Ri.PixelWidth:if("video"!==(null==(o=null==(a=this.currentTrack)?void 0:a.info)?void 0:o.type))break;this.currentTrack.info.width=qi(e,fe);break;case Ri.PixelHeight:if("video"!==(null==(d=null==(l=this.currentTrack)?void 0:l.info)?void 0:d.type))break;this.currentTrack.info.height=qi(e,fe);break;case Ri.DisplayWidth:if("video"!==(null==(f=null==(h=this.currentTrack)?void 0:h.info)?void 0:f.type))break;this.currentTrack.info.displayWidth=qi(e,fe);break;case Ri.DisplayHeight:if("video"!==(null==(p=null==(m=this.currentTrack)?void 0:m.info)?void 0:p.type))break;this.currentTrack.info.displayHeight=qi(e,fe);break;case Ri.DisplayUnit:if("video"!==(null==(k=null==(g=this.currentTrack)?void 0:g.info)?void 0:k.type))break;this.currentTrack.info.displayUnit=qi(e,fe);break;case Ri.AlphaMode:if("video"!==(null==(S=null==(T=this.currentTrack)?void 0:T.info)?void 0:S.type))break;this.currentTrack.info.alphaMode=1===qi(e,fe);break;case Ri.Colour:if("video"!==(null==(w=null==(v=this.currentTrack)?void 0:v.info)?void 0:w.type))break;this.currentTrack.info.colorSpace={},this.readContiguousElements(e.slice(me,fe));break;case Ri.MatrixCoefficients:{if("video"!==(null==(I=null==(P=this.currentTrack)?void 0:P.info)?void 0:I.type)||!this.currentTrack.info.colorSpace)break;const t=qi(e,fe),i=null!=(x=F[t])?x:null;this.currentTrack.info.colorSpace.matrix=i}break;case Ri.Range:if("video"!==(null==(E=null==(C=this.currentTrack)?void 0:C.info)?void 0:E.type)||!this.currentTrack.info.colorSpace)break;this.currentTrack.info.colorSpace.fullRange=2===qi(e,fe);break;case Ri.TransferCharacteristics:{if("video"!==(null==(R=null==(A=this.currentTrack)?void 0:A.info)?void 0:R.type)||!this.currentTrack.info.colorSpace)break;const t=qi(e,fe),i=null!=(D=_[t])?D:null;this.currentTrack.info.colorSpace.transfer=i}break;case Ri.Primaries:{if("video"!==(null==(N=null==(M=this.currentTrack)?void 0:M.info)?void 0:N.type)||!this.currentTrack.info.colorSpace)break;const t=qi(e,fe),i=null!=(O=B[t])?O:null;this.currentTrack.info.colorSpace.primaries=i}break;case Ri.Projection:if("video"!==(null==(z=null==(L=this.currentTrack)?void 0:L.info)?void 0:z.type))break;this.readContiguousElements(e.slice(me,fe));break;case Ri.ProjectionPoseRoll:{if("video"!==(null==(q=null==(U=this.currentTrack)?void 0:U.info)?void 0:q.type))break;const t=-Xi(e,fe);try{this.currentTrack.info.rotation=b(t)}catch(pe){}}break;case Ri.Audio:if("audio"!==(null==(V=null==(W=this.currentTrack)?void 0:W.info)?void 0:V.type))break;this.readContiguousElements(e.slice(me,fe));break;case Ri.SamplingFrequency:if("audio"!==(null==(K=null==(H=this.currentTrack)?void 0:H.info)?void 0:K.type))break;this.currentTrack.info.sampleRate=Xi(e,fe);break;case Ri.Channels:if("audio"!==(null==(X=null==(j=this.currentTrack)?void 0:j.info)?void 0:X.type))break;this.currentTrack.info.numberOfChannels=qi(e,fe);break;case Ri.BitDepth:if("audio"!==(null==(G=null==($=this.currentTrack)?void 0:$.info)?void 0:G.type))break;this.currentTrack.info.bitDepth=qi(e,fe);break;case Ri.CuePoint:if(!this.currentSegment)break;this.readContiguousElements(e.slice(me,fe)),this.currentCueTime=null;break;case Ri.CueTime:this.currentCueTime=qi(e,fe);break;case Ri.CueTrackPositions:{if(null===this.currentCueTime)break;y(this.currentSegment);const t={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(t),this.readContiguousElements(e.slice(me,fe)),-1!==t.trackId&&-1!==t.clusterPosition||this.currentSegment.cuePoints.pop()}break;case Ri.CueTrack:{const t=null==(Y=this.currentSegment)?void 0:Y.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;t.trackId=qi(e,fe)}break;case Ri.CueClusterPosition:{const t=null==(J=this.currentSegment)?void 0:J.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;y(this.currentSegment),t.clusterPosition=this.currentSegment.dataStartPos+qi(e,fe)}break;case Ri.Timestamp:if(!this.currentCluster)break;this.currentCluster.timestamp=qi(e,fe);break;case Ri.SimpleBlock:{if(!this.currentCluster)break;const t=Ui(e);if(null===t)break;const i=this.getTrackDataInCluster(this.currentCluster,t);if(!i)break;const r=Aa(e),n=Ca(e),s=n>>1&3;let a=!!(128&n);"audio"===(null==(Z=i.track.info)?void 0:Z.type)&&i.track.info.codec&&(a=!0);const o=xa(e,fe-(e.filePos-me)),l=i.track.decodingInstructions.length>0;i.blocks.push({timestamp:r,duration:0,isKeyFrame:a,data:o,lacing:s,decoded:!l,mainAdditional:null})}break;case Ri.BlockGroup:if(!this.currentCluster)break;this.readContiguousElements(e.slice(me,fe)),this.currentBlock=null;break;case Ri.Block:{if(!this.currentCluster)break;const t=Ui(e);if(null===t)break;const i=this.getTrackDataInCluster(this.currentCluster,t);if(!i)break;const r=Aa(e),n=Ca(e)>>1&3,s=xa(e,fe-(e.filePos-me)),a=i.track.decodingInstructions.length>0;this.currentBlock={timestamp:r,duration:0,isKeyFrame:!0,data:s,lacing:n,decoded:!a,mainAdditional:null},i.blocks.push(this.currentBlock)}break;case Ri.BlockAdditions:this.readContiguousElements(e.slice(me,fe));break;case Ri.BlockMore:if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(me,fe)),this.currentBlockAdditional.data&&1===this.currentBlockAdditional.addId&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null;break;case Ri.BlockAdditional:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=xa(e,fe);break;case Ri.BlockAddID:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=qi(e,fe);break;case Ri.BlockDuration:if(!this.currentBlock)break;this.currentBlock.duration=qi(e,fe);break;case Ri.ReferenceBlock:if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1;break;case Ri.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(me,fe));break;case Ri.Targets:this.readContiguousElements(e.slice(me,fe));break;case Ri.TargetTypeValue:50!==qi(e,fe)&&(this.currentTagTargetIsMovie=!1);break;case Ri.TagTrackUID:case Ri.TagEditionUID:case Ri.TagChapterUID:case Ri.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case Ri.SimpleTag:if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(me,fe));break;case Ri.TagName:this.currentSimpleTagName=ji(e,fe);break;case Ri.TagString:{if(!this.currentSimpleTagName)break;const t=ji(e,fe);this.processTagValue(this.currentSimpleTagName,t)}break;case Ri.TagBinary:{if(!this.currentSimpleTagName)break;const t=xa(e,fe);this.processTagValue(this.currentSimpleTagName,t)}break;case Ri.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(me,fe));const t=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(null!=t.raw||(t.raw={}),t.raw[this.currentAttachedFile.fileUid.toString()]=new Ce(this.currentAttachedFile.fileData,null!=(te=this.currentAttachedFile.fileMediaType)?te:void 0,null!=(ie=this.currentAttachedFile.fileName)?ie:void 0,null!=(re=this.currentAttachedFile.fileDescription)?re:void 0)),(null==(ne=this.currentAttachedFile.fileMediaType)?void 0:ne.startsWith("image/"))&&this.currentAttachedFile.fileData){const e=this.currentAttachedFile.fileName;let i="unknown";if(e){const t=e.toLowerCase();t.startsWith("cover.")?i="coverFront":t.startsWith("back.")&&(i="coverBack")}null!=t.images||(t.images=[]),t.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:i,name:null!=(se=this.currentAttachedFile.fileName)?se:void 0,description:null!=(ae=this.currentAttachedFile.fileDescription)?ae:void 0})}this.currentAttachedFile=null}break;case Ri.FileUID:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=((e,t)=>{if(t<1)throw new Error("Bad unsigned int size "+t);let i=BigInt("0");for(let r=0;rt.order-e.order);break;case Ri.ContentEncoding:this.currentDecodingInstruction={order:0,scope:dr.Block,data:null},this.readContiguousElements(e.slice(me,fe)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case Ri.ContentEncodingOrder:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=qi(e,fe);break;case Ri.ContentEncodingScope:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=qi(e,fe);break;case Ri.ContentCompression:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:fr.Zlib,settings:null},this.readContiguousElements(e.slice(me,fe));break;case Ri.ContentCompAlgo:if("decompress"!==(null==(le=null==(oe=this.currentDecodingInstruction)?void 0:oe.data)?void 0:le.type))break;this.currentDecodingInstruction.data.algorithm=qi(e,fe);break;case Ri.ContentCompSettings:if("decompress"!==(null==(ue=null==(ce=this.currentDecodingInstruction)?void 0:ce.data)?void 0:ue.type))break;this.currentDecodingInstruction.data.settings=xa(e,fe);break;case Ri.ContentEncryption:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}return e.filePos=me+fe,!0}decodeBlockData(e,t){y(e.decodingInstructions.length>0);let i=t;for(const r of e.decodingInstructions)if(y(r.data),"decompress"===r.data.type)if(r.data.algorithm===fr.HeaderStripping)if(r.data.settings&&r.data.settings.length>0){const e=r.data.settings,t=new Uint8Array(e.length+i.length);t.set(e,0),t.set(i,e.length),i=t}return i}processTagValue(e,t){var i,r;if(!(null==(i=this.currentSegment)?void 0:i.metadataTags))return;const n=this.currentSegment.metadataTags;if(null!=n.raw||(n.raw={}),null!=(r=n.raw)[e]||(r[e]=t),"string"===typeof t)switch(e.toLowerCase()){case"title":null!=n.title||(n.title=t);break;case"description":null!=n.description||(n.description=t);break;case"artist":null!=n.artist||(n.artist=t);break;case"album":null!=n.album||(n.album=t);break;case"album_artist":null!=n.albumArtist||(n.albumArtist=t);break;case"genre":null!=n.genre||(n.genre=t);break;case"comment":null!=n.comment||(n.comment=t);break;case"lyrics":null!=n.lyrics||(n.lyrics=t);break;case"date":{const e=new Date(t);Number.isNaN(e.getTime())||null!=n.date||(n.date=e)}break;case"track_number":case"part_number":{const e=t.split("/"),i=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(i)&&i>0&&(null!=n.trackNumber||(n.trackNumber=i)),r&&Number.isInteger(r)&&r>0&&(null!=n.tracksTotal||(n.tracksTotal=r))}break;case"disc_number":case"disc":{const e=t.split("/"),i=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(i)&&i>0&&(null!=n.discNumber||(n.discNumber=i)),r&&Number.isInteger(r)&&r>0&&(null!=n.discsTotal||(n.discsTotal=r))}}}}class yr{constructor(e){this.internalTrack=e,this.packetToClusterLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){const e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType();let i=0;for(const r of e.segments)for(const e of r.tracks)if(e.trackBacking.getType()===t&&i++,e===this.internalTrack)break;return i}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.codecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.segment.timestampFactor}isRelativeToUnixEpoch(){return!1}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return d(this,null,function*(){var e;const t=this.internalTrack.segment;if(t.duration<=0)return null;let i=t.duration/t.timestampFactor;const r=yield this.getFirstPacket({metadataOnly:!0});return i+=null!=(e=null==r?void 0:r.timestamp)?e:0,i})}getLiveRefreshInterval(){return d(this,null,function*(){return null})}getFirstPacket(e){return d(this,null,function*(){return this.performClusterLookup(null,e=>e.trackData.get(this.internalTrack.id)?{blockIndex:0,correctBlockFound:!0}:{blockIndex:-1,correctBlockFound:!1},-1/0,1/0,e)})}intoTimescale(e){return G(e*this.internalTrack.segment.timestampFactor)}getPacket(e,t){return d(this,null,function*(){const i=this.intoTimescale(e);return this.performClusterLookup(null,e=>{const t=e.trackData.get(this.internalTrack.id);if(!t)return{blockIndex:-1,correctBlockFound:!1};const r=z(t.presentationTimestamps,i,e=>e.timestamp);return{blockIndex:-1!==r?t.presentationTimestamps[r].blockIndex:-1,correctBlockFound:-1!==r&&i{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=V(t.presentationTimestamps,e=>t.blocks[e.blockIndex].isKeyFrame&&e.timestamp<=i);return{blockIndex:-1!==r?t.presentationTimestamps[r].blockIndex:-1,correctBlockFound:-1!==r&&i{if(e===i.cluster){const t=e.trackData.get(this.internalTrack.id).blocks.findIndex((e,t)=>e.isKeyFrame&&t>i.blockIndex);if(-1!==t)return{blockIndex:t,correctBlockFound:!0}}else{const t=e.trackData.get(this.internalTrack.id);if(t&&null!==t.firstKeyFrameTimestamp){const e=t.blocks.findIndex(e=>e.isKeyFrame);return y(-1!==e),{blockIndex:e,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)})}fetchPacketInCluster(e,t,i){return d(this,null,function*(){var r;if(-1===t)return null;const n=e.trackData.get(this.internalTrack.id).blocks[t];y(n),n.decoded||(n.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,n.data),n.decoded=!0);const s=i.metadataOnly?Gt:n.data,a=n.timestamp/this.internalTrack.segment.timestampFactor,o=n.duration/this.internalTrack.segment.timestampFactor,l={};n.mainAdditional&&"video"===(null==(r=this.internalTrack.info)?void 0:r.type)&&this.internalTrack.info.alphaMode&&(l.alpha=i.metadataOnly?Gt:n.mainAdditional,l.alphaByteLength=n.mainAdditional.byteLength);const c=new Yt(s,n.isKeyFrame?"key":"delta",a,o,e.dataStartPos+t,n.data.byteLength,l);return this.packetToClusterLocation.set(c,{cluster:e,blockIndex:t}),c})}performClusterLookup(e,t,i,r,n){return d(this,null,function*(){var s,a,o,l;const{demuxer:c,segment:u}=this.internalTrack;let d=null,h=null,f=-1;if(e){const{blockIndex:i,correctBlockFound:r}=t(e);if(r)return this.fetchPacketInCluster(e,i,n);-1!==i&&(h=e,f=i)}const m=z(this.internalTrack.cuePoints,i,e=>e.time),p=-1!==m?this.internalTrack.cuePoints[m]:null,g=z(this.internalTrack.clusterPositionCache,i,e=>e.startTimestamp),k=-1!==g?this.internalTrack.clusterPositionCache[g]:null,b=Math.max(null!=(s=null==p?void 0:p.clusterPosition)?s:0,null!=(a=null==k?void 0:k.elementStartPos)?a:0)||null;let T;for(e?null===b||e.elementStartPos>=b?(T=e.elementEndPos,d=e):T=b:T=null!=b?b:u.clusterSeekStartPos;null===u.elementEndPos||T<=u.elementEndPos-2;){if(d){const e=d.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>r)break}let e=c.reader.requestSliceRange(T,2,Li);if(e instanceof Promise&&(e=yield e),!e)break;const i=T,s=Hi(e);if(!s||!Ni.includes(s.id)&&s.id!==Ri.Void){const e=yield Qi(c.reader,i,Ni,Math.min(null!=(o=u.elementEndPos)?o:1/0,i+gr));if(e){T=e;continue}break}const a=s.id;let l=s.size;const m=e.filePos;if(a===Ri.Cluster){d=yield c.readCluster(i,u),l=d.elementEndPos-m;const{blockIndex:e,correctBlockFound:r}=t(d);if(r)return this.fetchPacketInCluster(d,e,n);-1!==e&&(h=d,f=e)}if(void 0===l){y(a!==Ri.Cluster);l=(yield $i(c.reader,m,Oi,u.elementEndPos)).pos-m}const p=m+l;if(null===u.elementEndPos){let e=c.reader.requestSliceRange(p,2,Li);if(e instanceof Promise&&(e=yield e),!e)break;if(Wi(e)===Ri.Segment){u.elementEndPos=p;break}}T=p}if(p&&(!h||h.elementStartPosd(this,null,function*(){var e,t;let i=null;("vp9"===this.internalTrack.info.codec||"av1"===this.internalTrack.info.codec||"avc"===this.internalTrack.info.codec&&!this.internalTrack.info.codecDescription||"hevc"===this.internalTrack.info.codec&&!this.internalTrack.info.codecDescription)&&(i=yield this.getFirstPacket({}));const r={codec:Ue({width:this.internalTrack.info.width,height:this.internalTrack.info.height,codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,colorSpace:this.internalTrack.info.colorSpace,avcType:1,avcCodecInfo:"avc"===this.internalTrack.info.codec&&i?pt(i.data):null,hevcCodecInfo:"hevc"===this.internalTrack.info.codec&&i?vt(i.data):null,vp9CodecInfo:"vp9"===this.internalTrack.info.codec&&i?Rt(i.data):null,av1CodecInfo:"av1"===this.internalTrack.info.codec&&i?Mt(i.data):null}),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:null!=(e=this.internalTrack.info.codecDescription)?e:void 0,colorSpace:null!=(t=this.internalTrack.info.colorSpace)?t:void 0};return this.internalTrack.info.width===this.internalTrack.info.squarePixelWidth&&this.internalTrack.info.height===this.internalTrack.info.squarePixelHeight||(r.displayAspectWidth=this.internalTrack.info.squarePixelWidth,r.displayAspectHeight=this.internalTrack.info.squarePixelHeight),r}))():null})}}class Tr extends yr{constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getType(){return"audio"}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}getDecoderConfig(){return d(this,null,function*(){var e,t;return this.internalTrack.info.codec?null!=(t=this.decoderConfig)?t:this.decoderConfig={codec:qe({codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,aacCodecInfo:this.internalTrack.info.aacCodecInfo}),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:null!=(e=this.internalTrack.info.codecDescription)?e:void 0}:null})}}const Sr=(e,t,i)=>d(null,null,function*(){const r=o(2,16);let n=t;for(;null===i||n=4;){const t=s.filePos,i=Ra(s),r=null!==e.fileSize?e.fileSize-n:null,a=Ye(i,r);if(a.header)return{header:a.header,startPos:n};s.filePos=t+a.bytesAdvanced,n=s.filePos}}return null});class vr extends Qt{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.firstFrameHeaderPos=null,this.loadedSamples=[],this.metadataTags=null,this.xingData=null,this.trackBackings=[],this.readingMutex=new D,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}readMetadata(){return d(this,null,function*(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>d(this,null,function*(){for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)yield this.advanceReader();if(!this.firstFrameHeader)throw new Error("No valid MP3 frame found.");this.trackBackings=[new wr(this)]}))()})}advanceReader(){return d(this,null,function*(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,Qa);if(e instanceof Promise&&(e=yield e),!e)return void(this.lastSampleLoaded=!0);const t=Za(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}const e=yield Sr(this.reader,this.lastLoadedPos,this.reader.fileSize);if(!e)return void(this.lastSampleLoaded=!0);const t=e.header;this.lastLoadedPos=e.startPos+t.totalSize-1;const i=Ge(t.mpegVersionId,t.channel);let r=this.reader.requestSlice(e.startPos+i,4);if(r instanceof Promise&&(r=yield r),r){const t=Ra(r);if(t===$e||t===Qe){if(!this.xingData){let t=this.reader.requestSlice(e.startPos+i+4,12);if(t instanceof Promise&&(t=yield t),t){const e=xa(t,12),i=P(e),r=i.getUint32(0,!1);this.xingData={frameCount:r&Ze.FrameCount?i.getUint32(4,!1):null,fileSize:r&Ze.FileSize?i.getUint32(8,!1):null}}}return}}this.firstFrameHeader||(this.firstFrameHeader=t,this.firstFrameHeaderPos=e.startPos),t.sampleRate!==this.firstFrameHeader.sampleRate&&console.warn(`MP3 changed sample rate mid-file: ${this.firstFrameHeader.sampleRate} Hz to ${t.sampleRate} Hz. Might be a bug, so please report this file.`);const n=t.audioSamplesInFrame/this.firstFrameHeader.sampleRate,s={timestamp:this.nextTimestampInSamples/this.firstFrameHeader.sampleRate,duration:n,dataStart:e.startPos,dataSize:t.totalSize};this.loadedSamples.push(s),this.nextTimestampInSamples+=t.audioSamplesInFrame})}getMimeType(){return d(this,null,function*(){return"audio/mpeg"})}getTrackBackings(){return d(this,null,function*(){return yield this.readMetadata(),this.trackBackings})}getMetadataTags(){return d(this,null,function*(){const e=yield this.readingMutex.acquire();try{if(yield this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let e=0,t=!1;for(;;){let i=this.reader.requestSlice(e,Qa);if(i instanceof Promise&&(i=yield i),!i)break;const r=Za(i);if(!r)break;t=!0;let n=this.reader.requestSlice(i.filePos,r.size);if(n instanceof Promise&&(n=yield n),!n)break;eo(n,r,this.metadataTags),e=i.filePos+r.size}if(!t&&null!==this.reader.fileSize&&this.reader.fileSize>=$a){let e=this.reader.requestSlice(this.reader.fileSize-$a,$a);e instanceof Promise&&(e=yield e),y(e);"TAG"===Wa(e,3)&&Ya(e,this.metadataTags)}return this.metadataTags}finally{e()}})}}class wr{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return y(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate/this.demuxer.firstFrameHeader.audioSamplesInFrame}isRelativeToUnixEpoch(){return!1}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return d(this,null,function*(){const e=this.demuxer;if(y(null!==e.firstFrameHeader),y(null!==e.firstFrameHeaderPos),e.xingData){if(null!==e.xingData.frameCount)return e.xingData.frameCount*e.firstFrameHeader.audioSamplesInFrame/e.firstFrameHeader.sampleRate}else if(null!==e.reader.fileSize){const s=(t=e.firstFrameHeader.lowSamplingFrequency,i=e.firstFrameHeader.layer,r=e.firstFrameHeader.bitrate,n=e.firstFrameHeader.sampleRate,0===i?0:1===i?144*r/(n<e.timestamp);if(-1===i)throw new Error("Packet was not created from this track.");const r=i+1;for(;r>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)yield this.demuxer.advanceReader();return this.getPacketAtIndex(r,t)}finally{i()}})}getPacket(e,t){return d(this,null,function*(){const i=yield this.demuxer.readingMutex.acquire();try{for(;;){const i=z(this.demuxer.loadedSamples,e,e=>e.timestamp);if(-1===i&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(i,t);if(i>=0&&i+1>>0&4294967295}const xr=e=>{const t=P(e),i=t.getUint32(22,!0);t.setUint32(22,0,!0);let r=0;for(let n=0;n>>24^t])>>>0}return t.setUint32(22,i,!0),r},Cr=(e,t,i)=>{let r=0,n=null;if(e.length>0)if("vorbis"===t.codec){y(t.vorbisInfo);const s=(1<<(e=>{let t=0;for(;e;)t++,e>>=1;return t})(t.vorbisInfo.modeBlockflags.length-1))-1<<1,a=(e[0]&s)>>1;if(a>=t.vorbisInfo.modeBlockflags.length)throw new Error("Invalid mode number.");let o=i;const l=t.vorbisInfo.modeBlockflags[a];if(n=t.vorbisInfo.blocksizes[l],1===l){const i=1+(1|s),r=e[0]&i?1:0;o=t.vorbisInfo.blocksizes[r]}r=null!==o?o+n>>2:0}else if("opus"===t.codec){r=(e=>{const t=e[0]>>3;return{durationInSamples:Nt[t]}})(e).durationInSamples}return{durationInSamples:r,vorbisBlockSize:n}},Br=27,Er=282,_r=e=>{const t=e.filePos;if(Da(e)!==Pr)return null;e.skip(1);const i=Ca(e),r=za(e),n=Da(e),s=Da(e),a=Da(e),o=Ca(e),l=new Uint8Array(o);for(let d=0;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}},Ar=(e,t)=>{for(;e.filePos>>8&255)===i||(t>>>16&255)===i||(t>>>24&255)===i){if(e.skip(-4),t===Pr)return!0;e.skip(1)}}return!1};class Fr extends Qt{constructor(e){super(e),this.metadataPromise=null,this.bitstreams=[],this.trackBackings=[],this.metadataTags={},this.reader=e._reader}readMetadata(){return d(this,null,function*(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>d(this,null,function*(){let e=0;for(;;){let t=this.reader.requestSliceRange(e,Br,Er);if(t instanceof Promise&&(t=yield t),!t)break;const i=_r(t);if(!i)break;if(!!!(2&i.headerType))break;this.bitstreams.push({serialNumber:i.serialNumber,bosPage:i,description:null,numberOfChannels:-1,sampleRate:-1,codecInfo:{codec:null,vorbisInfo:null,opusInfo:null},lastMetadataPacket:null}),e=i.headerStartPos+i.totalSize}for(const t of this.bitstreams){const e=yield this.readPacket(t.bosPage,0);e&&(e.data.byteLength>=7&&1===e.data[0]&&118===e.data[1]&&111===e.data[2]&&114===e.data[3]&&98===e.data[4]&&105===e.data[5]&&115===e.data[6]?yield this.readVorbisMetadata(e,t):e.data.byteLength>=8&&79===e.data[0]&&112===e.data[1]&&117===e.data[2]&&115===e.data[3]&&72===e.data[4]&&101===e.data[5]&&97===e.data[6]&&100===e.data[7]&&(yield this.readOpusMetadata(e,t)),null!==t.codecInfo.codec&&this.trackBackings.push(new Rr(t,this)))}}))()})}readVorbisMetadata(e,t){return d(this,null,function*(){let i=yield this.findNextPacketStart(e);if(!i)return;const r=yield this.readPacket(i.startPage,i.startSegmentIndex);if(!r)return;if(i=yield this.findNextPacketStart(r),!i)return;const n=yield this.readPacket(i.startPage,i.startSegmentIndex);if(!n)return;if(3!==r.data[0]||5!==n.data[0])return;const s=[],a=e=>{for(;s.push(Math.min(255,e)),!(e<255);)e-=255};a(e.data.length),a(r.data.length);const o=new Uint8Array(1+s.length+e.data.length+r.data.length+n.data.length);o[0]=2,o.set(s,1),o.set(e.data,1+s.length),o.set(r.data,1+s.length+e.data.length),o.set(n.data,1+s.length+e.data.length+r.data.length),t.codecInfo.codec="vorbis",t.description=o,t.lastMetadataPacket=n;const l=P(e.data);t.numberOfChannels=l.getUint8(11),t.sampleRate=l.getUint32(12,!0);const c=l.getUint8(28);t.codecInfo.vorbisInfo={blocksizes:[1<<(15&c),1<<(c>>4)],modeBlockflags:Ot(n.data).modeBlockflags},qt(r.data.subarray(7),this.metadataTags)})}readOpusMetadata(e,t){return d(this,null,function*(){const i=yield this.findNextPacketStart(e);if(!i)return;const r=yield this.readPacket(i.startPage,i.startSegmentIndex);if(!r)return;t.codecInfo.codec="opus",t.description=e.data,t.lastMetadataPacket=r;const n=(e=>{const t=P(e),i=t.getUint8(9),r=t.getUint16(10,!0),n=t.getUint32(12,!0),s=t.getInt16(16,!0),a=t.getUint8(18);let o=null;return a&&(o=e.subarray(19,21+i)),{outputChannelCount:i,preSkip:r,inputSampleRate:n,outputGain:s,channelMappingFamily:a,channelMappingTable:o}})(e.data);t.numberOfChannels=n.outputChannelCount,t.sampleRate=We,t.codecInfo.opusInfo={preSkip:n.preSkip},qt(r.data.subarray(8),this.metadataTags)})}readPacket(e,t){return d(this,null,function*(){y(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 d(this,null,function*(){return yield this.readMetadata(),this.trackBackings})}getMetadataTags(){return d(this,null,function*(){return yield this.readMetadata(),this.metadataTags})}}class Rr{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new D,this.internalSampleRate="opus"===e.codecInfo.codec?We:e.sampleRate}getType(){return"audio"}getId(){return this.bitstream.serialNumber}getNumber(){const e=this.demuxer.trackBackings.findIndex(e=>e.bitstream===this.bitstream);return y(-1!==e),e+1}getNumberOfChannels(){return this.bitstream.numberOfChannels}getSampleRate(){return this.bitstream.sampleRate}getTimeResolution(){return this.bitstream.sampleRate}isRelativeToUnixEpoch(){return!1}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return d(this,null,function*(){return null})}getLiveRefreshInterval(){return d(this,null,function*(){return null})}getCodec(){return this.bitstream.codecInfo.codec}getInternalCodecId(){return null}getDecoderConfig(){return d(this,null,function*(){var e;return y(this.bitstream.codecInfo.codec),{codec:this.bitstream.codecInfo.codec,numberOfChannels:this.bitstream.numberOfChannels,sampleRate:this.bitstream.sampleRate,description:null!=(e=this.bitstream.description)?e:void 0}})}getName(){return null}getLanguageCode(){return Q}getDisposition(){return u(c({},Be),{primary:!1})}granulePositionToTimestampInSamples(e){return"opus"===this.bitstream.codecInfo.codec?(y(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,i){if(!e)return null;const{durationInSamples:r,vorbisBlockSize:n}=Cr(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),s=new Yt(i.metadataOnly?Gt:e.data,"key",Math.max(0,t.timestampInSamples)/this.internalSampleRate,r/this.internalSampleRate,e.endPage.headerStartPos+e.endSegmentIndex,e.data.byteLength);return this.encodedPacketToMetadata.set(s,{packet:e,timestampInSamples:t.timestampInSamples,durationInSamples:r,vorbisLastBlockSize:t.vorbisLastBlocksize,vorbisBlockSize:n}),s}getFirstPacket(e){return d(this,null,function*(){y(this.bitstream.lastMetadataPacket);const t=yield this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let i=0;"opus"===this.bitstream.codecInfo.codec&&(y(this.bitstream.codecInfo.opusInfo),i-=this.bitstream.codecInfo.opusInfo.preSkip);const r=yield this.demuxer.readPacket(t.startPage,t.startSegmentIndex);return this.createEncodedPacketFromOggPacket(r,{timestampInSamples:i,vorbisLastBlocksize:null},e)})}getNextPacket(e,t){return d(this,null,function*(){const i=this.encodedPacketToMetadata.get(e);if(!i)throw new Error("Packet was not created from this track.");const r=yield this.demuxer.findNextPacketStart(i.packet);if(!r)return null;const n=i.timestampInSamples+i.durationInSamples,s=yield this.demuxer.readPacket(r.startPage,r.startSegmentIndex);return this.createEncodedPacketFromOggPacket(s,{timestampInSamples:n,vorbisLastBlocksize:i.vorbisBlockSize},t)})}getPacket(e,t){return d(this,null,function*(){var i,r;if(null===this.demuxer.reader.fileSize)return this.getPacketSequential(e,t);const n=G(e*this.internalSampleRate);if(0===n)return this.getFirstPacket(t);if(n<0)return null;y(this.bitstream.lastMetadataPacket);const s=yield this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!s)return null;let a=s.startPage,o=this.demuxer.reader.fileSize;const l=[a];e:for(;a.headerStartPos+a.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,Br,Er);t instanceof Promise&&(t=yield t),y(t);const i=_r(t);y(i),u=i,u.serialNumber===this.bitstream.serialNumber&&d.push(u)}y(-1!==u.granulePosition);let h,f,m=null,p=u,g=0;if(u.headerStartPos===s.startPage.headerStartPos)h=this.granulePositionToTimestampInSamples(0),f=!0,m=0;else{h=0,f=!1;for(let t=u.lacingValues.length-1;t>=0;t--){if(u.lacingValues[t]<255){m=t+1;break}}if(null===m)throw new Error("Invalid page with granule position: no packets end on this page.");g=m-1;const e={data:Gt,endPage:p,endSegmentIndex:g};if(yield this.demuxer.findNextPacketStart(e)){const e=Mr(d,u,m);y(e);const t=Dr(d,e.page,e.segmentIndex);t&&(u=t.page,m=t.segmentIndex)}else for(;;){const e=Mr(d,u,m);if(!e)break;const t=Dr(d,e.page,e.segmentIndex);if(!t)break;if(u=t.page,m=t.segmentIndex,e.page.headerStartPos!==p.headerStartPos){p=e.page,g=e.segmentIndex;break}}}let k=null,b=null;for(;null!==u;){y(null!==m);const e=yield this.demuxer.readPacket(u,m);if(!e)break;if(!(u.headerStartPos===s.startPage.headerStartPos&&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 d(this,null,function*(){const i=yield this.sequentialScanMutex.acquire();try{const i=G(e*this.internalSampleRate);e=i/this.internalSampleRate;const r=z(this.sequentialScanCache,i,e=>e.timestampInSamples);let n;if(-1!==r){const e=this.sequentialScanCache[r];n=this.createEncodedPacketFromOggPacket(e.packet,{timestampInSamples:e.timestampInSamples,vorbisLastBlocksize:e.vorbisLastBlockSize},t)}else n=yield this.getFirstPacket(t);let s=0;for(;n&&n.timestampe)break;if(n=i,s++,100===s){s=0;const e=this.encodedPacketToMetadata.get(n);y(e),this.sequentialScanCache.length>0&&y(T(this.sequentialScanCache).timestampInSamples<=e.timestampInSamples),this.sequentialScanCache.push(e)}}return n}finally{i()}})}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const Dr=(e,t,i)=>{let r=t,n=i;e:for(;;){for(n--;n>=0;n--){if(r.lacingValues[n]<255){n++;break e}}y(-1===n);if(!(1&r.headerType)){n=0;break}const t=W(e,e=>e.headerStartPos{if(i>0)return{page:t,segmentIndex:i-1};const r=W(e,e=>e.headerStartPosd(this,null,function*(){var e,t;let i=this.reader.requestSlice(0,12);i instanceof Promise&&(i=yield i),y(i);const r=Wa(i,4),n="RIFX"!==r,s="RF64"===r,a=Fa(i,n);let o=s?this.reader.fileSize:Math.min(a+8,null!=(e=this.reader.fileSize)?e:1/0);if("WAVE"!==Wa(i,4))throw new Error("Invalid WAVE file - wrong format");let l=0,c=null,u=i.filePos;for(;null===o||u=18&&357!==n){const e=Ba(r,i),s=t-18;if(Math.min(s,e)>=22&&n===Nr.EXTENSIBLE){r.skip(6);const e=xa(r,16);n=e[0]|e[1]<<8}}n!==Nr.MULAW&&n!==Nr.ALAW||(l=8),this.audioInfo={format:n,numberOfChannels:s,sampleRate:a,sampleSizeInBytes:Math.ceil(l/8),blockSizeInBytes:o}})}parseListChunk(e,t,i){return d(this,null,function*(){var r,n,s,a,o,l,c,u,d,h,f;let m=this.reader.requestSlice(e,t);if(m instanceof Promise&&(m=yield m),!m)return;const p=Wa(m,4);if("INFO"!==p&&"INF0"!==p)return;let g=m.filePos;for(;g<=e+t-8;){m.filePos=g;const e=Wa(m,4),t=Fa(m,i),p=xa(m,t);let k=0;for(let i=0;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 d(this,null,function*(){let i=this.reader.requestSlice(e,t);if(i instanceof Promise&&(i=yield i),!i)return;const r=Za(i);if(r){const n=t-Qa;if(r.size=Math.min(r.size,n),r.size>0){const t=i.slice(e+Qa,r.size);eo(t,r,this.metadataTags)}}})}getCodec(){if(y(this.audioInfo),this.audioInfo.format===Nr.MULAW)return"ulaw";if(this.audioInfo.format===Nr.ALAW)return"alaw";if(this.audioInfo.format===Nr.PCM){if(1===this.audioInfo.sampleSizeInBytes)return"pcm-u8";if(2===this.audioInfo.sampleSizeInBytes)return"pcm-s16";if(3===this.audioInfo.sampleSizeInBytes)return"pcm-s24";if(4===this.audioInfo.sampleSizeInBytes)return"pcm-s32"}return this.audioInfo.format===Nr.IEEE_FLOAT&&4===this.audioInfo.sampleSizeInBytes?"pcm-f32":null}getMimeType(){return d(this,null,function*(){return"audio/wav"})}getTrackBackings(){return d(this,null,function*(){return yield this.readMetadata(),this.trackBackings})}getMetadataTags(){return d(this,null,function*(){return yield this.readMetadata(),this.metadataTags})}}const zr=2048;class Ur{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return y(this.demuxer.audioInfo),this.demuxer.audioInfo.format}getDecoderConfig(){return d(this,null,function*(){const e=this.demuxer.getCodec();return e?(y(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null})}getNumberOfChannels(){return y(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return y(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return y(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return d(this,null,function*(){return y(-1!==this.demuxer.dataSize),this.demuxer.dataSize/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate})}getLiveRefreshInterval(){return d(this,null,function*(){return null})}getName(){return null}getLanguageCode(){return Q}getDisposition(){return c({},Be)}getPacketAtIndex(e,t){return d(this,null,function*(){y(e>=0),y(this.demuxer.audioInfo);const i=e*zr*this.demuxer.audioInfo.blockSizeInBytes;if(i>=this.demuxer.dataSize)return null;const r=Math.min(zr*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-i);if(null===this.demuxer.reader.fileSize){let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+i,r);if(e instanceof Promise&&(e=yield e),!e)return null}let n;if(t.metadataOnly)n=Gt;else{let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+i,r);e instanceof Promise&&(e=yield e),y(e),n=xa(e,r)}const s=e*zr/this.demuxer.audioInfo.sampleRate,a=r/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(e,this.demuxer.lastKnownPacketIndex),new Yt(n,"key",s,a,e,r)})}getFirstPacket(e){return this.getPacketAtIndex(0,e)}getPacket(e,t){return d(this,null,function*(){y(this.demuxer.audioInfo);const i=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/zr,(this.demuxer.dataSize-1)/(zr*this.demuxer.audioInfo.blockSizeInBytes)));if(i<0)return null;const r=yield this.getPacketAtIndex(i,t);if(r)return r;if(0===i)return null;y(null===this.demuxer.reader.fileSize);let n=yield this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,t);for(;n;){const e=yield this.getNextPacket(n,t);if(!e)break;n=e}return n})}getNextPacket(e,t){y(this.demuxer.audioInfo);const i=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/zr);return this.getPacketAtIndex(i+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const qr=e=>{const t=e.filePos,i=xa(e,9),r=new Ee(i);if(4095!==r.readBits(12))return null;r.skipBits(1);if(0!==r.readBits(2))return null;const n=r.readBits(1),s=r.readBits(2)+1,a=r.readBits(4);if(15===a)return null;r.skipBits(1);const o=r.readBits(3);if(0===o)throw new Error("ADTS frames with channel configuration 0 are not supported.");r.skipBits(1),r.skipBits(1),r.skipBits(1),r.skipBits(1);const l=r.readBits(13);r.skipBits(11);const c=r.readBits(2)+1;if(1!==c)throw new Error("ADTS frames with more than one AAC frame are not supported.");let u=null;return 1===n?e.filePos-=2:u=r.readBits(16),{objectType:s,samplingFrequencyIndex:a,channelConfiguration:o,frameLength:l,numberOfAacFrames:c,crcCheck:u,startPos:t}},Wr=1024;class Vr extends Qt{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.trackBackings=[],this.readingMutex=new D,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}readMetadata(){return d(this,null,function*(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>d(this,null,function*(){for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)yield this.advanceReader();y(this.firstFrameHeader),this.trackBackings=[new Hr(this)]}))()})}advanceReader(){return d(this,null,function*(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,Qa);if(e instanceof Promise&&(e=yield e),!e)return void(this.lastSampleLoaded=!0);const t=Za(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}let e=this.reader.requestSliceRange(this.lastLoadedPos,7,9);if(e instanceof Promise&&(e=yield e),!e)return void(this.lastSampleLoaded=!0);const t=qr(e);if(!t)return void(this.lastSampleLoaded=!0);if(null!==this.reader.fileSize&&t.startPos+t.frameLength>this.reader.fileSize)return void(this.lastSampleLoaded=!0);this.firstFrameHeader||(this.firstFrameHeader=t);const i=_e[t.samplingFrequencyIndex];y(void 0!==i);const r=Wr/i,n={timestamp:this.nextTimestampInSamples/i,duration:r,dataStart:t.startPos,dataSize:t.frameLength};this.loadedSamples.push(n),this.nextTimestampInSamples+=Wr,this.lastLoadedPos=t.startPos+t.frameLength})}getMimeType(){return d(this,null,function*(){return"audio/aac"})}getTrackBackings(){return d(this,null,function*(){return yield this.readMetadata(),this.trackBackings})}getMetadataTags(){return d(this,null,function*(){const e=yield this.readingMutex.acquire();try{if(yield this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let e=0;for(;;){let t=this.reader.requestSlice(e,Qa);if(t instanceof Promise&&(t=yield t),!t)break;const i=Za(t);if(!i)break;let r=this.reader.requestSlice(t.filePos,i.size);if(r instanceof Promise&&(r=yield r),!r)break;eo(r,i,this.metadataTags),e=t.filePos+i.size}return this.metadataTags}finally{e()}})}}class Hr{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return this.getSampleRate()/Wr}isRelativeToUnixEpoch(){return!1}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return d(this,null,function*(){return null})}getLiveRefreshInterval(){return d(this,null,function*(){return null})}getName(){return null}getLanguageCode(){return Q}getCodec(){return"aac"}getInternalCodecId(){return y(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){y(this.demuxer.firstFrameHeader);const e=Ae[this.demuxer.firstFrameHeader.channelConfiguration];return y(void 0!==e),e}getSampleRate(){y(this.demuxer.firstFrameHeader);const e=_e[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return y(void 0!==e),e}getDisposition(){return c({},Be)}getDecoderConfig(){return d(this,null,function*(){return y(this.demuxer.firstFrameHeader),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate()}})}getPacketAtIndex(e,t){return d(this,null,function*(){if(-1===e)return null;const i=this.demuxer.loadedSamples[e];if(!i)return null;let r;if(t.metadataOnly)r=Gt;else{let e=this.demuxer.reader.requestSlice(i.dataStart,i.dataSize);if(e instanceof Promise&&(e=yield e),!e)return null;r=xa(e,i.dataSize)}return new Yt(r,"key",i.timestamp,i.duration,e,i.dataSize)})}getFirstPacket(e){return this.getPacketAtIndex(0,e)}getNextPacket(e,t){return d(this,null,function*(){const i=yield this.demuxer.readingMutex.acquire();try{const i=L(this.demuxer.loadedSamples,e.timestamp,e=>e.timestamp);if(-1===i)throw new Error("Packet was not created from this track.");const r=i+1;for(;r>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)yield this.demuxer.advanceReader();return this.getPacketAtIndex(r,t)}finally{i()}})}getPacket(e,t){return d(this,null,function*(){const i=yield this.demuxer.readingMutex.acquire();try{for(;;){const i=z(this.demuxer.loadedSamples,e,e=>e.timestamp);if(-1===i&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(i,t);if(i>=0&&i+1d(this,null,function*(){for(var e;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===Ca(s)){const t=s.filePos;if(Ca(s)!==(1===this.blockingBit?249:248)){s.filePos=t;continue}s.skip(-2);const i=s.filePos-e,r=this.readFlacFrameHeader({slice:s,isFirstPacket:!1});if(!r){s.filePos=t;continue}if(0===this.blockingBit){if(r.num-a.num!==1){s.filePos=t;continue}}else if(r.num-a.num!==a.blockSize){s.filePos=t;continue}return{num:a.num,blockSize:a.blockSize,sampleRate:a.sampleRate,size:i,isLastFrame:!1}}}})}readFlacFrameHeader({slice:e,isFirstPacket:t}){const i=e.filePos,r=xa(e,4),n=new Ee(r);if(32764!==n.readBits(15))return null;if(null===this.blockingBit){y(t);const e=n.readBits(1);this.blockingBit=e}else if(1===this.blockingBit){y(!t);if(1!==n.readBits(1))return null}else{if(0!==this.blockingBit)throw new Error("Invalid blocking bit");y(!t);if(0!==n.readBits(1))return null}const s=(e=>0===e?null:1===e?192:e>=2&&e<=5?144*o(2,e):6===e?"uncommon-u8":7===e?"uncommon-u16":e>=8&&e<=15?o(2,e):null)(n.readBits(4));if(!s)return null;y(this.audioInfo);const a=((e,t)=>{switch(e){case 0:return t;case 1:return 88200;case 2:return 176400;case 3:return 192e3;case 4:return 8e3;case 5:return 16e3;case 6:return 22050;case 7:return 24e3;case 8:return 32e3;case 9:return 44100;case 10:return 48e3;case 11:return 96e3;case 12:return"uncommon-u8";case 13:return"uncommon-u16";case 14:return"uncommon-u16-10";default:return null}})(n.readBits(4),this.audioInfo.sampleRate);if(!a)return null;n.readBits(4),n.readBits(3);if(0!==n.readBits(1))return null;const l=(e=>{let t=0;const i=new Ee(xa(e,1));for(;1===i.readBits(1);)t++;if(0===t)return i.readBits(7);const r=[],n=t-1,s=new Ee(xa(e,n)),a=8-t-1;for(let o=0;oe|t<"uncommon-u16"===t?Ea(e)+1:"uncommon-u8"===t?Ca(e)+1:"number"===typeof t?t:(H(t),void y(!1)))(e,s),u=((e,t)=>"uncommon-u16"===t?Ea(e):"uncommon-u16-10"===t?10*Ea(e):"uncommon-u8"===t?Ca(e):"number"===typeof t?t:null)(e,a);if(null===u)return null;if(u!==this.audioInfo.sampleRate)return null;const d=e.filePos-i,h=Ca(e);e.skip(-d),e.skip(-1);const f=(e=>{let t=0;for(const i of e){t^=i;for(let e=0;e<8;e++)0!==(128&t)?t=t<<1^7:t<<=1,t&=255}return t})(xa(e,d));return h!==f?null:{num:l,blockSize:c,sampleRate:u}}advanceReader(){return d(this,null,function*(){yield this.readMetadata(),y(null!==this.lastLoadedPos),y(this.audioInfo);const e=this.lastLoadedPos,t=yield this.readNextFlacFrame({startPos:e,isFirstPacket:0===this.loadedSamples.length});if(!t)return void(this.lastSampleLoaded=!0);const i=this.loadedSamples[this.loadedSamples.length-1],r={blockOffset:i?i.blockOffset+i.blockSize:0,blockSize:t.blockSize,byteOffset:e,byteSize:t.size};this.lastLoadedPos=this.lastLoadedPos+t.size,this.loadedSamples.push(r),t.isLastFrame&&(this.lastSampleLoaded=!0)})}}class jr{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return y(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return y(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return Q}getTimeResolution(){return y(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return d(this,null,function*(){return y(this.demuxer.audioInfo),0===this.demuxer.audioInfo.totalSamples?null:this.demuxer.audioInfo.totalSamples/this.demuxer.audioInfo.sampleRate})}getLiveRefreshInterval(){return d(this,null,function*(){return null})}getDisposition(){return c({},Be)}getDecoderConfig(){return d(this,null,function*(){return y(this.demuxer.audioInfo),{codec:"flac",numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}})}getPacket(e,t){return d(this,null,function*(){if(y(this.demuxer.audioInfo),e<0)throw new Error("Timestamp cannot be negative");const i=yield this.demuxer.readingMutex.acquire();try{for(;;){const i=z(this.demuxer.loadedSamples,e,e=>e.blockOffset/this.demuxer.audioInfo.sampleRate);if(-1===i){yield this.demuxer.advanceReader();continue}const r=this.demuxer.loadedSamples[i],n=r.blockOffset/this.demuxer.audioInfo.sampleRate;if(!(n+r.blockSize/this.demuxer.audioInfo.sampleRate<=e))return this.getPacketAtIndex(i,t);if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(this.demuxer.loadedSamples.length-1,t);yield this.demuxer.advanceReader()}}finally{i()}})}getNextPacket(e,t){return d(this,null,function*(){const i=yield this.demuxer.readingMutex.acquire();try{const i=e.sequenceNumber+1;if(this.demuxer.lastSampleLoaded&&i>=this.demuxer.loadedSamples.length)return null;for(;i>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)yield this.demuxer.advanceReader();return this.getPacketAtIndex(i,t)}finally{i()}})}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}getPacketAtIndex(e,t){return d(this,null,function*(){const i=this.demuxer.loadedSamples[e];if(!i)return null;let r;if(t.metadataOnly)r=Gt;else{let e=this.demuxer.reader.requestSlice(i.byteOffset,i.byteSize);if(e instanceof Promise&&(e=yield e),!e)return null;r=xa(e,i.byteSize)}y(this.demuxer.audioInfo);const n=i.blockOffset/this.demuxer.audioInfo.sampleRate,s=i.blockSize/this.demuxer.audioInfo.sampleRate;return new Yt(r,"key",n,s,e,i.byteSize)})}getFirstPacket(e){return d(this,null,function*(){for(;0===this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)yield this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)})}}const Xr=9e4,$r=188,Qr="PES packet is missing PTS where it was expected. PES packets without PTS are not currently supported. If you think this file should be supported, please report it.",Gr=new Set;class Yr extends Qt{constructor(e){super(e),this.metadataPromise=null,this.elementaryStreams=[],this.trackBackingEntries=[],this.packetOffset=0,this.packetStride=-1,this.sectionEndPositions=[],this.seekChunkSize=5242880,this.minReferencePointByteDistance=-1,this.reader=e._reader}readMetadata(){return d(this,null,function*(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>d(this,null,function*(){let e=this.reader.requestSlice(0,205);e instanceof Promise&&(e=yield e),y(e);const t=xa(e,205);if(71===t[0]&&71===t[188])this.packetOffset=0,this.packetStride=$r;else if(71===t[0]&&71===t[204])this.packetOffset=0,this.packetStride=204;else{if(71!==t[4]||71!==t[196])throw new Error("Unreachable.");this.packetOffset=4,this.packetStride=192}this.minReferencePointByteDistance=256*this.packetStride;let i=this.packetOffset,r=null,n=!1,s=!1;for(;;){const e=yield this.readPacketHeader(i);if(!e)break;if(0===e.payloadUnitStartIndicator){i+=this.packetStride;continue}const t=yield this.readSection(i,!0,!s);if(!t)break;const a=3,o=32;let l=!1;if(!s&&0!==t.pid){if(!(0===t.payload[0]&&0===t.payload[1]&&1===t.payload[2])){const e=new Ee(t.payload),i=e.readAlignedByte();e.skipBits(8*i);l=2===e.readBits(8)}}if(0!==t.pid||n)if(t.pid!==r&&!l||s){const e=this.elementaryStreams.find(e=>e.pid===t.pid);e:if(e&&!e.initialized){const i=Zr(t,!0);if(!i)throw new Error(`Couldn't read first PES packet for Elementary Stream with PID ${e.pid}`);if(e.firstSection=t,e.canBeTrustedWithKeyPackets=1===t.randomAccessIndicator,this.input._initInput){const i=(yield this.input._initInput._getDemuxer()).elementaryStreams.find(i=>i.pid===t.pid&&i.info.codec===e.info.codec);if(i){e.info=i.info,e.initialized=!0;break e}}const r=new sn(e,i);if("video"===e.info.type){for(;;){if(r.suppliedPacket=null,yield r.markNextPacket(),"avc"===e.info.codec){if(!r.suppliedPacket)throw new Error("Invalid AVC video stream; could not extract AVCDecoderConfigurationRecord from any packet.");if(e.info.avcCodecInfo=pt(r.suppliedPacket.data),!e.info.avcCodecInfo)continue;const t=e.info.avcCodecInfo.sequenceParameterSets[0];y(t);const i=kt(t);e.info.width=i.displayWidth,e.info.height=i.displayHeight;const n=i.pixelAspectRatio.num,s=i.pixelAspectRatio.den;n>0&&s>0&&(n>s?(e.info.squarePixelWidth=Math.round(e.info.width*n/s),e.info.squarePixelHeight=e.info.height):(e.info.squarePixelWidth=e.info.width,e.info.squarePixelHeight=Math.round(e.info.height*s/n))),e.info.colorSpace={primaries:B[i.colourPrimaries],transfer:_[i.transferCharacteristics],matrix:F[i.matrixCoefficients],fullRange:!!i.fullRangeFlag},e.info.reorderSize=i.maxDecFrameBuffering;break}if("hevc"===e.info.codec){if(!r.suppliedPacket)throw new Error("Invalid HEVC video stream; could not extract HVCDecoderConfigurationRecord from first packet.");if(e.info.hevcCodecInfo=vt(r.suppliedPacket.data),!e.info.hevcCodecInfo)continue;const t=e.info.hevcCodecInfo.arrays.find(e=>e.nalUnitType===st.SPS_NUT).nalUnits[0];y(t);const i=St(t);e.info.width=i.displayWidth,e.info.height=i.displayHeight,i.pixelAspectRatio.num>i.pixelAspectRatio.den?(e.info.squarePixelWidth=Math.round(e.info.width*i.pixelAspectRatio.num/i.pixelAspectRatio.den),e.info.squarePixelHeight=e.info.height):(e.info.squarePixelWidth=e.info.width,e.info.squarePixelHeight=Math.round(e.info.height*i.pixelAspectRatio.den/i.pixelAspectRatio.num)),e.info.colorSpace={primaries:B[i.colourPrimaries],transfer:_[i.transferCharacteristics],matrix:F[i.matrixCoefficients],fullRange:!!i.fullRangeFlag},e.info.reorderSize=i.maxDecFrameBuffering;break}throw new Error("Unhandled.")}e.info.decoderConfig={codec:Ue({width:e.info.width,height:e.info.height,codec:e.info.codec,codecDescription:null,colorSpace:e.info.colorSpace,avcType:1,avcCodecInfo:e.info.avcCodecInfo,hevcCodecInfo:e.info.hevcCodecInfo,vp9CodecInfo:null,av1CodecInfo:null}),codedWidth:e.info.width,codedHeight:e.info.height,colorSpace:e.info.colorSpace},e.info.width===e.info.squarePixelWidth&&e.info.height===e.info.squarePixelHeight||(e.info.decoderConfig.displayAspectWidth=e.info.squarePixelWidth,e.info.decoderConfig.displayAspectHeight=e.info.squarePixelHeight),e.initialized=!0}else{if(yield r.markNextPacket(),!r.suppliedPacket)throw new Error(`Couldn't parse first media packet for Elementary Stream with PID ${e.pid}`);if("aac"===e.info.codec){const t=Pa.tempFromBytes(r.suppliedPacket.data),i=qr(t);if(!i)throw new Error("Invalid AAC audio stream; could not read ADTS frame header from first packet.");e.info.aacCodecInfo={isMpeg2:!1,objectType:i.objectType},e.info.numberOfChannels=Ae[i.channelConfiguration],e.info.sampleRate=_e[i.samplingFrequencyIndex]}else if("mp3"===e.info.codec){const t=Ra(Pa.tempFromBytes(r.suppliedPacket.data)),i=Ye(t,r.suppliedPacket.data.byteLength);if(!i.header)throw new Error("Invalid MP3 audio stream; could not read frame header from first packet.");e.info.numberOfChannels=3===i.header.channel?1:2,e.info.sampleRate=i.header.sampleRate}else if("ac3"===e.info.codec){const t=Vt(r.suppliedPacket.data);if(!t)throw new Error("Invalid AC-3 audio stream; could not read sync frame from first packet.");if(3===t.fscod)throw new Error("Invalid AC-3 audio stream; reserved sample rate code found in first packet.");e.info.numberOfChannels=Wt[t.acmod]+t.lfeon,e.info.sampleRate=tt[t.fscod]}else{if("eac3"!==e.info.codec)throw new Error("Unhandled.");{const t=jt(r.suppliedPacket.data);if(!t)throw new Error("Invalid E-AC-3 audio stream; could not read sync frame from first packet.");const i=Xt(t);if(null===i)throw new Error("Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.");e.info.numberOfChannels=$t(t),e.info.sampleRate=i}}e.info.decoderConfig={codec:qe({codec:e.info.codec,codecDescription:null,aacCodecInfo:e.info.aacCodecInfo}),numberOfChannels:e.info.numberOfChannels,sampleRate:e.info.sampleRate},e.initialized=!0}}}else{const e=new Ee(t.payload),i=e.readAlignedByte();e.skipBits(8*i),e.skipBits(12);const r=e.readBits(12);e.skipBits(43),e.readBits(13),e.skipBits(6);const n=e.readBits(10);for(e.skipBits(8*n);8*(r+a)-e.pos>o;){const t=e.readBits(8);e.skipBits(3);const i=e.readBits(13);e.skipBits(6);const r=e.readBits(10),n=e.pos+8*r;let s=!1,a=!1;for(;e.poso;){const t=e.readBits(16);e.skipBits(3);const i=e.readBits(13);if(0!==t){if(null!==r)throw new Error("Only files with a single program are supported.");r=i}}if(null===r)throw new Error("Program Association Table must link to a Program Map Table.");n=!0}if(s&&this.elementaryStreams.every(e=>e.initialized))break;i+=this.packetStride}if(!s){if(!n)throw new Error("No Program Association Table found in the file.");throw new Error("No Program Map Table found in the file.")}for(const a of this.elementaryStreams)"video"===a.info.type?this.trackBackingEntries.push(new tn(a)):this.trackBackingEntries.push(new rn(a))}))()})}getTrackBackings(){return d(this,null,function*(){return yield this.readMetadata(),this.trackBackingEntries})}getMetadataTags(){return d(this,null,function*(){return{}})}getMimeType(){return d(this,null,function*(){yield this.readMetadata();return(e=>{let t="video/MP2T";const i=[...new Set(e.filter(Boolean))];return i.length>0&&(t+=`; codecs="${i.join(", ")}"`),t})(yield Promise.all(this.trackBackingEntries.map(e=>e.getDecoderConfig().then(e=>{var t;return null!=(t=null==e?void 0:e.codec)?t:null}))))})}readSection(e,t,i=!1){return d(this,null,function*(){let r=e,n=e;const s=[];let a,o=0,l=null,c=!0,u=0;for(;;){const e=yield this.readPacket(n);if(n+=this.packetStride,!e)break;if(l){if(e.pid!==l.pid){if(i)break;continue}if(1===e.payloadUnitStartIndicator)break}else{if(0===e.payloadUnitStartIndicator)break;l=e}const a=!!(2&e.adaptationFieldControl),d=!!(1&e.adaptationFieldControl);let h=0;if(a&&(h=1+e.body[0],e===l&&h>1&&(u=e.body[1]>>6&1)),d&&(0===h?(s.push(e.body),o+=e.body.byteLength):(s.push(e.body.subarray(h)),o+=e.body.byteLength-h)),r=n,!t&&o>=64){c=!1;break}if(-1!==L(this.sectionEndPositions,r,e=>e)){c=!1;break}}if(c){const e=z(this.sectionEndPositions,r,e=>e);this.sectionEndPositions.splice(e+1,0,r)}if(!l)return null;if(1===s.length)a=s[0];else{const e=s.reduce((e,t)=>e+t.length,0);a=new Uint8Array(e);let t=0;for(const i of s)a.set(i,t),t+=i.length}return{startPos:e,endPos:t?r:null,pid:l.pid,payload:a,randomAccessIndicator:u}})}readPacketHeader(e){return d(this,null,function*(){let t=this.reader.requestSlice(e,4);if(t instanceof Promise&&(t=yield t),!t)return null;if(71!==Ca(t))throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");const i=Ea(t);return{payloadUnitStartIndicator:i>>14&1,pid:8191&i,adaptationFieldControl:Ca(t)>>4&3}})}readPacket(e){return d(this,null,function*(){let t=this.reader.requestSlice(e,$r);if(t instanceof Promise&&(t=yield t),!t)return null;const i=xa(t,$r);if(71!==i[0])throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");const r=(i[1]<<8)+i[2];return{payloadUnitStartIndicator:r>>14&1,pid:8191&r,adaptationFieldControl:i[3]>>4&3,body:i.subarray(4)}})}}const Jr=(e,t)=>{if(e.payload.byteLength<3)return null;const i=new Ee(e.payload);if(1!==i.readBits(24))return null;const r=i.readBits(8);if(i.skipBits(16),188===r||190===r||191===r||240===r||241===r||255===r||242===r||248===r)return null;i.skipBits(8);const n=i.readBits(2);i.skipBits(14);let s=null;if(2===n||3===n)s=0,i.skipBits(4),s+=i.readBits(3)*(1<<30),i.skipBits(1),s+=32768*i.readBits(15),i.skipBits(1),s+=i.readBits(15);else if(t)throw new Error(Qr);return{sectionStartPos:e.startPos,sectionEndPos:e.endPos,pts:s,randomAccessIndicator:e.randomAccessIndicator}},Zr=(e,t)=>{y(null!==e.endPos);const i=Jr(e,t);if(!i)return null;const r=new Ee(e.payload);r.skipBits(32);const n=r.readBits(16);r.skipBits(16);const s=r.readBits(8),a=r.pos+8*s;r.pos=a;const o=a/8;y(Number.isInteger(o));const l=e.payload.subarray(o,n>0?6+n:e.payload.byteLength);return u(c({},i),{data:l})};class en{constructor(e){this.elementaryStream=e,this.packetBuffers=new WeakMap,this.packetSectionStarts=new WeakMap}getId(){return this.elementaryStream.pid}getNumber(){const e=this.elementaryStream.demuxer,t=this.elementaryStream.info.type;let i=0;for(const r of e.trackBackingEntries)if(r.getType()===t&&i++,y(r instanceof en),r.elementaryStream===this.elementaryStream)break;return i}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.elementaryStream.streamType}getName(){return null}getLanguageCode(){return Q}getDisposition(){return u(c({},Be),{primary:!1})}getTimeResolution(){return Xr}isRelativeToUnixEpoch(){return!1}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return d(this,null,function*(){return null})}getLiveRefreshInterval(){return d(this,null,function*(){return null})}createEncodedPacket(e,t,i){let r;return r=this.allPacketsAreKeyPackets()||1===e.randomAccessIndicator?"key":"delta",new Yt(i.metadataOnly?Gt:e.data,r,e.pts/Xr,Math.max(t/Xr,0),e.sequenceNumber,e.data.byteLength)}getFirstPacket(e){return d(this,null,function*(){const t=this.elementaryStream.firstSection;y(t);const i=Zr(t,!0);y(i);const r=new sn(this.elementaryStream,i),n=new an(this,r),s=yield n.readNext();if(!s)return null;const a=this.createEncodedPacket(s.packet,s.duration,e);return this.packetBuffers.set(a,n),this.packetSectionStarts.set(a,s.packet.sectionStartPos),a})}getNextPacket(e,t){return d(this,null,function*(){let i=this.packetBuffers.get(e);if(i){const r=yield i.readNext();if(!r)return null;this.packetBuffers.delete(e);const n=this.createEncodedPacket(r.packet,r.duration,t);return this.packetBuffers.set(n,i),this.packetSectionStarts.set(n,r.packet.sectionStartPos),n}const r=this.packetSectionStarts.get(e);if(void 0===r)throw new Error("Packet was not created from this track.");const n=this.elementaryStream.demuxer,s=yield n.readSection(r,!0);y(s);const a=Zr(s,!0);y(a);const o=new sn(this.elementaryStream,a);i=new an(this,o);const l=e.sequenceNumber;for(;;){const e=yield i.readNext();if(!e)return null;if(e.packet.sequenceNumber>l){const r=this.createEncodedPacket(e.packet,e.duration,t);return this.packetBuffers.set(r,i),this.packetSectionStarts.set(r,e.packet.sectionStartPos),r}}})}getNextKeyPacket(e,t){return d(this,null,function*(){let i=e;for(;;){if(i=yield this.getNextPacket(i,t),!i)return null;if("key"===i.type)return i}})}getPacket(e,t){return this.doPacketLookup(e,!1,t)}getKeyPacket(e,t){return this.doPacketLookup(e,!0,t)}doPacketLookup(e,t,i){return d(this,null,function*(){var r,n,s,a,o,l;const c=G(e*Xr),u=this.elementaryStream.demuxer,{reader:h,seekChunkSize:f}=u,m=this.elementaryStream.pid,p=(e,t,i)=>d(this,null,function*(){let r=e;for(;re.pts),w=-1!==v?S[v]:null;if(w&&c-w.pts<45e3)b=w.sectionStartPos;else{let e=0;if(null!==h.fileSize){const t=Math.ceil(h.fileSize/f);if(t>1){let i=0,r=t-1;for(e=i;i<=r;){const t=Math.floor((i+r)/2),n=J(t*f,u.packetStride)+k.sectionStartPos,s=n+f,a=yield p(n,s,!1);a?a.pesPacketHeader.pts<=c?(e=t,i=t+1):r=t-1:r=t-1}}}b=J(e*f,u.packetStride)+k.sectionStartPos}const P=yield p(b,null!=(r=h.fileSize)?r:1/0,!1);let I=null!=(n=null==P?void 0:P.pesPacketHeader)?n:null;I||(I=k);const x=this.getReorderSize(),C=(e,t)=>d(this,null,function*(){var r,n;const s=yield u.readSection(e,!0);y(s);const a=Zr(s,!0);y(a);const o=new sn(this.elementaryStream,a),l=new an(this,o);for(;;){if((null!=(n=null==(r=T(l.presentationOrderPackets))?void 0:r.pts)?n:-1/0)>=c)break;if(!(yield l.readNextPacket()))break}const d=V(l.presentationOrderPackets,t);if(-1===d)return null;const h=l.presentationOrderPackets[d],f=0===d?0:h.pts-l.presentationOrderPackets[d-1].pts;for(;l.decodeOrderPackets[0]!==h;)l.decodeOrderPackets.shift();l.lastDuration=f;const m=yield l.readNext();y(m);const p=this.createEncodedPacket(m.packet,m.duration,i);return this.packetBuffers.set(p,l),this.packetSectionStarts.set(p,m.packet.sectionStartPos),p});if(!t||this.allPacketsAreKeyPackets()){e:for(;;){let e=I.sectionStartPos+u.packetStride;for(;;){const t=yield u.readPacketHeader(e);if(!t)break e;if(t.pid===m&&1===t.payloadUnitStartIndicator){const t=yield u.readSection(e,!1);if(t){const e=Jr(t,!1);if(e&&null!==e.pts){if(e.pts>c)break e;I=e,nn(this.elementaryStream,I);break}}}e+=u.packetStride}}e:for(let e=0;e=u.packetOffset;){const t=yield u.readPacketHeader(e);if(!t)break e;if(t.pid===m&&1===t.payloadUnitStartIndicator){const t=yield u.readSection(e,!1);if(t){const e=Jr(t,!1);if(e&&null!==e.pts){I=e;break}}}e-=u.packetStride}}return C(I.sectionStartPos,e=>e.pts<=c)}{let e=b,t=null;const i=!this.elementaryStream.canBeTrustedWithKeyPackets;for(;;){let r=null;const n=e<=k.sectionStartPos;let d,b=null;if(n)d=k,b=g;else{const t=yield p(e,null!=(s=h.fileSize)?s:1/0,i);d=null!=(a=null==t?void 0:t.pesPacketHeader)?a:null,b=null!=(o=null==t?void 0:t.section)?o:null}let T=!1,S=0;e:for(;d&&!(null!==t&&d.sectionStartPos>=t);){if(d.pts<=c){let e;if(this.elementaryStream.canBeTrustedWithKeyPackets)e=1===d.randomAccessIndicator;else{y(b);const t=Zr(b,!0);y(t);const i=new sn(this.elementaryStream,t);yield i.markNextPacket(),e=1===(null==(l=i.suppliedPacket)?void 0:l.randomAccessIndicator)}e&&(r=d)}if(d.pts>c&&(T=!0),T&&(S++,S>x))break;let e=d.sectionStartPos+u.packetStride;for(;;){const t=yield u.readPacketHeader(e);if(!t)break e;if(t.pid===m&&1===t.payloadUnitStartIndicator){const t=yield u.readSection(e,i);if(t){const e=Jr(t,!1);if(e&&null!==e.pts){d=e,b=t,nn(this.elementaryStream,d);break}}}e+=u.packetStride}}if(r){let e=r;if(0===S)e:for(let r=0;r=u.packetOffset;){const r=yield u.readPacketHeader(t);if(!r)break e;if(r.pid===m&&1===r.payloadUnitStartIndicator){const r=yield u.readSection(t,i);if(r){const t=Jr(r,!1);if(t&&null!==t.pts){e=t;break}}}t-=u.packetStride}}const t=yield C(e.sectionStartPos,e=>e.pts<=c&&1===e.randomAccessIndicator);return y(t),t}if(n)return null;t=e,e=Math.max(J(e-k.sectionStartPos-f,u.packetStride)+k.sectionStartPos,k.sectionStartPos)}}})}}class tn extends en{getType(){return"video"}getCodec(){return this.elementaryStream.info.codec}getCodedWidth(){return this.elementaryStream.info.width}getCodedHeight(){return this.elementaryStream.info.height}getSquarePixelWidth(){return this.elementaryStream.info.squarePixelWidth}getSquarePixelHeight(){return this.elementaryStream.info.squarePixelHeight}getRotation(){return 0}getColorSpace(){return d(this,null,function*(){return this.elementaryStream.info.colorSpace})}canBeTransparent(){return d(this,null,function*(){return!1})}getDecoderConfig(){return d(this,null,function*(){return y(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig})}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}}class rn extends en{getType(){return"audio"}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}getDecoderConfig(){return d(this,null,function*(){return y(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig})}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 0}}const nn=(e,t)=>{const i=e.referencePesPackets,r=z(i,t.sectionStartPos,e=>e.sectionStartPos);if(r>=0){const n=i[r];if(t.pts<=n.pts)return!1;const s=e.demuxer.minReferencePointByteDistance;if(t.sectionStartPos-n.sectionStartPos=e?e:this.bufferData(e-t).then(()=>Math.min(this.endPos-this.currentPos,e))}getCurrentPesPacket(){const e=this.pesPackets[this.currentPesPacketIndex];return y(e),e}bufferData(e){return d(this,null,function*(){const t=this.endPos+e;for(;this.endPos=a)break;o=e;const i=n+o;if(o+4>=a){this.seekTo(i);break}const l=s[o+1],c=s[o+2],u=s[o+3];let d=0,h=null;if(0===l&&0===c&&1===u?(d=4,h=s[o+4]):0===l&&1===c&&(d=3,h=u),0===d){o++;continue}const f=i;if(null!==r){if(null!==h){const e="avc"===t?ut(h):Tt(h);if("avc"===t?e===rt.AUD:e===st.AUD_NUT){const e=f-r;return this.seekTo(r),this.supplyPacket(e,0)}}o+=d}else r=f,o+=d}if(e>6,a=63&n[4];if(3===s||a>37){this.seekTo(t+1);continue}const o=Ht[3*a+s];y(void 0!==o),this.seekTo(t),r=this.ensureBuffered(o),r instanceof Promise&&(r=yield r);const l=Math.round(13824e4/e.info.sampleRate);return this.supplyPacket(r,l)}if("eac3"===t){if(11!==i)continue;this.skip(-1);const t=this.currentPos;let r=this.ensureBuffered(5);if(r instanceof Promise&&(r=yield r),r<5)return;const n=this.readBytes(5);if(11!==n[0]||119!==n[1]){this.seekTo(t+1);continue}const s=2*(((7&n[2])<<8|n[3])+1),a=3===n[4]>>6?3:n[4]>>4&3,o=Kt[a];this.seekTo(t),r=this.ensureBuffered(s),r instanceof Promise&&(r=yield r);const l=256*o,c=Math.round(l*Xr/e.info.sampleRate);return this.supplyPacket(r,c)}throw new Error("Unhandled.")}{if(255!==i)continue;this.skip(-1);const t=this.currentPos;let r=this.ensureBuffered(4);if(r instanceof Promise&&(r=yield r),r<4)return;const n=this.readBytes(4),s=P(n).getUint32(0),a=Ye(s,null);if(a.header){this.seekTo(t);let i=this.ensureBuffered(a.header.totalSize);i instanceof Promise&&(i=yield i);const r=a.header.audioSamplesInFrame*Xr/e.info.sampleRate;return this.supplyPacket(i,Math.round(r))}this.seekTo(t+1)}}}if(r=0)}readNext(){return d(this,null,function*(){if(0===this.decodeOrderPackets.length){if(!(yield this.readNextPacket()))return null}yield this.ensureCurrentPacketHasNext();const e=this.decodeOrderPackets[0],t=this.presentationOrderPackets.indexOf(e);let i;if(y(-1!==t),t===this.presentationOrderPackets.length-1)i=this.lastDuration;else{i=this.presentationOrderPackets[t+1].pts-e.pts,this.lastDuration=i}for(this.decodeOrderPackets.shift();this.presentationOrderPackets.length>0;){const e=this.presentationOrderPackets[0];if(this.decodeOrderPackets.includes(e))break;this.presentationOrderPackets.shift()}return{packet:e,duration:i}})}readNextPacket(){return d(this,null,function*(){if(this.reachedEnd)return!1;let e;return this.context.suppliedPacket||(yield this.context.markNextPacket()),e=this.context.suppliedPacket,this.context.suppliedPacket=null,e?(this.decodeOrderPackets.push(e),this.processPacketThroughReorderBuffer(e),!0):(this.reachedEnd=!0,this.flushReorderBuffer(),!1)})}ensureCurrentPacketHasNext(){return d(this,null,function*(){const e=this.decodeOrderPackets[0];for(y(e);;){const t=this.presentationOrderPackets.indexOf(e);if(-1!==t&&t<=this.presentationOrderPackets.length-2)break;if(!(yield this.readNextPacket()))break}})}processPacketThroughReorderBuffer(e){if(this.reorderBuffer.push(e),this.reorderBuffer.length>this.reorderSize){let e=0;for(let i=1;ie.pts-t.pts),this.presentationOrderPackets.push(...this.reorderBuffer),this.reorderBuffer.length=0}}const on="application/vnd.apple.mpegurl",ln="#EXT-X-STREAM-INF:",cn="#EXT-X-I-FRAME-STREAM-INF:",un="#EXT-X-MEDIA:",dn="#EXTINF:",hn="#EXT-X-MAP:",fn="#EXT-X-KEY:",mn="#EXT-X-MEDIA-SEQUENCE:",pn="#EXT-X-BYTERANGE:",gn="#EXT-X-PROGRAM-DATE-TIME:",kn="#EXT-X-TARGETDURATION:",yn="#EXT-X-PLAYLIST-TYPE:",bn=e=>0===e.length||e.startsWith("#")&&!e.startsWith("#EXT");class Tn{constructor(e){this._attributes={};let t="",i="",r=!1,n=!1;for(let s=0;sd(this,null,function*(){const e=[];if(this.trackDeclarations){for(const t of this.trackDeclarations)if("video"===t.type){const i=Te(e,e=>"video"===e.getType())+1;e.push(new wn(this,t,i))}else if("audio"===t.type){const i=Te(e,e=>"audio"===e.getType())+1;e.push(new Pn(this,t,i))}}else{if(this.firstSegment=yield this.getFirstSegment({}),!this.firstSegment)return[];const t=this.getInputForSegment(this.firstSegment),i=yield t.getTracks();for(const r of i)if("video"===r.type){const t=Te(e,e=>"video"===e.getType())+1;e.push(new wn(this,{id:e.length+1,type:"video"},t))}else if("audio"===r.type){const t=Te(e,e=>"audio"===e.getType())+1;e.push(new Pn(this,{id:e.length+1,type:"audio"},t))}}return e}))()})}getFirstTimestampForInput(e){return d(this,null,function*(){const t=this.firstTimestampCache.get(e);if(void 0!==t)return t;const i=yield e.getFirstTimestamp();return this.firstTimestampCache.set(e,i),i})}getMediaOffset(e,t){return d(this,null,function*(){var i;const r=null!=(i=e.firstSegment)?i:e;let n;if(this.firstSegmentFirstTimestamps.has(r))n=this.firstSegmentFirstTimestamps.get(r);else{const e=this.getInputForSegment(r);n=yield this.getFirstTimestampForInput(e),this.firstSegmentFirstTimestamps.set(r,n)}if(r===e)return r.timestamp-n;const s=yield this.getFirstTimestampForInput(t),a=e.timestamp-r.timestamp,o=s-n-a;return Math.abs(o)<=Math.min(.25,a)?r.timestamp-n:e.timestamp-s})}dispose(){for(const e of this.inputCache)e.input.dispose();this.inputCache.length=0}}class vn{constructor(e,t,i){this.packetInfos=new WeakMap,this.hydrationPromise=null,this.firstInputTrack=null,this.segmentedInput=e,this.decl=t,this.number=i}hydrate(){var e;return null!=(e=this.hydrationPromise)?e:this.hydrationPromise=(()=>d(this,null,function*(){var e;if(null!=(e=this.segmentedInput).firstSegment||(e.firstSegment=yield this.segmentedInput.getFirstSegment({})),!this.segmentedInput.firstSegment)throw new Error("Missing first segment, can't retrieve track.");const t=this.segmentedInput.getInputForSegment(this.segmentedInput.firstSegment),i=(yield t.getTracks()).find(e=>e.type===this.decl.type&&e.number===this.number);if(!i)throw new Error("No matching track found in underlying media data.");this.firstInputTrack=i}))()}getId(){return this.decl.id}getType(){return this.decl.type}getNumber(){return this.number}delegate(e){return this.firstInputTrack?e():this.hydrate().then(e)}getDecoderConfig(){return d(this,null,function*(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())})}getHasOnlyKeyPackets(){return this.delegate(()=>{var e,t,i;return null!=(i=null==(t=(e=this.firstInputTrack._backing).getHasOnlyKeyPackets)?void 0:t.call(e))?i:null})}getPairingMask(){return BigInt("1")}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getInternalCodecId(){return this.delegate(()=>this.firstInputTrack._backing.getInternalCodecId())}getDisposition(){return this.delegate(()=>this.firstInputTrack._backing.getDisposition())}getLanguageCode(){return this.delegate(()=>this.firstInputTrack._backing.getLanguageCode())}getName(){return this.delegate(()=>this.firstInputTrack._backing.getName())}getTimeResolution(){return this.delegate(()=>this.firstInputTrack._backing.getTimeResolution())}isRelativeToUnixEpoch(){return d(this,null,function*(){return yield this.hydrate(),y(this.segmentedInput.firstSegment),this.segmentedInput.firstSegment.relativeToUnixEpoch})}getBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getBitrate())}getAverageBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getAverageBitrate())}getDurationFromMetadata(e){return this.segmentedInput.getDurationFromMetadata(e)}getLiveRefreshInterval(){return this.segmentedInput.getLiveRefreshInterval()}createAdjustedPacket(e,t,i){return d(this,null,function*(){y(e.sequenceNumber>=0),y(this.segmentedInput.firstSegment);const r=yield this.segmentedInput.getMediaOffset(t,i.input),n=t.timestamp-this.segmentedInput.firstSegment.timestamp,s=e.clone({timestamp:Y(e.timestamp+r,yield i.getTimeResolution()),sequenceNumber:Math.floor(1e8*n)+e.sequenceNumber});return this.packetInfos.set(s,{segment:t,track:i,sourcePacket:e}),s})}getFirstPacket(e){return d(this,null,function*(){yield this.hydrate(),y(this.segmentedInput.firstSegment),y(this.firstInputTrack);const t=yield this.firstInputTrack._backing.getFirstPacket(e);return t?this.createAdjustedPacket(t,this.segmentedInput.firstSegment,this.firstInputTrack):null})}getNextPacket(e,t){return this._getNextInternal(e,t,!1)}getNextKeyPacket(e,t){return this._getNextInternal(e,t,!0)}_getNextInternal(e,t,i){return d(this,null,function*(){const r=this.packetInfos.get(e);if(!r)throw new Error("Packet was not created from this track.");const n=i?yield r.track._backing.getNextKeyPacket(r.sourcePacket,t):yield r.track._backing.getNextPacket(r.sourcePacket,t);if(n)return this.createAdjustedPacket(n,r.segment,r.track);let s=r.segment;for(;;){const e=yield this.segmentedInput.getNextSegment(s,{skipLiveWait:t.skipLiveWait});if(!e)return null;const i=this.segmentedInput.getInputForSegment(e),n=(yield i.getTracks()).find(e=>e.type===r.track.type&&e.number===r.track.number);if(!n){s=e;continue}const a=yield n._backing.getFirstPacket(t);return a?this.createAdjustedPacket(a,e,n):null}})}getPacket(e,t){return this._getPacketInternal(e,t,!1)}getKeyPacket(e,t){return this._getPacketInternal(e,t,!0)}_getPacketInternal(e,t,i){return d(this,null,function*(){let r=yield this.segmentedInput.getSegmentAt(e,{skipLiveWait:t.skipLiveWait});if(!r)return null;for(yield this.hydrate();r;){const n=this.segmentedInput.getInputForSegment(r),s=(yield n.getTracks()).find(e=>e.type===this.firstInputTrack.type&&e.number===this.firstInputTrack.number);if(!s){r=yield this.segmentedInput.getPreviousSegment(r,{skipLiveWait:t.skipLiveWait});continue}const a=yield this.segmentedInput.getMediaOffset(r,n),o=e-a,l=i?yield s._backing.getKeyPacket(o,t):yield s._backing.getPacket(o,t);if(l)return this.createAdjustedPacket(l,r,s);r=yield this.segmentedInput.getPreviousSegment(r,{skipLiveWait:t.skipLiveWait})}return null})}}class wn extends vn{getType(){return"video"}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getCodedWidth(){return this.delegate(()=>this.firstInputTrack._backing.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.firstInputTrack._backing.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.firstInputTrack._backing.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.firstInputTrack._backing.getSquarePixelHeight())}getRotation(){return this.delegate(()=>this.firstInputTrack._backing.getRotation())}getColorSpace(){return d(this,null,function*(){return this.delegate(()=>this.firstInputTrack._backing.getColorSpace())})}canBeTransparent(){return d(this,null,function*(){return this.delegate(()=>this.firstInputTrack._backing.canBeTransparent())})}getDecoderConfig(){return d(this,null,function*(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())})}}class Pn extends vn{getType(){return"audio"}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getNumberOfChannels(){return this.delegate(()=>this.firstInputTrack._backing.getNumberOfChannels())}getSampleRate(){return this.delegate(()=>this.firstInputTrack._backing.getSampleRate())}getDecoderConfig(){return d(this,null,function*(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())})}}ke();const In=1/0;class xn extends Ie{constructor(){super(...arguments),this._disposed=!1,this._refCount=0,this._usedForHls=!1,this._sizePromise=null,this.onread=null}getSizeOrNull(){return d(this,null,function*(){var e;if(this._disposed)throw new va;return null!=(e=this._sizePromise)?e:this._sizePromise=(()=>d(this,null,function*(){let e=this._getFileSize();return void 0!==e||(yield this._read(0,1,0,In),e=this._getFileSize(),y(void 0!==e)),e}))()})}getSize(){return d(this,null,function*(){if(this._disposed)throw new va;const e=yield this.getSizeOrNull();if(null===e)throw new Error("Cannot determine the size of an unsized source.");return e})}slice(e,t){if(!Number.isInteger(e)||e<0)throw new TypeError("offset must be a non-negative integer.");if(void 0!==t&&(!Number.isInteger(t)||t<0))throw new TypeError("length, when provided, must be a non-negative integer.");return new zn(this,e,t)}_dispatchRead(e,t){var i;null==(i=this.onread)||i.call(this,e,t),this._emit("read",{start:e,end:t})}ref(){return new Cn(this)}}class Cn{constructor(e){if(this._freed=!1,e._disposed)throw new Error("Cannot ref a disposed source.");e._refCount++,this._source=e}get source(){if(!this._source)throw new Error("Can't get source; ref has already been freed.");return this._source}get freed(){return this._freed}free(){if(this._freed)throw new Error("Illegal operation: double free on SourceRef.");const e=this.source;y(e._refCount>0),e._refCount--,0===e._refCount&&(e._dispose(),e._disposed=!0),this._freed=!0,this._source=null}[Symbol.dispose](){this.freed||this.free()}}class Bn extends xn{constructor(e,t){if("string"!==typeof e)throw new TypeError("rootPath must be a string.");if("function"!==typeof t)throw new TypeError("requestHandler must be a function.");super(),this.rootPath=e,this.requestHandler=t}_resolveRequest(e){const t=this.requestHandler(e),i=e=>{var t;if(!(e instanceof xn||e instanceof Cn))throw new TypeError("requestHandler must return or resolve to a Source or SourceRef.");const i=e instanceof xn?e.ref():e;return(t=i.source)._usedForHls||(t._usedForHls=this._usedForHls),i};return t instanceof Promise?t.then(i):i(t)}}const En=(e,t)=>e.path===t.path;class _n extends Bn{constructor(){super(...arguments),this._root=null,this._rootRequest=null}_read(e,t,i,r){if(!this._root){if(!this._rootRequest){const e=this._resolveRequest({path:this.rootPath,isRoot:!0}),t=e=>{const t=e instanceof xn?e.ref():e;return this._root=t,this._rootRequest=null,t};e instanceof Promise?this._rootRequest=e.then(t):(t(e),y(this._root))}if(this._rootRequest)return this._rootRequest.then(n=>n.source._read(e,t,i,r))}return this._root.source._read(e,t,i,r)}_getFileSize(){if(this._root)return this._root.source._getFileSize()}_dispose(){this._root?this._root.free():this._rootRequest&&this._rootRequest.then(e=>e.free())}}class An extends xn{constructor(e,t={}){var i;if(!(e instanceof Blob))throw new TypeError("blob must be a Blob.");if(!t||"object"!==typeof t)throw new TypeError("options must be an object.");if(void 0!==t.maxCacheSize&&(!ye(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");super(),this._readers=new WeakMap,this._blob=e,this._orchestrator=new Ln({maxCacheSize:null!=(i=t.maxCacheSize)?i:8*o(2,20),maxWorkerCount:4,runWorker:this._runWorker.bind(this),prefetchProfile:On.fileSystem}),this._orchestrator.fileSize=e.size}_getFileSize(){return this._orchestrator.fileSize}_read(e,t,i,r){return this._orchestrator.read(e,t,i,r)}_runWorker(e){return d(this,null,function*(){y(e.strictTarget);let t=this._readers.get(e);if(void 0===t){if("stream"in this._blob&&!oe()){t=this._blob.slice(e.currentPos).stream().getReader()}else t=null;this._readers.set(e,t)}for(;e.currentPos{if(t instanceof Error&&(t.message.includes("Failed to fetch")||t.message.includes("Load failed")||t.message.includes("NetworkError when attempting to fetch resource"))){let e=null;try{"undefined"!==typeof window&&"undefined"!==typeof window.location&&(e=new URL(i instanceof Request?i.url:i,window.location.href).origin)}catch(r){}if(("undefined"===typeof navigator||"boolean"!==typeof navigator.onLine||navigator.onLine)&&null!==e&&e!==window.location.origin)return console.warn("Request will not be retried because a CORS error was suspected due to different origins. You can modify this behavior by providing your own function for the 'getRetryDelay' option."),null}return Math.min(o(2,e-2),16)},Dn=new Set;class Mn extends Bn{constructor(e,t={}){var i,r,n;if("string"!==typeof e&&!(e instanceof URL)&&!("undefined"!==typeof Request&&e instanceof Request))throw new TypeError("url must be a string, URL or Request.");if(!t||"object"!==typeof t)throw new TypeError("options must be an object.");if(void 0!==t.requestInit&&(!t.requestInit||"object"!==typeof t.requestInit))throw new TypeError("options.requestInit, when provided, must be an object.");if(void 0!==t.getRetryDelay&&"function"!==typeof t.getRetryDelay)throw new TypeError("options.getRetryDelay, when provided, must be a function.");if(void 0!==t.maxCacheSize&&(!ye(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(void 0!==t.parallelism&&(!Number.isInteger(t.parallelism)||t.parallelism<1))throw new TypeError("options.parallelism, when provided, must be a positive number.");if(void 0!==t.fetchFn&&"function"!==typeof t.fetchFn)throw new TypeError("options.fetchFn, when provided, must be a function.");super(e instanceof Request?e.url:e instanceof URL?e.href:e,e=>new Mn(e.path,this._options)),this._fileSizeDetermined=!1,this._url=e,this._options=t,this._getRetryDelay=null!=(i=t.getRetryDelay)?i:Rn;this._orchestrator=new Ln({maxCacheSize:null!=(r=t.maxCacheSize)?r:64*o(2,20),maxWorkerCount:null!=(n=t.parallelism)?n:2,runWorker:this._runWorker.bind(this),prefetchProfile:On.network})}_getFileSize(){return this._fileSizeDetermined?this._orchestrator.fileSize:void 0}_read(e,t,i,r){return this._orchestrator.read(e,t,i,r)}_runWorker(e){return d(this,null,function*(){for(var t,i;;){const n=new AbortController,s=yield ne(null!=(t=this._options.fetchFn)?t:fetch,this._url,ie(null!=(i=this._options.requestInit)?i:{},{headers:{Range:`bytes=${e.currentPos}-`},signal:n.signal}),this._getRetryDelay,()=>this._disposed);if(!s.ok)throw new Error(`Error fetching ${String(this._url)}: ${s.status} ${s.statusText}`);e:if(null===this._orchestrator.fileSize){const t=s.headers.get("Content-Range");if(t){const e=/\/(\d+)/.exec(t);if(e){this._orchestrator.supplyFileSize(Number(e[1]));break e}}const i=s.headers.get("Content-Length");i&&this._orchestrator.supplyFileSize(e.currentPos+Number(i))}if(this._fileSizeDetermined=!0,206!==s.status){if(!this._usedForHls){const e=new URL(this._url instanceof Request?this._url.url:this._url,"undefined"!==typeof window?window.location.href:void 0);"null"===e.origin||e.pathname.endsWith(".m3u8")||e.pathname.endsWith(".m3u")||Dn.has(e.origin)||(console.log(this._usedForHls,this._url,e.pathname),console.warn(`HTTP server (origin ${e.origin}) did not respond to a range request with 206 Partial Content, meaning the entire resource will now be downloaded. To enable efficient media file streaming across a network, please make sure your server supports range requests.`),Dn.add(e.origin))}e.currentPos=0,this._orchestrator.options.maxCacheSize=1/0,null!==this._orchestrator.fileSize?e.targetPos=this._orchestrator.fileSize:(e.targetPos=1/0,e.strictTarget=!1),this._orchestrator.consolidateEverythingIntoOneWorker(e)}if(!s.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");const a=s.body.getReader();for(;;){if(e.currentPos>=e.targetPos||e.aborted)return n.abort(),void this._orchestrator.signalWorkerStoppedRunning(e);let t;try{t=yield a.read()}catch(r){if(this._disposed)throw r;const e=this._getRetryDelay(1,r,this._url);if(null!==e){console.error("Error while reading response stream. Attempting to resume.",r),yield Pe(1e3*e);break}throw r}if(e.aborted)continue;const{done:i,value:s}=t;if(i){if(e.currentPos>=e.targetPos)return void this._orchestrator.onWorkerFinished(e);if(e.strictTarget)break;return void this._orchestrator.onWorkerFinished(e)}this._dispatchRead(e.currentPos,e.currentPos+s.length),this._orchestrator.supplyWorkerData(e,s)}}})}_dispose(){this._orchestrator.dispose()}}class Nn extends xn{constructor(e,t={}){var i;if(!(e instanceof ReadableStream))throw new TypeError("stream must be a ReadableStream.");if(!t||"object"!==typeof t)throw new TypeError("options must be an object.");if(void 0!==t.maxCacheSize&&(!ye(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");super(),this._reader=null,this._cache=[],this._pendingSlices=[],this._currentIndex=0,this._targetIndex=0,this._maxRequestedIndex=0,this._endIndex=null,this._pulling=!1,this._stream=e,this._maxCacheSize=null!=(i=t.maxCacheSize)?i:16*o(2,20)}_getFileSize(){return this._endIndex}_read(e,t){if(null!==this._endIndex&&t>this._endIndex)return null;this._maxRequestedIndex=Math.max(this._maxRequestedIndex,t);const i=z(this._cache,e,e=>e.start),r=-1!==i?this._cache[i]:null;if(r&&r.start<=e&&t<=r.end)return{bytes:r.bytes,view:r.view,offset:r.start};let n=e;const s=new Uint8Array(t-e);if(-1!==i)for(let c=i;c=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}=q();return this._pendingSlices.push({start:e,end:t,bytes:s,resolve:o,reject:l}),this._targetIndex=Math.max(this._targetIndex,t),this._pulling||(this._pulling=!0,this._pull().catch(e=>{if(this._pulling=!1,!(this._pendingSlices.length>0))throw e;this._pendingSlices.forEach(t=>t.reject(e)),this._pendingSlices.length=0})),a}_throwDueToCacheMiss(){throw new Error("Read is before the cached region. With ReadableStreamSource, you must access the data more sequentially or increase the size of its cache.")}_pull(){return d(this,null,function*(){for(null!=this._reader||(this._reader=this._stream.getReader());this._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;this._pendingSlices.length=0,this._cache.length=0,null==(e=this._reader)||e.cancel()}}const On={fileSystem:(e,t)=>{const i=o(2,16);return{start:e=Math.floor((e-i)/i)*i,end:t=Math.ceil((t+i)/i)*i}},network:(e,t,i)=>{const r=o(2,16);e=Math.max(0,Math.floor((e-r)/r)*r);for(const n of i){const i=8*o(2,20),r=Math.max((n.startPos+n.targetPos)/2,n.targetPos-i);if(pe(e,t,r,n.targetPos)){const e=n.targetPos-n.startPos,r=Math.ceil((e+1)/i)*i,s=o(2,Math.ceil(Math.log2(e+1))),a=Math.min(s,r);t=Math.max(t,n.startPos+a)}}return{start:e,end:t=Math.max(t,e+Fn)}}};class Ln{constructor(e){this.options=e,this.fileSize=null,this.nextAge=0,this.workers=[],this.cache=[],this.currentCacheSize=0,this.disposed=!1,this.queuedReads=[]}read(e,t,i,r){var n;y(!this.disposed);const s=this.options.prefetchProfile(e,t,this.workers),a=Math.max(s.start,i),o=Math.min(s.end,null!=(n=this.fileSize)?n:1/0,r);y(a<=e&&t<=o);let l=null;const c=z(this.cache,e,e=>e.start),u=-1!==c?this.cache[c]:null;u&&u.start<=e&&t<=u.end&&(u.age=this.nextAge++,l={bytes:u.bytes,view:u.view,offset:u.start});const d=z(this.cache,a,e=>e.start),h=l?null:new Uint8Array(t-e);let f=0,m=a;const p=[];if(-1!==d){for(let i=d;i=o)break;if(r.end<=a)continue;const n=Math.max(a,r.start),s=Math.min(o,r.end);if(y(n<=s),m=h.length&&(l={bytes:h,view:P(h),offset:e}),0===p.length)return y(l),l;const{promise:g,resolve:k,reject:b}=q(),T=[];for(const y of p){const i=Math.max(e,y.start),r=Math.min(t,y.end);i===y.start&&r===y.end?T.push(y):ie.hole.start),i=-1!==t?this.queuedReads[t]:null;for(i&&y.start<=i.hole.end?(i.hole.end=Math.max(i.hole.end,y.end),i.strictTarget&&(i.strictTarget=e),S&&i.pendingSlices.push(S)):(t++,i={hole:{start:y.start,end:y.end},strictTarget:e,pendingSlices:S?[S]:[],age:this.nextAge++},this.queuedReads.splice(t,0,i));t+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||(y(h),l=g.then(t=>t&&{bytes:t,view:P(t),offset:e})),l}checkHoleAgainstWorker(e,t,i){const r=o(2,17);if(pe(t.start-r,t.start,e.currentPos,e.targetPos)){e.targetPos=Math.max(e.targetPos,t.end);for(let t=0;t=this.options.maxWorkerCount){let e=null,t=null;for(let i=0;i{if(e.running=!1,!(e.pendingSlices.length>0))throw t;e.pendingSlices.forEach(e=>e.reject(t)),e.pendingSlices.length=0}).finally(()=>{if(!e.running&&this.queuedReads.length>0){let e=0;for(let r=1;re.targetPos&&(e.targetPos=e.currentPos,this.checkQueuedReadsAgainstWorker(e));for(let n=0;nt.start&&(t.start=r),t.end<=t.start&&(s.holes.splice(e,1),e--)}0===s.holes.length&&(s.resolve(s.bytes),e.pendingSlices.splice(n,1),n--)}for(let n=0;ne){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.pendingSlices.length=0}onWorkerFinished(e){const t=this.workers.indexOf(e);y(-1!==t),e.running=!1,this.workers.splice(t,1),null===this.fileSize&&this.supplyFileSize(e.currentPos);for(const i of e.pendingSlices)i.resolve(null)}insertIntoCache(e){if(0===this.options.maxCacheSize)return;let t=z(this.cache,e.start,e=>e.start)+1;if(t>0){const i=this.cache[t-1];if(i.end>=e.end)return;if(i.end>e.start){const r=new Uint8Array(e.end-i.start);r.set(i.bytes,0),r.set(e.bytes,e.start-i.start),this.currentCacheSize+=e.end-i.end,i.bytes=r,i.view=P(r),i.end=e.end,t--,e=i}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length;for(let i=t+1;i=t.end){this.cache.splice(i,1),this.currentCacheSize-=t.bytes.length,i--;continue}const r=new Uint8Array(t.end-e.start);r.set(e.bytes,0),r.set(t.bytes,t.start-e.start),this.currentCacheSize-=e.end-t.start,e.bytes=r,e.view=P(r),e.end=t.end,this.cache.splice(i,1);break}for(;this.currentCacheSize>this.options.maxCacheSize;){let e=0,t=this.cache[0];for(let i=1;ithis._length)return null;const n=this._baseSource._read(this._offset+e,this._offset+t,this._offset+i,this._offset+r);return n instanceof Promise?n.then(e=>e?(e.offset-=this._offset,e):null):n?(n.offset-=this._offset,n):null}_dispose(){var e;null==(e=this._ref)||e.free()}ref(){return null!=this._ref||(this._ref=this._baseSource.ref()),super.ref()}}var Un=function(e,t,i){if(null!==t&&void 0!==t){if("object"!==typeof t&&"function"!==typeof t)throw new TypeError("Object expected.");var r,n;if(i){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");r=t[Symbol.asyncDispose]}if(void 0===r){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");r=t[Symbol.dispose],i&&(n=r)}if("function"!==typeof r)throw new TypeError("Object not disposable.");n&&(r=function(){try{n.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:r,async:i})}else i&&e.stack.push({async:!0});return t},qn=function(e){return function(t){function i(i){t.error=t.hasError?new e(i,t.error,"An error was suppressed during disposal."):i,t.hasError=!0}var r,n=0;return function e(){for(;r=t.stack.pop();)try{if(!r.async&&1===n)return n=0,t.stack.push(r),Promise.resolve().then(e);if(r.dispose){var s=r.dispose.call(r.value);if(r.async)return n|=2,Promise.resolve(s).then(e,function(t){return i(t),e()})}else n|=1}catch(a){i(a)}if(1===n)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"===typeof SuppressedError?SuppressedError:function(e,t,i){var r=new Error(i);return r.name="SuppressedError",r.error=e,r.suppressed=t,r});const Wn=/^0[xX][0-9a-fA-F]+$/,Vn=/^data:.*;base64,/i;class Hn extends Sn{constructor(e,t,i,r){super(e.input,t,i),this.segments=[],this.nextLines=null,this.currentUpdateSegmentsPromise=null,this.streamHasEnded=!1,this.lastSegmentUpdateTime=-1/0,this.refreshInterval=5,this.demuxer=e,this.nextLines=r}runUpdateSegments(){var e;return null!=(e=this.currentUpdateSegmentsPromise)?e:this.currentUpdateSegmentsPromise=(()=>d(this,null,function*(){try{const e=this.getRemainingWaitTimeMs();e>0&&(yield Pe(e)),this.lastSegmentUpdateTime=performance.now(),yield this.updateSegments()}finally{this.currentUpdateSegmentsPromise=null}}))()}getRemainingWaitTimeMs(){const e=performance.now()-this.lastSegmentUpdateTime,t=Math.max(0,1e3*this.refreshInterval-e);return t<=50?0:t}updateSegments(){return d(this,null,function*(){var e,t,i,r,n,s,a;let l=this.nextLines;if(this.nextLines=null,!l){const e={stack:[],error:void 0,hasError:!1};try{const t=Un(e,yield this.demuxer.input._getSourceUncached({path:this.path,isRoot:!1}),!1),i=new wa(t.source),r=yield i.requestEntireFile();y(r),l=Va(r,r.length,{ignore:bn})}catch(E){e.error=E,e.hasError=!0}finally{qn(e)}}let d=!1,h=0,f=null,m=null,p=0,g=null,k=null,b=null,S=null,v=null,w=null,I=!1,x=null!=(e=T(this.segments))?e:null;const C=e=>{const t=e.indexOf("@"),i=Number(-1===t?e:e.slice(0,t));if(!Number.isInteger(i)||i<0)throw new Error(`Invalid #EXT-X-BYTERANGE length '${e}'.`);let r=null;if(-1!==t&&(r=Number(e.slice(t+1)),!Number.isInteger(r)||r<0))throw new Error(`Invalid #EXT-X-BYTERANGE offset '${e}'.`);return{length:i,offset:r}},B=e=>{p=e,x&&(y(null!==x.sequenceNumber),x.sequenceNumber0&&null!==w&&(h=p*w),I=!0);const t=e.slice(8),i=t.indexOf(","),r=-1===i?t:t.slice(0,i),n=Number(r);if(!Number.isFinite(n)||n<0)throw new Error(`Invalid #EXTINF tag duration '${r}'.`);f=n}else if(e.startsWith(hn)){const t=new Tn(e.slice(11)),i=t.get("uri");if(!i)throw new Error("Invalid #EXT-X-MAP tag; missing URI attribute.");const s=t.get("byterange");let a=null;if(null!==s&&(a=C(s)),a&&null===a.offset)throw new Error("Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset.");if(!x){const e={path:be(this.path,i),offset:null!=(r=null==a?void 0:a.offset)?r:0,length:null!=(n=null==a?void 0:a.length)?n:null};if("AES-128"===(null==m?void 0:m.method)&&!m.iv)throw new Error("IV attribute must be set on #EXT-X-KEY tag preceding the #EXT-X-MAP tag.");k={timestamp:h,relativeToUnixEpoch:null!==v,firstSegment:null,sequenceNumber:null,location:e,duration:0,encryption:m,initSegment:null,lastProgramDateTimeSeconds:v}}f=null,null===S?b=null:S=null}else if(e.startsWith(fn)){const t=new Tn(e.slice(11)),i=t.get("method");if("NONE"===i)m=null;else if("AES-128"===i){const e=t.get("uri");if(!e)throw new Error("Invalid #EXT-X-KEY: AES-128 requires a URI attribute.");let i=null;const r=t.get("iv");if(r){if(!Wn.test(r))throw new Error(`Unsupported IV format '${r}'.`);let e=r.slice(2);e=e.padStart(32,"0"),i=new Uint8Array(ai);for(let t=0;t=8&&112===i[4]&&115===i[5]&&115===i[6]&&104===i[7]){const e=P(i).getUint32(0);r=Jt(i.subarray(8,Math.min(e,i.length)))}}m={method:i,psshBox:r}}}}else if(e.startsWith(mn)){const t=e.slice(22),i=Number(t);if(!Number.isInteger(i)||i<0)throw new Error(`Invalid EXT-X-MEDIA-SEQUENCE value '${t}'.`);B(i)}else if(e.startsWith(pn)){const t=C(e.slice(17));if(null===t.offset){if(null===b)throw new Error("Invalid M3U8 file; #EXT-X-BYTERANGE without offset requires a previous byte range.");t.offset=b}S=t,b=t.offset+t.length}else if(e.startsWith(gn)){if(x)continue;const t=e.slice(25),i=Date.parse(t);if(!Number.isFinite(i))continue;const r=i/1e3;if(v===r)continue;if(null===v&&this.segments.length>0){const e=T(this.segments),t=r-(e.timestamp+e.duration);for(const i of this.segments)i.timestamp+=t,i.relativeToUnixEpoch=!0;h+=t}v=r,h=r}else if("#EXT-X-DISCONTINUITY"===e)g=null;else if(e.startsWith(kn)){const t=e.slice(22),i=Number(t);if(!Number.isFinite(i)||i<0)throw new Error(`Invalid EXT-X-TARGETDURATION value '${t}'.`);this.refreshInterval=i,w=i}else{if("#EXT-X-ENDLIST"===e){this.streamHasEnded=!0;break}if(e.startsWith(yn)){"vod"===e.slice(21).toLowerCase()&&(this.streamHasEnded=!0)}}}else{if("#EXTM3U"!==e)throw new Error("Invalid M3U8 file; expected first line to be #EXTM3U.");d=!0}}if(!d)throw new Error("Invalid M3U8 file; no #EXTM3U header.")})}getFirstSegment(){return d(this,null,function*(){var e;return 0===this.segments.length&&(yield this.runUpdateSegments()),null!=(e=this.segments[0])?e:null})}getSegmentAt(e,t){return d(this,null,function*(){0===this.segments.length&&(yield this.runUpdateSegments());let i=!!t.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){const r=z(this.segments,e,e=>e.timestamp);if(-1===r)return null;if(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=u(c({},this.input._formatOptions),{isobmff:u(c({},this.input._formatOptions.isobmff),{resolveKeyId:(null==(i=this.input._formatOptions.isobmff)?void 0:i.resolveKeyId)&&(e=>{if(!r.encryption||"SAMPLE-AES"!==r.encryption.method&&"SAMPLE-AES-CTR"!==r.encryption.method||!r.encryption.psshBox)return this.input._formatOptions.isobmff.resolveKeyId(e);let t=e.psshBoxes;const{psshBox:i}=r.encryption;return null!==i.keyIds&&!i.keyIds.includes(e.keyId)||t.some(e=>Zt(e,i))||(t=[...t,i]),this.input._formatOptions.isobmff.resolveKeyId(u(c({},e),{psshBoxes:t}))})})}),l=new Ta({source:new _n(r.location.path,e=>d(this,null,function*(){var t,i;y(e.isRoot);const n=u(c({},e),{isRoot:!1});let s;const a=r.location.offset>0||null!==r.location.length;if(r.encryption&&"SAMPLE-AES"!==r.encryption.method&&"SAMPLE-AES-CTR"!==r.encryption.method)if("AES-128"===r.encryption.method){const e=r.encryption;y(e.iv);let t=yield this.input._getSourceCached(n);if(a){const e=t.source.slice(r.location.offset,null!=(i=r.location.length)?i:void 0).ref();t.free(),t=e}const l=((e,t,i)=>{let r=!1,n=0;const s=o(2,16),a=new pi;return new ReadableStream({pull:o=>d(null,null,function*(){r||(a.init(yield t()),r=!0);const l=s+16;let c=e.requestSliceRange(n,0,l);if(c instanceof Promise&&(c=yield c),!c||0===c.length)throw new Error("Invalid ciphertext.");const u=c.length;if(u%16!==0)throw new Error("Invalid ciphertext.");const d=u===l?u-16:u,h=xa(c,d),f=new Uint8Array(d);for(let e=0;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 wa(t.source),()=>d(this,null,function*(){const t={stack:[],error:void 0,hasError:!1};try{const i=Un(t,yield this.input._getSourceCached({path:e.keyUri,isRoot:!1},ya),!1),r=new wa(i.source),n=yield r.requestSlice(0,ai);if(!n)throw new Error("Invalid AES-128 key; expected at least 16 bytes of data.");return{key:xa(n,ai),iv:e.iv}}catch(i){t.error=i,t.hasError=!0}finally{qn(t)}}),()=>{t.free()});s=new Nn(l).ref()}else y(!1);else if(s=yield this.input._getSourceCached(n),a){const e=s.source.slice(r.location.offset,null!=(t=r.location.length)?t:void 0).ref();s.free(),s=e}return s})),formats:this.input._formats.filter(e=>!(e instanceof us)),initInput:null!=s?s:void 0,formatOptions:a});l._onFormatDetermined=e=>{var t,i;if(("SAMPLE-AES"===(null==(t=r.encryption)?void 0:t.method)||"SAMPLE-AES-CTR"===(null==(i=r.encryption)?void 0:i.method))&&!e._isIsobmff)throw new Error("The SAMPLE-AES and SAMPLE-AES-CTR encryption methods are currently only supported for ISOBMFF files.")},this.inputCache.push({segment:r,input:l,age:this.nextInputCacheAge++});if(this.inputCache.length>4){const e=Se(this.inputCache,e=>e.age);y(-1!==e),this.inputCache.splice(e,1)}return l}getLiveRefreshInterval(){return d(this,null,function*(){return 0===this.getRemainingWaitTimeMs()&&(yield this.runUpdateSegments()),this.streamHasEnded?null:this.refreshInterval})}}class Kn extends Qt{constructor(e){super(e),this.metadataPromise=null,this.trackBackings=null,this.internalTracks=null,this.segmentedInputs=[],this.hasMasterPlaylist=!0}readMetadata(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>d(this,null,function*(){y(this.input._rootSource instanceof Bn);const{rootPath:e}=this.input._rootSource,t=yield this.input._reader.requestEntireFile();y(t);const i=Va(t,t.length,{ignore:bn}),r=[],n=[];for(let u=1;u"video"===e.attributes.get("type").toLowerCase()).map(e=>e.attributes.get("group-id")))],a=[...new Set(n.filter(e=>"audio"===e.attributes.get("type").toLowerCase()).map(e=>e.attributes.get("group-id")))],o=yield Promise.all(r.map((t,i)=>d(this,null,function*(){var r,o,l,c;const u=[],h=t.attributes.get("codecs");let f;if(h)f=h.split(",").map(e=>e.trim());else{const e=this.getSegmentedInputForPath(t.fullPath),i=yield e.getTrackBackings(),r=yield Promise.all(i.map(e=>d(this,null,function*(){return{track:e,codec:yield e.getCodec()}})));f=yield Promise.all(r.filter(e=>null!==e.codec).map(e=>e.track.getDecoderConfig().then(e=>e.codec)))}const m=t.attributes.get("video"),p=t.attributes.get("audio"),g=f.some(e=>Re.includes(Ke(e))),k=f.some(e=>Me.includes(Ke(e)));if(null!==m&&!g){if(!s.includes(m))throw new Error(`Invalid M3U8 file; variant stream references video group "${m}" which is not defined in any #EXT-X-MEDIA tags.`);const t=n.find(e=>{const t=e.attributes.get("group-id"),i=e.attributes.get("type");return t===m&&"video"===i.toLowerCase()});e:if(t){const i=t.attributes.get("uri");if(null===i)break e;const r=be(e,i),n=this.getSegmentedInputForPath(r),s=(yield n.getTrackBackings()).find(e=>"video"===e.getType());if(!s||null===(yield s.getCodec()))break e;const a=yield s.getDecoderConfig().then(e=>{var t;return null!=(t=null==e?void 0:e.codec)?t:null});y(null!==a),f.push(a)}}if(null!==p&&!k){if(!a.includes(p))throw new Error(`Invalid M3U8 file; variant stream references audio group "${p}" which is not defined in any #EXT-X-MEDIA tags.`);const t=n.find(e=>{const t=e.attributes.get("group-id"),i=e.attributes.get("type");return t===p&&"audio"===i.toLowerCase()});e:if(t){const i=t.attributes.get("uri");if(null===i)break e;const r=be(e,i),n=this.getSegmentedInputForPath(r),s=(yield n.getTrackBackings()).find(e=>"audio"===e.getType());if(!s||null===(yield s.getCodec()))break e;const a=yield s.getDecoderConfig().then(e=>{var t;return null!=(t=null==e?void 0:e.codec)?t:null});y(null!==a),f.push(a)}}f=[...new Set(f)];let b=null,T=null;const S=t.attributes.getAsNumber("bandwidth");y(null!==S);const v=t.attributes.getAsNumber("average-bandwidth"),w=t.attributes.get("name");for(const e of f){const d=Ke(e);if(null!==d)if(Re.includes(d)){if(null!==b)throw new Error("Unsupported M3U8 file; multiple video codecs found in the CODECS attribute of a variant stream.");b=e;const a=t.attributes.get("video");if(null===a){const e=t.attributes.get("resolution");let r=null,n=null;if(e){const t=e.match(/^(\d+)x(\d+)$/);t&&(r=Number(t[1]),n=Number(t[2]))}u.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:Q,lineNumber:t.lineNumber,fullPath:t.fullPath,fullCodecString:b,pairingMask:BigInt("1")<0?r:null}})}else{if(!a.includes(r))throw new Error(`Invalid M3U8 file; variant stream references audio group "${r}" which is not defined in any #EXT-X-MEDIA tags.`);for(const e of n){const n=e.attributes.get("group-id"),s=e.attributes.get("type");if(n!==r||"audio"!==s.toLowerCase())continue;const a=null!=(l=e.attributes.get("channels"))?l:t.attributes.get("channels"),o=null!==a?Number(a.split("/")[0]):null;u.push({id:-1,demuxer:this,backingTrack:null,default:Qn(e.attributes),autoselect:Qn(e.attributes)||Gn(e.attributes),languageCode:Yn(e.attributes.get("language")),lineNumber:e.lineNumber,fullPath:null!=(c=e.fullPath)?c:t.fullPath,fullCodecString:T,pairingMask:BigInt("1")<0?o:null}})}}}}return u}))),l=[],c=e=>{var t,i;const r=l.find(t=>t.fullPath===e.fullPath&&t.info.type===e.info.type);r?(r.pairingMask|=e.pairingMask,r.default||(r.default=e.default),r.autoselect||(r.autoselect=e.autoselect),r.lineNumber=Math.min(r.lineNumber,e.lineNumber),null!==e.peakBitrate&&(r.peakBitrate=Math.max(null!=(t=r.peakBitrate)?t:-1/0,e.peakBitrate)),null!==e.averageBitrate&&(r.averageBitrate=Math.max(null!=(i=r.averageBitrate)?i:-1/0,e.averageBitrate)),r.languageCode===Q&&(r.languageCode=e.languageCode)):(e.id=l.length+1,l.push(e))};for(const u of o)for(const e of u)c(e);l.sort((e,t)=>e.lineNumber-t.lineNumber),this.trackBackings=[];for(const u of l)"video"===u.info.type?this.trackBackings.push(new Xn(u)):this.trackBackings.push(new $n(u));this.internalTracks=l}))()}getTrackBackings(){return d(this,null,function*(){return yield this.readMetadata(),y(this.trackBackings),this.trackBackings})}getSegmentedInputForPath(e){let t=this.segmentedInputs.find(t=>t.path===e);if(t)return t;let i=null;if(this.internalTracks){i=this.internalTracks.filter(t=>t.fullPath===e).map(e=>({id:e.id,type:e.info.type}))}return t=new Hn(this,e,i,null),this.segmentedInputs.push(t),t}getMetadataTags(){return d(this,null,function*(){return{}})}getMimeType(){return d(this,null,function*(){return on})}dispose(){if(this.segmentedInputs){for(const e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}}class jn{constructor(e){this.internalTrack=e,this.hydrationPromise=null}hydrate(){var e;return null!=(e=this.hydrationPromise)?e:this.hydrationPromise=(()=>d(this,null,function*(){const e=this.internalTrack.demuxer.getSegmentedInputForPath(this.internalTrack.fullPath);let t=null;const i=(yield e.getTrackBackings()).filter(e=>e.getType()===this.getType());if(1===i.length)t=i[0];else if(this instanceof Xn){for(const r of i)if((yield r.getCodec())===this.getCodec()){t=r;break}}else{y(this instanceof $n);for(const e of i)if((yield e.getCodec())===this.getCodec()){t=e;break}}if(!t)throw new Error("Could not find matching track in underlying media data.");this.internalTrack.backingTrack=t}))()}delegate(e){return this.internalTrack.backingTrack?e():this.hydrate().then(e)}getCodec(){throw new Error("Not implemented on base class.")}getDisposition(){return u(c({},Be),{default:this.internalTrack.autoselect,primary:this.internalTrack.default})}getId(){return this.internalTrack.id}getPairingMask(){return this.internalTrack.pairingMask}getInternalCodecId(){return null}getLanguageCode(){return this.internalTrack.languageCode}getName(){return this.internalTrack.name}getNumber(){y(this.internalTrack.demuxer.internalTracks);const e=this.internalTrack.info.type;let t=0;for(const i of this.internalTrack.demuxer.internalTracks)if(i.info.type===e&&t++,i===this.internalTrack)break;return t}getTimeResolution(){return this.delegate(()=>this.internalTrack.backingTrack.getTimeResolution())}isRelativeToUnixEpoch(){return this.delegate(()=>this.internalTrack.backingTrack.isRelativeToUnixEpoch())}getBitrate(){return this.internalTrack.peakBitrate}getAverageBitrate(){return this.internalTrack.averageBitrate}getDurationFromMetadata(e){return d(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getDurationFromMetadata(e)})}getLiveRefreshInterval(){return d(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getLiveRefreshInterval()})}getHasOnlyKeyPackets(){return this.internalTrack.hasOnlyKeyPackets||null}getFirstPacket(e){return d(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getFirstPacket(e)})}getPacket(e,t){return d(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getPacket(e,t)})}getKeyPacket(e,t){return d(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getKeyPacket(e,t)})}getNextPacket(e,t){return d(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getNextPacket(e,t)})}getNextKeyPacket(e,t){return d(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getNextKeyPacket(e,t)})}}class Xn extends jn{constructor(e){super(e)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return"video"}getCodec(){return Ke(this.internalTrack.fullCodecString)}getCodedWidth(){return this.delegate(()=>this.backingVideoTrack.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.backingVideoTrack.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelHeight())}getMetadataDisplayWidth(){return this.backingVideoTrack?null:this.internalTrack.info.width}getMetadataDisplayHeight(){return this.backingVideoTrack?null:this.internalTrack.info.height}getRotation(){return this.delegate(()=>this.backingVideoTrack.getRotation())}getColorSpace(){return d(this,null,function*(){return yield this.hydrate(),this.backingVideoTrack.getColorSpace()})}canBeTransparent(){return d(this,null,function*(){return yield this.hydrate(),this.backingVideoTrack.canBeTransparent()})}getMetadataCodecParameterString(){return this.backingVideoTrack?null:this.internalTrack.fullCodecString}getDecoderConfig(){return d(this,null,function*(){return yield this.hydrate(),this.backingVideoTrack.getDecoderConfig()})}}class $n extends jn{constructor(e){super(e)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return"audio"}getCodec(){return Ke(this.internalTrack.fullCodecString)}getNumberOfChannels(){return null!==this.internalTrack.info.numberOfChannels?this.internalTrack.info.numberOfChannels:this.delegate(()=>this.backingAudioTrack.getNumberOfChannels())}getSampleRate(){return this.delegate(()=>this.backingAudioTrack.getSampleRate())}getMetadataCodecParameterString(){return this.backingAudioTrack?null:this.internalTrack.fullCodecString}getDecoderConfig(){return d(this,null,function*(){return yield this.hydrate(),this.backingAudioTrack.getDecoderConfig()})}}const Qn=e=>{const t=e.get("default");if(null===t)return!1;const i=t.toUpperCase();if("YES"===i)return!0;if("NO"===i)return!1;throw new Error(`Invalid M3U8 file; #EXT-X-MEDIA DEFAULT attribute must be YES or NO, got "${t}".`)},Gn=e=>{const t=e.get("autoselect");if(null===t)return!1;const i=t.toUpperCase();if("YES"===i)return!0;if("NO"===i)return!1;throw new Error(`Invalid M3U8 file; #EXT-X-MEDIA AUTOSELECT attribute must be YES or NO, got "${t}".`)},Yn=e=>{if(null===e)return Q;const t=e.split("-")[0];return t||Q};class Jn{constructor(){this._isIsobmff=!1}}class Zn extends Jn{constructor(){super(...arguments),this._isIsobmff=!0}_getMajorBrand(e){return d(this,null,function*(){let t=e._reader.requestSlice(0,12);if(t instanceof Promise&&(t=yield t),!t)return null;t.skip(4);const i=Wa(t,4);return"ftyp"!==i&&"styp"!==i?null:Wa(t,4)})}_createDemuxer(e){return new gi(e)}}class es extends Zn{_canReadInput(e){return d(this,null,function*(){const t=yield this._getMajorBrand(e);if(null!==t)return"qt "!==t;let i=e._reader.requestSlice(4,4);return i instanceof Promise&&(i=yield i),!!i&&"moof"===Wa(i,4)})}get name(){return"MP4"}get mimeType(){return"video/mp4"}}class ts extends Zn{_canReadInput(e){return d(this,null,function*(){return"qt "===(yield this._getMajorBrand(e))})}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}}class is extends Jn{isSupportedEBMLOfDocType(e,t){return d(this,null,function*(){let i=e._reader.requestSlice(0,Li);if(i instanceof Promise&&(i=yield i),!i)return!1;const r=zi(i);if(null===r)return!1;if(r<1||r>8)return!1;if(qi(i,r)!==Ri.EBML)return!1;const n=Vi(i);if("number"!==typeof n)return!1;let s=e._reader.requestSlice(i.filePos,n);if(s instanceof Promise&&(s=yield s),!s)return!1;const a=i.filePos;for(;s.filePos<=a+n-2;){const e=Hi(s);if(!e)break;const{id:i,size:r}=e,n=s.filePos;if(void 0===r)return!1;switch(i){case Ri.EBMLVersion:if(1!==qi(s,r))return!1;break;case Ri.EBMLReadVersion:if(1!==qi(s,r))return!1;break;case Ri.DocType:if(Ki(s,r)!==t)return!1;break;case Ri.DocTypeVersion:if(qi(s,r)>4)return!1}s.filePos=n+r}return!0})}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new kr(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}}class rs extends is{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}}class ns extends Jn{_canReadInput(e){return d(this,null,function*(){let t=0;for(;;){let i=e._reader.requestSlice(t,Qa);if(i instanceof Promise&&(i=yield i),!i)break;const r=Za(i);if(!r)break;t=i.filePos+r.size}const i=yield Sr(e._reader,t,t+4096);if(!i)return!1;const r=i.header,n=Ge(r.mpegVersionId,r.channel);let s=e._reader.requestSlice(i.startPos+n,4);if(s instanceof Promise&&(s=yield s),!s)return!1;const a=Ra(s);if(a===$e||a===Qe)return!0;t=i.startPos+i.header.totalSize;const o=yield Sr(e._reader,t,t+4);if(!o)return!1;const l=o.header;return r.channel===l.channel&&r.sampleRate===l.sampleRate})}_createDemuxer(e){return new vr(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}}class ss extends Jn{_canReadInput(e){return d(this,null,function*(){let t=e._reader.requestSlice(0,12);if(t instanceof Promise&&(t=yield t),!t)return!1;const i=Wa(t,4);if("RIFF"!==i&&"RIFX"!==i&&"RF64"!==i)return!1;t.skip(4);return"WAVE"===Wa(t,4)})}_createDemuxer(e){return new Lr(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}}class as extends Jn{_canReadInput(e){return d(this,null,function*(){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=yield t),!!t&&"OggS"===Wa(t,4)})}_createDemuxer(e){return new Fr(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}}class os extends Jn{_canReadInput(e){return d(this,null,function*(){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=yield t),!!t&&"fLaC"===Wa(t,4)})}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new Kr(e)}}class ls extends Jn{_canReadInput(e){return d(this,null,function*(){let t=0;for(;;){let i=e._reader.requestSlice(t,Qa);if(i instanceof Promise&&(i=yield i),!i)break;const r=Za(i);if(!r)break;t=i.filePos+r.size}let i=e._reader.requestSliceRange(t,7,9);if(i instanceof Promise&&(i=yield i),!i)return!1;const r=qr(i);if(!r)return!1;if(t+=r.frameLength,i=e._reader.requestSliceRange(t,7,9),i instanceof Promise&&(i=yield i),!i)return!1;const n=qr(i);return!!n&&(r.objectType===n.objectType&&r.samplingFrequencyIndex===n.samplingFrequencyIndex&&r.channelConfiguration===n.channelConfiguration)})}_createDemuxer(e){return new Vr(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}}class cs extends Jn{_canReadInput(e){return d(this,null,function*(){let t=e._reader.requestSlice(0,205);if(t instanceof Promise&&(t=yield t),!t)return!1;const i=xa(t,205);return 71===i[0]&&71===i[188]||(71===i[0]&&71===i[204]||71===i[4]&&71===i[196])})}_createDemuxer(e){return new Yr(e)}get name(){return"MPEG Transport Stream"}get mimeType(){return"video/MP2T"}}class us extends Jn{_canReadInput(e){return d(this,null,function*(){let t=e._reader.requestSlice(0,7);if(t instanceof Promise&&(t=yield t),!t)return!1;if(!("#EXTM3U"===Wa(t,7)))return!1;if(!(e._rootSource instanceof Bn))throw new TypeError("HLS inputs require `InputOptions.source` to be a PathedSource or a ref to one.");return e._rootSource._usedForHls=!0,!0})}_createDemuxer(e){return new Kn(e)}get name(){return"HTTP Live Streaming (HLS)"}get mimeType(){return on}}const ds=new es,hs=new ts,fs=new is,ms=new rs,ps=new ns,gs=new ss,ks=new as,ys=new ls,bs=new os,Ts=new cs,Ss=new us,vs=[Ss,ds,hs,fs,ms,gs,ks,bs,ps,ys,Ts],ws=[Ss,ds,hs,ps,ys,Ts];ke();let Ps=-1/0,Is=-1/0,xs=null;"undefined"!==typeof FinalizationRegistry&&(xs=new FinalizationRegistry(e=>{const t=performance.now();"video"===e.type?(t-Ps>=1e3&&(console.error("A VideoSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your VideoSamples as soon as you're done using them."),Ps=t),"undefined"!==typeof VideoFrame&&e.data instanceof VideoFrame&&e.data.close()):(t-Is>=1e3&&(console.error("An AudioSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your AudioSamples as soon as you're done using them."),Is=t),"undefined"!==typeof AudioData&&e.data instanceof AudioData&&e.data.close())}));const Cs=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],Bs=new Set(Cs);class Es{get codedWidth(){return this.visibleRect.width}get codedHeight(){return this.visibleRect.height}get displayWidth(){return this.rotation%180===0?this.squarePixelWidth:this.squarePixelHeight}get displayHeight(){return this.rotation%180===0?this.squarePixelHeight:this.squarePixelWidth}get microsecondTimestamp(){return Math.trunc(te*this.timestamp)}get microsecondDuration(){return Math.trunc(te*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor(e,t){var i,r,n,s,a,o,l,c,u,d,h,f,m,p,g,k,b,T,S,v,P,I,x,C,B,E;if(this._closed=!1,e instanceof ArrayBuffer||"undefined"!==typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e)){if(!t||"object"!==typeof t)throw new TypeError("init must be an object.");if(void 0===t.format||!Bs.has(t.format))throw new TypeError("init.format must be one of: "+Cs.join(", "));if(!Number.isInteger(t.codedWidth)||t.codedWidth<=0)throw new TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(t.codedHeight)||t.codedHeight<=0)throw new TypeError("init.codedHeight must be a positive integer.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(void 0!==t.duration&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(void 0!==t.layout){if(!Array.isArray(t.layout))throw new TypeError("init.layout, when provided, must be an array.");for(const e of t.layout){if(!e||"object"!==typeof e||Array.isArray(e))throw new TypeError("Each entry in init.layout must be an object.");if(!Number.isInteger(e.offset)||e.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(e.stride)||e.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(void 0!==t.visibleRect&&we(t.visibleRect,"init.visibleRect"),void 0!==t.displayWidth&&(!Number.isInteger(t.displayWidth)||t.displayWidth<=0))throw new TypeError("init.displayWidth, when provided, must be a positive integer.");if(void 0!==t.displayHeight&&(!Number.isInteger(t.displayHeight)||t.displayHeight<=0))throw new TypeError("init.displayHeight, when provided, must be a positive integer.");if(void 0!==t.displayWidth!==(void 0!==t.displayHeight))throw new TypeError("init.displayWidth and init.displayHeight must be either both provided or both omitted.");this._data=w(e).slice(),this._layout=null!=(i=t.layout)?i:Ms(t.format,t.codedWidth,t.codedHeight),this.format=t.format,this.rotation=null!=(r=t.rotation)?r:0,this.timestamp=t.timestamp,this.duration=null!=(n=t.duration)?n:0,this.colorSpace=new _s(t.colorSpace),this.visibleRect={left:null!=(a=null==(s=t.visibleRect)?void 0:s.left)?a:0,top:null!=(l=null==(o=t.visibleRect)?void 0:o.top)?l:0,width:null!=(u=null==(c=t.visibleRect)?void 0:c.width)?u:t.codedWidth,height:null!=(h=null==(d=t.visibleRect)?void 0:d.height)?h:t.codedHeight},void 0!==t.displayWidth?(this.squarePixelWidth=this.rotation%180===0?t.displayWidth:t.displayHeight,this.squarePixelHeight=this.rotation%180===0?t.displayHeight:t.displayWidth):(this.squarePixelWidth=this.codedWidth,this.squarePixelHeight=this.codedHeight)}else if("undefined"!==typeof VideoFrame&&e instanceof VideoFrame){if(void 0!==(null==t?void 0:t.rotation)&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(void 0!==(null==t?void 0:t.timestamp)&&!Number.isFinite(null==t?void 0:t.timestamp))throw new TypeError("init.timestamp, when provided, must be a number.");if(void 0!==(null==t?void 0:t.duration)&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");void 0!==(null==t?void 0:t.visibleRect)&&we(t.visibleRect,"init.visibleRect"),this._data=e,this._layout=null,this.format=e.format,this.visibleRect={left:null!=(m=null==(f=e.visibleRect)?void 0:f.x)?m:0,top:null!=(g=null==(p=e.visibleRect)?void 0:p.y)?g:0,width:null!=(b=null==(k=e.visibleRect)?void 0:k.width)?b:e.codedWidth,height:null!=(S=null==(T=e.visibleRect)?void 0:T.height)?S:e.codedHeight},this.rotation=null!=(v=null==t?void 0:t.rotation)?v:0,this.squarePixelWidth=e.displayWidth,this.squarePixelHeight=e.displayHeight,this.timestamp=null!=(P=null==t?void 0:t.timestamp)?P:e.timestamp/1e6,this.duration=null!=(x=null==t?void 0:t.duration)?x:(null!=(I=e.duration)?I:0)/1e6,this.colorSpace=new _s(e.colorSpace)}else{if(!("undefined"!==typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!==typeof SVGImageElement&&e instanceof SVGImageElement||"undefined"!==typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!==typeof HTMLVideoElement&&e instanceof HTMLVideoElement||"undefined"!==typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!==typeof OffscreenCanvas&&e instanceof OffscreenCanvas))throw new TypeError("Invalid data type: Must be a BufferSource or CanvasImageSource.");{if(!t||"object"!==typeof t)throw new TypeError("init must be an object.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(void 0!==t.duration&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if("undefined"!==typeof VideoFrame)return new Es(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*te),duration:Math.trunc((null!=(C=t.duration)?C:0)*te)||void 0}),t);let i=0,r=0;if("naturalWidth"in e?(i=e.naturalWidth,r=e.naturalHeight):"videoWidth"in e?(i=e.videoWidth,r=e.videoHeight):"width"in e&&(i=Number(e.width),r=Number(e.height)),!i||!r)throw new TypeError("Could not determine dimensions.");const n=new OffscreenCanvas(i,r),s=n.getContext("2d",{alpha:ce(),willReadFrequently:!0});y(s),s.drawImage(e,0,0),this._data=n,this._layout=null,this.format="RGBX",this.visibleRect={left:0,top:0,width:i,height:r},this.squarePixelWidth=i,this.squarePixelHeight=r,this.rotation=null!=(B=t.rotation)?B:0,this.timestamp=t.timestamp,this.duration=null!=(E=t.duration)?E:0,this.colorSpace=new _s({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}}this.pixelAspectRatio=ve({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),null==xs||xs.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return y(null!==this._data),As(this._data)?new Es(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation}):this._data instanceof Uint8Array?(y(this._layout),new Es(this._data,{format:this.format,layout:this._layout,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight})):new Es(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight})}close(){this._closed||(null==xs||xs.unregister(this),As(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(Ds(e),this._closed)throw new Error("VideoSample is closed.");if(null===this.format)throw new Error("Cannot get allocation size when format is null. Sorry!");if(y(null!==this._data),!As(this._data)&&(e.colorSpace||e.format&&e.format!==this.format||e.layout||e.rect)){const t=this.toVideoFrame(),i=t.allocationSize(e);return t.close(),i}return As(this._data)?this._data.allocationSize(e):this._data instanceof Uint8Array?this._data.byteLength:this.codedWidth*this.codedHeight*4}copyTo(e){return d(this,arguments,function*(e,t={}){if(!R(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(Ds(t),this._closed)throw new Error("VideoSample is closed.");if(null===this.format)throw new Error("Cannot copy video sample data when format is null. Sorry!");if(y(null!==this._data),!As(this._data)&&(t.colorSpace||t.format&&t.format!==this.format||t.layout||t.rect)){const i=this.toVideoFrame(),r=yield i.copyTo(e,t);return i.close(),r}if(As(this._data))return this._data.copyTo(e,t);if(this._data instanceof Uint8Array){y(this._layout);return w(e).set(this._data),this._layout}{const t=this._data.getContext("2d");y(t);const i=t.getImageData(0,0,this.codedWidth,this.codedHeight);return w(e).set(i.data),[{offset:0,stride:4*this.codedWidth}]}})}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");return y(null!==this._data),As(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace}):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,t,i,r,n,s,a,o,l){let c=0,u=0,d=this.displayWidth,h=this.displayHeight,f=0,m=0,p=this.displayWidth,g=this.displayHeight;if(void 0!==s?(c=t,u=i,d=r,h=n,f=s,m=a,void 0!==o?(p=o,g=l):(p=d,g=h)):(f=t,m=i,void 0!==r&&(p=r,g=n)),!("undefined"!==typeof CanvasRenderingContext2D&&e instanceof CanvasRenderingContext2D||"undefined"!==typeof OffscreenCanvasRenderingContext2D&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(c))throw new TypeError("sx must be a number.");if(!Number.isFinite(u))throw new TypeError("sy must be a number.");if(!Number.isFinite(d)||d<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(h)||h<0)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(f))throw new TypeError("dx must be a number.");if(!Number.isFinite(m))throw new TypeError("dy must be a number.");if(!Number.isFinite(p)||p<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(g)||g<0)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw new Error("VideoSample is closed.");({sx:c,sy:u,sWidth:d,sHeight:h}=this._rotateSourceRegion(c,u,d,h,this.rotation));const k=this.toCanvasImageSource();e.save();const y=f+p/2,b=m+g/2;e.translate(y,b),e.rotate(this.rotation*Math.PI/180);const T=this.rotation%180===0?1:p/g;e.scale(1/T,T),e.drawImage(k,c,u,d,h,-p/2,-g/2,p,g),e.restore()}drawWithFit(e,t){var i,r,n,s,a,o,l,c,u;if(!("undefined"!==typeof CanvasRenderingContext2D&&e instanceof CanvasRenderingContext2D||"undefined"!==typeof OffscreenCanvasRenderingContext2D&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!t||"object"!==typeof t)throw new TypeError("options must be an object.");if(!["fill","contain","cover"].includes(t.fit))throw new TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");void 0!==t.crop&&Rs(t.crop,"options.");const d=e.canvas.width,h=e.canvas.height,f=null!=(i=t.rotation)?i:this.rotation,[m,p]=f%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let g,k,y,b;t.crop&&Fs(t.crop,m,p);const{sx:T,sy:S,sWidth:v,sHeight:w}=this._rotateSourceRegion(null!=(n=null==(r=t.crop)?void 0:r.left)?n:0,null!=(a=null==(s=t.crop)?void 0:s.top)?a:0,null!=(l=null==(o=t.crop)?void 0:o.width)?l:m,null!=(u=null==(c=t.crop)?void 0:c.height)?u:p,f);if("fill"===t.fit)g=0,k=0,y=d,b=h;else{const[e,i]=t.crop?[t.crop.width,t.crop.height]:[m,p],r="contain"===t.fit?Math.min(d/e,h/i):Math.max(d/e,h/i);y=e*r,b=i*r,g=(d-y)/2,k=(h-b)/2}e.save();const P=f%180===0?1:y/b;e.translate(d/2,h/2),e.rotate(f*Math.PI/180),e.scale(1/P,P),e.translate(-d/2,-h/2),e.drawImage(this.toCanvasImageSource(),T,S,v,w,g,k,y,b),e.restore()}_rotateSourceRegion(e,t,i,r,n){return 90===n?[e,t,i,r]=[t,this.squarePixelHeight-e-i,r,i]:180===n?[e,t]=[this.squarePixelWidth-e-i,this.squarePixelHeight-t-r]:270===n&&([e,t,i,r]=[this.squarePixelWidth-t-r,e,r,i]),{sx:e,sy:t,sWidth:i,sHeight:r}}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(y(null!==this._data),this._data instanceof Uint8Array){const e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}return this._data}setRotation(e){if(![0,90,180,270].includes(e))throw new TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}setDuration(e){if(!Number.isFinite(e)||e<0)throw new TypeError("newDuration must be a non-negative number.");this.duration=e}[Symbol.dispose](){this.close()}}class _s{constructor(e){var t,i,r,n;if(void 0!==e){if(!e||"object"!==typeof e)throw new TypeError("init.colorSpace, when provided, must be an object.");const t=Object.keys(C);if(null!=e.primaries&&!t.includes(e.primaries))throw new TypeError(`init.colorSpace.primaries, when provided, must be one of ${t.join(", ")}.`);const i=Object.keys(E);if(null!=e.transfer&&!i.includes(e.transfer))throw new TypeError(`init.colorSpace.transfer, when provided, must be one of ${i.join(", ")}.`);const r=Object.keys(A);if(null!=e.matrix&&!r.includes(e.matrix))throw new TypeError(`init.colorSpace.matrix, when provided, must be one of ${r.join(", ")}.`);if(null!=e.fullRange&&"boolean"!==typeof e.fullRange)throw new TypeError("init.colorSpace.fullRange, when provided, must be a boolean.")}this.primaries=null!=(t=null==e?void 0:e.primaries)?t:null,this.transfer=null!=(i=null==e?void 0:e.transfer)?i:null,this.matrix=null!=(r=null==e?void 0:e.matrix)?r:null,this.fullRange=null!=(n=null==e?void 0:e.fullRange)?n:null}toJSON(){return{primaries:this.primaries,transfer:this.transfer,matrix:this.matrix,fullRange:this.fullRange}}}const As=e=>"undefined"!==typeof VideoFrame&&e instanceof VideoFrame,Fs=(e,t,i)=>{const r=Math.min(e.left,t),n=Math.min(e.top,i),s=Math.min(e.width,t-r),a=Math.min(e.height,i-n);return y(s>=0),y(a>=0),{left:r,top:n,width:s,height:a}},Rs=(e,t)=>{if(!e||"object"!==typeof e)throw new TypeError(t+"crop, when provided, must be an object.");if(!Number.isInteger(e.left)||e.left<0)throw new TypeError(t+"crop.left must be a non-negative integer.");if(!Number.isInteger(e.top)||e.top<0)throw new TypeError(t+"crop.top must be a non-negative integer.");if(!Number.isInteger(e.width)||e.width<0)throw new TypeError(t+"crop.width must be a non-negative integer.");if(!Number.isInteger(e.height)||e.height<0)throw new TypeError(t+"crop.height must be a non-negative integer.")},Ds=e=>{if(!e||"object"!==typeof e)throw new TypeError("options must be an object.");if(void 0!==e.colorSpace&&!["display-p3","srgb"].includes(e.colorSpace))throw new TypeError("options.colorSpace, when provided, must be 'display-p3' or 'srgb'.");if(void 0!==e.format&&"string"!==typeof e.format)throw new TypeError("options.format, when provided, must be a string.");if(void 0!==e.layout){if(!Array.isArray(e.layout))throw new TypeError("options.layout, when provided, must be an array.");for(const t of e.layout){if(!t||"object"!==typeof t)throw new TypeError("Each entry in options.layout must be an object.");if(!Number.isInteger(t.offset)||t.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(t.stride)||t.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(void 0!==e.rect){if(!e.rect||"object"!==typeof e.rect)throw new TypeError("options.rect, when provided, must be an object.");if(void 0!==e.rect.x&&(!Number.isInteger(e.rect.x)||e.rect.x<0))throw new TypeError("options.rect.x, when provided, must be a non-negative integer.");if(void 0!==e.rect.y&&(!Number.isInteger(e.rect.y)||e.rect.y<0))throw new TypeError("options.rect.y, when provided, must be a non-negative integer.");if(void 0!==e.rect.width&&(!Number.isInteger(e.rect.width)||e.rect.width<0))throw new TypeError("options.rect.width, when provided, must be a non-negative integer.");if(void 0!==e.rect.height&&(!Number.isInteger(e.rect.height)||e.rect.height<0))throw new TypeError("options.rect.height, when provided, must be a non-negative integer.")}},Ms=(e,t,i)=>{const r=Ns(e),n=[];let s=0;for(const a of r){const e=Math.ceil(t/a.widthDivisor),r=Math.ceil(i/a.heightDivisor),o=e*a.sampleBytes,l=o*r;n.push({offset:s,stride:o}),s+=l}return n},Ns=e=>{const t=(e,t,i,r,n)=>{const s=[{sampleBytes:e,widthDivisor:1,heightDivisor:1},{sampleBytes:t,widthDivisor:i,heightDivisor:r},{sampleBytes:t,widthDivisor:i,heightDivisor:r}];return n&&s.push({sampleBytes:e,widthDivisor:1,heightDivisor:1}),s};switch(e){case"I420":return t(1,1,2,2,!1);case"I420P10":case"I420P12":return t(2,2,2,2,!1);case"I420A":return t(1,1,2,2,!0);case"I420AP10":case"I420AP12":return t(2,2,2,2,!0);case"I422":return t(1,1,2,1,!1);case"I422P10":case"I422P12":return t(2,2,2,1,!1);case"I422A":return t(1,1,2,1,!0);case"I422AP10":case"I422AP12":return t(2,2,2,1,!0);case"I444":return t(1,1,1,1,!1);case"I444P10":case"I444P12":return t(2,2,1,1,!1);case"I444A":return t(1,1,1,1,!0);case"I444AP10":case"I444AP12":return t(2,2,1,1,!0);case"NV12":return[{sampleBytes:1,widthDivisor:1,heightDivisor:1},{sampleBytes:2,widthDivisor:2,heightDivisor:2}];case"RGBA":case"RGBX":case"BGRA":case"BGRX":return[{sampleBytes:4,widthDivisor:1,heightDivisor:1}];default:H(e),y(!1)}},Os=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]);class Ls{get microsecondTimestamp(){return Math.trunc(te*this.timestamp)}get microsecondDuration(){return Math.trunc(te*this.duration)}constructor(e){if(this._closed=!1,Vs(e)){if(null===e.format)throw new TypeError("AudioData with null format is not supported.");this._data=e,this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=e.numberOfFrames,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp/1e6,this.duration=e.numberOfFrames/e.sampleRate}else{if(!e||"object"!==typeof e)throw new TypeError("Invalid AudioDataInit: must be an object.");if(!Os.has(e.format))throw new TypeError("Invalid AudioDataInit: invalid format.");if(!Number.isFinite(e.sampleRate)||e.sampleRate<=0)throw new TypeError("Invalid AudioDataInit: sampleRate must be > 0.");if(!Number.isInteger(e.numberOfChannels)||0===e.numberOfChannels)throw new TypeError("Invalid AudioDataInit: numberOfChannels must be an integer > 0.");if(!Number.isFinite(null==e?void 0:e.timestamp))throw new TypeError("init.timestamp must be a number.");const t=e.data.byteLength/(zs(e.format)*e.numberOfChannels);if(!Number.isInteger(t))throw new TypeError("Invalid AudioDataInit: data size is not a multiple of frame size.");let i;if(this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=t,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp,this.duration=t/e.sampleRate,e.data instanceof ArrayBuffer)i=new Uint8Array(e.data);else{if(!ArrayBuffer.isView(e.data))throw new TypeError("Invalid AudioDataInit: data is not a BufferSource.");i=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength)}const r=this.numberOfFrames*this.numberOfChannels*zs(this.format);if(i.byteLength=this.numberOfFrames)throw new RangeError("frameOffset out of range");const s=void 0!==e.frameCount?e.frameCount:this.numberOfFrames-n;if(s>this.numberOfFrames-n)throw new RangeError("frameCount out of range");const a=zs(r),o=Us(r);if(o&&e.planeIndex>=this.numberOfChannels)throw new RangeError("planeIndex out of range");if(!o&&0!==e.planeIndex)throw new RangeError("planeIndex out of range");return(o?s:s*this.numberOfChannels)*a}copyTo(e,t){if(!R(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(!t||"object"!==typeof t)throw new TypeError("options must be an object.");if(!Number.isInteger(t.planeIndex)||t.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(void 0!==t.format&&!Os.has(t.format))throw new TypeError("Invalid format.");if(void 0!==t.frameOffset&&(!Number.isInteger(t.frameOffset)||t.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(void 0!==t.frameCount&&(!Number.isInteger(t.frameCount)||t.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");const{planeIndex:i,format:r,frameCount:n,frameOffset:s}=t,a=this.format,o=null!=r?r:this.format;if(!o)throw new Error("Destination format not determined");const l=this.numberOfFrames,c=this.numberOfChannels,u=null!=s?s:0;if(u>=l)throw new RangeError("frameOffset out of range");const d=void 0!==n?n:l-u;if(d>l-u)throw new RangeError("frameCount out of range");const h=zs(o),f=Us(o);if(f&&i>=c)throw new RangeError("planeIndex out of range");if(!f&&0!==i)throw new RangeError("planeIndex out of range");const m=(f?d:d*c)*h;if(e.byteLength2&&o!==a?Hs(this._data,p,a,o,c,i,u,d):this._data.copyTo(e,{planeIndex:i,frameOffset:u,frameCount:d,format:o});else{const e=this._data,t=P(e),r=qs(a),n=zs(a),s=Us(a);for(let a=0;a0;){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")}},Us=e=>{switch(e){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},qs=e=>{switch(e){case"u8":case"u8-planar":return(e,t)=>(e.getUint8(t)-128)/128;case"s16":case"s16-planar":return(e,t)=>e.getInt16(t,!0)/32768;case"s32":case"s32-planar":return(e,t)=>e.getInt32(t,!0)/2147483648;case"f32":case"f32-planar":return(e,t)=>e.getFloat32(t,!0)}},Ws=e=>{switch(e){case"u8":case"u8-planar":return(e,t,i)=>e.setUint8(t,$(127.5*(i+1),0,255));case"s16":case"s16-planar":return(e,t,i)=>e.setInt16(t,$(Math.round(32767*i),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,i)=>e.setInt32(t,$(Math.round(2147483647*i),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,i)=>e.setFloat32(t,i,!0)}},Vs=e=>"undefined"!==typeof AudioData&&e instanceof AudioData,Hs=(e,t,i,r,n,s,a,o)=>{const l=qs(i),c=Ws(r),u=zs(i),d=zs(r),h=Us(i);if(Us(r))if(h){const r=new ArrayBuffer(o*u),n=P(r);e.copyTo(r,{planeIndex:s,frameOffset:a,frameCount:o,format:i});for(let e=0;e{if(!e||"object"!==typeof e)throw new TypeError("options must be an object.");if(void 0!==e.metadataOnly&&"boolean"!==typeof e.metadataOnly)throw new TypeError("options.metadataOnly, when defined, must be a boolean.");if(void 0!==e.verifyKeyPackets&&"boolean"!==typeof e.verifyKeyPackets)throw new TypeError("options.verifyKeyPackets, when defined, must be a boolean.");if(e.verifyKeyPackets&&e.metadataOnly)throw new TypeError("options.verifyKeyPackets and options.metadataOnly cannot be enabled together.");if(void 0!==e.skipLiveWait&&"boolean"!==typeof e.skipLiveWait)throw new TypeError("options.skipLiveWait, when defined, must be a boolean.")},$s=e=>{if(!ye(e))throw new TypeError("timestamp must be a number.")},Qs=(e,t,i)=>i.verifyKeyPackets?t.then(t=>d(null,null,function*(){if(!t||"delta"===t.type)return t;const i=yield e.determinePacketType(t);return i&&(t.type=i),t})):t;class Gs{constructor(e){if(!(e instanceof la))throw new TypeError("track must be an InputTrack.");this._track=e}getFirstPacket(){return d(this,arguments,function*(e={}){if(Xs(e),this._track.input._disposed)throw new va;return Qs(this._track,this._track._backing.getFirstPacket(e),e)})}getFirstKeyPacket(){return d(this,arguments,function*(e={}){Xs(e);const t=yield this.getFirstPacket(e);return t?"key"===t.type?t:this.getNextKeyPacket(t,e):null})}getPacket(e){return d(this,arguments,function*(e,t={}){if($s(e),Xs(t),this._track.input._disposed)throw new va;return Qs(this._track,this._track._backing.getPacket(e,t),t)})}getNextPacket(e){return d(this,arguments,function*(e,t={}){if(!(e instanceof Yt))throw new TypeError("packet must be an EncodedPacket.");if(Xs(t),this._track.input._disposed)throw new va;return Qs(this._track,this._track._backing.getNextPacket(e,t),t)})}getKeyPacket(e){return d(this,arguments,function*(e,t={}){if($s(e),Xs(t),this._track.input._disposed)throw new va;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);const i=yield this._track._backing.getKeyPacket(e,t);if(!i)return i;y("key"===i.type);return"delta"===(yield this._track.determinePacketType(i))?this.getKeyPacket(i.timestamp-1/(yield this._track.getTimeResolution()),t):i})}getNextKeyPacket(e){return d(this,arguments,function*(e,t={}){if(!(e instanceof Yt))throw new TypeError("packet must be an EncodedPacket.");if(Xs(t),this._track.input._disposed)throw new va;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);const i=yield this._track._backing.getNextKeyPacket(e,t);if(!i)return i;y("key"===i.type);return"delta"===(yield this._track.determinePacketType(i))?this.getNextKeyPacket(i,t):i})}packets(e,t,i={}){if(void 0!==e&&!(e instanceof Yt))throw new TypeError("startPacket must be an EncodedPacket.");if(void 0!==e&&e.isMetadataOnly&&!(null==i?void 0:i.metadataOnly))throw new TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(void 0!==t&&!(t instanceof Yt))throw new TypeError("endPacket must be an EncodedPacket.");if(Xs(i),this._track.input._disposed)throw new va;const r=[];let{promise:n,resolve:s}=q(),{promise:a,resolve:o}=q(),l=!1,c=!1,u=null;const h=[],f=()=>Math.max(2,h.length);(()=>d(this,null,function*(){let u=null!=e?e:yield this.getFirstPacket(i);for(;u&&!c&&!this._track.input._disposed&&!(t&&u.sequenceNumber>=(null==t?void 0:t.sequenceNumber));)r.length>f()?(({promise:a,resolve:o}=q()),yield a):(r.push(u),s(),({promise:n,resolve:s}=q()),u=yield this.getNextPacket(u,i));l=!0,s()}))().catch(e=>{u||(u=e,s())});const m=this._track;return{next(){return d(this,null,function*(){for(;;){if(m.input._disposed)throw new va;if(c)return{value:void 0,done:!0};if(u)throw u;if(r.length>0){const e=r.shift(),t=performance.now();for(h.push(t);h.length>0&&t-h[0]>=1e3;)h.shift();return o(),{value:e,done:!1}}if(l)return{value:void 0,done:!0};yield n}})},return(){return d(this,null,function*(){return c=!0,o(),s(),{value:void 0,done:!0}})},throw(e){return d(this,null,function*(){throw e})},[Symbol.asyncIterator](){return this}}}}class Ys{constructor(e,t){this.onSample=e,this.onError=t}}class Js{mediaSamplesInRange(e=0,t=1/0,i){$s(e),$s(t);const r=[];let n=!1,s=null,{promise:a,resolve:o}=q(),{promise:l,resolve:h}=q(),f=!1,m=!1,p=!1,g=null;const k=u(c({},i),{verifyKeyPackets:!0,metadataOnly:!1});(()=>d(this,null,function*(){var i;const c=yield this._createDecoder(i=>{h(),i.timestamp>=t&&(m=!0),m?i.close():(s&&(i.timestamp>e?(r.push(s),n=!0):s.close()),i.timestamp>=e&&(r.push(i),n=!0),s=n?null:i,r.length>0&&(o(),({promise:a,resolve:o}=q())))},e=>{g||(g=e,o())}),u=this._createPacketSink(),d=null!=(i=yield u.getKeyPacket(e,k))?i:yield u.getFirstKeyPacket(k);let y=d;const b=u.packets(null!=d?d:void 0,void 0,k);for(yield b.next();y&&!m&&!this._track.input._disposed;){const e=Zs(r.length);if(r.length+c.getDecodeQueueSize()>e){({promise:l,resolve:h}=q()),yield l;continue}c.decode(y);const t=yield b.next();if(t.done)break;y=t.value}yield b.return(),p||this._track.input._disposed||(yield c.flush()),c.close(),!n&&s&&r.push(s),f=!0,o()}))().catch(e=>{g||(g=e,o())});const y=this._track,b=()=>{null==s||s.close();for(const e of r)e.close()};return{next(){return d(this,null,function*(){for(;;){if(y.input._disposed)throw b(),new va;if(p)return{value:void 0,done:!0};if(g)throw b(),g;if(r.length>0){const e=r.shift();return h(),{value:e,done:!1}}if(f)return{value:void 0,done:!0};yield a}})},return(){return d(this,null,function*(){return p=!0,m=!0,h(),o(),b(),{value:void 0,done:!0}})},throw(e){return d(this,null,function*(){throw e})},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e,t){(e=>{if(!(Symbol.iterator in e)&&!(Symbol.asyncIterator in e))throw new TypeError("Argument must be an iterable or async iterable.")})(e);const i=function(e){return f(this,null,function*(){Symbol.iterator in e?yield*m(e[Symbol.iterator]()):yield*m(e[Symbol.asyncIterator]())})}(e),r=[],n=[];let{promise:s,resolve:a}=q(),{promise:o,resolve:l}=q(),h=!1,g=!1,k=null;const b=e=>{n.push(e),a(),({promise:s,resolve:a}=q())},T=u(c({},t),{verifyKeyPackets:!0,metadataOnly:!1});(()=>d(this,null,function*(){const e=yield this._createDecoder(e=>{if(l(),g)return void e.close();let t=0;for(;r.length>0&&e.timestamp-r[0]>-1e-10;)t++,r.shift();if(t>0)for(let i=0;i{k||(k=e,a())}),t=this._createPacketSink();let s=null,c=null,u=-1;const f=()=>d(this,null,function*(){y(c);let i=c;for(e.decode(i);i.sequenceNumberr&&!g;)({promise:o,resolve:l}=q()),yield o;if(g)break;const s=yield t.getNextPacket(i,T);y(s),e.decode(s),i=s}u=-1}),m=()=>d(this,null,function*(){yield e.flush();for(let e=0;e{k||(k=e,a())});const S=this._track,v=()=>{for(const e of n)null==e||e.close()};return{next(){return d(this,null,function*(){for(;;){if(S.input._disposed)throw v(),new va;if(g)return{value:void 0,done:!0};if(k)throw v(),k;if(n.length>0){const e=n.shift();return y(void 0!==e),l(),{value:e,done:!1}}if(h)return{value:void 0,done:!0};yield s}})},return(){return d(this,null,function*(){return g=!0,l(),a(),v(),{value:void 0,done:!0}})},throw(e){return d(this,null,function*(){throw e})},[Symbol.asyncIterator](){return this}}}}const Zs=e=>0===e?40:8;class ea extends Ys{constructor(e,t,i,r,n,s){super(e,t),this.codec=i,this.decoderConfig=r,this.rotation=n,this.timeResolution=s,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new se,this.customDecoderQueueSize=0,this.inputTimestamps=[],this.sampleQueue=[],this.currentPacketIndex=0,this.raslSkipped=!1,this.alphaDecoder=null,this.alphaHadKeyframe=!1,this.colorQueue=[],this.alphaQueue=[],this.merger=null,this.mergerCreationFailed=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue=[],this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1;const a=Ks.find(e=>e.supports(i,r));if(a)this.customDecoder=new a,this.customDecoder.codec=i,this.customDecoder.config=r,this.customDecoder.onSample=e=>{if(!(e instanceof Es))throw new TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(e)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{const e=e=>{if(this.alphaQueue.length>0){const t=this.alphaQueue.shift();y(void 0!==t),this.mergeAlpha(e,t)}else this.colorQueue.push(e)};if("avc"===i&&this.decoderConfig.description&&de()){const e=(e=>{try{const t=P(e);let i=0;const r=t.getUint8(i++),n=t.getUint8(i++),s=t.getUint8(i++),a=t.getUint8(i++),o=3&t.getUint8(i++),l=31&t.getUint8(i++),c=[];for(let f=0;f0){const t=kt(e.sequenceParameterSets[0]);t&&0===t.frameMbsOnlyFlag&&(this.decoderConfig=u(c({},this.decoderConfig),{hardwareAcceleration:"prefer-software"}))}}const t=new Error("Decoding error").stack;this.decoder=new VideoDecoder({output:t=>{try{e(t)}catch(i){this.onError(i)}},error:e=>{e.stack=t,this.onError(e)}}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){var e,t;return this.customDecoder?this.customDecoderQueueSize:(y(this.decoder),Math.max(this.decoder.decodeQueueSize,null!=(t=null==(e=this.alphaDecoder)?void 0:e.decodeQueueSize)?t:0))}decode(e){if("hevc"===this.codec&&this.currentPacketIndex>0&&!this.raslSkipped){if(this.hasHevcRaslPicture(e.data))return;this.raslSkipped=!0}if(this.customDecoder)this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--);else{if(y(this.decoder),oe()||U(this.inputTimestamps,e.timestamp,e=>e),de()&&0===this.currentPacketIndex)if("avc"===this.codec){const t=[];for(const r of ct(e.data,this.decoderConfig)){const i=ut(e.data[r.offset]);i>=20&&i<=31||t.push(e.data.subarray(r.offset,r.offset+r.length))}const i=((e,t)=>{if(t.description){const i=3&w(t.description)[4];return mt(e,i+1)}return ft(e)})(t,this.decoderConfig);e=new Yt(i,e.type,e.timestamp,e.duration)}else if("hevc"===this.codec){const t=Ft(e.data,this.decoderConfig);t&&(e=new Yt(t,e.type,e.timestamp,e.duration))}this.decoder.decode(e.toEncodedVideoChunk()),this.decodeAlphaData(e)}this.currentPacketIndex++}decodeAlphaData(e){if(!e.sideData.alpha||this.mergerCreationFailed)return void this.pushNullAlphaFrame();if(!this.merger)try{this.merger=new ta}catch(i){return console.error("Due to an error, only color data will be decoded.",i),this.mergerCreationFailed=!0,void this.decodeAlphaData(e)}if(!this.alphaDecoder){const e=e=>{if(this.alphaDecoderQueueSize--,this.colorQueue.length>0){const t=this.colorQueue.shift();y(void 0!==t),this.mergeAlpha(t,e)}else this.alphaQueue.push(e);for(this.decodedAlphaChunkCount++;this.nullAlphaFrameQueue.length>0&&this.nullAlphaFrameQueue[0]===this.decodedAlphaChunkCount;)if(this.nullAlphaFrameQueue.shift(),this.colorQueue.length>0){const e=this.colorQueue.shift();y(void 0!==e),this.mergeAlpha(e,null)}else this.alphaQueue.push(null)},t=new Error("Decoding error").stack;this.alphaDecoder=new VideoDecoder({output:t=>{try{e(t)}catch(i){this.onError(i)}},error:e=>{e.stack=t,this.onError(e)}}),this.alphaDecoder.configure(this.decoderConfig)}const t=Lt(this.codec,this.decoderConfig,e.sideData.alpha);if(this.alphaHadKeyframe||(this.alphaHadKeyframe="key"===t),this.alphaHadKeyframe){if("hevc"===this.codec&&this.currentAlphaPacketIndex>0&&!this.alphaRaslSkipped){if(this.hasHevcRaslPicture(e.sideData.alpha))return void this.pushNullAlphaFrame();this.alphaRaslSkipped=!0}this.currentAlphaPacketIndex++,this.alphaDecoder.decode(e.alphaToEncodedVideoChunk(null!=t?t:e.type)),this.alphaDecoderQueueSize++}else this.pushNullAlphaFrame()}pushNullAlphaFrame(){0===this.alphaDecoderQueueSize?this.alphaQueue.push(null):this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture(e){for(const t of bt(e,this.decoderConfig)){const i=Tt(e[t.offset]);if(i===st.RASL_N||i===st.RASL_R)return!0}return!1}sampleHandler(e){if(oe()){if(this.sampleQueue.length>0&&e.timestamp>=T(this.sampleQueue).timestamp){for(const e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}U(this.sampleQueue,e,e=>e.timestamp)}else{const t=this.inputTimestamps.shift();y(void 0!==t),e.setTimestamp(t),this.finalizeAndEmitSample(e)}}finalizeAndEmitSample(e){e.setTimestamp(Math.round(e.timestamp*this.timeResolution)/this.timeResolution),e.setDuration(Math.round(e.duration*this.timeResolution)/this.timeResolution),e.setRotation(this.rotation),this.onSample(e)}mergeAlpha(e,t){var i;if(!t){const t=new Es(e);return void this.sampleHandler(t)}y(this.merger),this.merger.update(e,t),e.close(),t.close();const r=new VideoFrame(this.merger.canvas,{timestamp:e.timestamp,duration:null!=(i=e.duration)?i:void 0}),n=new Es(r);this.sampleHandler(n)}flush(){return d(this,null,function*(){var e;if(this.customDecoder?yield this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(y(this.decoder),yield Promise.all([this.decoder.flush(),null==(e=this.alphaDecoder)?void 0:e.flush()]),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>null==e?void 0:e.close()),this.alphaQueue.length=0,this.alphaHadKeyframe=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue.length=0,this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1),oe()){for(const e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}this.currentPacketIndex=0,this.raslSkipped=!1})}close(){var e,t;this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(y(this.decoder),this.decoder.close(),null==(e=this.alphaDecoder)||e.close(),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>null==e?void 0:e.close()),this.alphaQueue.length=0,null==(t=this.merger)||t.close());for(const i of this.sampleQueue)i.close();this.sampleQueue.length=0}}class ta{constructor(){"undefined"!==typeof OffscreenCanvas?this.canvas=new OffscreenCanvas(300,150):this.canvas=document.createElement("canvas");const e=this.canvas.getContext("webgl2",{premultipliedAlpha:!1});if(!e)throw new Error("Couldn't acquire WebGL 2 context.");this.gl=e,this.program=this.createProgram(),this.vao=this.createVAO(),this.colorTexture=this.createTexture(),this.alphaTexture=this.createTexture(),this.gl.useProgram(this.program),this.gl.uniform1i(this.gl.getUniformLocation(this.program,"u_colorTexture"),0),this.gl.uniform1i(this.gl.getUniformLocation(this.program,"u_alphaTexture"),1)}createProgram(){const e=this.createShader(this.gl.VERTEX_SHADER,"#version 300 es\n\t\t\tin vec2 a_position;\n\t\t\tin vec2 a_texCoord;\n\t\t\tout vec2 v_texCoord;\n\t\t\t\n\t\t\tvoid main() {\n\t\t\t\tgl_Position = vec4(a_position, 0.0, 1.0);\n\t\t\t\tv_texCoord = a_texCoord;\n\t\t\t}\n\t\t"),t=this.createShader(this.gl.FRAGMENT_SHADER,"#version 300 es\n\t\t\tprecision highp float;\n\t\t\t\n\t\t\tuniform sampler2D u_colorTexture;\n\t\t\tuniform sampler2D u_alphaTexture;\n\t\t\tin vec2 v_texCoord;\n\t\t\tout vec4 fragColor;\n\t\t\t\n\t\t\tvoid main() {\n\t\t\t\tvec3 color = texture(u_colorTexture, v_texCoord).rgb;\n\t\t\t\tfloat alpha = texture(u_alphaTexture, v_texCoord).r;\n\t\t\t\tfragColor = vec4(color, alpha);\n\t\t\t}\n\t\t"),i=this.gl.createProgram();return this.gl.attachShader(i,e),this.gl.attachShader(i,t),this.gl.linkProgram(i),i}createShader(e,t){const i=this.gl.createShader(e);return this.gl.shaderSource(i,t),this.gl.compileShader(i),i}createVAO(){const e=this.gl.createVertexArray();this.gl.bindVertexArray(e);const t=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),i=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,i),this.gl.bufferData(this.gl.ARRAY_BUFFER,t,this.gl.STATIC_DRAW);const r=this.gl.getAttribLocation(this.program,"a_position"),n=this.gl.getAttribLocation(this.program,"a_texCoord");return this.gl.enableVertexAttribArray(r),this.gl.vertexAttribPointer(r,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(n),this.gl.vertexAttribPointer(n,2,this.gl.FLOAT,!1,16,8),e}createTexture(){const e=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),e}update(e,t){e.displayWidth===this.canvas.width&&e.displayHeight===this.canvas.height||(this.canvas.width=e.displayWidth,this.canvas.height=e.displayHeight),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.colorTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),this.gl.activeTexture(this.gl.TEXTURE1),this.gl.bindTexture(this.gl.TEXTURE_2D,this.alphaTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,t),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4)}close(){var e;null==(e=this.gl.getExtension("WEBGL_lose_context"))||e.loseContext(),this.gl=null}}class ia extends Js{constructor(e){if(!(e instanceof da))throw new TypeError("videoTrack must be an InputVideoTrack.");super(),this._track=e}_createDecoder(e,t){return d(this,null,function*(){if(!(yield this._track.canDecode()))throw new Error("This video track cannot be decoded by this browser. Make sure to check decodability before using a track.");const i=yield this._track.getCodec(),r=yield this._track.getRotation(),n=yield this._track.getDecoderConfig(),s=yield this._track.getTimeResolution();return y(i&&n),new ea(e,t,i,n,r,s)})}_createPacketSink(){return new Gs(this._track)}getSample(e){return d(this,arguments,function*(e,t={}){$s(e);try{for(var i,r,n,s=p(this.mediaSamplesAtTimestamps([e],t));i=!(r=yield s.next()).done;i=!1){return r.value}}catch(r){n=[r]}finally{try{i&&(r=s.return)&&(yield r.call(s))}finally{if(n)throw n[0]}}throw new Error("Internal error: Iterator returned nothing.")})}samples(e=0,t=1/0,i={}){return this.mediaSamplesInRange(e,t,i)}samplesAtTimestamps(e,t={}){return this.mediaSamplesAtTimestamps(e,t)}}class ra{constructor(e,t={}){var i,r,n;if(this._rotation=0,this._initPromise=null,this._nextCanvasIndex=0,!(e instanceof da))throw new TypeError("videoTrack must be an InputVideoTrack.");if(t&&"object"!==typeof t)throw new TypeError("options must be an object.");if(void 0!==t.alpha&&"boolean"!==typeof t.alpha)throw new TypeError("options.alpha, when provided, must be a boolean.");if(void 0!==t.width&&(!Number.isInteger(t.width)||t.width<=0))throw new TypeError("options.width, when defined, must be a positive integer.");if(void 0!==t.height&&(!Number.isInteger(t.height)||t.height<=0))throw new TypeError("options.height, when defined, must be a positive integer.");if(void 0!==t.fit&&!["fill","contain","cover"].includes(t.fit))throw new TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(void 0!==t.width&&void 0!==t.height&&void 0===t.fit)throw new TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180 or 270.");if(void 0!==t.crop&&Rs(t.crop,"options."),void 0!==t.poolSize&&("number"!==typeof t.poolSize||!Number.isInteger(t.poolSize)||t.poolSize<0))throw new TypeError("poolSize must be a non-negative integer.");this._videoTrack=e,this._alpha=null!=(i=t.alpha)&&i,this._options=t,this._fit=null!=(r=t.fit)?r:"fill",this._videoSampleSink=new ia(e),this._canvasPool=Array.from({length:null!=(n=t.poolSize)?n:0},()=>null)}_ensureInit(){var e;return null!=(e=this._initPromise)?e:this._initPromise=(()=>d(this,null,function*(){var e;const t=this._options,i=this._videoTrack,r=null!=(e=t.rotation)?e:yield i.getRotation(),n=yield i.getSquarePixelWidth(),s=yield i.getSquarePixelHeight(),[a,o]=r%180===0?[n,s]:[s,n];let l=t.crop;l&&(l=Fs(l,a,o));let[c,u]=l?[l.width,l.height]:[a,o];const d=c/u;void 0!==t.width&&void 0===t.height?(c=t.width,u=Math.round(c/d)):void 0===t.width&&void 0!==t.height?(u=t.height,c=Math.round(u*d)):void 0!==t.width&&void 0!==t.height&&(c=t.width,u=t.height),this._width=c,this._height=u,this._rotation=r,this._crop=l}))()}_videoSampleToWrappedCanvas(e){const t=this._width,i=this._height;let r=this._canvasPool[this._nextCanvasIndex],n=!1;r||("undefined"!==typeof document?(r=document.createElement("canvas"),r.width=t,r.height=i):r=new OffscreenCanvas(t,i),this._canvasPool.length>0&&(this._canvasPool[this._nextCanvasIndex]=r),n=!0),this._canvasPool.length>0&&(this._nextCanvasIndex=(this._nextCanvasIndex+1)%this._canvasPool.length);const s=r.getContext("2d",{alpha:this._alpha||ce()});y(s),s.resetTransform(),n||(!this._alpha&&ce()?(s.fillStyle="black",s.fillRect(0,0,t,i)):s.clearRect(0,0,t,i)),e.drawWithFit(s,{fit:this._fit,rotation:this._rotation,crop:this._crop});const a={canvas:r,timestamp:e.timestamp,duration:e.duration};return e.close(),a}getCanvas(e,t){return d(this,null,function*(){$s(e),yield this._ensureInit();const i=yield this._videoSampleSink.getSample(e,t);return i&&this._videoSampleToWrappedCanvas(i)})}canvases(e=0,t=1/0,i){return f(this,null,function*(){yield new h(this._ensureInit()),yield*m(X(this._videoSampleSink.samples(e,t,i),e=>this._videoSampleToWrappedCanvas(e)))})}canvasesAtTimestamps(e,t){return f(this,null,function*(){yield new h(this._ensureInit()),yield*m(X(this._videoSampleSink.samplesAtTimestamps(e,t),e=>e&&this._videoSampleToWrappedCanvas(e)))})}}class na extends Ys{constructor(e,t,i,r){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new se,this.customDecoderQueueSize=0,this.currentTimestamp=null;const n=t=>{(null===this.currentTimestamp||Math.abs(t.timestamp-this.currentTimestamp)>=t.duration)&&(this.currentTimestamp=t.timestamp);const i=this.currentTimestamp;if(this.currentTimestamp+=t.duration,0===t.numberOfFrames)return void t.close();const n=r.sampleRate;t.setTimestamp(Math.round(i*n)/n),e(t)},s=js.find(e=>e.supports(i,r));if(s)this.customDecoder=new s,this.customDecoder.codec=i,this.customDecoder.config=r,this.customDecoder.onSample=e=>{if(!(e instanceof Ls))throw new TypeError("The argument passed to onSample must be an AudioSample.");n(e)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{const e=new Error("Decoding error").stack;this.decoder=new AudioDecoder({output:e=>{try{n(new Ls(e))}catch(t){this.onError(t)}},error:t=>{t.stack=e,this.onError(t)}}),this.decoder.configure(r)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(y(this.decoder),this.decoder.decodeQueueSize)}decode(e){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--)):(y(this.decoder),this.decoder.decode(e.toEncodedAudioChunk()))}flush(){return this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(y(this.decoder),this.decoder.flush())}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(y(this.decoder),this.decoder.close())}}class sa extends Ys{constructor(e,t,i){super(e,t),this.decoderConfig=i,this.currentTimestamp=null,y(De.includes(i.codec)),this.codec=i.codec;const{dataType:r,sampleSize:n,littleEndian:s}=He(this.codec);switch(this.inputSampleSize=n,n){case 1:"unsigned"===r?this.readInputValue=(e,t)=>e.getUint8(t)-o(2,7):"signed"===r?this.readInputValue=(e,t)=>e.getInt8(t):"ulaw"===r?this.readInputValue=(e,t)=>(e=>{let t=0,i=0,r=~e;128&r&&(r&=-129,t=-1),i=5+((240&r)>>4);const n=(1<(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)-o(2,15):"signed"===r?this.readInputValue=(e,t)=>e.getInt16(t,s):y(!1);break;case 3:"unsigned"===r?this.readInputValue=(e,t)=>K(e,t,s)-o(2,23):"signed"===r?this.readInputValue=(e,t)=>((e,t,i)=>K(e,t,i)<<8>>8)(e,t,s):y(!1);break;case 4:"unsigned"===r?this.readInputValue=(e,t)=>e.getUint32(t,s)-o(2,31):"signed"===r?this.readInputValue=(e,t)=>e.getInt32(t,s):"float"===r?this.readInputValue=(e,t)=>e.getFloat32(t,s):y(!1);break;case 8:"float"===r?this.readInputValue=(e,t)=>e.getFloat64(t,s):y(!1);break;default:H(n),y(!1)}switch(n){case 1:"ulaw"===r||"alaw"===r?(this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(e,t,i)=>e.setInt16(t,i,!0)):(this.outputSampleSize=1,this.outputFormat="u8",this.writeOutputValue=(e,t,i)=>e.setUint8(t,i+o(2,7)));break;case 2:this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(e,t,i)=>e.setInt16(t,i,!0);break;case 3:this.outputSampleSize=4,this.outputFormat="s32",this.writeOutputValue=(e,t,i)=>e.setInt32(t,i<<8,!0);break;case 4:this.outputSampleSize=4,"float"===r?(this.outputFormat="f32",this.writeOutputValue=(e,t,i)=>e.setFloat32(t,i,!0)):(this.outputFormat="s32",this.writeOutputValue=(e,t,i)=>e.setInt32(t,i,!0));break;case 8:this.outputSampleSize=4,this.outputFormat="f32",this.writeOutputValue=(e,t,i)=>e.setFloat32(t,i,!0);break;default:H(n),y(!1)}}getDecodeQueueSize(){return 0}decode(e){const t=P(e.data),i=e.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize,r=i*this.decoderConfig.numberOfChannels*this.outputSampleSize,n=new ArrayBuffer(r),s=new DataView(n);for(let c=0;c=a)&&(this.currentTimestamp=e.timestamp);const o=this.currentTimestamp;this.currentTimestamp+=a;const l=new Ls({format:this.outputFormat,data:n,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:i,timestamp:o});this.onSample(l)}flush(){return d(this,null,function*(){})}close(){}}class aa extends Js{constructor(e){if(!(e instanceof ha))throw new TypeError("audioTrack must be an InputAudioTrack.");super(),this._track=e}_createDecoder(e,t){return d(this,null,function*(){if(!(yield this._track.canDecode()))throw new Error("This audio track cannot be decoded by this browser. Make sure to check decodability before using a track.");const i=yield this._track.getCodec(),r=yield this._track.getDecoderConfig();return y(i&&r),De.includes(r.codec)?new sa(e,t,r):new na(e,t,i,r)})}_createPacketSink(){return new Gs(this._track)}getSample(e){return d(this,arguments,function*(e,t={}){$s(e);try{for(var i,r,n,s=p(this.mediaSamplesAtTimestamps([e],t));i=!(r=yield s.next()).done;i=!1){return r.value}}catch(r){n=[r]}finally{try{i&&(r=s.return)&&(yield r.call(s))}finally{if(n)throw n[0]}}throw new Error("Internal error: Iterator returned nothing.")})}samples(e=0,t=1/0,i={}){return this.mediaSamplesInRange(e,t,i)}samplesAtTimestamps(e,t={}){return this.mediaSamplesAtTimestamps(e,t)}}class oa{constructor(e){if(!(e instanceof ha))throw new TypeError("audioTrack must be an InputAudioTrack.");this._audioSampleSink=new aa(e)}_audioSampleToWrappedArrayBuffer(e){const t={buffer:e.toAudioBuffer(),timestamp:e.timestamp,duration:e.duration};return e.close(),t}getBuffer(e,t){return d(this,null,function*(){$s(e);const i=yield this._audioSampleSink.getSample(e,t);return i&&this._audioSampleToWrappedArrayBuffer(i)})}buffers(e=0,t=1/0,i){return X(this._audioSampleSink.samples(e,t,i),e=>this._audioSampleToWrappedArrayBuffer(e))}buffersAtTimestamps(e,t){return X(this._audioSampleSink.samplesAtTimestamps(e,t),e=>e&&this._audioSampleToWrappedArrayBuffer(e))}}class la{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof da}isAudioTrack(){return this instanceof ha}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}getInternalCodecId(){return d(this,null,function*(){return this._backing.getInternalCodecId()})}get internalCodecId(){return ca(this._backing.getInternalCodecId(),"internalCodecId","getInternalCodecId")}getLanguageCode(){return d(this,null,function*(){return this._backing.getLanguageCode()})}get languageCode(){return ca(this._backing.getLanguageCode(),"languageCode","getLanguageCode")}getName(){return d(this,null,function*(){return this._backing.getName()})}get name(){return ca(this._backing.getName(),"name","getName")}getTimeResolution(){return d(this,null,function*(){return this._backing.getTimeResolution()})}get timeResolution(){return ca(this._backing.getTimeResolution(),"timeResolution","getTimeResolution")}isRelativeToUnixEpoch(){return d(this,null,function*(){return this._backing.isRelativeToUnixEpoch()})}getDisposition(){return d(this,null,function*(){return this._backing.getDisposition()})}get disposition(){return ca(this._backing.getDisposition(),"disposition","getDisposition")}getBitrate(){return d(this,null,function*(){return this._backing.getBitrate()})}getAverageBitrate(){return d(this,null,function*(){return this._backing.getAverageBitrate()})}getFirstTimestamp(){return d(this,null,function*(){var e;const t=yield this._backing.getFirstPacket({metadataOnly:!0});return null!=(e=null==t?void 0:t.timestamp)?e:0})}computeDuration(e){return d(this,null,function*(){var t,i;const r=yield this._backing.getPacket(1/0,c({metadataOnly:!0},e)),n=(null!=(t=null==r?void 0:r.timestamp)?t:0)+(null!=(i=null==r?void 0:r.duration)?i:0);return Y(n,yield this.getTimeResolution())})}getDurationFromMetadata(){return d(this,arguments,function*(e={}){return this._backing.getDurationFromMetadata(e)})}computePacketStats(e=1/0,t){return d(this,null,function*(){const i=new Gs(this);let r=1/0,n=-1/0,s=0,a=0;try{for(var o,l,u,d=p(i.packets(void 0,void 0,c({metadataOnly:!0},t)));o=!(l=yield d.next()).done;o=!1){const t=l.value;if(s>=e&&t.timestamp>=n)break;r=Math.min(r,t.timestamp),n=Math.max(n,t.timestamp+t.duration),s++,a+=t.byteLength}}catch(l){u=[l]}finally{try{o&&(l=d.return)&&(yield l.call(d))}finally{if(u)throw u[0]}}return{packetCount:s,averagePacketRate:s?Number((s/(n-r)).toPrecision(16)):0,averageBitrate:s?Number((8*a/(n-r)).toPrecision(16)):0}})}isLive(){return d(this,null,function*(){return null!==(yield this._backing.getLiveRefreshInterval())})}getLiveRefreshInterval(){return d(this,null,function*(){return this._backing.getLiveRefreshInterval()})}canBePairedWith(e){if(!(e instanceof la))throw new TypeError("other must be an InputTrack.");return this.input===e.input&&this!==e&&(this._backing.getPairingMask()&e._backing.getPairingMask())!==BigInt("0")}getPairableTracks(e){return d(this,null,function*(){return this.input.getTracks(ga({filter:e=>e.canBePairedWith(this)},e))})}getPairableVideoTracks(e){return d(this,null,function*(){return this.input.getVideoTracks(ga({filter:e=>e.canBePairedWith(this)},e))})}getPairableAudioTracks(e){return d(this,null,function*(){return this.input.getAudioTracks(ga({filter:e=>e.canBePairedWith(this)},e))})}getPrimaryPairableVideoTrack(e){return d(this,null,function*(){return this.input.getPrimaryVideoTrack(ga({filter:e=>e.canBePairedWith(this)},e))})}getPrimaryPairableAudioTrack(e){return d(this,null,function*(){return this.input.getPrimaryAudioTrack(ga({filter:e=>e.canBePairedWith(this)},e))})}hasPairableTrack(e){return d(this,null,function*(){e&&(e=ua(e));const t=yield this.input.getTracks();for(const i of t)if(this.canBePairedWith(i)&&(!e||(yield e(i))))return!0;return!1})}hasPairableVideoTrack(e){return e&&(e=ua(e)),this.hasPairableTrack(t=>d(this,null,function*(){return t.isVideoTrack()&&(!e||(yield e(t)))}))}hasPairableAudioTrack(e){return e&&(e=ua(e)),this.hasPairableTrack(t=>d(this,null,function*(){return t.isAudioTrack()&&(!e||(yield e(t)))}))}}const ca=(e,t,i)=>{if(e instanceof Promise)throw new Error(`'${t}' is deprecated and not available synchronously for this track. Use the preferred '${i}()' instead.`);return e},ua=e=>{if(void 0!==e&&"function"!==typeof e)throw new TypeError("predicate, when provided, must be a function.");return e?t=>{const i=e=>{if("boolean"!==typeof e)throw new TypeError("predicate must return or resolve to a boolean value.");return e},r=e(t);return r instanceof Promise?r.then(i):i(r)}:void 0};class da extends la{constructor(e,t){super(e,t),this._pixelAspectRatioCache=null,this._backing=t}get type(){return"video"}getCodec(){return d(this,null,function*(){return this._backing.getCodec()})}get codec(){return ca(this._backing.getCodec(),"codec","getCodec")}hasOnlyKeyPackets(){return d(this,null,function*(){var e,t,i;return null!=(i=yield null==(t=(e=this._backing).getHasOnlyKeyPackets)?void 0:t.call(e))&&i})}getCodedWidth(){return d(this,null,function*(){return this._backing.getCodedWidth()})}get codedWidth(){return ca(this._backing.getCodedWidth(),"codedWidth","getCodedWidth")}getCodedHeight(){return d(this,null,function*(){return this._backing.getCodedHeight()})}get codedHeight(){return ca(this._backing.getCodedHeight(),"codedHeight","getCodedHeight")}getRotation(){return d(this,null,function*(){return this._backing.getRotation()})}get rotation(){return ca(this._backing.getRotation(),"rotation","getRotation")}getSquarePixelWidth(){return d(this,null,function*(){return this._backing.getSquarePixelWidth()})}get squarePixelWidth(){return ca(this._backing.getSquarePixelWidth(),"squarePixelWidth","getSquarePixelWidth")}getSquarePixelHeight(){return d(this,null,function*(){return this._backing.getSquarePixelHeight()})}get squarePixelHeight(){return ca(this._backing.getSquarePixelHeight(),"squarePixelHeight","getSquarePixelHeight")}getPixelAspectRatio(){return d(this,null,function*(){var e;return null!=(e=this._pixelAspectRatioCache)?e:this._pixelAspectRatioCache=ve({num:(yield this.getSquarePixelWidth())*(yield this.getCodedHeight()),den:(yield this.getSquarePixelHeight())*(yield this.getCodedWidth())})})}get pixelAspectRatio(){var e;return null!=(e=this._pixelAspectRatioCache)?e:this._pixelAspectRatioCache=ve({num:ca(this._backing.getSquarePixelWidth(),"pixelAspectRatio","getPixelAspectRatio")*ca(this._backing.getCodedHeight(),"pixelAspectRatio","getPixelAspectRatio"),den:ca(this._backing.getSquarePixelHeight(),"pixelAspectRatio","getPixelAspectRatio")*ca(this._backing.getCodedWidth(),"pixelAspectRatio","getPixelAspectRatio")})}getDisplayWidth(){return d(this,null,function*(){var e,t;const i=yield null==(t=(e=this._backing).getMetadataDisplayWidth)?void 0:t.call(e);if(null!=i)return i;return(yield this.getRotation())%180===0?this.getSquarePixelWidth():this.getSquarePixelHeight()})}get displayWidth(){var e,t;const i=null==(t=(e=this._backing).getMetadataDisplayWidth)?void 0:t.call(e);if(void 0!==i){const e=ca(i,"displayWidth","getDisplayWidth");if(null!==e)return e}const r=ca(this._backing.getRotation(),"displayWidth","getDisplayWidth")%180===0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight();return ca(r,"displayWidth","getDisplayWidth")}getDisplayHeight(){return d(this,null,function*(){var e,t;const i=yield null==(t=(e=this._backing).getMetadataDisplayHeight)?void 0:t.call(e);if(null!=i)return i;return(yield this.getRotation())%180===0?this.getSquarePixelHeight():this.getSquarePixelWidth()})}get displayHeight(){var e,t;const i=null==(t=(e=this._backing).getMetadataDisplayHeight)?void 0:t.call(e);if(void 0!==i){const e=ca(i,"displayHeight","getDisplayHeight");if(null!==e)return e}const r=ca(this._backing.getRotation(),"displayHeight","getDisplayHeight")%180===0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth();return ca(r,"displayHeight","getDisplayHeight")}getColorSpace(){return d(this,null,function*(){return this._backing.getColorSpace()})}hasHighDynamicRange(){return d(this,null,function*(){const e=yield this._backing.getColorSpace();return"bt2020"===e.primaries||"smpte432"===e.primaries||"pg"===e.transfer||"hlg"===e.transfer||"bt2020-ncl"===e.matrix})}canBeTransparent(){return d(this,null,function*(){return this._backing.canBeTransparent()})}getDecoderConfig(){return d(this,null,function*(){return this._backing.getDecoderConfig()})}getCodecParameterString(){return d(this,null,function*(){var e,t,i;const r=yield null==(t=(e=this._backing).getMetadataCodecParameterString)?void 0:t.call(e);if(null!=r)return r;const n=yield this._backing.getDecoderConfig();return null!=(i=null==n?void 0:n.codec)?i:null})}canDecode(){return d(this,null,function*(){try{const e=yield this._backing.getDecoderConfig();if(!e)return!1;const t=yield this._backing.getCodec();if(y(null!==t),Ks.some(i=>i.supports(t,e)))return!0;if("undefined"===typeof VideoDecoder)return!1;return!0===(yield VideoDecoder.isConfigSupported(e)).supported}catch(e){return console.error("Error during decodability check:",e),!1}})}determinePacketType(e){return d(this,null,function*(){if(!(e instanceof Yt))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("packet must not be metadata-only to determine its type.");const t=yield this.getCodec();if(null===t)return null;const i=yield this.getDecoderConfig();return y(i),Lt(t,i,e.data)})}}class ha extends la{constructor(e,t){super(e,t),this._backing=t}get type(){return"audio"}getCodec(){return d(this,null,function*(){return this._backing.getCodec()})}get codec(){return ca(this._backing.getCodec(),"codec","getCodec")}hasOnlyKeyPackets(){return d(this,null,function*(){var e,t,i;return null==(i=yield null==(t=(e=this._backing).getHasOnlyKeyPackets)?void 0:t.call(e))||i})}getNumberOfChannels(){return d(this,null,function*(){return this._backing.getNumberOfChannels()})}get numberOfChannels(){return ca(this._backing.getNumberOfChannels(),"numberOfChannels","getNumberOfChannels")}getSampleRate(){return d(this,null,function*(){return this._backing.getSampleRate()})}get sampleRate(){return ca(this._backing.getSampleRate(),"sampleRate","getSampleRate")}getDecoderConfig(){return d(this,null,function*(){return this._backing.getDecoderConfig()})}getCodecParameterString(){return d(this,null,function*(){var e,t,i;const r=yield null==(t=(e=this._backing).getMetadataCodecParameterString)?void 0:t.call(e);if(null!=r)return r;const n=yield this._backing.getDecoderConfig();return null!=(i=null==n?void 0:n.codec)?i:null})}canDecode(){return d(this,null,function*(){try{const e=yield this._backing.getDecoderConfig();if(!e)return!1;const t=yield this._backing.getCodec();if(y(null!==t),js.some(i=>i.supports(t,e)))return!0;if(e.codec.startsWith("pcm-"))return!0;if("undefined"===typeof AudioDecoder)return!1;return!0===(yield AudioDecoder.isConfigSupported(e)).supported}catch(e){return console.error("Error during decodability check:",e),!1}})}determinePacketType(e){return d(this,null,function*(){if(!(e instanceof Yt))throw new TypeError("packet must be an EncodedPacket.");return null===(yield this.getCodec())?null:"key"})}}const fa=e=>-(null!=e?e:-1/0),ma=e=>-e,pa=e=>{if("object"!==typeof e||!e)throw new TypeError("query must be an object.");if(void 0!==e.filter&&"function"!==typeof e.filter)throw new TypeError("query.filter, when provided, must be a function.");if(void 0!==e.sortBy&&"function"!==typeof e.sortBy)throw new TypeError("query.sortBy, when provided, must be a function.");return{filter:e.filter?t=>{const i=e=>{if("boolean"!==typeof e)throw new TypeError("query.filter must return or resolve to a boolean.");return e},r=e.filter(t);return r instanceof Promise?r.then(i):i(r)}:void 0,sortBy:e.sortBy?t=>{const i=e=>{if("number"!==typeof e&&(!Array.isArray(e)||!e.every(e=>"number"===typeof e)))throw new TypeError("query.sortBy must return or resolve to a number or an array of numbers.");return e},r=e.sortBy(t);return r instanceof Promise?r.then(i):i(r)}:void 0}},ga=(e,t)=>({filter:(null==e?void 0:e.filter)||(null==t?void 0:t.filter)?i=>{var r,n;const s=null==(n=null==(r=null==e?void 0:e.filter)?void 0:r.call(e,i))||n,a=e=>{var r,n;return!1!==e&&(null==(n=null==(r=null==t?void 0:t.filter)?void 0:r.call(t,i))||n)};return s instanceof Promise?s.then(a):a(s)}:void 0,sortBy:(null==e?void 0:e.sortBy)||(null==t?void 0:t.sortBy)?i=>{var r,n,s,a;const o=null!=(n=null==(r=null==e?void 0:e.sortBy)?void 0:r.call(e,i))?n:[],l=null!=(a=null==(s=null==t?void 0:t.sortBy)?void 0:s.call(t,i))?a:[],c=(e,t)=>[...Array.isArray(e)?e:[e],...Array.isArray(t)?t:[t]];return o instanceof Promise||l instanceof Promise?Promise.all([o,l]).then(([e,t])=>c(e,t)):c(o,l)}:void 0}),ka=(e,t)=>d(null,null,function*(){let i=e;if(null==t?void 0:t.filter){const r=e.map(e=>t.filter(e));if(r.some(e=>e instanceof Promise)){const t=yield Promise.all(r);i=e.filter((e,i)=>t[i])}else i=e.filter((e,t)=>r[t])}if(!(null==t?void 0:t.sortBy))return i;const r=i.map(e=>t.sortBy(e)),n=r.some(e=>e instanceof Promise)?yield Promise.all(r):r;return i.map((e,t)=>({track:e,sortValue:n[t]})).sort((e,t)=>{var i,r;const n=Array.isArray(e.sortValue)?e.sortValue:[e.sortValue],s=Array.isArray(t.sortValue)?t.sortValue:[t.sortValue],a=Math.max(n.length,s.length);for(let o=0;oe.track)});ke();const ya=2;let ba=null;"undefined"!==typeof FinalizationRegistry&&(ba=new FinalizationRegistry(e=>{for(const t of e)t.freed||t.free()}));class Ta extends Ie{get disposed(){return this._disposed}constructor(e){var t,i;if(super(),this._demuxerPromise=null,this._format=null,this._trackBackingsCache=null,this._backingToTrack=new Map,this._disposed=!1,this._nextSourceCacheAge=0,this._sourceRefs=[],this._sourceCache=[],this._sourceCachePromises=[],this._onFormatDetermined=null,!e||"object"!==typeof e)throw new TypeError("options must be an object.");if(!Array.isArray(e.formats)||e.formats.some(e=>!(e instanceof Jn)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof xn||e.source instanceof Cn))throw new TypeError("options.source must be a Source or SourceRef.");if(e.source instanceof xn&&e.source._disposed)throw new TypeError("options.source must not be a disposed Source.");if(void 0!==e.initInput&&!(e.initInput instanceof Ta))throw new TypeError("options.initInput, when provided, must be an Input.");void 0!==e.formatOptions&&((e,t)=>{if(!e||"object"!==typeof e)throw new TypeError(`${t}, when provided, must be an object.`);if(void 0!==e.isobmff){if(!e.isobmff||"object"!==typeof e.isobmff)throw new TypeError(`${t}.isobmff, when provided, must be an object.`);if(void 0!==e.isobmff.resolveKeyId&&"function"!==typeof e.isobmff.resolveKeyId)throw new TypeError(`${t}.isobmff.resolveKeyId, when provided, must be a function.`)}})(e.formatOptions,"formatOptions"),this._formats=e.formats,this._initInput=null!=(t=e.initInput)?t:null,this._formatOptions=null!=(i=e.formatOptions)?i:{},e.source instanceof xn?this._rootRef=e.source.ref():this._rootRef=e.source,this._sourceRefs.push(this._rootRef),null==ba||ba.register(this,this._sourceRefs,this)}get _rootSource(){return this._rootRef.source}_getSourceUncached(e){return d(this,null,function*(){y(this._rootSource instanceof Bn);const t=yield this._rootSource._resolveRequest(e);return this._emit("source",{source:t.source,request:e,isRoot:e.isRoot}),t})}_getSourceCached(e,t=1){const i=this._sourceCache.find(i=>i.cacheGroup===t&&En(i.request,e));if(i)return i.age++,Promise.resolve(i.sourceRef.source.ref());const r=this._sourceCachePromises.find(i=>i.cacheGroup===t&&En(i.request,e));if(r)return r.promise.then(e=>e.sourceRef.source.ref());const n=(()=>d(this,null,function*(){const i=yield this._getSourceUncached(e);if(Te(this._sourceCache,e=>e.cacheGroup===t&&1===e.sourceRef.source._refCount)>=4){const e=Se(this._sourceCache,e=>e.cacheGroup===t&&1===e.sourceRef.source._refCount?e.age:1/0);y(-1!==e);const i=this._sourceCache[e];this._sourceCache.splice(e,1),i.sourceRef.free(),((e,t)=>{const i=e.indexOf(t);-1!==i&&e.splice(i,1)})(this._sourceRefs,i.sourceRef)}this._sourceRefs.push(i);const r=this._sourceCachePromises.findIndex(t=>t.request===e);y(-1!==r),this._sourceCachePromises.splice(r,1);return{request:e,sourceRef:i,age:this._nextSourceCacheAge++,cacheGroup:t}}))();return this._sourceCachePromises.push({request:e,cacheGroup:t,promise:n}),n.then(e=>{const t=e.sourceRef.source.ref();return this._sourceCache.push(e),t})}_getDemuxer(){var e;return null!=(e=this._demuxerPromise)?e:this._demuxerPromise=(()=>d(this,null,function*(){var e;this._reader=new wa(this._rootSource),this._emit("source",{source:this._rootSource,request:null,isRoot:!0});for(const t of this._formats){if(yield t._canReadInput(this))return this._format=t,null==(e=this._onFormatDetermined)||e.call(this,t),t._createDemuxer(this)}throw new Sa}))()}get source(){return this._rootSource}getFormat(){return d(this,null,function*(){return yield this._getDemuxer(),y(this._format),this._format})}canRead(){return d(this,null,function*(){try{return yield this._getDemuxer(),!0}catch(e){if(e instanceof Sa)return!1;throw e}})}getFirstTimestamp(e){return d(this,null,function*(){null!=e||(e=yield this.getTracks());const t=e.filter(e=>null!==e);if(0===t.length)return 0;const i=yield Promise.all(t.map(e=>e.getFirstTimestamp()));return Math.min(...i)})}computeDuration(e,t){return d(this,null,function*(){null!=e||(e=yield this.getTracks());const i=e.filter(e=>null!==e);if(0===i.length)return 0;const r=yield Promise.all(i.map(e=>e.computeDuration(t)));return Math.max(...r)})}getDurationFromMetadata(e,t){return d(this,null,function*(){null!=e||(e=yield this.getTracks());const i=e.filter(e=>null!==e),r=(yield Promise.all(i.map(e=>e.getDurationFromMetadata(t)))).filter(e=>null!==e);return 0===r.length?null:Math.max(...r)})}getTracks(e){return d(this,null,function*(){e&&(e=pa(e));const t=(yield this._getTrackBackings()).map(e=>this._wrapBackingAsTrack(e));return ka(t,e)})}getVideoTracks(e){return d(this,null,function*(){e&&(e=pa(e));const t=(yield this.getTracks()).filter(e=>e.isVideoTrack());return ka(t,e)})}getAudioTracks(e){return d(this,null,function*(){e&&(e=pa(e));const t=(yield this.getTracks()).filter(e=>e.isAudioTrack());return ka(t,e)})}getPrimaryVideoTrack(e){return d(this,null,function*(){var t;e&&(e=pa(e));const i=ga(e,{sortBy:e=>d(null,null,function*(){return[ma((yield e.getDisposition()).default),ma(yield e.hasPairableAudioTrack()),ma(!(yield e.hasOnlyKeyPackets())),fa(yield e.getBitrate())]})});return null!=(t=(yield this.getVideoTracks(i))[0])?t:null})}getPrimaryAudioTrack(e){return d(this,null,function*(){var t;e&&(e=pa(e));const i=yield this.getPrimaryVideoTrack(),r=ga(e,{sortBy:e=>d(this,null,function*(){return[ma(!i||e.canBePairedWith(i)),ma((yield e.getDisposition()).default),fa(yield e.getBitrate())]})});return null!=(t=(yield this.getAudioTracks(r))[0])?t:null})}_getTrackBackings(){return d(this,null,function*(){var e;const t=yield this._getDemuxer();return null!=(e=this._trackBackingsCache)?e:this._trackBackingsCache=yield t.getTrackBackings()})}_wrapBackingAsTrack(e){const t=this._backingToTrack.get(e);if(t)return t;const i="video"===e.getType()?new da(this,e):new ha(this,e);return this._backingToTrack.set(e,i),i}getMimeType(){return d(this,null,function*(){return(yield this._getDemuxer()).getMimeType()})}getMetadataTags(){return d(this,null,function*(){return(yield this._getDemuxer()).getMetadataTags()})}dispose(){var e;if(!this._disposed){this._disposed=!0;for(const e of this._sourceRefs)e.free();this._sourceRefs.length=0,null==ba||ba.unregister(this),null==(e=this._demuxerPromise)||e.then(e=>e.dispose())}}[Symbol.dispose](){this.dispose()}}class Sa extends Error{constructor(e="Input has an unsupported or unrecognizable format."){super(e),this.name="UnsupportedInputFormatError"}}class va extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}}class wa{constructor(e){this.source=e}get fileSize(){const e=this.source._getFileSize();if(void 0===e)throw new Error("Reading file size too early; read required first.");return e}get fileSizeNonStrict(){var e;return null!=(e=this.source._getFileSize())?e:null}requestSlice(e,t){if(this.source._disposed)throw new va;if(e<0)return null;if(null!==this.fileSizeNonStrict&&e+t>this.fileSizeNonStrict)return null;if(0===t){const t=new Uint8Array(0);return new Pa(t,P(t),0,e,e)}const i=e+t,r=this.source._read(e,i,0,In);return r instanceof Promise?r.then(t=>t?new Pa(t.bytes,t.view,t.offset,e,i):null):r?new Pa(r.bytes,r.view,r.offset,e,i):null}requestSliceRange(e,t,i){if(this.source._disposed)throw new va;if(e<0)return null;if(null!==this.fileSizeNonStrict)return this.requestSlice(e,$(this.fileSizeNonStrict-e,t,i));{const r=this.requestSlice(e,i),n=r=>r||(y(null!==this.fileSizeNonStrict),this.requestSlice(e,$(this.fileSizeNonStrict-e,t,i)));return r instanceof Promise?r.then(n):n(r)}}requestEntireFile(){if(null!==this.fileSizeNonStrict)return this.requestSlice(0,this.fileSizeNonStrict);return(()=>d(this,null,function*(){const e=[];let t=0;for(;;){if(1===e.length&&null!==this.fileSizeNonStrict)return this.requestSlice(0,this.fileSizeNonStrict);const i=1024*e.length;let r=this.requestSliceRange(i,0,1024);if(r instanceof Promise&&(r=yield r),!r)break;e.push(xa(r,r.length)),t+=r.length}const i=new Uint8Array(t);let r=0;for(const n of e)i.set(n,r),r+=n.length;return new Pa(i,P(i),0,0,t)}))()}}class Pa{constructor(e,t,i,r,n){this.bytes=e,this.view=t,this.offset=i,this.start=r,this.end=n,this.bufferPos=r-i}static tempFromBytes(e){return new Pa(e,P(e),0,0,e.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos(e){this.bufferPos=e-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip(e){this.bufferPos+=e}slice(e,t=this.end-e){if(ethis.end)throw new RangeError("Slicing outside of original slice.");return new Pa(this.bytes,this.view,this.offset,e,e+t)}}const Ia=(e,t)=>{if(e.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.`)},xa=(e,t)=>{Ia(e,t);const i=e.bytes.subarray(e.bufferPos,e.bufferPos+t);return e.bufferPos+=t,i},Ca=e=>(Ia(e,1),e.view.getUint8(e.bufferPos++)),Ba=(e,t)=>{Ia(e,2);const i=e.view.getUint16(e.bufferPos,t);return e.bufferPos+=2,i},Ea=e=>{Ia(e,2);const t=e.view.getUint16(e.bufferPos,!1);return e.bufferPos+=2,t},_a=e=>{Ia(e,3);const t=K(e.view,e.bufferPos,!1);return e.bufferPos+=3,t},Aa=e=>{Ia(e,2);const t=e.view.getInt16(e.bufferPos,!1);return e.bufferPos+=2,t},Fa=(e,t)=>{Ia(e,4);const i=e.view.getUint32(e.bufferPos,t);return e.bufferPos+=4,i},Ra=e=>{Ia(e,4);const t=e.view.getUint32(e.bufferPos,!1);return e.bufferPos+=4,t},Da=e=>{Ia(e,4);const t=e.view.getUint32(e.bufferPos,!0);return e.bufferPos+=4,t},Ma=e=>{Ia(e,4);const t=e.view.getInt32(e.bufferPos,!1);return e.bufferPos+=4,t},Na=(e,t)=>{let i,r;return t?(i=Fa(e,!0),r=Fa(e,!0)):(r=Fa(e,!1),i=Fa(e,!1)),4294967296*r+i},Oa=e=>4294967296*Ra(e)+Ra(e),La=e=>4294967296*Ma(e)+Ra(e),za=e=>{const t=Da(e),i=(e=>{Ia(e,4);const t=e.view.getInt32(e.bufferPos,!0);return e.bufferPos+=4,t})(e);return 4294967296*i+t},Ua=e=>{Ia(e,4);const t=e.view.getFloat32(e.bufferPos,!1);return e.bufferPos+=4,t},qa=e=>{Ia(e,8);const t=e.view.getFloat64(e.bufferPos,!1);return e.bufferPos+=8,t},Wa=(e,t)=>{Ia(e,t);let i="";for(let r=0;rI.decode(xa(e,t)).split("\n").map(e=>e.trim()).filter(e=>{var t;return e.length>0&&!(null==(t=null==i?void 0:i.ignore)?void 0:t.call(i,e))});var Ha,Ka,ja,Xa;(Ka=Ha||(Ha={}))[Ka.Unsynchronisation=128]="Unsynchronisation",Ka[Ka.ExtendedHeader=64]="ExtendedHeader",Ka[Ka.ExperimentalIndicator=32]="ExperimentalIndicator",Ka[Ka.Footer=16]="Footer",(Xa=ja||(ja={}))[Xa.ISO_8859_1=0]="ISO_8859_1",Xa[Xa.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",Xa[Xa.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",Xa[Xa.UTF_8=3]="UTF_8";const $a=128,Qa=10,Ga=["Blues","Classic rock","Country","Dance","Disco","Funk","Grunge","Hip-hop","Jazz","Metal","New age","Oldies","Other","Pop","Rhythm and blues","Rap","Reggae","Rock","Techno","Industrial","Alternative","Ska","Death metal","Pranks","Soundtrack","Euro-techno","Ambient","Trip-hop","Vocal","Jazz & funk","Fusion","Trance","Classical","Instrumental","Acid","House","Game","Sound clip","Gospel","Noise","Alternative rock","Bass","Soul","Punk","Space","Meditative","Instrumental pop","Instrumental rock","Ethnic","Gothic","Darkwave","Techno-industrial","Electronic","Pop-folk","Eurodance","Dream","Southern rock","Comedy","Cult","Gangsta","Top 40","Christian rap","Pop/funk","Jungle music","Native US","Cabaret","New wave","Psychedelic","Rave","Showtunes","Trailer","Lo-fi","Tribal","Acid punk","Acid jazz","Polka","Retro","Musical","Rock 'n' roll","Hard rock","Folk","Folk rock","National folk","Swing","Fast fusion","Bebop","Latin","Revival","Celtic","Bluegrass","Avantgarde","Gothic rock","Progressive rock","Psychedelic rock","Symphonic rock","Slow rock","Big band","Chorus","Easy listening","Acoustic","Humour","Speech","Chanson","Opera","Chamber music","Sonata","Symphony","Booty bass","Primus","Porn groove","Satire","Slow jam","Club","Tango","Samba","Folklore","Ballad","Power ballad","Rhythmic Soul","Freestyle","Duet","Punk rock","Drum solo","A cappella","Euro-house","Dance hall","Goa music","Drum & bass","Club-house","Hardcore techno","Terror","Indie","Britpop","Negerpunk","Polsk punk","Beat","Christian gangsta rap","Heavy metal","Black metal","Crossover","Contemporary Christian","Christian rock","Merengue","Salsa","Thrash metal","Anime","Jpop","Synthpop","Christmas","Art rock","Baroque","Bhangra","Big beat","Breakbeat","Chillout","Downtempo","Dub","EBM","Eclectic","Electro","Electroclash","Emo","Experimental","Garage","Global","IDM","Illbient","Industro-Goth","Jam Band","Krautrock","Leftfield","Lounge","Math rock","New romantic","Nu-breakz","Post-punk","Post-rock","Psytrance","Shoegaze","Space rock","Trop rock","World music","Neoclassical","Audiobook","Audio theatre","Neue Deutsche Welle","Podcast","Indie rock","G-Funk","Dubstep","Garage rock","Psybient"],Ya=(e,t)=>{var i;const r=e.filePos;null!=t.raw||(t.raw={}),null!=(i=t.raw).TAG||(i.TAG=xa(e,$a-3)),e.filePos=r;const n=Ja(e,30);n&&(null!=t.title||(t.title=n));const s=Ja(e,30);s&&(null!=t.artist||(t.artist=s));const a=Ja(e,30);a&&(null!=t.album||(t.album=a));const o=Ja(e,4),l=Number.parseInt(o,10);Number.isInteger(l)&&l>0&&(null!=t.date||(t.date=new Date(l,0,1)));const c=xa(e,30);let u;if(0===c[28]&&0!==c[29]){const i=c[29];i>0&&(null!=t.trackNumber||(t.trackNumber=i)),e.skip(-30),u=Ja(e,28),e.skip(2)}else e.skip(-30),u=Ja(e,30);u&&(null!=t.comment||(t.comment=u));const d=Ca(e);d{const i=xa(e,t),r=me(i.indexOf(0),i.length),n=i.subarray(0,r);let s="";for(let a=0;a{const t=e.filePos,i=Wa(e,3),r=Ca(e),n=Ca(e),s=Ca(e),a=Ra(e);if("ID3"!==i||255===r||255===n||0!==(2155905152&a))return e.filePos=t,null;return{majorVersion:r,revision:n,flags:s,size:Je(a)}},eo=(e,t,i)=>{var r,n,s,a,o,l;if(![2,3,4].includes(t.majorVersion))return void console.warn(`Unsupported ID3v2 major version: ${t.majorVersion}`);const c=xa(e,t.size),u=new to(t,c);if(t.flags&Ha.Footer&&u.removeFooter(),t.flags&Ha.Unsynchronisation&&3===t.majorVersion&&u.ununsynchronizeAll(),t.flags&Ha.ExtendedHeader){const e=u.readU32();3===t.majorVersion?u.pos+=e:u.pos+=e-4}for(;u.pos<=u.bytes.length-u.frameHeaderSize();){const e=u.readId3V2Frame();if(!e)break;const c=u.pos,d=u.pos+e.size;let h=!1,f=!1,m=!1;if(3===t.majorVersion?(h=!!(64&e.flags),f=!!(128&e.flags)):4===t.majorVersion&&(h=!!(4&e.flags),f=!!(8&e.flags),m=!!(2&e.flags)||!!(t.flags&Ha.Unsynchronisation)),h)console.warn(`Skipping encrypted ID3v2 frame ${e.id}`),u.pos=d;else if(f)console.warn(`Skipping compressed ID3v2 frame ${e.id}`),u.pos=d;else{if(m&&u.ununsynchronizeRegion(u.pos,d),null!=i.raw||(i.raw={}),"TXXX"===e.id){const e=null!=(n=(r=i.raw).TXXX)?n:r.TXXX={},t=u.readId3V2TextEncoding(),s=u.readId3V2Text(t,d),a=u.readId3V2Text(t,d);null!=e[s]||(e[s]=a)}else"T"===e.id[0]?null!=(s=i.raw)[a=e.id]||(s[a]=u.readId3V2EncodingAndText(d)):null!=(o=i.raw)[l=e.id]||(o[l]=u.readBytes(e.size));switch(u.pos=c,e.id){case"TIT2":case"TT2":null!=i.title||(i.title=u.readId3V2EncodingAndText(d));break;case"TIT3":case"TT3":null!=i.description||(i.description=u.readId3V2EncodingAndText(d));break;case"TPE1":case"TP1":null!=i.artist||(i.artist=u.readId3V2EncodingAndText(d));break;case"TALB":case"TAL":null!=i.album||(i.album=u.readId3V2EncodingAndText(d));break;case"TPE2":case"TP2":null!=i.albumArtist||(i.albumArtist=u.readId3V2EncodingAndText(d));break;case"TRCK":case"TRK":{const e=u.readId3V2EncodingAndText(d).split("/"),t=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(null!=i.trackNumber||(i.trackNumber=t)),r&&Number.isInteger(r)&&r>0&&(null!=i.tracksTotal||(i.tracksTotal=r))}break;case"TPOS":case"TPA":{const e=u.readId3V2EncodingAndText(d).split("/"),t=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(null!=i.discNumber||(i.discNumber=t)),r&&Number.isInteger(r)&&r>0&&(null!=i.discsTotal||(i.discsTotal=r))}break;case"TCON":case"TCO":{const e=u.readId3V2EncodingAndText(d);let t=/^\((\d+)\)/.exec(e);if(t){const e=Number.parseInt(t[1]);if(void 0!==Ga[e]){null!=i.genre||(i.genre=Ga[e]);break}}if(t=/^\d+$/.exec(e),t){const e=Number.parseInt(t[0]);if(void 0!==Ga[e]){null!=i.genre||(i.genre=Ga[e]);break}}null!=i.genre||(i.genre=e)}break;case"TDRC":case"TDAT":{const e=u.readId3V2EncodingAndText(d),t=new Date(e);Number.isNaN(t.getTime())||null!=i.date||(i.date=t)}break;case"TYER":case"TYE":{const e=u.readId3V2EncodingAndText(d),t=Number.parseInt(e,10);Number.isInteger(t)&&(null!=i.date||(i.date=new Date(t,0,1)))}break;case"USLT":case"ULT":{const e=u.readU8();u.pos+=3,u.readId3V2Text(e,d),null!=i.lyrics||(i.lyrics=u.readId3V2Text(e,d))}break;case"COMM":case"COM":{const e=u.readU8();u.pos+=3,u.readId3V2Text(e,d),null!=i.comment||(i.comment=u.readId3V2Text(e,d))}break;case"APIC":case"PIC":{const e=u.readId3V2TextEncoding();let r;if(2===t.majorVersion){const e=u.readAscii(3);r="PNG"===e?"image/png":"JPG"===e?"image/jpeg":"image/*"}else r=u.readId3V2Text(e,d);const n=u.readU8(),s=u.readId3V2Text(e,d).trimEnd(),a=d-u.pos;if(a>=0){const e=u.readBytes(a);i.images||(i.images=[]),i.images.push({data:e,mimeType:r,kind:3===n?"coverFront":4===n?"coverBack":"unknown",description:s})}}break;default:u.pos+=e.size}u.pos=d}}};class to{constructor(e,t){this.header=e,this.bytes=t,this.pos=0,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength)}frameHeaderSize(){return 2===this.header.majorVersion?6:10}ununsynchronizeAll(){const e=[];for(let t=0;t{const t=this.pos+e;if(t>this.bytes.length)return!1;if(t<=this.bytes.length-this.frameHeaderSize()){this.pos+=e;const t=this.readAscii(4);if("\0\0\0\0"!==t&&!/[0-9A-Z]{4}/.test(t))return!1}return!0};if(!s(i)){const e=4===this.header.majorVersion?t:Je(t);s(e)&&(i=e)}return this.pos=n,{id:e,size:i,flags:r}}}readId3V2TextEncoding(){const e=this.readU8();if(e>3)throw new Error(`Unsupported text encoding: ${e}`);return e}readId3V2Text(e,t){const i=this.pos,r=this.readBytes(t-this.pos);switch(e){case ja.ISO_8859_1:{let e="";for(let t=0;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=me(r.findIndex((e,t)=>0===e&&0===r[t+1]&&t%2===0),r.length);return this.pos=i+Math.min(t+2,r.length),e.decode(r.subarray(2,t))}{const e=me(r.findIndex(e=>0===e),r.length);return this.pos=i+Math.min(e+1,r.length),I.decode(r.subarray(0,e))}case ja.UTF_16_BE_NO_BOM:{const e=new TextDecoder("utf-16be"),t=me(r.findIndex((e,t)=>0===e&&0===r[t+1]&&t%2===0),r.length);return this.pos=i+Math.min(t+2,r.length),e.decode(r.subarray(0,t))}case ja.UTF_8:{const e=me(r.findIndex(e=>0===e),r.length);return this.pos=i+Math.min(e+1,r.length),I.decode(r.subarray(0,e))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";const t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}}class io{constructor(e){this.events=e,this.input=null,this.audioSink=null,this.audioIterator=null,this.audioContext=null,this.gainNode=null,this.audioContextStartTime=0,this.playbackTimeAtStart=0,this.latestScheduledEndTime=0,this.duration=Number.NaN,this.paused=!0,this.volume=.7,this.muted=!1,this.playbackRate=1,this.asyncId=0,this.queuedNodes=new Set}get currentTime(){return this.paused?this.playbackTimeAtStart:(this.audioContext.currentTime-this.audioContextStartTime)*this.playbackRate+this.playbackTimeAtStart}ensureAudioContext(e){if(this.audioContext)return;const t=window.AudioContext||window.webkitAudioContext;try{this.audioContext=new t({sampleRate:e})}catch(i){this.audioContext=new t}this.gainNode=this.audioContext.createGain(),this.gainNode.connect(this.audioContext.destination),this.updateGain()}updateGain(){if(!this.gainNode)return;const e=this.muted?0:this.volume;this.gainNode.gain.value=e*e}stopQueuedNodes(){this.queuedNodes.forEach(e=>e.stop()),this.queuedNodes.clear()}stopIterator(){return d(this,null,function*(){var e;yield null==(e=this.audioIterator)?void 0:e.return(),this.audioIterator=null})}handleNoAudioTrack(){this.audioSink=null,this.ensureAudioContext()}load(e,t){return d(this,null,function*(){++this.asyncId,yield this.stopIterator(),this.stopQueuedNodes(),this.paused=!0,this.playbackTimeAtStart=0,this.audioContextStartTime=0;const{input:i,audioTrack:r,duration:n}=e;return this.input=i,this.duration=n,r?null!==r.codec&&(yield r.canDecode())?(this.ensureAudioContext(r.sampleRate),this.audioSink=new oa(r),void(null==t||t())):(this.audioSink=null,this.ensureAudioContext(),void(null==t||t())):(this.handleNoAudioTrack(),void(null==t||t()))})}runIterator(e){return d(this,null,function*(){if(this.audioSink)for(yield this.stopIterator(),this.audioIterator=this.audioSink.buffers(this.currentTime);;){if(e!==this.asyncId||this.paused)return;const i=this.audioIterator.next(),r=setInterval(()=>{e!==this.asyncId||this.paused?clearInterval(r):"running"===this.audioContext.state&&this.audioContext.currentTime>=this.latestScheduledEndTime-.2&&(this.audioContext.suspend(),this.events.emit("waiting"))},50);let n;try{n=yield i}catch(t){console.error("Audio iterator error:",t);break}finally{clearInterval(r)}if(e!==this.asyncId||this.paused)return;if("suspended"===this.audioContext.state&&(yield this.audioContext.resume(),this.events.emit("canplay"),this.events.emit("playing")),n.done)break;const{buffer:s,timestamp:a}=n.value,o=this.audioContext.createBufferSource();o.buffer=s,o.connect(this.gainNode),o.playbackRate.value=this.playbackRate;const l=this.audioContextStartTime+(a-this.playbackTimeAtStart)/this.playbackRate,c=l+s.duration/this.playbackRate;c>this.latestScheduledEndTime&&(this.latestScheduledEndTime=c),l>=this.audioContext.currentTime?o.start(l):o.start(this.audioContext.currentTime,(this.audioContext.currentTime-l)*this.playbackRate),this.queuedNodes.add(o),o.onended=()=>this.queuedNodes.delete(o)}})}play(){return d(this,null,function*(){if(!this.paused)return;this.audioContext||this.ensureAudioContext(),"suspended"===this.audioContext.state&&(yield this.audioContext.resume()),this.audioContextStartTime=this.audioContext.currentTime,this.latestScheduledEndTime=this.audioContextStartTime,this.paused=!1;const e=++this.asyncId;this.runIterator(e)})}pause(){this.paused||(this.playbackTimeAtStart=this.currentTime,this.paused=!0,this.stopIterator(),this.stopQueuedNodes())}seek(e){return d(this,null,function*(){this.playbackTimeAtStart=Math.max(0,e),this.audioContextStartTime=this.audioContext.currentTime,this.latestScheduledEndTime=this.audioContextStartTime;const t=++this.asyncId;this.paused||this.runIterator(t)})}setVolume(e,t){this.volume=e,this.muted=t,this.updateGain()}setPlaybackRate(e){if(e!==this.playbackRate&&(this.paused||(this.playbackTimeAtStart=this.currentTime,this.audioContextStartTime=this.audioContext.currentTime),this.playbackRate=e,!this.paused)){const e=++this.asyncId;this.runIterator(e)}}destroy(){var e;this.asyncId++,this.pause(),null==(e=this.audioContext)||e.close(),this.audioContext=null,this.input=null,this.audioSink=null}}const ro=/\.m3u8(?:$|[?#])/i;function no(e){return"string"===typeof e&&ro.test(e)}function so(e){const t=function(e){return"string"===typeof e?new Mn(e):e instanceof Blob?new An(e):"undefined"!==typeof ReadableStream&&e instanceof ReadableStream?new Nn(e):null!=e?e:null}(e);return t?new Ta({source:t,formats:no(e)?ws:vs}):null}function ao(e){return d(this,arguments,function*({input:e,videoTrack:t,audioTrack:i}){const r=[t,i].filter(Boolean),n=t||i,s=Boolean(n&&(yield n.isLive()));let a=Number.NaN;return r.length>0&&(a=yield e.getDurationFromMetadata(r,{skipLiveWait:!0}),null!==a||s||(a=yield e.computeDuration(r,{skipLiveWait:!0}))),s?Number.POSITIVE_INFINITY:null!=a?a:Number.NaN})}function oo(e){return d(this,null,function*(){var t,i;return null!=(i=null!=(t=yield e.getAverageBitrate())?t:yield e.getBitrate())?i:0})}class lo{constructor({canvas:e,ctx:t,events:i,timeupdateInterval:r=250,avSyncTolerance:n=.12,dropLateFrames:s=!1,poster:a="",preflightRange:o=!1}){this.canvas=e,this.ctx=t,this.events=i,this.timeupdateInterval=r,this.avSyncTolerance=n,this.dropLateFrames=s,this.poster=a,this.preflightRange=o,this.input=null,this.videoSink=null,this.videoIterator=null,this.nextFrame=null,this.rafId=0,this.asyncId=0,this.width=0,this.height=0,this.duration=Number.NaN,this.audioClock=null,this.lastTimeUpdate=0,this.stalled=!1,this.playbackRate=1,this.posterDrawn=!1,this.isFetching=!1}preflight(e){return d(this,null,function*(){if(!this.preflightRange||"string"!==typeof e||no(e))return!0;try{const t=(yield fetch(e,{method:"HEAD"})).headers.get("accept-ranges");return!(!t||"none"===t)||(this.events.emit("error",new Event("RangeNotSupported")),!1)}catch(t){return console.warn("Preflight check failed:",t),!0}})}drawPoster(){if(!this.poster||this.posterDrawn)return;const e=new Image;e.onload=()=>{this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.canvas.width=e.naturalWidth||this.canvas.width,this.canvas.height=e.naturalHeight||this.canvas.height,this.ctx.drawImage(e,0,0,this.canvas.width,this.canvas.height),this.posterDrawn=!0},e.src=this.poster}stopIterator(){return d(this,null,function*(){var e;yield null==(e=this.videoIterator)?void 0:e.return(),this.videoIterator=null})}clear(){this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height)}load(e,t){return d(this,null,function*(){++this.asyncId,yield this.stopIterator(),this.clear(),this.posterDrawn=!1;const{input:i,videoTrack:r,duration:n}=e;if(this.input=i,this.duration=n,!r)return this.handleNoVideoTrack(),void(null==t||t());if(null===r.codec||!(yield r.canDecode()))return this.handleNoVideoTrack(),void(null==t||t());const s=yield r.canBeTransparent();this.videoSink=new ra(r,{poolSize:2,fit:"contain",alpha:s}),this.width=r.displayWidth,this.height=r.displayHeight,this.canvas.width=this.width,this.canvas.height=this.height,null==t||t(),yield this.resetIterator(0)})}handleNoVideoTrack(){this.videoSink=null,this.width=0,this.height=0,this.canvas.width=0,this.canvas.height=0,this.clear(),this.drawPoster()}resetIterator(e){return d(this,null,function*(){var t,i;if(yield this.stopIterator(),!this.videoSink)return;this.videoIterator=this.videoSink.canvases(e);const r=null!=(t=(yield this.videoIterator.next()).value)?t:null,n=null!=(i=(yield this.videoIterator.next()).value)?i:null;this.nextFrame=n,r?this.ctx.drawImage(r.canvas,0,0):this.drawPoster()})}updateNextFrame(e){return d(this,null,function*(){var t;if(this.videoIterator&&!this.isFetching){this.isFetching=!0;try{for(;;){const i=null!=(t=(yield this.videoIterator.next()).value)?t:null;if(!i||e!==this.asyncId)return;const r=this.audioClock.currentTime,n=this.dropLateFrames?Math.max(.06,this.avSyncTolerance/Math.max(1,this.playbackRate)):0;if(!(this.dropLateFrames&&i.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 d(this,null,function*(){this.asyncId++,yield this.resetIterator(e)})}setPlaybackRate(e){this.playbackRate=Math.max(.1,Number(e)||1)}destroy(){this.asyncId++,this.stop(),this.stopIterator(),this.posterDrawn=!1,this.videoSink=null,this.input=null}}class co{constructor({canvas:e,ctx:t,events:i,option:r={}}){var n,s,a,o,l,c;this.events=i,this.option=r,this.audio=new io(i),this.video=new lo({canvas:e,ctx:t,events:i,timeupdateInterval:null!=(n=r.timeupdateInterval)?n:250,avSyncTolerance:null!=(s=r.avSyncTolerance)?s:.12,dropLateFrames:null!=(a=r.dropLateFrames)&&a,poster:null!=(o=r.poster)?o:"",preflightRange:null!=(l=r.preflightRange)&&l}),this.paused=!0,this.ended=!1,this.readyState=0,this.networkState=0,this.error=null,this.seeking=!1,this.loadSeq=0,this.input=null,this.media=null,null==(c=i.addEventListener)||c.call(i,"ended",()=>{this.ended=!0,this.paused=!0})}load(e){return d(this,null,function*(){const t=++this.loadSeq;this.pause(),this.disposeInput(),this.ended=!1,this.error=null,this.networkState=2,this.readyState=0,setTimeout(()=>this.events.emit("waiting"),0),setTimeout(()=>this.events.emit("loadstart"),0);const i=Number.isFinite(this.option.loadTimeout)?this.option.loadTimeout:0;try{yield Promise.race([this.performLoad(e,t),i>0?this.createTimeout(i):new Promise(()=>{})])}catch(r){if(t!==this.loadSeq)return;this.loadSeq++,this.error={code:4,message:r.message},this.networkState=3,this.events.emit("error")}})}performLoad(e,t){return d(this,null,function*(){if(!(yield this.video.preflight(e)))return;const i=so(e);if(!i)return this.video.handleNoVideoTrack(),void this.audio.handleNoAudioTrack();const r=yield function(e,t){return d(this,null,function*(){const i=yield e.getPrimaryVideoTrack(),r=i?yield i.getPrimaryPairableAudioTrack():yield e.getPrimaryAudioTrack(),n=yield ao({input:e,videoTrack:i,audioTrack:r});return{input:e,videoTrack:i,audioTrack:r,duration:n,isLive:!Number.isFinite(n)&&Boolean((i||r)&&(yield(i||r).isLive())),isHls:no(t),videoMode:no(t)?"auto":"manual",audioMode:no(t)?"auto":"manual"}})}(i,e);if(t!==this.loadSeq)return void i.dispose();this.disposeInput(),this.input=i,this.media=r;let n=!r.videoTrack,s=!r.audioTrack;const a=()=>{n&&s&&(this.readyState=1,this.events.emit("loadedmetadata"),this.events.emit("durationchange"),this.events.emit("progress"))};try{if(yield Promise.all([this.video.load(r,()=>{t===this.loadSeq&&(n=!0,a())}),this.audio.load(r,()=>{t===this.loadSeq&&(s=!0,a())})]),t!==this.loadSeq)return;this.readyState=4,this.networkState=1,this.events.emit("loadeddata"),this.events.emit("canplay"),this.events.emit("canplaythrough"),this.events.emit("progress")}catch(o){if(t!==this.loadSeq)return;this.error={code:4,message:o.message},this.networkState=3,this.events.emit("error"),console.error("MediaBunny load error:",o)}})}createTimeout(e){return new Promise((t,i)=>{setTimeout(()=>i(new Error("Load timeout")),e)})}disposeInput(){var e;null==(e=this.input)||e.dispose(),this.input=null,this.media=null}replaceTracks(e){return d(this,arguments,function*({videoTrack:e,audioTrack:t,videoMode:i,audioMode:r}){if(!this.media)return;const n=u(c({},this.media),{videoTrack:e,audioTrack:t,videoMode:i,audioMode:r}),s=!this.paused,a=this.currentTime;this.pause(),this.ended=!1,this.seeking=!0,this.events.emit("seeking"),this.events.emit("waiting"),n.duration=yield ao(n),this.media=n,yield Promise.all([this.video.load(n),this.audio.load(n)]),yield Promise.all([this.video.seek(a),this.audio.seek(a)]),this.readyState=4,this.networkState=1,this.seeking=!1,this.events.emit("loadedmetadata"),this.events.emit("durationchange"),this.events.emit("progress"),this.events.emit("loadeddata"),this.events.emit("canplay"),this.events.emit("canplaythrough"),this.events.emit("seeked"),s&&(yield this.play())})}selectHlsQuality(e){return d(this,null,function*(){var t,i;if(!(null==(t=this.media)?void 0:t.isHls)||!this.input)return;const r=yield this.input.getVideoTracks(),n="auto"===e?yield this.input.getPrimaryVideoTrack():null!=(i=r.find(t=>t.id===e))?i:this.media.videoTrack;if(!n)return;let s=this.media.audioTrack,a=this.media.audioMode;s&&n.canBePairedWith(s)||(s=yield n.getPrimaryPairableAudioTrack(),a="auto"),yield this.replaceTracks({videoTrack:n,audioTrack:s,videoMode:"auto"===e?"auto":"manual",audioMode:a})})}selectHlsAudio(e){return d(this,null,function*(){var t,i;if(!(null==(t=this.media)?void 0:t.isHls)||!this.input)return;const r=yield this.input.getAudioTracks(),n="auto"===e?this.media.videoTrack?yield this.media.videoTrack.getPrimaryPairableAudioTrack():yield this.input.getPrimaryAudioTrack():null!=(i=r.find(t=>t.id===e))?i:this.media.audioTrack;if(!n)return;let s=this.media.videoTrack,a=this.media.videoMode;s&&n.canBePairedWith(s)||(s=yield n.getPrimaryPairableVideoTrack(),a="auto"),yield this.replaceTracks({videoTrack:s,audioTrack:n,videoMode:a,audioMode:"auto"===e?"auto":"manual"})})}getHlsState(){return function(e){return d(this,null,function*(){var t,i,r,n;if(!(null==e?void 0:e.isHls)||!e.input)return null;const[s,a]=yield Promise.all([e.input.getVideoTracks(),e.videoTrack?e.videoTrack.getPairableAudioTracks():[]]),[o,l]=yield Promise.all([Promise.all(s.map((e,t)=>d(null,null,function*(){return{id:e.id,track:e,index:t,name:yield e.getName(),height:yield e.getDisplayHeight(),bitrate:yield oo(e)}}))),Promise.all(a.map((e,t)=>d(null,null,function*(){const i=yield e.getName(),r=yield e.getLanguageCode();return{id:e.id,track:e,index:t,name:i,lang:r,language:r,bitrate:yield oo(e)}})))]);return{levels:o,audios:l,currentLevel:e.videoTrack&&null!=(t=o.find(t=>t.id===e.videoTrack.id))?t:null,currentAudio:e.audioTrack&&null!=(i=l.find(t=>t.id===e.audioTrack.id))?i:null,videoMode:null!=(r=e.videoMode)?r:"auto",audioMode:null!=(n=e.audioMode)?n:"auto"}})}(this.media)}play(){return d(this,null,function*(){this.paused&&(this.ended&&(this.ended=!1,yield this.seek(0)),this.paused=!1,yield this.audio.play(),this.video.start(this.audio),this.events.emit("play"),this.events.emit("playing"))})}pause(){this.paused||(this.paused=!0,this.audio.pause(),this.video.stop(),this.events.emit("pause"))}seek(e){return d(this,null,function*(){const t=!this.paused;this.ended=!1,this.seeking=!0,this.events.emit("seeking"),this.events.emit("waiting"),this.pause(),yield Promise.all([this.audio.seek(e),this.video.seek(e)]),this.seeking=!1,this.events.emit("seeked"),t&&!this.ended&&(yield this.play())})}setVolume(e,t){this.audio.setVolume(e,t)}setPlaybackRate(e){this.audio.setPlaybackRate(e),this.video.setPlaybackRate(e)}destroy(){this.pause(),this.disposeInput(),this.audio.destroy(),this.video.destroy()}get currentTime(){return this.audio.currentTime}get duration(){var e,t,i;return null!=(i=null!=(t=null==(e=this.media)?void 0:e.duration)?t:this.audio.duration)?i:this.video.duration}get videoWidth(){return this.video.width}get videoHeight(){return this.video.height}}class uo{constructor({art:e,canvas:t,ctx:i,option:r}){var n,s;this.art=e,this.canvas=t,this.option=r,this.events=new k,this.engine=new co({canvas:t,ctx:i,events:this.events,option:r}),this._src=null,this._volume=null!=(n=r.volume)?n:.7,this._muted=!!r.muted,this._playbackRate=1,this.engine.setVolume(this._volume,this._muted),this.setupEventForwarding(),r.source?this.src=r.source:(null==(s=e.option)?void 0:s.url)&&(this.src=e.option.url)}setupEventForwarding(){const{events:e}=this.art.constructor.config;e.forEach(e=>{this.events.addEventListener(e,e=>{this.art.emit(`video:${e.type}`,e)})})}addEventListener(e,t){this.events.addEventListener(e,t)}removeEventListener(e,t){this.events.removeEventListener(e,t)}get src(){return this._src}set src(e){this._src=e,e&&this.engine.load(e)}get currentSrc(){return this._src}get currentTime(){return this.engine.currentTime}set currentTime(e){this.engine.seek(Number(e)||0)}get duration(){return this.engine.duration}get buffered(){return this.createTimeRanges(0,this.engine.duration)}get played(){return this.createTimeRanges(0,this.engine.currentTime)}get seekable(){return this.createTimeRanges(0,this.engine.duration)}createTimeRanges(e,t){const i=this.engine.duration;return!i||Number.isNaN(i)||t<=0?{length:0,start:()=>0,end:()=>0}:{length:1,start:()=>e,end:()=>t}}get paused(){return this.engine.paused}get playing(){return!this.engine.paused&&!this.engine.ended}get ended(){return this.engine.ended}get seeking(){return this.engine.seeking}get readyState(){return this.engine.readyState}get networkState(){return this.engine.networkState}get error(){return this.engine.error}get playbackRate(){return this._playbackRate}set playbackRate(e){const t=Number(e);Number.isNaN(t)||t<=0||(this._playbackRate=t,this.engine.setPlaybackRate(t),this.events.emit("ratechange"))}get volume(){return this._volume}set volume(e){this._volume=function(e,t,i){return Math.max(t,Math.min(i,Number(e)||0))}(e,0,1),this._muted=!1,this.engine.setVolume(this._volume,this._muted),this.events.emit("volumechange")}get muted(){return this._muted}set muted(e){this._muted=!!e,this.engine.setVolume(this._volume,this._muted),this.events.emit("volumechange")}play(){return this.engine.play()}pause(){this.engine.pause()}load(){this._src&&this.engine.load(this._src)}getM3u8State(){return this.engine.getHlsState()}switchM3u8Quality(e){return this.engine.selectHlsQuality(e)}switchM3u8Audio(e){return this.engine.selectHlsAudio(e)}get videoWidth(){return this.engine.videoWidth}get videoHeight(){return this.engine.videoHeight}get poster(){return this.option.poster||""}set poster(e){this.option.poster=e}get autoplay(){return this.option.autoplay||!1}set autoplay(e){}get loop(){return this.option.loop||!1}set loop(e){}get controls(){return!1}set controls(e){}get playsInline(){return!0}set playsInline(e){}get crossOrigin(){return this.option.crossOrigin||""}set crossOrigin(e){}get preload(){return"auto"}set preload(e){}get defaultMuted(){return!1}set defaultMuted(e){}get defaultPlaybackRate(){return 1}set defaultPlaybackRate(e){}canPlayType(e){return"maybe"}getBoundingClientRect(){return this.canvas.getBoundingClientRect()}requestVideoFrameCallback(e){return requestAnimationFrame(t=>{e(t,{presentationTime:this.engine.currentTime,expectedDisplayTime:t+16.6,width:this.engine.videoWidth,height:this.engine.videoHeight,mediaTime:this.engine.currentTime,presentedFrames:0,processingDuration:0,captureTime:t,receiveTime:t,rtpTimestamp:0})})}cancelVideoFrameCallback(e){cancelAnimationFrame(e)}setAttribute(e,t){"src"===e?this.src=t:"autoplay"===e?this.autoplay=t:"loop"===e?this.loop=t:"muted"===e?this.muted=!0:this.canvas.setAttribute(e,t)}destroy(){this.engine.destroy()}}return function(e={}){return t=>{const{constructor:i}=t,{createElement:r}=i.utils,n=r("canvas"),s=n.getContext("2d"),a=new uo({art:t,canvas:n,ctx:s,option:e});t.mediabunny=a;const o={};for(const e in n)"function"===typeof n[e]&&(o[e]=n[e].bind(n));const l=new Set([...Object.getOwnPropertyNames(a),...Object.getOwnPropertyNames(Object.getPrototypeOf(a))]);for(const e of l)"constructor"!==e&&(e in n||Object.defineProperty(n,e,{get(){const t=a[e];return"function"===typeof t?t.bind(a):t},set(t){a[e]=t},configurable:!0,enumerable:!0}));for(const e in o)n[e]=(...t)=>o[e](...t);function c(){var e;(null==(e=t.template)?void 0:e.$player)&&!t.option.autoSize&&Object.assign(n.style,{width:"100%",height:"100%",objectFit:"contain"})}return t.on("resize",c),t.on("video:loadedmetadata",c),function({art:e,shim:t,option:i}){if(i.m3u8)return e.on("video:loadedmetadata",u),e.on("restart",u),{update:u};function r(t){e.controls.cache.has(t)&&e.controls.remove(t)}function n(t){e.setting.find(t)&&e.setting.remove(t)}function s(){r("mediabunny-quality"),n("mediabunny-quality")}function a(){r("mediabunny-audio"),n("mediabunny-audio")}function o(e={}){return e.control||e.setting}function l(r){return d(this,null,function*(){var n;const a=(null==(n=i.m3u8)?void 0:n.quality)||{};if(!o(a)||!(null==r?void 0:r.levels.length))return void s();const l=a.auto||"Auto",c=a.title||"Quality",h=a.getName||(e=>e.name||`${e.height}P`),f=r.currentLevel?h(r.currentLevel):l,m=g(r.levels.map(e=>{var t;return{html:h(e),value:e.id,default:(null==(t=r.currentLevel)?void 0:t.id)===e.id}}),"html").sort((e,t)=>{const i=r.levels.find(t=>t.id===e.value),n=r.levels.find(e=>e.id===t.value);return((null==n?void 0:n.height)||0)-((null==i?void 0:i.height)||0)});m.push({html:l,value:"auto",default:!r.currentLevel});const p=i=>d(null,null,function*(){return yield t.switchM3u8Quality(i.value),e.notice.show=`${c}: ${i.html}`,yield u(),i.html});a.control&&e.controls.update({name:"mediabunny-quality",position:"right",html:f,style:{padding:"0 10px"},selector:m,onSelect:p}),a.setting&&e.setting.update({name:"mediabunny-quality",tooltip:f,html:c,icon:'',width:200,selector:m,onSelect:p})})}function c(r){return d(this,null,function*(){var n;const s=(null==(n=i.m3u8)?void 0:n.audio)||{};if(!o(s)||!(null==r?void 0:r.audios.length)||r.audios.length<2)return void a();const l=s.auto||"Auto",c=s.title||"Audio",h=s.getName||(e=>e.name||e.lang||e.language),f=r.currentAudio?h(r.currentAudio):l,m=g(r.audios.map(e=>{var t;return{html:h(e),value:e.id,default:(null==(t=r.currentAudio)?void 0:t.id)===e.id}}),"html");m.push({html:l,value:"auto",default:!r.currentAudio});const p=i=>d(null,null,function*(){return yield t.switchM3u8Audio(i.value),e.notice.show=`${c}: ${i.html}`,yield u(),i.html});s.control&&e.controls.update({name:"mediabunny-audio",position:"right",html:f,style:{padding:"0 10px"},selector:m,onSelect:p}),s.setting&&e.setting.update({name:"mediabunny-audio",tooltip:f,html:c,icon:'',width:200,selector:m,onSelect:p})})}function u(){return d(this,null,function*(){const e=yield t.getM3u8State();if(!e)return s(),void a();yield Promise.all([l(e),c(e)])})}}({art:t,shim:a,option:e}),t.on("destroy",()=>{delete t.mediabunny,a.destroy()}),n}}}); +!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=Object.defineProperty,t=Object.defineProperties,i=Object.getOwnPropertyDescriptors,r=Object.getOwnPropertySymbols,n=Object.prototype.hasOwnProperty,s=Object.prototype.propertyIsEnumerable,a=(e,t)=>(t=Symbol[e])?t:Symbol.for("Symbol."+e),o=Math.pow,l=(t,i,r)=>i in t?e(t,i,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[i]=r,c=(e,t)=>{for(var i in t||(t={}))n.call(t,i)&&l(e,i,t[i]);if(r)for(var i of r(t))s.call(t,i)&&l(e,i,t[i]);return e},u=(e,r)=>t(e,i(r)),d=(e,t,i)=>new Promise((r,n)=>{var s=e=>{try{o(i.next(e))}catch(t){n(t)}},a=e=>{try{o(i.throw(e))}catch(t){n(t)}},o=e=>e.done?r(e.value):Promise.resolve(e.value).then(s,a);o((i=i.apply(e,t)).next())}),h=function(e,t){this[0]=e,this[1]=t},f=(e,t,i)=>{var r,n=(e,t,r,s)=>{try{var a=i[e](t),o=(t=a.value)instanceof h,l=a.done;Promise.resolve(o?t[0]:t).then(i=>o?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)=>o[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),o={};return i=i.apply(e,t),o[a("asyncIterator")]=()=>o,s("next"),s("throw"),s("return"),o},m=e=>{var t,i=e[a("asyncIterator")],r=!1,n={};return null==i?(i=e[a("iterator")](),t=e=>n[e]=t=>i[e](t)):(i=i.call(e),t=e=>n[e]=t=>{if(r){if(r=!1,"throw"===e)throw t;return t}return r=!0,{done:!1,value:new h(new Promise(r=>{var n=i[e](t);n instanceof Object||(e=>{throw TypeError(e)})("Object expected"),r(n)}),1)}}),n[a("iterator")]=()=>n,t("next"),"throw"in i?t("throw"):n.throw=e=>{throw e},"return"in i&&t("return"),n},p=(e,t,i)=>(t=e[a("asyncIterator")])?t.call(e):(e=e[a("iterator")](),t={},(i=(i,r)=>(r=e[i])&&(t[i]=t=>new Promise((i,n,s)=>(t=r.call(e,t),s=t.done,Promise.resolve(t.value).then(e=>i({value:e,done:s}),n)))))("next"),i("return"),t);function g(e,t){const i=new Map;return e.filter(e=>{const r=e[t];return void 0===r||!i.has(r)&&i.set(r,1)})}class k{constructor(){this.listeners=new Map}addEventListener(e,t){this.listeners.has(e)||this.listeners.set(e,[]),this.listeners.get(e).push(t)}removeEventListener(e,t){const i=this.listeners.get(e);if(!i)return;const r=i.indexOf(t);r>=0&&i.splice(r,1)}emit(e,t){const i=new Event(e);i.detail=t;const r=this.listeners.get(e);r&&r.forEach(e=>e(i))}}function y(e){if(!e)throw new Error("Assertion failed.")}const b=e=>{const t=(e%360+360)%360;if(0===t||90===t||180===t||270===t)return t;throw new Error(`Invalid rotation ${e}.`)},T=e=>e&&e[e.length-1],v=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-o(2,r))},w=e=>{const t=v(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),I=e=>e.constructor===DataView?e:ArrayBuffer.isView(e)?new DataView(e.buffer,e.byteOffset,e.byteLength):new DataView(e),x=new TextDecoder,C=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])),B={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},E=C(B),_={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},R=C(_),F={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},A=C(F),D=e=>!!e&&!!e.primaries&&!!e.transfer&&!!e.matrix&&void 0!==e.fullRange,M={primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0},N=e=>e instanceof ArrayBuffer||"undefined"!==typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e);class O{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}acquire(){return d(this,null,function*(){let e;const t=new Promise(t=>{let i=!1;e=()=>{i||(t(),this.pending--,i=!0)}}),i=this.currentPromise;return this.currentPromise=t,this.pending++,yield i,e})}}const L=/^[0-9a-fA-F]+$/,z=e=>[...e].map(e=>e.toString(16).padStart(2,"0")).join(""),U=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,q=(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},H=(e,t,i)=>{const r=W(e,i(t),i);e.splice(r+1,0,t)},V=()=>{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)},K=(e,t)=>{for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},X=(e,t)=>{for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},$=e=>{throw new Error(`Unexpected value: ${e}`)},G=(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},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)},Y=(e,t)=>({next(){return d(this,null,function*(){const i=yield e.next();return i.done?{value:void 0,done:!0}:{value:t(i.value),done:!1}})},return:()=>e.return(),throw:t=>e.throw(t),[Symbol.asyncIterator](){return this}}),J=(e,t,i)=>Math.max(t,Math.min(i,e)),Z="und",ee=e=>{const t=Math.round(e);return Math.abs(e/t-1)<10*Number.EPSILON?t:e},te=(e,t)=>Math.round(e/t)*t,ie=(e,t)=>Math.round(e*t)/t,re=(e,t)=>Math.floor(e/t)*t,ne=e=>{let t=0;for(;0!==e;)e&=e-1,t++;return t},se=/^[a-z]{3}$/,ae=e=>se.test(e),oe=1e6*(1+Number.EPSILON),le=(e,t)=>{const i=c(c({},e),t);if(e.headers||t.headers){const r=e.headers?ce(e.headers):{},n=t.headers?ce(t.headers):{},s=c({},r);Object.entries(n).forEach(([e,t])=>{const i=Object.keys(s).find(t=>t.toLowerCase()===e.toLowerCase());i&&delete s[i],s[e]=t}),i.headers=s}return i},ce=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},ue=(e,t,i,r,n)=>d(null,null,function*(){let s=0;for(;;)try{return yield e(t,i)}catch(a){if(n())throw a;s++;const e=r(s,a,t);if(null===e)throw a;if(Me._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 Re(1e3*e)),n())throw a}});class de{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}let he=null;const fe=()=>{var e;return null!==he?he:he=!("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 me=null;const pe=()=>{var e;return null!==me?me:me="undefined"!==typeof navigator&&(null==(e=navigator.userAgent)?void 0:e.includes("Firefox"))};let ge=null;const ke=()=>{var e;return null!==ge?ge:ge=!("undefined"===typeof navigator||!(null==(e=navigator.vendor)?void 0:e.includes("Google Inc"))&&!/Chrome/.test(navigator.userAgent))},ye=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.`,be=d(null,null,function*(){}).constructor,Te=e=>e instanceof be||e instanceof Promise||"function"===typeof(null==e?void 0:e.then),ve=(e,t)=>-1!==e?e:t,Se=(e,t,i,r)=>e<=r&&i<=t,we=e=>{const t=atob(e),i=new Uint8Array(t.length);for(let r=0;r{null!=Symbol.dispose||(Symbol.dispose=Symbol("Symbol.dispose"))},Ie=e=>"number"===typeof e&&!Number.isNaN(e),xe=(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("/")},Ce=(e,t)=>{let i=0;for(let r=0;r{let i=-1,r=1/0;for(let n=0;n{y(Number.isInteger(e.num)),y(Number.isInteger(e.den)),y(0!==e.den);let t=Math.abs(e.num),i=Math.abs(e.den);for(;0!==i;){const e=t%i;t=i,i=e}const r=t||1;return{num:e.num/r,den:e.den/r}},_e=(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.`)},Re=e=>new Promise(t=>setTimeout(t,e));class Fe{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 Ae,De;(De=Ae||(Ae={}))[De.Silent=0]="Silent",De[De.Errors=1]="Errors",De[De.Warnings=2]="Warnings",De[De.Info=3]="Info";class Me{constructor(){}static get level(){return Me._level}static set level(e){if(e!==Ae.Silent&&e!==Ae.Errors&&e!==Ae.Warnings&&e!==Ae.Info)throw new TypeError("Invalid log level. Use one of the values of the LogLevel enum.");Me._level=e}static get _emitter(){var e;return null!=(e=Me._emitterInstance)?e:Me._emitterInstance=new Fe}static on(e,t,i){return Me._emitter.on(e,t,i)}static _error(...e){Me._emitter._emit("error",e),Me._level>=Ae.Errors&&console.error(...e)}static _warn(...e){Me._emitter._emit("warn",e),Me._level>=Ae.Warnings&&console.warn(...e)}static _info(...e){Me._emitter._emit("info",e),Me._level>=Ae.Info&&console.info(...e)}}Me._level=Ae.Info,Me._emitterInstance=null;class Ne{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 Oe{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 Le={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1};class ze{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 ze(this.bytes);return e.pos=this.pos,e}}const Ue=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],qe=[-1,1,2,3,4,5,6,8],We=e=>{if(!e||e.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");const t=new ze(e),i=He(t),{frequencyIndex:r,sampleRate:n}=Ve(t),s=t.readBits(4);let a=null;s>=1&&s<=7&&(a=qe[s]);let o=i,l=!1,c=n;if(5===i||29===i)l=29===i,c=Ve(t).sampleRate,o=He(t),22===o&&t.skipBits(4);else for(;t.getBitsLeft()>15;){const e=t.pos;if(695===t.readBits(11)){5===He(t)&&t.readBits(1)&&(c=Ve(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}},He=e=>{const t=e.readBits(5);return 31===t?32+e.readBits(6):t},Ve=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&P(t.description)[4];return Je(e,i+1)}return Ye(e)},et=e=>31&e,tt=e=>{const t=[],i=e.length;for(let r=0;r{const t=e.reduce((e,t)=>e+it.byteLength+t.byteLength,0),i=new Uint8Array(t);let r=0;for(const n of e)i.set(it,r),r+=it.byteLength,i.set(n,r),r+=n.byteLength;return i},nt=(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:Q(e,n,s.byteLength);break;case 4:e.setUint32(n,s.byteLength,!1)}n+=t,r.set(s,n),n+=s.byteLength}return r},st=e=>{try{const t=[],i=[],r=[];for(const o of Ye(e)){const n=e.subarray(o.offset,o.offset+o.length),s=et(n[0]);s===Xe.SPS?t.push(n):s===Xe.PPS?i.push(n):s===Xe.SPS_EXT&&r.push(n)}if(0===t.length)return null;if(0===i.length)return null;const n=t[0],s=ct(n);y(null!==s);const a=100===s.profileIdc||110===s.profileIdc||122===s.profileIdc||144===s.profileIdc;return{configurationVersion:1,avcProfileIndication:s.profileIdc,profileCompatibility:s.constraintFlags,avcLevelIndication:s.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:t,pictureParameterSets:i,chromaFormat:a?s.chromaFormatIdc:null,bitDepthLumaMinus8:a?s.bitDepthLumaMinus8:null,bitDepthChromaMinus8:a?s.bitDepthChromaMinus8:null,sequenceParameterSetExt:a?r:null}}catch(t){return Me._error("Error building AVC Decoder Configuration Record:",t),null}},at=e=>{const t=[];t.push(e.configurationVersion),t.push(e.avcProfileIndication),t.push(e.profileCompatibility),t.push(e.avcLevelIndication),t.push(252|3&e.lengthSizeMinusOne),t.push(224|31&e.sequenceParameterSets.length);for(const i of e.sequenceParameterSets){const e=i.byteLength;t.push(e>>8),t.push(255&e);for(let r=0;r>8),t.push(255&e);for(let r=0;r>8),t.push(255&e);for(let r=0;r{try{const t=I(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=tt(e),r=new ze(i);r.skipBits(1),r.skipBits(2);if(7!==r.readBits(5))return null;const n=r.readAlignedByte(),s=r.readAlignedByte(),a=r.readAlignedByte();v(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=v(r),3===o&&(u=r.readBits(1)),l=v(r),c=v(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:T(ai),n=Math.min(Math.floor(r.maxDpbMbs/(e*i)),16);B=n,E=n}else B=0,E=0}return y(null!==E),{emulationUnpreventedBytes:i,profileIdc:n,constraintFlags:s,levelIdc:a,frameMbsOnlyFlag:b,chromaFormatIdc:o,bitDepthLumaMinus8:l,bitDepthChromaMinus8:c,codedWidth:m,codedHeight:p,displayWidth:g,displayHeight:k,pixelAspectRatio:C,colourPrimaries:S,matrixCoefficients:I,transferCharacteristics:P,fullRangeFlag:x,numReorderFrames:B,maxDecFrameBuffering:E,vuiParametersFlagBitOffset:F,bitstreamRestrictionFlagBitOffset:_,bitstreamRestrictionFlag:R}}catch(i){return Me._error("Error parsing AVC SPS:",i),null}},ut=e=>{const t=v(e);e.skipBits(4),e.skipBits(4);for(let i=0;i<=t;i++)v(e),v(e),e.skipBits(1);e.skipBits(5),e.skipBits(5),e.skipBits(5),e.skipBits(5)},dt=e=>{y(1!==e.bitstreamRestrictionFlag);const t=new Uint8Array(e.emulationUnpreventedBytes.byteLength+64),i=new ze(e.emulationUnpreventedBytes),r=new ze(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)):(y(null!==e.bitstreamRestrictionFlagBitOffset),r.copyBits(e.bitstreamRestrictionFlagBitOffset,i)),r.writeBits(1,1),r.writeBits(1,1),S(r,2),S(r,1),S(r,16),S(r,16),S(r,e.numReorderFrames),S(r,e.maxDecFrameBuffering),r.writeBits(1,1),r.writeBits((8-r.pos%8)%8,0);const n=r.pos/8;return y(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))},ht=(e,t)=>{if(t.description){const i=3&P(t.description)[21];return Je(e,i+1)}return Ye(e)},ft=e=>e>>1&63,mt=e=>{try{const t=new ze(tt(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}=gt(t,i);v(t);const u=v(t);let d=0;3===u&&(d=t.readBits(1));const h=v(t),f=v(t);let m=h,p=f;if(t.readBits(1)){const e=v(t),i=v(t),r=v(t),n=v(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=v(t),k=v(t);v(t);const y=t.readBits(1);let b=0;for(let e=y?0:i;e<=i;e++)v(t),b=v(t),v(t);v(t),v(t),v(t),v(t),v(t),v(t),t.readBits(1)&&t.readBits(1)&&kt(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(4),t.skipBits(4),v(t),v(t),t.skipBits(1));const T=v(t);if(yt(t,T),t.readBits(1)){const e=v(t);for(let i=0;i{try{const t=[],i=[],r=[],n=[];for(const l of Ye(e)){const s=e.subarray(l.offset,l.offset+l.length),a=ft(s[0]);a===Ge.VPS_NUT?t.push(s):a===Ge.SPS_NUT?i.push(s):a===Ge.PPS_NUT?r.push(s):a!==Ge.PREFIX_SEI_NUT&&a!==Ge.SUFFIX_SEI_NUT||n.push(s)}if(0===i.length||0===r.length)return null;const s=mt(i[0]);if(!s)return null;let a=0;if(r.length>0){const e=r[0],t=new ze(tt(e));t.skipBits(16),v(t),v(t),t.skipBits(1),t.skipBits(1),t.skipBits(3),t.skipBits(1),t.skipBits(1),v(t),v(t),w(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&v(t),w(t),w(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:Ge.VPS_NUT,nalUnits:t}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:Ge.SPS_NUT,nalUnits:i}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:Ge.PPS_NUT,nalUnits:r}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:ft(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 Me._error("Error building HEVC Decoder Configuration Record:",t),null}},gt=(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&&w(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-(v(e)+1)}else o=t-1;e.readBits(1),v(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=v(e),i=v(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=lt[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)&&(v(e),v(e)),e.readBits(1),e.readBits(1),e.readBits(1),e.readBits(1)&&(v(e),v(e),v(e),v(e)),e.readBits(1)&&(e.readBits(32),e.readBits(32),e.readBits(1)&&v(e),e.readBits(1)&&vt(e,!0,t)),e.readBits(1)&&(e.readBits(1),e.readBits(1),e.readBits(1),a=v(e),v(e),v(e),v(e),v(e)),{pixelAspectRatio:o,colourPrimaries:i,transferCharacteristics:r,matrixCoefficients:n,fullRangeFlag:s,minSpatialSegmentationIdc:a}},vt=(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?v(e):i=1===e.readBits(1);let a=1;if(!i){a=v(e)+1}r&&St(e,a,s),n&&St(e,a,s)}},St=(e,t,i)=>{for(let r=0;r{const i=new Set;let r=wt.audAllowed;for(const s of ht(e,t)){if(r===wt.noMoreDataAllowed){i.add(s.offset);continue}const t=ft(e[s.offset]);if(r===wt.eoBitstreamAllowed&&37!==t){i.add(s.offset);continue}let n=!1;35===t?r>wt.audAllowed?n=!0:r=wt.beforeFirstVcl:t<=31?r>wt.afterFirstVcl?n=!0:r=wt.afterFirstVcl:36===t?r!==wt.afterFirstVcl?n=!0:r=wt.eoBitstreamAllowed:37===t?r=41&&t<=44||t>=48&&t<=55?r>wt.beforeFirstVcl?n=!0:r=wt.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 nt(e,i+1)}return rt(e)})(n,t)},xt={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}},Ct=e=>{var t,i,r;const n=new ze(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=T(oi).level;for(const m of oi)if(d<=m.maxPictureSize){h=m.level;break}const f=xt[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}},Bt=function*(e){const t=new ze(e),i=()=>{let e=0;for(let i=0;i<8;i++){const r=t.readAlignedByte();if(e+=(127&r)*o(2,7*i),!(128&r))break;if(7===i&&128&r)return null}return e>o(2,32)-1?null:e};for(;t.getBitsLeft()>=8;){t.skipBits(1);const r=t.readBits(4),n=t.readBits(1),s=t.readBits(1);let a;if(t.skipBits(1),n&&t.skipBits(8),s){const e=i();if(null===e)return;a=e}else a=Math.floor(t.getBitsLeft()/8);y(t.pos%8===0),yield{type:r,data:e.subarray(t.pos/8,t.pos/8+a)},t.skipBits(8*a)}},Et=e=>{for(const{type:t,data:i}of Bt(e)){if(1!==t)continue;const e=new ze(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},_t=e=>{if(e.length<36)return null;const t=I(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)}},Rt=[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],Ft=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}},At=(e,t,i)=>{switch(e){case"avc":for(const e of Ze(i,t)){const t=i[e.offset],r=et(t);if(r>=Xe.NON_IDR_SLICE&&r<=Xe.SLICE_DPC)return"delta";if(r===Xe.IDR)return"key";if(r===Xe.SEI&&!ke()){const t=i.subarray(e.offset,e.offset+e.length),r=tt(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 ze(r);e.pos=8*n;const t=v(e),i=e.readBits(1);if(0===t&&1===i)return"key"}n+=t}while(n{var i,r;const n=I(e);let s=0;const a=n.getUint32(s,!0);s+=4;const o=x.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=we(c),i=I(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=x.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})}}}},Ot=[2,1,2,3,3,4,4,5],Lt=e=>{if(e.length<7)return null;if(11!==e[0]||119!==e[1])return null;const t=new ze(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)}},zt=[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],Ut=[1,2,3,6],qt=e=>{if(e.length<6)return null;if(11!==e[0]||119!==e[1])return null;const t=new ze(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=Ut[s];let d;d=n<3?je[n]/1e3:Ke[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}]}},Wt=e=>{const t=e.substreams[0];return y(t),t.fscod<3?je[t.fscod]:null!==t.fscod2&&t.fscod2<3?Ke[t.fscod2]:null},Ht=e=>{const t=e.substreams[0];y(t);let i=Ot[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},Vt=[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],Kt=[16,16,20,20,0,24,24,0],Xt=[1,2,2,2,2,3,3,4,4,5,6,6,6,7,8,8],$t=[1,2,2,2,2,3,18,19,6,7,518,323,83,519,582,535],Gt=[32e3,44100,48e3,0],Qt=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],Yt=[512,1024,2048,4096],Jt=e=>{const t=ei(e),i=I(e);let r=t?4*Math.ceil(t.frameSize/4):0,n=null;for(;r+4<=e.length&&1683496997===i.getUint32(r);){const t=ti(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}},Zt=e=>{const t=Jt(e);return(null==t?void 0:t.core)?t.hasExtensions?"dtsh":"dtsc":null},ei=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 ze(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>=Xt.length)return null;const a=Vt[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=Kt[t.readBits(3)];if(0===c)return null;const u=0!==l;return{frameSize:n,sampleRate:a,numberOfChannels:Xt[s]+(u?1:0),sampleCount:32*r,channelLayout:$t[s]|(u?8:0),amode:s,lfePresent:u,bitRate:o,pcmResolution:c}},ti=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 ze(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=Gt[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}}},ii=e=>ne(e)+ne(44646&e),ri=["avc","hevc","vp9","av1","vp8","prores"],ni=["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"],si=["aac","opus","mp3","vorbis","flac","ac3","eac3","dts",...ni],ai=[{maxMacroblocks:99,maxBitrate:64e3,maxDpbMbs:396,level:10},{maxMacroblocks:396,maxBitrate:192e3,maxDpbMbs:900,level:11},{maxMacroblocks:396,maxBitrate:384e3,maxDpbMbs:2376,level:12},{maxMacroblocks:396,maxBitrate:768e3,maxDpbMbs:2376,level:13},{maxMacroblocks:396,maxBitrate:2e6,maxDpbMbs:2376,level:20},{maxMacroblocks:792,maxBitrate:4e6,maxDpbMbs:4752,level:21},{maxMacroblocks:1620,maxBitrate:4e6,maxDpbMbs:8100,level:22},{maxMacroblocks:1620,maxBitrate:1e7,maxDpbMbs:8100,level:30},{maxMacroblocks:3600,maxBitrate:14e6,maxDpbMbs:18e3,level:31},{maxMacroblocks:5120,maxBitrate:2e7,maxDpbMbs:20480,level:32},{maxMacroblocks:8192,maxBitrate:2e7,maxDpbMbs:32768,level:40},{maxMacroblocks:8192,maxBitrate:5e7,maxDpbMbs:32768,level:41},{maxMacroblocks:8704,maxBitrate:5e7,maxDpbMbs:34816,level:42},{maxMacroblocks:22080,maxBitrate:135e6,maxDpbMbs:110400,level:50},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:51},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:52},{maxMacroblocks:139264,maxBitrate:24e7,maxDpbMbs:696320,level:60},{maxMacroblocks:139264,maxBitrate:48e7,maxDpbMbs:696320,level:61},{maxMacroblocks:139264,maxBitrate:8e8,maxDpbMbs:696320,level:62}],oi=[{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}],li=".01.01.01.01.00",ci=".0.110.01.01.01.0",ui=["ap4x","ap4h","apch","apcn","apcs","apco"],di=["dtsc","dtsh","dtsl","dtse"],hi=e=>{const{codec:t,codecDescription:i,colorSpace:r,avcCodecInfo:n,hevcCodecInfo:s,vp9CodecInfo:a,av1CodecInfo:o,proresFormat:l}=e;if("avc"===t){if(y(null!==e.avcType),n){const t=new Uint8Array([n.avcProfileIndication,n.profileCompatibility,n.avcLevelIndication]);return`avc${e.avcType}.${z(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}.${z(i.subarray(1,4))}`}if("hevc"===t){let e,t,r,n,a,o;if(s)e=s.generalProfileSpace,t=s.generalProfileIdc,r=U(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=I(i),l=s.getUint8(1);e=l>>6&3,t=31&l,r=U(s.getUint32(2)),n=l>>5&1,a=s.getUint8(12),o=[];for(let e=0;e<6;e++)o.push(s.getUint8(6+e))}let l="hev1.";for(l+=["","A","B","C"][e]+t,l+=".",l+=r.toString(16).toUpperCase(),l+=".",l+=0===n?"L":"H",l+=a;o.length>0&&0===o[o.length-1];)o.pop();return o.length>0&&(l+=".",l+=o.map(e=>e.toString(16).toUpperCase()).join(".")),l}if("vp8"===t)return"vp8";if("vp9"===t){if(!a){const t=e.width*e.height;let i=T(oi).level;for(const e of oi)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(li)&&(t=t.slice(0,-15)),t}if("av1"===t){if(!o){const t=e.width*e.height;let i=T(oi).level;for(const e of oi)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)?B[r.primaries]:1,u=(null==r?void 0:r.transfer)?_[r.transfer]:1,d=(null==r?void 0:r.matrix)?F[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(ci)&&(f=f.slice(0,-17)),f}if("prores"===t)return null!=l?l:"apch";throw null!==t&&$(t),new TypeError(`Unhandled codec '${t}'.`)},fi=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=ot(e.codecDescription))?void 0:i.sequenceParameterSets[0]),r){const e=ct(r);if(e)return{primaries:E[e.colourPrimaries],transfer:R[e.transferCharacteristics],matrix:A[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case"hevc":{let t=null==(n=null==(r=e.hevcCodecInfo)?void 0:r.arrays.find(e=>e.nalUnitType===Ge.SPS_NUT))?void 0:n.nalUnits[0];if(!t&&e.codecDescription&&(t=null==(a=null==(s=(e=>{try{const t=I(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===Ge.SPS_NUT))?void 0:a.nalUnits[0]),t){const e=mt(t);if(e)return{primaries:E[e.colourPrimaries],transfer:R[e.transferCharacteristics],matrix:A[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case"vp8":break;case"vp9":if(e.vp9CodecInfo)return{primaries:E[e.vp9CodecInfo.colourPrimaries],transfer:R[e.vp9CodecInfo.transferCharacteristics],matrix:A[e.vp9CodecInfo.matrixCoefficients],fullRange:!!e.vp9CodecInfo.videoFullRangeFlag};break;case"av1":if(e.av1CodecInfo)return{primaries:E[e.av1CodecInfo.colourPrimaries],transfer:R[e.av1CodecInfo.transferCharacteristics],matrix:A[e.av1CodecInfo.matrixCoefficients],fullRange:!!e.av1CodecInfo.videoFullRangeFlag};break;case"prores":if(e.proresCodecInfo)return{primaries:E[e.proresCodecInfo.colourPrimaries],transfer:R[e.proresCodecInfo.transferCharacteristics],matrix:A[e.proresCodecInfo.matrixCoefficients],fullRange:e.proresCodecInfo.fullRange}}return{primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0}},mi=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=We(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&&ni.includes(t))return t;throw new TypeError(`Unhandled codec '${t}'.`)},pi=48e3,gi=/^pcm-([usf])(\d+)(be)?$/,ki=e=>{if(y(ni.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=gi.exec(e);let i;y(t),i="u"===t[1]?"unsigned":"s"===t[1]?"signed":"float";return{dataType:i,sampleSize:Number(t[2])/8,littleEndian:"be"!==t[3],silentValue:"pcm-u8"===e?o(2,7):0}},yi=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":ui.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":di.includes(e)?"dts":"ulaw"===e?"ulaw":"alaw"===e?"alaw":gi.test(e)?e:"webvtt"===e?"webvtt":null,bi=[44100,48e3,32e3],Ti=[-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],vi=1483304551,Si=1231971951,wi=(e,t)=>3===e?3===t?21:36:3===t?13:21,Pi=(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=Ti[16*a*4+16*c+(n>>4&15)];if(-1===g)return{header:null,bytesAdvanced:1};const k=1e3*g,y=bi[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 xi,Ci;(Ci=xi||(xi={}))[Ci.FrameCount=1]="FrameCount",Ci[Ci.FileSize=2]="FileSize",Ci[Ci.Toc=4]="Toc";const Bi=e=>3===e?1:2;class Ei{constructor(e){this.input=e}dispose(){}}const _i=new Uint8Array(0);class Ri{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===_i&&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===_i}get microsecondTimestamp(){return Math.trunc(oe*this.timestamp)}get microsecondDuration(){return Math.trunc(oe*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 Ri(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 Ri(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 Fi=e=>{const t=I(e);let i=0;const r=t.getUint8(i);i+=1,i+=3;const n=z(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=Lo(e);const i=Xo(e,4);let r=8;1===t&&(t=Wo(e),r=16);const n=t-r;return n<0?null:{name:i,totalSize:t,headerSize:r,contentSize:n}},Mi=e=>Uo(e)/65536,Ni=e=>Uo(e)/1073741824,Oi=e=>{let t=0;for(let i=0;i<4;i++){t<<=7;const i=Fo(e);if(t|=127&i,0===(128&i))break}return t},Li=e=>{let t=Do(e);return e.skip(2),t=Math.min(t,e.remainingLength),x.decode(Ro(e,t))},zi=e=>{const t=Di(e);if(!t||"data"!==t.name)return null;if(e.remainingLength<8)return null;const i=Lo(e);e.skip(4);const r=Ro(e,t.contentSize-8);switch(i){case 1:return x.decode(r);case 2:return new TextDecoder("utf-16be").decode(r);case 13:return new Ne(r,"image/jpeg");case 14:return new Ne(r,"image/png");case 27:return new Ne(r,"image/bmp");default:return r}},Ui=16,qi=new Uint32Array(256),Wi=new Uint32Array(256),Hi=new Uint32Array(256),Vi=new Uint32Array(256),ji=new Uint32Array(256),Ki=new Uint32Array(256),Xi=new Uint32Array(10);let $i=!1;class Gi{constructor(){this.roundkey=new Uint32Array(44),this.iv=new Uint32Array(Ui/Uint32Array.BYTES_PER_ELEMENT),this.in=new Uint8Array(Ui),this.out=new Uint8Array(Ui),this.inView=new DataView(this.in.buffer),this.outView=new DataView(this.out.buffer)}init({key:e,iv:t}){y(16===e.byteLength),y(16===t.byteLength),$i||(()=>{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);qi[s]=t<<24|t<<16|t<<8|t,Ki[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);Wi[s]=n,Hi[s]=n>>>8|n<<24,Vi[s]=n>>>16|n<<16,ji[s]=n>>>24|n<<8}let n=1;for(let s=0;s<10;s++)Xi[s]=n<<24,n=n<<1^(128&n?283:0);$i=!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&qi[e>>>16&255]^16711680&qi[e>>>8&255]^65280&qi[e>>>0&255]^255&qi[e>>>24&255]^Xi[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]]^Hi[255&qi[t>>>16&255]]^Vi[255&qi[t>>>8&255]]^ji[255&qi[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=Wi[e>>>24]^Hi[r>>>16&255]^Vi[i>>>8&255]^ji[255&t]^this.roundkey[n],c=Wi[t>>>24]^Hi[e>>>16&255]^Vi[r>>>8&255]^ji[255&i]^this.roundkey[n+1],u=Wi[i>>>24]^Hi[t>>>16&255]^Vi[e>>>8&255]^ji[255&r]^this.roundkey[n+2],d=Wi[r>>>24]^Hi[i>>>16&255]^Vi[t>>>8&255]^ji[255&e]^this.roundkey[n+3],e=l,t=c,i=u,r=d}const h=4278190080&Ki[e>>>24&255]^16711680&Ki[r>>>16&255]^65280&Ki[i>>>8&255]^255&Ki[t>>>0&255]^this.roundkey[40],f=4278190080&Ki[t>>>24&255]^16711680&Ki[e>>>16&255]^65280&Ki[r>>>8&255]^255&Ki[i>>>0&255]^this.roundkey[41],m=4278190080&Ki[i>>>24&255]^16711680&Ki[t>>>16&255]^65280&Ki[e>>>8&255]^255&Ki[r>>>0&255]^this.roundkey[42],p=4278190080&Ki[r>>>24&255]^16711680&Ki[i>>>16&255]^65280&Ki[t>>>8&255]^255&Ki[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 Qi extends Ei{constructor(e){super(e),this.moovSlice=null,this.currentTrack=null,this.tracks=[],this.metadataPromise=null,this.movieTimescale=-1,this.movieDurationInTimescale=-1,this.isQuickTime=!1,this.metadataTags={},this.currentMetadataKeys=null,this.isFragmented=!1,this.fragmentTrackDefaults=[],this.psshBoxes=[],this.currentFragment=null,this.lastReadFragment=null,this.decryptionKeyCache=new Map,this.reader=e._reader}getTrackBackings(){return d(this,null,function*(){return yield this.readMetadata(),this.tracks.map(e=>e.trackBacking)})}getMimeType(){return d(this,null,function*(){yield this.readMetadata();const e=yield this.getTrackBackings(),t=yield Promise.all(e.map(e=>e.getDecoderConfig().then(e=>{var t;return null!=(t=null==e?void 0:e.codec)?t:null})));return(e=>{let t=(e.hasVideo?"video/":e.hasAudio?"audio/":"application/")+(e.isQuickTime?"quicktime":"mp4");e.codecStrings.length>0&&(t+=`; codecs="${[...new Set(e.codecStrings)].join(", ")}"`);return t})({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some(e=>{var t;return"video"===(null==(t=e.info)?void 0:t.type)}),hasAudio:this.tracks.some(e=>{var t;return"audio"===(null==(t=e.info)?void 0:t.type)}),codecStrings:t.filter(Boolean)})})}getMetadataTags(){return d(this,null,function*(){return yield this.readMetadata(),this.metadataTags})}readMetadata(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>d(this,null,function*(){let e=0,t=!1,i=!1;for(;;){let r=this.reader.requestSliceRange(e,8,16);if(Te(r)&&(r=yield r),!r)break;const n=e,s=Di(r);if(!s)break;if("ftyp"===s.name||"styp"===s.name){const e=Xo(r,4);this.isQuickTime="qt "===e}else{if("moov"===s.name){let e=this.reader.requestSlice(r.filePos,s.contentSize);if(Te(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){y(null!==this.reader.fileSize);let e=this.reader.requestSlice(this.reader.fileSize-4,4);Te(e)&&(e=yield e),y(e);const t=Lo(e),i=this.reader.fileSize-t;if(i>=0&&i<=this.reader.fileSize-16){let e=this.reader.requestSliceRange(i,8,16);if(Te(e)&&(e=yield e),e){const t=Di(e);if(t&&"mfra"===t.name){let i=this.reader.requestSlice(e.filePos,t.contentSize);Te(i)&&(i=yield i),i&&this.readContiguousBoxes(i)}}}}}))()}copyMetadataFromInitInput(e){return d(this,null,function*(){const t=yield e._getDemuxer();if(t.constructor!==Qi)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(y(t.info),"video"===t.info.type&&-1!==t.info.width){const e=t;t.trackBacking=new Ji(e),this.tracks.push(t)}else if("audio"===t.info.type&&-1!==t.info.numberOfChannels){const e=t;t.trackBacking=new Zi(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;y(this.moovSlice);const n=this.moovSlice.slice(e.sampleTableByteOffset);this.currentTrack=e,this.traverseBox(n),this.currentTrack=null;if("audio"===(null==(t=e.info)?void 0:t.type)&&e.info.codec&&ni.includes(e.info.codec)&&0===r.sampleCompositionTimeOffsets.length){y("audio"===(null==(i=e.info)?void 0:i.type));const t=ki(e.info.codec),n=[],s=[];for(let i=0;ie.startIndex),u=r.sampleTimingEntries[c],d=W(r.sampleTimingEntries,l,e=>e.startIndex),h=r.sampleTimingEntries[d],f=u.startDecodeTimestamp+(o-u.startIndex)*u.delta,m=h.startDecodeTimestamp+(l-h.startIndex)*h.delta-f,p=T(n);p&&p.delta===m?p.count++:n.push({startIndex:a.startChunkIndex+i,startDecodeTimestamp:f,count:1,delta:m});const g=a.samplesPerChunk*t.sampleSize*e.info.numberOfChannels;s.push(g)}a.startSampleIndex=a.startChunkIndex,a.samplesPerChunk=1}r.sampleTimingEntries=n,r.sampleSizes=s}if(r.sampleCompositionTimeOffsets.length>0){r.presentationTimestamps=[];for(const e of r.sampleTimingEntries)for(let t=0;te.presentationTimestamp-t.presentationTimestamp),r.presentationTimestampIndexMap=Array(r.presentationTimestamps.length).fill(-1);for(let e=0;ee.moofOffset===s.moofOffset);if(r)nr(e,r.timestamp);else{const t=W(i,s.moofOffset-1,e=>e.moofOffset);if(-1!==t){const r=i[t];nr(e,r.endTimestamp)}}e.startTimestampIsFinal=!0}const r=W(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 lr(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;ae(t.languageCode)||(t.languageCode=Z)}}break;case"hdlr":{const t=this.currentTrack;if(!t)break;e.skip(8);const i=Xo(e,4);"vide"===i?t.info={type:"video",width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:c({},M),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=Fo(e);e.skip(3);const r=Lo(e);for(let n=0;n0&&(1===a?(e.skip(4),l=8*Lo(e),e.skip(8)):2===a&&(e.skip(4),c=Ko(e),o=Lo(e),e.skip(4),l=Lo(e),u=Lo(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=pi;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(di.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":(Me._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":(Me._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":(Me._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":(Me._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":(Me._warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null):32===e?t.info.codec="pcm-f32be":64===e?t.info.codec="pcm-f64be":(Me._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!==Fo(e),t.encryptionInfo.defaultPerSampleIvSize=Fo(e),t.encryptionInfo.defaultKid=z(Ro(e,16)),t.encryptionInfo.defaultIsProtected&&0===t.encryptionInfo.defaultPerSampleIvSize){const i=Fo(e),r=new Uint8Array(16);r.set(Ro(e,i),0),t.encryptionInfo.defaultConstantIv=r}}break;case"avcC":{const t=this.currentTrack;if(!t)break;if(y(t.info),0===ke.contentSize)break;t.info.codecDescription=Ro(e,ke.contentSize)}break;case"hvcC":{const t=this.currentTrack;if(!t)break;if(y(t.info),0===ke.contentSize)break;t.info.codecDescription=Ro(e,ke.contentSize)}break;case"vpcC":{const i=this.currentTrack;if(!i)break;y("video"===(null==(t=i.info)?void 0:t.type)),e.skip(4);const r=Fo(e),n=Fo(e),s=Fo(e),a=s>>4,o=s>>1&7,l=1&s,c=Fo(e),u=Fo(e),d=Fo(e);i.info.vp9CodecInfo={profile:r,level:n,bitDepth:a,chromaSubsampling:o,videoFullRangeFlag:l,colourPrimaries:c,transferCharacteristics:u,matrixCoefficients:d}}break;case"av1C":{const t=this.currentTrack;if(!t)break;y("video"===(null==(i=t.info)?void 0:i.type)),e.skip(1);const o=Fo(e),l=o>>5,c=31&o,u=Fo(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 b=Ro(e,ke.contentSize-4),T=Et(b);t.info.av1CodecInfo={profile:l,level:c,tier:d,bitDepth:k,monochrome:f,chromaSubsamplingX:m,chromaSubsamplingY:p,chromaSamplePosition:g,videoFullRangeFlag:null!=(r=null==T?void 0:T.videoFullRangeFlag)?r:0,colourPrimaries:null!=(n=null==T?void 0:T.colourPrimaries)?n:2,transferCharacteristics:null!=(s=null==T?void 0:T.transferCharacteristics)?s:2,matrixCoefficients:null!=(a=null==T?void 0:T.matrixCoefficients)?a:2}}break;case"colr":{const t=this.currentTrack;if(!t)break;y("video"===(null==(o=t.info)?void 0:o.type));const i=Xo(e,4);if("nclx"!==i&&"nclc"!==i)break;const r=Do(e),n=Do(e),s=Do(e);let a;"nclx"===i&&(a=Boolean(128&Fo(e))),t.info.colorSpace={primaries:E[r],transfer:R[n],matrix:A[s],fullRange:a}}break;case"pasp":{const t=this.currentTrack;if(!t)break;y("video"===(null==(l=t.info)?void 0:l.type));const i=Lo(e),r=Lo(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==(d=t.info)?void 0:d.type))break;e.skip(4);y(3===Fo(e)),Oi(e),e.skip(2);const i=Fo(e),r=0!==(64&i),n=0!==(32&i);if(0!==(128&i)&&e.skip(2),r){const t=Fo(e);e.skip(t)}n&&e.skip(2);y(4===Fo(e));const s=Oi(e),a=e.filePos,o=Fo(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":Me._warn(`Unsupported audio codec (objectTypeIndication ${o}) - discarding track.`),e.skip(12),s>e.filePos-a){y(5===Fo(e));const i=Oi(e);if(t.info.codecDescription=Ro(e,i),"aac"===t.info.codec){const e=We(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;y("audio"===(null==(h=t.info)?void 0:h.type)),t.info.pcmLittleEndian=!!(255&Do(e))}break;case"pcmC":{const t=this.currentTrack;if(!t)break;y("audio"===(null==(f=t.info)?void 0:f.type)),e.skip(4);const i=Fo(e);t.info.pcmLittleEndian=Boolean(1&i),t.info.pcmSampleSize=Fo(e)}break;case"dOps":{const t=this.currentTrack;if(!t)break;y("audio"===(null==(m=t.info)?void 0:m.type)),e.skip(1);const i=Fo(e),r=Do(e),n=Lo(e),s=No(e),a=Fo(e);let o;o=0!==a?Ro(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;y("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=Ro(e,s-n),o=new Uint8Array(4+a.byteLength);new DataView(o.buffer).setUint32(0,1716281667,!1),o.set(a,4),t.info.codecDescription=o}break;case"dac3":{const t=this.currentTrack;if(!t)break;y("audio"===(null==(g=t.info)?void 0:g.type));const i=Ro(e,3),r=new ze(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=Ot[s]+a}break;case"dec3":{const t=this.currentTrack;if(!t)break;y("audio"===(null==(k=t.info)?void 0:k.type));const i=(e=>{if(e.length<2)return null;const t=new ze(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}})(Ro(e,ke.contentSize));if(!i){Me._warn("Invalid dec3 box contents, ignoring.");break}const r=Wt(i);null!==r&&(t.info.sampleRate=r),t.info.numberOfChannels=Ht(i)}break;case"ddts":{const t=this.currentTrack;if(!t)break;y("audio"===(null==(v=t.info)?void 0:v.type));const i=(e=>{if(e.length<20)return null;const t=I(e),i=t.getUint32(0);if(0===i)return null;const r=new ze(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=ii(o):ae.id===i);if(!r)break;const n=Lo(e),s=(12&n)>>2,a=3&n,o=[Fo,Do,Mo,Lo],l=o[(48&n)>>4],c=o[s],u=o[a],d=Lo(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!=(w=null==d?void 0:d.defaultSampleDescriptionIndex)?w:null,defaultSampleDuration:null!=(P=null==d?void 0:d.defaultSampleDuration)?P:null,defaultSampleSize:null!=(C=null==d?void 0:d.defaultSampleSize)?C:null,defaultSampleFlags:null!=(B=null==d?void 0:d.defaultSampleFlags)?B:null,startTimestamp:null,encryptionAuxInfo:null},i?u.currentFragmentState.baseDataOffset=Wo(e):l&&(u.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),r&&(u.currentFragmentState.sampleDescriptionIndex=Lo(e)),n&&(u.currentFragmentState.defaultSampleDuration=Lo(e)),s&&(u.currentFragmentState.defaultSampleSize=Lo(e)),a&&(u.currentFragmentState.defaultSampleFlags=Lo(e)),o&&(u.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{const t=this.currentTrack;if(!t)break;y(t.currentFragmentState);const i=Fo(e);e.skip(3);const r=0===i?Lo(e):Wo(e);t.currentFragmentState.startTimestamp=r}break;case"trun":{const t=this.currentTrack;if(!t)break;y(this.currentFragment),y(t.currentFragmentState);const i=Fo(e),r=Mo(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=Lo(e);let d=null;n&&(d=Uo(e));let h,f=null;s&&(f=Lo(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=Ro(e,r));const s=or(t);s.defaultSampleInfoSize=i,s.sampleSizes=n,s.sampleCount=r}break;case"saio":{const t=this.currentTrack;if(!t||!t.encryptionInfo)break;const i=Fo(e);if(1&Mo(e)){const i=Xo(e,4),r=Lo(e);if(i!==t.encryptionInfo.scheme||0!==r)break}const r=Lo(e);if(0===r)break;r>1&&Me._warn("Multiple saio entries are not supported; using the first offset only.");let n=0===i?Lo(e):Number(Wo(e));this.currentFragment&&(n+=this.currentFragment.moofOffset);or(t).offset=n}break;case"senc":{const t=this.currentTrack;if(!t||!t.encryptionInfo)break;y(this.currentFragment);const i=this.currentFragment.trackData.get(t.id);if(!i)break;e.skip(1);const r=Mo(e),n=Boolean(2&r),s=Lo(e),a=t.encryptionInfo.defaultPerSampleIvSize;y(null!==a);for(let o=0;o0?r.set(Ro(e,a),0):r.set(t.encryptionInfo.defaultConstantIv,0);let s=null;if(n){const t=Do(e);s=[];for(let i=0;i0&&(null!=(ue=this.metadataTags).trackNumber||(ue.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=I(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=I(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 Yi{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 d(this,null,function*(){var e;const t=this.internalTrack;if(t.durationInMediaTimescale<=0)return null;y(t.trackBacking);const i=yield t.trackBacking.getFirstPacket({metadataOnly:!0});return(null!=(e=null==i?void 0:i.timestamp)?e:0)+t.durationInMediaTimescale/t.timescale})}getLiveRefreshInterval(){return d(this,null,function*(){return null})}getFirstPacket(e){return d(this,null,function*(){const t=yield this.fetchPacketForSampleIndex(0,e);return t||!this.internalTrack.demuxer.isFragmented?t:this.performFragmentedLookup(null,e=>e.trackData.get(this.internalTrack.id)?{sampleIndex:0,correctSampleFound:!0}:{sampleIndex:-1,correctSampleFound:!1},-1/0,1/0,e)})}mapTimestampIntoTimescale(e){return ee(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}getPacket(e,t){return d(this,null,function*(){const i=this.mapTimestampIntoTimescale(e),r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),n=er(r,i),s=yield this.fetchPacketForSampleIndex(n,t);return ar(r)&&this.internalTrack.demuxer.isFragmented?this.performFragmentedLookup(null,e=>{const t=e.trackData.get(this.internalTrack.id);if(!t)return{sampleIndex:-1,correctSampleFound:!1};const r=W(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=X(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 y(-1!==e),{sampleIndex:e,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)})}fetchPacketForSampleIndex(e,t){return d(this,null,function*(){if(-1===e)return null;const i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),r=ir(i,e);if(!r)return null;let n;if(t.metadataOnly)n=_i;else{let t=this.internalTrack.demuxer.reader.requestSlice(r.sampleOffset,r.sampleSize);if(Te(t)&&(t=yield t),!t)return null;if(n=Ro(t,r.sampleSize),this.internalTrack.encryptionInfo){let t=null;if(this.internalTrack.encryptionAuxInfo){const i=yield lr(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);ee.timestamp),f=-1!==h?this.internalTrack.fragmentLookupTable[h]:null,m=W(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(Te(e)&&(e=yield e),!e)break;const i=k,s=Di(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.moofOffsetd(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&&_t(e.data)}}else{const e=yield this.getFirstPacket({}),t=e&&Et(e.data);t&&(this.internalTrack.info.av1CodecInfo=t)}else{const t=yield this.getFirstPacket({}),i=t&&Ct(t.data);i&&(this.internalTrack.info.vp9CodecInfo=u(c({},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&&pt(e.data)}else{const e=yield this.getFirstPacket({});this.internalTrack.info.avcCodecInfo=e&&st(e.data)}if(!D(this.internalTrack.info.colorSpace)){const e=fi(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:hi(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 Zi extends Yi{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 d(this,null,function*(){var e;return this.internalTrack.info.codec?null!=(e=this.decoderConfigPromise)?e:this.decoderConfigPromise=(()=>d(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&&Zt(e.data)}return{codec:mi(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 er=(e,t)=>{if(e.presentationTimestamps){const i=W(e.presentationTimestamps,t,e=>e.presentationTimestamp);return-1===i?-1:e.presentationTimestamps[i].sampleIndex}{const i=W(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)}},tr=(e,t)=>{var i;if(!e.keySampleIndices)return er(e,t);if(e.presentationTimestamps){const i=W(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!==q(e.keySampleIndices,i,e=>e))return i}return-1}{const r=er(e,t),n=W(e.keySampleIndices,r,e=>e);return null!=(i=e.keySampleIndices[n])?i:-1}},ir=(e,t)=>{const i=W(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=W(e.sampleCompositionTimeOffsets,t,e=>e.startIndex),a=e.sampleCompositionTimeOffsets[s];a&&t-a.startIndexe.startSampleIndex),c=e.sampleToChunk[l];y(c);const u=c.startChunkIndex+Math.floor((t-c.startSampleIndex)/c.samplesPerChunk),d=e.chunkOffsets[u],h=c.startSampleIndex+(u-c.startChunkIndex)*c.samplesPerChunk;let f=0,m=d;if(1===e.sampleSizes.length)m+=o*(t-h),f+=o*c.samplesPerChunk;else for(let g=h;ge)}},rr=(e,t)=>{var i;if(!e.keySampleIndices)return t+1;const r=W(e.keySampleIndices,t,e=>e);return null!=(i=e.keySampleIndices[r+1])?i:-1},nr=(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},sr=e=>{const[t,i]=e,r=Math.atan2(i,t);return Number.isFinite(r)?r*(180/Math.PI):0},ar=e=>0===e.sampleSizes.length,or=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}},lr=(e,t,i)=>d(null,null,function*(){if(i.resolved)return i.resolved;if(null===i.offset||0===i.sampleCount)throw new Error("Incomplete saiz/saio info; cannot resolve encryption data.");let r=0;if(i.defaultSampleInfoSize>0)r=i.defaultSampleInfoSize*i.sampleCount;else{y(i.sampleSizes);for(let e=0;e0?i.defaultSampleInfoSize:i.sampleSizes[e],o=new Uint8Array(16);s>0?o.set(Ro(n,s),0):o.set(t.defaultConstantIv,0);let l=null;if(r>s){const e=Do(n);l=[];for(let t=0;te.defaultConstantIv?{iv:e.defaultConstantIv,subsamples:null}:null,ur=(e,t,i,r)=>d(null,null,function*(){var n;y(e.encryptionInfo);const s=e.encryptionInfo;y(null!==s.defaultKid);const a=s.defaultKid;let o;const l=e.demuxer.decryptionKeyCache.get(a);if(l)o=yield l;else{if(!(null==(n=e.demuxer.input._formatOptions.isobmff)?void 0:n.resolveKeyId))throw new Error("Encrypted media samples encountered. To decrypt them, please provide a callback for InputOptions.formatOptions.isobmff.resolveKeyId.");const t=d(null,null,function*(){let t=e.demuxer.psshBoxes;if(r){t=[...t,...r.psshBoxes].filter(e=>null===e.keyIds||e.keyIds.includes(a));for(let e=0;e{y(e.length%2===0);const t=new Uint8Array(e.length/2);for(let i=0;id(null,null,function*(){const n=new Uint8Array(16);n.set(i.iv,0);const s=yield crypto.subtle.importKey("raw",e,{name:"AES-CTR"},!1,["decrypt"]),a=e=>d(null,null,function*(){const t=yield crypto.subtle.decrypt({name:"AES-CTR",counter:n,length:64},s,e);return new Uint8Array(t)});if(!i.subsamples)return a(r);y(null!==t.defaultCryptByteBlock&&null!==t.defaultSkipByteBlock);const o=fr(i.subsamples,t.defaultCryptByteBlock,t.defaultSkipByteBlock);let l=0;for(const e of o)for(const t of e.perSubsample)l+=t.length;const c=new Uint8Array(l);let u=0;for(const e of o)for(const t of e.perSubsample)c.set(r.subarray(t.offset,t.offset+t.length),u),u+=t.length;const h=yield a(c),f=new Uint8Array(r);let m=0;for(const e of o)for(const t of e.perSubsample)f.set(h.subarray(m,m+t.length),t.offset),m+=t.length;return f}),hr=(e,t,i,r)=>{const n=new Gi;n.init({key:e,iv:i.iv});const s=t.defaultCryptByteBlock,a=t.defaultSkipByteBlock;if(y(null!==s&&null!==a),!i.subsamples){const e=new Uint8Array(r),t=Math.floor(r.length/16);for(let i=0;i{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 mr,pr;(pr=mr||(mr={}))[pr.EBML=440786851]="EBML",pr[pr.EBMLVersion=17030]="EBMLVersion",pr[pr.EBMLReadVersion=17143]="EBMLReadVersion",pr[pr.EBMLMaxIDLength=17138]="EBMLMaxIDLength",pr[pr.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",pr[pr.DocType=17026]="DocType",pr[pr.DocTypeVersion=17031]="DocTypeVersion",pr[pr.DocTypeReadVersion=17029]="DocTypeReadVersion",pr[pr.Void=236]="Void",pr[pr.Segment=408125543]="Segment",pr[pr.SeekHead=290298740]="SeekHead",pr[pr.Seek=19899]="Seek",pr[pr.SeekID=21419]="SeekID",pr[pr.SeekPosition=21420]="SeekPosition",pr[pr.Duration=17545]="Duration",pr[pr.Info=357149030]="Info",pr[pr.TimestampScale=2807729]="TimestampScale",pr[pr.MuxingApp=19840]="MuxingApp",pr[pr.WritingApp=22337]="WritingApp",pr[pr.Tracks=374648427]="Tracks",pr[pr.TrackEntry=174]="TrackEntry",pr[pr.TrackNumber=215]="TrackNumber",pr[pr.TrackUID=29637]="TrackUID",pr[pr.TrackType=131]="TrackType",pr[pr.FlagEnabled=185]="FlagEnabled",pr[pr.FlagDefault=136]="FlagDefault",pr[pr.FlagForced=21930]="FlagForced",pr[pr.FlagOriginal=21934]="FlagOriginal",pr[pr.FlagHearingImpaired=21931]="FlagHearingImpaired",pr[pr.FlagVisualImpaired=21932]="FlagVisualImpaired",pr[pr.FlagCommentary=21935]="FlagCommentary",pr[pr.FlagLacing=156]="FlagLacing",pr[pr.Name=21358]="Name",pr[pr.Language=2274716]="Language",pr[pr.LanguageBCP47=2274717]="LanguageBCP47",pr[pr.CodecID=134]="CodecID",pr[pr.CodecPrivate=25506]="CodecPrivate",pr[pr.CodecDelay=22186]="CodecDelay",pr[pr.SeekPreRoll=22203]="SeekPreRoll",pr[pr.DefaultDuration=2352003]="DefaultDuration",pr[pr.Video=224]="Video",pr[pr.PixelWidth=176]="PixelWidth",pr[pr.PixelHeight=186]="PixelHeight",pr[pr.DisplayWidth=21680]="DisplayWidth",pr[pr.DisplayHeight=21690]="DisplayHeight",pr[pr.DisplayUnit=21682]="DisplayUnit",pr[pr.AlphaMode=21440]="AlphaMode",pr[pr.Audio=225]="Audio",pr[pr.SamplingFrequency=181]="SamplingFrequency",pr[pr.Channels=159]="Channels",pr[pr.BitDepth=25188]="BitDepth",pr[pr.SimpleBlock=163]="SimpleBlock",pr[pr.BlockGroup=160]="BlockGroup",pr[pr.Block=161]="Block",pr[pr.BlockAdditions=30113]="BlockAdditions",pr[pr.BlockMore=166]="BlockMore",pr[pr.BlockAdditional=165]="BlockAdditional",pr[pr.BlockAddID=238]="BlockAddID",pr[pr.BlockDuration=155]="BlockDuration",pr[pr.ReferenceBlock=251]="ReferenceBlock",pr[pr.Cluster=524531317]="Cluster",pr[pr.Timestamp=231]="Timestamp",pr[pr.Cues=475249515]="Cues",pr[pr.CuePoint=187]="CuePoint",pr[pr.CueTime=179]="CueTime",pr[pr.CueTrackPositions=183]="CueTrackPositions",pr[pr.CueTrack=247]="CueTrack",pr[pr.CueClusterPosition=241]="CueClusterPosition",pr[pr.Colour=21936]="Colour",pr[pr.MatrixCoefficients=21937]="MatrixCoefficients",pr[pr.TransferCharacteristics=21946]="TransferCharacteristics",pr[pr.Primaries=21947]="Primaries",pr[pr.Range=21945]="Range",pr[pr.Projection=30320]="Projection",pr[pr.ProjectionType=30321]="ProjectionType",pr[pr.ProjectionPoseRoll=30325]="ProjectionPoseRoll",pr[pr.Attachments=423732329]="Attachments",pr[pr.AttachedFile=24999]="AttachedFile",pr[pr.FileDescription=18046]="FileDescription",pr[pr.FileName=18030]="FileName",pr[pr.FileMediaType=18016]="FileMediaType",pr[pr.FileData=18012]="FileData",pr[pr.FileUID=18094]="FileUID",pr[pr.Chapters=272869232]="Chapters",pr[pr.Tags=307544935]="Tags",pr[pr.Tag=29555]="Tag",pr[pr.Targets=25536]="Targets",pr[pr.TargetTypeValue=26826]="TargetTypeValue",pr[pr.TargetType=25546]="TargetType",pr[pr.TagTrackUID=25541]="TagTrackUID",pr[pr.TagEditionUID=25545]="TagEditionUID",pr[pr.TagChapterUID=25540]="TagChapterUID",pr[pr.TagAttachmentUID=25542]="TagAttachmentUID",pr[pr.SimpleTag=26568]="SimpleTag",pr[pr.TagName=17827]="TagName",pr[pr.TagLanguage=17530]="TagLanguage",pr[pr.TagString=17543]="TagString",pr[pr.TagBinary=17541]="TagBinary",pr[pr.ContentEncodings=28032]="ContentEncodings",pr[pr.ContentEncoding=25152]="ContentEncoding",pr[pr.ContentEncodingOrder=20529]="ContentEncodingOrder",pr[pr.ContentEncodingScope=20530]="ContentEncodingScope",pr[pr.ContentCompression=20532]="ContentCompression",pr[pr.ContentCompAlgo=16980]="ContentCompAlgo",pr[pr.ContentCompSettings=16981]="ContentCompSettings",pr[pr.ContentEncryption=20533]="ContentEncryption";const gr=[mr.EBML,mr.Segment],kr=[mr.SeekHead,mr.Info,mr.Cluster,mr.Tracks,mr.Cues,mr.Attachments,mr.Chapters,mr.Tags],yr=[...gr,...kr],br=16,Tr=e=>{if(e.remainingLength<1)return null;const t=Fo(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=Fo(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=Tr(e);if(null===t)return null;if(e.remainingLength{if(e.remainingLength<1)return null;if(255===Fo(e))return;e.skip(-1);const t=vr(e);return null===t?null:72057594037927940!==t?t:void 0},Ir=e=>{y(e.remainingLength>=2);const t=wr(e);if(null===t)return null;const i=Pr(e);return null===i?null:{id:t,size:i}},xr=(e,t)=>{const i=Ro(e,t);let r=0;for(;r{const i=Ro(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):Ko(e)},Er=(e,t,i,r)=>d(null,null,function*(){const n=new Set(i);let s=t;for(;null===r||ss?r:s,found:!1}}),_r=(e,t,i,r)=>d(null,null,function*(){const n=o(2,16),s=new Set(i);let a=t;for(;ae.tracks.map(e=>e.trackBacking))})}getMimeType(){return d(this,null,function*(){yield this.readMetadata();const e=yield this.getTrackBackings(),t=yield Promise.all(e.map(e=>e.getDecoderConfig().then(e=>{var t;return null!=(t=null==e?void 0:e.codec)?t:null})));return(e=>{let t=(e.hasVideo?"video/":e.hasAudio?"audio/":"application/")+(e.isWebM?"webm":"x-matroska");e.codecStrings.length>0&&(t+=`; codecs="${[...new Set(e.codecStrings.filter(Boolean))].join(", ")}"`);return t})({isWebM:this.isWebM,hasVideo:this.segments.some(e=>e.tracks.some(e=>{var t;return"video"===(null==(t=e.info)?void 0:t.type)})),hasAudio:this.segments.some(e=>e.tracks.some(e=>{var t;return"audio"===(null==(t=e.info)?void 0:t.type)})),codecStrings:t.filter(Boolean)})})}getMetadataTags(){return d(this,null,function*(){yield this.readMetadata();for(const t of this.segments)t.metadataTagsCollected||(null!==this.reader.fileSize&&(yield this.loadSegmentMetadata(t)),t.metadataTagsCollected=!0);let e={};for(const t of this.segments)e=c(c({},e),t.metadataTags);return e})}readMetadata(){var e;return null!=(e=this.readMetadataPromise)?e:this.readMetadataPromise=(()=>d(this,null,function*(){let e=0;for(;;){let t=this.reader.requestSliceRange(e,2,br);if(Te(t)&&(t=yield t),!t)break;const i=Ir(t);if(!i)break;const r=i.id;let n=i.size;const s=t.filePos;if(r===mr.EBML){jr(n);let e=this.reader.requestSlice(s,n);if(Te(e)&&(e=yield e),!e)break;this.readContiguousElements(e)}else if(r===mr.Segment){if(yield this.readSegment(s,n),void 0===n)break;if(null===this.reader.fileSize)break}else if(r===mr.Cluster){if(null===this.reader.fileSize)break;if(void 0===n){n=(yield Er(this.reader,s,yr,this.reader.fileSize)).pos-s}const e=T(this.segments);e&&(e.elementEndPos=s+n)}jr(n),e=s+n}}))()}readSegment(e,t){return d(this,null,function*(){var i;this.currentSegment={seekHeadSeen:!1,infoSeen:!1,tracksSeen:!1,cuesSeen:!1,tagsSeen:!1,attachmentsSeen:!1,timestampScale:-1,timestampFactor:-1,duration:-1,seekEntries:[],tracks:[],cuePoints:[],dataStartPos:e,elementEndPos:void 0===t?null:e+t,clusterSeekStartPos:e,lastReadCluster:null,metadataTags:{},metadataTagsCollected:!1},this.segments.push(this.currentSegment);let r=e;for(;null===this.currentSegment.elementEndPos||re.id===s);if(-1!==l){const e=Jr[l].flag;this.currentSegment[e]=!0,jr(a);let t=this.reader.requestSlice(o,a);Te(t)&&(t=yield t),t&&this.readContiguousElements(t)}else if(s===mr.Tags||s===mr.Attachments){s===mr.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,jr(a);let e=this.reader.requestSlice(o,a);Te(e)&&(e=yield e),e&&this.readContiguousElements(e)}else if(s===mr.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=Jr.find(e=>e.id===t.id);if(!i)continue;if(this.currentSegment[i.flag])continue;let r=this.reader.requestSliceRange(e+t.segmentPosition,2,br);if(Te(r)&&(r=yield r),!r)continue;const n=Ir(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);Te(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 d(this,null,function*(){var i;if((null==(i=t.lastReadCluster)?void 0:i.elementStartPos)===e)return t.lastReadCluster;let r=this.reader.requestSliceRange(e,2,br);Te(r)&&(r=yield r),y(r);const n=e,s=Ir(r);y(s);y(s.id===mr.Cluster);let a=s.size;const o=r.filePos;if(void 0===a){a=(yield Er(this.reader,o,yr,t.elementEndPos)).pos-o}let l=this.reader.requestSlice(o,a);Te(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,yr);c.elementEndPos=e}for(const[,e]of c.trackData){const t=e.track;y(e.blocks.length>0);let i=!1;for(let n=0;n({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[T(e.presentationTimestamps).blockIndex];e.startTimestamp=r.timestamp,e.endTimestamp=s.timestamp+s.duration;const a=W(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,d,h,f,m,p,g,k,T,v,S,w,P,I,C,B,_,F,D,N,O,L,z,U,q,W,H,V,j,K,X,$,G,Q,Y,J,ee,te,ie,re,ne,se,oe,le,ce;const ue=Ir(e);if(!ue)return!1;if(t&&t.includes(ue.id))return!1;const{id:de,size:he}=ue,fe=e.filePos;switch(jr(he),de){case mr.DocType:this.isWebM="webm"===xr(e,he);break;case mr.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 mr.SeekID:{const t=null==(i=this.currentSegment)?void 0:i.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.id=Sr(e,he)}break;case mr.SeekPosition:{const t=null==(r=this.currentSegment)?void 0:r.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.segmentPosition=Sr(e,he)}break;case mr.TimestampScale:if(!this.currentSegment)break;this.currentSegment.timestampScale=Sr(e,he),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale;break;case mr.Duration:if(!this.currentSegment)break;this.currentSegment.duration=Br(e,he);break;case mr.TrackEntry:if(!this.currentSegment)break;if(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:u(c({},Le),{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!==$r.Block||e.data.algorithm!==Qr.HeaderStripping})&&(Me._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===Rr)this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(this.currentTrack.codecId===Fr)this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(t===Ar)this.currentTrack.info.codec="vp8";else if(t===Dr)this.currentTrack.info.codec="vp9";else if(t===Mr)this.currentTrack.info.codec="av1";else if(t===Nr){const e=this.currentTrack.codecPrivate?x.decode(this.currentTrack.codecPrivate):"";ui.includes(e)&&(this.currentTrack.info.codec="prores",this.currentTrack.info.proresFormat=e)}const e=this.currentTrack;this.currentTrack.trackBacking=new rn(e),this.currentSegment.tracks.push(this.currentTrack)}else if("audio"===this.currentTrack.info.type){t===Or?(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===Lr?this.currentTrack.info.codec="mp3":t===zr?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=pi):t===Ur?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===qr?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Wr?(this.currentTrack.info.codec="ac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Hr?(this.currentTrack.info.codec="eac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Vr?(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 nn(e),this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null;break;case mr.TrackNumber:if(!this.currentTrack)break;this.currentTrack.id=Sr(e,he);break;case mr.TrackType:{if(!this.currentTrack)break;const t=Sr(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:c({},M),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 mr.FlagEnabled:if(!this.currentTrack)break;Sr(e,he)||(this.currentTrack=null);break;case mr.FlagDefault:if(!this.currentTrack)break;this.currentTrack.disposition.default=!!Sr(e,he);break;case mr.FlagForced:if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!Sr(e,he);break;case mr.FlagOriginal:if(!this.currentTrack)break;this.currentTrack.disposition.original=!!Sr(e,he);break;case mr.FlagHearingImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!Sr(e,he);break;case mr.FlagVisualImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!Sr(e,he);break;case mr.FlagCommentary:if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!Sr(e,he);break;case mr.CodecID:if(!this.currentTrack)break;this.currentTrack.codecId=xr(e,he);break;case mr.CodecPrivate:if(!this.currentTrack)break;this.currentTrack.codecPrivate=Ro(e,he);break;case mr.DefaultDuration:if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=Sr(e,he);break;case mr.Name:if(!this.currentTrack)break;this.currentTrack.name=Cr(e,he);break;case mr.Language:if(!this.currentTrack)break;if(this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=xr(e,he),ae(this.currentTrack.languageCode)||(this.currentTrack.languageCode=Z);break;case mr.LanguageBCP47:{if(!this.currentTrack)break;const t=xr(e,he).split("-")[0];this.currentTrack.languageCode=t||Z,this.currentTrack.hasLanguageBcp47=!0}break;case mr.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 mr.PixelWidth:if("video"!==(null==(o=null==(a=this.currentTrack)?void 0:a.info)?void 0:o.type))break;this.currentTrack.info.width=Sr(e,he);break;case mr.PixelHeight:if("video"!==(null==(d=null==(l=this.currentTrack)?void 0:l.info)?void 0:d.type))break;this.currentTrack.info.height=Sr(e,he);break;case mr.DisplayWidth:if("video"!==(null==(f=null==(h=this.currentTrack)?void 0:h.info)?void 0:f.type))break;this.currentTrack.info.displayWidth=Sr(e,he);break;case mr.DisplayHeight:if("video"!==(null==(p=null==(m=this.currentTrack)?void 0:m.info)?void 0:p.type))break;this.currentTrack.info.displayHeight=Sr(e,he);break;case mr.DisplayUnit:if("video"!==(null==(k=null==(g=this.currentTrack)?void 0:g.info)?void 0:k.type))break;this.currentTrack.info.displayUnit=Sr(e,he);break;case mr.AlphaMode:if("video"!==(null==(v=null==(T=this.currentTrack)?void 0:T.info)?void 0:v.type))break;this.currentTrack.info.alphaMode=1===Sr(e,he);break;case mr.Colour:if("video"!==(null==(w=null==(S=this.currentTrack)?void 0:S.info)?void 0:w.type))break;this.readContiguousElements(e.slice(fe,he));break;case mr.MatrixCoefficients:{if("video"!==(null==(I=null==(P=this.currentTrack)?void 0:P.info)?void 0:I.type))break;const t=Sr(e,he),i=A[t];this.currentTrack.info.colorSpace.matrix=i}break;case mr.Range:{if("video"!==(null==(B=null==(C=this.currentTrack)?void 0:C.info)?void 0:B.type))break;const t=Sr(e,he);this.currentTrack.info.colorSpace.fullRange=1===t||2===t?2===t:void 0}break;case mr.TransferCharacteristics:{if("video"!==(null==(F=null==(_=this.currentTrack)?void 0:_.info)?void 0:F.type))break;const t=Sr(e,he),i=R[t];this.currentTrack.info.colorSpace.transfer=i}break;case mr.Primaries:{if("video"!==(null==(N=null==(D=this.currentTrack)?void 0:D.info)?void 0:N.type))break;const t=Sr(e,he),i=E[t];this.currentTrack.info.colorSpace.primaries=i}break;case mr.Projection:if("video"!==(null==(L=null==(O=this.currentTrack)?void 0:O.info)?void 0:L.type))break;this.readContiguousElements(e.slice(fe,he));break;case mr.ProjectionPoseRoll:{if("video"!==(null==(U=null==(z=this.currentTrack)?void 0:z.info)?void 0:U.type))break;const t=-Br(e,he);try{this.currentTrack.info.rotation=b(t)}catch(me){}}break;case mr.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 mr.SamplingFrequency:if("audio"!==(null==(V=null==(H=this.currentTrack)?void 0:H.info)?void 0:V.type))break;this.currentTrack.info.sampleRate=Br(e,he);break;case mr.Channels:if("audio"!==(null==(K=null==(j=this.currentTrack)?void 0:j.info)?void 0:K.type))break;this.currentTrack.info.numberOfChannels=Sr(e,he);break;case mr.BitDepth:if("audio"!==(null==($=null==(X=this.currentTrack)?void 0:X.info)?void 0:$.type))break;this.currentTrack.info.bitDepth=Sr(e,he);break;case mr.CuePoint:if(!this.currentSegment)break;this.readContiguousElements(e.slice(fe,he)),this.currentCueTime=null;break;case mr.CueTime:this.currentCueTime=Sr(e,he);break;case mr.CueTrackPositions:{if(null===this.currentCueTime)break;y(this.currentSegment);const t={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(t),this.readContiguousElements(e.slice(fe,he)),-1!==t.trackId&&-1!==t.clusterPosition||this.currentSegment.cuePoints.pop()}break;case mr.CueTrack:{const t=null==(G=this.currentSegment)?void 0:G.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;t.trackId=Sr(e,he)}break;case mr.CueClusterPosition:{const t=null==(Q=this.currentSegment)?void 0:Q.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;y(this.currentSegment),t.clusterPosition=this.currentSegment.dataStartPos+Sr(e,he)}break;case mr.Timestamp:if(!this.currentCluster)break;this.currentCluster.timestamp=Sr(e,he);break;case mr.SimpleBlock:{if(!this.currentCluster)break;const t=vr(e);if(null===t)break;const i=this.getTrackDataInCluster(this.currentCluster,t);if(!i)break;const r=No(e),n=Fo(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=Ro(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 mr.BlockGroup:if(!this.currentCluster)break;this.readContiguousElements(e.slice(fe,he)),this.currentBlock=null;break;case mr.Block:{if(!this.currentCluster)break;const t=vr(e);if(null===t)break;const i=this.getTrackDataInCluster(this.currentCluster,t);if(!i)break;const r=No(e),n=Fo(e)>>1&3,s=Ro(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 mr.BlockAdditions:this.readContiguousElements(e.slice(fe,he));break;case mr.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 mr.BlockAdditional:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=Ro(e,he);break;case mr.BlockAddID:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=Sr(e,he);break;case mr.BlockDuration:if(!this.currentBlock)break;this.currentBlock.duration=Sr(e,he);break;case mr.ReferenceBlock:if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1;break;case mr.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(fe,he));break;case mr.Targets:this.readContiguousElements(e.slice(fe,he));break;case mr.TargetTypeValue:50!==Sr(e,he)&&(this.currentTagTargetIsMovie=!1);break;case mr.TagTrackUID:case mr.TagEditionUID:case mr.TagChapterUID:case mr.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case mr.SimpleTag:if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(fe,he));break;case mr.TagName:this.currentSimpleTagName=Cr(e,he);break;case mr.TagString:{if(!this.currentSimpleTagName)break;const t=Cr(e,he);this.processTagValue(this.currentSimpleTagName,t)}break;case mr.TagBinary:{if(!this.currentSimpleTagName)break;const t=Ro(e,he);this.processTagValue(this.currentSimpleTagName,t)}break;case mr.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 Oe(this.currentAttachedFile.fileData,null!=(J=this.currentAttachedFile.fileMediaType)?J:void 0,null!=(ee=this.currentAttachedFile.fileName)?ee:void 0,null!=(te=this.currentAttachedFile.fileDescription)?te:void 0)),(null==(ie=this.currentAttachedFile.fileMediaType)?void 0:ie.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!=(re=this.currentAttachedFile.fileName)?re:void 0,description:null!=(ne=this.currentAttachedFile.fileDescription)?ne:void 0})}this.currentAttachedFile=null}break;case mr.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 mr.ContentEncoding:this.currentDecodingInstruction={order:0,scope:$r.Block,data:null},this.readContiguousElements(e.slice(fe,he)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case mr.ContentEncodingOrder:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=Sr(e,he);break;case mr.ContentEncodingScope:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=Sr(e,he);break;case mr.ContentCompression:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:Qr.Zlib,settings:null},this.readContiguousElements(e.slice(fe,he));break;case mr.ContentCompAlgo:if("decompress"!==(null==(oe=null==(se=this.currentDecodingInstruction)?void 0:se.data)?void 0:oe.type))break;this.currentDecodingInstruction.data.algorithm=Sr(e,he);break;case mr.ContentCompSettings:if("decompress"!==(null==(ce=null==(le=this.currentDecodingInstruction)?void 0:le.data)?void 0:ce.type))break;this.currentDecodingInstruction.data.settings=Ro(e,he);break;case mr.ContentEncryption:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}return e.filePos=fe+he,!0}decodeBlockData(e,t){y(e.decodingInstructions.length>0);let i=t;for(const r of e.decodingInstructions)if(y(r.data),"decompress"===r.data.type)if(r.data.algorithm===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,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 d(this,null,function*(){if(e.duration<=0)return null;let t=null;for(const r of e.tracks){y(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 tn{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 d(this,null,function*(){return this.internalTrack.demuxer.getDurationFromMetadata(this.internalTrack.segment)})}getLiveRefreshInterval(){return d(this,null,function*(){return null})}getFirstPacket(e){return d(this,null,function*(){return this.performClusterLookup(null,e=>e.trackData.get(this.internalTrack.id)?{blockIndex:0,correctBlockFound:!0}:{blockIndex:-1,correctBlockFound:!1},-1/0,1/0,e)})}intoTimescale(e){return ee(e*this.internalTrack.segment.timestampFactor)}getPacket(e,t){return d(this,null,function*(){const i=this.intoTimescale(e);return this.performClusterLookup(null,e=>{const t=e.trackData.get(this.internalTrack.id);if(!t)return{blockIndex:-1,correctBlockFound:!1};const r=W(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=X(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 y(-1!==e),{blockIndex:e,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)})}fetchPacketInCluster(e,t,i){return d(this,null,function*(){var r,n;if(-1===t)return null;const s=e.trackData.get(this.internalTrack.id).blocks[t];if(y(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);I(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?_i: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?_i:s.mainAdditional,c.alphaByteLength=s.mainAdditional.byteLength);const u=new Ri(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 d(this,null,function*(){var s,a,o,l;const{demuxer:c,segment:u}=this.internalTrack;let d=null,h=null,f=-1;if(e){const{blockIndex:i,correctBlockFound:r}=t(e);if(r)return this.fetchPacketInCluster(e,i,n);-1!==i&&(h=e,f=i)}const m=W(this.internalTrack.cuePoints,i,e=>e.time),p=-1!==m?this.internalTrack.cuePoints[m]:null,g=W(this.internalTrack.clusterPositionCache,i,e=>e.startTimestamp),k=-1!==g?this.internalTrack.clusterPositionCache[g]:null,b=Math.max(null!=(s=null==p?void 0:p.clusterPosition)?s:0,null!=(a=null==k?void 0:k.elementStartPos)?a:0)||null;let T;for(e?null===b||e.elementStartPos>=b?(T=e.elementEndPos,d=e):T=b:T=null!=b?b:u.clusterSeekStartPos;null===u.elementEndPos||T<=u.elementEndPos-2;){if(d){const e=d.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>r)break}let e=c.reader.requestSliceRange(T,2,br);if(Te(e)&&(e=yield e),!e)break;const i=T,s=Ir(e);if(!s||!kr.includes(s.id)&&s.id!==mr.Void){const e=yield _r(c.reader,i,kr,Math.min(null!=(o=u.elementEndPos)?o:1/0,i+Zr));if(e){T=e;continue}break}const a=s.id;let l=s.size;const m=e.filePos;if(a===mr.Cluster){d=yield c.readCluster(i,u),l=d.elementEndPos-m;const{blockIndex:e,correctBlockFound:r}=t(d);if(r)return this.fetchPacketInCluster(d,e,n);-1!==e&&(h=d,f=e)}if(void 0===l){y(a!==mr.Cluster);l=(yield Er(c.reader,m,yr,u.elementEndPos)).pos-m}const p=m+l;if(null===u.elementEndPos){let e=c.reader.requestSliceRange(p,2,br);if(Te(e)&&(e=yield e),!e)break;if(wr(e)===mr.Segment){u.elementEndPos=p;break}}T=p}if(p&&(!h||h.elementStartPosd(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?st(s.data):null,hevcCodecInfo:"hevc"===this.internalTrack.info.codec&&s?pt(s.data):null,vp9CodecInfo:"vp9"===this.internalTrack.info.codec&&s?Ct(s.data):null,av1CodecInfo:"av1"===this.internalTrack.info.codec&&s?Et(s.data):null,proresCodecInfo:"prores"===this.internalTrack.info.codec&&s?_t(s.data):null,proresFormat:this.internalTrack.info.proresFormat};if(!D(this.internalTrack.info.colorSpace)){const n=fi(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:hi(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 nn extends tn{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 d(this,null,function*(){var e;return this.internalTrack.info.codec?null!=(e=this.decoderConfigPromise)?e:this.decoderConfigPromise=(()=>d(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&&Zt(e.data)}return{codec:mi({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 sn=(e,t,i,r=null)=>d(null,null,function*(){const n=o(2,16);let s=t;for(;null===i||s=4;){const t=a.filePos,i=Lo(a),n=null!==e.fileSize?e.fileSize-s: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:s};a.filePos=t+o.bytesAdvanced,s=a.filePos}}return null});class an extends Ei{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 O,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}readMetadata(){return d(this,null,function*(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>d(this,null,function*(){for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)yield this.advanceReader();if(!this.firstFrameHeader&&this.xingFrameHeader&&(this.firstFrameHeader=this.xingFrameHeader,this.firstFrameHeaderPos=this.xingFrameHeaderPos),!this.firstFrameHeader)throw new Error("No valid MP3 frame found.");this.trackBackings=[new on(this)]}))()})}advanceReader(){return d(this,null,function*(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,el);if(Te(e)&&(e=yield e),!e)return void(this.lastSampleLoaded=!0);const t=nl(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}const e=yield sn(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=wi(t.mpegVersionId,t.channel);let r=this.reader.requestSlice(e.startPos+i,4);if(Te(r)&&(r=yield r),r){const n=Lo(r);if(n===vi||n===Si){if(this.xingFrameHeader||(this.xingFrameHeader=t,this.xingFrameHeaderPos=e.startPos),!this.xingData){let t=this.reader.requestSlice(e.startPos+i+4,12);if(Te(t)&&(t=yield t),t){const e=Ro(t,12),i=I(e),r=i.getUint32(0,!1);this.xingData={frameCount:r&xi.FrameCount?i.getUint32(4,!1):null,fileSize:r&xi.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 d(this,null,function*(){return"audio/mpeg"})}getTrackBackings(){return d(this,null,function*(){return yield this.readMetadata(),this.trackBackings})}getMetadataTags(){return d(this,null,function*(){const e=yield this.readingMutex.acquire();try{if(yield this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let e=0,t=!1;for(;;){let i=this.reader.requestSlice(e,el);if(Te(i)&&(i=yield i),!i)break;const r=nl(i);if(!r)break;t=!0;let n=this.reader.requestSlice(i.filePos,r.size);if(Te(n)&&(n=yield n),!n)break;sl(n,r,this.metadataTags),e=i.filePos+r.size}if(!t&&null!==this.reader.fileSize&&this.reader.fileSize>=Zo){let e=this.reader.requestSlice(this.reader.fileSize-Zo,Zo);Te(e)&&(e=yield e),y(e);"TAG"===Xo(e,3)&&il(e,this.metadataTags)}return this.metadataTags}finally{e()}})}}class on{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return y(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate/this.demuxer.firstFrameHeader.audioSamplesInFrame}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return d(this,null,function*(){const e=this.demuxer;if(y(null!==e.firstFrameHeader),y(null!==e.firstFrameHeaderPos),e.xingData){if(null!==e.xingData.frameCount)return e.xingData.frameCount*e.firstFrameHeader.audioSamplesInFrame/e.firstFrameHeader.sampleRate}else if(null!==e.reader.fileSize){const s=(t=e.firstFrameHeader.lowSamplingFrequency,i=e.firstFrameHeader.layer,r=e.firstFrameHeader.bitrate,n=e.firstFrameHeader.sampleRate,0===i?0:1===i?144*r/(n<e.timestamp);if(-1===i)throw new Error("Packet was not created from this track.");const r=i+1;for(;r>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)yield this.demuxer.advanceReader();return this.getPacketAtIndex(r,t)}finally{i()}})}getPacket(e,t){return d(this,null,function*(){const i=yield this.demuxer.readingMutex.acquire();try{for(;;){const i=W(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 un=e=>{const t=I(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},dn=(e,t,i)=>{let r=0,n=null;if(e.length>0)if("vorbis"===t.codec){y(t.vorbisInfo);const s=(1<<(e=>{let t=0;for(;e;)t++,e>>=1;return t})(t.vorbisInfo.modeBlockflags.length-1))-1<<1,a=(e[0]&s)>>1;if(a>=t.vorbisInfo.modeBlockflags.length)throw new Error("Invalid mode number.");let o=i;const l=t.vorbisInfo.modeBlockflags[a];if(n=t.vorbisInfo.blocksizes[l],1===l){const i=1+(1|s),r=e[0]&i?1:0;o=t.vorbisInfo.blocksizes[r]}r=null!==o?o+n>>2:0}else if("opus"===t.codec){r=(e=>{const t=e[0]>>3,i=3&e[0];let r;return r=0===i?1:1===i||2===i?2:63&e[1],{durationInSamples:Rt[t]*r}})(e).durationInSamples}return{durationInSamples:r,vorbisBlockSize:n}},hn=27,fn=282,mn=e=>{const t=e.filePos;if(zo(e)!==ln)return null;e.skip(1);const i=Fo(e),r=Vo(e),n=zo(e),s=zo(e),a=zo(e),o=Fo(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}},pn=(e,t)=>{for(;e.filePos>>8&255)===i||(t>>>16&255)===i||(t>>>24&255)===i){if(e.skip(-4),t===ln)return!0;e.skip(1)}}return!1};class gn extends Ei{constructor(e){super(e),this.metadataPromise=null,this.bitstreams=[],this.trackBackings=[],this.metadataTags={},this.reader=e._reader}readMetadata(){return d(this,null,function*(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>d(this,null,function*(){let e=0;for(;;){let t=this.reader.requestSliceRange(e,hn,fn);if(Te(t)&&(t=yield t),!t)break;const i=mn(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 kn(t,this)))}}))()})}readVorbisMetadata(e,t){return d(this,null,function*(){let i=yield this.findNextPacketStart(e);if(!i)return;const r=yield this.readPacket(i.startPage,i.startSegmentIndex);if(!r)return;if(i=yield this.findNextPacketStart(r),!i)return;const n=yield this.readPacket(i.startPage,i.startSegmentIndex);if(!n)return;if(3!==r.data[0]||5!==n.data[0])return;const s=[],a=e=>{for(;s.push(Math.min(255,e)),!(e<255);)e-=255};a(e.data.length),a(r.data.length);const o=new Uint8Array(1+s.length+e.data.length+r.data.length+n.data.length);o[0]=2,o.set(s,1),o.set(e.data,1+s.length),o.set(r.data,1+s.length+e.data.length),o.set(n.data,1+s.length+e.data.length+r.data.length),t.codecInfo.codec="vorbis",t.description=o,t.lastMetadataPacket=n;const l=I(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:Ft(n.data).modeBlockflags},Nt(r.data.subarray(7),this.metadataTags)})}readOpusMetadata(e,t){return d(this,null,function*(){const i=yield this.findNextPacketStart(e);if(!i)return;const r=yield this.readPacket(i.startPage,i.startSegmentIndex);if(!r)return;t.codecInfo.codec="opus",t.description=e.data,t.lastMetadataPacket=r;const n=(e=>{const t=I(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=pi,t.codecInfo.opusInfo={preSkip:n.preSkip},Nt(r.data.subarray(8),this.metadataTags)})}readPacket(e,t){return d(this,null,function*(){y(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 d(this,null,function*(){return yield this.readMetadata(),this.trackBackings})}getMetadataTags(){return d(this,null,function*(){return yield this.readMetadata(),this.metadataTags})}}class kn{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new O,this.internalSampleRate="opus"===e.codecInfo.codec?pi:e.sampleRate}getType(){return"audio"}getId(){return this.bitstream.serialNumber}getNumber(){const e=this.demuxer.trackBackings.findIndex(e=>e.bitstream===this.bitstream);return y(-1!==e),e+1}getNumberOfChannels(){return this.bitstream.numberOfChannels}getSampleRate(){return this.bitstream.sampleRate}getTimeResolution(){return this.bitstream.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return d(this,null,function*(){return null})}getLiveRefreshInterval(){return d(this,null,function*(){return null})}getCodec(){return this.bitstream.codecInfo.codec}getInternalCodecId(){return null}getDecoderConfig(){return d(this,null,function*(){var e;return y(this.bitstream.codecInfo.codec),{codec:this.bitstream.codecInfo.codec,numberOfChannels:this.bitstream.numberOfChannels,sampleRate:this.bitstream.sampleRate,description:null!=(e=this.bitstream.description)?e:void 0}})}getName(){return null}getLanguageCode(){return Z}getDisposition(){return u(c({},Le),{primary:!1})}granulePositionToTimestampInSamples(e){return"opus"===this.bitstream.codecInfo.codec?(y(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,i){if(!e)return null;const{durationInSamples:r,vorbisBlockSize:n}=dn(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),s=new Ri(i.metadataOnly?_i:e.data,"key",Math.max(0,t.timestampInSamples)/this.internalSampleRate,r/this.internalSampleRate,e.endPage.headerStartPos+e.endSegmentIndex,e.data.byteLength);return this.encodedPacketToMetadata.set(s,{packet:e,timestampInSamples:t.timestampInSamples,durationInSamples:r,vorbisLastBlockSize:t.vorbisLastBlocksize,vorbisBlockSize:n}),s}getFirstPacket(e){return d(this,null,function*(){y(this.bitstream.lastMetadataPacket);const t=yield this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let i=0;"opus"===this.bitstream.codecInfo.codec&&(y(this.bitstream.codecInfo.opusInfo),i-=this.bitstream.codecInfo.opusInfo.preSkip);const r=yield this.demuxer.readPacket(t.startPage,t.startSegmentIndex);return this.createEncodedPacketFromOggPacket(r,{timestampInSamples:i,vorbisLastBlocksize:null},e)})}getNextPacket(e,t){return d(this,null,function*(){const i=this.encodedPacketToMetadata.get(e);if(!i)throw new Error("Packet was not created from this track.");const r=yield this.demuxer.findNextPacketStart(i.packet);if(!r)return null;const n=i.timestampInSamples+i.durationInSamples,s=yield this.demuxer.readPacket(r.startPage,r.startSegmentIndex);return this.createEncodedPacketFromOggPacket(s,{timestampInSamples:n,vorbisLastBlocksize:i.vorbisBlockSize},t)})}getPacket(e,t){return d(this,null,function*(){var i,r;if(null===this.demuxer.reader.fileSize)return this.getPacketSequential(e,t);const n=ee(e*this.internalSampleRate);if(0===n)return this.getFirstPacket(t);if(n<0)return null;y(this.bitstream.lastMetadataPacket);const s=yield this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!s)return null;let a=s.startPage,o=this.demuxer.reader.fileSize;const l=[a];e:for(;a.headerStartPos+a.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,hn,fn);Te(t)&&(t=yield t),y(t);const i=mn(t);y(i),u=i,u.serialNumber===this.bitstream.serialNumber&&d.push(u)}y(-1!==u.granulePosition);let h,f,m=null,p=u,g=0;if(u.headerStartPos===s.startPage.headerStartPos)h=this.granulePositionToTimestampInSamples(0),f=!0,m=0;else{h=0,f=!1;for(let t=u.lacingValues.length-1;t>=0;t--){if(u.lacingValues[t]<255){m=t+1;break}}if(null===m)throw new Error("Invalid page with granule position: no packets end on this page.");g=m-1;const e={data:_i,endPage:p,endSegmentIndex:g};if(yield this.demuxer.findNextPacketStart(e)){const e=bn(d,u,m);y(e);const t=yn(d,e.page,e.segmentIndex);t&&(u=t.page,m=t.segmentIndex)}else for(;;){const e=bn(d,u,m);if(!e)break;const t=yn(d,e.page,e.segmentIndex);if(!t)break;if(u=t.page,m=t.segmentIndex,e.page.headerStartPos!==p.headerStartPos){p=e.page,g=e.segmentIndex;break}}}let k=null,b=null;for(;null!==u;){y(null!==m);const e=yield this.demuxer.readPacket(u,m);if(!e)break;if(!(u.headerStartPos===s.startPage.headerStartPos&&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 d(this,null,function*(){const i=yield this.sequentialScanMutex.acquire();try{const i=ee(e*this.internalSampleRate);e=i/this.internalSampleRate;const r=W(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);y(e),this.sequentialScanCache.length>0&&y(T(this.sequentialScanCache).timestampInSamples<=e.timestampInSamples),this.sequentialScanCache.push(e)}}return n}finally{i()}})}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const yn=(e,t,i)=>{let r=t,n=i;e:for(;;){for(n--;n>=0;n--){if(r.lacingValues[n]<255){n++;break e}}y(-1===n);if(!(1&r.headerType)){n=0;break}const t=K(e,e=>e.headerStartPos{if(i>0)return{page:t,segmentIndex:i-1};const r=K(e,e=>e.headerStartPosd(this,null,function*(){var e,t;let i=this.reader.requestSlice(0,12);Te(i)&&(i=yield i),y(i);const r=Xo(i,4),n="RIFX"!==r,s="RF64"===r,a=Oo(i,n);let o=s?this.reader.fileSize:Math.min(a+8,null!=(e=this.reader.fileSize)?e:1/0);if("WAVE"!==Xo(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=Ao(r,i),s=t-18;if(Math.min(s,e)>=22&&n===Tn.EXTENSIBLE){r.skip(6);const e=Ro(r,16);n=e[0]|e[1]<<8}}if(n!==Tn.MULAW&&n!==Tn.ALAW||(l=8),n!==Tn.PCM&&n!==Tn.IEEE_FLOAT&&n!==Tn.ALAW&&n!==Tn.MULAW)throw new Error(`Unsupported WAVE codec (format tag ${n}). Only integer/float PCM, A-law, and \u03bc-law are supported.`);if(n===Tn.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===Tn.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 d(this,null,function*(){var r,n,s,a,o,l,c,u,d,h,f;let m=this.reader.requestSlice(e,t);if(Te(m)&&(m=yield m),!m)return;const p=Xo(m,4);if("INFO"!==p&&"INF0"!==p)return;let g=m.filePos;for(;g<=e+t-8;){m.filePos=g;const e=Xo(m,4),t=Oo(m,i),p=Ro(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 d(this,null,function*(){let i=this.reader.requestSlice(e,t);if(Te(i)&&(i=yield i),!i)return;const r=nl(i);if(r){const n=t-el;if(r.size=Math.min(r.size,n),r.size>0){const t=i.slice(e+el,r.size);sl(t,r,this.metadataTags)}}})}getCodec(){if(y(this.audioInfo),this.audioInfo.format===Tn.MULAW)return"ulaw";if(this.audioInfo.format===Tn.ALAW)return"alaw";if(this.audioInfo.format===Tn.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===Tn.IEEE_FLOAT){if(4===this.audioInfo.sampleSizeInBytes)return"pcm-f32";if(8===this.audioInfo.sampleSizeInBytes)return"pcm-f64"}y(!1)}getMimeType(){return d(this,null,function*(){return"audio/wav"})}getTrackBackings(){return d(this,null,function*(){return yield this.readMetadata(),this.trackBackings})}getMetadataTags(){return d(this,null,function*(){return yield this.readMetadata(),this.metadataTags})}}const wn=2048;class Pn{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return y(this.demuxer.audioInfo),this.demuxer.audioInfo.format}getDecoderConfig(){return d(this,null,function*(){const e=this.demuxer.getCodec();return e?(y(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null})}getNumberOfChannels(){return y(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return y(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return y(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return d(this,null,function*(){return y(-1!==this.demuxer.dataSize),this.demuxer.dataSize/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate})}getLiveRefreshInterval(){return d(this,null,function*(){return null})}getName(){return null}getLanguageCode(){return Z}getDisposition(){return c({},Le)}getPacketAtIndex(e,t){return d(this,null,function*(){y(e>=0),y(this.demuxer.audioInfo);const i=e*wn*this.demuxer.audioInfo.blockSizeInBytes;if(i>=this.demuxer.dataSize)return null;const r=Math.min(wn*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(Te(e)&&(e=yield e),!e)return null}let n;if(t.metadataOnly)n=_i;else{let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+i,r);Te(e)&&(e=yield e),y(e),n=Ro(e,r)}const s=e*wn/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 Ri(n,"key",s,a,e,r)})}getFirstPacket(e){return this.getPacketAtIndex(0,e)}getPacket(e,t){return d(this,null,function*(){y(this.demuxer.audioInfo);const i=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/wn,(this.demuxer.dataSize-1)/(wn*this.demuxer.audioInfo.blockSizeInBytes)));if(i<0)return null;const r=yield this.getPacketAtIndex(i,t);if(r)return r;if(0===i)return null;y(null===this.demuxer.reader.fileSize);let n=yield this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,t);for(;n;){const e=yield this.getNextPacket(n,t);if(!e)break;n=e}return n})}getNextPacket(e,t){y(this.demuxer.audioInfo);const i=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/wn);return this.getPacketAtIndex(i+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const In=e=>{const t=e.filePos,i=Ro(e,9),r=new ze(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}},xn=1024;class Cn extends Ei{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.trackBackings=[],this.readingMutex=new O,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}readMetadata(){return d(this,null,function*(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>d(this,null,function*(){for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)yield this.advanceReader();y(this.firstFrameHeader),this.trackBackings=[new Bn(this)]}))()})}advanceReader(){return d(this,null,function*(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,el);if(Te(e)&&(e=yield e),!e)return void(this.lastSampleLoaded=!0);const t=nl(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}let e=this.reader.requestSliceRange(this.lastLoadedPos,7,9);if(Te(e)&&(e=yield e),!e)return void(this.lastSampleLoaded=!0);const t=In(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=Ue[t.samplingFrequencyIndex];y(void 0!==i);const r=xn/i,n={timestamp:this.nextTimestampInSamples/i,duration:r,dataStart:t.startPos,dataSize:t.frameLength};this.loadedSamples.push(n),this.nextTimestampInSamples+=xn,this.lastLoadedPos=t.startPos+t.frameLength})}getMimeType(){return d(this,null,function*(){return"audio/aac"})}getTrackBackings(){return d(this,null,function*(){return yield this.readMetadata(),this.trackBackings})}getMetadataTags(){return d(this,null,function*(){const e=yield this.readingMutex.acquire();try{if(yield this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let e=0;for(;;){let t=this.reader.requestSlice(e,el);if(Te(t)&&(t=yield t),!t)break;const i=nl(t);if(!i)break;let r=this.reader.requestSlice(t.filePos,i.size);if(Te(r)&&(r=yield r),!r)break;sl(r,i,this.metadataTags),e=t.filePos+i.size}return this.metadataTags}finally{e()}})}}class Bn{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return this.getSampleRate()/xn}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return d(this,null,function*(){return null})}getLiveRefreshInterval(){return d(this,null,function*(){return null})}getName(){return null}getLanguageCode(){return Z}getCodec(){return"aac"}getInternalCodecId(){return y(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){y(this.demuxer.firstFrameHeader);const e=qe[this.demuxer.firstFrameHeader.channelConfiguration];return y(void 0!==e),e}getSampleRate(){y(this.demuxer.firstFrameHeader);const e=Ue[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return y(void 0!==e),e}getDisposition(){return c({},Le)}getDecoderConfig(){return d(this,null,function*(){return y(this.demuxer.firstFrameHeader),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate()}})}getPacketAtIndex(e,t){return d(this,null,function*(){if(-1===e)return null;const i=this.demuxer.loadedSamples[e];if(!i)return null;let r;if(t.metadataOnly)r=_i;else{let e=this.demuxer.reader.requestSlice(i.dataStart,i.dataSize);if(Te(e)&&(e=yield e),!e)return null;r=Ro(e,i.dataSize)}return new Ri(r,"key",i.timestamp,i.duration,e,i.dataSize)})}getFirstPacket(e){return this.getPacketAtIndex(0,e)}getNextPacket(e,t){return d(this,null,function*(){const i=yield this.demuxer.readingMutex.acquire();try{const i=q(this.demuxer.loadedSamples,e.timestamp,e=>e.timestamp);if(-1===i)throw new Error("Packet was not created from this track.");const r=i+1;for(;r>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)yield this.demuxer.advanceReader();return this.getPacketAtIndex(r,t)}finally{i()}})}getPacket(e,t){return d(this,null,function*(){const i=yield this.demuxer.readingMutex.acquire();try{for(;;){const i=W(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+1d(this,null,function*(){var e;let t=0;for(;;){let e=this.reader.requestSlice(t,el);if(Te(e)&&(e=yield e),!e)return void(this.lastSampleLoaded=!0);const i=nl(e);if(!i)break;let r=this.reader.requestSlice(e.filePos,i.size);Te(r)&&(r=yield r),y(r),sl(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===Fo(s)){const t=s.filePos;if(Fo(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=Ro(e,4),n=new ze(r);if(32764!==n.readBits(15))return null;if(null===this.blockingBit){y(t);const e=n.readBits(1);this.blockingBit=e}else if(1===this.blockingBit){y(!t);if(1!==n.readBits(1))return null}else{if(0!==this.blockingBit)throw new Error("Invalid blocking bit");y(!t);if(0!==n.readBits(1))return null}const s=(e=>0===e?null:1===e?192:e>=2&&e<=5?144*o(2,e):6===e?"uncommon-u8":7===e?"uncommon-u16":e>=8&&e<=15?o(2,e):null)(n.readBits(4));if(!s)return null;y(this.audioInfo);const a=((e,t)=>{switch(e){case 0:return t;case 1:return 88200;case 2:return 176400;case 3:return 192e3;case 4:return 8e3;case 5:return 16e3;case 6:return 22050;case 7:return 24e3;case 8:return 32e3;case 9:return 44100;case 10:return 48e3;case 11:return 96e3;case 12:return"uncommon-u8";case 13:return"uncommon-u16";case 14:return"uncommon-u16-10";default:return null}})(n.readBits(4),this.audioInfo.sampleRate);if(!a)return null;n.readBits(4),n.readBits(3);if(0!==n.readBits(1))return null;const l=(e=>{let t=0;const i=new ze(Ro(e,1));for(;1===i.readBits(1);)t++;if(0===t)return i.readBits(7);const r=[],n=t-1,s=new ze(Ro(e,n)),a=8-t-1;for(let o=0;oe|t<"uncommon-u16"===t?Do(e)+1:"uncommon-u8"===t?Fo(e)+1:"number"===typeof t?t:($(t),void y(!1)))(e,s),u=((e,t)=>"uncommon-u16"===t?Do(e):"uncommon-u16-10"===t?10*Do(e):"uncommon-u8"===t?Fo(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=Fo(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})(Ro(e,d));return h!==f?null:{num:l,blockSize:c,sampleRate:u}}advanceReader(){return d(this,null,function*(){yield this.readMetadata(),y(null!==this.lastLoadedPos),y(this.audioInfo);const e=this.lastLoadedPos,t=yield this.readNextFlacFrame({startPos:e,isFirstPacket:0===this.loadedSamples.length});if(!t)return void(this.lastSampleLoaded=!0);const i=this.loadedSamples[this.loadedSamples.length-1],r={blockOffset:i?i.blockOffset+i.blockSize:0,blockSize:t.blockSize,byteOffset:e,byteSize:t.size};this.lastLoadedPos=this.lastLoadedPos+t.size,this.loadedSamples.push(r),t.isLastFrame&&(this.lastSampleLoaded=!0)})}}class _n{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return y(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return y(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return Z}getTimeResolution(){return y(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 d(this,null,function*(){return y(this.demuxer.audioInfo),0===this.demuxer.audioInfo.totalSamples?null:this.demuxer.audioInfo.totalSamples/this.demuxer.audioInfo.sampleRate})}getLiveRefreshInterval(){return d(this,null,function*(){return null})}getDisposition(){return c({},Le)}getDecoderConfig(){return d(this,null,function*(){return y(this.demuxer.audioInfo),{codec:"flac",numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}})}getPacket(e,t){return d(this,null,function*(){if(y(this.demuxer.audioInfo),e<0)return null;const i=yield this.demuxer.readingMutex.acquire();try{for(;;){const i=W(this.demuxer.loadedSamples,e,e=>e.blockOffset/this.demuxer.audioInfo.sampleRate);if(-1===i){yield this.demuxer.advanceReader();continue}const r=this.demuxer.loadedSamples[i],n=r.blockOffset/this.demuxer.audioInfo.sampleRate;if(!(n+r.blockSize/this.demuxer.audioInfo.sampleRate<=e))return this.getPacketAtIndex(i,t);if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(this.demuxer.loadedSamples.length-1,t);yield this.demuxer.advanceReader()}}finally{i()}})}getNextPacket(e,t){return d(this,null,function*(){const i=yield this.demuxer.readingMutex.acquire();try{const i=e.sequenceNumber+1;if(this.demuxer.lastSampleLoaded&&i>=this.demuxer.loadedSamples.length)return null;for(;i>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)yield this.demuxer.advanceReader();return this.getPacketAtIndex(i,t)}finally{i()}})}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}getPacketAtIndex(e,t){return d(this,null,function*(){const i=this.demuxer.loadedSamples[e];if(!i)return null;let r;if(t.metadataOnly)r=_i;else{let e=this.demuxer.reader.requestSlice(i.byteOffset,i.byteSize);if(Te(e)&&(e=yield e),!e)return null;r=Ro(e,i.byteSize)}y(this.demuxer.audioInfo);const n=i.blockOffset/this.demuxer.audioInfo.sampleRate,s=i.blockSize/this.demuxer.audioInfo.sampleRate;return new Ri(r,"key",n,s,e,i.byteSize)})}getFirstPacket(e){return d(this,null,function*(){for(;0===this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)yield this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)})}}const Rn=9e4,Fn=o(2,33),An=188,Dn="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.",Mn=new Set([133,134,162]),Nn=new Set;class On extends Ei{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 d(this,null,function*(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>d(this,null,function*(){let e=this.reader.requestSlice(0,205);Te(e)&&(e=yield e),y(e);const t=Ro(e,205);if(71===t[0]&&71===t[188])this.packetOffset=0,this.packetStride=An;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 ze(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=zn(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 Vn(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=st(r.suppliedPacket.data),!e.info.avcCodecInfo)continue;const t=e.info.avcCodecInfo.sequenceParameterSets[0];y(t);const i=ct(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:E[i.colourPrimaries],transfer:R[i.transferCharacteristics],matrix:A[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=pt(r.suppliedPacket.data),!e.info.hevcCodecInfo)continue;const t=e.info.hevcCodecInfo.arrays.find(e=>e.nalUnitType===Ge.SPS_NUT).nalUnits[0];y(t);const i=mt(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:E[i.colourPrimaries],transfer:R[i.transferCharacteristics],matrix:A[i.matrixCoefficients],fullRange:!!i.fullRangeFlag},e.info.reorderSize=i.maxDecFrameBuffering;break}throw new Error("Unhandled.")}e.info.decoderConfig={codec:hi({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=Eo.tempFromBytes(r.suppliedPacket.data),i=In(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=qe[i.channelConfiguration],e.info.sampleRate=Ue[i.samplingFrequencyIndex]}else if("mp3"===e.info.codec){const t=Lo(Eo.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=Lt(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=Ot[t.acmod]+t.lfeon,e.info.sampleRate=je[t.fscod]}else if("eac3"===e.info.codec){const t=qt(r.suppliedPacket.data);if(!t)throw new Error("Invalid E-AC-3 audio stream; could not read sync frame from first packet.");const i=Wt(t);if(null===i)throw new Error("Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.");e.info.numberOfChannels=Ht(t),e.info.sampleRate=i}else{if("dts"!==e.info.codec)throw new Error("Unhandled.");{const t=Jt(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:mi({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 ze(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&&Mn.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:Nn.has(t)||(Me._warn(`Note: MPEG-TS streams with stream_type 0x${t.toString(16)} are not currently supported.`),Nn.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 ze(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 qn(a)):this.trackBackingEntries.push(new Wn(a)))}))()})}getTrackBackings(){return d(this,null,function*(){return yield this.readMetadata(),this.trackBackingEntries})}getMetadataTags(){return d(this,null,function*(){return{}})}getMimeType(){return d(this,null,function*(){yield this.readMetadata();return(e=>{let t="video/MP2T";const i=[...new Set(e.filter(Boolean))];return i.length>0&&(t+=`; codecs="${i.join(", ")}"`),t})(yield Promise.all(this.trackBackingEntries.map(e=>e.getDecoderConfig().then(e=>{var t;return null!=(t=null==e?void 0:e.codec)?t:null}))))})}readSection(e,t,i=!1){return d(this,null,function*(){let r=e,n=e;const s=[];let a,o=0,l=null,c=!0,u=0;for(;;){const e=yield this.readPacket(n);if(n+=this.packetStride,!e)break;if(l){if(e.pid!==l.pid){if(i)break;continue}if(1===e.payloadUnitStartIndicator)break}else{if(0===e.payloadUnitStartIndicator)break;l=e}const a=!!(2&e.adaptationFieldControl),d=!!(1&e.adaptationFieldControl);let h=0;if(a&&(h=1+e.body[0],e===l&&h>1&&(u=e.body[1]>>6&1)),d&&(0===h?(s.push(e.body),o+=e.body.byteLength):(s.push(e.body.subarray(h)),o+=e.body.byteLength-h)),r=n,!t&&o>=64){c=!1;break}if(-1!==q(this.sectionEndPositions,r,e=>e)){c=!1;break}}if(c){const e=W(this.sectionEndPositions,r,e=>e);this.sectionEndPositions.splice(e+1,0,r)}if(!l)return null;if(1===s.length)a=s[0];else{const e=s.reduce((e,t)=>e+t.length,0);a=new Uint8Array(e);let t=0;for(const i of s)a.set(i,t),t+=i.length}return{startPos:e,endPos:t?r:null,pid:l.pid,payload:a,randomAccessIndicator:u}})}readPacketHeader(e){return d(this,null,function*(){let t=this.reader.requestSlice(e,4);if(Te(t)&&(t=yield t),!t)return null;if(71!==Fo(t))throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");const i=Do(t);return{payloadUnitStartIndicator:i>>14&1,pid:8191&i,adaptationFieldControl:Fo(t)>>4&3}})}readPacket(e){return d(this,null,function*(){let t=this.reader.requestSlice(e,An);if(Te(t)&&(t=yield t),!t)return null;const i=Ro(t,An);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>=Fn-t?-Fn:Fn}}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 ze(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(Dn);return{sectionStartPos:t.startPos,sectionEndPos:t.endPos,pts:a,randomAccessIndicator:t.randomAccessIndicator}},zn=(e,t,i)=>{y(null!==t.endPos);const r=Ln(e,t,i);if(!r)return null;const n=new ze(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;y(Number.isInteger(l));const d=t.payload.subarray(l,s>0?6+s:t.payload.byteLength);return u(c({},r),{data:d})};class Un{constructor(e){this.elementaryStream=e,this.packetBuffers=new WeakMap,this.packetSectionStarts=new WeakMap}getId(){return this.elementaryStream.pid}getNumber(){const e=this.elementaryStream.demuxer,t=this.elementaryStream.info.type;let i=0;for(const r of e.trackBackingEntries)if(r.getType()===t&&i++,y(r instanceof Un),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 Z}getDisposition(){return u(c({},Le),{primary:!1})}getTimeResolution(){return Rn}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return d(this,null,function*(){return null})}getLiveRefreshInterval(){return d(this,null,function*(){return null})}createEncodedPacket(e,t,i){let r;return r=this.allPacketsAreKeyPackets()||1===e.randomAccessIndicator?"key":"delta",new Ri(i.metadataOnly?_i:e.data,r,e.pts/Rn,Math.max(t/Rn,0),e.sequenceNumber,e.data.byteLength)}getFirstPacket(e){return d(this,null,function*(){const t=this.elementaryStream.firstSection;y(t);const i=zn(this.elementaryStream.demuxer,t,!0);y(i);const r=new Vn(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 d(this,null,function*(){let i=this.packetBuffers.get(e);if(i){const r=yield i.readNext();if(!r)return null;this.packetBuffers.delete(e);const n=this.createEncodedPacket(r.packet,r.duration,t);return this.packetBuffers.set(n,i),this.packetSectionStarts.set(n,r.packet.sectionStartPos),n}const r=this.packetSectionStarts.get(e);if(void 0===r)throw new Error("Packet was not created from this track.");const n=this.elementaryStream.demuxer,s=yield n.readSection(r,!0);y(s);const a=zn(n,s,!0);y(a);const o=new Vn(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 d(this,null,function*(){let i=e;for(;;){if(i=yield this.getNextPacket(i,t),!i)return null;if("key"===i.type)return i}})}getPacket(e,t){return this.doPacketLookup(e,!1,t)}getKeyPacket(e,t){return this.doPacketLookup(e,!0,t)}doPacketLookup(e,t,i){return d(this,null,function*(){var r,n,s,a,o,l;const c=ee(e*Rn),u=this.elementaryStream.demuxer,{reader:h,seekChunkSize:f}=u,m=this.elementaryStream.pid,p=(e,t,i)=>d(this,null,function*(){let r=e;for(;re.pts),w=-1!==S?v[S]:null;if(w&&c-w.pts<45e3)b=w.sectionStartPos;else{let e=0;if(null!==h.fileSize){const t=Math.ceil(h.fileSize/f);if(t>1){let i=0,r=t-1;for(e=i;i<=r;){const t=Math.floor((i+r)/2),n=re(t*f,u.packetStride)+k.sectionStartPos,s=n+f,a=yield p(n,s,!1);a?a.pesPacketHeader.pts<=c?(e=t,i=t+1):r=t-1:r=t-1}}}b=re(e*f,u.packetStride)+k.sectionStartPos}const P=yield p(b,null!=(r=h.fileSize)?r:1/0,!1);let I=null!=(n=null==P?void 0:P.pesPacketHeader)?n:null;I||(I=k);const x=this.getReorderSize(),C=(e,t)=>d(this,null,function*(){var r,n;const s=yield u.readSection(e,!0);y(s);const a=zn(u,s,!0);y(a);const o=new Vn(this.elementaryStream,a),l=new jn(this,o);for(;;){if((null!=(n=null==(r=T(l.presentationOrderPackets))?void 0:r.pts)?n:-1/0)>=c)break;if(!(yield l.readNextPacket()))break}const d=X(l.presentationOrderPackets,t);if(-1===d)return null;const h=l.presentationOrderPackets[d],f=0===d?0:h.pts-l.presentationOrderPackets[d-1].pts;for(;l.decodeOrderPackets[0]!==h;)l.decodeOrderPackets.shift();l.lastDuration=f;const m=yield l.readNext();y(m);const p=this.createEncodedPacket(m.packet,m.duration,i);return this.packetBuffers.set(p,l),this.packetSectionStarts.set(p,m.packet.sectionStartPos),p});if(!t||this.allPacketsAreKeyPackets()){e:for(;;){let e=I.sectionStartPos+u.packetStride;for(;;){const t=yield u.readPacketHeader(e);if(!t)break e;if(t.pid===m&&1===t.payloadUnitStartIndicator){const t=yield u.readSection(e,!1);if(t){const e=Ln(u,t,!1);if(e&&null!==e.pts){if(e.pts>c)break e;I=e,Hn(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===m&&1===t.payloadUnitStartIndicator){const t=yield u.readSection(e,!1);if(t){const e=Ln(u,t,!1);if(e&&null!==e.pts){I=e;break}}}e-=u.packetStride}}return C(I.sectionStartPos,e=>e.pts<=c)}{let e=b,t=null;const i=!this.elementaryStream.canBeTrustedWithKeyPackets;for(;;){let r=null;const n=e<=k.sectionStartPos;let d,b=null;if(n)d=k,b=g;else{const t=yield p(e,null!=(s=h.fileSize)?s:1/0,i);d=null!=(a=null==t?void 0:t.pesPacketHeader)?a:null,b=null!=(o=null==t?void 0:t.section)?o:null}let T=!1,v=0;e:for(;d&&!(null!==t&&d.sectionStartPos>=t);){if(d.pts<=c){let e;if(this.elementaryStream.canBeTrustedWithKeyPackets)e=1===d.randomAccessIndicator;else{y(b);const t=zn(u,b,!0);y(t);const i=new Vn(this.elementaryStream,t);yield i.markNextPacket(),e=1===(null==(l=i.suppliedPacket)?void 0:l.randomAccessIndicator)}e&&(r=d)}if(d.pts>c&&(T=!0),T&&(v++,v>x))break;let e=d.sectionStartPos+u.packetStride;for(;;){const t=yield u.readPacketHeader(e);if(!t)break e;if(t.pid===m&&1===t.payloadUnitStartIndicator){const t=yield u.readSection(e,i);if(t){const e=Ln(u,t,!1);if(e&&null!==e.pts){d=e,b=t,Hn(this.elementaryStream,d);break}}}e+=u.packetStride}}if(r){let e=r;if(0===v)e:for(let r=0;r=u.packetOffset;){const r=yield u.readPacketHeader(t);if(!r)break e;if(r.pid===m&&1===r.payloadUnitStartIndicator){const r=yield u.readSection(t,i);if(r){const t=Ln(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 y(t),t}if(n)return null;t=e,e=Math.max(re(e-k.sectionStartPos-f,u.packetStride)+k.sectionStartPos,k.sectionStartPos)}}})}}class qn extends Un{getType(){return"video"}getCodec(){return this.elementaryStream.info.codec}getCodedWidth(){return this.elementaryStream.info.width}getCodedHeight(){return this.elementaryStream.info.height}getSquarePixelWidth(){return this.elementaryStream.info.squarePixelWidth}getSquarePixelHeight(){return this.elementaryStream.info.squarePixelHeight}getRotation(){return 0}getColorSpace(){return d(this,null,function*(){return this.elementaryStream.info.colorSpace})}canBeTransparent(){return d(this,null,function*(){return!1})}getDecoderConfig(){return d(this,null,function*(){return y(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig})}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}}class Wn extends Un{getType(){return"audio"}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}getDecoderConfig(){return d(this,null,function*(){return y(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig})}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 0}}const Hn=(e,t)=>{const i=e.referencePesPackets,r=W(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 y(e),e}bufferData(e){return d(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,S,w;if("avc"===e)T=et(b),S=T===Xe.NON_IDR_SLICE||T===Xe.SLICE_DPA||T===Xe.IDR,w=T===Xe.SEI||T===Xe.SPS||T===Xe.PPS||T===Xe.AUD;else{T=ft(b);if(((1&b)<<5|l[g+1]>>3)>0){u+=m;continue}S=T<=Ge.RASL_R||T>=Ge.BLA_W_LP&&T<=21,w=T>=Ge.VPS_NUT&&T<=37||T===Ge.PREFIX_SEI_NUT||T>=41&&T<=44||T>=48&&T<=55}let P=!1;if(S){let t;if("avc"===e){const e=l.subarray(k,k+y),i=v(new ze(e));t=!s||i<=a,a=i}else t=l[k]>>7===1;t&&(s?P=!0:s=!0)}else w&&s&&(P=!0);if(P){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);Te(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=zt[3*a+n];y(void 0!==o),this.seekTo(e),t=this.ensureBuffered(o),Te(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(Te(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=Ut[a];this.seekTo(e),t=this.ensureBuffered(n),Te(t)&&(t=yield t);const l=256*o,c=Math.round(l*Rn/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(Te(a)&&(a=yield a),a<18)return;const o=this.readBytes(18),l=ei(o);let c=l?null:ti(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);Te(i)&&(i=yield i),c=null!=(e=ti(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(Te(i)&&(i=yield i),i=0)}readNext(){return d(this,null,function*(){if(0===this.decodeOrderPackets.length){if(!(yield this.readNextPacket()))return null}yield this.ensureCurrentPacketHasNext();const e=this.decodeOrderPackets[0],t=this.presentationOrderPackets.indexOf(e);let i;if(y(-1!==t),t===this.presentationOrderPackets.length-1)i=this.lastDuration;else{i=this.presentationOrderPackets[t+1].pts-e.pts,this.lastDuration=i}for(this.decodeOrderPackets.shift();this.presentationOrderPackets.length>0;){const e=this.presentationOrderPackets[0];if(this.decodeOrderPackets.includes(e))break;this.presentationOrderPackets.shift()}return{packet:e,duration:i}})}readNextPacket(){return d(this,null,function*(){if(this.reachedEnd)return!1;let e;return this.context.suppliedPacket||(yield this.context.markNextPacket()),e=this.context.suppliedPacket,this.context.suppliedPacket=null,e?(this.decodeOrderPackets.push(e),this.processPacketThroughReorderBuffer(e),!0):(this.reachedEnd=!0,this.flushReorderBuffer(),!1)})}ensureCurrentPacketHasNext(){return d(this,null,function*(){const e=this.decodeOrderPackets[0];for(y(e);;){const t=this.presentationOrderPackets.indexOf(e);if(-1!==t&&t<=this.presentationOrderPackets.length-2)break;if(!(yield this.readNextPacket()))break}})}processPacketThroughReorderBuffer(e){if(this.reorderBuffer.push(e),this.reorderBuffer.length>this.reorderSize){let e=0;for(let i=1;ie.pts-t.pts),this.presentationOrderPackets.push(...this.reorderBuffer),this.reorderBuffer.length=0}}const Kn="application/vnd.apple.mpegurl",Xn="#EXT-X-STREAM-INF:",$n="#EXT-X-I-FRAME-STREAM-INF:",Gn="#EXT-X-MEDIA:",Qn="#EXTINF:",Yn="#EXT-X-MAP:",Jn="#EXT-X-KEY:",Zn="#EXT-X-MEDIA-SEQUENCE:",es="#EXT-X-BYTERANGE:",ts="#EXT-X-PROGRAM-DATE-TIME:",is="#EXT-X-TARGETDURATION:",rs="#EXT-X-PLAYLIST-TYPE:",ns=e=>0===e.length||e.startsWith("#")&&!e.startsWith("#EXT");class ss{constructor(e){this._attributes={};let t="",i="",r=!1,n=!1;for(let s=0;sd(this,null,function*(){const e=[];if(this.trackDeclarations){for(const t of this.trackDeclarations)if("video"===t.type){const i=Ce(e,e=>"video"===e.getType())+1;e.push(new ls(this,t,i))}else if("audio"===t.type){const i=Ce(e,e=>"audio"===e.getType())+1;e.push(new cs(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=Ce(e,e=>"video"===e.getType())+1;e.push(new ls(this,{id:e.length+1,type:"video"},t))}else if("audio"===r.type){const t=Ce(e,e=>"audio"===e.getType())+1;e.push(new cs(this,{id:e.length+1,type:"audio"},t))}}return e}))()})}getFirstTimestampForInput(e){return d(this,null,function*(){const t=this.firstTimestampCache.get(e);if(void 0!==t)return t;const i=yield e.getFirstTimestamp();return this.firstTimestampCache.set(e,i),i})}getMediaOffset(e,t){return d(this,null,function*(){var i;const r=null!=(i=e.firstSegment)?i:e;let n;if(this.firstSegmentFirstTimestamps.has(r))n=this.firstSegmentFirstTimestamps.get(r);else{const e=this.getInputForSegment(r);n=yield this.getFirstTimestampForInput(e),this.firstSegmentFirstTimestamps.set(r,n)}if(r===e)return r.timestamp-n;const s=yield this.getFirstTimestampForInput(t),a=e.timestamp-r.timestamp,o=s-n-a;return Math.abs(o)<=Math.min(.25,a)?r.timestamp-n:e.timestamp-s})}dispose(){for(const e of this.inputCache)e.input.dispose();this.inputCache.length=0}}class os{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=(()=>d(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 d(this,null,function*(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())})}getHasOnlyKeyPackets(){return this.delegate(()=>{var e,t,i;return null!=(i=null==(t=(e=this.firstInputTrack._backing).getHasOnlyKeyPackets)?void 0:t.call(e))?i:null})}getPairingMask(){return BigInt("1")}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getInternalCodecId(){return this.delegate(()=>this.firstInputTrack._backing.getInternalCodecId())}getDisposition(){return this.delegate(()=>this.firstInputTrack._backing.getDisposition())}getLanguageCode(){return this.delegate(()=>this.firstInputTrack._backing.getLanguageCode())}getName(){return this.delegate(()=>this.firstInputTrack._backing.getName())}getTimeResolution(){return this.delegate(()=>this.firstInputTrack._backing.getTimeResolution())}isRelativeToUnixEpoch(){return d(this,null,function*(){return yield this.hydrate(),y(this.segmentedInput.firstSegment),this.segmentedInput.firstSegment.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 d(this,null,function*(){y(e.sequenceNumber>=0),y(this.segmentedInput.firstSegment);const r=yield this.segmentedInput.getMediaOffset(t,i.input),n=t.timestamp-this.segmentedInput.firstSegment.timestamp,s=e.clone({timestamp:ie(e.timestamp+r,yield i.getTimeResolution()),sequenceNumber:Math.floor(1e8*n)+e.sequenceNumber});return this.packetInfos.set(s,{segment:t,track:i,sourcePacket:e}),s})}getFirstPacket(e){return d(this,null,function*(){var t;yield this.hydrate(),y(this.firstInputTrack),y(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 d(this,null,function*(){const r=this.packetInfos.get(e);if(!r)throw new Error("Packet was not created from this track.");const n=i?yield r.track._backing.getNextKeyPacket(r.sourcePacket,t):yield r.track._backing.getNextPacket(r.sourcePacket,t);if(n)return this.createAdjustedPacket(n,r.segment,r.track);let s=r.segment;for(;;){const e=yield this.segmentedInput.getNextSegment(s,{skipLiveWait:t.skipLiveWait});if(!e)return null;const i=this.segmentedInput.getInputForSegment(e),n=(yield i.getTracks()).find(e=>e.type===r.track.type&&e.number===r.track.number);if(!n){s=e;continue}const a=yield n._backing.getFirstPacket(t);return a?this.createAdjustedPacket(a,e,n):null}})}getPacket(e,t){return this._getPacketInternal(e,t,!1)}getKeyPacket(e,t){return this._getPacketInternal(e,t,!0)}_getPacketInternal(e,t,i){return d(this,null,function*(){let r=yield this.segmentedInput.getSegmentAt(e,{skipLiveWait:t.skipLiveWait});if(!r)return null;for(yield this.hydrate();r;){const n=this.segmentedInput.getInputForSegment(r),s=(yield n.getTracks()).find(e=>e.type===this.firstInputTrack.type&&e.number===this.firstInputTrack.number);if(!s){r=yield this.segmentedInput.getPreviousSegment(r,{skipLiveWait:t.skipLiveWait});continue}const a=yield this.segmentedInput.getMediaOffset(r,n),o=e-a,l=i?yield s._backing.getKeyPacket(o,t):yield s._backing.getPacket(o,t);if(l)return this.createAdjustedPacket(l,r,s);r=yield this.segmentedInput.getPreviousSegment(r,{skipLiveWait:t.skipLiveWait})}return null})}}class ls extends os{getType(){return"video"}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getCodedWidth(){return this.delegate(()=>this.firstInputTrack._backing.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.firstInputTrack._backing.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.firstInputTrack._backing.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.firstInputTrack._backing.getSquarePixelHeight())}getRotation(){return this.delegate(()=>this.firstInputTrack._backing.getRotation())}getColorSpace(){return d(this,null,function*(){return this.delegate(()=>this.firstInputTrack._backing.getColorSpace())})}canBeTransparent(){return d(this,null,function*(){return this.delegate(()=>this.firstInputTrack._backing.canBeTransparent())})}getDecoderConfig(){return d(this,null,function*(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())})}}class cs extends os{getType(){return"audio"}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getNumberOfChannels(){return this.delegate(()=>this.firstInputTrack._backing.getNumberOfChannels())}getSampleRate(){return this.delegate(()=>this.firstInputTrack._backing.getSampleRate())}getDecoderConfig(){return d(this,null,function*(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())})}}Pe();const us=1/0;"undefined"!==typeof FinalizationRegistry&&new FinalizationRegistry(e=>{e()});class ds extends Fe{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 d(this,null,function*(){var e;if(this._disposed)throw new Co;return null!=(e=this._sizePromise)?e:this._sizePromise=(()=>d(this,null,function*(){let e=this._getFileSize();return void 0!==e||(yield this._read(0,1,0,us),e=this._getFileSize(),y(void 0!==e)),e}))()})}getSize(){return d(this,null,function*(){if(this._disposed)throw new Co;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 Cs(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 hs(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){this._refCount--,0===this._refCount&&(this._dispose(),this._disposed=!0)}}class hs{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;y(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 fs extends ds{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 ds||e instanceof hs))throw new TypeError("requestHandler must return or resolve to a Source or SourceRef.");const i=e instanceof ds?e.ref():e;return(t=i.source)._usedForHls||(t._usedForHls=this._usedForHls),i};return Te(t)?t.then(i):i(t)}}const ms=(e,t)=>e.path===t.path;class ps extends fs{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 ds?e.ref():e;return this._root=t,this._rootRequest=null,t};Te(e)?this._rootRequest=e.then(t):(t(e),y(this._root))}if(this._rootRequest)return this._rootRequest.then(n=>n.source._read(e,t,i,r))}return this._root.source._read(e,t,i,r)}_getFileSize(){if(this._root)return this._root.source._getFileSize()}_dispose(){this._root?this._root.free():this._rootRequest&&this._rootRequest.then(e=>e.free())}}const gs="undefined"!==typeof FinalizationRegistry?new FinalizationRegistry(e=>{e.cancel().catch(()=>{})}):null;class ks extends ds{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&&(!Ie(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 xs({maxCacheSize:null!=(i=t.maxCacheSize)?i:8*o(2,20),maxWorkerCount:4,runWorker:this._runWorker.bind(this),onIdleWorkerRemoved:e=>{const t=this._readers.get(e);t&&(this._readers.delete(e),null==gs||gs.unregister(e),t.cancel().catch(()=>{}))},prefetchProfile:Is.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 d(this,null,function*(){y(e.strictTarget);let t=this._readers.get(e);if(void 0===t){if("stream"in this._blob&&!fe()&&!1!==this._options.useStreamReader){t=this._blob.slice(e.currentPos).stream().getReader(),null==gs||gs.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 Me._warn("Request will not be retried because a CORS error was suspected due to different origins. You can modify this behavior by providing your own function for the 'getRetryDelay' option."),null}return Math.min(o(2,e-2),16)},Ts=new Set;class vs extends fs{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&&(!Ie(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 vs(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:bs,this._requestInit=c({},t.requestInit);let a=null;if(null==(r=t.requestInit)?void 0:r.headers){const e=c({},ce(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=ws(a);e&&(this._offset=e.offset,this._length=e.length)}this._orchestrator=new xs({maxCacheSize:null!=(n=t.maxCacheSize)?n:64*o(2,20),maxWorkerCount:null!=(s=t.parallelism)?s:2,runWorker:this._runWorker.bind(this),prefetchProfile:Is.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:J(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 Te(a)?a.then(o):o(a)}_runWorker(e){return d(this,null,function*(){for(var t;;){const r=new AbortController,n=yield ue(null!=(t=this._options.fetchFn)?t:fetch,this._url,le(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")||Ts.has(e.origin)||(Me._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.`),Ts.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){Me._error("Error while reading response stream. Attempting to resume.",i),yield Re(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=>d(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;Me._error("Error while reading response stream. Attempting to resume.",s),yield Re(1e3*e);const a=yield ue(null!=(n=this._options.fetchFn)?n:fetch,this._url,le(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 Ps(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);Te(e)?e.then(e=>{e?(y(e.offset===o.start),o.resolve(e.bytes)):o.resolve(null)},e=>o.reject(e)):(y(null===e),o.resolve(null))}}_dispose(){this._orchestrator.dispose(),this._sequentialBacking&&(this._sequentialBacking._disposed=!0,this._sequentialBacking._dispose())}}const Ss=/^bytes=(\d+)-(\d*)$/,ws=e=>{const t=Ss.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=W(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}=V();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 d(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 Co);this._pendingSlices.length=0,this._cache.length=0,null==(e=this._reader)||e.cancel()}}const Is={fileSystem:(e,t)=>{const i=o(2,16);return{start:e=Math.floor((e-i)/i)*i,end:t=Math.ceil((t+i)/i)*i}},network:(e,t,i)=>{const r=o(2,16);e=Math.max(0,Math.floor((e-r)/r)*r);for(const n of i){const i=8*o(2,20),r=Math.max((n.startPos+n.targetPos)/2,n.targetPos-i);if(Se(e,t,r,n.targetPos)){const e=n.targetPos-n.startPos,r=Math.ceil((e+1)/i)*i,s=o(2,Math.ceil(Math.log2(e+1))),a=Math.min(s,r);t=Math.max(t,n.startPos+a)}}return{start:e,end:t=Math.max(t,e+ys)}}};class xs{constructor(e){this.options=e,this.fileSize=null,this.nextAge=0,this.workers=[],this.cache=[],this.currentCacheSize=0,this.disposed=!1,this.queuedReads=[]}read(e,t,i,r){var n;y(!this.disposed);const s=this.options.prefetchProfile(e,t,this.workers),a=Math.max(s.start,i),o=Math.min(s.end,null!=(n=this.fileSize)?n:1/0,r);y(a<=e&&t<=o);let l=null;const c=W(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=W(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(y(n<=s),m=h.length&&(l={bytes:h,view:I(h),offset:e}),0===p.length)return y(l),l;const{promise:g,resolve:k,reject:b}=V(),T=[];for(const y of p){const i=Math.max(e,y.start),r=Math.min(t,y.end);i===y.start&&r===y.end?T.push(y):ie.hole.start),i=-1!==t?this.queuedReads[t]:null;for(i&&y.start<=i.hole.end?(i.hole.end=Math.max(i.hole.end,y.end),i.strictTarget&&(i.strictTarget=e),v&&i.pendingSlices.push(v)):(t++,i={hole:{start:y.start,end:y.end},strictTarget:e,pendingSlices:v?[v]:[],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)}}):(y(h),l=g.then(t=>t&&{bytes:t,view:I(t),offset:e})),l}checkHoleAgainstWorker(e,t,i){const r=o(2,17);if(Se(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);y(-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=W(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=I(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=I(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 Te(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 Bs=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},Es=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 _s=/^0[xX][0-9a-fA-F]+$/,Rs=/^data:.*;base64,/i;class Fs extends as{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=(()=>d(this,null,function*(){try{const e=this.getRemainingWaitTimeMs();e>0&&(yield Re(e)),this.lastSegmentUpdateTime=performance.now(),yield this.updateSegments()}finally{this.currentUpdateSegmentsPromise=null}}))()}getRemainingWaitTimeMs(){const e=performance.now()-this.lastSegmentUpdateTime,t=Math.max(0,1e3*this.refreshInterval-e);return t<=50?0:t}updateSegments(){return d(this,null,function*(){var e,t,i,r,n,s,a,l;let d=this.nextLines;if(this.nextLines=null,!d){const e={stack:[],error:void 0,hasError:!1};try{const t=Bs(e,yield this.demuxer.input._getSourceUncached({path:this.rootPath,isRoot:!1}),!1),i=new Bo(t.source),r=yield i.requestEntireFile();y(r),d=$o(r,r.length,{ignore:ns}),t.source instanceof fs&&(this.rootPath=t.source.rootPath)}catch(F){e.error=F,e.hasError=!0}finally{Es(e)}}const h=!1!==(null==(e=this.input._formatOptions.hls)?void 0:e.offsetTimestampsByDateTime);let f=!1,m=0,p=null,g=null,k=null,b=0,v=null,S=null,w=null,P=null,x=null,C=null,B=!1,E=null!=(t=T(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=>{b=e,E&&(y(null!==E.sequenceNumber),E.sequenceNumber0&&null!==C&&(m=b*C),B=!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(Yn)){const t=new ss(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(!E){const e={path:xe(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.");S={timestamp:m,unixEpochTimestamp:p,firstSegment:null,sequenceNumber:null,location:e,duration:0,encryption:k,initSegment:null,lastProgramDateTimeSeconds:x}}g=null,null===P?w=null:P=null}else if(e.startsWith(Jn)){const t=new ss(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(!_s.test(r))throw new Error(`Unsupported IV format '${r}'.`);let e=r.slice(2);e=e.padStart(32,"0"),i=new Uint8Array(Ui);for(let t=0;t=8&&112===i[4]&&115===i[5]&&115===i[6]&&104===i[7]){const e=I(i).getUint32(0);r=Fi(i.subarray(8,Math.min(e,i.length)))}}k={method:i,psshBox:r}}}}else if(e.startsWith(Zn)){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(es)){const t=_(e.slice(17));if(null===t.offset){if(null===w)throw new Error("Invalid M3U8 file; #EXT-X-BYTERANGE without offset requires a previous byte range.");t.offset=w}P=t,w=t.offset+t.length}else if(e.startsWith(ts)){if(E)continue;const t=e.slice(25),i=Date.parse(t);if(!Number.isFinite(i))continue;const r=i/1e3;if(x===r)continue;if(null===x&&this.segments.length>0){const e=T(this.segments),t=r-(e.timestamp+e.duration);for(const i of this.segments)i.unixEpochTimestamp=i.timestamp+t,h&&(i.timestamp=i.unixEpochTimestamp)}x=r,p=r,h&&(m=r)}else if("#EXT-X-DISCONTINUITY"===e)v=null;else if(e.startsWith(is)){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,C=i}else{if("#EXT-X-ENDLIST"===e){this.streamHasEnded=!0;break}if(e.startsWith(rs)){"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 d(this,null,function*(){var e;return 0===this.segments.length&&(yield this.runUpdateSegments()),null!=(e=this.segments[0])?e:null})}getSegmentAt(e,t){return d(this,null,function*(){0===this.segments.length&&(yield this.runUpdateSegments());let i=!!t.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){const r=W(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=u(c({},this.input._formatOptions),{isobmff:u(c({},this.input._formatOptions.isobmff),{resolveKeyId:(null==(i=this.input._formatOptions.isobmff)?void 0:i.resolveKeyId)&&(e=>{if(!r.encryption||"SAMPLE-AES"!==r.encryption.method&&"SAMPLE-AES-CTR"!==r.encryption.method||!r.encryption.psshBox)return this.input._formatOptions.isobmff.resolveKeyId(e);let t=e.psshBoxes;const{psshBox:i}=r.encryption;return null!==i.keyIds&&!i.keyIds.includes(e.keyId)||t.some(e=>Ai(e,i))||(t=[...t,i]),this.input._formatOptions.isobmff.resolveKeyId(u(c({},e),{psshBoxes:t}))})})}),l=new Io({source:new ps(r.location.path,e=>d(this,null,function*(){var t,i;y(e.isRoot);const n=u(c({},e),{isRoot:!1});let s;const a=r.location.offset>0||null!==r.location.length;if(r.encryption&&"SAMPLE-AES"!==r.encryption.method&&"SAMPLE-AES-CTR"!==r.encryption.method)if("AES-128"===r.encryption.method){const e=r.encryption;y(e.iv);let t=yield this.input._getSourceCached(n);if(a){const e=t.source.slice(r.location.offset,null!=(i=r.location.length)?i:void 0).ref();t.free(),t=e}const l=((e,t,i)=>{let r=!1,n=0;const s=o(2,16),a=new Gi;return new ReadableStream({pull:o=>d(null,null,function*(){r||(a.init(yield t()),r=!0);const l=s+16;let c=e.requestSliceRange(n,0,l);if(Te(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=Ro(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 Bo(t.source),()=>d(this,null,function*(){const t={stack:[],error:void 0,hasError:!1};try{const i=Bs(t,yield this.input._getSourceCached({path:e.keyUri,isRoot:!1},Po),!1),r=new Bo(i.source),n=yield r.requestSlice(0,Ui);if(!n)throw new Error("Invalid AES-128 key; expected at least 16 bytes of data.");return{key:Ro(n,Ui),iv:e.iv}}catch(i){t.error=i,t.hasError=!0}finally{Es(t)}}),()=>{t.free()});s=new Ps(l).ref()}else y(!1);else if(s=yield this.input._getSourceCached(n),a){const e=s.source.slice(r.location.offset,null!=(t=r.location.length)?t:void 0).ref();s.free(),s=e}return s})),formats:this.input._formats.filter(e=>!(e instanceof Js)),initInput:null!=s?s:void 0,formatOptions:a});l._onFormatDetermined=e=>{var t,i;if(("SAMPLE-AES"===(null==(t=r.encryption)?void 0:t.method)||"SAMPLE-AES-CTR"===(null==(i=r.encryption)?void 0:i.method))&&!e._isIsobmff)throw new Error("The SAMPLE-AES and SAMPLE-AES-CTR encryption methods are currently only supported for ISOBMFF files.")},this.inputCache.push({segment:r,input:l,age:this.nextInputCacheAge++});if(this.inputCache.length>4){const e=Be(this.inputCache,e=>e.age);y(-1!==e),this.inputCache.splice(e,1)}return l}getLiveRefreshInterval(){return d(this,null,function*(){return 0===this.getRemainingWaitTimeMs()&&(yield this.runUpdateSegments()),this.streamHasEnded?null:this.refreshInterval})}}class As extends Ei{constructor(e){super(e),this.metadataPromise=null,this.trackBackings=null,this.internalTracks=null,this.segmentedInputs=[],this.hasMasterPlaylist=!0}readMetadata(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>d(this,null,function*(){y(this.input._rootSource instanceof fs);const e=yield this.input._reader.requestEntireFile();y(e);const t=$o(e,e.length,{ignore:ns}),{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)=>d(this,null,function*(){var r,o,l,c;const u=[],h=e.attributes.get("codecs");let f;if(h)f=h.split(",").map(e=>e.trim());else{const t=this.getSegmentedInputForPath(e.fullPath),i=yield t.getTrackBackings(),r=yield Promise.all(i.map(e=>d(this,null,function*(){return{track:e,codec:yield e.getCodec()}})));f=yield Promise.all(r.filter(e=>null!==e.codec).map(e=>e.track.getDecoderConfig().then(e=>e.codec)))}const m=e.attributes.get("video"),p=e.attributes.get("audio"),g=f.some(e=>ri.includes(yi(e))),k=f.some(e=>si.includes(yi(e)));if(null!==m&&!g){if(!s.includes(m))throw new Error(`Invalid M3U8 file; variant stream references video group "${m}" which is not defined in any #EXT-X-MEDIA tags.`);const e=n.find(e=>{const t=e.attributes.get("group-id"),i=e.attributes.get("type");return t===m&&"video"===i.toLowerCase()});e:if(e){const t=e.attributes.get("uri");if(null===t)break e;const r=xe(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});y(null!==a),f.push(a)}}if(null!==p&&!k){if(!a.includes(p))throw new Error(`Invalid M3U8 file; variant stream references audio group "${p}" which is not defined in any #EXT-X-MEDIA tags.`);const e=n.find(e=>{const t=e.attributes.get("group-id"),i=e.attributes.get("type");return t===p&&"audio"===i.toLowerCase()});e:if(e){const t=e.attributes.get("uri");if(null===t)break e;const r=xe(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});y(null!==a),f.push(a)}}f=[...new Set(f)];let b=null,T=null;const v=e.attributes.getAsNumber("bandwidth");y(null!==v);const S=e.attributes.getAsNumber("average-bandwidth"),w=e.attributes.get("name");for(const i of f){const d=yi(i);if(null!==d)if(ri.includes(d)){if(null!==b)throw new Error("Unsupported M3U8 file; multiple video codecs found in the CODECS attribute of a variant stream.");b=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:Z,lineNumber:e.lineNumber,fullPath:e.fullPath,fullCodecString:b,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:Os(i.attributes),autoselect:Os(i.attributes)||Ls(i.attributes),languageCode:zs(i.attributes.get("language")),lineNumber:i.lineNumber,fullPath:null!=(c=i.fullPath)?c:e.fullPath,fullCodecString:T,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===Z&&(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 Ms(u)):this.trackBackings.push(new Ns(u));this.internalTracks=l}))()}getTrackBackings(){return d(this,null,function*(){return yield this.readMetadata(),y(this.trackBackings),this.trackBackings})}getSegmentedInputForPath(e){let t=this.segmentedInputs.find(t=>t.path===e);if(t)return t;let i=null;if(this.internalTracks){i=this.internalTracks.filter(t=>t.fullPath===e).map(e=>({id:e.id,type:e.info.type}))}return t=new Fs(this,e,i,null),this.segmentedInputs.push(t),t}getMetadataTags(){return d(this,null,function*(){return{}})}getMimeType(){return d(this,null,function*(){return Kn})}dispose(){if(this.segmentedInputs){for(const e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}}class Ds{constructor(e){this.internalTrack=e,this.hydrationPromise=null}hydrate(){var e;return null!=(e=this.hydrationPromise)?e:this.hydrationPromise=(()=>d(this,null,function*(){const e=this.internalTrack.demuxer.getSegmentedInputForPath(this.internalTrack.fullPath);let t=null;const i=(yield e.getTrackBackings()).filter(e=>e.getType()===this.getType());if(1===i.length)t=i[0];else if(this instanceof Ms){for(const r of i)if((yield r.getCodec())===this.getCodec()){t=r;break}}else{y(this instanceof Ns);for(const e of i)if((yield e.getCodec())===this.getCodec()){t=e;break}}if(!t)throw new Error("Could not find matching track in underlying media data.");this.internalTrack.backingTrack=t}))()}delegate(e){return this.internalTrack.backingTrack?e():this.hydrate().then(e)}getCodec(){throw new Error("Not implemented on base class.")}getDisposition(){return u(c({},Le),{default:this.internalTrack.autoselect,primary:this.internalTrack.default})}getId(){return this.internalTrack.id}getPairingMask(){return this.internalTrack.pairingMask}getInternalCodecId(){return null}getLanguageCode(){return this.internalTrack.languageCode}getName(){return this.internalTrack.name}getNumber(){y(this.internalTrack.demuxer.internalTracks);const e=this.internalTrack.info.type;let t=0;for(const i of this.internalTrack.demuxer.internalTracks)if(i.info.type===e&&t++,i===this.internalTrack)break;return t}getTimeResolution(){return this.delegate(()=>this.internalTrack.backingTrack.getTimeResolution())}isRelativeToUnixEpoch(){return this.delegate(()=>this.internalTrack.backingTrack.isRelativeToUnixEpoch())}getUnixTimeForTimestamp(e){return this.delegate(()=>this.internalTrack.backingTrack.getUnixTimeForTimestamp(e))}getBitrate(){return this.internalTrack.peakBitrate}getAverageBitrate(){return this.internalTrack.averageBitrate}getDurationFromMetadata(e){return d(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getDurationFromMetadata(e)})}getLiveRefreshInterval(){return d(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getLiveRefreshInterval()})}getHasOnlyKeyPackets(){return this.internalTrack.hasOnlyKeyPackets||null}getFirstPacket(e){return d(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getFirstPacket(e)})}getPacket(e,t){return d(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getPacket(e,t)})}getKeyPacket(e,t){return d(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getKeyPacket(e,t)})}getNextPacket(e,t){return d(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getNextPacket(e,t)})}getNextKeyPacket(e,t){return d(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getNextKeyPacket(e,t)})}}class Ms extends Ds{constructor(e){super(e)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return"video"}getCodec(){return yi(this.internalTrack.fullCodecString)}getCodedWidth(){return this.delegate(()=>this.backingVideoTrack.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.backingVideoTrack.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelHeight())}getMetadataDisplayWidth(){return this.backingVideoTrack?null:this.internalTrack.info.width}getMetadataDisplayHeight(){return this.backingVideoTrack?null:this.internalTrack.info.height}getRotation(){return this.delegate(()=>this.backingVideoTrack.getRotation())}getColorSpace(){return d(this,null,function*(){return yield this.hydrate(),this.backingVideoTrack.getColorSpace()})}canBeTransparent(){return d(this,null,function*(){return yield this.hydrate(),this.backingVideoTrack.canBeTransparent()})}getMetadataCodecParameterString(){return this.backingVideoTrack?null:this.internalTrack.fullCodecString}getDecoderConfig(){return d(this,null,function*(){return yield this.hydrate(),this.backingVideoTrack.getDecoderConfig()})}}class Ns extends Ds{constructor(e){super(e)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return"audio"}getCodec(){return yi(this.internalTrack.fullCodecString)}getNumberOfChannels(){return null!==this.internalTrack.info.numberOfChannels?this.internalTrack.info.numberOfChannels:this.delegate(()=>this.backingAudioTrack.getNumberOfChannels())}getSampleRate(){return this.delegate(()=>this.backingAudioTrack.getSampleRate())}getMetadataCodecParameterString(){return this.backingAudioTrack?null:this.internalTrack.fullCodecString}getDecoderConfig(){return d(this,null,function*(){return yield this.hydrate(),this.backingAudioTrack.getDecoderConfig()})}}const Os=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}".`)},Ls=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}".`)},zs=e=>{if(null===e)return Z;const t=e.split("-")[0];return t||Z};class Us{constructor(){this._isIsobmff=!1}}class qs extends Us{constructor(){super(...arguments),this._isIsobmff=!0}_getMajorBrand(e){return d(this,null,function*(){let t=e._reader.requestSlice(0,12);if(Te(t)&&(t=yield t),!t)return null;t.skip(4);const i=Xo(t,4);return"ftyp"!==i&&"styp"!==i?null:Xo(t,4)})}_createDemuxer(e){return new Qi(e)}}class Ws extends qs{_canReadInput(e){return d(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(Te(t)&&(t=yield t),!t)return!1;let r=Lo(t),n=8;if(1===r){let t=e._reader.requestSlice(i+8,8);if(Te(t)&&(t=yield t),!t)return!1;r=Wo(t),n=16}if(r8)return!1;if(Sr(i,r)!==mr.EBML)return!1;const n=Pr(i);if("number"!==typeof n)return!1;let s=e._reader.requestSlice(i.filePos,n);if(Te(s)&&(s=yield s),!s)return!1;const a=i.filePos;for(;s.filePos<=a+n-2;){const e=Ir(s);if(!e)break;const{id:i,size:r}=e,n=s.filePos;if(void 0===r)return!1;switch(i){case mr.EBMLVersion:if(1!==Sr(s,r))return!1;break;case mr.EBMLReadVersion:if(1!==Sr(s,r))return!1;break;case mr.DocType:if(xr(s,r)!==t)return!1;break;case mr.DocTypeVersion:if(Sr(s,r)>4)return!1}s.filePos=n+r}return!0})}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new en(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}}class js extends Vs{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}}class Ks extends Us{_canReadInput(e){return d(this,null,function*(){let t=0;for(;;){let i=e._reader.requestSlice(t,el);if(Te(i)&&(i=yield i),!i)break;const r=nl(i);if(!r)break;t=i.filePos+r.size}const i=yield sn(e._reader,t,t+4096);if(!i)return!1;const r=i.header,n=wi(r.mpegVersionId,r.channel);let s=e._reader.requestSlice(i.startPos+n,4);if(Te(s)&&(s=yield s),!s)return!1;const a=Lo(s);if(a===vi||a===Si)return!0;t=i.startPos+i.header.totalSize;const o=yield sn(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 an(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}}class Xs extends Us{_canReadInput(e){return d(this,null,function*(){let t=e._reader.requestSlice(0,12);if(Te(t)&&(t=yield t),!t)return!1;const i=Xo(t,4);if("RIFF"!==i&&"RIFX"!==i&&"RF64"!==i)return!1;t.skip(4);return"WAVE"===Xo(t,4)})}_createDemuxer(e){return new Sn(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}}class $s extends Us{_canReadInput(e){return d(this,null,function*(){let t=e._reader.requestSlice(0,4);return Te(t)&&(t=yield t),!!t&&"OggS"===Xo(t,4)})}_createDemuxer(e){return new gn(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}}class Gs extends Us{_canReadInput(e){return d(this,null,function*(){let t=0;for(;;){let i=e._reader.requestSlice(t,el);if(Te(i)&&(i=yield i),!i)break;const r=nl(i);if(!r)break;t=i.filePos+r.size}let i=e._reader.requestSlice(t,4);return Te(i)&&(i=yield i),!!i&&"fLaC"===Xo(i,4)})}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new En(e)}}class Qs extends Us{_canReadInput(e){return d(this,null,function*(){let t=0;for(;;){let i=e._reader.requestSlice(t,el);if(Te(i)&&(i=yield i),!i)break;const r=nl(i);if(!r)break;t=i.filePos+r.size}let i=e._reader.requestSliceRange(t,7,9);if(Te(i)&&(i=yield i),!i)return!1;const r=In(i);if(!r)return!1;if(t+=r.frameLength,i=e._reader.requestSliceRange(t,7,9),Te(i)&&(i=yield i),!i)return!1;const n=In(i);return!!n&&(r.objectType===n.objectType&&r.samplingFrequencyIndex===n.samplingFrequencyIndex&&r.channelConfiguration===n.channelConfiguration)})}_createDemuxer(e){return new Cn(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}}class Ys extends Us{_canReadInput(e){return d(this,null,function*(){let t=e._reader.requestSlice(0,205);if(Te(t)&&(t=yield t),!t)return!1;const i=Ro(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 On(e)}get name(){return"MPEG Transport Stream"}get mimeType(){return"video/MP2T"}}class Js extends Us{_canReadInput(e){return d(this,null,function*(){let t=e._reader.requestSlice(0,7);if(Te(t)&&(t=yield t),!t)return!1;if(!("#EXTM3U"===Xo(t,7)))return!1;if(!(e._rootSource instanceof fs))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 As(e)}get name(){return"HTTP Live Streaming (HLS)"}get mimeType(){return Kn}}const Zs=new Ws,ea=new Hs,ta=new Vs,ia=new js,ra=new Ks,na=new Xs,sa=new $s,aa=new Qs,oa=new Gs,la=new Ys,ca=new Js,ua=[ca,Zs,ea,ta,ia,na,sa,oa,ra,aa,la],da=[ca,Zs,ea,ra,aa,la];var ha=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});Pe();let fa=-1/0,ma=-1/0,pa=null;"undefined"!==typeof FinalizationRegistry&&(pa=new FinalizationRegistry(e=>{const t=performance.now();"video"===e.type?(t-fa>=1e3&&(Me._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."),fa=t),"undefined"!==typeof VideoFrame&&e.data instanceof VideoFrame&&e.data.close()):(t-ma>=1e3&&(Me._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."),ma=t),"undefined"!==typeof AudioData&&e.data instanceof AudioData&&e.data.close())}));class ga{constructor(){this._referenceCount=0,this._lastAllocationBuffer=null}}const ka=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],ya=new Set(ka);class ba{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(oe*this.timestamp)}get microsecondDuration(){return Math.trunc(oe*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,I,x,C,B,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||!ya.has(t.format))throw new TypeError("init.format must be one of: "+ka.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&&_e(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:Ea(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?P(e):P(e).slice(),this._layout=m,this.colorSpace=new Pa(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)&&_e(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!=(x=null==t?void 0:t.duration)?x:(null!=(I=e.duration)?I:0)/1e6,this.colorSpace=new Pa(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&&_e(t.visibleRect,"init.visibleRect"),"undefined"!==typeof VideoFrame)return new ba(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*oe),duration:Math.trunc((null!=(C=t.duration)?C:0)*oe)||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!=(B=t.visibleRect)?B:{left:0,top:0,width:i,height:r},s=new OffscreenCanvas(n.width,n.height),a=s.getContext("2d",{alpha:pe(),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 Pa({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else{if(!(e instanceof ga))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&&!ka.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=Ee({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),null==pa||pa.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return y(null!==this._data),this._data instanceof ga?new ba(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):Ia(this._data)?new ba(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):this._data instanceof Uint8Array?(y(this._layout),new ba(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 ba(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==pa||pa.unregister(this),this._data instanceof ga?(this._data._referenceCount--,0===this._data._referenceCount&&this._data.close()):Ia(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){var t;if(Ba(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(Ia(this._data))return this._data.allocationSize(e);return Ra(this,e).allocationSize}copyTo(e){return d(this,arguments,function*(e,t={}){var i,r;if(!N(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(Ba(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(y(null!==this._data),Ia(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 ga)){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 ba))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{ha(i)}}}const n=Ra(this,t);y(this.format);const s=P(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)y(this._layout),y(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");y(e);const t=e.getImageData(0,0,this.codedWidth,this.codedHeight);o=[{data:P(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 Ia(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?(y(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&&Ca(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=xa(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],l=i.crop?i.crop.width:s,c=i.crop?i.crop.height:a;let u=0;2*r0?wa(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*o(2,g),t=n*o(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(y(null!==this._data),this._data instanceof ga||this._data instanceof Uint8Array){const e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}return this._data}transform(e){return d(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&&Ca(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=b(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=xa(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=te(f,null!=(i=e.roundDimensionsTo)?i:1),m=te(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 Ta){let t=e(this,p);if(Te(t)&&(t=yield t),null!==t)return t}const{canvas:g,context:k,isNew:y}=wa(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 ba(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 Ta=[],va=[];let Sa=0;const wa=(e,t)=>{for(const n of va)if(n.canvas.width===e&&n.canvas.height===t)return n.age=Sa++,{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 va.length>=3&&va.splice(Be(va,e=>e.age),1),va.push({canvas:i,context:r,age:Sa++}),{canvas:i,context:r,isNew:!0}};class Pa{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(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(_);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(F);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 Ia=e=>"undefined"!==typeof VideoFrame&&e instanceof VideoFrame,xa=(e,t,i)=>{const r=Math.min(e.left,t),n=Math.min(e.top,i),s=Math.min(e.width,t-r),a=Math.min(e.height,i-n);return y(s>=0),y(a>=0),{left:r,top:n,width:s,height:a}},Ca=(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.")},Ba=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.")}},Ea=(e,t,i)=>{const r=_a(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},_a=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:$(e),y(!1)}},Ra=(e,t)=>{const i={left:0,top:0,width:e.codedWidth,height:e.codedHeight},r=t.rect,n=Fa(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 Da(n,a,s)},Fa=(e,t,i,r,n)=>{const s=c({},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(!Aa(n,s))throw new TypeError("visibleRect alignment is invalid for the format.");return s},Aa=(e,t)=>{if(null===e)return!0;const i=_a(e);for(let r=0;r{const r=_a(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/(La(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*La(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=La(r),o=za(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(!N(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&&!Ma.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=La(o),f=za(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 Ha(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=Ua(a),b=La(a),T=za(a);let v;if(this._data instanceof Na){const e=e=>{const t=this._data.getDataPlane(e);if(!(t instanceof Uint8Array))throw new TypeError("getDataPlane() must return a Uint8Array.");const i=l*b*(T?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(T)if(f)v=e(s),s=0;else{v=new Uint8Array(l*b*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 Oa({data:n,format:this.format,sampleRate:this.sampleRate,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp+e/this.sampleRate})}close(){this._closed||(null==pa||pa.unregister(this),this._data instanceof Na?(this._data._referenceCount--,0===this._data._referenceCount&&this._data.close()):Wa(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 Na?this._createAudioDataFromData():Wa(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(za(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")}},za=e=>{switch(e){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},Ua=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)}},qa=e=>{switch(e){case"u8":case"u8-planar":return(e,t,i)=>e.setUint8(t,J(127.5*(i+1),0,255));case"s16":case"s16-planar":return(e,t,i)=>e.setInt16(t,J(Math.round(32767*i),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,i)=>e.setInt32(t,J(Math.round(2147483647*i),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,i)=>e.setFloat32(t,i,!0)}},Wa=e=>"undefined"!==typeof AudioData&&e instanceof AudioData,Ha=(e,t,i,r,n,s,a,o)=>{const l=Ua(i),c=qa(r),u=La(i),d=La(r),h=za(i);if(za(r))if(h){const r=new ArrayBuffer(o*u),n=I(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.")},Xa=e=>{if(!Ie(e))throw new TypeError("timestamp must be a number.")},$a=(e,t,i)=>i.verifyKeyPackets?t.then(t=>d(null,null,function*(){if(!t||"delta"===t.type)return t;const i=yield e.determinePacketType(t);return i&&(t.type=i),t})):t;class Ga{constructor(e){if(!(e instanceof uo))throw new TypeError("track must be an InputTrack.");this._track=e}getFirstPacket(){return d(this,arguments,function*(e={}){if(Ka(e),this._track.input._disposed)throw new Co;return $a(this._track,this._track._backing.getFirstPacket(e),e)})}getFirstKeyPacket(){return d(this,arguments,function*(e={}){Ka(e);const t=yield this.getFirstPacket(e);return t?"key"===t.type?t:this.getNextKeyPacket(t,e):null})}getPacket(e){return d(this,arguments,function*(e,t={}){if(Xa(e),Ka(t),this._track.input._disposed)throw new Co;return $a(this._track,this._track._backing.getPacket(e,t),t)})}getNextPacket(e){return d(this,arguments,function*(e,t={}){if(!(e instanceof Ri))throw new TypeError("packet must be an EncodedPacket.");if(Ka(t),this._track.input._disposed)throw new Co;return $a(this._track,this._track._backing.getNextPacket(e,t),t)})}getKeyPacket(e){return d(this,arguments,function*(e,t={}){if(Xa(e),Ka(t),this._track.input._disposed)throw new Co;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);const i=yield this._track._backing.getKeyPacket(e,t);if(!i)return i;y("key"===i.type);return"delta"===(yield this._track.determinePacketType(i))?this.getKeyPacket(i.timestamp-1/(yield this._track.getTimeResolution()),t):i})}getNextKeyPacket(e){return d(this,arguments,function*(e,t={}){if(!(e instanceof Ri))throw new TypeError("packet must be an EncodedPacket.");if(Ka(t),this._track.input._disposed)throw new Co;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);const i=yield this._track._backing.getNextKeyPacket(e,t);if(!i)return i;y("key"===i.type);return"delta"===(yield this._track.determinePacketType(i))?this.getNextKeyPacket(i,t):i})}packets(e,t,i={}){if(void 0!==e&&!(e instanceof Ri))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 Ri))throw new TypeError("endPacket must be an EncodedPacket.");if(Ka(i),this._track.input._disposed)throw new Co;const r=[];let{promise:n,resolve:s}=V(),{promise:a,resolve:o}=V(),l=!1,c=!1,u=null,h=!1;const f=[],m=()=>Math.max(2,f.length);(()=>d(this,null,function*(){let u=null!=e?e:yield this.getFirstPacket(i);for(;u&&!c&&!this._track.input._disposed&&!(t&&u.sequenceNumber>=(null==t?void 0:t.sequenceNumber));)r.length>m()?(({promise:a,resolve:o}=V()),yield a):(r.push(u),s(),({promise:n,resolve:s}=V()),u=yield this.getNextPacket(u,i));l=!0,s()}))().catch(e=>{h||(u=e,h=!0,s())});const p=this._track;return{next(){return d(this,null,function*(){for(;;){if(p.input._disposed)throw new Co;if(c)return{value:void 0,done:!0};if(h)throw u;if(r.length>0){const e=r.shift(),t=performance.now();for(f.push(t);f.length>0&&t-f[0]>=1e3;)f.shift();return o(),{value:e,done:!1}}if(l)return{value:void 0,done:!0};yield n}})},return(){return d(this,null,function*(){return c=!0,o(),s(),{value:void 0,done:!0}})},throw(e){return d(this,null,function*(){throw e})},[Symbol.asyncIterator](){return this}}}}class Qa{constructor(e,t){this.onSample=e,this.onError=t}}class Ya{mediaSamplesInRange(e=-1/0,t=1/0,i){Xa(e),Xa(t);const r=[];let n=!1,s=null,{promise:a,resolve:o}=V(),{promise:l,resolve:h}=V(),f=!1,m=!1,p=!1,g=null,k=null,y=!1;const b=u(c({},i),{verifyKeyPackets:!0,metadataOnly:!1});(()=>d(this,null,function*(){var i;g=yield this._createDecoder(i=>{h(),i.timestamp>=t&&(m=!0),m?i.close():(s&&(i.timestamp>e?(r.push(s),n=!0):s.close()),i.timestamp>=e&&(r.push(i),n=!0),s=n?null:i,r.length>0&&(o(),({promise:a,resolve:o}=V())))},e=>{y||(k=e,y=!0,o())});const c=this._createPacketSink(),u=null!=(i=yield c.getKeyPacket(e,b))?i:yield c.getFirstKeyPacket(b);let d=u;const T=c.packets(null!=u?u:void 0,void 0,b);for(yield T.next();d&&!m&&!this._track.input._disposed;){const e=Ja(r.length);if(r.length+g.getDecodeQueueSize()>e){({promise:l,resolve:h}=V()),yield l;continue}g.decode(d);const t=yield T.next();if(t.done)break;d=t.value}yield T.return(),p||this._track.input._disposed||(yield g.flush()),!n&&s&&r.push(s),f=!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 d(this,null,function*(){for(;;){if(T.input._disposed)throw p=!0,m=!0,v(),new Co;if(p)return{value:void 0,done:!0};if(y)throw p=!0,m=!0,v(),k;if(r.length>0){const e=r.shift();return h(),{value:e,done:!1}}if(f)return{value:void 0,done:!0};yield a}})},return(){return d(this,null,function*(){return p=!0,m=!0,h(),o(),v(),{value:void 0,done:!0}})},throw(e){return d(this,null,function*(){throw e})},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e,t){(e=>{if(!(Symbol.iterator in e)&&!(Symbol.asyncIterator in e))throw new TypeError("Argument must be an iterable or async iterable.")})(e);const i=function(e){return f(this,null,function*(){Symbol.iterator in e?yield*m(e[Symbol.iterator]()):yield*m(e[Symbol.asyncIterator]())})}(e),r=[],n=[];let{promise:s,resolve:a}=V(),{promise:o,resolve:l}=V(),h=!1,g=!1,k=null,b=null,T=!1;const v=e=>{n.push(e),a(),({promise:s,resolve:a}=V())},S=u(c({},t),{verifyKeyPackets:!0,metadataOnly:!1});(()=>d(this,null,function*(){k=yield this._createDecoder(e=>{if(l(),g)return void e.close();let t=0;for(;r.length>0&&e.timestamp-r[0]>-1e-10;)t++,r.shift();if(t>0)for(let i=0;i{T||(b=e,T=!0,a())});const e=this._createPacketSink();let t=null,s=null,c=-1;const u=()=>d(this,null,function*(){y(s),y(k);let t=s;for(k.decode(t);t.sequenceNumberi&&!g;)({promise:o,resolve:l}=V()),yield o;if(g)break;const r=yield e.getNextPacket(t,S);y(r),k.decode(r),t=r}c=-1}),f=()=>d(this,null,function*(){y(k),yield k.flush();for(let e=0;e{T||(b=e,T=!0,a())}).finally(()=>{null==k||k.close()});const w=this._track,P=()=>{for(const e of n)null==e||e.close()};return{next(){return d(this,null,function*(){for(;;){if(w.input._disposed)throw g=!0,P(),new Co;if(g)return{value:void 0,done:!0};if(T)throw g=!0,P(),b;if(n.length>0){const e=n.shift();return y(void 0!==e),l(),{value:e,done:!1}}if(h)return{value:void 0,done:!0};yield s}})},return(){return d(this,null,function*(){return g=!0,l(),a(),P(),{value:void 0,done:!0}})},throw(e){return d(this,null,function*(){throw e})},[Symbol.asyncIterator](){return this}}}}const Ja=e=>0===e?40:8;class Za extends Qa{constructor(e,t,i,r,n,s){var a,o,l,d,h,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 de,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=Va.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 ba))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();y(void 0!==t),this.mergeAlpha(e,t)}else this.colorQueue.push(e)};if(ke()){if("avc"===i&&this.decoderConfig.description){const e=ot(P(this.decoderConfig.description));if(e&&e.sequenceParameterSets.length>0){const t=ct(e.sequenceParameterSets[0]);t&&(0===t.frameMbsOnlyFlag&&(this.decoderConfig=u(c({},this.decoderConfig),{hardwareAcceleration:"prefer-software"})),0!==t.maxDecFrameBuffering&&1!==t.bitstreamRestrictionFlag&&(e.sequenceParameterSets[0]=dt(t),this.decoderConfig=u(c({},this.decoderConfig),{description:at(e)})))}}D(this.decoderConfig.colorSpace)||(this.decoderConfig=u(c({},this.decoderConfig),{colorSpace:{primaries:null!=(o=null==(a=this.decoderConfig.colorSpace)?void 0:a.primaries)?o:"bt709",matrix:null!=(d=null==(l=this.decoderConfig.colorSpace)?void 0:l.matrix)?d:"bt709",transfer:null!=(f=null==(h=this.decoderConfig.colorSpace)?void 0:h.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:(y(this.decoder),Math.max(this.decoder.decodeQueueSize,null!=(t=null==(e=this.alphaDecoder)?void 0:e.decodeQueueSize)?t:0))}decode(e){if("hevc"===this.codec&&this.currentPacketIndex>0&&!this.raslSkipped){if(this.hasHevcRaslPicture(e.data))return;this.raslSkipped=!0}if(this.customDecoder)this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).catch(e=>this.onError(e)).finally(()=>this.customDecoderQueueSize--);else{if(y(this.decoder),fe()||H(this.inputTimestamps,e.timestamp,e=>e),ke()&&0===this.currentPacketIndex)if("avc"===this.codec){const t=[];let i=!1;for(const n of Ze(e.data,this.decoderConfig)){const r=et(e.data[n.offset]);if(i||(i=r>=1&&r<=5),r===Xe.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&P(t.description)[4];return nt(e,i+1)}return rt(e)})(t,this.decoderConfig);e=new Ri(r,e.type,e.timestamp,e.duration)}else if("hevc"===this.codec){const t=It(e.data,this.decoderConfig);t&&(e=new Ri(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 to),!this.alphaDecoder){const e=e=>{if(this.colorQueue.length>0){const t=this.colorQueue.shift();y(void 0!==t),this.mergeAlpha(t,e)}else this.alphaQueue.push(e);for(this.decodedAlphaChunkCount++;this.nullAlphaFrameQueue.length>0&&this.nullAlphaFrameQueue[0]===this.decodedAlphaChunkCount;)if(this.nullAlphaFrameQueue.shift(),this.colorQueue.length>0){const e=this.colorQueue.shift();y(void 0!==e),this.mergeAlpha(e,null)}else this.alphaQueue.push(null);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=At(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 ht(e,this.decoderConfig)){const i=ft(e[t.offset]);if(i===Ge.RASL_N||i===Ge.RASL_R)return!0}return!1}sampleHandler(e){if(fe()){if(this.sampleQueue.length>0&&e.timestamp>=T(this.sampleQueue).timestamp){for(const e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}H(this.sampleQueue,e,e=>e.timestamp)}else{const t=this.inputTimestamps.shift();y(void 0!==t),e.setTimestamp(t),this.finalizeAndEmitSample(e)}}finalizeAndEmitSample(e){e.setTimestamp(Math.round(e.timestamp*this.timeResolution)/this.timeResolution),e.setDuration(Math.round(e.duration*this.timeResolution)/this.timeResolution),e.setRotation(this.rotation),this.onSample(e)}mergeAlpha(e,t){return d(this,null,function*(){const i=V();this.mergeAlphaPromises.push(i.promise);const r={sample:null};this.finalSamples.push(r);try{if(t){y(this.merger);const i=yield this.merger.merge(e,t);r.sample=new ba(i)}else r.sample=new ba(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 d(this,null,function*(){var e;if(this.customDecoder?yield this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(y(this.decoder),yield Promise.all([this.decoder.flush(),null==(e=this.alphaDecoder)?void 0:e.flush()]),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),fe()){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()):(y(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 eo=null;class to{constructor(){this.workers=[],this.nextWorkerIndex=0,this.pendingRequests=new Map,this.nextRequestId=0}merge(e,t){if(0===this.workers.length){if(!eo){const e=new Blob([`(${io.toString()})()`],{type:"application/javascript"});eo=URL.createObjectURL(e)}const e=J(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=V();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 io=()=>{let e=null,t=null,i=Promise.resolve();self.addEventListener("message",e=>{const{id:t,color:n,alpha:s}=e.data;i=i.then(()=>d(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)=>d(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)=>d(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;ed(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)=>d(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;ed(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 no extends Ya{constructor(e,t={}){if(!(e instanceof mo))throw new TypeError("videoTrack must be an InputVideoTrack.");ro(t),super(),this._track=e,this._decoderOptions=t}_createDecoder(e,t){return d(this,null,function*(){if(!(yield this._track.canDecode())){if("undefined"===typeof VideoDecoder)throw new Error(ye("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 y(i&&n),n=u(c({},n),{hardwareAcceleration:this._decoderOptions.hardwareAcceleration,optimizeForLatency:this._decoderOptions.optimizeForLatency}),new Za(e,t,i,n,r,s)})}_createPacketSink(){return new Ga(this._track)}getSample(e){return d(this,arguments,function*(e,t={}){Xa(e);try{for(var i,r,n,s=p(this.mediaSamplesAtTimestamps([e],t));i=!(r=yield s.next()).done;i=!1){return r.value}}catch(r){n=[r]}finally{try{i&&(r=s.return)&&(yield r.call(s))}finally{if(n)throw n[0]}}throw new Error("Internal error: Iterator returned nothing.")})}samples(e,t,i={}){return this.mediaSamplesInRange(e,t,i)}samplesAtTimestamps(e,t={}){return this.mediaSamplesAtTimestamps(e,t)}}class so{constructor(e,t={}){var i,r,n;if(this._rotation=0,this._initPromise=null,this._nextCanvasIndex=0,!(e instanceof mo))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&&Ca(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&&ro(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 no(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=(()=>d(this,null,function*(){var e;const t=this._options,i=this._videoTrack,r=null!=(e=t.rotation)?e:yield i.getRotation(),n=yield i.getSquarePixelWidth(),s=yield i.getSquarePixelHeight(),[a,o]=r%180===0?[n,s]:[s,n];let l=t.crop;l&&(l=xa(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||pe()});y(s),e._drawWithFitAndMipmapping(r,s,{fit:this._fit,rotation:this._rotation,crop:this._crop,targetIsFresh:n,fillBlack:!this._alpha&&pe()});const a={canvas:r,timestamp:e.timestamp,duration:e.duration};return e.close(),a}getCanvas(e,t){return d(this,null,function*(){Xa(e),yield this._ensureInit();const i=yield this._videoSampleSink.getSample(e,t);return i&&this._videoSampleToWrappedCanvas(i)})}canvases(e,t,i){return f(this,null,function*(){yield new h(this._ensureInit()),yield*m(Y(this._videoSampleSink.samples(e,t,i),e=>this._videoSampleToWrappedCanvas(e)))})}canvasesAtTimestamps(e,t){return f(this,null,function*(){yield new h(this._ensureInit()),yield*m(Y(this._videoSampleSink.samplesAtTimestamps(e,t),e=>e&&this._videoSampleToWrappedCanvas(e)))})}}class ao extends Qa{constructor(e,t,i,r){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new de,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 Oa))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 Oa(e))}catch(t){this.onError(t)}},error:t=>{t.stack=e,this.onError(t)}}),this.decoder.configure(r)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(y(this.decoder),this.decoder.decodeQueueSize)}decode(e){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).catch(e=>this.onError(e)).finally(()=>this.customDecoderQueueSize--)):(y(this.decoder),null!=this.expectedFirstTimestamp||(this.expectedFirstTimestamp=e.timestamp),this.decoder.decode(e.toEncodedAudioChunk()))}flush(){return d(this,null,function*(){this.customDecoder?yield this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(y(this.decoder),yield this.decoder.flush()),this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0})}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(y(this.decoder),"closed"!==this.decoder.state&&this.decoder.close())}}class oo extends Qa{constructor(e,t,i){super(e,t),this.decoderConfig=i,this.currentTimestamp=null,y(ni.includes(i.codec)),this.codec=i.codec;const{dataType:r,sampleSize:n,littleEndian:s}=ki(this.codec);switch(this.inputSampleSize=n,n){case 1:"unsigned"===r?this.readInputValue=(e,t)=>e.getUint8(t)-o(2,7):"signed"===r?this.readInputValue=(e,t)=>e.getInt8(t):"ulaw"===r?this.readInputValue=(e,t)=>(e=>{let t=0,i=0,r=~e;128&r&&(r&=-129,t=-1),i=5+((240&r)>>4);const n=(1<(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)-o(2,15):"signed"===r?this.readInputValue=(e,t)=>e.getInt16(t,s):y(!1);break;case 3:"unsigned"===r?this.readInputValue=(e,t)=>G(e,t,s)-o(2,23):"signed"===r?this.readInputValue=(e,t)=>((e,t,i)=>G(e,t,i)<<8>>8)(e,t,s):y(!1);break;case 4:"unsigned"===r?this.readInputValue=(e,t)=>e.getUint32(t,s)-o(2,31):"signed"===r?this.readInputValue=(e,t)=>e.getInt32(t,s):"float"===r?this.readInputValue=(e,t)=>e.getFloat32(t,s):y(!1);break;case 8:"float"===r?this.readInputValue=(e,t)=>e.getFloat64(t,s):y(!1);break;default:$(n),y(!1)}switch(n){case 1:"ulaw"===r||"alaw"===r?(this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(e,t,i)=>e.setInt16(t,i,!0)):(this.outputSampleSize=1,this.outputFormat="u8",this.writeOutputValue=(e,t,i)=>e.setUint8(t,i+o(2,7)));break;case 2:this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(e,t,i)=>e.setInt16(t,i,!0);break;case 3:this.outputSampleSize=4,this.outputFormat="s32",this.writeOutputValue=(e,t,i)=>e.setInt32(t,i<<8,!0);break;case 4:this.outputSampleSize=4,"float"===r?(this.outputFormat="f32",this.writeOutputValue=(e,t,i)=>e.setFloat32(t,i,!0)):(this.outputFormat="s32",this.writeOutputValue=(e,t,i)=>e.setInt32(t,i,!0));break;case 8:this.outputSampleSize=4,this.outputFormat="f32",this.writeOutputValue=(e,t,i)=>e.setFloat32(t,i,!0);break;default:$(n),y(!1)}}getDecodeQueueSize(){return 0}decode(e){const t=I(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 Oa({format:this.outputFormat,data:n,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:i,timestamp:o});this.onSample(l)}flush(){return d(this,null,function*(){})}close(){}}class lo extends Ya{constructor(e){if(!(e instanceof po))throw new TypeError("audioTrack must be an InputAudioTrack.");super(),this._track=e}_createDecoder(e,t){return d(this,null,function*(){if(!(yield this._track.canDecode())){if("undefined"===typeof AudioDecoder)throw new Error(ye("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 y(i&&r),ni.includes(r.codec)?new oo(e,t,r):new ao(e,t,i,r)})}_createPacketSink(){return new Ga(this._track)}getSample(e){return d(this,arguments,function*(e,t={}){Xa(e);try{for(var i,r,n,s=p(this.mediaSamplesAtTimestamps([e],t));i=!(r=yield s.next()).done;i=!1){return r.value}}catch(r){n=[r]}finally{try{i&&(r=s.return)&&(yield r.call(s))}finally{if(n)throw n[0]}}throw new Error("Internal error: Iterator returned nothing.")})}samples(e,t,i={}){return this.mediaSamplesInRange(e,t,i)}samplesAtTimestamps(e,t={}){return this.mediaSamplesAtTimestamps(e,t)}}class co{constructor(e){if(!(e instanceof po))throw new TypeError("audioTrack must be an InputAudioTrack.");this._audioSampleSink=new lo(e)}_audioSampleToWrappedArrayBuffer(e){const t={buffer:e.toAudioBuffer(),timestamp:e.timestamp,duration:e.duration};return e.close(),t}getBuffer(e,t){return d(this,null,function*(){Xa(e);const i=yield this._audioSampleSink.getSample(e,t);return i&&this._audioSampleToWrappedArrayBuffer(i)})}buffers(e,t,i){return Y(this._audioSampleSink.samples(e,t,i),e=>this._audioSampleToWrappedArrayBuffer(e))}buffersAtTimestamps(e,t){return Y(this._audioSampleSink.samplesAtTimestamps(e,t),e=>e&&this._audioSampleToWrappedArrayBuffer(e))}}class uo{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof mo}isAudioTrack(){return this instanceof po}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}getInternalCodecId(){return d(this,null,function*(){return this._backing.getInternalCodecId()})}get internalCodecId(){return ho(this._backing.getInternalCodecId(),"internalCodecId","getInternalCodecId")}getLanguageCode(){return d(this,null,function*(){return this._backing.getLanguageCode()})}get languageCode(){return ho(this._backing.getLanguageCode(),"languageCode","getLanguageCode")}getName(){return d(this,null,function*(){return this._backing.getName()})}get name(){return ho(this._backing.getName(),"name","getName")}getTimeResolution(){return d(this,null,function*(){return this._backing.getTimeResolution()})}get timeResolution(){return ho(this._backing.getTimeResolution(),"timeResolution","getTimeResolution")}isRelativeToUnixEpoch(){return d(this,null,function*(){return this._backing.isRelativeToUnixEpoch()})}getUnixTimeForTimestamp(e){return d(this,null,function*(){return this._backing.getUnixTimeForTimestamp(e)})}hasUnixTimeMapping(){return d(this,null,function*(){return null!==(yield this._backing.getUnixTimeForTimestamp(yield this.getFirstTimestamp()))})}getDisposition(){return d(this,null,function*(){return this._backing.getDisposition()})}get disposition(){return ho(this._backing.getDisposition(),"disposition","getDisposition")}getBitrate(){return d(this,null,function*(){return this._backing.getBitrate()})}getAverageBitrate(){return d(this,null,function*(){return this._backing.getAverageBitrate()})}getFirstTimestamp(){return d(this,null,function*(){var e;const t=yield this._backing.getFirstPacket({metadataOnly:!0});return null!=(e=null==t?void 0:t.timestamp)?e:0})}computeDuration(e){return d(this,null,function*(){var t,i;const r=yield this._backing.getPacket(1/0,c({metadataOnly:!0},e)),n=(null!=(t=null==r?void 0:r.timestamp)?t:0)+(null!=(i=null==r?void 0:r.duration)?i:0);return ie(n,yield this.getTimeResolution())})}getDurationFromMetadata(){return d(this,arguments,function*(e={}){return this._backing.getDurationFromMetadata(e)})}computePacketStats(e=1/0,t){return d(this,null,function*(){const i=new Ga(this);let r=1/0,n=-1/0,s=0,a=0;try{for(var o,l,u,d=p(i.packets(void 0,void 0,c({metadataOnly:!0},t)));o=!(l=yield d.next()).done;o=!1){const t=l.value;if(s>=e&&t.timestamp>=n)break;r=Math.min(r,t.timestamp),n=Math.max(n,t.timestamp+t.duration),s++,a+=t.byteLength}}catch(l){u=[l]}finally{try{o&&(l=d.return)&&(yield l.call(d))}finally{if(u)throw u[0]}}return{packetCount:s,averagePacketRate:s?Number((s/(n-r)).toPrecision(16)):0,averageBitrate:s?Number((8*a/(n-r)).toPrecision(16)):0}})}isLive(){return d(this,null,function*(){return null!==(yield this._backing.getLiveRefreshInterval())})}getLiveRefreshInterval(){return d(this,null,function*(){return this._backing.getLiveRefreshInterval()})}canBePairedWith(e){if(!(e instanceof uo))throw new TypeError("other must be an InputTrack.");return this.input===e.input&&this!==e&&(this._backing.getPairingMask()&e._backing.getPairingMask())!==BigInt("0")}getPairableTracks(e){return d(this,null,function*(){return this.input.getTracks(bo({filter:e=>e.canBePairedWith(this)},e))})}getPairableVideoTracks(e){return d(this,null,function*(){return this.input.getVideoTracks(bo({filter:e=>e.canBePairedWith(this)},e))})}getPairableAudioTracks(e){return d(this,null,function*(){return this.input.getAudioTracks(bo({filter:e=>e.canBePairedWith(this)},e))})}getPrimaryPairableVideoTrack(e){return d(this,null,function*(){return this.input.getPrimaryVideoTrack(bo({filter:e=>e.canBePairedWith(this)},e))})}getPrimaryPairableAudioTrack(e){return d(this,null,function*(){return this.input.getPrimaryAudioTrack(bo({filter:e=>e.canBePairedWith(this)},e))})}hasPairableTrack(e){return d(this,null,function*(){e&&(e=fo(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=fo(e)),this.hasPairableTrack(t=>d(this,null,function*(){return t.isVideoTrack()&&(!e||(yield e(t)))}))}hasPairableAudioTrack(e){return e&&(e=fo(e)),this.hasPairableTrack(t=>d(this,null,function*(){return t.isAudioTrack()&&(!e||(yield e(t)))}))}}const ho=(e,t,i)=>{if(Te(e))throw new Error(`'${t}' is deprecated and not available synchronously for this track. Use the preferred '${i}()' instead.`);return e},fo=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 Te(r)?r.then(i):i(r)}:void 0};class mo extends uo{constructor(e,t){super(e,t),this._pixelAspectRatioCache=null,this._backing=t}get type(){return"video"}getCodec(){return d(this,null,function*(){return this._backing.getCodec()})}get codec(){return ho(this._backing.getCodec(),"codec","getCodec")}hasOnlyKeyPackets(){return d(this,null,function*(){var e,t,i;return null!=(i=yield null==(t=(e=this._backing).getHasOnlyKeyPackets)?void 0:t.call(e))?i:"prores"===(yield this._backing.getCodec())})}getCodedWidth(){return d(this,null,function*(){return this._backing.getCodedWidth()})}get codedWidth(){return ho(this._backing.getCodedWidth(),"codedWidth","getCodedWidth")}getCodedHeight(){return d(this,null,function*(){return this._backing.getCodedHeight()})}get codedHeight(){return ho(this._backing.getCodedHeight(),"codedHeight","getCodedHeight")}getRotation(){return d(this,null,function*(){return this._backing.getRotation()})}get rotation(){return ho(this._backing.getRotation(),"rotation","getRotation")}getSquarePixelWidth(){return d(this,null,function*(){return this._backing.getSquarePixelWidth()})}get squarePixelWidth(){return ho(this._backing.getSquarePixelWidth(),"squarePixelWidth","getSquarePixelWidth")}getSquarePixelHeight(){return d(this,null,function*(){return this._backing.getSquarePixelHeight()})}get squarePixelHeight(){return ho(this._backing.getSquarePixelHeight(),"squarePixelHeight","getSquarePixelHeight")}getPixelAspectRatio(){return d(this,null,function*(){var e;return null!=(e=this._pixelAspectRatioCache)?e:this._pixelAspectRatioCache=Ee({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=Ee({num:ho(this._backing.getSquarePixelWidth(),"pixelAspectRatio","getPixelAspectRatio")*ho(this._backing.getCodedHeight(),"pixelAspectRatio","getPixelAspectRatio"),den:ho(this._backing.getSquarePixelHeight(),"pixelAspectRatio","getPixelAspectRatio")*ho(this._backing.getCodedWidth(),"pixelAspectRatio","getPixelAspectRatio")})}getDisplayWidth(){return d(this,null,function*(){var e,t;const i=yield null==(t=(e=this._backing).getMetadataDisplayWidth)?void 0:t.call(e);if(null!=i)return i;return(yield this.getRotation())%180===0?this.getSquarePixelWidth():this.getSquarePixelHeight()})}get displayWidth(){var e,t;const i=null==(t=(e=this._backing).getMetadataDisplayWidth)?void 0:t.call(e);if(void 0!==i){const e=ho(i,"displayWidth","getDisplayWidth");if(null!==e)return e}const r=ho(this._backing.getRotation(),"displayWidth","getDisplayWidth")%180===0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight();return ho(r,"displayWidth","getDisplayWidth")}getDisplayHeight(){return d(this,null,function*(){var e,t;const i=yield null==(t=(e=this._backing).getMetadataDisplayHeight)?void 0:t.call(e);if(null!=i)return i;return(yield this.getRotation())%180===0?this.getSquarePixelHeight():this.getSquarePixelWidth()})}get displayHeight(){var e,t;const i=null==(t=(e=this._backing).getMetadataDisplayHeight)?void 0:t.call(e);if(void 0!==i){const e=ho(i,"displayHeight","getDisplayHeight");if(null!==e)return e}const r=ho(this._backing.getRotation(),"displayHeight","getDisplayHeight")%180===0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth();return ho(r,"displayHeight","getDisplayHeight")}getColorSpace(){return d(this,null,function*(){return this._backing.getColorSpace()})}hasHighDynamicRange(){return d(this,null,function*(){const e=yield this._backing.getColorSpace();return"bt2020"===e.primaries||"smpte432"===e.primaries||"pq"===e.transfer||"hlg"===e.transfer||"bt2020-ncl"===e.matrix})}canBeTransparent(){return d(this,null,function*(){return this._backing.canBeTransparent()})}getDecoderConfig(){return d(this,null,function*(){return this._backing.getDecoderConfig()})}getCodecParameterString(){return d(this,null,function*(){var e,t,i;const r=yield null==(t=(e=this._backing).getMetadataCodecParameterString)?void 0:t.call(e);if(null!=r)return r;const n=yield this._backing.getDecoderConfig();return null!=(i=null==n?void 0:n.codec)?i:null})}canDecode(){return d(this,null,function*(){try{const e=yield this._backing.getDecoderConfig();if(!e)return!1;const t=yield this._backing.getCodec();if(y(null!==t),Va.some(i=>i.supports(t,e)))return!0;if("undefined"===typeof VideoDecoder)return!1;return!0===(yield VideoDecoder.isConfigSupported(e)).supported}catch(e){return Me._error("Error during decodability check:",e),!1}})}determinePacketType(e){return d(this,null,function*(){if(!(e instanceof Ri))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("packet must not be metadata-only to determine its type.");const t=yield this.getCodec();if(null===t)return null;const i=yield this.getDecoderConfig();return y(i),At(t,i,e.data)})}computeFrameRateMetrics(){return d(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&&(!Ie(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 Ga(this),a=[];let o=-1/0,l=0;try{for(var c,u,d,h=p(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 p=0;pe-t),x=P-1>>1,C=P>>1;let B=0,E=0,_=0;for(const p of I)if(_+=T.get(p),0===B&&_>x&&(B=p),_>C){E=p;break}const R=(y/B+y/E)/2;return{underlyingFrameRate:k,bestGuessFrameRate:null!==k?k:wo(R),minFrameRate:y/S,maxFrameRate:y/v,averageFrameRate:y*P/w,medianFrameRate:R,frameRateIsConstant:null!==k&&1===v&&1===S,probedPacketCount:l}})}}class po extends uo{constructor(e,t){super(e,t),this._backing=t}get type(){return"audio"}getCodec(){return d(this,null,function*(){return this._backing.getCodec()})}get codec(){return ho(this._backing.getCodec(),"codec","getCodec")}hasOnlyKeyPackets(){return d(this,null,function*(){var e,t,i;return null==(i=yield null==(t=(e=this._backing).getHasOnlyKeyPackets)?void 0:t.call(e))||i})}getNumberOfChannels(){return d(this,null,function*(){return this._backing.getNumberOfChannels()})}get numberOfChannels(){return ho(this._backing.getNumberOfChannels(),"numberOfChannels","getNumberOfChannels")}getSampleRate(){return d(this,null,function*(){return this._backing.getSampleRate()})}get sampleRate(){return ho(this._backing.getSampleRate(),"sampleRate","getSampleRate")}getDecoderConfig(){return d(this,null,function*(){return this._backing.getDecoderConfig()})}getCodecParameterString(){return d(this,null,function*(){var e,t,i;const r=yield null==(t=(e=this._backing).getMetadataCodecParameterString)?void 0:t.call(e);if(null!=r)return r;const n=yield this._backing.getDecoderConfig();return null!=(i=null==n?void 0:n.codec)?i:null})}canDecode(){return d(this,null,function*(){try{const e=yield this._backing.getDecoderConfig();if(!e)return!1;const t=yield this._backing.getCodec();if(y(null!==t),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 Me._error("Error during decodability check:",e),!1}})}determinePacketType(e){return d(this,null,function*(){if(!(e instanceof Ri))throw new TypeError("packet must be an EncodedPacket.");return null===(yield this.getCodec())?null:"key"})}}const go=e=>-(null!=e?e:-1/0),ko=e=>-e,yo=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 Te(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 Te(r)?r.then(i):i(r)}:void 0}},bo=(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 Te(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 Te(o)||Te(l)?Promise.all([o,l]).then(([e,t])=>c(e,t)):c(o,l)}:void 0}),To=(e,t)=>d(null,null,function*(){let i=e;if(null==t?void 0:t.filter){const r=e.map(e=>t.filter(e));if(r.some(e=>Te(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=>Te(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)}),vo=(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 Us)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof ds||e.source instanceof hs))throw new TypeError("options.source must be a Source or SourceRef.");if(e.source instanceof ds&&e.source._disposed)throw new TypeError("options.source must not be a disposed Source.");if(void 0!==e.initInput&&!(e.initInput instanceof Io))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 ds?this._rootRef=e.source.ref():this._rootRef=e.source,this._sourceRefs.push(this._rootRef)}get _rootSource(){return this._rootRef.source}_getSourceUncached(e){return d(this,null,function*(){y(this._rootSource instanceof fs);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&&ms(i.request,e));if(i)return i.age++,Promise.resolve(i.sourceRef.source.ref());const r=this._sourceCachePromises.find(i=>i.cacheGroup===t&&ms(i.request,e));if(r)return r.promise.then(e=>e.sourceRef.source.ref());const n=(()=>d(this,null,function*(){const i=yield this._getSourceUncached(e);if(Ce(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);y(-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);y(-1!==r),this._sourceCachePromises.splice(r,1);return{request:e,sourceRef:i,age:this._nextSourceCacheAge++,cacheGroup:t}}))();return this._sourceCachePromises.push({request:e,cacheGroup:t,promise:n}),n.then(e=>{const t=e.sourceRef.source.ref();return this._sourceCache.push(e),t})}_getDemuxer(){var e;return null!=(e=this._demuxerPromise)?e:this._demuxerPromise=(()=>d(this,null,function*(){var e;this._reader=new Bo(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 xo}))()}get source(){return this._rootSource}getFormat(){return d(this,null,function*(){return yield this._getDemuxer(),y(this._format),this._format})}canRead(){return d(this,null,function*(){try{return yield this._getDemuxer(),!0}catch(e){if(e instanceof xo)return!1;throw e}})}getFirstTimestamp(e){return d(this,null,function*(){null!=e||(e=yield this.getTracks());const t=e.filter(e=>null!==e);if(0===t.length)return 0;const i=yield Promise.all(t.map(e=>e._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 d(this,null,function*(){null!=e||(e=yield this.getTracks());const i=e.filter(e=>null!==e);if(0===i.length)return 0;const r=yield Promise.all(i.map(e=>e.computeDuration(t)));return Math.max(...r)})}getDurationFromMetadata(e,t){return d(this,null,function*(){null!=e||(e=yield this.getTracks());const i=e.filter(e=>null!==e),r=(yield Promise.all(i.map(e=>e.getDurationFromMetadata(t)))).filter(e=>null!==e);return 0===r.length?null:Math.max(...r)})}getTracks(e){return d(this,null,function*(){e&&(e=yo(e));const t=(yield this._getTrackBackings()).map(e=>this._wrapBackingAsTrack(e));return To(t,e)})}getVideoTracks(e){return d(this,null,function*(){e&&(e=yo(e));const t=(yield this.getTracks()).filter(e=>e.isVideoTrack());return To(t,e)})}getAudioTracks(e){return d(this,null,function*(){e&&(e=yo(e));const t=(yield this.getTracks()).filter(e=>e.isAudioTrack());return To(t,e)})}getPrimaryVideoTrack(e){return d(this,null,function*(){var t;e&&(e=yo(e));const i=bo(e,{sortBy:e=>d(null,null,function*(){return[ko((yield e.getDisposition()).default),ko(yield e.hasPairableAudioTrack()),ko(!(yield e.hasOnlyKeyPackets())),go(yield e.getBitrate())]})});return null!=(t=(yield this.getVideoTracks(i))[0])?t:null})}getPrimaryAudioTrack(e){return d(this,null,function*(){var t;e&&(e=yo(e));const i=yield this.getPrimaryVideoTrack(),r=bo(e,{sortBy:e=>d(this,null,function*(){return[ko(!i||e.canBePairedWith(i)),ko((yield e.getDisposition()).default),go(yield e.getBitrate())]})});return null!=(t=(yield this.getAudioTracks(r))[0])?t:null})}_getTrackBackings(){return d(this,null,function*(){var e;const t=yield this._getDemuxer();return null!=(e=this._trackBackingsCache)?e:this._trackBackingsCache=yield t.getTrackBackings()})}_wrapBackingAsTrack(e){const t=this._backingToTrack.get(e);if(t)return t;const i="video"===e.getType()?new mo(this,e):new po(this,e);return this._backingToTrack.set(e,i),i}getMimeType(){return d(this,null,function*(){return(yield this._getDemuxer()).getMimeType()})}getMetadataTags(){return d(this,null,function*(){return(yield this._getDemuxer()).getMetadataTags()})}dispose(){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 xo extends Error{constructor(e="Input has an unsupported or unrecognizable format."){super(e),this.name="UnsupportedInputFormatError"}}class Co extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}}class Bo{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 Co;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 Eo(t,I(t),0,e,e)}const i=e+t,r=this.source._read(e,i,0,us);return Te(r)?r.then(t=>t?new Eo(t.bytes,t.view,t.offset,e,i):null):r?new Eo(r.bytes,r.view,r.offset,e,i):null}requestSliceRange(e,t,i){if(this.source._disposed)throw new Co;if(e<0)return null;if(null!==this.fileSizeNonStrict)return this.requestSlice(e,J(this.fileSizeNonStrict-e,t,i));{const r=this.requestSlice(e,i),n=r=>r||(y(null!==this.fileSizeNonStrict),this.requestSlice(e,J(this.fileSizeNonStrict-e,t,i)));return Te(r)?r.then(n):n(r)}}requestEntireFile(){if(null!==this.fileSizeNonStrict)return this.requestSlice(0,this.fileSizeNonStrict);return(()=>d(this,null,function*(){const e=[];let t=0;for(;;){if(1===e.length&&null!==this.fileSizeNonStrict)return this.requestSlice(0,this.fileSizeNonStrict);let i=this.requestSliceRange(t,0,1024);if(Te(i)&&(i=yield i),!i||0===i.length)break;const r=Ro(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 Eo(i,I(i),0,0,t)}))()}}class Eo{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 Eo(e,I(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 Eo(this.bytes,this.view,this.offset,e,e+t)}}const _o=(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.`)},Ro=(e,t)=>{_o(e,t);const i=e.bytes.subarray(e.bufferPos,e.bufferPos+t);return e.bufferPos+=t,i},Fo=e=>(_o(e,1),e.view.getUint8(e.bufferPos++)),Ao=(e,t)=>{_o(e,2);const i=e.view.getUint16(e.bufferPos,t);return e.bufferPos+=2,i},Do=e=>{_o(e,2);const t=e.view.getUint16(e.bufferPos,!1);return e.bufferPos+=2,t},Mo=e=>{_o(e,3);const t=G(e.view,e.bufferPos,!1);return e.bufferPos+=3,t},No=e=>{_o(e,2);const t=e.view.getInt16(e.bufferPos,!1);return e.bufferPos+=2,t},Oo=(e,t)=>{_o(e,4);const i=e.view.getUint32(e.bufferPos,t);return e.bufferPos+=4,i},Lo=e=>{_o(e,4);const t=e.view.getUint32(e.bufferPos,!1);return e.bufferPos+=4,t},zo=e=>{_o(e,4);const t=e.view.getUint32(e.bufferPos,!0);return e.bufferPos+=4,t},Uo=e=>{_o(e,4);const t=e.view.getInt32(e.bufferPos,!1);return e.bufferPos+=4,t},qo=(e,t)=>{let i,r;return t?(i=Oo(e,!0),r=Oo(e,!0)):(r=Oo(e,!1),i=Oo(e,!1)),4294967296*r+i},Wo=e=>4294967296*Lo(e)+Lo(e),Ho=e=>4294967296*Uo(e)+Lo(e),Vo=e=>{const t=zo(e),i=(e=>{_o(e,4);const t=e.view.getInt32(e.bufferPos,!0);return e.bufferPos+=4,t})(e);return 4294967296*i+t},jo=e=>{_o(e,4);const t=e.view.getFloat32(e.bufferPos,!1);return e.bufferPos+=4,t},Ko=e=>{_o(e,8);const t=e.view.getFloat64(e.bufferPos,!1);return e.bufferPos+=8,t},Xo=(e,t)=>{_o(e,t);let i="";for(let r=0;rx.decode(Ro(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 Go,Qo,Yo,Jo;(Qo=Go||(Go={}))[Qo.Unsynchronisation=128]="Unsynchronisation",Qo[Qo.ExtendedHeader=64]="ExtendedHeader",Qo[Qo.ExperimentalIndicator=32]="ExperimentalIndicator",Qo[Qo.Footer=16]="Footer",(Jo=Yo||(Yo={}))[Jo.ISO_8859_1=0]="ISO_8859_1",Jo[Jo.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",Jo[Jo.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",Jo[Jo.UTF_8=3]="UTF_8";const Zo=128,el=10,tl=["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"],il=(e,t)=>{var i;const r=e.filePos;null!=t.raw||(t.raw={}),null!=(i=t.raw).TAG||(i.TAG=Ro(e,Zo-3)),e.filePos=r;const n=rl(e,30);n&&(null!=t.title||(t.title=n));const s=rl(e,30);s&&(null!=t.artist||(t.artist=s));const a=rl(e,30);a&&(null!=t.album||(t.album=a));const o=rl(e,4),l=Number.parseInt(o,10);Number.isInteger(l)&&l>0&&(null!=t.date||(t.date=new Date(String(l))));const c=Ro(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=rl(e,28),e.skip(2)}else e.skip(-30),u=rl(e,30);u&&(null!=t.comment||(t.comment=u));const d=Fo(e);d{const i=Ro(e,t),r=ve(i.indexOf(0),i.length),n=i.subarray(0,r);let s="";for(let a=0;a{const t=e.filePos,i=Xo(e,3),r=Fo(e),n=Fo(e),s=Fo(e),a=Lo(e);if("ID3"!==i||255===r||255===n||0!==(2155905152&a))return e.filePos=t,null;let o=Ii(a);return s&Go.Footer&&(o+=el),{majorVersion:r,revision:n,flags:s,size:o}},sl=(e,t,i)=>{var r,n,s,a,o,l;if(![2,3,4].includes(t.majorVersion))return void Me._warn(`Unsupported ID3v2 major version: ${t.majorVersion}`);const c=t.flags&Go.Footer?t.size-el:t.size,u=Ro(e,c),d=new al(t,u);if(t.flags&Go.Unsynchronisation&&3===t.majorVersion&&d.ununsynchronizeAll(),t.flags&Go.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&Go.Unsynchronisation)),h)Me._warn(`Skipping encrypted ID3v2 frame ${e.id}`),d.pos=u;else if(f)Me._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!==tl[e]){null!=i.genre||(i.genre=tl[e]);break}}if(t=/^\d+$/.exec(e),t){const e=Number.parseInt(t[0]);if(void 0!==tl[e]){null!=i.genre||(i.genre=tl[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 al{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:Ii(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 Yo.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=ve(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=ve(r.findIndex(e=>0===e),r.length);return this.pos=i+Math.min(e+1,r.length),x.decode(r.subarray(0,e))}case Yo.UTF_16_BE_NO_BOM:{const e=new TextDecoder("utf-16be"),t=ve(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 Yo.UTF_8:{const e=ve(r.findIndex(e=>0===e),r.length);return this.pos=i+Math.min(e+1,r.length),x.decode(r.subarray(0,e))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";const t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}}class ol{constructor(e){this.events=e,this.input=null,this.audioSink=null,this.audioIterator=null,this.audioContext=null,this.gainNode=null,this.audioContextStartTime=0,this.playbackTimeAtStart=0,this.latestScheduledEndTime=0,this.duration=Number.NaN,this.paused=!0,this.volume=.7,this.muted=!1,this.playbackRate=1,this.asyncId=0,this.queuedNodes=new Set}get currentTime(){return this.paused?this.playbackTimeAtStart:(this.audioContext.currentTime-this.audioContextStartTime)*this.playbackRate+this.playbackTimeAtStart}ensureAudioContext(e){if(this.audioContext)return;const t=window.AudioContext||window.webkitAudioContext;try{this.audioContext=new t({sampleRate:e})}catch(i){this.audioContext=new t}this.gainNode=this.audioContext.createGain(),this.gainNode.connect(this.audioContext.destination),this.updateGain()}updateGain(){if(!this.gainNode)return;const e=this.muted?0:this.volume;this.gainNode.gain.value=e*e}stopQueuedNodes(){this.queuedNodes.forEach(e=>e.stop()),this.queuedNodes.clear()}stopIterator(){return d(this,null,function*(){var e;yield null==(e=this.audioIterator)?void 0:e.return(),this.audioIterator=null})}handleNoAudioTrack(){this.audioSink=null,this.ensureAudioContext()}load(e,t){return d(this,null,function*(){++this.asyncId,yield this.stopIterator(),this.stopQueuedNodes(),this.paused=!0,this.playbackTimeAtStart=0,this.audioContextStartTime=0;const{input:i,audioTrack:r,duration:n}=e;return this.input=i,this.duration=n,r?null!==r.codec&&(yield r.canDecode())?(this.ensureAudioContext(r.sampleRate),this.audioSink=new co(r),void(null==t||t())):(this.audioSink=null,this.ensureAudioContext(),void(null==t||t())):(this.handleNoAudioTrack(),void(null==t||t()))})}runIterator(e){return d(this,null,function*(){if(!this.audioSink)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 d(this,null,function*(){if(!this.paused)return;this.audioContext||this.ensureAudioContext(),"suspended"===this.audioContext.state&&(yield this.audioContext.resume()),this.audioContextStartTime=this.audioContext.currentTime,this.latestScheduledEndTime=this.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 d(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 ll(e){return d(this,null,function*(){var t,i;return null!=(i=null!=(t=yield e.getAverageBitrate())?t:yield e.getBitrate())?i:0})}const cl=/\.m3u8(?:$|[?#])/i;function ul(e){return"string"===typeof e&&cl.test(e)}function dl(e){const t=function(e){return"string"===typeof e?new vs(e):e instanceof Blob?new ks(e):"undefined"!==typeof ReadableStream&&e instanceof ReadableStream?new Ps(e):null!=e?e:null}(e);return t?new Io({source:t,formats:ul(e)?da:ua}):null}class hl{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 d(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 fl(e){return d(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 ml{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 d(this,null,function*(){return function(e,t,i,r,n=()=>!0){return d(this,null,function*(){if((null==r?void 0:r.aborted)||!n())return!1;if(!t||"string"!==typeof e||ul(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 d(this,null,function*(){var e;yield null==(e=this.videoIterator)?void 0:e.return(),this.videoIterator=null})}clear(){this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height)}load(e,t){return d(this,null,function*(){++this.asyncId,yield this.stopIterator(),this.clear(),this.posterDrawn=!1;const{input:i,videoTrack:r,duration:n}=e;if(this.input=i,this.duration=n,!r)return this.handleNoVideoTrack(),void(null==t||t());if(null===r.codec||!(yield r.canDecode()))return this.handleNoVideoTrack(),void(null==t||t());const s=yield r.canBeTransparent();this.videoSink=new so(r,{poolSize:2,fit:"contain",alpha:s}),this.width=r.displayWidth,this.height=r.displayHeight,this.canvas.width=this.width,this.canvas.height=this.height,null==t||t(),yield this.resetIterator(0)})}handleNoVideoTrack(){this.videoSink=null,this.width=0,this.height=0,this.canvas.width=0,this.canvas.height=0,this.clear(),this.drawPoster()}resetIterator(e){return d(this,null,function*(){var t,i;if(yield this.stopIterator(),!this.videoSink)return;this.videoIterator=this.videoSink.canvases(e);const r=null!=(t=(yield this.videoIterator.next()).value)?t:null,n=null!=(i=(yield this.videoIterator.next()).value)?i:null;this.nextFrame=n,r?this.ctx.drawImage(r.canvas,0,0):this.drawPoster()})}updateNextFrame(e){return d(this,null,function*(){var t;if(this.videoIterator&&!this.isFetching){this.isFetching=!0;try{for(;;){const i=null!=(t=(yield this.videoIterator.next()).value)?t:null;if(!i||e!==this.asyncId)return;const r=this.audioClock.currentTime,n=this.dropLateFrames?Math.max(.06,this.avSyncTolerance/Math.max(1,this.playbackRate)):0;if(!(this.dropLateFrames&&i.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 d(this,null,function*(){this.asyncId++,yield this.resetIterator(e)})}setPlaybackRate(e){this.playbackRate=Math.max(.1,Number(e)||1)}destroy(){this.asyncId++,this.stop(),this.stopIterator(),this.posterDrawn=!1,this.videoSink=null,this.input=null}}class pl{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 ol(i),this.video=new ml({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 d(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 hl;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 d(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=dl(e);if(!r)return this.video.handleNoVideoTrack(),void this.audio.handleNoAudioTrack();i.own(r);const n=yield function(e,t){return d(this,null,function*(){const i=yield e.getPrimaryVideoTrack(),r=i?yield i.getPrimaryPairableAudioTrack():yield e.getPrimaryAudioTrack(),n=yield fl({input:e,videoTrack:i,audioTrack:r}),s=i||r,a=ul(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 d(this,arguments,function*({videoTrack:e,audioTrack:t,videoMode:i,audioMode:r}){if(!this.media)return;const n=u(c({},this.media),{videoTrack:e,audioTrack:t,videoMode:i,audioMode:r}),s=!this.paused,a=this.currentTime;this.pause(),this.ended=!1,this.seeking=!0,this.events.emit("seeking"),this.events.emit("waiting"),n.duration=yield fl(n),this.media=n,yield Promise.all([this.video.load(n),this.audio.load(n)]),yield Promise.all([this.video.seek(a),this.audio.seek(a)]),this.readyState=4,this.networkState=1,this.seeking=!1,this.events.emit("loadedmetadata"),this.events.emit("durationchange"),this.events.emit("progress"),this.events.emit("loadeddata"),this.events.emit("canplay"),this.events.emit("canplaythrough"),this.events.emit("seeked"),s&&(yield this.play())})}selectHlsQuality(e){return d(this,null,function*(){var t,i;if(!(null==(t=this.media)?void 0:t.isHls)||!this.input)return;const r=yield this.input.getVideoTracks(),n="auto"===e?yield this.input.getPrimaryVideoTrack():null!=(i=r.find(t=>t.id===e))?i:this.media.videoTrack;if(!n)return;let s=this.media.audioTrack,a=this.media.audioMode;s&&n.canBePairedWith(s)||(s=yield n.getPrimaryPairableAudioTrack(),a="auto"),yield this.replaceTracks({videoTrack:n,audioTrack:s,videoMode:"auto"===e?"auto":"manual",audioMode:a})})}selectHlsAudio(e){return d(this,null,function*(){var t,i;if(!(null==(t=this.media)?void 0:t.isHls)||!this.input)return;const r=yield this.input.getAudioTracks(),n="auto"===e?this.media.videoTrack?yield this.media.videoTrack.getPrimaryPairableAudioTrack():yield this.input.getPrimaryAudioTrack():null!=(i=r.find(t=>t.id===e))?i:this.media.audioTrack;if(!n)return;let s=this.media.videoTrack,a=this.media.videoMode;s&&n.canBePairedWith(s)||(s=yield n.getPrimaryPairableVideoTrack(),a="auto"),yield this.replaceTracks({videoTrack:s,audioTrack:n,videoMode:a,audioMode:"auto"===e?"auto":"manual"})})}getHlsState(){return function(e){return d(this,null,function*(){var t,i,r,n;if(!(null==e?void 0:e.isHls)||!e.input)return null;const[s,a]=yield Promise.all([e.input.getVideoTracks(),e.videoTrack?e.videoTrack.getPairableAudioTracks():[]]),[o,l]=yield Promise.all([Promise.all(s.map((e,t)=>d(null,null,function*(){return{id:e.id,track:e,index:t,name:yield e.getName(),height:yield e.getDisplayHeight(),bitrate:yield ll(e)}}))),Promise.all(a.map((e,t)=>d(null,null,function*(){const i=yield e.getName(),r=yield e.getLanguageCode();return{id:e.id,track:e,index:t,name:i,lang:r,language:r,bitrate:yield ll(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 d(this,null,function*(){this.paused&&(this.ended&&(this.ended=!1,yield this.seek(0)),this.paused=!1,yield this.audio.play(),this.video.start(this.audio),this.events.emit("play"),this.events.emit("playing"))})}pause(){this.paused||(this.paused=!0,this.audio.pause(),this.video.stop(),this.events.emit("pause"))}seek(e){return d(this,null,function*(){const t=!this.paused;this.ended=!1,this.seeking=!0,this.events.emit("seeking"),this.events.emit("waiting"),this.pause(),yield Promise.all([this.audio.seek(e),this.video.seek(e)]),this.seeking=!1,this.events.emit("seeked"),t&&!this.ended&&(yield this.play())})}setVolume(e,t){this.audio.setVolume(e,t)}setPlaybackRate(e){this.audio.setPlaybackRate(e),this.video.setPlaybackRate(e)}destroy(){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}}class gl{constructor({art:e,canvas:t,ctx:i,option:r}){var n,s;this.art=e,this.canvas=t,this.option=r,this.events=new k,this.engine=new pl({canvas:t,ctx:i,events:this.events,option:r}),this._src=null,this._volume=null!=(n=r.volume)?n:.7,this._muted=!!r.muted,this._playbackRate=1,this.engine.setVolume(this._volume,this._muted),this.setupEventForwarding(),r.source?this.src=r.source:(null==(s=e.option)?void 0:s.url)&&(this.src=e.option.url)}setupEventForwarding(){const{events:e}=this.art.constructor.config;e.forEach(e=>{this.events.addEventListener(e,e=>{this.art.emit(`video:${e.type}`,e)})})}addEventListener(e,t){this.events.addEventListener(e,t)}removeEventListener(e,t){this.events.removeEventListener(e,t)}get src(){return this._src}set src(e){this._src=e,e&&this.engine.load(e)}get currentSrc(){return this._src}get currentTime(){return this.engine.currentTime}set currentTime(e){this.engine.seek(Number(e)||0)}get duration(){return this.engine.duration}get buffered(){return this.createTimeRanges(0,this.engine.duration)}get played(){return this.createTimeRanges(0,this.engine.currentTime)}get seekable(){return this.createTimeRanges(0,this.engine.duration)}createTimeRanges(e,t){const i=this.engine.duration;return!i||Number.isNaN(i)||t<=0?{length:0,start:()=>0,end:()=>0}:{length:1,start:()=>e,end:()=>t}}get paused(){return this.engine.paused}get playing(){return!this.engine.paused&&!this.engine.ended}get ended(){return this.engine.ended}get seeking(){return this.engine.seeking}get readyState(){return this.engine.readyState}get networkState(){return this.engine.networkState}get error(){return this.engine.error}get playbackRate(){return this._playbackRate}set playbackRate(e){const t=Number(e);Number.isNaN(t)||t<=0||(this._playbackRate=t,this.engine.setPlaybackRate(t),this.events.emit("ratechange"))}get volume(){return this._volume}set volume(e){this._volume=function(e,t,i){return Math.max(t,Math.min(i,Number(e)||0))}(e,0,1),this._muted=!1,this.engine.setVolume(this._volume,this._muted),this.events.emit("volumechange")}get muted(){return this._muted}set muted(e){this._muted=!!e,this.engine.setVolume(this._volume,this._muted),this.events.emit("volumechange")}play(){return this.engine.play()}pause(){this.engine.pause()}load(){this._src&&this.engine.load(this._src)}getM3u8State(){return this.engine.getHlsState()}switchM3u8Quality(e){return this.engine.selectHlsQuality(e)}switchM3u8Audio(e){return this.engine.selectHlsAudio(e)}get videoWidth(){return this.engine.videoWidth}get videoHeight(){return this.engine.videoHeight}get poster(){return this.option.poster||""}set poster(e){this.option.poster=e}get autoplay(){return this.option.autoplay||!1}set autoplay(e){}get loop(){return this.option.loop||!1}set loop(e){}get controls(){return!1}set controls(e){}get playsInline(){return!0}set playsInline(e){}get crossOrigin(){return this.option.crossOrigin||""}set crossOrigin(e){}get preload(){return"auto"}set preload(e){}get defaultMuted(){return!1}set defaultMuted(e){}get defaultPlaybackRate(){return 1}set defaultPlaybackRate(e){}canPlayType(e){return"maybe"}getBoundingClientRect(){return this.canvas.getBoundingClientRect()}requestVideoFrameCallback(e){return requestAnimationFrame(t=>{e(t,{presentationTime:this.engine.currentTime,expectedDisplayTime:t+16.6,width:this.engine.videoWidth,height:this.engine.videoHeight,mediaTime:this.engine.currentTime,presentedFrames:0,processingDuration:0,captureTime:t,receiveTime:t,rtpTimestamp:0})})}cancelVideoFrameCallback(e){cancelAnimationFrame(e)}setAttribute(e,t){"src"===e?this.src=t:"autoplay"===e?this.autoplay=t:"loop"===e?this.loop=t:"muted"===e?this.muted=!0:this.canvas.setAttribute(e,t)}destroy(){this.engine.destroy()}}return function(e={}){return t=>{const{constructor:i}=t,{createElement:r}=i.utils,n=r("canvas"),s=n.getContext("2d"),a=new gl({art:t,canvas:n,ctx:s,option:e});t.mediabunny=a;const o={};for(const e in n)"function"===typeof n[e]&&(o[e]=n[e].bind(n));const l=new Set([...Object.getOwnPropertyNames(a),...Object.getOwnPropertyNames(Object.getPrototypeOf(a))]);for(const e of l)"constructor"!==e&&(e in n||Object.defineProperty(n,e,{get(){const t=a[e];return"function"===typeof t?t.bind(a):t},set(t){a[e]=t},configurable:!0,enumerable:!0}));for(const e in o)n[e]=(...t)=>o[e](...t);function c(){var e;(null==(e=t.template)?void 0:e.$player)&&!t.option.autoSize&&Object.assign(n.style,{width:"100%",height:"100%",objectFit:"contain"})}return t.on("resize",c),t.on("video:loadedmetadata",c),function({art:e,shim:t,option:i}){if(i.m3u8)return e.on("video:loadedmetadata",u),e.on("restart",u),{update:u};function r(t){e.controls.cache.has(t)&&e.controls.remove(t)}function n(t){e.setting.find(t)&&e.setting.remove(t)}function s(){r("mediabunny-quality"),n("mediabunny-quality")}function a(){r("mediabunny-audio"),n("mediabunny-audio")}function o(e={}){return e.control||e.setting}function l(r){return d(this,null,function*(){var n;const a=(null==(n=i.m3u8)?void 0:n.quality)||{};if(!o(a)||!(null==r?void 0:r.levels.length))return void s();const l=a.auto||"Auto",c=a.title||"Quality",h=a.getName||(e=>e.name||`${e.height}P`),f=r.currentLevel?h(r.currentLevel):l,m=g(r.levels.map(e=>{var t;return{html:h(e),value:e.id,default:(null==(t=r.currentLevel)?void 0:t.id)===e.id}}),"html").sort((e,t)=>{const i=r.levels.find(t=>t.id===e.value),n=r.levels.find(e=>e.id===t.value);return((null==n?void 0:n.height)||0)-((null==i?void 0:i.height)||0)});m.push({html:l,value:"auto",default:!r.currentLevel});const p=i=>d(null,null,function*(){return yield t.switchM3u8Quality(i.value),e.notice.show=`${c}: ${i.html}`,yield u(),i.html});a.control&&e.controls.update({name:"mediabunny-quality",position:"right",html:f,style:{padding:"0 10px"},selector:m,onSelect:p}),a.setting&&e.setting.update({name:"mediabunny-quality",tooltip:f,html:c,icon:'',width:200,selector:m,onSelect:p})})}function c(r){return d(this,null,function*(){var n;const s=(null==(n=i.m3u8)?void 0:n.audio)||{};if(!o(s)||!(null==r?void 0:r.audios.length)||r.audios.length<2)return void a();const l=s.auto||"Auto",c=s.title||"Audio",h=s.getName||(e=>e.name||e.lang||e.language),f=r.currentAudio?h(r.currentAudio):l,m=g(r.audios.map(e=>{var t;return{html:h(e),value:e.id,default:(null==(t=r.currentAudio)?void 0:t.id)===e.id}}),"html");m.push({html:l,value:"auto",default:!r.currentAudio});const p=i=>d(null,null,function*(){return yield t.switchM3u8Audio(i.value),e.notice.show=`${c}: ${i.html}`,yield u(),i.html});s.control&&e.controls.update({name:"mediabunny-audio",position:"right",html:f,style:{padding:"0 10px"},selector:m,onSelect:p}),s.setting&&e.setting.update({name:"mediabunny-audio",tooltip:f,html:c,icon:'',width:200,selector:m,onSelect:p})})}function u(){return d(this,null,function*(){const e=yield t.getM3u8State();if(!e)return s(),void a();yield Promise.all([l(e),c(e)])})}}({art:t,shim:a,option:e}),t.on("destroy",()=>{delete t.mediabunny,a.destroy()}),n}}}); diff --git a/docs/compiled/artplayer-proxy-mediabunny.mjs b/docs/compiled/artplayer-proxy-mediabunny.mjs index 2cb05293a..182167ee4 100644 --- a/docs/compiled/artplayer-proxy-mediabunny.mjs +++ b/docs/compiled/artplayer-proxy-mediabunny.mjs @@ -221,6 +221,13 @@ const readExpGolomb = (bitstream) => { const result = (1 << leadingZeroBits) - 1 + bitstream.readBits(leadingZeroBits); return result; }; +const writeExpGolomb = (bitstream, value) => { + const codeNum = value + 1; + const leadingZeroBits = Math.floor(Math.log2(codeNum)); + bitstream.writeBits(leadingZeroBits, 0); + bitstream.writeBits(1, 1); + bitstream.writeBits(leadingZeroBits, codeNum - 2 ** leadingZeroBits); +}; const readSignedExpGolomb = (bitstream) => { const codeNum = readExpGolomb(bitstream); return (codeNum & 1) === 0 ? -(codeNum >> 1) : codeNum + 1 >> 1; @@ -288,6 +295,15 @@ const MATRIX_COEFFICIENTS_MAP = { // ITU-R BT.2020-2 (non-constant luminance) }; const MATRIX_COEFFICIENTS_MAP_INVERSE = /* @__PURE__ */ invertObject(MATRIX_COEFFICIENTS_MAP); +const colorSpaceIsComplete = (colorSpace) => { + return !!colorSpace && !!colorSpace.primaries && !!colorSpace.transfer && !!colorSpace.matrix && colorSpace.fullRange !== void 0; +}; +const EMPTY_COLOR_SPACE = { + primaries: void 0, + transfer: void 0, + matrix: void 0, + fullRange: void 0 +}; const isAllowSharedBufferSource = (x) => { return x instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && x instanceof SharedArrayBuffer || ArrayBuffer.isView(x); }; @@ -492,6 +508,14 @@ const ilog = (x) => { } return ret; }; +const popcount = (value) => { + let count = 0; + while (value !== 0) { + value &= value - 1; + count++; + } + return count; +}; const ISO_639_2_REGEX = /^[a-z]{3}$/; const isIso639Dash2LanguageCode = (x) => { return ISO_639_2_REGEX.test(x); @@ -545,7 +569,7 @@ const retriedFetch = async (fetchFn, url, requestInit, getRetryDelay, shouldStop if (retryDelayInSeconds === null) { throw error; } - console.error("Retrying failed fetch. Error:", error); + Logging._error("Retrying failed fetch. Error:", error); if (!Number.isFinite(retryDelayInSeconds) || retryDelayInSeconds < 0) { throw new TypeError("Retry delay must be a non-negative finite number."); } @@ -588,19 +612,19 @@ const isChromium = () => { } return isChromiumCache = !!(typeof navigator !== "undefined" && (navigator.vendor?.includes("Google Inc") || /Chrome/.test(navigator.userAgent))); }; -let chromiumVersionCache = null; -const getChromiumVersion = () => { - if (chromiumVersionCache !== null) { - return chromiumVersionCache; +const missingWebCodecsClassMessage = (className) => { + if (typeof globalThis.isSecureContext !== "undefined" && !globalThis.isSecureContext) { + return `${className} 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.`; } - if (typeof navigator === "undefined") { - return null; + return `${className} is not available in this environment.`; +}; +const NativePromiseConstructor = (async () => { +})().constructor; +const isThenable = (value) => { + if (value instanceof NativePromiseConstructor || value instanceof Promise) { + return true; } - const match = /\bChrome\/(\d+)/.exec(navigator.userAgent); - if (!match) { - return null; - } - return chromiumVersionCache = Number(match[1]); + return typeof value?.then === "function"; }; const coalesceIndex = (a, b) => { return a !== -1 ? a : b; @@ -746,7 +770,7 @@ class EventEmitter { constructor() { this._listeners = /* @__PURE__ */ new Map(); } - /** Registers a listener for the given event. */ + /** Registers a listener for the given event. Returns a function that, when called, removes the listener again. */ on(event, listener, options) { if (!this._listeners.has(event)) { this._listeners.set(event, /* @__PURE__ */ new Set()); @@ -776,6 +800,58 @@ class EventEmitter { } } } +var LogLevel; +(function(LogLevel2) { + LogLevel2[LogLevel2["Silent"] = 0] = "Silent"; + LogLevel2[LogLevel2["Errors"] = 1] = "Errors"; + LogLevel2[LogLevel2["Warnings"] = 2] = "Warnings"; + LogLevel2[LogLevel2["Info"] = 3] = "Info"; +})(LogLevel || (LogLevel = {})); +class Logging { + constructor() { + } + /** The current log level. Defaults to {@link LogLevel.Info}. */ + static get level() { + return Logging._level; + } + static set level(value) { + if (value !== LogLevel.Silent && value !== LogLevel.Errors && value !== LogLevel.Warnings && value !== LogLevel.Info) { + throw new TypeError("Invalid log level. Use one of the values of the LogLevel enum."); + } + Logging._level = value; + } + /** @internal */ + static get _emitter() { + return Logging._emitterInstance ?? (Logging._emitterInstance = new EventEmitter()); + } + /** Registers a listener for a log event. Returns a function that, when called, removes the listener again. */ + static on(event, listener, options) { + return Logging._emitter.on(event, listener, options); + } + /** @internal */ + static _error(...args) { + Logging._emitter._emit("error", args); + if (Logging._level >= LogLevel.Errors) { + console.error(...args); + } + } + /** @internal */ + static _warn(...args) { + Logging._emitter._emit("warn", args); + if (Logging._level >= LogLevel.Warnings) { + console.warn(...args); + } + } + /** @internal */ + static _info(...args) { + Logging._emitter._emit("info", args); + if (Logging._level >= LogLevel.Info) { + console.info(...args); + } + } +} +Logging._level = LogLevel.Info; +Logging._emitterInstance = null; class RichImageData { /** Creates a new {@link RichImageData}. */ constructor(data, mimeType) { @@ -858,6 +934,16 @@ class Bitstream { } this.pos = end; } + copyBits(n, other) { + let i = 0; + for (i; i < n - 7; i += 8) { + this.writeBits(8, other.readBits(8)); + } + const leftover = n - i; + if (leftover > 0) { + this.writeBits(leftover, other.readBits(leftover)); + } + } readAlignedByte() { if (this.pos % 8 !== 0) { throw new Error("Bitstream is not byte-aligned."); @@ -900,623 +986,68 @@ const parseAacAudioSpecificConfig = (bytes) => { throw new TypeError("AAC description must be at least 2 bytes long."); } const bitstream = new Bitstream(bytes); - let objectType = bitstream.readBits(5); - if (objectType === 31) { - objectType = 32 + bitstream.readBits(6); - } - const frequencyIndex = bitstream.readBits(4); - let sampleRate = null; - if (frequencyIndex === 15) { - sampleRate = bitstream.readBits(24); - } else { - if (frequencyIndex < aacFrequencyTable.length) { - sampleRate = aacFrequencyTable[frequencyIndex]; - } - } + const objectType = readAacObjectType(bitstream); + const { frequencyIndex, sampleRate } = readAacSamplingFrequency(bitstream); const channelConfiguration = bitstream.readBits(4); let numberOfChannels = null; if (channelConfiguration >= 1 && channelConfiguration <= 7) { numberOfChannels = aacChannelMap[channelConfiguration]; } + let coreObjectType = objectType; + let psPresent = false; + let outputSampleRate = sampleRate; + if (objectType === 5 || objectType === 29) { + psPresent = objectType === 29; + outputSampleRate = readAacSamplingFrequency(bitstream).sampleRate; + coreObjectType = readAacObjectType(bitstream); + if (coreObjectType === 22) { + bitstream.skipBits(4); + } + } else { + while (bitstream.getBitsLeft() > 15) { + const searchStart = bitstream.pos; + if (bitstream.readBits(11) !== 695) { + bitstream.pos = searchStart + 1; + continue; + } + if (readAacObjectType(bitstream) === 5 && bitstream.readBits(1)) { + outputSampleRate = readAacSamplingFrequency(bitstream).sampleRate; + if (bitstream.getBitsLeft() > 11 && bitstream.readBits(11) === 1352) { + psPresent = !!bitstream.readBits(1); + } + } + break; + } + } + if (numberOfChannels !== null && numberOfChannels > 1) { + psPresent = false; + } return { objectType, + coreObjectType, frequencyIndex, - sampleRate, channelConfiguration, - numberOfChannels + outputSampleRate, + outputNumberOfChannels: psPresent && numberOfChannels === 1 ? 2 : numberOfChannels }; }; -const VIDEO_CODECS = [ - "avc", - "hevc", - "vp9", - "av1", - "vp8" -]; -const PCM_AUDIO_CODECS = [ - "pcm-s16", - // We don't prefix 'le' so we're compatible with the WebCodecs-registered PCM codec strings - "pcm-s16be", - "pcm-s24", - "pcm-s24be", - "pcm-s32", - "pcm-s32be", - "pcm-f32", - "pcm-f32be", - "pcm-f64", - "pcm-f64be", - "pcm-u8", - "pcm-s8", - "ulaw", - "alaw" -]; -const NON_PCM_AUDIO_CODECS = [ - "aac", - "opus", - "mp3", - "vorbis", - "flac", - "ac3", - "eac3" -]; -const AUDIO_CODECS = [ - ...NON_PCM_AUDIO_CODECS, - ...PCM_AUDIO_CODECS -]; -const AVC_LEVEL_TABLE = [ - { maxMacroblocks: 99, maxBitrate: 64e3, maxDpbMbs: 396, level: 10 }, - // Level 1 - { maxMacroblocks: 396, maxBitrate: 192e3, maxDpbMbs: 900, level: 11 }, - // Level 1.1 - { maxMacroblocks: 396, maxBitrate: 384e3, maxDpbMbs: 2376, level: 12 }, - // Level 1.2 - { maxMacroblocks: 396, maxBitrate: 768e3, maxDpbMbs: 2376, level: 13 }, - // Level 1.3 - { maxMacroblocks: 396, maxBitrate: 2e6, maxDpbMbs: 2376, level: 20 }, - // Level 2 - { maxMacroblocks: 792, maxBitrate: 4e6, maxDpbMbs: 4752, level: 21 }, - // Level 2.1 - { maxMacroblocks: 1620, maxBitrate: 4e6, maxDpbMbs: 8100, level: 22 }, - // Level 2.2 - { maxMacroblocks: 1620, maxBitrate: 1e7, maxDpbMbs: 8100, level: 30 }, - // Level 3 - { maxMacroblocks: 3600, maxBitrate: 14e6, maxDpbMbs: 18e3, level: 31 }, - // Level 3.1 - { maxMacroblocks: 5120, maxBitrate: 2e7, maxDpbMbs: 20480, level: 32 }, - // Level 3.2 - { maxMacroblocks: 8192, maxBitrate: 2e7, maxDpbMbs: 32768, level: 40 }, - // Level 4 - { maxMacroblocks: 8192, maxBitrate: 5e7, maxDpbMbs: 32768, level: 41 }, - // Level 4.1 - { maxMacroblocks: 8704, maxBitrate: 5e7, maxDpbMbs: 34816, level: 42 }, - // Level 4.2 - { maxMacroblocks: 22080, maxBitrate: 135e6, maxDpbMbs: 110400, level: 50 }, - // Level 5 - { maxMacroblocks: 36864, maxBitrate: 24e7, maxDpbMbs: 184320, level: 51 }, - // Level 5.1 - { maxMacroblocks: 36864, maxBitrate: 24e7, maxDpbMbs: 184320, level: 52 }, - // Level 5.2 - { maxMacroblocks: 139264, maxBitrate: 24e7, maxDpbMbs: 696320, level: 60 }, - // Level 6 - { maxMacroblocks: 139264, maxBitrate: 48e7, maxDpbMbs: 696320, level: 61 }, - // Level 6.1 - { maxMacroblocks: 139264, maxBitrate: 8e8, maxDpbMbs: 696320, level: 62 } - // Level 6.2 -]; -const VP9_LEVEL_TABLE = [ - { maxPictureSize: 36864, maxBitrate: 2e5, level: 10 }, - // Level 1 - { maxPictureSize: 73728, maxBitrate: 8e5, level: 11 }, - // Level 1.1 - { maxPictureSize: 122880, maxBitrate: 18e5, level: 20 }, - // Level 2 - { maxPictureSize: 245760, maxBitrate: 36e5, level: 21 }, - // Level 2.1 - { maxPictureSize: 552960, maxBitrate: 72e5, level: 30 }, - // Level 3 - { maxPictureSize: 983040, maxBitrate: 12e6, level: 31 }, - // Level 3.1 - { maxPictureSize: 2228224, maxBitrate: 18e6, level: 40 }, - // Level 4 - { maxPictureSize: 2228224, maxBitrate: 3e7, level: 41 }, - // Level 4.1 - { maxPictureSize: 8912896, maxBitrate: 6e7, level: 50 }, - // Level 5 - { maxPictureSize: 8912896, maxBitrate: 12e7, level: 51 }, - // Level 5.1 - { maxPictureSize: 8912896, maxBitrate: 18e7, level: 52 }, - // Level 5.2 - { maxPictureSize: 35651584, maxBitrate: 18e7, level: 60 }, - // Level 6 - { maxPictureSize: 35651584, maxBitrate: 24e7, level: 61 }, - // Level 6.1 - { maxPictureSize: 35651584, maxBitrate: 48e7, level: 62 } - // Level 6.2 -]; -const VP9_DEFAULT_SUFFIX = ".01.01.01.01.00"; -const AV1_DEFAULT_SUFFIX = ".0.110.01.01.01.0"; -const extractVideoCodecString = (trackInfo) => { - const { codec, codecDescription, colorSpace, avcCodecInfo, hevcCodecInfo, vp9CodecInfo, av1CodecInfo } = trackInfo; - if (codec === "avc") { - assert(trackInfo.avcType !== null); - if (avcCodecInfo) { - const bytes = new Uint8Array([ - avcCodecInfo.avcProfileIndication, - avcCodecInfo.profileCompatibility, - avcCodecInfo.avcLevelIndication - ]); - return `avc${trackInfo.avcType}.${bytesToHexString(bytes)}`; - } - if (!codecDescription || codecDescription.byteLength < 4) { - throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long."); - } - return `avc${trackInfo.avcType}.${bytesToHexString(codecDescription.subarray(1, 4))}`; - } else if (codec === "hevc") { - let generalProfileSpace; - let generalProfileIdc; - let compatibilityFlags; - let generalTierFlag; - let generalLevelIdc; - let constraintFlags; - if (hevcCodecInfo) { - generalProfileSpace = hevcCodecInfo.generalProfileSpace; - generalProfileIdc = hevcCodecInfo.generalProfileIdc; - compatibilityFlags = reverseBitsU32(hevcCodecInfo.generalProfileCompatibilityFlags); - generalTierFlag = hevcCodecInfo.generalTierFlag; - generalLevelIdc = hevcCodecInfo.generalLevelIdc; - constraintFlags = [...hevcCodecInfo.generalConstraintIndicatorFlags]; - } else { - if (!codecDescription || codecDescription.byteLength < 23) { - throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long."); - } - const view = toDataView(codecDescription); - const profileByte = view.getUint8(1); - generalProfileSpace = profileByte >> 6 & 3; - generalProfileIdc = profileByte & 31; - compatibilityFlags = reverseBitsU32(view.getUint32(2)); - generalTierFlag = profileByte >> 5 & 1; - generalLevelIdc = view.getUint8(12); - constraintFlags = []; - for (let i = 0; i < 6; i++) { - constraintFlags.push(view.getUint8(6 + i)); - } - } - let codecString = "hev1."; - codecString += ["", "A", "B", "C"][generalProfileSpace] + generalProfileIdc; - codecString += "."; - codecString += compatibilityFlags.toString(16).toUpperCase(); - codecString += "."; - codecString += generalTierFlag === 0 ? "L" : "H"; - codecString += generalLevelIdc; - while (constraintFlags.length > 0 && constraintFlags[constraintFlags.length - 1] === 0) { - constraintFlags.pop(); - } - if (constraintFlags.length > 0) { - codecString += "."; - codecString += constraintFlags.map((x) => x.toString(16).toUpperCase()).join("."); - } - return codecString; - } else if (codec === "vp8") { - return "vp8"; - } else if (codec === "vp9") { - if (!vp9CodecInfo) { - const pictureSize = trackInfo.width * trackInfo.height; - let level2 = last(VP9_LEVEL_TABLE).level; - for (const entry of VP9_LEVEL_TABLE) { - if (pictureSize <= entry.maxPictureSize) { - level2 = entry.level; - break; - } - } - return `vp09.00.${level2.toString().padStart(2, "0")}.08`; - } - const profile = vp9CodecInfo.profile.toString().padStart(2, "0"); - const level = vp9CodecInfo.level.toString().padStart(2, "0"); - const bitDepth = vp9CodecInfo.bitDepth.toString().padStart(2, "0"); - const chromaSubsampling = vp9CodecInfo.chromaSubsampling.toString().padStart(2, "0"); - const colourPrimaries = vp9CodecInfo.colourPrimaries.toString().padStart(2, "0"); - const transferCharacteristics = vp9CodecInfo.transferCharacteristics.toString().padStart(2, "0"); - const matrixCoefficients = vp9CodecInfo.matrixCoefficients.toString().padStart(2, "0"); - const videoFullRangeFlag = vp9CodecInfo.videoFullRangeFlag.toString().padStart(2, "0"); - let string = `vp09.${profile}.${level}.${bitDepth}.${chromaSubsampling}`; - string += `.${colourPrimaries}.${transferCharacteristics}.${matrixCoefficients}.${videoFullRangeFlag}`; - if (string.endsWith(VP9_DEFAULT_SUFFIX)) { - string = string.slice(0, -VP9_DEFAULT_SUFFIX.length); - } - return string; - } else if (codec === "av1") { - if (!av1CodecInfo) { - const pictureSize = trackInfo.width * trackInfo.height; - let level2 = last(VP9_LEVEL_TABLE).level; - for (const entry of VP9_LEVEL_TABLE) { - if (pictureSize <= entry.maxPictureSize) { - level2 = entry.level; - break; - } - } - return `av01.0.${level2.toString().padStart(2, "0")}M.08`; - } - const profile = av1CodecInfo.profile; - const level = av1CodecInfo.level.toString().padStart(2, "0"); - const tier = av1CodecInfo.tier ? "H" : "M"; - const bitDepth = av1CodecInfo.bitDepth.toString().padStart(2, "0"); - const monochrome = av1CodecInfo.monochrome ? "1" : "0"; - const chromaSubsampling = 100 * av1CodecInfo.chromaSubsamplingX + 10 * av1CodecInfo.chromaSubsamplingY + 1 * (av1CodecInfo.chromaSubsamplingX && av1CodecInfo.chromaSubsamplingY ? av1CodecInfo.chromaSamplePosition : 0); - const colorPrimaries = colorSpace?.primaries ? COLOR_PRIMARIES_MAP[colorSpace.primaries] : 1; - const transferCharacteristics = colorSpace?.transfer ? TRANSFER_CHARACTERISTICS_MAP[colorSpace.transfer] : 1; - const matrixCoefficients = colorSpace?.matrix ? MATRIX_COEFFICIENTS_MAP[colorSpace.matrix] : 1; - const videoFullRangeFlag = colorSpace?.fullRange ? 1 : 0; - let string = `av01.${profile}.${level}${tier}.${bitDepth}`; - string += `.${monochrome}.${chromaSubsampling.toString().padStart(3, "0")}`; - string += `.${colorPrimaries.toString().padStart(2, "0")}`; - string += `.${transferCharacteristics.toString().padStart(2, "0")}`; - string += `.${matrixCoefficients.toString().padStart(2, "0")}`; - string += `.${videoFullRangeFlag}`; - if (string.endsWith(AV1_DEFAULT_SUFFIX)) { - string = string.slice(0, -AV1_DEFAULT_SUFFIX.length); - } - return string; - } - throw new TypeError(`Unhandled codec '${codec}'.`); +const readAacObjectType = (bitstream) => { + const objectType = bitstream.readBits(5); + return objectType === 31 ? 32 + bitstream.readBits(6) : objectType; }; -const extractAudioCodecString = (trackInfo) => { - const { codec, codecDescription, aacCodecInfo } = trackInfo; - if (codec === "aac") { - if (!aacCodecInfo) { - throw new TypeError("AAC codec info must be provided."); - } - if (aacCodecInfo.isMpeg2) { - return "mp4a.67"; - } else { - let objectType; - if (aacCodecInfo.objectType !== null) { - objectType = aacCodecInfo.objectType; - } else { - const audioSpecificConfig = parseAacAudioSpecificConfig(codecDescription); - objectType = audioSpecificConfig.objectType; - } - return `mp4a.40.${objectType}`; - } - } else if (codec === "mp3") { - return "mp3"; - } else if (codec === "opus") { - return "opus"; - } else if (codec === "vorbis") { - return "vorbis"; - } else if (codec === "flac") { - return "flac"; - } else if (codec === "ac3") { - return "ac-3"; - } else if (codec === "eac3") { - return "ec-3"; - } else if (codec && PCM_AUDIO_CODECS.includes(codec)) { - return codec; - } - throw new TypeError(`Unhandled codec '${codec}'.`); -}; -const OPUS_SAMPLE_RATE = 48e3; -const PCM_CODEC_REGEX = /^pcm-([usf])(\d+)+(be)?$/; -const parsePcmCodec = (codec) => { - assert(PCM_AUDIO_CODECS.includes(codec)); - if (codec === "ulaw") { - return { dataType: "ulaw", sampleSize: 1, littleEndian: true, silentValue: 255 }; - } else if (codec === "alaw") { - return { dataType: "alaw", sampleSize: 1, littleEndian: true, silentValue: 213 }; - } - const match = PCM_CODEC_REGEX.exec(codec); - assert(match); - let dataType; - if (match[1] === "u") { - dataType = "unsigned"; - } else if (match[1] === "s") { - dataType = "signed"; - } else { - dataType = "float"; - } - const sampleSize = Number(match[2]) / 8; - const littleEndian = match[3] !== "be"; - const silentValue = codec === "pcm-u8" ? 2 ** 7 : 0; - return { dataType, sampleSize, littleEndian, silentValue }; -}; -const inferCodecFromCodecString = (codecString) => { - if (codecString.startsWith("avc1") || codecString.startsWith("avc3")) { - return "avc"; - } else if (codecString.startsWith("hev1") || codecString.startsWith("hvc1")) { - return "hevc"; - } else if (codecString === "vp8") { - return "vp8"; - } else if (codecString.startsWith("vp09")) { - return "vp9"; - } else if (codecString.startsWith("av01")) { - return "av1"; - } - if (codecString === "mp3" || codecString === "mp4a.69" || codecString === "mp4a.6B" || codecString === "mp4a.6b" || codecString === "mp4a.40.34") { - return "mp3"; - } else if (codecString.startsWith("mp4a.40.") || codecString === "mp4a.67") { - return "aac"; - } else if (codecString === "opus") { - return "opus"; - } else if (codecString === "vorbis") { - return "vorbis"; - } else if (codecString === "flac") { - return "flac"; - } else if (codecString === "ac-3" || codecString === "ac3") { - return "ac3"; - } else if (codecString === "ec-3" || codecString === "eac3") { - return "eac3"; - } else if (codecString === "ulaw") { - return "ulaw"; - } else if (codecString === "alaw") { - return "alaw"; - } else if (PCM_CODEC_REGEX.test(codecString)) { - return codecString; - } - if (codecString === "webvtt") { - return "webvtt"; - } - return null; -}; -const FRAME_HEADER_SIZE = 4; -const SAMPLING_RATES = [44100, 48e3, 32e3]; -const KILOBIT_RATES = [ - // lowSamplingFrequency === 0 - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - // layer = 0 - -1, - 32, - 40, - 48, - 56, - 64, - 80, - 96, - 112, - 128, - 160, - 192, - 224, - 256, - 320, - -1, - // layer 1 - -1, - 32, - 48, - 56, - 64, - 80, - 96, - 112, - 128, - 160, - 192, - 224, - 256, - 320, - 384, - -1, - // layer = 2 - -1, - 32, - 64, - 96, - 128, - 160, - 192, - 224, - 256, - 288, - 320, - 352, - 384, - 416, - 448, - -1, - // layer = 3 - // lowSamplingFrequency === 1 - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - // layer = 0 - -1, - 8, - 16, - 24, - 32, - 40, - 48, - 56, - 64, - 80, - 96, - 112, - 128, - 144, - 160, - -1, - // layer = 1 - -1, - 8, - 16, - 24, - 32, - 40, - 48, - 56, - 64, - 80, - 96, - 112, - 128, - 144, - 160, - -1, - // layer = 2 - -1, - 32, - 48, - 56, - 64, - 80, - 96, - 112, - 128, - 144, - 160, - 176, - 192, - 224, - 256, - -1 - // layer = 3 -]; -const XING = 1483304551; -const INFO = 1231971951; -const computeMp3FrameSize = (lowSamplingFrequency, layer, bitrate, sampleRate, padding) => { - if (layer === 0) { - return 0; - } else if (layer === 1) { - return Math.floor(144 * bitrate / (sampleRate << lowSamplingFrequency)) + padding; - } else if (layer === 2) { - return Math.floor(144 * bitrate / sampleRate) + padding; - } else { - return (Math.floor(12 * bitrate / sampleRate) + padding) * 4; - } -}; -const computeAverageMp3FrameSize = (lowSamplingFrequency, layer, bitrate, sampleRate) => { - if (layer === 0) { - return 0; - } else if (layer === 1) { - return 144 * bitrate / (sampleRate << lowSamplingFrequency); - } else if (layer === 2) { - return 144 * bitrate / sampleRate; - } else { - return 12 * bitrate / sampleRate * 4; - } -}; -const getXingOffset = (mpegVersionId, channel) => { - return mpegVersionId === 3 ? channel === 3 ? 21 : 36 : channel === 3 ? 13 : 21; -}; -const readMp3FrameHeader = (word, remainingBytes) => { - const firstByte = word >>> 24; - const secondByte = word >>> 16 & 255; - const thirdByte = word >>> 8 & 255; - const fourthByte = word & 255; - if (firstByte !== 255 && secondByte !== 255 && thirdByte !== 255 && fourthByte !== 255) { +const readAacSamplingFrequency = (bitstream) => { + const frequencyIndex = bitstream.readBits(4); + if (frequencyIndex === 15) { return { - header: null, - bytesAdvanced: 4 + frequencyIndex, + sampleRate: bitstream.readBits(24) }; } - if (firstByte !== 255) { - return { header: null, bytesAdvanced: 1 }; - } - if ((secondByte & 224) !== 224) { - return { header: null, bytesAdvanced: 1 }; - } - let lowSamplingFrequency = 0; - let mpeg25 = 0; - if (secondByte & 1 << 4) { - lowSamplingFrequency = secondByte & 1 << 3 ? 0 : 1; - } else { - lowSamplingFrequency = 1; - mpeg25 = 1; - } - const mpegVersionId = secondByte >> 3 & 3; - const layer = secondByte >> 1 & 3; - const bitrateIndex = thirdByte >> 4 & 15; - const frequencyIndex = (thirdByte >> 2 & 3) % 3; - const padding = thirdByte >> 1 & 1; - const channel = fourthByte >> 6 & 3; - const modeExtension = fourthByte >> 4 & 3; - const copyright = fourthByte >> 3 & 1; - const original = fourthByte >> 2 & 1; - const emphasis = fourthByte & 3; - const kilobitRate = KILOBIT_RATES[lowSamplingFrequency * 16 * 4 + layer * 16 + bitrateIndex]; - if (kilobitRate === -1) { - return { header: null, bytesAdvanced: 1 }; - } - const bitrate = kilobitRate * 1e3; - const sampleRate = SAMPLING_RATES[frequencyIndex] >> lowSamplingFrequency + mpeg25; - const frameLength = computeMp3FrameSize(lowSamplingFrequency, layer, bitrate, sampleRate, padding); - if (remainingBytes !== null && remainingBytes < frameLength) { - return { header: null, bytesAdvanced: 1 }; - } - let audioSamplesInFrame; - if (mpegVersionId === 3) { - audioSamplesInFrame = layer === 3 ? 384 : 1152; - } else { - if (layer === 3) { - audioSamplesInFrame = 384; - } else if (layer === 2) { - audioSamplesInFrame = 1152; - } else { - audioSamplesInFrame = 576; - } - } return { - header: { - totalSize: frameLength, - mpegVersionId, - lowSamplingFrequency, - layer, - bitrate, - frequencyIndex, - sampleRate, - channel, - modeExtension, - copyright, - original, - emphasis, - audioSamplesInFrame - }, - bytesAdvanced: 1 + frequencyIndex, + sampleRate: frequencyIndex < aacFrequencyTable.length ? aacFrequencyTable[frequencyIndex] : null }; }; -const decodeSynchsafe = (synchsafed) => { - let mask = 2130706432; - let unsynchsafed = 0; - while (mask !== 0) { - unsynchsafed >>= 1; - unsynchsafed |= synchsafed & mask; - mask >>= 8; - } - return unsynchsafed; -}; -var XingFlags; -(function(XingFlags2) { - XingFlags2[XingFlags2["FrameCount"] = 1] = "FrameCount"; - XingFlags2[XingFlags2["FileSize"] = 2] = "FileSize"; - XingFlags2[XingFlags2["Toc"] = 4] = "Toc"; -})(XingFlags || (XingFlags = {})); const AC3_SAMPLE_RATES = [48e3, 44100, 32e3]; const EAC3_REDUCED_SAMPLE_RATES = [24e3, 22050, 16e3]; var AvcNalUnitType; @@ -1629,6 +1160,19 @@ const removeEmulationPreventionBytes = (data) => { } return new Uint8Array(result); }; +const addEmulationPreventionBytes = (data) => { + const result = []; + let zeroCount = 0; + for (const byte of data) { + if (zeroCount === 2 && byte <= 3) { + result.push(3); + zeroCount = 0; + } + result.push(byte); + zeroCount = byte === 0 ? zeroCount + 1 : 0; + } + return new Uint8Array(result); +}; const ANNEX_B_START_CODE = new Uint8Array([0, 0, 0, 1]); const concatNalUnitsInAnnexB = (nalUnits) => { const totalLength = nalUnits.reduce((a, b) => a + ANNEX_B_START_CODE.byteLength + b.byteLength, 0); @@ -1719,10 +1263,54 @@ const extractAvcDecoderConfigurationRecord = (packetData) => { sequenceParameterSetExt: hasExtendedData ? spsExtUnits : null }; } catch (error) { - console.error("Error building AVC Decoder Configuration Record:", error); + Logging._error("Error building AVC Decoder Configuration Record:", error); return null; } }; +const serializeAvcDecoderConfigurationRecord = (record) => { + const bytes = []; + bytes.push(record.configurationVersion); + bytes.push(record.avcProfileIndication); + bytes.push(record.profileCompatibility); + bytes.push(record.avcLevelIndication); + bytes.push(252 | record.lengthSizeMinusOne & 3); + bytes.push(224 | record.sequenceParameterSets.length & 31); + for (const sps of record.sequenceParameterSets) { + const length = sps.byteLength; + bytes.push(length >> 8); + bytes.push(length & 255); + for (let i = 0; i < length; i++) { + bytes.push(sps[i]); + } + } + bytes.push(record.pictureParameterSets.length); + for (const pps of record.pictureParameterSets) { + const length = pps.byteLength; + bytes.push(length >> 8); + bytes.push(length & 255); + for (let i = 0; i < length; i++) { + bytes.push(pps[i]); + } + } + if ((record.avcProfileIndication === 100 || record.avcProfileIndication === 110 || record.avcProfileIndication === 122 || record.avcProfileIndication === 144) && record.chromaFormat !== null) { + assert(record.bitDepthLumaMinus8 !== null); + assert(record.bitDepthChromaMinus8 !== null); + assert(record.sequenceParameterSetExt !== null); + bytes.push(252 | record.chromaFormat & 3); + bytes.push(248 | record.bitDepthLumaMinus8 & 7); + bytes.push(248 | record.bitDepthChromaMinus8 & 7); + bytes.push(record.sequenceParameterSetExt.length); + for (const spsExt of record.sequenceParameterSetExt) { + const length = spsExt.byteLength; + bytes.push(length >> 8); + bytes.push(length & 255); + for (let i = 0; i < length; i++) { + bytes.push(spsExt[i]); + } + } + } + return new Uint8Array(bytes); +}; const deserializeAvcDecoderConfigurationRecord = (data) => { try { const view = toDataView(data); @@ -1780,7 +1368,7 @@ const deserializeAvcDecoderConfigurationRecord = (data) => { } return record; } catch (error) { - console.error("Error deserializing AVC Decoder Configuration Record:", error); + Logging._error("Error deserializing AVC Decoder Configuration Record:", error); return null; } }; @@ -1804,7 +1392,8 @@ const AVC_HEVC_ASPECT_RATIO_IDC_TABLE = { }; const parseAvcSps = (sps) => { try { - const bitstream = new Bitstream(removeEmulationPreventionBytes(sps)); + const emulationUnpreventedBytes = removeEmulationPreventionBytes(sps); + const bitstream = new Bitstream(emulationUnpreventedBytes); bitstream.skipBits(1); bitstream.skipBits(2); const nalUnitType = bitstream.readBits(5); @@ -1900,6 +1489,9 @@ const parseAvcSps = (sps) => { let pixelAspectRatio = { num: 1, den: 1 }; let numReorderFrames = null; let maxDecFrameBuffering = null; + let bitstreamRestrictionFlagBitOffset = null; + let bitstreamRestrictionFlag = null; + const vuiParametersFlagBitOffset = bitstream.pos; const vuiParametersPresentFlag = bitstream.readBits(1); if (vuiParametersPresentFlag) { const aspectRatioInfoPresentFlag = bitstream.readBits(1); @@ -1955,7 +1547,8 @@ const parseAvcSps = (sps) => { bitstream.skipBits(1); } bitstream.skipBits(1); - const bitstreamRestrictionFlag = bitstream.readBits(1); + bitstreamRestrictionFlagBitOffset = bitstream.pos; + bitstreamRestrictionFlag = bitstream.readBits(1); if (bitstreamRestrictionFlag) { bitstream.skipBits(1); readExpGolomb(bitstream); @@ -1984,6 +1577,7 @@ const parseAvcSps = (sps) => { } assert(maxDecFrameBuffering !== null); return { + emulationUnpreventedBytes, profileIdc, constraintFlags, levelIdc, @@ -2001,10 +1595,13 @@ const parseAvcSps = (sps) => { transferCharacteristics, fullRangeFlag, numReorderFrames, - maxDecFrameBuffering + maxDecFrameBuffering, + vuiParametersFlagBitOffset, + bitstreamRestrictionFlagBitOffset, + bitstreamRestrictionFlag }; } catch (error) { - console.error("Error parsing AVC SPS:", error); + Logging._error("Error parsing AVC SPS:", error); return null; } }; @@ -2022,6 +1619,40 @@ const skipAvcHrdParameters = (bitstream) => { bitstream.skipBits(5); bitstream.skipBits(5); }; +const addAvcBitstreamRestriction = (sps) => { + assert(sps.bitstreamRestrictionFlag !== 1); + const modifiedBytes = new Uint8Array(sps.emulationUnpreventedBytes.byteLength + 64); + const oldBitstream = new Bitstream(sps.emulationUnpreventedBytes); + const newBitstream = new Bitstream(modifiedBytes); + if (sps.bitstreamRestrictionFlag === null) { + newBitstream.copyBits(sps.vuiParametersFlagBitOffset, oldBitstream); + newBitstream.writeBits(1, 1); + newBitstream.writeBits(1, 0); + newBitstream.writeBits(1, 0); + newBitstream.writeBits(1, 0); + newBitstream.writeBits(1, 0); + newBitstream.writeBits(1, 0); + newBitstream.writeBits(1, 0); + newBitstream.writeBits(1, 0); + newBitstream.writeBits(1, 0); + } else { + assert(sps.bitstreamRestrictionFlagBitOffset !== null); + newBitstream.copyBits(sps.bitstreamRestrictionFlagBitOffset, oldBitstream); + } + newBitstream.writeBits(1, 1); + newBitstream.writeBits(1, 1); + writeExpGolomb(newBitstream, 2); + writeExpGolomb(newBitstream, 1); + writeExpGolomb(newBitstream, 16); + writeExpGolomb(newBitstream, 16); + writeExpGolomb(newBitstream, sps.numReorderFrames); + writeExpGolomb(newBitstream, sps.maxDecFrameBuffering); + newBitstream.writeBits(1, 1); + newBitstream.writeBits((8 - newBitstream.pos % 8) % 8, 0); + const byteLength = newBitstream.pos / 8; + assert(Number.isInteger(byteLength)); + return addEmulationPreventionBytes(modifiedBytes.subarray(0, byteLength)); +}; const concatHevcNalUnits = (nalUnits, decoderConfig) => { if (decoderConfig.description) { const bytes = toUint8Array(decoderConfig.description); @@ -2161,7 +1792,7 @@ const parseHevcSps = (sps) => { minSpatialSegmentationIdc }; } catch (error) { - console.error("Error parsing HEVC SPS:", error); + Logging._error("Error parsing HEVC SPS:", error); return null; } }; @@ -2278,7 +1909,7 @@ const extractHevcDecoderConfigurationRecord = (packetData) => { }; return record; } catch (error) { - console.error("Error building HEVC Decoder Configuration Record:", error); + Logging._error("Error building HEVC Decoder Configuration Record:", error); return null; } }; @@ -2520,6 +2151,78 @@ const skipSubLayerHrdParameters = (bitstream, CpbCnt, sub_pic_hrd_params_present bitstream.readBits(1); } }; +const deserializeHevcDecoderConfigurationRecord = (data) => { + try { + const view = toDataView(data); + let offset = 0; + const configurationVersion = view.getUint8(offset++); + const byte1 = view.getUint8(offset++); + const generalProfileSpace = byte1 >> 6 & 3; + const generalTierFlag = byte1 >> 5 & 1; + const generalProfileIdc = byte1 & 31; + const generalProfileCompatibilityFlags = view.getUint32(offset, false); + offset += 4; + const generalConstraintIndicatorFlags = data.subarray(offset, offset + 6); + offset += 6; + const generalLevelIdc = view.getUint8(offset++); + const minSpatialSegmentationIdc = (view.getUint8(offset++) & 15) << 8 | view.getUint8(offset++); + const parallelismType = view.getUint8(offset++) & 3; + const chromaFormatIdc = view.getUint8(offset++) & 3; + const bitDepthLumaMinus8 = view.getUint8(offset++) & 7; + const bitDepthChromaMinus8 = view.getUint8(offset++) & 7; + const avgFrameRate = view.getUint16(offset, false); + offset += 2; + const byte21 = view.getUint8(offset++); + const constantFrameRate = byte21 >> 6 & 3; + const numTemporalLayers = byte21 >> 3 & 7; + const temporalIdNested = byte21 >> 2 & 1; + const lengthSizeMinusOne = byte21 & 3; + const numOfArrays = view.getUint8(offset++); + const arrays = []; + for (let i = 0; i < numOfArrays; i++) { + const arrByte = view.getUint8(offset++); + const arrayCompleteness = arrByte >> 7 & 1; + const nalUnitType = arrByte & 63; + const numNalus = view.getUint16(offset, false); + offset += 2; + const nalUnits = []; + for (let j = 0; j < numNalus; j++) { + const nalUnitLength = view.getUint16(offset, false); + offset += 2; + nalUnits.push(data.subarray(offset, offset + nalUnitLength)); + offset += nalUnitLength; + } + arrays.push({ + arrayCompleteness, + nalUnitType, + nalUnits + }); + } + return { + configurationVersion, + generalProfileSpace, + generalTierFlag, + generalProfileIdc, + generalProfileCompatibilityFlags, + generalConstraintIndicatorFlags, + generalLevelIdc, + minSpatialSegmentationIdc, + parallelismType, + chromaFormatIdc, + bitDepthLumaMinus8, + bitDepthChromaMinus8, + avgFrameRate, + constantFrameRate, + numTemporalLayers, + temporalIdNested, + lengthSizeMinusOne, + arrays + }; + } catch (error) { + Logging._error("Error deserializing HEVC Decoder Configuration Record:", error); + return null; + } +}; var HevcNaluOrderState; (function(HevcNaluOrderState2) { HevcNaluOrderState2[HevcNaluOrderState2["audAllowed"] = 0] = "audAllowed"; @@ -2592,6 +2295,20 @@ const sanitizeHevcPacketForChromium = (packetData, decoderConfig) => { } return concatHevcNalUnits(filteredNalUnits, decoderConfig); }; +const VP9_COLOR_SPACE_TABLE = { + 1: { colourPrimaries: 5, transferCharacteristics: 6, matrixCoefficients: 5 }, + // CS_BT_601 + 2: { colourPrimaries: 1, transferCharacteristics: 1, matrixCoefficients: 1 }, + // CS_BT_709 + 3: { colourPrimaries: 6, transferCharacteristics: 6, matrixCoefficients: 6 }, + // CS_SMPTE_170 + 4: { colourPrimaries: 7, transferCharacteristics: 7, matrixCoefficients: 7 }, + // CS_SMPTE_240 + 5: { colourPrimaries: 9, transferCharacteristics: 14, matrixCoefficients: 9 }, + // CS_BT_2020 + 7: { colourPrimaries: 1, transferCharacteristics: 13, matrixCoefficients: 0 } + // CS_RGB (sRGB) +}; const extractVp9CodecInfoFromPacket = (packet) => { const bitstream = new Bitstream(packet); const frameMarker = bitstream.readBits(2); @@ -2652,9 +2369,10 @@ const extractVp9CodecInfoFromPacket = (packet) => { break; } } - const matrixCoefficients = colorSpace === 7 ? 0 : colorSpace === 2 ? 1 : colorSpace === 1 ? 6 : 2; - const colourPrimaries = colorSpace === 2 ? 1 : colorSpace === 1 ? 6 : 2; - const transferCharacteristics = colorSpace === 2 ? 1 : colorSpace === 1 ? 6 : 2; + const colorSpaceValues = VP9_COLOR_SPACE_TABLE[colorSpace]; + const colourPrimaries = colorSpaceValues?.colourPrimaries ?? 2; + const transferCharacteristics = colorSpaceValues?.transferCharacteristics ?? 2; + const matrixCoefficients = colorSpaceValues?.matrixCoefficients ?? 2; return { profile, level, @@ -2666,13 +2384,16 @@ const extractVp9CodecInfoFromPacket = (packet) => { matrixCoefficients }; }; +const vp9CodecInfoHasColorInfo = (info) => { + return info.colourPrimaries !== 2 || info.transferCharacteristics !== 2 || info.matrixCoefficients !== 2; +}; const iterateAv1PacketObus = function* (packet) { const bitstream = new Bitstream(packet); const readLeb128 = () => { let value = 0; for (let i = 0; i < 8; i++) { const byte = bitstream.readAlignedByte(); - value |= (byte & 127) << i * 7; + value += (byte & 127) * 2 ** (i * 7); if (!(byte & 128)) { break; } @@ -2680,7 +2401,7 @@ const iterateAv1PacketObus = function* (packet) { return null; } } - if (value >= 2 ** 32 - 1) { + if (value > 2 ** 32 - 1) { return null; } return value; @@ -2727,21 +2448,29 @@ const extractAv1CodecInfoFromPacket = (packet) => { seqLevel = bitstream.readBits(5); } else { const timingInfoPresentFlag = bitstream.readBits(1); + let decoderModelInfoPresentFlag = 0; if (timingInfoPresentFlag) { bitstream.skipBits(32); bitstream.skipBits(32); const equalPictureInterval = bitstream.readBits(1); if (equalPictureInterval) { - return null; + let leadingZeros = 0; + while (leadingZeros < 32 && !bitstream.readBits(1)) { + leadingZeros++; + } + if (leadingZeros < 32) { + bitstream.skipBits(leadingZeros); + } + } + decoderModelInfoPresentFlag = bitstream.readBits(1); + if (decoderModelInfoPresentFlag) { + bufferDelayLengthMinus1 = bitstream.readBits(5); + bitstream.skipBits(32); + bitstream.skipBits(5); + bitstream.skipBits(5); } } - const decoderModelInfoPresentFlag = bitstream.readBits(1); - if (decoderModelInfoPresentFlag) { - bufferDelayLengthMinus1 = bitstream.readBits(5); - bitstream.skipBits(32); - bitstream.skipBits(5); - bitstream.skipBits(5); - } + const initialDisplayDelayPresentFlag = bitstream.readBits(1); const operatingPointsCntMinus1 = bitstream.readBits(5); for (let i = 0; i <= operatingPointsCntMinus1; i++) { bitstream.skipBits(12); @@ -2764,9 +2493,11 @@ const extractAv1CodecInfoFromPacket = (packet) => { bitstream.skipBits(1); } } - const initialDisplayDelayPresentFlag = bitstream.readBits(1); if (initialDisplayDelayPresentFlag) { - bitstream.skipBits(4); + const initialDisplayDelayPresentForThisOp = bitstream.readBits(1); + if (initialDisplayDelayPresentForThisOp) { + bitstream.skipBits(4); + } } } } @@ -2831,10 +2562,27 @@ const extractAv1CodecInfoFromPacket = (packet) => { if (seqProfile !== 1) { monochrome = bitstream.readBits(1); } + let colourPrimaries = 2; + let transferCharacteristics = 2; + let matrixCoefficients = 2; + const colorDescriptionPresentFlag = bitstream.readBits(1); + if (colorDescriptionPresentFlag) { + colourPrimaries = bitstream.readBits(8); + transferCharacteristics = bitstream.readBits(8); + matrixCoefficients = bitstream.readBits(8); + } + let videoFullRangeFlag = 0; let chromaSubsamplingX = 1; let chromaSubsamplingY = 1; let chromaSamplePosition = 0; - if (!monochrome) { + if (monochrome) { + videoFullRangeFlag = bitstream.readBits(1); + } else if (colourPrimaries === 1 && transferCharacteristics === 13 && matrixCoefficients === 0) { + videoFullRangeFlag = 1; + chromaSubsamplingX = 0; + chromaSubsamplingY = 0; + } else { + videoFullRangeFlag = bitstream.readBits(1); if (seqProfile === 0) { chromaSubsamplingX = 1; chromaSubsamplingY = 1; @@ -2844,9 +2592,10 @@ const extractAv1CodecInfoFromPacket = (packet) => { } else { if (bitDepth === 12) { chromaSubsamplingX = bitstream.readBits(1); - if (chromaSubsamplingX) { - chromaSubsamplingY = bitstream.readBits(1); - } + chromaSubsamplingY = chromaSubsamplingX ? bitstream.readBits(1) : 0; + } else { + chromaSubsamplingX = 1; + chromaSubsamplingY = 0; } } if (chromaSubsamplingX && chromaSubsamplingY) { @@ -2861,11 +2610,39 @@ const extractAv1CodecInfoFromPacket = (packet) => { monochrome, chromaSubsamplingX, chromaSubsamplingY, - chromaSamplePosition + chromaSamplePosition, + videoFullRangeFlag, + colourPrimaries, + transferCharacteristics, + matrixCoefficients }; } return null; }; +const av1CodecInfoHasColorInfo = (info) => { + return info.colourPrimaries !== 2 || info.transferCharacteristics !== 2 || info.matrixCoefficients !== 2; +}; +const extractProresCodecInfoFromPacket = (packet) => { + const frameHeaderStart = 8; + if (packet.length < frameHeaderStart + 28) { + return null; + } + const view = toDataView(packet); + if (view.getUint32(4) !== 1768124518) { + return null; + } + const headerSize = view.getUint16(frameHeaderStart); + if (headerSize < 28) { + return null; + } + return { + fullRange: false, + // ProRes is always limited range + colourPrimaries: view.getUint8(frameHeaderStart + 14), + transferCharacteristics: view.getUint8(frameHeaderStart + 15), + matrixCoefficients: view.getUint8(frameHeaderStart + 16) + }; +}; const parseOpusIdentificationHeader = (bytes) => { const view = toDataView(bytes); const outputChannelCount = view.getUint8(9); @@ -2922,8 +2699,17 @@ const OPUS_FRAME_DURATION_TABLE = [ ]; const parseOpusTocByte = (packet) => { const config = packet[0] >> 3; + const code = packet[0] & 3; + let frameCount; + if (code === 0) { + frameCount = 1; + } else if (code === 1 || code === 2) { + frameCount = 2; + } else { + frameCount = packet[1] & 63; + } return { - durationInSamples: OPUS_FRAME_DURATION_TABLE[config] + durationInSamples: OPUS_FRAME_DURATION_TABLE[config] * frameCount }; }; const parseModesFromVorbisSetupPacket = (setupHeader) => { @@ -3005,7 +2791,7 @@ const determineVideoPacketType = (codec, decoderConfig, packetData) => { if (type === AvcNalUnitType.IDR) { return "key"; } - if (type === AvcNalUnitType.SEI && (!isChromium() || getChromiumVersion() >= 144)) { + if (type === AvcNalUnitType.SEI && !isChromium()) { const nalUnit = packetData.subarray(loc.offset, loc.offset + loc.length); const bytes = removeEmulationPreventionBytes(nalUnit); let pos = 1; @@ -3102,6 +2888,9 @@ const determineVideoPacketType = (codec, decoderConfig, packetData) => { } return null; } + case "prores": { + return "key"; + } default: { assertNever(codec); assert(false); @@ -3140,7 +2929,13 @@ const readVorbisComments = (bytes, metadataTags) => { const key = string.slice(0, separatorIndex).toUpperCase(); const value = string.slice(separatorIndex + 1); metadataTags.raw ?? (metadataTags.raw = {}); - (_b = metadataTags.raw)[key] ?? (_b[key] = value); + if (Array.isArray(metadataTags.raw[key])) { + metadataTags.raw[key] = [...metadataTags.raw[key], value]; + } else if (typeof metadataTags.raw[key] === "string") { + metadataTags.raw[key] = [metadataTags.raw[key], value]; + } else { + (_b = metadataTags.raw)[key] ?? (_b[key] = value); + } switch (key) { case "TITLE": { @@ -3533,6 +3328,1056 @@ const getEac3ChannelCount = (config) => { } return channels; }; +const DTS_EXSS_SYNC_WORD = 1683496997; +const DTS_CORE_FRAME_HEADER_SIZE = 18; +const DTS_EXSS_HEADER_PREFIX_SIZE = 10; +const DTS_EXSS_MAX_HEADER_SIZE = 4096; +const DTS_PCM_BLOCK_SAMPLES = 32; +const DTS_SPECIFIC_BOX_SIZE = 20; +const DTS_SUBBAND_SAMPLES = 8; +const DTS_CORE_SAMPLE_RATES = [ + 0, + 8e3, + 16e3, + 32e3, + 0, + 0, + 11025, + 22050, + 44100, + 0, + 0, + 12e3, + 24e3, + 48e3, + 96e3, + 192e3 +]; +const DTS_CORE_BIT_RATES = [ + 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 +]; +const DTS_PCM_RESOLUTIONS = [16, 16, 20, 20, 0, 24, 24, 0]; +const DTS_AMODE_CHANNEL_COUNTS = [1, 2, 2, 2, 2, 3, 3, 4, 4, 5, 6, 6, 6, 7, 8, 8]; +const DTS_AMODE_CHANNEL_LAYOUTS = [ + 1, + 2, + 2, + 2, + 2, + 3, + 18, + 19, + 6, + 7, + 518, + 323, + 83, + 519, + 582, + 535 +]; +const DTS_CHANNEL_LAYOUT_LFE1 = 8; +const DTS_CHANNEL_LAYOUT_PAIR_MASK = 44646; +const DTS_EXSS_REF_CLOCKS = [32e3, 44100, 48e3, 0]; +const DTS_EXSS_SAMPLE_RATES = [ + 8e3, + 16e3, + 32e3, + 64e3, + 128e3, + 22050, + 44100, + 88200, + 176400, + 352800, + 12e3, + 24e3, + 48e3, + 96e3, + 192e3, + 384e3 +]; +const DTS_SPECIFIC_BOX_FRAME_DURATIONS = [512, 1024, 2048, 4096]; +const parseDtsFrame = (data) => { + const core = parseDtsCoreFrameHeader(data); + const view = toDataView(data); + let offset = core ? Math.ceil(core.frameSize / 4) * 4 : 0; + let firstExss = null; + while (offset + 4 <= data.length && view.getUint32(offset) === DTS_EXSS_SYNC_WORD) { + const exss = parseDtsExssHeader(data.subarray(offset)); + if (!exss) { + break; + } + firstExss ?? (firstExss = exss); + offset += exss.frameSize; + } + if (core) { + return { + frameSize: firstExss ? offset : core.frameSize, + sampleRate: core.sampleRate, + numberOfChannels: core.numberOfChannels, + sampleCount: core.sampleCount, + channelLayout: core.channelLayout, + pcmResolution: core.pcmResolution, + bitRate: core.bitRate, + core, + hasExtensions: firstExss !== null + }; + } + if (!firstExss?.asset) { + return null; + } + const { asset } = firstExss; + return { + frameSize: offset, + sampleRate: asset.sampleRate, + numberOfChannels: asset.numberOfChannels, + sampleCount: asset.sampleCount, + channelLayout: asset.channelLayout, + pcmResolution: asset.pcmResolution, + bitRate: 0, + core: null, + hasExtensions: true + }; +}; +const extractDtsFourCcFromPacket = (data) => { + const frameInfo = parseDtsFrame(data); + if (!frameInfo?.core) { + return null; + } + return frameInfo.hasExtensions ? "dtsh" : "dtsc"; +}; +const parseDtsCoreFrameHeader = (data) => { + if (data.length < DTS_CORE_FRAME_HEADER_SIZE) { + return null; + } + if (data[0] !== 127 || data[1] !== 254 || data[2] !== 128 || data[3] !== 1) { + return null; + } + const bitstream = new Bitstream(data); + bitstream.skipBits(32); + bitstream.skipBits(1); + if (bitstream.readBits(5) !== DTS_PCM_BLOCK_SAMPLES - 1) { + return null; + } + const cpf = bitstream.readBits(1); + const npcmblocks = bitstream.readBits(7) + 1; + if (npcmblocks % DTS_SUBBAND_SAMPLES !== 0) { + return null; + } + const frameSize = bitstream.readBits(14) + 1; + if (frameSize < 96) { + return null; + } + const amode = bitstream.readBits(6); + if (amode >= DTS_AMODE_CHANNEL_COUNTS.length) { + return null; + } + const sampleRate = DTS_CORE_SAMPLE_RATES[bitstream.readBits(4)]; + if (sampleRate === 0) { + return null; + } + const bitRate = DTS_CORE_BIT_RATES[bitstream.readBits(5)]; + if (bitstream.readBits(1) !== 0) { + return null; + } + bitstream.skipBits(1 + 1 + 1 + 1); + bitstream.skipBits(3 + 1 + 1); + const lff = bitstream.readBits(2); + if (lff === 3) { + return null; + } + bitstream.skipBits(1); + if (cpf) { + bitstream.skipBits(16); + } + bitstream.skipBits(1 + 4 + 2); + const pcmResolution = DTS_PCM_RESOLUTIONS[bitstream.readBits(3)]; + if (pcmResolution === 0) { + return null; + } + const lfePresent = lff !== 0; + return { + frameSize, + sampleRate, + numberOfChannels: DTS_AMODE_CHANNEL_COUNTS[amode] + (lfePresent ? 1 : 0), + sampleCount: npcmblocks * DTS_PCM_BLOCK_SAMPLES, + channelLayout: DTS_AMODE_CHANNEL_LAYOUTS[amode] | (lfePresent ? DTS_CHANNEL_LAYOUT_LFE1 : 0), + amode, + lfePresent, + bitRate, + pcmResolution + }; +}; +const parseDtsExssHeader = (data) => { + if (data.length < DTS_EXSS_HEADER_PREFIX_SIZE) { + return null; + } + if (data[0] !== 100 || data[1] !== 88 || data[2] !== 32 || data[3] !== 37) { + return null; + } + const bitstream = new Bitstream(data); + bitstream.skipBits(32); + bitstream.skipBits(8); + const extSsIndex = bitstream.readBits(2); + const wideHeader = bitstream.readBits(1); + const headerSizeBits = 8 + 4 * wideHeader; + const frameSizeBits = 16 + 4 * wideHeader; + bitstream.skipBits(headerSizeBits); + const frameSize = bitstream.readBits(frameSizeBits) + 1; + const incomplete = { frameSize, asset: null }; + if (!bitstream.readBits(1)) { + return incomplete; + } + const refClock = DTS_EXSS_REF_CLOCKS[bitstream.readBits(2)]; + const frameDurationCycles = 512 * (bitstream.readBits(3) + 1); + if (bitstream.readBits(1)) { + bitstream.skipBits(32 + 4); + } + const numAudioPresentations = bitstream.readBits(3) + 1; + const numAssets = bitstream.readBits(3) + 1; + const activeExssMasks = []; + for (let i = 0; i < numAudioPresentations; i++) { + activeExssMasks.push(bitstream.readBits(extSsIndex + 1)); + } + for (const mask of activeExssMasks) { + bitstream.skipBits(8 * popcount(mask)); + } + if (bitstream.readBits(1)) { + bitstream.skipBits(2); + const spkrMaskBits = bitstream.readBits(2) + 1 << 2; + const numMixOutConfigs = bitstream.readBits(2) + 1; + bitstream.skipBits(numMixOutConfigs * spkrMaskBits); + } + for (let i = 0; i < numAssets; i++) { + bitstream.skipBits(frameSizeBits); + } + bitstream.skipBits(9); + bitstream.skipBits(3); + if (bitstream.readBits(1)) { + bitstream.skipBits(4); + } + if (bitstream.readBits(1)) { + bitstream.skipBits(24); + } + if (bitstream.readBits(1)) { + bitstream.skipBits(8 * (bitstream.readBits(10) + 1)); + } + const pcmResolution = bitstream.readBits(5) + 1; + const sampleRate = DTS_EXSS_SAMPLE_RATES[bitstream.readBits(4)]; + const numberOfChannels = bitstream.readBits(8) + 1; + let channelLayout = 0; + if (bitstream.readBits(1)) { + if (numberOfChannels > 2) { + bitstream.skipBits(1); + } + if (numberOfChannels > 6) { + bitstream.skipBits(1); + } + if (bitstream.readBits(1)) { + const spkrMaskBits = bitstream.readBits(2) + 1 << 2; + channelLayout = bitstream.readBits(spkrMaskBits); + } + } + if (refClock === 0 || bitstream.getBitsLeft() < 0) { + return incomplete; + } + return { + frameSize, + asset: { + sampleRate, + numberOfChannels, + sampleCount: Math.round(frameDurationCycles * sampleRate / refClock), + channelLayout, + pcmResolution + } + }; +}; +const parseDtsSpecificBox = (data) => { + if (data.length < DTS_SPECIFIC_BOX_SIZE) { + return null; + } + const view = toDataView(data); + const sampleRate = view.getUint32(0); + if (sampleRate === 0) { + return null; + } + const bitstream = new Bitstream(data); + bitstream.seekToByte(13); + const frameDuration = bitstream.readBits(2); + bitstream.skipBits(5); + const coreLfePresent = bitstream.readBits(1); + const coreLayout = bitstream.readBits(6); + bitstream.skipBits(14); + bitstream.skipBits(1); + bitstream.skipBits(3); + const channelLayout = bitstream.readBits(16); + let numberOfChannels = null; + if (channelLayout !== 0) { + numberOfChannels = getDtsChannelCount(channelLayout); + } else if (coreLayout < DTS_AMODE_CHANNEL_COUNTS.length) { + numberOfChannels = DTS_AMODE_CHANNEL_COUNTS[coreLayout] + coreLfePresent; + } + return { + sampleRate, + maxBitrate: view.getUint32(4), + avgBitrate: view.getUint32(8), + pcmSampleDepth: data[12], + sampleCount: DTS_SPECIFIC_BOX_FRAME_DURATIONS[frameDuration], + channelLayout, + numberOfChannels + }; +}; +const getDtsChannelCount = (channelLayout) => { + return popcount(channelLayout) + popcount(channelLayout & DTS_CHANNEL_LAYOUT_PAIR_MASK); +}; +const VIDEO_CODECS = [ + "avc", + "hevc", + "vp9", + "av1", + "vp8", + "prores" +]; +const PCM_AUDIO_CODECS = [ + "pcm-s16", + // We don't prefix 'le' so we're compatible with the WebCodecs-registered PCM codec strings + "pcm-s16be", + "pcm-s24", + "pcm-s24be", + "pcm-s32", + "pcm-s32be", + "pcm-f32", + "pcm-f32be", + "pcm-f64", + "pcm-f64be", + "pcm-u8", + "pcm-s8", + "ulaw", + "alaw" +]; +const NON_PCM_AUDIO_CODECS = [ + "aac", + "opus", + "mp3", + "vorbis", + "flac", + "ac3", + "eac3", + "dts" +]; +const AUDIO_CODECS = [ + ...NON_PCM_AUDIO_CODECS, + ...PCM_AUDIO_CODECS +]; +const AVC_LEVEL_TABLE = [ + { maxMacroblocks: 99, maxBitrate: 64e3, maxDpbMbs: 396, level: 10 }, + // Level 1 + { maxMacroblocks: 396, maxBitrate: 192e3, maxDpbMbs: 900, level: 11 }, + // Level 1.1 + { maxMacroblocks: 396, maxBitrate: 384e3, maxDpbMbs: 2376, level: 12 }, + // Level 1.2 + { maxMacroblocks: 396, maxBitrate: 768e3, maxDpbMbs: 2376, level: 13 }, + // Level 1.3 + { maxMacroblocks: 396, maxBitrate: 2e6, maxDpbMbs: 2376, level: 20 }, + // Level 2 + { maxMacroblocks: 792, maxBitrate: 4e6, maxDpbMbs: 4752, level: 21 }, + // Level 2.1 + { maxMacroblocks: 1620, maxBitrate: 4e6, maxDpbMbs: 8100, level: 22 }, + // Level 2.2 + { maxMacroblocks: 1620, maxBitrate: 1e7, maxDpbMbs: 8100, level: 30 }, + // Level 3 + { maxMacroblocks: 3600, maxBitrate: 14e6, maxDpbMbs: 18e3, level: 31 }, + // Level 3.1 + { maxMacroblocks: 5120, maxBitrate: 2e7, maxDpbMbs: 20480, level: 32 }, + // Level 3.2 + { maxMacroblocks: 8192, maxBitrate: 2e7, maxDpbMbs: 32768, level: 40 }, + // Level 4 + { maxMacroblocks: 8192, maxBitrate: 5e7, maxDpbMbs: 32768, level: 41 }, + // Level 4.1 + { maxMacroblocks: 8704, maxBitrate: 5e7, maxDpbMbs: 34816, level: 42 }, + // Level 4.2 + { maxMacroblocks: 22080, maxBitrate: 135e6, maxDpbMbs: 110400, level: 50 }, + // Level 5 + { maxMacroblocks: 36864, maxBitrate: 24e7, maxDpbMbs: 184320, level: 51 }, + // Level 5.1 + { maxMacroblocks: 36864, maxBitrate: 24e7, maxDpbMbs: 184320, level: 52 }, + // Level 5.2 + { maxMacroblocks: 139264, maxBitrate: 24e7, maxDpbMbs: 696320, level: 60 }, + // Level 6 + { maxMacroblocks: 139264, maxBitrate: 48e7, maxDpbMbs: 696320, level: 61 }, + // Level 6.1 + { maxMacroblocks: 139264, maxBitrate: 8e8, maxDpbMbs: 696320, level: 62 } + // Level 6.2 +]; +const VP9_LEVEL_TABLE = [ + { maxPictureSize: 36864, maxBitrate: 2e5, level: 10 }, + // Level 1 + { maxPictureSize: 73728, maxBitrate: 8e5, level: 11 }, + // Level 1.1 + { maxPictureSize: 122880, maxBitrate: 18e5, level: 20 }, + // Level 2 + { maxPictureSize: 245760, maxBitrate: 36e5, level: 21 }, + // Level 2.1 + { maxPictureSize: 552960, maxBitrate: 72e5, level: 30 }, + // Level 3 + { maxPictureSize: 983040, maxBitrate: 12e6, level: 31 }, + // Level 3.1 + { maxPictureSize: 2228224, maxBitrate: 18e6, level: 40 }, + // Level 4 + { maxPictureSize: 2228224, maxBitrate: 3e7, level: 41 }, + // Level 4.1 + { maxPictureSize: 8912896, maxBitrate: 6e7, level: 50 }, + // Level 5 + { maxPictureSize: 8912896, maxBitrate: 12e7, level: 51 }, + // Level 5.1 + { maxPictureSize: 8912896, maxBitrate: 18e7, level: 52 }, + // Level 5.2 + { maxPictureSize: 35651584, maxBitrate: 18e7, level: 60 }, + // Level 6 + { maxPictureSize: 35651584, maxBitrate: 24e7, level: 61 }, + // Level 6.1 + { maxPictureSize: 35651584, maxBitrate: 48e7, level: 62 } + // Level 6.2 +]; +const VP9_DEFAULT_SUFFIX = ".01.01.01.01.00"; +const AV1_DEFAULT_SUFFIX = ".0.110.01.01.01.0"; +const PRORES_FOURCCS = [ + "ap4x", + // ProRes 4444 XQ + "ap4h", + // ProRes 4444 + "apch", + // ProRes 422 High Quality + "apcn", + // ProRes 422 Standard Definition + "apcs", + // ProRes 422 LT + "apco" + // ProRes 422 Proxy +]; +const DTS_FOURCCS = [ + "dtsc", + // DTS core + "dtsh", + // DTS-HD, core plus extension substreams + "dtsl", + // DTS-HD Lossless, no core + "dtse" + // DTS Express +]; +const extractVideoCodecString = (trackInfo) => { + const { codec, codecDescription, colorSpace, avcCodecInfo, hevcCodecInfo, vp9CodecInfo, av1CodecInfo, proresFormat } = trackInfo; + if (codec === "avc") { + assert(trackInfo.avcType !== null); + if (avcCodecInfo) { + const bytes = new Uint8Array([ + avcCodecInfo.avcProfileIndication, + avcCodecInfo.profileCompatibility, + avcCodecInfo.avcLevelIndication + ]); + return `avc${trackInfo.avcType}.${bytesToHexString(bytes)}`; + } + if (!codecDescription || codecDescription.byteLength < 4) { + throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long."); + } + return `avc${trackInfo.avcType}.${bytesToHexString(codecDescription.subarray(1, 4))}`; + } else if (codec === "hevc") { + let generalProfileSpace; + let generalProfileIdc; + let compatibilityFlags; + let generalTierFlag; + let generalLevelIdc; + let constraintFlags; + if (hevcCodecInfo) { + generalProfileSpace = hevcCodecInfo.generalProfileSpace; + generalProfileIdc = hevcCodecInfo.generalProfileIdc; + compatibilityFlags = reverseBitsU32(hevcCodecInfo.generalProfileCompatibilityFlags); + generalTierFlag = hevcCodecInfo.generalTierFlag; + generalLevelIdc = hevcCodecInfo.generalLevelIdc; + constraintFlags = [...hevcCodecInfo.generalConstraintIndicatorFlags]; + } else { + if (!codecDescription || codecDescription.byteLength < 23) { + throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long."); + } + const view = toDataView(codecDescription); + const profileByte = view.getUint8(1); + generalProfileSpace = profileByte >> 6 & 3; + generalProfileIdc = profileByte & 31; + compatibilityFlags = reverseBitsU32(view.getUint32(2)); + generalTierFlag = profileByte >> 5 & 1; + generalLevelIdc = view.getUint8(12); + constraintFlags = []; + for (let i = 0; i < 6; i++) { + constraintFlags.push(view.getUint8(6 + i)); + } + } + let codecString = "hev1."; + codecString += ["", "A", "B", "C"][generalProfileSpace] + generalProfileIdc; + codecString += "."; + codecString += compatibilityFlags.toString(16).toUpperCase(); + codecString += "."; + codecString += generalTierFlag === 0 ? "L" : "H"; + codecString += generalLevelIdc; + while (constraintFlags.length > 0 && constraintFlags[constraintFlags.length - 1] === 0) { + constraintFlags.pop(); + } + if (constraintFlags.length > 0) { + codecString += "."; + codecString += constraintFlags.map((x) => x.toString(16).toUpperCase()).join("."); + } + return codecString; + } else if (codec === "vp8") { + return "vp8"; + } else if (codec === "vp9") { + if (!vp9CodecInfo) { + const pictureSize = trackInfo.width * trackInfo.height; + let level2 = last(VP9_LEVEL_TABLE).level; + for (const entry of VP9_LEVEL_TABLE) { + if (pictureSize <= entry.maxPictureSize) { + level2 = entry.level; + break; + } + } + return `vp09.00.${level2.toString().padStart(2, "0")}.08`; + } + const profile = vp9CodecInfo.profile.toString().padStart(2, "0"); + const level = vp9CodecInfo.level.toString().padStart(2, "0"); + const bitDepth = vp9CodecInfo.bitDepth.toString().padStart(2, "0"); + const chromaSubsampling = vp9CodecInfo.chromaSubsampling.toString().padStart(2, "0"); + const colourPrimaries = vp9CodecInfo.colourPrimaries.toString().padStart(2, "0"); + const transferCharacteristics = vp9CodecInfo.transferCharacteristics.toString().padStart(2, "0"); + const matrixCoefficients = vp9CodecInfo.matrixCoefficients.toString().padStart(2, "0"); + const videoFullRangeFlag = vp9CodecInfo.videoFullRangeFlag.toString().padStart(2, "0"); + let string = `vp09.${profile}.${level}.${bitDepth}.${chromaSubsampling}`; + string += `.${colourPrimaries}.${transferCharacteristics}.${matrixCoefficients}.${videoFullRangeFlag}`; + if (string.endsWith(VP9_DEFAULT_SUFFIX)) { + string = string.slice(0, -VP9_DEFAULT_SUFFIX.length); + } + return string; + } else if (codec === "av1") { + if (!av1CodecInfo) { + const pictureSize = trackInfo.width * trackInfo.height; + let level2 = last(VP9_LEVEL_TABLE).level; + for (const entry of VP9_LEVEL_TABLE) { + if (pictureSize <= entry.maxPictureSize) { + level2 = entry.level; + break; + } + } + return `av01.0.${level2.toString().padStart(2, "0")}M.08`; + } + const profile = av1CodecInfo.profile; + const level = av1CodecInfo.level.toString().padStart(2, "0"); + const tier = av1CodecInfo.tier ? "H" : "M"; + const bitDepth = av1CodecInfo.bitDepth.toString().padStart(2, "0"); + const monochrome = av1CodecInfo.monochrome ? "1" : "0"; + const chromaSubsampling = 100 * av1CodecInfo.chromaSubsamplingX + 10 * av1CodecInfo.chromaSubsamplingY + 1 * (av1CodecInfo.chromaSubsamplingX && av1CodecInfo.chromaSubsamplingY ? av1CodecInfo.chromaSamplePosition : 0); + const colorPrimaries = colorSpace?.primaries ? COLOR_PRIMARIES_MAP[colorSpace.primaries] : 1; + const transferCharacteristics = colorSpace?.transfer ? TRANSFER_CHARACTERISTICS_MAP[colorSpace.transfer] : 1; + const matrixCoefficients = colorSpace?.matrix ? MATRIX_COEFFICIENTS_MAP[colorSpace.matrix] : 1; + const videoFullRangeFlag = colorSpace?.fullRange ? 1 : 0; + let string = `av01.${profile}.${level}${tier}.${bitDepth}`; + string += `.${monochrome}.${chromaSubsampling.toString().padStart(3, "0")}`; + string += `.${colorPrimaries.toString().padStart(2, "0")}`; + string += `.${transferCharacteristics.toString().padStart(2, "0")}`; + string += `.${matrixCoefficients.toString().padStart(2, "0")}`; + string += `.${videoFullRangeFlag}`; + if (string.endsWith(AV1_DEFAULT_SUFFIX)) { + string = string.slice(0, -AV1_DEFAULT_SUFFIX.length); + } + return string; + } else if (codec === "prores") { + return proresFormat ?? "apch"; + } else if (codec !== null) { + assertNever(codec); + } + throw new TypeError(`Unhandled codec '${codec}'.`); +}; +const extractColorSpace = (info) => { + switch (info.codec) { + case "avc": + { + let spsData = info.avcCodecInfo?.sequenceParameterSets[0]; + if (!spsData && info.codecDescription) { + spsData = deserializeAvcDecoderConfigurationRecord(info.codecDescription)?.sequenceParameterSets[0]; + } + if (spsData) { + const spsInfo = parseAvcSps(spsData); + if (spsInfo) { + return { + primaries: COLOR_PRIMARIES_MAP_INVERSE[spsInfo.colourPrimaries], + transfer: TRANSFER_CHARACTERISTICS_MAP_INVERSE[spsInfo.transferCharacteristics], + matrix: MATRIX_COEFFICIENTS_MAP_INVERSE[spsInfo.matrixCoefficients], + fullRange: !!spsInfo.fullRangeFlag + }; + } + } + } + break; + case "hevc": + { + let spsData = info.hevcCodecInfo?.arrays.find((x) => x.nalUnitType === HevcNalUnitType.SPS_NUT)?.nalUnits[0]; + if (!spsData && info.codecDescription) { + spsData = deserializeHevcDecoderConfigurationRecord(info.codecDescription)?.arrays.find((x) => x.nalUnitType === HevcNalUnitType.SPS_NUT)?.nalUnits[0]; + } + if (spsData) { + const spsInfo = parseHevcSps(spsData); + if (spsInfo) { + return { + primaries: COLOR_PRIMARIES_MAP_INVERSE[spsInfo.colourPrimaries], + transfer: TRANSFER_CHARACTERISTICS_MAP_INVERSE[spsInfo.transferCharacteristics], + matrix: MATRIX_COEFFICIENTS_MAP_INVERSE[spsInfo.matrixCoefficients], + fullRange: !!spsInfo.fullRangeFlag + }; + } + } + } + break; + case "vp8": + break; + case "vp9": + { + if (info.vp9CodecInfo) { + return { + primaries: COLOR_PRIMARIES_MAP_INVERSE[info.vp9CodecInfo.colourPrimaries], + transfer: TRANSFER_CHARACTERISTICS_MAP_INVERSE[info.vp9CodecInfo.transferCharacteristics], + matrix: MATRIX_COEFFICIENTS_MAP_INVERSE[info.vp9CodecInfo.matrixCoefficients], + fullRange: !!info.vp9CodecInfo.videoFullRangeFlag + }; + } + } + break; + case "av1": + { + if (info.av1CodecInfo) { + return { + primaries: COLOR_PRIMARIES_MAP_INVERSE[info.av1CodecInfo.colourPrimaries], + transfer: TRANSFER_CHARACTERISTICS_MAP_INVERSE[info.av1CodecInfo.transferCharacteristics], + matrix: MATRIX_COEFFICIENTS_MAP_INVERSE[info.av1CodecInfo.matrixCoefficients], + fullRange: !!info.av1CodecInfo.videoFullRangeFlag + }; + } + } + break; + case "prores": + { + if (info.proresCodecInfo) { + return { + primaries: COLOR_PRIMARIES_MAP_INVERSE[info.proresCodecInfo.colourPrimaries], + transfer: TRANSFER_CHARACTERISTICS_MAP_INVERSE[info.proresCodecInfo.transferCharacteristics], + matrix: MATRIX_COEFFICIENTS_MAP_INVERSE[info.proresCodecInfo.matrixCoefficients], + fullRange: info.proresCodecInfo.fullRange + }; + } + } + break; + } + return { + primaries: void 0, + transfer: void 0, + matrix: void 0, + fullRange: void 0 + }; +}; +const extractAudioCodecString = (trackInfo) => { + const { codec, codecDescription, aacCodecInfo, dtsFormat } = trackInfo; + if (codec === "aac") { + if (!aacCodecInfo) { + throw new TypeError("AAC codec info must be provided."); + } + if (aacCodecInfo.isMpeg2) { + return "mp4a.67"; + } else { + let objectType; + if (aacCodecInfo.objectType !== null) { + objectType = aacCodecInfo.objectType; + } else { + const audioSpecificConfig = parseAacAudioSpecificConfig(codecDescription); + objectType = audioSpecificConfig.objectType; + } + return `mp4a.40.${objectType}`; + } + } else if (codec === "mp3") { + return "mp3"; + } else if (codec === "opus") { + return "opus"; + } else if (codec === "vorbis") { + return "vorbis"; + } else if (codec === "flac") { + return "flac"; + } else if (codec === "ac3") { + return "ac-3"; + } else if (codec === "eac3") { + return "ec-3"; + } else if (codec === "dts") { + return dtsFormat ?? "dtsc"; + } else if (codec && PCM_AUDIO_CODECS.includes(codec)) { + return codec; + } + throw new TypeError(`Unhandled codec '${codec}'.`); +}; +const OPUS_SAMPLE_RATE = 48e3; +const PCM_CODEC_REGEX = /^pcm-([usf])(\d+)(be)?$/; +const parsePcmCodec = (codec) => { + assert(PCM_AUDIO_CODECS.includes(codec)); + if (codec === "ulaw") { + return { dataType: "ulaw", sampleSize: 1, littleEndian: true, silentValue: 255 }; + } else if (codec === "alaw") { + return { dataType: "alaw", sampleSize: 1, littleEndian: true, silentValue: 213 }; + } + const match = PCM_CODEC_REGEX.exec(codec); + assert(match); + let dataType; + if (match[1] === "u") { + dataType = "unsigned"; + } else if (match[1] === "s") { + dataType = "signed"; + } else { + dataType = "float"; + } + const sampleSize = Number(match[2]) / 8; + const littleEndian = match[3] !== "be"; + const silentValue = codec === "pcm-u8" ? 2 ** 7 : 0; + return { dataType, sampleSize, littleEndian, silentValue }; +}; +const inferCodecFromCodecString = (codecString) => { + if (codecString.startsWith("avc1") || codecString.startsWith("avc3")) { + return "avc"; + } else if (codecString.startsWith("hev1") || codecString.startsWith("hvc1")) { + return "hevc"; + } else if (codecString === "vp8") { + return "vp8"; + } else if (codecString.startsWith("vp09")) { + return "vp9"; + } else if (codecString.startsWith("av01")) { + return "av1"; + } else if (PRORES_FOURCCS.includes(codecString)) { + return "prores"; + } + if (codecString === "mp3" || codecString === "mp4a.69" || codecString === "mp4a.6B" || codecString === "mp4a.6b" || codecString === "mp4a.40.34") { + return "mp3"; + } else if (codecString.startsWith("mp4a.40.") || codecString === "mp4a.67") { + return "aac"; + } else if (codecString === "opus") { + return "opus"; + } else if (codecString === "vorbis") { + return "vorbis"; + } else if (codecString === "flac") { + return "flac"; + } else if (codecString === "ac-3" || codecString === "ac3") { + return "ac3"; + } else if (codecString === "ec-3" || codecString === "eac3") { + return "eac3"; + } else if (DTS_FOURCCS.includes(codecString)) { + return "dts"; + } else if (codecString === "ulaw") { + return "ulaw"; + } else if (codecString === "alaw") { + return "alaw"; + } else if (PCM_CODEC_REGEX.test(codecString)) { + return codecString; + } + if (codecString === "webvtt") { + return "webvtt"; + } + return null; +}; +const MP3_FRAME_HEADER_SIZE = 4; +const SAMPLING_RATES = [44100, 48e3, 32e3]; +const KILOBIT_RATES = [ + // lowSamplingFrequency === 0 + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + // layer = 0 + -1, + 32, + 40, + 48, + 56, + 64, + 80, + 96, + 112, + 128, + 160, + 192, + 224, + 256, + 320, + -1, + // layer 1 + -1, + 32, + 48, + 56, + 64, + 80, + 96, + 112, + 128, + 160, + 192, + 224, + 256, + 320, + 384, + -1, + // layer = 2 + -1, + 32, + 64, + 96, + 128, + 160, + 192, + 224, + 256, + 288, + 320, + 352, + 384, + 416, + 448, + -1, + // layer = 3 + // lowSamplingFrequency === 1 + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + // layer = 0 + -1, + 8, + 16, + 24, + 32, + 40, + 48, + 56, + 64, + 80, + 96, + 112, + 128, + 144, + 160, + -1, + // layer = 1 + -1, + 8, + 16, + 24, + 32, + 40, + 48, + 56, + 64, + 80, + 96, + 112, + 128, + 144, + 160, + -1, + // layer = 2 + -1, + 32, + 48, + 56, + 64, + 80, + 96, + 112, + 128, + 144, + 160, + 176, + 192, + 224, + 256, + -1 + // layer = 3 +]; +const XING = 1483304551; +const INFO = 1231971951; +const computeMp3FrameSize = (lowSamplingFrequency, layer, bitrate, sampleRate, padding) => { + if (layer === 0) { + return 0; + } else if (layer === 1) { + return Math.floor(144 * bitrate / (sampleRate << lowSamplingFrequency)) + padding; + } else if (layer === 2) { + return Math.floor(144 * bitrate / sampleRate) + padding; + } else { + return (Math.floor(12 * bitrate / sampleRate) + padding) * 4; + } +}; +const computeAverageMp3FrameSize = (lowSamplingFrequency, layer, bitrate, sampleRate) => { + if (layer === 0) { + return 0; + } else if (layer === 1) { + return 144 * bitrate / (sampleRate << lowSamplingFrequency); + } else if (layer === 2) { + return 144 * bitrate / sampleRate; + } else { + return 12 * bitrate / sampleRate * 4; + } +}; +const getXingOffset = (mpegVersionId, channel) => { + return mpegVersionId === 3 ? channel === 3 ? 21 : 36 : channel === 3 ? 13 : 21; +}; +const readMp3FrameHeader = (word, remainingBytes) => { + const firstByte = word >>> 24; + const secondByte = word >>> 16 & 255; + const thirdByte = word >>> 8 & 255; + const fourthByte = word & 255; + if (firstByte !== 255 && secondByte !== 255 && thirdByte !== 255 && fourthByte !== 255) { + return { + header: null, + bytesAdvanced: 4 + }; + } + if (firstByte !== 255) { + return { header: null, bytesAdvanced: 1 }; + } + if ((secondByte & 224) !== 224) { + return { header: null, bytesAdvanced: 1 }; + } + let lowSamplingFrequency = 0; + let mpeg25 = 0; + if (secondByte & 1 << 4) { + lowSamplingFrequency = secondByte & 1 << 3 ? 0 : 1; + } else { + lowSamplingFrequency = 1; + mpeg25 = 1; + } + const mpegVersionId = secondByte >> 3 & 3; + const layer = secondByte >> 1 & 3; + const bitrateIndex = thirdByte >> 4 & 15; + const frequencyIndex = (thirdByte >> 2 & 3) % 3; + const padding = thirdByte >> 1 & 1; + const channel = fourthByte >> 6 & 3; + const modeExtension = fourthByte >> 4 & 3; + const copyright = fourthByte >> 3 & 1; + const original = fourthByte >> 2 & 1; + const emphasis = fourthByte & 3; + const kilobitRate = KILOBIT_RATES[lowSamplingFrequency * 16 * 4 + layer * 16 + bitrateIndex]; + if (kilobitRate === -1) { + return { header: null, bytesAdvanced: 1 }; + } + const bitrate = kilobitRate * 1e3; + const sampleRate = SAMPLING_RATES[frequencyIndex] >> lowSamplingFrequency + mpeg25; + const frameLength = computeMp3FrameSize(lowSamplingFrequency, layer, bitrate, sampleRate, padding); + if (remainingBytes !== null && remainingBytes < frameLength) { + return { header: null, bytesAdvanced: 1 }; + } + let audioSamplesInFrame; + if (mpegVersionId === 3) { + audioSamplesInFrame = layer === 3 ? 384 : 1152; + } else { + if (layer === 3) { + audioSamplesInFrame = 384; + } else if (layer === 2) { + audioSamplesInFrame = 1152; + } else { + audioSamplesInFrame = 576; + } + } + return { + header: { + totalSize: frameLength, + mpegVersionId, + lowSamplingFrequency, + layer, + bitrate, + frequencyIndex, + sampleRate, + channel, + modeExtension, + copyright, + original, + emphasis, + audioSamplesInFrame + }, + bytesAdvanced: 1 + }; +}; +const decodeSynchsafe = (synchsafed) => { + let mask = 2130706432; + let unsynchsafed = 0; + while (mask !== 0) { + unsynchsafed >>= 1; + unsynchsafed |= synchsafed & mask; + mask >>= 8; + } + return unsynchsafed; +}; +var XingFlags; +(function(XingFlags2) { + XingFlags2[XingFlags2["FrameCount"] = 1] = "FrameCount"; + XingFlags2[XingFlags2["FileSize"] = 2] = "FileSize"; + XingFlags2[XingFlags2["Toc"] = 4] = "Toc"; +})(XingFlags || (XingFlags = {})); +const getMp3ChannelCount = (channel) => { + return channel === 3 ? 1 : 2; +}; class Demuxer { constructor(input) { this.input = input; @@ -3611,7 +4456,7 @@ class EncodedPacket { throw new TypeError("Metadata-only packets cannot be converted to a video chunk."); } if (typeof EncodedVideoChunk === "undefined") { - throw new Error("Your browser does not support EncodedVideoChunk."); + throw new Error("EncodedVideoChunk is not available in this environment."); } return new EncodedVideoChunk({ data: this.data, @@ -3633,7 +4478,7 @@ class EncodedPacket { throw new TypeError("Metadata-only packets cannot be converted to a video chunk."); } if (typeof EncodedVideoChunk === "undefined") { - throw new Error("Your browser does not support EncodedVideoChunk."); + throw new Error("EncodedVideoChunk is not available in this environment."); } return new EncodedVideoChunk({ data: this.sideData.alpha, @@ -3650,7 +4495,7 @@ class EncodedPacket { throw new TypeError("Metadata-only packets cannot be converted to an audio chunk."); } if (typeof EncodedAudioChunk === "undefined") { - throw new Error("Your browser does not support EncodedAudioChunk."); + throw new Error("EncodedAudioChunk is not available in this environment."); } return new EncodedAudioChunk({ data: this.data, @@ -3949,7 +4794,7 @@ const createAes128CbcDecryptStream = (reader, getInit, close) => { } const requestedLength = CHUNK_SIZE + BLOCK_SIZE; let nextSlice = reader.requestSliceRange(pos, 0, requestedLength); - if (nextSlice instanceof Promise) + if (isThenable(nextSlice)) nextSlice = await nextSlice; if (!nextSlice || nextSlice.length === 0) { throw new Error("Invalid ciphertext."); @@ -4028,9 +4873,10 @@ class IsobmffDemuxer extends Demuxer { return this.metadataPromise ?? (this.metadataPromise = (async () => { let currentPos = 0; let lookForMfraBox = false; + let foundMovieBoxes = false; while (true) { let slice = this.reader.requestSliceRange(currentPos, MIN_BOX_HEADER_SIZE, MAX_BOX_HEADER_SIZE); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) break; @@ -4044,7 +4890,7 @@ class IsobmffDemuxer extends Demuxer { this.isQuickTime = majorBrand === "qt "; } else if (boxInfo.name === "moov") { let moovSlice = this.reader.requestSlice(slice.filePos, boxInfo.contentSize); - if (moovSlice instanceof Promise) + if (isThenable(moovSlice)) moovSlice = await moovSlice; if (!moovSlice) break; @@ -4055,82 +4901,39 @@ class IsobmffDemuxer extends Demuxer { track.editListOffset -= Math.round(previousSegmentDurationsInSeconds * track.timescale); } lookForMfraBox = this.isFragmented && this.reader.fileSize !== null && this.reader.fileSize > startPos + boxInfo.totalSize; + foundMovieBoxes = true; break; } else if (boxInfo.name === "moof") { if (!this.input._initInput) { throw new Error('"moof" box encountered with no "moov" box present; this file is likely a Segment as described in ISO/IEC 14496-12 Section 8.16. A separate init file that contains a "moov" box is required to read this file, please provide it using InputOptions.initInput.'); } - const initDemuxer = await this.input._initInput._getDemuxer(); - if (initDemuxer.constructor !== IsobmffDemuxer) { - throw new Error("Init input must match the input's format."); - } - await initDemuxer.readMetadata(); - this.movieTimescale = initDemuxer.movieTimescale; - this.movieDurationInTimescale = initDemuxer.movieDurationInTimescale; - this.metadataTags = initDemuxer.metadataTags; - this.isFragmented = true; - this.fragmentTrackDefaults = initDemuxer.fragmentTrackDefaults; - this.psshBoxes = initDemuxer.psshBoxes; - for (const foreignTrack of initDemuxer.tracks) { - const track = { - id: foreignTrack.id, - demuxer: this, - trackBacking: null, - disposition: foreignTrack.disposition, - timescale: foreignTrack.timescale, - durationInMediaTimescale: foreignTrack.durationInMediaTimescale, - durationInMovieTimescale: foreignTrack.durationInMovieTimescale, - rotation: foreignTrack.rotation, - internalCodecId: foreignTrack.internalCodecId, - name: foreignTrack.name, - languageCode: foreignTrack.languageCode, - sampleTableByteOffset: null, - sampleTable: null, - fragmentLookupTable: [], - currentFragmentState: null, - fragmentPositionCache: [], - editListPreviousSegmentDurations: foreignTrack.editListPreviousSegmentDurations, - editListOffset: foreignTrack.editListOffset, - encryptionInfo: foreignTrack.encryptionInfo, - encryptionAuxInfo: null, - frmaCodecString: null, - info: foreignTrack.info - }; - if (foreignTrack.trackBacking) { - assert(track.info); - if (track.info.type === "video" && track.info.width !== -1) { - const videoTrack = track; - track.trackBacking = new IsobmffVideoTrackBacking(videoTrack); - this.tracks.push(track); - } else if (track.info.type === "audio" && track.info.numberOfChannels !== -1) { - const audioTrack = track; - track.trackBacking = new IsobmffAudioTrackBacking(audioTrack); - this.tracks.push(track); - } - } - } + await this.copyMetadataFromInitInput(this.input._initInput); lookForMfraBox = false; + foundMovieBoxes = true; break; } currentPos = startPos + boxInfo.totalSize; } + if (!foundMovieBoxes && this.input._initInput) { + await this.copyMetadataFromInitInput(this.input._initInput); + } if (lookForMfraBox) { assert(this.reader.fileSize !== null); let lastWordSlice = this.reader.requestSlice(this.reader.fileSize - 4, 4); - if (lastWordSlice instanceof Promise) + if (isThenable(lastWordSlice)) lastWordSlice = await lastWordSlice; assert(lastWordSlice); const lastWord = readU32Be(lastWordSlice); const potentialMfraPos = this.reader.fileSize - lastWord; if (potentialMfraPos >= 0 && potentialMfraPos <= this.reader.fileSize - MAX_BOX_HEADER_SIZE) { let mfraHeaderSlice = this.reader.requestSliceRange(potentialMfraPos, MIN_BOX_HEADER_SIZE, MAX_BOX_HEADER_SIZE); - if (mfraHeaderSlice instanceof Promise) + if (isThenable(mfraHeaderSlice)) mfraHeaderSlice = await mfraHeaderSlice; if (mfraHeaderSlice) { const boxInfo = readBoxHeader(mfraHeaderSlice); if (boxInfo && boxInfo.name === "mfra") { let mfraSlice = this.reader.requestSlice(mfraHeaderSlice.filePos, boxInfo.contentSize); - if (mfraSlice instanceof Promise) + if (isThenable(mfraSlice)) mfraSlice = await mfraSlice; if (mfraSlice) { this.readContiguousBoxes(mfraSlice); @@ -4141,6 +4944,57 @@ class IsobmffDemuxer extends Demuxer { } })()); } + async copyMetadataFromInitInput(initInput) { + const initDemuxer = await initInput._getDemuxer(); + if (initDemuxer.constructor !== IsobmffDemuxer) { + throw new Error("Init input must match the input's format."); + } + await initDemuxer.readMetadata(); + this.movieTimescale = initDemuxer.movieTimescale; + this.movieDurationInTimescale = initDemuxer.movieDurationInTimescale; + this.metadataTags = initDemuxer.metadataTags; + this.isFragmented = true; + this.fragmentTrackDefaults = initDemuxer.fragmentTrackDefaults; + this.psshBoxes = initDemuxer.psshBoxes; + for (const foreignTrack of initDemuxer.tracks) { + const track = { + id: foreignTrack.id, + demuxer: this, + trackBacking: null, + disposition: foreignTrack.disposition, + timescale: foreignTrack.timescale, + durationInMediaTimescale: foreignTrack.durationInMediaTimescale, + durationInMovieTimescale: foreignTrack.durationInMovieTimescale, + rotation: foreignTrack.rotation, + internalCodecId: foreignTrack.internalCodecId, + name: foreignTrack.name, + languageCode: foreignTrack.languageCode, + sampleTableByteOffset: null, + sampleTable: null, + fragmentLookupTable: [], + currentFragmentState: null, + fragmentPositionCache: [], + editListPreviousSegmentDurations: foreignTrack.editListPreviousSegmentDurations, + editListOffset: foreignTrack.editListOffset, + encryptionInfo: foreignTrack.encryptionInfo, + encryptionAuxInfo: null, + frmaCodecString: null, + info: foreignTrack.info + }; + if (foreignTrack.trackBacking) { + assert(track.info); + if (track.info.type === "video" && track.info.width !== -1) { + const videoTrack = track; + track.trackBacking = new IsobmffVideoTrackBacking(videoTrack); + this.tracks.push(track); + } else if (track.info.type === "audio" && track.info.numberOfChannels !== -1) { + const audioTrack = track; + track.trackBacking = new IsobmffAudioTrackBacking(audioTrack); + this.tracks.push(track); + } + } + } + } getSampleTableForTrack(internalTrack) { if (internalTrack.sampleTable) { return internalTrack.sampleTable; @@ -4237,13 +5091,13 @@ class IsobmffDemuxer extends Demuxer { return this.lastReadFragment; } let headerSlice = this.reader.requestSliceRange(startPos, MIN_BOX_HEADER_SIZE, MAX_BOX_HEADER_SIZE); - if (headerSlice instanceof Promise) + if (isThenable(headerSlice)) headerSlice = await headerSlice; assert(headerSlice); const moofBoxInfo = readBoxHeader(headerSlice); assert(moofBoxInfo?.name === "moof"); let entireSlice = this.reader.requestSlice(startPos, moofBoxInfo.totalSize); - if (entireSlice instanceof Promise) + if (isThenable(entireSlice)) entireSlice = await entireSlice; assert(entireSlice); this.traverseBox(entireSlice); @@ -4441,11 +5295,8 @@ class IsobmffDemuxer extends Demuxer { const segmentDuration = version === 1 ? readU64Be(slice) : readU32Be(slice); const mediaTime = version === 1 ? readI64Be(slice) : readI32Be(slice); const mediaRate = readFixed_16_16(slice); - if (segmentDuration === 0) { - continue; - } if (relevantEntryFound) { - console.warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit."); + Logging._warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit."); break; } if (mediaTime === -1) { @@ -4453,7 +5304,7 @@ class IsobmffDemuxer extends Demuxer { continue; } if (mediaRate !== 1) { - console.warn("Unsupported edit list entry: media rate must be 1."); + Logging._warn("Unsupported edit list entry: media rate must be 1."); break; } track.editListPreviousSegmentDurations = previousSegmentDurations; @@ -4509,12 +5360,14 @@ class IsobmffDemuxer extends Demuxer { squarePixelHeight: -1, codec: null, codecDescription: null, - colorSpace: null, + colorSpace: { ...EMPTY_COLOR_SPACE }, avcType: null, avcCodecInfo: null, hevcCodecInfo: null, vp9CodecInfo: null, - av1CodecInfo: null + av1CodecInfo: null, + proresCodecInfo: null, + proresFormat: null }; } else if (handlerType === "soun") { track.info = { @@ -4524,6 +5377,7 @@ class IsobmffDemuxer extends Demuxer { codec: null, codecDescription: null, aacCodecInfo: null, + dtsFormat: null, pcmLittleEndian: false, pcmSampleSize: null }; @@ -4582,10 +5436,13 @@ class IsobmffDemuxer extends Demuxer { track.info.codec = "vp9"; } else if (codecName === "av01") { track.info.codec = "av1"; + } else if (PRORES_FOURCCS.includes(lowercaseBoxName)) { + track.info.codec = "prores"; + track.info.proresFormat = lowercaseBoxName; } else if (codecName === null) { - console.warn(`Unknown encrypted video codec due to missing frma box.`); + Logging._warn(`Unknown encrypted video codec due to missing frma box.`); } else { - console.warn(`Unsupported video codec (sample entry type '${sampleBoxInfo.name}').`); + Logging._warn(`Unsupported video codec (sample entry type '${sampleBoxInfo.name}').`); } } else { slice.skip(6 * 1 + 2); @@ -4631,13 +5488,16 @@ class IsobmffDemuxer extends Demuxer { track.info.codec = "ac3"; } else if (codecName === "ec-3") { track.info.codec = "eac3"; + } else if (DTS_FOURCCS.includes(codecName)) { + track.info.codec = "dts"; + track.info.dtsFormat = codecName; } else if (codecName === "twos") { if (sampleSize === 8) { track.info.codec = "pcm-s8"; } else if (sampleSize === 16) { track.info.codec = track.info.pcmLittleEndian ? "pcm-s16" : "pcm-s16be"; } else { - console.warn(`Unsupported sample size ${sampleSize} for codec 'twos'.`); + Logging._warn(`Unsupported sample size ${sampleSize} for codec 'twos'.`); track.info.codec = null; } } else if (codecName === "sowt") { @@ -4646,7 +5506,7 @@ class IsobmffDemuxer extends Demuxer { } else if (sampleSize === 16) { track.info.codec = "pcm-s16"; } else { - console.warn(`Unsupported sample size ${sampleSize} for codec 'sowt'.`); + Logging._warn(`Unsupported sample size ${sampleSize} for codec 'sowt'.`); track.info.codec = null; } } else if (codecName === "raw ") { @@ -4669,7 +5529,7 @@ class IsobmffDemuxer extends Demuxer { } else if (pcmSampleSize === 32) { track.info.codec = "pcm-s32"; } else { - console.warn(`Invalid ipcm sample size ${pcmSampleSize}.`); + Logging._warn(`Invalid ipcm sample size ${pcmSampleSize}.`); track.info.codec = null; } } else { @@ -4680,7 +5540,7 @@ class IsobmffDemuxer extends Demuxer { } else if (pcmSampleSize === 32) { track.info.codec = "pcm-s32be"; } else { - console.warn(`Invalid ipcm sample size ${pcmSampleSize}.`); + Logging._warn(`Invalid ipcm sample size ${pcmSampleSize}.`); track.info.codec = null; } } @@ -4692,7 +5552,7 @@ class IsobmffDemuxer extends Demuxer { } else if (pcmSampleSize === 64) { track.info.codec = "pcm-f64"; } else { - console.warn(`Invalid fpcm sample size ${pcmSampleSize}.`); + Logging._warn(`Invalid fpcm sample size ${pcmSampleSize}.`); track.info.codec = null; } } else { @@ -4701,7 +5561,7 @@ class IsobmffDemuxer extends Demuxer { } else if (pcmSampleSize === 64) { track.info.codec = "pcm-f64be"; } else { - console.warn(`Invalid fpcm sample size ${pcmSampleSize}.`); + Logging._warn(`Invalid fpcm sample size ${pcmSampleSize}.`); track.info.codec = null; } } @@ -4734,12 +5594,12 @@ class IsobmffDemuxer extends Demuxer { } } if (track.info.codec === null) { - console.warn("Unsupported PCM format."); + Logging._warn("Unsupported PCM format."); } } else if (codecName === null) { - console.warn(`Unknown encrypted audio codec due to missing frma box.`); + Logging._warn(`Unknown encrypted audio codec due to missing frma box.`); } else { - console.warn(`Unsupported audio codec (sample entry type '${sampleBoxInfo.name}').`); + Logging._warn(`Unsupported audio codec (sample entry type '${sampleBoxInfo.name}').`); } } slice.filePos = sampleBoxStartPos + sampleBoxInfo.totalSize; @@ -4776,7 +5636,7 @@ class IsobmffDemuxer extends Demuxer { defaultSkipByteBlock: null }; } else { - console.warn(`Unsupported encryption scheme '${schemeType}'.`); + Logging._warn(`Unsupported encryption scheme '${schemeType}'.`); } } break; @@ -4815,6 +5675,9 @@ class IsobmffDemuxer extends Demuxer { break; } assert(track.info); + if (boxInfo.contentSize === 0) { + break; + } track.info.codecDescription = readBytes(slice, boxInfo.contentSize); } break; @@ -4825,6 +5688,9 @@ class IsobmffDemuxer extends Demuxer { break; } assert(track.info); + if (boxInfo.contentSize === 0) { + break; + } track.info.codecDescription = readBytes(slice, boxInfo.contentSize); } break; @@ -4877,6 +5743,9 @@ class IsobmffDemuxer extends Demuxer { const chromaSubsamplingY = thirdByte >> 2 & 1; const chromaSamplePosition = thirdByte & 3; const bitDepth = profile === 2 && highBitDepth ? twelveBit ? 12 : 10 : highBitDepth ? 10 : 8; + slice.skip(1); + const configObus = readBytes(slice, boxInfo.contentSize - 4); + const configObuInfo = extractAv1CodecInfoFromPacket(configObus); track.info.av1CodecInfo = { profile, level, @@ -4885,7 +5754,11 @@ class IsobmffDemuxer extends Demuxer { monochrome, chromaSubsamplingX, chromaSubsamplingY, - chromaSamplePosition + chromaSamplePosition, + videoFullRangeFlag: configObuInfo?.videoFullRangeFlag ?? 0, + colourPrimaries: configObuInfo?.colourPrimaries ?? 2, + transferCharacteristics: configObuInfo?.transferCharacteristics ?? 2, + matrixCoefficients: configObuInfo?.matrixCoefficients ?? 2 }; } break; @@ -4897,18 +5770,21 @@ class IsobmffDemuxer extends Demuxer { } assert(track.info?.type === "video"); const colourType = readAscii(slice, 4); - if (colourType !== "nclx") { + if (colourType !== "nclx" && colourType !== "nclc") { break; } const colourPrimaries = readU16Be(slice); const transferCharacteristics = readU16Be(slice); const matrixCoefficients = readU16Be(slice); - const fullRangeFlag = Boolean(readU8(slice) & 128); + let fullRange = void 0; + if (colourType === "nclx") { + fullRange = Boolean(readU8(slice) & 128); + } track.info.colorSpace = { primaries: COLOR_PRIMARIES_MAP_INVERSE[colourPrimaries], transfer: TRANSFER_CHARACTERISTICS_MAP_INVERSE[transferCharacteristics], matrix: MATRIX_COEFFICIENTS_MAP_INVERSE[matrixCoefficients], - fullRange: fullRangeFlag + fullRange }; } break; @@ -4938,10 +5814,9 @@ class IsobmffDemuxer extends Demuxer { case "esds": { const track = this.currentTrack; - if (!track) { + if (!track || track.info?.type !== "audio") { break; } - assert(track.info?.type === "audio"); slice.skip(4); const tag = readU8(slice); assert(tag === 3); @@ -4976,8 +5851,10 @@ class IsobmffDemuxer extends Demuxer { track.info.codec = "mp3"; } else if (objectTypeIndication === 221) { track.info.codec = "vorbis"; + } else if (objectTypeIndication === 169) { + track.info.codec = "dts"; } else { - console.warn(`Unsupported audio codec (objectTypeIndication ${objectTypeIndication}) - discarding track.`); + Logging._warn(`Unsupported audio codec (objectTypeIndication ${objectTypeIndication}) - discarding track.`); } slice.skip(1 + 3 + 4 + 4); if (decoderConfigDescriptorLength > slice.filePos - payloadStart) { @@ -4987,11 +5864,11 @@ class IsobmffDemuxer extends Demuxer { track.info.codecDescription = readBytes(slice, decoderSpecificInfoLength); if (track.info.codec === "aac") { const audioSpecificConfig = parseAacAudioSpecificConfig(track.info.codecDescription); - if (audioSpecificConfig.numberOfChannels !== null) { - track.info.numberOfChannels = audioSpecificConfig.numberOfChannels; + if (audioSpecificConfig.outputNumberOfChannels !== null) { + track.info.numberOfChannels = audioSpecificConfig.outputNumberOfChannels; } - if (audioSpecificConfig.sampleRate !== null) { - track.info.sampleRate = audioSpecificConfig.sampleRate; + if (audioSpecificConfig.outputSampleRate !== null) { + track.info.sampleRate = audioSpecificConfig.outputSampleRate; } } } @@ -5123,7 +6000,7 @@ class IsobmffDemuxer extends Demuxer { const bytes = readBytes(slice, boxInfo.contentSize); const config = parseEac3Config(bytes); if (!config) { - console.warn("Invalid dec3 box contents, ignoring."); + Logging._warn("Invalid dec3 box contents, ignoring."); break; } const sampleRate = getEac3SampleRate(config); @@ -5133,6 +6010,25 @@ class IsobmffDemuxer extends Demuxer { track.info.numberOfChannels = getEac3ChannelCount(config); } break; + case "ddts": + { + const track = this.currentTrack; + if (!track) { + break; + } + assert(track.info?.type === "audio"); + const bytes = readBytes(slice, Math.min(boxInfo.contentSize, DTS_SPECIFIC_BOX_SIZE)); + const config = parseDtsSpecificBox(bytes); + if (!config) { + Logging._warn("Invalid ddts box contents, ignoring."); + break; + } + track.info.sampleRate = config.sampleRate; + if (config.numberOfChannels !== null) { + track.info.numberOfChannels = config.numberOfChannels; + } + } + break; case "stts": { const track = this.currentTrack; @@ -5406,8 +6302,11 @@ class IsobmffDemuxer extends Demuxer { this.readContiguousBoxes(slice.slice(contentStartPos, boxInfo.contentSize)); if (this.currentTrack) { const trackData = this.currentFragment.trackData.get(this.currentTrack.id); - if (trackData) { - this.currentFragment.implicitBaseDataOffset = trackData.currentOffset; + cond: if (trackData) { + if (trackData.samples.length === 0) { + this.currentFragment.trackData.delete(this.currentTrack.id); + break cond; + } trackData.presentationTimestamps = trackData.samples.map((x, i) => ({ presentationTimestamp: x.presentationTimestamp, sampleIndex: i })).sort((a, b) => a.presentationTimestamp - b.presentationTimestamp); for (let i = 0; i < trackData.presentationTimestamps.length; i++) { const currentEntry = trackData.presentationTimestamps[i]; @@ -5562,10 +6461,6 @@ class IsobmffDemuxer extends Demuxer { }; this.currentFragment.trackData.set(track.id, trackData); } - if (sampleCount === 0) { - this.currentFragment.implicitBaseDataOffset = trackData.currentOffset; - break; - } for (let i = 0; i < sampleCount; i++) { let sampleDuration; if (sampleDurationPresent) { @@ -5611,6 +6506,7 @@ class IsobmffDemuxer extends Demuxer { trackData.currentOffset += sampleSize; trackData.currentTimestamp += sampleDuration; } + this.currentFragment.implicitBaseDataOffset = trackData.currentOffset; } break; case "saiz": @@ -5660,7 +6556,7 @@ class IsobmffDemuxer extends Demuxer { break; } if (entryCount > 1) { - console.warn("Multiple saio entries are not supported; using the first offset only."); + Logging._warn("Multiple saio entries are not supported; using the first offset only."); } let offset = version === 0 ? readU32Be(slice) : Number(readU64Be(slice)); if (this.currentFragment) { @@ -6057,6 +6953,9 @@ class IsobmffTrackBacking { isRelativeToUnixEpoch() { return false; } + getUnixTimeForTimestamp() { + return null; + } getDisposition() { return this.internalTrack.disposition; } @@ -6250,17 +7149,23 @@ class IsobmffTrackBacking { data = PLACEHOLDER_DATA; } else { let slice = this.internalTrack.demuxer.reader.requestSlice(sampleInfo.sampleOffset, sampleInfo.sampleSize); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) { return null; } data = readBytes(slice, sampleInfo.sampleSize); - if (this.internalTrack.encryptionAuxInfo) { - assert(this.internalTrack.encryptionInfo); - const entries = await resolveEncryptionAuxInfo(this.internalTrack.demuxer.reader, this.internalTrack.encryptionInfo, this.internalTrack.encryptionAuxInfo); - if (sampleIndex < entries.length) { - data = await decryptSample(this.internalTrack, entries[sampleIndex], data, null); + if (this.internalTrack.encryptionInfo) { + let sampleEncryption = null; + if (this.internalTrack.encryptionAuxInfo) { + const entries = await resolveEncryptionAuxInfo(this.internalTrack.demuxer.reader, this.internalTrack.encryptionInfo, this.internalTrack.encryptionAuxInfo); + if (sampleIndex < entries.length) { + sampleEncryption = entries[sampleIndex]; + } + } + sampleEncryption ?? (sampleEncryption = getDefaultSampleEncryption(this.internalTrack.encryptionInfo)); + if (sampleEncryption) { + data = await decryptSample(this.internalTrack, sampleEncryption, data, null); } } } @@ -6282,14 +7187,17 @@ class IsobmffTrackBacking { data = PLACEHOLDER_DATA; } else { let slice = this.internalTrack.demuxer.reader.requestSlice(fragmentSample.byteOffset, fragmentSample.byteSize); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) { return null; } data = readBytes(slice, fragmentSample.byteSize); - if (fragmentSample.encryption) { - data = await decryptSample(this.internalTrack, fragmentSample.encryption, data, fragment); + if (this.internalTrack.encryptionInfo) { + const sampleEncryption = fragmentSample.encryption ?? getDefaultSampleEncryption(this.internalTrack.encryptionInfo); + if (sampleEncryption) { + data = await decryptSample(this.internalTrack, sampleEncryption, data, fragment); + } } } const timestamp = (fragmentSample.presentationTimestamp - this.internalTrack.editListOffset) / this.internalTrack.timescale; @@ -6338,7 +7246,7 @@ class IsobmffTrackBacking { } } let slice = demuxer.reader.requestSliceRange(currentPos, MIN_BOX_HEADER_SIZE, MAX_BOX_HEADER_SIZE); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) break; @@ -6400,34 +7308,67 @@ class IsobmffVideoTrackBacking extends IsobmffTrackBacking { return this.internalTrack.rotation; } async getColorSpace() { + const decoderConfig = await this.getDecoderConfig(); + if (!decoderConfig) { + return this.internalTrack.info.colorSpace; + } return { - primaries: this.internalTrack.info.colorSpace?.primaries, - transfer: this.internalTrack.info.colorSpace?.transfer, - matrix: this.internalTrack.info.colorSpace?.matrix, - fullRange: this.internalTrack.info.colorSpace?.fullRange + primaries: decoderConfig.colorSpace?.primaries, + transfer: decoderConfig.colorSpace?.transfer, + matrix: decoderConfig.colorSpace?.matrix, + fullRange: decoderConfig.colorSpace?.fullRange }; } async canBeTransparent() { - return false; + return this.internalTrack.info.codec === "prores" && (this.internalTrack.info.proresFormat === "ap4h" || this.internalTrack.info.proresFormat === "ap4x"); } async getDecoderConfig() { if (!this.internalTrack.info.codec) { return null; } return this.decoderConfigPromise ?? (this.decoderConfigPromise = (async () => { - if (this.internalTrack.info.codec === "vp9" && !this.internalTrack.info.vp9CodecInfo) { + var _a, _b, _c, _d; + if (this.internalTrack.info.codec === "avc" && !this.internalTrack.info.codecDescription) { const firstPacket = await this.getFirstPacket({}); - this.internalTrack.info.vp9CodecInfo = firstPacket && extractVp9CodecInfoFromPacket(firstPacket.data); - } else if (this.internalTrack.info.codec === "av1" && !this.internalTrack.info.av1CodecInfo) { + this.internalTrack.info.avcCodecInfo = firstPacket && extractAvcDecoderConfigurationRecord(firstPacket.data); + } else if (this.internalTrack.info.codec === "hevc" && !this.internalTrack.info.codecDescription) { const firstPacket = await this.getFirstPacket({}); - this.internalTrack.info.av1CodecInfo = firstPacket && extractAv1CodecInfoFromPacket(firstPacket.data); + this.internalTrack.info.hevcCodecInfo = firstPacket && extractHevcDecoderConfigurationRecord(firstPacket.data); + } else if (this.internalTrack.info.codec === "vp9" && (!this.internalTrack.info.vp9CodecInfo || !vp9CodecInfoHasColorInfo(this.internalTrack.info.vp9CodecInfo))) { + const firstPacket = await this.getFirstPacket({}); + const packetInfo = firstPacket && extractVp9CodecInfoFromPacket(firstPacket.data); + if (packetInfo) { + this.internalTrack.info.vp9CodecInfo = { + ...this.internalTrack.info.vp9CodecInfo ?? packetInfo, + videoFullRangeFlag: packetInfo.videoFullRangeFlag, + colourPrimaries: packetInfo.colourPrimaries, + transferCharacteristics: packetInfo.transferCharacteristics, + matrixCoefficients: packetInfo.matrixCoefficients + }; + } + } else if (this.internalTrack.info.codec === "av1" && (!this.internalTrack.info.av1CodecInfo || !av1CodecInfoHasColorInfo(this.internalTrack.info.av1CodecInfo))) { + const firstPacket = await this.getFirstPacket({}); + const packetInfo = firstPacket && extractAv1CodecInfoFromPacket(firstPacket.data); + if (packetInfo) { + this.internalTrack.info.av1CodecInfo = packetInfo; + } + } else if (this.internalTrack.info.codec === "prores" && !this.internalTrack.info.proresCodecInfo) { + const firstPacket = await this.getFirstPacket({}); + this.internalTrack.info.proresCodecInfo = firstPacket && extractProresCodecInfoFromPacket(firstPacket.data); + } + if (!colorSpaceIsComplete(this.internalTrack.info.colorSpace)) { + const colorSpace = extractColorSpace(this.internalTrack.info); + (_a = this.internalTrack.info.colorSpace).primaries ?? (_a.primaries = colorSpace.primaries); + (_b = this.internalTrack.info.colorSpace).transfer ?? (_b.transfer = colorSpace.transfer); + (_c = this.internalTrack.info.colorSpace).matrix ?? (_c.matrix = colorSpace.matrix); + (_d = this.internalTrack.info.colorSpace).fullRange ?? (_d.fullRange = colorSpace.fullRange); } const config = { codec: extractVideoCodecString(this.internalTrack.info), codedWidth: this.internalTrack.info.width, codedHeight: this.internalTrack.info.height, description: this.internalTrack.info.codecDescription ?? void 0, - colorSpace: this.internalTrack.info.colorSpace ?? void 0 + colorSpace: this.internalTrack.info.colorSpace }; if (this.internalTrack.info.width !== this.internalTrack.info.squarePixelWidth || this.internalTrack.info.height !== this.internalTrack.info.squarePixelHeight) { config.displayAspectWidth = this.internalTrack.info.squarePixelWidth; @@ -6440,7 +7381,7 @@ class IsobmffVideoTrackBacking extends IsobmffTrackBacking { class IsobmffAudioTrackBacking extends IsobmffTrackBacking { constructor(internalTrack) { super(internalTrack); - this.decoderConfig = null; + this.decoderConfigPromise = null; this.internalTrack = internalTrack; } getType() { @@ -6459,12 +7400,18 @@ class IsobmffAudioTrackBacking extends IsobmffTrackBacking { if (!this.internalTrack.info.codec) { return null; } - return this.decoderConfig ?? (this.decoderConfig = { - codec: extractAudioCodecString(this.internalTrack.info), - numberOfChannels: this.internalTrack.info.numberOfChannels, - sampleRate: this.internalTrack.info.sampleRate, - description: this.internalTrack.info.codecDescription ?? void 0 - }); + return this.decoderConfigPromise ?? (this.decoderConfigPromise = (async () => { + if (this.internalTrack.info.codec === "dts" && !this.internalTrack.info.dtsFormat) { + const firstPacket = await this.getFirstPacket({}); + this.internalTrack.info.dtsFormat = firstPacket && extractDtsFourCcFromPacket(firstPacket.data); + } + return { + codec: extractAudioCodecString(this.internalTrack.info), + numberOfChannels: this.internalTrack.info.numberOfChannels, + sampleRate: this.internalTrack.info.sampleRate, + description: this.internalTrack.info.codecDescription ?? void 0 + }; + })()); } } const getSampleIndexForTimestamp = (sampleTable, timescaleUnits) => { @@ -6625,7 +7572,7 @@ const resolveEncryptionAuxInfo = async (reader, encryptionInfo, aux) => { } } let slice = reader.requestSlice(aux.offset, totalSize); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) { throw new Error("Failed to read auxiliary encryption info."); @@ -6656,6 +7603,15 @@ const resolveEncryptionAuxInfo = async (reader, encryptionInfo, aux) => { aux.resolved = entries; return entries; }; +const getDefaultSampleEncryption = (encryptionInfo) => { + if (!encryptionInfo.defaultConstantIv) { + return null; + } + return { + iv: encryptionInfo.defaultConstantIv, + subsamples: null + }; +}; const decryptSample = async (track, sampleEncryption, data, fragment) => { assert(track.encryptionInfo); const encryptionInfo = track.encryptionInfo; @@ -7078,7 +8034,7 @@ const searchForNextElementId = async (reader, startPos, ids, until) => { let currentPos = startPos; while (until === null || currentPos < until) { let slice = reader.requestSliceRange(currentPos, MIN_HEADER_SIZE, MAX_HEADER_SIZE); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) break; @@ -7100,7 +8056,7 @@ const resync = async (reader, startPos, ids, until) => { let currentPos = startPos; while (currentPos < until) { let slice = reader.requestSliceRange(currentPos, 0, Math.min(CHUNK_SIZE, until - currentPos)); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) break; @@ -7123,13 +8079,15 @@ const CODEC_STRING_MAP = { "vp8": "V_VP8", "vp9": "V_VP9", "av1": "V_AV1", + "prores": "V_PRORES", "aac": "A_AAC", "mp3": "A_MPEG/L3", "opus": "A_OPUS", "vorbis": "A_VORBIS", "flac": "A_FLAC", "ac3": "A_AC3", - "eac3": "A_EAC3" + "eac3": "A_EAC3", + "dts": "A_DTS" }; function assertDefinedSize(size) { if (size === void 0) { @@ -7226,7 +8184,7 @@ class MatroskaDemuxer extends Demuxer { let currentPos = 0; while (true) { let slice = this.reader.requestSliceRange(currentPos, MIN_HEADER_SIZE, MAX_HEADER_SIZE); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) break; @@ -7240,7 +8198,7 @@ class MatroskaDemuxer extends Demuxer { if (id === EBMLId.EBML) { assertDefinedSize(size); let slice2 = this.reader.requestSlice(dataStartPos, size); - if (slice2 instanceof Promise) + if (isThenable(slice2)) slice2 = await slice2; if (!slice2) break; @@ -7296,7 +8254,7 @@ class MatroskaDemuxer extends Demuxer { let currentPos = segmentDataStart; while (this.currentSegment.elementEndPos === null || currentPos < this.currentSegment.elementEndPos) { let slice = this.reader.requestSliceRange(currentPos, MIN_HEADER_SIZE, MAX_HEADER_SIZE); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) break; @@ -7319,7 +8277,7 @@ class MatroskaDemuxer extends Demuxer { this.currentSegment[field] = true; assertDefinedSize(size); let slice2 = this.reader.requestSlice(dataStartPos, size); - if (slice2 instanceof Promise) + if (isThenable(slice2)) slice2 = await slice2; if (slice2) { this.readContiguousElements(slice2); @@ -7332,7 +8290,7 @@ class MatroskaDemuxer extends Demuxer { } assertDefinedSize(size); let slice2 = this.reader.requestSlice(dataStartPos, size); - if (slice2 instanceof Promise) + if (isThenable(slice2)) slice2 = await slice2; if (slice2) { this.readContiguousElements(slice2); @@ -7357,7 +8315,7 @@ class MatroskaDemuxer extends Demuxer { if (this.currentSegment[target.flag]) continue; let slice = this.reader.requestSliceRange(segmentDataStart + seekEntry.segmentPosition, MIN_HEADER_SIZE, MAX_HEADER_SIZE); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) continue; @@ -7370,7 +8328,7 @@ class MatroskaDemuxer extends Demuxer { assertDefinedSize(size); this.currentSegment[target.flag] = true; let dataSlice = this.reader.requestSlice(slice.filePos, size); - if (dataSlice instanceof Promise) + if (isThenable(dataSlice)) dataSlice = await dataSlice; if (!dataSlice) continue; @@ -7424,7 +8382,7 @@ class MatroskaDemuxer extends Demuxer { return segment.lastReadCluster; } let headerSlice = this.reader.requestSliceRange(startPos, MIN_HEADER_SIZE, MAX_HEADER_SIZE); - if (headerSlice instanceof Promise) + if (isThenable(headerSlice)) headerSlice = await headerSlice; assert(headerSlice); const elementStartPos = startPos; @@ -7439,7 +8397,7 @@ class MatroskaDemuxer extends Demuxer { size = nextElementPos.pos - dataStartPos; } let dataSlice = this.reader.requestSlice(dataStartPos, size); - if (dataSlice instanceof Promise) + if (isThenable(dataSlice)) dataSlice = await dataSlice; const cluster = { segment, @@ -7600,6 +8558,7 @@ class MatroskaDemuxer extends Demuxer { data: frameData, lacing: BlockLacing.None, decoded: true, + postProcessed: false, mainAdditional: originalBlock.mainAdditional }); } @@ -7615,7 +8574,7 @@ class MatroskaDemuxer extends Demuxer { continue; } let slice = this.reader.requestSliceRange(segment.dataStartPos + seekEntry.segmentPosition, MIN_HEADER_SIZE, MAX_HEADER_SIZE); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) continue; @@ -7627,7 +8586,7 @@ class MatroskaDemuxer extends Demuxer { assert(!this.currentSegment); this.currentSegment = segment; let dataSlice = this.reader.requestSlice(slice.filePos, size); - if (dataSlice instanceof Promise) + if (isThenable(dataSlice)) dataSlice = await dataSlice; if (dataSlice) { this.readContiguousElements(dataSlice); @@ -7743,7 +8702,7 @@ class MatroskaDemuxer extends Demuxer { if (this.currentTrack.decodingInstructions.some((instruction) => { return instruction.data?.type !== "decompress" || instruction.scope !== ContentEncodingScope.Block || instruction.data.algorithm !== ContentCompAlgo.HeaderStripping; })) { - console.warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`); + Logging._warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`); this.currentTrack = null; } if (this.currentTrack && this.currentTrack.id !== -1 && this.currentTrack.codecId && this.currentTrack.info) { @@ -7775,6 +8734,12 @@ class MatroskaDemuxer extends Demuxer { this.currentTrack.info.codec = "vp9"; } else if (codecIdWithoutSuffix === CODEC_STRING_MAP.av1) { this.currentTrack.info.codec = "av1"; + } else if (codecIdWithoutSuffix === CODEC_STRING_MAP.prores) { + const format = this.currentTrack.codecPrivate ? textDecoder.decode(this.currentTrack.codecPrivate) : ""; + if (PRORES_FOURCCS.includes(format)) { + this.currentTrack.info.codec = "prores"; + this.currentTrack.info.proresFormat = format; + } } const videoTrack = this.currentTrack; this.currentTrack.trackBacking = new MatroskaVideoTrackBacking(videoTrack); @@ -7805,6 +8770,13 @@ class MatroskaDemuxer extends Demuxer { } else if (codecIdWithoutSuffix === CODEC_STRING_MAP.eac3) { this.currentTrack.info.codec = "eac3"; this.currentTrack.info.codecDescription = this.currentTrack.codecPrivate; + } else if (codecIdWithoutSuffix === CODEC_STRING_MAP.dts) { + this.currentTrack.info.codec = "dts"; + if (this.currentTrack.codecId === "A_DTS/EXPRESS") { + this.currentTrack.info.dtsFormat = "dtse"; + } else if (this.currentTrack.codecId === "A_DTS/LOSSLESS") { + this.currentTrack.info.dtsFormat = "dtsl"; + } } else if (this.currentTrack.codecId === "A_PCM/INT/LIT") { if (this.currentTrack.info.bitDepth === 8) { this.currentTrack.info.codec = "pcm-u8"; @@ -7865,8 +8837,9 @@ class MatroskaDemuxer extends Demuxer { rotation: 0, codec: null, codecDescription: null, - colorSpace: null, - alphaMode: false + colorSpace: { ...EMPTY_COLOR_SPACE }, + alphaMode: false, + proresFormat: null }; } else if (type === 2) { this.currentTrack.info = { @@ -7878,7 +8851,8 @@ class MatroskaDemuxer extends Demuxer { bitDepth: -1, codec: null, codecDescription: null, - aacCodecInfo: null + aacCodecInfo: null, + dtsFormat: null }; } } @@ -8043,41 +9017,41 @@ class MatroskaDemuxer extends Demuxer { { if (this.currentTrack?.info?.type !== "video") break; - this.currentTrack.info.colorSpace = {}; this.readContiguousElements(slice.slice(dataStartPos, size)); } break; case EBMLId.MatrixCoefficients: { - if (this.currentTrack?.info?.type !== "video" || !this.currentTrack.info.colorSpace) + if (this.currentTrack?.info?.type !== "video") break; const matrixCoefficients = readUnsignedInt(slice, size); - const mapped = MATRIX_COEFFICIENTS_MAP_INVERSE[matrixCoefficients] ?? null; + const mapped = MATRIX_COEFFICIENTS_MAP_INVERSE[matrixCoefficients]; this.currentTrack.info.colorSpace.matrix = mapped; } break; case EBMLId.Range: { - if (this.currentTrack?.info?.type !== "video" || !this.currentTrack.info.colorSpace) + if (this.currentTrack?.info?.type !== "video") break; - this.currentTrack.info.colorSpace.fullRange = readUnsignedInt(slice, size) === 2; + const range = readUnsignedInt(slice, size); + this.currentTrack.info.colorSpace.fullRange = range === 1 || range === 2 ? range === 2 : void 0; } break; case EBMLId.TransferCharacteristics: { - if (this.currentTrack?.info?.type !== "video" || !this.currentTrack.info.colorSpace) + if (this.currentTrack?.info?.type !== "video") break; const transferCharacteristics = readUnsignedInt(slice, size); - const mapped = TRANSFER_CHARACTERISTICS_MAP_INVERSE[transferCharacteristics] ?? null; + const mapped = TRANSFER_CHARACTERISTICS_MAP_INVERSE[transferCharacteristics]; this.currentTrack.info.colorSpace.transfer = mapped; } break; case EBMLId.Primaries: { - if (this.currentTrack?.info?.type !== "video" || !this.currentTrack.info.colorSpace) + if (this.currentTrack?.info?.type !== "video") break; const primaries = readUnsignedInt(slice, size); - const mapped = COLOR_PRIMARIES_MAP_INVERSE[primaries] ?? null; + const mapped = COLOR_PRIMARIES_MAP_INVERSE[primaries]; this.currentTrack.info.colorSpace.primaries = mapped; } break; @@ -8206,6 +9180,7 @@ class MatroskaDemuxer extends Demuxer { data: blockData, lacing, decoded: !hasDecodingInstructions, + postProcessed: false, mainAdditional: null }); } @@ -8242,6 +9217,7 @@ class MatroskaDemuxer extends Demuxer { data: blockData, lacing, decoded: !hasDecodingInstructions, + postProcessed: false, mainAdditional: null }; trackData.blocks.push(this.currentBlock); @@ -8616,6 +9592,22 @@ class MatroskaDemuxer extends Demuxer { } } } + async getDurationFromMetadata(segment) { + if (segment.duration <= 0) { + return null; + } + let minTimestamp = null; + for (const track of segment.tracks) { + assert(track.trackBacking); + const firstPacket = await track.trackBacking.getFirstPacket({ metadataOnly: true }); + if (firstPacket) { + minTimestamp = Math.min(minTimestamp ?? Infinity, firstPacket.timestamp); + } + } + let endTimestamp = segment.duration / segment.timestampFactor; + endTimestamp += minTimestamp ?? 0; + return endTimestamp; + } } class MatroskaTrackBacking { constructor(internalTrack) { @@ -8659,6 +9651,9 @@ class MatroskaTrackBacking { isRelativeToUnixEpoch() { return false; } + getUnixTimeForTimestamp() { + return null; + } getDisposition() { return this.internalTrack.disposition; } @@ -8672,14 +9667,7 @@ class MatroskaTrackBacking { return null; } async getDurationFromMetadata() { - const segment = this.internalTrack.segment; - if (segment.duration <= 0) { - return null; - } - let endTimestamp = segment.duration / segment.timestampFactor; - const firstPacket = await this.getFirstPacket({ metadataOnly: true }); - endTimestamp += firstPacket?.timestamp ?? 0; - return endTimestamp; + return this.internalTrack.demuxer.getDurationFromMetadata(this.internalTrack.segment); } async getLiveRefreshInterval() { return null; @@ -8824,6 +9812,23 @@ class MatroskaTrackBacking { block.data = this.internalTrack.demuxer.decodeBlockData(this.internalTrack, block.data); block.decoded = true; } + if (!block.postProcessed) { + if (this.internalTrack.info?.codec === "prores") { + const hasFrameContainer = block.data.length >= 8 && block.data[4] === 105 && block.data[5] === 99 && block.data[6] === 112 && block.data[7] === 102; + if (!hasFrameContainer) { + const newData = new Uint8Array(block.data.length + 8); + const newDataView = toDataView(newData); + newDataView.setUint32(0, newData.length, false); + newData[4] = 105; + newData[5] = 99; + newData[6] = 112; + newData[7] = 102; + newData.set(block.data, 8); + block.data = newData; + } + } + block.postProcessed = true; + } const data = options.metadataOnly ? PLACEHOLDER_DATA : block.data; const timestamp = block.timestamp / this.internalTrack.segment.timestampFactor; const duration = block.duration / this.internalTrack.segment.timestampFactor; @@ -8876,7 +9881,7 @@ class MatroskaTrackBacking { } } let slice = demuxer.reader.requestSliceRange(currentPos, MIN_HEADER_SIZE, MAX_HEADER_SIZE); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) break; @@ -8914,7 +9919,7 @@ class MatroskaTrackBacking { const endPos = dataStartPos + size; if (segment.elementEndPos === null) { let slice2 = demuxer.reader.requestSliceRange(endPos, MIN_HEADER_SIZE, MAX_HEADER_SIZE); - if (slice2 instanceof Promise) + if (isThenable(slice2)) slice2 = await slice2; if (!slice2) break; @@ -8966,44 +9971,59 @@ class MatroskaVideoTrackBacking extends MatroskaTrackBacking { return this.internalTrack.info.rotation; } async getColorSpace() { + const decoderConfig = await this.getDecoderConfig(); + if (!decoderConfig) { + return this.internalTrack.info.colorSpace; + } return { - primaries: this.internalTrack.info.colorSpace?.primaries, - transfer: this.internalTrack.info.colorSpace?.transfer, - matrix: this.internalTrack.info.colorSpace?.matrix, - fullRange: this.internalTrack.info.colorSpace?.fullRange + primaries: decoderConfig.colorSpace?.primaries, + transfer: decoderConfig.colorSpace?.transfer, + matrix: decoderConfig.colorSpace?.matrix, + fullRange: decoderConfig.colorSpace?.fullRange }; } async canBeTransparent() { - return this.internalTrack.info.alphaMode; + return this.internalTrack.info.alphaMode || this.internalTrack.info.codec === "prores" && (this.internalTrack.info.proresFormat === "ap4h" || this.internalTrack.info.proresFormat === "ap4x"); } async getDecoderConfig() { if (!this.internalTrack.info.codec) { return null; } return this.decoderConfigPromise ?? (this.decoderConfigPromise = (async () => { + var _a, _b, _c, _d; let firstPacket = null; - const needsPacketForAdditionalInfo = this.internalTrack.info.codec === "vp9" || this.internalTrack.info.codec === "av1" || this.internalTrack.info.codec === "avc" && !this.internalTrack.info.codecDescription || this.internalTrack.info.codec === "hevc" && !this.internalTrack.info.codecDescription; + const needsPacketForAdditionalInfo = this.internalTrack.info.codec === "vp9" || this.internalTrack.info.codec === "av1" || this.internalTrack.info.codec === "prores" || this.internalTrack.info.codec === "avc" && !this.internalTrack.info.codecDescription || this.internalTrack.info.codec === "hevc" && !this.internalTrack.info.codecDescription; if (needsPacketForAdditionalInfo) { firstPacket = await this.getFirstPacket({}); } + const codecInfo = { + 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, + // We don't know better (or do we?) so just assume 'avc1' + avcCodecInfo: this.internalTrack.info.codec === "avc" && firstPacket ? extractAvcDecoderConfigurationRecord(firstPacket.data) : null, + hevcCodecInfo: this.internalTrack.info.codec === "hevc" && firstPacket ? extractHevcDecoderConfigurationRecord(firstPacket.data) : null, + vp9CodecInfo: this.internalTrack.info.codec === "vp9" && firstPacket ? extractVp9CodecInfoFromPacket(firstPacket.data) : null, + av1CodecInfo: this.internalTrack.info.codec === "av1" && firstPacket ? extractAv1CodecInfoFromPacket(firstPacket.data) : null, + proresCodecInfo: this.internalTrack.info.codec === "prores" && firstPacket ? extractProresCodecInfoFromPacket(firstPacket.data) : null, + proresFormat: this.internalTrack.info.proresFormat + }; + if (!colorSpaceIsComplete(this.internalTrack.info.colorSpace)) { + const colorSpace = extractColorSpace(codecInfo); + (_a = this.internalTrack.info.colorSpace).primaries ?? (_a.primaries = colorSpace.primaries); + (_b = this.internalTrack.info.colorSpace).transfer ?? (_b.transfer = colorSpace.transfer); + (_c = this.internalTrack.info.colorSpace).matrix ?? (_c.matrix = colorSpace.matrix); + (_d = this.internalTrack.info.colorSpace).fullRange ?? (_d.fullRange = colorSpace.fullRange); + } const config = { - codec: extractVideoCodecString({ - 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, - // We don't know better (or do we?) so just assume 'avc1' - avcCodecInfo: this.internalTrack.info.codec === "avc" && firstPacket ? extractAvcDecoderConfigurationRecord(firstPacket.data) : null, - hevcCodecInfo: this.internalTrack.info.codec === "hevc" && firstPacket ? extractHevcDecoderConfigurationRecord(firstPacket.data) : null, - vp9CodecInfo: this.internalTrack.info.codec === "vp9" && firstPacket ? extractVp9CodecInfoFromPacket(firstPacket.data) : null, - av1CodecInfo: this.internalTrack.info.codec === "av1" && firstPacket ? extractAv1CodecInfoFromPacket(firstPacket.data) : null - }), + codec: extractVideoCodecString(codecInfo), codedWidth: this.internalTrack.info.width, codedHeight: this.internalTrack.info.height, description: this.internalTrack.info.codecDescription ?? void 0, - colorSpace: this.internalTrack.info.colorSpace ?? void 0 + colorSpace: this.internalTrack.info.colorSpace }; if (this.internalTrack.info.width !== this.internalTrack.info.squarePixelWidth || this.internalTrack.info.height !== this.internalTrack.info.squarePixelHeight) { config.displayAspectWidth = this.internalTrack.info.squarePixelWidth; @@ -9016,7 +10036,7 @@ class MatroskaVideoTrackBacking extends MatroskaTrackBacking { class MatroskaAudioTrackBacking extends MatroskaTrackBacking { constructor(internalTrack) { super(internalTrack); - this.decoderConfig = null; + this.decoderConfigPromise = null; this.internalTrack = internalTrack; } getType() { @@ -9035,34 +10055,43 @@ class MatroskaAudioTrackBacking extends MatroskaTrackBacking { if (!this.internalTrack.info.codec) { return null; } - return this.decoderConfig ?? (this.decoderConfig = { - codec: extractAudioCodecString({ - codec: this.internalTrack.info.codec, - codecDescription: this.internalTrack.info.codecDescription, - aacCodecInfo: this.internalTrack.info.aacCodecInfo - }), - numberOfChannels: this.internalTrack.info.numberOfChannels, - sampleRate: this.internalTrack.info.sampleRate, - description: this.internalTrack.info.codecDescription ?? void 0 - }); + return this.decoderConfigPromise ?? (this.decoderConfigPromise = (async () => { + if (this.internalTrack.info.codec === "dts" && !this.internalTrack.info.dtsFormat) { + const firstPacket = await this.getFirstPacket({}); + this.internalTrack.info.dtsFormat = firstPacket && extractDtsFourCcFromPacket(firstPacket.data); + } + return { + codec: extractAudioCodecString({ + 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 + }; + })()); } } -const readNextMp3FrameHeader = async (reader, startPos, until) => { +const readNextMp3FrameHeader = async (reader, startPos, until, ref = null) => { const CHUNK_SIZE = 2 ** 16; let currentPos = startPos; while (until === null || currentPos < until) { const maxLength = until !== null ? Math.min(CHUNK_SIZE, until - currentPos) : CHUNK_SIZE; - let slice = reader.requestSliceRange(currentPos, FRAME_HEADER_SIZE, maxLength); - if (slice instanceof Promise) + let slice = reader.requestSliceRange(currentPos, MP3_FRAME_HEADER_SIZE, maxLength); + if (isThenable(slice)) slice = await slice; - if (!slice || slice.length < FRAME_HEADER_SIZE) + if (!slice || slice.length < MP3_FRAME_HEADER_SIZE) break; - while (slice.remainingLength >= FRAME_HEADER_SIZE) { + while (slice.remainingLength >= MP3_FRAME_HEADER_SIZE) { const posBeforeRead = slice.filePos; const word = readU32Be(slice); const remainingBytes = reader.fileSize !== null ? reader.fileSize - currentPos : null; const result = readMp3FrameHeader(word, remainingBytes); - if (result.header) { + if (result.header && (!ref || // This condition helps us recover malformed streams + // https://stackoverflow.com/a/20884944 + result.header.sampleRate === ref.sampleRate && result.header.mpegVersionId === ref.mpegVersionId && result.header.layer === ref.layer && getMp3ChannelCount(result.header.channel) === getMp3ChannelCount(ref.channel))) { return { header: result.header, startPos: currentPos }; } slice.filePos = posBeforeRead + result.bytesAdvanced; @@ -9077,6 +10106,8 @@ class Mp3Demuxer extends Demuxer { this.metadataPromise = null; this.firstFrameHeader = null; this.firstFrameHeaderPos = null; + this.xingFrameHeader = null; + this.xingFrameHeaderPos = null; this.loadedSamples = []; this.metadataTags = null; this.xingData = null; @@ -9092,6 +10123,10 @@ class Mp3Demuxer extends Demuxer { while (!this.firstFrameHeader && !this.lastSampleLoaded) { await this.advanceReader(); } + if (!this.firstFrameHeader && this.xingFrameHeader) { + this.firstFrameHeader = this.xingFrameHeader; + this.firstFrameHeaderPos = this.xingFrameHeaderPos; + } if (!this.firstFrameHeader) { throw new Error("No valid MP3 frame found."); } @@ -9102,7 +10137,7 @@ class Mp3Demuxer extends Demuxer { if (this.lastLoadedPos === 0) { while (true) { let slice2 = this.reader.requestSlice(this.lastLoadedPos, ID3_V2_HEADER_SIZE); - if (slice2 instanceof Promise) + if (isThenable(slice2)) slice2 = await slice2; if (!slice2) { this.lastSampleLoaded = true; @@ -9115,7 +10150,7 @@ class Mp3Demuxer extends Demuxer { this.lastLoadedPos = slice2.filePos + id3V2Header.size; } } - const result = await readNextMp3FrameHeader(this.reader, this.lastLoadedPos, this.reader.fileSize); + const result = await readNextMp3FrameHeader(this.reader, this.lastLoadedPos, this.reader.fileSize, this.firstFrameHeader); if (!result) { this.lastSampleLoaded = true; return; @@ -9124,15 +10159,19 @@ class Mp3Demuxer extends Demuxer { this.lastLoadedPos = result.startPos + header.totalSize - 1; const xingOffset = getXingOffset(header.mpegVersionId, header.channel); let slice = this.reader.requestSlice(result.startPos + xingOffset, 4); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (slice) { const word = readU32Be(slice); const isXing = word === XING || word === INFO; if (isXing) { + if (!this.xingFrameHeader) { + this.xingFrameHeader = header; + this.xingFrameHeaderPos = result.startPos; + } if (!this.xingData) { let xingDataSlice = this.reader.requestSlice(result.startPos + xingOffset + 4, 12); - if (xingDataSlice instanceof Promise) + if (isThenable(xingDataSlice)) xingDataSlice = await xingDataSlice; if (xingDataSlice) { const xingData = readBytes(xingDataSlice, 12); @@ -9151,9 +10190,6 @@ class Mp3Demuxer extends Demuxer { this.firstFrameHeader = header; this.firstFrameHeaderPos = result.startPos; } - if (header.sampleRate !== this.firstFrameHeader.sampleRate) { - console.warn(`MP3 changed sample rate mid-file: ${this.firstFrameHeader.sampleRate} Hz to ${header.sampleRate} Hz. Might be a bug, so please report this file.`); - } const sampleDuration = header.audioSamplesInFrame / this.firstFrameHeader.sampleRate; const sample = { timestamp: this.nextTimestampInSamples / this.firstFrameHeader.sampleRate, @@ -9184,7 +10220,7 @@ class Mp3Demuxer extends Demuxer { let id3V2HeaderFound = false; while (true) { let headerSlice = this.reader.requestSlice(currentPos, ID3_V2_HEADER_SIZE); - if (headerSlice instanceof Promise) + if (isThenable(headerSlice)) headerSlice = await headerSlice; if (!headerSlice) break; @@ -9194,7 +10230,7 @@ class Mp3Demuxer extends Demuxer { } id3V2HeaderFound = true; let contentSlice = this.reader.requestSlice(headerSlice.filePos, id3V2Header.size); - if (contentSlice instanceof Promise) + if (isThenable(contentSlice)) contentSlice = await contentSlice; if (!contentSlice) break; @@ -9203,7 +10239,7 @@ class Mp3Demuxer extends Demuxer { } if (!id3V2HeaderFound && this.reader.fileSize !== null && this.reader.fileSize >= ID3_V1_TAG_SIZE) { let slice = this.reader.requestSlice(this.reader.fileSize - ID3_V1_TAG_SIZE, ID3_V1_TAG_SIZE); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; assert(slice); const tag = readAscii(slice, 3); @@ -9237,6 +10273,9 @@ class Mp3AudioTrackBacking { isRelativeToUnixEpoch() { return false; } + getUnixTimeForTimestamp() { + return null; + } getPairingMask() { return 1n; } @@ -9280,7 +10319,7 @@ class Mp3AudioTrackBacking { } getNumberOfChannels() { assert(this.demuxer.firstFrameHeader); - return this.demuxer.firstFrameHeader.channel === 3 ? 1 : 2; + return getMp3ChannelCount(this.demuxer.firstFrameHeader.channel); } getSampleRate() { assert(this.demuxer.firstFrameHeader); @@ -9295,7 +10334,7 @@ class Mp3AudioTrackBacking { assert(this.demuxer.firstFrameHeader); return { codec: "mp3", - numberOfChannels: this.demuxer.firstFrameHeader.channel === 3 ? 1 : 2, + numberOfChannels: getMp3ChannelCount(this.demuxer.firstFrameHeader.channel), sampleRate: this.demuxer.firstFrameHeader.sampleRate }; } @@ -9312,7 +10351,7 @@ class Mp3AudioTrackBacking { data = PLACEHOLDER_DATA; } else { let slice = this.demuxer.reader.requestSlice(rawSample.dataStart, rawSample.dataSize); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) { return null; @@ -9498,7 +10537,7 @@ class OggDemuxer extends Demuxer { let currentPos = 0; while (true) { let slice = this.reader.requestSliceRange(currentPos, MIN_PAGE_HEADER_SIZE, MAX_PAGE_HEADER_SIZE); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) break; @@ -9633,7 +10672,7 @@ class OggDemuxer extends Demuxer { const chunks = []; outer: while (true) { let pageSlice = this.reader.requestSlice(currentPage.dataStartPos, currentPage.dataSize); - if (pageSlice instanceof Promise) + if (isThenable(pageSlice)) pageSlice = await pageSlice; assert(pageSlice); const pageData = readBytes(pageSlice, currentPage.dataSize); @@ -9653,7 +10692,7 @@ class OggDemuxer extends Demuxer { let currentPos = currentPage.headerStartPos + currentPage.totalSize; while (true) { let headerSlice = this.reader.requestSliceRange(currentPos, MIN_PAGE_HEADER_SIZE, MAX_PAGE_HEADER_SIZE); - if (headerSlice instanceof Promise) + if (isThenable(headerSlice)) headerSlice = await headerSlice; if (!headerSlice) { return null; @@ -9700,7 +10739,7 @@ class OggDemuxer extends Demuxer { let currentPos = lastPacket.endPage.headerStartPos + lastPacket.endPage.totalSize; while (true) { let slice = this.reader.requestSliceRange(currentPos, MIN_PAGE_HEADER_SIZE, MAX_PAGE_HEADER_SIZE); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) { return null; @@ -9763,6 +10802,9 @@ class OggAudioTrackBacking { isRelativeToUnixEpoch() { return false; } + getUnixTimeForTimestamp() { + return null; + } getPairingMask() { return 1n; } @@ -9886,7 +10928,7 @@ class OggAudioTrackBacking { while (true) { const until = Math.min(searchStartPos + MAX_PAGE_SIZE, high - MIN_PAGE_HEADER_SIZE); let searchSlice = this.demuxer.reader.requestSlice(searchStartPos, until - searchStartPos); - if (searchSlice instanceof Promise) + if (isThenable(searchSlice)) searchSlice = await searchSlice; assert(searchSlice); const found = findNextPageHeader(searchSlice, until); @@ -9895,7 +10937,7 @@ class OggAudioTrackBacking { continue outer; } let headerSlice = this.demuxer.reader.requestSliceRange(searchSlice.filePos, MIN_PAGE_HEADER_SIZE, MAX_PAGE_HEADER_SIZE); - if (headerSlice instanceof Promise) + if (isThenable(headerSlice)) headerSlice = await headerSlice; assert(headerSlice); const page = readPageHeader(headerSlice); @@ -9905,7 +10947,7 @@ class OggAudioTrackBacking { pageValid = true; } else { let pageSlice = this.demuxer.reader.requestSlice(page.headerStartPos, page.totalSize); - if (pageSlice instanceof Promise) + if (isThenable(pageSlice)) pageSlice = await pageSlice; assert(pageSlice); const bytes = readBytes(pageSlice, page.totalSize); @@ -9951,7 +10993,7 @@ class OggAudioTrackBacking { } const nextPos = currentPage.headerStartPos + currentPage.totalSize; let slice = this.demuxer.reader.requestSliceRange(nextPos, MIN_PAGE_HEADER_SIZE, MAX_PAGE_HEADER_SIZE); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; assert(slice); const nextPage = readPageHeader(slice); @@ -10179,7 +11221,7 @@ class WaveDemuxer extends Demuxer { async readMetadata() { return this.metadataPromise ?? (this.metadataPromise = (async () => { let slice = this.reader.requestSlice(0, 12); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; assert(slice); const riffType = readAscii(slice, 4); @@ -10196,7 +11238,7 @@ class WaveDemuxer extends Demuxer { let currentPos = slice.filePos; while (totalFileSize === null || currentPos < totalFileSize) { let slice2 = this.reader.requestSlice(currentPos, 8); - if (slice2 instanceof Promise) + if (isThenable(slice2)) slice2 = await slice2; if (!slice2) break; @@ -10217,7 +11259,7 @@ class WaveDemuxer extends Demuxer { } } else if (chunkId === "ds64") { let ds64Slice = this.reader.requestSlice(startPos, chunkSize); - if (ds64Slice instanceof Promise) + if (isThenable(ds64Slice)) ds64Slice = await ds64Slice; if (!ds64Slice) break; @@ -10245,7 +11287,7 @@ class WaveDemuxer extends Demuxer { } async parseFmtChunk(startPos, size, littleEndian) { let slice = this.reader.requestSlice(startPos, size); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) return; @@ -10273,6 +11315,15 @@ class WaveDemuxer extends Demuxer { if (formatTag === WaveFormat.MULAW || formatTag === WaveFormat.ALAW) { bitsPerSample = 8; } + if (formatTag !== WaveFormat.PCM && formatTag !== WaveFormat.IEEE_FLOAT && formatTag !== WaveFormat.ALAW && formatTag !== WaveFormat.MULAW) { + throw new Error(`Unsupported WAVE codec (format tag ${formatTag}). Only integer/float PCM, A-law, and μ-law are supported.`); + } + if (formatTag === WaveFormat.PCM && ![8, 16, 24, 32].includes(bitsPerSample)) { + throw new Error(`Unsupported WAVE PCM bit depth (${bitsPerSample}). Only 8, 16, 24, and 32 bits are supported.`); + } + if (formatTag === WaveFormat.IEEE_FLOAT && ![32, 64].includes(bitsPerSample)) { + throw new Error(`Unsupported WAVE float bit depth (${bitsPerSample}). Only 32 and 64 bits are supported.`); + } this.audioInfo = { format: formatTag, numberOfChannels: numChannels, @@ -10284,7 +11335,7 @@ class WaveDemuxer extends Demuxer { async parseListChunk(startPos, size, littleEndian) { var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k; let slice = this.reader.requestSlice(startPos, size); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) return; @@ -10381,7 +11432,7 @@ class WaveDemuxer extends Demuxer { } async parseId3Chunk(startPos, size) { let slice = this.reader.requestSlice(startPos, size); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) return; @@ -10417,9 +11468,11 @@ class WaveDemuxer extends Demuxer { if (this.audioInfo.format === WaveFormat.IEEE_FLOAT) { if (this.audioInfo.sampleSizeInBytes === 4) { return "pcm-f32"; + } else if (this.audioInfo.sampleSizeInBytes === 8) { + return "pcm-f64"; } } - return null; + assert(false); } async getMimeType() { return "audio/wav"; @@ -10481,6 +11534,9 @@ class WaveAudioTrackBacking { isRelativeToUnixEpoch() { return false; } + getUnixTimeForTimestamp() { + return null; + } getPairingMask() { return 1n; } @@ -10518,7 +11574,7 @@ class WaveAudioTrackBacking { const sizeInBytes = Math.min(PACKET_SIZE_IN_FRAMES * this.demuxer.audioInfo.blockSizeInBytes, this.demuxer.dataSize - startOffset); if (this.demuxer.reader.fileSize === null) { let slice = this.demuxer.reader.requestSlice(this.demuxer.dataStart + startOffset, sizeInBytes); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) { return null; @@ -10529,7 +11585,7 @@ class WaveAudioTrackBacking { data = PLACEHOLDER_DATA; } else { let slice = this.demuxer.reader.requestSlice(this.demuxer.dataStart + startOffset, sizeInBytes); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; assert(slice); data = readBytes(slice, sizeInBytes); @@ -10658,7 +11714,7 @@ class AdtsDemuxer extends Demuxer { if (this.lastLoadedPos === 0) { while (true) { let slice2 = this.reader.requestSlice(this.lastLoadedPos, ID3_V2_HEADER_SIZE); - if (slice2 instanceof Promise) + if (isThenable(slice2)) slice2 = await slice2; if (!slice2) { this.lastSampleLoaded = true; @@ -10672,7 +11728,7 @@ class AdtsDemuxer extends Demuxer { } } let slice = this.reader.requestSliceRange(this.lastLoadedPos, MIN_ADTS_FRAME_HEADER_SIZE, MAX_ADTS_FRAME_HEADER_SIZE); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) { this.lastSampleLoaded = true; @@ -10721,7 +11777,7 @@ class AdtsDemuxer extends Demuxer { let currentPos = 0; while (true) { let headerSlice = this.reader.requestSlice(currentPos, ID3_V2_HEADER_SIZE); - if (headerSlice instanceof Promise) + if (isThenable(headerSlice)) headerSlice = await headerSlice; if (!headerSlice) break; @@ -10730,7 +11786,7 @@ class AdtsDemuxer extends Demuxer { break; } let contentSlice = this.reader.requestSlice(headerSlice.filePos, id3V2Header.size); - if (contentSlice instanceof Promise) + if (isThenable(contentSlice)) contentSlice = await contentSlice; if (!contentSlice) break; @@ -10763,6 +11819,9 @@ class AdtsAudioTrackBacking { isRelativeToUnixEpoch() { return false; } + getUnixTimeForTimestamp() { + return null; + } getPairingMask() { return 1n; } @@ -10829,7 +11888,7 @@ class AdtsAudioTrackBacking { data = PLACEHOLDER_DATA; } else { let slice = this.demuxer.reader.requestSlice(rawSample.dataStart, rawSample.dataSize); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) { return null; @@ -11037,12 +12096,32 @@ class FlacDemuxer extends Demuxer { return "audio/flac"; } async readMetadata() { - let currentPos = 4; return this.metadataPromise ?? (this.metadataPromise = (async () => { var _a; + let currentPos = 0; + while (true) { + let headerSlice = this.reader.requestSlice(currentPos, ID3_V2_HEADER_SIZE); + if (isThenable(headerSlice)) + headerSlice = await headerSlice; + if (!headerSlice) { + this.lastSampleLoaded = true; + return; + } + const id3V2Header = readId3V2Header(headerSlice); + if (!id3V2Header) { + break; + } + let contentSlice = this.reader.requestSlice(headerSlice.filePos, id3V2Header.size); + if (isThenable(contentSlice)) + contentSlice = await contentSlice; + assert(contentSlice); + parseId3V2Tag(contentSlice, id3V2Header, this.metadataTags); + currentPos = headerSlice.filePos + id3V2Header.size; + } + currentPos += 4; while (this.reader.fileSize === null || currentPos < this.reader.fileSize) { let sizeSlice = this.reader.requestSlice(currentPos, 4); - if (sizeSlice instanceof Promise) + if (isThenable(sizeSlice)) sizeSlice = await sizeSlice; currentPos += 4; if (sizeSlice === null) { @@ -11056,7 +12135,7 @@ class FlacDemuxer extends Demuxer { switch (metaBlockType) { case FlacBlockType.STREAMINFO: { let streamInfoBlock = this.reader.requestSlice(currentPos, size); - if (streamInfoBlock instanceof Promise) + if (isThenable(streamInfoBlock)) streamInfoBlock = await streamInfoBlock; assert(streamInfoBlock); if (streamInfoBlock === null) { @@ -11092,7 +12171,7 @@ class FlacDemuxer extends Demuxer { } case FlacBlockType.VORBIS_COMMENT: { let vorbisCommentBlock = this.reader.requestSlice(currentPos, size); - if (vorbisCommentBlock instanceof Promise) + if (isThenable(vorbisCommentBlock)) vorbisCommentBlock = await vorbisCommentBlock; assert(vorbisCommentBlock); readVorbisComments(readBytes(vorbisCommentBlock, size), this.metadataTags); @@ -11100,7 +12179,7 @@ class FlacDemuxer extends Demuxer { } case FlacBlockType.PICTURE: { let pictureBlock = this.reader.requestSlice(currentPos, size); - if (pictureBlock instanceof Promise) + if (isThenable(pictureBlock)) pictureBlock = await pictureBlock; assert(pictureBlock); const pictureType = readU32Be(pictureBlock); @@ -11334,6 +12413,9 @@ class FlacAudioTrackBacking { isRelativeToUnixEpoch() { return false; } + getUnixTimeForTimestamp() { + return null; + } getPairingMask() { return 1n; } @@ -11370,7 +12452,7 @@ class FlacAudioTrackBacking { async getPacket(timestamp, options) { assert(this.demuxer.audioInfo); if (timestamp < 0) { - throw new Error("Timestamp cannot be negative"); + return null; } const release = await this.demuxer.readingMutex.acquire(); try { @@ -11427,7 +12509,7 @@ class FlacAudioTrackBacking { data = PLACEHOLDER_DATA; } else { let slice = this.demuxer.reader.requestSlice(rawSample.byteOffset, rawSample.byteSize); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) { return null; @@ -11447,6 +12529,7 @@ class FlacAudioTrackBacking { } } const TIMESCALE = 9e4; +const TIMESTAMP_MODULUS = 2 ** 33; const TS_PACKET_SIZE = 188; const buildMpegTsMimeType = (codecStrings) => { let string = "video/MP2T"; @@ -11457,6 +12540,15 @@ const buildMpegTsMimeType = (codecStrings) => { return string; }; const MISSING_PTS_ERROR_MESSAGE = "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."; +const REGISTRATION_DESCRIPTOR_TAG = 5; +const HDMV_FORMAT_IDENTIFIER = 1212435798; +const HDPR_FORMAT_IDENTIFIER = 1212436562; +const DTS_FORMAT_IDENTIFIER_PREFIX = 1146376960; +const BLU_RAY_DTS_STREAM_TYPES = /* @__PURE__ */ new Set([ + 133, + 134, + 162 +]); const ignoredStreamTypes = /* @__PURE__ */ new Set(); class MpegTsDemuxer extends Demuxer { constructor(input) { @@ -11469,13 +12561,14 @@ class MpegTsDemuxer extends Demuxer { this.sectionEndPositions = []; this.seekChunkSize = 5 * 1024 * 1024; this.minReferencePointByteDistance = -1; + this.timestampWrapInfo = null; this.reader = input._reader; } async readMetadata() { return this.metadataPromise ?? (this.metadataPromise = (async () => { const lengthToCheck = TS_PACKET_SIZE + 16 + 1; let startingSlice = this.reader.requestSlice(0, lengthToCheck); - if (startingSlice instanceof Promise) + if (isThenable(startingSlice)) startingSlice = await startingSlice; assert(startingSlice); const startingBytes = readBytes(startingSlice, lengthToCheck); @@ -11506,6 +12599,10 @@ class MpegTsDemuxer extends Demuxer { currentPos += this.packetStride; continue; } + if (hasProgramMap && !this.elementaryStreams.some((x) => x.pid === packetHeader.pid)) { + currentPos += this.packetStride; + continue; + } const section = await this.readSection(currentPos, true, !hasProgramMap); if (!section) { break; @@ -11556,7 +12653,19 @@ class MpegTsDemuxer extends Demuxer { bitstream.readBits(13); bitstream.skipBits(6); const programInfoLength = bitstream.readBits(10); - bitstream.skipBits(8 * programInfoLength); + const programInfoEndPos = bitstream.pos + 8 * programInfoLength; + let isBluRayProgram = false; + while (bitstream.pos < programInfoEndPos) { + const descriptorTag = bitstream.readBits(8); + const descriptorLength = bitstream.readBits(8); + const descriptorEndPos = bitstream.pos + 8 * descriptorLength; + if (descriptorTag === REGISTRATION_DESCRIPTOR_TAG && descriptorLength >= 4) { + const formatIdentifier = bitstream.readBits(32); + isBluRayProgram || (isBluRayProgram = formatIdentifier === HDMV_FORMAT_IDENTIFIER || formatIdentifier === HDPR_FORMAT_IDENTIFIER); + } + bitstream.pos = descriptorEndPos; + } + bitstream.pos = programInfoEndPos; while (8 * (sectionLength + BYTES_BEFORE_SECTION_LENGTH) - bitstream.pos > BITS_IN_CRC_32) { const streamType = bitstream.readBits(8); bitstream.skipBits(3); @@ -11566,18 +12675,26 @@ class MpegTsDemuxer extends Demuxer { const esInfoEndPos = bitstream.pos + 8 * esInfoLength; let hasAc3Descriptor = false; let hasEac3Descriptor = false; + let hasDtsDescriptor = false; while (bitstream.pos < esInfoEndPos) { const descriptorTag = bitstream.readBits(8); const descriptorLength = bitstream.readBits(8); + const descriptorEndPos = bitstream.pos + 8 * descriptorLength; if (descriptorTag === 106) { hasAc3Descriptor = true; } else if (descriptorTag === 122 || descriptorTag === 204) { hasEac3Descriptor = true; + } else if (descriptorTag === 123) { + hasDtsDescriptor = true; + } else if (descriptorTag === REGISTRATION_DESCRIPTOR_TAG && descriptorLength >= 4) { + const formatIdentifier = bitstream.readBits(32); + hasDtsDescriptor || (hasDtsDescriptor = (formatIdentifier & 4294967040) === DTS_FORMAT_IDENTIFIER_PREFIX); } - bitstream.skipBits(8 * descriptorLength); + bitstream.pos = descriptorEndPos; } let info = null; - switch (streamType) { + const effectiveStreamType = isBluRayProgram && BLU_RAY_DTS_STREAM_TYPES.has(streamType) ? 130 : streamType; + switch (effectiveStreamType) { case 27: case 36: { @@ -11607,24 +12724,27 @@ class MpegTsDemuxer extends Demuxer { case 15: case 129: case 135: + case 130: + case 138: { let codec; - if (streamType === 3 || streamType === 4) { + if (effectiveStreamType === 3 || effectiveStreamType === 4) { codec = "mp3"; - } else if (streamType === 15) { + } else if (effectiveStreamType === 15) { codec = "aac"; - } else if (streamType === 129) { + } else if (effectiveStreamType === 129) { codec = "ac3"; - } else if (streamType === 135) { + } else if (effectiveStreamType === 135) { codec = "eac3"; } else { - throw new Error("Unreachable."); + codec = "dts"; } info = { type: "audio", codec, decoderConfig: null, aacCodecInfo: null, + dtsFormat: null, numberOfChannels: -1, sampleRate: -1 }; @@ -11638,6 +12758,7 @@ class MpegTsDemuxer extends Demuxer { codec: "eac3", decoderConfig: null, aacCodecInfo: null, + dtsFormat: null, numberOfChannels: -1, sampleRate: -1 }; @@ -11647,6 +12768,17 @@ class MpegTsDemuxer extends Demuxer { codec: "ac3", decoderConfig: null, aacCodecInfo: null, + dtsFormat: null, + numberOfChannels: -1, + sampleRate: -1 + }; + } else if (hasDtsDescriptor) { + info = { + type: "audio", + codec: "dts", + decoderConfig: null, + aacCodecInfo: null, + dtsFormat: null, numberOfChannels: -1, sampleRate: -1 }; @@ -11655,7 +12787,7 @@ class MpegTsDemuxer extends Demuxer { break; default: { if (!ignoredStreamTypes.has(streamType)) { - console.warn(`Note: MPEG-TS streams with stream_type 0x${streamType.toString(16)} are not currently supported.`); + Logging._warn(`Note: MPEG-TS streams with stream_type 0x${streamType.toString(16)} are not currently supported.`); ignoredStreamTypes.add(streamType); } } @@ -11677,7 +12809,7 @@ class MpegTsDemuxer extends Demuxer { } else { const elementaryStream = this.elementaryStreams.find((x) => x.pid === section.pid); outer: if (elementaryStream && !elementaryStream.initialized) { - const pesPacket = readPesPacket(section, true); + const pesPacket = readPesPacket(this, section, true); if (!pesPacket) { throw new Error(`Couldn't read first PES packet for Elementary Stream with PID ${elementaryStream.pid}`); } @@ -11774,7 +12906,8 @@ class MpegTsDemuxer extends Demuxer { avcCodecInfo: elementaryStream.info.avcCodecInfo, hevcCodecInfo: elementaryStream.info.hevcCodecInfo, vp9CodecInfo: null, - av1CodecInfo: null + av1CodecInfo: null, + proresFormat: null }), codedWidth: elementaryStream.info.width, codedHeight: elementaryStream.info.height, @@ -11808,7 +12941,7 @@ class MpegTsDemuxer extends Demuxer { if (!result.header) { throw new Error("Invalid MP3 audio stream; could not read frame header from first packet."); } - elementaryStream.info.numberOfChannels = result.header.channel === 3 ? 1 : 2; + elementaryStream.info.numberOfChannels = getMp3ChannelCount(result.header.channel); elementaryStream.info.sampleRate = result.header.sampleRate; } else if (elementaryStream.info.codec === "ac3") { const frameInfo = parseAc3SyncFrame(context.suppliedPacket.data); @@ -11831,6 +12964,16 @@ class MpegTsDemuxer extends Demuxer { } elementaryStream.info.numberOfChannels = getEac3ChannelCount(frameInfo); elementaryStream.info.sampleRate = sampleRate; + } else if (elementaryStream.info.codec === "dts") { + const frameInfo = parseDtsFrame(context.suppliedPacket.data); + if (!frameInfo) { + throw new Error("Invalid DTS audio stream; could not read frame header from first packet."); + } + elementaryStream.info.numberOfChannels = frameInfo.numberOfChannels; + elementaryStream.info.sampleRate = frameInfo.sampleRate; + if (frameInfo.core) { + elementaryStream.info.dtsFormat = frameInfo.hasExtensions ? "dtsh" : "dtsc"; + } } else { throw new Error("Unhandled."); } @@ -11838,7 +12981,8 @@ class MpegTsDemuxer extends Demuxer { codec: extractAudioCodecString({ codec: elementaryStream.info.codec, codecDescription: null, - aacCodecInfo: elementaryStream.info.aacCodecInfo + aacCodecInfo: elementaryStream.info.aacCodecInfo, + dtsFormat: elementaryStream.info.dtsFormat }), numberOfChannels: elementaryStream.info.numberOfChannels, sampleRate: elementaryStream.info.sampleRate @@ -11860,6 +13004,9 @@ class MpegTsDemuxer extends Demuxer { throw new Error("No Program Map Table found in the file."); } for (const stream of this.elementaryStreams) { + if (!stream.initialized) { + continue; + } if (stream.info.type === "video") { this.trackBackingEntries.push(new MpegTsVideoTrackBacking(stream)); } else { @@ -11969,7 +13116,7 @@ class MpegTsDemuxer extends Demuxer { } async readPacketHeader(pos) { let slice = this.reader.requestSlice(pos, 4); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) { return null; @@ -11991,7 +13138,7 @@ class MpegTsDemuxer extends Demuxer { } async readPacket(pos) { let slice = this.reader.requestSlice(pos, TS_PACKET_SIZE); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) { return null; @@ -12013,8 +13160,22 @@ class MpegTsDemuxer extends Demuxer { body: bytes.subarray(4) }; } + normalizeTimestamp(timestamp) { + if (!this.timestampWrapInfo) { + const tolerance = 60 * TIMESCALE; + this.timestampWrapInfo = { + reference: timestamp - tolerance, + offset: timestamp >= TIMESTAMP_MODULUS - tolerance ? -TIMESTAMP_MODULUS : TIMESTAMP_MODULUS + }; + } + const { reference, offset } = this.timestampWrapInfo; + if (offset < 0 && timestamp >= reference || offset > 0 && timestamp < reference) { + return timestamp + offset; + } + return timestamp; + } } -const readPesPacketHeader = (section, expectPts) => { +const readPesPacketHeader = (demuxer, section, expectPts) => { if (section.payload.byteLength < 3) { return null; } @@ -12040,6 +13201,7 @@ const readPesPacketHeader = (section, expectPts) => { pts += bitstream.readBits(15) * (1 << 15); bitstream.skipBits(1); pts += bitstream.readBits(15); + pts = demuxer.normalizeTimestamp(pts); } else { if (expectPts) { throw new Error(MISSING_PTS_ERROR_MESSAGE); @@ -12052,9 +13214,9 @@ const readPesPacketHeader = (section, expectPts) => { randomAccessIndicator: section.randomAccessIndicator }; }; -const readPesPacket = (section, expectPts) => { +const readPesPacket = (demuxer, section, expectPts) => { assert(section.endPos !== null); - const header = readPesPacketHeader(section, expectPts); + const header = readPesPacketHeader(demuxer, section, expectPts); if (!header) { return null; } @@ -12128,6 +13290,9 @@ class MpegTsTrackBacking { isRelativeToUnixEpoch() { return false; } + getUnixTimeForTimestamp() { + return null; + } getPairingMask() { return 1n; } @@ -12155,7 +13320,7 @@ class MpegTsTrackBacking { async getFirstPacket(options) { const section = this.elementaryStream.firstSection; assert(section); - const pesPacket = readPesPacket(section, true); + const pesPacket = readPesPacket(this.elementaryStream.demuxer, section, true); assert(pesPacket); const context = new PacketReadingContext(this.elementaryStream, pesPacket); const buffer = new PacketBuffer(this, context); @@ -12188,7 +13353,7 @@ class MpegTsTrackBacking { const demuxer = this.elementaryStream.demuxer; const section = await demuxer.readSection(sectionStartPos, true); assert(section); - const pesPacket = readPesPacket(section, true); + const pesPacket = readPesPacket(demuxer, section, true); assert(pesPacket); const context = new PacketReadingContext(this.elementaryStream, pesPacket); buffer = new PacketBuffer(this, context); @@ -12246,7 +13411,7 @@ class MpegTsTrackBacking { if (!section) { return null; } - const pesPacketHeader = readPesPacketHeader(section, false); + const pesPacketHeader = readPesPacketHeader(demuxer, section, false); if (pesPacketHeader && pesPacketHeader.pts !== null) { return { pesPacketHeader, @@ -12260,7 +13425,7 @@ class MpegTsTrackBacking { }; const firstSection = this.elementaryStream.firstSection; assert(firstSection); - const firstPesPacketHeader = readPesPacketHeader(firstSection, true); + const firstPesPacketHeader = readPesPacketHeader(demuxer, firstSection, true); assert(firstPesPacketHeader); if (searchPts < firstPesPacketHeader.pts) { return null; @@ -12308,7 +13473,7 @@ class MpegTsTrackBacking { const retrieveEncodedPacket = async (sectionStartPos, predicate) => { const section = await demuxer.readSection(sectionStartPos, true); assert(section); - const pesPacket = readPesPacket(section, true); + const pesPacket = readPesPacket(demuxer, section, true); assert(pesPacket); const context = new PacketReadingContext(this.elementaryStream, pesPacket); const buffer = new PacketBuffer(this, context); @@ -12350,7 +13515,7 @@ class MpegTsTrackBacking { if (packetHeader.pid === pid && packetHeader.payloadUnitStartIndicator === 1) { const section = await demuxer.readSection(currentPos, false); if (section) { - const nextPesHeader = readPesPacketHeader(section, false); + const nextPesHeader = readPesPacketHeader(demuxer, section, false); if (nextPesHeader && nextPesHeader.pts !== null) { if (nextPesHeader.pts > searchPts) { break outer; @@ -12374,7 +13539,7 @@ class MpegTsTrackBacking { if (packetHeader.pid === pid && packetHeader.payloadUnitStartIndicator === 1) { const section = await demuxer.readSection(pos, false); if (section) { - const header = readPesPacketHeader(section, false); + const header = readPesPacketHeader(demuxer, section, false); if (header && header.pts !== null) { currentPesHeader = header; break; @@ -12414,7 +13579,7 @@ class MpegTsTrackBacking { isKeyPacket = pesHeader.randomAccessIndicator === 1; } else { assert(pesHeaderSection); - const pesPacket = readPesPacket(pesHeaderSection, true); + const pesPacket = readPesPacket(demuxer, pesHeaderSection, true); assert(pesPacket); const context = new PacketReadingContext(this.elementaryStream, pesPacket); await context.markNextPacket(); @@ -12442,7 +13607,7 @@ class MpegTsTrackBacking { if (packetHeader.pid === pid && packetHeader.payloadUnitStartIndicator === 1) { const section = await demuxer.readSection(currentPos, readSectionsInFull); if (section) { - const nextPesHeader = readPesPacketHeader(section, false); + const nextPesHeader = readPesPacketHeader(demuxer, section, false); if (nextPesHeader && nextPesHeader.pts !== null) { pesHeader = nextPesHeader; pesHeaderSection = section; @@ -12467,7 +13632,7 @@ class MpegTsTrackBacking { if (packetHeader.pid === pid && packetHeader.payloadUnitStartIndicator === 1) { const section = await demuxer.readSection(pos, readSectionsInFull); if (section) { - const header = readPesPacketHeader(section, false); + const header = readPesPacketHeader(demuxer, section, false); if (header && header.pts !== null) { startPesHeader = header; break; @@ -12625,7 +13790,7 @@ class PacketReadingContext { if (!nextSection) { return; } - const nextPesPacket = readPesPacket(nextSection, false); + const nextPesPacket = readPesPacket(this.demuxer, nextSection, false); if (nextPesPacket) { pesPacket = nextPesPacket; break; @@ -12712,10 +13877,13 @@ class PacketReadingContext { if (codec !== "avc" && codec !== "hevc") { throw new Error("Unhandled."); } + const nalHeaderSize = codec === "avc" ? 1 : 2; let packetStartPos = null; + let frameStartFound = false; + let lastFirstMacroblockInSlice = 0; while (true) { let remaining = this.ensureBuffered(CHUNK_SIZE); - if (remaining instanceof Promise) + if (isThenable(remaining)) remaining = await remaining; if (remaining === 0) { break; @@ -12731,7 +13899,7 @@ class PacketReadingContext { } i = zeroIndex; const posBeforeZero = chunkStartPos + i; - if (i + 4 >= length) { + if (i + 3 >= length) { this.seekTo(posBeforeZero); break; } @@ -12739,32 +13907,68 @@ class PacketReadingContext { const b2 = chunk[i + 2]; const b3 = chunk[i + 3]; let startCodeLength = 0; - let nalUnitTypeByte = null; if (b1 === 0 && b2 === 0 && b3 === 1) { startCodeLength = 4; - nalUnitTypeByte = chunk[i + 4]; } else if (b1 === 0 && b2 === 1) { startCodeLength = 3; - nalUnitTypeByte = b3; } if (startCodeLength === 0) { i++; continue; } const startCodePos = posBeforeZero; - if (packetStartPos === null) { - packetStartPos = startCodePos; - i += startCodeLength; - continue; + packetStartPos ?? (packetStartPos = startCodePos); + const nalHeaderStart = i + startCodeLength; + const payloadStart = nalHeaderStart + nalHeaderSize; + const AVC_SLICE_HEADER_PEEK_SIZE = 6; + const bytesNeeded = payloadStart + (codec === "avc" ? AVC_SLICE_HEADER_PEEK_SIZE : 1); + if (bytesNeeded > length) { + this.seekTo(posBeforeZero); + break; } - if (nalUnitTypeByte !== null) { - const nalUnitType = codec === "avc" ? extractNalUnitTypeForAvc(nalUnitTypeByte) : extractNalUnitTypeForHevc(nalUnitTypeByte); - const isAud = codec === "avc" ? nalUnitType === AvcNalUnitType.AUD : nalUnitType === HevcNalUnitType.AUD_NUT; - if (isAud) { - const packetLength = startCodePos - packetStartPos; - this.seekTo(packetStartPos); - return this.supplyPacket(packetLength, 0); + const headerByte0 = chunk[nalHeaderStart]; + let nalUnitType; + let isSlice; + let isAccessUnitStart; + if (codec === "avc") { + nalUnitType = extractNalUnitTypeForAvc(headerByte0); + isSlice = nalUnitType === AvcNalUnitType.NON_IDR_SLICE || nalUnitType === AvcNalUnitType.SLICE_DPA || nalUnitType === AvcNalUnitType.IDR; + isAccessUnitStart = nalUnitType === AvcNalUnitType.SEI || nalUnitType === AvcNalUnitType.SPS || nalUnitType === AvcNalUnitType.PPS || nalUnitType === AvcNalUnitType.AUD; + } else { + nalUnitType = extractNalUnitTypeForHevc(headerByte0); + const layerId = (headerByte0 & 1) << 5 | chunk[nalHeaderStart + 1] >> 3; + if (layerId > 0) { + i += startCodeLength; + continue; } + isSlice = nalUnitType <= HevcNalUnitType.RASL_R || nalUnitType >= HevcNalUnitType.BLA_W_LP && nalUnitType <= 21; + isAccessUnitStart = nalUnitType >= HevcNalUnitType.VPS_NUT && nalUnitType <= 37 || nalUnitType === HevcNalUnitType.PREFIX_SEI_NUT || nalUnitType >= 41 && nalUnitType <= 44 || nalUnitType >= 48 && nalUnitType <= 55; + } + let isFrameBoundary = false; + if (isSlice) { + let startsNewPicture; + if (codec === "avc") { + const headerBytes = chunk.subarray(payloadStart, payloadStart + AVC_SLICE_HEADER_PEEK_SIZE); + const firstMacroblockInSlice = readExpGolomb(new Bitstream(headerBytes)); + startsNewPicture = !frameStartFound || firstMacroblockInSlice <= lastFirstMacroblockInSlice; + lastFirstMacroblockInSlice = firstMacroblockInSlice; + } else { + startsNewPicture = chunk[payloadStart] >> 7 === 1; + } + if (startsNewPicture) { + if (frameStartFound) { + isFrameBoundary = true; + } else { + frameStartFound = true; + } + } + } else if (isAccessUnitStart && frameStartFound) { + isFrameBoundary = true; + } + if (isFrameBoundary) { + const packetLength = startCodePos - packetStartPos; + this.seekTo(packetStartPos); + return this.supplyPacket(packetLength, 0); } i += startCodeLength; } @@ -12772,7 +13976,7 @@ class PacketReadingContext { break; } } - if (packetStartPos !== null) { + if (packetStartPos !== null && this.endPos > packetStartPos) { const packetLength = this.endPos - packetStartPos; this.seekTo(packetStartPos); return this.supplyPacket(packetLength, 0); @@ -12782,7 +13986,7 @@ class PacketReadingContext { const CHUNK_SIZE = 128; while (true) { let remaining = this.ensureBuffered(CHUNK_SIZE); - if (remaining instanceof Promise) + if (isThenable(remaining)) remaining = await remaining; const startPos = this.currentPos; while (this.currentPos - startPos < remaining) { @@ -12794,7 +13998,7 @@ class PacketReadingContext { this.skip(-1); const possibleHeaderStartPos = this.currentPos; let remaining2 = this.ensureBuffered(MAX_ADTS_FRAME_HEADER_SIZE); - if (remaining2 instanceof Promise) + if (isThenable(remaining2)) remaining2 = await remaining2; if (remaining2 < MAX_ADTS_FRAME_HEADER_SIZE) { return; @@ -12804,7 +14008,7 @@ class PacketReadingContext { if (header) { this.seekTo(possibleHeaderStartPos); let remaining3 = this.ensureBuffered(header.frameLength); - if (remaining3 instanceof Promise) + if (isThenable(remaining3)) remaining3 = await remaining3; return this.supplyPacket(remaining3, Math.round(SAMPLES_PER_AAC_FRAME * TIMESCALE / elementaryStream.info.sampleRate)); } else { @@ -12816,19 +14020,19 @@ class PacketReadingContext { } this.skip(-1); const possibleHeaderStartPos = this.currentPos; - let remaining2 = this.ensureBuffered(FRAME_HEADER_SIZE); - if (remaining2 instanceof Promise) + let remaining2 = this.ensureBuffered(MP3_FRAME_HEADER_SIZE); + if (isThenable(remaining2)) remaining2 = await remaining2; - if (remaining2 < FRAME_HEADER_SIZE) { + if (remaining2 < MP3_FRAME_HEADER_SIZE) { return; } - const headerBytes = this.readBytes(FRAME_HEADER_SIZE); + const headerBytes = this.readBytes(MP3_FRAME_HEADER_SIZE); const word = toDataView(headerBytes).getUint32(0); const result = readMp3FrameHeader(word, null); if (result.header) { this.seekTo(possibleHeaderStartPos); let remaining3 = this.ensureBuffered(result.header.totalSize); - if (remaining3 instanceof Promise) + if (isThenable(remaining3)) remaining3 = await remaining3; const duration = result.header.audioSamplesInFrame * TIMESCALE / elementaryStream.info.sampleRate; return this.supplyPacket(remaining3, Math.round(duration)); @@ -12842,7 +14046,7 @@ class PacketReadingContext { this.skip(-1); const possibleSyncPos = this.currentPos; let remaining2 = this.ensureBuffered(5); - if (remaining2 instanceof Promise) + if (isThenable(remaining2)) remaining2 = await remaining2; if (remaining2 < 5) { return; @@ -12862,7 +14066,7 @@ class PacketReadingContext { assert(frameSize !== void 0); this.seekTo(possibleSyncPos); remaining2 = this.ensureBuffered(frameSize); - if (remaining2 instanceof Promise) + if (isThenable(remaining2)) remaining2 = await remaining2; const duration = Math.round(AC3_SAMPLES_PER_FRAME * TIMESCALE / elementaryStream.info.sampleRate); return this.supplyPacket(remaining2, duration); @@ -12873,7 +14077,7 @@ class PacketReadingContext { this.skip(-1); const possibleSyncPos = this.currentPos; let remaining2 = this.ensureBuffered(5); - if (remaining2 instanceof Promise) + if (isThenable(remaining2)) remaining2 = await remaining2; if (remaining2 < 5) { return; @@ -12890,11 +14094,70 @@ class PacketReadingContext { const numblks = EAC3_NUMBLKS_TABLE[numblkscod]; this.seekTo(possibleSyncPos); remaining2 = this.ensureBuffered(frameSize); - if (remaining2 instanceof Promise) + if (isThenable(remaining2)) remaining2 = await remaining2; const samplesPerFrame = numblks * 256; const duration = Math.round(samplesPerFrame * TIMESCALE / elementaryStream.info.sampleRate); return this.supplyPacket(remaining2, duration); + } else if (codec === "dts") { + if (byte !== 127 && byte !== 100) { + continue; + } + this.skip(-1); + const possibleSyncPos = this.currentPos; + let remaining2 = this.ensureBuffered(DTS_CORE_FRAME_HEADER_SIZE); + if (isThenable(remaining2)) + remaining2 = await remaining2; + if (remaining2 < DTS_CORE_FRAME_HEADER_SIZE) { + return; + } + const headerBytes = this.readBytes(DTS_CORE_FRAME_HEADER_SIZE); + const core = parseDtsCoreFrameHeader(headerBytes); + let leadingExss = core ? null : parseDtsExssHeader(headerBytes); + if (!core && !leadingExss) { + this.seekTo(possibleSyncPos + 1); + continue; + } + if (leadingExss && !leadingExss.asset) { + this.seekTo(possibleSyncPos); + const headerBound = Math.min(leadingExss.frameSize, DTS_EXSS_MAX_HEADER_SIZE); + let remaining3 = this.ensureBuffered(headerBound); + if (isThenable(remaining3)) + remaining3 = await remaining3; + leadingExss = parseDtsExssHeader(this.readBytes(remaining3)) ?? leadingExss; + } + let frameSize = core ? core.frameSize : leadingExss.frameSize; + if (core) { + let nextSubstreamPos = Math.ceil(core.frameSize / 4) * 4; + while (true) { + this.seekTo(possibleSyncPos); + const neededBytes = nextSubstreamPos + DTS_EXSS_HEADER_PREFIX_SIZE; + let remaining3 = this.ensureBuffered(neededBytes); + if (isThenable(remaining3)) + remaining3 = await remaining3; + if (remaining3 < neededBytes) { + break; + } + this.seekTo(possibleSyncPos + nextSubstreamPos); + const exss = parseDtsExssHeader(this.readBytes(DTS_EXSS_HEADER_PREFIX_SIZE)); + if (!exss) { + break; + } + nextSubstreamPos += exss.frameSize; + frameSize = nextSubstreamPos; + } + } + const sampleCount = core?.sampleCount ?? leadingExss.asset?.sampleCount; + if (sampleCount === void 0) { + this.seekTo(possibleSyncPos + 1); + continue; + } + this.seekTo(possibleSyncPos); + remaining2 = this.ensureBuffered(frameSize); + if (isThenable(remaining2)) + remaining2 = await remaining2; + const duration = Math.round(sampleCount * TIMESCALE / elementaryStream.info.sampleRate); + return this.supplyPacket(remaining2, duration); } else { throw new Error("Unhandled."); } @@ -13124,6 +14387,15 @@ class SegmentedInput { } return lastSegment.timestamp + lastSegment.duration; } + async getUnixTimeForTimestamp(timestamp) { + let segment = await this.getSegmentAt(timestamp, {}); + segment ?? (segment = await this.getFirstSegment({})); + if (!segment || segment.unixEpochTimestamp === null) { + return null; + } + const elapsed = timestamp - segment.timestamp; + return segment.unixEpochTimestamp + elapsed; + } async getTrackBackings() { return this.trackBackingsPromise ?? (this.trackBackingsPromise = (async () => { const backings = []; @@ -13208,6 +14480,7 @@ class SegmentedInputInputTrackBacking { this.packetInfos = /* @__PURE__ */ new WeakMap(); this.hydrationPromise = null; this.firstInputTrack = null; + this.firstSegment = null; this.segmentedInput = segmentedInput; this.decl = decl; this.number = number; @@ -13219,13 +14492,22 @@ class SegmentedInputInputTrackBacking { if (!this.segmentedInput.firstSegment) { throw new Error("Missing first segment, can't retrieve track."); } - const input = this.segmentedInput.getInputForSegment(this.segmentedInput.firstSegment); - const inputTracks = await input.getTracks(); - const track = inputTracks.find((x) => x.type === this.decl.type && x.number === this.number); + let currentSegment = this.segmentedInput.firstSegment; + let track = null; + while (currentSegment) { + const input = this.segmentedInput.getInputForSegment(currentSegment); + const inputTracks = await input.getTracks(); + track = inputTracks.find((x) => x.type === this.decl.type && x.number === this.number) ?? null; + if (track) { + break; + } + currentSegment = await this.segmentedInput.getNextSegment(currentSegment, {}); + } if (!track) { throw new Error("No matching track found in underlying media data."); } this.firstInputTrack = track; + this.firstSegment = currentSegment; })()); } getId() { @@ -13274,7 +14556,10 @@ class SegmentedInputInputTrackBacking { async isRelativeToUnixEpoch() { await this.hydrate(); assert(this.segmentedInput.firstSegment); - return this.segmentedInput.firstSegment.relativeToUnixEpoch; + return this.segmentedInput.firstSegment.unixEpochTimestamp === this.segmentedInput.firstSegment.timestamp; + } + getUnixTimeForTimestamp(timestamp) { + return this.segmentedInput.getUnixTimeForTimestamp(timestamp); } getBitrate() { return this.delegate(() => this.firstInputTrack._backing.getBitrate()); @@ -13308,13 +14593,28 @@ class SegmentedInputInputTrackBacking { } async getFirstPacket(options) { await this.hydrate(); - assert(this.segmentedInput.firstSegment); assert(this.firstInputTrack); - const packet = await this.firstInputTrack._backing.getFirstPacket(options); - if (!packet) { - return null; + assert(this.firstSegment); + let currentTrack = this.firstInputTrack; + let currentSegment = this.firstSegment; + while (true) { + if (currentTrack) { + const packet = await currentTrack._backing.getFirstPacket(options); + if (packet) { + return this.createAdjustedPacket(packet, currentSegment, currentTrack); + } + } + currentSegment = await this.segmentedInput.getNextSegment(currentSegment, { + skipLiveWait: options.skipLiveWait + }); + if (!currentSegment) { + break; + } + const nextInput = this.segmentedInput.getInputForSegment(currentSegment); + const nextTracks = await nextInput.getTracks(); + currentTrack = nextTracks.find((t) => t.type === this.firstInputTrack.type && t.number === this.firstInputTrack.number) ?? null; } - return this.createAdjustedPacket(packet, this.segmentedInput.firstSegment, this.firstInputTrack); + return null; } getNextPacket(packet, options) { return this._getNextInternal(packet, options, false); @@ -13443,14 +14743,25 @@ class SegmentedInputInputAudioTrackBacking extends SegmentedInputInputTrackBacki polyfillSymbolDispose(); const DEFAULT_MIN_READ_POSITION = 0; const DEFAULT_MAX_READ_POSITION = Infinity; +if (typeof FinalizationRegistry !== "undefined") { + new FinalizationRegistry((cleanup) => { + cleanup(); + }); +} class Source extends EventEmitter { constructor() { - super(...arguments); + super(); this._disposed = false; this._refCount = 0; this._usedForHls = false; + this._refFinalizationRegistry = null; this._sizePromise = null; this.onread = null; + if (typeof FinalizationRegistry !== "undefined") { + this._refFinalizationRegistry = new FinalizationRegistry((source) => { + source._decrementRefCount(); + }); + } } /** * Resolves with the total size of the file in bytes. This function is memoized, meaning only the first call @@ -13516,6 +14827,18 @@ class Source extends EventEmitter { ref() { return new SourceRef(this); } + /** @internal */ + _incrementRefCount() { + this._refCount++; + } + /** @internal */ + _decrementRefCount() { + this._refCount--; + if (this._refCount === 0) { + this._dispose(); + this._disposed = true; + } + } } class SourceRef { /** @internal */ @@ -13524,7 +14847,8 @@ class SourceRef { if (source._disposed) { throw new Error("Cannot ref a disposed source."); } - source._refCount++; + source._incrementRefCount(); + source._refFinalizationRegistry?.register(this, source, this); this._source = source; } /** The {@link Source} this ref references. Accessing this field throws an error after having freed the ref. */ @@ -13548,11 +14872,8 @@ class SourceRef { } const source = this.source; assert(source._refCount > 0); - source._refCount--; - if (source._refCount === 0) { - source._dispose(); - source._disposed = true; - } + source._decrementRefCount(); + source._refFinalizationRegistry?.unregister(this); this._freed = true; this._source = null; } @@ -13589,7 +14910,7 @@ class PathedSource extends Source { (_a = ref.source)._usedForHls || (_a._usedForHls = this._usedForHls); return ref; }; - if (result instanceof Promise) { + if (isThenable(result)) { return result.then(handle); } else { return handle(result); @@ -13616,7 +14937,7 @@ class CustomPathedSource extends PathedSource { this._rootRequest = null; return ref; }; - if (result instanceof Promise) { + if (isThenable(result)) { this._rootRequest = result.then(handle); } else { handle(result); @@ -13645,6 +14966,10 @@ class CustomPathedSource extends PathedSource { } } } +const blobReaderRegistry = typeof FinalizationRegistry !== "undefined" ? new FinalizationRegistry((reader) => { + void reader.cancel().catch(() => { + }); +}) : null; class BlobSource extends Source { /** * Creates a new {@link BlobSource} backed by the specified @@ -13660,14 +14985,31 @@ class BlobSource extends Source { if (options.maxCacheSize !== void 0 && (!isNumber(options.maxCacheSize) || options.maxCacheSize < 0)) { throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number."); } + if (options.useStreamReader !== void 0 && typeof options.useStreamReader !== "boolean") { + throw new TypeError("options.useStreamReader, when provided, must be a boolean."); + } + if (options.handleUnhandledError !== void 0 && typeof options.handleUnhandledError !== "function") { + throw new TypeError("options.handleUnhandledError, when provided, must be a function."); + } super(); this._readers = /* @__PURE__ */ new WeakMap(); this._blob = blob; + this._options = options; this._orchestrator = new ReadOrchestrator({ maxCacheSize: options.maxCacheSize ?? 8 * 2 ** 20, maxWorkerCount: 4, runWorker: this._runWorker.bind(this), - prefetchProfile: PREFETCH_PROFILES.fileSystem + onIdleWorkerRemoved: (worker) => { + const reader = this._readers.get(worker); + if (reader) { + this._readers.delete(worker); + blobReaderRegistry?.unregister(worker); + void reader.cancel().catch(() => { + }); + } + }, + prefetchProfile: PREFETCH_PROFILES.fileSystem, + handleUnhandledError: options.handleUnhandledError }); this._orchestrator.fileSize = blob.size; } @@ -13684,9 +15026,10 @@ class BlobSource extends Source { assert(worker.strictTarget); let reader = this._readers.get(worker); if (reader === void 0) { - if ("stream" in this._blob && !isWebKit()) { + if ("stream" in this._blob && !isWebKit() && this._options.useStreamReader !== false) { const slice = this._blob.slice(worker.currentPos); reader = slice.stream().getReader(); + blobReaderRegistry?.register(worker, reader, worker); } else { reader = null; } @@ -13725,7 +15068,7 @@ class BlobSource extends Source { } const URL_SOURCE_MIN_LOAD_AMOUNT = 0.5 * 2 ** 20; const DEFAULT_RETRY_DELAY = ((previousAttempts, error, src) => { - const couldBeCorsError = error instanceof Error && (error.message.includes("Failed to fetch") || error.message.includes("Load failed") || error.message.includes("NetworkError when attempting to fetch resource")); + const couldBeCorsError = error instanceof Error && (error.message.includes("Failed to fetch") || error.message.includes("Load failed") || error.message.includes("NetworkError when attempting to fetch resource")) && typeof window !== "undefined"; if (couldBeCorsError) { let originOfSrc = null; try { @@ -13736,7 +15079,7 @@ const DEFAULT_RETRY_DELAY = ((previousAttempts, error, src) => { } const isOnline = typeof navigator !== "undefined" && typeof navigator.onLine === "boolean" ? navigator.onLine : true; if (isOnline && originOfSrc !== null && originOfSrc !== window.location.origin) { - console.warn(`Request will not be retried because a CORS error was suspected due to different origins. You can modify this behavior by providing your own function for the 'getRetryDelay' option.`); + Logging._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.`); return null; } } @@ -13747,8 +15090,8 @@ class UrlSource extends PathedSource { /** * Creates a new {@link UrlSource} backed by the resource at the specified URL. * - * When passing a `Request` instance, note that the `signal` and `headers.Range` options will be overridden by - * Mediabunny. If you want to cancel ongoing requests, use {@link Input.dispose}. + * When passing a `Request` instance, note that its `signal` will be overridden by Mediabunny; if you want to cancel + * ongoing requests, use {@link Input.dispose}. */ constructor(url, options = {}) { if (typeof url !== "string" && !(url instanceof URL) && !(typeof Request !== "undefined" && url instanceof Request)) { @@ -13772,33 +15115,90 @@ class UrlSource extends PathedSource { if (options.fetchFn !== void 0 && typeof options.fetchFn !== "function") { throw new TypeError("options.fetchFn, when provided, must be a function."); } + if (options.handleUnhandledError !== void 0 && typeof options.handleUnhandledError !== "function") { + throw new TypeError("options.handleUnhandledError, when provided, must be a function."); + } const urlString = url instanceof Request ? url.url : url instanceof URL ? url.href : url; super(urlString, (request) => new UrlSource(request.path, this._options)); + this._offset = 0; + this._length = null; this._fileSizeDetermined = false; + this._sequentialBacking = null; this._url = url; this._options = options; this._getRetryDelay = options.getRetryDelay ?? DEFAULT_RETRY_DELAY; + this._requestInit = { ...options.requestInit }; + let rangeHeaderValue = null; + if (options.requestInit?.headers) { + const headers = { ...normalizeHeaders(options.requestInit.headers) }; + const rangeKey = Object.keys(headers).find((key) => key.toLowerCase() === "range"); + if (rangeKey !== void 0) { + rangeHeaderValue = headers[rangeKey]; + delete headers[rangeKey]; + this._requestInit.headers = headers; + } + } + if (url instanceof Request) { + const requestRange = url.headers.get("Range"); + if (requestRange !== null) { + rangeHeaderValue ?? (rangeHeaderValue = requestRange); + const strippedRequest = new Request(url); + strippedRequest.headers.delete("Range"); + this._url = strippedRequest; + } + } + if (rangeHeaderValue !== null) { + const parsed = parseByteRangeHeader(rangeHeaderValue); + if (parsed) { + this._offset = parsed.offset; + this._length = parsed.length; + } + } const DEFAULT_PARALLELISM = 2; this._orchestrator = new ReadOrchestrator({ maxCacheSize: options.maxCacheSize ?? 64 * 2 ** 20, maxWorkerCount: options.parallelism ?? DEFAULT_PARALLELISM, runWorker: this._runWorker.bind(this), - prefetchProfile: PREFETCH_PROFILES.network + prefetchProfile: PREFETCH_PROFILES.network, + handleUnhandledError: options.handleUnhandledError }); } /** @internal */ _getFileSize() { - return this._fileSizeDetermined ? this._orchestrator.fileSize : void 0; + if (!this._fileSizeDetermined) { + return this._length !== null ? this._length : void 0; + } + const baseSize = this._sequentialBacking ? this._sequentialBacking._endIndex : this._orchestrator.fileSize; + if (baseSize === null) { + return this._length !== null ? this._length : null; + } + return clamp$1(baseSize - this._offset, 0, this._length ?? Infinity); } /** @internal */ _read(start, end, minReadPosition, maxReadPosition) { - return this._orchestrator.read(start, end, minReadPosition, maxReadPosition); + if (this._length !== null && end > this._length) { + return null; + } + const offset = this._offset; + const result = this._sequentialBacking ? this._sequentialBacking._read(offset + start, offset + end) : this._orchestrator.read(offset + start, offset + end, Math.max(offset + minReadPosition, offset), offset + Math.min(maxReadPosition, this._length ?? Infinity)); + const processResult = (result2) => { + if (!result2) { + return null; + } + result2.offset -= this._offset; + return result2; + }; + if (isThenable(result)) { + return result.then(processResult); + } else { + return processResult(result); + } } /** @internal */ async _runWorker(worker) { while (true) { const abortController = new AbortController(); - const response = await retriedFetch(this._options.fetchFn ?? fetch, this._url, mergeRequestInit(this._options.requestInit ?? {}, { + const response = await retriedFetch(this._options.fetchFn ?? fetch, this._url, mergeRequestInit(this._requestInit, { headers: { // Always sending a range request is a good way to probe if the server supports them Range: `bytes=${worker.currentPos}-` @@ -13808,7 +15208,10 @@ class UrlSource extends PathedSource { if (!response.ok) { throw new Error(`Error fetching ${String(this._url)}: ${response.status} ${response.statusText}`); } - outer: if (this._orchestrator.fileSize === null) { + if (response.redirected) { + this.rootPath = response.url; + } + outer: if (this._orchestrator.fileSize === null && (response.status === 206 || response.type === "basic" && !response.headers.has("Content-Encoding"))) { const contentRange = response.headers.get("Content-Range"); if (contentRange) { const match = /\/(\d+)/.exec(contentRange); @@ -13819,33 +15222,30 @@ class UrlSource extends PathedSource { } const contentLength = response.headers.get("Content-Length"); if (contentLength) { - this._orchestrator.supplyFileSize(worker.currentPos + Number(contentLength)); + const basePos = response.status === 206 ? worker.currentPos : 0; + this._orchestrator.supplyFileSize(basePos + Number(contentLength)); } } this._fileSizeDetermined = true; + if (!response.body) { + throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream."); + } if (response.status !== 206) { + if (this._sequentialBacking) { + void response.body.cancel(); + return; + } if (!this._usedForHls) { const url = new URL(this._url instanceof Request ? this._url.url : this._url, typeof window !== "undefined" ? window.location.href : void 0); if (url.origin !== "null" && !(url.pathname.endsWith(".m3u8") || url.pathname.endsWith(".m3u"))) { if (!warnedOrigins.has(url.origin)) { - console.log(this._usedForHls, this._url, url.pathname); - console.warn(`HTTP server (origin ${url.origin}) did not respond to a range request with 206 Partial Content, meaning the entire resource will now be downloaded. To enable efficient media file streaming across a network, please make sure your server supports range requests.`); + Logging._warn(`HTTP server (origin ${url.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.`); warnedOrigins.add(url.origin); } } } - worker.currentPos = 0; - this._orchestrator.options.maxCacheSize = Infinity; - if (this._orchestrator.fileSize !== null) { - worker.targetPos = this._orchestrator.fileSize; - } else { - worker.targetPos = Infinity; - worker.strictTarget = false; - } - this._orchestrator.consolidateEverythingIntoOneWorker(worker); - } - if (!response.body) { - throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream."); + this._transitionToSequentialMode(response.body); + return; } const reader = response.body.getReader(); while (true) { @@ -13863,7 +15263,7 @@ class UrlSource extends PathedSource { } const retryDelayInSeconds = this._getRetryDelay(1, error, this._url); if (retryDelayInSeconds !== null) { - console.error("Error while reading response stream. Attempting to resume.", error); + Logging._error("Error while reading response stream. Attempting to resume.", error); await wait(1e3 * retryDelayInSeconds); break; } else { @@ -13892,10 +15292,130 @@ class UrlSource extends PathedSource { } } /** @internal */ + _transitionToSequentialMode(body) { + let currentReader = body.getReader(); + let streamPosition = 0; + let skipRemaining = 0; + const wrappedStream = new ReadableStream({ + pull: async (controller) => { + while (true) { + let readResult; + try { + readResult = await currentReader.read(); + } catch (error) { + if (this._disposed) { + throw error; + } + const retryDelayInSeconds = this._getRetryDelay(1, error, this._url); + if (retryDelayInSeconds === null) { + throw error; + } + Logging._error("Error while reading response stream. Attempting to resume.", error); + await wait(1e3 * retryDelayInSeconds); + const newResponse = await retriedFetch(this._options.fetchFn ?? fetch, this._url, mergeRequestInit(this._requestInit, { + headers: { + // Who knows, maybe the server honors range requests this time + Range: `bytes=${streamPosition}-` + } + }), this._getRetryDelay, () => this._disposed); + if (!newResponse.ok) { + throw new Error( + // eslint-disable-next-line @typescript-eslint/no-base-to-string + `Error fetching ${String(this._url)}: ${newResponse.status} ${newResponse.statusText}` + ); + } + if (!newResponse.body) { + throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream."); + } + currentReader = newResponse.body.getReader(); + skipRemaining = newResponse.status === 206 ? 0 : streamPosition; + continue; + } + if (readResult.done) { + controller.close(); + return; + } + let chunk = readResult.value; + if (skipRemaining > 0) { + const skippedAmount = Math.min(skipRemaining, chunk.length); + skipRemaining -= skippedAmount; + chunk = chunk.subarray(skippedAmount); + } + if (chunk.length === 0) { + continue; + } + streamPosition += chunk.length; + controller.enqueue(chunk); + return; + } + }, + cancel: () => currentReader.cancel() + }); + const backing = new ReadableStreamSource(wrappedStream, { + maxCacheSize: this._orchestrator.options.maxCacheSize, + handleUnhandledError: this._options.handleUnhandledError + }); + backing._endIndex = this._orchestrator.fileSize; + backing._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."; + backing.on("read", ({ start, end }) => this._dispatchRead(start, end)); + this._sequentialBacking = backing; + const uniqueSlices = /* @__PURE__ */ new Set(); + for (const otherWorker of this._orchestrator.workers) { + for (const slice of otherWorker.pendingSlices) { + uniqueSlices.add(slice); + } + otherWorker.aborted = true; + otherWorker.pendingSlices.length = 0; + } + for (const queuedRead of this._orchestrator.queuedReads) { + for (const slice of queuedRead.pendingSlices) { + uniqueSlices.add(slice); + } + } + this._orchestrator.workers.length = 0; + this._orchestrator.queuedReads.length = 0; + for (const slice of uniqueSlices) { + const result = backing._read(slice.start, slice.start + slice.bytes.length); + if (isThenable(result)) { + result.then((readResult) => { + if (readResult) { + assert(readResult.offset === slice.start); + slice.resolve(readResult.bytes); + } else { + slice.resolve(null); + } + }, (error) => slice.reject(error)); + } else { + assert(result === null); + slice.resolve(null); + } + } + } + /** @internal */ _dispose() { this._orchestrator.dispose(); + if (this._sequentialBacking) { + this._sequentialBacking._disposed = true; + this._sequentialBacking._dispose(); + } } } +const BYTE_RANGE_REGEX = /^bytes=(\d+)-(\d*)$/; +const parseByteRangeHeader = (value) => { + const match = BYTE_RANGE_REGEX.exec(value.trim()); + if (!match) { + return null; + } + const offset = Number(match[1]); + const end = match[2] === "" ? null : Number(match[2]); + if (end !== null && end < offset) { + return null; + } + return { + offset, + length: end !== null ? end - offset + 1 : null + }; +}; class ReadableStreamSource extends Source { /** Creates a new {@link ReadableStreamSource} backed by the specified `ReadableStream`. */ constructor(stream, options = {}) { @@ -13905,6 +15425,9 @@ class ReadableStreamSource extends Source { if (!options || typeof options !== "object") { throw new TypeError("options must be an object."); } + if (options.handleUnhandledError !== void 0 && typeof options.handleUnhandledError !== "function") { + throw new TypeError("options.handleUnhandledError, when provided, must be a function."); + } if (options.maxCacheSize !== void 0 && (!isNumber(options.maxCacheSize) || options.maxCacheSize < 0)) { throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number."); } @@ -13917,8 +15440,10 @@ class ReadableStreamSource extends Source { this._maxRequestedIndex = 0; this._endIndex = null; this._pulling = false; + this._cacheMissErrorMessage = "Attempted to read data from an already-evicted part of the cache. With ReadableStreamSource, you must access the data more sequentially or increase the size of its cache."; this._stream = stream; - this._maxCacheSize = options.maxCacheSize ?? 16 * 2 ** 20; + this._maxCacheSize = options.maxCacheSize ?? 32 * 2 ** 20; + this._handleUnhandledError = options.handleUnhandledError; } /** @internal */ _getFileSize() { @@ -13984,6 +15509,8 @@ class ReadableStreamSource extends Source { if (this._pendingSlices.length > 0) { this._pendingSlices.forEach((x) => x.reject(error)); this._pendingSlices.length = 0; + } else if (this._handleUnhandledError) { + this._handleUnhandledError(error); } else { throw error; } @@ -13993,7 +15520,7 @@ class ReadableStreamSource extends Source { } /** @internal */ _throwDueToCacheMiss() { - throw new Error("Read is before the cached region. With ReadableStreamSource, you must access the data more sequentially or increase the size of its cache."); + throw new Error(this._cacheMissErrorMessage); } /** @internal */ async _pull() { @@ -14010,6 +15537,7 @@ class ReadableStreamSource extends Source { } const startIndex = this._currentIndex; const endIndex = this._currentIndex + value.byteLength; + this._dispatchRead(startIndex, endIndex); for (let i = 0; i < this._pendingSlices.length; i++) { const pendingSlice = this._pendingSlices[i]; const cappedStart = Math.max(startIndex, pendingSlice.start); @@ -14049,6 +15577,9 @@ class ReadableStreamSource extends Source { } /** @internal */ _dispose() { + for (const pendingSlice of this._pendingSlices) { + pendingSlice.reject(new InputDisposedError()); + } this._pendingSlices.length = 0; this._cache.length = 0; void this._reader?.cancel(); @@ -14237,6 +15768,17 @@ class ReadOrchestrator { view: toDataView(bytes2), offset: innerStart }); + } else { + promise.catch((error) => { + if (this.disposed) { + return; + } + if (this.options.handleUnhandledError) { + this.options.handleUnhandledError(error); + } else { + throw error; + } + }); } return result; } @@ -14286,6 +15828,7 @@ class ReadOrchestrator { assert(oldestIndex !== null); assert(oldestWorker.pendingSlices.length === 0); this.workers.splice(oldestIndex, 1); + this.options.onIdleWorkerRemoved?.(oldestWorker); } else { return null; } @@ -14316,8 +15859,12 @@ class ReadOrchestrator { if (worker.pendingSlices.length > 0) { worker.pendingSlices.forEach((x) => x.reject(error)); worker.pendingSlices.length = 0; - } else { - throw error; + } else if (!worker.aborted && !this.disposed) { + if (this.options.handleUnhandledError) { + this.options.handleUnhandledError(error); + } else { + throw error; + } } }).finally(() => { if (worker.running) { @@ -14332,38 +15879,16 @@ class ReadOrchestrator { } } const queuedRead = this.queuedReads[oldestIndex]; - this.queuedReads.splice(oldestIndex, 1); const newWorker = this.createWorker(queuedRead.hole.start, queuedRead.hole.end, queuedRead.strictTarget); - assert(newWorker); + if (!newWorker) { + return; + } + this.queuedReads.splice(oldestIndex, 1); newWorker.pendingSlices = queuedRead.pendingSlices; this.runWorker(newWorker); } }); } - consolidateEverythingIntoOneWorker(worker) { - const uniqueSlices = new Set(worker.pendingSlices); - for (let i = 0; i < this.workers.length; i++) { - const otherWorker = this.workers[i]; - if (otherWorker === worker) { - continue; - } - for (const slice of otherWorker.pendingSlices) { - uniqueSlices.add(slice); - } - otherWorker.aborted = true; - otherWorker.pendingSlices.length = 0; - this.workers.splice(i, 1); - i--; - } - for (let i = 0; i < this.queuedReads.length; i++) { - const queuedRead = this.queuedReads[i]; - for (const slice of queuedRead.pendingSlices) { - uniqueSlices.add(slice); - } - } - worker.pendingSlices = [...uniqueSlices]; - this.queuedReads.length = 0; - } /** Called by a worker when it has read some data. */ supplyWorkerData(worker, bytes) { assert(!worker.aborted); @@ -14411,6 +15936,7 @@ class ReadOrchestrator { } if (closedIntervalsOverlap(start, end, otherWorker.currentPos, otherWorker.targetPos)) { this.workers.splice(i, 1); + this.options.onIdleWorkerRemoved?.(otherWorker); i--; } } @@ -14456,7 +15982,9 @@ class ReadOrchestrator { } signalWorkerStoppedRunning(worker) { worker.running = false; - worker.pendingSlices.length = 0; + if (!worker.aborted) { + worker.pendingSlices.length = 0; + } } /** Called when a worker reaches the end of the underlying data and must be cleaned up. */ onWorkerFinished(worker) { @@ -14464,6 +15992,7 @@ class ReadOrchestrator { assert(index !== -1); worker.running = false; this.workers.splice(index, 1); + this.options.onIdleWorkerRemoved?.(worker); if (this.fileSize === null) { this.supplyFileSize(worker.currentPos); } @@ -14539,10 +16068,23 @@ class ReadOrchestrator { } dispose() { for (const worker of this.workers) { + for (const slice of worker.pendingSlices) { + slice.reject(new InputDisposedError()); + } + worker.pendingSlices.length = 0; worker.aborted = true; + if (!worker.running) { + this.options.onIdleWorkerRemoved?.(worker); + } + } + for (const queuedRead of this.queuedReads) { + for (const slice of queuedRead.pendingSlices) { + slice.reject(new InputDisposedError()); + } } this.workers.length = 0; this.cache.length = 0; + this.queuedReads.length = 0; this.disposed = true; } } @@ -14579,20 +16121,17 @@ class RangedSource extends Source { return null; } const result = this._baseSource._read(this._offset + start, this._offset + end, this._offset + minReadPosition, this._offset + maxReadPosition); - if (result instanceof Promise) { - return result.then((result2) => { - if (!result2) { - return null; - } - result2.offset -= this._offset; - return result2; - }); - } else { - if (!result) { + const processResult = (result2) => { + if (!result2) { return null; } - result.offset -= this._offset; - return result; + result2.offset -= this._offset; + return result2; + }; + if (isThenable(result)) { + return result.then(processResult); + } else { + return processResult(result); } } /** @internal */ @@ -14604,7 +16143,7 @@ class RangedSource extends Source { return super.ref(); } } -var __addDisposableResource = function(env, value, async) { +var __addDisposableResource$1 = function(env, value, async) { if (value !== null && value !== void 0) { if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); var dispose, inner; @@ -14631,7 +16170,7 @@ var __addDisposableResource = function(env, value, async) { } return value; }; -var __disposeResources = /* @__PURE__ */ (function(SuppressedError2) { +var __disposeResources$1 = /* @__PURE__ */ (function(SuppressedError2) { return function(env) { function fail(e) { env.error = env.hasError ? new SuppressedError2(e, env.error, "An error was suppressed during disposal.") : e; @@ -14673,6 +16212,7 @@ class HlsSegmentedInput extends SegmentedInput { this.streamHasEnded = false; this.lastSegmentUpdateTime = -Infinity; this.refreshInterval = 5; + this.rootPath = path; this.demuxer = demuxer; this.nextLines = lines; } @@ -14708,20 +16248,25 @@ class HlsSegmentedInput extends SegmentedInput { if (!lines) { const env_1 = { stack: [], error: void 0, hasError: false }; try { - const ref = __addDisposableResource(env_1, await this.demuxer.input._getSourceUncached({ path: this.path, isRoot: false }), false); + const ref = __addDisposableResource$1(env_1, await this.demuxer.input._getSourceUncached({ path: this.rootPath, isRoot: false }), false); const reader = new Reader(ref.source); const slice = await reader.requestEntireFile(); assert(slice); lines = readAllLines(slice, slice.length, { ignore: canIgnoreLine }); + if (ref.source instanceof PathedSource) { + this.rootPath = ref.source.rootPath; + } } catch (e_1) { env_1.error = e_1; env_1.hasError = true; } finally { - __disposeResources(env_1); + __disposeResources$1(env_1); } } + const offsetTimestampsByDateTime = this.input._formatOptions.hls?.offsetTimestampsByDateTime !== false; let headerRead = false; let accumulatedTime = 0; + let accumulatedUnixTime = null; let nextSegmentDuration = null; let currentKey = null; let nextSequenceNumber = 0; @@ -14757,6 +16302,7 @@ class HlsSegmentedInput extends SegmentedInput { currentFirstSegment = prevLastSegment.firstSegment; currentInitSegment = prevLastSegment.initSegment; lastProgramDateTimeSeconds = prevLastSegment.lastProgramDateTimeSeconds; + accumulatedUnixTime = prevLastSegment.unixEpochTimestamp !== null ? prevLastSegment.unixEpochTimestamp + prevLastSegment.duration : null; prevLastSegment = null; } } @@ -14783,7 +16329,7 @@ class HlsSegmentedInput extends SegmentedInput { view.setUint32(12, nextSequenceNumber); key = { ...key, iv }; } - const fullPath = joinPaths(this.path, line); + const fullPath = joinPaths(this.rootPath, line); const location = { path: fullPath, offset: nextByteRange?.offset ?? 0, @@ -14791,7 +16337,7 @@ class HlsSegmentedInput extends SegmentedInput { }; const segment = { timestamp: accumulatedTime, - relativeToUnixEpoch: lastProgramDateTimeSeconds !== null, + unixEpochTimestamp: accumulatedUnixTime, firstSegment: currentFirstSegment, sequenceNumber: nextSequenceNumber, location, @@ -14802,6 +16348,9 @@ class HlsSegmentedInput extends SegmentedInput { }; currentFirstSegment ?? (currentFirstSegment = segment); accumulatedTime += nextSegmentDuration; + if (accumulatedUnixTime !== null) { + accumulatedUnixTime += nextSegmentDuration; + } this.segments.push(segment); } nextSegmentDuration = null; @@ -14846,7 +16395,7 @@ class HlsSegmentedInput extends SegmentedInput { throw new Error("Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset."); } if (!prevLastSegment) { - const fullPath = joinPaths(this.path, uri); + const fullPath = joinPaths(this.rootPath, uri); const location = { path: fullPath, offset: parsedByteRange?.offset ?? 0, @@ -14857,7 +16406,7 @@ class HlsSegmentedInput extends SegmentedInput { } const segment = { timestamp: accumulatedTime, - relativeToUnixEpoch: lastProgramDateTimeSeconds !== null, + unixEpochTimestamp: accumulatedUnixTime, firstSegment: null, sequenceNumber: null, location, @@ -14904,7 +16453,7 @@ class HlsSegmentedInput extends SegmentedInput { } currentKey = { method: "AES-128", - keyUri: joinPaths(this.path, uri), + keyUri: joinPaths(this.rootPath, uri), iv, keyFormat }; @@ -14968,13 +16517,17 @@ class HlsSegmentedInput extends SegmentedInput { const lastSegmentEnd = lastSegment.timestamp + lastSegment.duration; const offset = dateTimeSeconds - lastSegmentEnd; for (const segment of this.segments) { - segment.timestamp += offset; - segment.relativeToUnixEpoch = true; + segment.unixEpochTimestamp = segment.timestamp + offset; + if (offsetTimestampsByDateTime) { + segment.timestamp = segment.unixEpochTimestamp; + } } - accumulatedTime += offset; } lastProgramDateTimeSeconds = dateTimeSeconds; - accumulatedTime = dateTimeSeconds; + accumulatedUnixTime = dateTimeSeconds; + if (offsetTimestampsByDateTime) { + accumulatedTime = dateTimeSeconds; + } } else if (line === TAG_DISCONTINUITY) { currentFirstSegment = null; } else if (line.startsWith(TAG_TARGETDURATION)) { @@ -15111,7 +16664,7 @@ class HlsSegmentedInput extends SegmentedInput { const stream = createAes128CbcDecryptStream(ciphertextReader, async () => { const env_2 = { stack: [], error: void 0, hasError: false }; try { - const keyRef = __addDisposableResource(env_2, await this.input._getSourceCached({ path: encryption.keyUri, isRoot: false }, ENCRYPTION_KEY_CACHE_GROUP), false); + const keyRef = __addDisposableResource$1(env_2, await this.input._getSourceCached({ path: encryption.keyUri, isRoot: false }, ENCRYPTION_KEY_CACHE_GROUP), false); const keyReader = new Reader(keyRef.source); const keySlice = await keyReader.requestSlice(0, AES_128_BLOCK_SIZE); if (!keySlice) { @@ -15123,7 +16676,7 @@ class HlsSegmentedInput extends SegmentedInput { env_2.error = e_2; env_2.hasError = true; } finally { - __disposeResources(env_2); + __disposeResources$1(env_2); } }, () => { ciphertextRef.free(); @@ -15176,10 +16729,10 @@ class HlsDemuxer extends Demuxer { readMetadata() { return this.metadataPromise ?? (this.metadataPromise = (async () => { assert(this.input._rootSource instanceof PathedSource); - const { rootPath } = this.input._rootSource; const slice = await this.input._reader.requestEntireFile(); assert(slice); const lines = readAllLines(slice, slice.length, { ignore: canIgnoreLine }); + const { rootPath } = this.input._rootSource; const variantStreams = []; const mediaTags = []; for (let i = 1; i < lines.length; i++) { @@ -15646,6 +17199,9 @@ class HlsInputTrackBacking { isRelativeToUnixEpoch() { return this.delegate(() => this.internalTrack.backingTrack.isRelativeToUnixEpoch()); } + getUnixTimeForTimestamp(timestamp) { + return this.delegate(() => this.internalTrack.backingTrack.getUnixTimeForTimestamp(timestamp)); + } getBitrate() { return this.internalTrack.peakBitrate; } @@ -15829,7 +17385,7 @@ class IsobmffInputFormat extends InputFormat { /** @internal */ async _getMajorBrand(input) { let slice = input._reader.requestSlice(0, 12); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) return null; @@ -15852,12 +17408,37 @@ class Mp4InputFormat extends IsobmffInputFormat { if (majorBrand !== null) { return majorBrand !== "qt "; } - let slice = input._reader.requestSlice(4, 4); - if (slice instanceof Promise) - slice = await slice; - if (!slice) - return false; - return readAscii(slice, 4) === "moof"; + let pos = 0; + for (let iter = 0; iter < 10; iter++) { + let slice = input._reader.requestSlice(pos, 8); + if (isThenable(slice)) + slice = await slice; + if (!slice) + return false; + let size = readU32Be(slice); + let headerSize = 8; + if (size === 1) { + let sizeExtensionSlice = input._reader.requestSlice(pos + 8, 8); + if (isThenable(sizeExtensionSlice)) + sizeExtensionSlice = await sizeExtensionSlice; + if (!sizeExtensionSlice) + return false; + size = readU64Be(sizeExtensionSlice); + headerSize = 16; + } + if (size < headerSize) { + return false; + } + const fourCc = readAscii(slice, 4); + if (fourCc === "moof" || fourCc === "sidx") { + return true; + } else if (fourCc === "emsg" || fourCc === "prft" || fourCc === "free") { + pos += size; + } else { + return false; + } + } + return false; } get name() { return "MP4"; @@ -15883,7 +17464,7 @@ class MatroskaInputFormat extends InputFormat { /** @internal */ async isSupportedEBMLOfDocType(input, desiredDocType) { let headerSlice = input._reader.requestSlice(0, MAX_HEADER_SIZE); - if (headerSlice instanceof Promise) + if (isThenable(headerSlice)) headerSlice = await headerSlice; if (!headerSlice) return false; @@ -15903,7 +17484,7 @@ class MatroskaInputFormat extends InputFormat { return false; } let dataSlice = input._reader.requestSlice(headerSlice.filePos, dataSize); - if (dataSlice instanceof Promise) + if (isThenable(dataSlice)) dataSlice = await dataSlice; if (!dataSlice) return false; @@ -15987,7 +17568,7 @@ class Mp3InputFormat extends InputFormat { let currentPos = 0; while (true) { let slice2 = input._reader.requestSlice(currentPos, ID3_V2_HEADER_SIZE); - if (slice2 instanceof Promise) + if (isThenable(slice2)) slice2 = await slice2; if (!slice2) break; @@ -16004,7 +17585,7 @@ class Mp3InputFormat extends InputFormat { const firstHeader = firstResult.header; const xingOffset = getXingOffset(firstHeader.mpegVersionId, firstHeader.channel); let slice = input._reader.requestSlice(firstResult.startPos + xingOffset, 4); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) return false; @@ -16014,7 +17595,7 @@ class Mp3InputFormat extends InputFormat { return true; } currentPos = firstResult.startPos + firstResult.header.totalSize; - const secondResult = await readNextMp3FrameHeader(input._reader, currentPos, currentPos + FRAME_HEADER_SIZE); + const secondResult = await readNextMp3FrameHeader(input._reader, currentPos, currentPos + MP3_FRAME_HEADER_SIZE); if (!secondResult) { return false; } @@ -16039,7 +17620,7 @@ class WaveInputFormat extends InputFormat { /** @internal */ async _canReadInput(input) { let slice = input._reader.requestSlice(0, 12); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) return false; @@ -16066,7 +17647,7 @@ class OggInputFormat extends InputFormat { /** @internal */ async _canReadInput(input) { let slice = input._reader.requestSlice(0, 4); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) return false; @@ -16086,8 +17667,21 @@ class OggInputFormat extends InputFormat { class FlacInputFormat extends InputFormat { /** @internal */ async _canReadInput(input) { - let slice = input._reader.requestSlice(0, 4); - if (slice instanceof Promise) + let currentPos = 0; + while (true) { + let slice2 = input._reader.requestSlice(currentPos, ID3_V2_HEADER_SIZE); + if (isThenable(slice2)) + slice2 = await slice2; + if (!slice2) + break; + const id3V2Header = readId3V2Header(slice2); + if (!id3V2Header) { + break; + } + currentPos = slice2.filePos + id3V2Header.size; + } + let slice = input._reader.requestSlice(currentPos, 4); + if (isThenable(slice)) slice = await slice; if (!slice) return false; @@ -16110,7 +17704,7 @@ class AdtsInputFormat extends InputFormat { let currentPos = 0; while (true) { let slice2 = input._reader.requestSlice(currentPos, ID3_V2_HEADER_SIZE); - if (slice2 instanceof Promise) + if (isThenable(slice2)) slice2 = await slice2; if (!slice2) break; @@ -16121,7 +17715,7 @@ class AdtsInputFormat extends InputFormat { currentPos = slice2.filePos + id3V2Header.size; } let slice = input._reader.requestSliceRange(currentPos, MIN_ADTS_FRAME_HEADER_SIZE, MAX_ADTS_FRAME_HEADER_SIZE); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) return false; @@ -16131,7 +17725,7 @@ class AdtsInputFormat extends InputFormat { } currentPos += firstHeader.frameLength; slice = input._reader.requestSliceRange(currentPos, MIN_ADTS_FRAME_HEADER_SIZE, MAX_ADTS_FRAME_HEADER_SIZE); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) return false; @@ -16157,7 +17751,7 @@ class MpegTsInputFormat extends InputFormat { async _canReadInput(input) { const lengthToCheck = TS_PACKET_SIZE + 16 + 1; let slice = input._reader.requestSlice(0, lengthToCheck); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) return false; @@ -16186,7 +17780,7 @@ class HlsInputFormat extends InputFormat { /** @internal */ async _canReadInput(input) { let slice = input._reader.requestSlice(0, 7); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) return false; @@ -16236,7 +17830,73 @@ const validateInputFormatOptions = (options, prefix) => { throw new TypeError(`${prefix}.isobmff.resolveKeyId, when provided, must be a function.`); } } + if (options.hls !== void 0) { + if (!options.hls || typeof options.hls !== "object") { + throw new TypeError(`${prefix}.hls, when provided, must be an object.`); + } + if (options.hls.offsetTimestampsByDateTime !== void 0 && typeof options.hls.offsetTimestampsByDateTime !== "boolean") { + throw new TypeError(`${prefix}.hls.offsetTimestampsByDateTime, when provided, must be a boolean.`); + } + } }; +var __addDisposableResource = function(env, value, async) { + if (value !== null && value !== void 0) { + if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); + var dispose, inner; + if (async) { + if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); + dispose = value[Symbol.asyncDispose]; + } + if (dispose === void 0) { + if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); + dispose = value[Symbol.dispose]; + if (async) inner = dispose; + } + if (typeof dispose !== "function") throw new TypeError("Object not disposable."); + if (inner) dispose = function() { + try { + inner.call(this); + } catch (e) { + return Promise.reject(e); + } + }; + env.stack.push({ value, dispose, async }); + } else if (async) { + env.stack.push({ async: true }); + } + return value; +}; +var __disposeResources = /* @__PURE__ */ (function(SuppressedError2) { + return function(env) { + function fail(e) { + env.error = env.hasError ? new SuppressedError2(e, env.error, "An error was suppressed during disposal.") : e; + env.hasError = true; + } + var r, s = 0; + function next() { + while (r = env.stack.pop()) { + try { + if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next); + if (r.dispose) { + var result = r.dispose.call(r.value); + if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { + fail(e); + return next(); + }); + } else s |= 1; + } catch (e) { + fail(e); + } + } + if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve(); + if (env.hasError) throw env.error; + } + return next(); + }; +})(typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; +}); polyfillSymbolDispose(); let lastVideoGcErrorLog = -Infinity; let lastAudioGcErrorLog = -Infinity; @@ -16246,7 +17906,7 @@ if (typeof FinalizationRegistry !== "undefined") { const now = performance.now(); if (value.type === "video") { if (now - lastVideoGcErrorLog >= 1e3) { - console.error(`A VideoSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your VideoSamples as soon as you're done using them.`); + Logging._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.`); lastVideoGcErrorLog = now; } if (typeof VideoFrame !== "undefined" && value.data instanceof VideoFrame) { @@ -16254,7 +17914,7 @@ if (typeof FinalizationRegistry !== "undefined") { } } else { if (now - lastAudioGcErrorLog >= 1e3) { - console.error(`An AudioSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your AudioSamples as soon as you're done using them.`); + Logging._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.`); lastAudioGcErrorLog = now; } if (typeof AudioData !== "undefined" && value.data instanceof AudioData) { @@ -16263,6 +17923,12 @@ if (typeof FinalizationRegistry !== "undefined") { } }); } +class VideoSampleResource { + constructor() { + this._referenceCount = 0; + this._lastAllocationBuffer = null; + } +} const VIDEO_SAMPLE_PIXEL_FORMATS = [ // 4:2:0 Y, U, V "I420", @@ -16384,13 +18050,29 @@ class VideoSample { if (init.displayWidth !== void 0 !== (init.displayHeight !== void 0)) { throw new TypeError("init.displayWidth and init.displayHeight must be either both provided or both omitted."); } - this._data = toUint8Array(data).slice(); - this._layout = init.layout ?? createDefaultPlaneLayout(init.format, init.codedWidth, init.codedHeight); this.format = init.format; this.rotation = init.rotation ?? 0; this.timestamp = init.timestamp; this.duration = init.duration ?? 0; - this.colorSpace = new VideoSampleColorSpace(init.colorSpace); + const layout = init.layout ?? createDefaultPlaneLayout(init.format, init.codedWidth, init.codedHeight); + let colorSpaceInit = init.colorSpace ?? null; + if (colorSpaceInit === null) { + if (this.format === "RGBA" || this.format === "RGBX" || this.format === "BGRA" || this.format === "BGRX") { + colorSpaceInit = { + primaries: "bt709", + transfer: "iec61966-2-1", + matrix: "rgb", + fullRange: true + }; + } else { + colorSpaceInit = { + primaries: "bt709", + transfer: "bt709", + matrix: "bt709", + fullRange: false + }; + } + } this.visibleRect = { left: init.visibleRect?.left ?? 0, top: init.visibleRect?.top ?? 0, @@ -16401,9 +18083,12 @@ class VideoSample { this.squarePixelWidth = this.rotation % 180 === 0 ? init.displayWidth : init.displayHeight; this.squarePixelHeight = this.rotation % 180 === 0 ? init.displayHeight : init.displayWidth; } else { - this.squarePixelWidth = this.codedWidth; - this.squarePixelHeight = this.codedHeight; + this.squarePixelWidth = this.visibleRect.width; + this.squarePixelHeight = this.visibleRect.height; } + this._data = init._doNotCopy ? toUint8Array(data) : toUint8Array(data).slice(); + this._layout = layout; + this.colorSpace = new VideoSampleColorSpace(colorSpaceInit); } else if (typeof VideoFrame !== "undefined" && data instanceof VideoFrame) { if (init?.rotation !== void 0 && ![0, 90, 180, 270].includes(init.rotation)) { throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270."); @@ -16445,11 +18130,21 @@ class VideoSample { if (init.duration !== void 0 && (!Number.isFinite(init.duration) || init.duration < 0)) { throw new TypeError("init.duration, when provided, must be a non-negative number."); } + if (init.visibleRect !== void 0) { + validateRectangle(init.visibleRect, "init.visibleRect"); + } if (typeof VideoFrame !== "undefined") { return new VideoSample(new VideoFrame(data, { timestamp: Math.trunc(init.timestamp * SECOND_TO_MICROSECOND_FACTOR), // Drag 0 to undefined - duration: Math.trunc((init.duration ?? 0) * SECOND_TO_MICROSECOND_FACTOR) || void 0 + duration: Math.trunc((init.duration ?? 0) * SECOND_TO_MICROSECOND_FACTOR) || void 0, + // WebCodecs wants DOMRectInit + visibleRect: init.visibleRect && { + x: init.visibleRect.left, + y: init.visibleRect.top, + width: init.visibleRect.width, + height: init.visibleRect.height + } }), init); } let width = 0; @@ -16467,20 +18162,23 @@ class VideoSample { if (!width || !height) { throw new TypeError("Could not determine dimensions."); } - const canvas = new OffscreenCanvas(width, height); + const visibleRect = init.visibleRect ?? { left: 0, top: 0, width, height }; + const canvas = new OffscreenCanvas(visibleRect.width, visibleRect.height); const context = canvas.getContext("2d", { alpha: isFirefox(), // Firefox has VideoFrame glitches with opaque canvases willReadFrequently: true }); - assert(context); - context.drawImage(data, 0, 0); + if (!context) { + throw new Error("OffscreenCanvas must have support for the '2d' context in order to create a VideoSample from this data."); + } + context.drawImage(data, -visibleRect.left, -visibleRect.top); this._data = canvas; this._layout = null; this.format = "RGBX"; - this.visibleRect = { left: 0, top: 0, width, height }; - this.squarePixelWidth = width; - this.squarePixelHeight = height; + this.visibleRect = { left: 0, top: 0, width: visibleRect.width, height: visibleRect.height }; + this.squarePixelWidth = visibleRect.width; + this.squarePixelHeight = visibleRect.height; this.rotation = init.rotation ?? 0; this.timestamp = init.timestamp; this.duration = init.duration ?? 0; @@ -16490,9 +18188,53 @@ class VideoSample { transfer: "iec61966-2-1", fullRange: true }); + } else if (data instanceof VideoSampleResource) { + if (!init || typeof init !== "object") { + throw new TypeError("init must be an object."); + } + if (init.rotation !== void 0 && ![0, 90, 180, 270].includes(init.rotation)) { + throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270."); + } + if (!Number.isFinite(init.timestamp)) { + throw new TypeError("init.timestamp must be a number."); + } + if (init.duration !== void 0 && (!Number.isFinite(init.duration) || init.duration < 0)) { + throw new TypeError("init.duration, when provided, must be a non-negative number."); + } + this._data = data; + data._referenceCount++; + this.format = data.getFormat(); + if (this.format !== null && !VIDEO_SAMPLE_PIXEL_FORMATS.includes(this.format)) { + throw new TypeError("getFormat() must return a VideoSamplePixelFormat or null."); + } + this.visibleRect = { + left: 0, + top: 0, + width: data.getCodedWidth(), + height: data.getCodedHeight() + }; + if (!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."); + } + this.squarePixelWidth = data.getSquarePixelWidth(); + if (!Number.isInteger(this.squarePixelWidth) || this.squarePixelWidth <= 0) { + throw new TypeError("getSquarePixelWidth() must return a positive integer."); + } + this.squarePixelHeight = data.getSquarePixelHeight(); + if (!Number.isInteger(this.squarePixelHeight) || this.squarePixelHeight <= 0) { + throw new TypeError("getSquarePixelHeight() must return a positive integer."); + } + this.rotation = init.rotation ?? 0; + this.timestamp = init.timestamp; + this.duration = init.duration ?? 0; + this.colorSpace = data.getColorSpace(); } else { - throw new TypeError("Invalid data type: Must be a BufferSource or CanvasImageSource."); + throw new TypeError("Invalid data type: Must be a BufferSource, CanvasImageSource, or VideoSampleResource."); } + this.encodeOptions = init?.encodeOptions ?? {}; this.pixelAspectRatio = simplifyRational({ num: this.squarePixelWidth * this.codedHeight, den: this.squarePixelHeight * this.codedWidth @@ -16505,11 +18247,19 @@ class VideoSample { throw new Error("VideoSample is closed."); } assert(this._data !== null); - if (isVideoFrame(this._data)) { + if (this._data instanceof VideoSampleResource) { + return new VideoSample(this._data, { + timestamp: this.timestamp, + duration: this.duration, + rotation: this.rotation, + encodeOptions: this.encodeOptions + }); + } else if (isVideoFrame(this._data)) { return new VideoSample(this._data.clone(), { timestamp: this.timestamp, duration: this.duration, - rotation: this.rotation + rotation: this.rotation, + encodeOptions: this.encodeOptions }); } else if (this._data instanceof Uint8Array) { assert(this._layout); @@ -16524,7 +18274,10 @@ class VideoSample { rotation: this.rotation, visibleRect: this.visibleRect, displayWidth: this.displayWidth, - displayHeight: this.displayHeight + displayHeight: this.displayHeight, + encodeOptions: this.encodeOptions, + // It's already been copied, if we copy it again we make the clone unnecessarily expensive + _doNotCopy: true }); } else { return new VideoSample(this._data, { @@ -16537,7 +18290,8 @@ class VideoSample { rotation: this.rotation, visibleRect: this.visibleRect, displayWidth: this.displayWidth, - displayHeight: this.displayHeight + displayHeight: this.displayHeight, + encodeOptions: this.encodeOptions }); } } @@ -16550,7 +18304,12 @@ class VideoSample { return; } finalizationRegistry?.unregister(this); - if (isVideoFrame(this._data)) { + if (this._data instanceof VideoSampleResource) { + this._data._referenceCount--; + if (this._data._referenceCount === 0) { + this._data.close(); + } + } else if (isVideoFrame(this._data)) { this._data.close(); } else { this._data = null; @@ -16558,35 +18317,24 @@ class VideoSample { this._closed = true; } /** - * Returns the number of bytes required to hold this video sample's pixel data. Throws if `format` is `null`. + * Returns the number of bytes required to hold this video sample's pixel data. */ allocationSize(options = {}) { validateVideoFrameCopyToOptions(options); if (this._closed) { throw new Error("VideoSample is closed."); } - if (this.format === null) { - throw new Error("Cannot get allocation size when format is null. Sorry!"); - } - assert(this._data !== null); - if (!isVideoFrame(this._data)) { - if (options.colorSpace || options.format && options.format !== this.format || options.layout || options.rect) { - const videoFrame = this.toVideoFrame(); - const size = videoFrame.allocationSize(options); - videoFrame.close(); - return size; - } + if ((options.format ?? this.format) == null) { + throw new Error("Cannot get allocation size when format is null."); } if (isVideoFrame(this._data)) { return this._data.allocationSize(options); - } else if (this._data instanceof Uint8Array) { - return this._data.byteLength; - } else { - return this.codedWidth * this.codedHeight * 4; } + const combinedLayout = ParseVideoFrameCopyToOptions(this, options); + return combinedLayout.allocationSize; } /** - * Copies this video sample's pixel data to an ArrayBuffer or ArrayBufferView. Throws if `format` is `null`. + * Copies this video sample's pixel data to an ArrayBuffer or ArrayBufferView. * @returns The byte layout of the planes of the copied data. */ async copyTo(destination, options = {}) { @@ -16597,37 +18345,127 @@ class VideoSample { if (this._closed) { throw new Error("VideoSample is closed."); } - if (this.format === null) { - throw new Error("Cannot copy video sample data when format is null. Sorry!"); + if ((options.format ?? this.format) == null) { + throw new Error("Cannot copy video sample data when format is null."); } assert(this._data !== null); - if (!isVideoFrame(this._data)) { - if (options.colorSpace || options.format && options.format !== this.format || options.layout || options.rect) { - const videoFrame = this.toVideoFrame(); - const layout = await videoFrame.copyTo(destination, options); - videoFrame.close(); - return layout; - } - } if (isVideoFrame(this._data)) { return this._data.copyTo(destination, options); + } + if (options.format && !["RGBA", "RGBX", "BGRA", "BGRX"].includes(this.format) && ["RGBA", "RGBX", "BGRA", "BGRX"].includes(options.format)) { + if (this._data instanceof VideoSampleResource) { + const env_1 = { stack: [], error: void 0, hasError: false }; + try { + const rgbSample = __addDisposableResource(env_1, await this._data.toRgbSample({ + timestamp: this.timestamp, + duration: this.duration, + rotation: this.rotation + }, options.colorSpace ?? "srgb"), false); + if (!(rgbSample instanceof VideoSample)) { + throw new TypeError("toRgbSample() must return a VideoSample."); + } + if (!["RGBA", "RGBX", "BGRA", "BGRX"].includes(rgbSample.format)) { + throw new Error(`Sample returned by toRgbSample was expected to have an RGB format, got '${rgbSample.format}' instead.`); + } + return await rgbSample.copyTo(destination, options); + } catch (e_1) { + env_1.error = e_1; + env_1.hasError = true; + } finally { + __disposeResources(env_1); + } + } else { + if (typeof VideoFrame === "undefined") { + throw new Error("For this sample, converting from a non-RGB to an RGB format requires VideoFrame to be defined."); + } + const tempFrame = this.toVideoFrame(); + const result = await tempFrame.copyTo(destination, options); + tempFrame.close(); + return result; + } + } + const combinedLayout = ParseVideoFrameCopyToOptions(this, options); + assert(this.format); + const destBytes = toUint8Array(destination); + if (destBytes.byteLength < combinedLayout.allocationSize) { + throw new TypeError(`Destination buffer too small. Required: ${combinedLayout.allocationSize}, Available: ${destBytes.byteLength}`); + } + const planeConfigs = getPlaneConfigs(this.format); + let dataPlanes; + if (this._data instanceof VideoSampleResource) { + let result = this._data.getDataPlanes(); + if (isThenable(result)) + result = await result; + if (!Array.isArray(result) || result.some((x) => !(x.data instanceof Uint8Array) || !Number.isInteger(x.stride) || x.stride < 0)) { + throw new TypeError('getDataPlanes() must return an array of objects with a Uint8Array "data" property and a non-negative integer "stride" property.'); + } + dataPlanes = result; } else if (this._data instanceof Uint8Array) { assert(this._layout); - const dest = toUint8Array(destination); - dest.set(this._data); - return this._layout; + assert(this._layout.length === planeConfigs.length); + dataPlanes = this._layout.map((planeLayout, i) => { + const height = Math.ceil(this.codedHeight / planeConfigs[i].heightDivisor); + return { + data: this._data.subarray(planeLayout.offset, planeLayout.offset + planeLayout.stride * height), + stride: planeLayout.stride + }; + }); } else { const canvas = this._data; const context = canvas.getContext("2d"); assert(context); const imageData = context.getImageData(0, 0, this.codedWidth, this.codedHeight); - const dest = toUint8Array(destination); - dest.set(imageData.data); - return [{ - offset: 0, + dataPlanes = [{ + data: toUint8Array(imageData.data), stride: 4 * this.codedWidth }]; } + const planeLayouts = []; + const numPlanes = planeConfigs.length; + for (let planeIndex = 0; planeIndex < numPlanes; planeIndex++) { + const computedLayout = combinedLayout.computedLayouts[planeIndex]; + const sourceStride = dataPlanes[planeIndex].stride; + const sourceData = dataPlanes[planeIndex].data; + let sourceOffset = computedLayout.sourceTop * sourceStride; + sourceOffset += computedLayout.sourceLeftBytes; + let destinationOffset = computedLayout.destinationOffset; + const rowBytes = computedLayout.sourceWidthBytes; + const layout = { + offset: destinationOffset, + stride: computedLayout.destinationStride + }; + for (let row = 0; row < computedLayout.sourceHeight; row++) { + if (sourceOffset + rowBytes > sourceData.byteLength) { + throw new Error(`Source buffer OOB read.`); + } + if (destinationOffset + rowBytes > destBytes.byteLength) { + throw new Error(`Destination buffer OOB write.`); + } + const srcSub = sourceData.subarray(sourceOffset, sourceOffset + rowBytes); + destBytes.set(srcSub, destinationOffset); + sourceOffset += sourceStride; + destinationOffset += computedLayout.destinationStride; + } + planeLayouts.push(layout); + } + if (options.format !== void 0) { + const needsRgbConversion = this.format.startsWith("RGB") !== options.format.startsWith("RGB"); + const needsAlphaConversion = this.format.includes("X") && options.format.includes("A"); + if (needsRgbConversion || needsAlphaConversion) { + for (let i = 0; i < combinedLayout.allocationSize; i += 4) { + if (needsRgbConversion) { + const r = destBytes[i]; + const b = destBytes[i + 2]; + destBytes[i] = b; + destBytes[i + 2] = r; + } + if (needsAlphaConversion) { + destBytes[i + 3] = 255; + } + } + } + } + return planeLayouts; } /** * Converts this video sample to a VideoFrame for use with the WebCodecs API. The VideoFrame returned by this @@ -16638,20 +18476,61 @@ class VideoSample { throw new Error("VideoSample is closed."); } assert(this._data !== null); - if (isVideoFrame(this._data)) { + if (this._data instanceof VideoSampleResource) { + if (this.format === null) { + throw new Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if format is null."); + } + const planes = this._data.getDataPlanes(); + if (isThenable(planes)) { + throw new Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if getDataPlanes() returns a promise."); + } + const size = planes.reduce((a, b) => a + b.data.byteLength, 0); + const buffer = new Uint8Array(size); + let offset = 0; + const offsets = []; + for (const plane of planes) { + buffer.set(plane.data, offset); + offsets.push(offset); + offset += plane.data.byteLength; + } + return new VideoFrame(buffer, { + format: this.format, + layout: planes.map((x, i) => ({ + offset: offsets[i], + stride: x.stride + })), + codedWidth: this.codedWidth, + codedHeight: this.codedHeight, + timestamp: this.microsecondTimestamp, + duration: this.microsecondDuration, + colorSpace: this.colorSpace, + visibleRect: this.visibleRect, + displayWidth: this.squarePixelWidth, + // Not display* since we're not passing rotation + displayHeight: this.squarePixelHeight + }); + } else if (isVideoFrame(this._data)) { return new VideoFrame(this._data, { timestamp: this.microsecondTimestamp, duration: this.microsecondDuration || void 0 // Drag 0 duration to undefined, glitches some codecs }); } else if (this._data instanceof Uint8Array) { + assert(this._layout); return new VideoFrame(this._data, { format: this.format, codedWidth: this.codedWidth, + // This is technically wrong! codedWidth is a lie technically. But, since codedHeight: this.codedHeight, + // we pass the layout (which contains the true coded width), we're good. + layout: this._layout, timestamp: this.microsecondTimestamp, duration: this.microsecondDuration || void 0, - colorSpace: this.colorSpace + colorSpace: this.colorSpace, + visibleRect: this.visibleRect, + displayWidth: this.squarePixelWidth, + // Not display* since we're not passing rotation + displayHeight: this.squarePixelHeight }); } else { return new VideoFrame(this._data, { @@ -16756,8 +18635,9 @@ class VideoSample { const canvasHeight = context.canvas.height; const rotation = options.rotation ?? this.rotation; const [rotatedWidth, rotatedHeight] = rotation % 180 === 0 ? [this.squarePixelWidth, this.squarePixelHeight] : [this.squarePixelHeight, this.squarePixelWidth]; - if (options.crop) { - clampCropRectangle(options.crop, rotatedWidth, rotatedHeight); + let finalCrop = options.crop; + if (finalCrop) { + finalCrop = clampCropRectangle(finalCrop, rotatedWidth, rotatedHeight); } let dx; let dy; @@ -16810,11 +18690,54 @@ class VideoSample { } return { sx, sy, sWidth, sHeight }; } + /** + * Draws the sample onto the target canvas with fit behavior, manually mipmapping on strong downscales for quality. + * @internal + */ + _drawWithFitAndMipmapping(targetCanvas, targetContext, options) { + const targetWidth = targetCanvas.width; + const targetHeight = targetCanvas.height; + const [rotatedWidth, rotatedHeight] = options.rotation % 180 === 0 ? [this.squarePixelWidth, this.squarePixelHeight] : [this.squarePixelHeight, this.squarePixelWidth]; + const sourceWidth = options.crop ? options.crop.width : rotatedWidth; + const sourceHeight = options.crop ? options.crop.height : rotatedHeight; + let mipLevels = 0; + if (2 * targetWidth < sourceWidth && 2 * targetHeight < sourceHeight) { + mipLevels = Math.floor(Math.log2(Math.min(sourceWidth / targetWidth, sourceHeight / targetHeight))); + } + const drawWidth = targetWidth * 2 ** mipLevels; + const drawHeight = targetHeight * 2 ** mipLevels; + const { canvas, context, isNew } = mipLevels > 0 ? getTransformationCanvas(drawWidth, drawHeight) : { canvas: targetCanvas, context: targetContext, isNew: options.targetIsFresh }; + context.imageSmoothingQuality = "high"; + if (options.fillBlack) { + context.fillStyle = "black"; + context.fillRect(0, 0, drawWidth, drawHeight); + } else if (!isNew) { + context.clearRect(0, 0, drawWidth, drawHeight); + } + this.drawWithFit(context, { + fit: options.fit, + rotation: options.rotation, + crop: options.crop + }); + context.globalCompositeOperation = "copy"; + for (let i = mipLevels; i > 1; i--) { + const levelWidth = targetWidth * 2 ** i; + const levelHeight = targetHeight * 2 ** i; + context.drawImage(canvas, 0, 0, levelWidth, levelHeight, 0, 0, levelWidth / 2, levelHeight / 2); + } + context.globalCompositeOperation = "source-over"; + if (mipLevels > 0) { + targetContext.imageSmoothingQuality = "high"; + targetContext.globalCompositeOperation = "copy"; + targetContext.drawImage(canvas, 0, 0, 2 * targetWidth, 2 * targetHeight, 0, 0, targetWidth, targetHeight); + targetContext.globalCompositeOperation = "source-over"; + } + } /** * Converts this video sample to a * [`CanvasImageSource`](https://udn.realityripple.com/docs/Web/API/CanvasImageSource) for drawing to a canvas. * - * You must use the value returned by this method immediately, as any VideoFrame created internally will + * You must use the value returned by this method immediately, as any VideoFrame created internally may * automatically be closed in the next microtask. */ toCanvasImageSource() { @@ -16822,7 +18745,7 @@ class VideoSample { throw new Error("VideoSample is closed."); } assert(this._data !== null); - if (this._data instanceof Uint8Array) { + if (this._data instanceof VideoSampleResource || this._data instanceof Uint8Array) { const videoFrame = this.toVideoFrame(); queueMicrotask(() => videoFrame.close()); return videoFrame; @@ -16830,6 +18753,103 @@ class VideoSample { return this._data; } } + /** + * Transform this video sample to a new video sample given the options. Can be used to resize, rotate, and crop + * the sample. + * + * In non-browser environments, this method will not work by default. To make it work, register a custom + * transformer function via {@link registerVideoSampleTransformer}. + */ + async transform(options) { + if (!options || typeof options !== "object") { + throw new TypeError("options must be an object."); + } + if (options.width !== void 0 && (!Number.isInteger(options.width) || options.width <= 0)) { + throw new TypeError("options.width, when provided, must be a positive integer."); + } + if (options.height !== void 0 && (!Number.isInteger(options.height) || options.height <= 0)) { + throw new TypeError("options.height, when provided, must be a positive integer."); + } + if (options.roundDimensionsTo !== void 0 && (!Number.isInteger(options.roundDimensionsTo) || options.roundDimensionsTo <= 0)) { + throw new TypeError("options.roundDimensionsTo, when provided, must be a positive integer."); + } + if (options.fit !== void 0 && !["fill", "contain", "cover"].includes(options.fit)) { + throw new TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".'); + } + if (options.width !== void 0 && options.height !== void 0 && options.fit === void 0) { + throw new TypeError("When both options.width and options.height are provided, options.fit must also be provided."); + } + if (options.rotate !== void 0 && ![0, 90, 180, 270].includes(options.rotate)) { + throw new TypeError("options.rotate, when provided, must be 0, 90, 180 or 270."); + } + if (options.crop !== void 0) { + validateCropRectangle(options.crop, "options."); + } + if (options.alpha !== void 0 && !["keep", "discard"].includes(options.alpha)) { + throw new TypeError("options.alpha, when provided, must be 'keep' or 'discard'."); + } + const rotation = normalizeRotation(this.rotation + (options.rotate ?? 0)); + const [rotatedWidth, rotatedHeight] = rotation % 180 === 0 ? [this.squarePixelWidth, this.squarePixelHeight] : [this.squarePixelHeight, this.squarePixelWidth]; + let finalCrop = options.crop; + if (finalCrop) { + finalCrop = clampCropRectangle(finalCrop, rotatedWidth, rotatedHeight); + } + const cropWidth = finalCrop ? finalCrop.width : rotatedWidth; + const cropHeight = finalCrop ? finalCrop.height : rotatedHeight; + const originalAspectRatio = cropWidth / cropHeight; + let targetWidth; + let targetHeight; + if (options.width !== void 0 && options.height === void 0) { + targetWidth = options.width; + targetHeight = targetWidth / originalAspectRatio; + } else if (options.width === void 0 && options.height !== void 0) { + targetHeight = options.height; + targetWidth = targetHeight * originalAspectRatio; + } else if (options.width !== void 0 && options.height !== void 0) { + targetWidth = options.width; + targetHeight = options.height; + } else { + targetWidth = cropWidth; + targetHeight = cropHeight; + } + targetWidth = roundToMultiple(targetWidth, options.roundDimensionsTo ?? 1); + targetHeight = roundToMultiple(targetHeight, options.roundDimensionsTo ?? 1); + const description = { + width: targetWidth, + height: targetHeight, + fit: options.fit ?? "fill", + rotation, + crop: finalCrop ?? { + left: 0, + top: 0, + width: rotatedWidth, + height: rotatedHeight + }, + alpha: options.alpha ?? "keep" + }; + for (const transformer of registeredVideoSampleTransformers) { + let result = transformer(this, description); + if (isThenable(result)) + result = await result; + if (result !== null) { + return result; + } + } + const { canvas, context, isNew } = getTransformationCanvas(description.width, description.height); + this._drawWithFitAndMipmapping(canvas, context, { + fit: description.fit, + rotation: description.rotation, + crop: description.crop, + targetIsFresh: isNew, + fillBlack: description.alpha === "discard" + }); + return new VideoSample(canvas, { + timestamp: this.timestamp, + duration: this.duration, + rotation: 0 + // Any previous rotation is now baked in + }); + } /** Sets the rotation metadata of this video sample. */ setRotation(newRotation) { if (![0, 90, 180, 270].includes(newRotation)) { @@ -16851,11 +18871,57 @@ class VideoSample { } this.duration = newDuration; } + /** Sets the encode options used when this sample is passed to an encoder. */ + setEncodeOptions(newEncodeOptions) { + if (!newEncodeOptions || typeof newEncodeOptions !== "object") { + throw new TypeError("newEncodeOptions must be an object."); + } + this.encodeOptions = newEncodeOptions; + } /** Calls `.close()`. */ [Symbol.dispose]() { this.close(); } } +const registeredVideoSampleTransformers = []; +const TRANSFORMATION_CANVAS_CACHE_MAX_SIZE = 3; +const transformationCanvasCache = []; +let transformationCanvasCacheNextAge = 0; +const getTransformationCanvas = (width, height) => { + for (const entry of transformationCanvasCache) { + if (entry.canvas.width === width && entry.canvas.height === height) { + entry.age = transformationCanvasCacheNextAge++; + return { canvas: entry.canvas, context: entry.context, isNew: false }; + } + } + let canvas; + if (typeof OffscreenCanvas !== "undefined") { + canvas = new OffscreenCanvas(width, height); + } else { + if (typeof window === "undefined" || typeof document === "undefined") { + 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()."); + } + canvas = document.createElement("canvas"); + canvas.width = width; + canvas.height = height; + } + const context = canvas.getContext("2d", { + alpha: true, + willReadFrequently: false + }); + if (!context) { + throw new Error("The '2d' canvas context is required to transform VideoSamples. Register a custom transformer using registerVideoSampleTransformer to work around this limitation."); + } + if (transformationCanvasCache.length >= TRANSFORMATION_CANVAS_CACHE_MAX_SIZE) { + transformationCanvasCache.splice(arrayArgmin(transformationCanvasCache, (x) => x.age), 1); + } + transformationCanvasCache.push({ + canvas, + context, + age: transformationCanvasCacheNextAge++ + }); + return { canvas, context, isNew: true }; +}; class VideoSampleColorSpace { /** Creates a new VideoSampleColorSpace. */ constructor(init) { @@ -17045,7 +19111,128 @@ const getPlaneConfigs = (format) => { assert(false); } }; +const ParseVideoFrameCopyToOptions = (sample, options) => { + const defaultRect = { + left: 0, + top: 0, + width: sample.codedWidth, + height: sample.codedHeight + }; + const overrideRect = options.rect; + const parsedRect = ParseVisibleRect(defaultRect, overrideRect, sample.codedWidth, sample.codedHeight, sample.format); + const optLayout = options.layout; + let format; + if (!options.format || options.format === sample.format) { + format = sample.format; + } else if (["RGBA", "RGBX", "BGRA", "BGRX"].includes(options.format)) { + format = options.format; + } else { + throw new Error("NotSupportedError: Invalid destination format."); + } + return ComputeLayoutAndAllocationSize(parsedRect, format, optLayout); +}; +const ParseVisibleRect = (defaultRect, overrideRect, codedWidth, codedHeight, format) => { + const sourceRect = { ...defaultRect }; + if (overrideRect !== void 0) { + if (overrideRect.width === 0 || overrideRect.height === 0) { + throw new TypeError("visibleRect dimensions cannot be zero."); + } + if ((overrideRect.x || 0) + (overrideRect.width || 0) > codedWidth) { + throw new TypeError("visibleRect exceeds codedWidth."); + } + if ((overrideRect.y || 0) + (overrideRect.height || 0) > codedHeight) { + throw new TypeError("visibleRect exceeds codedHeight."); + } + sourceRect.x = overrideRect.x || 0; + sourceRect.y = overrideRect.y || 0; + sourceRect.width = overrideRect.width || 0; + sourceRect.height = overrideRect.height || 0; + } + const validAlignment = VerifyRectOffsetAlignment(format, sourceRect); + if (!validAlignment) { + throw new TypeError("visibleRect alignment is invalid for the format."); + } + return sourceRect; +}; +const VerifyRectOffsetAlignment = (format, rect) => { + if (format === null) + return true; + const planes = getPlaneConfigs(format); + for (let planeIndex = 0; planeIndex < planes.length; planeIndex++) { + const plane = planes[planeIndex]; + const sampleWidth = plane.widthDivisor; + const sampleHeight = plane.heightDivisor; + if ((rect.x || 0) % sampleWidth !== 0) + return false; + if ((rect.y || 0) % sampleHeight !== 0) + return false; + } + return true; +}; +const ComputeLayoutAndAllocationSize = (parsedRect, format, layout) => { + const planes = getPlaneConfigs(format); + const numPlanes = planes.length; + if (layout !== void 0 && layout.length !== numPlanes) { + throw new TypeError(`Layout must have ${numPlanes} planes.`); + } + let minAllocationSize = 0; + const computedLayouts = []; + const endOffsets = []; + for (let planeIndex = 0; planeIndex < numPlanes; planeIndex++) { + const plane = planes[planeIndex]; + const sampleBytes = plane.sampleBytes; + const sampleWidth = plane.widthDivisor; + const sampleHeight = plane.heightDivisor; + const computedLayout = { + destinationOffset: 0, + destinationStride: 0, + sourceTop: 0, + sourceHeight: 0, + sourceLeftBytes: 0, + sourceWidthBytes: 0 + }; + computedLayout.sourceTop = Math.ceil(Math.trunc(parsedRect.y || 0) / sampleHeight); + computedLayout.sourceHeight = Math.ceil(Math.trunc(parsedRect.height || 0) / sampleHeight); + computedLayout.sourceLeftBytes = Math.floor(Math.trunc(parsedRect.x || 0) / sampleWidth) * sampleBytes; + computedLayout.sourceWidthBytes = Math.floor(Math.trunc(parsedRect.width || 0) / sampleWidth) * sampleBytes; + if (layout !== void 0) { + const planeLayout = layout[planeIndex]; + if (planeLayout.stride < computedLayout.sourceWidthBytes) { + throw new TypeError(`Stride for plane ${planeIndex} is too small.`); + } + computedLayout.destinationOffset = planeLayout.offset; + computedLayout.destinationStride = planeLayout.stride; + } else { + computedLayout.destinationOffset = minAllocationSize; + computedLayout.destinationStride = computedLayout.sourceWidthBytes; + } + const planeSize = computedLayout.destinationStride * computedLayout.sourceHeight; + const planeEnd = planeSize + computedLayout.destinationOffset; + if (planeEnd > 4294967295) { + throw new TypeError("Allocation size exceeds limit."); + } + endOffsets.push(planeEnd); + minAllocationSize = Math.max(minAllocationSize, planeEnd); + for (let earlierPlaneIndex = 0; earlierPlaneIndex < planeIndex; earlierPlaneIndex++) { + const earlierLayout = computedLayouts[earlierPlaneIndex]; + if (endOffsets[planeIndex] <= earlierLayout.destinationOffset || endOffsets[earlierPlaneIndex] <= computedLayout.destinationOffset) { + continue; + } + throw new TypeError("Planes overlap."); + } + computedLayouts.push(computedLayout); + } + return { + allocationSize: minAllocationSize, + computedLayouts + }; +}; const AUDIO_SAMPLE_FORMATS = /* @__PURE__ */ new Set(["f32", "f32-planar", "s16", "s16-planar", "s32", "s32-planar", "u8", "u8-planar"]); +class AudioSampleResource { + constructor() { + this._referenceCount = 0; + } +} class AudioSample { /** The presentation timestamp of the sample in microseconds. */ get microsecondTimestamp() { @@ -17055,11 +19242,6 @@ class AudioSample { get microsecondDuration() { return Math.trunc(SECOND_TO_MICROSECOND_FACTOR * this.duration); } - /** - * Creates a new {@link AudioSample}, either from an existing - * [`AudioData`](https://developer.mozilla.org/en-US/docs/Web/API/AudioData) or from raw bytes specified in - * {@link AudioSampleInit}. - */ constructor(init) { this._closed = false; if (isAudioData(init)) { @@ -17073,6 +19255,30 @@ class AudioSample { this.numberOfChannels = init.numberOfChannels; this.timestamp = init.timestamp / 1e6; this.duration = init.numberOfFrames / init.sampleRate; + } else if (init instanceof AudioSampleResource) { + this._data = init; + init._referenceCount++; + this.format = init.getFormat(); + if (!AUDIO_SAMPLE_FORMATS.has(this.format)) { + throw new TypeError("getFormat() must return an AudioSampleFormat."); + } + this.sampleRate = init.getSampleRate(); + if (!Number.isInteger(this.sampleRate) || this.sampleRate <= 0) { + throw new TypeError("getSampleRate() must return a positive integer."); + } + this.numberOfFrames = init.getNumberOfFrames(); + if (!Number.isInteger(this.numberOfFrames) || this.numberOfFrames < 0) { + throw new TypeError("getNumberOfFrames() must return a non-negative integer."); + } + this.numberOfChannels = init.getNumberOfChannels(); + if (!Number.isInteger(this.numberOfChannels) || this.numberOfChannels <= 0) { + throw new TypeError("getNumberOfChannels() must return a positive integer."); + } + this.timestamp = init.getTimestamp(); + if (!Number.isFinite(this.timestamp)) { + throw new TypeError("getTimestamp() must return a finite number."); + } + this.duration = this.numberOfFrames / this.sampleRate; } else { if (!init || typeof init !== "object") { throw new TypeError("Invalid AudioDataInit: must be an object."); @@ -17178,8 +19384,9 @@ class AudioSample { if (this._closed) { throw new Error("AudioSample is closed."); } - const { planeIndex, format, frameCount: optFrameCount, frameOffset: optFrameOffset } = options; - const srcFormat = this.format; + const { format, frameCount: optFrameCount, frameOffset: optFrameOffset } = options; + let { planeIndex } = options; + let srcFormat = this.format; const destFormat = format ?? this.format; if (!destFormat) throw new Error("Destination format not determined"); @@ -17211,44 +19418,105 @@ class AudioSample { if (isAudioData(this._data)) { if (isWebKit() && numChannels > 2 && destFormat !== srcFormat) { doAudioDataCopyToWebKitWorkaround(this._data, destView, srcFormat, destFormat, numChannels, planeIndex, frameOffset, copyFrameCount); + return; } else { - this._data.copyTo(destination, { - planeIndex, - frameOffset, - frameCount: copyFrameCount, - format: destFormat - }); + try { + this._data.copyTo(destination, { + planeIndex, + frameOffset, + frameCount: copyFrameCount, + format: destFormat + }); + return; + } catch (error) { + if (destFormat === "f32-planar") { + throw error; + } + srcFormat = "f32-planar"; + } } - } else { - const uint8Data = this._data; - const srcView = toDataView(uint8Data); - const readFn = getReadFunction(srcFormat); - const srcBytesPerSample = getBytesPerSample(srcFormat); - const srcIsPlanar = formatIsPlanar(srcFormat); - for (let i = 0; i < copyFrameCount; i++) { + } + const readFn = getReadFunction(srcFormat); + const srcBytesPerSample = getBytesPerSample(srcFormat); + const srcIsPlanar = formatIsPlanar(srcFormat); + let uint8Data; + if (this._data instanceof AudioSampleResource) { + const getDataPlaneValidated = (index) => { + const result = this._data.getDataPlane(index); + if (!(result instanceof Uint8Array)) { + throw new TypeError("getDataPlane() must return a Uint8Array."); + } + const expectedSize = numFrames * srcBytesPerSample * (srcIsPlanar ? 1 : numChannels); + if (result.byteLength !== expectedSize) { + throw new TypeError(`Data plane ${index} has invalid size. Expected exactly ${expectedSize} bytes, got ${result.byteLength} bytes.`); + } + return result; + }; + if (srcIsPlanar) { if (destIsPlanar) { - const destOffset = i * destBytesPerSample; + uint8Data = getDataPlaneValidated(planeIndex); + planeIndex = 0; + } else { + uint8Data = new Uint8Array(numFrames * srcBytesPerSample * numChannels); + for (let ch = 0; ch < numChannels; ch++) { + const planeData = getDataPlaneValidated(ch); + uint8Data.set(planeData, ch * numFrames * srcBytesPerSample); + } + } + } else { + uint8Data = getDataPlaneValidated(0); + } + } else if (this._data instanceof Uint8Array) { + uint8Data = this._data; + } else { + assert(srcFormat === "f32-planar"); + if (destIsPlanar) { + uint8Data = new Uint8Array(this._data.allocationSize({ + format: "f32-planar", + planeIndex + })); + this._data.copyTo(uint8Data, { + format: "f32-planar", + planeIndex + }); + planeIndex = 0; + } else { + uint8Data = new Uint8Array(this._data.allocationSize({ + format: "f32-planar", + planeIndex: 0 + }) * numChannels); + for (let ch = 0; ch < numChannels; ch++) { + this._data.copyTo(uint8Data.subarray(ch * numFrames * srcBytesPerSample, (ch + 1) * numFrames * srcBytesPerSample), { + format: "f32-planar", + planeIndex: ch + }); + } + } + } + const srcView = toDataView(uint8Data); + for (let i = 0; i < copyFrameCount; i++) { + if (destIsPlanar) { + const destOffset = i * destBytesPerSample; + let srcOffset; + if (srcIsPlanar) { + srcOffset = (planeIndex * numFrames + (i + frameOffset)) * srcBytesPerSample; + } else { + srcOffset = ((i + frameOffset) * numChannels + planeIndex) * srcBytesPerSample; + } + const normalized = readFn(srcView, srcOffset); + writeFn(destView, destOffset, normalized); + } else { + for (let ch = 0; ch < numChannels; ch++) { + const destIndex = i * numChannels + ch; + const destOffset = destIndex * destBytesPerSample; let srcOffset; if (srcIsPlanar) { - srcOffset = (planeIndex * numFrames + (i + frameOffset)) * srcBytesPerSample; + srcOffset = (ch * numFrames + (i + frameOffset)) * srcBytesPerSample; } else { - srcOffset = ((i + frameOffset) * numChannels + planeIndex) * srcBytesPerSample; + srcOffset = ((i + frameOffset) * numChannels + ch) * srcBytesPerSample; } const normalized = readFn(srcView, srcOffset); writeFn(destView, destOffset, normalized); - } else { - for (let ch = 0; ch < numChannels; ch++) { - const destIndex = i * numChannels + ch; - const destOffset = destIndex * destBytesPerSample; - let srcOffset; - if (srcIsPlanar) { - srcOffset = (ch * numFrames + (i + frameOffset)) * srcBytesPerSample; - } else { - srcOffset = ((i + frameOffset) * numChannels + ch) * srcBytesPerSample; - } - const normalized = readFn(srcView, srcOffset); - writeFn(destView, destOffset, normalized); - } } } } @@ -17258,7 +19526,11 @@ class AudioSample { if (this._closed) { throw new Error("AudioSample is closed."); } - if (isAudioData(this._data)) { + if (this._data instanceof AudioSampleResource) { + const sample = new AudioSample(this._data); + sample.setTimestamp(this.timestamp); + return sample; + } else if (isAudioData(this._data)) { const sample = new AudioSample(this._data.clone()); sample.setTimestamp(this.timestamp); return sample; @@ -17273,6 +19545,65 @@ class AudioSample { }); } } + /** + * Returns a new {@link AudioSample} containing only the frames in the range [startFrame, endFrame). Both bounds + * must lie within this sample's range of frames. The returned sample's timestamp is shifted to match the start of + * the trimmed section. + */ + trim(startFrame, endFrame = this.numberOfFrames) { + if (!Number.isInteger(startFrame) || startFrame < 0) { + throw new TypeError("startFrame must be a non-negative integer."); + } + if (!Number.isInteger(endFrame) || endFrame < 0) { + throw new TypeError("endFrame must be a non-negative integer."); + } + if (startFrame > this.numberOfFrames) { + throw new RangeError("startFrame out of range."); + } + if (endFrame > this.numberOfFrames) { + throw new RangeError("endFrame out of range."); + } + if (endFrame < startFrame) { + throw new RangeError("endFrame must not be less than startFrame."); + } + if (this._closed) { + throw new Error("AudioSample is closed."); + } + const frameCount = endFrame - startFrame; + const bytesPerSample = getBytesPerSample(this.format); + let data; + if (formatIsPlanar(this.format)) { + const planeSize = frameCount * bytesPerSample; + data = new Uint8Array(planeSize * this.numberOfChannels); + if (frameCount > 0) { + for (let i = 0; i < this.numberOfChannels; i++) { + this.copyTo(data.subarray(i * planeSize, (i + 1) * planeSize), { + planeIndex: i, + format: this.format, + frameOffset: startFrame, + frameCount + }); + } + } + } else { + data = new Uint8Array(frameCount * this.numberOfChannels * bytesPerSample); + if (frameCount > 0) { + this.copyTo(data, { + planeIndex: 0, + format: this.format, + frameOffset: startFrame, + frameCount + }); + } + } + return new AudioSample({ + data, + format: this.format, + sampleRate: this.sampleRate, + numberOfChannels: this.numberOfChannels, + timestamp: this.timestamp + startFrame / this.sampleRate + }); + } /** * Closes this audio sample, releasing held resources. Audio samples should be closed as soon as they are not * needed anymore. @@ -17282,7 +19613,12 @@ class AudioSample { return; } finalizationRegistry?.unregister(this); - if (isAudioData(this._data)) { + if (this._data instanceof AudioSampleResource) { + this._data._referenceCount--; + if (this._data._referenceCount === 0) { + this._data.close(); + } + } else if (isAudioData(this._data)) { this._data.close(); } else { this._data = new Uint8Array(0); @@ -17297,36 +19633,13 @@ class AudioSample { if (this._closed) { throw new Error("AudioSample is closed."); } - if (isAudioData(this._data)) { + if (this._data instanceof AudioSampleResource) { + return this._createAudioDataFromData(); + } else if (isAudioData(this._data)) { if (this._data.timestamp === this.microsecondTimestamp) { return this._data.clone(); } else { - if (formatIsPlanar(this.format)) { - const size = this.allocationSize({ planeIndex: 0, format: this.format }); - const data = new ArrayBuffer(size * this.numberOfChannels); - for (let i = 0; i < this.numberOfChannels; i++) { - this.copyTo(new Uint8Array(data, i * size, size), { planeIndex: i, format: this.format }); - } - return new AudioData({ - format: this.format, - sampleRate: this.sampleRate, - numberOfFrames: this.numberOfFrames, - numberOfChannels: this.numberOfChannels, - timestamp: this.microsecondTimestamp, - data - }); - } else { - const data = new ArrayBuffer(this.allocationSize({ planeIndex: 0, format: this.format })); - this.copyTo(data, { planeIndex: 0, format: this.format }); - return new AudioData({ - format: this.format, - sampleRate: this.sampleRate, - numberOfFrames: this.numberOfFrames, - numberOfChannels: this.numberOfChannels, - timestamp: this.microsecondTimestamp, - data - }); - } + return this._createAudioDataFromData(); } } else { return new AudioData({ @@ -17340,6 +19653,35 @@ class AudioSample { }); } } + /** @internal */ + _createAudioDataFromData() { + if (formatIsPlanar(this.format)) { + const size = this.allocationSize({ planeIndex: 0, format: this.format }); + const data = new ArrayBuffer(size * this.numberOfChannels); + for (let i = 0; i < this.numberOfChannels; i++) { + this.copyTo(new Uint8Array(data, i * size, size), { planeIndex: i, format: this.format }); + } + return new AudioData({ + format: this.format, + sampleRate: this.sampleRate, + numberOfFrames: this.numberOfFrames, + numberOfChannels: this.numberOfChannels, + timestamp: this.microsecondTimestamp, + data + }); + } else { + const data = new ArrayBuffer(this.allocationSize({ planeIndex: 0, format: this.format })); + this.copyTo(data, { planeIndex: 0, format: this.format }); + return new AudioData({ + format: this.format, + sampleRate: this.sampleRate, + numberOfFrames: this.numberOfFrames, + numberOfChannels: this.numberOfChannels, + timestamp: this.microsecondTimestamp, + data + }); + } + } /** Convert this audio sample to an AudioBuffer for use with the Web Audio API. */ toAudioBuffer() { if (this._closed) { @@ -17795,6 +20137,7 @@ class EncodedPacketSink { let ended = false; let terminated = false; let outOfBandError = null; + let hasOutOfBandError = false; const timestamps = []; const maxQueueSize = () => Math.max(2, timestamps.length); (async () => { @@ -17816,8 +20159,9 @@ class EncodedPacketSink { ended = true; onQueueNotEmpty(); })().catch((error) => { - if (!outOfBandError) { + if (!hasOutOfBandError) { outOfBandError = error; + hasOutOfBandError = true; onQueueNotEmpty(); } }); @@ -17829,7 +20173,7 @@ class EncodedPacketSink { throw new InputDisposedError(); } else if (terminated) { return { value: void 0, done: true }; - } else if (outOfBandError) { + } else if (hasOutOfBandError) { throw outOfBandError; } else if (packetQueue.length > 0) { const value = packetQueue.shift(); @@ -17870,7 +20214,7 @@ class DecoderWrapper { } class BaseMediaSampleSink { /** @internal */ - mediaSamplesInRange(startTimestamp = 0, endTimestamp = Infinity, options) { + mediaSamplesInRange(startTimestamp = -Infinity, endTimestamp = Infinity, options) { validateTimestamp(startTimestamp); validateTimestamp(endTimestamp); const sampleQueue = []; @@ -17881,14 +20225,16 @@ class BaseMediaSampleSink { let decoderIsFlushed = false; let ended = false; let terminated = false; + let decoder = null; let outOfBandError = null; + let hasOutOfBandError = false; const packetRetrievalOptions = { ...options, verifyKeyPackets: true, metadataOnly: false }; (async () => { - const decoder = await this._createDecoder((sample) => { + decoder = await this._createDecoder((sample) => { onQueueDequeue(); if (sample.timestamp >= endTimestamp) { ended = true; @@ -17915,8 +20261,9 @@ class BaseMediaSampleSink { ({ promise: queueNotEmpty, resolve: onQueueNotEmpty } = promiseWithResolvers()); } }, (error) => { - if (!outOfBandError) { + if (!hasOutOfBandError) { outOfBandError = error; + hasOutOfBandError = true; onQueueNotEmpty(); } }); @@ -17944,17 +20291,19 @@ class BaseMediaSampleSink { if (!terminated && !this._track.input._disposed) { await decoder.flush(); } - decoder.close(); if (!firstSampleQueued && lastSample) { sampleQueue.push(lastSample); } decoderIsFlushed = true; onQueueNotEmpty(); })().catch((error) => { - if (!outOfBandError) { + if (!hasOutOfBandError) { outOfBandError = error; + hasOutOfBandError = true; onQueueNotEmpty(); } + }).finally(() => { + decoder?.close(); }); const track = this._track; const closeSamples = () => { @@ -17967,11 +20316,15 @@ class BaseMediaSampleSink { async next() { while (true) { if (track.input._disposed) { + terminated = true; + ended = true; closeSamples(); throw new InputDisposedError(); } else if (terminated) { return { value: void 0, done: true }; - } else if (outOfBandError) { + } else if (hasOutOfBandError) { + terminated = true; + ended = true; closeSamples(); throw outOfBandError; } else if (sampleQueue.length > 0) { @@ -18011,7 +20364,9 @@ class BaseMediaSampleSink { let { promise: queueDequeue, resolve: onQueueDequeue } = promiseWithResolvers(); let decoderIsFlushed = false; let terminated = false; + let decoder = null; let outOfBandError = null; + let hasOutOfBandError = false; const pushToQueue = (sample) => { sampleQueue.push(sample); onQueueNotEmpty(); @@ -18023,7 +20378,7 @@ class BaseMediaSampleSink { metadataOnly: false }; (async () => { - const decoder = await this._createDecoder((sample) => { + decoder = await this._createDecoder((sample) => { onQueueDequeue(); if (terminated) { sample.close(); @@ -18042,8 +20397,9 @@ class BaseMediaSampleSink { sample.close(); } }, (error) => { - if (!outOfBandError) { + if (!hasOutOfBandError) { outOfBandError = error; + hasOutOfBandError = true; onQueueNotEmpty(); } }); @@ -18053,6 +20409,7 @@ class BaseMediaSampleSink { let maxSequenceNumber = -1; const decodePackets = async () => { assert(lastKeyPacket); + assert(decoder); let currentPacket = lastKeyPacket; decoder.decode(currentPacket); while (currentPacket.sequenceNumber < maxSequenceNumber) { @@ -18072,6 +20429,7 @@ class BaseMediaSampleSink { maxSequenceNumber = -1; }; const flushDecoder = async () => { + assert(decoder); await decoder.flush(); for (let i = 0; i < timestampsOfInterest.length; i++) { pushToQueue(null); @@ -18109,14 +20467,16 @@ class BaseMediaSampleSink { } await flushDecoder(); } - decoder.close(); decoderIsFlushed = true; onQueueNotEmpty(); })().catch((error) => { - if (!outOfBandError) { + if (!hasOutOfBandError) { outOfBandError = error; + hasOutOfBandError = true; onQueueNotEmpty(); } + }).finally(() => { + decoder?.close(); }); const track = this._track; const closeSamples = () => { @@ -18128,11 +20488,13 @@ class BaseMediaSampleSink { async next() { while (true) { if (track.input._disposed) { + terminated = true; closeSamples(); throw new InputDisposedError(); } else if (terminated) { return { value: void 0, done: true }; - } else if (outOfBandError) { + } else if (hasOutOfBandError) { + terminated = true; closeSamples(); throw outOfBandError; } else if (sampleQueue.length > 0) { @@ -18186,12 +20548,13 @@ class VideoDecoderWrapper extends DecoderWrapper { this.colorQueue = []; this.alphaQueue = []; this.merger = null; - this.mergerCreationFailed = false; this.decodedAlphaChunkCount = 0; this.alphaDecoderQueueSize = 0; this.nullAlphaFrameQueue = []; this.currentAlphaPacketIndex = 0; this.alphaRaslSkipped = false; + this.finalSamples = []; + this.mergeAlphaPromises = []; const MatchingCustomDecoder = customVideoDecoders.find((x) => x.supports(codec, decoderConfig)); if (MatchingCustomDecoder) { this.customDecoder = new MatchingCustomDecoder(); @@ -18203,28 +20566,53 @@ class VideoDecoderWrapper extends DecoderWrapper { } this.finalizeAndEmitSample(sample); }; - void this.customDecoderCallSerializer.call(() => this.customDecoder.init()); + this.customDecoder.onError = (error) => { + onError(error); + }; + void this.customDecoderCallSerializer.call(() => this.customDecoder.init()).catch((error) => onError(error)); } else { const colorHandler = (frame) => { if (this.alphaQueue.length > 0) { const alphaFrame = this.alphaQueue.shift(); assert(alphaFrame !== void 0); - this.mergeAlpha(frame, alphaFrame); + void this.mergeAlpha(frame, alphaFrame); } else { this.colorQueue.push(frame); } }; - if (codec === "avc" && this.decoderConfig.description && isChromium()) { - const record = deserializeAvcDecoderConfigurationRecord(toUint8Array(this.decoderConfig.description)); - if (record && record.sequenceParameterSets.length > 0) { - const sps = parseAvcSps(record.sequenceParameterSets[0]); - if (sps && sps.frameMbsOnlyFlag === 0) { - this.decoderConfig = { - ...this.decoderConfig, - hardwareAcceleration: "prefer-software" - }; + if (isChromium()) { + if (codec === "avc" && this.decoderConfig.description) { + const record = deserializeAvcDecoderConfigurationRecord(toUint8Array(this.decoderConfig.description)); + if (record && record.sequenceParameterSets.length > 0) { + const sps = parseAvcSps(record.sequenceParameterSets[0]); + if (sps) { + if (sps.frameMbsOnlyFlag === 0) { + this.decoderConfig = { + ...this.decoderConfig, + hardwareAcceleration: "prefer-software" + }; + } + if (sps.maxDecFrameBuffering !== 0 && sps.bitstreamRestrictionFlag !== 1) { + record.sequenceParameterSets[0] = addAvcBitstreamRestriction(sps); + this.decoderConfig = { + ...this.decoderConfig, + description: serializeAvcDecoderConfigurationRecord(record) + }; + } + } } } + if (!colorSpaceIsComplete(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 ?? false + } + }; + } } const stack = new Error("Decoding error").stack; this.decoder = new VideoDecoder({ @@ -18260,7 +20648,7 @@ class VideoDecoderWrapper extends DecoderWrapper { } if (this.customDecoder) { this.customDecoderQueueSize++; - void this.customDecoderCallSerializer.call(() => this.customDecoder.decode(packet)).then(() => this.customDecoderQueueSize--); + void this.customDecoderCallSerializer.call(() => this.customDecoder.decode(packet)).catch((error) => this.onError(error)).finally(() => this.customDecoderQueueSize--); } else { assert(this.decoder); if (!isWebKit()) { @@ -18269,12 +20657,34 @@ class VideoDecoderWrapper extends DecoderWrapper { if (isChromium() && this.currentPacketIndex === 0) { if (this.codec === "avc") { const filteredNalUnits = []; + let hasFrameData = false; for (const loc of iterateAvcNalUnits(packet.data, this.decoderConfig)) { const type = extractNalUnitTypeForAvc(packet.data[loc.offset]); + hasFrameData || (hasFrameData = type >= 1 && type <= 5); + if (type === AvcNalUnitType.AUD) { + if (hasFrameData) { + break; + } else { + filteredNalUnits.length = 0; + } + } if (!(type >= 20 && type <= 31)) { filteredNalUnits.push(packet.data.subarray(loc.offset, loc.offset + loc.length)); } } + if (!this.decoderConfig.description) { + for (let i = 0; i < filteredNalUnits.length; i++) { + const nalUnit = filteredNalUnits[i]; + if (extractNalUnitTypeForAvc(nalUnit[0]) !== AvcNalUnitType.SPS) { + continue; + } + const sps = parseAvcSps(nalUnit); + if (sps && sps.maxDecFrameBuffering !== 0 && sps.bitstreamRestrictionFlag !== 1) { + filteredNalUnits[i] = addAvcBitstreamRestriction(sps); + } + break; + } + } const newData = concatAvcNalUnits(filteredNalUnits, this.decoderConfig); packet = new EncodedPacket(newData, packet.type, packet.timestamp, packet.duration); } else if (this.codec === "hevc") { @@ -18290,27 +20700,19 @@ class VideoDecoderWrapper extends DecoderWrapper { this.currentPacketIndex++; } decodeAlphaData(packet) { - if (!packet.sideData.alpha || this.mergerCreationFailed) { + if (!packet.sideData.alpha) { this.pushNullAlphaFrame(); return; } if (!this.merger) { - try { - this.merger = new ColorAlphaMerger(); - } catch (error) { - console.error("Due to an error, only color data will be decoded.", error); - this.mergerCreationFailed = true; - this.decodeAlphaData(packet); - return; - } + this.merger = new ColorAlphaMerger(); } if (!this.alphaDecoder) { const alphaHandler = (frame) => { - this.alphaDecoderQueueSize--; if (this.colorQueue.length > 0) { const colorFrame = this.colorQueue.shift(); assert(colorFrame !== void 0); - this.mergeAlpha(colorFrame, frame); + void this.mergeAlpha(colorFrame, frame); } else { this.alphaQueue.push(frame); } @@ -18320,11 +20722,12 @@ class VideoDecoderWrapper extends DecoderWrapper { if (this.colorQueue.length > 0) { const colorFrame = this.colorQueue.shift(); assert(colorFrame !== void 0); - this.mergeAlpha(colorFrame, null); + void this.mergeAlpha(colorFrame, null); } else { this.alphaQueue.push(null); } } + this.alphaDecoderQueueSize--; }; const stack = new Error("Decoding error").stack; this.alphaDecoder = new VideoDecoder({ @@ -18406,22 +20809,30 @@ class VideoDecoderWrapper extends DecoderWrapper { sample.setRotation(this.rotation); this.onSample(sample); } - mergeAlpha(color, alpha) { - if (!alpha) { - const finalSample2 = new VideoSample(color); - this.sampleHandler(finalSample2); - return; + async mergeAlpha(color, alpha) { + const resolver = promiseWithResolvers(); + this.mergeAlphaPromises.push(resolver.promise); + const result = { sample: null }; + this.finalSamples.push(result); + try { + if (!alpha) { + result.sample = new VideoSample(color); + } else { + assert(this.merger); + const finalFrame = await this.merger.merge(color, alpha); + result.sample = new VideoSample(finalFrame); + } + while (this.finalSamples.length > 0 && this.finalSamples[0].sample !== null) { + const next = this.finalSamples.shift(); + this.sampleHandler(next.sample); + } + } catch (error) { + removeItem(this.finalSamples, result); + this.onError(error); + } finally { + removeItem(this.mergeAlphaPromises, resolver.promise); + resolver.resolve(); } - assert(this.merger); - this.merger.update(color, alpha); - color.close(); - alpha.close(); - const finalFrame = new VideoFrame(this.merger.canvas, { - timestamp: color.timestamp, - duration: color.duration ?? void 0 - }); - const finalSample = new VideoSample(finalFrame); - this.sampleHandler(finalSample); } async flush() { if (this.customDecoder) { @@ -18432,6 +20843,7 @@ class VideoDecoderWrapper extends DecoderWrapper { this.decoder.flush(), this.alphaDecoder?.flush() ]); + await Promise.all(this.mergeAlphaPromises); this.colorQueue.forEach((x) => x.close()); this.colorQueue.length = 0; this.alphaQueue.forEach((x) => x?.close()); @@ -18457,8 +20869,12 @@ class VideoDecoderWrapper extends DecoderWrapper { void this.customDecoderCallSerializer.call(() => this.customDecoder.close()); } else { assert(this.decoder); - this.decoder.close(); - this.alphaDecoder?.close(); + if (this.decoder.state !== "closed") { + this.decoder.close(); + } + if (this.alphaDecoder && this.alphaDecoder.state !== "closed") { + this.alphaDecoder.close(); + } this.colorQueue.forEach((x) => x.close()); this.colorQueue.length = 0; this.alphaQueue.forEach((x) => x?.close()); @@ -18471,146 +20887,259 @@ class VideoDecoderWrapper extends DecoderWrapper { this.sampleQueue.length = 0; } } +let mergerWorkerUrl = null; class ColorAlphaMerger { constructor() { - if (typeof OffscreenCanvas !== "undefined") { - this.canvas = new OffscreenCanvas(300, 150); - } else { - this.canvas = document.createElement("canvas"); + this.workers = []; + this.nextWorkerIndex = 0; + this.pendingRequests = /* @__PURE__ */ new Map(); + this.nextRequestId = 0; + } + merge(color, alpha) { + if (this.workers.length === 0) { + if (!mergerWorkerUrl) { + const blob = new Blob([`(${colorAlphaMergerWorkerCode.toString()})()`], { type: "application/javascript" }); + mergerWorkerUrl = URL.createObjectURL(blob); + } + const poolSize = clamp$1(navigator.hardwareConcurrency, 1, 4); + for (let i = 0; i < poolSize; i++) { + const worker2 = new Worker(mergerWorkerUrl); + worker2.addEventListener("message", (event) => { + const data = event.data; + const pending2 = this.pendingRequests.get(data.id); + if (!pending2) { + return; + } + this.pendingRequests.delete(data.id); + if ("error" in data) { + pending2.reject(new Error(data.error)); + } else { + pending2.resolve(data.frame); + } + }); + worker2.addEventListener("error", (event) => { + const error = new Error(event.message || "Color/alpha merge worker error."); + for (const pending2 of this.pendingRequests.values()) { + pending2.reject(error); + } + this.pendingRequests.clear(); + }); + this.workers.push(worker2); + } } - const gl = this.canvas.getContext("webgl2", { - premultipliedAlpha: false - }); - if (!gl) { - throw new Error("Couldn't acquire WebGL 2 context."); - } - this.gl = gl; - this.program = this.createProgram(); - this.vao = this.createVAO(); - this.colorTexture = this.createTexture(); - this.alphaTexture = this.createTexture(); - this.gl.useProgram(this.program); - this.gl.uniform1i(this.gl.getUniformLocation(this.program, "u_colorTexture"), 0); - this.gl.uniform1i(this.gl.getUniformLocation(this.program, "u_alphaTexture"), 1); - } - createProgram() { - const vertexShader = this.createShader(this.gl.VERTEX_SHADER, `#version 300 es - in vec2 a_position; - in vec2 a_texCoord; - out vec2 v_texCoord; - - void main() { - gl_Position = vec4(a_position, 0.0, 1.0); - v_texCoord = a_texCoord; - } - `); - const fragmentShader = this.createShader(this.gl.FRAGMENT_SHADER, `#version 300 es - precision highp float; - - uniform sampler2D u_colorTexture; - uniform sampler2D u_alphaTexture; - in vec2 v_texCoord; - out vec4 fragColor; - - void main() { - vec3 color = texture(u_colorTexture, v_texCoord).rgb; - float alpha = texture(u_alphaTexture, v_texCoord).r; - fragColor = vec4(color, alpha); - } - `); - const program = this.gl.createProgram(); - this.gl.attachShader(program, vertexShader); - this.gl.attachShader(program, fragmentShader); - this.gl.linkProgram(program); - return program; - } - createShader(type, source) { - const shader = this.gl.createShader(type); - this.gl.shaderSource(shader, source); - this.gl.compileShader(shader); - return shader; - } - createVAO() { - const vao = this.gl.createVertexArray(); - this.gl.bindVertexArray(vao); - const vertices = new Float32Array([ - -1, - -1, - 0, - 1, - 1, - -1, - 1, - 1, - -1, - 1, - 0, - 0, - 1, - 1, - 1, - 0 - ]); - const buffer = this.gl.createBuffer(); - this.gl.bindBuffer(this.gl.ARRAY_BUFFER, buffer); - this.gl.bufferData(this.gl.ARRAY_BUFFER, vertices, this.gl.STATIC_DRAW); - const positionLocation = this.gl.getAttribLocation(this.program, "a_position"); - const texCoordLocation = this.gl.getAttribLocation(this.program, "a_texCoord"); - this.gl.enableVertexAttribArray(positionLocation); - this.gl.vertexAttribPointer(positionLocation, 2, this.gl.FLOAT, false, 16, 0); - this.gl.enableVertexAttribArray(texCoordLocation); - this.gl.vertexAttribPointer(texCoordLocation, 2, this.gl.FLOAT, false, 16, 8); - return vao; - } - createTexture() { - const texture = this.gl.createTexture(); - this.gl.bindTexture(this.gl.TEXTURE_2D, texture); - this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_S, this.gl.CLAMP_TO_EDGE); - this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_T, this.gl.CLAMP_TO_EDGE); - this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_MIN_FILTER, this.gl.LINEAR); - this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_MAG_FILTER, this.gl.LINEAR); - return texture; - } - update(color, alpha) { - if (color.displayWidth !== this.canvas.width || color.displayHeight !== this.canvas.height) { - this.canvas.width = color.displayWidth; - this.canvas.height = color.displayHeight; - } - this.gl.activeTexture(this.gl.TEXTURE0); - this.gl.bindTexture(this.gl.TEXTURE_2D, this.colorTexture); - this.gl.texImage2D(this.gl.TEXTURE_2D, 0, this.gl.RGBA, this.gl.RGBA, this.gl.UNSIGNED_BYTE, color); - this.gl.activeTexture(this.gl.TEXTURE1); - this.gl.bindTexture(this.gl.TEXTURE_2D, this.alphaTexture); - this.gl.texImage2D(this.gl.TEXTURE_2D, 0, this.gl.RGBA, this.gl.RGBA, this.gl.UNSIGNED_BYTE, alpha); - this.gl.viewport(0, 0, this.canvas.width, this.canvas.height); - this.gl.clear(this.gl.COLOR_BUFFER_BIT); - this.gl.bindVertexArray(this.vao); - this.gl.drawArrays(this.gl.TRIANGLE_STRIP, 0, 4); + const id = this.nextRequestId++; + const pending = promiseWithResolvers(); + this.pendingRequests.set(id, pending); + const worker = this.workers[this.nextWorkerIndex]; + this.nextWorkerIndex = (this.nextWorkerIndex + 1) % this.workers.length; + worker.postMessage({ id, color, alpha }, { transfer: [color, alpha] }); + return pending.promise; } close() { - this.gl.getExtension("WEBGL_lose_context")?.loseContext(); - this.gl = null; + for (const worker of this.workers) { + worker.terminate(); + } + this.workers.length = 0; + const error = new Error("Color/alpha merger closed."); + for (const pending of this.pendingRequests.values()) { + pending.reject(error); + } + this.pendingRequests.clear(); } } +const colorAlphaMergerWorkerCode = () => { + let cpuAlphaBuffer = null; + let cpuColorBuffer = null; + let chain = Promise.resolve(); + self.addEventListener("message", (event) => { + const { id, color, alpha } = event.data; + chain = chain.then(async () => { + try { + const frame = await merge(color, alpha); + self.postMessage({ id, frame }, { transfer: [frame] }); + } catch (error) { + self.postMessage({ id, error: error.message }); + } finally { + color.close(); + alpha.close(); + } + }); + }); + const merge = async (color, alpha) => { + const format = color.format; + const alphaFormat = alpha.format; + if (!format || !alphaFormat) { + throw new Error("CPU color/alpha merging requires a known VideoFrame format."); + } + const colorIs10 = format.includes("P10"); + const colorIs12 = format.includes("P12"); + const alphaIs10 = alphaFormat.includes("P10"); + const alphaIs12 = alphaFormat.includes("P12"); + if (alphaIs10 !== colorIs10 || alphaIs12 !== colorIs12) { + throw new Error(`CPU color/alpha merging requires the alpha frame to have the same bit depth as the color frame (color: '${format}', alpha: '${alphaFormat}').`); + } + if (format === "RGBX" || format === "RGBA" || format === "BGRX" || format === "BGRA") { + return await mergeInterleavedRgba(color, alpha, format); + } else if (format === "I420" || format === "I420P10" || format === "I420P12" || format === "I422" || format === "I422P10" || format === "I422P12" || format === "I444" || format === "I444P10" || format === "I444P12") { + return await mergePlanarYuv(color, alpha, format); + } else if (format === "NV12") { + return await mergeNv12(color, alpha); + } + throw new Error(`CPU color/alpha merging does not support format '${format}'.`); + }; + const mergeInterleavedRgba = async (color, alpha, format) => { + const width = color.visibleRect?.width ?? color.codedWidth; + const height = color.visibleRect?.height ?? color.codedHeight; + const pixelCount = width * height; + const output = new Uint8Array(pixelCount * 4); + await color.copyTo(output); + const alphaY = await readAlpha(alpha, width, height, 1); + for (let i = 0, j = 3; i < pixelCount; i++, j += 4) { + output[j] = alphaY[i]; + } + const outputFormat = format === "RGBX" || format === "RGBA" ? "RGBA" : "BGRA"; + const init = { + format: outputFormat, + codedWidth: width, + codedHeight: height, + timestamp: color.timestamp, + duration: color.duration ?? void 0, + transfer: [output.buffer] + }; + return new VideoFrame(output, init); + }; + const mergePlanarYuv = async (color, alpha, format) => { + const width = color.visibleRect?.width ?? color.codedWidth; + const height = color.visibleRect?.height ?? color.codedHeight; + const is10 = format.includes("P10"); + const is12 = format.includes("P12"); + const bytesPerSample = is10 || is12 ? 2 : 1; + let chromaW; + let chromaH; + if (format.startsWith("I420")) { + chromaW = Math.ceil(width / 2); + chromaH = Math.ceil(height / 2); + } else if (format.startsWith("I422")) { + chromaW = Math.ceil(width / 2); + chromaH = height; + } else { + chromaW = width; + chromaH = height; + } + const ySamples = width * height; + const uvSamples = chromaW * chromaH; + const yBytes = ySamples * bytesPerSample; + const uvBytes = uvSamples * bytesPerSample; + const aBytes = ySamples * bytesPerSample; + const outputBytes = yBytes + 2 * uvBytes + aBytes; + const output = new Uint8Array(outputBytes); + await color.copyTo(output); + const alphaY = await readAlpha(alpha, width, height, bytesPerSample); + const aOffset = yBytes + 2 * uvBytes; + output.set(alphaY, aOffset); + const outputFormat = format.slice(0, 4) + "A" + format.slice(4); + const init = { + format: outputFormat, + codedWidth: width, + codedHeight: height, + timestamp: color.timestamp, + duration: color.duration ?? void 0, + transfer: [output.buffer] + }; + return new VideoFrame(output, init); + }; + const mergeNv12 = async (color, alpha) => { + const width = color.visibleRect?.width ?? color.codedWidth; + const height = color.visibleRect?.height ?? color.codedHeight; + const ySize = width * height; + const chromaW = Math.ceil(width / 2); + const chromaH = Math.ceil(height / 2); + const uvSize = chromaW * chromaH; + const sourceSize = color.allocationSize(); + if (!cpuColorBuffer || cpuColorBuffer.byteLength !== sourceSize) { + cpuColorBuffer = new Uint8Array(sourceSize); + } + await color.copyTo(cpuColorBuffer); + const output = new Uint8Array(ySize + 2 * uvSize + ySize); + output.set(cpuColorBuffer.subarray(0, ySize), 0); + const uOffset = ySize; + const vOffset = ySize + uvSize; + const uvStart = ySize; + for (let i = 0; i < uvSize; i++) { + output[uOffset + i] = cpuColorBuffer[uvStart + i * 2]; + output[vOffset + i] = cpuColorBuffer[uvStart + i * 2 + 1]; + } + const alphaY = await readAlpha(alpha, width, height, 1); + output.set(alphaY, ySize + 2 * uvSize); + const init = { + format: "I420A", + codedWidth: width, + codedHeight: height, + timestamp: color.timestamp, + duration: color.duration ?? void 0, + transfer: [output.buffer] + }; + return new VideoFrame(output, init); + }; + const readAlpha = async (alpha, width, height, bytesPerSample) => { + const size = alpha.allocationSize(); + if (!cpuAlphaBuffer || cpuAlphaBuffer.byteLength !== size) { + cpuAlphaBuffer = new Uint8Array(size); + } + await alpha.copyTo(cpuAlphaBuffer); + const format = alpha.format; + if (format === "RGBA" || format === "BGRA" || format === "RGBX" || format === "BGRX") { + const rOffset = format === "RGBA" || format === "RGBX" ? 0 : 2; + const pixelCount = width * height; + for (let i = 0; i < pixelCount; i++) { + cpuAlphaBuffer[i] = cpuAlphaBuffer[i * 4 + rOffset]; + } + return cpuAlphaBuffer.subarray(0, pixelCount); + } else { + return cpuAlphaBuffer.subarray(0, width * height * bytesPerSample); + } + }; +}; +const validateVideoSinkDecoderOptions = (decoderOptions) => { + if (!decoderOptions || typeof decoderOptions !== "object") { + throw new TypeError("decoderOptions must be an object."); + } + if (decoderOptions.hardwareAcceleration !== void 0 && !["no-preference", "prefer-hardware", "prefer-software"].includes(decoderOptions.hardwareAcceleration)) { + throw new TypeError("decoderOptions.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'."); + } + if (decoderOptions.optimizeForLatency !== void 0 && typeof decoderOptions.optimizeForLatency !== "boolean") { + throw new TypeError("decoderOptions.optimizeForLatency, when provided, must be a boolean."); + } +}; class VideoSampleSink extends BaseMediaSampleSink { /** Creates a new {@link VideoSampleSink} for the given {@link InputVideoTrack}. */ - constructor(videoTrack) { + constructor(videoTrack, decoderOptions = {}) { if (!(videoTrack instanceof InputVideoTrack)) { throw new TypeError("videoTrack must be an InputVideoTrack."); } + validateVideoSinkDecoderOptions(decoderOptions); super(); this._track = videoTrack; + this._decoderOptions = decoderOptions; } /** @internal */ async _createDecoder(onSample, onError) { if (!await this._track.canDecode()) { - throw new Error("This video track cannot be decoded by this browser. Make sure to check decodability before using a track."); + if (typeof VideoDecoder === "undefined") { + throw new Error(missingWebCodecsClassMessage("VideoDecoder")); + } + throw new Error("This video track cannot be decoded in this environment. Make sure to check decodability before using a track."); } const codec = await this._track.getCodec(); const rotation = await this._track.getRotation(); - const decoderConfig = await this._track.getDecoderConfig(); + let decoderConfig = await this._track.getDecoderConfig(); const timeResolution = await this._track.getTimeResolution(); assert(codec && decoderConfig); + decoderConfig = { + ...decoderConfig, + hardwareAcceleration: this._decoderOptions.hardwareAcceleration, + optimizeForLatency: this._decoderOptions.optimizeForLatency + }; return new VideoDecoderWrapper(onSample, onError, codec, decoderConfig, rotation, timeResolution); } /** @internal */ @@ -18640,7 +21169,7 @@ class VideoSampleSink extends BaseMediaSampleSink { * @param endTimestamp - The timestamp in seconds at which to stop yielding samples (exclusive). * @param options - Options used for the underlying packet retrieval. */ - samples(startTimestamp = 0, endTimestamp = Infinity, options = {}) { + samples(startTimestamp, endTimestamp, options = {}) { return this.mediaSamplesInRange(startTimestamp, endTimestamp, options); } /** @@ -18649,6 +21178,9 @@ class VideoSampleSink extends BaseMediaSampleSink { * once, and is therefore more efficient than manually getting the sample for every timestamp. The iterator may * yield null if no frame is available for a given timestamp. * + * This method is good for sparse access of media data. If you want primarily sequential media access, prefer + * {@link VideoSampleSink.samples} instead. + * * @param timestamps - An iterable or async iterable of timestamps in seconds. * @param options - Options used for the underlying packet retrieval. */ @@ -18692,11 +21224,14 @@ class CanvasSink { if (options.poolSize !== void 0 && (typeof options.poolSize !== "number" || !Number.isInteger(options.poolSize) || options.poolSize < 0)) { throw new TypeError("poolSize must be a non-negative integer."); } + if (options.decoderOptions !== void 0) { + validateVideoSinkDecoderOptions(options.decoderOptions); + } this._videoTrack = videoTrack; this._alpha = options.alpha ?? false; this._options = options; this._fit = options.fit ?? "fill"; - this._videoSampleSink = new VideoSampleSink(videoTrack); + this._videoSampleSink = new VideoSampleSink(videoTrack, options.decoderOptions); this._canvasPool = Array.from({ length: options.poolSize ?? 0 }, () => null); } /** @internal */ @@ -18757,19 +21292,12 @@ class CanvasSink { // Firefox has VideoFrame glitches with opaque canvases }); assert(context); - context.resetTransform(); - if (!canvasIsNew) { - if (!this._alpha && isFirefox()) { - context.fillStyle = "black"; - context.fillRect(0, 0, width, height); - } else { - context.clearRect(0, 0, width, height); - } - } - sample.drawWithFit(context, { + sample._drawWithFitAndMipmapping(canvas, context, { fit: this._fit, rotation: this._rotation, - crop: this._crop + crop: this._crop, + targetIsFresh: canvasIsNew, + fillBlack: !this._alpha && isFirefox() }); const result = { canvas, @@ -18801,7 +21329,7 @@ class CanvasSink { * @param endTimestamp - The timestamp in seconds at which to stop yielding canvases (exclusive). * @param options - Options used for the underlying packet retrieval. */ - async *canvases(startTimestamp = 0, endTimestamp = Infinity, options) { + async *canvases(startTimestamp, endTimestamp, options) { await this._ensureInit(); yield* mapAsyncGenerator(this._videoSampleSink.samples(startTimestamp, endTimestamp, options), (sample) => this._videoSampleToWrappedCanvas(sample)); } @@ -18811,6 +21339,9 @@ class CanvasSink { * therefore more efficient than manually getting the canvas for every timestamp. The iterator may yield null if * no frame is available for a given timestamp. * + * This method is good for sparse access of media data. If you want primarily sequential media access, prefer + * {@link CanvasSink.canvases} instead. + * * @param timestamps - An iterable or async iterable of timestamps in seconds. * @param options - Options used for the underlying packet retrieval. */ @@ -18827,9 +21358,16 @@ class AudioDecoderWrapper extends DecoderWrapper { this.customDecoderCallSerializer = new CallSerializer(); this.customDecoderQueueSize = 0; this.currentTimestamp = null; + this.expectedFirstTimestamp = null; + this.timestampOffset = 0; const sampleHandler = (sample) => { - if (this.currentTimestamp === null || Math.abs(sample.timestamp - this.currentTimestamp) >= sample.duration) { - this.currentTimestamp = sample.timestamp; + let sampleTimestamp = sample.timestamp; + if (this.expectedFirstTimestamp !== null && this.currentTimestamp === null) { + this.timestampOffset = this.expectedFirstTimestamp - sampleTimestamp; + } + sampleTimestamp += this.timestampOffset; + if (this.currentTimestamp === null || Math.abs(sampleTimestamp - this.currentTimestamp) >= sample.duration) { + this.currentTimestamp = sampleTimestamp; } const preciseTimestamp = this.currentTimestamp; this.currentTimestamp += sample.duration; @@ -18852,7 +21390,10 @@ class AudioDecoderWrapper extends DecoderWrapper { } sampleHandler(sample); }; - void this.customDecoderCallSerializer.call(() => this.customDecoder.init()); + this.customDecoder.onError = (error) => { + onError(error); + }; + void this.customDecoderCallSerializer.call(() => this.customDecoder.init()).catch((error) => onError(error)); } else { const stack = new Error("Decoding error").stack; this.decoder = new AudioDecoder({ @@ -18882,26 +21423,32 @@ class AudioDecoderWrapper extends DecoderWrapper { decode(packet) { if (this.customDecoder) { this.customDecoderQueueSize++; - void this.customDecoderCallSerializer.call(() => this.customDecoder.decode(packet)).then(() => this.customDecoderQueueSize--); + void this.customDecoderCallSerializer.call(() => this.customDecoder.decode(packet)).catch((error) => this.onError(error)).finally(() => this.customDecoderQueueSize--); } else { assert(this.decoder); + this.expectedFirstTimestamp ?? (this.expectedFirstTimestamp = packet.timestamp); this.decoder.decode(packet.toEncodedAudioChunk()); } } - flush() { + async flush() { if (this.customDecoder) { - return this.customDecoderCallSerializer.call(() => this.customDecoder.flush()); + await this.customDecoderCallSerializer.call(() => this.customDecoder.flush()); } else { assert(this.decoder); - return this.decoder.flush(); + await this.decoder.flush(); } + this.currentTimestamp = null; + this.expectedFirstTimestamp = null; + this.timestampOffset = 0; } close() { if (this.customDecoder) { void this.customDecoderCallSerializer.call(() => this.customDecoder.close()); } else { assert(this.decoder); - this.decoder.close(); + if (this.decoder.state !== "closed") { + this.decoder.close(); + } } } } @@ -19080,7 +21627,10 @@ class AudioSampleSink extends BaseMediaSampleSink { /** @internal */ async _createDecoder(onSample, onError) { if (!await this._track.canDecode()) { - throw new Error("This audio track cannot be decoded by this browser. Make sure to check decodability before using a track."); + if (typeof AudioDecoder === "undefined") { + throw new Error(missingWebCodecsClassMessage("AudioDecoder")); + } + throw new Error("This audio track cannot be decoded in this environment. Make sure to check decodability before using a track."); } const codec = await this._track.getCodec(); const decoderConfig = await this._track.getDecoderConfig(); @@ -19118,7 +21668,7 @@ class AudioSampleSink extends BaseMediaSampleSink { * @param endTimestamp - The timestamp in seconds at which to stop yielding samples (exclusive). * @param options - Options used for the underlying packet retrieval. */ - samples(startTimestamp = 0, endTimestamp = Infinity, options = {}) { + samples(startTimestamp, endTimestamp, options = {}) { return this.mediaSamplesInRange(startTimestamp, endTimestamp, options); } /** @@ -19127,6 +21677,9 @@ class AudioSampleSink extends BaseMediaSampleSink { * once, and is therefore more efficient than manually getting the sample for every timestamp. The iterator may * yield null if no sample is available for a given timestamp. * + * This method is good for sparse access of media data. If you want primarily sequential media access, prefer + * {@link AudioSampleSink.samples} instead. + * * @param timestamps - An iterable or async iterable of timestamps in seconds. * @param options - Options used for the underlying packet retrieval. */ @@ -19173,7 +21726,7 @@ class AudioBufferSink { * @param endTimestamp - The timestamp in seconds at which to stop yielding buffers (exclusive). * @param options - Options used for the underlying packet retrieval. */ - buffers(startTimestamp = 0, endTimestamp = Infinity, options) { + buffers(startTimestamp, endTimestamp, options) { return mapAsyncGenerator(this._audioSampleSink.samples(startTimestamp, endTimestamp, options), (data) => this._audioSampleToWrappedArrayBuffer(data)); } /** @@ -19285,6 +21838,26 @@ class InputTrack { async isRelativeToUnixEpoch() { return this._backing.isRelativeToUnixEpoch(); } + /** + * Returns the Unix time (in seconds since January 1, 1970 00:00:00 UTC) that the given track timestamp (in seconds) + * maps to, or `null` if there is no such mapping. This provides a piecewise-continuous mapping from this track's + * timestamp space into wall-clock time. Such mapping exists, for example, for HLS playlists with + * `#EXT-X-PROGRAM-DATE-TIME` tags present. + * + * This mapping can be available even when {@link InputTrack.isRelativeToUnixEpoch} is `false`, for example for HLS + * streams with program date time information but with {@link HlsInputFormatOptions.offsetTimestampsByDateTime} + * set to `false`. + */ + async getUnixTimeForTimestamp(timestamp) { + return this._backing.getUnixTimeForTimestamp(timestamp); + } + /** + * Whether the track's timestamps can be mapped to Unix wall clock time via + * {@link InputTrack.getUnixTimeForTimestamp}. + */ + async hasUnixTimeMapping() { + return await this._backing.getUnixTimeForTimestamp(await this.getFirstTimestamp()) !== null; + } /** Returns the track's disposition, i.e. information about its intended usage. */ async getDisposition() { return this._backing.getDisposition(); @@ -19474,7 +22047,7 @@ class InputTrack { } } const requireSync = (value, getterName, asyncName) => { - if (value instanceof Promise) { + if (isThenable(value)) { throw new Error(`'${getterName}' is deprecated and not available synchronously for this track. Use the preferred '${asyncName}()' instead.`); } return value; @@ -19491,7 +22064,7 @@ const toValidatedPredicate = (predicate) => { return result2; }; const result = predicate(track); - if (result instanceof Promise) { + if (isThenable(result)) { return result.then(handle); } return handle(result); @@ -19519,7 +22092,7 @@ class InputVideoTrack extends InputTrack { return requireSync(this._backing.getCodec(), "codec", "getCodec"); } async hasOnlyKeyPackets() { - return await this._backing.getHasOnlyKeyPackets?.() ?? false; + return await this._backing.getHasOnlyKeyPackets?.() ?? await this._backing.getCodec() === "prores"; } /** Returns the width in pixels of the track's coded samples, before any transformations or rotations. */ async getCodedWidth() { @@ -19658,7 +22231,7 @@ class InputVideoTrack extends InputTrack { /** If this method returns true, the track's samples use a high dynamic range (HDR). */ async hasHighDynamicRange() { const colorSpace = await this._backing.getColorSpace(); - return colorSpace.primaries === "bt2020" || colorSpace.primaries === "smpte432" || colorSpace.transfer === "pg" || colorSpace.transfer === "hlg" || colorSpace.matrix === "bt2020-ncl"; + return colorSpace.primaries === "bt2020" || colorSpace.primaries === "smpte432" || colorSpace.transfer === "pq" || colorSpace.transfer === "hlg" || colorSpace.matrix === "bt2020-ncl"; } /** Checks if this track may contain transparent samples with alpha data. */ async canBeTransparent() { @@ -19697,7 +22270,7 @@ class InputVideoTrack extends InputTrack { const support = await VideoDecoder.isConfigSupported(decoderConfig); return support.supported === true; } catch (error) { - console.error("Error during decodability check:", error); + Logging._error("Error during decodability check:", error); return false; } } @@ -19716,6 +22289,100 @@ class InputVideoTrack extends InputTrack { assert(decoderConfig); return determineVideoPacketType(codec, decoderConfig, packet.data); } + /** + * Computes frame rate metrics for this video track, i.e. estimates the video's frame rate. Frame rate is never + * determined from file metadata (which is unreliable) but is always deduced directly from the actual frame + * timestamps. + */ + async computeFrameRateMetrics(options = {}) { + if (!options || typeof options !== "object") { + throw new TypeError("options must be an object."); + } + if (options.targetPacketCount !== void 0 && (!isNumber(options.targetPacketCount) || options.targetPacketCount < 0)) { + throw new TypeError("options.targetPacketCount must be a non-negative number."); + } + const timeResolution = await this.getTimeResolution(); + const targetPacketCount = options.targetPacketCount ?? 256; + const sink = new EncodedPacketSink(this); + const timestamps = []; + let maxTimestamp = -Infinity; + let probedPacketCount = 0; + for await (const packet of sink.packets(void 0, void 0, { metadataOnly: true })) { + if (timestamps.length >= targetPacketCount && packet.timestamp >= maxTimestamp) { + break; + } + timestamps.push(packet.timestamp); + maxTimestamp = Math.max(maxTimestamp, packet.timestamp); + probedPacketCount++; + } + const ticks = new Float64Array(timestamps.length); + for (let i = 0; i < timestamps.length; i++) { + ticks[i] = Math.round(timestamps[i] * timeResolution); + } + ticks.sort(); + let n = 1; + for (let i = 1; i < ticks.length; i++) { + if (ticks[i] !== ticks[n - 1]) { + ticks[n++] = ticks[i]; + } + } + if (n < 2) { + return { + underlyingFrameRate: null, + bestGuessFrameRate: timeResolution, + minFrameRate: timeResolution, + maxFrameRate: timeResolution, + averageFrameRate: timeResolution, + medianFrameRate: timeResolution, + frameRateIsConstant: true, + probedPacketCount + }; + } + const activeTicks = ticks.subarray(0, n); + const underlyingFrameRate = findUnderlyingFrameRate(activeTicks, timeResolution); + const unitRate = underlyingFrameRate ?? timeResolution; + const ticksPerFrame = underlyingFrameRate !== null ? timeResolution / underlyingFrameRate : null; + const histogram = /* @__PURE__ */ new Map(); + let minDifference = Infinity; + let maxDifference = -Infinity; + let totalDifference = 0; + for (let i = 1; i < n; i++) { + const tickDifference = activeTicks[i] - activeTicks[i - 1]; + const difference = ticksPerFrame !== null ? Math.max(1, Math.round(tickDifference / ticksPerFrame)) : tickDifference; + histogram.set(difference, (histogram.get(difference) ?? 0) + 1); + minDifference = Math.min(minDifference, difference); + maxDifference = Math.max(maxDifference, difference); + totalDifference += difference; + } + const differenceCount = n - 1; + const sortedDifferences = [...histogram.keys()].sort((a, b) => a - b); + const middleA = differenceCount - 1 >> 1; + const middleB = differenceCount >> 1; + let medianDifferenceA = 0; + let medianDifferenceB = 0; + let cumulativeCount = 0; + for (const difference of sortedDifferences) { + cumulativeCount += histogram.get(difference); + if (medianDifferenceA === 0 && cumulativeCount > middleA) { + medianDifferenceA = difference; + } + if (cumulativeCount > middleB) { + medianDifferenceB = difference; + break; + } + } + const medianFrameRate = (unitRate / medianDifferenceA + unitRate / medianDifferenceB) / 2; + return { + underlyingFrameRate, + bestGuessFrameRate: underlyingFrameRate !== null ? underlyingFrameRate : getBestGuessFrameRate(medianFrameRate), + minFrameRate: unitRate / maxDifference, + maxFrameRate: unitRate / minDifference, + averageFrameRate: unitRate * differenceCount / totalDifference, + medianFrameRate, + frameRateIsConstant: underlyingFrameRate !== null && minDifference === 1 && maxDifference === 1, + probedPacketCount + }; + } } class InputAudioTrack extends InputTrack { /** @internal */ @@ -19799,7 +22466,7 @@ class InputAudioTrack extends InputTrack { return support.supported === true; } } catch (error) { - console.error("Error during decodability check:", error); + Logging._error("Error during decodability check:", error); return false; } } @@ -19838,7 +22505,7 @@ const toValidatedInputTrackQuery = (query) => { return bool; }; const result = query.filter(track); - if (result instanceof Promise) { + if (isThenable(result)) { return result.then(handle); } else { return handle(result); @@ -19852,7 +22519,7 @@ const toValidatedInputTrackQuery = (query) => { return value; }; const result = query.sortBy(track); - if (result instanceof Promise) { + if (isThenable(result)) { return result.then(handle); } else { return handle(result); @@ -19870,7 +22537,7 @@ const mergeInputTrackQueries = (queryA, queryB) => { } return queryB?.filter?.(track) ?? true; }; - if (resultA instanceof Promise) { + if (isThenable(resultA)) { return resultA.then(handleResultA); } else { return handleResultA(resultA); @@ -19885,7 +22552,7 @@ const mergeInputTrackQueries = (queryA, queryB) => { ...Array.isArray(resultB2) ? resultB2 : [resultB2] ]; }; - if (resultA instanceof Promise || resultB instanceof Promise) { + if (isThenable(resultA) || isThenable(resultB)) { return Promise.all([resultA, resultB]).then(([resultA2, resultB2]) => { return join(resultA2, resultB2); }); @@ -19899,7 +22566,7 @@ const queryInputTracks = async (tracks, query) => { let matched = tracks; if (query?.filter) { const filterMatches = tracks.map((t) => query.filter(t)); - const hasAsyncFilter = filterMatches.some((x) => x instanceof Promise); + const hasAsyncFilter = filterMatches.some((x) => isThenable(x)); if (hasAsyncFilter) { const resolvedFilterMatches = await Promise.all(filterMatches); matched = tracks.filter((_, i) => resolvedFilterMatches[i]); @@ -19911,7 +22578,7 @@ const queryInputTracks = async (tracks, query) => { return matched; } const sortValues = matched.map((t) => query.sortBy(t)); - const hasAsyncSort = sortValues.some((x) => x instanceof Promise); + const hasAsyncSort = sortValues.some((x) => isThenable(x)); const resolvedSortValues = hasAsyncSort ? await Promise.all(sortValues) : sortValues; return matched.map((track, i) => ({ track, sortValue: resolvedSortValues[i] })).sort((a, b) => { const aValues = Array.isArray(a.sortValue) ? a.sortValue : [a.sortValue]; @@ -19928,19 +22595,175 @@ const queryInputTracks = async (tracks, query) => { return 0; }).map((x) => x.track); }; +const findUnderlyingFrameRate = (ticks, resolution) => { + const MAX_DENOMINATOR = 1e6; + const MIN_INLIER_RATIO = 0.98; + const DELTA_TOLERANCE = 1 + 1e-9; + const MAX_EFFECTIVE_FRAME_SPAN = 1e3; + const KNOWN_FRAME_RATES = [ + 12, + 15, + 20, + 24e3 / 1001, + 24, + 25, + 3e4 / 1001, + 30, + 48, + 50, + 6e4 / 1001, + 60, + 100, + 12e4 / 1001, + 120, + 144, + 240 + ]; + if (ticks.length < 2) { + return null; + } + const gaps = new Float64Array(ticks.length - 1); + for (let i = 1; i < ticks.length; i++) { + const gap = ticks[i] - ticks[i - 1]; + if (!(gap > 0)) { + return null; + } + gaps[i - 1] = gap; + } + const sortedGaps = gaps.slice(); + sortedGaps.sort(); + let period = sortedGaps[Math.floor(sortedGaps.length * 0.05)]; + for (let iteration = 0; iteration < 6; iteration++) { + let totalTicks2 = 0; + let totalFrames2 = 0; + for (const gap of gaps) { + const multiple = Math.max(1, Math.round(gap / period)); + if (Math.abs(gap - multiple * period) >= DELTA_TOLERANCE) { + continue; + } + totalTicks2 += gap; + totalFrames2 += multiple; + } + if (totalFrames2 === 0) { + return null; + } + const refinedPeriod = totalTicks2 / totalFrames2; + if (Math.abs(refinedPeriod - period) <= 1e-12 * Math.max(1, period)) { + period = refinedPeriod; + break; + } + period = refinedPeriod; + } + let inlierCount = 0; + let totalTicks = 0; + let totalFrames = 0; + for (const gap of gaps) { + const multiple = Math.max(1, Math.round(gap / period)); + if (Math.abs(gap - multiple * period) >= DELTA_TOLERANCE) { + continue; + } + inlierCount++; + totalTicks += gap; + totalFrames += multiple; + } + if (inlierCount / gaps.length < MIN_INLIER_RATIO) { + return null; + } + period = totalTicks / totalFrames; + const uncertainty = 1 / Math.min(totalFrames, MAX_EFFECTIVE_FRAME_SPAN); + const periodLo = Math.max(Number.EPSILON, period - uncertainty); + const periodHi = period + uncertainty; + const fpsLo = resolution / periodHi; + const fpsHi = resolution / periodLo; + const fittedFps = resolution / period; + let fps = null; + let bestKnownError = Infinity; + for (const candidate of KNOWN_FRAME_RATES) { + if (candidate < fpsLo || candidate > fpsHi) { + continue; + } + const error = Math.abs(candidate / fittedFps - 1); + if (error < bestKnownError) { + fps = candidate; + bestKnownError = error; + } + } + if (fps === null) { + const periodFraction = simplestFractionBetween(periodLo, periodHi, MAX_DENOMINATOR); + const fpsFraction = simplestFractionBetween(fpsLo, fpsHi, MAX_DENOMINATOR); + if (fpsFraction && (!periodFraction || fpsFraction.den < periodFraction.den || fpsFraction.den === periodFraction.den && fpsFraction.num <= periodFraction.num)) { + fps = fpsFraction.num / fpsFraction.den; + } else if (periodFraction) { + fps = resolution * periodFraction.den / periodFraction.num; + } else { + return null; + } + } + const finalPeriod = resolution / fps; + let finalInlierCount = 0; + for (const gap of gaps) { + const multiple = Math.max(1, Math.round(gap / finalPeriod)); + if (Math.abs(gap - multiple * finalPeriod) < DELTA_TOLERANCE) { + finalInlierCount++; + } + } + if (finalInlierCount / gaps.length < MIN_INLIER_RATIO) { + return null; + } + return fps; +}; +const simplestFractionBetween = (lo, hi, maxDenominator) => { + for (let den = 1; den <= maxDenominator; den++) { + const num = Math.floor(lo * den) + 1; + if (num / den < hi) { + return simplifyRational({ num, den }); + } + } + return null; +}; +const getBestGuessFrameRate = (frameRate) => { + const SPECIAL_FRAME_RATES = [ + 24 / 1.001, + 30 / 1.001, + 60 / 1.001, + 120 / 1.001 + ]; + const COMMON_FRAME_RATES = [ + 12, + 15, + 20, + 24, + 25, + 30, + 48, + 50, + 60, + 100, + 120, + 144, + 240 + ]; + const SPECIAL_TOLERANCE = 5e-4; + const COMMON_TOLERANCE = 0.025; + for (const candidate of SPECIAL_FRAME_RATES) { + if (Math.abs(candidate / frameRate - 1) <= SPECIAL_TOLERANCE) { + return candidate; + } + } + let best = frameRate; + let bestError = Infinity; + for (const candidate of COMMON_FRAME_RATES) { + const error = Math.abs(candidate / frameRate - 1); + if (error <= COMMON_TOLERANCE && error < bestError) { + best = candidate; + bestError = error; + } + } + return best; +}; polyfillSymbolDispose(); const DEFAULT_SOURCE_CACHE_GROUP = 1; const ENCRYPTION_KEY_CACHE_GROUP = 2; -let inputFinalizationRegistry = null; -if (typeof FinalizationRegistry !== "undefined") { - inputFinalizationRegistry = new FinalizationRegistry((refs) => { - for (const ref of refs) { - if (!ref.freed) { - ref.free(); - } - } - }); -} class Input extends EventEmitter { /** True if the input has been disposed. */ get disposed() { @@ -19989,7 +22812,6 @@ class Input extends EventEmitter { this._rootRef = options.source; } this._sourceRefs.push(this._rootRef); - inputFinalizationRegistry?.register(this, this._sourceRefs, this); } /** @internal */ get _rootSource() { @@ -20107,8 +22929,9 @@ class Input extends EventEmitter { if (filtered.length === 0) { return 0; } - const firstTimestamps = await Promise.all(filtered.map((x) => x.getFirstTimestamp())); - return Math.min(...firstTimestamps); + const firstPackets = await Promise.all(filtered.map((x) => x._backing.getFirstPacket({ metadataOnly: true }))); + const result = Math.min(...firstPackets.map((x) => x?.timestamp ?? Infinity)); + return result === Infinity ? 0 : result; } /** * Computes the duration of the input file, in seconds. More precisely, returns the largest end timestamp among @@ -20263,8 +23086,10 @@ class Input extends EventEmitter { ref.free(); } this._sourceRefs.length = 0; - inputFinalizationRegistry?.unregister(this); - void this._demuxerPromise?.then((demuxer) => demuxer.dispose()); + if (this._demuxerPromise) { + void this._demuxerPromise.then((demuxer) => demuxer.dispose()).catch(() => { + }); + } } /** * Calls `.dispose()` on the input, implementing the `Disposable` interface for use with @@ -20318,7 +23143,7 @@ class Reader { } const end = start + length; const result = this.source._read(start, end, DEFAULT_MIN_READ_POSITION, DEFAULT_MAX_READ_POSITION); - if (result instanceof Promise) { + if (isThenable(result)) { return result.then((x) => { if (!x) { return null; @@ -20350,7 +23175,7 @@ class Reader { assert(this.fileSizeNonStrict !== null); return this.requestSlice(start, clamp$1(this.fileSizeNonStrict - start, minLength, maxLength)); }; - if (promisedAttempt instanceof Promise) { + if (isThenable(promisedAttempt)) { return promisedAttempt.then(handleAttempt); } else { return handleAttempt(promisedAttempt); @@ -20369,14 +23194,14 @@ class Reader { if (chunks.length === 1 && this.fileSizeNonStrict !== null) { return this.requestSlice(0, this.fileSizeNonStrict); } - const startOffset = chunks.length * CHUNK_SIZE; - let slice = this.requestSliceRange(startOffset, 0, CHUNK_SIZE); - if (slice instanceof Promise) + let slice = this.requestSliceRange(currentSize, 0, CHUNK_SIZE); + if (isThenable(slice)) slice = await slice; - if (!slice) { + if (!slice || slice.length === 0) { break; } - chunks.push(readBytes(slice, slice.length)); + const chunk = readBytes(slice, slice.length); + chunks.push(chunk); currentSize += slice.length; } const joined = new Uint8Array(currentSize); @@ -20774,7 +23599,7 @@ const parseId3V1Tag = (slice, tags) => { const yearText = readId3V1String(slice, 4); const year = Number.parseInt(yearText, 10); if (Number.isInteger(year) && year > 0) { - tags.date ?? (tags.date = new Date(year, 0, 1)); + tags.date ?? (tags.date = new Date(String(year))); } const commentBytes = readBytes(slice, 30); let comment; @@ -20818,20 +23643,21 @@ const readId3V2Header = (slice) => { slice.filePos = startPos; return null; } - const size = decodeSynchsafe(sizeRaw); + let size = decodeSynchsafe(sizeRaw); + if (flags & Id3V2HeaderFlags.Footer) { + size += ID3_V2_HEADER_SIZE; + } return { majorVersion, revision, flags, size }; }; const parseId3V2Tag = (slice, header, tags) => { var _a, _b, _c, _d, _e; if (![2, 3, 4].includes(header.majorVersion)) { - console.warn(`Unsupported ID3v2 major version: ${header.majorVersion}`); + Logging._warn(`Unsupported ID3v2 major version: ${header.majorVersion}`); return; } - const bytes = readBytes(slice, header.size); + const dataSize = header.flags & Id3V2HeaderFlags.Footer ? header.size - ID3_V2_HEADER_SIZE : header.size; + const bytes = readBytes(slice, dataSize); const reader = new Id3V2Reader(header, bytes); - if (header.flags & Id3V2HeaderFlags.Footer) { - reader.removeFooter(); - } if (header.flags & Id3V2HeaderFlags.Unsynchronisation && header.majorVersion === 3) { reader.ununsynchronizeAll(); } @@ -20862,12 +23688,12 @@ const parseId3V2Tag = (slice, header, tags) => { frameUnsynchronized = !!(frame.flags & 1 << 1) || !!(header.flags & Id3V2HeaderFlags.Unsynchronisation); } if (frameEncrypted) { - console.warn(`Skipping encrypted ID3v2 frame ${frame.id}`); + Logging._warn(`Skipping encrypted ID3v2 frame ${frame.id}`); reader.pos = frameEndPos; continue; } if (frameCompressed) { - console.warn(`Skipping compressed ID3v2 frame ${frame.id}`); + Logging._warn(`Skipping compressed ID3v2 frame ${frame.id}`); reader.pos = frameEndPos; continue; } @@ -20987,7 +23813,7 @@ const parseId3V2Tag = (slice, header, tags) => { const yearText = reader.readId3V2EncodingAndText(frameEndPos); const year = Number.parseInt(yearText, 10); if (Number.isInteger(year)) { - tags.date ?? (tags.date = new Date(year, 0, 1)); + tags.date ?? (tags.date = new Date(String(year))); } } break; @@ -21090,10 +23916,6 @@ class Id3V2Reader { this.bytes.set(after, before.length + newBytes.length); this.view = new DataView(this.bytes.buffer); } - removeFooter() { - this.bytes = this.bytes.subarray(0, this.bytes.length - ID3_V2_HEADER_SIZE); - this.view = new DataView(this.bytes.buffer); - } readBytes(length) { const slice = this.bytes.subarray(this.pos, this.pos + length); this.pos += length; @@ -21111,7 +23933,7 @@ class Id3V2Reader { } readU24() { const high = this.view.getUint16(this.pos, false); - const low = this.view.getUint8(this.pos + 1); + const low = this.view.getUint8(this.pos + 2); this.pos += 3; return high * 256 + low; } @@ -21315,59 +24137,64 @@ class AudioEngine { return; await this.stopIterator(); this.audioIterator = this.audioSink.buffers(this.currentTime); + const BATCH_SIZE = 16; while (true) { if (localId !== this.asyncId || this.paused) return; - const nextPromise = this.audioIterator.next(); - const checkStarvation = setInterval(() => { - if (localId !== this.asyncId || this.paused) { - clearInterval(checkStarvation); - return; - } - if (this.audioContext.state === "running" && this.audioContext.currentTime >= this.latestScheduledEndTime - 0.2) { - this.audioContext.suspend(); - this.events.emit("waiting"); - } - }, 50); - let result; + const batch = []; + let batchDone = false; try { - result = await nextPromise; + for (let i = 0; i < BATCH_SIZE; i++) { + const result = await this.audioIterator.next(); + if (result.done) { + batchDone = true; + break; + } + batch.push(result.value); + } } catch (e) { console.error("Audio iterator error:", e); - break; - } finally { - clearInterval(checkStarvation); + batchDone = true; } if (localId !== this.asyncId || this.paused) return; - if (this.audioContext.state === "suspended") { + if (batch.length > 0 && this.audioContext.state === "suspended") { await this.audioContext.resume(); this.events.emit("canplay"); this.events.emit("playing"); } - if (result.done) + for (const { buffer, timestamp } of batch) { + const node = this.audioContext.createBufferSource(); + node.buffer = buffer; + node.connect(this.gainNode); + node.playbackRate.value = this.playbackRate; + const startAt = this.audioContextStartTime + (timestamp - this.playbackTimeAtStart) / this.playbackRate; + const duration = buffer.duration; + const endAt = startAt + duration / this.playbackRate; + const endMediaTime = (endAt - this.audioContextStartTime) * this.playbackRate + this.playbackTimeAtStart; + if (endMediaTime > this.latestScheduledEndTime) { + this.latestScheduledEndTime = endMediaTime; + } + if (startAt >= this.audioContext.currentTime) { + node.start(startAt); + } else { + node.start( + this.audioContext.currentTime, + (this.audioContext.currentTime - startAt) * this.playbackRate + ); + } + this.queuedNodes.add(node); + node.onended = () => this.queuedNodes.delete(node); + } + if (batchDone) break; - const { buffer, timestamp } = result.value; - const node = this.audioContext.createBufferSource(); - node.buffer = buffer; - node.connect(this.gainNode); - node.playbackRate.value = this.playbackRate; - const startAt = this.audioContextStartTime + (timestamp - this.playbackTimeAtStart) / this.playbackRate; - const duration = buffer.duration; - const endAt = startAt + duration / this.playbackRate; - if (endAt > this.latestScheduledEndTime) { - this.latestScheduledEndTime = endAt; + await new Promise((resolve) => setTimeout(resolve, 0)); + const BUFFER_AHEAD = 1; + while (this.latestScheduledEndTime - this.currentTime > BUFFER_AHEAD) { + if (localId !== this.asyncId || this.paused) + return; + await new Promise((resolve) => setTimeout(resolve, 50)); } - if (startAt >= this.audioContext.currentTime) { - node.start(startAt); - } else { - node.start( - this.audioContext.currentTime, - (this.audioContext.currentTime - startAt) * this.playbackRate - ); - } - this.queuedNodes.add(node); - node.onended = () => this.queuedNodes.delete(node); } } async play() { @@ -21380,7 +24207,7 @@ class AudioEngine { await this.audioContext.resume(); } this.audioContextStartTime = this.audioContext.currentTime; - this.latestScheduledEndTime = this.audioContextStartTime; + this.latestScheduledEndTime = this.playbackTimeAtStart; this.paused = false; const id = ++this.asyncId; this.runIterator(id); @@ -21396,7 +24223,7 @@ class AudioEngine { async seek(time) { this.playbackTimeAtStart = Math.max(0, time); this.audioContextStartTime = this.audioContext.currentTime; - this.latestScheduledEndTime = this.audioContextStartTime; + this.latestScheduledEndTime = this.playbackTimeAtStart; const id = ++this.asyncId; if (!this.paused) { this.runIterator(id); @@ -21429,57 +24256,6 @@ class AudioEngine { this.audioSink = null; } } -const M3U8_RE = /\.m3u8(?:$|[?#])/i; -function isHlsSource(src) { - return typeof src === "string" && M3U8_RE.test(src); -} -function normalizeSource(src) { - if (typeof src === "string") - return new UrlSource(src); - if (src instanceof Blob) - return new BlobSource(src); - if (typeof ReadableStream !== "undefined" && src instanceof ReadableStream) { - return new ReadableStreamSource(src); - } - return src ?? null; -} -function createInput(src) { - const source = normalizeSource(src); - if (!source) - return null; - return new Input({ - source, - formats: isHlsSource(src) ? HLS_FORMATS : ALL_FORMATS - }); -} -async function resolveDuration({ input, videoTrack, audioTrack }) { - const tracks = [videoTrack, audioTrack].filter(Boolean); - const referenceTrack = videoTrack || audioTrack; - const isLive = Boolean(referenceTrack && await referenceTrack.isLive()); - let duration = Number.NaN; - if (tracks.length > 0) { - duration = await input.getDurationFromMetadata(tracks, { skipLiveWait: true }); - if (duration === null && !isLive) { - duration = await input.computeDuration(tracks, { skipLiveWait: true }); - } - } - return isLive ? Number.POSITIVE_INFINITY : duration ?? Number.NaN; -} -async function selectPlaybackTracks(input, src) { - const videoTrack = await input.getPrimaryVideoTrack(); - const audioTrack = videoTrack ? await videoTrack.getPrimaryPairableAudioTrack() : await input.getPrimaryAudioTrack(); - const duration = await resolveDuration({ input, videoTrack, audioTrack }); - return { - input, - videoTrack, - audioTrack, - duration, - isLive: Number.isFinite(duration) ? false : Boolean((videoTrack || audioTrack) && await (videoTrack || audioTrack).isLive()), - isHls: isHlsSource(src), - videoMode: isHlsSource(src) ? "auto" : "manual", - audioMode: isHlsSource(src) ? "auto" : "manual" - }; -} async function getTrackBitrate(track) { return await track.getAverageBitrate() ?? await track.getBitrate() ?? 0; } @@ -21516,12 +24292,154 @@ async function getHlsState(media) { return { levels, audios, - currentLevel: media.videoTrack ? levels.find((item) => item.id === media.videoTrack.id) ?? null : null, - currentAudio: media.audioTrack ? audios.find((item) => item.id === media.audioTrack.id) ?? null : null, + currentLevel: media.videoTrack ? levels.find((item) => item.id === media.videoTrack?.id) ?? null : null, + currentAudio: media.audioTrack ? audios.find((item) => item.id === media.audioTrack?.id) ?? null : null, videoMode: media.videoMode ?? "auto", audioMode: media.audioMode ?? "auto" }; } +const M3U8_RE = /\.m3u8(?:$|[?#])/i; +function isHlsSource(src) { + return typeof src === "string" && M3U8_RE.test(src); +} +function normalizeSource(src) { + if (typeof src === "string") + return new UrlSource(src); + if (src instanceof Blob) + return new BlobSource(src); + if (typeof ReadableStream !== "undefined" && src instanceof ReadableStream) + return new ReadableStreamSource(src); + return src ?? null; +} +function createInput(src) { + const source = normalizeSource(src); + if (!source) + return null; + return new Input({ + // Preserve SDK Source/SourceRef pass-through and its historical validation errors. + source, + formats: isHlsSource(src) ? HLS_FORMATS : ALL_FORMATS + }); +} +class LoadSession { + constructor() { + this.active = true; + this.input = null; + this.timers = /* @__PURE__ */ new Set(); + this.controller = typeof AbortController === "undefined" ? void 0 : new AbortController(); + this.cancellation = new Promise((resolve) => { + this.resolveCancellation = resolve; + }); + } + get signal() { + return this.controller?.signal; + } + own(input) { + if (this.active) + this.input = input; + else input.dispose(); + } + defer(callback) { + if (!this.active) + return; + const timer = setTimeout(() => { + this.timers.delete(timer); + if (this.active) + callback(); + }, 0); + this.timers.add(timer); + } + async wait(operation, milliseconds) { + try { + await Promise.race([ + operation, + this.cancellation, + milliseconds > 0 ? this.timeout(milliseconds) : new Promise(() => { + }) + ]); + } finally { + if (this.deadline !== void 0) { + clearTimeout(this.deadline); + this.deadline = void 0; + } + } + } + timeout(milliseconds) { + return new Promise((_, reject) => { + this.deadline = setTimeout(() => reject(new Error("Load timeout")), milliseconds); + }); + } + disposeInput() { + const input = this.input; + this.input = null; + input?.dispose(); + } + cancel() { + if (!this.active) + return; + this.active = false; + for (const timer of this.timers) clearTimeout(timer); + this.timers.clear(); + if (this.deadline !== void 0) { + clearTimeout(this.deadline); + this.deadline = void 0; + } + this.resolveCancellation(); + this.controller?.abort(); + this.disposeInput(); + } +} +async function resolveDuration({ input, videoTrack, audioTrack }) { + const tracks = [videoTrack, audioTrack].filter((track) => track !== null); + const referenceTrack = videoTrack || audioTrack; + const isLive = Boolean(referenceTrack && await referenceTrack.isLive()); + let duration = Number.NaN; + if (tracks.length > 0) { + duration = await input.getDurationFromMetadata(tracks, { skipLiveWait: true }); + if (duration === null && !isLive) + duration = await input.computeDuration(tracks, { skipLiveWait: true }); + } + return isLive ? Number.POSITIVE_INFINITY : duration ?? Number.NaN; +} +async function selectPlaybackTracks(input, src) { + const videoTrack = await input.getPrimaryVideoTrack(); + const audioTrack = videoTrack ? await videoTrack.getPrimaryPairableAudioTrack() : await input.getPrimaryAudioTrack(); + const duration = await resolveDuration({ input, videoTrack, audioTrack }); + const referenceTrack = videoTrack || audioTrack; + const isHls = isHlsSource(src); + return { + input, + videoTrack, + audioTrack, + duration, + isLive: Number.isFinite(duration) ? false : Boolean(referenceTrack && await referenceTrack.isLive()), + isHls, + videoMode: isHls ? "auto" : "manual", + audioMode: isHls ? "auto" : "manual" + }; +} +async function preflightRange(url, enabled, events, signal, isCurrent = () => true) { + if (signal?.aborted || !isCurrent()) + return false; + if (!enabled || typeof url !== "string" || isHlsSource(url)) + return true; + try { + const res = await fetch(url, signal ? { method: "HEAD", signal } : { method: "HEAD" }); + if (signal?.aborted || !isCurrent()) + return false; + const acceptRanges = res.headers.get("accept-ranges"); + if (!acceptRanges || acceptRanges === "none") { + events.emit("error", new Event("RangeNotSupported")); + return false; + } + return true; + } catch (error) { + if (signal?.aborted || !isCurrent()) + return false; + console.warn("Preflight check failed:", error); + return true; + } +} class VideoEngine { constructor({ canvas, @@ -21531,7 +24449,7 @@ class VideoEngine { avSyncTolerance = 0.12, dropLateFrames = false, poster = "", - preflightRange = false + preflightRange: preflightRange2 = false }) { this.canvas = canvas; this.ctx = ctx; @@ -21540,7 +24458,7 @@ class VideoEngine { this.avSyncTolerance = avSyncTolerance; this.dropLateFrames = dropLateFrames; this.poster = poster; - this.preflightRange = preflightRange; + this.preflightRange = preflightRange2; this.input = null; this.videoSink = null; this.videoIterator = null; @@ -21557,21 +24475,8 @@ class VideoEngine { this.posterDrawn = false; this.isFetching = false; } - async preflight(url) { - if (!this.preflightRange || typeof url !== "string" || isHlsSource(url)) - return true; - try { - const res = await fetch(url, { method: "HEAD" }); - const acceptRanges = res.headers.get("accept-ranges"); - if (!acceptRanges || acceptRanges === "none") { - this.events.emit("error", new Event("RangeNotSupported")); - return false; - } - return true; - } catch (e) { - console.warn("Preflight check failed:", e); - return true; - } + async preflight(url, signal, isCurrent) { + return preflightRange(url, this.preflightRange, this.events, signal, isCurrent); } drawPoster() { if (!this.poster || this.posterDrawn) @@ -21763,39 +24668,50 @@ class MediaBunnyEngine { this.loadSeq = 0; this.input = null; this.media = null; + this.loadSession = null; + this.destroyed = false; 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; this.readyState = 0; - setTimeout(() => this.events.emit("waiting"), 0); - setTimeout(() => this.events.emit("loadstart"), 0); + 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 Promise.race([ - this.performLoad(src, id), - loadTimeout > 0 ? this.createTimeout(loadTimeout) : new Promise(() => { - }) - ]); + await session.wait(this.performLoad(src, id, session), loadTimeout); } catch (err) { if (id !== this.loadSeq) return; - this.loadSeq++; + 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; this.events.emit("error"); } } - async performLoad(src, id) { - if (!await this.video.preflight(src)) + 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) { @@ -21803,12 +24719,10 @@ class MediaBunnyEngine { this.audio.handleNoAudioTrack(); return; } + session.own(input); const media = await selectPlaybackTracks(input, src); - if (id !== this.loadSeq) { - input.dispose(); + if (id !== this.loadSeq) return; - } - this.disposeInput(); this.input = input; this.media = media; let videoMetadataLoaded = !media.videoTrack; @@ -21847,10 +24761,8 @@ class MediaBunnyEngine { } catch (err) { if (id !== this.loadSeq) return; - this.error = { code: 4, message: err.message }; - this.networkState = 3; - this.events.emit("error"); console.error("MediaBunny load error:", err); + throw err; } } createTimeout(ms) { @@ -21859,7 +24771,7 @@ class MediaBunnyEngine { }); } disposeInput() { - this.input?.dispose(); + this.loadSession?.disposeInput(); this.input = null; this.media = null; } @@ -21993,6 +24905,11 @@ class MediaBunnyEngine { this.video.setPlaybackRate(rate); } destroy() { + if (this.destroyed) + return; + this.destroyed = true; + this.loadSeq++; + this.loadSession?.cancel(); this.pause(); this.disposeInput(); this.audio.destroy(); diff --git a/package.json b/package.json index 8eecf9a86..58569b15c 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/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-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": "node --test test/mediabunny.test.js test/mediabunny-load.test.js test/mediabunny-input.test.js" }, "browserslist": "last 1 Chrome version", "devDependencies": { @@ -108,6 +108,7 @@ "yaml": "2.8.2" }, "resolutions": { + "**/@types/dom-webcodecs": "0.1.19", "dts-bundle-generator/typescript": "5.9.3" } } diff --git a/packages/artplayer-proxy-mediabunny/ARCHITECTURE.md b/packages/artplayer-proxy-mediabunny/ARCHITECTURE.md new file mode 100644 index 000000000..bf91e996d --- /dev/null +++ b/packages/artplayer-proxy-mediabunny/ARCHITECTURE.md @@ -0,0 +1,92 @@ +# MediaBunny proxy maintenance + +The public entry is `src/index.js`: an optional-options factory returns the existing +ArtPlayer proxy callback and an HTMLCanvasElement. Public declarations remain in +`types/artplayer-proxy-mediabunny.d.ts`. The input migration does not change those +declarations, the factory signature, canvas forwarding, or package entrypoints. + +## Current module map + +| Module | Responsibility | +| --- | --- | +| `input.ts` | String/Blob/ReadableStream normalization, SDK Source/SourceRef pass-through, HLS detection and Input construction | +| `media.ts` | Internal SDK-backed media and track-mode types; not public consumer types | +| `tracks.ts` | Primary video and pairable audio selection, metadata/computed/live duration | +| `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 | +| `VideoEngine.js` / `AudioEngine.js` | Current native decoding, rendering, seeking, Web Audio clock and scheduling | +| `VideoShim.js` / `EventTarget.js` | Current video-like descriptors and event forwarding | +| `m3u8.js` | Current ArtPlayer control/setting integration | + +The six TypeScript modules use strict checking with `skipLibCheck: false` and no +ambient Node types. Remaining JavaScript is explicitly scheduled in PKG-MB-04/05/06/07/08. +Do not describe the whole package as migrated yet. + +## Input and cancellation flow + +Each `engine.load` invalidates the previous generation and cancels its session. +The new session owns an Input immediately after construction, before asynchronous +track selection. `engine.input` and `engine.media` become visible only after selection. +The session continues to own the Input during playback; these fields are aliases, +not separate disposal owners. Repeated cancellation/disposal is harmless. + +Source replacement, timeout and destroy release that Input through SDK `Input.dispose()`. +MediaBunny controls its media fetch cancellation; do not pass a signal in UrlSource's +`requestInit` (the SDK explicitly excludes it). The separate HEAD check uses its own +AbortController. Without that constructor, stale HEAD results/errors are still ignored, +although the network request cannot be physically aborted by this adapter. + +Cancellation settles the old load Promise without waiting for a stalled read. Its late +fulfillment/rejection remains observed but cannot update the current load. Active errors +retain `code: 4` and the SDK message; active timeout retains `Load timeout` and networkState 3. +Successful completion clears its deadline. Normal deferred waiting/loadstart ordering +remains; cancellation clears both callbacks. Destroy makes future loads inert. + +Range behavior remains opt-in: no/`none` accept-ranges emits an error with a +`RangeNotSupported` detail and returns false, without setting the engine error property. +Network failure warns and continues; HLS strings and non-string sources skip HEAD. +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. + +## Types and dependencies + +The locked runtime SDK remains MediaBunny 1.56.1. Its pinned WebCodecs declaration +0.1.13 duplicates types now present in TypeScript 5.9.3's DOM library. The root Yarn +resolution selects `@types/dom-webcodecs@0.1.19` for both dependency paths; the SDK +itself is unchanged. This is a build-time declaration correction, not a browser polyfill. +The package typecheck adds ESNext.Disposable for SDK declarations while keeping the +ES2020 target; production source does not use `using` or require Symbol.dispose. +Public consumer declarations do not import these SDK types; preserve that boundary +until the separate consumer-compatibility task verifies any proposed change. + +## Validation and remaining work + +```sh +yarn test:mediabunny +node node_modules/typescript/bin/tsc -p packages/artplayer-proxy-mediabunny/tsconfig.json +yarn build artplayer-proxy-mediabunny +yarn test:browser test/browser/mediabunny-inputs.spec.js test/browser/mediabunny.spec.js test/browser/mediabunny-load.spec.js +``` + +Node tests use actual SDK parsing and controlled lifecycle interleavings. Browser tests +include native decoding and separate pending ReadableStream cancellation with real timers. +`ARTPLAYER_MB_BASELINE=1` runs candidate load assertions against the immutable old main +to reproduce failures. `ARTPLAYER_MB_ARTIFACT` selects a built UMD main/legacy bundle; +`ARTPLAYER_MB_BROWSER_CANDIDATE=1` restricts browser runs to that candidate. Browser +reports record the implementation hash; archive the report and results before rerunning. + +The source of historical truth is `refactor/baselines/mb-release.json` and its Git/npm +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 +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 +races. PKG-MB-09 owns long-run AV sync, full core/proxy/plugin combinations and device +validation. PKG-MB-10 owns the demo, installed package and MPL/source notice gate. +Windows WebKit without WebCodecs/Web Audio is recorded as a capability failure, +not successful playback or a claim about all Safari installations. diff --git a/packages/artplayer-proxy-mediabunny/README.md b/packages/artplayer-proxy-mediabunny/README.md index be1fd5ee1..82fafd7f0 100644 --- a/packages/artplayer-proxy-mediabunny/README.md +++ b/packages/artplayer-proxy-mediabunny/README.md @@ -9,3 +9,7 @@ mediabunny proxy for ArtPlayer, including `m3u8` playback through Mediabunny's H ## License MIT © Harvey Zhao + +## Maintenance + +See [ARCHITECTURE.md](ARCHITECTURE.md) for current modules, resource ownership, compatibility boundaries and validation commands. diff --git a/packages/artplayer-proxy-mediabunny/dist/artplayer-proxy-mediabunny.js b/packages/artplayer-proxy-mediabunny/dist/artplayer-proxy-mediabunny.js index d2213fb12..dd37b8f40 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?(t.artplayerProxyMediabunny=t(),define(function(){return t.artplayerProxyMediabunny})):(e="undefined"!==typeof globalThis?globalThis:e||self).artplayerProxyMediabunny=t()}(this,function(){"use strict";function e(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 t{constructor(){this.listeners=new Map}addEventListener(e,t){this.listeners.has(e)||this.listeners.set(e,[]),this.listeners.get(e).push(t)}removeEventListener(e,t){const i=this.listeners.get(e);if(!i)return;const r=i.indexOf(t);r>=0&&i.splice(r,1)}emit(e,t){const i=new Event(e);i.detail=t;const r=this.listeners.get(e);r&&r.forEach(e=>e(i))}}function i(e){if(!e)throw new Error("Assertion failed.")}const r=e=>{const t=(e%360+360)%360;if(0===t||90===t||180===t||270===t)return t;throw new Error(`Invalid rotation ${e}.`)},a=e=>e&&e[e.length-1],s=e=>{let t=0;for(;0===e.readBits(1)&&t<32;)t++;if(t>=32)throw new Error("Invalid exponential-Golomb code.");return(1<{const t=s(e);return 0===(1&t)?-(t>>1):t+1>>1},o=e=>e.constructor===Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),c=e=>e.constructor===DataView?e:ArrayBuffer.isView(e)?new DataView(e.buffer,e.byteOffset,e.byteLength):new DataView(e),l=new TextDecoder,u=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])),d={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},h=u(d),f={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},m=u(f),p={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},g=u(p),k=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 y=/^[0-9a-fA-F]+$/,w=e=>[...e].map(e=>e.toString(16).padStart(2,"0")).join(""),T=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,S=(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},v=(e,t,i)=>{const r=P(e,i(t),i);e.splice(r+1,0,t)},I=()=>{let e,t;return{promise:new Promise((i,r)=>{e=i,t=r}),resolve:e,reject:t}},x=(e,t)=>{for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},C=(e,t)=>{for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},B=e=>{throw new Error(`Unexpected value: ${e}`)},E=(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},_=(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)},A=(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}}),F=(e,t,i)=>Math.max(t,Math.min(i,e)),R="und",D=e=>{const t=Math.round(e);return Math.abs(e/t-1)<10*Number.EPSILON?t:e},M=(e,t)=>Math.round(e*t)/t,N=(e,t)=>Math.floor(e/t)*t,O=/^[a-z]{3}$/,L=e=>O.test(e),z=1e6*(1+Number.EPSILON),U=(e,t)=>{const i={...e,...t};if(e.headers||t.headers){const r=e.headers?q(e.headers):{},a=t.headers?q(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},q=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},W=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(console.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 ce(1e3*e),a())throw n}};class V{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}let H=null;const K=()=>null!==H?H:H=!("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 j=null;const X=()=>null!==j?j:j="undefined"!==typeof navigator&&navigator.userAgent?.includes("Firefox");let $=null;const Q=()=>null!==$?$:$=!("undefined"===typeof navigator||!navigator.vendor?.includes("Google Inc")&&!/Chrome/.test(navigator.userAgent));let G=null;const Y=()=>{if(null!==G)return G;if("undefined"===typeof navigator)return null;const e=/\bChrome\/(\d+)/.exec(navigator.userAgent);return e?G=Number(e[1]):null},J=(e,t)=>-1!==e?e:t,Z=(e,t,i,r)=>e<=r&&i<=t,ee=e=>{const t=atob(e),i=new Uint8Array(t.length);for(let r=0;r{Symbol.dispose??(Symbol.dispose=Symbol("Symbol.dispose"))},ie=e=>"number"===typeof e&&!Number.isNaN(e),re=(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("/")},ae=(e,t)=>{let i=0;for(let r=0;r{let i=-1,r=1/0;for(let a=0;a{i(Number.isInteger(e.num)),i(Number.isInteger(e.den)),i(0!==e.den);let t=Math.abs(e.num),r=Math.abs(e.den);for(;0!==r;){const e=t%r;t=r,r=e}const a=t||1;return{num:e.num/a,den:e.den/a}},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.`)},ce=e=>new Promise(t=>setTimeout(t,e));class le{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)}}}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 de{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 he={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1};class fe{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<{if(!e||e.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");const t=new fe(e);let i=t.readBits(5);31===i&&(i=32+t.readBits(6));const r=t.readBits(4);let a=null;15===r?a=t.readBits(24):r=1&&s<=7&&(n=pe[s]),{objectType:i,frequencyIndex:r,sampleRate:a,channelConfiguration:s,numberOfChannels:n}},ke=["avc","hevc","vp9","av1","vp8"],be=["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"],ye=["aac","opus","mp3","vorbis","flac","ac3","eac3",...be],we=[{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}],Te=[{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}],Se=".01.01.01.01.00",Pe=".0.110.01.01.01.0",ve=e=>{const{codec:t,codecDescription:r,colorSpace:s,avcCodecInfo:n,hevcCodecInfo:o,vp9CodecInfo:l,av1CodecInfo:u}=e;if("avc"===t){if(i(null!==e.avcType),n){const t=new Uint8Array([n.avcProfileIndication,n.profileCompatibility,n.avcLevelIndication]);return`avc${e.avcType}.${w(t)}`}if(!r||r.byteLength<4)throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${e.avcType}.${w(r.subarray(1,4))}`}if("hevc"===t){let e,t,i,a,s,n;if(o)e=o.generalProfileSpace,t=o.generalProfileIdc,i=T(o.generalProfileCompatibilityFlags),a=o.generalTierFlag,s=o.generalLevelIdc,n=[...o.generalConstraintIndicatorFlags];else{if(!r||r.byteLength<23)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");const o=c(r),l=o.getUint8(1);e=l>>6&3,t=31&l,i=T(o.getUint32(2)),a=l>>5&1,s=o.getUint8(12),n=[];for(let e=0;e<6;e++)n.push(o.getUint8(6+e))}let l="hev1.";for(l+=["","A","B","C"][e]+t,l+=".",l+=i.toString(16).toUpperCase(),l+=".",l+=0===a?"L":"H",l+=s;n.length>0&&0===n[n.length-1];)n.pop();return n.length>0&&(l+=".",l+=n.map(e=>e.toString(16).toUpperCase()).join(".")),l}if("vp8"===t)return"vp8";if("vp9"===t){if(!l){const t=e.width*e.height;let i=a(Te).level;for(const e of Te)if(t<=e.maxPictureSize){i=e.level;break}return`vp09.00.${i.toString().padStart(2,"0")}.08`}let t=`vp09.${l.profile.toString().padStart(2,"0")}.${l.level.toString().padStart(2,"0")}.${l.bitDepth.toString().padStart(2,"0")}.${l.chromaSubsampling.toString().padStart(2,"0")}`;return t+=`.${l.colourPrimaries.toString().padStart(2,"0")}.${l.transferCharacteristics.toString().padStart(2,"0")}.${l.matrixCoefficients.toString().padStart(2,"0")}.${l.videoFullRangeFlag.toString().padStart(2,"0")}`,t.endsWith(Se)&&(t=t.slice(0,-15)),t}if("av1"===t){if(!u){const t=e.width*e.height;let i=a(Te).level;for(const e of Te)if(t<=e.maxPictureSize){i=e.level;break}return`av01.0.${i.toString().padStart(2,"0")}M.08`}const t=u.profile,i=u.level.toString().padStart(2,"0"),r=u.tier?"H":"M",n=u.bitDepth.toString().padStart(2,"0"),o=u.monochrome?"1":"0",c=100*u.chromaSubsamplingX+10*u.chromaSubsamplingY+1*(u.chromaSubsamplingX&&u.chromaSubsamplingY?u.chromaSamplePosition:0),l=s?.primaries?d[s.primaries]:1,h=s?.transfer?f[s.transfer]:1,m=s?.matrix?p[s.matrix]:1,g=s?.fullRange?1:0;let k=`av01.${t}.${i}${r}.${n}`;return k+=`.${o}.${c.toString().padStart(3,"0")}`,k+=`.${l.toString().padStart(2,"0")}`,k+=`.${h.toString().padStart(2,"0")}`,k+=`.${m.toString().padStart(2,"0")}`,k+=`.${g}`,k.endsWith(Pe)&&(k=k.slice(0,-17)),k}throw new TypeError(`Unhandled codec '${t}'.`)},Ie=e=>{const{codec:t,codecDescription:i,aacCodecInfo:r}=e;if("aac"===t){if(!r)throw new TypeError("AAC codec info must be provided.");if(r.isMpeg2)return"mp4a.67";{let e;if(null!==r.objectType)e=r.objectType;else{e=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(t&&be.includes(t))return t;throw new TypeError(`Unhandled codec '${t}'.`)},xe=48e3,Ce=/^pcm-([usf])(\d+)+(be)?$/,Be=e=>{if(i(be.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=Ce.exec(e);let r;i(t),r="u"===t[1]?"unsigned":"s"===t[1]?"signed":"float";return{dataType:r,sampleSize:Number(t[2])/8,littleEndian:"be"!==t[3],silentValue:"pcm-u8"===e?128:0}},Ee=e=>e.startsWith("avc1")||e.startsWith("avc3")?"avc":e.startsWith("hev1")||e.startsWith("hvc1")?"hevc":"vp8"===e?"vp8":e.startsWith("vp09")?"vp9":e.startsWith("av01")?"av1":"mp3"===e||"mp4a.69"===e||"mp4a.6B"===e||"mp4a.6b"===e||"mp4a.40.34"===e?"mp3":e.startsWith("mp4a.40.")||"mp4a.67"===e?"aac":"opus"===e?"opus":"vorbis"===e?"vorbis":"flac"===e?"flac":"ac-3"===e||"ac3"===e?"ac3":"ec-3"===e||"eac3"===e?"eac3":"ulaw"===e?"ulaw":"alaw"===e?"alaw":Ce.test(e)?e:"webvtt"===e?"webvtt":null,_e=[44100,48e3,32e3],Ae=[-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],Fe=1483304551,Re=1231971951,De=(e,t)=>3===e?3===t?21:36:3===t?13:21,Me=(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=Ae[16*n*4+16*l+(a>>4&15)];if(-1===g)return{header:null,bytesAdvanced:1};const k=1e3*g,b=_e[u]>>n+o,y=((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 Oe,Le;(Le=Oe||(Oe={}))[Le.FrameCount=1]="FrameCount",Le[Le.FileSize=2]="FileSize",Le[Le.Toc=4]="Toc";const ze=[48e3,44100,32e3],Ue=[24e3,22050,16e3];var qe,We,Ve,He;(We=qe||(qe={}))[We.NON_IDR_SLICE=1]="NON_IDR_SLICE",We[We.SLICE_DPA=2]="SLICE_DPA",We[We.SLICE_DPB=3]="SLICE_DPB",We[We.SLICE_DPC=4]="SLICE_DPC",We[We.IDR=5]="IDR",We[We.SEI=6]="SEI",We[We.SPS=7]="SPS",We[We.PPS=8]="PPS",We[We.AUD=9]="AUD",We[We.SPS_EXT=13]="SPS_EXT",(He=Ve||(Ve={}))[He.RASL_N=8]="RASL_N",He[He.RASL_R=9]="RASL_R",He[He.BLA_W_LP=16]="BLA_W_LP",He[He.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",He[He.VPS_NUT=32]="VPS_NUT",He[He.SPS_NUT=33]="SPS_NUT",He[He.PPS_NUT=34]="PPS_NUT",He[He.AUD_NUT=35]="AUD_NUT",He[He.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",He[He.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT";const Ke=function*(e){let t=0,i=-1;for(;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&o(t.description)[4];return je(e,i+1)}return Ke(e)},$e=e=>31&e,Qe=e=>{const t=[],i=e.length;for(let r=0;r{const t=e.reduce((e,t)=>e+Ge.byteLength+t.byteLength,0),i=new Uint8Array(t);let r=0;for(const a of e)i.set(Ge,r),r+=Ge.byteLength,i.set(a,r),r+=a.byteLength;return i},Je=(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:_(e,a,s.byteLength);break;case 4:e.setUint32(a,s.byteLength,!1)}a+=t,r.set(s,a),a+=s.byteLength}return r},Ze=e=>{try{const t=[],r=[],a=[];for(const i of Ke(e)){const s=e.subarray(i.offset,i.offset+i.length),n=$e(s[0]);n===qe.SPS?t.push(s):n===qe.PPS?r.push(s):n===qe.SPS_EXT&&a.push(s)}if(0===t.length)return null;if(0===r.length)return null;const s=t[0],n=tt(s);i(null!==n);const o=100===n.profileIdc||110===n.profileIdc||122===n.profileIdc||144===n.profileIdc;return{configurationVersion:1,avcProfileIndication:n.profileIdc,profileCompatibility:n.constraintFlags,avcLevelIndication:n.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:t,pictureParameterSets:r,chromaFormat:o?n.chromaFormatIdc:null,bitDepthLumaMinus8:o?n.bitDepthLumaMinus8:null,bitDepthChromaMinus8:o?n.bitDepthChromaMinus8:null,sequenceParameterSetExt:o?a:null}}catch(t){return console.error("Error building AVC Decoder Configuration Record:",t),null}},et={1:{num:1,den:1},2:{num:12,den:11},3:{num:10,den:11},4:{num:16,den:11},5:{num:40,den:33},6:{num:24,den:11},7:{num:20,den:11},8:{num:32,den:11},9:{num:80,den:33},10:{num:18,den:11},11:{num:15,den:11},12:{num:64,den:33},13:{num:160,den:99},14:{num:4,den:3},15:{num:3,den:2},16:{num:2,den:1}},tt=e=>{try{const t=new fe(Qe(e));t.skipBits(1),t.skipBits(2);if(7!==t.readBits(5))return null;const r=t.readAlignedByte(),o=t.readAlignedByte(),c=t.readAlignedByte();s(t);let l=1,u=0,d=0,h=0;if(100===r||110===r||122===r||244===r||44===r||83===r||86===r||118===r||128===r){l=s(t),3===l&&(h=t.readBits(1)),u=s(t),d=s(t),t.skipBits(1);if(t.readBits(1))for(let e=0;e<(3!==l?8:12);e++){if(t.readBits(1)){const i=e<6?16:64;let r=8,a=8;for(let e=0;ee.level>=c)??a(we),r=Math.min(Math.floor(i.maxDpbMbs/(e*t)),16);x=r,C=r}else x=0,C=0}return i(null!==C),{profileIdc:r,constraintFlags:o,levelIdc:c,frameMbsOnlyFlag:w,chromaFormatIdc:l,bitDepthLumaMinus8:u,bitDepthChromaMinus8:d,codedWidth:g,codedHeight:k,displayWidth:b,displayHeight:y,pixelAspectRatio:I,colourPrimaries:T,matrixCoefficients:P,transferCharacteristics:S,fullRangeFlag:v,numReorderFrames:x,maxDecFrameBuffering:C}}catch(t){return console.error("Error parsing AVC SPS:",t),null}},it=e=>{const t=s(e);e.skipBits(4),e.skipBits(4);for(let i=0;i<=t;i++)s(e),s(e),e.skipBits(1);e.skipBits(5),e.skipBits(5),e.skipBits(5),e.skipBits(5)},rt=(e,t)=>{if(t.description){const i=3&o(t.description)[21];return je(e,i+1)}return Ke(e)},at=e=>e>>1&63,st=e=>{try{const t=new fe(Qe(e));t.skipBits(16),t.readBits(4);const i=t.readBits(3),r=t.readBits(1),{general_profile_space:a,general_tier_flag:n,general_profile_idc:o,general_profile_compatibility_flags:c,general_constraint_indicator_flags:l,general_level_idc:u}=ot(t,i);s(t);const d=s(t);let h=0;3===d&&(h=t.readBits(1));const f=s(t),m=s(t);let p=f,g=m;if(t.readBits(1)){const e=s(t),i=s(t),r=s(t),a=s(t);let n=1,o=1;const c=0===h?d:0;1===c?(n=2,o=2):2===c&&(n=2,o=1),p-=(e+i)*n,g-=(r+a)*o}const k=s(t),b=s(t);s(t);const y=t.readBits(1);let w=0;for(let e=y?0:i;e<=i;e++)s(t),w=s(t),s(t);s(t),s(t),s(t),s(t),s(t),s(t),t.readBits(1)&&t.readBits(1)&&ct(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(4),t.skipBits(4),s(t),s(t),t.skipBits(1));const T=s(t);if(lt(t,T),t.readBits(1)){const e=s(t);for(let i=0;i{try{const t=[],i=[],r=[],a=[];for(const s of Ke(e)){const n=e.subarray(s.offset,s.offset+s.length),o=at(n[0]);o===Ve.VPS_NUT?t.push(n):o===Ve.SPS_NUT?i.push(n):o===Ve.PPS_NUT?r.push(n):o!==Ve.PREFIX_SEI_NUT&&o!==Ve.SUFFIX_SEI_NUT||a.push(n)}if(0===i.length||0===r.length)return null;const o=st(i[0]);if(!o)return null;let c=0;if(r.length>0){const e=r[0],t=new fe(Qe(e));t.skipBits(16),s(t),s(t),t.skipBits(1),t.skipBits(1),t.skipBits(3),t.skipBits(1),t.skipBits(1),s(t),s(t),n(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&s(t),n(t),n(t),t.skipBits(1),t.skipBits(1),t.skipBits(1),t.skipBits(1);const i=t.readBits(1),a=t.readBits(1);c=i||a?i&&!a?2:!i&&a?3:0:0}const l=[...t.length?[{arrayCompleteness:1,nalUnitType:Ve.VPS_NUT,nalUnits:t}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:Ve.SPS_NUT,nalUnits:i}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:Ve.PPS_NUT,nalUnits:r}]:[],...a.length?[{arrayCompleteness:1,nalUnitType:at(a[0][0]),nalUnits:a}]:[]];return{configurationVersion:1,generalProfileSpace:o.generalProfileSpace,generalTierFlag:o.generalTierFlag,generalProfileIdc:o.generalProfileIdc,generalProfileCompatibilityFlags:o.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:o.generalConstraintIndicatorFlags,generalLevelIdc:o.generalLevelIdc,minSpatialSegmentationIdc:o.minSpatialSegmentationIdc,parallelismType:c,chromaFormatIdc:o.chromaFormatIdc,bitDepthLumaMinus8:o.bitDepthLumaMinus8,bitDepthChromaMinus8:o.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:o.spsMaxSubLayersMinus1+1,temporalIdNested:o.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:l}}catch(t){return console.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&&n(e);for(let t=0;t{const i=[];for(let r=0;r{let a=0,n=0,o=0;if(0!==t&&(n=e.readBits(1)),n){if(t===i){o=t-(s(e)+1)}else o=t-1;e.readBits(1),s(e);const n=r[o]??0;for(let t=0;t<=n;t++){e.readBits(1)||e.readBits(1)}a=r[o]}else{const t=s(e),i=s(e);for(let r=0;r{let i=2,r=2,a=2,n=0,o=0,c={num:1,den:1};if(e.readBits(1)){const t=e.readBits(8);if(255===t)c={num:e.readBits(16),den:e.readBits(16)};else{const e=et[t];e&&(c=e)}}return e.readBits(1)&&e.readBits(1),e.readBits(1)&&(e.readBits(3),n=e.readBits(1),e.readBits(1)&&(i=e.readBits(8),r=e.readBits(8),a=e.readBits(8))),e.readBits(1)&&(s(e),s(e)),e.readBits(1),e.readBits(1),e.readBits(1),e.readBits(1)&&(s(e),s(e),s(e),s(e)),e.readBits(1)&&(e.readBits(32),e.readBits(32),e.readBits(1)&&s(e),e.readBits(1)&&ht(e,!0,t)),e.readBits(1)&&(e.readBits(1),e.readBits(1),e.readBits(1),o=s(e),s(e),s(e),s(e),s(e)),{pixelAspectRatio:c,colourPrimaries:i,transferCharacteristics:r,matrixCoefficients:a,fullRangeFlag:n,minSpatialSegmentationIdc:o}},ht=(e,t,i)=>{let r=!1,a=!1,n=!1;r=1===e.readBits(1),a=1===e.readBits(1),(r||a)&&(n=1===e.readBits(1),n&&(e.readBits(8),e.readBits(5),e.readBits(1),e.readBits(5)),e.readBits(4),e.readBits(4),n&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5));for(let o=0;o<=i;o++){let t=!0;1===e.readBits(1)||(t=1===e.readBits(1));let i=!1;t?s(e):i=1===e.readBits(1);let o=1;if(!i){o=s(e)+1}r&&ft(e,o,n),a&&ft(e,o,n)}},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&o(t.description)[21];return Je(e,i+1)}return Ye(e)})(a,t)},kt=e=>{const t=new fe(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 s=8;if(r>=2){s=t.readBits(1)?12:10}const n=t.readBits(3);let o=0,c=0;if(7!==n){if(c=t.readBits(1),1===r||3===r){const e=t.readBits(1),i=t.readBits(1);o=e||i?e&&!i?2:1:3,t.skipBits(1)}else o=1}else o=3,c=1;const l=(t.readBits(16)+1)*(t.readBits(16)+1);let u=a(Te).level;for(const a of Te)if(l<=a.maxPictureSize){u=a.level;break}return{profile:r,level:u,bitDepth:s,chromaSubsampling:o,videoFullRangeFlag:c,colourPrimaries:2===n?1:1===n?6:2,transferCharacteristics:2===n?1:1===n?6:2,matrixCoefficients:7===n?0:2===n?1:1===n?6:2}},bt=function*(e){const t=new fe(e),r=()=>{let e=0;for(let i=0;i<8;i++){const r=t.readAlignedByte();if(e|=(127&r)<<7*i,!(128&r))break;if(7===i&&128&r)return null}return e>=2**32-1?null:e};for(;t.getBitsLeft()>=8;){t.skipBits(1);const a=t.readBits(4),s=t.readBits(1),n=t.readBits(1);let o;if(t.skipBits(1),s&&t.skipBits(8),n){const e=r();if(null===e)return;o=e}else o=Math.floor(t.getBitsLeft()/8);i(t.pos%8===0),yield{type:a,data:e.subarray(t.pos/8,t.pos/8+o)},t.skipBits(8*o)}},yt=e=>{for(const{type:t,data:i}of bt(e)){if(1!==t)continue;const e=new fe(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{if(e.readBits(1)){e.skipBits(32),e.skipBits(32);if(e.readBits(1))return null}const t=e.readBits(1);t&&(o=e.readBits(5),e.skipBits(32),e.skipBits(5),e.skipBits(5));const i=e.readBits(5);for(let r=0;r<=i;r++){e.skipBits(12);const i=e.readBits(5);if(0===r&&(s=i),i>7){const t=e.readBits(1);0===r&&(n=t)}if(t){if(e.readBits(1)){const t=o+1;e.skipBits(t),e.skipBits(t),e.skipBits(1)}}e.readBits(1)&&e.skipBits(4)}}const 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=1,k=1,b=0;return p||(0===r?(g=1,k=1):1===r?(g=0,k=0):12===m&&(g=e.readBits(1),g&&(k=e.readBits(1))),g&&k&&(b=e.readBits(2))),{profile:r,level:s,tier:n,bitDepth:m,monochrome:p,chromaSubsamplingX:g,chromaSubsamplingY:k,chromaSamplePosition:b}}return null},wt=[480,960,1920,2880,480,960,1920,2880,480,960,1920,2880,480,960,480,960,120,240,480,960,120,240,480,960,120,240,480,960,120,240,480,960],Tt=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}},St=(e,t,r)=>{switch(e){case"avc":for(const e of Xe(r,t)){const t=r[e.offset],i=$e(t);if(i>=qe.NON_IDR_SLICE&&i<=qe.SLICE_DPC)return"delta";if(i===qe.IDR)return"key";if(i===qe.SEI&&(!Q()||Y()>=144)){const t=r.subarray(e.offset,e.offset+e.length),i=Qe(t);let a=1;do{let e=0;for(;;){const t=i[a++];if(void 0===t)break;if(e+=t,t<255)break}let t=0;for(;;){const e=i[a++];if(void 0===e)break;if(t+=e,e<255)break}if(e===6){const e=new fe(i);e.pos=8*a;const t=s(e),r=e.readBits(1);if(0===t&&1===r)return"key"}a+=t}while(a{var i,r;const a=c(e);let s=0;const n=a.getUint32(s,!0);s+=4;const o=l.decode(e.subarray(s,s+n));s+=n,n>0&&(t.raw??(t.raw={}),(i=t.raw).vendor??(i.vendor=o));const u=a.getUint32(s,!0);s+=4;for(let d=0;d0&&(t.trackNumber??(t.trackNumber=i)),r&&Number.isInteger(r)&&r>0&&(t.tracksTotal??(t.tracksTotal=r))}break;case"TRACKTOTAL":{const e=Number.parseInt(d,10);Number.isInteger(e)&&e>0&&(t.tracksTotal??(t.tracksTotal=e))}break;case"DISCNUMBER":{const e=d.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(d,10);Number.isInteger(e)&&e>0&&(t.discsTotal??(t.discsTotal=e))}break;case"DATE":{const e=new Date(d);Number.isNaN(e.getTime())||(t.date??(t.date=e))}break;case"GENRE":t.genre??(t.genre=d);break;case"METADATA_BLOCK_PICTURE":{const e=ee(d),i=c(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=l.decode(e.subarray(12+a,12+a+n)),u=i.getUint32(a+n+28),h=e.subarray(a+n+32,a+n+32+u);t.images??(t.images=[]),t.images.push({data:h,mimeType:s,kind:3===r?"coverFront":4===r?"coverBack":"unknown",name:void 0,description:o||void 0})}}}},xt=[2,1,2,3,3,4,4,5],Ct=e=>{if(e.length<7)return null;if(11!==e[0]||119!==e[1])return null;const t=new fe(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)}},Bt=[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],Et=[1,2,3,6],_t=e=>{if(e.length<6)return null;if(11!==e[0]||119!==e[1])return null;const t=new fe(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=Et[s];let d;d=a<3?ze[a]/1e3:Ue[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 i(t),t.fscod<3?ze[t.fscod]:null!==t.fscod2&&t.fscod2<3?Ue[t.fscod2]:null},Ft=e=>{const t=e.substreams[0];i(t);let r=xt[t.acmod]+t.lfeon;if(t.numDepSub>0){const e=[2,2,1,1,2,2,2,1,1];for(let i=0;i<9;i++)t.chanLoc&1<<8-i&&(r+=e[i])}return r};class Rt{constructor(e){this.input=e}dispose(){}}const Dt=new Uint8Array(0);class Mt{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===Dt&&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===Dt}get microsecondTimestamp(){return Math.trunc(z*this.timestamp)}get microsecondDuration(){return Math.trunc(z*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if("undefined"===typeof EncodedVideoChunk)throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw new TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if("undefined"===typeof EncodedVideoChunk)throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to an audio chunk.");if("undefined"===typeof EncodedAudioChunk)throw new Error("Your browser does not support EncodedAudioChunk.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(e,t){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 Mt(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 Mt(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 Nt=e=>{const t=c(e);let i=0;const r=t.getUint8(i);i+=1,i+=3;const a=w(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=gn(e);const i=In(e,4);let r=8;1===t&&(t=wn(e),r=16);const a=t-r;return a<0?null:{name:i,totalSize:t,headerSize:r,contentSize:a}},zt=e=>bn(e)/65536,Ut=e=>bn(e)/1073741824,qt=e=>{let t=0;for(let i=0;i<4;i++){t<<=7;const i=un(e);if(t|=127&i,0===(128&i))break}return t},Wt=e=>{let t=hn(e);return e.skip(2),t=Math.min(t,e.remainingLength),l.decode(ln(e,t))},Vt=e=>{const t=Lt(e);if(!t||"data"!==t.name)return null;if(e.remainingLength<8)return null;const i=gn(e);e.skip(4);const r=ln(e,t.contentSize-8);switch(i){case 1:return l.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}},Ht=16,Kt=new Uint32Array(256),jt=new Uint32Array(256),Xt=new Uint32Array(256),$t=new Uint32Array(256),Qt=new Uint32Array(256),Gt=new Uint32Array(256),Yt=new Uint32Array(10);let Jt=!1;class Zt{constructor(){this.roundkey=new Uint32Array(44),this.iv=new Uint32Array(Ht/Uint32Array.BYTES_PER_ELEMENT),this.in=new Uint8Array(Ht),this.out=new Uint8Array(Ht),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),Jt||(()=>{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);Kt[s]=t<<24|t<<16|t<<8|t,Gt[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);jt[s]=a,Xt[s]=a>>>8|a<<24,$t[s]=a>>>16|a<<16,Qt[s]=a>>>24|a<<8}let a=1;for(let s=0;s<10;s++)Yt[s]=a<<24,a=a<<1^(128&a?283:0);Jt=!0})();const r=new DataView(e.buffer,e.byteOffset,e.byteLength),a=new DataView(t.buffer,t.byteOffset,t.byteLength);this.roundkey[0]=r.getUint32(0,!1),this.roundkey[1]=r.getUint32(4,!1),this.roundkey[2]=r.getUint32(8,!1),this.roundkey[3]=r.getUint32(12,!1),this.iv[0]=a.getUint32(0,!1),this.iv[1]=a.getUint32(4,!1),this.iv[2]=a.getUint32(8,!1),this.iv[3]=a.getUint32(12,!1);for(let i=4;i<44;i+=4){const e=this.roundkey[i-1];this.roundkey[i]=this.roundkey[i-4]^4278190080&Kt[e>>>16&255]^16711680&Kt[e>>>8&255]^65280&Kt[e>>>0&255]^255&Kt[e>>>24&255]^Yt[i/4-1],this.roundkey[i+1]=this.roundkey[i-3]^this.roundkey[i],this.roundkey[i+2]=this.roundkey[i-2]^this.roundkey[i+1],this.roundkey[i+3]=this.roundkey[i-1]^this.roundkey[i+2]}for(let i=0,s=40;i>>24&255]]^Xt[255&Kt[t>>>16&255]]^$t[255&Kt[t>>>8&255]]^Qt[255&Kt[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=jt[e>>>24]^Xt[r>>>16&255]^$t[i>>>8&255]^Qt[255&t]^this.roundkey[a],l=jt[t>>>24]^Xt[e>>>16&255]^$t[r>>>8&255]^Qt[255&i]^this.roundkey[a+1],u=jt[i>>>24]^Xt[t>>>16&255]^$t[e>>>8&255]^Qt[255&r]^this.roundkey[a+2],d=jt[r>>>24]^Xt[i>>>16&255]^$t[t>>>8&255]^Qt[255&e]^this.roundkey[a+3],e=c,t=l,i=u,r=d}const h=4278190080&Gt[e>>>24&255]^16711680&Gt[r>>>16&255]^65280&Gt[i>>>8&255]^255&Gt[t>>>0&255]^this.roundkey[40],f=4278190080&Gt[t>>>24&255]^16711680&Gt[e>>>16&255]^65280&Gt[r>>>8&255]^255&Gt[i>>>0&255]^this.roundkey[41],m=4278190080&Gt[i>>>24&255]^16711680&Gt[t>>>16&255]^65280&Gt[e>>>8&255]^255&Gt[r>>>0&255]^this.roundkey[42],p=4278190080&Gt[r>>>24&255]^16711680&Gt[i>>>16&255]^65280&Gt[t>>>8&255]^255&Gt[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 ei extends Rt{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;for(;;){let r=this.reader.requestSliceRange(e,8,16);if(r instanceof Promise&&(r=await r),!r)break;const a=e,s=Lt(r);if(!s)break;if("ftyp"===s.name||"styp"===s.name){const e=In(r,4);this.isQuickTime="qt "===e}else{if("moov"===s.name){let e=this.reader.requestSlice(r.filePos,s.contentSize);if(e instanceof Promise&&(e=await e),!e)break;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;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.');const e=await this.input._initInput._getDemuxer();if(e.constructor!==ei)throw new Error("Init input must match the input's format.");await e.readMetadata(),this.movieTimescale=e.movieTimescale,this.movieDurationInTimescale=e.movieDurationInTimescale,this.metadataTags=e.metadataTags,this.isFragmented=!0,this.fragmentTrackDefaults=e.fragmentTrackDefaults,this.psshBoxes=e.psshBoxes;for(const t of e.tracks){const e={id:t.id,demuxer:this,trackBacking:null,disposition:t.disposition,timescale:t.timescale,durationInMediaTimescale:t.durationInMediaTimescale,durationInMovieTimescale:t.durationInMovieTimescale,rotation:t.rotation,internalCodecId:t.internalCodecId,name:t.name,languageCode:t.languageCode,sampleTableByteOffset:null,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:t.editListPreviousSegmentDurations,editListOffset:t.editListOffset,encryptionInfo:t.encryptionInfo,encryptionAuxInfo:null,frmaCodecString:null,info:t.info};if(t.trackBacking)if(i(e.info),"video"===e.info.type&&-1!==e.info.width){const t=e;e.trackBacking=new ii(t),this.tracks.push(e)}else if("audio"===e.info.type&&-1!==e.info.numberOfChannels){const t=e;e.trackBacking=new ri(t),this.tracks.push(e)}}t=!1;break}}e=a+s.totalSize}if(t){i(null!==this.reader.fileSize);let e=this.reader.requestSlice(this.reader.fileSize-4,4);e instanceof Promise&&(e=await e),i(e);const t=gn(e),r=this.reader.fileSize-t;if(r>=0&&r<=this.reader.fileSize-16){let e=this.reader.requestSliceRange(r,8,16);if(e instanceof Promise&&(e=await e),e){const t=Lt(e);if(t&&"mfra"===t.name){let i=this.reader.requestSlice(e.filePos,t.contentSize);i instanceof Promise&&(i=await i),i&&this.readContiguousBoxes(i)}}}}})())}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;i(this.moovSlice);const r=this.moovSlice.slice(e.sampleTableByteOffset);this.currentTrack=e,this.traverseBox(r),this.currentTrack=null;if("audio"===e.info?.type&&e.info.codec&&be.includes(e.info.codec)&&0===t.sampleCompositionTimeOffsets.length){i("audio"===e.info?.type);const r=Be(e.info.codec),s=[],n=[];for(let i=0;ie.startIndex),d=t.sampleTimingEntries[u],h=P(t.sampleTimingEntries,l,e=>e.startIndex),f=t.sampleTimingEntries[h],m=d.startDecodeTimestamp+(c-d.startIndex)*d.delta,p=f.startDecodeTimestamp+(l-f.startIndex)*f.delta-m,g=a(s);g&&g.delta===p?g.count++:s.push({startIndex:o.startChunkIndex+i,startDecodeTimestamp:m,count:1,delta:p});const k=o.samplesPerChunk*r.sampleSize*e.info.numberOfChannels;n.push(k)}o.startSampleIndex=o.startChunkIndex,o.samplesPerChunk=1}t.sampleTimingEntries=s,t.sampleSizes=n}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===s.moofOffset);if(r)ci(i,r.timestamp);else{const e=P(t,s.moofOffset-1,e=>e.moofOffset);if(-1!==e){const r=t[e];ci(i,r.endTimestamp)}}i.startTimestampIsFinal=!0}const r=P(t,i.startTimestamp,e=>e.startTimestamp);if(-1!==r&&t[r].moofOffset===s.moofOffset||t.splice(r+1,0,{moofOffset:s.moofOffset,startTimestamp:i.startTimestamp,endTimestamp:i.endTimestamp}),i.encryptionAuxInfo&&e.encryptionInfo){const t=await hi(this.reader,e.encryptionInfo,i.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;L(t.languageCode)||(t.languageCode=R)}}break;case"hdlr":{const t=this.currentTrack;if(!t)break;e.skip(8);const i=In(e,4);"vide"===i?t.info={type:"video",width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:null,avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null}:"soun"===i&&(t.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null,pcmLittleEndian:!1,pcmSampleSize:null})}break;case"stbl":{const t=this.currentTrack;if(!t)break;t.sampleTableByteOffset=K,this.readContiguousBoxes(e.slice(X,j.contentSize))}break;case"stsd":{const t=this.currentTrack;if(!t)break;if(null===t.info||t.sampleTable)break;const i=un(e);e.skip(3);const r=gn(e);for(let a=0;a0&&(1===n?(e.skip(4),c=8*gn(e),e.skip(8)):2===n&&(e.skip(4),l=vn(e),o=gn(e),e.skip(4),c=gn(e),u=gn(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=xe;else if("flac"===d)t.info.codec="flac";else if("ulaw"===d)t.info.codec="ulaw";else if("alaw"===d)t.info.codec="alaw";else if("ac-3"===d)t.info.codec="ac3";else if("ec-3"===d)t.info.codec="eac3";else if("twos"===d)8===c?t.info.codec="pcm-s8":16===c?t.info.codec=t.info.pcmLittleEndian?"pcm-s16":"pcm-s16be":(console.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":(console.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":(console.warn(`Invalid ipcm sample size ${e}.`),t.info.codec=null):16===e?t.info.codec="pcm-s16be":24===e?t.info.codec="pcm-s24be":32===e?t.info.codec="pcm-s32be":(console.warn(`Invalid ipcm sample size ${e}.`),t.info.codec=null)}else if("fpcm"===d){const e=t.info.pcmSampleSize;t.info.pcmLittleEndian?32===e?t.info.codec="pcm-f32":64===e?t.info.codec="pcm-f64":(console.warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null):32===e?t.info.codec="pcm-f32be":64===e?t.info.codec="pcm-f64be":(console.warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null)}else if("lpcm"===d&&null!==u){const e=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!==un(e),t.encryptionInfo.defaultPerSampleIvSize=un(e),t.encryptionInfo.defaultKid=w(ln(e,16)),t.encryptionInfo.defaultIsProtected&&0===t.encryptionInfo.defaultPerSampleIvSize){const i=un(e),r=new Uint8Array(16);r.set(ln(e,i),0),t.encryptionInfo.defaultConstantIv=r}}break;case"avcC":{const t=this.currentTrack;if(!t)break;i(t.info),t.info.codecDescription=ln(e,j.contentSize)}break;case"hvcC":{const t=this.currentTrack;if(!t)break;i(t.info),t.info.codecDescription=ln(e,j.contentSize)}break;case"vpcC":{const t=this.currentTrack;if(!t)break;i("video"===t.info?.type),e.skip(4);const r=un(e),a=un(e),s=un(e),n=s>>4,o=s>>1&7,c=1&s,l=un(e),u=un(e),d=un(e);t.info.vp9CodecInfo={profile:r,level:a,bitDepth:n,chromaSubsampling:o,videoFullRangeFlag:c,colourPrimaries:l,transferCharacteristics:u,matrixCoefficients:d}}break;case"av1C":{const t=this.currentTrack;if(!t)break;i("video"===t.info?.type),e.skip(1);const r=un(e),a=r>>5,s=31&r,n=un(e),o=n>>7,c=n>>6&1,l=n>>4&1,u=n>>3&1,d=n>>2&1,h=3&n,f=2===a&&c?n>>5&1?12:10:c?10:8;t.info.av1CodecInfo={profile:a,level:s,tier:o,bitDepth:f,monochrome:l,chromaSubsamplingX:u,chromaSubsamplingY:d,chromaSamplePosition:h}}break;case"colr":{const t=this.currentTrack;if(!t)break;i("video"===t.info?.type);if("nclx"!==In(e,4))break;const r=hn(e),a=hn(e),s=hn(e),n=Boolean(128&un(e));t.info.colorSpace={primaries:h[r],transfer:m[a],matrix:g[s],fullRange:n}}break;case"pasp":{const t=this.currentTrack;if(!t)break;i("video"===t.info?.type);const r=gn(e),a=gn(e);r>0&&a>0&&(r>a?t.info.squarePixelWidth=Math.round(t.info.width*r/a):t.info.squarePixelHeight=Math.round(t.info.height*a/r))}break;case"esds":{const t=this.currentTrack;if(!t)break;i("audio"===t.info?.type),e.skip(4);i(3===un(e)),qt(e),e.skip(2);const r=un(e),a=0!==(64&r),s=0!==(32&r);if(0!==(128&r)&&e.skip(2),a){const t=un(e);e.skip(t)}s&&e.skip(2);i(4===un(e));const n=qt(e),o=e.filePos,c=un(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":console.warn(`Unsupported audio codec (objectTypeIndication ${c}) - discarding track.`),e.skip(12),n>e.filePos-o){i(5===un(e));const r=qt(e);if(t.info.codecDescription=ln(e,r),"aac"===t.info.codec){const e=ge(t.info.codecDescription);null!==e.numberOfChannels&&(t.info.numberOfChannels=e.numberOfChannels),null!==e.sampleRate&&(t.info.sampleRate=e.sampleRate)}}}break;case"enda":{const t=this.currentTrack;if(!t)break;i("audio"===t.info?.type),t.info.pcmLittleEndian=!!(255&hn(e))}break;case"pcmC":{const t=this.currentTrack;if(!t)break;i("audio"===t.info?.type),e.skip(4);const r=un(e);t.info.pcmLittleEndian=Boolean(1&r),t.info.pcmSampleSize=un(e)}break;case"dOps":{const t=this.currentTrack;if(!t)break;i("audio"===t.info?.type),e.skip(1);const r=un(e),a=hn(e),s=gn(e),n=mn(e),o=un(e);let c;c=0!==o?ln(e,2+r):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,r),u.setUint16(10,a,!0),u.setUint32(12,s,!0),u.setInt16(16,n,!0),u.setUint8(18,o),l.set(c,19),t.info.codecDescription=l,t.info.numberOfChannels=r}break;case"dfLa":{const t=this.currentTrack;if(!t)break;i("audio"===t.info?.type),e.skip(4);const r=127,a=128,s=e.filePos;for(;e.filePos<$;){const i=un(e),s=fn(e);if((i&r)===Pt.STREAMINFO){e.skip(10);const i=gn(e),r=i>>>12,a=1+(i>>9&7);t.info.sampleRate=r,t.info.numberOfChannels=a,e.skip(20)}else e.skip(s);if(i&a)break}const n=e.filePos;e.filePos=s;const o=ln(e,n-s),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;i("audio"===t.info?.type);const r=ln(e,3),a=new fe(r),s=a.readBits(2);a.skipBits(8);const n=a.readBits(3),o=a.readBits(1);s<3&&(t.info.sampleRate=ze[s]),t.info.numberOfChannels=xt[n]+o}break;case"dec3":{const t=this.currentTrack;if(!t)break;i("audio"===t.info?.type);const r=(e=>{if(e.length<2)return null;const t=new fe(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}})(ln(e,j.contentSize));if(!r){console.warn("Invalid dec3 box contents, ignoring.");break}const a=At(r);null!==a&&(t.info.sampleRate=a),t.info.numberOfChannels=Ft(r)}break;case"stts":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4);const i=gn(e);let r=0,a=0;for(let s=0;se.id===i);if(!r)break;const a=gn(e),s=(12&a)>>2,n=3&a,o=[un,hn,fn,gn],c=o[(48&a)>>4],l=o[s],u=o[n],d=gn(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 i=0;ie.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},r?d.currentFragmentState.baseDataOffset=wn(e):l&&(d.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),a&&(d.currentFragmentState.sampleDescriptionIndex=gn(e)),s&&(d.currentFragmentState.defaultSampleDuration=gn(e)),n&&(d.currentFragmentState.defaultSampleSize=gn(e)),o&&(d.currentFragmentState.defaultSampleFlags=gn(e)),c&&(d.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{const t=this.currentTrack;if(!t)break;i(t.currentFragmentState);const r=un(e);e.skip(3);const a=0===r?gn(e):wn(e);t.currentFragmentState.startTimestamp=a}break;case"trun":{const t=this.currentTrack;if(!t)break;i(this.currentFragment),i(t.currentFragmentState);const r=un(e),a=fn(e),s=Boolean(1&a),n=Boolean(4&a),o=Boolean(256&a),c=Boolean(512&a),l=Boolean(1024&a),u=Boolean(2048&a),d=gn(e);let h=null;s&&(h=bn(e));let f,m=null;if(n&&(m=gn(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)),0===d){this.currentFragment.implicitBaseDataOffset=f.currentOffset;break}for(let p=0;p0&&(a=ln(e,r));const s=di(t);s.defaultSampleInfoSize=i,s.sampleSizes=a,s.sampleCount=r}break;case"saio":{const t=this.currentTrack;if(!t||!t.encryptionInfo)break;const i=un(e);if(1&fn(e)){const i=In(e,4),r=gn(e);if(i!==t.encryptionInfo.scheme||0!==r)break}const r=gn(e);if(0===r)break;r>1&&console.warn("Multiple saio entries are not supported; using the first offset only.");let a=0===i?gn(e):Number(wn(e));this.currentFragment&&(a+=this.currentFragment.moofOffset);di(t).offset=a}break;case"senc":{const t=this.currentTrack;if(!t||!t.encryptionInfo)break;i(this.currentFragment);const r=this.currentFragment.trackData.get(t.id);if(!r)break;e.skip(1);const a=fn(e),s=Boolean(2&a),n=gn(e),o=t.encryptionInfo.defaultPerSampleIvSize;i(null!==o);for(let i=0;i0?a.set(ln(e,o),0):a.set(t.encryptionInfo.defaultConstantIv,0);let n=null;if(s){const t=hn(e);n=[];for(let i=0;i0&&((z=this.metadataTags).trackNumber??(z.trackNumber=t)),i&&Number.isInteger(i)&&i>0&&((U=this.metadataTags).tracksTotal??(U.tracksTotal=i))}break;case"trkn":if(a instanceof Uint8Array&&a.length>=6){const e=c(a),t=e.getUint16(2,!1),i=e.getUint16(4,!1);t>0&&((q=this.metadataTags).trackNumber??(q.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=c(a),t=e.getUint16(2,!1),i=e.getUint16(4,!1);t>0&&((V=this.metadataTags).discNumber??(V.discNumber=t)),i>0&&((H=this.metadataTags).discsTotal??(H.discsTotal=i))}}}}}var Q,G;return e.filePos=$,!0}}class ti{constructor(e){this.internalTrack=e,this.packetToSampleIndex=new WeakMap,this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){const e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType();let i=0;for(const r of e.tracks)if(r.trackBacking.getType()===t&&i++,r===this.internalTrack)break;return i}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.internalCodecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}isRelativeToUnixEpoch(){return!1}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){const e=this.internalTrack;if(e.durationInMediaTimescale<=0)return null;i(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 D(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,t){const i=this.mapTimestampIntoTimescale(e),r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=ai(r,i),s=await this.fetchPacketForSampleIndex(a,t);return ui(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=P(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=C(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===a.fragment){const t=e.trackData.get(this.internalTrack.id).samples.findIndex((e,t)=>e.isKeyFrame&&t>a.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)}async fetchPacketForSampleIndex(e,t){if(-1===e)return null;const r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=ni(r,e);if(!a)return null;let s;if(t.metadataOnly)s=Dt;else{let t=this.internalTrack.demuxer.reader.requestSlice(a.sampleOffset,a.sampleSize);if(t instanceof Promise&&(t=await t),!t)return null;if(s=ln(t,a.sampleSize),this.internalTrack.encryptionAuxInfo){i(this.internalTrack.encryptionInfo);const t=await hi(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);ee.timestamp),d=-1!==u?this.internalTrack.fragmentLookupTable[u]:null,h=P(this.internalTrack.fragmentPositionCache,r,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>a)break}let e=n.reader.requestSliceRange(p,8,16);if(e instanceof Promise&&(e=await e),!e)break;const i=p,r=Lt(e);if(!r)break;if("moof"===r.name){o=await n.readFragment(i);const{sampleIndex:e,correctSampleFound:r}=t(o);if(r)return this.fetchPacketInFragment(o,e,s);-1!==e&&(c=o,l=e)}p=i+r.totalSize}if(d&&(!c||c.moofOffset{if("vp9"!==this.internalTrack.info.codec||this.internalTrack.info.vp9CodecInfo){if("av1"===this.internalTrack.info.codec&&!this.internalTrack.info.av1CodecInfo){const e=await this.getFirstPacket({});this.internalTrack.info.av1CodecInfo=e&&yt(e.data)}}else{const e=await this.getFirstPacket({});this.internalTrack.info.vp9CodecInfo=e&&kt(e.data)}const e={codec:ve(this.internalTrack.info),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0};return this.internalTrack.info.width===this.internalTrack.info.squarePixelWidth&&this.internalTrack.info.height===this.internalTrack.info.squarePixelHeight||(e.displayAspectWidth=this.internalTrack.info.squarePixelWidth,e.displayAspectHeight=this.internalTrack.info.squarePixelHeight),e})()):null}}class ri extends ti{constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getType(){return"audio"}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfig??(this.decoderConfig={codec:Ie(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}):null}}const ai=(e,t)=>{if(e.presentationTimestamps){const i=P(e.presentationTimestamps,t,e=>e.presentationTimestamp);return-1===i?-1:e.presentationTimestamps[i].sampleIndex}{const i=P(e.sampleTimingEntries,t,e=>e.startDecodeTimestamp);if(-1===i)return-1;const r=e.sampleTimingEntries[i];return r.startIndex+Math.min(Math.floor((t-r.startDecodeTimestamp)/r.delta),r.count-1)}},si=(e,t)=>{if(!e.keySampleIndices)return ai(e,t);if(e.presentationTimestamps){const i=P(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!==S(e.keySampleIndices,i,e=>e))return i}return-1}{const i=ai(e,t),r=P(e.keySampleIndices,i,e=>e);return e.keySampleIndices[r]??-1}},ni=(e,t)=>{const r=P(e.sampleTimingEntries,t,e=>e.startIndex),a=e.sampleTimingEntries[r];if(!a||a.startIndex+a.count<=t)return null;let s=a.startDecodeTimestamp+(t-a.startIndex)*a.delta;const n=P(e.sampleCompositionTimeOffsets,t,e=>e.startIndex),o=e.sampleCompositionTimeOffsets[n];o&&t-o.startIndexe.startSampleIndex),u=e.sampleToChunk[l];i(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 i=f;ie)}},oi=(e,t)=>{if(!e.keySampleIndices)return t+1;const i=P(e.keySampleIndices,t,e=>e);return e.keySampleIndices[i+1]??-1},ci=(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},li=e=>{const[t,i]=e,r=Math.atan2(i,t);return Number.isFinite(r)?r*(180/Math.PI):0},ui=e=>0===e.sampleSizes.length,di=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})},hi=async(e,t,r)=>{if(r.resolved)return r.resolved;if(null===r.offset||0===r.sampleCount)throw new Error("Incomplete saiz/saio info; cannot resolve encryption data.");let a=0;if(r.defaultSampleInfoSize>0)a=r.defaultSampleInfoSize*r.sampleCount;else{i(r.sampleSizes);for(let e=0;e0?r.defaultSampleInfoSize:r.sampleSizes[i],a=new Uint8Array(16);n>0?a.set(ln(s,n),0):a.set(t.defaultConstantIv,0);let c=null;if(e>n){const e=hn(s);c=[];for(let t=0;t{i(e.encryptionInfo);const s=e.encryptionInfo;i(null!==s.defaultKid);const n=s.defaultKid;let o;const c=e.demuxer.decryptionKeyCache.get(n);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(a){t=[...t,...a.psshBoxes].filter(e=>null===e.keyIds||e.keyIds.includes(n));for(let e=0;e{i(e.length%2===0);const t=new Uint8Array(e.length/2);for(let i=0;i{const s=new Uint8Array(16);s.set(r.iv,0);const n=await crypto.subtle.importKey("raw",e,{name:"AES-CTR"},!1,["decrypt"]),o=async e=>{const t=await crypto.subtle.decrypt({name:"AES-CTR",counter:s,length:64},n,e);return new Uint8Array(t)};if(!r.subsamples)return o(a);i(null!==t.defaultCryptByteBlock&&null!==t.defaultSkipByteBlock);const c=gi(r.subsamples,t.defaultCryptByteBlock,t.defaultSkipByteBlock);let l=0;for(const i of c)for(const e of i.perSubsample)l+=e.length;const u=new Uint8Array(l);let d=0;for(const i of c)for(const e of i.perSubsample)u.set(a.subarray(e.offset,e.offset+e.length),d),d+=e.length;const h=await o(u),f=new Uint8Array(a);let m=0;for(const i of c)for(const e of i.perSubsample)f.set(h.subarray(m,m+e.length),e.offset),m+=e.length;return f},pi=(e,t,r,a)=>{const s=new Zt;s.init({key:e,iv:r.iv});const n=t.defaultCryptByteBlock,o=t.defaultSkipByteBlock;if(i(null!==n&&null!==o),!r.subsamples){const e=new Uint8Array(a),t=Math.floor(a.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 ki,bi;(bi=ki||(ki={}))[bi.EBML=440786851]="EBML",bi[bi.EBMLVersion=17030]="EBMLVersion",bi[bi.EBMLReadVersion=17143]="EBMLReadVersion",bi[bi.EBMLMaxIDLength=17138]="EBMLMaxIDLength",bi[bi.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",bi[bi.DocType=17026]="DocType",bi[bi.DocTypeVersion=17031]="DocTypeVersion",bi[bi.DocTypeReadVersion=17029]="DocTypeReadVersion",bi[bi.Void=236]="Void",bi[bi.Segment=408125543]="Segment",bi[bi.SeekHead=290298740]="SeekHead",bi[bi.Seek=19899]="Seek",bi[bi.SeekID=21419]="SeekID",bi[bi.SeekPosition=21420]="SeekPosition",bi[bi.Duration=17545]="Duration",bi[bi.Info=357149030]="Info",bi[bi.TimestampScale=2807729]="TimestampScale",bi[bi.MuxingApp=19840]="MuxingApp",bi[bi.WritingApp=22337]="WritingApp",bi[bi.Tracks=374648427]="Tracks",bi[bi.TrackEntry=174]="TrackEntry",bi[bi.TrackNumber=215]="TrackNumber",bi[bi.TrackUID=29637]="TrackUID",bi[bi.TrackType=131]="TrackType",bi[bi.FlagEnabled=185]="FlagEnabled",bi[bi.FlagDefault=136]="FlagDefault",bi[bi.FlagForced=21930]="FlagForced",bi[bi.FlagOriginal=21934]="FlagOriginal",bi[bi.FlagHearingImpaired=21931]="FlagHearingImpaired",bi[bi.FlagVisualImpaired=21932]="FlagVisualImpaired",bi[bi.FlagCommentary=21935]="FlagCommentary",bi[bi.FlagLacing=156]="FlagLacing",bi[bi.Name=21358]="Name",bi[bi.Language=2274716]="Language",bi[bi.LanguageBCP47=2274717]="LanguageBCP47",bi[bi.CodecID=134]="CodecID",bi[bi.CodecPrivate=25506]="CodecPrivate",bi[bi.CodecDelay=22186]="CodecDelay",bi[bi.SeekPreRoll=22203]="SeekPreRoll",bi[bi.DefaultDuration=2352003]="DefaultDuration",bi[bi.Video=224]="Video",bi[bi.PixelWidth=176]="PixelWidth",bi[bi.PixelHeight=186]="PixelHeight",bi[bi.DisplayWidth=21680]="DisplayWidth",bi[bi.DisplayHeight=21690]="DisplayHeight",bi[bi.DisplayUnit=21682]="DisplayUnit",bi[bi.AlphaMode=21440]="AlphaMode",bi[bi.Audio=225]="Audio",bi[bi.SamplingFrequency=181]="SamplingFrequency",bi[bi.Channels=159]="Channels",bi[bi.BitDepth=25188]="BitDepth",bi[bi.SimpleBlock=163]="SimpleBlock",bi[bi.BlockGroup=160]="BlockGroup",bi[bi.Block=161]="Block",bi[bi.BlockAdditions=30113]="BlockAdditions",bi[bi.BlockMore=166]="BlockMore",bi[bi.BlockAdditional=165]="BlockAdditional",bi[bi.BlockAddID=238]="BlockAddID",bi[bi.BlockDuration=155]="BlockDuration",bi[bi.ReferenceBlock=251]="ReferenceBlock",bi[bi.Cluster=524531317]="Cluster",bi[bi.Timestamp=231]="Timestamp",bi[bi.Cues=475249515]="Cues",bi[bi.CuePoint=187]="CuePoint",bi[bi.CueTime=179]="CueTime",bi[bi.CueTrackPositions=183]="CueTrackPositions",bi[bi.CueTrack=247]="CueTrack",bi[bi.CueClusterPosition=241]="CueClusterPosition",bi[bi.Colour=21936]="Colour",bi[bi.MatrixCoefficients=21937]="MatrixCoefficients",bi[bi.TransferCharacteristics=21946]="TransferCharacteristics",bi[bi.Primaries=21947]="Primaries",bi[bi.Range=21945]="Range",bi[bi.Projection=30320]="Projection",bi[bi.ProjectionType=30321]="ProjectionType",bi[bi.ProjectionPoseRoll=30325]="ProjectionPoseRoll",bi[bi.Attachments=423732329]="Attachments",bi[bi.AttachedFile=24999]="AttachedFile",bi[bi.FileDescription=18046]="FileDescription",bi[bi.FileName=18030]="FileName",bi[bi.FileMediaType=18016]="FileMediaType",bi[bi.FileData=18012]="FileData",bi[bi.FileUID=18094]="FileUID",bi[bi.Chapters=272869232]="Chapters",bi[bi.Tags=307544935]="Tags",bi[bi.Tag=29555]="Tag",bi[bi.Targets=25536]="Targets",bi[bi.TargetTypeValue=26826]="TargetTypeValue",bi[bi.TargetType=25546]="TargetType",bi[bi.TagTrackUID=25541]="TagTrackUID",bi[bi.TagEditionUID=25545]="TagEditionUID",bi[bi.TagChapterUID=25540]="TagChapterUID",bi[bi.TagAttachmentUID=25542]="TagAttachmentUID",bi[bi.SimpleTag=26568]="SimpleTag",bi[bi.TagName=17827]="TagName",bi[bi.TagLanguage=17530]="TagLanguage",bi[bi.TagString=17543]="TagString",bi[bi.TagBinary=17541]="TagBinary",bi[bi.ContentEncodings=28032]="ContentEncodings",bi[bi.ContentEncoding=25152]="ContentEncoding",bi[bi.ContentEncodingOrder=20529]="ContentEncodingOrder",bi[bi.ContentEncodingScope=20530]="ContentEncodingScope",bi[bi.ContentCompression=20532]="ContentCompression",bi[bi.ContentCompAlgo=16980]="ContentCompAlgo",bi[bi.ContentCompSettings=16981]="ContentCompSettings",bi[bi.ContentEncryption=20533]="ContentEncryption";const yi=[ki.EBML,ki.Segment],wi=[ki.SeekHead,ki.Info,ki.Cluster,ki.Tracks,ki.Cues,ki.Attachments,ki.Chapters,ki.Tags],Ti=[...yi,...wi],Si=16,Pi=e=>{if(e.remainingLength<1)return null;const t=un(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=un(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=Pi(e);if(null===t)return null;if(e.remainingLength{if(e.remainingLength<1)return null;if(255===un(e))return;e.skip(-1);const t=vi(e);return null===t?null:72057594037927940!==t?t:void 0},Bi=e=>{i(e.remainingLength>=2);const t=xi(e);if(null===t)return null;const r=Ci(e);return null===r?null:{id:t,size:r}},Ei=(e,t)=>{const i=ln(e,t);let r=0;for(;r{const i=ln(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?Pn(e):vn(e)},Fi=async(e,t,i,r)=>{const a=new Set(i);let s=t;for(;null===r||ss?r:s,found:!1}},Ri=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,Si);if(t instanceof Promise&&(t=await t),!t)break;const i=Bi(t);if(!i)break;const r=i.id;let s=i.size;const n=t.filePos;if(r===ki.EBML){ji(s);let e=this.reader.requestSlice(n,s);if(e instanceof Promise&&(e=await e),!e)break;this.readContiguousElements(e)}else if(r===ki.Segment){if(await this.readSegment(n,s),void 0===s)break;if(null===this.reader.fileSize)break}else if(r===ki.Cluster){if(null===this.reader.fileSize)break;if(void 0===s){s=(await Fi(this.reader,n,Ti,this.reader.fileSize)).pos-n}const e=a(this.segments);e&&(e.elementEndPos=n+s)}ji(s),e=n+s}})())}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=Zi[o].flag;this.currentSegment[e]=!0,ji(s);let t=this.reader.requestSlice(n,s);t instanceof Promise&&(t=await t),t&&this.readContiguousElements(t)}else if(a===ki.Tags||a===ki.Attachments){a===ki.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,ji(s);let e=this.reader.requestSlice(n,s);e instanceof Promise&&(e=await e),e&&this.readContiguousElements(e)}else if(a===ki.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=Zi.find(e=>e.id===n.id);if(!t)continue;if(this.currentSegment[t.flag])continue;let i=this.reader.requestSliceRange(e+n.segmentPosition,2,Si);if(i instanceof Promise&&(i=await i),!i)continue;const r=Bi(i);if(!r)continue;const{id:a,size:s}=r;if(a!==t.id)continue;ji(s),this.currentSegment[t.flag]=!0;let o=this.reader.requestSlice(i.filePos,s);o instanceof Promise&&(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 r=this.reader.requestSliceRange(e,2,Si);r instanceof Promise&&(r=await r),i(r);const s=e,n=Bi(r);i(n);i(n.id===ki.Cluster);let o=n.size;const c=r.filePos;if(void 0===o){o=(await Fi(this.reader,c,Ti,t.elementEndPos)).pos-c}let l=this.reader.requestSlice(c,o);l instanceof Promise&&(l=await l);const u={segment:t,elementStartPos:s,elementEndPos:c+o,dataStartPos:c,timestamp:-1,trackData:new Map};if(this.currentCluster=u,l){const e=this.readContiguousElements(l,Ti);u.elementEndPos=e}for(const[,d]of u.trackData){const e=d.track;i(d.blocks.length>0);let t=!1;for(let i=0;i({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp);for(let i=0;i({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp));const r=d.blocks[d.presentationTimestamps[0].blockIndex],n=d.blocks[a(d.presentationTimestamps).blockIndex];d.startTimestamp=r.timestamp,d.endTimestamp=n.timestamp+n.duration;const o=P(e.clusterPositionCache,d.startTimestamp,e=>e.startTimestamp);-1!==o&&e.clusterPositionCache[o].elementStartPos===s||e.clusterPositionCache.splice(o+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 r=0;r=2;){const i=e.filePos;if(!this.traverseElement(e,t))return i}return e.filePos}traverseElement(e,t){const a=Bi(e);if(!a)return!1;if(t&&t.includes(a.id))return!1;const{id:s,size:n}=a,o=e.filePos;switch(ji(n),s){case ki.DocType:this.isWebM="webm"===Ei(e,n);break;case ki.Seek:{if(!this.currentSegment)break;const t={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(t),this.readContiguousElements(e.slice(o,n)),-1!==t.id&&-1!==t.segmentPosition||this.currentSegment.seekEntries.pop()}break;case ki.SeekID:{const t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.id=Ii(e,n)}break;case ki.SeekPosition:{const t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.segmentPosition=Ii(e,n)}break;case ki.TimestampScale:if(!this.currentSegment)break;this.currentSegment.timestampScale=Ii(e,n),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale;break;case ki.Duration:if(!this.currentSegment)break;this.currentSegment.duration=Ai(e,n);break;case ki.TrackEntry:if(!this.currentSegment)break;if(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...he,primary:!1},trackBacking:null,codecId:null,codecPrivate:null,defaultDuration:null,defaultDurationNs:null,name:null,languageCode:"eng",hasLanguageBcp47:!1,decodingInstructions:[],info:null},this.readContiguousElements(e.slice(o,n)),!this.currentTrack)break;if(this.currentTrack.decodingInstructions.some(e=>"decompress"!==e.data?.type||e.scope!==Qi.Block||e.data.algorithm!==Yi.HeaderStripping)&&(console.warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`),this.currentTrack=null),this.currentTrack&&-1!==this.currentTrack.id&&this.currentTrack.codecId&&this.currentTrack.info){const e=this.currentTrack.codecId.indexOf("/"),t=-1===e?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,e);if("video"===this.currentTrack.info.type&&-1!==this.currentTrack.info.width&&-1!==this.currentTrack.info.height){if(this.currentTrack.info.squarePixelWidth=this.currentTrack.info.width,this.currentTrack.info.squarePixelHeight=this.currentTrack.info.height,null!==this.currentTrack.info.displayWidth&&null!==this.currentTrack.info.displayHeight){const e=this.currentTrack.info.displayWidth*this.currentTrack.info.height,t=this.currentTrack.info.displayHeight*this.currentTrack.info.width;e>0&&t>0&&(e>t?this.currentTrack.info.squarePixelWidth=Math.round(this.currentTrack.info.width*e/t):this.currentTrack.info.squarePixelHeight=Math.round(this.currentTrack.info.height*t/e))}this.currentTrack.codecId===Di?(this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===Mi?(this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Ni?this.currentTrack.info.codec="vp8":t===Oi?this.currentTrack.info.codec="vp9":t===Li&&(this.currentTrack.info.codec="av1");const e=this.currentTrack;this.currentTrack.trackBacking=new rr(e),this.currentSegment.tracks.push(this.currentTrack)}else if("audio"===this.currentTrack.info.type){t===zi?(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===Ui?this.currentTrack.info.codec="mp3":t===qi?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=xe):t===Wi?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Vi?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Hi?(this.currentTrack.info.codec="ac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Ki?(this.currentTrack.info.codec="eac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):"A_PCM/INT/LIT"===this.currentTrack.codecId?8===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-u8":16===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s16":24===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s24":32===this.currentTrack.info.bitDepth&&(this.currentTrack.info.codec="pcm-s32"):"A_PCM/INT/BIG"===this.currentTrack.codecId?8===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-u8":16===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s16be":24===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s24be":32===this.currentTrack.info.bitDepth&&(this.currentTrack.info.codec="pcm-s32be"):"A_PCM/FLOAT/IEEE"===this.currentTrack.codecId&&(32===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-f32":64===this.currentTrack.info.bitDepth&&(this.currentTrack.info.codec="pcm-f64"));const e=this.currentTrack;this.currentTrack.trackBacking=new ar(e),this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null;break;case ki.TrackNumber:if(!this.currentTrack)break;this.currentTrack.id=Ii(e,n);break;case ki.TrackType:{if(!this.currentTrack)break;const t=Ii(e,n);1===t?this.currentTrack.info={type:"video",width:-1,height:-1,displayWidth:null,displayHeight:null,displayUnit:null,squarePixelWidth:-1,squarePixelHeight:-1,rotation:0,codec:null,codecDescription:null,colorSpace:null,alphaMode:!1}:2===t&&(this.currentTrack.info={type:"audio",numberOfChannels:1,sampleRate:8e3,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case ki.FlagEnabled:if(!this.currentTrack)break;Ii(e,n)||(this.currentTrack=null);break;case ki.FlagDefault:if(!this.currentTrack)break;this.currentTrack.disposition.default=!!Ii(e,n);break;case ki.FlagForced:if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!Ii(e,n);break;case ki.FlagOriginal:if(!this.currentTrack)break;this.currentTrack.disposition.original=!!Ii(e,n);break;case ki.FlagHearingImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!Ii(e,n);break;case ki.FlagVisualImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!Ii(e,n);break;case ki.FlagCommentary:if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!Ii(e,n);break;case ki.CodecID:if(!this.currentTrack)break;this.currentTrack.codecId=Ei(e,n);break;case ki.CodecPrivate:if(!this.currentTrack)break;this.currentTrack.codecPrivate=ln(e,n);break;case ki.DefaultDuration:if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=Ii(e,n);break;case ki.Name:if(!this.currentTrack)break;this.currentTrack.name=_i(e,n);break;case ki.Language:if(!this.currentTrack)break;if(this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=Ei(e,n),L(this.currentTrack.languageCode)||(this.currentTrack.languageCode=R);break;case ki.LanguageBCP47:{if(!this.currentTrack)break;const t=Ei(e,n).split("-")[0];this.currentTrack.languageCode=t||R,this.currentTrack.hasLanguageBcp47=!0}break;case ki.Video:if("video"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(o,n));break;case ki.PixelWidth:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.width=Ii(e,n);break;case ki.PixelHeight:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.height=Ii(e,n);break;case ki.DisplayWidth:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.displayWidth=Ii(e,n);break;case ki.DisplayHeight:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.displayHeight=Ii(e,n);break;case ki.DisplayUnit:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.displayUnit=Ii(e,n);break;case ki.AlphaMode:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.alphaMode=1===Ii(e,n);break;case ki.Colour:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.colorSpace={},this.readContiguousElements(e.slice(o,n));break;case ki.MatrixCoefficients:{if("video"!==this.currentTrack?.info?.type||!this.currentTrack.info.colorSpace)break;const t=Ii(e,n),i=g[t]??null;this.currentTrack.info.colorSpace.matrix=i}break;case ki.Range:if("video"!==this.currentTrack?.info?.type||!this.currentTrack.info.colorSpace)break;this.currentTrack.info.colorSpace.fullRange=2===Ii(e,n);break;case ki.TransferCharacteristics:{if("video"!==this.currentTrack?.info?.type||!this.currentTrack.info.colorSpace)break;const t=Ii(e,n),i=m[t]??null;this.currentTrack.info.colorSpace.transfer=i}break;case ki.Primaries:{if("video"!==this.currentTrack?.info?.type||!this.currentTrack.info.colorSpace)break;const t=Ii(e,n),i=h[t]??null;this.currentTrack.info.colorSpace.primaries=i}break;case ki.Projection:if("video"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(o,n));break;case ki.ProjectionPoseRoll:{if("video"!==this.currentTrack?.info?.type)break;const t=-Ai(e,n);try{this.currentTrack.info.rotation=r(t)}catch{}}break;case ki.Audio:if("audio"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(o,n));break;case ki.SamplingFrequency:if("audio"!==this.currentTrack?.info?.type)break;this.currentTrack.info.sampleRate=Ai(e,n);break;case ki.Channels:if("audio"!==this.currentTrack?.info?.type)break;this.currentTrack.info.numberOfChannels=Ii(e,n);break;case ki.BitDepth:if("audio"!==this.currentTrack?.info?.type)break;this.currentTrack.info.bitDepth=Ii(e,n);break;case ki.CuePoint:if(!this.currentSegment)break;this.readContiguousElements(e.slice(o,n)),this.currentCueTime=null;break;case ki.CueTime:this.currentCueTime=Ii(e,n);break;case ki.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(o,n)),-1!==t.trackId&&-1!==t.clusterPosition||this.currentSegment.cuePoints.pop()}break;case ki.CueTrack:{const t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;t.trackId=Ii(e,n)}break;case ki.CueClusterPosition:{const t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;i(this.currentSegment),t.clusterPosition=this.currentSegment.dataStartPos+Ii(e,n)}break;case ki.Timestamp:if(!this.currentCluster)break;this.currentCluster.timestamp=Ii(e,n);break;case ki.SimpleBlock:{if(!this.currentCluster)break;const t=vi(e);if(null===t)break;const i=this.getTrackDataInCluster(this.currentCluster,t);if(!i)break;const r=mn(e),a=un(e),s=a>>1&3;let c=!!(128&a);"audio"===i.track.info?.type&&i.track.info.codec&&(c=!0);const l=ln(e,n-(e.filePos-o)),u=i.track.decodingInstructions.length>0;i.blocks.push({timestamp:r,duration:0,isKeyFrame:c,data:l,lacing:s,decoded:!u,mainAdditional:null})}break;case ki.BlockGroup:if(!this.currentCluster)break;this.readContiguousElements(e.slice(o,n)),this.currentBlock=null;break;case ki.Block:{if(!this.currentCluster)break;const t=vi(e);if(null===t)break;const i=this.getTrackDataInCluster(this.currentCluster,t);if(!i)break;const r=mn(e),a=un(e)>>1&3,s=ln(e,n-(e.filePos-o)),c=i.track.decodingInstructions.length>0;this.currentBlock={timestamp:r,duration:0,isKeyFrame:!0,data:s,lacing:a,decoded:!c,mainAdditional:null},i.blocks.push(this.currentBlock)}break;case ki.BlockAdditions:this.readContiguousElements(e.slice(o,n));break;case ki.BlockMore:if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(o,n)),this.currentBlockAdditional.data&&1===this.currentBlockAdditional.addId&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null;break;case ki.BlockAdditional:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=ln(e,n);break;case ki.BlockAddID:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=Ii(e,n);break;case ki.BlockDuration:if(!this.currentBlock)break;this.currentBlock.duration=Ii(e,n);break;case ki.ReferenceBlock:if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1;break;case ki.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(o,n));break;case ki.Targets:this.readContiguousElements(e.slice(o,n));break;case ki.TargetTypeValue:50!==Ii(e,n)&&(this.currentTagTargetIsMovie=!1);break;case ki.TagTrackUID:case ki.TagEditionUID:case ki.TagChapterUID:case ki.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case ki.SimpleTag:if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(o,n));break;case ki.TagName:this.currentSimpleTagName=_i(e,n);break;case ki.TagString:{if(!this.currentSimpleTagName)break;const t=_i(e,n);this.processTagValue(this.currentSimpleTagName,t)}break;case ki.TagBinary:{if(!this.currentSimpleTagName)break;const t=ln(e,n);this.processTagValue(this.currentSimpleTagName,t)}break;case ki.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(o,n));const t=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(t.raw??(t.raw={}),t.raw[this.currentAttachedFile.fileUid.toString()]=new de(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 ki.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 ki.ContentEncoding:this.currentDecodingInstruction={order:0,scope:Qi.Block,data:null},this.readContiguousElements(e.slice(o,n)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case ki.ContentEncodingOrder:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=Ii(e,n);break;case ki.ContentEncodingScope:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=Ii(e,n);break;case ki.ContentCompression:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:Yi.Zlib,settings:null},this.readContiguousElements(e.slice(o,n));break;case ki.ContentCompAlgo:if("decompress"!==this.currentDecodingInstruction?.data?.type)break;this.currentDecodingInstruction.data.algorithm=Ii(e,n);break;case ki.ContentCompSettings:if("decompress"!==this.currentDecodingInstruction?.data?.type)break;this.currentDecodingInstruction.data.settings=ln(e,n);break;case ki.ContentEncryption:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}return e.filePos=o+n,!0}decodeBlockData(e,t){i(e.decodingInstructions.length>0);let r=t;for(const a of e.decodingInstructions)if(i(a.data),"decompress"===a.data.type)if(a.data.algorithm===Yi.HeaderStripping)if(a.data.settings&&a.data.settings.length>0){const e=a.data.settings,t=new Uint8Array(e.length+r.length);t.set(e,0),t.set(r,e.length),r=t}return r}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))}}}}class ir{constructor(e){this.internalTrack=e,this.packetToClusterLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){const e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType();let i=0;for(const r of e.segments)for(const e of r.tracks)if(e.trackBacking.getType()===t&&i++,e===this.internalTrack)break;return i}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.codecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.segment.timestampFactor}isRelativeToUnixEpoch(){return!1}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){const e=this.internalTrack.segment;if(e.duration<=0)return null;let t=e.duration/e.timestampFactor;const i=await this.getFirstPacket({metadataOnly:!0});return t+=i?.timestamp??0,t}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 D(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=P(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=C(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===r.cluster){const t=e.trackData.get(this.internalTrack.id).blocks.findIndex((e,t)=>e.isKeyFrame&&t>r.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)}async fetchPacketInCluster(e,t,r){if(-1===t)return null;const a=e.trackData.get(this.internalTrack.id).blocks[t];i(a),a.decoded||(a.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,a.data),a.decoded=!0);const s=r.metadataOnly?Dt:a.data,n=a.timestamp/this.internalTrack.segment.timestampFactor,o=a.duration/this.internalTrack.segment.timestampFactor,c={};a.mainAdditional&&"video"===this.internalTrack.info?.type&&this.internalTrack.info.alphaMode&&(c.alpha=r.metadataOnly?Dt:a.mainAdditional,c.alphaByteLength=a.mainAdditional.byteLength);const l=new Mt(s,a.isKeyFrame?"key":"delta",n,o,e.dataStartPos+t,a.data.byteLength,c);return this.packetToClusterLocation.set(l,{cluster:e,blockIndex:t}),l}async performClusterLookup(e,t,r,a,s){const{demuxer:n,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,s);-1!==i&&(l=e,u=i)}const d=P(this.internalTrack.cuePoints,r,e=>e.time),h=-1!==d?this.internalTrack.cuePoints[d]:null,f=P(this.internalTrack.clusterPositionCache,r,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>a)break}let e=n.reader.requestSliceRange(g,2,Si);if(e instanceof Promise&&(e=await e),!e)break;const r=g,d=Bi(e);if(!d||!wi.includes(d.id)&&d.id!==ki.Void){const e=await Ri(n.reader,r,wi,Math.min(o.elementEndPos??1/0,r+er));if(e){g=e;continue}break}const h=d.id;let f=d.size;const m=e.filePos;if(h===ki.Cluster){c=await n.readCluster(r,o),f=c.elementEndPos-m;const{blockIndex:e,correctBlockFound:i}=t(c);if(i)return this.fetchPacketInCluster(c,e,s);-1!==e&&(l=c,u=e)}if(void 0===f){i(h!==ki.Cluster);f=(await Fi(n.reader,m,Ti,o.elementEndPos)).pos-m}const p=m+f;if(null===o.elementEndPos){let e=n.reader.requestSliceRange(p,2,Si);if(e instanceof Promise&&(e=await e),!e)break;if(xi(e)===ki.Segment){o.elementEndPos=p;break}}g=p}if(h&&(!l||l.elementStartPos{let e=null;("vp9"===this.internalTrack.info.codec||"av1"===this.internalTrack.info.codec||"avc"===this.internalTrack.info.codec&&!this.internalTrack.info.codecDescription||"hevc"===this.internalTrack.info.codec&&!this.internalTrack.info.codecDescription)&&(e=await this.getFirstPacket({}));const t={codec:ve({width:this.internalTrack.info.width,height:this.internalTrack.info.height,codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,colorSpace:this.internalTrack.info.colorSpace,avcType:1,avcCodecInfo:"avc"===this.internalTrack.info.codec&&e?Ze(e.data):null,hevcCodecInfo:"hevc"===this.internalTrack.info.codec&&e?nt(e.data):null,vp9CodecInfo:"vp9"===this.internalTrack.info.codec&&e?kt(e.data):null,av1CodecInfo:"av1"===this.internalTrack.info.codec&&e?yt(e.data):null}),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0};return this.internalTrack.info.width===this.internalTrack.info.squarePixelWidth&&this.internalTrack.info.height===this.internalTrack.info.squarePixelHeight||(t.displayAspectWidth=this.internalTrack.info.squarePixelWidth,t.displayAspectHeight=this.internalTrack.info.squarePixelHeight),t})()):null}}class ar extends ir{constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getType(){return"audio"}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfig??(this.decoderConfig={codec:Ie({codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,aacCodecInfo:this.internalTrack.info.aacCodecInfo}),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}):null}}const sr=async(e,t,i)=>{let r=t;for(;null===i||r=4;){const t=a.filePos,i=gn(a),s=null!==e.fileSize?e.fileSize-r:null,n=Me(i,s);if(n.header)return{header:n.header,startPos:r};a.filePos=t+n.bytesAdvanced,r=a.filePos}}return null};class nr extends Rt{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.firstFrameHeaderPos=null,this.loadedSamples=[],this.metadataTags=null,this.xingData=null,this.trackBackings=[],this.readingMutex=new 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)throw new Error("No valid MP3 frame found.");this.trackBackings=[new or(this)]})())}async advanceReader(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,Fn);if(e instanceof Promise&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const t=Nn(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}const e=await sr(this.reader,this.lastLoadedPos,this.reader.fileSize);if(!e)return void(this.lastSampleLoaded=!0);const t=e.header;this.lastLoadedPos=e.startPos+t.totalSize-1;const i=De(t.mpegVersionId,t.channel);let r=this.reader.requestSlice(e.startPos+i,4);if(r instanceof Promise&&(r=await r),r){const t=gn(r);if(t===Fe||t===Re){if(!this.xingData){let t=this.reader.requestSlice(e.startPos+i+4,12);if(t instanceof Promise&&(t=await t),t){const e=ln(t,12),i=c(e),r=i.getUint32(0,!1);this.xingData={frameCount:r&Oe.FrameCount?i.getUint32(4,!1):null,fileSize:r&Oe.FileSize?i.getUint32(8,!1):null}}}return}}this.firstFrameHeader||(this.firstFrameHeader=t,this.firstFrameHeaderPos=e.startPos),t.sampleRate!==this.firstFrameHeader.sampleRate&&console.warn(`MP3 changed sample rate mid-file: ${this.firstFrameHeader.sampleRate} Hz to ${t.sampleRate} Hz. Might be a bug, so please report this file.`);const 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,Fn);if(i instanceof Promise&&(i=await i),!i)break;const r=Nn(i);if(!r)break;t=!0;let a=this.reader.requestSlice(i.filePos,r.size);if(a instanceof Promise&&(a=await a),!a)break;On(a,r,this.metadataTags),e=i.filePos+r.size}if(!t&&null!==this.reader.fileSize&&this.reader.fileSize>=An){let e=this.reader.requestSlice(this.reader.fileSize-An,An);e instanceof Promise&&(e=await e),i(e);"TAG"===In(e,3)&&Dn(e,this.metadataTags)}return this.metadataTags}finally{e()}}}class or{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}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){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 i=(t=e.firstFrameHeader.lowSamplingFrequency,r=e.firstFrameHeader.layer,a=e.firstFrameHeader.bitrate,s=e.firstFrameHeader.sampleRate,0===r?0:1===r?144*a/(s<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=P(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 ur=e=>{const t=c(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},dr=(e,t,r)=>{let a=0,s=null;if(e.length>0)if("vorbis"===t.codec){i(t.vorbisInfo);const n=(1<<(e=>{let t=0;for(;e;)t++,e>>=1;return t})(t.vorbisInfo.modeBlockflags.length-1))-1<<1,o=(e[0]&n)>>1;if(o>=t.vorbisInfo.modeBlockflags.length)throw new Error("Invalid mode number.");let c=r;const l=t.vorbisInfo.modeBlockflags[o];if(s=t.vorbisInfo.blocksizes[l],1===l){const i=1+(1|n),r=e[0]&i?1:0;c=t.vorbisInfo.blocksizes[r]}a=null!==c?c+s>>2:0}else if("opus"===t.codec){a=(e=>{const t=e[0]>>3;return{durationInSamples:wt[t]}})(e).durationInSamples}return{durationInSamples:a,vorbisBlockSize:s}},hr=27,fr=282,mr=e=>{const t=e.filePos;if(kn(e)!==cr)return null;e.skip(1);const i=un(e),r=Sn(e),a=kn(e),s=kn(e),n=kn(e),o=un(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}},pr=(e,t)=>{for(;e.filePos>>8&255)===i||(t>>>16&255)===i||(t>>>24&255)===i){if(e.skip(-4),t===cr)return!0;e.skip(1)}}return!1};class gr extends Rt{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,hr,fr);if(t instanceof Promise&&(t=await t),!t)break;const i=mr(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 kr(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 l=c(e.data);t.numberOfChannels=l.getUint8(11),t.sampleRate=l.getUint32(12,!0);const u=l.getUint8(28);t.codecInfo.vorbisInfo={blocksizes:[1<<(15&u),1<<(u>>4)],modeBlockflags:Tt(a.data).modeBlockflags},It(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=c(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=xe,t.codecInfo.opusInfo={preSkip:a.preSkip},It(r.data.subarray(8),this.metadataTags)}async readPacket(e,t){i(te+t.length,0);if(0===c)return null;const l=new Uint8Array(c);let u=0;for(let i=0;i{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 kr{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?xe: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}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 i(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 R}getDisposition(){return{...he,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:a}=dr(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),s=new Mt(i.metadataOnly?Dt: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){i(this.bitstream.lastMetadataPacket);const t=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let r=0;"opus"===this.bitstream.codecInfo.codec&&(i(this.bitstream.codecInfo.opusInfo),r-=this.bitstream.codecInfo.opusInfo.preSkip);const a=await this.demuxer.readPacket(t.startPage,t.startSegmentIndex);return this.createEncodedPacketFromOggPacket(a,{timestampInSamples:r,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 r=D(e*this.internalSampleRate);if(0===r)return this.getFirstPacket(t);if(r<0)return null;i(this.bitstream.lastMetadataPacket);const a=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!a)return null;let s=a.startPage,n=this.demuxer.reader.fileSize;const o=[s];e:for(;s.headerStartPos+s.totalSizer?n=u.headerStartPos:(s=u,o.push(u));continue e}a=u.headerStartPos+u.totalSize}}let c=a.startPage;for(const i of o){if(i.granulePosition===s.granulePosition)break;(!c||i.headerStartPos>c.headerStartPos)&&(c=i)}let l=c;const u=[l];for(;l.serialNumber!==this.bitstream.serialNumber||l.granulePosition!==s.granulePosition;){const e=l.headerStartPos+l.totalSize;let t=this.demuxer.reader.requestSliceRange(e,hr,fr);t instanceof Promise&&(t=await t),i(t);const r=mr(t);i(r),l=r,l.serialNumber===this.bitstream.serialNumber&&u.push(l)}i(-1!==l.granulePosition);let d,h,f=null,m=l,p=0;if(l.headerStartPos===a.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:Dt,endPage:m,endSegmentIndex:p};if(await this.demuxer.findNextPacketStart(e)){const e=yr(u,l,f);i(e);const t=br(u,e.page,e.segmentIndex);t&&(l=t.page,f=t.segmentIndex)}else for(;;){const e=yr(u,l,f);if(!e)break;const t=br(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;){i(null!==f);const e=await this.demuxer.readPacket(l,f);if(!e)break;if(!(l.headerStartPos===a.startPage.headerStartPos&&fr||Math.max(s.timestampInSamples,0)===r))break}const s=await this.demuxer.findNextPacketStart(e);if(!s)break;l=s.startPage,f=s.startSegmentIndex}return g}async getPacketSequential(e,t){const r=await this.sequentialScanMutex.acquire();try{const r=D(e*this.internalSampleRate);e=r/this.internalSampleRate;const s=P(this.sequentialScanCache,r,e=>e.timestampInSamples);let n;if(-1!==s){const e=this.sequentialScanCache[s];n=this.createEncodedPacketFromOggPacket(e.packet,{timestampInSamples:e.timestampInSamples,vorbisLastBlocksize:e.vorbisLastBlockSize},t)}else n=await this.getFirstPacket(t);let o=0;for(;n&&n.timestampe)break;if(n=r,o++,100===o){o=0;const e=this.encodedPacketToMetadata.get(n);i(e),this.sequentialScanCache.length>0&&i(a(this.sequentialScanCache).timestampInSamples<=e.timestampInSamples),this.sequentialScanCache.push(e)}}return n}finally{r()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const br=(e,t,r)=>{let a=t,s=r;e:for(;;){for(s--;s>=0;s--){if(a.lacingValues[s]<255){s++;break e}}i(-1===s);if(!(1&a.headerType)){s=0;break}const t=x(e,e=>e.headerStartPos{if(i>0)return{page:t,segmentIndex:i-1};const r=x(e,e=>e.headerStartPos{let e=this.reader.requestSlice(0,12);e instanceof Promise&&(e=await e),i(e);const t=In(e,4),r="RIFX"!==t,a="RF64"===t,s=pn(e,r);let n=a?this.reader.fileSize:Math.min(s+8,this.reader.fileSize??1/0);if("WAVE"!==In(e,4))throw new Error("Invalid WAVE file - wrong format");let o=0,c=null,l=e.filePos;for(;null===n||l=18&&357!==a){const e=dn(r,i),s=t-18;if(Math.min(s,e)>=22&&a===wr.EXTENSIBLE){r.skip(6);const e=ln(r,16);a=e[0]|e[1]<<8}}a!==wr.MULAW&&a!==wr.ALAW||(c=8),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(m instanceof Promise&&(m=await m),!m)return;const p=In(m,4);if("INFO"!==p&&"INF0"!==p)return;let g=m.filePos;for(;g<=e+t-8;){m.filePos=g;const e=In(m,4),t=pn(m,i),p=ln(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(b);Number.isNaN(e.getTime())||((u=this.metadataTags).date??(u.date=e))}break;case"YEAR":{const e=Number.parseInt(b,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=b);break;case"ICMT":case"CMNT":case"COMM":(f=this.metadataTags).comment??(f.comment=b)}g+=8+t+(1&t)}}async parseId3Chunk(e,t){let i=this.reader.requestSlice(e,t);if(i instanceof Promise&&(i=await i),!i)return;const r=Nn(i);if(r){const a=t-Fn;if(r.size=Math.min(r.size,a),r.size>0){const t=i.slice(e+Fn,r.size);On(t,r,this.metadataTags)}}}getCodec(){if(i(this.audioInfo),this.audioInfo.format===wr.MULAW)return"ulaw";if(this.audioInfo.format===wr.ALAW)return"alaw";if(this.audioInfo.format===wr.PCM){if(1===this.audioInfo.sampleSizeInBytes)return"pcm-u8";if(2===this.audioInfo.sampleSizeInBytes)return"pcm-s16";if(3===this.audioInfo.sampleSizeInBytes)return"pcm-s24";if(4===this.audioInfo.sampleSizeInBytes)return"pcm-s32"}return this.audioInfo.format===wr.IEEE_FLOAT&&4===this.audioInfo.sampleSizeInBytes?"pcm-f32":null}async getMimeType(){return"audio/wav"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}const Pr=2048;class vr{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}async getDecoderConfig(){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}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return i(-1!==this.demuxer.dataSize),this.demuxer.dataSize/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return R}getDisposition(){return{...he}}async getPacketAtIndex(e,t){i(e>=0),i(this.demuxer.audioInfo);const r=e*Pr*this.demuxer.audioInfo.blockSizeInBytes;if(r>=this.demuxer.dataSize)return null;const a=Math.min(Pr*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-r);if(null===this.demuxer.reader.fileSize){let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+r,a);if(e instanceof Promise&&(e=await e),!e)return null}let s;if(t.metadataOnly)s=Dt;else{let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+r,a);e instanceof Promise&&(e=await e),i(e),s=ln(e,a)}const n=e*Pr/this.demuxer.audioInfo.sampleRate,o=a/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(e,this.demuxer.lastKnownPacketIndex),new Mt(s,"key",n,o,e,a)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,t){i(this.demuxer.audioInfo);const r=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/Pr,(this.demuxer.dataSize-1)/(Pr*this.demuxer.audioInfo.blockSizeInBytes)));if(r<0)return null;const a=await this.getPacketAtIndex(r,t);if(a)return a;if(0===r)return null;i(null===this.demuxer.reader.fileSize);let s=await this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,t);for(;s;){const e=await this.getNextPacket(s,t);if(!e)break;s=e}return s}getNextPacket(e,t){i(this.demuxer.audioInfo);const r=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/Pr);return this.getPacketAtIndex(r+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const Ir=e=>{const t=e.filePos,i=ln(e,9),r=new fe(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}},xr=1024;class Cr extends Rt{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();i(this.firstFrameHeader),this.trackBackings=[new Br(this)]})())}async advanceReader(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,Fn);if(e instanceof Promise&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const t=Nn(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}let e=this.reader.requestSliceRange(this.lastLoadedPos,7,9);if(e instanceof Promise&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const t=Ir(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 r=me[t.samplingFrequencyIndex];i(void 0!==r);const a=xr/r,s={timestamp:this.nextTimestampInSamples/r,duration:a,dataStart:t.startPos,dataSize:t.frameLength};this.loadedSamples.push(s),this.nextTimestampInSamples+=xr,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,Fn);if(t instanceof Promise&&(t=await t),!t)break;const i=Nn(t);if(!i)break;let r=this.reader.requestSlice(t.filePos,i.size);if(r instanceof Promise&&(r=await r),!r)break;On(r,i,this.metadataTags),e=t.filePos+i.size}return this.metadataTags}finally{e()}}}class Br{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return this.getSampleRate()/xr}isRelativeToUnixEpoch(){return!1}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return R}getCodec(){return"aac"}getInternalCodecId(){return i(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){i(this.demuxer.firstFrameHeader);const e=pe[this.demuxer.firstFrameHeader.channelConfiguration];return i(void 0!==e),e}getSampleRate(){i(this.demuxer.firstFrameHeader);const e=me[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return i(void 0!==e),e}getDisposition(){return{...he}}async getDecoderConfig(){return i(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=Dt;else{let e=this.demuxer.reader.requestSlice(i.dataStart,i.dataSize);if(e instanceof Promise&&(e=await e),!e)return null;r=ln(e,i.dataSize)}return new Mt(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=S(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=P(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{for(var t;null===this.reader.fileSize||en.end-6)return{num:o.num,blockSize:o.blockSize,sampleRate:o.sampleRate,size:n.end-e,isLastFrame:!0};if(255===un(n)){const t=n.filePos;if(un(n)!==(1===this.blockingBit?249:248)){n.filePos=t;continue}n.skip(-2);const i=n.filePos-e,r=this.readFlacFrameHeader({slice:n,isFirstPacket:!1});if(!r){n.filePos=t;continue}if(0===this.blockingBit){if(r.num-o.num!==1){n.filePos=t;continue}}else if(r.num-o.num!==o.blockSize){n.filePos=t;continue}return{num:o.num,blockSize:o.blockSize,sampleRate:o.sampleRate,size:i,isLastFrame:!1}}}}readFlacFrameHeader({slice:e,isFirstPacket:t}){const r=e.filePos,a=ln(e,4),s=new fe(a);if(32764!==s.readBits(15))return null;if(null===this.blockingBit){i(t);const e=s.readBits(1);this.blockingBit=e}else if(1===this.blockingBit){i(!t);if(1!==s.readBits(1))return null}else{if(0!==this.blockingBit)throw new Error("Invalid blocking bit");i(!t);if(0!==s.readBits(1))return null}const n=(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)(s.readBits(4));if(!n)return null;i(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}})(s.readBits(4),this.audioInfo.sampleRate);if(!o)return null;s.readBits(4),s.readBits(3);if(0!==s.readBits(1))return null;const c=(e=>{let t=0;const i=new fe(ln(e,1));for(;1===i.readBits(1);)t++;if(0===t)return i.readBits(7);const r=[],a=t-1,s=new fe(ln(e,a)),n=8-t-1;for(let o=0;oe|t<"uncommon-u16"===t?hn(e)+1:"uncommon-u8"===t?un(e)+1:"number"===typeof t?t:(B(t),void i(!1)))(e,n),u=((e,t)=>"uncommon-u16"===t?hn(e):"uncommon-u16-10"===t?10*hn(e):"uncommon-u8"===t?un(e):"number"===typeof t?t:null)(e,o);if(null===u)return null;if(u!==this.audioInfo.sampleRate)return null;const d=e.filePos-r,h=un(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})(ln(e,d));return h!==f?null:{num:c,blockSize:l,sampleRate:u}}async advanceReader(){await this.readMetadata(),i(null!==this.lastLoadedPos),i(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 r=this.loadedSamples[this.loadedSamples.length-1],a={blockOffset:r?r.blockOffset+r.blockSize:0,blockSize:t.blockSize,byteOffset:e,byteSize:t.size};this.lastLoadedPos=this.lastLoadedPos+t.size,this.loadedSamples.push(a),t.isLastFrame&&(this.lastSampleLoaded=!0)}}class _r{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 R}getTimeResolution(){return i(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return i(this.demuxer.audioInfo),0===this.demuxer.audioInfo.totalSamples?null:this.demuxer.audioInfo.totalSamples/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getDisposition(){return{...he}}async getDecoderConfig(){return i(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(i(this.demuxer.audioInfo),e<0)throw new Error("Timestamp cannot be negative");const r=await this.demuxer.readingMutex.acquire();try{for(;;){const i=P(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{r()}}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 r=this.demuxer.loadedSamples[e];if(!r)return null;let a;if(t.metadataOnly)a=Dt;else{let e=this.demuxer.reader.requestSlice(r.byteOffset,r.byteSize);if(e instanceof Promise&&(e=await e),!e)return null;a=ln(e,r.byteSize)}i(this.demuxer.audioInfo);const s=r.blockOffset/this.demuxer.audioInfo.sampleRate,n=r.blockSize/this.demuxer.audioInfo.sampleRate;return new Mt(a,"key",s,n,e,r.byteSize)}async getFirstPacket(e){for(;0===this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)}}const Ar=9e4,Fr=188,Rr="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.",Dr=new Set;class Mr extends Rt{constructor(e){super(e),this.metadataPromise=null,this.elementaryStreams=[],this.trackBackingEntries=[],this.packetOffset=0,this.packetStride=-1,this.sectionEndPositions=[],this.seekChunkSize=5242880,this.minReferencePointByteDistance=-1,this.reader=e._reader}async readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{let e=this.reader.requestSlice(0,205);e instanceof Promise&&(e=await e),i(e);const t=ln(e,205);if(71===t[0]&&71===t[188])this.packetOffset=0,this.packetStride=Fr;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 r=this.packetOffset,a=null,s=!1,n=!1;for(;;){const e=await this.readPacketHeader(r);if(!e)break;if(0===e.payloadUnitStartIndicator){r+=this.packetStride;continue}const t=await this.readSection(r,!0,!n);if(!t)break;const o=3,c=32;let l=!1;if(!n&&0!==t.pid){if(!(0===t.payload[0]&&0===t.payload[1]&&1===t.payload[2])){const e=new fe(t.payload),i=e.readAlignedByte();e.skipBits(8*i);l=2===e.readBits(8)}}if(0!==t.pid||s)if(t.pid!==a&&!l||n){const e=this.elementaryStreams.find(e=>e.pid===t.pid);e:if(e&&!e.initialized){const r=Or(t,!0);if(!r)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 a=new Wr(e,r);if("video"===e.info.type){for(;;){if(a.suppliedPacket=null,await a.markNextPacket(),"avc"===e.info.codec){if(!a.suppliedPacket)throw new Error("Invalid AVC video stream; could not extract AVCDecoderConfigurationRecord from any packet.");if(e.info.avcCodecInfo=Ze(a.suppliedPacket.data),!e.info.avcCodecInfo)continue;const t=e.info.avcCodecInfo.sequenceParameterSets[0];i(t);const r=tt(t);e.info.width=r.displayWidth,e.info.height=r.displayHeight;const s=r.pixelAspectRatio.num,n=r.pixelAspectRatio.den;s>0&&n>0&&(s>n?(e.info.squarePixelWidth=Math.round(e.info.width*s/n),e.info.squarePixelHeight=e.info.height):(e.info.squarePixelWidth=e.info.width,e.info.squarePixelHeight=Math.round(e.info.height*n/s))),e.info.colorSpace={primaries:h[r.colourPrimaries],transfer:m[r.transferCharacteristics],matrix:g[r.matrixCoefficients],fullRange:!!r.fullRangeFlag},e.info.reorderSize=r.maxDecFrameBuffering;break}if("hevc"===e.info.codec){if(!a.suppliedPacket)throw new Error("Invalid HEVC video stream; could not extract HVCDecoderConfigurationRecord from first packet.");if(e.info.hevcCodecInfo=nt(a.suppliedPacket.data),!e.info.hevcCodecInfo)continue;const t=e.info.hevcCodecInfo.arrays.find(e=>e.nalUnitType===Ve.SPS_NUT).nalUnits[0];i(t);const r=st(t);e.info.width=r.displayWidth,e.info.height=r.displayHeight,r.pixelAspectRatio.num>r.pixelAspectRatio.den?(e.info.squarePixelWidth=Math.round(e.info.width*r.pixelAspectRatio.num/r.pixelAspectRatio.den),e.info.squarePixelHeight=e.info.height):(e.info.squarePixelWidth=e.info.width,e.info.squarePixelHeight=Math.round(e.info.height*r.pixelAspectRatio.den/r.pixelAspectRatio.num)),e.info.colorSpace={primaries:h[r.colourPrimaries],transfer:m[r.transferCharacteristics],matrix:g[r.matrixCoefficients],fullRange:!!r.fullRangeFlag},e.info.reorderSize=r.maxDecFrameBuffering;break}throw new Error("Unhandled.")}e.info.decoderConfig={codec:ve({width:e.info.width,height:e.info.height,codec:e.info.codec,codecDescription:null,colorSpace:e.info.colorSpace,avcType:1,avcCodecInfo:e.info.avcCodecInfo,hevcCodecInfo:e.info.hevcCodecInfo,vp9CodecInfo:null,av1CodecInfo:null}),codedWidth:e.info.width,codedHeight:e.info.height,colorSpace:e.info.colorSpace},e.info.width===e.info.squarePixelWidth&&e.info.height===e.info.squarePixelHeight||(e.info.decoderConfig.displayAspectWidth=e.info.squarePixelWidth,e.info.decoderConfig.displayAspectHeight=e.info.squarePixelHeight),e.initialized=!0}else{if(await a.markNextPacket(),!a.suppliedPacket)throw new Error(`Couldn't parse first media packet for Elementary Stream with PID ${e.pid}`);if("aac"===e.info.codec){const t=on.tempFromBytes(a.suppliedPacket.data),i=Ir(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=pe[i.channelConfiguration],e.info.sampleRate=me[i.samplingFrequencyIndex]}else if("mp3"===e.info.codec){const t=gn(on.tempFromBytes(a.suppliedPacket.data)),i=Me(t,a.suppliedPacket.data.byteLength);if(!i.header)throw new Error("Invalid MP3 audio stream; could not read frame header from first packet.");e.info.numberOfChannels=3===i.header.channel?1:2,e.info.sampleRate=i.header.sampleRate}else if("ac3"===e.info.codec){const t=Ct(a.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=xt[t.acmod]+t.lfeon,e.info.sampleRate=ze[t.fscod]}else{if("eac3"!==e.info.codec)throw new Error("Unhandled.");{const t=_t(a.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=Ft(t),e.info.sampleRate=i}}e.info.decoderConfig={codec:Ie({codec:e.info.codec,codecDescription:null,aacCodecInfo:e.info.aacCodecInfo}),numberOfChannels:e.info.numberOfChannels,sampleRate:e.info.sampleRate},e.initialized=!0}}}else{const e=new fe(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);for(e.skipBits(8*a);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;for(;e.posc;){const t=e.readBits(16);e.skipBits(3);const i=e.readBits(13);if(0!==t){if(null!==a)throw new Error("Only files with a single program are supported.");a=i}}if(null===a)throw new Error("Program Association Table must link to a Program Map Table.");s=!0}if(n&&this.elementaryStreams.every(e=>e.initialized))break;r+=this.packetStride}if(!n){if(!s)throw new Error("No Program Association Table found in the file.");throw new Error("No Program Map Table found in the file.")}for(const i of this.elementaryStreams)"video"===i.info.type?this.trackBackingEntries.push(new zr(i)):this.trackBackingEntries.push(new Ur(i))})())}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!==S(this.sectionEndPositions,r,e=>e)){l=!1;break}}if(l){const e=P(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(t instanceof Promise&&(t=await t),!t)return null;if(71!==un(t))throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");const i=hn(t);return{payloadUnitStartIndicator:i>>14&1,pid:8191&i,adaptationFieldControl:un(t)>>4&3}}async readPacket(e){let t=this.reader.requestSlice(e,Fr);if(t instanceof Promise&&(t=await t),!t)return null;const i=ln(t,Fr);if(71!==i[0])throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");const r=(i[1]<<8)+i[2];return{payloadUnitStartIndicator:r>>14&1,pid:8191&r,adaptationFieldControl:i[3]>>4&3,body:i.subarray(4)}}}const Nr=(e,t)=>{if(e.payload.byteLength<3)return null;const i=new fe(e.payload);if(1!==i.readBits(24))return null;const r=i.readBits(8);if(i.skipBits(16),188===r||190===r||191===r||240===r||241===r||255===r||242===r||248===r)return null;i.skipBits(8);const a=i.readBits(2);i.skipBits(14);let s=null;if(2===a||3===a)s=0,i.skipBits(4),s+=i.readBits(3)*(1<<30),i.skipBits(1),s+=32768*i.readBits(15),i.skipBits(1),s+=i.readBits(15);else if(t)throw new Error(Rr);return{sectionStartPos:e.startPos,sectionEndPos:e.endPos,pts:s,randomAccessIndicator:e.randomAccessIndicator}},Or=(e,t)=>{i(null!==e.endPos);const r=Nr(e,t);if(!r)return null;const a=new fe(e.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;i(Number.isInteger(c));const l=e.payload.subarray(c,s>0?6+s:e.payload.byteLength);return{...r,data:l}};class Lr{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 r=0;for(const a of e.trackBackingEntries)if(a.getType()===t&&r++,i(a instanceof Lr),a.elementaryStream===this.elementaryStream)break;return r}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.elementaryStream.streamType}getName(){return null}getLanguageCode(){return R}getDisposition(){return{...he,primary:!1}}getTimeResolution(){return Ar}isRelativeToUnixEpoch(){return!1}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 Mt(i.metadataOnly?Dt:e.data,r,e.pts/Ar,Math.max(t/Ar,0),e.sequenceNumber,e.data.byteLength)}async getFirstPacket(e){const t=this.elementaryStream.firstSection;i(t);const r=Or(t,!0);i(r);const a=new Wr(this.elementaryStream,r),s=new Vr(this,a),n=await s.readNext();if(!n)return null;const o=this.createEncodedPacket(n.packet,n.duration,e);return this.packetBuffers.set(o,s),this.packetSectionStarts.set(o,n.packet.sectionStartPos),o}async getNextPacket(e,t){let r=this.packetBuffers.get(e);if(r){const i=await r.readNext();if(!i)return null;this.packetBuffers.delete(e);const a=this.createEncodedPacket(i.packet,i.duration,t);return this.packetBuffers.set(a,r),this.packetSectionStarts.set(a,i.packet.sectionStartPos),a}const a=this.packetSectionStarts.get(e);if(void 0===a)throw new Error("Packet was not created from this track.");const s=this.elementaryStream.demuxer,n=await s.readSection(a,!0);i(n);const o=Or(n,!0);i(o);const c=new Wr(this.elementaryStream,o);r=new Vr(this,c);const l=e.sequenceNumber;for(;;){const e=await r.readNext();if(!e)return null;if(e.packet.sequenceNumber>l){const i=this.createEncodedPacket(e.packet,e.duration,t);return this.packetBuffers.set(i,r),this.packetSectionStarts.set(i,e.packet.sectionStartPos),i}}}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,r){const s=D(e*Ar),n=this.elementaryStream.demuxer,{reader:o,seekChunkSize:c}=n,l=this.elementaryStream.pid,u=async(e,t,i)=>{let r=e;for(;re.pts),g=-1!==p?m[p]:null;if(g&&s-g.pts<45e3)f=g.sectionStartPos;else{let e=0;if(null!==o.fileSize){const t=Math.ceil(o.fileSize/c);if(t>1){let i=0,r=t-1;for(e=i;i<=r;){const t=Math.floor((i+r)/2),a=N(t*c,n.packetStride)+h.sectionStartPos,o=a+c,l=await u(a,o,!1);l?l.pesPacketHeader.pts<=s?(e=t,i=t+1):r=t-1:r=t-1}}}f=N(e*c,n.packetStride)+h.sectionStartPos}const k=await u(f,o.fileSize??1/0,!1);let b=k?.pesPacketHeader??null;b||(b=h);const y=this.getReorderSize(),w=async(e,t)=>{const o=await n.readSection(e,!0);i(o);const c=Or(o,!0);i(c);const l=new Wr(this.elementaryStream,c),u=new Vr(this,l);for(;;){if((a(u.presentationOrderPackets)?.pts??-1/0)>=s)break;if(!(await u.readNextPacket()))break}const d=C(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();i(m);const p=this.createEncodedPacket(m.packet,m.duration,r);return this.packetBuffers.set(p,u),this.packetSectionStarts.set(p,m.packet.sectionStartPos),p};if(!t||this.allPacketsAreKeyPackets()){e:for(;;){let e=b.sectionStartPos+n.packetStride;for(;;){const t=await n.readPacketHeader(e);if(!t)break e;if(t.pid===l&&1===t.payloadUnitStartIndicator){const t=await n.readSection(e,!1);if(t){const e=Nr(t,!1);if(e&&null!==e.pts){if(e.pts>s)break e;b=e,qr(this.elementaryStream,b);break}}}e+=n.packetStride}}e:for(let e=0;e=n.packetOffset;){const t=await n.readPacketHeader(e);if(!t)break e;if(t.pid===l&&1===t.payloadUnitStartIndicator){const t=await n.readSection(e,!1);if(t){const e=Nr(t,!1);if(e&&null!==e.pts){b=e;break}}}e-=n.packetStride}}return w(b.sectionStartPos,e=>e.pts<=s)}{let e=f,t=null;const r=!this.elementaryStream.canBeTrustedWithKeyPackets;for(;;){let a=null;const f=e<=h.sectionStartPos;let m,p=null;if(f)m=h,p=d;else{const t=await u(e,o.fileSize??1/0,r);m=t?.pesPacketHeader??null,p=t?.section??null}let g=!1,k=0;e:for(;m&&!(null!==t&&m.sectionStartPos>=t);){if(m.pts<=s){let e;if(this.elementaryStream.canBeTrustedWithKeyPackets)e=1===m.randomAccessIndicator;else{i(p);const t=Or(p,!0);i(t);const r=new Wr(this.elementaryStream,t);await r.markNextPacket(),e=1===r.suppliedPacket?.randomAccessIndicator}e&&(a=m)}if(m.pts>s&&(g=!0),g&&(k++,k>y))break;let e=m.sectionStartPos+n.packetStride;for(;;){const t=await n.readPacketHeader(e);if(!t)break e;if(t.pid===l&&1===t.payloadUnitStartIndicator){const t=await n.readSection(e,r);if(t){const e=Nr(t,!1);if(e&&null!==e.pts){m=e,p=t,qr(this.elementaryStream,m);break}}}e+=n.packetStride}}if(a){let e=a;if(0===k)e:for(let i=0;i=n.packetOffset;){const i=await n.readPacketHeader(t);if(!i)break e;if(i.pid===l&&1===i.payloadUnitStartIndicator){const i=await n.readSection(t,r);if(i){const t=Nr(i,!1);if(t&&null!==t.pts){e=t;break}}}t-=n.packetStride}}const t=await w(e.sectionStartPos,e=>e.pts<=s&&1===e.randomAccessIndicator);return i(t),t}if(f)return null;t=e,e=Math.max(N(e-h.sectionStartPos-c,n.packetStride)+h.sectionStartPos,h.sectionStartPos)}}}}class zr extends Lr{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 i(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}}class Ur extends Lr{getType(){return"audio"}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}async getDecoderConfig(){return i(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 0}}const qr=(e,t)=>{const i=e.referencePesPackets,r=P(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 i(e),e}async bufferData(e){const t=this.endPos+e;for(;this.endPos=n)break;o=e;const i=a+o;if(o+4>=n){this.seekTo(i);break}const c=s[o+1],l=s[o+2],u=s[o+3];let d=0,h=null;if(0===c&&0===l&&1===u?(d=4,h=s[o+4]):0===c&&1===l&&(d=3,h=u),0===d){o++;continue}const f=i;if(null!==r){if(null!==h){const e="avc"===t?$e(h):at(h);if("avc"===t?e===qe.AUD:e===Ve.AUD_NUT){const e=f-r;return this.seekTo(r),this.supplyPacket(e,0)}}o+=d}else r=f,o+=d}if(e>6,o=63&s[4];if(3===n||o>37){this.seekTo(t+1);continue}const c=Bt[3*o+n];i(void 0!==c),this.seekTo(t),a=this.ensureBuffered(c),a instanceof Promise&&(a=await a);const l=Math.round(13824e4/e.info.sampleRate);return this.supplyPacket(a,l)}if("eac3"===t){if(11!==r)continue;this.skip(-1);const t=this.currentPos;let i=this.ensureBuffered(5);if(i instanceof Promise&&(i=await i),i<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=Et[n];this.seekTo(t),i=this.ensureBuffered(s),i instanceof Promise&&(i=await i);const c=256*o,l=Math.round(c*Ar/e.info.sampleRate);return this.supplyPacket(i,l)}throw new Error("Unhandled.")}{if(255!==r)continue;this.skip(-1);const t=this.currentPos;let i=this.ensureBuffered(4);if(i instanceof Promise&&(i=await i),i<4)return;const a=this.readBytes(4),s=c(a).getUint32(0),n=Me(s,null);if(n.header){this.seekTo(t);let i=this.ensureBuffered(n.header.totalSize);i instanceof Promise&&(i=await i);const r=n.header.audioSamplesInFrame*Ar/e.info.sampleRate;return this.supplyPacket(i,Math.round(r))}this.seekTo(t+1)}}}if(a=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 r;if(i(-1!==t),t===this.presentationOrderPackets.length-1)r=this.lastDuration;else{r=this.presentationOrderPackets[t+1].pts-e.pts,this.lastDuration=r}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:r}}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(i(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 Hr="application/vnd.apple.mpegurl",Kr="#EXT-X-STREAM-INF:",jr="#EXT-X-I-FRAME-STREAM-INF:",Xr="#EXT-X-MEDIA:",$r="#EXTINF:",Qr="#EXT-X-MAP:",Gr="#EXT-X-KEY:",Yr="#EXT-X-MEDIA-SEQUENCE:",Jr="#EXT-X-BYTERANGE:",Zr="#EXT-X-PROGRAM-DATE-TIME:",ea="#EXT-X-TARGETDURATION:",ta="#EXT-X-PLAYLIST-TYPE:",ia=e=>0===e.length||e.startsWith("#")&&!e.startsWith("#EXT");class ra{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=ae(e,e=>"video"===e.getType())+1;e.push(new na(this,t,i))}else if("audio"===t.type){const i=ae(e,e=>"audio"===e.getType())+1;e.push(new oa(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=ae(e,e=>"video"===e.getType())+1;e.push(new na(this,{id:e.length+1,type:"video"},t))}else if("audio"===r.type){const t=ae(e,e=>"audio"===e.getType())+1;e.push(new oa(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 sa{constructor(e,t,i){this.packetInfos=new WeakMap,this.hydrationPromise=null,this.firstInputTrack=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.");const t=this.segmentedInput.getInputForSegment(this.segmentedInput.firstSegment),i=(await t.getTracks()).find(e=>e.type===this.decl.type&&e.number===this.number);if(!i)throw new Error("No matching track found in underlying media data.");this.firstInputTrack=i})())}getId(){return this.decl.id}getType(){return this.decl.type}getNumber(){return this.number}delegate(e){return this.firstInputTrack?e():this.hydrate().then(e)}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(),i(this.segmentedInput.firstSegment),this.segmentedInput.firstSegment.relativeToUnixEpoch}getBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getBitrate())}getAverageBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getAverageBitrate())}getDurationFromMetadata(e){return this.segmentedInput.getDurationFromMetadata(e)}getLiveRefreshInterval(){return this.segmentedInput.getLiveRefreshInterval()}async createAdjustedPacket(e,t,r){i(e.sequenceNumber>=0),i(this.segmentedInput.firstSegment);const a=await this.segmentedInput.getMediaOffset(t,r.input),s=t.timestamp-this.segmentedInput.firstSegment.timestamp,n=e.clone({timestamp:M(e.timestamp+a,await r.getTimeResolution()),sequenceNumber:Math.floor(1e8*s)+e.sequenceNumber});return this.packetInfos.set(n,{segment:t,track:r,sourcePacket:e}),n}async getFirstPacket(e){await this.hydrate(),i(this.segmentedInput.firstSegment),i(this.firstInputTrack);const t=await this.firstInputTrack._backing.getFirstPacket(e);return t?this.createAdjustedPacket(t,this.segmentedInput.firstSegment,this.firstInputTrack):null}getNextPacket(e,t){return this._getNextInternal(e,t,!1)}getNextKeyPacket(e,t){return this._getNextInternal(e,t,!0)}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 na extends sa{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 oa extends sa{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())}}te();const ca=1/0;class la extends le{constructor(){super(...arguments),this._disposed=!1,this._refCount=0,this._usedForHls=!1,this._sizePromise=null,this.onread=null}async getSizeOrNull(){if(this._disposed)throw new sn;return this._sizePromise??(this._sizePromise=(async()=>{let e=this._getFileSize();return void 0!==e||(await this._read(0,1,0,ca),e=this._getFileSize(),i(void 0!==e)),e})())}async getSize(){if(this._disposed)throw new sn;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 Ta(this,e,t)}_dispatchRead(e,t){this.onread?.(e,t),this._emit("read",{start:e,end:t})}ref(){return new ua(this)}}class ua{constructor(e){if(this._freed=!1,e._disposed)throw new Error("Cannot ref a disposed source.");e._refCount++,this._source=e}get source(){if(!this._source)throw new Error("Can't get source; ref has already been freed.");return this._source}get freed(){return this._freed}free(){if(this._freed)throw new Error("Illegal operation: double free on SourceRef.");const e=this.source;i(e._refCount>0),e._refCount--,0===e._refCount&&(e._dispose(),e._disposed=!0),this._freed=!0,this._source=null}[Symbol.dispose](){this.freed||this.free()}}class da extends la{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 la||e instanceof ua))throw new TypeError("requestHandler must return or resolve to a Source or SourceRef.");const i=e instanceof la?e.ref():e;return(t=i.source)._usedForHls||(t._usedForHls=this._usedForHls),i};return t instanceof Promise?t.then(i):i(t)}}const ha=(e,t)=>e.path===t.path;class fa extends da{constructor(){super(...arguments),this._root=null,this._rootRequest=null}_read(e,t,r,a){if(!this._root){if(!this._rootRequest){const e=this._resolveRequest({path:this.rootPath,isRoot:!0}),t=e=>{const t=e instanceof la?e.ref():e;return this._root=t,this._rootRequest=null,t};e instanceof Promise?this._rootRequest=e.then(t):(t(e),i(this._root))}if(this._rootRequest)return this._rootRequest.then(i=>i.source._read(e,t,r,a))}return this._root.source._read(e,t,r,a)}_getFileSize(){if(this._root)return this._root.source._getFileSize()}_dispose(){this._root?this._root.free():this._rootRequest&&this._rootRequest.then(e=>e.free())}}class ma extends la{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&&(!ie(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");super(),this._readers=new WeakMap,this._blob=e,this._orchestrator=new wa({maxCacheSize:t.maxCacheSize??8388608,maxWorkerCount:4,runWorker:this._runWorker.bind(this),prefetchProfile:ya.fileSystem}),this._orchestrator.fileSize=e.size}_getFileSize(){return this._orchestrator.fileSize}_read(e,t,i,r){return this._orchestrator.read(e,t,i,r)}async _runWorker(e){i(e.strictTarget);let t=this._readers.get(e);if(void 0===t){if("stream"in this._blob&&!K()){t=this._blob.slice(e.currentPos).stream().getReader()}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"))){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 console.warn("Request will not be retried because a CORS error was suspected due to different origins. You can modify this behavior by providing your own function for the 'getRetryDelay' option."),null}return Math.min(2**(e-2),16)},ga=new Set;class ka extends da{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&&(!ie(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(void 0!==t.parallelism&&(!Number.isInteger(t.parallelism)||t.parallelism<1))throw new TypeError("options.parallelism, when provided, must be a positive number.");if(void 0!==t.fetchFn&&"function"!==typeof t.fetchFn)throw new TypeError("options.fetchFn, when provided, must be a function.");super(e instanceof Request?e.url:e instanceof URL?e.href:e,e=>new ka(e.path,this._options)),this._fileSizeDetermined=!1,this._url=e,this._options=t,this._getRetryDelay=t.getRetryDelay??pa;this._orchestrator=new wa({maxCacheSize:t.maxCacheSize??67108864,maxWorkerCount:t.parallelism??2,runWorker:this._runWorker.bind(this),prefetchProfile:ya.network})}_getFileSize(){return this._fileSizeDetermined?this._orchestrator.fileSize:void 0}_read(e,t,i,r){return this._orchestrator.read(e,t,i,r)}async _runWorker(e){for(;;){const i=new AbortController,r=await W(this._options.fetchFn??fetch,this._url,U(this._options.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}`);e:if(null===this._orchestrator.fileSize){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");i&&this._orchestrator.supplyFileSize(e.currentPos+Number(i))}if(this._fileSizeDetermined=!0,206!==r.status){if(!this._usedForHls){const e=new URL(this._url instanceof Request?this._url.url:this._url,"undefined"!==typeof window?window.location.href:void 0);"null"===e.origin||e.pathname.endsWith(".m3u8")||e.pathname.endsWith(".m3u")||ga.has(e.origin)||(console.log(this._usedForHls,this._url,e.pathname),console.warn(`HTTP server (origin ${e.origin}) did not respond to a range request with 206 Partial Content, meaning the entire resource will now be downloaded. To enable efficient media file streaming across a network, please make sure your server supports range requests.`),ga.add(e.origin))}e.currentPos=0,this._orchestrator.options.maxCacheSize=1/0,null!==this._orchestrator.fileSize?e.targetPos=this._orchestrator.fileSize:(e.targetPos=1/0,e.strictTarget=!1),this._orchestrator.consolidateEverythingIntoOneWorker(e)}if(!r.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");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){console.error("Error while reading response stream. Attempting to resume.",t),await ce(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)}}}_dispose(){this._orchestrator.dispose()}}class ba extends la{constructor(e,t={}){if(!(e instanceof ReadableStream))throw new TypeError("stream must be a ReadableStream.");if(!t||"object"!==typeof t)throw new TypeError("options must be an object.");if(void 0!==t.maxCacheSize&&(!ie(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");super(),this._reader=null,this._cache=[],this._pendingSlices=[],this._currentIndex=0,this._targetIndex=0,this._maxRequestedIndex=0,this._endIndex=null,this._pulling=!1,this._stream=e,this._maxCacheSize=t.maxCacheSize??16777216}_getFileSize(){return this._endIndex}_read(e,t){if(null!==this._endIndex&&t>this._endIndex)return null;this._maxRequestedIndex=Math.max(this._maxRequestedIndex,t);const i=P(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 c=i;c=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:l}=I();return this._pendingSlices.push({start:e,end:t,bytes:s,resolve:o,reject:l}),this._targetIndex=Math.max(this._targetIndex,t),this._pulling||(this._pulling=!0,this._pull().catch(e=>{if(this._pulling=!1,!(this._pendingSlices.length>0))throw e;this._pendingSlices.forEach(t=>t.reject(e)),this._pendingSlices.length=0})),n}_throwDueToCacheMiss(){throw new Error("Read is before the cached region. With ReadableStreamSource, you must access the data more sequentially or increase the size of its cache.")}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(){this._pendingSlices.length=0,this._cache.length=0,this._reader?.cancel()}}const ya={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(Z(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 wa{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,r,a){i(!this.disposed);const s=this.options.prefetchProfile(e,t,this.workers),n=Math.max(s.start,r),o=Math.min(s.end,this.fileSize??1/0,a);i(n<=e&&t<=o);let l=null;const u=P(this.cache,e,e=>e.start),d=-1!==u?this.cache[u]:null;d&&d.start<=e&&t<=d.end&&(d.age=this.nextAge++,l={bytes:d.bytes,view:d.view,offset:d.start});const h=P(this.cache,n,e=>e.start),f=l?null:new Uint8Array(t-e);let m=0,p=n;const g=[];if(-1!==h){for(let r=h;r=o)break;if(a.end<=n)continue;const s=Math.max(n,a.start),c=Math.min(o,a.end);if(i(s<=c),p=f.length&&(l={bytes:f,view:c(f),offset:e}),0===g.length)return i(l),l;const{promise:k,resolve:b,reject:y}=I(),w=[];for(const i of g){const r=Math.max(e,i.start),a=Math.min(t,i.end);r===i.start&&a===i.end?w.push(i):re.hole.start),r=-1!==t?this.queuedReads[t]:null;for(r&&i.start<=r.hole.end?(r.hole.end=Math.max(r.hole.end,i.end),r.strictTarget&&(r.strictTarget=e),T&&r.pendingSlices.push(T)):(t++,r={hole:{start:i.start,end:i.end},strictTarget:e,pendingSlices:T?[T]:[],age:this.nextAge++},this.queuedReads.splice(t,0,r));t+1r.hole.end)break;r.hole.end=Math.max(r.hole.end,e.hole.end),r.pendingSlices.push(...e.pendingSlices),r.strictTarget&&(r.strictTarget=e.strictTarget),r.age=Math.min(r.age,e.age),this.queuedReads.splice(t+1,1)}}}return l||(i(f),l=k.then(t=>t&&{bytes:t,view:c(t),offset:e})),l}checkHoleAgainstWorker(e,t,i){if(Z(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))throw t;e.pendingSlices.forEach(e=>e.reject(t)),e.pendingSlices.length=0}).finally(()=>{if(!e.running&&this.queuedReads.length>0){let e=0;for(let i=1;ie.targetPos&&(e.targetPos=e.currentPos,this.checkQueuedReadsAgainstWorker(e));for(let i=0;it.start&&(t.start=a),t.end<=t.start&&(s.holes.splice(e,1),e--)}0===s.holes.length&&(s.resolve(s.bytes),e.pendingSlices.splice(i,1),i--)}for(let i=0;ie){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.pendingSlices.length=0}onWorkerFinished(e){const t=this.workers.indexOf(e);i(-1!==t),e.running=!1,this.workers.splice(t,1),null===this.fileSize&&this.supplyFileSize(e.currentPos);for(const i of e.pendingSlices)i.resolve(null)}insertIntoCache(e){if(0===this.options.maxCacheSize)return;let t=P(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=c(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=c(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);return a instanceof Promise?a.then(e=>e?(e.offset-=this._offset,e):null):a?(a.offset-=this._offset,a):null}_dispose(){this._ref?.free()}ref(){return this._ref??(this._ref=this._baseSource.ref()),super.ref()}}var Sa=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},Pa=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 va=/^0[xX][0-9a-fA-F]+$/,Ia=/^data:.*;base64,/i;class xa extends aa{constructor(e,t,i,r){super(e.input,t,i),this.segments=[],this.nextLines=null,this.currentUpdateSegmentsPromise=null,this.streamHasEnded=!1,this.lastSegmentUpdateTime=-1/0,this.refreshInterval=5,this.demuxer=e,this.nextLines=r}runUpdateSegments(){return this.currentUpdateSegmentsPromise??(this.currentUpdateSegmentsPromise=(async()=>{try{const e=this.getRemainingWaitTimeMs();e>0&&await ce(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 r=Sa(t,await this.demuxer.input._getSourceUncached({path:this.path,isRoot:!1}),!1),a=new nn(r.source),s=await a.requestEntireFile();i(s),e=xn(s,s.length,{ignore:ia})}catch(y){t.error=y,t.hasError=!0}finally{Pa(t)}}let t=!1,r=0,s=null,n=null,o=0,l=null,u=null,d=null,h=null,f=null,m=null,p=!1,g=a(this.segments)??null;const k=e=>{const t=e.indexOf("@"),i=Number(-1===t?e:e.slice(0,t));if(!Number.isInteger(i)||i<0)throw new Error(`Invalid #EXT-X-BYTERANGE length '${e}'.`);let r=null;if(-1!==t&&(r=Number(e.slice(t+1)),!Number.isInteger(r)||r<0))throw new Error(`Invalid #EXT-X-BYTERANGE offset '${e}'.`);return{length:i,offset:r}},b=e=>{o=e,g&&(i(null!==g.sequenceNumber),g.sequenceNumber0&&null!==m&&(r=o*m),p=!0);const e=y.slice(8),t=e.indexOf(","),i=-1===t?e:e.slice(0,t),a=Number(i);if(!Number.isFinite(a)||a<0)throw new Error(`Invalid #EXTINF tag duration '${i}'.`);s=a}else if(y.startsWith(Qr)){const e=new ra(y.slice(11)),t=e.get("uri");if(!t)throw new Error("Invalid #EXT-X-MAP tag; missing URI attribute.");const i=e.get("byterange");let a=null;if(null!==i&&(a=k(i)),a&&null===a.offset)throw new Error("Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset.");if(!g){const e={path:re(this.path,t),offset:a?.offset??0,length:a?.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,relativeToUnixEpoch:null!==f,firstSegment:null,sequenceNumber:null,location:e,duration:0,encryption:n,initSegment:null,lastProgramDateTimeSeconds:f}}s=null,null===h?d=null:h=null}else if(y.startsWith(Gr)){const e=new ra(y.slice(11)),t=e.get("method");if("NONE"===t)n=null;else if("AES-128"===t){const t=e.get("uri");if(!t)throw new Error("Invalid #EXT-X-KEY: AES-128 requires a URI attribute.");let i=null;const r=e.get("iv");if(r){if(!va.test(r))throw new Error(`Unsupported IV format '${r}'.`);let e=r.slice(2);e=e.padStart(32,"0"),i=new Uint8Array(Ht);for(let t=0;t=8&&112===t[4]&&115===t[5]&&115===t[6]&&104===t[7]){const e=c(t).getUint32(0);r=Nt(t.subarray(8,Math.min(e,t.length)))}}n={method:t,psshBox:r}}}}else if(y.startsWith(Yr)){const e=y.slice(22),t=Number(e);if(!Number.isInteger(t)||t<0)throw new Error(`Invalid EXT-X-MEDIA-SEQUENCE value '${e}'.`);b(t)}else if(y.startsWith(Jr)){const e=k(y.slice(17));if(null===e.offset){if(null===d)throw new Error("Invalid M3U8 file; #EXT-X-BYTERANGE without offset requires a previous byte range.");e.offset=d}h=e,d=e.offset+e.length}else if(y.startsWith(Zr)){if(g)continue;const e=y.slice(25),t=Date.parse(e);if(!Number.isFinite(t))continue;const i=t/1e3;if(f===i)continue;if(null===f&&this.segments.length>0){const e=a(this.segments),t=i-(e.timestamp+e.duration);for(const i of this.segments)i.timestamp+=t,i.relativeToUnixEpoch=!0;r+=t}f=i,r=i}else if("#EXT-X-DISCONTINUITY"===y)l=null;else if(y.startsWith(ea)){const e=y.slice(22),t=Number(e);if(!Number.isFinite(t)||t<0)throw new Error(`Invalid EXT-X-TARGETDURATION value '${e}'.`);this.refreshInterval=t,m=t}else{if("#EXT-X-ENDLIST"===y){this.streamHasEnded=!0;break}if(y.startsWith(ta)){"vod"===y.slice(21).toLowerCase()&&(this.streamHasEnded=!0)}}}else{if("#EXTM3U"!==y)throw new Error("Invalid M3U8 file; expected first line to be #EXTM3U.");t=!0}}if(!t)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=P(this.segments,e,e=>e.timestamp);if(-1===r)return null;if(r0;for(;;){if(ae.segment===t);if(r)return r.age=this.nextInputCacheAge++,r.input;let a=null;(t.initSegment||t.firstSegment)&&(a=this.getInputForSegment(t.initSegment??t.firstSegment));const s={...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=>Ot(e,r))||(i=[...i,r]),this.input._formatOptions.isobmff.resolveKeyId({...e,psshBoxes:i})})}},n=new rn({source:new fa(t.location.path,async e=>{i(e.isRoot);const r={...e,isRoot:!1};let a;const s=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;i(e.iv);let n=await this.input._getSourceCached(r);if(s){const e=n.source.slice(t.location.offset,t.location.length??void 0).ref();n.free(),n=e}const o=((e,t,i)=>{let r=!1,a=0;const s=new Zt;return new ReadableStream({pull:async n=>{r||(s.init(await t()),r=!0);let o=e.requestSliceRange(a,0,65552);if(o instanceof Promise&&(o=await o),!o||0===o.length)throw 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=ln(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 nn(n.source),async()=>{const t={stack:[],error:void 0,hasError:!1};try{const i=Sa(t,await this.input._getSourceCached({path:e.keyUri,isRoot:!1},en),!1),r=new nn(i.source),a=await r.requestSlice(0,Ht);if(!a)throw new Error("Invalid AES-128 key; expected at least 16 bytes of data.");return{key:ln(a,Ht),iv:e.iv}}catch(i){t.error=i,t.hasError=!0}finally{Pa(t)}},()=>{n.free()});a=new ba(o).ref()}else i(!1);else if(a=await this.input._getSourceCached(r),s){const e=a.source.slice(t.location.offset,t.location.length??void 0).ref();a.free(),a=e}return a}),formats:this.input._formats.filter(e=>!(e instanceof ja)),initInput:a??void 0,formatOptions:s});n._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:n,age:this.nextInputCacheAge++});if(this.inputCache.length>4){const e=se(this.inputCache,e=>e.age);i(-1!==e),this.inputCache.splice(e,1)}return n}async getLiveRefreshInterval(){return 0===this.getRemainingWaitTimeMs()&&await this.runUpdateSegments(),this.streamHasEnded?null:this.refreshInterval}}class Ca extends Rt{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()=>{i(this.input._rootSource instanceof da);const{rootPath:e}=this.input._rootSource,t=await this.input._reader.requestEntireFile();i(t);const r=xn(t,t.length,{ignore:ia}),a=[],s=[];for(let i=1;i"video"===e.attributes.get("type").toLowerCase()).map(e=>e.attributes.get("group-id")))],o=[...new Set(s.filter(e=>"audio"===e.attributes.get("type").toLowerCase()).map(e=>e.attributes.get("group-id")))],c=await Promise.all(a.map(async(t,r)=>{const a=[],c=t.attributes.get("codecs");let l;if(c)l=c.split(",").map(e=>e.trim());else{const e=this.getSegmentedInputForPath(t.fullPath),i=await e.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=t.attributes.get("video"),d=t.attributes.get("audio"),h=l.some(e=>ke.includes(Ee(e))),f=l.some(e=>ye.includes(Ee(e)));if(null!==u&&!h){if(!n.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 t=s.find(e=>{const t=e.attributes.get("group-id"),i=e.attributes.get("type");return t===u&&"video"===i.toLowerCase()});e:if(t){const r=t.attributes.get("uri");if(null===r)break e;const a=re(e,r),s=this.getSegmentedInputForPath(a),n=(await s.getTrackBackings()).find(e=>"video"===e.getType());if(!n||null===await n.getCodec())break e;const o=await n.getDecoderConfig().then(e=>e?.codec??null);i(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 t=s.find(e=>{const t=e.attributes.get("group-id"),i=e.attributes.get("type");return t===d&&"audio"===i.toLowerCase()});e:if(t){const r=t.attributes.get("uri");if(null===r)break e;const a=re(e,r),s=this.getSegmentedInputForPath(a),n=(await s.getTrackBackings()).find(e=>"audio"===e.getType());if(!n||null===await n.getCodec())break e;const o=await n.getDecoderConfig().then(e=>e?.codec??null);i(null!==o),l.push(o)}}l=[...new Set(l)];let m=null,p=null;const g=t.attributes.getAsNumber("bandwidth");i(null!==g);const k=t.attributes.getAsNumber("average-bandwidth"),b=t.attributes.get("name");for(const e of l){const i=Ee(e);if(null!==i)if(ke.includes(i)){if(null!==m)throw new Error("Unsupported M3U8 file; multiple video codecs found in the CODECS attribute of a variant stream.");m=e;const i=t.attributes.get("video");if(null===i){const e=t.attributes.get("resolution");let i=null,s=null;if(e){const t=e.match(/^(\d+)x(\d+)$/);t&&(i=Number(t[1]),s=Number(t[2]))}a.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:R,lineNumber:t.lineNumber,fullPath:t.fullPath,fullCodecString:m,pairingMask:1n<0?i:null}})}else{if(!o.includes(i))throw new Error(`Invalid M3U8 file; variant stream references audio group "${i}" which is not defined in any #EXT-X-MEDIA tags.`);for(const e of s){const s=e.attributes.get("group-id"),n=e.attributes.get("type");if(s!==i||"audio"!==n.toLowerCase())continue;const o=e.attributes.get("channels")??t.attributes.get("channels"),c=null!==o?Number(o.split("/")[0]):null;a.push({id:-1,demuxer:this,backingTrack:null,default:Aa(e.attributes),autoselect:Aa(e.attributes)||Fa(e.attributes),languageCode:Ra(e.attributes.get("language")),lineNumber:e.lineNumber,fullPath:e.fullPath??t.fullPath,fullCodecString:p,pairingMask:1n<0?c:null}})}}}}return a})),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===R&&(t.languageCode=e.languageCode)):(e.id=l.length+1,l.push(e))};for(const i of c)for(const e of i)u(e);l.sort((e,t)=>e.lineNumber-t.lineNumber),this.trackBackings=[];for(const i of l)"video"===i.info.type?this.trackBackings.push(new Ea(i)):this.trackBackings.push(new _a(i));this.internalTracks=l})())}async getTrackBackings(){return await 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 xa(this,e,i,null),this.segmentedInputs.push(t),t}async getMetadataTags(){return{}}async getMimeType(){return Hr}dispose(){if(this.segmentedInputs){for(const e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}}class Ba{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 r=(await e.getTrackBackings()).filter(e=>e.getType()===this.getType());if(1===r.length)t=r[0];else if(this instanceof Ea){for(const i of r)if(await i.getCodec()===this.getCodec()){t=i;break}}else{i(this instanceof _a);for(const e of r)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{...he,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())}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 Ea extends Ba{constructor(e){super(e)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return"video"}getCodec(){return Ee(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 _a extends Ba{constructor(e){super(e)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return"audio"}getCodec(){return Ee(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 Aa=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}".`)},Fa=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}".`)},Ra=e=>{if(null===e)return R;const t=e.split("-")[0];return t||R};class Da{constructor(){this._isIsobmff=!1}}class Ma extends Da{constructor(){super(...arguments),this._isIsobmff=!0}async _getMajorBrand(e){let t=e._reader.requestSlice(0,12);if(t instanceof Promise&&(t=await t),!t)return null;t.skip(4);const i=In(t,4);return"ftyp"!==i&&"styp"!==i?null:In(t,4)}_createDemuxer(e){return new ei(e)}}class Na extends Ma{async _canReadInput(e){const t=await this._getMajorBrand(e);if(null!==t)return"qt "!==t;let i=e._reader.requestSlice(4,4);return i instanceof Promise&&(i=await i),!!i&&"moof"===In(i,4)}get name(){return"MP4"}get mimeType(){return"video/mp4"}}class Oa extends Ma{async _canReadInput(e){return"qt "===await this._getMajorBrand(e)}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}}class La extends Da{async isSupportedEBMLOfDocType(e,t){let i=e._reader.requestSlice(0,Si);if(i instanceof Promise&&(i=await i),!i)return!1;const r=Pi(i);if(null===r)return!1;if(r<1||r>8)return!1;if(Ii(i,r)!==ki.EBML)return!1;const a=Ci(i);if("number"!==typeof a)return!1;let s=e._reader.requestSlice(i.filePos,a);if(s instanceof Promise&&(s=await s),!s)return!1;const n=i.filePos;for(;s.filePos<=n+a-2;){const e=Bi(s);if(!e)break;const{id:i,size:r}=e,a=s.filePos;if(void 0===r)return!1;switch(i){case ki.EBMLVersion:if(1!==Ii(s,r))return!1;break;case ki.EBMLReadVersion:if(1!==Ii(s,r))return!1;break;case ki.DocType:if(Ei(s,r)!==t)return!1;break;case ki.DocTypeVersion:if(Ii(s,r)>4)return!1}s.filePos=a+r}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new tr(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}}class za extends La{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}}class Ua extends Da{async _canReadInput(e){let t=0;for(;;){let i=e._reader.requestSlice(t,Fn);if(i instanceof Promise&&(i=await i),!i)break;const r=Nn(i);if(!r)break;t=i.filePos+r.size}const i=await sr(e._reader,t,t+4096);if(!i)return!1;const r=i.header,a=De(r.mpegVersionId,r.channel);let s=e._reader.requestSlice(i.startPos+a,4);if(s instanceof Promise&&(s=await s),!s)return!1;const n=gn(s);if(n===Fe||n===Re)return!0;t=i.startPos+i.header.totalSize;const o=await sr(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 nr(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}}class qa extends Da{async _canReadInput(e){let t=e._reader.requestSlice(0,12);if(t instanceof Promise&&(t=await t),!t)return!1;const i=In(t,4);if("RIFF"!==i&&"RIFX"!==i&&"RF64"!==i)return!1;t.skip(4);return"WAVE"===In(t,4)}_createDemuxer(e){return new Sr(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}}class Wa extends Da{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=await t),!!t&&"OggS"===In(t,4)}_createDemuxer(e){return new gr(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}}class Va extends Da{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=await t),!!t&&"fLaC"===In(t,4)}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new Er(e)}}class Ha extends Da{async _canReadInput(e){let t=0;for(;;){let i=e._reader.requestSlice(t,Fn);if(i instanceof Promise&&(i=await i),!i)break;const r=Nn(i);if(!r)break;t=i.filePos+r.size}let i=e._reader.requestSliceRange(t,7,9);if(i instanceof Promise&&(i=await i),!i)return!1;const r=Ir(i);if(!r)return!1;if(t+=r.frameLength,i=e._reader.requestSliceRange(t,7,9),i instanceof Promise&&(i=await i),!i)return!1;const a=Ir(i);return!!a&&(r.objectType===a.objectType&&r.samplingFrequencyIndex===a.samplingFrequencyIndex&&r.channelConfiguration===a.channelConfiguration)}_createDemuxer(e){return new Cr(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}}class Ka extends Da{async _canReadInput(e){let t=e._reader.requestSlice(0,205);if(t instanceof Promise&&(t=await t),!t)return!1;const i=ln(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 Mr(e)}get name(){return"MPEG Transport Stream"}get mimeType(){return"video/MP2T"}}class ja extends Da{async _canReadInput(e){let t=e._reader.requestSlice(0,7);if(t instanceof Promise&&(t=await t),!t)return!1;if(!("#EXTM3U"===In(t,7)))return!1;if(!(e._rootSource instanceof da))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 Ca(e)}get name(){return"HTTP Live Streaming (HLS)"}get mimeType(){return Hr}}const Xa=new Na,$a=new Oa,Qa=new La,Ga=new za,Ya=new Ua,Ja=new qa,Za=new Wa,es=new Ha,ts=new Va,is=new Ka,rs=new ja,as=[rs,Xa,$a,Qa,Ga,Ja,Za,ts,Ya,es,is],ss=[rs,Xa,$a,Ya,es,is];te();let ns=-1/0,os=-1/0,cs=null;"undefined"!==typeof FinalizationRegistry&&(cs=new FinalizationRegistry(e=>{const t=performance.now();"video"===e.type?(t-ns>=1e3&&(console.error("A VideoSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your VideoSamples as soon as you're done using them."),ns=t),"undefined"!==typeof VideoFrame&&e.data instanceof VideoFrame&&e.data.close()):(t-os>=1e3&&(console.error("An AudioSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your AudioSamples as soon as you're done using them."),os=t),"undefined"!==typeof AudioData&&e.data instanceof AudioData&&e.data.close())}));const ls=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],us=new Set(ls);class ds{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(z*this.timestamp)}get microsecondDuration(){return Math.trunc(z*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||!us.has(t.format))throw new TypeError("init.format must be one of: "+ls.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._data=o(e).slice(),this._layout=t.layout??ks(t.format,t.codedWidth,t.codedHeight),this.format=t.format,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=new hs(t.colorSpace),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.codedWidth,this.squarePixelHeight=this.codedHeight)}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&&oe(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 hs(e.colorSpace)}else{if(!("undefined"!==typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!==typeof SVGImageElement&&e instanceof SVGImageElement||"undefined"!==typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!==typeof HTMLVideoElement&&e instanceof HTMLVideoElement||"undefined"!==typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!==typeof OffscreenCanvas&&e instanceof OffscreenCanvas))throw new TypeError("Invalid data type: Must be a BufferSource or CanvasImageSource.");{if(!t||"object"!==typeof t)throw new TypeError("init must be an object.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(void 0!==t.duration&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if("undefined"!==typeof VideoFrame)return new ds(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*z),duration:Math.trunc((t.duration??0)*z)||void 0}),t);let r=0,a=0;if("naturalWidth"in e?(r=e.naturalWidth,a=e.naturalHeight):"videoWidth"in e?(r=e.videoWidth,a=e.videoHeight):"width"in e&&(r=Number(e.width),a=Number(e.height)),!r||!a)throw new TypeError("Could not determine dimensions.");const s=new OffscreenCanvas(r,a),n=s.getContext("2d",{alpha:X(),willReadFrequently:!0});i(n),n.drawImage(e,0,0),this._data=s,this._layout=null,this.format="RGBX",this.visibleRect={left:0,top:0,width:r,height:a},this.squarePixelWidth=r,this.squarePixelHeight=a,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=new hs({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}}this.pixelAspectRatio=ne({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),cs?.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return i(null!==this._data),fs(this._data)?new ds(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation}):this._data instanceof Uint8Array?(i(this._layout),new ds(this._data,{format:this.format,layout:this._layout,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight})):new ds(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight})}close(){this._closed||(cs?.unregister(this),fs(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(gs(e),this._closed)throw new Error("VideoSample is closed.");if(null===this.format)throw new Error("Cannot get allocation size when format is null. Sorry!");if(i(null!==this._data),!fs(this._data)&&(e.colorSpace||e.format&&e.format!==this.format||e.layout||e.rect)){const t=this.toVideoFrame(),i=t.allocationSize(e);return t.close(),i}return fs(this._data)?this._data.allocationSize(e):this._data instanceof Uint8Array?this._data.byteLength:this.codedWidth*this.codedHeight*4}async copyTo(e,t={}){if(!k(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(gs(t),this._closed)throw new Error("VideoSample is closed.");if(null===this.format)throw new Error("Cannot copy video sample data when format is null. Sorry!");if(i(null!==this._data),!fs(this._data)&&(t.colorSpace||t.format&&t.format!==this.format||t.layout||t.rect)){const i=this.toVideoFrame(),r=await i.copyTo(e,t);return i.close(),r}if(fs(this._data))return this._data.copyTo(e,t);if(this._data instanceof Uint8Array){i(this._layout);return o(e).set(this._data),this._layout}{const t=this._data.getContext("2d");i(t);const r=t.getImageData(0,0,this.codedWidth,this.codedHeight);return o(e).set(r.data),[{offset:0,stride:4*this.codedWidth}]}}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");return i(null!==this._data),fs(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace}):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,t,i,r,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 b=f+p/2,y=m+g/2;e.translate(b,y),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&&ps(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;t.crop&&ms(t.crop,s,n);const{sx:d,sy:h,sWidth:f,sHeight:m}=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 p=a%180===0?1:l/u;e.translate(i/2,r/2),e.rotate(a*Math.PI/180),e.scale(1/p,p),e.translate(-i/2,-r/2),e.drawImage(this.toCanvasImageSource(),d,h,f,m,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}}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(i(null!==this._data),this._data instanceof Uint8Array){const e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}return this._data}setRotation(e){if(![0,90,180,270].includes(e))throw new TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}setDuration(e){if(!Number.isFinite(e)||e<0)throw new TypeError("newDuration must be a non-negative number.");this.duration=e}[Symbol.dispose](){this.close()}}class hs{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(d);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(f);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(p);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 fs=e=>"undefined"!==typeof VideoFrame&&e instanceof VideoFrame,ms=(e,t,r)=>{const a=Math.min(e.left,t),s=Math.min(e.top,r),n=Math.min(e.width,t-a),o=Math.min(e.height,r-s);return i(n>=0),i(o>=0),{left:a,top:s,width:n,height:o}},ps=(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.")},gs=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.")}},ks=(e,t,i)=>{const r=bs(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},bs=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:B(e),i(!1)}},ys=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]);class ws{get microsecondTimestamp(){return Math.trunc(z*this.timestamp)}get microsecondDuration(){return Math.trunc(z*this.duration)}constructor(e){if(this._closed=!1,Is(e)){if(null===e.format)throw new TypeError("AudioData with null format is not supported.");this._data=e,this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=e.numberOfFrames,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp/1e6,this.duration=e.numberOfFrames/e.sampleRate}else{if(!e||"object"!==typeof e)throw new TypeError("Invalid AudioDataInit: must be an object.");if(!ys.has(e.format))throw new TypeError("Invalid AudioDataInit: invalid format.");if(!Number.isFinite(e.sampleRate)||e.sampleRate<=0)throw new TypeError("Invalid AudioDataInit: sampleRate must be > 0.");if(!Number.isInteger(e.numberOfChannels)||0===e.numberOfChannels)throw new TypeError("Invalid AudioDataInit: numberOfChannels must be an integer > 0.");if(!Number.isFinite(e?.timestamp))throw new TypeError("init.timestamp must be a number.");const t=e.data.byteLength/(Ts(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*Ts(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=Ts(t),s=Ss(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(!k(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&&!ys.has(t.format))throw new TypeError("Invalid format.");if(void 0!==t.frameOffset&&(!Number.isInteger(t.frameOffset)||t.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(void 0!==t.frameCount&&(!Number.isInteger(t.frameCount)||t.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");const{planeIndex:i,format:r,frameCount:a,frameOffset:s}=t,n=this.format,o=r??this.format;if(!o)throw new Error("Destination format not determined");const l=this.numberOfFrames,u=this.numberOfChannels,d=s??0;if(d>=l)throw new RangeError("frameOffset out of range");const h=void 0!==a?a:l-d;if(h>l-d)throw new RangeError("frameCount out of range");const f=Ts(o),m=Ss(o);if(m&&i>=u)throw new RangeError("planeIndex out of range");if(!m&&0!==i)throw new RangeError("planeIndex out of range");const p=(m?h:h*u)*f;if(e.byteLength2&&o!==n?xs(this._data,g,n,o,u,i,d,h):this._data.copyTo(e,{planeIndex:i,frameOffset:d,frameCount:h,format:o});else{const e=this._data,t=c(e),r=Ps(n),a=Ts(n),s=Ss(n);for(let n=0;n0;){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")}},Ss=e=>{switch(e){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},Ps=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)}},vs=e=>{switch(e){case"u8":case"u8-planar":return(e,t,i)=>e.setUint8(t,F(127.5*(i+1),0,255));case"s16":case"s16-planar":return(e,t,i)=>e.setInt16(t,F(Math.round(32767*i),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,i)=>e.setInt32(t,F(Math.round(2147483647*i),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,i)=>e.setFloat32(t,i,!0)}},Is=e=>"undefined"!==typeof AudioData&&e instanceof AudioData,xs=(e,t,i,r,a,s,n,o)=>{const l=Ps(i),u=vs(r),d=Ts(i),h=Ts(r),f=Ss(i);if(Ss(r))if(f){const r=new ArrayBuffer(o*d),a=c(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.")},_s=e=>{if(!ie(e))throw new TypeError("timestamp must be a number.")},As=(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 Fs{constructor(e){if(!(e instanceof Hs))throw new TypeError("track must be an InputTrack.");this._track=e}async getFirstPacket(e={}){if(Es(e),this._track.input._disposed)throw new sn;return As(this._track,this._track._backing.getFirstPacket(e),e)}async getFirstKeyPacket(e={}){Es(e);const t=await this.getFirstPacket(e);return t?"key"===t.type?t:this.getNextKeyPacket(t,e):null}async getPacket(e,t={}){if(_s(e),Es(t),this._track.input._disposed)throw new sn;return As(this._track,this._track._backing.getPacket(e,t),t)}async getNextPacket(e,t={}){if(!(e instanceof Mt))throw new TypeError("packet must be an EncodedPacket.");if(Es(t),this._track.input._disposed)throw new sn;return As(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(_s(e),Es(t),this._track.input._disposed)throw new sn;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);const r=await this._track._backing.getKeyPacket(e,t);if(!r)return r;i("key"===r.type);return"delta"===await this._track.determinePacketType(r)?this.getKeyPacket(r.timestamp-1/await this._track.getTimeResolution(),t):r}async getNextKeyPacket(e,t={}){if(!(e instanceof Mt))throw new TypeError("packet must be an EncodedPacket.");if(Es(t),this._track.input._disposed)throw new sn;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);const r=await this._track._backing.getNextKeyPacket(e,t);if(!r)return r;i("key"===r.type);return"delta"===await this._track.determinePacketType(r)?this.getNextKeyPacket(r,t):r}packets(e,t,i={}){if(void 0!==e&&!(e instanceof Mt))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 Mt))throw new TypeError("endPacket must be an EncodedPacket.");if(Es(i),this._track.input._disposed)throw new sn;const r=[];let{promise:a,resolve:s}=I(),{promise:n,resolve:o}=I(),c=!1,l=!1,u=null;const d=[],h=()=>Math.max(2,d.length);(async()=>{let u=e??await this.getFirstPacket(i);for(;u&&!l&&!this._track.input._disposed&&!(t&&u.sequenceNumber>=t?.sequenceNumber);)r.length>h()?(({promise:n,resolve:o}=I()),await n):(r.push(u),s(),({promise:a,resolve:s}=I()),u=await this.getNextPacket(u,i));c=!0,s()})().catch(e=>{u||(u=e,s())});const f=this._track;return{async next(){for(;;){if(f.input._disposed)throw new sn;if(l)return{value:void 0,done:!0};if(u)throw u;if(r.length>0){const e=r.shift(),t=performance.now();for(d.push(t);d.length>0&&t-d[0]>=1e3;)d.shift();return o(),{value:e,done:!1}}if(c)return{value:void 0,done:!0};await a}},return:async()=>(l=!0,o(),s(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}}class Rs{constructor(e,t){this.onSample=e,this.onError=t}}class Ds{mediaSamplesInRange(e=0,t=1/0,i){_s(e),_s(t);const r=[];let a=!1,s=null,{promise:n,resolve:o}=I(),{promise:c,resolve:l}=I(),u=!1,d=!1,h=!1,f=null;const m={...i,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{const i=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}=I())))},e=>{f||(f=e,o())}),p=this._createPacketSink(),g=await p.getKeyPacket(e,m)??await p.getFirstKeyPacket(m);let k=g;const b=p.packets(g??void 0,void 0,m);for(await b.next();k&&!d&&!this._track.input._disposed;){const e=Ms(r.length);if(r.length+i.getDecodeQueueSize()>e){({promise:c,resolve:l}=I()),await c;continue}i.decode(k);const t=await b.next();if(t.done)break;k=t.value}await b.return(),h||this._track.input._disposed||await i.flush(),i.close(),!a&&s&&r.push(s),u=!0,o()})().catch(e=>{f||(f=e,o())});const p=this._track,g=()=>{s?.close();for(const e of r)e.close()};return{async next(){for(;;){if(p.input._disposed)throw g(),new sn;if(h)return{value:void 0,done:!0};if(f)throw g(),f;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(),g(),{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 r=async function*(e){Symbol.iterator in e?yield*e[Symbol.iterator]():yield*e[Symbol.asyncIterator]()}(e),a=[],s=[];let{promise:n,resolve:o}=I(),{promise:c,resolve:l}=I(),u=!1,d=!1,h=null;const f=e=>{s.push(e),o(),({promise:n,resolve:o}=I())},m={...t,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{const e=await this._createDecoder(e=>{if(l(),d)return void e.close();let t=0;for(;a.length>0&&e.timestamp-a[0]>-1e-10;)t++,a.shift();if(t>0)for(let i=0;i{h||(h=e,o())}),t=this._createPacketSink();let n=null,p=null,g=-1;const k=async()=>{i(p);let r=p;for(e.decode(r);r.sequenceNumbera&&!d;)({promise:c,resolve:l}=I()),await c;if(d)break;const n=await t.getNextPacket(r,m);i(n),e.decode(n),r=n}g=-1},b=async()=>{await e.flush();for(let e=0;e{h||(h=e,o())});const p=this._track,g=()=>{for(const e of s)e?.close()};return{async next(){for(;;){if(p.input._disposed)throw g(),new sn;if(d)return{value:void 0,done:!0};if(h)throw g(),h;if(s.length>0){const e=s.shift();return i(void 0!==e),l(),{value:e,done:!1}}if(u)return{value:void 0,done:!0};await n}},return:async()=>(d=!0,l(),o(),g(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}}const Ms=e=>0===e?40:8;class Ns extends Rs{constructor(e,t,r,a,s,n){super(e,t),this.codec=r,this.decoderConfig=a,this.rotation=s,this.timeResolution=n,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new V,this.customDecoderQueueSize=0,this.inputTimestamps=[],this.sampleQueue=[],this.currentPacketIndex=0,this.raslSkipped=!1,this.alphaDecoder=null,this.alphaHadKeyframe=!1,this.colorQueue=[],this.alphaQueue=[],this.merger=null,this.mergerCreationFailed=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue=[],this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1;const l=Cs.find(e=>e.supports(r,a));if(l)this.customDecoder=new l,this.customDecoder.codec=r,this.customDecoder.config=a,this.customDecoder.onSample=e=>{if(!(e instanceof ds))throw new TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(e)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{const e=e=>{if(this.alphaQueue.length>0){const t=this.alphaQueue.shift();i(void 0!==t),this.mergeAlpha(e,t)}else this.colorQueue.push(e)};if("avc"===r&&this.decoderConfig.description&&Q()){const e=(e=>{try{const t=c(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++),l=31&t.getUint8(i++),u=[];for(let c=0;c0){const t=tt(e.sequenceParameterSets[0]);t&&0===t.frameMbsOnlyFlag&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"})}}const t=new Error("Decoding error").stack;this.decoder=new VideoDecoder({output:t=>{try{e(t)}catch(i){this.onError(i)}},error:e=>{e.stack=t,this.onError(e)}}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(i(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)).then(()=>this.customDecoderQueueSize--);else{if(i(this.decoder),K()||v(this.inputTimestamps,e.timestamp,e=>e),Q()&&0===this.currentPacketIndex)if("avc"===this.codec){const t=[];for(const r of Xe(e.data,this.decoderConfig)){const i=$e(e.data[r.offset]);i>=20&&i<=31||t.push(e.data.subarray(r.offset,r.offset+r.length))}const i=((e,t)=>{if(t.description){const i=3&o(t.description)[4];return Je(e,i+1)}return Ye(e)})(t,this.decoderConfig);e=new Mt(i,e.type,e.timestamp,e.duration)}else if("hevc"===this.codec){const t=gt(e.data,this.decoderConfig);t&&(e=new Mt(t,e.type,e.timestamp,e.duration))}this.decoder.decode(e.toEncodedVideoChunk()),this.decodeAlphaData(e)}this.currentPacketIndex++}decodeAlphaData(e){if(!e.sideData.alpha||this.mergerCreationFailed)return void this.pushNullAlphaFrame();if(!this.merger)try{this.merger=new Os}catch(r){return console.error("Due to an error, only color data will be decoded.",r),this.mergerCreationFailed=!0,void this.decodeAlphaData(e)}if(!this.alphaDecoder){const e=e=>{if(this.alphaDecoderQueueSize--,this.colorQueue.length>0){const t=this.colorQueue.shift();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)},t=new Error("Decoding error").stack;this.alphaDecoder=new VideoDecoder({output:t=>{try{e(t)}catch(r){this.onError(r)}},error:e=>{e.stack=t,this.onError(e)}}),this.alphaDecoder.configure(this.decoderConfig)}const t=St(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===Ve.RASL_N||i===Ve.RASL_R)return!0}return!1}sampleHandler(e){if(K()){if(this.sampleQueue.length>0&&e.timestamp>=a(this.sampleQueue).timestamp){for(const e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}v(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){if(!t){const t=new ds(e);return void this.sampleHandler(t)}i(this.merger),this.merger.update(e,t),e.close(),t.close();const r=new VideoFrame(this.merger.canvas,{timestamp:e.timestamp,duration:e.duration??void 0}),a=new ds(r);this.sampleHandler(a)}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(i(this.decoder),await Promise.all([this.decoder.flush(),this.alphaDecoder?.flush()]),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),K()){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()):(i(this.decoder),this.decoder.close(),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}}class Os{constructor(){"undefined"!==typeof OffscreenCanvas?this.canvas=new OffscreenCanvas(300,150):this.canvas=document.createElement("canvas");const e=this.canvas.getContext("webgl2",{premultipliedAlpha:!1});if(!e)throw new Error("Couldn't acquire WebGL 2 context.");this.gl=e,this.program=this.createProgram(),this.vao=this.createVAO(),this.colorTexture=this.createTexture(),this.alphaTexture=this.createTexture(),this.gl.useProgram(this.program),this.gl.uniform1i(this.gl.getUniformLocation(this.program,"u_colorTexture"),0),this.gl.uniform1i(this.gl.getUniformLocation(this.program,"u_alphaTexture"),1)}createProgram(){const e=this.createShader(this.gl.VERTEX_SHADER,"#version 300 es\n\t\t\tin vec2 a_position;\n\t\t\tin vec2 a_texCoord;\n\t\t\tout vec2 v_texCoord;\n\t\t\t\n\t\t\tvoid main() {\n\t\t\t\tgl_Position = vec4(a_position, 0.0, 1.0);\n\t\t\t\tv_texCoord = a_texCoord;\n\t\t\t}\n\t\t"),t=this.createShader(this.gl.FRAGMENT_SHADER,"#version 300 es\n\t\t\tprecision highp float;\n\t\t\t\n\t\t\tuniform sampler2D u_colorTexture;\n\t\t\tuniform sampler2D u_alphaTexture;\n\t\t\tin vec2 v_texCoord;\n\t\t\tout vec4 fragColor;\n\t\t\t\n\t\t\tvoid main() {\n\t\t\t\tvec3 color = texture(u_colorTexture, v_texCoord).rgb;\n\t\t\t\tfloat alpha = texture(u_alphaTexture, v_texCoord).r;\n\t\t\t\tfragColor = vec4(color, alpha);\n\t\t\t}\n\t\t"),i=this.gl.createProgram();return this.gl.attachShader(i,e),this.gl.attachShader(i,t),this.gl.linkProgram(i),i}createShader(e,t){const i=this.gl.createShader(e);return this.gl.shaderSource(i,t),this.gl.compileShader(i),i}createVAO(){const e=this.gl.createVertexArray();this.gl.bindVertexArray(e);const t=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),i=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,i),this.gl.bufferData(this.gl.ARRAY_BUFFER,t,this.gl.STATIC_DRAW);const r=this.gl.getAttribLocation(this.program,"a_position"),a=this.gl.getAttribLocation(this.program,"a_texCoord");return this.gl.enableVertexAttribArray(r),this.gl.vertexAttribPointer(r,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(a),this.gl.vertexAttribPointer(a,2,this.gl.FLOAT,!1,16,8),e}createTexture(){const e=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),e}update(e,t){e.displayWidth===this.canvas.width&&e.displayHeight===this.canvas.height||(this.canvas.width=e.displayWidth,this.canvas.height=e.displayHeight),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.colorTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),this.gl.activeTexture(this.gl.TEXTURE1),this.gl.bindTexture(this.gl.TEXTURE_2D,this.alphaTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,t),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4)}close(){this.gl.getExtension("WEBGL_lose_context")?.loseContext(),this.gl=null}}class Ls extends Ds{constructor(e){if(!(e instanceof Xs))throw new TypeError("videoTrack must be an InputVideoTrack.");super(),this._track=e}async _createDecoder(e,t){if(!(await this._track.canDecode()))throw new Error("This video track cannot be decoded by this browser. Make sure to check decodability before using a track.");const r=await this._track.getCodec(),a=await this._track.getRotation(),s=await this._track.getDecoderConfig(),n=await this._track.getTimeResolution();return i(r&&s),new Ns(e,t,r,s,a,n)}_createPacketSink(){return new Fs(this._track)}async getSample(e,t={}){_s(e);for await(const i of this.mediaSamplesAtTimestamps([e],t))return i;throw new Error("Internal error: Iterator returned nothing.")}samples(e=0,t=1/0,i={}){return this.mediaSamplesInRange(e,t,i)}samplesAtTimestamps(e,t={}){return this.mediaSamplesAtTimestamps(e,t)}}class zs{constructor(e,t={}){if(this._rotation=0,this._initPromise=null,this._nextCanvasIndex=0,!(e instanceof Xs))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&&ps(t.crop,"options."),void 0!==t.poolSize&&("number"!==typeof t.poolSize||!Number.isInteger(t.poolSize)||t.poolSize<0))throw new TypeError("poolSize must be a non-negative integer.");this._videoTrack=e,this._alpha=t.alpha??!1,this._options=t,this._fit=t.fit??"fill",this._videoSampleSink=new Ls(e),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=ms(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,r=this._height;let a=this._canvasPool[this._nextCanvasIndex],s=!1;a||("undefined"!==typeof document?(a=document.createElement("canvas"),a.width=t,a.height=r):a=new OffscreenCanvas(t,r),this._canvasPool.length>0&&(this._canvasPool[this._nextCanvasIndex]=a),s=!0),this._canvasPool.length>0&&(this._nextCanvasIndex=(this._nextCanvasIndex+1)%this._canvasPool.length);const n=a.getContext("2d",{alpha:this._alpha||X()});i(n),n.resetTransform(),s||(!this._alpha&&X()?(n.fillStyle="black",n.fillRect(0,0,t,r)):n.clearRect(0,0,t,r)),e.drawWithFit(n,{fit:this._fit,rotation:this._rotation,crop:this._crop});const o={canvas:a,timestamp:e.timestamp,duration:e.duration};return e.close(),o}async getCanvas(e,t){_s(e),await this._ensureInit();const i=await this._videoSampleSink.getSample(e,t);return i&&this._videoSampleToWrappedCanvas(i)}async*canvases(e=0,t=1/0,i){await this._ensureInit(),yield*A(this._videoSampleSink.samples(e,t,i),e=>this._videoSampleToWrappedCanvas(e))}async*canvasesAtTimestamps(e,t){await this._ensureInit(),yield*A(this._videoSampleSink.samplesAtTimestamps(e,t),e=>e&&this._videoSampleToWrappedCanvas(e))}}class Us extends Rs{constructor(e,t,i,r){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new V,this.customDecoderQueueSize=0,this.currentTimestamp=null;const a=t=>{(null===this.currentTimestamp||Math.abs(t.timestamp-this.currentTimestamp)>=t.duration)&&(this.currentTimestamp=t.timestamp);const i=this.currentTimestamp;if(this.currentTimestamp+=t.duration,0===t.numberOfFrames)return void t.close();const a=r.sampleRate;t.setTimestamp(Math.round(i*a)/a),e(t)},s=Bs.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 ws))throw new TypeError("The argument passed to onSample must be an AudioSample.");a(e)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{const e=new Error("Decoding error").stack;this.decoder=new AudioDecoder({output:e=>{try{a(new ws(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)).then(()=>this.customDecoderQueueSize--)):(i(this.decoder),this.decoder.decode(e.toEncodedAudioChunk()))}flush(){return this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(i(this.decoder),this.decoder.flush())}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(i(this.decoder),this.decoder.close())}}class qs extends Rs{constructor(e,t,r){super(e,t),this.decoderConfig=r,this.currentTimestamp=null,i(be.includes(r.codec)),this.codec=r.codec;const{dataType:a,sampleSize:s,littleEndian:n}=Be(this.codec);switch(this.inputSampleSize=s,s){case 1:"unsigned"===a?this.readInputValue=(e,t)=>e.getUint8(t)-128:"signed"===a?this.readInputValue=(e,t)=>e.getInt8(t):"ulaw"===a?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,n)-32768:"signed"===a?this.readInputValue=(e,t)=>e.getInt16(t,n):i(!1);break;case 3:"unsigned"===a?this.readInputValue=(e,t)=>E(e,t,n)-2**23:"signed"===a?this.readInputValue=(e,t)=>((e,t,i)=>E(e,t,i)<<8>>8)(e,t,n):i(!1);break;case 4:"unsigned"===a?this.readInputValue=(e,t)=>e.getUint32(t,n)-2**31:"signed"===a?this.readInputValue=(e,t)=>e.getInt32(t,n):"float"===a?this.readInputValue=(e,t)=>e.getFloat32(t,n):i(!1);break;case 8:"float"===a?this.readInputValue=(e,t)=>e.getFloat64(t,n):i(!1);break;default:B(s),i(!1)}switch(s){case 1:"ulaw"===a||"alaw"===a?(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"===a?(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:B(s),i(!1)}}getDecodeQueueSize(){return 0}decode(e){const t=c(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 c=0;c=n)&&(this.currentTimestamp=e.timestamp);const o=this.currentTimestamp;this.currentTimestamp+=n;const l=new ws({format:this.outputFormat,data:a,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:i,timestamp:o});this.onSample(l)}async flush(){}close(){}}class Ws extends Ds{constructor(e){if(!(e instanceof $s))throw new TypeError("audioTrack must be an InputAudioTrack.");super(),this._track=e}async _createDecoder(e,t){if(!(await this._track.canDecode()))throw new Error("This audio track cannot be decoded by this browser. Make sure to check decodability before using a track.");const r=await this._track.getCodec(),a=await this._track.getDecoderConfig();return i(r&&a),be.includes(a.codec)?new qs(e,t,a):new Us(e,t,r,a)}_createPacketSink(){return new Fs(this._track)}async getSample(e,t={}){_s(e);for await(const i of this.mediaSamplesAtTimestamps([e],t))return i;throw new Error("Internal error: Iterator returned nothing.")}samples(e=0,t=1/0,i={}){return this.mediaSamplesInRange(e,t,i)}samplesAtTimestamps(e,t={}){return this.mediaSamplesAtTimestamps(e,t)}}class Vs{constructor(e){if(!(e instanceof $s))throw new TypeError("audioTrack must be an InputAudioTrack.");this._audioSampleSink=new Ws(e)}_audioSampleToWrappedArrayBuffer(e){const t={buffer:e.toAudioBuffer(),timestamp:e.timestamp,duration:e.duration};return e.close(),t}async getBuffer(e,t){_s(e);const i=await this._audioSampleSink.getSample(e,t);return i&&this._audioSampleToWrappedArrayBuffer(i)}buffers(e=0,t=1/0,i){return A(this._audioSampleSink.samples(e,t,i),e=>this._audioSampleToWrappedArrayBuffer(e))}buffersAtTimestamps(e,t){return A(this._audioSampleSink.samplesAtTimestamps(e,t),e=>e&&this._audioSampleToWrappedArrayBuffer(e))}}class Hs{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof Xs}isAudioTrack(){return this instanceof $s}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}async getInternalCodecId(){return this._backing.getInternalCodecId()}get internalCodecId(){return Ks(this._backing.getInternalCodecId(),"internalCodecId","getInternalCodecId")}async getLanguageCode(){return this._backing.getLanguageCode()}get languageCode(){return Ks(this._backing.getLanguageCode(),"languageCode","getLanguageCode")}async getName(){return this._backing.getName()}get name(){return Ks(this._backing.getName(),"name","getName")}async getTimeResolution(){return this._backing.getTimeResolution()}get timeResolution(){return Ks(this._backing.getTimeResolution(),"timeResolution","getTimeResolution")}async isRelativeToUnixEpoch(){return this._backing.isRelativeToUnixEpoch()}async getDisposition(){return this._backing.getDisposition()}get disposition(){return Ks(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 M((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 Fs(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 Hs))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(Js({filter:e=>e.canBePairedWith(this)},e))}async getPairableVideoTracks(e){return this.input.getVideoTracks(Js({filter:e=>e.canBePairedWith(this)},e))}async getPairableAudioTracks(e){return this.input.getAudioTracks(Js({filter:e=>e.canBePairedWith(this)},e))}async getPrimaryPairableVideoTrack(e){return this.input.getPrimaryVideoTrack(Js({filter:e=>e.canBePairedWith(this)},e))}async getPrimaryPairableAudioTrack(e){return this.input.getPrimaryAudioTrack(Js({filter:e=>e.canBePairedWith(this)},e))}async hasPairableTrack(e){e&&(e=js(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=js(e)),this.hasPairableTrack(async t=>t.isVideoTrack()&&(!e||await e(t)))}hasPairableAudioTrack(e){return e&&(e=js(e)),this.hasPairableTrack(async t=>t.isAudioTrack()&&(!e||await e(t)))}}const Ks=(e,t,i)=>{if(e instanceof Promise)throw new Error(`'${t}' is deprecated and not available synchronously for this track. Use the preferred '${i}()' instead.`);return e},js=e=>{if(void 0!==e&&"function"!==typeof e)throw new TypeError("predicate, when provided, must be a function.");return e?t=>{const i=e=>{if("boolean"!==typeof e)throw new TypeError("predicate must return or resolve to a boolean value.");return e},r=e(t);return r instanceof Promise?r.then(i):i(r)}:void 0};class Xs extends Hs{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 Ks(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){return await(this._backing.getHasOnlyKeyPackets?.())??!1}async getCodedWidth(){return this._backing.getCodedWidth()}get codedWidth(){return Ks(this._backing.getCodedWidth(),"codedWidth","getCodedWidth")}async getCodedHeight(){return this._backing.getCodedHeight()}get codedHeight(){return Ks(this._backing.getCodedHeight(),"codedHeight","getCodedHeight")}async getRotation(){return this._backing.getRotation()}get rotation(){return Ks(this._backing.getRotation(),"rotation","getRotation")}async getSquarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelWidth(){return Ks(this._backing.getSquarePixelWidth(),"squarePixelWidth","getSquarePixelWidth")}async getSquarePixelHeight(){return this._backing.getSquarePixelHeight()}get squarePixelHeight(){return Ks(this._backing.getSquarePixelHeight(),"squarePixelHeight","getSquarePixelHeight")}async getPixelAspectRatio(){return this._pixelAspectRatioCache??(this._pixelAspectRatioCache=ne({num:await this.getSquarePixelWidth()*await this.getCodedHeight(),den:await this.getSquarePixelHeight()*await this.getCodedWidth()}))}get pixelAspectRatio(){return this._pixelAspectRatioCache??(this._pixelAspectRatioCache=ne({num:Ks(this._backing.getSquarePixelWidth(),"pixelAspectRatio","getPixelAspectRatio")*Ks(this._backing.getCodedHeight(),"pixelAspectRatio","getPixelAspectRatio"),den:Ks(this._backing.getSquarePixelHeight(),"pixelAspectRatio","getPixelAspectRatio")*Ks(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=Ks(e,"displayWidth","getDisplayWidth");if(null!==t)return t}const t=Ks(this._backing.getRotation(),"displayWidth","getDisplayWidth")%180===0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight();return Ks(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=Ks(e,"displayHeight","getDisplayHeight");if(null!==t)return t}const t=Ks(this._backing.getRotation(),"displayHeight","getDisplayHeight")%180===0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth();return Ks(t,"displayHeight","getDisplayHeight")}async getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){const e=await this._backing.getColorSpace();return"bt2020"===e.primaries||"smpte432"===e.primaries||"pg"===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(i(null!==t),Cs.some(i=>i.supports(t,e)))return!0;if("undefined"===typeof VideoDecoder)return!1;return!0===(await VideoDecoder.isConfigSupported(e)).supported}catch(e){return console.error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof Mt))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 r=await this.getDecoderConfig();return i(r),St(t,r,e.data)}}class $s extends Hs{constructor(e,t){super(e,t),this._backing=t}get type(){return"audio"}async getCodec(){return this._backing.getCodec()}get codec(){return Ks(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){return await(this._backing.getHasOnlyKeyPackets?.())??!0}async getNumberOfChannels(){return this._backing.getNumberOfChannels()}get numberOfChannels(){return Ks(this._backing.getNumberOfChannels(),"numberOfChannels","getNumberOfChannels")}async getSampleRate(){return this._backing.getSampleRate()}get sampleRate(){return Ks(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(i(null!==t),Bs.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 console.error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof Mt))throw new TypeError("packet must be an EncodedPacket.");return null===await this.getCodec()?null:"key"}}const Qs=e=>-(e??-1/0),Gs=e=>-e,Ys=e=>{if("object"!==typeof e||!e)throw new TypeError("query must be an object.");if(void 0!==e.filter&&"function"!==typeof e.filter)throw new TypeError("query.filter, when provided, must be a function.");if(void 0!==e.sortBy&&"function"!==typeof e.sortBy)throw new TypeError("query.sortBy, when provided, must be a function.");return{filter:e.filter?t=>{const i=e=>{if("boolean"!==typeof e)throw new TypeError("query.filter must return or resolve to a boolean.");return e},r=e.filter(t);return r instanceof Promise?r.then(i):i(r)}:void 0,sortBy:e.sortBy?t=>{const i=e=>{if("number"!==typeof e&&(!Array.isArray(e)||!e.every(e=>"number"===typeof e)))throw new TypeError("query.sortBy must return or resolve to a number or an array of numbers.");return e},r=e.sortBy(t);return r instanceof Promise?r.then(i):i(r)}:void 0}},Js=(e,t)=>({filter:e?.filter||t?.filter?i=>{const r=e?.filter?.(i)??!0,a=e=>!1!==e&&(t?.filter?.(i)??!0);return r instanceof Promise?r.then(a):a(r)}:void 0,sortBy:e?.sortBy||t?.sortBy?i=>{const r=e?.sortBy?.(i)??[],a=t?.sortBy?.(i)??[],s=(e,t)=>[...Array.isArray(e)?e:[e],...Array.isArray(t)?t:[t]];return r instanceof Promise||a instanceof Promise?Promise.all([r,a]).then(([e,t])=>s(e,t)):s(r,a)}:void 0}),Zs=async(e,t)=>{let i=e;if(t?.filter){const r=e.map(e=>t.filter(e));if(r.some(e=>e instanceof Promise)){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=>e instanceof Promise)?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)};te();const en=2;let tn=null;"undefined"!==typeof FinalizationRegistry&&(tn=new FinalizationRegistry(e=>{for(const t of e)t.freed||t.free()}));class rn extends le{get disposed(){return this._disposed}constructor(e){if(super(),this._demuxerPromise=null,this._format=null,this._trackBackingsCache=null,this._backingToTrack=new Map,this._disposed=!1,this._nextSourceCacheAge=0,this._sourceRefs=[],this._sourceCache=[],this._sourceCachePromises=[],this._onFormatDetermined=null,!e||"object"!==typeof e)throw new TypeError("options must be an object.");if(!Array.isArray(e.formats)||e.formats.some(e=>!(e instanceof Da)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof la||e.source instanceof ua))throw new TypeError("options.source must be a Source or SourceRef.");if(e.source instanceof la&&e.source._disposed)throw new TypeError("options.source must not be a disposed Source.");if(void 0!==e.initInput&&!(e.initInput instanceof rn))throw new TypeError("options.initInput, when provided, must be an Input.");void 0!==e.formatOptions&&((e,t)=>{if(!e||"object"!==typeof e)throw new TypeError(`${t}, when provided, must be an object.`);if(void 0!==e.isobmff){if(!e.isobmff||"object"!==typeof e.isobmff)throw new TypeError(`${t}.isobmff, when provided, must be an object.`);if(void 0!==e.isobmff.resolveKeyId&&"function"!==typeof e.isobmff.resolveKeyId)throw new TypeError(`${t}.isobmff.resolveKeyId, when provided, must be a function.`)}})(e.formatOptions,"formatOptions"),this._formats=e.formats,this._initInput=e.initInput??null,this._formatOptions=e.formatOptions??{},e.source instanceof la?this._rootRef=e.source.ref():this._rootRef=e.source,this._sourceRefs.push(this._rootRef),tn?.register(this,this._sourceRefs,this)}get _rootSource(){return this._rootRef.source}async _getSourceUncached(e){i(this._rootSource instanceof da);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 r=this._sourceCache.find(i=>i.cacheGroup===t&&ha(i.request,e));if(r)return r.age++,Promise.resolve(r.sourceRef.source.ref());const a=this._sourceCachePromises.find(i=>i.cacheGroup===t&&ha(i.request,e));if(a)return a.promise.then(e=>e.sourceRef.source.ref());const s=(async()=>{const r=await this._getSourceUncached(e);if(ae(this._sourceCache,e=>e.cacheGroup===t&&1===e.sourceRef.source._refCount)>=4){const e=se(this._sourceCache,e=>e.cacheGroup===t&&1===e.sourceRef.source._refCount?e.age:1/0);i(-1!==e);const r=this._sourceCache[e];this._sourceCache.splice(e,1),r.sourceRef.free(),((e,t)=>{const i=e.indexOf(t);-1!==i&&e.splice(i,1)})(this._sourceRefs,r.sourceRef)}this._sourceRefs.push(r);const a=this._sourceCachePromises.findIndex(t=>t.request===e);i(-1!==a),this._sourceCachePromises.splice(a,1);return{request:e,sourceRef:r,age:this._nextSourceCacheAge++,cacheGroup:t}})();return this._sourceCachePromises.push({request:e,cacheGroup:t,promise:s}),s.then(e=>{const t=e.sourceRef.source.ref();return this._sourceCache.push(e),t})}_getDemuxer(){return this._demuxerPromise??(this._demuxerPromise=(async()=>{this._reader=new nn(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 an})())}get source(){return this._rootSource}async getFormat(){return await this._getDemuxer(),i(this._format),this._format}async canRead(){try{return await this._getDemuxer(),!0}catch(e){if(e instanceof an)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.getFirstTimestamp()));return Math.min(...i)}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=Ys(e));const t=(await this._getTrackBackings()).map(e=>this._wrapBackingAsTrack(e));return Zs(t,e)}async getVideoTracks(e){e&&(e=Ys(e));const t=(await this.getTracks()).filter(e=>e.isVideoTrack());return Zs(t,e)}async getAudioTracks(e){e&&(e=Ys(e));const t=(await this.getTracks()).filter(e=>e.isAudioTrack());return Zs(t,e)}async getPrimaryVideoTrack(e){e&&(e=Ys(e));const t=Js(e,{sortBy:async e=>[Gs((await e.getDisposition()).default),Gs(await e.hasPairableAudioTrack()),Gs(!(await e.hasOnlyKeyPackets())),Qs(await e.getBitrate())]});return(await this.getVideoTracks(t))[0]??null}async getPrimaryAudioTrack(e){e&&(e=Ys(e));const t=await this.getPrimaryVideoTrack(),i=Js(e,{sortBy:async e=>[Gs(!t||e.canBePairedWith(t)),Gs((await e.getDisposition()).default),Qs(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 Xs(this,e):new $s(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,tn?.unregister(this),this._demuxerPromise?.then(e=>e.dispose())}}[Symbol.dispose](){this.dispose()}}class an extends Error{constructor(e="Input has an unsupported or unrecognizable format."){super(e),this.name="UnsupportedInputFormatError"}}class sn extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}}class nn{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 sn;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 on(t,c(t),0,e,e)}const i=e+t,r=this.source._read(e,i,0,ca);return r instanceof Promise?r.then(t=>t?new on(t.bytes,t.view,t.offset,e,i):null):r?new on(r.bytes,r.view,r.offset,e,i):null}requestSliceRange(e,t,r){if(this.source._disposed)throw new sn;if(e<0)return null;if(null!==this.fileSizeNonStrict)return this.requestSlice(e,F(this.fileSizeNonStrict-e,t,r));{const a=this.requestSlice(e,r),s=a=>a||(i(null!==this.fileSizeNonStrict),this.requestSlice(e,F(this.fileSizeNonStrict-e,t,r)));return a instanceof Promise?a.then(s):s(a)}}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);const i=1024*e.length;let r=this.requestSliceRange(i,0,1024);if(r instanceof Promise&&(r=await r),!r)break;e.push(ln(r,r.length)),t+=r.length}const i=new Uint8Array(t);let r=0;for(const a of e)i.set(a,r),r+=a.length;return new on(i,c(i),0,0,t)})()}}class on{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 on(e,c(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 on(this.bytes,this.view,this.offset,e,e+t)}}const cn=(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.`)},ln=(e,t)=>{cn(e,t);const i=e.bytes.subarray(e.bufferPos,e.bufferPos+t);return e.bufferPos+=t,i},un=e=>(cn(e,1),e.view.getUint8(e.bufferPos++)),dn=(e,t)=>{cn(e,2);const i=e.view.getUint16(e.bufferPos,t);return e.bufferPos+=2,i},hn=e=>{cn(e,2);const t=e.view.getUint16(e.bufferPos,!1);return e.bufferPos+=2,t},fn=e=>{cn(e,3);const t=E(e.view,e.bufferPos,!1);return e.bufferPos+=3,t},mn=e=>{cn(e,2);const t=e.view.getInt16(e.bufferPos,!1);return e.bufferPos+=2,t},pn=(e,t)=>{cn(e,4);const i=e.view.getUint32(e.bufferPos,t);return e.bufferPos+=4,i},gn=e=>{cn(e,4);const t=e.view.getUint32(e.bufferPos,!1);return e.bufferPos+=4,t},kn=e=>{cn(e,4);const t=e.view.getUint32(e.bufferPos,!0);return e.bufferPos+=4,t},bn=e=>{cn(e,4);const t=e.view.getInt32(e.bufferPos,!1);return e.bufferPos+=4,t},yn=(e,t)=>{let i,r;return t?(i=pn(e,!0),r=pn(e,!0)):(r=pn(e,!1),i=pn(e,!1)),4294967296*r+i},wn=e=>4294967296*gn(e)+gn(e),Tn=e=>4294967296*bn(e)+gn(e),Sn=e=>{const t=kn(e),i=(e=>{cn(e,4);const t=e.view.getInt32(e.bufferPos,!0);return e.bufferPos+=4,t})(e);return 4294967296*i+t},Pn=e=>{cn(e,4);const t=e.view.getFloat32(e.bufferPos,!1);return e.bufferPos+=4,t},vn=e=>{cn(e,8);const t=e.view.getFloat64(e.bufferPos,!1);return e.bufferPos+=8,t},In=(e,t)=>{cn(e,t);let i="";for(let r=0;rl.decode(ln(e,t)).split("\n").map(e=>e.trim()).filter(e=>e.length>0&&!i?.ignore?.(e));var Cn,Bn,En,_n;(Bn=Cn||(Cn={}))[Bn.Unsynchronisation=128]="Unsynchronisation",Bn[Bn.ExtendedHeader=64]="ExtendedHeader",Bn[Bn.ExperimentalIndicator=32]="ExperimentalIndicator",Bn[Bn.Footer=16]="Footer",(_n=En||(En={}))[_n.ISO_8859_1=0]="ISO_8859_1",_n[_n.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",_n[_n.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",_n[_n.UTF_8=3]="UTF_8";const An=128,Fn=10,Rn=["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"],Dn=(e,t)=>{var i;const r=e.filePos;t.raw??(t.raw={}),(i=t.raw).TAG??(i.TAG=ln(e,An-3)),e.filePos=r;const a=Mn(e,30);a&&(t.title??(t.title=a));const s=Mn(e,30);s&&(t.artist??(t.artist=s));const n=Mn(e,30);n&&(t.album??(t.album=n));const o=Mn(e,4),c=Number.parseInt(o,10);Number.isInteger(c)&&c>0&&(t.date??(t.date=new Date(c,0,1)));const l=ln(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=Mn(e,28),e.skip(2)}else e.skip(-30),u=Mn(e,30);u&&(t.comment??(t.comment=u));const d=un(e);d{const i=ln(e,t),r=J(i.indexOf(0),i.length),a=i.subarray(0,r);let s="";for(let n=0;n{const t=e.filePos,i=In(e,3),r=un(e),a=un(e),s=un(e),n=gn(e);if("ID3"!==i||255===r||255===a||0!==(2155905152&n))return e.filePos=t,null;return{majorVersion:r,revision:a,flags:s,size:Ne(n)}},On=(e,t,i)=>{var r,a,s,n,o;if(![2,3,4].includes(t.majorVersion))return void console.warn(`Unsupported ID3v2 major version: ${t.majorVersion}`);const c=ln(e,t.size),l=new Ln(t,c);if(t.flags&Cn.Footer&&l.removeFooter(),t.flags&Cn.Unsynchronisation&&3===t.majorVersion&&l.ununsynchronizeAll(),t.flags&Cn.ExtendedHeader){const e=l.readU32();3===t.majorVersion?l.pos+=e:l.pos+=e-4}for(;l.pos<=l.bytes.length-l.frameHeaderSize();){const e=l.readId3V2Frame();if(!e)break;const c=l.pos,u=l.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&Cn.Unsynchronisation)),d)console.warn(`Skipping encrypted ID3v2 frame ${e.id}`),l.pos=u;else if(h)console.warn(`Skipping compressed ID3v2 frame ${e.id}`),l.pos=u;else{if(f&&l.ununsynchronizeRegion(l.pos,u),i.raw??(i.raw={}),"TXXX"===e.id){const e=(r=i.raw).TXXX??(r.TXXX={}),t=l.readId3V2TextEncoding(),a=l.readId3V2Text(t,u),s=l.readId3V2Text(t,u);e[a]??(e[a]=s)}else"T"===e.id[0]?(a=i.raw)[s=e.id]??(a[s]=l.readId3V2EncodingAndText(u)):(n=i.raw)[o=e.id]??(n[o]=l.readBytes(e.size));switch(l.pos=c,e.id){case"TIT2":case"TT2":i.title??(i.title=l.readId3V2EncodingAndText(u));break;case"TIT3":case"TT3":i.description??(i.description=l.readId3V2EncodingAndText(u));break;case"TPE1":case"TP1":i.artist??(i.artist=l.readId3V2EncodingAndText(u));break;case"TALB":case"TAL":i.album??(i.album=l.readId3V2EncodingAndText(u));break;case"TPE2":case"TP2":i.albumArtist??(i.albumArtist=l.readId3V2EncodingAndText(u));break;case"TRCK":case"TRK":{const e=l.readId3V2EncodingAndText(u).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=l.readId3V2EncodingAndText(u).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=l.readId3V2EncodingAndText(u);let t=/^\((\d+)\)/.exec(e);if(t){const e=Number.parseInt(t[1]);if(void 0!==Rn[e]){i.genre??(i.genre=Rn[e]);break}}if(t=/^\d+$/.exec(e),t){const e=Number.parseInt(t[0]);if(void 0!==Rn[e]){i.genre??(i.genre=Rn[e]);break}}i.genre??(i.genre=e)}break;case"TDRC":case"TDAT":{const e=l.readId3V2EncodingAndText(u),t=new Date(e);Number.isNaN(t.getTime())||(i.date??(i.date=t))}break;case"TYER":case"TYE":{const e=l.readId3V2EncodingAndText(u),t=Number.parseInt(e,10);Number.isInteger(t)&&(i.date??(i.date=new Date(t,0,1)))}break;case"USLT":case"ULT":{const e=l.readU8();l.pos+=3,l.readId3V2Text(e,u),i.lyrics??(i.lyrics=l.readId3V2Text(e,u))}break;case"COMM":case"COM":{const e=l.readU8();l.pos+=3,l.readId3V2Text(e,u),i.comment??(i.comment=l.readId3V2Text(e,u))}break;case"APIC":case"PIC":{const e=l.readId3V2TextEncoding();let r;if(2===t.majorVersion){const e=l.readAscii(3);r="PNG"===e?"image/png":"JPG"===e?"image/jpeg":"image/*"}else r=l.readId3V2Text(e,u);const a=l.readU8(),s=l.readId3V2Text(e,u).trimEnd(),n=u-l.pos;if(n>=0){const e=l.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:l.pos+=e.size}l.pos=u}}};class Ln{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:Ne(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 En.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=J(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=J(r.findIndex(e=>0===e),r.length);return this.pos=i+Math.min(e+1,r.length),l.decode(r.subarray(0,e))}case En.UTF_16_BE_NO_BOM:{const e=new TextDecoder("utf-16be"),t=J(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 En.UTF_8:{const e=J(r.findIndex(e=>0===e),r.length);return this.pos=i+Math.min(e+1,r.length),l.decode(r.subarray(0,e))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";const t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}}class zn{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 Vs(r),void t?.()):(this.audioSink=null,this.ensureAudioContext(),void t?.()):(this.handleNoAudioTrack(),void t?.())}async runIterator(e){if(this.audioSink)for(await this.stopIterator(),this.audioIterator=this.audioSink.buffers(this.currentTime);;){if(e!==this.asyncId||this.paused)return;const i=this.audioIterator.next(),r=setInterval(()=>{e!==this.asyncId||this.paused?clearInterval(r):"running"===this.audioContext.state&&this.audioContext.currentTime>=this.latestScheduledEndTime-.2&&(this.audioContext.suspend(),this.events.emit("waiting"))},50);let a;try{a=await i}catch(t){console.error("Audio iterator error:",t);break}finally{clearInterval(r)}if(e!==this.asyncId||this.paused)return;if("suspended"===this.audioContext.state&&(await this.audioContext.resume(),this.events.emit("canplay"),this.events.emit("playing")),a.done)break;const{buffer:s,timestamp:n}=a.value,o=this.audioContext.createBufferSource();o.buffer=s,o.connect(this.gainNode),o.playbackRate.value=this.playbackRate;const c=this.audioContextStartTime+(n-this.playbackTimeAtStart)/this.playbackRate,l=c+s.duration/this.playbackRate;l>this.latestScheduledEndTime&&(this.latestScheduledEndTime=l),c>=this.audioContext.currentTime?o.start(c):o.start(this.audioContext.currentTime,(this.audioContext.currentTime-c)*this.playbackRate),this.queuedNodes.add(o),o.onended=()=>this.queuedNodes.delete(o)}}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.audioContextStartTime,this.paused=!1;const e=++this.asyncId;this.runIterator(e)}pause(){this.paused||(this.playbackTimeAtStart=this.currentTime,this.paused=!0,this.stopIterator(),this.stopQueuedNodes())}async seek(e){this.playbackTimeAtStart=Math.max(0,e),this.audioContextStartTime=this.audioContext.currentTime,this.latestScheduledEndTime=this.audioContextStartTime;const t=++this.asyncId;this.paused||this.runIterator(t)}setVolume(e,t){this.volume=e,this.muted=t,this.updateGain()}setPlaybackRate(e){if(e!==this.playbackRate&&(this.paused||(this.playbackTimeAtStart=this.currentTime,this.audioContextStartTime=this.audioContext.currentTime),this.playbackRate=e,!this.paused)){const e=++this.asyncId;this.runIterator(e)}}destroy(){this.asyncId++,this.pause(),this.audioContext?.close(),this.audioContext=null,this.input=null,this.audioSink=null}}const Un=/\.m3u8(?:$|[?#])/i;function qn(e){return"string"===typeof e&&Un.test(e)}function Wn(e){const t=function(e){return"string"===typeof e?new ka(e):e instanceof Blob?new ma(e):"undefined"!==typeof ReadableStream&&e instanceof ReadableStream?new ba(e):e??null}(e);return t?new rn({source:t,formats:qn(e)?ss:as}):null}async function Vn({input:e,videoTrack:t,audioTrack:i}){const r=[t,i].filter(Boolean),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}async function Hn(e){return await e.getAverageBitrate()??await e.getBitrate()??0}class Kn{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){if(!this.preflightRange||"string"!==typeof e||qn(e))return!0;try{const t=(await fetch(e,{method:"HEAD"})).headers.get("accept-ranges");return!(!t||"none"===t)||(this.events.emit("error",new Event("RangeNotSupported")),!1)}catch(t){return console.warn("Preflight check failed:",t),!0}}drawPoster(){if(!this.poster||this.posterDrawn)return;const e=new Image;e.onload=()=>{this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.canvas.width=e.naturalWidth||this.canvas.width,this.canvas.height=e.naturalHeight||this.canvas.height,this.ctx.drawImage(e,0,0,this.canvas.width,this.canvas.height),this.posterDrawn=!0},e.src=this.poster}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 zs(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 jn{constructor({canvas:e,ctx:t,events:i,option:r={}}){this.events=i,this.option=r,this.audio=new zn(i),this.video=new Kn({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,i.addEventListener?.("ended",()=>{this.ended=!0,this.paused=!0})}async load(e){const t=++this.loadSeq;this.pause(),this.disposeInput(),this.ended=!1,this.error=null,this.networkState=2,this.readyState=0,setTimeout(()=>this.events.emit("waiting"),0),setTimeout(()=>this.events.emit("loadstart"),0);const i=Number.isFinite(this.option.loadTimeout)?this.option.loadTimeout:0;try{await Promise.race([this.performLoad(e,t),i>0?this.createTimeout(i):new Promise(()=>{})])}catch(r){if(t!==this.loadSeq)return;this.loadSeq++,this.error={code:4,message:r.message},this.networkState=3,this.events.emit("error")}}async performLoad(e,t){if(!(await this.video.preflight(e)))return;const i=Wn(e);if(!i)return this.video.handleNoVideoTrack(),void this.audio.handleNoAudioTrack();const r=await async function(e,t){const i=await e.getPrimaryVideoTrack(),r=i?await i.getPrimaryPairableAudioTrack():await e.getPrimaryAudioTrack(),a=await Vn({input:e,videoTrack:i,audioTrack:r});return{input:e,videoTrack:i,audioTrack:r,duration:a,isLive:!Number.isFinite(a)&&Boolean((i||r)&&await(i||r).isLive()),isHls:qn(t),videoMode:qn(t)?"auto":"manual",audioMode:qn(t)?"auto":"manual"}}(i,e);if(t!==this.loadSeq)return void i.dispose();this.disposeInput(),this.input=i,this.media=r;let a=!r.videoTrack,s=!r.audioTrack;const n=()=>{a&&s&&(this.readyState=1,this.events.emit("loadedmetadata"),this.events.emit("durationchange"),this.events.emit("progress"))};try{if(await Promise.all([this.video.load(r,()=>{t===this.loadSeq&&(a=!0,n())}),this.audio.load(r,()=>{t===this.loadSeq&&(s=!0,n())})]),t!==this.loadSeq)return;this.readyState=4,this.networkState=1,this.events.emit("loadeddata"),this.events.emit("canplay"),this.events.emit("canplaythrough"),this.events.emit("progress")}catch(o){if(t!==this.loadSeq)return;this.error={code:4,message:o.message},this.networkState=3,this.events.emit("error"),console.error("MediaBunny load error:",o)}}createTimeout(e){return new Promise((t,i)=>{setTimeout(()=>i(new Error("Load timeout")),e)})}disposeInput(){this.input?.dispose(),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 Vn(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 Hn(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 Hn(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.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}}class Xn{constructor({art:e,canvas:i,ctx:r,option:a}){this.art=e,this.canvas=i,this.option=a,this.events=new t,this.engine=new jn({canvas:i,ctx:r,events:this.events,option:a}),this._src=null,this._volume=a.volume??.7,this._muted=!!a.muted,this._playbackRate=1,this.engine.setVolume(this._volume,this._muted),this.setupEventForwarding(),a.source?this.src=a.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){const i=this.engine.duration;return!i||Number.isNaN(i)||t<=0?{length:0,start:()=>0,end:()=>0}:{length:1,start:()=>e,end:()=>t}}get paused(){return this.engine.paused}get playing(){return!this.engine.paused&&!this.engine.ended}get ended(){return this.engine.ended}get seeking(){return this.engine.seeking}get readyState(){return this.engine.readyState}get networkState(){return this.engine.networkState}get error(){return this.engine.error}get playbackRate(){return this._playbackRate}set playbackRate(e){const t=Number(e);Number.isNaN(t)||t<=0||(this._playbackRate=t,this.engine.setPlaybackRate(t),this.events.emit("ratechange"))}get volume(){return this._volume}set volume(e){this._volume=function(e,t,i){return Math.max(t,Math.min(i,Number(e)||0))}(e,0,1),this._muted=!1,this.engine.setVolume(this._volume,this._muted),this.events.emit("volumechange")}get muted(){return this._muted}set muted(e){this._muted=!!e,this.engine.setVolume(this._volume,this._muted),this.events.emit("volumechange")}play(){return this.engine.play()}pause(){this.engine.pause()}load(){this._src&&this.engine.load(this._src)}getM3u8State(){return this.engine.getHlsState()}switchM3u8Quality(e){return this.engine.selectHlsQuality(e)}switchM3u8Audio(e){return this.engine.selectHlsAudio(e)}get videoWidth(){return this.engine.videoWidth}get videoHeight(){return this.engine.videoHeight}get poster(){return this.option.poster||""}set poster(e){this.option.poster=e}get autoplay(){return this.option.autoplay||!1}set autoplay(e){}get loop(){return this.option.loop||!1}set loop(e){}get controls(){return!1}set controls(e){}get playsInline(){return!0}set playsInline(e){}get crossOrigin(){return this.option.crossOrigin||""}set crossOrigin(e){}get preload(){return"auto"}set preload(e){}get defaultMuted(){return!1}set defaultMuted(e){}get defaultPlaybackRate(){return 1}set defaultPlaybackRate(e){}canPlayType(e){return"maybe"}getBoundingClientRect(){return this.canvas.getBoundingClientRect()}requestVideoFrameCallback(e){return requestAnimationFrame(t=>{e(t,{presentationTime:this.engine.currentTime,expectedDisplayTime:t+16.6,width:this.engine.videoWidth,height:this.engine.videoHeight,mediaTime:this.engine.currentTime,presentedFrames:0,processingDuration:0,captureTime:t,receiveTime:t,rtpTimestamp:0})})}cancelVideoFrameCallback(e){cancelAnimationFrame(e)}setAttribute(e,t){"src"===e?this.src=t:"autoplay"===e?this.autoplay=t:"loop"===e?this.loop=t:"muted"===e?this.muted=!0:this.canvas.setAttribute(e,t)}destroy(){this.engine.destroy()}}return function(t={}){return i=>{const{constructor:r}=i,{createElement:a}=r.utils,s=a("canvas"),n=s.getContext("2d"),o=new Xn({art:i,canvas:s,ctx:n,option:t});i.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=i.template?.$player;e&&!i.option.autoSize&&Object.assign(s.style,{width:"100%",height:"100%",objectFit:"contain"})}return i.on("resize",u),i.on("video:loadedmetadata",u),function({art:t,shim:i,option:r}){if(r.m3u8)return t.on("video:loadedmetadata",d),t.on("restart",d),{update:d};function a(e){t.controls.cache.has(e)&&t.controls.remove(e)}function s(e){t.setting.find(e)&&t.setting.remove(e)}function n(){a("mediabunny-quality"),s("mediabunny-quality")}function o(){a("mediabunny-audio"),s("mediabunny-audio")}function c(e={}){return e.control||e.setting}async function l(a){const s=r.m3u8?.quality||{};if(!c(s)||!a?.levels.length)return void n();const o=s.auto||"Auto",l=s.title||"Quality",u=s.getName||(e=>e.name||`${e.height}P`),h=a.currentLevel?u(a.currentLevel):o,f=e(a.levels.map(e=>({html:u(e),value:e.id,default:a.currentLevel?.id===e.id})),"html").sort((e,t)=>{const i=a.levels.find(t=>t.id===e.value),r=a.levels.find(e=>e.id===t.value);return(r?.height||0)-(i?.height||0)});f.push({html:o,value:"auto",default:!a.currentLevel});const m=async e=>(await i.switchM3u8Quality(e.value),t.notice.show=`${l}: ${e.html}`,await d(),e.html);s.control&&t.controls.update({name:"mediabunny-quality",position:"right",html:h,style:{padding:"0 10px"},selector:f,onSelect:m}),s.setting&&t.setting.update({name:"mediabunny-quality",tooltip:h,html:l,icon:'',width:200,selector:f,onSelect:m})}async function u(a){const s=r.m3u8?.audio||{};if(!c(s)||!a?.audios.length||a.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=a.currentAudio?u(a.currentAudio):n,f=e(a.audios.map(e=>({html:u(e),value:e.id,default:a.currentAudio?.id===e.id})),"html");f.push({html:n,value:"auto",default:!a.currentAudio});const m=async e=>(await i.switchM3u8Audio(e.value),t.notice.show=`${l}: ${e.html}`,await d(),e.html);s.control&&t.controls.update({name:"mediabunny-audio",position:"right",html:h,style:{padding:"0 10px"},selector:f,onSelect:m}),s.setting&&t.setting.update({name:"mediabunny-audio",tooltip:h,html:l,icon:'',width:200,selector:f,onSelect:m})}async function d(){const e=await i.getM3u8State();if(!e)return n(),void o();await Promise.all([l(e),u(e)])}}({art:i,shim:o,option:t}),i.on("destroy",()=>{delete i.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";function e(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 t{constructor(){this.listeners=new Map}addEventListener(e,t){this.listeners.has(e)||this.listeners.set(e,[]),this.listeners.get(e).push(t)}removeEventListener(e,t){const i=this.listeners.get(e);if(!i)return;const r=i.indexOf(t);r>=0&&i.splice(r,1)}emit(e,t){const i=new Event(e);i.detail=t;const r=this.listeners.get(e);r&&r.forEach(e=>e(i))}}function i(e){if(!e)throw new Error("Assertion failed.")}const r=e=>{const t=(e%360+360)%360;if(0===t||90===t||180===t||270===t)return t;throw new Error(`Invalid rotation ${e}.`)},a=e=>e&&e[e.length-1],s=e=>{let t=0;for(;0===e.readBits(1)&&t<32;)t++;if(t>=32)throw new Error("Invalid exponential-Golomb code.");return(1<{const i=t+1,r=Math.floor(Math.log2(i));e.writeBits(r,0),e.writeBits(1,1),e.writeBits(r,i-2**r)},o=e=>{const t=s(e);return 0===(1&t)?-(t>>1):t+1>>1},c=e=>e.constructor===Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),l=e=>e.constructor===DataView?e:ArrayBuffer.isView(e)?new DataView(e.buffer,e.byteOffset,e.byteLength):new DataView(e),u=new TextDecoder,d=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])),h={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},f=d(h),m={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},p=d(m),g={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},k=d(g),y=e=>!!e&&!!e.primaries&&!!e.transfer&&!!e.matrix&&void 0!==e.fullRange,b={primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0},w=e=>e instanceof ArrayBuffer||"undefined"!==typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e);class T{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 S=/^[0-9a-fA-F]+$/,v=e=>[...e].map(e=>e.toString(16).padStart(2,"0")).join(""),P=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,I=(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},C=(e,t,i)=>{const r=x(e,i(t),i);e.splice(r+1,0,t)},B=()=>{let e,t;return{promise:new Promise((i,r)=>{e=i,t=r}),resolve:e,reject:t}},E=(e,t)=>{const i=e.indexOf(t);-1!==i&&e.splice(i,1)},_=(e,t)=>{for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},R=(e,t)=>{for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},F=e=>{throw new Error(`Unexpected value: ${e}`)},A=(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},D=(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)},M=(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}}),N=(e,t,i)=>Math.max(t,Math.min(i,e)),O="und",L=e=>{const t=Math.round(e);return Math.abs(e/t-1)<10*Number.EPSILON?t:e},z=(e,t)=>Math.round(e/t)*t,U=(e,t)=>Math.round(e*t)/t,q=(e,t)=>Math.floor(e/t)*t,W=e=>{let t=0;for(;0!==e;)e&=e-1,t++;return t},H=/^[a-z]{3}$/,V=e=>H.test(e),j=1e6*(1+Number.EPSILON),K=(e,t)=>{const i={...e,...t};if(e.headers||t.headers){const r=e.headers?X(e.headers):{},a=t.headers?X(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},X=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},$=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(be._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 pe(1e3*e),a())throw n}};class G{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}let Q=null;const Y=()=>null!==Q?Q:Q=!("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 J=null;const Z=()=>null!==J?J:J="undefined"!==typeof navigator&&navigator.userAgent?.includes("Firefox");let ee=null;const te=()=>null!==ee?ee:ee=!("undefined"===typeof navigator||!navigator.vendor?.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.`,re=(async()=>{})().constructor,ae=e=>e instanceof re||e instanceof Promise||"function"===typeof e?.then,se=(e,t)=>-1!==e?e:t,ne=(e,t,i,r)=>e<=r&&i<=t,oe=e=>{const t=atob(e),i=new Uint8Array(t.length);for(let r=0;r{Symbol.dispose??(Symbol.dispose=Symbol("Symbol.dispose"))},le=e=>"number"===typeof e&&!Number.isNaN(e),ue=(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("/")},de=(e,t)=>{let i=0;for(let r=0;r{let i=-1,r=1/0;for(let a=0;a{i(Number.isInteger(e.num)),i(Number.isInteger(e.den)),i(0!==e.den);let t=Math.abs(e.num),r=Math.abs(e.den);for(;0!==r;){const e=t%r;t=r,r=e}const a=t||1;return{num:e.num/a,den:e.den/a}},me=(e,t)=>{if("object"!==typeof e||!e)throw new TypeError(`${t} must be an object.`);if(!Number.isInteger(e.left)||e.left<0)throw new TypeError(`${t}.left must be a non-negative integer.`);if(!Number.isInteger(e.top)||e.top<0)throw new TypeError(`${t}.top must be a non-negative integer.`);if(!Number.isInteger(e.width)||e.width<0)throw new TypeError(`${t}.width must be a non-negative integer.`);if(!Number.isInteger(e.height)||e.height<0)throw new TypeError(`${t}.height must be a non-negative integer.`)},pe=e=>new Promise(t=>setTimeout(t,e));class ge{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 ke,ye;(ye=ke||(ke={}))[ye.Silent=0]="Silent",ye[ye.Errors=1]="Errors",ye[ye.Warnings=2]="Warnings",ye[ye.Info=3]="Info";class be{constructor(){}static get level(){return be._level}static set level(e){if(e!==ke.Silent&&e!==ke.Errors&&e!==ke.Warnings&&e!==ke.Info)throw new TypeError("Invalid log level. Use one of the values of the LogLevel enum.");be._level=e}static get _emitter(){return be._emitterInstance??(be._emitterInstance=new ge)}static on(e,t,i){return be._emitter.on(e,t,i)}static _error(...e){be._emitter._emit("error",e),be._level>=ke.Errors&&console.error(...e)}static _warn(...e){be._emitter._emit("warn",e),be._level>=ke.Warnings&&console.warn(...e)}static _info(...e){be._emitter._emit("info",e),be._level>=ke.Info&&console.info(...e)}}be._level=ke.Info,be._emitterInstance=null;class we{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 Te{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 Se={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1};class ve{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 ve(this.bytes);return e.pos=this.pos,e}}const Pe=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],Ie=[-1,1,2,3,4,5,6,8],xe=e=>{if(!e||e.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");const t=new ve(e),i=Ce(t),{frequencyIndex:r,sampleRate:a}=Be(t),s=t.readBits(4);let n=null;s>=1&&s<=7&&(n=Ie[s]);let o=i,c=!1,l=a;if(5===i||29===i)c=29===i,l=Be(t).sampleRate,o=Ce(t),22===o&&t.skipBits(4);else for(;t.getBitsLeft()>15;){const e=t.pos;if(695===t.readBits(11)){5===Ce(t)&&t.readBits(1)&&(l=Be(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}},Ce=e=>{const t=e.readBits(5);return 31===t?32+e.readBits(6):t},Be=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&c(t.description)[4];return Ne(e,i+1)}return Me(e)},Le=e=>31&e,ze=e=>{const t=[],i=e.length;for(let r=0;r{const t=e.reduce((e,t)=>e+Ue.byteLength+t.byteLength,0),i=new Uint8Array(t);let r=0;for(const a of e)i.set(Ue,r),r+=Ue.byteLength,i.set(a,r),r+=a.byteLength;return i},We=(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:D(e,a,s.byteLength);break;case 4:e.setUint32(a,s.byteLength,!1)}a+=t,r.set(s,a),a+=s.byteLength}return r},He=e=>{try{const t=[],r=[],a=[];for(const i of Me(e)){const s=e.subarray(i.offset,i.offset+i.length),n=Le(s[0]);n===Re.SPS?t.push(s):n===Re.PPS?r.push(s):n===Re.SPS_EXT&&a.push(s)}if(0===t.length)return null;if(0===r.length)return null;const s=t[0],n=Xe(s);i(null!==n);const o=100===n.profileIdc||110===n.profileIdc||122===n.profileIdc||144===n.profileIdc;return{configurationVersion:1,avcProfileIndication:n.profileIdc,profileCompatibility:n.constraintFlags,avcLevelIndication:n.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:t,pictureParameterSets:r,chromaFormat:o?n.chromaFormatIdc:null,bitDepthLumaMinus8:o?n.bitDepthLumaMinus8:null,bitDepthChromaMinus8:o?n.bitDepthChromaMinus8:null,sequenceParameterSetExt:o?a:null}}catch(t){return be._error("Error building AVC Decoder Configuration Record:",t),null}},Ve=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=l(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++),u=[];for(let l=0;l{try{const t=ze(e),r=new ve(t);r.skipBits(1),r.skipBits(2);if(7!==r.readBits(5))return null;const n=r.readAlignedByte(),c=r.readAlignedByte(),l=r.readAlignedByte();s(r);let u=1,d=0,h=0,f=0;if(100===n||110===n||122===n||244===n||44===n||83===n||86===n||118===n||128===n){u=s(r),3===u&&(f=r.readBits(1)),d=s(r),h=s(r),r.skipBits(1);if(r.readBits(1))for(let e=0;e<(3!==u?8:12);e++){if(r.readBits(1)){const t=e<6?16:64;let i=8,a=8;for(let e=0;ee.level>=l)??a(Vt),r=Math.min(Math.floor(i.maxDpbMbs/(e*t)),16);C=r,B=r}else C=0,B=0}return i(null!==B),{emulationUnpreventedBytes:t,profileIdc:n,constraintFlags:c,levelIdc:l,frameMbsOnlyFlag:T,chromaFormatIdc:u,bitDepthLumaMinus8:d,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 be._error("Error parsing AVC SPS:",t),null}},$e=e=>{const t=s(e);e.skipBits(4),e.skipBits(4);for(let i=0;i<=t;i++)s(e),s(e),e.skipBits(1);e.skipBits(5),e.skipBits(5),e.skipBits(5),e.skipBits(5)},Ge=e=>{i(1!==e.bitstreamRestrictionFlag);const t=new Uint8Array(e.emulationUnpreventedBytes.byteLength+64),r=new ve(e.emulationUnpreventedBytes),a=new ve(t);null===e.bitstreamRestrictionFlag?(a.copyBits(e.vuiParametersFlagBitOffset,r),a.writeBits(1,1),a.writeBits(1,0),a.writeBits(1,0),a.writeBits(1,0),a.writeBits(1,0),a.writeBits(1,0),a.writeBits(1,0),a.writeBits(1,0),a.writeBits(1,0)):(i(null!==e.bitstreamRestrictionFlagBitOffset),a.copyBits(e.bitstreamRestrictionFlagBitOffset,r)),a.writeBits(1,1),a.writeBits(1,1),n(a,2),n(a,1),n(a,16),n(a,16),n(a,e.numReorderFrames),n(a,e.maxDecFrameBuffering),a.writeBits(1,1),a.writeBits((8-a.pos%8)%8,0);const s=a.pos/8;return i(Number.isInteger(s)),(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,s))},Qe=(e,t)=>{if(t.description){const i=3&c(t.description)[21];return Ne(e,i+1)}return Me(e)},Ye=e=>e>>1&63,Je=e=>{try{const t=new ve(ze(e));t.skipBits(16),t.readBits(4);const i=t.readBits(3),r=t.readBits(1),{general_profile_space:a,general_tier_flag:n,general_profile_idc:o,general_profile_compatibility_flags:c,general_constraint_indicator_flags:l,general_level_idc:u}=et(t,i);s(t);const d=s(t);let h=0;3===d&&(h=t.readBits(1));const f=s(t),m=s(t);let p=f,g=m;if(t.readBits(1)){const e=s(t),i=s(t),r=s(t),a=s(t);let n=1,o=1;const c=0===h?d:0;1===c?(n=2,o=2):2===c&&(n=2,o=1),p-=(e+i)*n,g-=(r+a)*o}const k=s(t),y=s(t);s(t);const b=t.readBits(1);let w=0;for(let e=b?0:i;e<=i;e++)s(t),w=s(t),s(t);s(t),s(t),s(t),s(t),s(t),s(t),t.readBits(1)&&t.readBits(1)&&tt(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(4),t.skipBits(4),s(t),s(t),t.skipBits(1));const T=s(t);if(it(t,T),t.readBits(1)){const e=s(t);for(let i=0;i{try{const t=[],i=[],r=[],a=[];for(const s of Me(e)){const n=e.subarray(s.offset,s.offset+s.length),o=Ye(n[0]);o===Ae.VPS_NUT?t.push(n):o===Ae.SPS_NUT?i.push(n):o===Ae.PPS_NUT?r.push(n):o!==Ae.PREFIX_SEI_NUT&&o!==Ae.SUFFIX_SEI_NUT||a.push(n)}if(0===i.length||0===r.length)return null;const n=Je(i[0]);if(!n)return null;let c=0;if(r.length>0){const e=r[0],t=new ve(ze(e));t.skipBits(16),s(t),s(t),t.skipBits(1),t.skipBits(1),t.skipBits(3),t.skipBits(1),t.skipBits(1),s(t),s(t),o(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&s(t),o(t),o(t),t.skipBits(1),t.skipBits(1),t.skipBits(1),t.skipBits(1);const i=t.readBits(1),a=t.readBits(1);c=i||a?i&&!a?2:!i&&a?3:0:0}const l=[...t.length?[{arrayCompleteness:1,nalUnitType:Ae.VPS_NUT,nalUnits:t}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:Ae.SPS_NUT,nalUnits:i}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:Ae.PPS_NUT,nalUnits:r}]:[],...a.length?[{arrayCompleteness:1,nalUnitType:Ye(a[0][0]),nalUnits:a}]:[]];return{configurationVersion:1,generalProfileSpace:n.generalProfileSpace,generalTierFlag:n.generalTierFlag,generalProfileIdc:n.generalProfileIdc,generalProfileCompatibilityFlags:n.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:n.generalConstraintIndicatorFlags,generalLevelIdc:n.generalLevelIdc,minSpatialSegmentationIdc:n.minSpatialSegmentationIdc,parallelismType:c,chromaFormatIdc:n.chromaFormatIdc,bitDepthLumaMinus8:n.bitDepthLumaMinus8,bitDepthChromaMinus8:n.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:n.spsMaxSubLayersMinus1+1,temporalIdNested:n.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:l}}catch(t){return be._error("Error building HEVC Decoder Configuration Record:",t),null}},et=(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&&o(e);for(let t=0;t{const i=[];for(let r=0;r{let a=0,n=0,o=0;if(0!==t&&(n=e.readBits(1)),n){if(t===i){o=t-(s(e)+1)}else o=t-1;e.readBits(1),s(e);const n=r[o]??0;for(let t=0;t<=n;t++){e.readBits(1)||e.readBits(1)}a=r[o]}else{const t=s(e),i=s(e);for(let r=0;r{let i=2,r=2,a=2,n=0,o=0,c={num:1,den:1};if(e.readBits(1)){const t=e.readBits(8);if(255===t)c={num:e.readBits(16),den:e.readBits(16)};else{const e=Ke[t];e&&(c=e)}}return e.readBits(1)&&e.readBits(1),e.readBits(1)&&(e.readBits(3),n=e.readBits(1),e.readBits(1)&&(i=e.readBits(8),r=e.readBits(8),a=e.readBits(8))),e.readBits(1)&&(s(e),s(e)),e.readBits(1),e.readBits(1),e.readBits(1),e.readBits(1)&&(s(e),s(e),s(e),s(e)),e.readBits(1)&&(e.readBits(32),e.readBits(32),e.readBits(1)&&s(e),e.readBits(1)&&st(e,!0,t)),e.readBits(1)&&(e.readBits(1),e.readBits(1),e.readBits(1),o=s(e),s(e),s(e),s(e),s(e)),{pixelAspectRatio:c,colourPrimaries:i,transferCharacteristics:r,matrixCoefficients:a,fullRangeFlag:n,minSpatialSegmentationIdc:o}},st=(e,t,i)=>{let r=!1,a=!1,n=!1;r=1===e.readBits(1),a=1===e.readBits(1),(r||a)&&(n=1===e.readBits(1),n&&(e.readBits(8),e.readBits(5),e.readBits(1),e.readBits(5)),e.readBits(4),e.readBits(4),n&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5));for(let o=0;o<=i;o++){let t=!0;1===e.readBits(1)||(t=1===e.readBits(1));let i=!1;t?s(e):i=1===e.readBits(1);let o=1;if(!i){o=s(e)+1}r&&nt(e,o,n),a&&nt(e,o,n)}},nt=(e,t,i)=>{for(let r=0;r{const i=new Set;let r=ot.audAllowed;for(const s of Qe(e,t)){if(r===ot.noMoreDataAllowed){i.add(s.offset);continue}const t=Ye(e[s.offset]);if(r===ot.eoBitstreamAllowed&&37!==t){i.add(s.offset);continue}let a=!1;35===t?r>ot.audAllowed?a=!0:r=ot.beforeFirstVcl:t<=31?r>ot.afterFirstVcl?a=!0:r=ot.afterFirstVcl:36===t?r!==ot.afterFirstVcl?a=!0:r=ot.eoBitstreamAllowed:37===t?r=41&&t<=44||t>=48&&t<=55?r>ot.beforeFirstVcl?a=!0:r=ot.beforeFirstVcl:(38===t||40===t||t>=45&&t<=47||t>=56&&t<=63)&&r{if(t.description){const i=3&c(t.description)[21];return We(e,i+1)}return qe(e)})(a,t)},ut={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=>{const t=new ve(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 s=8;if(r>=2){s=t.readBits(1)?12:10}const n=t.readBits(3);let o=0,c=0;if(7!==n){if(c=t.readBits(1),1===r||3===r){const e=t.readBits(1),i=t.readBits(1);o=e||i?e&&!i?2:1:3,t.skipBits(1)}else o=1}else o=3,c=1;const l=(t.readBits(16)+1)*(t.readBits(16)+1);let u=a(jt).level;for(const a of jt)if(l<=a.maxPictureSize){u=a.level;break}const d=ut[n];return{profile:r,level:u,bitDepth:s,chromaSubsampling:o,videoFullRangeFlag:c,colourPrimaries:d?.colourPrimaries??2,transferCharacteristics:d?.transferCharacteristics??2,matrixCoefficients:d?.matrixCoefficients??2}},ht=function*(e){const t=new ve(e),r=()=>{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 a=t.readBits(4),s=t.readBits(1),n=t.readBits(1);let o;if(t.skipBits(1),s&&t.skipBits(8),n){const e=r();if(null===e)return;o=e}else o=Math.floor(t.getBitsLeft()/8);i(t.pos%8===0),yield{type:a,data:e.subarray(t.pos/8,t.pos/8+o)},t.skipBits(8*o)}},ft=e=>{for(const{type:t,data:i}of ht(e)){if(1!==t)continue;const e=new ve(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},mt=e=>{if(e.length<36)return null;const t=l(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)}},pt=[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],gt=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}},kt=(e,t,r)=>{switch(e){case"avc":for(const e of Oe(r,t)){const t=r[e.offset],i=Le(t);if(i>=Re.NON_IDR_SLICE&&i<=Re.SLICE_DPC)return"delta";if(i===Re.IDR)return"key";if(i===Re.SEI&&!te()){const t=r.subarray(e.offset,e.offset+e.length),i=ze(t);let a=1;do{let e=0;for(;;){const t=i[a++];if(void 0===t)break;if(e+=t,t<255)break}let t=0;for(;;){const e=i[a++];if(void 0===e)break;if(t+=e,e<255)break}if(e===6){const e=new ve(i);e.pos=8*a;const t=s(e),r=e.readBits(1);if(0===t&&1===r)return"key"}a+=t}while(a{var i,r;const a=l(e);let s=0;const n=a.getUint32(s,!0);s+=4;const o=u.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 d=0;d0&&(t.trackNumber??(t.trackNumber=i)),r&&Number.isInteger(r)&&r>0&&(t.tracksTotal??(t.tracksTotal=r))}break;case"TRACKTOTAL":{const e=Number.parseInt(d,10);Number.isInteger(e)&&e>0&&(t.tracksTotal??(t.tracksTotal=e))}break;case"DISCNUMBER":{const e=d.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(d,10);Number.isInteger(e)&&e>0&&(t.discsTotal??(t.discsTotal=e))}break;case"DATE":{const e=new Date(d);Number.isNaN(e.getTime())||(t.date??(t.date=e))}break;case"GENRE":t.genre??(t.genre=d);break;case"METADATA_BLOCK_PICTURE":{const e=oe(d),i=l(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=u.decode(e.subarray(12+a,12+a+n)),c=i.getUint32(a+n+28),h=e.subarray(a+n+32,a+n+32+c);t.images??(t.images=[]),t.images.push({data:h,mimeType:s,kind:3===r?"coverFront":4===r?"coverBack":"unknown",name:void 0,description:o||void 0})}}}},Tt=[2,1,2,3,3,4,4,5],St=e=>{if(e.length<7)return null;if(11!==e[0]||119!==e[1])return null;const t=new ve(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)}},vt=[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],Pt=[1,2,3,6],It=e=>{if(e.length<6)return null;if(11!==e[0]||119!==e[1])return null;const t=new ve(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=Pt[s];let d;d=a<3?Ee[a]/1e3:_e[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}]}},xt=e=>{const t=e.substreams[0];return i(t),t.fscod<3?Ee[t.fscod]:null!==t.fscod2&&t.fscod2<3?_e[t.fscod2]:null},Ct=e=>{const t=e.substreams[0];i(t);let r=Tt[t.acmod]+t.lfeon;if(t.numDepSub>0){const e=[2,2,1,1,2,2,2,1,1];for(let i=0;i<9;i++)t.chanLoc&1<<8-i&&(r+=e[i])}return r},Bt=[0,8e3,16e3,32e3,0,0,11025,22050,44100,0,0,12e3,24e3,48e3,96e3,192e3],Et=[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],_t=[16,16,20,20,0,24,24,0],Rt=[1,2,2,2,2,3,3,4,4,5,6,6,6,7,8,8],Ft=[1,2,2,2,2,3,18,19,6,7,518,323,83,519,582,535],At=[32e3,44100,48e3,0],Dt=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],Mt=[512,1024,2048,4096],Nt=e=>{const t=Lt(e),i=l(e);let r=t?4*Math.ceil(t.frameSize/4):0,a=null;for(;r+4<=e.length&&1683496997===i.getUint32(r);){const t=zt(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}},Ot=e=>{const t=Nt(e);return t?.core?t.hasExtensions?"dtsh":"dtsc":null},Lt=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 ve(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>=Rt.length)return null;const n=Bt[t.readBits(4)];if(0===n)return null;const o=Et[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=_t[t.readBits(3)];if(0===l)return null;const u=0!==c;return{frameSize:a,sampleRate:n,numberOfChannels:Rt[s]+(u?1:0),sampleCount:32*r,channelLayout:Ft[s]|(u?8:0),amode:s,lfePresent:u,bitRate:o,pcmResolution:l}},zt=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 ve(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=At[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}}},Ut=e=>W(e)+W(44646&e),qt=["avc","hevc","vp9","av1","vp8","prores"],Wt=["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"],Ht=["aac","opus","mp3","vorbis","flac","ac3","eac3","dts",...Wt],Vt=[{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}],Kt=".01.01.01.01.00",Xt=".0.110.01.01.01.0",$t=["ap4x","ap4h","apch","apcn","apcs","apco"],Gt=["dtsc","dtsh","dtsl","dtse"],Qt=e=>{const{codec:t,codecDescription:r,colorSpace:s,avcCodecInfo:n,hevcCodecInfo:o,vp9CodecInfo:c,av1CodecInfo:u,proresFormat:d}=e;if("avc"===t){if(i(null!==e.avcType),n){const t=new Uint8Array([n.avcProfileIndication,n.profileCompatibility,n.avcLevelIndication]);return`avc${e.avcType}.${v(t)}`}if(!r||r.byteLength<4)throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${e.avcType}.${v(r.subarray(1,4))}`}if("hevc"===t){let e,t,i,a,s,n;if(o)e=o.generalProfileSpace,t=o.generalProfileIdc,i=P(o.generalProfileCompatibilityFlags),a=o.generalTierFlag,s=o.generalLevelIdc,n=[...o.generalConstraintIndicatorFlags];else{if(!r||r.byteLength<23)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");const o=l(r),c=o.getUint8(1);e=c>>6&3,t=31&c,i=P(o.getUint32(2)),a=c>>5&1,s=o.getUint8(12),n=[];for(let e=0;e<6;e++)n.push(o.getUint8(6+e))}let c="hev1.";for(c+=["","A","B","C"][e]+t,c+=".",c+=i.toString(16).toUpperCase(),c+=".",c+=0===a?"L":"H",c+=s;n.length>0&&0===n[n.length-1];)n.pop();return n.length>0&&(c+=".",c+=n.map(e=>e.toString(16).toUpperCase()).join(".")),c}if("vp8"===t)return"vp8";if("vp9"===t){if(!c){const t=e.width*e.height;let i=a(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.${c.profile.toString().padStart(2,"0")}.${c.level.toString().padStart(2,"0")}.${c.bitDepth.toString().padStart(2,"0")}.${c.chromaSubsampling.toString().padStart(2,"0")}`;return t+=`.${c.colourPrimaries.toString().padStart(2,"0")}.${c.transferCharacteristics.toString().padStart(2,"0")}.${c.matrixCoefficients.toString().padStart(2,"0")}.${c.videoFullRangeFlag.toString().padStart(2,"0")}`,t.endsWith(Kt)&&(t=t.slice(0,-15)),t}if("av1"===t){if(!u){const t=e.width*e.height;let i=a(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=u.profile,i=u.level.toString().padStart(2,"0"),r=u.tier?"H":"M",n=u.bitDepth.toString().padStart(2,"0"),o=u.monochrome?"1":"0",c=100*u.chromaSubsamplingX+10*u.chromaSubsamplingY+1*(u.chromaSubsamplingX&&u.chromaSubsamplingY?u.chromaSamplePosition:0),l=s?.primaries?h[s.primaries]:1,d=s?.transfer?m[s.transfer]:1,f=s?.matrix?g[s.matrix]:1,p=s?.fullRange?1:0;let k=`av01.${t}.${i}${r}.${n}`;return k+=`.${o}.${c.toString().padStart(3,"0")}`,k+=`.${l.toString().padStart(2,"0")}`,k+=`.${d.toString().padStart(2,"0")}`,k+=`.${f.toString().padStart(2,"0")}`,k+=`.${p}`,k.endsWith(Xt)&&(k=k.slice(0,-17)),k}if("prores"===t)return d??"apch";throw null!==t&&F(t),new TypeError(`Unhandled codec '${t}'.`)},Yt=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=Xe(t);if(e)return{primaries:f[e.colourPrimaries],transfer:p[e.transferCharacteristics],matrix:k[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case"hevc":{let t=e.hevcCodecInfo?.arrays.find(e=>e.nalUnitType===Ae.SPS_NUT)?.nalUnits[0];if(!t&&e.codecDescription&&(t=(e=>{try{const t=l(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 u=e.subarray(i,i+6);i+=6;const d=t.getUint8(i++),h=(15&t.getUint8(i++))<<8|t.getUint8(i++),f=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 l=0;l>7&1,s=63&r,n=t.getUint16(i,!1);i+=2;const o=[];for(let c=0;ce.nalUnitType===Ae.SPS_NUT)?.nalUnits[0]),t){const e=Je(t);if(e)return{primaries:f[e.colourPrimaries],transfer:p[e.transferCharacteristics],matrix:k[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case"vp8":break;case"vp9":if(e.vp9CodecInfo)return{primaries:f[e.vp9CodecInfo.colourPrimaries],transfer:p[e.vp9CodecInfo.transferCharacteristics],matrix:k[e.vp9CodecInfo.matrixCoefficients],fullRange:!!e.vp9CodecInfo.videoFullRangeFlag};break;case"av1":if(e.av1CodecInfo)return{primaries:f[e.av1CodecInfo.colourPrimaries],transfer:p[e.av1CodecInfo.transferCharacteristics],matrix:k[e.av1CodecInfo.matrixCoefficients],fullRange:!!e.av1CodecInfo.videoFullRangeFlag};break;case"prores":if(e.proresCodecInfo)return{primaries:f[e.proresCodecInfo.colourPrimaries],transfer:p[e.proresCodecInfo.transferCharacteristics],matrix:k[e.proresCodecInfo.matrixCoefficients],fullRange:e.proresCodecInfo.fullRange}}return{primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0}},Jt=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=xe(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&&Wt.includes(t))return t;throw new TypeError(`Unhandled codec '${t}'.`)},Zt=48e3,ei=/^pcm-([usf])(\d+)(be)?$/,ti=e=>{if(i(Wt.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=ei.exec(e);let r;i(t),r="u"===t[1]?"unsigned":"s"===t[1]?"signed":"float";return{dataType:r,sampleSize:Number(t[2])/8,littleEndian:"be"!==t[3],silentValue:"pcm-u8"===e?128: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":$t.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":Gt.includes(e)?"dts":"ulaw"===e?"ulaw":"alaw"===e?"alaw":ei.test(e)?e:"webvtt"===e?"webvtt":null,ri=[44100,48e3,32e3],ai=[-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],si=1483304551,ni=1231971951,oi=(e,t)=>3===e?3===t?21:36:3===t?13:21,ci=(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=ai[16*n*4+16*l+(a>>4&15)];if(-1===g)return{header:null,bytesAdvanced:1};const k=1e3*g,y=ri[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 ui,di;(di=ui||(ui={}))[di.FrameCount=1]="FrameCount",di[di.FileSize=2]="FileSize",di[di.Toc=4]="Toc";const hi=e=>3===e?1:2;class fi{constructor(e){this.input=e}dispose(){}}const mi=new Uint8Array(0);class pi{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===mi&&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===mi}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 pi(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 pi(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 gi=e=>{const t=l(e);let i=0;const r=t.getUint8(i);i+=1,i+=3;const a=v(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=To(e);const i=_o(e,4);let r=8;1===t&&(t=Io(e),r=16);const a=t-r;return a<0?null:{name:i,totalSize:t,headerSize:r,contentSize:a}},bi=e=>vo(e)/65536,wi=e=>vo(e)/1073741824,Ti=e=>{let t=0;for(let i=0;i<4;i++){t<<=7;const i=po(e);if(t|=127&i,0===(128&i))break}return t},Si=e=>{let t=ko(e);return e.skip(2),t=Math.min(t,e.remainingLength),u.decode(mo(e,t))},vi=e=>{const t=yi(e);if(!t||"data"!==t.name)return null;if(e.remainingLength<8)return null;const i=To(e);e.skip(4);const r=mo(e,t.contentSize-8);switch(i){case 1:return u.decode(r);case 2:return new TextDecoder("utf-16be").decode(r);case 13:return new we(r,"image/jpeg");case 14:return new we(r,"image/png");case 27:return new we(r,"image/bmp");default:return r}},Pi=16,Ii=new Uint32Array(256),xi=new Uint32Array(256),Ci=new Uint32Array(256),Bi=new Uint32Array(256),Ei=new Uint32Array(256),_i=new Uint32Array(256),Ri=new Uint32Array(10);let Fi=!1;class Ai{constructor(){this.roundkey=new Uint32Array(44),this.iv=new Uint32Array(Pi/Uint32Array.BYTES_PER_ELEMENT),this.in=new Uint8Array(Pi),this.out=new Uint8Array(Pi),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),Fi||(()=>{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);Ii[s]=t<<24|t<<16|t<<8|t,_i[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);xi[s]=a,Ci[s]=a>>>8|a<<24,Bi[s]=a>>>16|a<<16,Ei[s]=a>>>24|a<<8}let a=1;for(let s=0;s<10;s++)Ri[s]=a<<24,a=a<<1^(128&a?283:0);Fi=!0})();const r=new DataView(e.buffer,e.byteOffset,e.byteLength),a=new DataView(t.buffer,t.byteOffset,t.byteLength);this.roundkey[0]=r.getUint32(0,!1),this.roundkey[1]=r.getUint32(4,!1),this.roundkey[2]=r.getUint32(8,!1),this.roundkey[3]=r.getUint32(12,!1),this.iv[0]=a.getUint32(0,!1),this.iv[1]=a.getUint32(4,!1),this.iv[2]=a.getUint32(8,!1),this.iv[3]=a.getUint32(12,!1);for(let i=4;i<44;i+=4){const e=this.roundkey[i-1];this.roundkey[i]=this.roundkey[i-4]^4278190080&Ii[e>>>16&255]^16711680&Ii[e>>>8&255]^65280&Ii[e>>>0&255]^255&Ii[e>>>24&255]^Ri[i/4-1],this.roundkey[i+1]=this.roundkey[i-3]^this.roundkey[i],this.roundkey[i+2]=this.roundkey[i-2]^this.roundkey[i+1],this.roundkey[i+3]=this.roundkey[i-1]^this.roundkey[i+2]}for(let i=0,s=40;i>>24&255]]^Ci[255&Ii[t>>>16&255]]^Bi[255&Ii[t>>>8&255]]^Ei[255&Ii[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=xi[e>>>24]^Ci[r>>>16&255]^Bi[i>>>8&255]^Ei[255&t]^this.roundkey[a],l=xi[t>>>24]^Ci[e>>>16&255]^Bi[r>>>8&255]^Ei[255&i]^this.roundkey[a+1],u=xi[i>>>24]^Ci[t>>>16&255]^Bi[e>>>8&255]^Ei[255&r]^this.roundkey[a+2],d=xi[r>>>24]^Ci[i>>>16&255]^Bi[t>>>8&255]^Ei[255&e]^this.roundkey[a+3],e=c,t=l,i=u,r=d}const h=4278190080&_i[e>>>24&255]^16711680&_i[r>>>16&255]^65280&_i[i>>>8&255]^255&_i[t>>>0&255]^this.roundkey[40],f=4278190080&_i[t>>>24&255]^16711680&_i[e>>>16&255]^65280&_i[r>>>8&255]^255&_i[i>>>0&255]^this.roundkey[41],m=4278190080&_i[i>>>24&255]^16711680&_i[t>>>16&255]^65280&_i[e>>>8&255]^255&_i[r>>>0&255]^this.roundkey[42],p=4278190080&_i[r>>>24&255]^16711680&_i[i>>>16&255]^65280&_i[t>>>8&255]^255&_i[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 Di extends fi{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,r=!1;for(;;){let i=this.reader.requestSliceRange(e,8,16);if(ae(i)&&(i=await i),!i)break;const a=e,s=yi(i);if(!s)break;if("ftyp"===s.name||"styp"===s.name){const e=_o(i,4);this.isQuickTime="qt "===e}else{if("moov"===s.name){let e=this.reader.requestSlice(i.filePos,s.contentSize);if(ae(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,r=!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,r=!0;break}}e=a+s.totalSize}if(!r&&this.input._initInput&&await this.copyMetadataFromInitInput(this.input._initInput),t){i(null!==this.reader.fileSize);let e=this.reader.requestSlice(this.reader.fileSize-4,4);ae(e)&&(e=await e),i(e);const t=To(e),r=this.reader.fileSize-t;if(r>=0&&r<=this.reader.fileSize-16){let e=this.reader.requestSliceRange(r,8,16);if(ae(e)&&(e=await e),e){const t=yi(e);if(t&&"mfra"===t.name){let i=this.reader.requestSlice(e.filePos,t.contentSize);ae(i)&&(i=await i),i&&this.readContiguousBoxes(i)}}}}})())}async copyMetadataFromInitInput(e){const t=await e._getDemuxer();if(t.constructor!==Di)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 r of t.tracks){const e={id:r.id,demuxer:this,trackBacking:null,disposition:r.disposition,timescale:r.timescale,durationInMediaTimescale:r.durationInMediaTimescale,durationInMovieTimescale:r.durationInMovieTimescale,rotation:r.rotation,internalCodecId:r.internalCodecId,name:r.name,languageCode:r.languageCode,sampleTableByteOffset:null,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:r.editListPreviousSegmentDurations,editListOffset:r.editListOffset,encryptionInfo:r.encryptionInfo,encryptionAuxInfo:null,frmaCodecString:null,info:r.info};if(r.trackBacking)if(i(e.info),"video"===e.info.type&&-1!==e.info.width){const t=e;e.trackBacking=new Ni(t),this.tracks.push(e)}else if("audio"===e.info.type&&-1!==e.info.numberOfChannels){const t=e;e.trackBacking=new Oi(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;i(this.moovSlice);const r=this.moovSlice.slice(e.sampleTableByteOffset);this.currentTrack=e,this.traverseBox(r),this.currentTrack=null;if("audio"===e.info?.type&&e.info.codec&&Wt.includes(e.info.codec)&&0===t.sampleCompositionTimeOffsets.length){i("audio"===e.info?.type);const r=ti(e.info.codec),s=[],n=[];for(let i=0;ie.startIndex),d=t.sampleTimingEntries[u],h=x(t.sampleTimingEntries,l,e=>e.startIndex),f=t.sampleTimingEntries[h],m=d.startDecodeTimestamp+(c-d.startIndex)*d.delta,p=f.startDecodeTimestamp+(l-f.startIndex)*f.delta-m,g=a(s);g&&g.delta===p?g.count++:s.push({startIndex:o.startChunkIndex+i,startDecodeTimestamp:m,count:1,delta:p});const k=o.samplesPerChunk*r.sampleSize*e.info.numberOfChannels;n.push(k)}o.startSampleIndex=o.startChunkIndex,o.samplesPerChunk=1}t.sampleTimingEntries=s,t.sampleSizes=n}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===s.moofOffset);if(r)Wi(i,r.timestamp);else{const e=x(t,s.moofOffset-1,e=>e.moofOffset);if(-1!==e){const r=t[e];Wi(i,r.endTimestamp)}}i.startTimestampIsFinal=!0}const r=x(t,i.startTimestamp,e=>e.startTimestamp);if(-1!==r&&t[r].moofOffset===s.moofOffset||t.splice(r+1,0,{moofOffset:s.moofOffset,startTimestamp:i.startTimestamp,endTimestamp:i.endTimestamp}),i.encryptionAuxInfo&&e.encryptionInfo){const t=await Ki(this.reader,e.encryptionInfo,i.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;V(t.languageCode)||(t.languageCode=O)}}break;case"hdlr":{const t=this.currentTrack;if(!t)break;e.skip(8);const i=_o(e,4);"vide"===i?t.info={type:"video",width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:{...b},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=X,this.readContiguousBoxes(e.slice(G,$.contentSize))}break;case"stsd":{const t=this.currentTrack;if(!t)break;if(null===t.info||t.sampleTable)break;const i=po(e);e.skip(3);const r=To(e);for(let a=0;a0&&(1===n?(e.skip(4),c=8*To(e),e.skip(8)):2===n&&(e.skip(4),l=Eo(e),o=To(e),e.skip(4),c=To(e),u=To(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=Zt;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(Gt.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":(be._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":(be._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":(be._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":(be._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":(be._warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null):32===e?t.info.codec="pcm-f32be":64===e?t.info.codec="pcm-f64be":(be._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!==po(e),t.encryptionInfo.defaultPerSampleIvSize=po(e),t.encryptionInfo.defaultKid=v(mo(e,16)),t.encryptionInfo.defaultIsProtected&&0===t.encryptionInfo.defaultPerSampleIvSize){const i=po(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(i(t.info),0===$.contentSize)break;t.info.codecDescription=mo(e,$.contentSize)}break;case"hvcC":{const t=this.currentTrack;if(!t)break;if(i(t.info),0===$.contentSize)break;t.info.codecDescription=mo(e,$.contentSize)}break;case"vpcC":{const t=this.currentTrack;if(!t)break;i("video"===t.info?.type),e.skip(4);const r=po(e),a=po(e),s=po(e),n=s>>4,o=s>>1&7,c=1&s,l=po(e),u=po(e),d=po(e);t.info.vp9CodecInfo={profile:r,level:a,bitDepth:n,chromaSubsampling:o,videoFullRangeFlag:c,colourPrimaries:l,transferCharacteristics:u,matrixCoefficients:d}}break;case"av1C":{const t=this.currentTrack;if(!t)break;i("video"===t.info?.type),e.skip(1);const r=po(e),a=r>>5,s=31&r,n=po(e),o=n>>7,c=n>>6&1,l=n>>4&1,u=n>>3&1,d=n>>2&1,h=3&n,f=2===a&&c?n>>5&1?12:10:c?10:8;e.skip(1);const m=mo(e,$.contentSize-4),p=ft(m);t.info.av1CodecInfo={profile:a,level:s,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;i("video"===t.info?.type);const r=_o(e,4);if("nclx"!==r&&"nclc"!==r)break;const a=ko(e),s=ko(e),n=ko(e);let o;"nclx"===r&&(o=Boolean(128&po(e))),t.info.colorSpace={primaries:f[a],transfer:p[s],matrix:k[n],fullRange:o}}break;case"pasp":{const t=this.currentTrack;if(!t)break;i("video"===t.info?.type);const r=To(e),a=To(e);r>0&&a>0&&(r>a?t.info.squarePixelWidth=Math.round(t.info.width*r/a):t.info.squarePixelHeight=Math.round(t.info.height*a/r))}break;case"esds":{const t=this.currentTrack;if(!t||"audio"!==t.info?.type)break;e.skip(4);i(3===po(e)),Ti(e),e.skip(2);const r=po(e),a=0!==(64&r),s=0!==(32&r);if(0!==(128&r)&&e.skip(2),a){const t=po(e);e.skip(t)}s&&e.skip(2);i(4===po(e));const n=Ti(e),o=e.filePos,c=po(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":be._warn(`Unsupported audio codec (objectTypeIndication ${c}) - discarding track.`),e.skip(12),n>e.filePos-o){i(5===po(e));const r=Ti(e);if(t.info.codecDescription=mo(e,r),"aac"===t.info.codec){const e=xe(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"===t.info?.type),t.info.pcmLittleEndian=!!(255&ko(e))}break;case"pcmC":{const t=this.currentTrack;if(!t)break;i("audio"===t.info?.type),e.skip(4);const r=po(e);t.info.pcmLittleEndian=Boolean(1&r),t.info.pcmSampleSize=po(e)}break;case"dOps":{const t=this.currentTrack;if(!t)break;i("audio"===t.info?.type),e.skip(1);const r=po(e),a=ko(e),s=To(e),n=bo(e),o=po(e);let c;c=0!==o?mo(e,2+r):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,r),u.setUint16(10,a,!0),u.setUint32(12,s,!0),u.setInt16(16,n,!0),u.setUint8(18,o),l.set(c,19),t.info.codecDescription=l,t.info.numberOfChannels=r}break;case"dfLa":{const t=this.currentTrack;if(!t)break;i("audio"===t.info?.type),e.skip(4);const r=127,a=128,s=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(i&a)break}const n=e.filePos;e.filePos=s;const o=mo(e,n-s),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;i("audio"===t.info?.type);const r=mo(e,3),a=new ve(r),s=a.readBits(2);a.skipBits(8);const n=a.readBits(3),o=a.readBits(1);s<3&&(t.info.sampleRate=Ee[s]),t.info.numberOfChannels=Tt[n]+o}break;case"dec3":{const t=this.currentTrack;if(!t)break;i("audio"===t.info?.type);const r=(e=>{if(e.length<2)return null;const t=new ve(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}})(mo(e,$.contentSize));if(!r){be._warn("Invalid dec3 box contents, ignoring.");break}const a=xt(r);null!==a&&(t.info.sampleRate=a),t.info.numberOfChannels=Ct(r)}break;case"ddts":{const t=this.currentTrack;if(!t)break;i("audio"===t.info?.type);const r=(e=>{if(e.length<20)return null;const t=l(e),i=t.getUint32(0);if(0===i)return null;const r=new ve(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=Ut(o):ne.id===i);if(!r)break;const a=To(e),s=(12&a)>>2,n=3&a,o=[po,ko,yo,To],c=o[(48&a)>>4],l=o[s],u=o[n],d=To(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 i=0;ie.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},r?d.currentFragmentState.baseDataOffset=Io(e):l&&(d.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),a&&(d.currentFragmentState.sampleDescriptionIndex=To(e)),s&&(d.currentFragmentState.defaultSampleDuration=To(e)),n&&(d.currentFragmentState.defaultSampleSize=To(e)),o&&(d.currentFragmentState.defaultSampleFlags=To(e)),c&&(d.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{const t=this.currentTrack;if(!t)break;i(t.currentFragmentState);const r=po(e);e.skip(3);const a=0===r?To(e):Io(e);t.currentFragmentState.startTimestamp=a}break;case"trun":{const t=this.currentTrack;if(!t)break;i(this.currentFragment),i(t.currentFragmentState);const r=po(e),a=yo(e),s=Boolean(1&a),n=Boolean(4&a),o=Boolean(256&a),c=Boolean(512&a),l=Boolean(1024&a),u=Boolean(2048&a),d=To(e);let h=null;s&&(h=vo(e));let f,m=null;n&&(m=To(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=mo(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=po(e);if(1&yo(e)){const i=_o(e,4),r=To(e);if(i!==t.encryptionInfo.scheme||0!==r)break}const r=To(e);if(0===r)break;r>1&&be._warn("Multiple saio entries are not supported; using the first offset only.");let a=0===i?To(e):Number(Io(e));this.currentFragment&&(a+=this.currentFragment.moofOffset);ji(t).offset=a}break;case"senc":{const t=this.currentTrack;if(!t||!t.encryptionInfo)break;i(this.currentFragment);const r=this.currentFragment.trackData.get(t.id);if(!r)break;e.skip(1);const a=yo(e),s=Boolean(2&a),n=To(e),o=t.encryptionInfo.defaultPerSampleIvSize;i(null!==o);for(let i=0;i0?a.set(mo(e,o),0):a.set(t.encryptionInfo.defaultConstantIv,0);let n=null;if(s){const t=ko(e);n=[];for(let i=0;i0&&((U=this.metadataTags).trackNumber??(U.trackNumber=t)),i&&Number.isInteger(i)&&i>0&&((q=this.metadataTags).tracksTotal??(q.tracksTotal=i))}break;case"trkn":if(a instanceof Uint8Array&&a.length>=6){const e=l(a),t=e.getUint16(2,!1),i=e.getUint16(4,!1);t>0&&((W=this.metadataTags).trackNumber??(W.trackNumber=t)),i>0&&((H=this.metadataTags).tracksTotal??(H.tracksTotal=i))}break;case"disc":case"disk":if(a instanceof Uint8Array&&a.length>=6){const e=l(a),t=e.getUint16(2,!1),i=e.getUint16(4,!1);t>0&&((j=this.metadataTags).discNumber??(j.discNumber=t)),i>0&&((K=this.metadataTags).discsTotal??(K.discsTotal=i))}}}}}return e.filePos=Q,!0}}class Mi{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;i(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 L(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,t){const i=this.mapTimestampIntoTimescale(e),r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=Li(r,i),s=await this.fetchPacketForSampleIndex(a,t);return Vi(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=x(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=R(t.presentationTimestamps,e=>t.samples[e.sampleIndex].isKeyFrame&&e.presentationTimestamp<=i);return{sampleIndex:-1!==r?t.presentationTimestamps[r].sampleIndex:-1,correctSampleFound:-1!==r&&i{if(e===a.fragment){const t=e.trackData.get(this.internalTrack.id).samples.findIndex((e,t)=>e.isKeyFrame&&t>a.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)}async fetchPacketForSampleIndex(e,t){if(-1===e)return null;const i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),r=Ui(i,e);if(!r)return null;let a;if(t.metadataOnly)a=mi;else{let t=this.internalTrack.demuxer.reader.requestSlice(r.sampleOffset,r.sampleSize);if(ae(t)&&(t=await t),!t)return null;if(a=mo(t,r.sampleSize),this.internalTrack.encryptionInfo){let t=null;if(this.internalTrack.encryptionAuxInfo){const i=await Ki(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);ee.timestamp),d=-1!==u?this.internalTrack.fragmentLookupTable[u]:null,h=x(this.internalTrack.fragmentPositionCache,r,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>a)break}let e=n.reader.requestSliceRange(p,8,16);if(ae(e)&&(e=await e),!e)break;const i=p,r=yi(e);if(!r)break;if("moof"===r.name){o=await n.readFragment(i);const{sampleIndex:e,correctSampleFound:r}=t(o);if(r)return this.fetchPacketInFragment(o,e,s);-1!==e&&(c=o,l=e)}p=i+r.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&&mt(e.data)}}else{const e=await this.getFirstPacket({}),t=e&&ft(e.data);t&&(this.internalTrack.info.av1CodecInfo=t)}else{const e=await this.getFirstPacket({}),t=e&&dt(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&&Ze(e.data)}else{const e=await this.getFirstPacket({});this.internalTrack.info.avcCodecInfo=e&&He(e.data)}if(!y(this.internalTrack.info.colorSpace)){const a=Yt(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:Qt(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 Oi extends Mi{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&&Ot(e.data)}return{codec:Jt(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}})()):null}}const Li=(e,t)=>{if(e.presentationTimestamps){const i=x(e.presentationTimestamps,t,e=>e.presentationTimestamp);return-1===i?-1:e.presentationTimestamps[i].sampleIndex}{const i=x(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)}},zi=(e,t)=>{if(!e.keySampleIndices)return Li(e,t);if(e.presentationTimestamps){const i=x(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!==I(e.keySampleIndices,i,e=>e))return i}return-1}{const i=Li(e,t),r=x(e.keySampleIndices,i,e=>e);return e.keySampleIndices[r]??-1}},Ui=(e,t)=>{const r=x(e.sampleTimingEntries,t,e=>e.startIndex),a=e.sampleTimingEntries[r];if(!a||a.startIndex+a.count<=t)return null;let s=a.startDecodeTimestamp+(t-a.startIndex)*a.delta;const n=x(e.sampleCompositionTimeOffsets,t,e=>e.startIndex),o=e.sampleCompositionTimeOffsets[n];o&&t-o.startIndexe.startSampleIndex),u=e.sampleToChunk[l];i(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 i=f;ie)}},qi=(e,t)=>{if(!e.keySampleIndices)return t+1;const i=x(e.keySampleIndices,t,e=>e);return e.keySampleIndices[i+1]??-1},Wi=(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},Hi=e=>{const[t,i]=e,r=Math.atan2(i,t);return Number.isFinite(r)?r*(180/Math.PI):0},Vi=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})},Ki=async(e,t,r)=>{if(r.resolved)return r.resolved;if(null===r.offset||0===r.sampleCount)throw new Error("Incomplete saiz/saio info; cannot resolve encryption data.");let a=0;if(r.defaultSampleInfoSize>0)a=r.defaultSampleInfoSize*r.sampleCount;else{i(r.sampleSizes);for(let e=0;e0?r.defaultSampleInfoSize:r.sampleSizes[i],a=new Uint8Array(16);n>0?a.set(mo(s,n),0):a.set(t.defaultConstantIv,0);let c=null;if(e>n){const e=ko(s);c=[];for(let t=0;te.defaultConstantIv?{iv:e.defaultConstantIv,subsamples:null}:null,$i=async(e,t,r,a)=>{i(e.encryptionInfo);const s=e.encryptionInfo;i(null!==s.defaultKid);const n=s.defaultKid;let o;const c=e.demuxer.decryptionKeyCache.get(n);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(a){t=[...t,...a.psshBoxes].filter(e=>null===e.keyIds||e.keyIds.includes(n));for(let e=0;e{i(e.length%2===0);const t=new Uint8Array(e.length/2);for(let i=0;i{const s=new Uint8Array(16);s.set(r.iv,0);const n=await crypto.subtle.importKey("raw",e,{name:"AES-CTR"},!1,["decrypt"]),o=async e=>{const t=await crypto.subtle.decrypt({name:"AES-CTR",counter:s,length:64},n,e);return new Uint8Array(t)};if(!r.subsamples)return o(a);i(null!==t.defaultCryptByteBlock&&null!==t.defaultSkipByteBlock);const c=Yi(r.subsamples,t.defaultCryptByteBlock,t.defaultSkipByteBlock);let l=0;for(const i of c)for(const e of i.perSubsample)l+=e.length;const u=new Uint8Array(l);let d=0;for(const i of c)for(const e of i.perSubsample)u.set(a.subarray(e.offset,e.offset+e.length),d),d+=e.length;const h=await o(u),f=new Uint8Array(a);let m=0;for(const i of c)for(const e of i.perSubsample)f.set(h.subarray(m,m+e.length),e.offset),m+=e.length;return f},Qi=(e,t,r,a)=>{const s=new Ai;s.init({key:e,iv:r.iv});const n=t.defaultCryptByteBlock,o=t.defaultSkipByteBlock;if(i(null!==n&&null!==o),!r.subsamples){const e=new Uint8Array(a),t=Math.floor(a.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 Ji,Zi;(Zi=Ji||(Ji={}))[Zi.EBML=440786851]="EBML",Zi[Zi.EBMLVersion=17030]="EBMLVersion",Zi[Zi.EBMLReadVersion=17143]="EBMLReadVersion",Zi[Zi.EBMLMaxIDLength=17138]="EBMLMaxIDLength",Zi[Zi.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",Zi[Zi.DocType=17026]="DocType",Zi[Zi.DocTypeVersion=17031]="DocTypeVersion",Zi[Zi.DocTypeReadVersion=17029]="DocTypeReadVersion",Zi[Zi.Void=236]="Void",Zi[Zi.Segment=408125543]="Segment",Zi[Zi.SeekHead=290298740]="SeekHead",Zi[Zi.Seek=19899]="Seek",Zi[Zi.SeekID=21419]="SeekID",Zi[Zi.SeekPosition=21420]="SeekPosition",Zi[Zi.Duration=17545]="Duration",Zi[Zi.Info=357149030]="Info",Zi[Zi.TimestampScale=2807729]="TimestampScale",Zi[Zi.MuxingApp=19840]="MuxingApp",Zi[Zi.WritingApp=22337]="WritingApp",Zi[Zi.Tracks=374648427]="Tracks",Zi[Zi.TrackEntry=174]="TrackEntry",Zi[Zi.TrackNumber=215]="TrackNumber",Zi[Zi.TrackUID=29637]="TrackUID",Zi[Zi.TrackType=131]="TrackType",Zi[Zi.FlagEnabled=185]="FlagEnabled",Zi[Zi.FlagDefault=136]="FlagDefault",Zi[Zi.FlagForced=21930]="FlagForced",Zi[Zi.FlagOriginal=21934]="FlagOriginal",Zi[Zi.FlagHearingImpaired=21931]="FlagHearingImpaired",Zi[Zi.FlagVisualImpaired=21932]="FlagVisualImpaired",Zi[Zi.FlagCommentary=21935]="FlagCommentary",Zi[Zi.FlagLacing=156]="FlagLacing",Zi[Zi.Name=21358]="Name",Zi[Zi.Language=2274716]="Language",Zi[Zi.LanguageBCP47=2274717]="LanguageBCP47",Zi[Zi.CodecID=134]="CodecID",Zi[Zi.CodecPrivate=25506]="CodecPrivate",Zi[Zi.CodecDelay=22186]="CodecDelay",Zi[Zi.SeekPreRoll=22203]="SeekPreRoll",Zi[Zi.DefaultDuration=2352003]="DefaultDuration",Zi[Zi.Video=224]="Video",Zi[Zi.PixelWidth=176]="PixelWidth",Zi[Zi.PixelHeight=186]="PixelHeight",Zi[Zi.DisplayWidth=21680]="DisplayWidth",Zi[Zi.DisplayHeight=21690]="DisplayHeight",Zi[Zi.DisplayUnit=21682]="DisplayUnit",Zi[Zi.AlphaMode=21440]="AlphaMode",Zi[Zi.Audio=225]="Audio",Zi[Zi.SamplingFrequency=181]="SamplingFrequency",Zi[Zi.Channels=159]="Channels",Zi[Zi.BitDepth=25188]="BitDepth",Zi[Zi.SimpleBlock=163]="SimpleBlock",Zi[Zi.BlockGroup=160]="BlockGroup",Zi[Zi.Block=161]="Block",Zi[Zi.BlockAdditions=30113]="BlockAdditions",Zi[Zi.BlockMore=166]="BlockMore",Zi[Zi.BlockAdditional=165]="BlockAdditional",Zi[Zi.BlockAddID=238]="BlockAddID",Zi[Zi.BlockDuration=155]="BlockDuration",Zi[Zi.ReferenceBlock=251]="ReferenceBlock",Zi[Zi.Cluster=524531317]="Cluster",Zi[Zi.Timestamp=231]="Timestamp",Zi[Zi.Cues=475249515]="Cues",Zi[Zi.CuePoint=187]="CuePoint",Zi[Zi.CueTime=179]="CueTime",Zi[Zi.CueTrackPositions=183]="CueTrackPositions",Zi[Zi.CueTrack=247]="CueTrack",Zi[Zi.CueClusterPosition=241]="CueClusterPosition",Zi[Zi.Colour=21936]="Colour",Zi[Zi.MatrixCoefficients=21937]="MatrixCoefficients",Zi[Zi.TransferCharacteristics=21946]="TransferCharacteristics",Zi[Zi.Primaries=21947]="Primaries",Zi[Zi.Range=21945]="Range",Zi[Zi.Projection=30320]="Projection",Zi[Zi.ProjectionType=30321]="ProjectionType",Zi[Zi.ProjectionPoseRoll=30325]="ProjectionPoseRoll",Zi[Zi.Attachments=423732329]="Attachments",Zi[Zi.AttachedFile=24999]="AttachedFile",Zi[Zi.FileDescription=18046]="FileDescription",Zi[Zi.FileName=18030]="FileName",Zi[Zi.FileMediaType=18016]="FileMediaType",Zi[Zi.FileData=18012]="FileData",Zi[Zi.FileUID=18094]="FileUID",Zi[Zi.Chapters=272869232]="Chapters",Zi[Zi.Tags=307544935]="Tags",Zi[Zi.Tag=29555]="Tag",Zi[Zi.Targets=25536]="Targets",Zi[Zi.TargetTypeValue=26826]="TargetTypeValue",Zi[Zi.TargetType=25546]="TargetType",Zi[Zi.TagTrackUID=25541]="TagTrackUID",Zi[Zi.TagEditionUID=25545]="TagEditionUID",Zi[Zi.TagChapterUID=25540]="TagChapterUID",Zi[Zi.TagAttachmentUID=25542]="TagAttachmentUID",Zi[Zi.SimpleTag=26568]="SimpleTag",Zi[Zi.TagName=17827]="TagName",Zi[Zi.TagLanguage=17530]="TagLanguage",Zi[Zi.TagString=17543]="TagString",Zi[Zi.TagBinary=17541]="TagBinary",Zi[Zi.ContentEncodings=28032]="ContentEncodings",Zi[Zi.ContentEncoding=25152]="ContentEncoding",Zi[Zi.ContentEncodingOrder=20529]="ContentEncodingOrder",Zi[Zi.ContentEncodingScope=20530]="ContentEncodingScope",Zi[Zi.ContentCompression=20532]="ContentCompression",Zi[Zi.ContentCompAlgo=16980]="ContentCompAlgo",Zi[Zi.ContentCompSettings=16981]="ContentCompSettings",Zi[Zi.ContentEncryption=20533]="ContentEncryption";const er=[Ji.EBML,Ji.Segment],tr=[Ji.SeekHead,Ji.Info,Ji.Cluster,Ji.Tracks,Ji.Cues,Ji.Attachments,Ji.Chapters,Ji.Tags],ir=[...er,...tr],rr=16,ar=e=>{if(e.remainingLength<1)return null;const t=po(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=po(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=ar(e);if(null===t)return null;if(e.remainingLength{if(e.remainingLength<1)return null;if(255===po(e))return;e.skip(-1);const t=sr(e);return null===t?null:72057594037927940!==t?t:void 0},lr=e=>{i(e.remainingLength>=2);const t=or(e);if(null===t)return null;const r=cr(e);return null===r?null:{id:t,size:r}},ur=(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?Bo(e):Eo(e)},fr=async(e,t,i,r)=>{const a=new Set(i);let s=t;for(;null===r||ss?r:s,found:!1}},mr=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,rr);if(ae(t)&&(t=await t),!t)break;const i=lr(t);if(!i)break;const r=i.id;let s=i.size;const n=t.filePos;if(r===Ji.EBML){Er(s);let e=this.reader.requestSlice(n,s);if(ae(e)&&(e=await e),!e)break;this.readContiguousElements(e)}else if(r===Ji.Segment){if(await this.readSegment(n,s),void 0===s)break;if(null===this.reader.fileSize)break}else if(r===Ji.Cluster){if(null===this.reader.fileSize)break;if(void 0===s){s=(await fr(this.reader,n,ir,this.reader.fileSize)).pos-n}const e=a(this.segments);e&&(e.elementEndPos=n+s)}Er(s),e=n+s}})())}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=Nr[o].flag;this.currentSegment[e]=!0,Er(s);let t=this.reader.requestSlice(n,s);ae(t)&&(t=await t),t&&this.readContiguousElements(t)}else if(a===Ji.Tags||a===Ji.Attachments){a===Ji.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,Er(s);let e=this.reader.requestSlice(n,s);ae(e)&&(e=await e),e&&this.readContiguousElements(e)}else if(a===Ji.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=Nr.find(e=>e.id===n.id);if(!t)continue;if(this.currentSegment[t.flag])continue;let i=this.reader.requestSliceRange(e+n.segmentPosition,2,rr);if(ae(i)&&(i=await i),!i)continue;const r=lr(i);if(!r)continue;const{id:a,size:s}=r;if(a!==t.id)continue;Er(s),this.currentSegment[t.flag]=!0;let o=this.reader.requestSlice(i.filePos,s);ae(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 r=this.reader.requestSliceRange(e,2,rr);ae(r)&&(r=await r),i(r);const s=e,n=lr(r);i(n);i(n.id===Ji.Cluster);let o=n.size;const c=r.filePos;if(void 0===o){o=(await fr(this.reader,c,ir,t.elementEndPos)).pos-c}let l=this.reader.requestSlice(c,o);ae(l)&&(l=await l);const u={segment:t,elementStartPos:s,elementEndPos:c+o,dataStartPos:c,timestamp:-1,trackData:new Map};if(this.currentCluster=u,l){const e=this.readContiguousElements(l,ir);u.elementEndPos=e}for(const[,d]of u.trackData){const e=d.track;i(d.blocks.length>0);let t=!1;for(let i=0;i({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp);for(let i=0;i({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp));const r=d.blocks[d.presentationTimestamps[0].blockIndex],n=d.blocks[a(d.presentationTimestamps).blockIndex];d.startTimestamp=r.timestamp,d.endTimestamp=n.timestamp+n.duration;const o=x(e.clusterPositionCache,d.startTimestamp,e=>e.startTimestamp);-1!==o&&e.clusterPositionCache[o].elementStartPos===s||e.clusterPositionCache.splice(o+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 r=0;r=2;){const i=e.filePos;if(!this.traverseElement(e,t))return i}return e.filePos}traverseElement(e,t){const a=lr(e);if(!a)return!1;if(t&&t.includes(a.id))return!1;const{id:s,size:n}=a,o=e.filePos;switch(Er(n),s){case Ji.DocType:this.isWebM="webm"===ur(e,n);break;case Ji.Seek:{if(!this.currentSegment)break;const t={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(t),this.readContiguousElements(e.slice(o,n)),-1!==t.id&&-1!==t.segmentPosition||this.currentSegment.seekEntries.pop()}break;case Ji.SeekID:{const t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.id=nr(e,n)}break;case Ji.SeekPosition:{const t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.segmentPosition=nr(e,n)}break;case Ji.TimestampScale:if(!this.currentSegment)break;this.currentSegment.timestampScale=nr(e,n),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale;break;case Ji.Duration:if(!this.currentSegment)break;this.currentSegment.duration=hr(e,n);break;case Ji.TrackEntry:if(!this.currentSegment)break;if(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...Se,primary:!1},trackBacking:null,codecId:null,codecPrivate:null,defaultDuration:null,defaultDurationNs:null,name:null,languageCode:"eng",hasLanguageBcp47:!1,decodingInstructions:[],info:null},this.readContiguousElements(e.slice(o,n)),!this.currentTrack)break;if(this.currentTrack.decodingInstructions.some(e=>"decompress"!==e.data?.type||e.scope!==Fr.Block||e.data.algorithm!==Dr.HeaderStripping)&&(be._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===pr)this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(this.currentTrack.codecId===gr)this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(t===kr)this.currentTrack.info.codec="vp8";else if(t===yr)this.currentTrack.info.codec="vp9";else if(t===br)this.currentTrack.info.codec="av1";else if(t===wr){const e=this.currentTrack.codecPrivate?u.decode(this.currentTrack.codecPrivate):"";$t.includes(e)&&(this.currentTrack.info.codec="prores",this.currentTrack.info.proresFormat=e)}const e=this.currentTrack;this.currentTrack.trackBacking=new Ur(e),this.currentSegment.tracks.push(this.currentTrack)}else if("audio"===this.currentTrack.info.type){t===Tr?(this.currentTrack.info.codec="aac",this.currentTrack.info.aacCodecInfo={isMpeg2:this.currentTrack.codecId.includes("MPEG2"),objectType:null},this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===Sr?this.currentTrack.info.codec="mp3":t===vr?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=Zt):t===Pr?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Ir?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===xr?(this.currentTrack.info.codec="ac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Cr?(this.currentTrack.info.codec="eac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Br?(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 qr(e),this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null;break;case Ji.TrackNumber:if(!this.currentTrack)break;this.currentTrack.id=nr(e,n);break;case Ji.TrackType:{if(!this.currentTrack)break;const t=nr(e,n);1===t?this.currentTrack.info={type:"video",width:-1,height:-1,displayWidth:null,displayHeight:null,displayUnit:null,squarePixelWidth:-1,squarePixelHeight:-1,rotation:0,codec:null,codecDescription:null,colorSpace:{...b},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 Ji.FlagEnabled:if(!this.currentTrack)break;nr(e,n)||(this.currentTrack=null);break;case Ji.FlagDefault:if(!this.currentTrack)break;this.currentTrack.disposition.default=!!nr(e,n);break;case Ji.FlagForced:if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!nr(e,n);break;case Ji.FlagOriginal:if(!this.currentTrack)break;this.currentTrack.disposition.original=!!nr(e,n);break;case Ji.FlagHearingImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!nr(e,n);break;case Ji.FlagVisualImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!nr(e,n);break;case Ji.FlagCommentary:if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!nr(e,n);break;case Ji.CodecID:if(!this.currentTrack)break;this.currentTrack.codecId=ur(e,n);break;case Ji.CodecPrivate:if(!this.currentTrack)break;this.currentTrack.codecPrivate=mo(e,n);break;case Ji.DefaultDuration:if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=nr(e,n);break;case Ji.Name:if(!this.currentTrack)break;this.currentTrack.name=dr(e,n);break;case Ji.Language:if(!this.currentTrack)break;if(this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=ur(e,n),V(this.currentTrack.languageCode)||(this.currentTrack.languageCode=O);break;case Ji.LanguageBCP47:{if(!this.currentTrack)break;const t=ur(e,n).split("-")[0];this.currentTrack.languageCode=t||O,this.currentTrack.hasLanguageBcp47=!0}break;case Ji.Video:if("video"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(o,n));break;case Ji.PixelWidth:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.width=nr(e,n);break;case Ji.PixelHeight:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.height=nr(e,n);break;case Ji.DisplayWidth:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.displayWidth=nr(e,n);break;case Ji.DisplayHeight:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.displayHeight=nr(e,n);break;case Ji.DisplayUnit:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.displayUnit=nr(e,n);break;case Ji.AlphaMode:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.alphaMode=1===nr(e,n);break;case Ji.Colour:if("video"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(o,n));break;case Ji.MatrixCoefficients:{if("video"!==this.currentTrack?.info?.type)break;const t=nr(e,n),i=k[t];this.currentTrack.info.colorSpace.matrix=i}break;case Ji.Range:{if("video"!==this.currentTrack?.info?.type)break;const t=nr(e,n);this.currentTrack.info.colorSpace.fullRange=1===t||2===t?2===t:void 0}break;case Ji.TransferCharacteristics:{if("video"!==this.currentTrack?.info?.type)break;const t=nr(e,n),i=p[t];this.currentTrack.info.colorSpace.transfer=i}break;case Ji.Primaries:{if("video"!==this.currentTrack?.info?.type)break;const t=nr(e,n),i=f[t];this.currentTrack.info.colorSpace.primaries=i}break;case Ji.Projection:if("video"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(o,n));break;case Ji.ProjectionPoseRoll:{if("video"!==this.currentTrack?.info?.type)break;const t=-hr(e,n);try{this.currentTrack.info.rotation=r(t)}catch{}}break;case Ji.Audio:if("audio"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(o,n));break;case Ji.SamplingFrequency:if("audio"!==this.currentTrack?.info?.type)break;this.currentTrack.info.sampleRate=hr(e,n);break;case Ji.Channels:if("audio"!==this.currentTrack?.info?.type)break;this.currentTrack.info.numberOfChannels=nr(e,n);break;case Ji.BitDepth:if("audio"!==this.currentTrack?.info?.type)break;this.currentTrack.info.bitDepth=nr(e,n);break;case Ji.CuePoint:if(!this.currentSegment)break;this.readContiguousElements(e.slice(o,n)),this.currentCueTime=null;break;case Ji.CueTime:this.currentCueTime=nr(e,n);break;case Ji.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(o,n)),-1!==t.trackId&&-1!==t.clusterPosition||this.currentSegment.cuePoints.pop()}break;case Ji.CueTrack:{const t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;t.trackId=nr(e,n)}break;case Ji.CueClusterPosition:{const t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;i(this.currentSegment),t.clusterPosition=this.currentSegment.dataStartPos+nr(e,n)}break;case Ji.Timestamp:if(!this.currentCluster)break;this.currentCluster.timestamp=nr(e,n);break;case Ji.SimpleBlock:{if(!this.currentCluster)break;const t=sr(e);if(null===t)break;const i=this.getTrackDataInCluster(this.currentCluster,t);if(!i)break;const r=bo(e),a=po(e),s=a>>1&3;let c=!!(128&a);"audio"===i.track.info?.type&&i.track.info.codec&&(c=!0);const l=mo(e,n-(e.filePos-o)),u=i.track.decodingInstructions.length>0;i.blocks.push({timestamp:r,duration:0,isKeyFrame:c,data:l,lacing:s,decoded:!u,postProcessed:!1,mainAdditional:null})}break;case Ji.BlockGroup:if(!this.currentCluster)break;this.readContiguousElements(e.slice(o,n)),this.currentBlock=null;break;case Ji.Block:{if(!this.currentCluster)break;const t=sr(e);if(null===t)break;const i=this.getTrackDataInCluster(this.currentCluster,t);if(!i)break;const r=bo(e),a=po(e)>>1&3,s=mo(e,n-(e.filePos-o)),c=i.track.decodingInstructions.length>0;this.currentBlock={timestamp:r,duration:0,isKeyFrame:!0,data:s,lacing:a,decoded:!c,postProcessed:!1,mainAdditional:null},i.blocks.push(this.currentBlock)}break;case Ji.BlockAdditions:this.readContiguousElements(e.slice(o,n));break;case Ji.BlockMore:if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(o,n)),this.currentBlockAdditional.data&&1===this.currentBlockAdditional.addId&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null;break;case Ji.BlockAdditional:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=mo(e,n);break;case Ji.BlockAddID:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=nr(e,n);break;case Ji.BlockDuration:if(!this.currentBlock)break;this.currentBlock.duration=nr(e,n);break;case Ji.ReferenceBlock:if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1;break;case Ji.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(o,n));break;case Ji.Targets:this.readContiguousElements(e.slice(o,n));break;case Ji.TargetTypeValue:50!==nr(e,n)&&(this.currentTagTargetIsMovie=!1);break;case Ji.TagTrackUID:case Ji.TagEditionUID:case Ji.TagChapterUID:case Ji.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case Ji.SimpleTag:if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(o,n));break;case Ji.TagName:this.currentSimpleTagName=dr(e,n);break;case Ji.TagString:{if(!this.currentSimpleTagName)break;const t=dr(e,n);this.processTagValue(this.currentSimpleTagName,t)}break;case Ji.TagBinary:{if(!this.currentSimpleTagName)break;const t=mo(e,n);this.processTagValue(this.currentSimpleTagName,t)}break;case Ji.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(o,n));const t=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(t.raw??(t.raw={}),t.raw[this.currentAttachedFile.fileUid.toString()]=new Te(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 Ji.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 Ji.ContentEncoding:this.currentDecodingInstruction={order:0,scope:Fr.Block,data:null},this.readContiguousElements(e.slice(o,n)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case Ji.ContentEncodingOrder:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=nr(e,n);break;case Ji.ContentEncodingScope:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=nr(e,n);break;case Ji.ContentCompression:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:Dr.Zlib,settings:null},this.readContiguousElements(e.slice(o,n));break;case Ji.ContentCompAlgo:if("decompress"!==this.currentDecodingInstruction?.data?.type)break;this.currentDecodingInstruction.data.algorithm=nr(e,n);break;case Ji.ContentCompSettings:if("decompress"!==this.currentDecodingInstruction?.data?.type)break;this.currentDecodingInstruction.data.settings=mo(e,n);break;case Ji.ContentEncryption:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}return e.filePos=o+n,!0}decodeBlockData(e,t){i(e.decodingInstructions.length>0);let r=t;for(const a of e.decodingInstructions)if(i(a.data),"decompress"===a.data.type)if(a.data.algorithm===Dr.HeaderStripping)if(a.data.settings&&a.data.settings.length>0){const e=a.data.settings,t=new Uint8Array(e.length+r.length);t.set(e,0),t.set(r,e.length),r=t}return r}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 a of e.tracks){i(a.trackBacking);const e=await a.trackBacking.getFirstPacket({metadataOnly:!0});e&&(t=Math.min(t??1/0,e.timestamp))}let r=e.duration/e.timestampFactor;return r+=t??0,r}}class zr{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 L(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=x(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=R(t.presentationTimestamps,e=>t.blocks[e.blockIndex].isKeyFrame&&e.timestamp<=i);return{blockIndex:-1!==r?t.presentationTimestamps[r].blockIndex:-1,correctBlockFound:-1!==r&&i{if(e===r.cluster){const t=e.trackData.get(this.internalTrack.id).blocks.findIndex((e,t)=>e.isKeyFrame&&t>r.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)}async fetchPacketInCluster(e,t,r){if(-1===t)return null;const a=e.trackData.get(this.internalTrack.id).blocks[t];if(i(a),a.decoded||(a.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,a.data),a.decoded=!0),!a.postProcessed){if("prores"===this.internalTrack.info?.codec){if(!(a.data.length>=8&&105===a.data[4]&&99===a.data[5]&&112===a.data[6]&&102===a.data[7])){const e=new Uint8Array(a.data.length+8);l(e).setUint32(0,e.length,!1),e[4]=105,e[5]=99,e[6]=112,e[7]=102,e.set(a.data,8),a.data=e}}a.postProcessed=!0}const s=r.metadataOnly?mi:a.data,n=a.timestamp/this.internalTrack.segment.timestampFactor,o=a.duration/this.internalTrack.segment.timestampFactor,c={};a.mainAdditional&&"video"===this.internalTrack.info?.type&&this.internalTrack.info.alphaMode&&(c.alpha=r.metadataOnly?mi:a.mainAdditional,c.alphaByteLength=a.mainAdditional.byteLength);const u=new pi(s,a.isKeyFrame?"key":"delta",n,o,e.dataStartPos+t,a.data.byteLength,c);return this.packetToClusterLocation.set(u,{cluster:e,blockIndex:t}),u}async performClusterLookup(e,t,r,a,s){const{demuxer:n,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,s);-1!==i&&(l=e,u=i)}const d=x(this.internalTrack.cuePoints,r,e=>e.time),h=-1!==d?this.internalTrack.cuePoints[d]:null,f=x(this.internalTrack.clusterPositionCache,r,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>a)break}let e=n.reader.requestSliceRange(g,2,rr);if(ae(e)&&(e=await e),!e)break;const r=g,d=lr(e);if(!d||!tr.includes(d.id)&&d.id!==Ji.Void){const e=await mr(n.reader,r,tr,Math.min(o.elementEndPos??1/0,r+Or));if(e){g=e;continue}break}const h=d.id;let f=d.size;const m=e.filePos;if(h===Ji.Cluster){c=await n.readCluster(r,o),f=c.elementEndPos-m;const{blockIndex:e,correctBlockFound:i}=t(c);if(i)return this.fetchPacketInCluster(c,e,s);-1!==e&&(l=c,u=e)}if(void 0===f){i(h!==Ji.Cluster);f=(await fr(n.reader,m,ir,o.elementEndPos)).pos-m}const p=m+f;if(null===o.elementEndPos){let e=n.reader.requestSliceRange(p,2,rr);if(ae(e)&&(e=await e),!e)break;if(or(e)===Ji.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?He(a.data):null,hevcCodecInfo:"hevc"===this.internalTrack.info.codec&&a?Ze(a.data):null,vp9CodecInfo:"vp9"===this.internalTrack.info.codec&&a?dt(a.data):null,av1CodecInfo:"av1"===this.internalTrack.info.codec&&a?ft(a.data):null,proresCodecInfo:"prores"===this.internalTrack.info.codec&&a?mt(a.data):null,proresFormat:this.internalTrack.info.proresFormat};if(!y(this.internalTrack.info.colorSpace)){const a=Yt(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:Qt(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 qr extends zr{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&&Ot(e.data)}return{codec:Jt({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 Wr=async(e,t,i,r=null)=>{let a=t;for(;null===i||a=4;){const t=s.filePos,i=To(s),n=null!==e.fileSize?e.fileSize-a:null,o=ci(i,n);if(o.header&&(!r||o.header.sampleRate===r.sampleRate&&o.header.mpegVersionId===r.mpegVersionId&&o.header.layer===r.layer&&hi(o.header.channel)===hi(r.channel)))return{header:o.header,startPos:a};s.filePos=t+o.bytesAdvanced,a=s.filePos}}return null};class Hr extends fi{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 T,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 Vr(this)]})())}async advanceReader(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,Oo);if(ae(e)&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const t=qo(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}const e=await Wr(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=oi(t.mpegVersionId,t.channel);let r=this.reader.requestSlice(e.startPos+i,4);if(ae(r)&&(r=await r),r){const a=To(r);if(a===si||a===ni){if(this.xingFrameHeader||(this.xingFrameHeader=t,this.xingFrameHeaderPos=e.startPos),!this.xingData){let t=this.reader.requestSlice(e.startPos+i+4,12);if(ae(t)&&(t=await t),t){const e=mo(t,12),i=l(e),r=i.getUint32(0,!1);this.xingData={frameCount:r&ui.FrameCount?i.getUint32(4,!1):null,fileSize:r&ui.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,Oo);if(ae(i)&&(i=await i),!i)break;const r=qo(i);if(!r)break;t=!0;let a=this.reader.requestSlice(i.filePos,r.size);if(ae(a)&&(a=await a),!a)break;Wo(a,r,this.metadataTags),e=i.filePos+r.size}if(!t&&null!==this.reader.fileSize&&this.reader.fileSize>=No){let e=this.reader.requestSlice(this.reader.fileSize-No,No);ae(e)&&(e=await e),i(e);"TAG"===_o(e,3)&&zo(e,this.metadataTags)}return this.metadataTags}finally{e()}}}class Vr{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 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){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 i=(t=e.firstFrameHeader.lowSamplingFrequency,r=e.firstFrameHeader.layer,a=e.firstFrameHeader.bitrate,s=e.firstFrameHeader.sampleRate,0===r?0:1===r?144*a/(s<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=x(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 Xr=e=>{const t=l(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},$r=(e,t,r)=>{let a=0,s=null;if(e.length>0)if("vorbis"===t.codec){i(t.vorbisInfo);const n=(1<<(e=>{let t=0;for(;e;)t++,e>>=1;return t})(t.vorbisInfo.modeBlockflags.length-1))-1<<1,o=(e[0]&n)>>1;if(o>=t.vorbisInfo.modeBlockflags.length)throw new Error("Invalid mode number.");let c=r;const l=t.vorbisInfo.modeBlockflags[o];if(s=t.vorbisInfo.blocksizes[l],1===l){const i=1+(1|n),r=e[0]&i?1:0;c=t.vorbisInfo.blocksizes[r]}a=null!==c?c+s>>2:0}else if("opus"===t.codec){a=(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:pt[t]*r}})(e).durationInSamples}return{durationInSamples:a,vorbisBlockSize:s}},Gr=27,Qr=282,Yr=e=>{const t=e.filePos;if(So(e)!==jr)return null;e.skip(1);const i=po(e),r=Co(e),a=So(e),s=So(e),n=So(e),o=po(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}},Jr=(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 Zr extends fi{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,Gr,Qr);if(ae(t)&&(t=await t),!t)break;const i=Yr(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 ea(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=l(e.data);t.numberOfChannels=c.getUint8(11),t.sampleRate=c.getUint32(12,!0);const u=c.getUint8(28);t.codecInfo.vorbisInfo={blocksizes:[1<<(15&u),1<<(u>>4)],modeBlockflags:gt(a.data).modeBlockflags},wt(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=l(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=Zt,t.codecInfo.opusInfo={preSkip:a.preSkip},wt(r.data.subarray(8),this.metadataTags)}async readPacket(e,t){i(te+t.length,0);if(0===c)return null;const l=new Uint8Array(c);let u=0;for(let i=0;i{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 ea{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new T,this.internalSampleRate="opus"===e.codecInfo.codec?Zt: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 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 i(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 O}getDisposition(){return{...Se,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:a}=$r(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),s=new pi(i.metadataOnly?mi: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){i(this.bitstream.lastMetadataPacket);const t=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let r=0;"opus"===this.bitstream.codecInfo.codec&&(i(this.bitstream.codecInfo.opusInfo),r-=this.bitstream.codecInfo.opusInfo.preSkip);const a=await this.demuxer.readPacket(t.startPage,t.startSegmentIndex);return this.createEncodedPacketFromOggPacket(a,{timestampInSamples:r,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 r=L(e*this.internalSampleRate);if(0===r)return this.getFirstPacket(t);if(r<0)return null;i(this.bitstream.lastMetadataPacket);const a=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!a)return null;let s=a.startPage,n=this.demuxer.reader.fileSize;const o=[s];e:for(;s.headerStartPos+s.totalSizer?n=u.headerStartPos:(s=u,o.push(u));continue e}a=u.headerStartPos+u.totalSize}}let c=a.startPage;for(const i of o){if(i.granulePosition===s.granulePosition)break;(!c||i.headerStartPos>c.headerStartPos)&&(c=i)}let l=c;const u=[l];for(;l.serialNumber!==this.bitstream.serialNumber||l.granulePosition!==s.granulePosition;){const e=l.headerStartPos+l.totalSize;let t=this.demuxer.reader.requestSliceRange(e,Gr,Qr);ae(t)&&(t=await t),i(t);const r=Yr(t);i(r),l=r,l.serialNumber===this.bitstream.serialNumber&&u.push(l)}i(-1!==l.granulePosition);let d,h,f=null,m=l,p=0;if(l.headerStartPos===a.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:mi,endPage:m,endSegmentIndex:p};if(await this.demuxer.findNextPacketStart(e)){const e=ia(u,l,f);i(e);const t=ta(u,e.page,e.segmentIndex);t&&(l=t.page,f=t.segmentIndex)}else for(;;){const e=ia(u,l,f);if(!e)break;const t=ta(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;){i(null!==f);const e=await this.demuxer.readPacket(l,f);if(!e)break;if(!(l.headerStartPos===a.startPage.headerStartPos&&fr||Math.max(s.timestampInSamples,0)===r))break}const s=await this.demuxer.findNextPacketStart(e);if(!s)break;l=s.startPage,f=s.startSegmentIndex}return g}async getPacketSequential(e,t){const r=await this.sequentialScanMutex.acquire();try{const r=L(e*this.internalSampleRate);e=r/this.internalSampleRate;const s=x(this.sequentialScanCache,r,e=>e.timestampInSamples);let n;if(-1!==s){const e=this.sequentialScanCache[s];n=this.createEncodedPacketFromOggPacket(e.packet,{timestampInSamples:e.timestampInSamples,vorbisLastBlocksize:e.vorbisLastBlockSize},t)}else n=await this.getFirstPacket(t);let o=0;for(;n&&n.timestampe)break;if(n=r,o++,100===o){o=0;const e=this.encodedPacketToMetadata.get(n);i(e),this.sequentialScanCache.length>0&&i(a(this.sequentialScanCache).timestampInSamples<=e.timestampInSamples),this.sequentialScanCache.push(e)}}return n}finally{r()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const ta=(e,t,r)=>{let a=t,s=r;e:for(;;){for(s--;s>=0;s--){if(a.lacingValues[s]<255){s++;break e}}i(-1===s);if(!(1&a.headerType)){s=0;break}const t=_(e,e=>e.headerStartPos{if(i>0)return{page:t,segmentIndex:i-1};const r=_(e,e=>e.headerStartPos{let e=this.reader.requestSlice(0,12);ae(e)&&(e=await e),i(e);const t=_o(e,4),r="RIFX"!==t,a="RF64"===t,s=wo(e,r);let n=a?this.reader.fileSize:Math.min(s+8,this.reader.fileSize??1/0);if("WAVE"!==_o(e,4))throw new Error("Invalid WAVE file - wrong format");let o=0,c=null,l=e.filePos;for(;null===n||l=18&&357!==a){const e=go(r,i),s=t-18;if(Math.min(s,e)>=22&&a===ra.EXTENSIBLE){r.skip(6);const e=mo(r,16);a=e[0]|e[1]<<8}}if(a!==ra.MULAW&&a!==ra.ALAW||(c=8),a!==ra.PCM&&a!==ra.IEEE_FLOAT&&a!==ra.ALAW&&a!==ra.MULAW)throw new Error(`Unsupported WAVE codec (format tag ${a}). Only integer/float PCM, A-law, and \u03bc-law are supported.`);if(a===ra.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===ra.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(ae(m)&&(m=await m),!m)return;const p=_o(m,4);if("INFO"!==p&&"INF0"!==p)return;let g=m.filePos;for(;g<=e+t-8;){m.filePos=g;const e=_o(m,4),t=wo(m,i),p=mo(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(ae(i)&&(i=await i),!i)return;const r=qo(i);if(r){const a=t-Oo;if(r.size=Math.min(r.size,a),r.size>0){const t=i.slice(e+Oo,r.size);Wo(t,r,this.metadataTags)}}}getCodec(){if(i(this.audioInfo),this.audioInfo.format===ra.MULAW)return"ulaw";if(this.audioInfo.format===ra.ALAW)return"alaw";if(this.audioInfo.format===ra.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===ra.IEEE_FLOAT){if(4===this.audioInfo.sampleSizeInBytes)return"pcm-f32";if(8===this.audioInfo.sampleSizeInBytes)return"pcm-f64"}i(!1)}async getMimeType(){return"audio/wav"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}const na=2048;class oa{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}async getDecoderConfig(){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 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return i(-1!==this.demuxer.dataSize),this.demuxer.dataSize/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return O}getDisposition(){return{...Se}}async getPacketAtIndex(e,t){i(e>=0),i(this.demuxer.audioInfo);const r=e*na*this.demuxer.audioInfo.blockSizeInBytes;if(r>=this.demuxer.dataSize)return null;const a=Math.min(na*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-r);if(null===this.demuxer.reader.fileSize){let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+r,a);if(ae(e)&&(e=await e),!e)return null}let s;if(t.metadataOnly)s=mi;else{let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+r,a);ae(e)&&(e=await e),i(e),s=mo(e,a)}const n=e*na/this.demuxer.audioInfo.sampleRate,o=a/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(e,this.demuxer.lastKnownPacketIndex),new pi(s,"key",n,o,e,a)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,t){i(this.demuxer.audioInfo);const r=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/na,(this.demuxer.dataSize-1)/(na*this.demuxer.audioInfo.blockSizeInBytes)));if(r<0)return null;const a=await this.getPacketAtIndex(r,t);if(a)return a;if(0===r)return null;i(null===this.demuxer.reader.fileSize);let s=await this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,t);for(;s;){const e=await this.getNextPacket(s,t);if(!e)break;s=e}return s}getNextPacket(e,t){i(this.demuxer.audioInfo);const r=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/na);return this.getPacketAtIndex(r+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const ca=e=>{const t=e.filePos,i=mo(e,9),r=new ve(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}},la=1024;class ua extends fi{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.trackBackings=[],this.readingMutex=new T,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();i(this.firstFrameHeader),this.trackBackings=[new da(this)]})())}async advanceReader(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,Oo);if(ae(e)&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const t=qo(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}let e=this.reader.requestSliceRange(this.lastLoadedPos,7,9);if(ae(e)&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const t=ca(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 r=Pe[t.samplingFrequencyIndex];i(void 0!==r);const a=la/r,s={timestamp:this.nextTimestampInSamples/r,duration:a,dataStart:t.startPos,dataSize:t.frameLength};this.loadedSamples.push(s),this.nextTimestampInSamples+=la,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,Oo);if(ae(t)&&(t=await t),!t)break;const i=qo(t);if(!i)break;let r=this.reader.requestSlice(t.filePos,i.size);if(ae(r)&&(r=await r),!r)break;Wo(r,i,this.metadataTags),e=t.filePos+i.size}return this.metadataTags}finally{e()}}}class da{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return this.getSampleRate()/la}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 O}getCodec(){return"aac"}getInternalCodecId(){return i(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){i(this.demuxer.firstFrameHeader);const e=Ie[this.demuxer.firstFrameHeader.channelConfiguration];return i(void 0!==e),e}getSampleRate(){i(this.demuxer.firstFrameHeader);const e=Pe[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return i(void 0!==e),e}getDisposition(){return{...Se}}async getDecoderConfig(){return i(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=mi;else{let e=this.demuxer.reader.requestSlice(i.dataStart,i.dataSize);if(ae(e)&&(e=await e),!e)return null;r=mo(e,i.dataSize)}return new pi(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=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;)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=x(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,Oo);if(ae(e)&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const r=qo(e);if(!r)break;let a=this.reader.requestSlice(e.filePos,r.size);ae(a)&&(a=await a),i(a),Wo(a,r,this.metadataTags),t=e.filePos+r.size}for(t+=4;null===this.reader.fileSize||tn.end-6)return{num:o.num,blockSize:o.blockSize,sampleRate:o.sampleRate,size:n.end-e,isLastFrame:!0};if(255===po(n)){const t=n.filePos;if(po(n)!==(1===this.blockingBit?249:248)){n.filePos=t;continue}n.skip(-2);const i=n.filePos-e,r=this.readFlacFrameHeader({slice:n,isFirstPacket:!1});if(!r){n.filePos=t;continue}if(0===this.blockingBit){if(r.num-o.num!==1){n.filePos=t;continue}}else if(r.num-o.num!==o.blockSize){n.filePos=t;continue}return{num:o.num,blockSize:o.blockSize,sampleRate:o.sampleRate,size:i,isLastFrame:!1}}}}readFlacFrameHeader({slice:e,isFirstPacket:t}){const r=e.filePos,a=mo(e,4),s=new ve(a);if(32764!==s.readBits(15))return null;if(null===this.blockingBit){i(t);const e=s.readBits(1);this.blockingBit=e}else if(1===this.blockingBit){i(!t);if(1!==s.readBits(1))return null}else{if(0!==this.blockingBit)throw new Error("Invalid blocking bit");i(!t);if(0!==s.readBits(1))return null}const n=(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)(s.readBits(4));if(!n)return null;i(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}})(s.readBits(4),this.audioInfo.sampleRate);if(!o)return null;s.readBits(4),s.readBits(3);if(0!==s.readBits(1))return null;const c=(e=>{let t=0;const i=new ve(mo(e,1));for(;1===i.readBits(1);)t++;if(0===t)return i.readBits(7);const r=[],a=t-1,s=new ve(mo(e,a)),n=8-t-1;for(let o=0;oe|t<"uncommon-u16"===t?ko(e)+1:"uncommon-u8"===t?po(e)+1:"number"===typeof t?t:(F(t),void i(!1)))(e,n),u=((e,t)=>"uncommon-u16"===t?ko(e):"uncommon-u16-10"===t?10*ko(e):"uncommon-u8"===t?po(e):"number"===typeof t?t:null)(e,o);if(null===u)return null;if(u!==this.audioInfo.sampleRate)return null;const d=e.filePos-r,h=po(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:c,blockSize:l,sampleRate:u}}async advanceReader(){await this.readMetadata(),i(null!==this.lastLoadedPos),i(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 r=this.loadedSamples[this.loadedSamples.length-1],a={blockOffset:r?r.blockOffset+r.blockSize:0,blockSize:t.blockSize,byteOffset:e,byteSize:t.size};this.lastLoadedPos=this.lastLoadedPos+t.size,this.loadedSamples.push(a),t.isLastFrame&&(this.lastSampleLoaded=!0)}}class fa{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 O}getTimeResolution(){return i(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 i(this.demuxer.audioInfo),0===this.demuxer.audioInfo.totalSamples?null:this.demuxer.audioInfo.totalSamples/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getDisposition(){return{...Se}}async getDecoderConfig(){return i(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(i(this.demuxer.audioInfo),e<0)return null;const r=await this.demuxer.readingMutex.acquire();try{for(;;){const i=x(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{r()}}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 r=this.demuxer.loadedSamples[e];if(!r)return null;let a;if(t.metadataOnly)a=mi;else{let e=this.demuxer.reader.requestSlice(r.byteOffset,r.byteSize);if(ae(e)&&(e=await e),!e)return null;a=mo(e,r.byteSize)}i(this.demuxer.audioInfo);const s=r.blockOffset/this.demuxer.audioInfo.sampleRate,n=r.blockSize/this.demuxer.audioInfo.sampleRate;return new pi(a,"key",s,n,e,r.byteSize)}async getFirstPacket(e){for(;0===this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)}}const ma=9e4,pa=2**33,ga=188,ka="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.",ya=new Set([133,134,162]),ba=new Set;class wa extends fi{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);ae(e)&&(e=await e),i(e);const t=mo(e,205);if(71===t[0]&&71===t[188])this.packetOffset=0,this.packetStride=ga;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 r=this.packetOffset,a=null,s=!1,n=!1;for(;;){const e=await this.readPacketHeader(r);if(!e)break;if(0===e.payloadUnitStartIndicator){r+=this.packetStride;continue}if(n&&!this.elementaryStreams.some(t=>t.pid===e.pid)){r+=this.packetStride;continue}const t=await this.readSection(r,!0,!n);if(!t)break;const o=3,c=32;let l=!1;if(!n&&0!==t.pid){if(!(0===t.payload[0]&&0===t.payload[1]&&1===t.payload[2])){const e=new ve(t.payload),i=e.readAlignedByte();e.skipBits(8*i);l=2===e.readBits(8)}}if(0!==t.pid||s)if(t.pid!==a&&!l||n){const e=this.elementaryStreams.find(e=>e.pid===t.pid);e:if(e&&!e.initialized){const r=Sa(this,t,!0);if(!r)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 a=new Ca(e,r);if("video"===e.info.type){for(;;){if(a.suppliedPacket=null,await a.markNextPacket(),"avc"===e.info.codec){if(!a.suppliedPacket)throw new Error("Invalid AVC video stream; could not extract AVCDecoderConfigurationRecord from any packet.");if(e.info.avcCodecInfo=He(a.suppliedPacket.data),!e.info.avcCodecInfo)continue;const t=e.info.avcCodecInfo.sequenceParameterSets[0];i(t);const r=Xe(t);e.info.width=r.displayWidth,e.info.height=r.displayHeight;const s=r.pixelAspectRatio.num,n=r.pixelAspectRatio.den;s>0&&n>0&&(s>n?(e.info.squarePixelWidth=Math.round(e.info.width*s/n),e.info.squarePixelHeight=e.info.height):(e.info.squarePixelWidth=e.info.width,e.info.squarePixelHeight=Math.round(e.info.height*n/s))),e.info.colorSpace={primaries:f[r.colourPrimaries],transfer:p[r.transferCharacteristics],matrix:k[r.matrixCoefficients],fullRange:!!r.fullRangeFlag},e.info.reorderSize=r.maxDecFrameBuffering;break}if("hevc"===e.info.codec){if(!a.suppliedPacket)throw new Error("Invalid HEVC video stream; could not extract HVCDecoderConfigurationRecord from first packet.");if(e.info.hevcCodecInfo=Ze(a.suppliedPacket.data),!e.info.hevcCodecInfo)continue;const t=e.info.hevcCodecInfo.arrays.find(e=>e.nalUnitType===Ae.SPS_NUT).nalUnits[0];i(t);const r=Je(t);e.info.width=r.displayWidth,e.info.height=r.displayHeight,r.pixelAspectRatio.num>r.pixelAspectRatio.den?(e.info.squarePixelWidth=Math.round(e.info.width*r.pixelAspectRatio.num/r.pixelAspectRatio.den),e.info.squarePixelHeight=e.info.height):(e.info.squarePixelWidth=e.info.width,e.info.squarePixelHeight=Math.round(e.info.height*r.pixelAspectRatio.den/r.pixelAspectRatio.num)),e.info.colorSpace={primaries:f[r.colourPrimaries],transfer:p[r.transferCharacteristics],matrix:k[r.matrixCoefficients],fullRange:!!r.fullRangeFlag},e.info.reorderSize=r.maxDecFrameBuffering;break}throw new Error("Unhandled.")}e.info.decoderConfig={codec:Qt({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 a.markNextPacket(),!a.suppliedPacket)throw new Error(`Couldn't parse first media packet for Elementary Stream with PID ${e.pid}`);if("aac"===e.info.codec){const t=ho.tempFromBytes(a.suppliedPacket.data),i=ca(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=Ie[i.channelConfiguration],e.info.sampleRate=Pe[i.samplingFrequencyIndex]}else if("mp3"===e.info.codec){const t=To(ho.tempFromBytes(a.suppliedPacket.data)),i=ci(t,a.suppliedPacket.data.byteLength);if(!i.header)throw new Error("Invalid MP3 audio stream; could not read frame header from first packet.");e.info.numberOfChannels=hi(i.header.channel),e.info.sampleRate=i.header.sampleRate}else if("ac3"===e.info.codec){const t=St(a.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=Tt[t.acmod]+t.lfeon,e.info.sampleRate=Ee[t.fscod]}else if("eac3"===e.info.codec){const t=It(a.suppliedPacket.data);if(!t)throw new Error("Invalid E-AC-3 audio stream; could not read sync frame from first packet.");const i=xt(t);if(null===i)throw new Error("Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.");e.info.numberOfChannels=Ct(t),e.info.sampleRate=i}else{if("dts"!==e.info.codec)throw new Error("Unhandled.");{const t=Nt(a.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:Jt({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 ve(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),s=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=s;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&&ya.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:ba.has(t)||(be._warn(`Note: MPEG-TS streams with stream_type 0x${t.toString(16)} are not currently supported.`),ba.add(t))}c&&this.elementaryStreams.push({demuxer:this,pid:i,streamType:t,initialized:!1,firstSection:null,canBeTrustedWithKeyPackets:!1,info:c,referencePesPackets:[]})}n=!0}else{const e=new ve(t.payload),i=e.readAlignedByte();e.skipBits(8*i),e.skipBits(14);const r=e.readBits(10);for(e.skipBits(40);8*(r+o)-e.pos>c;){const t=e.readBits(16);e.skipBits(3);const i=e.readBits(13);if(0!==t){if(null!==a)throw new Error("Only files with a single program are supported.");a=i}}if(null===a)throw new Error("Program Association Table must link to a Program Map Table.");s=!0}if(n&&this.elementaryStreams.every(e=>e.initialized))break;r+=this.packetStride}if(!n){if(!s)throw new Error("No Program Association Table found in the file.");throw new Error("No Program Map Table found in the file.")}for(const i of this.elementaryStreams)i.initialized&&("video"===i.info.type?this.trackBackingEntries.push(new Pa(i)):this.trackBackingEntries.push(new Ia(i)))})())}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!==I(this.sectionEndPositions,r,e=>e)){l=!1;break}}if(l){const e=x(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(ae(t)&&(t=await t),!t)return null;if(71!==po(t))throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");const i=ko(t);return{payloadUnitStartIndicator:i>>14&1,pid:8191&i,adaptationFieldControl:po(t)>>4&3}}async readPacket(e){let t=this.reader.requestSlice(e,ga);if(ae(t)&&(t=await t),!t)return null;const i=mo(t,ga);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>=pa-t?-8589934592:pa}}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 ve(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(ka);return{sectionStartPos:t.startPos,sectionEndPos:t.endPos,pts:n,randomAccessIndicator:t.randomAccessIndicator}},Sa=(e,t,r)=>{i(null!==t.endPos);const a=Ta(e,t,r);if(!a)return null;const s=new ve(t.payload);s.skipBits(32);const n=s.readBits(16);s.skipBits(16);const o=s.readBits(8),c=s.pos+8*o;s.pos=c;const l=c/8;i(Number.isInteger(l));const u=t.payload.subarray(l,n>0?6+n:t.payload.byteLength);return{...a,data:u}};class va{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 r=0;for(const a of e.trackBackingEntries)if(a.getType()===t&&r++,i(a instanceof va),a.elementaryStream===this.elementaryStream)break;return r}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.elementaryStream.streamType}getName(){return null}getLanguageCode(){return O}getDisposition(){return{...Se,primary:!1}}getTimeResolution(){return ma}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 pi(i.metadataOnly?mi:e.data,r,e.pts/ma,Math.max(t/ma,0),e.sequenceNumber,e.data.byteLength)}async getFirstPacket(e){const t=this.elementaryStream.firstSection;i(t);const r=Sa(this.elementaryStream.demuxer,t,!0);i(r);const a=new Ca(this.elementaryStream,r),s=new Ba(this,a),n=await s.readNext();if(!n)return null;const o=this.createEncodedPacket(n.packet,n.duration,e);return this.packetBuffers.set(o,s),this.packetSectionStarts.set(o,n.packet.sectionStartPos),o}async getNextPacket(e,t){let r=this.packetBuffers.get(e);if(r){const i=await r.readNext();if(!i)return null;this.packetBuffers.delete(e);const a=this.createEncodedPacket(i.packet,i.duration,t);return this.packetBuffers.set(a,r),this.packetSectionStarts.set(a,i.packet.sectionStartPos),a}const a=this.packetSectionStarts.get(e);if(void 0===a)throw new Error("Packet was not created from this track.");const s=this.elementaryStream.demuxer,n=await s.readSection(a,!0);i(n);const o=Sa(s,n,!0);i(o);const c=new Ca(this.elementaryStream,o);r=new Ba(this,c);const l=e.sequenceNumber;for(;;){const e=await r.readNext();if(!e)return null;if(e.packet.sequenceNumber>l){const i=this.createEncodedPacket(e.packet,e.duration,t);return this.packetBuffers.set(i,r),this.packetSectionStarts.set(i,e.packet.sectionStartPos),i}}}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,r){const s=L(e*ma),n=this.elementaryStream.demuxer,{reader:o,seekChunkSize:c}=n,l=this.elementaryStream.pid,u=async(e,t,i)=>{let r=e;for(;re.pts),g=-1!==p?m[p]:null;if(g&&s-g.pts<45e3)f=g.sectionStartPos;else{let e=0;if(null!==o.fileSize){const t=Math.ceil(o.fileSize/c);if(t>1){let i=0,r=t-1;for(e=i;i<=r;){const t=Math.floor((i+r)/2),a=q(t*c,n.packetStride)+h.sectionStartPos,o=a+c,l=await u(a,o,!1);l?l.pesPacketHeader.pts<=s?(e=t,i=t+1):r=t-1:r=t-1}}}f=q(e*c,n.packetStride)+h.sectionStartPos}const k=await u(f,o.fileSize??1/0,!1);let y=k?.pesPacketHeader??null;y||(y=h);const b=this.getReorderSize(),w=async(e,t)=>{const o=await n.readSection(e,!0);i(o);const c=Sa(n,o,!0);i(c);const l=new Ca(this.elementaryStream,c),u=new Ba(this,l);for(;;){if((a(u.presentationOrderPackets)?.pts??-1/0)>=s)break;if(!(await u.readNextPacket()))break}const d=R(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();i(m);const p=this.createEncodedPacket(m.packet,m.duration,r);return this.packetBuffers.set(p,u),this.packetSectionStarts.set(p,m.packet.sectionStartPos),p};if(!t||this.allPacketsAreKeyPackets()){e:for(;;){let e=y.sectionStartPos+n.packetStride;for(;;){const t=await n.readPacketHeader(e);if(!t)break e;if(t.pid===l&&1===t.payloadUnitStartIndicator){const t=await n.readSection(e,!1);if(t){const e=Ta(n,t,!1);if(e&&null!==e.pts){if(e.pts>s)break e;y=e,xa(this.elementaryStream,y);break}}}e+=n.packetStride}}e:for(let e=0;e=n.packetOffset;){const t=await n.readPacketHeader(e);if(!t)break e;if(t.pid===l&&1===t.payloadUnitStartIndicator){const t=await n.readSection(e,!1);if(t){const e=Ta(n,t,!1);if(e&&null!==e.pts){y=e;break}}}e-=n.packetStride}}return w(y.sectionStartPos,e=>e.pts<=s)}{let e=f,t=null;const r=!this.elementaryStream.canBeTrustedWithKeyPackets;for(;;){let a=null;const f=e<=h.sectionStartPos;let m,p=null;if(f)m=h,p=d;else{const t=await u(e,o.fileSize??1/0,r);m=t?.pesPacketHeader??null,p=t?.section??null}let g=!1,k=0;e:for(;m&&!(null!==t&&m.sectionStartPos>=t);){if(m.pts<=s){let e;if(this.elementaryStream.canBeTrustedWithKeyPackets)e=1===m.randomAccessIndicator;else{i(p);const t=Sa(n,p,!0);i(t);const r=new Ca(this.elementaryStream,t);await r.markNextPacket(),e=1===r.suppliedPacket?.randomAccessIndicator}e&&(a=m)}if(m.pts>s&&(g=!0),g&&(k++,k>b))break;let e=m.sectionStartPos+n.packetStride;for(;;){const t=await n.readPacketHeader(e);if(!t)break e;if(t.pid===l&&1===t.payloadUnitStartIndicator){const t=await n.readSection(e,r);if(t){const e=Ta(n,t,!1);if(e&&null!==e.pts){m=e,p=t,xa(this.elementaryStream,m);break}}}e+=n.packetStride}}if(a){let e=a;if(0===k)e:for(let i=0;i=n.packetOffset;){const i=await n.readPacketHeader(t);if(!i)break e;if(i.pid===l&&1===i.payloadUnitStartIndicator){const i=await n.readSection(t,r);if(i){const t=Ta(n,i,!1);if(t&&null!==t.pts){e=t;break}}}t-=n.packetStride}}const t=await w(e.sectionStartPos,e=>e.pts<=s&&1===e.randomAccessIndicator);return i(t),t}if(f)return null;t=e,e=Math.max(q(e-h.sectionStartPos-c,n.packetStride)+h.sectionStartPos,h.sectionStartPos)}}}}class Pa extends va{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 i(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}}class Ia extends va{getType(){return"audio"}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}async getDecoderConfig(){return i(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 0}}const xa=(e,t)=>{const i=e.referencePesPackets,r=x(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 i(e),e}async bufferData(e){const t=this.endPos+e;for(;this.endPos=u)break;d=e;const i=c+d;if(d+3>=u){this.seekTo(i);break}const h=l[d+1],f=l[d+2],m=l[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=l[k];let T,S,v;if("avc"===t)T=Le(w),S=T===Re.NON_IDR_SLICE||T===Re.SLICE_DPA||T===Re.IDR,v=T===Re.SEI||T===Re.SPS||T===Re.PPS||T===Re.AUD;else{T=Ye(w);if(((1&w)<<5|l[k+1]>>3)>0){d+=p;continue}S=T<=Ae.RASL_R||T>=Ae.BLA_W_LP&&T<=21,v=T>=Ae.VPS_NUT&&T<=37||T===Ae.PREFIX_SEI_NUT||T>=41&&T<=44||T>=48&&T<=55}let P=!1;if(S){let e;if("avc"===t){const t=l.subarray(y,y+b),i=s(new ve(t));e=!n||i<=o,o=i}else e=l[y]>>7===1;e&&(n?P=!0:n=!0)}else v&&n&&(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,r=128;for(;;){let a=this.ensureBuffered(r);ae(a)&&(a=await a);const s=this.currentPos;for(;this.currentPos-s>6,o=63&s[4];if(3===n||o>37){this.seekTo(t+1);continue}const c=vt[3*o+n];i(void 0!==c),this.seekTo(t),a=this.ensureBuffered(c),ae(a)&&(a=await a);const l=Math.round(13824e4/e.info.sampleRate);return this.supplyPacket(a,l)}if("eac3"===t){if(11!==r)continue;this.skip(-1);const t=this.currentPos;let i=this.ensureBuffered(5);if(ae(i)&&(i=await i),i<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=Pt[n];this.seekTo(t),i=this.ensureBuffered(s),ae(i)&&(i=await i);const c=256*o,l=Math.round(c*ma/e.info.sampleRate);return this.supplyPacket(i,l)}if("dts"===t){if(127!==r&&100!==r)continue;this.skip(-1);const t=this.currentPos;let i=this.ensureBuffered(18);if(ae(i)&&(i=await i),i<18)return;const a=this.readBytes(18),s=Lt(a);let n=s?null:zt(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);ae(i)&&(i=await i),n=zt(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(ae(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 r;if(i(-1!==t),t===this.presentationOrderPackets.length-1)r=this.lastDuration;else{r=this.presentationOrderPackets[t+1].pts-e.pts,this.lastDuration=r}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:r}}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(i(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 Ea="application/vnd.apple.mpegurl",_a="#EXT-X-STREAM-INF:",Ra="#EXT-X-I-FRAME-STREAM-INF:",Fa="#EXT-X-MEDIA:",Aa="#EXTINF:",Da="#EXT-X-MAP:",Ma="#EXT-X-KEY:",Na="#EXT-X-MEDIA-SEQUENCE:",Oa="#EXT-X-BYTERANGE:",La="#EXT-X-PROGRAM-DATE-TIME:",za="#EXT-X-TARGETDURATION:",Ua="#EXT-X-PLAYLIST-TYPE:",qa=e=>0===e.length||e.startsWith("#")&&!e.startsWith("#EXT");class Wa{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=de(e,e=>"video"===e.getType())+1;e.push(new ja(this,t,i))}else if("audio"===t.type){const i=de(e,e=>"audio"===e.getType())+1;e.push(new Ka(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=de(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=de(e,e=>"audio"===e.getType())+1;e.push(new Ka(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 Va{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(),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()}async createAdjustedPacket(e,t,r){i(e.sequenceNumber>=0),i(this.segmentedInput.firstSegment);const a=await this.segmentedInput.getMediaOffset(t,r.input),s=t.timestamp-this.segmentedInput.firstSegment.timestamp,n=e.clone({timestamp:U(e.timestamp+a,await r.getTimeResolution()),sequenceNumber:Math.floor(1e8*s)+e.sequenceNumber});return this.packetInfos.set(n,{segment:t,track:r,sourcePacket:e}),n}async getFirstPacket(e){await this.hydrate(),i(this.firstInputTrack),i(this.firstSegment);let t=this.firstInputTrack,r=this.firstSegment;for(;;){if(t){const i=await t._backing.getFirstPacket(e);if(i)return this.createAdjustedPacket(i,r,t)}if(r=await this.segmentedInput.getNextSegment(r,{skipLiveWait:e.skipLiveWait}),!r)break;const i=this.segmentedInput.getInputForSegment(r);t=(await i.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 Va{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 Ka extends Va{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())}}ce();const Xa=1/0;"undefined"!==typeof FinalizationRegistry&&new FinalizationRegistry(e=>{e()});class $a extends ge{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 lo;return this._sizePromise??(this._sizePromise=(async()=>{let e=this._getFileSize();return void 0!==e||(await this._read(0,1,0,Xa),e=this._getFileSize(),i(void 0!==e)),e})())}async getSize(){if(this._disposed)throw new lo;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 ls(this,e,t)}_dispatchRead(e,t){this.onread?.(e,t),this._emit("read",{start:e,end:t})}ref(){return new Ga(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){this._refCount--,0===this._refCount&&(this._dispose(),this._disposed=!0)}}class Ga{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;i(e._refCount>0),e._decrementRefCount(),e._refFinalizationRegistry?.unregister(this),this._freed=!0,this._source=null}[Symbol.dispose](){this.freed||this.free()}}class Qa extends $a{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 $a||e instanceof Ga))throw new TypeError("requestHandler must return or resolve to a Source or SourceRef.");const i=e instanceof $a?e.ref():e;return(t=i.source)._usedForHls||(t._usedForHls=this._usedForHls),i};return ae(t)?t.then(i):i(t)}}const Ya=(e,t)=>e.path===t.path;class Ja extends Qa{constructor(){super(...arguments),this._root=null,this._rootRequest=null}_read(e,t,r,a){if(!this._root){if(!this._rootRequest){const e=this._resolveRequest({path:this.rootPath,isRoot:!0}),t=e=>{const t=e instanceof $a?e.ref():e;return this._root=t,this._rootRequest=null,t};ae(e)?this._rootRequest=e.then(t):(t(e),i(this._root))}if(this._rootRequest)return this._rootRequest.then(i=>i.source._read(e,t,r,a))}return this._root.source._read(e,t,r,a)}_getFileSize(){if(this._root)return this._root.source._getFileSize()}_dispose(){this._root?this._root.free():this._rootRequest&&this._rootRequest.then(e=>e.free())}}const Za="undefined"!==typeof FinalizationRegistry?new FinalizationRegistry(e=>{e.cancel().catch(()=>{})}):null;class es extends $a{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&&(!le(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 cs({maxCacheSize:t.maxCacheSize??8388608,maxWorkerCount:4,runWorker:this._runWorker.bind(this),onIdleWorkerRemoved:e=>{const t=this._readers.get(e);t&&(this._readers.delete(e),Za?.unregister(e),t.cancel().catch(()=>{}))},prefetchProfile:os.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){i(e.strictTarget);let t=this._readers.get(e);if(void 0===t){if("stream"in this._blob&&!Y()&&!1!==this._options.useStreamReader){t=this._blob.slice(e.currentPos).stream().getReader(),Za?.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 be._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)},is=new Set;class rs extends Qa{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&&(!le(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 rs(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??ts,this._requestInit={...t.requestInit};let i=null;if(t.requestInit?.headers){const e={...X(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=ss(i);e&&(this._offset=e.offset,this._length=e.length)}this._orchestrator=new cs({maxCacheSize:t.maxCacheSize??67108864,maxWorkerCount:t.parallelism??2,runWorker:this._runWorker.bind(this),prefetchProfile:os.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:N(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 ae(s)?s.then(n):n(s)}async _runWorker(e){for(;;){const i=new AbortController,r=await $(this._options.fetchFn??fetch,this._url,K(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")||is.has(e.origin)||(be._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.`),is.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){be._error("Error while reading response stream. Attempting to resume.",t),await pe(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(),r=0,a=0;const s=new ReadableStream({pull:async e=>{for(;;){let s;try{s=await t.read()}catch(i){if(this._disposed)throw i;const e=this._getRetryDelay(1,i,this._url);if(null===e)throw i;be._error("Error while reading response stream. Attempting to resume.",i),await pe(1e3*e);const s=await $(this._options.fetchFn??fetch,this._url,K(this._requestInit,{headers:{Range:`bytes=${r}-`}}),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(),a=206===s.status?0:r;continue}if(s.done)return void e.close();let n=s.value;if(a>0){const e=Math.min(a,n.length);a-=e,n=n.subarray(e)}if(0!==n.length)return r+=n.length,void e.enqueue(n)}},cancel:()=>t.cancel()}),n=new ns(s,{maxCacheSize:this._orchestrator.options.maxCacheSize,handleUnhandledError:this._options.handleUnhandledError});n._endIndex=this._orchestrator.fileSize,n._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.",n.on("read",({start:e,end:t})=>this._dispatchRead(e,t)),this._sequentialBacking=n;const o=new Set;for(const i of this._orchestrator.workers){for(const e of i.pendingSlices)o.add(e);i.aborted=!0,i.pendingSlices.length=0}for(const i of this._orchestrator.queuedReads)for(const e of i.pendingSlices)o.add(e);this._orchestrator.workers.length=0,this._orchestrator.queuedReads.length=0;for(const c of o){const e=n._read(c.start,c.start+c.bytes.length);ae(e)?e.then(e=>{e?(i(e.offset===c.start),c.resolve(e.bytes)):c.resolve(null)},e=>c.reject(e)):(i(null===e),c.resolve(null))}}_dispose(){this._orchestrator.dispose(),this._sequentialBacking&&(this._sequentialBacking._disposed=!0,this._sequentialBacking._dispose())}}const as=/^bytes=(\d+)-(\d*)$/,ss=e=>{const t=as.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=x(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}=B();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 lo);this._pendingSlices.length=0,this._cache.length=0,this._reader?.cancel()}}const os={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(ne(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 cs{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,r,a){i(!this.disposed);const s=this.options.prefetchProfile(e,t,this.workers),n=Math.max(s.start,r),o=Math.min(s.end,this.fileSize??1/0,a);i(n<=e&&t<=o);let c=null;const u=x(this.cache,e,e=>e.start),d=-1!==u?this.cache[u]:null;d&&d.start<=e&&t<=d.end&&(d.age=this.nextAge++,c={bytes:d.bytes,view:d.view,offset:d.start});const h=x(this.cache,n,e=>e.start),f=c?null:new Uint8Array(t-e);let m=0,p=n;const g=[];if(-1!==h){for(let r=h;r=o)break;if(a.end<=n)continue;const s=Math.max(n,a.start),c=Math.min(o,a.end);if(i(s<=c),p=f.length&&(c={bytes:f,view:l(f),offset:e}),0===g.length)return i(c),c;const{promise:k,resolve:y,reject:b}=B(),w=[];for(const i of g){const r=Math.max(e,i.start),a=Math.min(t,i.end);r===i.start&&a===i.end?w.push(i):re.hole.start),r=-1!==t?this.queuedReads[t]:null;for(r&&i.start<=r.hole.end?(r.hole.end=Math.max(r.hole.end,i.end),r.strictTarget&&(r.strictTarget=e),T&&r.pendingSlices.push(T)):(t++,r={hole:{start:i.start,end:i.end},strictTarget:e,pendingSlices:T?[T]:[],age:this.nextAge++},this.queuedReads.splice(t,0,r));t+1r.hole.end)break;r.hole.end=Math.max(r.hole.end,e.hole.end),r.pendingSlices.push(...e.pendingSlices),r.strictTarget&&(r.strictTarget=e.strictTarget),r.age=Math.min(r.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)}}):(i(f),c=k.then(t=>t&&{bytes:t,view:l(t),offset:e})),c}checkHoleAgainstWorker(e,t,i){if(ne(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 i=0;it.start&&(t.start=a),t.end<=t.start&&(s.holes.splice(e,1),e--)}0===s.holes.length&&(s.resolve(s.bytes),e.pendingSlices.splice(i,1),i--)}for(let i=0;ie){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);i(-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=x(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=l(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=l(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 ae(a)?a.then(s):s(a)}_dispose(){this._ref?.free()}ref(){return this._ref??(this._ref=this._baseSource.ref()),super.ref()}}var us=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},ds=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 hs=/^0[xX][0-9a-fA-F]+$/,fs=/^data:.*;base64,/i;class ms extends Ha{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 pe(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 r=us(t,await this.demuxer.input._getSourceUncached({path:this.rootPath,isRoot:!1}),!1),a=new uo(r.source),s=await a.requestEntireFile();i(s),e=Ro(s,s.length,{ignore:qa}),r.source instanceof Qa&&(this.rootPath=r.source.rootPath)}catch(T){t.error=T,t.hasError=!0}finally{ds(t)}}const t=!1!==this.input._formatOptions.hls?.offsetTimestampsByDateTime;let r=!1,s=0,n=null,o=null,c=null,u=0,d=null,h=null,f=null,m=null,p=null,g=null,k=!1,y=a(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=>{u=e,y&&(i(null!==y.sequenceNumber),y.sequenceNumber0&&null!==g&&(s=u*g),k=!0);const e=T.slice(8),t=e.indexOf(","),i=-1===t?e:e.slice(0,t),r=Number(i);if(!Number.isFinite(r)||r<0)throw new Error(`Invalid #EXTINF tag duration '${i}'.`);o=r}else if(T.startsWith(Da)){const e=new Wa(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 r=null;if(null!==i&&(r=b(i)),r&&null===r.offset)throw new Error("Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset.");if(!y){const e={path:ue(this.rootPath,t),offset:r?.offset??0,length:r?.length??null};if("AES-128"===c?.method&&!c.iv)throw new Error("IV attribute must be set on #EXT-X-KEY tag preceding the #EXT-X-MAP tag.");h={timestamp:s,unixEpochTimestamp:n,firstSegment:null,sequenceNumber:null,location:e,duration:0,encryption:c,initSegment:null,lastProgramDateTimeSeconds:p}}o=null,null===m?f=null:m=null}else if(T.startsWith(Ma)){const e=new Wa(T.slice(11)),t=e.get("method");if("NONE"===t)c=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(!hs.test(r))throw new Error(`Unsupported IV format '${r}'.`);let e=r.slice(2);e=e.padStart(32,"0"),i=new Uint8Array(Pi);for(let t=0;t=8&&112===t[4]&&115===t[5]&&115===t[6]&&104===t[7]){const e=l(t).getUint32(0);r=gi(t.subarray(8,Math.min(e,t.length)))}}c={method:t,psshBox:r}}}}else if(T.startsWith(Na)){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(Oa)){const e=b(T.slice(17));if(null===e.offset){if(null===f)throw new Error("Invalid M3U8 file; #EXT-X-BYTERANGE without offset requires a previous byte range.");e.offset=f}m=e,f=e.offset+e.length}else if(T.startsWith(La)){if(y)continue;const e=T.slice(25),i=Date.parse(e);if(!Number.isFinite(i))continue;const r=i/1e3;if(p===r)continue;if(null===p&&this.segments.length>0){const e=a(this.segments),i=r-(e.timestamp+e.duration);for(const r of this.segments)r.unixEpochTimestamp=r.timestamp+i,t&&(r.timestamp=r.unixEpochTimestamp)}p=r,n=r,t&&(s=r)}else if("#EXT-X-DISCONTINUITY"===T)d=null;else if(T.startsWith(za)){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(Ua)){"vod"===T.slice(21).toLowerCase()&&(this.streamHasEnded=!0)}}}else{if("#EXTM3U"!==T)throw new Error("Invalid M3U8 file; expected first line to be #EXTM3U.");r=!0}}if(!r)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=x(this.segments,e,e=>e.timestamp);if(-1===r)return null;if(r0;for(;;){if(ae.segment===t);if(r)return r.age=this.nextInputCacheAge++,r.input;let a=null;(t.initSegment||t.firstSegment)&&(a=this.getInputForSegment(t.initSegment??t.firstSegment));const s={...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=>ki(e,r))||(i=[...i,r]),this.input._formatOptions.isobmff.resolveKeyId({...e,psshBoxes:i})})}},n=new oo({source:new Ja(t.location.path,async e=>{i(e.isRoot);const r={...e,isRoot:!1};let a;const s=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;i(e.iv);let n=await this.input._getSourceCached(r);if(s){const e=n.source.slice(t.location.offset,t.location.length??void 0).ref();n.free(),n=e}const o=((e,t,i)=>{let r=!1,a=0;const s=new Ai;return new ReadableStream({pull:async n=>{r||(s.init(await t()),r=!0);let o=e.requestSliceRange(a,0,65552);if(ae(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=mo(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 uo(n.source),async()=>{const t={stack:[],error:void 0,hasError:!1};try{const i=us(t,await this.input._getSourceCached({path:e.keyUri,isRoot:!1},no),!1),r=new uo(i.source),a=await r.requestSlice(0,Pi);if(!a)throw new Error("Invalid AES-128 key; expected at least 16 bytes of data.");return{key:mo(a,Pi),iv:e.iv}}catch(i){t.error=i,t.hasError=!0}finally{ds(t)}},()=>{n.free()});a=new ns(o).ref()}else i(!1);else if(a=await this.input._getSourceCached(r),s){const e=a.source.slice(t.location.offset,t.location.length??void 0).ref();a.free(),a=e}return a}),formats:this.input._formats.filter(e=>!(e instanceof Ds)),initInput:a??void 0,formatOptions:s});n._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:n,age:this.nextInputCacheAge++});if(this.inputCache.length>4){const e=he(this.inputCache,e=>e.age);i(-1!==e),this.inputCache.splice(e,1)}return n}async getLiveRefreshInterval(){return 0===this.getRemainingWaitTimeMs()&&await this.runUpdateSegments(),this.streamHasEnded?null:this.refreshInterval}}class ps extends fi{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()=>{i(this.input._rootSource instanceof Qa);const e=await this.input._reader.requestEntireFile();i(e);const t=Ro(e,e.length,{ignore:qa}),{rootPath:r}=this.input._rootSource,a=[],s=[];for(let i=1;i"video"===e.attributes.get("type").toLowerCase()).map(e=>e.attributes.get("group-id")))],o=[...new Set(s.filter(e=>"audio"===e.attributes.get("type").toLowerCase()).map(e=>e.attributes.get("group-id")))],c=await Promise.all(a.map(async(e,t)=>{const a=[],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=>qt.includes(ii(e))),f=l.some(e=>Ht.includes(ii(e)));if(null!==u&&!h){if(!n.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=s.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 a=ue(r,t),s=this.getSegmentedInputForPath(a),n=(await s.getTrackBackings()).find(e=>"video"===e.getType());if(!n||null===await n.getCodec())break e;const o=await n.getDecoderConfig().then(e=>e?.codec??null);i(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=s.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 a=ue(r,t),s=this.getSegmentedInputForPath(a),n=(await s.getTrackBackings()).find(e=>"audio"===e.getType());if(!n||null===await n.getCodec())break e;const o=await n.getDecoderConfig().then(e=>e?.codec??null);i(null!==o),l.push(o)}}l=[...new Set(l)];let m=null,p=null;const g=e.attributes.getAsNumber("bandwidth");i(null!==g);const k=e.attributes.getAsNumber("average-bandwidth"),y=e.attributes.get("name");for(const i of l){const r=ii(i);if(null!==r)if(qt.includes(r)){if(null!==m)throw new Error("Unsupported M3U8 file; multiple video codecs found in the CODECS attribute of a variant stream.");m=i;const r=e.attributes.get("video");if(null===r){const i=e.attributes.get("resolution");let r=null,s=null;if(i){const e=i.match(/^(\d+)x(\d+)$/);e&&(r=Number(e[1]),s=Number(e[2]))}a.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:O,lineNumber:e.lineNumber,fullPath:e.fullPath,fullCodecString:m,pairingMask:1n<0?r:null}})}else{if(!o.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 s){const s=i.attributes.get("group-id"),n=i.attributes.get("type");if(s!==r||"audio"!==n.toLowerCase())continue;const o=i.attributes.get("channels")??e.attributes.get("channels"),c=null!==o?Number(o.split("/")[0]):null;a.push({id:-1,demuxer:this,backingTrack:null,default:bs(i.attributes),autoselect:bs(i.attributes)||ws(i.attributes),languageCode:Ts(i.attributes.get("language")),lineNumber:i.lineNumber,fullPath:i.fullPath??e.fullPath,fullCodecString:p,pairingMask:1n<0?c:null}})}}}}return a})),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===O&&(t.languageCode=e.languageCode)):(e.id=l.length+1,l.push(e))};for(const i of c)for(const e of i)u(e);l.sort((e,t)=>e.lineNumber-t.lineNumber),this.trackBackings=[];for(const i of l)"video"===i.info.type?this.trackBackings.push(new ks(i)):this.trackBackings.push(new ys(i));this.internalTracks=l})())}async getTrackBackings(){return await 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 ms(this,e,i,null),this.segmentedInputs.push(t),t}async getMetadataTags(){return{}}async getMimeType(){return Ea}dispose(){if(this.segmentedInputs){for(const e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}}class gs{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 r=(await e.getTrackBackings()).filter(e=>e.getType()===this.getType());if(1===r.length)t=r[0];else if(this instanceof ks){for(const i of r)if(await i.getCodec()===this.getCodec()){t=i;break}}else{i(this instanceof ys);for(const e of r)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{...Se,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}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 ks extends gs{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())}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 ys extends gs{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}async getDecoderConfig(){return await this.hydrate(),this.backingAudioTrack.getDecoderConfig()}}const bs=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}".`)},Ts=e=>{if(null===e)return O;const t=e.split("-")[0];return t||O};class Ss{constructor(){this._isIsobmff=!1}}class vs extends Ss{constructor(){super(...arguments),this._isIsobmff=!0}async _getMajorBrand(e){let t=e._reader.requestSlice(0,12);if(ae(t)&&(t=await t),!t)return null;t.skip(4);const i=_o(t,4);return"ftyp"!==i&&"styp"!==i?null:_o(t,4)}_createDemuxer(e){return new Di(e)}}class Ps extends vs{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(ae(t)&&(t=await t),!t)return!1;let r=To(t),a=8;if(1===r){let t=e._reader.requestSlice(i+8,8);if(ae(t)&&(t=await t),!t)return!1;r=Io(t),a=16}if(r8)return!1;if(nr(i,r)!==Ji.EBML)return!1;const a=cr(i);if("number"!==typeof a)return!1;let s=e._reader.requestSlice(i.filePos,a);if(ae(s)&&(s=await s),!s)return!1;const n=i.filePos;for(;s.filePos<=n+a-2;){const e=lr(s);if(!e)break;const{id:i,size:r}=e,a=s.filePos;if(void 0===r)return!1;switch(i){case Ji.EBMLVersion:if(1!==nr(s,r))return!1;break;case Ji.EBMLReadVersion:if(1!==nr(s,r))return!1;break;case Ji.DocType:if(ur(s,r)!==t)return!1;break;case Ji.DocTypeVersion:if(nr(s,r)>4)return!1}s.filePos=a+r}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new Lr(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}}class Cs extends xs{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}}class Bs extends Ss{async _canReadInput(e){let t=0;for(;;){let i=e._reader.requestSlice(t,Oo);if(ae(i)&&(i=await i),!i)break;const r=qo(i);if(!r)break;t=i.filePos+r.size}const i=await Wr(e._reader,t,t+4096);if(!i)return!1;const r=i.header,a=oi(r.mpegVersionId,r.channel);let s=e._reader.requestSlice(i.startPos+a,4);if(ae(s)&&(s=await s),!s)return!1;const n=To(s);if(n===si||n===ni)return!0;t=i.startPos+i.header.totalSize;const o=await Wr(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 Hr(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}}class Es extends Ss{async _canReadInput(e){let t=e._reader.requestSlice(0,12);if(ae(t)&&(t=await t),!t)return!1;const i=_o(t,4);if("RIFF"!==i&&"RIFX"!==i&&"RF64"!==i)return!1;t.skip(4);return"WAVE"===_o(t,4)}_createDemuxer(e){return new sa(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}}class _s extends Ss{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return ae(t)&&(t=await t),!!t&&"OggS"===_o(t,4)}_createDemuxer(e){return new Zr(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}}class Rs extends Ss{async _canReadInput(e){let t=0;for(;;){let i=e._reader.requestSlice(t,Oo);if(ae(i)&&(i=await i),!i)break;const r=qo(i);if(!r)break;t=i.filePos+r.size}let i=e._reader.requestSlice(t,4);return ae(i)&&(i=await i),!!i&&"fLaC"===_o(i,4)}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new ha(e)}}class Fs extends Ss{async _canReadInput(e){let t=0;for(;;){let i=e._reader.requestSlice(t,Oo);if(ae(i)&&(i=await i),!i)break;const r=qo(i);if(!r)break;t=i.filePos+r.size}let i=e._reader.requestSliceRange(t,7,9);if(ae(i)&&(i=await i),!i)return!1;const r=ca(i);if(!r)return!1;if(t+=r.frameLength,i=e._reader.requestSliceRange(t,7,9),ae(i)&&(i=await i),!i)return!1;const a=ca(i);return!!a&&(r.objectType===a.objectType&&r.samplingFrequencyIndex===a.samplingFrequencyIndex&&r.channelConfiguration===a.channelConfiguration)}_createDemuxer(e){return new ua(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}}class As extends Ss{async _canReadInput(e){let t=e._reader.requestSlice(0,205);if(ae(t)&&(t=await 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 wa(e)}get name(){return"MPEG Transport Stream"}get mimeType(){return"video/MP2T"}}class Ds extends Ss{async _canReadInput(e){let t=e._reader.requestSlice(0,7);if(ae(t)&&(t=await t),!t)return!1;if(!("#EXTM3U"===_o(t,7)))return!1;if(!(e._rootSource instanceof Qa))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 ps(e)}get name(){return"HTTP Live Streaming (HLS)"}get mimeType(){return Ea}}const Ms=new Ps,Ns=new Is,Os=new xs,Ls=new Cs,zs=new Bs,Us=new Es,qs=new _s,Ws=new Fs,Hs=new Rs,Vs=new As,js=new Ds,Ks=[js,Ms,Ns,Os,Ls,Us,qs,Hs,zs,Ws,Vs],Xs=[js,Ms,Ns,zs,Ws,Vs];var $s=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});ce();let Gs=-1/0,Qs=-1/0,Ys=null;"undefined"!==typeof FinalizationRegistry&&(Ys=new FinalizationRegistry(e=>{const t=performance.now();"video"===e.type?(t-Gs>=1e3&&(be._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."),Gs=t),"undefined"!==typeof VideoFrame&&e.data instanceof VideoFrame&&e.data.close()):(t-Qs>=1e3&&(be._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."),Qs=t),"undefined"!==typeof AudioData&&e.data instanceof AudioData&&e.data.close())}));class Js{constructor(){this._referenceCount=0,this._lastAllocationBuffer=null}}const Zs=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],en=new Set(Zs);class tn{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||!en.has(t.format))throw new TypeError("init.format must be one of: "+Zs.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&&me(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??hn(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?c(e):c(e).slice(),this._layout=i,this.colorSpace=new on(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&&me(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 on(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&&me(t.visibleRect,"init.visibleRect"),"undefined"!==typeof VideoFrame)return new tn(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:Z(),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 on({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else{if(!(e instanceof Js))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&&!Zs.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=fe({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),Ys?.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 Js?new tn(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):cn(this._data)?new tn(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):this._data instanceof Uint8Array?(i(this._layout),new tn(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 tn(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||(Ys?.unregister(this),this._data instanceof Js?(this._data._referenceCount--,0===this._data._referenceCount&&this._data.close()):cn(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(dn(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(cn(this._data))return this._data.allocationSize(e);return mn(this,e).allocationSize}async copyTo(e,t={}){if(!w(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(dn(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(i(null!==this._data),cn(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 Js)){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 tn))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(u){i.error=u,i.hasError=!0}finally{$s(i)}}}const r=mn(this,t);i(this.format);const a=c(e);if(a.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.');n=e}else if(this._data instanceof Uint8Array)i(this._layout),i(this._layout.length===s.length),n=this._layout.map((e,t)=>{const i=Math.ceil(this.codedHeight/s[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);n=[{data:c(t.data),stride:4*this.codedWidth}]}const o=[],l=s.length;for(let i=0;is.byteLength)throw new Error("Source buffer OOB read.");if(l+u>a.byteLength)throw new Error("Destination buffer OOB write.");const i=s.subarray(c,c+u);a.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"),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 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 cn(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,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&&un(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=ln(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?nn(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(i(null!==this._data),this._data instanceof Js||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&&un(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=r(this.rotation+(e.rotate??0)),[i,a]=t%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let s=e.crop;s&&(s=ln(s,i,a));const n=s?s.width:i,o=s?s.height:a,c=n/o;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=n,u=o),l=z(l,e.roundDimensionsTo??1),u=z(u,e.roundDimensionsTo??1);const d={width:l,height:u,fit:e.fit??"fill",rotation:t,crop:s??{left:0,top:0,width:i,height:a},alpha:e.alpha??"keep"};for(const r of rn){let e=r(this,d);if(ae(e)&&(e=await e),null!==e)return e}const{canvas:h,context:f,isNew:m}=nn(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 tn(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 rn=[],an=[];let sn=0;const nn=(e,t)=>{for(const a of an)if(a.canvas.width===e&&a.canvas.height===t)return a.age=sn++,{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 an.length>=3&&an.splice(he(an,e=>e.age),1),an.push({canvas:i,context:r,age:sn++}),{canvas:i,context:r,isNew:!0}};class on{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(h);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(m);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(g);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 cn=e=>"undefined"!==typeof VideoFrame&&e instanceof VideoFrame,ln=(e,t,r)=>{const a=Math.min(e.left,t),s=Math.min(e.top,r),n=Math.min(e.width,t-a),o=Math.min(e.height,r-s);return i(n>=0),i(o>=0),{left:a,top:s,width:n,height:o}},un=(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.")},dn=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.")}},hn=(e,t,i)=>{const r=fn(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},fn=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:F(e),i(!1)}},mn=(e,t)=>{const i={left:0,top:0,width:e.codedWidth,height:e.codedHeight},r=t.rect,a=pn(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 kn(a,n,s)},pn=(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(!gn(a,s))throw new TypeError("visibleRect alignment is invalid for the format.");return s},gn=(e,t)=>{if(null===e)return!0;const i=fn(e);for(let r=0;r{const r=fn(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/(Tn(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*Tn(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=Tn(t),s=Sn(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(!w(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&&!yn.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:r,frameCount:a,frameOffset:s}=t;let{planeIndex:n}=t,o=this.format;const c=r??this.format;if(!c)throw new Error("Destination format not determined");const u=this.numberOfFrames,d=this.numberOfChannels,h=s??0;if(h>=u)throw new RangeError("frameOffset out of range");const f=void 0!==a?a:u-h;if(f>u-h)throw new RangeError("frameCount out of range");const m=Tn(c),p=Sn(c);if(p&&n>=d)throw new RangeError("planeIndex out of range");if(!p&&0!==n)throw new RangeError("planeIndex out of range");const g=(p?f:f*d)*m;if(e.byteLength2&&c!==o)return void xn(this._data,k,o,c,d,n,h,f);try{return void this._data.copyTo(e,{planeIndex:n,frameOffset:h,frameCount:f,format:c})}catch(I){if("f32-planar"===c)throw I;o="f32-planar"}}const b=vn(o),T=Tn(o),S=Sn(o);let v;if(this._data instanceof bn){const e=e=>{const t=this._data.getDataPlane(e);if(!(t instanceof Uint8Array))throw new TypeError("getDataPlane() must return a Uint8Array.");const i=u*T*(S?1:d);if(t.byteLength!==i)throw new TypeError(`Data plane ${e} has invalid size. Expected exactly ${i} bytes, got ${t.byteLength} bytes.`);return t};if(S)if(p)v=e(n),n=0;else{v=new Uint8Array(u*T*d);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 wn({data:a,format:this.format,sampleRate:this.sampleRate,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp+e/this.sampleRate})}close(){this._closed||(Ys?.unregister(this),this._data instanceof bn?(this._data._referenceCount--,0===this._data._referenceCount&&this._data.close()):In(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 bn?this._createAudioDataFromData():In(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(Sn(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")}},Sn=e=>{switch(e){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},vn=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)}},Pn=e=>{switch(e){case"u8":case"u8-planar":return(e,t,i)=>e.setUint8(t,N(127.5*(i+1),0,255));case"s16":case"s16-planar":return(e,t,i)=>e.setInt16(t,N(Math.round(32767*i),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,i)=>e.setInt32(t,N(Math.round(2147483647*i),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,i)=>e.setFloat32(t,i,!0)}},In=e=>"undefined"!==typeof AudioData&&e instanceof AudioData,xn=(e,t,i,r,a,s,n,o)=>{const c=vn(i),u=Pn(r),d=Tn(i),h=Tn(r),f=Sn(i);if(Sn(r))if(f){const r=new ArrayBuffer(o*d),a=l(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.")},_n=e=>{if(!le(e))throw new TypeError("timestamp must be a number.")},Rn=(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 Fn{constructor(e){if(!(e instanceof Xn))throw new TypeError("track must be an InputTrack.");this._track=e}async getFirstPacket(e={}){if(En(e),this._track.input._disposed)throw new lo;return Rn(this._track,this._track._backing.getFirstPacket(e),e)}async getFirstKeyPacket(e={}){En(e);const t=await this.getFirstPacket(e);return t?"key"===t.type?t:this.getNextKeyPacket(t,e):null}async getPacket(e,t={}){if(_n(e),En(t),this._track.input._disposed)throw new lo;return Rn(this._track,this._track._backing.getPacket(e,t),t)}async getNextPacket(e,t={}){if(!(e instanceof pi))throw new TypeError("packet must be an EncodedPacket.");if(En(t),this._track.input._disposed)throw new lo;return Rn(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(_n(e),En(t),this._track.input._disposed)throw new lo;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);const r=await this._track._backing.getKeyPacket(e,t);if(!r)return r;i("key"===r.type);return"delta"===await this._track.determinePacketType(r)?this.getKeyPacket(r.timestamp-1/await this._track.getTimeResolution(),t):r}async getNextKeyPacket(e,t={}){if(!(e instanceof pi))throw new TypeError("packet must be an EncodedPacket.");if(En(t),this._track.input._disposed)throw new lo;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);const r=await this._track._backing.getNextKeyPacket(e,t);if(!r)return r;i("key"===r.type);return"delta"===await this._track.determinePacketType(r)?this.getNextKeyPacket(r,t):r}packets(e,t,i={}){if(void 0!==e&&!(e instanceof pi))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 pi))throw new TypeError("endPacket must be an EncodedPacket.");if(En(i),this._track.input._disposed)throw new lo;const r=[];let{promise:a,resolve:s}=B(),{promise:n,resolve:o}=B(),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}=B()),await n):(r.push(u),s(),({promise:a,resolve:s}=B()),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 lo;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 An{constructor(e,t){this.onSample=e,this.onError=t}}class Dn{mediaSamplesInRange(e=-1/0,t=1/0,i){_n(e),_n(t);const r=[];let a=!1,s=null,{promise:n,resolve:o}=B(),{promise:c,resolve:l}=B(),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}=B())))},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=Mn(r.length);if(r.length+f.getDecodeQueueSize()>e){({promise:c,resolve:l}=B()),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 lo;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 r=async function*(e){Symbol.iterator in e?yield*e[Symbol.iterator]():yield*e[Symbol.asyncIterator]()}(e),a=[],s=[];let{promise:n,resolve:o}=B(),{promise:c,resolve:l}=B(),u=!1,d=!1,h=null,f=null,m=!1;const p=e=>{s.push(e),o(),({promise:n,resolve:o}=B())},g={...t,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{h=await this._createDecoder(e=>{if(l(),d)return void e.close();let t=0;for(;a.length>0&&e.timestamp-a[0]>-1e-10;)t++,a.shift();if(t>0)for(let i=0;i{m||(f=e,m=!0,o())});const e=this._createPacketSink();let t=null,n=null,k=-1;const y=async()=>{i(n),i(h);let t=n;for(h.decode(t);t.sequenceNumberr&&!d;)({promise:c,resolve:l}=B()),await c;if(d)break;const a=await e.getNextPacket(t,g);i(a),h.decode(a),t=a}k=-1},b=async()=>{i(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 s)e?.close()};return{async next(){for(;;){if(k.input._disposed)throw d=!0,y(),new lo;if(d)return{value:void 0,done:!0};if(m)throw d=!0,y(),f;if(s.length>0){const e=s.shift();return i(void 0!==e),l(),{value:e,done:!1}}if(u)return{value:void 0,done:!0};await n}},return:async()=>(d=!0,l(),o(),y(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}}const Mn=e=>0===e?40:8;class Nn extends An{constructor(e,t,r,a,s,n){super(e,t),this.codec=r,this.decoderConfig=a,this.rotation=s,this.timeResolution=n,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new G,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=Cn.find(e=>e.supports(r,a));if(o)this.customDecoder=new o,this.customDecoder.codec=r,this.customDecoder.config=a,this.customDecoder.onSample=e=>{if(!(e instanceof tn))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(te()){if("avc"===r&&this.decoderConfig.description){const e=je(c(this.decoderConfig.description));if(e&&e.sequenceParameterSets.length>0){const t=Xe(e.sequenceParameterSets[0]);t&&(0===t.frameMbsOnlyFlag&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"}),0!==t.maxDecFrameBuffering&&1!==t.bitstreamRestrictionFlag&&(e.sequenceParameterSets[0]=Ge(t),this.decoderConfig={...this.decoderConfig,description:Ve(e)}))}}y(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:(i(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(i(this.decoder),Y()||C(this.inputTimestamps,e.timestamp,e=>e),te()&&0===this.currentPacketIndex)if("avc"===this.codec){const t=[];let i=!1;for(const a of Oe(e.data,this.decoderConfig)){const r=Le(e.data[a.offset]);if(i||(i=r>=1&&r<=5),r===Re.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&c(t.description)[4];return We(e,i+1)}return qe(e)})(t,this.decoderConfig);e=new pi(r,e.type,e.timestamp,e.duration)}else if("hevc"===this.codec){const t=lt(e.data,this.decoderConfig);t&&(e=new pi(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 Ln),!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=kt(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 Qe(e,this.decoderConfig)){const i=Ye(e[t.offset]);if(i===Ae.RASL_N||i===Ae.RASL_R)return!0}return!1}sampleHandler(e){if(Y()){if(this.sampleQueue.length>0&&e.timestamp>=a(this.sampleQueue).timestamp){for(const e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}C(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)}async mergeAlpha(e,t){const r=B();this.mergeAlphaPromises.push(r.promise);const a={sample:null};this.finalSamples.push(a);try{if(t){i(this.merger);const r=await this.merger.merge(e,t);a.sample=new tn(r)}else a.sample=new tn(e);for(;this.finalSamples.length>0&&null!==this.finalSamples[0].sample;){const e=this.finalSamples.shift();this.sampleHandler(e.sample)}}catch(s){E(this.finalSamples,a),this.onError(s)}finally{E(this.mergeAlphaPromises,r.promise),r.resolve()}}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(i(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),Y()){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()):(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=>e?.close()),this.alphaQueue.length=0,this.merger?.close());for(const e of this.sampleQueue)e.close();this.sampleQueue.length=0}}let On=null;class Ln{constructor(){this.workers=[],this.nextWorkerIndex=0,this.pendingRequests=new Map,this.nextRequestId=0}merge(e,t){if(0===this.workers.length){if(!On){const e=new Blob([`(${zn.toString()})()`],{type:"application/javascript"});On=URL.createObjectURL(e)}const e=N(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=B();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 zn=()=>{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 qn extends Dn{constructor(e,t={}){if(!(e instanceof Qn))throw new TypeError("videoTrack must be an InputVideoTrack.");Un(t),super(),this._track=e,this._decoderOptions=t}async _createDecoder(e,t){if(!(await 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 r=await this._track.getCodec(),a=await this._track.getRotation();let s=await this._track.getDecoderConfig();const n=await this._track.getTimeResolution();return i(r&&s),s={...s,hardwareAcceleration:this._decoderOptions.hardwareAcceleration,optimizeForLatency:this._decoderOptions.optimizeForLatency},new Nn(e,t,r,s,a,n)}_createPacketSink(){return new Fn(this._track)}async getSample(e,t={}){_n(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 Wn{constructor(e,t={}){if(this._rotation=0,this._initPromise=null,this._nextCanvasIndex=0,!(e instanceof Qn))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&&un(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&&Un(t.decoderOptions),this._videoTrack=e,this._alpha=t.alpha??!1,this._options=t,this._fit=t.fit??"fill",this._videoSampleSink=new qn(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=ln(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,r=this._height;let a=this._canvasPool[this._nextCanvasIndex],s=!1;a||("undefined"!==typeof document?(a=document.createElement("canvas"),a.width=t,a.height=r):a=new OffscreenCanvas(t,r),this._canvasPool.length>0&&(this._canvasPool[this._nextCanvasIndex]=a),s=!0),this._canvasPool.length>0&&(this._nextCanvasIndex=(this._nextCanvasIndex+1)%this._canvasPool.length);const n=a.getContext("2d",{alpha:this._alpha||Z()});i(n),e._drawWithFitAndMipmapping(a,n,{fit:this._fit,rotation:this._rotation,crop:this._crop,targetIsFresh:s,fillBlack:!this._alpha&&Z()});const o={canvas:a,timestamp:e.timestamp,duration:e.duration};return e.close(),o}async getCanvas(e,t){_n(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*M(this._videoSampleSink.samples(e,t,i),e=>this._videoSampleToWrappedCanvas(e))}async*canvasesAtTimestamps(e,t){await this._ensureInit(),yield*M(this._videoSampleSink.samplesAtTimestamps(e,t),e=>e&&this._videoSampleToWrappedCanvas(e))}}class Hn extends An{constructor(e,t,i,r){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new G,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=Bn.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 wn))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 wn(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),this.expectedFirstTimestamp??(this.expectedFirstTimestamp=e.timestamp),this.decoder.decode(e.toEncodedAudioChunk()))}async flush(){this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(i(this.decoder),await 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 Vn extends An{constructor(e,t,r){super(e,t),this.decoderConfig=r,this.currentTimestamp=null,i(Wt.includes(r.codec)),this.codec=r.codec;const{dataType:a,sampleSize:s,littleEndian:n}=ti(this.codec);switch(this.inputSampleSize=s,s){case 1:"unsigned"===a?this.readInputValue=(e,t)=>e.getUint8(t)-128:"signed"===a?this.readInputValue=(e,t)=>e.getInt8(t):"ulaw"===a?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,n)-32768:"signed"===a?this.readInputValue=(e,t)=>e.getInt16(t,n):i(!1);break;case 3:"unsigned"===a?this.readInputValue=(e,t)=>A(e,t,n)-2**23:"signed"===a?this.readInputValue=(e,t)=>((e,t,i)=>A(e,t,i)<<8>>8)(e,t,n):i(!1);break;case 4:"unsigned"===a?this.readInputValue=(e,t)=>e.getUint32(t,n)-2**31:"signed"===a?this.readInputValue=(e,t)=>e.getInt32(t,n):"float"===a?this.readInputValue=(e,t)=>e.getFloat32(t,n):i(!1);break;case 8:"float"===a?this.readInputValue=(e,t)=>e.getFloat64(t,n):i(!1);break;default:F(s),i(!1)}switch(s){case 1:"ulaw"===a||"alaw"===a?(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"===a?(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:F(s),i(!1)}}getDecodeQueueSize(){return 0}decode(e){const t=l(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 wn({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 Dn{constructor(e){if(!(e instanceof Yn))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(ie("AudioDecoder"));throw new Error("This audio track cannot be decoded in this environment. Make sure to check decodability before using a track.")}const r=await this._track.getCodec(),a=await this._track.getDecoderConfig();return i(r&&a),Wt.includes(a.codec)?new Vn(e,t,a):new Hn(e,t,r,a)}_createPacketSink(){return new Fn(this._track)}async getSample(e,t={}){_n(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){if(!(e instanceof Yn))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){_n(e);const i=await this._audioSampleSink.getSample(e,t);return i&&this._audioSampleToWrappedArrayBuffer(i)}buffers(e,t,i){return M(this._audioSampleSink.samples(e,t,i),e=>this._audioSampleToWrappedArrayBuffer(e))}buffersAtTimestamps(e,t){return M(this._audioSampleSink.samplesAtTimestamps(e,t),e=>e&&this._audioSampleToWrappedArrayBuffer(e))}}class Xn{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof Qn}isAudioTrack(){return this instanceof Yn}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}async getInternalCodecId(){return this._backing.getInternalCodecId()}get internalCodecId(){return $n(this._backing.getInternalCodecId(),"internalCodecId","getInternalCodecId")}async getLanguageCode(){return this._backing.getLanguageCode()}get languageCode(){return $n(this._backing.getLanguageCode(),"languageCode","getLanguageCode")}async getName(){return this._backing.getName()}get name(){return $n(this._backing.getName(),"name","getName")}async getTimeResolution(){return this._backing.getTimeResolution()}get timeResolution(){return $n(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 $n(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 U((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 Fn(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 Xn))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(to({filter:e=>e.canBePairedWith(this)},e))}async getPairableVideoTracks(e){return this.input.getVideoTracks(to({filter:e=>e.canBePairedWith(this)},e))}async getPairableAudioTracks(e){return this.input.getAudioTracks(to({filter:e=>e.canBePairedWith(this)},e))}async getPrimaryPairableVideoTrack(e){return this.input.getPrimaryVideoTrack(to({filter:e=>e.canBePairedWith(this)},e))}async getPrimaryPairableAudioTrack(e){return this.input.getPrimaryAudioTrack(to({filter:e=>e.canBePairedWith(this)},e))}async hasPairableTrack(e){e&&(e=Gn(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=Gn(e)),this.hasPairableTrack(async t=>t.isVideoTrack()&&(!e||await e(t)))}hasPairableAudioTrack(e){return e&&(e=Gn(e)),this.hasPairableTrack(async t=>t.isAudioTrack()&&(!e||await e(t)))}}const $n=(e,t,i)=>{if(ae(e))throw new Error(`'${t}' is deprecated and not available synchronously for this track. Use the preferred '${i}()' instead.`);return e},Gn=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 ae(r)?r.then(i):i(r)}:void 0};class Qn extends Xn{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 $n(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 $n(this._backing.getCodedWidth(),"codedWidth","getCodedWidth")}async getCodedHeight(){return this._backing.getCodedHeight()}get codedHeight(){return $n(this._backing.getCodedHeight(),"codedHeight","getCodedHeight")}async getRotation(){return this._backing.getRotation()}get rotation(){return $n(this._backing.getRotation(),"rotation","getRotation")}async getSquarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelWidth(){return $n(this._backing.getSquarePixelWidth(),"squarePixelWidth","getSquarePixelWidth")}async getSquarePixelHeight(){return this._backing.getSquarePixelHeight()}get squarePixelHeight(){return $n(this._backing.getSquarePixelHeight(),"squarePixelHeight","getSquarePixelHeight")}async getPixelAspectRatio(){return this._pixelAspectRatioCache??(this._pixelAspectRatioCache=fe({num:await this.getSquarePixelWidth()*await this.getCodedHeight(),den:await this.getSquarePixelHeight()*await this.getCodedWidth()}))}get pixelAspectRatio(){return this._pixelAspectRatioCache??(this._pixelAspectRatioCache=fe({num:$n(this._backing.getSquarePixelWidth(),"pixelAspectRatio","getPixelAspectRatio")*$n(this._backing.getCodedHeight(),"pixelAspectRatio","getPixelAspectRatio"),den:$n(this._backing.getSquarePixelHeight(),"pixelAspectRatio","getPixelAspectRatio")*$n(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=$n(e,"displayWidth","getDisplayWidth");if(null!==t)return t}const t=$n(this._backing.getRotation(),"displayWidth","getDisplayWidth")%180===0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight();return $n(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=$n(e,"displayHeight","getDisplayHeight");if(null!==t)return t}const t=$n(this._backing.getRotation(),"displayHeight","getDisplayHeight")%180===0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth();return $n(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(i(null!==t),Cn.some(i=>i.supports(t,e)))return!0;if("undefined"===typeof VideoDecoder)return!1;return!0===(await VideoDecoder.isConfigSupported(e)).supported}catch(e){return be._error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof pi))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 r=await this.getDecoderConfig();return i(r),kt(t,r,e.data)}async computeFrameRateMetrics(e={}){if(!e||"object"!==typeof e)throw new TypeError("options must be an object.");if(void 0!==e.targetPacketCount&&(!le(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 Fn(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:so(P),minFrameRate:d/p,maxFrameRate:d/m,averageFrameRate:d*k/g,medianFrameRate:P,frameRateIsConstant:null!==u&&1===m&&1===p,probedPacketCount:n}}}class Yn extends Xn{constructor(e,t){super(e,t),this._backing=t}get type(){return"audio"}async getCodec(){return this._backing.getCodec()}get codec(){return $n(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){return await(this._backing.getHasOnlyKeyPackets?.())??!0}async getNumberOfChannels(){return this._backing.getNumberOfChannels()}get numberOfChannels(){return $n(this._backing.getNumberOfChannels(),"numberOfChannels","getNumberOfChannels")}async getSampleRate(){return this._backing.getSampleRate()}get sampleRate(){return $n(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(i(null!==t),Bn.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 be._error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof pi))throw new TypeError("packet must be an EncodedPacket.");return null===await this.getCodec()?null:"key"}}const Jn=e=>-(e??-1/0),Zn=e=>-e,eo=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 ae(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 ae(r)?r.then(i):i(r)}:void 0}},to=(e,t)=>({filter:e?.filter||t?.filter?i=>{const r=e?.filter?.(i)??!0,a=e=>!1!==e&&(t?.filter?.(i)??!0);return ae(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 ae(r)||ae(a)?Promise.all([r,a]).then(([e,t])=>s(e,t)):s(r,a)}:void 0}),io=async(e,t)=>{let i=e;if(t?.filter){const r=e.map(e=>t.filter(e));if(r.some(e=>ae(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=>ae(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)},ro=(e,t)=>{const i=1e6,r=1+1e-9,a=[12,15,20,24e3/1001,24,25,3e4/1001,30,48,50,6e4/1001,60,100,12e4/1001,120,144,240];if(e.length<2)return null;const s=new Float64Array(e.length-1);for(let T=1;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 Ss)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof $a||e.source instanceof Ga))throw new TypeError("options.source must be a Source or SourceRef.");if(e.source instanceof $a&&e.source._disposed)throw new TypeError("options.source must not be a disposed Source.");if(void 0!==e.initInput&&!(e.initInput instanceof oo))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 $a?this._rootRef=e.source.ref():this._rootRef=e.source,this._sourceRefs.push(this._rootRef)}get _rootSource(){return this._rootRef.source}async _getSourceUncached(e){i(this._rootSource instanceof Qa);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 r=this._sourceCache.find(i=>i.cacheGroup===t&&Ya(i.request,e));if(r)return r.age++,Promise.resolve(r.sourceRef.source.ref());const a=this._sourceCachePromises.find(i=>i.cacheGroup===t&&Ya(i.request,e));if(a)return a.promise.then(e=>e.sourceRef.source.ref());const s=(async()=>{const r=await this._getSourceUncached(e);if(de(this._sourceCache,e=>e.cacheGroup===t&&1===e.sourceRef.source._refCount)>=4){const e=he(this._sourceCache,e=>e.cacheGroup===t&&1===e.sourceRef.source._refCount?e.age:1/0);i(-1!==e);const r=this._sourceCache[e];this._sourceCache.splice(e,1),r.sourceRef.free(),E(this._sourceRefs,r.sourceRef)}this._sourceRefs.push(r);const a=this._sourceCachePromises.findIndex(t=>t.request===e);i(-1!==a),this._sourceCachePromises.splice(a,1);return{request:e,sourceRef:r,age:this._nextSourceCacheAge++,cacheGroup:t}})();return this._sourceCachePromises.push({request:e,cacheGroup:t,promise:s}),s.then(e=>{const t=e.sourceRef.source.ref();return this._sourceCache.push(e),t})}_getDemuxer(){return this._demuxerPromise??(this._demuxerPromise=(async()=>{this._reader=new uo(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 co})())}get source(){return this._rootSource}async getFormat(){return await this._getDemuxer(),i(this._format),this._format}async canRead(){try{return await this._getDemuxer(),!0}catch(e){if(e instanceof co)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=eo(e));const t=(await this._getTrackBackings()).map(e=>this._wrapBackingAsTrack(e));return io(t,e)}async getVideoTracks(e){e&&(e=eo(e));const t=(await this.getTracks()).filter(e=>e.isVideoTrack());return io(t,e)}async getAudioTracks(e){e&&(e=eo(e));const t=(await this.getTracks()).filter(e=>e.isAudioTrack());return io(t,e)}async getPrimaryVideoTrack(e){e&&(e=eo(e));const t=to(e,{sortBy:async e=>[Zn((await e.getDisposition()).default),Zn(await e.hasPairableAudioTrack()),Zn(!(await e.hasOnlyKeyPackets())),Jn(await e.getBitrate())]});return(await this.getVideoTracks(t))[0]??null}async getPrimaryAudioTrack(e){e&&(e=eo(e));const t=await this.getPrimaryVideoTrack(),i=to(e,{sortBy:async e=>[Zn(!t||e.canBePairedWith(t)),Zn((await e.getDisposition()).default),Jn(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 Qn(this,e):new Yn(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 co extends Error{constructor(e="Input has an unsupported or unrecognizable format."){super(e),this.name="UnsupportedInputFormatError"}}class lo extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}}class uo{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 lo;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 ho(t,l(t),0,e,e)}const i=e+t,r=this.source._read(e,i,0,Xa);return ae(r)?r.then(t=>t?new ho(t.bytes,t.view,t.offset,e,i):null):r?new ho(r.bytes,r.view,r.offset,e,i):null}requestSliceRange(e,t,r){if(this.source._disposed)throw new lo;if(e<0)return null;if(null!==this.fileSizeNonStrict)return this.requestSlice(e,N(this.fileSizeNonStrict-e,t,r));{const a=this.requestSlice(e,r),s=a=>a||(i(null!==this.fileSizeNonStrict),this.requestSlice(e,N(this.fileSizeNonStrict-e,t,r)));return ae(a)?a.then(s):s(a)}}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(ae(i)&&(i=await 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 a of e)i.set(a,r),r+=a.length;return new ho(i,l(i),0,0,t)})()}}class ho{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 ho(e,l(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 ho(this.bytes,this.view,this.offset,e,e+t)}}const fo=(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)=>{fo(e,t);const i=e.bytes.subarray(e.bufferPos,e.bufferPos+t);return e.bufferPos+=t,i},po=e=>(fo(e,1),e.view.getUint8(e.bufferPos++)),go=(e,t)=>{fo(e,2);const i=e.view.getUint16(e.bufferPos,t);return e.bufferPos+=2,i},ko=e=>{fo(e,2);const t=e.view.getUint16(e.bufferPos,!1);return e.bufferPos+=2,t},yo=e=>{fo(e,3);const t=A(e.view,e.bufferPos,!1);return e.bufferPos+=3,t},bo=e=>{fo(e,2);const t=e.view.getInt16(e.bufferPos,!1);return e.bufferPos+=2,t},wo=(e,t)=>{fo(e,4);const i=e.view.getUint32(e.bufferPos,t);return e.bufferPos+=4,i},To=e=>{fo(e,4);const t=e.view.getUint32(e.bufferPos,!1);return e.bufferPos+=4,t},So=e=>{fo(e,4);const t=e.view.getUint32(e.bufferPos,!0);return e.bufferPos+=4,t},vo=e=>{fo(e,4);const t=e.view.getInt32(e.bufferPos,!1);return e.bufferPos+=4,t},Po=(e,t)=>{let i,r;return t?(i=wo(e,!0),r=wo(e,!0)):(r=wo(e,!1),i=wo(e,!1)),4294967296*r+i},Io=e=>4294967296*To(e)+To(e),xo=e=>4294967296*vo(e)+To(e),Co=e=>{const t=So(e),i=(e=>{fo(e,4);const t=e.view.getInt32(e.bufferPos,!0);return e.bufferPos+=4,t})(e);return 4294967296*i+t},Bo=e=>{fo(e,4);const t=e.view.getFloat32(e.bufferPos,!1);return e.bufferPos+=4,t},Eo=e=>{fo(e,8);const t=e.view.getFloat64(e.bufferPos,!1);return e.bufferPos+=8,t},_o=(e,t)=>{fo(e,t);let i="";for(let r=0;ru.decode(mo(e,t)).split("\n").map(e=>e.trim()).filter(e=>e.length>0&&!i?.ignore?.(e));var Fo,Ao,Do,Mo;(Ao=Fo||(Fo={}))[Ao.Unsynchronisation=128]="Unsynchronisation",Ao[Ao.ExtendedHeader=64]="ExtendedHeader",Ao[Ao.ExperimentalIndicator=32]="ExperimentalIndicator",Ao[Ao.Footer=16]="Footer",(Mo=Do||(Do={}))[Mo.ISO_8859_1=0]="ISO_8859_1",Mo[Mo.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",Mo[Mo.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",Mo[Mo.UTF_8=3]="UTF_8";const No=128,Oo=10,Lo=["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"],zo=(e,t)=>{var i;const r=e.filePos;t.raw??(t.raw={}),(i=t.raw).TAG??(i.TAG=mo(e,No-3)),e.filePos=r;const a=Uo(e,30);a&&(t.title??(t.title=a));const s=Uo(e,30);s&&(t.artist??(t.artist=s));const n=Uo(e,30);n&&(t.album??(t.album=n));const o=Uo(e,4),c=Number.parseInt(o,10);Number.isInteger(c)&&c>0&&(t.date??(t.date=new Date(String(c))));const l=mo(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=Uo(e,28),e.skip(2)}else e.skip(-30),u=Uo(e,30);u&&(t.comment??(t.comment=u));const d=po(e);d{const i=mo(e,t),r=se(i.indexOf(0),i.length),a=i.subarray(0,r);let s="";for(let n=0;n{const t=e.filePos,i=_o(e,3),r=po(e),a=po(e),s=po(e),n=To(e);if("ID3"!==i||255===r||255===a||0!==(2155905152&n))return e.filePos=t,null;let o=li(n);return s&Fo.Footer&&(o+=Oo),{majorVersion:r,revision:a,flags:s,size:o}},Wo=(e,t,i)=>{var r,a,s,n,o;if(![2,3,4].includes(t.majorVersion))return void be._warn(`Unsupported ID3v2 major version: ${t.majorVersion}`);const c=t.flags&Fo.Footer?t.size-Oo:t.size,l=mo(e,c),u=new Ho(t,l);if(t.flags&Fo.Unsynchronisation&&3===t.majorVersion&&u.ununsynchronizeAll(),t.flags&Fo.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&Fo.Unsynchronisation)),d)be._warn(`Skipping encrypted ID3v2 frame ${e.id}`),u.pos=l;else if(h)be._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!==Lo[e]){i.genre??(i.genre=Lo[e]);break}}if(t=/^\d+$/.exec(e),t){const e=Number.parseInt(t[0]);if(void 0!==Lo[e]){i.genre??(i.genre=Lo[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 Ho{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:li(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 Do.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=se(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=se(r.findIndex(e=>0===e),r.length);return this.pos=i+Math.min(e+1,r.length),u.decode(r.subarray(0,e))}case Do.UTF_16_BE_NO_BOM:{const e=new TextDecoder("utf-16be"),t=se(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 Do.UTF_8:{const e=se(r.findIndex(e=>0===e),r.length);return this.pos=i+Math.min(e+1,r.length),u.decode(r.subarray(0,e))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";const t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}}class Vo{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 Kn(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 Ko=/\.m3u8(?:$|[?#])/i;function Xo(e){return"string"===typeof e&&Ko.test(e)}function $o(e){const t=function(e){return"string"===typeof e?new rs(e):e instanceof Blob?new es(e):"undefined"!==typeof ReadableStream&&e instanceof ReadableStream?new ns(e):e??null}(e);return t?new oo({source:t,formats:Xo(e)?Xs:Ks}):null}class Go{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 Qo({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 Yo{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||Xo(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 Wn(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 Jo{constructor({canvas:e,ctx:t,events:i,option:r={}}){this.events=i,this.option=r,this.audio=new Vo(i),this.video=new Yo({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 Go;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=$o(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 Qo({input:e,videoTrack:i,audioTrack:r}),s=i||r,n=Xo(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 Qo(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 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"}}(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}}class Zo{constructor({art:e,canvas:i,ctx:r,option:a}){this.art=e,this.canvas=i,this.option=a,this.events=new t,this.engine=new Jo({canvas:i,ctx:r,events:this.events,option:a}),this._src=null,this._volume=a.volume??.7,this._muted=!!a.muted,this._playbackRate=1,this.engine.setVolume(this._volume,this._muted),this.setupEventForwarding(),a.source?this.src=a.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){const i=this.engine.duration;return!i||Number.isNaN(i)||t<=0?{length:0,start:()=>0,end:()=>0}:{length:1,start:()=>e,end:()=>t}}get paused(){return this.engine.paused}get playing(){return!this.engine.paused&&!this.engine.ended}get ended(){return this.engine.ended}get seeking(){return this.engine.seeking}get readyState(){return this.engine.readyState}get networkState(){return this.engine.networkState}get error(){return this.engine.error}get playbackRate(){return this._playbackRate}set playbackRate(e){const t=Number(e);Number.isNaN(t)||t<=0||(this._playbackRate=t,this.engine.setPlaybackRate(t),this.events.emit("ratechange"))}get volume(){return this._volume}set volume(e){this._volume=function(e,t,i){return Math.max(t,Math.min(i,Number(e)||0))}(e,0,1),this._muted=!1,this.engine.setVolume(this._volume,this._muted),this.events.emit("volumechange")}get muted(){return this._muted}set muted(e){this._muted=!!e,this.engine.setVolume(this._volume,this._muted),this.events.emit("volumechange")}play(){return this.engine.play()}pause(){this.engine.pause()}load(){this._src&&this.engine.load(this._src)}getM3u8State(){return this.engine.getHlsState()}switchM3u8Quality(e){return this.engine.selectHlsQuality(e)}switchM3u8Audio(e){return this.engine.selectHlsAudio(e)}get videoWidth(){return this.engine.videoWidth}get videoHeight(){return this.engine.videoHeight}get poster(){return this.option.poster||""}set poster(e){this.option.poster=e}get autoplay(){return this.option.autoplay||!1}set autoplay(e){}get loop(){return this.option.loop||!1}set loop(e){}get controls(){return!1}set controls(e){}get playsInline(){return!0}set playsInline(e){}get crossOrigin(){return this.option.crossOrigin||""}set crossOrigin(e){}get preload(){return"auto"}set preload(e){}get defaultMuted(){return!1}set defaultMuted(e){}get defaultPlaybackRate(){return 1}set defaultPlaybackRate(e){}canPlayType(e){return"maybe"}getBoundingClientRect(){return this.canvas.getBoundingClientRect()}requestVideoFrameCallback(e){return requestAnimationFrame(t=>{e(t,{presentationTime:this.engine.currentTime,expectedDisplayTime:t+16.6,width:this.engine.videoWidth,height:this.engine.videoHeight,mediaTime:this.engine.currentTime,presentedFrames:0,processingDuration:0,captureTime:t,receiveTime:t,rtpTimestamp:0})})}cancelVideoFrameCallback(e){cancelAnimationFrame(e)}setAttribute(e,t){"src"===e?this.src=t:"autoplay"===e?this.autoplay=t:"loop"===e?this.loop=t:"muted"===e?this.muted=!0:this.canvas.setAttribute(e,t)}destroy(){this.engine.destroy()}}return function(t={}){return i=>{const{constructor:r}=i,{createElement:a}=r.utils,s=a("canvas"),n=s.getContext("2d"),o=new Zo({art:i,canvas:s,ctx:n,option:t});i.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=i.template?.$player;e&&!i.option.autoSize&&Object.assign(s.style,{width:"100%",height:"100%",objectFit:"contain"})}return i.on("resize",u),i.on("video:loadedmetadata",u),function({art:t,shim:i,option:r}){if(r.m3u8)return t.on("video:loadedmetadata",d),t.on("restart",d),{update:d};function a(e){t.controls.cache.has(e)&&t.controls.remove(e)}function s(e){t.setting.find(e)&&t.setting.remove(e)}function n(){a("mediabunny-quality"),s("mediabunny-quality")}function o(){a("mediabunny-audio"),s("mediabunny-audio")}function c(e={}){return e.control||e.setting}async function l(a){const s=r.m3u8?.quality||{};if(!c(s)||!a?.levels.length)return void n();const o=s.auto||"Auto",l=s.title||"Quality",u=s.getName||(e=>e.name||`${e.height}P`),h=a.currentLevel?u(a.currentLevel):o,f=e(a.levels.map(e=>({html:u(e),value:e.id,default:a.currentLevel?.id===e.id})),"html").sort((e,t)=>{const i=a.levels.find(t=>t.id===e.value),r=a.levels.find(e=>e.id===t.value);return(r?.height||0)-(i?.height||0)});f.push({html:o,value:"auto",default:!a.currentLevel});const m=async e=>(await i.switchM3u8Quality(e.value),t.notice.show=`${l}: ${e.html}`,await d(),e.html);s.control&&t.controls.update({name:"mediabunny-quality",position:"right",html:h,style:{padding:"0 10px"},selector:f,onSelect:m}),s.setting&&t.setting.update({name:"mediabunny-quality",tooltip:h,html:l,icon:'',width:200,selector:f,onSelect:m})}async function u(a){const s=r.m3u8?.audio||{};if(!c(s)||!a?.audios.length||a.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=a.currentAudio?u(a.currentAudio):n,f=e(a.audios.map(e=>({html:u(e),value:e.id,default:a.currentAudio?.id===e.id})),"html");f.push({html:n,value:"auto",default:!a.currentAudio});const m=async e=>(await i.switchM3u8Audio(e.value),t.notice.show=`${l}: ${e.html}`,await d(),e.html);s.control&&t.controls.update({name:"mediabunny-audio",position:"right",html:h,style:{padding:"0 10px"},selector:f,onSelect:m}),s.setting&&t.setting.update({name:"mediabunny-audio",tooltip:h,html:l,icon:'',width:200,selector:f,onSelect:m})}async function d(){const e=await i.getM3u8State();if(!e)return n(),void o();await Promise.all([l(e),u(e)])}}({art:i,shim:o,option:t}),i.on("destroy",()=>{delete i.mediabunny,o.destroy()}),s}}}); 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 7e89ad8c9..e376a5616 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?(t.artplayerProxyMediabunny=t(),define(function(){return t.artplayerProxyMediabunny})):(e="undefined"!==typeof globalThis?globalThis:e||self).artplayerProxyMediabunny=t()}(this,function(){"use strict";var e=Object.defineProperty,t=Object.defineProperties,i=Object.getOwnPropertyDescriptors,r=Object.getOwnPropertySymbols,n=Object.prototype.hasOwnProperty,s=Object.prototype.propertyIsEnumerable,a=(e,t)=>(t=Symbol[e])?t:Symbol.for("Symbol."+e),o=Math.pow,l=(t,i,r)=>i in t?e(t,i,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[i]=r,c=(e,t)=>{for(var i in t||(t={}))n.call(t,i)&&l(e,i,t[i]);if(r)for(var i of r(t))s.call(t,i)&&l(e,i,t[i]);return e},u=(e,r)=>t(e,i(r)),d=(e,t,i)=>new Promise((r,n)=>{var s=e=>{try{o(i.next(e))}catch(t){n(t)}},a=e=>{try{o(i.throw(e))}catch(t){n(t)}},o=e=>e.done?r(e.value):Promise.resolve(e.value).then(s,a);o((i=i.apply(e,t)).next())}),h=function(e,t){this[0]=e,this[1]=t},f=(e,t,i)=>{var r=(e,t,n,s)=>{try{var a=i[e](t),o=(t=a.value)instanceof h,l=a.done;Promise.resolve(o?t[0]:t).then(i=>o?r("return"===e?e:"next",t[1]?{done:i.done,value:i.value}:i,n,s):n({value:i,done:l})).catch(e=>r("throw",e,n,s))}catch(c){s(c)}},n=e=>s[e]=t=>new Promise((i,n)=>r(e,t,i,n)),s={};return i=i.apply(e,t),s[a("asyncIterator")]=()=>s,n("next"),n("throw"),n("return"),s},m=e=>{var t,i=e[a("asyncIterator")],r=!1,n={};return null==i?(i=e[a("iterator")](),t=e=>n[e]=t=>i[e](t)):(i=i.call(e),t=e=>n[e]=t=>{if(r){if(r=!1,"throw"===e)throw t;return t}return r=!0,{done:!1,value:new h(new Promise(r=>{var n=i[e](t);n instanceof Object||(e=>{throw TypeError(e)})("Object expected"),r(n)}),1)}}),n[a("iterator")]=()=>n,t("next"),"throw"in i?t("throw"):n.throw=e=>{throw e},"return"in i&&t("return"),n},p=(e,t,i)=>(t=e[a("asyncIterator")])?t.call(e):(e=e[a("iterator")](),t={},(i=(i,r)=>(r=e[i])&&(t[i]=t=>new Promise((i,n,s)=>(t=r.call(e,t),s=t.done,Promise.resolve(t.value).then(e=>i({value:e,done:s}),n)))))("next"),i("return"),t);function g(e,t){const i=new Map;return e.filter(e=>{const r=e[t];return void 0===r||!i.has(r)&&i.set(r,1)})}class k{constructor(){this.listeners=new Map}addEventListener(e,t){this.listeners.has(e)||this.listeners.set(e,[]),this.listeners.get(e).push(t)}removeEventListener(e,t){const i=this.listeners.get(e);if(!i)return;const r=i.indexOf(t);r>=0&&i.splice(r,1)}emit(e,t){const i=new Event(e);i.detail=t;const r=this.listeners.get(e);r&&r.forEach(e=>e(i))}}function y(e){if(!e)throw new Error("Assertion failed.")}const b=e=>{const t=(e%360+360)%360;if(0===t||90===t||180===t||270===t)return t;throw new Error(`Invalid rotation ${e}.`)},T=e=>e&&e[e.length-1],S=e=>{let t=0;for(;0===e.readBits(1)&&t<32;)t++;if(t>=32)throw new Error("Invalid exponential-Golomb code.");return(1<{const t=S(e);return 0===(1&t)?-(t>>1):t+1>>1},w=e=>e.constructor===Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),P=e=>e.constructor===DataView?e:ArrayBuffer.isView(e)?new DataView(e.buffer,e.byteOffset,e.byteLength):new DataView(e),I=new TextDecoder,x=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])),C={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},B=x(C),E={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},_=x(E),A={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},F=x(A),R=e=>e instanceof ArrayBuffer||"undefined"!==typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e);class D{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}acquire(){return d(this,null,function*(){let e;const t=new Promise(t=>{let i=!1;e=()=>{i||(t(),this.pending--,i=!0)}}),i=this.currentPromise;return this.currentPromise=t,this.pending++,yield i,e})}}const M=/^[0-9a-fA-F]+$/,N=e=>[...e].map(e=>e.toString(16).padStart(2,"0")).join(""),O=e=>(e=(e=(e=(e=(e=e>>1&1431655765|(1431655765&e)<<1)>>2&858993459|(858993459&e)<<2)>>4&252645135|(252645135&e)<<4)>>8&16711935|(16711935&e)<<8)>>16&65535|(65535&e)<<16)>>>0,L=(e,t,i)=>{let r=0,n=e.length-1,s=-1;for(;r<=n;){const a=r+n>>1,o=i(e[a]);o===t?(s=a,n=a-1):o{let r=0,n=e.length-1,s=-1;for(;r<=n;){const a=r+(n-r+1)/2|0;i(e[a])<=t?(s=a,r=a+1):n=a-1}return s},U=(e,t,i)=>{const r=z(e,i(t),i);e.splice(r+1,0,t)},q=()=>{let e,t;return{promise:new Promise((i,r)=>{e=i,t=r}),resolve:e,reject:t}},W=(e,t)=>{for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},V=(e,t)=>{for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},H=e=>{throw new Error(`Unexpected value: ${e}`)},K=(e,t,i)=>{const r=e.getUint8(t),n=e.getUint8(t+1),s=e.getUint8(t+2);return i?r|n<<8|s<<16:r<<16|n<<8|s},j=(e,t,i,r)=>{i>>>=0,i&=16777215,e.setUint8(t,i>>>16&255),e.setUint8(t+1,i>>>8&255),e.setUint8(t+2,255&i)},X=(e,t)=>({next(){return d(this,null,function*(){const i=yield e.next();return i.done?{value:void 0,done:!0}:{value:t(i.value),done:!1}})},return:()=>e.return(),throw:t=>e.throw(t),[Symbol.asyncIterator](){return this}}),$=(e,t,i)=>Math.max(t,Math.min(i,e)),Q="und",G=e=>{const t=Math.round(e);return Math.abs(e/t-1)<10*Number.EPSILON?t:e},Y=(e,t)=>Math.round(e*t)/t,J=(e,t)=>Math.floor(e/t)*t,Z=/^[a-z]{3}$/,ee=e=>Z.test(e),te=1e6*(1+Number.EPSILON),ie=(e,t)=>{const i=c(c({},e),t);if(e.headers||t.headers){const r=e.headers?re(e.headers):{},n=t.headers?re(t.headers):{},s=c({},r);Object.entries(n).forEach(([e,t])=>{const i=Object.keys(s).find(t=>t.toLowerCase()===e.toLowerCase());i&&delete s[i],s[e]=t}),i.headers=s}return i},re=e=>{if(e instanceof Headers){const t={};return e.forEach((e,i)=>{t[i]=e}),t}if(Array.isArray(e)){const t={};return e.forEach(([e,i])=>{t[e]=i}),t}return e},ne=(e,t,i,r,n)=>d(null,null,function*(){let s=0;for(;;)try{return yield e(t,i)}catch(a){if(n())throw a;s++;const e=r(s,a,t);if(null===e)throw a;if(console.error("Retrying failed fetch. Error:",a),!Number.isFinite(e)||e<0)throw new TypeError("Retry delay must be a non-negative finite number.");if(e>0&&(yield Pe(1e3*e)),n())throw a}});class se{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}let ae=null;const oe=()=>{var e;return null!==ae?ae:ae=!("undefined"===typeof navigator||!((null==(e=navigator.vendor)?void 0:e.match(/apple/i))||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent)))};let le=null;const ce=()=>{var e;return null!==le?le:le="undefined"!==typeof navigator&&(null==(e=navigator.userAgent)?void 0:e.includes("Firefox"))};let ue=null;const de=()=>{var e;return null!==ue?ue:ue=!("undefined"===typeof navigator||!(null==(e=navigator.vendor)?void 0:e.includes("Google Inc"))&&!/Chrome/.test(navigator.userAgent))};let he=null;const fe=()=>{if(null!==he)return he;if("undefined"===typeof navigator)return null;const e=/\bChrome\/(\d+)/.exec(navigator.userAgent);return e?he=Number(e[1]):null},me=(e,t)=>-1!==e?e:t,pe=(e,t,i,r)=>e<=r&&i<=t,ge=e=>{const t=atob(e),i=new Uint8Array(t.length);for(let r=0;r{null!=Symbol.dispose||(Symbol.dispose=Symbol("Symbol.dispose"))},ye=e=>"number"===typeof e&&!Number.isNaN(e),be=(e,t)=>{if(t.includes("://"))return t;if(e.includes("://")){const t=e.indexOf("?");-1!==t&&(e=e.slice(0,t))}let i;if(t.startsWith("/")){const r=e.indexOf("://");if(-1===r)i=t;else{const n=e.indexOf("/",r+3);i=-1===n?e+t:e.slice(0,n)+t}}else{const r=e.lastIndexOf("/");i=-1===r?t:e.slice(0,r+1)+t}let r="";const n=i.indexOf("://");if(-1!==n){const e=i.indexOf("/",n+3);-1!==e&&(r=i.slice(0,e),i=i.slice(e))}const s=i.split("/"),a=[];for(const o of s)".."===o?a.pop():"."!==o&&a.push(o);return r+a.join("/")},Te=(e,t)=>{let i=0;for(let r=0;r{let i=-1,r=1/0;for(let n=0;n{y(Number.isInteger(e.num)),y(Number.isInteger(e.den)),y(0!==e.den);let t=Math.abs(e.num),i=Math.abs(e.den);for(;0!==i;){const e=t%i;t=i,i=e}const r=t||1;return{num:e.num/r,den:e.den/r}},we=(e,t)=>{if("object"!==typeof e||!e)throw new TypeError(`${t} must be an object.`);if(!Number.isInteger(e.left)||e.left<0)throw new TypeError(`${t}.left must be a non-negative integer.`);if(!Number.isInteger(e.top)||e.top<0)throw new TypeError(`${t}.top must be a non-negative integer.`);if(!Number.isInteger(e.width)||e.width<0)throw new TypeError(`${t}.width must be a non-negative integer.`);if(!Number.isInteger(e.height)||e.height<0)throw new TypeError(`${t}.height must be a non-negative integer.`)},Pe=e=>new Promise(t=>setTimeout(t,e));class Ie{constructor(){this._listeners=new Map}on(e,t,i){var r;this._listeners.has(e)||this._listeners.set(e,new Set);const n={fn:t,once:null!=(r=null==i?void 0:i.once)&&r};return this._listeners.get(e).add(n),()=>{var t;null==(t=this._listeners.get(e))||t.delete(n)}}_emit(...e){const[t,i]=e,r=this._listeners.get(t);if(r)for(const s of r){try{s.fn(i)}catch(n){console.error(n)}s.once&&r.delete(s)}}}class xe{constructor(e,t){if(this.data=e,this.mimeType=t,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if("string"!==typeof t)throw new TypeError("mimeType must be a string.")}}class Ce{constructor(e,t,i,r){if(this.data=e,this.mimeType=t,this.name=i,this.description=r,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(void 0!==t&&"string"!==typeof t)throw new TypeError("mimeType, when provided, must be a string.");if(void 0!==i&&"string"!==typeof i)throw new TypeError("name, when provided, must be a string.");if(void 0!==r&&"string"!==typeof r)throw new TypeError("description, when provided, must be a string.")}}const Be={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1};class Ee{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){var e;const t=Math.floor(this.pos/8),i=null!=(e=this.bytes[t])?e:0,r=7-(7&this.pos),n=(i&1<>r;return this.pos++,n}readBits(e){if(1===e)return this.readBit();let t=0;for(let i=0;i>i-r-1<{if(!e||e.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");const t=new Ee(e);let i=t.readBits(5);31===i&&(i=32+t.readBits(6));const r=t.readBits(4);let n=null;15===r?n=t.readBits(24):r<_e.length&&(n=_e[r]);const s=t.readBits(4);let a=null;return s>=1&&s<=7&&(a=Ae[s]),{objectType:i,frequencyIndex:r,sampleRate:n,channelConfiguration:s,numberOfChannels:a}},Re=["avc","hevc","vp9","av1","vp8"],De=["pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be","pcm-u8","pcm-s8","ulaw","alaw"],Me=["aac","opus","mp3","vorbis","flac","ac3","eac3",...De],Ne=[{maxMacroblocks:99,maxBitrate:64e3,maxDpbMbs:396,level:10},{maxMacroblocks:396,maxBitrate:192e3,maxDpbMbs:900,level:11},{maxMacroblocks:396,maxBitrate:384e3,maxDpbMbs:2376,level:12},{maxMacroblocks:396,maxBitrate:768e3,maxDpbMbs:2376,level:13},{maxMacroblocks:396,maxBitrate:2e6,maxDpbMbs:2376,level:20},{maxMacroblocks:792,maxBitrate:4e6,maxDpbMbs:4752,level:21},{maxMacroblocks:1620,maxBitrate:4e6,maxDpbMbs:8100,level:22},{maxMacroblocks:1620,maxBitrate:1e7,maxDpbMbs:8100,level:30},{maxMacroblocks:3600,maxBitrate:14e6,maxDpbMbs:18e3,level:31},{maxMacroblocks:5120,maxBitrate:2e7,maxDpbMbs:20480,level:32},{maxMacroblocks:8192,maxBitrate:2e7,maxDpbMbs:32768,level:40},{maxMacroblocks:8192,maxBitrate:5e7,maxDpbMbs:32768,level:41},{maxMacroblocks:8704,maxBitrate:5e7,maxDpbMbs:34816,level:42},{maxMacroblocks:22080,maxBitrate:135e6,maxDpbMbs:110400,level:50},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:51},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:52},{maxMacroblocks:139264,maxBitrate:24e7,maxDpbMbs:696320,level:60},{maxMacroblocks:139264,maxBitrate:48e7,maxDpbMbs:696320,level:61},{maxMacroblocks:139264,maxBitrate:8e8,maxDpbMbs:696320,level:62}],Oe=[{maxPictureSize:36864,maxBitrate:2e5,level:10},{maxPictureSize:73728,maxBitrate:8e5,level:11},{maxPictureSize:122880,maxBitrate:18e5,level:20},{maxPictureSize:245760,maxBitrate:36e5,level:21},{maxPictureSize:552960,maxBitrate:72e5,level:30},{maxPictureSize:983040,maxBitrate:12e6,level:31},{maxPictureSize:2228224,maxBitrate:18e6,level:40},{maxPictureSize:2228224,maxBitrate:3e7,level:41},{maxPictureSize:8912896,maxBitrate:6e7,level:50},{maxPictureSize:8912896,maxBitrate:12e7,level:51},{maxPictureSize:8912896,maxBitrate:18e7,level:52},{maxPictureSize:35651584,maxBitrate:18e7,level:60},{maxPictureSize:35651584,maxBitrate:24e7,level:61},{maxPictureSize:35651584,maxBitrate:48e7,level:62}],Le=".01.01.01.01.00",ze=".0.110.01.01.01.0",Ue=e=>{const{codec:t,codecDescription:i,colorSpace:r,avcCodecInfo:n,hevcCodecInfo:s,vp9CodecInfo:a,av1CodecInfo:o}=e;if("avc"===t){if(y(null!==e.avcType),n){const t=new Uint8Array([n.avcProfileIndication,n.profileCompatibility,n.avcLevelIndication]);return`avc${e.avcType}.${N(t)}`}if(!i||i.byteLength<4)throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${e.avcType}.${N(i.subarray(1,4))}`}if("hevc"===t){let e,t,r,n,a,o;if(s)e=s.generalProfileSpace,t=s.generalProfileIdc,r=O(s.generalProfileCompatibilityFlags),n=s.generalTierFlag,a=s.generalLevelIdc,o=[...s.generalConstraintIndicatorFlags];else{if(!i||i.byteLength<23)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");const s=P(i),l=s.getUint8(1);e=l>>6&3,t=31&l,r=O(s.getUint32(2)),n=l>>5&1,a=s.getUint8(12),o=[];for(let e=0;e<6;e++)o.push(s.getUint8(6+e))}let l="hev1.";for(l+=["","A","B","C"][e]+t,l+=".",l+=r.toString(16).toUpperCase(),l+=".",l+=0===n?"L":"H",l+=a;o.length>0&&0===o[o.length-1];)o.pop();return o.length>0&&(l+=".",l+=o.map(e=>e.toString(16).toUpperCase()).join(".")),l}if("vp8"===t)return"vp8";if("vp9"===t){if(!a){const t=e.width*e.height;let i=T(Oe).level;for(const e of Oe)if(t<=e.maxPictureSize){i=e.level;break}return`vp09.00.${i.toString().padStart(2,"0")}.08`}let t=`vp09.${a.profile.toString().padStart(2,"0")}.${a.level.toString().padStart(2,"0")}.${a.bitDepth.toString().padStart(2,"0")}.${a.chromaSubsampling.toString().padStart(2,"0")}`;return t+=`.${a.colourPrimaries.toString().padStart(2,"0")}.${a.transferCharacteristics.toString().padStart(2,"0")}.${a.matrixCoefficients.toString().padStart(2,"0")}.${a.videoFullRangeFlag.toString().padStart(2,"0")}`,t.endsWith(Le)&&(t=t.slice(0,-15)),t}if("av1"===t){if(!o){const t=e.width*e.height;let i=T(Oe).level;for(const e of Oe)if(t<=e.maxPictureSize){i=e.level;break}return`av01.0.${i.toString().padStart(2,"0")}M.08`}const t=o.profile,i=o.level.toString().padStart(2,"0"),n=o.tier?"H":"M",s=o.bitDepth.toString().padStart(2,"0"),a=o.monochrome?"1":"0",l=100*o.chromaSubsamplingX+10*o.chromaSubsamplingY+1*(o.chromaSubsamplingX&&o.chromaSubsamplingY?o.chromaSamplePosition:0),c=(null==r?void 0:r.primaries)?C[r.primaries]:1,u=(null==r?void 0:r.transfer)?E[r.transfer]:1,d=(null==r?void 0:r.matrix)?A[r.matrix]:1,h=(null==r?void 0:r.fullRange)?1:0;let f=`av01.${t}.${i}${n}.${s}`;return f+=`.${a}.${l.toString().padStart(3,"0")}`,f+=`.${c.toString().padStart(2,"0")}`,f+=`.${u.toString().padStart(2,"0")}`,f+=`.${d.toString().padStart(2,"0")}`,f+=`.${h}`,f.endsWith(ze)&&(f=f.slice(0,-17)),f}throw new TypeError(`Unhandled codec '${t}'.`)},qe=e=>{const{codec:t,codecDescription:i,aacCodecInfo:r}=e;if("aac"===t){if(!r)throw new TypeError("AAC codec info must be provided.");if(r.isMpeg2)return"mp4a.67";{let e;if(null!==r.objectType)e=r.objectType;else{e=Fe(i).objectType}return`mp4a.40.${e}`}}if("mp3"===t)return"mp3";if("opus"===t)return"opus";if("vorbis"===t)return"vorbis";if("flac"===t)return"flac";if("ac3"===t)return"ac-3";if("eac3"===t)return"ec-3";if(t&&De.includes(t))return t;throw new TypeError(`Unhandled codec '${t}'.`)},We=48e3,Ve=/^pcm-([usf])(\d+)+(be)?$/,He=e=>{if(y(De.includes(e)),"ulaw"===e)return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if("alaw"===e)return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};const t=Ve.exec(e);let i;y(t),i="u"===t[1]?"unsigned":"s"===t[1]?"signed":"float";return{dataType:i,sampleSize:Number(t[2])/8,littleEndian:"be"!==t[3],silentValue:"pcm-u8"===e?o(2,7):0}},Ke=e=>e.startsWith("avc1")||e.startsWith("avc3")?"avc":e.startsWith("hev1")||e.startsWith("hvc1")?"hevc":"vp8"===e?"vp8":e.startsWith("vp09")?"vp9":e.startsWith("av01")?"av1":"mp3"===e||"mp4a.69"===e||"mp4a.6B"===e||"mp4a.6b"===e||"mp4a.40.34"===e?"mp3":e.startsWith("mp4a.40.")||"mp4a.67"===e?"aac":"opus"===e?"opus":"vorbis"===e?"vorbis":"flac"===e?"flac":"ac-3"===e||"ac3"===e?"ac3":"ec-3"===e||"eac3"===e?"eac3":"ulaw"===e?"ulaw":"alaw"===e?"alaw":Ve.test(e)?e:"webvtt"===e?"webvtt":null,je=[44100,48e3,32e3],Xe=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,32,40,48,56,64,80,96,112,128,160,192,224,256,320,-1,-1,32,48,56,64,80,96,112,128,160,192,224,256,320,384,-1,-1,32,64,96,128,160,192,224,256,288,320,352,384,416,448,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1,-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1,-1,32,48,56,64,80,96,112,128,144,160,176,192,224,256,-1],$e=1483304551,Qe=1231971951,Ge=(e,t)=>3===e?3===t?21:36:3===t?13:21,Ye=(e,t)=>{const i=e>>>24,r=e>>>16&255,n=e>>>8&255,s=255&e;if(255!==i&&255!==r&&255!==n&&255!==s)return{header:null,bytesAdvanced:4};if(255!==i)return{header:null,bytesAdvanced:1};if(224!==(224&r))return{header:null,bytesAdvanced:1};let a=0,o=0;16&r?a=8&r?0:1:(a=1,o=1);const l=r>>3&3,c=r>>1&3,u=(n>>2&3)%3,d=s>>6&3,h=s>>4&3,f=s>>3&1,m=s>>2&1,p=3&s,g=Xe[16*a*4+16*c+(n>>4&15)];if(-1===g)return{header:null,bytesAdvanced:1};const k=1e3*g,y=je[u]>>a+o,b=((e,t,i,r,n)=>0===t?0:1===t?Math.floor(144*i/(r<>1&1);if(null!==t&&t{let t=2130706432,i=0;for(;0!==t;)i>>=1,i|=e&t,t>>=8;return i};var Ze,et;(et=Ze||(Ze={}))[et.FrameCount=1]="FrameCount",et[et.FileSize=2]="FileSize",et[et.Toc=4]="Toc";const tt=[48e3,44100,32e3],it=[24e3,22050,16e3];var rt,nt,st,at;(nt=rt||(rt={}))[nt.NON_IDR_SLICE=1]="NON_IDR_SLICE",nt[nt.SLICE_DPA=2]="SLICE_DPA",nt[nt.SLICE_DPB=3]="SLICE_DPB",nt[nt.SLICE_DPC=4]="SLICE_DPC",nt[nt.IDR=5]="IDR",nt[nt.SEI=6]="SEI",nt[nt.SPS=7]="SPS",nt[nt.PPS=8]="PPS",nt[nt.AUD=9]="AUD",nt[nt.SPS_EXT=13]="SPS_EXT",(at=st||(st={}))[at.RASL_N=8]="RASL_N",at[at.RASL_R=9]="RASL_R",at[at.BLA_W_LP=16]="BLA_W_LP",at[at.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",at[at.VPS_NUT=32]="VPS_NUT",at[at.SPS_NUT=33]="SPS_NUT",at[at.PPS_NUT=34]="PPS_NUT",at[at.AUD_NUT=35]="AUD_NUT",at[at.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",at[at.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT";const ot=function*(e){let t=0,i=-1;for(;t=e.length-2)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&w(t.description)[4];return lt(e,i+1)}return ot(e)},ut=e=>31&e,dt=e=>{const t=[],i=e.length;for(let r=0;r{const t=e.reduce((e,t)=>e+ht.byteLength+t.byteLength,0),i=new Uint8Array(t);let r=0;for(const n of e)i.set(ht,r),r+=ht.byteLength,i.set(n,r),r+=n.byteLength;return i},mt=(e,t)=>{const i=e.reduce((e,i)=>e+t+i.byteLength,0),r=new Uint8Array(i);let n=0;for(const s of e){const e=new DataView(r.buffer,r.byteOffset,r.byteLength);switch(t){case 1:e.setUint8(n,s.byteLength);break;case 2:e.setUint16(n,s.byteLength,!1);break;case 3:j(e,n,s.byteLength);break;case 4:e.setUint32(n,s.byteLength,!1)}n+=t,r.set(s,n),n+=s.byteLength}return r},pt=e=>{try{const t=[],i=[],r=[];for(const o of ot(e)){const n=e.subarray(o.offset,o.offset+o.length),s=ut(n[0]);s===rt.SPS?t.push(n):s===rt.PPS?i.push(n):s===rt.SPS_EXT&&r.push(n)}if(0===t.length)return null;if(0===i.length)return null;const n=t[0],s=kt(n);y(null!==s);const a=100===s.profileIdc||110===s.profileIdc||122===s.profileIdc||144===s.profileIdc;return{configurationVersion:1,avcProfileIndication:s.profileIdc,profileCompatibility:s.constraintFlags,avcLevelIndication:s.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:t,pictureParameterSets:i,chromaFormat:a?s.chromaFormatIdc:null,bitDepthLumaMinus8:a?s.bitDepthLumaMinus8:null,bitDepthChromaMinus8:a?s.bitDepthChromaMinus8:null,sequenceParameterSetExt:a?r:null}}catch(t){return console.error("Error building AVC Decoder Configuration Record:",t),null}},gt={1:{num:1,den:1},2:{num:12,den:11},3:{num:10,den:11},4:{num:16,den:11},5:{num:40,den:33},6:{num:24,den:11},7:{num:20,den:11},8:{num:32,den:11},9:{num:80,den:33},10:{num:18,den:11},11:{num:15,den:11},12:{num:64,den:33},13:{num:160,den:99},14:{num:4,den:3},15:{num:3,den:2},16:{num:2,den:1}},kt=e=>{var t;try{const i=new Ee(dt(e));i.skipBits(1),i.skipBits(2);if(7!==i.readBits(5))return null;const r=i.readAlignedByte(),n=i.readAlignedByte(),s=i.readAlignedByte();S(i);let a=1,o=0,l=0,c=0;if(100===r||110===r||122===r||244===r||44===r||83===r||86===r||118===r||128===r){a=S(i),3===a&&(c=i.readBits(1)),o=S(i),l=S(i),i.skipBits(1);if(i.readBits(1))for(let e=0;e<(3!==a?8:12);e++){if(i.readBits(1)){const t=e<6?16:64;let r=8,n=8;for(let e=0;ee.level>=s))?t:T(Ne),n=Math.min(Math.floor(r.maxDpbMbs/(e*i)),16);C=n,B=n}else C=0,B=0}return y(null!==B),{profileIdc:r,constraintFlags:n,levelIdc:s,frameMbsOnlyFlag:k,chromaFormatIdc:a,bitDepthLumaMinus8:o,bitDepthChromaMinus8:l,codedWidth:f,codedHeight:m,displayWidth:p,displayHeight:g,pixelAspectRatio:x,colourPrimaries:b,matrixCoefficients:P,transferCharacteristics:w,fullRangeFlag:I,numReorderFrames:C,maxDecFrameBuffering:B}}catch(i){return console.error("Error parsing AVC SPS:",i),null}},yt=e=>{const t=S(e);e.skipBits(4),e.skipBits(4);for(let i=0;i<=t;i++)S(e),S(e),e.skipBits(1);e.skipBits(5),e.skipBits(5),e.skipBits(5),e.skipBits(5)},bt=(e,t)=>{if(t.description){const i=3&w(t.description)[21];return lt(e,i+1)}return ot(e)},Tt=e=>e>>1&63,St=e=>{try{const t=new Ee(dt(e));t.skipBits(16),t.readBits(4);const i=t.readBits(3),r=t.readBits(1),{general_profile_space:n,general_tier_flag:s,general_profile_idc:a,general_profile_compatibility_flags:o,general_constraint_indicator_flags:l,general_level_idc:c}=wt(t,i);S(t);const u=S(t);let d=0;3===u&&(d=t.readBits(1));const h=S(t),f=S(t);let m=h,p=f;if(t.readBits(1)){const e=S(t),i=S(t),r=S(t),n=S(t);let s=1,a=1;const o=0===d?u:0;1===o?(s=2,a=2):2===o&&(s=2,a=1),m-=(e+i)*s,p-=(r+n)*a}const g=S(t),k=S(t);S(t);const y=t.readBits(1);let b=0;for(let e=y?0:i;e<=i;e++)S(t),b=S(t),S(t);S(t),S(t),S(t),S(t),S(t),S(t),t.readBits(1)&&t.readBits(1)&&Pt(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(4),t.skipBits(4),S(t),S(t),t.skipBits(1));const T=S(t);if(It(t,T),t.readBits(1)){const e=S(t);for(let i=0;i{try{const t=[],i=[],r=[],n=[];for(const l of ot(e)){const s=e.subarray(l.offset,l.offset+l.length),a=Tt(s[0]);a===st.VPS_NUT?t.push(s):a===st.SPS_NUT?i.push(s):a===st.PPS_NUT?r.push(s):a!==st.PREFIX_SEI_NUT&&a!==st.SUFFIX_SEI_NUT||n.push(s)}if(0===i.length||0===r.length)return null;const s=St(i[0]);if(!s)return null;let a=0;if(r.length>0){const e=r[0],t=new Ee(dt(e));t.skipBits(16),S(t),S(t),t.skipBits(1),t.skipBits(1),t.skipBits(3),t.skipBits(1),t.skipBits(1),S(t),S(t),v(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&S(t),v(t),v(t),t.skipBits(1),t.skipBits(1),t.skipBits(1),t.skipBits(1);const i=t.readBits(1),n=t.readBits(1);a=i||n?i&&!n?2:!i&&n?3:0:0}const o=[...t.length?[{arrayCompleteness:1,nalUnitType:st.VPS_NUT,nalUnits:t}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:st.SPS_NUT,nalUnits:i}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:st.PPS_NUT,nalUnits:r}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:Tt(n[0][0]),nalUnits:n}]:[]];return{configurationVersion:1,generalProfileSpace:s.generalProfileSpace,generalTierFlag:s.generalTierFlag,generalProfileIdc:s.generalProfileIdc,generalProfileCompatibilityFlags:s.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:s.generalConstraintIndicatorFlags,generalLevelIdc:s.generalLevelIdc,minSpatialSegmentationIdc:s.minSpatialSegmentationIdc,parallelismType:a,chromaFormatIdc:s.chromaFormatIdc,bitDepthLumaMinus8:s.bitDepthLumaMinus8,bitDepthChromaMinus8:s.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:s.spsMaxSubLayersMinus1+1,temporalIdNested:s.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:o}}catch(t){return console.error("Error building HEVC Decoder Configuration Record:",t),null}},wt=(e,t)=>{const i=e.readBits(2),r=e.readBits(1),n=e.readBits(5);let s=0;for(let u=0;u<32;u++)s=s<<1|e.readBits(1);const a=new Uint8Array(6);for(let u=0;u<6;u++)a[u]=e.readBits(8);const o=e.readBits(8),l=[],c=[];for(let u=0;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&&v(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-(S(e)+1)}else o=t-1;e.readBits(1),S(e);const a=null!=(n=r[o])?n:0;for(let t=0;t<=a;t++){e.readBits(1)||e.readBits(1)}s=r[o]}else{const t=S(e),i=S(e);for(let r=0;r{let i=2,r=2,n=2,s=0,a=0,o={num:1,den:1};if(e.readBits(1)){const t=e.readBits(8);if(255===t)o={num:e.readBits(16),den:e.readBits(16)};else{const e=gt[t];e&&(o=e)}}return e.readBits(1)&&e.readBits(1),e.readBits(1)&&(e.readBits(3),s=e.readBits(1),e.readBits(1)&&(i=e.readBits(8),r=e.readBits(8),n=e.readBits(8))),e.readBits(1)&&(S(e),S(e)),e.readBits(1),e.readBits(1),e.readBits(1),e.readBits(1)&&(S(e),S(e),S(e),S(e)),e.readBits(1)&&(e.readBits(32),e.readBits(32),e.readBits(1)&&S(e),e.readBits(1)&&Bt(e,!0,t)),e.readBits(1)&&(e.readBits(1),e.readBits(1),e.readBits(1),a=S(e),S(e),S(e),S(e),S(e)),{pixelAspectRatio:o,colourPrimaries:i,transferCharacteristics:r,matrixCoefficients:n,fullRangeFlag:s,minSpatialSegmentationIdc:a}},Bt=(e,t,i)=>{let r=!1,n=!1,s=!1;r=1===e.readBits(1),n=1===e.readBits(1),(r||n)&&(s=1===e.readBits(1),s&&(e.readBits(8),e.readBits(5),e.readBits(1),e.readBits(5)),e.readBits(4),e.readBits(4),s&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5));for(let a=0;a<=i;a++){let t=!0;1===e.readBits(1)||(t=1===e.readBits(1));let i=!1;t?S(e):i=1===e.readBits(1);let a=1;if(!i){a=S(e)+1}r&&Et(e,a,s),n&&Et(e,a,s)}},Et=(e,t,i)=>{for(let r=0;r{const i=new Set;let r=_t.audAllowed;for(const s of bt(e,t)){if(r===_t.noMoreDataAllowed){i.add(s.offset);continue}const t=Tt(e[s.offset]);if(r===_t.eoBitstreamAllowed&&37!==t){i.add(s.offset);continue}let n=!1;35===t?r>_t.audAllowed?n=!0:r=_t.beforeFirstVcl:t<=31?r>_t.afterFirstVcl?n=!0:r=_t.afterFirstVcl:36===t?r!==_t.afterFirstVcl?n=!0:r=_t.eoBitstreamAllowed:37===t?r<_t.afterFirstVcl?n=!0:r=_t.noMoreDataAllowed:32===t||33===t||34===t||39===t||t>=41&&t<=44||t>=48&&t<=55?r>_t.beforeFirstVcl?n=!0:r=_t.beforeFirstVcl:(38===t||40===t||t>=45&&t<=47||t>=56&&t<=63)&&r<_t.afterFirstVcl&&(n=!0),n&&i.add(s.offset)}if(0===i.size)return null;const n=[];for(const s of bt(e,t))i.has(s.offset)||n.push(e.subarray(s.offset,s.offset+s.length));return((e,t)=>{if(t.description){const i=3&w(t.description)[21];return mt(e,i+1)}return ft(e)})(n,t)},Rt=e=>{const t=new Ee(e);if(2!==t.readBits(2))return null;const i=t.readBits(1),r=(t.readBits(1)<<1)+i;3===r&&t.skipBits(1);if(1===t.readBits(1))return null;if(0!==t.readBits(1))return null;t.skipBits(2);if(4817730!==t.readBits(24))return null;let n=8;if(r>=2){n=t.readBits(1)?12:10}const s=t.readBits(3);let a=0,o=0;if(7!==s){if(o=t.readBits(1),1===r||3===r){const e=t.readBits(1),i=t.readBits(1);a=e||i?e&&!i?2:1:3,t.skipBits(1)}else a=1}else a=3,o=1;const l=(t.readBits(16)+1)*(t.readBits(16)+1);let c=T(Oe).level;for(const u of Oe)if(l<=u.maxPictureSize){c=u.level;break}return{profile:r,level:c,bitDepth:n,chromaSubsampling:a,videoFullRangeFlag:o,colourPrimaries:2===s?1:1===s?6:2,transferCharacteristics:2===s?1:1===s?6:2,matrixCoefficients:7===s?0:2===s?1:1===s?6:2}},Dt=function*(e){const t=new Ee(e),i=()=>{let e=0;for(let i=0;i<8;i++){const r=t.readAlignedByte();if(e|=(127&r)<<7*i,!(128&r))break;if(7===i&&128&r)return null}return e>=o(2,32)-1?null:e};for(;t.getBitsLeft()>=8;){t.skipBits(1);const r=t.readBits(4),n=t.readBits(1),s=t.readBits(1);let a;if(t.skipBits(1),n&&t.skipBits(8),s){const e=i();if(null===e)return;a=e}else a=Math.floor(t.getBitsLeft()/8);y(t.pos%8===0),yield{type:r,data:e.subarray(t.pos/8,t.pos/8+a)},t.skipBits(8*a)}},Mt=e=>{for(const{type:t,data:i}of Dt(e)){if(1!==t)continue;const e=new Ee(i),r=e.readBits(3);e.readBits(1);const n=e.readBits(1);let s=0,a=0,o=0;if(n)s=e.readBits(5);else{if(e.readBits(1)){e.skipBits(32),e.skipBits(32);if(e.readBits(1))return null}const t=e.readBits(1);t&&(o=e.readBits(5),e.skipBits(32),e.skipBits(5),e.skipBits(5));const i=e.readBits(5);for(let r=0;r<=i;r++){e.skipBits(12);const i=e.readBits(5);if(0===r&&(s=i),i>7){const t=e.readBits(1);0===r&&(a=t)}if(t){if(e.readBits(1)){const t=o+1;e.skipBits(t),e.skipBits(t),e.skipBits(1)}}e.readBits(1)&&e.skipBits(4)}}const l=e.readBits(4),c=e.readBits(4),u=l+1;e.skipBits(u);const d=c+1;e.skipBits(d);let h=0;if(h=n?0:e.readBits(1),h&&(e.skipBits(4),e.skipBits(3)),e.skipBits(1),e.skipBits(1),e.skipBits(1),!n){e.skipBits(1),e.skipBits(1),e.skipBits(1),e.skipBits(1);const t=e.readBits(1);t&&(e.skipBits(1),e.skipBits(1));let i=0;if(i=e.readBits(1)?2:e.readBits(1),i>0){e.readBits(1)||e.skipBits(1)}t&&e.skipBits(3)}e.skipBits(1),e.skipBits(1),e.skipBits(1);const f=e.readBits(1);let m=8;if(2===r&&f){m=e.readBits(1)?12:10}else r<=2&&(m=f?10:8);let p=0;1!==r&&(p=e.readBits(1));let g=1,k=1,y=0;return p||(0===r?(g=1,k=1):1===r?(g=0,k=0):12===m&&(g=e.readBits(1),g&&(k=e.readBits(1))),g&&k&&(y=e.readBits(2))),{profile:r,level:s,tier:a,bitDepth:m,monochrome:p,chromaSubsamplingX:g,chromaSubsamplingY:k,chromaSamplePosition:y}}return null},Nt=[480,960,1920,2880,480,960,1920,2880,480,960,1920,2880,480,960,480,960,120,240,480,960,120,240,480,960,120,240,480,960,120,240,480,960],Ot=e=>{if(e.length<7)throw new Error("Setup header is too short.");if(5!==e[0])throw new Error("Wrong packet type in Setup header.");if("vorbis"!==String.fromCharCode(...e.slice(1,7)))throw new Error("Invalid packet signature in Setup header.");const t=e.length,i=new Uint8Array(t);for(let u=0;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}},Lt=(e,t,i)=>{switch(e){case"avc":for(const e of ct(i,t)){const t=i[e.offset],r=ut(t);if(r>=rt.NON_IDR_SLICE&&r<=rt.SLICE_DPC)return"delta";if(r===rt.IDR)return"key";if(r===rt.SEI&&(!de()||fe()>=144)){const t=i.subarray(e.offset,e.offset+e.length),r=dt(t);let n=1;do{let e=0;for(;;){const t=r[n++];if(void 0===t)break;if(e+=t,t<255)break}let t=0;for(;;){const e=r[n++];if(void 0===e)break;if(t+=e,e<255)break}if(e===6){const e=new Ee(r);e.pos=8*n;const t=S(e),i=e.readBits(1);if(0===t&&1===i)return"key"}n+=t}while(n{var i,r;const n=P(e);let s=0;const a=n.getUint32(s,!0);s+=4;const o=I.decode(e.subarray(s,s+a));s+=a,a>0&&(null!=t.raw||(t.raw={}),null!=(i=t.raw).vendor||(i.vendor=o));const l=n.getUint32(s,!0);s+=4;for(let c=0;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=ge(c),i=P(e),r=i.getUint32(0,!1),n=i.getUint32(4,!1),s=String.fromCharCode(...e.subarray(8,8+n)),a=i.getUint32(8+n,!1),o=I.decode(e.subarray(12+n,12+n+a)),l=i.getUint32(n+a+28),u=e.subarray(n+a+32,n+a+32+l);null!=t.images||(t.images=[]),t.images.push({data:u,mimeType:s,kind:3===r?"coverFront":4===r?"coverBack":"unknown",name:void 0,description:o||void 0})}}}},Wt=[2,1,2,3,3,4,4,5],Vt=e=>{if(e.length<7)return null;if(11!==e[0]||119!==e[1])return null;const t=new Ee(e);t.skipBits(16),t.skipBits(16);const i=t.readBits(2);if(3===i)return null;const r=t.readBits(6),n=t.readBits(5);if(n>8)return null;const s=t.readBits(3),a=t.readBits(3);0!==(1&a)&&1!==a&&t.skipBits(2),0!==(4&a)&&t.skipBits(2),2===a&&t.skipBits(2);return{fscod:i,bsid:n,bsmod:s,acmod:a,lfeon:t.readBits(1),bitRateCode:Math.floor(r/2)}},Ht=[128,138,192,128,140,192,160,174,240,160,176,240,192,208,288,192,210,288,224,242,336,224,244,336,256,278,384,256,280,384,320,348,480,320,350,480,384,416,576,384,418,576,448,486,672,448,488,672,512,556,768,512,558,768,640,696,960,640,698,960,768,834,1152,768,836,1152,896,974,1344,896,976,1344,1024,1114,1536,1024,1116,1536,1280,1392,1920,1280,1394,1920,1536,1670,2304,1536,1672,2304,1792,1950,2688,1792,1952,2688,2048,2228,3072,2048,2230,3072,2304,2506,3456,2304,2508,3456,2560,2786,3840,2560,2788,3840],Kt=[1,2,3,6],jt=e=>{if(e.length<6)return null;if(11!==e[0]||119!==e[1])return null;const t=new Ee(e);t.skipBits(16);const i=t.readBits(2);if(t.skipBits(3),0!==i&&2!==i)return null;const r=t.readBits(11),n=t.readBits(2);let s,a=0;3===n?(a=t.readBits(2),s=3):s=t.readBits(2);const o=t.readBits(3),l=t.readBits(1),c=t.readBits(5);if(c<11||c>16)return null;const u=Kt[s];let d;d=n<3?tt[n]/1e3:it[a]/1e3;return{dataRate:Math.round((r+1)*d/(16*u)),substreams:[{fscod:n,fscod2:a,bsid:c,bsmod:0,acmod:o,lfeon:l,numDepSub:0,chanLoc:0}]}},Xt=e=>{const t=e.substreams[0];return y(t),t.fscod<3?tt[t.fscod]:null!==t.fscod2&&t.fscod2<3?it[t.fscod2]:null},$t=e=>{const t=e.substreams[0];y(t);let i=Wt[t.acmod]+t.lfeon;if(t.numDepSub>0){const e=[2,2,1,1,2,2,2,1,1];for(let r=0;r<9;r++)t.chanLoc&1<<8-r&&(i+=e[r])}return i};class Qt{constructor(e){this.input=e}dispose(){}}const Gt=new Uint8Array(0);class Yt{constructor(e,t,i,r,n=-1,s,a){if(this.data=e,this.type=t,this.timestamp=i,this.duration=r,this.sequenceNumber=n,e===Gt&&void 0===s)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(void 0===s&&(s=e.byteLength),!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if("key"!==t&&"delta"!==t)throw new TypeError('type must be either "key" or "delta".');if(!Number.isFinite(i))throw new TypeError("timestamp must be a number.");if(!Number.isFinite(r)||r<0)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(n))throw new TypeError("sequenceNumber must be a number.");if(!Number.isInteger(s)||s<0)throw new TypeError("byteLength must be a non-negative integer.");if(void 0!==a&&("object"!==typeof a||!a))throw new TypeError("sideData, when provided, must be an object.");if(void 0!==(null==a?void 0:a.alpha)&&!(a.alpha instanceof Uint8Array))throw new TypeError("sideData.alpha, when provided, must be a Uint8Array.");if(void 0!==(null==a?void 0:a.alphaByteLength)&&(!Number.isInteger(a.alphaByteLength)||a.alphaByteLength<0))throw new TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=s,this.sideData=null!=a?a:{},this.sideData.alpha&&void 0===this.sideData.alphaByteLength&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===Gt}get microsecondTimestamp(){return Math.trunc(te*this.timestamp)}get microsecondDuration(){return Math.trunc(te*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if("undefined"===typeof EncodedVideoChunk)throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw new TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if("undefined"===typeof EncodedVideoChunk)throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to an audio chunk.");if("undefined"===typeof EncodedAudioChunk)throw new Error("Your browser does not support EncodedAudioChunk.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(e,t){var i;if(!(e instanceof EncodedVideoChunk||e instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");const r=new Uint8Array(e.byteLength);return e.copyTo(r),new Yt(r,e.type,e.timestamp/1e6,(null!=(i=e.duration)?i:0)/1e6,void 0,void 0,t)}clone(e){var t,i,r,n,s,a;if(void 0!==e&&("object"!==typeof e||null===e))throw new TypeError("options, when provided, must be an object.");if(void 0!==(null==e?void 0:e.data)&&!(e.data instanceof Uint8Array))throw new TypeError("options.data, when provided, must be a Uint8Array.");if(void 0!==(null==e?void 0:e.type)&&"key"!==e.type&&"delta"!==e.type)throw new TypeError('options.type, when provided, must be either "key" or "delta".');if(void 0!==(null==e?void 0:e.timestamp)&&!Number.isFinite(e.timestamp))throw new TypeError("options.timestamp, when provided, must be a number.");if(void 0!==(null==e?void 0:e.duration)&&!Number.isFinite(e.duration))throw new TypeError("options.duration, when provided, must be a number.");if(void 0!==(null==e?void 0:e.sequenceNumber)&&!Number.isFinite(e.sequenceNumber))throw new TypeError("options.sequenceNumber, when provided, must be a number.");if(void 0!==(null==e?void 0:e.sideData)&&("object"!==typeof e.sideData||null===e.sideData))throw new TypeError("options.sideData, when provided, must be an object.");return new Yt(null!=(t=null==e?void 0:e.data)?t:this.data,null!=(i=null==e?void 0:e.type)?i:this.type,null!=(r=null==e?void 0:e.timestamp)?r:this.timestamp,null!=(n=null==e?void 0:e.duration)?n:this.duration,null!=(s=null==e?void 0:e.sequenceNumber)?s:this.sequenceNumber,this.byteLength,null!=(a=null==e?void 0:e.sideData)?a:this.sideData)}}const Jt=e=>{const t=P(e);let i=0;const r=t.getUint8(i);i+=1,i+=3;const n=N(e.subarray(i,i+16));i+=16;let s=null;if(r>0){const r=t.getUint32(i);if(i+=4,r>0){s=[];for(let t=0;te.systemId===t.systemId&&((e,t)=>{if(e.length!==t.length)return!1;for(let i=0;i{let t=Ra(e);const i=Wa(e,4);let r=8;1===t&&(t=Oa(e),r=16);const n=t-r;return n<0?null:{name:i,totalSize:t,headerSize:r,contentSize:n}},ti=e=>Ma(e)/65536,ii=e=>Ma(e)/1073741824,ri=e=>{let t=0;for(let i=0;i<4;i++){t<<=7;const i=Ca(e);if(t|=127&i,0===(128&i))break}return t},ni=e=>{let t=Ea(e);return e.skip(2),t=Math.min(t,e.remainingLength),I.decode(xa(e,t))},si=e=>{const t=ei(e);if(!t||"data"!==t.name)return null;if(e.remainingLength<8)return null;const i=Ra(e);e.skip(4);const r=xa(e,t.contentSize-8);switch(i){case 1:return I.decode(r);case 2:return new TextDecoder("utf-16be").decode(r);case 13:return new xe(r,"image/jpeg");case 14:return new xe(r,"image/png");case 27:return new xe(r,"image/bmp");default:return r}},ai=16,oi=new Uint32Array(256),li=new Uint32Array(256),ci=new Uint32Array(256),ui=new Uint32Array(256),di=new Uint32Array(256),hi=new Uint32Array(256),fi=new Uint32Array(10);let mi=!1;class pi{constructor(){this.roundkey=new Uint32Array(44),this.iv=new Uint32Array(ai/Uint32Array.BYTES_PER_ELEMENT),this.in=new Uint8Array(ai),this.out=new Uint8Array(ai),this.inView=new DataView(this.in.buffer),this.outView=new DataView(this.out.buffer)}init({key:e,iv:t}){y(16===e.byteLength),y(16===t.byteLength),mi||(()=>{const e=new Uint8Array(256),t=new Uint8Array(256),i=new Uint8Array(256);for(let s=0,a=1;s<256;s++)i[s]=a,t[a]=s,a=a^a<<1^(128&a?283:0);const r=(e,r)=>e&&r?i[(t[e]+t[r])%255]:0;e[0]=99;for(let s=1;s<256;s++){const r=i[255-t[s]];let n=r^r<<1^r<<2^r<<3^r<<4;n=n>>>8^255&n^99,e[s]=n}for(let s=0;s<256;s++){const t=e[s],i=e.indexOf(s);oi[s]=t<<24|t<<16|t<<8|t,hi[s]=i<<24|i<<16|i<<8|i;const n=r(i,14)<<24|r(i,9)<<16|r(i,13)<<8|r(i,11);li[s]=n,ci[s]=n>>>8|n<<24,ui[s]=n>>>16|n<<16,di[s]=n>>>24|n<<8}let n=1;for(let s=0;s<10;s++)fi[s]=n<<24,n=n<<1^(128&n?283:0);mi=!0})();const i=new DataView(e.buffer,e.byteOffset,e.byteLength),r=new DataView(t.buffer,t.byteOffset,t.byteLength);this.roundkey[0]=i.getUint32(0,!1),this.roundkey[1]=i.getUint32(4,!1),this.roundkey[2]=i.getUint32(8,!1),this.roundkey[3]=i.getUint32(12,!1),this.iv[0]=r.getUint32(0,!1),this.iv[1]=r.getUint32(4,!1),this.iv[2]=r.getUint32(8,!1),this.iv[3]=r.getUint32(12,!1);for(let n=4;n<44;n+=4){const e=this.roundkey[n-1];this.roundkey[n]=this.roundkey[n-4]^4278190080&oi[e>>>16&255]^16711680&oi[e>>>8&255]^65280&oi[e>>>0&255]^255&oi[e>>>24&255]^fi[n/4-1],this.roundkey[n+1]=this.roundkey[n-3]^this.roundkey[n],this.roundkey[n+2]=this.roundkey[n-2]^this.roundkey[n+1],this.roundkey[n+3]=this.roundkey[n-1]^this.roundkey[n+2]}for(let n=0,s=40;n>>24&255]]^ci[255&oi[t>>>16&255]]^ui[255&oi[t>>>8&255]]^di[255&oi[t>>>0&255]]}}decrypt(){let e=this.inView.getUint32(0,!1)^this.roundkey[0],t=this.inView.getUint32(4,!1)^this.roundkey[1],i=this.inView.getUint32(8,!1)^this.roundkey[2],r=this.inView.getUint32(12,!1)^this.roundkey[3];const n=this.inView.getUint32(0,!1),s=this.inView.getUint32(4,!1),a=this.inView.getUint32(8,!1),o=this.inView.getUint32(12,!1);let l,c,u,d;for(let g=1;g<10;g++){const n=4*g;l=li[e>>>24]^ci[r>>>16&255]^ui[i>>>8&255]^di[255&t]^this.roundkey[n],c=li[t>>>24]^ci[e>>>16&255]^ui[r>>>8&255]^di[255&i]^this.roundkey[n+1],u=li[i>>>24]^ci[t>>>16&255]^ui[e>>>8&255]^di[255&r]^this.roundkey[n+2],d=li[r>>>24]^ci[i>>>16&255]^ui[t>>>8&255]^di[255&e]^this.roundkey[n+3],e=l,t=c,i=u,r=d}const h=4278190080&hi[e>>>24&255]^16711680&hi[r>>>16&255]^65280&hi[i>>>8&255]^255&hi[t>>>0&255]^this.roundkey[40],f=4278190080&hi[t>>>24&255]^16711680&hi[e>>>16&255]^65280&hi[r>>>8&255]^255&hi[i>>>0&255]^this.roundkey[41],m=4278190080&hi[i>>>24&255]^16711680&hi[t>>>16&255]^65280&hi[e>>>8&255]^255&hi[r>>>0&255]^this.roundkey[42],p=4278190080&hi[r>>>24&255]^16711680&hi[i>>>16&255]^65280&hi[t>>>8&255]^255&hi[e>>>0&255]^this.roundkey[43];this.outView.setUint32(0,h^this.iv[0],!1),this.outView.setUint32(4,f^this.iv[1],!1),this.outView.setUint32(8,m^this.iv[2],!1),this.outView.setUint32(12,p^this.iv[3],!1),this.iv[0]=n,this.iv[1]=s,this.iv[2]=a,this.iv[3]=o}}class gi extends Qt{constructor(e){super(e),this.moovSlice=null,this.currentTrack=null,this.tracks=[],this.metadataPromise=null,this.movieTimescale=-1,this.movieDurationInTimescale=-1,this.isQuickTime=!1,this.metadataTags={},this.currentMetadataKeys=null,this.isFragmented=!1,this.fragmentTrackDefaults=[],this.psshBoxes=[],this.currentFragment=null,this.lastReadFragment=null,this.decryptionKeyCache=new Map,this.reader=e._reader}getTrackBackings(){return d(this,null,function*(){return yield this.readMetadata(),this.tracks.map(e=>e.trackBacking)})}getMimeType(){return d(this,null,function*(){yield this.readMetadata();const e=yield this.getTrackBackings(),t=yield Promise.all(e.map(e=>e.getDecoderConfig().then(e=>{var t;return null!=(t=null==e?void 0:e.codec)?t:null})));return(e=>{let t=(e.hasVideo?"video/":e.hasAudio?"audio/":"application/")+(e.isQuickTime?"quicktime":"mp4");e.codecStrings.length>0&&(t+=`; codecs="${[...new Set(e.codecStrings)].join(", ")}"`);return t})({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some(e=>{var t;return"video"===(null==(t=e.info)?void 0:t.type)}),hasAudio:this.tracks.some(e=>{var t;return"audio"===(null==(t=e.info)?void 0:t.type)}),codecStrings:t.filter(Boolean)})})}getMetadataTags(){return d(this,null,function*(){return yield this.readMetadata(),this.metadataTags})}readMetadata(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>d(this,null,function*(){let e=0,t=!1;for(;;){let i=this.reader.requestSliceRange(e,8,16);if(i instanceof Promise&&(i=yield i),!i)break;const r=e,n=ei(i);if(!n)break;if("ftyp"===n.name||"styp"===n.name){const e=Wa(i,4);this.isQuickTime="qt "===e}else{if("moov"===n.name){let e=this.reader.requestSlice(i.filePos,n.contentSize);if(e instanceof Promise&&(e=yield e),!e)break;this.moovSlice=e,this.readContiguousBoxes(this.moovSlice);for(const t of this.tracks){const e=t.editListPreviousSegmentDurations/this.movieTimescale;t.editListOffset-=Math.round(e*t.timescale)}t=this.isFragmented&&null!==this.reader.fileSize&&this.reader.fileSize>r+n.totalSize;break}if("moof"===n.name){if(!this.input._initInput)throw new Error('"moof" box encountered with no "moov" box present; this file is likely a Segment as described in ISO/IEC 14496-12 Section 8.16. A separate init file that contains a "moov" box is required to read this file, please provide it using InputOptions.initInput.');const e=yield this.input._initInput._getDemuxer();if(e.constructor!==gi)throw new Error("Init input must match the input's format.");yield e.readMetadata(),this.movieTimescale=e.movieTimescale,this.movieDurationInTimescale=e.movieDurationInTimescale,this.metadataTags=e.metadataTags,this.isFragmented=!0,this.fragmentTrackDefaults=e.fragmentTrackDefaults,this.psshBoxes=e.psshBoxes;for(const t of e.tracks){const e={id:t.id,demuxer:this,trackBacking:null,disposition:t.disposition,timescale:t.timescale,durationInMediaTimescale:t.durationInMediaTimescale,durationInMovieTimescale:t.durationInMovieTimescale,rotation:t.rotation,internalCodecId:t.internalCodecId,name:t.name,languageCode:t.languageCode,sampleTableByteOffset:null,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:t.editListPreviousSegmentDurations,editListOffset:t.editListOffset,encryptionInfo:t.encryptionInfo,encryptionAuxInfo:null,frmaCodecString:null,info:t.info};if(t.trackBacking)if(y(e.info),"video"===e.info.type&&-1!==e.info.width){const t=e;e.trackBacking=new yi(t),this.tracks.push(e)}else if("audio"===e.info.type&&-1!==e.info.numberOfChannels){const t=e;e.trackBacking=new bi(t),this.tracks.push(e)}}t=!1;break}}e=r+n.totalSize}if(t){y(null!==this.reader.fileSize);let e=this.reader.requestSlice(this.reader.fileSize-4,4);e instanceof Promise&&(e=yield e),y(e);const t=Ra(e),i=this.reader.fileSize-t;if(i>=0&&i<=this.reader.fileSize-16){let e=this.reader.requestSliceRange(i,8,16);if(e instanceof Promise&&(e=yield e),e){const t=ei(e);if(t&&"mfra"===t.name){let i=this.reader.requestSlice(e.filePos,t.contentSize);i instanceof Promise&&(i=yield i),i&&this.readContiguousBoxes(i)}}}}}))()}getSampleTableForTrack(e){var t,i;if(e.sampleTable)return e.sampleTable;const r={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};if(e.sampleTable=r,null===e.sampleTableByteOffset)return r;y(this.moovSlice);const n=this.moovSlice.slice(e.sampleTableByteOffset);this.currentTrack=e,this.traverseBox(n),this.currentTrack=null;if("audio"===(null==(t=e.info)?void 0:t.type)&&e.info.codec&&De.includes(e.info.codec)&&0===r.sampleCompositionTimeOffsets.length){y("audio"===(null==(i=e.info)?void 0:i.type));const t=He(e.info.codec),n=[],s=[];for(let i=0;ie.startIndex),u=r.sampleTimingEntries[c],d=z(r.sampleTimingEntries,l,e=>e.startIndex),h=r.sampleTimingEntries[d],f=u.startDecodeTimestamp+(o-u.startIndex)*u.delta,m=h.startDecodeTimestamp+(l-h.startIndex)*h.delta-f,p=T(n);p&&p.delta===m?p.count++:n.push({startIndex:a.startChunkIndex+i,startDecodeTimestamp:f,count:1,delta:m});const g=a.samplesPerChunk*t.sampleSize*e.info.numberOfChannels;s.push(g)}a.startSampleIndex=a.startChunkIndex,a.samplesPerChunk=1}r.sampleTimingEntries=n,r.sampleSizes=s}if(r.sampleCompositionTimeOffsets.length>0){r.presentationTimestamps=[];for(const e of r.sampleTimingEntries)for(let t=0;te.presentationTimestamp-t.presentationTimestamp),r.presentationTimestampIndexMap=Array(r.presentationTimestamps.length).fill(-1);for(let e=0;ee.moofOffset===s.moofOffset);if(r)Pi(e,r.timestamp);else{const t=z(i,s.moofOffset-1,e=>e.moofOffset);if(-1!==t){const r=i[t];Pi(e,r.endTimestamp)}}e.startTimestampIsFinal=!0}const r=z(i,e.startTimestamp,e=>e.startTimestamp);if(-1!==r&&i[r].moofOffset===s.moofOffset||i.splice(r+1,0,{moofOffset:s.moofOffset,startTimestamp:e.startTimestamp,endTimestamp:e.endTimestamp}),e.encryptionAuxInfo&&t.encryptionInfo){const i=yield Bi(this.reader,t.encryptionInfo,e.encryptionAuxInfo);for(let t=0;t0){t.languageCode="";for(let e=0;e<3;e++)t.languageCode=String.fromCharCode(96+(31&r))+t.languageCode,r>>=5;ee(t.languageCode)||(t.languageCode=Q)}}break;case"hdlr":{const t=this.currentTrack;if(!t)break;e.skip(8);const i=Wa(e,4);"vide"===i?t.info={type:"video",width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:null,avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null}:"soun"===i&&(t.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null,pcmLittleEndian:!1,pcmSampleSize:null})}break;case"stbl":{const t=this.currentTrack;if(!t)break;t.sampleTableByteOffset=ce,this.readContiguousBoxes(e.slice(de,ue.contentSize))}break;case"stsd":{const t=this.currentTrack;if(!t)break;if(null===t.info||t.sampleTable)break;const i=Ca(e);e.skip(3);const r=Ra(e);for(let n=0;n0&&(1===a?(e.skip(4),l=8*Ra(e),e.skip(8)):2===a&&(e.skip(4),c=qa(e),o=Ra(e),e.skip(4),l=Ra(e),u=Ra(e),e.skip(8))),t.info.numberOfChannels=o,t.info.sampleRate=c,t.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,r+n.totalSize-e.filePos));const d="enca"===s?t.frmaCodecString:s;if(t.frmaCodecString=null,"mp4a"===d);else if("opus"===d)t.info.codec="opus",t.info.sampleRate=We;else if("flac"===d)t.info.codec="flac";else if("ulaw"===d)t.info.codec="ulaw";else if("alaw"===d)t.info.codec="alaw";else if("ac-3"===d)t.info.codec="ac3";else if("ec-3"===d)t.info.codec="eac3";else if("twos"===d)8===l?t.info.codec="pcm-s8":16===l?t.info.codec=t.info.pcmLittleEndian?"pcm-s16":"pcm-s16be":(console.warn(`Unsupported sample size ${l} for codec 'twos'.`),t.info.codec=null);else if("sowt"===d)8===l?t.info.codec="pcm-s8":16===l?t.info.codec="pcm-s16":(console.warn(`Unsupported sample size ${l} for codec 'sowt'.`),t.info.codec=null);else if("raw "===d)t.info.codec="pcm-u8";else if("in24"===d)t.info.codec=t.info.pcmLittleEndian?"pcm-s24":"pcm-s24be";else if("in32"===d)t.info.codec=t.info.pcmLittleEndian?"pcm-s32":"pcm-s32be";else if("fl32"===d)t.info.codec=t.info.pcmLittleEndian?"pcm-f32":"pcm-f32be";else if("fl64"===d)t.info.codec=t.info.pcmLittleEndian?"pcm-f64":"pcm-f64be";else if("ipcm"===d){const e=t.info.pcmSampleSize;t.info.pcmLittleEndian?16===e?t.info.codec="pcm-s16":24===e?t.info.codec="pcm-s24":32===e?t.info.codec="pcm-s32":(console.warn(`Invalid ipcm sample size ${e}.`),t.info.codec=null):16===e?t.info.codec="pcm-s16be":24===e?t.info.codec="pcm-s24be":32===e?t.info.codec="pcm-s32be":(console.warn(`Invalid ipcm sample size ${e}.`),t.info.codec=null)}else if("fpcm"===d){const e=t.info.pcmSampleSize;t.info.pcmLittleEndian?32===e?t.info.codec="pcm-f32":64===e?t.info.codec="pcm-f64":(console.warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null):32===e?t.info.codec="pcm-f32be":64===e?t.info.codec="pcm-f64be":(console.warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null)}else if("lpcm"===d&&null!==u){const e=l+7>>3,i=Boolean(1&u),r=Boolean(2&u),n=4&u?-1:0;l>0&&l<=64&&(i?32===l&&(t.info.codec=r?"pcm-f32be":"pcm-f32"):n&1<0?(t.encryptionInfo.defaultCryptByteBlock=r>>4,t.encryptionInfo.defaultSkipByteBlock=15&r):(t.encryptionInfo.defaultCryptByteBlock=0,t.encryptionInfo.defaultSkipByteBlock=0),t.encryptionInfo.defaultIsProtected=0!==Ca(e),t.encryptionInfo.defaultPerSampleIvSize=Ca(e),t.encryptionInfo.defaultKid=N(xa(e,16)),t.encryptionInfo.defaultIsProtected&&0===t.encryptionInfo.defaultPerSampleIvSize){const i=Ca(e),r=new Uint8Array(16);r.set(xa(e,i),0),t.encryptionInfo.defaultConstantIv=r}}break;case"avcC":{const t=this.currentTrack;if(!t)break;y(t.info),t.info.codecDescription=xa(e,ue.contentSize)}break;case"hvcC":{const t=this.currentTrack;if(!t)break;y(t.info),t.info.codecDescription=xa(e,ue.contentSize)}break;case"vpcC":{const i=this.currentTrack;if(!i)break;y("video"===(null==(t=i.info)?void 0:t.type)),e.skip(4);const r=Ca(e),n=Ca(e),s=Ca(e),a=s>>4,o=s>>1&7,l=1&s,c=Ca(e),u=Ca(e),d=Ca(e);i.info.vp9CodecInfo={profile:r,level:n,bitDepth:a,chromaSubsampling:o,videoFullRangeFlag:l,colourPrimaries:c,transferCharacteristics:u,matrixCoefficients:d}}break;case"av1C":{const t=this.currentTrack;if(!t)break;y("video"===(null==(i=t.info)?void 0:i.type)),e.skip(1);const r=Ca(e),n=r>>5,s=31&r,a=Ca(e),o=a>>7,l=a>>6&1,c=a>>4&1,u=a>>3&1,d=a>>2&1,h=3&a,f=2===n&&l?a>>5&1?12:10:l?10:8;t.info.av1CodecInfo={profile:n,level:s,tier:o,bitDepth:f,monochrome:c,chromaSubsamplingX:u,chromaSubsamplingY:d,chromaSamplePosition:h}}break;case"colr":{const t=this.currentTrack;if(!t)break;y("video"===(null==(r=t.info)?void 0:r.type));if("nclx"!==Wa(e,4))break;const i=Ea(e),n=Ea(e),s=Ea(e),a=Boolean(128&Ca(e));t.info.colorSpace={primaries:B[i],transfer:_[n],matrix:F[s],fullRange:a}}break;case"pasp":{const t=this.currentTrack;if(!t)break;y("video"===(null==(n=t.info)?void 0:n.type));const i=Ra(e),r=Ra(e);i>0&&r>0&&(i>r?t.info.squarePixelWidth=Math.round(t.info.width*i/r):t.info.squarePixelHeight=Math.round(t.info.height*r/i))}break;case"esds":{const t=this.currentTrack;if(!t)break;y("audio"===(null==(s=t.info)?void 0:s.type)),e.skip(4);y(3===Ca(e)),ri(e),e.skip(2);const i=Ca(e),r=0!==(64&i),n=0!==(32&i);if(0!==(128&i)&&e.skip(2),r){const t=Ca(e);e.skip(t)}n&&e.skip(2);y(4===Ca(e));const a=ri(e),o=e.filePos,l=Ca(e);if(64===l||103===l?(t.info.codec="aac",t.info.aacCodecInfo={isMpeg2:103===l,objectType:null}):105===l||107===l?t.info.codec="mp3":221===l?t.info.codec="vorbis":console.warn(`Unsupported audio codec (objectTypeIndication ${l}) - discarding track.`),e.skip(12),a>e.filePos-o){y(5===Ca(e));const i=ri(e);if(t.info.codecDescription=xa(e,i),"aac"===t.info.codec){const e=Fe(t.info.codecDescription);null!==e.numberOfChannels&&(t.info.numberOfChannels=e.numberOfChannels),null!==e.sampleRate&&(t.info.sampleRate=e.sampleRate)}}}break;case"enda":{const t=this.currentTrack;if(!t)break;y("audio"===(null==(a=t.info)?void 0:a.type)),t.info.pcmLittleEndian=!!(255&Ea(e))}break;case"pcmC":{const t=this.currentTrack;if(!t)break;y("audio"===(null==(o=t.info)?void 0:o.type)),e.skip(4);const i=Ca(e);t.info.pcmLittleEndian=Boolean(1&i),t.info.pcmSampleSize=Ca(e)}break;case"dOps":{const t=this.currentTrack;if(!t)break;y("audio"===(null==(l=t.info)?void 0:l.type)),e.skip(1);const i=Ca(e),r=Ea(e),n=Ra(e),s=Aa(e),a=Ca(e);let o;o=0!==a?xa(e,2+i):new Uint8Array(0);const c=new Uint8Array(19+o.byteLength),u=new DataView(c.buffer);u.setUint32(0,1332770163,!1),u.setUint32(4,1214603620,!1),u.setUint8(8,1),u.setUint8(9,i),u.setUint16(10,r,!0),u.setUint32(12,n,!0),u.setInt16(16,s,!0),u.setUint8(18,a),c.set(o,19),t.info.codecDescription=c,t.info.numberOfChannels=i}break;case"dfLa":{const t=this.currentTrack;if(!t)break;y("audio"===(null==(d=t.info)?void 0:d.type)),e.skip(4);const i=127,r=128,n=e.filePos;for(;e.filePos>>12,n=1+(i>>9&7);t.info.sampleRate=r,t.info.numberOfChannels=n,e.skip(20)}else e.skip(s);if(n&r)break}const s=e.filePos;e.filePos=n;const a=xa(e,s-n),o=new Uint8Array(4+a.byteLength);new DataView(o.buffer).setUint32(0,1716281667,!1),o.set(a,4),t.info.codecDescription=o}break;case"dac3":{const t=this.currentTrack;if(!t)break;y("audio"===(null==(h=t.info)?void 0:h.type));const i=xa(e,3),r=new Ee(i),n=r.readBits(2);r.skipBits(8);const s=r.readBits(3),a=r.readBits(1);n<3&&(t.info.sampleRate=tt[n]),t.info.numberOfChannels=Wt[s]+a}break;case"dec3":{const t=this.currentTrack;if(!t)break;y("audio"===(null==(f=t.info)?void 0:f.type));const i=(e=>{if(e.length<2)return null;const t=new Ee(e),i=t.readBits(13),r=t.readBits(3),n=[];for(let s=0;s<=r&&!(Math.ceil(t.pos/8)+3>e.length);s++){const e=t.readBits(2),i=t.readBits(5);t.skipBits(1),t.skipBits(1);const r=t.readBits(3),s=t.readBits(3),a=t.readBits(1);t.skipBits(3);const o=t.readBits(4);let l=0;o>0?l=t.readBits(9):t.skipBits(1),n.push({fscod:e,fscod2:null,bsid:i,bsmod:r,acmod:s,lfeon:a,numDepSub:o,chanLoc:l})}return 0===n.length?null:{dataRate:i,substreams:n}})(xa(e,ue.contentSize));if(!i){console.warn("Invalid dec3 box contents, ignoring.");break}const r=Xt(i);null!==r&&(t.info.sampleRate=r),t.info.numberOfChannels=$t(i)}break;case"stts":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4);const i=Ra(e);let r=0,n=0;for(let s=0;se.id===i);if(!r)break;const n=Ra(e),s=(12&n)>>2,a=3&n,o=[Ca,Ea,_a,Ra],l=o[(48&n)>>4],c=o[s],u=o[a],d=Ra(e);for(let h=0;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!=(p=null==d?void 0:d.defaultSampleDescriptionIndex)?p:null,defaultSampleDuration:null!=(g=null==d?void 0:d.defaultSampleDuration)?g:null,defaultSampleSize:null!=(k=null==d?void 0:d.defaultSampleSize)?k:null,defaultSampleFlags:null!=(S=null==d?void 0:d.defaultSampleFlags)?S:null,startTimestamp:null,encryptionAuxInfo:null},i?u.currentFragmentState.baseDataOffset=Oa(e):l&&(u.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),r&&(u.currentFragmentState.sampleDescriptionIndex=Ra(e)),n&&(u.currentFragmentState.defaultSampleDuration=Ra(e)),s&&(u.currentFragmentState.defaultSampleSize=Ra(e)),a&&(u.currentFragmentState.defaultSampleFlags=Ra(e)),o&&(u.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{const t=this.currentTrack;if(!t)break;y(t.currentFragmentState);const i=Ca(e);e.skip(3);const r=0===i?Ra(e):Oa(e);t.currentFragmentState.startTimestamp=r}break;case"trun":{const t=this.currentTrack;if(!t)break;y(this.currentFragment),y(t.currentFragmentState);const i=Ca(e),r=_a(e),n=Boolean(1&r),s=Boolean(4&r),a=Boolean(256&r),o=Boolean(512&r),l=Boolean(1024&r),c=Boolean(2048&r),u=Ra(e);let d=null;n&&(d=Ma(e));let h,f=null;if(s&&(f=Ra(e)),this.currentFragment.trackData.has(t.id)?(h=this.currentFragment.trackData.get(t.id),null!==d&&(h.currentOffset=t.currentFragmentState.baseDataOffset+d)):(h={track:t,currentTimestamp:0,currentOffset:t.currentFragmentState.baseDataOffset+(null!=d?d:0),startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1,encryptionAuxInfo:null},this.currentFragment.trackData.set(t.id,h)),0===u){this.currentFragment.implicitBaseDataOffset=h.currentOffset;break}for(let m=0;m0&&(n=xa(e,r));const s=Ci(t);s.defaultSampleInfoSize=i,s.sampleSizes=n,s.sampleCount=r}break;case"saio":{const t=this.currentTrack;if(!t||!t.encryptionInfo)break;const i=Ca(e);if(1&_a(e)){const i=Wa(e,4),r=Ra(e);if(i!==t.encryptionInfo.scheme||0!==r)break}const r=Ra(e);if(0===r)break;r>1&&console.warn("Multiple saio entries are not supported; using the first offset only.");let n=0===i?Ra(e):Number(Oa(e));this.currentFragment&&(n+=this.currentFragment.moofOffset);Ci(t).offset=n}break;case"senc":{const t=this.currentTrack;if(!t||!t.encryptionInfo)break;y(this.currentFragment);const i=this.currentFragment.trackData.get(t.id);if(!i)break;e.skip(1);const r=_a(e),n=Boolean(2&r),s=Ra(e),a=t.encryptionInfo.defaultPerSampleIvSize;y(null!==a);for(let o=0;o0?r.set(xa(e,a),0):r.set(t.encryptionInfo.defaultConstantIv,0);let s=null;if(n){const t=Ea(e);s=[];for(let i=0;i0&&(null!=(re=this.metadataTags).trackNumber||(re.trackNumber=t)),i&&Number.isInteger(i)&&i>0&&(null!=(ne=this.metadataTags).tracksTotal||(ne.tracksTotal=i))}break;case"trkn":if(n instanceof Uint8Array&&n.length>=6){const e=P(n),t=e.getUint16(2,!1),i=e.getUint16(4,!1);t>0&&(null!=(se=this.metadataTags).trackNumber||(se.trackNumber=t)),i>0&&(null!=(ae=this.metadataTags).tracksTotal||(ae.tracksTotal=i))}break;case"disc":case"disk":if(n instanceof Uint8Array&&n.length>=6){const e=P(n),t=e.getUint16(2,!1),i=e.getUint16(4,!1);t>0&&(null!=(oe=this.metadataTags).discNumber||(oe.discNumber=t)),i>0&&(null!=(le=this.metadataTags).discsTotal||(le.discsTotal=i))}}}}}var fe,me;return e.filePos=he,!0}}class ki{constructor(e){this.internalTrack=e,this.packetToSampleIndex=new WeakMap,this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){const e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType();let i=0;for(const r of e.tracks)if(r.trackBacking.getType()===t&&i++,r===this.internalTrack)break;return i}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.internalCodecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}isRelativeToUnixEpoch(){return!1}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return d(this,null,function*(){var e;const t=this.internalTrack;if(t.durationInMediaTimescale<=0)return null;y(t.trackBacking);const i=yield t.trackBacking.getFirstPacket({metadataOnly:!0});return(null!=(e=null==i?void 0:i.timestamp)?e:0)+t.durationInMediaTimescale/t.timescale})}getLiveRefreshInterval(){return d(this,null,function*(){return null})}getFirstPacket(e){return d(this,null,function*(){const t=yield this.fetchPacketForSampleIndex(0,e);return t||!this.internalTrack.demuxer.isFragmented?t:this.performFragmentedLookup(null,e=>e.trackData.get(this.internalTrack.id)?{sampleIndex:0,correctSampleFound:!0}:{sampleIndex:-1,correctSampleFound:!1},-1/0,1/0,e)})}mapTimestampIntoTimescale(e){return G(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}getPacket(e,t){return d(this,null,function*(){const i=this.mapTimestampIntoTimescale(e),r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),n=Ti(r,i),s=yield this.fetchPacketForSampleIndex(n,t);return xi(r)&&this.internalTrack.demuxer.isFragmented?this.performFragmentedLookup(null,e=>{const t=e.trackData.get(this.internalTrack.id);if(!t)return{sampleIndex:-1,correctSampleFound:!1};const r=z(t.presentationTimestamps,i,e=>e.presentationTimestamp);return{sampleIndex:-1!==r?t.presentationTimestamps[r].sampleIndex:-1,correctSampleFound:-1!==r&&i{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=V(t.presentationTimestamps,e=>t.samples[e.sampleIndex].isKeyFrame&&e.presentationTimestamp<=i);return{sampleIndex:-1!==r?t.presentationTimestamps[r].sampleIndex:-1,correctSampleFound:-1!==r&&i{if(e===r.fragment){const t=e.trackData.get(this.internalTrack.id).samples.findIndex((e,t)=>e.isKeyFrame&&t>r.sampleIndex);if(-1!==t)return{sampleIndex:t,correctSampleFound:!0}}else{const t=e.trackData.get(this.internalTrack.id);if(t&&null!==t.firstKeyFrameTimestamp){const e=t.samples.findIndex(e=>e.isKeyFrame);return y(-1!==e),{sampleIndex:e,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)})}fetchPacketForSampleIndex(e,t){return d(this,null,function*(){if(-1===e)return null;const i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),r=vi(i,e);if(!r)return null;let n;if(t.metadataOnly)n=Gt;else{let t=this.internalTrack.demuxer.reader.requestSlice(r.sampleOffset,r.sampleSize);if(t instanceof Promise&&(t=yield t),!t)return null;if(n=xa(t,r.sampleSize),this.internalTrack.encryptionAuxInfo){y(this.internalTrack.encryptionInfo);const t=yield Bi(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);ee.timestamp),f=-1!==h?this.internalTrack.fragmentLookupTable[h]:null,m=z(this.internalTrack.fragmentPositionCache,i,e=>e.startTimestamp),p=-1!==m?this.internalTrack.fragmentPositionCache[m]:null,g=Math.max(null!=(s=null==f?void 0:f.moofOffset)?s:0,null!=(a=null==p?void 0:p.moofOffset)?a:0)||null;let k;for(e?null===g||e.moofOffset>=g?(k=e.moofOffset+e.moofSize,c=e):k=g:k=null!=g?g:0;;){if(c){const e=c.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>r)break}let e=l.reader.requestSliceRange(k,8,16);if(e instanceof Promise&&(e=yield e),!e)break;const i=k,s=ei(e);if(!s)break;if("moof"===s.name){c=yield l.readFragment(i);const{sampleIndex:e,correctSampleFound:r}=t(c);if(r)return this.fetchPacketInFragment(c,e,n);-1!==e&&(u=c,d=e)}k=i+s.totalSize}if(f&&(!u||u.moofOffsetd(this,null,function*(){var e,t;if("vp9"!==this.internalTrack.info.codec||this.internalTrack.info.vp9CodecInfo){if("av1"===this.internalTrack.info.codec&&!this.internalTrack.info.av1CodecInfo){const e=yield this.getFirstPacket({});this.internalTrack.info.av1CodecInfo=e&&Mt(e.data)}}else{const e=yield this.getFirstPacket({});this.internalTrack.info.vp9CodecInfo=e&&Rt(e.data)}const i={codec:Ue(this.internalTrack.info),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:null!=(e=this.internalTrack.info.codecDescription)?e:void 0,colorSpace:null!=(t=this.internalTrack.info.colorSpace)?t:void 0};return this.internalTrack.info.width===this.internalTrack.info.squarePixelWidth&&this.internalTrack.info.height===this.internalTrack.info.squarePixelHeight||(i.displayAspectWidth=this.internalTrack.info.squarePixelWidth,i.displayAspectHeight=this.internalTrack.info.squarePixelHeight),i}))():null})}}class bi extends ki{constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getType(){return"audio"}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}getDecoderConfig(){return d(this,null,function*(){var e,t;return this.internalTrack.info.codec?null!=(t=this.decoderConfig)?t:this.decoderConfig={codec:qe(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:null!=(e=this.internalTrack.info.codecDescription)?e:void 0}:null})}}const Ti=(e,t)=>{if(e.presentationTimestamps){const i=z(e.presentationTimestamps,t,e=>e.presentationTimestamp);return-1===i?-1:e.presentationTimestamps[i].sampleIndex}{const i=z(e.sampleTimingEntries,t,e=>e.startDecodeTimestamp);if(-1===i)return-1;const r=e.sampleTimingEntries[i];return r.startIndex+Math.min(Math.floor((t-r.startDecodeTimestamp)/r.delta),r.count-1)}},Si=(e,t)=>{var i;if(!e.keySampleIndices)return Ti(e,t);if(e.presentationTimestamps){const i=z(e.presentationTimestamps,t,e=>e.presentationTimestamp);if(-1===i)return-1;for(let t=i;t>=0;t--){const i=e.presentationTimestamps[t].sampleIndex;if(-1!==L(e.keySampleIndices,i,e=>e))return i}return-1}{const r=Ti(e,t),n=z(e.keySampleIndices,r,e=>e);return null!=(i=e.keySampleIndices[n])?i:-1}},vi=(e,t)=>{const i=z(e.sampleTimingEntries,t,e=>e.startIndex),r=e.sampleTimingEntries[i];if(!r||r.startIndex+r.count<=t)return null;let n=r.startDecodeTimestamp+(t-r.startIndex)*r.delta;const s=z(e.sampleCompositionTimeOffsets,t,e=>e.startIndex),a=e.sampleCompositionTimeOffsets[s];a&&t-a.startIndexe.startSampleIndex),c=e.sampleToChunk[l];y(c);const u=c.startChunkIndex+Math.floor((t-c.startSampleIndex)/c.samplesPerChunk),d=e.chunkOffsets[u],h=c.startSampleIndex+(u-c.startChunkIndex)*c.samplesPerChunk;let f=0,m=d;if(1===e.sampleSizes.length)m+=o*(t-h),f+=o*c.samplesPerChunk;else for(let g=h;ge)}},wi=(e,t)=>{var i;if(!e.keySampleIndices)return t+1;const r=z(e.keySampleIndices,t,e=>e);return null!=(i=e.keySampleIndices[r+1])?i:-1},Pi=(e,t)=>{e.startTimestamp+=t,e.endTimestamp+=t;for(const i of e.samples)i.presentationTimestamp+=t;for(const i of e.presentationTimestamps)i.presentationTimestamp+=t},Ii=e=>{const[t,i]=e,r=Math.atan2(i,t);return Number.isFinite(r)?r*(180/Math.PI):0},xi=e=>0===e.sampleSizes.length,Ci=e=>{var t,i,r;return e.currentFragmentState?null!=(i=(t=e.currentFragmentState).encryptionAuxInfo)?i:t.encryptionAuxInfo={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null}:null!=(r=e.encryptionAuxInfo)?r:e.encryptionAuxInfo={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null}},Bi=(e,t,i)=>d(null,null,function*(){if(i.resolved)return i.resolved;if(null===i.offset||0===i.sampleCount)throw new Error("Incomplete saiz/saio info; cannot resolve encryption data.");let r=0;if(i.defaultSampleInfoSize>0)r=i.defaultSampleInfoSize*i.sampleCount;else{y(i.sampleSizes);for(let e=0;e0?i.defaultSampleInfoSize:i.sampleSizes[e],o=new Uint8Array(16);s>0?o.set(xa(n,s),0):o.set(t.defaultConstantIv,0);let l=null;if(r>s){const e=Ea(n);l=[];for(let t=0;td(null,null,function*(){var n;y(e.encryptionInfo);const s=e.encryptionInfo;y(null!==s.defaultKid);const a=s.defaultKid;let o;const l=e.demuxer.decryptionKeyCache.get(a);if(l)o=yield l;else{if(!(null==(n=e.demuxer.input._formatOptions.isobmff)?void 0:n.resolveKeyId))throw new Error("Encrypted media samples encountered. To decrypt them, please provide a callback for InputOptions.formatOptions.isobmff.resolveKeyId.");const t=d(null,null,function*(){let t=e.demuxer.psshBoxes;if(r){t=[...t,...r.psshBoxes].filter(e=>null===e.keyIds||e.keyIds.includes(a));for(let e=0;e{y(e.length%2===0);const t=new Uint8Array(e.length/2);for(let i=0;id(null,null,function*(){const n=new Uint8Array(16);n.set(i.iv,0);const s=yield crypto.subtle.importKey("raw",e,{name:"AES-CTR"},!1,["decrypt"]),a=e=>d(null,null,function*(){const t=yield crypto.subtle.decrypt({name:"AES-CTR",counter:n,length:64},s,e);return new Uint8Array(t)});if(!i.subsamples)return a(r);y(null!==t.defaultCryptByteBlock&&null!==t.defaultSkipByteBlock);const o=Fi(i.subsamples,t.defaultCryptByteBlock,t.defaultSkipByteBlock);let l=0;for(const e of o)for(const t of e.perSubsample)l+=t.length;const c=new Uint8Array(l);let u=0;for(const e of o)for(const t of e.perSubsample)c.set(r.subarray(t.offset,t.offset+t.length),u),u+=t.length;const h=yield a(c),f=new Uint8Array(r);let m=0;for(const e of o)for(const t of e.perSubsample)f.set(h.subarray(m,m+t.length),t.offset),m+=t.length;return f}),Ai=(e,t,i,r)=>{const n=new pi;n.init({key:e,iv:i.iv});const s=t.defaultCryptByteBlock,a=t.defaultSkipByteBlock;if(y(null!==s&&null!==a),!i.subsamples){const e=new Uint8Array(r),t=Math.floor(r.length/16);for(let i=0;i{const r=[],n=0!==t||0!==i;let s=0;for(const a of e){s+=a.clearLen;const e=[];if(n){let r=a.protectedLen,n=s;for(;r>0&&!(r<16*t);){const s=16*t;e.push({offset:n,length:s}),n+=s,r-=s;const a=Math.min(16*i,r);n+=a,r-=a}s+=a.protectedLen}else a.protectedLen>0&&e.push({offset:s,length:a.protectedLen}),s+=a.protectedLen;r.push({perSubsample:e})}return r};var Ri,Di;(Di=Ri||(Ri={}))[Di.EBML=440786851]="EBML",Di[Di.EBMLVersion=17030]="EBMLVersion",Di[Di.EBMLReadVersion=17143]="EBMLReadVersion",Di[Di.EBMLMaxIDLength=17138]="EBMLMaxIDLength",Di[Di.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",Di[Di.DocType=17026]="DocType",Di[Di.DocTypeVersion=17031]="DocTypeVersion",Di[Di.DocTypeReadVersion=17029]="DocTypeReadVersion",Di[Di.Void=236]="Void",Di[Di.Segment=408125543]="Segment",Di[Di.SeekHead=290298740]="SeekHead",Di[Di.Seek=19899]="Seek",Di[Di.SeekID=21419]="SeekID",Di[Di.SeekPosition=21420]="SeekPosition",Di[Di.Duration=17545]="Duration",Di[Di.Info=357149030]="Info",Di[Di.TimestampScale=2807729]="TimestampScale",Di[Di.MuxingApp=19840]="MuxingApp",Di[Di.WritingApp=22337]="WritingApp",Di[Di.Tracks=374648427]="Tracks",Di[Di.TrackEntry=174]="TrackEntry",Di[Di.TrackNumber=215]="TrackNumber",Di[Di.TrackUID=29637]="TrackUID",Di[Di.TrackType=131]="TrackType",Di[Di.FlagEnabled=185]="FlagEnabled",Di[Di.FlagDefault=136]="FlagDefault",Di[Di.FlagForced=21930]="FlagForced",Di[Di.FlagOriginal=21934]="FlagOriginal",Di[Di.FlagHearingImpaired=21931]="FlagHearingImpaired",Di[Di.FlagVisualImpaired=21932]="FlagVisualImpaired",Di[Di.FlagCommentary=21935]="FlagCommentary",Di[Di.FlagLacing=156]="FlagLacing",Di[Di.Name=21358]="Name",Di[Di.Language=2274716]="Language",Di[Di.LanguageBCP47=2274717]="LanguageBCP47",Di[Di.CodecID=134]="CodecID",Di[Di.CodecPrivate=25506]="CodecPrivate",Di[Di.CodecDelay=22186]="CodecDelay",Di[Di.SeekPreRoll=22203]="SeekPreRoll",Di[Di.DefaultDuration=2352003]="DefaultDuration",Di[Di.Video=224]="Video",Di[Di.PixelWidth=176]="PixelWidth",Di[Di.PixelHeight=186]="PixelHeight",Di[Di.DisplayWidth=21680]="DisplayWidth",Di[Di.DisplayHeight=21690]="DisplayHeight",Di[Di.DisplayUnit=21682]="DisplayUnit",Di[Di.AlphaMode=21440]="AlphaMode",Di[Di.Audio=225]="Audio",Di[Di.SamplingFrequency=181]="SamplingFrequency",Di[Di.Channels=159]="Channels",Di[Di.BitDepth=25188]="BitDepth",Di[Di.SimpleBlock=163]="SimpleBlock",Di[Di.BlockGroup=160]="BlockGroup",Di[Di.Block=161]="Block",Di[Di.BlockAdditions=30113]="BlockAdditions",Di[Di.BlockMore=166]="BlockMore",Di[Di.BlockAdditional=165]="BlockAdditional",Di[Di.BlockAddID=238]="BlockAddID",Di[Di.BlockDuration=155]="BlockDuration",Di[Di.ReferenceBlock=251]="ReferenceBlock",Di[Di.Cluster=524531317]="Cluster",Di[Di.Timestamp=231]="Timestamp",Di[Di.Cues=475249515]="Cues",Di[Di.CuePoint=187]="CuePoint",Di[Di.CueTime=179]="CueTime",Di[Di.CueTrackPositions=183]="CueTrackPositions",Di[Di.CueTrack=247]="CueTrack",Di[Di.CueClusterPosition=241]="CueClusterPosition",Di[Di.Colour=21936]="Colour",Di[Di.MatrixCoefficients=21937]="MatrixCoefficients",Di[Di.TransferCharacteristics=21946]="TransferCharacteristics",Di[Di.Primaries=21947]="Primaries",Di[Di.Range=21945]="Range",Di[Di.Projection=30320]="Projection",Di[Di.ProjectionType=30321]="ProjectionType",Di[Di.ProjectionPoseRoll=30325]="ProjectionPoseRoll",Di[Di.Attachments=423732329]="Attachments",Di[Di.AttachedFile=24999]="AttachedFile",Di[Di.FileDescription=18046]="FileDescription",Di[Di.FileName=18030]="FileName",Di[Di.FileMediaType=18016]="FileMediaType",Di[Di.FileData=18012]="FileData",Di[Di.FileUID=18094]="FileUID",Di[Di.Chapters=272869232]="Chapters",Di[Di.Tags=307544935]="Tags",Di[Di.Tag=29555]="Tag",Di[Di.Targets=25536]="Targets",Di[Di.TargetTypeValue=26826]="TargetTypeValue",Di[Di.TargetType=25546]="TargetType",Di[Di.TagTrackUID=25541]="TagTrackUID",Di[Di.TagEditionUID=25545]="TagEditionUID",Di[Di.TagChapterUID=25540]="TagChapterUID",Di[Di.TagAttachmentUID=25542]="TagAttachmentUID",Di[Di.SimpleTag=26568]="SimpleTag",Di[Di.TagName=17827]="TagName",Di[Di.TagLanguage=17530]="TagLanguage",Di[Di.TagString=17543]="TagString",Di[Di.TagBinary=17541]="TagBinary",Di[Di.ContentEncodings=28032]="ContentEncodings",Di[Di.ContentEncoding=25152]="ContentEncoding",Di[Di.ContentEncodingOrder=20529]="ContentEncodingOrder",Di[Di.ContentEncodingScope=20530]="ContentEncodingScope",Di[Di.ContentCompression=20532]="ContentCompression",Di[Di.ContentCompAlgo=16980]="ContentCompAlgo",Di[Di.ContentCompSettings=16981]="ContentCompSettings",Di[Di.ContentEncryption=20533]="ContentEncryption";const Mi=[Ri.EBML,Ri.Segment],Ni=[Ri.SeekHead,Ri.Info,Ri.Cluster,Ri.Tracks,Ri.Cues,Ri.Attachments,Ri.Chapters,Ri.Tags],Oi=[...Mi,...Ni],Li=16,zi=e=>{if(e.remainingLength<1)return null;const t=Ca(e);if(e.skip(-1),0===t)return null;let i=1,r=128;for(;0===(t&r);)i++,r>>=1;return e.remainingLength{if(e.remainingLength<1)return null;const t=Ca(e);if(0===t)return null;let i=1,r=128;for(;0===(t&r);)i++,r>>=1;if(e.remainingLength{if(t<1||t>8)throw new Error("Bad unsigned int size "+t);let i=0;for(let r=0;r{const t=zi(e);if(null===t)return null;if(e.remainingLength{if(e.remainingLength<1)return null;if(255===Ca(e))return;e.skip(-1);const t=Ui(e);return null===t?null:72057594037927940!==t?t:void 0},Hi=e=>{y(e.remainingLength>=2);const t=Wi(e);if(null===t)return null;const i=Vi(e);return null===i?null:{id:t,size:i}},Ki=(e,t)=>{const i=xa(e,t);let r=0;for(;r{const i=xa(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?Ua(e):qa(e)},$i=(e,t,i,r)=>d(null,null,function*(){const n=new Set(i);let s=t;for(;null===r||ss?r:s,found:!1}}),Qi=(e,t,i,r)=>d(null,null,function*(){const n=o(2,16),s=new Set(i);let a=t;for(;ae.tracks.map(e=>e.trackBacking))})}getMimeType(){return d(this,null,function*(){yield this.readMetadata();const e=yield this.getTrackBackings(),t=yield Promise.all(e.map(e=>e.getDecoderConfig().then(e=>{var t;return null!=(t=null==e?void 0:e.codec)?t:null})));return(e=>{let t=(e.hasVideo?"video/":e.hasAudio?"audio/":"application/")+(e.isWebM?"webm":"x-matroska");e.codecStrings.length>0&&(t+=`; codecs="${[...new Set(e.codecStrings.filter(Boolean))].join(", ")}"`);return t})({isWebM:this.isWebM,hasVideo:this.segments.some(e=>e.tracks.some(e=>{var t;return"video"===(null==(t=e.info)?void 0:t.type)})),hasAudio:this.segments.some(e=>e.tracks.some(e=>{var t;return"audio"===(null==(t=e.info)?void 0:t.type)})),codecStrings:t.filter(Boolean)})})}getMetadataTags(){return d(this,null,function*(){yield this.readMetadata();for(const t of this.segments)t.metadataTagsCollected||(null!==this.reader.fileSize&&(yield this.loadSegmentMetadata(t)),t.metadataTagsCollected=!0);let e={};for(const t of this.segments)e=c(c({},e),t.metadataTags);return e})}readMetadata(){var e;return null!=(e=this.readMetadataPromise)?e:this.readMetadataPromise=(()=>d(this,null,function*(){let e=0;for(;;){let t=this.reader.requestSliceRange(e,2,Li);if(t instanceof Promise&&(t=yield t),!t)break;const i=Hi(t);if(!i)break;const r=i.id;let n=i.size;const s=t.filePos;if(r===Ri.EBML){lr(n);let e=this.reader.requestSlice(s,n);if(e instanceof Promise&&(e=yield e),!e)break;this.readContiguousElements(e)}else if(r===Ri.Segment){if(yield this.readSegment(s,n),void 0===n)break;if(null===this.reader.fileSize)break}else if(r===Ri.Cluster){if(null===this.reader.fileSize)break;if(void 0===n){n=(yield $i(this.reader,s,Oi,this.reader.fileSize)).pos-s}const e=T(this.segments);e&&(e.elementEndPos=s+n)}lr(n),e=s+n}}))()}readSegment(e,t){return d(this,null,function*(){var i;this.currentSegment={seekHeadSeen:!1,infoSeen:!1,tracksSeen:!1,cuesSeen:!1,tagsSeen:!1,attachmentsSeen:!1,timestampScale:-1,timestampFactor:-1,duration:-1,seekEntries:[],tracks:[],cuePoints:[],dataStartPos:e,elementEndPos:void 0===t?null:e+t,clusterSeekStartPos:e,lastReadCluster:null,metadataTags:{},metadataTagsCollected:!1},this.segments.push(this.currentSegment);let r=e;for(;null===this.currentSegment.elementEndPos||re.id===s);if(-1!==l){const e=pr[l].flag;this.currentSegment[e]=!0,lr(a);let t=this.reader.requestSlice(o,a);t instanceof Promise&&(t=yield t),t&&this.readContiguousElements(t)}else if(s===Ri.Tags||s===Ri.Attachments){s===Ri.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,lr(a);let e=this.reader.requestSlice(o,a);e instanceof Promise&&(e=yield e),e&&this.readContiguousElements(e)}else if(s===Ri.Cluster){this.currentSegment.clusterSeekStartPos=t;break}if(void 0===a)break;r=o+a}if(this.currentSegment.seekEntries.sort((e,t)=>e.segmentPosition-t.segmentPosition),null!==this.reader.fileSize)for(const t of this.currentSegment.seekEntries){const i=pr.find(e=>e.id===t.id);if(!i)continue;if(this.currentSegment[i.flag])continue;let r=this.reader.requestSliceRange(e+t.segmentPosition,2,Li);if(r instanceof Promise&&(r=yield r),!r)continue;const n=Hi(r);if(!n)continue;const{id:s,size:a}=n;if(s!==i.id)continue;lr(a),this.currentSegment[i.flag]=!0;let o=this.reader.requestSlice(r.filePos,a);o instanceof Promise&&(o=yield o),o&&this.readContiguousElements(o)}-1===this.currentSegment.timestampScale&&(this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1e3);for(const e of this.currentSegment.tracks)null!==e.defaultDurationNs&&(e.defaultDuration=this.currentSegment.timestampFactor*e.defaultDurationNs/1e9);const n=new Map(this.currentSegment.tracks.map(e=>[e.id,e]));for(const e of this.currentSegment.cuePoints){const t=n.get(e.trackId);t&&t.cuePoints.push(e)}for(const e of this.currentSegment.tracks){e.cuePoints.sort((e,t)=>e.time-t.time);for(let t=0;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 d(this,null,function*(){var i;if((null==(i=t.lastReadCluster)?void 0:i.elementStartPos)===e)return t.lastReadCluster;let r=this.reader.requestSliceRange(e,2,Li);r instanceof Promise&&(r=yield r),y(r);const n=e,s=Hi(r);y(s);y(s.id===Ri.Cluster);let a=s.size;const o=r.filePos;if(void 0===a){a=(yield $i(this.reader,o,Oi,t.elementEndPos)).pos-o}let l=this.reader.requestSlice(o,a);l instanceof Promise&&(l=yield l);const c={segment:t,elementStartPos:n,elementEndPos:o+a,dataStartPos:o,timestamp:-1,trackData:new Map};if(this.currentCluster=c,l){const e=this.readContiguousElements(l,Oi);c.elementEndPos=e}for(const[,e]of c.trackData){const t=e.track;y(e.blocks.length>0);let i=!1;for(let n=0;n({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[T(e.presentationTimestamps).blockIndex];e.startTimestamp=r.timestamp,e.endTimestamp=s.timestamp+s.duration;const a=z(t.clusterPositionCache,e.startTimestamp,e=>e.startTimestamp);-1!==a&&t.clusterPositionCache[a].elementStartPos===n||t.clusterPositionCache.splice(a+1,0,{elementStartPos:c.elementStartPos,startTimestamp:e.startTimestamp})}return t.lastReadCluster=c,c})}getTrackDataInCluster(e,t){let i=e.trackData.get(t);if(!i){const r=e.segment.tracks.find(e=>e.id===t);if(!r)return null;i={track:r,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},e.trackData.set(t,i)}return i}expandLacedBlocks(e,t){var i;for(let r=0;r=2;){const i=e.filePos;if(!this.traverseElement(e,t))return i}return e.filePos}traverseElement(e,t){var i,r,n,s,a,o,l,d,h,f,m,p,g,k,T,S,v,w,P,I,x,C,E,A,R,D,M,N,O,L,z,U,q,W,V,H,K,j,X,$,G,Y,J,Z,te,ie,re,ne,se,ae,oe,le,ce,ue;const de=Hi(e);if(!de)return!1;if(t&&t.includes(de.id))return!1;const{id:he,size:fe}=de,me=e.filePos;switch(lr(fe),he){case Ri.DocType:this.isWebM="webm"===Ki(e,fe);break;case Ri.Seek:{if(!this.currentSegment)break;const t={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(t),this.readContiguousElements(e.slice(me,fe)),-1!==t.id&&-1!==t.segmentPosition||this.currentSegment.seekEntries.pop()}break;case Ri.SeekID:{const t=null==(i=this.currentSegment)?void 0:i.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.id=qi(e,fe)}break;case Ri.SeekPosition:{const t=null==(r=this.currentSegment)?void 0:r.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.segmentPosition=qi(e,fe)}break;case Ri.TimestampScale:if(!this.currentSegment)break;this.currentSegment.timestampScale=qi(e,fe),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale;break;case Ri.Duration:if(!this.currentSegment)break;this.currentSegment.duration=Xi(e,fe);break;case Ri.TrackEntry:if(!this.currentSegment)break;if(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:u(c({},Be),{primary:!1}),trackBacking:null,codecId:null,codecPrivate:null,defaultDuration:null,defaultDurationNs:null,name:null,languageCode:"eng",hasLanguageBcp47:!1,decodingInstructions:[],info:null},this.readContiguousElements(e.slice(me,fe)),!this.currentTrack)break;if(this.currentTrack.decodingInstructions.some(e=>{var t;return"decompress"!==(null==(t=e.data)?void 0:t.type)||e.scope!==dr.Block||e.data.algorithm!==fr.HeaderStripping})&&(console.warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`),this.currentTrack=null),this.currentTrack&&-1!==this.currentTrack.id&&this.currentTrack.codecId&&this.currentTrack.info){const e=this.currentTrack.codecId.indexOf("/"),t=-1===e?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,e);if("video"===this.currentTrack.info.type&&-1!==this.currentTrack.info.width&&-1!==this.currentTrack.info.height){if(this.currentTrack.info.squarePixelWidth=this.currentTrack.info.width,this.currentTrack.info.squarePixelHeight=this.currentTrack.info.height,null!==this.currentTrack.info.displayWidth&&null!==this.currentTrack.info.displayHeight){const e=this.currentTrack.info.displayWidth*this.currentTrack.info.height,t=this.currentTrack.info.displayHeight*this.currentTrack.info.width;e>0&&t>0&&(e>t?this.currentTrack.info.squarePixelWidth=Math.round(this.currentTrack.info.width*e/t):this.currentTrack.info.squarePixelHeight=Math.round(this.currentTrack.info.height*t/e))}this.currentTrack.codecId===Gi?(this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===Yi?(this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Ji?this.currentTrack.info.codec="vp8":t===Zi?this.currentTrack.info.codec="vp9":t===er&&(this.currentTrack.info.codec="av1");const e=this.currentTrack;this.currentTrack.trackBacking=new br(e),this.currentSegment.tracks.push(this.currentTrack)}else if("audio"===this.currentTrack.info.type){t===tr?(this.currentTrack.info.codec="aac",this.currentTrack.info.aacCodecInfo={isMpeg2:this.currentTrack.codecId.includes("MPEG2"),objectType:null},this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===ir?this.currentTrack.info.codec="mp3":t===rr?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=We):t===nr?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===sr?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===ar?(this.currentTrack.info.codec="ac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===or?(this.currentTrack.info.codec="eac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):"A_PCM/INT/LIT"===this.currentTrack.codecId?8===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-u8":16===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s16":24===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s24":32===this.currentTrack.info.bitDepth&&(this.currentTrack.info.codec="pcm-s32"):"A_PCM/INT/BIG"===this.currentTrack.codecId?8===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-u8":16===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s16be":24===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s24be":32===this.currentTrack.info.bitDepth&&(this.currentTrack.info.codec="pcm-s32be"):"A_PCM/FLOAT/IEEE"===this.currentTrack.codecId&&(32===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-f32":64===this.currentTrack.info.bitDepth&&(this.currentTrack.info.codec="pcm-f64"));const e=this.currentTrack;this.currentTrack.trackBacking=new Tr(e),this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null;break;case Ri.TrackNumber:if(!this.currentTrack)break;this.currentTrack.id=qi(e,fe);break;case Ri.TrackType:{if(!this.currentTrack)break;const t=qi(e,fe);1===t?this.currentTrack.info={type:"video",width:-1,height:-1,displayWidth:null,displayHeight:null,displayUnit:null,squarePixelWidth:-1,squarePixelHeight:-1,rotation:0,codec:null,codecDescription:null,colorSpace:null,alphaMode:!1}:2===t&&(this.currentTrack.info={type:"audio",numberOfChannels:1,sampleRate:8e3,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case Ri.FlagEnabled:if(!this.currentTrack)break;qi(e,fe)||(this.currentTrack=null);break;case Ri.FlagDefault:if(!this.currentTrack)break;this.currentTrack.disposition.default=!!qi(e,fe);break;case Ri.FlagForced:if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!qi(e,fe);break;case Ri.FlagOriginal:if(!this.currentTrack)break;this.currentTrack.disposition.original=!!qi(e,fe);break;case Ri.FlagHearingImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!qi(e,fe);break;case Ri.FlagVisualImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!qi(e,fe);break;case Ri.FlagCommentary:if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!qi(e,fe);break;case Ri.CodecID:if(!this.currentTrack)break;this.currentTrack.codecId=Ki(e,fe);break;case Ri.CodecPrivate:if(!this.currentTrack)break;this.currentTrack.codecPrivate=xa(e,fe);break;case Ri.DefaultDuration:if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=qi(e,fe);break;case Ri.Name:if(!this.currentTrack)break;this.currentTrack.name=ji(e,fe);break;case Ri.Language:if(!this.currentTrack)break;if(this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=Ki(e,fe),ee(this.currentTrack.languageCode)||(this.currentTrack.languageCode=Q);break;case Ri.LanguageBCP47:{if(!this.currentTrack)break;const t=Ki(e,fe).split("-")[0];this.currentTrack.languageCode=t||Q,this.currentTrack.hasLanguageBcp47=!0}break;case Ri.Video:if("video"!==(null==(s=null==(n=this.currentTrack)?void 0:n.info)?void 0:s.type))break;this.readContiguousElements(e.slice(me,fe));break;case Ri.PixelWidth:if("video"!==(null==(o=null==(a=this.currentTrack)?void 0:a.info)?void 0:o.type))break;this.currentTrack.info.width=qi(e,fe);break;case Ri.PixelHeight:if("video"!==(null==(d=null==(l=this.currentTrack)?void 0:l.info)?void 0:d.type))break;this.currentTrack.info.height=qi(e,fe);break;case Ri.DisplayWidth:if("video"!==(null==(f=null==(h=this.currentTrack)?void 0:h.info)?void 0:f.type))break;this.currentTrack.info.displayWidth=qi(e,fe);break;case Ri.DisplayHeight:if("video"!==(null==(p=null==(m=this.currentTrack)?void 0:m.info)?void 0:p.type))break;this.currentTrack.info.displayHeight=qi(e,fe);break;case Ri.DisplayUnit:if("video"!==(null==(k=null==(g=this.currentTrack)?void 0:g.info)?void 0:k.type))break;this.currentTrack.info.displayUnit=qi(e,fe);break;case Ri.AlphaMode:if("video"!==(null==(S=null==(T=this.currentTrack)?void 0:T.info)?void 0:S.type))break;this.currentTrack.info.alphaMode=1===qi(e,fe);break;case Ri.Colour:if("video"!==(null==(w=null==(v=this.currentTrack)?void 0:v.info)?void 0:w.type))break;this.currentTrack.info.colorSpace={},this.readContiguousElements(e.slice(me,fe));break;case Ri.MatrixCoefficients:{if("video"!==(null==(I=null==(P=this.currentTrack)?void 0:P.info)?void 0:I.type)||!this.currentTrack.info.colorSpace)break;const t=qi(e,fe),i=null!=(x=F[t])?x:null;this.currentTrack.info.colorSpace.matrix=i}break;case Ri.Range:if("video"!==(null==(E=null==(C=this.currentTrack)?void 0:C.info)?void 0:E.type)||!this.currentTrack.info.colorSpace)break;this.currentTrack.info.colorSpace.fullRange=2===qi(e,fe);break;case Ri.TransferCharacteristics:{if("video"!==(null==(R=null==(A=this.currentTrack)?void 0:A.info)?void 0:R.type)||!this.currentTrack.info.colorSpace)break;const t=qi(e,fe),i=null!=(D=_[t])?D:null;this.currentTrack.info.colorSpace.transfer=i}break;case Ri.Primaries:{if("video"!==(null==(N=null==(M=this.currentTrack)?void 0:M.info)?void 0:N.type)||!this.currentTrack.info.colorSpace)break;const t=qi(e,fe),i=null!=(O=B[t])?O:null;this.currentTrack.info.colorSpace.primaries=i}break;case Ri.Projection:if("video"!==(null==(z=null==(L=this.currentTrack)?void 0:L.info)?void 0:z.type))break;this.readContiguousElements(e.slice(me,fe));break;case Ri.ProjectionPoseRoll:{if("video"!==(null==(q=null==(U=this.currentTrack)?void 0:U.info)?void 0:q.type))break;const t=-Xi(e,fe);try{this.currentTrack.info.rotation=b(t)}catch(pe){}}break;case Ri.Audio:if("audio"!==(null==(V=null==(W=this.currentTrack)?void 0:W.info)?void 0:V.type))break;this.readContiguousElements(e.slice(me,fe));break;case Ri.SamplingFrequency:if("audio"!==(null==(K=null==(H=this.currentTrack)?void 0:H.info)?void 0:K.type))break;this.currentTrack.info.sampleRate=Xi(e,fe);break;case Ri.Channels:if("audio"!==(null==(X=null==(j=this.currentTrack)?void 0:j.info)?void 0:X.type))break;this.currentTrack.info.numberOfChannels=qi(e,fe);break;case Ri.BitDepth:if("audio"!==(null==(G=null==($=this.currentTrack)?void 0:$.info)?void 0:G.type))break;this.currentTrack.info.bitDepth=qi(e,fe);break;case Ri.CuePoint:if(!this.currentSegment)break;this.readContiguousElements(e.slice(me,fe)),this.currentCueTime=null;break;case Ri.CueTime:this.currentCueTime=qi(e,fe);break;case Ri.CueTrackPositions:{if(null===this.currentCueTime)break;y(this.currentSegment);const t={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(t),this.readContiguousElements(e.slice(me,fe)),-1!==t.trackId&&-1!==t.clusterPosition||this.currentSegment.cuePoints.pop()}break;case Ri.CueTrack:{const t=null==(Y=this.currentSegment)?void 0:Y.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;t.trackId=qi(e,fe)}break;case Ri.CueClusterPosition:{const t=null==(J=this.currentSegment)?void 0:J.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;y(this.currentSegment),t.clusterPosition=this.currentSegment.dataStartPos+qi(e,fe)}break;case Ri.Timestamp:if(!this.currentCluster)break;this.currentCluster.timestamp=qi(e,fe);break;case Ri.SimpleBlock:{if(!this.currentCluster)break;const t=Ui(e);if(null===t)break;const i=this.getTrackDataInCluster(this.currentCluster,t);if(!i)break;const r=Aa(e),n=Ca(e),s=n>>1&3;let a=!!(128&n);"audio"===(null==(Z=i.track.info)?void 0:Z.type)&&i.track.info.codec&&(a=!0);const o=xa(e,fe-(e.filePos-me)),l=i.track.decodingInstructions.length>0;i.blocks.push({timestamp:r,duration:0,isKeyFrame:a,data:o,lacing:s,decoded:!l,mainAdditional:null})}break;case Ri.BlockGroup:if(!this.currentCluster)break;this.readContiguousElements(e.slice(me,fe)),this.currentBlock=null;break;case Ri.Block:{if(!this.currentCluster)break;const t=Ui(e);if(null===t)break;const i=this.getTrackDataInCluster(this.currentCluster,t);if(!i)break;const r=Aa(e),n=Ca(e)>>1&3,s=xa(e,fe-(e.filePos-me)),a=i.track.decodingInstructions.length>0;this.currentBlock={timestamp:r,duration:0,isKeyFrame:!0,data:s,lacing:n,decoded:!a,mainAdditional:null},i.blocks.push(this.currentBlock)}break;case Ri.BlockAdditions:this.readContiguousElements(e.slice(me,fe));break;case Ri.BlockMore:if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(me,fe)),this.currentBlockAdditional.data&&1===this.currentBlockAdditional.addId&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null;break;case Ri.BlockAdditional:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=xa(e,fe);break;case Ri.BlockAddID:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=qi(e,fe);break;case Ri.BlockDuration:if(!this.currentBlock)break;this.currentBlock.duration=qi(e,fe);break;case Ri.ReferenceBlock:if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1;break;case Ri.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(me,fe));break;case Ri.Targets:this.readContiguousElements(e.slice(me,fe));break;case Ri.TargetTypeValue:50!==qi(e,fe)&&(this.currentTagTargetIsMovie=!1);break;case Ri.TagTrackUID:case Ri.TagEditionUID:case Ri.TagChapterUID:case Ri.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case Ri.SimpleTag:if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(me,fe));break;case Ri.TagName:this.currentSimpleTagName=ji(e,fe);break;case Ri.TagString:{if(!this.currentSimpleTagName)break;const t=ji(e,fe);this.processTagValue(this.currentSimpleTagName,t)}break;case Ri.TagBinary:{if(!this.currentSimpleTagName)break;const t=xa(e,fe);this.processTagValue(this.currentSimpleTagName,t)}break;case Ri.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(me,fe));const t=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(null!=t.raw||(t.raw={}),t.raw[this.currentAttachedFile.fileUid.toString()]=new Ce(this.currentAttachedFile.fileData,null!=(te=this.currentAttachedFile.fileMediaType)?te:void 0,null!=(ie=this.currentAttachedFile.fileName)?ie:void 0,null!=(re=this.currentAttachedFile.fileDescription)?re:void 0)),(null==(ne=this.currentAttachedFile.fileMediaType)?void 0:ne.startsWith("image/"))&&this.currentAttachedFile.fileData){const e=this.currentAttachedFile.fileName;let i="unknown";if(e){const t=e.toLowerCase();t.startsWith("cover.")?i="coverFront":t.startsWith("back.")&&(i="coverBack")}null!=t.images||(t.images=[]),t.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:i,name:null!=(se=this.currentAttachedFile.fileName)?se:void 0,description:null!=(ae=this.currentAttachedFile.fileDescription)?ae:void 0})}this.currentAttachedFile=null}break;case Ri.FileUID:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=((e,t)=>{if(t<1)throw new Error("Bad unsigned int size "+t);let i=BigInt("0");for(let r=0;rt.order-e.order);break;case Ri.ContentEncoding:this.currentDecodingInstruction={order:0,scope:dr.Block,data:null},this.readContiguousElements(e.slice(me,fe)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case Ri.ContentEncodingOrder:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=qi(e,fe);break;case Ri.ContentEncodingScope:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=qi(e,fe);break;case Ri.ContentCompression:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:fr.Zlib,settings:null},this.readContiguousElements(e.slice(me,fe));break;case Ri.ContentCompAlgo:if("decompress"!==(null==(le=null==(oe=this.currentDecodingInstruction)?void 0:oe.data)?void 0:le.type))break;this.currentDecodingInstruction.data.algorithm=qi(e,fe);break;case Ri.ContentCompSettings:if("decompress"!==(null==(ue=null==(ce=this.currentDecodingInstruction)?void 0:ce.data)?void 0:ue.type))break;this.currentDecodingInstruction.data.settings=xa(e,fe);break;case Ri.ContentEncryption:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}return e.filePos=me+fe,!0}decodeBlockData(e,t){y(e.decodingInstructions.length>0);let i=t;for(const r of e.decodingInstructions)if(y(r.data),"decompress"===r.data.type)if(r.data.algorithm===fr.HeaderStripping)if(r.data.settings&&r.data.settings.length>0){const e=r.data.settings,t=new Uint8Array(e.length+i.length);t.set(e,0),t.set(i,e.length),i=t}return i}processTagValue(e,t){var i,r;if(!(null==(i=this.currentSegment)?void 0:i.metadataTags))return;const n=this.currentSegment.metadataTags;if(null!=n.raw||(n.raw={}),null!=(r=n.raw)[e]||(r[e]=t),"string"===typeof t)switch(e.toLowerCase()){case"title":null!=n.title||(n.title=t);break;case"description":null!=n.description||(n.description=t);break;case"artist":null!=n.artist||(n.artist=t);break;case"album":null!=n.album||(n.album=t);break;case"album_artist":null!=n.albumArtist||(n.albumArtist=t);break;case"genre":null!=n.genre||(n.genre=t);break;case"comment":null!=n.comment||(n.comment=t);break;case"lyrics":null!=n.lyrics||(n.lyrics=t);break;case"date":{const e=new Date(t);Number.isNaN(e.getTime())||null!=n.date||(n.date=e)}break;case"track_number":case"part_number":{const e=t.split("/"),i=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(i)&&i>0&&(null!=n.trackNumber||(n.trackNumber=i)),r&&Number.isInteger(r)&&r>0&&(null!=n.tracksTotal||(n.tracksTotal=r))}break;case"disc_number":case"disc":{const e=t.split("/"),i=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(i)&&i>0&&(null!=n.discNumber||(n.discNumber=i)),r&&Number.isInteger(r)&&r>0&&(null!=n.discsTotal||(n.discsTotal=r))}}}}class yr{constructor(e){this.internalTrack=e,this.packetToClusterLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){const e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType();let i=0;for(const r of e.segments)for(const e of r.tracks)if(e.trackBacking.getType()===t&&i++,e===this.internalTrack)break;return i}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.codecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.segment.timestampFactor}isRelativeToUnixEpoch(){return!1}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return d(this,null,function*(){var e;const t=this.internalTrack.segment;if(t.duration<=0)return null;let i=t.duration/t.timestampFactor;const r=yield this.getFirstPacket({metadataOnly:!0});return i+=null!=(e=null==r?void 0:r.timestamp)?e:0,i})}getLiveRefreshInterval(){return d(this,null,function*(){return null})}getFirstPacket(e){return d(this,null,function*(){return this.performClusterLookup(null,e=>e.trackData.get(this.internalTrack.id)?{blockIndex:0,correctBlockFound:!0}:{blockIndex:-1,correctBlockFound:!1},-1/0,1/0,e)})}intoTimescale(e){return G(e*this.internalTrack.segment.timestampFactor)}getPacket(e,t){return d(this,null,function*(){const i=this.intoTimescale(e);return this.performClusterLookup(null,e=>{const t=e.trackData.get(this.internalTrack.id);if(!t)return{blockIndex:-1,correctBlockFound:!1};const r=z(t.presentationTimestamps,i,e=>e.timestamp);return{blockIndex:-1!==r?t.presentationTimestamps[r].blockIndex:-1,correctBlockFound:-1!==r&&i{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=V(t.presentationTimestamps,e=>t.blocks[e.blockIndex].isKeyFrame&&e.timestamp<=i);return{blockIndex:-1!==r?t.presentationTimestamps[r].blockIndex:-1,correctBlockFound:-1!==r&&i{if(e===i.cluster){const t=e.trackData.get(this.internalTrack.id).blocks.findIndex((e,t)=>e.isKeyFrame&&t>i.blockIndex);if(-1!==t)return{blockIndex:t,correctBlockFound:!0}}else{const t=e.trackData.get(this.internalTrack.id);if(t&&null!==t.firstKeyFrameTimestamp){const e=t.blocks.findIndex(e=>e.isKeyFrame);return y(-1!==e),{blockIndex:e,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)})}fetchPacketInCluster(e,t,i){return d(this,null,function*(){var r;if(-1===t)return null;const n=e.trackData.get(this.internalTrack.id).blocks[t];y(n),n.decoded||(n.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,n.data),n.decoded=!0);const s=i.metadataOnly?Gt:n.data,a=n.timestamp/this.internalTrack.segment.timestampFactor,o=n.duration/this.internalTrack.segment.timestampFactor,l={};n.mainAdditional&&"video"===(null==(r=this.internalTrack.info)?void 0:r.type)&&this.internalTrack.info.alphaMode&&(l.alpha=i.metadataOnly?Gt:n.mainAdditional,l.alphaByteLength=n.mainAdditional.byteLength);const c=new Yt(s,n.isKeyFrame?"key":"delta",a,o,e.dataStartPos+t,n.data.byteLength,l);return this.packetToClusterLocation.set(c,{cluster:e,blockIndex:t}),c})}performClusterLookup(e,t,i,r,n){return d(this,null,function*(){var s,a,o,l;const{demuxer:c,segment:u}=this.internalTrack;let d=null,h=null,f=-1;if(e){const{blockIndex:i,correctBlockFound:r}=t(e);if(r)return this.fetchPacketInCluster(e,i,n);-1!==i&&(h=e,f=i)}const m=z(this.internalTrack.cuePoints,i,e=>e.time),p=-1!==m?this.internalTrack.cuePoints[m]:null,g=z(this.internalTrack.clusterPositionCache,i,e=>e.startTimestamp),k=-1!==g?this.internalTrack.clusterPositionCache[g]:null,b=Math.max(null!=(s=null==p?void 0:p.clusterPosition)?s:0,null!=(a=null==k?void 0:k.elementStartPos)?a:0)||null;let T;for(e?null===b||e.elementStartPos>=b?(T=e.elementEndPos,d=e):T=b:T=null!=b?b:u.clusterSeekStartPos;null===u.elementEndPos||T<=u.elementEndPos-2;){if(d){const e=d.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>r)break}let e=c.reader.requestSliceRange(T,2,Li);if(e instanceof Promise&&(e=yield e),!e)break;const i=T,s=Hi(e);if(!s||!Ni.includes(s.id)&&s.id!==Ri.Void){const e=yield Qi(c.reader,i,Ni,Math.min(null!=(o=u.elementEndPos)?o:1/0,i+gr));if(e){T=e;continue}break}const a=s.id;let l=s.size;const m=e.filePos;if(a===Ri.Cluster){d=yield c.readCluster(i,u),l=d.elementEndPos-m;const{blockIndex:e,correctBlockFound:r}=t(d);if(r)return this.fetchPacketInCluster(d,e,n);-1!==e&&(h=d,f=e)}if(void 0===l){y(a!==Ri.Cluster);l=(yield $i(c.reader,m,Oi,u.elementEndPos)).pos-m}const p=m+l;if(null===u.elementEndPos){let e=c.reader.requestSliceRange(p,2,Li);if(e instanceof Promise&&(e=yield e),!e)break;if(Wi(e)===Ri.Segment){u.elementEndPos=p;break}}T=p}if(p&&(!h||h.elementStartPosd(this,null,function*(){var e,t;let i=null;("vp9"===this.internalTrack.info.codec||"av1"===this.internalTrack.info.codec||"avc"===this.internalTrack.info.codec&&!this.internalTrack.info.codecDescription||"hevc"===this.internalTrack.info.codec&&!this.internalTrack.info.codecDescription)&&(i=yield this.getFirstPacket({}));const r={codec:Ue({width:this.internalTrack.info.width,height:this.internalTrack.info.height,codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,colorSpace:this.internalTrack.info.colorSpace,avcType:1,avcCodecInfo:"avc"===this.internalTrack.info.codec&&i?pt(i.data):null,hevcCodecInfo:"hevc"===this.internalTrack.info.codec&&i?vt(i.data):null,vp9CodecInfo:"vp9"===this.internalTrack.info.codec&&i?Rt(i.data):null,av1CodecInfo:"av1"===this.internalTrack.info.codec&&i?Mt(i.data):null}),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:null!=(e=this.internalTrack.info.codecDescription)?e:void 0,colorSpace:null!=(t=this.internalTrack.info.colorSpace)?t:void 0};return this.internalTrack.info.width===this.internalTrack.info.squarePixelWidth&&this.internalTrack.info.height===this.internalTrack.info.squarePixelHeight||(r.displayAspectWidth=this.internalTrack.info.squarePixelWidth,r.displayAspectHeight=this.internalTrack.info.squarePixelHeight),r}))():null})}}class Tr extends yr{constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getType(){return"audio"}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}getDecoderConfig(){return d(this,null,function*(){var e,t;return this.internalTrack.info.codec?null!=(t=this.decoderConfig)?t:this.decoderConfig={codec:qe({codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,aacCodecInfo:this.internalTrack.info.aacCodecInfo}),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:null!=(e=this.internalTrack.info.codecDescription)?e:void 0}:null})}}const Sr=(e,t,i)=>d(null,null,function*(){const r=o(2,16);let n=t;for(;null===i||n=4;){const t=s.filePos,i=Ra(s),r=null!==e.fileSize?e.fileSize-n:null,a=Ye(i,r);if(a.header)return{header:a.header,startPos:n};s.filePos=t+a.bytesAdvanced,n=s.filePos}}return null});class vr extends Qt{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.firstFrameHeaderPos=null,this.loadedSamples=[],this.metadataTags=null,this.xingData=null,this.trackBackings=[],this.readingMutex=new D,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}readMetadata(){return d(this,null,function*(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>d(this,null,function*(){for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)yield this.advanceReader();if(!this.firstFrameHeader)throw new Error("No valid MP3 frame found.");this.trackBackings=[new wr(this)]}))()})}advanceReader(){return d(this,null,function*(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,Qa);if(e instanceof Promise&&(e=yield e),!e)return void(this.lastSampleLoaded=!0);const t=Za(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}const e=yield Sr(this.reader,this.lastLoadedPos,this.reader.fileSize);if(!e)return void(this.lastSampleLoaded=!0);const t=e.header;this.lastLoadedPos=e.startPos+t.totalSize-1;const i=Ge(t.mpegVersionId,t.channel);let r=this.reader.requestSlice(e.startPos+i,4);if(r instanceof Promise&&(r=yield r),r){const t=Ra(r);if(t===$e||t===Qe){if(!this.xingData){let t=this.reader.requestSlice(e.startPos+i+4,12);if(t instanceof Promise&&(t=yield t),t){const e=xa(t,12),i=P(e),r=i.getUint32(0,!1);this.xingData={frameCount:r&Ze.FrameCount?i.getUint32(4,!1):null,fileSize:r&Ze.FileSize?i.getUint32(8,!1):null}}}return}}this.firstFrameHeader||(this.firstFrameHeader=t,this.firstFrameHeaderPos=e.startPos),t.sampleRate!==this.firstFrameHeader.sampleRate&&console.warn(`MP3 changed sample rate mid-file: ${this.firstFrameHeader.sampleRate} Hz to ${t.sampleRate} Hz. Might be a bug, so please report this file.`);const n=t.audioSamplesInFrame/this.firstFrameHeader.sampleRate,s={timestamp:this.nextTimestampInSamples/this.firstFrameHeader.sampleRate,duration:n,dataStart:e.startPos,dataSize:t.totalSize};this.loadedSamples.push(s),this.nextTimestampInSamples+=t.audioSamplesInFrame})}getMimeType(){return d(this,null,function*(){return"audio/mpeg"})}getTrackBackings(){return d(this,null,function*(){return yield this.readMetadata(),this.trackBackings})}getMetadataTags(){return d(this,null,function*(){const e=yield this.readingMutex.acquire();try{if(yield this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let e=0,t=!1;for(;;){let i=this.reader.requestSlice(e,Qa);if(i instanceof Promise&&(i=yield i),!i)break;const r=Za(i);if(!r)break;t=!0;let n=this.reader.requestSlice(i.filePos,r.size);if(n instanceof Promise&&(n=yield n),!n)break;eo(n,r,this.metadataTags),e=i.filePos+r.size}if(!t&&null!==this.reader.fileSize&&this.reader.fileSize>=$a){let e=this.reader.requestSlice(this.reader.fileSize-$a,$a);e instanceof Promise&&(e=yield e),y(e);"TAG"===Wa(e,3)&&Ya(e,this.metadataTags)}return this.metadataTags}finally{e()}})}}class wr{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return y(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate/this.demuxer.firstFrameHeader.audioSamplesInFrame}isRelativeToUnixEpoch(){return!1}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return d(this,null,function*(){const e=this.demuxer;if(y(null!==e.firstFrameHeader),y(null!==e.firstFrameHeaderPos),e.xingData){if(null!==e.xingData.frameCount)return e.xingData.frameCount*e.firstFrameHeader.audioSamplesInFrame/e.firstFrameHeader.sampleRate}else if(null!==e.reader.fileSize){const s=(t=e.firstFrameHeader.lowSamplingFrequency,i=e.firstFrameHeader.layer,r=e.firstFrameHeader.bitrate,n=e.firstFrameHeader.sampleRate,0===i?0:1===i?144*r/(n<e.timestamp);if(-1===i)throw new Error("Packet was not created from this track.");const r=i+1;for(;r>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)yield this.demuxer.advanceReader();return this.getPacketAtIndex(r,t)}finally{i()}})}getPacket(e,t){return d(this,null,function*(){const i=yield this.demuxer.readingMutex.acquire();try{for(;;){const i=z(this.demuxer.loadedSamples,e,e=>e.timestamp);if(-1===i&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(i,t);if(i>=0&&i+1>>0&4294967295}const xr=e=>{const t=P(e),i=t.getUint32(22,!0);t.setUint32(22,0,!0);let r=0;for(let n=0;n>>24^t])>>>0}return t.setUint32(22,i,!0),r},Cr=(e,t,i)=>{let r=0,n=null;if(e.length>0)if("vorbis"===t.codec){y(t.vorbisInfo);const s=(1<<(e=>{let t=0;for(;e;)t++,e>>=1;return t})(t.vorbisInfo.modeBlockflags.length-1))-1<<1,a=(e[0]&s)>>1;if(a>=t.vorbisInfo.modeBlockflags.length)throw new Error("Invalid mode number.");let o=i;const l=t.vorbisInfo.modeBlockflags[a];if(n=t.vorbisInfo.blocksizes[l],1===l){const i=1+(1|s),r=e[0]&i?1:0;o=t.vorbisInfo.blocksizes[r]}r=null!==o?o+n>>2:0}else if("opus"===t.codec){r=(e=>{const t=e[0]>>3;return{durationInSamples:Nt[t]}})(e).durationInSamples}return{durationInSamples:r,vorbisBlockSize:n}},Br=27,Er=282,_r=e=>{const t=e.filePos;if(Da(e)!==Pr)return null;e.skip(1);const i=Ca(e),r=za(e),n=Da(e),s=Da(e),a=Da(e),o=Ca(e),l=new Uint8Array(o);for(let d=0;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}},Ar=(e,t)=>{for(;e.filePos>>8&255)===i||(t>>>16&255)===i||(t>>>24&255)===i){if(e.skip(-4),t===Pr)return!0;e.skip(1)}}return!1};class Fr extends Qt{constructor(e){super(e),this.metadataPromise=null,this.bitstreams=[],this.trackBackings=[],this.metadataTags={},this.reader=e._reader}readMetadata(){return d(this,null,function*(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>d(this,null,function*(){let e=0;for(;;){let t=this.reader.requestSliceRange(e,Br,Er);if(t instanceof Promise&&(t=yield t),!t)break;const i=_r(t);if(!i)break;if(!!!(2&i.headerType))break;this.bitstreams.push({serialNumber:i.serialNumber,bosPage:i,description:null,numberOfChannels:-1,sampleRate:-1,codecInfo:{codec:null,vorbisInfo:null,opusInfo:null},lastMetadataPacket:null}),e=i.headerStartPos+i.totalSize}for(const t of this.bitstreams){const e=yield this.readPacket(t.bosPage,0);e&&(e.data.byteLength>=7&&1===e.data[0]&&118===e.data[1]&&111===e.data[2]&&114===e.data[3]&&98===e.data[4]&&105===e.data[5]&&115===e.data[6]?yield this.readVorbisMetadata(e,t):e.data.byteLength>=8&&79===e.data[0]&&112===e.data[1]&&117===e.data[2]&&115===e.data[3]&&72===e.data[4]&&101===e.data[5]&&97===e.data[6]&&100===e.data[7]&&(yield this.readOpusMetadata(e,t)),null!==t.codecInfo.codec&&this.trackBackings.push(new Rr(t,this)))}}))()})}readVorbisMetadata(e,t){return d(this,null,function*(){let i=yield this.findNextPacketStart(e);if(!i)return;const r=yield this.readPacket(i.startPage,i.startSegmentIndex);if(!r)return;if(i=yield this.findNextPacketStart(r),!i)return;const n=yield this.readPacket(i.startPage,i.startSegmentIndex);if(!n)return;if(3!==r.data[0]||5!==n.data[0])return;const s=[],a=e=>{for(;s.push(Math.min(255,e)),!(e<255);)e-=255};a(e.data.length),a(r.data.length);const o=new Uint8Array(1+s.length+e.data.length+r.data.length+n.data.length);o[0]=2,o.set(s,1),o.set(e.data,1+s.length),o.set(r.data,1+s.length+e.data.length),o.set(n.data,1+s.length+e.data.length+r.data.length),t.codecInfo.codec="vorbis",t.description=o,t.lastMetadataPacket=n;const l=P(e.data);t.numberOfChannels=l.getUint8(11),t.sampleRate=l.getUint32(12,!0);const c=l.getUint8(28);t.codecInfo.vorbisInfo={blocksizes:[1<<(15&c),1<<(c>>4)],modeBlockflags:Ot(n.data).modeBlockflags},qt(r.data.subarray(7),this.metadataTags)})}readOpusMetadata(e,t){return d(this,null,function*(){const i=yield this.findNextPacketStart(e);if(!i)return;const r=yield this.readPacket(i.startPage,i.startSegmentIndex);if(!r)return;t.codecInfo.codec="opus",t.description=e.data,t.lastMetadataPacket=r;const n=(e=>{const t=P(e),i=t.getUint8(9),r=t.getUint16(10,!0),n=t.getUint32(12,!0),s=t.getInt16(16,!0),a=t.getUint8(18);let o=null;return a&&(o=e.subarray(19,21+i)),{outputChannelCount:i,preSkip:r,inputSampleRate:n,outputGain:s,channelMappingFamily:a,channelMappingTable:o}})(e.data);t.numberOfChannels=n.outputChannelCount,t.sampleRate=We,t.codecInfo.opusInfo={preSkip:n.preSkip},qt(r.data.subarray(8),this.metadataTags)})}readPacket(e,t){return d(this,null,function*(){y(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 d(this,null,function*(){return yield this.readMetadata(),this.trackBackings})}getMetadataTags(){return d(this,null,function*(){return yield this.readMetadata(),this.metadataTags})}}class Rr{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new D,this.internalSampleRate="opus"===e.codecInfo.codec?We:e.sampleRate}getType(){return"audio"}getId(){return this.bitstream.serialNumber}getNumber(){const e=this.demuxer.trackBackings.findIndex(e=>e.bitstream===this.bitstream);return y(-1!==e),e+1}getNumberOfChannels(){return this.bitstream.numberOfChannels}getSampleRate(){return this.bitstream.sampleRate}getTimeResolution(){return this.bitstream.sampleRate}isRelativeToUnixEpoch(){return!1}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return d(this,null,function*(){return null})}getLiveRefreshInterval(){return d(this,null,function*(){return null})}getCodec(){return this.bitstream.codecInfo.codec}getInternalCodecId(){return null}getDecoderConfig(){return d(this,null,function*(){var e;return y(this.bitstream.codecInfo.codec),{codec:this.bitstream.codecInfo.codec,numberOfChannels:this.bitstream.numberOfChannels,sampleRate:this.bitstream.sampleRate,description:null!=(e=this.bitstream.description)?e:void 0}})}getName(){return null}getLanguageCode(){return Q}getDisposition(){return u(c({},Be),{primary:!1})}granulePositionToTimestampInSamples(e){return"opus"===this.bitstream.codecInfo.codec?(y(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,i){if(!e)return null;const{durationInSamples:r,vorbisBlockSize:n}=Cr(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),s=new Yt(i.metadataOnly?Gt:e.data,"key",Math.max(0,t.timestampInSamples)/this.internalSampleRate,r/this.internalSampleRate,e.endPage.headerStartPos+e.endSegmentIndex,e.data.byteLength);return this.encodedPacketToMetadata.set(s,{packet:e,timestampInSamples:t.timestampInSamples,durationInSamples:r,vorbisLastBlockSize:t.vorbisLastBlocksize,vorbisBlockSize:n}),s}getFirstPacket(e){return d(this,null,function*(){y(this.bitstream.lastMetadataPacket);const t=yield this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let i=0;"opus"===this.bitstream.codecInfo.codec&&(y(this.bitstream.codecInfo.opusInfo),i-=this.bitstream.codecInfo.opusInfo.preSkip);const r=yield this.demuxer.readPacket(t.startPage,t.startSegmentIndex);return this.createEncodedPacketFromOggPacket(r,{timestampInSamples:i,vorbisLastBlocksize:null},e)})}getNextPacket(e,t){return d(this,null,function*(){const i=this.encodedPacketToMetadata.get(e);if(!i)throw new Error("Packet was not created from this track.");const r=yield this.demuxer.findNextPacketStart(i.packet);if(!r)return null;const n=i.timestampInSamples+i.durationInSamples,s=yield this.demuxer.readPacket(r.startPage,r.startSegmentIndex);return this.createEncodedPacketFromOggPacket(s,{timestampInSamples:n,vorbisLastBlocksize:i.vorbisBlockSize},t)})}getPacket(e,t){return d(this,null,function*(){var i,r;if(null===this.demuxer.reader.fileSize)return this.getPacketSequential(e,t);const n=G(e*this.internalSampleRate);if(0===n)return this.getFirstPacket(t);if(n<0)return null;y(this.bitstream.lastMetadataPacket);const s=yield this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!s)return null;let a=s.startPage,o=this.demuxer.reader.fileSize;const l=[a];e:for(;a.headerStartPos+a.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,Br,Er);t instanceof Promise&&(t=yield t),y(t);const i=_r(t);y(i),u=i,u.serialNumber===this.bitstream.serialNumber&&d.push(u)}y(-1!==u.granulePosition);let h,f,m=null,p=u,g=0;if(u.headerStartPos===s.startPage.headerStartPos)h=this.granulePositionToTimestampInSamples(0),f=!0,m=0;else{h=0,f=!1;for(let t=u.lacingValues.length-1;t>=0;t--){if(u.lacingValues[t]<255){m=t+1;break}}if(null===m)throw new Error("Invalid page with granule position: no packets end on this page.");g=m-1;const e={data:Gt,endPage:p,endSegmentIndex:g};if(yield this.demuxer.findNextPacketStart(e)){const e=Mr(d,u,m);y(e);const t=Dr(d,e.page,e.segmentIndex);t&&(u=t.page,m=t.segmentIndex)}else for(;;){const e=Mr(d,u,m);if(!e)break;const t=Dr(d,e.page,e.segmentIndex);if(!t)break;if(u=t.page,m=t.segmentIndex,e.page.headerStartPos!==p.headerStartPos){p=e.page,g=e.segmentIndex;break}}}let k=null,b=null;for(;null!==u;){y(null!==m);const e=yield this.demuxer.readPacket(u,m);if(!e)break;if(!(u.headerStartPos===s.startPage.headerStartPos&&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 d(this,null,function*(){const i=yield this.sequentialScanMutex.acquire();try{const i=G(e*this.internalSampleRate);e=i/this.internalSampleRate;const r=z(this.sequentialScanCache,i,e=>e.timestampInSamples);let n;if(-1!==r){const e=this.sequentialScanCache[r];n=this.createEncodedPacketFromOggPacket(e.packet,{timestampInSamples:e.timestampInSamples,vorbisLastBlocksize:e.vorbisLastBlockSize},t)}else n=yield this.getFirstPacket(t);let s=0;for(;n&&n.timestampe)break;if(n=i,s++,100===s){s=0;const e=this.encodedPacketToMetadata.get(n);y(e),this.sequentialScanCache.length>0&&y(T(this.sequentialScanCache).timestampInSamples<=e.timestampInSamples),this.sequentialScanCache.push(e)}}return n}finally{i()}})}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const Dr=(e,t,i)=>{let r=t,n=i;e:for(;;){for(n--;n>=0;n--){if(r.lacingValues[n]<255){n++;break e}}y(-1===n);if(!(1&r.headerType)){n=0;break}const t=W(e,e=>e.headerStartPos{if(i>0)return{page:t,segmentIndex:i-1};const r=W(e,e=>e.headerStartPosd(this,null,function*(){var e,t;let i=this.reader.requestSlice(0,12);i instanceof Promise&&(i=yield i),y(i);const r=Wa(i,4),n="RIFX"!==r,s="RF64"===r,a=Fa(i,n);let o=s?this.reader.fileSize:Math.min(a+8,null!=(e=this.reader.fileSize)?e:1/0);if("WAVE"!==Wa(i,4))throw new Error("Invalid WAVE file - wrong format");let l=0,c=null,u=i.filePos;for(;null===o||u=18&&357!==n){const e=Ba(r,i),s=t-18;if(Math.min(s,e)>=22&&n===Nr.EXTENSIBLE){r.skip(6);const e=xa(r,16);n=e[0]|e[1]<<8}}n!==Nr.MULAW&&n!==Nr.ALAW||(l=8),this.audioInfo={format:n,numberOfChannels:s,sampleRate:a,sampleSizeInBytes:Math.ceil(l/8),blockSizeInBytes:o}})}parseListChunk(e,t,i){return d(this,null,function*(){var r,n,s,a,o,l,c,u,d,h,f;let m=this.reader.requestSlice(e,t);if(m instanceof Promise&&(m=yield m),!m)return;const p=Wa(m,4);if("INFO"!==p&&"INF0"!==p)return;let g=m.filePos;for(;g<=e+t-8;){m.filePos=g;const e=Wa(m,4),t=Fa(m,i),p=xa(m,t);let k=0;for(let i=0;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 d(this,null,function*(){let i=this.reader.requestSlice(e,t);if(i instanceof Promise&&(i=yield i),!i)return;const r=Za(i);if(r){const n=t-Qa;if(r.size=Math.min(r.size,n),r.size>0){const t=i.slice(e+Qa,r.size);eo(t,r,this.metadataTags)}}})}getCodec(){if(y(this.audioInfo),this.audioInfo.format===Nr.MULAW)return"ulaw";if(this.audioInfo.format===Nr.ALAW)return"alaw";if(this.audioInfo.format===Nr.PCM){if(1===this.audioInfo.sampleSizeInBytes)return"pcm-u8";if(2===this.audioInfo.sampleSizeInBytes)return"pcm-s16";if(3===this.audioInfo.sampleSizeInBytes)return"pcm-s24";if(4===this.audioInfo.sampleSizeInBytes)return"pcm-s32"}return this.audioInfo.format===Nr.IEEE_FLOAT&&4===this.audioInfo.sampleSizeInBytes?"pcm-f32":null}getMimeType(){return d(this,null,function*(){return"audio/wav"})}getTrackBackings(){return d(this,null,function*(){return yield this.readMetadata(),this.trackBackings})}getMetadataTags(){return d(this,null,function*(){return yield this.readMetadata(),this.metadataTags})}}const zr=2048;class Ur{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return y(this.demuxer.audioInfo),this.demuxer.audioInfo.format}getDecoderConfig(){return d(this,null,function*(){const e=this.demuxer.getCodec();return e?(y(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null})}getNumberOfChannels(){return y(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return y(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return y(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return d(this,null,function*(){return y(-1!==this.demuxer.dataSize),this.demuxer.dataSize/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate})}getLiveRefreshInterval(){return d(this,null,function*(){return null})}getName(){return null}getLanguageCode(){return Q}getDisposition(){return c({},Be)}getPacketAtIndex(e,t){return d(this,null,function*(){y(e>=0),y(this.demuxer.audioInfo);const i=e*zr*this.demuxer.audioInfo.blockSizeInBytes;if(i>=this.demuxer.dataSize)return null;const r=Math.min(zr*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-i);if(null===this.demuxer.reader.fileSize){let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+i,r);if(e instanceof Promise&&(e=yield e),!e)return null}let n;if(t.metadataOnly)n=Gt;else{let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+i,r);e instanceof Promise&&(e=yield e),y(e),n=xa(e,r)}const s=e*zr/this.demuxer.audioInfo.sampleRate,a=r/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(e,this.demuxer.lastKnownPacketIndex),new Yt(n,"key",s,a,e,r)})}getFirstPacket(e){return this.getPacketAtIndex(0,e)}getPacket(e,t){return d(this,null,function*(){y(this.demuxer.audioInfo);const i=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/zr,(this.demuxer.dataSize-1)/(zr*this.demuxer.audioInfo.blockSizeInBytes)));if(i<0)return null;const r=yield this.getPacketAtIndex(i,t);if(r)return r;if(0===i)return null;y(null===this.demuxer.reader.fileSize);let n=yield this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,t);for(;n;){const e=yield this.getNextPacket(n,t);if(!e)break;n=e}return n})}getNextPacket(e,t){y(this.demuxer.audioInfo);const i=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/zr);return this.getPacketAtIndex(i+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const qr=e=>{const t=e.filePos,i=xa(e,9),r=new Ee(i);if(4095!==r.readBits(12))return null;r.skipBits(1);if(0!==r.readBits(2))return null;const n=r.readBits(1),s=r.readBits(2)+1,a=r.readBits(4);if(15===a)return null;r.skipBits(1);const o=r.readBits(3);if(0===o)throw new Error("ADTS frames with channel configuration 0 are not supported.");r.skipBits(1),r.skipBits(1),r.skipBits(1),r.skipBits(1);const l=r.readBits(13);r.skipBits(11);const c=r.readBits(2)+1;if(1!==c)throw new Error("ADTS frames with more than one AAC frame are not supported.");let u=null;return 1===n?e.filePos-=2:u=r.readBits(16),{objectType:s,samplingFrequencyIndex:a,channelConfiguration:o,frameLength:l,numberOfAacFrames:c,crcCheck:u,startPos:t}},Wr=1024;class Vr extends Qt{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.trackBackings=[],this.readingMutex=new D,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}readMetadata(){return d(this,null,function*(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>d(this,null,function*(){for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)yield this.advanceReader();y(this.firstFrameHeader),this.trackBackings=[new Hr(this)]}))()})}advanceReader(){return d(this,null,function*(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,Qa);if(e instanceof Promise&&(e=yield e),!e)return void(this.lastSampleLoaded=!0);const t=Za(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}let e=this.reader.requestSliceRange(this.lastLoadedPos,7,9);if(e instanceof Promise&&(e=yield e),!e)return void(this.lastSampleLoaded=!0);const t=qr(e);if(!t)return void(this.lastSampleLoaded=!0);if(null!==this.reader.fileSize&&t.startPos+t.frameLength>this.reader.fileSize)return void(this.lastSampleLoaded=!0);this.firstFrameHeader||(this.firstFrameHeader=t);const i=_e[t.samplingFrequencyIndex];y(void 0!==i);const r=Wr/i,n={timestamp:this.nextTimestampInSamples/i,duration:r,dataStart:t.startPos,dataSize:t.frameLength};this.loadedSamples.push(n),this.nextTimestampInSamples+=Wr,this.lastLoadedPos=t.startPos+t.frameLength})}getMimeType(){return d(this,null,function*(){return"audio/aac"})}getTrackBackings(){return d(this,null,function*(){return yield this.readMetadata(),this.trackBackings})}getMetadataTags(){return d(this,null,function*(){const e=yield this.readingMutex.acquire();try{if(yield this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let e=0;for(;;){let t=this.reader.requestSlice(e,Qa);if(t instanceof Promise&&(t=yield t),!t)break;const i=Za(t);if(!i)break;let r=this.reader.requestSlice(t.filePos,i.size);if(r instanceof Promise&&(r=yield r),!r)break;eo(r,i,this.metadataTags),e=t.filePos+i.size}return this.metadataTags}finally{e()}})}}class Hr{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return this.getSampleRate()/Wr}isRelativeToUnixEpoch(){return!1}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return d(this,null,function*(){return null})}getLiveRefreshInterval(){return d(this,null,function*(){return null})}getName(){return null}getLanguageCode(){return Q}getCodec(){return"aac"}getInternalCodecId(){return y(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){y(this.demuxer.firstFrameHeader);const e=Ae[this.demuxer.firstFrameHeader.channelConfiguration];return y(void 0!==e),e}getSampleRate(){y(this.demuxer.firstFrameHeader);const e=_e[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return y(void 0!==e),e}getDisposition(){return c({},Be)}getDecoderConfig(){return d(this,null,function*(){return y(this.demuxer.firstFrameHeader),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate()}})}getPacketAtIndex(e,t){return d(this,null,function*(){if(-1===e)return null;const i=this.demuxer.loadedSamples[e];if(!i)return null;let r;if(t.metadataOnly)r=Gt;else{let e=this.demuxer.reader.requestSlice(i.dataStart,i.dataSize);if(e instanceof Promise&&(e=yield e),!e)return null;r=xa(e,i.dataSize)}return new Yt(r,"key",i.timestamp,i.duration,e,i.dataSize)})}getFirstPacket(e){return this.getPacketAtIndex(0,e)}getNextPacket(e,t){return d(this,null,function*(){const i=yield this.demuxer.readingMutex.acquire();try{const i=L(this.demuxer.loadedSamples,e.timestamp,e=>e.timestamp);if(-1===i)throw new Error("Packet was not created from this track.");const r=i+1;for(;r>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)yield this.demuxer.advanceReader();return this.getPacketAtIndex(r,t)}finally{i()}})}getPacket(e,t){return d(this,null,function*(){const i=yield this.demuxer.readingMutex.acquire();try{for(;;){const i=z(this.demuxer.loadedSamples,e,e=>e.timestamp);if(-1===i&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(i,t);if(i>=0&&i+1d(this,null,function*(){for(var e;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===Ca(s)){const t=s.filePos;if(Ca(s)!==(1===this.blockingBit?249:248)){s.filePos=t;continue}s.skip(-2);const i=s.filePos-e,r=this.readFlacFrameHeader({slice:s,isFirstPacket:!1});if(!r){s.filePos=t;continue}if(0===this.blockingBit){if(r.num-a.num!==1){s.filePos=t;continue}}else if(r.num-a.num!==a.blockSize){s.filePos=t;continue}return{num:a.num,blockSize:a.blockSize,sampleRate:a.sampleRate,size:i,isLastFrame:!1}}}})}readFlacFrameHeader({slice:e,isFirstPacket:t}){const i=e.filePos,r=xa(e,4),n=new Ee(r);if(32764!==n.readBits(15))return null;if(null===this.blockingBit){y(t);const e=n.readBits(1);this.blockingBit=e}else if(1===this.blockingBit){y(!t);if(1!==n.readBits(1))return null}else{if(0!==this.blockingBit)throw new Error("Invalid blocking bit");y(!t);if(0!==n.readBits(1))return null}const s=(e=>0===e?null:1===e?192:e>=2&&e<=5?144*o(2,e):6===e?"uncommon-u8":7===e?"uncommon-u16":e>=8&&e<=15?o(2,e):null)(n.readBits(4));if(!s)return null;y(this.audioInfo);const a=((e,t)=>{switch(e){case 0:return t;case 1:return 88200;case 2:return 176400;case 3:return 192e3;case 4:return 8e3;case 5:return 16e3;case 6:return 22050;case 7:return 24e3;case 8:return 32e3;case 9:return 44100;case 10:return 48e3;case 11:return 96e3;case 12:return"uncommon-u8";case 13:return"uncommon-u16";case 14:return"uncommon-u16-10";default:return null}})(n.readBits(4),this.audioInfo.sampleRate);if(!a)return null;n.readBits(4),n.readBits(3);if(0!==n.readBits(1))return null;const l=(e=>{let t=0;const i=new Ee(xa(e,1));for(;1===i.readBits(1);)t++;if(0===t)return i.readBits(7);const r=[],n=t-1,s=new Ee(xa(e,n)),a=8-t-1;for(let o=0;oe|t<"uncommon-u16"===t?Ea(e)+1:"uncommon-u8"===t?Ca(e)+1:"number"===typeof t?t:(H(t),void y(!1)))(e,s),u=((e,t)=>"uncommon-u16"===t?Ea(e):"uncommon-u16-10"===t?10*Ea(e):"uncommon-u8"===t?Ca(e):"number"===typeof t?t:null)(e,a);if(null===u)return null;if(u!==this.audioInfo.sampleRate)return null;const d=e.filePos-i,h=Ca(e);e.skip(-d),e.skip(-1);const f=(e=>{let t=0;for(const i of e){t^=i;for(let e=0;e<8;e++)0!==(128&t)?t=t<<1^7:t<<=1,t&=255}return t})(xa(e,d));return h!==f?null:{num:l,blockSize:c,sampleRate:u}}advanceReader(){return d(this,null,function*(){yield this.readMetadata(),y(null!==this.lastLoadedPos),y(this.audioInfo);const e=this.lastLoadedPos,t=yield this.readNextFlacFrame({startPos:e,isFirstPacket:0===this.loadedSamples.length});if(!t)return void(this.lastSampleLoaded=!0);const i=this.loadedSamples[this.loadedSamples.length-1],r={blockOffset:i?i.blockOffset+i.blockSize:0,blockSize:t.blockSize,byteOffset:e,byteSize:t.size};this.lastLoadedPos=this.lastLoadedPos+t.size,this.loadedSamples.push(r),t.isLastFrame&&(this.lastSampleLoaded=!0)})}}class jr{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return y(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return y(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return Q}getTimeResolution(){return y(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return d(this,null,function*(){return y(this.demuxer.audioInfo),0===this.demuxer.audioInfo.totalSamples?null:this.demuxer.audioInfo.totalSamples/this.demuxer.audioInfo.sampleRate})}getLiveRefreshInterval(){return d(this,null,function*(){return null})}getDisposition(){return c({},Be)}getDecoderConfig(){return d(this,null,function*(){return y(this.demuxer.audioInfo),{codec:"flac",numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}})}getPacket(e,t){return d(this,null,function*(){if(y(this.demuxer.audioInfo),e<0)throw new Error("Timestamp cannot be negative");const i=yield this.demuxer.readingMutex.acquire();try{for(;;){const i=z(this.demuxer.loadedSamples,e,e=>e.blockOffset/this.demuxer.audioInfo.sampleRate);if(-1===i){yield this.demuxer.advanceReader();continue}const r=this.demuxer.loadedSamples[i],n=r.blockOffset/this.demuxer.audioInfo.sampleRate;if(!(n+r.blockSize/this.demuxer.audioInfo.sampleRate<=e))return this.getPacketAtIndex(i,t);if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(this.demuxer.loadedSamples.length-1,t);yield this.demuxer.advanceReader()}}finally{i()}})}getNextPacket(e,t){return d(this,null,function*(){const i=yield this.demuxer.readingMutex.acquire();try{const i=e.sequenceNumber+1;if(this.demuxer.lastSampleLoaded&&i>=this.demuxer.loadedSamples.length)return null;for(;i>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)yield this.demuxer.advanceReader();return this.getPacketAtIndex(i,t)}finally{i()}})}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}getPacketAtIndex(e,t){return d(this,null,function*(){const i=this.demuxer.loadedSamples[e];if(!i)return null;let r;if(t.metadataOnly)r=Gt;else{let e=this.demuxer.reader.requestSlice(i.byteOffset,i.byteSize);if(e instanceof Promise&&(e=yield e),!e)return null;r=xa(e,i.byteSize)}y(this.demuxer.audioInfo);const n=i.blockOffset/this.demuxer.audioInfo.sampleRate,s=i.blockSize/this.demuxer.audioInfo.sampleRate;return new Yt(r,"key",n,s,e,i.byteSize)})}getFirstPacket(e){return d(this,null,function*(){for(;0===this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)yield this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)})}}const Xr=9e4,$r=188,Qr="PES packet is missing PTS where it was expected. PES packets without PTS are not currently supported. If you think this file should be supported, please report it.",Gr=new Set;class Yr extends Qt{constructor(e){super(e),this.metadataPromise=null,this.elementaryStreams=[],this.trackBackingEntries=[],this.packetOffset=0,this.packetStride=-1,this.sectionEndPositions=[],this.seekChunkSize=5242880,this.minReferencePointByteDistance=-1,this.reader=e._reader}readMetadata(){return d(this,null,function*(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>d(this,null,function*(){let e=this.reader.requestSlice(0,205);e instanceof Promise&&(e=yield e),y(e);const t=xa(e,205);if(71===t[0]&&71===t[188])this.packetOffset=0,this.packetStride=$r;else if(71===t[0]&&71===t[204])this.packetOffset=0,this.packetStride=204;else{if(71!==t[4]||71!==t[196])throw new Error("Unreachable.");this.packetOffset=4,this.packetStride=192}this.minReferencePointByteDistance=256*this.packetStride;let i=this.packetOffset,r=null,n=!1,s=!1;for(;;){const e=yield this.readPacketHeader(i);if(!e)break;if(0===e.payloadUnitStartIndicator){i+=this.packetStride;continue}const t=yield this.readSection(i,!0,!s);if(!t)break;const a=3,o=32;let l=!1;if(!s&&0!==t.pid){if(!(0===t.payload[0]&&0===t.payload[1]&&1===t.payload[2])){const e=new Ee(t.payload),i=e.readAlignedByte();e.skipBits(8*i);l=2===e.readBits(8)}}if(0!==t.pid||n)if(t.pid!==r&&!l||s){const e=this.elementaryStreams.find(e=>e.pid===t.pid);e:if(e&&!e.initialized){const i=Zr(t,!0);if(!i)throw new Error(`Couldn't read first PES packet for Elementary Stream with PID ${e.pid}`);if(e.firstSection=t,e.canBeTrustedWithKeyPackets=1===t.randomAccessIndicator,this.input._initInput){const i=(yield this.input._initInput._getDemuxer()).elementaryStreams.find(i=>i.pid===t.pid&&i.info.codec===e.info.codec);if(i){e.info=i.info,e.initialized=!0;break e}}const r=new sn(e,i);if("video"===e.info.type){for(;;){if(r.suppliedPacket=null,yield r.markNextPacket(),"avc"===e.info.codec){if(!r.suppliedPacket)throw new Error("Invalid AVC video stream; could not extract AVCDecoderConfigurationRecord from any packet.");if(e.info.avcCodecInfo=pt(r.suppliedPacket.data),!e.info.avcCodecInfo)continue;const t=e.info.avcCodecInfo.sequenceParameterSets[0];y(t);const i=kt(t);e.info.width=i.displayWidth,e.info.height=i.displayHeight;const n=i.pixelAspectRatio.num,s=i.pixelAspectRatio.den;n>0&&s>0&&(n>s?(e.info.squarePixelWidth=Math.round(e.info.width*n/s),e.info.squarePixelHeight=e.info.height):(e.info.squarePixelWidth=e.info.width,e.info.squarePixelHeight=Math.round(e.info.height*s/n))),e.info.colorSpace={primaries:B[i.colourPrimaries],transfer:_[i.transferCharacteristics],matrix:F[i.matrixCoefficients],fullRange:!!i.fullRangeFlag},e.info.reorderSize=i.maxDecFrameBuffering;break}if("hevc"===e.info.codec){if(!r.suppliedPacket)throw new Error("Invalid HEVC video stream; could not extract HVCDecoderConfigurationRecord from first packet.");if(e.info.hevcCodecInfo=vt(r.suppliedPacket.data),!e.info.hevcCodecInfo)continue;const t=e.info.hevcCodecInfo.arrays.find(e=>e.nalUnitType===st.SPS_NUT).nalUnits[0];y(t);const i=St(t);e.info.width=i.displayWidth,e.info.height=i.displayHeight,i.pixelAspectRatio.num>i.pixelAspectRatio.den?(e.info.squarePixelWidth=Math.round(e.info.width*i.pixelAspectRatio.num/i.pixelAspectRatio.den),e.info.squarePixelHeight=e.info.height):(e.info.squarePixelWidth=e.info.width,e.info.squarePixelHeight=Math.round(e.info.height*i.pixelAspectRatio.den/i.pixelAspectRatio.num)),e.info.colorSpace={primaries:B[i.colourPrimaries],transfer:_[i.transferCharacteristics],matrix:F[i.matrixCoefficients],fullRange:!!i.fullRangeFlag},e.info.reorderSize=i.maxDecFrameBuffering;break}throw new Error("Unhandled.")}e.info.decoderConfig={codec:Ue({width:e.info.width,height:e.info.height,codec:e.info.codec,codecDescription:null,colorSpace:e.info.colorSpace,avcType:1,avcCodecInfo:e.info.avcCodecInfo,hevcCodecInfo:e.info.hevcCodecInfo,vp9CodecInfo:null,av1CodecInfo:null}),codedWidth:e.info.width,codedHeight:e.info.height,colorSpace:e.info.colorSpace},e.info.width===e.info.squarePixelWidth&&e.info.height===e.info.squarePixelHeight||(e.info.decoderConfig.displayAspectWidth=e.info.squarePixelWidth,e.info.decoderConfig.displayAspectHeight=e.info.squarePixelHeight),e.initialized=!0}else{if(yield r.markNextPacket(),!r.suppliedPacket)throw new Error(`Couldn't parse first media packet for Elementary Stream with PID ${e.pid}`);if("aac"===e.info.codec){const t=Pa.tempFromBytes(r.suppliedPacket.data),i=qr(t);if(!i)throw new Error("Invalid AAC audio stream; could not read ADTS frame header from first packet.");e.info.aacCodecInfo={isMpeg2:!1,objectType:i.objectType},e.info.numberOfChannels=Ae[i.channelConfiguration],e.info.sampleRate=_e[i.samplingFrequencyIndex]}else if("mp3"===e.info.codec){const t=Ra(Pa.tempFromBytes(r.suppliedPacket.data)),i=Ye(t,r.suppliedPacket.data.byteLength);if(!i.header)throw new Error("Invalid MP3 audio stream; could not read frame header from first packet.");e.info.numberOfChannels=3===i.header.channel?1:2,e.info.sampleRate=i.header.sampleRate}else if("ac3"===e.info.codec){const t=Vt(r.suppliedPacket.data);if(!t)throw new Error("Invalid AC-3 audio stream; could not read sync frame from first packet.");if(3===t.fscod)throw new Error("Invalid AC-3 audio stream; reserved sample rate code found in first packet.");e.info.numberOfChannels=Wt[t.acmod]+t.lfeon,e.info.sampleRate=tt[t.fscod]}else{if("eac3"!==e.info.codec)throw new Error("Unhandled.");{const t=jt(r.suppliedPacket.data);if(!t)throw new Error("Invalid E-AC-3 audio stream; could not read sync frame from first packet.");const i=Xt(t);if(null===i)throw new Error("Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.");e.info.numberOfChannels=$t(t),e.info.sampleRate=i}}e.info.decoderConfig={codec:qe({codec:e.info.codec,codecDescription:null,aacCodecInfo:e.info.aacCodecInfo}),numberOfChannels:e.info.numberOfChannels,sampleRate:e.info.sampleRate},e.initialized=!0}}}else{const e=new Ee(t.payload),i=e.readAlignedByte();e.skipBits(8*i),e.skipBits(12);const r=e.readBits(12);e.skipBits(43),e.readBits(13),e.skipBits(6);const n=e.readBits(10);for(e.skipBits(8*n);8*(r+a)-e.pos>o;){const t=e.readBits(8);e.skipBits(3);const i=e.readBits(13);e.skipBits(6);const r=e.readBits(10),n=e.pos+8*r;let s=!1,a=!1;for(;e.poso;){const t=e.readBits(16);e.skipBits(3);const i=e.readBits(13);if(0!==t){if(null!==r)throw new Error("Only files with a single program are supported.");r=i}}if(null===r)throw new Error("Program Association Table must link to a Program Map Table.");n=!0}if(s&&this.elementaryStreams.every(e=>e.initialized))break;i+=this.packetStride}if(!s){if(!n)throw new Error("No Program Association Table found in the file.");throw new Error("No Program Map Table found in the file.")}for(const a of this.elementaryStreams)"video"===a.info.type?this.trackBackingEntries.push(new tn(a)):this.trackBackingEntries.push(new rn(a))}))()})}getTrackBackings(){return d(this,null,function*(){return yield this.readMetadata(),this.trackBackingEntries})}getMetadataTags(){return d(this,null,function*(){return{}})}getMimeType(){return d(this,null,function*(){yield this.readMetadata();return(e=>{let t="video/MP2T";const i=[...new Set(e.filter(Boolean))];return i.length>0&&(t+=`; codecs="${i.join(", ")}"`),t})(yield Promise.all(this.trackBackingEntries.map(e=>e.getDecoderConfig().then(e=>{var t;return null!=(t=null==e?void 0:e.codec)?t:null}))))})}readSection(e,t,i=!1){return d(this,null,function*(){let r=e,n=e;const s=[];let a,o=0,l=null,c=!0,u=0;for(;;){const e=yield this.readPacket(n);if(n+=this.packetStride,!e)break;if(l){if(e.pid!==l.pid){if(i)break;continue}if(1===e.payloadUnitStartIndicator)break}else{if(0===e.payloadUnitStartIndicator)break;l=e}const a=!!(2&e.adaptationFieldControl),d=!!(1&e.adaptationFieldControl);let h=0;if(a&&(h=1+e.body[0],e===l&&h>1&&(u=e.body[1]>>6&1)),d&&(0===h?(s.push(e.body),o+=e.body.byteLength):(s.push(e.body.subarray(h)),o+=e.body.byteLength-h)),r=n,!t&&o>=64){c=!1;break}if(-1!==L(this.sectionEndPositions,r,e=>e)){c=!1;break}}if(c){const e=z(this.sectionEndPositions,r,e=>e);this.sectionEndPositions.splice(e+1,0,r)}if(!l)return null;if(1===s.length)a=s[0];else{const e=s.reduce((e,t)=>e+t.length,0);a=new Uint8Array(e);let t=0;for(const i of s)a.set(i,t),t+=i.length}return{startPos:e,endPos:t?r:null,pid:l.pid,payload:a,randomAccessIndicator:u}})}readPacketHeader(e){return d(this,null,function*(){let t=this.reader.requestSlice(e,4);if(t instanceof Promise&&(t=yield t),!t)return null;if(71!==Ca(t))throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");const i=Ea(t);return{payloadUnitStartIndicator:i>>14&1,pid:8191&i,adaptationFieldControl:Ca(t)>>4&3}})}readPacket(e){return d(this,null,function*(){let t=this.reader.requestSlice(e,$r);if(t instanceof Promise&&(t=yield t),!t)return null;const i=xa(t,$r);if(71!==i[0])throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");const r=(i[1]<<8)+i[2];return{payloadUnitStartIndicator:r>>14&1,pid:8191&r,adaptationFieldControl:i[3]>>4&3,body:i.subarray(4)}})}}const Jr=(e,t)=>{if(e.payload.byteLength<3)return null;const i=new Ee(e.payload);if(1!==i.readBits(24))return null;const r=i.readBits(8);if(i.skipBits(16),188===r||190===r||191===r||240===r||241===r||255===r||242===r||248===r)return null;i.skipBits(8);const n=i.readBits(2);i.skipBits(14);let s=null;if(2===n||3===n)s=0,i.skipBits(4),s+=i.readBits(3)*(1<<30),i.skipBits(1),s+=32768*i.readBits(15),i.skipBits(1),s+=i.readBits(15);else if(t)throw new Error(Qr);return{sectionStartPos:e.startPos,sectionEndPos:e.endPos,pts:s,randomAccessIndicator:e.randomAccessIndicator}},Zr=(e,t)=>{y(null!==e.endPos);const i=Jr(e,t);if(!i)return null;const r=new Ee(e.payload);r.skipBits(32);const n=r.readBits(16);r.skipBits(16);const s=r.readBits(8),a=r.pos+8*s;r.pos=a;const o=a/8;y(Number.isInteger(o));const l=e.payload.subarray(o,n>0?6+n:e.payload.byteLength);return u(c({},i),{data:l})};class en{constructor(e){this.elementaryStream=e,this.packetBuffers=new WeakMap,this.packetSectionStarts=new WeakMap}getId(){return this.elementaryStream.pid}getNumber(){const e=this.elementaryStream.demuxer,t=this.elementaryStream.info.type;let i=0;for(const r of e.trackBackingEntries)if(r.getType()===t&&i++,y(r instanceof en),r.elementaryStream===this.elementaryStream)break;return i}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.elementaryStream.streamType}getName(){return null}getLanguageCode(){return Q}getDisposition(){return u(c({},Be),{primary:!1})}getTimeResolution(){return Xr}isRelativeToUnixEpoch(){return!1}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return d(this,null,function*(){return null})}getLiveRefreshInterval(){return d(this,null,function*(){return null})}createEncodedPacket(e,t,i){let r;return r=this.allPacketsAreKeyPackets()||1===e.randomAccessIndicator?"key":"delta",new Yt(i.metadataOnly?Gt:e.data,r,e.pts/Xr,Math.max(t/Xr,0),e.sequenceNumber,e.data.byteLength)}getFirstPacket(e){return d(this,null,function*(){const t=this.elementaryStream.firstSection;y(t);const i=Zr(t,!0);y(i);const r=new sn(this.elementaryStream,i),n=new an(this,r),s=yield n.readNext();if(!s)return null;const a=this.createEncodedPacket(s.packet,s.duration,e);return this.packetBuffers.set(a,n),this.packetSectionStarts.set(a,s.packet.sectionStartPos),a})}getNextPacket(e,t){return d(this,null,function*(){let i=this.packetBuffers.get(e);if(i){const r=yield i.readNext();if(!r)return null;this.packetBuffers.delete(e);const n=this.createEncodedPacket(r.packet,r.duration,t);return this.packetBuffers.set(n,i),this.packetSectionStarts.set(n,r.packet.sectionStartPos),n}const r=this.packetSectionStarts.get(e);if(void 0===r)throw new Error("Packet was not created from this track.");const n=this.elementaryStream.demuxer,s=yield n.readSection(r,!0);y(s);const a=Zr(s,!0);y(a);const o=new sn(this.elementaryStream,a);i=new an(this,o);const l=e.sequenceNumber;for(;;){const e=yield i.readNext();if(!e)return null;if(e.packet.sequenceNumber>l){const r=this.createEncodedPacket(e.packet,e.duration,t);return this.packetBuffers.set(r,i),this.packetSectionStarts.set(r,e.packet.sectionStartPos),r}}})}getNextKeyPacket(e,t){return d(this,null,function*(){let i=e;for(;;){if(i=yield this.getNextPacket(i,t),!i)return null;if("key"===i.type)return i}})}getPacket(e,t){return this.doPacketLookup(e,!1,t)}getKeyPacket(e,t){return this.doPacketLookup(e,!0,t)}doPacketLookup(e,t,i){return d(this,null,function*(){var r,n,s,a,o,l;const c=G(e*Xr),u=this.elementaryStream.demuxer,{reader:h,seekChunkSize:f}=u,m=this.elementaryStream.pid,p=(e,t,i)=>d(this,null,function*(){let r=e;for(;re.pts),w=-1!==v?S[v]:null;if(w&&c-w.pts<45e3)b=w.sectionStartPos;else{let e=0;if(null!==h.fileSize){const t=Math.ceil(h.fileSize/f);if(t>1){let i=0,r=t-1;for(e=i;i<=r;){const t=Math.floor((i+r)/2),n=J(t*f,u.packetStride)+k.sectionStartPos,s=n+f,a=yield p(n,s,!1);a?a.pesPacketHeader.pts<=c?(e=t,i=t+1):r=t-1:r=t-1}}}b=J(e*f,u.packetStride)+k.sectionStartPos}const P=yield p(b,null!=(r=h.fileSize)?r:1/0,!1);let I=null!=(n=null==P?void 0:P.pesPacketHeader)?n:null;I||(I=k);const x=this.getReorderSize(),C=(e,t)=>d(this,null,function*(){var r,n;const s=yield u.readSection(e,!0);y(s);const a=Zr(s,!0);y(a);const o=new sn(this.elementaryStream,a),l=new an(this,o);for(;;){if((null!=(n=null==(r=T(l.presentationOrderPackets))?void 0:r.pts)?n:-1/0)>=c)break;if(!(yield l.readNextPacket()))break}const d=V(l.presentationOrderPackets,t);if(-1===d)return null;const h=l.presentationOrderPackets[d],f=0===d?0:h.pts-l.presentationOrderPackets[d-1].pts;for(;l.decodeOrderPackets[0]!==h;)l.decodeOrderPackets.shift();l.lastDuration=f;const m=yield l.readNext();y(m);const p=this.createEncodedPacket(m.packet,m.duration,i);return this.packetBuffers.set(p,l),this.packetSectionStarts.set(p,m.packet.sectionStartPos),p});if(!t||this.allPacketsAreKeyPackets()){e:for(;;){let e=I.sectionStartPos+u.packetStride;for(;;){const t=yield u.readPacketHeader(e);if(!t)break e;if(t.pid===m&&1===t.payloadUnitStartIndicator){const t=yield u.readSection(e,!1);if(t){const e=Jr(t,!1);if(e&&null!==e.pts){if(e.pts>c)break e;I=e,nn(this.elementaryStream,I);break}}}e+=u.packetStride}}e:for(let e=0;e=u.packetOffset;){const t=yield u.readPacketHeader(e);if(!t)break e;if(t.pid===m&&1===t.payloadUnitStartIndicator){const t=yield u.readSection(e,!1);if(t){const e=Jr(t,!1);if(e&&null!==e.pts){I=e;break}}}e-=u.packetStride}}return C(I.sectionStartPos,e=>e.pts<=c)}{let e=b,t=null;const i=!this.elementaryStream.canBeTrustedWithKeyPackets;for(;;){let r=null;const n=e<=k.sectionStartPos;let d,b=null;if(n)d=k,b=g;else{const t=yield p(e,null!=(s=h.fileSize)?s:1/0,i);d=null!=(a=null==t?void 0:t.pesPacketHeader)?a:null,b=null!=(o=null==t?void 0:t.section)?o:null}let T=!1,S=0;e:for(;d&&!(null!==t&&d.sectionStartPos>=t);){if(d.pts<=c){let e;if(this.elementaryStream.canBeTrustedWithKeyPackets)e=1===d.randomAccessIndicator;else{y(b);const t=Zr(b,!0);y(t);const i=new sn(this.elementaryStream,t);yield i.markNextPacket(),e=1===(null==(l=i.suppliedPacket)?void 0:l.randomAccessIndicator)}e&&(r=d)}if(d.pts>c&&(T=!0),T&&(S++,S>x))break;let e=d.sectionStartPos+u.packetStride;for(;;){const t=yield u.readPacketHeader(e);if(!t)break e;if(t.pid===m&&1===t.payloadUnitStartIndicator){const t=yield u.readSection(e,i);if(t){const e=Jr(t,!1);if(e&&null!==e.pts){d=e,b=t,nn(this.elementaryStream,d);break}}}e+=u.packetStride}}if(r){let e=r;if(0===S)e:for(let r=0;r=u.packetOffset;){const r=yield u.readPacketHeader(t);if(!r)break e;if(r.pid===m&&1===r.payloadUnitStartIndicator){const r=yield u.readSection(t,i);if(r){const t=Jr(r,!1);if(t&&null!==t.pts){e=t;break}}}t-=u.packetStride}}const t=yield C(e.sectionStartPos,e=>e.pts<=c&&1===e.randomAccessIndicator);return y(t),t}if(n)return null;t=e,e=Math.max(J(e-k.sectionStartPos-f,u.packetStride)+k.sectionStartPos,k.sectionStartPos)}}})}}class tn extends en{getType(){return"video"}getCodec(){return this.elementaryStream.info.codec}getCodedWidth(){return this.elementaryStream.info.width}getCodedHeight(){return this.elementaryStream.info.height}getSquarePixelWidth(){return this.elementaryStream.info.squarePixelWidth}getSquarePixelHeight(){return this.elementaryStream.info.squarePixelHeight}getRotation(){return 0}getColorSpace(){return d(this,null,function*(){return this.elementaryStream.info.colorSpace})}canBeTransparent(){return d(this,null,function*(){return!1})}getDecoderConfig(){return d(this,null,function*(){return y(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig})}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}}class rn extends en{getType(){return"audio"}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}getDecoderConfig(){return d(this,null,function*(){return y(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig})}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 0}}const nn=(e,t)=>{const i=e.referencePesPackets,r=z(i,t.sectionStartPos,e=>e.sectionStartPos);if(r>=0){const n=i[r];if(t.pts<=n.pts)return!1;const s=e.demuxer.minReferencePointByteDistance;if(t.sectionStartPos-n.sectionStartPos=e?e:this.bufferData(e-t).then(()=>Math.min(this.endPos-this.currentPos,e))}getCurrentPesPacket(){const e=this.pesPackets[this.currentPesPacketIndex];return y(e),e}bufferData(e){return d(this,null,function*(){const t=this.endPos+e;for(;this.endPos=a)break;o=e;const i=n+o;if(o+4>=a){this.seekTo(i);break}const l=s[o+1],c=s[o+2],u=s[o+3];let d=0,h=null;if(0===l&&0===c&&1===u?(d=4,h=s[o+4]):0===l&&1===c&&(d=3,h=u),0===d){o++;continue}const f=i;if(null!==r){if(null!==h){const e="avc"===t?ut(h):Tt(h);if("avc"===t?e===rt.AUD:e===st.AUD_NUT){const e=f-r;return this.seekTo(r),this.supplyPacket(e,0)}}o+=d}else r=f,o+=d}if(e>6,a=63&n[4];if(3===s||a>37){this.seekTo(t+1);continue}const o=Ht[3*a+s];y(void 0!==o),this.seekTo(t),r=this.ensureBuffered(o),r instanceof Promise&&(r=yield r);const l=Math.round(13824e4/e.info.sampleRate);return this.supplyPacket(r,l)}if("eac3"===t){if(11!==i)continue;this.skip(-1);const t=this.currentPos;let r=this.ensureBuffered(5);if(r instanceof Promise&&(r=yield r),r<5)return;const n=this.readBytes(5);if(11!==n[0]||119!==n[1]){this.seekTo(t+1);continue}const s=2*(((7&n[2])<<8|n[3])+1),a=3===n[4]>>6?3:n[4]>>4&3,o=Kt[a];this.seekTo(t),r=this.ensureBuffered(s),r instanceof Promise&&(r=yield r);const l=256*o,c=Math.round(l*Xr/e.info.sampleRate);return this.supplyPacket(r,c)}throw new Error("Unhandled.")}{if(255!==i)continue;this.skip(-1);const t=this.currentPos;let r=this.ensureBuffered(4);if(r instanceof Promise&&(r=yield r),r<4)return;const n=this.readBytes(4),s=P(n).getUint32(0),a=Ye(s,null);if(a.header){this.seekTo(t);let i=this.ensureBuffered(a.header.totalSize);i instanceof Promise&&(i=yield i);const r=a.header.audioSamplesInFrame*Xr/e.info.sampleRate;return this.supplyPacket(i,Math.round(r))}this.seekTo(t+1)}}}if(r=0)}readNext(){return d(this,null,function*(){if(0===this.decodeOrderPackets.length){if(!(yield this.readNextPacket()))return null}yield this.ensureCurrentPacketHasNext();const e=this.decodeOrderPackets[0],t=this.presentationOrderPackets.indexOf(e);let i;if(y(-1!==t),t===this.presentationOrderPackets.length-1)i=this.lastDuration;else{i=this.presentationOrderPackets[t+1].pts-e.pts,this.lastDuration=i}for(this.decodeOrderPackets.shift();this.presentationOrderPackets.length>0;){const e=this.presentationOrderPackets[0];if(this.decodeOrderPackets.includes(e))break;this.presentationOrderPackets.shift()}return{packet:e,duration:i}})}readNextPacket(){return d(this,null,function*(){if(this.reachedEnd)return!1;let e;return this.context.suppliedPacket||(yield this.context.markNextPacket()),e=this.context.suppliedPacket,this.context.suppliedPacket=null,e?(this.decodeOrderPackets.push(e),this.processPacketThroughReorderBuffer(e),!0):(this.reachedEnd=!0,this.flushReorderBuffer(),!1)})}ensureCurrentPacketHasNext(){return d(this,null,function*(){const e=this.decodeOrderPackets[0];for(y(e);;){const t=this.presentationOrderPackets.indexOf(e);if(-1!==t&&t<=this.presentationOrderPackets.length-2)break;if(!(yield this.readNextPacket()))break}})}processPacketThroughReorderBuffer(e){if(this.reorderBuffer.push(e),this.reorderBuffer.length>this.reorderSize){let e=0;for(let i=1;ie.pts-t.pts),this.presentationOrderPackets.push(...this.reorderBuffer),this.reorderBuffer.length=0}}const on="application/vnd.apple.mpegurl",ln="#EXT-X-STREAM-INF:",cn="#EXT-X-I-FRAME-STREAM-INF:",un="#EXT-X-MEDIA:",dn="#EXTINF:",hn="#EXT-X-MAP:",fn="#EXT-X-KEY:",mn="#EXT-X-MEDIA-SEQUENCE:",pn="#EXT-X-BYTERANGE:",gn="#EXT-X-PROGRAM-DATE-TIME:",kn="#EXT-X-TARGETDURATION:",yn="#EXT-X-PLAYLIST-TYPE:",bn=e=>0===e.length||e.startsWith("#")&&!e.startsWith("#EXT");class Tn{constructor(e){this._attributes={};let t="",i="",r=!1,n=!1;for(let s=0;sd(this,null,function*(){const e=[];if(this.trackDeclarations){for(const t of this.trackDeclarations)if("video"===t.type){const i=Te(e,e=>"video"===e.getType())+1;e.push(new wn(this,t,i))}else if("audio"===t.type){const i=Te(e,e=>"audio"===e.getType())+1;e.push(new Pn(this,t,i))}}else{if(this.firstSegment=yield this.getFirstSegment({}),!this.firstSegment)return[];const t=this.getInputForSegment(this.firstSegment),i=yield t.getTracks();for(const r of i)if("video"===r.type){const t=Te(e,e=>"video"===e.getType())+1;e.push(new wn(this,{id:e.length+1,type:"video"},t))}else if("audio"===r.type){const t=Te(e,e=>"audio"===e.getType())+1;e.push(new Pn(this,{id:e.length+1,type:"audio"},t))}}return e}))()})}getFirstTimestampForInput(e){return d(this,null,function*(){const t=this.firstTimestampCache.get(e);if(void 0!==t)return t;const i=yield e.getFirstTimestamp();return this.firstTimestampCache.set(e,i),i})}getMediaOffset(e,t){return d(this,null,function*(){var i;const r=null!=(i=e.firstSegment)?i:e;let n;if(this.firstSegmentFirstTimestamps.has(r))n=this.firstSegmentFirstTimestamps.get(r);else{const e=this.getInputForSegment(r);n=yield this.getFirstTimestampForInput(e),this.firstSegmentFirstTimestamps.set(r,n)}if(r===e)return r.timestamp-n;const s=yield this.getFirstTimestampForInput(t),a=e.timestamp-r.timestamp,o=s-n-a;return Math.abs(o)<=Math.min(.25,a)?r.timestamp-n:e.timestamp-s})}dispose(){for(const e of this.inputCache)e.input.dispose();this.inputCache.length=0}}class vn{constructor(e,t,i){this.packetInfos=new WeakMap,this.hydrationPromise=null,this.firstInputTrack=null,this.segmentedInput=e,this.decl=t,this.number=i}hydrate(){var e;return null!=(e=this.hydrationPromise)?e:this.hydrationPromise=(()=>d(this,null,function*(){var e;if(null!=(e=this.segmentedInput).firstSegment||(e.firstSegment=yield this.segmentedInput.getFirstSegment({})),!this.segmentedInput.firstSegment)throw new Error("Missing first segment, can't retrieve track.");const t=this.segmentedInput.getInputForSegment(this.segmentedInput.firstSegment),i=(yield t.getTracks()).find(e=>e.type===this.decl.type&&e.number===this.number);if(!i)throw new Error("No matching track found in underlying media data.");this.firstInputTrack=i}))()}getId(){return this.decl.id}getType(){return this.decl.type}getNumber(){return this.number}delegate(e){return this.firstInputTrack?e():this.hydrate().then(e)}getDecoderConfig(){return d(this,null,function*(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())})}getHasOnlyKeyPackets(){return this.delegate(()=>{var e,t,i;return null!=(i=null==(t=(e=this.firstInputTrack._backing).getHasOnlyKeyPackets)?void 0:t.call(e))?i:null})}getPairingMask(){return BigInt("1")}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getInternalCodecId(){return this.delegate(()=>this.firstInputTrack._backing.getInternalCodecId())}getDisposition(){return this.delegate(()=>this.firstInputTrack._backing.getDisposition())}getLanguageCode(){return this.delegate(()=>this.firstInputTrack._backing.getLanguageCode())}getName(){return this.delegate(()=>this.firstInputTrack._backing.getName())}getTimeResolution(){return this.delegate(()=>this.firstInputTrack._backing.getTimeResolution())}isRelativeToUnixEpoch(){return d(this,null,function*(){return yield this.hydrate(),y(this.segmentedInput.firstSegment),this.segmentedInput.firstSegment.relativeToUnixEpoch})}getBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getBitrate())}getAverageBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getAverageBitrate())}getDurationFromMetadata(e){return this.segmentedInput.getDurationFromMetadata(e)}getLiveRefreshInterval(){return this.segmentedInput.getLiveRefreshInterval()}createAdjustedPacket(e,t,i){return d(this,null,function*(){y(e.sequenceNumber>=0),y(this.segmentedInput.firstSegment);const r=yield this.segmentedInput.getMediaOffset(t,i.input),n=t.timestamp-this.segmentedInput.firstSegment.timestamp,s=e.clone({timestamp:Y(e.timestamp+r,yield i.getTimeResolution()),sequenceNumber:Math.floor(1e8*n)+e.sequenceNumber});return this.packetInfos.set(s,{segment:t,track:i,sourcePacket:e}),s})}getFirstPacket(e){return d(this,null,function*(){yield this.hydrate(),y(this.segmentedInput.firstSegment),y(this.firstInputTrack);const t=yield this.firstInputTrack._backing.getFirstPacket(e);return t?this.createAdjustedPacket(t,this.segmentedInput.firstSegment,this.firstInputTrack):null})}getNextPacket(e,t){return this._getNextInternal(e,t,!1)}getNextKeyPacket(e,t){return this._getNextInternal(e,t,!0)}_getNextInternal(e,t,i){return d(this,null,function*(){const r=this.packetInfos.get(e);if(!r)throw new Error("Packet was not created from this track.");const n=i?yield r.track._backing.getNextKeyPacket(r.sourcePacket,t):yield r.track._backing.getNextPacket(r.sourcePacket,t);if(n)return this.createAdjustedPacket(n,r.segment,r.track);let s=r.segment;for(;;){const e=yield this.segmentedInput.getNextSegment(s,{skipLiveWait:t.skipLiveWait});if(!e)return null;const i=this.segmentedInput.getInputForSegment(e),n=(yield i.getTracks()).find(e=>e.type===r.track.type&&e.number===r.track.number);if(!n){s=e;continue}const a=yield n._backing.getFirstPacket(t);return a?this.createAdjustedPacket(a,e,n):null}})}getPacket(e,t){return this._getPacketInternal(e,t,!1)}getKeyPacket(e,t){return this._getPacketInternal(e,t,!0)}_getPacketInternal(e,t,i){return d(this,null,function*(){let r=yield this.segmentedInput.getSegmentAt(e,{skipLiveWait:t.skipLiveWait});if(!r)return null;for(yield this.hydrate();r;){const n=this.segmentedInput.getInputForSegment(r),s=(yield n.getTracks()).find(e=>e.type===this.firstInputTrack.type&&e.number===this.firstInputTrack.number);if(!s){r=yield this.segmentedInput.getPreviousSegment(r,{skipLiveWait:t.skipLiveWait});continue}const a=yield this.segmentedInput.getMediaOffset(r,n),o=e-a,l=i?yield s._backing.getKeyPacket(o,t):yield s._backing.getPacket(o,t);if(l)return this.createAdjustedPacket(l,r,s);r=yield this.segmentedInput.getPreviousSegment(r,{skipLiveWait:t.skipLiveWait})}return null})}}class wn extends vn{getType(){return"video"}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getCodedWidth(){return this.delegate(()=>this.firstInputTrack._backing.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.firstInputTrack._backing.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.firstInputTrack._backing.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.firstInputTrack._backing.getSquarePixelHeight())}getRotation(){return this.delegate(()=>this.firstInputTrack._backing.getRotation())}getColorSpace(){return d(this,null,function*(){return this.delegate(()=>this.firstInputTrack._backing.getColorSpace())})}canBeTransparent(){return d(this,null,function*(){return this.delegate(()=>this.firstInputTrack._backing.canBeTransparent())})}getDecoderConfig(){return d(this,null,function*(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())})}}class Pn extends vn{getType(){return"audio"}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getNumberOfChannels(){return this.delegate(()=>this.firstInputTrack._backing.getNumberOfChannels())}getSampleRate(){return this.delegate(()=>this.firstInputTrack._backing.getSampleRate())}getDecoderConfig(){return d(this,null,function*(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())})}}ke();const In=1/0;class xn extends Ie{constructor(){super(...arguments),this._disposed=!1,this._refCount=0,this._usedForHls=!1,this._sizePromise=null,this.onread=null}getSizeOrNull(){return d(this,null,function*(){var e;if(this._disposed)throw new va;return null!=(e=this._sizePromise)?e:this._sizePromise=(()=>d(this,null,function*(){let e=this._getFileSize();return void 0!==e||(yield this._read(0,1,0,In),e=this._getFileSize(),y(void 0!==e)),e}))()})}getSize(){return d(this,null,function*(){if(this._disposed)throw new va;const e=yield this.getSizeOrNull();if(null===e)throw new Error("Cannot determine the size of an unsized source.");return e})}slice(e,t){if(!Number.isInteger(e)||e<0)throw new TypeError("offset must be a non-negative integer.");if(void 0!==t&&(!Number.isInteger(t)||t<0))throw new TypeError("length, when provided, must be a non-negative integer.");return new zn(this,e,t)}_dispatchRead(e,t){var i;null==(i=this.onread)||i.call(this,e,t),this._emit("read",{start:e,end:t})}ref(){return new Cn(this)}}class Cn{constructor(e){if(this._freed=!1,e._disposed)throw new Error("Cannot ref a disposed source.");e._refCount++,this._source=e}get source(){if(!this._source)throw new Error("Can't get source; ref has already been freed.");return this._source}get freed(){return this._freed}free(){if(this._freed)throw new Error("Illegal operation: double free on SourceRef.");const e=this.source;y(e._refCount>0),e._refCount--,0===e._refCount&&(e._dispose(),e._disposed=!0),this._freed=!0,this._source=null}[Symbol.dispose](){this.freed||this.free()}}class Bn extends xn{constructor(e,t){if("string"!==typeof e)throw new TypeError("rootPath must be a string.");if("function"!==typeof t)throw new TypeError("requestHandler must be a function.");super(),this.rootPath=e,this.requestHandler=t}_resolveRequest(e){const t=this.requestHandler(e),i=e=>{var t;if(!(e instanceof xn||e instanceof Cn))throw new TypeError("requestHandler must return or resolve to a Source or SourceRef.");const i=e instanceof xn?e.ref():e;return(t=i.source)._usedForHls||(t._usedForHls=this._usedForHls),i};return t instanceof Promise?t.then(i):i(t)}}const En=(e,t)=>e.path===t.path;class _n extends Bn{constructor(){super(...arguments),this._root=null,this._rootRequest=null}_read(e,t,i,r){if(!this._root){if(!this._rootRequest){const e=this._resolveRequest({path:this.rootPath,isRoot:!0}),t=e=>{const t=e instanceof xn?e.ref():e;return this._root=t,this._rootRequest=null,t};e instanceof Promise?this._rootRequest=e.then(t):(t(e),y(this._root))}if(this._rootRequest)return this._rootRequest.then(n=>n.source._read(e,t,i,r))}return this._root.source._read(e,t,i,r)}_getFileSize(){if(this._root)return this._root.source._getFileSize()}_dispose(){this._root?this._root.free():this._rootRequest&&this._rootRequest.then(e=>e.free())}}class An extends xn{constructor(e,t={}){var i;if(!(e instanceof Blob))throw new TypeError("blob must be a Blob.");if(!t||"object"!==typeof t)throw new TypeError("options must be an object.");if(void 0!==t.maxCacheSize&&(!ye(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");super(),this._readers=new WeakMap,this._blob=e,this._orchestrator=new Ln({maxCacheSize:null!=(i=t.maxCacheSize)?i:8*o(2,20),maxWorkerCount:4,runWorker:this._runWorker.bind(this),prefetchProfile:On.fileSystem}),this._orchestrator.fileSize=e.size}_getFileSize(){return this._orchestrator.fileSize}_read(e,t,i,r){return this._orchestrator.read(e,t,i,r)}_runWorker(e){return d(this,null,function*(){y(e.strictTarget);let t=this._readers.get(e);if(void 0===t){if("stream"in this._blob&&!oe()){t=this._blob.slice(e.currentPos).stream().getReader()}else t=null;this._readers.set(e,t)}for(;e.currentPos{if(t instanceof Error&&(t.message.includes("Failed to fetch")||t.message.includes("Load failed")||t.message.includes("NetworkError when attempting to fetch resource"))){let e=null;try{"undefined"!==typeof window&&"undefined"!==typeof window.location&&(e=new URL(i instanceof Request?i.url:i,window.location.href).origin)}catch(r){}if(("undefined"===typeof navigator||"boolean"!==typeof navigator.onLine||navigator.onLine)&&null!==e&&e!==window.location.origin)return console.warn("Request will not be retried because a CORS error was suspected due to different origins. You can modify this behavior by providing your own function for the 'getRetryDelay' option."),null}return Math.min(o(2,e-2),16)},Dn=new Set;class Mn extends Bn{constructor(e,t={}){var i,r,n;if("string"!==typeof e&&!(e instanceof URL)&&!("undefined"!==typeof Request&&e instanceof Request))throw new TypeError("url must be a string, URL or Request.");if(!t||"object"!==typeof t)throw new TypeError("options must be an object.");if(void 0!==t.requestInit&&(!t.requestInit||"object"!==typeof t.requestInit))throw new TypeError("options.requestInit, when provided, must be an object.");if(void 0!==t.getRetryDelay&&"function"!==typeof t.getRetryDelay)throw new TypeError("options.getRetryDelay, when provided, must be a function.");if(void 0!==t.maxCacheSize&&(!ye(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(void 0!==t.parallelism&&(!Number.isInteger(t.parallelism)||t.parallelism<1))throw new TypeError("options.parallelism, when provided, must be a positive number.");if(void 0!==t.fetchFn&&"function"!==typeof t.fetchFn)throw new TypeError("options.fetchFn, when provided, must be a function.");super(e instanceof Request?e.url:e instanceof URL?e.href:e,e=>new Mn(e.path,this._options)),this._fileSizeDetermined=!1,this._url=e,this._options=t,this._getRetryDelay=null!=(i=t.getRetryDelay)?i:Rn;this._orchestrator=new Ln({maxCacheSize:null!=(r=t.maxCacheSize)?r:64*o(2,20),maxWorkerCount:null!=(n=t.parallelism)?n:2,runWorker:this._runWorker.bind(this),prefetchProfile:On.network})}_getFileSize(){return this._fileSizeDetermined?this._orchestrator.fileSize:void 0}_read(e,t,i,r){return this._orchestrator.read(e,t,i,r)}_runWorker(e){return d(this,null,function*(){for(var t,i;;){const n=new AbortController,s=yield ne(null!=(t=this._options.fetchFn)?t:fetch,this._url,ie(null!=(i=this._options.requestInit)?i:{},{headers:{Range:`bytes=${e.currentPos}-`},signal:n.signal}),this._getRetryDelay,()=>this._disposed);if(!s.ok)throw new Error(`Error fetching ${String(this._url)}: ${s.status} ${s.statusText}`);e:if(null===this._orchestrator.fileSize){const t=s.headers.get("Content-Range");if(t){const e=/\/(\d+)/.exec(t);if(e){this._orchestrator.supplyFileSize(Number(e[1]));break e}}const i=s.headers.get("Content-Length");i&&this._orchestrator.supplyFileSize(e.currentPos+Number(i))}if(this._fileSizeDetermined=!0,206!==s.status){if(!this._usedForHls){const e=new URL(this._url instanceof Request?this._url.url:this._url,"undefined"!==typeof window?window.location.href:void 0);"null"===e.origin||e.pathname.endsWith(".m3u8")||e.pathname.endsWith(".m3u")||Dn.has(e.origin)||(console.log(this._usedForHls,this._url,e.pathname),console.warn(`HTTP server (origin ${e.origin}) did not respond to a range request with 206 Partial Content, meaning the entire resource will now be downloaded. To enable efficient media file streaming across a network, please make sure your server supports range requests.`),Dn.add(e.origin))}e.currentPos=0,this._orchestrator.options.maxCacheSize=1/0,null!==this._orchestrator.fileSize?e.targetPos=this._orchestrator.fileSize:(e.targetPos=1/0,e.strictTarget=!1),this._orchestrator.consolidateEverythingIntoOneWorker(e)}if(!s.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");const a=s.body.getReader();for(;;){if(e.currentPos>=e.targetPos||e.aborted)return n.abort(),void this._orchestrator.signalWorkerStoppedRunning(e);let t;try{t=yield a.read()}catch(r){if(this._disposed)throw r;const e=this._getRetryDelay(1,r,this._url);if(null!==e){console.error("Error while reading response stream. Attempting to resume.",r),yield Pe(1e3*e);break}throw r}if(e.aborted)continue;const{done:i,value:s}=t;if(i){if(e.currentPos>=e.targetPos)return void this._orchestrator.onWorkerFinished(e);if(e.strictTarget)break;return void this._orchestrator.onWorkerFinished(e)}this._dispatchRead(e.currentPos,e.currentPos+s.length),this._orchestrator.supplyWorkerData(e,s)}}})}_dispose(){this._orchestrator.dispose()}}class Nn extends xn{constructor(e,t={}){var i;if(!(e instanceof ReadableStream))throw new TypeError("stream must be a ReadableStream.");if(!t||"object"!==typeof t)throw new TypeError("options must be an object.");if(void 0!==t.maxCacheSize&&(!ye(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");super(),this._reader=null,this._cache=[],this._pendingSlices=[],this._currentIndex=0,this._targetIndex=0,this._maxRequestedIndex=0,this._endIndex=null,this._pulling=!1,this._stream=e,this._maxCacheSize=null!=(i=t.maxCacheSize)?i:16*o(2,20)}_getFileSize(){return this._endIndex}_read(e,t){if(null!==this._endIndex&&t>this._endIndex)return null;this._maxRequestedIndex=Math.max(this._maxRequestedIndex,t);const i=z(this._cache,e,e=>e.start),r=-1!==i?this._cache[i]:null;if(r&&r.start<=e&&t<=r.end)return{bytes:r.bytes,view:r.view,offset:r.start};let n=e;const s=new Uint8Array(t-e);if(-1!==i)for(let c=i;c=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}=q();return this._pendingSlices.push({start:e,end:t,bytes:s,resolve:o,reject:l}),this._targetIndex=Math.max(this._targetIndex,t),this._pulling||(this._pulling=!0,this._pull().catch(e=>{if(this._pulling=!1,!(this._pendingSlices.length>0))throw e;this._pendingSlices.forEach(t=>t.reject(e)),this._pendingSlices.length=0})),a}_throwDueToCacheMiss(){throw new Error("Read is before the cached region. With ReadableStreamSource, you must access the data more sequentially or increase the size of its cache.")}_pull(){return d(this,null,function*(){for(null!=this._reader||(this._reader=this._stream.getReader());this._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;this._pendingSlices.length=0,this._cache.length=0,null==(e=this._reader)||e.cancel()}}const On={fileSystem:(e,t)=>{const i=o(2,16);return{start:e=Math.floor((e-i)/i)*i,end:t=Math.ceil((t+i)/i)*i}},network:(e,t,i)=>{const r=o(2,16);e=Math.max(0,Math.floor((e-r)/r)*r);for(const n of i){const i=8*o(2,20),r=Math.max((n.startPos+n.targetPos)/2,n.targetPos-i);if(pe(e,t,r,n.targetPos)){const e=n.targetPos-n.startPos,r=Math.ceil((e+1)/i)*i,s=o(2,Math.ceil(Math.log2(e+1))),a=Math.min(s,r);t=Math.max(t,n.startPos+a)}}return{start:e,end:t=Math.max(t,e+Fn)}}};class Ln{constructor(e){this.options=e,this.fileSize=null,this.nextAge=0,this.workers=[],this.cache=[],this.currentCacheSize=0,this.disposed=!1,this.queuedReads=[]}read(e,t,i,r){var n;y(!this.disposed);const s=this.options.prefetchProfile(e,t,this.workers),a=Math.max(s.start,i),o=Math.min(s.end,null!=(n=this.fileSize)?n:1/0,r);y(a<=e&&t<=o);let l=null;const c=z(this.cache,e,e=>e.start),u=-1!==c?this.cache[c]:null;u&&u.start<=e&&t<=u.end&&(u.age=this.nextAge++,l={bytes:u.bytes,view:u.view,offset:u.start});const d=z(this.cache,a,e=>e.start),h=l?null:new Uint8Array(t-e);let f=0,m=a;const p=[];if(-1!==d){for(let i=d;i=o)break;if(r.end<=a)continue;const n=Math.max(a,r.start),s=Math.min(o,r.end);if(y(n<=s),m=h.length&&(l={bytes:h,view:P(h),offset:e}),0===p.length)return y(l),l;const{promise:g,resolve:k,reject:b}=q(),T=[];for(const y of p){const i=Math.max(e,y.start),r=Math.min(t,y.end);i===y.start&&r===y.end?T.push(y):ie.hole.start),i=-1!==t?this.queuedReads[t]:null;for(i&&y.start<=i.hole.end?(i.hole.end=Math.max(i.hole.end,y.end),i.strictTarget&&(i.strictTarget=e),S&&i.pendingSlices.push(S)):(t++,i={hole:{start:y.start,end:y.end},strictTarget:e,pendingSlices:S?[S]:[],age:this.nextAge++},this.queuedReads.splice(t,0,i));t+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||(y(h),l=g.then(t=>t&&{bytes:t,view:P(t),offset:e})),l}checkHoleAgainstWorker(e,t,i){const r=o(2,17);if(pe(t.start-r,t.start,e.currentPos,e.targetPos)){e.targetPos=Math.max(e.targetPos,t.end);for(let t=0;t=this.options.maxWorkerCount){let e=null,t=null;for(let i=0;i{if(e.running=!1,!(e.pendingSlices.length>0))throw t;e.pendingSlices.forEach(e=>e.reject(t)),e.pendingSlices.length=0}).finally(()=>{if(!e.running&&this.queuedReads.length>0){let e=0;for(let r=1;re.targetPos&&(e.targetPos=e.currentPos,this.checkQueuedReadsAgainstWorker(e));for(let n=0;nt.start&&(t.start=r),t.end<=t.start&&(s.holes.splice(e,1),e--)}0===s.holes.length&&(s.resolve(s.bytes),e.pendingSlices.splice(n,1),n--)}for(let n=0;ne){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.pendingSlices.length=0}onWorkerFinished(e){const t=this.workers.indexOf(e);y(-1!==t),e.running=!1,this.workers.splice(t,1),null===this.fileSize&&this.supplyFileSize(e.currentPos);for(const i of e.pendingSlices)i.resolve(null)}insertIntoCache(e){if(0===this.options.maxCacheSize)return;let t=z(this.cache,e.start,e=>e.start)+1;if(t>0){const i=this.cache[t-1];if(i.end>=e.end)return;if(i.end>e.start){const r=new Uint8Array(e.end-i.start);r.set(i.bytes,0),r.set(e.bytes,e.start-i.start),this.currentCacheSize+=e.end-i.end,i.bytes=r,i.view=P(r),i.end=e.end,t--,e=i}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length;for(let i=t+1;i=t.end){this.cache.splice(i,1),this.currentCacheSize-=t.bytes.length,i--;continue}const r=new Uint8Array(t.end-e.start);r.set(e.bytes,0),r.set(t.bytes,t.start-e.start),this.currentCacheSize-=e.end-t.start,e.bytes=r,e.view=P(r),e.end=t.end,this.cache.splice(i,1);break}for(;this.currentCacheSize>this.options.maxCacheSize;){let e=0,t=this.cache[0];for(let i=1;ithis._length)return null;const n=this._baseSource._read(this._offset+e,this._offset+t,this._offset+i,this._offset+r);return n instanceof Promise?n.then(e=>e?(e.offset-=this._offset,e):null):n?(n.offset-=this._offset,n):null}_dispose(){var e;null==(e=this._ref)||e.free()}ref(){return null!=this._ref||(this._ref=this._baseSource.ref()),super.ref()}}var Un=function(e,t,i){if(null!==t&&void 0!==t){if("object"!==typeof t&&"function"!==typeof t)throw new TypeError("Object expected.");var r,n;if(i){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");r=t[Symbol.asyncDispose]}if(void 0===r){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");r=t[Symbol.dispose],i&&(n=r)}if("function"!==typeof r)throw new TypeError("Object not disposable.");n&&(r=function(){try{n.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:r,async:i})}else i&&e.stack.push({async:!0});return t},qn=function(e){return function(t){function i(i){t.error=t.hasError?new e(i,t.error,"An error was suppressed during disposal."):i,t.hasError=!0}var r,n=0;return function e(){for(;r=t.stack.pop();)try{if(!r.async&&1===n)return n=0,t.stack.push(r),Promise.resolve().then(e);if(r.dispose){var s=r.dispose.call(r.value);if(r.async)return n|=2,Promise.resolve(s).then(e,function(t){return i(t),e()})}else n|=1}catch(a){i(a)}if(1===n)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"===typeof SuppressedError?SuppressedError:function(e,t,i){var r=new Error(i);return r.name="SuppressedError",r.error=e,r.suppressed=t,r});const Wn=/^0[xX][0-9a-fA-F]+$/,Vn=/^data:.*;base64,/i;class Hn extends Sn{constructor(e,t,i,r){super(e.input,t,i),this.segments=[],this.nextLines=null,this.currentUpdateSegmentsPromise=null,this.streamHasEnded=!1,this.lastSegmentUpdateTime=-1/0,this.refreshInterval=5,this.demuxer=e,this.nextLines=r}runUpdateSegments(){var e;return null!=(e=this.currentUpdateSegmentsPromise)?e:this.currentUpdateSegmentsPromise=(()=>d(this,null,function*(){try{const e=this.getRemainingWaitTimeMs();e>0&&(yield Pe(e)),this.lastSegmentUpdateTime=performance.now(),yield this.updateSegments()}finally{this.currentUpdateSegmentsPromise=null}}))()}getRemainingWaitTimeMs(){const e=performance.now()-this.lastSegmentUpdateTime,t=Math.max(0,1e3*this.refreshInterval-e);return t<=50?0:t}updateSegments(){return d(this,null,function*(){var e,t,i,r,n,s,a;let l=this.nextLines;if(this.nextLines=null,!l){const e={stack:[],error:void 0,hasError:!1};try{const t=Un(e,yield this.demuxer.input._getSourceUncached({path:this.path,isRoot:!1}),!1),i=new wa(t.source),r=yield i.requestEntireFile();y(r),l=Va(r,r.length,{ignore:bn})}catch(E){e.error=E,e.hasError=!0}finally{qn(e)}}let d=!1,h=0,f=null,m=null,p=0,g=null,k=null,b=null,S=null,v=null,w=null,I=!1,x=null!=(e=T(this.segments))?e:null;const C=e=>{const t=e.indexOf("@"),i=Number(-1===t?e:e.slice(0,t));if(!Number.isInteger(i)||i<0)throw new Error(`Invalid #EXT-X-BYTERANGE length '${e}'.`);let r=null;if(-1!==t&&(r=Number(e.slice(t+1)),!Number.isInteger(r)||r<0))throw new Error(`Invalid #EXT-X-BYTERANGE offset '${e}'.`);return{length:i,offset:r}},B=e=>{p=e,x&&(y(null!==x.sequenceNumber),x.sequenceNumber0&&null!==w&&(h=p*w),I=!0);const t=e.slice(8),i=t.indexOf(","),r=-1===i?t:t.slice(0,i),n=Number(r);if(!Number.isFinite(n)||n<0)throw new Error(`Invalid #EXTINF tag duration '${r}'.`);f=n}else if(e.startsWith(hn)){const t=new Tn(e.slice(11)),i=t.get("uri");if(!i)throw new Error("Invalid #EXT-X-MAP tag; missing URI attribute.");const s=t.get("byterange");let a=null;if(null!==s&&(a=C(s)),a&&null===a.offset)throw new Error("Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset.");if(!x){const e={path:be(this.path,i),offset:null!=(r=null==a?void 0:a.offset)?r:0,length:null!=(n=null==a?void 0:a.length)?n:null};if("AES-128"===(null==m?void 0:m.method)&&!m.iv)throw new Error("IV attribute must be set on #EXT-X-KEY tag preceding the #EXT-X-MAP tag.");k={timestamp:h,relativeToUnixEpoch:null!==v,firstSegment:null,sequenceNumber:null,location:e,duration:0,encryption:m,initSegment:null,lastProgramDateTimeSeconds:v}}f=null,null===S?b=null:S=null}else if(e.startsWith(fn)){const t=new Tn(e.slice(11)),i=t.get("method");if("NONE"===i)m=null;else if("AES-128"===i){const e=t.get("uri");if(!e)throw new Error("Invalid #EXT-X-KEY: AES-128 requires a URI attribute.");let i=null;const r=t.get("iv");if(r){if(!Wn.test(r))throw new Error(`Unsupported IV format '${r}'.`);let e=r.slice(2);e=e.padStart(32,"0"),i=new Uint8Array(ai);for(let t=0;t=8&&112===i[4]&&115===i[5]&&115===i[6]&&104===i[7]){const e=P(i).getUint32(0);r=Jt(i.subarray(8,Math.min(e,i.length)))}}m={method:i,psshBox:r}}}}else if(e.startsWith(mn)){const t=e.slice(22),i=Number(t);if(!Number.isInteger(i)||i<0)throw new Error(`Invalid EXT-X-MEDIA-SEQUENCE value '${t}'.`);B(i)}else if(e.startsWith(pn)){const t=C(e.slice(17));if(null===t.offset){if(null===b)throw new Error("Invalid M3U8 file; #EXT-X-BYTERANGE without offset requires a previous byte range.");t.offset=b}S=t,b=t.offset+t.length}else if(e.startsWith(gn)){if(x)continue;const t=e.slice(25),i=Date.parse(t);if(!Number.isFinite(i))continue;const r=i/1e3;if(v===r)continue;if(null===v&&this.segments.length>0){const e=T(this.segments),t=r-(e.timestamp+e.duration);for(const i of this.segments)i.timestamp+=t,i.relativeToUnixEpoch=!0;h+=t}v=r,h=r}else if("#EXT-X-DISCONTINUITY"===e)g=null;else if(e.startsWith(kn)){const t=e.slice(22),i=Number(t);if(!Number.isFinite(i)||i<0)throw new Error(`Invalid EXT-X-TARGETDURATION value '${t}'.`);this.refreshInterval=i,w=i}else{if("#EXT-X-ENDLIST"===e){this.streamHasEnded=!0;break}if(e.startsWith(yn)){"vod"===e.slice(21).toLowerCase()&&(this.streamHasEnded=!0)}}}else{if("#EXTM3U"!==e)throw new Error("Invalid M3U8 file; expected first line to be #EXTM3U.");d=!0}}if(!d)throw new Error("Invalid M3U8 file; no #EXTM3U header.")})}getFirstSegment(){return d(this,null,function*(){var e;return 0===this.segments.length&&(yield this.runUpdateSegments()),null!=(e=this.segments[0])?e:null})}getSegmentAt(e,t){return d(this,null,function*(){0===this.segments.length&&(yield this.runUpdateSegments());let i=!!t.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){const r=z(this.segments,e,e=>e.timestamp);if(-1===r)return null;if(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=u(c({},this.input._formatOptions),{isobmff:u(c({},this.input._formatOptions.isobmff),{resolveKeyId:(null==(i=this.input._formatOptions.isobmff)?void 0:i.resolveKeyId)&&(e=>{if(!r.encryption||"SAMPLE-AES"!==r.encryption.method&&"SAMPLE-AES-CTR"!==r.encryption.method||!r.encryption.psshBox)return this.input._formatOptions.isobmff.resolveKeyId(e);let t=e.psshBoxes;const{psshBox:i}=r.encryption;return null!==i.keyIds&&!i.keyIds.includes(e.keyId)||t.some(e=>Zt(e,i))||(t=[...t,i]),this.input._formatOptions.isobmff.resolveKeyId(u(c({},e),{psshBoxes:t}))})})}),l=new Ta({source:new _n(r.location.path,e=>d(this,null,function*(){var t,i;y(e.isRoot);const n=u(c({},e),{isRoot:!1});let s;const a=r.location.offset>0||null!==r.location.length;if(r.encryption&&"SAMPLE-AES"!==r.encryption.method&&"SAMPLE-AES-CTR"!==r.encryption.method)if("AES-128"===r.encryption.method){const e=r.encryption;y(e.iv);let t=yield this.input._getSourceCached(n);if(a){const e=t.source.slice(r.location.offset,null!=(i=r.location.length)?i:void 0).ref();t.free(),t=e}const l=((e,t,i)=>{let r=!1,n=0;const s=o(2,16),a=new pi;return new ReadableStream({pull:o=>d(null,null,function*(){r||(a.init(yield t()),r=!0);const l=s+16;let c=e.requestSliceRange(n,0,l);if(c instanceof Promise&&(c=yield c),!c||0===c.length)throw new Error("Invalid ciphertext.");const u=c.length;if(u%16!==0)throw new Error("Invalid ciphertext.");const d=u===l?u-16:u,h=xa(c,d),f=new Uint8Array(d);for(let e=0;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 wa(t.source),()=>d(this,null,function*(){const t={stack:[],error:void 0,hasError:!1};try{const i=Un(t,yield this.input._getSourceCached({path:e.keyUri,isRoot:!1},ya),!1),r=new wa(i.source),n=yield r.requestSlice(0,ai);if(!n)throw new Error("Invalid AES-128 key; expected at least 16 bytes of data.");return{key:xa(n,ai),iv:e.iv}}catch(i){t.error=i,t.hasError=!0}finally{qn(t)}}),()=>{t.free()});s=new Nn(l).ref()}else y(!1);else if(s=yield this.input._getSourceCached(n),a){const e=s.source.slice(r.location.offset,null!=(t=r.location.length)?t:void 0).ref();s.free(),s=e}return s})),formats:this.input._formats.filter(e=>!(e instanceof us)),initInput:null!=s?s:void 0,formatOptions:a});l._onFormatDetermined=e=>{var t,i;if(("SAMPLE-AES"===(null==(t=r.encryption)?void 0:t.method)||"SAMPLE-AES-CTR"===(null==(i=r.encryption)?void 0:i.method))&&!e._isIsobmff)throw new Error("The SAMPLE-AES and SAMPLE-AES-CTR encryption methods are currently only supported for ISOBMFF files.")},this.inputCache.push({segment:r,input:l,age:this.nextInputCacheAge++});if(this.inputCache.length>4){const e=Se(this.inputCache,e=>e.age);y(-1!==e),this.inputCache.splice(e,1)}return l}getLiveRefreshInterval(){return d(this,null,function*(){return 0===this.getRemainingWaitTimeMs()&&(yield this.runUpdateSegments()),this.streamHasEnded?null:this.refreshInterval})}}class Kn extends Qt{constructor(e){super(e),this.metadataPromise=null,this.trackBackings=null,this.internalTracks=null,this.segmentedInputs=[],this.hasMasterPlaylist=!0}readMetadata(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>d(this,null,function*(){y(this.input._rootSource instanceof Bn);const{rootPath:e}=this.input._rootSource,t=yield this.input._reader.requestEntireFile();y(t);const i=Va(t,t.length,{ignore:bn}),r=[],n=[];for(let u=1;u"video"===e.attributes.get("type").toLowerCase()).map(e=>e.attributes.get("group-id")))],a=[...new Set(n.filter(e=>"audio"===e.attributes.get("type").toLowerCase()).map(e=>e.attributes.get("group-id")))],o=yield Promise.all(r.map((t,i)=>d(this,null,function*(){var r,o,l,c;const u=[],h=t.attributes.get("codecs");let f;if(h)f=h.split(",").map(e=>e.trim());else{const e=this.getSegmentedInputForPath(t.fullPath),i=yield e.getTrackBackings(),r=yield Promise.all(i.map(e=>d(this,null,function*(){return{track:e,codec:yield e.getCodec()}})));f=yield Promise.all(r.filter(e=>null!==e.codec).map(e=>e.track.getDecoderConfig().then(e=>e.codec)))}const m=t.attributes.get("video"),p=t.attributes.get("audio"),g=f.some(e=>Re.includes(Ke(e))),k=f.some(e=>Me.includes(Ke(e)));if(null!==m&&!g){if(!s.includes(m))throw new Error(`Invalid M3U8 file; variant stream references video group "${m}" which is not defined in any #EXT-X-MEDIA tags.`);const t=n.find(e=>{const t=e.attributes.get("group-id"),i=e.attributes.get("type");return t===m&&"video"===i.toLowerCase()});e:if(t){const i=t.attributes.get("uri");if(null===i)break e;const r=be(e,i),n=this.getSegmentedInputForPath(r),s=(yield n.getTrackBackings()).find(e=>"video"===e.getType());if(!s||null===(yield s.getCodec()))break e;const a=yield s.getDecoderConfig().then(e=>{var t;return null!=(t=null==e?void 0:e.codec)?t:null});y(null!==a),f.push(a)}}if(null!==p&&!k){if(!a.includes(p))throw new Error(`Invalid M3U8 file; variant stream references audio group "${p}" which is not defined in any #EXT-X-MEDIA tags.`);const t=n.find(e=>{const t=e.attributes.get("group-id"),i=e.attributes.get("type");return t===p&&"audio"===i.toLowerCase()});e:if(t){const i=t.attributes.get("uri");if(null===i)break e;const r=be(e,i),n=this.getSegmentedInputForPath(r),s=(yield n.getTrackBackings()).find(e=>"audio"===e.getType());if(!s||null===(yield s.getCodec()))break e;const a=yield s.getDecoderConfig().then(e=>{var t;return null!=(t=null==e?void 0:e.codec)?t:null});y(null!==a),f.push(a)}}f=[...new Set(f)];let b=null,T=null;const S=t.attributes.getAsNumber("bandwidth");y(null!==S);const v=t.attributes.getAsNumber("average-bandwidth"),w=t.attributes.get("name");for(const e of f){const d=Ke(e);if(null!==d)if(Re.includes(d)){if(null!==b)throw new Error("Unsupported M3U8 file; multiple video codecs found in the CODECS attribute of a variant stream.");b=e;const a=t.attributes.get("video");if(null===a){const e=t.attributes.get("resolution");let r=null,n=null;if(e){const t=e.match(/^(\d+)x(\d+)$/);t&&(r=Number(t[1]),n=Number(t[2]))}u.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:Q,lineNumber:t.lineNumber,fullPath:t.fullPath,fullCodecString:b,pairingMask:BigInt("1")<0?r:null}})}else{if(!a.includes(r))throw new Error(`Invalid M3U8 file; variant stream references audio group "${r}" which is not defined in any #EXT-X-MEDIA tags.`);for(const e of n){const n=e.attributes.get("group-id"),s=e.attributes.get("type");if(n!==r||"audio"!==s.toLowerCase())continue;const a=null!=(l=e.attributes.get("channels"))?l:t.attributes.get("channels"),o=null!==a?Number(a.split("/")[0]):null;u.push({id:-1,demuxer:this,backingTrack:null,default:Qn(e.attributes),autoselect:Qn(e.attributes)||Gn(e.attributes),languageCode:Yn(e.attributes.get("language")),lineNumber:e.lineNumber,fullPath:null!=(c=e.fullPath)?c:t.fullPath,fullCodecString:T,pairingMask:BigInt("1")<0?o:null}})}}}}return u}))),l=[],c=e=>{var t,i;const r=l.find(t=>t.fullPath===e.fullPath&&t.info.type===e.info.type);r?(r.pairingMask|=e.pairingMask,r.default||(r.default=e.default),r.autoselect||(r.autoselect=e.autoselect),r.lineNumber=Math.min(r.lineNumber,e.lineNumber),null!==e.peakBitrate&&(r.peakBitrate=Math.max(null!=(t=r.peakBitrate)?t:-1/0,e.peakBitrate)),null!==e.averageBitrate&&(r.averageBitrate=Math.max(null!=(i=r.averageBitrate)?i:-1/0,e.averageBitrate)),r.languageCode===Q&&(r.languageCode=e.languageCode)):(e.id=l.length+1,l.push(e))};for(const u of o)for(const e of u)c(e);l.sort((e,t)=>e.lineNumber-t.lineNumber),this.trackBackings=[];for(const u of l)"video"===u.info.type?this.trackBackings.push(new Xn(u)):this.trackBackings.push(new $n(u));this.internalTracks=l}))()}getTrackBackings(){return d(this,null,function*(){return yield this.readMetadata(),y(this.trackBackings),this.trackBackings})}getSegmentedInputForPath(e){let t=this.segmentedInputs.find(t=>t.path===e);if(t)return t;let i=null;if(this.internalTracks){i=this.internalTracks.filter(t=>t.fullPath===e).map(e=>({id:e.id,type:e.info.type}))}return t=new Hn(this,e,i,null),this.segmentedInputs.push(t),t}getMetadataTags(){return d(this,null,function*(){return{}})}getMimeType(){return d(this,null,function*(){return on})}dispose(){if(this.segmentedInputs){for(const e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}}class jn{constructor(e){this.internalTrack=e,this.hydrationPromise=null}hydrate(){var e;return null!=(e=this.hydrationPromise)?e:this.hydrationPromise=(()=>d(this,null,function*(){const e=this.internalTrack.demuxer.getSegmentedInputForPath(this.internalTrack.fullPath);let t=null;const i=(yield e.getTrackBackings()).filter(e=>e.getType()===this.getType());if(1===i.length)t=i[0];else if(this instanceof Xn){for(const r of i)if((yield r.getCodec())===this.getCodec()){t=r;break}}else{y(this instanceof $n);for(const e of i)if((yield e.getCodec())===this.getCodec()){t=e;break}}if(!t)throw new Error("Could not find matching track in underlying media data.");this.internalTrack.backingTrack=t}))()}delegate(e){return this.internalTrack.backingTrack?e():this.hydrate().then(e)}getCodec(){throw new Error("Not implemented on base class.")}getDisposition(){return u(c({},Be),{default:this.internalTrack.autoselect,primary:this.internalTrack.default})}getId(){return this.internalTrack.id}getPairingMask(){return this.internalTrack.pairingMask}getInternalCodecId(){return null}getLanguageCode(){return this.internalTrack.languageCode}getName(){return this.internalTrack.name}getNumber(){y(this.internalTrack.demuxer.internalTracks);const e=this.internalTrack.info.type;let t=0;for(const i of this.internalTrack.demuxer.internalTracks)if(i.info.type===e&&t++,i===this.internalTrack)break;return t}getTimeResolution(){return this.delegate(()=>this.internalTrack.backingTrack.getTimeResolution())}isRelativeToUnixEpoch(){return this.delegate(()=>this.internalTrack.backingTrack.isRelativeToUnixEpoch())}getBitrate(){return this.internalTrack.peakBitrate}getAverageBitrate(){return this.internalTrack.averageBitrate}getDurationFromMetadata(e){return d(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getDurationFromMetadata(e)})}getLiveRefreshInterval(){return d(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getLiveRefreshInterval()})}getHasOnlyKeyPackets(){return this.internalTrack.hasOnlyKeyPackets||null}getFirstPacket(e){return d(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getFirstPacket(e)})}getPacket(e,t){return d(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getPacket(e,t)})}getKeyPacket(e,t){return d(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getKeyPacket(e,t)})}getNextPacket(e,t){return d(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getNextPacket(e,t)})}getNextKeyPacket(e,t){return d(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getNextKeyPacket(e,t)})}}class Xn extends jn{constructor(e){super(e)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return"video"}getCodec(){return Ke(this.internalTrack.fullCodecString)}getCodedWidth(){return this.delegate(()=>this.backingVideoTrack.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.backingVideoTrack.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelHeight())}getMetadataDisplayWidth(){return this.backingVideoTrack?null:this.internalTrack.info.width}getMetadataDisplayHeight(){return this.backingVideoTrack?null:this.internalTrack.info.height}getRotation(){return this.delegate(()=>this.backingVideoTrack.getRotation())}getColorSpace(){return d(this,null,function*(){return yield this.hydrate(),this.backingVideoTrack.getColorSpace()})}canBeTransparent(){return d(this,null,function*(){return yield this.hydrate(),this.backingVideoTrack.canBeTransparent()})}getMetadataCodecParameterString(){return this.backingVideoTrack?null:this.internalTrack.fullCodecString}getDecoderConfig(){return d(this,null,function*(){return yield this.hydrate(),this.backingVideoTrack.getDecoderConfig()})}}class $n extends jn{constructor(e){super(e)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return"audio"}getCodec(){return Ke(this.internalTrack.fullCodecString)}getNumberOfChannels(){return null!==this.internalTrack.info.numberOfChannels?this.internalTrack.info.numberOfChannels:this.delegate(()=>this.backingAudioTrack.getNumberOfChannels())}getSampleRate(){return this.delegate(()=>this.backingAudioTrack.getSampleRate())}getMetadataCodecParameterString(){return this.backingAudioTrack?null:this.internalTrack.fullCodecString}getDecoderConfig(){return d(this,null,function*(){return yield this.hydrate(),this.backingAudioTrack.getDecoderConfig()})}}const Qn=e=>{const t=e.get("default");if(null===t)return!1;const i=t.toUpperCase();if("YES"===i)return!0;if("NO"===i)return!1;throw new Error(`Invalid M3U8 file; #EXT-X-MEDIA DEFAULT attribute must be YES or NO, got "${t}".`)},Gn=e=>{const t=e.get("autoselect");if(null===t)return!1;const i=t.toUpperCase();if("YES"===i)return!0;if("NO"===i)return!1;throw new Error(`Invalid M3U8 file; #EXT-X-MEDIA AUTOSELECT attribute must be YES or NO, got "${t}".`)},Yn=e=>{if(null===e)return Q;const t=e.split("-")[0];return t||Q};class Jn{constructor(){this._isIsobmff=!1}}class Zn extends Jn{constructor(){super(...arguments),this._isIsobmff=!0}_getMajorBrand(e){return d(this,null,function*(){let t=e._reader.requestSlice(0,12);if(t instanceof Promise&&(t=yield t),!t)return null;t.skip(4);const i=Wa(t,4);return"ftyp"!==i&&"styp"!==i?null:Wa(t,4)})}_createDemuxer(e){return new gi(e)}}class es extends Zn{_canReadInput(e){return d(this,null,function*(){const t=yield this._getMajorBrand(e);if(null!==t)return"qt "!==t;let i=e._reader.requestSlice(4,4);return i instanceof Promise&&(i=yield i),!!i&&"moof"===Wa(i,4)})}get name(){return"MP4"}get mimeType(){return"video/mp4"}}class ts extends Zn{_canReadInput(e){return d(this,null,function*(){return"qt "===(yield this._getMajorBrand(e))})}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}}class is extends Jn{isSupportedEBMLOfDocType(e,t){return d(this,null,function*(){let i=e._reader.requestSlice(0,Li);if(i instanceof Promise&&(i=yield i),!i)return!1;const r=zi(i);if(null===r)return!1;if(r<1||r>8)return!1;if(qi(i,r)!==Ri.EBML)return!1;const n=Vi(i);if("number"!==typeof n)return!1;let s=e._reader.requestSlice(i.filePos,n);if(s instanceof Promise&&(s=yield s),!s)return!1;const a=i.filePos;for(;s.filePos<=a+n-2;){const e=Hi(s);if(!e)break;const{id:i,size:r}=e,n=s.filePos;if(void 0===r)return!1;switch(i){case Ri.EBMLVersion:if(1!==qi(s,r))return!1;break;case Ri.EBMLReadVersion:if(1!==qi(s,r))return!1;break;case Ri.DocType:if(Ki(s,r)!==t)return!1;break;case Ri.DocTypeVersion:if(qi(s,r)>4)return!1}s.filePos=n+r}return!0})}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new kr(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}}class rs extends is{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}}class ns extends Jn{_canReadInput(e){return d(this,null,function*(){let t=0;for(;;){let i=e._reader.requestSlice(t,Qa);if(i instanceof Promise&&(i=yield i),!i)break;const r=Za(i);if(!r)break;t=i.filePos+r.size}const i=yield Sr(e._reader,t,t+4096);if(!i)return!1;const r=i.header,n=Ge(r.mpegVersionId,r.channel);let s=e._reader.requestSlice(i.startPos+n,4);if(s instanceof Promise&&(s=yield s),!s)return!1;const a=Ra(s);if(a===$e||a===Qe)return!0;t=i.startPos+i.header.totalSize;const o=yield Sr(e._reader,t,t+4);if(!o)return!1;const l=o.header;return r.channel===l.channel&&r.sampleRate===l.sampleRate})}_createDemuxer(e){return new vr(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}}class ss extends Jn{_canReadInput(e){return d(this,null,function*(){let t=e._reader.requestSlice(0,12);if(t instanceof Promise&&(t=yield t),!t)return!1;const i=Wa(t,4);if("RIFF"!==i&&"RIFX"!==i&&"RF64"!==i)return!1;t.skip(4);return"WAVE"===Wa(t,4)})}_createDemuxer(e){return new Lr(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}}class as extends Jn{_canReadInput(e){return d(this,null,function*(){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=yield t),!!t&&"OggS"===Wa(t,4)})}_createDemuxer(e){return new Fr(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}}class os extends Jn{_canReadInput(e){return d(this,null,function*(){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=yield t),!!t&&"fLaC"===Wa(t,4)})}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new Kr(e)}}class ls extends Jn{_canReadInput(e){return d(this,null,function*(){let t=0;for(;;){let i=e._reader.requestSlice(t,Qa);if(i instanceof Promise&&(i=yield i),!i)break;const r=Za(i);if(!r)break;t=i.filePos+r.size}let i=e._reader.requestSliceRange(t,7,9);if(i instanceof Promise&&(i=yield i),!i)return!1;const r=qr(i);if(!r)return!1;if(t+=r.frameLength,i=e._reader.requestSliceRange(t,7,9),i instanceof Promise&&(i=yield i),!i)return!1;const n=qr(i);return!!n&&(r.objectType===n.objectType&&r.samplingFrequencyIndex===n.samplingFrequencyIndex&&r.channelConfiguration===n.channelConfiguration)})}_createDemuxer(e){return new Vr(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}}class cs extends Jn{_canReadInput(e){return d(this,null,function*(){let t=e._reader.requestSlice(0,205);if(t instanceof Promise&&(t=yield t),!t)return!1;const i=xa(t,205);return 71===i[0]&&71===i[188]||(71===i[0]&&71===i[204]||71===i[4]&&71===i[196])})}_createDemuxer(e){return new Yr(e)}get name(){return"MPEG Transport Stream"}get mimeType(){return"video/MP2T"}}class us extends Jn{_canReadInput(e){return d(this,null,function*(){let t=e._reader.requestSlice(0,7);if(t instanceof Promise&&(t=yield t),!t)return!1;if(!("#EXTM3U"===Wa(t,7)))return!1;if(!(e._rootSource instanceof Bn))throw new TypeError("HLS inputs require `InputOptions.source` to be a PathedSource or a ref to one.");return e._rootSource._usedForHls=!0,!0})}_createDemuxer(e){return new Kn(e)}get name(){return"HTTP Live Streaming (HLS)"}get mimeType(){return on}}const ds=new es,hs=new ts,fs=new is,ms=new rs,ps=new ns,gs=new ss,ks=new as,ys=new ls,bs=new os,Ts=new cs,Ss=new us,vs=[Ss,ds,hs,fs,ms,gs,ks,bs,ps,ys,Ts],ws=[Ss,ds,hs,ps,ys,Ts];ke();let Ps=-1/0,Is=-1/0,xs=null;"undefined"!==typeof FinalizationRegistry&&(xs=new FinalizationRegistry(e=>{const t=performance.now();"video"===e.type?(t-Ps>=1e3&&(console.error("A VideoSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your VideoSamples as soon as you're done using them."),Ps=t),"undefined"!==typeof VideoFrame&&e.data instanceof VideoFrame&&e.data.close()):(t-Is>=1e3&&(console.error("An AudioSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your AudioSamples as soon as you're done using them."),Is=t),"undefined"!==typeof AudioData&&e.data instanceof AudioData&&e.data.close())}));const Cs=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],Bs=new Set(Cs);class Es{get codedWidth(){return this.visibleRect.width}get codedHeight(){return this.visibleRect.height}get displayWidth(){return this.rotation%180===0?this.squarePixelWidth:this.squarePixelHeight}get displayHeight(){return this.rotation%180===0?this.squarePixelHeight:this.squarePixelWidth}get microsecondTimestamp(){return Math.trunc(te*this.timestamp)}get microsecondDuration(){return Math.trunc(te*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor(e,t){var i,r,n,s,a,o,l,c,u,d,h,f,m,p,g,k,b,T,S,v,P,I,x,C,B,E;if(this._closed=!1,e instanceof ArrayBuffer||"undefined"!==typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e)){if(!t||"object"!==typeof t)throw new TypeError("init must be an object.");if(void 0===t.format||!Bs.has(t.format))throw new TypeError("init.format must be one of: "+Cs.join(", "));if(!Number.isInteger(t.codedWidth)||t.codedWidth<=0)throw new TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(t.codedHeight)||t.codedHeight<=0)throw new TypeError("init.codedHeight must be a positive integer.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(void 0!==t.duration&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(void 0!==t.layout){if(!Array.isArray(t.layout))throw new TypeError("init.layout, when provided, must be an array.");for(const e of t.layout){if(!e||"object"!==typeof e||Array.isArray(e))throw new TypeError("Each entry in init.layout must be an object.");if(!Number.isInteger(e.offset)||e.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(e.stride)||e.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(void 0!==t.visibleRect&&we(t.visibleRect,"init.visibleRect"),void 0!==t.displayWidth&&(!Number.isInteger(t.displayWidth)||t.displayWidth<=0))throw new TypeError("init.displayWidth, when provided, must be a positive integer.");if(void 0!==t.displayHeight&&(!Number.isInteger(t.displayHeight)||t.displayHeight<=0))throw new TypeError("init.displayHeight, when provided, must be a positive integer.");if(void 0!==t.displayWidth!==(void 0!==t.displayHeight))throw new TypeError("init.displayWidth and init.displayHeight must be either both provided or both omitted.");this._data=w(e).slice(),this._layout=null!=(i=t.layout)?i:Ms(t.format,t.codedWidth,t.codedHeight),this.format=t.format,this.rotation=null!=(r=t.rotation)?r:0,this.timestamp=t.timestamp,this.duration=null!=(n=t.duration)?n:0,this.colorSpace=new _s(t.colorSpace),this.visibleRect={left:null!=(a=null==(s=t.visibleRect)?void 0:s.left)?a:0,top:null!=(l=null==(o=t.visibleRect)?void 0:o.top)?l:0,width:null!=(u=null==(c=t.visibleRect)?void 0:c.width)?u:t.codedWidth,height:null!=(h=null==(d=t.visibleRect)?void 0:d.height)?h:t.codedHeight},void 0!==t.displayWidth?(this.squarePixelWidth=this.rotation%180===0?t.displayWidth:t.displayHeight,this.squarePixelHeight=this.rotation%180===0?t.displayHeight:t.displayWidth):(this.squarePixelWidth=this.codedWidth,this.squarePixelHeight=this.codedHeight)}else if("undefined"!==typeof VideoFrame&&e instanceof VideoFrame){if(void 0!==(null==t?void 0:t.rotation)&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(void 0!==(null==t?void 0:t.timestamp)&&!Number.isFinite(null==t?void 0:t.timestamp))throw new TypeError("init.timestamp, when provided, must be a number.");if(void 0!==(null==t?void 0:t.duration)&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");void 0!==(null==t?void 0:t.visibleRect)&&we(t.visibleRect,"init.visibleRect"),this._data=e,this._layout=null,this.format=e.format,this.visibleRect={left:null!=(m=null==(f=e.visibleRect)?void 0:f.x)?m:0,top:null!=(g=null==(p=e.visibleRect)?void 0:p.y)?g:0,width:null!=(b=null==(k=e.visibleRect)?void 0:k.width)?b:e.codedWidth,height:null!=(S=null==(T=e.visibleRect)?void 0:T.height)?S:e.codedHeight},this.rotation=null!=(v=null==t?void 0:t.rotation)?v:0,this.squarePixelWidth=e.displayWidth,this.squarePixelHeight=e.displayHeight,this.timestamp=null!=(P=null==t?void 0:t.timestamp)?P:e.timestamp/1e6,this.duration=null!=(x=null==t?void 0:t.duration)?x:(null!=(I=e.duration)?I:0)/1e6,this.colorSpace=new _s(e.colorSpace)}else{if(!("undefined"!==typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!==typeof SVGImageElement&&e instanceof SVGImageElement||"undefined"!==typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!==typeof HTMLVideoElement&&e instanceof HTMLVideoElement||"undefined"!==typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!==typeof OffscreenCanvas&&e instanceof OffscreenCanvas))throw new TypeError("Invalid data type: Must be a BufferSource or CanvasImageSource.");{if(!t||"object"!==typeof t)throw new TypeError("init must be an object.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(void 0!==t.duration&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if("undefined"!==typeof VideoFrame)return new Es(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*te),duration:Math.trunc((null!=(C=t.duration)?C:0)*te)||void 0}),t);let i=0,r=0;if("naturalWidth"in e?(i=e.naturalWidth,r=e.naturalHeight):"videoWidth"in e?(i=e.videoWidth,r=e.videoHeight):"width"in e&&(i=Number(e.width),r=Number(e.height)),!i||!r)throw new TypeError("Could not determine dimensions.");const n=new OffscreenCanvas(i,r),s=n.getContext("2d",{alpha:ce(),willReadFrequently:!0});y(s),s.drawImage(e,0,0),this._data=n,this._layout=null,this.format="RGBX",this.visibleRect={left:0,top:0,width:i,height:r},this.squarePixelWidth=i,this.squarePixelHeight=r,this.rotation=null!=(B=t.rotation)?B:0,this.timestamp=t.timestamp,this.duration=null!=(E=t.duration)?E:0,this.colorSpace=new _s({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}}this.pixelAspectRatio=ve({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),null==xs||xs.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return y(null!==this._data),As(this._data)?new Es(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation}):this._data instanceof Uint8Array?(y(this._layout),new Es(this._data,{format:this.format,layout:this._layout,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight})):new Es(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight})}close(){this._closed||(null==xs||xs.unregister(this),As(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(Ds(e),this._closed)throw new Error("VideoSample is closed.");if(null===this.format)throw new Error("Cannot get allocation size when format is null. Sorry!");if(y(null!==this._data),!As(this._data)&&(e.colorSpace||e.format&&e.format!==this.format||e.layout||e.rect)){const t=this.toVideoFrame(),i=t.allocationSize(e);return t.close(),i}return As(this._data)?this._data.allocationSize(e):this._data instanceof Uint8Array?this._data.byteLength:this.codedWidth*this.codedHeight*4}copyTo(e){return d(this,arguments,function*(e,t={}){if(!R(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(Ds(t),this._closed)throw new Error("VideoSample is closed.");if(null===this.format)throw new Error("Cannot copy video sample data when format is null. Sorry!");if(y(null!==this._data),!As(this._data)&&(t.colorSpace||t.format&&t.format!==this.format||t.layout||t.rect)){const i=this.toVideoFrame(),r=yield i.copyTo(e,t);return i.close(),r}if(As(this._data))return this._data.copyTo(e,t);if(this._data instanceof Uint8Array){y(this._layout);return w(e).set(this._data),this._layout}{const t=this._data.getContext("2d");y(t);const i=t.getImageData(0,0,this.codedWidth,this.codedHeight);return w(e).set(i.data),[{offset:0,stride:4*this.codedWidth}]}})}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");return y(null!==this._data),As(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace}):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,t,i,r,n,s,a,o,l){let c=0,u=0,d=this.displayWidth,h=this.displayHeight,f=0,m=0,p=this.displayWidth,g=this.displayHeight;if(void 0!==s?(c=t,u=i,d=r,h=n,f=s,m=a,void 0!==o?(p=o,g=l):(p=d,g=h)):(f=t,m=i,void 0!==r&&(p=r,g=n)),!("undefined"!==typeof CanvasRenderingContext2D&&e instanceof CanvasRenderingContext2D||"undefined"!==typeof OffscreenCanvasRenderingContext2D&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(c))throw new TypeError("sx must be a number.");if(!Number.isFinite(u))throw new TypeError("sy must be a number.");if(!Number.isFinite(d)||d<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(h)||h<0)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(f))throw new TypeError("dx must be a number.");if(!Number.isFinite(m))throw new TypeError("dy must be a number.");if(!Number.isFinite(p)||p<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(g)||g<0)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw new Error("VideoSample is closed.");({sx:c,sy:u,sWidth:d,sHeight:h}=this._rotateSourceRegion(c,u,d,h,this.rotation));const k=this.toCanvasImageSource();e.save();const y=f+p/2,b=m+g/2;e.translate(y,b),e.rotate(this.rotation*Math.PI/180);const T=this.rotation%180===0?1:p/g;e.scale(1/T,T),e.drawImage(k,c,u,d,h,-p/2,-g/2,p,g),e.restore()}drawWithFit(e,t){var i,r,n,s,a,o,l,c,u;if(!("undefined"!==typeof CanvasRenderingContext2D&&e instanceof CanvasRenderingContext2D||"undefined"!==typeof OffscreenCanvasRenderingContext2D&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!t||"object"!==typeof t)throw new TypeError("options must be an object.");if(!["fill","contain","cover"].includes(t.fit))throw new TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");void 0!==t.crop&&Rs(t.crop,"options.");const d=e.canvas.width,h=e.canvas.height,f=null!=(i=t.rotation)?i:this.rotation,[m,p]=f%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let g,k,y,b;t.crop&&Fs(t.crop,m,p);const{sx:T,sy:S,sWidth:v,sHeight:w}=this._rotateSourceRegion(null!=(n=null==(r=t.crop)?void 0:r.left)?n:0,null!=(a=null==(s=t.crop)?void 0:s.top)?a:0,null!=(l=null==(o=t.crop)?void 0:o.width)?l:m,null!=(u=null==(c=t.crop)?void 0:c.height)?u:p,f);if("fill"===t.fit)g=0,k=0,y=d,b=h;else{const[e,i]=t.crop?[t.crop.width,t.crop.height]:[m,p],r="contain"===t.fit?Math.min(d/e,h/i):Math.max(d/e,h/i);y=e*r,b=i*r,g=(d-y)/2,k=(h-b)/2}e.save();const P=f%180===0?1:y/b;e.translate(d/2,h/2),e.rotate(f*Math.PI/180),e.scale(1/P,P),e.translate(-d/2,-h/2),e.drawImage(this.toCanvasImageSource(),T,S,v,w,g,k,y,b),e.restore()}_rotateSourceRegion(e,t,i,r,n){return 90===n?[e,t,i,r]=[t,this.squarePixelHeight-e-i,r,i]:180===n?[e,t]=[this.squarePixelWidth-e-i,this.squarePixelHeight-t-r]:270===n&&([e,t,i,r]=[this.squarePixelWidth-t-r,e,r,i]),{sx:e,sy:t,sWidth:i,sHeight:r}}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(y(null!==this._data),this._data instanceof Uint8Array){const e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}return this._data}setRotation(e){if(![0,90,180,270].includes(e))throw new TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}setDuration(e){if(!Number.isFinite(e)||e<0)throw new TypeError("newDuration must be a non-negative number.");this.duration=e}[Symbol.dispose](){this.close()}}class _s{constructor(e){var t,i,r,n;if(void 0!==e){if(!e||"object"!==typeof e)throw new TypeError("init.colorSpace, when provided, must be an object.");const t=Object.keys(C);if(null!=e.primaries&&!t.includes(e.primaries))throw new TypeError(`init.colorSpace.primaries, when provided, must be one of ${t.join(", ")}.`);const i=Object.keys(E);if(null!=e.transfer&&!i.includes(e.transfer))throw new TypeError(`init.colorSpace.transfer, when provided, must be one of ${i.join(", ")}.`);const r=Object.keys(A);if(null!=e.matrix&&!r.includes(e.matrix))throw new TypeError(`init.colorSpace.matrix, when provided, must be one of ${r.join(", ")}.`);if(null!=e.fullRange&&"boolean"!==typeof e.fullRange)throw new TypeError("init.colorSpace.fullRange, when provided, must be a boolean.")}this.primaries=null!=(t=null==e?void 0:e.primaries)?t:null,this.transfer=null!=(i=null==e?void 0:e.transfer)?i:null,this.matrix=null!=(r=null==e?void 0:e.matrix)?r:null,this.fullRange=null!=(n=null==e?void 0:e.fullRange)?n:null}toJSON(){return{primaries:this.primaries,transfer:this.transfer,matrix:this.matrix,fullRange:this.fullRange}}}const As=e=>"undefined"!==typeof VideoFrame&&e instanceof VideoFrame,Fs=(e,t,i)=>{const r=Math.min(e.left,t),n=Math.min(e.top,i),s=Math.min(e.width,t-r),a=Math.min(e.height,i-n);return y(s>=0),y(a>=0),{left:r,top:n,width:s,height:a}},Rs=(e,t)=>{if(!e||"object"!==typeof e)throw new TypeError(t+"crop, when provided, must be an object.");if(!Number.isInteger(e.left)||e.left<0)throw new TypeError(t+"crop.left must be a non-negative integer.");if(!Number.isInteger(e.top)||e.top<0)throw new TypeError(t+"crop.top must be a non-negative integer.");if(!Number.isInteger(e.width)||e.width<0)throw new TypeError(t+"crop.width must be a non-negative integer.");if(!Number.isInteger(e.height)||e.height<0)throw new TypeError(t+"crop.height must be a non-negative integer.")},Ds=e=>{if(!e||"object"!==typeof e)throw new TypeError("options must be an object.");if(void 0!==e.colorSpace&&!["display-p3","srgb"].includes(e.colorSpace))throw new TypeError("options.colorSpace, when provided, must be 'display-p3' or 'srgb'.");if(void 0!==e.format&&"string"!==typeof e.format)throw new TypeError("options.format, when provided, must be a string.");if(void 0!==e.layout){if(!Array.isArray(e.layout))throw new TypeError("options.layout, when provided, must be an array.");for(const t of e.layout){if(!t||"object"!==typeof t)throw new TypeError("Each entry in options.layout must be an object.");if(!Number.isInteger(t.offset)||t.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(t.stride)||t.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(void 0!==e.rect){if(!e.rect||"object"!==typeof e.rect)throw new TypeError("options.rect, when provided, must be an object.");if(void 0!==e.rect.x&&(!Number.isInteger(e.rect.x)||e.rect.x<0))throw new TypeError("options.rect.x, when provided, must be a non-negative integer.");if(void 0!==e.rect.y&&(!Number.isInteger(e.rect.y)||e.rect.y<0))throw new TypeError("options.rect.y, when provided, must be a non-negative integer.");if(void 0!==e.rect.width&&(!Number.isInteger(e.rect.width)||e.rect.width<0))throw new TypeError("options.rect.width, when provided, must be a non-negative integer.");if(void 0!==e.rect.height&&(!Number.isInteger(e.rect.height)||e.rect.height<0))throw new TypeError("options.rect.height, when provided, must be a non-negative integer.")}},Ms=(e,t,i)=>{const r=Ns(e),n=[];let s=0;for(const a of r){const e=Math.ceil(t/a.widthDivisor),r=Math.ceil(i/a.heightDivisor),o=e*a.sampleBytes,l=o*r;n.push({offset:s,stride:o}),s+=l}return n},Ns=e=>{const t=(e,t,i,r,n)=>{const s=[{sampleBytes:e,widthDivisor:1,heightDivisor:1},{sampleBytes:t,widthDivisor:i,heightDivisor:r},{sampleBytes:t,widthDivisor:i,heightDivisor:r}];return n&&s.push({sampleBytes:e,widthDivisor:1,heightDivisor:1}),s};switch(e){case"I420":return t(1,1,2,2,!1);case"I420P10":case"I420P12":return t(2,2,2,2,!1);case"I420A":return t(1,1,2,2,!0);case"I420AP10":case"I420AP12":return t(2,2,2,2,!0);case"I422":return t(1,1,2,1,!1);case"I422P10":case"I422P12":return t(2,2,2,1,!1);case"I422A":return t(1,1,2,1,!0);case"I422AP10":case"I422AP12":return t(2,2,2,1,!0);case"I444":return t(1,1,1,1,!1);case"I444P10":case"I444P12":return t(2,2,1,1,!1);case"I444A":return t(1,1,1,1,!0);case"I444AP10":case"I444AP12":return t(2,2,1,1,!0);case"NV12":return[{sampleBytes:1,widthDivisor:1,heightDivisor:1},{sampleBytes:2,widthDivisor:2,heightDivisor:2}];case"RGBA":case"RGBX":case"BGRA":case"BGRX":return[{sampleBytes:4,widthDivisor:1,heightDivisor:1}];default:H(e),y(!1)}},Os=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]);class Ls{get microsecondTimestamp(){return Math.trunc(te*this.timestamp)}get microsecondDuration(){return Math.trunc(te*this.duration)}constructor(e){if(this._closed=!1,Vs(e)){if(null===e.format)throw new TypeError("AudioData with null format is not supported.");this._data=e,this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=e.numberOfFrames,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp/1e6,this.duration=e.numberOfFrames/e.sampleRate}else{if(!e||"object"!==typeof e)throw new TypeError("Invalid AudioDataInit: must be an object.");if(!Os.has(e.format))throw new TypeError("Invalid AudioDataInit: invalid format.");if(!Number.isFinite(e.sampleRate)||e.sampleRate<=0)throw new TypeError("Invalid AudioDataInit: sampleRate must be > 0.");if(!Number.isInteger(e.numberOfChannels)||0===e.numberOfChannels)throw new TypeError("Invalid AudioDataInit: numberOfChannels must be an integer > 0.");if(!Number.isFinite(null==e?void 0:e.timestamp))throw new TypeError("init.timestamp must be a number.");const t=e.data.byteLength/(zs(e.format)*e.numberOfChannels);if(!Number.isInteger(t))throw new TypeError("Invalid AudioDataInit: data size is not a multiple of frame size.");let i;if(this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=t,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp,this.duration=t/e.sampleRate,e.data instanceof ArrayBuffer)i=new Uint8Array(e.data);else{if(!ArrayBuffer.isView(e.data))throw new TypeError("Invalid AudioDataInit: data is not a BufferSource.");i=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength)}const r=this.numberOfFrames*this.numberOfChannels*zs(this.format);if(i.byteLength=this.numberOfFrames)throw new RangeError("frameOffset out of range");const s=void 0!==e.frameCount?e.frameCount:this.numberOfFrames-n;if(s>this.numberOfFrames-n)throw new RangeError("frameCount out of range");const a=zs(r),o=Us(r);if(o&&e.planeIndex>=this.numberOfChannels)throw new RangeError("planeIndex out of range");if(!o&&0!==e.planeIndex)throw new RangeError("planeIndex out of range");return(o?s:s*this.numberOfChannels)*a}copyTo(e,t){if(!R(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(!t||"object"!==typeof t)throw new TypeError("options must be an object.");if(!Number.isInteger(t.planeIndex)||t.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(void 0!==t.format&&!Os.has(t.format))throw new TypeError("Invalid format.");if(void 0!==t.frameOffset&&(!Number.isInteger(t.frameOffset)||t.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(void 0!==t.frameCount&&(!Number.isInteger(t.frameCount)||t.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");const{planeIndex:i,format:r,frameCount:n,frameOffset:s}=t,a=this.format,o=null!=r?r:this.format;if(!o)throw new Error("Destination format not determined");const l=this.numberOfFrames,c=this.numberOfChannels,u=null!=s?s:0;if(u>=l)throw new RangeError("frameOffset out of range");const d=void 0!==n?n:l-u;if(d>l-u)throw new RangeError("frameCount out of range");const h=zs(o),f=Us(o);if(f&&i>=c)throw new RangeError("planeIndex out of range");if(!f&&0!==i)throw new RangeError("planeIndex out of range");const m=(f?d:d*c)*h;if(e.byteLength2&&o!==a?Hs(this._data,p,a,o,c,i,u,d):this._data.copyTo(e,{planeIndex:i,frameOffset:u,frameCount:d,format:o});else{const e=this._data,t=P(e),r=qs(a),n=zs(a),s=Us(a);for(let a=0;a0;){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")}},Us=e=>{switch(e){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},qs=e=>{switch(e){case"u8":case"u8-planar":return(e,t)=>(e.getUint8(t)-128)/128;case"s16":case"s16-planar":return(e,t)=>e.getInt16(t,!0)/32768;case"s32":case"s32-planar":return(e,t)=>e.getInt32(t,!0)/2147483648;case"f32":case"f32-planar":return(e,t)=>e.getFloat32(t,!0)}},Ws=e=>{switch(e){case"u8":case"u8-planar":return(e,t,i)=>e.setUint8(t,$(127.5*(i+1),0,255));case"s16":case"s16-planar":return(e,t,i)=>e.setInt16(t,$(Math.round(32767*i),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,i)=>e.setInt32(t,$(Math.round(2147483647*i),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,i)=>e.setFloat32(t,i,!0)}},Vs=e=>"undefined"!==typeof AudioData&&e instanceof AudioData,Hs=(e,t,i,r,n,s,a,o)=>{const l=qs(i),c=Ws(r),u=zs(i),d=zs(r),h=Us(i);if(Us(r))if(h){const r=new ArrayBuffer(o*u),n=P(r);e.copyTo(r,{planeIndex:s,frameOffset:a,frameCount:o,format:i});for(let e=0;e{if(!e||"object"!==typeof e)throw new TypeError("options must be an object.");if(void 0!==e.metadataOnly&&"boolean"!==typeof e.metadataOnly)throw new TypeError("options.metadataOnly, when defined, must be a boolean.");if(void 0!==e.verifyKeyPackets&&"boolean"!==typeof e.verifyKeyPackets)throw new TypeError("options.verifyKeyPackets, when defined, must be a boolean.");if(e.verifyKeyPackets&&e.metadataOnly)throw new TypeError("options.verifyKeyPackets and options.metadataOnly cannot be enabled together.");if(void 0!==e.skipLiveWait&&"boolean"!==typeof e.skipLiveWait)throw new TypeError("options.skipLiveWait, when defined, must be a boolean.")},$s=e=>{if(!ye(e))throw new TypeError("timestamp must be a number.")},Qs=(e,t,i)=>i.verifyKeyPackets?t.then(t=>d(null,null,function*(){if(!t||"delta"===t.type)return t;const i=yield e.determinePacketType(t);return i&&(t.type=i),t})):t;class Gs{constructor(e){if(!(e instanceof la))throw new TypeError("track must be an InputTrack.");this._track=e}getFirstPacket(){return d(this,arguments,function*(e={}){if(Xs(e),this._track.input._disposed)throw new va;return Qs(this._track,this._track._backing.getFirstPacket(e),e)})}getFirstKeyPacket(){return d(this,arguments,function*(e={}){Xs(e);const t=yield this.getFirstPacket(e);return t?"key"===t.type?t:this.getNextKeyPacket(t,e):null})}getPacket(e){return d(this,arguments,function*(e,t={}){if($s(e),Xs(t),this._track.input._disposed)throw new va;return Qs(this._track,this._track._backing.getPacket(e,t),t)})}getNextPacket(e){return d(this,arguments,function*(e,t={}){if(!(e instanceof Yt))throw new TypeError("packet must be an EncodedPacket.");if(Xs(t),this._track.input._disposed)throw new va;return Qs(this._track,this._track._backing.getNextPacket(e,t),t)})}getKeyPacket(e){return d(this,arguments,function*(e,t={}){if($s(e),Xs(t),this._track.input._disposed)throw new va;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);const i=yield this._track._backing.getKeyPacket(e,t);if(!i)return i;y("key"===i.type);return"delta"===(yield this._track.determinePacketType(i))?this.getKeyPacket(i.timestamp-1/(yield this._track.getTimeResolution()),t):i})}getNextKeyPacket(e){return d(this,arguments,function*(e,t={}){if(!(e instanceof Yt))throw new TypeError("packet must be an EncodedPacket.");if(Xs(t),this._track.input._disposed)throw new va;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);const i=yield this._track._backing.getNextKeyPacket(e,t);if(!i)return i;y("key"===i.type);return"delta"===(yield this._track.determinePacketType(i))?this.getNextKeyPacket(i,t):i})}packets(e,t,i={}){if(void 0!==e&&!(e instanceof Yt))throw new TypeError("startPacket must be an EncodedPacket.");if(void 0!==e&&e.isMetadataOnly&&!(null==i?void 0:i.metadataOnly))throw new TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(void 0!==t&&!(t instanceof Yt))throw new TypeError("endPacket must be an EncodedPacket.");if(Xs(i),this._track.input._disposed)throw new va;const r=[];let{promise:n,resolve:s}=q(),{promise:a,resolve:o}=q(),l=!1,c=!1,u=null;const h=[],f=()=>Math.max(2,h.length);(()=>d(this,null,function*(){let u=null!=e?e:yield this.getFirstPacket(i);for(;u&&!c&&!this._track.input._disposed&&!(t&&u.sequenceNumber>=(null==t?void 0:t.sequenceNumber));)r.length>f()?(({promise:a,resolve:o}=q()),yield a):(r.push(u),s(),({promise:n,resolve:s}=q()),u=yield this.getNextPacket(u,i));l=!0,s()}))().catch(e=>{u||(u=e,s())});const m=this._track;return{next(){return d(this,null,function*(){for(;;){if(m.input._disposed)throw new va;if(c)return{value:void 0,done:!0};if(u)throw u;if(r.length>0){const e=r.shift(),t=performance.now();for(h.push(t);h.length>0&&t-h[0]>=1e3;)h.shift();return o(),{value:e,done:!1}}if(l)return{value:void 0,done:!0};yield n}})},return(){return d(this,null,function*(){return c=!0,o(),s(),{value:void 0,done:!0}})},throw(e){return d(this,null,function*(){throw e})},[Symbol.asyncIterator](){return this}}}}class Ys{constructor(e,t){this.onSample=e,this.onError=t}}class Js{mediaSamplesInRange(e=0,t=1/0,i){$s(e),$s(t);const r=[];let n=!1,s=null,{promise:a,resolve:o}=q(),{promise:l,resolve:h}=q(),f=!1,m=!1,p=!1,g=null;const k=u(c({},i),{verifyKeyPackets:!0,metadataOnly:!1});(()=>d(this,null,function*(){var i;const c=yield this._createDecoder(i=>{h(),i.timestamp>=t&&(m=!0),m?i.close():(s&&(i.timestamp>e?(r.push(s),n=!0):s.close()),i.timestamp>=e&&(r.push(i),n=!0),s=n?null:i,r.length>0&&(o(),({promise:a,resolve:o}=q())))},e=>{g||(g=e,o())}),u=this._createPacketSink(),d=null!=(i=yield u.getKeyPacket(e,k))?i:yield u.getFirstKeyPacket(k);let y=d;const b=u.packets(null!=d?d:void 0,void 0,k);for(yield b.next();y&&!m&&!this._track.input._disposed;){const e=Zs(r.length);if(r.length+c.getDecodeQueueSize()>e){({promise:l,resolve:h}=q()),yield l;continue}c.decode(y);const t=yield b.next();if(t.done)break;y=t.value}yield b.return(),p||this._track.input._disposed||(yield c.flush()),c.close(),!n&&s&&r.push(s),f=!0,o()}))().catch(e=>{g||(g=e,o())});const y=this._track,b=()=>{null==s||s.close();for(const e of r)e.close()};return{next(){return d(this,null,function*(){for(;;){if(y.input._disposed)throw b(),new va;if(p)return{value:void 0,done:!0};if(g)throw b(),g;if(r.length>0){const e=r.shift();return h(),{value:e,done:!1}}if(f)return{value:void 0,done:!0};yield a}})},return(){return d(this,null,function*(){return p=!0,m=!0,h(),o(),b(),{value:void 0,done:!0}})},throw(e){return d(this,null,function*(){throw e})},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e,t){(e=>{if(!(Symbol.iterator in e)&&!(Symbol.asyncIterator in e))throw new TypeError("Argument must be an iterable or async iterable.")})(e);const i=function(e){return f(this,null,function*(){Symbol.iterator in e?yield*m(e[Symbol.iterator]()):yield*m(e[Symbol.asyncIterator]())})}(e),r=[],n=[];let{promise:s,resolve:a}=q(),{promise:o,resolve:l}=q(),h=!1,g=!1,k=null;const b=e=>{n.push(e),a(),({promise:s,resolve:a}=q())},T=u(c({},t),{verifyKeyPackets:!0,metadataOnly:!1});(()=>d(this,null,function*(){const e=yield this._createDecoder(e=>{if(l(),g)return void e.close();let t=0;for(;r.length>0&&e.timestamp-r[0]>-1e-10;)t++,r.shift();if(t>0)for(let i=0;i{k||(k=e,a())}),t=this._createPacketSink();let s=null,c=null,u=-1;const f=()=>d(this,null,function*(){y(c);let i=c;for(e.decode(i);i.sequenceNumberr&&!g;)({promise:o,resolve:l}=q()),yield o;if(g)break;const s=yield t.getNextPacket(i,T);y(s),e.decode(s),i=s}u=-1}),m=()=>d(this,null,function*(){yield e.flush();for(let e=0;e{k||(k=e,a())});const S=this._track,v=()=>{for(const e of n)null==e||e.close()};return{next(){return d(this,null,function*(){for(;;){if(S.input._disposed)throw v(),new va;if(g)return{value:void 0,done:!0};if(k)throw v(),k;if(n.length>0){const e=n.shift();return y(void 0!==e),l(),{value:e,done:!1}}if(h)return{value:void 0,done:!0};yield s}})},return(){return d(this,null,function*(){return g=!0,l(),a(),v(),{value:void 0,done:!0}})},throw(e){return d(this,null,function*(){throw e})},[Symbol.asyncIterator](){return this}}}}const Zs=e=>0===e?40:8;class ea extends Ys{constructor(e,t,i,r,n,s){super(e,t),this.codec=i,this.decoderConfig=r,this.rotation=n,this.timeResolution=s,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new se,this.customDecoderQueueSize=0,this.inputTimestamps=[],this.sampleQueue=[],this.currentPacketIndex=0,this.raslSkipped=!1,this.alphaDecoder=null,this.alphaHadKeyframe=!1,this.colorQueue=[],this.alphaQueue=[],this.merger=null,this.mergerCreationFailed=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue=[],this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1;const a=Ks.find(e=>e.supports(i,r));if(a)this.customDecoder=new a,this.customDecoder.codec=i,this.customDecoder.config=r,this.customDecoder.onSample=e=>{if(!(e instanceof Es))throw new TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(e)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{const e=e=>{if(this.alphaQueue.length>0){const t=this.alphaQueue.shift();y(void 0!==t),this.mergeAlpha(e,t)}else this.colorQueue.push(e)};if("avc"===i&&this.decoderConfig.description&&de()){const e=(e=>{try{const t=P(e);let i=0;const r=t.getUint8(i++),n=t.getUint8(i++),s=t.getUint8(i++),a=t.getUint8(i++),o=3&t.getUint8(i++),l=31&t.getUint8(i++),c=[];for(let f=0;f0){const t=kt(e.sequenceParameterSets[0]);t&&0===t.frameMbsOnlyFlag&&(this.decoderConfig=u(c({},this.decoderConfig),{hardwareAcceleration:"prefer-software"}))}}const t=new Error("Decoding error").stack;this.decoder=new VideoDecoder({output:t=>{try{e(t)}catch(i){this.onError(i)}},error:e=>{e.stack=t,this.onError(e)}}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){var e,t;return this.customDecoder?this.customDecoderQueueSize:(y(this.decoder),Math.max(this.decoder.decodeQueueSize,null!=(t=null==(e=this.alphaDecoder)?void 0:e.decodeQueueSize)?t:0))}decode(e){if("hevc"===this.codec&&this.currentPacketIndex>0&&!this.raslSkipped){if(this.hasHevcRaslPicture(e.data))return;this.raslSkipped=!0}if(this.customDecoder)this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--);else{if(y(this.decoder),oe()||U(this.inputTimestamps,e.timestamp,e=>e),de()&&0===this.currentPacketIndex)if("avc"===this.codec){const t=[];for(const r of ct(e.data,this.decoderConfig)){const i=ut(e.data[r.offset]);i>=20&&i<=31||t.push(e.data.subarray(r.offset,r.offset+r.length))}const i=((e,t)=>{if(t.description){const i=3&w(t.description)[4];return mt(e,i+1)}return ft(e)})(t,this.decoderConfig);e=new Yt(i,e.type,e.timestamp,e.duration)}else if("hevc"===this.codec){const t=Ft(e.data,this.decoderConfig);t&&(e=new Yt(t,e.type,e.timestamp,e.duration))}this.decoder.decode(e.toEncodedVideoChunk()),this.decodeAlphaData(e)}this.currentPacketIndex++}decodeAlphaData(e){if(!e.sideData.alpha||this.mergerCreationFailed)return void this.pushNullAlphaFrame();if(!this.merger)try{this.merger=new ta}catch(i){return console.error("Due to an error, only color data will be decoded.",i),this.mergerCreationFailed=!0,void this.decodeAlphaData(e)}if(!this.alphaDecoder){const e=e=>{if(this.alphaDecoderQueueSize--,this.colorQueue.length>0){const t=this.colorQueue.shift();y(void 0!==t),this.mergeAlpha(t,e)}else this.alphaQueue.push(e);for(this.decodedAlphaChunkCount++;this.nullAlphaFrameQueue.length>0&&this.nullAlphaFrameQueue[0]===this.decodedAlphaChunkCount;)if(this.nullAlphaFrameQueue.shift(),this.colorQueue.length>0){const e=this.colorQueue.shift();y(void 0!==e),this.mergeAlpha(e,null)}else this.alphaQueue.push(null)},t=new Error("Decoding error").stack;this.alphaDecoder=new VideoDecoder({output:t=>{try{e(t)}catch(i){this.onError(i)}},error:e=>{e.stack=t,this.onError(e)}}),this.alphaDecoder.configure(this.decoderConfig)}const t=Lt(this.codec,this.decoderConfig,e.sideData.alpha);if(this.alphaHadKeyframe||(this.alphaHadKeyframe="key"===t),this.alphaHadKeyframe){if("hevc"===this.codec&&this.currentAlphaPacketIndex>0&&!this.alphaRaslSkipped){if(this.hasHevcRaslPicture(e.sideData.alpha))return void this.pushNullAlphaFrame();this.alphaRaslSkipped=!0}this.currentAlphaPacketIndex++,this.alphaDecoder.decode(e.alphaToEncodedVideoChunk(null!=t?t:e.type)),this.alphaDecoderQueueSize++}else this.pushNullAlphaFrame()}pushNullAlphaFrame(){0===this.alphaDecoderQueueSize?this.alphaQueue.push(null):this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture(e){for(const t of bt(e,this.decoderConfig)){const i=Tt(e[t.offset]);if(i===st.RASL_N||i===st.RASL_R)return!0}return!1}sampleHandler(e){if(oe()){if(this.sampleQueue.length>0&&e.timestamp>=T(this.sampleQueue).timestamp){for(const e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}U(this.sampleQueue,e,e=>e.timestamp)}else{const t=this.inputTimestamps.shift();y(void 0!==t),e.setTimestamp(t),this.finalizeAndEmitSample(e)}}finalizeAndEmitSample(e){e.setTimestamp(Math.round(e.timestamp*this.timeResolution)/this.timeResolution),e.setDuration(Math.round(e.duration*this.timeResolution)/this.timeResolution),e.setRotation(this.rotation),this.onSample(e)}mergeAlpha(e,t){var i;if(!t){const t=new Es(e);return void this.sampleHandler(t)}y(this.merger),this.merger.update(e,t),e.close(),t.close();const r=new VideoFrame(this.merger.canvas,{timestamp:e.timestamp,duration:null!=(i=e.duration)?i:void 0}),n=new Es(r);this.sampleHandler(n)}flush(){return d(this,null,function*(){var e;if(this.customDecoder?yield this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(y(this.decoder),yield Promise.all([this.decoder.flush(),null==(e=this.alphaDecoder)?void 0:e.flush()]),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>null==e?void 0:e.close()),this.alphaQueue.length=0,this.alphaHadKeyframe=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue.length=0,this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1),oe()){for(const e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}this.currentPacketIndex=0,this.raslSkipped=!1})}close(){var e,t;this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(y(this.decoder),this.decoder.close(),null==(e=this.alphaDecoder)||e.close(),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>null==e?void 0:e.close()),this.alphaQueue.length=0,null==(t=this.merger)||t.close());for(const i of this.sampleQueue)i.close();this.sampleQueue.length=0}}class ta{constructor(){"undefined"!==typeof OffscreenCanvas?this.canvas=new OffscreenCanvas(300,150):this.canvas=document.createElement("canvas");const e=this.canvas.getContext("webgl2",{premultipliedAlpha:!1});if(!e)throw new Error("Couldn't acquire WebGL 2 context.");this.gl=e,this.program=this.createProgram(),this.vao=this.createVAO(),this.colorTexture=this.createTexture(),this.alphaTexture=this.createTexture(),this.gl.useProgram(this.program),this.gl.uniform1i(this.gl.getUniformLocation(this.program,"u_colorTexture"),0),this.gl.uniform1i(this.gl.getUniformLocation(this.program,"u_alphaTexture"),1)}createProgram(){const e=this.createShader(this.gl.VERTEX_SHADER,"#version 300 es\n\t\t\tin vec2 a_position;\n\t\t\tin vec2 a_texCoord;\n\t\t\tout vec2 v_texCoord;\n\t\t\t\n\t\t\tvoid main() {\n\t\t\t\tgl_Position = vec4(a_position, 0.0, 1.0);\n\t\t\t\tv_texCoord = a_texCoord;\n\t\t\t}\n\t\t"),t=this.createShader(this.gl.FRAGMENT_SHADER,"#version 300 es\n\t\t\tprecision highp float;\n\t\t\t\n\t\t\tuniform sampler2D u_colorTexture;\n\t\t\tuniform sampler2D u_alphaTexture;\n\t\t\tin vec2 v_texCoord;\n\t\t\tout vec4 fragColor;\n\t\t\t\n\t\t\tvoid main() {\n\t\t\t\tvec3 color = texture(u_colorTexture, v_texCoord).rgb;\n\t\t\t\tfloat alpha = texture(u_alphaTexture, v_texCoord).r;\n\t\t\t\tfragColor = vec4(color, alpha);\n\t\t\t}\n\t\t"),i=this.gl.createProgram();return this.gl.attachShader(i,e),this.gl.attachShader(i,t),this.gl.linkProgram(i),i}createShader(e,t){const i=this.gl.createShader(e);return this.gl.shaderSource(i,t),this.gl.compileShader(i),i}createVAO(){const e=this.gl.createVertexArray();this.gl.bindVertexArray(e);const t=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),i=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,i),this.gl.bufferData(this.gl.ARRAY_BUFFER,t,this.gl.STATIC_DRAW);const r=this.gl.getAttribLocation(this.program,"a_position"),n=this.gl.getAttribLocation(this.program,"a_texCoord");return this.gl.enableVertexAttribArray(r),this.gl.vertexAttribPointer(r,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(n),this.gl.vertexAttribPointer(n,2,this.gl.FLOAT,!1,16,8),e}createTexture(){const e=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),e}update(e,t){e.displayWidth===this.canvas.width&&e.displayHeight===this.canvas.height||(this.canvas.width=e.displayWidth,this.canvas.height=e.displayHeight),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.colorTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),this.gl.activeTexture(this.gl.TEXTURE1),this.gl.bindTexture(this.gl.TEXTURE_2D,this.alphaTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,t),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4)}close(){var e;null==(e=this.gl.getExtension("WEBGL_lose_context"))||e.loseContext(),this.gl=null}}class ia extends Js{constructor(e){if(!(e instanceof da))throw new TypeError("videoTrack must be an InputVideoTrack.");super(),this._track=e}_createDecoder(e,t){return d(this,null,function*(){if(!(yield this._track.canDecode()))throw new Error("This video track cannot be decoded by this browser. Make sure to check decodability before using a track.");const i=yield this._track.getCodec(),r=yield this._track.getRotation(),n=yield this._track.getDecoderConfig(),s=yield this._track.getTimeResolution();return y(i&&n),new ea(e,t,i,n,r,s)})}_createPacketSink(){return new Gs(this._track)}getSample(e){return d(this,arguments,function*(e,t={}){$s(e);try{for(var i,r,n,s=p(this.mediaSamplesAtTimestamps([e],t));i=!(r=yield s.next()).done;i=!1){return r.value}}catch(r){n=[r]}finally{try{i&&(r=s.return)&&(yield r.call(s))}finally{if(n)throw n[0]}}throw new Error("Internal error: Iterator returned nothing.")})}samples(e=0,t=1/0,i={}){return this.mediaSamplesInRange(e,t,i)}samplesAtTimestamps(e,t={}){return this.mediaSamplesAtTimestamps(e,t)}}class ra{constructor(e,t={}){var i,r,n;if(this._rotation=0,this._initPromise=null,this._nextCanvasIndex=0,!(e instanceof da))throw new TypeError("videoTrack must be an InputVideoTrack.");if(t&&"object"!==typeof t)throw new TypeError("options must be an object.");if(void 0!==t.alpha&&"boolean"!==typeof t.alpha)throw new TypeError("options.alpha, when provided, must be a boolean.");if(void 0!==t.width&&(!Number.isInteger(t.width)||t.width<=0))throw new TypeError("options.width, when defined, must be a positive integer.");if(void 0!==t.height&&(!Number.isInteger(t.height)||t.height<=0))throw new TypeError("options.height, when defined, must be a positive integer.");if(void 0!==t.fit&&!["fill","contain","cover"].includes(t.fit))throw new TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(void 0!==t.width&&void 0!==t.height&&void 0===t.fit)throw new TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180 or 270.");if(void 0!==t.crop&&Rs(t.crop,"options."),void 0!==t.poolSize&&("number"!==typeof t.poolSize||!Number.isInteger(t.poolSize)||t.poolSize<0))throw new TypeError("poolSize must be a non-negative integer.");this._videoTrack=e,this._alpha=null!=(i=t.alpha)&&i,this._options=t,this._fit=null!=(r=t.fit)?r:"fill",this._videoSampleSink=new ia(e),this._canvasPool=Array.from({length:null!=(n=t.poolSize)?n:0},()=>null)}_ensureInit(){var e;return null!=(e=this._initPromise)?e:this._initPromise=(()=>d(this,null,function*(){var e;const t=this._options,i=this._videoTrack,r=null!=(e=t.rotation)?e:yield i.getRotation(),n=yield i.getSquarePixelWidth(),s=yield i.getSquarePixelHeight(),[a,o]=r%180===0?[n,s]:[s,n];let l=t.crop;l&&(l=Fs(l,a,o));let[c,u]=l?[l.width,l.height]:[a,o];const d=c/u;void 0!==t.width&&void 0===t.height?(c=t.width,u=Math.round(c/d)):void 0===t.width&&void 0!==t.height?(u=t.height,c=Math.round(u*d)):void 0!==t.width&&void 0!==t.height&&(c=t.width,u=t.height),this._width=c,this._height=u,this._rotation=r,this._crop=l}))()}_videoSampleToWrappedCanvas(e){const t=this._width,i=this._height;let r=this._canvasPool[this._nextCanvasIndex],n=!1;r||("undefined"!==typeof document?(r=document.createElement("canvas"),r.width=t,r.height=i):r=new OffscreenCanvas(t,i),this._canvasPool.length>0&&(this._canvasPool[this._nextCanvasIndex]=r),n=!0),this._canvasPool.length>0&&(this._nextCanvasIndex=(this._nextCanvasIndex+1)%this._canvasPool.length);const s=r.getContext("2d",{alpha:this._alpha||ce()});y(s),s.resetTransform(),n||(!this._alpha&&ce()?(s.fillStyle="black",s.fillRect(0,0,t,i)):s.clearRect(0,0,t,i)),e.drawWithFit(s,{fit:this._fit,rotation:this._rotation,crop:this._crop});const a={canvas:r,timestamp:e.timestamp,duration:e.duration};return e.close(),a}getCanvas(e,t){return d(this,null,function*(){$s(e),yield this._ensureInit();const i=yield this._videoSampleSink.getSample(e,t);return i&&this._videoSampleToWrappedCanvas(i)})}canvases(e=0,t=1/0,i){return f(this,null,function*(){yield new h(this._ensureInit()),yield*m(X(this._videoSampleSink.samples(e,t,i),e=>this._videoSampleToWrappedCanvas(e)))})}canvasesAtTimestamps(e,t){return f(this,null,function*(){yield new h(this._ensureInit()),yield*m(X(this._videoSampleSink.samplesAtTimestamps(e,t),e=>e&&this._videoSampleToWrappedCanvas(e)))})}}class na extends Ys{constructor(e,t,i,r){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new se,this.customDecoderQueueSize=0,this.currentTimestamp=null;const n=t=>{(null===this.currentTimestamp||Math.abs(t.timestamp-this.currentTimestamp)>=t.duration)&&(this.currentTimestamp=t.timestamp);const i=this.currentTimestamp;if(this.currentTimestamp+=t.duration,0===t.numberOfFrames)return void t.close();const n=r.sampleRate;t.setTimestamp(Math.round(i*n)/n),e(t)},s=js.find(e=>e.supports(i,r));if(s)this.customDecoder=new s,this.customDecoder.codec=i,this.customDecoder.config=r,this.customDecoder.onSample=e=>{if(!(e instanceof Ls))throw new TypeError("The argument passed to onSample must be an AudioSample.");n(e)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{const e=new Error("Decoding error").stack;this.decoder=new AudioDecoder({output:e=>{try{n(new Ls(e))}catch(t){this.onError(t)}},error:t=>{t.stack=e,this.onError(t)}}),this.decoder.configure(r)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(y(this.decoder),this.decoder.decodeQueueSize)}decode(e){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--)):(y(this.decoder),this.decoder.decode(e.toEncodedAudioChunk()))}flush(){return this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(y(this.decoder),this.decoder.flush())}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(y(this.decoder),this.decoder.close())}}class sa extends Ys{constructor(e,t,i){super(e,t),this.decoderConfig=i,this.currentTimestamp=null,y(De.includes(i.codec)),this.codec=i.codec;const{dataType:r,sampleSize:n,littleEndian:s}=He(this.codec);switch(this.inputSampleSize=n,n){case 1:"unsigned"===r?this.readInputValue=(e,t)=>e.getUint8(t)-o(2,7):"signed"===r?this.readInputValue=(e,t)=>e.getInt8(t):"ulaw"===r?this.readInputValue=(e,t)=>(e=>{let t=0,i=0,r=~e;128&r&&(r&=-129,t=-1),i=5+((240&r)>>4);const n=(1<(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)-o(2,15):"signed"===r?this.readInputValue=(e,t)=>e.getInt16(t,s):y(!1);break;case 3:"unsigned"===r?this.readInputValue=(e,t)=>K(e,t,s)-o(2,23):"signed"===r?this.readInputValue=(e,t)=>((e,t,i)=>K(e,t,i)<<8>>8)(e,t,s):y(!1);break;case 4:"unsigned"===r?this.readInputValue=(e,t)=>e.getUint32(t,s)-o(2,31):"signed"===r?this.readInputValue=(e,t)=>e.getInt32(t,s):"float"===r?this.readInputValue=(e,t)=>e.getFloat32(t,s):y(!1);break;case 8:"float"===r?this.readInputValue=(e,t)=>e.getFloat64(t,s):y(!1);break;default:H(n),y(!1)}switch(n){case 1:"ulaw"===r||"alaw"===r?(this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(e,t,i)=>e.setInt16(t,i,!0)):(this.outputSampleSize=1,this.outputFormat="u8",this.writeOutputValue=(e,t,i)=>e.setUint8(t,i+o(2,7)));break;case 2:this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(e,t,i)=>e.setInt16(t,i,!0);break;case 3:this.outputSampleSize=4,this.outputFormat="s32",this.writeOutputValue=(e,t,i)=>e.setInt32(t,i<<8,!0);break;case 4:this.outputSampleSize=4,"float"===r?(this.outputFormat="f32",this.writeOutputValue=(e,t,i)=>e.setFloat32(t,i,!0)):(this.outputFormat="s32",this.writeOutputValue=(e,t,i)=>e.setInt32(t,i,!0));break;case 8:this.outputSampleSize=4,this.outputFormat="f32",this.writeOutputValue=(e,t,i)=>e.setFloat32(t,i,!0);break;default:H(n),y(!1)}}getDecodeQueueSize(){return 0}decode(e){const t=P(e.data),i=e.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize,r=i*this.decoderConfig.numberOfChannels*this.outputSampleSize,n=new ArrayBuffer(r),s=new DataView(n);for(let c=0;c=a)&&(this.currentTimestamp=e.timestamp);const o=this.currentTimestamp;this.currentTimestamp+=a;const l=new Ls({format:this.outputFormat,data:n,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:i,timestamp:o});this.onSample(l)}flush(){return d(this,null,function*(){})}close(){}}class aa extends Js{constructor(e){if(!(e instanceof ha))throw new TypeError("audioTrack must be an InputAudioTrack.");super(),this._track=e}_createDecoder(e,t){return d(this,null,function*(){if(!(yield this._track.canDecode()))throw new Error("This audio track cannot be decoded by this browser. Make sure to check decodability before using a track.");const i=yield this._track.getCodec(),r=yield this._track.getDecoderConfig();return y(i&&r),De.includes(r.codec)?new sa(e,t,r):new na(e,t,i,r)})}_createPacketSink(){return new Gs(this._track)}getSample(e){return d(this,arguments,function*(e,t={}){$s(e);try{for(var i,r,n,s=p(this.mediaSamplesAtTimestamps([e],t));i=!(r=yield s.next()).done;i=!1){return r.value}}catch(r){n=[r]}finally{try{i&&(r=s.return)&&(yield r.call(s))}finally{if(n)throw n[0]}}throw new Error("Internal error: Iterator returned nothing.")})}samples(e=0,t=1/0,i={}){return this.mediaSamplesInRange(e,t,i)}samplesAtTimestamps(e,t={}){return this.mediaSamplesAtTimestamps(e,t)}}class oa{constructor(e){if(!(e instanceof ha))throw new TypeError("audioTrack must be an InputAudioTrack.");this._audioSampleSink=new aa(e)}_audioSampleToWrappedArrayBuffer(e){const t={buffer:e.toAudioBuffer(),timestamp:e.timestamp,duration:e.duration};return e.close(),t}getBuffer(e,t){return d(this,null,function*(){$s(e);const i=yield this._audioSampleSink.getSample(e,t);return i&&this._audioSampleToWrappedArrayBuffer(i)})}buffers(e=0,t=1/0,i){return X(this._audioSampleSink.samples(e,t,i),e=>this._audioSampleToWrappedArrayBuffer(e))}buffersAtTimestamps(e,t){return X(this._audioSampleSink.samplesAtTimestamps(e,t),e=>e&&this._audioSampleToWrappedArrayBuffer(e))}}class la{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof da}isAudioTrack(){return this instanceof ha}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}getInternalCodecId(){return d(this,null,function*(){return this._backing.getInternalCodecId()})}get internalCodecId(){return ca(this._backing.getInternalCodecId(),"internalCodecId","getInternalCodecId")}getLanguageCode(){return d(this,null,function*(){return this._backing.getLanguageCode()})}get languageCode(){return ca(this._backing.getLanguageCode(),"languageCode","getLanguageCode")}getName(){return d(this,null,function*(){return this._backing.getName()})}get name(){return ca(this._backing.getName(),"name","getName")}getTimeResolution(){return d(this,null,function*(){return this._backing.getTimeResolution()})}get timeResolution(){return ca(this._backing.getTimeResolution(),"timeResolution","getTimeResolution")}isRelativeToUnixEpoch(){return d(this,null,function*(){return this._backing.isRelativeToUnixEpoch()})}getDisposition(){return d(this,null,function*(){return this._backing.getDisposition()})}get disposition(){return ca(this._backing.getDisposition(),"disposition","getDisposition")}getBitrate(){return d(this,null,function*(){return this._backing.getBitrate()})}getAverageBitrate(){return d(this,null,function*(){return this._backing.getAverageBitrate()})}getFirstTimestamp(){return d(this,null,function*(){var e;const t=yield this._backing.getFirstPacket({metadataOnly:!0});return null!=(e=null==t?void 0:t.timestamp)?e:0})}computeDuration(e){return d(this,null,function*(){var t,i;const r=yield this._backing.getPacket(1/0,c({metadataOnly:!0},e)),n=(null!=(t=null==r?void 0:r.timestamp)?t:0)+(null!=(i=null==r?void 0:r.duration)?i:0);return Y(n,yield this.getTimeResolution())})}getDurationFromMetadata(){return d(this,arguments,function*(e={}){return this._backing.getDurationFromMetadata(e)})}computePacketStats(e=1/0,t){return d(this,null,function*(){const i=new Gs(this);let r=1/0,n=-1/0,s=0,a=0;try{for(var o,l,u,d=p(i.packets(void 0,void 0,c({metadataOnly:!0},t)));o=!(l=yield d.next()).done;o=!1){const t=l.value;if(s>=e&&t.timestamp>=n)break;r=Math.min(r,t.timestamp),n=Math.max(n,t.timestamp+t.duration),s++,a+=t.byteLength}}catch(l){u=[l]}finally{try{o&&(l=d.return)&&(yield l.call(d))}finally{if(u)throw u[0]}}return{packetCount:s,averagePacketRate:s?Number((s/(n-r)).toPrecision(16)):0,averageBitrate:s?Number((8*a/(n-r)).toPrecision(16)):0}})}isLive(){return d(this,null,function*(){return null!==(yield this._backing.getLiveRefreshInterval())})}getLiveRefreshInterval(){return d(this,null,function*(){return this._backing.getLiveRefreshInterval()})}canBePairedWith(e){if(!(e instanceof la))throw new TypeError("other must be an InputTrack.");return this.input===e.input&&this!==e&&(this._backing.getPairingMask()&e._backing.getPairingMask())!==BigInt("0")}getPairableTracks(e){return d(this,null,function*(){return this.input.getTracks(ga({filter:e=>e.canBePairedWith(this)},e))})}getPairableVideoTracks(e){return d(this,null,function*(){return this.input.getVideoTracks(ga({filter:e=>e.canBePairedWith(this)},e))})}getPairableAudioTracks(e){return d(this,null,function*(){return this.input.getAudioTracks(ga({filter:e=>e.canBePairedWith(this)},e))})}getPrimaryPairableVideoTrack(e){return d(this,null,function*(){return this.input.getPrimaryVideoTrack(ga({filter:e=>e.canBePairedWith(this)},e))})}getPrimaryPairableAudioTrack(e){return d(this,null,function*(){return this.input.getPrimaryAudioTrack(ga({filter:e=>e.canBePairedWith(this)},e))})}hasPairableTrack(e){return d(this,null,function*(){e&&(e=ua(e));const t=yield this.input.getTracks();for(const i of t)if(this.canBePairedWith(i)&&(!e||(yield e(i))))return!0;return!1})}hasPairableVideoTrack(e){return e&&(e=ua(e)),this.hasPairableTrack(t=>d(this,null,function*(){return t.isVideoTrack()&&(!e||(yield e(t)))}))}hasPairableAudioTrack(e){return e&&(e=ua(e)),this.hasPairableTrack(t=>d(this,null,function*(){return t.isAudioTrack()&&(!e||(yield e(t)))}))}}const ca=(e,t,i)=>{if(e instanceof Promise)throw new Error(`'${t}' is deprecated and not available synchronously for this track. Use the preferred '${i}()' instead.`);return e},ua=e=>{if(void 0!==e&&"function"!==typeof e)throw new TypeError("predicate, when provided, must be a function.");return e?t=>{const i=e=>{if("boolean"!==typeof e)throw new TypeError("predicate must return or resolve to a boolean value.");return e},r=e(t);return r instanceof Promise?r.then(i):i(r)}:void 0};class da extends la{constructor(e,t){super(e,t),this._pixelAspectRatioCache=null,this._backing=t}get type(){return"video"}getCodec(){return d(this,null,function*(){return this._backing.getCodec()})}get codec(){return ca(this._backing.getCodec(),"codec","getCodec")}hasOnlyKeyPackets(){return d(this,null,function*(){var e,t,i;return null!=(i=yield null==(t=(e=this._backing).getHasOnlyKeyPackets)?void 0:t.call(e))&&i})}getCodedWidth(){return d(this,null,function*(){return this._backing.getCodedWidth()})}get codedWidth(){return ca(this._backing.getCodedWidth(),"codedWidth","getCodedWidth")}getCodedHeight(){return d(this,null,function*(){return this._backing.getCodedHeight()})}get codedHeight(){return ca(this._backing.getCodedHeight(),"codedHeight","getCodedHeight")}getRotation(){return d(this,null,function*(){return this._backing.getRotation()})}get rotation(){return ca(this._backing.getRotation(),"rotation","getRotation")}getSquarePixelWidth(){return d(this,null,function*(){return this._backing.getSquarePixelWidth()})}get squarePixelWidth(){return ca(this._backing.getSquarePixelWidth(),"squarePixelWidth","getSquarePixelWidth")}getSquarePixelHeight(){return d(this,null,function*(){return this._backing.getSquarePixelHeight()})}get squarePixelHeight(){return ca(this._backing.getSquarePixelHeight(),"squarePixelHeight","getSquarePixelHeight")}getPixelAspectRatio(){return d(this,null,function*(){var e;return null!=(e=this._pixelAspectRatioCache)?e:this._pixelAspectRatioCache=ve({num:(yield this.getSquarePixelWidth())*(yield this.getCodedHeight()),den:(yield this.getSquarePixelHeight())*(yield this.getCodedWidth())})})}get pixelAspectRatio(){var e;return null!=(e=this._pixelAspectRatioCache)?e:this._pixelAspectRatioCache=ve({num:ca(this._backing.getSquarePixelWidth(),"pixelAspectRatio","getPixelAspectRatio")*ca(this._backing.getCodedHeight(),"pixelAspectRatio","getPixelAspectRatio"),den:ca(this._backing.getSquarePixelHeight(),"pixelAspectRatio","getPixelAspectRatio")*ca(this._backing.getCodedWidth(),"pixelAspectRatio","getPixelAspectRatio")})}getDisplayWidth(){return d(this,null,function*(){var e,t;const i=yield null==(t=(e=this._backing).getMetadataDisplayWidth)?void 0:t.call(e);if(null!=i)return i;return(yield this.getRotation())%180===0?this.getSquarePixelWidth():this.getSquarePixelHeight()})}get displayWidth(){var e,t;const i=null==(t=(e=this._backing).getMetadataDisplayWidth)?void 0:t.call(e);if(void 0!==i){const e=ca(i,"displayWidth","getDisplayWidth");if(null!==e)return e}const r=ca(this._backing.getRotation(),"displayWidth","getDisplayWidth")%180===0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight();return ca(r,"displayWidth","getDisplayWidth")}getDisplayHeight(){return d(this,null,function*(){var e,t;const i=yield null==(t=(e=this._backing).getMetadataDisplayHeight)?void 0:t.call(e);if(null!=i)return i;return(yield this.getRotation())%180===0?this.getSquarePixelHeight():this.getSquarePixelWidth()})}get displayHeight(){var e,t;const i=null==(t=(e=this._backing).getMetadataDisplayHeight)?void 0:t.call(e);if(void 0!==i){const e=ca(i,"displayHeight","getDisplayHeight");if(null!==e)return e}const r=ca(this._backing.getRotation(),"displayHeight","getDisplayHeight")%180===0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth();return ca(r,"displayHeight","getDisplayHeight")}getColorSpace(){return d(this,null,function*(){return this._backing.getColorSpace()})}hasHighDynamicRange(){return d(this,null,function*(){const e=yield this._backing.getColorSpace();return"bt2020"===e.primaries||"smpte432"===e.primaries||"pg"===e.transfer||"hlg"===e.transfer||"bt2020-ncl"===e.matrix})}canBeTransparent(){return d(this,null,function*(){return this._backing.canBeTransparent()})}getDecoderConfig(){return d(this,null,function*(){return this._backing.getDecoderConfig()})}getCodecParameterString(){return d(this,null,function*(){var e,t,i;const r=yield null==(t=(e=this._backing).getMetadataCodecParameterString)?void 0:t.call(e);if(null!=r)return r;const n=yield this._backing.getDecoderConfig();return null!=(i=null==n?void 0:n.codec)?i:null})}canDecode(){return d(this,null,function*(){try{const e=yield this._backing.getDecoderConfig();if(!e)return!1;const t=yield this._backing.getCodec();if(y(null!==t),Ks.some(i=>i.supports(t,e)))return!0;if("undefined"===typeof VideoDecoder)return!1;return!0===(yield VideoDecoder.isConfigSupported(e)).supported}catch(e){return console.error("Error during decodability check:",e),!1}})}determinePacketType(e){return d(this,null,function*(){if(!(e instanceof Yt))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("packet must not be metadata-only to determine its type.");const t=yield this.getCodec();if(null===t)return null;const i=yield this.getDecoderConfig();return y(i),Lt(t,i,e.data)})}}class ha extends la{constructor(e,t){super(e,t),this._backing=t}get type(){return"audio"}getCodec(){return d(this,null,function*(){return this._backing.getCodec()})}get codec(){return ca(this._backing.getCodec(),"codec","getCodec")}hasOnlyKeyPackets(){return d(this,null,function*(){var e,t,i;return null==(i=yield null==(t=(e=this._backing).getHasOnlyKeyPackets)?void 0:t.call(e))||i})}getNumberOfChannels(){return d(this,null,function*(){return this._backing.getNumberOfChannels()})}get numberOfChannels(){return ca(this._backing.getNumberOfChannels(),"numberOfChannels","getNumberOfChannels")}getSampleRate(){return d(this,null,function*(){return this._backing.getSampleRate()})}get sampleRate(){return ca(this._backing.getSampleRate(),"sampleRate","getSampleRate")}getDecoderConfig(){return d(this,null,function*(){return this._backing.getDecoderConfig()})}getCodecParameterString(){return d(this,null,function*(){var e,t,i;const r=yield null==(t=(e=this._backing).getMetadataCodecParameterString)?void 0:t.call(e);if(null!=r)return r;const n=yield this._backing.getDecoderConfig();return null!=(i=null==n?void 0:n.codec)?i:null})}canDecode(){return d(this,null,function*(){try{const e=yield this._backing.getDecoderConfig();if(!e)return!1;const t=yield this._backing.getCodec();if(y(null!==t),js.some(i=>i.supports(t,e)))return!0;if(e.codec.startsWith("pcm-"))return!0;if("undefined"===typeof AudioDecoder)return!1;return!0===(yield AudioDecoder.isConfigSupported(e)).supported}catch(e){return console.error("Error during decodability check:",e),!1}})}determinePacketType(e){return d(this,null,function*(){if(!(e instanceof Yt))throw new TypeError("packet must be an EncodedPacket.");return null===(yield this.getCodec())?null:"key"})}}const fa=e=>-(null!=e?e:-1/0),ma=e=>-e,pa=e=>{if("object"!==typeof e||!e)throw new TypeError("query must be an object.");if(void 0!==e.filter&&"function"!==typeof e.filter)throw new TypeError("query.filter, when provided, must be a function.");if(void 0!==e.sortBy&&"function"!==typeof e.sortBy)throw new TypeError("query.sortBy, when provided, must be a function.");return{filter:e.filter?t=>{const i=e=>{if("boolean"!==typeof e)throw new TypeError("query.filter must return or resolve to a boolean.");return e},r=e.filter(t);return r instanceof Promise?r.then(i):i(r)}:void 0,sortBy:e.sortBy?t=>{const i=e=>{if("number"!==typeof e&&(!Array.isArray(e)||!e.every(e=>"number"===typeof e)))throw new TypeError("query.sortBy must return or resolve to a number or an array of numbers.");return e},r=e.sortBy(t);return r instanceof Promise?r.then(i):i(r)}:void 0}},ga=(e,t)=>({filter:(null==e?void 0:e.filter)||(null==t?void 0:t.filter)?i=>{var r,n;const s=null==(n=null==(r=null==e?void 0:e.filter)?void 0:r.call(e,i))||n,a=e=>{var r,n;return!1!==e&&(null==(n=null==(r=null==t?void 0:t.filter)?void 0:r.call(t,i))||n)};return s instanceof Promise?s.then(a):a(s)}:void 0,sortBy:(null==e?void 0:e.sortBy)||(null==t?void 0:t.sortBy)?i=>{var r,n,s,a;const o=null!=(n=null==(r=null==e?void 0:e.sortBy)?void 0:r.call(e,i))?n:[],l=null!=(a=null==(s=null==t?void 0:t.sortBy)?void 0:s.call(t,i))?a:[],c=(e,t)=>[...Array.isArray(e)?e:[e],...Array.isArray(t)?t:[t]];return o instanceof Promise||l instanceof Promise?Promise.all([o,l]).then(([e,t])=>c(e,t)):c(o,l)}:void 0}),ka=(e,t)=>d(null,null,function*(){let i=e;if(null==t?void 0:t.filter){const r=e.map(e=>t.filter(e));if(r.some(e=>e instanceof Promise)){const t=yield Promise.all(r);i=e.filter((e,i)=>t[i])}else i=e.filter((e,t)=>r[t])}if(!(null==t?void 0:t.sortBy))return i;const r=i.map(e=>t.sortBy(e)),n=r.some(e=>e instanceof Promise)?yield Promise.all(r):r;return i.map((e,t)=>({track:e,sortValue:n[t]})).sort((e,t)=>{var i,r;const n=Array.isArray(e.sortValue)?e.sortValue:[e.sortValue],s=Array.isArray(t.sortValue)?t.sortValue:[t.sortValue],a=Math.max(n.length,s.length);for(let o=0;oe.track)});ke();const ya=2;let ba=null;"undefined"!==typeof FinalizationRegistry&&(ba=new FinalizationRegistry(e=>{for(const t of e)t.freed||t.free()}));class Ta extends Ie{get disposed(){return this._disposed}constructor(e){var t,i;if(super(),this._demuxerPromise=null,this._format=null,this._trackBackingsCache=null,this._backingToTrack=new Map,this._disposed=!1,this._nextSourceCacheAge=0,this._sourceRefs=[],this._sourceCache=[],this._sourceCachePromises=[],this._onFormatDetermined=null,!e||"object"!==typeof e)throw new TypeError("options must be an object.");if(!Array.isArray(e.formats)||e.formats.some(e=>!(e instanceof Jn)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof xn||e.source instanceof Cn))throw new TypeError("options.source must be a Source or SourceRef.");if(e.source instanceof xn&&e.source._disposed)throw new TypeError("options.source must not be a disposed Source.");if(void 0!==e.initInput&&!(e.initInput instanceof Ta))throw new TypeError("options.initInput, when provided, must be an Input.");void 0!==e.formatOptions&&((e,t)=>{if(!e||"object"!==typeof e)throw new TypeError(`${t}, when provided, must be an object.`);if(void 0!==e.isobmff){if(!e.isobmff||"object"!==typeof e.isobmff)throw new TypeError(`${t}.isobmff, when provided, must be an object.`);if(void 0!==e.isobmff.resolveKeyId&&"function"!==typeof e.isobmff.resolveKeyId)throw new TypeError(`${t}.isobmff.resolveKeyId, when provided, must be a function.`)}})(e.formatOptions,"formatOptions"),this._formats=e.formats,this._initInput=null!=(t=e.initInput)?t:null,this._formatOptions=null!=(i=e.formatOptions)?i:{},e.source instanceof xn?this._rootRef=e.source.ref():this._rootRef=e.source,this._sourceRefs.push(this._rootRef),null==ba||ba.register(this,this._sourceRefs,this)}get _rootSource(){return this._rootRef.source}_getSourceUncached(e){return d(this,null,function*(){y(this._rootSource instanceof Bn);const t=yield this._rootSource._resolveRequest(e);return this._emit("source",{source:t.source,request:e,isRoot:e.isRoot}),t})}_getSourceCached(e,t=1){const i=this._sourceCache.find(i=>i.cacheGroup===t&&En(i.request,e));if(i)return i.age++,Promise.resolve(i.sourceRef.source.ref());const r=this._sourceCachePromises.find(i=>i.cacheGroup===t&&En(i.request,e));if(r)return r.promise.then(e=>e.sourceRef.source.ref());const n=(()=>d(this,null,function*(){const i=yield this._getSourceUncached(e);if(Te(this._sourceCache,e=>e.cacheGroup===t&&1===e.sourceRef.source._refCount)>=4){const e=Se(this._sourceCache,e=>e.cacheGroup===t&&1===e.sourceRef.source._refCount?e.age:1/0);y(-1!==e);const i=this._sourceCache[e];this._sourceCache.splice(e,1),i.sourceRef.free(),((e,t)=>{const i=e.indexOf(t);-1!==i&&e.splice(i,1)})(this._sourceRefs,i.sourceRef)}this._sourceRefs.push(i);const r=this._sourceCachePromises.findIndex(t=>t.request===e);y(-1!==r),this._sourceCachePromises.splice(r,1);return{request:e,sourceRef:i,age:this._nextSourceCacheAge++,cacheGroup:t}}))();return this._sourceCachePromises.push({request:e,cacheGroup:t,promise:n}),n.then(e=>{const t=e.sourceRef.source.ref();return this._sourceCache.push(e),t})}_getDemuxer(){var e;return null!=(e=this._demuxerPromise)?e:this._demuxerPromise=(()=>d(this,null,function*(){var e;this._reader=new wa(this._rootSource),this._emit("source",{source:this._rootSource,request:null,isRoot:!0});for(const t of this._formats){if(yield t._canReadInput(this))return this._format=t,null==(e=this._onFormatDetermined)||e.call(this,t),t._createDemuxer(this)}throw new Sa}))()}get source(){return this._rootSource}getFormat(){return d(this,null,function*(){return yield this._getDemuxer(),y(this._format),this._format})}canRead(){return d(this,null,function*(){try{return yield this._getDemuxer(),!0}catch(e){if(e instanceof Sa)return!1;throw e}})}getFirstTimestamp(e){return d(this,null,function*(){null!=e||(e=yield this.getTracks());const t=e.filter(e=>null!==e);if(0===t.length)return 0;const i=yield Promise.all(t.map(e=>e.getFirstTimestamp()));return Math.min(...i)})}computeDuration(e,t){return d(this,null,function*(){null!=e||(e=yield this.getTracks());const i=e.filter(e=>null!==e);if(0===i.length)return 0;const r=yield Promise.all(i.map(e=>e.computeDuration(t)));return Math.max(...r)})}getDurationFromMetadata(e,t){return d(this,null,function*(){null!=e||(e=yield this.getTracks());const i=e.filter(e=>null!==e),r=(yield Promise.all(i.map(e=>e.getDurationFromMetadata(t)))).filter(e=>null!==e);return 0===r.length?null:Math.max(...r)})}getTracks(e){return d(this,null,function*(){e&&(e=pa(e));const t=(yield this._getTrackBackings()).map(e=>this._wrapBackingAsTrack(e));return ka(t,e)})}getVideoTracks(e){return d(this,null,function*(){e&&(e=pa(e));const t=(yield this.getTracks()).filter(e=>e.isVideoTrack());return ka(t,e)})}getAudioTracks(e){return d(this,null,function*(){e&&(e=pa(e));const t=(yield this.getTracks()).filter(e=>e.isAudioTrack());return ka(t,e)})}getPrimaryVideoTrack(e){return d(this,null,function*(){var t;e&&(e=pa(e));const i=ga(e,{sortBy:e=>d(null,null,function*(){return[ma((yield e.getDisposition()).default),ma(yield e.hasPairableAudioTrack()),ma(!(yield e.hasOnlyKeyPackets())),fa(yield e.getBitrate())]})});return null!=(t=(yield this.getVideoTracks(i))[0])?t:null})}getPrimaryAudioTrack(e){return d(this,null,function*(){var t;e&&(e=pa(e));const i=yield this.getPrimaryVideoTrack(),r=ga(e,{sortBy:e=>d(this,null,function*(){return[ma(!i||e.canBePairedWith(i)),ma((yield e.getDisposition()).default),fa(yield e.getBitrate())]})});return null!=(t=(yield this.getAudioTracks(r))[0])?t:null})}_getTrackBackings(){return d(this,null,function*(){var e;const t=yield this._getDemuxer();return null!=(e=this._trackBackingsCache)?e:this._trackBackingsCache=yield t.getTrackBackings()})}_wrapBackingAsTrack(e){const t=this._backingToTrack.get(e);if(t)return t;const i="video"===e.getType()?new da(this,e):new ha(this,e);return this._backingToTrack.set(e,i),i}getMimeType(){return d(this,null,function*(){return(yield this._getDemuxer()).getMimeType()})}getMetadataTags(){return d(this,null,function*(){return(yield this._getDemuxer()).getMetadataTags()})}dispose(){var e;if(!this._disposed){this._disposed=!0;for(const e of this._sourceRefs)e.free();this._sourceRefs.length=0,null==ba||ba.unregister(this),null==(e=this._demuxerPromise)||e.then(e=>e.dispose())}}[Symbol.dispose](){this.dispose()}}class Sa extends Error{constructor(e="Input has an unsupported or unrecognizable format."){super(e),this.name="UnsupportedInputFormatError"}}class va extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}}class wa{constructor(e){this.source=e}get fileSize(){const e=this.source._getFileSize();if(void 0===e)throw new Error("Reading file size too early; read required first.");return e}get fileSizeNonStrict(){var e;return null!=(e=this.source._getFileSize())?e:null}requestSlice(e,t){if(this.source._disposed)throw new va;if(e<0)return null;if(null!==this.fileSizeNonStrict&&e+t>this.fileSizeNonStrict)return null;if(0===t){const t=new Uint8Array(0);return new Pa(t,P(t),0,e,e)}const i=e+t,r=this.source._read(e,i,0,In);return r instanceof Promise?r.then(t=>t?new Pa(t.bytes,t.view,t.offset,e,i):null):r?new Pa(r.bytes,r.view,r.offset,e,i):null}requestSliceRange(e,t,i){if(this.source._disposed)throw new va;if(e<0)return null;if(null!==this.fileSizeNonStrict)return this.requestSlice(e,$(this.fileSizeNonStrict-e,t,i));{const r=this.requestSlice(e,i),n=r=>r||(y(null!==this.fileSizeNonStrict),this.requestSlice(e,$(this.fileSizeNonStrict-e,t,i)));return r instanceof Promise?r.then(n):n(r)}}requestEntireFile(){if(null!==this.fileSizeNonStrict)return this.requestSlice(0,this.fileSizeNonStrict);return(()=>d(this,null,function*(){const e=[];let t=0;for(;;){if(1===e.length&&null!==this.fileSizeNonStrict)return this.requestSlice(0,this.fileSizeNonStrict);const i=1024*e.length;let r=this.requestSliceRange(i,0,1024);if(r instanceof Promise&&(r=yield r),!r)break;e.push(xa(r,r.length)),t+=r.length}const i=new Uint8Array(t);let r=0;for(const n of e)i.set(n,r),r+=n.length;return new Pa(i,P(i),0,0,t)}))()}}class Pa{constructor(e,t,i,r,n){this.bytes=e,this.view=t,this.offset=i,this.start=r,this.end=n,this.bufferPos=r-i}static tempFromBytes(e){return new Pa(e,P(e),0,0,e.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos(e){this.bufferPos=e-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip(e){this.bufferPos+=e}slice(e,t=this.end-e){if(ethis.end)throw new RangeError("Slicing outside of original slice.");return new Pa(this.bytes,this.view,this.offset,e,e+t)}}const Ia=(e,t)=>{if(e.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.`)},xa=(e,t)=>{Ia(e,t);const i=e.bytes.subarray(e.bufferPos,e.bufferPos+t);return e.bufferPos+=t,i},Ca=e=>(Ia(e,1),e.view.getUint8(e.bufferPos++)),Ba=(e,t)=>{Ia(e,2);const i=e.view.getUint16(e.bufferPos,t);return e.bufferPos+=2,i},Ea=e=>{Ia(e,2);const t=e.view.getUint16(e.bufferPos,!1);return e.bufferPos+=2,t},_a=e=>{Ia(e,3);const t=K(e.view,e.bufferPos,!1);return e.bufferPos+=3,t},Aa=e=>{Ia(e,2);const t=e.view.getInt16(e.bufferPos,!1);return e.bufferPos+=2,t},Fa=(e,t)=>{Ia(e,4);const i=e.view.getUint32(e.bufferPos,t);return e.bufferPos+=4,i},Ra=e=>{Ia(e,4);const t=e.view.getUint32(e.bufferPos,!1);return e.bufferPos+=4,t},Da=e=>{Ia(e,4);const t=e.view.getUint32(e.bufferPos,!0);return e.bufferPos+=4,t},Ma=e=>{Ia(e,4);const t=e.view.getInt32(e.bufferPos,!1);return e.bufferPos+=4,t},Na=(e,t)=>{let i,r;return t?(i=Fa(e,!0),r=Fa(e,!0)):(r=Fa(e,!1),i=Fa(e,!1)),4294967296*r+i},Oa=e=>4294967296*Ra(e)+Ra(e),La=e=>4294967296*Ma(e)+Ra(e),za=e=>{const t=Da(e),i=(e=>{Ia(e,4);const t=e.view.getInt32(e.bufferPos,!0);return e.bufferPos+=4,t})(e);return 4294967296*i+t},Ua=e=>{Ia(e,4);const t=e.view.getFloat32(e.bufferPos,!1);return e.bufferPos+=4,t},qa=e=>{Ia(e,8);const t=e.view.getFloat64(e.bufferPos,!1);return e.bufferPos+=8,t},Wa=(e,t)=>{Ia(e,t);let i="";for(let r=0;rI.decode(xa(e,t)).split("\n").map(e=>e.trim()).filter(e=>{var t;return e.length>0&&!(null==(t=null==i?void 0:i.ignore)?void 0:t.call(i,e))});var Ha,Ka,ja,Xa;(Ka=Ha||(Ha={}))[Ka.Unsynchronisation=128]="Unsynchronisation",Ka[Ka.ExtendedHeader=64]="ExtendedHeader",Ka[Ka.ExperimentalIndicator=32]="ExperimentalIndicator",Ka[Ka.Footer=16]="Footer",(Xa=ja||(ja={}))[Xa.ISO_8859_1=0]="ISO_8859_1",Xa[Xa.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",Xa[Xa.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",Xa[Xa.UTF_8=3]="UTF_8";const $a=128,Qa=10,Ga=["Blues","Classic rock","Country","Dance","Disco","Funk","Grunge","Hip-hop","Jazz","Metal","New age","Oldies","Other","Pop","Rhythm and blues","Rap","Reggae","Rock","Techno","Industrial","Alternative","Ska","Death metal","Pranks","Soundtrack","Euro-techno","Ambient","Trip-hop","Vocal","Jazz & funk","Fusion","Trance","Classical","Instrumental","Acid","House","Game","Sound clip","Gospel","Noise","Alternative rock","Bass","Soul","Punk","Space","Meditative","Instrumental pop","Instrumental rock","Ethnic","Gothic","Darkwave","Techno-industrial","Electronic","Pop-folk","Eurodance","Dream","Southern rock","Comedy","Cult","Gangsta","Top 40","Christian rap","Pop/funk","Jungle music","Native US","Cabaret","New wave","Psychedelic","Rave","Showtunes","Trailer","Lo-fi","Tribal","Acid punk","Acid jazz","Polka","Retro","Musical","Rock 'n' roll","Hard rock","Folk","Folk rock","National folk","Swing","Fast fusion","Bebop","Latin","Revival","Celtic","Bluegrass","Avantgarde","Gothic rock","Progressive rock","Psychedelic rock","Symphonic rock","Slow rock","Big band","Chorus","Easy listening","Acoustic","Humour","Speech","Chanson","Opera","Chamber music","Sonata","Symphony","Booty bass","Primus","Porn groove","Satire","Slow jam","Club","Tango","Samba","Folklore","Ballad","Power ballad","Rhythmic Soul","Freestyle","Duet","Punk rock","Drum solo","A cappella","Euro-house","Dance hall","Goa music","Drum & bass","Club-house","Hardcore techno","Terror","Indie","Britpop","Negerpunk","Polsk punk","Beat","Christian gangsta rap","Heavy metal","Black metal","Crossover","Contemporary Christian","Christian rock","Merengue","Salsa","Thrash metal","Anime","Jpop","Synthpop","Christmas","Art rock","Baroque","Bhangra","Big beat","Breakbeat","Chillout","Downtempo","Dub","EBM","Eclectic","Electro","Electroclash","Emo","Experimental","Garage","Global","IDM","Illbient","Industro-Goth","Jam Band","Krautrock","Leftfield","Lounge","Math rock","New romantic","Nu-breakz","Post-punk","Post-rock","Psytrance","Shoegaze","Space rock","Trop rock","World music","Neoclassical","Audiobook","Audio theatre","Neue Deutsche Welle","Podcast","Indie rock","G-Funk","Dubstep","Garage rock","Psybient"],Ya=(e,t)=>{var i;const r=e.filePos;null!=t.raw||(t.raw={}),null!=(i=t.raw).TAG||(i.TAG=xa(e,$a-3)),e.filePos=r;const n=Ja(e,30);n&&(null!=t.title||(t.title=n));const s=Ja(e,30);s&&(null!=t.artist||(t.artist=s));const a=Ja(e,30);a&&(null!=t.album||(t.album=a));const o=Ja(e,4),l=Number.parseInt(o,10);Number.isInteger(l)&&l>0&&(null!=t.date||(t.date=new Date(l,0,1)));const c=xa(e,30);let u;if(0===c[28]&&0!==c[29]){const i=c[29];i>0&&(null!=t.trackNumber||(t.trackNumber=i)),e.skip(-30),u=Ja(e,28),e.skip(2)}else e.skip(-30),u=Ja(e,30);u&&(null!=t.comment||(t.comment=u));const d=Ca(e);d{const i=xa(e,t),r=me(i.indexOf(0),i.length),n=i.subarray(0,r);let s="";for(let a=0;a{const t=e.filePos,i=Wa(e,3),r=Ca(e),n=Ca(e),s=Ca(e),a=Ra(e);if("ID3"!==i||255===r||255===n||0!==(2155905152&a))return e.filePos=t,null;return{majorVersion:r,revision:n,flags:s,size:Je(a)}},eo=(e,t,i)=>{var r,n,s,a,o,l;if(![2,3,4].includes(t.majorVersion))return void console.warn(`Unsupported ID3v2 major version: ${t.majorVersion}`);const c=xa(e,t.size),u=new to(t,c);if(t.flags&Ha.Footer&&u.removeFooter(),t.flags&Ha.Unsynchronisation&&3===t.majorVersion&&u.ununsynchronizeAll(),t.flags&Ha.ExtendedHeader){const e=u.readU32();3===t.majorVersion?u.pos+=e:u.pos+=e-4}for(;u.pos<=u.bytes.length-u.frameHeaderSize();){const e=u.readId3V2Frame();if(!e)break;const c=u.pos,d=u.pos+e.size;let h=!1,f=!1,m=!1;if(3===t.majorVersion?(h=!!(64&e.flags),f=!!(128&e.flags)):4===t.majorVersion&&(h=!!(4&e.flags),f=!!(8&e.flags),m=!!(2&e.flags)||!!(t.flags&Ha.Unsynchronisation)),h)console.warn(`Skipping encrypted ID3v2 frame ${e.id}`),u.pos=d;else if(f)console.warn(`Skipping compressed ID3v2 frame ${e.id}`),u.pos=d;else{if(m&&u.ununsynchronizeRegion(u.pos,d),null!=i.raw||(i.raw={}),"TXXX"===e.id){const e=null!=(n=(r=i.raw).TXXX)?n:r.TXXX={},t=u.readId3V2TextEncoding(),s=u.readId3V2Text(t,d),a=u.readId3V2Text(t,d);null!=e[s]||(e[s]=a)}else"T"===e.id[0]?null!=(s=i.raw)[a=e.id]||(s[a]=u.readId3V2EncodingAndText(d)):null!=(o=i.raw)[l=e.id]||(o[l]=u.readBytes(e.size));switch(u.pos=c,e.id){case"TIT2":case"TT2":null!=i.title||(i.title=u.readId3V2EncodingAndText(d));break;case"TIT3":case"TT3":null!=i.description||(i.description=u.readId3V2EncodingAndText(d));break;case"TPE1":case"TP1":null!=i.artist||(i.artist=u.readId3V2EncodingAndText(d));break;case"TALB":case"TAL":null!=i.album||(i.album=u.readId3V2EncodingAndText(d));break;case"TPE2":case"TP2":null!=i.albumArtist||(i.albumArtist=u.readId3V2EncodingAndText(d));break;case"TRCK":case"TRK":{const e=u.readId3V2EncodingAndText(d).split("/"),t=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(null!=i.trackNumber||(i.trackNumber=t)),r&&Number.isInteger(r)&&r>0&&(null!=i.tracksTotal||(i.tracksTotal=r))}break;case"TPOS":case"TPA":{const e=u.readId3V2EncodingAndText(d).split("/"),t=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(null!=i.discNumber||(i.discNumber=t)),r&&Number.isInteger(r)&&r>0&&(null!=i.discsTotal||(i.discsTotal=r))}break;case"TCON":case"TCO":{const e=u.readId3V2EncodingAndText(d);let t=/^\((\d+)\)/.exec(e);if(t){const e=Number.parseInt(t[1]);if(void 0!==Ga[e]){null!=i.genre||(i.genre=Ga[e]);break}}if(t=/^\d+$/.exec(e),t){const e=Number.parseInt(t[0]);if(void 0!==Ga[e]){null!=i.genre||(i.genre=Ga[e]);break}}null!=i.genre||(i.genre=e)}break;case"TDRC":case"TDAT":{const e=u.readId3V2EncodingAndText(d),t=new Date(e);Number.isNaN(t.getTime())||null!=i.date||(i.date=t)}break;case"TYER":case"TYE":{const e=u.readId3V2EncodingAndText(d),t=Number.parseInt(e,10);Number.isInteger(t)&&(null!=i.date||(i.date=new Date(t,0,1)))}break;case"USLT":case"ULT":{const e=u.readU8();u.pos+=3,u.readId3V2Text(e,d),null!=i.lyrics||(i.lyrics=u.readId3V2Text(e,d))}break;case"COMM":case"COM":{const e=u.readU8();u.pos+=3,u.readId3V2Text(e,d),null!=i.comment||(i.comment=u.readId3V2Text(e,d))}break;case"APIC":case"PIC":{const e=u.readId3V2TextEncoding();let r;if(2===t.majorVersion){const e=u.readAscii(3);r="PNG"===e?"image/png":"JPG"===e?"image/jpeg":"image/*"}else r=u.readId3V2Text(e,d);const n=u.readU8(),s=u.readId3V2Text(e,d).trimEnd(),a=d-u.pos;if(a>=0){const e=u.readBytes(a);i.images||(i.images=[]),i.images.push({data:e,mimeType:r,kind:3===n?"coverFront":4===n?"coverBack":"unknown",description:s})}}break;default:u.pos+=e.size}u.pos=d}}};class to{constructor(e,t){this.header=e,this.bytes=t,this.pos=0,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength)}frameHeaderSize(){return 2===this.header.majorVersion?6:10}ununsynchronizeAll(){const e=[];for(let t=0;t{const t=this.pos+e;if(t>this.bytes.length)return!1;if(t<=this.bytes.length-this.frameHeaderSize()){this.pos+=e;const t=this.readAscii(4);if("\0\0\0\0"!==t&&!/[0-9A-Z]{4}/.test(t))return!1}return!0};if(!s(i)){const e=4===this.header.majorVersion?t:Je(t);s(e)&&(i=e)}return this.pos=n,{id:e,size:i,flags:r}}}readId3V2TextEncoding(){const e=this.readU8();if(e>3)throw new Error(`Unsupported text encoding: ${e}`);return e}readId3V2Text(e,t){const i=this.pos,r=this.readBytes(t-this.pos);switch(e){case ja.ISO_8859_1:{let e="";for(let t=0;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=me(r.findIndex((e,t)=>0===e&&0===r[t+1]&&t%2===0),r.length);return this.pos=i+Math.min(t+2,r.length),e.decode(r.subarray(2,t))}{const e=me(r.findIndex(e=>0===e),r.length);return this.pos=i+Math.min(e+1,r.length),I.decode(r.subarray(0,e))}case ja.UTF_16_BE_NO_BOM:{const e=new TextDecoder("utf-16be"),t=me(r.findIndex((e,t)=>0===e&&0===r[t+1]&&t%2===0),r.length);return this.pos=i+Math.min(t+2,r.length),e.decode(r.subarray(0,t))}case ja.UTF_8:{const e=me(r.findIndex(e=>0===e),r.length);return this.pos=i+Math.min(e+1,r.length),I.decode(r.subarray(0,e))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";const t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}}class io{constructor(e){this.events=e,this.input=null,this.audioSink=null,this.audioIterator=null,this.audioContext=null,this.gainNode=null,this.audioContextStartTime=0,this.playbackTimeAtStart=0,this.latestScheduledEndTime=0,this.duration=Number.NaN,this.paused=!0,this.volume=.7,this.muted=!1,this.playbackRate=1,this.asyncId=0,this.queuedNodes=new Set}get currentTime(){return this.paused?this.playbackTimeAtStart:(this.audioContext.currentTime-this.audioContextStartTime)*this.playbackRate+this.playbackTimeAtStart}ensureAudioContext(e){if(this.audioContext)return;const t=window.AudioContext||window.webkitAudioContext;try{this.audioContext=new t({sampleRate:e})}catch(i){this.audioContext=new t}this.gainNode=this.audioContext.createGain(),this.gainNode.connect(this.audioContext.destination),this.updateGain()}updateGain(){if(!this.gainNode)return;const e=this.muted?0:this.volume;this.gainNode.gain.value=e*e}stopQueuedNodes(){this.queuedNodes.forEach(e=>e.stop()),this.queuedNodes.clear()}stopIterator(){return d(this,null,function*(){var e;yield null==(e=this.audioIterator)?void 0:e.return(),this.audioIterator=null})}handleNoAudioTrack(){this.audioSink=null,this.ensureAudioContext()}load(e,t){return d(this,null,function*(){++this.asyncId,yield this.stopIterator(),this.stopQueuedNodes(),this.paused=!0,this.playbackTimeAtStart=0,this.audioContextStartTime=0;const{input:i,audioTrack:r,duration:n}=e;return this.input=i,this.duration=n,r?null!==r.codec&&(yield r.canDecode())?(this.ensureAudioContext(r.sampleRate),this.audioSink=new oa(r),void(null==t||t())):(this.audioSink=null,this.ensureAudioContext(),void(null==t||t())):(this.handleNoAudioTrack(),void(null==t||t()))})}runIterator(e){return d(this,null,function*(){if(this.audioSink)for(yield this.stopIterator(),this.audioIterator=this.audioSink.buffers(this.currentTime);;){if(e!==this.asyncId||this.paused)return;const i=this.audioIterator.next(),r=setInterval(()=>{e!==this.asyncId||this.paused?clearInterval(r):"running"===this.audioContext.state&&this.audioContext.currentTime>=this.latestScheduledEndTime-.2&&(this.audioContext.suspend(),this.events.emit("waiting"))},50);let n;try{n=yield i}catch(t){console.error("Audio iterator error:",t);break}finally{clearInterval(r)}if(e!==this.asyncId||this.paused)return;if("suspended"===this.audioContext.state&&(yield this.audioContext.resume(),this.events.emit("canplay"),this.events.emit("playing")),n.done)break;const{buffer:s,timestamp:a}=n.value,o=this.audioContext.createBufferSource();o.buffer=s,o.connect(this.gainNode),o.playbackRate.value=this.playbackRate;const l=this.audioContextStartTime+(a-this.playbackTimeAtStart)/this.playbackRate,c=l+s.duration/this.playbackRate;c>this.latestScheduledEndTime&&(this.latestScheduledEndTime=c),l>=this.audioContext.currentTime?o.start(l):o.start(this.audioContext.currentTime,(this.audioContext.currentTime-l)*this.playbackRate),this.queuedNodes.add(o),o.onended=()=>this.queuedNodes.delete(o)}})}play(){return d(this,null,function*(){if(!this.paused)return;this.audioContext||this.ensureAudioContext(),"suspended"===this.audioContext.state&&(yield this.audioContext.resume()),this.audioContextStartTime=this.audioContext.currentTime,this.latestScheduledEndTime=this.audioContextStartTime,this.paused=!1;const e=++this.asyncId;this.runIterator(e)})}pause(){this.paused||(this.playbackTimeAtStart=this.currentTime,this.paused=!0,this.stopIterator(),this.stopQueuedNodes())}seek(e){return d(this,null,function*(){this.playbackTimeAtStart=Math.max(0,e),this.audioContextStartTime=this.audioContext.currentTime,this.latestScheduledEndTime=this.audioContextStartTime;const t=++this.asyncId;this.paused||this.runIterator(t)})}setVolume(e,t){this.volume=e,this.muted=t,this.updateGain()}setPlaybackRate(e){if(e!==this.playbackRate&&(this.paused||(this.playbackTimeAtStart=this.currentTime,this.audioContextStartTime=this.audioContext.currentTime),this.playbackRate=e,!this.paused)){const e=++this.asyncId;this.runIterator(e)}}destroy(){var e;this.asyncId++,this.pause(),null==(e=this.audioContext)||e.close(),this.audioContext=null,this.input=null,this.audioSink=null}}const ro=/\.m3u8(?:$|[?#])/i;function no(e){return"string"===typeof e&&ro.test(e)}function so(e){const t=function(e){return"string"===typeof e?new Mn(e):e instanceof Blob?new An(e):"undefined"!==typeof ReadableStream&&e instanceof ReadableStream?new Nn(e):null!=e?e:null}(e);return t?new Ta({source:t,formats:no(e)?ws:vs}):null}function ao(e){return d(this,arguments,function*({input:e,videoTrack:t,audioTrack:i}){const r=[t,i].filter(Boolean),n=t||i,s=Boolean(n&&(yield n.isLive()));let a=Number.NaN;return r.length>0&&(a=yield e.getDurationFromMetadata(r,{skipLiveWait:!0}),null!==a||s||(a=yield e.computeDuration(r,{skipLiveWait:!0}))),s?Number.POSITIVE_INFINITY:null!=a?a:Number.NaN})}function oo(e){return d(this,null,function*(){var t,i;return null!=(i=null!=(t=yield e.getAverageBitrate())?t:yield e.getBitrate())?i:0})}class lo{constructor({canvas:e,ctx:t,events:i,timeupdateInterval:r=250,avSyncTolerance:n=.12,dropLateFrames:s=!1,poster:a="",preflightRange:o=!1}){this.canvas=e,this.ctx=t,this.events=i,this.timeupdateInterval=r,this.avSyncTolerance=n,this.dropLateFrames=s,this.poster=a,this.preflightRange=o,this.input=null,this.videoSink=null,this.videoIterator=null,this.nextFrame=null,this.rafId=0,this.asyncId=0,this.width=0,this.height=0,this.duration=Number.NaN,this.audioClock=null,this.lastTimeUpdate=0,this.stalled=!1,this.playbackRate=1,this.posterDrawn=!1,this.isFetching=!1}preflight(e){return d(this,null,function*(){if(!this.preflightRange||"string"!==typeof e||no(e))return!0;try{const t=(yield fetch(e,{method:"HEAD"})).headers.get("accept-ranges");return!(!t||"none"===t)||(this.events.emit("error",new Event("RangeNotSupported")),!1)}catch(t){return console.warn("Preflight check failed:",t),!0}})}drawPoster(){if(!this.poster||this.posterDrawn)return;const e=new Image;e.onload=()=>{this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.canvas.width=e.naturalWidth||this.canvas.width,this.canvas.height=e.naturalHeight||this.canvas.height,this.ctx.drawImage(e,0,0,this.canvas.width,this.canvas.height),this.posterDrawn=!0},e.src=this.poster}stopIterator(){return d(this,null,function*(){var e;yield null==(e=this.videoIterator)?void 0:e.return(),this.videoIterator=null})}clear(){this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height)}load(e,t){return d(this,null,function*(){++this.asyncId,yield this.stopIterator(),this.clear(),this.posterDrawn=!1;const{input:i,videoTrack:r,duration:n}=e;if(this.input=i,this.duration=n,!r)return this.handleNoVideoTrack(),void(null==t||t());if(null===r.codec||!(yield r.canDecode()))return this.handleNoVideoTrack(),void(null==t||t());const s=yield r.canBeTransparent();this.videoSink=new ra(r,{poolSize:2,fit:"contain",alpha:s}),this.width=r.displayWidth,this.height=r.displayHeight,this.canvas.width=this.width,this.canvas.height=this.height,null==t||t(),yield this.resetIterator(0)})}handleNoVideoTrack(){this.videoSink=null,this.width=0,this.height=0,this.canvas.width=0,this.canvas.height=0,this.clear(),this.drawPoster()}resetIterator(e){return d(this,null,function*(){var t,i;if(yield this.stopIterator(),!this.videoSink)return;this.videoIterator=this.videoSink.canvases(e);const r=null!=(t=(yield this.videoIterator.next()).value)?t:null,n=null!=(i=(yield this.videoIterator.next()).value)?i:null;this.nextFrame=n,r?this.ctx.drawImage(r.canvas,0,0):this.drawPoster()})}updateNextFrame(e){return d(this,null,function*(){var t;if(this.videoIterator&&!this.isFetching){this.isFetching=!0;try{for(;;){const i=null!=(t=(yield this.videoIterator.next()).value)?t:null;if(!i||e!==this.asyncId)return;const r=this.audioClock.currentTime,n=this.dropLateFrames?Math.max(.06,this.avSyncTolerance/Math.max(1,this.playbackRate)):0;if(!(this.dropLateFrames&&i.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 d(this,null,function*(){this.asyncId++,yield this.resetIterator(e)})}setPlaybackRate(e){this.playbackRate=Math.max(.1,Number(e)||1)}destroy(){this.asyncId++,this.stop(),this.stopIterator(),this.posterDrawn=!1,this.videoSink=null,this.input=null}}class co{constructor({canvas:e,ctx:t,events:i,option:r={}}){var n,s,a,o,l,c;this.events=i,this.option=r,this.audio=new io(i),this.video=new lo({canvas:e,ctx:t,events:i,timeupdateInterval:null!=(n=r.timeupdateInterval)?n:250,avSyncTolerance:null!=(s=r.avSyncTolerance)?s:.12,dropLateFrames:null!=(a=r.dropLateFrames)&&a,poster:null!=(o=r.poster)?o:"",preflightRange:null!=(l=r.preflightRange)&&l}),this.paused=!0,this.ended=!1,this.readyState=0,this.networkState=0,this.error=null,this.seeking=!1,this.loadSeq=0,this.input=null,this.media=null,null==(c=i.addEventListener)||c.call(i,"ended",()=>{this.ended=!0,this.paused=!0})}load(e){return d(this,null,function*(){const t=++this.loadSeq;this.pause(),this.disposeInput(),this.ended=!1,this.error=null,this.networkState=2,this.readyState=0,setTimeout(()=>this.events.emit("waiting"),0),setTimeout(()=>this.events.emit("loadstart"),0);const i=Number.isFinite(this.option.loadTimeout)?this.option.loadTimeout:0;try{yield Promise.race([this.performLoad(e,t),i>0?this.createTimeout(i):new Promise(()=>{})])}catch(r){if(t!==this.loadSeq)return;this.loadSeq++,this.error={code:4,message:r.message},this.networkState=3,this.events.emit("error")}})}performLoad(e,t){return d(this,null,function*(){if(!(yield this.video.preflight(e)))return;const i=so(e);if(!i)return this.video.handleNoVideoTrack(),void this.audio.handleNoAudioTrack();const r=yield function(e,t){return d(this,null,function*(){const i=yield e.getPrimaryVideoTrack(),r=i?yield i.getPrimaryPairableAudioTrack():yield e.getPrimaryAudioTrack(),n=yield ao({input:e,videoTrack:i,audioTrack:r});return{input:e,videoTrack:i,audioTrack:r,duration:n,isLive:!Number.isFinite(n)&&Boolean((i||r)&&(yield(i||r).isLive())),isHls:no(t),videoMode:no(t)?"auto":"manual",audioMode:no(t)?"auto":"manual"}})}(i,e);if(t!==this.loadSeq)return void i.dispose();this.disposeInput(),this.input=i,this.media=r;let n=!r.videoTrack,s=!r.audioTrack;const a=()=>{n&&s&&(this.readyState=1,this.events.emit("loadedmetadata"),this.events.emit("durationchange"),this.events.emit("progress"))};try{if(yield Promise.all([this.video.load(r,()=>{t===this.loadSeq&&(n=!0,a())}),this.audio.load(r,()=>{t===this.loadSeq&&(s=!0,a())})]),t!==this.loadSeq)return;this.readyState=4,this.networkState=1,this.events.emit("loadeddata"),this.events.emit("canplay"),this.events.emit("canplaythrough"),this.events.emit("progress")}catch(o){if(t!==this.loadSeq)return;this.error={code:4,message:o.message},this.networkState=3,this.events.emit("error"),console.error("MediaBunny load error:",o)}})}createTimeout(e){return new Promise((t,i)=>{setTimeout(()=>i(new Error("Load timeout")),e)})}disposeInput(){var e;null==(e=this.input)||e.dispose(),this.input=null,this.media=null}replaceTracks(e){return d(this,arguments,function*({videoTrack:e,audioTrack:t,videoMode:i,audioMode:r}){if(!this.media)return;const n=u(c({},this.media),{videoTrack:e,audioTrack:t,videoMode:i,audioMode:r}),s=!this.paused,a=this.currentTime;this.pause(),this.ended=!1,this.seeking=!0,this.events.emit("seeking"),this.events.emit("waiting"),n.duration=yield ao(n),this.media=n,yield Promise.all([this.video.load(n),this.audio.load(n)]),yield Promise.all([this.video.seek(a),this.audio.seek(a)]),this.readyState=4,this.networkState=1,this.seeking=!1,this.events.emit("loadedmetadata"),this.events.emit("durationchange"),this.events.emit("progress"),this.events.emit("loadeddata"),this.events.emit("canplay"),this.events.emit("canplaythrough"),this.events.emit("seeked"),s&&(yield this.play())})}selectHlsQuality(e){return d(this,null,function*(){var t,i;if(!(null==(t=this.media)?void 0:t.isHls)||!this.input)return;const r=yield this.input.getVideoTracks(),n="auto"===e?yield this.input.getPrimaryVideoTrack():null!=(i=r.find(t=>t.id===e))?i:this.media.videoTrack;if(!n)return;let s=this.media.audioTrack,a=this.media.audioMode;s&&n.canBePairedWith(s)||(s=yield n.getPrimaryPairableAudioTrack(),a="auto"),yield this.replaceTracks({videoTrack:n,audioTrack:s,videoMode:"auto"===e?"auto":"manual",audioMode:a})})}selectHlsAudio(e){return d(this,null,function*(){var t,i;if(!(null==(t=this.media)?void 0:t.isHls)||!this.input)return;const r=yield this.input.getAudioTracks(),n="auto"===e?this.media.videoTrack?yield this.media.videoTrack.getPrimaryPairableAudioTrack():yield this.input.getPrimaryAudioTrack():null!=(i=r.find(t=>t.id===e))?i:this.media.audioTrack;if(!n)return;let s=this.media.videoTrack,a=this.media.videoMode;s&&n.canBePairedWith(s)||(s=yield n.getPrimaryPairableVideoTrack(),a="auto"),yield this.replaceTracks({videoTrack:s,audioTrack:n,videoMode:a,audioMode:"auto"===e?"auto":"manual"})})}getHlsState(){return function(e){return d(this,null,function*(){var t,i,r,n;if(!(null==e?void 0:e.isHls)||!e.input)return null;const[s,a]=yield Promise.all([e.input.getVideoTracks(),e.videoTrack?e.videoTrack.getPairableAudioTracks():[]]),[o,l]=yield Promise.all([Promise.all(s.map((e,t)=>d(null,null,function*(){return{id:e.id,track:e,index:t,name:yield e.getName(),height:yield e.getDisplayHeight(),bitrate:yield oo(e)}}))),Promise.all(a.map((e,t)=>d(null,null,function*(){const i=yield e.getName(),r=yield e.getLanguageCode();return{id:e.id,track:e,index:t,name:i,lang:r,language:r,bitrate:yield oo(e)}})))]);return{levels:o,audios:l,currentLevel:e.videoTrack&&null!=(t=o.find(t=>t.id===e.videoTrack.id))?t:null,currentAudio:e.audioTrack&&null!=(i=l.find(t=>t.id===e.audioTrack.id))?i:null,videoMode:null!=(r=e.videoMode)?r:"auto",audioMode:null!=(n=e.audioMode)?n:"auto"}})}(this.media)}play(){return d(this,null,function*(){this.paused&&(this.ended&&(this.ended=!1,yield this.seek(0)),this.paused=!1,yield this.audio.play(),this.video.start(this.audio),this.events.emit("play"),this.events.emit("playing"))})}pause(){this.paused||(this.paused=!0,this.audio.pause(),this.video.stop(),this.events.emit("pause"))}seek(e){return d(this,null,function*(){const t=!this.paused;this.ended=!1,this.seeking=!0,this.events.emit("seeking"),this.events.emit("waiting"),this.pause(),yield Promise.all([this.audio.seek(e),this.video.seek(e)]),this.seeking=!1,this.events.emit("seeked"),t&&!this.ended&&(yield this.play())})}setVolume(e,t){this.audio.setVolume(e,t)}setPlaybackRate(e){this.audio.setPlaybackRate(e),this.video.setPlaybackRate(e)}destroy(){this.pause(),this.disposeInput(),this.audio.destroy(),this.video.destroy()}get currentTime(){return this.audio.currentTime}get duration(){var e,t,i;return null!=(i=null!=(t=null==(e=this.media)?void 0:e.duration)?t:this.audio.duration)?i:this.video.duration}get videoWidth(){return this.video.width}get videoHeight(){return this.video.height}}class uo{constructor({art:e,canvas:t,ctx:i,option:r}){var n,s;this.art=e,this.canvas=t,this.option=r,this.events=new k,this.engine=new co({canvas:t,ctx:i,events:this.events,option:r}),this._src=null,this._volume=null!=(n=r.volume)?n:.7,this._muted=!!r.muted,this._playbackRate=1,this.engine.setVolume(this._volume,this._muted),this.setupEventForwarding(),r.source?this.src=r.source:(null==(s=e.option)?void 0:s.url)&&(this.src=e.option.url)}setupEventForwarding(){const{events:e}=this.art.constructor.config;e.forEach(e=>{this.events.addEventListener(e,e=>{this.art.emit(`video:${e.type}`,e)})})}addEventListener(e,t){this.events.addEventListener(e,t)}removeEventListener(e,t){this.events.removeEventListener(e,t)}get src(){return this._src}set src(e){this._src=e,e&&this.engine.load(e)}get currentSrc(){return this._src}get currentTime(){return this.engine.currentTime}set currentTime(e){this.engine.seek(Number(e)||0)}get duration(){return this.engine.duration}get buffered(){return this.createTimeRanges(0,this.engine.duration)}get played(){return this.createTimeRanges(0,this.engine.currentTime)}get seekable(){return this.createTimeRanges(0,this.engine.duration)}createTimeRanges(e,t){const i=this.engine.duration;return!i||Number.isNaN(i)||t<=0?{length:0,start:()=>0,end:()=>0}:{length:1,start:()=>e,end:()=>t}}get paused(){return this.engine.paused}get playing(){return!this.engine.paused&&!this.engine.ended}get ended(){return this.engine.ended}get seeking(){return this.engine.seeking}get readyState(){return this.engine.readyState}get networkState(){return this.engine.networkState}get error(){return this.engine.error}get playbackRate(){return this._playbackRate}set playbackRate(e){const t=Number(e);Number.isNaN(t)||t<=0||(this._playbackRate=t,this.engine.setPlaybackRate(t),this.events.emit("ratechange"))}get volume(){return this._volume}set volume(e){this._volume=function(e,t,i){return Math.max(t,Math.min(i,Number(e)||0))}(e,0,1),this._muted=!1,this.engine.setVolume(this._volume,this._muted),this.events.emit("volumechange")}get muted(){return this._muted}set muted(e){this._muted=!!e,this.engine.setVolume(this._volume,this._muted),this.events.emit("volumechange")}play(){return this.engine.play()}pause(){this.engine.pause()}load(){this._src&&this.engine.load(this._src)}getM3u8State(){return this.engine.getHlsState()}switchM3u8Quality(e){return this.engine.selectHlsQuality(e)}switchM3u8Audio(e){return this.engine.selectHlsAudio(e)}get videoWidth(){return this.engine.videoWidth}get videoHeight(){return this.engine.videoHeight}get poster(){return this.option.poster||""}set poster(e){this.option.poster=e}get autoplay(){return this.option.autoplay||!1}set autoplay(e){}get loop(){return this.option.loop||!1}set loop(e){}get controls(){return!1}set controls(e){}get playsInline(){return!0}set playsInline(e){}get crossOrigin(){return this.option.crossOrigin||""}set crossOrigin(e){}get preload(){return"auto"}set preload(e){}get defaultMuted(){return!1}set defaultMuted(e){}get defaultPlaybackRate(){return 1}set defaultPlaybackRate(e){}canPlayType(e){return"maybe"}getBoundingClientRect(){return this.canvas.getBoundingClientRect()}requestVideoFrameCallback(e){return requestAnimationFrame(t=>{e(t,{presentationTime:this.engine.currentTime,expectedDisplayTime:t+16.6,width:this.engine.videoWidth,height:this.engine.videoHeight,mediaTime:this.engine.currentTime,presentedFrames:0,processingDuration:0,captureTime:t,receiveTime:t,rtpTimestamp:0})})}cancelVideoFrameCallback(e){cancelAnimationFrame(e)}setAttribute(e,t){"src"===e?this.src=t:"autoplay"===e?this.autoplay=t:"loop"===e?this.loop=t:"muted"===e?this.muted=!0:this.canvas.setAttribute(e,t)}destroy(){this.engine.destroy()}}return function(e={}){return t=>{const{constructor:i}=t,{createElement:r}=i.utils,n=r("canvas"),s=n.getContext("2d"),a=new uo({art:t,canvas:n,ctx:s,option:e});t.mediabunny=a;const o={};for(const e in n)"function"===typeof n[e]&&(o[e]=n[e].bind(n));const l=new Set([...Object.getOwnPropertyNames(a),...Object.getOwnPropertyNames(Object.getPrototypeOf(a))]);for(const e of l)"constructor"!==e&&(e in n||Object.defineProperty(n,e,{get(){const t=a[e];return"function"===typeof t?t.bind(a):t},set(t){a[e]=t},configurable:!0,enumerable:!0}));for(const e in o)n[e]=(...t)=>o[e](...t);function c(){var e;(null==(e=t.template)?void 0:e.$player)&&!t.option.autoSize&&Object.assign(n.style,{width:"100%",height:"100%",objectFit:"contain"})}return t.on("resize",c),t.on("video:loadedmetadata",c),function({art:e,shim:t,option:i}){if(i.m3u8)return e.on("video:loadedmetadata",u),e.on("restart",u),{update:u};function r(t){e.controls.cache.has(t)&&e.controls.remove(t)}function n(t){e.setting.find(t)&&e.setting.remove(t)}function s(){r("mediabunny-quality"),n("mediabunny-quality")}function a(){r("mediabunny-audio"),n("mediabunny-audio")}function o(e={}){return e.control||e.setting}function l(r){return d(this,null,function*(){var n;const a=(null==(n=i.m3u8)?void 0:n.quality)||{};if(!o(a)||!(null==r?void 0:r.levels.length))return void s();const l=a.auto||"Auto",c=a.title||"Quality",h=a.getName||(e=>e.name||`${e.height}P`),f=r.currentLevel?h(r.currentLevel):l,m=g(r.levels.map(e=>{var t;return{html:h(e),value:e.id,default:(null==(t=r.currentLevel)?void 0:t.id)===e.id}}),"html").sort((e,t)=>{const i=r.levels.find(t=>t.id===e.value),n=r.levels.find(e=>e.id===t.value);return((null==n?void 0:n.height)||0)-((null==i?void 0:i.height)||0)});m.push({html:l,value:"auto",default:!r.currentLevel});const p=i=>d(null,null,function*(){return yield t.switchM3u8Quality(i.value),e.notice.show=`${c}: ${i.html}`,yield u(),i.html});a.control&&e.controls.update({name:"mediabunny-quality",position:"right",html:f,style:{padding:"0 10px"},selector:m,onSelect:p}),a.setting&&e.setting.update({name:"mediabunny-quality",tooltip:f,html:c,icon:'',width:200,selector:m,onSelect:p})})}function c(r){return d(this,null,function*(){var n;const s=(null==(n=i.m3u8)?void 0:n.audio)||{};if(!o(s)||!(null==r?void 0:r.audios.length)||r.audios.length<2)return void a();const l=s.auto||"Auto",c=s.title||"Audio",h=s.getName||(e=>e.name||e.lang||e.language),f=r.currentAudio?h(r.currentAudio):l,m=g(r.audios.map(e=>{var t;return{html:h(e),value:e.id,default:(null==(t=r.currentAudio)?void 0:t.id)===e.id}}),"html");m.push({html:l,value:"auto",default:!r.currentAudio});const p=i=>d(null,null,function*(){return yield t.switchM3u8Audio(i.value),e.notice.show=`${c}: ${i.html}`,yield u(),i.html});s.control&&e.controls.update({name:"mediabunny-audio",position:"right",html:f,style:{padding:"0 10px"},selector:m,onSelect:p}),s.setting&&e.setting.update({name:"mediabunny-audio",tooltip:f,html:c,icon:'',width:200,selector:m,onSelect:p})})}function u(){return d(this,null,function*(){const e=yield t.getM3u8State();if(!e)return s(),void a();yield Promise.all([l(e),c(e)])})}}({art:t,shim:a,option:e}),t.on("destroy",()=>{delete t.mediabunny,a.destroy()}),n}}}); +!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=Object.defineProperty,t=Object.defineProperties,i=Object.getOwnPropertyDescriptors,r=Object.getOwnPropertySymbols,n=Object.prototype.hasOwnProperty,s=Object.prototype.propertyIsEnumerable,a=(e,t)=>(t=Symbol[e])?t:Symbol.for("Symbol."+e),o=Math.pow,l=(t,i,r)=>i in t?e(t,i,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[i]=r,c=(e,t)=>{for(var i in t||(t={}))n.call(t,i)&&l(e,i,t[i]);if(r)for(var i of r(t))s.call(t,i)&&l(e,i,t[i]);return e},u=(e,r)=>t(e,i(r)),d=(e,t,i)=>new Promise((r,n)=>{var s=e=>{try{o(i.next(e))}catch(t){n(t)}},a=e=>{try{o(i.throw(e))}catch(t){n(t)}},o=e=>e.done?r(e.value):Promise.resolve(e.value).then(s,a);o((i=i.apply(e,t)).next())}),h=function(e,t){this[0]=e,this[1]=t},f=(e,t,i)=>{var r,n=(e,t,r,s)=>{try{var a=i[e](t),o=(t=a.value)instanceof h,l=a.done;Promise.resolve(o?t[0]:t).then(i=>o?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)=>o[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),o={};return i=i.apply(e,t),o[a("asyncIterator")]=()=>o,s("next"),s("throw"),s("return"),o},m=e=>{var t,i=e[a("asyncIterator")],r=!1,n={};return null==i?(i=e[a("iterator")](),t=e=>n[e]=t=>i[e](t)):(i=i.call(e),t=e=>n[e]=t=>{if(r){if(r=!1,"throw"===e)throw t;return t}return r=!0,{done:!1,value:new h(new Promise(r=>{var n=i[e](t);n instanceof Object||(e=>{throw TypeError(e)})("Object expected"),r(n)}),1)}}),n[a("iterator")]=()=>n,t("next"),"throw"in i?t("throw"):n.throw=e=>{throw e},"return"in i&&t("return"),n},p=(e,t,i)=>(t=e[a("asyncIterator")])?t.call(e):(e=e[a("iterator")](),t={},(i=(i,r)=>(r=e[i])&&(t[i]=t=>new Promise((i,n,s)=>(t=r.call(e,t),s=t.done,Promise.resolve(t.value).then(e=>i({value:e,done:s}),n)))))("next"),i("return"),t);function g(e,t){const i=new Map;return e.filter(e=>{const r=e[t];return void 0===r||!i.has(r)&&i.set(r,1)})}class k{constructor(){this.listeners=new Map}addEventListener(e,t){this.listeners.has(e)||this.listeners.set(e,[]),this.listeners.get(e).push(t)}removeEventListener(e,t){const i=this.listeners.get(e);if(!i)return;const r=i.indexOf(t);r>=0&&i.splice(r,1)}emit(e,t){const i=new Event(e);i.detail=t;const r=this.listeners.get(e);r&&r.forEach(e=>e(i))}}function y(e){if(!e)throw new Error("Assertion failed.")}const b=e=>{const t=(e%360+360)%360;if(0===t||90===t||180===t||270===t)return t;throw new Error(`Invalid rotation ${e}.`)},T=e=>e&&e[e.length-1],v=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-o(2,r))},w=e=>{const t=v(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),I=e=>e.constructor===DataView?e:ArrayBuffer.isView(e)?new DataView(e.buffer,e.byteOffset,e.byteLength):new DataView(e),x=new TextDecoder,C=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])),B={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},E=C(B),_={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},R=C(_),F={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},A=C(F),D=e=>!!e&&!!e.primaries&&!!e.transfer&&!!e.matrix&&void 0!==e.fullRange,M={primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0},N=e=>e instanceof ArrayBuffer||"undefined"!==typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e);class O{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}acquire(){return d(this,null,function*(){let e;const t=new Promise(t=>{let i=!1;e=()=>{i||(t(),this.pending--,i=!0)}}),i=this.currentPromise;return this.currentPromise=t,this.pending++,yield i,e})}}const L=/^[0-9a-fA-F]+$/,z=e=>[...e].map(e=>e.toString(16).padStart(2,"0")).join(""),U=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,q=(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},H=(e,t,i)=>{const r=W(e,i(t),i);e.splice(r+1,0,t)},V=()=>{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)},K=(e,t)=>{for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},X=(e,t)=>{for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},$=e=>{throw new Error(`Unexpected value: ${e}`)},G=(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},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)},Y=(e,t)=>({next(){return d(this,null,function*(){const i=yield e.next();return i.done?{value:void 0,done:!0}:{value:t(i.value),done:!1}})},return:()=>e.return(),throw:t=>e.throw(t),[Symbol.asyncIterator](){return this}}),J=(e,t,i)=>Math.max(t,Math.min(i,e)),Z="und",ee=e=>{const t=Math.round(e);return Math.abs(e/t-1)<10*Number.EPSILON?t:e},te=(e,t)=>Math.round(e/t)*t,ie=(e,t)=>Math.round(e*t)/t,re=(e,t)=>Math.floor(e/t)*t,ne=e=>{let t=0;for(;0!==e;)e&=e-1,t++;return t},se=/^[a-z]{3}$/,ae=e=>se.test(e),oe=1e6*(1+Number.EPSILON),le=(e,t)=>{const i=c(c({},e),t);if(e.headers||t.headers){const r=e.headers?ce(e.headers):{},n=t.headers?ce(t.headers):{},s=c({},r);Object.entries(n).forEach(([e,t])=>{const i=Object.keys(s).find(t=>t.toLowerCase()===e.toLowerCase());i&&delete s[i],s[e]=t}),i.headers=s}return i},ce=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},ue=(e,t,i,r,n)=>d(null,null,function*(){let s=0;for(;;)try{return yield e(t,i)}catch(a){if(n())throw a;s++;const e=r(s,a,t);if(null===e)throw a;if(Me._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 Re(1e3*e)),n())throw a}});class de{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}let he=null;const fe=()=>{var e;return null!==he?he:he=!("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 me=null;const pe=()=>{var e;return null!==me?me:me="undefined"!==typeof navigator&&(null==(e=navigator.userAgent)?void 0:e.includes("Firefox"))};let ge=null;const ke=()=>{var e;return null!==ge?ge:ge=!("undefined"===typeof navigator||!(null==(e=navigator.vendor)?void 0:e.includes("Google Inc"))&&!/Chrome/.test(navigator.userAgent))},ye=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.`,be=d(null,null,function*(){}).constructor,Te=e=>e instanceof be||e instanceof Promise||"function"===typeof(null==e?void 0:e.then),ve=(e,t)=>-1!==e?e:t,Se=(e,t,i,r)=>e<=r&&i<=t,we=e=>{const t=atob(e),i=new Uint8Array(t.length);for(let r=0;r{null!=Symbol.dispose||(Symbol.dispose=Symbol("Symbol.dispose"))},Ie=e=>"number"===typeof e&&!Number.isNaN(e),xe=(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("/")},Ce=(e,t)=>{let i=0;for(let r=0;r{let i=-1,r=1/0;for(let n=0;n{y(Number.isInteger(e.num)),y(Number.isInteger(e.den)),y(0!==e.den);let t=Math.abs(e.num),i=Math.abs(e.den);for(;0!==i;){const e=t%i;t=i,i=e}const r=t||1;return{num:e.num/r,den:e.den/r}},_e=(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.`)},Re=e=>new Promise(t=>setTimeout(t,e));class Fe{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 Ae,De;(De=Ae||(Ae={}))[De.Silent=0]="Silent",De[De.Errors=1]="Errors",De[De.Warnings=2]="Warnings",De[De.Info=3]="Info";class Me{constructor(){}static get level(){return Me._level}static set level(e){if(e!==Ae.Silent&&e!==Ae.Errors&&e!==Ae.Warnings&&e!==Ae.Info)throw new TypeError("Invalid log level. Use one of the values of the LogLevel enum.");Me._level=e}static get _emitter(){var e;return null!=(e=Me._emitterInstance)?e:Me._emitterInstance=new Fe}static on(e,t,i){return Me._emitter.on(e,t,i)}static _error(...e){Me._emitter._emit("error",e),Me._level>=Ae.Errors&&console.error(...e)}static _warn(...e){Me._emitter._emit("warn",e),Me._level>=Ae.Warnings&&console.warn(...e)}static _info(...e){Me._emitter._emit("info",e),Me._level>=Ae.Info&&console.info(...e)}}Me._level=Ae.Info,Me._emitterInstance=null;class Ne{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 Oe{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 Le={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1};class ze{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 ze(this.bytes);return e.pos=this.pos,e}}const Ue=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],qe=[-1,1,2,3,4,5,6,8],We=e=>{if(!e||e.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");const t=new ze(e),i=He(t),{frequencyIndex:r,sampleRate:n}=Ve(t),s=t.readBits(4);let a=null;s>=1&&s<=7&&(a=qe[s]);let o=i,l=!1,c=n;if(5===i||29===i)l=29===i,c=Ve(t).sampleRate,o=He(t),22===o&&t.skipBits(4);else for(;t.getBitsLeft()>15;){const e=t.pos;if(695===t.readBits(11)){5===He(t)&&t.readBits(1)&&(c=Ve(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}},He=e=>{const t=e.readBits(5);return 31===t?32+e.readBits(6):t},Ve=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&P(t.description)[4];return Je(e,i+1)}return Ye(e)},et=e=>31&e,tt=e=>{const t=[],i=e.length;for(let r=0;r{const t=e.reduce((e,t)=>e+it.byteLength+t.byteLength,0),i=new Uint8Array(t);let r=0;for(const n of e)i.set(it,r),r+=it.byteLength,i.set(n,r),r+=n.byteLength;return i},nt=(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:Q(e,n,s.byteLength);break;case 4:e.setUint32(n,s.byteLength,!1)}n+=t,r.set(s,n),n+=s.byteLength}return r},st=e=>{try{const t=[],i=[],r=[];for(const o of Ye(e)){const n=e.subarray(o.offset,o.offset+o.length),s=et(n[0]);s===Xe.SPS?t.push(n):s===Xe.PPS?i.push(n):s===Xe.SPS_EXT&&r.push(n)}if(0===t.length)return null;if(0===i.length)return null;const n=t[0],s=ct(n);y(null!==s);const a=100===s.profileIdc||110===s.profileIdc||122===s.profileIdc||144===s.profileIdc;return{configurationVersion:1,avcProfileIndication:s.profileIdc,profileCompatibility:s.constraintFlags,avcLevelIndication:s.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:t,pictureParameterSets:i,chromaFormat:a?s.chromaFormatIdc:null,bitDepthLumaMinus8:a?s.bitDepthLumaMinus8:null,bitDepthChromaMinus8:a?s.bitDepthChromaMinus8:null,sequenceParameterSetExt:a?r:null}}catch(t){return Me._error("Error building AVC Decoder Configuration Record:",t),null}},at=e=>{const t=[];t.push(e.configurationVersion),t.push(e.avcProfileIndication),t.push(e.profileCompatibility),t.push(e.avcLevelIndication),t.push(252|3&e.lengthSizeMinusOne),t.push(224|31&e.sequenceParameterSets.length);for(const i of e.sequenceParameterSets){const e=i.byteLength;t.push(e>>8),t.push(255&e);for(let r=0;r>8),t.push(255&e);for(let r=0;r>8),t.push(255&e);for(let r=0;r{try{const t=I(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=tt(e),r=new ze(i);r.skipBits(1),r.skipBits(2);if(7!==r.readBits(5))return null;const n=r.readAlignedByte(),s=r.readAlignedByte(),a=r.readAlignedByte();v(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=v(r),3===o&&(u=r.readBits(1)),l=v(r),c=v(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:T(ai),n=Math.min(Math.floor(r.maxDpbMbs/(e*i)),16);B=n,E=n}else B=0,E=0}return y(null!==E),{emulationUnpreventedBytes:i,profileIdc:n,constraintFlags:s,levelIdc:a,frameMbsOnlyFlag:b,chromaFormatIdc:o,bitDepthLumaMinus8:l,bitDepthChromaMinus8:c,codedWidth:m,codedHeight:p,displayWidth:g,displayHeight:k,pixelAspectRatio:C,colourPrimaries:S,matrixCoefficients:I,transferCharacteristics:P,fullRangeFlag:x,numReorderFrames:B,maxDecFrameBuffering:E,vuiParametersFlagBitOffset:F,bitstreamRestrictionFlagBitOffset:_,bitstreamRestrictionFlag:R}}catch(i){return Me._error("Error parsing AVC SPS:",i),null}},ut=e=>{const t=v(e);e.skipBits(4),e.skipBits(4);for(let i=0;i<=t;i++)v(e),v(e),e.skipBits(1);e.skipBits(5),e.skipBits(5),e.skipBits(5),e.skipBits(5)},dt=e=>{y(1!==e.bitstreamRestrictionFlag);const t=new Uint8Array(e.emulationUnpreventedBytes.byteLength+64),i=new ze(e.emulationUnpreventedBytes),r=new ze(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)):(y(null!==e.bitstreamRestrictionFlagBitOffset),r.copyBits(e.bitstreamRestrictionFlagBitOffset,i)),r.writeBits(1,1),r.writeBits(1,1),S(r,2),S(r,1),S(r,16),S(r,16),S(r,e.numReorderFrames),S(r,e.maxDecFrameBuffering),r.writeBits(1,1),r.writeBits((8-r.pos%8)%8,0);const n=r.pos/8;return y(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))},ht=(e,t)=>{if(t.description){const i=3&P(t.description)[21];return Je(e,i+1)}return Ye(e)},ft=e=>e>>1&63,mt=e=>{try{const t=new ze(tt(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}=gt(t,i);v(t);const u=v(t);let d=0;3===u&&(d=t.readBits(1));const h=v(t),f=v(t);let m=h,p=f;if(t.readBits(1)){const e=v(t),i=v(t),r=v(t),n=v(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=v(t),k=v(t);v(t);const y=t.readBits(1);let b=0;for(let e=y?0:i;e<=i;e++)v(t),b=v(t),v(t);v(t),v(t),v(t),v(t),v(t),v(t),t.readBits(1)&&t.readBits(1)&&kt(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(4),t.skipBits(4),v(t),v(t),t.skipBits(1));const T=v(t);if(yt(t,T),t.readBits(1)){const e=v(t);for(let i=0;i{try{const t=[],i=[],r=[],n=[];for(const l of Ye(e)){const s=e.subarray(l.offset,l.offset+l.length),a=ft(s[0]);a===Ge.VPS_NUT?t.push(s):a===Ge.SPS_NUT?i.push(s):a===Ge.PPS_NUT?r.push(s):a!==Ge.PREFIX_SEI_NUT&&a!==Ge.SUFFIX_SEI_NUT||n.push(s)}if(0===i.length||0===r.length)return null;const s=mt(i[0]);if(!s)return null;let a=0;if(r.length>0){const e=r[0],t=new ze(tt(e));t.skipBits(16),v(t),v(t),t.skipBits(1),t.skipBits(1),t.skipBits(3),t.skipBits(1),t.skipBits(1),v(t),v(t),w(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&v(t),w(t),w(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:Ge.VPS_NUT,nalUnits:t}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:Ge.SPS_NUT,nalUnits:i}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:Ge.PPS_NUT,nalUnits:r}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:ft(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 Me._error("Error building HEVC Decoder Configuration Record:",t),null}},gt=(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&&w(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-(v(e)+1)}else o=t-1;e.readBits(1),v(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=v(e),i=v(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=lt[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)&&(v(e),v(e)),e.readBits(1),e.readBits(1),e.readBits(1),e.readBits(1)&&(v(e),v(e),v(e),v(e)),e.readBits(1)&&(e.readBits(32),e.readBits(32),e.readBits(1)&&v(e),e.readBits(1)&&vt(e,!0,t)),e.readBits(1)&&(e.readBits(1),e.readBits(1),e.readBits(1),a=v(e),v(e),v(e),v(e),v(e)),{pixelAspectRatio:o,colourPrimaries:i,transferCharacteristics:r,matrixCoefficients:n,fullRangeFlag:s,minSpatialSegmentationIdc:a}},vt=(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?v(e):i=1===e.readBits(1);let a=1;if(!i){a=v(e)+1}r&&St(e,a,s),n&&St(e,a,s)}},St=(e,t,i)=>{for(let r=0;r{const i=new Set;let r=wt.audAllowed;for(const s of ht(e,t)){if(r===wt.noMoreDataAllowed){i.add(s.offset);continue}const t=ft(e[s.offset]);if(r===wt.eoBitstreamAllowed&&37!==t){i.add(s.offset);continue}let n=!1;35===t?r>wt.audAllowed?n=!0:r=wt.beforeFirstVcl:t<=31?r>wt.afterFirstVcl?n=!0:r=wt.afterFirstVcl:36===t?r!==wt.afterFirstVcl?n=!0:r=wt.eoBitstreamAllowed:37===t?r=41&&t<=44||t>=48&&t<=55?r>wt.beforeFirstVcl?n=!0:r=wt.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 nt(e,i+1)}return rt(e)})(n,t)},xt={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}},Ct=e=>{var t,i,r;const n=new ze(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=T(oi).level;for(const m of oi)if(d<=m.maxPictureSize){h=m.level;break}const f=xt[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}},Bt=function*(e){const t=new ze(e),i=()=>{let e=0;for(let i=0;i<8;i++){const r=t.readAlignedByte();if(e+=(127&r)*o(2,7*i),!(128&r))break;if(7===i&&128&r)return null}return e>o(2,32)-1?null:e};for(;t.getBitsLeft()>=8;){t.skipBits(1);const r=t.readBits(4),n=t.readBits(1),s=t.readBits(1);let a;if(t.skipBits(1),n&&t.skipBits(8),s){const e=i();if(null===e)return;a=e}else a=Math.floor(t.getBitsLeft()/8);y(t.pos%8===0),yield{type:r,data:e.subarray(t.pos/8,t.pos/8+a)},t.skipBits(8*a)}},Et=e=>{for(const{type:t,data:i}of Bt(e)){if(1!==t)continue;const e=new ze(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},_t=e=>{if(e.length<36)return null;const t=I(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)}},Rt=[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],Ft=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}},At=(e,t,i)=>{switch(e){case"avc":for(const e of Ze(i,t)){const t=i[e.offset],r=et(t);if(r>=Xe.NON_IDR_SLICE&&r<=Xe.SLICE_DPC)return"delta";if(r===Xe.IDR)return"key";if(r===Xe.SEI&&!ke()){const t=i.subarray(e.offset,e.offset+e.length),r=tt(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 ze(r);e.pos=8*n;const t=v(e),i=e.readBits(1);if(0===t&&1===i)return"key"}n+=t}while(n{var i,r;const n=I(e);let s=0;const a=n.getUint32(s,!0);s+=4;const o=x.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=we(c),i=I(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=x.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})}}}},Ot=[2,1,2,3,3,4,4,5],Lt=e=>{if(e.length<7)return null;if(11!==e[0]||119!==e[1])return null;const t=new ze(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)}},zt=[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],Ut=[1,2,3,6],qt=e=>{if(e.length<6)return null;if(11!==e[0]||119!==e[1])return null;const t=new ze(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=Ut[s];let d;d=n<3?je[n]/1e3:Ke[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}]}},Wt=e=>{const t=e.substreams[0];return y(t),t.fscod<3?je[t.fscod]:null!==t.fscod2&&t.fscod2<3?Ke[t.fscod2]:null},Ht=e=>{const t=e.substreams[0];y(t);let i=Ot[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},Vt=[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],Kt=[16,16,20,20,0,24,24,0],Xt=[1,2,2,2,2,3,3,4,4,5,6,6,6,7,8,8],$t=[1,2,2,2,2,3,18,19,6,7,518,323,83,519,582,535],Gt=[32e3,44100,48e3,0],Qt=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],Yt=[512,1024,2048,4096],Jt=e=>{const t=ei(e),i=I(e);let r=t?4*Math.ceil(t.frameSize/4):0,n=null;for(;r+4<=e.length&&1683496997===i.getUint32(r);){const t=ti(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}},Zt=e=>{const t=Jt(e);return(null==t?void 0:t.core)?t.hasExtensions?"dtsh":"dtsc":null},ei=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 ze(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>=Xt.length)return null;const a=Vt[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=Kt[t.readBits(3)];if(0===c)return null;const u=0!==l;return{frameSize:n,sampleRate:a,numberOfChannels:Xt[s]+(u?1:0),sampleCount:32*r,channelLayout:$t[s]|(u?8:0),amode:s,lfePresent:u,bitRate:o,pcmResolution:c}},ti=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 ze(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=Gt[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}}},ii=e=>ne(e)+ne(44646&e),ri=["avc","hevc","vp9","av1","vp8","prores"],ni=["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"],si=["aac","opus","mp3","vorbis","flac","ac3","eac3","dts",...ni],ai=[{maxMacroblocks:99,maxBitrate:64e3,maxDpbMbs:396,level:10},{maxMacroblocks:396,maxBitrate:192e3,maxDpbMbs:900,level:11},{maxMacroblocks:396,maxBitrate:384e3,maxDpbMbs:2376,level:12},{maxMacroblocks:396,maxBitrate:768e3,maxDpbMbs:2376,level:13},{maxMacroblocks:396,maxBitrate:2e6,maxDpbMbs:2376,level:20},{maxMacroblocks:792,maxBitrate:4e6,maxDpbMbs:4752,level:21},{maxMacroblocks:1620,maxBitrate:4e6,maxDpbMbs:8100,level:22},{maxMacroblocks:1620,maxBitrate:1e7,maxDpbMbs:8100,level:30},{maxMacroblocks:3600,maxBitrate:14e6,maxDpbMbs:18e3,level:31},{maxMacroblocks:5120,maxBitrate:2e7,maxDpbMbs:20480,level:32},{maxMacroblocks:8192,maxBitrate:2e7,maxDpbMbs:32768,level:40},{maxMacroblocks:8192,maxBitrate:5e7,maxDpbMbs:32768,level:41},{maxMacroblocks:8704,maxBitrate:5e7,maxDpbMbs:34816,level:42},{maxMacroblocks:22080,maxBitrate:135e6,maxDpbMbs:110400,level:50},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:51},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:52},{maxMacroblocks:139264,maxBitrate:24e7,maxDpbMbs:696320,level:60},{maxMacroblocks:139264,maxBitrate:48e7,maxDpbMbs:696320,level:61},{maxMacroblocks:139264,maxBitrate:8e8,maxDpbMbs:696320,level:62}],oi=[{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}],li=".01.01.01.01.00",ci=".0.110.01.01.01.0",ui=["ap4x","ap4h","apch","apcn","apcs","apco"],di=["dtsc","dtsh","dtsl","dtse"],hi=e=>{const{codec:t,codecDescription:i,colorSpace:r,avcCodecInfo:n,hevcCodecInfo:s,vp9CodecInfo:a,av1CodecInfo:o,proresFormat:l}=e;if("avc"===t){if(y(null!==e.avcType),n){const t=new Uint8Array([n.avcProfileIndication,n.profileCompatibility,n.avcLevelIndication]);return`avc${e.avcType}.${z(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}.${z(i.subarray(1,4))}`}if("hevc"===t){let e,t,r,n,a,o;if(s)e=s.generalProfileSpace,t=s.generalProfileIdc,r=U(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=I(i),l=s.getUint8(1);e=l>>6&3,t=31&l,r=U(s.getUint32(2)),n=l>>5&1,a=s.getUint8(12),o=[];for(let e=0;e<6;e++)o.push(s.getUint8(6+e))}let l="hev1.";for(l+=["","A","B","C"][e]+t,l+=".",l+=r.toString(16).toUpperCase(),l+=".",l+=0===n?"L":"H",l+=a;o.length>0&&0===o[o.length-1];)o.pop();return o.length>0&&(l+=".",l+=o.map(e=>e.toString(16).toUpperCase()).join(".")),l}if("vp8"===t)return"vp8";if("vp9"===t){if(!a){const t=e.width*e.height;let i=T(oi).level;for(const e of oi)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(li)&&(t=t.slice(0,-15)),t}if("av1"===t){if(!o){const t=e.width*e.height;let i=T(oi).level;for(const e of oi)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)?B[r.primaries]:1,u=(null==r?void 0:r.transfer)?_[r.transfer]:1,d=(null==r?void 0:r.matrix)?F[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(ci)&&(f=f.slice(0,-17)),f}if("prores"===t)return null!=l?l:"apch";throw null!==t&&$(t),new TypeError(`Unhandled codec '${t}'.`)},fi=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=ot(e.codecDescription))?void 0:i.sequenceParameterSets[0]),r){const e=ct(r);if(e)return{primaries:E[e.colourPrimaries],transfer:R[e.transferCharacteristics],matrix:A[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case"hevc":{let t=null==(n=null==(r=e.hevcCodecInfo)?void 0:r.arrays.find(e=>e.nalUnitType===Ge.SPS_NUT))?void 0:n.nalUnits[0];if(!t&&e.codecDescription&&(t=null==(a=null==(s=(e=>{try{const t=I(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===Ge.SPS_NUT))?void 0:a.nalUnits[0]),t){const e=mt(t);if(e)return{primaries:E[e.colourPrimaries],transfer:R[e.transferCharacteristics],matrix:A[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case"vp8":break;case"vp9":if(e.vp9CodecInfo)return{primaries:E[e.vp9CodecInfo.colourPrimaries],transfer:R[e.vp9CodecInfo.transferCharacteristics],matrix:A[e.vp9CodecInfo.matrixCoefficients],fullRange:!!e.vp9CodecInfo.videoFullRangeFlag};break;case"av1":if(e.av1CodecInfo)return{primaries:E[e.av1CodecInfo.colourPrimaries],transfer:R[e.av1CodecInfo.transferCharacteristics],matrix:A[e.av1CodecInfo.matrixCoefficients],fullRange:!!e.av1CodecInfo.videoFullRangeFlag};break;case"prores":if(e.proresCodecInfo)return{primaries:E[e.proresCodecInfo.colourPrimaries],transfer:R[e.proresCodecInfo.transferCharacteristics],matrix:A[e.proresCodecInfo.matrixCoefficients],fullRange:e.proresCodecInfo.fullRange}}return{primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0}},mi=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=We(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&&ni.includes(t))return t;throw new TypeError(`Unhandled codec '${t}'.`)},pi=48e3,gi=/^pcm-([usf])(\d+)(be)?$/,ki=e=>{if(y(ni.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=gi.exec(e);let i;y(t),i="u"===t[1]?"unsigned":"s"===t[1]?"signed":"float";return{dataType:i,sampleSize:Number(t[2])/8,littleEndian:"be"!==t[3],silentValue:"pcm-u8"===e?o(2,7):0}},yi=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":ui.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":di.includes(e)?"dts":"ulaw"===e?"ulaw":"alaw"===e?"alaw":gi.test(e)?e:"webvtt"===e?"webvtt":null,bi=[44100,48e3,32e3],Ti=[-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],vi=1483304551,Si=1231971951,wi=(e,t)=>3===e?3===t?21:36:3===t?13:21,Pi=(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=Ti[16*a*4+16*c+(n>>4&15)];if(-1===g)return{header:null,bytesAdvanced:1};const k=1e3*g,y=bi[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 xi,Ci;(Ci=xi||(xi={}))[Ci.FrameCount=1]="FrameCount",Ci[Ci.FileSize=2]="FileSize",Ci[Ci.Toc=4]="Toc";const Bi=e=>3===e?1:2;class Ei{constructor(e){this.input=e}dispose(){}}const _i=new Uint8Array(0);class Ri{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===_i&&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===_i}get microsecondTimestamp(){return Math.trunc(oe*this.timestamp)}get microsecondDuration(){return Math.trunc(oe*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 Ri(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 Ri(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 Fi=e=>{const t=I(e);let i=0;const r=t.getUint8(i);i+=1,i+=3;const n=z(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=Lo(e);const i=Xo(e,4);let r=8;1===t&&(t=Wo(e),r=16);const n=t-r;return n<0?null:{name:i,totalSize:t,headerSize:r,contentSize:n}},Mi=e=>Uo(e)/65536,Ni=e=>Uo(e)/1073741824,Oi=e=>{let t=0;for(let i=0;i<4;i++){t<<=7;const i=Fo(e);if(t|=127&i,0===(128&i))break}return t},Li=e=>{let t=Do(e);return e.skip(2),t=Math.min(t,e.remainingLength),x.decode(Ro(e,t))},zi=e=>{const t=Di(e);if(!t||"data"!==t.name)return null;if(e.remainingLength<8)return null;const i=Lo(e);e.skip(4);const r=Ro(e,t.contentSize-8);switch(i){case 1:return x.decode(r);case 2:return new TextDecoder("utf-16be").decode(r);case 13:return new Ne(r,"image/jpeg");case 14:return new Ne(r,"image/png");case 27:return new Ne(r,"image/bmp");default:return r}},Ui=16,qi=new Uint32Array(256),Wi=new Uint32Array(256),Hi=new Uint32Array(256),Vi=new Uint32Array(256),ji=new Uint32Array(256),Ki=new Uint32Array(256),Xi=new Uint32Array(10);let $i=!1;class Gi{constructor(){this.roundkey=new Uint32Array(44),this.iv=new Uint32Array(Ui/Uint32Array.BYTES_PER_ELEMENT),this.in=new Uint8Array(Ui),this.out=new Uint8Array(Ui),this.inView=new DataView(this.in.buffer),this.outView=new DataView(this.out.buffer)}init({key:e,iv:t}){y(16===e.byteLength),y(16===t.byteLength),$i||(()=>{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);qi[s]=t<<24|t<<16|t<<8|t,Ki[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);Wi[s]=n,Hi[s]=n>>>8|n<<24,Vi[s]=n>>>16|n<<16,ji[s]=n>>>24|n<<8}let n=1;for(let s=0;s<10;s++)Xi[s]=n<<24,n=n<<1^(128&n?283:0);$i=!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&qi[e>>>16&255]^16711680&qi[e>>>8&255]^65280&qi[e>>>0&255]^255&qi[e>>>24&255]^Xi[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]]^Hi[255&qi[t>>>16&255]]^Vi[255&qi[t>>>8&255]]^ji[255&qi[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=Wi[e>>>24]^Hi[r>>>16&255]^Vi[i>>>8&255]^ji[255&t]^this.roundkey[n],c=Wi[t>>>24]^Hi[e>>>16&255]^Vi[r>>>8&255]^ji[255&i]^this.roundkey[n+1],u=Wi[i>>>24]^Hi[t>>>16&255]^Vi[e>>>8&255]^ji[255&r]^this.roundkey[n+2],d=Wi[r>>>24]^Hi[i>>>16&255]^Vi[t>>>8&255]^ji[255&e]^this.roundkey[n+3],e=l,t=c,i=u,r=d}const h=4278190080&Ki[e>>>24&255]^16711680&Ki[r>>>16&255]^65280&Ki[i>>>8&255]^255&Ki[t>>>0&255]^this.roundkey[40],f=4278190080&Ki[t>>>24&255]^16711680&Ki[e>>>16&255]^65280&Ki[r>>>8&255]^255&Ki[i>>>0&255]^this.roundkey[41],m=4278190080&Ki[i>>>24&255]^16711680&Ki[t>>>16&255]^65280&Ki[e>>>8&255]^255&Ki[r>>>0&255]^this.roundkey[42],p=4278190080&Ki[r>>>24&255]^16711680&Ki[i>>>16&255]^65280&Ki[t>>>8&255]^255&Ki[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 Qi extends Ei{constructor(e){super(e),this.moovSlice=null,this.currentTrack=null,this.tracks=[],this.metadataPromise=null,this.movieTimescale=-1,this.movieDurationInTimescale=-1,this.isQuickTime=!1,this.metadataTags={},this.currentMetadataKeys=null,this.isFragmented=!1,this.fragmentTrackDefaults=[],this.psshBoxes=[],this.currentFragment=null,this.lastReadFragment=null,this.decryptionKeyCache=new Map,this.reader=e._reader}getTrackBackings(){return d(this,null,function*(){return yield this.readMetadata(),this.tracks.map(e=>e.trackBacking)})}getMimeType(){return d(this,null,function*(){yield this.readMetadata();const e=yield this.getTrackBackings(),t=yield Promise.all(e.map(e=>e.getDecoderConfig().then(e=>{var t;return null!=(t=null==e?void 0:e.codec)?t:null})));return(e=>{let t=(e.hasVideo?"video/":e.hasAudio?"audio/":"application/")+(e.isQuickTime?"quicktime":"mp4");e.codecStrings.length>0&&(t+=`; codecs="${[...new Set(e.codecStrings)].join(", ")}"`);return t})({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some(e=>{var t;return"video"===(null==(t=e.info)?void 0:t.type)}),hasAudio:this.tracks.some(e=>{var t;return"audio"===(null==(t=e.info)?void 0:t.type)}),codecStrings:t.filter(Boolean)})})}getMetadataTags(){return d(this,null,function*(){return yield this.readMetadata(),this.metadataTags})}readMetadata(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>d(this,null,function*(){let e=0,t=!1,i=!1;for(;;){let r=this.reader.requestSliceRange(e,8,16);if(Te(r)&&(r=yield r),!r)break;const n=e,s=Di(r);if(!s)break;if("ftyp"===s.name||"styp"===s.name){const e=Xo(r,4);this.isQuickTime="qt "===e}else{if("moov"===s.name){let e=this.reader.requestSlice(r.filePos,s.contentSize);if(Te(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){y(null!==this.reader.fileSize);let e=this.reader.requestSlice(this.reader.fileSize-4,4);Te(e)&&(e=yield e),y(e);const t=Lo(e),i=this.reader.fileSize-t;if(i>=0&&i<=this.reader.fileSize-16){let e=this.reader.requestSliceRange(i,8,16);if(Te(e)&&(e=yield e),e){const t=Di(e);if(t&&"mfra"===t.name){let i=this.reader.requestSlice(e.filePos,t.contentSize);Te(i)&&(i=yield i),i&&this.readContiguousBoxes(i)}}}}}))()}copyMetadataFromInitInput(e){return d(this,null,function*(){const t=yield e._getDemuxer();if(t.constructor!==Qi)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(y(t.info),"video"===t.info.type&&-1!==t.info.width){const e=t;t.trackBacking=new Ji(e),this.tracks.push(t)}else if("audio"===t.info.type&&-1!==t.info.numberOfChannels){const e=t;t.trackBacking=new Zi(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;y(this.moovSlice);const n=this.moovSlice.slice(e.sampleTableByteOffset);this.currentTrack=e,this.traverseBox(n),this.currentTrack=null;if("audio"===(null==(t=e.info)?void 0:t.type)&&e.info.codec&&ni.includes(e.info.codec)&&0===r.sampleCompositionTimeOffsets.length){y("audio"===(null==(i=e.info)?void 0:i.type));const t=ki(e.info.codec),n=[],s=[];for(let i=0;ie.startIndex),u=r.sampleTimingEntries[c],d=W(r.sampleTimingEntries,l,e=>e.startIndex),h=r.sampleTimingEntries[d],f=u.startDecodeTimestamp+(o-u.startIndex)*u.delta,m=h.startDecodeTimestamp+(l-h.startIndex)*h.delta-f,p=T(n);p&&p.delta===m?p.count++:n.push({startIndex:a.startChunkIndex+i,startDecodeTimestamp:f,count:1,delta:m});const g=a.samplesPerChunk*t.sampleSize*e.info.numberOfChannels;s.push(g)}a.startSampleIndex=a.startChunkIndex,a.samplesPerChunk=1}r.sampleTimingEntries=n,r.sampleSizes=s}if(r.sampleCompositionTimeOffsets.length>0){r.presentationTimestamps=[];for(const e of r.sampleTimingEntries)for(let t=0;te.presentationTimestamp-t.presentationTimestamp),r.presentationTimestampIndexMap=Array(r.presentationTimestamps.length).fill(-1);for(let e=0;ee.moofOffset===s.moofOffset);if(r)nr(e,r.timestamp);else{const t=W(i,s.moofOffset-1,e=>e.moofOffset);if(-1!==t){const r=i[t];nr(e,r.endTimestamp)}}e.startTimestampIsFinal=!0}const r=W(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 lr(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;ae(t.languageCode)||(t.languageCode=Z)}}break;case"hdlr":{const t=this.currentTrack;if(!t)break;e.skip(8);const i=Xo(e,4);"vide"===i?t.info={type:"video",width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:c({},M),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=Fo(e);e.skip(3);const r=Lo(e);for(let n=0;n0&&(1===a?(e.skip(4),l=8*Lo(e),e.skip(8)):2===a&&(e.skip(4),c=Ko(e),o=Lo(e),e.skip(4),l=Lo(e),u=Lo(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=pi;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(di.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":(Me._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":(Me._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":(Me._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":(Me._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":(Me._warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null):32===e?t.info.codec="pcm-f32be":64===e?t.info.codec="pcm-f64be":(Me._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!==Fo(e),t.encryptionInfo.defaultPerSampleIvSize=Fo(e),t.encryptionInfo.defaultKid=z(Ro(e,16)),t.encryptionInfo.defaultIsProtected&&0===t.encryptionInfo.defaultPerSampleIvSize){const i=Fo(e),r=new Uint8Array(16);r.set(Ro(e,i),0),t.encryptionInfo.defaultConstantIv=r}}break;case"avcC":{const t=this.currentTrack;if(!t)break;if(y(t.info),0===ke.contentSize)break;t.info.codecDescription=Ro(e,ke.contentSize)}break;case"hvcC":{const t=this.currentTrack;if(!t)break;if(y(t.info),0===ke.contentSize)break;t.info.codecDescription=Ro(e,ke.contentSize)}break;case"vpcC":{const i=this.currentTrack;if(!i)break;y("video"===(null==(t=i.info)?void 0:t.type)),e.skip(4);const r=Fo(e),n=Fo(e),s=Fo(e),a=s>>4,o=s>>1&7,l=1&s,c=Fo(e),u=Fo(e),d=Fo(e);i.info.vp9CodecInfo={profile:r,level:n,bitDepth:a,chromaSubsampling:o,videoFullRangeFlag:l,colourPrimaries:c,transferCharacteristics:u,matrixCoefficients:d}}break;case"av1C":{const t=this.currentTrack;if(!t)break;y("video"===(null==(i=t.info)?void 0:i.type)),e.skip(1);const o=Fo(e),l=o>>5,c=31&o,u=Fo(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 b=Ro(e,ke.contentSize-4),T=Et(b);t.info.av1CodecInfo={profile:l,level:c,tier:d,bitDepth:k,monochrome:f,chromaSubsamplingX:m,chromaSubsamplingY:p,chromaSamplePosition:g,videoFullRangeFlag:null!=(r=null==T?void 0:T.videoFullRangeFlag)?r:0,colourPrimaries:null!=(n=null==T?void 0:T.colourPrimaries)?n:2,transferCharacteristics:null!=(s=null==T?void 0:T.transferCharacteristics)?s:2,matrixCoefficients:null!=(a=null==T?void 0:T.matrixCoefficients)?a:2}}break;case"colr":{const t=this.currentTrack;if(!t)break;y("video"===(null==(o=t.info)?void 0:o.type));const i=Xo(e,4);if("nclx"!==i&&"nclc"!==i)break;const r=Do(e),n=Do(e),s=Do(e);let a;"nclx"===i&&(a=Boolean(128&Fo(e))),t.info.colorSpace={primaries:E[r],transfer:R[n],matrix:A[s],fullRange:a}}break;case"pasp":{const t=this.currentTrack;if(!t)break;y("video"===(null==(l=t.info)?void 0:l.type));const i=Lo(e),r=Lo(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==(d=t.info)?void 0:d.type))break;e.skip(4);y(3===Fo(e)),Oi(e),e.skip(2);const i=Fo(e),r=0!==(64&i),n=0!==(32&i);if(0!==(128&i)&&e.skip(2),r){const t=Fo(e);e.skip(t)}n&&e.skip(2);y(4===Fo(e));const s=Oi(e),a=e.filePos,o=Fo(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":Me._warn(`Unsupported audio codec (objectTypeIndication ${o}) - discarding track.`),e.skip(12),s>e.filePos-a){y(5===Fo(e));const i=Oi(e);if(t.info.codecDescription=Ro(e,i),"aac"===t.info.codec){const e=We(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;y("audio"===(null==(h=t.info)?void 0:h.type)),t.info.pcmLittleEndian=!!(255&Do(e))}break;case"pcmC":{const t=this.currentTrack;if(!t)break;y("audio"===(null==(f=t.info)?void 0:f.type)),e.skip(4);const i=Fo(e);t.info.pcmLittleEndian=Boolean(1&i),t.info.pcmSampleSize=Fo(e)}break;case"dOps":{const t=this.currentTrack;if(!t)break;y("audio"===(null==(m=t.info)?void 0:m.type)),e.skip(1);const i=Fo(e),r=Do(e),n=Lo(e),s=No(e),a=Fo(e);let o;o=0!==a?Ro(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;y("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=Ro(e,s-n),o=new Uint8Array(4+a.byteLength);new DataView(o.buffer).setUint32(0,1716281667,!1),o.set(a,4),t.info.codecDescription=o}break;case"dac3":{const t=this.currentTrack;if(!t)break;y("audio"===(null==(g=t.info)?void 0:g.type));const i=Ro(e,3),r=new ze(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=Ot[s]+a}break;case"dec3":{const t=this.currentTrack;if(!t)break;y("audio"===(null==(k=t.info)?void 0:k.type));const i=(e=>{if(e.length<2)return null;const t=new ze(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}})(Ro(e,ke.contentSize));if(!i){Me._warn("Invalid dec3 box contents, ignoring.");break}const r=Wt(i);null!==r&&(t.info.sampleRate=r),t.info.numberOfChannels=Ht(i)}break;case"ddts":{const t=this.currentTrack;if(!t)break;y("audio"===(null==(v=t.info)?void 0:v.type));const i=(e=>{if(e.length<20)return null;const t=I(e),i=t.getUint32(0);if(0===i)return null;const r=new ze(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=ii(o):ae.id===i);if(!r)break;const n=Lo(e),s=(12&n)>>2,a=3&n,o=[Fo,Do,Mo,Lo],l=o[(48&n)>>4],c=o[s],u=o[a],d=Lo(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!=(w=null==d?void 0:d.defaultSampleDescriptionIndex)?w:null,defaultSampleDuration:null!=(P=null==d?void 0:d.defaultSampleDuration)?P:null,defaultSampleSize:null!=(C=null==d?void 0:d.defaultSampleSize)?C:null,defaultSampleFlags:null!=(B=null==d?void 0:d.defaultSampleFlags)?B:null,startTimestamp:null,encryptionAuxInfo:null},i?u.currentFragmentState.baseDataOffset=Wo(e):l&&(u.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),r&&(u.currentFragmentState.sampleDescriptionIndex=Lo(e)),n&&(u.currentFragmentState.defaultSampleDuration=Lo(e)),s&&(u.currentFragmentState.defaultSampleSize=Lo(e)),a&&(u.currentFragmentState.defaultSampleFlags=Lo(e)),o&&(u.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{const t=this.currentTrack;if(!t)break;y(t.currentFragmentState);const i=Fo(e);e.skip(3);const r=0===i?Lo(e):Wo(e);t.currentFragmentState.startTimestamp=r}break;case"trun":{const t=this.currentTrack;if(!t)break;y(this.currentFragment),y(t.currentFragmentState);const i=Fo(e),r=Mo(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=Lo(e);let d=null;n&&(d=Uo(e));let h,f=null;s&&(f=Lo(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=Ro(e,r));const s=or(t);s.defaultSampleInfoSize=i,s.sampleSizes=n,s.sampleCount=r}break;case"saio":{const t=this.currentTrack;if(!t||!t.encryptionInfo)break;const i=Fo(e);if(1&Mo(e)){const i=Xo(e,4),r=Lo(e);if(i!==t.encryptionInfo.scheme||0!==r)break}const r=Lo(e);if(0===r)break;r>1&&Me._warn("Multiple saio entries are not supported; using the first offset only.");let n=0===i?Lo(e):Number(Wo(e));this.currentFragment&&(n+=this.currentFragment.moofOffset);or(t).offset=n}break;case"senc":{const t=this.currentTrack;if(!t||!t.encryptionInfo)break;y(this.currentFragment);const i=this.currentFragment.trackData.get(t.id);if(!i)break;e.skip(1);const r=Mo(e),n=Boolean(2&r),s=Lo(e),a=t.encryptionInfo.defaultPerSampleIvSize;y(null!==a);for(let o=0;o0?r.set(Ro(e,a),0):r.set(t.encryptionInfo.defaultConstantIv,0);let s=null;if(n){const t=Do(e);s=[];for(let i=0;i0&&(null!=(ue=this.metadataTags).trackNumber||(ue.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=I(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=I(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 Yi{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 d(this,null,function*(){var e;const t=this.internalTrack;if(t.durationInMediaTimescale<=0)return null;y(t.trackBacking);const i=yield t.trackBacking.getFirstPacket({metadataOnly:!0});return(null!=(e=null==i?void 0:i.timestamp)?e:0)+t.durationInMediaTimescale/t.timescale})}getLiveRefreshInterval(){return d(this,null,function*(){return null})}getFirstPacket(e){return d(this,null,function*(){const t=yield this.fetchPacketForSampleIndex(0,e);return t||!this.internalTrack.demuxer.isFragmented?t:this.performFragmentedLookup(null,e=>e.trackData.get(this.internalTrack.id)?{sampleIndex:0,correctSampleFound:!0}:{sampleIndex:-1,correctSampleFound:!1},-1/0,1/0,e)})}mapTimestampIntoTimescale(e){return ee(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}getPacket(e,t){return d(this,null,function*(){const i=this.mapTimestampIntoTimescale(e),r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),n=er(r,i),s=yield this.fetchPacketForSampleIndex(n,t);return ar(r)&&this.internalTrack.demuxer.isFragmented?this.performFragmentedLookup(null,e=>{const t=e.trackData.get(this.internalTrack.id);if(!t)return{sampleIndex:-1,correctSampleFound:!1};const r=W(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=X(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 y(-1!==e),{sampleIndex:e,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)})}fetchPacketForSampleIndex(e,t){return d(this,null,function*(){if(-1===e)return null;const i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),r=ir(i,e);if(!r)return null;let n;if(t.metadataOnly)n=_i;else{let t=this.internalTrack.demuxer.reader.requestSlice(r.sampleOffset,r.sampleSize);if(Te(t)&&(t=yield t),!t)return null;if(n=Ro(t,r.sampleSize),this.internalTrack.encryptionInfo){let t=null;if(this.internalTrack.encryptionAuxInfo){const i=yield lr(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);ee.timestamp),f=-1!==h?this.internalTrack.fragmentLookupTable[h]:null,m=W(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(Te(e)&&(e=yield e),!e)break;const i=k,s=Di(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.moofOffsetd(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&&_t(e.data)}}else{const e=yield this.getFirstPacket({}),t=e&&Et(e.data);t&&(this.internalTrack.info.av1CodecInfo=t)}else{const t=yield this.getFirstPacket({}),i=t&&Ct(t.data);i&&(this.internalTrack.info.vp9CodecInfo=u(c({},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&&pt(e.data)}else{const e=yield this.getFirstPacket({});this.internalTrack.info.avcCodecInfo=e&&st(e.data)}if(!D(this.internalTrack.info.colorSpace)){const e=fi(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:hi(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 Zi extends Yi{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 d(this,null,function*(){var e;return this.internalTrack.info.codec?null!=(e=this.decoderConfigPromise)?e:this.decoderConfigPromise=(()=>d(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&&Zt(e.data)}return{codec:mi(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 er=(e,t)=>{if(e.presentationTimestamps){const i=W(e.presentationTimestamps,t,e=>e.presentationTimestamp);return-1===i?-1:e.presentationTimestamps[i].sampleIndex}{const i=W(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)}},tr=(e,t)=>{var i;if(!e.keySampleIndices)return er(e,t);if(e.presentationTimestamps){const i=W(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!==q(e.keySampleIndices,i,e=>e))return i}return-1}{const r=er(e,t),n=W(e.keySampleIndices,r,e=>e);return null!=(i=e.keySampleIndices[n])?i:-1}},ir=(e,t)=>{const i=W(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=W(e.sampleCompositionTimeOffsets,t,e=>e.startIndex),a=e.sampleCompositionTimeOffsets[s];a&&t-a.startIndexe.startSampleIndex),c=e.sampleToChunk[l];y(c);const u=c.startChunkIndex+Math.floor((t-c.startSampleIndex)/c.samplesPerChunk),d=e.chunkOffsets[u],h=c.startSampleIndex+(u-c.startChunkIndex)*c.samplesPerChunk;let f=0,m=d;if(1===e.sampleSizes.length)m+=o*(t-h),f+=o*c.samplesPerChunk;else for(let g=h;ge)}},rr=(e,t)=>{var i;if(!e.keySampleIndices)return t+1;const r=W(e.keySampleIndices,t,e=>e);return null!=(i=e.keySampleIndices[r+1])?i:-1},nr=(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},sr=e=>{const[t,i]=e,r=Math.atan2(i,t);return Number.isFinite(r)?r*(180/Math.PI):0},ar=e=>0===e.sampleSizes.length,or=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}},lr=(e,t,i)=>d(null,null,function*(){if(i.resolved)return i.resolved;if(null===i.offset||0===i.sampleCount)throw new Error("Incomplete saiz/saio info; cannot resolve encryption data.");let r=0;if(i.defaultSampleInfoSize>0)r=i.defaultSampleInfoSize*i.sampleCount;else{y(i.sampleSizes);for(let e=0;e0?i.defaultSampleInfoSize:i.sampleSizes[e],o=new Uint8Array(16);s>0?o.set(Ro(n,s),0):o.set(t.defaultConstantIv,0);let l=null;if(r>s){const e=Do(n);l=[];for(let t=0;te.defaultConstantIv?{iv:e.defaultConstantIv,subsamples:null}:null,ur=(e,t,i,r)=>d(null,null,function*(){var n;y(e.encryptionInfo);const s=e.encryptionInfo;y(null!==s.defaultKid);const a=s.defaultKid;let o;const l=e.demuxer.decryptionKeyCache.get(a);if(l)o=yield l;else{if(!(null==(n=e.demuxer.input._formatOptions.isobmff)?void 0:n.resolveKeyId))throw new Error("Encrypted media samples encountered. To decrypt them, please provide a callback for InputOptions.formatOptions.isobmff.resolveKeyId.");const t=d(null,null,function*(){let t=e.demuxer.psshBoxes;if(r){t=[...t,...r.psshBoxes].filter(e=>null===e.keyIds||e.keyIds.includes(a));for(let e=0;e{y(e.length%2===0);const t=new Uint8Array(e.length/2);for(let i=0;id(null,null,function*(){const n=new Uint8Array(16);n.set(i.iv,0);const s=yield crypto.subtle.importKey("raw",e,{name:"AES-CTR"},!1,["decrypt"]),a=e=>d(null,null,function*(){const t=yield crypto.subtle.decrypt({name:"AES-CTR",counter:n,length:64},s,e);return new Uint8Array(t)});if(!i.subsamples)return a(r);y(null!==t.defaultCryptByteBlock&&null!==t.defaultSkipByteBlock);const o=fr(i.subsamples,t.defaultCryptByteBlock,t.defaultSkipByteBlock);let l=0;for(const e of o)for(const t of e.perSubsample)l+=t.length;const c=new Uint8Array(l);let u=0;for(const e of o)for(const t of e.perSubsample)c.set(r.subarray(t.offset,t.offset+t.length),u),u+=t.length;const h=yield a(c),f=new Uint8Array(r);let m=0;for(const e of o)for(const t of e.perSubsample)f.set(h.subarray(m,m+t.length),t.offset),m+=t.length;return f}),hr=(e,t,i,r)=>{const n=new Gi;n.init({key:e,iv:i.iv});const s=t.defaultCryptByteBlock,a=t.defaultSkipByteBlock;if(y(null!==s&&null!==a),!i.subsamples){const e=new Uint8Array(r),t=Math.floor(r.length/16);for(let i=0;i{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 mr,pr;(pr=mr||(mr={}))[pr.EBML=440786851]="EBML",pr[pr.EBMLVersion=17030]="EBMLVersion",pr[pr.EBMLReadVersion=17143]="EBMLReadVersion",pr[pr.EBMLMaxIDLength=17138]="EBMLMaxIDLength",pr[pr.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",pr[pr.DocType=17026]="DocType",pr[pr.DocTypeVersion=17031]="DocTypeVersion",pr[pr.DocTypeReadVersion=17029]="DocTypeReadVersion",pr[pr.Void=236]="Void",pr[pr.Segment=408125543]="Segment",pr[pr.SeekHead=290298740]="SeekHead",pr[pr.Seek=19899]="Seek",pr[pr.SeekID=21419]="SeekID",pr[pr.SeekPosition=21420]="SeekPosition",pr[pr.Duration=17545]="Duration",pr[pr.Info=357149030]="Info",pr[pr.TimestampScale=2807729]="TimestampScale",pr[pr.MuxingApp=19840]="MuxingApp",pr[pr.WritingApp=22337]="WritingApp",pr[pr.Tracks=374648427]="Tracks",pr[pr.TrackEntry=174]="TrackEntry",pr[pr.TrackNumber=215]="TrackNumber",pr[pr.TrackUID=29637]="TrackUID",pr[pr.TrackType=131]="TrackType",pr[pr.FlagEnabled=185]="FlagEnabled",pr[pr.FlagDefault=136]="FlagDefault",pr[pr.FlagForced=21930]="FlagForced",pr[pr.FlagOriginal=21934]="FlagOriginal",pr[pr.FlagHearingImpaired=21931]="FlagHearingImpaired",pr[pr.FlagVisualImpaired=21932]="FlagVisualImpaired",pr[pr.FlagCommentary=21935]="FlagCommentary",pr[pr.FlagLacing=156]="FlagLacing",pr[pr.Name=21358]="Name",pr[pr.Language=2274716]="Language",pr[pr.LanguageBCP47=2274717]="LanguageBCP47",pr[pr.CodecID=134]="CodecID",pr[pr.CodecPrivate=25506]="CodecPrivate",pr[pr.CodecDelay=22186]="CodecDelay",pr[pr.SeekPreRoll=22203]="SeekPreRoll",pr[pr.DefaultDuration=2352003]="DefaultDuration",pr[pr.Video=224]="Video",pr[pr.PixelWidth=176]="PixelWidth",pr[pr.PixelHeight=186]="PixelHeight",pr[pr.DisplayWidth=21680]="DisplayWidth",pr[pr.DisplayHeight=21690]="DisplayHeight",pr[pr.DisplayUnit=21682]="DisplayUnit",pr[pr.AlphaMode=21440]="AlphaMode",pr[pr.Audio=225]="Audio",pr[pr.SamplingFrequency=181]="SamplingFrequency",pr[pr.Channels=159]="Channels",pr[pr.BitDepth=25188]="BitDepth",pr[pr.SimpleBlock=163]="SimpleBlock",pr[pr.BlockGroup=160]="BlockGroup",pr[pr.Block=161]="Block",pr[pr.BlockAdditions=30113]="BlockAdditions",pr[pr.BlockMore=166]="BlockMore",pr[pr.BlockAdditional=165]="BlockAdditional",pr[pr.BlockAddID=238]="BlockAddID",pr[pr.BlockDuration=155]="BlockDuration",pr[pr.ReferenceBlock=251]="ReferenceBlock",pr[pr.Cluster=524531317]="Cluster",pr[pr.Timestamp=231]="Timestamp",pr[pr.Cues=475249515]="Cues",pr[pr.CuePoint=187]="CuePoint",pr[pr.CueTime=179]="CueTime",pr[pr.CueTrackPositions=183]="CueTrackPositions",pr[pr.CueTrack=247]="CueTrack",pr[pr.CueClusterPosition=241]="CueClusterPosition",pr[pr.Colour=21936]="Colour",pr[pr.MatrixCoefficients=21937]="MatrixCoefficients",pr[pr.TransferCharacteristics=21946]="TransferCharacteristics",pr[pr.Primaries=21947]="Primaries",pr[pr.Range=21945]="Range",pr[pr.Projection=30320]="Projection",pr[pr.ProjectionType=30321]="ProjectionType",pr[pr.ProjectionPoseRoll=30325]="ProjectionPoseRoll",pr[pr.Attachments=423732329]="Attachments",pr[pr.AttachedFile=24999]="AttachedFile",pr[pr.FileDescription=18046]="FileDescription",pr[pr.FileName=18030]="FileName",pr[pr.FileMediaType=18016]="FileMediaType",pr[pr.FileData=18012]="FileData",pr[pr.FileUID=18094]="FileUID",pr[pr.Chapters=272869232]="Chapters",pr[pr.Tags=307544935]="Tags",pr[pr.Tag=29555]="Tag",pr[pr.Targets=25536]="Targets",pr[pr.TargetTypeValue=26826]="TargetTypeValue",pr[pr.TargetType=25546]="TargetType",pr[pr.TagTrackUID=25541]="TagTrackUID",pr[pr.TagEditionUID=25545]="TagEditionUID",pr[pr.TagChapterUID=25540]="TagChapterUID",pr[pr.TagAttachmentUID=25542]="TagAttachmentUID",pr[pr.SimpleTag=26568]="SimpleTag",pr[pr.TagName=17827]="TagName",pr[pr.TagLanguage=17530]="TagLanguage",pr[pr.TagString=17543]="TagString",pr[pr.TagBinary=17541]="TagBinary",pr[pr.ContentEncodings=28032]="ContentEncodings",pr[pr.ContentEncoding=25152]="ContentEncoding",pr[pr.ContentEncodingOrder=20529]="ContentEncodingOrder",pr[pr.ContentEncodingScope=20530]="ContentEncodingScope",pr[pr.ContentCompression=20532]="ContentCompression",pr[pr.ContentCompAlgo=16980]="ContentCompAlgo",pr[pr.ContentCompSettings=16981]="ContentCompSettings",pr[pr.ContentEncryption=20533]="ContentEncryption";const gr=[mr.EBML,mr.Segment],kr=[mr.SeekHead,mr.Info,mr.Cluster,mr.Tracks,mr.Cues,mr.Attachments,mr.Chapters,mr.Tags],yr=[...gr,...kr],br=16,Tr=e=>{if(e.remainingLength<1)return null;const t=Fo(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=Fo(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=Tr(e);if(null===t)return null;if(e.remainingLength{if(e.remainingLength<1)return null;if(255===Fo(e))return;e.skip(-1);const t=vr(e);return null===t?null:72057594037927940!==t?t:void 0},Ir=e=>{y(e.remainingLength>=2);const t=wr(e);if(null===t)return null;const i=Pr(e);return null===i?null:{id:t,size:i}},xr=(e,t)=>{const i=Ro(e,t);let r=0;for(;r{const i=Ro(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):Ko(e)},Er=(e,t,i,r)=>d(null,null,function*(){const n=new Set(i);let s=t;for(;null===r||ss?r:s,found:!1}}),_r=(e,t,i,r)=>d(null,null,function*(){const n=o(2,16),s=new Set(i);let a=t;for(;ae.tracks.map(e=>e.trackBacking))})}getMimeType(){return d(this,null,function*(){yield this.readMetadata();const e=yield this.getTrackBackings(),t=yield Promise.all(e.map(e=>e.getDecoderConfig().then(e=>{var t;return null!=(t=null==e?void 0:e.codec)?t:null})));return(e=>{let t=(e.hasVideo?"video/":e.hasAudio?"audio/":"application/")+(e.isWebM?"webm":"x-matroska");e.codecStrings.length>0&&(t+=`; codecs="${[...new Set(e.codecStrings.filter(Boolean))].join(", ")}"`);return t})({isWebM:this.isWebM,hasVideo:this.segments.some(e=>e.tracks.some(e=>{var t;return"video"===(null==(t=e.info)?void 0:t.type)})),hasAudio:this.segments.some(e=>e.tracks.some(e=>{var t;return"audio"===(null==(t=e.info)?void 0:t.type)})),codecStrings:t.filter(Boolean)})})}getMetadataTags(){return d(this,null,function*(){yield this.readMetadata();for(const t of this.segments)t.metadataTagsCollected||(null!==this.reader.fileSize&&(yield this.loadSegmentMetadata(t)),t.metadataTagsCollected=!0);let e={};for(const t of this.segments)e=c(c({},e),t.metadataTags);return e})}readMetadata(){var e;return null!=(e=this.readMetadataPromise)?e:this.readMetadataPromise=(()=>d(this,null,function*(){let e=0;for(;;){let t=this.reader.requestSliceRange(e,2,br);if(Te(t)&&(t=yield t),!t)break;const i=Ir(t);if(!i)break;const r=i.id;let n=i.size;const s=t.filePos;if(r===mr.EBML){jr(n);let e=this.reader.requestSlice(s,n);if(Te(e)&&(e=yield e),!e)break;this.readContiguousElements(e)}else if(r===mr.Segment){if(yield this.readSegment(s,n),void 0===n)break;if(null===this.reader.fileSize)break}else if(r===mr.Cluster){if(null===this.reader.fileSize)break;if(void 0===n){n=(yield Er(this.reader,s,yr,this.reader.fileSize)).pos-s}const e=T(this.segments);e&&(e.elementEndPos=s+n)}jr(n),e=s+n}}))()}readSegment(e,t){return d(this,null,function*(){var i;this.currentSegment={seekHeadSeen:!1,infoSeen:!1,tracksSeen:!1,cuesSeen:!1,tagsSeen:!1,attachmentsSeen:!1,timestampScale:-1,timestampFactor:-1,duration:-1,seekEntries:[],tracks:[],cuePoints:[],dataStartPos:e,elementEndPos:void 0===t?null:e+t,clusterSeekStartPos:e,lastReadCluster:null,metadataTags:{},metadataTagsCollected:!1},this.segments.push(this.currentSegment);let r=e;for(;null===this.currentSegment.elementEndPos||re.id===s);if(-1!==l){const e=Jr[l].flag;this.currentSegment[e]=!0,jr(a);let t=this.reader.requestSlice(o,a);Te(t)&&(t=yield t),t&&this.readContiguousElements(t)}else if(s===mr.Tags||s===mr.Attachments){s===mr.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,jr(a);let e=this.reader.requestSlice(o,a);Te(e)&&(e=yield e),e&&this.readContiguousElements(e)}else if(s===mr.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=Jr.find(e=>e.id===t.id);if(!i)continue;if(this.currentSegment[i.flag])continue;let r=this.reader.requestSliceRange(e+t.segmentPosition,2,br);if(Te(r)&&(r=yield r),!r)continue;const n=Ir(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);Te(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 d(this,null,function*(){var i;if((null==(i=t.lastReadCluster)?void 0:i.elementStartPos)===e)return t.lastReadCluster;let r=this.reader.requestSliceRange(e,2,br);Te(r)&&(r=yield r),y(r);const n=e,s=Ir(r);y(s);y(s.id===mr.Cluster);let a=s.size;const o=r.filePos;if(void 0===a){a=(yield Er(this.reader,o,yr,t.elementEndPos)).pos-o}let l=this.reader.requestSlice(o,a);Te(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,yr);c.elementEndPos=e}for(const[,e]of c.trackData){const t=e.track;y(e.blocks.length>0);let i=!1;for(let n=0;n({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[T(e.presentationTimestamps).blockIndex];e.startTimestamp=r.timestamp,e.endTimestamp=s.timestamp+s.duration;const a=W(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,d,h,f,m,p,g,k,T,v,S,w,P,I,C,B,_,F,D,N,O,L,z,U,q,W,H,V,j,K,X,$,G,Q,Y,J,ee,te,ie,re,ne,se,oe,le,ce;const ue=Ir(e);if(!ue)return!1;if(t&&t.includes(ue.id))return!1;const{id:de,size:he}=ue,fe=e.filePos;switch(jr(he),de){case mr.DocType:this.isWebM="webm"===xr(e,he);break;case mr.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 mr.SeekID:{const t=null==(i=this.currentSegment)?void 0:i.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.id=Sr(e,he)}break;case mr.SeekPosition:{const t=null==(r=this.currentSegment)?void 0:r.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.segmentPosition=Sr(e,he)}break;case mr.TimestampScale:if(!this.currentSegment)break;this.currentSegment.timestampScale=Sr(e,he),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale;break;case mr.Duration:if(!this.currentSegment)break;this.currentSegment.duration=Br(e,he);break;case mr.TrackEntry:if(!this.currentSegment)break;if(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:u(c({},Le),{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!==$r.Block||e.data.algorithm!==Qr.HeaderStripping})&&(Me._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===Rr)this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(this.currentTrack.codecId===Fr)this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(t===Ar)this.currentTrack.info.codec="vp8";else if(t===Dr)this.currentTrack.info.codec="vp9";else if(t===Mr)this.currentTrack.info.codec="av1";else if(t===Nr){const e=this.currentTrack.codecPrivate?x.decode(this.currentTrack.codecPrivate):"";ui.includes(e)&&(this.currentTrack.info.codec="prores",this.currentTrack.info.proresFormat=e)}const e=this.currentTrack;this.currentTrack.trackBacking=new rn(e),this.currentSegment.tracks.push(this.currentTrack)}else if("audio"===this.currentTrack.info.type){t===Or?(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===Lr?this.currentTrack.info.codec="mp3":t===zr?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=pi):t===Ur?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===qr?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Wr?(this.currentTrack.info.codec="ac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Hr?(this.currentTrack.info.codec="eac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Vr?(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 nn(e),this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null;break;case mr.TrackNumber:if(!this.currentTrack)break;this.currentTrack.id=Sr(e,he);break;case mr.TrackType:{if(!this.currentTrack)break;const t=Sr(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:c({},M),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 mr.FlagEnabled:if(!this.currentTrack)break;Sr(e,he)||(this.currentTrack=null);break;case mr.FlagDefault:if(!this.currentTrack)break;this.currentTrack.disposition.default=!!Sr(e,he);break;case mr.FlagForced:if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!Sr(e,he);break;case mr.FlagOriginal:if(!this.currentTrack)break;this.currentTrack.disposition.original=!!Sr(e,he);break;case mr.FlagHearingImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!Sr(e,he);break;case mr.FlagVisualImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!Sr(e,he);break;case mr.FlagCommentary:if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!Sr(e,he);break;case mr.CodecID:if(!this.currentTrack)break;this.currentTrack.codecId=xr(e,he);break;case mr.CodecPrivate:if(!this.currentTrack)break;this.currentTrack.codecPrivate=Ro(e,he);break;case mr.DefaultDuration:if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=Sr(e,he);break;case mr.Name:if(!this.currentTrack)break;this.currentTrack.name=Cr(e,he);break;case mr.Language:if(!this.currentTrack)break;if(this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=xr(e,he),ae(this.currentTrack.languageCode)||(this.currentTrack.languageCode=Z);break;case mr.LanguageBCP47:{if(!this.currentTrack)break;const t=xr(e,he).split("-")[0];this.currentTrack.languageCode=t||Z,this.currentTrack.hasLanguageBcp47=!0}break;case mr.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 mr.PixelWidth:if("video"!==(null==(o=null==(a=this.currentTrack)?void 0:a.info)?void 0:o.type))break;this.currentTrack.info.width=Sr(e,he);break;case mr.PixelHeight:if("video"!==(null==(d=null==(l=this.currentTrack)?void 0:l.info)?void 0:d.type))break;this.currentTrack.info.height=Sr(e,he);break;case mr.DisplayWidth:if("video"!==(null==(f=null==(h=this.currentTrack)?void 0:h.info)?void 0:f.type))break;this.currentTrack.info.displayWidth=Sr(e,he);break;case mr.DisplayHeight:if("video"!==(null==(p=null==(m=this.currentTrack)?void 0:m.info)?void 0:p.type))break;this.currentTrack.info.displayHeight=Sr(e,he);break;case mr.DisplayUnit:if("video"!==(null==(k=null==(g=this.currentTrack)?void 0:g.info)?void 0:k.type))break;this.currentTrack.info.displayUnit=Sr(e,he);break;case mr.AlphaMode:if("video"!==(null==(v=null==(T=this.currentTrack)?void 0:T.info)?void 0:v.type))break;this.currentTrack.info.alphaMode=1===Sr(e,he);break;case mr.Colour:if("video"!==(null==(w=null==(S=this.currentTrack)?void 0:S.info)?void 0:w.type))break;this.readContiguousElements(e.slice(fe,he));break;case mr.MatrixCoefficients:{if("video"!==(null==(I=null==(P=this.currentTrack)?void 0:P.info)?void 0:I.type))break;const t=Sr(e,he),i=A[t];this.currentTrack.info.colorSpace.matrix=i}break;case mr.Range:{if("video"!==(null==(B=null==(C=this.currentTrack)?void 0:C.info)?void 0:B.type))break;const t=Sr(e,he);this.currentTrack.info.colorSpace.fullRange=1===t||2===t?2===t:void 0}break;case mr.TransferCharacteristics:{if("video"!==(null==(F=null==(_=this.currentTrack)?void 0:_.info)?void 0:F.type))break;const t=Sr(e,he),i=R[t];this.currentTrack.info.colorSpace.transfer=i}break;case mr.Primaries:{if("video"!==(null==(N=null==(D=this.currentTrack)?void 0:D.info)?void 0:N.type))break;const t=Sr(e,he),i=E[t];this.currentTrack.info.colorSpace.primaries=i}break;case mr.Projection:if("video"!==(null==(L=null==(O=this.currentTrack)?void 0:O.info)?void 0:L.type))break;this.readContiguousElements(e.slice(fe,he));break;case mr.ProjectionPoseRoll:{if("video"!==(null==(U=null==(z=this.currentTrack)?void 0:z.info)?void 0:U.type))break;const t=-Br(e,he);try{this.currentTrack.info.rotation=b(t)}catch(me){}}break;case mr.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 mr.SamplingFrequency:if("audio"!==(null==(V=null==(H=this.currentTrack)?void 0:H.info)?void 0:V.type))break;this.currentTrack.info.sampleRate=Br(e,he);break;case mr.Channels:if("audio"!==(null==(K=null==(j=this.currentTrack)?void 0:j.info)?void 0:K.type))break;this.currentTrack.info.numberOfChannels=Sr(e,he);break;case mr.BitDepth:if("audio"!==(null==($=null==(X=this.currentTrack)?void 0:X.info)?void 0:$.type))break;this.currentTrack.info.bitDepth=Sr(e,he);break;case mr.CuePoint:if(!this.currentSegment)break;this.readContiguousElements(e.slice(fe,he)),this.currentCueTime=null;break;case mr.CueTime:this.currentCueTime=Sr(e,he);break;case mr.CueTrackPositions:{if(null===this.currentCueTime)break;y(this.currentSegment);const t={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(t),this.readContiguousElements(e.slice(fe,he)),-1!==t.trackId&&-1!==t.clusterPosition||this.currentSegment.cuePoints.pop()}break;case mr.CueTrack:{const t=null==(G=this.currentSegment)?void 0:G.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;t.trackId=Sr(e,he)}break;case mr.CueClusterPosition:{const t=null==(Q=this.currentSegment)?void 0:Q.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;y(this.currentSegment),t.clusterPosition=this.currentSegment.dataStartPos+Sr(e,he)}break;case mr.Timestamp:if(!this.currentCluster)break;this.currentCluster.timestamp=Sr(e,he);break;case mr.SimpleBlock:{if(!this.currentCluster)break;const t=vr(e);if(null===t)break;const i=this.getTrackDataInCluster(this.currentCluster,t);if(!i)break;const r=No(e),n=Fo(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=Ro(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 mr.BlockGroup:if(!this.currentCluster)break;this.readContiguousElements(e.slice(fe,he)),this.currentBlock=null;break;case mr.Block:{if(!this.currentCluster)break;const t=vr(e);if(null===t)break;const i=this.getTrackDataInCluster(this.currentCluster,t);if(!i)break;const r=No(e),n=Fo(e)>>1&3,s=Ro(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 mr.BlockAdditions:this.readContiguousElements(e.slice(fe,he));break;case mr.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 mr.BlockAdditional:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=Ro(e,he);break;case mr.BlockAddID:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=Sr(e,he);break;case mr.BlockDuration:if(!this.currentBlock)break;this.currentBlock.duration=Sr(e,he);break;case mr.ReferenceBlock:if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1;break;case mr.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(fe,he));break;case mr.Targets:this.readContiguousElements(e.slice(fe,he));break;case mr.TargetTypeValue:50!==Sr(e,he)&&(this.currentTagTargetIsMovie=!1);break;case mr.TagTrackUID:case mr.TagEditionUID:case mr.TagChapterUID:case mr.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case mr.SimpleTag:if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(fe,he));break;case mr.TagName:this.currentSimpleTagName=Cr(e,he);break;case mr.TagString:{if(!this.currentSimpleTagName)break;const t=Cr(e,he);this.processTagValue(this.currentSimpleTagName,t)}break;case mr.TagBinary:{if(!this.currentSimpleTagName)break;const t=Ro(e,he);this.processTagValue(this.currentSimpleTagName,t)}break;case mr.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 Oe(this.currentAttachedFile.fileData,null!=(J=this.currentAttachedFile.fileMediaType)?J:void 0,null!=(ee=this.currentAttachedFile.fileName)?ee:void 0,null!=(te=this.currentAttachedFile.fileDescription)?te:void 0)),(null==(ie=this.currentAttachedFile.fileMediaType)?void 0:ie.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!=(re=this.currentAttachedFile.fileName)?re:void 0,description:null!=(ne=this.currentAttachedFile.fileDescription)?ne:void 0})}this.currentAttachedFile=null}break;case mr.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 mr.ContentEncoding:this.currentDecodingInstruction={order:0,scope:$r.Block,data:null},this.readContiguousElements(e.slice(fe,he)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case mr.ContentEncodingOrder:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=Sr(e,he);break;case mr.ContentEncodingScope:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=Sr(e,he);break;case mr.ContentCompression:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:Qr.Zlib,settings:null},this.readContiguousElements(e.slice(fe,he));break;case mr.ContentCompAlgo:if("decompress"!==(null==(oe=null==(se=this.currentDecodingInstruction)?void 0:se.data)?void 0:oe.type))break;this.currentDecodingInstruction.data.algorithm=Sr(e,he);break;case mr.ContentCompSettings:if("decompress"!==(null==(ce=null==(le=this.currentDecodingInstruction)?void 0:le.data)?void 0:ce.type))break;this.currentDecodingInstruction.data.settings=Ro(e,he);break;case mr.ContentEncryption:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}return e.filePos=fe+he,!0}decodeBlockData(e,t){y(e.decodingInstructions.length>0);let i=t;for(const r of e.decodingInstructions)if(y(r.data),"decompress"===r.data.type)if(r.data.algorithm===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,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 d(this,null,function*(){if(e.duration<=0)return null;let t=null;for(const r of e.tracks){y(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 tn{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 d(this,null,function*(){return this.internalTrack.demuxer.getDurationFromMetadata(this.internalTrack.segment)})}getLiveRefreshInterval(){return d(this,null,function*(){return null})}getFirstPacket(e){return d(this,null,function*(){return this.performClusterLookup(null,e=>e.trackData.get(this.internalTrack.id)?{blockIndex:0,correctBlockFound:!0}:{blockIndex:-1,correctBlockFound:!1},-1/0,1/0,e)})}intoTimescale(e){return ee(e*this.internalTrack.segment.timestampFactor)}getPacket(e,t){return d(this,null,function*(){const i=this.intoTimescale(e);return this.performClusterLookup(null,e=>{const t=e.trackData.get(this.internalTrack.id);if(!t)return{blockIndex:-1,correctBlockFound:!1};const r=W(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=X(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 y(-1!==e),{blockIndex:e,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)})}fetchPacketInCluster(e,t,i){return d(this,null,function*(){var r,n;if(-1===t)return null;const s=e.trackData.get(this.internalTrack.id).blocks[t];if(y(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);I(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?_i: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?_i:s.mainAdditional,c.alphaByteLength=s.mainAdditional.byteLength);const u=new Ri(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 d(this,null,function*(){var s,a,o,l;const{demuxer:c,segment:u}=this.internalTrack;let d=null,h=null,f=-1;if(e){const{blockIndex:i,correctBlockFound:r}=t(e);if(r)return this.fetchPacketInCluster(e,i,n);-1!==i&&(h=e,f=i)}const m=W(this.internalTrack.cuePoints,i,e=>e.time),p=-1!==m?this.internalTrack.cuePoints[m]:null,g=W(this.internalTrack.clusterPositionCache,i,e=>e.startTimestamp),k=-1!==g?this.internalTrack.clusterPositionCache[g]:null,b=Math.max(null!=(s=null==p?void 0:p.clusterPosition)?s:0,null!=(a=null==k?void 0:k.elementStartPos)?a:0)||null;let T;for(e?null===b||e.elementStartPos>=b?(T=e.elementEndPos,d=e):T=b:T=null!=b?b:u.clusterSeekStartPos;null===u.elementEndPos||T<=u.elementEndPos-2;){if(d){const e=d.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>r)break}let e=c.reader.requestSliceRange(T,2,br);if(Te(e)&&(e=yield e),!e)break;const i=T,s=Ir(e);if(!s||!kr.includes(s.id)&&s.id!==mr.Void){const e=yield _r(c.reader,i,kr,Math.min(null!=(o=u.elementEndPos)?o:1/0,i+Zr));if(e){T=e;continue}break}const a=s.id;let l=s.size;const m=e.filePos;if(a===mr.Cluster){d=yield c.readCluster(i,u),l=d.elementEndPos-m;const{blockIndex:e,correctBlockFound:r}=t(d);if(r)return this.fetchPacketInCluster(d,e,n);-1!==e&&(h=d,f=e)}if(void 0===l){y(a!==mr.Cluster);l=(yield Er(c.reader,m,yr,u.elementEndPos)).pos-m}const p=m+l;if(null===u.elementEndPos){let e=c.reader.requestSliceRange(p,2,br);if(Te(e)&&(e=yield e),!e)break;if(wr(e)===mr.Segment){u.elementEndPos=p;break}}T=p}if(p&&(!h||h.elementStartPosd(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?st(s.data):null,hevcCodecInfo:"hevc"===this.internalTrack.info.codec&&s?pt(s.data):null,vp9CodecInfo:"vp9"===this.internalTrack.info.codec&&s?Ct(s.data):null,av1CodecInfo:"av1"===this.internalTrack.info.codec&&s?Et(s.data):null,proresCodecInfo:"prores"===this.internalTrack.info.codec&&s?_t(s.data):null,proresFormat:this.internalTrack.info.proresFormat};if(!D(this.internalTrack.info.colorSpace)){const n=fi(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:hi(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 nn extends tn{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 d(this,null,function*(){var e;return this.internalTrack.info.codec?null!=(e=this.decoderConfigPromise)?e:this.decoderConfigPromise=(()=>d(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&&Zt(e.data)}return{codec:mi({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 sn=(e,t,i,r=null)=>d(null,null,function*(){const n=o(2,16);let s=t;for(;null===i||s=4;){const t=a.filePos,i=Lo(a),n=null!==e.fileSize?e.fileSize-s: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:s};a.filePos=t+o.bytesAdvanced,s=a.filePos}}return null});class an extends Ei{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 O,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}readMetadata(){return d(this,null,function*(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>d(this,null,function*(){for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)yield this.advanceReader();if(!this.firstFrameHeader&&this.xingFrameHeader&&(this.firstFrameHeader=this.xingFrameHeader,this.firstFrameHeaderPos=this.xingFrameHeaderPos),!this.firstFrameHeader)throw new Error("No valid MP3 frame found.");this.trackBackings=[new on(this)]}))()})}advanceReader(){return d(this,null,function*(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,el);if(Te(e)&&(e=yield e),!e)return void(this.lastSampleLoaded=!0);const t=nl(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}const e=yield sn(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=wi(t.mpegVersionId,t.channel);let r=this.reader.requestSlice(e.startPos+i,4);if(Te(r)&&(r=yield r),r){const n=Lo(r);if(n===vi||n===Si){if(this.xingFrameHeader||(this.xingFrameHeader=t,this.xingFrameHeaderPos=e.startPos),!this.xingData){let t=this.reader.requestSlice(e.startPos+i+4,12);if(Te(t)&&(t=yield t),t){const e=Ro(t,12),i=I(e),r=i.getUint32(0,!1);this.xingData={frameCount:r&xi.FrameCount?i.getUint32(4,!1):null,fileSize:r&xi.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 d(this,null,function*(){return"audio/mpeg"})}getTrackBackings(){return d(this,null,function*(){return yield this.readMetadata(),this.trackBackings})}getMetadataTags(){return d(this,null,function*(){const e=yield this.readingMutex.acquire();try{if(yield this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let e=0,t=!1;for(;;){let i=this.reader.requestSlice(e,el);if(Te(i)&&(i=yield i),!i)break;const r=nl(i);if(!r)break;t=!0;let n=this.reader.requestSlice(i.filePos,r.size);if(Te(n)&&(n=yield n),!n)break;sl(n,r,this.metadataTags),e=i.filePos+r.size}if(!t&&null!==this.reader.fileSize&&this.reader.fileSize>=Zo){let e=this.reader.requestSlice(this.reader.fileSize-Zo,Zo);Te(e)&&(e=yield e),y(e);"TAG"===Xo(e,3)&&il(e,this.metadataTags)}return this.metadataTags}finally{e()}})}}class on{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return y(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate/this.demuxer.firstFrameHeader.audioSamplesInFrame}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return d(this,null,function*(){const e=this.demuxer;if(y(null!==e.firstFrameHeader),y(null!==e.firstFrameHeaderPos),e.xingData){if(null!==e.xingData.frameCount)return e.xingData.frameCount*e.firstFrameHeader.audioSamplesInFrame/e.firstFrameHeader.sampleRate}else if(null!==e.reader.fileSize){const s=(t=e.firstFrameHeader.lowSamplingFrequency,i=e.firstFrameHeader.layer,r=e.firstFrameHeader.bitrate,n=e.firstFrameHeader.sampleRate,0===i?0:1===i?144*r/(n<e.timestamp);if(-1===i)throw new Error("Packet was not created from this track.");const r=i+1;for(;r>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)yield this.demuxer.advanceReader();return this.getPacketAtIndex(r,t)}finally{i()}})}getPacket(e,t){return d(this,null,function*(){const i=yield this.demuxer.readingMutex.acquire();try{for(;;){const i=W(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 un=e=>{const t=I(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},dn=(e,t,i)=>{let r=0,n=null;if(e.length>0)if("vorbis"===t.codec){y(t.vorbisInfo);const s=(1<<(e=>{let t=0;for(;e;)t++,e>>=1;return t})(t.vorbisInfo.modeBlockflags.length-1))-1<<1,a=(e[0]&s)>>1;if(a>=t.vorbisInfo.modeBlockflags.length)throw new Error("Invalid mode number.");let o=i;const l=t.vorbisInfo.modeBlockflags[a];if(n=t.vorbisInfo.blocksizes[l],1===l){const i=1+(1|s),r=e[0]&i?1:0;o=t.vorbisInfo.blocksizes[r]}r=null!==o?o+n>>2:0}else if("opus"===t.codec){r=(e=>{const t=e[0]>>3,i=3&e[0];let r;return r=0===i?1:1===i||2===i?2:63&e[1],{durationInSamples:Rt[t]*r}})(e).durationInSamples}return{durationInSamples:r,vorbisBlockSize:n}},hn=27,fn=282,mn=e=>{const t=e.filePos;if(zo(e)!==ln)return null;e.skip(1);const i=Fo(e),r=Vo(e),n=zo(e),s=zo(e),a=zo(e),o=Fo(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}},pn=(e,t)=>{for(;e.filePos>>8&255)===i||(t>>>16&255)===i||(t>>>24&255)===i){if(e.skip(-4),t===ln)return!0;e.skip(1)}}return!1};class gn extends Ei{constructor(e){super(e),this.metadataPromise=null,this.bitstreams=[],this.trackBackings=[],this.metadataTags={},this.reader=e._reader}readMetadata(){return d(this,null,function*(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>d(this,null,function*(){let e=0;for(;;){let t=this.reader.requestSliceRange(e,hn,fn);if(Te(t)&&(t=yield t),!t)break;const i=mn(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 kn(t,this)))}}))()})}readVorbisMetadata(e,t){return d(this,null,function*(){let i=yield this.findNextPacketStart(e);if(!i)return;const r=yield this.readPacket(i.startPage,i.startSegmentIndex);if(!r)return;if(i=yield this.findNextPacketStart(r),!i)return;const n=yield this.readPacket(i.startPage,i.startSegmentIndex);if(!n)return;if(3!==r.data[0]||5!==n.data[0])return;const s=[],a=e=>{for(;s.push(Math.min(255,e)),!(e<255);)e-=255};a(e.data.length),a(r.data.length);const o=new Uint8Array(1+s.length+e.data.length+r.data.length+n.data.length);o[0]=2,o.set(s,1),o.set(e.data,1+s.length),o.set(r.data,1+s.length+e.data.length),o.set(n.data,1+s.length+e.data.length+r.data.length),t.codecInfo.codec="vorbis",t.description=o,t.lastMetadataPacket=n;const l=I(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:Ft(n.data).modeBlockflags},Nt(r.data.subarray(7),this.metadataTags)})}readOpusMetadata(e,t){return d(this,null,function*(){const i=yield this.findNextPacketStart(e);if(!i)return;const r=yield this.readPacket(i.startPage,i.startSegmentIndex);if(!r)return;t.codecInfo.codec="opus",t.description=e.data,t.lastMetadataPacket=r;const n=(e=>{const t=I(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=pi,t.codecInfo.opusInfo={preSkip:n.preSkip},Nt(r.data.subarray(8),this.metadataTags)})}readPacket(e,t){return d(this,null,function*(){y(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 d(this,null,function*(){return yield this.readMetadata(),this.trackBackings})}getMetadataTags(){return d(this,null,function*(){return yield this.readMetadata(),this.metadataTags})}}class kn{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new O,this.internalSampleRate="opus"===e.codecInfo.codec?pi:e.sampleRate}getType(){return"audio"}getId(){return this.bitstream.serialNumber}getNumber(){const e=this.demuxer.trackBackings.findIndex(e=>e.bitstream===this.bitstream);return y(-1!==e),e+1}getNumberOfChannels(){return this.bitstream.numberOfChannels}getSampleRate(){return this.bitstream.sampleRate}getTimeResolution(){return this.bitstream.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return d(this,null,function*(){return null})}getLiveRefreshInterval(){return d(this,null,function*(){return null})}getCodec(){return this.bitstream.codecInfo.codec}getInternalCodecId(){return null}getDecoderConfig(){return d(this,null,function*(){var e;return y(this.bitstream.codecInfo.codec),{codec:this.bitstream.codecInfo.codec,numberOfChannels:this.bitstream.numberOfChannels,sampleRate:this.bitstream.sampleRate,description:null!=(e=this.bitstream.description)?e:void 0}})}getName(){return null}getLanguageCode(){return Z}getDisposition(){return u(c({},Le),{primary:!1})}granulePositionToTimestampInSamples(e){return"opus"===this.bitstream.codecInfo.codec?(y(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,i){if(!e)return null;const{durationInSamples:r,vorbisBlockSize:n}=dn(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),s=new Ri(i.metadataOnly?_i:e.data,"key",Math.max(0,t.timestampInSamples)/this.internalSampleRate,r/this.internalSampleRate,e.endPage.headerStartPos+e.endSegmentIndex,e.data.byteLength);return this.encodedPacketToMetadata.set(s,{packet:e,timestampInSamples:t.timestampInSamples,durationInSamples:r,vorbisLastBlockSize:t.vorbisLastBlocksize,vorbisBlockSize:n}),s}getFirstPacket(e){return d(this,null,function*(){y(this.bitstream.lastMetadataPacket);const t=yield this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let i=0;"opus"===this.bitstream.codecInfo.codec&&(y(this.bitstream.codecInfo.opusInfo),i-=this.bitstream.codecInfo.opusInfo.preSkip);const r=yield this.demuxer.readPacket(t.startPage,t.startSegmentIndex);return this.createEncodedPacketFromOggPacket(r,{timestampInSamples:i,vorbisLastBlocksize:null},e)})}getNextPacket(e,t){return d(this,null,function*(){const i=this.encodedPacketToMetadata.get(e);if(!i)throw new Error("Packet was not created from this track.");const r=yield this.demuxer.findNextPacketStart(i.packet);if(!r)return null;const n=i.timestampInSamples+i.durationInSamples,s=yield this.demuxer.readPacket(r.startPage,r.startSegmentIndex);return this.createEncodedPacketFromOggPacket(s,{timestampInSamples:n,vorbisLastBlocksize:i.vorbisBlockSize},t)})}getPacket(e,t){return d(this,null,function*(){var i,r;if(null===this.demuxer.reader.fileSize)return this.getPacketSequential(e,t);const n=ee(e*this.internalSampleRate);if(0===n)return this.getFirstPacket(t);if(n<0)return null;y(this.bitstream.lastMetadataPacket);const s=yield this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!s)return null;let a=s.startPage,o=this.demuxer.reader.fileSize;const l=[a];e:for(;a.headerStartPos+a.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,hn,fn);Te(t)&&(t=yield t),y(t);const i=mn(t);y(i),u=i,u.serialNumber===this.bitstream.serialNumber&&d.push(u)}y(-1!==u.granulePosition);let h,f,m=null,p=u,g=0;if(u.headerStartPos===s.startPage.headerStartPos)h=this.granulePositionToTimestampInSamples(0),f=!0,m=0;else{h=0,f=!1;for(let t=u.lacingValues.length-1;t>=0;t--){if(u.lacingValues[t]<255){m=t+1;break}}if(null===m)throw new Error("Invalid page with granule position: no packets end on this page.");g=m-1;const e={data:_i,endPage:p,endSegmentIndex:g};if(yield this.demuxer.findNextPacketStart(e)){const e=bn(d,u,m);y(e);const t=yn(d,e.page,e.segmentIndex);t&&(u=t.page,m=t.segmentIndex)}else for(;;){const e=bn(d,u,m);if(!e)break;const t=yn(d,e.page,e.segmentIndex);if(!t)break;if(u=t.page,m=t.segmentIndex,e.page.headerStartPos!==p.headerStartPos){p=e.page,g=e.segmentIndex;break}}}let k=null,b=null;for(;null!==u;){y(null!==m);const e=yield this.demuxer.readPacket(u,m);if(!e)break;if(!(u.headerStartPos===s.startPage.headerStartPos&&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 d(this,null,function*(){const i=yield this.sequentialScanMutex.acquire();try{const i=ee(e*this.internalSampleRate);e=i/this.internalSampleRate;const r=W(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);y(e),this.sequentialScanCache.length>0&&y(T(this.sequentialScanCache).timestampInSamples<=e.timestampInSamples),this.sequentialScanCache.push(e)}}return n}finally{i()}})}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const yn=(e,t,i)=>{let r=t,n=i;e:for(;;){for(n--;n>=0;n--){if(r.lacingValues[n]<255){n++;break e}}y(-1===n);if(!(1&r.headerType)){n=0;break}const t=K(e,e=>e.headerStartPos{if(i>0)return{page:t,segmentIndex:i-1};const r=K(e,e=>e.headerStartPosd(this,null,function*(){var e,t;let i=this.reader.requestSlice(0,12);Te(i)&&(i=yield i),y(i);const r=Xo(i,4),n="RIFX"!==r,s="RF64"===r,a=Oo(i,n);let o=s?this.reader.fileSize:Math.min(a+8,null!=(e=this.reader.fileSize)?e:1/0);if("WAVE"!==Xo(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=Ao(r,i),s=t-18;if(Math.min(s,e)>=22&&n===Tn.EXTENSIBLE){r.skip(6);const e=Ro(r,16);n=e[0]|e[1]<<8}}if(n!==Tn.MULAW&&n!==Tn.ALAW||(l=8),n!==Tn.PCM&&n!==Tn.IEEE_FLOAT&&n!==Tn.ALAW&&n!==Tn.MULAW)throw new Error(`Unsupported WAVE codec (format tag ${n}). Only integer/float PCM, A-law, and \u03bc-law are supported.`);if(n===Tn.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===Tn.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 d(this,null,function*(){var r,n,s,a,o,l,c,u,d,h,f;let m=this.reader.requestSlice(e,t);if(Te(m)&&(m=yield m),!m)return;const p=Xo(m,4);if("INFO"!==p&&"INF0"!==p)return;let g=m.filePos;for(;g<=e+t-8;){m.filePos=g;const e=Xo(m,4),t=Oo(m,i),p=Ro(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 d(this,null,function*(){let i=this.reader.requestSlice(e,t);if(Te(i)&&(i=yield i),!i)return;const r=nl(i);if(r){const n=t-el;if(r.size=Math.min(r.size,n),r.size>0){const t=i.slice(e+el,r.size);sl(t,r,this.metadataTags)}}})}getCodec(){if(y(this.audioInfo),this.audioInfo.format===Tn.MULAW)return"ulaw";if(this.audioInfo.format===Tn.ALAW)return"alaw";if(this.audioInfo.format===Tn.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===Tn.IEEE_FLOAT){if(4===this.audioInfo.sampleSizeInBytes)return"pcm-f32";if(8===this.audioInfo.sampleSizeInBytes)return"pcm-f64"}y(!1)}getMimeType(){return d(this,null,function*(){return"audio/wav"})}getTrackBackings(){return d(this,null,function*(){return yield this.readMetadata(),this.trackBackings})}getMetadataTags(){return d(this,null,function*(){return yield this.readMetadata(),this.metadataTags})}}const wn=2048;class Pn{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return y(this.demuxer.audioInfo),this.demuxer.audioInfo.format}getDecoderConfig(){return d(this,null,function*(){const e=this.demuxer.getCodec();return e?(y(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null})}getNumberOfChannels(){return y(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return y(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return y(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return d(this,null,function*(){return y(-1!==this.demuxer.dataSize),this.demuxer.dataSize/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate})}getLiveRefreshInterval(){return d(this,null,function*(){return null})}getName(){return null}getLanguageCode(){return Z}getDisposition(){return c({},Le)}getPacketAtIndex(e,t){return d(this,null,function*(){y(e>=0),y(this.demuxer.audioInfo);const i=e*wn*this.demuxer.audioInfo.blockSizeInBytes;if(i>=this.demuxer.dataSize)return null;const r=Math.min(wn*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(Te(e)&&(e=yield e),!e)return null}let n;if(t.metadataOnly)n=_i;else{let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+i,r);Te(e)&&(e=yield e),y(e),n=Ro(e,r)}const s=e*wn/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 Ri(n,"key",s,a,e,r)})}getFirstPacket(e){return this.getPacketAtIndex(0,e)}getPacket(e,t){return d(this,null,function*(){y(this.demuxer.audioInfo);const i=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/wn,(this.demuxer.dataSize-1)/(wn*this.demuxer.audioInfo.blockSizeInBytes)));if(i<0)return null;const r=yield this.getPacketAtIndex(i,t);if(r)return r;if(0===i)return null;y(null===this.demuxer.reader.fileSize);let n=yield this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,t);for(;n;){const e=yield this.getNextPacket(n,t);if(!e)break;n=e}return n})}getNextPacket(e,t){y(this.demuxer.audioInfo);const i=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/wn);return this.getPacketAtIndex(i+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const In=e=>{const t=e.filePos,i=Ro(e,9),r=new ze(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}},xn=1024;class Cn extends Ei{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.trackBackings=[],this.readingMutex=new O,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}readMetadata(){return d(this,null,function*(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>d(this,null,function*(){for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)yield this.advanceReader();y(this.firstFrameHeader),this.trackBackings=[new Bn(this)]}))()})}advanceReader(){return d(this,null,function*(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,el);if(Te(e)&&(e=yield e),!e)return void(this.lastSampleLoaded=!0);const t=nl(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}let e=this.reader.requestSliceRange(this.lastLoadedPos,7,9);if(Te(e)&&(e=yield e),!e)return void(this.lastSampleLoaded=!0);const t=In(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=Ue[t.samplingFrequencyIndex];y(void 0!==i);const r=xn/i,n={timestamp:this.nextTimestampInSamples/i,duration:r,dataStart:t.startPos,dataSize:t.frameLength};this.loadedSamples.push(n),this.nextTimestampInSamples+=xn,this.lastLoadedPos=t.startPos+t.frameLength})}getMimeType(){return d(this,null,function*(){return"audio/aac"})}getTrackBackings(){return d(this,null,function*(){return yield this.readMetadata(),this.trackBackings})}getMetadataTags(){return d(this,null,function*(){const e=yield this.readingMutex.acquire();try{if(yield this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let e=0;for(;;){let t=this.reader.requestSlice(e,el);if(Te(t)&&(t=yield t),!t)break;const i=nl(t);if(!i)break;let r=this.reader.requestSlice(t.filePos,i.size);if(Te(r)&&(r=yield r),!r)break;sl(r,i,this.metadataTags),e=t.filePos+i.size}return this.metadataTags}finally{e()}})}}class Bn{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return this.getSampleRate()/xn}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return d(this,null,function*(){return null})}getLiveRefreshInterval(){return d(this,null,function*(){return null})}getName(){return null}getLanguageCode(){return Z}getCodec(){return"aac"}getInternalCodecId(){return y(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){y(this.demuxer.firstFrameHeader);const e=qe[this.demuxer.firstFrameHeader.channelConfiguration];return y(void 0!==e),e}getSampleRate(){y(this.demuxer.firstFrameHeader);const e=Ue[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return y(void 0!==e),e}getDisposition(){return c({},Le)}getDecoderConfig(){return d(this,null,function*(){return y(this.demuxer.firstFrameHeader),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate()}})}getPacketAtIndex(e,t){return d(this,null,function*(){if(-1===e)return null;const i=this.demuxer.loadedSamples[e];if(!i)return null;let r;if(t.metadataOnly)r=_i;else{let e=this.demuxer.reader.requestSlice(i.dataStart,i.dataSize);if(Te(e)&&(e=yield e),!e)return null;r=Ro(e,i.dataSize)}return new Ri(r,"key",i.timestamp,i.duration,e,i.dataSize)})}getFirstPacket(e){return this.getPacketAtIndex(0,e)}getNextPacket(e,t){return d(this,null,function*(){const i=yield this.demuxer.readingMutex.acquire();try{const i=q(this.demuxer.loadedSamples,e.timestamp,e=>e.timestamp);if(-1===i)throw new Error("Packet was not created from this track.");const r=i+1;for(;r>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)yield this.demuxer.advanceReader();return this.getPacketAtIndex(r,t)}finally{i()}})}getPacket(e,t){return d(this,null,function*(){const i=yield this.demuxer.readingMutex.acquire();try{for(;;){const i=W(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+1d(this,null,function*(){var e;let t=0;for(;;){let e=this.reader.requestSlice(t,el);if(Te(e)&&(e=yield e),!e)return void(this.lastSampleLoaded=!0);const i=nl(e);if(!i)break;let r=this.reader.requestSlice(e.filePos,i.size);Te(r)&&(r=yield r),y(r),sl(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===Fo(s)){const t=s.filePos;if(Fo(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=Ro(e,4),n=new ze(r);if(32764!==n.readBits(15))return null;if(null===this.blockingBit){y(t);const e=n.readBits(1);this.blockingBit=e}else if(1===this.blockingBit){y(!t);if(1!==n.readBits(1))return null}else{if(0!==this.blockingBit)throw new Error("Invalid blocking bit");y(!t);if(0!==n.readBits(1))return null}const s=(e=>0===e?null:1===e?192:e>=2&&e<=5?144*o(2,e):6===e?"uncommon-u8":7===e?"uncommon-u16":e>=8&&e<=15?o(2,e):null)(n.readBits(4));if(!s)return null;y(this.audioInfo);const a=((e,t)=>{switch(e){case 0:return t;case 1:return 88200;case 2:return 176400;case 3:return 192e3;case 4:return 8e3;case 5:return 16e3;case 6:return 22050;case 7:return 24e3;case 8:return 32e3;case 9:return 44100;case 10:return 48e3;case 11:return 96e3;case 12:return"uncommon-u8";case 13:return"uncommon-u16";case 14:return"uncommon-u16-10";default:return null}})(n.readBits(4),this.audioInfo.sampleRate);if(!a)return null;n.readBits(4),n.readBits(3);if(0!==n.readBits(1))return null;const l=(e=>{let t=0;const i=new ze(Ro(e,1));for(;1===i.readBits(1);)t++;if(0===t)return i.readBits(7);const r=[],n=t-1,s=new ze(Ro(e,n)),a=8-t-1;for(let o=0;oe|t<"uncommon-u16"===t?Do(e)+1:"uncommon-u8"===t?Fo(e)+1:"number"===typeof t?t:($(t),void y(!1)))(e,s),u=((e,t)=>"uncommon-u16"===t?Do(e):"uncommon-u16-10"===t?10*Do(e):"uncommon-u8"===t?Fo(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=Fo(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})(Ro(e,d));return h!==f?null:{num:l,blockSize:c,sampleRate:u}}advanceReader(){return d(this,null,function*(){yield this.readMetadata(),y(null!==this.lastLoadedPos),y(this.audioInfo);const e=this.lastLoadedPos,t=yield this.readNextFlacFrame({startPos:e,isFirstPacket:0===this.loadedSamples.length});if(!t)return void(this.lastSampleLoaded=!0);const i=this.loadedSamples[this.loadedSamples.length-1],r={blockOffset:i?i.blockOffset+i.blockSize:0,blockSize:t.blockSize,byteOffset:e,byteSize:t.size};this.lastLoadedPos=this.lastLoadedPos+t.size,this.loadedSamples.push(r),t.isLastFrame&&(this.lastSampleLoaded=!0)})}}class _n{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return y(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return y(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return Z}getTimeResolution(){return y(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 d(this,null,function*(){return y(this.demuxer.audioInfo),0===this.demuxer.audioInfo.totalSamples?null:this.demuxer.audioInfo.totalSamples/this.demuxer.audioInfo.sampleRate})}getLiveRefreshInterval(){return d(this,null,function*(){return null})}getDisposition(){return c({},Le)}getDecoderConfig(){return d(this,null,function*(){return y(this.demuxer.audioInfo),{codec:"flac",numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}})}getPacket(e,t){return d(this,null,function*(){if(y(this.demuxer.audioInfo),e<0)return null;const i=yield this.demuxer.readingMutex.acquire();try{for(;;){const i=W(this.demuxer.loadedSamples,e,e=>e.blockOffset/this.demuxer.audioInfo.sampleRate);if(-1===i){yield this.demuxer.advanceReader();continue}const r=this.demuxer.loadedSamples[i],n=r.blockOffset/this.demuxer.audioInfo.sampleRate;if(!(n+r.blockSize/this.demuxer.audioInfo.sampleRate<=e))return this.getPacketAtIndex(i,t);if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(this.demuxer.loadedSamples.length-1,t);yield this.demuxer.advanceReader()}}finally{i()}})}getNextPacket(e,t){return d(this,null,function*(){const i=yield this.demuxer.readingMutex.acquire();try{const i=e.sequenceNumber+1;if(this.demuxer.lastSampleLoaded&&i>=this.demuxer.loadedSamples.length)return null;for(;i>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)yield this.demuxer.advanceReader();return this.getPacketAtIndex(i,t)}finally{i()}})}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}getPacketAtIndex(e,t){return d(this,null,function*(){const i=this.demuxer.loadedSamples[e];if(!i)return null;let r;if(t.metadataOnly)r=_i;else{let e=this.demuxer.reader.requestSlice(i.byteOffset,i.byteSize);if(Te(e)&&(e=yield e),!e)return null;r=Ro(e,i.byteSize)}y(this.demuxer.audioInfo);const n=i.blockOffset/this.demuxer.audioInfo.sampleRate,s=i.blockSize/this.demuxer.audioInfo.sampleRate;return new Ri(r,"key",n,s,e,i.byteSize)})}getFirstPacket(e){return d(this,null,function*(){for(;0===this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)yield this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)})}}const Rn=9e4,Fn=o(2,33),An=188,Dn="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.",Mn=new Set([133,134,162]),Nn=new Set;class On extends Ei{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 d(this,null,function*(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>d(this,null,function*(){let e=this.reader.requestSlice(0,205);Te(e)&&(e=yield e),y(e);const t=Ro(e,205);if(71===t[0]&&71===t[188])this.packetOffset=0,this.packetStride=An;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 ze(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=zn(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 Vn(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=st(r.suppliedPacket.data),!e.info.avcCodecInfo)continue;const t=e.info.avcCodecInfo.sequenceParameterSets[0];y(t);const i=ct(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:E[i.colourPrimaries],transfer:R[i.transferCharacteristics],matrix:A[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=pt(r.suppliedPacket.data),!e.info.hevcCodecInfo)continue;const t=e.info.hevcCodecInfo.arrays.find(e=>e.nalUnitType===Ge.SPS_NUT).nalUnits[0];y(t);const i=mt(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:E[i.colourPrimaries],transfer:R[i.transferCharacteristics],matrix:A[i.matrixCoefficients],fullRange:!!i.fullRangeFlag},e.info.reorderSize=i.maxDecFrameBuffering;break}throw new Error("Unhandled.")}e.info.decoderConfig={codec:hi({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=Eo.tempFromBytes(r.suppliedPacket.data),i=In(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=qe[i.channelConfiguration],e.info.sampleRate=Ue[i.samplingFrequencyIndex]}else if("mp3"===e.info.codec){const t=Lo(Eo.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=Lt(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=Ot[t.acmod]+t.lfeon,e.info.sampleRate=je[t.fscod]}else if("eac3"===e.info.codec){const t=qt(r.suppliedPacket.data);if(!t)throw new Error("Invalid E-AC-3 audio stream; could not read sync frame from first packet.");const i=Wt(t);if(null===i)throw new Error("Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.");e.info.numberOfChannels=Ht(t),e.info.sampleRate=i}else{if("dts"!==e.info.codec)throw new Error("Unhandled.");{const t=Jt(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:mi({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 ze(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&&Mn.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:Nn.has(t)||(Me._warn(`Note: MPEG-TS streams with stream_type 0x${t.toString(16)} are not currently supported.`),Nn.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 ze(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 qn(a)):this.trackBackingEntries.push(new Wn(a)))}))()})}getTrackBackings(){return d(this,null,function*(){return yield this.readMetadata(),this.trackBackingEntries})}getMetadataTags(){return d(this,null,function*(){return{}})}getMimeType(){return d(this,null,function*(){yield this.readMetadata();return(e=>{let t="video/MP2T";const i=[...new Set(e.filter(Boolean))];return i.length>0&&(t+=`; codecs="${i.join(", ")}"`),t})(yield Promise.all(this.trackBackingEntries.map(e=>e.getDecoderConfig().then(e=>{var t;return null!=(t=null==e?void 0:e.codec)?t:null}))))})}readSection(e,t,i=!1){return d(this,null,function*(){let r=e,n=e;const s=[];let a,o=0,l=null,c=!0,u=0;for(;;){const e=yield this.readPacket(n);if(n+=this.packetStride,!e)break;if(l){if(e.pid!==l.pid){if(i)break;continue}if(1===e.payloadUnitStartIndicator)break}else{if(0===e.payloadUnitStartIndicator)break;l=e}const a=!!(2&e.adaptationFieldControl),d=!!(1&e.adaptationFieldControl);let h=0;if(a&&(h=1+e.body[0],e===l&&h>1&&(u=e.body[1]>>6&1)),d&&(0===h?(s.push(e.body),o+=e.body.byteLength):(s.push(e.body.subarray(h)),o+=e.body.byteLength-h)),r=n,!t&&o>=64){c=!1;break}if(-1!==q(this.sectionEndPositions,r,e=>e)){c=!1;break}}if(c){const e=W(this.sectionEndPositions,r,e=>e);this.sectionEndPositions.splice(e+1,0,r)}if(!l)return null;if(1===s.length)a=s[0];else{const e=s.reduce((e,t)=>e+t.length,0);a=new Uint8Array(e);let t=0;for(const i of s)a.set(i,t),t+=i.length}return{startPos:e,endPos:t?r:null,pid:l.pid,payload:a,randomAccessIndicator:u}})}readPacketHeader(e){return d(this,null,function*(){let t=this.reader.requestSlice(e,4);if(Te(t)&&(t=yield t),!t)return null;if(71!==Fo(t))throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");const i=Do(t);return{payloadUnitStartIndicator:i>>14&1,pid:8191&i,adaptationFieldControl:Fo(t)>>4&3}})}readPacket(e){return d(this,null,function*(){let t=this.reader.requestSlice(e,An);if(Te(t)&&(t=yield t),!t)return null;const i=Ro(t,An);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>=Fn-t?-Fn:Fn}}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 ze(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(Dn);return{sectionStartPos:t.startPos,sectionEndPos:t.endPos,pts:a,randomAccessIndicator:t.randomAccessIndicator}},zn=(e,t,i)=>{y(null!==t.endPos);const r=Ln(e,t,i);if(!r)return null;const n=new ze(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;y(Number.isInteger(l));const d=t.payload.subarray(l,s>0?6+s:t.payload.byteLength);return u(c({},r),{data:d})};class Un{constructor(e){this.elementaryStream=e,this.packetBuffers=new WeakMap,this.packetSectionStarts=new WeakMap}getId(){return this.elementaryStream.pid}getNumber(){const e=this.elementaryStream.demuxer,t=this.elementaryStream.info.type;let i=0;for(const r of e.trackBackingEntries)if(r.getType()===t&&i++,y(r instanceof Un),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 Z}getDisposition(){return u(c({},Le),{primary:!1})}getTimeResolution(){return Rn}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return d(this,null,function*(){return null})}getLiveRefreshInterval(){return d(this,null,function*(){return null})}createEncodedPacket(e,t,i){let r;return r=this.allPacketsAreKeyPackets()||1===e.randomAccessIndicator?"key":"delta",new Ri(i.metadataOnly?_i:e.data,r,e.pts/Rn,Math.max(t/Rn,0),e.sequenceNumber,e.data.byteLength)}getFirstPacket(e){return d(this,null,function*(){const t=this.elementaryStream.firstSection;y(t);const i=zn(this.elementaryStream.demuxer,t,!0);y(i);const r=new Vn(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 d(this,null,function*(){let i=this.packetBuffers.get(e);if(i){const r=yield i.readNext();if(!r)return null;this.packetBuffers.delete(e);const n=this.createEncodedPacket(r.packet,r.duration,t);return this.packetBuffers.set(n,i),this.packetSectionStarts.set(n,r.packet.sectionStartPos),n}const r=this.packetSectionStarts.get(e);if(void 0===r)throw new Error("Packet was not created from this track.");const n=this.elementaryStream.demuxer,s=yield n.readSection(r,!0);y(s);const a=zn(n,s,!0);y(a);const o=new Vn(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 d(this,null,function*(){let i=e;for(;;){if(i=yield this.getNextPacket(i,t),!i)return null;if("key"===i.type)return i}})}getPacket(e,t){return this.doPacketLookup(e,!1,t)}getKeyPacket(e,t){return this.doPacketLookup(e,!0,t)}doPacketLookup(e,t,i){return d(this,null,function*(){var r,n,s,a,o,l;const c=ee(e*Rn),u=this.elementaryStream.demuxer,{reader:h,seekChunkSize:f}=u,m=this.elementaryStream.pid,p=(e,t,i)=>d(this,null,function*(){let r=e;for(;re.pts),w=-1!==S?v[S]:null;if(w&&c-w.pts<45e3)b=w.sectionStartPos;else{let e=0;if(null!==h.fileSize){const t=Math.ceil(h.fileSize/f);if(t>1){let i=0,r=t-1;for(e=i;i<=r;){const t=Math.floor((i+r)/2),n=re(t*f,u.packetStride)+k.sectionStartPos,s=n+f,a=yield p(n,s,!1);a?a.pesPacketHeader.pts<=c?(e=t,i=t+1):r=t-1:r=t-1}}}b=re(e*f,u.packetStride)+k.sectionStartPos}const P=yield p(b,null!=(r=h.fileSize)?r:1/0,!1);let I=null!=(n=null==P?void 0:P.pesPacketHeader)?n:null;I||(I=k);const x=this.getReorderSize(),C=(e,t)=>d(this,null,function*(){var r,n;const s=yield u.readSection(e,!0);y(s);const a=zn(u,s,!0);y(a);const o=new Vn(this.elementaryStream,a),l=new jn(this,o);for(;;){if((null!=(n=null==(r=T(l.presentationOrderPackets))?void 0:r.pts)?n:-1/0)>=c)break;if(!(yield l.readNextPacket()))break}const d=X(l.presentationOrderPackets,t);if(-1===d)return null;const h=l.presentationOrderPackets[d],f=0===d?0:h.pts-l.presentationOrderPackets[d-1].pts;for(;l.decodeOrderPackets[0]!==h;)l.decodeOrderPackets.shift();l.lastDuration=f;const m=yield l.readNext();y(m);const p=this.createEncodedPacket(m.packet,m.duration,i);return this.packetBuffers.set(p,l),this.packetSectionStarts.set(p,m.packet.sectionStartPos),p});if(!t||this.allPacketsAreKeyPackets()){e:for(;;){let e=I.sectionStartPos+u.packetStride;for(;;){const t=yield u.readPacketHeader(e);if(!t)break e;if(t.pid===m&&1===t.payloadUnitStartIndicator){const t=yield u.readSection(e,!1);if(t){const e=Ln(u,t,!1);if(e&&null!==e.pts){if(e.pts>c)break e;I=e,Hn(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===m&&1===t.payloadUnitStartIndicator){const t=yield u.readSection(e,!1);if(t){const e=Ln(u,t,!1);if(e&&null!==e.pts){I=e;break}}}e-=u.packetStride}}return C(I.sectionStartPos,e=>e.pts<=c)}{let e=b,t=null;const i=!this.elementaryStream.canBeTrustedWithKeyPackets;for(;;){let r=null;const n=e<=k.sectionStartPos;let d,b=null;if(n)d=k,b=g;else{const t=yield p(e,null!=(s=h.fileSize)?s:1/0,i);d=null!=(a=null==t?void 0:t.pesPacketHeader)?a:null,b=null!=(o=null==t?void 0:t.section)?o:null}let T=!1,v=0;e:for(;d&&!(null!==t&&d.sectionStartPos>=t);){if(d.pts<=c){let e;if(this.elementaryStream.canBeTrustedWithKeyPackets)e=1===d.randomAccessIndicator;else{y(b);const t=zn(u,b,!0);y(t);const i=new Vn(this.elementaryStream,t);yield i.markNextPacket(),e=1===(null==(l=i.suppliedPacket)?void 0:l.randomAccessIndicator)}e&&(r=d)}if(d.pts>c&&(T=!0),T&&(v++,v>x))break;let e=d.sectionStartPos+u.packetStride;for(;;){const t=yield u.readPacketHeader(e);if(!t)break e;if(t.pid===m&&1===t.payloadUnitStartIndicator){const t=yield u.readSection(e,i);if(t){const e=Ln(u,t,!1);if(e&&null!==e.pts){d=e,b=t,Hn(this.elementaryStream,d);break}}}e+=u.packetStride}}if(r){let e=r;if(0===v)e:for(let r=0;r=u.packetOffset;){const r=yield u.readPacketHeader(t);if(!r)break e;if(r.pid===m&&1===r.payloadUnitStartIndicator){const r=yield u.readSection(t,i);if(r){const t=Ln(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 y(t),t}if(n)return null;t=e,e=Math.max(re(e-k.sectionStartPos-f,u.packetStride)+k.sectionStartPos,k.sectionStartPos)}}})}}class qn extends Un{getType(){return"video"}getCodec(){return this.elementaryStream.info.codec}getCodedWidth(){return this.elementaryStream.info.width}getCodedHeight(){return this.elementaryStream.info.height}getSquarePixelWidth(){return this.elementaryStream.info.squarePixelWidth}getSquarePixelHeight(){return this.elementaryStream.info.squarePixelHeight}getRotation(){return 0}getColorSpace(){return d(this,null,function*(){return this.elementaryStream.info.colorSpace})}canBeTransparent(){return d(this,null,function*(){return!1})}getDecoderConfig(){return d(this,null,function*(){return y(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig})}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}}class Wn extends Un{getType(){return"audio"}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}getDecoderConfig(){return d(this,null,function*(){return y(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig})}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 0}}const Hn=(e,t)=>{const i=e.referencePesPackets,r=W(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 y(e),e}bufferData(e){return d(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,S,w;if("avc"===e)T=et(b),S=T===Xe.NON_IDR_SLICE||T===Xe.SLICE_DPA||T===Xe.IDR,w=T===Xe.SEI||T===Xe.SPS||T===Xe.PPS||T===Xe.AUD;else{T=ft(b);if(((1&b)<<5|l[g+1]>>3)>0){u+=m;continue}S=T<=Ge.RASL_R||T>=Ge.BLA_W_LP&&T<=21,w=T>=Ge.VPS_NUT&&T<=37||T===Ge.PREFIX_SEI_NUT||T>=41&&T<=44||T>=48&&T<=55}let P=!1;if(S){let t;if("avc"===e){const e=l.subarray(k,k+y),i=v(new ze(e));t=!s||i<=a,a=i}else t=l[k]>>7===1;t&&(s?P=!0:s=!0)}else w&&s&&(P=!0);if(P){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);Te(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=zt[3*a+n];y(void 0!==o),this.seekTo(e),t=this.ensureBuffered(o),Te(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(Te(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=Ut[a];this.seekTo(e),t=this.ensureBuffered(n),Te(t)&&(t=yield t);const l=256*o,c=Math.round(l*Rn/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(Te(a)&&(a=yield a),a<18)return;const o=this.readBytes(18),l=ei(o);let c=l?null:ti(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);Te(i)&&(i=yield i),c=null!=(e=ti(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(Te(i)&&(i=yield i),i=0)}readNext(){return d(this,null,function*(){if(0===this.decodeOrderPackets.length){if(!(yield this.readNextPacket()))return null}yield this.ensureCurrentPacketHasNext();const e=this.decodeOrderPackets[0],t=this.presentationOrderPackets.indexOf(e);let i;if(y(-1!==t),t===this.presentationOrderPackets.length-1)i=this.lastDuration;else{i=this.presentationOrderPackets[t+1].pts-e.pts,this.lastDuration=i}for(this.decodeOrderPackets.shift();this.presentationOrderPackets.length>0;){const e=this.presentationOrderPackets[0];if(this.decodeOrderPackets.includes(e))break;this.presentationOrderPackets.shift()}return{packet:e,duration:i}})}readNextPacket(){return d(this,null,function*(){if(this.reachedEnd)return!1;let e;return this.context.suppliedPacket||(yield this.context.markNextPacket()),e=this.context.suppliedPacket,this.context.suppliedPacket=null,e?(this.decodeOrderPackets.push(e),this.processPacketThroughReorderBuffer(e),!0):(this.reachedEnd=!0,this.flushReorderBuffer(),!1)})}ensureCurrentPacketHasNext(){return d(this,null,function*(){const e=this.decodeOrderPackets[0];for(y(e);;){const t=this.presentationOrderPackets.indexOf(e);if(-1!==t&&t<=this.presentationOrderPackets.length-2)break;if(!(yield this.readNextPacket()))break}})}processPacketThroughReorderBuffer(e){if(this.reorderBuffer.push(e),this.reorderBuffer.length>this.reorderSize){let e=0;for(let i=1;ie.pts-t.pts),this.presentationOrderPackets.push(...this.reorderBuffer),this.reorderBuffer.length=0}}const Kn="application/vnd.apple.mpegurl",Xn="#EXT-X-STREAM-INF:",$n="#EXT-X-I-FRAME-STREAM-INF:",Gn="#EXT-X-MEDIA:",Qn="#EXTINF:",Yn="#EXT-X-MAP:",Jn="#EXT-X-KEY:",Zn="#EXT-X-MEDIA-SEQUENCE:",es="#EXT-X-BYTERANGE:",ts="#EXT-X-PROGRAM-DATE-TIME:",is="#EXT-X-TARGETDURATION:",rs="#EXT-X-PLAYLIST-TYPE:",ns=e=>0===e.length||e.startsWith("#")&&!e.startsWith("#EXT");class ss{constructor(e){this._attributes={};let t="",i="",r=!1,n=!1;for(let s=0;sd(this,null,function*(){const e=[];if(this.trackDeclarations){for(const t of this.trackDeclarations)if("video"===t.type){const i=Ce(e,e=>"video"===e.getType())+1;e.push(new ls(this,t,i))}else if("audio"===t.type){const i=Ce(e,e=>"audio"===e.getType())+1;e.push(new cs(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=Ce(e,e=>"video"===e.getType())+1;e.push(new ls(this,{id:e.length+1,type:"video"},t))}else if("audio"===r.type){const t=Ce(e,e=>"audio"===e.getType())+1;e.push(new cs(this,{id:e.length+1,type:"audio"},t))}}return e}))()})}getFirstTimestampForInput(e){return d(this,null,function*(){const t=this.firstTimestampCache.get(e);if(void 0!==t)return t;const i=yield e.getFirstTimestamp();return this.firstTimestampCache.set(e,i),i})}getMediaOffset(e,t){return d(this,null,function*(){var i;const r=null!=(i=e.firstSegment)?i:e;let n;if(this.firstSegmentFirstTimestamps.has(r))n=this.firstSegmentFirstTimestamps.get(r);else{const e=this.getInputForSegment(r);n=yield this.getFirstTimestampForInput(e),this.firstSegmentFirstTimestamps.set(r,n)}if(r===e)return r.timestamp-n;const s=yield this.getFirstTimestampForInput(t),a=e.timestamp-r.timestamp,o=s-n-a;return Math.abs(o)<=Math.min(.25,a)?r.timestamp-n:e.timestamp-s})}dispose(){for(const e of this.inputCache)e.input.dispose();this.inputCache.length=0}}class os{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=(()=>d(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 d(this,null,function*(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())})}getHasOnlyKeyPackets(){return this.delegate(()=>{var e,t,i;return null!=(i=null==(t=(e=this.firstInputTrack._backing).getHasOnlyKeyPackets)?void 0:t.call(e))?i:null})}getPairingMask(){return BigInt("1")}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getInternalCodecId(){return this.delegate(()=>this.firstInputTrack._backing.getInternalCodecId())}getDisposition(){return this.delegate(()=>this.firstInputTrack._backing.getDisposition())}getLanguageCode(){return this.delegate(()=>this.firstInputTrack._backing.getLanguageCode())}getName(){return this.delegate(()=>this.firstInputTrack._backing.getName())}getTimeResolution(){return this.delegate(()=>this.firstInputTrack._backing.getTimeResolution())}isRelativeToUnixEpoch(){return d(this,null,function*(){return yield this.hydrate(),y(this.segmentedInput.firstSegment),this.segmentedInput.firstSegment.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 d(this,null,function*(){y(e.sequenceNumber>=0),y(this.segmentedInput.firstSegment);const r=yield this.segmentedInput.getMediaOffset(t,i.input),n=t.timestamp-this.segmentedInput.firstSegment.timestamp,s=e.clone({timestamp:ie(e.timestamp+r,yield i.getTimeResolution()),sequenceNumber:Math.floor(1e8*n)+e.sequenceNumber});return this.packetInfos.set(s,{segment:t,track:i,sourcePacket:e}),s})}getFirstPacket(e){return d(this,null,function*(){var t;yield this.hydrate(),y(this.firstInputTrack),y(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 d(this,null,function*(){const r=this.packetInfos.get(e);if(!r)throw new Error("Packet was not created from this track.");const n=i?yield r.track._backing.getNextKeyPacket(r.sourcePacket,t):yield r.track._backing.getNextPacket(r.sourcePacket,t);if(n)return this.createAdjustedPacket(n,r.segment,r.track);let s=r.segment;for(;;){const e=yield this.segmentedInput.getNextSegment(s,{skipLiveWait:t.skipLiveWait});if(!e)return null;const i=this.segmentedInput.getInputForSegment(e),n=(yield i.getTracks()).find(e=>e.type===r.track.type&&e.number===r.track.number);if(!n){s=e;continue}const a=yield n._backing.getFirstPacket(t);return a?this.createAdjustedPacket(a,e,n):null}})}getPacket(e,t){return this._getPacketInternal(e,t,!1)}getKeyPacket(e,t){return this._getPacketInternal(e,t,!0)}_getPacketInternal(e,t,i){return d(this,null,function*(){let r=yield this.segmentedInput.getSegmentAt(e,{skipLiveWait:t.skipLiveWait});if(!r)return null;for(yield this.hydrate();r;){const n=this.segmentedInput.getInputForSegment(r),s=(yield n.getTracks()).find(e=>e.type===this.firstInputTrack.type&&e.number===this.firstInputTrack.number);if(!s){r=yield this.segmentedInput.getPreviousSegment(r,{skipLiveWait:t.skipLiveWait});continue}const a=yield this.segmentedInput.getMediaOffset(r,n),o=e-a,l=i?yield s._backing.getKeyPacket(o,t):yield s._backing.getPacket(o,t);if(l)return this.createAdjustedPacket(l,r,s);r=yield this.segmentedInput.getPreviousSegment(r,{skipLiveWait:t.skipLiveWait})}return null})}}class ls extends os{getType(){return"video"}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getCodedWidth(){return this.delegate(()=>this.firstInputTrack._backing.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.firstInputTrack._backing.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.firstInputTrack._backing.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.firstInputTrack._backing.getSquarePixelHeight())}getRotation(){return this.delegate(()=>this.firstInputTrack._backing.getRotation())}getColorSpace(){return d(this,null,function*(){return this.delegate(()=>this.firstInputTrack._backing.getColorSpace())})}canBeTransparent(){return d(this,null,function*(){return this.delegate(()=>this.firstInputTrack._backing.canBeTransparent())})}getDecoderConfig(){return d(this,null,function*(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())})}}class cs extends os{getType(){return"audio"}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getNumberOfChannels(){return this.delegate(()=>this.firstInputTrack._backing.getNumberOfChannels())}getSampleRate(){return this.delegate(()=>this.firstInputTrack._backing.getSampleRate())}getDecoderConfig(){return d(this,null,function*(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())})}}Pe();const us=1/0;"undefined"!==typeof FinalizationRegistry&&new FinalizationRegistry(e=>{e()});class ds extends Fe{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 d(this,null,function*(){var e;if(this._disposed)throw new Co;return null!=(e=this._sizePromise)?e:this._sizePromise=(()=>d(this,null,function*(){let e=this._getFileSize();return void 0!==e||(yield this._read(0,1,0,us),e=this._getFileSize(),y(void 0!==e)),e}))()})}getSize(){return d(this,null,function*(){if(this._disposed)throw new Co;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 Cs(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 hs(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){this._refCount--,0===this._refCount&&(this._dispose(),this._disposed=!0)}}class hs{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;y(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 fs extends ds{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 ds||e instanceof hs))throw new TypeError("requestHandler must return or resolve to a Source or SourceRef.");const i=e instanceof ds?e.ref():e;return(t=i.source)._usedForHls||(t._usedForHls=this._usedForHls),i};return Te(t)?t.then(i):i(t)}}const ms=(e,t)=>e.path===t.path;class ps extends fs{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 ds?e.ref():e;return this._root=t,this._rootRequest=null,t};Te(e)?this._rootRequest=e.then(t):(t(e),y(this._root))}if(this._rootRequest)return this._rootRequest.then(n=>n.source._read(e,t,i,r))}return this._root.source._read(e,t,i,r)}_getFileSize(){if(this._root)return this._root.source._getFileSize()}_dispose(){this._root?this._root.free():this._rootRequest&&this._rootRequest.then(e=>e.free())}}const gs="undefined"!==typeof FinalizationRegistry?new FinalizationRegistry(e=>{e.cancel().catch(()=>{})}):null;class ks extends ds{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&&(!Ie(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 xs({maxCacheSize:null!=(i=t.maxCacheSize)?i:8*o(2,20),maxWorkerCount:4,runWorker:this._runWorker.bind(this),onIdleWorkerRemoved:e=>{const t=this._readers.get(e);t&&(this._readers.delete(e),null==gs||gs.unregister(e),t.cancel().catch(()=>{}))},prefetchProfile:Is.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 d(this,null,function*(){y(e.strictTarget);let t=this._readers.get(e);if(void 0===t){if("stream"in this._blob&&!fe()&&!1!==this._options.useStreamReader){t=this._blob.slice(e.currentPos).stream().getReader(),null==gs||gs.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 Me._warn("Request will not be retried because a CORS error was suspected due to different origins. You can modify this behavior by providing your own function for the 'getRetryDelay' option."),null}return Math.min(o(2,e-2),16)},Ts=new Set;class vs extends fs{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&&(!Ie(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 vs(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:bs,this._requestInit=c({},t.requestInit);let a=null;if(null==(r=t.requestInit)?void 0:r.headers){const e=c({},ce(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=ws(a);e&&(this._offset=e.offset,this._length=e.length)}this._orchestrator=new xs({maxCacheSize:null!=(n=t.maxCacheSize)?n:64*o(2,20),maxWorkerCount:null!=(s=t.parallelism)?s:2,runWorker:this._runWorker.bind(this),prefetchProfile:Is.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:J(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 Te(a)?a.then(o):o(a)}_runWorker(e){return d(this,null,function*(){for(var t;;){const r=new AbortController,n=yield ue(null!=(t=this._options.fetchFn)?t:fetch,this._url,le(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")||Ts.has(e.origin)||(Me._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.`),Ts.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){Me._error("Error while reading response stream. Attempting to resume.",i),yield Re(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=>d(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;Me._error("Error while reading response stream. Attempting to resume.",s),yield Re(1e3*e);const a=yield ue(null!=(n=this._options.fetchFn)?n:fetch,this._url,le(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 Ps(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);Te(e)?e.then(e=>{e?(y(e.offset===o.start),o.resolve(e.bytes)):o.resolve(null)},e=>o.reject(e)):(y(null===e),o.resolve(null))}}_dispose(){this._orchestrator.dispose(),this._sequentialBacking&&(this._sequentialBacking._disposed=!0,this._sequentialBacking._dispose())}}const Ss=/^bytes=(\d+)-(\d*)$/,ws=e=>{const t=Ss.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=W(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}=V();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 d(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 Co);this._pendingSlices.length=0,this._cache.length=0,null==(e=this._reader)||e.cancel()}}const Is={fileSystem:(e,t)=>{const i=o(2,16);return{start:e=Math.floor((e-i)/i)*i,end:t=Math.ceil((t+i)/i)*i}},network:(e,t,i)=>{const r=o(2,16);e=Math.max(0,Math.floor((e-r)/r)*r);for(const n of i){const i=8*o(2,20),r=Math.max((n.startPos+n.targetPos)/2,n.targetPos-i);if(Se(e,t,r,n.targetPos)){const e=n.targetPos-n.startPos,r=Math.ceil((e+1)/i)*i,s=o(2,Math.ceil(Math.log2(e+1))),a=Math.min(s,r);t=Math.max(t,n.startPos+a)}}return{start:e,end:t=Math.max(t,e+ys)}}};class xs{constructor(e){this.options=e,this.fileSize=null,this.nextAge=0,this.workers=[],this.cache=[],this.currentCacheSize=0,this.disposed=!1,this.queuedReads=[]}read(e,t,i,r){var n;y(!this.disposed);const s=this.options.prefetchProfile(e,t,this.workers),a=Math.max(s.start,i),o=Math.min(s.end,null!=(n=this.fileSize)?n:1/0,r);y(a<=e&&t<=o);let l=null;const c=W(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=W(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(y(n<=s),m=h.length&&(l={bytes:h,view:I(h),offset:e}),0===p.length)return y(l),l;const{promise:g,resolve:k,reject:b}=V(),T=[];for(const y of p){const i=Math.max(e,y.start),r=Math.min(t,y.end);i===y.start&&r===y.end?T.push(y):ie.hole.start),i=-1!==t?this.queuedReads[t]:null;for(i&&y.start<=i.hole.end?(i.hole.end=Math.max(i.hole.end,y.end),i.strictTarget&&(i.strictTarget=e),v&&i.pendingSlices.push(v)):(t++,i={hole:{start:y.start,end:y.end},strictTarget:e,pendingSlices:v?[v]:[],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)}}):(y(h),l=g.then(t=>t&&{bytes:t,view:I(t),offset:e})),l}checkHoleAgainstWorker(e,t,i){const r=o(2,17);if(Se(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);y(-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=W(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=I(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=I(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 Te(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 Bs=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},Es=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 _s=/^0[xX][0-9a-fA-F]+$/,Rs=/^data:.*;base64,/i;class Fs extends as{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=(()=>d(this,null,function*(){try{const e=this.getRemainingWaitTimeMs();e>0&&(yield Re(e)),this.lastSegmentUpdateTime=performance.now(),yield this.updateSegments()}finally{this.currentUpdateSegmentsPromise=null}}))()}getRemainingWaitTimeMs(){const e=performance.now()-this.lastSegmentUpdateTime,t=Math.max(0,1e3*this.refreshInterval-e);return t<=50?0:t}updateSegments(){return d(this,null,function*(){var e,t,i,r,n,s,a,l;let d=this.nextLines;if(this.nextLines=null,!d){const e={stack:[],error:void 0,hasError:!1};try{const t=Bs(e,yield this.demuxer.input._getSourceUncached({path:this.rootPath,isRoot:!1}),!1),i=new Bo(t.source),r=yield i.requestEntireFile();y(r),d=$o(r,r.length,{ignore:ns}),t.source instanceof fs&&(this.rootPath=t.source.rootPath)}catch(F){e.error=F,e.hasError=!0}finally{Es(e)}}const h=!1!==(null==(e=this.input._formatOptions.hls)?void 0:e.offsetTimestampsByDateTime);let f=!1,m=0,p=null,g=null,k=null,b=0,v=null,S=null,w=null,P=null,x=null,C=null,B=!1,E=null!=(t=T(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=>{b=e,E&&(y(null!==E.sequenceNumber),E.sequenceNumber0&&null!==C&&(m=b*C),B=!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(Yn)){const t=new ss(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(!E){const e={path:xe(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.");S={timestamp:m,unixEpochTimestamp:p,firstSegment:null,sequenceNumber:null,location:e,duration:0,encryption:k,initSegment:null,lastProgramDateTimeSeconds:x}}g=null,null===P?w=null:P=null}else if(e.startsWith(Jn)){const t=new ss(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(!_s.test(r))throw new Error(`Unsupported IV format '${r}'.`);let e=r.slice(2);e=e.padStart(32,"0"),i=new Uint8Array(Ui);for(let t=0;t=8&&112===i[4]&&115===i[5]&&115===i[6]&&104===i[7]){const e=I(i).getUint32(0);r=Fi(i.subarray(8,Math.min(e,i.length)))}}k={method:i,psshBox:r}}}}else if(e.startsWith(Zn)){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(es)){const t=_(e.slice(17));if(null===t.offset){if(null===w)throw new Error("Invalid M3U8 file; #EXT-X-BYTERANGE without offset requires a previous byte range.");t.offset=w}P=t,w=t.offset+t.length}else if(e.startsWith(ts)){if(E)continue;const t=e.slice(25),i=Date.parse(t);if(!Number.isFinite(i))continue;const r=i/1e3;if(x===r)continue;if(null===x&&this.segments.length>0){const e=T(this.segments),t=r-(e.timestamp+e.duration);for(const i of this.segments)i.unixEpochTimestamp=i.timestamp+t,h&&(i.timestamp=i.unixEpochTimestamp)}x=r,p=r,h&&(m=r)}else if("#EXT-X-DISCONTINUITY"===e)v=null;else if(e.startsWith(is)){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,C=i}else{if("#EXT-X-ENDLIST"===e){this.streamHasEnded=!0;break}if(e.startsWith(rs)){"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 d(this,null,function*(){var e;return 0===this.segments.length&&(yield this.runUpdateSegments()),null!=(e=this.segments[0])?e:null})}getSegmentAt(e,t){return d(this,null,function*(){0===this.segments.length&&(yield this.runUpdateSegments());let i=!!t.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){const r=W(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=u(c({},this.input._formatOptions),{isobmff:u(c({},this.input._formatOptions.isobmff),{resolveKeyId:(null==(i=this.input._formatOptions.isobmff)?void 0:i.resolveKeyId)&&(e=>{if(!r.encryption||"SAMPLE-AES"!==r.encryption.method&&"SAMPLE-AES-CTR"!==r.encryption.method||!r.encryption.psshBox)return this.input._formatOptions.isobmff.resolveKeyId(e);let t=e.psshBoxes;const{psshBox:i}=r.encryption;return null!==i.keyIds&&!i.keyIds.includes(e.keyId)||t.some(e=>Ai(e,i))||(t=[...t,i]),this.input._formatOptions.isobmff.resolveKeyId(u(c({},e),{psshBoxes:t}))})})}),l=new Io({source:new ps(r.location.path,e=>d(this,null,function*(){var t,i;y(e.isRoot);const n=u(c({},e),{isRoot:!1});let s;const a=r.location.offset>0||null!==r.location.length;if(r.encryption&&"SAMPLE-AES"!==r.encryption.method&&"SAMPLE-AES-CTR"!==r.encryption.method)if("AES-128"===r.encryption.method){const e=r.encryption;y(e.iv);let t=yield this.input._getSourceCached(n);if(a){const e=t.source.slice(r.location.offset,null!=(i=r.location.length)?i:void 0).ref();t.free(),t=e}const l=((e,t,i)=>{let r=!1,n=0;const s=o(2,16),a=new Gi;return new ReadableStream({pull:o=>d(null,null,function*(){r||(a.init(yield t()),r=!0);const l=s+16;let c=e.requestSliceRange(n,0,l);if(Te(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=Ro(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 Bo(t.source),()=>d(this,null,function*(){const t={stack:[],error:void 0,hasError:!1};try{const i=Bs(t,yield this.input._getSourceCached({path:e.keyUri,isRoot:!1},Po),!1),r=new Bo(i.source),n=yield r.requestSlice(0,Ui);if(!n)throw new Error("Invalid AES-128 key; expected at least 16 bytes of data.");return{key:Ro(n,Ui),iv:e.iv}}catch(i){t.error=i,t.hasError=!0}finally{Es(t)}}),()=>{t.free()});s=new Ps(l).ref()}else y(!1);else if(s=yield this.input._getSourceCached(n),a){const e=s.source.slice(r.location.offset,null!=(t=r.location.length)?t:void 0).ref();s.free(),s=e}return s})),formats:this.input._formats.filter(e=>!(e instanceof Js)),initInput:null!=s?s:void 0,formatOptions:a});l._onFormatDetermined=e=>{var t,i;if(("SAMPLE-AES"===(null==(t=r.encryption)?void 0:t.method)||"SAMPLE-AES-CTR"===(null==(i=r.encryption)?void 0:i.method))&&!e._isIsobmff)throw new Error("The SAMPLE-AES and SAMPLE-AES-CTR encryption methods are currently only supported for ISOBMFF files.")},this.inputCache.push({segment:r,input:l,age:this.nextInputCacheAge++});if(this.inputCache.length>4){const e=Be(this.inputCache,e=>e.age);y(-1!==e),this.inputCache.splice(e,1)}return l}getLiveRefreshInterval(){return d(this,null,function*(){return 0===this.getRemainingWaitTimeMs()&&(yield this.runUpdateSegments()),this.streamHasEnded?null:this.refreshInterval})}}class As extends Ei{constructor(e){super(e),this.metadataPromise=null,this.trackBackings=null,this.internalTracks=null,this.segmentedInputs=[],this.hasMasterPlaylist=!0}readMetadata(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>d(this,null,function*(){y(this.input._rootSource instanceof fs);const e=yield this.input._reader.requestEntireFile();y(e);const t=$o(e,e.length,{ignore:ns}),{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)=>d(this,null,function*(){var r,o,l,c;const u=[],h=e.attributes.get("codecs");let f;if(h)f=h.split(",").map(e=>e.trim());else{const t=this.getSegmentedInputForPath(e.fullPath),i=yield t.getTrackBackings(),r=yield Promise.all(i.map(e=>d(this,null,function*(){return{track:e,codec:yield e.getCodec()}})));f=yield Promise.all(r.filter(e=>null!==e.codec).map(e=>e.track.getDecoderConfig().then(e=>e.codec)))}const m=e.attributes.get("video"),p=e.attributes.get("audio"),g=f.some(e=>ri.includes(yi(e))),k=f.some(e=>si.includes(yi(e)));if(null!==m&&!g){if(!s.includes(m))throw new Error(`Invalid M3U8 file; variant stream references video group "${m}" which is not defined in any #EXT-X-MEDIA tags.`);const e=n.find(e=>{const t=e.attributes.get("group-id"),i=e.attributes.get("type");return t===m&&"video"===i.toLowerCase()});e:if(e){const t=e.attributes.get("uri");if(null===t)break e;const r=xe(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});y(null!==a),f.push(a)}}if(null!==p&&!k){if(!a.includes(p))throw new Error(`Invalid M3U8 file; variant stream references audio group "${p}" which is not defined in any #EXT-X-MEDIA tags.`);const e=n.find(e=>{const t=e.attributes.get("group-id"),i=e.attributes.get("type");return t===p&&"audio"===i.toLowerCase()});e:if(e){const t=e.attributes.get("uri");if(null===t)break e;const r=xe(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});y(null!==a),f.push(a)}}f=[...new Set(f)];let b=null,T=null;const v=e.attributes.getAsNumber("bandwidth");y(null!==v);const S=e.attributes.getAsNumber("average-bandwidth"),w=e.attributes.get("name");for(const i of f){const d=yi(i);if(null!==d)if(ri.includes(d)){if(null!==b)throw new Error("Unsupported M3U8 file; multiple video codecs found in the CODECS attribute of a variant stream.");b=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:Z,lineNumber:e.lineNumber,fullPath:e.fullPath,fullCodecString:b,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:Os(i.attributes),autoselect:Os(i.attributes)||Ls(i.attributes),languageCode:zs(i.attributes.get("language")),lineNumber:i.lineNumber,fullPath:null!=(c=i.fullPath)?c:e.fullPath,fullCodecString:T,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===Z&&(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 Ms(u)):this.trackBackings.push(new Ns(u));this.internalTracks=l}))()}getTrackBackings(){return d(this,null,function*(){return yield this.readMetadata(),y(this.trackBackings),this.trackBackings})}getSegmentedInputForPath(e){let t=this.segmentedInputs.find(t=>t.path===e);if(t)return t;let i=null;if(this.internalTracks){i=this.internalTracks.filter(t=>t.fullPath===e).map(e=>({id:e.id,type:e.info.type}))}return t=new Fs(this,e,i,null),this.segmentedInputs.push(t),t}getMetadataTags(){return d(this,null,function*(){return{}})}getMimeType(){return d(this,null,function*(){return Kn})}dispose(){if(this.segmentedInputs){for(const e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}}class Ds{constructor(e){this.internalTrack=e,this.hydrationPromise=null}hydrate(){var e;return null!=(e=this.hydrationPromise)?e:this.hydrationPromise=(()=>d(this,null,function*(){const e=this.internalTrack.demuxer.getSegmentedInputForPath(this.internalTrack.fullPath);let t=null;const i=(yield e.getTrackBackings()).filter(e=>e.getType()===this.getType());if(1===i.length)t=i[0];else if(this instanceof Ms){for(const r of i)if((yield r.getCodec())===this.getCodec()){t=r;break}}else{y(this instanceof Ns);for(const e of i)if((yield e.getCodec())===this.getCodec()){t=e;break}}if(!t)throw new Error("Could not find matching track in underlying media data.");this.internalTrack.backingTrack=t}))()}delegate(e){return this.internalTrack.backingTrack?e():this.hydrate().then(e)}getCodec(){throw new Error("Not implemented on base class.")}getDisposition(){return u(c({},Le),{default:this.internalTrack.autoselect,primary:this.internalTrack.default})}getId(){return this.internalTrack.id}getPairingMask(){return this.internalTrack.pairingMask}getInternalCodecId(){return null}getLanguageCode(){return this.internalTrack.languageCode}getName(){return this.internalTrack.name}getNumber(){y(this.internalTrack.demuxer.internalTracks);const e=this.internalTrack.info.type;let t=0;for(const i of this.internalTrack.demuxer.internalTracks)if(i.info.type===e&&t++,i===this.internalTrack)break;return t}getTimeResolution(){return this.delegate(()=>this.internalTrack.backingTrack.getTimeResolution())}isRelativeToUnixEpoch(){return this.delegate(()=>this.internalTrack.backingTrack.isRelativeToUnixEpoch())}getUnixTimeForTimestamp(e){return this.delegate(()=>this.internalTrack.backingTrack.getUnixTimeForTimestamp(e))}getBitrate(){return this.internalTrack.peakBitrate}getAverageBitrate(){return this.internalTrack.averageBitrate}getDurationFromMetadata(e){return d(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getDurationFromMetadata(e)})}getLiveRefreshInterval(){return d(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getLiveRefreshInterval()})}getHasOnlyKeyPackets(){return this.internalTrack.hasOnlyKeyPackets||null}getFirstPacket(e){return d(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getFirstPacket(e)})}getPacket(e,t){return d(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getPacket(e,t)})}getKeyPacket(e,t){return d(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getKeyPacket(e,t)})}getNextPacket(e,t){return d(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getNextPacket(e,t)})}getNextKeyPacket(e,t){return d(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getNextKeyPacket(e,t)})}}class Ms extends Ds{constructor(e){super(e)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return"video"}getCodec(){return yi(this.internalTrack.fullCodecString)}getCodedWidth(){return this.delegate(()=>this.backingVideoTrack.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.backingVideoTrack.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelHeight())}getMetadataDisplayWidth(){return this.backingVideoTrack?null:this.internalTrack.info.width}getMetadataDisplayHeight(){return this.backingVideoTrack?null:this.internalTrack.info.height}getRotation(){return this.delegate(()=>this.backingVideoTrack.getRotation())}getColorSpace(){return d(this,null,function*(){return yield this.hydrate(),this.backingVideoTrack.getColorSpace()})}canBeTransparent(){return d(this,null,function*(){return yield this.hydrate(),this.backingVideoTrack.canBeTransparent()})}getMetadataCodecParameterString(){return this.backingVideoTrack?null:this.internalTrack.fullCodecString}getDecoderConfig(){return d(this,null,function*(){return yield this.hydrate(),this.backingVideoTrack.getDecoderConfig()})}}class Ns extends Ds{constructor(e){super(e)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return"audio"}getCodec(){return yi(this.internalTrack.fullCodecString)}getNumberOfChannels(){return null!==this.internalTrack.info.numberOfChannels?this.internalTrack.info.numberOfChannels:this.delegate(()=>this.backingAudioTrack.getNumberOfChannels())}getSampleRate(){return this.delegate(()=>this.backingAudioTrack.getSampleRate())}getMetadataCodecParameterString(){return this.backingAudioTrack?null:this.internalTrack.fullCodecString}getDecoderConfig(){return d(this,null,function*(){return yield this.hydrate(),this.backingAudioTrack.getDecoderConfig()})}}const Os=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}".`)},Ls=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}".`)},zs=e=>{if(null===e)return Z;const t=e.split("-")[0];return t||Z};class Us{constructor(){this._isIsobmff=!1}}class qs extends Us{constructor(){super(...arguments),this._isIsobmff=!0}_getMajorBrand(e){return d(this,null,function*(){let t=e._reader.requestSlice(0,12);if(Te(t)&&(t=yield t),!t)return null;t.skip(4);const i=Xo(t,4);return"ftyp"!==i&&"styp"!==i?null:Xo(t,4)})}_createDemuxer(e){return new Qi(e)}}class Ws extends qs{_canReadInput(e){return d(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(Te(t)&&(t=yield t),!t)return!1;let r=Lo(t),n=8;if(1===r){let t=e._reader.requestSlice(i+8,8);if(Te(t)&&(t=yield t),!t)return!1;r=Wo(t),n=16}if(r8)return!1;if(Sr(i,r)!==mr.EBML)return!1;const n=Pr(i);if("number"!==typeof n)return!1;let s=e._reader.requestSlice(i.filePos,n);if(Te(s)&&(s=yield s),!s)return!1;const a=i.filePos;for(;s.filePos<=a+n-2;){const e=Ir(s);if(!e)break;const{id:i,size:r}=e,n=s.filePos;if(void 0===r)return!1;switch(i){case mr.EBMLVersion:if(1!==Sr(s,r))return!1;break;case mr.EBMLReadVersion:if(1!==Sr(s,r))return!1;break;case mr.DocType:if(xr(s,r)!==t)return!1;break;case mr.DocTypeVersion:if(Sr(s,r)>4)return!1}s.filePos=n+r}return!0})}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new en(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}}class js extends Vs{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}}class Ks extends Us{_canReadInput(e){return d(this,null,function*(){let t=0;for(;;){let i=e._reader.requestSlice(t,el);if(Te(i)&&(i=yield i),!i)break;const r=nl(i);if(!r)break;t=i.filePos+r.size}const i=yield sn(e._reader,t,t+4096);if(!i)return!1;const r=i.header,n=wi(r.mpegVersionId,r.channel);let s=e._reader.requestSlice(i.startPos+n,4);if(Te(s)&&(s=yield s),!s)return!1;const a=Lo(s);if(a===vi||a===Si)return!0;t=i.startPos+i.header.totalSize;const o=yield sn(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 an(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}}class Xs extends Us{_canReadInput(e){return d(this,null,function*(){let t=e._reader.requestSlice(0,12);if(Te(t)&&(t=yield t),!t)return!1;const i=Xo(t,4);if("RIFF"!==i&&"RIFX"!==i&&"RF64"!==i)return!1;t.skip(4);return"WAVE"===Xo(t,4)})}_createDemuxer(e){return new Sn(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}}class $s extends Us{_canReadInput(e){return d(this,null,function*(){let t=e._reader.requestSlice(0,4);return Te(t)&&(t=yield t),!!t&&"OggS"===Xo(t,4)})}_createDemuxer(e){return new gn(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}}class Gs extends Us{_canReadInput(e){return d(this,null,function*(){let t=0;for(;;){let i=e._reader.requestSlice(t,el);if(Te(i)&&(i=yield i),!i)break;const r=nl(i);if(!r)break;t=i.filePos+r.size}let i=e._reader.requestSlice(t,4);return Te(i)&&(i=yield i),!!i&&"fLaC"===Xo(i,4)})}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new En(e)}}class Qs extends Us{_canReadInput(e){return d(this,null,function*(){let t=0;for(;;){let i=e._reader.requestSlice(t,el);if(Te(i)&&(i=yield i),!i)break;const r=nl(i);if(!r)break;t=i.filePos+r.size}let i=e._reader.requestSliceRange(t,7,9);if(Te(i)&&(i=yield i),!i)return!1;const r=In(i);if(!r)return!1;if(t+=r.frameLength,i=e._reader.requestSliceRange(t,7,9),Te(i)&&(i=yield i),!i)return!1;const n=In(i);return!!n&&(r.objectType===n.objectType&&r.samplingFrequencyIndex===n.samplingFrequencyIndex&&r.channelConfiguration===n.channelConfiguration)})}_createDemuxer(e){return new Cn(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}}class Ys extends Us{_canReadInput(e){return d(this,null,function*(){let t=e._reader.requestSlice(0,205);if(Te(t)&&(t=yield t),!t)return!1;const i=Ro(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 On(e)}get name(){return"MPEG Transport Stream"}get mimeType(){return"video/MP2T"}}class Js extends Us{_canReadInput(e){return d(this,null,function*(){let t=e._reader.requestSlice(0,7);if(Te(t)&&(t=yield t),!t)return!1;if(!("#EXTM3U"===Xo(t,7)))return!1;if(!(e._rootSource instanceof fs))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 As(e)}get name(){return"HTTP Live Streaming (HLS)"}get mimeType(){return Kn}}const Zs=new Ws,ea=new Hs,ta=new Vs,ia=new js,ra=new Ks,na=new Xs,sa=new $s,aa=new Qs,oa=new Gs,la=new Ys,ca=new Js,ua=[ca,Zs,ea,ta,ia,na,sa,oa,ra,aa,la],da=[ca,Zs,ea,ra,aa,la];var ha=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});Pe();let fa=-1/0,ma=-1/0,pa=null;"undefined"!==typeof FinalizationRegistry&&(pa=new FinalizationRegistry(e=>{const t=performance.now();"video"===e.type?(t-fa>=1e3&&(Me._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."),fa=t),"undefined"!==typeof VideoFrame&&e.data instanceof VideoFrame&&e.data.close()):(t-ma>=1e3&&(Me._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."),ma=t),"undefined"!==typeof AudioData&&e.data instanceof AudioData&&e.data.close())}));class ga{constructor(){this._referenceCount=0,this._lastAllocationBuffer=null}}const ka=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],ya=new Set(ka);class ba{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(oe*this.timestamp)}get microsecondDuration(){return Math.trunc(oe*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,I,x,C,B,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||!ya.has(t.format))throw new TypeError("init.format must be one of: "+ka.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&&_e(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:Ea(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?P(e):P(e).slice(),this._layout=m,this.colorSpace=new Pa(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)&&_e(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!=(x=null==t?void 0:t.duration)?x:(null!=(I=e.duration)?I:0)/1e6,this.colorSpace=new Pa(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&&_e(t.visibleRect,"init.visibleRect"),"undefined"!==typeof VideoFrame)return new ba(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*oe),duration:Math.trunc((null!=(C=t.duration)?C:0)*oe)||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!=(B=t.visibleRect)?B:{left:0,top:0,width:i,height:r},s=new OffscreenCanvas(n.width,n.height),a=s.getContext("2d",{alpha:pe(),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 Pa({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else{if(!(e instanceof ga))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&&!ka.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=Ee({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),null==pa||pa.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return y(null!==this._data),this._data instanceof ga?new ba(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):Ia(this._data)?new ba(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):this._data instanceof Uint8Array?(y(this._layout),new ba(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 ba(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==pa||pa.unregister(this),this._data instanceof ga?(this._data._referenceCount--,0===this._data._referenceCount&&this._data.close()):Ia(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){var t;if(Ba(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(Ia(this._data))return this._data.allocationSize(e);return Ra(this,e).allocationSize}copyTo(e){return d(this,arguments,function*(e,t={}){var i,r;if(!N(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(Ba(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(y(null!==this._data),Ia(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 ga)){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 ba))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{ha(i)}}}const n=Ra(this,t);y(this.format);const s=P(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)y(this._layout),y(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");y(e);const t=e.getImageData(0,0,this.codedWidth,this.codedHeight);o=[{data:P(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 Ia(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?(y(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&&Ca(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=xa(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],l=i.crop?i.crop.width:s,c=i.crop?i.crop.height:a;let u=0;2*r0?wa(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*o(2,g),t=n*o(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(y(null!==this._data),this._data instanceof ga||this._data instanceof Uint8Array){const e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}return this._data}transform(e){return d(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&&Ca(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=b(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=xa(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=te(f,null!=(i=e.roundDimensionsTo)?i:1),m=te(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 Ta){let t=e(this,p);if(Te(t)&&(t=yield t),null!==t)return t}const{canvas:g,context:k,isNew:y}=wa(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 ba(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 Ta=[],va=[];let Sa=0;const wa=(e,t)=>{for(const n of va)if(n.canvas.width===e&&n.canvas.height===t)return n.age=Sa++,{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 va.length>=3&&va.splice(Be(va,e=>e.age),1),va.push({canvas:i,context:r,age:Sa++}),{canvas:i,context:r,isNew:!0}};class Pa{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(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(_);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(F);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 Ia=e=>"undefined"!==typeof VideoFrame&&e instanceof VideoFrame,xa=(e,t,i)=>{const r=Math.min(e.left,t),n=Math.min(e.top,i),s=Math.min(e.width,t-r),a=Math.min(e.height,i-n);return y(s>=0),y(a>=0),{left:r,top:n,width:s,height:a}},Ca=(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.")},Ba=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.")}},Ea=(e,t,i)=>{const r=_a(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},_a=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:$(e),y(!1)}},Ra=(e,t)=>{const i={left:0,top:0,width:e.codedWidth,height:e.codedHeight},r=t.rect,n=Fa(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 Da(n,a,s)},Fa=(e,t,i,r,n)=>{const s=c({},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(!Aa(n,s))throw new TypeError("visibleRect alignment is invalid for the format.");return s},Aa=(e,t)=>{if(null===e)return!0;const i=_a(e);for(let r=0;r{const r=_a(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/(La(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*La(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=La(r),o=za(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(!N(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&&!Ma.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=La(o),f=za(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 Ha(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=Ua(a),b=La(a),T=za(a);let v;if(this._data instanceof Na){const e=e=>{const t=this._data.getDataPlane(e);if(!(t instanceof Uint8Array))throw new TypeError("getDataPlane() must return a Uint8Array.");const i=l*b*(T?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(T)if(f)v=e(s),s=0;else{v=new Uint8Array(l*b*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 Oa({data:n,format:this.format,sampleRate:this.sampleRate,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp+e/this.sampleRate})}close(){this._closed||(null==pa||pa.unregister(this),this._data instanceof Na?(this._data._referenceCount--,0===this._data._referenceCount&&this._data.close()):Wa(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 Na?this._createAudioDataFromData():Wa(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(za(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")}},za=e=>{switch(e){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},Ua=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)}},qa=e=>{switch(e){case"u8":case"u8-planar":return(e,t,i)=>e.setUint8(t,J(127.5*(i+1),0,255));case"s16":case"s16-planar":return(e,t,i)=>e.setInt16(t,J(Math.round(32767*i),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,i)=>e.setInt32(t,J(Math.round(2147483647*i),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,i)=>e.setFloat32(t,i,!0)}},Wa=e=>"undefined"!==typeof AudioData&&e instanceof AudioData,Ha=(e,t,i,r,n,s,a,o)=>{const l=Ua(i),c=qa(r),u=La(i),d=La(r),h=za(i);if(za(r))if(h){const r=new ArrayBuffer(o*u),n=I(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.")},Xa=e=>{if(!Ie(e))throw new TypeError("timestamp must be a number.")},$a=(e,t,i)=>i.verifyKeyPackets?t.then(t=>d(null,null,function*(){if(!t||"delta"===t.type)return t;const i=yield e.determinePacketType(t);return i&&(t.type=i),t})):t;class Ga{constructor(e){if(!(e instanceof uo))throw new TypeError("track must be an InputTrack.");this._track=e}getFirstPacket(){return d(this,arguments,function*(e={}){if(Ka(e),this._track.input._disposed)throw new Co;return $a(this._track,this._track._backing.getFirstPacket(e),e)})}getFirstKeyPacket(){return d(this,arguments,function*(e={}){Ka(e);const t=yield this.getFirstPacket(e);return t?"key"===t.type?t:this.getNextKeyPacket(t,e):null})}getPacket(e){return d(this,arguments,function*(e,t={}){if(Xa(e),Ka(t),this._track.input._disposed)throw new Co;return $a(this._track,this._track._backing.getPacket(e,t),t)})}getNextPacket(e){return d(this,arguments,function*(e,t={}){if(!(e instanceof Ri))throw new TypeError("packet must be an EncodedPacket.");if(Ka(t),this._track.input._disposed)throw new Co;return $a(this._track,this._track._backing.getNextPacket(e,t),t)})}getKeyPacket(e){return d(this,arguments,function*(e,t={}){if(Xa(e),Ka(t),this._track.input._disposed)throw new Co;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);const i=yield this._track._backing.getKeyPacket(e,t);if(!i)return i;y("key"===i.type);return"delta"===(yield this._track.determinePacketType(i))?this.getKeyPacket(i.timestamp-1/(yield this._track.getTimeResolution()),t):i})}getNextKeyPacket(e){return d(this,arguments,function*(e,t={}){if(!(e instanceof Ri))throw new TypeError("packet must be an EncodedPacket.");if(Ka(t),this._track.input._disposed)throw new Co;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);const i=yield this._track._backing.getNextKeyPacket(e,t);if(!i)return i;y("key"===i.type);return"delta"===(yield this._track.determinePacketType(i))?this.getNextKeyPacket(i,t):i})}packets(e,t,i={}){if(void 0!==e&&!(e instanceof Ri))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 Ri))throw new TypeError("endPacket must be an EncodedPacket.");if(Ka(i),this._track.input._disposed)throw new Co;const r=[];let{promise:n,resolve:s}=V(),{promise:a,resolve:o}=V(),l=!1,c=!1,u=null,h=!1;const f=[],m=()=>Math.max(2,f.length);(()=>d(this,null,function*(){let u=null!=e?e:yield this.getFirstPacket(i);for(;u&&!c&&!this._track.input._disposed&&!(t&&u.sequenceNumber>=(null==t?void 0:t.sequenceNumber));)r.length>m()?(({promise:a,resolve:o}=V()),yield a):(r.push(u),s(),({promise:n,resolve:s}=V()),u=yield this.getNextPacket(u,i));l=!0,s()}))().catch(e=>{h||(u=e,h=!0,s())});const p=this._track;return{next(){return d(this,null,function*(){for(;;){if(p.input._disposed)throw new Co;if(c)return{value:void 0,done:!0};if(h)throw u;if(r.length>0){const e=r.shift(),t=performance.now();for(f.push(t);f.length>0&&t-f[0]>=1e3;)f.shift();return o(),{value:e,done:!1}}if(l)return{value:void 0,done:!0};yield n}})},return(){return d(this,null,function*(){return c=!0,o(),s(),{value:void 0,done:!0}})},throw(e){return d(this,null,function*(){throw e})},[Symbol.asyncIterator](){return this}}}}class Qa{constructor(e,t){this.onSample=e,this.onError=t}}class Ya{mediaSamplesInRange(e=-1/0,t=1/0,i){Xa(e),Xa(t);const r=[];let n=!1,s=null,{promise:a,resolve:o}=V(),{promise:l,resolve:h}=V(),f=!1,m=!1,p=!1,g=null,k=null,y=!1;const b=u(c({},i),{verifyKeyPackets:!0,metadataOnly:!1});(()=>d(this,null,function*(){var i;g=yield this._createDecoder(i=>{h(),i.timestamp>=t&&(m=!0),m?i.close():(s&&(i.timestamp>e?(r.push(s),n=!0):s.close()),i.timestamp>=e&&(r.push(i),n=!0),s=n?null:i,r.length>0&&(o(),({promise:a,resolve:o}=V())))},e=>{y||(k=e,y=!0,o())});const c=this._createPacketSink(),u=null!=(i=yield c.getKeyPacket(e,b))?i:yield c.getFirstKeyPacket(b);let d=u;const T=c.packets(null!=u?u:void 0,void 0,b);for(yield T.next();d&&!m&&!this._track.input._disposed;){const e=Ja(r.length);if(r.length+g.getDecodeQueueSize()>e){({promise:l,resolve:h}=V()),yield l;continue}g.decode(d);const t=yield T.next();if(t.done)break;d=t.value}yield T.return(),p||this._track.input._disposed||(yield g.flush()),!n&&s&&r.push(s),f=!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 d(this,null,function*(){for(;;){if(T.input._disposed)throw p=!0,m=!0,v(),new Co;if(p)return{value:void 0,done:!0};if(y)throw p=!0,m=!0,v(),k;if(r.length>0){const e=r.shift();return h(),{value:e,done:!1}}if(f)return{value:void 0,done:!0};yield a}})},return(){return d(this,null,function*(){return p=!0,m=!0,h(),o(),v(),{value:void 0,done:!0}})},throw(e){return d(this,null,function*(){throw e})},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e,t){(e=>{if(!(Symbol.iterator in e)&&!(Symbol.asyncIterator in e))throw new TypeError("Argument must be an iterable or async iterable.")})(e);const i=function(e){return f(this,null,function*(){Symbol.iterator in e?yield*m(e[Symbol.iterator]()):yield*m(e[Symbol.asyncIterator]())})}(e),r=[],n=[];let{promise:s,resolve:a}=V(),{promise:o,resolve:l}=V(),h=!1,g=!1,k=null,b=null,T=!1;const v=e=>{n.push(e),a(),({promise:s,resolve:a}=V())},S=u(c({},t),{verifyKeyPackets:!0,metadataOnly:!1});(()=>d(this,null,function*(){k=yield this._createDecoder(e=>{if(l(),g)return void e.close();let t=0;for(;r.length>0&&e.timestamp-r[0]>-1e-10;)t++,r.shift();if(t>0)for(let i=0;i{T||(b=e,T=!0,a())});const e=this._createPacketSink();let t=null,s=null,c=-1;const u=()=>d(this,null,function*(){y(s),y(k);let t=s;for(k.decode(t);t.sequenceNumberi&&!g;)({promise:o,resolve:l}=V()),yield o;if(g)break;const r=yield e.getNextPacket(t,S);y(r),k.decode(r),t=r}c=-1}),f=()=>d(this,null,function*(){y(k),yield k.flush();for(let e=0;e{T||(b=e,T=!0,a())}).finally(()=>{null==k||k.close()});const w=this._track,P=()=>{for(const e of n)null==e||e.close()};return{next(){return d(this,null,function*(){for(;;){if(w.input._disposed)throw g=!0,P(),new Co;if(g)return{value:void 0,done:!0};if(T)throw g=!0,P(),b;if(n.length>0){const e=n.shift();return y(void 0!==e),l(),{value:e,done:!1}}if(h)return{value:void 0,done:!0};yield s}})},return(){return d(this,null,function*(){return g=!0,l(),a(),P(),{value:void 0,done:!0}})},throw(e){return d(this,null,function*(){throw e})},[Symbol.asyncIterator](){return this}}}}const Ja=e=>0===e?40:8;class Za extends Qa{constructor(e,t,i,r,n,s){var a,o,l,d,h,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 de,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=Va.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 ba))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();y(void 0!==t),this.mergeAlpha(e,t)}else this.colorQueue.push(e)};if(ke()){if("avc"===i&&this.decoderConfig.description){const e=ot(P(this.decoderConfig.description));if(e&&e.sequenceParameterSets.length>0){const t=ct(e.sequenceParameterSets[0]);t&&(0===t.frameMbsOnlyFlag&&(this.decoderConfig=u(c({},this.decoderConfig),{hardwareAcceleration:"prefer-software"})),0!==t.maxDecFrameBuffering&&1!==t.bitstreamRestrictionFlag&&(e.sequenceParameterSets[0]=dt(t),this.decoderConfig=u(c({},this.decoderConfig),{description:at(e)})))}}D(this.decoderConfig.colorSpace)||(this.decoderConfig=u(c({},this.decoderConfig),{colorSpace:{primaries:null!=(o=null==(a=this.decoderConfig.colorSpace)?void 0:a.primaries)?o:"bt709",matrix:null!=(d=null==(l=this.decoderConfig.colorSpace)?void 0:l.matrix)?d:"bt709",transfer:null!=(f=null==(h=this.decoderConfig.colorSpace)?void 0:h.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:(y(this.decoder),Math.max(this.decoder.decodeQueueSize,null!=(t=null==(e=this.alphaDecoder)?void 0:e.decodeQueueSize)?t:0))}decode(e){if("hevc"===this.codec&&this.currentPacketIndex>0&&!this.raslSkipped){if(this.hasHevcRaslPicture(e.data))return;this.raslSkipped=!0}if(this.customDecoder)this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).catch(e=>this.onError(e)).finally(()=>this.customDecoderQueueSize--);else{if(y(this.decoder),fe()||H(this.inputTimestamps,e.timestamp,e=>e),ke()&&0===this.currentPacketIndex)if("avc"===this.codec){const t=[];let i=!1;for(const n of Ze(e.data,this.decoderConfig)){const r=et(e.data[n.offset]);if(i||(i=r>=1&&r<=5),r===Xe.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&P(t.description)[4];return nt(e,i+1)}return rt(e)})(t,this.decoderConfig);e=new Ri(r,e.type,e.timestamp,e.duration)}else if("hevc"===this.codec){const t=It(e.data,this.decoderConfig);t&&(e=new Ri(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 to),!this.alphaDecoder){const e=e=>{if(this.colorQueue.length>0){const t=this.colorQueue.shift();y(void 0!==t),this.mergeAlpha(t,e)}else this.alphaQueue.push(e);for(this.decodedAlphaChunkCount++;this.nullAlphaFrameQueue.length>0&&this.nullAlphaFrameQueue[0]===this.decodedAlphaChunkCount;)if(this.nullAlphaFrameQueue.shift(),this.colorQueue.length>0){const e=this.colorQueue.shift();y(void 0!==e),this.mergeAlpha(e,null)}else this.alphaQueue.push(null);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=At(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 ht(e,this.decoderConfig)){const i=ft(e[t.offset]);if(i===Ge.RASL_N||i===Ge.RASL_R)return!0}return!1}sampleHandler(e){if(fe()){if(this.sampleQueue.length>0&&e.timestamp>=T(this.sampleQueue).timestamp){for(const e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}H(this.sampleQueue,e,e=>e.timestamp)}else{const t=this.inputTimestamps.shift();y(void 0!==t),e.setTimestamp(t),this.finalizeAndEmitSample(e)}}finalizeAndEmitSample(e){e.setTimestamp(Math.round(e.timestamp*this.timeResolution)/this.timeResolution),e.setDuration(Math.round(e.duration*this.timeResolution)/this.timeResolution),e.setRotation(this.rotation),this.onSample(e)}mergeAlpha(e,t){return d(this,null,function*(){const i=V();this.mergeAlphaPromises.push(i.promise);const r={sample:null};this.finalSamples.push(r);try{if(t){y(this.merger);const i=yield this.merger.merge(e,t);r.sample=new ba(i)}else r.sample=new ba(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 d(this,null,function*(){var e;if(this.customDecoder?yield this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(y(this.decoder),yield Promise.all([this.decoder.flush(),null==(e=this.alphaDecoder)?void 0:e.flush()]),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),fe()){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()):(y(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 eo=null;class to{constructor(){this.workers=[],this.nextWorkerIndex=0,this.pendingRequests=new Map,this.nextRequestId=0}merge(e,t){if(0===this.workers.length){if(!eo){const e=new Blob([`(${io.toString()})()`],{type:"application/javascript"});eo=URL.createObjectURL(e)}const e=J(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=V();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 io=()=>{let e=null,t=null,i=Promise.resolve();self.addEventListener("message",e=>{const{id:t,color:n,alpha:s}=e.data;i=i.then(()=>d(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)=>d(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)=>d(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;ed(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)=>d(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;ed(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 no extends Ya{constructor(e,t={}){if(!(e instanceof mo))throw new TypeError("videoTrack must be an InputVideoTrack.");ro(t),super(),this._track=e,this._decoderOptions=t}_createDecoder(e,t){return d(this,null,function*(){if(!(yield this._track.canDecode())){if("undefined"===typeof VideoDecoder)throw new Error(ye("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 y(i&&n),n=u(c({},n),{hardwareAcceleration:this._decoderOptions.hardwareAcceleration,optimizeForLatency:this._decoderOptions.optimizeForLatency}),new Za(e,t,i,n,r,s)})}_createPacketSink(){return new Ga(this._track)}getSample(e){return d(this,arguments,function*(e,t={}){Xa(e);try{for(var i,r,n,s=p(this.mediaSamplesAtTimestamps([e],t));i=!(r=yield s.next()).done;i=!1){return r.value}}catch(r){n=[r]}finally{try{i&&(r=s.return)&&(yield r.call(s))}finally{if(n)throw n[0]}}throw new Error("Internal error: Iterator returned nothing.")})}samples(e,t,i={}){return this.mediaSamplesInRange(e,t,i)}samplesAtTimestamps(e,t={}){return this.mediaSamplesAtTimestamps(e,t)}}class so{constructor(e,t={}){var i,r,n;if(this._rotation=0,this._initPromise=null,this._nextCanvasIndex=0,!(e instanceof mo))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&&Ca(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&&ro(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 no(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=(()=>d(this,null,function*(){var e;const t=this._options,i=this._videoTrack,r=null!=(e=t.rotation)?e:yield i.getRotation(),n=yield i.getSquarePixelWidth(),s=yield i.getSquarePixelHeight(),[a,o]=r%180===0?[n,s]:[s,n];let l=t.crop;l&&(l=xa(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||pe()});y(s),e._drawWithFitAndMipmapping(r,s,{fit:this._fit,rotation:this._rotation,crop:this._crop,targetIsFresh:n,fillBlack:!this._alpha&&pe()});const a={canvas:r,timestamp:e.timestamp,duration:e.duration};return e.close(),a}getCanvas(e,t){return d(this,null,function*(){Xa(e),yield this._ensureInit();const i=yield this._videoSampleSink.getSample(e,t);return i&&this._videoSampleToWrappedCanvas(i)})}canvases(e,t,i){return f(this,null,function*(){yield new h(this._ensureInit()),yield*m(Y(this._videoSampleSink.samples(e,t,i),e=>this._videoSampleToWrappedCanvas(e)))})}canvasesAtTimestamps(e,t){return f(this,null,function*(){yield new h(this._ensureInit()),yield*m(Y(this._videoSampleSink.samplesAtTimestamps(e,t),e=>e&&this._videoSampleToWrappedCanvas(e)))})}}class ao extends Qa{constructor(e,t,i,r){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new de,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 Oa))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 Oa(e))}catch(t){this.onError(t)}},error:t=>{t.stack=e,this.onError(t)}}),this.decoder.configure(r)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(y(this.decoder),this.decoder.decodeQueueSize)}decode(e){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).catch(e=>this.onError(e)).finally(()=>this.customDecoderQueueSize--)):(y(this.decoder),null!=this.expectedFirstTimestamp||(this.expectedFirstTimestamp=e.timestamp),this.decoder.decode(e.toEncodedAudioChunk()))}flush(){return d(this,null,function*(){this.customDecoder?yield this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(y(this.decoder),yield this.decoder.flush()),this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0})}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(y(this.decoder),"closed"!==this.decoder.state&&this.decoder.close())}}class oo extends Qa{constructor(e,t,i){super(e,t),this.decoderConfig=i,this.currentTimestamp=null,y(ni.includes(i.codec)),this.codec=i.codec;const{dataType:r,sampleSize:n,littleEndian:s}=ki(this.codec);switch(this.inputSampleSize=n,n){case 1:"unsigned"===r?this.readInputValue=(e,t)=>e.getUint8(t)-o(2,7):"signed"===r?this.readInputValue=(e,t)=>e.getInt8(t):"ulaw"===r?this.readInputValue=(e,t)=>(e=>{let t=0,i=0,r=~e;128&r&&(r&=-129,t=-1),i=5+((240&r)>>4);const n=(1<(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)-o(2,15):"signed"===r?this.readInputValue=(e,t)=>e.getInt16(t,s):y(!1);break;case 3:"unsigned"===r?this.readInputValue=(e,t)=>G(e,t,s)-o(2,23):"signed"===r?this.readInputValue=(e,t)=>((e,t,i)=>G(e,t,i)<<8>>8)(e,t,s):y(!1);break;case 4:"unsigned"===r?this.readInputValue=(e,t)=>e.getUint32(t,s)-o(2,31):"signed"===r?this.readInputValue=(e,t)=>e.getInt32(t,s):"float"===r?this.readInputValue=(e,t)=>e.getFloat32(t,s):y(!1);break;case 8:"float"===r?this.readInputValue=(e,t)=>e.getFloat64(t,s):y(!1);break;default:$(n),y(!1)}switch(n){case 1:"ulaw"===r||"alaw"===r?(this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(e,t,i)=>e.setInt16(t,i,!0)):(this.outputSampleSize=1,this.outputFormat="u8",this.writeOutputValue=(e,t,i)=>e.setUint8(t,i+o(2,7)));break;case 2:this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(e,t,i)=>e.setInt16(t,i,!0);break;case 3:this.outputSampleSize=4,this.outputFormat="s32",this.writeOutputValue=(e,t,i)=>e.setInt32(t,i<<8,!0);break;case 4:this.outputSampleSize=4,"float"===r?(this.outputFormat="f32",this.writeOutputValue=(e,t,i)=>e.setFloat32(t,i,!0)):(this.outputFormat="s32",this.writeOutputValue=(e,t,i)=>e.setInt32(t,i,!0));break;case 8:this.outputSampleSize=4,this.outputFormat="f32",this.writeOutputValue=(e,t,i)=>e.setFloat32(t,i,!0);break;default:$(n),y(!1)}}getDecodeQueueSize(){return 0}decode(e){const t=I(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 Oa({format:this.outputFormat,data:n,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:i,timestamp:o});this.onSample(l)}flush(){return d(this,null,function*(){})}close(){}}class lo extends Ya{constructor(e){if(!(e instanceof po))throw new TypeError("audioTrack must be an InputAudioTrack.");super(),this._track=e}_createDecoder(e,t){return d(this,null,function*(){if(!(yield this._track.canDecode())){if("undefined"===typeof AudioDecoder)throw new Error(ye("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 y(i&&r),ni.includes(r.codec)?new oo(e,t,r):new ao(e,t,i,r)})}_createPacketSink(){return new Ga(this._track)}getSample(e){return d(this,arguments,function*(e,t={}){Xa(e);try{for(var i,r,n,s=p(this.mediaSamplesAtTimestamps([e],t));i=!(r=yield s.next()).done;i=!1){return r.value}}catch(r){n=[r]}finally{try{i&&(r=s.return)&&(yield r.call(s))}finally{if(n)throw n[0]}}throw new Error("Internal error: Iterator returned nothing.")})}samples(e,t,i={}){return this.mediaSamplesInRange(e,t,i)}samplesAtTimestamps(e,t={}){return this.mediaSamplesAtTimestamps(e,t)}}class co{constructor(e){if(!(e instanceof po))throw new TypeError("audioTrack must be an InputAudioTrack.");this._audioSampleSink=new lo(e)}_audioSampleToWrappedArrayBuffer(e){const t={buffer:e.toAudioBuffer(),timestamp:e.timestamp,duration:e.duration};return e.close(),t}getBuffer(e,t){return d(this,null,function*(){Xa(e);const i=yield this._audioSampleSink.getSample(e,t);return i&&this._audioSampleToWrappedArrayBuffer(i)})}buffers(e,t,i){return Y(this._audioSampleSink.samples(e,t,i),e=>this._audioSampleToWrappedArrayBuffer(e))}buffersAtTimestamps(e,t){return Y(this._audioSampleSink.samplesAtTimestamps(e,t),e=>e&&this._audioSampleToWrappedArrayBuffer(e))}}class uo{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof mo}isAudioTrack(){return this instanceof po}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}getInternalCodecId(){return d(this,null,function*(){return this._backing.getInternalCodecId()})}get internalCodecId(){return ho(this._backing.getInternalCodecId(),"internalCodecId","getInternalCodecId")}getLanguageCode(){return d(this,null,function*(){return this._backing.getLanguageCode()})}get languageCode(){return ho(this._backing.getLanguageCode(),"languageCode","getLanguageCode")}getName(){return d(this,null,function*(){return this._backing.getName()})}get name(){return ho(this._backing.getName(),"name","getName")}getTimeResolution(){return d(this,null,function*(){return this._backing.getTimeResolution()})}get timeResolution(){return ho(this._backing.getTimeResolution(),"timeResolution","getTimeResolution")}isRelativeToUnixEpoch(){return d(this,null,function*(){return this._backing.isRelativeToUnixEpoch()})}getUnixTimeForTimestamp(e){return d(this,null,function*(){return this._backing.getUnixTimeForTimestamp(e)})}hasUnixTimeMapping(){return d(this,null,function*(){return null!==(yield this._backing.getUnixTimeForTimestamp(yield this.getFirstTimestamp()))})}getDisposition(){return d(this,null,function*(){return this._backing.getDisposition()})}get disposition(){return ho(this._backing.getDisposition(),"disposition","getDisposition")}getBitrate(){return d(this,null,function*(){return this._backing.getBitrate()})}getAverageBitrate(){return d(this,null,function*(){return this._backing.getAverageBitrate()})}getFirstTimestamp(){return d(this,null,function*(){var e;const t=yield this._backing.getFirstPacket({metadataOnly:!0});return null!=(e=null==t?void 0:t.timestamp)?e:0})}computeDuration(e){return d(this,null,function*(){var t,i;const r=yield this._backing.getPacket(1/0,c({metadataOnly:!0},e)),n=(null!=(t=null==r?void 0:r.timestamp)?t:0)+(null!=(i=null==r?void 0:r.duration)?i:0);return ie(n,yield this.getTimeResolution())})}getDurationFromMetadata(){return d(this,arguments,function*(e={}){return this._backing.getDurationFromMetadata(e)})}computePacketStats(e=1/0,t){return d(this,null,function*(){const i=new Ga(this);let r=1/0,n=-1/0,s=0,a=0;try{for(var o,l,u,d=p(i.packets(void 0,void 0,c({metadataOnly:!0},t)));o=!(l=yield d.next()).done;o=!1){const t=l.value;if(s>=e&&t.timestamp>=n)break;r=Math.min(r,t.timestamp),n=Math.max(n,t.timestamp+t.duration),s++,a+=t.byteLength}}catch(l){u=[l]}finally{try{o&&(l=d.return)&&(yield l.call(d))}finally{if(u)throw u[0]}}return{packetCount:s,averagePacketRate:s?Number((s/(n-r)).toPrecision(16)):0,averageBitrate:s?Number((8*a/(n-r)).toPrecision(16)):0}})}isLive(){return d(this,null,function*(){return null!==(yield this._backing.getLiveRefreshInterval())})}getLiveRefreshInterval(){return d(this,null,function*(){return this._backing.getLiveRefreshInterval()})}canBePairedWith(e){if(!(e instanceof uo))throw new TypeError("other must be an InputTrack.");return this.input===e.input&&this!==e&&(this._backing.getPairingMask()&e._backing.getPairingMask())!==BigInt("0")}getPairableTracks(e){return d(this,null,function*(){return this.input.getTracks(bo({filter:e=>e.canBePairedWith(this)},e))})}getPairableVideoTracks(e){return d(this,null,function*(){return this.input.getVideoTracks(bo({filter:e=>e.canBePairedWith(this)},e))})}getPairableAudioTracks(e){return d(this,null,function*(){return this.input.getAudioTracks(bo({filter:e=>e.canBePairedWith(this)},e))})}getPrimaryPairableVideoTrack(e){return d(this,null,function*(){return this.input.getPrimaryVideoTrack(bo({filter:e=>e.canBePairedWith(this)},e))})}getPrimaryPairableAudioTrack(e){return d(this,null,function*(){return this.input.getPrimaryAudioTrack(bo({filter:e=>e.canBePairedWith(this)},e))})}hasPairableTrack(e){return d(this,null,function*(){e&&(e=fo(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=fo(e)),this.hasPairableTrack(t=>d(this,null,function*(){return t.isVideoTrack()&&(!e||(yield e(t)))}))}hasPairableAudioTrack(e){return e&&(e=fo(e)),this.hasPairableTrack(t=>d(this,null,function*(){return t.isAudioTrack()&&(!e||(yield e(t)))}))}}const ho=(e,t,i)=>{if(Te(e))throw new Error(`'${t}' is deprecated and not available synchronously for this track. Use the preferred '${i}()' instead.`);return e},fo=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 Te(r)?r.then(i):i(r)}:void 0};class mo extends uo{constructor(e,t){super(e,t),this._pixelAspectRatioCache=null,this._backing=t}get type(){return"video"}getCodec(){return d(this,null,function*(){return this._backing.getCodec()})}get codec(){return ho(this._backing.getCodec(),"codec","getCodec")}hasOnlyKeyPackets(){return d(this,null,function*(){var e,t,i;return null!=(i=yield null==(t=(e=this._backing).getHasOnlyKeyPackets)?void 0:t.call(e))?i:"prores"===(yield this._backing.getCodec())})}getCodedWidth(){return d(this,null,function*(){return this._backing.getCodedWidth()})}get codedWidth(){return ho(this._backing.getCodedWidth(),"codedWidth","getCodedWidth")}getCodedHeight(){return d(this,null,function*(){return this._backing.getCodedHeight()})}get codedHeight(){return ho(this._backing.getCodedHeight(),"codedHeight","getCodedHeight")}getRotation(){return d(this,null,function*(){return this._backing.getRotation()})}get rotation(){return ho(this._backing.getRotation(),"rotation","getRotation")}getSquarePixelWidth(){return d(this,null,function*(){return this._backing.getSquarePixelWidth()})}get squarePixelWidth(){return ho(this._backing.getSquarePixelWidth(),"squarePixelWidth","getSquarePixelWidth")}getSquarePixelHeight(){return d(this,null,function*(){return this._backing.getSquarePixelHeight()})}get squarePixelHeight(){return ho(this._backing.getSquarePixelHeight(),"squarePixelHeight","getSquarePixelHeight")}getPixelAspectRatio(){return d(this,null,function*(){var e;return null!=(e=this._pixelAspectRatioCache)?e:this._pixelAspectRatioCache=Ee({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=Ee({num:ho(this._backing.getSquarePixelWidth(),"pixelAspectRatio","getPixelAspectRatio")*ho(this._backing.getCodedHeight(),"pixelAspectRatio","getPixelAspectRatio"),den:ho(this._backing.getSquarePixelHeight(),"pixelAspectRatio","getPixelAspectRatio")*ho(this._backing.getCodedWidth(),"pixelAspectRatio","getPixelAspectRatio")})}getDisplayWidth(){return d(this,null,function*(){var e,t;const i=yield null==(t=(e=this._backing).getMetadataDisplayWidth)?void 0:t.call(e);if(null!=i)return i;return(yield this.getRotation())%180===0?this.getSquarePixelWidth():this.getSquarePixelHeight()})}get displayWidth(){var e,t;const i=null==(t=(e=this._backing).getMetadataDisplayWidth)?void 0:t.call(e);if(void 0!==i){const e=ho(i,"displayWidth","getDisplayWidth");if(null!==e)return e}const r=ho(this._backing.getRotation(),"displayWidth","getDisplayWidth")%180===0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight();return ho(r,"displayWidth","getDisplayWidth")}getDisplayHeight(){return d(this,null,function*(){var e,t;const i=yield null==(t=(e=this._backing).getMetadataDisplayHeight)?void 0:t.call(e);if(null!=i)return i;return(yield this.getRotation())%180===0?this.getSquarePixelHeight():this.getSquarePixelWidth()})}get displayHeight(){var e,t;const i=null==(t=(e=this._backing).getMetadataDisplayHeight)?void 0:t.call(e);if(void 0!==i){const e=ho(i,"displayHeight","getDisplayHeight");if(null!==e)return e}const r=ho(this._backing.getRotation(),"displayHeight","getDisplayHeight")%180===0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth();return ho(r,"displayHeight","getDisplayHeight")}getColorSpace(){return d(this,null,function*(){return this._backing.getColorSpace()})}hasHighDynamicRange(){return d(this,null,function*(){const e=yield this._backing.getColorSpace();return"bt2020"===e.primaries||"smpte432"===e.primaries||"pq"===e.transfer||"hlg"===e.transfer||"bt2020-ncl"===e.matrix})}canBeTransparent(){return d(this,null,function*(){return this._backing.canBeTransparent()})}getDecoderConfig(){return d(this,null,function*(){return this._backing.getDecoderConfig()})}getCodecParameterString(){return d(this,null,function*(){var e,t,i;const r=yield null==(t=(e=this._backing).getMetadataCodecParameterString)?void 0:t.call(e);if(null!=r)return r;const n=yield this._backing.getDecoderConfig();return null!=(i=null==n?void 0:n.codec)?i:null})}canDecode(){return d(this,null,function*(){try{const e=yield this._backing.getDecoderConfig();if(!e)return!1;const t=yield this._backing.getCodec();if(y(null!==t),Va.some(i=>i.supports(t,e)))return!0;if("undefined"===typeof VideoDecoder)return!1;return!0===(yield VideoDecoder.isConfigSupported(e)).supported}catch(e){return Me._error("Error during decodability check:",e),!1}})}determinePacketType(e){return d(this,null,function*(){if(!(e instanceof Ri))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("packet must not be metadata-only to determine its type.");const t=yield this.getCodec();if(null===t)return null;const i=yield this.getDecoderConfig();return y(i),At(t,i,e.data)})}computeFrameRateMetrics(){return d(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&&(!Ie(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 Ga(this),a=[];let o=-1/0,l=0;try{for(var c,u,d,h=p(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 p=0;pe-t),x=P-1>>1,C=P>>1;let B=0,E=0,_=0;for(const p of I)if(_+=T.get(p),0===B&&_>x&&(B=p),_>C){E=p;break}const R=(y/B+y/E)/2;return{underlyingFrameRate:k,bestGuessFrameRate:null!==k?k:wo(R),minFrameRate:y/S,maxFrameRate:y/v,averageFrameRate:y*P/w,medianFrameRate:R,frameRateIsConstant:null!==k&&1===v&&1===S,probedPacketCount:l}})}}class po extends uo{constructor(e,t){super(e,t),this._backing=t}get type(){return"audio"}getCodec(){return d(this,null,function*(){return this._backing.getCodec()})}get codec(){return ho(this._backing.getCodec(),"codec","getCodec")}hasOnlyKeyPackets(){return d(this,null,function*(){var e,t,i;return null==(i=yield null==(t=(e=this._backing).getHasOnlyKeyPackets)?void 0:t.call(e))||i})}getNumberOfChannels(){return d(this,null,function*(){return this._backing.getNumberOfChannels()})}get numberOfChannels(){return ho(this._backing.getNumberOfChannels(),"numberOfChannels","getNumberOfChannels")}getSampleRate(){return d(this,null,function*(){return this._backing.getSampleRate()})}get sampleRate(){return ho(this._backing.getSampleRate(),"sampleRate","getSampleRate")}getDecoderConfig(){return d(this,null,function*(){return this._backing.getDecoderConfig()})}getCodecParameterString(){return d(this,null,function*(){var e,t,i;const r=yield null==(t=(e=this._backing).getMetadataCodecParameterString)?void 0:t.call(e);if(null!=r)return r;const n=yield this._backing.getDecoderConfig();return null!=(i=null==n?void 0:n.codec)?i:null})}canDecode(){return d(this,null,function*(){try{const e=yield this._backing.getDecoderConfig();if(!e)return!1;const t=yield this._backing.getCodec();if(y(null!==t),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 Me._error("Error during decodability check:",e),!1}})}determinePacketType(e){return d(this,null,function*(){if(!(e instanceof Ri))throw new TypeError("packet must be an EncodedPacket.");return null===(yield this.getCodec())?null:"key"})}}const go=e=>-(null!=e?e:-1/0),ko=e=>-e,yo=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 Te(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 Te(r)?r.then(i):i(r)}:void 0}},bo=(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 Te(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 Te(o)||Te(l)?Promise.all([o,l]).then(([e,t])=>c(e,t)):c(o,l)}:void 0}),To=(e,t)=>d(null,null,function*(){let i=e;if(null==t?void 0:t.filter){const r=e.map(e=>t.filter(e));if(r.some(e=>Te(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=>Te(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)}),vo=(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 Us)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof ds||e.source instanceof hs))throw new TypeError("options.source must be a Source or SourceRef.");if(e.source instanceof ds&&e.source._disposed)throw new TypeError("options.source must not be a disposed Source.");if(void 0!==e.initInput&&!(e.initInput instanceof Io))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 ds?this._rootRef=e.source.ref():this._rootRef=e.source,this._sourceRefs.push(this._rootRef)}get _rootSource(){return this._rootRef.source}_getSourceUncached(e){return d(this,null,function*(){y(this._rootSource instanceof fs);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&&ms(i.request,e));if(i)return i.age++,Promise.resolve(i.sourceRef.source.ref());const r=this._sourceCachePromises.find(i=>i.cacheGroup===t&&ms(i.request,e));if(r)return r.promise.then(e=>e.sourceRef.source.ref());const n=(()=>d(this,null,function*(){const i=yield this._getSourceUncached(e);if(Ce(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);y(-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);y(-1!==r),this._sourceCachePromises.splice(r,1);return{request:e,sourceRef:i,age:this._nextSourceCacheAge++,cacheGroup:t}}))();return this._sourceCachePromises.push({request:e,cacheGroup:t,promise:n}),n.then(e=>{const t=e.sourceRef.source.ref();return this._sourceCache.push(e),t})}_getDemuxer(){var e;return null!=(e=this._demuxerPromise)?e:this._demuxerPromise=(()=>d(this,null,function*(){var e;this._reader=new Bo(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 xo}))()}get source(){return this._rootSource}getFormat(){return d(this,null,function*(){return yield this._getDemuxer(),y(this._format),this._format})}canRead(){return d(this,null,function*(){try{return yield this._getDemuxer(),!0}catch(e){if(e instanceof xo)return!1;throw e}})}getFirstTimestamp(e){return d(this,null,function*(){null!=e||(e=yield this.getTracks());const t=e.filter(e=>null!==e);if(0===t.length)return 0;const i=yield Promise.all(t.map(e=>e._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 d(this,null,function*(){null!=e||(e=yield this.getTracks());const i=e.filter(e=>null!==e);if(0===i.length)return 0;const r=yield Promise.all(i.map(e=>e.computeDuration(t)));return Math.max(...r)})}getDurationFromMetadata(e,t){return d(this,null,function*(){null!=e||(e=yield this.getTracks());const i=e.filter(e=>null!==e),r=(yield Promise.all(i.map(e=>e.getDurationFromMetadata(t)))).filter(e=>null!==e);return 0===r.length?null:Math.max(...r)})}getTracks(e){return d(this,null,function*(){e&&(e=yo(e));const t=(yield this._getTrackBackings()).map(e=>this._wrapBackingAsTrack(e));return To(t,e)})}getVideoTracks(e){return d(this,null,function*(){e&&(e=yo(e));const t=(yield this.getTracks()).filter(e=>e.isVideoTrack());return To(t,e)})}getAudioTracks(e){return d(this,null,function*(){e&&(e=yo(e));const t=(yield this.getTracks()).filter(e=>e.isAudioTrack());return To(t,e)})}getPrimaryVideoTrack(e){return d(this,null,function*(){var t;e&&(e=yo(e));const i=bo(e,{sortBy:e=>d(null,null,function*(){return[ko((yield e.getDisposition()).default),ko(yield e.hasPairableAudioTrack()),ko(!(yield e.hasOnlyKeyPackets())),go(yield e.getBitrate())]})});return null!=(t=(yield this.getVideoTracks(i))[0])?t:null})}getPrimaryAudioTrack(e){return d(this,null,function*(){var t;e&&(e=yo(e));const i=yield this.getPrimaryVideoTrack(),r=bo(e,{sortBy:e=>d(this,null,function*(){return[ko(!i||e.canBePairedWith(i)),ko((yield e.getDisposition()).default),go(yield e.getBitrate())]})});return null!=(t=(yield this.getAudioTracks(r))[0])?t:null})}_getTrackBackings(){return d(this,null,function*(){var e;const t=yield this._getDemuxer();return null!=(e=this._trackBackingsCache)?e:this._trackBackingsCache=yield t.getTrackBackings()})}_wrapBackingAsTrack(e){const t=this._backingToTrack.get(e);if(t)return t;const i="video"===e.getType()?new mo(this,e):new po(this,e);return this._backingToTrack.set(e,i),i}getMimeType(){return d(this,null,function*(){return(yield this._getDemuxer()).getMimeType()})}getMetadataTags(){return d(this,null,function*(){return(yield this._getDemuxer()).getMetadataTags()})}dispose(){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 xo extends Error{constructor(e="Input has an unsupported or unrecognizable format."){super(e),this.name="UnsupportedInputFormatError"}}class Co extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}}class Bo{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 Co;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 Eo(t,I(t),0,e,e)}const i=e+t,r=this.source._read(e,i,0,us);return Te(r)?r.then(t=>t?new Eo(t.bytes,t.view,t.offset,e,i):null):r?new Eo(r.bytes,r.view,r.offset,e,i):null}requestSliceRange(e,t,i){if(this.source._disposed)throw new Co;if(e<0)return null;if(null!==this.fileSizeNonStrict)return this.requestSlice(e,J(this.fileSizeNonStrict-e,t,i));{const r=this.requestSlice(e,i),n=r=>r||(y(null!==this.fileSizeNonStrict),this.requestSlice(e,J(this.fileSizeNonStrict-e,t,i)));return Te(r)?r.then(n):n(r)}}requestEntireFile(){if(null!==this.fileSizeNonStrict)return this.requestSlice(0,this.fileSizeNonStrict);return(()=>d(this,null,function*(){const e=[];let t=0;for(;;){if(1===e.length&&null!==this.fileSizeNonStrict)return this.requestSlice(0,this.fileSizeNonStrict);let i=this.requestSliceRange(t,0,1024);if(Te(i)&&(i=yield i),!i||0===i.length)break;const r=Ro(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 Eo(i,I(i),0,0,t)}))()}}class Eo{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 Eo(e,I(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 Eo(this.bytes,this.view,this.offset,e,e+t)}}const _o=(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.`)},Ro=(e,t)=>{_o(e,t);const i=e.bytes.subarray(e.bufferPos,e.bufferPos+t);return e.bufferPos+=t,i},Fo=e=>(_o(e,1),e.view.getUint8(e.bufferPos++)),Ao=(e,t)=>{_o(e,2);const i=e.view.getUint16(e.bufferPos,t);return e.bufferPos+=2,i},Do=e=>{_o(e,2);const t=e.view.getUint16(e.bufferPos,!1);return e.bufferPos+=2,t},Mo=e=>{_o(e,3);const t=G(e.view,e.bufferPos,!1);return e.bufferPos+=3,t},No=e=>{_o(e,2);const t=e.view.getInt16(e.bufferPos,!1);return e.bufferPos+=2,t},Oo=(e,t)=>{_o(e,4);const i=e.view.getUint32(e.bufferPos,t);return e.bufferPos+=4,i},Lo=e=>{_o(e,4);const t=e.view.getUint32(e.bufferPos,!1);return e.bufferPos+=4,t},zo=e=>{_o(e,4);const t=e.view.getUint32(e.bufferPos,!0);return e.bufferPos+=4,t},Uo=e=>{_o(e,4);const t=e.view.getInt32(e.bufferPos,!1);return e.bufferPos+=4,t},qo=(e,t)=>{let i,r;return t?(i=Oo(e,!0),r=Oo(e,!0)):(r=Oo(e,!1),i=Oo(e,!1)),4294967296*r+i},Wo=e=>4294967296*Lo(e)+Lo(e),Ho=e=>4294967296*Uo(e)+Lo(e),Vo=e=>{const t=zo(e),i=(e=>{_o(e,4);const t=e.view.getInt32(e.bufferPos,!0);return e.bufferPos+=4,t})(e);return 4294967296*i+t},jo=e=>{_o(e,4);const t=e.view.getFloat32(e.bufferPos,!1);return e.bufferPos+=4,t},Ko=e=>{_o(e,8);const t=e.view.getFloat64(e.bufferPos,!1);return e.bufferPos+=8,t},Xo=(e,t)=>{_o(e,t);let i="";for(let r=0;rx.decode(Ro(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 Go,Qo,Yo,Jo;(Qo=Go||(Go={}))[Qo.Unsynchronisation=128]="Unsynchronisation",Qo[Qo.ExtendedHeader=64]="ExtendedHeader",Qo[Qo.ExperimentalIndicator=32]="ExperimentalIndicator",Qo[Qo.Footer=16]="Footer",(Jo=Yo||(Yo={}))[Jo.ISO_8859_1=0]="ISO_8859_1",Jo[Jo.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",Jo[Jo.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",Jo[Jo.UTF_8=3]="UTF_8";const Zo=128,el=10,tl=["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"],il=(e,t)=>{var i;const r=e.filePos;null!=t.raw||(t.raw={}),null!=(i=t.raw).TAG||(i.TAG=Ro(e,Zo-3)),e.filePos=r;const n=rl(e,30);n&&(null!=t.title||(t.title=n));const s=rl(e,30);s&&(null!=t.artist||(t.artist=s));const a=rl(e,30);a&&(null!=t.album||(t.album=a));const o=rl(e,4),l=Number.parseInt(o,10);Number.isInteger(l)&&l>0&&(null!=t.date||(t.date=new Date(String(l))));const c=Ro(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=rl(e,28),e.skip(2)}else e.skip(-30),u=rl(e,30);u&&(null!=t.comment||(t.comment=u));const d=Fo(e);d{const i=Ro(e,t),r=ve(i.indexOf(0),i.length),n=i.subarray(0,r);let s="";for(let a=0;a{const t=e.filePos,i=Xo(e,3),r=Fo(e),n=Fo(e),s=Fo(e),a=Lo(e);if("ID3"!==i||255===r||255===n||0!==(2155905152&a))return e.filePos=t,null;let o=Ii(a);return s&Go.Footer&&(o+=el),{majorVersion:r,revision:n,flags:s,size:o}},sl=(e,t,i)=>{var r,n,s,a,o,l;if(![2,3,4].includes(t.majorVersion))return void Me._warn(`Unsupported ID3v2 major version: ${t.majorVersion}`);const c=t.flags&Go.Footer?t.size-el:t.size,u=Ro(e,c),d=new al(t,u);if(t.flags&Go.Unsynchronisation&&3===t.majorVersion&&d.ununsynchronizeAll(),t.flags&Go.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&Go.Unsynchronisation)),h)Me._warn(`Skipping encrypted ID3v2 frame ${e.id}`),d.pos=u;else if(f)Me._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!==tl[e]){null!=i.genre||(i.genre=tl[e]);break}}if(t=/^\d+$/.exec(e),t){const e=Number.parseInt(t[0]);if(void 0!==tl[e]){null!=i.genre||(i.genre=tl[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 al{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:Ii(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 Yo.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=ve(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=ve(r.findIndex(e=>0===e),r.length);return this.pos=i+Math.min(e+1,r.length),x.decode(r.subarray(0,e))}case Yo.UTF_16_BE_NO_BOM:{const e=new TextDecoder("utf-16be"),t=ve(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 Yo.UTF_8:{const e=ve(r.findIndex(e=>0===e),r.length);return this.pos=i+Math.min(e+1,r.length),x.decode(r.subarray(0,e))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";const t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}}class ol{constructor(e){this.events=e,this.input=null,this.audioSink=null,this.audioIterator=null,this.audioContext=null,this.gainNode=null,this.audioContextStartTime=0,this.playbackTimeAtStart=0,this.latestScheduledEndTime=0,this.duration=Number.NaN,this.paused=!0,this.volume=.7,this.muted=!1,this.playbackRate=1,this.asyncId=0,this.queuedNodes=new Set}get currentTime(){return this.paused?this.playbackTimeAtStart:(this.audioContext.currentTime-this.audioContextStartTime)*this.playbackRate+this.playbackTimeAtStart}ensureAudioContext(e){if(this.audioContext)return;const t=window.AudioContext||window.webkitAudioContext;try{this.audioContext=new t({sampleRate:e})}catch(i){this.audioContext=new t}this.gainNode=this.audioContext.createGain(),this.gainNode.connect(this.audioContext.destination),this.updateGain()}updateGain(){if(!this.gainNode)return;const e=this.muted?0:this.volume;this.gainNode.gain.value=e*e}stopQueuedNodes(){this.queuedNodes.forEach(e=>e.stop()),this.queuedNodes.clear()}stopIterator(){return d(this,null,function*(){var e;yield null==(e=this.audioIterator)?void 0:e.return(),this.audioIterator=null})}handleNoAudioTrack(){this.audioSink=null,this.ensureAudioContext()}load(e,t){return d(this,null,function*(){++this.asyncId,yield this.stopIterator(),this.stopQueuedNodes(),this.paused=!0,this.playbackTimeAtStart=0,this.audioContextStartTime=0;const{input:i,audioTrack:r,duration:n}=e;return this.input=i,this.duration=n,r?null!==r.codec&&(yield r.canDecode())?(this.ensureAudioContext(r.sampleRate),this.audioSink=new co(r),void(null==t||t())):(this.audioSink=null,this.ensureAudioContext(),void(null==t||t())):(this.handleNoAudioTrack(),void(null==t||t()))})}runIterator(e){return d(this,null,function*(){if(!this.audioSink)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 d(this,null,function*(){if(!this.paused)return;this.audioContext||this.ensureAudioContext(),"suspended"===this.audioContext.state&&(yield this.audioContext.resume()),this.audioContextStartTime=this.audioContext.currentTime,this.latestScheduledEndTime=this.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 d(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 ll(e){return d(this,null,function*(){var t,i;return null!=(i=null!=(t=yield e.getAverageBitrate())?t:yield e.getBitrate())?i:0})}const cl=/\.m3u8(?:$|[?#])/i;function ul(e){return"string"===typeof e&&cl.test(e)}function dl(e){const t=function(e){return"string"===typeof e?new vs(e):e instanceof Blob?new ks(e):"undefined"!==typeof ReadableStream&&e instanceof ReadableStream?new Ps(e):null!=e?e:null}(e);return t?new Io({source:t,formats:ul(e)?da:ua}):null}class hl{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 d(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 fl(e){return d(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 ml{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 d(this,null,function*(){return function(e,t,i,r,n=()=>!0){return d(this,null,function*(){if((null==r?void 0:r.aborted)||!n())return!1;if(!t||"string"!==typeof e||ul(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 d(this,null,function*(){var e;yield null==(e=this.videoIterator)?void 0:e.return(),this.videoIterator=null})}clear(){this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height)}load(e,t){return d(this,null,function*(){++this.asyncId,yield this.stopIterator(),this.clear(),this.posterDrawn=!1;const{input:i,videoTrack:r,duration:n}=e;if(this.input=i,this.duration=n,!r)return this.handleNoVideoTrack(),void(null==t||t());if(null===r.codec||!(yield r.canDecode()))return this.handleNoVideoTrack(),void(null==t||t());const s=yield r.canBeTransparent();this.videoSink=new so(r,{poolSize:2,fit:"contain",alpha:s}),this.width=r.displayWidth,this.height=r.displayHeight,this.canvas.width=this.width,this.canvas.height=this.height,null==t||t(),yield this.resetIterator(0)})}handleNoVideoTrack(){this.videoSink=null,this.width=0,this.height=0,this.canvas.width=0,this.canvas.height=0,this.clear(),this.drawPoster()}resetIterator(e){return d(this,null,function*(){var t,i;if(yield this.stopIterator(),!this.videoSink)return;this.videoIterator=this.videoSink.canvases(e);const r=null!=(t=(yield this.videoIterator.next()).value)?t:null,n=null!=(i=(yield this.videoIterator.next()).value)?i:null;this.nextFrame=n,r?this.ctx.drawImage(r.canvas,0,0):this.drawPoster()})}updateNextFrame(e){return d(this,null,function*(){var t;if(this.videoIterator&&!this.isFetching){this.isFetching=!0;try{for(;;){const i=null!=(t=(yield this.videoIterator.next()).value)?t:null;if(!i||e!==this.asyncId)return;const r=this.audioClock.currentTime,n=this.dropLateFrames?Math.max(.06,this.avSyncTolerance/Math.max(1,this.playbackRate)):0;if(!(this.dropLateFrames&&i.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 d(this,null,function*(){this.asyncId++,yield this.resetIterator(e)})}setPlaybackRate(e){this.playbackRate=Math.max(.1,Number(e)||1)}destroy(){this.asyncId++,this.stop(),this.stopIterator(),this.posterDrawn=!1,this.videoSink=null,this.input=null}}class pl{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 ol(i),this.video=new ml({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 d(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 hl;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 d(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=dl(e);if(!r)return this.video.handleNoVideoTrack(),void this.audio.handleNoAudioTrack();i.own(r);const n=yield function(e,t){return d(this,null,function*(){const i=yield e.getPrimaryVideoTrack(),r=i?yield i.getPrimaryPairableAudioTrack():yield e.getPrimaryAudioTrack(),n=yield fl({input:e,videoTrack:i,audioTrack:r}),s=i||r,a=ul(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 d(this,arguments,function*({videoTrack:e,audioTrack:t,videoMode:i,audioMode:r}){if(!this.media)return;const n=u(c({},this.media),{videoTrack:e,audioTrack:t,videoMode:i,audioMode:r}),s=!this.paused,a=this.currentTime;this.pause(),this.ended=!1,this.seeking=!0,this.events.emit("seeking"),this.events.emit("waiting"),n.duration=yield fl(n),this.media=n,yield Promise.all([this.video.load(n),this.audio.load(n)]),yield Promise.all([this.video.seek(a),this.audio.seek(a)]),this.readyState=4,this.networkState=1,this.seeking=!1,this.events.emit("loadedmetadata"),this.events.emit("durationchange"),this.events.emit("progress"),this.events.emit("loadeddata"),this.events.emit("canplay"),this.events.emit("canplaythrough"),this.events.emit("seeked"),s&&(yield this.play())})}selectHlsQuality(e){return d(this,null,function*(){var t,i;if(!(null==(t=this.media)?void 0:t.isHls)||!this.input)return;const r=yield this.input.getVideoTracks(),n="auto"===e?yield this.input.getPrimaryVideoTrack():null!=(i=r.find(t=>t.id===e))?i:this.media.videoTrack;if(!n)return;let s=this.media.audioTrack,a=this.media.audioMode;s&&n.canBePairedWith(s)||(s=yield n.getPrimaryPairableAudioTrack(),a="auto"),yield this.replaceTracks({videoTrack:n,audioTrack:s,videoMode:"auto"===e?"auto":"manual",audioMode:a})})}selectHlsAudio(e){return d(this,null,function*(){var t,i;if(!(null==(t=this.media)?void 0:t.isHls)||!this.input)return;const r=yield this.input.getAudioTracks(),n="auto"===e?this.media.videoTrack?yield this.media.videoTrack.getPrimaryPairableAudioTrack():yield this.input.getPrimaryAudioTrack():null!=(i=r.find(t=>t.id===e))?i:this.media.audioTrack;if(!n)return;let s=this.media.videoTrack,a=this.media.videoMode;s&&n.canBePairedWith(s)||(s=yield n.getPrimaryPairableVideoTrack(),a="auto"),yield this.replaceTracks({videoTrack:s,audioTrack:n,videoMode:a,audioMode:"auto"===e?"auto":"manual"})})}getHlsState(){return function(e){return d(this,null,function*(){var t,i,r,n;if(!(null==e?void 0:e.isHls)||!e.input)return null;const[s,a]=yield Promise.all([e.input.getVideoTracks(),e.videoTrack?e.videoTrack.getPairableAudioTracks():[]]),[o,l]=yield Promise.all([Promise.all(s.map((e,t)=>d(null,null,function*(){return{id:e.id,track:e,index:t,name:yield e.getName(),height:yield e.getDisplayHeight(),bitrate:yield ll(e)}}))),Promise.all(a.map((e,t)=>d(null,null,function*(){const i=yield e.getName(),r=yield e.getLanguageCode();return{id:e.id,track:e,index:t,name:i,lang:r,language:r,bitrate:yield ll(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 d(this,null,function*(){this.paused&&(this.ended&&(this.ended=!1,yield this.seek(0)),this.paused=!1,yield this.audio.play(),this.video.start(this.audio),this.events.emit("play"),this.events.emit("playing"))})}pause(){this.paused||(this.paused=!0,this.audio.pause(),this.video.stop(),this.events.emit("pause"))}seek(e){return d(this,null,function*(){const t=!this.paused;this.ended=!1,this.seeking=!0,this.events.emit("seeking"),this.events.emit("waiting"),this.pause(),yield Promise.all([this.audio.seek(e),this.video.seek(e)]),this.seeking=!1,this.events.emit("seeked"),t&&!this.ended&&(yield this.play())})}setVolume(e,t){this.audio.setVolume(e,t)}setPlaybackRate(e){this.audio.setPlaybackRate(e),this.video.setPlaybackRate(e)}destroy(){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}}class gl{constructor({art:e,canvas:t,ctx:i,option:r}){var n,s;this.art=e,this.canvas=t,this.option=r,this.events=new k,this.engine=new pl({canvas:t,ctx:i,events:this.events,option:r}),this._src=null,this._volume=null!=(n=r.volume)?n:.7,this._muted=!!r.muted,this._playbackRate=1,this.engine.setVolume(this._volume,this._muted),this.setupEventForwarding(),r.source?this.src=r.source:(null==(s=e.option)?void 0:s.url)&&(this.src=e.option.url)}setupEventForwarding(){const{events:e}=this.art.constructor.config;e.forEach(e=>{this.events.addEventListener(e,e=>{this.art.emit(`video:${e.type}`,e)})})}addEventListener(e,t){this.events.addEventListener(e,t)}removeEventListener(e,t){this.events.removeEventListener(e,t)}get src(){return this._src}set src(e){this._src=e,e&&this.engine.load(e)}get currentSrc(){return this._src}get currentTime(){return this.engine.currentTime}set currentTime(e){this.engine.seek(Number(e)||0)}get duration(){return this.engine.duration}get buffered(){return this.createTimeRanges(0,this.engine.duration)}get played(){return this.createTimeRanges(0,this.engine.currentTime)}get seekable(){return this.createTimeRanges(0,this.engine.duration)}createTimeRanges(e,t){const i=this.engine.duration;return!i||Number.isNaN(i)||t<=0?{length:0,start:()=>0,end:()=>0}:{length:1,start:()=>e,end:()=>t}}get paused(){return this.engine.paused}get playing(){return!this.engine.paused&&!this.engine.ended}get ended(){return this.engine.ended}get seeking(){return this.engine.seeking}get readyState(){return this.engine.readyState}get networkState(){return this.engine.networkState}get error(){return this.engine.error}get playbackRate(){return this._playbackRate}set playbackRate(e){const t=Number(e);Number.isNaN(t)||t<=0||(this._playbackRate=t,this.engine.setPlaybackRate(t),this.events.emit("ratechange"))}get volume(){return this._volume}set volume(e){this._volume=function(e,t,i){return Math.max(t,Math.min(i,Number(e)||0))}(e,0,1),this._muted=!1,this.engine.setVolume(this._volume,this._muted),this.events.emit("volumechange")}get muted(){return this._muted}set muted(e){this._muted=!!e,this.engine.setVolume(this._volume,this._muted),this.events.emit("volumechange")}play(){return this.engine.play()}pause(){this.engine.pause()}load(){this._src&&this.engine.load(this._src)}getM3u8State(){return this.engine.getHlsState()}switchM3u8Quality(e){return this.engine.selectHlsQuality(e)}switchM3u8Audio(e){return this.engine.selectHlsAudio(e)}get videoWidth(){return this.engine.videoWidth}get videoHeight(){return this.engine.videoHeight}get poster(){return this.option.poster||""}set poster(e){this.option.poster=e}get autoplay(){return this.option.autoplay||!1}set autoplay(e){}get loop(){return this.option.loop||!1}set loop(e){}get controls(){return!1}set controls(e){}get playsInline(){return!0}set playsInline(e){}get crossOrigin(){return this.option.crossOrigin||""}set crossOrigin(e){}get preload(){return"auto"}set preload(e){}get defaultMuted(){return!1}set defaultMuted(e){}get defaultPlaybackRate(){return 1}set defaultPlaybackRate(e){}canPlayType(e){return"maybe"}getBoundingClientRect(){return this.canvas.getBoundingClientRect()}requestVideoFrameCallback(e){return requestAnimationFrame(t=>{e(t,{presentationTime:this.engine.currentTime,expectedDisplayTime:t+16.6,width:this.engine.videoWidth,height:this.engine.videoHeight,mediaTime:this.engine.currentTime,presentedFrames:0,processingDuration:0,captureTime:t,receiveTime:t,rtpTimestamp:0})})}cancelVideoFrameCallback(e){cancelAnimationFrame(e)}setAttribute(e,t){"src"===e?this.src=t:"autoplay"===e?this.autoplay=t:"loop"===e?this.loop=t:"muted"===e?this.muted=!0:this.canvas.setAttribute(e,t)}destroy(){this.engine.destroy()}}return function(e={}){return t=>{const{constructor:i}=t,{createElement:r}=i.utils,n=r("canvas"),s=n.getContext("2d"),a=new gl({art:t,canvas:n,ctx:s,option:e});t.mediabunny=a;const o={};for(const e in n)"function"===typeof n[e]&&(o[e]=n[e].bind(n));const l=new Set([...Object.getOwnPropertyNames(a),...Object.getOwnPropertyNames(Object.getPrototypeOf(a))]);for(const e of l)"constructor"!==e&&(e in n||Object.defineProperty(n,e,{get(){const t=a[e];return"function"===typeof t?t.bind(a):t},set(t){a[e]=t},configurable:!0,enumerable:!0}));for(const e in o)n[e]=(...t)=>o[e](...t);function c(){var e;(null==(e=t.template)?void 0:e.$player)&&!t.option.autoSize&&Object.assign(n.style,{width:"100%",height:"100%",objectFit:"contain"})}return t.on("resize",c),t.on("video:loadedmetadata",c),function({art:e,shim:t,option:i}){if(i.m3u8)return e.on("video:loadedmetadata",u),e.on("restart",u),{update:u};function r(t){e.controls.cache.has(t)&&e.controls.remove(t)}function n(t){e.setting.find(t)&&e.setting.remove(t)}function s(){r("mediabunny-quality"),n("mediabunny-quality")}function a(){r("mediabunny-audio"),n("mediabunny-audio")}function o(e={}){return e.control||e.setting}function l(r){return d(this,null,function*(){var n;const a=(null==(n=i.m3u8)?void 0:n.quality)||{};if(!o(a)||!(null==r?void 0:r.levels.length))return void s();const l=a.auto||"Auto",c=a.title||"Quality",h=a.getName||(e=>e.name||`${e.height}P`),f=r.currentLevel?h(r.currentLevel):l,m=g(r.levels.map(e=>{var t;return{html:h(e),value:e.id,default:(null==(t=r.currentLevel)?void 0:t.id)===e.id}}),"html").sort((e,t)=>{const i=r.levels.find(t=>t.id===e.value),n=r.levels.find(e=>e.id===t.value);return((null==n?void 0:n.height)||0)-((null==i?void 0:i.height)||0)});m.push({html:l,value:"auto",default:!r.currentLevel});const p=i=>d(null,null,function*(){return yield t.switchM3u8Quality(i.value),e.notice.show=`${c}: ${i.html}`,yield u(),i.html});a.control&&e.controls.update({name:"mediabunny-quality",position:"right",html:f,style:{padding:"0 10px"},selector:m,onSelect:p}),a.setting&&e.setting.update({name:"mediabunny-quality",tooltip:f,html:c,icon:'',width:200,selector:m,onSelect:p})})}function c(r){return d(this,null,function*(){var n;const s=(null==(n=i.m3u8)?void 0:n.audio)||{};if(!o(s)||!(null==r?void 0:r.audios.length)||r.audios.length<2)return void a();const l=s.auto||"Auto",c=s.title||"Audio",h=s.getName||(e=>e.name||e.lang||e.language),f=r.currentAudio?h(r.currentAudio):l,m=g(r.audios.map(e=>{var t;return{html:h(e),value:e.id,default:(null==(t=r.currentAudio)?void 0:t.id)===e.id}}),"html");m.push({html:l,value:"auto",default:!r.currentAudio});const p=i=>d(null,null,function*(){return yield t.switchM3u8Audio(i.value),e.notice.show=`${c}: ${i.html}`,yield u(),i.html});s.control&&e.controls.update({name:"mediabunny-audio",position:"right",html:f,style:{padding:"0 10px"},selector:m,onSelect:p}),s.setting&&e.setting.update({name:"mediabunny-audio",tooltip:f,html:c,icon:'',width:200,selector:m,onSelect:p})})}function u(){return d(this,null,function*(){const e=yield t.getM3u8State();if(!e)return s(),void a();yield Promise.all([l(e),c(e)])})}}({art:t,shim:a,option:e}),t.on("destroy",()=>{delete t.mediabunny,a.destroy()}),n}}}); diff --git a/packages/artplayer-proxy-mediabunny/dist/artplayer-proxy-mediabunny.mjs b/packages/artplayer-proxy-mediabunny/dist/artplayer-proxy-mediabunny.mjs index 2cb05293a..182167ee4 100644 --- a/packages/artplayer-proxy-mediabunny/dist/artplayer-proxy-mediabunny.mjs +++ b/packages/artplayer-proxy-mediabunny/dist/artplayer-proxy-mediabunny.mjs @@ -221,6 +221,13 @@ const readExpGolomb = (bitstream) => { const result = (1 << leadingZeroBits) - 1 + bitstream.readBits(leadingZeroBits); return result; }; +const writeExpGolomb = (bitstream, value) => { + const codeNum = value + 1; + const leadingZeroBits = Math.floor(Math.log2(codeNum)); + bitstream.writeBits(leadingZeroBits, 0); + bitstream.writeBits(1, 1); + bitstream.writeBits(leadingZeroBits, codeNum - 2 ** leadingZeroBits); +}; const readSignedExpGolomb = (bitstream) => { const codeNum = readExpGolomb(bitstream); return (codeNum & 1) === 0 ? -(codeNum >> 1) : codeNum + 1 >> 1; @@ -288,6 +295,15 @@ const MATRIX_COEFFICIENTS_MAP = { // ITU-R BT.2020-2 (non-constant luminance) }; const MATRIX_COEFFICIENTS_MAP_INVERSE = /* @__PURE__ */ invertObject(MATRIX_COEFFICIENTS_MAP); +const colorSpaceIsComplete = (colorSpace) => { + return !!colorSpace && !!colorSpace.primaries && !!colorSpace.transfer && !!colorSpace.matrix && colorSpace.fullRange !== void 0; +}; +const EMPTY_COLOR_SPACE = { + primaries: void 0, + transfer: void 0, + matrix: void 0, + fullRange: void 0 +}; const isAllowSharedBufferSource = (x) => { return x instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && x instanceof SharedArrayBuffer || ArrayBuffer.isView(x); }; @@ -492,6 +508,14 @@ const ilog = (x) => { } return ret; }; +const popcount = (value) => { + let count = 0; + while (value !== 0) { + value &= value - 1; + count++; + } + return count; +}; const ISO_639_2_REGEX = /^[a-z]{3}$/; const isIso639Dash2LanguageCode = (x) => { return ISO_639_2_REGEX.test(x); @@ -545,7 +569,7 @@ const retriedFetch = async (fetchFn, url, requestInit, getRetryDelay, shouldStop if (retryDelayInSeconds === null) { throw error; } - console.error("Retrying failed fetch. Error:", error); + Logging._error("Retrying failed fetch. Error:", error); if (!Number.isFinite(retryDelayInSeconds) || retryDelayInSeconds < 0) { throw new TypeError("Retry delay must be a non-negative finite number."); } @@ -588,19 +612,19 @@ const isChromium = () => { } return isChromiumCache = !!(typeof navigator !== "undefined" && (navigator.vendor?.includes("Google Inc") || /Chrome/.test(navigator.userAgent))); }; -let chromiumVersionCache = null; -const getChromiumVersion = () => { - if (chromiumVersionCache !== null) { - return chromiumVersionCache; +const missingWebCodecsClassMessage = (className) => { + if (typeof globalThis.isSecureContext !== "undefined" && !globalThis.isSecureContext) { + return `${className} 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.`; } - if (typeof navigator === "undefined") { - return null; + return `${className} is not available in this environment.`; +}; +const NativePromiseConstructor = (async () => { +})().constructor; +const isThenable = (value) => { + if (value instanceof NativePromiseConstructor || value instanceof Promise) { + return true; } - const match = /\bChrome\/(\d+)/.exec(navigator.userAgent); - if (!match) { - return null; - } - return chromiumVersionCache = Number(match[1]); + return typeof value?.then === "function"; }; const coalesceIndex = (a, b) => { return a !== -1 ? a : b; @@ -746,7 +770,7 @@ class EventEmitter { constructor() { this._listeners = /* @__PURE__ */ new Map(); } - /** Registers a listener for the given event. */ + /** Registers a listener for the given event. Returns a function that, when called, removes the listener again. */ on(event, listener, options) { if (!this._listeners.has(event)) { this._listeners.set(event, /* @__PURE__ */ new Set()); @@ -776,6 +800,58 @@ class EventEmitter { } } } +var LogLevel; +(function(LogLevel2) { + LogLevel2[LogLevel2["Silent"] = 0] = "Silent"; + LogLevel2[LogLevel2["Errors"] = 1] = "Errors"; + LogLevel2[LogLevel2["Warnings"] = 2] = "Warnings"; + LogLevel2[LogLevel2["Info"] = 3] = "Info"; +})(LogLevel || (LogLevel = {})); +class Logging { + constructor() { + } + /** The current log level. Defaults to {@link LogLevel.Info}. */ + static get level() { + return Logging._level; + } + static set level(value) { + if (value !== LogLevel.Silent && value !== LogLevel.Errors && value !== LogLevel.Warnings && value !== LogLevel.Info) { + throw new TypeError("Invalid log level. Use one of the values of the LogLevel enum."); + } + Logging._level = value; + } + /** @internal */ + static get _emitter() { + return Logging._emitterInstance ?? (Logging._emitterInstance = new EventEmitter()); + } + /** Registers a listener for a log event. Returns a function that, when called, removes the listener again. */ + static on(event, listener, options) { + return Logging._emitter.on(event, listener, options); + } + /** @internal */ + static _error(...args) { + Logging._emitter._emit("error", args); + if (Logging._level >= LogLevel.Errors) { + console.error(...args); + } + } + /** @internal */ + static _warn(...args) { + Logging._emitter._emit("warn", args); + if (Logging._level >= LogLevel.Warnings) { + console.warn(...args); + } + } + /** @internal */ + static _info(...args) { + Logging._emitter._emit("info", args); + if (Logging._level >= LogLevel.Info) { + console.info(...args); + } + } +} +Logging._level = LogLevel.Info; +Logging._emitterInstance = null; class RichImageData { /** Creates a new {@link RichImageData}. */ constructor(data, mimeType) { @@ -858,6 +934,16 @@ class Bitstream { } this.pos = end; } + copyBits(n, other) { + let i = 0; + for (i; i < n - 7; i += 8) { + this.writeBits(8, other.readBits(8)); + } + const leftover = n - i; + if (leftover > 0) { + this.writeBits(leftover, other.readBits(leftover)); + } + } readAlignedByte() { if (this.pos % 8 !== 0) { throw new Error("Bitstream is not byte-aligned."); @@ -900,623 +986,68 @@ const parseAacAudioSpecificConfig = (bytes) => { throw new TypeError("AAC description must be at least 2 bytes long."); } const bitstream = new Bitstream(bytes); - let objectType = bitstream.readBits(5); - if (objectType === 31) { - objectType = 32 + bitstream.readBits(6); - } - const frequencyIndex = bitstream.readBits(4); - let sampleRate = null; - if (frequencyIndex === 15) { - sampleRate = bitstream.readBits(24); - } else { - if (frequencyIndex < aacFrequencyTable.length) { - sampleRate = aacFrequencyTable[frequencyIndex]; - } - } + const objectType = readAacObjectType(bitstream); + const { frequencyIndex, sampleRate } = readAacSamplingFrequency(bitstream); const channelConfiguration = bitstream.readBits(4); let numberOfChannels = null; if (channelConfiguration >= 1 && channelConfiguration <= 7) { numberOfChannels = aacChannelMap[channelConfiguration]; } + let coreObjectType = objectType; + let psPresent = false; + let outputSampleRate = sampleRate; + if (objectType === 5 || objectType === 29) { + psPresent = objectType === 29; + outputSampleRate = readAacSamplingFrequency(bitstream).sampleRate; + coreObjectType = readAacObjectType(bitstream); + if (coreObjectType === 22) { + bitstream.skipBits(4); + } + } else { + while (bitstream.getBitsLeft() > 15) { + const searchStart = bitstream.pos; + if (bitstream.readBits(11) !== 695) { + bitstream.pos = searchStart + 1; + continue; + } + if (readAacObjectType(bitstream) === 5 && bitstream.readBits(1)) { + outputSampleRate = readAacSamplingFrequency(bitstream).sampleRate; + if (bitstream.getBitsLeft() > 11 && bitstream.readBits(11) === 1352) { + psPresent = !!bitstream.readBits(1); + } + } + break; + } + } + if (numberOfChannels !== null && numberOfChannels > 1) { + psPresent = false; + } return { objectType, + coreObjectType, frequencyIndex, - sampleRate, channelConfiguration, - numberOfChannels + outputSampleRate, + outputNumberOfChannels: psPresent && numberOfChannels === 1 ? 2 : numberOfChannels }; }; -const VIDEO_CODECS = [ - "avc", - "hevc", - "vp9", - "av1", - "vp8" -]; -const PCM_AUDIO_CODECS = [ - "pcm-s16", - // We don't prefix 'le' so we're compatible with the WebCodecs-registered PCM codec strings - "pcm-s16be", - "pcm-s24", - "pcm-s24be", - "pcm-s32", - "pcm-s32be", - "pcm-f32", - "pcm-f32be", - "pcm-f64", - "pcm-f64be", - "pcm-u8", - "pcm-s8", - "ulaw", - "alaw" -]; -const NON_PCM_AUDIO_CODECS = [ - "aac", - "opus", - "mp3", - "vorbis", - "flac", - "ac3", - "eac3" -]; -const AUDIO_CODECS = [ - ...NON_PCM_AUDIO_CODECS, - ...PCM_AUDIO_CODECS -]; -const AVC_LEVEL_TABLE = [ - { maxMacroblocks: 99, maxBitrate: 64e3, maxDpbMbs: 396, level: 10 }, - // Level 1 - { maxMacroblocks: 396, maxBitrate: 192e3, maxDpbMbs: 900, level: 11 }, - // Level 1.1 - { maxMacroblocks: 396, maxBitrate: 384e3, maxDpbMbs: 2376, level: 12 }, - // Level 1.2 - { maxMacroblocks: 396, maxBitrate: 768e3, maxDpbMbs: 2376, level: 13 }, - // Level 1.3 - { maxMacroblocks: 396, maxBitrate: 2e6, maxDpbMbs: 2376, level: 20 }, - // Level 2 - { maxMacroblocks: 792, maxBitrate: 4e6, maxDpbMbs: 4752, level: 21 }, - // Level 2.1 - { maxMacroblocks: 1620, maxBitrate: 4e6, maxDpbMbs: 8100, level: 22 }, - // Level 2.2 - { maxMacroblocks: 1620, maxBitrate: 1e7, maxDpbMbs: 8100, level: 30 }, - // Level 3 - { maxMacroblocks: 3600, maxBitrate: 14e6, maxDpbMbs: 18e3, level: 31 }, - // Level 3.1 - { maxMacroblocks: 5120, maxBitrate: 2e7, maxDpbMbs: 20480, level: 32 }, - // Level 3.2 - { maxMacroblocks: 8192, maxBitrate: 2e7, maxDpbMbs: 32768, level: 40 }, - // Level 4 - { maxMacroblocks: 8192, maxBitrate: 5e7, maxDpbMbs: 32768, level: 41 }, - // Level 4.1 - { maxMacroblocks: 8704, maxBitrate: 5e7, maxDpbMbs: 34816, level: 42 }, - // Level 4.2 - { maxMacroblocks: 22080, maxBitrate: 135e6, maxDpbMbs: 110400, level: 50 }, - // Level 5 - { maxMacroblocks: 36864, maxBitrate: 24e7, maxDpbMbs: 184320, level: 51 }, - // Level 5.1 - { maxMacroblocks: 36864, maxBitrate: 24e7, maxDpbMbs: 184320, level: 52 }, - // Level 5.2 - { maxMacroblocks: 139264, maxBitrate: 24e7, maxDpbMbs: 696320, level: 60 }, - // Level 6 - { maxMacroblocks: 139264, maxBitrate: 48e7, maxDpbMbs: 696320, level: 61 }, - // Level 6.1 - { maxMacroblocks: 139264, maxBitrate: 8e8, maxDpbMbs: 696320, level: 62 } - // Level 6.2 -]; -const VP9_LEVEL_TABLE = [ - { maxPictureSize: 36864, maxBitrate: 2e5, level: 10 }, - // Level 1 - { maxPictureSize: 73728, maxBitrate: 8e5, level: 11 }, - // Level 1.1 - { maxPictureSize: 122880, maxBitrate: 18e5, level: 20 }, - // Level 2 - { maxPictureSize: 245760, maxBitrate: 36e5, level: 21 }, - // Level 2.1 - { maxPictureSize: 552960, maxBitrate: 72e5, level: 30 }, - // Level 3 - { maxPictureSize: 983040, maxBitrate: 12e6, level: 31 }, - // Level 3.1 - { maxPictureSize: 2228224, maxBitrate: 18e6, level: 40 }, - // Level 4 - { maxPictureSize: 2228224, maxBitrate: 3e7, level: 41 }, - // Level 4.1 - { maxPictureSize: 8912896, maxBitrate: 6e7, level: 50 }, - // Level 5 - { maxPictureSize: 8912896, maxBitrate: 12e7, level: 51 }, - // Level 5.1 - { maxPictureSize: 8912896, maxBitrate: 18e7, level: 52 }, - // Level 5.2 - { maxPictureSize: 35651584, maxBitrate: 18e7, level: 60 }, - // Level 6 - { maxPictureSize: 35651584, maxBitrate: 24e7, level: 61 }, - // Level 6.1 - { maxPictureSize: 35651584, maxBitrate: 48e7, level: 62 } - // Level 6.2 -]; -const VP9_DEFAULT_SUFFIX = ".01.01.01.01.00"; -const AV1_DEFAULT_SUFFIX = ".0.110.01.01.01.0"; -const extractVideoCodecString = (trackInfo) => { - const { codec, codecDescription, colorSpace, avcCodecInfo, hevcCodecInfo, vp9CodecInfo, av1CodecInfo } = trackInfo; - if (codec === "avc") { - assert(trackInfo.avcType !== null); - if (avcCodecInfo) { - const bytes = new Uint8Array([ - avcCodecInfo.avcProfileIndication, - avcCodecInfo.profileCompatibility, - avcCodecInfo.avcLevelIndication - ]); - return `avc${trackInfo.avcType}.${bytesToHexString(bytes)}`; - } - if (!codecDescription || codecDescription.byteLength < 4) { - throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long."); - } - return `avc${trackInfo.avcType}.${bytesToHexString(codecDescription.subarray(1, 4))}`; - } else if (codec === "hevc") { - let generalProfileSpace; - let generalProfileIdc; - let compatibilityFlags; - let generalTierFlag; - let generalLevelIdc; - let constraintFlags; - if (hevcCodecInfo) { - generalProfileSpace = hevcCodecInfo.generalProfileSpace; - generalProfileIdc = hevcCodecInfo.generalProfileIdc; - compatibilityFlags = reverseBitsU32(hevcCodecInfo.generalProfileCompatibilityFlags); - generalTierFlag = hevcCodecInfo.generalTierFlag; - generalLevelIdc = hevcCodecInfo.generalLevelIdc; - constraintFlags = [...hevcCodecInfo.generalConstraintIndicatorFlags]; - } else { - if (!codecDescription || codecDescription.byteLength < 23) { - throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long."); - } - const view = toDataView(codecDescription); - const profileByte = view.getUint8(1); - generalProfileSpace = profileByte >> 6 & 3; - generalProfileIdc = profileByte & 31; - compatibilityFlags = reverseBitsU32(view.getUint32(2)); - generalTierFlag = profileByte >> 5 & 1; - generalLevelIdc = view.getUint8(12); - constraintFlags = []; - for (let i = 0; i < 6; i++) { - constraintFlags.push(view.getUint8(6 + i)); - } - } - let codecString = "hev1."; - codecString += ["", "A", "B", "C"][generalProfileSpace] + generalProfileIdc; - codecString += "."; - codecString += compatibilityFlags.toString(16).toUpperCase(); - codecString += "."; - codecString += generalTierFlag === 0 ? "L" : "H"; - codecString += generalLevelIdc; - while (constraintFlags.length > 0 && constraintFlags[constraintFlags.length - 1] === 0) { - constraintFlags.pop(); - } - if (constraintFlags.length > 0) { - codecString += "."; - codecString += constraintFlags.map((x) => x.toString(16).toUpperCase()).join("."); - } - return codecString; - } else if (codec === "vp8") { - return "vp8"; - } else if (codec === "vp9") { - if (!vp9CodecInfo) { - const pictureSize = trackInfo.width * trackInfo.height; - let level2 = last(VP9_LEVEL_TABLE).level; - for (const entry of VP9_LEVEL_TABLE) { - if (pictureSize <= entry.maxPictureSize) { - level2 = entry.level; - break; - } - } - return `vp09.00.${level2.toString().padStart(2, "0")}.08`; - } - const profile = vp9CodecInfo.profile.toString().padStart(2, "0"); - const level = vp9CodecInfo.level.toString().padStart(2, "0"); - const bitDepth = vp9CodecInfo.bitDepth.toString().padStart(2, "0"); - const chromaSubsampling = vp9CodecInfo.chromaSubsampling.toString().padStart(2, "0"); - const colourPrimaries = vp9CodecInfo.colourPrimaries.toString().padStart(2, "0"); - const transferCharacteristics = vp9CodecInfo.transferCharacteristics.toString().padStart(2, "0"); - const matrixCoefficients = vp9CodecInfo.matrixCoefficients.toString().padStart(2, "0"); - const videoFullRangeFlag = vp9CodecInfo.videoFullRangeFlag.toString().padStart(2, "0"); - let string = `vp09.${profile}.${level}.${bitDepth}.${chromaSubsampling}`; - string += `.${colourPrimaries}.${transferCharacteristics}.${matrixCoefficients}.${videoFullRangeFlag}`; - if (string.endsWith(VP9_DEFAULT_SUFFIX)) { - string = string.slice(0, -VP9_DEFAULT_SUFFIX.length); - } - return string; - } else if (codec === "av1") { - if (!av1CodecInfo) { - const pictureSize = trackInfo.width * trackInfo.height; - let level2 = last(VP9_LEVEL_TABLE).level; - for (const entry of VP9_LEVEL_TABLE) { - if (pictureSize <= entry.maxPictureSize) { - level2 = entry.level; - break; - } - } - return `av01.0.${level2.toString().padStart(2, "0")}M.08`; - } - const profile = av1CodecInfo.profile; - const level = av1CodecInfo.level.toString().padStart(2, "0"); - const tier = av1CodecInfo.tier ? "H" : "M"; - const bitDepth = av1CodecInfo.bitDepth.toString().padStart(2, "0"); - const monochrome = av1CodecInfo.monochrome ? "1" : "0"; - const chromaSubsampling = 100 * av1CodecInfo.chromaSubsamplingX + 10 * av1CodecInfo.chromaSubsamplingY + 1 * (av1CodecInfo.chromaSubsamplingX && av1CodecInfo.chromaSubsamplingY ? av1CodecInfo.chromaSamplePosition : 0); - const colorPrimaries = colorSpace?.primaries ? COLOR_PRIMARIES_MAP[colorSpace.primaries] : 1; - const transferCharacteristics = colorSpace?.transfer ? TRANSFER_CHARACTERISTICS_MAP[colorSpace.transfer] : 1; - const matrixCoefficients = colorSpace?.matrix ? MATRIX_COEFFICIENTS_MAP[colorSpace.matrix] : 1; - const videoFullRangeFlag = colorSpace?.fullRange ? 1 : 0; - let string = `av01.${profile}.${level}${tier}.${bitDepth}`; - string += `.${monochrome}.${chromaSubsampling.toString().padStart(3, "0")}`; - string += `.${colorPrimaries.toString().padStart(2, "0")}`; - string += `.${transferCharacteristics.toString().padStart(2, "0")}`; - string += `.${matrixCoefficients.toString().padStart(2, "0")}`; - string += `.${videoFullRangeFlag}`; - if (string.endsWith(AV1_DEFAULT_SUFFIX)) { - string = string.slice(0, -AV1_DEFAULT_SUFFIX.length); - } - return string; - } - throw new TypeError(`Unhandled codec '${codec}'.`); +const readAacObjectType = (bitstream) => { + const objectType = bitstream.readBits(5); + return objectType === 31 ? 32 + bitstream.readBits(6) : objectType; }; -const extractAudioCodecString = (trackInfo) => { - const { codec, codecDescription, aacCodecInfo } = trackInfo; - if (codec === "aac") { - if (!aacCodecInfo) { - throw new TypeError("AAC codec info must be provided."); - } - if (aacCodecInfo.isMpeg2) { - return "mp4a.67"; - } else { - let objectType; - if (aacCodecInfo.objectType !== null) { - objectType = aacCodecInfo.objectType; - } else { - const audioSpecificConfig = parseAacAudioSpecificConfig(codecDescription); - objectType = audioSpecificConfig.objectType; - } - return `mp4a.40.${objectType}`; - } - } else if (codec === "mp3") { - return "mp3"; - } else if (codec === "opus") { - return "opus"; - } else if (codec === "vorbis") { - return "vorbis"; - } else if (codec === "flac") { - return "flac"; - } else if (codec === "ac3") { - return "ac-3"; - } else if (codec === "eac3") { - return "ec-3"; - } else if (codec && PCM_AUDIO_CODECS.includes(codec)) { - return codec; - } - throw new TypeError(`Unhandled codec '${codec}'.`); -}; -const OPUS_SAMPLE_RATE = 48e3; -const PCM_CODEC_REGEX = /^pcm-([usf])(\d+)+(be)?$/; -const parsePcmCodec = (codec) => { - assert(PCM_AUDIO_CODECS.includes(codec)); - if (codec === "ulaw") { - return { dataType: "ulaw", sampleSize: 1, littleEndian: true, silentValue: 255 }; - } else if (codec === "alaw") { - return { dataType: "alaw", sampleSize: 1, littleEndian: true, silentValue: 213 }; - } - const match = PCM_CODEC_REGEX.exec(codec); - assert(match); - let dataType; - if (match[1] === "u") { - dataType = "unsigned"; - } else if (match[1] === "s") { - dataType = "signed"; - } else { - dataType = "float"; - } - const sampleSize = Number(match[2]) / 8; - const littleEndian = match[3] !== "be"; - const silentValue = codec === "pcm-u8" ? 2 ** 7 : 0; - return { dataType, sampleSize, littleEndian, silentValue }; -}; -const inferCodecFromCodecString = (codecString) => { - if (codecString.startsWith("avc1") || codecString.startsWith("avc3")) { - return "avc"; - } else if (codecString.startsWith("hev1") || codecString.startsWith("hvc1")) { - return "hevc"; - } else if (codecString === "vp8") { - return "vp8"; - } else if (codecString.startsWith("vp09")) { - return "vp9"; - } else if (codecString.startsWith("av01")) { - return "av1"; - } - if (codecString === "mp3" || codecString === "mp4a.69" || codecString === "mp4a.6B" || codecString === "mp4a.6b" || codecString === "mp4a.40.34") { - return "mp3"; - } else if (codecString.startsWith("mp4a.40.") || codecString === "mp4a.67") { - return "aac"; - } else if (codecString === "opus") { - return "opus"; - } else if (codecString === "vorbis") { - return "vorbis"; - } else if (codecString === "flac") { - return "flac"; - } else if (codecString === "ac-3" || codecString === "ac3") { - return "ac3"; - } else if (codecString === "ec-3" || codecString === "eac3") { - return "eac3"; - } else if (codecString === "ulaw") { - return "ulaw"; - } else if (codecString === "alaw") { - return "alaw"; - } else if (PCM_CODEC_REGEX.test(codecString)) { - return codecString; - } - if (codecString === "webvtt") { - return "webvtt"; - } - return null; -}; -const FRAME_HEADER_SIZE = 4; -const SAMPLING_RATES = [44100, 48e3, 32e3]; -const KILOBIT_RATES = [ - // lowSamplingFrequency === 0 - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - // layer = 0 - -1, - 32, - 40, - 48, - 56, - 64, - 80, - 96, - 112, - 128, - 160, - 192, - 224, - 256, - 320, - -1, - // layer 1 - -1, - 32, - 48, - 56, - 64, - 80, - 96, - 112, - 128, - 160, - 192, - 224, - 256, - 320, - 384, - -1, - // layer = 2 - -1, - 32, - 64, - 96, - 128, - 160, - 192, - 224, - 256, - 288, - 320, - 352, - 384, - 416, - 448, - -1, - // layer = 3 - // lowSamplingFrequency === 1 - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - // layer = 0 - -1, - 8, - 16, - 24, - 32, - 40, - 48, - 56, - 64, - 80, - 96, - 112, - 128, - 144, - 160, - -1, - // layer = 1 - -1, - 8, - 16, - 24, - 32, - 40, - 48, - 56, - 64, - 80, - 96, - 112, - 128, - 144, - 160, - -1, - // layer = 2 - -1, - 32, - 48, - 56, - 64, - 80, - 96, - 112, - 128, - 144, - 160, - 176, - 192, - 224, - 256, - -1 - // layer = 3 -]; -const XING = 1483304551; -const INFO = 1231971951; -const computeMp3FrameSize = (lowSamplingFrequency, layer, bitrate, sampleRate, padding) => { - if (layer === 0) { - return 0; - } else if (layer === 1) { - return Math.floor(144 * bitrate / (sampleRate << lowSamplingFrequency)) + padding; - } else if (layer === 2) { - return Math.floor(144 * bitrate / sampleRate) + padding; - } else { - return (Math.floor(12 * bitrate / sampleRate) + padding) * 4; - } -}; -const computeAverageMp3FrameSize = (lowSamplingFrequency, layer, bitrate, sampleRate) => { - if (layer === 0) { - return 0; - } else if (layer === 1) { - return 144 * bitrate / (sampleRate << lowSamplingFrequency); - } else if (layer === 2) { - return 144 * bitrate / sampleRate; - } else { - return 12 * bitrate / sampleRate * 4; - } -}; -const getXingOffset = (mpegVersionId, channel) => { - return mpegVersionId === 3 ? channel === 3 ? 21 : 36 : channel === 3 ? 13 : 21; -}; -const readMp3FrameHeader = (word, remainingBytes) => { - const firstByte = word >>> 24; - const secondByte = word >>> 16 & 255; - const thirdByte = word >>> 8 & 255; - const fourthByte = word & 255; - if (firstByte !== 255 && secondByte !== 255 && thirdByte !== 255 && fourthByte !== 255) { +const readAacSamplingFrequency = (bitstream) => { + const frequencyIndex = bitstream.readBits(4); + if (frequencyIndex === 15) { return { - header: null, - bytesAdvanced: 4 + frequencyIndex, + sampleRate: bitstream.readBits(24) }; } - if (firstByte !== 255) { - return { header: null, bytesAdvanced: 1 }; - } - if ((secondByte & 224) !== 224) { - return { header: null, bytesAdvanced: 1 }; - } - let lowSamplingFrequency = 0; - let mpeg25 = 0; - if (secondByte & 1 << 4) { - lowSamplingFrequency = secondByte & 1 << 3 ? 0 : 1; - } else { - lowSamplingFrequency = 1; - mpeg25 = 1; - } - const mpegVersionId = secondByte >> 3 & 3; - const layer = secondByte >> 1 & 3; - const bitrateIndex = thirdByte >> 4 & 15; - const frequencyIndex = (thirdByte >> 2 & 3) % 3; - const padding = thirdByte >> 1 & 1; - const channel = fourthByte >> 6 & 3; - const modeExtension = fourthByte >> 4 & 3; - const copyright = fourthByte >> 3 & 1; - const original = fourthByte >> 2 & 1; - const emphasis = fourthByte & 3; - const kilobitRate = KILOBIT_RATES[lowSamplingFrequency * 16 * 4 + layer * 16 + bitrateIndex]; - if (kilobitRate === -1) { - return { header: null, bytesAdvanced: 1 }; - } - const bitrate = kilobitRate * 1e3; - const sampleRate = SAMPLING_RATES[frequencyIndex] >> lowSamplingFrequency + mpeg25; - const frameLength = computeMp3FrameSize(lowSamplingFrequency, layer, bitrate, sampleRate, padding); - if (remainingBytes !== null && remainingBytes < frameLength) { - return { header: null, bytesAdvanced: 1 }; - } - let audioSamplesInFrame; - if (mpegVersionId === 3) { - audioSamplesInFrame = layer === 3 ? 384 : 1152; - } else { - if (layer === 3) { - audioSamplesInFrame = 384; - } else if (layer === 2) { - audioSamplesInFrame = 1152; - } else { - audioSamplesInFrame = 576; - } - } return { - header: { - totalSize: frameLength, - mpegVersionId, - lowSamplingFrequency, - layer, - bitrate, - frequencyIndex, - sampleRate, - channel, - modeExtension, - copyright, - original, - emphasis, - audioSamplesInFrame - }, - bytesAdvanced: 1 + frequencyIndex, + sampleRate: frequencyIndex < aacFrequencyTable.length ? aacFrequencyTable[frequencyIndex] : null }; }; -const decodeSynchsafe = (synchsafed) => { - let mask = 2130706432; - let unsynchsafed = 0; - while (mask !== 0) { - unsynchsafed >>= 1; - unsynchsafed |= synchsafed & mask; - mask >>= 8; - } - return unsynchsafed; -}; -var XingFlags; -(function(XingFlags2) { - XingFlags2[XingFlags2["FrameCount"] = 1] = "FrameCount"; - XingFlags2[XingFlags2["FileSize"] = 2] = "FileSize"; - XingFlags2[XingFlags2["Toc"] = 4] = "Toc"; -})(XingFlags || (XingFlags = {})); const AC3_SAMPLE_RATES = [48e3, 44100, 32e3]; const EAC3_REDUCED_SAMPLE_RATES = [24e3, 22050, 16e3]; var AvcNalUnitType; @@ -1629,6 +1160,19 @@ const removeEmulationPreventionBytes = (data) => { } return new Uint8Array(result); }; +const addEmulationPreventionBytes = (data) => { + const result = []; + let zeroCount = 0; + for (const byte of data) { + if (zeroCount === 2 && byte <= 3) { + result.push(3); + zeroCount = 0; + } + result.push(byte); + zeroCount = byte === 0 ? zeroCount + 1 : 0; + } + return new Uint8Array(result); +}; const ANNEX_B_START_CODE = new Uint8Array([0, 0, 0, 1]); const concatNalUnitsInAnnexB = (nalUnits) => { const totalLength = nalUnits.reduce((a, b) => a + ANNEX_B_START_CODE.byteLength + b.byteLength, 0); @@ -1719,10 +1263,54 @@ const extractAvcDecoderConfigurationRecord = (packetData) => { sequenceParameterSetExt: hasExtendedData ? spsExtUnits : null }; } catch (error) { - console.error("Error building AVC Decoder Configuration Record:", error); + Logging._error("Error building AVC Decoder Configuration Record:", error); return null; } }; +const serializeAvcDecoderConfigurationRecord = (record) => { + const bytes = []; + bytes.push(record.configurationVersion); + bytes.push(record.avcProfileIndication); + bytes.push(record.profileCompatibility); + bytes.push(record.avcLevelIndication); + bytes.push(252 | record.lengthSizeMinusOne & 3); + bytes.push(224 | record.sequenceParameterSets.length & 31); + for (const sps of record.sequenceParameterSets) { + const length = sps.byteLength; + bytes.push(length >> 8); + bytes.push(length & 255); + for (let i = 0; i < length; i++) { + bytes.push(sps[i]); + } + } + bytes.push(record.pictureParameterSets.length); + for (const pps of record.pictureParameterSets) { + const length = pps.byteLength; + bytes.push(length >> 8); + bytes.push(length & 255); + for (let i = 0; i < length; i++) { + bytes.push(pps[i]); + } + } + if ((record.avcProfileIndication === 100 || record.avcProfileIndication === 110 || record.avcProfileIndication === 122 || record.avcProfileIndication === 144) && record.chromaFormat !== null) { + assert(record.bitDepthLumaMinus8 !== null); + assert(record.bitDepthChromaMinus8 !== null); + assert(record.sequenceParameterSetExt !== null); + bytes.push(252 | record.chromaFormat & 3); + bytes.push(248 | record.bitDepthLumaMinus8 & 7); + bytes.push(248 | record.bitDepthChromaMinus8 & 7); + bytes.push(record.sequenceParameterSetExt.length); + for (const spsExt of record.sequenceParameterSetExt) { + const length = spsExt.byteLength; + bytes.push(length >> 8); + bytes.push(length & 255); + for (let i = 0; i < length; i++) { + bytes.push(spsExt[i]); + } + } + } + return new Uint8Array(bytes); +}; const deserializeAvcDecoderConfigurationRecord = (data) => { try { const view = toDataView(data); @@ -1780,7 +1368,7 @@ const deserializeAvcDecoderConfigurationRecord = (data) => { } return record; } catch (error) { - console.error("Error deserializing AVC Decoder Configuration Record:", error); + Logging._error("Error deserializing AVC Decoder Configuration Record:", error); return null; } }; @@ -1804,7 +1392,8 @@ const AVC_HEVC_ASPECT_RATIO_IDC_TABLE = { }; const parseAvcSps = (sps) => { try { - const bitstream = new Bitstream(removeEmulationPreventionBytes(sps)); + const emulationUnpreventedBytes = removeEmulationPreventionBytes(sps); + const bitstream = new Bitstream(emulationUnpreventedBytes); bitstream.skipBits(1); bitstream.skipBits(2); const nalUnitType = bitstream.readBits(5); @@ -1900,6 +1489,9 @@ const parseAvcSps = (sps) => { let pixelAspectRatio = { num: 1, den: 1 }; let numReorderFrames = null; let maxDecFrameBuffering = null; + let bitstreamRestrictionFlagBitOffset = null; + let bitstreamRestrictionFlag = null; + const vuiParametersFlagBitOffset = bitstream.pos; const vuiParametersPresentFlag = bitstream.readBits(1); if (vuiParametersPresentFlag) { const aspectRatioInfoPresentFlag = bitstream.readBits(1); @@ -1955,7 +1547,8 @@ const parseAvcSps = (sps) => { bitstream.skipBits(1); } bitstream.skipBits(1); - const bitstreamRestrictionFlag = bitstream.readBits(1); + bitstreamRestrictionFlagBitOffset = bitstream.pos; + bitstreamRestrictionFlag = bitstream.readBits(1); if (bitstreamRestrictionFlag) { bitstream.skipBits(1); readExpGolomb(bitstream); @@ -1984,6 +1577,7 @@ const parseAvcSps = (sps) => { } assert(maxDecFrameBuffering !== null); return { + emulationUnpreventedBytes, profileIdc, constraintFlags, levelIdc, @@ -2001,10 +1595,13 @@ const parseAvcSps = (sps) => { transferCharacteristics, fullRangeFlag, numReorderFrames, - maxDecFrameBuffering + maxDecFrameBuffering, + vuiParametersFlagBitOffset, + bitstreamRestrictionFlagBitOffset, + bitstreamRestrictionFlag }; } catch (error) { - console.error("Error parsing AVC SPS:", error); + Logging._error("Error parsing AVC SPS:", error); return null; } }; @@ -2022,6 +1619,40 @@ const skipAvcHrdParameters = (bitstream) => { bitstream.skipBits(5); bitstream.skipBits(5); }; +const addAvcBitstreamRestriction = (sps) => { + assert(sps.bitstreamRestrictionFlag !== 1); + const modifiedBytes = new Uint8Array(sps.emulationUnpreventedBytes.byteLength + 64); + const oldBitstream = new Bitstream(sps.emulationUnpreventedBytes); + const newBitstream = new Bitstream(modifiedBytes); + if (sps.bitstreamRestrictionFlag === null) { + newBitstream.copyBits(sps.vuiParametersFlagBitOffset, oldBitstream); + newBitstream.writeBits(1, 1); + newBitstream.writeBits(1, 0); + newBitstream.writeBits(1, 0); + newBitstream.writeBits(1, 0); + newBitstream.writeBits(1, 0); + newBitstream.writeBits(1, 0); + newBitstream.writeBits(1, 0); + newBitstream.writeBits(1, 0); + newBitstream.writeBits(1, 0); + } else { + assert(sps.bitstreamRestrictionFlagBitOffset !== null); + newBitstream.copyBits(sps.bitstreamRestrictionFlagBitOffset, oldBitstream); + } + newBitstream.writeBits(1, 1); + newBitstream.writeBits(1, 1); + writeExpGolomb(newBitstream, 2); + writeExpGolomb(newBitstream, 1); + writeExpGolomb(newBitstream, 16); + writeExpGolomb(newBitstream, 16); + writeExpGolomb(newBitstream, sps.numReorderFrames); + writeExpGolomb(newBitstream, sps.maxDecFrameBuffering); + newBitstream.writeBits(1, 1); + newBitstream.writeBits((8 - newBitstream.pos % 8) % 8, 0); + const byteLength = newBitstream.pos / 8; + assert(Number.isInteger(byteLength)); + return addEmulationPreventionBytes(modifiedBytes.subarray(0, byteLength)); +}; const concatHevcNalUnits = (nalUnits, decoderConfig) => { if (decoderConfig.description) { const bytes = toUint8Array(decoderConfig.description); @@ -2161,7 +1792,7 @@ const parseHevcSps = (sps) => { minSpatialSegmentationIdc }; } catch (error) { - console.error("Error parsing HEVC SPS:", error); + Logging._error("Error parsing HEVC SPS:", error); return null; } }; @@ -2278,7 +1909,7 @@ const extractHevcDecoderConfigurationRecord = (packetData) => { }; return record; } catch (error) { - console.error("Error building HEVC Decoder Configuration Record:", error); + Logging._error("Error building HEVC Decoder Configuration Record:", error); return null; } }; @@ -2520,6 +2151,78 @@ const skipSubLayerHrdParameters = (bitstream, CpbCnt, sub_pic_hrd_params_present bitstream.readBits(1); } }; +const deserializeHevcDecoderConfigurationRecord = (data) => { + try { + const view = toDataView(data); + let offset = 0; + const configurationVersion = view.getUint8(offset++); + const byte1 = view.getUint8(offset++); + const generalProfileSpace = byte1 >> 6 & 3; + const generalTierFlag = byte1 >> 5 & 1; + const generalProfileIdc = byte1 & 31; + const generalProfileCompatibilityFlags = view.getUint32(offset, false); + offset += 4; + const generalConstraintIndicatorFlags = data.subarray(offset, offset + 6); + offset += 6; + const generalLevelIdc = view.getUint8(offset++); + const minSpatialSegmentationIdc = (view.getUint8(offset++) & 15) << 8 | view.getUint8(offset++); + const parallelismType = view.getUint8(offset++) & 3; + const chromaFormatIdc = view.getUint8(offset++) & 3; + const bitDepthLumaMinus8 = view.getUint8(offset++) & 7; + const bitDepthChromaMinus8 = view.getUint8(offset++) & 7; + const avgFrameRate = view.getUint16(offset, false); + offset += 2; + const byte21 = view.getUint8(offset++); + const constantFrameRate = byte21 >> 6 & 3; + const numTemporalLayers = byte21 >> 3 & 7; + const temporalIdNested = byte21 >> 2 & 1; + const lengthSizeMinusOne = byte21 & 3; + const numOfArrays = view.getUint8(offset++); + const arrays = []; + for (let i = 0; i < numOfArrays; i++) { + const arrByte = view.getUint8(offset++); + const arrayCompleteness = arrByte >> 7 & 1; + const nalUnitType = arrByte & 63; + const numNalus = view.getUint16(offset, false); + offset += 2; + const nalUnits = []; + for (let j = 0; j < numNalus; j++) { + const nalUnitLength = view.getUint16(offset, false); + offset += 2; + nalUnits.push(data.subarray(offset, offset + nalUnitLength)); + offset += nalUnitLength; + } + arrays.push({ + arrayCompleteness, + nalUnitType, + nalUnits + }); + } + return { + configurationVersion, + generalProfileSpace, + generalTierFlag, + generalProfileIdc, + generalProfileCompatibilityFlags, + generalConstraintIndicatorFlags, + generalLevelIdc, + minSpatialSegmentationIdc, + parallelismType, + chromaFormatIdc, + bitDepthLumaMinus8, + bitDepthChromaMinus8, + avgFrameRate, + constantFrameRate, + numTemporalLayers, + temporalIdNested, + lengthSizeMinusOne, + arrays + }; + } catch (error) { + Logging._error("Error deserializing HEVC Decoder Configuration Record:", error); + return null; + } +}; var HevcNaluOrderState; (function(HevcNaluOrderState2) { HevcNaluOrderState2[HevcNaluOrderState2["audAllowed"] = 0] = "audAllowed"; @@ -2592,6 +2295,20 @@ const sanitizeHevcPacketForChromium = (packetData, decoderConfig) => { } return concatHevcNalUnits(filteredNalUnits, decoderConfig); }; +const VP9_COLOR_SPACE_TABLE = { + 1: { colourPrimaries: 5, transferCharacteristics: 6, matrixCoefficients: 5 }, + // CS_BT_601 + 2: { colourPrimaries: 1, transferCharacteristics: 1, matrixCoefficients: 1 }, + // CS_BT_709 + 3: { colourPrimaries: 6, transferCharacteristics: 6, matrixCoefficients: 6 }, + // CS_SMPTE_170 + 4: { colourPrimaries: 7, transferCharacteristics: 7, matrixCoefficients: 7 }, + // CS_SMPTE_240 + 5: { colourPrimaries: 9, transferCharacteristics: 14, matrixCoefficients: 9 }, + // CS_BT_2020 + 7: { colourPrimaries: 1, transferCharacteristics: 13, matrixCoefficients: 0 } + // CS_RGB (sRGB) +}; const extractVp9CodecInfoFromPacket = (packet) => { const bitstream = new Bitstream(packet); const frameMarker = bitstream.readBits(2); @@ -2652,9 +2369,10 @@ const extractVp9CodecInfoFromPacket = (packet) => { break; } } - const matrixCoefficients = colorSpace === 7 ? 0 : colorSpace === 2 ? 1 : colorSpace === 1 ? 6 : 2; - const colourPrimaries = colorSpace === 2 ? 1 : colorSpace === 1 ? 6 : 2; - const transferCharacteristics = colorSpace === 2 ? 1 : colorSpace === 1 ? 6 : 2; + const colorSpaceValues = VP9_COLOR_SPACE_TABLE[colorSpace]; + const colourPrimaries = colorSpaceValues?.colourPrimaries ?? 2; + const transferCharacteristics = colorSpaceValues?.transferCharacteristics ?? 2; + const matrixCoefficients = colorSpaceValues?.matrixCoefficients ?? 2; return { profile, level, @@ -2666,13 +2384,16 @@ const extractVp9CodecInfoFromPacket = (packet) => { matrixCoefficients }; }; +const vp9CodecInfoHasColorInfo = (info) => { + return info.colourPrimaries !== 2 || info.transferCharacteristics !== 2 || info.matrixCoefficients !== 2; +}; const iterateAv1PacketObus = function* (packet) { const bitstream = new Bitstream(packet); const readLeb128 = () => { let value = 0; for (let i = 0; i < 8; i++) { const byte = bitstream.readAlignedByte(); - value |= (byte & 127) << i * 7; + value += (byte & 127) * 2 ** (i * 7); if (!(byte & 128)) { break; } @@ -2680,7 +2401,7 @@ const iterateAv1PacketObus = function* (packet) { return null; } } - if (value >= 2 ** 32 - 1) { + if (value > 2 ** 32 - 1) { return null; } return value; @@ -2727,21 +2448,29 @@ const extractAv1CodecInfoFromPacket = (packet) => { seqLevel = bitstream.readBits(5); } else { const timingInfoPresentFlag = bitstream.readBits(1); + let decoderModelInfoPresentFlag = 0; if (timingInfoPresentFlag) { bitstream.skipBits(32); bitstream.skipBits(32); const equalPictureInterval = bitstream.readBits(1); if (equalPictureInterval) { - return null; + let leadingZeros = 0; + while (leadingZeros < 32 && !bitstream.readBits(1)) { + leadingZeros++; + } + if (leadingZeros < 32) { + bitstream.skipBits(leadingZeros); + } + } + decoderModelInfoPresentFlag = bitstream.readBits(1); + if (decoderModelInfoPresentFlag) { + bufferDelayLengthMinus1 = bitstream.readBits(5); + bitstream.skipBits(32); + bitstream.skipBits(5); + bitstream.skipBits(5); } } - const decoderModelInfoPresentFlag = bitstream.readBits(1); - if (decoderModelInfoPresentFlag) { - bufferDelayLengthMinus1 = bitstream.readBits(5); - bitstream.skipBits(32); - bitstream.skipBits(5); - bitstream.skipBits(5); - } + const initialDisplayDelayPresentFlag = bitstream.readBits(1); const operatingPointsCntMinus1 = bitstream.readBits(5); for (let i = 0; i <= operatingPointsCntMinus1; i++) { bitstream.skipBits(12); @@ -2764,9 +2493,11 @@ const extractAv1CodecInfoFromPacket = (packet) => { bitstream.skipBits(1); } } - const initialDisplayDelayPresentFlag = bitstream.readBits(1); if (initialDisplayDelayPresentFlag) { - bitstream.skipBits(4); + const initialDisplayDelayPresentForThisOp = bitstream.readBits(1); + if (initialDisplayDelayPresentForThisOp) { + bitstream.skipBits(4); + } } } } @@ -2831,10 +2562,27 @@ const extractAv1CodecInfoFromPacket = (packet) => { if (seqProfile !== 1) { monochrome = bitstream.readBits(1); } + let colourPrimaries = 2; + let transferCharacteristics = 2; + let matrixCoefficients = 2; + const colorDescriptionPresentFlag = bitstream.readBits(1); + if (colorDescriptionPresentFlag) { + colourPrimaries = bitstream.readBits(8); + transferCharacteristics = bitstream.readBits(8); + matrixCoefficients = bitstream.readBits(8); + } + let videoFullRangeFlag = 0; let chromaSubsamplingX = 1; let chromaSubsamplingY = 1; let chromaSamplePosition = 0; - if (!monochrome) { + if (monochrome) { + videoFullRangeFlag = bitstream.readBits(1); + } else if (colourPrimaries === 1 && transferCharacteristics === 13 && matrixCoefficients === 0) { + videoFullRangeFlag = 1; + chromaSubsamplingX = 0; + chromaSubsamplingY = 0; + } else { + videoFullRangeFlag = bitstream.readBits(1); if (seqProfile === 0) { chromaSubsamplingX = 1; chromaSubsamplingY = 1; @@ -2844,9 +2592,10 @@ const extractAv1CodecInfoFromPacket = (packet) => { } else { if (bitDepth === 12) { chromaSubsamplingX = bitstream.readBits(1); - if (chromaSubsamplingX) { - chromaSubsamplingY = bitstream.readBits(1); - } + chromaSubsamplingY = chromaSubsamplingX ? bitstream.readBits(1) : 0; + } else { + chromaSubsamplingX = 1; + chromaSubsamplingY = 0; } } if (chromaSubsamplingX && chromaSubsamplingY) { @@ -2861,11 +2610,39 @@ const extractAv1CodecInfoFromPacket = (packet) => { monochrome, chromaSubsamplingX, chromaSubsamplingY, - chromaSamplePosition + chromaSamplePosition, + videoFullRangeFlag, + colourPrimaries, + transferCharacteristics, + matrixCoefficients }; } return null; }; +const av1CodecInfoHasColorInfo = (info) => { + return info.colourPrimaries !== 2 || info.transferCharacteristics !== 2 || info.matrixCoefficients !== 2; +}; +const extractProresCodecInfoFromPacket = (packet) => { + const frameHeaderStart = 8; + if (packet.length < frameHeaderStart + 28) { + return null; + } + const view = toDataView(packet); + if (view.getUint32(4) !== 1768124518) { + return null; + } + const headerSize = view.getUint16(frameHeaderStart); + if (headerSize < 28) { + return null; + } + return { + fullRange: false, + // ProRes is always limited range + colourPrimaries: view.getUint8(frameHeaderStart + 14), + transferCharacteristics: view.getUint8(frameHeaderStart + 15), + matrixCoefficients: view.getUint8(frameHeaderStart + 16) + }; +}; const parseOpusIdentificationHeader = (bytes) => { const view = toDataView(bytes); const outputChannelCount = view.getUint8(9); @@ -2922,8 +2699,17 @@ const OPUS_FRAME_DURATION_TABLE = [ ]; const parseOpusTocByte = (packet) => { const config = packet[0] >> 3; + const code = packet[0] & 3; + let frameCount; + if (code === 0) { + frameCount = 1; + } else if (code === 1 || code === 2) { + frameCount = 2; + } else { + frameCount = packet[1] & 63; + } return { - durationInSamples: OPUS_FRAME_DURATION_TABLE[config] + durationInSamples: OPUS_FRAME_DURATION_TABLE[config] * frameCount }; }; const parseModesFromVorbisSetupPacket = (setupHeader) => { @@ -3005,7 +2791,7 @@ const determineVideoPacketType = (codec, decoderConfig, packetData) => { if (type === AvcNalUnitType.IDR) { return "key"; } - if (type === AvcNalUnitType.SEI && (!isChromium() || getChromiumVersion() >= 144)) { + if (type === AvcNalUnitType.SEI && !isChromium()) { const nalUnit = packetData.subarray(loc.offset, loc.offset + loc.length); const bytes = removeEmulationPreventionBytes(nalUnit); let pos = 1; @@ -3102,6 +2888,9 @@ const determineVideoPacketType = (codec, decoderConfig, packetData) => { } return null; } + case "prores": { + return "key"; + } default: { assertNever(codec); assert(false); @@ -3140,7 +2929,13 @@ const readVorbisComments = (bytes, metadataTags) => { const key = string.slice(0, separatorIndex).toUpperCase(); const value = string.slice(separatorIndex + 1); metadataTags.raw ?? (metadataTags.raw = {}); - (_b = metadataTags.raw)[key] ?? (_b[key] = value); + if (Array.isArray(metadataTags.raw[key])) { + metadataTags.raw[key] = [...metadataTags.raw[key], value]; + } else if (typeof metadataTags.raw[key] === "string") { + metadataTags.raw[key] = [metadataTags.raw[key], value]; + } else { + (_b = metadataTags.raw)[key] ?? (_b[key] = value); + } switch (key) { case "TITLE": { @@ -3533,6 +3328,1056 @@ const getEac3ChannelCount = (config) => { } return channels; }; +const DTS_EXSS_SYNC_WORD = 1683496997; +const DTS_CORE_FRAME_HEADER_SIZE = 18; +const DTS_EXSS_HEADER_PREFIX_SIZE = 10; +const DTS_EXSS_MAX_HEADER_SIZE = 4096; +const DTS_PCM_BLOCK_SAMPLES = 32; +const DTS_SPECIFIC_BOX_SIZE = 20; +const DTS_SUBBAND_SAMPLES = 8; +const DTS_CORE_SAMPLE_RATES = [ + 0, + 8e3, + 16e3, + 32e3, + 0, + 0, + 11025, + 22050, + 44100, + 0, + 0, + 12e3, + 24e3, + 48e3, + 96e3, + 192e3 +]; +const DTS_CORE_BIT_RATES = [ + 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 +]; +const DTS_PCM_RESOLUTIONS = [16, 16, 20, 20, 0, 24, 24, 0]; +const DTS_AMODE_CHANNEL_COUNTS = [1, 2, 2, 2, 2, 3, 3, 4, 4, 5, 6, 6, 6, 7, 8, 8]; +const DTS_AMODE_CHANNEL_LAYOUTS = [ + 1, + 2, + 2, + 2, + 2, + 3, + 18, + 19, + 6, + 7, + 518, + 323, + 83, + 519, + 582, + 535 +]; +const DTS_CHANNEL_LAYOUT_LFE1 = 8; +const DTS_CHANNEL_LAYOUT_PAIR_MASK = 44646; +const DTS_EXSS_REF_CLOCKS = [32e3, 44100, 48e3, 0]; +const DTS_EXSS_SAMPLE_RATES = [ + 8e3, + 16e3, + 32e3, + 64e3, + 128e3, + 22050, + 44100, + 88200, + 176400, + 352800, + 12e3, + 24e3, + 48e3, + 96e3, + 192e3, + 384e3 +]; +const DTS_SPECIFIC_BOX_FRAME_DURATIONS = [512, 1024, 2048, 4096]; +const parseDtsFrame = (data) => { + const core = parseDtsCoreFrameHeader(data); + const view = toDataView(data); + let offset = core ? Math.ceil(core.frameSize / 4) * 4 : 0; + let firstExss = null; + while (offset + 4 <= data.length && view.getUint32(offset) === DTS_EXSS_SYNC_WORD) { + const exss = parseDtsExssHeader(data.subarray(offset)); + if (!exss) { + break; + } + firstExss ?? (firstExss = exss); + offset += exss.frameSize; + } + if (core) { + return { + frameSize: firstExss ? offset : core.frameSize, + sampleRate: core.sampleRate, + numberOfChannels: core.numberOfChannels, + sampleCount: core.sampleCount, + channelLayout: core.channelLayout, + pcmResolution: core.pcmResolution, + bitRate: core.bitRate, + core, + hasExtensions: firstExss !== null + }; + } + if (!firstExss?.asset) { + return null; + } + const { asset } = firstExss; + return { + frameSize: offset, + sampleRate: asset.sampleRate, + numberOfChannels: asset.numberOfChannels, + sampleCount: asset.sampleCount, + channelLayout: asset.channelLayout, + pcmResolution: asset.pcmResolution, + bitRate: 0, + core: null, + hasExtensions: true + }; +}; +const extractDtsFourCcFromPacket = (data) => { + const frameInfo = parseDtsFrame(data); + if (!frameInfo?.core) { + return null; + } + return frameInfo.hasExtensions ? "dtsh" : "dtsc"; +}; +const parseDtsCoreFrameHeader = (data) => { + if (data.length < DTS_CORE_FRAME_HEADER_SIZE) { + return null; + } + if (data[0] !== 127 || data[1] !== 254 || data[2] !== 128 || data[3] !== 1) { + return null; + } + const bitstream = new Bitstream(data); + bitstream.skipBits(32); + bitstream.skipBits(1); + if (bitstream.readBits(5) !== DTS_PCM_BLOCK_SAMPLES - 1) { + return null; + } + const cpf = bitstream.readBits(1); + const npcmblocks = bitstream.readBits(7) + 1; + if (npcmblocks % DTS_SUBBAND_SAMPLES !== 0) { + return null; + } + const frameSize = bitstream.readBits(14) + 1; + if (frameSize < 96) { + return null; + } + const amode = bitstream.readBits(6); + if (amode >= DTS_AMODE_CHANNEL_COUNTS.length) { + return null; + } + const sampleRate = DTS_CORE_SAMPLE_RATES[bitstream.readBits(4)]; + if (sampleRate === 0) { + return null; + } + const bitRate = DTS_CORE_BIT_RATES[bitstream.readBits(5)]; + if (bitstream.readBits(1) !== 0) { + return null; + } + bitstream.skipBits(1 + 1 + 1 + 1); + bitstream.skipBits(3 + 1 + 1); + const lff = bitstream.readBits(2); + if (lff === 3) { + return null; + } + bitstream.skipBits(1); + if (cpf) { + bitstream.skipBits(16); + } + bitstream.skipBits(1 + 4 + 2); + const pcmResolution = DTS_PCM_RESOLUTIONS[bitstream.readBits(3)]; + if (pcmResolution === 0) { + return null; + } + const lfePresent = lff !== 0; + return { + frameSize, + sampleRate, + numberOfChannels: DTS_AMODE_CHANNEL_COUNTS[amode] + (lfePresent ? 1 : 0), + sampleCount: npcmblocks * DTS_PCM_BLOCK_SAMPLES, + channelLayout: DTS_AMODE_CHANNEL_LAYOUTS[amode] | (lfePresent ? DTS_CHANNEL_LAYOUT_LFE1 : 0), + amode, + lfePresent, + bitRate, + pcmResolution + }; +}; +const parseDtsExssHeader = (data) => { + if (data.length < DTS_EXSS_HEADER_PREFIX_SIZE) { + return null; + } + if (data[0] !== 100 || data[1] !== 88 || data[2] !== 32 || data[3] !== 37) { + return null; + } + const bitstream = new Bitstream(data); + bitstream.skipBits(32); + bitstream.skipBits(8); + const extSsIndex = bitstream.readBits(2); + const wideHeader = bitstream.readBits(1); + const headerSizeBits = 8 + 4 * wideHeader; + const frameSizeBits = 16 + 4 * wideHeader; + bitstream.skipBits(headerSizeBits); + const frameSize = bitstream.readBits(frameSizeBits) + 1; + const incomplete = { frameSize, asset: null }; + if (!bitstream.readBits(1)) { + return incomplete; + } + const refClock = DTS_EXSS_REF_CLOCKS[bitstream.readBits(2)]; + const frameDurationCycles = 512 * (bitstream.readBits(3) + 1); + if (bitstream.readBits(1)) { + bitstream.skipBits(32 + 4); + } + const numAudioPresentations = bitstream.readBits(3) + 1; + const numAssets = bitstream.readBits(3) + 1; + const activeExssMasks = []; + for (let i = 0; i < numAudioPresentations; i++) { + activeExssMasks.push(bitstream.readBits(extSsIndex + 1)); + } + for (const mask of activeExssMasks) { + bitstream.skipBits(8 * popcount(mask)); + } + if (bitstream.readBits(1)) { + bitstream.skipBits(2); + const spkrMaskBits = bitstream.readBits(2) + 1 << 2; + const numMixOutConfigs = bitstream.readBits(2) + 1; + bitstream.skipBits(numMixOutConfigs * spkrMaskBits); + } + for (let i = 0; i < numAssets; i++) { + bitstream.skipBits(frameSizeBits); + } + bitstream.skipBits(9); + bitstream.skipBits(3); + if (bitstream.readBits(1)) { + bitstream.skipBits(4); + } + if (bitstream.readBits(1)) { + bitstream.skipBits(24); + } + if (bitstream.readBits(1)) { + bitstream.skipBits(8 * (bitstream.readBits(10) + 1)); + } + const pcmResolution = bitstream.readBits(5) + 1; + const sampleRate = DTS_EXSS_SAMPLE_RATES[bitstream.readBits(4)]; + const numberOfChannels = bitstream.readBits(8) + 1; + let channelLayout = 0; + if (bitstream.readBits(1)) { + if (numberOfChannels > 2) { + bitstream.skipBits(1); + } + if (numberOfChannels > 6) { + bitstream.skipBits(1); + } + if (bitstream.readBits(1)) { + const spkrMaskBits = bitstream.readBits(2) + 1 << 2; + channelLayout = bitstream.readBits(spkrMaskBits); + } + } + if (refClock === 0 || bitstream.getBitsLeft() < 0) { + return incomplete; + } + return { + frameSize, + asset: { + sampleRate, + numberOfChannels, + sampleCount: Math.round(frameDurationCycles * sampleRate / refClock), + channelLayout, + pcmResolution + } + }; +}; +const parseDtsSpecificBox = (data) => { + if (data.length < DTS_SPECIFIC_BOX_SIZE) { + return null; + } + const view = toDataView(data); + const sampleRate = view.getUint32(0); + if (sampleRate === 0) { + return null; + } + const bitstream = new Bitstream(data); + bitstream.seekToByte(13); + const frameDuration = bitstream.readBits(2); + bitstream.skipBits(5); + const coreLfePresent = bitstream.readBits(1); + const coreLayout = bitstream.readBits(6); + bitstream.skipBits(14); + bitstream.skipBits(1); + bitstream.skipBits(3); + const channelLayout = bitstream.readBits(16); + let numberOfChannels = null; + if (channelLayout !== 0) { + numberOfChannels = getDtsChannelCount(channelLayout); + } else if (coreLayout < DTS_AMODE_CHANNEL_COUNTS.length) { + numberOfChannels = DTS_AMODE_CHANNEL_COUNTS[coreLayout] + coreLfePresent; + } + return { + sampleRate, + maxBitrate: view.getUint32(4), + avgBitrate: view.getUint32(8), + pcmSampleDepth: data[12], + sampleCount: DTS_SPECIFIC_BOX_FRAME_DURATIONS[frameDuration], + channelLayout, + numberOfChannels + }; +}; +const getDtsChannelCount = (channelLayout) => { + return popcount(channelLayout) + popcount(channelLayout & DTS_CHANNEL_LAYOUT_PAIR_MASK); +}; +const VIDEO_CODECS = [ + "avc", + "hevc", + "vp9", + "av1", + "vp8", + "prores" +]; +const PCM_AUDIO_CODECS = [ + "pcm-s16", + // We don't prefix 'le' so we're compatible with the WebCodecs-registered PCM codec strings + "pcm-s16be", + "pcm-s24", + "pcm-s24be", + "pcm-s32", + "pcm-s32be", + "pcm-f32", + "pcm-f32be", + "pcm-f64", + "pcm-f64be", + "pcm-u8", + "pcm-s8", + "ulaw", + "alaw" +]; +const NON_PCM_AUDIO_CODECS = [ + "aac", + "opus", + "mp3", + "vorbis", + "flac", + "ac3", + "eac3", + "dts" +]; +const AUDIO_CODECS = [ + ...NON_PCM_AUDIO_CODECS, + ...PCM_AUDIO_CODECS +]; +const AVC_LEVEL_TABLE = [ + { maxMacroblocks: 99, maxBitrate: 64e3, maxDpbMbs: 396, level: 10 }, + // Level 1 + { maxMacroblocks: 396, maxBitrate: 192e3, maxDpbMbs: 900, level: 11 }, + // Level 1.1 + { maxMacroblocks: 396, maxBitrate: 384e3, maxDpbMbs: 2376, level: 12 }, + // Level 1.2 + { maxMacroblocks: 396, maxBitrate: 768e3, maxDpbMbs: 2376, level: 13 }, + // Level 1.3 + { maxMacroblocks: 396, maxBitrate: 2e6, maxDpbMbs: 2376, level: 20 }, + // Level 2 + { maxMacroblocks: 792, maxBitrate: 4e6, maxDpbMbs: 4752, level: 21 }, + // Level 2.1 + { maxMacroblocks: 1620, maxBitrate: 4e6, maxDpbMbs: 8100, level: 22 }, + // Level 2.2 + { maxMacroblocks: 1620, maxBitrate: 1e7, maxDpbMbs: 8100, level: 30 }, + // Level 3 + { maxMacroblocks: 3600, maxBitrate: 14e6, maxDpbMbs: 18e3, level: 31 }, + // Level 3.1 + { maxMacroblocks: 5120, maxBitrate: 2e7, maxDpbMbs: 20480, level: 32 }, + // Level 3.2 + { maxMacroblocks: 8192, maxBitrate: 2e7, maxDpbMbs: 32768, level: 40 }, + // Level 4 + { maxMacroblocks: 8192, maxBitrate: 5e7, maxDpbMbs: 32768, level: 41 }, + // Level 4.1 + { maxMacroblocks: 8704, maxBitrate: 5e7, maxDpbMbs: 34816, level: 42 }, + // Level 4.2 + { maxMacroblocks: 22080, maxBitrate: 135e6, maxDpbMbs: 110400, level: 50 }, + // Level 5 + { maxMacroblocks: 36864, maxBitrate: 24e7, maxDpbMbs: 184320, level: 51 }, + // Level 5.1 + { maxMacroblocks: 36864, maxBitrate: 24e7, maxDpbMbs: 184320, level: 52 }, + // Level 5.2 + { maxMacroblocks: 139264, maxBitrate: 24e7, maxDpbMbs: 696320, level: 60 }, + // Level 6 + { maxMacroblocks: 139264, maxBitrate: 48e7, maxDpbMbs: 696320, level: 61 }, + // Level 6.1 + { maxMacroblocks: 139264, maxBitrate: 8e8, maxDpbMbs: 696320, level: 62 } + // Level 6.2 +]; +const VP9_LEVEL_TABLE = [ + { maxPictureSize: 36864, maxBitrate: 2e5, level: 10 }, + // Level 1 + { maxPictureSize: 73728, maxBitrate: 8e5, level: 11 }, + // Level 1.1 + { maxPictureSize: 122880, maxBitrate: 18e5, level: 20 }, + // Level 2 + { maxPictureSize: 245760, maxBitrate: 36e5, level: 21 }, + // Level 2.1 + { maxPictureSize: 552960, maxBitrate: 72e5, level: 30 }, + // Level 3 + { maxPictureSize: 983040, maxBitrate: 12e6, level: 31 }, + // Level 3.1 + { maxPictureSize: 2228224, maxBitrate: 18e6, level: 40 }, + // Level 4 + { maxPictureSize: 2228224, maxBitrate: 3e7, level: 41 }, + // Level 4.1 + { maxPictureSize: 8912896, maxBitrate: 6e7, level: 50 }, + // Level 5 + { maxPictureSize: 8912896, maxBitrate: 12e7, level: 51 }, + // Level 5.1 + { maxPictureSize: 8912896, maxBitrate: 18e7, level: 52 }, + // Level 5.2 + { maxPictureSize: 35651584, maxBitrate: 18e7, level: 60 }, + // Level 6 + { maxPictureSize: 35651584, maxBitrate: 24e7, level: 61 }, + // Level 6.1 + { maxPictureSize: 35651584, maxBitrate: 48e7, level: 62 } + // Level 6.2 +]; +const VP9_DEFAULT_SUFFIX = ".01.01.01.01.00"; +const AV1_DEFAULT_SUFFIX = ".0.110.01.01.01.0"; +const PRORES_FOURCCS = [ + "ap4x", + // ProRes 4444 XQ + "ap4h", + // ProRes 4444 + "apch", + // ProRes 422 High Quality + "apcn", + // ProRes 422 Standard Definition + "apcs", + // ProRes 422 LT + "apco" + // ProRes 422 Proxy +]; +const DTS_FOURCCS = [ + "dtsc", + // DTS core + "dtsh", + // DTS-HD, core plus extension substreams + "dtsl", + // DTS-HD Lossless, no core + "dtse" + // DTS Express +]; +const extractVideoCodecString = (trackInfo) => { + const { codec, codecDescription, colorSpace, avcCodecInfo, hevcCodecInfo, vp9CodecInfo, av1CodecInfo, proresFormat } = trackInfo; + if (codec === "avc") { + assert(trackInfo.avcType !== null); + if (avcCodecInfo) { + const bytes = new Uint8Array([ + avcCodecInfo.avcProfileIndication, + avcCodecInfo.profileCompatibility, + avcCodecInfo.avcLevelIndication + ]); + return `avc${trackInfo.avcType}.${bytesToHexString(bytes)}`; + } + if (!codecDescription || codecDescription.byteLength < 4) { + throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long."); + } + return `avc${trackInfo.avcType}.${bytesToHexString(codecDescription.subarray(1, 4))}`; + } else if (codec === "hevc") { + let generalProfileSpace; + let generalProfileIdc; + let compatibilityFlags; + let generalTierFlag; + let generalLevelIdc; + let constraintFlags; + if (hevcCodecInfo) { + generalProfileSpace = hevcCodecInfo.generalProfileSpace; + generalProfileIdc = hevcCodecInfo.generalProfileIdc; + compatibilityFlags = reverseBitsU32(hevcCodecInfo.generalProfileCompatibilityFlags); + generalTierFlag = hevcCodecInfo.generalTierFlag; + generalLevelIdc = hevcCodecInfo.generalLevelIdc; + constraintFlags = [...hevcCodecInfo.generalConstraintIndicatorFlags]; + } else { + if (!codecDescription || codecDescription.byteLength < 23) { + throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long."); + } + const view = toDataView(codecDescription); + const profileByte = view.getUint8(1); + generalProfileSpace = profileByte >> 6 & 3; + generalProfileIdc = profileByte & 31; + compatibilityFlags = reverseBitsU32(view.getUint32(2)); + generalTierFlag = profileByte >> 5 & 1; + generalLevelIdc = view.getUint8(12); + constraintFlags = []; + for (let i = 0; i < 6; i++) { + constraintFlags.push(view.getUint8(6 + i)); + } + } + let codecString = "hev1."; + codecString += ["", "A", "B", "C"][generalProfileSpace] + generalProfileIdc; + codecString += "."; + codecString += compatibilityFlags.toString(16).toUpperCase(); + codecString += "."; + codecString += generalTierFlag === 0 ? "L" : "H"; + codecString += generalLevelIdc; + while (constraintFlags.length > 0 && constraintFlags[constraintFlags.length - 1] === 0) { + constraintFlags.pop(); + } + if (constraintFlags.length > 0) { + codecString += "."; + codecString += constraintFlags.map((x) => x.toString(16).toUpperCase()).join("."); + } + return codecString; + } else if (codec === "vp8") { + return "vp8"; + } else if (codec === "vp9") { + if (!vp9CodecInfo) { + const pictureSize = trackInfo.width * trackInfo.height; + let level2 = last(VP9_LEVEL_TABLE).level; + for (const entry of VP9_LEVEL_TABLE) { + if (pictureSize <= entry.maxPictureSize) { + level2 = entry.level; + break; + } + } + return `vp09.00.${level2.toString().padStart(2, "0")}.08`; + } + const profile = vp9CodecInfo.profile.toString().padStart(2, "0"); + const level = vp9CodecInfo.level.toString().padStart(2, "0"); + const bitDepth = vp9CodecInfo.bitDepth.toString().padStart(2, "0"); + const chromaSubsampling = vp9CodecInfo.chromaSubsampling.toString().padStart(2, "0"); + const colourPrimaries = vp9CodecInfo.colourPrimaries.toString().padStart(2, "0"); + const transferCharacteristics = vp9CodecInfo.transferCharacteristics.toString().padStart(2, "0"); + const matrixCoefficients = vp9CodecInfo.matrixCoefficients.toString().padStart(2, "0"); + const videoFullRangeFlag = vp9CodecInfo.videoFullRangeFlag.toString().padStart(2, "0"); + let string = `vp09.${profile}.${level}.${bitDepth}.${chromaSubsampling}`; + string += `.${colourPrimaries}.${transferCharacteristics}.${matrixCoefficients}.${videoFullRangeFlag}`; + if (string.endsWith(VP9_DEFAULT_SUFFIX)) { + string = string.slice(0, -VP9_DEFAULT_SUFFIX.length); + } + return string; + } else if (codec === "av1") { + if (!av1CodecInfo) { + const pictureSize = trackInfo.width * trackInfo.height; + let level2 = last(VP9_LEVEL_TABLE).level; + for (const entry of VP9_LEVEL_TABLE) { + if (pictureSize <= entry.maxPictureSize) { + level2 = entry.level; + break; + } + } + return `av01.0.${level2.toString().padStart(2, "0")}M.08`; + } + const profile = av1CodecInfo.profile; + const level = av1CodecInfo.level.toString().padStart(2, "0"); + const tier = av1CodecInfo.tier ? "H" : "M"; + const bitDepth = av1CodecInfo.bitDepth.toString().padStart(2, "0"); + const monochrome = av1CodecInfo.monochrome ? "1" : "0"; + const chromaSubsampling = 100 * av1CodecInfo.chromaSubsamplingX + 10 * av1CodecInfo.chromaSubsamplingY + 1 * (av1CodecInfo.chromaSubsamplingX && av1CodecInfo.chromaSubsamplingY ? av1CodecInfo.chromaSamplePosition : 0); + const colorPrimaries = colorSpace?.primaries ? COLOR_PRIMARIES_MAP[colorSpace.primaries] : 1; + const transferCharacteristics = colorSpace?.transfer ? TRANSFER_CHARACTERISTICS_MAP[colorSpace.transfer] : 1; + const matrixCoefficients = colorSpace?.matrix ? MATRIX_COEFFICIENTS_MAP[colorSpace.matrix] : 1; + const videoFullRangeFlag = colorSpace?.fullRange ? 1 : 0; + let string = `av01.${profile}.${level}${tier}.${bitDepth}`; + string += `.${monochrome}.${chromaSubsampling.toString().padStart(3, "0")}`; + string += `.${colorPrimaries.toString().padStart(2, "0")}`; + string += `.${transferCharacteristics.toString().padStart(2, "0")}`; + string += `.${matrixCoefficients.toString().padStart(2, "0")}`; + string += `.${videoFullRangeFlag}`; + if (string.endsWith(AV1_DEFAULT_SUFFIX)) { + string = string.slice(0, -AV1_DEFAULT_SUFFIX.length); + } + return string; + } else if (codec === "prores") { + return proresFormat ?? "apch"; + } else if (codec !== null) { + assertNever(codec); + } + throw new TypeError(`Unhandled codec '${codec}'.`); +}; +const extractColorSpace = (info) => { + switch (info.codec) { + case "avc": + { + let spsData = info.avcCodecInfo?.sequenceParameterSets[0]; + if (!spsData && info.codecDescription) { + spsData = deserializeAvcDecoderConfigurationRecord(info.codecDescription)?.sequenceParameterSets[0]; + } + if (spsData) { + const spsInfo = parseAvcSps(spsData); + if (spsInfo) { + return { + primaries: COLOR_PRIMARIES_MAP_INVERSE[spsInfo.colourPrimaries], + transfer: TRANSFER_CHARACTERISTICS_MAP_INVERSE[spsInfo.transferCharacteristics], + matrix: MATRIX_COEFFICIENTS_MAP_INVERSE[spsInfo.matrixCoefficients], + fullRange: !!spsInfo.fullRangeFlag + }; + } + } + } + break; + case "hevc": + { + let spsData = info.hevcCodecInfo?.arrays.find((x) => x.nalUnitType === HevcNalUnitType.SPS_NUT)?.nalUnits[0]; + if (!spsData && info.codecDescription) { + spsData = deserializeHevcDecoderConfigurationRecord(info.codecDescription)?.arrays.find((x) => x.nalUnitType === HevcNalUnitType.SPS_NUT)?.nalUnits[0]; + } + if (spsData) { + const spsInfo = parseHevcSps(spsData); + if (spsInfo) { + return { + primaries: COLOR_PRIMARIES_MAP_INVERSE[spsInfo.colourPrimaries], + transfer: TRANSFER_CHARACTERISTICS_MAP_INVERSE[spsInfo.transferCharacteristics], + matrix: MATRIX_COEFFICIENTS_MAP_INVERSE[spsInfo.matrixCoefficients], + fullRange: !!spsInfo.fullRangeFlag + }; + } + } + } + break; + case "vp8": + break; + case "vp9": + { + if (info.vp9CodecInfo) { + return { + primaries: COLOR_PRIMARIES_MAP_INVERSE[info.vp9CodecInfo.colourPrimaries], + transfer: TRANSFER_CHARACTERISTICS_MAP_INVERSE[info.vp9CodecInfo.transferCharacteristics], + matrix: MATRIX_COEFFICIENTS_MAP_INVERSE[info.vp9CodecInfo.matrixCoefficients], + fullRange: !!info.vp9CodecInfo.videoFullRangeFlag + }; + } + } + break; + case "av1": + { + if (info.av1CodecInfo) { + return { + primaries: COLOR_PRIMARIES_MAP_INVERSE[info.av1CodecInfo.colourPrimaries], + transfer: TRANSFER_CHARACTERISTICS_MAP_INVERSE[info.av1CodecInfo.transferCharacteristics], + matrix: MATRIX_COEFFICIENTS_MAP_INVERSE[info.av1CodecInfo.matrixCoefficients], + fullRange: !!info.av1CodecInfo.videoFullRangeFlag + }; + } + } + break; + case "prores": + { + if (info.proresCodecInfo) { + return { + primaries: COLOR_PRIMARIES_MAP_INVERSE[info.proresCodecInfo.colourPrimaries], + transfer: TRANSFER_CHARACTERISTICS_MAP_INVERSE[info.proresCodecInfo.transferCharacteristics], + matrix: MATRIX_COEFFICIENTS_MAP_INVERSE[info.proresCodecInfo.matrixCoefficients], + fullRange: info.proresCodecInfo.fullRange + }; + } + } + break; + } + return { + primaries: void 0, + transfer: void 0, + matrix: void 0, + fullRange: void 0 + }; +}; +const extractAudioCodecString = (trackInfo) => { + const { codec, codecDescription, aacCodecInfo, dtsFormat } = trackInfo; + if (codec === "aac") { + if (!aacCodecInfo) { + throw new TypeError("AAC codec info must be provided."); + } + if (aacCodecInfo.isMpeg2) { + return "mp4a.67"; + } else { + let objectType; + if (aacCodecInfo.objectType !== null) { + objectType = aacCodecInfo.objectType; + } else { + const audioSpecificConfig = parseAacAudioSpecificConfig(codecDescription); + objectType = audioSpecificConfig.objectType; + } + return `mp4a.40.${objectType}`; + } + } else if (codec === "mp3") { + return "mp3"; + } else if (codec === "opus") { + return "opus"; + } else if (codec === "vorbis") { + return "vorbis"; + } else if (codec === "flac") { + return "flac"; + } else if (codec === "ac3") { + return "ac-3"; + } else if (codec === "eac3") { + return "ec-3"; + } else if (codec === "dts") { + return dtsFormat ?? "dtsc"; + } else if (codec && PCM_AUDIO_CODECS.includes(codec)) { + return codec; + } + throw new TypeError(`Unhandled codec '${codec}'.`); +}; +const OPUS_SAMPLE_RATE = 48e3; +const PCM_CODEC_REGEX = /^pcm-([usf])(\d+)(be)?$/; +const parsePcmCodec = (codec) => { + assert(PCM_AUDIO_CODECS.includes(codec)); + if (codec === "ulaw") { + return { dataType: "ulaw", sampleSize: 1, littleEndian: true, silentValue: 255 }; + } else if (codec === "alaw") { + return { dataType: "alaw", sampleSize: 1, littleEndian: true, silentValue: 213 }; + } + const match = PCM_CODEC_REGEX.exec(codec); + assert(match); + let dataType; + if (match[1] === "u") { + dataType = "unsigned"; + } else if (match[1] === "s") { + dataType = "signed"; + } else { + dataType = "float"; + } + const sampleSize = Number(match[2]) / 8; + const littleEndian = match[3] !== "be"; + const silentValue = codec === "pcm-u8" ? 2 ** 7 : 0; + return { dataType, sampleSize, littleEndian, silentValue }; +}; +const inferCodecFromCodecString = (codecString) => { + if (codecString.startsWith("avc1") || codecString.startsWith("avc3")) { + return "avc"; + } else if (codecString.startsWith("hev1") || codecString.startsWith("hvc1")) { + return "hevc"; + } else if (codecString === "vp8") { + return "vp8"; + } else if (codecString.startsWith("vp09")) { + return "vp9"; + } else if (codecString.startsWith("av01")) { + return "av1"; + } else if (PRORES_FOURCCS.includes(codecString)) { + return "prores"; + } + if (codecString === "mp3" || codecString === "mp4a.69" || codecString === "mp4a.6B" || codecString === "mp4a.6b" || codecString === "mp4a.40.34") { + return "mp3"; + } else if (codecString.startsWith("mp4a.40.") || codecString === "mp4a.67") { + return "aac"; + } else if (codecString === "opus") { + return "opus"; + } else if (codecString === "vorbis") { + return "vorbis"; + } else if (codecString === "flac") { + return "flac"; + } else if (codecString === "ac-3" || codecString === "ac3") { + return "ac3"; + } else if (codecString === "ec-3" || codecString === "eac3") { + return "eac3"; + } else if (DTS_FOURCCS.includes(codecString)) { + return "dts"; + } else if (codecString === "ulaw") { + return "ulaw"; + } else if (codecString === "alaw") { + return "alaw"; + } else if (PCM_CODEC_REGEX.test(codecString)) { + return codecString; + } + if (codecString === "webvtt") { + return "webvtt"; + } + return null; +}; +const MP3_FRAME_HEADER_SIZE = 4; +const SAMPLING_RATES = [44100, 48e3, 32e3]; +const KILOBIT_RATES = [ + // lowSamplingFrequency === 0 + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + // layer = 0 + -1, + 32, + 40, + 48, + 56, + 64, + 80, + 96, + 112, + 128, + 160, + 192, + 224, + 256, + 320, + -1, + // layer 1 + -1, + 32, + 48, + 56, + 64, + 80, + 96, + 112, + 128, + 160, + 192, + 224, + 256, + 320, + 384, + -1, + // layer = 2 + -1, + 32, + 64, + 96, + 128, + 160, + 192, + 224, + 256, + 288, + 320, + 352, + 384, + 416, + 448, + -1, + // layer = 3 + // lowSamplingFrequency === 1 + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + // layer = 0 + -1, + 8, + 16, + 24, + 32, + 40, + 48, + 56, + 64, + 80, + 96, + 112, + 128, + 144, + 160, + -1, + // layer = 1 + -1, + 8, + 16, + 24, + 32, + 40, + 48, + 56, + 64, + 80, + 96, + 112, + 128, + 144, + 160, + -1, + // layer = 2 + -1, + 32, + 48, + 56, + 64, + 80, + 96, + 112, + 128, + 144, + 160, + 176, + 192, + 224, + 256, + -1 + // layer = 3 +]; +const XING = 1483304551; +const INFO = 1231971951; +const computeMp3FrameSize = (lowSamplingFrequency, layer, bitrate, sampleRate, padding) => { + if (layer === 0) { + return 0; + } else if (layer === 1) { + return Math.floor(144 * bitrate / (sampleRate << lowSamplingFrequency)) + padding; + } else if (layer === 2) { + return Math.floor(144 * bitrate / sampleRate) + padding; + } else { + return (Math.floor(12 * bitrate / sampleRate) + padding) * 4; + } +}; +const computeAverageMp3FrameSize = (lowSamplingFrequency, layer, bitrate, sampleRate) => { + if (layer === 0) { + return 0; + } else if (layer === 1) { + return 144 * bitrate / (sampleRate << lowSamplingFrequency); + } else if (layer === 2) { + return 144 * bitrate / sampleRate; + } else { + return 12 * bitrate / sampleRate * 4; + } +}; +const getXingOffset = (mpegVersionId, channel) => { + return mpegVersionId === 3 ? channel === 3 ? 21 : 36 : channel === 3 ? 13 : 21; +}; +const readMp3FrameHeader = (word, remainingBytes) => { + const firstByte = word >>> 24; + const secondByte = word >>> 16 & 255; + const thirdByte = word >>> 8 & 255; + const fourthByte = word & 255; + if (firstByte !== 255 && secondByte !== 255 && thirdByte !== 255 && fourthByte !== 255) { + return { + header: null, + bytesAdvanced: 4 + }; + } + if (firstByte !== 255) { + return { header: null, bytesAdvanced: 1 }; + } + if ((secondByte & 224) !== 224) { + return { header: null, bytesAdvanced: 1 }; + } + let lowSamplingFrequency = 0; + let mpeg25 = 0; + if (secondByte & 1 << 4) { + lowSamplingFrequency = secondByte & 1 << 3 ? 0 : 1; + } else { + lowSamplingFrequency = 1; + mpeg25 = 1; + } + const mpegVersionId = secondByte >> 3 & 3; + const layer = secondByte >> 1 & 3; + const bitrateIndex = thirdByte >> 4 & 15; + const frequencyIndex = (thirdByte >> 2 & 3) % 3; + const padding = thirdByte >> 1 & 1; + const channel = fourthByte >> 6 & 3; + const modeExtension = fourthByte >> 4 & 3; + const copyright = fourthByte >> 3 & 1; + const original = fourthByte >> 2 & 1; + const emphasis = fourthByte & 3; + const kilobitRate = KILOBIT_RATES[lowSamplingFrequency * 16 * 4 + layer * 16 + bitrateIndex]; + if (kilobitRate === -1) { + return { header: null, bytesAdvanced: 1 }; + } + const bitrate = kilobitRate * 1e3; + const sampleRate = SAMPLING_RATES[frequencyIndex] >> lowSamplingFrequency + mpeg25; + const frameLength = computeMp3FrameSize(lowSamplingFrequency, layer, bitrate, sampleRate, padding); + if (remainingBytes !== null && remainingBytes < frameLength) { + return { header: null, bytesAdvanced: 1 }; + } + let audioSamplesInFrame; + if (mpegVersionId === 3) { + audioSamplesInFrame = layer === 3 ? 384 : 1152; + } else { + if (layer === 3) { + audioSamplesInFrame = 384; + } else if (layer === 2) { + audioSamplesInFrame = 1152; + } else { + audioSamplesInFrame = 576; + } + } + return { + header: { + totalSize: frameLength, + mpegVersionId, + lowSamplingFrequency, + layer, + bitrate, + frequencyIndex, + sampleRate, + channel, + modeExtension, + copyright, + original, + emphasis, + audioSamplesInFrame + }, + bytesAdvanced: 1 + }; +}; +const decodeSynchsafe = (synchsafed) => { + let mask = 2130706432; + let unsynchsafed = 0; + while (mask !== 0) { + unsynchsafed >>= 1; + unsynchsafed |= synchsafed & mask; + mask >>= 8; + } + return unsynchsafed; +}; +var XingFlags; +(function(XingFlags2) { + XingFlags2[XingFlags2["FrameCount"] = 1] = "FrameCount"; + XingFlags2[XingFlags2["FileSize"] = 2] = "FileSize"; + XingFlags2[XingFlags2["Toc"] = 4] = "Toc"; +})(XingFlags || (XingFlags = {})); +const getMp3ChannelCount = (channel) => { + return channel === 3 ? 1 : 2; +}; class Demuxer { constructor(input) { this.input = input; @@ -3611,7 +4456,7 @@ class EncodedPacket { throw new TypeError("Metadata-only packets cannot be converted to a video chunk."); } if (typeof EncodedVideoChunk === "undefined") { - throw new Error("Your browser does not support EncodedVideoChunk."); + throw new Error("EncodedVideoChunk is not available in this environment."); } return new EncodedVideoChunk({ data: this.data, @@ -3633,7 +4478,7 @@ class EncodedPacket { throw new TypeError("Metadata-only packets cannot be converted to a video chunk."); } if (typeof EncodedVideoChunk === "undefined") { - throw new Error("Your browser does not support EncodedVideoChunk."); + throw new Error("EncodedVideoChunk is not available in this environment."); } return new EncodedVideoChunk({ data: this.sideData.alpha, @@ -3650,7 +4495,7 @@ class EncodedPacket { throw new TypeError("Metadata-only packets cannot be converted to an audio chunk."); } if (typeof EncodedAudioChunk === "undefined") { - throw new Error("Your browser does not support EncodedAudioChunk."); + throw new Error("EncodedAudioChunk is not available in this environment."); } return new EncodedAudioChunk({ data: this.data, @@ -3949,7 +4794,7 @@ const createAes128CbcDecryptStream = (reader, getInit, close) => { } const requestedLength = CHUNK_SIZE + BLOCK_SIZE; let nextSlice = reader.requestSliceRange(pos, 0, requestedLength); - if (nextSlice instanceof Promise) + if (isThenable(nextSlice)) nextSlice = await nextSlice; if (!nextSlice || nextSlice.length === 0) { throw new Error("Invalid ciphertext."); @@ -4028,9 +4873,10 @@ class IsobmffDemuxer extends Demuxer { return this.metadataPromise ?? (this.metadataPromise = (async () => { let currentPos = 0; let lookForMfraBox = false; + let foundMovieBoxes = false; while (true) { let slice = this.reader.requestSliceRange(currentPos, MIN_BOX_HEADER_SIZE, MAX_BOX_HEADER_SIZE); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) break; @@ -4044,7 +4890,7 @@ class IsobmffDemuxer extends Demuxer { this.isQuickTime = majorBrand === "qt "; } else if (boxInfo.name === "moov") { let moovSlice = this.reader.requestSlice(slice.filePos, boxInfo.contentSize); - if (moovSlice instanceof Promise) + if (isThenable(moovSlice)) moovSlice = await moovSlice; if (!moovSlice) break; @@ -4055,82 +4901,39 @@ class IsobmffDemuxer extends Demuxer { track.editListOffset -= Math.round(previousSegmentDurationsInSeconds * track.timescale); } lookForMfraBox = this.isFragmented && this.reader.fileSize !== null && this.reader.fileSize > startPos + boxInfo.totalSize; + foundMovieBoxes = true; break; } else if (boxInfo.name === "moof") { if (!this.input._initInput) { throw new Error('"moof" box encountered with no "moov" box present; this file is likely a Segment as described in ISO/IEC 14496-12 Section 8.16. A separate init file that contains a "moov" box is required to read this file, please provide it using InputOptions.initInput.'); } - const initDemuxer = await this.input._initInput._getDemuxer(); - if (initDemuxer.constructor !== IsobmffDemuxer) { - throw new Error("Init input must match the input's format."); - } - await initDemuxer.readMetadata(); - this.movieTimescale = initDemuxer.movieTimescale; - this.movieDurationInTimescale = initDemuxer.movieDurationInTimescale; - this.metadataTags = initDemuxer.metadataTags; - this.isFragmented = true; - this.fragmentTrackDefaults = initDemuxer.fragmentTrackDefaults; - this.psshBoxes = initDemuxer.psshBoxes; - for (const foreignTrack of initDemuxer.tracks) { - const track = { - id: foreignTrack.id, - demuxer: this, - trackBacking: null, - disposition: foreignTrack.disposition, - timescale: foreignTrack.timescale, - durationInMediaTimescale: foreignTrack.durationInMediaTimescale, - durationInMovieTimescale: foreignTrack.durationInMovieTimescale, - rotation: foreignTrack.rotation, - internalCodecId: foreignTrack.internalCodecId, - name: foreignTrack.name, - languageCode: foreignTrack.languageCode, - sampleTableByteOffset: null, - sampleTable: null, - fragmentLookupTable: [], - currentFragmentState: null, - fragmentPositionCache: [], - editListPreviousSegmentDurations: foreignTrack.editListPreviousSegmentDurations, - editListOffset: foreignTrack.editListOffset, - encryptionInfo: foreignTrack.encryptionInfo, - encryptionAuxInfo: null, - frmaCodecString: null, - info: foreignTrack.info - }; - if (foreignTrack.trackBacking) { - assert(track.info); - if (track.info.type === "video" && track.info.width !== -1) { - const videoTrack = track; - track.trackBacking = new IsobmffVideoTrackBacking(videoTrack); - this.tracks.push(track); - } else if (track.info.type === "audio" && track.info.numberOfChannels !== -1) { - const audioTrack = track; - track.trackBacking = new IsobmffAudioTrackBacking(audioTrack); - this.tracks.push(track); - } - } - } + await this.copyMetadataFromInitInput(this.input._initInput); lookForMfraBox = false; + foundMovieBoxes = true; break; } currentPos = startPos + boxInfo.totalSize; } + if (!foundMovieBoxes && this.input._initInput) { + await this.copyMetadataFromInitInput(this.input._initInput); + } if (lookForMfraBox) { assert(this.reader.fileSize !== null); let lastWordSlice = this.reader.requestSlice(this.reader.fileSize - 4, 4); - if (lastWordSlice instanceof Promise) + if (isThenable(lastWordSlice)) lastWordSlice = await lastWordSlice; assert(lastWordSlice); const lastWord = readU32Be(lastWordSlice); const potentialMfraPos = this.reader.fileSize - lastWord; if (potentialMfraPos >= 0 && potentialMfraPos <= this.reader.fileSize - MAX_BOX_HEADER_SIZE) { let mfraHeaderSlice = this.reader.requestSliceRange(potentialMfraPos, MIN_BOX_HEADER_SIZE, MAX_BOX_HEADER_SIZE); - if (mfraHeaderSlice instanceof Promise) + if (isThenable(mfraHeaderSlice)) mfraHeaderSlice = await mfraHeaderSlice; if (mfraHeaderSlice) { const boxInfo = readBoxHeader(mfraHeaderSlice); if (boxInfo && boxInfo.name === "mfra") { let mfraSlice = this.reader.requestSlice(mfraHeaderSlice.filePos, boxInfo.contentSize); - if (mfraSlice instanceof Promise) + if (isThenable(mfraSlice)) mfraSlice = await mfraSlice; if (mfraSlice) { this.readContiguousBoxes(mfraSlice); @@ -4141,6 +4944,57 @@ class IsobmffDemuxer extends Demuxer { } })()); } + async copyMetadataFromInitInput(initInput) { + const initDemuxer = await initInput._getDemuxer(); + if (initDemuxer.constructor !== IsobmffDemuxer) { + throw new Error("Init input must match the input's format."); + } + await initDemuxer.readMetadata(); + this.movieTimescale = initDemuxer.movieTimescale; + this.movieDurationInTimescale = initDemuxer.movieDurationInTimescale; + this.metadataTags = initDemuxer.metadataTags; + this.isFragmented = true; + this.fragmentTrackDefaults = initDemuxer.fragmentTrackDefaults; + this.psshBoxes = initDemuxer.psshBoxes; + for (const foreignTrack of initDemuxer.tracks) { + const track = { + id: foreignTrack.id, + demuxer: this, + trackBacking: null, + disposition: foreignTrack.disposition, + timescale: foreignTrack.timescale, + durationInMediaTimescale: foreignTrack.durationInMediaTimescale, + durationInMovieTimescale: foreignTrack.durationInMovieTimescale, + rotation: foreignTrack.rotation, + internalCodecId: foreignTrack.internalCodecId, + name: foreignTrack.name, + languageCode: foreignTrack.languageCode, + sampleTableByteOffset: null, + sampleTable: null, + fragmentLookupTable: [], + currentFragmentState: null, + fragmentPositionCache: [], + editListPreviousSegmentDurations: foreignTrack.editListPreviousSegmentDurations, + editListOffset: foreignTrack.editListOffset, + encryptionInfo: foreignTrack.encryptionInfo, + encryptionAuxInfo: null, + frmaCodecString: null, + info: foreignTrack.info + }; + if (foreignTrack.trackBacking) { + assert(track.info); + if (track.info.type === "video" && track.info.width !== -1) { + const videoTrack = track; + track.trackBacking = new IsobmffVideoTrackBacking(videoTrack); + this.tracks.push(track); + } else if (track.info.type === "audio" && track.info.numberOfChannels !== -1) { + const audioTrack = track; + track.trackBacking = new IsobmffAudioTrackBacking(audioTrack); + this.tracks.push(track); + } + } + } + } getSampleTableForTrack(internalTrack) { if (internalTrack.sampleTable) { return internalTrack.sampleTable; @@ -4237,13 +5091,13 @@ class IsobmffDemuxer extends Demuxer { return this.lastReadFragment; } let headerSlice = this.reader.requestSliceRange(startPos, MIN_BOX_HEADER_SIZE, MAX_BOX_HEADER_SIZE); - if (headerSlice instanceof Promise) + if (isThenable(headerSlice)) headerSlice = await headerSlice; assert(headerSlice); const moofBoxInfo = readBoxHeader(headerSlice); assert(moofBoxInfo?.name === "moof"); let entireSlice = this.reader.requestSlice(startPos, moofBoxInfo.totalSize); - if (entireSlice instanceof Promise) + if (isThenable(entireSlice)) entireSlice = await entireSlice; assert(entireSlice); this.traverseBox(entireSlice); @@ -4441,11 +5295,8 @@ class IsobmffDemuxer extends Demuxer { const segmentDuration = version === 1 ? readU64Be(slice) : readU32Be(slice); const mediaTime = version === 1 ? readI64Be(slice) : readI32Be(slice); const mediaRate = readFixed_16_16(slice); - if (segmentDuration === 0) { - continue; - } if (relevantEntryFound) { - console.warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit."); + Logging._warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit."); break; } if (mediaTime === -1) { @@ -4453,7 +5304,7 @@ class IsobmffDemuxer extends Demuxer { continue; } if (mediaRate !== 1) { - console.warn("Unsupported edit list entry: media rate must be 1."); + Logging._warn("Unsupported edit list entry: media rate must be 1."); break; } track.editListPreviousSegmentDurations = previousSegmentDurations; @@ -4509,12 +5360,14 @@ class IsobmffDemuxer extends Demuxer { squarePixelHeight: -1, codec: null, codecDescription: null, - colorSpace: null, + colorSpace: { ...EMPTY_COLOR_SPACE }, avcType: null, avcCodecInfo: null, hevcCodecInfo: null, vp9CodecInfo: null, - av1CodecInfo: null + av1CodecInfo: null, + proresCodecInfo: null, + proresFormat: null }; } else if (handlerType === "soun") { track.info = { @@ -4524,6 +5377,7 @@ class IsobmffDemuxer extends Demuxer { codec: null, codecDescription: null, aacCodecInfo: null, + dtsFormat: null, pcmLittleEndian: false, pcmSampleSize: null }; @@ -4582,10 +5436,13 @@ class IsobmffDemuxer extends Demuxer { track.info.codec = "vp9"; } else if (codecName === "av01") { track.info.codec = "av1"; + } else if (PRORES_FOURCCS.includes(lowercaseBoxName)) { + track.info.codec = "prores"; + track.info.proresFormat = lowercaseBoxName; } else if (codecName === null) { - console.warn(`Unknown encrypted video codec due to missing frma box.`); + Logging._warn(`Unknown encrypted video codec due to missing frma box.`); } else { - console.warn(`Unsupported video codec (sample entry type '${sampleBoxInfo.name}').`); + Logging._warn(`Unsupported video codec (sample entry type '${sampleBoxInfo.name}').`); } } else { slice.skip(6 * 1 + 2); @@ -4631,13 +5488,16 @@ class IsobmffDemuxer extends Demuxer { track.info.codec = "ac3"; } else if (codecName === "ec-3") { track.info.codec = "eac3"; + } else if (DTS_FOURCCS.includes(codecName)) { + track.info.codec = "dts"; + track.info.dtsFormat = codecName; } else if (codecName === "twos") { if (sampleSize === 8) { track.info.codec = "pcm-s8"; } else if (sampleSize === 16) { track.info.codec = track.info.pcmLittleEndian ? "pcm-s16" : "pcm-s16be"; } else { - console.warn(`Unsupported sample size ${sampleSize} for codec 'twos'.`); + Logging._warn(`Unsupported sample size ${sampleSize} for codec 'twos'.`); track.info.codec = null; } } else if (codecName === "sowt") { @@ -4646,7 +5506,7 @@ class IsobmffDemuxer extends Demuxer { } else if (sampleSize === 16) { track.info.codec = "pcm-s16"; } else { - console.warn(`Unsupported sample size ${sampleSize} for codec 'sowt'.`); + Logging._warn(`Unsupported sample size ${sampleSize} for codec 'sowt'.`); track.info.codec = null; } } else if (codecName === "raw ") { @@ -4669,7 +5529,7 @@ class IsobmffDemuxer extends Demuxer { } else if (pcmSampleSize === 32) { track.info.codec = "pcm-s32"; } else { - console.warn(`Invalid ipcm sample size ${pcmSampleSize}.`); + Logging._warn(`Invalid ipcm sample size ${pcmSampleSize}.`); track.info.codec = null; } } else { @@ -4680,7 +5540,7 @@ class IsobmffDemuxer extends Demuxer { } else if (pcmSampleSize === 32) { track.info.codec = "pcm-s32be"; } else { - console.warn(`Invalid ipcm sample size ${pcmSampleSize}.`); + Logging._warn(`Invalid ipcm sample size ${pcmSampleSize}.`); track.info.codec = null; } } @@ -4692,7 +5552,7 @@ class IsobmffDemuxer extends Demuxer { } else if (pcmSampleSize === 64) { track.info.codec = "pcm-f64"; } else { - console.warn(`Invalid fpcm sample size ${pcmSampleSize}.`); + Logging._warn(`Invalid fpcm sample size ${pcmSampleSize}.`); track.info.codec = null; } } else { @@ -4701,7 +5561,7 @@ class IsobmffDemuxer extends Demuxer { } else if (pcmSampleSize === 64) { track.info.codec = "pcm-f64be"; } else { - console.warn(`Invalid fpcm sample size ${pcmSampleSize}.`); + Logging._warn(`Invalid fpcm sample size ${pcmSampleSize}.`); track.info.codec = null; } } @@ -4734,12 +5594,12 @@ class IsobmffDemuxer extends Demuxer { } } if (track.info.codec === null) { - console.warn("Unsupported PCM format."); + Logging._warn("Unsupported PCM format."); } } else if (codecName === null) { - console.warn(`Unknown encrypted audio codec due to missing frma box.`); + Logging._warn(`Unknown encrypted audio codec due to missing frma box.`); } else { - console.warn(`Unsupported audio codec (sample entry type '${sampleBoxInfo.name}').`); + Logging._warn(`Unsupported audio codec (sample entry type '${sampleBoxInfo.name}').`); } } slice.filePos = sampleBoxStartPos + sampleBoxInfo.totalSize; @@ -4776,7 +5636,7 @@ class IsobmffDemuxer extends Demuxer { defaultSkipByteBlock: null }; } else { - console.warn(`Unsupported encryption scheme '${schemeType}'.`); + Logging._warn(`Unsupported encryption scheme '${schemeType}'.`); } } break; @@ -4815,6 +5675,9 @@ class IsobmffDemuxer extends Demuxer { break; } assert(track.info); + if (boxInfo.contentSize === 0) { + break; + } track.info.codecDescription = readBytes(slice, boxInfo.contentSize); } break; @@ -4825,6 +5688,9 @@ class IsobmffDemuxer extends Demuxer { break; } assert(track.info); + if (boxInfo.contentSize === 0) { + break; + } track.info.codecDescription = readBytes(slice, boxInfo.contentSize); } break; @@ -4877,6 +5743,9 @@ class IsobmffDemuxer extends Demuxer { const chromaSubsamplingY = thirdByte >> 2 & 1; const chromaSamplePosition = thirdByte & 3; const bitDepth = profile === 2 && highBitDepth ? twelveBit ? 12 : 10 : highBitDepth ? 10 : 8; + slice.skip(1); + const configObus = readBytes(slice, boxInfo.contentSize - 4); + const configObuInfo = extractAv1CodecInfoFromPacket(configObus); track.info.av1CodecInfo = { profile, level, @@ -4885,7 +5754,11 @@ class IsobmffDemuxer extends Demuxer { monochrome, chromaSubsamplingX, chromaSubsamplingY, - chromaSamplePosition + chromaSamplePosition, + videoFullRangeFlag: configObuInfo?.videoFullRangeFlag ?? 0, + colourPrimaries: configObuInfo?.colourPrimaries ?? 2, + transferCharacteristics: configObuInfo?.transferCharacteristics ?? 2, + matrixCoefficients: configObuInfo?.matrixCoefficients ?? 2 }; } break; @@ -4897,18 +5770,21 @@ class IsobmffDemuxer extends Demuxer { } assert(track.info?.type === "video"); const colourType = readAscii(slice, 4); - if (colourType !== "nclx") { + if (colourType !== "nclx" && colourType !== "nclc") { break; } const colourPrimaries = readU16Be(slice); const transferCharacteristics = readU16Be(slice); const matrixCoefficients = readU16Be(slice); - const fullRangeFlag = Boolean(readU8(slice) & 128); + let fullRange = void 0; + if (colourType === "nclx") { + fullRange = Boolean(readU8(slice) & 128); + } track.info.colorSpace = { primaries: COLOR_PRIMARIES_MAP_INVERSE[colourPrimaries], transfer: TRANSFER_CHARACTERISTICS_MAP_INVERSE[transferCharacteristics], matrix: MATRIX_COEFFICIENTS_MAP_INVERSE[matrixCoefficients], - fullRange: fullRangeFlag + fullRange }; } break; @@ -4938,10 +5814,9 @@ class IsobmffDemuxer extends Demuxer { case "esds": { const track = this.currentTrack; - if (!track) { + if (!track || track.info?.type !== "audio") { break; } - assert(track.info?.type === "audio"); slice.skip(4); const tag = readU8(slice); assert(tag === 3); @@ -4976,8 +5851,10 @@ class IsobmffDemuxer extends Demuxer { track.info.codec = "mp3"; } else if (objectTypeIndication === 221) { track.info.codec = "vorbis"; + } else if (objectTypeIndication === 169) { + track.info.codec = "dts"; } else { - console.warn(`Unsupported audio codec (objectTypeIndication ${objectTypeIndication}) - discarding track.`); + Logging._warn(`Unsupported audio codec (objectTypeIndication ${objectTypeIndication}) - discarding track.`); } slice.skip(1 + 3 + 4 + 4); if (decoderConfigDescriptorLength > slice.filePos - payloadStart) { @@ -4987,11 +5864,11 @@ class IsobmffDemuxer extends Demuxer { track.info.codecDescription = readBytes(slice, decoderSpecificInfoLength); if (track.info.codec === "aac") { const audioSpecificConfig = parseAacAudioSpecificConfig(track.info.codecDescription); - if (audioSpecificConfig.numberOfChannels !== null) { - track.info.numberOfChannels = audioSpecificConfig.numberOfChannels; + if (audioSpecificConfig.outputNumberOfChannels !== null) { + track.info.numberOfChannels = audioSpecificConfig.outputNumberOfChannels; } - if (audioSpecificConfig.sampleRate !== null) { - track.info.sampleRate = audioSpecificConfig.sampleRate; + if (audioSpecificConfig.outputSampleRate !== null) { + track.info.sampleRate = audioSpecificConfig.outputSampleRate; } } } @@ -5123,7 +6000,7 @@ class IsobmffDemuxer extends Demuxer { const bytes = readBytes(slice, boxInfo.contentSize); const config = parseEac3Config(bytes); if (!config) { - console.warn("Invalid dec3 box contents, ignoring."); + Logging._warn("Invalid dec3 box contents, ignoring."); break; } const sampleRate = getEac3SampleRate(config); @@ -5133,6 +6010,25 @@ class IsobmffDemuxer extends Demuxer { track.info.numberOfChannels = getEac3ChannelCount(config); } break; + case "ddts": + { + const track = this.currentTrack; + if (!track) { + break; + } + assert(track.info?.type === "audio"); + const bytes = readBytes(slice, Math.min(boxInfo.contentSize, DTS_SPECIFIC_BOX_SIZE)); + const config = parseDtsSpecificBox(bytes); + if (!config) { + Logging._warn("Invalid ddts box contents, ignoring."); + break; + } + track.info.sampleRate = config.sampleRate; + if (config.numberOfChannels !== null) { + track.info.numberOfChannels = config.numberOfChannels; + } + } + break; case "stts": { const track = this.currentTrack; @@ -5406,8 +6302,11 @@ class IsobmffDemuxer extends Demuxer { this.readContiguousBoxes(slice.slice(contentStartPos, boxInfo.contentSize)); if (this.currentTrack) { const trackData = this.currentFragment.trackData.get(this.currentTrack.id); - if (trackData) { - this.currentFragment.implicitBaseDataOffset = trackData.currentOffset; + cond: if (trackData) { + if (trackData.samples.length === 0) { + this.currentFragment.trackData.delete(this.currentTrack.id); + break cond; + } trackData.presentationTimestamps = trackData.samples.map((x, i) => ({ presentationTimestamp: x.presentationTimestamp, sampleIndex: i })).sort((a, b) => a.presentationTimestamp - b.presentationTimestamp); for (let i = 0; i < trackData.presentationTimestamps.length; i++) { const currentEntry = trackData.presentationTimestamps[i]; @@ -5562,10 +6461,6 @@ class IsobmffDemuxer extends Demuxer { }; this.currentFragment.trackData.set(track.id, trackData); } - if (sampleCount === 0) { - this.currentFragment.implicitBaseDataOffset = trackData.currentOffset; - break; - } for (let i = 0; i < sampleCount; i++) { let sampleDuration; if (sampleDurationPresent) { @@ -5611,6 +6506,7 @@ class IsobmffDemuxer extends Demuxer { trackData.currentOffset += sampleSize; trackData.currentTimestamp += sampleDuration; } + this.currentFragment.implicitBaseDataOffset = trackData.currentOffset; } break; case "saiz": @@ -5660,7 +6556,7 @@ class IsobmffDemuxer extends Demuxer { break; } if (entryCount > 1) { - console.warn("Multiple saio entries are not supported; using the first offset only."); + Logging._warn("Multiple saio entries are not supported; using the first offset only."); } let offset = version === 0 ? readU32Be(slice) : Number(readU64Be(slice)); if (this.currentFragment) { @@ -6057,6 +6953,9 @@ class IsobmffTrackBacking { isRelativeToUnixEpoch() { return false; } + getUnixTimeForTimestamp() { + return null; + } getDisposition() { return this.internalTrack.disposition; } @@ -6250,17 +7149,23 @@ class IsobmffTrackBacking { data = PLACEHOLDER_DATA; } else { let slice = this.internalTrack.demuxer.reader.requestSlice(sampleInfo.sampleOffset, sampleInfo.sampleSize); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) { return null; } data = readBytes(slice, sampleInfo.sampleSize); - if (this.internalTrack.encryptionAuxInfo) { - assert(this.internalTrack.encryptionInfo); - const entries = await resolveEncryptionAuxInfo(this.internalTrack.demuxer.reader, this.internalTrack.encryptionInfo, this.internalTrack.encryptionAuxInfo); - if (sampleIndex < entries.length) { - data = await decryptSample(this.internalTrack, entries[sampleIndex], data, null); + if (this.internalTrack.encryptionInfo) { + let sampleEncryption = null; + if (this.internalTrack.encryptionAuxInfo) { + const entries = await resolveEncryptionAuxInfo(this.internalTrack.demuxer.reader, this.internalTrack.encryptionInfo, this.internalTrack.encryptionAuxInfo); + if (sampleIndex < entries.length) { + sampleEncryption = entries[sampleIndex]; + } + } + sampleEncryption ?? (sampleEncryption = getDefaultSampleEncryption(this.internalTrack.encryptionInfo)); + if (sampleEncryption) { + data = await decryptSample(this.internalTrack, sampleEncryption, data, null); } } } @@ -6282,14 +7187,17 @@ class IsobmffTrackBacking { data = PLACEHOLDER_DATA; } else { let slice = this.internalTrack.demuxer.reader.requestSlice(fragmentSample.byteOffset, fragmentSample.byteSize); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) { return null; } data = readBytes(slice, fragmentSample.byteSize); - if (fragmentSample.encryption) { - data = await decryptSample(this.internalTrack, fragmentSample.encryption, data, fragment); + if (this.internalTrack.encryptionInfo) { + const sampleEncryption = fragmentSample.encryption ?? getDefaultSampleEncryption(this.internalTrack.encryptionInfo); + if (sampleEncryption) { + data = await decryptSample(this.internalTrack, sampleEncryption, data, fragment); + } } } const timestamp = (fragmentSample.presentationTimestamp - this.internalTrack.editListOffset) / this.internalTrack.timescale; @@ -6338,7 +7246,7 @@ class IsobmffTrackBacking { } } let slice = demuxer.reader.requestSliceRange(currentPos, MIN_BOX_HEADER_SIZE, MAX_BOX_HEADER_SIZE); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) break; @@ -6400,34 +7308,67 @@ class IsobmffVideoTrackBacking extends IsobmffTrackBacking { return this.internalTrack.rotation; } async getColorSpace() { + const decoderConfig = await this.getDecoderConfig(); + if (!decoderConfig) { + return this.internalTrack.info.colorSpace; + } return { - primaries: this.internalTrack.info.colorSpace?.primaries, - transfer: this.internalTrack.info.colorSpace?.transfer, - matrix: this.internalTrack.info.colorSpace?.matrix, - fullRange: this.internalTrack.info.colorSpace?.fullRange + primaries: decoderConfig.colorSpace?.primaries, + transfer: decoderConfig.colorSpace?.transfer, + matrix: decoderConfig.colorSpace?.matrix, + fullRange: decoderConfig.colorSpace?.fullRange }; } async canBeTransparent() { - return false; + return this.internalTrack.info.codec === "prores" && (this.internalTrack.info.proresFormat === "ap4h" || this.internalTrack.info.proresFormat === "ap4x"); } async getDecoderConfig() { if (!this.internalTrack.info.codec) { return null; } return this.decoderConfigPromise ?? (this.decoderConfigPromise = (async () => { - if (this.internalTrack.info.codec === "vp9" && !this.internalTrack.info.vp9CodecInfo) { + var _a, _b, _c, _d; + if (this.internalTrack.info.codec === "avc" && !this.internalTrack.info.codecDescription) { const firstPacket = await this.getFirstPacket({}); - this.internalTrack.info.vp9CodecInfo = firstPacket && extractVp9CodecInfoFromPacket(firstPacket.data); - } else if (this.internalTrack.info.codec === "av1" && !this.internalTrack.info.av1CodecInfo) { + this.internalTrack.info.avcCodecInfo = firstPacket && extractAvcDecoderConfigurationRecord(firstPacket.data); + } else if (this.internalTrack.info.codec === "hevc" && !this.internalTrack.info.codecDescription) { const firstPacket = await this.getFirstPacket({}); - this.internalTrack.info.av1CodecInfo = firstPacket && extractAv1CodecInfoFromPacket(firstPacket.data); + this.internalTrack.info.hevcCodecInfo = firstPacket && extractHevcDecoderConfigurationRecord(firstPacket.data); + } else if (this.internalTrack.info.codec === "vp9" && (!this.internalTrack.info.vp9CodecInfo || !vp9CodecInfoHasColorInfo(this.internalTrack.info.vp9CodecInfo))) { + const firstPacket = await this.getFirstPacket({}); + const packetInfo = firstPacket && extractVp9CodecInfoFromPacket(firstPacket.data); + if (packetInfo) { + this.internalTrack.info.vp9CodecInfo = { + ...this.internalTrack.info.vp9CodecInfo ?? packetInfo, + videoFullRangeFlag: packetInfo.videoFullRangeFlag, + colourPrimaries: packetInfo.colourPrimaries, + transferCharacteristics: packetInfo.transferCharacteristics, + matrixCoefficients: packetInfo.matrixCoefficients + }; + } + } else if (this.internalTrack.info.codec === "av1" && (!this.internalTrack.info.av1CodecInfo || !av1CodecInfoHasColorInfo(this.internalTrack.info.av1CodecInfo))) { + const firstPacket = await this.getFirstPacket({}); + const packetInfo = firstPacket && extractAv1CodecInfoFromPacket(firstPacket.data); + if (packetInfo) { + this.internalTrack.info.av1CodecInfo = packetInfo; + } + } else if (this.internalTrack.info.codec === "prores" && !this.internalTrack.info.proresCodecInfo) { + const firstPacket = await this.getFirstPacket({}); + this.internalTrack.info.proresCodecInfo = firstPacket && extractProresCodecInfoFromPacket(firstPacket.data); + } + if (!colorSpaceIsComplete(this.internalTrack.info.colorSpace)) { + const colorSpace = extractColorSpace(this.internalTrack.info); + (_a = this.internalTrack.info.colorSpace).primaries ?? (_a.primaries = colorSpace.primaries); + (_b = this.internalTrack.info.colorSpace).transfer ?? (_b.transfer = colorSpace.transfer); + (_c = this.internalTrack.info.colorSpace).matrix ?? (_c.matrix = colorSpace.matrix); + (_d = this.internalTrack.info.colorSpace).fullRange ?? (_d.fullRange = colorSpace.fullRange); } const config = { codec: extractVideoCodecString(this.internalTrack.info), codedWidth: this.internalTrack.info.width, codedHeight: this.internalTrack.info.height, description: this.internalTrack.info.codecDescription ?? void 0, - colorSpace: this.internalTrack.info.colorSpace ?? void 0 + colorSpace: this.internalTrack.info.colorSpace }; if (this.internalTrack.info.width !== this.internalTrack.info.squarePixelWidth || this.internalTrack.info.height !== this.internalTrack.info.squarePixelHeight) { config.displayAspectWidth = this.internalTrack.info.squarePixelWidth; @@ -6440,7 +7381,7 @@ class IsobmffVideoTrackBacking extends IsobmffTrackBacking { class IsobmffAudioTrackBacking extends IsobmffTrackBacking { constructor(internalTrack) { super(internalTrack); - this.decoderConfig = null; + this.decoderConfigPromise = null; this.internalTrack = internalTrack; } getType() { @@ -6459,12 +7400,18 @@ class IsobmffAudioTrackBacking extends IsobmffTrackBacking { if (!this.internalTrack.info.codec) { return null; } - return this.decoderConfig ?? (this.decoderConfig = { - codec: extractAudioCodecString(this.internalTrack.info), - numberOfChannels: this.internalTrack.info.numberOfChannels, - sampleRate: this.internalTrack.info.sampleRate, - description: this.internalTrack.info.codecDescription ?? void 0 - }); + return this.decoderConfigPromise ?? (this.decoderConfigPromise = (async () => { + if (this.internalTrack.info.codec === "dts" && !this.internalTrack.info.dtsFormat) { + const firstPacket = await this.getFirstPacket({}); + this.internalTrack.info.dtsFormat = firstPacket && extractDtsFourCcFromPacket(firstPacket.data); + } + return { + codec: extractAudioCodecString(this.internalTrack.info), + numberOfChannels: this.internalTrack.info.numberOfChannels, + sampleRate: this.internalTrack.info.sampleRate, + description: this.internalTrack.info.codecDescription ?? void 0 + }; + })()); } } const getSampleIndexForTimestamp = (sampleTable, timescaleUnits) => { @@ -6625,7 +7572,7 @@ const resolveEncryptionAuxInfo = async (reader, encryptionInfo, aux) => { } } let slice = reader.requestSlice(aux.offset, totalSize); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) { throw new Error("Failed to read auxiliary encryption info."); @@ -6656,6 +7603,15 @@ const resolveEncryptionAuxInfo = async (reader, encryptionInfo, aux) => { aux.resolved = entries; return entries; }; +const getDefaultSampleEncryption = (encryptionInfo) => { + if (!encryptionInfo.defaultConstantIv) { + return null; + } + return { + iv: encryptionInfo.defaultConstantIv, + subsamples: null + }; +}; const decryptSample = async (track, sampleEncryption, data, fragment) => { assert(track.encryptionInfo); const encryptionInfo = track.encryptionInfo; @@ -7078,7 +8034,7 @@ const searchForNextElementId = async (reader, startPos, ids, until) => { let currentPos = startPos; while (until === null || currentPos < until) { let slice = reader.requestSliceRange(currentPos, MIN_HEADER_SIZE, MAX_HEADER_SIZE); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) break; @@ -7100,7 +8056,7 @@ const resync = async (reader, startPos, ids, until) => { let currentPos = startPos; while (currentPos < until) { let slice = reader.requestSliceRange(currentPos, 0, Math.min(CHUNK_SIZE, until - currentPos)); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) break; @@ -7123,13 +8079,15 @@ const CODEC_STRING_MAP = { "vp8": "V_VP8", "vp9": "V_VP9", "av1": "V_AV1", + "prores": "V_PRORES", "aac": "A_AAC", "mp3": "A_MPEG/L3", "opus": "A_OPUS", "vorbis": "A_VORBIS", "flac": "A_FLAC", "ac3": "A_AC3", - "eac3": "A_EAC3" + "eac3": "A_EAC3", + "dts": "A_DTS" }; function assertDefinedSize(size) { if (size === void 0) { @@ -7226,7 +8184,7 @@ class MatroskaDemuxer extends Demuxer { let currentPos = 0; while (true) { let slice = this.reader.requestSliceRange(currentPos, MIN_HEADER_SIZE, MAX_HEADER_SIZE); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) break; @@ -7240,7 +8198,7 @@ class MatroskaDemuxer extends Demuxer { if (id === EBMLId.EBML) { assertDefinedSize(size); let slice2 = this.reader.requestSlice(dataStartPos, size); - if (slice2 instanceof Promise) + if (isThenable(slice2)) slice2 = await slice2; if (!slice2) break; @@ -7296,7 +8254,7 @@ class MatroskaDemuxer extends Demuxer { let currentPos = segmentDataStart; while (this.currentSegment.elementEndPos === null || currentPos < this.currentSegment.elementEndPos) { let slice = this.reader.requestSliceRange(currentPos, MIN_HEADER_SIZE, MAX_HEADER_SIZE); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) break; @@ -7319,7 +8277,7 @@ class MatroskaDemuxer extends Demuxer { this.currentSegment[field] = true; assertDefinedSize(size); let slice2 = this.reader.requestSlice(dataStartPos, size); - if (slice2 instanceof Promise) + if (isThenable(slice2)) slice2 = await slice2; if (slice2) { this.readContiguousElements(slice2); @@ -7332,7 +8290,7 @@ class MatroskaDemuxer extends Demuxer { } assertDefinedSize(size); let slice2 = this.reader.requestSlice(dataStartPos, size); - if (slice2 instanceof Promise) + if (isThenable(slice2)) slice2 = await slice2; if (slice2) { this.readContiguousElements(slice2); @@ -7357,7 +8315,7 @@ class MatroskaDemuxer extends Demuxer { if (this.currentSegment[target.flag]) continue; let slice = this.reader.requestSliceRange(segmentDataStart + seekEntry.segmentPosition, MIN_HEADER_SIZE, MAX_HEADER_SIZE); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) continue; @@ -7370,7 +8328,7 @@ class MatroskaDemuxer extends Demuxer { assertDefinedSize(size); this.currentSegment[target.flag] = true; let dataSlice = this.reader.requestSlice(slice.filePos, size); - if (dataSlice instanceof Promise) + if (isThenable(dataSlice)) dataSlice = await dataSlice; if (!dataSlice) continue; @@ -7424,7 +8382,7 @@ class MatroskaDemuxer extends Demuxer { return segment.lastReadCluster; } let headerSlice = this.reader.requestSliceRange(startPos, MIN_HEADER_SIZE, MAX_HEADER_SIZE); - if (headerSlice instanceof Promise) + if (isThenable(headerSlice)) headerSlice = await headerSlice; assert(headerSlice); const elementStartPos = startPos; @@ -7439,7 +8397,7 @@ class MatroskaDemuxer extends Demuxer { size = nextElementPos.pos - dataStartPos; } let dataSlice = this.reader.requestSlice(dataStartPos, size); - if (dataSlice instanceof Promise) + if (isThenable(dataSlice)) dataSlice = await dataSlice; const cluster = { segment, @@ -7600,6 +8558,7 @@ class MatroskaDemuxer extends Demuxer { data: frameData, lacing: BlockLacing.None, decoded: true, + postProcessed: false, mainAdditional: originalBlock.mainAdditional }); } @@ -7615,7 +8574,7 @@ class MatroskaDemuxer extends Demuxer { continue; } let slice = this.reader.requestSliceRange(segment.dataStartPos + seekEntry.segmentPosition, MIN_HEADER_SIZE, MAX_HEADER_SIZE); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) continue; @@ -7627,7 +8586,7 @@ class MatroskaDemuxer extends Demuxer { assert(!this.currentSegment); this.currentSegment = segment; let dataSlice = this.reader.requestSlice(slice.filePos, size); - if (dataSlice instanceof Promise) + if (isThenable(dataSlice)) dataSlice = await dataSlice; if (dataSlice) { this.readContiguousElements(dataSlice); @@ -7743,7 +8702,7 @@ class MatroskaDemuxer extends Demuxer { if (this.currentTrack.decodingInstructions.some((instruction) => { return instruction.data?.type !== "decompress" || instruction.scope !== ContentEncodingScope.Block || instruction.data.algorithm !== ContentCompAlgo.HeaderStripping; })) { - console.warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`); + Logging._warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`); this.currentTrack = null; } if (this.currentTrack && this.currentTrack.id !== -1 && this.currentTrack.codecId && this.currentTrack.info) { @@ -7775,6 +8734,12 @@ class MatroskaDemuxer extends Demuxer { this.currentTrack.info.codec = "vp9"; } else if (codecIdWithoutSuffix === CODEC_STRING_MAP.av1) { this.currentTrack.info.codec = "av1"; + } else if (codecIdWithoutSuffix === CODEC_STRING_MAP.prores) { + const format = this.currentTrack.codecPrivate ? textDecoder.decode(this.currentTrack.codecPrivate) : ""; + if (PRORES_FOURCCS.includes(format)) { + this.currentTrack.info.codec = "prores"; + this.currentTrack.info.proresFormat = format; + } } const videoTrack = this.currentTrack; this.currentTrack.trackBacking = new MatroskaVideoTrackBacking(videoTrack); @@ -7805,6 +8770,13 @@ class MatroskaDemuxer extends Demuxer { } else if (codecIdWithoutSuffix === CODEC_STRING_MAP.eac3) { this.currentTrack.info.codec = "eac3"; this.currentTrack.info.codecDescription = this.currentTrack.codecPrivate; + } else if (codecIdWithoutSuffix === CODEC_STRING_MAP.dts) { + this.currentTrack.info.codec = "dts"; + if (this.currentTrack.codecId === "A_DTS/EXPRESS") { + this.currentTrack.info.dtsFormat = "dtse"; + } else if (this.currentTrack.codecId === "A_DTS/LOSSLESS") { + this.currentTrack.info.dtsFormat = "dtsl"; + } } else if (this.currentTrack.codecId === "A_PCM/INT/LIT") { if (this.currentTrack.info.bitDepth === 8) { this.currentTrack.info.codec = "pcm-u8"; @@ -7865,8 +8837,9 @@ class MatroskaDemuxer extends Demuxer { rotation: 0, codec: null, codecDescription: null, - colorSpace: null, - alphaMode: false + colorSpace: { ...EMPTY_COLOR_SPACE }, + alphaMode: false, + proresFormat: null }; } else if (type === 2) { this.currentTrack.info = { @@ -7878,7 +8851,8 @@ class MatroskaDemuxer extends Demuxer { bitDepth: -1, codec: null, codecDescription: null, - aacCodecInfo: null + aacCodecInfo: null, + dtsFormat: null }; } } @@ -8043,41 +9017,41 @@ class MatroskaDemuxer extends Demuxer { { if (this.currentTrack?.info?.type !== "video") break; - this.currentTrack.info.colorSpace = {}; this.readContiguousElements(slice.slice(dataStartPos, size)); } break; case EBMLId.MatrixCoefficients: { - if (this.currentTrack?.info?.type !== "video" || !this.currentTrack.info.colorSpace) + if (this.currentTrack?.info?.type !== "video") break; const matrixCoefficients = readUnsignedInt(slice, size); - const mapped = MATRIX_COEFFICIENTS_MAP_INVERSE[matrixCoefficients] ?? null; + const mapped = MATRIX_COEFFICIENTS_MAP_INVERSE[matrixCoefficients]; this.currentTrack.info.colorSpace.matrix = mapped; } break; case EBMLId.Range: { - if (this.currentTrack?.info?.type !== "video" || !this.currentTrack.info.colorSpace) + if (this.currentTrack?.info?.type !== "video") break; - this.currentTrack.info.colorSpace.fullRange = readUnsignedInt(slice, size) === 2; + const range = readUnsignedInt(slice, size); + this.currentTrack.info.colorSpace.fullRange = range === 1 || range === 2 ? range === 2 : void 0; } break; case EBMLId.TransferCharacteristics: { - if (this.currentTrack?.info?.type !== "video" || !this.currentTrack.info.colorSpace) + if (this.currentTrack?.info?.type !== "video") break; const transferCharacteristics = readUnsignedInt(slice, size); - const mapped = TRANSFER_CHARACTERISTICS_MAP_INVERSE[transferCharacteristics] ?? null; + const mapped = TRANSFER_CHARACTERISTICS_MAP_INVERSE[transferCharacteristics]; this.currentTrack.info.colorSpace.transfer = mapped; } break; case EBMLId.Primaries: { - if (this.currentTrack?.info?.type !== "video" || !this.currentTrack.info.colorSpace) + if (this.currentTrack?.info?.type !== "video") break; const primaries = readUnsignedInt(slice, size); - const mapped = COLOR_PRIMARIES_MAP_INVERSE[primaries] ?? null; + const mapped = COLOR_PRIMARIES_MAP_INVERSE[primaries]; this.currentTrack.info.colorSpace.primaries = mapped; } break; @@ -8206,6 +9180,7 @@ class MatroskaDemuxer extends Demuxer { data: blockData, lacing, decoded: !hasDecodingInstructions, + postProcessed: false, mainAdditional: null }); } @@ -8242,6 +9217,7 @@ class MatroskaDemuxer extends Demuxer { data: blockData, lacing, decoded: !hasDecodingInstructions, + postProcessed: false, mainAdditional: null }; trackData.blocks.push(this.currentBlock); @@ -8616,6 +9592,22 @@ class MatroskaDemuxer extends Demuxer { } } } + async getDurationFromMetadata(segment) { + if (segment.duration <= 0) { + return null; + } + let minTimestamp = null; + for (const track of segment.tracks) { + assert(track.trackBacking); + const firstPacket = await track.trackBacking.getFirstPacket({ metadataOnly: true }); + if (firstPacket) { + minTimestamp = Math.min(minTimestamp ?? Infinity, firstPacket.timestamp); + } + } + let endTimestamp = segment.duration / segment.timestampFactor; + endTimestamp += minTimestamp ?? 0; + return endTimestamp; + } } class MatroskaTrackBacking { constructor(internalTrack) { @@ -8659,6 +9651,9 @@ class MatroskaTrackBacking { isRelativeToUnixEpoch() { return false; } + getUnixTimeForTimestamp() { + return null; + } getDisposition() { return this.internalTrack.disposition; } @@ -8672,14 +9667,7 @@ class MatroskaTrackBacking { return null; } async getDurationFromMetadata() { - const segment = this.internalTrack.segment; - if (segment.duration <= 0) { - return null; - } - let endTimestamp = segment.duration / segment.timestampFactor; - const firstPacket = await this.getFirstPacket({ metadataOnly: true }); - endTimestamp += firstPacket?.timestamp ?? 0; - return endTimestamp; + return this.internalTrack.demuxer.getDurationFromMetadata(this.internalTrack.segment); } async getLiveRefreshInterval() { return null; @@ -8824,6 +9812,23 @@ class MatroskaTrackBacking { block.data = this.internalTrack.demuxer.decodeBlockData(this.internalTrack, block.data); block.decoded = true; } + if (!block.postProcessed) { + if (this.internalTrack.info?.codec === "prores") { + const hasFrameContainer = block.data.length >= 8 && block.data[4] === 105 && block.data[5] === 99 && block.data[6] === 112 && block.data[7] === 102; + if (!hasFrameContainer) { + const newData = new Uint8Array(block.data.length + 8); + const newDataView = toDataView(newData); + newDataView.setUint32(0, newData.length, false); + newData[4] = 105; + newData[5] = 99; + newData[6] = 112; + newData[7] = 102; + newData.set(block.data, 8); + block.data = newData; + } + } + block.postProcessed = true; + } const data = options.metadataOnly ? PLACEHOLDER_DATA : block.data; const timestamp = block.timestamp / this.internalTrack.segment.timestampFactor; const duration = block.duration / this.internalTrack.segment.timestampFactor; @@ -8876,7 +9881,7 @@ class MatroskaTrackBacking { } } let slice = demuxer.reader.requestSliceRange(currentPos, MIN_HEADER_SIZE, MAX_HEADER_SIZE); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) break; @@ -8914,7 +9919,7 @@ class MatroskaTrackBacking { const endPos = dataStartPos + size; if (segment.elementEndPos === null) { let slice2 = demuxer.reader.requestSliceRange(endPos, MIN_HEADER_SIZE, MAX_HEADER_SIZE); - if (slice2 instanceof Promise) + if (isThenable(slice2)) slice2 = await slice2; if (!slice2) break; @@ -8966,44 +9971,59 @@ class MatroskaVideoTrackBacking extends MatroskaTrackBacking { return this.internalTrack.info.rotation; } async getColorSpace() { + const decoderConfig = await this.getDecoderConfig(); + if (!decoderConfig) { + return this.internalTrack.info.colorSpace; + } return { - primaries: this.internalTrack.info.colorSpace?.primaries, - transfer: this.internalTrack.info.colorSpace?.transfer, - matrix: this.internalTrack.info.colorSpace?.matrix, - fullRange: this.internalTrack.info.colorSpace?.fullRange + primaries: decoderConfig.colorSpace?.primaries, + transfer: decoderConfig.colorSpace?.transfer, + matrix: decoderConfig.colorSpace?.matrix, + fullRange: decoderConfig.colorSpace?.fullRange }; } async canBeTransparent() { - return this.internalTrack.info.alphaMode; + return this.internalTrack.info.alphaMode || this.internalTrack.info.codec === "prores" && (this.internalTrack.info.proresFormat === "ap4h" || this.internalTrack.info.proresFormat === "ap4x"); } async getDecoderConfig() { if (!this.internalTrack.info.codec) { return null; } return this.decoderConfigPromise ?? (this.decoderConfigPromise = (async () => { + var _a, _b, _c, _d; let firstPacket = null; - const needsPacketForAdditionalInfo = this.internalTrack.info.codec === "vp9" || this.internalTrack.info.codec === "av1" || this.internalTrack.info.codec === "avc" && !this.internalTrack.info.codecDescription || this.internalTrack.info.codec === "hevc" && !this.internalTrack.info.codecDescription; + const needsPacketForAdditionalInfo = this.internalTrack.info.codec === "vp9" || this.internalTrack.info.codec === "av1" || this.internalTrack.info.codec === "prores" || this.internalTrack.info.codec === "avc" && !this.internalTrack.info.codecDescription || this.internalTrack.info.codec === "hevc" && !this.internalTrack.info.codecDescription; if (needsPacketForAdditionalInfo) { firstPacket = await this.getFirstPacket({}); } + const codecInfo = { + 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, + // We don't know better (or do we?) so just assume 'avc1' + avcCodecInfo: this.internalTrack.info.codec === "avc" && firstPacket ? extractAvcDecoderConfigurationRecord(firstPacket.data) : null, + hevcCodecInfo: this.internalTrack.info.codec === "hevc" && firstPacket ? extractHevcDecoderConfigurationRecord(firstPacket.data) : null, + vp9CodecInfo: this.internalTrack.info.codec === "vp9" && firstPacket ? extractVp9CodecInfoFromPacket(firstPacket.data) : null, + av1CodecInfo: this.internalTrack.info.codec === "av1" && firstPacket ? extractAv1CodecInfoFromPacket(firstPacket.data) : null, + proresCodecInfo: this.internalTrack.info.codec === "prores" && firstPacket ? extractProresCodecInfoFromPacket(firstPacket.data) : null, + proresFormat: this.internalTrack.info.proresFormat + }; + if (!colorSpaceIsComplete(this.internalTrack.info.colorSpace)) { + const colorSpace = extractColorSpace(codecInfo); + (_a = this.internalTrack.info.colorSpace).primaries ?? (_a.primaries = colorSpace.primaries); + (_b = this.internalTrack.info.colorSpace).transfer ?? (_b.transfer = colorSpace.transfer); + (_c = this.internalTrack.info.colorSpace).matrix ?? (_c.matrix = colorSpace.matrix); + (_d = this.internalTrack.info.colorSpace).fullRange ?? (_d.fullRange = colorSpace.fullRange); + } const config = { - codec: extractVideoCodecString({ - 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, - // We don't know better (or do we?) so just assume 'avc1' - avcCodecInfo: this.internalTrack.info.codec === "avc" && firstPacket ? extractAvcDecoderConfigurationRecord(firstPacket.data) : null, - hevcCodecInfo: this.internalTrack.info.codec === "hevc" && firstPacket ? extractHevcDecoderConfigurationRecord(firstPacket.data) : null, - vp9CodecInfo: this.internalTrack.info.codec === "vp9" && firstPacket ? extractVp9CodecInfoFromPacket(firstPacket.data) : null, - av1CodecInfo: this.internalTrack.info.codec === "av1" && firstPacket ? extractAv1CodecInfoFromPacket(firstPacket.data) : null - }), + codec: extractVideoCodecString(codecInfo), codedWidth: this.internalTrack.info.width, codedHeight: this.internalTrack.info.height, description: this.internalTrack.info.codecDescription ?? void 0, - colorSpace: this.internalTrack.info.colorSpace ?? void 0 + colorSpace: this.internalTrack.info.colorSpace }; if (this.internalTrack.info.width !== this.internalTrack.info.squarePixelWidth || this.internalTrack.info.height !== this.internalTrack.info.squarePixelHeight) { config.displayAspectWidth = this.internalTrack.info.squarePixelWidth; @@ -9016,7 +10036,7 @@ class MatroskaVideoTrackBacking extends MatroskaTrackBacking { class MatroskaAudioTrackBacking extends MatroskaTrackBacking { constructor(internalTrack) { super(internalTrack); - this.decoderConfig = null; + this.decoderConfigPromise = null; this.internalTrack = internalTrack; } getType() { @@ -9035,34 +10055,43 @@ class MatroskaAudioTrackBacking extends MatroskaTrackBacking { if (!this.internalTrack.info.codec) { return null; } - return this.decoderConfig ?? (this.decoderConfig = { - codec: extractAudioCodecString({ - codec: this.internalTrack.info.codec, - codecDescription: this.internalTrack.info.codecDescription, - aacCodecInfo: this.internalTrack.info.aacCodecInfo - }), - numberOfChannels: this.internalTrack.info.numberOfChannels, - sampleRate: this.internalTrack.info.sampleRate, - description: this.internalTrack.info.codecDescription ?? void 0 - }); + return this.decoderConfigPromise ?? (this.decoderConfigPromise = (async () => { + if (this.internalTrack.info.codec === "dts" && !this.internalTrack.info.dtsFormat) { + const firstPacket = await this.getFirstPacket({}); + this.internalTrack.info.dtsFormat = firstPacket && extractDtsFourCcFromPacket(firstPacket.data); + } + return { + codec: extractAudioCodecString({ + 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 + }; + })()); } } -const readNextMp3FrameHeader = async (reader, startPos, until) => { +const readNextMp3FrameHeader = async (reader, startPos, until, ref = null) => { const CHUNK_SIZE = 2 ** 16; let currentPos = startPos; while (until === null || currentPos < until) { const maxLength = until !== null ? Math.min(CHUNK_SIZE, until - currentPos) : CHUNK_SIZE; - let slice = reader.requestSliceRange(currentPos, FRAME_HEADER_SIZE, maxLength); - if (slice instanceof Promise) + let slice = reader.requestSliceRange(currentPos, MP3_FRAME_HEADER_SIZE, maxLength); + if (isThenable(slice)) slice = await slice; - if (!slice || slice.length < FRAME_HEADER_SIZE) + if (!slice || slice.length < MP3_FRAME_HEADER_SIZE) break; - while (slice.remainingLength >= FRAME_HEADER_SIZE) { + while (slice.remainingLength >= MP3_FRAME_HEADER_SIZE) { const posBeforeRead = slice.filePos; const word = readU32Be(slice); const remainingBytes = reader.fileSize !== null ? reader.fileSize - currentPos : null; const result = readMp3FrameHeader(word, remainingBytes); - if (result.header) { + if (result.header && (!ref || // This condition helps us recover malformed streams + // https://stackoverflow.com/a/20884944 + result.header.sampleRate === ref.sampleRate && result.header.mpegVersionId === ref.mpegVersionId && result.header.layer === ref.layer && getMp3ChannelCount(result.header.channel) === getMp3ChannelCount(ref.channel))) { return { header: result.header, startPos: currentPos }; } slice.filePos = posBeforeRead + result.bytesAdvanced; @@ -9077,6 +10106,8 @@ class Mp3Demuxer extends Demuxer { this.metadataPromise = null; this.firstFrameHeader = null; this.firstFrameHeaderPos = null; + this.xingFrameHeader = null; + this.xingFrameHeaderPos = null; this.loadedSamples = []; this.metadataTags = null; this.xingData = null; @@ -9092,6 +10123,10 @@ class Mp3Demuxer extends Demuxer { while (!this.firstFrameHeader && !this.lastSampleLoaded) { await this.advanceReader(); } + if (!this.firstFrameHeader && this.xingFrameHeader) { + this.firstFrameHeader = this.xingFrameHeader; + this.firstFrameHeaderPos = this.xingFrameHeaderPos; + } if (!this.firstFrameHeader) { throw new Error("No valid MP3 frame found."); } @@ -9102,7 +10137,7 @@ class Mp3Demuxer extends Demuxer { if (this.lastLoadedPos === 0) { while (true) { let slice2 = this.reader.requestSlice(this.lastLoadedPos, ID3_V2_HEADER_SIZE); - if (slice2 instanceof Promise) + if (isThenable(slice2)) slice2 = await slice2; if (!slice2) { this.lastSampleLoaded = true; @@ -9115,7 +10150,7 @@ class Mp3Demuxer extends Demuxer { this.lastLoadedPos = slice2.filePos + id3V2Header.size; } } - const result = await readNextMp3FrameHeader(this.reader, this.lastLoadedPos, this.reader.fileSize); + const result = await readNextMp3FrameHeader(this.reader, this.lastLoadedPos, this.reader.fileSize, this.firstFrameHeader); if (!result) { this.lastSampleLoaded = true; return; @@ -9124,15 +10159,19 @@ class Mp3Demuxer extends Demuxer { this.lastLoadedPos = result.startPos + header.totalSize - 1; const xingOffset = getXingOffset(header.mpegVersionId, header.channel); let slice = this.reader.requestSlice(result.startPos + xingOffset, 4); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (slice) { const word = readU32Be(slice); const isXing = word === XING || word === INFO; if (isXing) { + if (!this.xingFrameHeader) { + this.xingFrameHeader = header; + this.xingFrameHeaderPos = result.startPos; + } if (!this.xingData) { let xingDataSlice = this.reader.requestSlice(result.startPos + xingOffset + 4, 12); - if (xingDataSlice instanceof Promise) + if (isThenable(xingDataSlice)) xingDataSlice = await xingDataSlice; if (xingDataSlice) { const xingData = readBytes(xingDataSlice, 12); @@ -9151,9 +10190,6 @@ class Mp3Demuxer extends Demuxer { this.firstFrameHeader = header; this.firstFrameHeaderPos = result.startPos; } - if (header.sampleRate !== this.firstFrameHeader.sampleRate) { - console.warn(`MP3 changed sample rate mid-file: ${this.firstFrameHeader.sampleRate} Hz to ${header.sampleRate} Hz. Might be a bug, so please report this file.`); - } const sampleDuration = header.audioSamplesInFrame / this.firstFrameHeader.sampleRate; const sample = { timestamp: this.nextTimestampInSamples / this.firstFrameHeader.sampleRate, @@ -9184,7 +10220,7 @@ class Mp3Demuxer extends Demuxer { let id3V2HeaderFound = false; while (true) { let headerSlice = this.reader.requestSlice(currentPos, ID3_V2_HEADER_SIZE); - if (headerSlice instanceof Promise) + if (isThenable(headerSlice)) headerSlice = await headerSlice; if (!headerSlice) break; @@ -9194,7 +10230,7 @@ class Mp3Demuxer extends Demuxer { } id3V2HeaderFound = true; let contentSlice = this.reader.requestSlice(headerSlice.filePos, id3V2Header.size); - if (contentSlice instanceof Promise) + if (isThenable(contentSlice)) contentSlice = await contentSlice; if (!contentSlice) break; @@ -9203,7 +10239,7 @@ class Mp3Demuxer extends Demuxer { } if (!id3V2HeaderFound && this.reader.fileSize !== null && this.reader.fileSize >= ID3_V1_TAG_SIZE) { let slice = this.reader.requestSlice(this.reader.fileSize - ID3_V1_TAG_SIZE, ID3_V1_TAG_SIZE); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; assert(slice); const tag = readAscii(slice, 3); @@ -9237,6 +10273,9 @@ class Mp3AudioTrackBacking { isRelativeToUnixEpoch() { return false; } + getUnixTimeForTimestamp() { + return null; + } getPairingMask() { return 1n; } @@ -9280,7 +10319,7 @@ class Mp3AudioTrackBacking { } getNumberOfChannels() { assert(this.demuxer.firstFrameHeader); - return this.demuxer.firstFrameHeader.channel === 3 ? 1 : 2; + return getMp3ChannelCount(this.demuxer.firstFrameHeader.channel); } getSampleRate() { assert(this.demuxer.firstFrameHeader); @@ -9295,7 +10334,7 @@ class Mp3AudioTrackBacking { assert(this.demuxer.firstFrameHeader); return { codec: "mp3", - numberOfChannels: this.demuxer.firstFrameHeader.channel === 3 ? 1 : 2, + numberOfChannels: getMp3ChannelCount(this.demuxer.firstFrameHeader.channel), sampleRate: this.demuxer.firstFrameHeader.sampleRate }; } @@ -9312,7 +10351,7 @@ class Mp3AudioTrackBacking { data = PLACEHOLDER_DATA; } else { let slice = this.demuxer.reader.requestSlice(rawSample.dataStart, rawSample.dataSize); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) { return null; @@ -9498,7 +10537,7 @@ class OggDemuxer extends Demuxer { let currentPos = 0; while (true) { let slice = this.reader.requestSliceRange(currentPos, MIN_PAGE_HEADER_SIZE, MAX_PAGE_HEADER_SIZE); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) break; @@ -9633,7 +10672,7 @@ class OggDemuxer extends Demuxer { const chunks = []; outer: while (true) { let pageSlice = this.reader.requestSlice(currentPage.dataStartPos, currentPage.dataSize); - if (pageSlice instanceof Promise) + if (isThenable(pageSlice)) pageSlice = await pageSlice; assert(pageSlice); const pageData = readBytes(pageSlice, currentPage.dataSize); @@ -9653,7 +10692,7 @@ class OggDemuxer extends Demuxer { let currentPos = currentPage.headerStartPos + currentPage.totalSize; while (true) { let headerSlice = this.reader.requestSliceRange(currentPos, MIN_PAGE_HEADER_SIZE, MAX_PAGE_HEADER_SIZE); - if (headerSlice instanceof Promise) + if (isThenable(headerSlice)) headerSlice = await headerSlice; if (!headerSlice) { return null; @@ -9700,7 +10739,7 @@ class OggDemuxer extends Demuxer { let currentPos = lastPacket.endPage.headerStartPos + lastPacket.endPage.totalSize; while (true) { let slice = this.reader.requestSliceRange(currentPos, MIN_PAGE_HEADER_SIZE, MAX_PAGE_HEADER_SIZE); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) { return null; @@ -9763,6 +10802,9 @@ class OggAudioTrackBacking { isRelativeToUnixEpoch() { return false; } + getUnixTimeForTimestamp() { + return null; + } getPairingMask() { return 1n; } @@ -9886,7 +10928,7 @@ class OggAudioTrackBacking { while (true) { const until = Math.min(searchStartPos + MAX_PAGE_SIZE, high - MIN_PAGE_HEADER_SIZE); let searchSlice = this.demuxer.reader.requestSlice(searchStartPos, until - searchStartPos); - if (searchSlice instanceof Promise) + if (isThenable(searchSlice)) searchSlice = await searchSlice; assert(searchSlice); const found = findNextPageHeader(searchSlice, until); @@ -9895,7 +10937,7 @@ class OggAudioTrackBacking { continue outer; } let headerSlice = this.demuxer.reader.requestSliceRange(searchSlice.filePos, MIN_PAGE_HEADER_SIZE, MAX_PAGE_HEADER_SIZE); - if (headerSlice instanceof Promise) + if (isThenable(headerSlice)) headerSlice = await headerSlice; assert(headerSlice); const page = readPageHeader(headerSlice); @@ -9905,7 +10947,7 @@ class OggAudioTrackBacking { pageValid = true; } else { let pageSlice = this.demuxer.reader.requestSlice(page.headerStartPos, page.totalSize); - if (pageSlice instanceof Promise) + if (isThenable(pageSlice)) pageSlice = await pageSlice; assert(pageSlice); const bytes = readBytes(pageSlice, page.totalSize); @@ -9951,7 +10993,7 @@ class OggAudioTrackBacking { } const nextPos = currentPage.headerStartPos + currentPage.totalSize; let slice = this.demuxer.reader.requestSliceRange(nextPos, MIN_PAGE_HEADER_SIZE, MAX_PAGE_HEADER_SIZE); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; assert(slice); const nextPage = readPageHeader(slice); @@ -10179,7 +11221,7 @@ class WaveDemuxer extends Demuxer { async readMetadata() { return this.metadataPromise ?? (this.metadataPromise = (async () => { let slice = this.reader.requestSlice(0, 12); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; assert(slice); const riffType = readAscii(slice, 4); @@ -10196,7 +11238,7 @@ class WaveDemuxer extends Demuxer { let currentPos = slice.filePos; while (totalFileSize === null || currentPos < totalFileSize) { let slice2 = this.reader.requestSlice(currentPos, 8); - if (slice2 instanceof Promise) + if (isThenable(slice2)) slice2 = await slice2; if (!slice2) break; @@ -10217,7 +11259,7 @@ class WaveDemuxer extends Demuxer { } } else if (chunkId === "ds64") { let ds64Slice = this.reader.requestSlice(startPos, chunkSize); - if (ds64Slice instanceof Promise) + if (isThenable(ds64Slice)) ds64Slice = await ds64Slice; if (!ds64Slice) break; @@ -10245,7 +11287,7 @@ class WaveDemuxer extends Demuxer { } async parseFmtChunk(startPos, size, littleEndian) { let slice = this.reader.requestSlice(startPos, size); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) return; @@ -10273,6 +11315,15 @@ class WaveDemuxer extends Demuxer { if (formatTag === WaveFormat.MULAW || formatTag === WaveFormat.ALAW) { bitsPerSample = 8; } + if (formatTag !== WaveFormat.PCM && formatTag !== WaveFormat.IEEE_FLOAT && formatTag !== WaveFormat.ALAW && formatTag !== WaveFormat.MULAW) { + throw new Error(`Unsupported WAVE codec (format tag ${formatTag}). Only integer/float PCM, A-law, and μ-law are supported.`); + } + if (formatTag === WaveFormat.PCM && ![8, 16, 24, 32].includes(bitsPerSample)) { + throw new Error(`Unsupported WAVE PCM bit depth (${bitsPerSample}). Only 8, 16, 24, and 32 bits are supported.`); + } + if (formatTag === WaveFormat.IEEE_FLOAT && ![32, 64].includes(bitsPerSample)) { + throw new Error(`Unsupported WAVE float bit depth (${bitsPerSample}). Only 32 and 64 bits are supported.`); + } this.audioInfo = { format: formatTag, numberOfChannels: numChannels, @@ -10284,7 +11335,7 @@ class WaveDemuxer extends Demuxer { async parseListChunk(startPos, size, littleEndian) { var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k; let slice = this.reader.requestSlice(startPos, size); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) return; @@ -10381,7 +11432,7 @@ class WaveDemuxer extends Demuxer { } async parseId3Chunk(startPos, size) { let slice = this.reader.requestSlice(startPos, size); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) return; @@ -10417,9 +11468,11 @@ class WaveDemuxer extends Demuxer { if (this.audioInfo.format === WaveFormat.IEEE_FLOAT) { if (this.audioInfo.sampleSizeInBytes === 4) { return "pcm-f32"; + } else if (this.audioInfo.sampleSizeInBytes === 8) { + return "pcm-f64"; } } - return null; + assert(false); } async getMimeType() { return "audio/wav"; @@ -10481,6 +11534,9 @@ class WaveAudioTrackBacking { isRelativeToUnixEpoch() { return false; } + getUnixTimeForTimestamp() { + return null; + } getPairingMask() { return 1n; } @@ -10518,7 +11574,7 @@ class WaveAudioTrackBacking { const sizeInBytes = Math.min(PACKET_SIZE_IN_FRAMES * this.demuxer.audioInfo.blockSizeInBytes, this.demuxer.dataSize - startOffset); if (this.demuxer.reader.fileSize === null) { let slice = this.demuxer.reader.requestSlice(this.demuxer.dataStart + startOffset, sizeInBytes); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) { return null; @@ -10529,7 +11585,7 @@ class WaveAudioTrackBacking { data = PLACEHOLDER_DATA; } else { let slice = this.demuxer.reader.requestSlice(this.demuxer.dataStart + startOffset, sizeInBytes); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; assert(slice); data = readBytes(slice, sizeInBytes); @@ -10658,7 +11714,7 @@ class AdtsDemuxer extends Demuxer { if (this.lastLoadedPos === 0) { while (true) { let slice2 = this.reader.requestSlice(this.lastLoadedPos, ID3_V2_HEADER_SIZE); - if (slice2 instanceof Promise) + if (isThenable(slice2)) slice2 = await slice2; if (!slice2) { this.lastSampleLoaded = true; @@ -10672,7 +11728,7 @@ class AdtsDemuxer extends Demuxer { } } let slice = this.reader.requestSliceRange(this.lastLoadedPos, MIN_ADTS_FRAME_HEADER_SIZE, MAX_ADTS_FRAME_HEADER_SIZE); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) { this.lastSampleLoaded = true; @@ -10721,7 +11777,7 @@ class AdtsDemuxer extends Demuxer { let currentPos = 0; while (true) { let headerSlice = this.reader.requestSlice(currentPos, ID3_V2_HEADER_SIZE); - if (headerSlice instanceof Promise) + if (isThenable(headerSlice)) headerSlice = await headerSlice; if (!headerSlice) break; @@ -10730,7 +11786,7 @@ class AdtsDemuxer extends Demuxer { break; } let contentSlice = this.reader.requestSlice(headerSlice.filePos, id3V2Header.size); - if (contentSlice instanceof Promise) + if (isThenable(contentSlice)) contentSlice = await contentSlice; if (!contentSlice) break; @@ -10763,6 +11819,9 @@ class AdtsAudioTrackBacking { isRelativeToUnixEpoch() { return false; } + getUnixTimeForTimestamp() { + return null; + } getPairingMask() { return 1n; } @@ -10829,7 +11888,7 @@ class AdtsAudioTrackBacking { data = PLACEHOLDER_DATA; } else { let slice = this.demuxer.reader.requestSlice(rawSample.dataStart, rawSample.dataSize); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) { return null; @@ -11037,12 +12096,32 @@ class FlacDemuxer extends Demuxer { return "audio/flac"; } async readMetadata() { - let currentPos = 4; return this.metadataPromise ?? (this.metadataPromise = (async () => { var _a; + let currentPos = 0; + while (true) { + let headerSlice = this.reader.requestSlice(currentPos, ID3_V2_HEADER_SIZE); + if (isThenable(headerSlice)) + headerSlice = await headerSlice; + if (!headerSlice) { + this.lastSampleLoaded = true; + return; + } + const id3V2Header = readId3V2Header(headerSlice); + if (!id3V2Header) { + break; + } + let contentSlice = this.reader.requestSlice(headerSlice.filePos, id3V2Header.size); + if (isThenable(contentSlice)) + contentSlice = await contentSlice; + assert(contentSlice); + parseId3V2Tag(contentSlice, id3V2Header, this.metadataTags); + currentPos = headerSlice.filePos + id3V2Header.size; + } + currentPos += 4; while (this.reader.fileSize === null || currentPos < this.reader.fileSize) { let sizeSlice = this.reader.requestSlice(currentPos, 4); - if (sizeSlice instanceof Promise) + if (isThenable(sizeSlice)) sizeSlice = await sizeSlice; currentPos += 4; if (sizeSlice === null) { @@ -11056,7 +12135,7 @@ class FlacDemuxer extends Demuxer { switch (metaBlockType) { case FlacBlockType.STREAMINFO: { let streamInfoBlock = this.reader.requestSlice(currentPos, size); - if (streamInfoBlock instanceof Promise) + if (isThenable(streamInfoBlock)) streamInfoBlock = await streamInfoBlock; assert(streamInfoBlock); if (streamInfoBlock === null) { @@ -11092,7 +12171,7 @@ class FlacDemuxer extends Demuxer { } case FlacBlockType.VORBIS_COMMENT: { let vorbisCommentBlock = this.reader.requestSlice(currentPos, size); - if (vorbisCommentBlock instanceof Promise) + if (isThenable(vorbisCommentBlock)) vorbisCommentBlock = await vorbisCommentBlock; assert(vorbisCommentBlock); readVorbisComments(readBytes(vorbisCommentBlock, size), this.metadataTags); @@ -11100,7 +12179,7 @@ class FlacDemuxer extends Demuxer { } case FlacBlockType.PICTURE: { let pictureBlock = this.reader.requestSlice(currentPos, size); - if (pictureBlock instanceof Promise) + if (isThenable(pictureBlock)) pictureBlock = await pictureBlock; assert(pictureBlock); const pictureType = readU32Be(pictureBlock); @@ -11334,6 +12413,9 @@ class FlacAudioTrackBacking { isRelativeToUnixEpoch() { return false; } + getUnixTimeForTimestamp() { + return null; + } getPairingMask() { return 1n; } @@ -11370,7 +12452,7 @@ class FlacAudioTrackBacking { async getPacket(timestamp, options) { assert(this.demuxer.audioInfo); if (timestamp < 0) { - throw new Error("Timestamp cannot be negative"); + return null; } const release = await this.demuxer.readingMutex.acquire(); try { @@ -11427,7 +12509,7 @@ class FlacAudioTrackBacking { data = PLACEHOLDER_DATA; } else { let slice = this.demuxer.reader.requestSlice(rawSample.byteOffset, rawSample.byteSize); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) { return null; @@ -11447,6 +12529,7 @@ class FlacAudioTrackBacking { } } const TIMESCALE = 9e4; +const TIMESTAMP_MODULUS = 2 ** 33; const TS_PACKET_SIZE = 188; const buildMpegTsMimeType = (codecStrings) => { let string = "video/MP2T"; @@ -11457,6 +12540,15 @@ const buildMpegTsMimeType = (codecStrings) => { return string; }; const MISSING_PTS_ERROR_MESSAGE = "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."; +const REGISTRATION_DESCRIPTOR_TAG = 5; +const HDMV_FORMAT_IDENTIFIER = 1212435798; +const HDPR_FORMAT_IDENTIFIER = 1212436562; +const DTS_FORMAT_IDENTIFIER_PREFIX = 1146376960; +const BLU_RAY_DTS_STREAM_TYPES = /* @__PURE__ */ new Set([ + 133, + 134, + 162 +]); const ignoredStreamTypes = /* @__PURE__ */ new Set(); class MpegTsDemuxer extends Demuxer { constructor(input) { @@ -11469,13 +12561,14 @@ class MpegTsDemuxer extends Demuxer { this.sectionEndPositions = []; this.seekChunkSize = 5 * 1024 * 1024; this.minReferencePointByteDistance = -1; + this.timestampWrapInfo = null; this.reader = input._reader; } async readMetadata() { return this.metadataPromise ?? (this.metadataPromise = (async () => { const lengthToCheck = TS_PACKET_SIZE + 16 + 1; let startingSlice = this.reader.requestSlice(0, lengthToCheck); - if (startingSlice instanceof Promise) + if (isThenable(startingSlice)) startingSlice = await startingSlice; assert(startingSlice); const startingBytes = readBytes(startingSlice, lengthToCheck); @@ -11506,6 +12599,10 @@ class MpegTsDemuxer extends Demuxer { currentPos += this.packetStride; continue; } + if (hasProgramMap && !this.elementaryStreams.some((x) => x.pid === packetHeader.pid)) { + currentPos += this.packetStride; + continue; + } const section = await this.readSection(currentPos, true, !hasProgramMap); if (!section) { break; @@ -11556,7 +12653,19 @@ class MpegTsDemuxer extends Demuxer { bitstream.readBits(13); bitstream.skipBits(6); const programInfoLength = bitstream.readBits(10); - bitstream.skipBits(8 * programInfoLength); + const programInfoEndPos = bitstream.pos + 8 * programInfoLength; + let isBluRayProgram = false; + while (bitstream.pos < programInfoEndPos) { + const descriptorTag = bitstream.readBits(8); + const descriptorLength = bitstream.readBits(8); + const descriptorEndPos = bitstream.pos + 8 * descriptorLength; + if (descriptorTag === REGISTRATION_DESCRIPTOR_TAG && descriptorLength >= 4) { + const formatIdentifier = bitstream.readBits(32); + isBluRayProgram || (isBluRayProgram = formatIdentifier === HDMV_FORMAT_IDENTIFIER || formatIdentifier === HDPR_FORMAT_IDENTIFIER); + } + bitstream.pos = descriptorEndPos; + } + bitstream.pos = programInfoEndPos; while (8 * (sectionLength + BYTES_BEFORE_SECTION_LENGTH) - bitstream.pos > BITS_IN_CRC_32) { const streamType = bitstream.readBits(8); bitstream.skipBits(3); @@ -11566,18 +12675,26 @@ class MpegTsDemuxer extends Demuxer { const esInfoEndPos = bitstream.pos + 8 * esInfoLength; let hasAc3Descriptor = false; let hasEac3Descriptor = false; + let hasDtsDescriptor = false; while (bitstream.pos < esInfoEndPos) { const descriptorTag = bitstream.readBits(8); const descriptorLength = bitstream.readBits(8); + const descriptorEndPos = bitstream.pos + 8 * descriptorLength; if (descriptorTag === 106) { hasAc3Descriptor = true; } else if (descriptorTag === 122 || descriptorTag === 204) { hasEac3Descriptor = true; + } else if (descriptorTag === 123) { + hasDtsDescriptor = true; + } else if (descriptorTag === REGISTRATION_DESCRIPTOR_TAG && descriptorLength >= 4) { + const formatIdentifier = bitstream.readBits(32); + hasDtsDescriptor || (hasDtsDescriptor = (formatIdentifier & 4294967040) === DTS_FORMAT_IDENTIFIER_PREFIX); } - bitstream.skipBits(8 * descriptorLength); + bitstream.pos = descriptorEndPos; } let info = null; - switch (streamType) { + const effectiveStreamType = isBluRayProgram && BLU_RAY_DTS_STREAM_TYPES.has(streamType) ? 130 : streamType; + switch (effectiveStreamType) { case 27: case 36: { @@ -11607,24 +12724,27 @@ class MpegTsDemuxer extends Demuxer { case 15: case 129: case 135: + case 130: + case 138: { let codec; - if (streamType === 3 || streamType === 4) { + if (effectiveStreamType === 3 || effectiveStreamType === 4) { codec = "mp3"; - } else if (streamType === 15) { + } else if (effectiveStreamType === 15) { codec = "aac"; - } else if (streamType === 129) { + } else if (effectiveStreamType === 129) { codec = "ac3"; - } else if (streamType === 135) { + } else if (effectiveStreamType === 135) { codec = "eac3"; } else { - throw new Error("Unreachable."); + codec = "dts"; } info = { type: "audio", codec, decoderConfig: null, aacCodecInfo: null, + dtsFormat: null, numberOfChannels: -1, sampleRate: -1 }; @@ -11638,6 +12758,7 @@ class MpegTsDemuxer extends Demuxer { codec: "eac3", decoderConfig: null, aacCodecInfo: null, + dtsFormat: null, numberOfChannels: -1, sampleRate: -1 }; @@ -11647,6 +12768,17 @@ class MpegTsDemuxer extends Demuxer { codec: "ac3", decoderConfig: null, aacCodecInfo: null, + dtsFormat: null, + numberOfChannels: -1, + sampleRate: -1 + }; + } else if (hasDtsDescriptor) { + info = { + type: "audio", + codec: "dts", + decoderConfig: null, + aacCodecInfo: null, + dtsFormat: null, numberOfChannels: -1, sampleRate: -1 }; @@ -11655,7 +12787,7 @@ class MpegTsDemuxer extends Demuxer { break; default: { if (!ignoredStreamTypes.has(streamType)) { - console.warn(`Note: MPEG-TS streams with stream_type 0x${streamType.toString(16)} are not currently supported.`); + Logging._warn(`Note: MPEG-TS streams with stream_type 0x${streamType.toString(16)} are not currently supported.`); ignoredStreamTypes.add(streamType); } } @@ -11677,7 +12809,7 @@ class MpegTsDemuxer extends Demuxer { } else { const elementaryStream = this.elementaryStreams.find((x) => x.pid === section.pid); outer: if (elementaryStream && !elementaryStream.initialized) { - const pesPacket = readPesPacket(section, true); + const pesPacket = readPesPacket(this, section, true); if (!pesPacket) { throw new Error(`Couldn't read first PES packet for Elementary Stream with PID ${elementaryStream.pid}`); } @@ -11774,7 +12906,8 @@ class MpegTsDemuxer extends Demuxer { avcCodecInfo: elementaryStream.info.avcCodecInfo, hevcCodecInfo: elementaryStream.info.hevcCodecInfo, vp9CodecInfo: null, - av1CodecInfo: null + av1CodecInfo: null, + proresFormat: null }), codedWidth: elementaryStream.info.width, codedHeight: elementaryStream.info.height, @@ -11808,7 +12941,7 @@ class MpegTsDemuxer extends Demuxer { if (!result.header) { throw new Error("Invalid MP3 audio stream; could not read frame header from first packet."); } - elementaryStream.info.numberOfChannels = result.header.channel === 3 ? 1 : 2; + elementaryStream.info.numberOfChannels = getMp3ChannelCount(result.header.channel); elementaryStream.info.sampleRate = result.header.sampleRate; } else if (elementaryStream.info.codec === "ac3") { const frameInfo = parseAc3SyncFrame(context.suppliedPacket.data); @@ -11831,6 +12964,16 @@ class MpegTsDemuxer extends Demuxer { } elementaryStream.info.numberOfChannels = getEac3ChannelCount(frameInfo); elementaryStream.info.sampleRate = sampleRate; + } else if (elementaryStream.info.codec === "dts") { + const frameInfo = parseDtsFrame(context.suppliedPacket.data); + if (!frameInfo) { + throw new Error("Invalid DTS audio stream; could not read frame header from first packet."); + } + elementaryStream.info.numberOfChannels = frameInfo.numberOfChannels; + elementaryStream.info.sampleRate = frameInfo.sampleRate; + if (frameInfo.core) { + elementaryStream.info.dtsFormat = frameInfo.hasExtensions ? "dtsh" : "dtsc"; + } } else { throw new Error("Unhandled."); } @@ -11838,7 +12981,8 @@ class MpegTsDemuxer extends Demuxer { codec: extractAudioCodecString({ codec: elementaryStream.info.codec, codecDescription: null, - aacCodecInfo: elementaryStream.info.aacCodecInfo + aacCodecInfo: elementaryStream.info.aacCodecInfo, + dtsFormat: elementaryStream.info.dtsFormat }), numberOfChannels: elementaryStream.info.numberOfChannels, sampleRate: elementaryStream.info.sampleRate @@ -11860,6 +13004,9 @@ class MpegTsDemuxer extends Demuxer { throw new Error("No Program Map Table found in the file."); } for (const stream of this.elementaryStreams) { + if (!stream.initialized) { + continue; + } if (stream.info.type === "video") { this.trackBackingEntries.push(new MpegTsVideoTrackBacking(stream)); } else { @@ -11969,7 +13116,7 @@ class MpegTsDemuxer extends Demuxer { } async readPacketHeader(pos) { let slice = this.reader.requestSlice(pos, 4); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) { return null; @@ -11991,7 +13138,7 @@ class MpegTsDemuxer extends Demuxer { } async readPacket(pos) { let slice = this.reader.requestSlice(pos, TS_PACKET_SIZE); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) { return null; @@ -12013,8 +13160,22 @@ class MpegTsDemuxer extends Demuxer { body: bytes.subarray(4) }; } + normalizeTimestamp(timestamp) { + if (!this.timestampWrapInfo) { + const tolerance = 60 * TIMESCALE; + this.timestampWrapInfo = { + reference: timestamp - tolerance, + offset: timestamp >= TIMESTAMP_MODULUS - tolerance ? -TIMESTAMP_MODULUS : TIMESTAMP_MODULUS + }; + } + const { reference, offset } = this.timestampWrapInfo; + if (offset < 0 && timestamp >= reference || offset > 0 && timestamp < reference) { + return timestamp + offset; + } + return timestamp; + } } -const readPesPacketHeader = (section, expectPts) => { +const readPesPacketHeader = (demuxer, section, expectPts) => { if (section.payload.byteLength < 3) { return null; } @@ -12040,6 +13201,7 @@ const readPesPacketHeader = (section, expectPts) => { pts += bitstream.readBits(15) * (1 << 15); bitstream.skipBits(1); pts += bitstream.readBits(15); + pts = demuxer.normalizeTimestamp(pts); } else { if (expectPts) { throw new Error(MISSING_PTS_ERROR_MESSAGE); @@ -12052,9 +13214,9 @@ const readPesPacketHeader = (section, expectPts) => { randomAccessIndicator: section.randomAccessIndicator }; }; -const readPesPacket = (section, expectPts) => { +const readPesPacket = (demuxer, section, expectPts) => { assert(section.endPos !== null); - const header = readPesPacketHeader(section, expectPts); + const header = readPesPacketHeader(demuxer, section, expectPts); if (!header) { return null; } @@ -12128,6 +13290,9 @@ class MpegTsTrackBacking { isRelativeToUnixEpoch() { return false; } + getUnixTimeForTimestamp() { + return null; + } getPairingMask() { return 1n; } @@ -12155,7 +13320,7 @@ class MpegTsTrackBacking { async getFirstPacket(options) { const section = this.elementaryStream.firstSection; assert(section); - const pesPacket = readPesPacket(section, true); + const pesPacket = readPesPacket(this.elementaryStream.demuxer, section, true); assert(pesPacket); const context = new PacketReadingContext(this.elementaryStream, pesPacket); const buffer = new PacketBuffer(this, context); @@ -12188,7 +13353,7 @@ class MpegTsTrackBacking { const demuxer = this.elementaryStream.demuxer; const section = await demuxer.readSection(sectionStartPos, true); assert(section); - const pesPacket = readPesPacket(section, true); + const pesPacket = readPesPacket(demuxer, section, true); assert(pesPacket); const context = new PacketReadingContext(this.elementaryStream, pesPacket); buffer = new PacketBuffer(this, context); @@ -12246,7 +13411,7 @@ class MpegTsTrackBacking { if (!section) { return null; } - const pesPacketHeader = readPesPacketHeader(section, false); + const pesPacketHeader = readPesPacketHeader(demuxer, section, false); if (pesPacketHeader && pesPacketHeader.pts !== null) { return { pesPacketHeader, @@ -12260,7 +13425,7 @@ class MpegTsTrackBacking { }; const firstSection = this.elementaryStream.firstSection; assert(firstSection); - const firstPesPacketHeader = readPesPacketHeader(firstSection, true); + const firstPesPacketHeader = readPesPacketHeader(demuxer, firstSection, true); assert(firstPesPacketHeader); if (searchPts < firstPesPacketHeader.pts) { return null; @@ -12308,7 +13473,7 @@ class MpegTsTrackBacking { const retrieveEncodedPacket = async (sectionStartPos, predicate) => { const section = await demuxer.readSection(sectionStartPos, true); assert(section); - const pesPacket = readPesPacket(section, true); + const pesPacket = readPesPacket(demuxer, section, true); assert(pesPacket); const context = new PacketReadingContext(this.elementaryStream, pesPacket); const buffer = new PacketBuffer(this, context); @@ -12350,7 +13515,7 @@ class MpegTsTrackBacking { if (packetHeader.pid === pid && packetHeader.payloadUnitStartIndicator === 1) { const section = await demuxer.readSection(currentPos, false); if (section) { - const nextPesHeader = readPesPacketHeader(section, false); + const nextPesHeader = readPesPacketHeader(demuxer, section, false); if (nextPesHeader && nextPesHeader.pts !== null) { if (nextPesHeader.pts > searchPts) { break outer; @@ -12374,7 +13539,7 @@ class MpegTsTrackBacking { if (packetHeader.pid === pid && packetHeader.payloadUnitStartIndicator === 1) { const section = await demuxer.readSection(pos, false); if (section) { - const header = readPesPacketHeader(section, false); + const header = readPesPacketHeader(demuxer, section, false); if (header && header.pts !== null) { currentPesHeader = header; break; @@ -12414,7 +13579,7 @@ class MpegTsTrackBacking { isKeyPacket = pesHeader.randomAccessIndicator === 1; } else { assert(pesHeaderSection); - const pesPacket = readPesPacket(pesHeaderSection, true); + const pesPacket = readPesPacket(demuxer, pesHeaderSection, true); assert(pesPacket); const context = new PacketReadingContext(this.elementaryStream, pesPacket); await context.markNextPacket(); @@ -12442,7 +13607,7 @@ class MpegTsTrackBacking { if (packetHeader.pid === pid && packetHeader.payloadUnitStartIndicator === 1) { const section = await demuxer.readSection(currentPos, readSectionsInFull); if (section) { - const nextPesHeader = readPesPacketHeader(section, false); + const nextPesHeader = readPesPacketHeader(demuxer, section, false); if (nextPesHeader && nextPesHeader.pts !== null) { pesHeader = nextPesHeader; pesHeaderSection = section; @@ -12467,7 +13632,7 @@ class MpegTsTrackBacking { if (packetHeader.pid === pid && packetHeader.payloadUnitStartIndicator === 1) { const section = await demuxer.readSection(pos, readSectionsInFull); if (section) { - const header = readPesPacketHeader(section, false); + const header = readPesPacketHeader(demuxer, section, false); if (header && header.pts !== null) { startPesHeader = header; break; @@ -12625,7 +13790,7 @@ class PacketReadingContext { if (!nextSection) { return; } - const nextPesPacket = readPesPacket(nextSection, false); + const nextPesPacket = readPesPacket(this.demuxer, nextSection, false); if (nextPesPacket) { pesPacket = nextPesPacket; break; @@ -12712,10 +13877,13 @@ class PacketReadingContext { if (codec !== "avc" && codec !== "hevc") { throw new Error("Unhandled."); } + const nalHeaderSize = codec === "avc" ? 1 : 2; let packetStartPos = null; + let frameStartFound = false; + let lastFirstMacroblockInSlice = 0; while (true) { let remaining = this.ensureBuffered(CHUNK_SIZE); - if (remaining instanceof Promise) + if (isThenable(remaining)) remaining = await remaining; if (remaining === 0) { break; @@ -12731,7 +13899,7 @@ class PacketReadingContext { } i = zeroIndex; const posBeforeZero = chunkStartPos + i; - if (i + 4 >= length) { + if (i + 3 >= length) { this.seekTo(posBeforeZero); break; } @@ -12739,32 +13907,68 @@ class PacketReadingContext { const b2 = chunk[i + 2]; const b3 = chunk[i + 3]; let startCodeLength = 0; - let nalUnitTypeByte = null; if (b1 === 0 && b2 === 0 && b3 === 1) { startCodeLength = 4; - nalUnitTypeByte = chunk[i + 4]; } else if (b1 === 0 && b2 === 1) { startCodeLength = 3; - nalUnitTypeByte = b3; } if (startCodeLength === 0) { i++; continue; } const startCodePos = posBeforeZero; - if (packetStartPos === null) { - packetStartPos = startCodePos; - i += startCodeLength; - continue; + packetStartPos ?? (packetStartPos = startCodePos); + const nalHeaderStart = i + startCodeLength; + const payloadStart = nalHeaderStart + nalHeaderSize; + const AVC_SLICE_HEADER_PEEK_SIZE = 6; + const bytesNeeded = payloadStart + (codec === "avc" ? AVC_SLICE_HEADER_PEEK_SIZE : 1); + if (bytesNeeded > length) { + this.seekTo(posBeforeZero); + break; } - if (nalUnitTypeByte !== null) { - const nalUnitType = codec === "avc" ? extractNalUnitTypeForAvc(nalUnitTypeByte) : extractNalUnitTypeForHevc(nalUnitTypeByte); - const isAud = codec === "avc" ? nalUnitType === AvcNalUnitType.AUD : nalUnitType === HevcNalUnitType.AUD_NUT; - if (isAud) { - const packetLength = startCodePos - packetStartPos; - this.seekTo(packetStartPos); - return this.supplyPacket(packetLength, 0); + const headerByte0 = chunk[nalHeaderStart]; + let nalUnitType; + let isSlice; + let isAccessUnitStart; + if (codec === "avc") { + nalUnitType = extractNalUnitTypeForAvc(headerByte0); + isSlice = nalUnitType === AvcNalUnitType.NON_IDR_SLICE || nalUnitType === AvcNalUnitType.SLICE_DPA || nalUnitType === AvcNalUnitType.IDR; + isAccessUnitStart = nalUnitType === AvcNalUnitType.SEI || nalUnitType === AvcNalUnitType.SPS || nalUnitType === AvcNalUnitType.PPS || nalUnitType === AvcNalUnitType.AUD; + } else { + nalUnitType = extractNalUnitTypeForHevc(headerByte0); + const layerId = (headerByte0 & 1) << 5 | chunk[nalHeaderStart + 1] >> 3; + if (layerId > 0) { + i += startCodeLength; + continue; } + isSlice = nalUnitType <= HevcNalUnitType.RASL_R || nalUnitType >= HevcNalUnitType.BLA_W_LP && nalUnitType <= 21; + isAccessUnitStart = nalUnitType >= HevcNalUnitType.VPS_NUT && nalUnitType <= 37 || nalUnitType === HevcNalUnitType.PREFIX_SEI_NUT || nalUnitType >= 41 && nalUnitType <= 44 || nalUnitType >= 48 && nalUnitType <= 55; + } + let isFrameBoundary = false; + if (isSlice) { + let startsNewPicture; + if (codec === "avc") { + const headerBytes = chunk.subarray(payloadStart, payloadStart + AVC_SLICE_HEADER_PEEK_SIZE); + const firstMacroblockInSlice = readExpGolomb(new Bitstream(headerBytes)); + startsNewPicture = !frameStartFound || firstMacroblockInSlice <= lastFirstMacroblockInSlice; + lastFirstMacroblockInSlice = firstMacroblockInSlice; + } else { + startsNewPicture = chunk[payloadStart] >> 7 === 1; + } + if (startsNewPicture) { + if (frameStartFound) { + isFrameBoundary = true; + } else { + frameStartFound = true; + } + } + } else if (isAccessUnitStart && frameStartFound) { + isFrameBoundary = true; + } + if (isFrameBoundary) { + const packetLength = startCodePos - packetStartPos; + this.seekTo(packetStartPos); + return this.supplyPacket(packetLength, 0); } i += startCodeLength; } @@ -12772,7 +13976,7 @@ class PacketReadingContext { break; } } - if (packetStartPos !== null) { + if (packetStartPos !== null && this.endPos > packetStartPos) { const packetLength = this.endPos - packetStartPos; this.seekTo(packetStartPos); return this.supplyPacket(packetLength, 0); @@ -12782,7 +13986,7 @@ class PacketReadingContext { const CHUNK_SIZE = 128; while (true) { let remaining = this.ensureBuffered(CHUNK_SIZE); - if (remaining instanceof Promise) + if (isThenable(remaining)) remaining = await remaining; const startPos = this.currentPos; while (this.currentPos - startPos < remaining) { @@ -12794,7 +13998,7 @@ class PacketReadingContext { this.skip(-1); const possibleHeaderStartPos = this.currentPos; let remaining2 = this.ensureBuffered(MAX_ADTS_FRAME_HEADER_SIZE); - if (remaining2 instanceof Promise) + if (isThenable(remaining2)) remaining2 = await remaining2; if (remaining2 < MAX_ADTS_FRAME_HEADER_SIZE) { return; @@ -12804,7 +14008,7 @@ class PacketReadingContext { if (header) { this.seekTo(possibleHeaderStartPos); let remaining3 = this.ensureBuffered(header.frameLength); - if (remaining3 instanceof Promise) + if (isThenable(remaining3)) remaining3 = await remaining3; return this.supplyPacket(remaining3, Math.round(SAMPLES_PER_AAC_FRAME * TIMESCALE / elementaryStream.info.sampleRate)); } else { @@ -12816,19 +14020,19 @@ class PacketReadingContext { } this.skip(-1); const possibleHeaderStartPos = this.currentPos; - let remaining2 = this.ensureBuffered(FRAME_HEADER_SIZE); - if (remaining2 instanceof Promise) + let remaining2 = this.ensureBuffered(MP3_FRAME_HEADER_SIZE); + if (isThenable(remaining2)) remaining2 = await remaining2; - if (remaining2 < FRAME_HEADER_SIZE) { + if (remaining2 < MP3_FRAME_HEADER_SIZE) { return; } - const headerBytes = this.readBytes(FRAME_HEADER_SIZE); + const headerBytes = this.readBytes(MP3_FRAME_HEADER_SIZE); const word = toDataView(headerBytes).getUint32(0); const result = readMp3FrameHeader(word, null); if (result.header) { this.seekTo(possibleHeaderStartPos); let remaining3 = this.ensureBuffered(result.header.totalSize); - if (remaining3 instanceof Promise) + if (isThenable(remaining3)) remaining3 = await remaining3; const duration = result.header.audioSamplesInFrame * TIMESCALE / elementaryStream.info.sampleRate; return this.supplyPacket(remaining3, Math.round(duration)); @@ -12842,7 +14046,7 @@ class PacketReadingContext { this.skip(-1); const possibleSyncPos = this.currentPos; let remaining2 = this.ensureBuffered(5); - if (remaining2 instanceof Promise) + if (isThenable(remaining2)) remaining2 = await remaining2; if (remaining2 < 5) { return; @@ -12862,7 +14066,7 @@ class PacketReadingContext { assert(frameSize !== void 0); this.seekTo(possibleSyncPos); remaining2 = this.ensureBuffered(frameSize); - if (remaining2 instanceof Promise) + if (isThenable(remaining2)) remaining2 = await remaining2; const duration = Math.round(AC3_SAMPLES_PER_FRAME * TIMESCALE / elementaryStream.info.sampleRate); return this.supplyPacket(remaining2, duration); @@ -12873,7 +14077,7 @@ class PacketReadingContext { this.skip(-1); const possibleSyncPos = this.currentPos; let remaining2 = this.ensureBuffered(5); - if (remaining2 instanceof Promise) + if (isThenable(remaining2)) remaining2 = await remaining2; if (remaining2 < 5) { return; @@ -12890,11 +14094,70 @@ class PacketReadingContext { const numblks = EAC3_NUMBLKS_TABLE[numblkscod]; this.seekTo(possibleSyncPos); remaining2 = this.ensureBuffered(frameSize); - if (remaining2 instanceof Promise) + if (isThenable(remaining2)) remaining2 = await remaining2; const samplesPerFrame = numblks * 256; const duration = Math.round(samplesPerFrame * TIMESCALE / elementaryStream.info.sampleRate); return this.supplyPacket(remaining2, duration); + } else if (codec === "dts") { + if (byte !== 127 && byte !== 100) { + continue; + } + this.skip(-1); + const possibleSyncPos = this.currentPos; + let remaining2 = this.ensureBuffered(DTS_CORE_FRAME_HEADER_SIZE); + if (isThenable(remaining2)) + remaining2 = await remaining2; + if (remaining2 < DTS_CORE_FRAME_HEADER_SIZE) { + return; + } + const headerBytes = this.readBytes(DTS_CORE_FRAME_HEADER_SIZE); + const core = parseDtsCoreFrameHeader(headerBytes); + let leadingExss = core ? null : parseDtsExssHeader(headerBytes); + if (!core && !leadingExss) { + this.seekTo(possibleSyncPos + 1); + continue; + } + if (leadingExss && !leadingExss.asset) { + this.seekTo(possibleSyncPos); + const headerBound = Math.min(leadingExss.frameSize, DTS_EXSS_MAX_HEADER_SIZE); + let remaining3 = this.ensureBuffered(headerBound); + if (isThenable(remaining3)) + remaining3 = await remaining3; + leadingExss = parseDtsExssHeader(this.readBytes(remaining3)) ?? leadingExss; + } + let frameSize = core ? core.frameSize : leadingExss.frameSize; + if (core) { + let nextSubstreamPos = Math.ceil(core.frameSize / 4) * 4; + while (true) { + this.seekTo(possibleSyncPos); + const neededBytes = nextSubstreamPos + DTS_EXSS_HEADER_PREFIX_SIZE; + let remaining3 = this.ensureBuffered(neededBytes); + if (isThenable(remaining3)) + remaining3 = await remaining3; + if (remaining3 < neededBytes) { + break; + } + this.seekTo(possibleSyncPos + nextSubstreamPos); + const exss = parseDtsExssHeader(this.readBytes(DTS_EXSS_HEADER_PREFIX_SIZE)); + if (!exss) { + break; + } + nextSubstreamPos += exss.frameSize; + frameSize = nextSubstreamPos; + } + } + const sampleCount = core?.sampleCount ?? leadingExss.asset?.sampleCount; + if (sampleCount === void 0) { + this.seekTo(possibleSyncPos + 1); + continue; + } + this.seekTo(possibleSyncPos); + remaining2 = this.ensureBuffered(frameSize); + if (isThenable(remaining2)) + remaining2 = await remaining2; + const duration = Math.round(sampleCount * TIMESCALE / elementaryStream.info.sampleRate); + return this.supplyPacket(remaining2, duration); } else { throw new Error("Unhandled."); } @@ -13124,6 +14387,15 @@ class SegmentedInput { } return lastSegment.timestamp + lastSegment.duration; } + async getUnixTimeForTimestamp(timestamp) { + let segment = await this.getSegmentAt(timestamp, {}); + segment ?? (segment = await this.getFirstSegment({})); + if (!segment || segment.unixEpochTimestamp === null) { + return null; + } + const elapsed = timestamp - segment.timestamp; + return segment.unixEpochTimestamp + elapsed; + } async getTrackBackings() { return this.trackBackingsPromise ?? (this.trackBackingsPromise = (async () => { const backings = []; @@ -13208,6 +14480,7 @@ class SegmentedInputInputTrackBacking { this.packetInfos = /* @__PURE__ */ new WeakMap(); this.hydrationPromise = null; this.firstInputTrack = null; + this.firstSegment = null; this.segmentedInput = segmentedInput; this.decl = decl; this.number = number; @@ -13219,13 +14492,22 @@ class SegmentedInputInputTrackBacking { if (!this.segmentedInput.firstSegment) { throw new Error("Missing first segment, can't retrieve track."); } - const input = this.segmentedInput.getInputForSegment(this.segmentedInput.firstSegment); - const inputTracks = await input.getTracks(); - const track = inputTracks.find((x) => x.type === this.decl.type && x.number === this.number); + let currentSegment = this.segmentedInput.firstSegment; + let track = null; + while (currentSegment) { + const input = this.segmentedInput.getInputForSegment(currentSegment); + const inputTracks = await input.getTracks(); + track = inputTracks.find((x) => x.type === this.decl.type && x.number === this.number) ?? null; + if (track) { + break; + } + currentSegment = await this.segmentedInput.getNextSegment(currentSegment, {}); + } if (!track) { throw new Error("No matching track found in underlying media data."); } this.firstInputTrack = track; + this.firstSegment = currentSegment; })()); } getId() { @@ -13274,7 +14556,10 @@ class SegmentedInputInputTrackBacking { async isRelativeToUnixEpoch() { await this.hydrate(); assert(this.segmentedInput.firstSegment); - return this.segmentedInput.firstSegment.relativeToUnixEpoch; + return this.segmentedInput.firstSegment.unixEpochTimestamp === this.segmentedInput.firstSegment.timestamp; + } + getUnixTimeForTimestamp(timestamp) { + return this.segmentedInput.getUnixTimeForTimestamp(timestamp); } getBitrate() { return this.delegate(() => this.firstInputTrack._backing.getBitrate()); @@ -13308,13 +14593,28 @@ class SegmentedInputInputTrackBacking { } async getFirstPacket(options) { await this.hydrate(); - assert(this.segmentedInput.firstSegment); assert(this.firstInputTrack); - const packet = await this.firstInputTrack._backing.getFirstPacket(options); - if (!packet) { - return null; + assert(this.firstSegment); + let currentTrack = this.firstInputTrack; + let currentSegment = this.firstSegment; + while (true) { + if (currentTrack) { + const packet = await currentTrack._backing.getFirstPacket(options); + if (packet) { + return this.createAdjustedPacket(packet, currentSegment, currentTrack); + } + } + currentSegment = await this.segmentedInput.getNextSegment(currentSegment, { + skipLiveWait: options.skipLiveWait + }); + if (!currentSegment) { + break; + } + const nextInput = this.segmentedInput.getInputForSegment(currentSegment); + const nextTracks = await nextInput.getTracks(); + currentTrack = nextTracks.find((t) => t.type === this.firstInputTrack.type && t.number === this.firstInputTrack.number) ?? null; } - return this.createAdjustedPacket(packet, this.segmentedInput.firstSegment, this.firstInputTrack); + return null; } getNextPacket(packet, options) { return this._getNextInternal(packet, options, false); @@ -13443,14 +14743,25 @@ class SegmentedInputInputAudioTrackBacking extends SegmentedInputInputTrackBacki polyfillSymbolDispose(); const DEFAULT_MIN_READ_POSITION = 0; const DEFAULT_MAX_READ_POSITION = Infinity; +if (typeof FinalizationRegistry !== "undefined") { + new FinalizationRegistry((cleanup) => { + cleanup(); + }); +} class Source extends EventEmitter { constructor() { - super(...arguments); + super(); this._disposed = false; this._refCount = 0; this._usedForHls = false; + this._refFinalizationRegistry = null; this._sizePromise = null; this.onread = null; + if (typeof FinalizationRegistry !== "undefined") { + this._refFinalizationRegistry = new FinalizationRegistry((source) => { + source._decrementRefCount(); + }); + } } /** * Resolves with the total size of the file in bytes. This function is memoized, meaning only the first call @@ -13516,6 +14827,18 @@ class Source extends EventEmitter { ref() { return new SourceRef(this); } + /** @internal */ + _incrementRefCount() { + this._refCount++; + } + /** @internal */ + _decrementRefCount() { + this._refCount--; + if (this._refCount === 0) { + this._dispose(); + this._disposed = true; + } + } } class SourceRef { /** @internal */ @@ -13524,7 +14847,8 @@ class SourceRef { if (source._disposed) { throw new Error("Cannot ref a disposed source."); } - source._refCount++; + source._incrementRefCount(); + source._refFinalizationRegistry?.register(this, source, this); this._source = source; } /** The {@link Source} this ref references. Accessing this field throws an error after having freed the ref. */ @@ -13548,11 +14872,8 @@ class SourceRef { } const source = this.source; assert(source._refCount > 0); - source._refCount--; - if (source._refCount === 0) { - source._dispose(); - source._disposed = true; - } + source._decrementRefCount(); + source._refFinalizationRegistry?.unregister(this); this._freed = true; this._source = null; } @@ -13589,7 +14910,7 @@ class PathedSource extends Source { (_a = ref.source)._usedForHls || (_a._usedForHls = this._usedForHls); return ref; }; - if (result instanceof Promise) { + if (isThenable(result)) { return result.then(handle); } else { return handle(result); @@ -13616,7 +14937,7 @@ class CustomPathedSource extends PathedSource { this._rootRequest = null; return ref; }; - if (result instanceof Promise) { + if (isThenable(result)) { this._rootRequest = result.then(handle); } else { handle(result); @@ -13645,6 +14966,10 @@ class CustomPathedSource extends PathedSource { } } } +const blobReaderRegistry = typeof FinalizationRegistry !== "undefined" ? new FinalizationRegistry((reader) => { + void reader.cancel().catch(() => { + }); +}) : null; class BlobSource extends Source { /** * Creates a new {@link BlobSource} backed by the specified @@ -13660,14 +14985,31 @@ class BlobSource extends Source { if (options.maxCacheSize !== void 0 && (!isNumber(options.maxCacheSize) || options.maxCacheSize < 0)) { throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number."); } + if (options.useStreamReader !== void 0 && typeof options.useStreamReader !== "boolean") { + throw new TypeError("options.useStreamReader, when provided, must be a boolean."); + } + if (options.handleUnhandledError !== void 0 && typeof options.handleUnhandledError !== "function") { + throw new TypeError("options.handleUnhandledError, when provided, must be a function."); + } super(); this._readers = /* @__PURE__ */ new WeakMap(); this._blob = blob; + this._options = options; this._orchestrator = new ReadOrchestrator({ maxCacheSize: options.maxCacheSize ?? 8 * 2 ** 20, maxWorkerCount: 4, runWorker: this._runWorker.bind(this), - prefetchProfile: PREFETCH_PROFILES.fileSystem + onIdleWorkerRemoved: (worker) => { + const reader = this._readers.get(worker); + if (reader) { + this._readers.delete(worker); + blobReaderRegistry?.unregister(worker); + void reader.cancel().catch(() => { + }); + } + }, + prefetchProfile: PREFETCH_PROFILES.fileSystem, + handleUnhandledError: options.handleUnhandledError }); this._orchestrator.fileSize = blob.size; } @@ -13684,9 +15026,10 @@ class BlobSource extends Source { assert(worker.strictTarget); let reader = this._readers.get(worker); if (reader === void 0) { - if ("stream" in this._blob && !isWebKit()) { + if ("stream" in this._blob && !isWebKit() && this._options.useStreamReader !== false) { const slice = this._blob.slice(worker.currentPos); reader = slice.stream().getReader(); + blobReaderRegistry?.register(worker, reader, worker); } else { reader = null; } @@ -13725,7 +15068,7 @@ class BlobSource extends Source { } const URL_SOURCE_MIN_LOAD_AMOUNT = 0.5 * 2 ** 20; const DEFAULT_RETRY_DELAY = ((previousAttempts, error, src) => { - const couldBeCorsError = error instanceof Error && (error.message.includes("Failed to fetch") || error.message.includes("Load failed") || error.message.includes("NetworkError when attempting to fetch resource")); + const couldBeCorsError = error instanceof Error && (error.message.includes("Failed to fetch") || error.message.includes("Load failed") || error.message.includes("NetworkError when attempting to fetch resource")) && typeof window !== "undefined"; if (couldBeCorsError) { let originOfSrc = null; try { @@ -13736,7 +15079,7 @@ const DEFAULT_RETRY_DELAY = ((previousAttempts, error, src) => { } const isOnline = typeof navigator !== "undefined" && typeof navigator.onLine === "boolean" ? navigator.onLine : true; if (isOnline && originOfSrc !== null && originOfSrc !== window.location.origin) { - console.warn(`Request will not be retried because a CORS error was suspected due to different origins. You can modify this behavior by providing your own function for the 'getRetryDelay' option.`); + Logging._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.`); return null; } } @@ -13747,8 +15090,8 @@ class UrlSource extends PathedSource { /** * Creates a new {@link UrlSource} backed by the resource at the specified URL. * - * When passing a `Request` instance, note that the `signal` and `headers.Range` options will be overridden by - * Mediabunny. If you want to cancel ongoing requests, use {@link Input.dispose}. + * When passing a `Request` instance, note that its `signal` will be overridden by Mediabunny; if you want to cancel + * ongoing requests, use {@link Input.dispose}. */ constructor(url, options = {}) { if (typeof url !== "string" && !(url instanceof URL) && !(typeof Request !== "undefined" && url instanceof Request)) { @@ -13772,33 +15115,90 @@ class UrlSource extends PathedSource { if (options.fetchFn !== void 0 && typeof options.fetchFn !== "function") { throw new TypeError("options.fetchFn, when provided, must be a function."); } + if (options.handleUnhandledError !== void 0 && typeof options.handleUnhandledError !== "function") { + throw new TypeError("options.handleUnhandledError, when provided, must be a function."); + } const urlString = url instanceof Request ? url.url : url instanceof URL ? url.href : url; super(urlString, (request) => new UrlSource(request.path, this._options)); + this._offset = 0; + this._length = null; this._fileSizeDetermined = false; + this._sequentialBacking = null; this._url = url; this._options = options; this._getRetryDelay = options.getRetryDelay ?? DEFAULT_RETRY_DELAY; + this._requestInit = { ...options.requestInit }; + let rangeHeaderValue = null; + if (options.requestInit?.headers) { + const headers = { ...normalizeHeaders(options.requestInit.headers) }; + const rangeKey = Object.keys(headers).find((key) => key.toLowerCase() === "range"); + if (rangeKey !== void 0) { + rangeHeaderValue = headers[rangeKey]; + delete headers[rangeKey]; + this._requestInit.headers = headers; + } + } + if (url instanceof Request) { + const requestRange = url.headers.get("Range"); + if (requestRange !== null) { + rangeHeaderValue ?? (rangeHeaderValue = requestRange); + const strippedRequest = new Request(url); + strippedRequest.headers.delete("Range"); + this._url = strippedRequest; + } + } + if (rangeHeaderValue !== null) { + const parsed = parseByteRangeHeader(rangeHeaderValue); + if (parsed) { + this._offset = parsed.offset; + this._length = parsed.length; + } + } const DEFAULT_PARALLELISM = 2; this._orchestrator = new ReadOrchestrator({ maxCacheSize: options.maxCacheSize ?? 64 * 2 ** 20, maxWorkerCount: options.parallelism ?? DEFAULT_PARALLELISM, runWorker: this._runWorker.bind(this), - prefetchProfile: PREFETCH_PROFILES.network + prefetchProfile: PREFETCH_PROFILES.network, + handleUnhandledError: options.handleUnhandledError }); } /** @internal */ _getFileSize() { - return this._fileSizeDetermined ? this._orchestrator.fileSize : void 0; + if (!this._fileSizeDetermined) { + return this._length !== null ? this._length : void 0; + } + const baseSize = this._sequentialBacking ? this._sequentialBacking._endIndex : this._orchestrator.fileSize; + if (baseSize === null) { + return this._length !== null ? this._length : null; + } + return clamp$1(baseSize - this._offset, 0, this._length ?? Infinity); } /** @internal */ _read(start, end, minReadPosition, maxReadPosition) { - return this._orchestrator.read(start, end, minReadPosition, maxReadPosition); + if (this._length !== null && end > this._length) { + return null; + } + const offset = this._offset; + const result = this._sequentialBacking ? this._sequentialBacking._read(offset + start, offset + end) : this._orchestrator.read(offset + start, offset + end, Math.max(offset + minReadPosition, offset), offset + Math.min(maxReadPosition, this._length ?? Infinity)); + const processResult = (result2) => { + if (!result2) { + return null; + } + result2.offset -= this._offset; + return result2; + }; + if (isThenable(result)) { + return result.then(processResult); + } else { + return processResult(result); + } } /** @internal */ async _runWorker(worker) { while (true) { const abortController = new AbortController(); - const response = await retriedFetch(this._options.fetchFn ?? fetch, this._url, mergeRequestInit(this._options.requestInit ?? {}, { + const response = await retriedFetch(this._options.fetchFn ?? fetch, this._url, mergeRequestInit(this._requestInit, { headers: { // Always sending a range request is a good way to probe if the server supports them Range: `bytes=${worker.currentPos}-` @@ -13808,7 +15208,10 @@ class UrlSource extends PathedSource { if (!response.ok) { throw new Error(`Error fetching ${String(this._url)}: ${response.status} ${response.statusText}`); } - outer: if (this._orchestrator.fileSize === null) { + if (response.redirected) { + this.rootPath = response.url; + } + outer: if (this._orchestrator.fileSize === null && (response.status === 206 || response.type === "basic" && !response.headers.has("Content-Encoding"))) { const contentRange = response.headers.get("Content-Range"); if (contentRange) { const match = /\/(\d+)/.exec(contentRange); @@ -13819,33 +15222,30 @@ class UrlSource extends PathedSource { } const contentLength = response.headers.get("Content-Length"); if (contentLength) { - this._orchestrator.supplyFileSize(worker.currentPos + Number(contentLength)); + const basePos = response.status === 206 ? worker.currentPos : 0; + this._orchestrator.supplyFileSize(basePos + Number(contentLength)); } } this._fileSizeDetermined = true; + if (!response.body) { + throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream."); + } if (response.status !== 206) { + if (this._sequentialBacking) { + void response.body.cancel(); + return; + } if (!this._usedForHls) { const url = new URL(this._url instanceof Request ? this._url.url : this._url, typeof window !== "undefined" ? window.location.href : void 0); if (url.origin !== "null" && !(url.pathname.endsWith(".m3u8") || url.pathname.endsWith(".m3u"))) { if (!warnedOrigins.has(url.origin)) { - console.log(this._usedForHls, this._url, url.pathname); - console.warn(`HTTP server (origin ${url.origin}) did not respond to a range request with 206 Partial Content, meaning the entire resource will now be downloaded. To enable efficient media file streaming across a network, please make sure your server supports range requests.`); + Logging._warn(`HTTP server (origin ${url.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.`); warnedOrigins.add(url.origin); } } } - worker.currentPos = 0; - this._orchestrator.options.maxCacheSize = Infinity; - if (this._orchestrator.fileSize !== null) { - worker.targetPos = this._orchestrator.fileSize; - } else { - worker.targetPos = Infinity; - worker.strictTarget = false; - } - this._orchestrator.consolidateEverythingIntoOneWorker(worker); - } - if (!response.body) { - throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream."); + this._transitionToSequentialMode(response.body); + return; } const reader = response.body.getReader(); while (true) { @@ -13863,7 +15263,7 @@ class UrlSource extends PathedSource { } const retryDelayInSeconds = this._getRetryDelay(1, error, this._url); if (retryDelayInSeconds !== null) { - console.error("Error while reading response stream. Attempting to resume.", error); + Logging._error("Error while reading response stream. Attempting to resume.", error); await wait(1e3 * retryDelayInSeconds); break; } else { @@ -13892,10 +15292,130 @@ class UrlSource extends PathedSource { } } /** @internal */ + _transitionToSequentialMode(body) { + let currentReader = body.getReader(); + let streamPosition = 0; + let skipRemaining = 0; + const wrappedStream = new ReadableStream({ + pull: async (controller) => { + while (true) { + let readResult; + try { + readResult = await currentReader.read(); + } catch (error) { + if (this._disposed) { + throw error; + } + const retryDelayInSeconds = this._getRetryDelay(1, error, this._url); + if (retryDelayInSeconds === null) { + throw error; + } + Logging._error("Error while reading response stream. Attempting to resume.", error); + await wait(1e3 * retryDelayInSeconds); + const newResponse = await retriedFetch(this._options.fetchFn ?? fetch, this._url, mergeRequestInit(this._requestInit, { + headers: { + // Who knows, maybe the server honors range requests this time + Range: `bytes=${streamPosition}-` + } + }), this._getRetryDelay, () => this._disposed); + if (!newResponse.ok) { + throw new Error( + // eslint-disable-next-line @typescript-eslint/no-base-to-string + `Error fetching ${String(this._url)}: ${newResponse.status} ${newResponse.statusText}` + ); + } + if (!newResponse.body) { + throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream."); + } + currentReader = newResponse.body.getReader(); + skipRemaining = newResponse.status === 206 ? 0 : streamPosition; + continue; + } + if (readResult.done) { + controller.close(); + return; + } + let chunk = readResult.value; + if (skipRemaining > 0) { + const skippedAmount = Math.min(skipRemaining, chunk.length); + skipRemaining -= skippedAmount; + chunk = chunk.subarray(skippedAmount); + } + if (chunk.length === 0) { + continue; + } + streamPosition += chunk.length; + controller.enqueue(chunk); + return; + } + }, + cancel: () => currentReader.cancel() + }); + const backing = new ReadableStreamSource(wrappedStream, { + maxCacheSize: this._orchestrator.options.maxCacheSize, + handleUnhandledError: this._options.handleUnhandledError + }); + backing._endIndex = this._orchestrator.fileSize; + backing._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."; + backing.on("read", ({ start, end }) => this._dispatchRead(start, end)); + this._sequentialBacking = backing; + const uniqueSlices = /* @__PURE__ */ new Set(); + for (const otherWorker of this._orchestrator.workers) { + for (const slice of otherWorker.pendingSlices) { + uniqueSlices.add(slice); + } + otherWorker.aborted = true; + otherWorker.pendingSlices.length = 0; + } + for (const queuedRead of this._orchestrator.queuedReads) { + for (const slice of queuedRead.pendingSlices) { + uniqueSlices.add(slice); + } + } + this._orchestrator.workers.length = 0; + this._orchestrator.queuedReads.length = 0; + for (const slice of uniqueSlices) { + const result = backing._read(slice.start, slice.start + slice.bytes.length); + if (isThenable(result)) { + result.then((readResult) => { + if (readResult) { + assert(readResult.offset === slice.start); + slice.resolve(readResult.bytes); + } else { + slice.resolve(null); + } + }, (error) => slice.reject(error)); + } else { + assert(result === null); + slice.resolve(null); + } + } + } + /** @internal */ _dispose() { this._orchestrator.dispose(); + if (this._sequentialBacking) { + this._sequentialBacking._disposed = true; + this._sequentialBacking._dispose(); + } } } +const BYTE_RANGE_REGEX = /^bytes=(\d+)-(\d*)$/; +const parseByteRangeHeader = (value) => { + const match = BYTE_RANGE_REGEX.exec(value.trim()); + if (!match) { + return null; + } + const offset = Number(match[1]); + const end = match[2] === "" ? null : Number(match[2]); + if (end !== null && end < offset) { + return null; + } + return { + offset, + length: end !== null ? end - offset + 1 : null + }; +}; class ReadableStreamSource extends Source { /** Creates a new {@link ReadableStreamSource} backed by the specified `ReadableStream`. */ constructor(stream, options = {}) { @@ -13905,6 +15425,9 @@ class ReadableStreamSource extends Source { if (!options || typeof options !== "object") { throw new TypeError("options must be an object."); } + if (options.handleUnhandledError !== void 0 && typeof options.handleUnhandledError !== "function") { + throw new TypeError("options.handleUnhandledError, when provided, must be a function."); + } if (options.maxCacheSize !== void 0 && (!isNumber(options.maxCacheSize) || options.maxCacheSize < 0)) { throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number."); } @@ -13917,8 +15440,10 @@ class ReadableStreamSource extends Source { this._maxRequestedIndex = 0; this._endIndex = null; this._pulling = false; + this._cacheMissErrorMessage = "Attempted to read data from an already-evicted part of the cache. With ReadableStreamSource, you must access the data more sequentially or increase the size of its cache."; this._stream = stream; - this._maxCacheSize = options.maxCacheSize ?? 16 * 2 ** 20; + this._maxCacheSize = options.maxCacheSize ?? 32 * 2 ** 20; + this._handleUnhandledError = options.handleUnhandledError; } /** @internal */ _getFileSize() { @@ -13984,6 +15509,8 @@ class ReadableStreamSource extends Source { if (this._pendingSlices.length > 0) { this._pendingSlices.forEach((x) => x.reject(error)); this._pendingSlices.length = 0; + } else if (this._handleUnhandledError) { + this._handleUnhandledError(error); } else { throw error; } @@ -13993,7 +15520,7 @@ class ReadableStreamSource extends Source { } /** @internal */ _throwDueToCacheMiss() { - throw new Error("Read is before the cached region. With ReadableStreamSource, you must access the data more sequentially or increase the size of its cache."); + throw new Error(this._cacheMissErrorMessage); } /** @internal */ async _pull() { @@ -14010,6 +15537,7 @@ class ReadableStreamSource extends Source { } const startIndex = this._currentIndex; const endIndex = this._currentIndex + value.byteLength; + this._dispatchRead(startIndex, endIndex); for (let i = 0; i < this._pendingSlices.length; i++) { const pendingSlice = this._pendingSlices[i]; const cappedStart = Math.max(startIndex, pendingSlice.start); @@ -14049,6 +15577,9 @@ class ReadableStreamSource extends Source { } /** @internal */ _dispose() { + for (const pendingSlice of this._pendingSlices) { + pendingSlice.reject(new InputDisposedError()); + } this._pendingSlices.length = 0; this._cache.length = 0; void this._reader?.cancel(); @@ -14237,6 +15768,17 @@ class ReadOrchestrator { view: toDataView(bytes2), offset: innerStart }); + } else { + promise.catch((error) => { + if (this.disposed) { + return; + } + if (this.options.handleUnhandledError) { + this.options.handleUnhandledError(error); + } else { + throw error; + } + }); } return result; } @@ -14286,6 +15828,7 @@ class ReadOrchestrator { assert(oldestIndex !== null); assert(oldestWorker.pendingSlices.length === 0); this.workers.splice(oldestIndex, 1); + this.options.onIdleWorkerRemoved?.(oldestWorker); } else { return null; } @@ -14316,8 +15859,12 @@ class ReadOrchestrator { if (worker.pendingSlices.length > 0) { worker.pendingSlices.forEach((x) => x.reject(error)); worker.pendingSlices.length = 0; - } else { - throw error; + } else if (!worker.aborted && !this.disposed) { + if (this.options.handleUnhandledError) { + this.options.handleUnhandledError(error); + } else { + throw error; + } } }).finally(() => { if (worker.running) { @@ -14332,38 +15879,16 @@ class ReadOrchestrator { } } const queuedRead = this.queuedReads[oldestIndex]; - this.queuedReads.splice(oldestIndex, 1); const newWorker = this.createWorker(queuedRead.hole.start, queuedRead.hole.end, queuedRead.strictTarget); - assert(newWorker); + if (!newWorker) { + return; + } + this.queuedReads.splice(oldestIndex, 1); newWorker.pendingSlices = queuedRead.pendingSlices; this.runWorker(newWorker); } }); } - consolidateEverythingIntoOneWorker(worker) { - const uniqueSlices = new Set(worker.pendingSlices); - for (let i = 0; i < this.workers.length; i++) { - const otherWorker = this.workers[i]; - if (otherWorker === worker) { - continue; - } - for (const slice of otherWorker.pendingSlices) { - uniqueSlices.add(slice); - } - otherWorker.aborted = true; - otherWorker.pendingSlices.length = 0; - this.workers.splice(i, 1); - i--; - } - for (let i = 0; i < this.queuedReads.length; i++) { - const queuedRead = this.queuedReads[i]; - for (const slice of queuedRead.pendingSlices) { - uniqueSlices.add(slice); - } - } - worker.pendingSlices = [...uniqueSlices]; - this.queuedReads.length = 0; - } /** Called by a worker when it has read some data. */ supplyWorkerData(worker, bytes) { assert(!worker.aborted); @@ -14411,6 +15936,7 @@ class ReadOrchestrator { } if (closedIntervalsOverlap(start, end, otherWorker.currentPos, otherWorker.targetPos)) { this.workers.splice(i, 1); + this.options.onIdleWorkerRemoved?.(otherWorker); i--; } } @@ -14456,7 +15982,9 @@ class ReadOrchestrator { } signalWorkerStoppedRunning(worker) { worker.running = false; - worker.pendingSlices.length = 0; + if (!worker.aborted) { + worker.pendingSlices.length = 0; + } } /** Called when a worker reaches the end of the underlying data and must be cleaned up. */ onWorkerFinished(worker) { @@ -14464,6 +15992,7 @@ class ReadOrchestrator { assert(index !== -1); worker.running = false; this.workers.splice(index, 1); + this.options.onIdleWorkerRemoved?.(worker); if (this.fileSize === null) { this.supplyFileSize(worker.currentPos); } @@ -14539,10 +16068,23 @@ class ReadOrchestrator { } dispose() { for (const worker of this.workers) { + for (const slice of worker.pendingSlices) { + slice.reject(new InputDisposedError()); + } + worker.pendingSlices.length = 0; worker.aborted = true; + if (!worker.running) { + this.options.onIdleWorkerRemoved?.(worker); + } + } + for (const queuedRead of this.queuedReads) { + for (const slice of queuedRead.pendingSlices) { + slice.reject(new InputDisposedError()); + } } this.workers.length = 0; this.cache.length = 0; + this.queuedReads.length = 0; this.disposed = true; } } @@ -14579,20 +16121,17 @@ class RangedSource extends Source { return null; } const result = this._baseSource._read(this._offset + start, this._offset + end, this._offset + minReadPosition, this._offset + maxReadPosition); - if (result instanceof Promise) { - return result.then((result2) => { - if (!result2) { - return null; - } - result2.offset -= this._offset; - return result2; - }); - } else { - if (!result) { + const processResult = (result2) => { + if (!result2) { return null; } - result.offset -= this._offset; - return result; + result2.offset -= this._offset; + return result2; + }; + if (isThenable(result)) { + return result.then(processResult); + } else { + return processResult(result); } } /** @internal */ @@ -14604,7 +16143,7 @@ class RangedSource extends Source { return super.ref(); } } -var __addDisposableResource = function(env, value, async) { +var __addDisposableResource$1 = function(env, value, async) { if (value !== null && value !== void 0) { if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); var dispose, inner; @@ -14631,7 +16170,7 @@ var __addDisposableResource = function(env, value, async) { } return value; }; -var __disposeResources = /* @__PURE__ */ (function(SuppressedError2) { +var __disposeResources$1 = /* @__PURE__ */ (function(SuppressedError2) { return function(env) { function fail(e) { env.error = env.hasError ? new SuppressedError2(e, env.error, "An error was suppressed during disposal.") : e; @@ -14673,6 +16212,7 @@ class HlsSegmentedInput extends SegmentedInput { this.streamHasEnded = false; this.lastSegmentUpdateTime = -Infinity; this.refreshInterval = 5; + this.rootPath = path; this.demuxer = demuxer; this.nextLines = lines; } @@ -14708,20 +16248,25 @@ class HlsSegmentedInput extends SegmentedInput { if (!lines) { const env_1 = { stack: [], error: void 0, hasError: false }; try { - const ref = __addDisposableResource(env_1, await this.demuxer.input._getSourceUncached({ path: this.path, isRoot: false }), false); + const ref = __addDisposableResource$1(env_1, await this.demuxer.input._getSourceUncached({ path: this.rootPath, isRoot: false }), false); const reader = new Reader(ref.source); const slice = await reader.requestEntireFile(); assert(slice); lines = readAllLines(slice, slice.length, { ignore: canIgnoreLine }); + if (ref.source instanceof PathedSource) { + this.rootPath = ref.source.rootPath; + } } catch (e_1) { env_1.error = e_1; env_1.hasError = true; } finally { - __disposeResources(env_1); + __disposeResources$1(env_1); } } + const offsetTimestampsByDateTime = this.input._formatOptions.hls?.offsetTimestampsByDateTime !== false; let headerRead = false; let accumulatedTime = 0; + let accumulatedUnixTime = null; let nextSegmentDuration = null; let currentKey = null; let nextSequenceNumber = 0; @@ -14757,6 +16302,7 @@ class HlsSegmentedInput extends SegmentedInput { currentFirstSegment = prevLastSegment.firstSegment; currentInitSegment = prevLastSegment.initSegment; lastProgramDateTimeSeconds = prevLastSegment.lastProgramDateTimeSeconds; + accumulatedUnixTime = prevLastSegment.unixEpochTimestamp !== null ? prevLastSegment.unixEpochTimestamp + prevLastSegment.duration : null; prevLastSegment = null; } } @@ -14783,7 +16329,7 @@ class HlsSegmentedInput extends SegmentedInput { view.setUint32(12, nextSequenceNumber); key = { ...key, iv }; } - const fullPath = joinPaths(this.path, line); + const fullPath = joinPaths(this.rootPath, line); const location = { path: fullPath, offset: nextByteRange?.offset ?? 0, @@ -14791,7 +16337,7 @@ class HlsSegmentedInput extends SegmentedInput { }; const segment = { timestamp: accumulatedTime, - relativeToUnixEpoch: lastProgramDateTimeSeconds !== null, + unixEpochTimestamp: accumulatedUnixTime, firstSegment: currentFirstSegment, sequenceNumber: nextSequenceNumber, location, @@ -14802,6 +16348,9 @@ class HlsSegmentedInput extends SegmentedInput { }; currentFirstSegment ?? (currentFirstSegment = segment); accumulatedTime += nextSegmentDuration; + if (accumulatedUnixTime !== null) { + accumulatedUnixTime += nextSegmentDuration; + } this.segments.push(segment); } nextSegmentDuration = null; @@ -14846,7 +16395,7 @@ class HlsSegmentedInput extends SegmentedInput { throw new Error("Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset."); } if (!prevLastSegment) { - const fullPath = joinPaths(this.path, uri); + const fullPath = joinPaths(this.rootPath, uri); const location = { path: fullPath, offset: parsedByteRange?.offset ?? 0, @@ -14857,7 +16406,7 @@ class HlsSegmentedInput extends SegmentedInput { } const segment = { timestamp: accumulatedTime, - relativeToUnixEpoch: lastProgramDateTimeSeconds !== null, + unixEpochTimestamp: accumulatedUnixTime, firstSegment: null, sequenceNumber: null, location, @@ -14904,7 +16453,7 @@ class HlsSegmentedInput extends SegmentedInput { } currentKey = { method: "AES-128", - keyUri: joinPaths(this.path, uri), + keyUri: joinPaths(this.rootPath, uri), iv, keyFormat }; @@ -14968,13 +16517,17 @@ class HlsSegmentedInput extends SegmentedInput { const lastSegmentEnd = lastSegment.timestamp + lastSegment.duration; const offset = dateTimeSeconds - lastSegmentEnd; for (const segment of this.segments) { - segment.timestamp += offset; - segment.relativeToUnixEpoch = true; + segment.unixEpochTimestamp = segment.timestamp + offset; + if (offsetTimestampsByDateTime) { + segment.timestamp = segment.unixEpochTimestamp; + } } - accumulatedTime += offset; } lastProgramDateTimeSeconds = dateTimeSeconds; - accumulatedTime = dateTimeSeconds; + accumulatedUnixTime = dateTimeSeconds; + if (offsetTimestampsByDateTime) { + accumulatedTime = dateTimeSeconds; + } } else if (line === TAG_DISCONTINUITY) { currentFirstSegment = null; } else if (line.startsWith(TAG_TARGETDURATION)) { @@ -15111,7 +16664,7 @@ class HlsSegmentedInput extends SegmentedInput { const stream = createAes128CbcDecryptStream(ciphertextReader, async () => { const env_2 = { stack: [], error: void 0, hasError: false }; try { - const keyRef = __addDisposableResource(env_2, await this.input._getSourceCached({ path: encryption.keyUri, isRoot: false }, ENCRYPTION_KEY_CACHE_GROUP), false); + const keyRef = __addDisposableResource$1(env_2, await this.input._getSourceCached({ path: encryption.keyUri, isRoot: false }, ENCRYPTION_KEY_CACHE_GROUP), false); const keyReader = new Reader(keyRef.source); const keySlice = await keyReader.requestSlice(0, AES_128_BLOCK_SIZE); if (!keySlice) { @@ -15123,7 +16676,7 @@ class HlsSegmentedInput extends SegmentedInput { env_2.error = e_2; env_2.hasError = true; } finally { - __disposeResources(env_2); + __disposeResources$1(env_2); } }, () => { ciphertextRef.free(); @@ -15176,10 +16729,10 @@ class HlsDemuxer extends Demuxer { readMetadata() { return this.metadataPromise ?? (this.metadataPromise = (async () => { assert(this.input._rootSource instanceof PathedSource); - const { rootPath } = this.input._rootSource; const slice = await this.input._reader.requestEntireFile(); assert(slice); const lines = readAllLines(slice, slice.length, { ignore: canIgnoreLine }); + const { rootPath } = this.input._rootSource; const variantStreams = []; const mediaTags = []; for (let i = 1; i < lines.length; i++) { @@ -15646,6 +17199,9 @@ class HlsInputTrackBacking { isRelativeToUnixEpoch() { return this.delegate(() => this.internalTrack.backingTrack.isRelativeToUnixEpoch()); } + getUnixTimeForTimestamp(timestamp) { + return this.delegate(() => this.internalTrack.backingTrack.getUnixTimeForTimestamp(timestamp)); + } getBitrate() { return this.internalTrack.peakBitrate; } @@ -15829,7 +17385,7 @@ class IsobmffInputFormat extends InputFormat { /** @internal */ async _getMajorBrand(input) { let slice = input._reader.requestSlice(0, 12); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) return null; @@ -15852,12 +17408,37 @@ class Mp4InputFormat extends IsobmffInputFormat { if (majorBrand !== null) { return majorBrand !== "qt "; } - let slice = input._reader.requestSlice(4, 4); - if (slice instanceof Promise) - slice = await slice; - if (!slice) - return false; - return readAscii(slice, 4) === "moof"; + let pos = 0; + for (let iter = 0; iter < 10; iter++) { + let slice = input._reader.requestSlice(pos, 8); + if (isThenable(slice)) + slice = await slice; + if (!slice) + return false; + let size = readU32Be(slice); + let headerSize = 8; + if (size === 1) { + let sizeExtensionSlice = input._reader.requestSlice(pos + 8, 8); + if (isThenable(sizeExtensionSlice)) + sizeExtensionSlice = await sizeExtensionSlice; + if (!sizeExtensionSlice) + return false; + size = readU64Be(sizeExtensionSlice); + headerSize = 16; + } + if (size < headerSize) { + return false; + } + const fourCc = readAscii(slice, 4); + if (fourCc === "moof" || fourCc === "sidx") { + return true; + } else if (fourCc === "emsg" || fourCc === "prft" || fourCc === "free") { + pos += size; + } else { + return false; + } + } + return false; } get name() { return "MP4"; @@ -15883,7 +17464,7 @@ class MatroskaInputFormat extends InputFormat { /** @internal */ async isSupportedEBMLOfDocType(input, desiredDocType) { let headerSlice = input._reader.requestSlice(0, MAX_HEADER_SIZE); - if (headerSlice instanceof Promise) + if (isThenable(headerSlice)) headerSlice = await headerSlice; if (!headerSlice) return false; @@ -15903,7 +17484,7 @@ class MatroskaInputFormat extends InputFormat { return false; } let dataSlice = input._reader.requestSlice(headerSlice.filePos, dataSize); - if (dataSlice instanceof Promise) + if (isThenable(dataSlice)) dataSlice = await dataSlice; if (!dataSlice) return false; @@ -15987,7 +17568,7 @@ class Mp3InputFormat extends InputFormat { let currentPos = 0; while (true) { let slice2 = input._reader.requestSlice(currentPos, ID3_V2_HEADER_SIZE); - if (slice2 instanceof Promise) + if (isThenable(slice2)) slice2 = await slice2; if (!slice2) break; @@ -16004,7 +17585,7 @@ class Mp3InputFormat extends InputFormat { const firstHeader = firstResult.header; const xingOffset = getXingOffset(firstHeader.mpegVersionId, firstHeader.channel); let slice = input._reader.requestSlice(firstResult.startPos + xingOffset, 4); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) return false; @@ -16014,7 +17595,7 @@ class Mp3InputFormat extends InputFormat { return true; } currentPos = firstResult.startPos + firstResult.header.totalSize; - const secondResult = await readNextMp3FrameHeader(input._reader, currentPos, currentPos + FRAME_HEADER_SIZE); + const secondResult = await readNextMp3FrameHeader(input._reader, currentPos, currentPos + MP3_FRAME_HEADER_SIZE); if (!secondResult) { return false; } @@ -16039,7 +17620,7 @@ class WaveInputFormat extends InputFormat { /** @internal */ async _canReadInput(input) { let slice = input._reader.requestSlice(0, 12); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) return false; @@ -16066,7 +17647,7 @@ class OggInputFormat extends InputFormat { /** @internal */ async _canReadInput(input) { let slice = input._reader.requestSlice(0, 4); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) return false; @@ -16086,8 +17667,21 @@ class OggInputFormat extends InputFormat { class FlacInputFormat extends InputFormat { /** @internal */ async _canReadInput(input) { - let slice = input._reader.requestSlice(0, 4); - if (slice instanceof Promise) + let currentPos = 0; + while (true) { + let slice2 = input._reader.requestSlice(currentPos, ID3_V2_HEADER_SIZE); + if (isThenable(slice2)) + slice2 = await slice2; + if (!slice2) + break; + const id3V2Header = readId3V2Header(slice2); + if (!id3V2Header) { + break; + } + currentPos = slice2.filePos + id3V2Header.size; + } + let slice = input._reader.requestSlice(currentPos, 4); + if (isThenable(slice)) slice = await slice; if (!slice) return false; @@ -16110,7 +17704,7 @@ class AdtsInputFormat extends InputFormat { let currentPos = 0; while (true) { let slice2 = input._reader.requestSlice(currentPos, ID3_V2_HEADER_SIZE); - if (slice2 instanceof Promise) + if (isThenable(slice2)) slice2 = await slice2; if (!slice2) break; @@ -16121,7 +17715,7 @@ class AdtsInputFormat extends InputFormat { currentPos = slice2.filePos + id3V2Header.size; } let slice = input._reader.requestSliceRange(currentPos, MIN_ADTS_FRAME_HEADER_SIZE, MAX_ADTS_FRAME_HEADER_SIZE); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) return false; @@ -16131,7 +17725,7 @@ class AdtsInputFormat extends InputFormat { } currentPos += firstHeader.frameLength; slice = input._reader.requestSliceRange(currentPos, MIN_ADTS_FRAME_HEADER_SIZE, MAX_ADTS_FRAME_HEADER_SIZE); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) return false; @@ -16157,7 +17751,7 @@ class MpegTsInputFormat extends InputFormat { async _canReadInput(input) { const lengthToCheck = TS_PACKET_SIZE + 16 + 1; let slice = input._reader.requestSlice(0, lengthToCheck); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) return false; @@ -16186,7 +17780,7 @@ class HlsInputFormat extends InputFormat { /** @internal */ async _canReadInput(input) { let slice = input._reader.requestSlice(0, 7); - if (slice instanceof Promise) + if (isThenable(slice)) slice = await slice; if (!slice) return false; @@ -16236,7 +17830,73 @@ const validateInputFormatOptions = (options, prefix) => { throw new TypeError(`${prefix}.isobmff.resolveKeyId, when provided, must be a function.`); } } + if (options.hls !== void 0) { + if (!options.hls || typeof options.hls !== "object") { + throw new TypeError(`${prefix}.hls, when provided, must be an object.`); + } + if (options.hls.offsetTimestampsByDateTime !== void 0 && typeof options.hls.offsetTimestampsByDateTime !== "boolean") { + throw new TypeError(`${prefix}.hls.offsetTimestampsByDateTime, when provided, must be a boolean.`); + } + } }; +var __addDisposableResource = function(env, value, async) { + if (value !== null && value !== void 0) { + if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); + var dispose, inner; + if (async) { + if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); + dispose = value[Symbol.asyncDispose]; + } + if (dispose === void 0) { + if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); + dispose = value[Symbol.dispose]; + if (async) inner = dispose; + } + if (typeof dispose !== "function") throw new TypeError("Object not disposable."); + if (inner) dispose = function() { + try { + inner.call(this); + } catch (e) { + return Promise.reject(e); + } + }; + env.stack.push({ value, dispose, async }); + } else if (async) { + env.stack.push({ async: true }); + } + return value; +}; +var __disposeResources = /* @__PURE__ */ (function(SuppressedError2) { + return function(env) { + function fail(e) { + env.error = env.hasError ? new SuppressedError2(e, env.error, "An error was suppressed during disposal.") : e; + env.hasError = true; + } + var r, s = 0; + function next() { + while (r = env.stack.pop()) { + try { + if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next); + if (r.dispose) { + var result = r.dispose.call(r.value); + if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { + fail(e); + return next(); + }); + } else s |= 1; + } catch (e) { + fail(e); + } + } + if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve(); + if (env.hasError) throw env.error; + } + return next(); + }; +})(typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; +}); polyfillSymbolDispose(); let lastVideoGcErrorLog = -Infinity; let lastAudioGcErrorLog = -Infinity; @@ -16246,7 +17906,7 @@ if (typeof FinalizationRegistry !== "undefined") { const now = performance.now(); if (value.type === "video") { if (now - lastVideoGcErrorLog >= 1e3) { - console.error(`A VideoSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your VideoSamples as soon as you're done using them.`); + Logging._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.`); lastVideoGcErrorLog = now; } if (typeof VideoFrame !== "undefined" && value.data instanceof VideoFrame) { @@ -16254,7 +17914,7 @@ if (typeof FinalizationRegistry !== "undefined") { } } else { if (now - lastAudioGcErrorLog >= 1e3) { - console.error(`An AudioSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your AudioSamples as soon as you're done using them.`); + Logging._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.`); lastAudioGcErrorLog = now; } if (typeof AudioData !== "undefined" && value.data instanceof AudioData) { @@ -16263,6 +17923,12 @@ if (typeof FinalizationRegistry !== "undefined") { } }); } +class VideoSampleResource { + constructor() { + this._referenceCount = 0; + this._lastAllocationBuffer = null; + } +} const VIDEO_SAMPLE_PIXEL_FORMATS = [ // 4:2:0 Y, U, V "I420", @@ -16384,13 +18050,29 @@ class VideoSample { if (init.displayWidth !== void 0 !== (init.displayHeight !== void 0)) { throw new TypeError("init.displayWidth and init.displayHeight must be either both provided or both omitted."); } - this._data = toUint8Array(data).slice(); - this._layout = init.layout ?? createDefaultPlaneLayout(init.format, init.codedWidth, init.codedHeight); this.format = init.format; this.rotation = init.rotation ?? 0; this.timestamp = init.timestamp; this.duration = init.duration ?? 0; - this.colorSpace = new VideoSampleColorSpace(init.colorSpace); + const layout = init.layout ?? createDefaultPlaneLayout(init.format, init.codedWidth, init.codedHeight); + let colorSpaceInit = init.colorSpace ?? null; + if (colorSpaceInit === null) { + if (this.format === "RGBA" || this.format === "RGBX" || this.format === "BGRA" || this.format === "BGRX") { + colorSpaceInit = { + primaries: "bt709", + transfer: "iec61966-2-1", + matrix: "rgb", + fullRange: true + }; + } else { + colorSpaceInit = { + primaries: "bt709", + transfer: "bt709", + matrix: "bt709", + fullRange: false + }; + } + } this.visibleRect = { left: init.visibleRect?.left ?? 0, top: init.visibleRect?.top ?? 0, @@ -16401,9 +18083,12 @@ class VideoSample { this.squarePixelWidth = this.rotation % 180 === 0 ? init.displayWidth : init.displayHeight; this.squarePixelHeight = this.rotation % 180 === 0 ? init.displayHeight : init.displayWidth; } else { - this.squarePixelWidth = this.codedWidth; - this.squarePixelHeight = this.codedHeight; + this.squarePixelWidth = this.visibleRect.width; + this.squarePixelHeight = this.visibleRect.height; } + this._data = init._doNotCopy ? toUint8Array(data) : toUint8Array(data).slice(); + this._layout = layout; + this.colorSpace = new VideoSampleColorSpace(colorSpaceInit); } else if (typeof VideoFrame !== "undefined" && data instanceof VideoFrame) { if (init?.rotation !== void 0 && ![0, 90, 180, 270].includes(init.rotation)) { throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270."); @@ -16445,11 +18130,21 @@ class VideoSample { if (init.duration !== void 0 && (!Number.isFinite(init.duration) || init.duration < 0)) { throw new TypeError("init.duration, when provided, must be a non-negative number."); } + if (init.visibleRect !== void 0) { + validateRectangle(init.visibleRect, "init.visibleRect"); + } if (typeof VideoFrame !== "undefined") { return new VideoSample(new VideoFrame(data, { timestamp: Math.trunc(init.timestamp * SECOND_TO_MICROSECOND_FACTOR), // Drag 0 to undefined - duration: Math.trunc((init.duration ?? 0) * SECOND_TO_MICROSECOND_FACTOR) || void 0 + duration: Math.trunc((init.duration ?? 0) * SECOND_TO_MICROSECOND_FACTOR) || void 0, + // WebCodecs wants DOMRectInit + visibleRect: init.visibleRect && { + x: init.visibleRect.left, + y: init.visibleRect.top, + width: init.visibleRect.width, + height: init.visibleRect.height + } }), init); } let width = 0; @@ -16467,20 +18162,23 @@ class VideoSample { if (!width || !height) { throw new TypeError("Could not determine dimensions."); } - const canvas = new OffscreenCanvas(width, height); + const visibleRect = init.visibleRect ?? { left: 0, top: 0, width, height }; + const canvas = new OffscreenCanvas(visibleRect.width, visibleRect.height); const context = canvas.getContext("2d", { alpha: isFirefox(), // Firefox has VideoFrame glitches with opaque canvases willReadFrequently: true }); - assert(context); - context.drawImage(data, 0, 0); + if (!context) { + throw new Error("OffscreenCanvas must have support for the '2d' context in order to create a VideoSample from this data."); + } + context.drawImage(data, -visibleRect.left, -visibleRect.top); this._data = canvas; this._layout = null; this.format = "RGBX"; - this.visibleRect = { left: 0, top: 0, width, height }; - this.squarePixelWidth = width; - this.squarePixelHeight = height; + this.visibleRect = { left: 0, top: 0, width: visibleRect.width, height: visibleRect.height }; + this.squarePixelWidth = visibleRect.width; + this.squarePixelHeight = visibleRect.height; this.rotation = init.rotation ?? 0; this.timestamp = init.timestamp; this.duration = init.duration ?? 0; @@ -16490,9 +18188,53 @@ class VideoSample { transfer: "iec61966-2-1", fullRange: true }); + } else if (data instanceof VideoSampleResource) { + if (!init || typeof init !== "object") { + throw new TypeError("init must be an object."); + } + if (init.rotation !== void 0 && ![0, 90, 180, 270].includes(init.rotation)) { + throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270."); + } + if (!Number.isFinite(init.timestamp)) { + throw new TypeError("init.timestamp must be a number."); + } + if (init.duration !== void 0 && (!Number.isFinite(init.duration) || init.duration < 0)) { + throw new TypeError("init.duration, when provided, must be a non-negative number."); + } + this._data = data; + data._referenceCount++; + this.format = data.getFormat(); + if (this.format !== null && !VIDEO_SAMPLE_PIXEL_FORMATS.includes(this.format)) { + throw new TypeError("getFormat() must return a VideoSamplePixelFormat or null."); + } + this.visibleRect = { + left: 0, + top: 0, + width: data.getCodedWidth(), + height: data.getCodedHeight() + }; + if (!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."); + } + this.squarePixelWidth = data.getSquarePixelWidth(); + if (!Number.isInteger(this.squarePixelWidth) || this.squarePixelWidth <= 0) { + throw new TypeError("getSquarePixelWidth() must return a positive integer."); + } + this.squarePixelHeight = data.getSquarePixelHeight(); + if (!Number.isInteger(this.squarePixelHeight) || this.squarePixelHeight <= 0) { + throw new TypeError("getSquarePixelHeight() must return a positive integer."); + } + this.rotation = init.rotation ?? 0; + this.timestamp = init.timestamp; + this.duration = init.duration ?? 0; + this.colorSpace = data.getColorSpace(); } else { - throw new TypeError("Invalid data type: Must be a BufferSource or CanvasImageSource."); + throw new TypeError("Invalid data type: Must be a BufferSource, CanvasImageSource, or VideoSampleResource."); } + this.encodeOptions = init?.encodeOptions ?? {}; this.pixelAspectRatio = simplifyRational({ num: this.squarePixelWidth * this.codedHeight, den: this.squarePixelHeight * this.codedWidth @@ -16505,11 +18247,19 @@ class VideoSample { throw new Error("VideoSample is closed."); } assert(this._data !== null); - if (isVideoFrame(this._data)) { + if (this._data instanceof VideoSampleResource) { + return new VideoSample(this._data, { + timestamp: this.timestamp, + duration: this.duration, + rotation: this.rotation, + encodeOptions: this.encodeOptions + }); + } else if (isVideoFrame(this._data)) { return new VideoSample(this._data.clone(), { timestamp: this.timestamp, duration: this.duration, - rotation: this.rotation + rotation: this.rotation, + encodeOptions: this.encodeOptions }); } else if (this._data instanceof Uint8Array) { assert(this._layout); @@ -16524,7 +18274,10 @@ class VideoSample { rotation: this.rotation, visibleRect: this.visibleRect, displayWidth: this.displayWidth, - displayHeight: this.displayHeight + displayHeight: this.displayHeight, + encodeOptions: this.encodeOptions, + // It's already been copied, if we copy it again we make the clone unnecessarily expensive + _doNotCopy: true }); } else { return new VideoSample(this._data, { @@ -16537,7 +18290,8 @@ class VideoSample { rotation: this.rotation, visibleRect: this.visibleRect, displayWidth: this.displayWidth, - displayHeight: this.displayHeight + displayHeight: this.displayHeight, + encodeOptions: this.encodeOptions }); } } @@ -16550,7 +18304,12 @@ class VideoSample { return; } finalizationRegistry?.unregister(this); - if (isVideoFrame(this._data)) { + if (this._data instanceof VideoSampleResource) { + this._data._referenceCount--; + if (this._data._referenceCount === 0) { + this._data.close(); + } + } else if (isVideoFrame(this._data)) { this._data.close(); } else { this._data = null; @@ -16558,35 +18317,24 @@ class VideoSample { this._closed = true; } /** - * Returns the number of bytes required to hold this video sample's pixel data. Throws if `format` is `null`. + * Returns the number of bytes required to hold this video sample's pixel data. */ allocationSize(options = {}) { validateVideoFrameCopyToOptions(options); if (this._closed) { throw new Error("VideoSample is closed."); } - if (this.format === null) { - throw new Error("Cannot get allocation size when format is null. Sorry!"); - } - assert(this._data !== null); - if (!isVideoFrame(this._data)) { - if (options.colorSpace || options.format && options.format !== this.format || options.layout || options.rect) { - const videoFrame = this.toVideoFrame(); - const size = videoFrame.allocationSize(options); - videoFrame.close(); - return size; - } + if ((options.format ?? this.format) == null) { + throw new Error("Cannot get allocation size when format is null."); } if (isVideoFrame(this._data)) { return this._data.allocationSize(options); - } else if (this._data instanceof Uint8Array) { - return this._data.byteLength; - } else { - return this.codedWidth * this.codedHeight * 4; } + const combinedLayout = ParseVideoFrameCopyToOptions(this, options); + return combinedLayout.allocationSize; } /** - * Copies this video sample's pixel data to an ArrayBuffer or ArrayBufferView. Throws if `format` is `null`. + * Copies this video sample's pixel data to an ArrayBuffer or ArrayBufferView. * @returns The byte layout of the planes of the copied data. */ async copyTo(destination, options = {}) { @@ -16597,37 +18345,127 @@ class VideoSample { if (this._closed) { throw new Error("VideoSample is closed."); } - if (this.format === null) { - throw new Error("Cannot copy video sample data when format is null. Sorry!"); + if ((options.format ?? this.format) == null) { + throw new Error("Cannot copy video sample data when format is null."); } assert(this._data !== null); - if (!isVideoFrame(this._data)) { - if (options.colorSpace || options.format && options.format !== this.format || options.layout || options.rect) { - const videoFrame = this.toVideoFrame(); - const layout = await videoFrame.copyTo(destination, options); - videoFrame.close(); - return layout; - } - } if (isVideoFrame(this._data)) { return this._data.copyTo(destination, options); + } + if (options.format && !["RGBA", "RGBX", "BGRA", "BGRX"].includes(this.format) && ["RGBA", "RGBX", "BGRA", "BGRX"].includes(options.format)) { + if (this._data instanceof VideoSampleResource) { + const env_1 = { stack: [], error: void 0, hasError: false }; + try { + const rgbSample = __addDisposableResource(env_1, await this._data.toRgbSample({ + timestamp: this.timestamp, + duration: this.duration, + rotation: this.rotation + }, options.colorSpace ?? "srgb"), false); + if (!(rgbSample instanceof VideoSample)) { + throw new TypeError("toRgbSample() must return a VideoSample."); + } + if (!["RGBA", "RGBX", "BGRA", "BGRX"].includes(rgbSample.format)) { + throw new Error(`Sample returned by toRgbSample was expected to have an RGB format, got '${rgbSample.format}' instead.`); + } + return await rgbSample.copyTo(destination, options); + } catch (e_1) { + env_1.error = e_1; + env_1.hasError = true; + } finally { + __disposeResources(env_1); + } + } else { + if (typeof VideoFrame === "undefined") { + throw new Error("For this sample, converting from a non-RGB to an RGB format requires VideoFrame to be defined."); + } + const tempFrame = this.toVideoFrame(); + const result = await tempFrame.copyTo(destination, options); + tempFrame.close(); + return result; + } + } + const combinedLayout = ParseVideoFrameCopyToOptions(this, options); + assert(this.format); + const destBytes = toUint8Array(destination); + if (destBytes.byteLength < combinedLayout.allocationSize) { + throw new TypeError(`Destination buffer too small. Required: ${combinedLayout.allocationSize}, Available: ${destBytes.byteLength}`); + } + const planeConfigs = getPlaneConfigs(this.format); + let dataPlanes; + if (this._data instanceof VideoSampleResource) { + let result = this._data.getDataPlanes(); + if (isThenable(result)) + result = await result; + if (!Array.isArray(result) || result.some((x) => !(x.data instanceof Uint8Array) || !Number.isInteger(x.stride) || x.stride < 0)) { + throw new TypeError('getDataPlanes() must return an array of objects with a Uint8Array "data" property and a non-negative integer "stride" property.'); + } + dataPlanes = result; } else if (this._data instanceof Uint8Array) { assert(this._layout); - const dest = toUint8Array(destination); - dest.set(this._data); - return this._layout; + assert(this._layout.length === planeConfigs.length); + dataPlanes = this._layout.map((planeLayout, i) => { + const height = Math.ceil(this.codedHeight / planeConfigs[i].heightDivisor); + return { + data: this._data.subarray(planeLayout.offset, planeLayout.offset + planeLayout.stride * height), + stride: planeLayout.stride + }; + }); } else { const canvas = this._data; const context = canvas.getContext("2d"); assert(context); const imageData = context.getImageData(0, 0, this.codedWidth, this.codedHeight); - const dest = toUint8Array(destination); - dest.set(imageData.data); - return [{ - offset: 0, + dataPlanes = [{ + data: toUint8Array(imageData.data), stride: 4 * this.codedWidth }]; } + const planeLayouts = []; + const numPlanes = planeConfigs.length; + for (let planeIndex = 0; planeIndex < numPlanes; planeIndex++) { + const computedLayout = combinedLayout.computedLayouts[planeIndex]; + const sourceStride = dataPlanes[planeIndex].stride; + const sourceData = dataPlanes[planeIndex].data; + let sourceOffset = computedLayout.sourceTop * sourceStride; + sourceOffset += computedLayout.sourceLeftBytes; + let destinationOffset = computedLayout.destinationOffset; + const rowBytes = computedLayout.sourceWidthBytes; + const layout = { + offset: destinationOffset, + stride: computedLayout.destinationStride + }; + for (let row = 0; row < computedLayout.sourceHeight; row++) { + if (sourceOffset + rowBytes > sourceData.byteLength) { + throw new Error(`Source buffer OOB read.`); + } + if (destinationOffset + rowBytes > destBytes.byteLength) { + throw new Error(`Destination buffer OOB write.`); + } + const srcSub = sourceData.subarray(sourceOffset, sourceOffset + rowBytes); + destBytes.set(srcSub, destinationOffset); + sourceOffset += sourceStride; + destinationOffset += computedLayout.destinationStride; + } + planeLayouts.push(layout); + } + if (options.format !== void 0) { + const needsRgbConversion = this.format.startsWith("RGB") !== options.format.startsWith("RGB"); + const needsAlphaConversion = this.format.includes("X") && options.format.includes("A"); + if (needsRgbConversion || needsAlphaConversion) { + for (let i = 0; i < combinedLayout.allocationSize; i += 4) { + if (needsRgbConversion) { + const r = destBytes[i]; + const b = destBytes[i + 2]; + destBytes[i] = b; + destBytes[i + 2] = r; + } + if (needsAlphaConversion) { + destBytes[i + 3] = 255; + } + } + } + } + return planeLayouts; } /** * Converts this video sample to a VideoFrame for use with the WebCodecs API. The VideoFrame returned by this @@ -16638,20 +18476,61 @@ class VideoSample { throw new Error("VideoSample is closed."); } assert(this._data !== null); - if (isVideoFrame(this._data)) { + if (this._data instanceof VideoSampleResource) { + if (this.format === null) { + throw new Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if format is null."); + } + const planes = this._data.getDataPlanes(); + if (isThenable(planes)) { + throw new Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if getDataPlanes() returns a promise."); + } + const size = planes.reduce((a, b) => a + b.data.byteLength, 0); + const buffer = new Uint8Array(size); + let offset = 0; + const offsets = []; + for (const plane of planes) { + buffer.set(plane.data, offset); + offsets.push(offset); + offset += plane.data.byteLength; + } + return new VideoFrame(buffer, { + format: this.format, + layout: planes.map((x, i) => ({ + offset: offsets[i], + stride: x.stride + })), + codedWidth: this.codedWidth, + codedHeight: this.codedHeight, + timestamp: this.microsecondTimestamp, + duration: this.microsecondDuration, + colorSpace: this.colorSpace, + visibleRect: this.visibleRect, + displayWidth: this.squarePixelWidth, + // Not display* since we're not passing rotation + displayHeight: this.squarePixelHeight + }); + } else if (isVideoFrame(this._data)) { return new VideoFrame(this._data, { timestamp: this.microsecondTimestamp, duration: this.microsecondDuration || void 0 // Drag 0 duration to undefined, glitches some codecs }); } else if (this._data instanceof Uint8Array) { + assert(this._layout); return new VideoFrame(this._data, { format: this.format, codedWidth: this.codedWidth, + // This is technically wrong! codedWidth is a lie technically. But, since codedHeight: this.codedHeight, + // we pass the layout (which contains the true coded width), we're good. + layout: this._layout, timestamp: this.microsecondTimestamp, duration: this.microsecondDuration || void 0, - colorSpace: this.colorSpace + colorSpace: this.colorSpace, + visibleRect: this.visibleRect, + displayWidth: this.squarePixelWidth, + // Not display* since we're not passing rotation + displayHeight: this.squarePixelHeight }); } else { return new VideoFrame(this._data, { @@ -16756,8 +18635,9 @@ class VideoSample { const canvasHeight = context.canvas.height; const rotation = options.rotation ?? this.rotation; const [rotatedWidth, rotatedHeight] = rotation % 180 === 0 ? [this.squarePixelWidth, this.squarePixelHeight] : [this.squarePixelHeight, this.squarePixelWidth]; - if (options.crop) { - clampCropRectangle(options.crop, rotatedWidth, rotatedHeight); + let finalCrop = options.crop; + if (finalCrop) { + finalCrop = clampCropRectangle(finalCrop, rotatedWidth, rotatedHeight); } let dx; let dy; @@ -16810,11 +18690,54 @@ class VideoSample { } return { sx, sy, sWidth, sHeight }; } + /** + * Draws the sample onto the target canvas with fit behavior, manually mipmapping on strong downscales for quality. + * @internal + */ + _drawWithFitAndMipmapping(targetCanvas, targetContext, options) { + const targetWidth = targetCanvas.width; + const targetHeight = targetCanvas.height; + const [rotatedWidth, rotatedHeight] = options.rotation % 180 === 0 ? [this.squarePixelWidth, this.squarePixelHeight] : [this.squarePixelHeight, this.squarePixelWidth]; + const sourceWidth = options.crop ? options.crop.width : rotatedWidth; + const sourceHeight = options.crop ? options.crop.height : rotatedHeight; + let mipLevels = 0; + if (2 * targetWidth < sourceWidth && 2 * targetHeight < sourceHeight) { + mipLevels = Math.floor(Math.log2(Math.min(sourceWidth / targetWidth, sourceHeight / targetHeight))); + } + const drawWidth = targetWidth * 2 ** mipLevels; + const drawHeight = targetHeight * 2 ** mipLevels; + const { canvas, context, isNew } = mipLevels > 0 ? getTransformationCanvas(drawWidth, drawHeight) : { canvas: targetCanvas, context: targetContext, isNew: options.targetIsFresh }; + context.imageSmoothingQuality = "high"; + if (options.fillBlack) { + context.fillStyle = "black"; + context.fillRect(0, 0, drawWidth, drawHeight); + } else if (!isNew) { + context.clearRect(0, 0, drawWidth, drawHeight); + } + this.drawWithFit(context, { + fit: options.fit, + rotation: options.rotation, + crop: options.crop + }); + context.globalCompositeOperation = "copy"; + for (let i = mipLevels; i > 1; i--) { + const levelWidth = targetWidth * 2 ** i; + const levelHeight = targetHeight * 2 ** i; + context.drawImage(canvas, 0, 0, levelWidth, levelHeight, 0, 0, levelWidth / 2, levelHeight / 2); + } + context.globalCompositeOperation = "source-over"; + if (mipLevels > 0) { + targetContext.imageSmoothingQuality = "high"; + targetContext.globalCompositeOperation = "copy"; + targetContext.drawImage(canvas, 0, 0, 2 * targetWidth, 2 * targetHeight, 0, 0, targetWidth, targetHeight); + targetContext.globalCompositeOperation = "source-over"; + } + } /** * Converts this video sample to a * [`CanvasImageSource`](https://udn.realityripple.com/docs/Web/API/CanvasImageSource) for drawing to a canvas. * - * You must use the value returned by this method immediately, as any VideoFrame created internally will + * You must use the value returned by this method immediately, as any VideoFrame created internally may * automatically be closed in the next microtask. */ toCanvasImageSource() { @@ -16822,7 +18745,7 @@ class VideoSample { throw new Error("VideoSample is closed."); } assert(this._data !== null); - if (this._data instanceof Uint8Array) { + if (this._data instanceof VideoSampleResource || this._data instanceof Uint8Array) { const videoFrame = this.toVideoFrame(); queueMicrotask(() => videoFrame.close()); return videoFrame; @@ -16830,6 +18753,103 @@ class VideoSample { return this._data; } } + /** + * Transform this video sample to a new video sample given the options. Can be used to resize, rotate, and crop + * the sample. + * + * In non-browser environments, this method will not work by default. To make it work, register a custom + * transformer function via {@link registerVideoSampleTransformer}. + */ + async transform(options) { + if (!options || typeof options !== "object") { + throw new TypeError("options must be an object."); + } + if (options.width !== void 0 && (!Number.isInteger(options.width) || options.width <= 0)) { + throw new TypeError("options.width, when provided, must be a positive integer."); + } + if (options.height !== void 0 && (!Number.isInteger(options.height) || options.height <= 0)) { + throw new TypeError("options.height, when provided, must be a positive integer."); + } + if (options.roundDimensionsTo !== void 0 && (!Number.isInteger(options.roundDimensionsTo) || options.roundDimensionsTo <= 0)) { + throw new TypeError("options.roundDimensionsTo, when provided, must be a positive integer."); + } + if (options.fit !== void 0 && !["fill", "contain", "cover"].includes(options.fit)) { + throw new TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".'); + } + if (options.width !== void 0 && options.height !== void 0 && options.fit === void 0) { + throw new TypeError("When both options.width and options.height are provided, options.fit must also be provided."); + } + if (options.rotate !== void 0 && ![0, 90, 180, 270].includes(options.rotate)) { + throw new TypeError("options.rotate, when provided, must be 0, 90, 180 or 270."); + } + if (options.crop !== void 0) { + validateCropRectangle(options.crop, "options."); + } + if (options.alpha !== void 0 && !["keep", "discard"].includes(options.alpha)) { + throw new TypeError("options.alpha, when provided, must be 'keep' or 'discard'."); + } + const rotation = normalizeRotation(this.rotation + (options.rotate ?? 0)); + const [rotatedWidth, rotatedHeight] = rotation % 180 === 0 ? [this.squarePixelWidth, this.squarePixelHeight] : [this.squarePixelHeight, this.squarePixelWidth]; + let finalCrop = options.crop; + if (finalCrop) { + finalCrop = clampCropRectangle(finalCrop, rotatedWidth, rotatedHeight); + } + const cropWidth = finalCrop ? finalCrop.width : rotatedWidth; + const cropHeight = finalCrop ? finalCrop.height : rotatedHeight; + const originalAspectRatio = cropWidth / cropHeight; + let targetWidth; + let targetHeight; + if (options.width !== void 0 && options.height === void 0) { + targetWidth = options.width; + targetHeight = targetWidth / originalAspectRatio; + } else if (options.width === void 0 && options.height !== void 0) { + targetHeight = options.height; + targetWidth = targetHeight * originalAspectRatio; + } else if (options.width !== void 0 && options.height !== void 0) { + targetWidth = options.width; + targetHeight = options.height; + } else { + targetWidth = cropWidth; + targetHeight = cropHeight; + } + targetWidth = roundToMultiple(targetWidth, options.roundDimensionsTo ?? 1); + targetHeight = roundToMultiple(targetHeight, options.roundDimensionsTo ?? 1); + const description = { + width: targetWidth, + height: targetHeight, + fit: options.fit ?? "fill", + rotation, + crop: finalCrop ?? { + left: 0, + top: 0, + width: rotatedWidth, + height: rotatedHeight + }, + alpha: options.alpha ?? "keep" + }; + for (const transformer of registeredVideoSampleTransformers) { + let result = transformer(this, description); + if (isThenable(result)) + result = await result; + if (result !== null) { + return result; + } + } + const { canvas, context, isNew } = getTransformationCanvas(description.width, description.height); + this._drawWithFitAndMipmapping(canvas, context, { + fit: description.fit, + rotation: description.rotation, + crop: description.crop, + targetIsFresh: isNew, + fillBlack: description.alpha === "discard" + }); + return new VideoSample(canvas, { + timestamp: this.timestamp, + duration: this.duration, + rotation: 0 + // Any previous rotation is now baked in + }); + } /** Sets the rotation metadata of this video sample. */ setRotation(newRotation) { if (![0, 90, 180, 270].includes(newRotation)) { @@ -16851,11 +18871,57 @@ class VideoSample { } this.duration = newDuration; } + /** Sets the encode options used when this sample is passed to an encoder. */ + setEncodeOptions(newEncodeOptions) { + if (!newEncodeOptions || typeof newEncodeOptions !== "object") { + throw new TypeError("newEncodeOptions must be an object."); + } + this.encodeOptions = newEncodeOptions; + } /** Calls `.close()`. */ [Symbol.dispose]() { this.close(); } } +const registeredVideoSampleTransformers = []; +const TRANSFORMATION_CANVAS_CACHE_MAX_SIZE = 3; +const transformationCanvasCache = []; +let transformationCanvasCacheNextAge = 0; +const getTransformationCanvas = (width, height) => { + for (const entry of transformationCanvasCache) { + if (entry.canvas.width === width && entry.canvas.height === height) { + entry.age = transformationCanvasCacheNextAge++; + return { canvas: entry.canvas, context: entry.context, isNew: false }; + } + } + let canvas; + if (typeof OffscreenCanvas !== "undefined") { + canvas = new OffscreenCanvas(width, height); + } else { + if (typeof window === "undefined" || typeof document === "undefined") { + 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()."); + } + canvas = document.createElement("canvas"); + canvas.width = width; + canvas.height = height; + } + const context = canvas.getContext("2d", { + alpha: true, + willReadFrequently: false + }); + if (!context) { + throw new Error("The '2d' canvas context is required to transform VideoSamples. Register a custom transformer using registerVideoSampleTransformer to work around this limitation."); + } + if (transformationCanvasCache.length >= TRANSFORMATION_CANVAS_CACHE_MAX_SIZE) { + transformationCanvasCache.splice(arrayArgmin(transformationCanvasCache, (x) => x.age), 1); + } + transformationCanvasCache.push({ + canvas, + context, + age: transformationCanvasCacheNextAge++ + }); + return { canvas, context, isNew: true }; +}; class VideoSampleColorSpace { /** Creates a new VideoSampleColorSpace. */ constructor(init) { @@ -17045,7 +19111,128 @@ const getPlaneConfigs = (format) => { assert(false); } }; +const ParseVideoFrameCopyToOptions = (sample, options) => { + const defaultRect = { + left: 0, + top: 0, + width: sample.codedWidth, + height: sample.codedHeight + }; + const overrideRect = options.rect; + const parsedRect = ParseVisibleRect(defaultRect, overrideRect, sample.codedWidth, sample.codedHeight, sample.format); + const optLayout = options.layout; + let format; + if (!options.format || options.format === sample.format) { + format = sample.format; + } else if (["RGBA", "RGBX", "BGRA", "BGRX"].includes(options.format)) { + format = options.format; + } else { + throw new Error("NotSupportedError: Invalid destination format."); + } + return ComputeLayoutAndAllocationSize(parsedRect, format, optLayout); +}; +const ParseVisibleRect = (defaultRect, overrideRect, codedWidth, codedHeight, format) => { + const sourceRect = { ...defaultRect }; + if (overrideRect !== void 0) { + if (overrideRect.width === 0 || overrideRect.height === 0) { + throw new TypeError("visibleRect dimensions cannot be zero."); + } + if ((overrideRect.x || 0) + (overrideRect.width || 0) > codedWidth) { + throw new TypeError("visibleRect exceeds codedWidth."); + } + if ((overrideRect.y || 0) + (overrideRect.height || 0) > codedHeight) { + throw new TypeError("visibleRect exceeds codedHeight."); + } + sourceRect.x = overrideRect.x || 0; + sourceRect.y = overrideRect.y || 0; + sourceRect.width = overrideRect.width || 0; + sourceRect.height = overrideRect.height || 0; + } + const validAlignment = VerifyRectOffsetAlignment(format, sourceRect); + if (!validAlignment) { + throw new TypeError("visibleRect alignment is invalid for the format."); + } + return sourceRect; +}; +const VerifyRectOffsetAlignment = (format, rect) => { + if (format === null) + return true; + const planes = getPlaneConfigs(format); + for (let planeIndex = 0; planeIndex < planes.length; planeIndex++) { + const plane = planes[planeIndex]; + const sampleWidth = plane.widthDivisor; + const sampleHeight = plane.heightDivisor; + if ((rect.x || 0) % sampleWidth !== 0) + return false; + if ((rect.y || 0) % sampleHeight !== 0) + return false; + } + return true; +}; +const ComputeLayoutAndAllocationSize = (parsedRect, format, layout) => { + const planes = getPlaneConfigs(format); + const numPlanes = planes.length; + if (layout !== void 0 && layout.length !== numPlanes) { + throw new TypeError(`Layout must have ${numPlanes} planes.`); + } + let minAllocationSize = 0; + const computedLayouts = []; + const endOffsets = []; + for (let planeIndex = 0; planeIndex < numPlanes; planeIndex++) { + const plane = planes[planeIndex]; + const sampleBytes = plane.sampleBytes; + const sampleWidth = plane.widthDivisor; + const sampleHeight = plane.heightDivisor; + const computedLayout = { + destinationOffset: 0, + destinationStride: 0, + sourceTop: 0, + sourceHeight: 0, + sourceLeftBytes: 0, + sourceWidthBytes: 0 + }; + computedLayout.sourceTop = Math.ceil(Math.trunc(parsedRect.y || 0) / sampleHeight); + computedLayout.sourceHeight = Math.ceil(Math.trunc(parsedRect.height || 0) / sampleHeight); + computedLayout.sourceLeftBytes = Math.floor(Math.trunc(parsedRect.x || 0) / sampleWidth) * sampleBytes; + computedLayout.sourceWidthBytes = Math.floor(Math.trunc(parsedRect.width || 0) / sampleWidth) * sampleBytes; + if (layout !== void 0) { + const planeLayout = layout[planeIndex]; + if (planeLayout.stride < computedLayout.sourceWidthBytes) { + throw new TypeError(`Stride for plane ${planeIndex} is too small.`); + } + computedLayout.destinationOffset = planeLayout.offset; + computedLayout.destinationStride = planeLayout.stride; + } else { + computedLayout.destinationOffset = minAllocationSize; + computedLayout.destinationStride = computedLayout.sourceWidthBytes; + } + const planeSize = computedLayout.destinationStride * computedLayout.sourceHeight; + const planeEnd = planeSize + computedLayout.destinationOffset; + if (planeEnd > 4294967295) { + throw new TypeError("Allocation size exceeds limit."); + } + endOffsets.push(planeEnd); + minAllocationSize = Math.max(minAllocationSize, planeEnd); + for (let earlierPlaneIndex = 0; earlierPlaneIndex < planeIndex; earlierPlaneIndex++) { + const earlierLayout = computedLayouts[earlierPlaneIndex]; + if (endOffsets[planeIndex] <= earlierLayout.destinationOffset || endOffsets[earlierPlaneIndex] <= computedLayout.destinationOffset) { + continue; + } + throw new TypeError("Planes overlap."); + } + computedLayouts.push(computedLayout); + } + return { + allocationSize: minAllocationSize, + computedLayouts + }; +}; const AUDIO_SAMPLE_FORMATS = /* @__PURE__ */ new Set(["f32", "f32-planar", "s16", "s16-planar", "s32", "s32-planar", "u8", "u8-planar"]); +class AudioSampleResource { + constructor() { + this._referenceCount = 0; + } +} class AudioSample { /** The presentation timestamp of the sample in microseconds. */ get microsecondTimestamp() { @@ -17055,11 +19242,6 @@ class AudioSample { get microsecondDuration() { return Math.trunc(SECOND_TO_MICROSECOND_FACTOR * this.duration); } - /** - * Creates a new {@link AudioSample}, either from an existing - * [`AudioData`](https://developer.mozilla.org/en-US/docs/Web/API/AudioData) or from raw bytes specified in - * {@link AudioSampleInit}. - */ constructor(init) { this._closed = false; if (isAudioData(init)) { @@ -17073,6 +19255,30 @@ class AudioSample { this.numberOfChannels = init.numberOfChannels; this.timestamp = init.timestamp / 1e6; this.duration = init.numberOfFrames / init.sampleRate; + } else if (init instanceof AudioSampleResource) { + this._data = init; + init._referenceCount++; + this.format = init.getFormat(); + if (!AUDIO_SAMPLE_FORMATS.has(this.format)) { + throw new TypeError("getFormat() must return an AudioSampleFormat."); + } + this.sampleRate = init.getSampleRate(); + if (!Number.isInteger(this.sampleRate) || this.sampleRate <= 0) { + throw new TypeError("getSampleRate() must return a positive integer."); + } + this.numberOfFrames = init.getNumberOfFrames(); + if (!Number.isInteger(this.numberOfFrames) || this.numberOfFrames < 0) { + throw new TypeError("getNumberOfFrames() must return a non-negative integer."); + } + this.numberOfChannels = init.getNumberOfChannels(); + if (!Number.isInteger(this.numberOfChannels) || this.numberOfChannels <= 0) { + throw new TypeError("getNumberOfChannels() must return a positive integer."); + } + this.timestamp = init.getTimestamp(); + if (!Number.isFinite(this.timestamp)) { + throw new TypeError("getTimestamp() must return a finite number."); + } + this.duration = this.numberOfFrames / this.sampleRate; } else { if (!init || typeof init !== "object") { throw new TypeError("Invalid AudioDataInit: must be an object."); @@ -17178,8 +19384,9 @@ class AudioSample { if (this._closed) { throw new Error("AudioSample is closed."); } - const { planeIndex, format, frameCount: optFrameCount, frameOffset: optFrameOffset } = options; - const srcFormat = this.format; + const { format, frameCount: optFrameCount, frameOffset: optFrameOffset } = options; + let { planeIndex } = options; + let srcFormat = this.format; const destFormat = format ?? this.format; if (!destFormat) throw new Error("Destination format not determined"); @@ -17211,44 +19418,105 @@ class AudioSample { if (isAudioData(this._data)) { if (isWebKit() && numChannels > 2 && destFormat !== srcFormat) { doAudioDataCopyToWebKitWorkaround(this._data, destView, srcFormat, destFormat, numChannels, planeIndex, frameOffset, copyFrameCount); + return; } else { - this._data.copyTo(destination, { - planeIndex, - frameOffset, - frameCount: copyFrameCount, - format: destFormat - }); + try { + this._data.copyTo(destination, { + planeIndex, + frameOffset, + frameCount: copyFrameCount, + format: destFormat + }); + return; + } catch (error) { + if (destFormat === "f32-planar") { + throw error; + } + srcFormat = "f32-planar"; + } } - } else { - const uint8Data = this._data; - const srcView = toDataView(uint8Data); - const readFn = getReadFunction(srcFormat); - const srcBytesPerSample = getBytesPerSample(srcFormat); - const srcIsPlanar = formatIsPlanar(srcFormat); - for (let i = 0; i < copyFrameCount; i++) { + } + const readFn = getReadFunction(srcFormat); + const srcBytesPerSample = getBytesPerSample(srcFormat); + const srcIsPlanar = formatIsPlanar(srcFormat); + let uint8Data; + if (this._data instanceof AudioSampleResource) { + const getDataPlaneValidated = (index) => { + const result = this._data.getDataPlane(index); + if (!(result instanceof Uint8Array)) { + throw new TypeError("getDataPlane() must return a Uint8Array."); + } + const expectedSize = numFrames * srcBytesPerSample * (srcIsPlanar ? 1 : numChannels); + if (result.byteLength !== expectedSize) { + throw new TypeError(`Data plane ${index} has invalid size. Expected exactly ${expectedSize} bytes, got ${result.byteLength} bytes.`); + } + return result; + }; + if (srcIsPlanar) { if (destIsPlanar) { - const destOffset = i * destBytesPerSample; + uint8Data = getDataPlaneValidated(planeIndex); + planeIndex = 0; + } else { + uint8Data = new Uint8Array(numFrames * srcBytesPerSample * numChannels); + for (let ch = 0; ch < numChannels; ch++) { + const planeData = getDataPlaneValidated(ch); + uint8Data.set(planeData, ch * numFrames * srcBytesPerSample); + } + } + } else { + uint8Data = getDataPlaneValidated(0); + } + } else if (this._data instanceof Uint8Array) { + uint8Data = this._data; + } else { + assert(srcFormat === "f32-planar"); + if (destIsPlanar) { + uint8Data = new Uint8Array(this._data.allocationSize({ + format: "f32-planar", + planeIndex + })); + this._data.copyTo(uint8Data, { + format: "f32-planar", + planeIndex + }); + planeIndex = 0; + } else { + uint8Data = new Uint8Array(this._data.allocationSize({ + format: "f32-planar", + planeIndex: 0 + }) * numChannels); + for (let ch = 0; ch < numChannels; ch++) { + this._data.copyTo(uint8Data.subarray(ch * numFrames * srcBytesPerSample, (ch + 1) * numFrames * srcBytesPerSample), { + format: "f32-planar", + planeIndex: ch + }); + } + } + } + const srcView = toDataView(uint8Data); + for (let i = 0; i < copyFrameCount; i++) { + if (destIsPlanar) { + const destOffset = i * destBytesPerSample; + let srcOffset; + if (srcIsPlanar) { + srcOffset = (planeIndex * numFrames + (i + frameOffset)) * srcBytesPerSample; + } else { + srcOffset = ((i + frameOffset) * numChannels + planeIndex) * srcBytesPerSample; + } + const normalized = readFn(srcView, srcOffset); + writeFn(destView, destOffset, normalized); + } else { + for (let ch = 0; ch < numChannels; ch++) { + const destIndex = i * numChannels + ch; + const destOffset = destIndex * destBytesPerSample; let srcOffset; if (srcIsPlanar) { - srcOffset = (planeIndex * numFrames + (i + frameOffset)) * srcBytesPerSample; + srcOffset = (ch * numFrames + (i + frameOffset)) * srcBytesPerSample; } else { - srcOffset = ((i + frameOffset) * numChannels + planeIndex) * srcBytesPerSample; + srcOffset = ((i + frameOffset) * numChannels + ch) * srcBytesPerSample; } const normalized = readFn(srcView, srcOffset); writeFn(destView, destOffset, normalized); - } else { - for (let ch = 0; ch < numChannels; ch++) { - const destIndex = i * numChannels + ch; - const destOffset = destIndex * destBytesPerSample; - let srcOffset; - if (srcIsPlanar) { - srcOffset = (ch * numFrames + (i + frameOffset)) * srcBytesPerSample; - } else { - srcOffset = ((i + frameOffset) * numChannels + ch) * srcBytesPerSample; - } - const normalized = readFn(srcView, srcOffset); - writeFn(destView, destOffset, normalized); - } } } } @@ -17258,7 +19526,11 @@ class AudioSample { if (this._closed) { throw new Error("AudioSample is closed."); } - if (isAudioData(this._data)) { + if (this._data instanceof AudioSampleResource) { + const sample = new AudioSample(this._data); + sample.setTimestamp(this.timestamp); + return sample; + } else if (isAudioData(this._data)) { const sample = new AudioSample(this._data.clone()); sample.setTimestamp(this.timestamp); return sample; @@ -17273,6 +19545,65 @@ class AudioSample { }); } } + /** + * Returns a new {@link AudioSample} containing only the frames in the range [startFrame, endFrame). Both bounds + * must lie within this sample's range of frames. The returned sample's timestamp is shifted to match the start of + * the trimmed section. + */ + trim(startFrame, endFrame = this.numberOfFrames) { + if (!Number.isInteger(startFrame) || startFrame < 0) { + throw new TypeError("startFrame must be a non-negative integer."); + } + if (!Number.isInteger(endFrame) || endFrame < 0) { + throw new TypeError("endFrame must be a non-negative integer."); + } + if (startFrame > this.numberOfFrames) { + throw new RangeError("startFrame out of range."); + } + if (endFrame > this.numberOfFrames) { + throw new RangeError("endFrame out of range."); + } + if (endFrame < startFrame) { + throw new RangeError("endFrame must not be less than startFrame."); + } + if (this._closed) { + throw new Error("AudioSample is closed."); + } + const frameCount = endFrame - startFrame; + const bytesPerSample = getBytesPerSample(this.format); + let data; + if (formatIsPlanar(this.format)) { + const planeSize = frameCount * bytesPerSample; + data = new Uint8Array(planeSize * this.numberOfChannels); + if (frameCount > 0) { + for (let i = 0; i < this.numberOfChannels; i++) { + this.copyTo(data.subarray(i * planeSize, (i + 1) * planeSize), { + planeIndex: i, + format: this.format, + frameOffset: startFrame, + frameCount + }); + } + } + } else { + data = new Uint8Array(frameCount * this.numberOfChannels * bytesPerSample); + if (frameCount > 0) { + this.copyTo(data, { + planeIndex: 0, + format: this.format, + frameOffset: startFrame, + frameCount + }); + } + } + return new AudioSample({ + data, + format: this.format, + sampleRate: this.sampleRate, + numberOfChannels: this.numberOfChannels, + timestamp: this.timestamp + startFrame / this.sampleRate + }); + } /** * Closes this audio sample, releasing held resources. Audio samples should be closed as soon as they are not * needed anymore. @@ -17282,7 +19613,12 @@ class AudioSample { return; } finalizationRegistry?.unregister(this); - if (isAudioData(this._data)) { + if (this._data instanceof AudioSampleResource) { + this._data._referenceCount--; + if (this._data._referenceCount === 0) { + this._data.close(); + } + } else if (isAudioData(this._data)) { this._data.close(); } else { this._data = new Uint8Array(0); @@ -17297,36 +19633,13 @@ class AudioSample { if (this._closed) { throw new Error("AudioSample is closed."); } - if (isAudioData(this._data)) { + if (this._data instanceof AudioSampleResource) { + return this._createAudioDataFromData(); + } else if (isAudioData(this._data)) { if (this._data.timestamp === this.microsecondTimestamp) { return this._data.clone(); } else { - if (formatIsPlanar(this.format)) { - const size = this.allocationSize({ planeIndex: 0, format: this.format }); - const data = new ArrayBuffer(size * this.numberOfChannels); - for (let i = 0; i < this.numberOfChannels; i++) { - this.copyTo(new Uint8Array(data, i * size, size), { planeIndex: i, format: this.format }); - } - return new AudioData({ - format: this.format, - sampleRate: this.sampleRate, - numberOfFrames: this.numberOfFrames, - numberOfChannels: this.numberOfChannels, - timestamp: this.microsecondTimestamp, - data - }); - } else { - const data = new ArrayBuffer(this.allocationSize({ planeIndex: 0, format: this.format })); - this.copyTo(data, { planeIndex: 0, format: this.format }); - return new AudioData({ - format: this.format, - sampleRate: this.sampleRate, - numberOfFrames: this.numberOfFrames, - numberOfChannels: this.numberOfChannels, - timestamp: this.microsecondTimestamp, - data - }); - } + return this._createAudioDataFromData(); } } else { return new AudioData({ @@ -17340,6 +19653,35 @@ class AudioSample { }); } } + /** @internal */ + _createAudioDataFromData() { + if (formatIsPlanar(this.format)) { + const size = this.allocationSize({ planeIndex: 0, format: this.format }); + const data = new ArrayBuffer(size * this.numberOfChannels); + for (let i = 0; i < this.numberOfChannels; i++) { + this.copyTo(new Uint8Array(data, i * size, size), { planeIndex: i, format: this.format }); + } + return new AudioData({ + format: this.format, + sampleRate: this.sampleRate, + numberOfFrames: this.numberOfFrames, + numberOfChannels: this.numberOfChannels, + timestamp: this.microsecondTimestamp, + data + }); + } else { + const data = new ArrayBuffer(this.allocationSize({ planeIndex: 0, format: this.format })); + this.copyTo(data, { planeIndex: 0, format: this.format }); + return new AudioData({ + format: this.format, + sampleRate: this.sampleRate, + numberOfFrames: this.numberOfFrames, + numberOfChannels: this.numberOfChannels, + timestamp: this.microsecondTimestamp, + data + }); + } + } /** Convert this audio sample to an AudioBuffer for use with the Web Audio API. */ toAudioBuffer() { if (this._closed) { @@ -17795,6 +20137,7 @@ class EncodedPacketSink { let ended = false; let terminated = false; let outOfBandError = null; + let hasOutOfBandError = false; const timestamps = []; const maxQueueSize = () => Math.max(2, timestamps.length); (async () => { @@ -17816,8 +20159,9 @@ class EncodedPacketSink { ended = true; onQueueNotEmpty(); })().catch((error) => { - if (!outOfBandError) { + if (!hasOutOfBandError) { outOfBandError = error; + hasOutOfBandError = true; onQueueNotEmpty(); } }); @@ -17829,7 +20173,7 @@ class EncodedPacketSink { throw new InputDisposedError(); } else if (terminated) { return { value: void 0, done: true }; - } else if (outOfBandError) { + } else if (hasOutOfBandError) { throw outOfBandError; } else if (packetQueue.length > 0) { const value = packetQueue.shift(); @@ -17870,7 +20214,7 @@ class DecoderWrapper { } class BaseMediaSampleSink { /** @internal */ - mediaSamplesInRange(startTimestamp = 0, endTimestamp = Infinity, options) { + mediaSamplesInRange(startTimestamp = -Infinity, endTimestamp = Infinity, options) { validateTimestamp(startTimestamp); validateTimestamp(endTimestamp); const sampleQueue = []; @@ -17881,14 +20225,16 @@ class BaseMediaSampleSink { let decoderIsFlushed = false; let ended = false; let terminated = false; + let decoder = null; let outOfBandError = null; + let hasOutOfBandError = false; const packetRetrievalOptions = { ...options, verifyKeyPackets: true, metadataOnly: false }; (async () => { - const decoder = await this._createDecoder((sample) => { + decoder = await this._createDecoder((sample) => { onQueueDequeue(); if (sample.timestamp >= endTimestamp) { ended = true; @@ -17915,8 +20261,9 @@ class BaseMediaSampleSink { ({ promise: queueNotEmpty, resolve: onQueueNotEmpty } = promiseWithResolvers()); } }, (error) => { - if (!outOfBandError) { + if (!hasOutOfBandError) { outOfBandError = error; + hasOutOfBandError = true; onQueueNotEmpty(); } }); @@ -17944,17 +20291,19 @@ class BaseMediaSampleSink { if (!terminated && !this._track.input._disposed) { await decoder.flush(); } - decoder.close(); if (!firstSampleQueued && lastSample) { sampleQueue.push(lastSample); } decoderIsFlushed = true; onQueueNotEmpty(); })().catch((error) => { - if (!outOfBandError) { + if (!hasOutOfBandError) { outOfBandError = error; + hasOutOfBandError = true; onQueueNotEmpty(); } + }).finally(() => { + decoder?.close(); }); const track = this._track; const closeSamples = () => { @@ -17967,11 +20316,15 @@ class BaseMediaSampleSink { async next() { while (true) { if (track.input._disposed) { + terminated = true; + ended = true; closeSamples(); throw new InputDisposedError(); } else if (terminated) { return { value: void 0, done: true }; - } else if (outOfBandError) { + } else if (hasOutOfBandError) { + terminated = true; + ended = true; closeSamples(); throw outOfBandError; } else if (sampleQueue.length > 0) { @@ -18011,7 +20364,9 @@ class BaseMediaSampleSink { let { promise: queueDequeue, resolve: onQueueDequeue } = promiseWithResolvers(); let decoderIsFlushed = false; let terminated = false; + let decoder = null; let outOfBandError = null; + let hasOutOfBandError = false; const pushToQueue = (sample) => { sampleQueue.push(sample); onQueueNotEmpty(); @@ -18023,7 +20378,7 @@ class BaseMediaSampleSink { metadataOnly: false }; (async () => { - const decoder = await this._createDecoder((sample) => { + decoder = await this._createDecoder((sample) => { onQueueDequeue(); if (terminated) { sample.close(); @@ -18042,8 +20397,9 @@ class BaseMediaSampleSink { sample.close(); } }, (error) => { - if (!outOfBandError) { + if (!hasOutOfBandError) { outOfBandError = error; + hasOutOfBandError = true; onQueueNotEmpty(); } }); @@ -18053,6 +20409,7 @@ class BaseMediaSampleSink { let maxSequenceNumber = -1; const decodePackets = async () => { assert(lastKeyPacket); + assert(decoder); let currentPacket = lastKeyPacket; decoder.decode(currentPacket); while (currentPacket.sequenceNumber < maxSequenceNumber) { @@ -18072,6 +20429,7 @@ class BaseMediaSampleSink { maxSequenceNumber = -1; }; const flushDecoder = async () => { + assert(decoder); await decoder.flush(); for (let i = 0; i < timestampsOfInterest.length; i++) { pushToQueue(null); @@ -18109,14 +20467,16 @@ class BaseMediaSampleSink { } await flushDecoder(); } - decoder.close(); decoderIsFlushed = true; onQueueNotEmpty(); })().catch((error) => { - if (!outOfBandError) { + if (!hasOutOfBandError) { outOfBandError = error; + hasOutOfBandError = true; onQueueNotEmpty(); } + }).finally(() => { + decoder?.close(); }); const track = this._track; const closeSamples = () => { @@ -18128,11 +20488,13 @@ class BaseMediaSampleSink { async next() { while (true) { if (track.input._disposed) { + terminated = true; closeSamples(); throw new InputDisposedError(); } else if (terminated) { return { value: void 0, done: true }; - } else if (outOfBandError) { + } else if (hasOutOfBandError) { + terminated = true; closeSamples(); throw outOfBandError; } else if (sampleQueue.length > 0) { @@ -18186,12 +20548,13 @@ class VideoDecoderWrapper extends DecoderWrapper { this.colorQueue = []; this.alphaQueue = []; this.merger = null; - this.mergerCreationFailed = false; this.decodedAlphaChunkCount = 0; this.alphaDecoderQueueSize = 0; this.nullAlphaFrameQueue = []; this.currentAlphaPacketIndex = 0; this.alphaRaslSkipped = false; + this.finalSamples = []; + this.mergeAlphaPromises = []; const MatchingCustomDecoder = customVideoDecoders.find((x) => x.supports(codec, decoderConfig)); if (MatchingCustomDecoder) { this.customDecoder = new MatchingCustomDecoder(); @@ -18203,28 +20566,53 @@ class VideoDecoderWrapper extends DecoderWrapper { } this.finalizeAndEmitSample(sample); }; - void this.customDecoderCallSerializer.call(() => this.customDecoder.init()); + this.customDecoder.onError = (error) => { + onError(error); + }; + void this.customDecoderCallSerializer.call(() => this.customDecoder.init()).catch((error) => onError(error)); } else { const colorHandler = (frame) => { if (this.alphaQueue.length > 0) { const alphaFrame = this.alphaQueue.shift(); assert(alphaFrame !== void 0); - this.mergeAlpha(frame, alphaFrame); + void this.mergeAlpha(frame, alphaFrame); } else { this.colorQueue.push(frame); } }; - if (codec === "avc" && this.decoderConfig.description && isChromium()) { - const record = deserializeAvcDecoderConfigurationRecord(toUint8Array(this.decoderConfig.description)); - if (record && record.sequenceParameterSets.length > 0) { - const sps = parseAvcSps(record.sequenceParameterSets[0]); - if (sps && sps.frameMbsOnlyFlag === 0) { - this.decoderConfig = { - ...this.decoderConfig, - hardwareAcceleration: "prefer-software" - }; + if (isChromium()) { + if (codec === "avc" && this.decoderConfig.description) { + const record = deserializeAvcDecoderConfigurationRecord(toUint8Array(this.decoderConfig.description)); + if (record && record.sequenceParameterSets.length > 0) { + const sps = parseAvcSps(record.sequenceParameterSets[0]); + if (sps) { + if (sps.frameMbsOnlyFlag === 0) { + this.decoderConfig = { + ...this.decoderConfig, + hardwareAcceleration: "prefer-software" + }; + } + if (sps.maxDecFrameBuffering !== 0 && sps.bitstreamRestrictionFlag !== 1) { + record.sequenceParameterSets[0] = addAvcBitstreamRestriction(sps); + this.decoderConfig = { + ...this.decoderConfig, + description: serializeAvcDecoderConfigurationRecord(record) + }; + } + } } } + if (!colorSpaceIsComplete(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 ?? false + } + }; + } } const stack = new Error("Decoding error").stack; this.decoder = new VideoDecoder({ @@ -18260,7 +20648,7 @@ class VideoDecoderWrapper extends DecoderWrapper { } if (this.customDecoder) { this.customDecoderQueueSize++; - void this.customDecoderCallSerializer.call(() => this.customDecoder.decode(packet)).then(() => this.customDecoderQueueSize--); + void this.customDecoderCallSerializer.call(() => this.customDecoder.decode(packet)).catch((error) => this.onError(error)).finally(() => this.customDecoderQueueSize--); } else { assert(this.decoder); if (!isWebKit()) { @@ -18269,12 +20657,34 @@ class VideoDecoderWrapper extends DecoderWrapper { if (isChromium() && this.currentPacketIndex === 0) { if (this.codec === "avc") { const filteredNalUnits = []; + let hasFrameData = false; for (const loc of iterateAvcNalUnits(packet.data, this.decoderConfig)) { const type = extractNalUnitTypeForAvc(packet.data[loc.offset]); + hasFrameData || (hasFrameData = type >= 1 && type <= 5); + if (type === AvcNalUnitType.AUD) { + if (hasFrameData) { + break; + } else { + filteredNalUnits.length = 0; + } + } if (!(type >= 20 && type <= 31)) { filteredNalUnits.push(packet.data.subarray(loc.offset, loc.offset + loc.length)); } } + if (!this.decoderConfig.description) { + for (let i = 0; i < filteredNalUnits.length; i++) { + const nalUnit = filteredNalUnits[i]; + if (extractNalUnitTypeForAvc(nalUnit[0]) !== AvcNalUnitType.SPS) { + continue; + } + const sps = parseAvcSps(nalUnit); + if (sps && sps.maxDecFrameBuffering !== 0 && sps.bitstreamRestrictionFlag !== 1) { + filteredNalUnits[i] = addAvcBitstreamRestriction(sps); + } + break; + } + } const newData = concatAvcNalUnits(filteredNalUnits, this.decoderConfig); packet = new EncodedPacket(newData, packet.type, packet.timestamp, packet.duration); } else if (this.codec === "hevc") { @@ -18290,27 +20700,19 @@ class VideoDecoderWrapper extends DecoderWrapper { this.currentPacketIndex++; } decodeAlphaData(packet) { - if (!packet.sideData.alpha || this.mergerCreationFailed) { + if (!packet.sideData.alpha) { this.pushNullAlphaFrame(); return; } if (!this.merger) { - try { - this.merger = new ColorAlphaMerger(); - } catch (error) { - console.error("Due to an error, only color data will be decoded.", error); - this.mergerCreationFailed = true; - this.decodeAlphaData(packet); - return; - } + this.merger = new ColorAlphaMerger(); } if (!this.alphaDecoder) { const alphaHandler = (frame) => { - this.alphaDecoderQueueSize--; if (this.colorQueue.length > 0) { const colorFrame = this.colorQueue.shift(); assert(colorFrame !== void 0); - this.mergeAlpha(colorFrame, frame); + void this.mergeAlpha(colorFrame, frame); } else { this.alphaQueue.push(frame); } @@ -18320,11 +20722,12 @@ class VideoDecoderWrapper extends DecoderWrapper { if (this.colorQueue.length > 0) { const colorFrame = this.colorQueue.shift(); assert(colorFrame !== void 0); - this.mergeAlpha(colorFrame, null); + void this.mergeAlpha(colorFrame, null); } else { this.alphaQueue.push(null); } } + this.alphaDecoderQueueSize--; }; const stack = new Error("Decoding error").stack; this.alphaDecoder = new VideoDecoder({ @@ -18406,22 +20809,30 @@ class VideoDecoderWrapper extends DecoderWrapper { sample.setRotation(this.rotation); this.onSample(sample); } - mergeAlpha(color, alpha) { - if (!alpha) { - const finalSample2 = new VideoSample(color); - this.sampleHandler(finalSample2); - return; + async mergeAlpha(color, alpha) { + const resolver = promiseWithResolvers(); + this.mergeAlphaPromises.push(resolver.promise); + const result = { sample: null }; + this.finalSamples.push(result); + try { + if (!alpha) { + result.sample = new VideoSample(color); + } else { + assert(this.merger); + const finalFrame = await this.merger.merge(color, alpha); + result.sample = new VideoSample(finalFrame); + } + while (this.finalSamples.length > 0 && this.finalSamples[0].sample !== null) { + const next = this.finalSamples.shift(); + this.sampleHandler(next.sample); + } + } catch (error) { + removeItem(this.finalSamples, result); + this.onError(error); + } finally { + removeItem(this.mergeAlphaPromises, resolver.promise); + resolver.resolve(); } - assert(this.merger); - this.merger.update(color, alpha); - color.close(); - alpha.close(); - const finalFrame = new VideoFrame(this.merger.canvas, { - timestamp: color.timestamp, - duration: color.duration ?? void 0 - }); - const finalSample = new VideoSample(finalFrame); - this.sampleHandler(finalSample); } async flush() { if (this.customDecoder) { @@ -18432,6 +20843,7 @@ class VideoDecoderWrapper extends DecoderWrapper { this.decoder.flush(), this.alphaDecoder?.flush() ]); + await Promise.all(this.mergeAlphaPromises); this.colorQueue.forEach((x) => x.close()); this.colorQueue.length = 0; this.alphaQueue.forEach((x) => x?.close()); @@ -18457,8 +20869,12 @@ class VideoDecoderWrapper extends DecoderWrapper { void this.customDecoderCallSerializer.call(() => this.customDecoder.close()); } else { assert(this.decoder); - this.decoder.close(); - this.alphaDecoder?.close(); + if (this.decoder.state !== "closed") { + this.decoder.close(); + } + if (this.alphaDecoder && this.alphaDecoder.state !== "closed") { + this.alphaDecoder.close(); + } this.colorQueue.forEach((x) => x.close()); this.colorQueue.length = 0; this.alphaQueue.forEach((x) => x?.close()); @@ -18471,146 +20887,259 @@ class VideoDecoderWrapper extends DecoderWrapper { this.sampleQueue.length = 0; } } +let mergerWorkerUrl = null; class ColorAlphaMerger { constructor() { - if (typeof OffscreenCanvas !== "undefined") { - this.canvas = new OffscreenCanvas(300, 150); - } else { - this.canvas = document.createElement("canvas"); + this.workers = []; + this.nextWorkerIndex = 0; + this.pendingRequests = /* @__PURE__ */ new Map(); + this.nextRequestId = 0; + } + merge(color, alpha) { + if (this.workers.length === 0) { + if (!mergerWorkerUrl) { + const blob = new Blob([`(${colorAlphaMergerWorkerCode.toString()})()`], { type: "application/javascript" }); + mergerWorkerUrl = URL.createObjectURL(blob); + } + const poolSize = clamp$1(navigator.hardwareConcurrency, 1, 4); + for (let i = 0; i < poolSize; i++) { + const worker2 = new Worker(mergerWorkerUrl); + worker2.addEventListener("message", (event) => { + const data = event.data; + const pending2 = this.pendingRequests.get(data.id); + if (!pending2) { + return; + } + this.pendingRequests.delete(data.id); + if ("error" in data) { + pending2.reject(new Error(data.error)); + } else { + pending2.resolve(data.frame); + } + }); + worker2.addEventListener("error", (event) => { + const error = new Error(event.message || "Color/alpha merge worker error."); + for (const pending2 of this.pendingRequests.values()) { + pending2.reject(error); + } + this.pendingRequests.clear(); + }); + this.workers.push(worker2); + } } - const gl = this.canvas.getContext("webgl2", { - premultipliedAlpha: false - }); - if (!gl) { - throw new Error("Couldn't acquire WebGL 2 context."); - } - this.gl = gl; - this.program = this.createProgram(); - this.vao = this.createVAO(); - this.colorTexture = this.createTexture(); - this.alphaTexture = this.createTexture(); - this.gl.useProgram(this.program); - this.gl.uniform1i(this.gl.getUniformLocation(this.program, "u_colorTexture"), 0); - this.gl.uniform1i(this.gl.getUniformLocation(this.program, "u_alphaTexture"), 1); - } - createProgram() { - const vertexShader = this.createShader(this.gl.VERTEX_SHADER, `#version 300 es - in vec2 a_position; - in vec2 a_texCoord; - out vec2 v_texCoord; - - void main() { - gl_Position = vec4(a_position, 0.0, 1.0); - v_texCoord = a_texCoord; - } - `); - const fragmentShader = this.createShader(this.gl.FRAGMENT_SHADER, `#version 300 es - precision highp float; - - uniform sampler2D u_colorTexture; - uniform sampler2D u_alphaTexture; - in vec2 v_texCoord; - out vec4 fragColor; - - void main() { - vec3 color = texture(u_colorTexture, v_texCoord).rgb; - float alpha = texture(u_alphaTexture, v_texCoord).r; - fragColor = vec4(color, alpha); - } - `); - const program = this.gl.createProgram(); - this.gl.attachShader(program, vertexShader); - this.gl.attachShader(program, fragmentShader); - this.gl.linkProgram(program); - return program; - } - createShader(type, source) { - const shader = this.gl.createShader(type); - this.gl.shaderSource(shader, source); - this.gl.compileShader(shader); - return shader; - } - createVAO() { - const vao = this.gl.createVertexArray(); - this.gl.bindVertexArray(vao); - const vertices = new Float32Array([ - -1, - -1, - 0, - 1, - 1, - -1, - 1, - 1, - -1, - 1, - 0, - 0, - 1, - 1, - 1, - 0 - ]); - const buffer = this.gl.createBuffer(); - this.gl.bindBuffer(this.gl.ARRAY_BUFFER, buffer); - this.gl.bufferData(this.gl.ARRAY_BUFFER, vertices, this.gl.STATIC_DRAW); - const positionLocation = this.gl.getAttribLocation(this.program, "a_position"); - const texCoordLocation = this.gl.getAttribLocation(this.program, "a_texCoord"); - this.gl.enableVertexAttribArray(positionLocation); - this.gl.vertexAttribPointer(positionLocation, 2, this.gl.FLOAT, false, 16, 0); - this.gl.enableVertexAttribArray(texCoordLocation); - this.gl.vertexAttribPointer(texCoordLocation, 2, this.gl.FLOAT, false, 16, 8); - return vao; - } - createTexture() { - const texture = this.gl.createTexture(); - this.gl.bindTexture(this.gl.TEXTURE_2D, texture); - this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_S, this.gl.CLAMP_TO_EDGE); - this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_T, this.gl.CLAMP_TO_EDGE); - this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_MIN_FILTER, this.gl.LINEAR); - this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_MAG_FILTER, this.gl.LINEAR); - return texture; - } - update(color, alpha) { - if (color.displayWidth !== this.canvas.width || color.displayHeight !== this.canvas.height) { - this.canvas.width = color.displayWidth; - this.canvas.height = color.displayHeight; - } - this.gl.activeTexture(this.gl.TEXTURE0); - this.gl.bindTexture(this.gl.TEXTURE_2D, this.colorTexture); - this.gl.texImage2D(this.gl.TEXTURE_2D, 0, this.gl.RGBA, this.gl.RGBA, this.gl.UNSIGNED_BYTE, color); - this.gl.activeTexture(this.gl.TEXTURE1); - this.gl.bindTexture(this.gl.TEXTURE_2D, this.alphaTexture); - this.gl.texImage2D(this.gl.TEXTURE_2D, 0, this.gl.RGBA, this.gl.RGBA, this.gl.UNSIGNED_BYTE, alpha); - this.gl.viewport(0, 0, this.canvas.width, this.canvas.height); - this.gl.clear(this.gl.COLOR_BUFFER_BIT); - this.gl.bindVertexArray(this.vao); - this.gl.drawArrays(this.gl.TRIANGLE_STRIP, 0, 4); + const id = this.nextRequestId++; + const pending = promiseWithResolvers(); + this.pendingRequests.set(id, pending); + const worker = this.workers[this.nextWorkerIndex]; + this.nextWorkerIndex = (this.nextWorkerIndex + 1) % this.workers.length; + worker.postMessage({ id, color, alpha }, { transfer: [color, alpha] }); + return pending.promise; } close() { - this.gl.getExtension("WEBGL_lose_context")?.loseContext(); - this.gl = null; + for (const worker of this.workers) { + worker.terminate(); + } + this.workers.length = 0; + const error = new Error("Color/alpha merger closed."); + for (const pending of this.pendingRequests.values()) { + pending.reject(error); + } + this.pendingRequests.clear(); } } +const colorAlphaMergerWorkerCode = () => { + let cpuAlphaBuffer = null; + let cpuColorBuffer = null; + let chain = Promise.resolve(); + self.addEventListener("message", (event) => { + const { id, color, alpha } = event.data; + chain = chain.then(async () => { + try { + const frame = await merge(color, alpha); + self.postMessage({ id, frame }, { transfer: [frame] }); + } catch (error) { + self.postMessage({ id, error: error.message }); + } finally { + color.close(); + alpha.close(); + } + }); + }); + const merge = async (color, alpha) => { + const format = color.format; + const alphaFormat = alpha.format; + if (!format || !alphaFormat) { + throw new Error("CPU color/alpha merging requires a known VideoFrame format."); + } + const colorIs10 = format.includes("P10"); + const colorIs12 = format.includes("P12"); + const alphaIs10 = alphaFormat.includes("P10"); + const alphaIs12 = alphaFormat.includes("P12"); + if (alphaIs10 !== colorIs10 || alphaIs12 !== colorIs12) { + throw new Error(`CPU color/alpha merging requires the alpha frame to have the same bit depth as the color frame (color: '${format}', alpha: '${alphaFormat}').`); + } + if (format === "RGBX" || format === "RGBA" || format === "BGRX" || format === "BGRA") { + return await mergeInterleavedRgba(color, alpha, format); + } else if (format === "I420" || format === "I420P10" || format === "I420P12" || format === "I422" || format === "I422P10" || format === "I422P12" || format === "I444" || format === "I444P10" || format === "I444P12") { + return await mergePlanarYuv(color, alpha, format); + } else if (format === "NV12") { + return await mergeNv12(color, alpha); + } + throw new Error(`CPU color/alpha merging does not support format '${format}'.`); + }; + const mergeInterleavedRgba = async (color, alpha, format) => { + const width = color.visibleRect?.width ?? color.codedWidth; + const height = color.visibleRect?.height ?? color.codedHeight; + const pixelCount = width * height; + const output = new Uint8Array(pixelCount * 4); + await color.copyTo(output); + const alphaY = await readAlpha(alpha, width, height, 1); + for (let i = 0, j = 3; i < pixelCount; i++, j += 4) { + output[j] = alphaY[i]; + } + const outputFormat = format === "RGBX" || format === "RGBA" ? "RGBA" : "BGRA"; + const init = { + format: outputFormat, + codedWidth: width, + codedHeight: height, + timestamp: color.timestamp, + duration: color.duration ?? void 0, + transfer: [output.buffer] + }; + return new VideoFrame(output, init); + }; + const mergePlanarYuv = async (color, alpha, format) => { + const width = color.visibleRect?.width ?? color.codedWidth; + const height = color.visibleRect?.height ?? color.codedHeight; + const is10 = format.includes("P10"); + const is12 = format.includes("P12"); + const bytesPerSample = is10 || is12 ? 2 : 1; + let chromaW; + let chromaH; + if (format.startsWith("I420")) { + chromaW = Math.ceil(width / 2); + chromaH = Math.ceil(height / 2); + } else if (format.startsWith("I422")) { + chromaW = Math.ceil(width / 2); + chromaH = height; + } else { + chromaW = width; + chromaH = height; + } + const ySamples = width * height; + const uvSamples = chromaW * chromaH; + const yBytes = ySamples * bytesPerSample; + const uvBytes = uvSamples * bytesPerSample; + const aBytes = ySamples * bytesPerSample; + const outputBytes = yBytes + 2 * uvBytes + aBytes; + const output = new Uint8Array(outputBytes); + await color.copyTo(output); + const alphaY = await readAlpha(alpha, width, height, bytesPerSample); + const aOffset = yBytes + 2 * uvBytes; + output.set(alphaY, aOffset); + const outputFormat = format.slice(0, 4) + "A" + format.slice(4); + const init = { + format: outputFormat, + codedWidth: width, + codedHeight: height, + timestamp: color.timestamp, + duration: color.duration ?? void 0, + transfer: [output.buffer] + }; + return new VideoFrame(output, init); + }; + const mergeNv12 = async (color, alpha) => { + const width = color.visibleRect?.width ?? color.codedWidth; + const height = color.visibleRect?.height ?? color.codedHeight; + const ySize = width * height; + const chromaW = Math.ceil(width / 2); + const chromaH = Math.ceil(height / 2); + const uvSize = chromaW * chromaH; + const sourceSize = color.allocationSize(); + if (!cpuColorBuffer || cpuColorBuffer.byteLength !== sourceSize) { + cpuColorBuffer = new Uint8Array(sourceSize); + } + await color.copyTo(cpuColorBuffer); + const output = new Uint8Array(ySize + 2 * uvSize + ySize); + output.set(cpuColorBuffer.subarray(0, ySize), 0); + const uOffset = ySize; + const vOffset = ySize + uvSize; + const uvStart = ySize; + for (let i = 0; i < uvSize; i++) { + output[uOffset + i] = cpuColorBuffer[uvStart + i * 2]; + output[vOffset + i] = cpuColorBuffer[uvStart + i * 2 + 1]; + } + const alphaY = await readAlpha(alpha, width, height, 1); + output.set(alphaY, ySize + 2 * uvSize); + const init = { + format: "I420A", + codedWidth: width, + codedHeight: height, + timestamp: color.timestamp, + duration: color.duration ?? void 0, + transfer: [output.buffer] + }; + return new VideoFrame(output, init); + }; + const readAlpha = async (alpha, width, height, bytesPerSample) => { + const size = alpha.allocationSize(); + if (!cpuAlphaBuffer || cpuAlphaBuffer.byteLength !== size) { + cpuAlphaBuffer = new Uint8Array(size); + } + await alpha.copyTo(cpuAlphaBuffer); + const format = alpha.format; + if (format === "RGBA" || format === "BGRA" || format === "RGBX" || format === "BGRX") { + const rOffset = format === "RGBA" || format === "RGBX" ? 0 : 2; + const pixelCount = width * height; + for (let i = 0; i < pixelCount; i++) { + cpuAlphaBuffer[i] = cpuAlphaBuffer[i * 4 + rOffset]; + } + return cpuAlphaBuffer.subarray(0, pixelCount); + } else { + return cpuAlphaBuffer.subarray(0, width * height * bytesPerSample); + } + }; +}; +const validateVideoSinkDecoderOptions = (decoderOptions) => { + if (!decoderOptions || typeof decoderOptions !== "object") { + throw new TypeError("decoderOptions must be an object."); + } + if (decoderOptions.hardwareAcceleration !== void 0 && !["no-preference", "prefer-hardware", "prefer-software"].includes(decoderOptions.hardwareAcceleration)) { + throw new TypeError("decoderOptions.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'."); + } + if (decoderOptions.optimizeForLatency !== void 0 && typeof decoderOptions.optimizeForLatency !== "boolean") { + throw new TypeError("decoderOptions.optimizeForLatency, when provided, must be a boolean."); + } +}; class VideoSampleSink extends BaseMediaSampleSink { /** Creates a new {@link VideoSampleSink} for the given {@link InputVideoTrack}. */ - constructor(videoTrack) { + constructor(videoTrack, decoderOptions = {}) { if (!(videoTrack instanceof InputVideoTrack)) { throw new TypeError("videoTrack must be an InputVideoTrack."); } + validateVideoSinkDecoderOptions(decoderOptions); super(); this._track = videoTrack; + this._decoderOptions = decoderOptions; } /** @internal */ async _createDecoder(onSample, onError) { if (!await this._track.canDecode()) { - throw new Error("This video track cannot be decoded by this browser. Make sure to check decodability before using a track."); + if (typeof VideoDecoder === "undefined") { + throw new Error(missingWebCodecsClassMessage("VideoDecoder")); + } + throw new Error("This video track cannot be decoded in this environment. Make sure to check decodability before using a track."); } const codec = await this._track.getCodec(); const rotation = await this._track.getRotation(); - const decoderConfig = await this._track.getDecoderConfig(); + let decoderConfig = await this._track.getDecoderConfig(); const timeResolution = await this._track.getTimeResolution(); assert(codec && decoderConfig); + decoderConfig = { + ...decoderConfig, + hardwareAcceleration: this._decoderOptions.hardwareAcceleration, + optimizeForLatency: this._decoderOptions.optimizeForLatency + }; return new VideoDecoderWrapper(onSample, onError, codec, decoderConfig, rotation, timeResolution); } /** @internal */ @@ -18640,7 +21169,7 @@ class VideoSampleSink extends BaseMediaSampleSink { * @param endTimestamp - The timestamp in seconds at which to stop yielding samples (exclusive). * @param options - Options used for the underlying packet retrieval. */ - samples(startTimestamp = 0, endTimestamp = Infinity, options = {}) { + samples(startTimestamp, endTimestamp, options = {}) { return this.mediaSamplesInRange(startTimestamp, endTimestamp, options); } /** @@ -18649,6 +21178,9 @@ class VideoSampleSink extends BaseMediaSampleSink { * once, and is therefore more efficient than manually getting the sample for every timestamp. The iterator may * yield null if no frame is available for a given timestamp. * + * This method is good for sparse access of media data. If you want primarily sequential media access, prefer + * {@link VideoSampleSink.samples} instead. + * * @param timestamps - An iterable or async iterable of timestamps in seconds. * @param options - Options used for the underlying packet retrieval. */ @@ -18692,11 +21224,14 @@ class CanvasSink { if (options.poolSize !== void 0 && (typeof options.poolSize !== "number" || !Number.isInteger(options.poolSize) || options.poolSize < 0)) { throw new TypeError("poolSize must be a non-negative integer."); } + if (options.decoderOptions !== void 0) { + validateVideoSinkDecoderOptions(options.decoderOptions); + } this._videoTrack = videoTrack; this._alpha = options.alpha ?? false; this._options = options; this._fit = options.fit ?? "fill"; - this._videoSampleSink = new VideoSampleSink(videoTrack); + this._videoSampleSink = new VideoSampleSink(videoTrack, options.decoderOptions); this._canvasPool = Array.from({ length: options.poolSize ?? 0 }, () => null); } /** @internal */ @@ -18757,19 +21292,12 @@ class CanvasSink { // Firefox has VideoFrame glitches with opaque canvases }); assert(context); - context.resetTransform(); - if (!canvasIsNew) { - if (!this._alpha && isFirefox()) { - context.fillStyle = "black"; - context.fillRect(0, 0, width, height); - } else { - context.clearRect(0, 0, width, height); - } - } - sample.drawWithFit(context, { + sample._drawWithFitAndMipmapping(canvas, context, { fit: this._fit, rotation: this._rotation, - crop: this._crop + crop: this._crop, + targetIsFresh: canvasIsNew, + fillBlack: !this._alpha && isFirefox() }); const result = { canvas, @@ -18801,7 +21329,7 @@ class CanvasSink { * @param endTimestamp - The timestamp in seconds at which to stop yielding canvases (exclusive). * @param options - Options used for the underlying packet retrieval. */ - async *canvases(startTimestamp = 0, endTimestamp = Infinity, options) { + async *canvases(startTimestamp, endTimestamp, options) { await this._ensureInit(); yield* mapAsyncGenerator(this._videoSampleSink.samples(startTimestamp, endTimestamp, options), (sample) => this._videoSampleToWrappedCanvas(sample)); } @@ -18811,6 +21339,9 @@ class CanvasSink { * therefore more efficient than manually getting the canvas for every timestamp. The iterator may yield null if * no frame is available for a given timestamp. * + * This method is good for sparse access of media data. If you want primarily sequential media access, prefer + * {@link CanvasSink.canvases} instead. + * * @param timestamps - An iterable or async iterable of timestamps in seconds. * @param options - Options used for the underlying packet retrieval. */ @@ -18827,9 +21358,16 @@ class AudioDecoderWrapper extends DecoderWrapper { this.customDecoderCallSerializer = new CallSerializer(); this.customDecoderQueueSize = 0; this.currentTimestamp = null; + this.expectedFirstTimestamp = null; + this.timestampOffset = 0; const sampleHandler = (sample) => { - if (this.currentTimestamp === null || Math.abs(sample.timestamp - this.currentTimestamp) >= sample.duration) { - this.currentTimestamp = sample.timestamp; + let sampleTimestamp = sample.timestamp; + if (this.expectedFirstTimestamp !== null && this.currentTimestamp === null) { + this.timestampOffset = this.expectedFirstTimestamp - sampleTimestamp; + } + sampleTimestamp += this.timestampOffset; + if (this.currentTimestamp === null || Math.abs(sampleTimestamp - this.currentTimestamp) >= sample.duration) { + this.currentTimestamp = sampleTimestamp; } const preciseTimestamp = this.currentTimestamp; this.currentTimestamp += sample.duration; @@ -18852,7 +21390,10 @@ class AudioDecoderWrapper extends DecoderWrapper { } sampleHandler(sample); }; - void this.customDecoderCallSerializer.call(() => this.customDecoder.init()); + this.customDecoder.onError = (error) => { + onError(error); + }; + void this.customDecoderCallSerializer.call(() => this.customDecoder.init()).catch((error) => onError(error)); } else { const stack = new Error("Decoding error").stack; this.decoder = new AudioDecoder({ @@ -18882,26 +21423,32 @@ class AudioDecoderWrapper extends DecoderWrapper { decode(packet) { if (this.customDecoder) { this.customDecoderQueueSize++; - void this.customDecoderCallSerializer.call(() => this.customDecoder.decode(packet)).then(() => this.customDecoderQueueSize--); + void this.customDecoderCallSerializer.call(() => this.customDecoder.decode(packet)).catch((error) => this.onError(error)).finally(() => this.customDecoderQueueSize--); } else { assert(this.decoder); + this.expectedFirstTimestamp ?? (this.expectedFirstTimestamp = packet.timestamp); this.decoder.decode(packet.toEncodedAudioChunk()); } } - flush() { + async flush() { if (this.customDecoder) { - return this.customDecoderCallSerializer.call(() => this.customDecoder.flush()); + await this.customDecoderCallSerializer.call(() => this.customDecoder.flush()); } else { assert(this.decoder); - return this.decoder.flush(); + await this.decoder.flush(); } + this.currentTimestamp = null; + this.expectedFirstTimestamp = null; + this.timestampOffset = 0; } close() { if (this.customDecoder) { void this.customDecoderCallSerializer.call(() => this.customDecoder.close()); } else { assert(this.decoder); - this.decoder.close(); + if (this.decoder.state !== "closed") { + this.decoder.close(); + } } } } @@ -19080,7 +21627,10 @@ class AudioSampleSink extends BaseMediaSampleSink { /** @internal */ async _createDecoder(onSample, onError) { if (!await this._track.canDecode()) { - throw new Error("This audio track cannot be decoded by this browser. Make sure to check decodability before using a track."); + if (typeof AudioDecoder === "undefined") { + throw new Error(missingWebCodecsClassMessage("AudioDecoder")); + } + throw new Error("This audio track cannot be decoded in this environment. Make sure to check decodability before using a track."); } const codec = await this._track.getCodec(); const decoderConfig = await this._track.getDecoderConfig(); @@ -19118,7 +21668,7 @@ class AudioSampleSink extends BaseMediaSampleSink { * @param endTimestamp - The timestamp in seconds at which to stop yielding samples (exclusive). * @param options - Options used for the underlying packet retrieval. */ - samples(startTimestamp = 0, endTimestamp = Infinity, options = {}) { + samples(startTimestamp, endTimestamp, options = {}) { return this.mediaSamplesInRange(startTimestamp, endTimestamp, options); } /** @@ -19127,6 +21677,9 @@ class AudioSampleSink extends BaseMediaSampleSink { * once, and is therefore more efficient than manually getting the sample for every timestamp. The iterator may * yield null if no sample is available for a given timestamp. * + * This method is good for sparse access of media data. If you want primarily sequential media access, prefer + * {@link AudioSampleSink.samples} instead. + * * @param timestamps - An iterable or async iterable of timestamps in seconds. * @param options - Options used for the underlying packet retrieval. */ @@ -19173,7 +21726,7 @@ class AudioBufferSink { * @param endTimestamp - The timestamp in seconds at which to stop yielding buffers (exclusive). * @param options - Options used for the underlying packet retrieval. */ - buffers(startTimestamp = 0, endTimestamp = Infinity, options) { + buffers(startTimestamp, endTimestamp, options) { return mapAsyncGenerator(this._audioSampleSink.samples(startTimestamp, endTimestamp, options), (data) => this._audioSampleToWrappedArrayBuffer(data)); } /** @@ -19285,6 +21838,26 @@ class InputTrack { async isRelativeToUnixEpoch() { return this._backing.isRelativeToUnixEpoch(); } + /** + * Returns the Unix time (in seconds since January 1, 1970 00:00:00 UTC) that the given track timestamp (in seconds) + * maps to, or `null` if there is no such mapping. This provides a piecewise-continuous mapping from this track's + * timestamp space into wall-clock time. Such mapping exists, for example, for HLS playlists with + * `#EXT-X-PROGRAM-DATE-TIME` tags present. + * + * This mapping can be available even when {@link InputTrack.isRelativeToUnixEpoch} is `false`, for example for HLS + * streams with program date time information but with {@link HlsInputFormatOptions.offsetTimestampsByDateTime} + * set to `false`. + */ + async getUnixTimeForTimestamp(timestamp) { + return this._backing.getUnixTimeForTimestamp(timestamp); + } + /** + * Whether the track's timestamps can be mapped to Unix wall clock time via + * {@link InputTrack.getUnixTimeForTimestamp}. + */ + async hasUnixTimeMapping() { + return await this._backing.getUnixTimeForTimestamp(await this.getFirstTimestamp()) !== null; + } /** Returns the track's disposition, i.e. information about its intended usage. */ async getDisposition() { return this._backing.getDisposition(); @@ -19474,7 +22047,7 @@ class InputTrack { } } const requireSync = (value, getterName, asyncName) => { - if (value instanceof Promise) { + if (isThenable(value)) { throw new Error(`'${getterName}' is deprecated and not available synchronously for this track. Use the preferred '${asyncName}()' instead.`); } return value; @@ -19491,7 +22064,7 @@ const toValidatedPredicate = (predicate) => { return result2; }; const result = predicate(track); - if (result instanceof Promise) { + if (isThenable(result)) { return result.then(handle); } return handle(result); @@ -19519,7 +22092,7 @@ class InputVideoTrack extends InputTrack { return requireSync(this._backing.getCodec(), "codec", "getCodec"); } async hasOnlyKeyPackets() { - return await this._backing.getHasOnlyKeyPackets?.() ?? false; + return await this._backing.getHasOnlyKeyPackets?.() ?? await this._backing.getCodec() === "prores"; } /** Returns the width in pixels of the track's coded samples, before any transformations or rotations. */ async getCodedWidth() { @@ -19658,7 +22231,7 @@ class InputVideoTrack extends InputTrack { /** If this method returns true, the track's samples use a high dynamic range (HDR). */ async hasHighDynamicRange() { const colorSpace = await this._backing.getColorSpace(); - return colorSpace.primaries === "bt2020" || colorSpace.primaries === "smpte432" || colorSpace.transfer === "pg" || colorSpace.transfer === "hlg" || colorSpace.matrix === "bt2020-ncl"; + return colorSpace.primaries === "bt2020" || colorSpace.primaries === "smpte432" || colorSpace.transfer === "pq" || colorSpace.transfer === "hlg" || colorSpace.matrix === "bt2020-ncl"; } /** Checks if this track may contain transparent samples with alpha data. */ async canBeTransparent() { @@ -19697,7 +22270,7 @@ class InputVideoTrack extends InputTrack { const support = await VideoDecoder.isConfigSupported(decoderConfig); return support.supported === true; } catch (error) { - console.error("Error during decodability check:", error); + Logging._error("Error during decodability check:", error); return false; } } @@ -19716,6 +22289,100 @@ class InputVideoTrack extends InputTrack { assert(decoderConfig); return determineVideoPacketType(codec, decoderConfig, packet.data); } + /** + * Computes frame rate metrics for this video track, i.e. estimates the video's frame rate. Frame rate is never + * determined from file metadata (which is unreliable) but is always deduced directly from the actual frame + * timestamps. + */ + async computeFrameRateMetrics(options = {}) { + if (!options || typeof options !== "object") { + throw new TypeError("options must be an object."); + } + if (options.targetPacketCount !== void 0 && (!isNumber(options.targetPacketCount) || options.targetPacketCount < 0)) { + throw new TypeError("options.targetPacketCount must be a non-negative number."); + } + const timeResolution = await this.getTimeResolution(); + const targetPacketCount = options.targetPacketCount ?? 256; + const sink = new EncodedPacketSink(this); + const timestamps = []; + let maxTimestamp = -Infinity; + let probedPacketCount = 0; + for await (const packet of sink.packets(void 0, void 0, { metadataOnly: true })) { + if (timestamps.length >= targetPacketCount && packet.timestamp >= maxTimestamp) { + break; + } + timestamps.push(packet.timestamp); + maxTimestamp = Math.max(maxTimestamp, packet.timestamp); + probedPacketCount++; + } + const ticks = new Float64Array(timestamps.length); + for (let i = 0; i < timestamps.length; i++) { + ticks[i] = Math.round(timestamps[i] * timeResolution); + } + ticks.sort(); + let n = 1; + for (let i = 1; i < ticks.length; i++) { + if (ticks[i] !== ticks[n - 1]) { + ticks[n++] = ticks[i]; + } + } + if (n < 2) { + return { + underlyingFrameRate: null, + bestGuessFrameRate: timeResolution, + minFrameRate: timeResolution, + maxFrameRate: timeResolution, + averageFrameRate: timeResolution, + medianFrameRate: timeResolution, + frameRateIsConstant: true, + probedPacketCount + }; + } + const activeTicks = ticks.subarray(0, n); + const underlyingFrameRate = findUnderlyingFrameRate(activeTicks, timeResolution); + const unitRate = underlyingFrameRate ?? timeResolution; + const ticksPerFrame = underlyingFrameRate !== null ? timeResolution / underlyingFrameRate : null; + const histogram = /* @__PURE__ */ new Map(); + let minDifference = Infinity; + let maxDifference = -Infinity; + let totalDifference = 0; + for (let i = 1; i < n; i++) { + const tickDifference = activeTicks[i] - activeTicks[i - 1]; + const difference = ticksPerFrame !== null ? Math.max(1, Math.round(tickDifference / ticksPerFrame)) : tickDifference; + histogram.set(difference, (histogram.get(difference) ?? 0) + 1); + minDifference = Math.min(minDifference, difference); + maxDifference = Math.max(maxDifference, difference); + totalDifference += difference; + } + const differenceCount = n - 1; + const sortedDifferences = [...histogram.keys()].sort((a, b) => a - b); + const middleA = differenceCount - 1 >> 1; + const middleB = differenceCount >> 1; + let medianDifferenceA = 0; + let medianDifferenceB = 0; + let cumulativeCount = 0; + for (const difference of sortedDifferences) { + cumulativeCount += histogram.get(difference); + if (medianDifferenceA === 0 && cumulativeCount > middleA) { + medianDifferenceA = difference; + } + if (cumulativeCount > middleB) { + medianDifferenceB = difference; + break; + } + } + const medianFrameRate = (unitRate / medianDifferenceA + unitRate / medianDifferenceB) / 2; + return { + underlyingFrameRate, + bestGuessFrameRate: underlyingFrameRate !== null ? underlyingFrameRate : getBestGuessFrameRate(medianFrameRate), + minFrameRate: unitRate / maxDifference, + maxFrameRate: unitRate / minDifference, + averageFrameRate: unitRate * differenceCount / totalDifference, + medianFrameRate, + frameRateIsConstant: underlyingFrameRate !== null && minDifference === 1 && maxDifference === 1, + probedPacketCount + }; + } } class InputAudioTrack extends InputTrack { /** @internal */ @@ -19799,7 +22466,7 @@ class InputAudioTrack extends InputTrack { return support.supported === true; } } catch (error) { - console.error("Error during decodability check:", error); + Logging._error("Error during decodability check:", error); return false; } } @@ -19838,7 +22505,7 @@ const toValidatedInputTrackQuery = (query) => { return bool; }; const result = query.filter(track); - if (result instanceof Promise) { + if (isThenable(result)) { return result.then(handle); } else { return handle(result); @@ -19852,7 +22519,7 @@ const toValidatedInputTrackQuery = (query) => { return value; }; const result = query.sortBy(track); - if (result instanceof Promise) { + if (isThenable(result)) { return result.then(handle); } else { return handle(result); @@ -19870,7 +22537,7 @@ const mergeInputTrackQueries = (queryA, queryB) => { } return queryB?.filter?.(track) ?? true; }; - if (resultA instanceof Promise) { + if (isThenable(resultA)) { return resultA.then(handleResultA); } else { return handleResultA(resultA); @@ -19885,7 +22552,7 @@ const mergeInputTrackQueries = (queryA, queryB) => { ...Array.isArray(resultB2) ? resultB2 : [resultB2] ]; }; - if (resultA instanceof Promise || resultB instanceof Promise) { + if (isThenable(resultA) || isThenable(resultB)) { return Promise.all([resultA, resultB]).then(([resultA2, resultB2]) => { return join(resultA2, resultB2); }); @@ -19899,7 +22566,7 @@ const queryInputTracks = async (tracks, query) => { let matched = tracks; if (query?.filter) { const filterMatches = tracks.map((t) => query.filter(t)); - const hasAsyncFilter = filterMatches.some((x) => x instanceof Promise); + const hasAsyncFilter = filterMatches.some((x) => isThenable(x)); if (hasAsyncFilter) { const resolvedFilterMatches = await Promise.all(filterMatches); matched = tracks.filter((_, i) => resolvedFilterMatches[i]); @@ -19911,7 +22578,7 @@ const queryInputTracks = async (tracks, query) => { return matched; } const sortValues = matched.map((t) => query.sortBy(t)); - const hasAsyncSort = sortValues.some((x) => x instanceof Promise); + const hasAsyncSort = sortValues.some((x) => isThenable(x)); const resolvedSortValues = hasAsyncSort ? await Promise.all(sortValues) : sortValues; return matched.map((track, i) => ({ track, sortValue: resolvedSortValues[i] })).sort((a, b) => { const aValues = Array.isArray(a.sortValue) ? a.sortValue : [a.sortValue]; @@ -19928,19 +22595,175 @@ const queryInputTracks = async (tracks, query) => { return 0; }).map((x) => x.track); }; +const findUnderlyingFrameRate = (ticks, resolution) => { + const MAX_DENOMINATOR = 1e6; + const MIN_INLIER_RATIO = 0.98; + const DELTA_TOLERANCE = 1 + 1e-9; + const MAX_EFFECTIVE_FRAME_SPAN = 1e3; + const KNOWN_FRAME_RATES = [ + 12, + 15, + 20, + 24e3 / 1001, + 24, + 25, + 3e4 / 1001, + 30, + 48, + 50, + 6e4 / 1001, + 60, + 100, + 12e4 / 1001, + 120, + 144, + 240 + ]; + if (ticks.length < 2) { + return null; + } + const gaps = new Float64Array(ticks.length - 1); + for (let i = 1; i < ticks.length; i++) { + const gap = ticks[i] - ticks[i - 1]; + if (!(gap > 0)) { + return null; + } + gaps[i - 1] = gap; + } + const sortedGaps = gaps.slice(); + sortedGaps.sort(); + let period = sortedGaps[Math.floor(sortedGaps.length * 0.05)]; + for (let iteration = 0; iteration < 6; iteration++) { + let totalTicks2 = 0; + let totalFrames2 = 0; + for (const gap of gaps) { + const multiple = Math.max(1, Math.round(gap / period)); + if (Math.abs(gap - multiple * period) >= DELTA_TOLERANCE) { + continue; + } + totalTicks2 += gap; + totalFrames2 += multiple; + } + if (totalFrames2 === 0) { + return null; + } + const refinedPeriod = totalTicks2 / totalFrames2; + if (Math.abs(refinedPeriod - period) <= 1e-12 * Math.max(1, period)) { + period = refinedPeriod; + break; + } + period = refinedPeriod; + } + let inlierCount = 0; + let totalTicks = 0; + let totalFrames = 0; + for (const gap of gaps) { + const multiple = Math.max(1, Math.round(gap / period)); + if (Math.abs(gap - multiple * period) >= DELTA_TOLERANCE) { + continue; + } + inlierCount++; + totalTicks += gap; + totalFrames += multiple; + } + if (inlierCount / gaps.length < MIN_INLIER_RATIO) { + return null; + } + period = totalTicks / totalFrames; + const uncertainty = 1 / Math.min(totalFrames, MAX_EFFECTIVE_FRAME_SPAN); + const periodLo = Math.max(Number.EPSILON, period - uncertainty); + const periodHi = period + uncertainty; + const fpsLo = resolution / periodHi; + const fpsHi = resolution / periodLo; + const fittedFps = resolution / period; + let fps = null; + let bestKnownError = Infinity; + for (const candidate of KNOWN_FRAME_RATES) { + if (candidate < fpsLo || candidate > fpsHi) { + continue; + } + const error = Math.abs(candidate / fittedFps - 1); + if (error < bestKnownError) { + fps = candidate; + bestKnownError = error; + } + } + if (fps === null) { + const periodFraction = simplestFractionBetween(periodLo, periodHi, MAX_DENOMINATOR); + const fpsFraction = simplestFractionBetween(fpsLo, fpsHi, MAX_DENOMINATOR); + if (fpsFraction && (!periodFraction || fpsFraction.den < periodFraction.den || fpsFraction.den === periodFraction.den && fpsFraction.num <= periodFraction.num)) { + fps = fpsFraction.num / fpsFraction.den; + } else if (periodFraction) { + fps = resolution * periodFraction.den / periodFraction.num; + } else { + return null; + } + } + const finalPeriod = resolution / fps; + let finalInlierCount = 0; + for (const gap of gaps) { + const multiple = Math.max(1, Math.round(gap / finalPeriod)); + if (Math.abs(gap - multiple * finalPeriod) < DELTA_TOLERANCE) { + finalInlierCount++; + } + } + if (finalInlierCount / gaps.length < MIN_INLIER_RATIO) { + return null; + } + return fps; +}; +const simplestFractionBetween = (lo, hi, maxDenominator) => { + for (let den = 1; den <= maxDenominator; den++) { + const num = Math.floor(lo * den) + 1; + if (num / den < hi) { + return simplifyRational({ num, den }); + } + } + return null; +}; +const getBestGuessFrameRate = (frameRate) => { + const SPECIAL_FRAME_RATES = [ + 24 / 1.001, + 30 / 1.001, + 60 / 1.001, + 120 / 1.001 + ]; + const COMMON_FRAME_RATES = [ + 12, + 15, + 20, + 24, + 25, + 30, + 48, + 50, + 60, + 100, + 120, + 144, + 240 + ]; + const SPECIAL_TOLERANCE = 5e-4; + const COMMON_TOLERANCE = 0.025; + for (const candidate of SPECIAL_FRAME_RATES) { + if (Math.abs(candidate / frameRate - 1) <= SPECIAL_TOLERANCE) { + return candidate; + } + } + let best = frameRate; + let bestError = Infinity; + for (const candidate of COMMON_FRAME_RATES) { + const error = Math.abs(candidate / frameRate - 1); + if (error <= COMMON_TOLERANCE && error < bestError) { + best = candidate; + bestError = error; + } + } + return best; +}; polyfillSymbolDispose(); const DEFAULT_SOURCE_CACHE_GROUP = 1; const ENCRYPTION_KEY_CACHE_GROUP = 2; -let inputFinalizationRegistry = null; -if (typeof FinalizationRegistry !== "undefined") { - inputFinalizationRegistry = new FinalizationRegistry((refs) => { - for (const ref of refs) { - if (!ref.freed) { - ref.free(); - } - } - }); -} class Input extends EventEmitter { /** True if the input has been disposed. */ get disposed() { @@ -19989,7 +22812,6 @@ class Input extends EventEmitter { this._rootRef = options.source; } this._sourceRefs.push(this._rootRef); - inputFinalizationRegistry?.register(this, this._sourceRefs, this); } /** @internal */ get _rootSource() { @@ -20107,8 +22929,9 @@ class Input extends EventEmitter { if (filtered.length === 0) { return 0; } - const firstTimestamps = await Promise.all(filtered.map((x) => x.getFirstTimestamp())); - return Math.min(...firstTimestamps); + const firstPackets = await Promise.all(filtered.map((x) => x._backing.getFirstPacket({ metadataOnly: true }))); + const result = Math.min(...firstPackets.map((x) => x?.timestamp ?? Infinity)); + return result === Infinity ? 0 : result; } /** * Computes the duration of the input file, in seconds. More precisely, returns the largest end timestamp among @@ -20263,8 +23086,10 @@ class Input extends EventEmitter { ref.free(); } this._sourceRefs.length = 0; - inputFinalizationRegistry?.unregister(this); - void this._demuxerPromise?.then((demuxer) => demuxer.dispose()); + if (this._demuxerPromise) { + void this._demuxerPromise.then((demuxer) => demuxer.dispose()).catch(() => { + }); + } } /** * Calls `.dispose()` on the input, implementing the `Disposable` interface for use with @@ -20318,7 +23143,7 @@ class Reader { } const end = start + length; const result = this.source._read(start, end, DEFAULT_MIN_READ_POSITION, DEFAULT_MAX_READ_POSITION); - if (result instanceof Promise) { + if (isThenable(result)) { return result.then((x) => { if (!x) { return null; @@ -20350,7 +23175,7 @@ class Reader { assert(this.fileSizeNonStrict !== null); return this.requestSlice(start, clamp$1(this.fileSizeNonStrict - start, minLength, maxLength)); }; - if (promisedAttempt instanceof Promise) { + if (isThenable(promisedAttempt)) { return promisedAttempt.then(handleAttempt); } else { return handleAttempt(promisedAttempt); @@ -20369,14 +23194,14 @@ class Reader { if (chunks.length === 1 && this.fileSizeNonStrict !== null) { return this.requestSlice(0, this.fileSizeNonStrict); } - const startOffset = chunks.length * CHUNK_SIZE; - let slice = this.requestSliceRange(startOffset, 0, CHUNK_SIZE); - if (slice instanceof Promise) + let slice = this.requestSliceRange(currentSize, 0, CHUNK_SIZE); + if (isThenable(slice)) slice = await slice; - if (!slice) { + if (!slice || slice.length === 0) { break; } - chunks.push(readBytes(slice, slice.length)); + const chunk = readBytes(slice, slice.length); + chunks.push(chunk); currentSize += slice.length; } const joined = new Uint8Array(currentSize); @@ -20774,7 +23599,7 @@ const parseId3V1Tag = (slice, tags) => { const yearText = readId3V1String(slice, 4); const year = Number.parseInt(yearText, 10); if (Number.isInteger(year) && year > 0) { - tags.date ?? (tags.date = new Date(year, 0, 1)); + tags.date ?? (tags.date = new Date(String(year))); } const commentBytes = readBytes(slice, 30); let comment; @@ -20818,20 +23643,21 @@ const readId3V2Header = (slice) => { slice.filePos = startPos; return null; } - const size = decodeSynchsafe(sizeRaw); + let size = decodeSynchsafe(sizeRaw); + if (flags & Id3V2HeaderFlags.Footer) { + size += ID3_V2_HEADER_SIZE; + } return { majorVersion, revision, flags, size }; }; const parseId3V2Tag = (slice, header, tags) => { var _a, _b, _c, _d, _e; if (![2, 3, 4].includes(header.majorVersion)) { - console.warn(`Unsupported ID3v2 major version: ${header.majorVersion}`); + Logging._warn(`Unsupported ID3v2 major version: ${header.majorVersion}`); return; } - const bytes = readBytes(slice, header.size); + const dataSize = header.flags & Id3V2HeaderFlags.Footer ? header.size - ID3_V2_HEADER_SIZE : header.size; + const bytes = readBytes(slice, dataSize); const reader = new Id3V2Reader(header, bytes); - if (header.flags & Id3V2HeaderFlags.Footer) { - reader.removeFooter(); - } if (header.flags & Id3V2HeaderFlags.Unsynchronisation && header.majorVersion === 3) { reader.ununsynchronizeAll(); } @@ -20862,12 +23688,12 @@ const parseId3V2Tag = (slice, header, tags) => { frameUnsynchronized = !!(frame.flags & 1 << 1) || !!(header.flags & Id3V2HeaderFlags.Unsynchronisation); } if (frameEncrypted) { - console.warn(`Skipping encrypted ID3v2 frame ${frame.id}`); + Logging._warn(`Skipping encrypted ID3v2 frame ${frame.id}`); reader.pos = frameEndPos; continue; } if (frameCompressed) { - console.warn(`Skipping compressed ID3v2 frame ${frame.id}`); + Logging._warn(`Skipping compressed ID3v2 frame ${frame.id}`); reader.pos = frameEndPos; continue; } @@ -20987,7 +23813,7 @@ const parseId3V2Tag = (slice, header, tags) => { const yearText = reader.readId3V2EncodingAndText(frameEndPos); const year = Number.parseInt(yearText, 10); if (Number.isInteger(year)) { - tags.date ?? (tags.date = new Date(year, 0, 1)); + tags.date ?? (tags.date = new Date(String(year))); } } break; @@ -21090,10 +23916,6 @@ class Id3V2Reader { this.bytes.set(after, before.length + newBytes.length); this.view = new DataView(this.bytes.buffer); } - removeFooter() { - this.bytes = this.bytes.subarray(0, this.bytes.length - ID3_V2_HEADER_SIZE); - this.view = new DataView(this.bytes.buffer); - } readBytes(length) { const slice = this.bytes.subarray(this.pos, this.pos + length); this.pos += length; @@ -21111,7 +23933,7 @@ class Id3V2Reader { } readU24() { const high = this.view.getUint16(this.pos, false); - const low = this.view.getUint8(this.pos + 1); + const low = this.view.getUint8(this.pos + 2); this.pos += 3; return high * 256 + low; } @@ -21315,59 +24137,64 @@ class AudioEngine { return; await this.stopIterator(); this.audioIterator = this.audioSink.buffers(this.currentTime); + const BATCH_SIZE = 16; while (true) { if (localId !== this.asyncId || this.paused) return; - const nextPromise = this.audioIterator.next(); - const checkStarvation = setInterval(() => { - if (localId !== this.asyncId || this.paused) { - clearInterval(checkStarvation); - return; - } - if (this.audioContext.state === "running" && this.audioContext.currentTime >= this.latestScheduledEndTime - 0.2) { - this.audioContext.suspend(); - this.events.emit("waiting"); - } - }, 50); - let result; + const batch = []; + let batchDone = false; try { - result = await nextPromise; + for (let i = 0; i < BATCH_SIZE; i++) { + const result = await this.audioIterator.next(); + if (result.done) { + batchDone = true; + break; + } + batch.push(result.value); + } } catch (e) { console.error("Audio iterator error:", e); - break; - } finally { - clearInterval(checkStarvation); + batchDone = true; } if (localId !== this.asyncId || this.paused) return; - if (this.audioContext.state === "suspended") { + if (batch.length > 0 && this.audioContext.state === "suspended") { await this.audioContext.resume(); this.events.emit("canplay"); this.events.emit("playing"); } - if (result.done) + for (const { buffer, timestamp } of batch) { + const node = this.audioContext.createBufferSource(); + node.buffer = buffer; + node.connect(this.gainNode); + node.playbackRate.value = this.playbackRate; + const startAt = this.audioContextStartTime + (timestamp - this.playbackTimeAtStart) / this.playbackRate; + const duration = buffer.duration; + const endAt = startAt + duration / this.playbackRate; + const endMediaTime = (endAt - this.audioContextStartTime) * this.playbackRate + this.playbackTimeAtStart; + if (endMediaTime > this.latestScheduledEndTime) { + this.latestScheduledEndTime = endMediaTime; + } + if (startAt >= this.audioContext.currentTime) { + node.start(startAt); + } else { + node.start( + this.audioContext.currentTime, + (this.audioContext.currentTime - startAt) * this.playbackRate + ); + } + this.queuedNodes.add(node); + node.onended = () => this.queuedNodes.delete(node); + } + if (batchDone) break; - const { buffer, timestamp } = result.value; - const node = this.audioContext.createBufferSource(); - node.buffer = buffer; - node.connect(this.gainNode); - node.playbackRate.value = this.playbackRate; - const startAt = this.audioContextStartTime + (timestamp - this.playbackTimeAtStart) / this.playbackRate; - const duration = buffer.duration; - const endAt = startAt + duration / this.playbackRate; - if (endAt > this.latestScheduledEndTime) { - this.latestScheduledEndTime = endAt; + await new Promise((resolve) => setTimeout(resolve, 0)); + const BUFFER_AHEAD = 1; + while (this.latestScheduledEndTime - this.currentTime > BUFFER_AHEAD) { + if (localId !== this.asyncId || this.paused) + return; + await new Promise((resolve) => setTimeout(resolve, 50)); } - if (startAt >= this.audioContext.currentTime) { - node.start(startAt); - } else { - node.start( - this.audioContext.currentTime, - (this.audioContext.currentTime - startAt) * this.playbackRate - ); - } - this.queuedNodes.add(node); - node.onended = () => this.queuedNodes.delete(node); } } async play() { @@ -21380,7 +24207,7 @@ class AudioEngine { await this.audioContext.resume(); } this.audioContextStartTime = this.audioContext.currentTime; - this.latestScheduledEndTime = this.audioContextStartTime; + this.latestScheduledEndTime = this.playbackTimeAtStart; this.paused = false; const id = ++this.asyncId; this.runIterator(id); @@ -21396,7 +24223,7 @@ class AudioEngine { async seek(time) { this.playbackTimeAtStart = Math.max(0, time); this.audioContextStartTime = this.audioContext.currentTime; - this.latestScheduledEndTime = this.audioContextStartTime; + this.latestScheduledEndTime = this.playbackTimeAtStart; const id = ++this.asyncId; if (!this.paused) { this.runIterator(id); @@ -21429,57 +24256,6 @@ class AudioEngine { this.audioSink = null; } } -const M3U8_RE = /\.m3u8(?:$|[?#])/i; -function isHlsSource(src) { - return typeof src === "string" && M3U8_RE.test(src); -} -function normalizeSource(src) { - if (typeof src === "string") - return new UrlSource(src); - if (src instanceof Blob) - return new BlobSource(src); - if (typeof ReadableStream !== "undefined" && src instanceof ReadableStream) { - return new ReadableStreamSource(src); - } - return src ?? null; -} -function createInput(src) { - const source = normalizeSource(src); - if (!source) - return null; - return new Input({ - source, - formats: isHlsSource(src) ? HLS_FORMATS : ALL_FORMATS - }); -} -async function resolveDuration({ input, videoTrack, audioTrack }) { - const tracks = [videoTrack, audioTrack].filter(Boolean); - const referenceTrack = videoTrack || audioTrack; - const isLive = Boolean(referenceTrack && await referenceTrack.isLive()); - let duration = Number.NaN; - if (tracks.length > 0) { - duration = await input.getDurationFromMetadata(tracks, { skipLiveWait: true }); - if (duration === null && !isLive) { - duration = await input.computeDuration(tracks, { skipLiveWait: true }); - } - } - return isLive ? Number.POSITIVE_INFINITY : duration ?? Number.NaN; -} -async function selectPlaybackTracks(input, src) { - const videoTrack = await input.getPrimaryVideoTrack(); - const audioTrack = videoTrack ? await videoTrack.getPrimaryPairableAudioTrack() : await input.getPrimaryAudioTrack(); - const duration = await resolveDuration({ input, videoTrack, audioTrack }); - return { - input, - videoTrack, - audioTrack, - duration, - isLive: Number.isFinite(duration) ? false : Boolean((videoTrack || audioTrack) && await (videoTrack || audioTrack).isLive()), - isHls: isHlsSource(src), - videoMode: isHlsSource(src) ? "auto" : "manual", - audioMode: isHlsSource(src) ? "auto" : "manual" - }; -} async function getTrackBitrate(track) { return await track.getAverageBitrate() ?? await track.getBitrate() ?? 0; } @@ -21516,12 +24292,154 @@ async function getHlsState(media) { return { levels, audios, - currentLevel: media.videoTrack ? levels.find((item) => item.id === media.videoTrack.id) ?? null : null, - currentAudio: media.audioTrack ? audios.find((item) => item.id === media.audioTrack.id) ?? null : null, + currentLevel: media.videoTrack ? levels.find((item) => item.id === media.videoTrack?.id) ?? null : null, + currentAudio: media.audioTrack ? audios.find((item) => item.id === media.audioTrack?.id) ?? null : null, videoMode: media.videoMode ?? "auto", audioMode: media.audioMode ?? "auto" }; } +const M3U8_RE = /\.m3u8(?:$|[?#])/i; +function isHlsSource(src) { + return typeof src === "string" && M3U8_RE.test(src); +} +function normalizeSource(src) { + if (typeof src === "string") + return new UrlSource(src); + if (src instanceof Blob) + return new BlobSource(src); + if (typeof ReadableStream !== "undefined" && src instanceof ReadableStream) + return new ReadableStreamSource(src); + return src ?? null; +} +function createInput(src) { + const source = normalizeSource(src); + if (!source) + return null; + return new Input({ + // Preserve SDK Source/SourceRef pass-through and its historical validation errors. + source, + formats: isHlsSource(src) ? HLS_FORMATS : ALL_FORMATS + }); +} +class LoadSession { + constructor() { + this.active = true; + this.input = null; + this.timers = /* @__PURE__ */ new Set(); + this.controller = typeof AbortController === "undefined" ? void 0 : new AbortController(); + this.cancellation = new Promise((resolve) => { + this.resolveCancellation = resolve; + }); + } + get signal() { + return this.controller?.signal; + } + own(input) { + if (this.active) + this.input = input; + else input.dispose(); + } + defer(callback) { + if (!this.active) + return; + const timer = setTimeout(() => { + this.timers.delete(timer); + if (this.active) + callback(); + }, 0); + this.timers.add(timer); + } + async wait(operation, milliseconds) { + try { + await Promise.race([ + operation, + this.cancellation, + milliseconds > 0 ? this.timeout(milliseconds) : new Promise(() => { + }) + ]); + } finally { + if (this.deadline !== void 0) { + clearTimeout(this.deadline); + this.deadline = void 0; + } + } + } + timeout(milliseconds) { + return new Promise((_, reject) => { + this.deadline = setTimeout(() => reject(new Error("Load timeout")), milliseconds); + }); + } + disposeInput() { + const input = this.input; + this.input = null; + input?.dispose(); + } + cancel() { + if (!this.active) + return; + this.active = false; + for (const timer of this.timers) clearTimeout(timer); + this.timers.clear(); + if (this.deadline !== void 0) { + clearTimeout(this.deadline); + this.deadline = void 0; + } + this.resolveCancellation(); + this.controller?.abort(); + this.disposeInput(); + } +} +async function resolveDuration({ input, videoTrack, audioTrack }) { + const tracks = [videoTrack, audioTrack].filter((track) => track !== null); + const referenceTrack = videoTrack || audioTrack; + const isLive = Boolean(referenceTrack && await referenceTrack.isLive()); + let duration = Number.NaN; + if (tracks.length > 0) { + duration = await input.getDurationFromMetadata(tracks, { skipLiveWait: true }); + if (duration === null && !isLive) + duration = await input.computeDuration(tracks, { skipLiveWait: true }); + } + return isLive ? Number.POSITIVE_INFINITY : duration ?? Number.NaN; +} +async function selectPlaybackTracks(input, src) { + const videoTrack = await input.getPrimaryVideoTrack(); + const audioTrack = videoTrack ? await videoTrack.getPrimaryPairableAudioTrack() : await input.getPrimaryAudioTrack(); + const duration = await resolveDuration({ input, videoTrack, audioTrack }); + const referenceTrack = videoTrack || audioTrack; + const isHls = isHlsSource(src); + return { + input, + videoTrack, + audioTrack, + duration, + isLive: Number.isFinite(duration) ? false : Boolean(referenceTrack && await referenceTrack.isLive()), + isHls, + videoMode: isHls ? "auto" : "manual", + audioMode: isHls ? "auto" : "manual" + }; +} +async function preflightRange(url, enabled, events, signal, isCurrent = () => true) { + if (signal?.aborted || !isCurrent()) + return false; + if (!enabled || typeof url !== "string" || isHlsSource(url)) + return true; + try { + const res = await fetch(url, signal ? { method: "HEAD", signal } : { method: "HEAD" }); + if (signal?.aborted || !isCurrent()) + return false; + const acceptRanges = res.headers.get("accept-ranges"); + if (!acceptRanges || acceptRanges === "none") { + events.emit("error", new Event("RangeNotSupported")); + return false; + } + return true; + } catch (error) { + if (signal?.aborted || !isCurrent()) + return false; + console.warn("Preflight check failed:", error); + return true; + } +} class VideoEngine { constructor({ canvas, @@ -21531,7 +24449,7 @@ class VideoEngine { avSyncTolerance = 0.12, dropLateFrames = false, poster = "", - preflightRange = false + preflightRange: preflightRange2 = false }) { this.canvas = canvas; this.ctx = ctx; @@ -21540,7 +24458,7 @@ class VideoEngine { this.avSyncTolerance = avSyncTolerance; this.dropLateFrames = dropLateFrames; this.poster = poster; - this.preflightRange = preflightRange; + this.preflightRange = preflightRange2; this.input = null; this.videoSink = null; this.videoIterator = null; @@ -21557,21 +24475,8 @@ class VideoEngine { this.posterDrawn = false; this.isFetching = false; } - async preflight(url) { - if (!this.preflightRange || typeof url !== "string" || isHlsSource(url)) - return true; - try { - const res = await fetch(url, { method: "HEAD" }); - const acceptRanges = res.headers.get("accept-ranges"); - if (!acceptRanges || acceptRanges === "none") { - this.events.emit("error", new Event("RangeNotSupported")); - return false; - } - return true; - } catch (e) { - console.warn("Preflight check failed:", e); - return true; - } + async preflight(url, signal, isCurrent) { + return preflightRange(url, this.preflightRange, this.events, signal, isCurrent); } drawPoster() { if (!this.poster || this.posterDrawn) @@ -21763,39 +24668,50 @@ class MediaBunnyEngine { this.loadSeq = 0; this.input = null; this.media = null; + this.loadSession = null; + this.destroyed = false; 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; this.readyState = 0; - setTimeout(() => this.events.emit("waiting"), 0); - setTimeout(() => this.events.emit("loadstart"), 0); + 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 Promise.race([ - this.performLoad(src, id), - loadTimeout > 0 ? this.createTimeout(loadTimeout) : new Promise(() => { - }) - ]); + await session.wait(this.performLoad(src, id, session), loadTimeout); } catch (err) { if (id !== this.loadSeq) return; - this.loadSeq++; + 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; this.events.emit("error"); } } - async performLoad(src, id) { - if (!await this.video.preflight(src)) + 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) { @@ -21803,12 +24719,10 @@ class MediaBunnyEngine { this.audio.handleNoAudioTrack(); return; } + session.own(input); const media = await selectPlaybackTracks(input, src); - if (id !== this.loadSeq) { - input.dispose(); + if (id !== this.loadSeq) return; - } - this.disposeInput(); this.input = input; this.media = media; let videoMetadataLoaded = !media.videoTrack; @@ -21847,10 +24761,8 @@ class MediaBunnyEngine { } catch (err) { if (id !== this.loadSeq) return; - this.error = { code: 4, message: err.message }; - this.networkState = 3; - this.events.emit("error"); console.error("MediaBunny load error:", err); + throw err; } } createTimeout(ms) { @@ -21859,7 +24771,7 @@ class MediaBunnyEngine { }); } disposeInput() { - this.input?.dispose(); + this.loadSession?.disposeInput(); this.input = null; this.media = null; } @@ -21993,6 +24905,11 @@ class MediaBunnyEngine { this.video.setPlaybackRate(rate); } destroy() { + if (this.destroyed) + return; + this.destroyed = true; + this.loadSeq++; + this.loadSession?.cancel(); this.pause(); this.disposeInput(); this.audio.destroy(); diff --git a/packages/artplayer-proxy-mediabunny/src/MediaBunnyEngine.js b/packages/artplayer-proxy-mediabunny/src/MediaBunnyEngine.js index 62ae900b9..ba8af946d 100644 --- a/packages/artplayer-proxy-mediabunny/src/MediaBunnyEngine.js +++ b/packages/artplayer-proxy-mediabunny/src/MediaBunnyEngine.js @@ -3,7 +3,10 @@ * Coordinates audio and video playback */ import AudioEngine from './AudioEngine.js' -import { createInput, getHlsState, resolveDuration, selectPlaybackTracks } from './input.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 { @@ -34,6 +37,8 @@ export default class MediaBunnyEngine { this.loadSeq = 0 this.input = null this.media = null + this.loadSession = null + this.destroyed = false // Listen to ended event events.addEventListener?.('ended', () => { @@ -43,41 +48,50 @@ export default class MediaBunnyEngine { } 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 - setTimeout(() => this.events.emit('waiting'), 0) - setTimeout(() => this.events.emit('loadstart'), 0) + 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 Promise.race([ - this.performLoad(src, id), - loadTimeout > 0 ? this.createTimeout(loadTimeout) : new Promise(() => {}), - ]) + await session.wait(this.performLoad(src, id, session), loadTimeout) } catch (err) { if (id !== this.loadSeq) return - this.loadSeq++ + 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) { - if (!(await this.video.preflight(src))) + 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) @@ -86,14 +100,10 @@ export default class MediaBunnyEngine { this.audio.handleNoAudioTrack() return } - + session.own(input) const media = await selectPlaybackTracks(input, src) - if (id !== this.loadSeq) { - input.dispose() + if (id !== this.loadSeq) return - } - - this.disposeInput() this.input = input this.media = media @@ -139,10 +149,8 @@ export default class MediaBunnyEngine { if (id !== this.loadSeq) return - this.error = { code: 4, message: err.message } - this.networkState = 3 - this.events.emit('error') console.error('MediaBunny load error:', err) + throw err } } @@ -153,7 +161,7 @@ export default class MediaBunnyEngine { } disposeInput() { - this.input?.dispose() + this.loadSession?.disposeInput() this.input = null this.media = null } @@ -334,6 +342,11 @@ export default class MediaBunnyEngine { } destroy() { + if (this.destroyed) + return + this.destroyed = true + this.loadSeq++ + this.loadSession?.cancel() this.pause() this.disposeInput() this.audio.destroy() diff --git a/packages/artplayer-proxy-mediabunny/src/VideoEngine.js b/packages/artplayer-proxy-mediabunny/src/VideoEngine.js index ea1c959db..8a4ad7846 100644 --- a/packages/artplayer-proxy-mediabunny/src/VideoEngine.js +++ b/packages/artplayer-proxy-mediabunny/src/VideoEngine.js @@ -5,7 +5,7 @@ import { CanvasSink, } from 'mediabunny' -import { isHlsSource } from './input.js' +import { preflightRange } from './preflight' export default class VideoEngine { constructor({ @@ -51,23 +51,8 @@ export default class VideoEngine { this.isFetching = false } - async preflight(url) { - if (!this.preflightRange || typeof url !== 'string' || isHlsSource(url)) - return true - - try { - const res = await fetch(url, { method: 'HEAD' }) - const acceptRanges = res.headers.get('accept-ranges') - if (!acceptRanges || acceptRanges === 'none') { - this.events.emit('error', new Event('RangeNotSupported')) - return false - } - return true - } - catch (e) { - console.warn('Preflight check failed:', e) - return true - } + async preflight(url, signal, isCurrent) { + return preflightRange(url, this.preflightRange, this.events, signal, isCurrent) } drawPoster() { diff --git a/packages/artplayer-proxy-mediabunny/src/hls-state.ts b/packages/artplayer-proxy-mediabunny/src/hls-state.ts new file mode 100644 index 000000000..63be0d053 --- /dev/null +++ b/packages/artplayer-proxy-mediabunny/src/hls-state.ts @@ -0,0 +1,47 @@ +import type { InputTrack } from 'mediabunny' +import type { PlaybackMedia } from './media' + +async function getTrackBitrate(track: InputTrack): Promise { + return await track.getAverageBitrate() ?? await track.getBitrate() ?? 0 +} + +export async function getHlsState(media: PlaybackMedia | null) { + if (!media?.isHls || !media.input) + return null + + const [videoTracks, pairableAudioTracks] = await Promise.all([ + media.input.getVideoTracks(), + media.videoTrack ? media.videoTrack.getPairableAudioTracks() : [], + ]) + const [levels, audios] = await Promise.all([ + Promise.all(videoTracks.map(async (track, index) => ({ + id: track.id, + track, + index, + name: await track.getName(), + height: await track.getDisplayHeight(), + bitrate: await getTrackBitrate(track), + }))), + Promise.all(pairableAudioTracks.map(async (track, index) => { + const name = await track.getName() + const language = await track.getLanguageCode() + return { + id: track.id, + track, + index, + name, + lang: language, + language, + bitrate: await getTrackBitrate(track), + } + })), + ]) + return { + levels, + audios, + currentLevel: media.videoTrack ? levels.find(item => item.id === media.videoTrack?.id) ?? null : null, + currentAudio: media.audioTrack ? audios.find(item => item.id === media.audioTrack?.id) ?? null : null, + videoMode: media.videoMode ?? 'auto', + audioMode: media.audioMode ?? 'auto', + } +} diff --git a/packages/artplayer-proxy-mediabunny/src/input.js b/packages/artplayer-proxy-mediabunny/src/input.js deleted file mode 100644 index a69609404..000000000 --- a/packages/artplayer-proxy-mediabunny/src/input.js +++ /dev/null @@ -1,120 +0,0 @@ -import { - ALL_FORMATS, - BlobSource, - HLS_FORMATS, - Input, - ReadableStreamSource, - UrlSource, -} from 'mediabunny' - -const M3U8_RE = /\.m3u8(?:$|[?#])/i - -export function isHlsSource(src) { - return typeof src === 'string' && M3U8_RE.test(src) -} - -export function normalizeSource(src) { - if (typeof src === 'string') - return new UrlSource(src) - if (src instanceof Blob) - return new BlobSource(src) - if (typeof ReadableStream !== 'undefined' && src instanceof ReadableStream) { - return new ReadableStreamSource(src) - } - return src ?? null -} - -export function createInput(src) { - const source = normalizeSource(src) - if (!source) - return null - - return new Input({ - source, - formats: isHlsSource(src) ? HLS_FORMATS : ALL_FORMATS, - }) -} - -export async function resolveDuration({ input, videoTrack, audioTrack }) { - const tracks = [videoTrack, audioTrack].filter(Boolean) - const referenceTrack = videoTrack || audioTrack - const isLive = Boolean(referenceTrack && await referenceTrack.isLive()) - - let duration = Number.NaN - if (tracks.length > 0) { - duration = await input.getDurationFromMetadata(tracks, { skipLiveWait: true }) - if (duration === null && !isLive) { - duration = await input.computeDuration(tracks, { skipLiveWait: true }) - } - } - - return isLive ? Number.POSITIVE_INFINITY : duration ?? Number.NaN -} - -export async function selectPlaybackTracks(input, src) { - const videoTrack = await input.getPrimaryVideoTrack() - const audioTrack = videoTrack - ? await videoTrack.getPrimaryPairableAudioTrack() - : await input.getPrimaryAudioTrack() - const duration = await resolveDuration({ input, videoTrack, audioTrack }) - - return { - input, - videoTrack, - audioTrack, - duration, - isLive: Number.isFinite(duration) ? false : Boolean((videoTrack || audioTrack) && await (videoTrack || audioTrack).isLive()), - isHls: isHlsSource(src), - videoMode: isHlsSource(src) ? 'auto' : 'manual', - audioMode: isHlsSource(src) ? 'auto' : 'manual', - } -} - -async function getTrackBitrate(track) { - return await track.getAverageBitrate() ?? await track.getBitrate() ?? 0 -} - -export async function getHlsState(media) { - if (!media?.isHls || !media.input) - return null - - const [videoTracks, pairableAudioTracks] = await Promise.all([ - media.input.getVideoTracks(), - media.videoTrack - ? media.videoTrack.getPairableAudioTracks() - : [], - ]) - - const [levels, audios] = await Promise.all([ - Promise.all(videoTracks.map(async (track, index) => ({ - id: track.id, - track, - index, - name: await track.getName(), - height: await track.getDisplayHeight(), - bitrate: await getTrackBitrate(track), - }))), - Promise.all(pairableAudioTracks.map(async (track, index) => { - const name = await track.getName() - const language = await track.getLanguageCode() - return { - id: track.id, - track, - index, - name, - lang: language, - language, - bitrate: await getTrackBitrate(track), - } - })), - ]) - - return { - levels, - audios, - currentLevel: media.videoTrack ? levels.find(item => item.id === media.videoTrack.id) ?? null : null, - currentAudio: media.audioTrack ? audios.find(item => item.id === media.audioTrack.id) ?? null : null, - videoMode: media.videoMode ?? 'auto', - audioMode: media.audioMode ?? 'auto', - } -} diff --git a/packages/artplayer-proxy-mediabunny/src/input.ts b/packages/artplayer-proxy-mediabunny/src/input.ts new file mode 100644 index 000000000..7de0208fc --- /dev/null +++ b/packages/artplayer-proxy-mediabunny/src/input.ts @@ -0,0 +1,37 @@ +import type { InputOptions } from 'mediabunny' +import { + ALL_FORMATS, + BlobSource, + HLS_FORMATS, + Input, + ReadableStreamSource, + UrlSource, +} from 'mediabunny' + +const M3U8_RE = /\.m3u8(?:$|[?#])/i + +export function isHlsSource(src: unknown): boolean { + return typeof src === 'string' && M3U8_RE.test(src) +} + +export function normalizeSource(src: unknown): unknown { + if (typeof src === 'string') + return new UrlSource(src) + if (src instanceof Blob) + return new BlobSource(src) + if (typeof ReadableStream !== 'undefined' && src instanceof ReadableStream) + return new ReadableStreamSource(src) + return src ?? null +} + +export function createInput(src: unknown): Input | null { + const source = normalizeSource(src) + if (!source) + return null + + return new Input({ + // Preserve SDK Source/SourceRef pass-through and its historical validation errors. + source: source as InputOptions['source'], + formats: isHlsSource(src) ? HLS_FORMATS : ALL_FORMATS, + }) +} diff --git a/packages/artplayer-proxy-mediabunny/src/load-session.ts b/packages/artplayer-proxy-mediabunny/src/load-session.ts new file mode 100644 index 000000000..90df696ca --- /dev/null +++ b/packages/artplayer-proxy-mediabunny/src/load-session.ts @@ -0,0 +1,77 @@ +import type { Input } from 'mediabunny' + +export default class LoadSession { + private active = true + private input: Input | null = null + private timers = new Set>() + private deadline: ReturnType | undefined + private controller = typeof AbortController === 'undefined' ? undefined : new AbortController() + private resolveCancellation!: () => void + private cancellation = new Promise((resolve) => { + this.resolveCancellation = resolve + }) + + get signal(): AbortSignal | undefined { + return this.controller?.signal + } + + own(input: Input): void { + if (this.active) + this.input = input + else input.dispose() + } + + defer(callback: () => void): void { + if (!this.active) + return + const timer = setTimeout(() => { + this.timers.delete(timer) + if (this.active) + callback() + }, 0) + this.timers.add(timer) + } + + async wait(operation: Promise, milliseconds: number): Promise { + try { + await Promise.race([ + operation, + this.cancellation, + milliseconds > 0 ? this.timeout(milliseconds) : new Promise(() => {}), + ]) + } + finally { + if (this.deadline !== undefined) { + clearTimeout(this.deadline) + this.deadline = undefined + } + } + } + + timeout(milliseconds: number): Promise { + return new Promise((_, reject) => { + this.deadline = setTimeout(() => reject(new Error('Load timeout')), milliseconds) + }) + } + + disposeInput(): void { + const input = this.input + this.input = null + input?.dispose() + } + + cancel(): void { + if (!this.active) + return + this.active = false + for (const timer of this.timers) clearTimeout(timer) + this.timers.clear() + if (this.deadline !== undefined) { + clearTimeout(this.deadline) + this.deadline = undefined + } + this.resolveCancellation() + this.controller?.abort() + this.disposeInput() + } +} diff --git a/packages/artplayer-proxy-mediabunny/src/media.ts b/packages/artplayer-proxy-mediabunny/src/media.ts new file mode 100644 index 000000000..549c4baed --- /dev/null +++ b/packages/artplayer-proxy-mediabunny/src/media.ts @@ -0,0 +1,14 @@ +import type { Input, InputAudioTrack, InputVideoTrack } from 'mediabunny' + +export type TrackMode = 'auto' | 'manual' + +export interface PlaybackMedia { + input: Input + videoTrack: InputVideoTrack | null + audioTrack: InputAudioTrack | null + duration: number + isLive: boolean + isHls: boolean + videoMode: TrackMode + audioMode: TrackMode +} diff --git a/packages/artplayer-proxy-mediabunny/src/preflight.ts b/packages/artplayer-proxy-mediabunny/src/preflight.ts new file mode 100644 index 000000000..3b8bdcb74 --- /dev/null +++ b/packages/artplayer-proxy-mediabunny/src/preflight.ts @@ -0,0 +1,30 @@ +import { isHlsSource } from './input' + +interface RangeEvents { + emit: (type: string, detail?: Event) => void +} + +export async function preflightRange(url: unknown, enabled: boolean, events: RangeEvents, signal?: AbortSignal, isCurrent = (): boolean => true): Promise { + if (signal?.aborted || !isCurrent()) + return false + if (!enabled || typeof url !== 'string' || isHlsSource(url)) + return true + + try { + const res = await fetch(url, signal ? { method: 'HEAD', signal } : { method: 'HEAD' }) + if (signal?.aborted || !isCurrent()) + return false + const acceptRanges = res.headers.get('accept-ranges') + if (!acceptRanges || acceptRanges === 'none') { + events.emit('error', new Event('RangeNotSupported')) + return false + } + return true + } + catch (error) { + if (signal?.aborted || !isCurrent()) + return false + console.warn('Preflight check failed:', error) + return true + } +} diff --git a/packages/artplayer-proxy-mediabunny/src/tracks.ts b/packages/artplayer-proxy-mediabunny/src/tracks.ts new file mode 100644 index 000000000..a1f15189f --- /dev/null +++ b/packages/artplayer-proxy-mediabunny/src/tracks.ts @@ -0,0 +1,38 @@ +import type { Input, InputAudioTrack, InputVideoTrack } from 'mediabunny' +import type { PlaybackMedia } from './media' +import { isHlsSource } from './input' + +export async function resolveDuration({ input, videoTrack, audioTrack }: Pick): Promise { + const tracks = [videoTrack, audioTrack].filter((track): track is InputVideoTrack | InputAudioTrack => track !== null) + const referenceTrack = videoTrack || audioTrack + const isLive = Boolean(referenceTrack && await referenceTrack.isLive()) + + let duration: number | null = Number.NaN + if (tracks.length > 0) { + duration = await input.getDurationFromMetadata(tracks, { skipLiveWait: true }) + if (duration === null && !isLive) + duration = await input.computeDuration(tracks, { skipLiveWait: true }) + } + return isLive ? Number.POSITIVE_INFINITY : duration ?? Number.NaN +} + +export async function selectPlaybackTracks(input: Input, src: unknown): Promise { + const videoTrack = await input.getPrimaryVideoTrack() + const audioTrack = videoTrack + ? await videoTrack.getPrimaryPairableAudioTrack() + : await input.getPrimaryAudioTrack() + const duration = await resolveDuration({ input, videoTrack, audioTrack }) + const referenceTrack = videoTrack || audioTrack + const isHls = isHlsSource(src) + + return { + input, + videoTrack, + audioTrack, + duration, + isLive: Number.isFinite(duration) ? false : Boolean(referenceTrack && await referenceTrack.isLive()), + isHls, + videoMode: isHls ? 'auto' : 'manual', + audioMode: isHls ? 'auto' : 'manual', + } +} diff --git a/packages/artplayer-proxy-mediabunny/tsconfig.json b/packages/artplayer-proxy-mediabunny/tsconfig.json new file mode 100644 index 000000000..7a81990c8 --- /dev/null +++ b/packages/artplayer-proxy-mediabunny/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "allowJs": false, + "lib": ["ES2020", "DOM", "DOM.Iterable", "ESNext.Disposable"] + }, + "include": ["src/**/*.ts", "types/**/*.d.ts"] +} diff --git a/refactor/baselines/mb-input-validation.json b/refactor/baselines/mb-input-validation.json new file mode 100644 index 000000000..4f9979bf3 --- /dev/null +++ b/refactor/baselines/mb-input-validation.json @@ -0,0 +1,1277 @@ +{ + "task": "PKG-MB-03", + "status": "done", + "parentCommit": "03451c029b8c10ca3e56fe54475b9031abe7e91c", + "sourceSha256LF": { + "packages/artplayer-proxy-mediabunny/src/AudioEngine.js": "910d6831372e4895d55dec78010f281a199bc88f99735630a5a3b621f192ac35", + "packages/artplayer-proxy-mediabunny/src/EventTarget.js": "c1854510af5a37301b4bd3b1fbcc28f7e0f105f50cb67324c5c05a76f2d054fb", + "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.js": "5ce3bc85572121ec9068fbc051ac4845d3a3991e670e10dafcaede1c1609f1fb", + "packages/artplayer-proxy-mediabunny/src/preflight.ts": "d296234312f23b97a1e0a054f1d7dbbc988d5240c5fd5089c36df1677c7b7348", + "packages/artplayer-proxy-mediabunny/src/tracks.ts": "6da68530c1fc7105ab17ed742d87d93e84447e822e84386591f9c3e6d0bec733", + "packages/artplayer-proxy-mediabunny/src/VideoEngine.js": "5ac862b0fd9c196dc6656f8908a214c1b3a0a53a7e85ff845d9068888831986b", + "packages/artplayer-proxy-mediabunny/src/VideoShim.js": "f01c954e8a98fb70138dded78b99eb2765f5cd1e8a98dafbb35ffbf8f7741dbb", + "packages/artplayer-proxy-mediabunny/dist/artplayer-proxy-mediabunny.js": "f9d5571f75f47ee1714d04c951836c1a6c903f4e465fab2a267dcb4948c0de7b", + "packages/artplayer-proxy-mediabunny/dist/artplayer-proxy-mediabunny.legacy.js": "3fa2deff62a9269e1a2fd833590b2b23c9899b59af5474009162504c9c76a070", + "packages/artplayer-proxy-mediabunny/dist/artplayer-proxy-mediabunny.mjs": "08c72004a797b1601e949a7f8902d06d8b57cac92ea757cc6c370817c62fbcb5", + "packages/artplayer-proxy-mediabunny/tsconfig.json": "f287a0e014faa10c0da2aabd0341b4d74359be4135f4d07480b4f7a3108c8128", + "packages/artplayer-proxy-mediabunny/ARCHITECTURE.md": "5b8d97bcd08dba5666bed1fe6eb54d871c954aa52a3a7659446a8337566db710", + "packages/artplayer-proxy-mediabunny/types/artplayer-proxy-mediabunny.d.ts": "af2083224d0760752d83eb2ac86b1dea5586455b81d47e4ba70f9f6a874a75d8", + "package.json": "495a03ea54bc05746f94ed2138118036b263a41459acd3e7beb8dc522ba47a4e", + "yarn.lock": "6dfb6c5b0154bcd3adc279e12c4393db66a6ec52274002adf2d5ab93caa05d4b", + "test/mediabunny-load.test.js": "fee16a64293a7ec1d820e0047f9447df86380c4f1e07923f5657d49fcedc5e3f", + "test/mediabunny-input.test.js": "2d2b6a22ce009c2bf89534d07359563e4d761c60c457e9668488922c108102e0", + "test/helpers/mediabunny.js": "1bc506fee52a199e0b50363e68af0639484b1f8c1164fe7998089f6ef0b09a7e", + "test/browser/mediabunny-inputs.spec.js": "3f42d8fa7ea7a170495ca25af34ce99a789016d280ebcebdb3883fc91f426a73", + "test/browser/mediabunny.spec.js": "d250f75509b0eb9b8a5e048cf34669415cf163e22dbaf52da0760bece4f71cf5", + "test/browser/mediabunny-load.spec.js": "4822b8561a193c307b5b9724be6b80f6a62813909fa6c3fefece25f8c0a144cd", + "refactor/third-party.json": "54ecc99c3edb59e872b3118ecbffe09f05ae7634d0a39cc63f85dd07c3de6540", + "packages/artplayer-proxy-mediabunny/README.md": "90e15d4f66488de3bc386f8aa000d6e0c31ee78afdcce593ef830525ef5cd029" + }, + "modules": { + "strictTypeScript": 6, + "remainingJavaScript": 7 + }, + "node": { + "historical": 24, + "candidateInput": 12, + "candidateLoad": 20, + "total": 56, + "sameLoadAssertionsOnFrozenMain": { + "passed": 6, + "failed": 14 + }, + "main": 20, + "legacy": 20 + }, + "browser": { + "total": 72, + "candidate": 30, + "historical": 42, + "groups": { + "historical": { + "native-input-playback-and-seek": 16, + "historical-trackless-readiness-control": 4, + "historical-stream-lock-control": 3, + "historical-unsupported-hls-control": 3, + "unsupported-capability-control": 10, + "native-mp4-playback-observed": 4, + "verified-unsupported-capability-control": 2 + }, + "candidate": { + "native-input-playback-and-seek": 10, + "candidate-trackless-readiness-gap": 2, + "unsupported-capability-control": 6, + "native-pending-stream-cancellation": 9, + "native-mp4-playback-observed": 2, + "verified-unsupported-capability-control": 1 + } + }, + "records": [ + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "published-1.2.0", + "sha256": "7d088c0abe2f3c1e2857cb0547405ce1e5588630f28e484a64211fc675322bbd", + "input": "webm", + "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 readiness remains MB-READY-01, not release acceptance." + }, + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "published-1.2.0", + "sha256": "7d088c0abe2f3c1e2857cb0547405ce1e5588630f28e484a64211fc675322bbd", + "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 readiness remains MB-READY-01, not release acceptance." + }, + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "published-1.2.0", + "sha256": "7d088c0abe2f3c1e2857cb0547405ce1e5588630f28e484a64211fc675322bbd", + "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 readiness remains MB-READY-01, not release acceptance." + }, + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "published-1.2.0", + "sha256": "7d088c0abe2f3c1e2857cb0547405ce1e5588630f28e484a64211fc675322bbd", + "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 readiness remains MB-READY-01, not release acceptance." + }, + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "published-1.2.0", + "sha256": "7d088c0abe2f3c1e2857cb0547405ce1e5588630f28e484a64211fc675322bbd", + "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 readiness remains MB-READY-01, not release acceptance." + }, + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "published-1.2.0", + "sha256": "7d088c0abe2f3c1e2857cb0547405ce1e5588630f28e484a64211fc675322bbd", + "input": "trackless", + "outcome": "historical-trackless-readiness-control", + "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 readiness remains MB-READY-01, not release acceptance." + }, + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "published-1.0.0", + "sha256": "7331465d8c7a6575505b9d3fd45986c5d3d9cb3839b2620ad5a52c581199562b", + "input": "webm", + "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 readiness remains MB-READY-01, not release acceptance." + }, + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "published-1.0.0", + "sha256": "7331465d8c7a6575505b9d3fd45986c5d3d9cb3839b2620ad5a52c581199562b", + "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 readiness remains MB-READY-01, not release acceptance." + }, + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "published-1.0.0", + "sha256": "7331465d8c7a6575505b9d3fd45986c5d3d9cb3839b2620ad5a52c581199562b", + "input": "stream", + "outcome": "historical-stream-lock-control", + "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 readiness remains MB-READY-01, not release acceptance." + }, + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "published-1.0.0", + "sha256": "7331465d8c7a6575505b9d3fd45986c5d3d9cb3839b2620ad5a52c581199562b", + "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 readiness remains MB-READY-01, not release acceptance." + }, + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "published-1.0.0", + "sha256": "7331465d8c7a6575505b9d3fd45986c5d3d9cb3839b2620ad5a52c581199562b", + "input": "hls", + "outcome": "historical-unsupported-hls-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 readiness remains MB-READY-01, not release acceptance." + }, + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "published-1.0.0", + "sha256": "7331465d8c7a6575505b9d3fd45986c5d3d9cb3839b2620ad5a52c581199562b", + "input": "trackless", + "outcome": "historical-trackless-readiness-control", + "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 readiness remains MB-READY-01, not release acceptance." + }, + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "f9d5571f75f47ee1714d04c951836c1a6c903f4e465fab2a267dcb4948c0de7b", + "input": "webm", + "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 readiness remains MB-READY-01, not release acceptance." + }, + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "f9d5571f75f47ee1714d04c951836c1a6c903f4e465fab2a267dcb4948c0de7b", + "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 readiness remains MB-READY-01, not release acceptance." + }, + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "f9d5571f75f47ee1714d04c951836c1a6c903f4e465fab2a267dcb4948c0de7b", + "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 readiness remains MB-READY-01, not release acceptance." + }, + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "f9d5571f75f47ee1714d04c951836c1a6c903f4e465fab2a267dcb4948c0de7b", + "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 readiness remains MB-READY-01, not release acceptance." + }, + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "f9d5571f75f47ee1714d04c951836c1a6c903f4e465fab2a267dcb4948c0de7b", + "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 readiness remains MB-READY-01, not release acceptance." + }, + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "f9d5571f75f47ee1714d04c951836c1a6c903f4e465fab2a267dcb4948c0de7b", + "input": "trackless", + "outcome": "candidate-trackless-readiness-gap", + "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 readiness remains MB-READY-01, not release acceptance." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "published-1.2.0", + "sha256": "7d088c0abe2f3c1e2857cb0547405ce1e5588630f28e484a64211fc675322bbd", + "input": "webm", + "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 readiness remains MB-READY-01, not release acceptance." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "published-1.2.0", + "sha256": "7d088c0abe2f3c1e2857cb0547405ce1e5588630f28e484a64211fc675322bbd", + "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 readiness remains MB-READY-01, not release acceptance." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "published-1.2.0", + "sha256": "7d088c0abe2f3c1e2857cb0547405ce1e5588630f28e484a64211fc675322bbd", + "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 readiness remains MB-READY-01, not release acceptance." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "published-1.2.0", + "sha256": "7d088c0abe2f3c1e2857cb0547405ce1e5588630f28e484a64211fc675322bbd", + "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 readiness remains MB-READY-01, not release acceptance." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "published-1.2.0", + "sha256": "7d088c0abe2f3c1e2857cb0547405ce1e5588630f28e484a64211fc675322bbd", + "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 readiness remains MB-READY-01, not release acceptance." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "published-1.2.0", + "sha256": "7d088c0abe2f3c1e2857cb0547405ce1e5588630f28e484a64211fc675322bbd", + "input": "trackless", + "outcome": "historical-trackless-readiness-control", + "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 readiness remains MB-READY-01, not release acceptance." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "published-1.0.0", + "sha256": "7331465d8c7a6575505b9d3fd45986c5d3d9cb3839b2620ad5a52c581199562b", + "input": "webm", + "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 readiness remains MB-READY-01, not release acceptance." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "published-1.0.0", + "sha256": "7331465d8c7a6575505b9d3fd45986c5d3d9cb3839b2620ad5a52c581199562b", + "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 readiness remains MB-READY-01, not release acceptance." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "published-1.0.0", + "sha256": "7331465d8c7a6575505b9d3fd45986c5d3d9cb3839b2620ad5a52c581199562b", + "input": "stream", + "outcome": "historical-stream-lock-control", + "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 readiness remains MB-READY-01, not release acceptance." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "published-1.0.0", + "sha256": "7331465d8c7a6575505b9d3fd45986c5d3d9cb3839b2620ad5a52c581199562b", + "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 readiness remains MB-READY-01, not release acceptance." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "published-1.0.0", + "sha256": "7331465d8c7a6575505b9d3fd45986c5d3d9cb3839b2620ad5a52c581199562b", + "input": "hls", + "outcome": "historical-unsupported-hls-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 readiness remains MB-READY-01, not release acceptance." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "published-1.0.0", + "sha256": "7331465d8c7a6575505b9d3fd45986c5d3d9cb3839b2620ad5a52c581199562b", + "input": "trackless", + "outcome": "historical-trackless-readiness-control", + "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 readiness remains MB-READY-01, not release acceptance." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "f9d5571f75f47ee1714d04c951836c1a6c903f4e465fab2a267dcb4948c0de7b", + "input": "webm", + "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 readiness remains MB-READY-01, not release acceptance." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "f9d5571f75f47ee1714d04c951836c1a6c903f4e465fab2a267dcb4948c0de7b", + "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 readiness remains MB-READY-01, not release acceptance." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "f9d5571f75f47ee1714d04c951836c1a6c903f4e465fab2a267dcb4948c0de7b", + "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 readiness remains MB-READY-01, not release acceptance." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "f9d5571f75f47ee1714d04c951836c1a6c903f4e465fab2a267dcb4948c0de7b", + "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 readiness remains MB-READY-01, not release acceptance." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "f9d5571f75f47ee1714d04c951836c1a6c903f4e465fab2a267dcb4948c0de7b", + "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 readiness remains MB-READY-01, not release acceptance." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "f9d5571f75f47ee1714d04c951836c1a6c903f4e465fab2a267dcb4948c0de7b", + "input": "trackless", + "outcome": "candidate-trackless-readiness-gap", + "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 readiness remains MB-READY-01, not release acceptance." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "published-1.2.0", + "sha256": "7d088c0abe2f3c1e2857cb0547405ce1e5588630f28e484a64211fc675322bbd", + "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 readiness remains MB-READY-01, not release acceptance." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "published-1.2.0", + "sha256": "7d088c0abe2f3c1e2857cb0547405ce1e5588630f28e484a64211fc675322bbd", + "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 readiness remains MB-READY-01, not release acceptance." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "published-1.2.0", + "sha256": "7d088c0abe2f3c1e2857cb0547405ce1e5588630f28e484a64211fc675322bbd", + "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 readiness remains MB-READY-01, not release acceptance." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "published-1.2.0", + "sha256": "7d088c0abe2f3c1e2857cb0547405ce1e5588630f28e484a64211fc675322bbd", + "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 readiness remains MB-READY-01, not release acceptance." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "published-1.2.0", + "sha256": "7d088c0abe2f3c1e2857cb0547405ce1e5588630f28e484a64211fc675322bbd", + "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 readiness remains MB-READY-01, not release acceptance." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "published-1.2.0", + "sha256": "7d088c0abe2f3c1e2857cb0547405ce1e5588630f28e484a64211fc675322bbd", + "input": "trackless", + "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 readiness remains MB-READY-01, not release acceptance." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "published-1.0.0", + "sha256": "7331465d8c7a6575505b9d3fd45986c5d3d9cb3839b2620ad5a52c581199562b", + "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 readiness remains MB-READY-01, not release acceptance." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "published-1.0.0", + "sha256": "7331465d8c7a6575505b9d3fd45986c5d3d9cb3839b2620ad5a52c581199562b", + "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 readiness remains MB-READY-01, not release acceptance." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "published-1.0.0", + "sha256": "7331465d8c7a6575505b9d3fd45986c5d3d9cb3839b2620ad5a52c581199562b", + "input": "stream", + "outcome": "historical-stream-lock-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 readiness remains MB-READY-01, not release acceptance." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "published-1.0.0", + "sha256": "7331465d8c7a6575505b9d3fd45986c5d3d9cb3839b2620ad5a52c581199562b", + "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 readiness remains MB-READY-01, not release acceptance." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "published-1.0.0", + "sha256": "7331465d8c7a6575505b9d3fd45986c5d3d9cb3839b2620ad5a52c581199562b", + "input": "hls", + "outcome": "historical-unsupported-hls-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 readiness remains MB-READY-01, not release acceptance." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "published-1.0.0", + "sha256": "7331465d8c7a6575505b9d3fd45986c5d3d9cb3839b2620ad5a52c581199562b", + "input": "trackless", + "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 readiness remains MB-READY-01, not release acceptance." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "f9d5571f75f47ee1714d04c951836c1a6c903f4e465fab2a267dcb4948c0de7b", + "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 readiness remains MB-READY-01, not release acceptance." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "f9d5571f75f47ee1714d04c951836c1a6c903f4e465fab2a267dcb4948c0de7b", + "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 readiness remains MB-READY-01, not release acceptance." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "f9d5571f75f47ee1714d04c951836c1a6c903f4e465fab2a267dcb4948c0de7b", + "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 readiness remains MB-READY-01, not release acceptance." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "f9d5571f75f47ee1714d04c951836c1a6c903f4e465fab2a267dcb4948c0de7b", + "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 readiness remains MB-READY-01, not release acceptance." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "f9d5571f75f47ee1714d04c951836c1a6c903f4e465fab2a267dcb4948c0de7b", + "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 readiness remains MB-READY-01, not release acceptance." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "f9d5571f75f47ee1714d04c951836c1a6c903f4e465fab2a267dcb4948c0de7b", + "input": "trackless", + "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 readiness remains MB-READY-01, not release acceptance." + }, + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "f9d5571f75f47ee1714d04c951836c1a6c903f4e465fab2a267dcb4948c0de7b", + "ending": "destroy", + "outcome": "native-pending-stream-cancellation", + "cancellations": [ + "old" + ], + "state": { + "error": null, + "readyState": 0, + "events": [ + "video:waiting", + "video:loadstart", + "destroy" + ], + "input": true + }, + "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": "f9d5571f75f47ee1714d04c951836c1a6c903f4e465fab2a267dcb4948c0de7b", + "ending": "source", + "outcome": "native-pending-stream-cancellation", + "cancellations": [ + "old", + "new" + ], + "state": { + "error": null, + "readyState": 0, + "events": [ + "video:waiting", + "video:loadstart", + "video:waiting", + "video:loadstart" + ], + "input": true + }, + "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": "f9d5571f75f47ee1714d04c951836c1a6c903f4e465fab2a267dcb4948c0de7b", + "ending": "timeout", + "outcome": "native-pending-stream-cancellation", + "cancellations": [ + "old" + ], + "state": { + "error": { + "code": 4, + "message": "Load timeout" + }, + "readyState": 0, + "events": [ + "video:waiting", + "video:loadstart", + "video:error" + ], + "input": true + }, + "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": "f9d5571f75f47ee1714d04c951836c1a6c903f4e465fab2a267dcb4948c0de7b", + "ending": "destroy", + "outcome": "native-pending-stream-cancellation", + "cancellations": [ + "old" + ], + "state": { + "error": null, + "readyState": 0, + "events": [ + "video:waiting", + "video:loadstart", + "destroy" + ], + "input": true + }, + "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": "f9d5571f75f47ee1714d04c951836c1a6c903f4e465fab2a267dcb4948c0de7b", + "ending": "source", + "outcome": "native-pending-stream-cancellation", + "cancellations": [ + "old", + "new" + ], + "state": { + "error": null, + "readyState": 0, + "events": [ + "video:waiting", + "video:loadstart", + "video:waiting", + "video:loadstart" + ], + "input": true + }, + "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": "f9d5571f75f47ee1714d04c951836c1a6c903f4e465fab2a267dcb4948c0de7b", + "ending": "timeout", + "outcome": "native-pending-stream-cancellation", + "cancellations": [ + "old" + ], + "state": { + "error": { + "code": 4, + "message": "Load timeout" + }, + "readyState": 0, + "events": [ + "video:waiting", + "video:loadstart", + "video:error" + ], + "input": true + }, + "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": "f9d5571f75f47ee1714d04c951836c1a6c903f4e465fab2a267dcb4948c0de7b", + "ending": "destroy", + "outcome": "native-pending-stream-cancellation", + "cancellations": [ + "old" + ], + "state": { + "error": null, + "readyState": 0, + "events": [ + "video:waiting", + "video:loadstart", + "destroy" + ], + "input": true + }, + "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": "f9d5571f75f47ee1714d04c951836c1a6c903f4e465fab2a267dcb4948c0de7b", + "ending": "source", + "outcome": "native-pending-stream-cancellation", + "cancellations": [ + "old", + "new" + ], + "state": { + "error": null, + "readyState": 0, + "events": [ + "video:waiting", + "video:loadstart", + "video:waiting", + "video:loadstart" + ], + "input": true + }, + "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": "f9d5571f75f47ee1714d04c951836c1a6c903f4e465fab2a267dcb4948c0de7b", + "ending": "timeout", + "outcome": "native-pending-stream-cancellation", + "cancellations": [ + "old" + ], + "state": { + "error": { + "code": 4, + "message": "Load timeout" + }, + "readyState": 0, + "events": [ + "video:waiting", + "video:loadstart", + "video:error" + ], + "input": true + }, + "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": "published-1.2.0", + "sha256": "7d088c0abe2f3c1e2857cb0547405ce1e5588630f28e484a64211fc675322bbd", + "outcome": "native-mp4-playback-observed", + "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." + }, + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "published-1.0.0", + "sha256": "7331465d8c7a6575505b9d3fd45986c5d3d9cb3839b2620ad5a52c581199562b", + "outcome": "native-mp4-playback-observed", + "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." + }, + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "f9d5571f75f47ee1714d04c951836c1a6c903f4e465fab2a267dcb4948c0de7b", + "outcome": "native-mp4-playback-observed", + "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." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "published-1.2.0", + "sha256": "7d088c0abe2f3c1e2857cb0547405ce1e5588630f28e484a64211fc675322bbd", + "outcome": "native-mp4-playback-observed", + "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." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "published-1.0.0", + "sha256": "7331465d8c7a6575505b9d3fd45986c5d3d9cb3839b2620ad5a52c581199562b", + "outcome": "native-mp4-playback-observed", + "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." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "f9d5571f75f47ee1714d04c951836c1a6c903f4e465fab2a267dcb4948c0de7b", + "outcome": "native-mp4-playback-observed", + "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." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "published-1.2.0", + "sha256": "7d088c0abe2f3c1e2857cb0547405ce1e5588630f28e484a64211fc675322bbd", + "outcome": "verified-unsupported-capability-control", + "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." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "published-1.0.0", + "sha256": "7331465d8c7a6575505b9d3fd45986c5d3d9cb3839b2620ad5a52c581199562b", + "outcome": "verified-unsupported-capability-control", + "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." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "f9d5571f75f47ee1714d04c951836c1a6c903f4e465fab2a267dcb4948c0de7b", + "outcome": "verified-unsupported-capability-control", + "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." + } + ], + "report": "refactor/.cache/mb03-built-results/report.json", + "reportSha256": "f069c4f171e738e922b8b0b5a3f2376525f8782b71781bfac9cbbd89fed3ffc4", + "results": "refactor/.cache/mb03-built-results/results" + }, + "dependency": { + "runtime": "mediabunny@1.56.1 unchanged", + "declarationResolution": "@types/dom-webcodecs@0.1.19", + "minimumInternalTypeScript": "5.8", + "reason": "Replace incompatible 0.1.13 supplement for TypeScript5.9 DOM; add ESNext.Disposable lib for checked SDK declarations", + "publicTypesChanged": false + }, + "checks": [ + { + "command": "yarn test:mediabunny", + "result": "pass", + "tests": 56, + "log": "refactor/.cache/mb03-tests-final.log" + }, + { + "command": "ARTPLAYER_MB_BASELINE=1 node --test test/mediabunny-load.test.js", + "result": "expected historical failures", + "pass": 6, + "fail": 14, + "log": "refactor/.cache/mb03-frozen-expanded.log" + }, + { + "command": "package strict typecheck and focused eslint --no-fix", + "result": "pass", + "strictProductionModules": 6 + }, + { + "command": "yarn install --frozen-lockfile --ignore-scripts --non-interactive", + "result": "pass; already up-to-date", + "log": "refactor/.cache/mb03-frozen-install.log" + }, + { + "command": "yarn build artplayer-proxy-mediabunny", + "result": "pass", + "formats": [ + "main", + "legacy", + "esm" + ], + "log": "refactor/.cache/mb03-build.log" + }, + { + "command": "built main/legacy load regressions and main/legacy/ESM export checks", + "result": "pass", + "main": 20, + "legacy": 20, + "scope": "Local artifacts, not installed package consumers" + }, + { + "command": "yarn test:browser test/browser/mediabunny-inputs.spec.js test/browser/mediabunny.spec.js test/browser/mediabunny-load.spec.js with built main", + "result": "pass", + "tests": 72, + "candidate": 30, + "historical": 42, + "log": "refactor/.cache/mb03-browser-built.log" + }, + { + "command": "yarn ci:check", + "result": "pass", + "tests": { + "unit": 1062, + "engineering": 14, + "baseline": 141, + "mainTotal": 1217, + "repeatedContractExecutions": 44 + }, + "strictProductionTypeScriptFiles": 296, + "log": "refactor/.cache/mb03-ci-final.log" + } + ], + "limitations": [ + "Partial package migration: seven JavaScript modules remain.", + "Two candidate trackless readiness cases expose MB-READY-01, not release acceptance.", + "Seven Windows WebKit candidate capability controls are not successful playback.", + "Stream cancellation occurs before media bytes; pending decoder frames/audio callbacks remain MB-04/05/06.", + "Long-run AV sync, native combinations, demo/installed package/license and release reviews remain open." + ], + "failedAttempts": [ + { + "log": "refactor/.cache/mb03-ci.log", + "resolution": "Updated stale input.js evidence in third-party integration inventory; kept validation enabled and reran its tests and full CI." + } + ] +} diff --git a/refactor/changes/2026-09-12-PKG-MB-03-input.md b/refactor/changes/2026-09-12-PKG-MB-03-input.md new file mode 100644 index 000000000..b45bd61c8 --- /dev/null +++ b/refactor/changes/2026-09-12-PKG-MB-03-input.md @@ -0,0 +1,62 @@ +# PKG-MB-03 输入、Range 与加载取消 + +## 结构与兼容 + +原input.js拆为input.ts、media.ts、tracks.ts、hls-state.ts;新增preflight.ts和load-session.ts, +共六个strict生产TS模块。原Engine/VideoEngine仅接入新边界,主协调、视频、音频和HLS UI的 +其余迁移仍分别归04/05/06/07。实际维护地图见包内ARCHITECTURE.md。 + +保留String/Blob/ReadableStream、SDK Source/SourceRef转交和SDK对错误输入的验证; +HLS匹配、成对音轨、live/metadata/computed时长、语言别名和默认auto/manual模式保持。 +公开factory、Canvas精确Result、types及main/module/legacy路径均未更改。 + +API-05/10的明确缺陷修正:旧加载在切源/销毁/超时后无需等待底层操作即可settle, +不能再发晚error/Range事件或持有等待定时器;成功加载清除deadline;销毁后load无副作用。 +当前活动错误仍code4,超时仍Load timeout/networkState3。合法正常Range行为保留: +缺头/none发RangeNotSupported detail但不设置engine.error,网络失败警告后继续,HLS跳过HEAD。 + +Input在创建后、异步选轨前就属于LoadSession;engine.input/media只在选轨后暴露, +避免旧实现未绑定Input期间无法取消。Input.dispose由唯一session负责,幂等释放; +SDK声明明确不允许UrlSource.requestInit.signal,媒体请求交给Input.dispose取消。 +独立HEAD使用AbortController和代次守卫;无AbortController仍隔离过期结果,不能声称物理中止请求。 + +## 类型与依赖决策 + +首次严格检查实际复现SDK依赖dom-webcodecs0.1.13与TS5.9.3 DOM的重复声明和BufferSource冲突, +以及缺失Disposable。未开启skipLibCheck,也未使用自制any类型掩盖SDK。 +通过Yarn registry确认并固定@types/dom-webcodecs0.1.19(最低TS5.8),root resolutions覆盖两个 +传递路径;yarn.lock记录完整性。SDK运行时仍1.56.1、原始四文件哈希未改。 +Yarn会明确提示替换SDK精确0.1.13,这是有记录的仅声明覆盖,不是无意漂移。 +包内lib追加ESNext.Disposable以检查SDK声明;target仍ES2020,源代码未引入using/Symbol.dispose。 +公共声明不引用SDK,不把内部编译器版本要求传给旧消费者。 + +## 验证 + +32项候选专项:12项来源/轨道/时长/HLS与真实SDK解析,20项加载正常及竞态回归。 +同一20项加载断言跑冻结旧main:6正常通过、14失败;候选20通过。原24项历史基线继续通过, +yarn test:mediabunny共56项已接入test:unit。main与legacy各20项通过;三格式由仓库build生成。 + +首轮21项候选源码浏览器检查通过,包含12次实际播放、7次Windows WebKit能力对照、 +2次待修复的无轨道就绪行为。构建产物的完整矩阵另加真实浏览器Stream取消(无模拟timer), +最终报告、结果和源码/产物哈希见[验证证据](../baselines/mb-input-validation.json)。 + +测试初稿的空源操作在受控环境触发真实AudioContext缺失,仅在对应隔离Range用例中明确控制 +无音轨处理;跨VM对象原型改为字段比较;MP4 fixture实际8秒修正了测试草稿2秒假设。 +这些失败日志与SDK声明冲突日志保留,均未修改冻结基线或扩大媒体成功定义。 + +## 剩余范围与回退 + +本步没有宣称解决所有生命周期问题。重复/无轨道就绪、事件重入、pending play/seek、 +已经进入解码器的晚帧/音频回调、长期AV sync、HLS UI并发、完整安装与MPL通知仍有责任任务。 +旧createTimeout内部方法仍在Engine供后续协调迁移审查,正常load已不通过它创建无人管理的timer。 +PKG-MB-09/10及全局发布复盘未完成。保持Canvas/Ambilight类型决策待确认;未推送或发布。 + +回退以本任务独立提交为单位,同时回退六模块、JS接入、产物、Yarn声明覆盖、测试和文档; +不要覆盖03451c02的历史媒体基线。完成状态以任务表、最终验证证据和独立commit为准。 + +首轮完整CI的单元/工程通过,基线中第三方来源清单仍指向已拆分input.js。 +已同步third-party.json的六模块来源路径与验证范围,专项台账及完整CI随后复跑;未降低台账校验。 + +最终完整CI1217项通过(1062单元、14工程、141基线),另44重复契约,296生产TS严格检查。 +最终72项浏览器无失败/重试/跳过;候选30项为12次播放、9次原生Stream取消、7次能力对照、 +2次已登记trackless就绪缺口。源码、产物、测试哈希与报告匹配,docs/compiled与dist三格式逐字节一致。 diff --git a/refactor/mb-validation.md b/refactor/mb-validation.md index f960ecbfe..b4d015ead 100644 --- a/refactor/mb-validation.md +++ b/refactor/mb-validation.md @@ -25,6 +25,14 @@ play/load/seek转发测试刻意截获engine方法;不得宣传为真实播放 ## 后续顺序 +MB-03实施将input分离为六个strict TS模块,接入加载session、Range取消和SDK Input释放。 +实际文件地图见包内ARCHITECTURE.md,过程见[输入迁移](changes/2026-09-12-PKG-MB-03-input.md)。 +`yarn test:mediabunny`现在包括24历史、20候选加载及12输入/轨道检查;20加载断言可通过 +`ARTPLAYER_MB_BASELINE=1`重跑冻结main,正常控制6通过、缺陷回归14失败。 +浏览器默认包含两个发布版与候选,并增加mediabunny-load.spec.js的三种真实Stream取消; +`ARTPLAYER_MB_ARTIFACT`指定构建的UMD文件,`ARTPLAYER_MB_BROWSER_CANDIDATE=1`可仅跑候选。 +每轮须读取报告确认具体数量和结果;配置了用例不等于该轮已运行。 + 1. MB-02的输入、seek、HLS轨道、无轨道和失败样本见行为基线。42项浏览器检查须区分 20次实际播放、12次能力对照、6次历史输入失败及4次无轨道就绪行为;24项生命周期测试含18个历史缺陷。 后续修改须复跑对应正常和负例,不把全部负例变为候选豁免;并发选轨、晚帧和音频回调的完整修复分别在04/05/06/07。 diff --git a/refactor/plan.md b/refactor/plan.md index 2aef873f7..e44763c11 100644 --- a/refactor/plan.md +++ b/refactor/plan.md @@ -4,7 +4,7 @@ 基线:`40fcda6a37d0049d42e49c1e64e70d4fd9ba5f7f`。总任务 222 项,范围 22 个包及工作区/示例。 -状态:todo 116 / doing 7 / blocked 0 / done 99 / deferred 0。风险 L/M/H 表示兼容风险,不表示工期。 +状态:todo 115 / doing 7 / blocked 0 / done 100 / deferred 0。风险 L/M/H 表示兼容风险,不表示工期。 前置依赖是启动条件;验收是完成条件。任务可以继续拆分,但不能复用或悄悄删除旧 ID。 @@ -331,7 +331,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 | todo | +| 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 | todo | | 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 | @@ -522,4 +522,5 @@ - PKG-CANVAS-04: [记录](changes/2026-09-12-PKG-CANVAS-04-types.md) [记录](baselines/canvas-types-validation.json) [记录](canvas-validation.md) - 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-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 006e910dd..2c7fe7789 100644 --- a/refactor/progress.md +++ b/refactor/progress.md @@ -1,5 +1,16 @@ # 进度与证据 +## 最新完成:PKG-MB-03 输入、Range与加载取消 + +六个strict TS模块已接入生产,修复切源/销毁/超时后的待加载Input、HEAD及timer资源与陈旧回调。 +同一20项加载断言在冻结版6通过/14失败,候选source/main/legacy各20通过;来源/轨道12项与 +旧基线24项继续通过。实际SDK保持1.56.1,WebCodecs补充声明固定0.1.19解决严格DOM声明冲突。 +三格式构建与导出通过,72项最终浏览器检查通过;候选30项含12播放、9原生Stream取消、7能力 +失败对照、2待修复无轨道就绪。完整CI1217项(1062单元+14工程+141基线),另44重复契约,296生产TS。 +见[步骤记录](changes/2026-09-12-PKG-MB-03-input.md)和[验证证据](baselines/mb-input-validation.json)。 +下一步MB-04主协调/事件/VideoShim;晚帧、音频、HLS UI和完整发布验收仍未完成。 +222项:100 done、7 doing、115 todo。Canvas/Ambilight类型决定仍待确认;独立本地commit,不推送/发布。 + ## 最新完成:PKG-MB-02 媒体、事件与资源基线 24项历史生命周期检查通过,已接入统一CI;42项真实浏览器检查包含20次播放、12次环境能力 diff --git a/refactor/risks.json b/refactor/risks.json index 3097670cf..f122c4109 100644 --- a/refactor/risks.json +++ b/refactor/risks.json @@ -755,7 +755,7 @@ "PKG-MB-09" ], "evidence": [ - "packages/artplayer-proxy-mediabunny/src/input.js", + "packages/artplayer-proxy-mediabunny/src/input.ts", "packages/artplayer-proxy-mediabunny/package.json" ], "compatibleResolution": "Preserve native-video-like events, HLS input and topology, codec capability failures and AV sync; actual library/codec environment still requires verification.", @@ -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.", + "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.", "closureCriteria": "Historical failing interleavings and candidate cancellation/cleanup pass with real media and event evidence, including long playback and track topology.", "status": "open", "evidence": [ @@ -3658,7 +3658,8 @@ "refactor/changes/2026-09-12-PKG-MB-02-checkpoint.md", "refactor/baselines/mb-media-checkpoint.json", "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-03-input.md" ] }, { diff --git a/refactor/tasks.json b/refactor/tasks.json index 1717a6ef0..b2debb990 100644 --- a/refactor/tasks.json +++ b/refactor/tasks.json @@ -3439,11 +3439,14 @@ "PKG-MB-02", "CORE-09" ], - "status": "todo", + "status": "done", "risk": "H", "deliverable": "input.js 源检测、输入资源、Range 与取消", "acceptance": "HLS 检测在 input 边界,旧来源类型和超时保持", - "evidence": [] + "evidence": [ + "changes/2026-09-12-PKG-MB-03-input.md", + "baselines/mb-input-validation.json" + ] }, { "id": "PKG-MB-04", diff --git a/refactor/third-party.json b/refactor/third-party.json index 7aeae9369..037a7b439 100644 --- a/refactor/third-party.json +++ b/refactor/third-party.json @@ -1172,11 +1172,16 @@ "PKG-MB-09" ], "sourceFiles": [ - "packages/artplayer-proxy-mediabunny/src/input.js", + "packages/artplayer-proxy-mediabunny/src/input.ts", + "packages/artplayer-proxy-mediabunny/src/media.ts", + "packages/artplayer-proxy-mediabunny/src/tracks.ts", + "packages/artplayer-proxy-mediabunny/src/hls-state.ts", + "packages/artplayer-proxy-mediabunny/src/preflight.ts", + "packages/artplayer-proxy-mediabunny/src/load-session.ts", "packages/artplayer-proxy-mediabunny/package.json" ], "contract": "Preserve native-video-like events, HLS input and topology, codec capability failures and AV sync; actual library/codec environment still requires verification.", - "validationStatus": "PKG-MB-01 verifies actual 1.0.0/1.2.0 archives and installed 1.56.1 MPL-2.0 provenance, recorded in mb-release.json and mb-contract.md. Historical embedded SDK version is unknown; notices are MB-LICENSE-01/MB-10. Native codec, SDK media and AV sync remain MB-02/09.", + "validationStatus": "PKG-MB-01 verifies actual 1.0.0/1.2.0 archives and installed 1.56.1 MPL-2.0 provenance, recorded in mb-release.json and mb-contract.md. Historical embedded SDK version is unknown; notices are MB-LICENSE-01/MB-10. Native codec, SDK media and AV sync remain MB-02/09. MB-02 freezes actual native input behavior; MB-03 candidate has 72 browser checks including 12 candidate plays and nine native pending-stream cancellations, six strict TS modules and a build-only WebCodecs 0.1.19 resolution. Full AV sync/decoder cleanup and release notices remain MB-04/05/06/09/10.", "demoPathsSource": "refactor/baselines/demo-inventory.json" }, { diff --git a/test/README.md b/test/README.md index e564222d1..1e9f37cf1 100644 --- a/test/README.md +++ b/test/README.md @@ -2,6 +2,12 @@ Use the pinned Node/Yarn toolchain from `../refactor/toolchain-setup.md`. +`yarn test:mediabunny` runs historical lifecycle observations, candidate load cancellation, +and real SDK input parsing/track contracts; all are in `test:unit`. Candidate failures +can be reproduced against the frozen main with `ARTPLAYER_MB_BASELINE=1`. This does not +replace native playback or installed consumers. See `refactor/mb-validation.md` and the +proxy package's `ARCHITECTURE.md` for browser and artifact selection. + `yarn test:ads` runs source, verified npm 1.0.6 and the frozen unpublished 2.1.0 Ads bundle against controlled clock/host contracts. It is included in `test:unit`. The helper uses the real option validator but does not simulate media decoding or layout. diff --git a/test/browser/mediabunny-inputs.spec.js b/test/browser/mediabunny-inputs.spec.js index 53242df3e..832315f92 100644 --- a/test/browser/mediabunny-inputs.spec.js +++ b/test/browser/mediabunny-inputs.spec.js @@ -1,11 +1,11 @@ import assert from 'node:assert/strict' import fs from 'node:fs' import { hash } from '../../refactor/scripts/releases.mjs' -import { mbHistorical } from '../helpers/mediabunny.js' +import { mbBrowserImplementations } from '../helpers/mediabunny.js' import { tracklessMp4 } from '../helpers/trackless-mp4.js' import { expect, test } from './fixtures.js' -const implementations = (await mbHistorical()).filter(item => item.name.startsWith('published')) +const implementations = await mbBrowserImplementations() const manifest = JSON.parse(fs.readFileSync(new URL('./media/hls/manifest.json', import.meta.url))) const hls = new Map(Object.entries(manifest.files).map(([name, expected]) => { const bytes = fs.readFileSync(new URL(`./media/hls/${name}`, import.meta.url)) @@ -98,7 +98,13 @@ for (const implementation of implementations) { else if (capabilities.AudioContext === 'undefined' && capabilities.webkitAudioContext === 'undefined') { expect(browserName).toBe('webkit') expect(capabilities).toEqual({ VideoDecoder: 'undefined', AudioDecoder: 'undefined', AudioContext: 'undefined', webkitAudioContext: 'undefined' }) - expect(loaded.error).toEqual({ code: 4, message: 'undefined is not a constructor (evaluating \'new t\')' }) + if (implementation.name.startsWith('candidate')) { + expect(loaded.error.code).toBe(4) + expect(loaded.error.message).toMatch(/^undefined is not a constructor \(evaluating 'new [\w$]+(?:\(\))?'\)$/) + } + else { + expect(loaded.error).toEqual({ code: 4, message: 'undefined is not a constructor (evaluating \'new t\')' }) + } expect(loaded.readyState).toBeLessThan(4) outcome = 'unsupported-capability-control' } @@ -107,9 +113,9 @@ for (const implementation of implementations) { expect(loaded.readyState).toBe(4) if (input === 'trackless') { expect(loaded.dimensions).toEqual([0, 0]) - expect(await page.evaluate(() => window.mbEvents.filter(item => item.name === 'video:loadedmetadata').length)).toBe(implementation.name === 'published-1.2.0' ? 2 : 1) + 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 = 'historical-trackless-readiness-control' + outcome = implementation.name.startsWith('candidate') ? 'candidate-trackless-readiness-gap' : '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))) @@ -208,7 +214,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: 'Actual published 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.' }) }) + 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.' }) }) } }) } diff --git a/test/browser/mediabunny-load.spec.js b/test/browser/mediabunny-load.spec.js new file mode 100644 index 000000000..7bb7708c4 --- /dev/null +++ b/test/browser/mediabunny-load.spec.js @@ -0,0 +1,66 @@ +import { hash } from '../../refactor/scripts/releases.mjs' +import { mbCandidate } from '../helpers/mediabunny.js' +import { expect, test } from './fixtures.js' + +const implementation = await mbCandidate() +for (const ending of ['destroy', 'source', 'timeout']) { + test(`MediaBunny ${implementation.name}: native pending stream cancelled by ${ending}`, async ({ page }, testInfo) => { + await page.goto('/test/player.html?core=published') + await page.addScriptTag({ content: `(() => { const module = { exports: {} }; const exports = module.exports; + ${implementation.code}; window.mbFactory = module.exports.default || module.exports; })();` }) + await page.evaluate(() => { + const listeners = new Map() + window.mbCancelled = [] + window.mbEvents = [] + window.mbHost = { + constructor: window.Artplayer, + option: { url: '', autoSize: false }, + template: { $player: document.querySelector('.player') }, + on(name, callback) { + const list = listeners.get(name) || [] + list.push(callback) + listeners.set(name, list) + }, + emit(name, ...args) { + window.mbEvents.push(name) + for (const callback of listeners.get(name) || []) callback(...args) + }, + } + window.mbCanvas = window.mbFactory({ loadTimeout: 1000 })(window.mbHost) + window.mbStream = new ReadableStream({ cancel() { + window.mbCancelled.push('old') + } }) + window.mbSettled = false + window.mbLoad = window.mbCanvas.engine.load(window.mbStream).then(() => window.mbSettled = true) + }) + try { + await expect.poll(() => page.evaluate(() => window.mbStream.locked)).toBe(true) + expect(await page.evaluate(() => window.mbSettled)).toBe(false) + await page.evaluate((ending) => { + if (ending === 'destroy') + window.mbHost.emit('destroy') + if (ending === 'source') { + window.mbReplacement = new ReadableStream({ cancel() { + window.mbCancelled.push('new') + } }) + window.mbNextLoad = window.mbCanvas.engine.load(window.mbReplacement) + } + }, ending) + await expect.poll(() => page.evaluate(() => window.mbSettled)).toBe(true) + expect(await page.evaluate(() => window.mbCancelled)).toEqual(['old']) + const state = await page.evaluate(() => ({ error: window.mbCanvas.error, readyState: window.mbCanvas.readyState, events: window.mbEvents, input: window.mbCanvas.engine.input === null })) + expect(state.input).toBe(true) + expect(state.readyState).toBe(0) + expect(state.events.filter(name => ['video:loadedmetadata', 'video:loadeddata', 'video:canplay'].includes(name))).toEqual([]) + expect(state.error).toEqual(ending === 'timeout' ? { code: 4, message: 'Load timeout' } : null) + if (ending === 'source') + await expect.poll(() => page.evaluate(() => window.mbReplacement.locked)).toBe(true) + await page.evaluate(() => window.mbHost.emit('destroy')) + await expect.poll(() => page.evaluate(() => window.mbCancelled)).toEqual(ending === 'source' ? ['old', 'new'] : ['old']) + await testInfo.attach('mediabunny-load-cancellation', { contentType: 'application/json', body: JSON.stringify({ implementation: implementation.name, sha256: hash(implementation.code), ending, state, cancellations: await page.evaluate(() => window.mbCancelled), 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.' }) }) + } + finally { + await page.evaluate(() => window.mbHost.emit('destroy')) + } + }) +} diff --git a/test/browser/mediabunny.spec.js b/test/browser/mediabunny.spec.js index 6fd0fdc59..b801421b9 100644 --- a/test/browser/mediabunny.spec.js +++ b/test/browser/mediabunny.spec.js @@ -1,8 +1,8 @@ import { hash } from '../../refactor/scripts/releases.mjs' -import { mbHistorical } from '../helpers/mediabunny.js' +import { mbBrowserImplementations } from '../helpers/mediabunny.js' import { expect, test } from './fixtures.js' -const implementations = (await mbHistorical()).filter(item => item.name.startsWith('published')) +const implementations = await mbBrowserImplementations() for (const implementation of implementations) { test(`MediaBunny ${implementation.name}: native MP4 playback or exact Windows WebKit capability failure`, async ({ page, browserName }, testInfo) => { diff --git a/test/helpers/mediabunny.js b/test/helpers/mediabunny.js index 1dd38d0d5..99e958174 100644 --- a/test/helpers/mediabunny.js +++ b/test/helpers/mediabunny.js @@ -1,6 +1,24 @@ +import fs from 'node:fs' +import process from 'node:process' import vm from 'node:vm' import { verifyMbContract } from '../../refactor/scripts/mb-contract.mjs' import { readMember } from '../../refactor/scripts/releases.mjs' +import { compilePackage } from './load.js' + +export async function mbCandidate() { + if (process.env.ARTPLAYER_MB_BASELINE === '1') + return (await mbHistorical()).find(item => item.name === 'frozen-workspace') + if (process.env.ARTPLAYER_MB_ARTIFACT) + return { name: 'candidate-artifact', code: fs.readFileSync(process.env.ARTPLAYER_MB_ARTIFACT, 'utf8') } + return { name: 'candidate-source', code: await compilePackage('artplayer-proxy-mediabunny', 'umd') } +} + +export async function mbBrowserImplementations() { + const candidate = await mbCandidate() + return process.env.ARTPLAYER_MB_BROWSER_CANDIDATE === '1' + ? [candidate] + : [...(await mbHistorical()).filter(item => item.name.startsWith('published')), candidate] +} export async function mbHistorical() { const { baseline, archives, sources } = await verifyMbContract() @@ -63,6 +81,8 @@ export function mbEnvironment({ code }, option = {}) { Blob, Event, URL, + AbortController, + queueMicrotask, console, performance, setTimeout: option.setTimeout || setTimeout, diff --git a/test/mediabunny-input.test.js b/test/mediabunny-input.test.js new file mode 100644 index 000000000..48abe676e --- /dev/null +++ b/test/mediabunny-input.test.js @@ -0,0 +1,140 @@ +import assert from 'node:assert/strict' +import fs from 'node:fs' +// eslint-disable-next-line test/no-import-node-test -- Use actual SDK input parsing and explicit track selection contracts. +import test from 'node:test' +import { loadModules } from './helpers/load.js' + +const base = 'packages/artplayer-proxy-mediabunny/src/' +const { isHlsSource, normalizeSource, createInput, resolveDuration, selectPlaybackTracks, getHlsState } = await loadModules({ + isHlsSource: { file: `${base}input`, name: 'isHlsSource' }, + normalizeSource: { file: `${base}input`, name: 'normalizeSource' }, + createInput: { file: `${base}input`, name: 'createInput' }, + resolveDuration: { file: `${base}tracks`, name: 'resolveDuration' }, + selectPlaybackTracks: { file: `${base}tracks`, name: 'selectPlaybackTracks' }, + getHlsState: { file: `${base}hls-state`, name: 'getHlsState' }, +}) + +test('MediaBunny input detection preserves URL suffix, query/hash, casing and non-string boundaries', () => { + for (const source of ['live.m3u8', 'LIVE.M3U8?token=x', 'live.m3u8#segment']) assert.equal(isHlsSource(source), true) + for (const source of ['live.m3u8.mp4', 'file.mp4?name=live.m3u8&x=1', new URL('https://example.com/live.m3u8'), null, new Blob()]) assert.equal(isHlsSource(source), false) +}) + +test('MediaBunny inputs preserve falsy source handling and SDK validation ownership', () => { + for (const source of [null, undefined, false, 0]) assert.equal(createInput(source), null) + for (const source of [{ invalid: true }, 42, true]) { + assert.equal(normalizeSource(source), source) + assert.throws(() => createInput(source), { message: 'options.source must be a Source or SourceRef.' }) + } + const source = normalizeSource('https://example.com/movie.mp4') + assert.equal(normalizeSource(source), source) + const input = createInput(source) + input.dispose() +}) + +for (const sourceType of ['blob', 'stream']) { + test(`MediaBunny ${sourceType} uses one actual SDK input for metadata, duration and track selection`, async () => { + const bytes = fs.readFileSync(new URL('./browser/media/pattern.mp4', import.meta.url)) + const source = sourceType === 'blob' + ? new Blob([bytes]) + : new ReadableStream({ start(controller) { + for (let offset = 0; offset < bytes.length; offset += 1024) controller.enqueue(bytes.subarray(offset, offset + 1024)) + controller.close() + } }) + const input = createInput(source) + try { + const media = await selectPlaybackTracks(input, source) + assert.equal(media.input, input) + assert.equal(media.videoTrack.displayWidth, 320) + assert.equal(media.videoTrack.displayHeight, 180) + assert.equal(media.audioTrack, null) + assert.equal(media.duration, 8) + assert.equal(media.isLive, false) + assert.equal(media.videoMode, 'manual') + assert.equal(media.audioMode, 'manual') + assert.equal(await getHlsState(media), null) + } + finally { input.dispose() } + }) +} + +for (const scenario of ['metadata', 'computed', 'live', 'unknown', 'trackless']) { + test(`MediaBunny duration preserves ${scenario} handling without scanning live or trackless inputs`, async () => { + const calls = [] + const track = scenario === 'trackless' ? null : { isLive: async () => scenario === 'live' } + const duration = await resolveDuration({ + input: { + getDurationFromMetadata: async (tracks, option) => { + assert.deepEqual(tracks, [track]) + assert.deepEqual(option, { skipLiveWait: true }) + calls.push('metadata') + return scenario === 'metadata' ? 12 : null + }, + computeDuration: async (tracks, option) => { + assert.deepEqual(tracks, [track]) + assert.deepEqual(option, { skipLiveWait: true }) + calls.push('compute') + return scenario === 'unknown' ? null : 18 + }, + }, + videoTrack: track, + audioTrack: null, + }) + assert.equal(duration, scenario === 'metadata' ? 12 : scenario === 'computed' ? 18 : scenario === 'live' ? Infinity : Number.NaN) + assert.deepEqual(calls, scenario === 'trackless' ? [] : ['computed', 'unknown'].includes(scenario) ? ['metadata', 'compute'] : ['metadata']) + }) +} + +test('MediaBunny chooses pairable audio from primary video instead of an unrelated primary audio track', async () => { + const paired = { id: 2 } + const videoTrack = { isLive: async () => false, getPrimaryPairableAudioTrack: async () => paired } + const input = { + getPrimaryVideoTrack: async () => videoTrack, + getPrimaryAudioTrack: async () => { throw new Error('Unrelated audio must not be selected') }, + getDurationFromMetadata: async (tracks) => { + assert.deepEqual(tracks, [videoTrack, paired]) + return 5 + }, + } + const media = await selectPlaybackTracks(input, 'live.m3u8') + assert.equal(media.audioTrack, paired) + assert.equal(media.videoMode, 'auto') + assert.equal(media.audioMode, 'auto') + assert.equal(media.isHls, true) +}) + +test('MediaBunny audio-only input selects primary audio and retains live detection', async () => { + const audioTrack = { isLive: async () => true } + const media = await selectPlaybackTracks({ getPrimaryVideoTrack: async () => null, getPrimaryAudioTrack: async () => audioTrack, getDurationFromMetadata: async () => null }, 'live.m3u8') + assert.equal(media.videoTrack, null) + assert.equal(media.audioTrack, audioTrack) + assert.equal(media.duration, Infinity) + assert.equal(media.isLive, true) +}) + +test('MediaBunny HLS state keeps actual track identity, pairability, bitrate fallback and language aliases', async () => { + const audio = { id: 7, getName: async () => null, getLanguageCode: async () => 'fr', getAverageBitrate: async () => null, getBitrate: async () => 128000 } + const video = { + id: 3, + getName: async () => 'Main', + getDisplayHeight: async () => 180, + getAverageBitrate: async () => 0, + getBitrate: async () => { + throw new Error('Zero is a valid average bitrate') + }, + getPairableAudioTracks: async () => [audio], + } + const media = { input: { getVideoTracks: async () => [video] }, isHls: true, videoTrack: video, audioTrack: audio, videoMode: 'manual', audioMode: 'auto' } + const state = await getHlsState(media) + assert.equal(state.currentLevel, state.levels[0]) + assert.equal(state.currentAudio, state.audios[0]) + assert.equal(state.currentLevel.track, video) + assert.equal(state.currentLevel.bitrate, 0) + assert.equal(state.currentAudio.track, audio) + assert.equal(state.currentAudio.name, null) + assert.equal(state.currentAudio.lang, 'fr') + assert.equal(state.currentAudio.language, 'fr') + assert.equal(state.currentAudio.bitrate, 128000) + assert.equal(state.videoMode, 'manual') + assert.equal(state.audioMode, 'auto') + assert.equal(await getHlsState(null), null) +}) diff --git a/test/mediabunny-load.test.js b/test/mediabunny-load.test.js new file mode 100644 index 000000000..aa376cfd2 --- /dev/null +++ b/test/mediabunny-load.test.js @@ -0,0 +1,272 @@ +import assert from 'node:assert/strict' +import fs from 'node:fs' +// eslint-disable-next-line test/no-import-node-test -- Compare candidate cancellation with the frozen implementation. +import test from 'node:test' +import { mbCandidate, mbEnvironment } from './helpers/mediabunny.js' + +const implementation = await mbCandidate() +const flush = () => new Promise(resolve => setImmediate(resolve)) +function deferred() { + let resolve, reject + const promise = new Promise((yes, no) => { + resolve = yes + reject = no + }) + return { promise, resolve, reject } +} + +function environment(option = {}) { + const timers = new Map() + let sequence = 0 + const env = mbEnvironment(implementation, { + setTimeout(fn, delay) { + const id = sequence++ + timers.set(id, { fn, delay }) + return id + }, + clearTimeout(id) { timers.delete(id) }, + }) + env.eventNames.push('waiting', 'loadstart', 'loadeddata', 'canplay') + const canvas = env.factory(option)(env.art) + const errors = [] + const warnings = [] + env.globals.console = { error: (...args) => errors.push(args), warn: (...args) => warnings.push(args), log() {}, debug() {} } + function fire(delay) { + for (const [id, timer] of [...timers]) { + if (timer.delay === delay) { + timers.delete(id) + timer.fn() + } + } + } + return { ...env, canvas, engine: canvas.engine, timers, fire, errors, warnings } +} + +test('MediaBunny candidate destroy settles pending load, drops deferred events and ignores late failure', async () => { + const env = environment({ loadTimeout: 100 }) + const pending = deferred() + env.engine.performLoad = () => pending.promise + let settled = false + const loading = env.engine.load('movie.mp4').then(() => settled = true) + env.art.emit('destroy') + await flush() + assert.equal(settled, true, 'Cancellation must not wait for the underlying operation') + assert.equal(env.timers.size, 0) + const cursor = env.emitted.length + pending.reject(new Error('late failure')) + await loading + await flush() + assert.equal(env.engine.error, null) + assert.equal(env.emitted.length, cursor) +}) + +test('MediaBunny candidate source replacement settles old load without waiting for its result', async () => { + const env = environment({ loadTimeout: 100 }) + const pending = deferred() + const sources = [] + env.engine.performLoad = (src) => { + sources.push(src) + return src === 'old' ? pending.promise : Promise.resolve() + } + let settled = false + const old = env.engine.load('old').then(() => settled = true) + await env.engine.load('new') + await flush() + assert.equal(settled, true) + assert.deepEqual(sources, ['old', 'new']) + assert.equal([...env.timers.values()].filter(timer => timer.delay === 100).length, 0) + env.fire(0) + assert.deepEqual(env.emitted.map(event => event.name), ['video:waiting', 'video:loadstart']) + pending.reject(new Error('obsolete')) + await old + await flush() + assert.equal(env.engine.error, null) + env.art.emit('destroy') +}) + +test('MediaBunny candidate clears successful load deadline while keeping its normal deferred notifications', async () => { + const env = environment({ loadTimeout: 100 }) + env.engine.performLoad = async () => {} + await env.engine.load('movie.mp4') + assert.deepEqual([...env.timers.values()].map(timer => timer.delay), [0, 0]) + env.fire(0) + assert.deepEqual(env.emitted.map(event => event.name), ['video:waiting', 'video:loadstart']) + env.art.emit('destroy') + assert.equal(env.timers.size, 0) +}) + +test('MediaBunny candidate keeps active timeout error and suppresses a late operation failure', async () => { + const env = environment({ loadTimeout: 100 }) + const pending = deferred() + env.engine.performLoad = () => pending.promise + const loading = env.engine.load('movie.mp4') + env.fire(100) + await loading + assert.deepEqual({ ...env.engine.error }, { code: 4, message: 'Load timeout' }) + assert.equal(env.engine.networkState, 3) + assert.equal(env.timers.size, 0) + pending.reject(new Error('late failure')) + await flush() + assert.deepEqual(env.emitted.map(event => event.name), ['video:error']) + assert.equal(env.engine.error.message, 'Load timeout') + env.art.emit('destroy') +}) + +for (const ending of ['destroy', 'source', 'timeout']) { + test(`MediaBunny candidate ${ending} aborts pending HEAD and suppresses stale Range errors`, async () => { + const env = environment({ preflightRange: true, loadTimeout: 100 }) + const response = deferred() + let request + env.globals.fetch = (url, init) => { + request = { url, init } + return response.promise + } + const loading = env.engine.load('movie.mp4') + assert.equal(request.init.method, 'HEAD') + if (ending === 'destroy') { + env.art.emit('destroy') + } + else if (ending === 'source') { + env.engine.audio.handleNoAudioTrack = () => {} + await env.engine.load(null) + } + else { + env.fire(100) + } + await flush() + assert.equal(request.init.signal?.aborted, true) + const cursor = env.emitted.length + response.resolve({ headers: { get: () => 'none' } }) + await loading + await flush() + assert.equal(env.emitted.length, cursor) + assert.equal(env.warnings.length, 0) + if (ending === 'timeout') + assert.equal(env.engine.error.message, 'Load timeout') + else assert.equal(env.engine.error, null) + env.art.emit('destroy') + assert.equal(env.timers.size, 0) + }) +} + +for (const ending of ['destroy', 'source', 'timeout']) { + test(`MediaBunny candidate ${ending} disposes the real SDK Input while its first stream read is pending`, async () => { + const env = environment({ loadTimeout: 100 }) + let cancellations = 0 + const stream = new ReadableStream({ cancel() { + cancellations++ + } }) + let settled = false + const loading = env.engine.load(stream).then(() => settled = true) + await flush() + assert.equal(stream.locked, true, 'The SDK must have started reading the real stream') + if (ending === 'destroy') + env.art.emit('destroy') + else if (ending === 'source') + await env.engine.load(null) + else env.fire(100) + await flush() + assert.equal(settled, true) + assert.equal(cancellations, 1) + assert.equal(env.engine.input, null) + assert.equal(env.engine.media, null) + await loading + env.art.emit('destroy') + assert.equal(cancellations, 1) + assert.equal(env.timers.size, 0) + }) +} + +test('MediaBunny candidate Range retains supported, missing, network-failure and HLS bypass behavior', async () => { + const env = environment({ preflightRange: true }) + const requests = [] + env.globals.fetch = async (url, init) => { + requests.push({ url, init }) + if (url === 'network') + throw new Error('network failure') + return { headers: { get: () => url === 'supported' ? 'bytes' : null } } + } + assert.equal(await env.engine.video.preflight('supported'), true) + assert.equal(await env.engine.video.preflight('missing'), false) + assert.equal(env.emitted.at(-1).args[0].detail.type, 'RangeNotSupported') + assert.equal(env.engine.error, null) + assert.equal(await env.engine.video.preflight('network'), true) + assert.equal(env.warnings.length, 1) + assert.equal(await env.engine.video.preflight('LIVE.M3U8?x=1'), true) + assert.equal(await env.engine.video.preflight(new Blob()), true) + assert.deepEqual(requests.map(({ url, init }) => ({ url, init: { ...init } })), ['supported', 'missing', 'network'].map(url => ({ url, init: { method: 'HEAD' } }))) + env.art.emit('destroy') +}) + +test('MediaBunny candidate has no load side effects after destruction', async () => { + const env = environment() + let calls = 0 + env.engine.performLoad = async () => calls++ + env.art.emit('destroy') + await env.engine.load('later.mp4') + assert.equal(calls, 0) + assert.equal(env.timers.size, 0) +}) + +for (const failure of [false, true]) { + test(`MediaBunny candidate suppresses stale HEAD ${failure ? 'rejection' : 'response'} without AbortController`, async () => { + const env = environment({ preflightRange: true }) + env.globals.AbortController = undefined + const response = deferred() + env.globals.fetch = () => response.promise + let settled = false + const loading = env.engine.load('movie.mp4').then(() => settled = true) + env.art.emit('destroy') + await flush() + assert.equal(settled, true) + const cursor = env.emitted.length + if (failure) + response.reject(new Error('obsolete')) + else response.resolve({ headers: { get: () => null } }) + await loading + await flush() + assert.equal(env.emitted.length, cursor) + assert.equal(env.warnings.length, 0) + }) +} + +for (const timeout of [0, -1, Number.NaN, Infinity, '100']) { + test(`MediaBunny candidate keeps ${String(timeout)} timeout disabled`, async () => { + const env = environment({ loadTimeout: timeout }) + env.engine.performLoad = async () => {} + await env.engine.load('movie.mp4') + assert.deepEqual([...env.timers.values()].map(timer => timer.delay), [0, 0]) + env.art.emit('destroy') + }) +} + +test('MediaBunny candidate releases the real SDK input after decoder setup failure and ignores late metadata', async () => { + const env = environment() + const pendingAudio = deferred() + let metadata + let disposals = 0 + env.engine.video.load = async (media) => { + const dispose = media.input.dispose.bind(media.input) + media.input.dispose = () => { + disposals++ + dispose() + } + throw new Error('decoder setup failed') + } + env.engine.audio.load = (media, onMetadata) => { + metadata = onMetadata + return pendingAudio.promise + } + await env.engine.load(new Blob([fs.readFileSync(new URL('./browser/media/pattern.mp4', import.meta.url))])) + assert.equal(disposals, 1) + assert.equal(env.engine.input, null) + assert.equal(env.engine.error.message, 'decoder setup failed') + const cursor = env.emitted.length + metadata() + pendingAudio.resolve() + await flush() + assert.equal(env.emitted.length, cursor) + assert.equal(env.engine.readyState, 0) + env.art.emit('destroy') + assert.equal(disposals, 1) +}) diff --git a/yarn.lock b/yarn.lock index 675485a4a..d42494ce0 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1717,15 +1717,10 @@ dependencies: "@types/dom-webcodecs" "*" -"@types/dom-webcodecs@*": - version "0.1.18" - resolved "https://registry.npmjs.org/@types/dom-webcodecs/-/dom-webcodecs-0.1.18.tgz" - integrity sha512-vAvE8C9DGWR+tkb19xyjk1TSUlJ7RUzzp4a9Anu7mwBT+fpyePWK1UxmH14tMO5zHmrnrRIMg5NutnnDztLxgg== - -"@types/dom-webcodecs@0.1.13": - version "0.1.13" - resolved "https://registry.npmjs.org/@types/dom-webcodecs/-/dom-webcodecs-0.1.13.tgz" - integrity sha512-O5hkiFIcjjszPIYyUSyvScyvrBoV3NOEEZx/pMlsu44TKzWNkLVBBxnxJz42in5n3QIolYOcBYFCPZZ0h8SkwQ== +"@types/dom-webcodecs@*", "@types/dom-webcodecs@0.1.13", "@types/dom-webcodecs@0.1.19": + version "0.1.19" + resolved "https://registry.yarnpkg.com/@types/dom-webcodecs/-/dom-webcodecs-0.1.19.tgz#46479c9f47fb0024b762aa38987b38e3c31ac650" + integrity sha512-+yFUIDUaASFz0vQpWBErPxun/Lb+F0TdrlTsj50gm7K797YzEx2TmV6fEiwciHyFNghlZYPgQXH5qRcwMHcJFQ== "@types/estree@1.0.8", "@types/estree@^1.0.6", "@types/estree@^1.0.8": version "1.0.8"