mirror of
https://github.com/zhw2590582/ArtPlayer.git
synced 2026-10-08 10:56:15 -08:00
feat: add danmuku plugin documentation and i18n setup guide - Created a new documentation file for the danmuku plugin with code examples. - Added a comprehensive guide for language settings (i18n) including default languages, importing languages, adding new languages, and modifying existing languages. - Included code snippets for initializing the Artplayer with different language settings. Add internationalization support for multiple languages in Artplayer - Introduced Arabic (ar), Czech (cs), Spanish (es), Persian (fa), French (fr), Indonesian (id), Polish (pl), Russian (ru), Turkish (tr), Vietnamese (vi), and Traditional Chinese (zh-tw) translations. - Created corresponding JavaScript and ES module files for each language containing translated strings for player controls and settings. - Added a new documentation file for language settings in the project. feat: add initial implementation of start option page with interactive code execution buttons feat: add danmuku plugin documentation and i18n setup guide - Created a new documentation file for the danmuku plugin, providing code examples for usage. - Added a comprehensive guide for language settings, including default languages, importing languages, adding new languages, and modifying existing languages. - Included code snippets for initializing the Artplayer with different language settings and importing language files. refactor: update danmuku worker implementation and remove unused i18n files - Changed the way the Danmuku class creates a Web Worker by using a worker loader instead of creating a blob. - Removed Arabic, Czech, Spanish, Persian, French, Indonesian, Polish, Russian, Turkish, Vietnamese, and Traditional Chinese i18n files as they are no longer needed. - Updated the Vite build configuration to disable banners for inline workers and added a plugin to remove worker banners from generated code. feat: add danmuku plugin and i18n setup documentation - Created a new documentation file for the danmuku plugin, providing code examples for usage. - Added a new documentation file for language settings (i18n), detailing how to set default languages, import languages, and add new languages. - Included code snippets for initializing the Artplayer with different language settings and examples for modifying existing languages. feat: add danmuku plugin and i18n setup documentation - Created a new documentation file for the danmuku plugin with code examples. - Added a new documentation file for language settings (i18n) including import instructions and examples for setting default and custom languages. - Updated the i18n documentation to include details on adding and modifying languages. feat: add danmuku plugin and i18n setup documentation - Created a new JavaScript file for the danmuku plugin documentation with multiple code execution buttons. - Added a new JavaScript file for i18n (internationalization) setup documentation, including instructions for language settings, importing languages, and modifying language options. - Included examples for setting default languages and adding new languages in the i18n documentation. Refactor code structure for improved readability and maintainability
222 lines
265 KiB
JavaScript
222 lines
265 KiB
JavaScript
/*!
|
|
* artplayer-proxy-mediabunny.js v1.0.1
|
|
* Github: https://github.com/zhw2590582/ArtPlayer
|
|
* (c) 2017-2026 Harvey Zhao
|
|
* Released under the MIT License.
|
|
*/
|
|
!function(e,t){"object"===typeof exports&&"undefined"!==typeof module?module.exports=t():"function"==typeof define&&define.amd?(t.ArtplayerProxyMediabunny=t(),define(function(){return t.ArtplayerProxyMediabunny})):(e="undefined"!==typeof globalThis?globalThis:e||self).ArtplayerProxyMediabunny=t()}(this,function(){"use strict";var e=Object.defineProperty,t=Object.defineProperties,r=Object.getOwnPropertyDescriptors,i=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,r,i)=>r in t?e(t,r,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[r]=i,c=(e,t)=>{for(var r in t||(t={}))n.call(t,r)&&l(e,r,t[r]);if(i)for(var r of i(t))s.call(t,r)&&l(e,r,t[r]);return e},u=(e,t,r)=>new Promise((i,n)=>{var s=e=>{try{o(r.next(e))}catch(t){n(t)}},a=e=>{try{o(r.throw(e))}catch(t){n(t)}},o=e=>e.done?i(e.value):Promise.resolve(e.value).then(s,a);o((r=r.apply(e,t)).next())}),d=function(e,t){this[0]=e,this[1]=t},h=e=>{var t,r=e[a("asyncIterator")],i=!1,n={};return null==r?(r=e[a("iterator")](),t=e=>n[e]=t=>r[e](t)):(r=r.call(e),t=e=>n[e]=t=>{if(i){if(i=!1,"throw"===e)throw t;return t}return i=!0,{done:!1,value:new d(new Promise(i=>{var n=r[e](t);n instanceof Object||(e=>{throw TypeError(e)})("Object expected"),i(n)}),1)}}),n[a("iterator")]=()=>n,t("next"),"throw"in r?t("throw"):n.throw=e=>{throw e},"return"in r&&t("return"),n},m=(e,t,r)=>(t=e[a("asyncIterator")])?t.call(e):(e=e[a("iterator")](),t={},(r=(r,i)=>(i=e[r])&&(t[r]=t=>new Promise((r,n,s)=>(t=i.call(e,t),s=t.done,Promise.resolve(t.value).then(e=>r({value:e,done:s}),n)))))("next"),r("return"),t);class f{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 r=this.listeners.get(e);if(!r)return;const i=r.indexOf(t);i>=0&&r.splice(i,1)}emit(e,t){const r=new Event(e);r.detail=t;const i=this.listeners.get(e);i&&i.forEach(e=>e(r))}}
|
|
/*!
|
|
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
*
|
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
*/function p(e){if(!e)throw new Error("Assertion failed.")}const g=e=>{const t=(e%360+360)%360;if(0===t||90===t||180===t||270===t)return t;throw new Error(`Invalid rotation ${e}.`)},k=e=>e&&e[e.length-1];class b{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){var e;const t=Math.floor(this.pos/8),r=null!=(e=this.bytes[t])?e:0,i=7-(7&this.pos),n=(r&1<<i)>>i;return this.pos++,n}readBits(e){if(1===e)return this.readBit();let t=0;for(let r=0;r<e;r++)t<<=1,t|=this.readBit();return t}writeBits(e,t){const r=this.pos+e;for(let i=this.pos;i<r;i++){const e=Math.floor(i/8);let n=this.bytes[e];const s=7-(7&i);n&=~(1<<s),n|=(t&1<<r-i-1)>>r-i-1<<s,this.bytes[e]=n}this.pos=r}readAlignedByte(){var e;if(this.pos%8!==0)throw new Error("Bitstream is not byte-aligned.");const t=this.pos/8,r=null!=(e=this.bytes[t])?e:0;return this.pos+=8,r}skipBits(e){this.pos+=e}getBitsLeft(){return 8*this.bytes.length-this.pos}clone(){const e=new b(this.bytes);return e.pos=this.pos,e}}const y=e=>{let t=0;for(;0===e.readBits(1)&&t<32;)t++;if(t>=32)throw new Error("Invalid exponential-Golomb code.");return(1<<t)-1+e.readBits(t)},T=e=>{const t=y(e);return 0===(1&t)?-(t>>1):t+1>>1},S=e=>e.constructor===Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),v=e=>e.constructor===DataView?e:ArrayBuffer.isView(e)?new DataView(e.buffer,e.byteOffset,e.byteLength):new DataView(e),w=new TextDecoder,I=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])),P={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},x=I(P),C={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},_=I(C),B={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},E=I(B),F=e=>e instanceof ArrayBuffer||"undefined"!==typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e);class D{constructor(){this.currentPromise=Promise.resolve()}acquire(){return u(this,null,function*(){let e;const t=new Promise(t=>{e=t}),r=this.currentPromise;return this.currentPromise=t,yield r,e})}}const A=e=>[...e].map(e=>e.toString(16).padStart(2,"0")).join(""),R=e=>(e=(e=(e=(e=(e=e>>1&1431655765|(1431655765&e)<<1)>>2&858993459|(858993459&e)<<2)>>4&252645135|(252645135&e)<<4)>>8&16711935|(16711935&e)<<8)>>16&65535|(65535&e)<<16)>>>0,M=(e,t,r)=>{let i=0,n=e.length-1,s=-1;for(;i<=n;){const a=i+n>>1,o=r(e[a]);o===t?(s=a,n=a-1):o<t?i=a+1:n=a-1}return s},N=(e,t,r)=>{let i=0,n=e.length-1,s=-1;for(;i<=n;){const a=i+(n-i+1)/2|0;r(e[a])<=t?(s=a,i=a+1):n=a-1}return s},z=(e,t,r)=>{const i=N(e,r(t),r);e.splice(i+1,0,t)},O=()=>{let e,t;return{promise:new Promise((r,i)=>{e=r,t=i}),resolve:e,reject:t}},L=(e,t)=>{for(let r=e.length-1;r>=0;r--)if(t(e[r]))return e[r]},U=(e,t)=>{for(let r=e.length-1;r>=0;r--)if(t(e[r]))return r;return-1},V=function(e){return((e,t,r)=>{var i=(e,t,n,s)=>{try{var a=r[e](t),o=(t=a.value)instanceof d,l=a.done;Promise.resolve(o?t[0]:t).then(r=>o?i("return"===e?e:"next",t[1]?{done:r.done,value:r.value}:r,n,s):n({value:r,done:l})).catch(e=>i("throw",e,n,s))}catch(c){s(c)}},n=e=>s[e]=t=>new Promise((r,n)=>i(e,t,r,n)),s={};return r=r.apply(e,t),s[a("asyncIterator")]=()=>s,n("next"),n("throw"),n("return"),s})(this,null,function*(){Symbol.iterator in e?yield*h(e[Symbol.iterator]()):yield*h(e[Symbol.asyncIterator]())})},q=e=>{throw new Error(`Unexpected value: ${e}`)},H=(e,t,r)=>{const i=e.getUint8(t),n=e.getUint8(t+1),s=e.getUint8(t+2);return r?i|n<<8|s<<16:i<<16|n<<8|s},W=(e,t,r,i)=>{r>>>=0,r&=16777215,e.setUint8(t,r>>>16&255),e.setUint8(t+1,r>>>8&255),e.setUint8(t+2,255&r)},j=(e,t)=>({next(){return u(this,null,function*(){const r=yield e.next();return r.done?{value:void 0,done:!0}:{value:t(r.value),done:!1}})},return:()=>e.return(),throw:t=>e.throw(t),[Symbol.asyncIterator](){return this}}),K=(e,t,r)=>Math.max(t,Math.min(r,e)),$="und",Q=e=>{const t=Math.round(e);return Math.abs(e/t-1)<10*Number.EPSILON?t:e},G=/^[a-z]{3}$/,X=e=>G.test(e),Y=1e6*(1+Number.EPSILON),J=(e,t)=>{const r=c(c({},e),t);if(e.headers||t.headers){const i=e.headers?Z(e.headers):{},n=t.headers?Z(t.headers):{},s=c({},i);Object.entries(n).forEach(([e,t])=>{const r=Object.keys(s).find(t=>t.toLowerCase()===e.toLowerCase());r&&delete s[r],s[e]=t}),r.headers=s}return r},Z=e=>{if(e instanceof Headers){const t={};return e.forEach((e,r)=>{t[r]=e}),t}if(Array.isArray(e)){const t={};return e.forEach(([e,r])=>{t[e]=r}),t}return e},ee=(e,t,r,i,n)=>u(null,null,function*(){let s=0;for(;;)try{return yield e(t,r)}catch(a){if(n())throw a;s++;const e=i(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 new Promise(t=>setTimeout(t,1e3*e))),n())throw a}});class te{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}let re=null;const ie=()=>{var e;return null!==re?re:re=!("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 ne=null;const se=()=>{var e;return null!==ne?ne:ne="undefined"!==typeof navigator&&(null==(e=navigator.userAgent)?void 0:e.includes("Firefox"))};let ae=null;const oe=()=>{var e;return null!==ae?ae:ae=!("undefined"===typeof navigator||!(null==(e=navigator.vendor)?void 0:e.includes("Google Inc"))&&!/Chrome/.test(navigator.userAgent))};let le=null;const ce=(e,t)=>-1!==e?e:t,ue=(e,t,r,i)=>e<=i&&r<=t,de=e=>{const t=atob(e),r=new Uint8Array(t.length);for(let i=0;i<t.length;i++)r[i]=t.charCodeAt(i);return r},he=()=>{null!=Symbol.dispose||(Symbol.dispose=Symbol("Symbol.dispose"))},me=e=>"number"===typeof e&&!Number.isNaN(e);
|
|
/*!
|
|
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
*
|
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
*/
|
|
class fe{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 pe{constructor(e,t,r,i){if(this.data=e,this.mimeType=t,this.name=r,this.description=i,!(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!==r&&"string"!==typeof r)throw new TypeError("name, when provided, must be a string.");if(void 0!==i&&"string"!==typeof i)throw new TypeError("description, when provided, must be a string.")}}const ge={default:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1},ke=["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"],be=[{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}],ye=".01.01.01.01.00",Te=".0.110.01.01.01.0",Se=e=>{const{codec:t,codecDescription:r,colorSpace:i,avcCodecInfo:n,hevcCodecInfo:s,vp9CodecInfo:a,av1CodecInfo:o}=e;if("avc"===t){if(p(null!==e.avcType),n){const t=new Uint8Array([n.avcProfileIndication,n.profileCompatibility,n.avcLevelIndication]);return`avc${e.avcType}.${A(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}.${A(r.subarray(1,4))}`}if("hevc"===t){let e,t,i,n,a,o;if(s)e=s.generalProfileSpace,t=s.generalProfileIdc,i=R(s.generalProfileCompatibilityFlags),n=s.generalTierFlag,a=s.generalLevelIdc,o=[...s.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 s=v(r),l=s.getUint8(1);e=l>>6&3,t=31&l,i=R(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+=i.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 r=k(be).level;for(const e of be)if(t<=e.maxPictureSize){r=e.level;break}return`vp09.00.${r.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(ye)&&(t=t.slice(0,-15)),t}if("av1"===t){if(!o){const t=e.width*e.height;let r=k(be).level;for(const e of be)if(t<=e.maxPictureSize){r=e.level;break}return`av01.0.${r.toString().padStart(2,"0")}M.08`}const t=o.profile,r=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==i?void 0:i.primaries)?P[i.primaries]:1,u=(null==i?void 0:i.transfer)?C[i.transfer]:1,d=(null==i?void 0:i.matrix)?B[i.matrix]:1,h=(null==i?void 0:i.fullRange)?1:0;let m=`av01.${t}.${r}${n}.${s}`;return m+=`.${a}.${l.toString().padStart(3,"0")}`,m+=`.${c.toString().padStart(2,"0")}`,m+=`.${u.toString().padStart(2,"0")}`,m+=`.${d.toString().padStart(2,"0")}`,m+=`.${h}`,m.endsWith(Te)&&(m=m.slice(0,-17)),m}throw new TypeError(`Unhandled codec '${t}'.`)},ve=e=>{const{codec:t,codecDescription:r,aacCodecInfo:i}=e;if("aac"===t){if(!i)throw new TypeError("AAC codec info must be provided.");if(i.isMpeg2)return"mp4a.67";return`mp4a.40.${Pe(r).objectType}`}if("mp3"===t)return"mp3";if("opus"===t)return"opus";if("vorbis"===t)return"vorbis";if("flac"===t)return"flac";if(t&&ke.includes(t))return t;throw new TypeError(`Unhandled codec '${t}'.`)},we=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],Ie=[-1,1,2,3,4,5,6,8],Pe=e=>{if(!e||e.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");const t=new b(e);let r=t.readBits(5);31===r&&(r=32+t.readBits(6));const i=t.readBits(4);let n=null;15===i?n=t.readBits(24):i<we.length&&(n=we[i]);const s=t.readBits(4);let a=null;return s>=1&&s<=7&&(a=Ie[s]),{objectType:r,frequencyIndex:i,sampleRate:n,channelConfiguration:s,numberOfChannels:a}},xe=48e3,Ce=/^pcm-([usf])(\d+)+(be)?$/,_e=e=>{if(p(ke.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;p(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?o(2,7):0}};
|
|
/*!
|
|
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
*
|
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
*/
|
|
/*!
|
|
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
*
|
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
*/
|
|
var Be,Ee,Fe,De;(Ee=Be||(Be={}))[Ee.IDR=5]="IDR",Ee[Ee.SEI=6]="SEI",Ee[Ee.SPS=7]="SPS",Ee[Ee.PPS=8]="PPS",Ee[Ee.SPS_EXT=13]="SPS_EXT",(De=Fe||(Fe={}))[De.RASL_N=8]="RASL_N",De[De.RASL_R=9]="RASL_R",De[De.BLA_W_LP=16]="BLA_W_LP",De[De.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",De[De.VPS_NUT=32]="VPS_NUT",De[De.SPS_NUT=33]="SPS_NUT",De[De.PPS_NUT=34]="PPS_NUT",De[De.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",De[De.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT";const Ae=e=>{const t=[];let r=0;for(;r<e.length;){let i=-1,n=0;for(let t=r;t<e.length-3;t++){if(0===e[t]&&0===e[t+1]&&1===e[t+2]){i=t,n=3;break}if(t<e.length-4&&0===e[t]&&0===e[t+1]&&0===e[t+2]&&1===e[t+3]){i=t,n=4;break}}if(-1===i)break;if(r>0&&i>r){const n=e.subarray(r,i);n.length>0&&t.push(n)}r=i+n}if(r<e.length){const i=e.subarray(r);i.length>0&&t.push(i)}return t},Re=(e,t)=>{const r=[];let i=0;const n=new DataView(e.buffer,e.byteOffset,e.byteLength);for(;i+t<=e.length;){let s;1===t?s=n.getUint8(i):2===t?s=n.getUint16(i,!1):3===t?s=H(n,i,!1):4===t?s=n.getUint32(i,!1):(q(t),p(!1)),i+=t;const a=e.subarray(i,i+s);r.push(a),i+=s}return r},Me=e=>{const t=[],r=e.length;for(let i=0;i<r;i++)i+2<r&&0===e[i]&&0===e[i+1]&&3===e[i+2]?(t.push(0,0),i+=2):t.push(e[i]);return new Uint8Array(t)},Ne=new Uint8Array([0,0,0,1]),ze=(e,t)=>{if(t.description){const r=3&S(t.description)[4];return Re(e,r+1)}return Ae(e)},Oe=(e,t)=>{if(t.description){return((e,t)=>{const r=e.reduce((e,r)=>e+t+r.byteLength,0),i=new Uint8Array(r);let n=0;for(const s of e){const e=new DataView(i.buffer,i.byteOffset,i.byteLength);switch(t){case 1:e.setUint8(n,s.byteLength);break;case 2:e.setUint16(n,s.byteLength,!1);break;case 3:W(e,n,s.byteLength);break;case 4:e.setUint32(n,s.byteLength,!1)}n+=t,i.set(s,n),n+=s.byteLength}return i})(e,(3&S(t.description)[4])+1)}return(e=>{const t=e.reduce((e,t)=>e+Ne.byteLength+t.byteLength,0),r=new Uint8Array(t);let i=0;for(const n of e)r.set(Ne,i),i+=Ne.byteLength,r.set(n,i),i+=n.byteLength;return r})(e)},Le=e=>31&e[0],Ue=e=>{try{const t=Ae(e),r=t.filter(e=>Le(e)===Be.SPS),i=t.filter(e=>Le(e)===Be.PPS),n=t.filter(e=>Le(e)===Be.SPS_EXT);if(0===r.length)return null;if(0===i.length)return null;const s=r[0],a=Ve(s);p(null!==a);const o=100===a.profileIdc||110===a.profileIdc||122===a.profileIdc||144===a.profileIdc;return{configurationVersion:1,avcProfileIndication:a.profileIdc,profileCompatibility:a.constraintFlags,avcLevelIndication:a.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:r,pictureParameterSets:i,chromaFormat:o?a.chromaFormatIdc:null,bitDepthLumaMinus8:o?a.bitDepthLumaMinus8:null,bitDepthChromaMinus8:o?a.bitDepthChromaMinus8:null,sequenceParameterSetExt:o?n:null}}catch(t){return console.error("Error building AVC Decoder Configuration Record:",t),null}},Ve=e=>{try{const t=new b(Me(e));t.skipBits(1),t.skipBits(2);if(7!==t.readBits(5))return null;const r=t.readAlignedByte(),i=t.readAlignedByte(),n=t.readAlignedByte();y(t);let s=null,a=null,o=null;if(100===r||110===r||122===r||244===r||44===r||83===r||86===r||118===r||128===r){s=y(t),3===s&&t.skipBits(1),a=y(t),o=y(t),t.skipBits(1);if(t.readBits(1))for(let e=0;e<(3!==s?8:12);e++){if(t.readBits(1)){const r=e<6?16:64;let i=8,n=8;for(let e=0;e<r;e++){if(0!==n){n=(i+T(t)+256)%256}i=0===n?i:n}}}}y(t);const l=y(t);if(0===l)y(t);else if(1===l){t.skipBits(1),T(t),T(t);const e=y(t);for(let r=0;r<e;r++)T(t)}y(t),t.skipBits(1),y(t),y(t);return{profileIdc:r,constraintFlags:i,levelIdc:n,frameMbsOnlyFlag:t.readBits(1),chromaFormatIdc:s,bitDepthLumaMinus8:a,bitDepthChromaMinus8:o}}catch(t){return console.error("Error parsing AVC SPS:",t),null}},qe=(e,t)=>{if(t.description){const r=3&S(t.description)[21];return Re(e,r+1)}return Ae(e)},He=e=>e[0]>>1&63,We=e=>{try{const t=Ae(e),r=t.filter(e=>He(e)===Fe.VPS_NUT),i=t.filter(e=>He(e)===Fe.SPS_NUT),n=t.filter(e=>He(e)===Fe.PPS_NUT),s=t.filter(e=>He(e)===Fe.PREFIX_SEI_NUT||He(e)===Fe.SUFFIX_SEI_NUT);if(0===i.length||0===n.length)return null;const a=i[0],o=new b(Me(a));o.skipBits(16),o.readBits(4);const l=o.readBits(3),c=o.readBits(1),{general_profile_space:u,general_tier_flag:d,general_profile_idc:h,general_profile_compatibility_flags:m,general_constraint_indicator_flags:f,general_level_idc:p}=je(o,l);y(o);const g=y(o);3===g&&o.skipBits(1),y(o),y(o),o.readBits(1)&&(y(o),y(o),y(o),y(o));const k=y(o),S=y(o);y(o);const v=o.readBits(1);for(let e=v?0:l;e<=l;e++)y(o),y(o),y(o);y(o),y(o),y(o),y(o),y(o),y(o),o.readBits(1)&&o.readBits(1)&&Ke(o),o.skipBits(1),o.skipBits(1),o.readBits(1)&&(o.skipBits(4),o.skipBits(4),y(o),y(o),o.skipBits(1));const w=y(o);if($e(o,w),o.readBits(1)){const e=y(o);for(let t=0;t<e;t++)y(o),o.skipBits(1)}o.skipBits(1),o.skipBits(1);let I=0;o.readBits(1)&&(I=Ge(o,l));let P=0;if(n.length>0){const e=n[0],t=new b(Me(e));t.skipBits(16),y(t),y(t),t.skipBits(1),t.skipBits(1),t.skipBits(3),t.skipBits(1),t.skipBits(1),y(t),y(t),T(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&y(t),T(t),T(t),t.skipBits(1),t.skipBits(1),t.skipBits(1),t.skipBits(1);const r=t.readBits(1),i=t.readBits(1);P=r||i?r&&!i?2:!r&&i?3:0:0}const x=[...r.length?[{arrayCompleteness:1,nalUnitType:Fe.VPS_NUT,nalUnits:r}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:Fe.SPS_NUT,nalUnits:i}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:Fe.PPS_NUT,nalUnits:n}]:[],...s.length?[{arrayCompleteness:1,nalUnitType:He(s[0]),nalUnits:s}]:[]];return{configurationVersion:1,generalProfileSpace:u,generalTierFlag:d,generalProfileIdc:h,generalProfileCompatibilityFlags:m,generalConstraintIndicatorFlags:f,generalLevelIdc:p,minSpatialSegmentationIdc:I,parallelismType:P,chromaFormatIdc:g,bitDepthLumaMinus8:k,bitDepthChromaMinus8:S,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:l+1,temporalIdNested:c,lengthSizeMinusOne:3,arrays:x}}catch(t){return console.error("Error building HEVC Decoder Configuration Record:",t),null}},je=(e,t)=>{const r=e.readBits(2),i=e.readBits(1),n=e.readBits(5);let s=0;for(let u=0;u<32;u++)s=s<<1|e.readBits(1);const a=new Uint8Array(6);for(let u=0;u<6;u++)a[u]=e.readBits(8);const o=e.readBits(8),l=[],c=[];for(let u=0;u<t;u++)l.push(e.readBits(1)),c.push(e.readBits(1));if(t>0)for(let u=t;u<8;u++)e.skipBits(2);for(let u=0;u<t;u++)l[u]&&e.skipBits(88),c[u]&&e.skipBits(8);return{general_profile_space:r,general_tier_flag:i,general_profile_idc:n,general_profile_compatibility_flags:s,general_constraint_indicator_flags:a,general_level_idc:o}},Ke=e=>{for(let t=0;t<4;t++)for(let r=0;r<(3===t?2:6);r++){if(e.readBits(1)){const r=Math.min(64,1<<4+(t<<1));t>1&&T(e);for(let t=0;t<r;t++)T(e)}else y(e)}},$e=(e,t)=>{const r=[];for(let i=0;i<t;i++)r[i]=Qe(e,i,t,r)},Qe=(e,t,r,i)=>{var n;let s=0,a=0,o=0;if(0!==t&&(a=e.readBits(1)),a){if(t===r){o=t-(y(e)+1)}else o=t-1;e.readBits(1),y(e);const a=null!=(n=i[o])?n:0;for(let t=0;t<=a;t++){e.readBits(1)||e.readBits(1)}s=i[o]}else{const t=y(e),r=y(e);for(let i=0;i<t;i++)y(e),e.readBits(1);for(let i=0;i<r;i++)y(e),e.readBits(1);s=t+r}return s},Ge=(e,t)=>{if(e.readBits(1)){255===e.readBits(8)&&(e.readBits(16),e.readBits(16))}if(e.readBits(1)&&e.readBits(1),e.readBits(1)&&(e.readBits(3),e.readBits(1),e.readBits(1)&&(e.readBits(8),e.readBits(8),e.readBits(8))),e.readBits(1)&&(y(e),y(e)),e.readBits(1),e.readBits(1),e.readBits(1),e.readBits(1)&&(y(e),y(e),y(e),y(e)),e.readBits(1)&&(e.readBits(32),e.readBits(32),e.readBits(1)&&y(e),e.readBits(1)&&Xe(e,!0,t)),e.readBits(1)){e.readBits(1),e.readBits(1),e.readBits(1);const t=y(e);return y(e),y(e),y(e),y(e),t}return 0},Xe=(e,t,r)=>{let i=!1,n=!1,s=!1;i=1===e.readBits(1),n=1===e.readBits(1),(i||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<=r;a++){let t=!0;1===e.readBits(1)||(t=1===e.readBits(1));let r=!1;t?y(e):r=1===e.readBits(1);let a=1;if(!r){a=y(e)+1}i&&Ye(e,a,s),n&&Ye(e,a,s)}},Ye=(e,t,r)=>{for(let i=0;i<t;i++)y(e),y(e),r&&(y(e),y(e)),e.readBits(1)},Je=e=>{const t=new b(e);if(2!==t.readBits(2))return null;const r=t.readBits(1),i=(t.readBits(1)<<1)+r;3===i&&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(i>=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===i||3===i){const e=t.readBits(1),r=t.readBits(1);a=e||r?e&&!r?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=k(be).level;for(const u of be)if(l<=u.maxPictureSize){c=u.level;break}return{profile:i,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}},Ze=function*(e){const t=new b(e),r=()=>{let e=0;for(let r=0;r<8;r++){const i=t.readAlignedByte();if(e|=(127&i)<<7*r,!(128&i))break;if(7===r&&128&i)return null}return e>=o(2,32)-1?null:e};for(;t.getBitsLeft()>=8;){t.skipBits(1);const i=t.readBits(4),n=t.readBits(1),s=t.readBits(1);let a;if(t.skipBits(1),n&&t.skipBits(8),s){const e=r();if(null===e)return;a=e}else a=Math.floor(t.getBitsLeft()/8);p(t.pos%8===0),yield{type:i,data:e.subarray(t.pos/8,t.pos/8+a)},t.skipBits(8*a)}},et=e=>{for(const{type:t,data:r}of Ze(e)){if(1!==t)continue;const e=new b(r),i=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 r=e.readBits(5);for(let i=0;i<=r;i++){e.skipBits(12);const r=e.readBits(5);if(0===i&&(s=r),r>7){const t=e.readBits(1);0===i&&(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 r=0;if(r=e.readBits(1)?2:e.readBits(1),r>0){e.readBits(1)||e.skipBits(1)}t&&e.skipBits(3)}e.skipBits(1),e.skipBits(1),e.skipBits(1);const m=e.readBits(1);let f=8;if(2===i&&m){f=e.readBits(1)?12:10}else i<=2&&(f=m?10:8);let p=0;1!==i&&(p=e.readBits(1));let g=1,k=1,y=0;return p||(0===i?(g=1,k=1):1===i?(g=0,k=0):12===f&&(g=e.readBits(1),g&&(k=e.readBits(1))),g&&k&&(y=e.readBits(2))),{profile:i,level:s,tier:a,bitDepth:f,monochrome:p,chromaSubsamplingX:g,chromaSubsamplingY:k,chromaSamplePosition:y}}return null},tt=[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],rt=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,r=new Uint8Array(t);for(let u=0;u<t;u++)r[u]=e[t-1-u];const i=new b(r);let n=0;for(;i.getBitsLeft()>97;)if(1===i.readBits(1)){n=i.pos;break}if(0===n)throw new Error("Invalid Setup header: framing bit not found.");let s=0,a=!1,o=0;for(;i.getBitsLeft()>=97;){const e=i.pos,t=i.readBits(8),r=i.readBits(16),n=i.readBits(16);if(t>63||0!==r||0!==n){i.pos=e;break}if(i.skipBits(1),s++,s>64)break;i.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;i.pos=0,i.skipBits(n);const c=Array(l).fill(0);for(let u=l-1;u>=0;u--)i.skipBits(40),c[u]=i.readBits(1);return{modeBlockflags:c}},it=(e,t,r)=>{switch(e){case"avc":{const e=ze(r,t);let i=e.some(e=>Le(e)===Be.IDR);if(!i&&(!oe()||(()=>{if(null!==le)return le;if("undefined"===typeof navigator)return null;const e=/\bChrome\/(\d+)/.exec(navigator.userAgent);return e?le=Number(e[1]):null})()>=144))for(const t of e){if(Le(t)!==Be.SEI)continue;const e=Me(t);let r=1;do{let t=0;for(;;){const i=e[r++];if(void 0===i)break;if(t+=i,i<255)break}let n=0;for(;;){const t=e[r++];if(void 0===t)break;if(n+=t,t<255)break}if(t===6){const t=new b(e);t.pos=8*r;const n=y(t),s=t.readBits(1);if(0===n&&1===s){i=!0;break}}r+=n}while(r<e.length-1)}return i?"key":"delta"}case"hevc":return qe(r,t).some(e=>{const t=He(e);return Fe.BLA_W_LP<=t&&t<=Fe.RSV_IRAP_VCL23})?"key":"delta";case"vp8":return 0===(1&r[0])?"key":"delta";case"vp9":{const e=new b(r);if(2!==e.readBits(2))return null;const t=e.readBits(1);3===(e.readBits(1)<<1)+t&&e.skipBits(1);if(e.readBits(1))return null;return 0===e.readBits(1)?"key":"delta"}case"av1":{let e=!1;for(const{type:t,data:i}of Ze(r))if(1===t){const t=new b(i);t.skipBits(4),e=!!t.readBits(1)}else if(3===t||6===t||7===t){if(e)return"key";const t=new b(i);if(t.readBits(1))return null;return 0===t.readBits(2)?"key":"delta"}return null}default:q(e),p(!1)}};var nt,st;(st=nt||(nt={}))[st.STREAMINFO=0]="STREAMINFO",st[st.VORBIS_COMMENT=4]="VORBIS_COMMENT",st[st.PICTURE=6]="PICTURE";const at=(e,t)=>{var r,i;const n=v(e);let s=0;const a=n.getUint32(s,!0);s+=4;const o=w.decode(e.subarray(s,s+a));s+=a,a>0&&(null!=t.raw||(t.raw={}),null!=(r=t.raw).vendor||(r.vendor=o));const l=n.getUint32(s,!0);s+=4;for(let c=0;c<l;c++){const r=n.getUint32(s,!0);s+=4;const a=w.decode(e.subarray(s,s+r));s+=r;const o=a.indexOf("=");if(-1===o)continue;const l=a.slice(0,o).toUpperCase(),c=a.slice(o+1);switch(null!=t.raw||(t.raw={}),null!=(i=t.raw)[l]||(i[l]=c),l){case"TITLE":null!=t.title||(t.title=c);break;case"DESCRIPTION":null!=t.description||(t.description=c);break;case"ARTIST":null!=t.artist||(t.artist=c);break;case"ALBUM":null!=t.album||(t.album=c);break;case"ALBUMARTIST":null!=t.albumArtist||(t.albumArtist=c);break;case"COMMENT":null!=t.comment||(t.comment=c);break;case"LYRICS":null!=t.lyrics||(t.lyrics=c);break;case"TRACKNUMBER":{const e=c.split("/"),r=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(r)&&r>0&&(null!=t.trackNumber||(t.trackNumber=r)),i&&Number.isInteger(i)&&i>0&&(null!=t.tracksTotal||(t.tracksTotal=i))}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("/"),r=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(r)&&r>0&&(null!=t.discNumber||(t.discNumber=r)),i&&Number.isInteger(i)&&i>0&&(null!=t.discsTotal||(t.discsTotal=i))}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=de(c),r=v(e),i=r.getUint32(0,!1),n=r.getUint32(4,!1),s=String.fromCharCode(...e.subarray(8,8+n)),a=r.getUint32(8+n,!1),o=w.decode(e.subarray(12+n,12+n+a)),l=r.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===i?"coverFront":4===i?"coverBack":"unknown",name:void 0,description:o||void 0})}}}};
|
|
/*!
|
|
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
*
|
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
*/class ot{constructor(e){this.input=e}}
|
|
/*!
|
|
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
*
|
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
*/const lt=[],ct=[],ut=new Uint8Array(0);class dt{constructor(e,t,r,i,n=-1,s,a){if(this.data=e,this.type=t,this.timestamp=r,this.duration=i,this.sequenceNumber=n,e===ut&&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(r))throw new TypeError("timestamp must be a number.");if(!Number.isFinite(i)||i<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===ut}get microsecondTimestamp(){return Math.trunc(Y*this.timestamp)}get microsecondDuration(){return Math.trunc(Y*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 r;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 dt(i,e.type,e.timestamp/1e6,(null!=(r=e.duration)?r:0)/1e6,void 0,void 0,t)}clone(e){var t,r;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.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.");return new dt(this.data,this.type,null!=(t=null==e?void 0:e.timestamp)?t:this.timestamp,null!=(r=null==e?void 0:e.duration)?r:this.duration,this.sequenceNumber,this.byteLength)}}
|
|
/*!
|
|
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
*
|
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
*/
|
|
/*!
|
|
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
*
|
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
*/
|
|
he();let ht=-1/0,mt=-1/0,ft=null;"undefined"!==typeof FinalizationRegistry&&(ft=new FinalizationRegistry(e=>{const t=Date.now();"video"===e.type?(t-ht>=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."),ht=t),"undefined"!==typeof VideoFrame&&e.data instanceof VideoFrame&&e.data.close()):(t-mt>=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."),mt=t),"undefined"!==typeof AudioData&&e.data instanceof AudioData&&e.data.close())}));const pt=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],gt=new Set(pt);class kt{get displayWidth(){return this.rotation%180===0?this.codedWidth:this.codedHeight}get displayHeight(){return this.rotation%180===0?this.codedHeight:this.codedWidth}get microsecondTimestamp(){return Math.trunc(Y*this.timestamp)}get microsecondDuration(){return Math.trunc(Y*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor(e,t){var r,i,n,s,a,o,l,c,u,d;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||!gt.has(t.format))throw new TypeError("init.format must be one of: "+pt.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.");this._data=S(e).slice(),this._layout=null!=(r=t.layout)?r:wt(t.format,t.codedWidth,t.codedHeight),this.format=t.format,this.codedWidth=t.codedWidth,this.codedHeight=t.codedHeight,this.rotation=null!=(i=t.rotation)?i:0,this.timestamp=t.timestamp,this.duration=null!=(n=t.duration)?n:0,this.colorSpace=new bt(t.colorSpace)}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.");this._data=e,this._layout=null,this.format=e.format,this.codedWidth=e.displayWidth,this.codedHeight=e.displayHeight,this.rotation=null!=(s=null==t?void 0:t.rotation)?s:0,this.timestamp=null!=(a=null==t?void 0:t.timestamp)?a:e.timestamp/1e6,this.duration=null!=(l=null==t?void 0:t.duration)?l:(null!=(o=e.duration)?o:0)/1e6,this.colorSpace=new bt(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 kt(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*Y),duration:Math.trunc((null!=(c=t.duration)?c:0)*Y)||void 0}),t);let r=0,i=0;if("naturalWidth"in e?(r=e.naturalWidth,i=e.naturalHeight):"videoWidth"in e?(r=e.videoWidth,i=e.videoHeight):"width"in e&&(r=Number(e.width),i=Number(e.height)),!r||!i)throw new TypeError("Could not determine dimensions.");const n=new OffscreenCanvas(r,i),s=n.getContext("2d",{alpha:se(),willReadFrequently:!0});p(s),s.drawImage(e,0,0),this._data=n,this._layout=null,this.format="RGBX",this.codedWidth=r,this.codedHeight=i,this.rotation=null!=(u=t.rotation)?u:0,this.timestamp=t.timestamp,this.duration=null!=(d=t.duration)?d:0,this.colorSpace=new bt({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}}null==ft||ft.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return p(null!==this._data),yt(this._data)?new kt(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation}):this._data instanceof Uint8Array?(p(this._layout),new kt(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})):new kt(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation})}close(){this._closed||(null==ft||ft.unregister(this),yt(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(vt(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(p(null!==this._data),!yt(this._data)&&(e.colorSpace||e.format&&e.format!==this.format||e.layout||e.rect)){const t=this.toVideoFrame(),r=t.allocationSize(e);return t.close(),r}return yt(this._data)?this._data.allocationSize(e):this._data instanceof Uint8Array?this._data.byteLength:this.codedWidth*this.codedHeight*4}copyTo(e){return u(this,arguments,function*(e,t={}){if(!F(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(vt(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(p(null!==this._data),!yt(this._data)&&(t.colorSpace||t.format&&t.format!==this.format||t.layout||t.rect)){const r=this.toVideoFrame(),i=yield r.copyTo(e,t);return r.close(),i}if(yt(this._data))return this._data.copyTo(e,t);if(this._data instanceof Uint8Array){p(this._layout);return S(e).set(this._data),this._layout}{const t=this._data.getContext("2d");p(t);const r=t.getImageData(0,0,this.codedWidth,this.codedHeight);return S(e).set(r.data),[{offset:0,stride:4*this.codedWidth}]}})}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");return p(null!==this._data),yt(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,r,i,n,s,a,o,l){let c=0,u=0,d=this.displayWidth,h=this.displayHeight,m=0,f=0,p=this.displayWidth,g=this.displayHeight;if(void 0!==s?(c=t,u=r,d=i,h=n,m=s,f=a,void 0!==o?(p=o,g=l):(p=d,g=h)):(m=t,f=r,void 0!==i&&(p=i,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(m))throw new TypeError("dx must be a number.");if(!Number.isFinite(f))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 b=m+p/2,y=f+g/2;e.translate(b,y),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 r,i,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&&St(t.crop,"options.");const d=e.canvas.width,h=e.canvas.height,m=null!=(r=t.rotation)?r:this.rotation,[f,p]=m%180===0?[this.codedWidth,this.codedHeight]:[this.codedHeight,this.codedWidth];let g,k,b,y;t.crop&&Tt(t.crop,f,p);const{sx:T,sy:S,sWidth:v,sHeight:w}=this._rotateSourceRegion(null!=(n=null==(i=t.crop)?void 0:i.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:f,null!=(u=null==(c=t.crop)?void 0:c.height)?u:p,m);if("fill"===t.fit)g=0,k=0,b=d,y=h;else{const[e,r]=t.crop?[t.crop.width,t.crop.height]:[f,p],i="contain"===t.fit?Math.min(d/e,h/r):Math.max(d/e,h/r);b=e*i,y=r*i,g=(d-b)/2,k=(h-y)/2}e.save();const I=m%180===0?1:b/y;e.translate(d/2,h/2),e.rotate(m*Math.PI/180),e.scale(1/I,I),e.translate(-d/2,-h/2),e.drawImage(this.toCanvasImageSource(),T,S,v,w,g,k,b,y),e.restore()}_rotateSourceRegion(e,t,r,i,n){return 90===n?[e,t,r,i]=[t,this.codedHeight-e-r,i,r]:180===n?[e,t]=[this.codedWidth-e-r,this.codedHeight-t-i]:270===n&&([e,t,r,i]=[this.codedWidth-t-i,e,i,r]),{sx:e,sy:t,sWidth:r,sHeight:i}}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(p(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 bt{constructor(e){var t,r,i,n;this.primaries=null!=(t=null==e?void 0:e.primaries)?t:null,this.transfer=null!=(r=null==e?void 0:e.transfer)?r:null,this.matrix=null!=(i=null==e?void 0:e.matrix)?i: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 yt=e=>"undefined"!==typeof VideoFrame&&e instanceof VideoFrame,Tt=(e,t,r)=>{e.left=Math.min(e.left,t),e.top=Math.min(e.top,r),e.width=Math.min(e.width,t-e.left),e.height=Math.min(e.height,r-e.top),p(e.width>=0),p(e.height>=0)},St=(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.")},vt=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.")}},wt=(e,t,r)=>{const i=It(e),n=[];let s=0;for(const a of i){const e=Math.ceil(t/a.widthDivisor),i=Math.ceil(r/a.heightDivisor),o=e*a.sampleBytes,l=o*i;n.push({offset:s,stride:o}),s+=l}return n},It=e=>{const t=(e,t,r,i,n)=>{const s=[{sampleBytes:e,widthDivisor:1,heightDivisor:1},{sampleBytes:t,widthDivisor:r,heightDivisor:i},{sampleBytes:t,widthDivisor:r,heightDivisor:i}];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:q(e),p(!1)}},Pt=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]);class xt{get microsecondTimestamp(){return Math.trunc(Y*this.timestamp)}get microsecondDuration(){return Math.trunc(Y*this.duration)}constructor(e){if(this._closed=!1,Ft(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(!Pt.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/(Ct(e.format)*e.numberOfChannels);if(!Number.isInteger(t))throw new TypeError("Invalid AudioDataInit: data size is not a multiple of frame size.");let r;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)r=new Uint8Array(e.data);else{if(!ArrayBuffer.isView(e.data))throw new TypeError("Invalid AudioDataInit: data is not a BufferSource.");r=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength)}const i=this.numberOfFrames*this.numberOfChannels*Ct(this.format);if(r.byteLength<i)throw new TypeError("Invalid AudioDataInit: insufficient data size.");this._data=r}null==ft||ft.register(this,{type:"audio",data:this._data},this)}allocationSize(e){var t,r;if(!e||"object"!==typeof e)throw new TypeError("options must be an object.");if(!Number.isInteger(e.planeIndex)||e.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(void 0!==e.format&&!Pt.has(e.format))throw new TypeError("Invalid format.");if(void 0!==e.frameOffset&&(!Number.isInteger(e.frameOffset)||e.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(void 0!==e.frameCount&&(!Number.isInteger(e.frameCount)||e.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");const i=null!=(t=e.format)?t:this.format,n=null!=(r=e.frameOffset)?r:0;if(n>=this.numberOfFrames)throw new RangeError("frameOffset out of range");const s=void 0!==e.frameCount?e.frameCount:this.numberOfFrames-n;if(s>this.numberOfFrames-n)throw new RangeError("frameCount out of range");const a=Ct(i),o=_t(i);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(!F(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&&!Pt.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:r,format:i,frameCount:n,frameOffset:s}=t,a=this.format,o=null!=i?i: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=Ct(o),m=_t(o);if(m&&r>=c)throw new RangeError("planeIndex out of range");if(!m&&0!==r)throw new RangeError("planeIndex out of range");const f=(m?d:d*c)*h;if(e.byteLength<f)throw new RangeError("Destination buffer is too small");const p=v(e),g=Et(o);if(Ft(this._data))ie()&&c>2&&o!==a?Dt(this._data,p,a,o,c,r,u,d):this._data.copyTo(e,{planeIndex:r,frameOffset:u,frameCount:d,format:o});else{const e=this._data,t=v(e),i=Bt(a),n=Ct(a),s=_t(a);for(let a=0;a<d;a++)if(m){let e;e=s?(r*l+(a+u))*n:((a+u)*c+r)*n;g(p,a*h,i(t,e))}else for(let e=0;e<c;e++){let r;r=s?(e*l+(a+u))*n:((a+u)*c+e)*n;g(p,(a*c+e)*h,i(t,r))}}}clone(){if(this._closed)throw new Error("AudioSample is closed.");if(Ft(this._data)){const e=new xt(this._data.clone());return e.setTimestamp(this.timestamp),e}return new xt({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data})}close(){this._closed||(null==ft||ft.unregister(this),Ft(this._data)?this._data.close():this._data=new Uint8Array(0),this._closed=!0)}toAudioData(){if(this._closed)throw new Error("AudioSample is closed.");if(Ft(this._data)){if(this._data.timestamp===this.microsecondTimestamp)return this._data.clone();if(_t(this.format)){const e=this.allocationSize({planeIndex:0,format:this.format}),t=new ArrayBuffer(e*this.numberOfChannels);for(let r=0;r<this.numberOfChannels;r++)this.copyTo(new Uint8Array(t,r*e,e),{planeIndex:r,format:this.format});return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:t})}{const e=new ArrayBuffer(this.allocationSize({planeIndex:0,format:this.format}));return this.copyTo(e,{planeIndex:0,format:this.format}),new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:e})}}return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:this._data.buffer instanceof ArrayBuffer?this._data.buffer:this._data.slice()})}toAudioBuffer(){if(this._closed)throw new Error("AudioSample is closed.");const e=new AudioBuffer({numberOfChannels:this.numberOfChannels,length:this.numberOfFrames,sampleRate:this.sampleRate}),t=new Float32Array(this.allocationSize({planeIndex:0,format:"f32-planar"})/4);for(let r=0;r<this.numberOfChannels;r++)this.copyTo(t,{planeIndex:r,format:"f32-planar"}),e.copyToChannel(t,r);return e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}[Symbol.dispose](){this.close()}static*_fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");const r=e.numberOfChannels,i=e.sampleRate,n=e.length,s=Math.floor(24e4/r);let a=0,o=n;for(;o>0;){const n=Math.min(s,o),l=new Float32Array(r*n);for(let t=0;t<r;t++)e.copyFromChannel(l.subarray(t*n,(t+1)*n),t,a);yield new xt({format:"f32-planar",sampleRate:i,numberOfFrames:n,numberOfChannels:r,timestamp:t+a/i,data:l}),a+=n,o-=n}}static fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");const r=e.numberOfChannels,i=e.sampleRate,n=e.length,s=Math.floor(24e4/r);let a=0,o=n;const l=[];for(;o>0;){const n=Math.min(s,o),c=new Float32Array(r*n);for(let t=0;t<r;t++)e.copyFromChannel(c.subarray(t*n,(t+1)*n),t,a);const u=new xt({format:"f32-planar",sampleRate:i,numberOfFrames:n,numberOfChannels:r,timestamp:t+a/i,data:c});l.push(u),a+=n,o-=n}return l}}const Ct=e=>{switch(e){case"u8":case"u8-planar":return 1;case"s16":case"s16-planar":return 2;case"s32":case"s32-planar":case"f32":case"f32-planar":return 4;default:throw new Error("Unknown AudioSampleFormat")}},_t=e=>{switch(e){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},Bt=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)}},Et=e=>{switch(e){case"u8":case"u8-planar":return(e,t,r)=>e.setUint8(t,K(127.5*(r+1),0,255));case"s16":case"s16-planar":return(e,t,r)=>e.setInt16(t,K(Math.round(32767*r),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,r)=>e.setInt32(t,K(Math.round(2147483647*r),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,r)=>e.setFloat32(t,r,!0)}},Ft=e=>"undefined"!==typeof AudioData&&e instanceof AudioData,Dt=(e,t,r,i,n,s,a,o)=>{const l=Bt(r),c=Et(i),u=Ct(r),d=Ct(i),h=_t(r);if(_t(i))if(h){const i=new ArrayBuffer(o*u),n=v(i);e.copyTo(i,{planeIndex:s,frameOffset:a,frameCount:o,format:r});for(let e=0;e<o;e++){c(t,e*d,l(n,e*u))}}else{const i=new ArrayBuffer(o*n*u),h=v(i);e.copyTo(i,{planeIndex:0,frameOffset:a,frameCount:o,format:r});for(let e=0;e<o;e++){c(t,e*d,l(h,(e*n+s)*u))}}else if(h){const i=new ArrayBuffer(o*u),s=v(i);for(let h=0;h<n;h++){e.copyTo(i,{planeIndex:h,frameOffset:a,frameCount:o,format:r});for(let e=0;e<o;e++){c(t,(e*n+h)*d,l(s,e*u))}}}else{const i=new ArrayBuffer(o*n*u),s=v(i);e.copyTo(i,{planeIndex:0,frameOffset:a,frameCount:o,format:r});for(let e=0;e<o;e++)for(let r=0;r<n;r++){const i=e*n+r;c(t,i*d,l(s,i*u))}}},At=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.")},Rt=e=>{if(!me(e))throw new TypeError("timestamp must be a number.")},Mt=(e,t,r)=>r.verifyKeyPackets?t.then(t=>u(null,null,function*(){if(!t||"delta"===t.type)return t;const r=yield e.determinePacketType(t);return r&&(t.type=r),t})):t;class Nt{constructor(e){if(!(e instanceof Qt))throw new TypeError("track must be an InputTrack.");this._track=e}getFirstPacket(e={}){if(At(e),this._track.input._disposed)throw new gn;return Mt(this._track,this._track._backing.getFirstPacket(e),e)}getPacket(e,t={}){if(Rt(e),At(t),this._track.input._disposed)throw new gn;return Mt(this._track,this._track._backing.getPacket(e,t),t)}getNextPacket(e,t={}){if(!(e instanceof dt))throw new TypeError("packet must be an EncodedPacket.");if(At(t),this._track.input._disposed)throw new gn;return Mt(this._track,this._track._backing.getNextPacket(e,t),t)}getKeyPacket(e){return u(this,arguments,function*(e,t={}){if(Rt(e),At(t),this._track.input._disposed)throw new gn;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);const r=yield this._track._backing.getKeyPacket(e,t);if(!r)return r;p("key"===r.type);return"delta"===(yield this._track.determinePacketType(r))?this.getKeyPacket(r.timestamp-1/this._track.timeResolution,t):r})}getNextKeyPacket(e){return u(this,arguments,function*(e,t={}){if(!(e instanceof dt))throw new TypeError("packet must be an EncodedPacket.");if(At(t),this._track.input._disposed)throw new gn;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);const r=yield this._track._backing.getNextKeyPacket(e,t);if(!r)return r;p("key"===r.type);return"delta"===(yield this._track.determinePacketType(r))?this.getNextKeyPacket(r,t):r})}packets(e,t,r={}){if(void 0!==e&&!(e instanceof dt))throw new TypeError("startPacket must be an EncodedPacket.");if(void 0!==e&&e.isMetadataOnly&&!(null==r?void 0:r.metadataOnly))throw new TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(void 0!==t&&!(t instanceof dt))throw new TypeError("endPacket must be an EncodedPacket.");if(At(r),this._track.input._disposed)throw new gn;const i=[];let{promise:n,resolve:s}=O(),{promise:a,resolve:o}=O(),l=!1,c=!1,d=null;const h=[],m=()=>Math.max(2,h.length);(()=>u(this,null,function*(){let u=null!=e?e:yield this.getFirstPacket(r);for(;u&&!c&&!this._track.input._disposed&&!(t&&u.sequenceNumber>=(null==t?void 0:t.sequenceNumber));)i.length>m()?(({promise:a,resolve:o}=O()),yield a):(i.push(u),s(),({promise:n,resolve:s}=O()),u=yield this.getNextPacket(u,r));l=!0,s()}))().catch(e=>{d||(d=e,s())});const f=this._track;return{next(){return u(this,null,function*(){for(;;){if(f.input._disposed)throw new gn;if(c)return{value:void 0,done:!0};if(d)throw d;if(i.length>0){const e=i.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 u(this,null,function*(){return c=!0,o(),s(),{value:void 0,done:!0}})},throw(e){return u(this,null,function*(){throw e})},[Symbol.asyncIterator](){return this}}}}class zt{constructor(e,t){this.onSample=e,this.onError=t}}class Ot{mediaSamplesInRange(e=0,t=1/0){Rt(e),Rt(t);const r=[];let i=!1,n=null,{promise:s,resolve:a}=O(),{promise:o,resolve:l}=O(),c=!1,d=!1,h=!1,m=null;(()=>u(this,null,function*(){var u;const f=yield this._createDecoder(o=>{l(),o.timestamp>=t&&(d=!0),d?o.close():(n&&(o.timestamp>e?(r.push(n),i=!0):n.close()),o.timestamp>=e&&(r.push(o),i=!0),n=i?null:o,r.length>0&&(a(),({promise:s,resolve:a}=O())))},e=>{m||(m=e,a())}),p=this._createPacketSink(),g=null!=(u=yield p.getKeyPacket(e,{verifyKeyPackets:!0}))?u:yield p.getFirstPacket();let k=g;const b=p.packets(null!=g?g:void 0,void 0);for(yield b.next();k&&!d&&!this._track.input._disposed;){const e=Lt(r.length);if(r.length+f.getDecodeQueueSize()>e){({promise:o,resolve:l}=O()),yield o;continue}f.decode(k);const t=yield b.next();if(t.done)break;k=t.value}yield b.return(),h||this._track.input._disposed||(yield f.flush()),f.close(),!i&&n&&r.push(n),c=!0,a()}))().catch(e=>{m||(m=e,a())});const f=this._track,p=()=>{null==n||n.close();for(const e of r)e.close()};return{next(){return u(this,null,function*(){for(;;){if(f.input._disposed)throw p(),new gn;if(h)return{value:void 0,done:!0};if(m)throw p(),m;if(r.length>0){const e=r.shift();return l(),{value:e,done:!1}}if(c)return{value:void 0,done:!0};yield s}})},return(){return u(this,null,function*(){return h=!0,d=!0,l(),a(),p(),{value:void 0,done:!0}})},throw(e){return u(this,null,function*(){throw e})},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e){(e=>{if(!(Symbol.iterator in e)&&!(Symbol.asyncIterator in e))throw new TypeError("Argument must be an iterable or async iterable.")})(e);const t=V(e),r=[],i=[];let{promise:n,resolve:s}=O(),{promise:a,resolve:o}=O(),l=!1,c=!1,d=null;const h=e=>{i.push(e),s(),({promise:n,resolve:s}=O())};(()=>u(this,null,function*(){const e=yield this._createDecoder(e=>{if(o(),c)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 r=0;r<t;r++)h(r<t-1?e.clone():e);else e.close()},e=>{d||(d=e,s())}),n=this._createPacketSink();let f=null,g=null,k=-1;const b=()=>u(this,null,function*(){p(g);let t=g;for(e.decode(t);t.sequenceNumber<k;){const r=Lt(i.length);for(;i.length+e.getDecodeQueueSize()>r&&!c;)({promise:a,resolve:o}=O()),yield a;if(c)break;const s=yield n.getNextPacket(t);p(s),e.decode(s),t=s}k=-1}),y=()=>u(this,null,function*(){yield e.flush();for(let e=0;e<r.length;e++)h(null);r.length=0});try{for(var T,S,v,w=m(t);T=!(S=yield w.next()).done;T=!1){const e=S.value;if(Rt(e),c||this._track.input._disposed)break;const t=yield n.getPacket(e),i=t&&(yield n.getKeyPacket(e,{verifyKeyPackets:!0}));i?(f&&(i.sequenceNumber!==g.sequenceNumber||t.timestamp<f.timestamp)&&(yield b(),yield y()),r.push(t.timestamp),k=Math.max(t.sequenceNumber,k),f=t,g=i):(-1!==k&&(yield b(),yield y()),h(null),f=null)}}catch(S){v=[S]}finally{try{T&&(S=w.return)&&(yield S.call(w))}finally{if(v)throw v[0]}}c||this._track.input._disposed||(-1!==k&&(yield b()),yield y()),e.close(),l=!0,s()}))().catch(e=>{d||(d=e,s())});const f=this._track,g=()=>{for(const e of i)null==e||e.close()};return{next(){return u(this,null,function*(){for(;;){if(f.input._disposed)throw g(),new gn;if(c)return{value:void 0,done:!0};if(d)throw g(),d;if(i.length>0){const e=i.shift();return p(void 0!==e),o(),{value:e,done:!1}}if(l)return{value:void 0,done:!0};yield n}})},return(){return u(this,null,function*(){return c=!0,o(),s(),g(),{value:void 0,done:!0}})},throw(e){return u(this,null,function*(){throw e})},[Symbol.asyncIterator](){return this}}}}const Lt=e=>0===e?40:8;class Ut extends zt{constructor(e,i,n,s,a,o){super(e,i),this.codec=n,this.decoderConfig=s,this.rotation=a,this.timeResolution=o,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new te,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=lt.find(e=>e.supports(n,s));if(l)this.customDecoder=new l,this.customDecoder.codec=n,this.customDecoder.config=s,this.customDecoder.onSample=e=>{if(!(e instanceof kt))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();p(void 0!==t),this.mergeAlpha(e,t)}else this.colorQueue.push(e)};if("avc"===n&&this.decoderConfig.description&&oe()){const e=(e=>{try{const t=v(e);let r=0;const i=t.getUint8(r++),n=t.getUint8(r++),s=t.getUint8(r++),a=t.getUint8(r++),o=3&t.getUint8(r++),l=31&t.getUint8(r++),c=[];for(let m=0;m<l;m++){const i=t.getUint16(r,!1);r+=2,c.push(e.subarray(r,r+i)),r+=i}const u=t.getUint8(r++),d=[];for(let m=0;m<u;m++){const i=t.getUint16(r,!1);r+=2,d.push(e.subarray(r,r+i)),r+=i}const h={configurationVersion:i,avcProfileIndication:n,profileCompatibility:s,avcLevelIndication:a,lengthSizeMinusOne:o,sequenceParameterSets:c,pictureParameterSets:d,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((100===n||110===n||122===n||144===n)&&r+4<=e.length){const i=3&t.getUint8(r++),n=7&t.getUint8(r++),s=7&t.getUint8(r++),a=t.getUint8(r++);h.chromaFormat=i,h.bitDepthLumaMinus8=n,h.bitDepthChromaMinus8=s;const o=[];for(let l=0;l<a;l++){const i=t.getUint16(r,!1);r+=2,o.push(e.subarray(r,r+i)),r+=i}h.sequenceParameterSetExt=o}return h}catch(t){return console.error("Error deserializing AVC Decoder Configuration Record:",t),null}})(S(this.decoderConfig.description));if(e&&e.sequenceParameterSets.length>0){const i=Ve(e.sequenceParameterSets[0]);i&&0===i.frameMbsOnlyFlag&&(this.decoderConfig=(u=c({},this.decoderConfig),t(u,r({hardwareAcceleration:"prefer-software"}))))}}const i=new Error("Decoding error").stack;this.decoder=new VideoDecoder({output:t=>{try{e(t)}catch(r){this.onError(r)}},error:e=>{e.stack=i,this.onError(e)}}),this.decoder.configure(this.decoderConfig)}var u}getDecodeQueueSize(){var e,t;return this.customDecoder?this.customDecoderQueueSize:(p(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(p(this.decoder),ie()||z(this.inputTimestamps,e.timestamp,e=>e),oe()&&0===this.currentPacketIndex&&"avc"===this.codec){const t=ze(e.data,this.decoderConfig).filter(e=>{const t=Le(e);return!(t>=20&&t<=31)}),r=Oe(t,this.decoderConfig);e=new dt(r,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 Vt}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();p(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();p(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=it(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){return qe(e,this.decoderConfig).some(e=>{const t=He(e);return t===Fe.RASL_N||t===Fe.RASL_R})}sampleHandler(e){if(ie()){if(this.sampleQueue.length>0&&e.timestamp>=k(this.sampleQueue).timestamp){for(const e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}z(this.sampleQueue,e,e=>e.timestamp)}else{const t=this.inputTimestamps.shift();p(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 r;if(!t){const t=new kt(e);return void this.sampleHandler(t)}p(this.merger),this.merger.update(e,t),e.close(),t.close();const i=new VideoFrame(this.merger.canvas,{timestamp:e.timestamp,duration:null!=(r=e.duration)?r:void 0}),n=new kt(i);this.sampleHandler(n)}flush(){return u(this,null,function*(){var e;if(this.customDecoder?yield this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(p(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),ie()){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()):(p(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 r of this.sampleQueue)r.close();this.sampleQueue.length=0}}class Vt{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"),r=this.gl.createProgram();return this.gl.attachShader(r,e),this.gl.attachShader(r,t),this.gl.linkProgram(r),r}createShader(e,t){const r=this.gl.createShader(e);return this.gl.shaderSource(r,t),this.gl.compileShader(r),r}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]),r=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,r),this.gl.bufferData(this.gl.ARRAY_BUFFER,t,this.gl.STATIC_DRAW);const i=this.gl.getAttribLocation(this.program,"a_position"),n=this.gl.getAttribLocation(this.program,"a_texCoord");return this.gl.enableVertexAttribArray(i),this.gl.vertexAttribPointer(i,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 qt extends Ot{constructor(e){if(!(e instanceof Gt))throw new TypeError("videoTrack must be an InputVideoTrack.");super(),this._track=e}_createDecoder(e,t){return u(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 r=this._track.codec,i=this._track.rotation,n=yield this._track.getDecoderConfig(),s=this._track.timeResolution;return p(r&&n),new Ut(e,t,r,n,i,s)})}_createPacketSink(){return new Nt(this._track)}getSample(e){return u(this,null,function*(){Rt(e);try{for(var t,r,i,n=m(this.mediaSamplesAtTimestamps([e]));t=!(r=yield n.next()).done;t=!1){return r.value}}catch(r){i=[r]}finally{try{t&&(r=n.return)&&(yield r.call(n))}finally{if(i)throw i[0]}}throw new Error("Internal error: Iterator returned nothing.")})}samples(e=0,t=1/0){return this.mediaSamplesInRange(e,t)}samplesAtTimestamps(e){return this.mediaSamplesAtTimestamps(e)}}class Ht{constructor(e,t={}){var r,i,n,s;if(this._nextCanvasIndex=0,!(e instanceof Gt))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&&St(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.");const a=null!=(r=t.rotation)?r:e.rotation,[o,l]=a%180===0?[e.codedWidth,e.codedHeight]:[e.codedHeight,e.codedWidth],c=t.crop;c&&Tt(c,o,l);let[u,d]=c?[c.width,c.height]:[o,l];const h=u/d;void 0!==t.width&&void 0===t.height?(u=t.width,d=Math.round(u/h)):void 0===t.width&&void 0!==t.height?(d=t.height,u=Math.round(d*h)):void 0!==t.width&&void 0!==t.height&&(u=t.width,d=t.height),this._videoTrack=e,this._alpha=null!=(i=t.alpha)&&i,this._width=u,this._height=d,this._rotation=a,this._crop=c,this._fit=null!=(n=t.fit)?n:"fill",this._videoSampleSink=new qt(e),this._canvasPool=Array.from({length:null!=(s=t.poolSize)?s:0},()=>null)}_videoSampleToWrappedCanvas(e){let t=this._canvasPool[this._nextCanvasIndex],r=!1;t||("undefined"!==typeof document?(t=document.createElement("canvas"),t.width=this._width,t.height=this._height):t=new OffscreenCanvas(this._width,this._height),this._canvasPool.length>0&&(this._canvasPool[this._nextCanvasIndex]=t),r=!0),this._canvasPool.length>0&&(this._nextCanvasIndex=(this._nextCanvasIndex+1)%this._canvasPool.length);const i=t.getContext("2d",{alpha:this._alpha||se()});p(i),i.resetTransform(),r||(!this._alpha&&se()?(i.fillStyle="black",i.fillRect(0,0,this._width,this._height)):i.clearRect(0,0,this._width,this._height)),e.drawWithFit(i,{fit:this._fit,rotation:this._rotation,crop:this._crop});const n={canvas:t,timestamp:e.timestamp,duration:e.duration};return e.close(),n}getCanvas(e){return u(this,null,function*(){Rt(e);const t=yield this._videoSampleSink.getSample(e);return t&&this._videoSampleToWrappedCanvas(t)})}canvases(e=0,t=1/0){return j(this._videoSampleSink.samples(e,t),e=>this._videoSampleToWrappedCanvas(e))}canvasesAtTimestamps(e){return j(this._videoSampleSink.samplesAtTimestamps(e),e=>e&&this._videoSampleToWrappedCanvas(e))}}class Wt extends zt{constructor(e,t,r,i){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new te,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 r=this.currentTimestamp;if(this.currentTimestamp+=t.duration,0===t.numberOfFrames)return void t.close();const n=i.sampleRate;t.setTimestamp(Math.round(r*n)/n),e(t)},s=ct.find(e=>e.supports(r,i));if(s)this.customDecoder=new s,this.customDecoder.codec=r,this.customDecoder.config=i,this.customDecoder.onSample=e=>{if(!(e instanceof xt))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 xt(e))}catch(t){this.onError(t)}},error:t=>{t.stack=e,this.onError(t)}}),this.decoder.configure(i)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(p(this.decoder),this.decoder.decodeQueueSize)}decode(e){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--)):(p(this.decoder),this.decoder.decode(e.toEncodedAudioChunk()))}flush(){return this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(p(this.decoder),this.decoder.flush())}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(p(this.decoder),this.decoder.close())}}class jt extends zt{constructor(e,t,r){super(e,t),this.decoderConfig=r,this.currentTimestamp=null,p(ke.includes(r.codec)),this.codec=r.codec;const{dataType:i,sampleSize:n,littleEndian:s}=_e(this.codec);switch(this.inputSampleSize=n,n){case 1:"unsigned"===i?this.readInputValue=(e,t)=>e.getUint8(t)-o(2,7):"signed"===i?this.readInputValue=(e,t)=>e.getInt8(t):"ulaw"===i?this.readInputValue=(e,t)=>(e=>{let t=0,r=0,i=~e;128&i&&(i&=-129,t=-1),r=5+((240&i)>>4);const n=(1<<r|(15&i)<<r-4|1<<r-5)-33;return 0===t?n:-n})(e.getUint8(t)):"alaw"===i?this.readInputValue=(e,t)=>(e=>{let t=0,r=0,i=85^e;128&i&&(i&=-129,t=-1),r=4+((240&i)>>4);let n=0;return n=4!==r?1<<r|(15&i)<<r-4|1<<r-5:i<<1|1,0===t?n:-n})(e.getUint8(t)):p(!1);break;case 2:"unsigned"===i?this.readInputValue=(e,t)=>e.getUint16(t,s)-o(2,15):"signed"===i?this.readInputValue=(e,t)=>e.getInt16(t,s):p(!1);break;case 3:"unsigned"===i?this.readInputValue=(e,t)=>H(e,t,s)-o(2,23):"signed"===i?this.readInputValue=(e,t)=>((e,t,r)=>H(e,t,r)<<8>>8)(e,t,s):p(!1);break;case 4:"unsigned"===i?this.readInputValue=(e,t)=>e.getUint32(t,s)-o(2,31):"signed"===i?this.readInputValue=(e,t)=>e.getInt32(t,s):"float"===i?this.readInputValue=(e,t)=>e.getFloat32(t,s):p(!1);break;case 8:"float"===i?this.readInputValue=(e,t)=>e.getFloat64(t,s):p(!1);break;default:q(n),p(!1)}switch(n){case 1:"ulaw"===i||"alaw"===i?(this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(e,t,r)=>e.setInt16(t,r,!0)):(this.outputSampleSize=1,this.outputFormat="u8",this.writeOutputValue=(e,t,r)=>e.setUint8(t,r+o(2,7)));break;case 2:this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(e,t,r)=>e.setInt16(t,r,!0);break;case 3:this.outputSampleSize=4,this.outputFormat="s32",this.writeOutputValue=(e,t,r)=>e.setInt32(t,r<<8,!0);break;case 4:this.outputSampleSize=4,"float"===i?(this.outputFormat="f32",this.writeOutputValue=(e,t,r)=>e.setFloat32(t,r,!0)):(this.outputFormat="s32",this.writeOutputValue=(e,t,r)=>e.setInt32(t,r,!0));break;case 8:this.outputSampleSize=4,this.outputFormat="f32",this.writeOutputValue=(e,t,r)=>e.setFloat32(t,r,!0);break;default:q(n),p(!1)}}getDecodeQueueSize(){return 0}decode(e){const t=v(e.data),r=e.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize,i=r*this.decoderConfig.numberOfChannels*this.outputSampleSize,n=new ArrayBuffer(i),s=new DataView(n);for(let c=0;c<r*this.decoderConfig.numberOfChannels;c++){const e=c*this.inputSampleSize,r=c*this.outputSampleSize,i=this.readInputValue(t,e);this.writeOutputValue(s,r,i)}const a=r/this.decoderConfig.sampleRate;(null===this.currentTimestamp||Math.abs(e.timestamp-this.currentTimestamp)>=a)&&(this.currentTimestamp=e.timestamp);const o=this.currentTimestamp;this.currentTimestamp+=a;const l=new xt({format:this.outputFormat,data:n,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:r,timestamp:o});this.onSample(l)}flush(){return u(this,null,function*(){})}close(){}}class Kt extends Ot{constructor(e){if(!(e instanceof Xt))throw new TypeError("audioTrack must be an InputAudioTrack.");super(),this._track=e}_createDecoder(e,t){return u(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 r=this._track.codec,i=yield this._track.getDecoderConfig();return p(r&&i),ke.includes(i.codec)?new jt(e,t,i):new Wt(e,t,r,i)})}_createPacketSink(){return new Nt(this._track)}getSample(e){return u(this,null,function*(){Rt(e);try{for(var t,r,i,n=m(this.mediaSamplesAtTimestamps([e]));t=!(r=yield n.next()).done;t=!1){return r.value}}catch(r){i=[r]}finally{try{t&&(r=n.return)&&(yield r.call(n))}finally{if(i)throw i[0]}}throw new Error("Internal error: Iterator returned nothing.")})}samples(e=0,t=1/0){return this.mediaSamplesInRange(e,t)}samplesAtTimestamps(e){return this.mediaSamplesAtTimestamps(e)}}class $t{constructor(e){if(!(e instanceof Xt))throw new TypeError("audioTrack must be an InputAudioTrack.");this._audioSampleSink=new Kt(e)}_audioSampleToWrappedArrayBuffer(e){const t={buffer:e.toAudioBuffer(),timestamp:e.timestamp,duration:e.duration};return e.close(),t}getBuffer(e){return u(this,null,function*(){Rt(e);const t=yield this._audioSampleSink.getSample(e);return t&&this._audioSampleToWrappedArrayBuffer(t)})}buffers(e=0,t=1/0){return j(this._audioSampleSink.samples(e,t),e=>this._audioSampleToWrappedArrayBuffer(e))}buffersAtTimestamps(e){return j(this._audioSampleSink.samplesAtTimestamps(e),e=>e&&this._audioSampleToWrappedArrayBuffer(e))}}
|
|
/*!
|
|
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
*
|
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
*/class Qt{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof Gt}isAudioTrack(){return this instanceof Xt}get id(){return this._backing.getId()}get internalCodecId(){return this._backing.getInternalCodecId()}get languageCode(){return this._backing.getLanguageCode()}get name(){return this._backing.getName()}get timeResolution(){return this._backing.getTimeResolution()}get disposition(){return this._backing.getDisposition()}getFirstTimestamp(){return this._backing.getFirstTimestamp()}computeDuration(){return this._backing.computeDuration()}computePacketStats(e=1/0){return u(this,null,function*(){const t=new Nt(this);let r=1/0,i=-1/0,n=0,s=0;try{for(var a,o,l,c=m(t.packets(void 0,void 0,{metadataOnly:!0}));a=!(o=yield c.next()).done;a=!1){const t=o.value;if(n>=e&&t.timestamp>=i)break;r=Math.min(r,t.timestamp),i=Math.max(i,t.timestamp+t.duration),n++,s+=t.byteLength}}catch(o){l=[o]}finally{try{a&&(o=c.return)&&(yield o.call(c))}finally{if(l)throw l[0]}}return{packetCount:n,averagePacketRate:n?Number((n/(i-r)).toPrecision(16)):0,averageBitrate:n?Number((8*s/(i-r)).toPrecision(16)):0}})}}class Gt extends Qt{constructor(e,t){super(e,t),this._backing=t}get type(){return"video"}get codec(){return this._backing.getCodec()}get codedWidth(){return this._backing.getCodedWidth()}get codedHeight(){return this._backing.getCodedHeight()}get rotation(){return this._backing.getRotation()}get displayWidth(){return this._backing.getRotation()%180===0?this._backing.getCodedWidth():this._backing.getCodedHeight()}get displayHeight(){return this._backing.getRotation()%180===0?this._backing.getCodedHeight():this._backing.getCodedWidth()}getColorSpace(){return this._backing.getColorSpace()}hasHighDynamicRange(){return u(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 this._backing.canBeTransparent()}getDecoderConfig(){return this._backing.getDecoderConfig()}getCodecParameterString(){return u(this,null,function*(){var e;const t=yield this._backing.getDecoderConfig();return null!=(e=null==t?void 0:t.codec)?e:null})}canDecode(){return u(this,null,function*(){try{const e=yield this._backing.getDecoderConfig();if(!e)return!1;const t=this._backing.getCodec();if(p(null!==t),lt.some(r=>r.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 u(this,null,function*(){if(!(e instanceof dt))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("packet must not be metadata-only to determine its type.");if(null===this.codec)return null;const t=yield this.getDecoderConfig();return p(t),it(this.codec,t,e.data)})}}class Xt extends Qt{constructor(e,t){super(e,t),this._backing=t}get type(){return"audio"}get codec(){return this._backing.getCodec()}get numberOfChannels(){return this._backing.getNumberOfChannels()}get sampleRate(){return this._backing.getSampleRate()}getDecoderConfig(){return this._backing.getDecoderConfig()}getCodecParameterString(){return u(this,null,function*(){var e;const t=yield this._backing.getDecoderConfig();return null!=(e=null==t?void 0:t.codec)?e:null})}canDecode(){return u(this,null,function*(){try{const e=yield this._backing.getDecoderConfig();if(!e)return!1;const t=this._backing.getCodec();if(p(null!==t),ct.some(r=>r.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 u(this,null,function*(){if(!(e instanceof dt))throw new TypeError("packet must be an EncodedPacket.");return null===this.codec?null:"key"})}}
|
|
/*!
|
|
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
*
|
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
*/const Yt=e=>{let t=Cn(e);const r=Nn(e,4);let i=8;1===t&&(t=Fn(e),i=16);const n=t-i;return n<0?null:{name:r,totalSize:t,headerSize:i,contentSize:n}},Jt=e=>Bn(e)/65536,Zt=e=>Bn(e)/1073741824,er=e=>{let t=0;for(let r=0;r<4;r++){t<<=7;const r=Sn(e);if(t|=127&r,0===(128&r))break}return t},tr=e=>{let t=wn(e);return e.skip(2),t=Math.min(t,e.remainingLength),w.decode(Tn(e,t))},rr=e=>{const t=Yt(e);if(!t||"data"!==t.name)return null;if(e.remainingLength<8)return null;const r=Cn(e);e.skip(4);const i=Tn(e,t.contentSize-8);switch(r){case 1:return w.decode(i);case 2:return new TextDecoder("utf-16be").decode(i);case 13:return new fe(i,"image/jpeg");case 14:return new fe(i,"image/png");case 27:return new fe(i,"image/bmp");default:return i}};
|
|
/*!
|
|
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
*
|
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
*/
|
|
/*!
|
|
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
*
|
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
*/
|
|
class ir extends ot{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.currentFragment=null,this.lastReadFragment=null,this.reader=e._reader}computeDuration(){return u(this,null,function*(){const e=yield this.getTracks(),t=yield Promise.all(e.map(e=>e.computeDuration()));return Math.max(0,...t)})}getTracks(){return u(this,null,function*(){return yield this.readMetadata(),this.tracks.map(e=>e.inputTrack)})}getMimeType(){return u(this,null,function*(){yield this.readMetadata();const e=yield Promise.all(this.tracks.map(e=>e.inputTrack.getCodecParameterString()));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:e.filter(Boolean)})})}getMetadataTags(){return u(this,null,function*(){return yield this.readMetadata(),this.metadataTags})}readMetadata(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>u(this,null,function*(){let e=0;for(;;){let t=this.reader.requestSliceRange(e,8,16);if(t instanceof Promise&&(t=yield t),!t)break;const r=e,i=Yt(t);if(!i)break;if("ftyp"===i.name){const e=Nn(t,4);this.isQuickTime="qt "===e}else if("moov"===i.name){let e=this.reader.requestSlice(t.filePos,i.contentSize);if(e instanceof Promise&&(e=yield e),!e)break;this.moovSlice=e,this.readContiguousBoxes(this.moovSlice),this.tracks.sort((e,t)=>Number(t.disposition.default)-Number(e.disposition.default));for(const t of this.tracks){const e=t.editListPreviousSegmentDurations/this.movieTimescale;t.editListOffset-=Math.round(e*t.timescale)}break}e=r+i.totalSize}if(this.isFragmented&&null!==this.reader.fileSize){let e=this.reader.requestSlice(this.reader.fileSize-4,4);e instanceof Promise&&(e=yield e),p(e);const t=Cn(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=yield e),e){const t=Yt(e);if(t&&"mfra"===t.name){let r=this.reader.requestSlice(e.filePos,t.contentSize);r instanceof Promise&&(r=yield r),r&&this.readContiguousBoxes(r)}}}}}))()}getSampleTableForTrack(e){var t,r;if(e.sampleTable)return e.sampleTable;const i={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};e.sampleTable=i,p(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&&ke.includes(e.info.codec)&&0===i.sampleCompositionTimeOffsets.length){p("audio"===(null==(r=e.info)?void 0:r.type));const t=_e(e.info.codec),n=[],s=[];for(let r=0;r<i.sampleToChunk.length;r++){const a=i.sampleToChunk[r],o=i.sampleToChunk[r+1],l=(o?o.startChunkIndex:i.chunkOffsets.length)-a.startChunkIndex;for(let r=0;r<l;r++){const o=a.startSampleIndex+r*a.samplesPerChunk,l=o+a.samplesPerChunk,c=N(i.sampleTimingEntries,o,e=>e.startIndex),u=i.sampleTimingEntries[c],d=N(i.sampleTimingEntries,l,e=>e.startIndex),h=i.sampleTimingEntries[d],m=u.startDecodeTimestamp+(o-u.startIndex)*u.delta,f=h.startDecodeTimestamp+(l-h.startIndex)*h.delta-m,p=k(n);p&&p.delta===f?p.count++:n.push({startIndex:a.startChunkIndex+r,startDecodeTimestamp:m,count:1,delta:f});const g=a.samplesPerChunk*t.sampleSize*e.info.numberOfChannels;s.push(g)}a.startSampleIndex=a.startChunkIndex,a.samplesPerChunk=1}i.sampleTimingEntries=n,i.sampleSizes=s}if(i.sampleCompositionTimeOffsets.length>0){i.presentationTimestamps=[];for(const e of i.sampleTimingEntries)for(let t=0;t<e.count;t++)i.presentationTimestamps.push({presentationTimestamp:e.startDecodeTimestamp+t*e.delta,sampleIndex:e.startIndex+t});for(const e of i.sampleCompositionTimeOffsets)for(let t=0;t<e.count;t++){const r=e.startIndex+t,n=i.presentationTimestamps[r];n&&(n.presentationTimestamp+=e.offset)}i.presentationTimestamps.sort((e,t)=>e.presentationTimestamp-t.presentationTimestamp),i.presentationTimestampIndexMap=Array(i.presentationTimestamps.length).fill(-1);for(let e=0;e<i.presentationTimestamps.length;e++)i.presentationTimestampIndexMap[i.presentationTimestamps[e].sampleIndex]=e}return i}readFragment(e){return u(this,null,function*(){var t;if((null==(t=this.lastReadFragment)?void 0:t.moofOffset)===e)return this.lastReadFragment;let r=this.reader.requestSliceRange(e,8,16);r instanceof Promise&&(r=yield r),p(r);const i=Yt(r);p("moof"===(null==i?void 0:i.name));let n=this.reader.requestSlice(e,i.totalSize);n instanceof Promise&&(n=yield n),p(n),this.traverseBox(n);const s=this.lastReadFragment;p(s&&s.moofOffset===e);for(const[,e]of s.trackData){const t=e.track,{fragmentPositionCache:r}=t;if(!e.startTimestampIsFinal){const i=t.fragmentLookupTable.find(e=>e.moofOffset===s.moofOffset);if(i)dr(e,i.timestamp);else{const t=N(r,s.moofOffset-1,e=>e.moofOffset);if(-1!==t){const i=r[t];dr(e,i.endTimestamp)}}e.startTimestampIsFinal=!0}const i=N(r,e.startTimestamp,e=>e.startTimestamp);-1!==i&&r[i].moofOffset===s.moofOffset||r.splice(i+1,0,{moofOffset:s.moofOffset,startTimestamp:e.startTimestamp,endTimestamp:e.endTimestamp})}return s})}readContiguousBoxes(e){const t=e.filePos;for(;e.filePos-t<=e.length-8;){if(!this.traverseBox(e))break}}*iterateContiguousBoxes(e){const t=e.filePos;for(;e.filePos-t<=e.length-8;){const t=e.filePos,r=Yt(e);if(!r)break;yield{boxInfo:r,slice:e},e.filePos=t+r.totalSize}}traverseBox(e){var t,r,i,n,s,a,o,l,u,d,h,m,f,y,T,S,I,P,C,B,F,D,A,R,M,N,z,O,L,U,V,q,H,W,j,K,Q,G,Y,J,Z,ee,te,re,ie;const ne=e.filePos,se=Yt(e);if(!se)return!1;const ae=e.filePos,oe=ne+se.totalSize;switch(se.name){case"mdia":case"minf":case"dinf":case"mfra":case"edts":case"wave":this.readContiguousBoxes(e.slice(ae,se.contentSize));break;case"mvhd":{const t=Sn(e);e.skip(3),1===t?(e.skip(16),this.movieTimescale=Cn(e),this.movieDurationInTimescale=Fn(e)):(e.skip(8),this.movieTimescale=Cn(e),this.movieDurationInTimescale=Cn(e))}break;case"trak":{const t={id:-1,demuxer:this,inputTrack:null,disposition:c({},ge),info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,internalCodecId:null,name:null,languageCode:$,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0};if(this.currentTrack=t,this.readContiguousBoxes(e.slice(ae,se.contentSize)),-1!==t.id&&-1!==t.timescale&&null!==t.info)if("video"===t.info.type&&-1!==t.info.width){const e=t;t.inputTrack=new Gt(this.input,new sr(e)),this.tracks.push(t)}else if("audio"===t.info.type&&-1!==t.info.numberOfChannels){const e=t;t.inputTrack=new Xt(this.input,new ar(e)),this.tracks.push(t)}this.currentTrack=null}break;case"tkhd":{const t=this.currentTrack;if(!t)break;const r=Sn(e),i=!!(1&In(e));if(t.disposition.default=i,0===r)e.skip(8),t.id=Cn(e),e.skip(4),t.durationInMovieTimescale=Cn(e);else{if(1!==r)throw new Error(`Incorrect track header version ${r}.`);e.skip(16),t.id=Cn(e),e.skip(4),t.durationInMovieTimescale=Fn(e)}e.skip(16);const n=[Jt(e),Jt(e),Zt(e),Jt(e),Jt(e),Zt(e),Jt(e),Jt(e),Zt(e)],s=g((le=hr(n),ce=90,Math.round(le/ce)*ce));p(0===s||90===s||180===s||270===s),t.rotation=s}break;case"elst":{const t=this.currentTrack;if(!t)break;const r=Sn(e);e.skip(3);let i=!1,n=0;const s=Cn(e);for(let a=0;a<s;a++){const s=1===r?Fn(e):Cn(e),a=1===r?Dn(e):Bn(e),o=Jt(e);if(0!==s){if(i){console.warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit.");break}if(-1!==a){if(1!==o){console.warn("Unsupported edit list entry: media rate must be 1.");break}t.editListPreviousSegmentDurations=n,t.editListOffset=a,i=!0}else n+=s}}}break;case"mdhd":{const t=this.currentTrack;if(!t)break;const r=Sn(e);e.skip(3),0===r?(e.skip(8),t.timescale=Cn(e),t.durationInMediaTimescale=Cn(e)):1===r&&(e.skip(16),t.timescale=Cn(e),t.durationInMediaTimescale=Fn(e));let i=wn(e);if(i>0){t.languageCode="";for(let e=0;e<3;e++)t.languageCode=String.fromCharCode(96+(31&i))+t.languageCode,i>>=5;X(t.languageCode)||(t.languageCode=$)}}break;case"hdlr":{const t=this.currentTrack;if(!t)break;e.skip(8);const r=Nn(e,4);"vide"===r?t.info={type:"video",width:-1,height:-1,codec:null,codecDescription:null,colorSpace:null,avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null}:"soun"===r&&(t.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case"stbl":{const t=this.currentTrack;if(!t)break;t.sampleTableByteOffset=ne,this.readContiguousBoxes(e.slice(ae,se.contentSize))}break;case"stsd":{const t=this.currentTrack;if(!t)break;if(null===t.info||t.sampleTable)break;const r=Sn(e);e.skip(3);const i=Cn(e);for(let n=0;n<i;n++){const i=e.filePos,n=Yt(e);if(!n)break;t.internalCodecId=n.name;const s=n.name.toLowerCase();if("video"===t.info.type)"avc1"===s||"avc3"===s?(t.info.codec="avc",t.info.avcType="avc1"===s?1:3):"hvc1"===s||"hev1"===s?t.info.codec="hevc":"vp08"===s?t.info.codec="vp8":"vp09"===s?t.info.codec="vp9":"av01"===s?t.info.codec="av1":console.warn(`Unsupported video codec (sample entry type '${n.name}').`),e.skip(24),t.info.width=wn(e),t.info.height=wn(e),e.skip(50),this.readContiguousBoxes(e.slice(e.filePos,i+n.totalSize-e.filePos));else{"mp4a"===s||("opus"===s?t.info.codec="opus":"flac"===s?t.info.codec="flac":"twos"===s||"sowt"===s||"raw "===s||"in24"===s||"in32"===s||"fl32"===s||"fl64"===s||"lpcm"===s||"ipcm"===s||"fpcm"===s||("ulaw"===s?t.info.codec="ulaw":"alaw"===s?t.info.codec="alaw":console.warn(`Unsupported audio codec (sample entry type '${n.name}').`))),e.skip(8);const a=wn(e);e.skip(6);let o=wn(e),l=wn(e);e.skip(4);let c=Cn(e)/65536;if(0===r&&a>0)if(1===a)e.skip(4),l=8*Cn(e),e.skip(8);else if(2===a){e.skip(4),c=Mn(e),o=Cn(e),e.skip(4),l=Cn(e);const r=Cn(e);if(e.skip(8),"lpcm"===s){const e=l+7>>3,i=Boolean(1&r),n=Boolean(2&r),s=4&r?-1:0;l>0&&l<=64&&(i?32===l&&(t.info.codec=n?"pcm-f32be":"pcm-f32"):s&1<<e-1?1===e?t.info.codec="pcm-s8":2===e?t.info.codec=n?"pcm-s16be":"pcm-s16":3===e?t.info.codec=n?"pcm-s24be":"pcm-s24":4===e&&(t.info.codec=n?"pcm-s32be":"pcm-s32"):1===e&&(t.info.codec="pcm-u8")),null===t.info.codec&&console.warn("Unsupported PCM format.")}}"opus"===t.info.codec&&(c=xe),t.info.numberOfChannels=o,t.info.sampleRate=c,"twos"===s?8===l?t.info.codec="pcm-s8":16===l?t.info.codec="pcm-s16be":(console.warn(`Unsupported sample size ${l} for codec 'twos'.`),t.info.codec=null):"sowt"===s?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):"raw "===s?t.info.codec="pcm-u8":"in24"===s?t.info.codec="pcm-s24be":"in32"===s?t.info.codec="pcm-s32be":"fl32"===s?t.info.codec="pcm-f32be":"fl64"===s?t.info.codec="pcm-f64be":"ipcm"===s?t.info.codec="pcm-s16be":"fpcm"===s&&(t.info.codec="pcm-f32be"),this.readContiguousBoxes(e.slice(e.filePos,i+n.totalSize-e.filePos))}}}break;case"avcC":{const t=this.currentTrack;if(!t)break;p(t.info),t.info.codecDescription=Tn(e,se.contentSize)}break;case"hvcC":{const t=this.currentTrack;if(!t)break;p(t.info),t.info.codecDescription=Tn(e,se.contentSize)}break;case"vpcC":{const r=this.currentTrack;if(!r)break;p("video"===(null==(t=r.info)?void 0:t.type)),e.skip(4);const i=Sn(e),n=Sn(e),s=Sn(e),a=s>>4,o=s>>1&7,l=1&s,c=Sn(e),u=Sn(e),d=Sn(e);r.info.vp9CodecInfo={profile:i,level:n,bitDepth:a,chromaSubsampling:o,videoFullRangeFlag:l,colourPrimaries:c,transferCharacteristics:u,matrixCoefficients:d}}break;case"av1C":{const t=this.currentTrack;if(!t)break;p("video"===(null==(r=t.info)?void 0:r.type)),e.skip(1);const i=Sn(e),n=i>>5,s=31&i,a=Sn(e),o=a>>7,l=a>>6&1,c=a>>4&1,u=a>>3&1,d=a>>2&1,h=3&a,m=2===n&&l?a>>5&1?12:10:l?10:8;t.info.av1CodecInfo={profile:n,level:s,tier:o,bitDepth:m,monochrome:c,chromaSubsamplingX:u,chromaSubsamplingY:d,chromaSamplePosition:h}}break;case"colr":{const t=this.currentTrack;if(!t)break;p("video"===(null==(i=t.info)?void 0:i.type));if("nclx"!==Nn(e,4))break;const r=wn(e),n=wn(e),s=wn(e),a=Boolean(128&Sn(e));t.info.colorSpace={primaries:x[r],transfer:_[n],matrix:E[s],fullRange:a}}break;case"esds":{const t=this.currentTrack;if(!t)break;p("audio"===(null==(n=t.info)?void 0:n.type)),e.skip(4);p(3===Sn(e)),er(e),e.skip(2);const r=Sn(e),i=0!==(64&r),s=0!==(32&r);if(0!==(128&r)&&e.skip(2),i){const t=Sn(e);e.skip(t)}s&&e.skip(2);p(4===Sn(e));const a=er(e),o=e.filePos,l=Sn(e);if(64===l||103===l?(t.info.codec="aac",t.info.aacCodecInfo={isMpeg2:103===l}):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){p(5===Sn(e));const r=er(e);if(t.info.codecDescription=Tn(e,r),"aac"===t.info.codec){const e=Pe(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;p("audio"===(null==(s=t.info)?void 0:s.type));255&wn(e)&&("pcm-s16be"===t.info.codec?t.info.codec="pcm-s16":"pcm-s24be"===t.info.codec?t.info.codec="pcm-s24":"pcm-s32be"===t.info.codec?t.info.codec="pcm-s32":"pcm-f32be"===t.info.codec?t.info.codec="pcm-f32":"pcm-f64be"===t.info.codec&&(t.info.codec="pcm-f64"))}break;case"pcmC":{const t=this.currentTrack;if(!t)break;p("audio"===(null==(a=t.info)?void 0:a.type)),e.skip(4);const r=Sn(e),i=Boolean(1&r),n=Sn(e);"pcm-s16be"===t.info.codec?i?16===n?t.info.codec="pcm-s16":24===n?t.info.codec="pcm-s24":32===n?t.info.codec="pcm-s32":(console.warn(`Invalid ipcm sample size ${n}.`),t.info.codec=null):16===n?t.info.codec="pcm-s16be":24===n?t.info.codec="pcm-s24be":32===n?t.info.codec="pcm-s32be":(console.warn(`Invalid ipcm sample size ${n}.`),t.info.codec=null):"pcm-f32be"===t.info.codec&&(i?32===n?t.info.codec="pcm-f32":64===n?t.info.codec="pcm-f64":(console.warn(`Invalid fpcm sample size ${n}.`),t.info.codec=null):32===n?t.info.codec="pcm-f32be":64===n?t.info.codec="pcm-f64be":(console.warn(`Invalid fpcm sample size ${n}.`),t.info.codec=null));break}case"dOps":{const t=this.currentTrack;if(!t)break;p("audio"===(null==(o=t.info)?void 0:o.type)),e.skip(1);const r=Sn(e),i=wn(e),n=Cn(e),s=Pn(e),a=Sn(e);let l;l=0!==a?Tn(e,2+r):new Uint8Array(0);const c=new Uint8Array(19+l.byteLength),u=new DataView(c.buffer);u.setUint32(0,1332770163,!1),u.setUint32(4,1214603620,!1),u.setUint8(8,1),u.setUint8(9,r),u.setUint16(10,i,!0),u.setUint32(12,n,!0),u.setInt16(16,s,!0),u.setUint8(18,a),c.set(l,19),t.info.codecDescription=c,t.info.numberOfChannels=r}break;case"dfLa":{const t=this.currentTrack;if(!t)break;p("audio"===(null==(l=t.info)?void 0:l.type)),e.skip(4);const r=127,i=128,n=e.filePos;for(;e.filePos<oe;){const n=Sn(e),s=In(e);if((n&r)===nt.STREAMINFO){e.skip(10);const r=Cn(e),i=r>>>12,n=1+(r>>9&7);t.info.sampleRate=i,t.info.numberOfChannels=n,e.skip(20)}else e.skip(s);if(n&i)break}const s=e.filePos;e.filePos=n;const a=Tn(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"stts":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4);const r=Cn(e);let i=0,n=0;for(let s=0;s<r;s++){const r=Cn(e),s=Cn(e);t.sampleTable.sampleTimingEntries.push({startIndex:i,startDecodeTimestamp:n,count:r,delta:s}),i+=r,n+=r*s}}break;case"ctts":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4);const r=Cn(e);let i=0;for(let n=0;n<r;n++){const r=Cn(e),n=Bn(e);t.sampleTable.sampleCompositionTimeOffsets.push({startIndex:i,count:r,offset:n}),i+=r}}break;case"stsz":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4);const r=Cn(e),i=Cn(e);if(0===r)for(let n=0;n<i;n++){const r=Cn(e);t.sampleTable.sampleSizes.push(r)}else t.sampleTable.sampleSizes.push(r)}break;case"stz2":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4),e.skip(3);const r=Sn(e),i=Cn(e),n=Tn(e,Math.ceil(i*r/8)),s=new b(n);for(let e=0;e<i;e++){const e=s.readBits(r);t.sampleTable.sampleSizes.push(e)}}break;case"stss":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4),t.sampleTable.keySampleIndices=[];const r=Cn(e);for(let i=0;i<r;i++){const r=Cn(e)-1;t.sampleTable.keySampleIndices.push(r)}0!==t.sampleTable.keySampleIndices[0]&&t.sampleTable.keySampleIndices.unshift(0)}break;case"stsc":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4);const r=Cn(e);for(let n=0;n<r;n++){const r=Cn(e)-1,i=Cn(e),n=Cn(e);t.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:r,samplesPerChunk:i,sampleDescriptionIndex:n})}let i=0;for(let e=0;e<t.sampleTable.sampleToChunk.length;e++)if(t.sampleTable.sampleToChunk[e].startSampleIndex=i,e<t.sampleTable.sampleToChunk.length-1){i+=(t.sampleTable.sampleToChunk[e+1].startChunkIndex-t.sampleTable.sampleToChunk[e].startChunkIndex)*t.sampleTable.sampleToChunk[e].samplesPerChunk}}break;case"stco":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4);const r=Cn(e);for(let i=0;i<r;i++){const r=Cn(e);t.sampleTable.chunkOffsets.push(r)}}break;case"co64":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4);const r=Cn(e);for(let i=0;i<r;i++){const r=Fn(e);t.sampleTable.chunkOffsets.push(r)}}break;case"mvex":this.isFragmented=!0,this.readContiguousBoxes(e.slice(ae,se.contentSize));break;case"mehd":{const t=Sn(e);e.skip(3);const r=1===t?Fn(e):Cn(e);this.movieDurationInTimescale=r}break;case"trex":{e.skip(4);const t=Cn(e),r=Cn(e),i=Cn(e),n=Cn(e),s=Cn(e);this.fragmentTrackDefaults.push({trackId:t,defaultSampleDescriptionIndex:r,defaultSampleDuration:i,defaultSampleSize:n,defaultSampleFlags:s})}break;case"tfra":{const t=Sn(e);e.skip(3);const r=Cn(e),i=this.tracks.find(e=>e.id===r);if(!i)break;const n=Cn(e),s=(12&n)>>2,a=3&n,o=[Sn,wn,In,Cn],l=o[(48&n)>>4],c=o[s],u=o[a],d=Cn(e);for(let h=0;h<d;h++){const r=1===t?Fn(e):Cn(e),n=1===t?Fn(e):Cn(e);l(e),c(e),u(e),i.fragmentLookupTable.push({timestamp:r,moofOffset:n})}i.fragmentLookupTable.sort((e,t)=>e.timestamp-t.timestamp);for(let e=0;e<i.fragmentLookupTable.length-1;e++){const t=i.fragmentLookupTable[e],r=i.fragmentLookupTable[e+1];t.timestamp===r.timestamp&&(i.fragmentLookupTable.splice(e+1,1),e--)}}break;case"moof":this.currentFragment={moofOffset:ne,moofSize:se.totalSize,implicitBaseDataOffset:ne,trackData:new Map},this.readContiguousBoxes(e.slice(ae,se.contentSize)),this.lastReadFragment=this.currentFragment,this.currentFragment=null;break;case"traf":if(p(this.currentFragment),this.readContiguousBoxes(e.slice(ae,se.contentSize)),this.currentTrack){const e=this.currentFragment.trackData.get(this.currentTrack.id);if(e){const{currentFragmentState:t}=this.currentTrack;p(t),null!==t.startTimestamp&&(dr(e,t.startTimestamp),e.startTimestampIsFinal=!0)}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case"tfhd":{p(this.currentFragment),e.skip(1);const t=In(e),r=Boolean(1&t),i=Boolean(2&t),n=Boolean(8&t),s=Boolean(16&t),a=Boolean(32&t),o=Boolean(65536&t),l=Boolean(131072&t),c=Cn(e),f=this.tracks.find(e=>e.id===c);if(!f)break;const g=this.fragmentTrackDefaults.find(e=>e.trackId===c);this.currentTrack=f,f.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:null!=(u=null==g?void 0:g.defaultSampleDescriptionIndex)?u:null,defaultSampleDuration:null!=(d=null==g?void 0:g.defaultSampleDuration)?d:null,defaultSampleSize:null!=(h=null==g?void 0:g.defaultSampleSize)?h:null,defaultSampleFlags:null!=(m=null==g?void 0:g.defaultSampleFlags)?m:null,startTimestamp:null},r?f.currentFragmentState.baseDataOffset=Fn(e):l&&(f.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),i&&(f.currentFragmentState.sampleDescriptionIndex=Cn(e)),n&&(f.currentFragmentState.defaultSampleDuration=Cn(e)),s&&(f.currentFragmentState.defaultSampleSize=Cn(e)),a&&(f.currentFragmentState.defaultSampleFlags=Cn(e)),o&&(f.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{const t=this.currentTrack;if(!t)break;p(t.currentFragmentState);const r=Sn(e);e.skip(3);const i=0===r?Cn(e):Fn(e);t.currentFragmentState.startTimestamp=i}break;case"trun":{const t=this.currentTrack;if(!t)break;if(p(this.currentFragment),p(t.currentFragmentState),this.currentFragment.trackData.has(t.id)){console.warn("Can't have two trun boxes for the same track in one fragment. Ignoring...");break}const r=Sn(e),i=In(e),n=Boolean(1&i),s=Boolean(4&i),a=Boolean(256&i),o=Boolean(512&i),l=Boolean(1024&i),c=Boolean(2048&i),u=Cn(e);let d=t.currentFragmentState.baseDataOffset;n&&(d+=Bn(e));let h=null;s&&(h=Cn(e));let m=d;if(0===u){this.currentFragment.implicitBaseDataOffset=m;break}let f=0;const g={track:t,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1};this.currentFragment.trackData.set(t.id,g);for(let k=0;k<u;k++){let i,n,s;a?i=Cn(e):(p(null!==t.currentFragmentState.defaultSampleDuration),i=t.currentFragmentState.defaultSampleDuration),o?n=Cn(e):(p(null!==t.currentFragmentState.defaultSampleSize),n=t.currentFragmentState.defaultSampleSize),l?s=Cn(e):(p(null!==t.currentFragmentState.defaultSampleFlags),s=t.currentFragmentState.defaultSampleFlags),0===k&&null!==h&&(s=h);let u=0;c&&(u=0===r?Cn(e):Bn(e));const d=!(65536&s);g.samples.push({presentationTimestamp:f+u,duration:i,byteOffset:m,byteSize:n,isKeyFrame:d}),m+=n,f+=i}g.presentationTimestamps=g.samples.map((e,t)=>({presentationTimestamp:e.presentationTimestamp,sampleIndex:t})).sort((e,t)=>e.presentationTimestamp-t.presentationTimestamp);for(let e=0;e<g.presentationTimestamps.length;e++){const t=g.presentationTimestamps[e],r=g.samples[t.sampleIndex];if(null===g.firstKeyFrameTimestamp&&r.isKeyFrame&&(g.firstKeyFrameTimestamp=r.presentationTimestamp),e<g.presentationTimestamps.length-1){const i=g.presentationTimestamps[e+1];r.duration=i.presentationTimestamp-t.presentationTimestamp}}const b=g.samples[g.presentationTimestamps[0].sampleIndex],y=g.samples[k(g.presentationTimestamps).sampleIndex];g.startTimestamp=b.presentationTimestamp,g.endTimestamp=y.presentationTimestamp+y.duration,this.currentFragment.implicitBaseDataOffset=m}break;case"udta":{const t=this.iterateContiguousBoxes(e.slice(ae,se.contentSize));for(const{boxInfo:e,slice:r}of t){if("meta"!==e.name&&!this.currentTrack){const t=r.filePos;null!=(f=this.metadataTags).raw||(f.raw={}),"\xa9"===e.name[0]?null!=(y=this.metadataTags.raw)[T=e.name]||(y[T]=tr(r)):null!=(S=this.metadataTags.raw)[I=e.name]||(S[I]=Tn(r,e.contentSize)),r.filePos=t}switch(e.name){case"meta":r.skip(-e.headerSize),this.traverseBox(r);break;case"\xa9nam":case"name":this.currentTrack?this.currentTrack.name=w.decode(Tn(r,e.contentSize)):null!=(P=this.metadataTags).title||(P.title=tr(r));break;case"\xa9des":this.currentTrack||null!=(C=this.metadataTags).description||(C.description=tr(r));break;case"\xa9ART":this.currentTrack||null!=(B=this.metadataTags).artist||(B.artist=tr(r));break;case"\xa9alb":this.currentTrack||null!=(F=this.metadataTags).album||(F.album=tr(r));break;case"albr":this.currentTrack||null!=(D=this.metadataTags).albumArtist||(D.albumArtist=tr(r));break;case"\xa9gen":this.currentTrack||null!=(A=this.metadataTags).genre||(A.genre=tr(r));break;case"\xa9day":if(!this.currentTrack){const e=new Date(tr(r));Number.isNaN(e.getTime())||null!=(R=this.metadataTags).date||(R.date=e)}break;case"\xa9cmt":this.currentTrack||null!=(M=this.metadataTags).comment||(M.comment=tr(r));break;case"\xa9lyr":this.currentTrack||null!=(N=this.metadataTags).lyrics||(N.lyrics=tr(r))}}}break;case"meta":{if(this.currentTrack)break;const t=0!==Cn(e);this.currentMetadataKeys=new Map,t?this.readContiguousBoxes(e.slice(ae,se.contentSize)):this.readContiguousBoxes(e.slice(ae+4,se.contentSize-4)),this.currentMetadataKeys=null}break;case"keys":{if(!this.currentMetadataKeys)break;e.skip(4);const t=Cn(e);for(let r=0;r<t;r++){const t=Cn(e);e.skip(4);const i=w.decode(Tn(e,t-8));this.currentMetadataKeys.set(r+1,i)}}break;case"ilst":{if(!this.currentMetadataKeys)break;const t=this.iterateContiguousBoxes(e.slice(ae,se.contentSize));for(const{boxInfo:e,slice:r}of t){let t=e.name;const i=(t.charCodeAt(0)<<24)+(t.charCodeAt(1)<<16)+(t.charCodeAt(2)<<8)+t.charCodeAt(3);this.currentMetadataKeys.has(i)&&(t=this.currentMetadataKeys.get(i));const n=rr(r);switch(null!=(z=this.metadataTags).raw||(z.raw={}),null!=(O=this.metadataTags.raw)[t]||(O[t]=n),t){case"\xa9nam":case"titl":case"com.apple.quicktime.title":case"title":"string"===typeof n&&(null!=(L=this.metadataTags).title||(L.title=n));break;case"\xa9des":case"desc":case"dscp":case"com.apple.quicktime.description":case"description":"string"===typeof n&&(null!=(U=this.metadataTags).description||(U.description=n));break;case"\xa9ART":case"com.apple.quicktime.artist":case"artist":"string"===typeof n&&(null!=(V=this.metadataTags).artist||(V.artist=n));break;case"\xa9alb":case"albm":case"com.apple.quicktime.album":case"album":"string"===typeof n&&(null!=(q=this.metadataTags).album||(q.album=n));break;case"aART":case"album_artist":"string"===typeof n&&(null!=(H=this.metadataTags).albumArtist||(H.albumArtist=n));break;case"\xa9cmt":case"com.apple.quicktime.comment":case"comment":"string"===typeof n&&(null!=(W=this.metadataTags).comment||(W.comment=n));break;case"\xa9gen":case"gnre":case"com.apple.quicktime.genre":case"genre":"string"===typeof n&&(null!=(j=this.metadataTags).genre||(j.genre=n));break;case"\xa9lyr":case"lyrics":"string"===typeof n&&(null!=(K=this.metadataTags).lyrics||(K.lyrics=n));break;case"\xa9day":case"rldt":case"com.apple.quicktime.creationdate":case"date":if("string"===typeof n){const e=new Date(n);Number.isNaN(e.getTime())||null!=(Q=this.metadataTags).date||(Q.date=e)}break;case"covr":case"com.apple.quicktime.artwork":n instanceof fe?(null!=(G=this.metadataTags).images||(G.images=[]),this.metadataTags.images.push({data:n.data,kind:"coverFront",mimeType:n.mimeType})):n instanceof Uint8Array&&(null!=(Y=this.metadataTags).images||(Y.images=[]),this.metadataTags.images.push({data:n,kind:"coverFront",mimeType:"image/*"}));break;case"track":if("string"===typeof n){const e=n.split("/"),t=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(null!=(J=this.metadataTags).trackNumber||(J.trackNumber=t)),r&&Number.isInteger(r)&&r>0&&(null!=(Z=this.metadataTags).tracksTotal||(Z.tracksTotal=r))}break;case"trkn":if(n instanceof Uint8Array&&n.length>=6){const e=v(n),t=e.getUint16(2,!1),r=e.getUint16(4,!1);t>0&&(null!=(ee=this.metadataTags).trackNumber||(ee.trackNumber=t)),r>0&&(null!=(te=this.metadataTags).tracksTotal||(te.tracksTotal=r))}break;case"disc":case"disk":if(n instanceof Uint8Array&&n.length>=6){const e=v(n),t=e.getUint16(2,!1),r=e.getUint16(4,!1);t>0&&(null!=(re=this.metadataTags).discNumber||(re.discNumber=t)),r>0&&(null!=(ie=this.metadataTags).discsTotal||(ie.discsTotal=r))}}}}}var le,ce;return e.filePos=oe,!0}}class nr{constructor(e){this.internalTrack=e,this.packetToSampleIndex=new WeakMap,this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}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}getDisposition(){return this.internalTrack.disposition}computeDuration(){return u(this,null,function*(){var e,t;const r=yield this.getPacket(1/0,{metadataOnly:!0});return(null!=(e=null==r?void 0:r.timestamp)?e:0)+(null!=(t=null==r?void 0:r.duration)?t:0)})}getFirstTimestamp(){return u(this,null,function*(){var e;const t=yield this.getFirstPacket({metadataOnly:!0});return null!=(e=null==t?void 0:t.timestamp)?e:0})}getFirstPacket(e){return u(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 Q(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}getPacket(e,t){return u(this,null,function*(){const r=this.mapTimestampIntoTimescale(e),i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),n=or(i,r),s=yield this.fetchPacketForSampleIndex(n,t);return mr(i)&&this.internalTrack.demuxer.isFragmented?this.performFragmentedLookup(null,e=>{const t=e.trackData.get(this.internalTrack.id);if(!t)return{sampleIndex:-1,correctSampleFound:!1};const i=N(t.presentationTimestamps,r,e=>e.presentationTimestamp);return{sampleIndex:-1!==i?t.presentationTimestamps[i].sampleIndex:-1,correctSampleFound:-1!==i&&r<t.endTimestamp}},r,r,t):s})}getNextPacket(e,t){return u(this,null,function*(){const r=this.packetToSampleIndex.get(e);if(void 0!==r)return this.fetchPacketForSampleIndex(r+1,t);const i=this.packetToFragmentLocation.get(e);if(void 0===i)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(i.fragment,e=>{if(e===i.fragment){const t=e.trackData.get(this.internalTrack.id);if(i.sampleIndex+1<t.samples.length)return{sampleIndex:i.sampleIndex+1,correctSampleFound:!0}}else{if(e.trackData.get(this.internalTrack.id))return{sampleIndex:0,correctSampleFound:!0}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)})}getKeyPacket(e,t){return u(this,null,function*(){const r=this.mapTimestampIntoTimescale(e),i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),n=lr(i,r),s=yield this.fetchPacketForSampleIndex(n,t);return mr(i)&&this.internalTrack.demuxer.isFragmented?this.performFragmentedLookup(null,e=>{const t=e.trackData.get(this.internalTrack.id);if(!t)return{sampleIndex:-1,correctSampleFound:!1};const i=U(t.presentationTimestamps,e=>t.samples[e.sampleIndex].isKeyFrame&&e.presentationTimestamp<=r);return{sampleIndex:-1!==i?t.presentationTimestamps[i].sampleIndex:-1,correctSampleFound:-1!==i&&r<t.endTimestamp}},r,r,t):s})}getNextKeyPacket(e,t){return u(this,null,function*(){const r=this.packetToSampleIndex.get(e);if(void 0!==r){const e=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=ur(e,r);return this.fetchPacketForSampleIndex(i,t)}const i=this.packetToFragmentLocation.get(e);if(void 0===i)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(i.fragment,e=>{if(e===i.fragment){const t=e.trackData.get(this.internalTrack.id).samples.findIndex((e,t)=>e.isKeyFrame&&t>i.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 p(-1!==e),{sampleIndex:e,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)})}fetchPacketForSampleIndex(e,t){return u(this,null,function*(){if(-1===e)return null;const r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=cr(r,e);if(!i)return null;let n;if(t.metadataOnly)n=ut;else{let e=this.internalTrack.demuxer.reader.requestSlice(i.sampleOffset,i.sampleSize);e instanceof Promise&&(e=yield e),p(e),n=Tn(e,i.sampleSize)}const s=(i.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,a=i.duration/this.internalTrack.timescale,o=new dt(n,i.isKeyFrame?"key":"delta",s,a,e,i.sampleSize);return this.packetToSampleIndex.set(o,e),o})}fetchPacketInFragment(e,t,r){return u(this,null,function*(){if(-1===t)return null;const i=e.trackData.get(this.internalTrack.id).samples[t];let n;if(p(i),r.metadataOnly)n=ut;else{let e=this.internalTrack.demuxer.reader.requestSlice(i.byteOffset,i.byteSize);e instanceof Promise&&(e=yield e),p(e),n=Tn(e,i.byteSize)}const s=(i.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,a=i.duration/this.internalTrack.timescale,o=new dt(n,i.isKeyFrame?"key":"delta",s,a,e.moofOffset+t,i.byteSize);return this.packetToFragmentLocation.set(o,{fragment:e,sampleIndex:t}),o})}performFragmentedLookup(e,t,r,i,n){return u(this,null,function*(){var s,a,o;const l=this.internalTrack.demuxer;let c=null,u=null,d=-1;if(e){const{sampleIndex:r,correctSampleFound:i}=t(e);if(i)return this.fetchPacketInFragment(e,r,n);-1!==r&&(u=e,d=r)}const h=N(this.internalTrack.fragmentLookupTable,r,e=>e.timestamp),m=-1!==h?this.internalTrack.fragmentLookupTable[h]:null,f=N(this.internalTrack.fragmentPositionCache,r,e=>e.startTimestamp),g=-1!==f?this.internalTrack.fragmentPositionCache[f]:null,k=Math.max(null!=(s=null==m?void 0:m.moofOffset)?s:0,null!=(a=null==g?void 0:g.moofOffset)?a:0)||null;let b;for(e?null===k||e.moofOffset>=k?(b=e.moofOffset+e.moofSize,c=e):b=k:b=null!=k?k:0;;){if(c){const e=c.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>i)break}let e=l.reader.requestSliceRange(b,8,16);if(e instanceof Promise&&(e=yield e),!e)break;const r=b,s=Yt(e);if(!s)break;if("moof"===s.name){c=yield l.readFragment(r);const{sampleIndex:e,correctSampleFound:i}=t(c);if(i)return this.fetchPacketInFragment(c,e,n);-1!==e&&(u=c,d=e)}b=r+s.totalSize}if(m&&(!u||u.moofOffset<m.moofOffset)){const e=this.internalTrack.fragmentLookupTable[h-1];p(!e||e.timestamp<m.timestamp);const r=null!=(o=null==e?void 0:e.timestamp)?o:-1/0;return this.performFragmentedLookup(null,t,r,i,n)}return u?this.fetchPacketInFragment(u,d,n):null})}}class sr extends nr{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getRotation(){return this.internalTrack.rotation}getColorSpace(){return u(this,null,function*(){var e,t,r,i;return{primaries:null==(e=this.internalTrack.info.colorSpace)?void 0:e.primaries,transfer:null==(t=this.internalTrack.info.colorSpace)?void 0:t.transfer,matrix:null==(r=this.internalTrack.info.colorSpace)?void 0:r.matrix,fullRange:null==(i=this.internalTrack.info.colorSpace)?void 0:i.fullRange}})}canBeTransparent(){return u(this,null,function*(){return!1})}getDecoderConfig(){return u(this,null,function*(){var e;return this.internalTrack.info.codec?null!=(e=this.decoderConfigPromise)?e:this.decoderConfigPromise=(()=>u(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&&et(e.data)}}else{const e=yield this.getFirstPacket({});this.internalTrack.info.vp9CodecInfo=e&&Je(e.data)}return{codec:Se(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}}))():null})}}class ar extends nr{constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}getDecoderConfig(){return u(this,null,function*(){var e,t;return this.internalTrack.info.codec?null!=(t=this.decoderConfig)?t:this.decoderConfig={codec:ve(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:null!=(e=this.internalTrack.info.codecDescription)?e:void 0}:null})}}const or=(e,t)=>{if(e.presentationTimestamps){const r=N(e.presentationTimestamps,t,e=>e.presentationTimestamp);return-1===r?-1:e.presentationTimestamps[r].sampleIndex}{const r=N(e.sampleTimingEntries,t,e=>e.startDecodeTimestamp);if(-1===r)return-1;const i=e.sampleTimingEntries[r];return i.startIndex+Math.min(Math.floor((t-i.startDecodeTimestamp)/i.delta),i.count-1)}},lr=(e,t)=>{var r;if(!e.keySampleIndices)return or(e,t);if(e.presentationTimestamps){const r=N(e.presentationTimestamps,t,e=>e.presentationTimestamp);if(-1===r)return-1;for(let t=r;t>=0;t--){const r=e.presentationTimestamps[t].sampleIndex;if(-1!==M(e.keySampleIndices,r,e=>e))return r}return-1}{const i=or(e,t),n=N(e.keySampleIndices,i,e=>e);return null!=(r=e.keySampleIndices[n])?r:-1}},cr=(e,t)=>{const r=N(e.sampleTimingEntries,t,e=>e.startIndex),i=e.sampleTimingEntries[r];if(!i||i.startIndex+i.count<=t)return null;let n=i.startDecodeTimestamp+(t-i.startIndex)*i.delta;const s=N(e.sampleCompositionTimeOffsets,t,e=>e.startIndex),a=e.sampleCompositionTimeOffsets[s];a&&t-a.startIndex<a.count&&(n+=a.offset);const o=e.sampleSizes[Math.min(t,e.sampleSizes.length-1)],l=N(e.sampleToChunk,t,e=>e.startSampleIndex),c=e.sampleToChunk[l];p(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 m=0,f=d;if(1===e.sampleSizes.length)f+=o*(t-h),m+=o*c.samplesPerChunk;else for(let p=h;p<h+c.samplesPerChunk;p++){const r=e.sampleSizes[p];p<t&&(f+=r),m+=r}let g=i.delta;if(e.presentationTimestamps){const r=e.presentationTimestampIndexMap[t];if(p(void 0!==r),r<e.presentationTimestamps.length-1){g=e.presentationTimestamps[r+1].presentationTimestamp-n}}return{presentationTimestamp:n,duration:g,sampleOffset:f,sampleSize:o,chunkOffset:d,chunkSize:m,isKeyFrame:!e.keySampleIndices||-1!==M(e.keySampleIndices,t,e=>e)}},ur=(e,t)=>{var r;if(!e.keySampleIndices)return t+1;const i=N(e.keySampleIndices,t,e=>e);return null!=(r=e.keySampleIndices[i+1])?r:-1},dr=(e,t)=>{e.startTimestamp+=t,e.endTimestamp+=t;for(const r of e.samples)r.presentationTimestamp+=t;for(const r of e.presentationTimestamps)r.presentationTimestamp+=t},hr=e=>{const[t,,,r]=e,i=Math.hypot(t,r),n=t/i,s=r/i,a=-Math.atan2(s,n)*(180/Math.PI);return Number.isFinite(a)?a:0},mr=e=>0===e.sampleSizes.length;
|
|
/*!
|
|
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
*
|
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
*/
|
|
var fr,pr;(pr=fr||(fr={}))[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.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=[fr.EBML,fr.Segment],kr=[fr.SeekHead,fr.Info,fr.Cluster,fr.Tracks,fr.Cues,fr.Attachments,fr.Chapters,fr.Tags],br=[...gr,...kr],yr=16,Tr=e=>{if(e.remainingLength<1)return null;const t=Sn(e);if(e.skip(-1),0===t)return null;let r=1,i=128;for(;0===(t&i);)r++,i>>=1;return e.remainingLength<r?null:r},Sr=e=>{if(e.remainingLength<1)return null;const t=Sn(e);if(0===t)return null;let r=1,i=128;for(;0===(t&i);)r++,i>>=1;if(e.remainingLength<r-1)return null;let n=t&i-1;for(let s=1;s<r;s++)n*=256,n+=Sn(e);return n},vr=(e,t)=>{if(t<1||t>8)throw new Error("Bad unsigned int size "+t);let r=0;for(let i=0;i<t;i++)r*=256,r+=Sn(e);return r},wr=e=>{const t=Tr(e);if(null===t)return null;if(e.remainingLength<t)return null;return vr(e,t)},Ir=e=>{if(e.remainingLength<1)return null;if(255===Sn(e))return;e.skip(-1);const t=Sr(e);return null===t?null:72057594037927940!==t?t:void 0},Pr=e=>{p(e.remainingLength>=2);const t=wr(e);if(null===t)return null;const r=Ir(e);return null===r?null:{id:t,size:r}},xr=(e,t)=>{const r=Tn(e,t);let i=0;for(;i<t&&0!==r[i];)i+=1;return String.fromCharCode(...r.subarray(0,i))},Cr=(e,t)=>{const r=Tn(e,t);let i=0;for(;i<t&&0!==r[i];)i+=1;return w.decode(r.subarray(0,i))},_r=(e,t)=>{if(0===t)return 0;if(4!==t&&8!==t)throw new Error("Bad float size "+t);return 4===t?Rn(e):Mn(e)},Br=(e,t,r,i)=>u(null,null,function*(){const n=new Set(r);let s=t;for(;null===i||s<i;){let t=e.requestSliceRange(s,2,yr);if(t instanceof Promise&&(t=yield t),!t)break;const r=Pr(t);if(!r)break;if(n.has(r.id))return{pos:s,found:!0};Vr(r.size),s=t.filePos+r.size}return{pos:null!==i&&i>s?i:s,found:!1}}),Er=(e,t,r,i)=>u(null,null,function*(){const n=o(2,16),s=new Set(r);let a=t;for(;a<i;){let t=e.requestSliceRange(a,0,Math.min(n,i-a));if(t instanceof Promise&&(t=yield t),!t)break;if(t.length<8)break;for(let e=0;e<t.length-8;e++){t.filePos=a;const e=wr(t);if(null!==e&&s.has(e))return a;a++}}return null}),Fr="V_MPEG4/ISO/AVC",Dr="V_MPEGH/ISO/HEVC",Ar="V_VP8",Rr="V_VP9",Mr="V_AV1",Nr="A_AAC",zr="A_MPEG/L3",Or="A_OPUS",Lr="A_VORBIS",Ur="A_FLAC";function Vr(e){if(void 0===e)throw new Error("Undefined element size is used in a place where it is not supported.")}
|
|
/*!
|
|
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
*
|
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
*/
|
|
/*!
|
|
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
*
|
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
*/
|
|
var qr,Hr,Wr,jr,Kr,$r;(Hr=qr||(qr={}))[Hr.None=0]="None",Hr[Hr.Xiph=1]="Xiph",Hr[Hr.FixedSize=2]="FixedSize",Hr[Hr.Ebml=3]="Ebml",(jr=Wr||(Wr={}))[jr.Block=1]="Block",jr[jr.Private=2]="Private",jr[jr.Next=4]="Next",($r=Kr||(Kr={}))[$r.Zlib=0]="Zlib",$r[$r.Bzlib=1]="Bzlib",$r[$r.lzo1x=2]="lzo1x",$r[$r.HeaderStripping=3]="HeaderStripping";const Qr=[{id:fr.SeekHead,flag:"seekHeadSeen"},{id:fr.Info,flag:"infoSeen"},{id:fr.Tracks,flag:"tracksSeen"},{id:fr.Cues,flag:"cuesSeen"}],Gr=10*o(2,20);class Xr extends ot{constructor(e){super(e),this.readMetadataPromise=null,this.segments=[],this.currentSegment=null,this.currentTrack=null,this.currentCluster=null,this.currentBlock=null,this.currentBlockAdditional=null,this.currentCueTime=null,this.currentDecodingInstruction=null,this.currentTagTargetIsMovie=!0,this.currentSimpleTagName=null,this.currentAttachedFile=null,this.isWebM=!1,this.reader=e._reader}computeDuration(){return u(this,null,function*(){const e=yield this.getTracks(),t=yield Promise.all(e.map(e=>e.computeDuration()));return Math.max(0,...t)})}getTracks(){return u(this,null,function*(){return yield this.readMetadata(),this.segments.flatMap(e=>e.tracks.map(e=>e.inputTrack))})}getMimeType(){return u(this,null,function*(){yield this.readMetadata();const e=yield this.getTracks(),t=yield Promise.all(e.map(e=>e.getCodecParameterString()));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 u(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=(()=>u(this,null,function*(){let e=0;for(;;){let t=this.reader.requestSliceRange(e,2,yr);if(t instanceof Promise&&(t=yield t),!t)break;const r=Pr(t);if(!r)break;const i=r.id;let n=r.size;const s=t.filePos;if(i===fr.EBML){Vr(n);let e=this.reader.requestSlice(s,n);if(e instanceof Promise&&(e=yield e),!e)break;this.readContiguousElements(e)}else if(i===fr.Segment){if(yield this.readSegment(s,n),void 0===n)break;if(null===this.reader.fileSize)break}else if(i===fr.Cluster){if(null===this.reader.fileSize)break;if(void 0===n){n=(yield Br(this.reader,s,br,this.reader.fileSize)).pos-s}const e=k(this.segments);e&&(e.elementEndPos=s+n)}Vr(n),e=s+n}}))()}readSegment(e,t){return u(this,null,function*(){var r;this.currentSegment={seekHeadSeen:!1,infoSeen:!1,tracksSeen:!1,cuesSeen:!1,tagsSeen:!1,attachmentsSeen:!1,timestampScale:-1,timestampFactor:-1,duration:-1,seekEntries:[],tracks:[],cuePoints:[],dataStartPos:e,elementEndPos:void 0===t?null:e+t,clusterSeekStartPos:e,lastReadCluster:null,metadataTags:{},metadataTagsCollected:!1},this.segments.push(this.currentSegment);let i=e;for(;null===this.currentSegment.elementEndPos||i<this.currentSegment.elementEndPos;){let e=this.reader.requestSliceRange(i,2,yr);if(e instanceof Promise&&(e=yield e),!e)break;const t=i,n=Pr(e);if(!n||!kr.includes(n.id)&&n.id!==fr.Void){const e=yield Er(this.reader,t,kr,Math.min(null!=(r=this.currentSegment.elementEndPos)?r:1/0,t+Gr));if(e){i=e;continue}break}const{id:s,size:a}=n,o=e.filePos,l=Qr.findIndex(e=>e.id===s);if(-1!==l){const e=Qr[l].flag;this.currentSegment[e]=!0,Vr(a);let t=this.reader.requestSlice(o,a);t instanceof Promise&&(t=yield t),t&&this.readContiguousElements(t)}else if(s===fr.Tags||s===fr.Attachments){s===fr.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,Vr(a);let e=this.reader.requestSlice(o,a);e instanceof Promise&&(e=yield e),e&&this.readContiguousElements(e)}else if(s===fr.Cluster){this.currentSegment.clusterSeekStartPos=t;break}if(void 0===a)break;i=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 r=Qr.find(e=>e.id===t.id);if(!r)continue;if(this.currentSegment[r.flag])continue;let i=this.reader.requestSliceRange(e+t.segmentPosition,2,yr);if(i instanceof Promise&&(i=yield i),!i)continue;const n=Pr(i);if(!n)continue;const{id:s,size:a}=n;if(s!==r.id)continue;Vr(a),this.currentSegment[r.flag]=!0;let o=this.reader.requestSlice(i.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);this.currentSegment.tracks.sort((e,t)=>Number(t.disposition.default)-Number(e.disposition.default));const n=new Map(this.currentSegment.tracks.map(e=>[e.id,e]));for(const e of this.currentSegment.cuePoints){const t=n.get(e.trackId);t&&t.cuePoints.push(e)}for(const e of this.currentSegment.tracks){e.cuePoints.sort((e,t)=>e.time-t.time);for(let t=0;t<e.cuePoints.length-1;t++){const r=e.cuePoints[t],i=e.cuePoints[t+1];r.time===i.time&&(e.cuePoints.splice(t+1,1),t--)}}let s=null,a=-1/0;for(const e of this.currentSegment.tracks)e.cuePoints.length>a&&(a=e.cuePoints.length,s=e);for(const e of this.currentSegment.tracks)0===e.cuePoints.length&&(e.cuePoints=s.cuePoints);this.currentSegment=null})}readCluster(e,t){return u(this,null,function*(){var r;if((null==(r=t.lastReadCluster)?void 0:r.elementStartPos)===e)return t.lastReadCluster;let i=this.reader.requestSliceRange(e,2,yr);i instanceof Promise&&(i=yield i),p(i);const n=e,s=Pr(i);p(s);p(s.id===fr.Cluster);let a=s.size;const o=i.filePos;if(void 0===a){a=(yield Br(this.reader,o,br,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,br);c.elementEndPos=e}for(const[,e]of c.trackData){const t=e.track;p(e.blocks.length>0);let r=!1;for(let n=0;n<e.blocks.length;n++){const t=e.blocks[n];t.timestamp+=c.timestamp,r||(r=t.lacing!==qr.None)}e.presentationTimestamps=e.blocks.map((e,t)=>({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp);for(let n=0;n<e.presentationTimestamps.length;n++){const r=e.presentationTimestamps[n],i=e.blocks[r.blockIndex];if(null===e.firstKeyFrameTimestamp&&i.isKeyFrame&&(e.firstKeyFrameTimestamp=i.timestamp),n<e.presentationTimestamps.length-1){const t=e.presentationTimestamps[n+1];i.duration=t.timestamp-i.timestamp}else 0===i.duration&&null!=t.defaultDuration&&i.lacing===qr.None&&(i.duration=t.defaultDuration)}r&&(this.expandLacedBlocks(e.blocks,t),e.presentationTimestamps=e.blocks.map((e,t)=>({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp));const i=e.blocks[e.presentationTimestamps[0].blockIndex],s=e.blocks[k(e.presentationTimestamps).blockIndex];e.startTimestamp=i.timestamp,e.endTimestamp=s.timestamp+s.duration;const a=N(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 r=e.trackData.get(t);if(!r){const i=e.segment.tracks.find(e=>e.id===t);if(!i)return null;r={track:i,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},e.trackData.set(t,r)}return r}expandLacedBlocks(e,t){var r;for(let i=0;i<e.length;i++){const n=e[i];if(n.lacing===qr.None)continue;n.decoded||(n.data=this.decodeBlockData(t,n.data),n.decoded=!0);const s=bn.tempFromBytes(n.data),a=[],o=Sn(s)+1;switch(n.lacing){case qr.Xiph:{let e=0;for(let t=0;t<o-1;t++){let t=0;for(;s.bufferPos<s.length;){const r=Sn(s);if(t+=r,r<255){a.push(t),e+=t;break}}}a.push(s.length-(s.bufferPos+e))}break;case qr.FixedSize:{const e=s.length-1,t=Math.floor(e/o);for(let r=0;r<o;r++)a.push(t)}break;case qr.Ebml:{const e=Sr(s);p(null!==e);let t=e;a.push(t);let r=t;for(let i=1;i<o-1;i++){const e=s.bufferPos,i=Sr(s);p(null!==i);t+=i-((1<<7*(s.bufferPos-e)-1)-1),a.push(t),r+=t}a.push(s.length-(s.bufferPos+r))}break;default:p(!1)}p(a.length===o),e.splice(i,1);const l=n.duration||o*(null!=(r=t.defaultDuration)?r:0);for(let t=0;t<o;t++){const r=a[t],c=Tn(s,r),u=n.timestamp+l*t/o,d=l/o;e.splice(i+t,0,{timestamp:u,duration:d,isKeyFrame:n.isKeyFrame,data:c,lacing:qr.None,decoded:!0,mainAdditional:n.mainAdditional})}i+=o,i--}}loadSegmentMetadata(e){return u(this,null,function*(){for(const t of e.seekEntries){if(t.id!==fr.Tags||e.tagsSeen){if(t.id!==fr.Attachments||e.attachmentsSeen)continue}else;let r=this.reader.requestSliceRange(e.dataStartPos+t.segmentPosition,2,yr);if(r instanceof Promise&&(r=yield r),!r)continue;const i=Pr(r);if(!i||i.id!==t.id)continue;const{size:n}=i;Vr(n),p(!this.currentSegment),this.currentSegment=e;let s=this.reader.requestSlice(r.filePos,n);s instanceof Promise&&(s=yield s),s&&this.readContiguousElements(s),this.currentSegment=null,t.id===fr.Tags?e.tagsSeen=!0:t.id===fr.Attachments&&(e.attachmentsSeen=!0)}})}readContiguousElements(e,t){for(;e.remainingLength>=2;){const r=e.filePos;if(!this.traverseElement(e,t))return r}return e.filePos}traverseElement(e,t){var r,i,n,s,a,o,l,u,d,h,m,f,k,b,y,T,S,v,w,I,P,C,B,F,D,A,R,M,N,z,O,L,U,V,q,H,W,j,K,Q,G,Y,J,Z,ee,te,re,ie;const ne=Pr(e);if(!ne)return!1;if(t&&t.includes(ne.id))return!1;const{id:se,size:ae}=ne,oe=e.filePos;switch(Vr(ae),se){case fr.DocType:this.isWebM="webm"===xr(e,ae);break;case fr.Seek:{if(!this.currentSegment)break;const t={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(t),this.readContiguousElements(e.slice(oe,ae)),-1!==t.id&&-1!==t.segmentPosition||this.currentSegment.seekEntries.pop()}break;case fr.SeekID:{const t=null==(r=this.currentSegment)?void 0:r.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.id=vr(e,ae)}break;case fr.SeekPosition:{const t=null==(i=this.currentSegment)?void 0:i.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.segmentPosition=vr(e,ae)}break;case fr.TimestampScale:if(!this.currentSegment)break;this.currentSegment.timestampScale=vr(e,ae),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale;break;case fr.Duration:if(!this.currentSegment)break;this.currentSegment.duration=_r(e,ae);break;case fr.TrackEntry:if(!this.currentSegment)break;if(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:c({},ge),inputTrack:null,codecId:null,codecPrivate:null,defaultDuration:null,defaultDurationNs:null,name:null,languageCode:$,decodingInstructions:[],info:null},this.readContiguousElements(e.slice(oe,ae)),!this.currentTrack)break;if(this.currentTrack.decodingInstructions.some(e=>{var t;return"decompress"!==(null==(t=e.data)?void 0:t.type)||e.scope!==Wr.Block||e.data.algorithm!==Kr.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){this.currentTrack.codecId===Fr?(this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===Dr?(this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Ar?this.currentTrack.info.codec="vp8":t===Rr?this.currentTrack.info.codec="vp9":t===Mr&&(this.currentTrack.info.codec="av1");const e=this.currentTrack,r=new Gt(this.input,new Jr(e));this.currentTrack.inputTrack=r,this.currentSegment.tracks.push(this.currentTrack)}else if("audio"===this.currentTrack.info.type&&-1!==this.currentTrack.info.numberOfChannels&&-1!==this.currentTrack.info.sampleRate){t===Nr?(this.currentTrack.info.codec="aac",this.currentTrack.info.aacCodecInfo={isMpeg2:this.currentTrack.codecId.includes("MPEG2")},this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===zr?this.currentTrack.info.codec="mp3":t===Or?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=xe):t===Lr?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Ur?(this.currentTrack.info.codec="flac",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,r=new Xt(this.input,new Zr(e));this.currentTrack.inputTrack=r,this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null;break;case fr.TrackNumber:if(!this.currentTrack)break;this.currentTrack.id=vr(e,ae);break;case fr.TrackType:{if(!this.currentTrack)break;const t=vr(e,ae);1===t?this.currentTrack.info={type:"video",width:-1,height:-1,rotation:0,codec:null,codecDescription:null,colorSpace:null,alphaMode:!1}:2===t&&(this.currentTrack.info={type:"audio",numberOfChannels:-1,sampleRate:-1,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case fr.FlagEnabled:if(!this.currentTrack)break;vr(e,ae)||(this.currentTrack=null);break;case fr.FlagDefault:if(!this.currentTrack)break;this.currentTrack.disposition.default=!!vr(e,ae);break;case fr.FlagForced:if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!vr(e,ae);break;case fr.FlagOriginal:if(!this.currentTrack)break;this.currentTrack.disposition.original=!!vr(e,ae);break;case fr.FlagHearingImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!vr(e,ae);break;case fr.FlagVisualImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!vr(e,ae);break;case fr.FlagCommentary:if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!vr(e,ae);break;case fr.CodecID:if(!this.currentTrack)break;this.currentTrack.codecId=xr(e,ae);break;case fr.CodecPrivate:if(!this.currentTrack)break;this.currentTrack.codecPrivate=Tn(e,ae);break;case fr.DefaultDuration:if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=vr(e,ae);break;case fr.Name:if(!this.currentTrack)break;this.currentTrack.name=Cr(e,ae);break;case fr.Language:if(!this.currentTrack)break;if(this.currentTrack.languageCode!==$)break;this.currentTrack.languageCode=xr(e,ae),X(this.currentTrack.languageCode)||(this.currentTrack.languageCode=$);break;case fr.LanguageBCP47:{if(!this.currentTrack)break;const t=xr(e,ae).split("-")[0];this.currentTrack.languageCode=t||$}break;case fr.Video:if("video"!==(null==(s=null==(n=this.currentTrack)?void 0:n.info)?void 0:s.type))break;this.readContiguousElements(e.slice(oe,ae));break;case fr.PixelWidth:if("video"!==(null==(o=null==(a=this.currentTrack)?void 0:a.info)?void 0:o.type))break;this.currentTrack.info.width=vr(e,ae);break;case fr.PixelHeight:if("video"!==(null==(u=null==(l=this.currentTrack)?void 0:l.info)?void 0:u.type))break;this.currentTrack.info.height=vr(e,ae);break;case fr.AlphaMode:if("video"!==(null==(h=null==(d=this.currentTrack)?void 0:d.info)?void 0:h.type))break;this.currentTrack.info.alphaMode=1===vr(e,ae);break;case fr.Colour:if("video"!==(null==(f=null==(m=this.currentTrack)?void 0:m.info)?void 0:f.type))break;this.currentTrack.info.colorSpace={},this.readContiguousElements(e.slice(oe,ae));break;case fr.MatrixCoefficients:{if("video"!==(null==(b=null==(k=this.currentTrack)?void 0:k.info)?void 0:b.type)||!this.currentTrack.info.colorSpace)break;const t=vr(e,ae),r=null!=(y=E[t])?y:null;this.currentTrack.info.colorSpace.matrix=r}break;case fr.Range:if("video"!==(null==(S=null==(T=this.currentTrack)?void 0:T.info)?void 0:S.type)||!this.currentTrack.info.colorSpace)break;this.currentTrack.info.colorSpace.fullRange=2===vr(e,ae);break;case fr.TransferCharacteristics:{if("video"!==(null==(w=null==(v=this.currentTrack)?void 0:v.info)?void 0:w.type)||!this.currentTrack.info.colorSpace)break;const t=vr(e,ae),r=null!=(I=_[t])?I:null;this.currentTrack.info.colorSpace.transfer=r}break;case fr.Primaries:{if("video"!==(null==(C=null==(P=this.currentTrack)?void 0:P.info)?void 0:C.type)||!this.currentTrack.info.colorSpace)break;const t=vr(e,ae),r=null!=(B=x[t])?B:null;this.currentTrack.info.colorSpace.primaries=r}break;case fr.Projection:if("video"!==(null==(D=null==(F=this.currentTrack)?void 0:F.info)?void 0:D.type))break;this.readContiguousElements(e.slice(oe,ae));break;case fr.ProjectionPoseRoll:{if("video"!==(null==(R=null==(A=this.currentTrack)?void 0:A.info)?void 0:R.type))break;const t=-_r(e,ae);try{this.currentTrack.info.rotation=g(t)}catch(le){}}break;case fr.Audio:if("audio"!==(null==(N=null==(M=this.currentTrack)?void 0:M.info)?void 0:N.type))break;this.readContiguousElements(e.slice(oe,ae));break;case fr.SamplingFrequency:if("audio"!==(null==(O=null==(z=this.currentTrack)?void 0:z.info)?void 0:O.type))break;this.currentTrack.info.sampleRate=_r(e,ae);break;case fr.Channels:if("audio"!==(null==(U=null==(L=this.currentTrack)?void 0:L.info)?void 0:U.type))break;this.currentTrack.info.numberOfChannels=vr(e,ae);break;case fr.BitDepth:if("audio"!==(null==(q=null==(V=this.currentTrack)?void 0:V.info)?void 0:q.type))break;this.currentTrack.info.bitDepth=vr(e,ae);break;case fr.CuePoint:if(!this.currentSegment)break;this.readContiguousElements(e.slice(oe,ae)),this.currentCueTime=null;break;case fr.CueTime:this.currentCueTime=vr(e,ae);break;case fr.CueTrackPositions:{if(null===this.currentCueTime)break;p(this.currentSegment);const t={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(t),this.readContiguousElements(e.slice(oe,ae)),-1!==t.trackId&&-1!==t.clusterPosition||this.currentSegment.cuePoints.pop()}break;case fr.CueTrack:{const t=null==(H=this.currentSegment)?void 0:H.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;t.trackId=vr(e,ae)}break;case fr.CueClusterPosition:{const t=null==(W=this.currentSegment)?void 0:W.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;p(this.currentSegment),t.clusterPosition=this.currentSegment.dataStartPos+vr(e,ae)}break;case fr.Timestamp:if(!this.currentCluster)break;this.currentCluster.timestamp=vr(e,ae);break;case fr.SimpleBlock:{if(!this.currentCluster)break;const t=Sr(e);if(null===t)break;const r=this.getTrackDataInCluster(this.currentCluster,t);if(!r)break;const i=Pn(e),n=Sn(e),s=n>>1&3;let a=!!(128&n);"audio"===(null==(j=r.track.info)?void 0:j.type)&&r.track.info.codec&&(a=!0);const o=Tn(e,ae-(e.filePos-oe)),l=r.track.decodingInstructions.length>0;r.blocks.push({timestamp:i,duration:0,isKeyFrame:a,data:o,lacing:s,decoded:!l,mainAdditional:null})}break;case fr.BlockGroup:if(!this.currentCluster)break;this.readContiguousElements(e.slice(oe,ae)),this.currentBlock=null;break;case fr.Block:{if(!this.currentCluster)break;const t=Sr(e);if(null===t)break;const r=this.getTrackDataInCluster(this.currentCluster,t);if(!r)break;const i=Pn(e),n=Sn(e)>>1&3,s=Tn(e,ae-(e.filePos-oe)),a=r.track.decodingInstructions.length>0;this.currentBlock={timestamp:i,duration:0,isKeyFrame:!0,data:s,lacing:n,decoded:!a,mainAdditional:null},r.blocks.push(this.currentBlock)}break;case fr.BlockAdditions:this.readContiguousElements(e.slice(oe,ae));break;case fr.BlockMore:if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(oe,ae)),this.currentBlockAdditional.data&&1===this.currentBlockAdditional.addId&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null;break;case fr.BlockAdditional:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=Tn(e,ae);break;case fr.BlockAddID:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=vr(e,ae);break;case fr.BlockDuration:if(!this.currentBlock)break;this.currentBlock.duration=vr(e,ae);break;case fr.ReferenceBlock:if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1;break;case fr.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(oe,ae));break;case fr.Targets:this.readContiguousElements(e.slice(oe,ae));break;case fr.TargetTypeValue:50!==vr(e,ae)&&(this.currentTagTargetIsMovie=!1);break;case fr.TagTrackUID:case fr.TagEditionUID:case fr.TagChapterUID:case fr.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case fr.SimpleTag:if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(oe,ae));break;case fr.TagName:this.currentSimpleTagName=Cr(e,ae);break;case fr.TagString:{if(!this.currentSimpleTagName)break;const t=Cr(e,ae);this.processTagValue(this.currentSimpleTagName,t)}break;case fr.TagBinary:{if(!this.currentSimpleTagName)break;const t=Tn(e,ae);this.processTagValue(this.currentSimpleTagName,t)}break;case fr.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(oe,ae));const t=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(null!=t.raw||(t.raw={}),t.raw[this.currentAttachedFile.fileUid.toString()]=new pe(this.currentAttachedFile.fileData,null!=(K=this.currentAttachedFile.fileMediaType)?K:void 0,null!=(Q=this.currentAttachedFile.fileName)?Q:void 0,null!=(G=this.currentAttachedFile.fileDescription)?G:void 0)),(null==(Y=this.currentAttachedFile.fileMediaType)?void 0:Y.startsWith("image/"))&&this.currentAttachedFile.fileData){const e=this.currentAttachedFile.fileName;let r="unknown";if(e){const t=e.toLowerCase();t.startsWith("cover.")?r="coverFront":t.startsWith("back.")&&(r="coverBack")}null!=t.images||(t.images=[]),t.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:r,name:null!=(J=this.currentAttachedFile.fileName)?J:void 0,description:null!=(Z=this.currentAttachedFile.fileDescription)?Z:void 0})}this.currentAttachedFile=null}break;case fr.FileUID:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=((e,t)=>{if(t<1)throw new Error("Bad unsigned int size "+t);let r=BigInt("0");for(let i=0;i<t;i++)r<<=BigInt("8"),r+=BigInt(Sn(e));return r})(e,ae);break;case fr.FileName:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=Cr(e,ae);break;case fr.FileMediaType:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=xr(e,ae);break;case fr.FileData:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=Tn(e,ae);break;case fr.FileDescription:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=Cr(e,ae);break;case fr.ContentEncodings:if(!this.currentTrack)break;this.readContiguousElements(e.slice(oe,ae)),this.currentTrack.decodingInstructions.sort((e,t)=>t.order-e.order);break;case fr.ContentEncoding:this.currentDecodingInstruction={order:0,scope:Wr.Block,data:null},this.readContiguousElements(e.slice(oe,ae)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case fr.ContentEncodingOrder:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=vr(e,ae);break;case fr.ContentEncodingScope:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=vr(e,ae);break;case fr.ContentCompression:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:Kr.Zlib,settings:null},this.readContiguousElements(e.slice(oe,ae));break;case fr.ContentCompAlgo:if("decompress"!==(null==(te=null==(ee=this.currentDecodingInstruction)?void 0:ee.data)?void 0:te.type))break;this.currentDecodingInstruction.data.algorithm=vr(e,ae);break;case fr.ContentCompSettings:if("decompress"!==(null==(ie=null==(re=this.currentDecodingInstruction)?void 0:re.data)?void 0:ie.type))break;this.currentDecodingInstruction.data.settings=Tn(e,ae);break;case fr.ContentEncryption:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}return e.filePos=oe+ae,!0}decodeBlockData(e,t){p(e.decodingInstructions.length>0);let r=t;for(const i of e.decodingInstructions)if(p(i.data),"decompress"===i.data.type)if(i.data.algorithm===Kr.HeaderStripping)if(i.data.settings&&i.data.settings.length>0){const e=i.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 r,i;if(!(null==(r=this.currentSegment)?void 0:r.metadataTags))return;const n=this.currentSegment.metadataTags;if(null!=n.raw||(n.raw={}),null!=(i=n.raw)[e]||(i[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("/"),r=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(r)&&r>0&&(null!=n.trackNumber||(n.trackNumber=r)),i&&Number.isInteger(i)&&i>0&&(null!=n.tracksTotal||(n.tracksTotal=i))}break;case"disc_number":case"disc":{const e=t.split("/"),r=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(r)&&r>0&&(null!=n.discNumber||(n.discNumber=r)),i&&Number.isInteger(i)&&i>0&&(null!=n.discsTotal||(n.discsTotal=i))}}}}class Yr{constructor(e){this.internalTrack=e,this.packetToClusterLocation=new WeakMap}getId(){return this.internalTrack.id}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.codecId}computeDuration(){return u(this,null,function*(){var e,t;const r=yield this.getPacket(1/0,{metadataOnly:!0});return(null!=(e=null==r?void 0:r.timestamp)?e:0)+(null!=(t=null==r?void 0:r.duration)?t:0)})}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getFirstTimestamp(){return u(this,null,function*(){var e;const t=yield this.getFirstPacket({metadataOnly:!0});return null!=(e=null==t?void 0:t.timestamp)?e:0})}getTimeResolution(){return this.internalTrack.segment.timestampFactor}getDisposition(){return this.internalTrack.disposition}getFirstPacket(e){return u(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 Q(e*this.internalTrack.segment.timestampFactor)}getPacket(e,t){return u(this,null,function*(){const r=this.intoTimescale(e);return this.performClusterLookup(null,e=>{const t=e.trackData.get(this.internalTrack.id);if(!t)return{blockIndex:-1,correctBlockFound:!1};const i=N(t.presentationTimestamps,r,e=>e.timestamp);return{blockIndex:-1!==i?t.presentationTimestamps[i].blockIndex:-1,correctBlockFound:-1!==i&&r<t.endTimestamp}},r,r,t)})}getNextPacket(e,t){return u(this,null,function*(){const r=this.packetToClusterLocation.get(e);if(void 0===r)throw new Error("Packet was not created from this track.");return this.performClusterLookup(r.cluster,e=>{if(e===r.cluster){const t=e.trackData.get(this.internalTrack.id);if(r.blockIndex+1<t.blocks.length)return{blockIndex:r.blockIndex+1,correctBlockFound:!0}}else{if(e.trackData.get(this.internalTrack.id))return{blockIndex:0,correctBlockFound:!0}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)})}getKeyPacket(e,t){return u(this,null,function*(){const r=this.intoTimescale(e);return this.performClusterLookup(null,e=>{const t=e.trackData.get(this.internalTrack.id);if(!t)return{blockIndex:-1,correctBlockFound:!1};const i=U(t.presentationTimestamps,e=>t.blocks[e.blockIndex].isKeyFrame&&e.timestamp<=r);return{blockIndex:-1!==i?t.presentationTimestamps[i].blockIndex:-1,correctBlockFound:-1!==i&&r<t.endTimestamp}},r,r,t)})}getNextKeyPacket(e,t){return u(this,null,function*(){const r=this.packetToClusterLocation.get(e);if(void 0===r)throw new Error("Packet was not created from this track.");return this.performClusterLookup(r.cluster,e=>{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 p(-1!==e),{blockIndex:e,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)})}fetchPacketInCluster(e,t,r){return u(this,null,function*(){var i;if(-1===t)return null;const n=e.trackData.get(this.internalTrack.id).blocks[t];p(n),n.decoded||(n.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,n.data),n.decoded=!0);const s=r.metadataOnly?ut:n.data,a=n.timestamp/this.internalTrack.segment.timestampFactor,o=n.duration/this.internalTrack.segment.timestampFactor,l={};n.mainAdditional&&"video"===(null==(i=this.internalTrack.info)?void 0:i.type)&&this.internalTrack.info.alphaMode&&(l.alpha=r.metadataOnly?ut:n.mainAdditional,l.alphaByteLength=n.mainAdditional.byteLength);const c=new dt(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,r,i,n){return u(this,null,function*(){var s,a,o,l;const{demuxer:c,segment:u}=this.internalTrack;let d=null,h=null,m=-1;if(e){const{blockIndex:r,correctBlockFound:i}=t(e);if(i)return this.fetchPacketInCluster(e,r,n);-1!==r&&(h=e,m=r)}const f=N(this.internalTrack.cuePoints,r,e=>e.time),g=-1!==f?this.internalTrack.cuePoints[f]:null,k=N(this.internalTrack.clusterPositionCache,r,e=>e.startTimestamp),b=-1!==k?this.internalTrack.clusterPositionCache[k]:null,y=Math.max(null!=(s=null==g?void 0:g.clusterPosition)?s:0,null!=(a=null==b?void 0:b.elementStartPos)?a:0)||null;let T;for(e?null===y||e.elementStartPos>=y?(T=e.elementEndPos,d=e):T=y:T=null!=y?y:u.clusterSeekStartPos;null===u.elementEndPos||T<=u.elementEndPos-2;){if(d){const e=d.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>i)break}let e=c.reader.requestSliceRange(T,2,yr);if(e instanceof Promise&&(e=yield e),!e)break;const r=T,s=Pr(e);if(!s||!kr.includes(s.id)&&s.id!==fr.Void){const e=yield Er(c.reader,r,kr,Math.min(null!=(o=u.elementEndPos)?o:1/0,r+Gr));if(e){T=e;continue}break}const a=s.id;let l=s.size;const f=e.filePos;if(a===fr.Cluster){d=yield c.readCluster(r,u),l=d.elementEndPos-f;const{blockIndex:e,correctBlockFound:i}=t(d);if(i)return this.fetchPacketInCluster(d,e,n);-1!==e&&(h=d,m=e)}if(void 0===l){p(a!==fr.Cluster);l=(yield Br(c.reader,f,br,u.elementEndPos)).pos-f}const g=f+l;if(null===u.elementEndPos){let e=c.reader.requestSliceRange(g,2,yr);if(e instanceof Promise&&(e=yield e),!e)break;if(wr(e)===fr.Segment){u.elementEndPos=g;break}}T=g}if(g&&(!h||h.elementStartPos<g.clusterPosition)){const e=this.internalTrack.cuePoints[f-1];p(!e||e.time<g.time);const r=null!=(l=null==e?void 0:e.time)?l:-1/0;return this.performClusterLookup(null,t,r,i,n)}return h?this.fetchPacketInCluster(h,m,n):null})}}class Jr extends Yr{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getRotation(){return this.internalTrack.info.rotation}getColorSpace(){return u(this,null,function*(){var e,t,r,i;return{primaries:null==(e=this.internalTrack.info.colorSpace)?void 0:e.primaries,transfer:null==(t=this.internalTrack.info.colorSpace)?void 0:t.transfer,matrix:null==(r=this.internalTrack.info.colorSpace)?void 0:r.matrix,fullRange:null==(i=this.internalTrack.info.colorSpace)?void 0:i.fullRange}})}canBeTransparent(){return u(this,null,function*(){return this.internalTrack.info.alphaMode})}getDecoderConfig(){return u(this,null,function*(){var e;return this.internalTrack.info.codec?null!=(e=this.decoderConfigPromise)?e:this.decoderConfigPromise=(()=>u(this,null,function*(){var e,t;let r=null;return("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)&&(r=yield this.getFirstPacket({})),{codec:Se({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&&r?Ue(r.data):null,hevcCodecInfo:"hevc"===this.internalTrack.info.codec&&r?We(r.data):null,vp9CodecInfo:"vp9"===this.internalTrack.info.codec&&r?Je(r.data):null,av1CodecInfo:"av1"===this.internalTrack.info.codec&&r?et(r.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}}))():null})}}class Zr extends Yr{constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}getDecoderConfig(){return u(this,null,function*(){var e,t;return this.internalTrack.info.codec?null!=(t=this.decoderConfig)?t:this.decoderConfig={codec:ve({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})}}
|
|
/*!
|
|
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
*
|
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
*/const ei=[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],ri=(e,t)=>{const r=e>>>24,i=e>>>16&255,n=e>>>8&255,s=255&e;if(255!==r&&255!==i&&255!==n&&255!==s)return{header:null,bytesAdvanced:4};if(255!==r)return{header:null,bytesAdvanced:1};if(224!==(224&i))return{header:null,bytesAdvanced:1};let a=0,o=0;16&i?a=8&i?0:1:(a=1,o=1);const l=i>>3&3,c=i>>1&3,u=(n>>2&3)%3,d=s>>6&3,h=s>>4&3,m=s>>3&1,f=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,b=ei[u]>>a+o,y=((e,t,r,i,n)=>0===t?0:1===t?Math.floor(144*r/(i<<e))+n:2===t?Math.floor(144*r/i)+n:4*(Math.floor(12*r/i)+n))(a,c,k,b,n>>1&1);if(null!==t&&t<y)return{header:null,bytesAdvanced:1};let T;return T=3===l?3===c?384:1152:3===c?384:2===c?1152:576,{header:{totalSize:y,mpegVersionId:l,layer:c,bitrate:k,frequencyIndex:u,sampleRate:b,channel:d,modeExtension:h,copyright:m,original:f,emphasis:p,audioSamplesInFrame:T},bytesAdvanced:1}},ii=e=>{let t=2130706432,r=0;for(;0!==t;)r>>=1,r|=e&t,t>>=8;return r};
|
|
/*!
|
|
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
*
|
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
*/
|
|
var ni,si,ai,oi;(si=ni||(ni={}))[si.Unsynchronisation=128]="Unsynchronisation",si[si.ExtendedHeader=64]="ExtendedHeader",si[si.ExperimentalIndicator=32]="ExperimentalIndicator",si[si.Footer=16]="Footer",(oi=ai||(ai={}))[oi.ISO_8859_1=0]="ISO_8859_1",oi[oi.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",oi[oi.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",oi[oi.UTF_8=3]="UTF_8";const li=128,ci=["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"],ui=(e,t)=>{const r=Tn(e,t),i=ce(r.indexOf(0),r.length),n=r.subarray(0,i);let s="";for(let a=0;a<n.length;a++)s+=String.fromCharCode(n[a]);return s.trimEnd()},di=e=>{const t=e.filePos,r=Nn(e,3),i=Sn(e),n=Sn(e),s=Sn(e),a=Cn(e);if("ID3"!==r||255===i||255===n||0!==(2155905152&a))return e.filePos=t,null;return{majorVersion:i,revision:n,flags:s,size:ii(a)}},hi=(e,t,r)=>{var i,n,s,a;if(![2,3,4].includes(t.majorVersion))return void console.warn(`Unsupported ID3v2 major version: ${t.majorVersion}`);const o=Tn(e,t.size),l=new mi(t,o);if(t.flags&ni.Footer&&l.removeFooter(),t.flags&ni.Unsynchronisation&&3===t.majorVersion&&l.ununsynchronizeAll(),t.flags&ni.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 o=l.pos,c=l.pos+e.size;let u=!1,d=!1,h=!1;if(3===t.majorVersion?(u=!!(64&e.flags),d=!!(128&e.flags)):4===t.majorVersion&&(u=!!(4&e.flags),d=!!(8&e.flags),h=!!(2&e.flags)||!!(t.flags&ni.Unsynchronisation)),u)console.warn(`Skipping encrypted ID3v2 frame ${e.id}`),l.pos=c;else if(d)console.warn(`Skipping compressed ID3v2 frame ${e.id}`),l.pos=c;else{switch(h&&l.ununsynchronizeRegion(l.pos,c),null!=r.raw||(r.raw={}),"T"===e.id[0]?null!=(i=r.raw)[n=e.id]||(i[n]=l.readId3V2EncodingAndText(c)):null!=(s=r.raw)[a=e.id]||(s[a]=l.readBytes(e.size)),l.pos=o,e.id){case"TIT2":case"TT2":null!=r.title||(r.title=l.readId3V2EncodingAndText(c));break;case"TIT3":case"TT3":null!=r.description||(r.description=l.readId3V2EncodingAndText(c));break;case"TPE1":case"TP1":null!=r.artist||(r.artist=l.readId3V2EncodingAndText(c));break;case"TALB":case"TAL":null!=r.album||(r.album=l.readId3V2EncodingAndText(c));break;case"TPE2":case"TP2":null!=r.albumArtist||(r.albumArtist=l.readId3V2EncodingAndText(c));break;case"TRCK":case"TRK":{const e=l.readId3V2EncodingAndText(c).split("/"),t=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(null!=r.trackNumber||(r.trackNumber=t)),i&&Number.isInteger(i)&&i>0&&(null!=r.tracksTotal||(r.tracksTotal=i))}break;case"TPOS":case"TPA":{const e=l.readId3V2EncodingAndText(c).split("/"),t=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(null!=r.discNumber||(r.discNumber=t)),i&&Number.isInteger(i)&&i>0&&(null!=r.discsTotal||(r.discsTotal=i))}break;case"TCON":case"TCO":{const e=l.readId3V2EncodingAndText(c);let t=/^\((\d+)\)/.exec(e);if(t){const e=Number.parseInt(t[1]);if(void 0!==ci[e]){null!=r.genre||(r.genre=ci[e]);break}}if(t=/^\d+$/.exec(e),t){const e=Number.parseInt(t[0]);if(void 0!==ci[e]){null!=r.genre||(r.genre=ci[e]);break}}null!=r.genre||(r.genre=e)}break;case"TDRC":case"TDAT":{const e=l.readId3V2EncodingAndText(c),t=new Date(e);Number.isNaN(t.getTime())||null!=r.date||(r.date=t)}break;case"TYER":case"TYE":{const e=l.readId3V2EncodingAndText(c),t=Number.parseInt(e,10);Number.isInteger(t)&&(null!=r.date||(r.date=new Date(t,0,1)))}break;case"USLT":case"ULT":{const e=l.readU8();l.pos+=3,l.readId3V2Text(e,c),null!=r.lyrics||(r.lyrics=l.readId3V2Text(e,c))}break;case"COMM":case"COM":{const e=l.readU8();l.pos+=3,l.readId3V2Text(e,c),null!=r.comment||(r.comment=l.readId3V2Text(e,c))}break;case"APIC":case"PIC":{const e=l.readId3V2TextEncoding();let i;if(2===t.majorVersion){const e=l.readAscii(3);i="PNG"===e?"image/png":"JPG"===e?"image/jpeg":"image/*"}else i=l.readId3V2Text(e,c);const n=l.readU8(),s=l.readId3V2Text(e,c).trimEnd(),a=c-l.pos;if(a>=0){const e=l.readBytes(a);r.images||(r.images=[]),r.images.push({data:e,mimeType:i,kind:3===n?"coverFront":4===n?"coverBack":"unknown",description:s})}}break;default:l.pos+=e.size}l.pos=c}}};class mi{constructor(e,t){this.header=e,this.bytes=t,this.pos=0,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength)}frameHeaderSize(){return 2===this.header.majorVersion?6:10}ununsynchronizeAll(){const e=[];for(let t=0;t<this.bytes.length;t++){const r=this.bytes[t];if(e.push(r),255===r&&t!==this.bytes.length-1){0===this.bytes[t]&&t++}}this.bytes=new Uint8Array(e),this.view=new DataView(this.bytes.buffer)}ununsynchronizeRegion(e,t){const r=[];for(let s=e;s<t;s++){const e=this.bytes[s];if(r.push(e),255===e&&s!==t-1){0===this.bytes[s+1]&&s++}}const i=this.bytes.subarray(0,e),n=this.bytes.subarray(t);this.bytes=new Uint8Array(i.length+r.length+n.length),this.bytes.set(i,0),this.bytes.set(r,i.length),this.bytes.set(n,i.length+r.length),this.view=new DataView(this.bytes.buffer)}removeFooter(){this.bytes=this.bytes.subarray(0,this.bytes.length-10),this.view=new DataView(this.bytes.buffer)}readBytes(e){const t=this.bytes.subarray(this.pos,this.pos+e);return this.pos+=e,t}readU8(){const e=this.view.getUint8(this.pos);return this.pos+=1,e}readU16(){const e=this.view.getUint16(this.pos,!1);return this.pos+=2,e}readU24(){const e=this.view.getUint16(this.pos,!1),t=this.view.getUint8(this.pos+1);return this.pos+=3,256*e+t}readU32(){const e=this.view.getUint32(this.pos,!1);return this.pos+=4,e}readAscii(e){let t="";for(let r=0;r<e;r++)t+=String.fromCharCode(this.view.getUint8(this.pos+r));return this.pos+=e,t}readId3V2Frame(){if(2===this.header.majorVersion){const e=this.readAscii(3);if("\0\0\0"===e)return null;return{id:e,size:this.readU24(),flags:0}}{const e=this.readAscii(4);if("\0\0\0\0"===e)return null;const t=this.readU32();let r=4===this.header.majorVersion?ii(t):t;const i=this.readU16(),n=this.pos,s=e=>{const t=this.pos+e;if(t>this.bytes.length)return!1;if(t<=this.bytes.length-this.frameHeaderSize()){this.pos+=e;const t=this.readAscii(4);if("\0\0\0\0"!==t&&!/[0-9A-Z]{4}/.test(t))return!1}return!0};if(!s(r)){const e=4===this.header.majorVersion?t:ii(t);s(e)&&(r=e)}return this.pos=n,{id:e,size:r,flags:i}}}readId3V2TextEncoding(){const e=this.readU8();if(e>3)throw new Error(`Unsupported text encoding: ${e}`);return e}readId3V2Text(e,t){const r=this.pos,i=this.readBytes(t-this.pos);switch(e){case ai.ISO_8859_1:{let e="";for(let t=0;t<i.length;t++){const n=i[t];if(0===n){this.pos=r+t+1;break}e+=String.fromCharCode(n)}return e}case ai.UTF_16_WITH_BOM:if(255===i[0]&&254===i[1]){const e=new TextDecoder("utf-16le"),t=ce(i.findIndex((e,t)=>0===e&&0===i[t+1]&&t%2===0),i.length);return this.pos=r+Math.min(t+2,i.length),e.decode(i.subarray(2,t))}if(254===i[0]&&255===i[1]){const e=new TextDecoder("utf-16be"),t=ce(i.findIndex((e,t)=>0===e&&0===i[t+1]&&t%2===0),i.length);return this.pos=r+Math.min(t+2,i.length),e.decode(i.subarray(2,t))}{const e=ce(i.findIndex(e=>0===e),i.length);return this.pos=r+Math.min(e+1,i.length),w.decode(i.subarray(0,e))}case ai.UTF_16_BE_NO_BOM:{const e=new TextDecoder("utf-16be"),t=ce(i.findIndex((e,t)=>0===e&&0===i[t+1]&&t%2===0),i.length);return this.pos=r+Math.min(t+2,i.length),e.decode(i.subarray(0,t))}case ai.UTF_8:{const e=ce(i.findIndex(e=>0===e),i.length);return this.pos=r+Math.min(e+1,i.length),w.decode(i.subarray(0,e))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";const t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}}
|
|
/*!
|
|
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
*
|
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
*/const fi=(e,t,r)=>u(null,null,function*(){let i=t;for(;null===r||i<r;){let t=e.requestSlice(i,4);if(t instanceof Promise&&(t=yield t),!t)break;const r=Cn(t),n=ri(r,null!==e.fileSize?e.fileSize-i:null);if(n.header)return{header:n.header,startPos:i};i+=n.bytesAdvanced}return null});
|
|
/*!
|
|
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
*
|
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
*/class pi extends ot{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.tracks=[],this.readingMutex=new D,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}readMetadata(){return u(this,null,function*(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>u(this,null,function*(){for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)yield this.advanceReader();if(!this.firstFrameHeader)throw new Error("No valid MP3 frame found.");this.tracks=[new Xt(this.input,new gi(this))]}))()})}advanceReader(){return u(this,null,function*(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,10);if(e instanceof Promise&&(e=yield e),!e)return void(this.lastSampleLoaded=!0);const t=di(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}const e=yield fi(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 r=(i=t.mpegVersionId,n=t.channel,3===i?3===n?21:36:3===n?13:21);var i,n;let s=this.reader.requestSlice(e.startPos+r,4);if(s instanceof Promise&&(s=yield s),s){const e=Cn(s);if(1483304551===e||1231971951===e)return}this.firstFrameHeader||(this.firstFrameHeader=t),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,o={timestamp:this.nextTimestampInSamples/this.firstFrameHeader.sampleRate,duration:a,dataStart:e.startPos,dataSize:t.totalSize};this.loadedSamples.push(o),this.nextTimestampInSamples+=t.audioSamplesInFrame})}getMimeType(){return u(this,null,function*(){return"audio/mpeg"})}getTracks(){return u(this,null,function*(){return yield this.readMetadata(),this.tracks})}computeDuration(){return u(this,null,function*(){yield this.readMetadata();const e=this.tracks[0];return p(e),e.computeDuration()})}getMetadataTags(){return u(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 r=this.reader.requestSlice(e,10);if(r instanceof Promise&&(r=yield r),!r)break;const i=di(r);if(!i)break;t=!0;let n=this.reader.requestSlice(r.filePos,i.size);if(n instanceof Promise&&(n=yield n),!n)break;hi(n,i,this.metadataTags),e=r.filePos+i.size}if(!t&&null!==this.reader.fileSize&&this.reader.fileSize>=li){let e=this.reader.requestSlice(this.reader.fileSize-li,li);e instanceof Promise&&(e=yield e),p(e);"TAG"===Nn(e,3)&&((e,t)=>{var r;const i=e.filePos;null!=t.raw||(t.raw={}),null!=(r=t.raw).TAG||(r.TAG=Tn(e,125)),e.filePos=i;const n=ui(e,30);n&&(null!=t.title||(t.title=n));const s=ui(e,30);s&&(null!=t.artist||(t.artist=s));const a=ui(e,30);a&&(null!=t.album||(t.album=a));const o=ui(e,4),l=Number.parseInt(o,10);Number.isInteger(l)&&l>0&&(null!=t.date||(t.date=new Date(l,0,1)));const c=Tn(e,30);let u;if(0===c[28]&&0!==c[29]){const r=c[29];r>0&&(null!=t.trackNumber||(t.trackNumber=r)),e.skip(-30),u=ui(e,28),e.skip(2)}else e.skip(-30),u=ui(e,30);u&&(null!=t.comment||(t.comment=u));const d=Sn(e);d<ci.length&&(null!=t.genre||(t.genre=ci[d]))})(e,this.metadataTags)}return this.metadataTags}finally{e()}})}}class gi{constructor(e){this.demuxer=e}getId(){return 1}getFirstTimestamp(){return u(this,null,function*(){return 0})}getTimeResolution(){return p(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate/this.demuxer.firstFrameHeader.audioSamplesInFrame}computeDuration(){return u(this,null,function*(){var e,t;const r=yield this.getPacket(1/0,{metadataOnly:!0});return(null!=(e=null==r?void 0:r.timestamp)?e:0)+(null!=(t=null==r?void 0:r.duration)?t:0)})}getName(){return null}getLanguageCode(){return $}getCodec(){return"mp3"}getInternalCodecId(){return null}getNumberOfChannels(){return p(this.demuxer.firstFrameHeader),3===this.demuxer.firstFrameHeader.channel?1:2}getSampleRate(){return p(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return c({},ge)}getDecoderConfig(){return u(this,null,function*(){return p(this.demuxer.firstFrameHeader),{codec:"mp3",numberOfChannels:3===this.demuxer.firstFrameHeader.channel?1:2,sampleRate:this.demuxer.firstFrameHeader.sampleRate}})}getPacketAtIndex(e,t){return u(this,null,function*(){if(-1===e)return null;const r=this.demuxer.loadedSamples[e];if(!r)return null;let i;if(t.metadataOnly)i=ut;else{let e=this.demuxer.reader.requestSlice(r.dataStart,r.dataSize);if(e instanceof Promise&&(e=yield e),!e)return null;i=Tn(e,r.dataSize)}return new dt(i,"key",r.timestamp,r.duration,e,r.dataSize)})}getFirstPacket(e){return this.getPacketAtIndex(0,e)}getNextPacket(e,t){return u(this,null,function*(){const r=yield this.demuxer.readingMutex.acquire();try{const r=M(this.demuxer.loadedSamples,e.timestamp,e=>e.timestamp);if(-1===r)throw new Error("Packet was not created from this track.");const i=r+1;for(;i>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)yield this.demuxer.advanceReader();return this.getPacketAtIndex(i,t)}finally{r()}})}getPacket(e,t){return u(this,null,function*(){const r=yield this.demuxer.readingMutex.acquire();try{for(;;){const r=N(this.demuxer.loadedSamples,e,e=>e.timestamp);if(-1===r&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(r,t);if(r>=0&&r+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(r,t);yield this.demuxer.advanceReader()}}finally{r()}})}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}
|
|
/*!
|
|
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
*
|
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
*/const ki=1399285583,bi=new Uint32Array(256);for(let qn=0;qn<256;qn++){let e=qn<<24;for(let t=0;t<8;t++)e=2147483648&e?e<<1^79764919:e<<1;bi[qn]=e>>>0&4294967295}const yi=e=>{const t=v(e),r=t.getUint32(22,!0);t.setUint32(22,0,!0);let i=0;for(let n=0;n<e.length;n++){const t=e[n];i=(i<<8^bi[i>>>24^t])>>>0}return t.setUint32(22,r,!0),i},Ti=(e,t,r)=>{let i=0,n=null;if(e.length>0)if("vorbis"===t.codec){p(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=r;const l=t.vorbisInfo.modeBlockflags[a];if(n=t.vorbisInfo.blocksizes[l],1===l){const r=1+(1|s),i=e[0]&r?1:0;o=t.vorbisInfo.blocksizes[i]}i=null!==o?o+n>>2:0}else if("opus"===t.codec){i=(e=>{const t=e[0]>>3;return{durationInSamples:tt[t]}})(e).durationInSamples}return{durationInSamples:i,vorbisBlockSize:n}},Si=27,vi=282,wi=e=>{const t=e.filePos;if(_n(e)!==ki)return null;e.skip(1);const r=Sn(e),i=An(e),n=_n(e),s=_n(e),a=_n(e),o=Sn(e),l=new Uint8Array(o);for(let d=0;d<o;d++)l[d]=Sn(e);const c=27+o,u=l.reduce((e,t)=>e+t,0);return{headerStartPos:t,totalSize:c+u,dataStartPos:t+c,dataSize:u,headerType:r,granulePosition:i,serialNumber:n,sequenceNumber:s,checksum:a,lacingValues:l}},Ii=(e,t)=>{for(;e.filePos<t-3;){const t=_n(e),r=79;if((255&t)===r||(t>>>8&255)===r||(t>>>16&255)===r||(t>>>24&255)===r){if(e.skip(-4),t===ki)return!0;e.skip(1)}}return!1};
|
|
/*!
|
|
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
*
|
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
*/
|
|
class Pi extends ot{constructor(e){super(e),this.metadataPromise=null,this.bitstreams=[],this.tracks=[],this.metadataTags={},this.reader=e._reader}readMetadata(){return u(this,null,function*(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>u(this,null,function*(){let e=0;for(;;){let t=this.reader.requestSliceRange(e,Si,vi);if(t instanceof Promise&&(t=yield t),!t)break;const r=wi(t);if(!r)break;if(!!!(2&r.headerType))break;this.bitstreams.push({serialNumber:r.serialNumber,bosPage:r,description:null,numberOfChannels:-1,sampleRate:-1,codecInfo:{codec:null,vorbisInfo:null,opusInfo:null},lastMetadataPacket:null}),e=r.headerStartPos+r.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.tracks.push(new Xt(this.input,new xi(t,this))))}}))()})}readVorbisMetadata(e,t){return u(this,null,function*(){let r=yield this.findNextPacketStart(e);if(!r)return;const i=yield this.readPacket(r.startPage,r.startSegmentIndex);if(!i)return;if(r=yield this.findNextPacketStart(i),!r)return;const n=yield this.readPacket(r.startPage,r.startSegmentIndex);if(!n)return;if(3!==i.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(i.data.length);const o=new Uint8Array(1+s.length+e.data.length+i.data.length+n.data.length);o[0]=2,o.set(s,1),o.set(e.data,1+s.length),o.set(i.data,1+s.length+e.data.length),o.set(n.data,1+s.length+e.data.length+i.data.length),t.codecInfo.codec="vorbis",t.description=o,t.lastMetadataPacket=n;const l=v(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:rt(n.data).modeBlockflags},at(i.data.subarray(7),this.metadataTags)})}readOpusMetadata(e,t){return u(this,null,function*(){const r=yield this.findNextPacketStart(e);if(!r)return;const i=yield this.readPacket(r.startPage,r.startSegmentIndex);if(!i)return;t.codecInfo.codec="opus",t.description=e.data,t.lastMetadataPacket=i;const n=(e=>{const t=v(e),r=t.getUint8(9),i=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+r)),{outputChannelCount:r,preSkip:i,inputSampleRate:n,outputGain:s,channelMappingFamily:a,channelMappingTable:o}})(e.data);t.numberOfChannels=n.outputChannelCount,t.sampleRate=xe,t.codecInfo.opusInfo={preSkip:n.preSkip},at(i.data.subarray(8),this.metadataTags)})}readPacket(e,t){return u(this,null,function*(){p(t<e.lacingValues.length);let r=0;for(let u=0;u<t;u++)r+=e.lacingValues[u];let i=e,n=r,s=t;const a=[];e:for(;;){let t=this.reader.requestSlice(i.dataStartPos,i.dataSize);t instanceof Promise&&(t=yield t),p(t);const o=Tn(t,i.dataSize);for(;;){if(s===i.lacingValues.length){a.push(o.subarray(r,n));break}const e=i.lacingValues[s];if(n+=e,e<255){a.push(o.subarray(r,n));break e}s++}let l=i.headerStartPos+i.totalSize;for(;;){let t=this.reader.requestSliceRange(l,Si,vi);if(t instanceof Promise&&(t=yield t),!t)return null;const r=wi(t);if(!r)return null;if(i=r,i.serialNumber===e.serialNumber)break;l=i.headerStartPos+i.totalSize}r=0,n=0,s=0}const o=a.reduce((e,t)=>e+t.length,0);if(0===o)return null;const l=new Uint8Array(o);let c=0;for(let e=0;e<a.length;e++){const t=a[e];l.set(t,c),c+=t.length}return{data:l,endPage:i,endSegmentIndex:s}})}findNextPacketStart(e){return u(this,null,function*(){if(e.endSegmentIndex<e.endPage.lacingValues.length-1)return{startPage:e.endPage,startSegmentIndex:e.endSegmentIndex+1};if(!!(4&e.endPage.headerType))return null;let t=e.endPage.headerStartPos+e.endPage.totalSize;for(;;){let r=this.reader.requestSliceRange(t,Si,vi);if(r instanceof Promise&&(r=yield r),!r)return null;const i=wi(r);if(!i)return null;if(i.serialNumber===e.endPage.serialNumber)return{startPage:i,startSegmentIndex:0};t=i.headerStartPos+i.totalSize}})}getMimeType(){return u(this,null,function*(){yield this.readMetadata();return(e=>{let t="audio/ogg";e.codecStrings&&(t+=`; codecs="${[...new Set(e.codecStrings)].join(", ")}"`);return t})({codecStrings:(yield Promise.all(this.tracks.map(e=>e.getCodecParameterString()))).filter(Boolean)})})}getTracks(){return u(this,null,function*(){return yield this.readMetadata(),this.tracks})}computeDuration(){return u(this,null,function*(){const e=yield this.getTracks(),t=yield Promise.all(e.map(e=>e.computeDuration()));return Math.max(0,...t)})}getMetadataTags(){return u(this,null,function*(){return yield this.readMetadata(),this.metadataTags})}}class xi{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?xe:e.sampleRate}getId(){return this.bitstream.serialNumber}getNumberOfChannels(){return this.bitstream.numberOfChannels}getSampleRate(){return this.bitstream.sampleRate}getTimeResolution(){return this.bitstream.sampleRate}getCodec(){return this.bitstream.codecInfo.codec}getInternalCodecId(){return null}getDecoderConfig(){return u(this,null,function*(){var e;return p(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 $}getDisposition(){return c({},ge)}getFirstTimestamp(){return u(this,null,function*(){return 0})}computeDuration(){return u(this,null,function*(){var e,t;const r=yield this.getPacket(1/0,{metadataOnly:!0});return(null!=(e=null==r?void 0:r.timestamp)?e:0)+(null!=(t=null==r?void 0:r.duration)?t:0)})}granulePositionToTimestampInSamples(e){return"opus"===this.bitstream.codecInfo.codec?(p(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,r){if(!e)return null;const{durationInSamples:i,vorbisBlockSize:n}=Ti(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),s=new dt(r.metadataOnly?ut:e.data,"key",Math.max(0,t.timestampInSamples)/this.internalSampleRate,i/this.internalSampleRate,e.endPage.headerStartPos+e.endSegmentIndex,e.data.byteLength);return this.encodedPacketToMetadata.set(s,{packet:e,timestampInSamples:t.timestampInSamples,durationInSamples:i,vorbisLastBlockSize:t.vorbisLastBlocksize,vorbisBlockSize:n}),s}getFirstPacket(e){return u(this,null,function*(){p(this.bitstream.lastMetadataPacket);const t=yield this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let r=0;"opus"===this.bitstream.codecInfo.codec&&(p(this.bitstream.codecInfo.opusInfo),r-=this.bitstream.codecInfo.opusInfo.preSkip);const i=yield this.demuxer.readPacket(t.startPage,t.startSegmentIndex);return this.createEncodedPacketFromOggPacket(i,{timestampInSamples:r,vorbisLastBlocksize:null},e)})}getNextPacket(e,t){return u(this,null,function*(){const r=this.encodedPacketToMetadata.get(e);if(!r)throw new Error("Packet was not created from this track.");const i=yield this.demuxer.findNextPacketStart(r.packet);if(!i)return null;const n=r.timestampInSamples+r.durationInSamples,s=yield this.demuxer.readPacket(i.startPage,i.startSegmentIndex);return this.createEncodedPacketFromOggPacket(s,{timestampInSamples:n,vorbisLastBlocksize:r.vorbisBlockSize},t)})}getPacket(e,t){return u(this,null,function*(){var r,i;if(null===this.demuxer.reader.fileSize)return this.getPacketSequential(e,t);const n=Q(e*this.internalSampleRate);if(0===n)return this.getFirstPacket(t);if(n<0)return null;p(this.bitstream.lastMetadataPacket);const s=yield this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!s)return null;let a=s.startPage,o=this.demuxer.reader.fileSize;const l=[a];e:for(;a.headerStartPos+a.totalSize<o;){const e=a.headerStartPos,t=Math.floor((e+o)/2);let r=t;for(;;){const e=Math.min(r+65307,o-Si);let i=this.demuxer.reader.requestSlice(r,e-r);i instanceof Promise&&(i=yield i),p(i);if(!Ii(i,e)){o=t+Si;continue e}let s=this.demuxer.reader.requestSliceRange(i.filePos,Si,vi);s instanceof Promise&&(s=yield s),p(s);const c=wi(s);p(c);let u=!1;if(c.serialNumber===this.bitstream.serialNumber)u=!0;else{let e=this.demuxer.reader.requestSlice(c.headerStartPos,c.totalSize);e instanceof Promise&&(e=yield e),p(e);const t=Tn(e,c.totalSize);u=yi(t)===c.checksum}if(!u){r=c.headerStartPos+4;continue}if(u&&c.serialNumber!==this.bitstream.serialNumber){r=c.headerStartPos+c.totalSize;continue}if(!(-1===c.granulePosition)){this.granulePositionToTimestampInSamples(c.granulePosition)>n?o=c.headerStartPos:(a=c,l.push(c));continue e}r=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,Si,vi);t instanceof Promise&&(t=yield t),p(t);const r=wi(t);p(r),u=r,u.serialNumber===this.bitstream.serialNumber&&d.push(u)}p(-1!==u.granulePosition);let h,m,f=null,g=u,k=0;if(u.headerStartPos===s.startPage.headerStartPos)h=this.granulePositionToTimestampInSamples(0),m=!0,f=0;else{h=0,m=!1;for(let t=u.lacingValues.length-1;t>=0;t--){if(u.lacingValues[t]<255){f=t+1;break}}if(null===f)throw new Error("Invalid page with granule position: no packets end on this page.");k=f-1;const e={data:ut,endPage:g,endSegmentIndex:k};if(yield this.demuxer.findNextPacketStart(e)){const e=_i(d,u,f);p(e);const t=Ci(d,e.page,e.segmentIndex);t&&(u=t.page,f=t.segmentIndex)}else for(;;){const e=_i(d,u,f);if(!e)break;const t=Ci(d,e.page,e.segmentIndex);if(!t)break;if(u=t.page,f=t.segmentIndex,e.page.headerStartPos!==g.headerStartPos){g=e.page,k=e.segmentIndex;break}}}let b=null,y=null;for(;null!==u;){p(null!==f);const e=yield this.demuxer.readPacket(u,f);if(!e)break;if(!(u.headerStartPos===s.startPage.headerStartPos&&f<s.startSegmentIndex)){let s=this.createEncodedPacketFromOggPacket(e,{timestampInSamples:h,vorbisLastBlocksize:null!=(r=null==y?void 0:y.vorbisBlockSize)?r:null},t);p(s);let a=this.encodedPacketToMetadata.get(s);if(p(a),m||e.endPage.headerStartPos!==g.headerStartPos||e.endSegmentIndex!==k?h+=a.durationInSamples:(h=this.granulePositionToTimestampInSamples(u.granulePosition),m=!0,s=this.createEncodedPacketFromOggPacket(e,{timestampInSamples:h-a.durationInSamples,vorbisLastBlocksize:null!=(i=null==y?void 0:y.vorbisBlockSize)?i:null},t),p(s),a=this.encodedPacketToMetadata.get(s),p(a)),b=s,y=a,m&&(Math.max(h,0)>n||Math.max(a.timestampInSamples,0)===n))break}const a=yield this.demuxer.findNextPacketStart(e);if(!a)break;u=a.startPage,f=a.startSegmentIndex}return b})}getPacketSequential(e,t){return u(this,null,function*(){const r=yield this.sequentialScanMutex.acquire();try{const r=Q(e*this.internalSampleRate);e=r/this.internalSampleRate;const i=N(this.sequentialScanCache,r,e=>e.timestampInSamples);let n;if(-1!==i){const e=this.sequentialScanCache[i];n=this.createEncodedPacketFromOggPacket(e.packet,{timestampInSamples:e.timestampInSamples,vorbisLastBlocksize:e.vorbisLastBlockSize},t)}else n=yield this.getFirstPacket(t);let s=0;for(;n&&n.timestamp<e;){const r=yield this.getNextPacket(n,t);if(!r||r.timestamp>e)break;if(n=r,s++,100===s){s=0;const e=this.encodedPacketToMetadata.get(n);p(e),this.sequentialScanCache.length>0&&p(k(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 Ci=(e,t,r)=>{let i=t,n=r;e:for(;;){for(n--;n>=0;n--){if(i.lacingValues[n]<255){n++;break e}}p(-1===n);if(!(1&i.headerType)){n=0;break}const t=L(e,e=>e.headerStartPos<i.headerStartPos);if(!t)return null;i=t,n=i.lacingValues.length}if(p(-1!==n),n===i.lacingValues.length){const t=e[e.indexOf(i)+1];p(t),i=t,n=0}return{page:i,segmentIndex:n}},_i=(e,t,r)=>{if(r>0)return{page:t,segmentIndex:r-1};const i=L(e,e=>e.headerStartPos<t.headerStartPos);return i?{page:i,segmentIndex:i.lacingValues.length-1}:null};
|
|
/*!
|
|
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
*
|
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
*/
|
|
var Bi,Ei;(Ei=Bi||(Bi={}))[Ei.PCM=1]="PCM",Ei[Ei.IEEE_FLOAT=3]="IEEE_FLOAT",Ei[Ei.ALAW=6]="ALAW",Ei[Ei.MULAW=7]="MULAW",Ei[Ei.EXTENSIBLE=65534]="EXTENSIBLE";class Fi extends ot{constructor(e){super(e),this.metadataPromise=null,this.dataStart=-1,this.dataSize=-1,this.audioInfo=null,this.tracks=[],this.lastKnownPacketIndex=0,this.metadataTags={},this.reader=e._reader}readMetadata(){return u(this,null,function*(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>u(this,null,function*(){var e,t;let r=this.reader.requestSlice(0,12);r instanceof Promise&&(r=yield r),p(r);const i=Nn(r,4),n="RIFX"!==i,s="RF64"===i,a=xn(r,n);let o=s?this.reader.fileSize:Math.min(a+8,null!=(e=this.reader.fileSize)?e:1/0);if("WAVE"!==Nn(r,4))throw new Error("Invalid WAVE file - wrong format");let l=0,c=null,u=r.filePos;for(;null===o||u<o;){let e=this.reader.requestSlice(u,8);if(e instanceof Promise&&(e=yield e),!e)break;const r=Nn(e,4),i=xn(e,n),a=e.filePos;if(s&&0===l&&"ds64"!==r)throw new Error('Invalid RF64 file: First chunk must be "ds64".');if("fmt "===r)yield this.parseFmtChunk(a,i,n);else if("data"===r){if(null!=c||(c=i),this.dataStart=e.filePos,this.dataSize=Math.min(c,(null!=o?o:1/0)-this.dataStart),null===this.reader.fileSize)break}else if("ds64"===r){let e=this.reader.requestSlice(a,i);if(e instanceof Promise&&(e=yield e),!e)break;const r=En(e,n);c=En(e,n),o=Math.min(r+8,null!=(t=this.reader.fileSize)?t:1/0)}else"LIST"===r?yield this.parseListChunk(a,i,n):"ID3 "!==r&&"id3 "!==r||(yield this.parseId3Chunk(a,i));u=a+i+(1&i),l++}if(!this.audioInfo)throw new Error('Invalid WAVE file - missing "fmt " chunk');if(-1===this.dataStart)throw new Error('Invalid WAVE file - missing "data" chunk');const d=this.audioInfo.blockSizeInBytes;this.dataSize=Math.floor(this.dataSize/d)*d,this.tracks.push(new Xt(this.input,new Ai(this)))}))()})}parseFmtChunk(e,t,r){return u(this,null,function*(){let i=this.reader.requestSlice(e,t);if(i instanceof Promise&&(i=yield i),!i)return;let n=vn(i,r);const s=vn(i,r),a=xn(i,r);i.skip(4);const o=vn(i,r);let l;if(l=14===t?8:vn(i,r),t>=18&&357!==n){const e=vn(i,r),s=t-18;if(Math.min(s,e)>=22&&n===Bi.EXTENSIBLE){i.skip(6);const e=Tn(i,16);n=e[0]|e[1]<<8}}n!==Bi.MULAW&&n!==Bi.ALAW||(l=8),this.audioInfo={format:n,numberOfChannels:s,sampleRate:a,sampleSizeInBytes:Math.ceil(l/8),blockSizeInBytes:o}})}parseListChunk(e,t,r){return u(this,null,function*(){var i,n,s,a,o,l,c,u,d,h,m;let f=this.reader.requestSlice(e,t);if(f instanceof Promise&&(f=yield f),!f)return;const p=Nn(f,4);if("INFO"!==p&&"INF0"!==p)return;let g=f.filePos;for(;g<=e+t-8;){f.filePos=g;const e=Nn(f,4),t=xn(f,r),p=Tn(f,t);let k=0;for(let r=0;r<p.length&&0!==p[r];r++)k++;const b=String.fromCharCode(...p.subarray(0,k));switch(null!=(i=this.metadataTags).raw||(i.raw={}),this.metadataTags.raw[e]=b,e){case"INAM":case"TITL":null!=(n=this.metadataTags).title||(n.title=b);break;case"TIT3":null!=(s=this.metadataTags).description||(s.description=b);break;case"IART":null!=(a=this.metadataTags).artist||(a.artist=b);break;case"IPRD":null!=(o=this.metadataTags).album||(o.album=b);break;case"IPRT":case"ITRK":case"TRCK":{const e=b.split("/"),t=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(null!=(l=this.metadataTags).trackNumber||(l.trackNumber=t)),r&&Number.isInteger(r)&&r>0&&(null!=(c=this.metadataTags).tracksTotal||(c.tracksTotal=r))}break;case"ICRD":case"IDIT":{const e=new Date(b);Number.isNaN(e.getTime())||null!=(u=this.metadataTags).date||(u.date=e)}break;case"YEAR":{const e=Number.parseInt(b,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=b);break;case"ICMT":case"CMNT":case"COMM":null!=(m=this.metadataTags).comment||(m.comment=b)}g+=8+t+(1&t)}})}parseId3Chunk(e,t){return u(this,null,function*(){let r=this.reader.requestSlice(e,t);if(r instanceof Promise&&(r=yield r),!r)return;const i=di(r);if(i){const t=r.slice(e+10,i.size);hi(t,i,this.metadataTags)}})}getCodec(){if(p(this.audioInfo),this.audioInfo.format===Bi.MULAW)return"ulaw";if(this.audioInfo.format===Bi.ALAW)return"alaw";if(this.audioInfo.format===Bi.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===Bi.IEEE_FLOAT&&4===this.audioInfo.sampleSizeInBytes?"pcm-f32":null}getMimeType(){return u(this,null,function*(){return"audio/wav"})}computeDuration(){return u(this,null,function*(){yield this.readMetadata();const e=this.tracks[0];return p(e),e.computeDuration()})}getTracks(){return u(this,null,function*(){return yield this.readMetadata(),this.tracks})}getMetadataTags(){return u(this,null,function*(){return yield this.readMetadata(),this.metadataTags})}}const Di=2048;class Ai{constructor(e){this.demuxer=e}getId(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return p(this.demuxer.audioInfo),this.demuxer.audioInfo.format}getDecoderConfig(){return u(this,null,function*(){const e=this.demuxer.getCodec();return e?(p(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null})}computeDuration(){return u(this,null,function*(){var e,t;const r=yield this.getPacket(1/0,{metadataOnly:!0});return(null!=(e=null==r?void 0:r.timestamp)?e:0)+(null!=(t=null==r?void 0:r.duration)?t:0)})}getNumberOfChannels(){return p(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return p(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return p(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return $}getDisposition(){return c({},ge)}getFirstTimestamp(){return u(this,null,function*(){return 0})}getPacketAtIndex(e,t){return u(this,null,function*(){p(this.demuxer.audioInfo);const r=e*Di*this.demuxer.audioInfo.blockSizeInBytes;if(r>=this.demuxer.dataSize)return null;const i=Math.min(Di*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-r);if(null===this.demuxer.reader.fileSize){let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+r,i);if(e instanceof Promise&&(e=yield e),!e)return null}let n;if(t.metadataOnly)n=ut;else{let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+r,i);e instanceof Promise&&(e=yield e),p(e),n=Tn(e,i)}const s=e*Di/this.demuxer.audioInfo.sampleRate,a=i/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(e,s),new dt(n,"key",s,a,e,i)})}getFirstPacket(e){return this.getPacketAtIndex(0,e)}getPacket(e,t){return u(this,null,function*(){p(this.demuxer.audioInfo);const r=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/Di,(this.demuxer.dataSize-1)/(Di*this.demuxer.audioInfo.blockSizeInBytes))),i=yield this.getPacketAtIndex(r,t);if(i)return i;if(0===r)return null;p(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){p(this.demuxer.audioInfo);const r=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/Di);return this.getPacketAtIndex(r+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}
|
|
/*!
|
|
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
*
|
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
*/const Ri=e=>{const t=e.filePos,r=Tn(e,9),i=new b(r);if(4095!==i.readBits(12))return null;i.skipBits(1);if(0!==i.readBits(2))return null;const n=i.readBits(1),s=i.readBits(2)+1,a=i.readBits(4);if(15===a)return null;i.skipBits(1);const o=i.readBits(3);if(0===o)throw new Error("ADTS frames with channel configuration 0 are not supported.");i.skipBits(1),i.skipBits(1),i.skipBits(1),i.skipBits(1);const l=i.readBits(13);i.skipBits(11);const c=i.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=i.readBits(16),{objectType:s,samplingFrequencyIndex:a,channelConfiguration:o,frameLength:l,numberOfAacFrames:c,crcCheck:u,startPos:t}},Mi=1024;class Ni extends ot{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.tracks=[],this.readingMutex=new D,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}readMetadata(){return u(this,null,function*(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>u(this,null,function*(){for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)yield this.advanceReader();p(this.firstFrameHeader),this.tracks=[new Xt(this.input,new zi(this))]}))()})}advanceReader(){return u(this,null,function*(){let e=this.reader.requestSliceRange(this.lastLoadedPos,7,9);if(e instanceof Promise&&(e=yield e),!e)return void(this.lastSampleLoaded=!0);const t=Ri(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=we[t.samplingFrequencyIndex];p(void 0!==r);const i=Mi/r,n=t.crcCheck?9:7,s={timestamp:this.nextTimestampInSamples/r,duration:i,dataStart:t.startPos+n,dataSize:t.frameLength-n};this.loadedSamples.push(s),this.nextTimestampInSamples+=Mi,this.lastLoadedPos=t.startPos+t.frameLength})}getMimeType(){return u(this,null,function*(){return"audio/aac"})}getTracks(){return u(this,null,function*(){return yield this.readMetadata(),this.tracks})}computeDuration(){return u(this,null,function*(){yield this.readMetadata();const e=this.tracks[0];return p(e),e.computeDuration()})}getMetadataTags(){return u(this,null,function*(){return{}})}}class zi{constructor(e){this.demuxer=e}getId(){return 1}getFirstTimestamp(){return u(this,null,function*(){return 0})}getTimeResolution(){return this.getSampleRate()/Mi}computeDuration(){return u(this,null,function*(){var e,t;const r=yield this.getPacket(1/0,{metadataOnly:!0});return(null!=(e=null==r?void 0:r.timestamp)?e:0)+(null!=(t=null==r?void 0:r.duration)?t:0)})}getName(){return null}getLanguageCode(){return $}getCodec(){return"aac"}getInternalCodecId(){return p(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){p(this.demuxer.firstFrameHeader);const e=Ie[this.demuxer.firstFrameHeader.channelConfiguration];return p(void 0!==e),e}getSampleRate(){p(this.demuxer.firstFrameHeader);const e=we[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return p(void 0!==e),e}getDisposition(){return c({},ge)}getDecoderConfig(){return u(this,null,function*(){p(this.demuxer.firstFrameHeader);const e=new Uint8Array(3),t=new b(e),{objectType:r,samplingFrequencyIndex:i,channelConfiguration:n}=this.demuxer.firstFrameHeader;return r>31?(t.writeBits(5,31),t.writeBits(6,r-32)):t.writeBits(5,r),t.writeBits(4,i),t.writeBits(4,n),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate(),description:e.subarray(0,Math.ceil((t.pos-1)/8))}})}getPacketAtIndex(e,t){return u(this,null,function*(){if(-1===e)return null;const r=this.demuxer.loadedSamples[e];if(!r)return null;let i;if(t.metadataOnly)i=ut;else{let e=this.demuxer.reader.requestSlice(r.dataStart,r.dataSize);if(e instanceof Promise&&(e=yield e),!e)return null;i=Tn(e,r.dataSize)}return new dt(i,"key",r.timestamp,r.duration,e,r.dataSize)})}getFirstPacket(e){return this.getPacketAtIndex(0,e)}getNextPacket(e,t){return u(this,null,function*(){const r=yield this.demuxer.readingMutex.acquire();try{const r=M(this.demuxer.loadedSamples,e.timestamp,e=>e.timestamp);if(-1===r)throw new Error("Packet was not created from this track.");const i=r+1;for(;i>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)yield this.demuxer.advanceReader();return this.getPacketAtIndex(i,t)}finally{r()}})}getPacket(e,t){return u(this,null,function*(){const r=yield this.demuxer.readingMutex.acquire();try{for(;;){const r=N(this.demuxer.loadedSamples,e,e=>e.timestamp);if(-1===r&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(r,t);if(r>=0&&r+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(r,t);yield this.demuxer.advanceReader()}}finally{r()}})}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}
|
|
/*!
|
|
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
*
|
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
*/
|
|
/*!
|
|
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
*
|
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
*/
|
|
class Oi extends ot{constructor(e){super(e),this.loadedSamples=[],this.metadataPromise=null,this.track=null,this.metadataTags={},this.audioInfo=null,this.lastLoadedPos=null,this.blockingBit=null,this.readingMutex=new D,this.lastSampleLoaded=!1,this.reader=e._reader}computeDuration(){return u(this,null,function*(){return yield this.readMetadata(),p(this.track),this.track.computeDuration()})}getMetadataTags(){return u(this,null,function*(){return yield this.readMetadata(),this.metadataTags})}getTracks(){return u(this,null,function*(){return yield this.readMetadata(),p(this.track),[this.track]})}getMimeType(){return u(this,null,function*(){return"audio/flac"})}readMetadata(){return u(this,null,function*(){var e;let t=4;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>u(this,null,function*(){for(var e;null===this.reader.fileSize||t<this.reader.fileSize;){let r=this.reader.requestSlice(t,4);if(r instanceof Promise&&(r=yield r),t+=4,null===r)throw new Error(`Metadata block at position ${t} is too small! Corrupted file.`);p(r);const i=Sn(r),n=In(r),s=0!==(128&i);switch(127&i){case nt.STREAMINFO:{let e=this.reader.requestSlice(t,n);if(e instanceof Promise&&(e=yield e),p(e),null===e)throw new Error(`StreamInfo block at position ${t} is too small! Corrupted file.`);const r=Tn(e,34),i=new b(r),s=i.readBits(16),a=i.readBits(16),o=i.readBits(24),l=i.readBits(24),c=i.readBits(20),u=i.readBits(3)+1;i.readBits(5);const d=i.readBits(36);i.skipBits(128);const h=new Uint8Array(42);h.set(new Uint8Array([102,76,97,67]),0),h.set(new Uint8Array([128,0,0,34]),4),h.set(r,8),this.audioInfo={numberOfChannels:u,sampleRate:c,totalSamples:d,minimumBlockSize:s,maximumBlockSize:a,minimumFrameSize:o,maximumFrameSize:l,description:h},this.track=new Xt(this.input,new Li(this));break}case nt.VORBIS_COMMENT:{let e=this.reader.requestSlice(t,n);e instanceof Promise&&(e=yield e),p(e),at(Tn(e,n),this.metadataTags);break}case nt.PICTURE:{let r=this.reader.requestSlice(t,n);r instanceof Promise&&(r=yield r),p(r);const i=Cn(r),s=Cn(r),a=w.decode(Tn(r,s)),o=Cn(r),l=w.decode(Tn(r,o));r.skip(16);const c=Cn(r),u=Tn(r,c);null!=(e=this.metadataTags).images||(e.images=[]),this.metadataTags.images.push({data:u,mimeType:a,kind:3===i?"coverFront":4===i?"coverBack":"unknown",description:l});break}}if(t+=n,s){this.lastLoadedPos=t;break}}}))()})}readNextFlacFrame(e){return u(this,arguments,function*({startPos:e,isFirstPacket:t}){p(this.audioInfo);const r=this.audioInfo.maximumFrameSize+16,i=yield this.reader.requestSliceRange(e,this.audioInfo.minimumFrameSize,r);if(!i)return null;const n=this.readFlacFrameHeader({slice:i,isFirstPacket:t});if(!n)return null;for(i.filePos=e+this.audioInfo.minimumFrameSize;;){if(i.filePos>i.end-6)return{num:n.num,blockSize:n.blockSize,sampleRate:n.sampleRate,size:i.end-e,isLastFrame:!0};if(255===Sn(i)){const t=i.filePos;if(Sn(i)!==(1===this.blockingBit?249:248)){i.filePos=t;continue}i.skip(-2);const r=i.filePos-e,s=this.readFlacFrameHeader({slice:i,isFirstPacket:!1});if(!s){i.filePos=t;continue}if(0===this.blockingBit){if(s.num-n.num!==1){i.filePos=t;continue}}else if(s.num-n.num!==n.blockSize){i.filePos=t;continue}return{num:n.num,blockSize:n.blockSize,sampleRate:n.sampleRate,size:r,isLastFrame:!1}}}})}readFlacFrameHeader({slice:e,isFirstPacket:t}){const r=e.filePos,i=Tn(e,4),n=new b(i);if(32764!==n.readBits(15))return null;if(null===this.blockingBit){p(t);const e=n.readBits(1);this.blockingBit=e}else if(1===this.blockingBit){p(!t);if(1!==n.readBits(1))return null}else{if(0!==this.blockingBit)throw new Error("Invalid blocking bit");p(!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;p(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 r=new b(Tn(e,1));for(;1===r.readBits(1);)t++;if(0===t)return r.readBits(7);const i=[],n=t-1,s=new b(Tn(e,n)),a=8-t-1;for(let o=0;o<a;o++)i.unshift(r.readBits(1));for(let o=0;o<n;o++)for(let e=0;e<8;e++){const t=s.readBits(1);e<2||i.unshift(t)}return i.reduce((e,t,r)=>e|t<<r,0)})(e),c=((e,t)=>"uncommon-u16"===t?wn(e)+1:"uncommon-u8"===t?Sn(e)+1:"number"===typeof t?t:(q(t),void p(!1)))(e,s),u=((e,t)=>"uncommon-u16"===t?wn(e):"uncommon-u16-10"===t?10*wn(e):"uncommon-u8"===t?Sn(e):"number"===typeof t?t:null)(e,a);if(null===u)return null;if(u!==this.audioInfo.sampleRate)return null;const d=e.filePos-r,h=Sn(e);e.skip(-d),e.skip(-1);const m=(e=>{let t=0;for(const r of e){t^=r;for(let e=0;e<8;e++)0!==(128&t)?t=t<<1^7:t<<=1,t&=255}return t})(Tn(e,d));return h!==m?null:{num:l,blockSize:c,sampleRate:u}}advanceReader(){return u(this,null,function*(){yield this.readMetadata(),p(null!==this.lastLoadedPos),p(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 r=this.loadedSamples[this.loadedSamples.length-1],i={blockOffset:r?r.blockOffset+r.blockSize:0,blockSize:t.blockSize,byteOffset:e,byteSize:t.size};this.lastLoadedPos=this.lastLoadedPos+t.size,this.loadedSamples.push(i),t.isLastFrame&&(this.lastSampleLoaded=!0)})}}class Li{constructor(e){this.demuxer=e}getId(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return p(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}computeDuration(){return u(this,null,function*(){var e,t;const r=yield this.getPacket(1/0,{metadataOnly:!0});return(null!=(e=null==r?void 0:r.timestamp)?e:0)+(null!=(t=null==r?void 0:r.duration)?t:0)})}getSampleRate(){return p(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return $}getTimeResolution(){return p(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getDisposition(){return c({},ge)}getFirstTimestamp(){return u(this,null,function*(){return 0})}getDecoderConfig(){return u(this,null,function*(){return p(this.demuxer.audioInfo),{codec:"flac",numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}})}getPacket(e,t){return u(this,null,function*(){if(p(this.demuxer.audioInfo),e<0)throw new Error("Timestamp cannot be negative");const r=yield this.demuxer.readingMutex.acquire();try{for(;;){const r=N(this.demuxer.loadedSamples,e,e=>e.blockOffset/this.demuxer.audioInfo.sampleRate);if(-1===r){yield this.demuxer.advanceReader();continue}const i=this.demuxer.loadedSamples[r],n=i.blockOffset/this.demuxer.audioInfo.sampleRate;if(!(n+i.blockSize/this.demuxer.audioInfo.sampleRate<=e))return this.getPacketAtIndex(r,t);if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(this.demuxer.loadedSamples.length-1,t);yield this.demuxer.advanceReader()}}finally{r()}})}getNextPacket(e,t){return u(this,null,function*(){const r=yield this.demuxer.readingMutex.acquire();try{const r=e.sequenceNumber+1;if(this.demuxer.lastSampleLoaded&&r>=this.demuxer.loadedSamples.length)return null;for(;r>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)yield this.demuxer.advanceReader();return this.getPacketAtIndex(r,t)}finally{r()}})}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}getPacketAtIndex(e,t){return u(this,null,function*(){const r=this.demuxer.loadedSamples[e];if(!r)return null;let i;if(t.metadataOnly)i=ut;else{let e=this.demuxer.reader.requestSlice(r.byteOffset,r.byteSize);if(e instanceof Promise&&(e=yield e),!e)return null;i=Tn(e,r.byteSize)}p(this.demuxer.audioInfo);const n=r.blockOffset/this.demuxer.audioInfo.sampleRate,s=r.blockSize/this.demuxer.audioInfo.sampleRate;return new dt(i,"key",n,s,e,r.byteSize)})}getFirstPacket(e){return u(this,null,function*(){for(;0===this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)yield this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)})}}
|
|
/*!
|
|
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
*
|
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
*/class Ui{}class Vi extends Ui{_getMajorBrand(e){return u(this,null,function*(){let t=e._reader.requestSlice(0,12);if(t instanceof Promise&&(t=yield t),!t)return null;t.skip(4);return"ftyp"!==Nn(t,4)?null:Nn(t,4)})}_createDemuxer(e){return new ir(e)}}class qi extends Vi{_canReadInput(e){return u(this,null,function*(){const t=yield this._getMajorBrand(e);return!!t&&"qt "!==t})}get name(){return"MP4"}get mimeType(){return"video/mp4"}}class Hi extends Vi{_canReadInput(e){return u(this,null,function*(){return"qt "===(yield this._getMajorBrand(e))})}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}}class Wi extends Ui{isSupportedEBMLOfDocType(e,t){return u(this,null,function*(){let r=e._reader.requestSlice(0,yr);if(r instanceof Promise&&(r=yield r),!r)return!1;const i=Tr(r);if(null===i)return!1;if(i<1||i>8)return!1;if(vr(r,i)!==fr.EBML)return!1;const n=Ir(r);if("number"!==typeof n)return!1;let s=e._reader.requestSlice(r.filePos,n);if(s instanceof Promise&&(s=yield s),!s)return!1;const a=r.filePos;for(;s.filePos<=a+n-2;){const e=Pr(s);if(!e)break;const{id:r,size:i}=e,n=s.filePos;if(void 0===i)return!1;switch(r){case fr.EBMLVersion:if(1!==vr(s,i))return!1;break;case fr.EBMLReadVersion:if(1!==vr(s,i))return!1;break;case fr.DocType:if(xr(s,i)!==t)return!1;break;case fr.DocTypeVersion:if(vr(s,i)>4)return!1}s.filePos=n+i}return!0})}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new Xr(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}}class ji extends Wi{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}}class Ki extends Ui{_canReadInput(e){return u(this,null,function*(){let t=e._reader.requestSlice(0,10);if(t instanceof Promise&&(t=yield t),!t)return!1;let r=0,i=!1;for(;;){let t=e._reader.requestSlice(r,10);if(t instanceof Promise&&(t=yield t),!t)break;const n=di(t);if(!n)break;i=!0,r=t.filePos+n.size}const n=yield fi(e._reader,r,r+4096);if(!n)return!1;if(i)return!0;r=n.startPos+n.header.totalSize;const s=yield fi(e._reader,r,r+4);if(!s)return!1;const a=n.header,o=s.header;return a.channel===o.channel&&a.sampleRate===o.sampleRate})}_createDemuxer(e){return new pi(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}}class $i extends Ui{_canReadInput(e){return u(this,null,function*(){let t=e._reader.requestSlice(0,12);if(t instanceof Promise&&(t=yield t),!t)return!1;const r=Nn(t,4);if("RIFF"!==r&&"RIFX"!==r&&"RF64"!==r)return!1;t.skip(4);return"WAVE"===Nn(t,4)})}_createDemuxer(e){return new Fi(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}}class Qi extends Ui{_canReadInput(e){return u(this,null,function*(){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=yield t),!!t&&"OggS"===Nn(t,4)})}_createDemuxer(e){return new Pi(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}}class Gi extends Ui{_canReadInput(e){return u(this,null,function*(){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=yield t),!!t&&"fLaC"===Nn(t,4)})}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new Oi(e)}}class Xi extends Ui{_canReadInput(e){return u(this,null,function*(){let t=e._reader.requestSliceRange(0,7,9);if(t instanceof Promise&&(t=yield t),!t)return!1;const r=Ri(t);if(!r)return!1;if(t=e._reader.requestSliceRange(r.frameLength,7,9),t instanceof Promise&&(t=yield t),!t)return!1;const i=Ri(t);return!!i&&(r.objectType===i.objectType&&r.samplingFrequencyIndex===i.samplingFrequencyIndex&&r.channelConfiguration===i.channelConfiguration)})}_createDemuxer(e){return new Ni(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}}const Yi=new qi,Ji=new Hi,Zi=new Wi,en=new ji,tn=new Ki,rn=new $i,nn=new Qi,sn=new Xi,an=[Yi,Ji,Zi,en,rn,nn,new Gi,tn,sn];
|
|
/*!
|
|
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
*
|
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
*/
|
|
class on{constructor(){this._disposed=!1,this._sizePromise=null,this.onread=null}getSizeOrNull(){return u(this,null,function*(){var e;if(this._disposed)throw new gn;return null!=(e=this._sizePromise)?e:this._sizePromise=Promise.resolve(this._retrieveSize())})}getSize(){return u(this,null,function*(){if(this._disposed)throw new gn;const e=yield this.getSizeOrNull();if(null===e)throw new Error("Cannot determine the size of an unsized source.");return e})}}class ln extends on{constructor(e,t={}){var r;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&&(!me(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 fn({maxCacheSize:null!=(r=t.maxCacheSize)?r:8*o(2,20),maxWorkerCount:4,runWorker:this._runWorker.bind(this),prefetchProfile:mn.fileSystem})}_retrieveSize(){const e=this._blob.size;return this._orchestrator.fileSize=e,e}_read(e,t){return this._orchestrator.read(e,t)}_runWorker(e){return u(this,null,function*(){var t,r;let i=this._readers.get(e);if(void 0===i){if("stream"in this._blob&&!ie()){i=this._blob.slice(e.currentPos).stream().getReader()}else i=null;this._readers.set(e,i)}for(;e.currentPos<e.targetPos&&!e.aborted;)if(i){const{done:r,value:n}=yield i.read();if(r)throw this._orchestrator.forgetWorker(e),new Error("Blob reader stopped unexpectedly before all requested data was read.");if(e.aborted)break;null==(t=this.onread)||t.call(this,e.currentPos,e.currentPos+n.length),this._orchestrator.supplyWorkerData(e,n)}else{const t=yield this._blob.slice(e.currentPos,e.targetPos).arrayBuffer();if(e.aborted)break;null==(r=this.onread)||r.call(this,e.currentPos,e.currentPos+t.byteLength),this._orchestrator.supplyWorkerData(e,new Uint8Array(t))}e.running=!1,e.aborted&&(yield null==i?void 0:i.cancel())})}_dispose(){this._orchestrator.dispose()}}const cn=.5*o(2,20),un=(e,t,r)=>{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(r instanceof Request?r.url:r,window.location.href).origin)}catch(i){}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)};class dn extends on{constructor(e,t={}){var r,i;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&&(!me(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(void 0!==t.fetchFn&&"function"!==typeof t.fetchFn)throw new TypeError("options.fetchFn, when provided, must be a function.");super(),this._existingResponses=new WeakMap,this._url=e,this._options=t,this._getRetryDelay=null!=(r=t.getRetryDelay)?r:un,this._orchestrator=new fn({maxCacheSize:null!=(i=t.maxCacheSize)?i:64*o(2,20),maxWorkerCount:2,runWorker:this._runWorker.bind(this),prefetchProfile:mn.network})}_retrieveSize(){return u(this,null,function*(){var e,t;const r=new AbortController,i=yield ee(null!=(e=this._options.fetchFn)?e:fetch,this._url,J(null!=(t=this._options.requestInit)?t:{},{headers:{Range:"bytes=0-"},signal:r.signal}),this._getRetryDelay,()=>this._disposed);if(!i.ok)throw new Error(`Error fetching ${String(this._url)}: ${i.status} ${i.statusText}`);let n,s;if(206===i.status)s=this._getTotalLengthFromRangeResponse(i),n=this._orchestrator.createWorker(0,Math.min(s,cn));else{const e=i.headers.get("Content-Length");if(!e)throw new Error(`HTTP response (status ${i.status}) must surface Content-Length header.`);s=Number(e),n=this._orchestrator.createWorker(0,s),this._orchestrator.options.maxCacheSize=1/0,console.warn("HTTP server did not respond with 206 Partial Content, meaning the entire remote resource now has to be downloaded. For efficient media file streaming across a network, please make sure your server supports range requests.")}return this._orchestrator.fileSize=s,this._existingResponses.set(n,{response:i,abortController:r}),this._orchestrator.runWorker(n),s})}_read(e,t){return this._orchestrator.read(e,t)}_runWorker(e){return u(this,null,function*(){for(var t,r,i;;){const s=this._existingResponses.get(e);this._existingResponses.delete(e);let a=null==s?void 0:s.abortController,o=null==s?void 0:s.response;if(a||(a=new AbortController,o=yield ee(null!=(t=this._options.fetchFn)?t:fetch,this._url,J(null!=(r=this._options.requestInit)?r:{},{headers:{Range:`bytes=${e.currentPos}-`},signal:a.signal}),this._getRetryDelay,()=>this._disposed)),p(o),!o.ok)throw new Error(`Error fetching ${String(this._url)}: ${o.status} ${o.statusText}`);if(e.currentPos>0&&206!==o.status)throw new Error("HTTP server did not respond with 206 Partial Content to a range request. To enable efficient media file streaming across a network, please make sure your server supports range requests.");if(!o.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");const l=o.body.getReader();for(;;){if(e.currentPos>=e.targetPos||e.aborted)return a.abort(),void(e.running=!1);let t;try{t=yield l.read()}catch(n){if(this._disposed)throw n;const e=this._getRetryDelay(1,n,this._url);if(null!==e){console.error("Error while reading response stream. Attempting to resume.",n),yield new Promise(t=>setTimeout(t,1e3*e));break}throw n}if(e.aborted)continue;const{done:r,value:s}=t;if(r){if(e.currentPos>=e.targetPos)return this._orchestrator.forgetWorker(e),void(e.running=!1);break}null==(i=this.onread)||i.call(this,e.currentPos,e.currentPos+s.length),this._orchestrator.supplyWorkerData(e,s)}}})}_getTotalLengthFromRangeResponse(e){const t=e.headers.get("Content-Range");if(t){const e=/\/(\d+)/.exec(t);if(e)return Number(e[1])}const r=e.headers.get("Content-Length");if(r)return Number(r);throw new Error("Partial HTTP response (status 206) must surface either Content-Range or Content-Length header.")}_dispose(){this._orchestrator.dispose()}}class hn extends on{constructor(e,t={}){var r;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&&(!me(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!=(r=t.maxCacheSize)?r:16*o(2,20)}_retrieveSize(){return this._endIndex}_read(e,t){if(null!==this._endIndex&&t>this._endIndex)return null;this._maxRequestedIndex=Math.max(this._maxRequestedIndex,t);const r=N(this._cache,e,e=>e.start),i=-1!==r?this._cache[r]:null;if(i&&i.start<=e&&t<=i.end)return{bytes:i.bytes,view:i.view,offset:i.start};let n=e;const s=new Uint8Array(t-e);if(-1!==r)for(let c=r;c<this._cache.length;c++){const r=this._cache[c];if(r.start>=t)break;const i=Math.max(e,r.start);i>n&&this._throwDueToCacheMiss();const a=Math.min(t,r.end);i<a&&(s.set(r.bytes.subarray(i-r.start,a-r.start),i-e),n=a)}if(n===t)return{bytes:s,view:v(s),offset:e};this._currentIndex>n&&this._throwDueToCacheMiss();const{promise:a,resolve:o,reject:l}=O();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 u(this,null,function*(){for(null!=this._reader||(this._reader=this._stream.getReader());this._currentIndex<this._targetIndex&&!this._disposed;){const{done:e,value:t}=yield this._reader.read();if(e){for(const e of this._pendingSlices)e.resolve(null);this._pendingSlices.length=0,this._endIndex=this._currentIndex;break}const r=this._currentIndex,i=this._currentIndex+t.byteLength;for(let n=0;n<this._pendingSlices.length;n++){const e=this._pendingSlices[n],s=Math.max(r,e.start),a=Math.min(i,e.end);s<a&&(e.bytes.set(t.subarray(s-r,a-r),s-e.start),a===e.end&&(e.resolve({bytes:e.bytes,view:v(e.bytes),offset:e.start}),this._pendingSlices.splice(n,1),n--))}for(this._cache.push({start:r,end:i,bytes:t,view:v(t),age:0});this._cache.length>0;){const e=this._cache[0];if(this._maxRequestedIndex-e.end<=this._maxCacheSize)break;this._cache.shift()}this._currentIndex+=t.byteLength}this._pulling=!1})}_dispose(){this._pendingSlices.length=0,this._cache.length=0}}const mn={fileSystem:(e,t)=>{const r=o(2,16);return{start:e=Math.floor((e-r)/r)*r,end:t=Math.ceil((t+r)/r)*r}},network:(e,t,r)=>{const i=o(2,16);e=Math.max(0,Math.floor((e-i)/i)*i);for(const n of r){const r=8*o(2,20),i=Math.max((n.startPos+n.targetPos)/2,n.targetPos-r);if(ue(e,t,i,n.targetPos)){const e=n.targetPos-n.startPos,i=Math.ceil((e+1)/r)*r,s=o(2,Math.ceil(Math.log2(e+1))),a=Math.min(s,i);t=Math.max(t,n.startPos+a)}}return{start:e,end:t=Math.max(t,e+cn)}}};class fn{constructor(e){this.options=e,this.fileSize=null,this.nextAge=0,this.workers=[],this.cache=[],this.currentCacheSize=0,this.disposed=!1}read(e,t){p(null!==this.fileSize);const r=this.options.prefetchProfile(e,t,this.workers),i=Math.max(r.start,0),n=Math.min(r.end,this.fileSize);p(i<=e&&t<=n);let s=null;const a=N(this.cache,e,e=>e.start),l=-1!==a?this.cache[a]:null;l&&l.start<=e&&t<=l.end&&(l.age=this.nextAge++,s={bytes:l.bytes,view:l.view,offset:l.start});const c=N(this.cache,i,e=>e.start),u=s?null:new Uint8Array(t-e);let d=0,h=i;const m=[];if(-1!==c){for(let r=c;r<this.cache.length;r++){const s=this.cache[r];if(s.start>=n)break;if(s.end<=i)continue;const a=Math.max(i,s.start),o=Math.min(n,s.end);if(p(a<=o),h<a&&m.push({start:h,end:a}),h=o,u){const r=Math.max(e,s.start),i=Math.min(t,s.end);if(r<i){const t=r-e;u.set(s.bytes.subarray(r-s.start,i-s.start),t),t===d&&(d=i-e)}}s.age=this.nextAge++}h<n&&m.push({start:h,end:n})}else m.push({start:i,end:n});if(u&&d>=u.length&&(s={bytes:u,view:v(u),offset:e}),0===m.length)return p(s),s;const{promise:f,resolve:g,reject:k}=O(),b=[];for(const o of m){const r=Math.max(e,o.start),i=Math.min(t,o.end);r===o.start&&i===o.end?b.push(o):r<i&&b.push({start:r,end:i})}for(const p of m){const t=u&&{start:e,bytes:u,holes:b,resolve:g,reject:k};let r=!1;for(const e of this.workers){const i=o(2,17);if(ue(p.start-i,p.start,e.currentPos,e.targetPos)){e.targetPos=Math.max(e.targetPos,p.end),r=!0,t&&!e.pendingSlices.includes(t)&&e.pendingSlices.push(t),e.running||this.runWorker(e);break}}if(!r){const e=this.createWorker(p.start,p.end);t&&(e.pendingSlices=[t]),this.runWorker(e)}}return s||(p(u),s=f.then(t=>({bytes:t,view:v(t),offset:e}))),s}createWorker(e,t){const r={startPos:e,currentPos:e,targetPos:t,running:!1,aborted:this.disposed,pendingSlices:[],age:this.nextAge++};for(this.workers.push(r);this.workers.length>this.options.maxWorkerCount;){let e=0,t=this.workers[0];for(let r=1;r<this.workers.length;r++){const i=this.workers[r];i.age<t.age&&(e=r,t=i)}if(t.running&&t.pendingSlices.length>0)break;t.aborted=!0,this.workers.splice(e,1)}return r}runWorker(e){p(!e.running),p(e.currentPos<e.targetPos),e.running=!0,e.age=this.nextAge++,this.options.runWorker(e).catch(t=>{if(e.running=!1,!(e.pendingSlices.length>0))throw t;e.pendingSlices.forEach(e=>e.reject(t)),e.pendingSlices.length=0})}supplyWorkerData(e,t){p(!e.aborted);const r=e.currentPos,i=r+t.length;this.insertIntoCache({start:r,end:i,bytes:t,view:v(t),age:this.nextAge++}),e.currentPos+=t.length,e.targetPos=Math.max(e.targetPos,e.currentPos);for(let n=0;n<e.pendingSlices.length;n++){const s=e.pendingSlices[n],a=Math.max(r,s.start),o=Math.min(i,s.start+s.bytes.length);a<o&&s.bytes.set(t.subarray(a-r,o-r),a-s.start);for(let e=0;e<s.holes.length;e++){const t=s.holes[e];r<=t.start&&i>t.start&&(t.start=i),t.end<=t.start&&(s.holes.splice(e,1),e--)}0===s.holes.length&&(s.resolve(s.bytes),e.pendingSlices.splice(n,1),n--)}for(let n=0;n<this.workers.length;n++){const t=this.workers[n];e===t||t.running||ue(r,i,t.currentPos,t.targetPos)&&(this.workers.splice(n,1),n--)}}forgetWorker(e){const t=this.workers.indexOf(e);p(-1!==t),this.workers.splice(t,1)}insertIntoCache(e){if(0===this.options.maxCacheSize)return;let t=N(this.cache,e.start,e=>e.start)+1;if(t>0){const r=this.cache[t-1];if(r.end>=e.end)return;if(r.end>e.start){const i=new Uint8Array(e.end-r.start);i.set(r.bytes,0),i.set(e.bytes,e.start-r.start),this.currentCacheSize+=e.end-r.end,r.bytes=i,r.view=v(i),r.end=e.end,t--,e=r}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 r=t+1;r<this.cache.length;r++){const t=this.cache[r];if(e.end<=t.start)break;if(e.end>=t.end){this.cache.splice(r,1),this.currentCacheSize-=t.bytes.length,r--;continue}const i=new Uint8Array(t.end-e.start);i.set(e.bytes,0),i.set(t.bytes,t.start-e.start),this.currentCacheSize-=e.end-t.start,e.bytes=i,e.view=v(i),e.end=t.end,this.cache.splice(r,1);break}for(;this.currentCacheSize>this.options.maxCacheSize;){let e=0,t=this.cache[0];for(let r=1;r<this.cache.length;r++){const i=this.cache[r];i.age<t.age&&(e=r,t=i)}if(this.currentCacheSize-t.bytes.length<=this.options.maxCacheSize)break;this.cache.splice(e,1),this.currentCacheSize-=t.bytes.length}}dispose(){for(const e of this.workers)e.aborted=!0;this.workers.length=0,this.cache.length=0,this.disposed=!0}}
|
|
/*!
|
|
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
*
|
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
*/he();class pn{get disposed(){return this._disposed}constructor(e){if(this._demuxerPromise=null,this._format=null,this._disposed=!1,!e||"object"!==typeof e)throw new TypeError("options must be an object.");if(!Array.isArray(e.formats)||e.formats.some(e=>!(e instanceof Ui)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof on))throw new TypeError("options.source must be a Source.");if(e.source._disposed)throw new Error("options.source must not be disposed.");this._formats=e.formats,this._source=e.source,this._reader=new kn(e.source)}_getDemuxer(){var e;return null!=(e=this._demuxerPromise)?e:this._demuxerPromise=(()=>u(this,null,function*(){this._reader.fileSize=yield this._source.getSizeOrNull();for(const e of this._formats){if(yield e._canReadInput(this))return this._format=e,e._createDemuxer(this)}throw new Error("Input has an unsupported or unrecognizable format.")}))()}get source(){return this._source}getFormat(){return u(this,null,function*(){return yield this._getDemuxer(),p(this._format),this._format})}computeDuration(){return u(this,null,function*(){return(yield this._getDemuxer()).computeDuration()})}getTracks(){return u(this,null,function*(){return(yield this._getDemuxer()).getTracks()})}getVideoTracks(){return u(this,null,function*(){return(yield this.getTracks()).filter(e=>e.isVideoTrack())})}getAudioTracks(){return u(this,null,function*(){return(yield this.getTracks()).filter(e=>e.isAudioTrack())})}getPrimaryVideoTrack(){return u(this,null,function*(){var e;return null!=(e=(yield this.getTracks()).find(e=>e.isVideoTrack()))?e:null})}getPrimaryAudioTrack(){return u(this,null,function*(){var e;return null!=(e=(yield this.getTracks()).find(e=>e.isAudioTrack()))?e:null})}getMimeType(){return u(this,null,function*(){return(yield this._getDemuxer()).getMimeType()})}getMetadataTags(){return u(this,null,function*(){return(yield this._getDemuxer()).getMetadataTags()})}dispose(){this._disposed||(this._disposed=!0,this._source._disposed=!0,this._source._dispose())}[Symbol.dispose](){this.dispose()}}class gn extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}}
|
|
/*!
|
|
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
*
|
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
*/class kn{constructor(e){this.source=e}requestSlice(e,t){if(this.source._disposed)throw new gn;if(null!==this.fileSize&&e+t>this.fileSize)return null;const r=e+t,i=this.source._read(e,r);return i instanceof Promise?i.then(t=>t?new bn(t.bytes,t.view,t.offset,e,r):null):i?new bn(i.bytes,i.view,i.offset,e,r):null}requestSliceRange(e,t,r){if(this.source._disposed)throw new gn;if(null!==this.fileSize)return this.requestSlice(e,K(this.fileSize-e,t,r));{const i=this.requestSlice(e,r),n=i=>{if(i)return i;const n=i=>(p(null!==i),this.requestSlice(e,K(i-e,t,r))),s=this.source._retrieveSize();return s instanceof Promise?s.then(n):n(s)};return i instanceof Promise?i.then(n):n(i)}}}class bn{constructor(e,t,r,i,n){this.bytes=e,this.view=t,this.offset=r,this.start=i,this.end=n,this.bufferPos=i-r}static tempFromBytes(e){return new bn(e,v(e),0,0,e.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos(e){this.bufferPos=e-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip(e){this.bufferPos+=e}slice(e,t=this.end-e){if(e<this.start||e+t>this.end)throw new RangeError("Slicing outside of original slice.");return new bn(this.bytes,this.view,this.offset,e,e+t)}}const yn=(e,t)=>{if(e.filePos<e.start||e.filePos+t>e.end)throw new RangeError(`Tried reading [${e.filePos}, ${e.filePos+t}), but slice is [${e.start}, ${e.end}). This is likely an internal error, please report it alongside the file that caused it.`)},Tn=(e,t)=>{yn(e,t);const r=e.bytes.subarray(e.bufferPos,e.bufferPos+t);return e.bufferPos+=t,r},Sn=e=>(yn(e,1),e.view.getUint8(e.bufferPos++)),vn=(e,t)=>{yn(e,2);const r=e.view.getUint16(e.bufferPos,t);return e.bufferPos+=2,r},wn=e=>{yn(e,2);const t=e.view.getUint16(e.bufferPos,!1);return e.bufferPos+=2,t},In=e=>{yn(e,3);const t=H(e.view,e.bufferPos,!1);return e.bufferPos+=3,t},Pn=e=>{yn(e,2);const t=e.view.getInt16(e.bufferPos,!1);return e.bufferPos+=2,t},xn=(e,t)=>{yn(e,4);const r=e.view.getUint32(e.bufferPos,t);return e.bufferPos+=4,r},Cn=e=>{yn(e,4);const t=e.view.getUint32(e.bufferPos,!1);return e.bufferPos+=4,t},_n=e=>{yn(e,4);const t=e.view.getUint32(e.bufferPos,!0);return e.bufferPos+=4,t},Bn=e=>{yn(e,4);const t=e.view.getInt32(e.bufferPos,!1);return e.bufferPos+=4,t},En=(e,t)=>{let r,i;return t?(r=xn(e,!0),i=xn(e,!0)):(i=xn(e,!1),r=xn(e,!1)),4294967296*i+r},Fn=e=>4294967296*Cn(e)+Cn(e),Dn=e=>4294967296*Bn(e)+Cn(e),An=e=>{const t=_n(e),r=(e=>{yn(e,4);const t=e.view.getInt32(e.bufferPos,!0);return e.bufferPos+=4,t})(e);return 4294967296*r+t},Rn=e=>{yn(e,4);const t=e.view.getFloat32(e.bufferPos,!1);return e.bufferPos+=4,t},Mn=e=>{yn(e,8);const t=e.view.getFloat64(e.bufferPos,!1);return e.bufferPos+=8,t},Nn=(e,t)=>{yn(e,t);let r="";for(let i=0;i<t;i++)r+=String.fromCharCode(e.bytes[e.bufferPos++]);return r};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}normalizeSource(e){return"string"===typeof e?new dn(e):e instanceof Blob?new ln(e):"undefined"!==typeof ReadableStream&&e instanceof ReadableStream?new hn(e):e}ensureAudioContext(e){if(this.audioContext)return;const t=window.AudioContext||window.webkitAudioContext;try{this.audioContext=new t({sampleRate:e})}catch(r){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 u(this,null,function*(){var e;yield null==(e=this.audioIterator)?void 0:e.return(),this.audioIterator=null})}load(e,t){return u(this,null,function*(){const r=++this.asyncId;yield this.stopIterator(),this.stopQueuedNodes(),this.paused=!0,this.playbackTimeAtStart=0,this.audioContextStartTime=0;const i=this.normalizeSource(e);if(!i)return;if(this.input=new pn({source:i,formats:an}),this.duration=yield this.input.computeDuration(),r!==this.asyncId)return;const n=yield this.input.getPrimaryAudioTrack();return n&&null!==n.codec&&(yield n.canDecode())?(this.ensureAudioContext(n.sampleRate),this.audioSink=new $t(n),void(null==t||t())):(this.audioSink=null,this.ensureAudioContext(),void(null==t||t()))})}runIterator(e){return u(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 r=this.audioIterator.next(),i=setInterval(()=>{e!==this.asyncId||this.paused?clearInterval(i):"running"===this.audioContext.state&&this.audioContext.currentTime>=this.latestScheduledEndTime-.2&&(this.audioContext.suspend(),this.events.emit("waiting"))},50);let n;try{n=yield r}catch(t){console.error("Audio iterator error:",t);break}finally{clearInterval(i)}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 u(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 u(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}}class On{constructor({canvas:e,ctx:t,events:r,timeupdateInterval:i=250,avSyncTolerance:n=.12,dropLateFrames:s=!1,poster:a="",preflightRange:o=!1}){this.canvas=e,this.ctx=t,this.events=r,this.timeupdateInterval=i,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}normalizeSource(e){return"string"===typeof e?new dn(e):e instanceof Blob?new ln(e):"undefined"!==typeof ReadableStream&&e instanceof ReadableStream?new hn(e):e}preflight(e){return u(this,null,function*(){if(!this.preflightRange||"string"!==typeof 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 u(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 u(this,null,function*(){const r=++this.asyncId;if(yield this.stopIterator(),this.clear(),this.posterDrawn=!1,!(yield this.preflight(e)))return;const i=this.normalizeSource(e);if(!i)return void this.drawPoster();if(this.input=new pn({source:i,formats:an}),this.duration=yield this.input.computeDuration(),r!==this.asyncId)return;const n=yield this.input.getPrimaryVideoTrack();if(!n)return this.handleNoVideoTrack(),void(null==t||t());if(null===n.codec||!(yield n.canDecode()))return this.handleNoVideoTrack(),void(null==t||t());const s=yield n.canBeTransparent();this.videoSink=new Ht(n,{poolSize:2,fit:"contain",alpha:s}),this.width=n.displayWidth,this.height=n.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 u(this,null,function*(){var t,r;if(yield this.stopIterator(),!this.videoSink)return;this.videoIterator=this.videoSink.canvases(e);const i=null!=(t=(yield this.videoIterator.next()).value)?t:null,n=null!=(r=(yield this.videoIterator.next()).value)?r:null;this.nextFrame=n,i?(this.ctx.drawImage(i.canvas,0,0),this.events.emit("loadeddata")):this.drawPoster()})}updateNextFrame(e){return u(this,null,function*(){var t;if(this.videoIterator&&!this.isFetching){this.isFetching=!0;try{for(;;){const r=null!=(t=(yield this.videoIterator.next()).value)?t:null;if(!r||e!==this.asyncId)return;const i=this.audioClock.currentTime,n=this.dropLateFrames?Math.max(.06,this.avSyncTolerance/Math.max(1,this.playbackRate)):0;if(!(this.dropLateFrames&&r.timestamp<i-n)){if(!(r.timestamp<=i+n))return void(this.nextFrame=r);if(this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.ctx.drawImage(r.canvas,0,0),!this.dropLateFrames&&r.timestamp>i)return void(this.nextFrame=null)}}}finally{this.isFetching=!1}}})}render(){if(!this.audioClock)return;const e=this.audioClock.currentTime,t=Date.now();if(t-this.lastTimeUpdate>=this.timeupdateInterval&&(this.events.emit("timeupdate"),this.lastTimeUpdate=t),Number.isFinite(this.duration)&&e>=this.duration)return this.stop(),this.stalled=!1,this.events.emit("ended"),this.events.emit("pause"),void this.events.emit("canplay");this.nextFrame&&this.nextFrame.timestamp<=e?(this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.ctx.drawImage(this.nextFrame.canvas,0,0),this.nextFrame=null,this.updateNextFrame(this.asyncId),this.stalled&&(this.events.emit("canplay"),this.events.emit("playing"),this.stalled=!1)):this.nextFrame||(this.updateNextFrame(this.asyncId),!this.nextFrame&&Number.isFinite(this.duration)&&e<this.duration&&!this.stalled&&(this.stalled=!0,this.events.emit("waiting"))),this.rafId=requestAnimationFrame(()=>this.render())}start(e){this.audioClock=e,this.asyncId++,this.stalled=!1,this.updateNextFrame(this.asyncId),this.rafId=requestAnimationFrame(()=>this.render())}stop(){cancelAnimationFrame(this.rafId)}seek(e){return u(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.input=null,this.videoSink=null}}class Ln{constructor({canvas:e,ctx:t,events:r,option:i={}}){var n,s,a,o,l,c;this.events=r,this.option=i,this.audio=new zn(r),this.video=new On({canvas:e,ctx:t,events:r,timeupdateInterval:null!=(n=i.timeupdateInterval)?n:250,avSyncTolerance:null!=(s=i.avSyncTolerance)?s:.12,dropLateFrames:null!=(a=i.dropLateFrames)&&a,poster:null!=(o=i.poster)?o:"",preflightRange:null!=(l=i.preflightRange)&&l}),this.paused=!0,this.ended=!1,this.readyState=0,this.networkState=0,this.error=null,this.seeking=!1,this.loadSeq=0,null==(c=r.addEventListener)||c.call(r,"ended",()=>{this.ended=!0,this.paused=!0})}load(e){return u(this,null,function*(){const t=++this.loadSeq;this.pause(),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 r=Number.isFinite(this.option.loadTimeout)?this.option.loadTimeout:0;try{yield Promise.race([this.performLoad(e,t),r>0?this.createTimeout(r):new Promise(()=>{})])}catch(i){if(t!==this.loadSeq)return;this.loadSeq++,this.error={code:4,message:i.message},this.networkState=3,this.events.emit("error")}})}performLoad(e,t){return u(this,null,function*(){let r=!1,i=!1;const n=()=>{r&&i&&(this.readyState=1,this.events.emit("loadedmetadata"),this.events.emit("durationchange"),this.events.emit("progress"))};try{if(yield Promise.all([this.video.load(e,()=>{t===this.loadSeq&&(r=!0,n())}),this.audio.load(e,()=>{t===this.loadSeq&&(i=!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(s){if(t!==this.loadSeq)return;this.error={code:4,message:s.message},this.networkState=3,this.events.emit("error"),console.error("MediaBunny load error:",s)}})}createTimeout(e){return new Promise((t,r)=>{setTimeout(()=>r(new Error("Load timeout")),e)})}play(){return u(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 u(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.audio.destroy(),this.video.destroy()}get currentTime(){return this.audio.currentTime}get duration(){return this.audio.duration||this.video.duration}get videoWidth(){return this.video.width}get videoHeight(){return this.video.height}}class Un{constructor({art:e,canvas:t,ctx:r,option:i}){var n,s;this.art=e,this.canvas=t,this.option=i,this.events=new f,this.engine=new Ln({canvas:t,ctx:r,events:this.events,option:i}),this._src=null,this._volume=null!=(n=i.volume)?n:.7,this._muted=!!i.muted,this._playbackRate=1,this.engine.setVolume(this._volume,this._muted),this.setupEventForwarding(),i.source?this.src=i.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 r=this.engine.duration;return!r||Number.isNaN(r)||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,r){return Math.max(t,Math.min(r,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)}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()}}function Vn(e={}){return t=>{const{constructor:r}=t,{createElement:i}=r.utils,n=i("canvas"),s=n.getContext("2d"),a=new Un({art:t,canvas:n,ctx:s,option:e}),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),t.on("destroy",()=>{a.destroy()}),n}}return"undefined"!==typeof window&&(window.artplayerProxyMediabunny=Vn),Vn});
|