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
252 KiB
JavaScript
222 lines
252 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";class e{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 t(e){if(!e)throw new Error("Assertion failed.")}const r=e=>{const t=(e%360+360)%360;if(0===t||90===t||180===t||270===t)return t;throw new Error(`Invalid rotation ${e}.`)},i=e=>e&&e[e.length-1];class a{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){const e=Math.floor(this.pos/8),t=this.bytes[e]??0,r=7-(7&this.pos),i=(t&1<<r)>>r;return this.pos++,i}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 a=this.bytes[e];const s=7-(7&i);a&=~(1<<s),a|=(t&1<<r-i-1)>>r-i-1<<s,this.bytes[e]=a}this.pos=r}readAlignedByte(){if(this.pos%8!==0)throw new Error("Bitstream is not byte-aligned.");const e=this.pos/8,t=this.bytes[e]??0;return this.pos+=8,t}skipBits(e){this.pos+=e}getBitsLeft(){return 8*this.bytes.length-this.pos}clone(){const e=new a(this.bytes);return e.pos=this.pos,e}}const s=e=>{let t=0;for(;0===e.readBits(1)&&t<32;)t++;if(t>=32)throw new Error("Invalid exponential-Golomb code.");return(1<<t)-1+e.readBits(t)},n=e=>{const t=s(e);return 0===(1&t)?-(t>>1):t+1>>1},o=e=>e.constructor===Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),c=e=>e.constructor===DataView?e:ArrayBuffer.isView(e)?new DataView(e.buffer,e.byteOffset,e.byteLength):new DataView(e),l=new TextDecoder,d=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])),u={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},h=d(u),m={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},f=d(m),p={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},g=d(p),k=e=>e instanceof ArrayBuffer||"undefined"!==typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e);class b{constructor(){this.currentPromise=Promise.resolve()}async acquire(){let e;const t=new Promise(t=>{e=t}),r=this.currentPromise;return this.currentPromise=t,await r,e}}const T=e=>[...e].map(e=>e.toString(16).padStart(2,"0")).join(""),y=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,w=(e,t,r)=>{let i=0,a=e.length-1,s=-1;for(;i<=a;){const n=i+a>>1,o=r(e[n]);o===t?(s=n,a=n-1):o<t?i=n+1:a=n-1}return s},S=(e,t,r)=>{let i=0,a=e.length-1,s=-1;for(;i<=a;){const n=i+(a-i+1)/2|0;r(e[n])<=t?(s=n,i=n+1):a=n-1}return s},I=(e,t,r)=>{const i=S(e,r(t),r);e.splice(i+1,0,t)},v=()=>{let e,t;return{promise:new Promise((r,i)=>{e=r,t=i}),resolve:e,reject:t}},P=(e,t)=>{for(let r=e.length-1;r>=0;r--)if(t(e[r]))return e[r]},x=(e,t)=>{for(let r=e.length-1;r>=0;r--)if(t(e[r]))return r;return-1},C=e=>{throw new Error(`Unexpected value: ${e}`)},_=(e,t,r)=>{const i=e.getUint8(t),a=e.getUint8(t+1),s=e.getUint8(t+2);return r?i|a<<8|s<<16:i<<16|a<<8|s},B=(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)},E=(e,t)=>({async next(){const r=await 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}}),F=(e,t,r)=>Math.max(t,Math.min(r,e)),D="und",A=e=>{const t=Math.round(e);return Math.abs(e/t-1)<10*Number.EPSILON?t:e},R=/^[a-z]{3}$/,M=e=>R.test(e),N=1e6*(1+Number.EPSILON),z=(e,t)=>{const r={...e,...t};if(e.headers||t.headers){const i=e.headers?O(e.headers):{},a=t.headers?O(t.headers):{},s={...i};Object.entries(a).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},O=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},L=async(e,t,r,i,a)=>{let s=0;for(;;)try{return await e(t,r)}catch(n){if(a())throw n;s++;const e=i(s,n,t);if(null===e)throw n;if(console.error("Retrying failed fetch. Error:",n),!Number.isFinite(e)||e<0)throw new TypeError("Retry delay must be a non-negative finite number.");if(e>0&&await new Promise(t=>setTimeout(t,1e3*e)),a())throw n}};class U{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}let V=null;const q=()=>null!==V?V:V=!("undefined"===typeof navigator||!(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent)));let H=null;const W=()=>null!==H?H:H="undefined"!==typeof navigator&&navigator.userAgent?.includes("Firefox");let j=null;const K=()=>null!==j?j:j=!("undefined"===typeof navigator||!navigator.vendor?.includes("Google Inc")&&!/Chrome/.test(navigator.userAgent));let $=null;const Q=(e,t)=>-1!==e?e:t,G=(e,t,r,i)=>e<=i&&r<=t,X=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},Y=()=>{Symbol.dispose??(Symbol.dispose=Symbol("Symbol.dispose"))},J=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 Z{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 ee{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 te={default:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1},re=["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"],ie=[{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}],ae=".01.01.01.01.00",se=".0.110.01.01.01.0",ne=e=>{const{codec:r,codecDescription:a,colorSpace:s,avcCodecInfo:n,hevcCodecInfo:o,vp9CodecInfo:l,av1CodecInfo:d}=e;if("avc"===r){if(t(null!==e.avcType),n){const t=new Uint8Array([n.avcProfileIndication,n.profileCompatibility,n.avcLevelIndication]);return`avc${e.avcType}.${T(t)}`}if(!a||a.byteLength<4)throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${e.avcType}.${T(a.subarray(1,4))}`}if("hevc"===r){let e,t,r,i,s,n;if(o)e=o.generalProfileSpace,t=o.generalProfileIdc,r=y(o.generalProfileCompatibilityFlags),i=o.generalTierFlag,s=o.generalLevelIdc,n=[...o.generalConstraintIndicatorFlags];else{if(!a||a.byteLength<23)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");const o=c(a),l=o.getUint8(1);e=l>>6&3,t=31&l,r=y(o.getUint32(2)),i=l>>5&1,s=o.getUint8(12),n=[];for(let e=0;e<6;e++)n.push(o.getUint8(6+e))}let l="hev1.";for(l+=["","A","B","C"][e]+t,l+=".",l+=r.toString(16).toUpperCase(),l+=".",l+=0===i?"L":"H",l+=s;n.length>0&&0===n[n.length-1];)n.pop();return n.length>0&&(l+=".",l+=n.map(e=>e.toString(16).toUpperCase()).join(".")),l}if("vp8"===r)return"vp8";if("vp9"===r){if(!l){const t=e.width*e.height;let r=i(ie).level;for(const e of ie)if(t<=e.maxPictureSize){r=e.level;break}return`vp09.00.${r.toString().padStart(2,"0")}.08`}let t=`vp09.${l.profile.toString().padStart(2,"0")}.${l.level.toString().padStart(2,"0")}.${l.bitDepth.toString().padStart(2,"0")}.${l.chromaSubsampling.toString().padStart(2,"0")}`;return t+=`.${l.colourPrimaries.toString().padStart(2,"0")}.${l.transferCharacteristics.toString().padStart(2,"0")}.${l.matrixCoefficients.toString().padStart(2,"0")}.${l.videoFullRangeFlag.toString().padStart(2,"0")}`,t.endsWith(ae)&&(t=t.slice(0,-15)),t}if("av1"===r){if(!d){const t=e.width*e.height;let r=i(ie).level;for(const e of ie)if(t<=e.maxPictureSize){r=e.level;break}return`av01.0.${r.toString().padStart(2,"0")}M.08`}const t=d.profile,r=d.level.toString().padStart(2,"0"),a=d.tier?"H":"M",n=d.bitDepth.toString().padStart(2,"0"),o=d.monochrome?"1":"0",c=100*d.chromaSubsamplingX+10*d.chromaSubsamplingY+1*(d.chromaSubsamplingX&&d.chromaSubsamplingY?d.chromaSamplePosition:0),l=s?.primaries?u[s.primaries]:1,h=s?.transfer?m[s.transfer]:1,f=s?.matrix?p[s.matrix]:1,g=s?.fullRange?1:0;let k=`av01.${t}.${r}${a}.${n}`;return k+=`.${o}.${c.toString().padStart(3,"0")}`,k+=`.${l.toString().padStart(2,"0")}`,k+=`.${h.toString().padStart(2,"0")}`,k+=`.${f.toString().padStart(2,"0")}`,k+=`.${g}`,k.endsWith(se)&&(k=k.slice(0,-17)),k}throw new TypeError(`Unhandled codec '${r}'.`)},oe=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.${de(r).objectType}`}if("mp3"===t)return"mp3";if("opus"===t)return"opus";if("vorbis"===t)return"vorbis";if("flac"===t)return"flac";if(t&&re.includes(t))return t;throw new TypeError(`Unhandled codec '${t}'.`)},ce=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],le=[-1,1,2,3,4,5,6,8],de=e=>{if(!e||e.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");const t=new a(e);let r=t.readBits(5);31===r&&(r=32+t.readBits(6));const i=t.readBits(4);let s=null;15===i?s=t.readBits(24):i<ce.length&&(s=ce[i]);const n=t.readBits(4);let o=null;return n>=1&&n<=7&&(o=le[n]),{objectType:r,frequencyIndex:i,sampleRate:s,channelConfiguration:n,numberOfChannels:o}},ue=48e3,he=/^pcm-([usf])(\d+)+(be)?$/,me=e=>{if(t(re.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 r=he.exec(e);let i;t(r),i="u"===r[1]?"unsigned":"s"===r[1]?"signed":"float";return{dataType:i,sampleSize:Number(r[2])/8,littleEndian:"be"!==r[3],silentValue:"pcm-u8"===e?128: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 fe,pe,ge,ke;(pe=fe||(fe={}))[pe.IDR=5]="IDR",pe[pe.SEI=6]="SEI",pe[pe.SPS=7]="SPS",pe[pe.PPS=8]="PPS",pe[pe.SPS_EXT=13]="SPS_EXT",(ke=ge||(ge={}))[ke.RASL_N=8]="RASL_N",ke[ke.RASL_R=9]="RASL_R",ke[ke.BLA_W_LP=16]="BLA_W_LP",ke[ke.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",ke[ke.VPS_NUT=32]="VPS_NUT",ke[ke.SPS_NUT=33]="SPS_NUT",ke[ke.PPS_NUT=34]="PPS_NUT",ke[ke.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",ke[ke.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT";const be=e=>{const t=[];let r=0;for(;r<e.length;){let i=-1,a=0;for(let t=r;t<e.length-3;t++){if(0===e[t]&&0===e[t+1]&&1===e[t+2]){i=t,a=3;break}if(t<e.length-4&&0===e[t]&&0===e[t+1]&&0===e[t+2]&&1===e[t+3]){i=t,a=4;break}}if(-1===i)break;if(r>0&&i>r){const a=e.subarray(r,i);a.length>0&&t.push(a)}r=i+a}if(r<e.length){const i=e.subarray(r);i.length>0&&t.push(i)}return t},Te=(e,r)=>{const i=[];let a=0;const s=new DataView(e.buffer,e.byteOffset,e.byteLength);for(;a+r<=e.length;){let n;1===r?n=s.getUint8(a):2===r?n=s.getUint16(a,!1):3===r?n=_(s,a,!1):4===r?n=s.getUint32(a,!1):(C(r),t(!1)),a+=r;const o=e.subarray(a,a+n);i.push(o),a+=n}return i},ye=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)},we=new Uint8Array([0,0,0,1]),Se=(e,t)=>{if(t.description){const r=3&o(t.description)[4];return Te(e,r+1)}return be(e)},Ie=(e,t)=>{if(t.description){return((e,t)=>{const r=e.reduce((e,r)=>e+t+r.byteLength,0),i=new Uint8Array(r);let a=0;for(const s of e){const e=new DataView(i.buffer,i.byteOffset,i.byteLength);switch(t){case 1:e.setUint8(a,s.byteLength);break;case 2:e.setUint16(a,s.byteLength,!1);break;case 3:B(e,a,s.byteLength);break;case 4:e.setUint32(a,s.byteLength,!1)}a+=t,i.set(s,a),a+=s.byteLength}return i})(e,(3&o(t.description)[4])+1)}return(e=>{const t=e.reduce((e,t)=>e+we.byteLength+t.byteLength,0),r=new Uint8Array(t);let i=0;for(const a of e)r.set(we,i),i+=we.byteLength,r.set(a,i),i+=a.byteLength;return r})(e)},ve=e=>31&e[0],Pe=e=>{try{const r=be(e),i=r.filter(e=>ve(e)===fe.SPS),a=r.filter(e=>ve(e)===fe.PPS),s=r.filter(e=>ve(e)===fe.SPS_EXT);if(0===i.length)return null;if(0===a.length)return null;const n=i[0],o=xe(n);t(null!==o);const c=100===o.profileIdc||110===o.profileIdc||122===o.profileIdc||144===o.profileIdc;return{configurationVersion:1,avcProfileIndication:o.profileIdc,profileCompatibility:o.constraintFlags,avcLevelIndication:o.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:i,pictureParameterSets:a,chromaFormat:c?o.chromaFormatIdc:null,bitDepthLumaMinus8:c?o.bitDepthLumaMinus8:null,bitDepthChromaMinus8:c?o.bitDepthChromaMinus8:null,sequenceParameterSetExt:c?s:null}}catch(r){return console.error("Error building AVC Decoder Configuration Record:",r),null}},xe=e=>{try{const t=new a(ye(e));t.skipBits(1),t.skipBits(2);if(7!==t.readBits(5))return null;const r=t.readAlignedByte(),i=t.readAlignedByte(),o=t.readAlignedByte();s(t);let c=null,l=null,d=null;if(100===r||110===r||122===r||244===r||44===r||83===r||86===r||118===r||128===r){c=s(t),3===c&&t.skipBits(1),l=s(t),d=s(t),t.skipBits(1);if(t.readBits(1))for(let e=0;e<(3!==c?8:12);e++){if(t.readBits(1)){const r=e<6?16:64;let i=8,a=8;for(let e=0;e<r;e++){if(0!==a){a=(i+n(t)+256)%256}i=0===a?i:a}}}}s(t);const u=s(t);if(0===u)s(t);else if(1===u){t.skipBits(1),n(t),n(t);const e=s(t);for(let r=0;r<e;r++)n(t)}s(t),t.skipBits(1),s(t),s(t);return{profileIdc:r,constraintFlags:i,levelIdc:o,frameMbsOnlyFlag:t.readBits(1),chromaFormatIdc:c,bitDepthLumaMinus8:l,bitDepthChromaMinus8:d}}catch(t){return console.error("Error parsing AVC SPS:",t),null}},Ce=(e,t)=>{if(t.description){const r=3&o(t.description)[21];return Te(e,r+1)}return be(e)},_e=e=>e[0]>>1&63,Be=e=>{try{const t=be(e),r=t.filter(e=>_e(e)===ge.VPS_NUT),i=t.filter(e=>_e(e)===ge.SPS_NUT),o=t.filter(e=>_e(e)===ge.PPS_NUT),c=t.filter(e=>_e(e)===ge.PREFIX_SEI_NUT||_e(e)===ge.SUFFIX_SEI_NUT);if(0===i.length||0===o.length)return null;const l=i[0],d=new a(ye(l));d.skipBits(16),d.readBits(4);const u=d.readBits(3),h=d.readBits(1),{general_profile_space:m,general_tier_flag:f,general_profile_idc:p,general_profile_compatibility_flags:g,general_constraint_indicator_flags:k,general_level_idc:b}=Ee(d,u);s(d);const T=s(d);3===T&&d.skipBits(1),s(d),s(d),d.readBits(1)&&(s(d),s(d),s(d),s(d));const y=s(d),w=s(d);s(d);const S=d.readBits(1);for(let e=S?0:u;e<=u;e++)s(d),s(d),s(d);s(d),s(d),s(d),s(d),s(d),s(d),d.readBits(1)&&d.readBits(1)&&Fe(d),d.skipBits(1),d.skipBits(1),d.readBits(1)&&(d.skipBits(4),d.skipBits(4),s(d),s(d),d.skipBits(1));const I=s(d);if(De(d,I),d.readBits(1)){const e=s(d);for(let t=0;t<e;t++)s(d),d.skipBits(1)}d.skipBits(1),d.skipBits(1);let v=0;d.readBits(1)&&(v=Re(d,u));let P=0;if(o.length>0){const e=o[0],t=new a(ye(e));t.skipBits(16),s(t),s(t),t.skipBits(1),t.skipBits(1),t.skipBits(3),t.skipBits(1),t.skipBits(1),s(t),s(t),n(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&s(t),n(t),n(t),t.skipBits(1),t.skipBits(1),t.skipBits(1),t.skipBits(1);const 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:ge.VPS_NUT,nalUnits:r}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:ge.SPS_NUT,nalUnits:i}]:[],...o.length?[{arrayCompleteness:1,nalUnitType:ge.PPS_NUT,nalUnits:o}]:[],...c.length?[{arrayCompleteness:1,nalUnitType:_e(c[0]),nalUnits:c}]:[]];return{configurationVersion:1,generalProfileSpace:m,generalTierFlag:f,generalProfileIdc:p,generalProfileCompatibilityFlags:g,generalConstraintIndicatorFlags:k,generalLevelIdc:b,minSpatialSegmentationIdc:v,parallelismType:P,chromaFormatIdc:T,bitDepthLumaMinus8:y,bitDepthChromaMinus8:w,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:u+1,temporalIdNested:h,lengthSizeMinusOne:3,arrays:x}}catch(t){return console.error("Error building HEVC Decoder Configuration Record:",t),null}},Ee=(e,t)=>{const r=e.readBits(2),i=e.readBits(1),a=e.readBits(5);let s=0;for(let d=0;d<32;d++)s=s<<1|e.readBits(1);const n=new Uint8Array(6);for(let d=0;d<6;d++)n[d]=e.readBits(8);const o=e.readBits(8),c=[],l=[];for(let d=0;d<t;d++)c.push(e.readBits(1)),l.push(e.readBits(1));if(t>0)for(let d=t;d<8;d++)e.skipBits(2);for(let d=0;d<t;d++)c[d]&&e.skipBits(88),l[d]&&e.skipBits(8);return{general_profile_space:r,general_tier_flag:i,general_profile_idc:a,general_profile_compatibility_flags:s,general_constraint_indicator_flags:n,general_level_idc:o}},Fe=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&&n(e);for(let t=0;t<r;t++)n(e)}else s(e)}},De=(e,t)=>{const r=[];for(let i=0;i<t;i++)r[i]=Ae(e,i,t,r)},Ae=(e,t,r,i)=>{let a=0,n=0,o=0;if(0!==t&&(n=e.readBits(1)),n){if(t===r){o=t-(s(e)+1)}else o=t-1;e.readBits(1),s(e);const n=i[o]??0;for(let t=0;t<=n;t++){e.readBits(1)||e.readBits(1)}a=i[o]}else{const t=s(e),r=s(e);for(let i=0;i<t;i++)s(e),e.readBits(1);for(let i=0;i<r;i++)s(e),e.readBits(1);a=t+r}return a},Re=(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)&&(s(e),s(e)),e.readBits(1),e.readBits(1),e.readBits(1),e.readBits(1)&&(s(e),s(e),s(e),s(e)),e.readBits(1)&&(e.readBits(32),e.readBits(32),e.readBits(1)&&s(e),e.readBits(1)&&Me(e,!0,t)),e.readBits(1)){e.readBits(1),e.readBits(1),e.readBits(1);const t=s(e);return s(e),s(e),s(e),s(e),t}return 0},Me=(e,t,r)=>{let i=!1,a=!1,n=!1;i=1===e.readBits(1),a=1===e.readBits(1),(i||a)&&(n=1===e.readBits(1),n&&(e.readBits(8),e.readBits(5),e.readBits(1),e.readBits(5)),e.readBits(4),e.readBits(4),n&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5));for(let o=0;o<=r;o++){let t=!0;1===e.readBits(1)||(t=1===e.readBits(1));let r=!1;t?s(e):r=1===e.readBits(1);let o=1;if(!r){o=s(e)+1}i&&Ne(e,o,n),a&&Ne(e,o,n)}},Ne=(e,t,r)=>{for(let i=0;i<t;i++)s(e),s(e),r&&(s(e),s(e)),e.readBits(1)},ze=e=>{const t=new a(e);if(2!==t.readBits(2))return null;const r=t.readBits(1),s=(t.readBits(1)<<1)+r;3===s&&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(s>=2){n=t.readBits(1)?12:10}const o=t.readBits(3);let c=0,l=0;if(7!==o){if(l=t.readBits(1),1===s||3===s){const e=t.readBits(1),r=t.readBits(1);c=e||r?e&&!r?2:1:3,t.skipBits(1)}else c=1}else c=3,l=1;const d=(t.readBits(16)+1)*(t.readBits(16)+1);let u=i(ie).level;for(const i of ie)if(d<=i.maxPictureSize){u=i.level;break}return{profile:s,level:u,bitDepth:n,chromaSubsampling:c,videoFullRangeFlag:l,colourPrimaries:2===o?1:1===o?6:2,transferCharacteristics:2===o?1:1===o?6:2,matrixCoefficients:7===o?0:2===o?1:1===o?6:2}},Oe=function*(e){const r=new a(e),i=()=>{let e=0;for(let t=0;t<8;t++){const i=r.readAlignedByte();if(e|=(127&i)<<7*t,!(128&i))break;if(7===t&&128&i)return null}return e>=2**32-1?null:e};for(;r.getBitsLeft()>=8;){r.skipBits(1);const a=r.readBits(4),s=r.readBits(1),n=r.readBits(1);let o;if(r.skipBits(1),s&&r.skipBits(8),n){const e=i();if(null===e)return;o=e}else o=Math.floor(r.getBitsLeft()/8);t(r.pos%8===0),yield{type:a,data:e.subarray(r.pos/8,r.pos/8+o)},r.skipBits(8*o)}},Le=e=>{for(const{type:t,data:r}of Oe(e)){if(1!==t)continue;const e=new a(r),i=e.readBits(3);e.readBits(1);const s=e.readBits(1);let n=0,o=0,c=0;if(s)n=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&&(c=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&&(n=r),r>7){const t=e.readBits(1);0===i&&(o=t)}if(t){if(e.readBits(1)){const t=c+1;e.skipBits(t),e.skipBits(t),e.skipBits(1)}}e.readBits(1)&&e.skipBits(4)}}const l=e.readBits(4),d=e.readBits(4),u=l+1;e.skipBits(u);const h=d+1;e.skipBits(h);let m=0;if(m=s?0:e.readBits(1),m&&(e.skipBits(4),e.skipBits(3)),e.skipBits(1),e.skipBits(1),e.skipBits(1),!s){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 f=e.readBits(1);let p=8;if(2===i&&f){p=e.readBits(1)?12:10}else i<=2&&(p=f?10:8);let g=0;1!==i&&(g=e.readBits(1));let k=1,b=1,T=0;return g||(0===i?(k=1,b=1):1===i?(k=0,b=0):12===p&&(k=e.readBits(1),k&&(b=e.readBits(1))),k&&b&&(T=e.readBits(2))),{profile:i,level:n,tier:o,bitDepth:p,monochrome:g,chromaSubsamplingX:k,chromaSubsamplingY:b,chromaSamplePosition:T}}return null},Ue=[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],Ve=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 a=0;a<t;a++)r[a]=e[t-1-a];const i=new a(r);let s=0;for(;i.getBitsLeft()>97;)if(1===i.readBits(1)){s=i.pos;break}if(0===s)throw new Error("Invalid Setup header: framing bit not found.");let n=0,o=!1,c=0;for(;i.getBitsLeft()>=97;){const e=i.pos,t=i.readBits(8),r=i.readBits(16),a=i.readBits(16);if(t>63||0!==r||0!==a){i.pos=e;break}if(i.skipBits(1),n++,n>64)break;i.clone().readBits(6)+1===n&&(o=!0,c=n)}if(!o)throw new Error("Invalid Setup header: mode header not found.");if(c>63)throw new Error(`Unsupported mode count: ${c}.`);const l=c;i.pos=0,i.skipBits(s);const d=Array(l).fill(0);for(let a=l-1;a>=0;a--)i.skipBits(40),d[a]=i.readBits(1);return{modeBlockflags:d}},qe=(e,r,i)=>{switch(e){case"avc":{const e=Se(i,r);let t=e.some(e=>ve(e)===fe.IDR);if(!t&&(!K()||(()=>{if(null!==$)return $;if("undefined"===typeof navigator)return null;const e=/\bChrome\/(\d+)/.exec(navigator.userAgent);return e?$=Number(e[1]):null})()>=144))for(const r of e){if(ve(r)!==fe.SEI)continue;const e=ye(r);let i=1;do{let r=0;for(;;){const t=e[i++];if(void 0===t)break;if(r+=t,t<255)break}let n=0;for(;;){const t=e[i++];if(void 0===t)break;if(n+=t,t<255)break}if(r===6){const r=new a(e);r.pos=8*i;const n=s(r),o=r.readBits(1);if(0===n&&1===o){t=!0;break}}i+=n}while(i<e.length-1)}return t?"key":"delta"}case"hevc":return Ce(i,r).some(e=>{const t=_e(e);return ge.BLA_W_LP<=t&&t<=ge.RSV_IRAP_VCL23})?"key":"delta";case"vp8":return 0===(1&i[0])?"key":"delta";case"vp9":{const e=new a(i);if(2!==e.readBits(2))return null;const t=e.readBits(1);3===(e.readBits(1)<<1)+t&&e.skipBits(1);if(e.readBits(1))return null;return 0===e.readBits(1)?"key":"delta"}case"av1":{let e=!1;for(const{type:t,data:r}of Oe(i))if(1===t){const t=new a(r);t.skipBits(4),e=!!t.readBits(1)}else if(3===t||6===t||7===t){if(e)return"key";const t=new a(r);if(t.readBits(1))return null;return 0===t.readBits(2)?"key":"delta"}return null}default:C(e),t(!1)}};var He,We;(We=He||(He={}))[We.STREAMINFO=0]="STREAMINFO",We[We.VORBIS_COMMENT=4]="VORBIS_COMMENT",We[We.PICTURE=6]="PICTURE";const je=(e,t)=>{var r,i;const a=c(e);let s=0;const n=a.getUint32(s,!0);s+=4;const o=l.decode(e.subarray(s,s+n));s+=n,n>0&&(t.raw??(t.raw={}),(r=t.raw).vendor??(r.vendor=o));const d=a.getUint32(s,!0);s+=4;for(let u=0;u<d;u++){const r=a.getUint32(s,!0);s+=4;const n=l.decode(e.subarray(s,s+r));s+=r;const o=n.indexOf("=");if(-1===o)continue;const d=n.slice(0,o).toUpperCase(),u=n.slice(o+1);switch(t.raw??(t.raw={}),(i=t.raw)[d]??(i[d]=u),d){case"TITLE":t.title??(t.title=u);break;case"DESCRIPTION":t.description??(t.description=u);break;case"ARTIST":t.artist??(t.artist=u);break;case"ALBUM":t.album??(t.album=u);break;case"ALBUMARTIST":t.albumArtist??(t.albumArtist=u);break;case"COMMENT":t.comment??(t.comment=u);break;case"LYRICS":t.lyrics??(t.lyrics=u);break;case"TRACKNUMBER":{const e=u.split("/"),r=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(r)&&r>0&&(t.trackNumber??(t.trackNumber=r)),i&&Number.isInteger(i)&&i>0&&(t.tracksTotal??(t.tracksTotal=i))}break;case"TRACKTOTAL":{const e=Number.parseInt(u,10);Number.isInteger(e)&&e>0&&(t.tracksTotal??(t.tracksTotal=e))}break;case"DISCNUMBER":{const e=u.split("/"),r=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(r)&&r>0&&(t.discNumber??(t.discNumber=r)),i&&Number.isInteger(i)&&i>0&&(t.discsTotal??(t.discsTotal=i))}break;case"DISCTOTAL":{const e=Number.parseInt(u,10);Number.isInteger(e)&&e>0&&(t.discsTotal??(t.discsTotal=e))}break;case"DATE":{const e=new Date(u);Number.isNaN(e.getTime())||(t.date??(t.date=e))}break;case"GENRE":t.genre??(t.genre=u);break;case"METADATA_BLOCK_PICTURE":{const e=X(u),r=c(e),i=r.getUint32(0,!1),a=r.getUint32(4,!1),s=String.fromCharCode(...e.subarray(8,8+a)),n=r.getUint32(8+a,!1),o=l.decode(e.subarray(12+a,12+a+n)),d=r.getUint32(a+n+28),h=e.subarray(a+n+32,a+n+32+d);t.images??(t.images=[]),t.images.push({data:h,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 Ke{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 $e=[],Qe=[],Ge=new Uint8Array(0);class Xe{constructor(e,t,r,i,a=-1,s,n){if(this.data=e,this.type=t,this.timestamp=r,this.duration=i,this.sequenceNumber=a,e===Ge&&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(a))throw new TypeError("sequenceNumber must be a number.");if(!Number.isInteger(s)||s<0)throw new TypeError("byteLength must be a non-negative integer.");if(void 0!==n&&("object"!==typeof n||!n))throw new TypeError("sideData, when provided, must be an object.");if(void 0!==n?.alpha&&!(n.alpha instanceof Uint8Array))throw new TypeError("sideData.alpha, when provided, must be a Uint8Array.");if(void 0!==n?.alphaByteLength&&(!Number.isInteger(n.alphaByteLength)||n.alphaByteLength<0))throw new TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=s,this.sideData=n??{},this.sideData.alpha&&void 0===this.sideData.alphaByteLength&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===Ge}get microsecondTimestamp(){return Math.trunc(N*this.timestamp)}get microsecondDuration(){return Math.trunc(N*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if("undefined"===typeof EncodedVideoChunk)throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw new TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if("undefined"===typeof EncodedVideoChunk)throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to an audio chunk.");if("undefined"===typeof EncodedAudioChunk)throw new Error("Your browser does not support EncodedAudioChunk.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(e,t){if(!(e instanceof EncodedVideoChunk||e instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");const r=new Uint8Array(e.byteLength);return e.copyTo(r),new Xe(r,e.type,e.timestamp/1e6,(e.duration??0)/1e6,void 0,void 0,t)}clone(e){if(void 0!==e&&("object"!==typeof e||null===e))throw new TypeError("options, when provided, must be an object.");if(void 0!==e?.timestamp&&!Number.isFinite(e.timestamp))throw new TypeError("options.timestamp, when provided, must be a number.");if(void 0!==e?.duration&&!Number.isFinite(e.duration))throw new TypeError("options.duration, when provided, must be a number.");return new Xe(this.data,this.type,e?.timestamp??this.timestamp,e?.duration??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/.
|
|
*/
|
|
Y();let Ye=-1/0,Je=-1/0,Ze=null;"undefined"!==typeof FinalizationRegistry&&(Ze=new FinalizationRegistry(e=>{const t=Date.now();"video"===e.type?(t-Ye>=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."),Ye=t),"undefined"!==typeof VideoFrame&&e.data instanceof VideoFrame&&e.data.close()):(t-Je>=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."),Je=t),"undefined"!==typeof AudioData&&e.data instanceof AudioData&&e.data.close())}));const et=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],tt=new Set(et);class rt{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(N*this.timestamp)}get microsecondDuration(){return Math.trunc(N*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor(e,r){if(this._closed=!1,e instanceof ArrayBuffer||"undefined"!==typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e)){if(!r||"object"!==typeof r)throw new TypeError("init must be an object.");if(void 0===r.format||!tt.has(r.format))throw new TypeError("init.format must be one of: "+et.join(", "));if(!Number.isInteger(r.codedWidth)||r.codedWidth<=0)throw new TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(r.codedHeight)||r.codedHeight<=0)throw new TypeError("init.codedHeight must be a positive integer.");if(void 0!==r.rotation&&![0,90,180,270].includes(r.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(r.timestamp))throw new TypeError("init.timestamp must be a number.");if(void 0!==r.duration&&(!Number.isFinite(r.duration)||r.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");this._data=o(e).slice(),this._layout=r.layout??ct(r.format,r.codedWidth,r.codedHeight),this.format=r.format,this.codedWidth=r.codedWidth,this.codedHeight=r.codedHeight,this.rotation=r.rotation??0,this.timestamp=r.timestamp,this.duration=r.duration??0,this.colorSpace=new it(r.colorSpace)}else if("undefined"!==typeof VideoFrame&&e instanceof VideoFrame){if(void 0!==r?.rotation&&![0,90,180,270].includes(r.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(void 0!==r?.timestamp&&!Number.isFinite(r?.timestamp))throw new TypeError("init.timestamp, when provided, must be a number.");if(void 0!==r?.duration&&(!Number.isFinite(r.duration)||r.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=r?.rotation??0,this.timestamp=r?.timestamp??e.timestamp/1e6,this.duration=r?.duration??(e.duration??0)/1e6,this.colorSpace=new it(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(!r||"object"!==typeof r)throw new TypeError("init must be an object.");if(void 0!==r.rotation&&![0,90,180,270].includes(r.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(r.timestamp))throw new TypeError("init.timestamp must be a number.");if(void 0!==r.duration&&(!Number.isFinite(r.duration)||r.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if("undefined"!==typeof VideoFrame)return new rt(new VideoFrame(e,{timestamp:Math.trunc(r.timestamp*N),duration:Math.trunc((r.duration??0)*N)||void 0}),r);let i=0,a=0;if("naturalWidth"in e?(i=e.naturalWidth,a=e.naturalHeight):"videoWidth"in e?(i=e.videoWidth,a=e.videoHeight):"width"in e&&(i=Number(e.width),a=Number(e.height)),!i||!a)throw new TypeError("Could not determine dimensions.");const s=new OffscreenCanvas(i,a),n=s.getContext("2d",{alpha:W(),willReadFrequently:!0});t(n),n.drawImage(e,0,0),this._data=s,this._layout=null,this.format="RGBX",this.codedWidth=i,this.codedHeight=a,this.rotation=r.rotation??0,this.timestamp=r.timestamp,this.duration=r.duration??0,this.colorSpace=new it({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}}Ze?.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return t(null!==this._data),at(this._data)?new rt(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation}):this._data instanceof Uint8Array?(t(this._layout),new rt(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 rt(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||(Ze?.unregister(this),at(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(ot(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(t(null!==this._data),!at(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 at(this._data)?this._data.allocationSize(e):this._data instanceof Uint8Array?this._data.byteLength:this.codedWidth*this.codedHeight*4}async copyTo(e,r={}){if(!k(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(ot(r),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(t(null!==this._data),!at(this._data)&&(r.colorSpace||r.format&&r.format!==this.format||r.layout||r.rect)){const t=this.toVideoFrame(),i=await t.copyTo(e,r);return t.close(),i}if(at(this._data))return this._data.copyTo(e,r);if(this._data instanceof Uint8Array){t(this._layout);return o(e).set(this._data),this._layout}{const r=this._data.getContext("2d");t(r);const i=r.getImageData(0,0,this.codedWidth,this.codedHeight);return o(e).set(i.data),[{offset:0,stride:4*this.codedWidth}]}}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");return t(null!==this._data),at(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,a,s,n,o,c){let l=0,d=0,u=this.displayWidth,h=this.displayHeight,m=0,f=0,p=this.displayWidth,g=this.displayHeight;if(void 0!==s?(l=t,d=r,u=i,h=a,m=s,f=n,void 0!==o?(p=o,g=c):(p=u,g=h)):(m=t,f=r,void 0!==i&&(p=i,g=a)),!("undefined"!==typeof CanvasRenderingContext2D&&e instanceof CanvasRenderingContext2D||"undefined"!==typeof OffscreenCanvasRenderingContext2D&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(l))throw new TypeError("sx must be a number.");if(!Number.isFinite(d))throw new TypeError("sy must be a number.");if(!Number.isFinite(u)||u<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:l,sy:d,sWidth:u,sHeight:h}=this._rotateSourceRegion(l,d,u,h,this.rotation));const k=this.toCanvasImageSource();e.save();const b=m+p/2,T=f+g/2;e.translate(b,T),e.rotate(this.rotation*Math.PI/180);const y=this.rotation%180===0?1:p/g;e.scale(1/y,y),e.drawImage(k,l,d,u,h,-p/2,-g/2,p,g),e.restore()}drawWithFit(e,t){if(!("undefined"!==typeof CanvasRenderingContext2D&&e instanceof CanvasRenderingContext2D||"undefined"!==typeof OffscreenCanvasRenderingContext2D&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!t||"object"!==typeof t)throw new TypeError("options must be an object.");if(!["fill","contain","cover"].includes(t.fit))throw new TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");void 0!==t.crop&&nt(t.crop,"options.");const r=e.canvas.width,i=e.canvas.height,a=t.rotation??this.rotation,[s,n]=a%180===0?[this.codedWidth,this.codedHeight]:[this.codedHeight,this.codedWidth];let o,c,l,d;t.crop&&st(t.crop,s,n);const{sx:u,sy:h,sWidth:m,sHeight:f}=this._rotateSourceRegion(t.crop?.left??0,t.crop?.top??0,t.crop?.width??s,t.crop?.height??n,a);if("fill"===t.fit)o=0,c=0,l=r,d=i;else{const[e,a]=t.crop?[t.crop.width,t.crop.height]:[s,n],u="contain"===t.fit?Math.min(r/e,i/a):Math.max(r/e,i/a);l=e*u,d=a*u,o=(r-l)/2,c=(i-d)/2}e.save();const p=a%180===0?1:l/d;e.translate(r/2,i/2),e.rotate(a*Math.PI/180),e.scale(1/p,p),e.translate(-r/2,-i/2),e.drawImage(this.toCanvasImageSource(),u,h,m,f,o,c,l,d),e.restore()}_rotateSourceRegion(e,t,r,i,a){return 90===a?[e,t,r,i]=[t,this.codedHeight-e-r,i,r]:180===a?[e,t]=[this.codedWidth-e-r,this.codedHeight-t-i]:270===a&&([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(t(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 it{constructor(e){this.primaries=e?.primaries??null,this.transfer=e?.transfer??null,this.matrix=e?.matrix??null,this.fullRange=e?.fullRange??null}toJSON(){return{primaries:this.primaries,transfer:this.transfer,matrix:this.matrix,fullRange:this.fullRange}}}const at=e=>"undefined"!==typeof VideoFrame&&e instanceof VideoFrame,st=(e,r,i)=>{e.left=Math.min(e.left,r),e.top=Math.min(e.top,i),e.width=Math.min(e.width,r-e.left),e.height=Math.min(e.height,i-e.top),t(e.width>=0),t(e.height>=0)},nt=(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.")},ot=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.")}},ct=(e,t,r)=>{const i=lt(e),a=[];let s=0;for(const n of i){const e=Math.ceil(t/n.widthDivisor),i=Math.ceil(r/n.heightDivisor),o=e*n.sampleBytes,c=o*i;a.push({offset:s,stride:o}),s+=c}return a},lt=e=>{const r=(e,t,r,i,a)=>{const s=[{sampleBytes:e,widthDivisor:1,heightDivisor:1},{sampleBytes:t,widthDivisor:r,heightDivisor:i},{sampleBytes:t,widthDivisor:r,heightDivisor:i}];return a&&s.push({sampleBytes:e,widthDivisor:1,heightDivisor:1}),s};switch(e){case"I420":return r(1,1,2,2,!1);case"I420P10":case"I420P12":return r(2,2,2,2,!1);case"I420A":return r(1,1,2,2,!0);case"I420AP10":case"I420AP12":return r(2,2,2,2,!0);case"I422":return r(1,1,2,1,!1);case"I422P10":case"I422P12":return r(2,2,2,1,!1);case"I422A":return r(1,1,2,1,!0);case"I422AP10":case"I422AP12":return r(2,2,2,1,!0);case"I444":return r(1,1,1,1,!1);case"I444P10":case"I444P12":return r(2,2,1,1,!1);case"I444A":return r(1,1,1,1,!0);case"I444AP10":case"I444AP12":return r(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:C(e),t(!1)}},dt=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]);class ut{get microsecondTimestamp(){return Math.trunc(N*this.timestamp)}get microsecondDuration(){return Math.trunc(N*this.duration)}constructor(e){if(this._closed=!1,gt(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(!dt.has(e.format))throw new TypeError("Invalid AudioDataInit: invalid format.");if(!Number.isFinite(e.sampleRate)||e.sampleRate<=0)throw new TypeError("Invalid AudioDataInit: sampleRate must be > 0.");if(!Number.isInteger(e.numberOfChannels)||0===e.numberOfChannels)throw new TypeError("Invalid AudioDataInit: numberOfChannels must be an integer > 0.");if(!Number.isFinite(e?.timestamp))throw new TypeError("init.timestamp must be a number.");const t=e.data.byteLength/(ht(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*ht(this.format);if(r.byteLength<i)throw new TypeError("Invalid AudioDataInit: insufficient data size.");this._data=r}Ze?.register(this,{type:"audio",data:this._data},this)}allocationSize(e){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&&!dt.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 t=e.format??this.format,r=e.frameOffset??0;if(r>=this.numberOfFrames)throw new RangeError("frameOffset out of range");const i=void 0!==e.frameCount?e.frameCount:this.numberOfFrames-r;if(i>this.numberOfFrames-r)throw new RangeError("frameCount out of range");const a=ht(t),s=mt(t);if(s&&e.planeIndex>=this.numberOfChannels)throw new RangeError("planeIndex out of range");if(!s&&0!==e.planeIndex)throw new RangeError("planeIndex out of range");return(s?i:i*this.numberOfChannels)*a}copyTo(e,t){if(!k(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(!t||"object"!==typeof t)throw new TypeError("options must be an object.");if(!Number.isInteger(t.planeIndex)||t.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(void 0!==t.format&&!dt.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:a,frameOffset:s}=t,n=this.format,o=i??this.format;if(!o)throw new Error("Destination format not determined");const l=this.numberOfFrames,d=this.numberOfChannels,u=s??0;if(u>=l)throw new RangeError("frameOffset out of range");const h=void 0!==a?a:l-u;if(h>l-u)throw new RangeError("frameCount out of range");const m=ht(o),f=mt(o);if(f&&r>=d)throw new RangeError("planeIndex out of range");if(!f&&0!==r)throw new RangeError("planeIndex out of range");const p=(f?h:h*d)*m;if(e.byteLength<p)throw new RangeError("Destination buffer is too small");const g=c(e),b=pt(o);if(gt(this._data))q()&&d>2&&o!==n?kt(this._data,g,n,o,d,r,u,h):this._data.copyTo(e,{planeIndex:r,frameOffset:u,frameCount:h,format:o});else{const e=this._data,t=c(e),i=ft(n),a=ht(n),s=mt(n);for(let n=0;n<h;n++)if(f){let e;e=s?(r*l+(n+u))*a:((n+u)*d+r)*a;b(g,n*m,i(t,e))}else for(let e=0;e<d;e++){let r;r=s?(e*l+(n+u))*a:((n+u)*d+e)*a;b(g,(n*d+e)*m,i(t,r))}}}clone(){if(this._closed)throw new Error("AudioSample is closed.");if(gt(this._data)){const e=new ut(this._data.clone());return e.setTimestamp(this.timestamp),e}return new ut({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data})}close(){this._closed||(Ze?.unregister(this),gt(this._data)?this._data.close():this._data=new Uint8Array(0),this._closed=!0)}toAudioData(){if(this._closed)throw new Error("AudioSample is closed.");if(gt(this._data)){if(this._data.timestamp===this.microsecondTimestamp)return this._data.clone();if(mt(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,a=e.length,s=Math.floor(24e4/r);let n=0,o=a;for(;o>0;){const a=Math.min(s,o),c=new Float32Array(r*a);for(let t=0;t<r;t++)e.copyFromChannel(c.subarray(t*a,(t+1)*a),t,n);yield new ut({format:"f32-planar",sampleRate:i,numberOfFrames:a,numberOfChannels:r,timestamp:t+n/i,data:c}),n+=a,o-=a}}static fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");const r=e.numberOfChannels,i=e.sampleRate,a=e.length,s=Math.floor(24e4/r);let n=0,o=a;const c=[];for(;o>0;){const a=Math.min(s,o),l=new Float32Array(r*a);for(let t=0;t<r;t++)e.copyFromChannel(l.subarray(t*a,(t+1)*a),t,n);const d=new ut({format:"f32-planar",sampleRate:i,numberOfFrames:a,numberOfChannels:r,timestamp:t+n/i,data:l});c.push(d),n+=a,o-=a}return c}}const ht=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")}},mt=e=>{switch(e){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},ft=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)}},pt=e=>{switch(e){case"u8":case"u8-planar":return(e,t,r)=>e.setUint8(t,F(127.5*(r+1),0,255));case"s16":case"s16-planar":return(e,t,r)=>e.setInt16(t,F(Math.round(32767*r),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,r)=>e.setInt32(t,F(Math.round(2147483647*r),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,r)=>e.setFloat32(t,r,!0)}},gt=e=>"undefined"!==typeof AudioData&&e instanceof AudioData,kt=(e,t,r,i,a,s,n,o)=>{const l=ft(r),d=pt(i),u=ht(r),h=ht(i),m=mt(r);if(mt(i))if(m){const i=new ArrayBuffer(o*u),a=c(i);e.copyTo(i,{planeIndex:s,frameOffset:n,frameCount:o,format:r});for(let e=0;e<o;e++){d(t,e*h,l(a,e*u))}}else{const i=new ArrayBuffer(o*a*u),m=c(i);e.copyTo(i,{planeIndex:0,frameOffset:n,frameCount:o,format:r});for(let e=0;e<o;e++){d(t,e*h,l(m,(e*a+s)*u))}}else if(m){const i=new ArrayBuffer(o*u),s=c(i);for(let c=0;c<a;c++){e.copyTo(i,{planeIndex:c,frameOffset:n,frameCount:o,format:r});for(let e=0;e<o;e++){d(t,(e*a+c)*h,l(s,e*u))}}}else{const i=new ArrayBuffer(o*a*u),s=c(i);e.copyTo(i,{planeIndex:0,frameOffset:n,frameCount:o,format:r});for(let e=0;e<o;e++)for(let r=0;r<a;r++){const i=e*a+r;d(t,i*h,l(s,i*u))}}},bt=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.")},Tt=e=>{if(!J(e))throw new TypeError("timestamp must be a number.")},yt=(e,t,r)=>r.verifyKeyPackets?t.then(async t=>{if(!t||"delta"===t.type)return t;const r=await e.determinePacketType(t);return r&&(t.type=r),t}):t;class wt{constructor(e){if(!(e instanceof At))throw new TypeError("track must be an InputTrack.");this._track=e}getFirstPacket(e={}){if(bt(e),this._track.input._disposed)throw new ea;return yt(this._track,this._track._backing.getFirstPacket(e),e)}getPacket(e,t={}){if(Tt(e),bt(t),this._track.input._disposed)throw new ea;return yt(this._track,this._track._backing.getPacket(e,t),t)}getNextPacket(e,t={}){if(!(e instanceof Xe))throw new TypeError("packet must be an EncodedPacket.");if(bt(t),this._track.input._disposed)throw new ea;return yt(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,r={}){if(Tt(e),bt(r),this._track.input._disposed)throw new ea;if(!r.verifyKeyPackets)return this._track._backing.getKeyPacket(e,r);const i=await this._track._backing.getKeyPacket(e,r);if(!i)return i;t("key"===i.type);return"delta"===await this._track.determinePacketType(i)?this.getKeyPacket(i.timestamp-1/this._track.timeResolution,r):i}async getNextKeyPacket(e,r={}){if(!(e instanceof Xe))throw new TypeError("packet must be an EncodedPacket.");if(bt(r),this._track.input._disposed)throw new ea;if(!r.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,r);const i=await this._track._backing.getNextKeyPacket(e,r);if(!i)return i;t("key"===i.type);return"delta"===await this._track.determinePacketType(i)?this.getNextKeyPacket(i,r):i}packets(e,t,r={}){if(void 0!==e&&!(e instanceof Xe))throw new TypeError("startPacket must be an EncodedPacket.");if(void 0!==e&&e.isMetadataOnly&&!r?.metadataOnly)throw new TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(void 0!==t&&!(t instanceof Xe))throw new TypeError("endPacket must be an EncodedPacket.");if(bt(r),this._track.input._disposed)throw new ea;const i=[];let{promise:a,resolve:s}=v(),{promise:n,resolve:o}=v(),c=!1,l=!1,d=null;const u=[],h=()=>Math.max(2,u.length);(async()=>{let d=e??await this.getFirstPacket(r);for(;d&&!l&&!this._track.input._disposed&&!(t&&d.sequenceNumber>=t?.sequenceNumber);)i.length>h()?(({promise:n,resolve:o}=v()),await n):(i.push(d),s(),({promise:a,resolve:s}=v()),d=await this.getNextPacket(d,r));c=!0,s()})().catch(e=>{d||(d=e,s())});const m=this._track;return{async next(){for(;;){if(m.input._disposed)throw new ea;if(l)return{value:void 0,done:!0};if(d)throw d;if(i.length>0){const e=i.shift(),t=performance.now();for(u.push(t);u.length>0&&t-u[0]>=1e3;)u.shift();return o(),{value:e,done:!1}}if(c)return{value:void 0,done:!0};await a}},return:async()=>(l=!0,o(),s(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}}class St{constructor(e,t){this.onSample=e,this.onError=t}}class It{mediaSamplesInRange(e=0,t=1/0){Tt(e),Tt(t);const r=[];let i=!1,a=null,{promise:s,resolve:n}=v(),{promise:o,resolve:c}=v(),l=!1,d=!1,u=!1,h=null;(async()=>{const m=await this._createDecoder(o=>{c(),o.timestamp>=t&&(d=!0),d?o.close():(a&&(o.timestamp>e?(r.push(a),i=!0):a.close()),o.timestamp>=e&&(r.push(o),i=!0),a=i?null:o,r.length>0&&(n(),({promise:s,resolve:n}=v())))},e=>{h||(h=e,n())}),f=this._createPacketSink(),p=await f.getKeyPacket(e,{verifyKeyPackets:!0})??await f.getFirstPacket();let g=p;const k=f.packets(p??void 0,void 0);for(await k.next();g&&!d&&!this._track.input._disposed;){const e=vt(r.length);if(r.length+m.getDecodeQueueSize()>e){({promise:o,resolve:c}=v()),await o;continue}m.decode(g);const t=await k.next();if(t.done)break;g=t.value}await k.return(),u||this._track.input._disposed||await m.flush(),m.close(),!i&&a&&r.push(a),l=!0,n()})().catch(e=>{h||(h=e,n())});const m=this._track,f=()=>{a?.close();for(const e of r)e.close()};return{async next(){for(;;){if(m.input._disposed)throw f(),new ea;if(u)return{value:void 0,done:!0};if(h)throw f(),h;if(r.length>0){const e=r.shift();return c(),{value:e,done:!1}}if(l)return{value:void 0,done:!0};await s}},return:async()=>(u=!0,d=!0,c(),n(),f(),{value:void 0,done:!0}),async throw(e){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 r=async function*(e){Symbol.iterator in e?yield*e[Symbol.iterator]():yield*e[Symbol.asyncIterator]()}(e),i=[],a=[];let{promise:s,resolve:n}=v(),{promise:o,resolve:c}=v(),l=!1,d=!1,u=null;const h=e=>{a.push(e),n(),({promise:s,resolve:n}=v())};(async()=>{const e=await this._createDecoder(e=>{if(c(),d)return void e.close();let t=0;for(;i.length>0&&e.timestamp-i[0]>-1e-10;)t++,i.shift();if(t>0)for(let r=0;r<t;r++)h(r<t-1?e.clone():e);else e.close()},e=>{u||(u=e,n())}),s=this._createPacketSink();let m=null,f=null,p=-1;const g=async()=>{t(f);let r=f;for(e.decode(r);r.sequenceNumber<p;){const i=vt(a.length);for(;a.length+e.getDecodeQueueSize()>i&&!d;)({promise:o,resolve:c}=v()),await o;if(d)break;const n=await s.getNextPacket(r);t(n),e.decode(n),r=n}p=-1},k=async()=>{await e.flush();for(let e=0;e<i.length;e++)h(null);i.length=0};for await(const t of r){if(Tt(t),d||this._track.input._disposed)break;const e=await s.getPacket(t),r=e&&await s.getKeyPacket(t,{verifyKeyPackets:!0});r?(m&&(r.sequenceNumber!==f.sequenceNumber||e.timestamp<m.timestamp)&&(await g(),await k()),i.push(e.timestamp),p=Math.max(e.sequenceNumber,p),m=e,f=r):(-1!==p&&(await g(),await k()),h(null),m=null)}d||this._track.input._disposed||(-1!==p&&await g(),await k()),e.close(),l=!0,n()})().catch(e=>{u||(u=e,n())});const m=this._track,f=()=>{for(const e of a)e?.close()};return{async next(){for(;;){if(m.input._disposed)throw f(),new ea;if(d)return{value:void 0,done:!0};if(u)throw f(),u;if(a.length>0){const e=a.shift();return t(void 0!==e),c(),{value:e,done:!1}}if(l)return{value:void 0,done:!0};await s}},return:async()=>(d=!0,c(),n(),f(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}}const vt=e=>0===e?40:8;class Pt extends St{constructor(e,r,i,a,s,n){super(e,r),this.codec=i,this.decoderConfig=a,this.rotation=s,this.timeResolution=n,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new U,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=$e.find(e=>e.supports(i,a));if(l)this.customDecoder=new l,this.customDecoder.codec=i,this.customDecoder.config=a,this.customDecoder.onSample=e=>{if(!(e instanceof rt))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 r=this.alphaQueue.shift();t(void 0!==r),this.mergeAlpha(e,r)}else this.colorQueue.push(e)};if("avc"===i&&this.decoderConfig.description&&K()){const e=(e=>{try{const t=c(e);let r=0;const i=t.getUint8(r++),a=t.getUint8(r++),s=t.getUint8(r++),n=t.getUint8(r++),o=3&t.getUint8(r++),l=31&t.getUint8(r++),d=[];for(let c=0;c<l;c++){const i=t.getUint16(r,!1);r+=2,d.push(e.subarray(r,r+i)),r+=i}const u=t.getUint8(r++),h=[];for(let c=0;c<u;c++){const i=t.getUint16(r,!1);r+=2,h.push(e.subarray(r,r+i)),r+=i}const m={configurationVersion:i,avcProfileIndication:a,profileCompatibility:s,avcLevelIndication:n,lengthSizeMinusOne:o,sequenceParameterSets:d,pictureParameterSets:h,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((100===a||110===a||122===a||144===a)&&r+4<=e.length){const i=3&t.getUint8(r++),a=7&t.getUint8(r++),s=7&t.getUint8(r++),n=t.getUint8(r++);m.chromaFormat=i,m.bitDepthLumaMinus8=a,m.bitDepthChromaMinus8=s;const o=[];for(let c=0;c<n;c++){const i=t.getUint16(r,!1);r+=2,o.push(e.subarray(r,r+i)),r+=i}m.sequenceParameterSetExt=o}return m}catch(t){return console.error("Error deserializing AVC Decoder Configuration Record:",t),null}})(o(this.decoderConfig.description));if(e&&e.sequenceParameterSets.length>0){const t=xe(e.sequenceParameterSets[0]);t&&0===t.frameMbsOnlyFlag&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"})}}const r=new Error("Decoding error").stack;this.decoder=new VideoDecoder({output:t=>{try{e(t)}catch(r){this.onError(r)}},error:e=>{e.stack=r,this.onError(e)}}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(t(this.decoder),Math.max(this.decoder.decodeQueueSize,this.alphaDecoder?.decodeQueueSize??0))}decode(e){if("hevc"===this.codec&&this.currentPacketIndex>0&&!this.raslSkipped){if(this.hasHevcRaslPicture(e.data))return;this.raslSkipped=!0}if(this.customDecoder)this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--);else{if(t(this.decoder),q()||I(this.inputTimestamps,e.timestamp,e=>e),K()&&0===this.currentPacketIndex&&"avc"===this.codec){const t=Se(e.data,this.decoderConfig).filter(e=>{const t=ve(e);return!(t>=20&&t<=31)}),r=Ie(t,this.decoderConfig);e=new Xe(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 xt}catch(i){return console.error("Due to an error, only color data will be decoded.",i),this.mergerCreationFailed=!0,void this.decodeAlphaData(e)}if(!this.alphaDecoder){const e=e=>{if(this.alphaDecoderQueueSize--,this.colorQueue.length>0){const r=this.colorQueue.shift();t(void 0!==r),this.mergeAlpha(r,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();t(void 0!==e),this.mergeAlpha(e,null)}else this.alphaQueue.push(null)},r=new Error("Decoding error").stack;this.alphaDecoder=new VideoDecoder({output:t=>{try{e(t)}catch(i){this.onError(i)}},error:e=>{e.stack=r,this.onError(e)}}),this.alphaDecoder.configure(this.decoderConfig)}const r=qe(this.codec,this.decoderConfig,e.sideData.alpha);if(this.alphaHadKeyframe||(this.alphaHadKeyframe="key"===r),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(r??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 Ce(e,this.decoderConfig).some(e=>{const t=_e(e);return t===ge.RASL_N||t===ge.RASL_R})}sampleHandler(e){if(q()){if(this.sampleQueue.length>0&&e.timestamp>=i(this.sampleQueue).timestamp){for(const e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}I(this.sampleQueue,e,e=>e.timestamp)}else{const r=this.inputTimestamps.shift();t(void 0!==r),e.setTimestamp(r),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,r){if(!r){const t=new rt(e);return void this.sampleHandler(t)}t(this.merger),this.merger.update(e,r),e.close(),r.close();const i=new VideoFrame(this.merger.canvas,{timestamp:e.timestamp,duration:e.duration??void 0}),a=new rt(i);this.sampleHandler(a)}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(t(this.decoder),await Promise.all([this.decoder.flush(),this.alphaDecoder?.flush()]),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.alphaHadKeyframe=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue.length=0,this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1),q()){for(const e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}this.currentPacketIndex=0,this.raslSkipped=!1}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(t(this.decoder),this.decoder.close(),this.alphaDecoder?.close(),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.merger?.close());for(const e of this.sampleQueue)e.close();this.sampleQueue.length=0}}class xt{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"),a=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(a),this.gl.vertexAttribPointer(a,2,this.gl.FLOAT,!1,16,8),e}createTexture(){const e=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),e}update(e,t){e.displayWidth===this.canvas.width&&e.displayHeight===this.canvas.height||(this.canvas.width=e.displayWidth,this.canvas.height=e.displayHeight),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.colorTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),this.gl.activeTexture(this.gl.TEXTURE1),this.gl.bindTexture(this.gl.TEXTURE_2D,this.alphaTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,t),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4)}close(){this.gl.getExtension("WEBGL_lose_context")?.loseContext(),this.gl=null}}class Ct extends It{constructor(e){if(!(e instanceof Rt))throw new TypeError("videoTrack must be an InputVideoTrack.");super(),this._track=e}async _createDecoder(e,r){if(!(await this._track.canDecode()))throw new Error("This video track cannot be decoded by this browser. Make sure to check decodability before using a track.");const i=this._track.codec,a=this._track.rotation,s=await this._track.getDecoderConfig(),n=this._track.timeResolution;return t(i&&s),new Pt(e,r,i,s,a,n)}_createPacketSink(){return new wt(this._track)}async getSample(e){Tt(e);for await(const t of this.mediaSamplesAtTimestamps([e]))return t;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,t={}){if(this._nextCanvasIndex=0,!(e instanceof Rt))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&&nt(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 r=t.rotation??e.rotation,[i,a]=r%180===0?[e.codedWidth,e.codedHeight]:[e.codedHeight,e.codedWidth],s=t.crop;s&&st(s,i,a);let[n,o]=s?[s.width,s.height]:[i,a];const c=n/o;void 0!==t.width&&void 0===t.height?(n=t.width,o=Math.round(n/c)):void 0===t.width&&void 0!==t.height?(o=t.height,n=Math.round(o*c)):void 0!==t.width&&void 0!==t.height&&(n=t.width,o=t.height),this._videoTrack=e,this._alpha=t.alpha??!1,this._width=n,this._height=o,this._rotation=r,this._crop=s,this._fit=t.fit??"fill",this._videoSampleSink=new Ct(e),this._canvasPool=Array.from({length:t.poolSize??0},()=>null)}_videoSampleToWrappedCanvas(e){let r=this._canvasPool[this._nextCanvasIndex],i=!1;r||("undefined"!==typeof document?(r=document.createElement("canvas"),r.width=this._width,r.height=this._height):r=new OffscreenCanvas(this._width,this._height),this._canvasPool.length>0&&(this._canvasPool[this._nextCanvasIndex]=r),i=!0),this._canvasPool.length>0&&(this._nextCanvasIndex=(this._nextCanvasIndex+1)%this._canvasPool.length);const a=r.getContext("2d",{alpha:this._alpha||W()});t(a),a.resetTransform(),i||(!this._alpha&&W()?(a.fillStyle="black",a.fillRect(0,0,this._width,this._height)):a.clearRect(0,0,this._width,this._height)),e.drawWithFit(a,{fit:this._fit,rotation:this._rotation,crop:this._crop});const s={canvas:r,timestamp:e.timestamp,duration:e.duration};return e.close(),s}async getCanvas(e){Tt(e);const t=await this._videoSampleSink.getSample(e);return t&&this._videoSampleToWrappedCanvas(t)}canvases(e=0,t=1/0){return E(this._videoSampleSink.samples(e,t),e=>this._videoSampleToWrappedCanvas(e))}canvasesAtTimestamps(e){return E(this._videoSampleSink.samplesAtTimestamps(e),e=>e&&this._videoSampleToWrappedCanvas(e))}}class Bt extends St{constructor(e,t,r,i){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new U,this.customDecoderQueueSize=0,this.currentTimestamp=null;const a=t=>{(null===this.currentTimestamp||Math.abs(t.timestamp-this.currentTimestamp)>=t.duration)&&(this.currentTimestamp=t.timestamp);const r=this.currentTimestamp;if(this.currentTimestamp+=t.duration,0===t.numberOfFrames)return void t.close();const a=i.sampleRate;t.setTimestamp(Math.round(r*a)/a),e(t)},s=Qe.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 ut))throw new TypeError("The argument passed to onSample must be an AudioSample.");a(e)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{const e=new Error("Decoding error").stack;this.decoder=new AudioDecoder({output:e=>{try{a(new ut(e))}catch(t){this.onError(t)}},error:t=>{t.stack=e,this.onError(t)}}),this.decoder.configure(i)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(t(this.decoder),this.decoder.decodeQueueSize)}decode(e){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--)):(t(this.decoder),this.decoder.decode(e.toEncodedAudioChunk()))}flush(){return this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(t(this.decoder),this.decoder.flush())}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(t(this.decoder),this.decoder.close())}}class Et extends St{constructor(e,r,i){super(e,r),this.decoderConfig=i,this.currentTimestamp=null,t(re.includes(i.codec)),this.codec=i.codec;const{dataType:a,sampleSize:s,littleEndian:n}=me(this.codec);switch(this.inputSampleSize=s,s){case 1:"unsigned"===a?this.readInputValue=(e,t)=>e.getUint8(t)-128:"signed"===a?this.readInputValue=(e,t)=>e.getInt8(t):"ulaw"===a?this.readInputValue=(e,t)=>(e=>{let t=0,r=0,i=~e;128&i&&(i&=-129,t=-1),r=5+((240&i)>>4);const a=(1<<r|(15&i)<<r-4|1<<r-5)-33;return 0===t?a:-a})(e.getUint8(t)):"alaw"===a?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 a=0;return a=4!==r?1<<r|(15&i)<<r-4|1<<r-5:i<<1|1,0===t?a:-a})(e.getUint8(t)):t(!1);break;case 2:"unsigned"===a?this.readInputValue=(e,t)=>e.getUint16(t,n)-32768:"signed"===a?this.readInputValue=(e,t)=>e.getInt16(t,n):t(!1);break;case 3:"unsigned"===a?this.readInputValue=(e,t)=>_(e,t,n)-2**23:"signed"===a?this.readInputValue=(e,t)=>((e,t,r)=>_(e,t,r)<<8>>8)(e,t,n):t(!1);break;case 4:"unsigned"===a?this.readInputValue=(e,t)=>e.getUint32(t,n)-2**31:"signed"===a?this.readInputValue=(e,t)=>e.getInt32(t,n):"float"===a?this.readInputValue=(e,t)=>e.getFloat32(t,n):t(!1);break;case 8:"float"===a?this.readInputValue=(e,t)=>e.getFloat64(t,n):t(!1);break;default:C(s),t(!1)}switch(s){case 1:"ulaw"===a||"alaw"===a?(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+128));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"===a?(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:C(s),t(!1)}}getDecodeQueueSize(){return 0}decode(e){const t=c(e.data),r=e.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize,i=r*this.decoderConfig.numberOfChannels*this.outputSampleSize,a=new ArrayBuffer(i),s=new DataView(a);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 n=r/this.decoderConfig.sampleRate;(null===this.currentTimestamp||Math.abs(e.timestamp-this.currentTimestamp)>=n)&&(this.currentTimestamp=e.timestamp);const o=this.currentTimestamp;this.currentTimestamp+=n;const l=new ut({format:this.outputFormat,data:a,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:r,timestamp:o});this.onSample(l)}async flush(){}close(){}}class Ft extends It{constructor(e){if(!(e instanceof Mt))throw new TypeError("audioTrack must be an InputAudioTrack.");super(),this._track=e}async _createDecoder(e,r){if(!(await this._track.canDecode()))throw new Error("This audio track cannot be decoded by this browser. Make sure to check decodability before using a track.");const i=this._track.codec,a=await this._track.getDecoderConfig();return t(i&&a),re.includes(a.codec)?new Et(e,r,a):new Bt(e,r,i,a)}_createPacketSink(){return new wt(this._track)}async getSample(e){Tt(e);for await(const t of this.mediaSamplesAtTimestamps([e]))return t;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 Dt{constructor(e){if(!(e instanceof Mt))throw new TypeError("audioTrack must be an InputAudioTrack.");this._audioSampleSink=new Ft(e)}_audioSampleToWrappedArrayBuffer(e){const t={buffer:e.toAudioBuffer(),timestamp:e.timestamp,duration:e.duration};return e.close(),t}async getBuffer(e){Tt(e);const t=await this._audioSampleSink.getSample(e);return t&&this._audioSampleToWrappedArrayBuffer(t)}buffers(e=0,t=1/0){return E(this._audioSampleSink.samples(e,t),e=>this._audioSampleToWrappedArrayBuffer(e))}buffersAtTimestamps(e){return E(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 At{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof Rt}isAudioTrack(){return this instanceof Mt}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()}async computePacketStats(e=1/0){const t=new wt(this);let r=1/0,i=-1/0,a=0,s=0;for await(const n of t.packets(void 0,void 0,{metadataOnly:!0})){if(a>=e&&n.timestamp>=i)break;r=Math.min(r,n.timestamp),i=Math.max(i,n.timestamp+n.duration),a++,s+=n.byteLength}return{packetCount:a,averagePacketRate:a?Number((a/(i-r)).toPrecision(16)):0,averageBitrate:a?Number((8*s/(i-r)).toPrecision(16)):0}}}class Rt extends At{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()}async hasHighDynamicRange(){const e=await this._backing.getColorSpace();return"bt2020"===e.primaries||"smpte432"===e.primaries||"pg"===e.transfer||"hlg"===e.transfer||"bt2020-ncl"===e.matrix}canBeTransparent(){return this._backing.canBeTransparent()}getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){const e=await this._backing.getDecoderConfig();return e?.codec??null}async canDecode(){try{const e=await this._backing.getDecoderConfig();if(!e)return!1;const r=this._backing.getCodec();if(t(null!==r),$e.some(t=>t.supports(r,e)))return!0;if("undefined"===typeof VideoDecoder)return!1;return!0===(await VideoDecoder.isConfigSupported(e)).supported}catch(e){return console.error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof Xe))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 r=await this.getDecoderConfig();return t(r),qe(this.codec,r,e.data)}}class Mt extends At{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()}async getCodecParameterString(){const e=await this._backing.getDecoderConfig();return e?.codec??null}async canDecode(){try{const e=await this._backing.getDecoderConfig();if(!e)return!1;const r=this._backing.getCodec();if(t(null!==r),Qe.some(t=>t.supports(r,e)))return!0;if(e.codec.startsWith("pcm-"))return!0;if("undefined"===typeof AudioDecoder)return!1;return!0===(await AudioDecoder.isConfigSupported(e)).supported}catch(e){return console.error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof Xe))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 Nt=e=>{let t=ua(e);const r=ya(e,4);let i=8;1===t&&(t=pa(e),i=16);const a=t-i;return a<0?null:{name:r,totalSize:t,headerSize:i,contentSize:a}},zt=e=>ma(e)/65536,Ot=e=>ma(e)/1073741824,Lt=e=>{let t=0;for(let r=0;r<4;r++){t<<=7;const r=sa(e);if(t|=127&r,0===(128&r))break}return t},Ut=e=>{let t=oa(e);return e.skip(2),t=Math.min(t,e.remainingLength),l.decode(aa(e,t))},Vt=e=>{const t=Nt(e);if(!t||"data"!==t.name)return null;if(e.remainingLength<8)return null;const r=ua(e);e.skip(4);const i=aa(e,t.contentSize-8);switch(r){case 1:return l.decode(i);case 2:return new TextDecoder("utf-16be").decode(i);case 13:return new Z(i,"image/jpeg");case 14:return new Z(i,"image/png");case 27:return new Z(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 qt extends Ke{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}async computeDuration(){const e=await this.getTracks(),t=await Promise.all(e.map(e=>e.computeDuration()));return Math.max(0,...t)}async getTracks(){return await this.readMetadata(),this.tracks.map(e=>e.inputTrack)}async getMimeType(){await this.readMetadata();const e=await 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=>"video"===e.info?.type),hasAudio:this.tracks.some(e=>"audio"===e.info?.type),codecStrings:e.filter(Boolean)})}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,8,16);if(t instanceof Promise&&(t=await t),!t)break;const r=e,i=Nt(t);if(!i)break;if("ftyp"===i.name){const e=ya(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=await 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=await e),t(e);const r=ua(e),i=this.reader.fileSize-r;if(i>=0&&i<=this.reader.fileSize-16){let e=this.reader.requestSliceRange(i,8,16);if(e instanceof Promise&&(e=await e),e){const t=Nt(e);if(t&&"mfra"===t.name){let r=this.reader.requestSlice(e.filePos,t.contentSize);r instanceof Promise&&(r=await r),r&&this.readContiguousBoxes(r)}}}}})())}getSampleTableForTrack(e){if(e.sampleTable)return e.sampleTable;const r={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};e.sampleTable=r,t(this.moovSlice);const a=this.moovSlice.slice(e.sampleTableByteOffset);this.currentTrack=e,this.traverseBox(a),this.currentTrack=null;if("audio"===e.info?.type&&e.info.codec&&re.includes(e.info.codec)&&0===r.sampleCompositionTimeOffsets.length){t("audio"===e.info?.type);const a=me(e.info.codec),s=[],n=[];for(let t=0;t<r.sampleToChunk.length;t++){const o=r.sampleToChunk[t],c=r.sampleToChunk[t+1],l=(c?c.startChunkIndex:r.chunkOffsets.length)-o.startChunkIndex;for(let t=0;t<l;t++){const c=o.startSampleIndex+t*o.samplesPerChunk,l=c+o.samplesPerChunk,d=S(r.sampleTimingEntries,c,e=>e.startIndex),u=r.sampleTimingEntries[d],h=S(r.sampleTimingEntries,l,e=>e.startIndex),m=r.sampleTimingEntries[h],f=u.startDecodeTimestamp+(c-u.startIndex)*u.delta,p=m.startDecodeTimestamp+(l-m.startIndex)*m.delta-f,g=i(s);g&&g.delta===p?g.count++:s.push({startIndex:o.startChunkIndex+t,startDecodeTimestamp:f,count:1,delta:p});const k=o.samplesPerChunk*a.sampleSize*e.info.numberOfChannels;n.push(k)}o.startSampleIndex=o.startChunkIndex,o.samplesPerChunk=1}r.sampleTimingEntries=s,r.sampleSizes=n}if(r.sampleCompositionTimeOffsets.length>0){r.presentationTimestamps=[];for(const e of r.sampleTimingEntries)for(let t=0;t<e.count;t++)r.presentationTimestamps.push({presentationTimestamp:e.startDecodeTimestamp+t*e.delta,sampleIndex:e.startIndex+t});for(const e of r.sampleCompositionTimeOffsets)for(let t=0;t<e.count;t++){const i=e.startIndex+t,a=r.presentationTimestamps[i];a&&(a.presentationTimestamp+=e.offset)}r.presentationTimestamps.sort((e,t)=>e.presentationTimestamp-t.presentationTimestamp),r.presentationTimestampIndexMap=Array(r.presentationTimestamps.length).fill(-1);for(let e=0;e<r.presentationTimestamps.length;e++)r.presentationTimestampIndexMap[r.presentationTimestamps[e].sampleIndex]=e}return r}async readFragment(e){if(this.lastReadFragment?.moofOffset===e)return this.lastReadFragment;let r=this.reader.requestSliceRange(e,8,16);r instanceof Promise&&(r=await r),t(r);const i=Nt(r);t("moof"===i?.name);let a=this.reader.requestSlice(e,i.totalSize);a instanceof Promise&&(a=await a),t(a),this.traverseBox(a);const s=this.lastReadFragment;t(s&&s.moofOffset===e);for(const[,t]of s.trackData){const e=t.track,{fragmentPositionCache:r}=e;if(!t.startTimestampIsFinal){const i=e.fragmentLookupTable.find(e=>e.moofOffset===s.moofOffset);if(i)Xt(t,i.timestamp);else{const e=S(r,s.moofOffset-1,e=>e.moofOffset);if(-1!==e){const i=r[e];Xt(t,i.endTimestamp)}}t.startTimestampIsFinal=!0}const i=S(r,t.startTimestamp,e=>e.startTimestamp);-1!==i&&r[i].moofOffset===s.moofOffset||r.splice(i+1,0,{moofOffset:s.moofOffset,startTimestamp:t.startTimestamp,endTimestamp:t.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=Nt(e);if(!r)break;yield{boxInfo:r,slice:e},e.filePos=t+r.totalSize}}traverseBox(e){var s,n,o,d,u,m,p,k,b,T,y,w,S,I,v,P,x,C,_,B,E,F,A,R,N,z,O,L,U,V,q,H,W;const j=e.filePos,K=Nt(e);if(!K)return!1;const $=e.filePos,Q=j+K.totalSize;switch(K.name){case"mdia":case"minf":case"dinf":case"mfra":case"edts":case"wave":this.readContiguousBoxes(e.slice($,K.contentSize));break;case"mvhd":{const t=sa(e);e.skip(3),1===t?(e.skip(16),this.movieTimescale=ua(e),this.movieDurationInTimescale=pa(e)):(e.skip(8),this.movieTimescale=ua(e),this.movieDurationInTimescale=ua(e))}break;case"trak":{const t={id:-1,demuxer:this,inputTrack:null,disposition:{...te},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,internalCodecId:null,name:null,languageCode:D,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0};if(this.currentTrack=t,this.readContiguousBoxes(e.slice($,K.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 Rt(this.input,new Wt(e)),this.tracks.push(t)}else if("audio"===t.info.type&&-1!==t.info.numberOfChannels){const e=t;t.inputTrack=new Mt(this.input,new jt(e)),this.tracks.push(t)}this.currentTrack=null}break;case"tkhd":{const i=this.currentTrack;if(!i)break;const a=sa(e),s=!!(1&ca(e));if(i.disposition.default=s,0===a)e.skip(8),i.id=ua(e),e.skip(4),i.durationInMovieTimescale=ua(e);else{if(1!==a)throw new Error(`Incorrect track header version ${a}.`);e.skip(16),i.id=ua(e),e.skip(4),i.durationInMovieTimescale=pa(e)}e.skip(16);const n=[zt(e),zt(e),Ot(e),zt(e),zt(e),Ot(e),zt(e),zt(e),Ot(e)],o=r((G=Yt(n),X=90,Math.round(G/X)*X));t(0===o||90===o||180===o||270===o),i.rotation=o}break;case"elst":{const t=this.currentTrack;if(!t)break;const r=sa(e);e.skip(3);let i=!1,a=0;const s=ua(e);for(let n=0;n<s;n++){const s=1===r?pa(e):ua(e),n=1===r?ga(e):ma(e),o=zt(e);if(0!==s){if(i){console.warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit.");break}if(-1!==n){if(1!==o){console.warn("Unsupported edit list entry: media rate must be 1.");break}t.editListPreviousSegmentDurations=a,t.editListOffset=n,i=!0}else a+=s}}}break;case"mdhd":{const t=this.currentTrack;if(!t)break;const r=sa(e);e.skip(3),0===r?(e.skip(8),t.timescale=ua(e),t.durationInMediaTimescale=ua(e)):1===r&&(e.skip(16),t.timescale=ua(e),t.durationInMediaTimescale=pa(e));let i=oa(e);if(i>0){t.languageCode="";for(let e=0;e<3;e++)t.languageCode=String.fromCharCode(96+(31&i))+t.languageCode,i>>=5;M(t.languageCode)||(t.languageCode=D)}}break;case"hdlr":{const t=this.currentTrack;if(!t)break;e.skip(8);const r=ya(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=j,this.readContiguousBoxes(e.slice($,K.contentSize))}break;case"stsd":{const t=this.currentTrack;if(!t)break;if(null===t.info||t.sampleTable)break;const r=sa(e);e.skip(3);const i=ua(e);for(let a=0;a<i;a++){const i=e.filePos,a=Nt(e);if(!a)break;t.internalCodecId=a.name;const s=a.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 '${a.name}').`),e.skip(24),t.info.width=oa(e),t.info.height=oa(e),e.skip(50),this.readContiguousBoxes(e.slice(e.filePos,i+a.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 '${a.name}').`))),e.skip(8);const n=oa(e);e.skip(6);let o=oa(e),c=oa(e);e.skip(4);let l=ua(e)/65536;if(0===r&&n>0)if(1===n)e.skip(4),c=8*ua(e),e.skip(8);else if(2===n){e.skip(4),l=Ta(e),o=ua(e),e.skip(4),c=ua(e);const r=ua(e);if(e.skip(8),"lpcm"===s){const e=c+7>>3,i=Boolean(1&r),a=Boolean(2&r),s=4&r?-1:0;c>0&&c<=64&&(i?32===c&&(t.info.codec=a?"pcm-f32be":"pcm-f32"):s&1<<e-1?1===e?t.info.codec="pcm-s8":2===e?t.info.codec=a?"pcm-s16be":"pcm-s16":3===e?t.info.codec=a?"pcm-s24be":"pcm-s24":4===e&&(t.info.codec=a?"pcm-s32be":"pcm-s32"):1===e&&(t.info.codec="pcm-u8")),null===t.info.codec&&console.warn("Unsupported PCM format.")}}"opus"===t.info.codec&&(l=ue),t.info.numberOfChannels=o,t.info.sampleRate=l,"twos"===s?8===c?t.info.codec="pcm-s8":16===c?t.info.codec="pcm-s16be":(console.warn(`Unsupported sample size ${c} for codec 'twos'.`),t.info.codec=null):"sowt"===s?8===c?t.info.codec="pcm-s8":16===c?t.info.codec="pcm-s16":(console.warn(`Unsupported sample size ${c} for codec 'sowt'.`),t.info.codec=null):"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+a.totalSize-e.filePos))}}}break;case"avcC":{const r=this.currentTrack;if(!r)break;t(r.info),r.info.codecDescription=aa(e,K.contentSize)}break;case"hvcC":{const r=this.currentTrack;if(!r)break;t(r.info),r.info.codecDescription=aa(e,K.contentSize)}break;case"vpcC":{const r=this.currentTrack;if(!r)break;t("video"===r.info?.type),e.skip(4);const i=sa(e),a=sa(e),s=sa(e),n=s>>4,o=s>>1&7,c=1&s,l=sa(e),d=sa(e),u=sa(e);r.info.vp9CodecInfo={profile:i,level:a,bitDepth:n,chromaSubsampling:o,videoFullRangeFlag:c,colourPrimaries:l,transferCharacteristics:d,matrixCoefficients:u}}break;case"av1C":{const r=this.currentTrack;if(!r)break;t("video"===r.info?.type),e.skip(1);const i=sa(e),a=i>>5,s=31&i,n=sa(e),o=n>>7,c=n>>6&1,l=n>>4&1,d=n>>3&1,u=n>>2&1,h=3&n,m=2===a&&c?n>>5&1?12:10:c?10:8;r.info.av1CodecInfo={profile:a,level:s,tier:o,bitDepth:m,monochrome:l,chromaSubsamplingX:d,chromaSubsamplingY:u,chromaSamplePosition:h}}break;case"colr":{const r=this.currentTrack;if(!r)break;t("video"===r.info?.type);if("nclx"!==ya(e,4))break;const i=oa(e),a=oa(e),s=oa(e),n=Boolean(128&sa(e));r.info.colorSpace={primaries:h[i],transfer:f[a],matrix:g[s],fullRange:n}}break;case"esds":{const r=this.currentTrack;if(!r)break;t("audio"===r.info?.type),e.skip(4);t(3===sa(e)),Lt(e),e.skip(2);const i=sa(e),a=0!==(64&i),s=0!==(32&i);if(0!==(128&i)&&e.skip(2),a){const t=sa(e);e.skip(t)}s&&e.skip(2);t(4===sa(e));const n=Lt(e),o=e.filePos,c=sa(e);if(64===c||103===c?(r.info.codec="aac",r.info.aacCodecInfo={isMpeg2:103===c}):105===c||107===c?r.info.codec="mp3":221===c?r.info.codec="vorbis":console.warn(`Unsupported audio codec (objectTypeIndication ${c}) - discarding track.`),e.skip(12),n>e.filePos-o){t(5===sa(e));const i=Lt(e);if(r.info.codecDescription=aa(e,i),"aac"===r.info.codec){const e=de(r.info.codecDescription);null!==e.numberOfChannels&&(r.info.numberOfChannels=e.numberOfChannels),null!==e.sampleRate&&(r.info.sampleRate=e.sampleRate)}}}break;case"enda":{const r=this.currentTrack;if(!r)break;t("audio"===r.info?.type);255&oa(e)&&("pcm-s16be"===r.info.codec?r.info.codec="pcm-s16":"pcm-s24be"===r.info.codec?r.info.codec="pcm-s24":"pcm-s32be"===r.info.codec?r.info.codec="pcm-s32":"pcm-f32be"===r.info.codec?r.info.codec="pcm-f32":"pcm-f64be"===r.info.codec&&(r.info.codec="pcm-f64"))}break;case"pcmC":{const r=this.currentTrack;if(!r)break;t("audio"===r.info?.type),e.skip(4);const i=sa(e),a=Boolean(1&i),s=sa(e);"pcm-s16be"===r.info.codec?a?16===s?r.info.codec="pcm-s16":24===s?r.info.codec="pcm-s24":32===s?r.info.codec="pcm-s32":(console.warn(`Invalid ipcm sample size ${s}.`),r.info.codec=null):16===s?r.info.codec="pcm-s16be":24===s?r.info.codec="pcm-s24be":32===s?r.info.codec="pcm-s32be":(console.warn(`Invalid ipcm sample size ${s}.`),r.info.codec=null):"pcm-f32be"===r.info.codec&&(a?32===s?r.info.codec="pcm-f32":64===s?r.info.codec="pcm-f64":(console.warn(`Invalid fpcm sample size ${s}.`),r.info.codec=null):32===s?r.info.codec="pcm-f32be":64===s?r.info.codec="pcm-f64be":(console.warn(`Invalid fpcm sample size ${s}.`),r.info.codec=null));break}case"dOps":{const r=this.currentTrack;if(!r)break;t("audio"===r.info?.type),e.skip(1);const i=sa(e),a=oa(e),s=ua(e),n=la(e),o=sa(e);let c;c=0!==o?aa(e,2+i):new Uint8Array(0);const l=new Uint8Array(19+c.byteLength),d=new DataView(l.buffer);d.setUint32(0,1332770163,!1),d.setUint32(4,1214603620,!1),d.setUint8(8,1),d.setUint8(9,i),d.setUint16(10,a,!0),d.setUint32(12,s,!0),d.setInt16(16,n,!0),d.setUint8(18,o),l.set(c,19),r.info.codecDescription=l,r.info.numberOfChannels=i}break;case"dfLa":{const r=this.currentTrack;if(!r)break;t("audio"===r.info?.type),e.skip(4);const i=127,a=128,s=e.filePos;for(;e.filePos<Q;){const t=sa(e),s=ca(e);if((t&i)===He.STREAMINFO){e.skip(10);const t=ua(e),i=t>>>12,a=1+(t>>9&7);r.info.sampleRate=i,r.info.numberOfChannels=a,e.skip(20)}else e.skip(s);if(t&a)break}const n=e.filePos;e.filePos=s;const o=aa(e,n-s),c=new Uint8Array(4+o.byteLength);new DataView(c.buffer).setUint32(0,1716281667,!1),c.set(o,4),r.info.codecDescription=c}break;case"stts":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4);const r=ua(e);let i=0,a=0;for(let s=0;s<r;s++){const r=ua(e),s=ua(e);t.sampleTable.sampleTimingEntries.push({startIndex:i,startDecodeTimestamp:a,count:r,delta:s}),i+=r,a+=r*s}}break;case"ctts":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4);const r=ua(e);let i=0;for(let a=0;a<r;a++){const r=ua(e),a=ma(e);t.sampleTable.sampleCompositionTimeOffsets.push({startIndex:i,count:r,offset:a}),i+=r}}break;case"stsz":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4);const r=ua(e),i=ua(e);if(0===r)for(let a=0;a<i;a++){const r=ua(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=sa(e),i=ua(e),s=aa(e,Math.ceil(i*r/8)),n=new a(s);for(let e=0;e<i;e++){const e=n.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=ua(e);for(let i=0;i<r;i++){const r=ua(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=ua(e);for(let a=0;a<r;a++){const r=ua(e)-1,i=ua(e),a=ua(e);t.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:r,samplesPerChunk:i,sampleDescriptionIndex:a})}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=ua(e);for(let i=0;i<r;i++){const r=ua(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=ua(e);for(let i=0;i<r;i++){const r=pa(e);t.sampleTable.chunkOffsets.push(r)}}break;case"mvex":this.isFragmented=!0,this.readContiguousBoxes(e.slice($,K.contentSize));break;case"mehd":{const t=sa(e);e.skip(3);const r=1===t?pa(e):ua(e);this.movieDurationInTimescale=r}break;case"trex":{e.skip(4);const t=ua(e),r=ua(e),i=ua(e),a=ua(e),s=ua(e);this.fragmentTrackDefaults.push({trackId:t,defaultSampleDescriptionIndex:r,defaultSampleDuration:i,defaultSampleSize:a,defaultSampleFlags:s})}break;case"tfra":{const t=sa(e);e.skip(3);const r=ua(e),i=this.tracks.find(e=>e.id===r);if(!i)break;const a=ua(e),s=(12&a)>>2,n=3&a,o=[sa,oa,ca,ua],c=o[(48&a)>>4],l=o[s],d=o[n],u=ua(e);for(let h=0;h<u;h++){const r=1===t?pa(e):ua(e),a=1===t?pa(e):ua(e);c(e),l(e),d(e),i.fragmentLookupTable.push({timestamp:r,moofOffset:a})}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:j,moofSize:K.totalSize,implicitBaseDataOffset:j,trackData:new Map},this.readContiguousBoxes(e.slice($,K.contentSize)),this.lastReadFragment=this.currentFragment,this.currentFragment=null;break;case"traf":if(t(this.currentFragment),this.readContiguousBoxes(e.slice($,K.contentSize)),this.currentTrack){const e=this.currentFragment.trackData.get(this.currentTrack.id);if(e){const{currentFragmentState:r}=this.currentTrack;t(r),null!==r.startTimestamp&&(Xt(e,r.startTimestamp),e.startTimestampIsFinal=!0)}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case"tfhd":{t(this.currentFragment),e.skip(1);const r=ca(e),i=Boolean(1&r),a=Boolean(2&r),s=Boolean(8&r),n=Boolean(16&r),o=Boolean(32&r),c=Boolean(65536&r),l=Boolean(131072&r),d=ua(e),u=this.tracks.find(e=>e.id===d);if(!u)break;const h=this.fragmentTrackDefaults.find(e=>e.trackId===d);this.currentTrack=u,u.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:h?.defaultSampleDescriptionIndex??null,defaultSampleDuration:h?.defaultSampleDuration??null,defaultSampleSize:h?.defaultSampleSize??null,defaultSampleFlags:h?.defaultSampleFlags??null,startTimestamp:null},i?u.currentFragmentState.baseDataOffset=pa(e):l&&(u.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),a&&(u.currentFragmentState.sampleDescriptionIndex=ua(e)),s&&(u.currentFragmentState.defaultSampleDuration=ua(e)),n&&(u.currentFragmentState.defaultSampleSize=ua(e)),o&&(u.currentFragmentState.defaultSampleFlags=ua(e)),c&&(u.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{const r=this.currentTrack;if(!r)break;t(r.currentFragmentState);const i=sa(e);e.skip(3);const a=0===i?ua(e):pa(e);r.currentFragmentState.startTimestamp=a}break;case"trun":{const r=this.currentTrack;if(!r)break;if(t(this.currentFragment),t(r.currentFragmentState),this.currentFragment.trackData.has(r.id)){console.warn("Can't have two trun boxes for the same track in one fragment. Ignoring...");break}const a=sa(e),s=ca(e),n=Boolean(1&s),o=Boolean(4&s),c=Boolean(256&s),l=Boolean(512&s),d=Boolean(1024&s),u=Boolean(2048&s),h=ua(e);let m=r.currentFragmentState.baseDataOffset;n&&(m+=ma(e));let f=null;o&&(f=ua(e));let p=m;if(0===h){this.currentFragment.implicitBaseDataOffset=p;break}let g=0;const k={track:r,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1};this.currentFragment.trackData.set(r.id,k);for(let i=0;i<h;i++){let s,n,o;c?s=ua(e):(t(null!==r.currentFragmentState.defaultSampleDuration),s=r.currentFragmentState.defaultSampleDuration),l?n=ua(e):(t(null!==r.currentFragmentState.defaultSampleSize),n=r.currentFragmentState.defaultSampleSize),d?o=ua(e):(t(null!==r.currentFragmentState.defaultSampleFlags),o=r.currentFragmentState.defaultSampleFlags),0===i&&null!==f&&(o=f);let h=0;u&&(h=0===a?ua(e):ma(e));const m=!(65536&o);k.samples.push({presentationTimestamp:g+h,duration:s,byteOffset:p,byteSize:n,isKeyFrame:m}),p+=n,g+=s}k.presentationTimestamps=k.samples.map((e,t)=>({presentationTimestamp:e.presentationTimestamp,sampleIndex:t})).sort((e,t)=>e.presentationTimestamp-t.presentationTimestamp);for(let e=0;e<k.presentationTimestamps.length;e++){const t=k.presentationTimestamps[e],r=k.samples[t.sampleIndex];if(null===k.firstKeyFrameTimestamp&&r.isKeyFrame&&(k.firstKeyFrameTimestamp=r.presentationTimestamp),e<k.presentationTimestamps.length-1){const i=k.presentationTimestamps[e+1];r.duration=i.presentationTimestamp-t.presentationTimestamp}}const b=k.samples[k.presentationTimestamps[0].sampleIndex],T=k.samples[i(k.presentationTimestamps).sampleIndex];k.startTimestamp=b.presentationTimestamp,k.endTimestamp=T.presentationTimestamp+T.duration,this.currentFragment.implicitBaseDataOffset=p}break;case"udta":{const t=this.iterateContiguousBoxes(e.slice($,K.contentSize));for(const{boxInfo:e,slice:r}of t){if("meta"!==e.name&&!this.currentTrack){const t=r.filePos;(s=this.metadataTags).raw??(s.raw={}),"\xa9"===e.name[0]?(n=this.metadataTags.raw)[o=e.name]??(n[o]=Ut(r)):(d=this.metadataTags.raw)[u=e.name]??(d[u]=aa(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=l.decode(aa(r,e.contentSize)):(m=this.metadataTags).title??(m.title=Ut(r));break;case"\xa9des":this.currentTrack||((p=this.metadataTags).description??(p.description=Ut(r)));break;case"\xa9ART":this.currentTrack||((k=this.metadataTags).artist??(k.artist=Ut(r)));break;case"\xa9alb":this.currentTrack||((b=this.metadataTags).album??(b.album=Ut(r)));break;case"albr":this.currentTrack||((T=this.metadataTags).albumArtist??(T.albumArtist=Ut(r)));break;case"\xa9gen":this.currentTrack||((y=this.metadataTags).genre??(y.genre=Ut(r)));break;case"\xa9day":if(!this.currentTrack){const e=new Date(Ut(r));Number.isNaN(e.getTime())||((w=this.metadataTags).date??(w.date=e))}break;case"\xa9cmt":this.currentTrack||((S=this.metadataTags).comment??(S.comment=Ut(r)));break;case"\xa9lyr":this.currentTrack||((I=this.metadataTags).lyrics??(I.lyrics=Ut(r)))}}}break;case"meta":{if(this.currentTrack)break;const t=0!==ua(e);this.currentMetadataKeys=new Map,t?this.readContiguousBoxes(e.slice($,K.contentSize)):this.readContiguousBoxes(e.slice($+4,K.contentSize-4)),this.currentMetadataKeys=null}break;case"keys":{if(!this.currentMetadataKeys)break;e.skip(4);const t=ua(e);for(let r=0;r<t;r++){const t=ua(e);e.skip(4);const i=l.decode(aa(e,t-8));this.currentMetadataKeys.set(r+1,i)}}break;case"ilst":{if(!this.currentMetadataKeys)break;const t=this.iterateContiguousBoxes(e.slice($,K.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 a=Vt(r);switch((v=this.metadataTags).raw??(v.raw={}),(P=this.metadataTags.raw)[t]??(P[t]=a),t){case"\xa9nam":case"titl":case"com.apple.quicktime.title":case"title":"string"===typeof a&&((x=this.metadataTags).title??(x.title=a));break;case"\xa9des":case"desc":case"dscp":case"com.apple.quicktime.description":case"description":"string"===typeof a&&((C=this.metadataTags).description??(C.description=a));break;case"\xa9ART":case"com.apple.quicktime.artist":case"artist":"string"===typeof a&&((_=this.metadataTags).artist??(_.artist=a));break;case"\xa9alb":case"albm":case"com.apple.quicktime.album":case"album":"string"===typeof a&&((B=this.metadataTags).album??(B.album=a));break;case"aART":case"album_artist":"string"===typeof a&&((E=this.metadataTags).albumArtist??(E.albumArtist=a));break;case"\xa9cmt":case"com.apple.quicktime.comment":case"comment":"string"===typeof a&&((F=this.metadataTags).comment??(F.comment=a));break;case"\xa9gen":case"gnre":case"com.apple.quicktime.genre":case"genre":"string"===typeof a&&((A=this.metadataTags).genre??(A.genre=a));break;case"\xa9lyr":case"lyrics":"string"===typeof a&&((R=this.metadataTags).lyrics??(R.lyrics=a));break;case"\xa9day":case"rldt":case"com.apple.quicktime.creationdate":case"date":if("string"===typeof a){const e=new Date(a);Number.isNaN(e.getTime())||((N=this.metadataTags).date??(N.date=e))}break;case"covr":case"com.apple.quicktime.artwork":a instanceof Z?((z=this.metadataTags).images??(z.images=[]),this.metadataTags.images.push({data:a.data,kind:"coverFront",mimeType:a.mimeType})):a instanceof Uint8Array&&((O=this.metadataTags).images??(O.images=[]),this.metadataTags.images.push({data:a,kind:"coverFront",mimeType:"image/*"}));break;case"track":if("string"===typeof a){const e=a.split("/"),t=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&((L=this.metadataTags).trackNumber??(L.trackNumber=t)),r&&Number.isInteger(r)&&r>0&&((U=this.metadataTags).tracksTotal??(U.tracksTotal=r))}break;case"trkn":if(a instanceof Uint8Array&&a.length>=6){const e=c(a),t=e.getUint16(2,!1),r=e.getUint16(4,!1);t>0&&((V=this.metadataTags).trackNumber??(V.trackNumber=t)),r>0&&((q=this.metadataTags).tracksTotal??(q.tracksTotal=r))}break;case"disc":case"disk":if(a instanceof Uint8Array&&a.length>=6){const e=c(a),t=e.getUint16(2,!1),r=e.getUint16(4,!1);t>0&&((H=this.metadataTags).discNumber??(H.discNumber=t)),r>0&&((W=this.metadataTags).discsTotal??(W.discsTotal=r))}}}}}var G,X;return e.filePos=Q,!0}}class Ht{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}async computeDuration(){const e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}async getFirstTimestamp(){const e=await this.getFirstPacket({metadataOnly:!0});return e?.timestamp??0}async getFirstPacket(e){const t=await this.fetchPacketForSampleIndex(0,e);return t||!this.internalTrack.demuxer.isFragmented?t:this.performFragmentedLookup(null,e=>e.trackData.get(this.internalTrack.id)?{sampleIndex:0,correctSampleFound:!0}:{sampleIndex:-1,correctSampleFound:!1},-1/0,1/0,e)}mapTimestampIntoTimescale(e){return A(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,t){const r=this.mapTimestampIntoTimescale(e),i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=Kt(i,r),s=await this.fetchPacketForSampleIndex(a,t);return Jt(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=S(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}async getNextPacket(e,t){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)}async getKeyPacket(e,t){const r=this.mapTimestampIntoTimescale(e),i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=$t(i,r),s=await this.fetchPacketForSampleIndex(a,t);return Jt(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=x(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}async getNextKeyPacket(e,r){const i=this.packetToSampleIndex.get(e);if(void 0!==i){const e=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),t=Gt(e,i);return this.fetchPacketForSampleIndex(t,r)}const a=this.packetToFragmentLocation.get(e);if(void 0===a)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(a.fragment,e=>{if(e===a.fragment){const t=e.trackData.get(this.internalTrack.id).samples.findIndex((e,t)=>e.isKeyFrame&&t>a.sampleIndex);if(-1!==t)return{sampleIndex:t,correctSampleFound:!0}}else{const r=e.trackData.get(this.internalTrack.id);if(r&&null!==r.firstKeyFrameTimestamp){const e=r.samples.findIndex(e=>e.isKeyFrame);return t(-1!==e),{sampleIndex:e,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,r)}async fetchPacketForSampleIndex(e,r){if(-1===e)return null;const i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=Qt(i,e);if(!a)return null;let s;if(r.metadataOnly)s=Ge;else{let e=this.internalTrack.demuxer.reader.requestSlice(a.sampleOffset,a.sampleSize);e instanceof Promise&&(e=await e),t(e),s=aa(e,a.sampleSize)}const n=(a.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,o=a.duration/this.internalTrack.timescale,c=new Xe(s,a.isKeyFrame?"key":"delta",n,o,e,a.sampleSize);return this.packetToSampleIndex.set(c,e),c}async fetchPacketInFragment(e,r,i){if(-1===r)return null;const a=e.trackData.get(this.internalTrack.id).samples[r];let s;if(t(a),i.metadataOnly)s=Ge;else{let e=this.internalTrack.demuxer.reader.requestSlice(a.byteOffset,a.byteSize);e instanceof Promise&&(e=await e),t(e),s=aa(e,a.byteSize)}const n=(a.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,o=a.duration/this.internalTrack.timescale,c=new Xe(s,a.isKeyFrame?"key":"delta",n,o,e.moofOffset+r,a.byteSize);return this.packetToFragmentLocation.set(c,{fragment:e,sampleIndex:r}),c}async performFragmentedLookup(e,r,i,a,s){const n=this.internalTrack.demuxer;let o=null,c=null,l=-1;if(e){const{sampleIndex:t,correctSampleFound:i}=r(e);if(i)return this.fetchPacketInFragment(e,t,s);-1!==t&&(c=e,l=t)}const d=S(this.internalTrack.fragmentLookupTable,i,e=>e.timestamp),u=-1!==d?this.internalTrack.fragmentLookupTable[d]:null,h=S(this.internalTrack.fragmentPositionCache,i,e=>e.startTimestamp),m=-1!==h?this.internalTrack.fragmentPositionCache[h]:null,f=Math.max(u?.moofOffset??0,m?.moofOffset??0)||null;let p;for(e?null===f||e.moofOffset>=f?(p=e.moofOffset+e.moofSize,o=e):p=f:p=f??0;;){if(o){const e=o.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>a)break}let e=n.reader.requestSliceRange(p,8,16);if(e instanceof Promise&&(e=await e),!e)break;const t=p,i=Nt(e);if(!i)break;if("moof"===i.name){o=await n.readFragment(t);const{sampleIndex:e,correctSampleFound:i}=r(o);if(i)return this.fetchPacketInFragment(o,e,s);-1!==e&&(c=o,l=e)}p=t+i.totalSize}if(u&&(!c||c.moofOffset<u.moofOffset)){const e=this.internalTrack.fragmentLookupTable[d-1];t(!e||e.timestamp<u.timestamp);const i=e?.timestamp??-1/0;return this.performFragmentedLookup(null,r,i,a,s)}return c?this.fetchPacketInFragment(c,l,s):null}}class Wt extends Ht{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}async getColorSpace(){return{primaries:this.internalTrack.info.colorSpace?.primaries,transfer:this.internalTrack.info.colorSpace?.transfer,matrix:this.internalTrack.info.colorSpace?.matrix,fullRange:this.internalTrack.info.colorSpace?.fullRange}}async canBeTransparent(){return!1}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??(this.decoderConfigPromise=(async()=>{if("vp9"!==this.internalTrack.info.codec||this.internalTrack.info.vp9CodecInfo){if("av1"===this.internalTrack.info.codec&&!this.internalTrack.info.av1CodecInfo){const e=await this.getFirstPacket({});this.internalTrack.info.av1CodecInfo=e&&Le(e.data)}}else{const e=await this.getFirstPacket({});this.internalTrack.info.vp9CodecInfo=e&&ze(e.data)}return{codec:ne(this.internalTrack.info),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0}})()):null}}class jt extends Ht{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}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfig??(this.decoderConfig={codec:oe(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}):null}}const Kt=(e,t)=>{if(e.presentationTimestamps){const r=S(e.presentationTimestamps,t,e=>e.presentationTimestamp);return-1===r?-1:e.presentationTimestamps[r].sampleIndex}{const r=S(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)}},$t=(e,t)=>{if(!e.keySampleIndices)return Kt(e,t);if(e.presentationTimestamps){const r=S(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!==w(e.keySampleIndices,r,e=>e))return r}return-1}{const r=Kt(e,t),i=S(e.keySampleIndices,r,e=>e);return e.keySampleIndices[i]??-1}},Qt=(e,r)=>{const i=S(e.sampleTimingEntries,r,e=>e.startIndex),a=e.sampleTimingEntries[i];if(!a||a.startIndex+a.count<=r)return null;let s=a.startDecodeTimestamp+(r-a.startIndex)*a.delta;const n=S(e.sampleCompositionTimeOffsets,r,e=>e.startIndex),o=e.sampleCompositionTimeOffsets[n];o&&r-o.startIndex<o.count&&(s+=o.offset);const c=e.sampleSizes[Math.min(r,e.sampleSizes.length-1)],l=S(e.sampleToChunk,r,e=>e.startSampleIndex),d=e.sampleToChunk[l];t(d);const u=d.startChunkIndex+Math.floor((r-d.startSampleIndex)/d.samplesPerChunk),h=e.chunkOffsets[u],m=d.startSampleIndex+(u-d.startChunkIndex)*d.samplesPerChunk;let f=0,p=h;if(1===e.sampleSizes.length)p+=c*(r-m),f+=c*d.samplesPerChunk;else for(let t=m;t<m+d.samplesPerChunk;t++){const i=e.sampleSizes[t];t<r&&(p+=i),f+=i}let g=a.delta;if(e.presentationTimestamps){const i=e.presentationTimestampIndexMap[r];if(t(void 0!==i),i<e.presentationTimestamps.length-1){g=e.presentationTimestamps[i+1].presentationTimestamp-s}}return{presentationTimestamp:s,duration:g,sampleOffset:p,sampleSize:c,chunkOffset:h,chunkSize:f,isKeyFrame:!e.keySampleIndices||-1!==w(e.keySampleIndices,r,e=>e)}},Gt=(e,t)=>{if(!e.keySampleIndices)return t+1;const r=S(e.keySampleIndices,t,e=>e);return e.keySampleIndices[r+1]??-1},Xt=(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},Yt=e=>{const[t,,,r]=e,i=Math.hypot(t,r),a=t/i,s=r/i,n=-Math.atan2(s,a)*(180/Math.PI);return Number.isFinite(n)?n:0},Jt=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 Zt,er;(er=Zt||(Zt={}))[er.EBML=440786851]="EBML",er[er.EBMLVersion=17030]="EBMLVersion",er[er.EBMLReadVersion=17143]="EBMLReadVersion",er[er.EBMLMaxIDLength=17138]="EBMLMaxIDLength",er[er.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",er[er.DocType=17026]="DocType",er[er.DocTypeVersion=17031]="DocTypeVersion",er[er.DocTypeReadVersion=17029]="DocTypeReadVersion",er[er.Void=236]="Void",er[er.Segment=408125543]="Segment",er[er.SeekHead=290298740]="SeekHead",er[er.Seek=19899]="Seek",er[er.SeekID=21419]="SeekID",er[er.SeekPosition=21420]="SeekPosition",er[er.Duration=17545]="Duration",er[er.Info=357149030]="Info",er[er.TimestampScale=2807729]="TimestampScale",er[er.MuxingApp=19840]="MuxingApp",er[er.WritingApp=22337]="WritingApp",er[er.Tracks=374648427]="Tracks",er[er.TrackEntry=174]="TrackEntry",er[er.TrackNumber=215]="TrackNumber",er[er.TrackUID=29637]="TrackUID",er[er.TrackType=131]="TrackType",er[er.FlagEnabled=185]="FlagEnabled",er[er.FlagDefault=136]="FlagDefault",er[er.FlagForced=21930]="FlagForced",er[er.FlagOriginal=21934]="FlagOriginal",er[er.FlagHearingImpaired=21931]="FlagHearingImpaired",er[er.FlagVisualImpaired=21932]="FlagVisualImpaired",er[er.FlagCommentary=21935]="FlagCommentary",er[er.FlagLacing=156]="FlagLacing",er[er.Name=21358]="Name",er[er.Language=2274716]="Language",er[er.LanguageBCP47=2274717]="LanguageBCP47",er[er.CodecID=134]="CodecID",er[er.CodecPrivate=25506]="CodecPrivate",er[er.CodecDelay=22186]="CodecDelay",er[er.SeekPreRoll=22203]="SeekPreRoll",er[er.DefaultDuration=2352003]="DefaultDuration",er[er.Video=224]="Video",er[er.PixelWidth=176]="PixelWidth",er[er.PixelHeight=186]="PixelHeight",er[er.AlphaMode=21440]="AlphaMode",er[er.Audio=225]="Audio",er[er.SamplingFrequency=181]="SamplingFrequency",er[er.Channels=159]="Channels",er[er.BitDepth=25188]="BitDepth",er[er.SimpleBlock=163]="SimpleBlock",er[er.BlockGroup=160]="BlockGroup",er[er.Block=161]="Block",er[er.BlockAdditions=30113]="BlockAdditions",er[er.BlockMore=166]="BlockMore",er[er.BlockAdditional=165]="BlockAdditional",er[er.BlockAddID=238]="BlockAddID",er[er.BlockDuration=155]="BlockDuration",er[er.ReferenceBlock=251]="ReferenceBlock",er[er.Cluster=524531317]="Cluster",er[er.Timestamp=231]="Timestamp",er[er.Cues=475249515]="Cues",er[er.CuePoint=187]="CuePoint",er[er.CueTime=179]="CueTime",er[er.CueTrackPositions=183]="CueTrackPositions",er[er.CueTrack=247]="CueTrack",er[er.CueClusterPosition=241]="CueClusterPosition",er[er.Colour=21936]="Colour",er[er.MatrixCoefficients=21937]="MatrixCoefficients",er[er.TransferCharacteristics=21946]="TransferCharacteristics",er[er.Primaries=21947]="Primaries",er[er.Range=21945]="Range",er[er.Projection=30320]="Projection",er[er.ProjectionType=30321]="ProjectionType",er[er.ProjectionPoseRoll=30325]="ProjectionPoseRoll",er[er.Attachments=423732329]="Attachments",er[er.AttachedFile=24999]="AttachedFile",er[er.FileDescription=18046]="FileDescription",er[er.FileName=18030]="FileName",er[er.FileMediaType=18016]="FileMediaType",er[er.FileData=18012]="FileData",er[er.FileUID=18094]="FileUID",er[er.Chapters=272869232]="Chapters",er[er.Tags=307544935]="Tags",er[er.Tag=29555]="Tag",er[er.Targets=25536]="Targets",er[er.TargetTypeValue=26826]="TargetTypeValue",er[er.TargetType=25546]="TargetType",er[er.TagTrackUID=25541]="TagTrackUID",er[er.TagEditionUID=25545]="TagEditionUID",er[er.TagChapterUID=25540]="TagChapterUID",er[er.TagAttachmentUID=25542]="TagAttachmentUID",er[er.SimpleTag=26568]="SimpleTag",er[er.TagName=17827]="TagName",er[er.TagLanguage=17530]="TagLanguage",er[er.TagString=17543]="TagString",er[er.TagBinary=17541]="TagBinary",er[er.ContentEncodings=28032]="ContentEncodings",er[er.ContentEncoding=25152]="ContentEncoding",er[er.ContentEncodingOrder=20529]="ContentEncodingOrder",er[er.ContentEncodingScope=20530]="ContentEncodingScope",er[er.ContentCompression=20532]="ContentCompression",er[er.ContentCompAlgo=16980]="ContentCompAlgo",er[er.ContentCompSettings=16981]="ContentCompSettings",er[er.ContentEncryption=20533]="ContentEncryption";const tr=[Zt.EBML,Zt.Segment],rr=[Zt.SeekHead,Zt.Info,Zt.Cluster,Zt.Tracks,Zt.Cues,Zt.Attachments,Zt.Chapters,Zt.Tags],ir=[...tr,...rr],ar=16,sr=e=>{if(e.remainingLength<1)return null;const t=sa(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},nr=e=>{if(e.remainingLength<1)return null;const t=sa(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 a=t&i-1;for(let s=1;s<r;s++)a*=256,a+=sa(e);return a},or=(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+=sa(e);return r},cr=e=>{const t=sr(e);if(null===t)return null;if(e.remainingLength<t)return null;return or(e,t)},lr=e=>{if(e.remainingLength<1)return null;if(255===sa(e))return;e.skip(-1);const t=nr(e);return null===t?null:72057594037927940!==t?t:void 0},dr=e=>{t(e.remainingLength>=2);const r=cr(e);if(null===r)return null;const i=lr(e);return null===i?null:{id:r,size:i}},ur=(e,t)=>{const r=aa(e,t);let i=0;for(;i<t&&0!==r[i];)i+=1;return String.fromCharCode(...r.subarray(0,i))},hr=(e,t)=>{const r=aa(e,t);let i=0;for(;i<t&&0!==r[i];)i+=1;return l.decode(r.subarray(0,i))},mr=(e,t)=>{if(0===t)return 0;if(4!==t&&8!==t)throw new Error("Bad float size "+t);return 4===t?ba(e):Ta(e)},fr=async(e,t,r,i)=>{const a=new Set(r);let s=t;for(;null===i||s<i;){let t=e.requestSliceRange(s,2,ar);if(t instanceof Promise&&(t=await t),!t)break;const r=dr(t);if(!r)break;if(a.has(r.id))return{pos:s,found:!0};xr(r.size),s=t.filePos+r.size}return{pos:null!==i&&i>s?i:s,found:!1}},pr=async(e,t,r,i)=>{const a=new Set(r);let s=t;for(;s<i;){let t=e.requestSliceRange(s,0,Math.min(65536,i-s));if(t instanceof Promise&&(t=await t),!t)break;if(t.length<8)break;for(let e=0;e<t.length-8;e++){t.filePos=s;const e=cr(t);if(null!==e&&a.has(e))return s;s++}}return null},gr="V_MPEG4/ISO/AVC",kr="V_MPEGH/ISO/HEVC",br="V_VP8",Tr="V_VP9",yr="V_AV1",wr="A_AAC",Sr="A_MPEG/L3",Ir="A_OPUS",vr="A_VORBIS",Pr="A_FLAC";function xr(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 Cr,_r,Br,Er,Fr,Dr;(_r=Cr||(Cr={}))[_r.None=0]="None",_r[_r.Xiph=1]="Xiph",_r[_r.FixedSize=2]="FixedSize",_r[_r.Ebml=3]="Ebml",(Er=Br||(Br={}))[Er.Block=1]="Block",Er[Er.Private=2]="Private",Er[Er.Next=4]="Next",(Dr=Fr||(Fr={}))[Dr.Zlib=0]="Zlib",Dr[Dr.Bzlib=1]="Bzlib",Dr[Dr.lzo1x=2]="lzo1x",Dr[Dr.HeaderStripping=3]="HeaderStripping";const Ar=[{id:Zt.SeekHead,flag:"seekHeadSeen"},{id:Zt.Info,flag:"infoSeen"},{id:Zt.Tracks,flag:"tracksSeen"},{id:Zt.Cues,flag:"cuesSeen"}],Rr=10485760;class Mr extends Ke{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}async computeDuration(){const e=await this.getTracks(),t=await Promise.all(e.map(e=>e.computeDuration()));return Math.max(0,...t)}async getTracks(){return await this.readMetadata(),this.segments.flatMap(e=>e.tracks.map(e=>e.inputTrack))}async getMimeType(){await this.readMetadata();const e=await this.getTracks(),t=await 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=>"video"===e.info?.type)),hasAudio:this.segments.some(e=>e.tracks.some(e=>"audio"===e.info?.type)),codecStrings:t.filter(Boolean)})}async getMetadataTags(){await this.readMetadata();for(const t of this.segments)t.metadataTagsCollected||(null!==this.reader.fileSize&&await this.loadSegmentMetadata(t),t.metadataTagsCollected=!0);let e={};for(const t of this.segments)e={...e,...t.metadataTags};return e}readMetadata(){return this.readMetadataPromise??(this.readMetadataPromise=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,2,ar);if(t instanceof Promise&&(t=await t),!t)break;const r=dr(t);if(!r)break;const a=r.id;let s=r.size;const n=t.filePos;if(a===Zt.EBML){xr(s);let e=this.reader.requestSlice(n,s);if(e instanceof Promise&&(e=await e),!e)break;this.readContiguousElements(e)}else if(a===Zt.Segment){if(await this.readSegment(n,s),void 0===s)break;if(null===this.reader.fileSize)break}else if(a===Zt.Cluster){if(null===this.reader.fileSize)break;if(void 0===s){s=(await fr(this.reader,n,ir,this.reader.fileSize)).pos-n}const e=i(this.segments);e&&(e.elementEndPos=n+s)}xr(s),e=n+s}})())}async readSegment(e,t){this.currentSegment={seekHeadSeen:!1,infoSeen:!1,tracksSeen:!1,cuesSeen:!1,tagsSeen:!1,attachmentsSeen:!1,timestampScale:-1,timestampFactor:-1,duration:-1,seekEntries:[],tracks:[],cuePoints:[],dataStartPos:e,elementEndPos:void 0===t?null:e+t,clusterSeekStartPos:e,lastReadCluster:null,metadataTags:{},metadataTagsCollected:!1},this.segments.push(this.currentSegment);let r=e;for(;null===this.currentSegment.elementEndPos||r<this.currentSegment.elementEndPos;){let e=this.reader.requestSliceRange(r,2,ar);if(e instanceof Promise&&(e=await e),!e)break;const t=r,i=dr(e);if(!i||!rr.includes(i.id)&&i.id!==Zt.Void){const e=await pr(this.reader,t,rr,Math.min(this.currentSegment.elementEndPos??1/0,t+Rr));if(e){r=e;continue}break}const{id:a,size:s}=i,n=e.filePos,o=Ar.findIndex(e=>e.id===a);if(-1!==o){const e=Ar[o].flag;this.currentSegment[e]=!0,xr(s);let t=this.reader.requestSlice(n,s);t instanceof Promise&&(t=await t),t&&this.readContiguousElements(t)}else if(a===Zt.Tags||a===Zt.Attachments){a===Zt.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,xr(s);let e=this.reader.requestSlice(n,s);e instanceof Promise&&(e=await e),e&&this.readContiguousElements(e)}else if(a===Zt.Cluster){this.currentSegment.clusterSeekStartPos=t;break}if(void 0===s)break;r=n+s}if(this.currentSegment.seekEntries.sort((e,t)=>e.segmentPosition-t.segmentPosition),null!==this.reader.fileSize)for(const n of this.currentSegment.seekEntries){const t=Ar.find(e=>e.id===n.id);if(!t)continue;if(this.currentSegment[t.flag])continue;let r=this.reader.requestSliceRange(e+n.segmentPosition,2,ar);if(r instanceof Promise&&(r=await r),!r)continue;const i=dr(r);if(!i)continue;const{id:a,size:s}=i;if(a!==t.id)continue;xr(s),this.currentSegment[t.flag]=!0;let o=this.reader.requestSlice(r.filePos,s);o instanceof Promise&&(o=await o),o&&this.readContiguousElements(o)}-1===this.currentSegment.timestampScale&&(this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1e3);for(const n of this.currentSegment.tracks)null!==n.defaultDurationNs&&(n.defaultDuration=this.currentSegment.timestampFactor*n.defaultDurationNs/1e9);this.currentSegment.tracks.sort((e,t)=>Number(t.disposition.default)-Number(e.disposition.default));const i=new Map(this.currentSegment.tracks.map(e=>[e.id,e]));for(const n of this.currentSegment.cuePoints){const e=i.get(n.trackId);e&&e.cuePoints.push(n)}for(const n of this.currentSegment.tracks){n.cuePoints.sort((e,t)=>e.time-t.time);for(let e=0;e<n.cuePoints.length-1;e++){const t=n.cuePoints[e],r=n.cuePoints[e+1];t.time===r.time&&(n.cuePoints.splice(e+1,1),e--)}}let a=null,s=-1/0;for(const n of this.currentSegment.tracks)n.cuePoints.length>s&&(s=n.cuePoints.length,a=n);for(const n of this.currentSegment.tracks)0===n.cuePoints.length&&(n.cuePoints=a.cuePoints);this.currentSegment=null}async readCluster(e,r){if(r.lastReadCluster?.elementStartPos===e)return r.lastReadCluster;let a=this.reader.requestSliceRange(e,2,ar);a instanceof Promise&&(a=await a),t(a);const s=e,n=dr(a);t(n);t(n.id===Zt.Cluster);let o=n.size;const c=a.filePos;if(void 0===o){o=(await fr(this.reader,c,ir,r.elementEndPos)).pos-c}let l=this.reader.requestSlice(c,o);l instanceof Promise&&(l=await l);const d={segment:r,elementStartPos:s,elementEndPos:c+o,dataStartPos:c,timestamp:-1,trackData:new Map};if(this.currentCluster=d,l){const e=this.readContiguousElements(l,ir);d.elementEndPos=e}for(const[,u]of d.trackData){const e=u.track;t(u.blocks.length>0);let r=!1;for(let t=0;t<u.blocks.length;t++){const e=u.blocks[t];e.timestamp+=d.timestamp,r||(r=e.lacing!==Cr.None)}u.presentationTimestamps=u.blocks.map((e,t)=>({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp);for(let t=0;t<u.presentationTimestamps.length;t++){const r=u.presentationTimestamps[t],i=u.blocks[r.blockIndex];if(null===u.firstKeyFrameTimestamp&&i.isKeyFrame&&(u.firstKeyFrameTimestamp=i.timestamp),t<u.presentationTimestamps.length-1){const e=u.presentationTimestamps[t+1];i.duration=e.timestamp-i.timestamp}else 0===i.duration&&null!=e.defaultDuration&&i.lacing===Cr.None&&(i.duration=e.defaultDuration)}r&&(this.expandLacedBlocks(u.blocks,e),u.presentationTimestamps=u.blocks.map((e,t)=>({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp));const a=u.blocks[u.presentationTimestamps[0].blockIndex],n=u.blocks[i(u.presentationTimestamps).blockIndex];u.startTimestamp=a.timestamp,u.endTimestamp=n.timestamp+n.duration;const o=S(e.clusterPositionCache,u.startTimestamp,e=>e.startTimestamp);-1!==o&&e.clusterPositionCache[o].elementStartPos===s||e.clusterPositionCache.splice(o+1,0,{elementStartPos:d.elementStartPos,startTimestamp:u.startTimestamp})}return r.lastReadCluster=d,d}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,r){for(let i=0;i<e.length;i++){const a=e[i];if(a.lacing===Cr.None)continue;a.decoded||(a.data=this.decodeBlockData(r,a.data),a.decoded=!0);const s=ra.tempFromBytes(a.data),n=[],o=sa(s)+1;switch(a.lacing){case Cr.Xiph:{let e=0;for(let t=0;t<o-1;t++){let t=0;for(;s.bufferPos<s.length;){const r=sa(s);if(t+=r,r<255){n.push(t),e+=t;break}}}n.push(s.length-(s.bufferPos+e))}break;case Cr.FixedSize:{const e=s.length-1,t=Math.floor(e/o);for(let r=0;r<o;r++)n.push(t)}break;case Cr.Ebml:{const e=nr(s);t(null!==e);let r=e;n.push(r);let i=r;for(let a=1;a<o-1;a++){const e=s.bufferPos,a=nr(s);t(null!==a);r+=a-((1<<7*(s.bufferPos-e)-1)-1),n.push(r),i+=r}n.push(s.length-(s.bufferPos+i))}break;default:t(!1)}t(n.length===o),e.splice(i,1);const c=a.duration||o*(r.defaultDuration??0);for(let t=0;t<o;t++){const r=n[t],l=aa(s,r),d=a.timestamp+c*t/o,u=c/o;e.splice(i+t,0,{timestamp:d,duration:u,isKeyFrame:a.isKeyFrame,data:l,lacing:Cr.None,decoded:!0,mainAdditional:a.mainAdditional})}i+=o,i--}}async loadSegmentMetadata(e){for(const r of e.seekEntries){if(r.id!==Zt.Tags||e.tagsSeen){if(r.id!==Zt.Attachments||e.attachmentsSeen)continue}else;let i=this.reader.requestSliceRange(e.dataStartPos+r.segmentPosition,2,ar);if(i instanceof Promise&&(i=await i),!i)continue;const a=dr(i);if(!a||a.id!==r.id)continue;const{size:s}=a;xr(s),t(!this.currentSegment),this.currentSegment=e;let n=this.reader.requestSlice(i.filePos,s);n instanceof Promise&&(n=await n),n&&this.readContiguousElements(n),this.currentSegment=null,r.id===Zt.Tags?e.tagsSeen=!0:r.id===Zt.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,i){const a=dr(e);if(!a)return!1;if(i&&i.includes(a.id))return!1;const{id:s,size:n}=a,o=e.filePos;switch(xr(n),s){case Zt.DocType:this.isWebM="webm"===ur(e,n);break;case Zt.Seek:{if(!this.currentSegment)break;const t={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(t),this.readContiguousElements(e.slice(o,n)),-1!==t.id&&-1!==t.segmentPosition||this.currentSegment.seekEntries.pop()}break;case Zt.SeekID:{const t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.id=or(e,n)}break;case Zt.SeekPosition:{const t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.segmentPosition=or(e,n)}break;case Zt.TimestampScale:if(!this.currentSegment)break;this.currentSegment.timestampScale=or(e,n),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale;break;case Zt.Duration:if(!this.currentSegment)break;this.currentSegment.duration=mr(e,n);break;case Zt.TrackEntry:if(!this.currentSegment)break;if(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...te},inputTrack:null,codecId:null,codecPrivate:null,defaultDuration:null,defaultDurationNs:null,name:null,languageCode:D,decodingInstructions:[],info:null},this.readContiguousElements(e.slice(o,n)),!this.currentTrack)break;if(this.currentTrack.decodingInstructions.some(e=>"decompress"!==e.data?.type||e.scope!==Br.Block||e.data.algorithm!==Fr.HeaderStripping)&&(console.warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`),this.currentTrack=null),this.currentTrack&&-1!==this.currentTrack.id&&this.currentTrack.codecId&&this.currentTrack.info){const e=this.currentTrack.codecId.indexOf("/"),t=-1===e?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,e);if("video"===this.currentTrack.info.type&&-1!==this.currentTrack.info.width&&-1!==this.currentTrack.info.height){this.currentTrack.codecId===gr?(this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===kr?(this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===br?this.currentTrack.info.codec="vp8":t===Tr?this.currentTrack.info.codec="vp9":t===yr&&(this.currentTrack.info.codec="av1");const e=this.currentTrack,r=new Rt(this.input,new zr(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===wr?(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===Sr?this.currentTrack.info.codec="mp3":t===Ir?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=ue):t===vr?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Pr?(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 Mt(this.input,new Or(e));this.currentTrack.inputTrack=r,this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null;break;case Zt.TrackNumber:if(!this.currentTrack)break;this.currentTrack.id=or(e,n);break;case Zt.TrackType:{if(!this.currentTrack)break;const t=or(e,n);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 Zt.FlagEnabled:if(!this.currentTrack)break;or(e,n)||(this.currentTrack=null);break;case Zt.FlagDefault:if(!this.currentTrack)break;this.currentTrack.disposition.default=!!or(e,n);break;case Zt.FlagForced:if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!or(e,n);break;case Zt.FlagOriginal:if(!this.currentTrack)break;this.currentTrack.disposition.original=!!or(e,n);break;case Zt.FlagHearingImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!or(e,n);break;case Zt.FlagVisualImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!or(e,n);break;case Zt.FlagCommentary:if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!or(e,n);break;case Zt.CodecID:if(!this.currentTrack)break;this.currentTrack.codecId=ur(e,n);break;case Zt.CodecPrivate:if(!this.currentTrack)break;this.currentTrack.codecPrivate=aa(e,n);break;case Zt.DefaultDuration:if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=or(e,n);break;case Zt.Name:if(!this.currentTrack)break;this.currentTrack.name=hr(e,n);break;case Zt.Language:if(!this.currentTrack)break;if(this.currentTrack.languageCode!==D)break;this.currentTrack.languageCode=ur(e,n),M(this.currentTrack.languageCode)||(this.currentTrack.languageCode=D);break;case Zt.LanguageBCP47:{if(!this.currentTrack)break;const t=ur(e,n).split("-")[0];this.currentTrack.languageCode=t||D}break;case Zt.Video:if("video"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(o,n));break;case Zt.PixelWidth:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.width=or(e,n);break;case Zt.PixelHeight:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.height=or(e,n);break;case Zt.AlphaMode:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.alphaMode=1===or(e,n);break;case Zt.Colour:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.colorSpace={},this.readContiguousElements(e.slice(o,n));break;case Zt.MatrixCoefficients:{if("video"!==this.currentTrack?.info?.type||!this.currentTrack.info.colorSpace)break;const t=or(e,n),r=g[t]??null;this.currentTrack.info.colorSpace.matrix=r}break;case Zt.Range:if("video"!==this.currentTrack?.info?.type||!this.currentTrack.info.colorSpace)break;this.currentTrack.info.colorSpace.fullRange=2===or(e,n);break;case Zt.TransferCharacteristics:{if("video"!==this.currentTrack?.info?.type||!this.currentTrack.info.colorSpace)break;const t=or(e,n),r=f[t]??null;this.currentTrack.info.colorSpace.transfer=r}break;case Zt.Primaries:{if("video"!==this.currentTrack?.info?.type||!this.currentTrack.info.colorSpace)break;const t=or(e,n),r=h[t]??null;this.currentTrack.info.colorSpace.primaries=r}break;case Zt.Projection:if("video"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(o,n));break;case Zt.ProjectionPoseRoll:{if("video"!==this.currentTrack?.info?.type)break;const t=-mr(e,n);try{this.currentTrack.info.rotation=r(t)}catch{}}break;case Zt.Audio:if("audio"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(o,n));break;case Zt.SamplingFrequency:if("audio"!==this.currentTrack?.info?.type)break;this.currentTrack.info.sampleRate=mr(e,n);break;case Zt.Channels:if("audio"!==this.currentTrack?.info?.type)break;this.currentTrack.info.numberOfChannels=or(e,n);break;case Zt.BitDepth:if("audio"!==this.currentTrack?.info?.type)break;this.currentTrack.info.bitDepth=or(e,n);break;case Zt.CuePoint:if(!this.currentSegment)break;this.readContiguousElements(e.slice(o,n)),this.currentCueTime=null;break;case Zt.CueTime:this.currentCueTime=or(e,n);break;case Zt.CueTrackPositions:{if(null===this.currentCueTime)break;t(this.currentSegment);const r={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(r),this.readContiguousElements(e.slice(o,n)),-1!==r.trackId&&-1!==r.clusterPosition||this.currentSegment.cuePoints.pop()}break;case Zt.CueTrack:{const t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;t.trackId=or(e,n)}break;case Zt.CueClusterPosition:{const r=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!r)break;t(this.currentSegment),r.clusterPosition=this.currentSegment.dataStartPos+or(e,n)}break;case Zt.Timestamp:if(!this.currentCluster)break;this.currentCluster.timestamp=or(e,n);break;case Zt.SimpleBlock:{if(!this.currentCluster)break;const t=nr(e);if(null===t)break;const r=this.getTrackDataInCluster(this.currentCluster,t);if(!r)break;const i=la(e),a=sa(e),s=a>>1&3;let c=!!(128&a);"audio"===r.track.info?.type&&r.track.info.codec&&(c=!0);const l=aa(e,n-(e.filePos-o)),d=r.track.decodingInstructions.length>0;r.blocks.push({timestamp:i,duration:0,isKeyFrame:c,data:l,lacing:s,decoded:!d,mainAdditional:null})}break;case Zt.BlockGroup:if(!this.currentCluster)break;this.readContiguousElements(e.slice(o,n)),this.currentBlock=null;break;case Zt.Block:{if(!this.currentCluster)break;const t=nr(e);if(null===t)break;const r=this.getTrackDataInCluster(this.currentCluster,t);if(!r)break;const i=la(e),a=sa(e)>>1&3,s=aa(e,n-(e.filePos-o)),c=r.track.decodingInstructions.length>0;this.currentBlock={timestamp:i,duration:0,isKeyFrame:!0,data:s,lacing:a,decoded:!c,mainAdditional:null},r.blocks.push(this.currentBlock)}break;case Zt.BlockAdditions:this.readContiguousElements(e.slice(o,n));break;case Zt.BlockMore:if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(o,n)),this.currentBlockAdditional.data&&1===this.currentBlockAdditional.addId&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null;break;case Zt.BlockAdditional:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=aa(e,n);break;case Zt.BlockAddID:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=or(e,n);break;case Zt.BlockDuration:if(!this.currentBlock)break;this.currentBlock.duration=or(e,n);break;case Zt.ReferenceBlock:if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1;break;case Zt.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(o,n));break;case Zt.Targets:this.readContiguousElements(e.slice(o,n));break;case Zt.TargetTypeValue:50!==or(e,n)&&(this.currentTagTargetIsMovie=!1);break;case Zt.TagTrackUID:case Zt.TagEditionUID:case Zt.TagChapterUID:case Zt.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case Zt.SimpleTag:if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(o,n));break;case Zt.TagName:this.currentSimpleTagName=hr(e,n);break;case Zt.TagString:{if(!this.currentSimpleTagName)break;const t=hr(e,n);this.processTagValue(this.currentSimpleTagName,t)}break;case Zt.TagBinary:{if(!this.currentSimpleTagName)break;const t=aa(e,n);this.processTagValue(this.currentSimpleTagName,t)}break;case Zt.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(o,n));const t=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(t.raw??(t.raw={}),t.raw[this.currentAttachedFile.fileUid.toString()]=new ee(this.currentAttachedFile.fileData,this.currentAttachedFile.fileMediaType??void 0,this.currentAttachedFile.fileName??void 0,this.currentAttachedFile.fileDescription??void 0)),this.currentAttachedFile.fileMediaType?.startsWith("image/")&&this.currentAttachedFile.fileData){const e=this.currentAttachedFile.fileName;let r="unknown";if(e){const t=e.toLowerCase();t.startsWith("cover.")?r="coverFront":t.startsWith("back.")&&(r="coverBack")}t.images??(t.images=[]),t.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:r,name:this.currentAttachedFile.fileName??void 0,description:this.currentAttachedFile.fileDescription??void 0})}this.currentAttachedFile=null}break;case Zt.FileUID:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=((e,t)=>{if(t<1)throw new Error("Bad unsigned int size "+t);let r=0n;for(let i=0;i<t;i++)r<<=8n,r+=BigInt(sa(e));return r})(e,n);break;case Zt.FileName:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=hr(e,n);break;case Zt.FileMediaType:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=ur(e,n);break;case Zt.FileData:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=aa(e,n);break;case Zt.FileDescription:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=hr(e,n);break;case Zt.ContentEncodings:if(!this.currentTrack)break;this.readContiguousElements(e.slice(o,n)),this.currentTrack.decodingInstructions.sort((e,t)=>t.order-e.order);break;case Zt.ContentEncoding:this.currentDecodingInstruction={order:0,scope:Br.Block,data:null},this.readContiguousElements(e.slice(o,n)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case Zt.ContentEncodingOrder:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=or(e,n);break;case Zt.ContentEncodingScope:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=or(e,n);break;case Zt.ContentCompression:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:Fr.Zlib,settings:null},this.readContiguousElements(e.slice(o,n));break;case Zt.ContentCompAlgo:if("decompress"!==this.currentDecodingInstruction?.data?.type)break;this.currentDecodingInstruction.data.algorithm=or(e,n);break;case Zt.ContentCompSettings:if("decompress"!==this.currentDecodingInstruction?.data?.type)break;this.currentDecodingInstruction.data.settings=aa(e,n);break;case Zt.ContentEncryption:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}return e.filePos=o+n,!0}decodeBlockData(e,r){t(e.decodingInstructions.length>0);let i=r;for(const a of e.decodingInstructions)if(t(a.data),"decompress"===a.data.type)if(a.data.algorithm===Fr.HeaderStripping)if(a.data.settings&&a.data.settings.length>0){const e=a.data.settings,t=new Uint8Array(e.length+i.length);t.set(e,0),t.set(i,e.length),i=t}return i}processTagValue(e,t){var r;if(!this.currentSegment?.metadataTags)return;const i=this.currentSegment.metadataTags;if(i.raw??(i.raw={}),(r=i.raw)[e]??(r[e]=t),"string"===typeof t)switch(e.toLowerCase()){case"title":i.title??(i.title=t);break;case"description":i.description??(i.description=t);break;case"artist":i.artist??(i.artist=t);break;case"album":i.album??(i.album=t);break;case"album_artist":i.albumArtist??(i.albumArtist=t);break;case"genre":i.genre??(i.genre=t);break;case"comment":i.comment??(i.comment=t);break;case"lyrics":i.lyrics??(i.lyrics=t);break;case"date":{const e=new Date(t);Number.isNaN(e.getTime())||(i.date??(i.date=e))}break;case"track_number":case"part_number":{const e=t.split("/"),r=Number.parseInt(e[0],10),a=e[1]&&Number.parseInt(e[1],10);Number.isInteger(r)&&r>0&&(i.trackNumber??(i.trackNumber=r)),a&&Number.isInteger(a)&&a>0&&(i.tracksTotal??(i.tracksTotal=a))}break;case"disc_number":case"disc":{const e=t.split("/"),r=Number.parseInt(e[0],10),a=e[1]&&Number.parseInt(e[1],10);Number.isInteger(r)&&r>0&&(i.discNumber??(i.discNumber=r)),a&&Number.isInteger(a)&&a>0&&(i.discsTotal??(i.discsTotal=a))}}}}class Nr{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}async computeDuration(){const e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}async getFirstTimestamp(){const e=await this.getFirstPacket({metadataOnly:!0});return e?.timestamp??0}getTimeResolution(){return this.internalTrack.segment.timestampFactor}getDisposition(){return this.internalTrack.disposition}async getFirstPacket(e){return this.performClusterLookup(null,e=>e.trackData.get(this.internalTrack.id)?{blockIndex:0,correctBlockFound:!0}:{blockIndex:-1,correctBlockFound:!1},-1/0,1/0,e)}intoTimescale(e){return A(e*this.internalTrack.segment.timestampFactor)}async getPacket(e,t){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=S(t.presentationTimestamps,r,e=>e.timestamp);return{blockIndex:-1!==i?t.presentationTimestamps[i].blockIndex:-1,correctBlockFound:-1!==i&&r<t.endTimestamp}},r,r,t)}async getNextPacket(e,t){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)}async getKeyPacket(e,t){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=x(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)}async getNextKeyPacket(e,r){const i=this.packetToClusterLocation.get(e);if(void 0===i)throw new Error("Packet was not created from this track.");return this.performClusterLookup(i.cluster,e=>{if(e===i.cluster){const t=e.trackData.get(this.internalTrack.id).blocks.findIndex((e,t)=>e.isKeyFrame&&t>i.blockIndex);if(-1!==t)return{blockIndex:t,correctBlockFound:!0}}else{const r=e.trackData.get(this.internalTrack.id);if(r&&null!==r.firstKeyFrameTimestamp){const e=r.blocks.findIndex(e=>e.isKeyFrame);return t(-1!==e),{blockIndex:e,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,r)}async fetchPacketInCluster(e,r,i){if(-1===r)return null;const a=e.trackData.get(this.internalTrack.id).blocks[r];t(a),a.decoded||(a.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,a.data),a.decoded=!0);const s=i.metadataOnly?Ge:a.data,n=a.timestamp/this.internalTrack.segment.timestampFactor,o=a.duration/this.internalTrack.segment.timestampFactor,c={};a.mainAdditional&&"video"===this.internalTrack.info?.type&&this.internalTrack.info.alphaMode&&(c.alpha=i.metadataOnly?Ge:a.mainAdditional,c.alphaByteLength=a.mainAdditional.byteLength);const l=new Xe(s,a.isKeyFrame?"key":"delta",n,o,e.dataStartPos+r,a.data.byteLength,c);return this.packetToClusterLocation.set(l,{cluster:e,blockIndex:r}),l}async performClusterLookup(e,r,i,a,s){const{demuxer:n,segment:o}=this.internalTrack;let c=null,l=null,d=-1;if(e){const{blockIndex:t,correctBlockFound:i}=r(e);if(i)return this.fetchPacketInCluster(e,t,s);-1!==t&&(l=e,d=t)}const u=S(this.internalTrack.cuePoints,i,e=>e.time),h=-1!==u?this.internalTrack.cuePoints[u]:null,m=S(this.internalTrack.clusterPositionCache,i,e=>e.startTimestamp),f=-1!==m?this.internalTrack.clusterPositionCache[m]:null,p=Math.max(h?.clusterPosition??0,f?.elementStartPos??0)||null;let g;for(e?null===p||e.elementStartPos>=p?(g=e.elementEndPos,c=e):g=p:g=p??o.clusterSeekStartPos;null===o.elementEndPos||g<=o.elementEndPos-2;){if(c){const e=c.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>a)break}let e=n.reader.requestSliceRange(g,2,ar);if(e instanceof Promise&&(e=await e),!e)break;const i=g,u=dr(e);if(!u||!rr.includes(u.id)&&u.id!==Zt.Void){const e=await pr(n.reader,i,rr,Math.min(o.elementEndPos??1/0,i+Rr));if(e){g=e;continue}break}const h=u.id;let m=u.size;const f=e.filePos;if(h===Zt.Cluster){c=await n.readCluster(i,o),m=c.elementEndPos-f;const{blockIndex:e,correctBlockFound:t}=r(c);if(t)return this.fetchPacketInCluster(c,e,s);-1!==e&&(l=c,d=e)}if(void 0===m){t(h!==Zt.Cluster);m=(await fr(n.reader,f,ir,o.elementEndPos)).pos-f}const p=f+m;if(null===o.elementEndPos){let e=n.reader.requestSliceRange(p,2,ar);if(e instanceof Promise&&(e=await e),!e)break;if(cr(e)===Zt.Segment){o.elementEndPos=p;break}}g=p}if(h&&(!l||l.elementStartPos<h.clusterPosition)){const e=this.internalTrack.cuePoints[u-1];t(!e||e.time<h.time);const i=e?.time??-1/0;return this.performClusterLookup(null,r,i,a,s)}return l?this.fetchPacketInCluster(l,d,s):null}}class zr 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.info.rotation}async getColorSpace(){return{primaries:this.internalTrack.info.colorSpace?.primaries,transfer:this.internalTrack.info.colorSpace?.transfer,matrix:this.internalTrack.info.colorSpace?.matrix,fullRange:this.internalTrack.info.colorSpace?.fullRange}}async canBeTransparent(){return this.internalTrack.info.alphaMode}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??(this.decoderConfigPromise=(async()=>{let e=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)&&(e=await this.getFirstPacket({})),{codec:ne({width:this.internalTrack.info.width,height:this.internalTrack.info.height,codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,colorSpace:this.internalTrack.info.colorSpace,avcType:1,avcCodecInfo:"avc"===this.internalTrack.info.codec&&e?Pe(e.data):null,hevcCodecInfo:"hevc"===this.internalTrack.info.codec&&e?Be(e.data):null,vp9CodecInfo:"vp9"===this.internalTrack.info.codec&&e?ze(e.data):null,av1CodecInfo:"av1"===this.internalTrack.info.codec&&e?Le(e.data):null}),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0}})()):null}}class Or 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}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfig??(this.decoderConfig={codec:oe({codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,aacCodecInfo:this.internalTrack.info.aacCodecInfo}),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}):null}}
|
|
/*!
|
|
* 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 Lr=[44100,48e3,32e3],Ur=[-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],Vr=(e,t)=>{const r=e>>>24,i=e>>>16&255,a=e>>>8&255,s=255&e;if(255!==r&&255!==i&&255!==a&&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 n=0,o=0;16&i?n=8&i?0:1:(n=1,o=1);const c=i>>3&3,l=i>>1&3,d=(a>>2&3)%3,u=s>>6&3,h=s>>4&3,m=s>>3&1,f=s>>2&1,p=3&s,g=Ur[16*n*4+16*l+(a>>4&15)];if(-1===g)return{header:null,bytesAdvanced:1};const k=1e3*g,b=Lr[d]>>n+o,T=((e,t,r,i,a)=>0===t?0:1===t?Math.floor(144*r/(i<<e))+a:2===t?Math.floor(144*r/i)+a:4*(Math.floor(12*r/i)+a))(n,l,k,b,a>>1&1);if(null!==t&&t<T)return{header:null,bytesAdvanced:1};let y;return y=3===c?3===l?384:1152:3===l?384:2===l?1152:576,{header:{totalSize:T,mpegVersionId:c,layer:l,bitrate:k,frequencyIndex:d,sampleRate:b,channel:u,modeExtension:h,copyright:m,original:f,emphasis:p,audioSamplesInFrame:y},bytesAdvanced:1}},qr=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 Hr,Wr,jr,Kr;(Wr=Hr||(Hr={}))[Wr.Unsynchronisation=128]="Unsynchronisation",Wr[Wr.ExtendedHeader=64]="ExtendedHeader",Wr[Wr.ExperimentalIndicator=32]="ExperimentalIndicator",Wr[Wr.Footer=16]="Footer",(Kr=jr||(jr={}))[Kr.ISO_8859_1=0]="ISO_8859_1",Kr[Kr.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",Kr[Kr.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",Kr[Kr.UTF_8=3]="UTF_8";const $r=128,Qr=["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"],Gr=(e,t)=>{const r=aa(e,t),i=Q(r.indexOf(0),r.length),a=r.subarray(0,i);let s="";for(let n=0;n<a.length;n++)s+=String.fromCharCode(a[n]);return s.trimEnd()},Xr=e=>{const t=e.filePos,r=ya(e,3),i=sa(e),a=sa(e),s=sa(e),n=ua(e);if("ID3"!==r||255===i||255===a||0!==(2155905152&n))return e.filePos=t,null;return{majorVersion:i,revision:a,flags:s,size:qr(n)}},Yr=(e,t,r)=>{var i,a,s,n;if(![2,3,4].includes(t.majorVersion))return void console.warn(`Unsupported ID3v2 major version: ${t.majorVersion}`);const o=aa(e,t.size),c=new Jr(t,o);if(t.flags&Hr.Footer&&c.removeFooter(),t.flags&Hr.Unsynchronisation&&3===t.majorVersion&&c.ununsynchronizeAll(),t.flags&Hr.ExtendedHeader){const e=c.readU32();3===t.majorVersion?c.pos+=e:c.pos+=e-4}for(;c.pos<=c.bytes.length-c.frameHeaderSize();){const e=c.readId3V2Frame();if(!e)break;const o=c.pos,l=c.pos+e.size;let d=!1,u=!1,h=!1;if(3===t.majorVersion?(d=!!(64&e.flags),u=!!(128&e.flags)):4===t.majorVersion&&(d=!!(4&e.flags),u=!!(8&e.flags),h=!!(2&e.flags)||!!(t.flags&Hr.Unsynchronisation)),d)console.warn(`Skipping encrypted ID3v2 frame ${e.id}`),c.pos=l;else if(u)console.warn(`Skipping compressed ID3v2 frame ${e.id}`),c.pos=l;else{switch(h&&c.ununsynchronizeRegion(c.pos,l),r.raw??(r.raw={}),"T"===e.id[0]?(i=r.raw)[a=e.id]??(i[a]=c.readId3V2EncodingAndText(l)):(s=r.raw)[n=e.id]??(s[n]=c.readBytes(e.size)),c.pos=o,e.id){case"TIT2":case"TT2":r.title??(r.title=c.readId3V2EncodingAndText(l));break;case"TIT3":case"TT3":r.description??(r.description=c.readId3V2EncodingAndText(l));break;case"TPE1":case"TP1":r.artist??(r.artist=c.readId3V2EncodingAndText(l));break;case"TALB":case"TAL":r.album??(r.album=c.readId3V2EncodingAndText(l));break;case"TPE2":case"TP2":r.albumArtist??(r.albumArtist=c.readId3V2EncodingAndText(l));break;case"TRCK":case"TRK":{const e=c.readId3V2EncodingAndText(l).split("/"),t=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(r.trackNumber??(r.trackNumber=t)),i&&Number.isInteger(i)&&i>0&&(r.tracksTotal??(r.tracksTotal=i))}break;case"TPOS":case"TPA":{const e=c.readId3V2EncodingAndText(l).split("/"),t=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(r.discNumber??(r.discNumber=t)),i&&Number.isInteger(i)&&i>0&&(r.discsTotal??(r.discsTotal=i))}break;case"TCON":case"TCO":{const e=c.readId3V2EncodingAndText(l);let t=/^\((\d+)\)/.exec(e);if(t){const e=Number.parseInt(t[1]);if(void 0!==Qr[e]){r.genre??(r.genre=Qr[e]);break}}if(t=/^\d+$/.exec(e),t){const e=Number.parseInt(t[0]);if(void 0!==Qr[e]){r.genre??(r.genre=Qr[e]);break}}r.genre??(r.genre=e)}break;case"TDRC":case"TDAT":{const e=c.readId3V2EncodingAndText(l),t=new Date(e);Number.isNaN(t.getTime())||(r.date??(r.date=t))}break;case"TYER":case"TYE":{const e=c.readId3V2EncodingAndText(l),t=Number.parseInt(e,10);Number.isInteger(t)&&(r.date??(r.date=new Date(t,0,1)))}break;case"USLT":case"ULT":{const e=c.readU8();c.pos+=3,c.readId3V2Text(e,l),r.lyrics??(r.lyrics=c.readId3V2Text(e,l))}break;case"COMM":case"COM":{const e=c.readU8();c.pos+=3,c.readId3V2Text(e,l),r.comment??(r.comment=c.readId3V2Text(e,l))}break;case"APIC":case"PIC":{const e=c.readId3V2TextEncoding();let i;if(2===t.majorVersion){const e=c.readAscii(3);i="PNG"===e?"image/png":"JPG"===e?"image/jpeg":"image/*"}else i=c.readId3V2Text(e,l);const a=c.readU8(),s=c.readId3V2Text(e,l).trimEnd(),n=l-c.pos;if(n>=0){const e=c.readBytes(n);r.images||(r.images=[]),r.images.push({data:e,mimeType:i,kind:3===a?"coverFront":4===a?"coverBack":"unknown",description:s})}}break;default:c.pos+=e.size}c.pos=l}}};class Jr{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),a=this.bytes.subarray(t);this.bytes=new Uint8Array(i.length+r.length+a.length),this.bytes.set(i,0),this.bytes.set(r,i.length),this.bytes.set(a,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?qr(t):t;const i=this.readU16(),a=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:qr(t);s(e)&&(r=e)}return this.pos=a,{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 jr.ISO_8859_1:{let e="";for(let t=0;t<i.length;t++){const a=i[t];if(0===a){this.pos=r+t+1;break}e+=String.fromCharCode(a)}return e}case jr.UTF_16_WITH_BOM:if(255===i[0]&&254===i[1]){const e=new TextDecoder("utf-16le"),t=Q(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=Q(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=Q(i.findIndex(e=>0===e),i.length);return this.pos=r+Math.min(e+1,i.length),l.decode(i.subarray(0,e))}case jr.UTF_16_BE_NO_BOM:{const e=new TextDecoder("utf-16be"),t=Q(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 jr.UTF_8:{const e=Q(i.findIndex(e=>0===e),i.length);return this.pos=r+Math.min(e+1,i.length),l.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 Zr=async(e,t,r)=>{let i=t;for(;null===r||i<r;){let t=e.requestSlice(i,4);if(t instanceof Promise&&(t=await t),!t)break;const r=ua(t),a=Vr(r,null!==e.fileSize?e.fileSize-i:null);if(a.header)return{header:a.header,startPos:i};i+=a.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 ei extends Ke{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.tracks=[],this.readingMutex=new b,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();if(!this.firstFrameHeader)throw new Error("No valid MP3 frame found.");this.tracks=[new Mt(this.input,new ti(this))]})())}async advanceReader(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,10);if(e instanceof Promise&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const t=Xr(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}const e=await Zr(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,a=t.channel,3===i?3===a?21:36:3===a?13:21);var i,a;let s=this.reader.requestSlice(e.startPos+r,4);if(s instanceof Promise&&(s=await s),s){const e=ua(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 n=t.audioSamplesInFrame/this.firstFrameHeader.sampleRate,o={timestamp:this.nextTimestampInSamples/this.firstFrameHeader.sampleRate,duration:n,dataStart:e.startPos,dataSize:t.totalSize};this.loadedSamples.push(o),this.nextTimestampInSamples+=t.audioSamplesInFrame}async getMimeType(){return"audio/mpeg"}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){await this.readMetadata();const e=this.tracks[0];return t(e),e.computeDuration()}async getMetadataTags(){const e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let e=0,r=!1;for(;;){let t=this.reader.requestSlice(e,10);if(t instanceof Promise&&(t=await t),!t)break;const i=Xr(t);if(!i)break;r=!0;let a=this.reader.requestSlice(t.filePos,i.size);if(a instanceof Promise&&(a=await a),!a)break;Yr(a,i,this.metadataTags),e=t.filePos+i.size}if(!r&&null!==this.reader.fileSize&&this.reader.fileSize>=$r){let e=this.reader.requestSlice(this.reader.fileSize-$r,$r);e instanceof Promise&&(e=await e),t(e);"TAG"===ya(e,3)&&((e,t)=>{var r;const i=e.filePos;t.raw??(t.raw={}),(r=t.raw).TAG??(r.TAG=aa(e,125)),e.filePos=i;const a=Gr(e,30);a&&(t.title??(t.title=a));const s=Gr(e,30);s&&(t.artist??(t.artist=s));const n=Gr(e,30);n&&(t.album??(t.album=n));const o=Gr(e,4),c=Number.parseInt(o,10);Number.isInteger(c)&&c>0&&(t.date??(t.date=new Date(c,0,1)));const l=aa(e,30);let d;if(0===l[28]&&0!==l[29]){const r=l[29];r>0&&(t.trackNumber??(t.trackNumber=r)),e.skip(-30),d=Gr(e,28),e.skip(2)}else e.skip(-30),d=Gr(e,30);d&&(t.comment??(t.comment=d));const u=sa(e);u<Qr.length&&(t.genre??(t.genre=Qr[u]))})(e,this.metadataTags)}return this.metadataTags}finally{e()}}}class ti{constructor(e){this.demuxer=e}getId(){return 1}async getFirstTimestamp(){return 0}getTimeResolution(){return t(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate/this.demuxer.firstFrameHeader.audioSamplesInFrame}async computeDuration(){const e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getName(){return null}getLanguageCode(){return D}getCodec(){return"mp3"}getInternalCodecId(){return null}getNumberOfChannels(){return t(this.demuxer.firstFrameHeader),3===this.demuxer.firstFrameHeader.channel?1:2}getSampleRate(){return t(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{...te}}async getDecoderConfig(){return t(this.demuxer.firstFrameHeader),{codec:"mp3",numberOfChannels:3===this.demuxer.firstFrameHeader.channel?1:2,sampleRate:this.demuxer.firstFrameHeader.sampleRate}}async getPacketAtIndex(e,t){if(-1===e)return null;const r=this.demuxer.loadedSamples[e];if(!r)return null;let i;if(t.metadataOnly)i=Ge;else{let e=this.demuxer.reader.requestSlice(r.dataStart,r.dataSize);if(e instanceof Promise&&(e=await e),!e)return null;i=aa(e,r.dataSize)}return new Xe(i,"key",r.timestamp,r.duration,e,r.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){const r=await this.demuxer.readingMutex.acquire();try{const r=w(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;)await this.demuxer.advanceReader();return this.getPacketAtIndex(i,t)}finally{r()}}async getPacket(e,t){const r=await this.demuxer.readingMutex.acquire();try{for(;;){const r=S(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);await 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 ri=1399285583,ii=new Uint32Array(256);for(let xa=0;xa<256;xa++){let e=xa<<24;for(let t=0;t<8;t++)e=2147483648&e?e<<1^79764919:e<<1;ii[xa]=e>>>0&4294967295}const ai=e=>{const t=c(e),r=t.getUint32(22,!0);t.setUint32(22,0,!0);let i=0;for(let a=0;a<e.length;a++){const t=e[a];i=(i<<8^ii[i>>>24^t])>>>0}return t.setUint32(22,r,!0),i},si=(e,r,i)=>{let a=0,s=null;if(e.length>0)if("vorbis"===r.codec){t(r.vorbisInfo);const n=(1<<(e=>{let t=0;for(;e;)t++,e>>=1;return t})(r.vorbisInfo.modeBlockflags.length-1))-1<<1,o=(e[0]&n)>>1;if(o>=r.vorbisInfo.modeBlockflags.length)throw new Error("Invalid mode number.");let c=i;const l=r.vorbisInfo.modeBlockflags[o];if(s=r.vorbisInfo.blocksizes[l],1===l){const t=1+(1|n),i=e[0]&t?1:0;c=r.vorbisInfo.blocksizes[i]}a=null!==c?c+s>>2:0}else if("opus"===r.codec){a=(e=>{const t=e[0]>>3;return{durationInSamples:Ue[t]}})(e).durationInSamples}return{durationInSamples:a,vorbisBlockSize:s}},ni=27,oi=282,ci=e=>{const t=e.filePos;if(ha(e)!==ri)return null;e.skip(1);const r=sa(e),i=ka(e),a=ha(e),s=ha(e),n=ha(e),o=sa(e),c=new Uint8Array(o);for(let u=0;u<o;u++)c[u]=sa(e);const l=27+o,d=c.reduce((e,t)=>e+t,0);return{headerStartPos:t,totalSize:l+d,dataStartPos:t+l,dataSize:d,headerType:r,granulePosition:i,serialNumber:a,sequenceNumber:s,checksum:n,lacingValues:c}},li=(e,t)=>{for(;e.filePos<t-3;){const t=ha(e),r=79;if((255&t)===r||(t>>>8&255)===r||(t>>>16&255)===r||(t>>>24&255)===r){if(e.skip(-4),t===ri)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 di extends Ke{constructor(e){super(e),this.metadataPromise=null,this.bitstreams=[],this.tracks=[],this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,ni,oi);if(t instanceof Promise&&(t=await t),!t)break;const r=ci(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=await this.readPacket(t.bosPage,0);e&&(e.data.byteLength>=7&&1===e.data[0]&&118===e.data[1]&&111===e.data[2]&&114===e.data[3]&&98===e.data[4]&&105===e.data[5]&&115===e.data[6]?await this.readVorbisMetadata(e,t):e.data.byteLength>=8&&79===e.data[0]&&112===e.data[1]&&117===e.data[2]&&115===e.data[3]&&72===e.data[4]&&101===e.data[5]&&97===e.data[6]&&100===e.data[7]&&await this.readOpusMetadata(e,t),null!==t.codecInfo.codec&&this.tracks.push(new Mt(this.input,new ui(t,this))))}})())}async readVorbisMetadata(e,t){let r=await this.findNextPacketStart(e);if(!r)return;const i=await this.readPacket(r.startPage,r.startSegmentIndex);if(!i)return;if(r=await this.findNextPacketStart(i),!r)return;const a=await this.readPacket(r.startPage,r.startSegmentIndex);if(!a)return;if(3!==i.data[0]||5!==a.data[0])return;const s=[],n=e=>{for(;s.push(Math.min(255,e)),!(e<255);)e-=255};n(e.data.length),n(i.data.length);const o=new Uint8Array(1+s.length+e.data.length+i.data.length+a.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(a.data,1+s.length+e.data.length+i.data.length),t.codecInfo.codec="vorbis",t.description=o,t.lastMetadataPacket=a;const l=c(e.data);t.numberOfChannels=l.getUint8(11),t.sampleRate=l.getUint32(12,!0);const d=l.getUint8(28);t.codecInfo.vorbisInfo={blocksizes:[1<<(15&d),1<<(d>>4)],modeBlockflags:Ve(a.data).modeBlockflags},je(i.data.subarray(7),this.metadataTags)}async readOpusMetadata(e,t){const r=await this.findNextPacketStart(e);if(!r)return;const i=await this.readPacket(r.startPage,r.startSegmentIndex);if(!i)return;t.codecInfo.codec="opus",t.description=e.data,t.lastMetadataPacket=i;const a=(e=>{const t=c(e),r=t.getUint8(9),i=t.getUint16(10,!0),a=t.getUint32(12,!0),s=t.getInt16(16,!0),n=t.getUint8(18);let o=null;return n&&(o=e.subarray(19,21+r)),{outputChannelCount:r,preSkip:i,inputSampleRate:a,outputGain:s,channelMappingFamily:n,channelMappingTable:o}})(e.data);t.numberOfChannels=a.outputChannelCount,t.sampleRate=ue,t.codecInfo.opusInfo={preSkip:a.preSkip},je(i.data.subarray(8),this.metadataTags)}async readPacket(e,r){t(r<e.lacingValues.length);let i=0;for(let t=0;t<r;t++)i+=e.lacingValues[t];let a=e,s=i,n=r;const o=[];e:for(;;){let r=this.reader.requestSlice(a.dataStartPos,a.dataSize);r instanceof Promise&&(r=await r),t(r);const c=aa(r,a.dataSize);for(;;){if(n===a.lacingValues.length){o.push(c.subarray(i,s));break}const e=a.lacingValues[n];if(s+=e,e<255){o.push(c.subarray(i,s));break e}n++}let l=a.headerStartPos+a.totalSize;for(;;){let t=this.reader.requestSliceRange(l,ni,oi);if(t instanceof Promise&&(t=await t),!t)return null;const r=ci(t);if(!r)return null;if(a=r,a.serialNumber===e.serialNumber)break;l=a.headerStartPos+a.totalSize}i=0,s=0,n=0}const c=o.reduce((e,t)=>e+t.length,0);if(0===c)return null;const l=new Uint8Array(c);let d=0;for(let t=0;t<o.length;t++){const e=o[t];l.set(e,d),d+=e.length}return{data:l,endPage:a,endSegmentIndex:n}}async findNextPacketStart(e){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,ni,oi);if(r instanceof Promise&&(r=await r),!r)return null;const i=ci(r);if(!i)return null;if(i.serialNumber===e.endPage.serialNumber)return{startPage:i,startSegmentIndex:0};t=i.headerStartPos+i.totalSize}}async getMimeType(){await this.readMetadata();return(e=>{let t="audio/ogg";e.codecStrings&&(t+=`; codecs="${[...new Set(e.codecStrings)].join(", ")}"`);return t})({codecStrings:(await Promise.all(this.tracks.map(e=>e.getCodecParameterString()))).filter(Boolean)})}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){const e=await this.getTracks(),t=await Promise.all(e.map(e=>e.computeDuration()));return Math.max(0,...t)}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}class ui{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new b,this.internalSampleRate="opus"===e.codecInfo.codec?ue: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}async getDecoderConfig(){return t(this.bitstream.codecInfo.codec),{codec:this.bitstream.codecInfo.codec,numberOfChannels:this.bitstream.numberOfChannels,sampleRate:this.bitstream.sampleRate,description:this.bitstream.description??void 0}}getName(){return null}getLanguageCode(){return D}getDisposition(){return{...te}}async getFirstTimestamp(){return 0}async computeDuration(){const e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}granulePositionToTimestampInSamples(e){return"opus"===this.bitstream.codecInfo.codec?(t(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,r){if(!e)return null;const{durationInSamples:i,vorbisBlockSize:a}=si(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),s=new Xe(r.metadataOnly?Ge: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:a}),s}async getFirstPacket(e){t(this.bitstream.lastMetadataPacket);const r=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!r)return null;let i=0;"opus"===this.bitstream.codecInfo.codec&&(t(this.bitstream.codecInfo.opusInfo),i-=this.bitstream.codecInfo.opusInfo.preSkip);const a=await this.demuxer.readPacket(r.startPage,r.startSegmentIndex);return this.createEncodedPacketFromOggPacket(a,{timestampInSamples:i,vorbisLastBlocksize:null},e)}async getNextPacket(e,t){const r=this.encodedPacketToMetadata.get(e);if(!r)throw new Error("Packet was not created from this track.");const i=await this.demuxer.findNextPacketStart(r.packet);if(!i)return null;const a=r.timestampInSamples+r.durationInSamples,s=await this.demuxer.readPacket(i.startPage,i.startSegmentIndex);return this.createEncodedPacketFromOggPacket(s,{timestampInSamples:a,vorbisLastBlocksize:r.vorbisBlockSize},t)}async getPacket(e,r){if(null===this.demuxer.reader.fileSize)return this.getPacketSequential(e,r);const i=A(e*this.internalSampleRate);if(0===i)return this.getFirstPacket(r);if(i<0)return null;t(this.bitstream.lastMetadataPacket);const a=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!a)return null;let s=a.startPage,n=this.demuxer.reader.fileSize;const o=[s];e:for(;s.headerStartPos+s.totalSize<n;){const e=s.headerStartPos,r=Math.floor((e+n)/2);let a=r;for(;;){const e=Math.min(a+65307,n-ni);let c=this.demuxer.reader.requestSlice(a,e-a);c instanceof Promise&&(c=await c),t(c);if(!li(c,e)){n=r+ni;continue e}let l=this.demuxer.reader.requestSliceRange(c.filePos,ni,oi);l instanceof Promise&&(l=await l),t(l);const d=ci(l);t(d);let u=!1;if(d.serialNumber===this.bitstream.serialNumber)u=!0;else{let e=this.demuxer.reader.requestSlice(d.headerStartPos,d.totalSize);e instanceof Promise&&(e=await e),t(e);const r=aa(e,d.totalSize);u=ai(r)===d.checksum}if(!u){a=d.headerStartPos+4;continue}if(u&&d.serialNumber!==this.bitstream.serialNumber){a=d.headerStartPos+d.totalSize;continue}if(!(-1===d.granulePosition)){this.granulePositionToTimestampInSamples(d.granulePosition)>i?n=d.headerStartPos:(s=d,o.push(d));continue e}a=d.headerStartPos+d.totalSize}}let c=a.startPage;for(const t of o){if(t.granulePosition===s.granulePosition)break;(!c||t.headerStartPos>c.headerStartPos)&&(c=t)}let l=c;const d=[l];for(;l.serialNumber!==this.bitstream.serialNumber||l.granulePosition!==s.granulePosition;){const e=l.headerStartPos+l.totalSize;let r=this.demuxer.reader.requestSliceRange(e,ni,oi);r instanceof Promise&&(r=await r),t(r);const i=ci(r);t(i),l=i,l.serialNumber===this.bitstream.serialNumber&&d.push(l)}t(-1!==l.granulePosition);let u,h,m=null,f=l,p=0;if(l.headerStartPos===a.startPage.headerStartPos)u=this.granulePositionToTimestampInSamples(0),h=!0,m=0;else{u=0,h=!1;for(let t=l.lacingValues.length-1;t>=0;t--){if(l.lacingValues[t]<255){m=t+1;break}}if(null===m)throw new Error("Invalid page with granule position: no packets end on this page.");p=m-1;const e={data:Ge,endPage:f,endSegmentIndex:p};if(await this.demuxer.findNextPacketStart(e)){const e=mi(d,l,m);t(e);const r=hi(d,e.page,e.segmentIndex);r&&(l=r.page,m=r.segmentIndex)}else for(;;){const e=mi(d,l,m);if(!e)break;const t=hi(d,e.page,e.segmentIndex);if(!t)break;if(l=t.page,m=t.segmentIndex,e.page.headerStartPos!==f.headerStartPos){f=e.page,p=e.segmentIndex;break}}}let g=null,k=null;for(;null!==l;){t(null!==m);const e=await this.demuxer.readPacket(l,m);if(!e)break;if(!(l.headerStartPos===a.startPage.headerStartPos&&m<a.startSegmentIndex)){let a=this.createEncodedPacketFromOggPacket(e,{timestampInSamples:u,vorbisLastBlocksize:k?.vorbisBlockSize??null},r);t(a);let s=this.encodedPacketToMetadata.get(a);if(t(s),h||e.endPage.headerStartPos!==f.headerStartPos||e.endSegmentIndex!==p?u+=s.durationInSamples:(u=this.granulePositionToTimestampInSamples(l.granulePosition),h=!0,a=this.createEncodedPacketFromOggPacket(e,{timestampInSamples:u-s.durationInSamples,vorbisLastBlocksize:k?.vorbisBlockSize??null},r),t(a),s=this.encodedPacketToMetadata.get(a),t(s)),g=a,k=s,h&&(Math.max(u,0)>i||Math.max(s.timestampInSamples,0)===i))break}const s=await this.demuxer.findNextPacketStart(e);if(!s)break;l=s.startPage,m=s.startSegmentIndex}return g}async getPacketSequential(e,r){const a=await this.sequentialScanMutex.acquire();try{const a=A(e*this.internalSampleRate);e=a/this.internalSampleRate;const s=S(this.sequentialScanCache,a,e=>e.timestampInSamples);let n;if(-1!==s){const e=this.sequentialScanCache[s];n=this.createEncodedPacketFromOggPacket(e.packet,{timestampInSamples:e.timestampInSamples,vorbisLastBlocksize:e.vorbisLastBlockSize},r)}else n=await this.getFirstPacket(r);let o=0;for(;n&&n.timestamp<e;){const a=await this.getNextPacket(n,r);if(!a||a.timestamp>e)break;if(n=a,o++,100===o){o=0;const e=this.encodedPacketToMetadata.get(n);t(e),this.sequentialScanCache.length>0&&t(i(this.sequentialScanCache).timestampInSamples<=e.timestampInSamples),this.sequentialScanCache.push(e)}}return n}finally{a()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const hi=(e,r,i)=>{let a=r,s=i;e:for(;;){for(s--;s>=0;s--){if(a.lacingValues[s]<255){s++;break e}}t(-1===s);if(!(1&a.headerType)){s=0;break}const r=P(e,e=>e.headerStartPos<a.headerStartPos);if(!r)return null;a=r,s=a.lacingValues.length}if(t(-1!==s),s===a.lacingValues.length){const r=e[e.indexOf(a)+1];t(r),a=r,s=0}return{page:a,segmentIndex:s}},mi=(e,t,r)=>{if(r>0)return{page:t,segmentIndex:r-1};const i=P(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 fi,pi;(pi=fi||(fi={}))[pi.PCM=1]="PCM",pi[pi.IEEE_FLOAT=3]="IEEE_FLOAT",pi[pi.ALAW=6]="ALAW",pi[pi.MULAW=7]="MULAW",pi[pi.EXTENSIBLE=65534]="EXTENSIBLE";class gi extends Ke{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}async readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{let e=this.reader.requestSlice(0,12);e instanceof Promise&&(e=await e),t(e);const r=ya(e,4),i="RIFX"!==r,a="RF64"===r,s=da(e,i);let n=a?this.reader.fileSize:Math.min(s+8,this.reader.fileSize??1/0);if("WAVE"!==ya(e,4))throw new Error("Invalid WAVE file - wrong format");let o=0,c=null,l=e.filePos;for(;null===n||l<n;){let e=this.reader.requestSlice(l,8);if(e instanceof Promise&&(e=await e),!e)break;const t=ya(e,4),r=da(e,i),s=e.filePos;if(a&&0===o&&"ds64"!==t)throw new Error('Invalid RF64 file: First chunk must be "ds64".');if("fmt "===t)await this.parseFmtChunk(s,r,i);else if("data"===t){if(c??(c=r),this.dataStart=e.filePos,this.dataSize=Math.min(c,(n??1/0)-this.dataStart),null===this.reader.fileSize)break}else if("ds64"===t){let e=this.reader.requestSlice(s,r);if(e instanceof Promise&&(e=await e),!e)break;const t=fa(e,i);c=fa(e,i),n=Math.min(t+8,this.reader.fileSize??1/0)}else"LIST"===t?await this.parseListChunk(s,r,i):"ID3 "!==t&&"id3 "!==t||await this.parseId3Chunk(s,r);l=s+r+(1&r),o++}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 Mt(this.input,new bi(this)))})())}async parseFmtChunk(e,t,r){let i=this.reader.requestSlice(e,t);if(i instanceof Promise&&(i=await i),!i)return;let a=na(i,r);const s=na(i,r),n=da(i,r);i.skip(4);const o=na(i,r);let c;if(c=14===t?8:na(i,r),t>=18&&357!==a){const e=na(i,r),s=t-18;if(Math.min(s,e)>=22&&a===fi.EXTENSIBLE){i.skip(6);const e=aa(i,16);a=e[0]|e[1]<<8}}a!==fi.MULAW&&a!==fi.ALAW||(c=8),this.audioInfo={format:a,numberOfChannels:s,sampleRate:n,sampleSizeInBytes:Math.ceil(c/8),blockSizeInBytes:o}}async parseListChunk(e,t,r){var i,a,s,n,o,c,l,d,u,h,m;let f=this.reader.requestSlice(e,t);if(f instanceof Promise&&(f=await f),!f)return;const p=ya(f,4);if("INFO"!==p&&"INF0"!==p)return;let g=f.filePos;for(;g<=e+t-8;){f.filePos=g;const e=ya(f,4),t=da(f,r),p=aa(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((i=this.metadataTags).raw??(i.raw={}),this.metadataTags.raw[e]=b,e){case"INAM":case"TITL":(a=this.metadataTags).title??(a.title=b);break;case"TIT3":(s=this.metadataTags).description??(s.description=b);break;case"IART":(n=this.metadataTags).artist??(n.artist=b);break;case"IPRD":(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&&((c=this.metadataTags).trackNumber??(c.trackNumber=t)),r&&Number.isInteger(r)&&r>0&&((l=this.metadataTags).tracksTotal??(l.tracksTotal=r))}break;case"ICRD":case"IDIT":{const e=new Date(b);Number.isNaN(e.getTime())||((d=this.metadataTags).date??(d.date=e))}break;case"YEAR":{const e=Number.parseInt(b,10);Number.isInteger(e)&&e>0&&((u=this.metadataTags).date??(u.date=new Date(e,0,1)))}break;case"IGNR":case"GENR":(h=this.metadataTags).genre??(h.genre=b);break;case"ICMT":case"CMNT":case"COMM":(m=this.metadataTags).comment??(m.comment=b)}g+=8+t+(1&t)}}async parseId3Chunk(e,t){let r=this.reader.requestSlice(e,t);if(r instanceof Promise&&(r=await r),!r)return;const i=Xr(r);if(i){const t=r.slice(e+10,i.size);Yr(t,i,this.metadataTags)}}getCodec(){if(t(this.audioInfo),this.audioInfo.format===fi.MULAW)return"ulaw";if(this.audioInfo.format===fi.ALAW)return"alaw";if(this.audioInfo.format===fi.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===fi.IEEE_FLOAT&&4===this.audioInfo.sampleSizeInBytes?"pcm-f32":null}async getMimeType(){return"audio/wav"}async computeDuration(){await this.readMetadata();const e=this.tracks[0];return t(e),e.computeDuration()}async getTracks(){return await this.readMetadata(),this.tracks}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}const ki=2048;class bi{constructor(e){this.demuxer=e}getId(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return t(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){const e=this.demuxer.getCodec();return e?(t(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null}async computeDuration(){const e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getNumberOfChannels(){return t(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return t(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return t(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return D}getDisposition(){return{...te}}async getFirstTimestamp(){return 0}async getPacketAtIndex(e,r){t(this.demuxer.audioInfo);const i=e*ki*this.demuxer.audioInfo.blockSizeInBytes;if(i>=this.demuxer.dataSize)return null;const a=Math.min(ki*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-i);if(null===this.demuxer.reader.fileSize){let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+i,a);if(e instanceof Promise&&(e=await e),!e)return null}let s;if(r.metadataOnly)s=Ge;else{let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+i,a);e instanceof Promise&&(e=await e),t(e),s=aa(e,a)}const n=e*ki/this.demuxer.audioInfo.sampleRate,o=a/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(e,n),new Xe(s,"key",n,o,e,a)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,r){t(this.demuxer.audioInfo);const i=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/ki,(this.demuxer.dataSize-1)/(ki*this.demuxer.audioInfo.blockSizeInBytes))),a=await this.getPacketAtIndex(i,r);if(a)return a;if(0===i)return null;t(null===this.demuxer.reader.fileSize);let s=await this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,r);for(;s;){const e=await this.getNextPacket(s,r);if(!e)break;s=e}return s}getNextPacket(e,r){t(this.demuxer.audioInfo);const i=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/ki);return this.getPacketAtIndex(i+1,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 Ti=e=>{const t=e.filePos,r=aa(e,9),i=new a(r);if(4095!==i.readBits(12))return null;i.skipBits(1);if(0!==i.readBits(2))return null;const s=i.readBits(1),n=i.readBits(2)+1,o=i.readBits(4);if(15===o)return null;i.skipBits(1);const c=i.readBits(3);if(0===c)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 d=i.readBits(2)+1;if(1!==d)throw new Error("ADTS frames with more than one AAC frame are not supported.");let u=null;return 1===s?e.filePos-=2:u=i.readBits(16),{objectType:n,samplingFrequencyIndex:o,channelConfiguration:c,frameLength:l,numberOfAacFrames:d,crcCheck:u,startPos:t}},yi=1024;class wi extends Ke{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.tracks=[],this.readingMutex=new b,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();t(this.firstFrameHeader),this.tracks=[new Mt(this.input,new Si(this))]})())}async advanceReader(){let e=this.reader.requestSliceRange(this.lastLoadedPos,7,9);if(e instanceof Promise&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const r=Ti(e);if(!r)return void(this.lastSampleLoaded=!0);if(null!==this.reader.fileSize&&r.startPos+r.frameLength>this.reader.fileSize)return void(this.lastSampleLoaded=!0);this.firstFrameHeader||(this.firstFrameHeader=r);const i=ce[r.samplingFrequencyIndex];t(void 0!==i);const a=yi/i,s=r.crcCheck?9:7,n={timestamp:this.nextTimestampInSamples/i,duration:a,dataStart:r.startPos+s,dataSize:r.frameLength-s};this.loadedSamples.push(n),this.nextTimestampInSamples+=yi,this.lastLoadedPos=r.startPos+r.frameLength}async getMimeType(){return"audio/aac"}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){await this.readMetadata();const e=this.tracks[0];return t(e),e.computeDuration()}async getMetadataTags(){return{}}}class Si{constructor(e){this.demuxer=e}getId(){return 1}async getFirstTimestamp(){return 0}getTimeResolution(){return this.getSampleRate()/yi}async computeDuration(){const e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getName(){return null}getLanguageCode(){return D}getCodec(){return"aac"}getInternalCodecId(){return t(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){t(this.demuxer.firstFrameHeader);const e=le[this.demuxer.firstFrameHeader.channelConfiguration];return t(void 0!==e),e}getSampleRate(){t(this.demuxer.firstFrameHeader);const e=ce[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return t(void 0!==e),e}getDisposition(){return{...te}}async getDecoderConfig(){t(this.demuxer.firstFrameHeader);const e=new Uint8Array(3),r=new a(e),{objectType:i,samplingFrequencyIndex:s,channelConfiguration:n}=this.demuxer.firstFrameHeader;return i>31?(r.writeBits(5,31),r.writeBits(6,i-32)):r.writeBits(5,i),r.writeBits(4,s),r.writeBits(4,n),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate(),description:e.subarray(0,Math.ceil((r.pos-1)/8))}}async getPacketAtIndex(e,t){if(-1===e)return null;const r=this.demuxer.loadedSamples[e];if(!r)return null;let i;if(t.metadataOnly)i=Ge;else{let e=this.demuxer.reader.requestSlice(r.dataStart,r.dataSize);if(e instanceof Promise&&(e=await e),!e)return null;i=aa(e,r.dataSize)}return new Xe(i,"key",r.timestamp,r.duration,e,r.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){const r=await this.demuxer.readingMutex.acquire();try{const r=w(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;)await this.demuxer.advanceReader();return this.getPacketAtIndex(i,t)}finally{r()}}async getPacket(e,t){const r=await this.demuxer.readingMutex.acquire();try{for(;;){const r=S(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);await 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 Ii extends Ke{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 b,this.lastSampleLoaded=!1,this.reader=e._reader}async computeDuration(){return await this.readMetadata(),t(this.track),this.track.computeDuration()}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}async getTracks(){return await this.readMetadata(),t(this.track),[this.track]}async getMimeType(){return"audio/flac"}async readMetadata(){let e=4;return this.metadataPromise??(this.metadataPromise=(async()=>{for(var r;null===this.reader.fileSize||e<this.reader.fileSize;){let i=this.reader.requestSlice(e,4);if(i instanceof Promise&&(i=await i),e+=4,null===i)throw new Error(`Metadata block at position ${e} is too small! Corrupted file.`);t(i);const s=sa(i),n=ca(i),o=0!==(128&s);switch(127&s){case He.STREAMINFO:{let r=this.reader.requestSlice(e,n);if(r instanceof Promise&&(r=await r),t(r),null===r)throw new Error(`StreamInfo block at position ${e} is too small! Corrupted file.`);const i=aa(r,34),s=new a(i),o=s.readBits(16),c=s.readBits(16),l=s.readBits(24),d=s.readBits(24),u=s.readBits(20),h=s.readBits(3)+1;s.readBits(5);const m=s.readBits(36);s.skipBits(128);const f=new Uint8Array(42);f.set(new Uint8Array([102,76,97,67]),0),f.set(new Uint8Array([128,0,0,34]),4),f.set(i,8),this.audioInfo={numberOfChannels:h,sampleRate:u,totalSamples:m,minimumBlockSize:o,maximumBlockSize:c,minimumFrameSize:l,maximumFrameSize:d,description:f},this.track=new Mt(this.input,new vi(this));break}case He.VORBIS_COMMENT:{let r=this.reader.requestSlice(e,n);r instanceof Promise&&(r=await r),t(r),je(aa(r,n),this.metadataTags);break}case He.PICTURE:{let i=this.reader.requestSlice(e,n);i instanceof Promise&&(i=await i),t(i);const a=ua(i),s=ua(i),o=l.decode(aa(i,s)),c=ua(i),d=l.decode(aa(i,c));i.skip(16);const u=ua(i),h=aa(i,u);(r=this.metadataTags).images??(r.images=[]),this.metadataTags.images.push({data:h,mimeType:o,kind:3===a?"coverFront":4===a?"coverBack":"unknown",description:d});break}}if(e+=n,o){this.lastLoadedPos=e;break}}})())}async readNextFlacFrame({startPos:e,isFirstPacket:r}){t(this.audioInfo);const i=this.audioInfo.maximumFrameSize+16,a=await this.reader.requestSliceRange(e,this.audioInfo.minimumFrameSize,i);if(!a)return null;const s=this.readFlacFrameHeader({slice:a,isFirstPacket:r});if(!s)return null;for(a.filePos=e+this.audioInfo.minimumFrameSize;;){if(a.filePos>a.end-6)return{num:s.num,blockSize:s.blockSize,sampleRate:s.sampleRate,size:a.end-e,isLastFrame:!0};if(255===sa(a)){const t=a.filePos;if(sa(a)!==(1===this.blockingBit?249:248)){a.filePos=t;continue}a.skip(-2);const r=a.filePos-e,i=this.readFlacFrameHeader({slice:a,isFirstPacket:!1});if(!i){a.filePos=t;continue}if(0===this.blockingBit){if(i.num-s.num!==1){a.filePos=t;continue}}else if(i.num-s.num!==s.blockSize){a.filePos=t;continue}return{num:s.num,blockSize:s.blockSize,sampleRate:s.sampleRate,size:r,isLastFrame:!1}}}}readFlacFrameHeader({slice:e,isFirstPacket:r}){const i=e.filePos,s=aa(e,4),n=new a(s);if(32764!==n.readBits(15))return null;if(null===this.blockingBit){t(r);const e=n.readBits(1);this.blockingBit=e}else if(1===this.blockingBit){t(!r);if(1!==n.readBits(1))return null}else{if(0!==this.blockingBit)throw new Error("Invalid blocking bit");t(!r);if(0!==n.readBits(1))return null}const o=(e=>0===e?null:1===e?192:e>=2&&e<=5?144*2**e:6===e?"uncommon-u8":7===e?"uncommon-u16":e>=8&&e<=15?2**e:null)(n.readBits(4));if(!o)return null;t(this.audioInfo);const c=((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(!c)return null;n.readBits(4),n.readBits(3);if(0!==n.readBits(1))return null;const l=(e=>{let t=0;const r=new a(aa(e,1));for(;1===r.readBits(1);)t++;if(0===t)return r.readBits(7);const i=[],s=t-1,n=new a(aa(e,s)),o=8-t-1;for(let a=0;a<o;a++)i.unshift(r.readBits(1));for(let a=0;a<s;a++)for(let e=0;e<8;e++){const t=n.readBits(1);e<2||i.unshift(t)}return i.reduce((e,t,r)=>e|t<<r,0)})(e),d=((e,r)=>"uncommon-u16"===r?oa(e)+1:"uncommon-u8"===r?sa(e)+1:"number"===typeof r?r:(C(r),void t(!1)))(e,o),u=((e,t)=>"uncommon-u16"===t?oa(e):"uncommon-u16-10"===t?10*oa(e):"uncommon-u8"===t?sa(e):"number"===typeof t?t:null)(e,c);if(null===u)return null;if(u!==this.audioInfo.sampleRate)return null;const h=e.filePos-i,m=sa(e);e.skip(-h),e.skip(-1);const f=(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})(aa(e,h));return m!==f?null:{num:l,blockSize:d,sampleRate:u}}async advanceReader(){await this.readMetadata(),t(null!==this.lastLoadedPos),t(this.audioInfo);const e=this.lastLoadedPos,r=await this.readNextFlacFrame({startPos:e,isFirstPacket:0===this.loadedSamples.length});if(!r)return void(this.lastSampleLoaded=!0);const i=this.loadedSamples[this.loadedSamples.length-1],a={blockOffset:i?i.blockOffset+i.blockSize:0,blockSize:r.blockSize,byteOffset:e,byteSize:r.size};this.lastLoadedPos=this.lastLoadedPos+r.size,this.loadedSamples.push(a),r.isLastFrame&&(this.lastSampleLoaded=!0)}}class vi{constructor(e){this.demuxer=e}getId(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return t(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}async computeDuration(){const e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getSampleRate(){return t(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return D}getTimeResolution(){return t(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getDisposition(){return{...te}}async getFirstTimestamp(){return 0}async getDecoderConfig(){return t(this.demuxer.audioInfo),{codec:"flac",numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}}async getPacket(e,r){if(t(this.demuxer.audioInfo),e<0)throw new Error("Timestamp cannot be negative");const i=await this.demuxer.readingMutex.acquire();try{for(;;){const t=S(this.demuxer.loadedSamples,e,e=>e.blockOffset/this.demuxer.audioInfo.sampleRate);if(-1===t){await this.demuxer.advanceReader();continue}const i=this.demuxer.loadedSamples[t],a=i.blockOffset/this.demuxer.audioInfo.sampleRate;if(!(a+i.blockSize/this.demuxer.audioInfo.sampleRate<=e))return this.getPacketAtIndex(t,r);if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(this.demuxer.loadedSamples.length-1,r);await this.demuxer.advanceReader()}}finally{i()}}async getNextPacket(e,t){const r=await 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;)await 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)}async getPacketAtIndex(e,r){const i=this.demuxer.loadedSamples[e];if(!i)return null;let a;if(r.metadataOnly)a=Ge;else{let e=this.demuxer.reader.requestSlice(i.byteOffset,i.byteSize);if(e instanceof Promise&&(e=await e),!e)return null;a=aa(e,i.byteSize)}t(this.demuxer.audioInfo);const s=i.blockOffset/this.demuxer.audioInfo.sampleRate,n=i.blockSize/this.demuxer.audioInfo.sampleRate;return new Xe(a,"key",s,n,e,i.byteSize)}async getFirstPacket(e){for(;0===this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await 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 Pi{}class xi extends Pi{async _getMajorBrand(e){let t=e._reader.requestSlice(0,12);if(t instanceof Promise&&(t=await t),!t)return null;t.skip(4);return"ftyp"!==ya(t,4)?null:ya(t,4)}_createDemuxer(e){return new qt(e)}}class Ci extends xi{async _canReadInput(e){const t=await this._getMajorBrand(e);return!!t&&"qt "!==t}get name(){return"MP4"}get mimeType(){return"video/mp4"}}class _i extends xi{async _canReadInput(e){return"qt "===await this._getMajorBrand(e)}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}}class Bi extends Pi{async isSupportedEBMLOfDocType(e,t){let r=e._reader.requestSlice(0,ar);if(r instanceof Promise&&(r=await r),!r)return!1;const i=sr(r);if(null===i)return!1;if(i<1||i>8)return!1;if(or(r,i)!==Zt.EBML)return!1;const a=lr(r);if("number"!==typeof a)return!1;let s=e._reader.requestSlice(r.filePos,a);if(s instanceof Promise&&(s=await s),!s)return!1;const n=r.filePos;for(;s.filePos<=n+a-2;){const e=dr(s);if(!e)break;const{id:r,size:i}=e,a=s.filePos;if(void 0===i)return!1;switch(r){case Zt.EBMLVersion:if(1!==or(s,i))return!1;break;case Zt.EBMLReadVersion:if(1!==or(s,i))return!1;break;case Zt.DocType:if(ur(s,i)!==t)return!1;break;case Zt.DocTypeVersion:if(or(s,i)>4)return!1}s.filePos=a+i}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new Mr(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}}class Ei extends Bi{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}}class Fi extends Pi{async _canReadInput(e){let t=e._reader.requestSlice(0,10);if(t instanceof Promise&&(t=await t),!t)return!1;let r=0,i=!1;for(;;){let t=e._reader.requestSlice(r,10);if(t instanceof Promise&&(t=await t),!t)break;const a=Xr(t);if(!a)break;i=!0,r=t.filePos+a.size}const a=await Zr(e._reader,r,r+4096);if(!a)return!1;if(i)return!0;r=a.startPos+a.header.totalSize;const s=await Zr(e._reader,r,r+4);if(!s)return!1;const n=a.header,o=s.header;return n.channel===o.channel&&n.sampleRate===o.sampleRate}_createDemuxer(e){return new ei(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}}class Di extends Pi{async _canReadInput(e){let t=e._reader.requestSlice(0,12);if(t instanceof Promise&&(t=await t),!t)return!1;const r=ya(t,4);if("RIFF"!==r&&"RIFX"!==r&&"RF64"!==r)return!1;t.skip(4);return"WAVE"===ya(t,4)}_createDemuxer(e){return new gi(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}}class Ai extends Pi{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=await t),!!t&&"OggS"===ya(t,4)}_createDemuxer(e){return new di(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}}class Ri extends Pi{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=await t),!!t&&"fLaC"===ya(t,4)}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new Ii(e)}}class Mi extends Pi{async _canReadInput(e){let t=e._reader.requestSliceRange(0,7,9);if(t instanceof Promise&&(t=await t),!t)return!1;const r=Ti(t);if(!r)return!1;if(t=e._reader.requestSliceRange(r.frameLength,7,9),t instanceof Promise&&(t=await t),!t)return!1;const i=Ti(t);return!!i&&(r.objectType===i.objectType&&r.samplingFrequencyIndex===i.samplingFrequencyIndex&&r.channelConfiguration===i.channelConfiguration)}_createDemuxer(e){return new wi(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}}const Ni=new Ci,zi=new _i,Oi=new Bi,Li=new Ei,Ui=new Fi,Vi=new Di,qi=new Ai,Hi=new Mi,Wi=[Ni,zi,Oi,Li,Vi,qi,new Ri,Ui,Hi];
|
|
/*!
|
|
* 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 ji{constructor(){this._disposed=!1,this._sizePromise=null,this.onread=null}async getSizeOrNull(){if(this._disposed)throw new ea;return this._sizePromise??(this._sizePromise=Promise.resolve(this._retrieveSize()))}async getSize(){if(this._disposed)throw new ea;const e=await this.getSizeOrNull();if(null===e)throw new Error("Cannot determine the size of an unsized source.");return e}}class Ki extends ji{constructor(e,t={}){if(!(e instanceof Blob))throw new TypeError("blob must be a Blob.");if(!t||"object"!==typeof t)throw new TypeError("options must be an object.");if(void 0!==t.maxCacheSize&&(!J(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 Ji({maxCacheSize:t.maxCacheSize??8388608,maxWorkerCount:4,runWorker:this._runWorker.bind(this),prefetchProfile:Yi.fileSystem})}_retrieveSize(){const e=this._blob.size;return this._orchestrator.fileSize=e,e}_read(e,t){return this._orchestrator.read(e,t)}async _runWorker(e){let t=this._readers.get(e);if(void 0===t){if("stream"in this._blob&&!q()){t=this._blob.slice(e.currentPos).stream().getReader()}else t=null;this._readers.set(e,t)}for(;e.currentPos<e.targetPos&&!e.aborted;)if(t){const{done:r,value:i}=await t.read();if(r)throw this._orchestrator.forgetWorker(e),new Error("Blob reader stopped unexpectedly before all requested data was read.");if(e.aborted)break;this.onread?.(e.currentPos,e.currentPos+i.length),this._orchestrator.supplyWorkerData(e,i)}else{const t=await this._blob.slice(e.currentPos,e.targetPos).arrayBuffer();if(e.aborted)break;this.onread?.(e.currentPos,e.currentPos+t.byteLength),this._orchestrator.supplyWorkerData(e,new Uint8Array(t))}e.running=!1,e.aborted&&await(t?.cancel())}_dispose(){this._orchestrator.dispose()}}const $i=524288,Qi=(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{}if(("undefined"===typeof navigator||"boolean"!==typeof navigator.onLine||navigator.onLine)&&null!==e&&e!==window.location.origin)return console.warn("Request will not be retried because a CORS error was suspected due to different origins. You can modify this behavior by providing your own function for the 'getRetryDelay' option."),null}return Math.min(2**(e-2),16)};class Gi extends ji{constructor(e,t={}){if("string"!==typeof e&&!(e instanceof URL)&&!("undefined"!==typeof Request&&e instanceof Request))throw new TypeError("url must be a string, URL or Request.");if(!t||"object"!==typeof t)throw new TypeError("options must be an object.");if(void 0!==t.requestInit&&(!t.requestInit||"object"!==typeof t.requestInit))throw new TypeError("options.requestInit, when provided, must be an object.");if(void 0!==t.getRetryDelay&&"function"!==typeof t.getRetryDelay)throw new TypeError("options.getRetryDelay, when provided, must be a function.");if(void 0!==t.maxCacheSize&&(!J(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=t.getRetryDelay??Qi,this._orchestrator=new Ji({maxCacheSize:t.maxCacheSize??67108864,maxWorkerCount:2,runWorker:this._runWorker.bind(this),prefetchProfile:Yi.network})}async _retrieveSize(){const e=new AbortController,t=await L(this._options.fetchFn??fetch,this._url,z(this._options.requestInit??{},{headers:{Range:"bytes=0-"},signal:e.signal}),this._getRetryDelay,()=>this._disposed);if(!t.ok)throw new Error(`Error fetching ${String(this._url)}: ${t.status} ${t.statusText}`);let r,i;if(206===t.status)i=this._getTotalLengthFromRangeResponse(t),r=this._orchestrator.createWorker(0,Math.min(i,$i));else{const e=t.headers.get("Content-Length");if(!e)throw new Error(`HTTP response (status ${t.status}) must surface Content-Length header.`);i=Number(e),r=this._orchestrator.createWorker(0,i),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=i,this._existingResponses.set(r,{response:t,abortController:e}),this._orchestrator.runWorker(r),i}_read(e,t){return this._orchestrator.read(e,t)}async _runWorker(e){for(;;){const i=this._existingResponses.get(e);this._existingResponses.delete(e);let a=i?.abortController,s=i?.response;if(a||(a=new AbortController,s=await L(this._options.fetchFn??fetch,this._url,z(this._options.requestInit??{},{headers:{Range:`bytes=${e.currentPos}-`},signal:a.signal}),this._getRetryDelay,()=>this._disposed)),t(s),!s.ok)throw new Error(`Error fetching ${String(this._url)}: ${s.status} ${s.statusText}`);if(e.currentPos>0&&206!==s.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(!s.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");const n=s.body.getReader();for(;;){if(e.currentPos>=e.targetPos||e.aborted)return a.abort(),void(e.running=!1);let t;try{t=await n.read()}catch(r){if(this._disposed)throw r;const e=this._getRetryDelay(1,r,this._url);if(null!==e){console.error("Error while reading response stream. Attempting to resume.",r),await new Promise(t=>setTimeout(t,1e3*e));break}throw r}if(e.aborted)continue;const{done:i,value:s}=t;if(i){if(e.currentPos>=e.targetPos)return this._orchestrator.forgetWorker(e),void(e.running=!1);break}this.onread?.(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 Xi extends ji{constructor(e,t={}){if(!(e instanceof ReadableStream))throw new TypeError("stream must be a ReadableStream.");if(!t||"object"!==typeof t)throw new TypeError("options must be an object.");if(void 0!==t.maxCacheSize&&(!J(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");super(),this._reader=null,this._cache=[],this._pendingSlices=[],this._currentIndex=0,this._targetIndex=0,this._maxRequestedIndex=0,this._endIndex=null,this._pulling=!1,this._stream=e,this._maxCacheSize=t.maxCacheSize??16777216}_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=S(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 a=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>a&&this._throwDueToCacheMiss();const n=Math.min(t,r.end);i<n&&(s.set(r.bytes.subarray(i-r.start,n-r.start),i-e),a=n)}if(a===t)return{bytes:s,view:c(s),offset:e};this._currentIndex>a&&this._throwDueToCacheMiss();const{promise:n,resolve:o,reject:l}=v();return this._pendingSlices.push({start:e,end:t,bytes:s,resolve:o,reject:l}),this._targetIndex=Math.max(this._targetIndex,t),this._pulling||(this._pulling=!0,this._pull().catch(e=>{if(this._pulling=!1,!(this._pendingSlices.length>0))throw e;this._pendingSlices.forEach(t=>t.reject(e)),this._pendingSlices.length=0})),n}_throwDueToCacheMiss(){throw new Error("Read is before the cached region. With ReadableStreamSource, you must access the data more sequentially or increase the size of its cache.")}async _pull(){for(this._reader??(this._reader=this._stream.getReader());this._currentIndex<this._targetIndex&&!this._disposed;){const{done:e,value:t}=await 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 a=0;a<this._pendingSlices.length;a++){const e=this._pendingSlices[a],s=Math.max(r,e.start),n=Math.min(i,e.end);s<n&&(e.bytes.set(t.subarray(s-r,n-r),s-e.start),n===e.end&&(e.resolve({bytes:e.bytes,view:c(e.bytes),offset:e.start}),this._pendingSlices.splice(a,1),a--))}for(this._cache.push({start:r,end:i,bytes:t,view:c(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 Yi={fileSystem:(e,t)=>{const r=65536;return{start:e=Math.floor((e-r)/r)*r,end:t=Math.ceil((t+r)/r)*r}},network:(e,t,r)=>{const i=65536;e=Math.max(0,Math.floor((e-i)/i)*i);for(const a of r){const r=8388608,i=Math.max((a.startPos+a.targetPos)/2,a.targetPos-r);if(G(e,t,i,a.targetPos)){const e=a.targetPos-a.startPos,i=Math.ceil((e+1)/r)*r,s=2**Math.ceil(Math.log2(e+1)),n=Math.min(s,i);t=Math.max(t,a.startPos+n)}}return{start:e,end:t=Math.max(t,e+$i)}}};class Ji{constructor(e){this.options=e,this.fileSize=null,this.nextAge=0,this.workers=[],this.cache=[],this.currentCacheSize=0,this.disposed=!1}read(e,r){t(null!==this.fileSize);const i=this.options.prefetchProfile(e,r,this.workers),a=Math.max(i.start,0),s=Math.min(i.end,this.fileSize);t(a<=e&&r<=s);let n=null;const o=S(this.cache,e,e=>e.start),l=-1!==o?this.cache[o]:null;l&&l.start<=e&&r<=l.end&&(l.age=this.nextAge++,n={bytes:l.bytes,view:l.view,offset:l.start});const d=S(this.cache,a,e=>e.start),u=n?null:new Uint8Array(r-e);let h=0,m=a;const f=[];if(-1!==d){for(let i=d;i<this.cache.length;i++){const n=this.cache[i];if(n.start>=s)break;if(n.end<=a)continue;const o=Math.max(a,n.start),c=Math.min(s,n.end);if(t(o<=c),m<o&&f.push({start:m,end:o}),m=c,u){const t=Math.max(e,n.start),i=Math.min(r,n.end);if(t<i){const r=t-e;u.set(n.bytes.subarray(t-n.start,i-n.start),r),r===h&&(h=i-e)}}n.age=this.nextAge++}m<s&&f.push({start:m,end:s})}else f.push({start:a,end:s});if(u&&h>=u.length&&(n={bytes:u,view:c(u),offset:e}),0===f.length)return t(n),n;const{promise:p,resolve:g,reject:k}=v(),b=[];for(const t of f){const i=Math.max(e,t.start),a=Math.min(r,t.end);i===t.start&&a===t.end?b.push(t):i<a&&b.push({start:i,end:a})}for(const t of f){const r=u&&{start:e,bytes:u,holes:b,resolve:g,reject:k};let i=!1;for(const e of this.workers){const a=2**17;if(G(t.start-a,t.start,e.currentPos,e.targetPos)){e.targetPos=Math.max(e.targetPos,t.end),i=!0,r&&!e.pendingSlices.includes(r)&&e.pendingSlices.push(r),e.running||this.runWorker(e);break}}if(!i){const e=this.createWorker(t.start,t.end);r&&(e.pendingSlices=[r]),this.runWorker(e)}}return n||(t(u),n=p.then(t=>({bytes:t,view:c(t),offset:e}))),n}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){t(!e.running),t(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,r){t(!e.aborted);const i=e.currentPos,a=i+r.length;this.insertIntoCache({start:i,end:a,bytes:r,view:c(r),age:this.nextAge++}),e.currentPos+=r.length,e.targetPos=Math.max(e.targetPos,e.currentPos);for(let t=0;t<e.pendingSlices.length;t++){const s=e.pendingSlices[t],n=Math.max(i,s.start),o=Math.min(a,s.start+s.bytes.length);n<o&&s.bytes.set(r.subarray(n-i,o-i),n-s.start);for(let e=0;e<s.holes.length;e++){const t=s.holes[e];i<=t.start&&a>t.start&&(t.start=a),t.end<=t.start&&(s.holes.splice(e,1),e--)}0===s.holes.length&&(s.resolve(s.bytes),e.pendingSlices.splice(t,1),t--)}for(let t=0;t<this.workers.length;t++){const r=this.workers[t];e===r||r.running||G(i,a,r.currentPos,r.targetPos)&&(this.workers.splice(t,1),t--)}}forgetWorker(e){const r=this.workers.indexOf(e);t(-1!==r),this.workers.splice(r,1)}insertIntoCache(e){if(0===this.options.maxCacheSize)return;let t=S(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=c(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=c(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/.
|
|
*/Y();class Zi{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 Pi)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof ji))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 ta(e.source)}_getDemuxer(){return this._demuxerPromise??(this._demuxerPromise=(async()=>{this._reader.fileSize=await this._source.getSizeOrNull();for(const e of this._formats){if(await 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}async getFormat(){return await this._getDemuxer(),t(this._format),this._format}async computeDuration(){return(await this._getDemuxer()).computeDuration()}async getTracks(){return(await this._getDemuxer()).getTracks()}async getVideoTracks(){return(await this.getTracks()).filter(e=>e.isVideoTrack())}async getAudioTracks(){return(await this.getTracks()).filter(e=>e.isAudioTrack())}async getPrimaryVideoTrack(){return(await this.getTracks()).find(e=>e.isVideoTrack())??null}async getPrimaryAudioTrack(){return(await this.getTracks()).find(e=>e.isAudioTrack())??null}async getMimeType(){return(await this._getDemuxer()).getMimeType()}async getMetadataTags(){return(await this._getDemuxer()).getMetadataTags()}dispose(){this._disposed||(this._disposed=!0,this._source._disposed=!0,this._source._dispose())}[Symbol.dispose](){this.dispose()}}class ea 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 ta{constructor(e){this.source=e}requestSlice(e,t){if(this.source._disposed)throw new ea;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 ra(t.bytes,t.view,t.offset,e,r):null):i?new ra(i.bytes,i.view,i.offset,e,r):null}requestSliceRange(e,r,i){if(this.source._disposed)throw new ea;if(null!==this.fileSize)return this.requestSlice(e,F(this.fileSize-e,r,i));{const a=this.requestSlice(e,i),s=a=>{if(a)return a;const s=a=>(t(null!==a),this.requestSlice(e,F(a-e,r,i))),n=this.source._retrieveSize();return n instanceof Promise?n.then(s):s(n)};return a instanceof Promise?a.then(s):s(a)}}}class ra{constructor(e,t,r,i,a){this.bytes=e,this.view=t,this.offset=r,this.start=i,this.end=a,this.bufferPos=i-r}static tempFromBytes(e){return new ra(e,c(e),0,0,e.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos(e){this.bufferPos=e-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip(e){this.bufferPos+=e}slice(e,t=this.end-e){if(e<this.start||e+t>this.end)throw new RangeError("Slicing outside of original slice.");return new ra(this.bytes,this.view,this.offset,e,e+t)}}const ia=(e,t)=>{if(e.filePos<e.start||e.filePos+t>e.end)throw new RangeError(`Tried reading [${e.filePos}, ${e.filePos+t}), but slice is [${e.start}, ${e.end}). This is likely an internal error, please report it alongside the file that caused it.`)},aa=(e,t)=>{ia(e,t);const r=e.bytes.subarray(e.bufferPos,e.bufferPos+t);return e.bufferPos+=t,r},sa=e=>(ia(e,1),e.view.getUint8(e.bufferPos++)),na=(e,t)=>{ia(e,2);const r=e.view.getUint16(e.bufferPos,t);return e.bufferPos+=2,r},oa=e=>{ia(e,2);const t=e.view.getUint16(e.bufferPos,!1);return e.bufferPos+=2,t},ca=e=>{ia(e,3);const t=_(e.view,e.bufferPos,!1);return e.bufferPos+=3,t},la=e=>{ia(e,2);const t=e.view.getInt16(e.bufferPos,!1);return e.bufferPos+=2,t},da=(e,t)=>{ia(e,4);const r=e.view.getUint32(e.bufferPos,t);return e.bufferPos+=4,r},ua=e=>{ia(e,4);const t=e.view.getUint32(e.bufferPos,!1);return e.bufferPos+=4,t},ha=e=>{ia(e,4);const t=e.view.getUint32(e.bufferPos,!0);return e.bufferPos+=4,t},ma=e=>{ia(e,4);const t=e.view.getInt32(e.bufferPos,!1);return e.bufferPos+=4,t},fa=(e,t)=>{let r,i;return t?(r=da(e,!0),i=da(e,!0)):(i=da(e,!1),r=da(e,!1)),4294967296*i+r},pa=e=>4294967296*ua(e)+ua(e),ga=e=>4294967296*ma(e)+ua(e),ka=e=>{const t=ha(e),r=(e=>{ia(e,4);const t=e.view.getInt32(e.bufferPos,!0);return e.bufferPos+=4,t})(e);return 4294967296*r+t},ba=e=>{ia(e,4);const t=e.view.getFloat32(e.bufferPos,!1);return e.bufferPos+=4,t},Ta=e=>{ia(e,8);const t=e.view.getFloat64(e.bufferPos,!1);return e.bufferPos+=8,t},ya=(e,t)=>{ia(e,t);let r="";for(let i=0;i<t;i++)r+=String.fromCharCode(e.bytes[e.bufferPos++]);return r};class wa{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 Gi(e):e instanceof Blob?new Ki(e):"undefined"!==typeof ReadableStream&&e instanceof ReadableStream?new Xi(e):e}ensureAudioContext(e){if(this.audioContext)return;const t=window.AudioContext||window.webkitAudioContext;try{this.audioContext=new t({sampleRate:e})}catch{this.audioContext=new t}this.gainNode=this.audioContext.createGain(),this.gainNode.connect(this.audioContext.destination),this.updateGain()}updateGain(){if(!this.gainNode)return;const e=this.muted?0:this.volume;this.gainNode.gain.value=e*e}stopQueuedNodes(){this.queuedNodes.forEach(e=>e.stop()),this.queuedNodes.clear()}async stopIterator(){await(this.audioIterator?.return()),this.audioIterator=null}async load(e,t){const r=++this.asyncId;await 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 Zi({source:i,formats:Wi}),this.duration=await this.input.computeDuration(),r!==this.asyncId)return;const a=await this.input.getPrimaryAudioTrack();return a&&null!==a.codec&&await a.canDecode()?(this.ensureAudioContext(a.sampleRate),this.audioSink=new Dt(a),void t?.()):(this.audioSink=null,this.ensureAudioContext(),void t?.())}async runIterator(e){if(this.audioSink)for(await this.stopIterator(),this.audioIterator=this.audioSink.buffers(this.currentTime);;){if(e!==this.asyncId||this.paused)return;const 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 a;try{a=await 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&&(await this.audioContext.resume(),this.events.emit("canplay"),this.events.emit("playing")),a.done)break;const{buffer:s,timestamp:n}=a.value,o=this.audioContext.createBufferSource();o.buffer=s,o.connect(this.gainNode),o.playbackRate.value=this.playbackRate;const c=this.audioContextStartTime+(n-this.playbackTimeAtStart)/this.playbackRate,l=c+s.duration/this.playbackRate;l>this.latestScheduledEndTime&&(this.latestScheduledEndTime=l),c>=this.audioContext.currentTime?o.start(c):o.start(this.audioContext.currentTime,(this.audioContext.currentTime-c)*this.playbackRate),this.queuedNodes.add(o),o.onended=()=>this.queuedNodes.delete(o)}}async play(){if(!this.paused)return;this.audioContext||this.ensureAudioContext(),"suspended"===this.audioContext.state&&await this.audioContext.resume(),this.audioContextStartTime=this.audioContext.currentTime,this.latestScheduledEndTime=this.audioContextStartTime,this.paused=!1;const e=++this.asyncId;this.runIterator(e)}pause(){this.paused||(this.playbackTimeAtStart=this.currentTime,this.paused=!0,this.stopIterator(),this.stopQueuedNodes())}async seek(e){this.playbackTimeAtStart=Math.max(0,e),this.audioContextStartTime=this.audioContext.currentTime,this.latestScheduledEndTime=this.audioContextStartTime;const t=++this.asyncId;this.paused||this.runIterator(t)}setVolume(e,t){this.volume=e,this.muted=t,this.updateGain()}setPlaybackRate(e){if(e!==this.playbackRate&&(this.paused||(this.playbackTimeAtStart=this.currentTime,this.audioContextStartTime=this.audioContext.currentTime),this.playbackRate=e,!this.paused)){const e=++this.asyncId;this.runIterator(e)}}destroy(){this.asyncId++,this.pause(),this.audioContext?.close(),this.audioContext=null,this.input=null,this.audioSink=null}}class Sa{constructor({canvas:e,ctx:t,events:r,timeupdateInterval:i=250,avSyncTolerance:a=.12,dropLateFrames:s=!1,poster:n="",preflightRange:o=!1}){this.canvas=e,this.ctx=t,this.events=r,this.timeupdateInterval=i,this.avSyncTolerance=a,this.dropLateFrames=s,this.poster=n,this.preflightRange=o,this.input=null,this.videoSink=null,this.videoIterator=null,this.nextFrame=null,this.rafId=0,this.asyncId=0,this.width=0,this.height=0,this.duration=Number.NaN,this.audioClock=null,this.lastTimeUpdate=0,this.stalled=!1,this.playbackRate=1,this.posterDrawn=!1,this.isFetching=!1}normalizeSource(e){return"string"===typeof e?new Gi(e):e instanceof Blob?new Ki(e):"undefined"!==typeof ReadableStream&&e instanceof ReadableStream?new Xi(e):e}async preflight(e){if(!this.preflightRange||"string"!==typeof e)return!0;try{const t=(await fetch(e,{method:"HEAD"})).headers.get("accept-ranges");return!(!t||"none"===t)||(this.events.emit("error",new Event("RangeNotSupported")),!1)}catch(t){return console.warn("Preflight check failed:",t),!0}}drawPoster(){if(!this.poster||this.posterDrawn)return;const e=new Image;e.onload=()=>{this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.canvas.width=e.naturalWidth||this.canvas.width,this.canvas.height=e.naturalHeight||this.canvas.height,this.ctx.drawImage(e,0,0,this.canvas.width,this.canvas.height),this.posterDrawn=!0},e.src=this.poster}async stopIterator(){await(this.videoIterator?.return()),this.videoIterator=null}clear(){this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height)}async load(e,t){const r=++this.asyncId;if(await this.stopIterator(),this.clear(),this.posterDrawn=!1,!(await this.preflight(e)))return;const i=this.normalizeSource(e);if(!i)return void this.drawPoster();if(this.input=new Zi({source:i,formats:Wi}),this.duration=await this.input.computeDuration(),r!==this.asyncId)return;const a=await this.input.getPrimaryVideoTrack();if(!a)return this.handleNoVideoTrack(),void t?.();if(null===a.codec||!(await a.canDecode()))return this.handleNoVideoTrack(),void t?.();const s=await a.canBeTransparent();this.videoSink=new _t(a,{poolSize:2,fit:"contain",alpha:s}),this.width=a.displayWidth,this.height=a.displayHeight,this.canvas.width=this.width,this.canvas.height=this.height,t?.(),await this.resetIterator(0)}handleNoVideoTrack(){this.videoSink=null,this.width=0,this.height=0,this.canvas.width=0,this.canvas.height=0,this.clear(),this.drawPoster()}async resetIterator(e){if(await this.stopIterator(),!this.videoSink)return;this.videoIterator=this.videoSink.canvases(e);const t=(await this.videoIterator.next()).value??null,r=(await this.videoIterator.next()).value??null;this.nextFrame=r,t?(this.ctx.drawImage(t.canvas,0,0),this.events.emit("loadeddata")):this.drawPoster()}async updateNextFrame(e){if(this.videoIterator&&!this.isFetching){this.isFetching=!0;try{for(;;){const t=(await this.videoIterator.next()).value??null;if(!t||e!==this.asyncId)return;const r=this.audioClock.currentTime,i=this.dropLateFrames?Math.max(.06,this.avSyncTolerance/Math.max(1,this.playbackRate)):0;if(!(this.dropLateFrames&&t.timestamp<r-i)){if(!(t.timestamp<=r+i))return void(this.nextFrame=t);if(this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.ctx.drawImage(t.canvas,0,0),!this.dropLateFrames&&t.timestamp>r)return void(this.nextFrame=null)}}}finally{this.isFetching=!1}}}render(){if(!this.audioClock)return;const e=this.audioClock.currentTime,t=Date.now();if(t-this.lastTimeUpdate>=this.timeupdateInterval&&(this.events.emit("timeupdate"),this.lastTimeUpdate=t),Number.isFinite(this.duration)&&e>=this.duration)return this.stop(),this.stalled=!1,this.events.emit("ended"),this.events.emit("pause"),void this.events.emit("canplay");this.nextFrame&&this.nextFrame.timestamp<=e?(this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.ctx.drawImage(this.nextFrame.canvas,0,0),this.nextFrame=null,this.updateNextFrame(this.asyncId),this.stalled&&(this.events.emit("canplay"),this.events.emit("playing"),this.stalled=!1)):this.nextFrame||(this.updateNextFrame(this.asyncId),!this.nextFrame&&Number.isFinite(this.duration)&&e<this.duration&&!this.stalled&&(this.stalled=!0,this.events.emit("waiting"))),this.rafId=requestAnimationFrame(()=>this.render())}start(e){this.audioClock=e,this.asyncId++,this.stalled=!1,this.updateNextFrame(this.asyncId),this.rafId=requestAnimationFrame(()=>this.render())}stop(){cancelAnimationFrame(this.rafId)}async seek(e){this.asyncId++,await this.resetIterator(e)}setPlaybackRate(e){this.playbackRate=Math.max(.1,Number(e)||1)}destroy(){this.asyncId++,this.stop(),this.stopIterator(),this.posterDrawn=!1,this.input=null,this.videoSink=null}}class Ia{constructor({canvas:e,ctx:t,events:r,option:i={}}){this.events=r,this.option=i,this.audio=new wa(r),this.video=new Sa({canvas:e,ctx:t,events:r,timeupdateInterval:i.timeupdateInterval??250,avSyncTolerance:i.avSyncTolerance??.12,dropLateFrames:i.dropLateFrames??!1,poster:i.poster??"",preflightRange:i.preflightRange??!1}),this.paused=!0,this.ended=!1,this.readyState=0,this.networkState=0,this.error=null,this.seeking=!1,this.loadSeq=0,r.addEventListener?.("ended",()=>{this.ended=!0,this.paused=!0})}async load(e){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{await 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")}}async performLoad(e,t){let r=!1,i=!1;const a=()=>{r&&i&&(this.readyState=1,this.events.emit("loadedmetadata"),this.events.emit("durationchange"),this.events.emit("progress"))};try{if(await Promise.all([this.video.load(e,()=>{t===this.loadSeq&&(r=!0,a())}),this.audio.load(e,()=>{t===this.loadSeq&&(i=!0,a())})]),t!==this.loadSeq)return;this.readyState=4,this.networkState=1,this.events.emit("loadeddata"),this.events.emit("canplay"),this.events.emit("canplaythrough"),this.events.emit("progress")}catch(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)})}async play(){this.paused&&(this.ended&&(this.ended=!1,await this.seek(0)),this.paused=!1,await this.audio.play(),this.video.start(this.audio),this.events.emit("play"),this.events.emit("playing"))}pause(){this.paused||(this.paused=!0,this.audio.pause(),this.video.stop(),this.events.emit("pause"))}async seek(e){const t=!this.paused;this.ended=!1,this.seeking=!0,this.events.emit("seeking"),this.events.emit("waiting"),this.pause(),await Promise.all([this.audio.seek(e),this.video.seek(e)]),this.seeking=!1,this.events.emit("seeked"),t&&!this.ended&&await this.play()}setVolume(e,t){this.audio.setVolume(e,t)}setPlaybackRate(e){this.audio.setPlaybackRate(e),this.video.setPlaybackRate(e)}destroy(){this.pause(),this.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 va{constructor({art:t,canvas:r,ctx:i,option:a}){this.art=t,this.canvas=r,this.option=a,this.events=new e,this.engine=new Ia({canvas:r,ctx:i,events:this.events,option:a}),this._src=null,this._volume=a.volume??.7,this._muted=!!a.muted,this._playbackRate=1,this.engine.setVolume(this._volume,this._muted),this.setupEventForwarding(),a.source?this.src=a.source:t.option?.url&&(this.src=t.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 Pa(e={}){return t=>{const{constructor:r}=t,{createElement:i}=r.utils,a=i("canvas"),s=a.getContext("2d"),n=new va({art:t,canvas:a,ctx:s,option:e}),o={};for(const e in a)"function"===typeof a[e]&&(o[e]=a[e].bind(a));const c=new Set([...Object.getOwnPropertyNames(n),...Object.getOwnPropertyNames(Object.getPrototypeOf(n))]);for(const e of c)"constructor"!==e&&(e in a||Object.defineProperty(a,e,{get(){const t=n[e];return"function"===typeof t?t.bind(n):t},set(t){n[e]=t},configurable:!0,enumerable:!0}));for(const e in o)a[e]=(...t)=>o[e](...t);function l(){const e=t.template?.$player;e&&!t.option.autoSize&&Object.assign(a.style,{width:"100%",height:"100%",objectFit:"contain"})}return t.on("resize",l),t.on("video:loadedmetadata",l),t.on("destroy",()=>{n.destroy()}),a}}return"undefined"!==typeof window&&(window.artplayerProxyMediabunny=Pa),Pa});
|