krono-flow 0.0.1
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/LICENSE +21 -0
- package/dist/decoder.js +15882 -0
- package/dist/decoder.js.map +1 -0
- package/dist/decoder.min.js +217 -0
- package/dist/decoder.min.js.map +1 -0
- package/dist/encoder.js +7002 -0
- package/dist/encoder.js.map +1 -0
- package/dist/encoder.min.js +121 -0
- package/dist/encoder.min.js.map +1 -0
- package/dist/index.js +38331 -0
- package/dist/index.js.map +1 -0
- package/dist/index.min.js +274 -0
- package/dist/index.min.js.map +1 -0
- package/dist/style.css +217 -0
- package/dist/style.css.map +1 -0
- package/dist/style.min.css +1 -0
- package/dist/style.min.css.map +1 -0
- package/package.json +61 -0
|
@@ -0,0 +1,121 @@
|
|
|
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(i||(i=Promise))(function(a,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function n(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?a(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(o,n)}c((r=r.apply(e,t||[])).next())})}function i(e,t){var i,r,a,s={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]},o=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return o.next=n(0),o.throw=n(1),o.return=n(2),"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function n(n){return function(c){return function(n){if(i)throw new TypeError("Generator is already executing.");for(;o&&(o=0,n[0]&&(s=0)),s;)try{if(i=1,r&&(a=2&n[0]?r.return:n[0]?r.throw||((a=r.return)&&a.call(r),0):r.next)&&!(a=a.call(r,n[1])).done)return a;switch(r=0,a&&(n=[2&n[0],a.value]),n[0]){case 0:case 1:a=n;break;case 4:return s.label++,{value:n[1],done:!1};case 5:s.label++,r=n[1],n=[0];continue;case 7:n=s.ops.pop(),s.trys.pop();continue;default:if(!(a=s.trys,(a=a.length>0&&a[a.length-1])||6!==n[0]&&2!==n[0])){s=0;continue}if(3===n[0]&&(!a||n[1]>a[0]&&n[1]<a[3])){s.label=n[1];break}if(6===n[0]&&s.label<a[1]){s.label=a[1],a=n;break}if(a&&s.label<a[2]){s.label=a[2],s.ops.push(n);break}a[2]&&s.ops.pop(),s.trys.pop();continue}n=t.call(e,s)}catch(e){n=[6,e],r=0}finally{i=a=0}if(5&n[0])throw n[1];return{value:n[0]?n[1]:void 0,done:!0}}([n,c])}}}
|
|
2
|
+
/*!
|
|
3
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
4
|
+
*
|
|
5
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
6
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
7
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
8
|
+
*/
|
|
9
|
+
function r(e){if(!e)throw new Error("Assertion failed.")}"function"==typeof SuppressedError&&SuppressedError;const a=e=>e&&e[e.length-1],s=e=>e>=0&&e<2**32;class o{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){const e=Math.floor(this.pos/8),t=this.bytes[e]??0,i=7-(7&this.pos),r=(t&1<<i)>>i;return this.pos++,r}readBits(e){if(1===e)return this.readBit();let t=0;for(let i=0;i<e;i++)t<<=1,t|=this.readBit();return t}writeBits(e,t){const i=this.pos+e;for(let e=this.pos;e<i;e++){const r=Math.floor(e/8);let a=this.bytes[r];const s=7-(7&e);a&=~(1<<s),a|=(t&1<<i-e-1)>>i-e-1<<s,this.bytes[r]=a}this.pos=i}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 o(this.bytes);return e.pos=this.pos,e}}const n=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)},c=e=>{const t=n(e);return 1&t?t+1>>1:-(t>>1)},d=e=>e.constructor===Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength),u=new TextEncoder,l={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},h={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},m={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},p=e=>!!(e&&e.primaries&&e.transfer&&e.matrix&&void 0!==e.fullRange),f=e=>e instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e);class g{constructor(){this.currentPromise=Promise.resolve()}async acquire(){let e;const t=new Promise(t=>{e=t}),i=this.currentPromise;return this.currentPromise=t,await i,e}}const w=()=>{let e,t;return{promise:new Promise((i,r)=>{e=i,t=r}),resolve:e,reject:t}},k=e=>{throw new Error(`Unexpected value: ${e}`)},y=(e,t)=>Math.round(e/t)*t,b=/^[a-z]{3}$/,T=1e6*(1+Number.EPSILON),C=function*(e){for(const t in e){const i=e[t];void 0!==i&&(yield{key:t,value:i})}},v=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}},S=(e,t)=>{if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(e[i]!==t[i])return!1;return!0};
|
|
10
|
+
/*!
|
|
11
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
12
|
+
*
|
|
13
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
14
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
15
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
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.")};
|
|
18
|
+
/*!
|
|
19
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
20
|
+
*
|
|
21
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
22
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
23
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
24
|
+
*/
|
|
25
|
+
class ${constructor(e){this.mutex=new g,this.firstMediaStreamTimestamp=null,this.trackTimestampInfo=new WeakMap,this.output=e}onTrackClose(e){}validateAndNormalizeTimestamp(e,t,i){t+=e.source._timestampOffset;let r=this.trackTimestampInfo.get(e);if(!r){if(!i)throw new Error("First packet must be a key packet.");r={maxTimestamp:t,maxTimestampBeforeLastKeyPacket:t},this.trackTimestampInfo.set(e,r)}if(t<0)throw new Error(`Timestamps must be non-negative (got ${t}s).`);if(i&&(r.maxTimestampBeforeLastKeyPacket=r.maxTimestamp),t<r.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 ${r.maxTimestampBeforeLastKeyPacket}s.`);return r.maxTimestamp=Math.max(r.maxTimestamp,t),t}}
|
|
26
|
+
/*!
|
|
27
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
28
|
+
*
|
|
29
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
30
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
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={}));
|
|
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
|
+
*/
|
|
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)}}
|
|
41
|
+
/*!
|
|
42
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
43
|
+
*
|
|
44
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
45
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
46
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
47
|
+
*/
|
|
48
|
+
/*!
|
|
49
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
50
|
+
*
|
|
51
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
52
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
53
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
54
|
+
*/
|
|
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")};
|
|
56
|
+
/*!
|
|
57
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
58
|
+
*
|
|
59
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
60
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
61
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
62
|
+
*/
|
|
63
|
+
/*!
|
|
64
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
65
|
+
*
|
|
66
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
67
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
68
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
69
|
+
*/
|
|
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};
|
|
71
|
+
/*!
|
|
72
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
73
|
+
*
|
|
74
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
75
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
76
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
77
|
+
*/
|
|
78
|
+
class ti{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 i=t+e.byteLength-this.trackedStart;let r=this.trackedWrites.byteLength;for(;r<i;)r*=2;if(r!==this.trackedWrites.byteLength){const e=new Uint8Array(r);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 ii=65536,ri=2**32;class ai extends ti{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(ii,{maxByteLength:ri})}catch{this.buffer=new ArrayBuffer(ii),this.supportsResize=!1}else this.buffer=new ArrayBuffer(ii);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>ri)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),i=new Uint8Array(e);i.set(this.bytes,0),this.buffer=e,this.bytes=i}}}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
|
+
/*!
|
|
80
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
81
|
+
*
|
|
82
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
83
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
84
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
85
|
+
*/class si{constructor(){this._output=null,this.onwrite=null}}class oi extends si{constructor(){super(...arguments),this.buffer=null}_createWriter(){return new ai(this)}}
|
|
86
|
+
/*!
|
|
87
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
88
|
+
*
|
|
89
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
90
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
91
|
+
* 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()}}
|
|
93
|
+
/*!
|
|
94
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
95
|
+
*
|
|
96
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
97
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
98
|
+
* 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()}}
|
|
100
|
+
/*!
|
|
101
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
102
|
+
*
|
|
103
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
104
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
105
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
106
|
+
*/class pi{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>B.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>x.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>P.includes(e))}_codecUnsupportedHint(e){return""}}class fi extends pi{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 ui(e,this)}}class gi extends fi{constructor(e){super(e)}get _name(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...B,...M,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...P]}_codecUnsupportedHint(e){return(new wi).getSupportedCodecs().includes(e)?" Switching to MOV will grant support for this codec.":""}}class wi extends fi{constructor(e){super(e)}get _name(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...B,...x]}_codecUnsupportedHint(e){return(new gi).getSupportedCodecs().includes(e)?" Switching to MP4 will grant support for this codec.":""}}class ki extends pi{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 mi(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[...B,...M,...A.filter(e=>!["pcm-s8","pcm-f32be","pcm-f64be","ulaw","alaw"].includes(e)),...P]}get supportsVideoRotationMetadata(){return!1}}class yi extends ki{constructor(e){super(e)}getSupportedCodecs(){return[...B.filter(e=>["vp8","vp9","av1"].includes(e)),...x.filter(e=>["opus","vorbis"].includes(e)),...P]}get _name(){return"WebM"}get fileExtension(){return".webm"}get mimeType(){return"video/webm"}_codecUnsupportedHint(e){return(new ki).getSupportedCodecs().includes(e)?" Switching to MKV will grant support for this codec.":""}}
|
|
107
|
+
/*!
|
|
108
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
109
|
+
*
|
|
110
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
111
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
112
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
113
|
+
*/class bi{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 Ti extends bi{constructor(e){if(super(),this._connectedTrack=null,!B.includes(e))throw new TypeError(`Invalid video codec '${e}'. Must be one of: ${B.join(", ")}.`);this._codec=e}}class Ci extends Ti{constructor(e){super(e)}add(e,t){if(!(e instanceof de))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 vi extends bi{constructor(e){if(super(),this._connectedTrack=null,!x.includes(e))throw new TypeError(`Invalid audio codec '${e}'. Must be one of: ${x.join(", ")}.`);this._codec=e}}class Si extends vi{constructor(e){super(e)}add(e,t){if(!(e instanceof de))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 Ei extends bi{constructor(e){if(super(),this._connectedTrack=null,!P.includes(e))throw new TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${P.join(", ")}.`);this._codec=e}}
|
|
114
|
+
/*!
|
|
115
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
116
|
+
*
|
|
117
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
118
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
119
|
+
* 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});
|
|
121
|
+
//# sourceMappingURL=encoder.min.js.map
|