krono-flow 0.0.1 → 0.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/decoder.js +770 -324
- package/dist/decoder.js.map +1 -1
- package/dist/decoder.min.js +24 -24
- package/dist/decoder.min.js.map +1 -1
- package/dist/encoder.js +15824 -565
- package/dist/encoder.js.map +1 -1
- package/dist/encoder.min.js +168 -15
- package/dist/encoder.min.js.map +1 -1
- package/dist/index.js +10128 -1891
- package/dist/index.js.map +1 -1
- package/dist/index.min.js +35 -35
- package/dist/index.min.js.map +1 -1
- package/dist/index.mjs +46560 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +5 -6
package/dist/encoder.min.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).encoder={})}(this,function(e){"use strict";function t(e,t,i,r){return new(
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).encoder={})}(this,function(e){"use strict";var t=function(){return t=Object.assign||function(e){for(var t,r=1,a=arguments.length;r<a;r++)for(var i in t=arguments[r])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},t.apply(this,arguments)};function r(e,t,r,a){return new(r||(r=Promise))(function(i,s){function n(e){try{c(a.next(e))}catch(e){s(e)}}function o(e){try{c(a.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(n,o)}c((a=a.apply(e,t||[])).next())})}function a(e,t){var r,a,i,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},n=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return n.next=o(0),n.throw=o(1),n.return=o(2),"function"==typeof Symbol&&(n[Symbol.iterator]=function(){return this}),n;function o(o){return function(c){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;n&&(n=0,o[0]&&(s=0)),s;)try{if(r=1,a&&(i=2&o[0]?a.return:o[0]?a.throw||((i=a.return)&&i.call(a),0):a.next)&&!(i=i.call(a,o[1])).done)return i;switch(a=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,a=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]<i[3])){s.label=o[1];break}if(6===o[0]&&s.label<i[1]){s.label=i[1],i=o;break}if(i&&s.label<i[2]){s.label=i[2],s.ops.push(o);break}i[2]&&s.ops.pop(),s.trys.pop();continue}o=t.call(e,s)}catch(e){o=[6,e],a=0}finally{r=i=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,c])}}}function i(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],a=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&a>=e.length&&(e=void 0),{value:e&&e[a++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function s(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e=i(e),t={},a("next"),a("throw"),a("return"),t[Symbol.asyncIterator]=function(){return this},t);function a(r){t[r]=e[r]&&function(t){return new Promise(function(a,i){(function(e,t,r,a){Promise.resolve(a).then(function(t){e({value:t,done:r})},t)})(a,i,(t=e[r](t)).done,t.value)})}}}
|
|
2
2
|
/*!
|
|
3
3
|
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
4
4
|
*
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
7
7
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
8
8
|
*/
|
|
9
|
-
function
|
|
9
|
+
function n(e){if(!e)throw new Error("Assertion failed.")}"function"==typeof SuppressedError&&SuppressedError;const o=e=>{const t=(e%360+360)%360;if(0===t||90===t||180===t||270===t)return t;throw new Error(`Invalid rotation ${e}.`)},c=e=>e&&e[e.length-1],d=e=>e>=0&&e<2**32;class u{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),a=(t&1<<r)>>r;return this.pos++,a}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 e=this.pos;e<r;e++){const a=Math.floor(e/8);let i=this.bytes[a];const s=7-(7&e);i&=~(1<<s),i|=(t&1<<r-e-1)>>r-e-1<<s,this.bytes[a]=i}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 u(this.bytes);return e.pos=this.pos,e}}const l=e=>{let t=0;for(;0===e.readBits(1)&&t<32;)t++;if(t>=32)throw new Error("Invalid exponential-Golomb code.");return(1<<t)-1+e.readBits(t)},h=e=>{const t=l(e);return 1&t?t+1>>1:-(t>>1)},m=e=>e.constructor===Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),f=e=>e.constructor===DataView?e:ArrayBuffer.isView(e)?new DataView(e.buffer,e.byteOffset,e.byteLength):new DataView(e),p=new TextDecoder,g=new TextEncoder,k=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])),b={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},w=k(b),T={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},y=k(T),S={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},C=k(S),v=e=>!!(e&&e.primaries&&e.transfer&&e.matrix&&void 0!==e.fullRange),P=e=>e instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e);class I{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 x=e=>[...e].map(e=>e.toString(16).padStart(2,"0")).join(""),E=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,D=(e,t,r)=>{let a=0,i=e.length-1,s=-1;for(;a<=i;){const n=a+i>>1,o=r(e[n]);o===t?(s=n,i=n-1):o<t?a=n+1:i=n-1}return s},B=(e,t,r)=>{let a=0,i=e.length-1,s=-1;for(;a<=i;){const n=a+(i-a+1)/2|0;r(e[n])<=t?(s=n,a=n+1):i=n-1}return s},A=(e,t,r)=>{const a=B(e,r(t),r);e.splice(a+1,0,t)},_=()=>{let e,t;return{promise:new Promise((r,a)=>{e=r,t=a}),resolve:e,reject:t}},F=(e,t)=>{for(let r=e.length-1;r>=0;r--)if(t(e[r]))return e[r]},M=(e,t)=>{for(let r=e.length-1;r>=0;r--)if(t(e[r]))return r;return-1},R=e=>{throw new Error(`Unexpected value: ${e}`)},z=(e,t,r)=>{const a=e.getUint8(t),i=e.getUint8(t+1),s=e.getUint8(t+2);return r?a|i<<8|s<<16:a<<16|i<<8|s},O=(e,t,r,a)=>{r>>>=0,r&=16777215,e.setUint8(t,r>>>16&255),e.setUint8(t+1,r>>>8&255),e.setUint8(t+2,255&r)},N=(e,t,r)=>Math.max(t,Math.min(r,e)),L="und",U=e=>{const t=Math.round(e);return Math.abs(e/t-1)<10*Number.EPSILON?t:e},V=(e,t)=>Math.round(e/t)*t,W=/^[a-z]{3}$/,H=e=>W.test(e),q=1e6*(1+Number.EPSILON),j=(e,t)=>{const r={...e,...t};if(e.headers||t.headers){const a=e.headers?$(e.headers):{},i=t.headers?$(t.headers):{},s={...a};Object.entries(i).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},$=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},Q=async(e,t,r,a,i)=>{let s=0;for(;;)try{return await e(t,r)}catch(e){if(i())throw e;s++;const r=a(s,e,t);if(null===r)throw e;if(console.error("Retrying failed fetch. Error:",e),!Number.isFinite(r)||r<0)throw new TypeError("Retry delay must be a non-negative finite number.");if(r>0&&await new Promise(e=>setTimeout(e,1e3*r)),i())throw e}};class K{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}let G=null;const X=()=>null!==G?G:G=!("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 Y=null;let J=null;const Z=()=>null!==J?J:J=!("undefined"==typeof navigator||!navigator.vendor?.includes("Google Inc")&&!/Chrome/.test(navigator.userAgent));let ee=null;const te=(e,t)=>-1!==e?e:t,re=(e,t,r,a)=>e<=a&&r<=t,ae=function*(e){for(const t in e){const r=e[t];void 0!==r&&(yield{key:t,value:r})}},ie=e=>{switch(e.toLowerCase()){case"image/jpeg":case"image/jpg":return".jpg";case"image/png":return".png";case"image/gif":return".gif";case"image/webp":return".webp";case"image/bmp":return".bmp";case"image/svg+xml":return".svg";case"image/tiff":return".tiff";case"image/avif":return".avif";case"image/x-icon":case"image/vnd.microsoft.icon":return".ico";default:return null}},se=e=>{const t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r},ne=(e,t)=>{if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0},oe=()=>{Symbol.dispose??=Symbol("Symbol.dispose")},ce=e=>"number"==typeof e&&!Number.isNaN(e);
|
|
10
10
|
/*!
|
|
11
11
|
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
12
12
|
*
|
|
@@ -14,7 +14,7 @@ function r(e){if(!e)throw new Error("Assertion failed.")}"function"==typeof Supp
|
|
|
14
14
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
15
15
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
16
16
|
*/
|
|
17
|
-
class E{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 _{constructor(e,t,i,r){if(this.data=e,this.mimeType=t,this.name=i,this.description=r,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(void 0!==t&&"string"!=typeof t)throw new TypeError("mimeType, when provided, must be a string.");if(void 0!==i&&"string"!=typeof i)throw new TypeError("name, when provided, must be a string.");if(void 0!==r&&"string"!=typeof r)throw new TypeError("description, when provided, must be a string.")}}const B=["avc","hevc","vp9","av1","vp8"],A=["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"],M=["aac","opus","mp3","vorbis","flac"],x=[...M,...A],P=["webvtt"],I=e=>{const t=e.split(".");return[1,1,Number(t[1]),2,1,Number(t[2]),3,1,Number(t[3]),4,1,t[4]?Number(t[4]):1]},D=e=>{const t=e.split("."),i=Number(t[1]),r=t[2];return[129,(i<<5)+Number(r.slice(0,-1)),(("H"===r.slice(-1)?1:0)<<7)+((8===Number(t[3])?0:1)<<6)+0+((t[4]?Number(t[4]):0)<<4)+((t[5]?Number(t[5][0]):1)<<3)+((t[5]?Number(t[5][1]):1)<<2)+(t[5]?Number(t[5][2]):0),0]},V=/^pcm-([usf])(\d+)+(be)?$/,U=e=>{if(r(A.includes(e)),"ulaw"===e)return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if("alaw"===e)return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};const t=V.exec(e);let i;r(t),i="u"===t[1]?"unsigned":"s"===t[1]?"signed":"float";return{dataType:i,sampleSize:Number(t[2])/8,littleEndian:"be"!==t[3],silentValue:"pcm-u8"===e?128:0}},F=["avc1","avc3","hev1","hvc1","vp8","vp09","av01"],W=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,N=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,O=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,L=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,R=e=>{if(!e)throw new TypeError("Video chunk metadata must be provided.");if("object"!=typeof e)throw new TypeError("Video chunk metadata must be an object.");if(!e.decoderConfig)throw new TypeError("Video chunk metadata must include a decoder configuration.");if("object"!=typeof e.decoderConfig)throw new TypeError("Video chunk metadata decoder configuration must be an object.");if("string"!=typeof e.decoderConfig.codec)throw new TypeError("Video chunk metadata decoder configuration must specify a codec string.");if(!F.some(t=>e.decoderConfig.codec.startsWith(t)))throw new TypeError("Video chunk metadata decoder configuration codec string must be a valid video codec string as specified in the WebCodecs Codec Registry.");if(!Number.isInteger(e.decoderConfig.codedWidth)||e.decoderConfig.codedWidth<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).");if(!Number.isInteger(e.decoderConfig.codedHeight)||e.decoderConfig.codedHeight<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).");if(void 0!==e.decoderConfig.description&&!f(e.decoderConfig.description))throw new TypeError("Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(void 0!==e.decoderConfig.colorSpace){const{colorSpace:t}=e.decoderConfig;if("object"!=typeof t)throw new TypeError("Video chunk metadata decoder configuration colorSpace, when provided, must be an object.");const i=Object.keys(l);if(null!=t.primaries&&!i.includes(t.primaries))throw new TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${i.join(", ")}.`);const r=Object.keys(h);if(null!=t.transfer&&!r.includes(t.transfer))throw new TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${r.join(", ")}.`);const a=Object.keys(m);if(null!=t.matrix&&!a.includes(t.matrix))throw new TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${a.join(", ")}.`);if(null!=t.fullRange&&"boolean"!=typeof t.fullRange)throw new TypeError("Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean.")}if(e.decoderConfig.codec.startsWith("avc1")||e.decoderConfig.codec.startsWith("avc3")){if(!W.test(e.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for AVC must be a valid AVC codec string as specified in Section 3.4 of RFC 6381.")}else if(e.decoderConfig.codec.startsWith("hev1")||e.decoderConfig.codec.startsWith("hvc1")){if(!N.test(e.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for HEVC must be a valid HEVC codec string as specified in Section E.3 of ISO 14496-15.")}else if(e.decoderConfig.codec.startsWith("vp8")){if("vp8"!==e.decoderConfig.codec)throw new TypeError('Video chunk metadata decoder configuration codec string for VP8 must be "vp8".')}else if(e.decoderConfig.codec.startsWith("vp09")){if(!O.test(e.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for VP9 must be a valid VP9 codec string as specified in Section "Codecs Parameter String" of https://www.webmproject.org/vp9/mp4/.')}else if(e.decoderConfig.codec.startsWith("av01")&&!L.test(e.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for AV1 must be a valid AV1 codec string as specified in Section "Codecs Parameter String" of https://aomediacodec.github.io/av1-isobmff/.')},z=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm"],H=e=>{if(!e)throw new TypeError("Audio chunk metadata must be provided.");if("object"!=typeof e)throw new TypeError("Audio chunk metadata must be an object.");if(!e.decoderConfig)throw new TypeError("Audio chunk metadata must include a decoder configuration.");if("object"!=typeof e.decoderConfig)throw new TypeError("Audio chunk metadata decoder configuration must be an object.");if("string"!=typeof e.decoderConfig.codec)throw new TypeError("Audio chunk metadata decoder configuration must specify a codec string.");if(!z.some(t=>e.decoderConfig.codec.startsWith(t)))throw new TypeError("Audio chunk metadata decoder configuration codec string must be a valid audio codec string as specified in the WebCodecs Codec Registry.");if(!Number.isInteger(e.decoderConfig.sampleRate)||e.decoderConfig.sampleRate<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).");if(!Number.isInteger(e.decoderConfig.numberOfChannels)||e.decoderConfig.numberOfChannels<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).");if(void 0!==e.decoderConfig.description&&!f(e.decoderConfig.description))throw new TypeError("Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(e.decoderConfig.codec.startsWith("mp4a")&&"mp4a.69"!==e.decoderConfig.codec&&"mp4a.6B"!==e.decoderConfig.codec&&"mp4a.6b"!==e.decoderConfig.codec){if(!["mp4a.40.2","mp4a.40.02","mp4a.40.5","mp4a.40.05","mp4a.40.29","mp4a.67"].includes(e.decoderConfig.codec))throw new TypeError("Audio chunk metadata decoder configuration codec string for AAC must be a valid AAC codec string as specified in https://www.w3.org/TR/webcodecs-aac-codec-registration/.");if(!e.decoderConfig.description)throw new TypeError("Audio chunk metadata decoder configuration for AAC must include a description, which is expected to be an AudioSpecificConfig as specified in ISO 14496-3.")}else if(e.decoderConfig.codec.startsWith("mp3")||e.decoderConfig.codec.startsWith("mp4a")){if("mp3"!==e.decoderConfig.codec&&"mp4a.69"!==e.decoderConfig.codec&&"mp4a.6B"!==e.decoderConfig.codec&&"mp4a.6b"!==e.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for MP3 must be "mp3", "mp4a.69" or "mp4a.6B".')}else if(e.decoderConfig.codec.startsWith("opus")){if("opus"!==e.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for Opus must be "opus".');if(e.decoderConfig.description&&e.decoderConfig.description.byteLength<18)throw new TypeError("Audio chunk metadata decoder configuration description, when specified, is expected to be an Identification Header as specified in Section 5.1 of RFC 7845.")}else if(e.decoderConfig.codec.startsWith("vorbis")){if("vorbis"!==e.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".');if(!e.decoderConfig.description)throw new TypeError("Audio chunk metadata decoder configuration for Vorbis must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-vorbis-codec-registration/.")}else if(e.decoderConfig.codec.startsWith("flac")){if("flac"!==e.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for FLAC must be "flac".');const t=42;if(!e.decoderConfig.description||e.decoderConfig.description.byteLength<t)throw new TypeError("Audio chunk metadata decoder configuration for FLAC must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-flac-codec-registration/.")}else if((e.decoderConfig.codec.startsWith("pcm")||e.decoderConfig.codec.startsWith("ulaw")||e.decoderConfig.codec.startsWith("alaw"))&&!A.includes(e.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${A.join(", ")}).`)},j=e=>{if(!e)throw new TypeError("Subtitle metadata must be provided.");if("object"!=typeof e)throw new TypeError("Subtitle metadata must be an object.");if(!e.config)throw new TypeError("Subtitle metadata must include a config object.");if("object"!=typeof e.config)throw new TypeError("Subtitle metadata config must be an object.");if("string"!=typeof e.config.description)throw new TypeError("Subtitle metadata config description must be a string.")};
|
|
17
|
+
class de{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 ue{constructor(e,t,r,a){if(this.data=e,this.mimeType=t,this.name=r,this.description=a,!(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!==a&&"string"!=typeof a)throw new TypeError("description, when provided, must be a string.")}}const le={default:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1},he=["avc","hevc","vp9","av1","vp8"],me=["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"],fe=["aac","opus","mp3","vorbis","flac"],pe=[...fe,...me],ge=["webvtt"],ke=[{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}],be=".01.01.01.01.00",we=".0.110.01.01.01.0",Te=e=>{const t=e.split(".");return[1,1,Number(t[1]),2,1,Number(t[2]),3,1,Number(t[3]),4,1,t[4]?Number(t[4]):1]},ye=e=>{const t=e.split("."),r=Number(t[1]),a=t[2];return[129,(r<<5)+Number(a.slice(0,-1)),(("H"===a.slice(-1)?1:0)<<7)+((8===Number(t[3])?0:1)<<6)+0+((t[4]?Number(t[4]):0)<<4)+((t[5]?Number(t[5][0]):1)<<3)+((t[5]?Number(t[5][1]):1)<<2)+(t[5]?Number(t[5][2]):0),0]},Se=e=>{const{codec:t,codecDescription:r,colorSpace:a,avcCodecInfo:i,hevcCodecInfo:s,vp9CodecInfo:o,av1CodecInfo:d}=e;if("avc"===t){if(n(null!==e.avcType),i){const t=new Uint8Array([i.avcProfileIndication,i.profileCompatibility,i.avcLevelIndication]);return`avc${e.avcType}.${x(t)}`}if(!r||r.byteLength<4)throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${e.avcType}.${x(r.subarray(1,4))}`}if("hevc"===t){let e,t,a,i,n,o;if(s)e=s.generalProfileSpace,t=s.generalProfileIdc,a=E(s.generalProfileCompatibilityFlags),i=s.generalTierFlag,n=s.generalLevelIdc,o=[...s.generalConstraintIndicatorFlags];else{if(!r||r.byteLength<23)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");const s=f(r),c=s.getUint8(1);e=c>>6&3,t=31&c,a=E(s.getUint32(2)),i=c>>5&1,n=s.getUint8(12),o=[];for(let e=0;e<6;e++)o.push(s.getUint8(6+e))}let c="hev1.";for(c+=["","A","B","C"][e]+t,c+=".",c+=a.toString(16).toUpperCase(),c+=".",c+=0===i?"L":"H",c+=n;o.length>0&&0===o[o.length-1];)o.pop();return o.length>0&&(c+=".",c+=o.map(e=>e.toString(16).toUpperCase()).join(".")),c}if("vp8"===t)return"vp8";if("vp9"===t){if(!o){const t=e.width*e.height;let r=c(ke).level;for(const e of ke)if(t<=e.maxPictureSize){r=e.level;break}return`vp09.00.${r.toString().padStart(2,"0")}.08`}let t=`vp09.${o.profile.toString().padStart(2,"0")}.${o.level.toString().padStart(2,"0")}.${o.bitDepth.toString().padStart(2,"0")}.${o.chromaSubsampling.toString().padStart(2,"0")}`;return t+=`.${o.colourPrimaries.toString().padStart(2,"0")}.${o.transferCharacteristics.toString().padStart(2,"0")}.${o.matrixCoefficients.toString().padStart(2,"0")}.${o.videoFullRangeFlag.toString().padStart(2,"0")}`,t.endsWith(be)&&(t=t.slice(0,-15)),t}if("av1"===t){if(!d){const t=e.width*e.height;let r=c(ke).level;for(const e of ke)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"),i=d.tier?"H":"M",s=d.bitDepth.toString().padStart(2,"0"),n=d.monochrome?"1":"0",o=100*d.chromaSubsamplingX+10*d.chromaSubsamplingY+1*(d.chromaSubsamplingX&&d.chromaSubsamplingY?d.chromaSamplePosition:0),u=a?.primaries?b[a.primaries]:1,l=a?.transfer?T[a.transfer]:1,h=a?.matrix?S[a.matrix]:1,m=a?.fullRange?1:0;let f=`av01.${t}.${r}${i}.${s}`;return f+=`.${n}.${o.toString().padStart(3,"0")}`,f+=`.${u.toString().padStart(2,"0")}`,f+=`.${l.toString().padStart(2,"0")}`,f+=`.${h.toString().padStart(2,"0")}`,f+=`.${m}`,f.endsWith(we)&&(f=f.slice(0,-17)),f}throw new TypeError(`Unhandled codec '${t}'.`)},Ce=e=>{const{codec:t,codecDescription:r,aacCodecInfo:a}=e;if("aac"===t){if(!a)throw new TypeError("AAC codec info must be provided.");if(a.isMpeg2)return"mp4a.67";return`mp4a.40.${Ie(r).objectType}`}if("mp3"===t)return"mp3";if("opus"===t)return"opus";if("vorbis"===t)return"vorbis";if("flac"===t)return"flac";if(t&&me.includes(t))return t;throw new TypeError(`Unhandled codec '${t}'.`)},ve=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],Pe=[-1,1,2,3,4,5,6,8],Ie=e=>{if(!e||e.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");const t=new u(e);let r=t.readBits(5);31===r&&(r=32+t.readBits(6));const a=t.readBits(4);let i=null;15===a?i=t.readBits(24):a<ve.length&&(i=ve[a]);const s=t.readBits(4);let n=null;return s>=1&&s<=7&&(n=Pe[s]),{objectType:r,frequencyIndex:a,sampleRate:i,channelConfiguration:s,numberOfChannels:n}},xe=48e3,Ee=/^pcm-([usf])(\d+)+(be)?$/,De=e=>{if(n(me.includes(e)),"ulaw"===e)return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if("alaw"===e)return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};const t=Ee.exec(e);let r;n(t),r="u"===t[1]?"unsigned":"s"===t[1]?"signed":"float";return{dataType:r,sampleSize:Number(t[2])/8,littleEndian:"be"!==t[3],silentValue:"pcm-u8"===e?128:0}},Be=["avc1","avc3","hev1","hvc1","vp8","vp09","av01"],Ae=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,_e=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,Fe=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,Me=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,Re=e=>{if(!e)throw new TypeError("Video chunk metadata must be provided.");if("object"!=typeof e)throw new TypeError("Video chunk metadata must be an object.");if(!e.decoderConfig)throw new TypeError("Video chunk metadata must include a decoder configuration.");if("object"!=typeof e.decoderConfig)throw new TypeError("Video chunk metadata decoder configuration must be an object.");if("string"!=typeof e.decoderConfig.codec)throw new TypeError("Video chunk metadata decoder configuration must specify a codec string.");if(!Be.some(t=>e.decoderConfig.codec.startsWith(t)))throw new TypeError("Video chunk metadata decoder configuration codec string must be a valid video codec string as specified in the WebCodecs Codec Registry.");if(!Number.isInteger(e.decoderConfig.codedWidth)||e.decoderConfig.codedWidth<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).");if(!Number.isInteger(e.decoderConfig.codedHeight)||e.decoderConfig.codedHeight<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).");if(void 0!==e.decoderConfig.description&&!P(e.decoderConfig.description))throw new TypeError("Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(void 0!==e.decoderConfig.colorSpace){const{colorSpace:t}=e.decoderConfig;if("object"!=typeof t)throw new TypeError("Video chunk metadata decoder configuration colorSpace, when provided, must be an object.");const r=Object.keys(b);if(null!=t.primaries&&!r.includes(t.primaries))throw new TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${r.join(", ")}.`);const a=Object.keys(T);if(null!=t.transfer&&!a.includes(t.transfer))throw new TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${a.join(", ")}.`);const i=Object.keys(S);if(null!=t.matrix&&!i.includes(t.matrix))throw new TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${i.join(", ")}.`);if(null!=t.fullRange&&"boolean"!=typeof t.fullRange)throw new TypeError("Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean.")}if(e.decoderConfig.codec.startsWith("avc1")||e.decoderConfig.codec.startsWith("avc3")){if(!Ae.test(e.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for AVC must be a valid AVC codec string as specified in Section 3.4 of RFC 6381.")}else if(e.decoderConfig.codec.startsWith("hev1")||e.decoderConfig.codec.startsWith("hvc1")){if(!_e.test(e.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for HEVC must be a valid HEVC codec string as specified in Section E.3 of ISO 14496-15.")}else if(e.decoderConfig.codec.startsWith("vp8")){if("vp8"!==e.decoderConfig.codec)throw new TypeError('Video chunk metadata decoder configuration codec string for VP8 must be "vp8".')}else if(e.decoderConfig.codec.startsWith("vp09")){if(!Fe.test(e.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for VP9 must be a valid VP9 codec string as specified in Section "Codecs Parameter String" of https://www.webmproject.org/vp9/mp4/.')}else if(e.decoderConfig.codec.startsWith("av01")&&!Me.test(e.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for AV1 must be a valid AV1 codec string as specified in Section "Codecs Parameter String" of https://aomediacodec.github.io/av1-isobmff/.')},ze=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm"],Oe=e=>{if(!e)throw new TypeError("Audio chunk metadata must be provided.");if("object"!=typeof e)throw new TypeError("Audio chunk metadata must be an object.");if(!e.decoderConfig)throw new TypeError("Audio chunk metadata must include a decoder configuration.");if("object"!=typeof e.decoderConfig)throw new TypeError("Audio chunk metadata decoder configuration must be an object.");if("string"!=typeof e.decoderConfig.codec)throw new TypeError("Audio chunk metadata decoder configuration must specify a codec string.");if(!ze.some(t=>e.decoderConfig.codec.startsWith(t)))throw new TypeError("Audio chunk metadata decoder configuration codec string must be a valid audio codec string as specified in the WebCodecs Codec Registry.");if(!Number.isInteger(e.decoderConfig.sampleRate)||e.decoderConfig.sampleRate<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).");if(!Number.isInteger(e.decoderConfig.numberOfChannels)||e.decoderConfig.numberOfChannels<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).");if(void 0!==e.decoderConfig.description&&!P(e.decoderConfig.description))throw new TypeError("Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(e.decoderConfig.codec.startsWith("mp4a")&&"mp4a.69"!==e.decoderConfig.codec&&"mp4a.6B"!==e.decoderConfig.codec&&"mp4a.6b"!==e.decoderConfig.codec){if(!["mp4a.40.2","mp4a.40.02","mp4a.40.5","mp4a.40.05","mp4a.40.29","mp4a.67"].includes(e.decoderConfig.codec))throw new TypeError("Audio chunk metadata decoder configuration codec string for AAC must be a valid AAC codec string as specified in https://www.w3.org/TR/webcodecs-aac-codec-registration/.");if(!e.decoderConfig.description)throw new TypeError("Audio chunk metadata decoder configuration for AAC must include a description, which is expected to be an AudioSpecificConfig as specified in ISO 14496-3.")}else if(e.decoderConfig.codec.startsWith("mp3")||e.decoderConfig.codec.startsWith("mp4a")){if("mp3"!==e.decoderConfig.codec&&"mp4a.69"!==e.decoderConfig.codec&&"mp4a.6B"!==e.decoderConfig.codec&&"mp4a.6b"!==e.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for MP3 must be "mp3", "mp4a.69" or "mp4a.6B".')}else if(e.decoderConfig.codec.startsWith("opus")){if("opus"!==e.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for Opus must be "opus".');if(e.decoderConfig.description&&e.decoderConfig.description.byteLength<18)throw new TypeError("Audio chunk metadata decoder configuration description, when specified, is expected to be an Identification Header as specified in Section 5.1 of RFC 7845.")}else if(e.decoderConfig.codec.startsWith("vorbis")){if("vorbis"!==e.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".');if(!e.decoderConfig.description)throw new TypeError("Audio chunk metadata decoder configuration for Vorbis must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-vorbis-codec-registration/.")}else if(e.decoderConfig.codec.startsWith("flac")){if("flac"!==e.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for FLAC must be "flac".');const t=42;if(!e.decoderConfig.description||e.decoderConfig.description.byteLength<t)throw new TypeError("Audio chunk metadata decoder configuration for FLAC must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-flac-codec-registration/.")}else if((e.decoderConfig.codec.startsWith("pcm")||e.decoderConfig.codec.startsWith("ulaw")||e.decoderConfig.codec.startsWith("alaw"))&&!me.includes(e.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${me.join(", ")}).`)},Ne=e=>{if(!e)throw new TypeError("Subtitle metadata must be provided.");if("object"!=typeof e)throw new TypeError("Subtitle metadata must be an object.");if(!e.config)throw new TypeError("Subtitle metadata must include a config object.");if("object"!=typeof e.config)throw new TypeError("Subtitle metadata config must be an object.");if("string"!=typeof e.config.description)throw new TypeError("Subtitle metadata config description must be a string.")};
|
|
18
18
|
/*!
|
|
19
19
|
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
20
20
|
*
|
|
@@ -22,14 +22,35 @@ class E{constructor(e,t){if(this.data=e,this.mimeType=t,!(e instanceof Uint8Arra
|
|
|
22
22
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
23
23
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
24
24
|
*/
|
|
25
|
-
class
|
|
25
|
+
class Le{constructor(e){this.mutex=new I,this.firstMediaStreamTimestamp=null,this.trackTimestampInfo=new WeakMap,this.output=e}onTrackClose(e){}validateAndNormalizeTimestamp(e,t,r){t+=e.source._timestampOffset;let a=this.trackTimestampInfo.get(e);if(!a){if(!r)throw new Error("First packet must be a key packet.");a={maxTimestamp:t,maxTimestampBeforeLastKeyPacket:t},this.trackTimestampInfo.set(e,a)}if(t<0)throw new Error(`Timestamps must be non-negative (got ${t}s).`);if(r&&(a.maxTimestampBeforeLastKeyPacket=a.maxTimestamp),t<a.maxTimestampBeforeLastKeyPacket)throw new Error(`Timestamps cannot be smaller than the largest timestamp of the previous GOP (a GOP begins with a key packet and ends right before the next key packet). Got ${t}s, but largest timestamp is ${a.maxTimestampBeforeLastKeyPacket}s.`);return a.maxTimestamp=Math.max(a.maxTimestamp,t),t}}
|
|
26
26
|
/*!
|
|
27
27
|
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
28
28
|
*
|
|
29
29
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
30
30
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
31
31
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
32
|
-
*/var Q,q;!function(e){e[e.IDR=5]="IDR",e[e.SPS=7]="SPS",e[e.PPS=8]="PPS",e[e.SPS_EXT=13]="SPS_EXT"}(Q||(Q={})),function(e){e[e.RASL_N=8]="RASL_N",e[e.RASL_R=9]="RASL_R",e[e.BLA_W_LP=16]="BLA_W_LP",e[e.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",e[e.VPS_NUT=32]="VPS_NUT",e[e.SPS_NUT=33]="SPS_NUT",e[e.PPS_NUT=34]="PPS_NUT",e[e.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",e[e.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"}(q||(q={}));const K=e=>{const t=[];let i=0;for(;i<e.length;){let r=-1,a=0;for(let t=i;t<e.length-3;t++){if(0===e[t]&&0===e[t+1]&&1===e[t+2]){r=t,a=3;break}if(t<e.length-4&&0===e[t]&&0===e[t+1]&&0===e[t+2]&&1===e[t+3]){r=t,a=4;break}}if(-1===r)break;if(i>0&&r>i){const a=e.subarray(i,r);a.length>0&&t.push(a)}i=r+a}if(i<e.length){const r=e.subarray(i);r.length>0&&t.push(r)}return t},G=e=>{const t=[],i=e.length;for(let r=0;r<i;r++)r+2<i&&0===e[r]&&0===e[r+1]&&3===e[r+2]?(t.push(0,0),r+=2):t.push(e[r]);return new Uint8Array(t)},X=e=>31&e[0],Y=e=>{try{const t=new o(G(e));t.skipBits(1),t.skipBits(2);if(7!==t.readBits(5))return null;const i=t.readAlignedByte(),r=t.readAlignedByte(),a=t.readAlignedByte();n(t);let s=null,d=null,u=null;if(100===i||110===i||122===i||244===i||44===i||83===i||86===i||118===i||128===i){s=n(t),3===s&&t.skipBits(1),d=n(t),u=n(t),t.skipBits(1);if(t.readBits(1))for(let e=0;e<(3!==s?8:12);e++){if(t.readBits(1)){const i=e<6?16:64;let r=8,a=8;for(let e=0;e<i;e++){if(0!==a){a=(r+c(t)+256)%256}r=0===a?r:a}}}}n(t);const l=n(t);if(0===l)n(t);else if(1===l){t.skipBits(1),c(t),c(t);const e=n(t);for(let i=0;i<e;i++)c(t)}n(t),t.skipBits(1),n(t),n(t);return{profileIdc:i,constraintFlags:r,levelIdc:a,frameMbsOnlyFlag:t.readBits(1),chromaFormatIdc:s,bitDepthLumaMinus8:d,bitDepthChromaMinus8:u}}catch(e){return console.error("Error parsing AVC SPS:",e),null}},J=e=>e[0]>>1&63,Z=(e,t)=>{const i=e.readBits(2),r=e.readBits(1),a=e.readBits(5);let s=0;for(let t=0;t<32;t++)s=s<<1|e.readBits(1);const o=new Uint8Array(6);for(let t=0;t<6;t++)o[t]=e.readBits(8);const n=e.readBits(8),c=[],d=[];for(let i=0;i<t;i++)c.push(e.readBits(1)),d.push(e.readBits(1));if(t>0)for(let i=t;i<8;i++)e.skipBits(2);for(let i=0;i<t;i++)c[i]&&e.skipBits(88),d[i]&&e.skipBits(8);return{general_profile_space:i,general_tier_flag:r,general_profile_idc:a,general_profile_compatibility_flags:s,general_constraint_indicator_flags:o,general_level_idc:n}},ee=e=>{for(let t=0;t<4;t++)for(let i=0;i<(3===t?2:6);i++){if(e.readBits(1)){const i=Math.min(64,1<<4+(t<<1));t>1&&c(e);for(let t=0;t<i;t++)c(e)}else n(e)}},te=(e,t)=>{const i=[];for(let r=0;r<t;r++)i[r]=ie(e,r,t,i)},ie=(e,t,i,r)=>{let a=0,s=0,o=0;if(0!==t&&(s=e.readBits(1)),s){if(t===i){o=t-(n(e)+1)}else o=t-1;e.readBits(1),n(e);const s=r[o]??0;for(let t=0;t<=s;t++){e.readBits(1)||e.readBits(1)}a=r[o]}else{const t=n(e),i=n(e);for(let i=0;i<t;i++)n(e),e.readBits(1);for(let t=0;t<i;t++)n(e),e.readBits(1);a=t+i}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)&&(n(e),n(e)),e.readBits(1),e.readBits(1),e.readBits(1),e.readBits(1)&&(n(e),n(e),n(e),n(e)),e.readBits(1)&&(e.readBits(32),e.readBits(32),e.readBits(1)&&n(e),e.readBits(1)&&ae(e,!0,t)),e.readBits(1)){e.readBits(1),e.readBits(1),e.readBits(1);const t=n(e);return n(e),n(e),n(e),n(e),t}return 0},ae=(e,t,i)=>{let r=!1,a=!1,s=!1;r=1===e.readBits(1),a=1===e.readBits(1),(r||a)&&(s=1===e.readBits(1),s&&(e.readBits(8),e.readBits(5),e.readBits(1),e.readBits(5)),e.readBits(4),e.readBits(4),s&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5));for(let t=0;t<=i;t++){let t=!0;1===e.readBits(1)||(t=1===e.readBits(1));let i=!1;t?n(e):i=1===e.readBits(1);let o=1;if(!i){o=n(e)+1}r&&se(e,o,s),a&&se(e,o,s)}},se=(e,t,i)=>{for(let r=0;r<t;r++)n(e),n(e),i&&(n(e),n(e)),e.readBits(1)},oe=e=>{const t=(i=e).constructor===DataView?i:i instanceof ArrayBuffer?new DataView(i):new DataView(i.buffer,i.byteOffset,i.byteLength);var i;const r=t.getUint8(9),a=t.getUint16(10,!0),s=t.getUint32(12,!0),o=t.getInt16(16,!0),n=t.getUint8(18);let c=null;return n&&(c=e.subarray(19,21+r)),{outputChannelCount:r,preSkip:a,inputSampleRate:s,outputGain:o,channelMappingFamily:n,channelMappingTable:c}};var ne;!function(e){e[e.STREAMINFO=0]="STREAMINFO",e[e.VORBIS_COMMENT=4]="VORBIS_COMMENT",e[e.PICTURE=6]="PICTURE"}(ne||(ne={}));
|
|
32
|
+
*/var Ue,Ve;!function(e){e[e.IDR=5]="IDR",e[e.SEI=6]="SEI",e[e.SPS=7]="SPS",e[e.PPS=8]="PPS",e[e.SPS_EXT=13]="SPS_EXT"}(Ue||(Ue={})),function(e){e[e.RASL_N=8]="RASL_N",e[e.RASL_R=9]="RASL_R",e[e.BLA_W_LP=16]="BLA_W_LP",e[e.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",e[e.VPS_NUT=32]="VPS_NUT",e[e.SPS_NUT=33]="SPS_NUT",e[e.PPS_NUT=34]="PPS_NUT",e[e.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",e[e.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"}(Ve||(Ve={}));const We=e=>{const t=[];let r=0;for(;r<e.length;){let a=-1,i=0;for(let t=r;t<e.length-3;t++){if(0===e[t]&&0===e[t+1]&&1===e[t+2]){a=t,i=3;break}if(t<e.length-4&&0===e[t]&&0===e[t+1]&&0===e[t+2]&&1===e[t+3]){a=t,i=4;break}}if(-1===a)break;if(r>0&&a>r){const i=e.subarray(r,a);i.length>0&&t.push(i)}r=a+i}if(r<e.length){const a=e.subarray(r);a.length>0&&t.push(a)}return t},He=(e,t)=>{const r=[];let a=0;const i=new DataView(e.buffer,e.byteOffset,e.byteLength);for(;a+t<=e.length;){let s;1===t?s=i.getUint8(a):2===t?s=i.getUint16(a,!1):3===t?s=z(i,a,!1):4===t?s=i.getUint32(a,!1):(R(t),n(!1)),a+=t;const o=e.subarray(a,a+s);r.push(o),a+=s}return r},qe=e=>{const t=[],r=e.length;for(let a=0;a<r;a++)a+2<r&&0===e[a]&&0===e[a+1]&&3===e[a+2]?(t.push(0,0),a+=2):t.push(e[a]);return new Uint8Array(t)},je=new Uint8Array([0,0,0,1]),$e=(e,t)=>{const r=e.reduce((e,r)=>e+t+r.byteLength,0),a=new Uint8Array(r);let i=0;for(const r of e){const e=new DataView(a.buffer,a.byteOffset,a.byteLength);switch(t){case 1:e.setUint8(i,r.byteLength);break;case 2:e.setUint16(i,r.byteLength,!1);break;case 3:O(e,i,r.byteLength);break;case 4:e.setUint32(i,r.byteLength,!1)}i+=t,a.set(r,i),i+=r.byteLength}return a},Qe=(e,t)=>{if(t.description){const r=3&m(t.description)[4];return He(e,r+1)}return We(e)},Ke=(e,t)=>{if(t.description){const r=3&m(t.description)[4];return $e(e,r+1)}return(e=>{const t=e.reduce((e,t)=>e+je.byteLength+t.byteLength,0),r=new Uint8Array(t);let a=0;for(const t of e)r.set(je,a),a+=je.byteLength,r.set(t,a),a+=t.byteLength;return r})(e)},Ge=e=>31&e[0],Xe=e=>{try{const t=We(e),r=t.filter(e=>Ge(e)===Ue.SPS),a=t.filter(e=>Ge(e)===Ue.PPS),i=t.filter(e=>Ge(e)===Ue.SPS_EXT);if(0===r.length)return null;if(0===a.length)return null;const s=r[0],o=Ye(s);n(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:r,pictureParameterSets:a,chromaFormat:c?o.chromaFormatIdc:null,bitDepthLumaMinus8:c?o.bitDepthLumaMinus8:null,bitDepthChromaMinus8:c?o.bitDepthChromaMinus8:null,sequenceParameterSetExt:c?i:null}}catch(e){return console.error("Error building AVC Decoder Configuration Record:",e),null}},Ye=e=>{try{const t=new u(qe(e));t.skipBits(1),t.skipBits(2);if(7!==t.readBits(5))return null;const r=t.readAlignedByte(),a=t.readAlignedByte(),i=t.readAlignedByte();l(t);let s=null,n=null,o=null;if(100===r||110===r||122===r||244===r||44===r||83===r||86===r||118===r||128===r){s=l(t),3===s&&t.skipBits(1),n=l(t),o=l(t),t.skipBits(1);if(t.readBits(1))for(let e=0;e<(3!==s?8:12);e++){if(t.readBits(1)){const r=e<6?16:64;let a=8,i=8;for(let e=0;e<r;e++){if(0!==i){i=(a+h(t)+256)%256}a=0===i?a:i}}}}l(t);const c=l(t);if(0===c)l(t);else if(1===c){t.skipBits(1),h(t),h(t);const e=l(t);for(let r=0;r<e;r++)h(t)}l(t),t.skipBits(1),l(t),l(t);return{profileIdc:r,constraintFlags:a,levelIdc:i,frameMbsOnlyFlag:t.readBits(1),chromaFormatIdc:s,bitDepthLumaMinus8:n,bitDepthChromaMinus8:o}}catch(e){return console.error("Error parsing AVC SPS:",e),null}},Je=(e,t)=>{if(t.description){const r=3&m(t.description)[21];return He(e,r+1)}return We(e)},Ze=e=>e[0]>>1&63,et=e=>{try{const t=We(e),r=t.filter(e=>Ze(e)===Ve.VPS_NUT),a=t.filter(e=>Ze(e)===Ve.SPS_NUT),i=t.filter(e=>Ze(e)===Ve.PPS_NUT),s=t.filter(e=>Ze(e)===Ve.PREFIX_SEI_NUT||Ze(e)===Ve.SUFFIX_SEI_NUT);if(0===a.length||0===i.length)return null;const n=a[0],o=new u(qe(n));o.skipBits(16),o.readBits(4);const c=o.readBits(3),d=o.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}=tt(o,c);l(o);const w=l(o);3===w&&o.skipBits(1),l(o),l(o),o.readBits(1)&&(l(o),l(o),l(o),l(o));const T=l(o),y=l(o);l(o);const S=o.readBits(1);for(let e=S?0:c;e<=c;e++)l(o),l(o),l(o);l(o),l(o),l(o),l(o),l(o),l(o),o.readBits(1)&&o.readBits(1)&&rt(o),o.skipBits(1),o.skipBits(1),o.readBits(1)&&(o.skipBits(4),o.skipBits(4),l(o),l(o),o.skipBits(1));const C=l(o);if(at(o,C),o.readBits(1)){const e=l(o);for(let t=0;t<e;t++)l(o),o.skipBits(1)}o.skipBits(1),o.skipBits(1);let v=0;o.readBits(1)&&(v=st(o,c));let P=0;if(i.length>0){const e=i[0],t=new u(qe(e));t.skipBits(16),l(t),l(t),t.skipBits(1),t.skipBits(1),t.skipBits(3),t.skipBits(1),t.skipBits(1),l(t),l(t),h(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&l(t),h(t),h(t),t.skipBits(1),t.skipBits(1),t.skipBits(1),t.skipBits(1);const r=t.readBits(1),a=t.readBits(1);P=r||a?r&&!a?2:!r&&a?3:0:0}const I=[...r.length?[{arrayCompleteness:1,nalUnitType:Ve.VPS_NUT,nalUnits:r}]:[],...a.length?[{arrayCompleteness:1,nalUnitType:Ve.SPS_NUT,nalUnits:a}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:Ve.PPS_NUT,nalUnits:i}]:[],...s.length?[{arrayCompleteness:1,nalUnitType:Ze(s[0]),nalUnits:s}]:[]];return{configurationVersion:1,generalProfileSpace:m,generalTierFlag:f,generalProfileIdc:p,generalProfileCompatibilityFlags:g,generalConstraintIndicatorFlags:k,generalLevelIdc:b,minSpatialSegmentationIdc:v,parallelismType:P,chromaFormatIdc:w,bitDepthLumaMinus8:T,bitDepthChromaMinus8:y,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:c+1,temporalIdNested:d,lengthSizeMinusOne:3,arrays:I}}catch(e){return console.error("Error building HEVC Decoder Configuration Record:",e),null}},tt=(e,t)=>{const r=e.readBits(2),a=e.readBits(1),i=e.readBits(5);let s=0;for(let t=0;t<32;t++)s=s<<1|e.readBits(1);const n=new Uint8Array(6);for(let t=0;t<6;t++)n[t]=e.readBits(8);const o=e.readBits(8),c=[],d=[];for(let r=0;r<t;r++)c.push(e.readBits(1)),d.push(e.readBits(1));if(t>0)for(let r=t;r<8;r++)e.skipBits(2);for(let r=0;r<t;r++)c[r]&&e.skipBits(88),d[r]&&e.skipBits(8);return{general_profile_space:r,general_tier_flag:a,general_profile_idc:i,general_profile_compatibility_flags:s,general_constraint_indicator_flags:n,general_level_idc:o}},rt=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&&h(e);for(let t=0;t<r;t++)h(e)}else l(e)}},at=(e,t)=>{const r=[];for(let a=0;a<t;a++)r[a]=it(e,a,t,r)},it=(e,t,r,a)=>{let i=0,s=0,n=0;if(0!==t&&(s=e.readBits(1)),s){if(t===r){n=t-(l(e)+1)}else n=t-1;e.readBits(1),l(e);const s=a[n]??0;for(let t=0;t<=s;t++){e.readBits(1)||e.readBits(1)}i=a[n]}else{const t=l(e),r=l(e);for(let r=0;r<t;r++)l(e),e.readBits(1);for(let t=0;t<r;t++)l(e),e.readBits(1);i=t+r}return i},st=(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)&&(l(e),l(e)),e.readBits(1),e.readBits(1),e.readBits(1),e.readBits(1)&&(l(e),l(e),l(e),l(e)),e.readBits(1)&&(e.readBits(32),e.readBits(32),e.readBits(1)&&l(e),e.readBits(1)&&nt(e,!0,t)),e.readBits(1)){e.readBits(1),e.readBits(1),e.readBits(1);const t=l(e);return l(e),l(e),l(e),l(e),t}return 0},nt=(e,t,r)=>{let a=!1,i=!1,s=!1;a=1===e.readBits(1),i=1===e.readBits(1),(a||i)&&(s=1===e.readBits(1),s&&(e.readBits(8),e.readBits(5),e.readBits(1),e.readBits(5)),e.readBits(4),e.readBits(4),s&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5));for(let t=0;t<=r;t++){let t=!0;1===e.readBits(1)||(t=1===e.readBits(1));let r=!1;t?l(e):r=1===e.readBits(1);let n=1;if(!r){n=l(e)+1}a&&ot(e,n,s),i&&ot(e,n,s)}},ot=(e,t,r)=>{for(let a=0;a<t;a++)l(e),l(e),r&&(l(e),l(e)),e.readBits(1)},ct=e=>{const t=new u(e);if(2!==t.readBits(2))return null;const r=t.readBits(1),a=(t.readBits(1)<<1)+r;3===a&&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 i=8;if(a>=2){i=t.readBits(1)?12:10}const s=t.readBits(3);let n=0,o=0;if(7!==s){if(o=t.readBits(1),1===a||3===a){const e=t.readBits(1),r=t.readBits(1);n=e||r?e&&!r?2:1:3,t.skipBits(1)}else n=1}else n=3,o=1;const d=(t.readBits(16)+1)*(t.readBits(16)+1);let l=c(ke).level;for(const e of ke)if(d<=e.maxPictureSize){l=e.level;break}return{profile:a,level:l,bitDepth:i,chromaSubsampling:n,videoFullRangeFlag:o,colourPrimaries:2===s?1:1===s?6:2,transferCharacteristics:2===s?1:1===s?6:2,matrixCoefficients:7===s?0:2===s?1:1===s?6:2}},dt=function*(e){const t=new u(e),r=()=>{let e=0;for(let r=0;r<8;r++){const a=t.readAlignedByte();if(e|=(127&a)<<7*r,!(128&a))break;if(7===r&&128&a)return null}return e>=2**32-1?null:e};for(;t.getBitsLeft()>=8;){t.skipBits(1);const a=t.readBits(4),i=t.readBits(1),s=t.readBits(1);let o;if(t.skipBits(1),i&&t.skipBits(8),s){const e=r();if(null===e)return;o=e}else o=Math.floor(t.getBitsLeft()/8);n(t.pos%8==0),yield{type:a,data:e.subarray(t.pos/8,t.pos/8+o)},t.skipBits(8*o)}},ut=e=>{for(const{type:t,data:r}of dt(e)){if(1!==t)continue;const e=new u(r),a=e.readBits(3);e.readBits(1);const i=e.readBits(1);let s=0,n=0,o=0;if(i)s=e.readBits(5);else{if(e.readBits(1)){e.skipBits(32),e.skipBits(32);if(e.readBits(1))return null}const t=e.readBits(1);t&&(o=e.readBits(5),e.skipBits(32),e.skipBits(5),e.skipBits(5));const r=e.readBits(5);for(let a=0;a<=r;a++){e.skipBits(12);const r=e.readBits(5);if(0===a&&(s=r),r>7){const t=e.readBits(1);0===a&&(n=t)}if(t){if(e.readBits(1)){const t=o+1;e.skipBits(t),e.skipBits(t),e.skipBits(1)}}e.readBits(1)&&e.skipBits(4)}}const c=e.readBits(4),d=e.readBits(4),l=c+1;e.skipBits(l);const h=d+1;e.skipBits(h);let m=0;if(m=i?0:e.readBits(1),m&&(e.skipBits(4),e.skipBits(3)),e.skipBits(1),e.skipBits(1),e.skipBits(1),!i){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===a&&f){p=e.readBits(1)?12:10}else a<=2&&(p=f?10:8);let g=0;1!==a&&(g=e.readBits(1));let k=1,b=1,w=0;return g||(0===a?(k=1,b=1):1===a?(k=0,b=0):12===p&&(k=e.readBits(1),k&&(b=e.readBits(1))),k&&b&&(w=e.readBits(2))),{profile:a,level:s,tier:n,bitDepth:p,monochrome:g,chromaSubsamplingX:k,chromaSubsamplingY:b,chromaSamplePosition:w}}return null},lt=e=>{const t=f(e),r=t.getUint8(9),a=t.getUint16(10,!0),i=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:a,inputSampleRate:i,outputGain:s,channelMappingFamily:n,channelMappingTable:o}},ht=[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],mt=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 a=new u(r);let i=0;for(;a.getBitsLeft()>97;)if(1===a.readBits(1)){i=a.pos;break}if(0===i)throw new Error("Invalid Setup header: framing bit not found.");let s=0,n=!1,o=0;for(;a.getBitsLeft()>=97;){const e=a.pos,t=a.readBits(8),r=a.readBits(16),i=a.readBits(16);if(t>63||0!==r||0!==i){a.pos=e;break}if(a.skipBits(1),s++,s>64)break;a.clone().readBits(6)+1===s&&(n=!0,o=s)}if(!n)throw new Error("Invalid Setup header: mode header not found.");if(o>63)throw new Error(`Unsupported mode count: ${o}.`);const c=o;a.pos=0,a.skipBits(i);const d=Array(c).fill(0);for(let e=c-1;e>=0;e--)a.skipBits(40),d[e]=a.readBits(1);return{modeBlockflags:d}},ft=(e,t,r)=>{switch(e){case"avc":{const e=Qe(r,t);let a=e.some(e=>Ge(e)===Ue.IDR);if(!a&&(!Z()||(()=>{if(null!==ee)return ee;if("undefined"==typeof navigator)return null;const e=/\bChrome\/(\d+)/.exec(navigator.userAgent);return e?ee=Number(e[1]):null})()>=144))for(const t of e){if(Ge(t)!==Ue.SEI)continue;const e=qe(t);let r=1;do{let t=0;for(;;){const a=e[r++];if(void 0===a)break;if(t+=a,a<255)break}let i=0;for(;;){const t=e[r++];if(void 0===t)break;if(i+=t,t<255)break}if(t===6){const t=new u(e);t.pos=8*r;const i=l(t),s=t.readBits(1);if(0===i&&1===s){a=!0;break}}r+=i}while(r<e.length-1)}return a?"key":"delta"}case"hevc":return Je(r,t).some(e=>{const t=Ze(e);return Ve.BLA_W_LP<=t&&t<=Ve.RSV_IRAP_VCL23})?"key":"delta";case"vp8":return 0===(1&r[0])?"key":"delta";case"vp9":{const e=new u(r);if(2!==e.readBits(2))return null;const t=e.readBits(1);3===(e.readBits(1)<<1)+t&&e.skipBits(1);if(e.readBits(1))return null;return 0===e.readBits(1)?"key":"delta"}case"av1":{let e=!1;for(const{type:t,data:a}of dt(r))if(1===t){const t=new u(a);t.skipBits(4),e=!!t.readBits(1)}else if(3===t||6===t||7===t){if(e)return"key";const t=new u(a);if(t.readBits(1))return null;return 0===t.readBits(2)?"key":"delta"}return null}default:R(e),n(!1)}};var pt;!function(e){e[e.STREAMINFO=0]="STREAMINFO",e[e.VORBIS_COMMENT=4]="VORBIS_COMMENT",e[e.PICTURE=6]="PICTURE"}(pt||(pt={}));const gt=(e,t)=>{const r=f(e);let a=0;const i=r.getUint32(a,!0);a+=4;const s=p.decode(e.subarray(a,a+i));a+=i,i>0&&(t.raw??={},t.raw.vendor??=s);const n=r.getUint32(a,!0);a+=4;for(let i=0;i<n;i++){const i=r.getUint32(a,!0);a+=4;const s=p.decode(e.subarray(a,a+i));a+=i;const n=s.indexOf("=");if(-1===n)continue;const o=s.slice(0,n).toUpperCase(),c=s.slice(n+1);switch(t.raw??={},t.raw[o]??=c,o){case"TITLE":t.title??=c;break;case"DESCRIPTION":t.description??=c;break;case"ARTIST":t.artist??=c;break;case"ALBUM":t.album??=c;break;case"ALBUMARTIST":t.albumArtist??=c;break;case"COMMENT":t.comment??=c;break;case"LYRICS":t.lyrics??=c;break;case"TRACKNUMBER":{const e=c.split("/"),r=Number.parseInt(e[0],10),a=e[1]&&Number.parseInt(e[1],10);Number.isInteger(r)&&r>0&&(t.trackNumber??=r),a&&Number.isInteger(a)&&a>0&&(t.tracksTotal??=a)}break;case"TRACKTOTAL":{const e=Number.parseInt(c,10);Number.isInteger(e)&&e>0&&(t.tracksTotal??=e)}break;case"DISCNUMBER":{const e=c.split("/"),r=Number.parseInt(e[0],10),a=e[1]&&Number.parseInt(e[1],10);Number.isInteger(r)&&r>0&&(t.discNumber??=r),a&&Number.isInteger(a)&&a>0&&(t.discsTotal??=a)}break;case"DISCTOTAL":{const e=Number.parseInt(c,10);Number.isInteger(e)&&e>0&&(t.discsTotal??=e)}break;case"DATE":{const e=new Date(c);Number.isNaN(e.getTime())||(t.date??=e)}break;case"GENRE":t.genre??=c;break;case"METADATA_BLOCK_PICTURE":{const e=se(c),r=f(e),a=r.getUint32(0,!1),i=r.getUint32(4,!1),s=String.fromCharCode(...e.subarray(8,8+i)),n=r.getUint32(8+i,!1),o=p.decode(e.subarray(12+i,12+i+n)),d=r.getUint32(i+n+28),u=e.subarray(i+n+32,i+n+32+d);t.images??=[],t.images.push({data:u,mimeType:s,kind:3===a?"coverFront":4===a?"coverBack":"unknown",name:void 0,description:o||void 0})}}}};
|
|
33
|
+
/*!
|
|
34
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
35
|
+
*
|
|
36
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
37
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
38
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
39
|
+
*/class kt{constructor(e){this.input=e}}
|
|
40
|
+
/*!
|
|
41
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
42
|
+
*
|
|
43
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
44
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
45
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
46
|
+
*/const bt=[],wt=[],Tt=new Uint8Array(0);class yt{constructor(e,t,r,a,i=-1,s,n){if(this.data=e,this.type=t,this.timestamp=r,this.duration=a,this.sequenceNumber=i,e===Tt&&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(a)||a<0)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(i))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===Tt}get microsecondTimestamp(){return Math.trunc(q*this.timestamp)}get microsecondDuration(){return Math.trunc(q*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 yt(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 yt(this.data,this.type,e?.timestamp??this.timestamp,e?.duration??this.duration,this.sequenceNumber,this.byteLength)}}
|
|
47
|
+
/*!
|
|
48
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
49
|
+
*
|
|
50
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
51
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
52
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
53
|
+
*/
|
|
33
54
|
/*!
|
|
34
55
|
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
35
56
|
*
|
|
@@ -37,7 +58,21 @@ class ${constructor(e){this.mutex=new g,this.firstMediaStreamTimestamp=null,this
|
|
|
37
58
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
38
59
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
39
60
|
*/
|
|
40
|
-
const ce=new Uint8Array(0);class de{constructor(e,t,i,r,a=-1,s,o){if(this.data=e,this.type=t,this.timestamp=i,this.duration=r,this.sequenceNumber=a,e===ce&&void 0===s)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(void 0===s&&(s=e.byteLength),!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if("key"!==t&&"delta"!==t)throw new TypeError('type must be either "key" or "delta".');if(!Number.isFinite(i))throw new TypeError("timestamp must be a number.");if(!Number.isFinite(r)||r<0)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(a))throw new TypeError("sequenceNumber must be a number.");if(!Number.isInteger(s)||s<0)throw new TypeError("byteLength must be a non-negative integer.");if(void 0!==o&&("object"!=typeof o||!o))throw new TypeError("sideData, when provided, must be an object.");if(void 0!==o?.alpha&&!(o.alpha instanceof Uint8Array))throw new TypeError("sideData.alpha, when provided, must be a Uint8Array.");if(void 0!==o?.alphaByteLength&&(!Number.isInteger(o.alphaByteLength)||o.alphaByteLength<0))throw new TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=s,this.sideData=o??{},this.sideData.alpha&&void 0===this.sideData.alphaByteLength&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===ce}get microsecondTimestamp(){return Math.trunc(T*this.timestamp)}get microsecondDuration(){return Math.trunc(T*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if("undefined"==typeof EncodedVideoChunk)throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw new TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if("undefined"==typeof EncodedVideoChunk)throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to an audio chunk.");if("undefined"==typeof EncodedAudioChunk)throw new Error("Your browser does not support EncodedAudioChunk.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(e,t){if(!(e instanceof EncodedVideoChunk||e instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");const i=new Uint8Array(e.byteLength);return e.copyTo(i),new de(i,e.type,e.timestamp/1e6,(e.duration??0)/1e6,void 0,void 0,t)}clone(e){if(void 0!==e&&("object"!=typeof e||null===e))throw new TypeError("options, when provided, must be an object.");if(void 0!==e?.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 de(this.data,this.type,e?.timestamp??this.timestamp,e?.duration??this.duration,this.sequenceNumber,this.byteLength)}}
|
|
61
|
+
oe();let St=-1/0,Ct=-1/0,vt=null;"undefined"!=typeof FinalizationRegistry&&(vt=new FinalizationRegistry(e=>{const t=Date.now();"video"===e.type?(t-St>=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."),St=t),"undefined"!=typeof VideoFrame&&e.data instanceof VideoFrame&&e.data.close()):(t-Ct>=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."),Ct=t),"undefined"!=typeof AudioData&&e.data instanceof AudioData&&e.data.close())}));const Pt=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],It=new Set(Pt);class xt{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(q*this.timestamp)}get microsecondDuration(){return Math.trunc(q*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor(e,t){if(this._closed=!1,e instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e)){if(!t||"object"!=typeof t)throw new TypeError("init must be an object.");if(void 0===t.format||!It.has(t.format))throw new TypeError("init.format must be one of: "+Pt.join(", "));if(!Number.isInteger(t.codedWidth)||t.codedWidth<=0)throw new TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(t.codedHeight)||t.codedHeight<=0)throw new TypeError("init.codedHeight must be a positive integer.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(void 0!==t.duration&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");this._data=m(e).slice(),this._layout=t.layout??Ft(t.format,t.codedWidth,t.codedHeight),this.format=t.format,this.codedWidth=t.codedWidth,this.codedHeight=t.codedHeight,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=new Et(t.colorSpace)}else if("undefined"!=typeof VideoFrame&&e instanceof VideoFrame){if(void 0!==t?.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(void 0!==t?.timestamp&&!Number.isFinite(t?.timestamp))throw new TypeError("init.timestamp, when provided, must be a number.");if(void 0!==t?.duration&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");this._data=e,this._layout=null,this.format=e.format,this.codedWidth=e.displayWidth,this.codedHeight=e.displayHeight,this.rotation=t?.rotation??0,this.timestamp=t?.timestamp??e.timestamp/1e6,this.duration=t?.duration??(e.duration??0)/1e6,this.colorSpace=new Et(e.colorSpace)}else{if(!("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof SVGImageElement&&e instanceof SVGImageElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!=typeof HTMLVideoElement&&e instanceof HTMLVideoElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas))throw new TypeError("Invalid data type: Must be a BufferSource or CanvasImageSource.");{if(!t||"object"!=typeof t)throw new TypeError("init must be an object.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(void 0!==t.duration&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if("undefined"!=typeof VideoFrame)return new xt(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*q),duration:Math.trunc((t.duration??0)*q)||void 0}),t);let r=0,a=0;if("naturalWidth"in e?(r=e.naturalWidth,a=e.naturalHeight):"videoWidth"in e?(r=e.videoWidth,a=e.videoHeight):"width"in e&&(r=Number(e.width),a=Number(e.height)),!r||!a)throw new TypeError("Could not determine dimensions.");const i=new OffscreenCanvas(r,a),s=i.getContext("2d",{alpha:null!==Y?Y:Y="undefined"!=typeof navigator&&navigator.userAgent?.includes("Firefox"),willReadFrequently:!0});n(s),s.drawImage(e,0,0),this._data=i,this._layout=null,this.format="RGBX",this.codedWidth=r,this.codedHeight=a,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=new Et({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}}vt?.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return n(null!==this._data),Dt(this._data)?new xt(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation}):this._data instanceof Uint8Array?(n(this._layout),new xt(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 xt(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||(vt?.unregister(this),Dt(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(_t(e),this._closed)throw new Error("VideoSample is closed.");if(null===(e.format??this.format))throw new Error("Cannot get allocation size when format is null. Please manually provide an RGB pixel format in the options instead.");if(n(null!==this._data),!Dt(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 Dt(this._data)?this._data.allocationSize(e):this._data instanceof Uint8Array?this._data.byteLength:this.codedWidth*this.codedHeight*4}async copyTo(e,t={}){if(!P(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(_t(t),this._closed)throw new Error("VideoSample is closed.");if(null===(t.format??this.format))throw new Error("Cannot copy video sample data when format is null. Please manually provide an RGB pixel format in the options instead.");if(n(null!==this._data),!Dt(this._data)&&(t.colorSpace||t.format&&t.format!==this.format||t.layout||t.rect)){const r=this.toVideoFrame(),a=await r.copyTo(e,t);return r.close(),a}if(Dt(this._data))return this._data.copyTo(e,t);if(this._data instanceof Uint8Array){n(this._layout);return m(e).set(this._data),this._layout}{const t=this._data.getContext("2d");n(t);const r=t.getImageData(0,0,this.codedWidth,this.codedHeight);return m(e).set(r.data),[{offset:0,stride:4*this.codedWidth}]}}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");return n(null!==this._data),Dt(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,a,i,s,n,o,c){let d=0,u=0,l=this.displayWidth,h=this.displayHeight,m=0,f=0,p=this.displayWidth,g=this.displayHeight;if(void 0!==s?(d=t,u=r,l=a,h=i,m=s,f=n,void 0!==o?(p=o,g=c):(p=l,g=h)):(m=t,f=r,void 0!==a&&(p=a,g=i)),!("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(d))throw new TypeError("sx must be a number.");if(!Number.isFinite(u))throw new TypeError("sy must be a number.");if(!Number.isFinite(l)||l<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:d,sy:u,sWidth:l,sHeight:h}=this._rotateSourceRegion(d,u,l,h,this.rotation));const k=this.toCanvasImageSource();e.save();const b=m+p/2,w=f+g/2;e.translate(b,w),e.rotate(this.rotation*Math.PI/180);const T=this.rotation%180==0?1:p/g;e.scale(1/T,T),e.drawImage(k,d,u,l,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&&At(t.crop,"options.");const r=e.canvas.width,a=e.canvas.height,i=t.rotation??this.rotation,[s,n]=i%180==0?[this.codedWidth,this.codedHeight]:[this.codedHeight,this.codedWidth];let o,c,d,u;t.crop&&Bt(t.crop,s,n);const{sx:l,sy:h,sWidth:m,sHeight:f}=this._rotateSourceRegion(t.crop?.left??0,t.crop?.top??0,t.crop?.width??s,t.crop?.height??n,i);if("fill"===t.fit)o=0,c=0,d=r,u=a;else{const[e,i]=t.crop?[t.crop.width,t.crop.height]:[s,n],l="contain"===t.fit?Math.min(r/e,a/i):Math.max(r/e,a/i);d=e*l,u=i*l,o=(r-d)/2,c=(a-u)/2}e.save();const p=i%180==0?1:d/u;e.translate(r/2,a/2),e.rotate(i*Math.PI/180),e.scale(1/p,p),e.translate(-r/2,-a/2),e.drawImage(this.toCanvasImageSource(),l,h,m,f,o,c,d,u),e.restore()}_rotateSourceRegion(e,t,r,a,i){return 90===i?[e,t,r,a]=[t,this.codedHeight-e-r,a,r]:180===i?[e,t]=[this.codedWidth-e-r,this.codedHeight-t-a]:270===i&&([e,t,r,a]=[this.codedWidth-t-a,e,a,r]),{sx:e,sy:t,sWidth:r,sHeight:a}}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(n(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 Et{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 Dt=e=>"undefined"!=typeof VideoFrame&&e instanceof VideoFrame,Bt=(e,t,r)=>{e.left=Math.min(e.left,t),e.top=Math.min(e.top,r),e.width=Math.min(e.width,t-e.left),e.height=Math.min(e.height,r-e.top),n(e.width>=0),n(e.height>=0)},At=(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.")},_t=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.")}},Ft=(e,t,r)=>{const a=Mt(e),i=[];let s=0;for(const e of a){const a=Math.ceil(t/e.widthDivisor),n=Math.ceil(r/e.heightDivisor),o=a*e.sampleBytes,c=o*n;i.push({offset:s,stride:o}),s+=c}return i},Mt=e=>{const t=(e,t,r,a,i)=>{const s=[{sampleBytes:e,widthDivisor:1,heightDivisor:1},{sampleBytes:t,widthDivisor:r,heightDivisor:a},{sampleBytes:t,widthDivisor:r,heightDivisor:a}];return i&&s.push({sampleBytes:e,widthDivisor:1,heightDivisor:1}),s};switch(e){case"I420":return t(1,1,2,2,!1);case"I420P10":case"I420P12":return t(2,2,2,2,!1);case"I420A":return t(1,1,2,2,!0);case"I420AP10":case"I420AP12":return t(2,2,2,2,!0);case"I422":return t(1,1,2,1,!1);case"I422P10":case"I422P12":return t(2,2,2,1,!1);case"I422A":return t(1,1,2,1,!0);case"I422AP10":case"I422AP12":return t(2,2,2,1,!0);case"I444":return t(1,1,1,1,!1);case"I444P10":case"I444P12":return t(2,2,1,1,!1);case"I444A":return t(1,1,1,1,!0);case"I444AP10":case"I444AP12":return t(2,2,1,1,!0);case"NV12":return[{sampleBytes:1,widthDivisor:1,heightDivisor:1},{sampleBytes:2,widthDivisor:2,heightDivisor:2}];case"RGBA":case"RGBX":case"BGRA":case"BGRX":return[{sampleBytes:4,widthDivisor:1,heightDivisor:1}];default:R(e),n(!1)}},Rt=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]);class zt{get microsecondTimestamp(){return Math.trunc(q*this.timestamp)}get microsecondDuration(){return Math.trunc(q*this.duration)}constructor(e){if(this._closed=!1,Vt(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(!Rt.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/(Ot(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 a=this.numberOfFrames*this.numberOfChannels*Ot(this.format);if(r.byteLength<a)throw new TypeError("Invalid AudioDataInit: insufficient data size.");this._data=r}vt?.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&&!Rt.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 a=void 0!==e.frameCount?e.frameCount:this.numberOfFrames-r;if(a>this.numberOfFrames-r)throw new RangeError("frameCount out of range");const i=Ot(t),s=Nt(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?a:a*this.numberOfChannels)*i}copyTo(e,t){if(!P(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(!t||"object"!=typeof t)throw new TypeError("options must be an object.");if(!Number.isInteger(t.planeIndex)||t.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(void 0!==t.format&&!Rt.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:a,frameCount:i,frameOffset:s}=t,n=this.format,o=a??this.format;if(!o)throw new Error("Destination format not determined");const c=this.numberOfFrames,d=this.numberOfChannels,u=s??0;if(u>=c)throw new RangeError("frameOffset out of range");const l=void 0!==i?i:c-u;if(l>c-u)throw new RangeError("frameCount out of range");const h=Ot(o),m=Nt(o);if(m&&r>=d)throw new RangeError("planeIndex out of range");if(!m&&0!==r)throw new RangeError("planeIndex out of range");const p=(m?l:l*d)*h;if(e.byteLength<p)throw new RangeError("Destination buffer is too small");const g=f(e),k=Ut(o);if(Vt(this._data))X()&&d>2&&o!==n?Wt(this._data,g,n,o,d,r,u,l):this._data.copyTo(e,{planeIndex:r,frameOffset:u,frameCount:l,format:o});else{const e=this._data,t=f(e),a=Lt(n),i=Ot(n),s=Nt(n);for(let e=0;e<l;e++)if(m){let n;n=s?(r*c+(e+u))*i:((e+u)*d+r)*i;k(g,e*h,a(t,n))}else for(let r=0;r<d;r++){let n;n=s?(r*c+(e+u))*i:((e+u)*d+r)*i;k(g,(e*d+r)*h,a(t,n))}}}clone(){if(this._closed)throw new Error("AudioSample is closed.");if(Vt(this._data)){const e=new zt(this._data.clone());return e.setTimestamp(this.timestamp),e}return new zt({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data})}close(){this._closed||(vt?.unregister(this),Vt(this._data)?this._data.close():this._data=new Uint8Array(0),this._closed=!0)}toAudioData(){if(this._closed)throw new Error("AudioSample is closed.");if(Vt(this._data)){if(this._data.timestamp===this.microsecondTimestamp)return this._data.clone();if(Nt(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,a=e.sampleRate,i=e.length,s=Math.floor(24e4/r);let n=0,o=i;for(;o>0;){const i=Math.min(s,o),c=new Float32Array(r*i);for(let t=0;t<r;t++)e.copyFromChannel(c.subarray(t*i,(t+1)*i),t,n);yield new zt({format:"f32-planar",sampleRate:a,numberOfFrames:i,numberOfChannels:r,timestamp:t+n/a,data:c}),n+=i,o-=i}}static fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");const r=e.numberOfChannels,a=e.sampleRate,i=e.length,s=Math.floor(24e4/r);let n=0,o=i;const c=[];for(;o>0;){const i=Math.min(s,o),d=new Float32Array(r*i);for(let t=0;t<r;t++)e.copyFromChannel(d.subarray(t*i,(t+1)*i),t,n);const u=new zt({format:"f32-planar",sampleRate:a,numberOfFrames:i,numberOfChannels:r,timestamp:t+n/a,data:d});c.push(u),n+=i,o-=i}return c}}const Ot=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")}},Nt=e=>{switch(e){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},Lt=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)}},Ut=e=>{switch(e){case"u8":case"u8-planar":return(e,t,r)=>e.setUint8(t,N(127.5*(r+1),0,255));case"s16":case"s16-planar":return(e,t,r)=>e.setInt16(t,N(Math.round(32767*r),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,r)=>e.setInt32(t,N(Math.round(2147483647*r),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,r)=>e.setFloat32(t,r,!0)}},Vt=e=>"undefined"!=typeof AudioData&&e instanceof AudioData,Wt=(e,t,r,a,i,s,n,o)=>{const c=Lt(r),d=Ut(a),u=Ot(r),l=Ot(a),h=Nt(r);if(Nt(a))if(h){const a=new ArrayBuffer(o*u),i=f(a);e.copyTo(a,{planeIndex:s,frameOffset:n,frameCount:o,format:r});for(let e=0;e<o;e++){d(t,e*l,c(i,e*u))}}else{const a=new ArrayBuffer(o*i*u),h=f(a);e.copyTo(a,{planeIndex:0,frameOffset:n,frameCount:o,format:r});for(let e=0;e<o;e++){d(t,e*l,c(h,(e*i+s)*u))}}else if(h){const a=new ArrayBuffer(o*u),s=f(a);for(let h=0;h<i;h++){e.copyTo(a,{planeIndex:h,frameOffset:n,frameCount:o,format:r});for(let e=0;e<o;e++){d(t,(e*i+h)*l,c(s,e*u))}}}else{const a=new ArrayBuffer(o*i*u),s=f(a);e.copyTo(a,{planeIndex:0,frameOffset:n,frameCount:o,format:r});for(let e=0;e<o;e++)for(let r=0;r<i;r++){const a=e*i+r;d(t,a*l,c(s,a*u))}}},Ht=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.")},qt=e=>{if(!ce(e))throw new TypeError("timestamp must be a number.")},jt=(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 $t{constructor(e){if(!(e instanceof rr))throw new TypeError("track must be an InputTrack.");this._track=e}getFirstPacket(e={}){if(Ht(e),this._track.input._disposed)throw new ki;return jt(this._track,this._track._backing.getFirstPacket(e),e)}getPacket(e,t={}){if(qt(e),Ht(t),this._track.input._disposed)throw new ki;return jt(this._track,this._track._backing.getPacket(e,t),t)}getNextPacket(e,t={}){if(!(e instanceof yt))throw new TypeError("packet must be an EncodedPacket.");if(Ht(t),this._track.input._disposed)throw new ki;return jt(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(qt(e),Ht(t),this._track.input._disposed)throw new ki;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);const r=await this._track._backing.getKeyPacket(e,t);if(!r)return r;n("key"===r.type);return"delta"===await this._track.determinePacketType(r)?this.getKeyPacket(r.timestamp-1/this._track.timeResolution,t):r}async getNextKeyPacket(e,t={}){if(!(e instanceof yt))throw new TypeError("packet must be an EncodedPacket.");if(Ht(t),this._track.input._disposed)throw new ki;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);const r=await this._track._backing.getNextKeyPacket(e,t);if(!r)return r;n("key"===r.type);return"delta"===await this._track.determinePacketType(r)?this.getNextKeyPacket(r,t):r}packets(e,t,r={}){if(void 0!==e&&!(e instanceof yt))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 yt))throw new TypeError("endPacket must be an EncodedPacket.");if(Ht(r),this._track.input._disposed)throw new ki;const a=[];let{promise:i,resolve:s}=_(),{promise:n,resolve:o}=_(),c=!1,d=!1,u=null;const l=[],h=()=>Math.max(2,l.length);(async()=>{let u=e??await this.getFirstPacket(r);for(;u&&!d&&!this._track.input._disposed&&!(t&&u.sequenceNumber>=t?.sequenceNumber);)a.length>h()?(({promise:n,resolve:o}=_()),await n):(a.push(u),s(),({promise:i,resolve:s}=_()),u=await this.getNextPacket(u,r));c=!0,s()})().catch(e=>{u||(u=e,s())});const m=this._track;return{async next(){for(;;){if(m.input._disposed)throw new ki;if(d)return{value:void 0,done:!0};if(u)throw u;if(a.length>0){const e=a.shift(),t=performance.now();for(l.push(t);l.length>0&&t-l[0]>=1e3;)l.shift();return o(),{value:e,done:!1}}if(c)return{value:void 0,done:!0};await i}},return:async()=>(d=!0,o(),s(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}}class Qt{constructor(e,t){this.onSample=e,this.onError=t}}class Kt{mediaSamplesInRange(e=0,t=1/0){qt(e),qt(t);const r=[];let a=!1,i=null,{promise:s,resolve:n}=_(),{promise:o,resolve:c}=_(),d=!1,u=!1,l=!1,h=null;(async()=>{const m=await this._createDecoder(o=>{c(),o.timestamp>=t&&(u=!0),u?o.close():(i&&(o.timestamp>e?(r.push(i),a=!0):i.close()),o.timestamp>=e&&(r.push(o),a=!0),i=a?null:o,r.length>0&&(n(),({promise:s,resolve:n}=_())))},e=>{h||(h=e,n())}),f=this._createPacketSink(),p=await f.getKeyPacket(e,{verifyKeyPackets:!0})??await f.getFirstPacket();let g,k=p;if(t<1/0){const e=await f.getPacket(t),r=e?"key"===e.type&&e.timestamp===t?e:await f.getNextKeyPacket(e,{verifyKeyPackets:!0}):null;r&&(g=r)}const b=f.packets(p??void 0,g);for(await b.next();k&&!u&&!this._track.input._disposed;){const e=Gt(r.length);if(r.length+m.getDecodeQueueSize()>e){({promise:o,resolve:c}=_()),await o;continue}m.decode(k);const t=await b.next();if(t.done)break;k=t.value}await b.return(),l||this._track.input._disposed||await m.flush(),m.close(),!a&&i&&r.push(i),d=!0,n()})().catch(e=>{h||(h=e,n())});const m=this._track,f=()=>{i?.close();for(const e of r)e.close()};return{async next(){for(;;){if(m.input._disposed)throw f(),new ki;if(l)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(d)return{value:void 0,done:!0};await s}},return:async()=>(l=!0,u=!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 t=async function*(e){Symbol.iterator in e?yield*e[Symbol.iterator]():yield*e[Symbol.asyncIterator]()}(e),r=[],a=[];let{promise:i,resolve:s}=_(),{promise:o,resolve:c}=_(),d=!1,u=!1,l=null;const h=e=>{a.push(e),s(),({promise:i,resolve:s}=_())};(async()=>{const e=await this._createDecoder(e=>{if(c(),u)return void e.close();let t=0;for(;r.length>0&&e.timestamp-r[0]>-1e-10;)t++,r.shift();if(t>0)for(let r=0;r<t;r++)h(r<t-1?e.clone():e);else e.close()},e=>{l||(l=e,s())}),i=this._createPacketSink();let m=null,f=null,p=-1;const g=async()=>{n(f);let t=f;for(e.decode(t);t.sequenceNumber<p;){const r=Gt(a.length);for(;a.length+e.getDecodeQueueSize()>r&&!u;)({promise:o,resolve:c}=_()),await o;if(u)break;const s=await i.getNextPacket(t);n(s),e.decode(s),t=s}p=-1},k=async()=>{await e.flush();for(let e=0;e<r.length;e++)h(null);r.length=0};for await(const e of t){if(qt(e),u||this._track.input._disposed)break;const t=await i.getPacket(e),a=t&&await i.getKeyPacket(e,{verifyKeyPackets:!0});a?(m&&(a.sequenceNumber!==f.sequenceNumber||t.timestamp<m.timestamp)&&(await g(),await k()),r.push(t.timestamp),p=Math.max(t.sequenceNumber,p),m=t,f=a):(-1!==p&&(await g(),await k()),h(null),m=null)}u||this._track.input._disposed||(-1!==p&&await g(),await k()),e.close(),d=!0,s()})().catch(e=>{l||(l=e,s())});const m=this._track,f=()=>{for(const e of a)e?.close()};return{async next(){for(;;){if(m.input._disposed)throw f(),new ki;if(u)return{value:void 0,done:!0};if(l)throw f(),l;if(a.length>0){const e=a.shift();return n(void 0!==e),c(),{value:e,done:!1}}if(d)return{value:void 0,done:!0};await i}},return:async()=>(u=!0,c(),s(),f(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}}const Gt=e=>0===e?40:8;class Xt extends Qt{constructor(e,t,r,a,i,s){super(e,t),this.codec=r,this.decoderConfig=a,this.rotation=i,this.timeResolution=s,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new K,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 o=bt.find(e=>e.supports(r,a));if(o)this.customDecoder=new o,this.customDecoder.codec=r,this.customDecoder.config=a,this.customDecoder.onSample=e=>{if(!(e instanceof xt))throw new TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(e)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{const e=e=>{if(this.alphaQueue.length>0){const t=this.alphaQueue.shift();n(void 0!==t),this.mergeAlpha(e,t)}else this.colorQueue.push(e)};if("avc"===r&&this.decoderConfig.description&&Z()){const e=(e=>{try{const t=f(e);let r=0;const a=t.getUint8(r++),i=t.getUint8(r++),s=t.getUint8(r++),n=t.getUint8(r++),o=3&t.getUint8(r++),c=31&t.getUint8(r++),d=[];for(let a=0;a<c;a++){const a=t.getUint16(r,!1);r+=2,d.push(e.subarray(r,r+a)),r+=a}const u=t.getUint8(r++),l=[];for(let a=0;a<u;a++){const a=t.getUint16(r,!1);r+=2,l.push(e.subarray(r,r+a)),r+=a}const h={configurationVersion:a,avcProfileIndication:i,profileCompatibility:s,avcLevelIndication:n,lengthSizeMinusOne:o,sequenceParameterSets:d,pictureParameterSets:l,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((100===i||110===i||122===i||144===i)&&r+4<=e.length){const a=3&t.getUint8(r++),i=7&t.getUint8(r++),s=7&t.getUint8(r++),n=t.getUint8(r++);h.chromaFormat=a,h.bitDepthLumaMinus8=i,h.bitDepthChromaMinus8=s;const o=[];for(let a=0;a<n;a++){const a=t.getUint16(r,!1);r+=2,o.push(e.subarray(r,r+a)),r+=a}h.sequenceParameterSetExt=o}return h}catch(e){return console.error("Error deserializing AVC Decoder Configuration Record:",e),null}})(m(this.decoderConfig.description));if(e&&e.sequenceParameterSets.length>0){const t=Ye(e.sequenceParameterSets[0]);t&&0===t.frameMbsOnlyFlag&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"})}}const t=new Error("Decoding error").stack;this.decoder=new VideoDecoder({output:t=>{try{e(t)}catch(e){this.onError(e)}},error:e=>{e.stack=t,this.onError(e)}}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(n(this.decoder),Math.max(this.decoder.decodeQueueSize,this.alphaDecoder?.decodeQueueSize??0))}decode(e){if("hevc"===this.codec&&this.currentPacketIndex>0&&!this.raslSkipped){if(this.hasHevcRaslPicture(e.data))return;this.raslSkipped=!0}if(this.customDecoder)this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--);else{if(n(this.decoder),X()||A(this.inputTimestamps,e.timestamp,e=>e),Z()&&0===this.currentPacketIndex&&"avc"===this.codec){const t=Qe(e.data,this.decoderConfig).filter(e=>{const t=Ge(e);return!(t>=20&&t<=31)}),r=Ke(t,this.decoderConfig);e=new yt(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 Yt}catch(t){return console.error("Due to an error, only color data will be decoded.",t),this.mergerCreationFailed=!0,void this.decodeAlphaData(e)}if(!this.alphaDecoder){const e=e=>{if(this.alphaDecoderQueueSize--,this.colorQueue.length>0){const t=this.colorQueue.shift();n(void 0!==t),this.mergeAlpha(t,e)}else this.alphaQueue.push(e);for(this.decodedAlphaChunkCount++;this.nullAlphaFrameQueue.length>0&&this.nullAlphaFrameQueue[0]===this.decodedAlphaChunkCount;)if(this.nullAlphaFrameQueue.shift(),this.colorQueue.length>0){const e=this.colorQueue.shift();n(void 0!==e),this.mergeAlpha(e,null)}else this.alphaQueue.push(null)},t=new Error("Decoding error").stack;this.alphaDecoder=new VideoDecoder({output:t=>{try{e(t)}catch(e){this.onError(e)}},error:e=>{e.stack=t,this.onError(e)}}),this.alphaDecoder.configure(this.decoderConfig)}const t=ft(this.codec,this.decoderConfig,e.sideData.alpha);if(this.alphaHadKeyframe||(this.alphaHadKeyframe="key"===t),this.alphaHadKeyframe){if("hevc"===this.codec&&this.currentAlphaPacketIndex>0&&!this.alphaRaslSkipped){if(this.hasHevcRaslPicture(e.sideData.alpha))return void this.pushNullAlphaFrame();this.alphaRaslSkipped=!0}this.currentAlphaPacketIndex++,this.alphaDecoder.decode(e.alphaToEncodedVideoChunk(t??e.type)),this.alphaDecoderQueueSize++}else this.pushNullAlphaFrame()}pushNullAlphaFrame(){0===this.alphaDecoderQueueSize?this.alphaQueue.push(null):this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture(e){return Je(e,this.decoderConfig).some(e=>{const t=Ze(e);return t===Ve.RASL_N||t===Ve.RASL_R})}sampleHandler(e){if(X()){if(this.sampleQueue.length>0&&e.timestamp>=c(this.sampleQueue).timestamp){for(const e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}A(this.sampleQueue,e,e=>e.timestamp)}else{const t=this.inputTimestamps.shift();n(void 0!==t),e.setTimestamp(t),this.finalizeAndEmitSample(e)}}finalizeAndEmitSample(e){e.setTimestamp(Math.round(e.timestamp*this.timeResolution)/this.timeResolution),e.setDuration(Math.round(e.duration*this.timeResolution)/this.timeResolution),e.setRotation(this.rotation),this.onSample(e)}mergeAlpha(e,t){if(!t){const t=new xt(e);return void this.sampleHandler(t)}n(this.merger),this.merger.update(e,t),e.close(),t.close();const r=new VideoFrame(this.merger.canvas,{timestamp:e.timestamp,duration:e.duration??void 0}),a=new xt(r);this.sampleHandler(a)}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(n(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),X()){for(const e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}this.currentPacketIndex=0,this.raslSkipped=!1}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(n(this.decoder),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 Yt{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 a=this.gl.getAttribLocation(this.program,"a_position"),i=this.gl.getAttribLocation(this.program,"a_texCoord");return this.gl.enableVertexAttribArray(a),this.gl.vertexAttribPointer(a,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(i),this.gl.vertexAttribPointer(i,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 Jt extends Kt{constructor(e){if(!(e instanceof ar))throw new TypeError("videoTrack must be an InputVideoTrack.");super(),this._track=e}async _createDecoder(e,t){if(!await this._track.canDecode())throw new Error("This video track cannot be decoded by this browser. Make sure to check decodability before using a track.");const r=this._track.codec,a=this._track.rotation,i=await this._track.getDecoderConfig(),s=this._track.timeResolution;return n(r&&i),new Xt(e,t,r,i,a,s)}_createPacketSink(){return new $t(this._track)}async getSample(e){qt(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 Zt extends Qt{constructor(e,t,r,a){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new K,this.customDecoderQueueSize=0,this.currentTimestamp=null;const i=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 i=a.sampleRate;t.setTimestamp(Math.round(r*i)/i),e(t)},s=wt.find(e=>e.supports(r,a));if(s)this.customDecoder=new s,this.customDecoder.codec=r,this.customDecoder.config=a,this.customDecoder.onSample=e=>{if(!(e instanceof zt))throw new TypeError("The argument passed to onSample must be an AudioSample.");i(e)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{const e=new Error("Decoding error").stack;this.decoder=new AudioDecoder({output:e=>{try{i(new zt(e))}catch(e){this.onError(e)}},error:t=>{t.stack=e,this.onError(t)}}),this.decoder.configure(a)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(n(this.decoder),this.decoder.decodeQueueSize)}decode(e){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--)):(n(this.decoder),this.decoder.decode(e.toEncodedAudioChunk()))}flush(){return this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(n(this.decoder),this.decoder.flush())}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(n(this.decoder),this.decoder.close())}}class er extends Qt{constructor(e,t,r){super(e,t),this.decoderConfig=r,this.currentTimestamp=null,n(me.includes(r.codec)),this.codec=r.codec;const{dataType:a,sampleSize:i,littleEndian:s}=De(this.codec);switch(this.inputSampleSize=i,i){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,a=~e;128&a&&(a&=-129,t=-1),r=5+((240&a)>>4);const i=(1<<r|(15&a)<<r-4|1<<r-5)-33;return 0===t?i:-i})(e.getUint8(t)):"alaw"===a?this.readInputValue=(e,t)=>(e=>{let t=0,r=0,a=85^e;128&a&&(a&=-129,t=-1),r=4+((240&a)>>4);let i=0;return i=4!==r?1<<r|(15&a)<<r-4|1<<r-5:a<<1|1,0===t?i:-i})(e.getUint8(t)):n(!1);break;case 2:"unsigned"===a?this.readInputValue=(e,t)=>e.getUint16(t,s)-32768:"signed"===a?this.readInputValue=(e,t)=>e.getInt16(t,s):n(!1);break;case 3:"unsigned"===a?this.readInputValue=(e,t)=>z(e,t,s)-2**23:"signed"===a?this.readInputValue=(e,t)=>((e,t,r)=>z(e,t,r)<<8>>8)(e,t,s):n(!1);break;case 4:"unsigned"===a?this.readInputValue=(e,t)=>e.getUint32(t,s)-2**31:"signed"===a?this.readInputValue=(e,t)=>e.getInt32(t,s):"float"===a?this.readInputValue=(e,t)=>e.getFloat32(t,s):n(!1);break;case 8:"float"===a?this.readInputValue=(e,t)=>e.getFloat64(t,s):n(!1);break;default:R(i),n(!1)}switch(i){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:R(i),n(!1)}}getDecodeQueueSize(){return 0}decode(e){const t=f(e.data),r=e.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize,a=r*this.decoderConfig.numberOfChannels*this.outputSampleSize,i=new ArrayBuffer(a),s=new DataView(i);for(let e=0;e<r*this.decoderConfig.numberOfChannels;e++){const r=e*this.inputSampleSize,a=e*this.outputSampleSize,i=this.readInputValue(t,r);this.writeOutputValue(s,a,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 c=new zt({format:this.outputFormat,data:i,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:r,timestamp:o});this.onSample(c)}async flush(){}close(){}}class tr extends Kt{constructor(e){if(!(e instanceof ir))throw new TypeError("audioTrack must be an InputAudioTrack.");super(),this._track=e}async _createDecoder(e,t){if(!await this._track.canDecode())throw new Error("This audio track cannot be decoded by this browser. Make sure to check decodability before using a track.");const r=this._track.codec,a=await this._track.getDecoderConfig();return n(r&&a),me.includes(a.codec)?new er(e,t,a):new Zt(e,t,r,a)}_createPacketSink(){return new $t(this._track)}async getSample(e){qt(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)}}
|
|
62
|
+
/*!
|
|
63
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
64
|
+
*
|
|
65
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
66
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
67
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
68
|
+
*/class rr{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof ar}isAudioTrack(){return this instanceof ir}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 $t(this);let r=1/0,a=-1/0,i=0,s=0;for await(const n of t.packets(void 0,void 0,{metadataOnly:!0})){if(i>=e&&n.timestamp>=a)break;r=Math.min(r,n.timestamp),a=Math.max(a,n.timestamp+n.duration),i++,s+=n.byteLength}return{packetCount:i,averagePacketRate:i?Number((i/(a-r)).toPrecision(16)):0,averageBitrate:i?Number((8*s/(a-r)).toPrecision(16)):0}}}class ar extends rr{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 t=this._backing.getCodec();if(n(null!==t),bt.some(r=>r.supports(t,e)))return!0;if("undefined"==typeof VideoDecoder)return!1;return!0===(await VideoDecoder.isConfigSupported(e)).supported}catch(e){return console.error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof yt))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("packet must not be metadata-only to determine its type.");if(null===this.codec)return null;const t=await this.getDecoderConfig();return n(t),ft(this.codec,t,e.data)}}class ir extends rr{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 t=this._backing.getCodec();if(n(null!==t),wt.some(r=>r.supports(t,e)))return!0;if(e.codec.startsWith("pcm-"))return!0;if("undefined"==typeof AudioDecoder)return!1;return!0===(await AudioDecoder.isConfigSupported(e)).supported}catch(e){return console.error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof yt))throw new TypeError("packet must be an EncodedPacket.");return null===this.codec?null:"key"}}
|
|
69
|
+
/*!
|
|
70
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
71
|
+
*
|
|
72
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
73
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
74
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
75
|
+
*/const sr=e=>{let t=(e.hasVideo?"video/":e.hasAudio?"audio/":"application/")+(e.isQuickTime?"quicktime":"mp4");if(e.codecStrings.length>0){t+=`; codecs="${[...new Set(e.codecStrings)].join(", ")}"`}return t},nr=16,or=e=>{let t=Ei(e);const r=Oi(e,4);let a=8;1===t&&(t=_i(e),a=16);const i=t-a;return i<0?null:{name:r,totalSize:t,headerSize:a,contentSize:i}},cr=e=>Bi(e)/65536,dr=e=>Bi(e)/1073741824,ur=e=>{let t=0;for(let r=0;r<4;r++){t<<=7;const r=Si(e);if(t|=127&r,!(128&r))break}return t},lr=e=>{let t=vi(e);return e.skip(2),t=Math.min(t,e.remainingLength),p.decode(yi(e,t))},hr=e=>{const t=or(e);if(!t||"data"!==t.name)return null;if(e.remainingLength<8)return null;const r=Ei(e);e.skip(4);const a=yi(e,t.contentSize-8);switch(r){case 1:return p.decode(a);case 2:return new TextDecoder("utf-16be").decode(a);case 13:return new de(a,"image/jpeg");case 14:return new de(a,"image/png");case 27:return new de(a,"image/bmp");default:return a}};
|
|
41
76
|
/*!
|
|
42
77
|
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
43
78
|
*
|
|
@@ -52,7 +87,7 @@ const ce=new Uint8Array(0);class de{constructor(e,t,i,r,a=-1,s,o){if(this.data=e
|
|
|
52
87
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
53
88
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
54
89
|
*/
|
|
55
|
-
class ue{constructor(e){this.value=e}}class le{constructor(e){this.value=e}}class he{constructor(e){this.value=e}}class me{constructor(e){this.value=e}}var pe;!function(e){e[e.EBML=440786851]="EBML",e[e.EBMLVersion=17030]="EBMLVersion",e[e.EBMLReadVersion=17143]="EBMLReadVersion",e[e.EBMLMaxIDLength=17138]="EBMLMaxIDLength",e[e.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",e[e.DocType=17026]="DocType",e[e.DocTypeVersion=17031]="DocTypeVersion",e[e.DocTypeReadVersion=17029]="DocTypeReadVersion",e[e.Void=236]="Void",e[e.Segment=408125543]="Segment",e[e.SeekHead=290298740]="SeekHead",e[e.Seek=19899]="Seek",e[e.SeekID=21419]="SeekID",e[e.SeekPosition=21420]="SeekPosition",e[e.Duration=17545]="Duration",e[e.Info=357149030]="Info",e[e.TimestampScale=2807729]="TimestampScale",e[e.MuxingApp=19840]="MuxingApp",e[e.WritingApp=22337]="WritingApp",e[e.Tracks=374648427]="Tracks",e[e.TrackEntry=174]="TrackEntry",e[e.TrackNumber=215]="TrackNumber",e[e.TrackUID=29637]="TrackUID",e[e.TrackType=131]="TrackType",e[e.FlagEnabled=185]="FlagEnabled",e[e.FlagDefault=136]="FlagDefault",e[e.FlagForced=21930]="FlagForced",e[e.FlagOriginal=21934]="FlagOriginal",e[e.FlagHearingImpaired=21931]="FlagHearingImpaired",e[e.FlagVisualImpaired=21932]="FlagVisualImpaired",e[e.FlagCommentary=21935]="FlagCommentary",e[e.FlagLacing=156]="FlagLacing",e[e.Name=21358]="Name",e[e.Language=2274716]="Language",e[e.LanguageBCP47=2274717]="LanguageBCP47",e[e.CodecID=134]="CodecID",e[e.CodecPrivate=25506]="CodecPrivate",e[e.CodecDelay=22186]="CodecDelay",e[e.SeekPreRoll=22203]="SeekPreRoll",e[e.DefaultDuration=2352003]="DefaultDuration",e[e.Video=224]="Video",e[e.PixelWidth=176]="PixelWidth",e[e.PixelHeight=186]="PixelHeight",e[e.AlphaMode=21440]="AlphaMode",e[e.Audio=225]="Audio",e[e.SamplingFrequency=181]="SamplingFrequency",e[e.Channels=159]="Channels",e[e.BitDepth=25188]="BitDepth",e[e.SimpleBlock=163]="SimpleBlock",e[e.BlockGroup=160]="BlockGroup",e[e.Block=161]="Block",e[e.BlockAdditions=30113]="BlockAdditions",e[e.BlockMore=166]="BlockMore",e[e.BlockAdditional=165]="BlockAdditional",e[e.BlockAddID=238]="BlockAddID",e[e.BlockDuration=155]="BlockDuration",e[e.ReferenceBlock=251]="ReferenceBlock",e[e.Cluster=524531317]="Cluster",e[e.Timestamp=231]="Timestamp",e[e.Cues=475249515]="Cues",e[e.CuePoint=187]="CuePoint",e[e.CueTime=179]="CueTime",e[e.CueTrackPositions=183]="CueTrackPositions",e[e.CueTrack=247]="CueTrack",e[e.CueClusterPosition=241]="CueClusterPosition",e[e.Colour=21936]="Colour",e[e.MatrixCoefficients=21937]="MatrixCoefficients",e[e.TransferCharacteristics=21946]="TransferCharacteristics",e[e.Primaries=21947]="Primaries",e[e.Range=21945]="Range",e[e.Projection=30320]="Projection",e[e.ProjectionType=30321]="ProjectionType",e[e.ProjectionPoseRoll=30325]="ProjectionPoseRoll",e[e.Attachments=423732329]="Attachments",e[e.AttachedFile=24999]="AttachedFile",e[e.FileDescription=18046]="FileDescription",e[e.FileName=18030]="FileName",e[e.FileMediaType=18016]="FileMediaType",e[e.FileData=18012]="FileData",e[e.FileUID=18094]="FileUID",e[e.Chapters=272869232]="Chapters",e[e.Tags=307544935]="Tags",e[e.Tag=29555]="Tag",e[e.Targets=25536]="Targets",e[e.TargetTypeValue=26826]="TargetTypeValue",e[e.TargetType=25546]="TargetType",e[e.TagTrackUID=25541]="TagTrackUID",e[e.TagEditionUID=25545]="TagEditionUID",e[e.TagChapterUID=25540]="TagChapterUID",e[e.TagAttachmentUID=25542]="TagAttachmentUID",e[e.SimpleTag=26568]="SimpleTag",e[e.TagName=17827]="TagName",e[e.TagLanguage=17530]="TagLanguage",e[e.TagString=17543]="TagString",e[e.TagBinary=17541]="TagBinary",e[e.ContentEncodings=28032]="ContentEncodings",e[e.ContentEncoding=25152]="ContentEncoding",e[e.ContentEncodingOrder=20529]="ContentEncodingOrder",e[e.ContentEncodingScope=20530]="ContentEncodingScope",e[e.ContentCompression=20532]="ContentCompression",e[e.ContentCompAlgo=16980]="ContentCompAlgo",e[e.ContentCompSettings=16981]="ContentCompSettings",e[e.ContentEncryption=20533]="ContentEncryption"}(pe||(pe={})),pe.EBML,pe.Segment,pe.SeekHead,pe.Info,pe.Cluster,pe.Tracks,pe.Cues,pe.Attachments,pe.Chapters,pe.Tags;const fe=e=>e<256?1:e<65536?2:e<1<<24?3:e<2**32?4:e<2**40?5:6,ge=e=>e<256n?1:e<65536n?2:e<1n<<24n?3:e<1n<<32n?4:e<1n<<40n?5:e<1n<<48n?6:e<1n<<56n?7:8,we=e=>e>=-64&&e<64?1:e>=-8192&&e<8192?2:e>=-1048576&&e<1<<20?3:e>=-134217728&&e<1<<27?4:e>=-17179869184&&e<2**34?5:6;class ke{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=new WeakMap,this.dataOffsets=new WeakMap}writeByte(e){this.helperView.setUint8(0,e),this.writer.write(this.helper.subarray(0,1))}writeFloat32(e){this.helperView.setFloat32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeFloat64(e){this.helperView.setFloat64(0,e,!1),this.writer.write(this.helper)}writeUnsignedInt(e,t=fe(e)){let i=0;switch(t){case 6:this.helperView.setUint8(i++,e/2**40|0);case 5:this.helperView.setUint8(i++,e/2**32|0);case 4:this.helperView.setUint8(i++,e>>24);case 3:this.helperView.setUint8(i++,e>>16);case 2:this.helperView.setUint8(i++,e>>8);case 1:this.helperView.setUint8(i++,e);break;default:throw new Error("Bad unsigned int size "+t)}this.writer.write(this.helper.subarray(0,i))}writeUnsignedBigInt(e,t=ge(e)){let i=0;for(let r=t-1;r>=0;r--)this.helperView.setUint8(i++,Number(e>>BigInt(8*r)&0xffn));this.writer.write(this.helper.subarray(0,i))}writeSignedInt(e,t=we(e)){e<0&&(e+=2**(8*t)),this.writeUnsignedInt(e,t)}writeVarInt(e,t=(e=>{if(e<127)return 1;if(e<16383)return 2;if(e<2097151)return 3;if(e<268435455)return 4;if(e<2**35-1)return 5;if(e<2**42-1)return 6;throw new Error("EBML varint size not supported "+e)})(e)){let i=0;switch(t){case 1:this.helperView.setUint8(i++,128|e);break;case 2:this.helperView.setUint8(i++,64|e>>8),this.helperView.setUint8(i++,e);break;case 3:this.helperView.setUint8(i++,32|e>>16),this.helperView.setUint8(i++,e>>8),this.helperView.setUint8(i++,e);break;case 4:this.helperView.setUint8(i++,16|e>>24),this.helperView.setUint8(i++,e>>16),this.helperView.setUint8(i++,e>>8),this.helperView.setUint8(i++,e);break;case 5:this.helperView.setUint8(i++,8|e/2**32&7),this.helperView.setUint8(i++,e>>24),this.helperView.setUint8(i++,e>>16),this.helperView.setUint8(i++,e>>8),this.helperView.setUint8(i++,e);break;case 6:this.helperView.setUint8(i++,4|e/2**40&3),this.helperView.setUint8(i++,e/2**32|0),this.helperView.setUint8(i++,e>>24),this.helperView.setUint8(i++,e>>16),this.helperView.setUint8(i++,e>>8),this.helperView.setUint8(i++,e);break;default:throw new Error("Bad EBML varint size "+t)}this.writer.write(this.helper.subarray(0,i))}writeAsciiString(e){this.writer.write(new Uint8Array(e.split("").map(e=>e.charCodeAt(0))))}writeEBML(e){if(null!==e)if(e instanceof Uint8Array)this.writer.write(e);else if(Array.isArray(e))for(const t of e)this.writeEBML(t);else if(this.offsets.set(e,this.writer.getPos()),this.writeUnsignedInt(e.id),Array.isArray(e.data)){const t=this.writer.getPos(),i=-1===e.size?1:e.size??4;-1===e.size?this.writeByte(255):this.writer.seek(this.writer.getPos()+i);const r=this.writer.getPos();if(this.dataOffsets.set(e,r),this.writeEBML(e.data),-1!==e.size){const e=this.writer.getPos()-r,a=this.writer.getPos();this.writer.seek(t),this.writeVarInt(e,i),this.writer.seek(a)}}else if("number"==typeof e.data){const t=e.size??fe(e.data);this.writeVarInt(t),this.writeUnsignedInt(e.data,t)}else if("bigint"==typeof e.data){const t=e.size??ge(e.data);this.writeVarInt(t),this.writeUnsignedBigInt(e.data,t)}else if("string"==typeof e.data)this.writeVarInt(e.data.length),this.writeAsciiString(e.data);else if(e.data instanceof Uint8Array)this.writeVarInt(e.data.byteLength,e.size),this.writer.write(e.data);else if(e.data instanceof ue)this.writeVarInt(4),this.writeFloat32(e.data.value);else if(e.data instanceof le)this.writeVarInt(8),this.writeFloat64(e.data.value);else if(e.data instanceof he){const t=e.size??we(e.data.value);this.writeVarInt(t),this.writeSignedInt(e.data.value,t)}else if(e.data instanceof me){const t=u.encode(e.data.value);this.writeVarInt(t.length),this.writer.write(t)}else k(e.data)}}const ye={avc:"V_MPEG4/ISO/AVC",hevc:"V_MPEGH/ISO/HEVC",vp8:"V_VP8",vp9:"V_VP9",av1:"V_AV1",aac:"A_AAC",mp3:"A_MPEG/L3",opus:"A_OPUS",vorbis:"A_VORBIS",flac:"A_FLAC","pcm-u8":"A_PCM/INT/LIT","pcm-s16":"A_PCM/INT/LIT","pcm-s16be":"A_PCM/INT/BIG","pcm-s24":"A_PCM/INT/LIT","pcm-s24be":"A_PCM/INT/BIG","pcm-s32":"A_PCM/INT/LIT","pcm-s32be":"A_PCM/INT/BIG","pcm-f32":"A_PCM/FLOAT/IEEE","pcm-f64":"A_PCM/FLOAT/IEEE",webvtt:"S_TEXT/WEBVTT"},be=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,Te=/(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})/,Ce=e=>{const t=Math.floor(e/36e5),i=Math.floor(e%36e5/6e4),r=Math.floor(e%6e4/1e3),a=e%1e3;return t.toString().padStart(2,"0")+":"+i.toString().padStart(2,"0")+":"+r.toString().padStart(2,"0")+"."+a.toString().padStart(3,"0")};
|
|
90
|
+
class mr extends kt{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 sr({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??=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,8,nr);if(t instanceof Promise&&(t=await t),!t)break;const r=e,a=or(t);if(!a)break;if("ftyp"===a.name){const e=Oi(t,4);this.isQuickTime="qt "===e}else if("moov"===a.name){let e=this.reader.requestSlice(t.filePos,a.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 e of this.tracks){const t=e.editListPreviousSegmentDurations/this.movieTimescale;e.editListOffset-=Math.round(t*e.timescale)}break}e=r+a.totalSize}if(this.isFragmented&&null!==this.reader.fileSize){let e=this.reader.requestSlice(this.reader.fileSize-4,4);e instanceof Promise&&(e=await e),n(e);const t=Ei(e),r=this.reader.fileSize-t;if(r>=0&&r<=this.reader.fileSize-nr){let e=this.reader.requestSliceRange(r,8,nr);if(e instanceof Promise&&(e=await e),e){const t=or(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 t={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};e.sampleTable=t,n(this.moovSlice);const r=this.moovSlice.slice(e.sampleTableByteOffset);this.currentTrack=e,this.traverseBox(r),this.currentTrack=null;if("audio"===e.info?.type&&e.info.codec&&me.includes(e.info.codec)&&0===t.sampleCompositionTimeOffsets.length){n("audio"===e.info?.type);const r=De(e.info.codec),a=[],i=[];for(let s=0;s<t.sampleToChunk.length;s++){const n=t.sampleToChunk[s],o=t.sampleToChunk[s+1],d=(o?o.startChunkIndex:t.chunkOffsets.length)-n.startChunkIndex;for(let s=0;s<d;s++){const o=n.startSampleIndex+s*n.samplesPerChunk,d=o+n.samplesPerChunk,u=B(t.sampleTimingEntries,o,e=>e.startIndex),l=t.sampleTimingEntries[u],h=B(t.sampleTimingEntries,d,e=>e.startIndex),m=t.sampleTimingEntries[h],f=l.startDecodeTimestamp+(o-l.startIndex)*l.delta,p=m.startDecodeTimestamp+(d-m.startIndex)*m.delta-f,g=c(a);g&&g.delta===p?g.count++:a.push({startIndex:n.startChunkIndex+s,startDecodeTimestamp:f,count:1,delta:p});const k=n.samplesPerChunk*r.sampleSize*e.info.numberOfChannels;i.push(k)}n.startSampleIndex=n.startChunkIndex,n.samplesPerChunk=1}t.sampleTimingEntries=a,t.sampleSizes=i}if(t.sampleCompositionTimeOffsets.length>0){t.presentationTimestamps=[];for(const e of t.sampleTimingEntries)for(let r=0;r<e.count;r++)t.presentationTimestamps.push({presentationTimestamp:e.startDecodeTimestamp+r*e.delta,sampleIndex:e.startIndex+r});for(const e of t.sampleCompositionTimeOffsets)for(let r=0;r<e.count;r++){const a=e.startIndex+r,i=t.presentationTimestamps[a];i&&(i.presentationTimestamp+=e.offset)}t.presentationTimestamps.sort((e,t)=>e.presentationTimestamp-t.presentationTimestamp),t.presentationTimestampIndexMap=Array(t.presentationTimestamps.length).fill(-1);for(let e=0;e<t.presentationTimestamps.length;e++)t.presentationTimestampIndexMap[t.presentationTimestamps[e].sampleIndex]=e}return t}async readFragment(e){if(this.lastReadFragment?.moofOffset===e)return this.lastReadFragment;let t=this.reader.requestSliceRange(e,8,nr);t instanceof Promise&&(t=await t),n(t);const r=or(t);n("moof"===r?.name);let a=this.reader.requestSlice(e,r.totalSize);a instanceof Promise&&(a=await a),n(a),this.traverseBox(a);const i=this.lastReadFragment;n(i&&i.moofOffset===e);for(const[,e]of i.trackData){const t=e.track,{fragmentPositionCache:r}=t;if(!e.startTimestampIsFinal){const a=t.fragmentLookupTable.find(e=>e.moofOffset===i.moofOffset);if(a)yr(e,a.timestamp);else{const t=B(r,i.moofOffset-1,e=>e.moofOffset);if(-1!==t){const a=r[t];yr(e,a.endTimestamp)}}e.startTimestampIsFinal=!0}const a=B(r,e.startTimestamp,e=>e.startTimestamp);-1!==a&&r[a].moofOffset===i.moofOffset||r.splice(a+1,0,{moofOffset:i.moofOffset,startTimestamp:e.startTimestamp,endTimestamp:e.endTimestamp})}return i}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=or(e);if(!r)break;yield{boxInfo:r,slice:e},e.filePos=t+r.totalSize}}traverseBox(e){const t=e.filePos,r=or(e);if(!r)return!1;const a=e.filePos,i=t+r.totalSize;switch(r.name){case"mdia":case"minf":case"dinf":case"mfra":case"edts":case"wave":this.readContiguousBoxes(e.slice(a,r.contentSize));break;case"mvhd":{const t=Si(e);e.skip(3),1===t?(e.skip(16),this.movieTimescale=Ei(e),this.movieDurationInTimescale=_i(e)):(e.skip(8),this.movieTimescale=Ei(e),this.movieDurationInTimescale=Ei(e))}break;case"trak":{const t={id:-1,demuxer:this,inputTrack:null,disposition:{...le},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,internalCodecId:null,name:null,languageCode:L,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0};if(this.currentTrack=t,this.readContiguousBoxes(e.slice(a,r.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 ar(this.input,new pr(e)),this.tracks.push(t)}else if("audio"===t.info.type&&-1!==t.info.numberOfChannels){const e=t;t.inputTrack=new ir(this.input,new gr(e)),this.tracks.push(t)}this.currentTrack=null}break;case"tkhd":{const t=this.currentTrack;if(!t)break;const r=Si(e),a=!!(1&Pi(e));if(t.disposition.default=a,0===r)e.skip(8),t.id=Ei(e),e.skip(4),t.durationInMovieTimescale=Ei(e);else{if(1!==r)throw new Error(`Incorrect track header version ${r}.`);e.skip(16),t.id=Ei(e),e.skip(4),t.durationInMovieTimescale=_i(e)}e.skip(16);const i=[cr(e),cr(e),dr(e),cr(e),cr(e),dr(e),cr(e),cr(e),dr(e)],s=o(V(Sr(i),90));n(0===s||90===s||180===s||270===s),t.rotation=s}break;case"elst":{const t=this.currentTrack;if(!t)break;const r=Si(e);e.skip(3);let a=!1,i=0;const s=Ei(e);for(let n=0;n<s;n++){const s=1===r?_i(e):Ei(e),n=1===r?Fi(e):Bi(e),o=cr(e);if(0!==s){if(a){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=i,t.editListOffset=n,a=!0}else i+=s}}}break;case"mdhd":{const t=this.currentTrack;if(!t)break;const r=Si(e);e.skip(3),0===r?(e.skip(8),t.timescale=Ei(e),t.durationInMediaTimescale=Ei(e)):1===r&&(e.skip(16),t.timescale=Ei(e),t.durationInMediaTimescale=_i(e));let a=vi(e);if(a>0){t.languageCode="";for(let e=0;e<3;e++)t.languageCode=String.fromCharCode(96+(31&a))+t.languageCode,a>>=5;H(t.languageCode)||(t.languageCode=L)}}break;case"hdlr":{const t=this.currentTrack;if(!t)break;e.skip(8);const r=Oi(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 i=this.currentTrack;if(!i)break;i.sampleTableByteOffset=t,this.readContiguousBoxes(e.slice(a,r.contentSize))}break;case"stsd":{const t=this.currentTrack;if(!t)break;if(null===t.info||t.sampleTable)break;const r=Si(e);e.skip(3);const a=Ei(e);for(let i=0;i<a;i++){const a=e.filePos,i=or(e);if(!i)break;t.internalCodecId=i.name;const s=i.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 '${i.name}').`),e.skip(24),t.info.width=vi(e),t.info.height=vi(e),e.skip(50),this.readContiguousBoxes(e.slice(e.filePos,a+i.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 '${i.name}').`))),e.skip(8);const n=vi(e);e.skip(6);let o=vi(e),c=vi(e);e.skip(4);let d=Ei(e)/65536;if(0===r&&n>0)if(1===n)e.skip(4),c=8*Ei(e),e.skip(8);else if(2===n){e.skip(4),d=zi(e),o=Ei(e),e.skip(4),c=Ei(e);const r=Ei(e);if(e.skip(8),"lpcm"===s){const e=c+7>>3,a=Boolean(1&r),i=Boolean(2&r),s=4&r?-1:0;c>0&&c<=64&&(a?32===c&&(t.info.codec=i?"pcm-f32be":"pcm-f32"):s&1<<e-1?1===e?t.info.codec="pcm-s8":2===e?t.info.codec=i?"pcm-s16be":"pcm-s16":3===e?t.info.codec=i?"pcm-s24be":"pcm-s24":4===e&&(t.info.codec=i?"pcm-s32be":"pcm-s32"):1===e&&(t.info.codec="pcm-u8")),null===t.info.codec&&console.warn("Unsupported PCM format.")}}"opus"===t.info.codec&&(d=xe),t.info.numberOfChannels=o,t.info.sampleRate=d,"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,a+i.totalSize-e.filePos))}}}break;case"avcC":{const t=this.currentTrack;if(!t)break;n(t.info),t.info.codecDescription=yi(e,r.contentSize)}break;case"hvcC":{const t=this.currentTrack;if(!t)break;n(t.info),t.info.codecDescription=yi(e,r.contentSize)}break;case"vpcC":{const t=this.currentTrack;if(!t)break;n("video"===t.info?.type),e.skip(4);const r=Si(e),a=Si(e),i=Si(e),s=i>>4,o=i>>1&7,c=1&i,d=Si(e),u=Si(e),l=Si(e);t.info.vp9CodecInfo={profile:r,level:a,bitDepth:s,chromaSubsampling:o,videoFullRangeFlag:c,colourPrimaries:d,transferCharacteristics:u,matrixCoefficients:l}}break;case"av1C":{const t=this.currentTrack;if(!t)break;n("video"===t.info?.type),e.skip(1);const r=Si(e),a=r>>5,i=31&r,s=Si(e),o=s>>7,c=s>>6&1,d=s>>4&1,u=s>>3&1,l=s>>2&1,h=3&s,m=2===a&&c?s>>5&1?12:10:c?10:8;t.info.av1CodecInfo={profile:a,level:i,tier:o,bitDepth:m,monochrome:d,chromaSubsamplingX:u,chromaSubsamplingY:l,chromaSamplePosition:h}}break;case"colr":{const t=this.currentTrack;if(!t)break;n("video"===t.info?.type);if("nclx"!==Oi(e,4))break;const r=vi(e),a=vi(e),i=vi(e),s=Boolean(128&Si(e));t.info.colorSpace={primaries:w[r],transfer:y[a],matrix:C[i],fullRange:s}}break;case"esds":{const t=this.currentTrack;if(!t)break;n("audio"===t.info?.type),e.skip(4);n(3===Si(e)),ur(e),e.skip(2);const r=Si(e),a=!!(64&r),i=!!(32&r);if(!!(128&r)&&e.skip(2),a){const t=Si(e);e.skip(t)}i&&e.skip(2);n(4===Si(e));const s=ur(e),o=e.filePos,c=Si(e);if(64===c||103===c?(t.info.codec="aac",t.info.aacCodecInfo={isMpeg2:103===c}):105===c||107===c?t.info.codec="mp3":221===c?t.info.codec="vorbis":console.warn(`Unsupported audio codec (objectTypeIndication ${c}) - discarding track.`),e.skip(12),s>e.filePos-o){n(5===Si(e));const r=ur(e);if(t.info.codecDescription=yi(e,r),"aac"===t.info.codec){const e=Ie(t.info.codecDescription);null!==e.numberOfChannels&&(t.info.numberOfChannels=e.numberOfChannels),null!==e.sampleRate&&(t.info.sampleRate=e.sampleRate)}}}break;case"enda":{const t=this.currentTrack;if(!t)break;n("audio"===t.info?.type);255&vi(e)&&("pcm-s16be"===t.info.codec?t.info.codec="pcm-s16":"pcm-s24be"===t.info.codec?t.info.codec="pcm-s24":"pcm-s32be"===t.info.codec?t.info.codec="pcm-s32":"pcm-f32be"===t.info.codec?t.info.codec="pcm-f32":"pcm-f64be"===t.info.codec&&(t.info.codec="pcm-f64"))}break;case"pcmC":{const t=this.currentTrack;if(!t)break;n("audio"===t.info?.type),e.skip(4);const r=Si(e),a=Boolean(1&r),i=Si(e);"pcm-s16be"===t.info.codec?a?16===i?t.info.codec="pcm-s16":24===i?t.info.codec="pcm-s24":32===i?t.info.codec="pcm-s32":(console.warn(`Invalid ipcm sample size ${i}.`),t.info.codec=null):16===i?t.info.codec="pcm-s16be":24===i?t.info.codec="pcm-s24be":32===i?t.info.codec="pcm-s32be":(console.warn(`Invalid ipcm sample size ${i}.`),t.info.codec=null):"pcm-f32be"===t.info.codec&&(a?32===i?t.info.codec="pcm-f32":64===i?t.info.codec="pcm-f64":(console.warn(`Invalid fpcm sample size ${i}.`),t.info.codec=null):32===i?t.info.codec="pcm-f32be":64===i?t.info.codec="pcm-f64be":(console.warn(`Invalid fpcm sample size ${i}.`),t.info.codec=null));break}case"dOps":{const t=this.currentTrack;if(!t)break;n("audio"===t.info?.type),e.skip(1);const r=Si(e),a=vi(e),i=Ei(e),s=Ii(e),o=Si(e);let c;c=0!==o?yi(e,2+r):new Uint8Array(0);const d=new Uint8Array(19+c.byteLength),u=new DataView(d.buffer);u.setUint32(0,1332770163,!1),u.setUint32(4,1214603620,!1),u.setUint8(8,1),u.setUint8(9,r),u.setUint16(10,a,!0),u.setUint32(12,i,!0),u.setInt16(16,s,!0),u.setUint8(18,o),d.set(c,19),t.info.codecDescription=d,t.info.numberOfChannels=r}break;case"dfLa":{const t=this.currentTrack;if(!t)break;n("audio"===t.info?.type),e.skip(4);const r=127,a=128,s=e.filePos;for(;e.filePos<i;){const i=Si(e),s=Pi(e);if((i&r)===pt.STREAMINFO){e.skip(10);const r=Ei(e),a=r>>>12,i=1+(r>>9&7);t.info.sampleRate=a,t.info.numberOfChannels=i,e.skip(20)}else e.skip(s);if(i&a)break}const o=e.filePos;e.filePos=s;const c=yi(e,o-s),d=new Uint8Array(4+c.byteLength);new DataView(d.buffer).setUint32(0,1716281667,!1),d.set(c,4),t.info.codecDescription=d}break;case"stts":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4);const r=Ei(e);let a=0,i=0;for(let s=0;s<r;s++){const r=Ei(e),s=Ei(e);t.sampleTable.sampleTimingEntries.push({startIndex:a,startDecodeTimestamp:i,count:r,delta:s}),a+=r,i+=r*s}}break;case"ctts":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4);const r=Ei(e);let a=0;for(let i=0;i<r;i++){const r=Ei(e),i=Bi(e);t.sampleTable.sampleCompositionTimeOffsets.push({startIndex:a,count:r,offset:i}),a+=r}}break;case"stsz":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4);const r=Ei(e),a=Ei(e);if(0===r)for(let r=0;r<a;r++){const r=Ei(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=Si(e),a=Ei(e),i=yi(e,Math.ceil(a*r/8)),s=new u(i);for(let e=0;e<a;e++){const e=s.readBits(r);t.sampleTable.sampleSizes.push(e)}}break;case"stss":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4),t.sampleTable.keySampleIndices=[];const r=Ei(e);for(let a=0;a<r;a++){const r=Ei(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=Ei(e);for(let a=0;a<r;a++){const r=Ei(e)-1,a=Ei(e),i=Ei(e);t.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:r,samplesPerChunk:a,sampleDescriptionIndex:i})}let a=0;for(let e=0;e<t.sampleTable.sampleToChunk.length;e++)if(t.sampleTable.sampleToChunk[e].startSampleIndex=a,e<t.sampleTable.sampleToChunk.length-1){a+=(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=Ei(e);for(let a=0;a<r;a++){const r=Ei(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=Ei(e);for(let a=0;a<r;a++){const r=_i(e);t.sampleTable.chunkOffsets.push(r)}}break;case"mvex":this.isFragmented=!0,this.readContiguousBoxes(e.slice(a,r.contentSize));break;case"mehd":{const t=Si(e);e.skip(3);const r=1===t?_i(e):Ei(e);this.movieDurationInTimescale=r}break;case"trex":{e.skip(4);const t=Ei(e),r=Ei(e),a=Ei(e),i=Ei(e),s=Ei(e);this.fragmentTrackDefaults.push({trackId:t,defaultSampleDescriptionIndex:r,defaultSampleDuration:a,defaultSampleSize:i,defaultSampleFlags:s})}break;case"tfra":{const t=Si(e);e.skip(3);const r=Ei(e),a=this.tracks.find(e=>e.id===r);if(!a)break;const i=Ei(e),s=(12&i)>>2,n=3&i,o=[Si,vi,Pi,Ei],c=o[(48&i)>>4],d=o[s],u=o[n],l=Ei(e);for(let r=0;r<l;r++){const r=1===t?_i(e):Ei(e),i=1===t?_i(e):Ei(e);c(e),d(e),u(e),a.fragmentLookupTable.push({timestamp:r,moofOffset:i})}a.fragmentLookupTable.sort((e,t)=>e.timestamp-t.timestamp);for(let e=0;e<a.fragmentLookupTable.length-1;e++){const t=a.fragmentLookupTable[e],r=a.fragmentLookupTable[e+1];t.timestamp===r.timestamp&&(a.fragmentLookupTable.splice(e+1,1),e--)}}break;case"moof":this.currentFragment={moofOffset:t,moofSize:r.totalSize,implicitBaseDataOffset:t,trackData:new Map},this.readContiguousBoxes(e.slice(a,r.contentSize)),this.lastReadFragment=this.currentFragment,this.currentFragment=null;break;case"traf":if(n(this.currentFragment),this.readContiguousBoxes(e.slice(a,r.contentSize)),this.currentTrack){const e=this.currentFragment.trackData.get(this.currentTrack.id);if(e){const{currentFragmentState:t}=this.currentTrack;n(t),null!==t.startTimestamp&&(yr(e,t.startTimestamp),e.startTimestampIsFinal=!0)}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case"tfhd":{n(this.currentFragment),e.skip(1);const t=Pi(e),r=Boolean(1&t),a=Boolean(2&t),i=Boolean(8&t),s=Boolean(16&t),o=Boolean(32&t),c=Boolean(65536&t),d=Boolean(131072&t),u=Ei(e),l=this.tracks.find(e=>e.id===u);if(!l)break;const h=this.fragmentTrackDefaults.find(e=>e.trackId===u);this.currentTrack=l,l.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:h?.defaultSampleDescriptionIndex??null,defaultSampleDuration:h?.defaultSampleDuration??null,defaultSampleSize:h?.defaultSampleSize??null,defaultSampleFlags:h?.defaultSampleFlags??null,startTimestamp:null},r?l.currentFragmentState.baseDataOffset=_i(e):d&&(l.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),a&&(l.currentFragmentState.sampleDescriptionIndex=Ei(e)),i&&(l.currentFragmentState.defaultSampleDuration=Ei(e)),s&&(l.currentFragmentState.defaultSampleSize=Ei(e)),o&&(l.currentFragmentState.defaultSampleFlags=Ei(e)),c&&(l.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{const t=this.currentTrack;if(!t)break;n(t.currentFragmentState);const r=Si(e);e.skip(3);const a=0===r?Ei(e):_i(e);t.currentFragmentState.startTimestamp=a}break;case"trun":{const t=this.currentTrack;if(!t)break;if(n(this.currentFragment),n(t.currentFragmentState),this.currentFragment.trackData.has(t.id)){console.warn("Can't have two trun boxes for the same track in one fragment. Ignoring...");break}const r=Si(e),a=Pi(e),i=Boolean(1&a),s=Boolean(4&a),o=Boolean(256&a),d=Boolean(512&a),u=Boolean(1024&a),l=Boolean(2048&a),h=Ei(e);let m=t.currentFragmentState.baseDataOffset;i&&(m+=Bi(e));let f=null;s&&(f=Ei(e));let p=m;if(0===h){this.currentFragment.implicitBaseDataOffset=p;break}let g=0;const k={track:t,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1};this.currentFragment.trackData.set(t.id,k);for(let a=0;a<h;a++){let i,s,c;o?i=Ei(e):(n(null!==t.currentFragmentState.defaultSampleDuration),i=t.currentFragmentState.defaultSampleDuration),d?s=Ei(e):(n(null!==t.currentFragmentState.defaultSampleSize),s=t.currentFragmentState.defaultSampleSize),u?c=Ei(e):(n(null!==t.currentFragmentState.defaultSampleFlags),c=t.currentFragmentState.defaultSampleFlags),0===a&&null!==f&&(c=f);let h=0;l&&(h=0===r?Ei(e):Bi(e));const m=!(65536&c);k.samples.push({presentationTimestamp:g+h,duration:i,byteOffset:p,byteSize:s,isKeyFrame:m}),p+=s,g+=i}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 a=k.presentationTimestamps[e+1];r.duration=a.presentationTimestamp-t.presentationTimestamp}}const b=k.samples[k.presentationTimestamps[0].sampleIndex],w=k.samples[c(k.presentationTimestamps).sampleIndex];k.startTimestamp=b.presentationTimestamp,k.endTimestamp=w.presentationTimestamp+w.duration,this.currentFragment.implicitBaseDataOffset=p}break;case"udta":{const t=this.iterateContiguousBoxes(e.slice(a,r.contentSize));for(const{boxInfo:e,slice:r}of t){if("meta"!==e.name&&!this.currentTrack){const t=r.filePos;this.metadataTags.raw??={},"©"===e.name[0]?this.metadataTags.raw[e.name]??=lr(r):this.metadataTags.raw[e.name]??=yi(r,e.contentSize),r.filePos=t}switch(e.name){case"meta":r.skip(-e.headerSize),this.traverseBox(r);break;case"©nam":case"name":this.currentTrack?this.currentTrack.name=p.decode(yi(r,e.contentSize)):this.metadataTags.title??=lr(r);break;case"©des":this.currentTrack||(this.metadataTags.description??=lr(r));break;case"©ART":this.currentTrack||(this.metadataTags.artist??=lr(r));break;case"©alb":this.currentTrack||(this.metadataTags.album??=lr(r));break;case"albr":this.currentTrack||(this.metadataTags.albumArtist??=lr(r));break;case"©gen":this.currentTrack||(this.metadataTags.genre??=lr(r));break;case"©day":if(!this.currentTrack){const e=new Date(lr(r));Number.isNaN(e.getTime())||(this.metadataTags.date??=e)}break;case"©cmt":this.currentTrack||(this.metadataTags.comment??=lr(r));break;case"©lyr":this.currentTrack||(this.metadataTags.lyrics??=lr(r))}}}break;case"meta":{if(this.currentTrack)break;const t=0!==Ei(e);this.currentMetadataKeys=new Map,t?this.readContiguousBoxes(e.slice(a,r.contentSize)):this.readContiguousBoxes(e.slice(a+4,r.contentSize-4)),this.currentMetadataKeys=null}break;case"keys":{if(!this.currentMetadataKeys)break;e.skip(4);const t=Ei(e);for(let r=0;r<t;r++){const t=Ei(e);e.skip(4);const a=p.decode(yi(e,t-8));this.currentMetadataKeys.set(r+1,a)}}break;case"ilst":{if(!this.currentMetadataKeys)break;const t=this.iterateContiguousBoxes(e.slice(a,r.contentSize));for(const{boxInfo:e,slice:r}of t){let t=e.name;const a=(t.charCodeAt(0)<<24)+(t.charCodeAt(1)<<16)+(t.charCodeAt(2)<<8)+t.charCodeAt(3);this.currentMetadataKeys.has(a)&&(t=this.currentMetadataKeys.get(a));const i=hr(r);switch(this.metadataTags.raw??={},this.metadataTags.raw[t]??=i,t){case"©nam":case"titl":case"com.apple.quicktime.title":case"title":"string"==typeof i&&(this.metadataTags.title??=i);break;case"©des":case"desc":case"dscp":case"com.apple.quicktime.description":case"description":"string"==typeof i&&(this.metadataTags.description??=i);break;case"©ART":case"com.apple.quicktime.artist":case"artist":"string"==typeof i&&(this.metadataTags.artist??=i);break;case"©alb":case"albm":case"com.apple.quicktime.album":case"album":"string"==typeof i&&(this.metadataTags.album??=i);break;case"aART":case"album_artist":"string"==typeof i&&(this.metadataTags.albumArtist??=i);break;case"©cmt":case"com.apple.quicktime.comment":case"comment":"string"==typeof i&&(this.metadataTags.comment??=i);break;case"©gen":case"gnre":case"com.apple.quicktime.genre":case"genre":"string"==typeof i&&(this.metadataTags.genre??=i);break;case"©lyr":case"lyrics":"string"==typeof i&&(this.metadataTags.lyrics??=i);break;case"©day":case"rldt":case"com.apple.quicktime.creationdate":case"date":if("string"==typeof i){const e=new Date(i);Number.isNaN(e.getTime())||(this.metadataTags.date??=e)}break;case"covr":case"com.apple.quicktime.artwork":i instanceof de?(this.metadataTags.images??=[],this.metadataTags.images.push({data:i.data,kind:"coverFront",mimeType:i.mimeType})):i instanceof Uint8Array&&(this.metadataTags.images??=[],this.metadataTags.images.push({data:i,kind:"coverFront",mimeType:"image/*"}));break;case"track":if("string"==typeof i){const e=i.split("/"),t=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(this.metadataTags.trackNumber??=t),r&&Number.isInteger(r)&&r>0&&(this.metadataTags.tracksTotal??=r)}break;case"trkn":if(i instanceof Uint8Array&&i.length>=6){const e=f(i),t=e.getUint16(2,!1),r=e.getUint16(4,!1);t>0&&(this.metadataTags.trackNumber??=t),r>0&&(this.metadataTags.tracksTotal??=r)}break;case"disc":case"disk":if(i instanceof Uint8Array&&i.length>=6){const e=f(i),t=e.getUint16(2,!1),r=e.getUint16(4,!1);t>0&&(this.metadataTags.discNumber??=t),r>0&&(this.metadataTags.discsTotal??=r)}}}}}return e.filePos=i,!0}}class fr{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 U(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,t){const r=this.mapTimestampIntoTimescale(e),a=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=kr(a,r),s=await this.fetchPacketForSampleIndex(i,t);return Cr(a)&&this.internalTrack.demuxer.isFragmented?this.performFragmentedLookup(null,e=>{const t=e.trackData.get(this.internalTrack.id);if(!t)return{sampleIndex:-1,correctSampleFound:!1};const a=B(t.presentationTimestamps,r,e=>e.presentationTimestamp);return{sampleIndex:-1!==a?t.presentationTimestamps[a].sampleIndex:-1,correctSampleFound:-1!==a&&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 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);if(a.sampleIndex+1<t.samples.length)return{sampleIndex:a.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),a=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=br(a,r),s=await this.fetchPacketForSampleIndex(i,t);return Cr(a)&&this.internalTrack.demuxer.isFragmented?this.performFragmentedLookup(null,e=>{const t=e.trackData.get(this.internalTrack.id);if(!t)return{sampleIndex:-1,correctSampleFound:!1};const a=M(t.presentationTimestamps,e=>t.samples[e.sampleIndex].isKeyFrame&&e.presentationTimestamp<=r);return{sampleIndex:-1!==a?t.presentationTimestamps[a].sampleIndex:-1,correctSampleFound:-1!==a&&r<t.endTimestamp}},r,r,t):s}async getNextKeyPacket(e,t){const r=this.packetToSampleIndex.get(e);if(void 0!==r){const e=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=Tr(e,r);return this.fetchPacketForSampleIndex(a,t)}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 t=e.trackData.get(this.internalTrack.id);if(t&&null!==t.firstKeyFrameTimestamp){const e=t.samples.findIndex(e=>e.isKeyFrame);return n(-1!==e),{sampleIndex:e,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async fetchPacketForSampleIndex(e,t){if(-1===e)return null;const r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=wr(r,e);if(!a)return null;let i;if(t.metadataOnly)i=Tt;else{let e=this.internalTrack.demuxer.reader.requestSlice(a.sampleOffset,a.sampleSize);e instanceof Promise&&(e=await e),n(e),i=yi(e,a.sampleSize)}const s=(a.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,o=a.duration/this.internalTrack.timescale,c=new yt(i,a.isKeyFrame?"key":"delta",s,o,e,a.sampleSize);return this.packetToSampleIndex.set(c,e),c}async fetchPacketInFragment(e,t,r){if(-1===t)return null;const a=e.trackData.get(this.internalTrack.id).samples[t];let i;if(n(a),r.metadataOnly)i=Tt;else{let e=this.internalTrack.demuxer.reader.requestSlice(a.byteOffset,a.byteSize);e instanceof Promise&&(e=await e),n(e),i=yi(e,a.byteSize)}const s=(a.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,o=a.duration/this.internalTrack.timescale,c=new yt(i,a.isKeyFrame?"key":"delta",s,o,e.moofOffset+t,a.byteSize);return this.packetToFragmentLocation.set(c,{fragment:e,sampleIndex:t}),c}async performFragmentedLookup(e,t,r,a,i){const s=this.internalTrack.demuxer;let o=null,c=null,d=-1;if(e){const{sampleIndex:r,correctSampleFound:a}=t(e);if(a)return this.fetchPacketInFragment(e,r,i);-1!==r&&(c=e,d=r)}const u=B(this.internalTrack.fragmentLookupTable,r,e=>e.timestamp),l=-1!==u?this.internalTrack.fragmentLookupTable[u]:null,h=B(this.internalTrack.fragmentPositionCache,r,e=>e.startTimestamp),m=-1!==h?this.internalTrack.fragmentPositionCache[h]:null,f=Math.max(l?.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=s.reader.requestSliceRange(p,8,nr);if(e instanceof Promise&&(e=await e),!e)break;const r=p,n=or(e);if(!n)break;if("moof"===n.name){o=await s.readFragment(r);const{sampleIndex:e,correctSampleFound:a}=t(o);if(a)return this.fetchPacketInFragment(o,e,i);-1!==e&&(c=o,d=e)}p=r+n.totalSize}if(l&&(!c||c.moofOffset<l.moofOffset)){const e=this.internalTrack.fragmentLookupTable[u-1];n(!e||e.timestamp<l.timestamp);const r=e?.timestamp??-1/0;return this.performFragmentedLookup(null,t,r,a,i)}return c?this.fetchPacketInFragment(c,d,i):null}}class pr extends fr{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??=(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&&ut(e.data)}}else{const e=await this.getFirstPacket({});this.internalTrack.info.vp9CodecInfo=e&&ct(e.data)}return{codec:Se(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 gr extends fr{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??={codec:Ce(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}}const kr=(e,t)=>{if(e.presentationTimestamps){const r=B(e.presentationTimestamps,t,e=>e.presentationTimestamp);return-1===r?-1:e.presentationTimestamps[r].sampleIndex}{const r=B(e.sampleTimingEntries,t,e=>e.startDecodeTimestamp);if(-1===r)return-1;const a=e.sampleTimingEntries[r];return a.startIndex+Math.min(Math.floor((t-a.startDecodeTimestamp)/a.delta),a.count-1)}},br=(e,t)=>{if(!e.keySampleIndices)return kr(e,t);if(e.presentationTimestamps){const r=B(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!==D(e.keySampleIndices,r,e=>e))return r}return-1}{const r=kr(e,t),a=B(e.keySampleIndices,r,e=>e);return e.keySampleIndices[a]??-1}},wr=(e,t)=>{const r=B(e.sampleTimingEntries,t,e=>e.startIndex),a=e.sampleTimingEntries[r];if(!a||a.startIndex+a.count<=t)return null;let i=a.startDecodeTimestamp+(t-a.startIndex)*a.delta;const s=B(e.sampleCompositionTimeOffsets,t,e=>e.startIndex),o=e.sampleCompositionTimeOffsets[s];o&&t-o.startIndex<o.count&&(i+=o.offset);const c=e.sampleSizes[Math.min(t,e.sampleSizes.length-1)],d=B(e.sampleToChunk,t,e=>e.startSampleIndex),u=e.sampleToChunk[d];n(u);const l=u.startChunkIndex+Math.floor((t-u.startSampleIndex)/u.samplesPerChunk),h=e.chunkOffsets[l],m=u.startSampleIndex+(l-u.startChunkIndex)*u.samplesPerChunk;let f=0,p=h;if(1===e.sampleSizes.length)p+=c*(t-m),f+=c*u.samplesPerChunk;else for(let r=m;r<m+u.samplesPerChunk;r++){const a=e.sampleSizes[r];r<t&&(p+=a),f+=a}let g=a.delta;if(e.presentationTimestamps){const r=e.presentationTimestampIndexMap[t];if(n(void 0!==r),r<e.presentationTimestamps.length-1){g=e.presentationTimestamps[r+1].presentationTimestamp-i}}return{presentationTimestamp:i,duration:g,sampleOffset:p,sampleSize:c,chunkOffset:h,chunkSize:f,isKeyFrame:!e.keySampleIndices||-1!==D(e.keySampleIndices,t,e=>e)}},Tr=(e,t)=>{if(!e.keySampleIndices)return t+1;const r=B(e.keySampleIndices,t,e=>e);return e.keySampleIndices[r+1]??-1},yr=(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},Sr=e=>{const[t,,,r]=e,a=Math.hypot(t,r),i=t/a,s=r/a,n=-Math.atan2(s,i)*(180/Math.PI);return Number.isFinite(n)?n:0},Cr=e=>0===e.sampleSizes.length;
|
|
56
91
|
/*!
|
|
57
92
|
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
58
93
|
*
|
|
@@ -60,6 +95,124 @@ class ue{constructor(e){this.value=e}}class le{constructor(e){this.value=e}}clas
|
|
|
60
95
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
61
96
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
62
97
|
*/
|
|
98
|
+
class vr{constructor(e){this.value=e}}class Pr{constructor(e){this.value=e}}class Ir{constructor(e){this.value=e}}class xr{constructor(e){this.value=e}}var Er;!function(e){e[e.EBML=440786851]="EBML",e[e.EBMLVersion=17030]="EBMLVersion",e[e.EBMLReadVersion=17143]="EBMLReadVersion",e[e.EBMLMaxIDLength=17138]="EBMLMaxIDLength",e[e.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",e[e.DocType=17026]="DocType",e[e.DocTypeVersion=17031]="DocTypeVersion",e[e.DocTypeReadVersion=17029]="DocTypeReadVersion",e[e.Void=236]="Void",e[e.Segment=408125543]="Segment",e[e.SeekHead=290298740]="SeekHead",e[e.Seek=19899]="Seek",e[e.SeekID=21419]="SeekID",e[e.SeekPosition=21420]="SeekPosition",e[e.Duration=17545]="Duration",e[e.Info=357149030]="Info",e[e.TimestampScale=2807729]="TimestampScale",e[e.MuxingApp=19840]="MuxingApp",e[e.WritingApp=22337]="WritingApp",e[e.Tracks=374648427]="Tracks",e[e.TrackEntry=174]="TrackEntry",e[e.TrackNumber=215]="TrackNumber",e[e.TrackUID=29637]="TrackUID",e[e.TrackType=131]="TrackType",e[e.FlagEnabled=185]="FlagEnabled",e[e.FlagDefault=136]="FlagDefault",e[e.FlagForced=21930]="FlagForced",e[e.FlagOriginal=21934]="FlagOriginal",e[e.FlagHearingImpaired=21931]="FlagHearingImpaired",e[e.FlagVisualImpaired=21932]="FlagVisualImpaired",e[e.FlagCommentary=21935]="FlagCommentary",e[e.FlagLacing=156]="FlagLacing",e[e.Name=21358]="Name",e[e.Language=2274716]="Language",e[e.LanguageBCP47=2274717]="LanguageBCP47",e[e.CodecID=134]="CodecID",e[e.CodecPrivate=25506]="CodecPrivate",e[e.CodecDelay=22186]="CodecDelay",e[e.SeekPreRoll=22203]="SeekPreRoll",e[e.DefaultDuration=2352003]="DefaultDuration",e[e.Video=224]="Video",e[e.PixelWidth=176]="PixelWidth",e[e.PixelHeight=186]="PixelHeight",e[e.AlphaMode=21440]="AlphaMode",e[e.Audio=225]="Audio",e[e.SamplingFrequency=181]="SamplingFrequency",e[e.Channels=159]="Channels",e[e.BitDepth=25188]="BitDepth",e[e.SimpleBlock=163]="SimpleBlock",e[e.BlockGroup=160]="BlockGroup",e[e.Block=161]="Block",e[e.BlockAdditions=30113]="BlockAdditions",e[e.BlockMore=166]="BlockMore",e[e.BlockAdditional=165]="BlockAdditional",e[e.BlockAddID=238]="BlockAddID",e[e.BlockDuration=155]="BlockDuration",e[e.ReferenceBlock=251]="ReferenceBlock",e[e.Cluster=524531317]="Cluster",e[e.Timestamp=231]="Timestamp",e[e.Cues=475249515]="Cues",e[e.CuePoint=187]="CuePoint",e[e.CueTime=179]="CueTime",e[e.CueTrackPositions=183]="CueTrackPositions",e[e.CueTrack=247]="CueTrack",e[e.CueClusterPosition=241]="CueClusterPosition",e[e.Colour=21936]="Colour",e[e.MatrixCoefficients=21937]="MatrixCoefficients",e[e.TransferCharacteristics=21946]="TransferCharacteristics",e[e.Primaries=21947]="Primaries",e[e.Range=21945]="Range",e[e.Projection=30320]="Projection",e[e.ProjectionType=30321]="ProjectionType",e[e.ProjectionPoseRoll=30325]="ProjectionPoseRoll",e[e.Attachments=423732329]="Attachments",e[e.AttachedFile=24999]="AttachedFile",e[e.FileDescription=18046]="FileDescription",e[e.FileName=18030]="FileName",e[e.FileMediaType=18016]="FileMediaType",e[e.FileData=18012]="FileData",e[e.FileUID=18094]="FileUID",e[e.Chapters=272869232]="Chapters",e[e.Tags=307544935]="Tags",e[e.Tag=29555]="Tag",e[e.Targets=25536]="Targets",e[e.TargetTypeValue=26826]="TargetTypeValue",e[e.TargetType=25546]="TargetType",e[e.TagTrackUID=25541]="TagTrackUID",e[e.TagEditionUID=25545]="TagEditionUID",e[e.TagChapterUID=25540]="TagChapterUID",e[e.TagAttachmentUID=25542]="TagAttachmentUID",e[e.SimpleTag=26568]="SimpleTag",e[e.TagName=17827]="TagName",e[e.TagLanguage=17530]="TagLanguage",e[e.TagString=17543]="TagString",e[e.TagBinary=17541]="TagBinary",e[e.ContentEncodings=28032]="ContentEncodings",e[e.ContentEncoding=25152]="ContentEncoding",e[e.ContentEncodingOrder=20529]="ContentEncodingOrder",e[e.ContentEncodingScope=20530]="ContentEncodingScope",e[e.ContentCompression=20532]="ContentCompression",e[e.ContentCompAlgo=16980]="ContentCompAlgo",e[e.ContentCompSettings=16981]="ContentCompSettings",e[e.ContentEncryption=20533]="ContentEncryption"}(Er||(Er={}));const Dr=[Er.EBML,Er.Segment],Br=[Er.SeekHead,Er.Info,Er.Cluster,Er.Tracks,Er.Cues,Er.Attachments,Er.Chapters,Er.Tags],Ar=[...Dr,...Br],_r=e=>e<256?1:e<65536?2:e<1<<24?3:e<2**32?4:e<2**40?5:6,Fr=e=>e<256n?1:e<65536n?2:e<1n<<24n?3:e<1n<<32n?4:e<1n<<40n?5:e<1n<<48n?6:e<1n<<56n?7:8,Mr=e=>e>=-64&&e<64?1:e>=-8192&&e<8192?2:e>=-1048576&&e<1<<20?3:e>=-134217728&&e<1<<27?4:e>=-17179869184&&e<2**34?5:6;class Rr{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=new WeakMap,this.dataOffsets=new WeakMap}writeByte(e){this.helperView.setUint8(0,e),this.writer.write(this.helper.subarray(0,1))}writeFloat32(e){this.helperView.setFloat32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeFloat64(e){this.helperView.setFloat64(0,e,!1),this.writer.write(this.helper)}writeUnsignedInt(e,t=_r(e)){let r=0;switch(t){case 6:this.helperView.setUint8(r++,e/2**40|0);case 5:this.helperView.setUint8(r++,e/2**32|0);case 4:this.helperView.setUint8(r++,e>>24);case 3:this.helperView.setUint8(r++,e>>16);case 2:this.helperView.setUint8(r++,e>>8);case 1:this.helperView.setUint8(r++,e);break;default:throw new Error("Bad unsigned int size "+t)}this.writer.write(this.helper.subarray(0,r))}writeUnsignedBigInt(e,t=Fr(e)){let r=0;for(let a=t-1;a>=0;a--)this.helperView.setUint8(r++,Number(e>>BigInt(8*a)&0xffn));this.writer.write(this.helper.subarray(0,r))}writeSignedInt(e,t=Mr(e)){e<0&&(e+=2**(8*t)),this.writeUnsignedInt(e,t)}writeVarInt(e,t=(e=>{if(e<127)return 1;if(e<16383)return 2;if(e<2097151)return 3;if(e<268435455)return 4;if(e<2**35-1)return 5;if(e<2**42-1)return 6;throw new Error("EBML varint size not supported "+e)})(e)){let r=0;switch(t){case 1:this.helperView.setUint8(r++,128|e);break;case 2:this.helperView.setUint8(r++,64|e>>8),this.helperView.setUint8(r++,e);break;case 3:this.helperView.setUint8(r++,32|e>>16),this.helperView.setUint8(r++,e>>8),this.helperView.setUint8(r++,e);break;case 4:this.helperView.setUint8(r++,16|e>>24),this.helperView.setUint8(r++,e>>16),this.helperView.setUint8(r++,e>>8),this.helperView.setUint8(r++,e);break;case 5:this.helperView.setUint8(r++,8|e/2**32&7),this.helperView.setUint8(r++,e>>24),this.helperView.setUint8(r++,e>>16),this.helperView.setUint8(r++,e>>8),this.helperView.setUint8(r++,e);break;case 6:this.helperView.setUint8(r++,4|e/2**40&3),this.helperView.setUint8(r++,e/2**32|0),this.helperView.setUint8(r++,e>>24),this.helperView.setUint8(r++,e>>16),this.helperView.setUint8(r++,e>>8),this.helperView.setUint8(r++,e);break;default:throw new Error("Bad EBML varint size "+t)}this.writer.write(this.helper.subarray(0,r))}writeAsciiString(e){this.writer.write(new Uint8Array(e.split("").map(e=>e.charCodeAt(0))))}writeEBML(e){if(null!==e)if(e instanceof Uint8Array)this.writer.write(e);else if(Array.isArray(e))for(const t of e)this.writeEBML(t);else if(this.offsets.set(e,this.writer.getPos()),this.writeUnsignedInt(e.id),Array.isArray(e.data)){const t=this.writer.getPos(),r=-1===e.size?1:e.size??4;-1===e.size?this.writeByte(255):this.writer.seek(this.writer.getPos()+r);const a=this.writer.getPos();if(this.dataOffsets.set(e,a),this.writeEBML(e.data),-1!==e.size){const e=this.writer.getPos()-a,i=this.writer.getPos();this.writer.seek(t),this.writeVarInt(e,r),this.writer.seek(i)}}else if("number"==typeof e.data){const t=e.size??_r(e.data);this.writeVarInt(t),this.writeUnsignedInt(e.data,t)}else if("bigint"==typeof e.data){const t=e.size??Fr(e.data);this.writeVarInt(t),this.writeUnsignedBigInt(e.data,t)}else if("string"==typeof e.data)this.writeVarInt(e.data.length),this.writeAsciiString(e.data);else if(e.data instanceof Uint8Array)this.writeVarInt(e.data.byteLength,e.size),this.writer.write(e.data);else if(e.data instanceof vr)this.writeVarInt(4),this.writeFloat32(e.data.value);else if(e.data instanceof Pr)this.writeVarInt(8),this.writeFloat64(e.data.value);else if(e.data instanceof Ir){const t=e.size??Mr(e.data.value);this.writeVarInt(t),this.writeSignedInt(e.data.value,t)}else if(e.data instanceof xr){const t=g.encode(e.data.value);this.writeVarInt(t.length),this.writer.write(t)}else R(e.data)}}const zr=16,Or=e=>{const t=Si(e);if(e.skip(-1),0===t)return null;let r=1,a=128;for(;0===(t&a);)r++,a>>=1;return r},Nr=e=>{const t=Si(e);if(0===t)return null;let r=1,a=128;for(;0===(t&a);)r++,a>>=1;let i=t&a-1;for(let t=1;t<r;t++)i*=256,i+=Si(e);return i},Lr=(e,t)=>{if(t<1||t>8)throw new Error("Bad unsigned int size "+t);let r=0;for(let a=0;a<t;a++)r*=256,r+=Si(e);return r},Ur=e=>{const t=Or(e);if(null===t)return null;return Lr(e,t)},Vr=e=>{let t=Si(e);return 255===t?t=null:(e.skip(-1),t=Nr(e),72057594037927940===t&&(t=null)),t},Wr=e=>{const t=Ur(e);if(null===t)return null;return{id:t,size:Vr(e)}},Hr=(e,t)=>{const r=yi(e,t);let a=0;for(;a<t&&0!==r[a];)a+=1;return String.fromCharCode(...r.subarray(0,a))},qr=(e,t)=>{const r=yi(e,t);let a=0;for(;a<t&&0!==r[a];)a+=1;return p.decode(r.subarray(0,a))},jr=(e,t)=>{if(0===t)return 0;if(4!==t&&8!==t)throw new Error("Bad float size "+t);return 4===t?Ri(e):zi(e)},$r=async(e,t,r,a)=>{const i=new Set(r);let s=t;for(;null===a||s<a;){let t=e.requestSliceRange(s,2,zr);if(t instanceof Promise&&(t=await t),!t)break;const r=Wr(t);if(!r)break;if(i.has(r.id))return{pos:s,found:!0};Gr(r.size),s=t.filePos+r.size}return{pos:null!==a&&a>s?a:s,found:!1}},Qr=async(e,t,r,a)=>{const i=new Set(r);let s=t;for(;s<a;){let t=e.requestSliceRange(s,0,Math.min(65536,a-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=Ur(t);if(null!==e&&i.has(e))return s;s++}}return null},Kr={avc:"V_MPEG4/ISO/AVC",hevc:"V_MPEGH/ISO/HEVC",vp8:"V_VP8",vp9:"V_VP9",av1:"V_AV1",aac:"A_AAC",mp3:"A_MPEG/L3",opus:"A_OPUS",vorbis:"A_VORBIS",flac:"A_FLAC","pcm-u8":"A_PCM/INT/LIT","pcm-s16":"A_PCM/INT/LIT","pcm-s16be":"A_PCM/INT/BIG","pcm-s24":"A_PCM/INT/LIT","pcm-s24be":"A_PCM/INT/BIG","pcm-s32":"A_PCM/INT/LIT","pcm-s32be":"A_PCM/INT/BIG","pcm-f32":"A_PCM/FLOAT/IEEE","pcm-f64":"A_PCM/FLOAT/IEEE",webvtt:"S_TEXT/WEBVTT"};function Gr(e){if(null===e)throw new Error("Undefined element size is used in a place where it is not supported.")}
|
|
99
|
+
/*!
|
|
100
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
101
|
+
*
|
|
102
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
103
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
104
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
105
|
+
*/const Xr=e=>{let t=(e.hasVideo?"video/":e.hasAudio?"audio/":"application/")+(e.isWebM?"webm":"x-matroska");if(e.codecStrings.length>0){t+=`; codecs="${[...new Set(e.codecStrings.filter(Boolean))].join(", ")}"`}return t};
|
|
106
|
+
/*!
|
|
107
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
108
|
+
*
|
|
109
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
110
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
111
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
112
|
+
*/var Yr,Jr,Zr;!function(e){e[e.None=0]="None",e[e.Xiph=1]="Xiph",e[e.FixedSize=2]="FixedSize",e[e.Ebml=3]="Ebml"}(Yr||(Yr={})),function(e){e[e.Block=1]="Block",e[e.Private=2]="Private",e[e.Next=4]="Next"}(Jr||(Jr={})),function(e){e[e.Zlib=0]="Zlib",e[e.Bzlib=1]="Bzlib",e[e.lzo1x=2]="lzo1x",e[e.HeaderStripping=3]="HeaderStripping"}(Zr||(Zr={}));const ea=[{id:Er.SeekHead,flag:"seekHeadSeen"},{id:Er.Info,flag:"infoSeen"},{id:Er.Tracks,flag:"tracksSeen"},{id:Er.Cues,flag:"cuesSeen"}],ta=10485760;class ra extends kt{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 Xr({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 e of this.segments)e.metadataTagsCollected||(null!==this.reader.fileSize&&await this.loadSegmentMetadata(e),e.metadataTagsCollected=!0);let e={};for(const t of this.segments)e={...e,...t.metadataTags};return e}readMetadata(){return this.readMetadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,2,zr);if(t instanceof Promise&&(t=await t),!t)break;const r=Wr(t);if(!r)break;const a=r.id;let i=r.size;const s=t.filePos;if(a===Er.EBML){Gr(i);let e=this.reader.requestSlice(s,i);if(e instanceof Promise&&(e=await e),!e)break;this.readContiguousElements(e)}else if(a===Er.Segment){if(await this.readSegment(s,i),null===i)break;if(null===this.reader.fileSize)break}else if(a===Er.Cluster){if(null===this.reader.fileSize)break;if(null===i){i=(await $r(this.reader,s,Ar,this.reader.fileSize)).pos-s}const e=c(this.segments);e&&(e.elementEndPos=s+i)}Gr(i),e=s+i}})()}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:null===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,zr);if(e instanceof Promise&&(e=await e),!e)break;const t=r,a=Wr(e);if(!a||!Br.includes(a.id)&&a.id!==Er.Void){const e=await Qr(this.reader,t,Br,Math.min(this.currentSegment.elementEndPos??1/0,t+ta));if(e){r=e;continue}break}const{id:i,size:s}=a,n=e.filePos,o=ea.findIndex(e=>e.id===i);if(-1!==o){const e=ea[o].flag;this.currentSegment[e]=!0,Gr(s);let t=this.reader.requestSlice(n,s);t instanceof Promise&&(t=await t),t&&this.readContiguousElements(t)}else if(i===Er.Tags||i===Er.Attachments){i===Er.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,Gr(s);let e=this.reader.requestSlice(n,s);e instanceof Promise&&(e=await e),e&&this.readContiguousElements(e)}else if(i===Er.Cluster){this.currentSegment.clusterSeekStartPos=t;break}if(null===s)break;r=n+s}if(this.currentSegment.seekEntries.sort((e,t)=>e.segmentPosition-t.segmentPosition),null!==this.reader.fileSize)for(const t of this.currentSegment.seekEntries){const r=ea.find(e=>e.id===t.id);if(!r)continue;if(this.currentSegment[r.flag])continue;let a=this.reader.requestSliceRange(e+t.segmentPosition,2,zr);if(a instanceof Promise&&(a=await a),!a)continue;const i=Wr(a);if(!i)continue;const{id:s,size:n}=i;if(s!==r.id)continue;Gr(n),this.currentSegment[r.flag]=!0;let o=this.reader.requestSlice(a.filePos,n);o instanceof Promise&&(o=await o),o&&this.readContiguousElements(o)}-1===this.currentSegment.timestampScale&&(this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1e3),this.currentSegment.tracks.sort((e,t)=>Number(t.disposition.default)-Number(e.disposition.default));const a=new Map(this.currentSegment.tracks.map(e=>[e.id,e]));for(const e of this.currentSegment.cuePoints){const t=a.get(e.trackId);t&&t.cuePoints.push(e)}for(const e of this.currentSegment.tracks){e.cuePoints.sort((e,t)=>e.time-t.time);for(let t=0;t<e.cuePoints.length-1;t++){const r=e.cuePoints[t],a=e.cuePoints[t+1];r.time===a.time&&(e.cuePoints.splice(t+1,1),t--)}}let i=null,s=-1/0;for(const e of this.currentSegment.tracks)e.cuePoints.length>s&&(s=e.cuePoints.length,i=e);for(const e of this.currentSegment.tracks)0===e.cuePoints.length&&(e.cuePoints=i.cuePoints);this.currentSegment=null}async readCluster(e,t){if(t.lastReadCluster?.elementStartPos===e)return t.lastReadCluster;let r=this.reader.requestSliceRange(e,2,zr);r instanceof Promise&&(r=await r),n(r);const a=e,i=Wr(r);n(i);n(i.id===Er.Cluster);let s=i.size;const o=r.filePos;if(null===s){s=(await $r(this.reader,o,Ar,t.elementEndPos)).pos-o}let d=this.reader.requestSlice(o,s);d instanceof Promise&&(d=await d);const u={segment:t,elementStartPos:a,elementEndPos:o+s,dataStartPos:o,timestamp:-1,trackData:new Map};if(this.currentCluster=u,d){const e=this.readContiguousElements(d,Ar);u.elementEndPos=e}for(const[,e]of u.trackData){const t=e.track;n(e.blocks.length>0);let r=!1;for(let t=0;t<e.blocks.length;t++){const a=e.blocks[t];a.timestamp+=u.timestamp,r||=a.lacing!==Yr.None}e.presentationTimestamps=e.blocks.map((e,t)=>({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp);for(let r=0;r<e.presentationTimestamps.length;r++){const a=e.presentationTimestamps[r],i=e.blocks[a.blockIndex];if(null===e.firstKeyFrameTimestamp&&i.isKeyFrame&&(e.firstKeyFrameTimestamp=i.timestamp),r<e.presentationTimestamps.length-1){const t=e.presentationTimestamps[r+1];i.duration=t.timestamp-i.timestamp}else 0===i.duration&&null!=t.defaultDuration&&i.lacing===Yr.None&&(i.duration=t.defaultDuration)}r&&(this.expandLacedBlocks(e.blocks,t),e.presentationTimestamps=e.blocks.map((e,t)=>({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp));const i=e.blocks[e.presentationTimestamps[0].blockIndex],s=e.blocks[c(e.presentationTimestamps).blockIndex];e.startTimestamp=i.timestamp,e.endTimestamp=s.timestamp+s.duration;const o=B(t.clusterPositionCache,e.startTimestamp,e=>e.startTimestamp);-1!==o&&t.clusterPositionCache[o].elementStartPos===a||t.clusterPositionCache.splice(o+1,0,{elementStartPos:u.elementStartPos,startTimestamp:e.startTimestamp})}return t.lastReadCluster=u,u}getTrackDataInCluster(e,t){let r=e.trackData.get(t);if(!r){const a=e.segment.tracks.find(e=>e.id===t);if(!a)return null;r={track:a,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},e.trackData.set(t,r)}return r}expandLacedBlocks(e,t){for(let r=0;r<e.length;r++){const a=e[r];if(a.lacing===Yr.None)continue;a.decoded||(a.data=this.decodeBlockData(t,a.data),a.decoded=!0);const i=wi.tempFromBytes(a.data),s=[],o=Si(i)+1;switch(a.lacing){case Yr.Xiph:{let e=0;for(let t=0;t<o-1;t++){let t=0;for(;i.bufferPos<i.length;){const r=Si(i);if(t+=r,r<255){s.push(t),e+=t;break}}}s.push(i.length-(i.bufferPos+e))}break;case Yr.FixedSize:{const e=i.length-1,t=Math.floor(e/o);for(let e=0;e<o;e++)s.push(t)}break;case Yr.Ebml:{const e=Nr(i);n(null!==e);let t=e;s.push(t);let r=t;for(let e=1;e<o-1;e++){const e=i.bufferPos,a=Nr(i);n(null!==a);t+=a-((1<<7*(i.bufferPos-e)-1)-1),s.push(t),r+=t}s.push(i.length-(i.bufferPos+r))}break;default:n(!1)}n(s.length===o),e.splice(r,1);const c=a.duration||o*(t.defaultDuration??0);for(let t=0;t<o;t++){const n=s[t],d=yi(i,n),u=a.timestamp+c*t/o,l=c/o;e.splice(r+t,0,{timestamp:u,duration:l,isKeyFrame:a.isKeyFrame,data:d,lacing:Yr.None,decoded:!0,mainAdditional:a.mainAdditional})}r+=o,r--}}async loadSegmentMetadata(e){for(const t of e.seekEntries){if(t.id!==Er.Tags||e.tagsSeen){if(t.id!==Er.Attachments||e.attachmentsSeen)continue}else;let r=this.reader.requestSliceRange(e.dataStartPos+t.segmentPosition,2,zr);if(r instanceof Promise&&(r=await r),!r)continue;const a=Wr(r);if(!a||a.id!==t.id)continue;const{size:i}=a;Gr(i),n(!this.currentSegment),this.currentSegment=e;let s=this.reader.requestSlice(r.filePos,i);s instanceof Promise&&(s=await s),s&&this.readContiguousElements(s),this.currentSegment=null,t.id===Er.Tags?e.tagsSeen=!0:t.id===Er.Attachments&&(e.attachmentsSeen=!0)}}readContiguousElements(e,t){const r=e.filePos;for(;e.filePos-r<=e.length-2;){const r=e.filePos;if(!this.traverseElement(e,t))return r}return e.filePos}traverseElement(e,t){const r=Wr(e);if(!r)return!1;if(t&&t.includes(r.id))return!1;const{id:a,size:i}=r,s=e.filePos;switch(Gr(i),a){case Er.DocType:this.isWebM="webm"===Hr(e,i);break;case Er.Seek:{if(!this.currentSegment)break;const t={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(t),this.readContiguousElements(e.slice(s,i)),-1!==t.id&&-1!==t.segmentPosition||this.currentSegment.seekEntries.pop()}break;case Er.SeekID:{const t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.id=Lr(e,i)}break;case Er.SeekPosition:{const t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.segmentPosition=Lr(e,i)}break;case Er.TimestampScale:if(!this.currentSegment)break;this.currentSegment.timestampScale=Lr(e,i),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale;break;case Er.Duration:if(!this.currentSegment)break;this.currentSegment.duration=jr(e,i);break;case Er.TrackEntry:if(!this.currentSegment)break;if(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...le},inputTrack:null,codecId:null,codecPrivate:null,defaultDuration:null,name:null,languageCode:L,decodingInstructions:[],info:null},this.readContiguousElements(e.slice(s,i)),this.currentTrack.decodingInstructions.some(e=>"decompress"!==e.data?.type||e.scope!==Jr.Block||e.data.algorithm!==Zr.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===Kr.avc?(this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===Kr.hevc?(this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Kr.vp8?this.currentTrack.info.codec="vp8":t===Kr.vp9?this.currentTrack.info.codec="vp9":t===Kr.av1&&(this.currentTrack.info.codec="av1");const e=this.currentTrack,r=new ar(this.input,new ia(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===Kr.aac?(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===Kr.mp3?this.currentTrack.info.codec="mp3":t===Kr.opus?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=xe):t===Kr.vorbis?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Kr.flac?(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 ir(this.input,new sa(e));this.currentTrack.inputTrack=r,this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null;break;case Er.TrackNumber:if(!this.currentTrack)break;this.currentTrack.id=Lr(e,i);break;case Er.TrackType:{if(!this.currentTrack)break;const t=Lr(e,i);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 Er.FlagEnabled:if(!this.currentTrack)break;Lr(e,i)||(this.currentSegment.tracks.pop(),this.currentTrack=null);break;case Er.FlagDefault:if(!this.currentTrack)break;this.currentTrack.disposition.default=!!Lr(e,i);break;case Er.FlagForced:if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!Lr(e,i);break;case Er.FlagOriginal:if(!this.currentTrack)break;this.currentTrack.disposition.original=!!Lr(e,i);break;case Er.FlagHearingImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!Lr(e,i);break;case Er.FlagVisualImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!Lr(e,i);break;case Er.FlagCommentary:if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!Lr(e,i);break;case Er.CodecID:if(!this.currentTrack)break;this.currentTrack.codecId=Hr(e,i);break;case Er.CodecPrivate:if(!this.currentTrack)break;this.currentTrack.codecPrivate=yi(e,i);break;case Er.DefaultDuration:if(!this.currentTrack)break;this.currentTrack.defaultDuration=this.currentTrack.segment.timestampFactor*Lr(e,i)/1e9;break;case Er.Name:if(!this.currentTrack)break;this.currentTrack.name=qr(e,i);break;case Er.Language:if(!this.currentTrack)break;if(this.currentTrack.languageCode!==L)break;this.currentTrack.languageCode=Hr(e,i),H(this.currentTrack.languageCode)||(this.currentTrack.languageCode=L);break;case Er.LanguageBCP47:{if(!this.currentTrack)break;const t=Hr(e,i).split("-")[0];this.currentTrack.languageCode=t||L}break;case Er.Video:if("video"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(s,i));break;case Er.PixelWidth:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.width=Lr(e,i);break;case Er.PixelHeight:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.height=Lr(e,i);break;case Er.AlphaMode:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.alphaMode=1===Lr(e,i);break;case Er.Colour:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.colorSpace={},this.readContiguousElements(e.slice(s,i));break;case Er.MatrixCoefficients:{if("video"!==this.currentTrack?.info?.type||!this.currentTrack.info.colorSpace)break;const t=Lr(e,i),r=C[t]??null;this.currentTrack.info.colorSpace.matrix=r}break;case Er.Range:if("video"!==this.currentTrack?.info?.type||!this.currentTrack.info.colorSpace)break;this.currentTrack.info.colorSpace.fullRange=2===Lr(e,i);break;case Er.TransferCharacteristics:{if("video"!==this.currentTrack?.info?.type||!this.currentTrack.info.colorSpace)break;const t=Lr(e,i),r=y[t]??null;this.currentTrack.info.colorSpace.transfer=r}break;case Er.Primaries:{if("video"!==this.currentTrack?.info?.type||!this.currentTrack.info.colorSpace)break;const t=Lr(e,i),r=w[t]??null;this.currentTrack.info.colorSpace.primaries=r}break;case Er.Projection:if("video"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(s,i));break;case Er.ProjectionPoseRoll:{if("video"!==this.currentTrack?.info?.type)break;const t=-jr(e,i);try{this.currentTrack.info.rotation=o(t)}catch{}}break;case Er.Audio:if("audio"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(s,i));break;case Er.SamplingFrequency:if("audio"!==this.currentTrack?.info?.type)break;this.currentTrack.info.sampleRate=jr(e,i);break;case Er.Channels:if("audio"!==this.currentTrack?.info?.type)break;this.currentTrack.info.numberOfChannels=Lr(e,i);break;case Er.BitDepth:if("audio"!==this.currentTrack?.info?.type)break;this.currentTrack.info.bitDepth=Lr(e,i);break;case Er.CuePoint:if(!this.currentSegment)break;this.readContiguousElements(e.slice(s,i)),this.currentCueTime=null;break;case Er.CueTime:this.currentCueTime=Lr(e,i);break;case Er.CueTrackPositions:{if(null===this.currentCueTime)break;n(this.currentSegment);const t={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(t),this.readContiguousElements(e.slice(s,i)),-1!==t.trackId&&-1!==t.clusterPosition||this.currentSegment.cuePoints.pop()}break;case Er.CueTrack:{const t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;t.trackId=Lr(e,i)}break;case Er.CueClusterPosition:{const t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;n(this.currentSegment),t.clusterPosition=this.currentSegment.dataStartPos+Lr(e,i)}break;case Er.Timestamp:if(!this.currentCluster)break;this.currentCluster.timestamp=Lr(e,i);break;case Er.SimpleBlock:{if(!this.currentCluster)break;const t=Nr(e);if(null===t)break;const r=this.getTrackDataInCluster(this.currentCluster,t);if(!r)break;const a=Ii(e),n=Si(e),o=n>>1&3;let c=!!(128&n);"audio"===r.track.info?.type&&r.track.info.codec&&(c=!0);const d=yi(e,i-(e.filePos-s)),u=r.track.decodingInstructions.length>0;r.blocks.push({timestamp:a,duration:0,isKeyFrame:c,data:d,lacing:o,decoded:!u,mainAdditional:null})}break;case Er.BlockGroup:if(!this.currentCluster)break;this.readContiguousElements(e.slice(s,i)),this.currentBlock=null;break;case Er.Block:{if(!this.currentCluster)break;const t=Nr(e);if(null===t)break;const r=this.getTrackDataInCluster(this.currentCluster,t);if(!r)break;const a=Ii(e),n=Si(e)>>1&3,o=yi(e,i-(e.filePos-s)),c=r.track.decodingInstructions.length>0;this.currentBlock={timestamp:a,duration:0,isKeyFrame:!0,data:o,lacing:n,decoded:!c,mainAdditional:null},r.blocks.push(this.currentBlock)}break;case Er.BlockAdditions:this.readContiguousElements(e.slice(s,i));break;case Er.BlockMore:if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(s,i)),this.currentBlockAdditional.data&&1===this.currentBlockAdditional.addId&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null;break;case Er.BlockAdditional:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=yi(e,i);break;case Er.BlockAddID:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=Lr(e,i);break;case Er.BlockDuration:if(!this.currentBlock)break;this.currentBlock.duration=Lr(e,i);break;case Er.ReferenceBlock:if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1;break;case Er.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(s,i));break;case Er.Targets:this.readContiguousElements(e.slice(s,i));break;case Er.TargetTypeValue:50!==Lr(e,i)&&(this.currentTagTargetIsMovie=!1);break;case Er.TagTrackUID:case Er.TagEditionUID:case Er.TagChapterUID:case Er.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case Er.SimpleTag:if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(s,i));break;case Er.TagName:this.currentSimpleTagName=qr(e,i);break;case Er.TagString:{if(!this.currentSimpleTagName)break;const t=qr(e,i);this.processTagValue(this.currentSimpleTagName,t)}break;case Er.TagBinary:{if(!this.currentSimpleTagName)break;const t=yi(e,i);this.processTagValue(this.currentSimpleTagName,t)}break;case Er.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(s,i));const t=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(t.raw??={},t.raw[this.currentAttachedFile.fileUid.toString()]=new ue(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.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 Er.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 a=0;a<t;a++)r<<=8n,r+=BigInt(Si(e));return r})(e,i);break;case Er.FileName:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=qr(e,i);break;case Er.FileMediaType:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=Hr(e,i);break;case Er.FileData:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=yi(e,i);break;case Er.FileDescription:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=qr(e,i);break;case Er.ContentEncodings:if(!this.currentTrack)break;this.readContiguousElements(e.slice(s,i)),this.currentTrack.decodingInstructions.sort((e,t)=>t.order-e.order);break;case Er.ContentEncoding:this.currentDecodingInstruction={order:0,scope:Jr.Block,data:null},this.readContiguousElements(e.slice(s,i)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case Er.ContentEncodingOrder:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=Lr(e,i);break;case Er.ContentEncodingScope:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=Lr(e,i);break;case Er.ContentCompression:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:Zr.Zlib,settings:null},this.readContiguousElements(e.slice(s,i));break;case Er.ContentCompAlgo:if("decompress"!==this.currentDecodingInstruction?.data?.type)break;this.currentDecodingInstruction.data.algorithm=Lr(e,i);break;case Er.ContentCompSettings:if("decompress"!==this.currentDecodingInstruction?.data?.type)break;this.currentDecodingInstruction.data.settings=yi(e,i);break;case Er.ContentEncryption:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}return e.filePos=s+i,!0}decodeBlockData(e,t){n(e.decodingInstructions.length>0);let r=t;for(const t of e.decodingInstructions)if(n(t.data),"decompress"===t.data.type)if(t.data.algorithm===Zr.HeaderStripping)if(t.data.settings&&t.data.settings.length>0){const e=t.data.settings,a=new Uint8Array(e.length+r.length);a.set(e,0),a.set(r,e.length),r=a}return r}processTagValue(e,t){if(!this.currentSegment?.metadataTags)return;const r=this.currentSegment.metadataTags;if(r.raw??={},r.raw[e]??=t,"string"==typeof t)switch(e.toLowerCase()){case"title":r.title??=t;break;case"description":r.description??=t;break;case"artist":r.artist??=t;break;case"album":r.album??=t;break;case"album_artist":r.albumArtist??=t;break;case"genre":r.genre??=t;break;case"comment":r.comment??=t;break;case"lyrics":r.lyrics??=t;break;case"date":{const e=new Date(t);Number.isNaN(e.getTime())||(r.date??=e)}break;case"track_number":case"part_number":{const e=t.split("/"),a=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(a)&&a>0&&(r.trackNumber??=a),i&&Number.isInteger(i)&&i>0&&(r.tracksTotal??=i)}break;case"disc_number":case"disc":{const e=t.split("/"),a=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(a)&&a>0&&(r.discNumber??=a),i&&Number.isInteger(i)&&i>0&&(r.discsTotal??=i)}}}}class aa{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 U(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 a=B(t.presentationTimestamps,r,e=>e.timestamp);return{blockIndex:-1!==a?t.presentationTimestamps[a].blockIndex:-1,correctBlockFound:-1!==a&&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 a=M(t.presentationTimestamps,e=>t.blocks[e.blockIndex].isKeyFrame&&e.timestamp<=r);return{blockIndex:-1!==a?t.presentationTimestamps[a].blockIndex:-1,correctBlockFound:-1!==a&&r<t.endTimestamp}},r,r,t)}async getNextKeyPacket(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).blocks.findIndex((e,t)=>e.isKeyFrame&&t>r.blockIndex);if(-1!==t)return{blockIndex:t,correctBlockFound:!0}}else{const t=e.trackData.get(this.internalTrack.id);if(t&&null!==t.firstKeyFrameTimestamp){const e=t.blocks.findIndex(e=>e.isKeyFrame);return n(-1!==e),{blockIndex:e,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async fetchPacketInCluster(e,t,r){if(-1===t)return null;const a=e.trackData.get(this.internalTrack.id).blocks[t];n(a),a.decoded||(a.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,a.data),a.decoded=!0);const i=r.metadataOnly?Tt:a.data,s=a.timestamp/this.internalTrack.segment.timestampFactor,o=a.duration/this.internalTrack.segment.timestampFactor,c={};a.mainAdditional&&"video"===this.internalTrack.info?.type&&this.internalTrack.info.alphaMode&&(c.alpha=r.metadataOnly?Tt:a.mainAdditional,c.alphaByteLength=a.mainAdditional.byteLength);const d=new yt(i,a.isKeyFrame?"key":"delta",s,o,e.dataStartPos+t,a.data.byteLength,c);return this.packetToClusterLocation.set(d,{cluster:e,blockIndex:t}),d}async performClusterLookup(e,t,r,a,i){const{demuxer:s,segment:o}=this.internalTrack;let c=null,d=null,u=-1;if(e){const{blockIndex:r,correctBlockFound:a}=t(e);if(a)return this.fetchPacketInCluster(e,r,i);-1!==r&&(d=e,u=r)}const l=B(this.internalTrack.cuePoints,r,e=>e.time),h=-1!==l?this.internalTrack.cuePoints[l]:null,m=B(this.internalTrack.clusterPositionCache,r,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=s.reader.requestSliceRange(g,2,zr);if(e instanceof Promise&&(e=await e),!e)break;const r=g,l=Wr(e);if(!l||!Br.includes(l.id)&&l.id!==Er.Void){const e=await Qr(s.reader,r,Br,Math.min(o.elementEndPos??1/0,r+ta));if(e){g=e;continue}break}const h=l.id;let m=l.size;const f=e.filePos;if(h===Er.Cluster){c=await s.readCluster(r,o),m=c.elementEndPos-f;const{blockIndex:e,correctBlockFound:a}=t(c);if(a)return this.fetchPacketInCluster(c,e,i);-1!==e&&(d=c,u=e)}if(null===m){n(h!==Er.Cluster);m=(await $r(s.reader,f,Ar,o.elementEndPos)).pos-f}const p=f+m;if(null===o.elementEndPos){let e=s.reader.requestSliceRange(p,2,zr);if(e instanceof Promise&&(e=await e),!e)break;if(Ur(e)===Er.Segment){o.elementEndPos=p;break}}g=p}if(h&&(!d||d.elementStartPos<h.clusterPosition)){const e=this.internalTrack.cuePoints[l-1];n(!e||e.time<h.time);const r=e?.time??-1/0;return this.performClusterLookup(null,t,r,a,i)}return d?this.fetchPacketInCluster(d,u,i):null}}class ia extends aa{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??=(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:Se({width:this.internalTrack.info.width,height:this.internalTrack.info.height,codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,colorSpace:this.internalTrack.info.colorSpace,avcType:1,avcCodecInfo:"avc"===this.internalTrack.info.codec&&e?Xe(e.data):null,hevcCodecInfo:"hevc"===this.internalTrack.info.codec&&e?et(e.data):null,vp9CodecInfo:"vp9"===this.internalTrack.info.codec&&e?ct(e.data):null,av1CodecInfo:"av1"===this.internalTrack.info.codec&&e?ut(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 sa extends aa{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??={codec:Ce({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}}
|
|
113
|
+
/*!
|
|
114
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
115
|
+
*
|
|
116
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
117
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
118
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
119
|
+
*/const na=[44100,48e3,32e3],oa=[-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],ca=(e,t)=>{const r=e>>>24,a=e>>>16&255,i=e>>>8&255,s=255&e;if(255!==r&&255!==a&&255!==i&&255!==s)return{header:null,bytesAdvanced:4};if(255!==r)return{header:null,bytesAdvanced:1};if(224&~a)return{header:null,bytesAdvanced:1};let n=0,o=0;16&a?n=8&a?0:1:(n=1,o=1);const c=a>>3&3,d=a>>1&3,u=(i>>2&3)%3,l=s>>6&3,h=s>>4&3,m=s>>3&1,f=s>>2&1,p=3&s,g=oa[16*n*4+16*d+(i>>4&15)];if(-1===g)return{header:null,bytesAdvanced:1};const k=1e3*g,b=na[u]>>n+o,w=((e,t,r,a,i)=>0===t?0:1===t?Math.floor(144*r/(a<<e))+i:2===t?Math.floor(144*r/a)+i:4*(Math.floor(12*r/a)+i))(n,d,k,b,i>>1&1);if(null!==t&&t<w)return{header:null,bytesAdvanced:1};let T;return T=3===c?3===d?384:1152:3===d?384:2===d?1152:576,{header:{totalSize:w,mpegVersionId:c,layer:d,bitrate:k,frequencyIndex:u,sampleRate:b,channel:l,modeExtension:h,copyright:m,original:f,emphasis:p,audioSamplesInFrame:T},bytesAdvanced:1}},da=e=>{let t=2130706432,r=0;for(;0!==t;)r>>=1,r|=e&t,t>>=8;return r};
|
|
120
|
+
/*!
|
|
121
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
122
|
+
*
|
|
123
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
124
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
125
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
126
|
+
*/
|
|
127
|
+
var ua,la;!function(e){e[e.Unsynchronisation=128]="Unsynchronisation",e[e.ExtendedHeader=64]="ExtendedHeader",e[e.ExperimentalIndicator=32]="ExperimentalIndicator",e[e.Footer=16]="Footer"}(ua||(ua={})),function(e){e[e.ISO_8859_1=0]="ISO_8859_1",e[e.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",e[e.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",e[e.UTF_8=3]="UTF_8"}(la||(la={}));const ha=128,ma=["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"],fa=(e,t)=>{const r=yi(e,t),a=te(r.indexOf(0),r.length),i=r.subarray(0,a);let s="";for(let e=0;e<i.length;e++)s+=String.fromCharCode(i[e]);return s.trimEnd()},pa=e=>{const t=e.filePos,r=Oi(e,3),a=Si(e),i=Si(e),s=Si(e),n=Ei(e);if("ID3"!==r||255===a||255===i||2155905152&n)return e.filePos=t,null;return{majorVersion:a,revision:i,flags:s,size:da(n)}},ga=(e,t,r)=>{if(![2,3,4].includes(t.majorVersion))return void console.warn(`Unsupported ID3v2 major version: ${t.majorVersion}`);const a=yi(e,t.size),i=new ka(t,a);if(t.flags&ua.Footer&&i.removeFooter(),t.flags&ua.Unsynchronisation&&3===t.majorVersion&&i.ununsynchronizeAll(),t.flags&ua.ExtendedHeader){const e=i.readU32();3===t.majorVersion?i.pos+=e:i.pos+=e-4}for(;i.pos<=i.bytes.length-i.frameHeaderSize();){const e=i.readId3V2Frame();if(!e)break;const a=i.pos,s=i.pos+e.size;let n=!1,o=!1,c=!1;if(3===t.majorVersion?(n=!!(64&e.flags),o=!!(128&e.flags)):4===t.majorVersion&&(n=!!(4&e.flags),o=!!(8&e.flags),c=!!(2&e.flags)||!!(t.flags&ua.Unsynchronisation)),n)console.warn(`Skipping encrypted ID3v2 frame ${e.id}`),i.pos=s;else if(o)console.warn(`Skipping compressed ID3v2 frame ${e.id}`),i.pos=s;else{switch(c&&i.ununsynchronizeRegion(i.pos,s),r.raw??={},"T"===e.id[0]?r.raw[e.id]??=i.readId3V2EncodingAndText(s):r.raw[e.id]??=i.readBytes(e.size),i.pos=a,e.id){case"TIT2":case"TT2":r.title??=i.readId3V2EncodingAndText(s);break;case"TIT3":case"TT3":r.description??=i.readId3V2EncodingAndText(s);break;case"TPE1":case"TP1":r.artist??=i.readId3V2EncodingAndText(s);break;case"TALB":case"TAL":r.album??=i.readId3V2EncodingAndText(s);break;case"TPE2":case"TP2":r.albumArtist??=i.readId3V2EncodingAndText(s);break;case"TRCK":case"TRK":{const e=i.readId3V2EncodingAndText(s).split("/"),t=Number.parseInt(e[0],10),a=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(r.trackNumber??=t),a&&Number.isInteger(a)&&a>0&&(r.tracksTotal??=a)}break;case"TPOS":case"TPA":{const e=i.readId3V2EncodingAndText(s).split("/"),t=Number.parseInt(e[0],10),a=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(r.discNumber??=t),a&&Number.isInteger(a)&&a>0&&(r.discsTotal??=a)}break;case"TCON":case"TCO":{const e=i.readId3V2EncodingAndText(s);let t=/^\((\d+)\)/.exec(e);if(t){const e=Number.parseInt(t[1]);if(void 0!==ma[e]){r.genre??=ma[e];break}}if(t=/^\d+$/.exec(e),t){const e=Number.parseInt(t[0]);if(void 0!==ma[e]){r.genre??=ma[e];break}}r.genre??=e}break;case"TDRC":case"TDAT":{const e=i.readId3V2EncodingAndText(s),t=new Date(e);Number.isNaN(t.getTime())||(r.date??=t)}break;case"TYER":case"TYE":{const e=i.readId3V2EncodingAndText(s),t=Number.parseInt(e,10);Number.isInteger(t)&&(r.date??=new Date(t,0,1))}break;case"USLT":case"ULT":{const e=i.readU8();i.pos+=3,i.readId3V2Text(e,s),r.lyrics??=i.readId3V2Text(e,s)}break;case"COMM":case"COM":{const e=i.readU8();i.pos+=3,i.readId3V2Text(e,s),r.comment??=i.readId3V2Text(e,s)}break;case"APIC":case"PIC":{const e=i.readId3V2TextEncoding();let a;if(2===t.majorVersion){const e=i.readAscii(3);a="PNG"===e?"image/png":"JPG"===e?"image/jpeg":"image/*"}else a=i.readId3V2Text(e,s);const n=i.readU8(),o=i.readId3V2Text(e,s).trimEnd(),c=s-i.pos;if(c>=0){const e=i.readBytes(c);r.images||(r.images=[]),r.images.push({data:e,mimeType:a,kind:3===n?"coverFront":4===n?"coverBack":"unknown",description:o})}}break;default:i.pos+=e.size}i.pos=s}}};class ka{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 a=e;a<t;a++){const e=this.bytes[a];if(r.push(e),255===e&&a!==t-1){0===this.bytes[a+1]&&a++}}const a=this.bytes.subarray(0,e),i=this.bytes.subarray(t);this.bytes=new Uint8Array(a.length+r.length+i.length),this.bytes.set(a,0),this.bytes.set(r,a.length),this.bytes.set(i,a.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?da(t):t;const a=this.readU16(),i=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:da(t);s(e)&&(r=e)}return this.pos=i,{id:e,size:r,flags:a}}}readId3V2TextEncoding(){const e=this.readU8();if(e>3)throw new Error(`Unsupported text encoding: ${e}`);return e}readId3V2Text(e,t){const r=this.pos,a=this.readBytes(t-this.pos);switch(e){case la.ISO_8859_1:{let e="";for(let t=0;t<a.length;t++){const i=a[t];if(0===i){this.pos=r+t+1;break}e+=String.fromCharCode(i)}return e}case la.UTF_16_WITH_BOM:if(255===a[0]&&254===a[1]){const e=new TextDecoder("utf-16le"),t=te(a.findIndex((e,t)=>0===e&&0===a[t+1]&&t%2==0),a.length);return this.pos=r+Math.min(t+2,a.length),e.decode(a.subarray(2,t))}if(254===a[0]&&255===a[1]){const e=new TextDecoder("utf-16be"),t=te(a.findIndex((e,t)=>0===e&&0===a[t+1]&&t%2==0),a.length);return this.pos=r+Math.min(t+2,a.length),e.decode(a.subarray(2,t))}{const e=te(a.findIndex(e=>0===e),a.length);return this.pos=r+Math.min(e+1,a.length),p.decode(a.subarray(0,e))}case la.UTF_16_BE_NO_BOM:{const e=new TextDecoder("utf-16be"),t=te(a.findIndex((e,t)=>0===e&&0===a[t+1]&&t%2==0),a.length);return this.pos=r+Math.min(t+2,a.length),e.decode(a.subarray(0,t))}case la.UTF_8:{const e=te(a.findIndex(e=>0===e),a.length);return this.pos=r+Math.min(e+1,a.length),p.decode(a.subarray(0,e))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";const t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}}
|
|
128
|
+
/*!
|
|
129
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
130
|
+
*
|
|
131
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
132
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
133
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
134
|
+
*/const ba=async(e,t,r)=>{let a=t;for(;null===r||a<r;){let t=e.requestSlice(a,4);if(t instanceof Promise&&(t=await t),!t)break;const r=Ei(t),i=ca(r,null!==e.fileSize?e.fileSize-a:null);if(i.header)return{header:i.header,startPos:a};a+=i.bytesAdvanced}return null};
|
|
135
|
+
/*!
|
|
136
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
137
|
+
*
|
|
138
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
139
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
140
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
141
|
+
*/class wa extends kt{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.tracks=[],this.readingMutex=new I,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return 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 ir(this.input,new Ta(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=pa(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}const e=await ba(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=(a=t.mpegVersionId,i=t.channel,3===a?3===i?21:36:3===i?13:21);var a,i;let s=this.reader.requestSlice(e.startPos+r,4);if(s instanceof Promise&&(s=await s),s){const e=Ei(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 n(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,t=!1;for(;;){let r=this.reader.requestSlice(e,10);if(r instanceof Promise&&(r=await r),!r)break;const a=pa(r);if(!a)break;t=!0;let i=this.reader.requestSlice(r.filePos,a.size);if(i instanceof Promise&&(i=await i),!i)break;ga(i,a,this.metadataTags),e=r.filePos+a.size}if(!t&&null!==this.reader.fileSize&&this.reader.fileSize>=ha){let e=this.reader.requestSlice(this.reader.fileSize-ha,ha);e instanceof Promise&&(e=await e),n(e);"TAG"===Oi(e,3)&&((e,t)=>{const r=e.filePos;t.raw??={},t.raw.TAG??=yi(e,125),e.filePos=r;const a=fa(e,30);a&&(t.title??=a);const i=fa(e,30);i&&(t.artist??=i);const s=fa(e,30);s&&(t.album??=s);const n=fa(e,4),o=Number.parseInt(n,10);Number.isInteger(o)&&o>0&&(t.date??=new Date(o,0,1));const c=yi(e,30);let d;if(0===c[28]&&0!==c[29]){const r=c[29];r>0&&(t.trackNumber??=r),e.skip(-30),d=fa(e,28),e.skip(2)}else e.skip(-30),d=fa(e,30);d&&(t.comment??=d);const u=Si(e);u<ma.length&&(t.genre??=ma[u])})(e,this.metadataTags)}return this.metadataTags}finally{e()}}}class Ta{constructor(e){this.demuxer=e}getId(){return 1}async getFirstTimestamp(){return 0}getTimeResolution(){return n(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 L}getCodec(){return"mp3"}getInternalCodecId(){return null}getNumberOfChannels(){return n(this.demuxer.firstFrameHeader),3===this.demuxer.firstFrameHeader.channel?1:2}getSampleRate(){return n(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{...le}}async getDecoderConfig(){return n(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 a;if(t.metadataOnly)a=Tt;else{let e=this.demuxer.reader.requestSlice(r.dataStart,r.dataSize);if(e instanceof Promise&&(e=await e),!e)return null;a=yi(e,r.dataSize)}return new yt(a,"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=D(this.demuxer.loadedSamples,e.timestamp,e=>e.timestamp);if(-1===r)throw new Error("Packet was not created from this track.");const a=r+1;for(;a>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(a,t)}finally{r()}}async getPacket(e,t){const r=await this.demuxer.readingMutex.acquire();try{for(;;){const r=B(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)}}
|
|
142
|
+
/*!
|
|
143
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
144
|
+
*
|
|
145
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
146
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
147
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
148
|
+
*/const ya=1399285583,Sa=new Uint32Array(256);for(let e=0;e<256;e++){let t=e<<24;for(let e=0;e<8;e++)t=2147483648&t?t<<1^79764919:t<<1;Sa[e]=t>>>0&4294967295}const Ca=e=>{const t=f(e),r=t.getUint32(22,!0);t.setUint32(22,0,!0);let a=0;for(let t=0;t<e.length;t++){const r=e[t];a=(a<<8^Sa[a>>>24^r])>>>0}return t.setUint32(22,r,!0),a},va=(e,t,r)=>{let a=0,i=null;if(e.length>0)if("vorbis"===t.codec){n(t.vorbisInfo);const s=(1<<(e=>{let t=0;for(;e;)t++,e>>=1;return t})(t.vorbisInfo.modeBlockflags.length-1))-1<<1,o=(e[0]&s)>>1;if(o>=t.vorbisInfo.modeBlockflags.length)throw new Error("Invalid mode number.");let c=r;const d=t.vorbisInfo.modeBlockflags[o];if(i=t.vorbisInfo.blocksizes[d],1===d){const r=1+(1|s),a=e[0]&r?1:0;c=t.vorbisInfo.blocksizes[a]}a=null!==c?c+i>>2:0}else if("opus"===t.codec){const t=(e=>{const t=e[0]>>3;return{durationInSamples:ht[t]}})(e);a=t.durationInSamples}return{durationInSamples:a,vorbisBlockSize:i}},Pa=27,Ia=282,xa=e=>{const t=e.filePos;if(Di(e)!==ya)return null;e.skip(1);const r=Si(e),a=Mi(e),i=Di(e),s=Di(e),n=Di(e),o=Si(e),c=new Uint8Array(o);for(let t=0;t<o;t++)c[t]=Si(e);const d=27+o,u=c.reduce((e,t)=>e+t,0);return{headerStartPos:t,totalSize:d+u,dataStartPos:t+d,dataSize:u,headerType:r,granulePosition:a,serialNumber:i,sequenceNumber:s,checksum:n,lacingValues:c}},Ea=(e,t)=>{for(;e.filePos<t-3;){const t=Di(e),r=79;if((255&t)===r||(t>>>8&255)===r||(t>>>16&255)===r||(t>>>24&255)===r){if(e.skip(-4),t===ya)return!0;e.skip(1)}}return!1};
|
|
149
|
+
/*!
|
|
150
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
151
|
+
*
|
|
152
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
153
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
154
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
155
|
+
*/
|
|
156
|
+
class Da extends kt{constructor(e){super(e),this.metadataPromise=null,this.bitstreams=[],this.tracks=[],this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,Pa,Ia);if(t instanceof Promise&&(t=await t),!t)break;const r=xa(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 e of this.bitstreams){const t=await this.readPacket(e.bosPage,0);t&&(t.data.byteLength>=7&&1===t.data[0]&&118===t.data[1]&&111===t.data[2]&&114===t.data[3]&&98===t.data[4]&&105===t.data[5]&&115===t.data[6]?await this.readVorbisMetadata(t,e):t.data.byteLength>=8&&79===t.data[0]&&112===t.data[1]&&117===t.data[2]&&115===t.data[3]&&72===t.data[4]&&101===t.data[5]&&97===t.data[6]&&100===t.data[7]&&await this.readOpusMetadata(t,e),null!==e.codecInfo.codec&&this.tracks.push(new ir(this.input,new Ba(e,this))))}})()}async readVorbisMetadata(e,t){let r=await this.findNextPacketStart(e);if(!r)return;const a=await this.readPacket(r.startPage,r.startSegmentIndex);if(!a)return;if(r=await this.findNextPacketStart(a),!r)return;const i=await this.readPacket(r.startPage,r.startSegmentIndex);if(!i)return;if(3!==a.data[0]||5!==i.data[0])return;const s=[],n=e=>{for(;s.push(Math.min(255,e)),!(e<255);)e-=255};n(e.data.length),n(a.data.length);const o=new Uint8Array(1+s.length+e.data.length+a.data.length+i.data.length);o[0]=2,o.set(s,1),o.set(e.data,1+s.length),o.set(a.data,1+s.length+e.data.length),o.set(i.data,1+s.length+e.data.length+a.data.length),t.codecInfo.codec="vorbis",t.description=o,t.lastMetadataPacket=i;const c=f(e.data);t.numberOfChannels=c.getUint8(11),t.sampleRate=c.getUint32(12,!0);const d=c.getUint8(28);t.codecInfo.vorbisInfo={blocksizes:[1<<(15&d),1<<(d>>4)],modeBlockflags:mt(i.data).modeBlockflags},gt(a.data.subarray(7),this.metadataTags)}async readOpusMetadata(e,t){const r=await this.findNextPacketStart(e);if(!r)return;const a=await this.readPacket(r.startPage,r.startSegmentIndex);if(!a)return;t.codecInfo.codec="opus",t.description=e.data,t.lastMetadataPacket=a;const i=lt(e.data);t.numberOfChannels=i.outputChannelCount,t.sampleRate=xe,t.codecInfo.opusInfo={preSkip:i.preSkip},gt(a.data.subarray(8),this.metadataTags)}async readPacket(e,t){n(t<e.lacingValues.length);let r=0;for(let a=0;a<t;a++)r+=e.lacingValues[a];let a=e,i=r,s=t;const o=[];e:for(;;){let t=this.reader.requestSlice(a.dataStartPos,a.dataSize);t instanceof Promise&&(t=await t),n(t);const c=yi(t,a.dataSize);for(;;){if(s===a.lacingValues.length){o.push(c.subarray(r,i));break}const e=a.lacingValues[s];if(i+=e,e<255){o.push(c.subarray(r,i));break e}s++}let d=a.headerStartPos+a.totalSize;for(;;){let t=this.reader.requestSliceRange(d,Pa,Ia);if(t instanceof Promise&&(t=await t),!t)return null;const r=xa(t);if(!r)return null;if(a=r,a.serialNumber===e.serialNumber)break;d=a.headerStartPos+a.totalSize}r=0,i=0,s=0}const c=o.reduce((e,t)=>e+t.length,0),d=new Uint8Array(c);let u=0;for(let e=0;e<o.length;e++){const t=o[e];d.set(t,u),u+=t.length}return{data:d,endPage:a,endSegmentIndex:s}}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,Pa,Ia);if(r instanceof Promise&&(r=await r),!r)return null;const a=xa(r);if(!a)return null;if(a.serialNumber===e.endPage.serialNumber)return{startPage:a,startSegmentIndex:0};t=a.headerStartPos+a.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 Ba{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new I,this.internalSampleRate="opus"===e.codecInfo.codec?xe:e.sampleRate}getId(){return this.bitstream.serialNumber}getNumberOfChannels(){return this.bitstream.numberOfChannels}getSampleRate(){return this.bitstream.sampleRate}getTimeResolution(){return this.bitstream.sampleRate}getCodec(){return this.bitstream.codecInfo.codec}getInternalCodecId(){return null}async getDecoderConfig(){return n(this.bitstream.codecInfo.codec),{codec:this.bitstream.codecInfo.codec,numberOfChannels:this.bitstream.numberOfChannels,sampleRate:this.bitstream.sampleRate,description:this.bitstream.description??void 0}}getName(){return null}getLanguageCode(){return L}getDisposition(){return{...le}}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?(n(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,r){if(!e)return null;const{durationInSamples:a,vorbisBlockSize:i}=va(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),s=new yt(r.metadataOnly?Tt:e.data,"key",Math.max(0,t.timestampInSamples)/this.internalSampleRate,a/this.internalSampleRate,e.endPage.headerStartPos+e.endSegmentIndex,e.data.byteLength);return this.encodedPacketToMetadata.set(s,{packet:e,timestampInSamples:t.timestampInSamples,durationInSamples:a,vorbisLastBlockSize:t.vorbisLastBlocksize,vorbisBlockSize:i}),s}async getFirstPacket(e){n(this.bitstream.lastMetadataPacket);const t=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let r=0;"opus"===this.bitstream.codecInfo.codec&&(n(this.bitstream.codecInfo.opusInfo),r-=this.bitstream.codecInfo.opusInfo.preSkip);const a=await this.demuxer.readPacket(t.startPage,t.startSegmentIndex);return this.createEncodedPacketFromOggPacket(a,{timestampInSamples:r,vorbisLastBlocksize:null},e)}async getNextPacket(e,t){const r=this.encodedPacketToMetadata.get(e);if(!r)throw new Error("Packet was not created from this track.");const a=await this.demuxer.findNextPacketStart(r.packet);if(!a)return null;const i=r.timestampInSamples+r.durationInSamples,s=await this.demuxer.readPacket(a.startPage,a.startSegmentIndex);return this.createEncodedPacketFromOggPacket(s,{timestampInSamples:i,vorbisLastBlocksize:r.vorbisBlockSize},t)}async getPacket(e,t){if(null===this.demuxer.reader.fileSize)return this.getPacketSequential(e,t);const r=U(e*this.internalSampleRate);if(0===r)return this.getFirstPacket(t);if(r<0)return null;n(this.bitstream.lastMetadataPacket);const a=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!a)return null;let i=a.startPage,s=this.demuxer.reader.fileSize;const o=[i];e:for(;i.headerStartPos+i.totalSize<s;){const e=i.headerStartPos,t=Math.floor((e+s)/2);let a=t;for(;;){const e=Math.min(a+65307,s-Pa);let c=this.demuxer.reader.requestSlice(a,e-a);c instanceof Promise&&(c=await c),n(c);if(!Ea(c,e)){s=t+Pa;continue e}let d=this.demuxer.reader.requestSliceRange(c.filePos,Pa,Ia);d instanceof Promise&&(d=await d),n(d);const u=xa(d);n(u);let l=!1;if(u.serialNumber===this.bitstream.serialNumber)l=!0;else{let e=this.demuxer.reader.requestSlice(u.headerStartPos,u.totalSize);e instanceof Promise&&(e=await e),n(e);const t=yi(e,u.totalSize);l=Ca(t)===u.checksum}if(!l){a=u.headerStartPos+4;continue}if(l&&u.serialNumber!==this.bitstream.serialNumber){a=u.headerStartPos+u.totalSize;continue}if(!(-1===u.granulePosition)){this.granulePositionToTimestampInSamples(u.granulePosition)>r?s=u.headerStartPos:(i=u,o.push(u));continue e}a=u.headerStartPos+u.totalSize}}let c=a.startPage;for(const e of o){if(e.granulePosition===i.granulePosition)break;(!c||e.headerStartPos>c.headerStartPos)&&(c=e)}let d=c;const u=[d];for(;d.serialNumber!==this.bitstream.serialNumber||d.granulePosition!==i.granulePosition;){const e=d.headerStartPos+d.totalSize;let t=this.demuxer.reader.requestSliceRange(e,Pa,Ia);t instanceof Promise&&(t=await t),n(t);const r=xa(t);n(r),d=r,d.serialNumber===this.bitstream.serialNumber&&u.push(d)}n(-1!==d.granulePosition);let l,h,m=null,f=d,p=0;if(d.headerStartPos===a.startPage.headerStartPos)l=this.granulePositionToTimestampInSamples(0),h=!0,m=0;else{l=0,h=!1;for(let e=d.lacingValues.length-1;e>=0;e--){if(d.lacingValues[e]<255){m=e+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:Tt,endPage:f,endSegmentIndex:p};if(await this.demuxer.findNextPacketStart(e)){const e=_a(u,d,m);n(e);const t=Aa(u,e.page,e.segmentIndex);t&&(d=t.page,m=t.segmentIndex)}else for(;;){const e=_a(u,d,m);if(!e)break;const t=Aa(u,e.page,e.segmentIndex);if(!t)break;if(d=t.page,m=t.segmentIndex,e.page.headerStartPos!==f.headerStartPos){f=e.page,p=e.segmentIndex;break}}}let g=null,k=null;for(;null!==d;){n(null!==m);const e=await this.demuxer.readPacket(d,m);if(!e)break;if(!(d.headerStartPos===a.startPage.headerStartPos&&m<a.startSegmentIndex)){let a=this.createEncodedPacketFromOggPacket(e,{timestampInSamples:l,vorbisLastBlocksize:k?.vorbisBlockSize??null},t);n(a);let i=this.encodedPacketToMetadata.get(a);if(n(i),h||e.endPage.headerStartPos!==f.headerStartPos||e.endSegmentIndex!==p?l+=i.durationInSamples:(l=this.granulePositionToTimestampInSamples(d.granulePosition),h=!0,a=this.createEncodedPacketFromOggPacket(e,{timestampInSamples:l-i.durationInSamples,vorbisLastBlocksize:k?.vorbisBlockSize??null},t),n(a),i=this.encodedPacketToMetadata.get(a),n(i)),g=a,k=i,h&&(Math.max(l,0)>r||Math.max(i.timestampInSamples,0)===r))break}const i=await this.demuxer.findNextPacketStart(e);if(!i)break;d=i.startPage,m=i.startSegmentIndex}return g}async getPacketSequential(e,t){const r=await this.sequentialScanMutex.acquire();try{const r=U(e*this.internalSampleRate);e=r/this.internalSampleRate;const a=B(this.sequentialScanCache,r,e=>e.timestampInSamples);let i;if(-1!==a){const e=this.sequentialScanCache[a];i=this.createEncodedPacketFromOggPacket(e.packet,{timestampInSamples:e.timestampInSamples,vorbisLastBlocksize:e.vorbisLastBlockSize},t)}else i=await this.getFirstPacket(t);let s=0;for(;i&&i.timestamp<e;){const r=await this.getNextPacket(i,t);if(!r||r.timestamp>e)break;if(i=r,s++,100===s){s=0;const e=this.encodedPacketToMetadata.get(i);n(e),this.sequentialScanCache.length>0&&n(c(this.sequentialScanCache).timestampInSamples<=e.timestampInSamples),this.sequentialScanCache.push(e)}}return i}finally{r()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const Aa=(e,t,r)=>{let a=t,i=r;e:for(;;){for(i--;i>=0;i--){if(a.lacingValues[i]<255){i++;break e}}n(-1===i);if(!(1&a.headerType)){i=0;break}const t=F(e,e=>e.headerStartPos<a.headerStartPos);if(!t)return null;a=t,i=a.lacingValues.length}if(n(-1!==i),i===a.lacingValues.length){const t=e[e.indexOf(a)+1];n(t),a=t,i=0}return{page:a,segmentIndex:i}},_a=(e,t,r)=>{if(r>0)return{page:t,segmentIndex:r-1};const a=F(e,e=>e.headerStartPos<t.headerStartPos);return a?{page:a,segmentIndex:a.lacingValues.length-1}:null};
|
|
157
|
+
/*!
|
|
158
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
159
|
+
*
|
|
160
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
161
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
162
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
163
|
+
*/
|
|
164
|
+
var Fa;!function(e){e[e.PCM=1]="PCM",e[e.IEEE_FLOAT=3]="IEEE_FLOAT",e[e.ALAW=6]="ALAW",e[e.MULAW=7]="MULAW",e[e.EXTENSIBLE=65534]="EXTENSIBLE"}(Fa||(Fa={}));class Ma extends kt{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??=(async()=>{let e=this.reader.requestSlice(0,12);e instanceof Promise&&(e=await e),n(e);const t=Oi(e,4),r="RIFX"!==t,a="RF64"===t,i=xi(e,r);let s=a?this.reader.fileSize:Math.min(i+8,this.reader.fileSize??1/0);if("WAVE"!==Oi(e,4))throw new Error("Invalid WAVE file - wrong format");let o=0,c=null,d=e.filePos;for(;null===s||d<s;){let e=this.reader.requestSlice(d,8);if(e instanceof Promise&&(e=await e),!e)break;const t=Oi(e,4),i=xi(e,r),n=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(n,i,r);else if("data"===t){if(c??=i,this.dataStart=e.filePos,this.dataSize=Math.min(c,(s??1/0)-this.dataStart),null===this.reader.fileSize)break}else if("ds64"===t){let e=this.reader.requestSlice(n,i);if(e instanceof Promise&&(e=await e),!e)break;const t=Ai(e,r);c=Ai(e,r),s=Math.min(t+8,this.reader.fileSize??1/0)}else"LIST"===t?await this.parseListChunk(n,i,r):"ID3 "!==t&&"id3 "!==t||await this.parseId3Chunk(n,i);d=n+i+(1&i),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 u=this.audioInfo.blockSizeInBytes;this.dataSize=Math.floor(this.dataSize/u)*u,this.tracks.push(new ir(this.input,new za(this)))})()}async parseFmtChunk(e,t,r){let a=this.reader.requestSlice(e,t);if(a instanceof Promise&&(a=await a),!a)return;let i=Ci(a,r);const s=Ci(a,r),n=xi(a,r);a.skip(4);const o=Ci(a,r);let c;if(c=14===t?8:Ci(a,r),t>=18&&357!==i){const e=Ci(a,r),s=t-18;if(Math.min(s,e)>=22&&i===Fa.EXTENSIBLE){a.skip(6);const e=yi(a,16);i=e[0]|e[1]<<8}}i!==Fa.MULAW&&i!==Fa.ALAW||(c=8),this.audioInfo={format:i,numberOfChannels:s,sampleRate:n,sampleSizeInBytes:Math.ceil(c/8),blockSizeInBytes:o}}async parseListChunk(e,t,r){let a=this.reader.requestSlice(e,t);if(a instanceof Promise&&(a=await a),!a)return;const i=Oi(a,4);if("INFO"!==i&&"INF0"!==i)return;let s=a.filePos;for(;s<=e+t-8;){a.filePos=s;const e=Oi(a,4),t=xi(a,r),i=yi(a,t);let n=0;for(let e=0;e<i.length&&0!==i[e];e++)n++;const o=String.fromCharCode(...i.subarray(0,n));switch(this.metadataTags.raw??={},this.metadataTags.raw[e]=o,e){case"INAM":case"TITL":this.metadataTags.title??=o;break;case"TIT3":this.metadataTags.description??=o;break;case"IART":this.metadataTags.artist??=o;break;case"IPRD":this.metadataTags.album??=o;break;case"IPRT":case"ITRK":case"TRCK":{const e=o.split("/"),t=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(this.metadataTags.trackNumber??=t),r&&Number.isInteger(r)&&r>0&&(this.metadataTags.tracksTotal??=r)}break;case"ICRD":case"IDIT":{const e=new Date(o);Number.isNaN(e.getTime())||(this.metadataTags.date??=e)}break;case"YEAR":{const e=Number.parseInt(o,10);Number.isInteger(e)&&e>0&&(this.metadataTags.date??=new Date(e,0,1))}break;case"IGNR":case"GENR":this.metadataTags.genre??=o;break;case"ICMT":case"CMNT":case"COMM":this.metadataTags.comment??=o}s+=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 a=pa(r);if(a){const t=r.slice(e+10,a.size);ga(t,a,this.metadataTags)}}getCodec(){if(n(this.audioInfo),this.audioInfo.format===Fa.MULAW)return"ulaw";if(this.audioInfo.format===Fa.ALAW)return"alaw";if(this.audioInfo.format===Fa.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===Fa.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 n(e),e.computeDuration()}async getTracks(){return await this.readMetadata(),this.tracks}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}const Ra=2048;class za{constructor(e){this.demuxer=e}getId(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return n(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){const e=this.demuxer.getCodec();return e?(n(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null}async computeDuration(){const e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getNumberOfChannels(){return n(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return n(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return n(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return L}getDisposition(){return{...le}}async getFirstTimestamp(){return 0}async getPacketAtIndex(e,t){n(this.demuxer.audioInfo);const r=e*Ra*this.demuxer.audioInfo.blockSizeInBytes;if(r>=this.demuxer.dataSize)return null;const a=Math.min(Ra*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-r);if(null===this.demuxer.reader.fileSize){let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+r,a);if(e instanceof Promise&&(e=await e),!e)return null}let i;if(t.metadataOnly)i=Tt;else{let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+r,a);e instanceof Promise&&(e=await e),n(e),i=yi(e,a)}const s=e*Ra/this.demuxer.audioInfo.sampleRate,o=a/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(e,s),new yt(i,"key",s,o,e,a)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,t){n(this.demuxer.audioInfo);const r=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/Ra,(this.demuxer.dataSize-1)/(Ra*this.demuxer.audioInfo.blockSizeInBytes))),a=await this.getPacketAtIndex(r,t);if(a)return a;if(0===r)return null;n(null===this.demuxer.reader.fileSize);let i=await this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,t);for(;i;){const e=await this.getNextPacket(i,t);if(!e)break;i=e}return i}getNextPacket(e,t){n(this.demuxer.audioInfo);const r=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/Ra);return this.getPacketAtIndex(r+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}
|
|
165
|
+
/*!
|
|
166
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
167
|
+
*
|
|
168
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
169
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
170
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
171
|
+
*/const Oa=e=>{const t=e.filePos,r=yi(e,9),a=new u(r);if(4095!==a.readBits(12))return null;a.skipBits(1);if(0!==a.readBits(2))return null;const i=a.readBits(1),s=a.readBits(2)+1,n=a.readBits(4);if(15===n)return null;a.skipBits(1);const o=a.readBits(3);if(0===o)throw new Error("ADTS frames with channel configuration 0 are not supported.");a.skipBits(1),a.skipBits(1),a.skipBits(1),a.skipBits(1);const c=a.readBits(13);a.skipBits(11);const d=a.readBits(2)+1;if(1!==d)throw new Error("ADTS frames with more than one AAC frame are not supported.");let l=null;return 1===i?e.filePos-=2:l=a.readBits(16),{objectType:s,samplingFrequencyIndex:n,channelConfiguration:o,frameLength:c,numberOfAacFrames:d,crcCheck:l,startPos:t}},Na=1024;class La extends kt{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.tracks=[],this.readingMutex=new I,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();n(this.firstFrameHeader),this.tracks=[new ir(this.input,new Ua(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 t=Oa(e);if(!t)return void(this.lastSampleLoaded=!0);if(null!==this.reader.fileSize&&t.startPos+t.frameLength>this.reader.fileSize)return void(this.lastSampleLoaded=!0);this.firstFrameHeader||(this.firstFrameHeader=t);const r=ve[t.samplingFrequencyIndex];n(void 0!==r);const a=Na/r,i=t.crcCheck?9:7,s={timestamp:this.nextTimestampInSamples/r,duration:a,dataStart:t.startPos+i,dataSize:t.frameLength-i};this.loadedSamples.push(s),this.nextTimestampInSamples+=Na,this.lastLoadedPos=t.startPos+t.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 n(e),e.computeDuration()}async getMetadataTags(){return{}}}class Ua{constructor(e){this.demuxer=e}getId(){return 1}async getFirstTimestamp(){return 0}getTimeResolution(){return this.getSampleRate()/Na}async computeDuration(){const e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getName(){return null}getLanguageCode(){return L}getCodec(){return"aac"}getInternalCodecId(){return n(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){n(this.demuxer.firstFrameHeader);const e=Pe[this.demuxer.firstFrameHeader.channelConfiguration];return n(void 0!==e),e}getSampleRate(){n(this.demuxer.firstFrameHeader);const e=ve[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return n(void 0!==e),e}getDisposition(){return{...le}}async getDecoderConfig(){n(this.demuxer.firstFrameHeader);const e=new Uint8Array(3),t=new u(e),{objectType:r,samplingFrequencyIndex:a,channelConfiguration:i}=this.demuxer.firstFrameHeader;return r>31?(t.writeBits(5,31),t.writeBits(6,r-32)):t.writeBits(5,r),t.writeBits(4,a),t.writeBits(4,i),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate(),description:e.subarray(0,Math.ceil((t.pos-1)/8))}}async getPacketAtIndex(e,t){if(-1===e)return null;const r=this.demuxer.loadedSamples[e];if(!r)return null;let a;if(t.metadataOnly)a=Tt;else{let e=this.demuxer.reader.requestSlice(r.dataStart,r.dataSize);if(e instanceof Promise&&(e=await e),!e)return null;a=yi(e,r.dataSize)}return new yt(a,"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=D(this.demuxer.loadedSamples,e.timestamp,e=>e.timestamp);if(-1===r)throw new Error("Packet was not created from this track.");const a=r+1;for(;a>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(a,t)}finally{r()}}async getPacket(e,t){const r=await this.demuxer.readingMutex.acquire();try{for(;;){const r=B(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)}}
|
|
172
|
+
/*!
|
|
173
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
174
|
+
*
|
|
175
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
176
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
177
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
178
|
+
*/
|
|
179
|
+
/*!
|
|
180
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
181
|
+
*
|
|
182
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
183
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
184
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
185
|
+
*/
|
|
186
|
+
class Va extends kt{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 I,this.lastSampleLoaded=!1,this.reader=e._reader}async computeDuration(){return await this.readMetadata(),n(this.track),this.track.computeDuration()}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}async getTracks(){return await this.readMetadata(),n(this.track),[this.track]}async getMimeType(){return"audio/flac"}async readMetadata(){let e=4;return this.metadataPromise??=(async()=>{for(;null===this.reader.fileSize||e<this.reader.fileSize;){let t=this.reader.requestSlice(e,4);if(t instanceof Promise&&(t=await t),e+=4,null===t)throw new Error(`Metadata block at position ${e} is too small! Corrupted file.`);n(t);const r=Si(t),a=Pi(t),i=!!(128&r);switch(127&r){case pt.STREAMINFO:{let t=this.reader.requestSlice(e,a);if(t instanceof Promise&&(t=await t),n(t),null===t)throw new Error(`StreamInfo block at position ${e} is too small! Corrupted file.`);const r=yi(t,34),i=new u(r),s=i.readBits(16),o=i.readBits(16),c=i.readBits(24),d=i.readBits(24),l=i.readBits(20),h=i.readBits(3)+1;i.readBits(5);const m=i.readBits(36);i.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(r,8),this.audioInfo={numberOfChannels:h,sampleRate:l,totalSamples:m,minimumBlockSize:s,maximumBlockSize:o,minimumFrameSize:c,maximumFrameSize:d,description:f},this.track=new ir(this.input,new Wa(this));break}case pt.VORBIS_COMMENT:{let t=this.reader.requestSlice(e,a);t instanceof Promise&&(t=await t),n(t),gt(yi(t,a),this.metadataTags);break}case pt.PICTURE:{let t=this.reader.requestSlice(e,a);t instanceof Promise&&(t=await t),n(t);const r=Ei(t),i=Ei(t),s=p.decode(yi(t,i)),o=Ei(t),c=p.decode(yi(t,o));t.skip(16);const d=Ei(t),u=yi(t,d);this.metadataTags.images??=[],this.metadataTags.images.push({data:u,mimeType:s,kind:3===r?"coverFront":4===r?"coverBack":"unknown",description:c});break}}if(e+=a,i){this.lastLoadedPos=e;break}}})()}async readNextFlacFrame({startPos:e,isFirstPacket:t}){n(this.audioInfo);const r=this.audioInfo.maximumFrameSize+16,a=await this.reader.requestSliceRange(e,this.audioInfo.minimumFrameSize,r);if(!a)return null;const i=this.readFlacFrameHeader({slice:a,isFirstPacket:t});if(!i)return null;for(a.filePos=e+this.audioInfo.minimumFrameSize;;){if(a.filePos>a.end-6)return{num:i.num,blockSize:i.blockSize,sampleRate:i.sampleRate,size:a.end-e,isLastFrame:!0};if(255===Si(a)){const t=a.filePos;if(Si(a)!==(1===this.blockingBit?249:248)){a.filePos=t;continue}a.skip(-2);const r=a.filePos-e,s=this.readFlacFrameHeader({slice:a,isFirstPacket:!1});if(!s){a.filePos=t;continue}if(0===this.blockingBit){if(s.num-i.num!==1){a.filePos=t;continue}}else if(s.num-i.num!==i.blockSize){a.filePos=t;continue}return{num:i.num,blockSize:i.blockSize,sampleRate:i.sampleRate,size:r,isLastFrame:!1}}}}readFlacFrameHeader({slice:e,isFirstPacket:t}){const r=e.filePos,a=yi(e,4),i=new u(a);if(32764!==i.readBits(15))return null;if(null===this.blockingBit){n(t);const e=i.readBits(1);this.blockingBit=e}else if(1===this.blockingBit){n(!t);if(1!==i.readBits(1))return null}else{if(0!==this.blockingBit)throw new Error("Invalid blocking bit");n(!t);if(0!==i.readBits(1))return null}const s=(e=>0===e?null:1===e?192:e>=2&&e<=5?144*2**e:6===e?"uncommon-u8":7===e?"uncommon-u16":e>=8&&e<=15?2**e:null)(i.readBits(4));if(!s)return null;n(this.audioInfo);const o=((e,t)=>{switch(e){case 0:return t;case 1:return 88200;case 2:return 176400;case 3:return 192e3;case 4:return 8e3;case 5:return 16e3;case 6:return 22050;case 7:return 24e3;case 8:return 32e3;case 9:return 44100;case 10:return 48e3;case 11:return 96e3;case 12:return"uncommon-u8";case 13:return"uncommon-u16";case 14:return"uncommon-u16-10";default:return null}})(i.readBits(4),this.audioInfo.sampleRate);if(!o)return null;i.readBits(4),i.readBits(3);if(0!==i.readBits(1))return null;const c=(e=>{let t=0;const r=new u(yi(e,1));for(;1===r.readBits(1);)t++;if(0===t)return r.readBits(7);const a=[],i=t-1,s=new u(yi(e,i)),n=8-t-1;for(let e=0;e<n;e++)a.unshift(r.readBits(1));for(let e=0;e<i;e++)for(let e=0;e<8;e++){const t=s.readBits(1);e<2||a.unshift(t)}return a.reduce((e,t,r)=>e|t<<r,0)})(e),d=((e,t)=>"uncommon-u16"===t?vi(e)+1:"uncommon-u8"===t?Si(e)+1:"number"==typeof t?t:(R(t),void n(!1)))(e,s),l=((e,t)=>"uncommon-u16"===t?vi(e):"uncommon-u16-10"===t?10*vi(e):"uncommon-u8"===t?Si(e):"number"==typeof t?t:null)(e,o);if(null===l)return null;if(l!==this.audioInfo.sampleRate)return null;const h=e.filePos-r,m=Si(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++)128&t?t=t<<1^7:t<<=1,t&=255}return t})(yi(e,h));return m!==f?null:{num:c,blockSize:d,sampleRate:l}}async advanceReader(){await this.readMetadata(),n(null!==this.lastLoadedPos),n(this.audioInfo);const e=this.lastLoadedPos,t=await this.readNextFlacFrame({startPos:e,isFirstPacket:0===this.loadedSamples.length});if(!t)return void(this.lastSampleLoaded=!0);const r=this.loadedSamples[this.loadedSamples.length-1],a={blockOffset:r?r.blockOffset+r.blockSize:0,blockSize:t.blockSize,byteOffset:e,byteSize:t.size};this.lastLoadedPos=this.lastLoadedPos+t.size,this.loadedSamples.push(a),t.isLastFrame&&(this.lastSampleLoaded=!0)}}class Wa{constructor(e){this.demuxer=e}getId(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return n(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 n(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return L}getTimeResolution(){return n(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getDisposition(){return{...le}}async getFirstTimestamp(){return 0}async getDecoderConfig(){return n(this.demuxer.audioInfo),{codec:"flac",numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}}async getPacket(e,t){if(n(this.demuxer.audioInfo),e<0)throw new Error("Timestamp cannot be negative");const r=await this.demuxer.readingMutex.acquire();try{for(;;){const r=B(this.demuxer.loadedSamples,e,e=>e.blockOffset/this.demuxer.audioInfo.sampleRate);if(-1===r){await this.demuxer.advanceReader();continue}const a=this.demuxer.loadedSamples[r],i=a.blockOffset/this.demuxer.audioInfo.sampleRate;if(!(i+a.blockSize/this.demuxer.audioInfo.sampleRate<=e))return this.getPacketAtIndex(r,t);if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(this.demuxer.loadedSamples.length-1,t);await this.demuxer.advanceReader()}}finally{r()}}async getNextPacket(e,t){const 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,t){const r=this.demuxer.loadedSamples[e];if(!r)return null;let a;if(t.metadataOnly)a=Tt;else{let e=this.demuxer.reader.requestSlice(r.byteOffset,r.byteSize);if(e instanceof Promise&&(e=await e),!e)return null;a=yi(e,r.byteSize)}n(this.demuxer.audioInfo);const i=r.blockOffset/this.demuxer.audioInfo.sampleRate,s=r.blockSize/this.demuxer.audioInfo.sampleRate;return new yt(a,"key",i,s,e,r.byteSize)}async getFirstPacket(e){for(;0===this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)}}
|
|
187
|
+
/*!
|
|
188
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
189
|
+
*
|
|
190
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
191
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
192
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
193
|
+
*/class Ha{}class qa extends Ha{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"!==Oi(t,4)?null:Oi(t,4)}_createDemuxer(e){return new mr(e)}}class ja extends qa{async _canReadInput(e){const t=await this._getMajorBrand(e);return!!t&&"qt "!==t}get name(){return"MP4"}get mimeType(){return"video/mp4"}}class $a extends qa{async _canReadInput(e){return"qt "===await this._getMajorBrand(e)}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}}class Qa extends Ha{async isSupportedEBMLOfDocType(e,t){let r=e._reader.requestSlice(0,zr);if(r instanceof Promise&&(r=await r),!r)return!1;const a=Or(r);if(null===a)return!1;if(a<1||a>8)return!1;if(Lr(r,a)!==Er.EBML)return!1;const i=Vr(r);if(null===i)return!1;let s=e._reader.requestSlice(r.filePos,i);if(s instanceof Promise&&(s=await s),!s)return!1;const n=r.filePos;for(;s.filePos<=n+i-2;){const e=Wr(s);if(!e)break;const{id:r,size:a}=e,i=s.filePos;if(null===a)return!1;switch(r){case Er.EBMLVersion:if(1!==Lr(s,a))return!1;break;case Er.EBMLReadVersion:if(1!==Lr(s,a))return!1;break;case Er.DocType:if(Hr(s,a)!==t)return!1;break;case Er.DocTypeVersion:if(Lr(s,a)>4)return!1}s.filePos=i+a}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new ra(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}}class Ka extends Qa{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}}class Ga extends Ha{async _canReadInput(e){let t=e._reader.requestSlice(0,10);if(t instanceof Promise&&(t=await t),!t)return!1;let r=0,a=!1;for(;;){let t=e._reader.requestSlice(r,10);if(t instanceof Promise&&(t=await t),!t)break;const i=pa(t);if(!i)break;a=!0,r=t.filePos+i.size}const i=await ba(e._reader,r,r+4096);if(!i)return!1;if(a)return!0;r=i.startPos+i.header.totalSize;const s=await ba(e._reader,r,r+4);if(!s)return!1;const n=i.header,o=s.header;return n.channel===o.channel&&n.sampleRate===o.sampleRate}_createDemuxer(e){return new wa(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}}class Xa extends Ha{async _canReadInput(e){let t=e._reader.requestSlice(0,12);if(t instanceof Promise&&(t=await t),!t)return!1;const r=Oi(t,4);if("RIFF"!==r&&"RIFX"!==r&&"RF64"!==r)return!1;t.skip(4);return"WAVE"===Oi(t,4)}_createDemuxer(e){return new Ma(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}}class Ya extends Ha{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=await t),!!t&&"OggS"===Oi(t,4)}_createDemuxer(e){return new Da(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}}class Ja extends Ha{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=await t),!!t&&"fLaC"===Oi(t,4)}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new Va(e)}}class Za extends Ha{async _canReadInput(e){let t=e._reader.requestSliceRange(0,7,9);if(t instanceof Promise&&(t=await t),!t)return!1;const r=Oa(t);if(!r)return!1;if(t=e._reader.requestSliceRange(r.frameLength,7,9),t instanceof Promise&&(t=await t),!t)return!1;const a=Oa(t);return!!a&&(r.objectType===a.objectType&&r.samplingFrequencyIndex===a.samplingFrequencyIndex&&r.channelConfiguration===a.channelConfiguration)}_createDemuxer(e){return new La(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}}const ei=new ja,ti=new $a,ri=new Qa,ai=new Ka,ii=new Ga,si=new Xa,ni=new Ya,oi=new Za,ci=[ei,ti,ri,ai,si,ni,new Ja,ii,oi];
|
|
194
|
+
/*!
|
|
195
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
196
|
+
*
|
|
197
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
198
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
199
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
200
|
+
*/
|
|
201
|
+
class di{constructor(){this._disposed=!1,this._sizePromise=null,this.onread=null}async getSizeOrNull(){if(this._disposed)throw new ki;return this._sizePromise??=Promise.resolve(this._retrieveSize())}async getSize(){if(this._disposed)throw new ki;const e=await this.getSizeOrNull();if(null===e)throw new Error("Cannot determine the size of an unsized source.");return e}}const ui=524288,li=(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&&void 0!==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 hi extends di{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&&(!ce(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??li,this._orchestrator=new pi({maxCacheSize:t.maxCacheSize??67108864,maxWorkerCount:2,runWorker:this._runWorker.bind(this),prefetchProfile:fi.network})}async _retrieveSize(){const e=new AbortController,t=await Q(this._options.fetchFn??fetch,this._url,j(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,a;if(206===t.status)a=this._getTotalLengthFromRangeResponse(t),r=this._orchestrator.createWorker(0,Math.min(a,ui));else{const e=t.headers.get("Content-Length");if(!e)throw new Error(`HTTP response (status ${t.status}) must surface Content-Length header.`);a=Number(e),r=this._orchestrator.createWorker(0,a),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=a,this._existingResponses.set(r,{response:t,abortController:e}),this._orchestrator.runWorker(r),a}_read(e,t){return this._orchestrator.read(e,t)}async _runWorker(e){for(;;){const t=this._existingResponses.get(e);this._existingResponses.delete(e);let r=t?.abortController,a=t?.response;if(r||(r=new AbortController,a=await Q(this._options.fetchFn??fetch,this._url,j(this._options.requestInit??{},{headers:{Range:`bytes=${e.currentPos}-`},signal:r.signal}),this._getRetryDelay,()=>this._disposed)),n(a),!a.ok)throw new Error(`Error fetching ${String(this._url)}: ${a.status} ${a.statusText}`);if(e.currentPos>0&&206!==a.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(!a.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");const i=a.body.getReader();for(;;){if(e.currentPos>=e.targetPos||e.aborted)return r.abort(),void(e.running=!1);let t;try{t=await i.read()}catch(e){if(this._disposed)throw e;const t=this._getRetryDelay(1,e,this._url);if(null!==t){console.error("Error while reading response stream. Attempting to resume.",e),await new Promise(e=>setTimeout(e,1e3*t));break}throw e}if(e.aborted)continue;const{done:a,value:s}=t;if(a){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 mi extends di{constructor(e){if(!e||"object"!=typeof e)throw new TypeError("options must be an object.");if("function"!=typeof e.getSize)throw new TypeError("options.getSize must be a function.");if("function"!=typeof e.read)throw new TypeError("options.read must be a function.");if(void 0!==e.dispose&&"function"!=typeof e.dispose)throw new TypeError("options.dispose, when provided, must be a function.");if(void 0!==e.maxCacheSize&&(!ce(e.maxCacheSize)||e.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(e.prefetchProfile&&!["none","fileSystem","network"].includes(e.prefetchProfile))throw new TypeError("options.prefetchProfile, when provided, must be one of 'none', 'fileSystem' or 'network'.");super(),this._options=e,this._orchestrator=new pi({maxCacheSize:e.maxCacheSize??8388608,maxWorkerCount:2,prefetchProfile:fi[e.prefetchProfile??"none"],runWorker:this._runWorker.bind(this)})}_retrieveSize(){const e=this._options.getSize();if(e instanceof Promise)return e.then(e=>{if(!Number.isInteger(e)||e<0)throw new TypeError("options.getSize must return or resolve to a non-negative integer.");return this._orchestrator.fileSize=e,e});if(!Number.isInteger(e)||e<0)throw new TypeError("options.getSize must return or resolve to a non-negative integer.");return this._orchestrator.fileSize=e,e}_read(e,t){return this._orchestrator.read(e,t)}async _runWorker(e){for(;e.currentPos<e.targetPos&&!e.aborted;){const t=e.currentPos,r=e.targetPos;let a=this._options.read(e.currentPos,r);if(a instanceof Promise&&(a=await a),e.aborted)break;if(a instanceof Uint8Array){if(a=m(a),a.length!==r-e.currentPos)throw new Error(`options.read returned a Uint8Array with unexpected length: Requested ${r-e.currentPos} bytes, but got ${a.length}.`);this.onread?.(e.currentPos,e.currentPos+a.length),this._orchestrator.supplyWorkerData(e,a)}else{if(!(a instanceof ReadableStream))throw new TypeError("options.read must return or resolve to a Uint8Array or a ReadableStream.");{const i=a.getReader();for(;e.currentPos<r&&!e.aborted;){const{done:a,value:s}=await i.read();if(a){if(e.currentPos<r)throw new Error(`ReadableStream returned by options.read ended before supplying enough data. Requested ${r-t} bytes, but got ${e.currentPos-t}`);break}if(!(s instanceof Uint8Array))throw new TypeError("ReadableStream returned by options.read must yield Uint8Array chunks.");if(e.aborted)break;const n=m(s);this.onread?.(e.currentPos,e.currentPos+n.length),this._orchestrator.supplyWorkerData(e,n)}}}}e.running=!1}_dispose(){this._orchestrator.dispose(),this._options.dispose?.()}}const fi={none:(e,t)=>({start:e,end:t}),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 a=65536;e=Math.max(0,Math.floor((e-a)/a)*a);for(const a of r){const r=8388608,i=Math.max((a.startPos+a.targetPos)/2,a.targetPos-r);if(re(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+ui)}}};class pi{constructor(e){this.options=e,this.fileSize=null,this.nextAge=0,this.workers=[],this.cache=[],this.currentCacheSize=0,this.disposed=!1}read(e,t){n(null!==this.fileSize);const r=this.options.prefetchProfile(e,t,this.workers),a=Math.max(r.start,0),i=Math.min(r.end,this.fileSize);n(a<=e&&t<=i);let s=null;const o=B(this.cache,e,e=>e.start),c=-1!==o?this.cache[o]:null;c&&c.start<=e&&t<=c.end&&(c.age=this.nextAge++,s={bytes:c.bytes,view:c.view,offset:c.start});const d=B(this.cache,a,e=>e.start),u=s?null:new Uint8Array(t-e);let l=0,h=a;const m=[];if(-1!==d){for(let r=d;r<this.cache.length;r++){const s=this.cache[r];if(s.start>=i)break;if(s.end<=a)continue;const o=Math.max(a,s.start),c=Math.min(i,s.end);if(n(o<=c),h<o&&m.push({start:h,end:o}),h=c,u){const r=Math.max(e,s.start),a=Math.min(t,s.end);if(r<a){const t=r-e;u.set(s.bytes.subarray(r-s.start,a-s.start),t),t===l&&(l=a-e)}}s.age=this.nextAge++}h<i&&m.push({start:h,end:i})}else m.push({start:a,end:i});if(u&&l>=u.length&&(s={bytes:u,view:f(u),offset:e}),0===m.length)return n(s),s;const{promise:p,resolve:g,reject:k}=_(),b=[];for(const r of m){const a=Math.max(e,r.start),i=Math.min(t,r.end);a===r.start&&i===r.end?b.push(r):a<i&&b.push({start:a,end:i})}for(const t of m){const r=u&&{start:e,bytes:u,holes:b,resolve:g,reject:k};let a=!1;for(const e of this.workers){const i=2**17;if(re(t.start-i,t.start,e.currentPos,e.targetPos)){e.targetPos=Math.max(e.targetPos,t.end),a=!0,r&&!e.pendingSlices.includes(r)&&e.pendingSlices.push(r),e.running||this.runWorker(e);break}}if(!a){const e=this.createWorker(t.start,t.end);r&&(e.pendingSlices=[r]),this.runWorker(e)}}return s||(n(u),s=p.then(t=>({bytes:t,view:f(t),offset:e}))),s}createWorker(e,t){const r={startPos:e,currentPos:e,targetPos:t,running:!1,aborted:this.disposed,pendingSlices:[],age:this.nextAge++};for(this.workers.push(r);this.workers.length>this.options.maxWorkerCount;){let e=0,t=this.workers[0];for(let r=1;r<this.workers.length;r++){const a=this.workers[r];a.age<t.age&&(e=r,t=a)}if(t.running&&t.pendingSlices.length>0)break;t.aborted=!0,this.workers.splice(e,1)}return r}runWorker(e){n(!e.running),n(e.currentPos<e.targetPos),e.running=!0,e.age=this.nextAge++,this.options.runWorker(e).catch(t=>{if(e.running=!1,!(e.pendingSlices.length>0))throw t;e.pendingSlices.forEach(e=>e.reject(t)),e.pendingSlices.length=0})}supplyWorkerData(e,t){n(!e.aborted);const r=e.currentPos,a=r+t.length;this.insertIntoCache({start:r,end:a,bytes:t,view:f(t),age:this.nextAge++}),e.currentPos+=t.length,e.targetPos=Math.max(e.targetPos,e.currentPos);for(let i=0;i<e.pendingSlices.length;i++){const s=e.pendingSlices[i],n=Math.max(r,s.start),o=Math.min(a,s.start+s.bytes.length);n<o&&s.bytes.set(t.subarray(n-r,o-r),n-s.start);for(let e=0;e<s.holes.length;e++){const t=s.holes[e];r<=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(i,1),i--)}for(let t=0;t<this.workers.length;t++){const i=this.workers[t];e===i||i.running||re(r,a,i.currentPos,i.targetPos)&&(this.workers.splice(t,1),t--)}}forgetWorker(e){const t=this.workers.indexOf(e);n(-1!==t),this.workers.splice(t,1)}insertIntoCache(e){if(0===this.options.maxCacheSize)return;let t=B(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 a=new Uint8Array(e.end-r.start);a.set(r.bytes,0),a.set(e.bytes,e.start-r.start),this.currentCacheSize+=e.end-r.end,r.bytes=a,r.view=f(a),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 a=new Uint8Array(t.end-e.start);a.set(e.bytes,0),a.set(t.bytes,t.start-e.start),this.currentCacheSize-=e.end-t.start,e.bytes=a,e.view=f(a),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 a=this.cache[r];a.age<t.age&&(e=r,t=a)}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}}
|
|
202
|
+
/*!
|
|
203
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
204
|
+
*
|
|
205
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
206
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
207
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
208
|
+
*/oe();class gi{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 Ha)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof di))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 bi(e.source)}_getDemuxer(){return 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(),n(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 ki extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}}
|
|
209
|
+
/*!
|
|
210
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
211
|
+
*
|
|
212
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
213
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
214
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
215
|
+
*/class bi{constructor(e){this.source=e}requestSlice(e,t){if(this.source._disposed)throw new ki;if(null!==this.fileSize&&e+t>this.fileSize)return null;const r=e+t,a=this.source._read(e,r);return a instanceof Promise?a.then(t=>t?new wi(t.bytes,t.view,t.offset,e,r):null):a?new wi(a.bytes,a.view,a.offset,e,r):null}requestSliceRange(e,t,r){if(this.source._disposed)throw new ki;if(null!==this.fileSize)return this.requestSlice(e,N(this.fileSize-e,t,r));{const a=this.requestSlice(e,r),i=a=>{if(a)return a;const i=a=>(n(null!==a),this.requestSlice(e,N(a-e,t,r))),s=this.source._retrieveSize();return s instanceof Promise?s.then(i):i(s)};return a instanceof Promise?a.then(i):i(a)}}}class wi{constructor(e,t,r,a,i){this.bytes=e,this.view=t,this.offset=r,this.start=a,this.end=i,this.bufferPos=a-r}static tempFromBytes(e){return new wi(e,f(e),0,0,e.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos(e){this.bufferPos=e-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip(e){this.bufferPos+=e}slice(e,t=this.end-e){if(e<this.start||e+t>this.end)throw new RangeError("Slicing outside of original slice.");return new wi(this.bytes,this.view,this.offset,e,e+t)}}const Ti=(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.`)},yi=(e,t)=>{Ti(e,t);const r=e.bytes.subarray(e.bufferPos,e.bufferPos+t);return e.bufferPos+=t,r},Si=e=>(Ti(e,1),e.view.getUint8(e.bufferPos++)),Ci=(e,t)=>{Ti(e,2);const r=e.view.getUint16(e.bufferPos,t);return e.bufferPos+=2,r},vi=e=>{Ti(e,2);const t=e.view.getUint16(e.bufferPos,!1);return e.bufferPos+=2,t},Pi=e=>{Ti(e,3);const t=z(e.view,e.bufferPos,!1);return e.bufferPos+=3,t},Ii=e=>{Ti(e,2);const t=e.view.getInt16(e.bufferPos,!1);return e.bufferPos+=2,t},xi=(e,t)=>{Ti(e,4);const r=e.view.getUint32(e.bufferPos,t);return e.bufferPos+=4,r},Ei=e=>{Ti(e,4);const t=e.view.getUint32(e.bufferPos,!1);return e.bufferPos+=4,t},Di=e=>{Ti(e,4);const t=e.view.getUint32(e.bufferPos,!0);return e.bufferPos+=4,t},Bi=e=>{Ti(e,4);const t=e.view.getInt32(e.bufferPos,!1);return e.bufferPos+=4,t},Ai=(e,t)=>{let r,a;return t?(r=xi(e,!0),a=xi(e,!0)):(a=xi(e,!1),r=xi(e,!1)),4294967296*a+r},_i=e=>4294967296*Ei(e)+Ei(e),Fi=e=>4294967296*Bi(e)+Ei(e),Mi=e=>{const t=Di(e),r=(e=>{Ti(e,4);const t=e.view.getInt32(e.bufferPos,!0);return e.bufferPos+=4,t})(e);return 4294967296*r+t},Ri=e=>{Ti(e,4);const t=e.view.getFloat32(e.bufferPos,!1);return e.bufferPos+=4,t},zi=e=>{Ti(e,8);const t=e.view.getFloat64(e.bufferPos,!1);return e.bufferPos+=8,t},Oi=(e,t)=>{Ti(e,t);let r="";for(let a=0;a<t;a++)r+=String.fromCharCode(e.bytes[e.bufferPos++]);return r},Ni=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,Li=/(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})/,Ui=e=>{const t=Math.floor(e/36e5),r=Math.floor(e%36e5/6e4),a=Math.floor(e%6e4/1e3),i=e%1e3;return t.toString().padStart(2,"0")+":"+r.toString().padStart(2,"0")+":"+a.toString().padStart(2,"0")+"."+i.toString().padStart(3,"0")};
|
|
63
216
|
/*!
|
|
64
217
|
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
65
218
|
*
|
|
@@ -67,7 +220,7 @@ class ue{constructor(e){this.value=e}}class le{constructor(e){this.value=e}}clas
|
|
|
67
220
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
68
221
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
69
222
|
*/
|
|
70
|
-
class ve{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=new WeakMap}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeU64(e){this.helperView.setUint32(0,Math.floor(e/2**32),!1),this.helperView.setUint32(4,e,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii(e){for(let t=0;t<e.length;t++)this.helperView.setUint8(t%8,e.charCodeAt(t)),t%8==7&&this.writer.write(this.helper);e.length%8!=0&&this.writer.write(this.helper.subarray(0,e.length%8))}writeBox(e){if(this.offsets.set(e,this.writer.getPos()),e.contents&&!e.children)this.writeBoxHeader(e,e.size??e.contents.byteLength+8),this.writer.write(e.contents);else{const t=this.writer.getPos();if(this.writeBoxHeader(e,0),e.contents&&this.writer.write(e.contents),e.children)for(const t of e.children)t&&this.writeBox(t);const i=this.writer.getPos(),r=e.size??i-t;this.writer.seek(t),this.writeBoxHeader(e,r),this.writer.seek(i)}}writeBoxHeader(e,t){this.writeU32(e.largeSize?1:t),this.writeAscii(e.type),e.largeSize&&this.writeU64(t)}measureBoxHeader(e){return 8+(e.largeSize?8:0)}patchBox(e){const t=this.offsets.get(e);r(void 0!==t);const i=this.writer.getPos();this.writer.seek(t),this.writeBox(e),this.writer.seek(i)}measureBox(e){if(e.contents&&!e.children){return this.measureBoxHeader(e)+e.contents.byteLength}{let t=this.measureBoxHeader(e);if(e.contents&&(t+=e.contents.byteLength),e.children)for(const i of e.children)i&&(t+=this.measureBox(i));return t}}}const Se=new Uint8Array(8),Ee=new DataView(Se.buffer),_e=e=>[(e%256+256)%256],Be=e=>(Ee.setUint16(0,e,!1),[Se[0],Se[1]]),Ae=e=>(Ee.setInt16(0,e,!1),[Se[0],Se[1]]),Me=e=>(Ee.setUint32(0,e,!1),[Se[1],Se[2],Se[3]]),xe=e=>(Ee.setUint32(0,e,!1),[Se[0],Se[1],Se[2],Se[3]]),Pe=e=>(Ee.setInt32(0,e,!1),[Se[0],Se[1],Se[2],Se[3]]),Ie=e=>(Ee.setUint32(0,Math.floor(e/2**32),!1),Ee.setUint32(4,e,!1),[Se[0],Se[1],Se[2],Se[3],Se[4],Se[5],Se[6],Se[7]]),De=e=>(Ee.setInt16(0,256*e,!1),[Se[0],Se[1]]),Ve=e=>(Ee.setInt32(0,65536*e,!1),[Se[0],Se[1],Se[2],Se[3]]),Ue=e=>(Ee.setInt32(0,2**30*e,!1),[Se[0],Se[1],Se[2],Se[3]]),Fe=(e,t)=>{const i=[];let r=e;do{let e=127&r;r>>=7,i.length>0&&(e|=128),i.push(e)}while(r>0||t);return i.reverse()},We=(e,t=!1)=>{const i=Array(e.length).fill(null).map((t,i)=>e.charCodeAt(i));return t&&i.push(0),i},Ne=e=>{let t=null;for(const i of e)(!t||i.timestamp>t.timestamp)&&(t=i);return t},Oe=e=>{const t=e*(Math.PI/180),i=Math.round(Math.cos(t)),r=Math.round(Math.sin(t));return[i,r,0,-r,i,0,0,0,1]},Le=Oe(0),Re=e=>[Ve(e[0]),Ve(e[1]),Ue(e[2]),Ve(e[3]),Ve(e[4]),Ue(e[5]),Ve(e[6]),Ve(e[7]),Ue(e[8])],ze=(e,t,i)=>({type:e,contents:t&&new Uint8Array(t.flat(10)),children:i}),He=(e,t,i,r,a)=>ze(e,[_e(t),Me(i),r??[]],a),je=e=>({type:"mdat",largeSize:e}),$e=e=>ze("moov",void 0,[Qe(e.creationTime,e.trackDatas),...e.trackDatas.map(t=>qe(t,e.creationTime)),e.isFragmented?_t(e.trackDatas):null,Lt(e)]),Qe=(e,t)=>{const i=di(Math.max(0,...t.filter(e=>e.samples.length>0).map(e=>{const t=Ne(e.samples);return t.timestamp+t.duration})),ni),r=Math.max(0,...t.map(e=>e.track.id))+1,a=!s(e)||!s(i),o=a?Ie:xe;return He("mvhd",+a,0,[o(e),o(e),xe(ni),o(i),Ve(1),De(1),Array(10).fill(0),Re(Le),Array(24).fill(0),xe(r)])},qe=(e,t)=>{const i=ci(e);return ze("trak",void 0,[Ke(e,t),Ge(e,t),void 0!==i.name?ze("udta",void 0,[ze("name",[...u.encode(i.name)])]):null])},Ke=(e,t)=>{const i=Ne(e.samples),r=di(i?i.timestamp+i.duration:0,ni),a=!s(t)||!s(r),o=a?Ie:xe;let n;if("video"===e.type){const t=e.track.metadata.rotation;n=Oe(t??0)}else n=Le;let c=2;return!1!==e.track.metadata.disposition?.default&&(c|=1),He("tkhd",+a,c,[o(t),o(t),xe(e.track.id),xe(0),o(r),Array(8).fill(0),Be(0),Be(e.track.id),De("audio"===e.type?1:0),Be(0),Re(n),Ve("video"===e.type?e.info.width:0),Ve("video"===e.type?e.info.height:0)])},Ge=(e,t)=>ze("mdia",void 0,[Xe(e,t),Ze(!0,Ye[e.type],Je[e.type]),et(e)]),Xe=(e,t)=>{const i=Ne(e.samples),r=di(i?i.timestamp+i.duration:0,e.timescale),a=!s(t)||!s(r),o=a?Ie:xe;return He("mdhd",+a,0,[o(t),o(t),xe(e.timescale),o(r),Be(ei(e.track.metadata.languageCode??"und")),Be(0)])},Ye={video:"vide",audio:"soun",subtitle:"text"},Je={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},Ze=(e,t,i,r="\0\0\0\0")=>He("hdlr",0,0,[e?We("mhlr"):xe(0),We(t),We(r),xe(0),xe(0),We(i,!0)]),et=e=>ze("minf",void 0,[tt[e.type](),it(),st(e)]),tt={video:()=>He("vmhd",0,1,[Be(0),Be(0),Be(0),Be(0)]),audio:()=>He("smhd",0,0,[Be(0),Be(0)]),subtitle:()=>He("nmhd",0,0)},it=()=>ze("dinf",void 0,[rt()]),rt=()=>He("dref",0,0,[xe(1)],[at()]),at=()=>He("url ",0,1),st=e=>{const t=e.compositionTimeOffsetTable.length>1||e.compositionTimeOffsetTable.some(e=>0!==e.sampleCompositionTimeOffset);return ze("stbl",void 0,[ot(e),yt(e),t?St(e):null,t?Et(e):null,Tt(e),Ct(e),vt(e),bt(e)])},ot=e=>{let t;if("video"===e.type)t=nt(Kt(e.track.source._codec,e.info.decoderConfig.codec),e);else if("audio"===e.type){const i=Xt(e.track.source._codec,e.muxer.isQuickTime);r(i),t=ut(i,e)}else"subtitle"===e.type&&(t=kt(Jt[e.track.source._codec],e));return r(t),He("stsd",0,0,[xe(1)],[t])},nt=(e,t)=>ze(e,[Array(6).fill(0),Be(1),Be(0),Be(0),Array(12).fill(0),Be(t.info.width),Be(t.info.height),xe(4718592),xe(4718592),xe(0),Be(1),Array(32).fill(0),Be(24),Ae(65535)],[Gt[t.track.source._codec](t),p(t.info.decoderConfig.colorSpace)?ct(t):null]),ct=e=>ze("colr",[We("nclx"),Be(l[e.info.decoderConfig.colorSpace.primaries]),Be(h[e.info.decoderConfig.colorSpace.transfer]),Be(m[e.info.decoderConfig.colorSpace.matrix]),_e((e.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),dt=e=>{if(!e.info.decoderConfig)return null;const t=e.info.decoderConfig,i=t.codec.split("."),r=Number(i[1]),a=Number(i[2]),s=(Number(i[3])<<4)+((i[4]?Number(i[4]):1)<<1)+(i[8]?Number(i[8]):Number(t.colorSpace?.fullRange??0)),o=i[5]?Number(i[5]):t.colorSpace?.primaries?l[t.colorSpace.primaries]:2,n=i[6]?Number(i[6]):t.colorSpace?.transfer?h[t.colorSpace.transfer]:2,c=i[7]?Number(i[7]):t.colorSpace?.matrix?m[t.colorSpace.matrix]:2;return He("vpcC",1,0,[_e(r),_e(a),_e(s),_e(o),_e(n),_e(c),Be(0)])},ut=(e,t)=>{let i,r=0,a=16;if(A.includes(t.track.source._codec)){const e=t.track.source._codec,{sampleSize:i}=U(e);a=8*i,a>16&&(r=1)}return i=0===r?[Array(6).fill(0),Be(1),Be(r),Be(0),xe(0),Be(t.info.numberOfChannels),Be(a),Be(0),Be(0),Be(t.info.sampleRate<65536?t.info.sampleRate:0),Be(0)]:[Array(6).fill(0),Be(1),Be(r),Be(0),xe(0),Be(t.info.numberOfChannels),Be(Math.min(a,16)),Be(0),Be(0),Be(t.info.sampleRate<65536?t.info.sampleRate:0),Be(0),xe(1),xe(a/8),xe(t.info.numberOfChannels*a/8),xe(2)],ze(e,i,[Yt(t.track.source._codec,t.muxer.isQuickTime)?.(t)??null])},lt=e=>{let t;switch(e.track.source._codec){case"aac":t=64;break;case"mp3":t=107;break;case"vorbis":t=221;break;default:throw new Error(`Unhandled audio codec: ${e.track.source._codec}`)}let i=[..._e(t),..._e(21),...Me(0),...xe(0),...xe(0)];if(e.info.decoderConfig.description){const t=d(e.info.decoderConfig.description);i=[...i,..._e(5),...Fe(t.byteLength),...t]}return i=[...Be(1),..._e(0),..._e(4),...Fe(i.length),...i,..._e(6),..._e(1),..._e(2)],i=[..._e(3),...Fe(i.length),...i],He("esds",0,0,i)},ht=e=>ze("wave",void 0,[mt(e),pt(e),ze("\0\0\0\0")]),mt=e=>ze("frma",[We(Xt(e.track.source._codec,e.muxer.isQuickTime))]),pt=e=>{const{littleEndian:t}=U(e.track.source._codec);return ze("enda",[Be(+t)])},ft=e=>{let t=e.info.numberOfChannels,i=3840,a=e.info.sampleRate,s=0,o=0,n=new Uint8Array(0);const c=e.info.decoderConfig?.description;if(c){r(c.byteLength>=18);const e=d(c),u=oe(e);t=u.outputChannelCount,i=u.preSkip,a=u.inputSampleRate,s=u.outputGain,o=u.channelMappingFamily,u.channelMappingTable&&(n=u.channelMappingTable)}return ze("dOps",[_e(0),_e(t),Be(i),xe(a),Ae(s),_e(o),...n])},gt=e=>{const t=e.info.decoderConfig?.description;r(t);const i=d(t);return He("dfLa",0,0,[...i.subarray(4)])},wt=e=>{const{littleEndian:t,sampleSize:i}=U(e.track.source._codec);return He("pcmC",0,0,[_e(+t),_e(8*i)])},kt=(e,t)=>ze(e,[Array(6).fill(0),Be(1)],[Zt[t.track.source._codec](t)]),yt=e=>He("stts",0,0,[xe(e.timeToSampleTable.length),e.timeToSampleTable.map(e=>[xe(e.sampleCount),xe(e.sampleDelta)])]),bt=e=>{if(e.samples.every(e=>"key"===e.type))return null;const t=[...e.samples.entries()].filter(([,e])=>"key"===e.type);return He("stss",0,0,[xe(t.length),t.map(([e])=>xe(e+1))])},Tt=e=>He("stsc",0,0,[xe(e.compactlyCodedChunkTable.length),e.compactlyCodedChunkTable.map(e=>[xe(e.firstChunk),xe(e.samplesPerChunk),xe(1)])]),Ct=e=>{if("audio"===e.type&&e.info.requiresPcmTransformation){const{sampleSize:t}=U(e.track.source._codec);return He("stsz",0,0,[xe(t*e.info.numberOfChannels),xe(e.samples.reduce((t,i)=>t+di(i.duration,e.timescale),0))])}return He("stsz",0,0,[xe(0),xe(e.samples.length),e.samples.map(e=>xe(e.size))])},vt=e=>e.finalizedChunks.length>0&&a(e.finalizedChunks).offset>=2**32?He("co64",0,0,[xe(e.finalizedChunks.length),e.finalizedChunks.map(e=>Ie(e.offset))]):He("stco",0,0,[xe(e.finalizedChunks.length),e.finalizedChunks.map(e=>xe(e.offset))]),St=e=>He("ctts",1,0,[xe(e.compositionTimeOffsetTable.length),e.compositionTimeOffsetTable.map(e=>[xe(e.sampleCount),Pe(e.sampleCompositionTimeOffset)])]),Et=e=>{let t=1/0,i=-1/0,a=1/0,s=-1/0;r(e.compositionTimeOffsetTable.length>0),r(e.samples.length>0);for(let r=0;r<e.compositionTimeOffsetTable.length;r++){const a=e.compositionTimeOffsetTable[r];t=Math.min(t,a.sampleCompositionTimeOffset),i=Math.max(i,a.sampleCompositionTimeOffset)}for(let t=0;t<e.samples.length;t++){const i=e.samples[t];a=Math.min(a,di(i.timestamp,e.timescale)),s=Math.max(s,di(i.timestamp+i.duration,e.timescale))}const o=Math.max(-t,0);return s>=2**31?null:He("cslg",0,0,[Pe(o),Pe(t),Pe(i),Pe(a),Pe(s)])},_t=e=>ze("mvex",void 0,e.map(Bt)),Bt=e=>He("trex",0,0,[xe(e.track.id),xe(1),xe(0),xe(0),xe(0)]),At=(e,t)=>ze("moof",void 0,[Mt(e),...t.map(Pt)]),Mt=e=>He("mfhd",0,0,[xe(e)]),xt=e=>{let t=0,i=0;const r="delta"===e.type;return i|=+r,t|=r?1:2,t<<24|i<<16},Pt=e=>ze("traf",void 0,[It(e),Dt(e),Vt(e)]),It=e=>{r(e.currentChunk);let t=0;t|=8,t|=16,t|=32,t|=131072;const i=e.currentChunk.samples[1]??e.currentChunk.samples[0],a={duration:i.timescaleUnitsToNextSample,size:i.size,flags:xt(i)};return He("tfhd",0,131128,[xe(e.track.id),xe(a.duration),xe(a.size),xe(a.flags)])},Dt=e=>(r(e.currentChunk),He("tfdt",1,0,[Ie(di(e.currentChunk.startTimestamp,e.timescale))])),Vt=e=>{r(e.currentChunk);const t=e.currentChunk.samples.map(e=>e.timescaleUnitsToNextSample),i=e.currentChunk.samples.map(e=>e.size),a=e.currentChunk.samples.map(xt),s=e.currentChunk.samples.map(t=>di(t.timestamp-t.decodeTimestamp,e.timescale)),o=new Set(t),n=new Set(i),c=new Set(a),d=new Set(s),u=2===c.size&&a[0]!==a[1],l=o.size>1,h=n.size>1,m=!u&&c.size>1,p=d.size>1||[...d].some(e=>0!==e);let f=0;return f|=1,f|=4*+u,f|=256*+l,f|=512*+h,f|=1024*+m,f|=2048*+p,He("trun",1,f,[xe(e.currentChunk.samples.length),xe(e.currentChunk.offset-e.currentChunk.moofOffset||0),u?xe(a[0]):[],e.currentChunk.samples.map((e,r)=>[l?xe(t[r]):[],h?xe(i[r]):[],m?xe(a[r]):[],p?Pe(s[r]):[]])])},Ut=(e,t)=>He("tfra",1,0,[xe(e.track.id),xe(63),xe(e.finalizedChunks.length),e.finalizedChunks.map(i=>[Ie(di(i.samples[0].timestamp,e.timescale)),Ie(i.moofOffset),xe(t+1),xe(1),xe(1)])]),Ft=()=>He("mfro",0,0,[xe(0)]),Wt=()=>ze("vtte"),Nt=(e,t,i,r,a)=>ze("vttc",void 0,[null!==a?ze("vsid",[Pe(a)]):null,null!==i?ze("iden",[...u.encode(i)]):null,null!==t?ze("ctim",[...u.encode(Ce(t))]):null,null!==r?ze("sttg",[...u.encode(r)]):null,ze("payl",[...u.encode(e)])]),Ot=e=>ze("vtta",[...u.encode(e)]),Lt=e=>{const t=[],i=e.format._options.metadataFormat??"auto",r=e.output._metadataTags;if("mdir"===i||"auto"===i&&!e.isQuickTime){const e=$t(r);e&&t.push(e)}else if("mdta"===i){const e=Qt(r);e&&t.push(e)}else("udta"===i||"auto"===i&&e.isQuickTime)&&Rt(t,e.output._metadataTags);return 0===t.length?null:ze("udta",void 0,t)},Rt=(e,t)=>{for(const{key:i,value:r}of C(t))switch(i){case"title":e.push(zt("©nam",r));break;case"description":e.push(zt("©des",r));break;case"artist":e.push(zt("©ART",r));break;case"album":e.push(zt("©alb",r));break;case"albumArtist":e.push(zt("albr",r));break;case"genre":e.push(zt("©gen",r));break;case"date":e.push(zt("©day",r.toISOString().slice(0,10)));break;case"comment":e.push(zt("©cmt",r));break;case"lyrics":e.push(zt("©lyr",r));break;case"raw":case"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"images":break;default:k(i)}if(t.raw)for(const i in t.raw){const r=t.raw[i];null==r||4!==i.length||e.some(e=>e.type===i)||("string"==typeof r?e.push(zt(i,r)):r instanceof Uint8Array&&e.push(ze(i,Array.from(r))))}},zt=(e,t)=>{const i=u.encode(t);return ze(e,[Be(i.length),Be(ei("und")),Array.from(i)])},Ht={"image/jpeg":13,"image/png":14,"image/bmp":27},jt=(e,t)=>{const i=[];for(const{key:r,value:a}of C(e))switch(r){case"title":i.push({key:t?"title":"©nam",value:qt(a)});break;case"description":i.push({key:t?"description":"©des",value:qt(a)});break;case"artist":i.push({key:t?"artist":"©ART",value:qt(a)});break;case"album":i.push({key:t?"album":"©alb",value:qt(a)});break;case"albumArtist":i.push({key:t?"album_artist":"aART",value:qt(a)});break;case"comment":i.push({key:t?"comment":"©cmt",value:qt(a)});break;case"genre":i.push({key:t?"genre":"©gen",value:qt(a)});break;case"lyrics":i.push({key:t?"lyrics":"©lyr",value:qt(a)});break;case"date":i.push({key:t?"date":"©day",value:qt(a.toISOString().slice(0,10))});break;case"images":for(const e of a)"coverFront"===e.kind&&i.push({key:"covr",value:ze("data",[xe(Ht[e.mimeType]??0),xe(0),Array.from(e.data)])});break;case"trackNumber":if(t){const t=void 0!==e.tracksTotal?`${a}/${e.tracksTotal}`:a.toString();i.push({key:"track",value:qt(t)})}else i.push({key:"trkn",value:ze("data",[xe(0),xe(0),Be(0),Be(a),Be(e.tracksTotal??0),Be(0)])});break;case"discNumber":t||i.push({key:"disc",value:ze("data",[xe(0),xe(0),Be(0),Be(a),Be(e.discsTotal??0),Be(0)])});break;case"tracksTotal":case"discsTotal":case"raw":break;default:k(r)}if(e.raw)for(const r in e.raw){const a=e.raw[r];null==a||!t&&4!==r.length||i.some(e=>e.key===r)||("string"==typeof a?i.push({key:r,value:qt(a)}):a instanceof Uint8Array?i.push({key:r,value:ze("data",[xe(0),xe(0),Array.from(a)])}):a instanceof E&&i.push({key:r,value:ze("data",[xe(Ht[a.mimeType]??0),xe(0),Array.from(a.data)])}))}return i},$t=e=>{const t=jt(e,!1);return 0===t.length?null:He("meta",0,0,void 0,[Ze(!1,"mdir","","appl"),ze("ilst",void 0,t.map(e=>ze(e.key,void 0,[e.value])))])},Qt=e=>{const t=jt(e,!0);return 0===t.length?null:ze("meta",void 0,[Ze(!1,"mdta",""),He("keys",0,0,[xe(t.length)],t.map(e=>ze("mdta",[...u.encode(e.key)]))),ze("ilst",void 0,t.map((e,t)=>{const i=String.fromCharCode(...xe(t+1));return ze(i,void 0,[e.value])}))])},qt=e=>ze("data",[xe(1),xe(0),...u.encode(e)]),Kt=(e,t)=>{switch(e){case"avc":return t.startsWith("avc3")?"avc3":"avc1";case"hevc":return"hvc1";case"vp8":return"vp08";case"vp9":return"vp09";case"av1":return"av01"}},Gt={avc:e=>e.info.decoderConfig&&ze("avcC",[...d(e.info.decoderConfig.description)]),hevc:e=>e.info.decoderConfig&&ze("hvcC",[...d(e.info.decoderConfig.description)]),vp8:dt,vp9:dt,av1:e=>ze("av1C",D(e.info.decoderConfig.codec))},Xt=(e,t)=>{switch(e){case"aac":case"mp3":case"vorbis":return"mp4a";case"opus":return"Opus";case"flac":return"fLaC";case"ulaw":return"ulaw";case"alaw":return"alaw";case"pcm-u8":return"raw ";case"pcm-s8":return"sowt"}if(t)switch(e){case"pcm-s16":return"sowt";case"pcm-s16be":return"twos";case"pcm-s24":case"pcm-s24be":return"in24";case"pcm-s32":case"pcm-s32be":return"in32";case"pcm-f32":case"pcm-f32be":return"fl32";case"pcm-f64":case"pcm-f64be":return"fl64"}else switch(e){case"pcm-s16":case"pcm-s16be":case"pcm-s24":case"pcm-s24be":case"pcm-s32":case"pcm-s32be":return"ipcm";case"pcm-f32":case"pcm-f32be":case"pcm-f64":case"pcm-f64be":return"fpcm"}},Yt=(e,t)=>{switch(e){case"aac":case"mp3":case"vorbis":return lt;case"opus":return ft;case"flac":return gt}if(t)switch(e){case"pcm-s24":case"pcm-s24be":case"pcm-s32":case"pcm-s32be":case"pcm-f32":case"pcm-f32be":case"pcm-f64":case"pcm-f64be":return ht}else switch(e){case"pcm-s16":case"pcm-s16be":case"pcm-s24":case"pcm-s24be":case"pcm-s32":case"pcm-s32be":case"pcm-f32":case"pcm-f32be":case"pcm-f64":case"pcm-f64be":return wt}return null},Jt={webvtt:"wvtt"},Zt={webvtt:e=>ze("vttC",[...u.encode(e.info.config.description)])},ei=e=>{r(3===e.length);let t=0;for(let i=0;i<3;i++)t<<=5,t+=e.charCodeAt(i)-96;return t};
|
|
223
|
+
class Vi{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=new WeakMap}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeU64(e){this.helperView.setUint32(0,Math.floor(e/2**32),!1),this.helperView.setUint32(4,e,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii(e){for(let t=0;t<e.length;t++)this.helperView.setUint8(t%8,e.charCodeAt(t)),t%8==7&&this.writer.write(this.helper);e.length%8!=0&&this.writer.write(this.helper.subarray(0,e.length%8))}writeBox(e){if(this.offsets.set(e,this.writer.getPos()),e.contents&&!e.children)this.writeBoxHeader(e,e.size??e.contents.byteLength+8),this.writer.write(e.contents);else{const t=this.writer.getPos();if(this.writeBoxHeader(e,0),e.contents&&this.writer.write(e.contents),e.children)for(const t of e.children)t&&this.writeBox(t);const r=this.writer.getPos(),a=e.size??r-t;this.writer.seek(t),this.writeBoxHeader(e,a),this.writer.seek(r)}}writeBoxHeader(e,t){this.writeU32(e.largeSize?1:t),this.writeAscii(e.type),e.largeSize&&this.writeU64(t)}measureBoxHeader(e){return 8+(e.largeSize?8:0)}patchBox(e){const t=this.offsets.get(e);n(void 0!==t);const r=this.writer.getPos();this.writer.seek(t),this.writeBox(e),this.writer.seek(r)}measureBox(e){if(e.contents&&!e.children){return this.measureBoxHeader(e)+e.contents.byteLength}{let t=this.measureBoxHeader(e);if(e.contents&&(t+=e.contents.byteLength),e.children)for(const r of e.children)r&&(t+=this.measureBox(r));return t}}}const Wi=new Uint8Array(8),Hi=new DataView(Wi.buffer),qi=e=>[(e%256+256)%256],ji=e=>(Hi.setUint16(0,e,!1),[Wi[0],Wi[1]]),$i=e=>(Hi.setInt16(0,e,!1),[Wi[0],Wi[1]]),Qi=e=>(Hi.setUint32(0,e,!1),[Wi[1],Wi[2],Wi[3]]),Ki=e=>(Hi.setUint32(0,e,!1),[Wi[0],Wi[1],Wi[2],Wi[3]]),Gi=e=>(Hi.setInt32(0,e,!1),[Wi[0],Wi[1],Wi[2],Wi[3]]),Xi=e=>(Hi.setUint32(0,Math.floor(e/2**32),!1),Hi.setUint32(4,e,!1),[Wi[0],Wi[1],Wi[2],Wi[3],Wi[4],Wi[5],Wi[6],Wi[7]]),Yi=e=>(Hi.setInt16(0,256*e,!1),[Wi[0],Wi[1]]),Ji=e=>(Hi.setInt32(0,65536*e,!1),[Wi[0],Wi[1],Wi[2],Wi[3]]),Zi=e=>(Hi.setInt32(0,2**30*e,!1),[Wi[0],Wi[1],Wi[2],Wi[3]]),es=(e,t)=>{const r=[];let a=e;do{let e=127&a;a>>=7,r.length>0&&(e|=128),r.push(e)}while(a>0||t);return r.reverse()},ts=(e,t=!1)=>{const r=Array(e.length).fill(null).map((t,r)=>e.charCodeAt(r));return t&&r.push(0),r},rs=e=>{let t=null;for(const r of e)(!t||r.timestamp>t.timestamp)&&(t=r);return t},as=e=>{const t=e*(Math.PI/180),r=Math.round(Math.cos(t)),a=Math.round(Math.sin(t));return[r,a,0,-a,r,0,0,0,1]},is=as(0),ss=e=>[Ji(e[0]),Ji(e[1]),Zi(e[2]),Ji(e[3]),Ji(e[4]),Zi(e[5]),Ji(e[6]),Ji(e[7]),Zi(e[8])],ns=(e,t,r)=>({type:e,contents:t&&new Uint8Array(t.flat(10)),children:r}),os=(e,t,r,a,i)=>ns(e,[qi(t),Qi(r),a??[]],i),cs=e=>({type:"mdat",largeSize:e}),ds=e=>ns("moov",void 0,[us(e.creationTime,e.trackDatas),...e.trackDatas.map(t=>ls(t,e.creationTime)),e.isFragmented?qs(e.trackDatas):null,sn(e)]),us=(e,t)=>{const r=En(Math.max(0,...t.filter(e=>e.samples.length>0).map(e=>{const t=rs(e.samples);return t.timestamp+t.duration})),In),a=Math.max(0,...t.map(e=>e.track.id))+1,i=!d(e)||!d(r),s=i?Xi:Ki;return os("mvhd",+i,0,[s(e),s(e),Ki(In),s(r),Ji(1),Yi(1),Array(10).fill(0),ss(is),Array(24).fill(0),Ki(a)])},ls=(e,t)=>{const r=xn(e);return ns("trak",void 0,[hs(e,t),ms(e,t),void 0!==r.name?ns("udta",void 0,[ns("name",[...g.encode(r.name)])]):null])},hs=(e,t)=>{const r=rs(e.samples),a=En(r?r.timestamp+r.duration:0,In),i=!d(t)||!d(a),s=i?Xi:Ki;let n;if("video"===e.type){const t=e.track.metadata.rotation;n=as(t??0)}else n=is;let o=2;return!1!==e.track.metadata.disposition?.default&&(o|=1),os("tkhd",+i,o,[s(t),s(t),Ki(e.track.id),Ki(0),s(a),Array(8).fill(0),ji(0),ji(e.track.id),Yi("audio"===e.type?1:0),ji(0),ss(n),Ji("video"===e.type?e.info.width:0),Ji("video"===e.type?e.info.height:0)])},ms=(e,t)=>ns("mdia",void 0,[fs(e,t),ks(!0,ps[e.type],gs[e.type]),bs(e)]),fs=(e,t)=>{const r=rs(e.samples),a=En(r?r.timestamp+r.duration:0,e.timescale),i=!d(t)||!d(a),s=i?Xi:Ki;return os("mdhd",+i,0,[s(t),s(t),Ki(e.timescale),s(a),ji(wn(e.track.metadata.languageCode??L)),ji(0)])},ps={video:"vide",audio:"soun",subtitle:"text"},gs={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},ks=(e,t,r,a="\0\0\0\0")=>os("hdlr",0,0,[e?ts("mhlr"):Ki(0),ts(t),ts(a),Ki(0),Ki(0),ts(r,!0)]),bs=e=>ns("minf",void 0,[ws[e.type](),Ts(),Cs(e)]),ws={video:()=>os("vmhd",0,1,[ji(0),ji(0),ji(0),ji(0)]),audio:()=>os("smhd",0,0,[ji(0),ji(0)]),subtitle:()=>os("nmhd",0,0)},Ts=()=>ns("dinf",void 0,[ys()]),ys=()=>os("dref",0,0,[Ki(1)],[Ss()]),Ss=()=>os("url ",0,1),Cs=e=>{const t=e.compositionTimeOffsetTable.length>1||e.compositionTimeOffsetTable.some(e=>0!==e.sampleCompositionTimeOffset);return ns("stbl",void 0,[vs(e),Os(e),t?Ws(e):null,t?Hs(e):null,Ls(e),Us(e),Vs(e),Ns(e)])},vs=e=>{let t;if("video"===e.type)t=Ps(mn(e.track.source._codec,e.info.decoderConfig.codec),e);else if("audio"===e.type){const r=pn(e.track.source._codec,e.muxer.isQuickTime);n(r),t=Es(r,e)}else"subtitle"===e.type&&(t=zs(kn[e.track.source._codec],e));return n(t),os("stsd",0,0,[Ki(1)],[t])},Ps=(e,t)=>ns(e,[Array(6).fill(0),ji(1),ji(0),ji(0),Array(12).fill(0),ji(t.info.width),ji(t.info.height),Ki(4718592),Ki(4718592),Ki(0),ji(1),Array(32).fill(0),ji(24),$i(65535)],[fn[t.track.source._codec](t),v(t.info.decoderConfig.colorSpace)?Is(t):null]),Is=e=>ns("colr",[ts("nclx"),ji(b[e.info.decoderConfig.colorSpace.primaries]),ji(T[e.info.decoderConfig.colorSpace.transfer]),ji(S[e.info.decoderConfig.colorSpace.matrix]),qi((e.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),xs=e=>{if(!e.info.decoderConfig)return null;const t=e.info.decoderConfig,r=t.codec.split("."),a=Number(r[1]),i=Number(r[2]),s=(Number(r[3])<<4)+((r[4]?Number(r[4]):1)<<1)+(r[8]?Number(r[8]):Number(t.colorSpace?.fullRange??0)),n=r[5]?Number(r[5]):t.colorSpace?.primaries?b[t.colorSpace.primaries]:2,o=r[6]?Number(r[6]):t.colorSpace?.transfer?T[t.colorSpace.transfer]:2,c=r[7]?Number(r[7]):t.colorSpace?.matrix?S[t.colorSpace.matrix]:2;return os("vpcC",1,0,[qi(a),qi(i),qi(s),qi(n),qi(o),qi(c),ji(0)])},Es=(e,t)=>{let r,a=0,i=16;if(me.includes(t.track.source._codec)){const e=t.track.source._codec,{sampleSize:r}=De(e);i=8*r,i>16&&(a=1)}return r=0===a?[Array(6).fill(0),ji(1),ji(a),ji(0),Ki(0),ji(t.info.numberOfChannels),ji(i),ji(0),ji(0),ji(t.info.sampleRate<65536?t.info.sampleRate:0),ji(0)]:[Array(6).fill(0),ji(1),ji(a),ji(0),Ki(0),ji(t.info.numberOfChannels),ji(Math.min(i,16)),ji(0),ji(0),ji(t.info.sampleRate<65536?t.info.sampleRate:0),ji(0),Ki(1),Ki(i/8),Ki(t.info.numberOfChannels*i/8),Ki(2)],ns(e,r,[gn(t.track.source._codec,t.muxer.isQuickTime)?.(t)??null])},Ds=e=>{let t;switch(e.track.source._codec){case"aac":t=64;break;case"mp3":t=107;break;case"vorbis":t=221;break;default:throw new Error(`Unhandled audio codec: ${e.track.source._codec}`)}let r=[...qi(t),...qi(21),...Qi(0),...Ki(0),...Ki(0)];if(e.info.decoderConfig.description){const t=m(e.info.decoderConfig.description);r=[...r,...qi(5),...es(t.byteLength),...t]}return r=[...ji(1),...qi(0),...qi(4),...es(r.length),...r,...qi(6),...qi(1),...qi(2)],r=[...qi(3),...es(r.length),...r],os("esds",0,0,r)},Bs=e=>ns("wave",void 0,[As(e),_s(e),ns("\0\0\0\0")]),As=e=>ns("frma",[ts(pn(e.track.source._codec,e.muxer.isQuickTime))]),_s=e=>{const{littleEndian:t}=De(e.track.source._codec);return ns("enda",[ji(+t)])},Fs=e=>{let t=e.info.numberOfChannels,r=3840,a=e.info.sampleRate,i=0,s=0,o=new Uint8Array(0);const c=e.info.decoderConfig?.description;if(c){n(c.byteLength>=18);const e=m(c),d=lt(e);t=d.outputChannelCount,r=d.preSkip,a=d.inputSampleRate,i=d.outputGain,s=d.channelMappingFamily,d.channelMappingTable&&(o=d.channelMappingTable)}return ns("dOps",[qi(0),qi(t),ji(r),Ki(a),$i(i),qi(s),...o])},Ms=e=>{const t=e.info.decoderConfig?.description;n(t);const r=m(t);return os("dfLa",0,0,[...r.subarray(4)])},Rs=e=>{const{littleEndian:t,sampleSize:r}=De(e.track.source._codec);return os("pcmC",0,0,[qi(+t),qi(8*r)])},zs=(e,t)=>ns(e,[Array(6).fill(0),ji(1)],[bn[t.track.source._codec](t)]),Os=e=>os("stts",0,0,[Ki(e.timeToSampleTable.length),e.timeToSampleTable.map(e=>[Ki(e.sampleCount),Ki(e.sampleDelta)])]),Ns=e=>{if(e.samples.every(e=>"key"===e.type))return null;const t=[...e.samples.entries()].filter(([,e])=>"key"===e.type);return os("stss",0,0,[Ki(t.length),t.map(([e])=>Ki(e+1))])},Ls=e=>os("stsc",0,0,[Ki(e.compactlyCodedChunkTable.length),e.compactlyCodedChunkTable.map(e=>[Ki(e.firstChunk),Ki(e.samplesPerChunk),Ki(1)])]),Us=e=>{if("audio"===e.type&&e.info.requiresPcmTransformation){const{sampleSize:t}=De(e.track.source._codec);return os("stsz",0,0,[Ki(t*e.info.numberOfChannels),Ki(e.samples.reduce((t,r)=>t+En(r.duration,e.timescale),0))])}return os("stsz",0,0,[Ki(0),Ki(e.samples.length),e.samples.map(e=>Ki(e.size))])},Vs=e=>e.finalizedChunks.length>0&&c(e.finalizedChunks).offset>=2**32?os("co64",0,0,[Ki(e.finalizedChunks.length),e.finalizedChunks.map(e=>Xi(e.offset))]):os("stco",0,0,[Ki(e.finalizedChunks.length),e.finalizedChunks.map(e=>Ki(e.offset))]),Ws=e=>os("ctts",1,0,[Ki(e.compositionTimeOffsetTable.length),e.compositionTimeOffsetTable.map(e=>[Ki(e.sampleCount),Gi(e.sampleCompositionTimeOffset)])]),Hs=e=>{let t=1/0,r=-1/0,a=1/0,i=-1/0;n(e.compositionTimeOffsetTable.length>0),n(e.samples.length>0);for(let a=0;a<e.compositionTimeOffsetTable.length;a++){const i=e.compositionTimeOffsetTable[a];t=Math.min(t,i.sampleCompositionTimeOffset),r=Math.max(r,i.sampleCompositionTimeOffset)}for(let t=0;t<e.samples.length;t++){const r=e.samples[t];a=Math.min(a,En(r.timestamp,e.timescale)),i=Math.max(i,En(r.timestamp+r.duration,e.timescale))}const s=Math.max(-t,0);return i>=2**31?null:os("cslg",0,0,[Gi(s),Gi(t),Gi(r),Gi(a),Gi(i)])},qs=e=>ns("mvex",void 0,e.map(js)),js=e=>os("trex",0,0,[Ki(e.track.id),Ki(1),Ki(0),Ki(0),Ki(0)]),$s=(e,t)=>ns("moof",void 0,[Qs(e),...t.map(Gs)]),Qs=e=>os("mfhd",0,0,[Ki(e)]),Ks=e=>{let t=0,r=0;const a="delta"===e.type;return r|=+a,t|=a?1:2,t<<24|r<<16},Gs=e=>ns("traf",void 0,[Xs(e),Ys(e),Js(e)]),Xs=e=>{n(e.currentChunk);let t=0;t|=8,t|=16,t|=32,t|=131072;const r=e.currentChunk.samples[1]??e.currentChunk.samples[0],a={duration:r.timescaleUnitsToNextSample,size:r.size,flags:Ks(r)};return os("tfhd",0,131128,[Ki(e.track.id),Ki(a.duration),Ki(a.size),Ki(a.flags)])},Ys=e=>(n(e.currentChunk),os("tfdt",1,0,[Xi(En(e.currentChunk.startTimestamp,e.timescale))])),Js=e=>{n(e.currentChunk);const t=e.currentChunk.samples.map(e=>e.timescaleUnitsToNextSample),r=e.currentChunk.samples.map(e=>e.size),a=e.currentChunk.samples.map(Ks),i=e.currentChunk.samples.map(t=>En(t.timestamp-t.decodeTimestamp,e.timescale)),s=new Set(t),o=new Set(r),c=new Set(a),d=new Set(i),u=2===c.size&&a[0]!==a[1],l=s.size>1,h=o.size>1,m=!u&&c.size>1,f=d.size>1||[...d].some(e=>0!==e);let p=0;return p|=1,p|=4*+u,p|=256*+l,p|=512*+h,p|=1024*+m,p|=2048*+f,os("trun",1,p,[Ki(e.currentChunk.samples.length),Ki(e.currentChunk.offset-e.currentChunk.moofOffset||0),u?Ki(a[0]):[],e.currentChunk.samples.map((e,s)=>[l?Ki(t[s]):[],h?Ki(r[s]):[],m?Ki(a[s]):[],f?Gi(i[s]):[]])])},Zs=(e,t)=>os("tfra",1,0,[Ki(e.track.id),Ki(63),Ki(e.finalizedChunks.length),e.finalizedChunks.map(r=>[Xi(En(r.samples[0].timestamp,e.timescale)),Xi(r.moofOffset),Ki(t+1),Ki(1),Ki(1)])]),en=()=>os("mfro",0,0,[Ki(0)]),tn=()=>ns("vtte"),rn=(e,t,r,a,i)=>ns("vttc",void 0,[null!==i?ns("vsid",[Gi(i)]):null,null!==r?ns("iden",[...g.encode(r)]):null,null!==t?ns("ctim",[...g.encode(Ui(t))]):null,null!==a?ns("sttg",[...g.encode(a)]):null,ns("payl",[...g.encode(e)])]),an=e=>ns("vtta",[...g.encode(e)]),sn=e=>{const t=[],r=e.format._options.metadataFormat??"auto",a=e.output._metadataTags;if("mdir"===r||"auto"===r&&!e.isQuickTime){const e=un(a);e&&t.push(e)}else if("mdta"===r){const e=ln(a);e&&t.push(e)}else("udta"===r||"auto"===r&&e.isQuickTime)&&nn(t,e.output._metadataTags);return 0===t.length?null:ns("udta",void 0,t)},nn=(e,t)=>{for(const{key:r,value:a}of ae(t))switch(r){case"title":e.push(on("©nam",a));break;case"description":e.push(on("©des",a));break;case"artist":e.push(on("©ART",a));break;case"album":e.push(on("©alb",a));break;case"albumArtist":e.push(on("albr",a));break;case"genre":e.push(on("©gen",a));break;case"date":e.push(on("©day",a.toISOString().slice(0,10)));break;case"comment":e.push(on("©cmt",a));break;case"lyrics":e.push(on("©lyr",a));break;case"raw":case"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"images":break;default:R(r)}if(t.raw)for(const r in t.raw){const a=t.raw[r];null==a||4!==r.length||e.some(e=>e.type===r)||("string"==typeof a?e.push(on(r,a)):a instanceof Uint8Array&&e.push(ns(r,Array.from(a))))}},on=(e,t)=>{const r=g.encode(t);return ns(e,[ji(r.length),ji(wn("und")),Array.from(r)])},cn={"image/jpeg":13,"image/png":14,"image/bmp":27},dn=(e,t)=>{const r=[];for(const{key:a,value:i}of ae(e))switch(a){case"title":r.push({key:t?"title":"©nam",value:hn(i)});break;case"description":r.push({key:t?"description":"©des",value:hn(i)});break;case"artist":r.push({key:t?"artist":"©ART",value:hn(i)});break;case"album":r.push({key:t?"album":"©alb",value:hn(i)});break;case"albumArtist":r.push({key:t?"album_artist":"aART",value:hn(i)});break;case"comment":r.push({key:t?"comment":"©cmt",value:hn(i)});break;case"genre":r.push({key:t?"genre":"©gen",value:hn(i)});break;case"lyrics":r.push({key:t?"lyrics":"©lyr",value:hn(i)});break;case"date":r.push({key:t?"date":"©day",value:hn(i.toISOString().slice(0,10))});break;case"images":for(const e of i)"coverFront"===e.kind&&r.push({key:"covr",value:ns("data",[Ki(cn[e.mimeType]??0),Ki(0),Array.from(e.data)])});break;case"trackNumber":if(t){const t=void 0!==e.tracksTotal?`${i}/${e.tracksTotal}`:i.toString();r.push({key:"track",value:hn(t)})}else r.push({key:"trkn",value:ns("data",[Ki(0),Ki(0),ji(0),ji(i),ji(e.tracksTotal??0),ji(0)])});break;case"discNumber":t||r.push({key:"disc",value:ns("data",[Ki(0),Ki(0),ji(0),ji(i),ji(e.discsTotal??0),ji(0)])});break;case"tracksTotal":case"discsTotal":case"raw":break;default:R(a)}if(e.raw)for(const a in e.raw){const i=e.raw[a];null==i||!t&&4!==a.length||r.some(e=>e.key===a)||("string"==typeof i?r.push({key:a,value:hn(i)}):i instanceof Uint8Array?r.push({key:a,value:ns("data",[Ki(0),Ki(0),Array.from(i)])}):i instanceof de&&r.push({key:a,value:ns("data",[Ki(cn[i.mimeType]??0),Ki(0),Array.from(i.data)])}))}return r},un=e=>{const t=dn(e,!1);return 0===t.length?null:os("meta",0,0,void 0,[ks(!1,"mdir","","appl"),ns("ilst",void 0,t.map(e=>ns(e.key,void 0,[e.value])))])},ln=e=>{const t=dn(e,!0);return 0===t.length?null:ns("meta",void 0,[ks(!1,"mdta",""),os("keys",0,0,[Ki(t.length)],t.map(e=>ns("mdta",[...g.encode(e.key)]))),ns("ilst",void 0,t.map((e,t)=>{const r=String.fromCharCode(...Ki(t+1));return ns(r,void 0,[e.value])}))])},hn=e=>ns("data",[Ki(1),Ki(0),...g.encode(e)]),mn=(e,t)=>{switch(e){case"avc":return t.startsWith("avc3")?"avc3":"avc1";case"hevc":return"hvc1";case"vp8":return"vp08";case"vp9":return"vp09";case"av1":return"av01"}},fn={avc:e=>e.info.decoderConfig&&ns("avcC",[...m(e.info.decoderConfig.description)]),hevc:e=>e.info.decoderConfig&&ns("hvcC",[...m(e.info.decoderConfig.description)]),vp8:xs,vp9:xs,av1:e=>ns("av1C",ye(e.info.decoderConfig.codec))},pn=(e,t)=>{switch(e){case"aac":case"mp3":case"vorbis":return"mp4a";case"opus":return"Opus";case"flac":return"fLaC";case"ulaw":return"ulaw";case"alaw":return"alaw";case"pcm-u8":return"raw ";case"pcm-s8":return"sowt"}if(t)switch(e){case"pcm-s16":return"sowt";case"pcm-s16be":return"twos";case"pcm-s24":case"pcm-s24be":return"in24";case"pcm-s32":case"pcm-s32be":return"in32";case"pcm-f32":case"pcm-f32be":return"fl32";case"pcm-f64":case"pcm-f64be":return"fl64"}else switch(e){case"pcm-s16":case"pcm-s16be":case"pcm-s24":case"pcm-s24be":case"pcm-s32":case"pcm-s32be":return"ipcm";case"pcm-f32":case"pcm-f32be":case"pcm-f64":case"pcm-f64be":return"fpcm"}},gn=(e,t)=>{switch(e){case"aac":case"mp3":case"vorbis":return Ds;case"opus":return Fs;case"flac":return Ms}if(t)switch(e){case"pcm-s24":case"pcm-s24be":case"pcm-s32":case"pcm-s32be":case"pcm-f32":case"pcm-f32be":case"pcm-f64":case"pcm-f64be":return Bs}else switch(e){case"pcm-s16":case"pcm-s16be":case"pcm-s24":case"pcm-s24be":case"pcm-s32":case"pcm-s32be":case"pcm-f32":case"pcm-f32be":case"pcm-f64":case"pcm-f64be":return Rs}return null},kn={webvtt:"wvtt"},bn={webvtt:e=>ns("vttC",[...g.encode(e.info.config.description)])},wn=e=>{n(3===e.length);let t=0;for(let r=0;r<3;r++)t<<=5,t+=e.charCodeAt(r)-96;return t};
|
|
71
224
|
/*!
|
|
72
225
|
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
73
226
|
*
|
|
@@ -75,47 +228,47 @@ class ve{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperV
|
|
|
75
228
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
76
229
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
77
230
|
*/
|
|
78
|
-
class
|
|
231
|
+
class Tn{constructor(){this.ensureMonotonicity=!1,this.trackedWrites=null,this.trackedStart=-1,this.trackedEnd=-1}start(){}maybeTrackWrites(e){if(!this.trackedWrites)return;let t=this.getPos();if(t<this.trackedStart){if(t+e.byteLength<=this.trackedStart)return;e=e.subarray(this.trackedStart-t),t=0}const r=t+e.byteLength-this.trackedStart;let a=this.trackedWrites.byteLength;for(;a<r;)a*=2;if(a!==this.trackedWrites.byteLength){const e=new Uint8Array(a);e.set(this.trackedWrites,0),this.trackedWrites=e}this.trackedWrites.set(e,t-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,t+e.byteLength)}startTrackingWrites(){this.trackedWrites=new Uint8Array(1024),this.trackedStart=this.getPos(),this.trackedEnd=this.trackedStart}stopTrackingWrites(){if(!this.trackedWrites)throw new Error("Internal error: Can't get tracked writes since nothing was tracked.");const e={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,e}}const yn=65536,Sn=2**32;class Cn extends Tn{constructor(e){if(super(),this.pos=0,this.maxPos=0,this.target=e,this.supportsResize="resize"in new ArrayBuffer(0),this.supportsResize)try{this.buffer=new ArrayBuffer(yn,{maxByteLength:Sn})}catch{this.buffer=new ArrayBuffer(yn),this.supportsResize=!1}else this.buffer=new ArrayBuffer(yn);this.bytes=new Uint8Array(this.buffer)}ensureSize(e){let t=this.buffer.byteLength;for(;t<e;)t*=2;if(t!==this.buffer.byteLength){if(t>Sn)throw new Error("ArrayBuffer exceeded maximum size of 4294967296 bytes. Please consider using another target.");if(this.supportsResize)this.buffer.resize(t);else{const e=new ArrayBuffer(t),r=new Uint8Array(e);r.set(this.bytes,0),this.buffer=e,this.bytes=r}}}write(e){this.maybeTrackWrites(e),this.ensureSize(this.pos+e.byteLength),this.bytes.set(e,this.pos),this.target.onwrite?.(this.pos,this.pos+e.byteLength),this.pos+=e.byteLength,this.maxPos=Math.max(this.maxPos,this.pos)}seek(e){this.pos=e}getPos(){return this.pos}async flush(){}async finalize(){this.ensureSize(this.pos),this.target.buffer=this.buffer.slice(0,Math.max(this.maxPos,this.pos))}async close(){}getSlice(e,t){return this.bytes.slice(e,t)}}
|
|
79
232
|
/*!
|
|
80
233
|
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
81
234
|
*
|
|
82
235
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
83
236
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
84
237
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
85
|
-
*/class
|
|
238
|
+
*/class vn{constructor(){this._output=null,this.onwrite=null}}class Pn extends vn{constructor(){super(...arguments),this.buffer=null}_createWriter(){return new Cn(this)}}
|
|
86
239
|
/*!
|
|
87
240
|
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
88
241
|
*
|
|
89
242
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
90
243
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
91
244
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
92
|
-
*/const ni=1e3,ci=e=>{const t={},i=e.track;return void 0!==i.metadata.name&&(t.name=i.metadata.name),t},di=(e,t,i=!0)=>{const r=e*t;return i?Math.round(r):r};class ui extends ${constructor(e,t){super(e),this.auxTarget=new oi,this.auxWriter=this.auxTarget._createWriter(),this.auxBoxWriter=new ve(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=w(),this.creationTime=Math.floor(Date.now()/1e3)+2082844800,this.finalizedChunks=[],this.nextFragmentNumber=1,this.maxWrittenTimestamp=-1/0,this.format=t,this.writer=e._writer,this.boxWriter=new ve(this.writer),this.isQuickTime=t instanceof wi;const i=this.writer instanceof ai&&"in-memory";this.fastStart=t._options.fastStart??i,this.isFragmented="fragmented"===this.fastStart,("in-memory"===this.fastStart||this.isFragmented)&&(this.writer.ensureMonotonicity=!0),this.minimumFragmentDuration=t._options.minimumFragmentDuration??1}async start(){const e=await this.mutex.acquire(),t=this.output._tracks.some(e=>"video"===e.type&&"avc"===e.source._codec);if(this.format._options.onFtyp&&this.writer.startTrackingWrites(),this.boxWriter.writeBox((i={isQuickTime:this.isQuickTime,holdsAvc:t,fragmented:this.isFragmented}).isQuickTime?ze("ftyp",[We("qt "),xe(512),We("qt ")]):i.fragmented?ze("ftyp",[We("iso5"),xe(512),We("iso5"),We("iso6"),We("mp41")]):ze("ftyp",[We("isom"),xe(512),We("isom"),i.holdsAvc?We("avc1"):[],We("mp41")])),this.format._options.onFtyp){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onFtyp(e,t)}var i;if(this.ftypSize=this.writer.getPos(),"in-memory"===this.fastStart);else if("reserve"===this.fastStart){for(const e of this.output._tracks)if(void 0===e.metadata.maximumPacketCount)throw new Error("All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.")}else this.isFragmented||(this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=je(!0),this.boxWriter.writeBox(this.mdat));await this.writer.flush(),e()}allTracksAreKnown(){for(const e of this.output._tracks)if(!e.source._closed&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;const e=this.trackDatas.map(e=>{if("video"===e.type)return e.info.decoderConfig.codec;if("audio"===e.type)return e.info.decoderConfig.codec;return{webvtt:"wvtt"}[e.track.source._codec]});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.trackDatas.some(e=>"video"===e.type),hasAudio:this.trackDatas.some(e=>"audio"===e.type),codecStrings:e})}getVideoTrackData(e,t,i){const a=this.trackDatas.find(t=>t.track===e);if(a)return a;R(i),r(i),r(i.decoderConfig);const s={...i.decoderConfig};r(void 0!==s.codedWidth),r(void 0!==s.codedHeight);let d=!1;if("avc"!==e.source._codec||s.description){if("hevc"===e.source._codec&&!s.description){const e=(e=>{try{const t=K(e),i=t.filter(e=>J(e)===q.VPS_NUT),r=t.filter(e=>J(e)===q.SPS_NUT),a=t.filter(e=>J(e)===q.PPS_NUT),s=t.filter(e=>J(e)===q.PREFIX_SEI_NUT||J(e)===q.SUFFIX_SEI_NUT);if(0===r.length||0===a.length)return null;const d=r[0],u=new o(G(d));u.skipBits(16),u.readBits(4);const l=u.readBits(3),h=u.readBits(1),{general_profile_space:m,general_tier_flag:p,general_profile_idc:f,general_profile_compatibility_flags:g,general_constraint_indicator_flags:w,general_level_idc:k}=Z(u,l);n(u);const y=n(u);3===y&&u.skipBits(1),n(u),n(u),u.readBits(1)&&(n(u),n(u),n(u),n(u));const b=n(u),T=n(u);n(u);for(let e=u.readBits(1)?0:l;e<=l;e++)n(u),n(u),n(u);n(u),n(u),n(u),n(u),n(u),n(u),u.readBits(1)&&u.readBits(1)&&ee(u),u.skipBits(1),u.skipBits(1),u.readBits(1)&&(u.skipBits(4),u.skipBits(4),n(u),n(u),u.skipBits(1));const C=n(u);if(te(u,C),u.readBits(1)){const e=n(u);for(let t=0;t<e;t++)n(u),u.skipBits(1)}u.skipBits(1),u.skipBits(1);let v=0;u.readBits(1)&&(v=re(u,l));let S=0;if(a.length>0){const e=a[0],t=new o(G(e));t.skipBits(16),n(t),n(t),t.skipBits(1),t.skipBits(1),t.skipBits(3),t.skipBits(1),t.skipBits(1),n(t),n(t),c(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&n(t),c(t),c(t),t.skipBits(1),t.skipBits(1),t.skipBits(1),t.skipBits(1);const i=t.readBits(1),r=t.readBits(1);S=i||r?i&&!r?2:!i&&r?3:0:0}return{configurationVersion:1,generalProfileSpace:m,generalTierFlag:p,generalProfileIdc:f,generalProfileCompatibilityFlags:g,generalConstraintIndicatorFlags:w,generalLevelIdc:k,minSpatialSegmentationIdc:v,parallelismType:S,chromaFormatIdc:y,bitDepthLumaMinus8:b,bitDepthChromaMinus8:T,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:l+1,temporalIdNested:h,lengthSizeMinusOne:3,arrays:[...i.length?[{arrayCompleteness:1,nalUnitType:q.VPS_NUT,nalUnits:i}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:q.SPS_NUT,nalUnits:r}]:[],...a.length?[{arrayCompleteness:1,nalUnitType:q.PPS_NUT,nalUnits:a}]:[],...s.length?[{arrayCompleteness:1,nalUnitType:J(s[0]),nalUnits:s}]:[]]}}catch(e){return console.error("Error building HEVC Decoder Configuration Record:",e),null}})(t.data);if(!e)throw new Error("Couldn't extract an HEVCDecoderConfigurationRecord from the HEVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.265) when not providing a description, or provide a description (must be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in HEVC format.");s.description=(e=>{const t=[];t.push(e.configurationVersion),t.push((3&e.generalProfileSpace)<<6|(1&e.generalTierFlag)<<5|31&e.generalProfileIdc),t.push(e.generalProfileCompatibilityFlags>>>24&255),t.push(e.generalProfileCompatibilityFlags>>>16&255),t.push(e.generalProfileCompatibilityFlags>>>8&255),t.push(255&e.generalProfileCompatibilityFlags),t.push(...e.generalConstraintIndicatorFlags),t.push(255&e.generalLevelIdc),t.push(240|e.minSpatialSegmentationIdc>>8&15),t.push(255&e.minSpatialSegmentationIdc),t.push(252|3&e.parallelismType),t.push(252|3&e.chromaFormatIdc),t.push(248|7&e.bitDepthLumaMinus8),t.push(248|7&e.bitDepthChromaMinus8),t.push(e.avgFrameRate>>8&255),t.push(255&e.avgFrameRate),t.push((3&e.constantFrameRate)<<6|(7&e.numTemporalLayers)<<3|(1&e.temporalIdNested)<<2|3&e.lengthSizeMinusOne),t.push(255&e.arrays.length);for(const i of e.arrays){t.push((1&i.arrayCompleteness)<<7|63&i.nalUnitType),t.push(i.nalUnits.length>>8&255),t.push(255&i.nalUnits.length);for(const e of i.nalUnits){t.push(e.length>>8&255),t.push(255&e.length);for(let i=0;i<e.length;i++)t.push(e[i])}}return new Uint8Array(t)})(e),d=!0}}else{const e=(e=>{try{const t=K(e),i=t.filter(e=>X(e)===Q.SPS),a=t.filter(e=>X(e)===Q.PPS),s=t.filter(e=>X(e)===Q.SPS_EXT);if(0===i.length)return null;if(0===a.length)return null;const o=i[0],n=Y(o);r(null!==n);const c=100===n.profileIdc||110===n.profileIdc||122===n.profileIdc||144===n.profileIdc;return{configurationVersion:1,avcProfileIndication:n.profileIdc,profileCompatibility:n.constraintFlags,avcLevelIndication:n.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:i,pictureParameterSets:a,chromaFormat:c?n.chromaFormatIdc:null,bitDepthLumaMinus8:c?n.bitDepthLumaMinus8:null,bitDepthChromaMinus8:c?n.bitDepthChromaMinus8:null,sequenceParameterSetExt:c?s:null}}catch(e){return console.error("Error building AVC Decoder Configuration Record:",e),null}})(t.data);if(!e)throw new Error("Couldn't extract an AVCDecoderConfigurationRecord from the AVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.264) when not providing a description, or provide a description (must be an AVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in AVCC format.");s.description=(e=>{const t=[];t.push(e.configurationVersion),t.push(e.avcProfileIndication),t.push(e.profileCompatibility),t.push(e.avcLevelIndication),t.push(252|3&e.lengthSizeMinusOne),t.push(224|31&e.sequenceParameterSets.length);for(const i of e.sequenceParameterSets){const e=i.byteLength;t.push(e>>8),t.push(255&e);for(let r=0;r<e;r++)t.push(i[r])}t.push(e.pictureParameterSets.length);for(const i of e.pictureParameterSets){const e=i.byteLength;t.push(e>>8),t.push(255&e);for(let r=0;r<e;r++)t.push(i[r])}if(100===e.avcProfileIndication||110===e.avcProfileIndication||122===e.avcProfileIndication||144===e.avcProfileIndication){r(null!==e.chromaFormat),r(null!==e.bitDepthLumaMinus8),r(null!==e.bitDepthChromaMinus8),r(null!==e.sequenceParameterSetExt),t.push(252|3&e.chromaFormat),t.push(248|7&e.bitDepthLumaMinus8),t.push(248|7&e.bitDepthChromaMinus8),t.push(e.sequenceParameterSetExt.length);for(const i of e.sequenceParameterSetExt){const e=i.byteLength;t.push(e>>8),t.push(255&e);for(let r=0;r<e;r++)t.push(i[r])}}return new Uint8Array(t)})(e),d=!0}const u=((e,t)=>{const i=e<0?-1:1;let r=0,a=1,s=1,o=0,n=e=Math.abs(e);for(;;){const e=Math.floor(n),c=e*s+r,d=e*o+a;if(d>t)return{numerator:i*s,denominator:o};if(r=s,a=o,s=c,o=d,n=1/(n-e),!isFinite(n))break}return{numerator:i*s,denominator:o}})(1/(e.metadata.frameRate??57600),1e6).denominator,l={muxer:this,track:e,type:"video",info:{width:s.codedWidth,height:s.codedHeight,decoderConfig:s,requiresAnnexBTransformation:d},timescale:u,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};return this.trackDatas.push(l),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),l}getAudioTrackData(e,t){const i=this.trackDatas.find(t=>t.track===e);if(i)return i;H(t),r(t),r(t.decoderConfig);const a={muxer:this,track:e,type:"audio",info:{numberOfChannels:t.decoderConfig.numberOfChannels,sampleRate:t.decoderConfig.sampleRate,decoderConfig:t.decoderConfig,requiresPcmTransformation:!this.isFragmented&&A.includes(e.source._codec)},timescale:t.decoderConfig.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};return this.trackDatas.push(a),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),a}getSubtitleTrackData(e,t){const i=this.trackDatas.find(t=>t.track===e);if(i)return i;j(t),r(t),r(t.config);const a={muxer:this,track:e,type:"subtitle",info:{config:t.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],lastCueEndTimestamp:0,cueQueue:[],nextSourceId:0,cueToSourceId:new WeakMap};return this.trackDatas.push(a),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),a}async addEncodedVideoPacket(e,t,i){const r=await this.mutex.acquire();try{const r=this.getVideoTrackData(e,t,i);let a=t.data;if(r.info.requiresAnnexBTransformation){const e=(e=>{const t=K(e);if(0===t.length)return null;let i=0;for(const e of t)i+=4+e.byteLength;const r=new Uint8Array(i),a=new DataView(r.buffer);let s=0;for(const e of t){const t=e.byteLength;a.setUint32(s,t,!1),s+=4,r.set(e,s),s+=e.byteLength}return r})(a);if(!e)throw new Error("Failed to transform packet data. Make sure all packets are provided in Annex B format, as specified in ITU-T-REC-H.264 and ITU-T-REC-H.265.");a=e}const s=this.validateAndNormalizeTimestamp(r.track,t.timestamp,"key"===t.type),o=this.createSampleForTrack(r,a,s,t.duration,t.type);await this.registerSample(r,o)}finally{r()}}async addEncodedAudioPacket(e,t,i){const r=await this.mutex.acquire();try{const r=this.getAudioTrackData(e,i),a=this.validateAndNormalizeTimestamp(r.track,t.timestamp,"key"===t.type),s=this.createSampleForTrack(r,t.data,a,t.duration,t.type);r.info.requiresPcmTransformation&&await this.maybePadWithSilence(r,a),await this.registerSample(r,s)}finally{r()}}async maybePadWithSilence(e,t){const i=a(e.samples),r=i?i.timestamp+i.duration:0,s=t-r,o=di(s,e.timescale);if(o>0){const{sampleSize:t,silentValue:i}=U(e.info.decoderConfig.codec),a=o*e.info.numberOfChannels,n=new Uint8Array(t*a).fill(i),c=this.createSampleForTrack(e,new Uint8Array(n.buffer),r,s,"key");await this.registerSample(e,c)}}async addSubtitleCue(e,t,i){const r=await this.mutex.acquire();try{const r=this.getSubtitleTrackData(e,i);this.validateAndNormalizeTimestamp(r.track,t.timestamp,!0),"webvtt"===e.source._codec&&(r.cueQueue.push(t),await this.processWebVTTCues(r,t.timestamp))}finally{r()}}async processWebVTTCues(e,t){for(;e.cueQueue.length>0;){const i=new Set([]);for(const a of e.cueQueue)r(a.timestamp<=t),r(e.lastCueEndTimestamp<=a.timestamp+a.duration),i.add(Math.max(a.timestamp,e.lastCueEndTimestamp)),i.add(a.timestamp+a.duration);const a=[...i].sort((e,t)=>e-t),s=a[0],o=a[1]??s;if(t<o)break;if(e.lastCueEndTimestamp<s){this.auxWriter.seek(0);const t=Wt();this.auxBoxWriter.writeBox(t);const i=this.auxWriter.getSlice(0,this.auxWriter.getPos()),r=this.createSampleForTrack(e,i,e.lastCueEndTimestamp,s-e.lastCueEndTimestamp,"key");await this.registerSample(e,r),e.lastCueEndTimestamp=s}this.auxWriter.seek(0);for(let t=0;t<e.cueQueue.length;t++){const i=e.cueQueue[t];if(i.timestamp>=o)break;be.lastIndex=0;const r=be.test(i.text),a=i.timestamp+i.duration;let n=e.cueToSourceId.get(i);if(void 0===n&&o<a&&(n=e.nextSourceId++,e.cueToSourceId.set(i,n)),i.notes){const e=Ot(i.notes);this.auxBoxWriter.writeBox(e)}const c=Nt(i.text,r?s:null,i.identifier??null,i.settings??null,n??null);this.auxBoxWriter.writeBox(c),a===o&&e.cueQueue.splice(t--,1)}const n=this.auxWriter.getSlice(0,this.auxWriter.getPos()),c=this.createSampleForTrack(e,n,s,o-s,"key");await this.registerSample(e,c),e.lastCueEndTimestamp=o}}createSampleForTrack(e,t,i,r,a){return{timestamp:i,decodeTimestamp:i,duration:r,data:t,size:t.byteLength,type:a,timescaleUnitsToNextSample:di(r,e.timescale)}}processTimestamps(e,t){if(0===e.timestampProcessingQueue.length)return;if("audio"===e.type&&e.info.requiresPcmTransformation){let t=0;for(let i=0;i<e.timestampProcessingQueue.length;i++){const r=e.timestampProcessingQueue[i];t+=di(r.duration,e.timescale)}if(0===e.timeToSampleTable.length)e.timeToSampleTable.push({sampleCount:t,sampleDelta:1});else{a(e.timeToSampleTable).sampleCount+=t}return void(e.timestampProcessingQueue.length=0)}const i=e.timestampProcessingQueue.map(e=>e.timestamp).sort((e,t)=>e-t);for(let t=0;t<e.timestampProcessingQueue.length;t++){const s=e.timestampProcessingQueue[t];s.decodeTimestamp=i[t],this.isFragmented||null!==e.lastTimescaleUnits||(s.decodeTimestamp=0);const o=di(s.timestamp-s.decodeTimestamp,e.timescale),n=di(s.duration,e.timescale);if(null!==e.lastTimescaleUnits){r(e.lastSample);const t=di(s.decodeTimestamp,e.timescale,!1),i=Math.round(t-e.lastTimescaleUnits);if(r(i>=0),e.lastTimescaleUnits+=i,e.lastSample.timescaleUnitsToNextSample=i,!this.isFragmented){let t=a(e.timeToSampleTable);if(r(t),1===t.sampleCount){t.sampleDelta=i;const r=e.timeToSampleTable[e.timeToSampleTable.length-2];r&&r.sampleDelta===i&&(r.sampleCount++,e.timeToSampleTable.pop(),t=r)}else t.sampleDelta!==i&&(t.sampleCount--,e.timeToSampleTable.push(t={sampleCount:1,sampleDelta:i}));t.sampleDelta===n?t.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:n});const s=a(e.compositionTimeOffsetTable);r(s),s.sampleCompositionTimeOffset===o?s.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:o})}}else e.lastTimescaleUnits=di(s.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:n}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:o}));e.lastSample=s}if(e.timestampProcessingQueue.length=0,r(e.lastSample),r(null!==e.lastTimescaleUnits),void 0!==t&&0===e.lastSample.timescaleUnitsToNextSample){r("key"===t.type);const i=di(t.timestamp,e.timescale,!1),a=Math.round(i-e.lastTimescaleUnits);e.lastSample.timescaleUnitsToNextSample=a}}async registerSample(e,t){"key"===t.type&&this.processTimestamps(e,t),e.timestampProcessingQueue.push(t),this.isFragmented?(e.sampleQueue.push(t),await this.interleaveSamples()):"reserve"===this.fastStart?await this.registerSampleFastStartReserve(e,t):await this.addSampleToTrack(e,t)}async addSampleToTrack(e,t){if(!this.isFragmented&&(e.samples.push(t),"reserve"===this.fastStart)){const t=e.track.metadata.maximumPacketCount;if(r(void 0!==t),e.samples.length>t)throw new Error(`Track #${e.track.id} has already reached the maximum packet count (${t}). Either add less packets or increase the maximum packet count.`)}let i=!1;if(e.currentChunk){e.currentChunk.startTimestamp=Math.min(e.currentChunk.startTimestamp,t.timestamp);const r=t.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){const a=this.trackDatas.every(i=>{if(e===i)return"key"===t.type;const r=i.sampleQueue[0];return r?"key"===r.type:i.track.source._closed});r>=this.minimumFragmentDuration&&a&&t.timestamp>this.maxWrittenTimestamp&&(i=!0,await this.finalizeFragment())}else i=r>=.5}else i=!0;i&&(e.currentChunk&&await this.finalizeCurrentChunk(e),e.currentChunk={startTimestamp:t.timestamp,samples:[],offset:null,moofOffset:null}),r(e.currentChunk),e.currentChunk.samples.push(t),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,t.timestamp))}async finalizeCurrentChunk(e){if(r(!this.isFragmented),!e.currentChunk)return;e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk);let t=e.currentChunk.samples.length;if("audio"===e.type&&e.info.requiresPcmTransformation&&(t=e.currentChunk.samples.reduce((t,i)=>t+di(i.duration,e.timescale),0)),0!==e.compactlyCodedChunkTable.length&&a(e.compactlyCodedChunkTable).samplesPerChunk===t||e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:t}),"in-memory"!==this.fastStart){e.currentChunk.offset=this.writer.getPos();for(const t of e.currentChunk.samples)r(t.data),this.writer.write(t.data),t.data=null;await this.writer.flush()}else e.currentChunk.offset=0}async interleaveSamples(e=!1){if(r(this.isFragmented),e||this.allTracksAreKnown())e:for(;;){let t=null,i=1/0;for(const r of this.trackDatas){if(!e&&0===r.sampleQueue.length&&!r.track.source._closed)break e;r.sampleQueue.length>0&&r.sampleQueue[0].timestamp<i&&(t=r,i=r.sampleQueue[0].timestamp)}if(!t)break;const r=t.sampleQueue.shift();await this.addSampleToTrack(t,r)}}async finalizeFragment(e=!0){r(this.isFragmented);const t=this.nextFragmentNumber++;if(1===t){this.format._options.onMoov&&this.writer.startTrackingWrites();const e=$e(this);if(this.boxWriter.writeBox(e),this.format._options.onMoov){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMoov(e,t)}}const i=this.trackDatas.filter(e=>e.currentChunk),a=At(t,i),s=this.writer.getPos(),o=s+this.boxWriter.measureBox(a);let n=o+8,c=1/0;for(const e of i){e.currentChunk.offset=n,e.currentChunk.moofOffset=s;for(const t of e.currentChunk.samples)n+=t.size;c=Math.min(c,e.currentChunk.startTimestamp)}const d=n-o,u=d>=2**32;if(u)for(const e of i)e.currentChunk.offset+=8;this.format._options.onMoof&&this.writer.startTrackingWrites();const l=At(t,i);if(this.boxWriter.writeBox(l),this.format._options.onMoof){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMoof(e,t,c)}r(this.writer.getPos()===o),this.format._options.onMdat&&this.writer.startTrackingWrites();const h=je(u);h.size=d,this.boxWriter.writeBox(h),this.writer.seek(o+(u?16:8));for(const e of i)for(const t of e.currentChunk.samples)this.writer.write(t.data),t.data=null;if(this.format._options.onMdat){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMdat(e,t)}for(const e of i)e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk),e.currentChunk=null;e&&await this.writer.flush()}async registerSampleFastStartReserve(e,t){if(this.allTracksAreKnown()){if(!this.mdat){const e=$e(this),t=this.boxWriter.measureBox(e)+this.computeSampleTableSizeUpperBound()+4096;r(null!==this.ftypSize),this.writer.seek(this.ftypSize+t),this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=je(!0),this.boxWriter.writeBox(this.mdat);for(const e of this.trackDatas){for(const t of e.sampleQueue)await this.addSampleToTrack(e,t);e.sampleQueue.length=0}}await this.addSampleToTrack(e,t)}else e.sampleQueue.push(t)}computeSampleTableSizeUpperBound(){r("reserve"===this.fastStart);let e=0;for(const t of this.trackDatas){const i=t.track.metadata.maximumPacketCount;r(void 0!==i),e+=8*Math.ceil(2/3*i),e+=4*i,e+=8*Math.ceil(2/3*i),e+=12*Math.ceil(2/3*i),e+=4*i,e+=8*i}return e}async onTrackClose(e){const t=await this.mutex.acquire();if("subtitle"===e.type&&"webvtt"===e.source._codec){const t=this.trackDatas.find(t=>t.track===e);t&&await this.processWebVTTCues(t,1/0)}this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),t()}async finalize(){const e=await this.mutex.acquire();this.allTracksKnown.resolve();for(const e of this.trackDatas)"subtitle"===e.type&&"webvtt"===e.track.source._codec&&await this.processWebVTTCues(e,1/0);if(this.isFragmented){await this.interleaveSamples(!0);for(const e of this.trackDatas)this.processTimestamps(e);await this.finalizeFragment(!1)}else for(const e of this.trackDatas)this.processTimestamps(e),await this.finalizeCurrentChunk(e);if("in-memory"===this.fastStart){let e;this.mdat=je(!1);for(let t=0;t<2;t++){const t=$e(this),i=this.boxWriter.measureBox(t);e=this.boxWriter.measureBox(this.mdat);let a=this.writer.getPos()+i+e;for(const t of this.finalizedChunks){t.offset=a;for(const{data:i}of t.samples)r(i),a+=i.byteLength,e+=i.byteLength}if(a<2**32)break;e>=2**32&&(this.mdat.largeSize=!0)}this.format._options.onMoov&&this.writer.startTrackingWrites();const t=$e(this);if(this.boxWriter.writeBox(t),this.format._options.onMoov){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMoov(e,t)}this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=e,this.boxWriter.writeBox(this.mdat);for(const e of this.finalizedChunks)for(const t of e.samples)r(t.data),this.writer.write(t.data),t.data=null;if(this.format._options.onMdat){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMdat(e,t)}}else if(this.isFragmented){const e=this.writer.getPos(),i=(t=this.trackDatas,ze("mfra",void 0,[...t.map(Ut),Ft()]));this.boxWriter.writeBox(i);const r=this.writer.getPos()-e;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(r)}else{r(this.mdat);const e=this.boxWriter.offsets.get(this.mdat);r(void 0!==e);const t=this.writer.getPos()-e;if(this.mdat.size=t,this.mdat.largeSize=t>=2**32,this.boxWriter.patchBox(this.mdat),this.format._options.onMdat){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMdat(e,t)}const i=$e(this);if("reserve"===this.fastStart){r(null!==this.ftypSize),this.writer.seek(this.ftypSize),this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(i);const e=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox({type:"free",size:e})}else this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(i);if(this.format._options.onMoov){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMoov(e,t)}}var t;e()}}
|
|
245
|
+
*/const In=1e3,xn=e=>{const t={},r=e.track;return void 0!==r.metadata.name&&(t.name=r.metadata.name),t},En=(e,t,r=!0)=>{const a=e*t;return r?Math.round(a):a};class Dn extends Le{constructor(e,t){super(e),this.auxTarget=new Pn,this.auxWriter=this.auxTarget._createWriter(),this.auxBoxWriter=new Vi(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=_(),this.creationTime=Math.floor(Date.now()/1e3)+2082844800,this.finalizedChunks=[],this.nextFragmentNumber=1,this.maxWrittenTimestamp=-1/0,this.format=t,this.writer=e._writer,this.boxWriter=new Vi(this.writer),this.isQuickTime=t instanceof zn;const r=this.writer instanceof Cn&&"in-memory";this.fastStart=t._options.fastStart??r,this.isFragmented="fragmented"===this.fastStart,("in-memory"===this.fastStart||this.isFragmented)&&(this.writer.ensureMonotonicity=!0),this.minimumFragmentDuration=t._options.minimumFragmentDuration??1}async start(){const e=await this.mutex.acquire(),t=this.output._tracks.some(e=>"video"===e.type&&"avc"===e.source._codec);if(this.format._options.onFtyp&&this.writer.startTrackingWrites(),this.boxWriter.writeBox((r={isQuickTime:this.isQuickTime,holdsAvc:t,fragmented:this.isFragmented}).isQuickTime?ns("ftyp",[ts("qt "),Ki(512),ts("qt ")]):r.fragmented?ns("ftyp",[ts("iso5"),Ki(512),ts("iso5"),ts("iso6"),ts("mp41")]):ns("ftyp",[ts("isom"),Ki(512),ts("isom"),r.holdsAvc?ts("avc1"):[],ts("mp41")])),this.format._options.onFtyp){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onFtyp(e,t)}var r;if(this.ftypSize=this.writer.getPos(),"in-memory"===this.fastStart);else if("reserve"===this.fastStart){for(const e of this.output._tracks)if(void 0===e.metadata.maximumPacketCount)throw new Error("All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.")}else this.isFragmented||(this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=cs(!0),this.boxWriter.writeBox(this.mdat));await this.writer.flush(),e()}allTracksAreKnown(){for(const e of this.output._tracks)if(!e.source._closed&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;const e=this.trackDatas.map(e=>{if("video"===e.type)return e.info.decoderConfig.codec;if("audio"===e.type)return e.info.decoderConfig.codec;return{webvtt:"wvtt"}[e.track.source._codec]});return sr({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(e=>"video"===e.type),hasAudio:this.trackDatas.some(e=>"audio"===e.type),codecStrings:e})}getVideoTrackData(e,t,r){const a=this.trackDatas.find(t=>t.track===e);if(a)return a;Re(r),n(r),n(r.decoderConfig);const i={...r.decoderConfig};n(void 0!==i.codedWidth),n(void 0!==i.codedHeight);let s=!1;if("avc"!==e.source._codec||i.description){if("hevc"===e.source._codec&&!i.description){const e=et(t.data);if(!e)throw new Error("Couldn't extract an HEVCDecoderConfigurationRecord from the HEVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.265) when not providing a description, or provide a description (must be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in HEVC format.");i.description=(e=>{const t=[];t.push(e.configurationVersion),t.push((3&e.generalProfileSpace)<<6|(1&e.generalTierFlag)<<5|31&e.generalProfileIdc),t.push(e.generalProfileCompatibilityFlags>>>24&255),t.push(e.generalProfileCompatibilityFlags>>>16&255),t.push(e.generalProfileCompatibilityFlags>>>8&255),t.push(255&e.generalProfileCompatibilityFlags),t.push(...e.generalConstraintIndicatorFlags),t.push(255&e.generalLevelIdc),t.push(240|e.minSpatialSegmentationIdc>>8&15),t.push(255&e.minSpatialSegmentationIdc),t.push(252|3&e.parallelismType),t.push(252|3&e.chromaFormatIdc),t.push(248|7&e.bitDepthLumaMinus8),t.push(248|7&e.bitDepthChromaMinus8),t.push(e.avgFrameRate>>8&255),t.push(255&e.avgFrameRate),t.push((3&e.constantFrameRate)<<6|(7&e.numTemporalLayers)<<3|(1&e.temporalIdNested)<<2|3&e.lengthSizeMinusOne),t.push(255&e.arrays.length);for(const r of e.arrays){t.push((1&r.arrayCompleteness)<<7|63&r.nalUnitType),t.push(r.nalUnits.length>>8&255),t.push(255&r.nalUnits.length);for(const e of r.nalUnits){t.push(e.length>>8&255),t.push(255&e.length);for(let r=0;r<e.length;r++)t.push(e[r])}}return new Uint8Array(t)})(e),s=!0}}else{const e=Xe(t.data);if(!e)throw new Error("Couldn't extract an AVCDecoderConfigurationRecord from the AVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.264) when not providing a description, or provide a description (must be an AVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in AVCC format.");i.description=(e=>{const t=[];t.push(e.configurationVersion),t.push(e.avcProfileIndication),t.push(e.profileCompatibility),t.push(e.avcLevelIndication),t.push(252|3&e.lengthSizeMinusOne),t.push(224|31&e.sequenceParameterSets.length);for(const r of e.sequenceParameterSets){const e=r.byteLength;t.push(e>>8),t.push(255&e);for(let a=0;a<e;a++)t.push(r[a])}t.push(e.pictureParameterSets.length);for(const r of e.pictureParameterSets){const e=r.byteLength;t.push(e>>8),t.push(255&e);for(let a=0;a<e;a++)t.push(r[a])}if(100===e.avcProfileIndication||110===e.avcProfileIndication||122===e.avcProfileIndication||144===e.avcProfileIndication){n(null!==e.chromaFormat),n(null!==e.bitDepthLumaMinus8),n(null!==e.bitDepthChromaMinus8),n(null!==e.sequenceParameterSetExt),t.push(252|3&e.chromaFormat),t.push(248|7&e.bitDepthLumaMinus8),t.push(248|7&e.bitDepthChromaMinus8),t.push(e.sequenceParameterSetExt.length);for(const r of e.sequenceParameterSetExt){const e=r.byteLength;t.push(e>>8),t.push(255&e);for(let a=0;a<e;a++)t.push(r[a])}}return new Uint8Array(t)})(e),s=!0}const o=((e,t)=>{const r=e<0?-1:1;let a=0,i=1,s=1,n=0,o=e=Math.abs(e);for(;;){const e=Math.floor(o),c=e*s+a,d=e*n+i;if(d>t)return{numerator:r*s,denominator:n};if(a=s,i=n,s=c,n=d,o=1/(o-e),!isFinite(o))break}return{numerator:r*s,denominator:n}})(1/(e.metadata.frameRate??57600),1e6).denominator,c={muxer:this,track:e,type:"video",info:{width:i.codedWidth,height:i.codedHeight,decoderConfig:i,requiresAnnexBTransformation:s},timescale:o,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};return this.trackDatas.push(c),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),c}getAudioTrackData(e,t){const r=this.trackDatas.find(t=>t.track===e);if(r)return r;Oe(t),n(t),n(t.decoderConfig);const a={muxer:this,track:e,type:"audio",info:{numberOfChannels:t.decoderConfig.numberOfChannels,sampleRate:t.decoderConfig.sampleRate,decoderConfig:t.decoderConfig,requiresPcmTransformation:!this.isFragmented&&me.includes(e.source._codec)},timescale:t.decoderConfig.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};return this.trackDatas.push(a),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),a}getSubtitleTrackData(e,t){const r=this.trackDatas.find(t=>t.track===e);if(r)return r;Ne(t),n(t),n(t.config);const a={muxer:this,track:e,type:"subtitle",info:{config:t.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],lastCueEndTimestamp:0,cueQueue:[],nextSourceId:0,cueToSourceId:new WeakMap};return this.trackDatas.push(a),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),a}async addEncodedVideoPacket(e,t,r){const a=await this.mutex.acquire();try{const a=this.getVideoTrackData(e,t,r);let i=t.data;if(a.info.requiresAnnexBTransformation){const e=We(i);if(0===e.length)throw new Error("Failed to transform packet data. Make sure all packets are provided in Annex B format, as specified in ITU-T-REC-H.264 and ITU-T-REC-H.265.");i=$e(e,4)}const s=this.validateAndNormalizeTimestamp(a.track,t.timestamp,"key"===t.type),n=this.createSampleForTrack(a,i,s,t.duration,t.type);await this.registerSample(a,n)}finally{a()}}async addEncodedAudioPacket(e,t,r){const a=await this.mutex.acquire();try{const a=this.getAudioTrackData(e,r),i=this.validateAndNormalizeTimestamp(a.track,t.timestamp,"key"===t.type),s=this.createSampleForTrack(a,t.data,i,t.duration,t.type);a.info.requiresPcmTransformation&&await this.maybePadWithSilence(a,i),await this.registerSample(a,s)}finally{a()}}async maybePadWithSilence(e,t){const r=c(e.samples),a=r?r.timestamp+r.duration:0,i=t-a,s=En(i,e.timescale);if(s>0){const{sampleSize:t,silentValue:r}=De(e.info.decoderConfig.codec),n=s*e.info.numberOfChannels,o=new Uint8Array(t*n).fill(r),c=this.createSampleForTrack(e,new Uint8Array(o.buffer),a,i,"key");await this.registerSample(e,c)}}async addSubtitleCue(e,t,r){const a=await this.mutex.acquire();try{const a=this.getSubtitleTrackData(e,r);this.validateAndNormalizeTimestamp(a.track,t.timestamp,!0),"webvtt"===e.source._codec&&(a.cueQueue.push(t),await this.processWebVTTCues(a,t.timestamp))}finally{a()}}async processWebVTTCues(e,t){for(;e.cueQueue.length>0;){const r=new Set([]);for(const a of e.cueQueue)n(a.timestamp<=t),n(e.lastCueEndTimestamp<=a.timestamp+a.duration),r.add(Math.max(a.timestamp,e.lastCueEndTimestamp)),r.add(a.timestamp+a.duration);const a=[...r].sort((e,t)=>e-t),i=a[0],s=a[1]??i;if(t<s)break;if(e.lastCueEndTimestamp<i){this.auxWriter.seek(0);const t=tn();this.auxBoxWriter.writeBox(t);const r=this.auxWriter.getSlice(0,this.auxWriter.getPos()),a=this.createSampleForTrack(e,r,e.lastCueEndTimestamp,i-e.lastCueEndTimestamp,"key");await this.registerSample(e,a),e.lastCueEndTimestamp=i}this.auxWriter.seek(0);for(let t=0;t<e.cueQueue.length;t++){const r=e.cueQueue[t];if(r.timestamp>=s)break;Ni.lastIndex=0;const a=Ni.test(r.text),n=r.timestamp+r.duration;let o=e.cueToSourceId.get(r);if(void 0===o&&s<n&&(o=e.nextSourceId++,e.cueToSourceId.set(r,o)),r.notes){const e=an(r.notes);this.auxBoxWriter.writeBox(e)}const c=rn(r.text,a?i:null,r.identifier??null,r.settings??null,o??null);this.auxBoxWriter.writeBox(c),n===s&&e.cueQueue.splice(t--,1)}const o=this.auxWriter.getSlice(0,this.auxWriter.getPos()),c=this.createSampleForTrack(e,o,i,s-i,"key");await this.registerSample(e,c),e.lastCueEndTimestamp=s}}createSampleForTrack(e,t,r,a,i){return{timestamp:r,decodeTimestamp:r,duration:a,data:t,size:t.byteLength,type:i,timescaleUnitsToNextSample:En(a,e.timescale)}}processTimestamps(e,t){if(0===e.timestampProcessingQueue.length)return;if("audio"===e.type&&e.info.requiresPcmTransformation){let t=0;for(let r=0;r<e.timestampProcessingQueue.length;r++){const a=e.timestampProcessingQueue[r];t+=En(a.duration,e.timescale)}if(0===e.timeToSampleTable.length)e.timeToSampleTable.push({sampleCount:t,sampleDelta:1});else{c(e.timeToSampleTable).sampleCount+=t}return void(e.timestampProcessingQueue.length=0)}const r=e.timestampProcessingQueue.map(e=>e.timestamp).sort((e,t)=>e-t);for(let t=0;t<e.timestampProcessingQueue.length;t++){const a=e.timestampProcessingQueue[t];a.decodeTimestamp=r[t],this.isFragmented||null!==e.lastTimescaleUnits||(a.decodeTimestamp=0);const i=En(a.timestamp-a.decodeTimestamp,e.timescale),s=En(a.duration,e.timescale);if(null!==e.lastTimescaleUnits){n(e.lastSample);const t=En(a.decodeTimestamp,e.timescale,!1),r=Math.round(t-e.lastTimescaleUnits);if(n(r>=0),e.lastTimescaleUnits+=r,e.lastSample.timescaleUnitsToNextSample=r,!this.isFragmented){let t=c(e.timeToSampleTable);if(n(t),1===t.sampleCount){t.sampleDelta=r;const a=e.timeToSampleTable[e.timeToSampleTable.length-2];a&&a.sampleDelta===r&&(a.sampleCount++,e.timeToSampleTable.pop(),t=a)}else t.sampleDelta!==r&&(t.sampleCount--,e.timeToSampleTable.push(t={sampleCount:1,sampleDelta:r}));t.sampleDelta===s?t.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:s});const a=c(e.compositionTimeOffsetTable);n(a),a.sampleCompositionTimeOffset===i?a.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:i})}}else e.lastTimescaleUnits=En(a.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:s}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:i}));e.lastSample=a}if(e.timestampProcessingQueue.length=0,n(e.lastSample),n(null!==e.lastTimescaleUnits),void 0!==t&&0===e.lastSample.timescaleUnitsToNextSample){n("key"===t.type);const r=En(t.timestamp,e.timescale,!1),a=Math.round(r-e.lastTimescaleUnits);e.lastSample.timescaleUnitsToNextSample=a}}async registerSample(e,t){"key"===t.type&&this.processTimestamps(e,t),e.timestampProcessingQueue.push(t),this.isFragmented?(e.sampleQueue.push(t),await this.interleaveSamples()):"reserve"===this.fastStart?await this.registerSampleFastStartReserve(e,t):await this.addSampleToTrack(e,t)}async addSampleToTrack(e,t){if(!this.isFragmented&&(e.samples.push(t),"reserve"===this.fastStart)){const t=e.track.metadata.maximumPacketCount;if(n(void 0!==t),e.samples.length>t)throw new Error(`Track #${e.track.id} has already reached the maximum packet count (${t}). Either add less packets or increase the maximum packet count.`)}let r=!1;if(e.currentChunk){e.currentChunk.startTimestamp=Math.min(e.currentChunk.startTimestamp,t.timestamp);const a=t.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){const i=this.trackDatas.every(r=>{if(e===r)return"key"===t.type;const a=r.sampleQueue[0];return a?"key"===a.type:r.track.source._closed});a>=this.minimumFragmentDuration&&i&&t.timestamp>this.maxWrittenTimestamp&&(r=!0,await this.finalizeFragment())}else r=a>=.5}else r=!0;r&&(e.currentChunk&&await this.finalizeCurrentChunk(e),e.currentChunk={startTimestamp:t.timestamp,samples:[],offset:null,moofOffset:null}),n(e.currentChunk),e.currentChunk.samples.push(t),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,t.timestamp))}async finalizeCurrentChunk(e){if(n(!this.isFragmented),!e.currentChunk)return;e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk);let t=e.currentChunk.samples.length;if("audio"===e.type&&e.info.requiresPcmTransformation&&(t=e.currentChunk.samples.reduce((t,r)=>t+En(r.duration,e.timescale),0)),0!==e.compactlyCodedChunkTable.length&&c(e.compactlyCodedChunkTable).samplesPerChunk===t||e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:t}),"in-memory"!==this.fastStart){e.currentChunk.offset=this.writer.getPos();for(const t of e.currentChunk.samples)n(t.data),this.writer.write(t.data),t.data=null;await this.writer.flush()}else e.currentChunk.offset=0}async interleaveSamples(e=!1){if(n(this.isFragmented),e||this.allTracksAreKnown())e:for(;;){let t=null,r=1/0;for(const a of this.trackDatas){if(!e&&0===a.sampleQueue.length&&!a.track.source._closed)break e;a.sampleQueue.length>0&&a.sampleQueue[0].timestamp<r&&(t=a,r=a.sampleQueue[0].timestamp)}if(!t)break;const a=t.sampleQueue.shift();await this.addSampleToTrack(t,a)}}async finalizeFragment(e=!0){n(this.isFragmented);const t=this.nextFragmentNumber++;if(1===t){this.format._options.onMoov&&this.writer.startTrackingWrites();const e=ds(this);if(this.boxWriter.writeBox(e),this.format._options.onMoov){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMoov(e,t)}}const r=this.trackDatas.filter(e=>e.currentChunk),a=$s(t,r),i=this.writer.getPos(),s=i+this.boxWriter.measureBox(a);let o=s+8,c=1/0;for(const e of r){e.currentChunk.offset=o,e.currentChunk.moofOffset=i;for(const t of e.currentChunk.samples)o+=t.size;c=Math.min(c,e.currentChunk.startTimestamp)}const d=o-s,u=d>=2**32;if(u)for(const e of r)e.currentChunk.offset+=8;this.format._options.onMoof&&this.writer.startTrackingWrites();const l=$s(t,r);if(this.boxWriter.writeBox(l),this.format._options.onMoof){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMoof(e,t,c)}n(this.writer.getPos()===s),this.format._options.onMdat&&this.writer.startTrackingWrites();const h=cs(u);h.size=d,this.boxWriter.writeBox(h),this.writer.seek(s+(u?nr:8));for(const e of r)for(const t of e.currentChunk.samples)this.writer.write(t.data),t.data=null;if(this.format._options.onMdat){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMdat(e,t)}for(const e of r)e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk),e.currentChunk=null;e&&await this.writer.flush()}async registerSampleFastStartReserve(e,t){if(this.allTracksAreKnown()){if(!this.mdat){const e=ds(this),t=this.boxWriter.measureBox(e)+this.computeSampleTableSizeUpperBound()+4096;n(null!==this.ftypSize),this.writer.seek(this.ftypSize+t),this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=cs(!0),this.boxWriter.writeBox(this.mdat);for(const e of this.trackDatas){for(const t of e.sampleQueue)await this.addSampleToTrack(e,t);e.sampleQueue.length=0}}await this.addSampleToTrack(e,t)}else e.sampleQueue.push(t)}computeSampleTableSizeUpperBound(){n("reserve"===this.fastStart);let e=0;for(const t of this.trackDatas){const r=t.track.metadata.maximumPacketCount;n(void 0!==r),e+=8*Math.ceil(2/3*r),e+=4*r,e+=8*Math.ceil(2/3*r),e+=12*Math.ceil(2/3*r),e+=4*r,e+=8*r}return e}async onTrackClose(e){const t=await this.mutex.acquire();if("subtitle"===e.type&&"webvtt"===e.source._codec){const t=this.trackDatas.find(t=>t.track===e);t&&await this.processWebVTTCues(t,1/0)}this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),t()}async finalize(){const e=await this.mutex.acquire();this.allTracksKnown.resolve();for(const e of this.trackDatas)"subtitle"===e.type&&"webvtt"===e.track.source._codec&&await this.processWebVTTCues(e,1/0);if(this.isFragmented){await this.interleaveSamples(!0);for(const e of this.trackDatas)this.processTimestamps(e);await this.finalizeFragment(!1)}else for(const e of this.trackDatas)this.processTimestamps(e),await this.finalizeCurrentChunk(e);if("in-memory"===this.fastStart){let e;this.mdat=cs(!1);for(let t=0;t<2;t++){const t=ds(this),r=this.boxWriter.measureBox(t);e=this.boxWriter.measureBox(this.mdat);let a=this.writer.getPos()+r+e;for(const t of this.finalizedChunks){t.offset=a;for(const{data:r}of t.samples)n(r),a+=r.byteLength,e+=r.byteLength}if(a<2**32)break;e>=2**32&&(this.mdat.largeSize=!0)}this.format._options.onMoov&&this.writer.startTrackingWrites();const t=ds(this);if(this.boxWriter.writeBox(t),this.format._options.onMoov){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMoov(e,t)}this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=e,this.boxWriter.writeBox(this.mdat);for(const e of this.finalizedChunks)for(const t of e.samples)n(t.data),this.writer.write(t.data),t.data=null;if(this.format._options.onMdat){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMdat(e,t)}}else if(this.isFragmented){const e=this.writer.getPos(),r=(t=this.trackDatas,ns("mfra",void 0,[...t.map(Zs),en()]));this.boxWriter.writeBox(r);const a=this.writer.getPos()-e;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(a)}else{n(this.mdat);const e=this.boxWriter.offsets.get(this.mdat);n(void 0!==e);const t=this.writer.getPos()-e;if(this.mdat.size=t,this.mdat.largeSize=t>=2**32,this.boxWriter.patchBox(this.mdat),this.format._options.onMdat){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMdat(e,t)}const r=ds(this);if("reserve"===this.fastStart){n(null!==this.ftypSize),this.writer.seek(this.ftypSize),this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(r);const e=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox({type:"free",size:e})}else this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(r);if(this.format._options.onMoov){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMoov(e,t)}}var t;e()}}
|
|
93
246
|
/*!
|
|
94
247
|
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
95
248
|
*
|
|
96
249
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
97
250
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
98
251
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
99
|
-
*/const li="Mediabunny",hi={video:1,audio:2,subtitle:17};class mi extends ${constructor(e,t){super(e),this.trackDatas=[],this.allTracksKnown=w(),this.segment=null,this.segmentInfo=null,this.seekHead=null,this.tracksElement=null,this.tagsElement=null,this.attachmentsElement=null,this.segmentDuration=null,this.cues=null,this.currentCluster=null,this.currentClusterStartMsTimestamp=null,this.currentClusterMaxMsTimestamp=null,this.trackDatasInCurrentCluster=new Map,this.duration=0,this.writer=e._writer,this.format=t,this.ebmlWriter=new ke(this.writer),this.format._options.appendOnly&&(this.writer.ensureMonotonicity=!0)}async start(){const e=await this.mutex.acquire();this.writeEBMLHeader(),this.createSegmentInfo(),this.createCues(),await this.writer.flush(),e()}writeEBMLHeader(){this.format._options.onEbmlHeader&&this.writer.startTrackingWrites();const e={id:pe.EBML,data:[{id:pe.EBMLVersion,data:1},{id:pe.EBMLReadVersion,data:1},{id:pe.EBMLMaxIDLength,data:4},{id:pe.EBMLMaxSizeLength,data:8},{id:pe.DocType,data:this.format instanceof yi?"webm":"matroska"},{id:pe.DocTypeVersion,data:2},{id:pe.DocTypeReadVersion,data:2}]};if(this.ebmlWriter.writeEBML(e),this.format._options.onEbmlHeader){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onEbmlHeader(e,t)}}maybeCreateSeekHead(e){if(this.format._options.appendOnly)return;const t=new Uint8Array([28,83,187,107]),i=new Uint8Array([21,73,169,102]),r=new Uint8Array([22,84,174,107]),a=new Uint8Array([25,65,164,105]),s=new Uint8Array([18,84,195,103]),o={id:pe.SeekHead,data:[{id:pe.Seek,data:[{id:pe.SeekID,data:t},{id:pe.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.cues)-this.segmentDataOffset:0}]},{id:pe.Seek,data:[{id:pe.SeekID,data:i},{id:pe.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.segmentInfo)-this.segmentDataOffset:0}]},{id:pe.Seek,data:[{id:pe.SeekID,data:r},{id:pe.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.tracksElement)-this.segmentDataOffset:0}]},this.attachmentsElement?{id:pe.Seek,data:[{id:pe.SeekID,data:a},{id:pe.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.attachmentsElement)-this.segmentDataOffset:0}]}:null,this.tagsElement?{id:pe.Seek,data:[{id:pe.SeekID,data:s},{id:pe.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.tagsElement)-this.segmentDataOffset:0}]}:null]};this.seekHead=o}createSegmentInfo(){const e={id:pe.Duration,data:new le(0)};this.segmentDuration=e;const t={id:pe.Info,data:[{id:pe.TimestampScale,data:1e6},{id:pe.MuxingApp,data:li},{id:pe.WritingApp,data:li},this.format._options.appendOnly?null:e]};this.segmentInfo=t}createTracks(){const e={id:pe.Tracks,data:[]};this.tracksElement=e;for(const t of this.trackDatas){const i=ye[t.track.source._codec];r(i);let a=0;if("audio"===t.type&&"opus"===t.track.source._codec){a=8e7;const e=t.info.decoderConfig.description;if(e){const t=d(e),i=oe(t);a=Math.round(i.preSkip/48e3*1e9)}}e.data.push({id:pe.TrackEntry,data:[{id:pe.TrackNumber,data:t.track.id},{id:pe.TrackUID,data:t.track.id},{id:pe.TrackType,data:hi[t.type]},!1===t.track.metadata.disposition?.default?{id:pe.FlagDefault,data:0}:null,t.track.metadata.disposition?.forced?{id:pe.FlagForced,data:1}:null,t.track.metadata.disposition?.hearingImpaired?{id:pe.FlagHearingImpaired,data:1}:null,t.track.metadata.disposition?.visuallyImpaired?{id:pe.FlagVisualImpaired,data:1}:null,t.track.metadata.disposition?.original?{id:pe.FlagOriginal,data:1}:null,t.track.metadata.disposition?.commentary?{id:pe.FlagCommentary,data:1}:null,{id:pe.FlagLacing,data:0},{id:pe.Language,data:t.track.metadata.languageCode??"und"},{id:pe.CodecID,data:i},{id:pe.CodecDelay,data:0},{id:pe.SeekPreRoll,data:a},void 0!==t.track.metadata.name?{id:pe.Name,data:new me(t.track.metadata.name)}:null,"video"===t.type?this.videoSpecificTrackInfo(t):null,"audio"===t.type?this.audioSpecificTrackInfo(t):null,"subtitle"===t.type?this.subtitleSpecificTrackInfo(t):null]})}}videoSpecificTrackInfo(e){const{frameRate:t,rotation:i}=e.track.metadata,r=[e.info.decoderConfig.description?{id:pe.CodecPrivate,data:d(e.info.decoderConfig.description)}:null,t?{id:pe.DefaultDuration,data:1e9/t}:null],a=i?(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):0,s=e.info.decoderConfig.colorSpace,o={id:pe.Video,data:[{id:pe.PixelWidth,data:e.info.width},{id:pe.PixelHeight,data:e.info.height},e.info.alphaMode?{id:pe.AlphaMode,data:1}:null,p(s)?{id:pe.Colour,data:[{id:pe.MatrixCoefficients,data:m[s.matrix]},{id:pe.TransferCharacteristics,data:h[s.transfer]},{id:pe.Primaries,data:l[s.primaries]},{id:pe.Range,data:s.fullRange?2:1}]}:null,a?{id:pe.Projection,data:[{id:pe.ProjectionType,data:0},{id:pe.ProjectionPoseRoll,data:new ue((a+180)%360-180)}]}:null]};return r.push(o),r}audioSpecificTrackInfo(e){const t=A.includes(e.track.source._codec)?U(e.track.source._codec):null;return[e.info.decoderConfig.description?{id:pe.CodecPrivate,data:d(e.info.decoderConfig.description)}:null,{id:pe.Audio,data:[{id:pe.SamplingFrequency,data:new ue(e.info.sampleRate)},{id:pe.Channels,data:e.info.numberOfChannels},t?{id:pe.BitDepth,data:8*t.sampleSize}:null]}]}subtitleSpecificTrackInfo(e){return[{id:pe.CodecPrivate,data:u.encode(e.info.config.description)}]}maybeCreateTags(){const e=[],t=(t,i)=>{e.push({id:pe.SimpleTag,data:[{id:pe.TagName,data:new me(t)},"string"==typeof i?{id:pe.TagString,data:new me(i)}:{id:pe.TagBinary,data:i}]})},i=this.output._metadataTags,r=new Set;for(const{key:e,value:a}of C(i))switch(e){case"title":t("TITLE",a),r.add("TITLE");break;case"description":t("DESCRIPTION",a),r.add("DESCRIPTION");break;case"artist":t("ARTIST",a),r.add("ARTIST");break;case"album":t("ALBUM",a),r.add("ALBUM");break;case"albumArtist":t("ALBUM_ARTIST",a),r.add("ALBUM_ARTIST");break;case"genre":t("GENRE",a),r.add("GENRE");break;case"comment":t("COMMENT",a),r.add("COMMENT");break;case"lyrics":t("LYRICS",a),r.add("LYRICS");break;case"date":t("DATE",a.toISOString().slice(0,10)),r.add("DATE");break;case"trackNumber":t("PART_NUMBER",void 0!==i.tracksTotal?`${a}/${i.tracksTotal}`:a.toString()),r.add("PART_NUMBER");break;case"discNumber":t("DISC",void 0!==i.discsTotal?`${a}/${i.discsTotal}`:a.toString()),r.add("DISC");break;case"tracksTotal":case"discsTotal":case"images":case"raw":break;default:k(e)}if(i.raw)for(const e in i.raw){const a=i.raw[e];null==a||r.has(e)||("string"==typeof a||a instanceof Uint8Array)&&t(e,a)}0!==e.length&&(this.tagsElement={id:pe.Tags,data:[{id:pe.Tag,data:[{id:pe.Targets,data:[{id:pe.TargetTypeValue,data:50},{id:pe.TargetType,data:"MOVIE"}]},...e]}]})}maybeCreateAttachments(){const e=this.output._metadataTags,t=[],i=new Set,r=e.images??[];for(const e of r){let r,a=e.name;if(void 0===a){a=("coverFront"===e.kind?"cover":"coverBack"===e.kind?"back":"image")+(v(e.mimeType)??"")}for(;;){r=0n;for(let e=0;e<8;e++)r<<=8n,r|=BigInt(Math.floor(256*Math.random()));if(0n!==r&&!i.has(r))break}i.add(r),t.push({id:pe.AttachedFile,data:[void 0!==e.description?{id:pe.FileDescription,data:new me(e.description)}:null,{id:pe.FileName,data:new me(a)},{id:pe.FileMediaType,data:e.mimeType},{id:pe.FileData,data:e.data},{id:pe.FileUID,data:r}]})}for(const[i,a]of Object.entries(e.raw??{})){if(!(a instanceof _))continue;/^\d+$/.test(i)&&(r.find(e=>e.mimeType===a.mimeType&&S(e.data,a.data))||t.push({id:pe.AttachedFile,data:[void 0!==a.description?{id:pe.FileDescription,data:new me(a.description)}:null,{id:pe.FileName,data:new me(a.name??"")},{id:pe.FileMediaType,data:a.mimeType??""},{id:pe.FileData,data:a.data},{id:pe.FileUID,data:BigInt(i)}]}))}0!==t.length&&(this.attachmentsElement={id:pe.Attachments,data:t})}createSegment(){this.createTracks(),this.maybeCreateTags(),this.maybeCreateAttachments(),this.maybeCreateSeekHead(!1);const e={id:pe.Segment,size:this.format._options.appendOnly?-1:6,data:[this.seekHead,this.segmentInfo,this.tracksElement,this.attachmentsElement,this.tagsElement]};if(this.segment=e,this.format._options.onSegmentHeader&&this.writer.startTrackingWrites(),this.ebmlWriter.writeEBML(e),this.format._options.onSegmentHeader){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onSegmentHeader(e,t)}}createCues(){this.cues={id:pe.Cues,data:[]}}get segmentDataOffset(){return r(this.segment),this.ebmlWriter.dataOffsets.get(this.segment)}allTracksAreKnown(){for(const e of this.output._tracks)if(!e.source._closed&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;const e=this.trackDatas.map(e=>{if("video"===e.type)return e.info.decoderConfig.codec;if("audio"===e.type)return e.info.decoderConfig.codec;return{webvtt:"wvtt"}[e.track.source._codec]});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.format instanceof yi,hasVideo:this.trackDatas.some(e=>"video"===e.type),hasAudio:this.trackDatas.some(e=>"audio"===e.type),codecStrings:e})}getVideoTrackData(e,t,i){const a=this.trackDatas.find(t=>t.track===e);if(a)return a;R(i),r(i),r(i.decoderConfig),r(void 0!==i.decoderConfig.codedWidth),r(void 0!==i.decoderConfig.codedHeight);const s={track:e,type:"video",info:{width:i.decoderConfig.codedWidth,height:i.decoderConfig.codedHeight,decoderConfig:i.decoderConfig,alphaMode:!!t.sideData.alpha},chunkQueue:[],lastWrittenMsTimestamp:null};return"vp9"===e.source._codec?s.info.decoderConfig={...s.info.decoderConfig,description:new Uint8Array(I(s.info.decoderConfig.codec))}:"av1"===e.source._codec&&(s.info.decoderConfig={...s.info.decoderConfig,description:new Uint8Array(D(s.info.decoderConfig.codec))}),this.trackDatas.push(s),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),s}getAudioTrackData(e,t){const i=this.trackDatas.find(t=>t.track===e);if(i)return i;H(t),r(t),r(t.decoderConfig);const a={track:e,type:"audio",info:{numberOfChannels:t.decoderConfig.numberOfChannels,sampleRate:t.decoderConfig.sampleRate,decoderConfig:t.decoderConfig},chunkQueue:[],lastWrittenMsTimestamp:null};return this.trackDatas.push(a),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),a}getSubtitleTrackData(e,t){const i=this.trackDatas.find(t=>t.track===e);if(i)return i;j(t),r(t),r(t.config);const a={track:e,type:"subtitle",info:{config:t.config},chunkQueue:[],lastWrittenMsTimestamp:null};return this.trackDatas.push(a),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),a}async addEncodedVideoPacket(e,t,i){const r=await this.mutex.acquire();try{const r=this.getVideoTrackData(e,t,i),a="key"===t.type;let s=this.validateAndNormalizeTimestamp(r.track,t.timestamp,a),o=t.duration;void 0!==e.metadata.frameRate&&(s=y(s,1/e.metadata.frameRate),o=y(o,1/e.metadata.frameRate));const n=r.info.alphaMode?t.sideData.alpha??null:null,c=this.createInternalChunk(t.data,s,o,t.type,n);"vp9"===e.source._codec&&this.fixVP9ColorSpace(r,c),r.chunkQueue.push(c),await this.interleaveChunks()}finally{r()}}async addEncodedAudioPacket(e,t,i){const r=await this.mutex.acquire();try{const r=this.getAudioTrackData(e,i),a="key"===t.type,s=this.validateAndNormalizeTimestamp(r.track,t.timestamp,a),o=this.createInternalChunk(t.data,s,t.duration,t.type);r.chunkQueue.push(o),await this.interleaveChunks()}finally{r()}}async addSubtitleCue(e,t,i){const r=await this.mutex.acquire();try{const r=this.getSubtitleTrackData(e,i),a=this.validateAndNormalizeTimestamp(r.track,t.timestamp,!0);let s=t.text;const o=Math.round(1e3*a);be.lastIndex=0,s=s.replace(be,e=>{const t=(e=>{const t=Te.exec(e);if(!t)throw new Error("Expected match.");return 36e5*Number(t[1]||"0")+6e4*Number(t[2])+1e3*Number(t[3])+Number(t[4])})(e.slice(1,-1));return`<${Ce(t-o)}>`});const n=u.encode(s),c=`${t.settings??""}\n${t.identifier??""}\n${t.notes??""}`,d=this.createInternalChunk(n,a,t.duration,"key",c.trim()?u.encode(c):null);r.chunkQueue.push(d),await this.interleaveChunks()}finally{r()}}async interleaveChunks(e=!1){if(e||this.allTracksAreKnown()){e:for(;;){let t=null,i=1/0;for(const r of this.trackDatas){if(!e&&0===r.chunkQueue.length&&!r.track.source._closed)break e;r.chunkQueue.length>0&&r.chunkQueue[0].timestamp<i&&(t=r,i=r.chunkQueue[0].timestamp)}if(!t)break;const r=t.chunkQueue.shift();this.writeBlock(t,r)}e||await this.writer.flush()}}fixVP9ColorSpace(e,t){if("key"!==t.type)return;if(!e.info.decoderConfig.colorSpace||!e.info.decoderConfig.colorSpace.matrix)return;const i=new o(t.data);i.skipBits(2);const r=i.readBits(1),a=(i.readBits(1)<<1)+r;3===a&&i.skipBits(1);if(i.readBits(1))return;if(0!==i.readBits(1))return;i.skipBits(2);if(4817730!==i.readBits(24))return;a>=2&&i.skipBits(1);const s={rgb:7,bt709:2,bt470bg:1,smpte170m:3}[e.info.decoderConfig.colorSpace.matrix];((e,t,i,r)=>{for(let a=t;a<i;a++){const t=Math.floor(a/8);let s=e[t];const o=7-(7&a);s&=~(1<<o),s|=(r&1<<i-a-1)>>i-a-1<<o,e[t]=s}})(t.data,i.pos,i.pos+3,s)}createInternalChunk(e,t,i,r,a=null){return{data:e,type:r,timestamp:t,duration:i,additions:a}}writeBlock(e,t){this.segment||this.createSegment();const i=Math.round(1e3*t.timestamp),a=this.trackDatas.every(i=>{if(e===i)return"key"===t.type;const r=i.chunkQueue[0];return r?"key"===r.type:i.track.source._closed});let s=!1;if(this.currentCluster){r(null!==this.currentClusterStartMsTimestamp),r(null!==this.currentClusterMaxMsTimestamp);const e=i-this.currentClusterStartMsTimestamp;s=a&&i>this.currentClusterMaxMsTimestamp&&e>=1e3*(this.format._options.minimumClusterDuration??1)||e>32767}else s=!0;s&&this.createNewCluster(i);const o=i-this.currentClusterStartMsTimestamp;if(o<-32768)return;const n=new Uint8Array(4),c=new DataView(n.buffer);c.setUint8(0,128|e.track.id),c.setInt16(1,o,!1);const d=Math.round(1e3*t.duration);if(t.additions){const r={id:pe.BlockGroup,data:[{id:pe.Block,data:[n,t.data]},"delta"===t.type?{id:pe.ReferenceBlock,data:new he(e.lastWrittenMsTimestamp-i)}:null,t.additions?{id:pe.BlockAdditions,data:[{id:pe.BlockMore,data:[{id:pe.BlockAddID,data:1},{id:pe.BlockAdditional,data:t.additions}]}]}:null,d>0?{id:pe.BlockDuration,data:d}:null]};this.ebmlWriter.writeEBML(r)}else{c.setUint8(3,Number("key"===t.type)<<7);const e={id:pe.SimpleBlock,data:[n,t.data]};this.ebmlWriter.writeEBML(e)}this.duration=Math.max(this.duration,i+d),e.lastWrittenMsTimestamp=i,this.trackDatasInCurrentCluster.has(e)||this.trackDatasInCurrentCluster.set(e,{firstMsTimestamp:i}),this.currentClusterMaxMsTimestamp=Math.max(this.currentClusterMaxMsTimestamp,i)}createNewCluster(e){this.currentCluster&&this.finalizeCurrentCluster(),this.format._options.onCluster&&this.writer.startTrackingWrites(),this.currentCluster={id:pe.Cluster,size:this.format._options.appendOnly?-1:5,data:[{id:pe.Timestamp,data:e}]},this.ebmlWriter.writeEBML(this.currentCluster),this.currentClusterStartMsTimestamp=e,this.currentClusterMaxMsTimestamp=e,this.trackDatasInCurrentCluster.clear()}finalizeCurrentCluster(){if(r(this.currentCluster),!this.format._options.appendOnly){const e=this.writer.getPos()-this.ebmlWriter.dataOffsets.get(this.currentCluster),t=this.writer.getPos();this.writer.seek(this.ebmlWriter.offsets.get(this.currentCluster)+4),this.ebmlWriter.writeVarInt(e,5),this.writer.seek(t)}if(this.format._options.onCluster){r(null!==this.currentClusterStartMsTimestamp);const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onCluster(e,t,this.currentClusterStartMsTimestamp/1e3)}const e=this.ebmlWriter.offsets.get(this.currentCluster)-this.segmentDataOffset,t=new Map;for(const[e,{firstMsTimestamp:i}]of this.trackDatasInCurrentCluster)t.has(i)||t.set(i,[]),t.get(i).push(e);const i=[...t.entries()].sort((e,t)=>e[0]-t[0]);for(const[t,a]of i)r(this.cues),this.cues.data.push({id:pe.CuePoint,data:[{id:pe.CueTime,data:t},...a.map(t=>({id:pe.CueTrackPositions,data:[{id:pe.CueTrack,data:t.track.id},{id:pe.CueClusterPosition,data:e}]}))]})}async onTrackClose(){const e=await this.mutex.acquire();this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleaveChunks(),e()}async finalize(){const e=await this.mutex.acquire();if(this.allTracksKnown.resolve(),this.segment||this.createSegment(),await this.interleaveChunks(!0),this.currentCluster&&this.finalizeCurrentCluster(),r(this.cues),this.ebmlWriter.writeEBML(this.cues),!this.format._options.appendOnly){const e=this.writer.getPos(),t=this.writer.getPos()-this.segmentDataOffset;this.writer.seek(this.ebmlWriter.offsets.get(this.segment)+4),this.ebmlWriter.writeVarInt(t,6),this.segmentDuration.data=new le(this.duration),this.writer.seek(this.ebmlWriter.offsets.get(this.segmentDuration)),this.ebmlWriter.writeEBML(this.segmentDuration),r(this.seekHead),this.writer.seek(this.ebmlWriter.offsets.get(this.seekHead)),this.maybeCreateSeekHead(!0),this.ebmlWriter.writeEBML(this.seekHead),this.writer.seek(e)}e()}}
|
|
252
|
+
*/const Bn="Mediabunny",An={video:1,audio:2,subtitle:17};class _n extends Le{constructor(e,t){super(e),this.trackDatas=[],this.allTracksKnown=_(),this.segment=null,this.segmentInfo=null,this.seekHead=null,this.tracksElement=null,this.tagsElement=null,this.attachmentsElement=null,this.segmentDuration=null,this.cues=null,this.currentCluster=null,this.currentClusterStartMsTimestamp=null,this.currentClusterMaxMsTimestamp=null,this.trackDatasInCurrentCluster=new Map,this.duration=0,this.writer=e._writer,this.format=t,this.ebmlWriter=new Rr(this.writer),this.format._options.appendOnly&&(this.writer.ensureMonotonicity=!0)}async start(){const e=await this.mutex.acquire();this.writeEBMLHeader(),this.createSegmentInfo(),this.createCues(),await this.writer.flush(),e()}writeEBMLHeader(){this.format._options.onEbmlHeader&&this.writer.startTrackingWrites();const e={id:Er.EBML,data:[{id:Er.EBMLVersion,data:1},{id:Er.EBMLReadVersion,data:1},{id:Er.EBMLMaxIDLength,data:4},{id:Er.EBMLMaxSizeLength,data:8},{id:Er.DocType,data:this.format instanceof Nn?"webm":"matroska"},{id:Er.DocTypeVersion,data:2},{id:Er.DocTypeReadVersion,data:2}]};if(this.ebmlWriter.writeEBML(e),this.format._options.onEbmlHeader){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onEbmlHeader(e,t)}}maybeCreateSeekHead(e){if(this.format._options.appendOnly)return;const t=new Uint8Array([28,83,187,107]),r=new Uint8Array([21,73,169,102]),a=new Uint8Array([22,84,174,107]),i=new Uint8Array([25,65,164,105]),s=new Uint8Array([18,84,195,103]),n={id:Er.SeekHead,data:[{id:Er.Seek,data:[{id:Er.SeekID,data:t},{id:Er.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.cues)-this.segmentDataOffset:0}]},{id:Er.Seek,data:[{id:Er.SeekID,data:r},{id:Er.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.segmentInfo)-this.segmentDataOffset:0}]},{id:Er.Seek,data:[{id:Er.SeekID,data:a},{id:Er.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.tracksElement)-this.segmentDataOffset:0}]},this.attachmentsElement?{id:Er.Seek,data:[{id:Er.SeekID,data:i},{id:Er.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.attachmentsElement)-this.segmentDataOffset:0}]}:null,this.tagsElement?{id:Er.Seek,data:[{id:Er.SeekID,data:s},{id:Er.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.tagsElement)-this.segmentDataOffset:0}]}:null]};this.seekHead=n}createSegmentInfo(){const e={id:Er.Duration,data:new Pr(0)};this.segmentDuration=e;const t={id:Er.Info,data:[{id:Er.TimestampScale,data:1e6},{id:Er.MuxingApp,data:Bn},{id:Er.WritingApp,data:Bn},this.format._options.appendOnly?null:e]};this.segmentInfo=t}createTracks(){const e={id:Er.Tracks,data:[]};this.tracksElement=e;for(const t of this.trackDatas){const r=Kr[t.track.source._codec];n(r);let a=0;if("audio"===t.type&&"opus"===t.track.source._codec){a=8e7;const e=t.info.decoderConfig.description;if(e){const t=m(e),r=lt(t);a=Math.round(r.preSkip/xe*1e9)}}e.data.push({id:Er.TrackEntry,data:[{id:Er.TrackNumber,data:t.track.id},{id:Er.TrackUID,data:t.track.id},{id:Er.TrackType,data:An[t.type]},!1===t.track.metadata.disposition?.default?{id:Er.FlagDefault,data:0}:null,t.track.metadata.disposition?.forced?{id:Er.FlagForced,data:1}:null,t.track.metadata.disposition?.hearingImpaired?{id:Er.FlagHearingImpaired,data:1}:null,t.track.metadata.disposition?.visuallyImpaired?{id:Er.FlagVisualImpaired,data:1}:null,t.track.metadata.disposition?.original?{id:Er.FlagOriginal,data:1}:null,t.track.metadata.disposition?.commentary?{id:Er.FlagCommentary,data:1}:null,{id:Er.FlagLacing,data:0},{id:Er.Language,data:t.track.metadata.languageCode??L},{id:Er.CodecID,data:r},{id:Er.CodecDelay,data:0},{id:Er.SeekPreRoll,data:a},void 0!==t.track.metadata.name?{id:Er.Name,data:new xr(t.track.metadata.name)}:null,"video"===t.type?this.videoSpecificTrackInfo(t):null,"audio"===t.type?this.audioSpecificTrackInfo(t):null,"subtitle"===t.type?this.subtitleSpecificTrackInfo(t):null]})}}videoSpecificTrackInfo(e){const{frameRate:t,rotation:r}=e.track.metadata,a=[e.info.decoderConfig.description?{id:Er.CodecPrivate,data:m(e.info.decoderConfig.description)}:null,t?{id:Er.DefaultDuration,data:1e9/t}:null],i=r?o(-r):0,s=e.info.decoderConfig.colorSpace,n={id:Er.Video,data:[{id:Er.PixelWidth,data:e.info.width},{id:Er.PixelHeight,data:e.info.height},e.info.alphaMode?{id:Er.AlphaMode,data:1}:null,v(s)?{id:Er.Colour,data:[{id:Er.MatrixCoefficients,data:S[s.matrix]},{id:Er.TransferCharacteristics,data:T[s.transfer]},{id:Er.Primaries,data:b[s.primaries]},{id:Er.Range,data:s.fullRange?2:1}]}:null,i?{id:Er.Projection,data:[{id:Er.ProjectionType,data:0},{id:Er.ProjectionPoseRoll,data:new vr((i+180)%360-180)}]}:null]};return a.push(n),a}audioSpecificTrackInfo(e){const t=me.includes(e.track.source._codec)?De(e.track.source._codec):null;return[e.info.decoderConfig.description?{id:Er.CodecPrivate,data:m(e.info.decoderConfig.description)}:null,{id:Er.Audio,data:[{id:Er.SamplingFrequency,data:new vr(e.info.sampleRate)},{id:Er.Channels,data:e.info.numberOfChannels},t?{id:Er.BitDepth,data:8*t.sampleSize}:null]}]}subtitleSpecificTrackInfo(e){return[{id:Er.CodecPrivate,data:g.encode(e.info.config.description)}]}maybeCreateTags(){const e=[],t=(t,r)=>{e.push({id:Er.SimpleTag,data:[{id:Er.TagName,data:new xr(t)},"string"==typeof r?{id:Er.TagString,data:new xr(r)}:{id:Er.TagBinary,data:r}]})},r=this.output._metadataTags,a=new Set;for(const{key:e,value:i}of ae(r))switch(e){case"title":t("TITLE",i),a.add("TITLE");break;case"description":t("DESCRIPTION",i),a.add("DESCRIPTION");break;case"artist":t("ARTIST",i),a.add("ARTIST");break;case"album":t("ALBUM",i),a.add("ALBUM");break;case"albumArtist":t("ALBUM_ARTIST",i),a.add("ALBUM_ARTIST");break;case"genre":t("GENRE",i),a.add("GENRE");break;case"comment":t("COMMENT",i),a.add("COMMENT");break;case"lyrics":t("LYRICS",i),a.add("LYRICS");break;case"date":t("DATE",i.toISOString().slice(0,10)),a.add("DATE");break;case"trackNumber":t("PART_NUMBER",void 0!==r.tracksTotal?`${i}/${r.tracksTotal}`:i.toString()),a.add("PART_NUMBER");break;case"discNumber":t("DISC",void 0!==r.discsTotal?`${i}/${r.discsTotal}`:i.toString()),a.add("DISC");break;case"tracksTotal":case"discsTotal":case"images":case"raw":break;default:R(e)}if(r.raw)for(const e in r.raw){const i=r.raw[e];null==i||a.has(e)||("string"==typeof i||i instanceof Uint8Array)&&t(e,i)}0!==e.length&&(this.tagsElement={id:Er.Tags,data:[{id:Er.Tag,data:[{id:Er.Targets,data:[{id:Er.TargetTypeValue,data:50},{id:Er.TargetType,data:"MOVIE"}]},...e]}]})}maybeCreateAttachments(){const e=this.output._metadataTags,t=[],r=new Set,a=e.images??[];for(const e of a){let a,i=e.name;if(void 0===i){i=("coverFront"===e.kind?"cover":"coverBack"===e.kind?"back":"image")+(ie(e.mimeType)??"")}for(;;){a=0n;for(let e=0;e<8;e++)a<<=8n,a|=BigInt(Math.floor(256*Math.random()));if(0n!==a&&!r.has(a))break}r.add(a),t.push({id:Er.AttachedFile,data:[void 0!==e.description?{id:Er.FileDescription,data:new xr(e.description)}:null,{id:Er.FileName,data:new xr(i)},{id:Er.FileMediaType,data:e.mimeType},{id:Er.FileData,data:e.data},{id:Er.FileUID,data:a}]})}for(const[r,i]of Object.entries(e.raw??{})){if(!(i instanceof ue))continue;/^\d+$/.test(r)&&(a.find(e=>e.mimeType===i.mimeType&&ne(e.data,i.data))||t.push({id:Er.AttachedFile,data:[void 0!==i.description?{id:Er.FileDescription,data:new xr(i.description)}:null,{id:Er.FileName,data:new xr(i.name??"")},{id:Er.FileMediaType,data:i.mimeType??""},{id:Er.FileData,data:i.data},{id:Er.FileUID,data:BigInt(r)}]}))}0!==t.length&&(this.attachmentsElement={id:Er.Attachments,data:t})}createSegment(){this.createTracks(),this.maybeCreateTags(),this.maybeCreateAttachments(),this.maybeCreateSeekHead(!1);const e={id:Er.Segment,size:this.format._options.appendOnly?-1:6,data:[this.seekHead,this.segmentInfo,this.tracksElement,this.attachmentsElement,this.tagsElement]};if(this.segment=e,this.format._options.onSegmentHeader&&this.writer.startTrackingWrites(),this.ebmlWriter.writeEBML(e),this.format._options.onSegmentHeader){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onSegmentHeader(e,t)}}createCues(){this.cues={id:Er.Cues,data:[]}}get segmentDataOffset(){return n(this.segment),this.ebmlWriter.dataOffsets.get(this.segment)}allTracksAreKnown(){for(const e of this.output._tracks)if(!e.source._closed&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;const e=this.trackDatas.map(e=>{if("video"===e.type)return e.info.decoderConfig.codec;if("audio"===e.type)return e.info.decoderConfig.codec;return{webvtt:"wvtt"}[e.track.source._codec]});return Xr({isWebM:this.format instanceof Nn,hasVideo:this.trackDatas.some(e=>"video"===e.type),hasAudio:this.trackDatas.some(e=>"audio"===e.type),codecStrings:e})}getVideoTrackData(e,t,r){const a=this.trackDatas.find(t=>t.track===e);if(a)return a;Re(r),n(r),n(r.decoderConfig),n(void 0!==r.decoderConfig.codedWidth),n(void 0!==r.decoderConfig.codedHeight);const i={track:e,type:"video",info:{width:r.decoderConfig.codedWidth,height:r.decoderConfig.codedHeight,decoderConfig:r.decoderConfig,alphaMode:!!t.sideData.alpha},chunkQueue:[],lastWrittenMsTimestamp:null};return"vp9"===e.source._codec?i.info.decoderConfig={...i.info.decoderConfig,description:new Uint8Array(Te(i.info.decoderConfig.codec))}:"av1"===e.source._codec&&(i.info.decoderConfig={...i.info.decoderConfig,description:new Uint8Array(ye(i.info.decoderConfig.codec))}),this.trackDatas.push(i),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),i}getAudioTrackData(e,t){const r=this.trackDatas.find(t=>t.track===e);if(r)return r;Oe(t),n(t),n(t.decoderConfig);const a={track:e,type:"audio",info:{numberOfChannels:t.decoderConfig.numberOfChannels,sampleRate:t.decoderConfig.sampleRate,decoderConfig:t.decoderConfig},chunkQueue:[],lastWrittenMsTimestamp:null};return this.trackDatas.push(a),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),a}getSubtitleTrackData(e,t){const r=this.trackDatas.find(t=>t.track===e);if(r)return r;Ne(t),n(t),n(t.config);const a={track:e,type:"subtitle",info:{config:t.config},chunkQueue:[],lastWrittenMsTimestamp:null};return this.trackDatas.push(a),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),a}async addEncodedVideoPacket(e,t,r){const a=await this.mutex.acquire();try{const a=this.getVideoTrackData(e,t,r),i="key"===t.type;let s=this.validateAndNormalizeTimestamp(a.track,t.timestamp,i),n=t.duration;void 0!==e.metadata.frameRate&&(s=V(s,1/e.metadata.frameRate),n=V(n,1/e.metadata.frameRate));const o=a.info.alphaMode?t.sideData.alpha??null:null,c=this.createInternalChunk(t.data,s,n,t.type,o);"vp9"===e.source._codec&&this.fixVP9ColorSpace(a,c),a.chunkQueue.push(c),await this.interleaveChunks()}finally{a()}}async addEncodedAudioPacket(e,t,r){const a=await this.mutex.acquire();try{const a=this.getAudioTrackData(e,r),i="key"===t.type,s=this.validateAndNormalizeTimestamp(a.track,t.timestamp,i),n=this.createInternalChunk(t.data,s,t.duration,t.type);a.chunkQueue.push(n),await this.interleaveChunks()}finally{a()}}async addSubtitleCue(e,t,r){const a=await this.mutex.acquire();try{const a=this.getSubtitleTrackData(e,r),i=this.validateAndNormalizeTimestamp(a.track,t.timestamp,!0);let s=t.text;const n=Math.round(1e3*i);Ni.lastIndex=0,s=s.replace(Ni,e=>{const t=(e=>{const t=Li.exec(e);if(!t)throw new Error("Expected match.");return 36e5*Number(t[1]||"0")+6e4*Number(t[2])+1e3*Number(t[3])+Number(t[4])})(e.slice(1,-1));return`<${Ui(t-n)}>`});const o=g.encode(s),c=`${t.settings??""}\n${t.identifier??""}\n${t.notes??""}`,d=this.createInternalChunk(o,i,t.duration,"key",c.trim()?g.encode(c):null);a.chunkQueue.push(d),await this.interleaveChunks()}finally{a()}}async interleaveChunks(e=!1){if(e||this.allTracksAreKnown()){e:for(;;){let t=null,r=1/0;for(const a of this.trackDatas){if(!e&&0===a.chunkQueue.length&&!a.track.source._closed)break e;a.chunkQueue.length>0&&a.chunkQueue[0].timestamp<r&&(t=a,r=a.chunkQueue[0].timestamp)}if(!t)break;const a=t.chunkQueue.shift();this.writeBlock(t,a)}e||await this.writer.flush()}}fixVP9ColorSpace(e,t){if("key"!==t.type)return;if(!e.info.decoderConfig.colorSpace||!e.info.decoderConfig.colorSpace.matrix)return;const r=new u(t.data);r.skipBits(2);const a=r.readBits(1),i=(r.readBits(1)<<1)+a;3===i&&r.skipBits(1);if(r.readBits(1))return;if(0!==r.readBits(1))return;r.skipBits(2);if(4817730!==r.readBits(24))return;i>=2&&r.skipBits(1);const s={rgb:7,bt709:2,bt470bg:1,smpte170m:3}[e.info.decoderConfig.colorSpace.matrix];((e,t,r,a)=>{for(let i=t;i<r;i++){const t=Math.floor(i/8);let s=e[t];const n=7-(7&i);s&=~(1<<n),s|=(a&1<<r-i-1)>>r-i-1<<n,e[t]=s}})(t.data,r.pos,r.pos+3,s)}createInternalChunk(e,t,r,a,i=null){return{data:e,type:a,timestamp:t,duration:r,additions:i}}writeBlock(e,t){this.segment||this.createSegment();const r=Math.round(1e3*t.timestamp),a=this.trackDatas.every(r=>{if(e===r)return"key"===t.type;const a=r.chunkQueue[0];return a?"key"===a.type:r.track.source._closed});let i=!1;if(this.currentCluster){n(null!==this.currentClusterStartMsTimestamp),n(null!==this.currentClusterMaxMsTimestamp);const e=r-this.currentClusterStartMsTimestamp;i=a&&r>this.currentClusterMaxMsTimestamp&&e>=1e3*(this.format._options.minimumClusterDuration??1)||e>32767}else i=!0;i&&this.createNewCluster(r);const s=r-this.currentClusterStartMsTimestamp;if(s<-32768)return;const o=new Uint8Array(4),c=new DataView(o.buffer);c.setUint8(0,128|e.track.id),c.setInt16(1,s,!1);const d=Math.round(1e3*t.duration);if(t.additions){const a={id:Er.BlockGroup,data:[{id:Er.Block,data:[o,t.data]},"delta"===t.type?{id:Er.ReferenceBlock,data:new Ir(e.lastWrittenMsTimestamp-r)}:null,t.additions?{id:Er.BlockAdditions,data:[{id:Er.BlockMore,data:[{id:Er.BlockAddID,data:1},{id:Er.BlockAdditional,data:t.additions}]}]}:null,d>0?{id:Er.BlockDuration,data:d}:null]};this.ebmlWriter.writeEBML(a)}else{c.setUint8(3,Number("key"===t.type)<<7);const e={id:Er.SimpleBlock,data:[o,t.data]};this.ebmlWriter.writeEBML(e)}this.duration=Math.max(this.duration,r+d),e.lastWrittenMsTimestamp=r,this.trackDatasInCurrentCluster.has(e)||this.trackDatasInCurrentCluster.set(e,{firstMsTimestamp:r}),this.currentClusterMaxMsTimestamp=Math.max(this.currentClusterMaxMsTimestamp,r)}createNewCluster(e){this.currentCluster&&this.finalizeCurrentCluster(),this.format._options.onCluster&&this.writer.startTrackingWrites(),this.currentCluster={id:Er.Cluster,size:this.format._options.appendOnly?-1:5,data:[{id:Er.Timestamp,data:e}]},this.ebmlWriter.writeEBML(this.currentCluster),this.currentClusterStartMsTimestamp=e,this.currentClusterMaxMsTimestamp=e,this.trackDatasInCurrentCluster.clear()}finalizeCurrentCluster(){if(n(this.currentCluster),!this.format._options.appendOnly){const e=this.writer.getPos()-this.ebmlWriter.dataOffsets.get(this.currentCluster),t=this.writer.getPos();this.writer.seek(this.ebmlWriter.offsets.get(this.currentCluster)+4),this.ebmlWriter.writeVarInt(e,5),this.writer.seek(t)}if(this.format._options.onCluster){n(null!==this.currentClusterStartMsTimestamp);const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onCluster(e,t,this.currentClusterStartMsTimestamp/1e3)}const e=this.ebmlWriter.offsets.get(this.currentCluster)-this.segmentDataOffset,t=new Map;for(const[e,{firstMsTimestamp:r}]of this.trackDatasInCurrentCluster)t.has(r)||t.set(r,[]),t.get(r).push(e);const r=[...t.entries()].sort((e,t)=>e[0]-t[0]);for(const[t,a]of r)n(this.cues),this.cues.data.push({id:Er.CuePoint,data:[{id:Er.CueTime,data:t},...a.map(t=>({id:Er.CueTrackPositions,data:[{id:Er.CueTrack,data:t.track.id},{id:Er.CueClusterPosition,data:e}]}))]})}async onTrackClose(){const e=await this.mutex.acquire();this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleaveChunks(),e()}async finalize(){const e=await this.mutex.acquire();if(this.allTracksKnown.resolve(),this.segment||this.createSegment(),await this.interleaveChunks(!0),this.currentCluster&&this.finalizeCurrentCluster(),n(this.cues),this.ebmlWriter.writeEBML(this.cues),!this.format._options.appendOnly){const e=this.writer.getPos(),t=this.writer.getPos()-this.segmentDataOffset;this.writer.seek(this.ebmlWriter.offsets.get(this.segment)+4),this.ebmlWriter.writeVarInt(t,6),this.segmentDuration.data=new Pr(this.duration),this.writer.seek(this.ebmlWriter.offsets.get(this.segmentDuration)),this.ebmlWriter.writeEBML(this.segmentDuration),n(this.seekHead),this.writer.seek(this.ebmlWriter.offsets.get(this.seekHead)),this.maybeCreateSeekHead(!0),this.ebmlWriter.writeEBML(this.seekHead),this.writer.seek(e)}e()}}
|
|
100
253
|
/*!
|
|
101
254
|
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
102
255
|
*
|
|
103
256
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
104
257
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
105
258
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
106
|
-
*/class
|
|
259
|
+
*/class Fn{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>he.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>pe.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>ge.includes(e))}_codecUnsupportedHint(e){return""}}class Mn extends Fn{constructor(e={}){if(!e||"object"!=typeof e)throw new TypeError("options must be an object.");if(void 0!==e.fastStart&&![!1,"in-memory","reserve","fragmented"].includes(e.fastStart))throw new TypeError("options.fastStart, when provided, must be false, 'in-memory', 'reserve', or 'fragmented'.");if(void 0!==e.minimumFragmentDuration&&(!Number.isFinite(e.minimumFragmentDuration)||e.minimumFragmentDuration<0))throw new TypeError("options.minimumFragmentDuration, when provided, must be a non-negative number.");if(void 0!==e.onFtyp&&"function"!=typeof e.onFtyp)throw new TypeError("options.onFtyp, when provided, must be a function.");if(void 0!==e.onMoov&&"function"!=typeof e.onMoov)throw new TypeError("options.onMoov, when provided, must be a function.");if(void 0!==e.onMdat&&"function"!=typeof e.onMdat)throw new TypeError("options.onMdat, when provided, must be a function.");if(void 0!==e.onMoof&&"function"!=typeof e.onMoof)throw new TypeError("options.onMoof, when provided, must be a function.");if(void 0!==e.metadataFormat&&!["mdir","mdta","udta","auto"].includes(e.metadataFormat))throw new TypeError("options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.");super(),this._options=e}getSupportedTrackCounts(){return{video:{min:0,max:1/0},audio:{min:0,max:1/0},subtitle:{min:0,max:1/0},total:{min:1,max:2**32-1}}}get supportsVideoRotationMetadata(){return!0}_createMuxer(e){return new Dn(e,this)}}class Rn extends Mn{constructor(e){super(e)}get _name(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...he,...fe,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...ge]}_codecUnsupportedHint(e){return(new zn).getSupportedCodecs().includes(e)?" Switching to MOV will grant support for this codec.":""}}class zn extends Mn{constructor(e){super(e)}get _name(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...he,...pe]}_codecUnsupportedHint(e){return(new Rn).getSupportedCodecs().includes(e)?" Switching to MP4 will grant support for this codec.":""}}class On extends Fn{constructor(e={}){if(!e||"object"!=typeof e)throw new TypeError("options must be an object.");if(void 0!==e.appendOnly&&"boolean"!=typeof e.appendOnly)throw new TypeError("options.appendOnly, when provided, must be a boolean.");if(void 0!==e.minimumClusterDuration&&(!Number.isFinite(e.minimumClusterDuration)||e.minimumClusterDuration<0))throw new TypeError("options.minimumClusterDuration, when provided, must be a non-negative number.");if(void 0!==e.onEbmlHeader&&"function"!=typeof e.onEbmlHeader)throw new TypeError("options.onEbmlHeader, when provided, must be a function.");if(void 0!==e.onSegmentHeader&&"function"!=typeof e.onSegmentHeader)throw new TypeError("options.onHeader, when provided, must be a function.");if(void 0!==e.onCluster&&"function"!=typeof e.onCluster)throw new TypeError("options.onCluster, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new _n(e,this)}get _name(){return"Matroska"}getSupportedTrackCounts(){return{video:{min:0,max:1/0},audio:{min:0,max:1/0},subtitle:{min:0,max:1/0},total:{min:1,max:127}}}get fileExtension(){return".mkv"}get mimeType(){return"video/x-matroska"}getSupportedCodecs(){return[...he,...fe,...me.filter(e=>!["pcm-s8","pcm-f32be","pcm-f64be","ulaw","alaw"].includes(e)),...ge]}get supportsVideoRotationMetadata(){return!1}}class Nn extends On{constructor(e){super(e)}getSupportedCodecs(){return[...he.filter(e=>["vp8","vp9","av1"].includes(e)),...pe.filter(e=>["opus","vorbis"].includes(e)),...ge]}get _name(){return"WebM"}get fileExtension(){return".webm"}get mimeType(){return"video/webm"}_codecUnsupportedHint(e){return(new On).getSupportedCodecs().includes(e)?" Switching to MKV will grant support for this codec.":""}}
|
|
107
260
|
/*!
|
|
108
261
|
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
109
262
|
*
|
|
110
263
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
111
264
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
112
265
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
113
|
-
*/class
|
|
266
|
+
*/class Ln{constructor(){this._connectedTrack=null,this._closingPromise=null,this._closed=!1,this._timestampOffset=0}_ensureValidAdd(){if(!this._connectedTrack)throw new Error("Source is not connected to an output track.");if("canceled"===this._connectedTrack.output.state)throw new Error("Output has been canceled.");if("finalizing"===this._connectedTrack.output.state||"finalized"===this._connectedTrack.output.state)throw new Error("Output has been finalized.");if("pending"===this._connectedTrack.output.state)throw new Error("Output has not started.");if(this._closed)throw new Error("Source is closed.")}async _start(){}async _flushAndClose(e){}close(){if(this._closingPromise)return;const e=this._connectedTrack;if(!e)throw new Error("Cannot call close without connecting the source to an output track.");if("pending"===e.output.state)throw new Error("Cannot call close before output has been started.");this._closingPromise=(async()=>{await this._flushAndClose(!1),this._closed=!0,"finalizing"!==e.output.state&&"finalized"!==e.output.state&&e.output._muxer.onTrackClose(e)})()}async _flushOrWaitForOngoingClose(e){return this._closingPromise?this._closingPromise:this._flushAndClose(e)}}class Un extends Ln{constructor(e){if(super(),this._connectedTrack=null,!he.includes(e))throw new TypeError(`Invalid video codec '${e}'. Must be one of: ${he.join(", ")}.`);this._codec=e}}class Vn extends Un{constructor(e){super(e)}add(e,t){if(!(e instanceof yt))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be added.");if(void 0!==t&&(!t||"object"!=typeof t))throw new TypeError("meta, when provided, must be an object.");return this._ensureValidAdd(),this._connectedTrack.output._muxer.addEncodedVideoPacket(this._connectedTrack,e,t)}}class Wn extends Ln{constructor(e){if(super(),this._connectedTrack=null,!pe.includes(e))throw new TypeError(`Invalid audio codec '${e}'. Must be one of: ${pe.join(", ")}.`);this._codec=e}}class Hn extends Wn{constructor(e){super(e)}add(e,t){if(!(e instanceof yt))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be added.");if(void 0!==t&&(!t||"object"!=typeof t))throw new TypeError("meta, when provided, must be an object.");return this._ensureValidAdd(),this._connectedTrack.output._muxer.addEncodedAudioPacket(this._connectedTrack,e,t)}}class qn extends Ln{constructor(e){if(super(),this._connectedTrack=null,!ge.includes(e))throw new TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${ge.join(", ")}.`);this._codec=e}}
|
|
114
267
|
/*!
|
|
115
268
|
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
116
269
|
*
|
|
117
270
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
118
271
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
119
272
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
120
|
-
*/const _i=["video","audio","subtitle"],Bi=e=>{if(!e||"object"!=typeof e)throw new TypeError("metadata must be an object.");if(void 0!==e.languageCode&&(t=e.languageCode,!b.test(t)))throw new TypeError("metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.");var t;if(void 0!==e.name&&"string"!=typeof e.name)throw new TypeError("metadata.name, when provided, must be a string.");if(void 0!==e.disposition&&(e=>{if(!e||"object"!=typeof e)throw new TypeError("disposition must be an object.");if(void 0!==e.default&&"boolean"!=typeof e.default)throw new TypeError("disposition.default must be a boolean.");if(void 0!==e.forced&&"boolean"!=typeof e.forced)throw new TypeError("disposition.forced must be a boolean.");if(void 0!==e.original&&"boolean"!=typeof e.original)throw new TypeError("disposition.original must be a boolean.");if(void 0!==e.commentary&&"boolean"!=typeof e.commentary)throw new TypeError("disposition.commentary must be a boolean.");if(void 0!==e.hearingImpaired&&"boolean"!=typeof e.hearingImpaired)throw new TypeError("disposition.hearingImpaired must be a boolean.");if(void 0!==e.visuallyImpaired&&"boolean"!=typeof e.visuallyImpaired)throw new TypeError("disposition.visuallyImpaired must be a boolean.")})(e.disposition),void 0!==e.maximumPacketCount&&(!Number.isInteger(e.maximumPacketCount)||e.maximumPacketCount<0))throw new TypeError("metadata.maximumPacketCount, when provided, must be a non-negative integer.")};class Ai{constructor(e){if(this.state="pending",this._tracks=[],this._startPromise=null,this._cancelPromise=null,this._finalizePromise=null,this._mutex=new g,this._metadataTags={},!e||"object"!=typeof e)throw new TypeError("options must be an object.");if(!(e.format instanceof pi))throw new TypeError("options.format must be an OutputFormat.");if(!(e.target instanceof si))throw new TypeError("options.target must be a Target.");if(e.target._output)throw new Error("Target is already used for another output.");e.target._output=this,this.format=e.format,this.target=e.target,this._writer=e.target._createWriter(),this._muxer=e.format._createMuxer(this)}addVideoTrack(e,t={}){if(!(e instanceof Ti))throw new TypeError("source must be a VideoSource.");if(Bi(t),void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError(`Invalid video rotation: ${t.rotation}. Has to be 0, 90, 180 or 270.`);if(!this.format.supportsVideoRotationMetadata&&t.rotation)throw new Error(`${this.format._name} does not support video rotation metadata.`);if(void 0!==t.frameRate&&(!Number.isFinite(t.frameRate)||t.frameRate<=0))throw new TypeError(`Invalid video frame rate: ${t.frameRate}. Must be a positive number.`);this._addTrack("video",e,t)}addAudioTrack(e,t={}){if(!(e instanceof vi))throw new TypeError("source must be an AudioSource.");Bi(t),this._addTrack("audio",e,t)}addSubtitleTrack(e,t={}){if(!(e instanceof Ei))throw new TypeError("source must be a SubtitleSource.");Bi(t),this._addTrack("subtitle",e,t)}setMetadataTags(e){if((e=>{if(!e||"object"!=typeof e)throw new TypeError("tags must be an object.");if(void 0!==e.title&&"string"!=typeof e.title)throw new TypeError("tags.title, when provided, must be a string.");if(void 0!==e.description&&"string"!=typeof e.description)throw new TypeError("tags.description, when provided, must be a string.");if(void 0!==e.artist&&"string"!=typeof e.artist)throw new TypeError("tags.artist, when provided, must be a string.");if(void 0!==e.album&&"string"!=typeof e.album)throw new TypeError("tags.album, when provided, must be a string.");if(void 0!==e.albumArtist&&"string"!=typeof e.albumArtist)throw new TypeError("tags.albumArtist, when provided, must be a string.");if(void 0!==e.trackNumber&&(!Number.isInteger(e.trackNumber)||e.trackNumber<=0))throw new TypeError("tags.trackNumber, when provided, must be a positive integer.");if(void 0!==e.tracksTotal&&(!Number.isInteger(e.tracksTotal)||e.tracksTotal<=0))throw new TypeError("tags.tracksTotal, when provided, must be a positive integer.");if(void 0!==e.discNumber&&(!Number.isInteger(e.discNumber)||e.discNumber<=0))throw new TypeError("tags.discNumber, when provided, must be a positive integer.");if(void 0!==e.discsTotal&&(!Number.isInteger(e.discsTotal)||e.discsTotal<=0))throw new TypeError("tags.discsTotal, when provided, must be a positive integer.");if(void 0!==e.genre&&"string"!=typeof e.genre)throw new TypeError("tags.genre, when provided, must be a string.");if(void 0!==e.date&&(!(e.date instanceof Date)||Number.isNaN(e.date.getTime())))throw new TypeError("tags.date, when provided, must be a valid Date.");if(void 0!==e.lyrics&&"string"!=typeof e.lyrics)throw new TypeError("tags.lyrics, when provided, must be a string.");if(void 0!==e.images){if(!Array.isArray(e.images))throw new TypeError("tags.images, when provided, must be an array.");for(const t of e.images){if(!t||"object"!=typeof t)throw new TypeError("Each image in tags.images must be an object.");if(!(t.data instanceof Uint8Array))throw new TypeError("Each image.data must be a Uint8Array.");if("string"!=typeof t.mimeType)throw new TypeError("Each image.mimeType must be a string.");if(!["coverFront","coverBack","unknown"].includes(t.kind))throw new TypeError("Each image.kind must be 'coverFront', 'coverBack', or 'unknown'.")}}if(void 0!==e.comment&&"string"!=typeof e.comment)throw new TypeError("tags.comment, when provided, must be a string.");if(void 0!==e.raw){if(!e.raw||"object"!=typeof e.raw)throw new TypeError("tags.raw, when provided, must be an object.");for(const t of Object.values(e.raw))if(!(null===t||"string"==typeof t||t instanceof Uint8Array||t instanceof E||t instanceof _))throw new TypeError("Each value in tags.raw must be a string, Uint8Array, RichImageData, AttachedFile, or null.")}})(e),"pending"!==this.state)throw new Error("Cannot set metadata tags after output has been started or canceled.");this._metadataTags=e}_addTrack(e,t,i){if("pending"!==this.state)throw new Error("Cannot add track after output has been started or canceled.");if(t._connectedTrack)throw new Error("Source is already used for a track.");const r=this.format.getSupportedTrackCounts(),a=this._tracks.reduce((t,i)=>t+(i.type===e?1:0),0),s=r[e].max;if(a===s)throw new Error(0===s?`${this.format._name} does not support ${e} tracks.`:`${this.format._name} does not support more than ${s} ${e} track`+(1===s?"":"s")+".");const o=r.total.max;if(this._tracks.length===o)throw new Error(`${this.format._name} does not support more than ${o} tracks`+(1===o?"":"s")+" in total.");const n={id:this._tracks.length+1,output:this,type:e,source:t,metadata:i};if("video"===n.type){const e=this.format.getSupportedVideoCodecs();if(0===e.length)throw new Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(n.source._codec));if(!e.includes(n.source._codec))throw new Error(`Codec '${n.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${e.map(e=>`'${e}'`).join(", ")}.`+this.format._codecUnsupportedHint(n.source._codec))}else if("audio"===n.type){const e=this.format.getSupportedAudioCodecs();if(0===e.length)throw new Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(n.source._codec));if(!e.includes(n.source._codec))throw new Error(`Codec '${n.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${e.map(e=>`'${e}'`).join(", ")}.`+this.format._codecUnsupportedHint(n.source._codec))}else if("subtitle"===n.type){const e=this.format.getSupportedSubtitleCodecs();if(0===e.length)throw new Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(n.source._codec));if(!e.includes(n.source._codec))throw new Error(`Codec '${n.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${e.map(e=>`'${e}'`).join(", ")}.`+this.format._codecUnsupportedHint(n.source._codec))}this._tracks.push(n),t._connectedTrack=n}async start(){const e=this.format.getSupportedTrackCounts();for(const t of _i){const i=this._tracks.reduce((e,i)=>e+(i.type===t?1:0),0),r=e[t].min;if(i<r)throw new Error(r===e[t].max?`${this.format._name} requires exactly ${r} ${t} track${1===r?"":"s"}.`:`${this.format._name} requires at least ${r} ${t} track${1===r?"":"s"}.`)}const t=e.total.min;if(this._tracks.length<t)throw new Error(t===e.total.max?`${this.format._name} requires exactly ${t} track`+(1===t?"":"s")+".":`${this.format._name} requires at least ${t} track`+(1===t?"":"s")+".");if("canceled"===this.state)throw new Error("Output has been canceled.");return this._startPromise?(console.warn("Output has already been started."),this._startPromise):this._startPromise=(async()=>{this.state="started",this._writer.start();const e=await this._mutex.acquire();await this._muxer.start();const t=this._tracks.map(e=>e.source._start());await Promise.all(t),e()})()}getMimeType(){return this._muxer.getMimeType()}async cancel(){return this._cancelPromise?(console.warn("Output has already been canceled."),this._cancelPromise):"finalizing"!==this.state&&"finalized"!==this.state?this._cancelPromise=(async()=>{this.state="canceled";const e=await this._mutex.acquire(),t=this._tracks.map(e=>e.source._flushOrWaitForOngoingClose(!0));await Promise.all(t),await this._writer.close(),e()})():void console.warn("Output has already been finalized.")}async finalize(){if("pending"===this.state)throw new Error("Cannot finalize before starting.");if("canceled"===this.state)throw new Error("Cannot finalize after canceling.");return this._finalizePromise?(console.warn("Output has already been finalized."),this._finalizePromise):this._finalizePromise=(async()=>{this.state="finalizing";const e=await this._mutex.acquire(),t=this._tracks.map(e=>e.source._flushOrWaitForOngoingClose(!1));await Promise.all(t),await this._muxer.finalize(),await this._writer.flush(),await this._writer.finalize(),this.state="finalized",e()})()}}var Mi,xi,Pi,Ii,Di,Vi,Ui;e.EncoderType=void 0,(Mi=e.EncoderType||(e.EncoderType={}))[Mi.INIT=0]="INIT",Mi[Mi.FRAME=1]="FRAME",Mi[Mi.END=2]="END",e.EncoderEvent=void 0,(xi=e.EncoderEvent||(e.EncoderEvent={}))[xi.PROGRESS=0]="PROGRESS",xi[xi.FINISH=1]="FINISH",xi[xi.ERROR=2]="ERROR";var Fi,Wi=!1,Ni=!1,Oi=[],Li=0,Ri=0,zi=function(r){return t(void 0,void 0,void 0,function(){var t,a,s,o,n,c,d,u,l,h,m,p,f,g,w,k,y,b,T,C,v,S,E,_,B,A,M,x,P,I,D,V,U,F,W,N,O;return i(this,function(i){switch(i.label){case 0:if(t=r.data,a=t.type,s=t.isWorker,o=function(t){var i={type:e.EncoderEvent.ERROR,error:t};return s&&self.postMessage(i),{data:i}},n=new Promise(function(e){Fi=e}),a!==e.EncoderType.INIT)return[3,2];if(Pi&&(Pi.close(),Pi=void 0),Ii&&(Ii.close(),Ii=void 0),c=function(){if(Wi&&Ni){var t={type:e.EncoderEvent.PROGRESS};s&&self.postMessage(t),Fi({data:t})}},d=null===(N=r.data.videoEncoderConfig)||void 0===N?void 0:N.codec,u=void 0,u=/^vp/.test(d)?new yi:new gi,Di=new Ai({format:u,target:new oi}),/^vp8/.test(d)?Vi=new Ci("vp8"):/^vp09\./.test(d)?Vi=new Ci("vp9"):/^av01\./.test(d)?Vi=new Ci("av1"):/^hev1\./.test(d)||/^hvc1\./.test(d)?Vi=new Ci("hevc"):(/^avc1\./.test(d)||/^avc3\./.test(d))&&(Vi=new Ci("avc")),Vi&&(Di.addVideoTrack(Vi),Pi=new VideoEncoder({output:function(e,t){var i=de.fromEncodedChunk(e);Vi.add(i,t),Wi=!0,c()},error:function(e){o(e.message)}}),Pi.configure(r.data.videoEncoderConfig)),l=null===(O=r.data.audioEncoderConfig)||void 0===O?void 0:O.codec,r.data.mute?Ui=void 0:/^mp3/.test(l)?Ui=new Si("mp3"):/^flac/.test(l)?Ui=new Si("flac"):/^opus/.test(l)?Ui=new Si("opus"):/^vorbis/.test(l)?Ui=new Si("vorbis"):/^pcm-/.test(l)?Ui=new Si(l):/^mp4a\./.test(l)?Ui=new Si("aac"):/^ulaw/.test(l)?Ui=new Si("ulaw"):/^alaw/.test(l)&&(Ui=new Si("alaw")),Ui){for(Di.addAudioTrack(Ui),Ii=new AudioEncoder({output:function(e,t){var i=de.fromEncodedChunk(e);Ui.add(i,t),Ni=!0,c()},error:function(e){o(e.message)}}),Ii.configure(r.data.audioEncoderConfig),Oi.splice(0),h=r.data.audioEncoderConfig.sampleRate*Math.ceil(.001*r.data.duration),I=0;I<r.data.audioEncoderConfig.numberOfChannels;I++)Oi.push(new Float32Array(h));Li=0,Ri=0}return[4,Di.start()];case 1:return i.sent(),[3,8];case 2:if(a!==e.EncoderType.FRAME)return[3,3];if(Wi=!1,Ni=!1,m=r.data.videoFrame,Pi&&"configured"===Pi.state&&m&&Pi.encode(m),null==m||m.close(),p=r.data.audioList,f=r.data.audioEncoderConfig,g=f.numberOfChannels,w=f.sampleRate,Ii&&"configured"===Ii.state){if(p.length)for(I=0,k=p.length;I<k;I++)for(y=p[I],b=y.audioChunk,T=y.volume,C=Math.round(.001*b.timestamp*w),v=b.numberOfFrames,S=0;S<g;S++)for(E=Oi[S],_=b.channels[S],B=0;B<v;B++)A=E[M=C+B]+_[B]*T,E[M]=Math.max(-1,Math.min(1,A));if(r.data.timestamp&&(M=Math.round(.001*r.data.timestamp*w))>Li){for(x=M-Li,P=new Float32Array(x*Oi.length),I=0;I<Oi.length;I++)D=Oi[I],V=D.subarray(Li,M),P.set(V,I*x);U=new AudioData({format:"f32-planar",sampleRate:w,numberOfFrames:x,numberOfChannels:g,timestamp:Ri,data:P}),Li=M,Ri=r.data.timestamp,Ii.encode(U)}Ni=!0}else r.data.mute&&(Ni=!0);return[2,n];case 3:return a!==e.EncoderType.END?[3,8]:Pi&&Di?[4,Pi.flush()]:[2];case 4:return i.sent(),Pi.close(),Pi=void 0,"configured"!==(null==Ii?void 0:Ii.state)?[3,6]:[4,Ii.flush()];case 5:i.sent(),Ii.close(),Ii=void 0,i.label=6;case 6:return[4,Di.finalize()];case 7:if(i.sent(),F=Di.target.buffer,Di=void 0,W={type:e.EncoderEvent.FINISH,buffer:F},!s)return[2,{data:W}];self.postMessage(W,[F]),i.label=8;case 8:return[2]}})})};self.onmessage=zi,e.onMessage=zi});
|
|
273
|
+
*/const jn=["video","audio","subtitle"],$n=e=>{if(!e||"object"!=typeof e)throw new TypeError("metadata must be an object.");if(void 0!==e.languageCode&&!H(e.languageCode))throw new TypeError("metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.");if(void 0!==e.name&&"string"!=typeof e.name)throw new TypeError("metadata.name, when provided, must be a string.");if(void 0!==e.disposition&&(e=>{if(!e||"object"!=typeof e)throw new TypeError("disposition must be an object.");if(void 0!==e.default&&"boolean"!=typeof e.default)throw new TypeError("disposition.default must be a boolean.");if(void 0!==e.forced&&"boolean"!=typeof e.forced)throw new TypeError("disposition.forced must be a boolean.");if(void 0!==e.original&&"boolean"!=typeof e.original)throw new TypeError("disposition.original must be a boolean.");if(void 0!==e.commentary&&"boolean"!=typeof e.commentary)throw new TypeError("disposition.commentary must be a boolean.");if(void 0!==e.hearingImpaired&&"boolean"!=typeof e.hearingImpaired)throw new TypeError("disposition.hearingImpaired must be a boolean.");if(void 0!==e.visuallyImpaired&&"boolean"!=typeof e.visuallyImpaired)throw new TypeError("disposition.visuallyImpaired must be a boolean.")})(e.disposition),void 0!==e.maximumPacketCount&&(!Number.isInteger(e.maximumPacketCount)||e.maximumPacketCount<0))throw new TypeError("metadata.maximumPacketCount, when provided, must be a non-negative integer.")};class Qn{constructor(e){if(this.state="pending",this._tracks=[],this._startPromise=null,this._cancelPromise=null,this._finalizePromise=null,this._mutex=new I,this._metadataTags={},!e||"object"!=typeof e)throw new TypeError("options must be an object.");if(!(e.format instanceof Fn))throw new TypeError("options.format must be an OutputFormat.");if(!(e.target instanceof vn))throw new TypeError("options.target must be a Target.");if(e.target._output)throw new Error("Target is already used for another output.");e.target._output=this,this.format=e.format,this.target=e.target,this._writer=e.target._createWriter(),this._muxer=e.format._createMuxer(this)}addVideoTrack(e,t={}){if(!(e instanceof Un))throw new TypeError("source must be a VideoSource.");if($n(t),void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError(`Invalid video rotation: ${t.rotation}. Has to be 0, 90, 180 or 270.`);if(!this.format.supportsVideoRotationMetadata&&t.rotation)throw new Error(`${this.format._name} does not support video rotation metadata.`);if(void 0!==t.frameRate&&(!Number.isFinite(t.frameRate)||t.frameRate<=0))throw new TypeError(`Invalid video frame rate: ${t.frameRate}. Must be a positive number.`);this._addTrack("video",e,t)}addAudioTrack(e,t={}){if(!(e instanceof Wn))throw new TypeError("source must be an AudioSource.");$n(t),this._addTrack("audio",e,t)}addSubtitleTrack(e,t={}){if(!(e instanceof qn))throw new TypeError("source must be a SubtitleSource.");$n(t),this._addTrack("subtitle",e,t)}setMetadataTags(e){if((e=>{if(!e||"object"!=typeof e)throw new TypeError("tags must be an object.");if(void 0!==e.title&&"string"!=typeof e.title)throw new TypeError("tags.title, when provided, must be a string.");if(void 0!==e.description&&"string"!=typeof e.description)throw new TypeError("tags.description, when provided, must be a string.");if(void 0!==e.artist&&"string"!=typeof e.artist)throw new TypeError("tags.artist, when provided, must be a string.");if(void 0!==e.album&&"string"!=typeof e.album)throw new TypeError("tags.album, when provided, must be a string.");if(void 0!==e.albumArtist&&"string"!=typeof e.albumArtist)throw new TypeError("tags.albumArtist, when provided, must be a string.");if(void 0!==e.trackNumber&&(!Number.isInteger(e.trackNumber)||e.trackNumber<=0))throw new TypeError("tags.trackNumber, when provided, must be a positive integer.");if(void 0!==e.tracksTotal&&(!Number.isInteger(e.tracksTotal)||e.tracksTotal<=0))throw new TypeError("tags.tracksTotal, when provided, must be a positive integer.");if(void 0!==e.discNumber&&(!Number.isInteger(e.discNumber)||e.discNumber<=0))throw new TypeError("tags.discNumber, when provided, must be a positive integer.");if(void 0!==e.discsTotal&&(!Number.isInteger(e.discsTotal)||e.discsTotal<=0))throw new TypeError("tags.discsTotal, when provided, must be a positive integer.");if(void 0!==e.genre&&"string"!=typeof e.genre)throw new TypeError("tags.genre, when provided, must be a string.");if(void 0!==e.date&&(!(e.date instanceof Date)||Number.isNaN(e.date.getTime())))throw new TypeError("tags.date, when provided, must be a valid Date.");if(void 0!==e.lyrics&&"string"!=typeof e.lyrics)throw new TypeError("tags.lyrics, when provided, must be a string.");if(void 0!==e.images){if(!Array.isArray(e.images))throw new TypeError("tags.images, when provided, must be an array.");for(const t of e.images){if(!t||"object"!=typeof t)throw new TypeError("Each image in tags.images must be an object.");if(!(t.data instanceof Uint8Array))throw new TypeError("Each image.data must be a Uint8Array.");if("string"!=typeof t.mimeType)throw new TypeError("Each image.mimeType must be a string.");if(!["coverFront","coverBack","unknown"].includes(t.kind))throw new TypeError("Each image.kind must be 'coverFront', 'coverBack', or 'unknown'.")}}if(void 0!==e.comment&&"string"!=typeof e.comment)throw new TypeError("tags.comment, when provided, must be a string.");if(void 0!==e.raw){if(!e.raw||"object"!=typeof e.raw)throw new TypeError("tags.raw, when provided, must be an object.");for(const t of Object.values(e.raw))if(!(null===t||"string"==typeof t||t instanceof Uint8Array||t instanceof de||t instanceof ue))throw new TypeError("Each value in tags.raw must be a string, Uint8Array, RichImageData, AttachedFile, or null.")}})(e),"pending"!==this.state)throw new Error("Cannot set metadata tags after output has been started or canceled.");this._metadataTags=e}_addTrack(e,t,r){if("pending"!==this.state)throw new Error("Cannot add track after output has been started or canceled.");if(t._connectedTrack)throw new Error("Source is already used for a track.");const a=this.format.getSupportedTrackCounts(),i=this._tracks.reduce((t,r)=>t+(r.type===e?1:0),0),s=a[e].max;if(i===s)throw new Error(0===s?`${this.format._name} does not support ${e} tracks.`:`${this.format._name} does not support more than ${s} ${e} track`+(1===s?"":"s")+".");const n=a.total.max;if(this._tracks.length===n)throw new Error(`${this.format._name} does not support more than ${n} tracks`+(1===n?"":"s")+" in total.");const o={id:this._tracks.length+1,output:this,type:e,source:t,metadata:r};if("video"===o.type){const e=this.format.getSupportedVideoCodecs();if(0===e.length)throw new Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(o.source._codec));if(!e.includes(o.source._codec))throw new Error(`Codec '${o.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${e.map(e=>`'${e}'`).join(", ")}.`+this.format._codecUnsupportedHint(o.source._codec))}else if("audio"===o.type){const e=this.format.getSupportedAudioCodecs();if(0===e.length)throw new Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(o.source._codec));if(!e.includes(o.source._codec))throw new Error(`Codec '${o.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${e.map(e=>`'${e}'`).join(", ")}.`+this.format._codecUnsupportedHint(o.source._codec))}else if("subtitle"===o.type){const e=this.format.getSupportedSubtitleCodecs();if(0===e.length)throw new Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(o.source._codec));if(!e.includes(o.source._codec))throw new Error(`Codec '${o.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${e.map(e=>`'${e}'`).join(", ")}.`+this.format._codecUnsupportedHint(o.source._codec))}this._tracks.push(o),t._connectedTrack=o}async start(){const e=this.format.getSupportedTrackCounts();for(const t of jn){const r=this._tracks.reduce((e,r)=>e+(r.type===t?1:0),0),a=e[t].min;if(r<a)throw new Error(a===e[t].max?`${this.format._name} requires exactly ${a} ${t} track${1===a?"":"s"}.`:`${this.format._name} requires at least ${a} ${t} track${1===a?"":"s"}.`)}const t=e.total.min;if(this._tracks.length<t)throw new Error(t===e.total.max?`${this.format._name} requires exactly ${t} track`+(1===t?"":"s")+".":`${this.format._name} requires at least ${t} track`+(1===t?"":"s")+".");if("canceled"===this.state)throw new Error("Output has been canceled.");return this._startPromise?(console.warn("Output has already been started."),this._startPromise):this._startPromise=(async()=>{this.state="started",this._writer.start();const e=await this._mutex.acquire();await this._muxer.start();const t=this._tracks.map(e=>e.source._start());await Promise.all(t),e()})()}getMimeType(){return this._muxer.getMimeType()}async cancel(){return this._cancelPromise?(console.warn("Output has already been canceled."),this._cancelPromise):"finalizing"!==this.state&&"finalized"!==this.state?this._cancelPromise=(async()=>{this.state="canceled";const e=await this._mutex.acquire(),t=this._tracks.map(e=>e.source._flushOrWaitForOngoingClose(!0));await Promise.all(t),await this._writer.close(),e()})():void console.warn("Output has already been finalized.")}async finalize(){if("pending"===this.state)throw new Error("Cannot finalize before starting.");if("canceled"===this.state)throw new Error("Cannot finalize after canceling.");return this._finalizePromise?(console.warn("Output has already been finalized."),this._finalizePromise):this._finalizePromise=(async()=>{this.state="finalizing";const e=await this._mutex.acquire(),t=this._tracks.map(e=>e.source._flushOrWaitForOngoingClose(!1));await Promise.all(t),await this._muxer.finalize(),await this._writer.flush(),await this._writer.finalize(),this.state="finalized",e()})()}}var Kn="VideoRange";function Gn(){return r(this,void 0,void 0,function(){return a(this,function(e){return[2,new Promise(function(e,t){var r=indexedDB.open("VideoEditorDB",1);r.onupgradeneeded=function(e){var t=e.target.result;t.objectStoreNames.contains(Kn)||t.createObjectStore(Kn,{keyPath:"id"})},r.onsuccess=function(){e(r.result)},r.onerror=function(){t("IndexedDB Error: ".concat(r.error))}})]})})}function Xn(e){return new Promise(function(t,r){e.onsuccess=function(){return t(e.result)},e.onerror=function(){return r(e.error)}})}function Yn(e){return new Promise(function(t,r){e.oncomplete=function(){return t(void 0)},e.onerror=function(){return r(e.error)}})}function Jn(e,t){return r(this,void 0,void 0,function(){var r;return a(this,function(a){switch(a.label){case 0:return t?[3,2]:[4,Gn()];case 1:t=a.sent(),a.label=2;case 2:return r=t.transaction(Kn,"readonly"),[2,Xn(r.objectStore(Kn).get(e))]}})})}function Zn(e,t){return r(this,void 0,void 0,function(){var r;return a(this,function(a){switch(a.label){case 0:return t?[3,2]:[4,Gn()];case 1:t=a.sent(),a.label=2;case 2:return r=t.transaction(Kn,"readwrite"),[4,Xn(r.objectStore(Kn).put(e))];case 3:return a.sent(),[4,Yn(r)];case 4:return a.sent(),[2]}})})}var eo,to,ro,ao=4194304;function io(e,i,s,n,o){return r(this,void 0,void 0,function(){var c,d,u,l,h,m,f,p,g,k,b,w;return a(this,function(T){switch(T.label){case 0:return(null==o?void 0:o.indexedDB)?[3,4]:[4,fetch(e,t(t({},o),{cache:"force-cache",headers:{"Cache-Control":"max-age=31536000",Range:"bytes=".concat(i,"-").concat(s)}}))];case 1:return 206!==(c=T.sent()).status?[3,3]:[4,c.arrayBuffer()];case 2:return[2,{status:206,arrayBuffer:T.sent()}];case 3:return[2,{status:c.status}];case 4:for(d=[],u=ao*Math.floor(i/ao),l=u;u<=s;)h=Math.min(n-1,u+ao-1),d.push([u,h]),u=h+1;return[4,Gn()];case 5:return m=T.sent(),[4,Promise.all(d.map(function(i){return function(e,i,s,n,o){return r(this,void 0,void 0,function(){var r,c,d,u;return a(this,function(a){switch(a.label){case 0:return[4,Jn(r=e+":"+i+"-"+s,n)];case 1:return(c=a.sent())?[2,{status:206,arrayBuffer:c.arrayBuffer}]:[4,fetch(e,t(t({},o),{cache:"force-cache",headers:{"Cache-Control":"max-age=31536000",Range:"bytes=".concat(i,"-").concat(s)}}))];case 2:return 206!==(d=a.sent()).status?[3,5]:[4,d.arrayBuffer()];case 3:return u=a.sent(),[4,Zn({id:r,arrayBuffer:u})];case 4:return a.sent(),[2,{status:206,arrayBuffer:u}];case 5:return[2,{status:d.status}]}})})}(e,i[0],i[1],m,o)}))];case 6:for(f=T.sent(),p=new Uint8Array(d.length*ao*8),g=0,k=f.length;g<k;g++){if(206!==(b=f[g]).status)return[2,{status:b.status}];w=new Uint8Array(b.arrayBuffer),p.set(w,g*ao)}return[2,{status:206,arrayBuffer:p.buffer.slice(i-l,s-l+1)}]}})})}function so(e){return r(this,void 0,void 0,function(){return a(this,function(t){return[2,new Promise(function(t){return setTimeout(t,e)})]})})}!function(e){e[e.META=0]="META",e[e.DECODE=1]="DECODE",e[e.RELEASE=2]="RELEASE"}(eo||(eo={})),function(e){e.META="meta",e.ERROR="error",e.DECODED="decoded"}(to||(to={})),function(e){e[e.NONE=0]="NONE",e[e.DECODING=1]="DECODING",e[e.DECODED=2]="DECODED",e[e.DECODED_FRAME=3]="DECODED_FRAME",e[e.ERROR=4]="ERROR"}(ro||(ro={}));var no={};self.onmessage=function(e){return r(void 0,void 0,void 0,function(){var t,i,n,o,c,d,u,l,h,m,f,p,g,k,b,w,T,y,S,C,v,P,I,x,E,D,B,A,_,F,M,R,z,O,N,L,U,V,W,H,q,j,$,Q,K,G,X,Y,J,Z,ee,te,re,ae,ie,se,ne,oe,ce,de,ue,le,he,me,fe,pe,ge,ke,be,we,Te,ye,Se,Ce,ve,Pe,Ie,xe,Ee,De,Be;return a(this,function(Ae){switch(Ae.label){case 0:return t=e.data,i=t.url,n=t.id,o=t.type,c=t.isWorker,d=function(e){var t={url:i,type:to.ERROR,data:e};return c&&self.postMessage(t),{data:t}},no[i]||(no[i]={gopList:[]}),u=no[i],o!==eo.META?[3,38]:[4,fetch(i,{method:"HEAD"})];case 1:if(l=Ae.sent(),!(h=l.headers.get("content-length"))||200!==l.status&&304!==l.status)return[2,d("Unknown content-length")];m=parseInt(h),f={duration:0,fileSize:m},p=void 0,p=e.data.preloadAll?new hi(i):new mi({read:function(t,s){return r(void 0,void 0,void 0,function(){var r;return a(this,function(a){switch(a.label){case 0:return[4,io(i,t,s-1,m,{indexedDB:e.data.indexedDB})];case 1:if(!(r=a.sent().arrayBuffer))throw new Error("Missing buffer in range: "+t+"-"+(s-1));return[2,new Uint8Array(r)]}})})},getSize:function(){return r(void 0,void 0,void 0,function(){return a(this,function(e){return[2,m]})})},prefetchProfile:"network"}),g=new gi({formats:ci,source:p}),Ae.label=2;case 2:return Ae.trys.push([2,4,,5]),[4,g.computeDuration()];case 3:return k=Ae.sent(),f.duration=1e3*k,[3,5];case 4:return b=Ae.sent(),[2,d(b.message)];case 5:return[4,g.getPrimaryVideoTrack()];case 6:return(w=Ae.sent())?(u.videoTrack=w,[4,w.computeDuration()]):[3,21];case 7:ne=Ae.sent(),G=new $t(w),Ae.label=8;case 8:Ae.trys.push([8,13,14,19]),T=!0,y=s(G.packets(void 0,void 0,{metadataOnly:!0})),Ae.label=9;case 9:return[4,y.next()];case 10:if(S=Ae.sent(),pe=S.done)return[3,12];if(be=S.value,T=!1,"key"===(F=be).type){if(C=u.gopList.length){if(N=u.gopList[C-1],e.data.gopMinDuration&&1e3*F.timestamp-N.timestamp<e.data.gopMinDuration)return[3,11];N.duration=N.audioDuration=1e3*F.timestamp-N.timestamp}u.gopList.push({state:ro.NONE,index:u.gopList.length,sequenceNumber:F.sequenceNumber,timestamp:1e3*F.timestamp,duration:1e3*F.duration,audioTimestamp:1e3*F.timestamp,audioDuration:1e3*F.duration,users:[]})}Ae.label=11;case 11:return T=!0,[3,9];case 12:return[3,19];case 13:return v=Ae.sent(),ge={error:v},[3,19];case 14:return Ae.trys.push([14,,17,18]),T||pe||!(ke=y.return)?[3,16]:[4,ke.call(y)];case 15:Ae.sent(),Ae.label=16;case 16:return[3,18];case 17:if(ge)throw ge.error;return[7];case 18:return[7];case 19:return(O=u.gopList.length)&&((N=u.gopList[O-1]).duration=N.audioDuration=1e3*ne-N.timestamp),[4,w.getFirstTimestamp()];case 20:se=Ae.sent(),f.video={id:w.id,languageCode:w.languageCode,codec:w.codec,name:w.name,codedWidth:w.codedWidth,codedHeight:w.codedHeight,displayWidth:w.displayWidth,displayHeight:w.displayHeight,width:w.displayWidth,height:w.displayHeight,timeResolution:w.timeResolution,rotation:w.rotation,timestamp:1e3*se,duration:1e3*ne},Ae.label=21;case 21:return[4,g.getPrimaryAudioTrack()];case 22:return(P=Ae.sent())?(u.audioTrack=P,[4,P.computeDuration()]):[3,37];case 23:return ne=Ae.sent(),[4,P.getFirstTimestamp()];case 24:if(se=Ae.sent(),f.audio={id:P.id,languageCode:P.languageCode,codec:P.codec,name:P.name,numberOfChannels:P.numberOfChannels,sampleRate:P.sampleRate,timestamp:1e3*se,duration:1e3*ne},w)return[3,37];I=e.data.gopMinDuration||5e3,G=new $t(P),x=-1,E=!0,D=0,Ae.label=25;case 25:Ae.trys.push([25,30,31,36]),B=!0,A=s(G.packets(void 0,void 0,{metadataOnly:!0})),Ae.label=26;case 26:return[4,A.next()];case 27:if(_=Ae.sent(),we=_.done)return[3,29];Se=_.value,B=!1,F=Se,-1===x&&(x=F.timestamp),M=F.timestamp-x,(E||1e3*M>=I)&&(E=!1,(R=u.gopList.length)&&((N=u.gopList[R-1]).duration=N.audioDuration=1e3*F.timestamp-N.timestamp),u.gopList.push({state:ro.NONE,index:u.gopList.length,sequenceNumber:D,timestamp:1e3*F.timestamp,duration:1e3*F.duration,audioTimestamp:1e3*F.timestamp,audioDuration:1e3*F.duration,users:[]}),x=F.timestamp),D++,Ae.label=28;case 28:return B=!0,[3,26];case 29:return[3,36];case 30:return z=Ae.sent(),Te={error:z},[3,36];case 31:return Ae.trys.push([31,,34,35]),B||we||!(ye=A.return)?[3,33]:[4,ye.call(A)];case 32:Ae.sent(),Ae.label=33;case 33:return[3,35];case 34:if(Te)throw Te.error;return[7];case 35:return[7];case 36:(O=u.gopList.length)&&((N=u.gopList[O-1]).duration=N.audioDuration=1e3*ne-N.timestamp),Ae.label=37;case 37:return L=u.gopList.map(function(e){return{index:e.index,sequenceNumber:e.sequenceNumber,timestamp:e.timestamp,duration:e.duration,audioTimestamp:e.audioTimestamp,audioDuration:e.audioDuration}}),he={url:i,type:to.META,data:{meta:f,simpleGOPList:L}},c&&self.postMessage(he),[2,{data:he}];case 38:return o!==eo.DECODE?[3,64]:(me=u.gopList[e.data.index])&&me.state!==ro.ERROR?me.state===ro.DECODED?[2]:(me.users.includes(n)||me.users.push(n),[4,so(100)]):[2];case 39:if(Ae.sent(),!me.users.includes(n))return[2];if(me.state===ro.DECODING||me.state===ro.DECODED)return[2];if(me.state=ro.DECODING,U=[],!u.videoTrack)return[3,51];G=new Jt(u.videoTrack),Ae.label=40;case 40:Ae.trys.push([40,45,46,51]),V=!0,W=s(G.samples(.001*me.timestamp,.001*(me.timestamp+me.duration))),Ae.label=41;case 41:return[4,W.next()];case 42:if(H=Ae.sent(),Ce=H.done)return[3,44];Ie=H.value,V=!1,re=Ie,U.push(re.toVideoFrame()),re.close(),Ae.label=43;case 43:return V=!0,[3,41];case 44:return[3,51];case 45:return q=Ae.sent(),ve={error:q},[3,51];case 46:return Ae.trys.push([46,,49,50]),V||Ce||!(Pe=W.return)?[3,48]:[4,Pe.call(W)];case 47:Ae.sent(),Ae.label=48;case 48:return[3,50];case 49:if(ve)throw ve.error;return[7];case 50:return[7];case 51:if(j=[],$=0,Q=-1,K=0,!u.audioTrack||e.data.mute||me.didAudioChunk)return[3,63];me.didAudioChunk=!0,G=new tr(u.audioTrack),X=.001*me.timestamp,Y=.001*(me.timestamp+me.duration),J=G.samples(X,Y),Ae.label=52;case 52:Ae.trys.push([52,57,58,63]),Z=!0,ee=s(J),Ae.label=53;case 53:return[4,ee.next()];case 54:if(te=Ae.sent(),xe=te.done)return[3,56];if(Be=te.value,Z=!1,$=(re=Be).sampleRate,ae=re.numberOfChannels,ie=re.numberOfFrames,se=re.timestamp,ne=re.duration,se>=Y&&me.index<u.gopList.length-1||se<X)return[3,55];for(-1===Q&&(Q=1e3*se),K=1e3*se-Q+1e3*ne,oe=[],ce=0;ce<ae;ce++)de=new Float32Array(ie),re.copyTo(de,{planeIndex:ce,format:"f32-planar"}),oe.push(de);j.push({format:"f32-planar",channels:oe,sampleRate:$,numberOfFrames:ie,numberOfChannels:ae,timestamp:1e3*se,duration:1e3*ne}),re.close(),Ae.label=55;case 55:return Z=!0,[3,53];case 56:return[3,63];case 57:return ue=Ae.sent(),Ee={error:ue},[3,63];case 58:return Ae.trys.push([58,,61,62]),Z||xe||!(De=ee.return)?[3,60]:[4,De.call(ee)];case 59:Ae.sent(),Ae.label=60;case 60:return[3,62];case 61:if(Ee)throw Ee.error;return[7];case 62:return[7];case 63:return me.state!==ro.DECODING?(me.didAudioChunk=!1,U.forEach(function(e){e.close()}),[2]):(me.state=ro.DECODED,le=[],U.forEach(function(e){return le.push(e)}),j.forEach(function(e){e.channels.forEach(function(e){le.push(e.buffer)})}),he={url:i,type:to.DECODED,data:{index:e.data.index,videoFrames:U,audioChunks:j,sampleRate:$,audioTimeStamp:Q,audioDuration:K}},c&&self.postMessage(he,le),[2,{data:he}]);case 64:if(o===eo.RELEASE){if(!(me=u.gopList[e.data.index]))return[2];(fe=me.users.indexOf(e.data.id))>-1&&me.users.splice(fe,1),me.users.length||(me.state=ro.NONE,me.didAudioChunk=!1)}Ae.label=65;case 65:return[2]}})})};var oo=!1,co="Arial",uo=1e3/60,lo={};var ho,mo,fo,po,go,ko,bo,wo,To,yo={},So={requestAnimationFrame:function(e){return e?("undefined"!=typeof requestAnimationFrame?(So.requestAnimationFrame=requestAnimationFrame.bind(null),t=requestAnimationFrame(e)):(t=setTimeout(e,uo),So.requestAnimationFrame=function(e){return setTimeout(e,uo)}),t):-1;var t},cancelAnimationFrame:function(e){var t;return"undefined"!=typeof cancelAnimationFrame?(So.cancelAnimationFrame=cancelAnimationFrame.bind(null),t=cancelAnimationFrame(e)):(t=clearTimeout(e),So.cancelAnimationFrame=function(e){return clearTimeout(e)}),t},now:function(){return"undefined"!=typeof performance?(So.now=function(){return Math.floor(performance.now())},Math.floor(performance.now())):(So.now=Date.now.bind(Date),Date.now())},hasOffscreenCanvas:function(e){return e&&lo.hasOwnProperty(e)},getOffscreenCanvas:function(e,t,r,a){return function(e,t,r,a){var i;i=r?lo[r]?lo[r]:lo[r]=document.createElement("canvas"):document.createElement("canvas"),e=Math.ceil(e),t=Math.ceil(t),i.width=e,i.height=t,i.style.position="fixed",i.style.left="9999px",i.style.top="0px",i.style.webkitFontSmoothing="antialiased",i.style.mozOsxFontSmoothing="grayscale",i instanceof HTMLCanvasElement&&(document.body.appendChild(i),r&&i.setAttribute("key",r));var s=i.getContext("2d",a);return s||So.error("Total canvas memory use exceeds the maximum limit"),{canvas:i,ctx:s,width:e,height:t,available:!0,release:function(){this.available&&!oo&&(this.available=!1,s.globalAlpha=1,s.globalCompositeOperation="source-over",s.setTransform(1,0,0,1,0,0),s.clearRect(0,0,e,t),i.width=i.height=0,i instanceof HTMLCanvasElement&&document.body.removeChild(i),i=null)}}}(e,t,r,a)},isWebGLTexture:function(e){if(e&&"undefined"!=typeof WebGLTexture)return e instanceof WebGLTexture},getFontCanvas:function(){return So.getOffscreenCanvas(16,16,"__$$CHECK_SUPPORT_FONT_FAMILY$$__",{willReadFrequently:!0})},checkSupportFontFamily:function(e){if(e===co)return!0;if(yo.hasOwnProperty(e))return yo[e];var t=So.getFontCanvas().ctx;t.textAlign="center",t.fillStyle="#000",t.textBaseline="middle",ho||(t.clearRect(0,0,16,16),t.font="16px "+co,t.fillText("a",8,8),ho=t.getImageData(0,0,16,16).data),t.clearRect(0,0,16,16),/\s/.test(e)&&(e='"'+e.replace(/"/g,'\\"')+'"'),t.font="16px "+e+","+co,t.fillText("a",8,8);for(var r=t.getImageData(0,0,16,16).data,a=0,i=r.length;a<i;a++)if(ho[a]!==r[a])return yo[e]=!0;return yo[e]=!1},addArrayBufferFont:function(e,t){return r(this,void 0,void 0,function(){var r;return a(this,function(a){switch(a.label){case 0:return"undefined"==typeof document||"undefined"==typeof FontFace?[3,2]:[4,(r=new FontFace(e,t)).load()];case 1:a.sent(),document.fonts.add(r),a.label=2;case 2:return[2]}})})},addLocalFont:function(e){return r(this,void 0,void 0,function(){var t;return a(this,function(r){switch(r.label){case 0:return"undefined"==typeof document||"undefined"==typeof FontFace?[3,2]:[4,(t=new FontFace(e,"local(".concat(e))).load()];case 1:r.sent(),document.fonts.add(t),r.label=2;case 2:return[2]}})})},loadArrayBufferImg:function(e){return r(this,void 0,void 0,function(){var t,r;return a(this,function(a){return t=new Blob([e]),r=new Image,[2,new Promise(function(e,a){r.onload=function(){e(r)},r.onerror=function(e){a(e)},r.src=URL.createObjectURL(t)})]})})},pdfjsLibWorkerSrc:"https://gw.alipayobjects.com/os/lib/pdfjs-dist/3.11.174/build/pdf.worker.min.js",loadArrayBufferPdf:function(e){return r(this,void 0,void 0,function(){var t,r,i,s,n,o,c,d,u;return a(this,function(a){switch(a.label){case 0:return(t=window.pdfjsLib).GlobalWorkerOptions.workerSrc=So.pdfjsLibWorkerSrc,r=new Blob([e]),i=URL.createObjectURL(r),[4,t.getDocument(i).promise];case 1:return[4,a.sent().getPage(1)];case 2:return s=a.sent(),n=s.getViewport({scale:1}),(o=document.createElement("canvas")).width=n.width,o.height=n.height,c=o.getContext("2d"),[4,s.render({viewport:n,canvasContext:c,background:"transparent"}).promise];case 3:return a.sent(),[4,new Promise(function(e,t){o.toBlob(function(r){r?e(r):t("")})})];case 4:return d=a.sent(),u=new Image,[2,new Promise(function(e,t){u.onload=function(){e(u)},u.onerror=function(e){t(e)},u.src=URL.createObjectURL(d)})]}})})},loadLocalFonts:function(){return r(this,void 0,void 0,function(){var e;return a(this,function(t){switch(t.label){case 0:if("undefined"==typeof navigator)return[3,5];t.label=1;case 1:return t.trys.push([1,4,,5]),[4,navigator.permissions.query({name:"local-fonts"})];case 2:return"denied"===t.sent().state?(So.error("No Permission."),[2,[]]):[4,window.queryLocalFonts()];case 3:return[2,t.sent()];case 4:return e=t.sent(),So.error(e),[2,[]];case 5:return[2,[]]}})})},uploadBlobImgSrc:function(e){return r(this,void 0,void 0,function(){return a(this,function(e){return[2]})})},log:function(e){console.log(e)},warn:function(e){console.warn(e)},error:function(e){console.error(e)}};e.EncoderType=void 0,(mo=e.EncoderType||(e.EncoderType={}))[mo.INIT=0]="INIT",mo[mo.FRAME=1]="FRAME",mo[mo.END=2]="END",e.EncoderEvent=void 0,(fo=e.EncoderEvent||(e.EncoderEvent={}))[fo.PROGRESS=0]="PROGRESS",fo[fo.FINISH=1]="FINISH",fo[fo.ERROR=2]="ERROR";var Co,vo=0,Po=0,Io=[],xo=0,Eo=0;function Do(e,t,r){var a=t.numberOfChannels,i=t.sampleRate;if(e&&"configured"===e.state&&r){var s=Math.floor(.001*r*i);if(s>xo){for(var n=s-xo,o=new Float32Array(n*Io.length),c=0;c<Io.length;c++){var d=Io[c].subarray(xo,s);o.set(d,c*n)}var u=new AudioData({format:"f32-planar",sampleRate:i,numberOfFrames:n,numberOfChannels:a,timestamp:Eo,data:o});xo=s,Eo=r,e.encode(u)}}}var Bo=function(t){return r(void 0,void 0,void 0,function(){var r,i,s,n,o,c,d,u,l,h,m,f,p,g,k,b,w,T,y,S,C,v,P,I,x,E,D,B,A,_,F;return a(this,function(a){switch(a.label){case 0:if(r=t.data,i=r.type,s=r.isWorker,n=function(t){var r={type:e.EncoderEvent.ERROR,error:t};return s&&self.postMessage(r),{data:r}},vo>=0&&(Co=new Promise(function(e){To=e})),i!==e.EncoderType.INIT)return[3,2];if(Co=void 0,vo=t.data.encoderFrameQue||0,Po=0,vo>=0&&(Co=new Promise(function(e){To=e})),po&&(po.close(),po=void 0),go&&(go.close(),go=void 0),o=function(){if(Co&&(! --Po||Po<vo)){var t={type:e.EncoderEvent.PROGRESS};s&&self.postMessage(t),To({data:t})}},c=null===(_=t.data.videoEncoderConfig)||void 0===_?void 0:_.codec,d=void 0,d=/^vp/.test(c)?new Nn:new Rn,ko=new Qn({format:d,target:new Pn}),/^vp8/.test(c)?bo=new Vn("vp8"):/^vp09\./.test(c)?bo=new Vn("vp9"):/^av01\./.test(c)?bo=new Vn("av1"):/^hev1\./.test(c)||/^hvc1\./.test(c)?bo=new Vn("hevc"):(/^avc1\./.test(c)||/^avc3\./.test(c))&&(bo=new Vn("avc")),bo&&(ko.addVideoTrack(bo),po=new VideoEncoder({output:function(e,r){var a=yt.fromEncodedChunk(e);bo.add(a,r),go&&Do(go,t.data.audioEncoderConfig,.001*e.timestamp),o()},error:function(e){n(e.message)}}),po.configure(t.data.videoEncoderConfig)),u=null===(F=t.data.audioEncoderConfig)||void 0===F?void 0:F.codec,t.data.mute?wo=void 0:/^mp3/.test(u)?wo=new Hn("mp3"):/^flac/.test(u)?wo=new Hn("flac"):/^opus/.test(u)?wo=new Hn("opus"):/^vorbis/.test(u)?wo=new Hn("vorbis"):/^pcm-/.test(u)?wo=new Hn(u):/^mp4a\./.test(u)?wo=new Hn("aac"):/^ulaw/.test(u)?wo=new Hn("ulaw"):/^alaw/.test(u)&&(wo=new Hn("alaw")),wo){for(ko.addAudioTrack(wo),go=new AudioEncoder({output:function(e,t){var r=yt.fromEncodedChunk(e);wo.add(r,t)},error:function(e){n(e.message)}}),go.configure(t.data.audioEncoderConfig),Io.splice(0),l=t.data.audioEncoderConfig.sampleRate*Math.ceil(.001*t.data.duration),k=0;k<t.data.audioEncoderConfig.numberOfChannels;k++)Io.push(new Float32Array(l));xo=0,Eo=0}return[4,ko.start()];case 1:return a.sent(),[3,15];case 2:return i!==e.EncoderType.FRAME?[3,10]:(Po++,h=t.data.videoFrame,po&&"configured"===po.state&&h?po.encodeQueueSize>5?[4,so(100)]:[3,8]:[3,9]);case 3:a.sent(),So.warn("encodeQueueSize: "+po.encodeQueueSize),k=0,a.label=4;case 4:return k<20?po.encodeQueueSize>5?[4,so(100)]:[3,6]:[3,8];case 5:return a.sent(),So.warn("encodeQueueSize: "+po.encodeQueueSize+", "+k),[3,7];case 6:return[3,8];case 7:return k++,[3,4];case 8:po.encode(h),a.label=9;case 9:if(null==h||h.close(),go){if((m=t.data.audioList).length&&m.length)for(f=t.data.audioEncoderConfig,p=f.numberOfChannels,g=f.sampleRate,k=0,b=m.length;k<b;k++)for(w=m[k],T=w.audioChunk,y=w.volume,S=Math.round(.001*T.timestamp*g),C=T.numberOfFrames,v=0;v<p;v++)for(P=Io[v],I=T.channels[v],x=0;x<C;x++)D=P[E=S+x]+I[x]*y,P[E]=Math.max(-1,Math.min(1,D));Do(go,t.data.audioEncoderConfig,t.data.timestamp)}return!Co||Po<vo?(A={type:e.EncoderEvent.PROGRESS},s&&self.postMessage(A),[2,{data:A}]):[2,Co];case 10:return i!==e.EncoderType.END?[3,15]:po&&ko?[4,po.flush()]:[2];case 11:return a.sent(),po.close(),po=void 0,"configured"!==(null==go?void 0:go.state)?[3,13]:(Do(go,t.data.audioEncoderConfig,t.data.timestamp),[4,go.flush()]);case 12:a.sent(),go.close(),go=void 0,a.label=13;case 13:return[4,ko.finalize()];case 14:if(a.sent(),B=ko.target.buffer,ko=void 0,A={type:e.EncoderEvent.FINISH,buffer:B},!s)return[2,{data:A}];self.postMessage(A,[B]),a.label=15;case 15:return[2]}})})};self.onmessage=Bo,e.onMessage=Bo});
|
|
121
274
|
//# sourceMappingURL=encoder.min.js.map
|