@mediabunny/server 1.56.2 → 1.56.3
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.
|
@@ -491,6 +491,139 @@ var MediabunnyServer = (() => {
|
|
|
491
491
|
return new DataView(source);
|
|
492
492
|
}
|
|
493
493
|
};
|
|
494
|
+
var TextEncoder = typeof globalThis.TextEncoder !== "undefined" ? globalThis.TextEncoder : class TextEncoder2 {
|
|
495
|
+
constructor() {
|
|
496
|
+
this.encoding = "utf-8";
|
|
497
|
+
}
|
|
498
|
+
encode(input = "") {
|
|
499
|
+
const bytes = new Uint8Array(3 * input.length);
|
|
500
|
+
let n = 0;
|
|
501
|
+
for (let i = 0; i < input.length; i++) {
|
|
502
|
+
let c = input.charCodeAt(i);
|
|
503
|
+
if (c < 128) {
|
|
504
|
+
bytes[n++] = c;
|
|
505
|
+
} else if (c < 2048) {
|
|
506
|
+
bytes[n++] = 192 | c >> 6;
|
|
507
|
+
bytes[n++] = 128 | c & 63;
|
|
508
|
+
} else if (c < 55296 || c > 57343) {
|
|
509
|
+
bytes[n++] = 224 | c >> 12;
|
|
510
|
+
bytes[n++] = 128 | c >> 6 & 63;
|
|
511
|
+
bytes[n++] = 128 | c & 63;
|
|
512
|
+
} else {
|
|
513
|
+
const next = i + 1 < input.length ? input.charCodeAt(i + 1) : 0;
|
|
514
|
+
if (c < 56320 && next >= 56320 && next <= 57343) {
|
|
515
|
+
c = 65536 + (c - 55296 << 10) + (next - 56320);
|
|
516
|
+
i++;
|
|
517
|
+
bytes[n++] = 240 | c >> 18;
|
|
518
|
+
bytes[n++] = 128 | c >> 12 & 63;
|
|
519
|
+
bytes[n++] = 128 | c >> 6 & 63;
|
|
520
|
+
bytes[n++] = 128 | c & 63;
|
|
521
|
+
} else {
|
|
522
|
+
bytes[n++] = 239;
|
|
523
|
+
bytes[n++] = 191;
|
|
524
|
+
bytes[n++] = 189;
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
return bytes.slice(0, n);
|
|
529
|
+
}
|
|
530
|
+
};
|
|
531
|
+
var TextDecoder = typeof globalThis.TextDecoder !== "undefined" ? globalThis.TextDecoder : class TextDecoder2 {
|
|
532
|
+
constructor(label = "utf-8") {
|
|
533
|
+
const normalized = label.trim().toLowerCase();
|
|
534
|
+
if (normalized === "utf-8" || normalized === "utf8" || normalized === "unicode-1-1-utf-8") {
|
|
535
|
+
this.encoding = "utf-8";
|
|
536
|
+
} else if (normalized === "utf-16le" || normalized === "utf-16") {
|
|
537
|
+
this.encoding = "utf-16le";
|
|
538
|
+
} else if (normalized === "utf-16be") {
|
|
539
|
+
this.encoding = "utf-16be";
|
|
540
|
+
} else {
|
|
541
|
+
throw new RangeError(`The encoding label provided ('${label}') is invalid.`);
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
decode(input) {
|
|
545
|
+
const bytes = input ? toUint8Array(input) : new Uint8Array(0);
|
|
546
|
+
const units = [];
|
|
547
|
+
if (this.encoding === "utf-8") {
|
|
548
|
+
let i = bytes.length >= 3 && bytes[0] === 239 && bytes[1] === 187 && bytes[2] === 191 ? 3 : 0;
|
|
549
|
+
while (i < bytes.length) {
|
|
550
|
+
const lead = bytes[i];
|
|
551
|
+
if (lead < 128) {
|
|
552
|
+
units.push(lead);
|
|
553
|
+
i++;
|
|
554
|
+
continue;
|
|
555
|
+
}
|
|
556
|
+
let continuationCount;
|
|
557
|
+
let codePoint;
|
|
558
|
+
if (lead >= 194 && lead < 224) {
|
|
559
|
+
continuationCount = 1;
|
|
560
|
+
codePoint = lead & 31;
|
|
561
|
+
} else if (lead >= 224 && lead < 240) {
|
|
562
|
+
continuationCount = 2;
|
|
563
|
+
codePoint = lead & 15;
|
|
564
|
+
} else if (lead >= 240 && lead < 245) {
|
|
565
|
+
continuationCount = 3;
|
|
566
|
+
codePoint = lead & 7;
|
|
567
|
+
} else {
|
|
568
|
+
units.push(65533);
|
|
569
|
+
i++;
|
|
570
|
+
continue;
|
|
571
|
+
}
|
|
572
|
+
let lowerBound = lead === 224 ? 160 : lead === 240 ? 144 : 128;
|
|
573
|
+
let upperBound = lead === 237 ? 159 : lead === 244 ? 143 : 191;
|
|
574
|
+
let j = 1;
|
|
575
|
+
for (; j <= continuationCount; j++) {
|
|
576
|
+
const byte = i + j < bytes.length ? bytes[i + j] : 0;
|
|
577
|
+
if (byte < lowerBound || byte > upperBound) {
|
|
578
|
+
break;
|
|
579
|
+
}
|
|
580
|
+
codePoint = codePoint << 6 | byte & 63;
|
|
581
|
+
lowerBound = 128;
|
|
582
|
+
upperBound = 191;
|
|
583
|
+
}
|
|
584
|
+
i += j;
|
|
585
|
+
if (j <= continuationCount) {
|
|
586
|
+
units.push(65533);
|
|
587
|
+
} else if (codePoint >= 65536) {
|
|
588
|
+
codePoint -= 65536;
|
|
589
|
+
units.push(55296 | codePoint >> 10, 56320 | codePoint & 1023);
|
|
590
|
+
} else {
|
|
591
|
+
units.push(codePoint);
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
} else {
|
|
595
|
+
const littleEndian = this.encoding === "utf-16le";
|
|
596
|
+
const bomLow = littleEndian ? 255 : 254;
|
|
597
|
+
const bomHigh = littleEndian ? 254 : 255;
|
|
598
|
+
let i = bytes.length >= 2 && bytes[0] === bomLow && bytes[1] === bomHigh ? 2 : 0;
|
|
599
|
+
while (i + 1 < bytes.length) {
|
|
600
|
+
const unit = littleEndian ? bytes[i] | bytes[i + 1] << 8 : bytes[i] << 8 | bytes[i + 1];
|
|
601
|
+
i += 2;
|
|
602
|
+
if (unit >= 55296 && unit <= 56319) {
|
|
603
|
+
const next = i + 1 < bytes.length ? littleEndian ? bytes[i] | bytes[i + 1] << 8 : bytes[i] << 8 | bytes[i + 1] : -1;
|
|
604
|
+
if (next >= 56320 && next <= 57343) {
|
|
605
|
+
units.push(unit, next);
|
|
606
|
+
i += 2;
|
|
607
|
+
} else {
|
|
608
|
+
units.push(65533);
|
|
609
|
+
}
|
|
610
|
+
} else if (unit >= 56320 && unit <= 57343) {
|
|
611
|
+
units.push(65533);
|
|
612
|
+
} else {
|
|
613
|
+
units.push(unit);
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
if (i < bytes.length) {
|
|
617
|
+
units.push(65533);
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
let result = "";
|
|
621
|
+
for (let i = 0; i < units.length; i += 8192) {
|
|
622
|
+
result += String.fromCharCode(...units.slice(i, i + 8192));
|
|
623
|
+
}
|
|
624
|
+
return result;
|
|
625
|
+
}
|
|
626
|
+
};
|
|
494
627
|
var COLOR_PRIMARIES_MAP = {
|
|
495
628
|
bt709: 1,
|
|
496
629
|
// ITU-R BT.709
|
|
@@ -5,6 +5,6 @@
|
|
|
5
5
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
6
6
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
7
7
|
*/
|
|
8
|
-
"use strict";var MediabunnyServer=(()=>{var Rt=Object.create;var ge=Object.defineProperty;var Ft=Object.getOwnPropertyDescriptor;var Vt=Object.getOwnPropertyNames;var Nt=Object.getPrototypeOf,Mt=Object.prototype.hasOwnProperty;var k=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(r,t)=>(typeof require<"u"?require:r)[t]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var kt=(e,r)=>{for(var t in r)ge(e,t,{get:r[t],enumerable:!0})},Ge=(e,r,t,n)=>{if(r&&typeof r=="object"||typeof r=="function")for(let i of Vt(r))!Mt.call(e,i)&&i!==t&&ge(e,i,{get:()=>r[i],enumerable:!(n=Ft(r,i))||n.enumerable});return e};var ne=(e,r,t)=>(t=e!=null?Rt(Nt(e)):{},Ge(r||!e||!e.__esModule?ge(t,"default",{value:e,enumerable:!0}):t,e)),Ut=e=>Ge(ge({},"__esModule",{value:!0}),e);var cr={};kt(cr,{AvFrameAudioSampleResource:()=>j,AvFrameVideoSampleResource:()=>W,_serverOptions:()=>Q,registerMediabunnyServer:()=>sr,toAvFrame:()=>ar});var O=k("mediabunny"),Y=ne(k("node-av"));var ye=k("mediabunny"),C=ne(k("node-av"));var o=ne(k("node-av"));var ee={avc:o.AV_CODEC_ID_H264,hevc:o.AV_CODEC_ID_HEVC,vp8:o.AV_CODEC_ID_VP8,vp9:o.AV_CODEC_ID_VP9,av1:o.AV_CODEC_ID_AV1,prores:o.AV_CODEC_ID_PRORES,aac:o.AV_CODEC_ID_AAC,opus:o.AV_CODEC_ID_OPUS,mp3:o.AV_CODEC_ID_MP3,vorbis:o.AV_CODEC_ID_VORBIS,flac:o.AV_CODEC_ID_FLAC,ac3:o.AV_CODEC_ID_AC3,eac3:o.AV_CODEC_ID_EAC3,dts:o.AV_CODEC_ID_DTS},Fe,Ye=()=>Q.hardwareContext!==void 0&&typeof Q.hardwareContext!="function"?Q.hardwareContext:(Fe===void 0&&(Fe=o.HardwareContext.auto()),Fe),Ke=e=>{if(e!==null&&!(e instanceof o.HardwareContext))throw new TypeError("When serverOptions.hardwareContext is a function, it must return or resolve to a NodeAv.HardwareContext or null.")},Ve=new Map,Qe=async e=>{if(typeof Q.hardwareContext=="function"){let r=await Q.hardwareContext(e);return Ke(r),r?.getDecoderCodec(e)??null}if(!Ve.has(e)){let r=Ye();Ve.set(e,r?.getDecoderCodec(e)??null)}return Ve.get(e)},Ne=new Map,$e=async e=>{if(typeof Q.hardwareContext=="function"){let r=await Q.hardwareContext(e);return Ke(r),r?.getEncoderCodec(e)??null}if(!Ne.has(e)){let r=Ye();Ne.set(e,r?.getEncoderCodec(e)??null)}return Ne.get(e)},je=e=>{switch(e){case"bt709":return o.AVCOL_PRI_BT709;case"bt470bg":return o.AVCOL_PRI_BT470BG;case"smpte170m":return o.AVCOL_PRI_SMPTE170M;case"bt2020":return o.AVCOL_PRI_BT2020;case"smpte432":return o.AVCOL_PRI_SMPTE432}return null},Ce=e=>{switch(e){case o.AVCOL_PRI_BT709:return"bt709";case o.AVCOL_PRI_BT470BG:return"bt470bg";case o.AVCOL_PRI_SMPTE170M:return"smpte170m";case o.AVCOL_PRI_BT2020:return"bt2020";case o.AVCOL_PRI_SMPTE432:return"smpte432"}return null},Je=e=>{switch(e){case"bt709":return o.AVCOL_TRC_BT709;case"smpte170m":return o.AVCOL_TRC_SMPTE170M;case"iec61966-2-1":return o.AVCOL_TRC_IEC61966_2_1;case"linear":return o.AVCOL_TRC_LINEAR;case"pq":return o.AVCOL_TRC_SMPTE2084;case"hlg":return o.AVCOL_TRC_ARIB_STD_B67}return null},be=e=>{switch(e){case o.AVCOL_TRC_BT709:return"bt709";case o.AVCOL_TRC_SMPTE170M:return"smpte170m";case o.AVCOL_TRC_IEC61966_2_1:return"iec61966-2-1";case o.AVCOL_TRC_LINEAR:return"linear";case o.AVCOL_TRC_SMPTE2084:return"pq";case o.AVCOL_TRC_ARIB_STD_B67:return"hlg"}return null},Ze=e=>{switch(e){case"rgb":return o.AVCOL_SPC_RGB;case"bt709":return o.AVCOL_SPC_BT709;case"bt470bg":return o.AVCOL_SPC_BT470BG;case"smpte170m":return o.AVCOL_SPC_SMPTE170M;case"bt2020-ncl":return o.AVCOL_SPC_BT2020_NCL}return null},xe=e=>{switch(e){case o.AVCOL_SPC_RGB:return"rgb";case o.AVCOL_SPC_BT709:return"bt709";case o.AVCOL_SPC_BT470BG:return"bt470bg";case o.AVCOL_SPC_SMPTE170M:return"smpte170m";case o.AVCOL_SPC_BT2020_NCL:return"bt2020-ncl"}return null},et=e=>{switch(e){case o.AV_PIX_FMT_YUV420P:return"I420";case o.AV_PIX_FMT_YUVJ420P:return"I420";case o.AV_PIX_FMT_YUV420P10LE:return"I420P10";case o.AV_PIX_FMT_YUV420P12LE:return"I420P12";case o.AV_PIX_FMT_YUVA420P:return"I420A";case o.AV_PIX_FMT_YUVA420P10LE:return"I420AP10";case o.AV_PIX_FMT_YUV422P:return"I422";case o.AV_PIX_FMT_YUVJ422P:return"I422";case o.AV_PIX_FMT_YUV422P10LE:return"I422P10";case o.AV_PIX_FMT_YUV422P12LE:return"I422P12";case o.AV_PIX_FMT_YUVA422P:return"I422A";case o.AV_PIX_FMT_YUVA422P10LE:return"I422AP10";case o.AV_PIX_FMT_YUVA422P12LE:return"I422AP12";case o.AV_PIX_FMT_YUV444P:return"I444";case o.AV_PIX_FMT_YUVJ444P:return"I444";case o.AV_PIX_FMT_YUV444P10LE:return"I444P10";case o.AV_PIX_FMT_YUV444P12LE:return"I444P12";case o.AV_PIX_FMT_YUVA444P:return"I444A";case o.AV_PIX_FMT_YUVA444P10LE:return"I444AP10";case o.AV_PIX_FMT_YUVA444P12LE:return"I444AP12";case o.AV_PIX_FMT_NV12:return"NV12";case o.AV_PIX_FMT_RGBA:return"RGBA";case o.AV_PIX_FMT_RGB0:return"RGBX";case o.AV_PIX_FMT_BGRA:return"BGRA";case o.AV_PIX_FMT_BGR0:return"BGRX";default:return null}},Me=e=>{switch(e){case"I420":return o.AV_PIX_FMT_YUV420P;case"I420P10":return o.AV_PIX_FMT_YUV420P10LE;case"I420P12":return o.AV_PIX_FMT_YUV420P12LE;case"I420A":return o.AV_PIX_FMT_YUVA420P;case"I420AP10":return o.AV_PIX_FMT_YUVA420P10LE;case"I422":return o.AV_PIX_FMT_YUV422P;case"I422P10":return o.AV_PIX_FMT_YUV422P10LE;case"I422P12":return o.AV_PIX_FMT_YUV422P12LE;case"I422A":return o.AV_PIX_FMT_YUVA422P;case"I422AP10":return o.AV_PIX_FMT_YUVA422P10LE;case"I422AP12":return o.AV_PIX_FMT_YUVA422P12LE;case"I444":return o.AV_PIX_FMT_YUV444P;case"I444P10":return o.AV_PIX_FMT_YUV444P10LE;case"I444P12":return o.AV_PIX_FMT_YUV444P12LE;case"I444A":return o.AV_PIX_FMT_YUVA444P;case"I444AP10":return o.AV_PIX_FMT_YUVA444P10LE;case"I444AP12":return o.AV_PIX_FMT_YUVA444P12LE;case"NV12":return o.AV_PIX_FMT_NV12;case"RGBA":return o.AV_PIX_FMT_RGBA;case"RGBX":return o.AV_PIX_FMT_RGB0;case"BGRA":return o.AV_PIX_FMT_BGRA;case"BGRX":return o.AV_PIX_FMT_BGR0;default:return o.AV_PIX_FMT_NONE}},tt=e=>{switch(e){case o.AV_SAMPLE_FMT_U8:return"u8";case o.AV_SAMPLE_FMT_S16:return"s16";case o.AV_SAMPLE_FMT_S32:return"s32";case o.AV_SAMPLE_FMT_FLT:return"f32";case o.AV_SAMPLE_FMT_U8P:return"u8-planar";case o.AV_SAMPLE_FMT_S16P:return"s16-planar";case o.AV_SAMPLE_FMT_S32P:return"s32-planar";case o.AV_SAMPLE_FMT_FLTP:return"f32-planar";default:return null}},rt=e=>{switch(e){case"u8":return o.AV_SAMPLE_FMT_U8;case"s16":return o.AV_SAMPLE_FMT_S16;case"s32":return o.AV_SAMPLE_FMT_S32;case"f32":return o.AV_SAMPLE_FMT_FLT;case"u8-planar":return o.AV_SAMPLE_FMT_U8P;case"s16-planar":return o.AV_SAMPLE_FMT_S16P;case"s32-planar":return o.AV_SAMPLE_FMT_S32P;case"f32-planar":return o.AV_SAMPLE_FMT_FLTP;default:return o.AV_SAMPLE_FMT_NONE}},oe=e=>{switch(e){case 1:return o.AV_CHANNEL_LAYOUT_MONO;case 2:return o.AV_CHANNEL_LAYOUT_STEREO;case 4:return o.AV_CHANNEL_LAYOUT_QUAD;case 6:return o.AV_CHANNEL_LAYOUT_5POINT1_BACK;case 8:return o.AV_CHANNEL_LAYOUT_7POINT1;default:return{nbChannels:e,order:o.AV_CHANNEL_ORDER_UNSPEC,mask:0n}}},Ot=0x603n,nt=e=>{switch(e){case 1:return o.AV_CHANNEL_LAYOUT_MONO;case 2:return o.AV_CHANNEL_LAYOUT_STEREO;case 4:return{nbChannels:4,order:o.AV_CHANNEL_ORDER_NATIVE,mask:Ot};case 5:return o.AV_CHANNEL_LAYOUT_5POINT0;case 6:return o.AV_CHANNEL_LAYOUT_5POINT1;default:return{nbChannels:e,order:o.AV_CHANNEL_ORDER_UNSPEC,mask:0n}}};var H=class H{constructor(){}static get level(){return H._level}static set level(r){if(r!==0&&r!==1&&r!==2&&r!==3)throw new TypeError("Invalid log level. Use one of the values of the LogLevel enum.");H._level=r}static get _emitter(){return H._emitterInstance??=new ve}static on(r,t,n){return H._emitter.on(r,t,n)}static _error(...r){H._emitter._emit("error",r),H._level>=1&&console.error(...r)}static _warn(...r){H._emitter._emit("warn",r),H._level>=2&&console.warn(...r)}static _info(...r){H._emitter._emit("info",r),H._level>=3&&console.info(...r)}};H._level=3,H._emitterInstance=null;var se=H;function p(e){if(!e)throw new Error("Assertion failed.")}var le=e=>e&&e[e.length-1];var d=e=>{let r=0;for(;e.readBits(1)===0&&r<32;)r++;if(r>=32)throw new Error("Invalid exponential-Golomb code.");return(1<<r)-1+e.readBits(r)};var $=e=>{let r=d(e);return(r&1)===0?-(r>>1):r+1>>1};var z=e=>e.constructor===Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),ke=e=>e.constructor===DataView?e:ArrayBuffer.isView(e)?new DataView(e.buffer,e.byteOffset,e.byteLength):new DataView(e);var it={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12};var ot={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18};var st={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9};var Ue=e=>[...e].map(r=>r.toString(16).padStart(2,"0")).join("");var Oe=e=>(e=e>>1&1431655765|(e&1431655765)<<1,e=e>>2&858993459|(e&858993459)<<2,e=e>>4&252645135|(e&252645135)<<4,e=e>>8&16711935|(e&16711935)<<8,e=e>>16&65535|(e&65535)<<16,e>>>0);var de=(e,r,t)=>{let n=0,i=e.length-1,s=-1;for(;n<=i;){let a=n+(i-n+1)/2|0;t(e[a])<=r?(s=a,n=a+1):i=a-1}return s};var De=e=>{throw new Error(`Unexpected value: ${e}`)};var mr=1e6*(1+Number.EPSILON);var pr=(async()=>{})().constructor;var _e=e=>{p(Number.isInteger(e.num)),p(Number.isInteger(e.den)),p(e.den!==0);let r=Math.abs(e.num),t=Math.abs(e.den);for(;t!==0;){let i=r%t;r=t,t=i}let n=r||1;return{num:e.num/n,den:e.den/n}};var ve=class{constructor(){this._listeners=new Map}on(r,t,n){this._listeners.has(r)||this._listeners.set(r,new Set);let i={fn:t,once:n?.once??!1};return this._listeners.get(r).add(i),()=>{this._listeners.get(r)?.delete(i)}}_emit(...r){let[t,n]=r,i=this._listeners.get(t);if(i)for(let s of i){try{s.fn(n)}catch(a){console.error(a)}s.once&&i.delete(s)}}};var ae=k("mediabunny"),m=ne(k("node-av"));var Dt=new Set([m.AV_PIX_FMT_YUVJ411P,m.AV_PIX_FMT_YUVJ420P,m.AV_PIX_FMT_YUVJ422P,m.AV_PIX_FMT_YUVJ440P,m.AV_PIX_FMT_YUVJ444P]),W=class e extends ae.VideoSampleResource{get frame(){if(!this._frame)throw new Error("AvFrameVideoSampleResource has been closed.");return this._frame}constructor(r){if(super(),!(r instanceof m.Frame))throw new TypeError("frame must be a NodeAv.Frame.");if(r.getMediaType()!==m.AVMEDIA_TYPE_VIDEO)throw new Error("AvFrameVideoSampleResource must be initialized with a video frame.");this._frame=r}getFormat(){return et(this.frame.format)}getCodedWidth(){return this.frame.width}getCodedHeight(){return this.frame.height}getSquarePixelWidth(){return this.frame.sampleAspectRatio.num>this.frame.sampleAspectRatio.den?Math.round(this.frame.width*this.frame.sampleAspectRatio.num/this.frame.sampleAspectRatio.den):this.frame.width}getSquarePixelHeight(){return this.frame.sampleAspectRatio.num>this.frame.sampleAspectRatio.den?this.frame.height:Math.round(this.frame.height*this.frame.sampleAspectRatio.den/this.frame.sampleAspectRatio.num)}getColorSpace(){return new ae.VideoSampleColorSpace({primaries:Ce(this.frame.colorPrimaries),transfer:be(this.frame.colorTrc),matrix:xe(this.frame.colorSpace),fullRange:this.frame.colorRange===m.AVCOL_RANGE_JPEG||Dt.has(this.frame.format)?!0:this.frame.colorRange===m.AVCOL_RANGE_MPEG?!1:null})}close(){this.frame.free(),this._frame=null}getDataPlanes(){return p(this.frame.data),this.frame.data.map((r,t)=>({data:z(r),stride:this.frame.linesize[t]}))}async toRgbSample(r,t){let n=this.frame.width,i=this.frame.height,s=new m.SoftwareScaleContext,a=this.frame.format,c=Me("RGBA");s.getContext(n,i,a,n,i,c,m.SWS_BILINEAR);let f=new m.Frame;f.width=n,f.height=i,f.format=c,f.alloc(),f.allocBuffer();let l=this.frame;try{await s.scaleFrame(f,l)}finally{s.freeContext()}return f.sampleAspectRatio=l.sampleAspectRatio,new ae.VideoSample(new e(f),r)}},pe=async(e,r,t)=>{p(e.format!==null),r.format=Me(e.format),r.width=e.codedWidth,r.height=e.codedHeight,r.sampleAspectRatio=new m.Rational(e.pixelAspectRatio.num,e.pixelAspectRatio.den),r.colorPrimaries=je(e.colorSpace.primaries??"unknown")??m.AVCOL_PRI_UNSPECIFIED,r.colorSpace=Ze(e.colorSpace.matrix??"unknown")??m.AVCOL_SPC_UNSPECIFIED,r.colorTrc=Je(e.colorSpace.transfer??"unknown")??m.AVCOL_TRC_UNSPECIFIED,r.colorRange=e.colorSpace.fullRange===!1?m.AVCOL_RANGE_MPEG:e.colorSpace.fullRange===!0?m.AVCOL_RANGE_JPEG:m.AVCOL_RANGE_UNSPECIFIED;let n=e.allocationSize();return(!t||t.byteLength!==n)&&(t=Buffer.from({length:n})),await e.copyTo(t),r.fromBuffer(t),t},at=async(e,r)=>{let t,n=!1;if(e._data instanceof W)t=e._data.frame;else{if(e.format===null)return null;t=new m.Frame,t.alloc(),n=!0,await pe(e,t,null)}let i=[];(e.squarePixelWidth!==e.codedWidth||e.squarePixelHeight!==e.codedHeight)&&(i.push(`scale=${e.squarePixelWidth}:${e.squarePixelHeight}`),i.push("setsar=1")),r.rotation===90?i.push("transpose=1"):r.rotation===180?i.push("transpose=1,transpose=1"):r.rotation===270&&i.push("transpose=2"),i.push(`crop=${Math.round(r.crop.width)}:${Math.round(r.crop.height)}:${Math.round(r.crop.left)}:${Math.round(r.crop.top)}`),r.fit==="fill"?i.push(`scale=${r.width}:${r.height}`):r.fit==="contain"?(i.push(`scale=${r.width}:${r.height}:force_original_aspect_ratio=decrease`),i.push(`pad=${r.width}:${r.height}:(ow-iw)/2:(oh-ih)/2:color=black@0`)):r.fit==="cover"&&(i.push(`scale=${r.width}:${r.height}:force_original_aspect_ratio=increase`),i.push(`crop=${r.width}:${r.height}`)),i.push("setsar=1");let s=new m.FilterGraph;s.alloc();try{let a=`video_size=${t.width}x${t.height}:pix_fmt=${t.format}:time_base=1/1000000:pixel_aspect=${e.pixelAspectRatio.num}/${e.pixelAspectRatio.den}`,c=s.createFilter(m.Filter.getByName("buffer"),"src",a),f=s.createFilter(m.Filter.getByName("buffersink"),"sink");p(c&&f);let l=m.FilterInOut.createList([{name:"in",filterCtx:c,padIdx:0}]),u=m.FilterInOut.createList([{name:"out",filterCtx:f,padIdx:0}]),h=s.parsePtr(`[in]${i.join(",")}[out]`,u,l);m.FFmpegError.throwIfError(h,"FilterGraph.parsePtr");let _=await s.config();m.FFmpegError.throwIfError(_,"FilterGraph.config");let R=await c.buffersrcAddFrame(t);m.FFmpegError.throwIfError(R,"buffersrcAddFrame"),await c.buffersrcAddFrame(null);let g=new m.Frame;g.alloc();let x=await f.buffersinkGetFrame(g);return m.FFmpegError.throwIfError(x,"buffersinkGetFrame"),new ae.VideoSample(new W(g),{timestamp:e.timestamp,duration:e.duration,rotation:0})}finally{s.free(),n&&t.free()}};var Se=class extends ye.CustomVideoDecoder{constructor(){super(...arguments);this.codecContext=null;this.preciseTimings=[]}static supports(t,n){return t==="avc"||t==="hevc"||t==="vp8"||t==="vp9"||t==="av1"}async init(){this.frame=new C.Frame,this.frame.alloc(),this.packet=new C.Packet,this.packet.alloc()}async initCodecContext(t){p(this.codecContext===null);let n=ee[this.codec];p(n!==void 0);let i;if(this.codec==="vp9"&&t.sideData.alpha?i=C.Codec.findDecoderByName(C.FF_DECODER_LIBVPX_VP9)??C.Codec.findDecoder(n):this.config.hardwareAcceleration==="prefer-software"||this.codec==="av1"?i=C.Codec.findDecoder(n):i=await Qe(n)??C.Codec.findDecoder(n),!i)throw new Error(`Unable to obtain libav codec for '${this.codec}'.`);let s=new C.CodecContext;s.allocContext3(i),this.pixelAspectRatio=_e({num:(this.config.displayAspectWidth??this.config.codedWidth??0)*(this.config.codedHeight??0),den:(this.config.displayAspectHeight??this.config.codedHeight??0)*(this.config.codedWidth??0)||1}),s.width=this.config.codedWidth??0,s.height=this.config.codedHeight??0,s.codecType=C.AVMEDIA_TYPE_VIDEO,s.codecId=n,s.extraData=this.config.description?Buffer.from(z(this.config.description)):null,s.sampleAspectRatio=new C.Rational(this.pixelAspectRatio.num,this.pixelAspectRatio.den);let a=C.Dictionary.fromObject({strict:C.FF_COMPLIANCE_STRICT}),c=await s.open2(i,a);C.FFmpegError.throwIfError(c,"Open codec context"),this.codecContext=s}async decode(t){if(this.codecContext===null&&await this.initCodecContext(t),p(this.codecContext),this.packet.isKeyframe=t.type==="key",this.packet.data=Buffer.from(t.data),this.packet.timeBase={num:1,den:1e6},this.packet.pts=BigInt(t.microsecondTimestamp),this.packet.dts=C.AV_NOPTS_VALUE,this.packet.duration=BigInt(t.microsecondDuration),t.sideData.alpha){let a=Buffer.alloc(8+t.sideData.alpha.byteLength);a[7]=1,a.set(t.sideData.alpha,8),this.packet.addSideData(C.AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL,a)}let n=de(this.preciseTimings,t.microsecondTimestamp,a=>a.microsecondTimestamp),i=n!==-1?this.preciseTimings[n]:null;i&&i.microsecondTimestamp===t.microsecondTimestamp?(i.timestamp!==t.timestamp&&(i.timestampIsValid=!1),i.duration!==t.duration&&(i.durationIsValid=!1)):(this.preciseTimings.splice(n+1,0,{microsecondTimestamp:t.microsecondTimestamp,timestamp:t.timestamp,duration:t.duration,timestampIsValid:!0,durationIsValid:!0}),this.preciseTimings.length>128&&this.preciseTimings.shift());let s=await this.codecContext.sendPacket(this.packet);for(C.FFmpegError.throwIfError(s,"Send packet"),this.packet.unref();;){let a=await this.codecContext.receiveFrame(this.frame);if(a===C.AVERROR_EAGAIN||a===C.AVERROR_EOF)break;this.receiveFrame(a)}}receiveFrame(t){C.FFmpegError.throwIfError(t,"Receive frame"),this.frame.sampleAspectRatio=new C.Rational(this.pixelAspectRatio.num,this.pixelAspectRatio.den);let n=Number(this.frame.pts)/1e6,i=Number(this.frame.duration)/1e6,s=de(this.preciseTimings,Number(this.frame.pts),f=>f.microsecondTimestamp),a=s!==-1?this.preciseTimings[s]:null;a&&a.microsecondTimestamp===Number(this.frame.pts)&&(a.timestampIsValid&&(n=a.timestamp),a.durationIsValid&&(i=a.duration));let c=this.frame.clone();if(!c)throw new Error("Frame clone allocation failed.");this.onSample(new ye.VideoSample(new W(c),{timestamp:n,duration:i}))}async flush(){if(!this.codecContext)return;let t=await this.codecContext.sendPacket(null);for(C.FFmpegError.throwIfError(t,"Flush decoder");;){let n=await this.codecContext.receiveFrame(this.frame);if(n===C.AVERROR_EAGAIN||n===C.AVERROR_EOF)break;this.receiveFrame(n)}this.codecContext.flushBuffers()}close(){this.codecContext?.freeContext(),this.frame.free(),this.packet.free()}};var Ae=k("mediabunny"),A=ne(k("node-av"));var X=class e{constructor(r){this.bytes=r;this.pos=0}seekToByte(r){this.pos=8*r}readBit(){let r=Math.floor(this.pos/8),t=this.bytes[r]??0,n=7-(this.pos&7),i=(t&1<<n)>>n;return this.pos++,i}readBits(r){if(r===1)return this.readBit();let t=0;for(let n=0;n<r;n++)t<<=1,t|=this.readBit();return t}writeBits(r,t){let n=this.pos+r;for(let i=this.pos;i<n;i++){let s=Math.floor(i/8),a=this.bytes[s],c=7-(i&7);a&=~(1<<c),a|=(t&1<<n-i-1)>>n-i-1<<c,this.bytes[s]=a}this.pos=n}copyBits(r,t){let n=0;for(n;n<r-7;n+=8)this.writeBits(8,t.readBits(8));let i=r-n;i>0&&this.writeBits(i,t.readBits(i))}readAlignedByte(){if(this.pos%8!==0)throw new Error("Bitstream is not byte-aligned.");let r=this.pos/8,t=this.bytes[r]??0;return this.pos+=8,t}skipBits(r){this.pos+=r}getBitsLeft(){return this.bytes.length*8-this.pos}clone(){let r=new e(this.bytes);return r.pos=this.pos,r}};var ct=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],Lt=[-1,1,2,3,4,5,6,8],lt=e=>{if(!e||e.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");let r=new X(e),t=Le(r),{frequencyIndex:n,sampleRate:i}=He(r),s=r.readBits(4),a=null;s>=1&&s<=7&&(a=Lt[s]);let c=t,f=!1,l=i;if(t===5||t===29)f=t===29,l=He(r).sampleRate,c=Le(r),c===22&&r.skipBits(4);else for(;r.getBitsLeft()>15;){let u=r.pos;if(r.readBits(11)!==695){r.pos=u+1;continue}Le(r)===5&&r.readBits(1)&&(l=He(r).sampleRate,r.getBitsLeft()>11&&r.readBits(11)===1352&&(f=!!r.readBits(1)));break}return a!==null&&a>1&&(f=!1),{objectType:t,coreObjectType:c,frequencyIndex:n,channelConfiguration:s,outputSampleRate:l,outputNumberOfChannels:f&&a===1?2:a}},Le=e=>{let r=e.readBits(5);return r===31?32+e.readBits(6):r},He=e=>{let r=e.readBits(4);return r===15?{frequencyIndex:r,sampleRate:e.readBits(24)}:{frequencyIndex:r,sampleRate:r<ct.length?ct[r]:null}};var dt=e=>{let r=new Uint8Array(7),t=new X(r),{coreObjectType:n,frequencyIndex:i,channelConfiguration:s}=e,a=n-1;return t.writeBits(12,4095),t.writeBits(1,0),t.writeBits(2,0),t.writeBits(1,1),t.writeBits(2,a),t.writeBits(4,i),t.writeBits(1,0),t.writeBits(3,s),t.writeBits(1,0),t.writeBits(1,0),t.writeBits(1,0),t.writeBits(1,0),t.skipBits(13),t.writeBits(11,2047),t.writeBits(2,0),{header:r,bitstream:t}};var zt=["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"],qt=["aac","opus","mp3","vorbis","flac","ac3","eac3","dts"],Lr=[...qt,...zt];var ze=[{maxMacroblocks:99,maxBitrate:64e3,maxDpbMbs:396,level:10},{maxMacroblocks:396,maxBitrate:192e3,maxDpbMbs:900,level:11},{maxMacroblocks:396,maxBitrate:384e3,maxDpbMbs:2376,level:12},{maxMacroblocks:396,maxBitrate:768e3,maxDpbMbs:2376,level:13},{maxMacroblocks:396,maxBitrate:2e6,maxDpbMbs:2376,level:20},{maxMacroblocks:792,maxBitrate:4e6,maxDpbMbs:4752,level:21},{maxMacroblocks:1620,maxBitrate:4e6,maxDpbMbs:8100,level:22},{maxMacroblocks:1620,maxBitrate:1e7,maxDpbMbs:8100,level:30},{maxMacroblocks:3600,maxBitrate:14e6,maxDpbMbs:18e3,level:31},{maxMacroblocks:5120,maxBitrate:2e7,maxDpbMbs:20480,level:32},{maxMacroblocks:8192,maxBitrate:2e7,maxDpbMbs:32768,level:40},{maxMacroblocks:8192,maxBitrate:5e7,maxDpbMbs:32768,level:41},{maxMacroblocks:8704,maxBitrate:5e7,maxDpbMbs:34816,level:42},{maxMacroblocks:22080,maxBitrate:135e6,maxDpbMbs:110400,level:50},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:51},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:52},{maxMacroblocks:139264,maxBitrate:24e7,maxDpbMbs:696320,level:60},{maxMacroblocks:139264,maxBitrate:48e7,maxDpbMbs:696320,level:61},{maxMacroblocks:139264,maxBitrate:8e8,maxDpbMbs:696320,level:62}];var ce=[{maxPictureSize:36864,maxBitrate:2e5,level:10},{maxPictureSize:73728,maxBitrate:8e5,level:11},{maxPictureSize:122880,maxBitrate:18e5,level:20},{maxPictureSize:245760,maxBitrate:36e5,level:21},{maxPictureSize:552960,maxBitrate:72e5,level:30},{maxPictureSize:983040,maxBitrate:12e6,level:31},{maxPictureSize:2228224,maxBitrate:18e6,level:40},{maxPictureSize:2228224,maxBitrate:3e7,level:41},{maxPictureSize:8912896,maxBitrate:6e7,level:50},{maxPictureSize:8912896,maxBitrate:12e7,level:51},{maxPictureSize:8912896,maxBitrate:18e7,level:52},{maxPictureSize:35651584,maxBitrate:18e7,level:60},{maxPictureSize:35651584,maxBitrate:24e7,level:61},{maxPictureSize:35651584,maxBitrate:48e7,level:62}];var ut=".01.01.01.01.00",At=".0.110.01.01.01.0",Wt=["ap4x","ap4h","apch","apcn","apcs","apco"];var ue=e=>{let{codec:r,codecDescription:t,colorSpace:n,avcCodecInfo:i,hevcCodecInfo:s,vp9CodecInfo:a,av1CodecInfo:c,proresFormat:f}=e;if(r==="avc"){if(p(e.avcType!==null),i){let l=new Uint8Array([i.avcProfileIndication,i.profileCompatibility,i.avcLevelIndication]);return`avc${e.avcType}.${Ue(l)}`}if(!t||t.byteLength<4)throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${e.avcType}.${Ue(t.subarray(1,4))}`}else if(r==="hevc"){let l,u,h,_,R,g;if(s)l=s.generalProfileSpace,u=s.generalProfileIdc,h=Oe(s.generalProfileCompatibilityFlags),_=s.generalTierFlag,R=s.generalLevelIdc,g=[...s.generalConstraintIndicatorFlags];else{if(!t||t.byteLength<23)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");let b=ke(t),y=b.getUint8(1);l=y>>6&3,u=y&31,h=Oe(b.getUint32(2)),_=y>>5&1,R=b.getUint8(12),g=[];for(let E=0;E<6;E++)g.push(b.getUint8(6+E))}let x="hev1.";for(x+=["","A","B","C"][l]+u,x+=".",x+=h.toString(16).toUpperCase(),x+=".",x+=_===0?"L":"H",x+=R;g.length>0&&g[g.length-1]===0;)g.pop();return g.length>0&&(x+=".",x+=g.map(b=>b.toString(16).toUpperCase()).join(".")),x}else{if(r==="vp8")return"vp8";if(r==="vp9"){if(!a){let E=e.width*e.height,B=le(ce).level;for(let T of ce)if(E<=T.maxPictureSize){B=T.level;break}return`vp09.00.${B.toString().padStart(2,"0")}.08`}let l=a.profile.toString().padStart(2,"0"),u=a.level.toString().padStart(2,"0"),h=a.bitDepth.toString().padStart(2,"0"),_=a.chromaSubsampling.toString().padStart(2,"0"),R=a.colourPrimaries.toString().padStart(2,"0"),g=a.transferCharacteristics.toString().padStart(2,"0"),x=a.matrixCoefficients.toString().padStart(2,"0"),b=a.videoFullRangeFlag.toString().padStart(2,"0"),y=`vp09.${l}.${u}.${h}.${_}`;return y+=`.${R}.${g}.${x}.${b}`,y.endsWith(ut)&&(y=y.slice(0,-ut.length)),y}else if(r==="av1"){if(!c){let T=e.width*e.height,w=le(ce).level;for(let I of ce)if(T<=I.maxPictureSize){w=I.level;break}return`av01.0.${w.toString().padStart(2,"0")}M.08`}let l=c.profile,u=c.level.toString().padStart(2,"0"),h=c.tier?"H":"M",_=c.bitDepth.toString().padStart(2,"0"),R=c.monochrome?"1":"0",g=100*c.chromaSubsamplingX+10*c.chromaSubsamplingY+1*(c.chromaSubsamplingX&&c.chromaSubsamplingY?c.chromaSamplePosition:0),x=n?.primaries?it[n.primaries]:1,b=n?.transfer?ot[n.transfer]:1,y=n?.matrix?st[n.matrix]:1,E=n?.fullRange?1:0,B=`av01.${l}.${u}${h}.${_}`;return B+=`.${R}.${g.toString().padStart(3,"0")}`,B+=`.${x.toString().padStart(2,"0")}`,B+=`.${b.toString().padStart(2,"0")}`,B+=`.${y.toString().padStart(2,"0")}`,B+=`.${E}`,B.endsWith(At)&&(B=B.slice(0,-At.length)),B}else{if(r==="prores")return f??"apch";r!==null&&De(r)}}throw new TypeError(`Unhandled codec '${r}'.`)};var Hr=["avc1","avc3","hev1","hvc1","vp8","vp09","av01",...Wt];var Be=function*(e){let r=0,t=-1;for(;r<e.length-2;){let n=e.indexOf(0,r);if(n===-1||n>=e.length-2)break;r=n;let i=0;if(r+3<e.length&&e[r+1]===0&&e[r+2]===0&&e[r+3]===1?i=4:e[r+1]===0&&e[r+2]===1&&(i=3),i===0){r++;continue}t!==-1&&r>t&&(yield{offset:t,length:r-t}),t=r+i,r=t}t!==-1&&t<e.length&&(yield{offset:t,length:e.length-t})};var qe=e=>e&31,We=e=>{let r=[],t=e.length;for(let n=0;n<t;n++)n+2<t&&e[n]===0&&e[n+1]===0&&e[n+2]===3?(r.push(0,0),n+=2):r.push(e[n]);return new Uint8Array(r)};var sn=new Uint8Array([0,0,0,1]);var pt=e=>{try{let r=[],t=[],n=[];for(let c of Be(e)){let f=e.subarray(c.offset,c.offset+c.length),l=qe(f[0]);l===7?r.push(f):l===8?t.push(f):l===13&&n.push(f)}if(r.length===0||t.length===0)return null;let i=r[0],s=Xt(i);p(s!==null);let a=s.profileIdc===100||s.profileIdc===110||s.profileIdc===122||s.profileIdc===144;return{configurationVersion:1,avcProfileIndication:s.profileIdc,profileCompatibility:s.constraintFlags,avcLevelIndication:s.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:r,pictureParameterSets:t,chromaFormat:a?s.chromaFormatIdc:null,bitDepthLumaMinus8:a?s.bitDepthLumaMinus8:null,bitDepthChromaMinus8:a?s.bitDepthChromaMinus8:null,sequenceParameterSetExt:a?n:null}}catch(r){return se._error("Error building AVC Decoder Configuration Record:",r),null}},ht=e=>{let r=[];r.push(e.configurationVersion),r.push(e.avcProfileIndication),r.push(e.profileCompatibility),r.push(e.avcLevelIndication),r.push(252|e.lengthSizeMinusOne&3),r.push(224|e.sequenceParameterSets.length&31);for(let t of e.sequenceParameterSets){let n=t.byteLength;r.push(n>>8),r.push(n&255);for(let i=0;i<n;i++)r.push(t[i])}r.push(e.pictureParameterSets.length);for(let t of e.pictureParameterSets){let n=t.byteLength;r.push(n>>8),r.push(n&255);for(let i=0;i<n;i++)r.push(t[i])}if((e.avcProfileIndication===100||e.avcProfileIndication===110||e.avcProfileIndication===122||e.avcProfileIndication===144)&&e.chromaFormat!==null){p(e.bitDepthLumaMinus8!==null),p(e.bitDepthChromaMinus8!==null),p(e.sequenceParameterSetExt!==null),r.push(252|e.chromaFormat&3),r.push(248|e.bitDepthLumaMinus8&7),r.push(248|e.bitDepthChromaMinus8&7),r.push(e.sequenceParameterSetExt.length);for(let t of e.sequenceParameterSetExt){let n=t.byteLength;r.push(n>>8),r.push(n&255);for(let i=0;i<n;i++)r.push(t[i])}}return new Uint8Array(r)};var gt={1:{num:1,den:1},2:{num:12,den:11},3:{num:10,den:11},4:{num:16,den:11},5:{num:40,den:33},6:{num:24,den:11},7:{num:20,den:11},8:{num:32,den:11},9:{num:80,den:33},10:{num:18,den:11},11:{num:15,den:11},12:{num:64,den:33},13:{num:160,den:99},14:{num:4,den:3},15:{num:3,den:2},16:{num:2,den:1}},Xt=e=>{try{let r=We(e),t=new X(r);if(t.skipBits(1),t.skipBits(2),t.readBits(5)!==7)return null;let i=t.readAlignedByte(),s=t.readAlignedByte(),a=t.readAlignedByte();d(t);let c=1,f=0,l=0,u=0;if((i===100||i===110||i===122||i===244||i===44||i===83||i===86||i===118||i===128)&&(c=d(t),c===3&&(u=t.readBits(1)),f=d(t),l=d(t),t.skipBits(1),t.readBits(1))){for(let V=0;V<(c!==3?8:12);V++)if(t.readBits(1)){let Z=V<6?16:64,K=8,L=8;for(let re=0;re<Z;re++){if(L!==0){let ie=$(t);L=(K+ie+256)%256}K=L===0?K:L}}}d(t);let h=d(t);if(h===0)d(t);else if(h===1){t.skipBits(1),$(t),$(t);let M=d(t);for(let V=0;V<M;V++)$(t)}d(t),t.skipBits(1);let _=d(t),R=d(t),g=16*(_+1),x=16*(R+1),b=g,y=x,E=t.readBits(1);if(E||t.skipBits(1),t.skipBits(1),t.readBits(1)){let M=d(t),V=d(t),q=d(t),Z=d(t),K,L;if((u===0?c:0)===0)K=1,L=2-E;else{let ie=c===3?1:2,he=c===1?2:1;K=ie,L=he*(2-E)}b-=K*(M+V),y-=L*(q+Z)}let T=2,w=2,I=2,F=0,N={num:1,den:1},D=null,U=null,G=null,P=null,J=t.pos;if(t.readBits(1)){if(t.readBits(1)){let ie=t.readBits(8);if(ie===255)N={num:t.readBits(16),den:t.readBits(16)};else{let he=gt[ie];he&&(N=he)}}t.readBits(1)&&t.skipBits(1),t.readBits(1)&&(t.skipBits(3),F=t.readBits(1),t.readBits(1)&&(T=t.readBits(8),w=t.readBits(8),I=t.readBits(8))),t.readBits(1)&&(d(t),d(t)),t.readBits(1)&&(t.skipBits(32),t.skipBits(32),t.skipBits(1));let L=t.readBits(1);L&&ft(t);let re=t.readBits(1);re&&ft(t),(L||re)&&t.skipBits(1),t.skipBits(1),G=t.pos,P=t.readBits(1),P&&(t.skipBits(1),d(t),d(t),d(t),d(t),D=d(t),U=d(t))}if(D===null){p(U===null);let M=s&16;if((i===44||i===86||i===100||i===110||i===122||i===244)&&M)D=0,U=0;else{let V=_+1,q=R+1,Z=(2-E)*q,K=ze.find(re=>re.level>=a)??le(ze),L=Math.min(Math.floor(K.maxDpbMbs/(V*Z)),16);D=L,U=L}}return p(U!==null),{emulationUnpreventedBytes:r,profileIdc:i,constraintFlags:s,levelIdc:a,frameMbsOnlyFlag:E,chromaFormatIdc:c,bitDepthLumaMinus8:f,bitDepthChromaMinus8:l,codedWidth:g,codedHeight:x,displayWidth:b,displayHeight:y,pixelAspectRatio:N,colourPrimaries:T,matrixCoefficients:I,transferCharacteristics:w,fullRangeFlag:F,numReorderFrames:D,maxDecFrameBuffering:U,vuiParametersFlagBitOffset:J,bitstreamRestrictionFlagBitOffset:G,bitstreamRestrictionFlag:P}}catch(r){return se._error("Error parsing AVC SPS:",r),null}},ft=e=>{let r=d(e);e.skipBits(4),e.skipBits(4);for(let t=0;t<=r;t++)d(e),d(e),e.skipBits(1);e.skipBits(5),e.skipBits(5),e.skipBits(5),e.skipBits(5)};var Ee=e=>e>>1&63,Gt=e=>{try{let r=new X(We(e));r.skipBits(16),r.readBits(4);let t=r.readBits(3),n=r.readBits(1),{general_profile_space:i,general_tier_flag:s,general_profile_idc:a,general_profile_compatibility_flags:c,general_constraint_indicator_flags:f,general_level_idc:l}=Yt(r,t);d(r);let u=d(r),h=0;u===3&&(h=r.readBits(1));let _=d(r),R=d(r),g=_,x=R;if(r.readBits(1)){let P=d(r),J=d(r),te=d(r),M=d(r),V=1,q=1,Z=h===0?u:0;Z===1?(V=2,q=2):Z===2&&(V=2,q=1),g-=(P+J)*V,x-=(te+M)*q}let b=d(r),y=d(r);d(r);let B=r.readBits(1)?0:t,T=0;for(let P=B;P<=t;P++)d(r),T=d(r),d(r);d(r),d(r),d(r),d(r),d(r),d(r),r.readBits(1)&&r.readBits(1)&&Kt(r),r.skipBits(1),r.skipBits(1),r.readBits(1)&&(r.skipBits(4),r.skipBits(4),d(r),d(r),r.skipBits(1));let w=d(r);if(Qt(r,w),r.readBits(1)){let P=d(r);for(let J=0;J<P;J++)d(r),r.skipBits(1)}r.skipBits(1),r.skipBits(1);let I=2,F=2,N=2,D=0,U=0,G={num:1,den:1};if(r.readBits(1)){let P=jt(r,t);G=P.pixelAspectRatio,I=P.colourPrimaries,F=P.transferCharacteristics,N=P.matrixCoefficients,D=P.fullRangeFlag,U=P.minSpatialSegmentationIdc}return{displayWidth:g,displayHeight:x,pixelAspectRatio:G,colourPrimaries:I,transferCharacteristics:F,matrixCoefficients:N,fullRangeFlag:D,maxDecFrameBuffering:T+1,spsMaxSubLayersMinus1:t,spsTemporalIdNestingFlag:n,generalProfileSpace:i,generalTierFlag:s,generalProfileIdc:a,generalProfileCompatibilityFlags:c,generalConstraintIndicatorFlags:f,generalLevelIdc:l,chromaFormatIdc:u,bitDepthLumaMinus8:b,bitDepthChromaMinus8:y,minSpatialSegmentationIdc:U}}catch(r){return se._error("Error parsing HEVC SPS:",r),null}},Ct=e=>{try{let r=[],t=[],n=[],i=[];for(let l of Be(e)){let u=e.subarray(l.offset,l.offset+l.length),h=Ee(u[0]);h===32?r.push(u):h===33?t.push(u):h===34?n.push(u):(h===39||h===40)&&i.push(u)}if(t.length===0||n.length===0)return null;let s=Gt(t[0]);if(!s)return null;let a=0;if(n.length>0){let l=n[0],u=new X(We(l));u.skipBits(16),d(u),d(u),u.skipBits(1),u.skipBits(1),u.skipBits(3),u.skipBits(1),u.skipBits(1),d(u),d(u),$(u),u.skipBits(1),u.skipBits(1),u.readBits(1)&&d(u),$(u),$(u),u.skipBits(1),u.skipBits(1),u.skipBits(1),u.skipBits(1);let h=u.readBits(1),_=u.readBits(1);!h&&!_?a=0:h&&!_?a=2:!h&&_?a=3:a=0}let c=[...r.length?[{arrayCompleteness:1,nalUnitType:32,nalUnits:r}]:[],...t.length?[{arrayCompleteness:1,nalUnitType:33,nalUnits:t}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:34,nalUnits:n}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:Ee(i[0][0]),nalUnits:i}]:[]];return{configurationVersion:1,generalProfileSpace:s.generalProfileSpace,generalTierFlag:s.generalTierFlag,generalProfileIdc:s.generalProfileIdc,generalProfileCompatibilityFlags:s.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:s.generalConstraintIndicatorFlags,generalLevelIdc:s.generalLevelIdc,minSpatialSegmentationIdc:s.minSpatialSegmentationIdc,parallelismType:a,chromaFormatIdc:s.chromaFormatIdc,bitDepthLumaMinus8:s.bitDepthLumaMinus8,bitDepthChromaMinus8:s.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:s.spsMaxSubLayersMinus1+1,temporalIdNested:s.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:c}}catch(r){return se._error("Error building HEVC Decoder Configuration Record:",r),null}},Yt=(e,r)=>{let t=e.readBits(2),n=e.readBits(1),i=e.readBits(5),s=0;for(let u=0;u<32;u++)s=s<<1|e.readBits(1);let a=new Uint8Array(6);for(let u=0;u<6;u++)a[u]=e.readBits(8);let c=e.readBits(8),f=[],l=[];for(let u=0;u<r;u++)f.push(e.readBits(1)),l.push(e.readBits(1));if(r>0)for(let u=r;u<8;u++)e.skipBits(2);for(let u=0;u<r;u++)f[u]&&e.skipBits(88),l[u]&&e.skipBits(8);return{general_profile_space:t,general_tier_flag:n,general_profile_idc:i,general_profile_compatibility_flags:s,general_constraint_indicator_flags:a,general_level_idc:c}},Kt=e=>{for(let r=0;r<4;r++)for(let t=0;t<(r===3?2:6);t++)if(!e.readBits(1))d(e);else{let i=Math.min(64,1<<4+(r<<1));r>1&&$(e);for(let s=0;s<i;s++)$(e)}},Qt=(e,r)=>{let t=[];for(let n=0;n<r;n++)t[n]=$t(e,n,r,t)},$t=(e,r,t,n)=>{let i=0,s=0,a=0;if(r!==0&&(s=e.readBits(1)),s){if(r===t){let f=d(e);a=r-(f+1)}else a=r-1;e.readBits(1),d(e);let c=n[a]??0;for(let f=0;f<=c;f++)e.readBits(1)||e.readBits(1);i=n[a]}else{let c=d(e),f=d(e);for(let l=0;l<c;l++)d(e),e.readBits(1);for(let l=0;l<f;l++)d(e),e.readBits(1);i=c+f}return i},jt=(e,r)=>{let t=2,n=2,i=2,s=0,a=0,c={num:1,den:1};if(e.readBits(1)){let f=e.readBits(8);if(f===255)c={num:e.readBits(16),den:e.readBits(16)};else{let l=gt[f];l&&(c=l)}}return e.readBits(1)&&e.readBits(1),e.readBits(1)&&(e.readBits(3),s=e.readBits(1),e.readBits(1)&&(t=e.readBits(8),n=e.readBits(8),i=e.readBits(8))),e.readBits(1)&&(d(e),d(e)),e.readBits(1),e.readBits(1),e.readBits(1),e.readBits(1)&&(d(e),d(e),d(e),d(e)),e.readBits(1)&&(e.readBits(32),e.readBits(32),e.readBits(1)&&d(e),e.readBits(1)&&Jt(e,!0,r)),e.readBits(1)&&(e.readBits(1),e.readBits(1),e.readBits(1),a=d(e),d(e),d(e),d(e),d(e)),{pixelAspectRatio:c,colourPrimaries:t,transferCharacteristics:n,matrixCoefficients:i,fullRangeFlag:s,minSpatialSegmentationIdc:a}},Jt=(e,r,t)=>{let n=!1,i=!1,s=!1;r&&(n=e.readBits(1)===1,i=e.readBits(1)===1,(n||i)&&(s=e.readBits(1)===1,s&&(e.readBits(8),e.readBits(5),e.readBits(1),e.readBits(5)),e.readBits(4),e.readBits(4),s&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5)));for(let a=0;a<=t;a++){let c=e.readBits(1)===1,f=!0;c||(f=e.readBits(1)===1);let l=!1;f?d(e):l=e.readBits(1)===1;let u=1;l||(u=d(e)+1),n&&mt(e,u,s),i&&mt(e,u,s)}},mt=(e,r,t)=>{for(let n=0;n<r;n++)d(e),d(e),t&&(d(e),d(e)),e.readBits(1)},bt=e=>{let r=[];r.push(e.configurationVersion),r.push((e.generalProfileSpace&3)<<6|(e.generalTierFlag&1)<<5|e.generalProfileIdc&31),r.push(e.generalProfileCompatibilityFlags>>>24&255),r.push(e.generalProfileCompatibilityFlags>>>16&255),r.push(e.generalProfileCompatibilityFlags>>>8&255),r.push(e.generalProfileCompatibilityFlags&255),r.push(...e.generalConstraintIndicatorFlags),r.push(e.generalLevelIdc&255),r.push(240|e.minSpatialSegmentationIdc>>8&15),r.push(e.minSpatialSegmentationIdc&255),r.push(252|e.parallelismType&3),r.push(252|e.chromaFormatIdc&3),r.push(248|e.bitDepthLumaMinus8&7),r.push(248|e.bitDepthChromaMinus8&7),r.push(e.avgFrameRate>>8&255),r.push(e.avgFrameRate&255),r.push((e.constantFrameRate&3)<<6|(e.numTemporalLayers&7)<<3|(e.temporalIdNested&1)<<2|e.lengthSizeMinusOne&3),r.push(e.arrays.length&255);for(let t of e.arrays){r.push((t.arrayCompleteness&1)<<7|0|t.nalUnitType&63),r.push(t.nalUnits.length>>8&255),r.push(t.nalUnits.length&255);for(let n of t.nalUnits){r.push(n.length>>8&255),r.push(n.length&255);for(let i=0;i<n.length;i++)r.push(n[i])}}return new Uint8Array(r)};var Zt={1:{colourPrimaries:5,transferCharacteristics:6,matrixCoefficients:5},2:{colourPrimaries:1,transferCharacteristics:1,matrixCoefficients:1},3:{colourPrimaries:6,transferCharacteristics:6,matrixCoefficients:6},4:{colourPrimaries:7,transferCharacteristics:7,matrixCoefficients:7},5:{colourPrimaries:9,transferCharacteristics:14,matrixCoefficients:9},7:{colourPrimaries:1,transferCharacteristics:13,matrixCoefficients:0}},xt=e=>{let r=new X(e);if(r.readBits(2)!==2)return null;let n=r.readBits(1),s=(r.readBits(1)<<1)+n;if(s===3&&r.skipBits(1),r.readBits(1)===1||r.readBits(1)!==0||(r.skipBits(2),r.readBits(24)!==4817730))return null;let l=8;s>=2&&(l=r.readBits(1)?12:10);let u=r.readBits(3),h=0,_=0;if(u!==7)if(_=r.readBits(1),s===1||s===3){let N=r.readBits(1),D=r.readBits(1);h=!N&&!D?3:N&&!D?2:1,r.skipBits(1)}else h=1;else h=3,_=1;let R=r.readBits(16),g=r.readBits(16),x=R+1,b=g+1,y=x*b,E=le(ce).level;for(let F of ce)if(y<=F.maxPictureSize){E=F.level;break}let B=Zt[u],T=B?.colourPrimaries??2,w=B?.transferCharacteristics??2,I=B?.matrixCoefficients??2;return{profile:s,level:E,bitDepth:l,chromaSubsampling:h,videoFullRangeFlag:_,colourPrimaries:T,transferCharacteristics:w,matrixCoefficients:I}};var er=function*(e){let r=new X(e),t=()=>{let n=0;for(let i=0;i<8;i++){let s=r.readAlignedByte();if(n+=(s&127)*2**(i*7),!(s&128))break;if(i===7&&s&128)return null}return n>2**32-1?null:n};for(;r.getBitsLeft()>=8;){r.skipBits(1);let n=r.readBits(4),i=r.readBits(1),s=r.readBits(1);r.skipBits(1),i&&r.skipBits(8);let a;if(s){let c=t();if(c===null)return;a=c}else a=Math.floor(r.getBitsLeft()/8);p(r.pos%8===0),yield{type:n,data:e.subarray(r.pos/8,r.pos/8+a)},r.skipBits(a*8)}},vt=e=>{for(let{type:r,data:t}of er(e)){if(r!==1)continue;let n=new X(t),i=n.readBits(3),s=n.readBits(1),a=n.readBits(1),c=0,f=0,l=0;if(a)c=n.readBits(5);else{let U=n.readBits(1),G=0;if(U){if(n.skipBits(32),n.skipBits(32),n.readBits(1)){let M=0;for(;M<32&&!n.readBits(1);)M++;M<32&&n.skipBits(M)}G=n.readBits(1),G&&(l=n.readBits(5),n.skipBits(32),n.skipBits(5),n.skipBits(5))}let P=n.readBits(1),J=n.readBits(5);for(let te=0;te<=J;te++){n.skipBits(12);let M=n.readBits(5);if(te===0&&(c=M),M>7){let V=n.readBits(1);te===0&&(f=V)}if(G&&n.readBits(1)){let q=l+1;n.skipBits(q),n.skipBits(q),n.skipBits(1)}P&&n.readBits(1)&&n.skipBits(4)}}let u=n.readBits(4),h=n.readBits(4),_=u+1;n.skipBits(_);let R=h+1;n.skipBits(R);let g=0;if(a?g=0:g=n.readBits(1),g&&(n.skipBits(4),n.skipBits(3)),n.skipBits(1),n.skipBits(1),n.skipBits(1),!a){n.skipBits(1),n.skipBits(1),n.skipBits(1),n.skipBits(1);let U=n.readBits(1);U&&(n.skipBits(1),n.skipBits(1));let G=n.readBits(1),P=0;G?P=2:P=n.readBits(1),P>0&&(n.readBits(1)||n.skipBits(1)),U&&n.skipBits(3)}n.skipBits(1),n.skipBits(1),n.skipBits(1);let x=n.readBits(1),b=8;i===2&&x?b=n.readBits(1)?12:10:i<=2&&(b=x?10:8);let y=0;i!==1&&(y=n.readBits(1));let E=2,B=2,T=2;n.readBits(1)&&(E=n.readBits(8),B=n.readBits(8),T=n.readBits(8));let I=0,F=1,N=1,D=0;return y?I=n.readBits(1):E===1&&B===13&&T===0?(I=1,F=0,N=0):(I=n.readBits(1),i===0?(F=1,N=1):i===1?(F=0,N=0):b===12?(F=n.readBits(1),N=F?n.readBits(1):0):(F=1,N=0),F&&N&&(D=n.readBits(2))),{profile:i,level:c,tier:f,bitDepth:b,monochrome:y,chromaSubsamplingX:F,chromaSubsamplingY:N,chromaSamplePosition:D,videoFullRangeFlag:I,colourPrimaries:E,transferCharacteristics:B,matrixCoefficients:T}}return null};var an=[64*2,69*2,96*2,64*2,70*2,96*2,80*2,87*2,120*2,80*2,88*2,120*2,96*2,104*2,144*2,96*2,105*2,144*2,112*2,121*2,168*2,112*2,122*2,168*2,128*2,139*2,192*2,128*2,140*2,192*2,160*2,174*2,240*2,160*2,175*2,240*2,192*2,208*2,288*2,192*2,209*2,288*2,224*2,243*2,336*2,224*2,244*2,336*2,256*2,278*2,384*2,256*2,279*2,384*2,320*2,348*2,480*2,320*2,349*2,480*2,384*2,417*2,576*2,384*2,418*2,576*2,448*2,487*2,672*2,448*2,488*2,672*2,512*2,557*2,768*2,512*2,558*2,768*2,640*2,696*2,960*2,640*2,697*2,960*2,768*2,835*2,1152*2,768*2,836*2,1152*2,896*2,975*2,1344*2,896*2,976*2,1344*2,1024*2,1114*2,1536*2,1024*2,1115*2,1536*2,1152*2,1253*2,1728*2,1152*2,1254*2,1728*2,1280*2,1393*2,1920*2,1280*2,1394*2,1920*2];var cn=new Uint8Array([5,4,65,67,45,51]),ln=new Uint8Array([5,4,69,65,67,51]);var tr={apco:A.AV_PROFILE_PRORES_PROXY,apcs:A.AV_PROFILE_PRORES_LT,apcn:A.AV_PROFILE_PRORES_STANDARD,apch:A.AV_PROFILE_PRORES_HQ,ap4h:A.AV_PROFILE_PRORES_4444,ap4x:A.AV_PROFILE_PRORES_XQ},Ie=class extends Ae.CustomVideoEncoder{constructor(){super(...arguments);this.codecContext=null;this.scaler=null;this.dstFrame=null;this.lastBuffer=null;this.packetEmitted=!1;this.lastScalerKey=null;this.quantizer=null;this.preciseTimings=[]}static supports(t,n){return n.bitrateMode==="quantizer"?t==="avc"||t==="hevc"||t==="vp9"||t==="av1":t==="avc"||t==="hevc"||t==="vp8"||t==="vp9"||t==="av1"||t==="prores"}async init(){this.frame=new A.Frame,this.frame.alloc(),this.frame.timeBase=new A.Rational(1,1e6),this.packet=new A.Packet,this.packet.alloc();let t=ee[this.codec];p(t!==void 0);let n=()=>{if(this.codec==="prores"){let s=A.Codec.findEncoderByName(A.FF_ENCODER_PRORES_KS);if(s)return s}return A.Codec.findEncoder(t)},i=null;if(this.codec==="vp9"&&this.config.alpha==="keep")i=A.Codec.findEncoderByName(A.FF_ENCODER_LIBVPX_VP9)??A.Codec.findEncoder(t);else if(this.config.hardwareAcceleration==="prefer-software")i=n();else{let s=await $e(t);s&&this.config.bitrateMode==="quantizer"&&!s.name?.endsWith("_nvenc")&&(s=null),i=s??n()}if(!i)throw new Error(`Unable to obtain libav codec for '${this.codec}'.`);this.avCodec=i,this.config.bitrateMode!=="quantizer"&&await this.createCodecContext()}async createCodecContext(){p(this.codecContext===null);let t=new A.CodecContext;t.allocContext3(this.avCodec);let n=A.AV_PIX_FMT_YUV420P;this.avCodec.pixelFormats&&(this.avCodec.pixelFormats.includes(A.AV_PIX_FMT_YUV420P)||(n=this.avCodec.pixelFormats[0]),this.config.alpha==="keep"&&(this.avCodec.pixelFormats.includes(A.AV_PIX_FMT_YUVA420P)?n=A.AV_PIX_FMT_YUVA420P:n=A.avcodecFindBestPixFmtOfList(this.avCodec.pixelFormats,A.AV_PIX_FMT_YUVA444P12LE)));let i=_e({num:(this.config.displayWidth??this.config.width)*this.config.height,den:(this.config.displayHeight??this.config.height)*this.config.width});t.width=this.config.width,t.height=this.config.height,t.pixelFormat=n,t.timeBase=new A.Rational(1,1e6),t.gopSize=60,t.framerate=new A.Rational(Math.round(this.config.framerate??0)||30,1),t.bitRate=this.config.bitrateMode==="quantizer"?0n:BigInt(this.config.bitrate??new Ae.Quality("medium")._toVideoBitrate(this.codec,this.config.width,this.config.height)),t.sampleAspectRatio=new A.Rational(i.num,i.den),this.config.bitrateMode==="constant"&&(t.rcMinRate=t.bitRate,t.rcMaxRate=t.bitRate);let s=this.config.latencyMode==="realtime";if(this.avCodec.name==="libx264"?s&&(t.setOption("tune","zerolatency"),t.setOption("preset","ultrafast")):this.avCodec.name==="libx265"?(t.setOption("x265-params","log-level=error"),s&&(t.setOption("tune","zerolatency"),t.setOption("preset","ultrafast"))):this.avCodec.name==="libvpx"?(s&&t.setOption("deadline","realtime"),t.setOption("cpu-used","8")):this.avCodec.name==="libvpx-vp9"?(t.setOption("deadline","realtime"),s?t.setOption("cpu-used","8"):t.setOption("cpu-used","5")):this.avCodec.name==="libsvtav1"?(process.env.SVT_LOG="1",s&&t.setOption("preset","12")):(this.avCodec.name==="h264_nvenc"||this.avCodec.name==="hevc_nvenc")&&t.setOption("forced-idr","1"),this.config.bitrateMode==="quantizer"){p(this.quantizer!==null);let c;if(this.avCodec.name==="libaom-av1"||this.avCodec.name==="libsvtav1"?c=Math.round(this.quantizer/4):c=this.quantizer,this.avCodec.name==="libx264"||this.avCodec.name==="libx265")t.setOption("qp",String(c));else if(this.avCodec.name==="libvpx-vp9"||this.avCodec.name==="libaom-av1")t.setOption("crf",String(c));else if(this.avCodec.name==="libsvtav1")t.setOption("qp",String(c));else if(this.avCodec.name==="librav1e")t.setOption("qp",String(c));else if(this.avCodec.name?.endsWith("_nvenc"))t.setOption("rc","constqp"),t.setOption("qp",String(c));else throw new Error(`Encoder '${this.avCodec.name}' cannot be used for quantizer-based encoding.`);t.qMin=c,t.qMax=c}if(this.codec==="prores"){let c=tr[this.config.codec];p(c!==void 0),t.setOption("profile",String(c))}let a=await t.open2();A.FFmpegError.throwIfError(a,"Open codec context"),this.codecContext=t}async encode(t,n){if(this.config.bitrateMode==="quantizer"){let l;if(this.codec==="avc"?l=n.avc?.quantizer:this.codec==="hevc"?l=n.hevc?.quantizer:this.codec==="vp9"?l=n.vp9?.quantizer:l=n.av1?.quantizer,p(l!=null),this.codecContext!==null&&l!==this.quantizer){let u=await this.codecContext.sendFrame(null);for(A.FFmpegError.throwIfError(u,"Send frame");;){let h=await this.codecContext.receivePacket(this.packet);if(h===A.AVERROR_EAGAIN||h===A.AVERROR_EOF)break;this.receivePacket(h)}this.codecContext.freeContext(),this.codecContext=null}this.quantizer=l}if(this.codecContext===null&&await this.createCodecContext(),p(this.codecContext),t._data instanceof W)this.frame.unref(),this.frame.ref(t._data.frame);else{if(t.format===null)throw new Error("Cannot encode foreign VideoSample with unknown (null) format.");this.lastBuffer=await pe(t,this.frame,this.lastBuffer)}let i=this.frame;if(this.codecContext.pixelFormat!==this.frame.format||this.codecContext.width!==this.frame.width||this.codecContext.height!==this.frame.height){this.scaler||(this.scaler=new A.SoftwareScaleContext);let l=`${this.frame.width}x${this.frame.height}:${this.frame.format}`;if(l!==this.lastScalerKey){this.scaler.getContext(this.frame.width,this.frame.height,this.frame.format,this.codecContext.width,this.codecContext.height,this.codecContext.pixelFormat,A.SWS_FAST_BILINEAR),this.lastScalerKey=l;let h=this.scaler.initContext();A.FFmpegError.throwIfError(h,"initContext")}this.dstFrame||(this.dstFrame=new A.Frame,this.dstFrame.alloc(),this.dstFrame.width=this.codecContext.width,this.dstFrame.height=this.codecContext.height,this.dstFrame.format=this.codecContext.pixelFormat,this.dstFrame.allocBuffer()),await this.scaler.scaleFrame(this.dstFrame,this.frame),this.dstFrame.copyProps(this.frame),i=this.dstFrame}i.pts=BigInt(t.microsecondTimestamp),i.duration=BigInt(t.microsecondDuration),i.timeBase=new A.Rational(1,1e6),i.pictType=n?.keyFrame?A.AV_PICTURE_TYPE_I:A.AV_PICTURE_TYPE_NONE,i.keyFrame=n?.keyFrame?1:0;let a=de(this.preciseTimings,t.microsecondTimestamp,l=>l.microsecondTimestamp),c=a!==-1?this.preciseTimings[a]:null;c&&c.microsecondTimestamp===t.microsecondTimestamp?(c.timestamp!==t.timestamp&&(c.timestampIsValid=!1),c.duration!==t.duration&&(c.durationIsValid=!1)):(this.preciseTimings.splice(a+1,0,{microsecondTimestamp:t.microsecondTimestamp,timestamp:t.timestamp,duration:t.duration,timestampIsValid:!0,durationIsValid:!0}),this.preciseTimings.length>128&&this.preciseTimings.shift());let f=await this.codecContext.sendFrame(i);for(A.FFmpegError.throwIfError(f,"Send frame");;){let l=await this.codecContext.receivePacket(this.packet);if(l===A.AVERROR_EAGAIN||l===A.AVERROR_EOF)break;this.receivePacket(l)}}receivePacket(t){if(p(this.codecContext),A.FFmpegError.throwIfError(t,"Receive packet"),!this.packet.data)return;let n=z(this.packet.data),i=Number(this.packet.pts)/1e6,s=Number(this.packet.duration)/1e6,a=de(this.preciseTimings,Number(this.packet.pts),g=>g.microsecondTimestamp),c=a!==-1?this.preciseTimings[a]:null;c&&c.microsecondTimestamp===Number(this.packet.pts)&&(c.timestampIsValid&&(i=c.timestamp),c.durationIsValid&&(s=c.duration));let f={},l=null,u=null;if(this.codec==="avc"||this.codec==="hevc"){let g=!1;if(this.codec==="avc"?g=this.config.avc?.format==="annexb":g=this.config.hevc?.format==="annexb",!this.packetEmitted){let x;if(this.codec==="avc"){let b=pt(this.packet.data);if(!b)throw new Error("Invalid AVC data, could not extract decoder configuration record.");x=ht(b)}else{let b=Ct(this.packet.data);if(!b)throw new Error("Invalid HEVC data, could not extract decoder configuration record.");x=bt(b)}l=ue({width:this.config.width,height:this.config.height,codec:this.codec,codecDescription:x,colorSpace:null,avcType:1,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null,proresFormat:null}),g||(u=x)}if(!g){let b=[];for(let w of Be(n))if(this.codec==="avc"){let I=qe(n[w.offset]);I!==7&&I!==8&&I!==13&&b.push(w)}else{let I=Ee(n[w.offset]);I!==33&&I!==34&&I!==32&&b.push(w)}let y=0;for(let w of b)y+=4+w.length;let E=new Uint8Array(y),B=new DataView(E.buffer),T=0;for(let w of b){let I=w.length;B.setUint32(T,I,!1),T+=4,E.set(n.subarray(w.offset,w.offset+w.length),T),T+=w.length}n=E}}else if(this.codec==="vp8")this.packetEmitted||(l=ue({width:this.config.width,height:this.config.height,codec:"vp8",codecDescription:null,colorSpace:null,avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null,proresFormat:null}));else if(this.codec==="vp9"){if(!this.packetEmitted){let g=xt(n);l=ue({width:this.config.width,height:this.config.height,codec:"vp9",codecDescription:null,colorSpace:null,avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:g,av1CodecInfo:null,proresFormat:null})}}else if(this.codec==="av1"){if(!this.packetEmitted){let g=vt(n);l=ue({width:this.config.width,height:this.config.height,codec:"av1",codecDescription:null,colorSpace:null,avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:g,proresFormat:null})}}else if(this.codec==="prores")this.packetEmitted||(l=ue({width:this.config.width,height:this.config.height,codec:"prores",codecDescription:null,colorSpace:null,avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null,proresFormat:this.config.codec}));else throw new Error("Unreachable.");let h={},_=this.packet.getSideData(A.AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL);_&&(h.alpha=z(_).subarray(8));let R=new Ae.EncodedPacket(n,this.packet.isKeyframe?"key":"delta",i,s,void 0,void 0,h);l!==null&&(f.decoderConfig={codec:l,codedWidth:this.codecContext.width,codedHeight:this.codecContext.height,displayAspectWidth:this.config.displayWidth??this.codecContext.width,displayAspectHeight:this.config.displayHeight??this.codecContext.height,description:u??void 0,colorSpace:{primaries:Ce(this.codecContext.colorPrimaries),matrix:xe(this.codecContext.colorSpace),transfer:be(this.codecContext.colorTrc),fullRange:this.codecContext.colorRange===A.AVCOL_RANGE_JPEG?!0:this.codecContext.colorRange===A.AVCOL_RANGE_MPEG?!1:void 0}}),this.packetEmitted=!0,this.onPacket(R,f)}async flush(){if(this.codecContext){let t=await this.codecContext.sendFrame(null);for(A.FFmpegError.throwIfError(t,"Send frame");;){let n=await this.codecContext.receivePacket(this.packet);if(n===A.AVERROR_EAGAIN||n===A.AVERROR_EOF)break;this.receivePacket(n)}this.codecContext.freeContext(),this.codecContext=null}this.packetEmitted=!1}close(){this.codecContext?.freeContext(),this.frame.free(),this.packet.free(),this.scaler?.freeContext(),this.dstFrame?.free()}};var Te=k("mediabunny"),S=ne(k("node-av"));var _t=k("mediabunny"),fe=ne(k("node-av"));var j=class extends _t.AudioSampleResource{get frame(){if(!this._frame)throw new Error("AvFrameAudioSampleResource has been closed.");return this._frame}constructor(r){if(super(),!(r instanceof fe.Frame))throw new TypeError("frame must be a NodeAv.Frame.");if(r.getMediaType()!==fe.AVMEDIA_TYPE_AUDIO)throw new Error("AvFrameAudioSampleResource must be initialized with an audio frame.");this._frame=r}getFormat(){let r=tt(this.frame.format);if(r===null){let t=fe.avGetSampleFmtName(this.frame.format);throw new TypeError(`Unsupported audio sample format: ${t} (${this.frame.format})`)}return r}getSampleRate(){return this.frame.sampleRate}getNumberOfChannels(){return this.frame.channels}getNumberOfFrames(){return this.frame.nbSamples}getTimestamp(){return Number(this.frame.pts)/this.frame.timeBase.den}close(){this.frame.free(),this._frame=null}getDataPlane(r){return p(this.frame.data&&r<this.frame.data.length),z(this.frame.data[r])}},we=(e,r)=>{r.format=rt(e.format),r.nbSamples=e.numberOfFrames,r.sampleRate=e.sampleRate,r.channelLayout=oe(e.numberOfChannels),r.allocBuffer(),p(r.data);for(let t=0;t<r.data.length;t++)e.copyTo(r.data[t],{planeIndex:t})};var Pe=class extends Te.CustomAudioDecoder{constructor(){super(...arguments);this.codecContext=null}static supports(t,n){return t==="aac"||t==="opus"||t==="mp3"||t==="vorbis"||t==="flac"||t==="ac3"||t==="eac3"||t==="dts"}async init(){this.frame=new S.Frame,this.frame.alloc(),this.packet=new S.Packet,this.packet.alloc();let t=ee[this.codec];p(t!==void 0);let n=S.Codec.findDecoder(t);if(n===null)throw new Error(`Unable to obtain libav codec for '${this.codec}'.`);let i=new S.CodecContext;i.allocContext3(n),i.sampleRate=this.config.sampleRate,i.channelLayout=oe(this.config.numberOfChannels),i.timeBase=new S.Rational(1,this.config.sampleRate),i.codecType=S.AVMEDIA_TYPE_AUDIO,i.codecId=t,i.extraData=this.config.description?Buffer.from(z(this.config.description)):null;let s=await i.open2();S.FFmpegError.throwIfError(s,"Open codec context"),this.codecContext=i}async decode(t){p(this.codecContext),this.packet.isKeyframe=t.type==="key",this.packet.data=Buffer.from(t.data),this.packet.timeBase={num:1,den:this.config.sampleRate},this.packet.pts=BigInt(Math.round(t.timestamp*this.config.sampleRate)),this.packet.dts=S.AV_NOPTS_VALUE,this.packet.duration=BigInt(Math.round(t.duration*this.config.sampleRate));let n=await this.codecContext.sendPacket(this.packet);for(S.FFmpegError.throwIfError(n,"Send packet"),this.packet.unref();;){let i=await this.codecContext.receiveFrame(this.frame);if(i===S.AVERROR_EAGAIN||i===S.AVERROR_EOF)break;this.receiveFrame(i)}}receiveFrame(t){S.FFmpegError.throwIfError(t,"Receive frame");let n=this.frame.clone();if(!n)throw new Error("Allocation failure during frame clone.");n.timeBase=new S.Rational(1,this.config.sampleRate),this.onSample(new Te.AudioSample(new j(n)))}async flush(){p(this.codecContext);let t=await this.codecContext.sendPacket(null);for(S.FFmpegError.throwIfError(t,"Flush decoder");;){let n=await this.codecContext.receiveFrame(this.frame);if(n===S.AVERROR_EAGAIN||n===S.AVERROR_EOF)break;this.receiveFrame(n)}this.codecContext.flushBuffers()}close(){this.codecContext?.freeContext(),this.frame.free(),this.packet.free()}};var me=k("mediabunny"),v=ne(k("node-av"));var St=[8e3,11025,12e3,16e3,22050,24e3,32e3,44100,48e3],yt=[1,2,4,5,6],rr=16384,Et=(e,r,t)=>{if(e<32e3||e>384e4)return!1;let n=t===6,i=t-(n?1:0),s=32*Math.ceil(Math.ceil(e*512/r)/32),a=132+(493+28*32)*i+(n?72:0);return s>=a&&s<=8*rr};var nr=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],ir=[8e3,12e3,16e3,24e3,48e3],or=[8e3,11025,12e3,16e3,22050,24e3,32e3,44100,48e3],Bt=[32e3,44100,48e3],Xe=1024,Re=class extends me.CustomAudioEncoder{constructor(){super(...arguments);this.codecContext=null;this.resampler=null;this.dstFrame=null;this.firstExpectedTimestamp=null;this.outputTimestampOffset=0;this.inputParametersKey=null;this.resamplerInputSampleRate=null;this.nextResamplerPts=null;this.packetEmitted=!1;this.adtsHeaderTemplate=null}static supports(t,n){let{numberOfChannels:i,sampleRate:s}=n;return t==="aac"&&i>=1&&i<=48&&nr.includes(s)||t==="opus"&&i>=1&&i<=255&&ir.includes(s)||t==="mp3"&&i>=1&&i<=2&&or.includes(s)||t==="vorbis"&&i>=1&&i<=255&&s<=2e5||t==="flac"&&i>=1&&i<=8&&s<=655350||t==="ac3"&&i>=1&&i<=6&&Bt.includes(s)||t==="eac3"&&i>=1&&i<=16&&Bt.includes(s)||t==="dts"&&yt.includes(i)&&St.includes(s)&&Et(It(n,t),s,i)}async init(){this.frame=new v.Frame,this.frame.alloc(),this.packet=new v.Packet,this.packet.alloc();let t=ee[this.codec];p(t!==void 0);let n=v.Codec.findEncoder(t);if(!n)throw new Error(`Unable to obtain libav codec for '${this.codec}'.`);this.avCodec=n,await this.createCodecContext()}async createCodecContext(){p(this.codecContext===null);let t=new v.CodecContext;t.allocContext3(this.avCodec);let n=v.AV_SAMPLE_FMT_FLTP;this.avCodec.sampleFormats&&!this.avCodec.sampleFormats.includes(v.AV_SAMPLE_FMT_FLTP)&&(n=this.avCodec.sampleFormats[0]),t.sampleRate=this.config.sampleRate,t.channelLayout=this.codec==="dts"?nt(this.config.numberOfChannels):oe(this.config.numberOfChannels),t.codecType=v.AVMEDIA_TYPE_AUDIO,t.codecId=ee[this.codec],t.sampleFormat=n,t.timeBase=new v.Rational(1,this.config.sampleRate),t.bitRate=BigInt(It(this.config,this.codec)),this.config.bitrateMode==="constant"&&(t.rcMinRate=t.bitRate,t.rcMaxRate=t.bitRate);let i=this.codec==="dts"?v.Dictionary.fromObject({strict:-2}):null,s=await t.open2(this.avCodec,i);v.FFmpegError.throwIfError(s,"Open codec context"),this.codecContext=t}async encode(t){this.codecContext===null&&(await this.createCodecContext(),p(this.codecContext)),this.firstExpectedTimestamp??=t.timestamp,t._data instanceof j?(this.frame.unref(),this.frame.ref(t._data.frame)):we(t,this.frame),this.frame.pts=BigInt(Math.round(t.timestamp*this.config.sampleRate)),this.frame.duration=BigInt(Math.round(t.duration*this.config.sampleRate)),this.frame.timeBase=new v.Rational(1,this.config.sampleRate);let n=`${this.frame.sampleRate}:${this.frame.channels}:${this.frame.format}`;if(this.inputParametersKey!==null&&this.inputParametersKey!==n)throw new Error("Input audio parameters changed. For this audio encoder, you cannot change the input audio parameters over time.");if(this.inputParametersKey=n,this.codecContext.frameSize>0||this.codecContext.sampleFormat!==this.frame.format||this.codecContext.sampleRate!==this.frame.sampleRate||this.codecContext.channels!==this.frame.channels){if(!this.resampler){this.resampler=new v.SoftwareResampleContext,this.resamplerInputSampleRate=this.frame.sampleRate;let a=this.codecContext.channelLayout,c=oe(this.frame.channels),f=this.resampler.allocSetOpts2(a,this.codecContext.sampleFormat,this.codecContext.sampleRate,c,this.frame.format,this.frame.sampleRate);v.FFmpegError.throwIfError(f,"allocSetOpts2");let l=this.resampler.init();v.FFmpegError.throwIfError(l,"init"),this.dstFrame=new v.Frame,this.dstFrame.alloc(),this.dstFrame.channelLayout=a,this.dstFrame.sampleRate=this.codecContext.sampleRate,this.dstFrame.format=this.codecContext.sampleFormat,this.dstFrame.nbSamples=this.codecContext.frameSize||Xe,this.dstFrame.duration=BigInt(this.dstFrame.nbSamples),this.dstFrame.allocBuffer(),this.nextResamplerPts=this.frame.pts}let s=this.frame.data;if(!s)throw new DOMException("Frame has no data","EncodingError");await this.resampler.convert(null,0,s,this.frame.nbSamples),await this.pullResampledFrames()}else await this.sendFrameAndReceivePackets(this.frame)}async pullResampledFrames(){p(this.codecContext),p(this.resampler),p(this.dstFrame),p(this.nextResamplerPts!==null);let t=this.codecContext.frameSize||Xe;for(;!(this.resampler.getOutSamples(0)<t);)await this.resampler.convert(this.dstFrame.data,t,null,0),this.dstFrame.pts=this.nextResamplerPts,await this.sendFrameAndReceivePackets(this.dstFrame),this.nextResamplerPts+=BigInt(t)}async sendFrameAndReceivePackets(t){p(this.codecContext);let n=await this.codecContext.sendFrame(t);for(v.FFmpegError.throwIfError(n,"Send frame");;){let i=await this.codecContext.receivePacket(this.packet);if(i===v.AVERROR_EAGAIN||i===v.AVERROR_EOF)break;this.receivePacket(i)}}receivePacket(t){if(p(this.codecContext),p(this.firstExpectedTimestamp!==null),v.FFmpegError.throwIfError(t,"Receive packet"),!this.packet.data)return;let n=Number(this.packet.pts)/this.codecContext.sampleRate,i=Number(this.packet.duration)/this.codecContext.sampleRate,s=this.packet.data,a;if(this.packetEmitted)a={};else{this.outputTimestampOffset=Math.max(this.firstExpectedTimestamp-n,0);let f=this.config.codec,l=this.codecContext.extraData?z(this.codecContext.extraData):void 0;if(this.codec==="aac"){if(!l)throw new Error("Extradata expected for AAC.");if(this.config.aac?.format==="adts"){let h=lt(l);this.adtsHeaderTemplate=dt(h),l=void 0}}else if(this.codec==="opus"){if(!l)throw new Error("Extradata expected for Opus.")}else if(this.codec==="vorbis"){if(!l)throw new Error("Extradata expected for Vorbis.")}else if(this.codec==="flac"){if(!l)throw new Error("Extradata expected for FLAC.");l=new Uint8Array([102,76,97,67,128,0,0,l.byteLength,...l])}a={decoderConfig:{codec:f,sampleRate:this.codecContext.sampleRate,numberOfChannels:this.codecContext.channels,description:l}}}if(this.adtsHeaderTemplate){let f=s.byteLength+this.adtsHeaderTemplate.header.byteLength;this.adtsHeaderTemplate.bitstream.pos=30,this.adtsHeaderTemplate.bitstream.writeBits(13,f);let l=new Uint8Array(this.adtsHeaderTemplate.header.byteLength+s.byteLength);l.set(this.adtsHeaderTemplate.header,0),l.set(s,this.adtsHeaderTemplate.header.byteLength),s=l}n+=this.outputTimestampOffset;let c=new me.EncodedPacket(s,"key",n,i);this.packetEmitted=!0,this.onPacket(c,a)}async flush(){if(this.codecContext){e:if(this.resampler){p(this.resamplerInputSampleRate!==null);let t=this.resampler.getOutSamples(0);if(t===0)break e;let n=this.codecContext.frameSize||Xe;p(t<n);let i=Math.ceil((n-t)/this.codecContext.sampleRate*this.resamplerInputSampleRate);this.resampler.injectSilence(i),await this.pullResampledFrames()}await this.sendFrameAndReceivePackets(null),this.codecContext.freeContext(),this.codecContext=null,this.packetEmitted=!1,this.firstExpectedTimestamp=null,this.outputTimestampOffset=0,this.adtsHeaderTemplate=null,this.resampler?.free(),this.resampler=null,this.inputParametersKey=null,this.resamplerInputSampleRate=null,this.nextResamplerPts=null,this.dstFrame?.free(),this.dstFrame=null}}close(){this.codecContext?.freeContext(),this.frame.free(),this.packet.free(),this.dstFrame?.free(),this.resampler?.free()}},It=(e,r)=>e.bitrate??new me.Quality("medium")._toAudioBitrate(r)??0;var Pt=k("@mediabunny/prores");var Tt=Symbol.for("@mediabunny/server loaded");globalThis[Tt]&&O.Logging._error(`[WARNING]
|
|
9
|
-
@mediabunny/server was loaded twice. This will likely cause the package not to work correctly. Check if multiple dependencies are importing different versions of @mediabunny/server, or if something is being bundled incorrectly.`);globalThis[
|
|
8
|
+
"use strict";var MediabunnyServer=(()=>{var Rt=Object.create;var ge=Object.defineProperty;var Ft=Object.getOwnPropertyDescriptor;var Vt=Object.getOwnPropertyNames;var Nt=Object.getPrototypeOf,Mt=Object.prototype.hasOwnProperty;var k=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(r,e)=>(typeof require<"u"?require:r)[e]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var kt=(t,r)=>{for(var e in r)ge(t,e,{get:r[e],enumerable:!0})},Ge=(t,r,e,n)=>{if(r&&typeof r=="object"||typeof r=="function")for(let i of Vt(r))!Mt.call(t,i)&&i!==e&&ge(t,i,{get:()=>r[i],enumerable:!(n=Ft(r,i))||n.enumerable});return t};var ne=(t,r,e)=>(e=t!=null?Rt(Nt(t)):{},Ge(r||!t||!t.__esModule?ge(e,"default",{value:t,enumerable:!0}):e,t)),Ut=t=>Ge(ge({},"__esModule",{value:!0}),t);var cr={};kt(cr,{AvFrameAudioSampleResource:()=>j,AvFrameVideoSampleResource:()=>W,_serverOptions:()=>Q,registerMediabunnyServer:()=>sr,toAvFrame:()=>ar});var D=k("mediabunny"),Y=ne(k("node-av"));var ye=k("mediabunny"),C=ne(k("node-av"));var o=ne(k("node-av"));var ee={avc:o.AV_CODEC_ID_H264,hevc:o.AV_CODEC_ID_HEVC,vp8:o.AV_CODEC_ID_VP8,vp9:o.AV_CODEC_ID_VP9,av1:o.AV_CODEC_ID_AV1,prores:o.AV_CODEC_ID_PRORES,aac:o.AV_CODEC_ID_AAC,opus:o.AV_CODEC_ID_OPUS,mp3:o.AV_CODEC_ID_MP3,vorbis:o.AV_CODEC_ID_VORBIS,flac:o.AV_CODEC_ID_FLAC,ac3:o.AV_CODEC_ID_AC3,eac3:o.AV_CODEC_ID_EAC3,dts:o.AV_CODEC_ID_DTS},Fe,Ye=()=>Q.hardwareContext!==void 0&&typeof Q.hardwareContext!="function"?Q.hardwareContext:(Fe===void 0&&(Fe=o.HardwareContext.auto()),Fe),Ke=t=>{if(t!==null&&!(t instanceof o.HardwareContext))throw new TypeError("When serverOptions.hardwareContext is a function, it must return or resolve to a NodeAv.HardwareContext or null.")},Ve=new Map,Qe=async t=>{if(typeof Q.hardwareContext=="function"){let r=await Q.hardwareContext(t);return Ke(r),r?.getDecoderCodec(t)??null}if(!Ve.has(t)){let r=Ye();Ve.set(t,r?.getDecoderCodec(t)??null)}return Ve.get(t)},Ne=new Map,$e=async t=>{if(typeof Q.hardwareContext=="function"){let r=await Q.hardwareContext(t);return Ke(r),r?.getEncoderCodec(t)??null}if(!Ne.has(t)){let r=Ye();Ne.set(t,r?.getEncoderCodec(t)??null)}return Ne.get(t)},je=t=>{switch(t){case"bt709":return o.AVCOL_PRI_BT709;case"bt470bg":return o.AVCOL_PRI_BT470BG;case"smpte170m":return o.AVCOL_PRI_SMPTE170M;case"bt2020":return o.AVCOL_PRI_BT2020;case"smpte432":return o.AVCOL_PRI_SMPTE432}return null},Ce=t=>{switch(t){case o.AVCOL_PRI_BT709:return"bt709";case o.AVCOL_PRI_BT470BG:return"bt470bg";case o.AVCOL_PRI_SMPTE170M:return"smpte170m";case o.AVCOL_PRI_BT2020:return"bt2020";case o.AVCOL_PRI_SMPTE432:return"smpte432"}return null},Je=t=>{switch(t){case"bt709":return o.AVCOL_TRC_BT709;case"smpte170m":return o.AVCOL_TRC_SMPTE170M;case"iec61966-2-1":return o.AVCOL_TRC_IEC61966_2_1;case"linear":return o.AVCOL_TRC_LINEAR;case"pq":return o.AVCOL_TRC_SMPTE2084;case"hlg":return o.AVCOL_TRC_ARIB_STD_B67}return null},xe=t=>{switch(t){case o.AVCOL_TRC_BT709:return"bt709";case o.AVCOL_TRC_SMPTE170M:return"smpte170m";case o.AVCOL_TRC_IEC61966_2_1:return"iec61966-2-1";case o.AVCOL_TRC_LINEAR:return"linear";case o.AVCOL_TRC_SMPTE2084:return"pq";case o.AVCOL_TRC_ARIB_STD_B67:return"hlg"}return null},Ze=t=>{switch(t){case"rgb":return o.AVCOL_SPC_RGB;case"bt709":return o.AVCOL_SPC_BT709;case"bt470bg":return o.AVCOL_SPC_BT470BG;case"smpte170m":return o.AVCOL_SPC_SMPTE170M;case"bt2020-ncl":return o.AVCOL_SPC_BT2020_NCL}return null},be=t=>{switch(t){case o.AVCOL_SPC_RGB:return"rgb";case o.AVCOL_SPC_BT709:return"bt709";case o.AVCOL_SPC_BT470BG:return"bt470bg";case o.AVCOL_SPC_SMPTE170M:return"smpte170m";case o.AVCOL_SPC_BT2020_NCL:return"bt2020-ncl"}return null},et=t=>{switch(t){case o.AV_PIX_FMT_YUV420P:return"I420";case o.AV_PIX_FMT_YUVJ420P:return"I420";case o.AV_PIX_FMT_YUV420P10LE:return"I420P10";case o.AV_PIX_FMT_YUV420P12LE:return"I420P12";case o.AV_PIX_FMT_YUVA420P:return"I420A";case o.AV_PIX_FMT_YUVA420P10LE:return"I420AP10";case o.AV_PIX_FMT_YUV422P:return"I422";case o.AV_PIX_FMT_YUVJ422P:return"I422";case o.AV_PIX_FMT_YUV422P10LE:return"I422P10";case o.AV_PIX_FMT_YUV422P12LE:return"I422P12";case o.AV_PIX_FMT_YUVA422P:return"I422A";case o.AV_PIX_FMT_YUVA422P10LE:return"I422AP10";case o.AV_PIX_FMT_YUVA422P12LE:return"I422AP12";case o.AV_PIX_FMT_YUV444P:return"I444";case o.AV_PIX_FMT_YUVJ444P:return"I444";case o.AV_PIX_FMT_YUV444P10LE:return"I444P10";case o.AV_PIX_FMT_YUV444P12LE:return"I444P12";case o.AV_PIX_FMT_YUVA444P:return"I444A";case o.AV_PIX_FMT_YUVA444P10LE:return"I444AP10";case o.AV_PIX_FMT_YUVA444P12LE:return"I444AP12";case o.AV_PIX_FMT_NV12:return"NV12";case o.AV_PIX_FMT_RGBA:return"RGBA";case o.AV_PIX_FMT_RGB0:return"RGBX";case o.AV_PIX_FMT_BGRA:return"BGRA";case o.AV_PIX_FMT_BGR0:return"BGRX";default:return null}},Me=t=>{switch(t){case"I420":return o.AV_PIX_FMT_YUV420P;case"I420P10":return o.AV_PIX_FMT_YUV420P10LE;case"I420P12":return o.AV_PIX_FMT_YUV420P12LE;case"I420A":return o.AV_PIX_FMT_YUVA420P;case"I420AP10":return o.AV_PIX_FMT_YUVA420P10LE;case"I422":return o.AV_PIX_FMT_YUV422P;case"I422P10":return o.AV_PIX_FMT_YUV422P10LE;case"I422P12":return o.AV_PIX_FMT_YUV422P12LE;case"I422A":return o.AV_PIX_FMT_YUVA422P;case"I422AP10":return o.AV_PIX_FMT_YUVA422P10LE;case"I422AP12":return o.AV_PIX_FMT_YUVA422P12LE;case"I444":return o.AV_PIX_FMT_YUV444P;case"I444P10":return o.AV_PIX_FMT_YUV444P10LE;case"I444P12":return o.AV_PIX_FMT_YUV444P12LE;case"I444A":return o.AV_PIX_FMT_YUVA444P;case"I444AP10":return o.AV_PIX_FMT_YUVA444P10LE;case"I444AP12":return o.AV_PIX_FMT_YUVA444P12LE;case"NV12":return o.AV_PIX_FMT_NV12;case"RGBA":return o.AV_PIX_FMT_RGBA;case"RGBX":return o.AV_PIX_FMT_RGB0;case"BGRA":return o.AV_PIX_FMT_BGRA;case"BGRX":return o.AV_PIX_FMT_BGR0;default:return o.AV_PIX_FMT_NONE}},tt=t=>{switch(t){case o.AV_SAMPLE_FMT_U8:return"u8";case o.AV_SAMPLE_FMT_S16:return"s16";case o.AV_SAMPLE_FMT_S32:return"s32";case o.AV_SAMPLE_FMT_FLT:return"f32";case o.AV_SAMPLE_FMT_U8P:return"u8-planar";case o.AV_SAMPLE_FMT_S16P:return"s16-planar";case o.AV_SAMPLE_FMT_S32P:return"s32-planar";case o.AV_SAMPLE_FMT_FLTP:return"f32-planar";default:return null}},rt=t=>{switch(t){case"u8":return o.AV_SAMPLE_FMT_U8;case"s16":return o.AV_SAMPLE_FMT_S16;case"s32":return o.AV_SAMPLE_FMT_S32;case"f32":return o.AV_SAMPLE_FMT_FLT;case"u8-planar":return o.AV_SAMPLE_FMT_U8P;case"s16-planar":return o.AV_SAMPLE_FMT_S16P;case"s32-planar":return o.AV_SAMPLE_FMT_S32P;case"f32-planar":return o.AV_SAMPLE_FMT_FLTP;default:return o.AV_SAMPLE_FMT_NONE}},oe=t=>{switch(t){case 1:return o.AV_CHANNEL_LAYOUT_MONO;case 2:return o.AV_CHANNEL_LAYOUT_STEREO;case 4:return o.AV_CHANNEL_LAYOUT_QUAD;case 6:return o.AV_CHANNEL_LAYOUT_5POINT1_BACK;case 8:return o.AV_CHANNEL_LAYOUT_7POINT1;default:return{nbChannels:t,order:o.AV_CHANNEL_ORDER_UNSPEC,mask:0n}}},Ot=0x603n,nt=t=>{switch(t){case 1:return o.AV_CHANNEL_LAYOUT_MONO;case 2:return o.AV_CHANNEL_LAYOUT_STEREO;case 4:return{nbChannels:4,order:o.AV_CHANNEL_ORDER_NATIVE,mask:Ot};case 5:return o.AV_CHANNEL_LAYOUT_5POINT0;case 6:return o.AV_CHANNEL_LAYOUT_5POINT1;default:return{nbChannels:t,order:o.AV_CHANNEL_ORDER_UNSPEC,mask:0n}}};var z=class z{constructor(){}static get level(){return z._level}static set level(r){if(r!==0&&r!==1&&r!==2&&r!==3)throw new TypeError("Invalid log level. Use one of the values of the LogLevel enum.");z._level=r}static get _emitter(){return z._emitterInstance??=new ve}static on(r,e,n){return z._emitter.on(r,e,n)}static _error(...r){z._emitter._emit("error",r),z._level>=1&&console.error(...r)}static _warn(...r){z._emitter._emit("warn",r),z._level>=2&&console.warn(...r)}static _info(...r){z._emitter._emit("info",r),z._level>=3&&console.info(...r)}};z._level=3,z._emitterInstance=null;var se=z;function h(t){if(!t)throw new Error("Assertion failed.")}var le=t=>t&&t[t.length-1];var A=t=>{let r=0;for(;t.readBits(1)===0&&r<32;)r++;if(r>=32)throw new Error("Invalid exponential-Golomb code.");return(1<<r)-1+t.readBits(r)};var $=t=>{let r=A(t);return(r&1)===0?-(r>>1):r+1>>1};var O=t=>t.constructor===Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t),ke=t=>t.constructor===DataView?t:ArrayBuffer.isView(t)?new DataView(t.buffer,t.byteOffset,t.byteLength):new DataView(t),mr=typeof globalThis.TextEncoder<"u"?globalThis.TextEncoder:class{constructor(){this.encoding="utf-8"}encode(r=""){let e=new Uint8Array(3*r.length),n=0;for(let i=0;i<r.length;i++){let s=r.charCodeAt(i);if(s<128)e[n++]=s;else if(s<2048)e[n++]=192|s>>6,e[n++]=128|s&63;else if(s<55296||s>57343)e[n++]=224|s>>12,e[n++]=128|s>>6&63,e[n++]=128|s&63;else{let a=i+1<r.length?r.charCodeAt(i+1):0;s<56320&&a>=56320&&a<=57343?(s=65536+(s-55296<<10)+(a-56320),i++,e[n++]=240|s>>18,e[n++]=128|s>>12&63,e[n++]=128|s>>6&63,e[n++]=128|s&63):(e[n++]=239,e[n++]=191,e[n++]=189)}}return e.slice(0,n)}},hr=typeof globalThis.TextDecoder<"u"?globalThis.TextDecoder:class{constructor(r="utf-8"){let e=r.trim().toLowerCase();if(e==="utf-8"||e==="utf8"||e==="unicode-1-1-utf-8")this.encoding="utf-8";else if(e==="utf-16le"||e==="utf-16")this.encoding="utf-16le";else if(e==="utf-16be")this.encoding="utf-16be";else throw new RangeError(`The encoding label provided ('${r}') is invalid.`)}decode(r){let e=r?O(r):new Uint8Array(0),n=[];if(this.encoding==="utf-8"){let s=e.length>=3&&e[0]===239&&e[1]===187&&e[2]===191?3:0;for(;s<e.length;){let a=e[s];if(a<128){n.push(a),s++;continue}let c,d;if(a>=194&&a<224)c=1,d=a&31;else if(a>=224&&a<240)c=2,d=a&15;else if(a>=240&&a<245)c=3,d=a&7;else{n.push(65533),s++;continue}let l=a===224?160:a===240?144:128,u=a===237?159:a===244?143:191,m=1;for(;m<=c;m++){let v=s+m<e.length?e[s+m]:0;if(v<l||v>u)break;d=d<<6|v&63,l=128,u=191}s+=m,m<=c?n.push(65533):d>=65536?(d-=65536,n.push(55296|d>>10,56320|d&1023)):n.push(d)}}else{let s=this.encoding==="utf-16le",a=s?255:254,c=s?254:255,d=e.length>=2&&e[0]===a&&e[1]===c?2:0;for(;d+1<e.length;){let l=s?e[d]|e[d+1]<<8:e[d]<<8|e[d+1];if(d+=2,l>=55296&&l<=56319){let u=d+1<e.length?s?e[d]|e[d+1]<<8:e[d]<<8|e[d+1]:-1;u>=56320&&u<=57343?(n.push(l,u),d+=2):n.push(65533)}else l>=56320&&l<=57343?n.push(65533):n.push(l)}d<e.length&&n.push(65533)}let i="";for(let s=0;s<n.length;s+=8192)i+=String.fromCharCode(...n.slice(s,s+8192));return i}};var it={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12};var ot={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18};var st={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9};var Ue=t=>[...t].map(r=>r.toString(16).padStart(2,"0")).join("");var Oe=t=>(t=t>>1&1431655765|(t&1431655765)<<1,t=t>>2&858993459|(t&858993459)<<2,t=t>>4&252645135|(t&252645135)<<4,t=t>>8&16711935|(t&16711935)<<8,t=t>>16&65535|(t&65535)<<16,t>>>0);var de=(t,r,e)=>{let n=0,i=t.length-1,s=-1;for(;n<=i;){let a=n+(i-n+1)/2|0;e(t[a])<=r?(s=a,n=a+1):i=a-1}return s};var De=t=>{throw new Error(`Unexpected value: ${t}`)};var Cr=1e6*(1+Number.EPSILON);var xr=(async()=>{})().constructor;var _e=t=>{h(Number.isInteger(t.num)),h(Number.isInteger(t.den)),h(t.den!==0);let r=Math.abs(t.num),e=Math.abs(t.den);for(;e!==0;){let i=r%e;r=e,e=i}let n=r||1;return{num:t.num/n,den:t.den/n}};var ve=class{constructor(){this._listeners=new Map}on(r,e,n){this._listeners.has(r)||this._listeners.set(r,new Set);let i={fn:e,once:n?.once??!1};return this._listeners.get(r).add(i),()=>{this._listeners.get(r)?.delete(i)}}_emit(...r){let[e,n]=r,i=this._listeners.get(e);if(i)for(let s of i){try{s.fn(n)}catch(a){console.error(a)}s.once&&i.delete(s)}}};var ae=k("mediabunny"),p=ne(k("node-av"));var Dt=new Set([p.AV_PIX_FMT_YUVJ411P,p.AV_PIX_FMT_YUVJ420P,p.AV_PIX_FMT_YUVJ422P,p.AV_PIX_FMT_YUVJ440P,p.AV_PIX_FMT_YUVJ444P]),W=class t extends ae.VideoSampleResource{get frame(){if(!this._frame)throw new Error("AvFrameVideoSampleResource has been closed.");return this._frame}constructor(r){if(super(),!(r instanceof p.Frame))throw new TypeError("frame must be a NodeAv.Frame.");if(r.getMediaType()!==p.AVMEDIA_TYPE_VIDEO)throw new Error("AvFrameVideoSampleResource must be initialized with a video frame.");this._frame=r}getFormat(){return et(this.frame.format)}getCodedWidth(){return this.frame.width}getCodedHeight(){return this.frame.height}getSquarePixelWidth(){return this.frame.sampleAspectRatio.num>this.frame.sampleAspectRatio.den?Math.round(this.frame.width*this.frame.sampleAspectRatio.num/this.frame.sampleAspectRatio.den):this.frame.width}getSquarePixelHeight(){return this.frame.sampleAspectRatio.num>this.frame.sampleAspectRatio.den?this.frame.height:Math.round(this.frame.height*this.frame.sampleAspectRatio.den/this.frame.sampleAspectRatio.num)}getColorSpace(){return new ae.VideoSampleColorSpace({primaries:Ce(this.frame.colorPrimaries),transfer:xe(this.frame.colorTrc),matrix:be(this.frame.colorSpace),fullRange:this.frame.colorRange===p.AVCOL_RANGE_JPEG||Dt.has(this.frame.format)?!0:this.frame.colorRange===p.AVCOL_RANGE_MPEG?!1:null})}close(){this.frame.free(),this._frame=null}getDataPlanes(){return h(this.frame.data),this.frame.data.map((r,e)=>({data:O(r),stride:this.frame.linesize[e]}))}async toRgbSample(r,e){let n=this.frame.width,i=this.frame.height,s=new p.SoftwareScaleContext,a=this.frame.format,c=Me("RGBA");s.getContext(n,i,a,n,i,c,p.SWS_BILINEAR);let d=new p.Frame;d.width=n,d.height=i,d.format=c,d.alloc(),d.allocBuffer();let l=this.frame;try{await s.scaleFrame(d,l)}finally{s.freeContext()}return d.sampleAspectRatio=l.sampleAspectRatio,new ae.VideoSample(new t(d),r)}},pe=async(t,r,e)=>{h(t.format!==null),r.format=Me(t.format),r.width=t.codedWidth,r.height=t.codedHeight,r.sampleAspectRatio=new p.Rational(t.pixelAspectRatio.num,t.pixelAspectRatio.den),r.colorPrimaries=je(t.colorSpace.primaries??"unknown")??p.AVCOL_PRI_UNSPECIFIED,r.colorSpace=Ze(t.colorSpace.matrix??"unknown")??p.AVCOL_SPC_UNSPECIFIED,r.colorTrc=Je(t.colorSpace.transfer??"unknown")??p.AVCOL_TRC_UNSPECIFIED,r.colorRange=t.colorSpace.fullRange===!1?p.AVCOL_RANGE_MPEG:t.colorSpace.fullRange===!0?p.AVCOL_RANGE_JPEG:p.AVCOL_RANGE_UNSPECIFIED;let n=t.allocationSize();return(!e||e.byteLength!==n)&&(e=Buffer.from({length:n})),await t.copyTo(e),r.fromBuffer(e),e},at=async(t,r)=>{let e,n=!1;if(t._data instanceof W)e=t._data.frame;else{if(t.format===null)return null;e=new p.Frame,e.alloc(),n=!0,await pe(t,e,null)}let i=[];(t.squarePixelWidth!==t.codedWidth||t.squarePixelHeight!==t.codedHeight)&&(i.push(`scale=${t.squarePixelWidth}:${t.squarePixelHeight}`),i.push("setsar=1")),r.rotation===90?i.push("transpose=1"):r.rotation===180?i.push("transpose=1,transpose=1"):r.rotation===270&&i.push("transpose=2"),i.push(`crop=${Math.round(r.crop.width)}:${Math.round(r.crop.height)}:${Math.round(r.crop.left)}:${Math.round(r.crop.top)}`),r.fit==="fill"?i.push(`scale=${r.width}:${r.height}`):r.fit==="contain"?(i.push(`scale=${r.width}:${r.height}:force_original_aspect_ratio=decrease`),i.push(`pad=${r.width}:${r.height}:(ow-iw)/2:(oh-ih)/2:color=black@0`)):r.fit==="cover"&&(i.push(`scale=${r.width}:${r.height}:force_original_aspect_ratio=increase`),i.push(`crop=${r.width}:${r.height}`)),i.push("setsar=1");let s=new p.FilterGraph;s.alloc();try{let a=`video_size=${e.width}x${e.height}:pix_fmt=${e.format}:time_base=1/1000000:pixel_aspect=${t.pixelAspectRatio.num}/${t.pixelAspectRatio.den}`,c=s.createFilter(p.Filter.getByName("buffer"),"src",a),d=s.createFilter(p.Filter.getByName("buffersink"),"sink");h(c&&d);let l=p.FilterInOut.createList([{name:"in",filterCtx:c,padIdx:0}]),u=p.FilterInOut.createList([{name:"out",filterCtx:d,padIdx:0}]),m=s.parsePtr(`[in]${i.join(",")}[out]`,u,l);p.FFmpegError.throwIfError(m,"FilterGraph.parsePtr");let v=await s.config();p.FFmpegError.throwIfError(v,"FilterGraph.config");let R=await c.buffersrcAddFrame(e);p.FFmpegError.throwIfError(R,"buffersrcAddFrame"),await c.buffersrcAddFrame(null);let g=new p.Frame;g.alloc();let b=await d.buffersinkGetFrame(g);return p.FFmpegError.throwIfError(b,"buffersinkGetFrame"),new ae.VideoSample(new W(g),{timestamp:t.timestamp,duration:t.duration,rotation:0})}finally{s.free(),n&&e.free()}};var Se=class extends ye.CustomVideoDecoder{constructor(){super(...arguments);this.codecContext=null;this.preciseTimings=[]}static supports(e,n){return e==="avc"||e==="hevc"||e==="vp8"||e==="vp9"||e==="av1"}async init(){this.frame=new C.Frame,this.frame.alloc(),this.packet=new C.Packet,this.packet.alloc()}async initCodecContext(e){h(this.codecContext===null);let n=ee[this.codec];h(n!==void 0);let i;if(this.codec==="vp9"&&e.sideData.alpha?i=C.Codec.findDecoderByName(C.FF_DECODER_LIBVPX_VP9)??C.Codec.findDecoder(n):this.config.hardwareAcceleration==="prefer-software"||this.codec==="av1"?i=C.Codec.findDecoder(n):i=await Qe(n)??C.Codec.findDecoder(n),!i)throw new Error(`Unable to obtain libav codec for '${this.codec}'.`);let s=new C.CodecContext;s.allocContext3(i),this.pixelAspectRatio=_e({num:(this.config.displayAspectWidth??this.config.codedWidth??0)*(this.config.codedHeight??0),den:(this.config.displayAspectHeight??this.config.codedHeight??0)*(this.config.codedWidth??0)||1}),s.width=this.config.codedWidth??0,s.height=this.config.codedHeight??0,s.codecType=C.AVMEDIA_TYPE_VIDEO,s.codecId=n,s.extraData=this.config.description?Buffer.from(O(this.config.description)):null,s.sampleAspectRatio=new C.Rational(this.pixelAspectRatio.num,this.pixelAspectRatio.den);let a=C.Dictionary.fromObject({strict:C.FF_COMPLIANCE_STRICT}),c=await s.open2(i,a);C.FFmpegError.throwIfError(c,"Open codec context"),this.codecContext=s}async decode(e){if(this.codecContext===null&&await this.initCodecContext(e),h(this.codecContext),this.packet.isKeyframe=e.type==="key",this.packet.data=Buffer.from(e.data),this.packet.timeBase={num:1,den:1e6},this.packet.pts=BigInt(e.microsecondTimestamp),this.packet.dts=C.AV_NOPTS_VALUE,this.packet.duration=BigInt(e.microsecondDuration),e.sideData.alpha){let a=Buffer.alloc(8+e.sideData.alpha.byteLength);a[7]=1,a.set(e.sideData.alpha,8),this.packet.addSideData(C.AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL,a)}let n=de(this.preciseTimings,e.microsecondTimestamp,a=>a.microsecondTimestamp),i=n!==-1?this.preciseTimings[n]:null;i&&i.microsecondTimestamp===e.microsecondTimestamp?(i.timestamp!==e.timestamp&&(i.timestampIsValid=!1),i.duration!==e.duration&&(i.durationIsValid=!1)):(this.preciseTimings.splice(n+1,0,{microsecondTimestamp:e.microsecondTimestamp,timestamp:e.timestamp,duration:e.duration,timestampIsValid:!0,durationIsValid:!0}),this.preciseTimings.length>128&&this.preciseTimings.shift());let s=await this.codecContext.sendPacket(this.packet);for(C.FFmpegError.throwIfError(s,"Send packet"),this.packet.unref();;){let a=await this.codecContext.receiveFrame(this.frame);if(a===C.AVERROR_EAGAIN||a===C.AVERROR_EOF)break;this.receiveFrame(a)}}receiveFrame(e){C.FFmpegError.throwIfError(e,"Receive frame"),this.frame.sampleAspectRatio=new C.Rational(this.pixelAspectRatio.num,this.pixelAspectRatio.den);let n=Number(this.frame.pts)/1e6,i=Number(this.frame.duration)/1e6,s=de(this.preciseTimings,Number(this.frame.pts),d=>d.microsecondTimestamp),a=s!==-1?this.preciseTimings[s]:null;a&&a.microsecondTimestamp===Number(this.frame.pts)&&(a.timestampIsValid&&(n=a.timestamp),a.durationIsValid&&(i=a.duration));let c=this.frame.clone();if(!c)throw new Error("Frame clone allocation failed.");this.onSample(new ye.VideoSample(new W(c),{timestamp:n,duration:i}))}async flush(){if(!this.codecContext)return;let e=await this.codecContext.sendPacket(null);for(C.FFmpegError.throwIfError(e,"Flush decoder");;){let n=await this.codecContext.receiveFrame(this.frame);if(n===C.AVERROR_EAGAIN||n===C.AVERROR_EOF)break;this.receiveFrame(n)}this.codecContext.flushBuffers()}close(){this.codecContext?.freeContext(),this.frame.free(),this.packet.free()}};var Ae=k("mediabunny"),f=ne(k("node-av"));var X=class t{constructor(r){this.bytes=r;this.pos=0}seekToByte(r){this.pos=8*r}readBit(){let r=Math.floor(this.pos/8),e=this.bytes[r]??0,n=7-(this.pos&7),i=(e&1<<n)>>n;return this.pos++,i}readBits(r){if(r===1)return this.readBit();let e=0;for(let n=0;n<r;n++)e<<=1,e|=this.readBit();return e}writeBits(r,e){let n=this.pos+r;for(let i=this.pos;i<n;i++){let s=Math.floor(i/8),a=this.bytes[s],c=7-(i&7);a&=~(1<<c),a|=(e&1<<n-i-1)>>n-i-1<<c,this.bytes[s]=a}this.pos=n}copyBits(r,e){let n=0;for(n;n<r-7;n+=8)this.writeBits(8,e.readBits(8));let i=r-n;i>0&&this.writeBits(i,e.readBits(i))}readAlignedByte(){if(this.pos%8!==0)throw new Error("Bitstream is not byte-aligned.");let r=this.pos/8,e=this.bytes[r]??0;return this.pos+=8,e}skipBits(r){this.pos+=r}getBitsLeft(){return this.bytes.length*8-this.pos}clone(){let r=new t(this.bytes);return r.pos=this.pos,r}};var ct=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],Lt=[-1,1,2,3,4,5,6,8],lt=t=>{if(!t||t.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");let r=new X(t),e=Le(r),{frequencyIndex:n,sampleRate:i}=He(r),s=r.readBits(4),a=null;s>=1&&s<=7&&(a=Lt[s]);let c=e,d=!1,l=i;if(e===5||e===29)d=e===29,l=He(r).sampleRate,c=Le(r),c===22&&r.skipBits(4);else for(;r.getBitsLeft()>15;){let u=r.pos;if(r.readBits(11)!==695){r.pos=u+1;continue}Le(r)===5&&r.readBits(1)&&(l=He(r).sampleRate,r.getBitsLeft()>11&&r.readBits(11)===1352&&(d=!!r.readBits(1)));break}return a!==null&&a>1&&(d=!1),{objectType:e,coreObjectType:c,frequencyIndex:n,channelConfiguration:s,outputSampleRate:l,outputNumberOfChannels:d&&a===1?2:a}},Le=t=>{let r=t.readBits(5);return r===31?32+t.readBits(6):r},He=t=>{let r=t.readBits(4);return r===15?{frequencyIndex:r,sampleRate:t.readBits(24)}:{frequencyIndex:r,sampleRate:r<ct.length?ct[r]:null}};var dt=t=>{let r=new Uint8Array(7),e=new X(r),{coreObjectType:n,frequencyIndex:i,channelConfiguration:s}=t,a=n-1;return e.writeBits(12,4095),e.writeBits(1,0),e.writeBits(2,0),e.writeBits(1,1),e.writeBits(2,a),e.writeBits(4,i),e.writeBits(1,0),e.writeBits(3,s),e.writeBits(1,0),e.writeBits(1,0),e.writeBits(1,0),e.writeBits(1,0),e.skipBits(13),e.writeBits(11,2047),e.writeBits(2,0),{header:r,bitstream:e}};var zt=["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"],qt=["aac","opus","mp3","vorbis","flac","ac3","eac3","dts"],Wr=[...qt,...zt];var ze=[{maxMacroblocks:99,maxBitrate:64e3,maxDpbMbs:396,level:10},{maxMacroblocks:396,maxBitrate:192e3,maxDpbMbs:900,level:11},{maxMacroblocks:396,maxBitrate:384e3,maxDpbMbs:2376,level:12},{maxMacroblocks:396,maxBitrate:768e3,maxDpbMbs:2376,level:13},{maxMacroblocks:396,maxBitrate:2e6,maxDpbMbs:2376,level:20},{maxMacroblocks:792,maxBitrate:4e6,maxDpbMbs:4752,level:21},{maxMacroblocks:1620,maxBitrate:4e6,maxDpbMbs:8100,level:22},{maxMacroblocks:1620,maxBitrate:1e7,maxDpbMbs:8100,level:30},{maxMacroblocks:3600,maxBitrate:14e6,maxDpbMbs:18e3,level:31},{maxMacroblocks:5120,maxBitrate:2e7,maxDpbMbs:20480,level:32},{maxMacroblocks:8192,maxBitrate:2e7,maxDpbMbs:32768,level:40},{maxMacroblocks:8192,maxBitrate:5e7,maxDpbMbs:32768,level:41},{maxMacroblocks:8704,maxBitrate:5e7,maxDpbMbs:34816,level:42},{maxMacroblocks:22080,maxBitrate:135e6,maxDpbMbs:110400,level:50},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:51},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:52},{maxMacroblocks:139264,maxBitrate:24e7,maxDpbMbs:696320,level:60},{maxMacroblocks:139264,maxBitrate:48e7,maxDpbMbs:696320,level:61},{maxMacroblocks:139264,maxBitrate:8e8,maxDpbMbs:696320,level:62}];var ce=[{maxPictureSize:36864,maxBitrate:2e5,level:10},{maxPictureSize:73728,maxBitrate:8e5,level:11},{maxPictureSize:122880,maxBitrate:18e5,level:20},{maxPictureSize:245760,maxBitrate:36e5,level:21},{maxPictureSize:552960,maxBitrate:72e5,level:30},{maxPictureSize:983040,maxBitrate:12e6,level:31},{maxPictureSize:2228224,maxBitrate:18e6,level:40},{maxPictureSize:2228224,maxBitrate:3e7,level:41},{maxPictureSize:8912896,maxBitrate:6e7,level:50},{maxPictureSize:8912896,maxBitrate:12e7,level:51},{maxPictureSize:8912896,maxBitrate:18e7,level:52},{maxPictureSize:35651584,maxBitrate:18e7,level:60},{maxPictureSize:35651584,maxBitrate:24e7,level:61},{maxPictureSize:35651584,maxBitrate:48e7,level:62}];var ut=".01.01.01.01.00",At=".0.110.01.01.01.0",Wt=["ap4x","ap4h","apch","apcn","apcs","apco"];var ue=t=>{let{codec:r,codecDescription:e,colorSpace:n,avcCodecInfo:i,hevcCodecInfo:s,vp9CodecInfo:a,av1CodecInfo:c,proresFormat:d}=t;if(r==="avc"){if(h(t.avcType!==null),i){let l=new Uint8Array([i.avcProfileIndication,i.profileCompatibility,i.avcLevelIndication]);return`avc${t.avcType}.${Ue(l)}`}if(!e||e.byteLength<4)throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${t.avcType}.${Ue(e.subarray(1,4))}`}else if(r==="hevc"){let l,u,m,v,R,g;if(s)l=s.generalProfileSpace,u=s.generalProfileIdc,m=Oe(s.generalProfileCompatibilityFlags),v=s.generalTierFlag,R=s.generalLevelIdc,g=[...s.generalConstraintIndicatorFlags];else{if(!e||e.byteLength<23)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");let x=ke(e),y=x.getUint8(1);l=y>>6&3,u=y&31,m=Oe(x.getUint32(2)),v=y>>5&1,R=x.getUint8(12),g=[];for(let E=0;E<6;E++)g.push(x.getUint8(6+E))}let b="hev1.";for(b+=["","A","B","C"][l]+u,b+=".",b+=m.toString(16).toUpperCase(),b+=".",b+=v===0?"L":"H",b+=R;g.length>0&&g[g.length-1]===0;)g.pop();return g.length>0&&(b+=".",b+=g.map(x=>x.toString(16).toUpperCase()).join(".")),b}else{if(r==="vp8")return"vp8";if(r==="vp9"){if(!a){let E=t.width*t.height,B=le(ce).level;for(let P of ce)if(E<=P.maxPictureSize){B=P.level;break}return`vp09.00.${B.toString().padStart(2,"0")}.08`}let l=a.profile.toString().padStart(2,"0"),u=a.level.toString().padStart(2,"0"),m=a.bitDepth.toString().padStart(2,"0"),v=a.chromaSubsampling.toString().padStart(2,"0"),R=a.colourPrimaries.toString().padStart(2,"0"),g=a.transferCharacteristics.toString().padStart(2,"0"),b=a.matrixCoefficients.toString().padStart(2,"0"),x=a.videoFullRangeFlag.toString().padStart(2,"0"),y=`vp09.${l}.${u}.${m}.${v}`;return y+=`.${R}.${g}.${b}.${x}`,y.endsWith(ut)&&(y=y.slice(0,-ut.length)),y}else if(r==="av1"){if(!c){let P=t.width*t.height,I=le(ce).level;for(let w of ce)if(P<=w.maxPictureSize){I=w.level;break}return`av01.0.${I.toString().padStart(2,"0")}M.08`}let l=c.profile,u=c.level.toString().padStart(2,"0"),m=c.tier?"H":"M",v=c.bitDepth.toString().padStart(2,"0"),R=c.monochrome?"1":"0",g=100*c.chromaSubsamplingX+10*c.chromaSubsamplingY+1*(c.chromaSubsamplingX&&c.chromaSubsamplingY?c.chromaSamplePosition:0),b=n?.primaries?it[n.primaries]:1,x=n?.transfer?ot[n.transfer]:1,y=n?.matrix?st[n.matrix]:1,E=n?.fullRange?1:0,B=`av01.${l}.${u}${m}.${v}`;return B+=`.${R}.${g.toString().padStart(3,"0")}`,B+=`.${b.toString().padStart(2,"0")}`,B+=`.${x.toString().padStart(2,"0")}`,B+=`.${y.toString().padStart(2,"0")}`,B+=`.${E}`,B.endsWith(At)&&(B=B.slice(0,-At.length)),B}else{if(r==="prores")return d??"apch";r!==null&&De(r)}}throw new TypeError(`Unhandled codec '${r}'.`)};var Xr=["avc1","avc3","hev1","hvc1","vp8","vp09","av01",...Wt];var Be=function*(t){let r=0,e=-1;for(;r<t.length-2;){let n=t.indexOf(0,r);if(n===-1||n>=t.length-2)break;r=n;let i=0;if(r+3<t.length&&t[r+1]===0&&t[r+2]===0&&t[r+3]===1?i=4:t[r+1]===0&&t[r+2]===1&&(i=3),i===0){r++;continue}e!==-1&&r>e&&(yield{offset:e,length:r-e}),e=r+i,r=e}e!==-1&&e<t.length&&(yield{offset:e,length:t.length-e})};var qe=t=>t&31,We=t=>{let r=[],e=t.length;for(let n=0;n<e;n++)n+2<e&&t[n]===0&&t[n+1]===0&&t[n+2]===3?(r.push(0,0),n+=2):r.push(t[n]);return new Uint8Array(r)};var dn=new Uint8Array([0,0,0,1]);var pt=t=>{try{let r=[],e=[],n=[];for(let c of Be(t)){let d=t.subarray(c.offset,c.offset+c.length),l=qe(d[0]);l===7?r.push(d):l===8?e.push(d):l===13&&n.push(d)}if(r.length===0||e.length===0)return null;let i=r[0],s=Xt(i);h(s!==null);let a=s.profileIdc===100||s.profileIdc===110||s.profileIdc===122||s.profileIdc===144;return{configurationVersion:1,avcProfileIndication:s.profileIdc,profileCompatibility:s.constraintFlags,avcLevelIndication:s.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:r,pictureParameterSets:e,chromaFormat:a?s.chromaFormatIdc:null,bitDepthLumaMinus8:a?s.bitDepthLumaMinus8:null,bitDepthChromaMinus8:a?s.bitDepthChromaMinus8:null,sequenceParameterSetExt:a?n:null}}catch(r){return se._error("Error building AVC Decoder Configuration Record:",r),null}},ht=t=>{let r=[];r.push(t.configurationVersion),r.push(t.avcProfileIndication),r.push(t.profileCompatibility),r.push(t.avcLevelIndication),r.push(252|t.lengthSizeMinusOne&3),r.push(224|t.sequenceParameterSets.length&31);for(let e of t.sequenceParameterSets){let n=e.byteLength;r.push(n>>8),r.push(n&255);for(let i=0;i<n;i++)r.push(e[i])}r.push(t.pictureParameterSets.length);for(let e of t.pictureParameterSets){let n=e.byteLength;r.push(n>>8),r.push(n&255);for(let i=0;i<n;i++)r.push(e[i])}if((t.avcProfileIndication===100||t.avcProfileIndication===110||t.avcProfileIndication===122||t.avcProfileIndication===144)&&t.chromaFormat!==null){h(t.bitDepthLumaMinus8!==null),h(t.bitDepthChromaMinus8!==null),h(t.sequenceParameterSetExt!==null),r.push(252|t.chromaFormat&3),r.push(248|t.bitDepthLumaMinus8&7),r.push(248|t.bitDepthChromaMinus8&7),r.push(t.sequenceParameterSetExt.length);for(let e of t.sequenceParameterSetExt){let n=e.byteLength;r.push(n>>8),r.push(n&255);for(let i=0;i<n;i++)r.push(e[i])}}return new Uint8Array(r)};var gt={1:{num:1,den:1},2:{num:12,den:11},3:{num:10,den:11},4:{num:16,den:11},5:{num:40,den:33},6:{num:24,den:11},7:{num:20,den:11},8:{num:32,den:11},9:{num:80,den:33},10:{num:18,den:11},11:{num:15,den:11},12:{num:64,den:33},13:{num:160,den:99},14:{num:4,den:3},15:{num:3,den:2},16:{num:2,den:1}},Xt=t=>{try{let r=We(t),e=new X(r);if(e.skipBits(1),e.skipBits(2),e.readBits(5)!==7)return null;let i=e.readAlignedByte(),s=e.readAlignedByte(),a=e.readAlignedByte();A(e);let c=1,d=0,l=0,u=0;if((i===100||i===110||i===122||i===244||i===44||i===83||i===86||i===118||i===128)&&(c=A(e),c===3&&(u=e.readBits(1)),d=A(e),l=A(e),e.skipBits(1),e.readBits(1))){for(let V=0;V<(c!==3?8:12);V++)if(e.readBits(1)){let Z=V<6?16:64,K=8,H=8;for(let re=0;re<Z;re++){if(H!==0){let ie=$(e);H=(K+ie+256)%256}K=H===0?K:H}}}A(e);let m=A(e);if(m===0)A(e);else if(m===1){e.skipBits(1),$(e),$(e);let M=A(e);for(let V=0;V<M;V++)$(e)}A(e),e.skipBits(1);let v=A(e),R=A(e),g=16*(v+1),b=16*(R+1),x=g,y=b,E=e.readBits(1);if(E||e.skipBits(1),e.skipBits(1),e.readBits(1)){let M=A(e),V=A(e),q=A(e),Z=A(e),K,H;if((u===0?c:0)===0)K=1,H=2-E;else{let ie=c===3?1:2,he=c===1?2:1;K=ie,H=he*(2-E)}x-=K*(M+V),y-=H*(q+Z)}let P=2,I=2,w=2,F=0,N={num:1,den:1},L=null,U=null,G=null,T=null,J=e.pos;if(e.readBits(1)){if(e.readBits(1)){let ie=e.readBits(8);if(ie===255)N={num:e.readBits(16),den:e.readBits(16)};else{let he=gt[ie];he&&(N=he)}}e.readBits(1)&&e.skipBits(1),e.readBits(1)&&(e.skipBits(3),F=e.readBits(1),e.readBits(1)&&(P=e.readBits(8),I=e.readBits(8),w=e.readBits(8))),e.readBits(1)&&(A(e),A(e)),e.readBits(1)&&(e.skipBits(32),e.skipBits(32),e.skipBits(1));let H=e.readBits(1);H&&ft(e);let re=e.readBits(1);re&&ft(e),(H||re)&&e.skipBits(1),e.skipBits(1),G=e.pos,T=e.readBits(1),T&&(e.skipBits(1),A(e),A(e),A(e),A(e),L=A(e),U=A(e))}if(L===null){h(U===null);let M=s&16;if((i===44||i===86||i===100||i===110||i===122||i===244)&&M)L=0,U=0;else{let V=v+1,q=R+1,Z=(2-E)*q,K=ze.find(re=>re.level>=a)??le(ze),H=Math.min(Math.floor(K.maxDpbMbs/(V*Z)),16);L=H,U=H}}return h(U!==null),{emulationUnpreventedBytes:r,profileIdc:i,constraintFlags:s,levelIdc:a,frameMbsOnlyFlag:E,chromaFormatIdc:c,bitDepthLumaMinus8:d,bitDepthChromaMinus8:l,codedWidth:g,codedHeight:b,displayWidth:x,displayHeight:y,pixelAspectRatio:N,colourPrimaries:P,matrixCoefficients:w,transferCharacteristics:I,fullRangeFlag:F,numReorderFrames:L,maxDecFrameBuffering:U,vuiParametersFlagBitOffset:J,bitstreamRestrictionFlagBitOffset:G,bitstreamRestrictionFlag:T}}catch(r){return se._error("Error parsing AVC SPS:",r),null}},ft=t=>{let r=A(t);t.skipBits(4),t.skipBits(4);for(let e=0;e<=r;e++)A(t),A(t),t.skipBits(1);t.skipBits(5),t.skipBits(5),t.skipBits(5),t.skipBits(5)};var Ee=t=>t>>1&63,Gt=t=>{try{let r=new X(We(t));r.skipBits(16),r.readBits(4);let e=r.readBits(3),n=r.readBits(1),{general_profile_space:i,general_tier_flag:s,general_profile_idc:a,general_profile_compatibility_flags:c,general_constraint_indicator_flags:d,general_level_idc:l}=Yt(r,e);A(r);let u=A(r),m=0;u===3&&(m=r.readBits(1));let v=A(r),R=A(r),g=v,b=R;if(r.readBits(1)){let T=A(r),J=A(r),te=A(r),M=A(r),V=1,q=1,Z=m===0?u:0;Z===1?(V=2,q=2):Z===2&&(V=2,q=1),g-=(T+J)*V,b-=(te+M)*q}let x=A(r),y=A(r);A(r);let B=r.readBits(1)?0:e,P=0;for(let T=B;T<=e;T++)A(r),P=A(r),A(r);A(r),A(r),A(r),A(r),A(r),A(r),r.readBits(1)&&r.readBits(1)&&Kt(r),r.skipBits(1),r.skipBits(1),r.readBits(1)&&(r.skipBits(4),r.skipBits(4),A(r),A(r),r.skipBits(1));let I=A(r);if(Qt(r,I),r.readBits(1)){let T=A(r);for(let J=0;J<T;J++)A(r),r.skipBits(1)}r.skipBits(1),r.skipBits(1);let w=2,F=2,N=2,L=0,U=0,G={num:1,den:1};if(r.readBits(1)){let T=jt(r,e);G=T.pixelAspectRatio,w=T.colourPrimaries,F=T.transferCharacteristics,N=T.matrixCoefficients,L=T.fullRangeFlag,U=T.minSpatialSegmentationIdc}return{displayWidth:g,displayHeight:b,pixelAspectRatio:G,colourPrimaries:w,transferCharacteristics:F,matrixCoefficients:N,fullRangeFlag:L,maxDecFrameBuffering:P+1,spsMaxSubLayersMinus1:e,spsTemporalIdNestingFlag:n,generalProfileSpace:i,generalTierFlag:s,generalProfileIdc:a,generalProfileCompatibilityFlags:c,generalConstraintIndicatorFlags:d,generalLevelIdc:l,chromaFormatIdc:u,bitDepthLumaMinus8:x,bitDepthChromaMinus8:y,minSpatialSegmentationIdc:U}}catch(r){return se._error("Error parsing HEVC SPS:",r),null}},Ct=t=>{try{let r=[],e=[],n=[],i=[];for(let l of Be(t)){let u=t.subarray(l.offset,l.offset+l.length),m=Ee(u[0]);m===32?r.push(u):m===33?e.push(u):m===34?n.push(u):(m===39||m===40)&&i.push(u)}if(e.length===0||n.length===0)return null;let s=Gt(e[0]);if(!s)return null;let a=0;if(n.length>0){let l=n[0],u=new X(We(l));u.skipBits(16),A(u),A(u),u.skipBits(1),u.skipBits(1),u.skipBits(3),u.skipBits(1),u.skipBits(1),A(u),A(u),$(u),u.skipBits(1),u.skipBits(1),u.readBits(1)&&A(u),$(u),$(u),u.skipBits(1),u.skipBits(1),u.skipBits(1),u.skipBits(1);let m=u.readBits(1),v=u.readBits(1);!m&&!v?a=0:m&&!v?a=2:!m&&v?a=3:a=0}let c=[...r.length?[{arrayCompleteness:1,nalUnitType:32,nalUnits:r}]:[],...e.length?[{arrayCompleteness:1,nalUnitType:33,nalUnits:e}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:34,nalUnits:n}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:Ee(i[0][0]),nalUnits:i}]:[]];return{configurationVersion:1,generalProfileSpace:s.generalProfileSpace,generalTierFlag:s.generalTierFlag,generalProfileIdc:s.generalProfileIdc,generalProfileCompatibilityFlags:s.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:s.generalConstraintIndicatorFlags,generalLevelIdc:s.generalLevelIdc,minSpatialSegmentationIdc:s.minSpatialSegmentationIdc,parallelismType:a,chromaFormatIdc:s.chromaFormatIdc,bitDepthLumaMinus8:s.bitDepthLumaMinus8,bitDepthChromaMinus8:s.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:s.spsMaxSubLayersMinus1+1,temporalIdNested:s.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:c}}catch(r){return se._error("Error building HEVC Decoder Configuration Record:",r),null}},Yt=(t,r)=>{let e=t.readBits(2),n=t.readBits(1),i=t.readBits(5),s=0;for(let u=0;u<32;u++)s=s<<1|t.readBits(1);let a=new Uint8Array(6);for(let u=0;u<6;u++)a[u]=t.readBits(8);let c=t.readBits(8),d=[],l=[];for(let u=0;u<r;u++)d.push(t.readBits(1)),l.push(t.readBits(1));if(r>0)for(let u=r;u<8;u++)t.skipBits(2);for(let u=0;u<r;u++)d[u]&&t.skipBits(88),l[u]&&t.skipBits(8);return{general_profile_space:e,general_tier_flag:n,general_profile_idc:i,general_profile_compatibility_flags:s,general_constraint_indicator_flags:a,general_level_idc:c}},Kt=t=>{for(let r=0;r<4;r++)for(let e=0;e<(r===3?2:6);e++)if(!t.readBits(1))A(t);else{let i=Math.min(64,1<<4+(r<<1));r>1&&$(t);for(let s=0;s<i;s++)$(t)}},Qt=(t,r)=>{let e=[];for(let n=0;n<r;n++)e[n]=$t(t,n,r,e)},$t=(t,r,e,n)=>{let i=0,s=0,a=0;if(r!==0&&(s=t.readBits(1)),s){if(r===e){let d=A(t);a=r-(d+1)}else a=r-1;t.readBits(1),A(t);let c=n[a]??0;for(let d=0;d<=c;d++)t.readBits(1)||t.readBits(1);i=n[a]}else{let c=A(t),d=A(t);for(let l=0;l<c;l++)A(t),t.readBits(1);for(let l=0;l<d;l++)A(t),t.readBits(1);i=c+d}return i},jt=(t,r)=>{let e=2,n=2,i=2,s=0,a=0,c={num:1,den:1};if(t.readBits(1)){let d=t.readBits(8);if(d===255)c={num:t.readBits(16),den:t.readBits(16)};else{let l=gt[d];l&&(c=l)}}return t.readBits(1)&&t.readBits(1),t.readBits(1)&&(t.readBits(3),s=t.readBits(1),t.readBits(1)&&(e=t.readBits(8),n=t.readBits(8),i=t.readBits(8))),t.readBits(1)&&(A(t),A(t)),t.readBits(1),t.readBits(1),t.readBits(1),t.readBits(1)&&(A(t),A(t),A(t),A(t)),t.readBits(1)&&(t.readBits(32),t.readBits(32),t.readBits(1)&&A(t),t.readBits(1)&&Jt(t,!0,r)),t.readBits(1)&&(t.readBits(1),t.readBits(1),t.readBits(1),a=A(t),A(t),A(t),A(t),A(t)),{pixelAspectRatio:c,colourPrimaries:e,transferCharacteristics:n,matrixCoefficients:i,fullRangeFlag:s,minSpatialSegmentationIdc:a}},Jt=(t,r,e)=>{let n=!1,i=!1,s=!1;r&&(n=t.readBits(1)===1,i=t.readBits(1)===1,(n||i)&&(s=t.readBits(1)===1,s&&(t.readBits(8),t.readBits(5),t.readBits(1),t.readBits(5)),t.readBits(4),t.readBits(4),s&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5)));for(let a=0;a<=e;a++){let c=t.readBits(1)===1,d=!0;c||(d=t.readBits(1)===1);let l=!1;d?A(t):l=t.readBits(1)===1;let u=1;l||(u=A(t)+1),n&&mt(t,u,s),i&&mt(t,u,s)}},mt=(t,r,e)=>{for(let n=0;n<r;n++)A(t),A(t),e&&(A(t),A(t)),t.readBits(1)},xt=t=>{let r=[];r.push(t.configurationVersion),r.push((t.generalProfileSpace&3)<<6|(t.generalTierFlag&1)<<5|t.generalProfileIdc&31),r.push(t.generalProfileCompatibilityFlags>>>24&255),r.push(t.generalProfileCompatibilityFlags>>>16&255),r.push(t.generalProfileCompatibilityFlags>>>8&255),r.push(t.generalProfileCompatibilityFlags&255),r.push(...t.generalConstraintIndicatorFlags),r.push(t.generalLevelIdc&255),r.push(240|t.minSpatialSegmentationIdc>>8&15),r.push(t.minSpatialSegmentationIdc&255),r.push(252|t.parallelismType&3),r.push(252|t.chromaFormatIdc&3),r.push(248|t.bitDepthLumaMinus8&7),r.push(248|t.bitDepthChromaMinus8&7),r.push(t.avgFrameRate>>8&255),r.push(t.avgFrameRate&255),r.push((t.constantFrameRate&3)<<6|(t.numTemporalLayers&7)<<3|(t.temporalIdNested&1)<<2|t.lengthSizeMinusOne&3),r.push(t.arrays.length&255);for(let e of t.arrays){r.push((e.arrayCompleteness&1)<<7|0|e.nalUnitType&63),r.push(e.nalUnits.length>>8&255),r.push(e.nalUnits.length&255);for(let n of e.nalUnits){r.push(n.length>>8&255),r.push(n.length&255);for(let i=0;i<n.length;i++)r.push(n[i])}}return new Uint8Array(r)};var Zt={1:{colourPrimaries:5,transferCharacteristics:6,matrixCoefficients:5},2:{colourPrimaries:1,transferCharacteristics:1,matrixCoefficients:1},3:{colourPrimaries:6,transferCharacteristics:6,matrixCoefficients:6},4:{colourPrimaries:7,transferCharacteristics:7,matrixCoefficients:7},5:{colourPrimaries:9,transferCharacteristics:14,matrixCoefficients:9},7:{colourPrimaries:1,transferCharacteristics:13,matrixCoefficients:0}},bt=t=>{let r=new X(t);if(r.readBits(2)!==2)return null;let n=r.readBits(1),s=(r.readBits(1)<<1)+n;if(s===3&&r.skipBits(1),r.readBits(1)===1||r.readBits(1)!==0||(r.skipBits(2),r.readBits(24)!==4817730))return null;let l=8;s>=2&&(l=r.readBits(1)?12:10);let u=r.readBits(3),m=0,v=0;if(u!==7)if(v=r.readBits(1),s===1||s===3){let N=r.readBits(1),L=r.readBits(1);m=!N&&!L?3:N&&!L?2:1,r.skipBits(1)}else m=1;else m=3,v=1;let R=r.readBits(16),g=r.readBits(16),b=R+1,x=g+1,y=b*x,E=le(ce).level;for(let F of ce)if(y<=F.maxPictureSize){E=F.level;break}let B=Zt[u],P=B?.colourPrimaries??2,I=B?.transferCharacteristics??2,w=B?.matrixCoefficients??2;return{profile:s,level:E,bitDepth:l,chromaSubsampling:m,videoFullRangeFlag:v,colourPrimaries:P,transferCharacteristics:I,matrixCoefficients:w}};var er=function*(t){let r=new X(t),e=()=>{let n=0;for(let i=0;i<8;i++){let s=r.readAlignedByte();if(n+=(s&127)*2**(i*7),!(s&128))break;if(i===7&&s&128)return null}return n>2**32-1?null:n};for(;r.getBitsLeft()>=8;){r.skipBits(1);let n=r.readBits(4),i=r.readBits(1),s=r.readBits(1);r.skipBits(1),i&&r.skipBits(8);let a;if(s){let c=e();if(c===null)return;a=c}else a=Math.floor(r.getBitsLeft()/8);h(r.pos%8===0),yield{type:n,data:t.subarray(r.pos/8,r.pos/8+a)},r.skipBits(a*8)}},vt=t=>{for(let{type:r,data:e}of er(t)){if(r!==1)continue;let n=new X(e),i=n.readBits(3),s=n.readBits(1),a=n.readBits(1),c=0,d=0,l=0;if(a)c=n.readBits(5);else{let U=n.readBits(1),G=0;if(U){if(n.skipBits(32),n.skipBits(32),n.readBits(1)){let M=0;for(;M<32&&!n.readBits(1);)M++;M<32&&n.skipBits(M)}G=n.readBits(1),G&&(l=n.readBits(5),n.skipBits(32),n.skipBits(5),n.skipBits(5))}let T=n.readBits(1),J=n.readBits(5);for(let te=0;te<=J;te++){n.skipBits(12);let M=n.readBits(5);if(te===0&&(c=M),M>7){let V=n.readBits(1);te===0&&(d=V)}if(G&&n.readBits(1)){let q=l+1;n.skipBits(q),n.skipBits(q),n.skipBits(1)}T&&n.readBits(1)&&n.skipBits(4)}}let u=n.readBits(4),m=n.readBits(4),v=u+1;n.skipBits(v);let R=m+1;n.skipBits(R);let g=0;if(a?g=0:g=n.readBits(1),g&&(n.skipBits(4),n.skipBits(3)),n.skipBits(1),n.skipBits(1),n.skipBits(1),!a){n.skipBits(1),n.skipBits(1),n.skipBits(1),n.skipBits(1);let U=n.readBits(1);U&&(n.skipBits(1),n.skipBits(1));let G=n.readBits(1),T=0;G?T=2:T=n.readBits(1),T>0&&(n.readBits(1)||n.skipBits(1)),U&&n.skipBits(3)}n.skipBits(1),n.skipBits(1),n.skipBits(1);let b=n.readBits(1),x=8;i===2&&b?x=n.readBits(1)?12:10:i<=2&&(x=b?10:8);let y=0;i!==1&&(y=n.readBits(1));let E=2,B=2,P=2;n.readBits(1)&&(E=n.readBits(8),B=n.readBits(8),P=n.readBits(8));let w=0,F=1,N=1,L=0;return y?w=n.readBits(1):E===1&&B===13&&P===0?(w=1,F=0,N=0):(w=n.readBits(1),i===0?(F=1,N=1):i===1?(F=0,N=0):x===12?(F=n.readBits(1),N=F?n.readBits(1):0):(F=1,N=0),F&&N&&(L=n.readBits(2))),{profile:i,level:c,tier:d,bitDepth:x,monochrome:y,chromaSubsamplingX:F,chromaSubsamplingY:N,chromaSamplePosition:L,videoFullRangeFlag:w,colourPrimaries:E,transferCharacteristics:B,matrixCoefficients:P}}return null};var un=[64*2,69*2,96*2,64*2,70*2,96*2,80*2,87*2,120*2,80*2,88*2,120*2,96*2,104*2,144*2,96*2,105*2,144*2,112*2,121*2,168*2,112*2,122*2,168*2,128*2,139*2,192*2,128*2,140*2,192*2,160*2,174*2,240*2,160*2,175*2,240*2,192*2,208*2,288*2,192*2,209*2,288*2,224*2,243*2,336*2,224*2,244*2,336*2,256*2,278*2,384*2,256*2,279*2,384*2,320*2,348*2,480*2,320*2,349*2,480*2,384*2,417*2,576*2,384*2,418*2,576*2,448*2,487*2,672*2,448*2,488*2,672*2,512*2,557*2,768*2,512*2,558*2,768*2,640*2,696*2,960*2,640*2,697*2,960*2,768*2,835*2,1152*2,768*2,836*2,1152*2,896*2,975*2,1344*2,896*2,976*2,1344*2,1024*2,1114*2,1536*2,1024*2,1115*2,1536*2,1152*2,1253*2,1728*2,1152*2,1254*2,1728*2,1280*2,1393*2,1920*2,1280*2,1394*2,1920*2];var An=new Uint8Array([5,4,65,67,45,51]),fn=new Uint8Array([5,4,69,65,67,51]);var tr={apco:f.AV_PROFILE_PRORES_PROXY,apcs:f.AV_PROFILE_PRORES_LT,apcn:f.AV_PROFILE_PRORES_STANDARD,apch:f.AV_PROFILE_PRORES_HQ,ap4h:f.AV_PROFILE_PRORES_4444,ap4x:f.AV_PROFILE_PRORES_XQ},we=class extends Ae.CustomVideoEncoder{constructor(){super(...arguments);this.codecContext=null;this.scaler=null;this.dstFrame=null;this.lastBuffer=null;this.packetEmitted=!1;this.lastScalerKey=null;this.quantizer=null;this.preciseTimings=[]}static supports(e,n){return n.bitrateMode==="quantizer"?e==="avc"||e==="hevc"||e==="vp9"||e==="av1":e==="avc"||e==="hevc"||e==="vp8"||e==="vp9"||e==="av1"||e==="prores"}async init(){this.frame=new f.Frame,this.frame.alloc(),this.frame.timeBase=new f.Rational(1,1e6),this.packet=new f.Packet,this.packet.alloc();let e=ee[this.codec];h(e!==void 0);let n=()=>{if(this.codec==="prores"){let s=f.Codec.findEncoderByName(f.FF_ENCODER_PRORES_KS);if(s)return s}return f.Codec.findEncoder(e)},i=null;if(this.codec==="vp9"&&this.config.alpha==="keep")i=f.Codec.findEncoderByName(f.FF_ENCODER_LIBVPX_VP9)??f.Codec.findEncoder(e);else if(this.config.hardwareAcceleration==="prefer-software")i=n();else{let s=await $e(e);s&&this.config.bitrateMode==="quantizer"&&!s.name?.endsWith("_nvenc")&&(s=null),i=s??n()}if(!i)throw new Error(`Unable to obtain libav codec for '${this.codec}'.`);this.avCodec=i,this.config.bitrateMode!=="quantizer"&&await this.createCodecContext()}async createCodecContext(){h(this.codecContext===null);let e=new f.CodecContext;e.allocContext3(this.avCodec);let n=f.AV_PIX_FMT_YUV420P;this.avCodec.pixelFormats&&(this.avCodec.pixelFormats.includes(f.AV_PIX_FMT_YUV420P)||(n=this.avCodec.pixelFormats[0]),this.config.alpha==="keep"&&(this.avCodec.pixelFormats.includes(f.AV_PIX_FMT_YUVA420P)?n=f.AV_PIX_FMT_YUVA420P:n=f.avcodecFindBestPixFmtOfList(this.avCodec.pixelFormats,f.AV_PIX_FMT_YUVA444P12LE)));let i=_e({num:(this.config.displayWidth??this.config.width)*this.config.height,den:(this.config.displayHeight??this.config.height)*this.config.width});e.width=this.config.width,e.height=this.config.height,e.pixelFormat=n,e.timeBase=new f.Rational(1,1e6),e.gopSize=60,e.framerate=new f.Rational(Math.round(this.config.framerate??0)||30,1),e.bitRate=this.config.bitrateMode==="quantizer"?0n:BigInt(this.config.bitrate??new Ae.Quality("medium")._toVideoBitrate(this.codec,this.config.width,this.config.height)),e.sampleAspectRatio=new f.Rational(i.num,i.den),this.config.bitrateMode==="constant"&&(e.rcMinRate=e.bitRate,e.rcMaxRate=e.bitRate);let s=this.config.latencyMode==="realtime";if(this.avCodec.name==="libx264"?s&&(e.setOption("tune","zerolatency"),e.setOption("preset","ultrafast")):this.avCodec.name==="libx265"?(e.setOption("x265-params","log-level=error"),s&&(e.setOption("tune","zerolatency"),e.setOption("preset","ultrafast"))):this.avCodec.name==="libvpx"?(s&&e.setOption("deadline","realtime"),e.setOption("cpu-used","8")):this.avCodec.name==="libvpx-vp9"?(e.setOption("deadline","realtime"),s?e.setOption("cpu-used","8"):e.setOption("cpu-used","5")):this.avCodec.name==="libsvtav1"?(process.env.SVT_LOG="1",s&&e.setOption("preset","12")):(this.avCodec.name==="h264_nvenc"||this.avCodec.name==="hevc_nvenc")&&e.setOption("forced-idr","1"),this.config.bitrateMode==="quantizer"){h(this.quantizer!==null);let c;if(this.avCodec.name==="libaom-av1"||this.avCodec.name==="libsvtav1"?c=Math.round(this.quantizer/4):c=this.quantizer,this.avCodec.name==="libx264"||this.avCodec.name==="libx265")e.setOption("qp",String(c));else if(this.avCodec.name==="libvpx-vp9"||this.avCodec.name==="libaom-av1")e.setOption("crf",String(c));else if(this.avCodec.name==="libsvtav1")e.setOption("qp",String(c));else if(this.avCodec.name==="librav1e")e.setOption("qp",String(c));else if(this.avCodec.name?.endsWith("_nvenc"))e.setOption("rc","constqp"),e.setOption("qp",String(c));else throw new Error(`Encoder '${this.avCodec.name}' cannot be used for quantizer-based encoding.`);e.qMin=c,e.qMax=c}if(this.codec==="prores"){let c=tr[this.config.codec];h(c!==void 0),e.setOption("profile",String(c))}let a=await e.open2();f.FFmpegError.throwIfError(a,"Open codec context"),this.codecContext=e}async encode(e,n){if(this.config.bitrateMode==="quantizer"){let l;if(this.codec==="avc"?l=n.avc?.quantizer:this.codec==="hevc"?l=n.hevc?.quantizer:this.codec==="vp9"?l=n.vp9?.quantizer:l=n.av1?.quantizer,h(l!=null),this.codecContext!==null&&l!==this.quantizer){let u=await this.codecContext.sendFrame(null);for(f.FFmpegError.throwIfError(u,"Send frame");;){let m=await this.codecContext.receivePacket(this.packet);if(m===f.AVERROR_EAGAIN||m===f.AVERROR_EOF)break;this.receivePacket(m)}this.codecContext.freeContext(),this.codecContext=null}this.quantizer=l}if(this.codecContext===null&&await this.createCodecContext(),h(this.codecContext),e._data instanceof W)this.frame.unref(),this.frame.ref(e._data.frame);else{if(e.format===null)throw new Error("Cannot encode foreign VideoSample with unknown (null) format.");this.lastBuffer=await pe(e,this.frame,this.lastBuffer)}let i=this.frame;if(this.codecContext.pixelFormat!==this.frame.format||this.codecContext.width!==this.frame.width||this.codecContext.height!==this.frame.height){this.scaler||(this.scaler=new f.SoftwareScaleContext);let l=`${this.frame.width}x${this.frame.height}:${this.frame.format}`;if(l!==this.lastScalerKey){this.scaler.getContext(this.frame.width,this.frame.height,this.frame.format,this.codecContext.width,this.codecContext.height,this.codecContext.pixelFormat,f.SWS_FAST_BILINEAR),this.lastScalerKey=l;let m=this.scaler.initContext();f.FFmpegError.throwIfError(m,"initContext")}this.dstFrame||(this.dstFrame=new f.Frame,this.dstFrame.alloc(),this.dstFrame.width=this.codecContext.width,this.dstFrame.height=this.codecContext.height,this.dstFrame.format=this.codecContext.pixelFormat,this.dstFrame.allocBuffer()),await this.scaler.scaleFrame(this.dstFrame,this.frame),this.dstFrame.copyProps(this.frame),i=this.dstFrame}i.pts=BigInt(e.microsecondTimestamp),i.duration=BigInt(e.microsecondDuration),i.timeBase=new f.Rational(1,1e6),i.pictType=n?.keyFrame?f.AV_PICTURE_TYPE_I:f.AV_PICTURE_TYPE_NONE,i.keyFrame=n?.keyFrame?1:0;let a=de(this.preciseTimings,e.microsecondTimestamp,l=>l.microsecondTimestamp),c=a!==-1?this.preciseTimings[a]:null;c&&c.microsecondTimestamp===e.microsecondTimestamp?(c.timestamp!==e.timestamp&&(c.timestampIsValid=!1),c.duration!==e.duration&&(c.durationIsValid=!1)):(this.preciseTimings.splice(a+1,0,{microsecondTimestamp:e.microsecondTimestamp,timestamp:e.timestamp,duration:e.duration,timestampIsValid:!0,durationIsValid:!0}),this.preciseTimings.length>128&&this.preciseTimings.shift());let d=await this.codecContext.sendFrame(i);for(f.FFmpegError.throwIfError(d,"Send frame");;){let l=await this.codecContext.receivePacket(this.packet);if(l===f.AVERROR_EAGAIN||l===f.AVERROR_EOF)break;this.receivePacket(l)}}receivePacket(e){if(h(this.codecContext),f.FFmpegError.throwIfError(e,"Receive packet"),!this.packet.data)return;let n=O(this.packet.data),i=Number(this.packet.pts)/1e6,s=Number(this.packet.duration)/1e6,a=de(this.preciseTimings,Number(this.packet.pts),g=>g.microsecondTimestamp),c=a!==-1?this.preciseTimings[a]:null;c&&c.microsecondTimestamp===Number(this.packet.pts)&&(c.timestampIsValid&&(i=c.timestamp),c.durationIsValid&&(s=c.duration));let d={},l=null,u=null;if(this.codec==="avc"||this.codec==="hevc"){let g=!1;if(this.codec==="avc"?g=this.config.avc?.format==="annexb":g=this.config.hevc?.format==="annexb",!this.packetEmitted){let b;if(this.codec==="avc"){let x=pt(this.packet.data);if(!x)throw new Error("Invalid AVC data, could not extract decoder configuration record.");b=ht(x)}else{let x=Ct(this.packet.data);if(!x)throw new Error("Invalid HEVC data, could not extract decoder configuration record.");b=xt(x)}l=ue({width:this.config.width,height:this.config.height,codec:this.codec,codecDescription:b,colorSpace:null,avcType:1,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null,proresFormat:null}),g||(u=b)}if(!g){let x=[];for(let I of Be(n))if(this.codec==="avc"){let w=qe(n[I.offset]);w!==7&&w!==8&&w!==13&&x.push(I)}else{let w=Ee(n[I.offset]);w!==33&&w!==34&&w!==32&&x.push(I)}let y=0;for(let I of x)y+=4+I.length;let E=new Uint8Array(y),B=new DataView(E.buffer),P=0;for(let I of x){let w=I.length;B.setUint32(P,w,!1),P+=4,E.set(n.subarray(I.offset,I.offset+I.length),P),P+=I.length}n=E}}else if(this.codec==="vp8")this.packetEmitted||(l=ue({width:this.config.width,height:this.config.height,codec:"vp8",codecDescription:null,colorSpace:null,avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null,proresFormat:null}));else if(this.codec==="vp9"){if(!this.packetEmitted){let g=bt(n);l=ue({width:this.config.width,height:this.config.height,codec:"vp9",codecDescription:null,colorSpace:null,avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:g,av1CodecInfo:null,proresFormat:null})}}else if(this.codec==="av1"){if(!this.packetEmitted){let g=vt(n);l=ue({width:this.config.width,height:this.config.height,codec:"av1",codecDescription:null,colorSpace:null,avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:g,proresFormat:null})}}else if(this.codec==="prores")this.packetEmitted||(l=ue({width:this.config.width,height:this.config.height,codec:"prores",codecDescription:null,colorSpace:null,avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null,proresFormat:this.config.codec}));else throw new Error("Unreachable.");let m={},v=this.packet.getSideData(f.AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL);v&&(m.alpha=O(v).subarray(8));let R=new Ae.EncodedPacket(n,this.packet.isKeyframe?"key":"delta",i,s,void 0,void 0,m);l!==null&&(d.decoderConfig={codec:l,codedWidth:this.codecContext.width,codedHeight:this.codecContext.height,displayAspectWidth:this.config.displayWidth??this.codecContext.width,displayAspectHeight:this.config.displayHeight??this.codecContext.height,description:u??void 0,colorSpace:{primaries:Ce(this.codecContext.colorPrimaries),matrix:be(this.codecContext.colorSpace),transfer:xe(this.codecContext.colorTrc),fullRange:this.codecContext.colorRange===f.AVCOL_RANGE_JPEG?!0:this.codecContext.colorRange===f.AVCOL_RANGE_MPEG?!1:void 0}}),this.packetEmitted=!0,this.onPacket(R,d)}async flush(){if(this.codecContext){let e=await this.codecContext.sendFrame(null);for(f.FFmpegError.throwIfError(e,"Send frame");;){let n=await this.codecContext.receivePacket(this.packet);if(n===f.AVERROR_EAGAIN||n===f.AVERROR_EOF)break;this.receivePacket(n)}this.codecContext.freeContext(),this.codecContext=null}this.packetEmitted=!1}close(){this.codecContext?.freeContext(),this.frame.free(),this.packet.free(),this.scaler?.freeContext(),this.dstFrame?.free()}};var Pe=k("mediabunny"),S=ne(k("node-av"));var _t=k("mediabunny"),fe=ne(k("node-av"));var j=class extends _t.AudioSampleResource{get frame(){if(!this._frame)throw new Error("AvFrameAudioSampleResource has been closed.");return this._frame}constructor(r){if(super(),!(r instanceof fe.Frame))throw new TypeError("frame must be a NodeAv.Frame.");if(r.getMediaType()!==fe.AVMEDIA_TYPE_AUDIO)throw new Error("AvFrameAudioSampleResource must be initialized with an audio frame.");this._frame=r}getFormat(){let r=tt(this.frame.format);if(r===null){let e=fe.avGetSampleFmtName(this.frame.format);throw new TypeError(`Unsupported audio sample format: ${e} (${this.frame.format})`)}return r}getSampleRate(){return this.frame.sampleRate}getNumberOfChannels(){return this.frame.channels}getNumberOfFrames(){return this.frame.nbSamples}getTimestamp(){return Number(this.frame.pts)/this.frame.timeBase.den}close(){this.frame.free(),this._frame=null}getDataPlane(r){return h(this.frame.data&&r<this.frame.data.length),O(this.frame.data[r])}},Ie=(t,r)=>{r.format=rt(t.format),r.nbSamples=t.numberOfFrames,r.sampleRate=t.sampleRate,r.channelLayout=oe(t.numberOfChannels),r.allocBuffer(),h(r.data);for(let e=0;e<r.data.length;e++)t.copyTo(r.data[e],{planeIndex:e})};var Te=class extends Pe.CustomAudioDecoder{constructor(){super(...arguments);this.codecContext=null}static supports(e,n){return e==="aac"||e==="opus"||e==="mp3"||e==="vorbis"||e==="flac"||e==="ac3"||e==="eac3"||e==="dts"}async init(){this.frame=new S.Frame,this.frame.alloc(),this.packet=new S.Packet,this.packet.alloc();let e=ee[this.codec];h(e!==void 0);let n=S.Codec.findDecoder(e);if(n===null)throw new Error(`Unable to obtain libav codec for '${this.codec}'.`);let i=new S.CodecContext;i.allocContext3(n),i.sampleRate=this.config.sampleRate,i.channelLayout=oe(this.config.numberOfChannels),i.timeBase=new S.Rational(1,this.config.sampleRate),i.codecType=S.AVMEDIA_TYPE_AUDIO,i.codecId=e,i.extraData=this.config.description?Buffer.from(O(this.config.description)):null;let s=await i.open2();S.FFmpegError.throwIfError(s,"Open codec context"),this.codecContext=i}async decode(e){h(this.codecContext),this.packet.isKeyframe=e.type==="key",this.packet.data=Buffer.from(e.data),this.packet.timeBase={num:1,den:this.config.sampleRate},this.packet.pts=BigInt(Math.round(e.timestamp*this.config.sampleRate)),this.packet.dts=S.AV_NOPTS_VALUE,this.packet.duration=BigInt(Math.round(e.duration*this.config.sampleRate));let n=await this.codecContext.sendPacket(this.packet);for(S.FFmpegError.throwIfError(n,"Send packet"),this.packet.unref();;){let i=await this.codecContext.receiveFrame(this.frame);if(i===S.AVERROR_EAGAIN||i===S.AVERROR_EOF)break;this.receiveFrame(i)}}receiveFrame(e){S.FFmpegError.throwIfError(e,"Receive frame");let n=this.frame.clone();if(!n)throw new Error("Allocation failure during frame clone.");n.timeBase=new S.Rational(1,this.config.sampleRate),this.onSample(new Pe.AudioSample(new j(n)))}async flush(){h(this.codecContext);let e=await this.codecContext.sendPacket(null);for(S.FFmpegError.throwIfError(e,"Flush decoder");;){let n=await this.codecContext.receiveFrame(this.frame);if(n===S.AVERROR_EAGAIN||n===S.AVERROR_EOF)break;this.receiveFrame(n)}this.codecContext.flushBuffers()}close(){this.codecContext?.freeContext(),this.frame.free(),this.packet.free()}};var me=k("mediabunny"),_=ne(k("node-av"));var St=[8e3,11025,12e3,16e3,22050,24e3,32e3,44100,48e3],yt=[1,2,4,5,6],rr=16384,Et=(t,r,e)=>{if(t<32e3||t>384e4)return!1;let n=e===6,i=e-(n?1:0),s=32*Math.ceil(Math.ceil(t*512/r)/32),a=132+(493+28*32)*i+(n?72:0);return s>=a&&s<=8*rr};var nr=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],ir=[8e3,12e3,16e3,24e3,48e3],or=[8e3,11025,12e3,16e3,22050,24e3,32e3,44100,48e3],Bt=[32e3,44100,48e3],Xe=1024,Re=class extends me.CustomAudioEncoder{constructor(){super(...arguments);this.codecContext=null;this.resampler=null;this.dstFrame=null;this.firstExpectedTimestamp=null;this.outputTimestampOffset=0;this.inputParametersKey=null;this.resamplerInputSampleRate=null;this.nextResamplerPts=null;this.packetEmitted=!1;this.adtsHeaderTemplate=null}static supports(e,n){let{numberOfChannels:i,sampleRate:s}=n;return e==="aac"&&i>=1&&i<=48&&nr.includes(s)||e==="opus"&&i>=1&&i<=255&&ir.includes(s)||e==="mp3"&&i>=1&&i<=2&&or.includes(s)||e==="vorbis"&&i>=1&&i<=255&&s<=2e5||e==="flac"&&i>=1&&i<=8&&s<=655350||e==="ac3"&&i>=1&&i<=6&&Bt.includes(s)||e==="eac3"&&i>=1&&i<=16&&Bt.includes(s)||e==="dts"&&yt.includes(i)&&St.includes(s)&&Et(wt(n,e),s,i)}async init(){this.frame=new _.Frame,this.frame.alloc(),this.packet=new _.Packet,this.packet.alloc();let e=ee[this.codec];h(e!==void 0);let n=_.Codec.findEncoder(e);if(!n)throw new Error(`Unable to obtain libav codec for '${this.codec}'.`);this.avCodec=n,await this.createCodecContext()}async createCodecContext(){h(this.codecContext===null);let e=new _.CodecContext;e.allocContext3(this.avCodec);let n=_.AV_SAMPLE_FMT_FLTP;this.avCodec.sampleFormats&&!this.avCodec.sampleFormats.includes(_.AV_SAMPLE_FMT_FLTP)&&(n=this.avCodec.sampleFormats[0]),e.sampleRate=this.config.sampleRate,e.channelLayout=this.codec==="dts"?nt(this.config.numberOfChannels):oe(this.config.numberOfChannels),e.codecType=_.AVMEDIA_TYPE_AUDIO,e.codecId=ee[this.codec],e.sampleFormat=n,e.timeBase=new _.Rational(1,this.config.sampleRate),e.bitRate=BigInt(wt(this.config,this.codec)),this.config.bitrateMode==="constant"&&(e.rcMinRate=e.bitRate,e.rcMaxRate=e.bitRate);let i=this.codec==="dts"?_.Dictionary.fromObject({strict:-2}):null,s=await e.open2(this.avCodec,i);_.FFmpegError.throwIfError(s,"Open codec context"),this.codecContext=e}async encode(e){this.codecContext===null&&(await this.createCodecContext(),h(this.codecContext)),this.firstExpectedTimestamp??=e.timestamp,e._data instanceof j?(this.frame.unref(),this.frame.ref(e._data.frame)):Ie(e,this.frame),this.frame.pts=BigInt(Math.round(e.timestamp*this.config.sampleRate)),this.frame.duration=BigInt(Math.round(e.duration*this.config.sampleRate)),this.frame.timeBase=new _.Rational(1,this.config.sampleRate);let n=`${this.frame.sampleRate}:${this.frame.channels}:${this.frame.format}`;if(this.inputParametersKey!==null&&this.inputParametersKey!==n)throw new Error("Input audio parameters changed. For this audio encoder, you cannot change the input audio parameters over time.");if(this.inputParametersKey=n,this.codecContext.frameSize>0||this.codecContext.sampleFormat!==this.frame.format||this.codecContext.sampleRate!==this.frame.sampleRate||this.codecContext.channels!==this.frame.channels){if(!this.resampler){this.resampler=new _.SoftwareResampleContext,this.resamplerInputSampleRate=this.frame.sampleRate;let a=this.codecContext.channelLayout,c=oe(this.frame.channels),d=this.resampler.allocSetOpts2(a,this.codecContext.sampleFormat,this.codecContext.sampleRate,c,this.frame.format,this.frame.sampleRate);_.FFmpegError.throwIfError(d,"allocSetOpts2");let l=this.resampler.init();_.FFmpegError.throwIfError(l,"init"),this.dstFrame=new _.Frame,this.dstFrame.alloc(),this.dstFrame.channelLayout=a,this.dstFrame.sampleRate=this.codecContext.sampleRate,this.dstFrame.format=this.codecContext.sampleFormat,this.dstFrame.nbSamples=this.codecContext.frameSize||Xe,this.dstFrame.duration=BigInt(this.dstFrame.nbSamples),this.dstFrame.allocBuffer(),this.nextResamplerPts=this.frame.pts}let s=this.frame.data;if(!s)throw new DOMException("Frame has no data","EncodingError");await this.resampler.convert(null,0,s,this.frame.nbSamples),await this.pullResampledFrames()}else await this.sendFrameAndReceivePackets(this.frame)}async pullResampledFrames(){h(this.codecContext),h(this.resampler),h(this.dstFrame),h(this.nextResamplerPts!==null);let e=this.codecContext.frameSize||Xe;for(;!(this.resampler.getOutSamples(0)<e);)await this.resampler.convert(this.dstFrame.data,e,null,0),this.dstFrame.pts=this.nextResamplerPts,await this.sendFrameAndReceivePackets(this.dstFrame),this.nextResamplerPts+=BigInt(e)}async sendFrameAndReceivePackets(e){h(this.codecContext);let n=await this.codecContext.sendFrame(e);for(_.FFmpegError.throwIfError(n,"Send frame");;){let i=await this.codecContext.receivePacket(this.packet);if(i===_.AVERROR_EAGAIN||i===_.AVERROR_EOF)break;this.receivePacket(i)}}receivePacket(e){if(h(this.codecContext),h(this.firstExpectedTimestamp!==null),_.FFmpegError.throwIfError(e,"Receive packet"),!this.packet.data)return;let n=Number(this.packet.pts)/this.codecContext.sampleRate,i=Number(this.packet.duration)/this.codecContext.sampleRate,s=this.packet.data,a;if(this.packetEmitted)a={};else{this.outputTimestampOffset=Math.max(this.firstExpectedTimestamp-n,0);let d=this.config.codec,l=this.codecContext.extraData?O(this.codecContext.extraData):void 0;if(this.codec==="aac"){if(!l)throw new Error("Extradata expected for AAC.");if(this.config.aac?.format==="adts"){let m=lt(l);this.adtsHeaderTemplate=dt(m),l=void 0}}else if(this.codec==="opus"){if(!l)throw new Error("Extradata expected for Opus.")}else if(this.codec==="vorbis"){if(!l)throw new Error("Extradata expected for Vorbis.")}else if(this.codec==="flac"){if(!l)throw new Error("Extradata expected for FLAC.");l=new Uint8Array([102,76,97,67,128,0,0,l.byteLength,...l])}a={decoderConfig:{codec:d,sampleRate:this.codecContext.sampleRate,numberOfChannels:this.codecContext.channels,description:l}}}if(this.adtsHeaderTemplate){let d=s.byteLength+this.adtsHeaderTemplate.header.byteLength;this.adtsHeaderTemplate.bitstream.pos=30,this.adtsHeaderTemplate.bitstream.writeBits(13,d);let l=new Uint8Array(this.adtsHeaderTemplate.header.byteLength+s.byteLength);l.set(this.adtsHeaderTemplate.header,0),l.set(s,this.adtsHeaderTemplate.header.byteLength),s=l}n+=this.outputTimestampOffset;let c=new me.EncodedPacket(s,"key",n,i);this.packetEmitted=!0,this.onPacket(c,a)}async flush(){if(this.codecContext){e:if(this.resampler){h(this.resamplerInputSampleRate!==null);let e=this.resampler.getOutSamples(0);if(e===0)break e;let n=this.codecContext.frameSize||Xe;h(e<n);let i=Math.ceil((n-e)/this.codecContext.sampleRate*this.resamplerInputSampleRate);this.resampler.injectSilence(i),await this.pullResampledFrames()}await this.sendFrameAndReceivePackets(null),this.codecContext.freeContext(),this.codecContext=null,this.packetEmitted=!1,this.firstExpectedTimestamp=null,this.outputTimestampOffset=0,this.adtsHeaderTemplate=null,this.resampler?.free(),this.resampler=null,this.inputParametersKey=null,this.resamplerInputSampleRate=null,this.nextResamplerPts=null,this.dstFrame?.free(),this.dstFrame=null}}close(){this.codecContext?.freeContext(),this.frame.free(),this.packet.free(),this.dstFrame?.free(),this.resampler?.free()}},wt=(t,r)=>t.bitrate??new me.Quality("medium")._toAudioBitrate(r)??0;var Tt=k("@mediabunny/prores");var Pt=Symbol.for("@mediabunny/server loaded");globalThis[Pt]&&D.Logging._error(`[WARNING]
|
|
9
|
+
@mediabunny/server was loaded twice. This will likely cause the package not to work correctly. Check if multiple dependencies are importing different versions of @mediabunny/server, or if something is being bundled incorrectly.`);globalThis[Pt]=!0;var It=!1,Q={},sr=(t={})=>{if(typeof t!="object"||!t)throw new TypeError("options must be an object.");if(t.hardwareContext!=null&&!(t.hardwareContext instanceof Y.HardwareContext||typeof t.hardwareContext=="function"))throw new TypeError("options.hardwareContext, when provided, must be a NodeAv.HardwareContext, a function, or null.");It||(It=!0,Q=t,Y.Log.setLevel(Y.AV_LOG_ERROR),(0,D.registerDecoder)(Se),(0,Tt.registerProresDecoder)(),(0,D.registerEncoder)(we),(0,D.registerDecoder)(Te),(0,D.registerEncoder)(Re),(0,D.registerVideoSampleTransformer)(at))},ar=async(t,r)=>{if(!(t instanceof D.VideoSample)&&!(t instanceof D.AudioSample))throw new TypeError("sample must be a VideoSample or an AudioSample.");if(!(r instanceof Y.Frame))throw new TypeError("frame must be a NodeAv.Frame.");if(t instanceof D.VideoSample){if(t._data instanceof W)r.unref(),r.ref(t._data.frame);else{if(t.format===null)throw new Error("Cannot convert foreign VideoSample with unknown (null) format.");await pe(t,r,null)}r.pts=BigInt(t.microsecondTimestamp),r.duration=BigInt(t.microsecondDuration),r.timeBase=new Y.Rational(1,1e6)}else t._data instanceof j?(r.unref(),r.ref(t._data.frame)):Ie(t,r),r.timeBase=new Y.Rational(1,t.sampleRate),r.pts=BigInt(Math.round(t.timestamp*t.sampleRate)),r.duration=BigInt(t.numberOfFrames)};return Ut(cr);})();
|
|
10
10
|
if (typeof module === "object" && typeof module.exports === "object") Object.assign(module.exports, MediabunnyServer)
|