@ahmedrowaihi/mediabunny-server 1.65.2-beta.534 → 1.65.2-beta.537

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.
@@ -5623,8 +5623,13 @@ var MediabunnyServer = (() => {
5623
5623
  return;
5624
5624
  }
5625
5625
  this.closed = true;
5626
- await this.pumping?.catch(() => {
5627
- });
5626
+ while (this.pumping !== null || this.queue.chunks.length > 0) {
5627
+ this.pumping ??= this.pump().finally(() => {
5628
+ this.pumping = null;
5629
+ });
5630
+ await this.pumping.catch(() => {
5631
+ });
5632
+ }
5628
5633
  if (!aborting && !this.failure && this.io && this.partialLength > 0) {
5629
5634
  await this.writeDatagram(this.partial.subarray(0, this.partialLength)).catch((error) => {
5630
5635
  this.failure ??= error instanceof Error ? error : new Error(String(error));
@@ -6,6 +6,6 @@
6
6
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
7
7
  */
8
8
  "use strict";var MediabunnyServer=(()=>{var Zr=Object.create;var Te=Object.defineProperty;var en=Object.getOwnPropertyDescriptor;var tn=Object.getOwnPropertyNames;var rn=Object.getPrototypeOf,nn=Object.prototype.hasOwnProperty;var I=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});var on=(r,t)=>{for(var e in t)Te(r,e,{get:t[e],enumerable:!0})},wt=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of tn(t))!nn.call(r,i)&&i!==e&&Te(r,i,{get:()=>t[i],enumerable:!(n=en(t,i))||n.enumerable});return r};var ae=(r,t,e)=>(e=r!=null?Zr(rn(r)):{},wt(t||!r||!r.__esModule?Te(e,"default",{value:r,enumerable:!0}):e,r)),sn=r=>wt(Te({},"__esModule",{value:!0}),r);var Ai={};on(Ai,{AvFrameAudioSampleResource:()=>re,AvFrameVideoSampleResource:()=>G,DEFAULT_RIST_BUFFER_MS:()=>St,NetworkSource:()=>We,RistSource:()=>Ke,RtmpSource:()=>$e,SrtTarget:()=>Qe,_serverOptions:()=>Z,registerMediabunnyServer:()=>mi,toAvFrame:()=>pi});var U=I("mediabunny"),Q=ae(I("node-av"));var Oe=I("mediabunny"),E=ae(I("node-av"));var s=ae(I("node-av")),Tt=I("node-av"),It=I("node-av/constants");var Ie=async r=>{let t=new URL(r);t.search="",(t.hostname==="0.0.0.0"||t.hostname==="::"||t.hostname==="[::]")&&(t.hostname="127.0.0.1");let e=new Tt.IOContext;try{await e.open2(t.toString(),It.AVIO_FLAG_WRITE)}catch{}await e.closep().catch(()=>{})},j={avc:s.AV_CODEC_ID_H264,hevc:s.AV_CODEC_ID_HEVC,vp8:s.AV_CODEC_ID_VP8,vp9:s.AV_CODEC_ID_VP9,av1:s.AV_CODEC_ID_AV1,prores:s.AV_CODEC_ID_PRORES,aac:s.AV_CODEC_ID_AAC,opus:s.AV_CODEC_ID_OPUS,mp3:s.AV_CODEC_ID_MP3,vorbis:s.AV_CODEC_ID_VORBIS,flac:s.AV_CODEC_ID_FLAC,ac3:s.AV_CODEC_ID_AC3,eac3:s.AV_CODEC_ID_EAC3,dts:s.AV_CODEC_ID_DTS,truehd:s.AV_CODEC_ID_TRUEHD},Je,Pt=()=>Z.hardwareContext!==void 0&&typeof Z.hardwareContext!="function"?Z.hardwareContext:(Je===void 0&&(Je=s.HardwareContext.auto()),Je),Rt=r=>{if(r!==null&&!(r instanceof s.HardwareContext))throw new TypeError("When serverOptions.hardwareContext is a function, it must return or resolve to a NodeAv.HardwareContext or null.")},Ze=new Map,Bt=async r=>{if(typeof Z.hardwareContext=="function"){let t=await Z.hardwareContext(r);return Rt(t),t?.getDecoderCodec(r)??null}if(!Ze.has(r)){let t=Pt();Ze.set(r,t?.getDecoderCodec(r)??null)}return Ze.get(r)},et=new Map,Ft=async r=>{if(typeof Z.hardwareContext=="function"){let t=await Z.hardwareContext(r);return Rt(t),t?.getEncoderCodec(r)??null}if(!et.has(r)){let t=Pt();et.set(r,t?.getEncoderCodec(r)??null)}return et.get(r)},Nt=r=>{switch(r){case"bt709":return s.AVCOL_PRI_BT709;case"bt470bg":return s.AVCOL_PRI_BT470BG;case"smpte170m":return s.AVCOL_PRI_SMPTE170M;case"bt2020":return s.AVCOL_PRI_BT2020;case"smpte432":return s.AVCOL_PRI_SMPTE432}return null},Pe=r=>{switch(r){case s.AVCOL_PRI_BT709:return"bt709";case s.AVCOL_PRI_BT470BG:return"bt470bg";case s.AVCOL_PRI_SMPTE170M:return"smpte170m";case s.AVCOL_PRI_BT2020:return"bt2020";case s.AVCOL_PRI_SMPTE432:return"smpte432"}return null},Vt=r=>{switch(r){case"bt709":return s.AVCOL_TRC_BT709;case"smpte170m":return s.AVCOL_TRC_SMPTE170M;case"iec61966-2-1":return s.AVCOL_TRC_IEC61966_2_1;case"linear":return s.AVCOL_TRC_LINEAR;case"pq":return s.AVCOL_TRC_SMPTE2084;case"hlg":return s.AVCOL_TRC_ARIB_STD_B67}return null},Re=r=>{switch(r){case s.AVCOL_TRC_BT709:return"bt709";case s.AVCOL_TRC_SMPTE170M:return"smpte170m";case s.AVCOL_TRC_IEC61966_2_1:return"iec61966-2-1";case s.AVCOL_TRC_LINEAR:return"linear";case s.AVCOL_TRC_SMPTE2084:return"pq";case s.AVCOL_TRC_ARIB_STD_B67:return"hlg"}return null},Mt=r=>{switch(r){case"rgb":return s.AVCOL_SPC_RGB;case"bt709":return s.AVCOL_SPC_BT709;case"bt470bg":return s.AVCOL_SPC_BT470BG;case"smpte170m":return s.AVCOL_SPC_SMPTE170M;case"bt2020-ncl":return s.AVCOL_SPC_BT2020_NCL}return null},Be=r=>{switch(r){case s.AVCOL_SPC_RGB:return"rgb";case s.AVCOL_SPC_BT709:return"bt709";case s.AVCOL_SPC_BT470BG:return"bt470bg";case s.AVCOL_SPC_SMPTE170M:return"smpte170m";case s.AVCOL_SPC_BT2020_NCL:return"bt2020-ncl"}return null},ye=r=>{let t=s.avGetPixFmtName(r)??"";return/rgb|bgr|gbr/.test(t)},kt=r=>{switch(r){case s.AV_PIX_FMT_YUV420P:return"I420";case s.AV_PIX_FMT_YUVJ420P:return"I420";case s.AV_PIX_FMT_YUV420P10LE:return"I420P10";case s.AV_PIX_FMT_YUV420P12LE:return"I420P12";case s.AV_PIX_FMT_YUVA420P:return"I420A";case s.AV_PIX_FMT_YUVA420P10LE:return"I420AP10";case s.AV_PIX_FMT_YUV422P:return"I422";case s.AV_PIX_FMT_YUVJ422P:return"I422";case s.AV_PIX_FMT_YUV422P10LE:return"I422P10";case s.AV_PIX_FMT_YUV422P12LE:return"I422P12";case s.AV_PIX_FMT_YUVA422P:return"I422A";case s.AV_PIX_FMT_YUVA422P10LE:return"I422AP10";case s.AV_PIX_FMT_YUVA422P12LE:return"I422AP12";case s.AV_PIX_FMT_YUV444P:return"I444";case s.AV_PIX_FMT_YUVJ444P:return"I444";case s.AV_PIX_FMT_YUV444P10LE:return"I444P10";case s.AV_PIX_FMT_YUV444P12LE:return"I444P12";case s.AV_PIX_FMT_YUVA444P:return"I444A";case s.AV_PIX_FMT_YUVA444P10LE:return"I444AP10";case s.AV_PIX_FMT_YUVA444P12LE:return"I444AP12";case s.AV_PIX_FMT_NV12:return"NV12";case s.AV_PIX_FMT_RGBA:return"RGBA";case s.AV_PIX_FMT_RGB0:return"RGBX";case s.AV_PIX_FMT_BGRA:return"BGRA";case s.AV_PIX_FMT_BGR0:return"BGRX";default:return null}},tt=r=>{switch(r){case"I420":return s.AV_PIX_FMT_YUV420P;case"I420P10":return s.AV_PIX_FMT_YUV420P10LE;case"I420P12":return s.AV_PIX_FMT_YUV420P12LE;case"I420A":return s.AV_PIX_FMT_YUVA420P;case"I420AP10":return s.AV_PIX_FMT_YUVA420P10LE;case"I422":return s.AV_PIX_FMT_YUV422P;case"I422P10":return s.AV_PIX_FMT_YUV422P10LE;case"I422P12":return s.AV_PIX_FMT_YUV422P12LE;case"I422A":return s.AV_PIX_FMT_YUVA422P;case"I422AP10":return s.AV_PIX_FMT_YUVA422P10LE;case"I422AP12":return s.AV_PIX_FMT_YUVA422P12LE;case"I444":return s.AV_PIX_FMT_YUV444P;case"I444P10":return s.AV_PIX_FMT_YUV444P10LE;case"I444P12":return s.AV_PIX_FMT_YUV444P12LE;case"I444A":return s.AV_PIX_FMT_YUVA444P;case"I444AP10":return s.AV_PIX_FMT_YUVA444P10LE;case"I444AP12":return s.AV_PIX_FMT_YUVA444P12LE;case"NV12":return s.AV_PIX_FMT_NV12;case"RGBA":return s.AV_PIX_FMT_RGBA;case"RGBX":return s.AV_PIX_FMT_RGB0;case"BGRA":return s.AV_PIX_FMT_BGRA;case"BGRX":return s.AV_PIX_FMT_BGR0;default:return s.AV_PIX_FMT_NONE}},Ot=r=>{switch(r){case s.AV_SAMPLE_FMT_U8:return"u8";case s.AV_SAMPLE_FMT_S16:return"s16";case s.AV_SAMPLE_FMT_S32:return"s32";case s.AV_SAMPLE_FMT_FLT:return"f32";case s.AV_SAMPLE_FMT_U8P:return"u8-planar";case s.AV_SAMPLE_FMT_S16P:return"s16-planar";case s.AV_SAMPLE_FMT_S32P:return"s32-planar";case s.AV_SAMPLE_FMT_FLTP:return"f32-planar";default:return null}},Dt=r=>{switch(r){case"u8":return s.AV_SAMPLE_FMT_U8;case"s16":return s.AV_SAMPLE_FMT_S16;case"s32":return s.AV_SAMPLE_FMT_S32;case"f32":return s.AV_SAMPLE_FMT_FLT;case"u8-planar":return s.AV_SAMPLE_FMT_U8P;case"s16-planar":return s.AV_SAMPLE_FMT_S16P;case"s32-planar":return s.AV_SAMPLE_FMT_S32P;case"f32-planar":return s.AV_SAMPLE_FMT_FLTP;default:return s.AV_SAMPLE_FMT_NONE}},de=r=>{switch(r){case 1:return s.AV_CHANNEL_LAYOUT_MONO;case 2:return s.AV_CHANNEL_LAYOUT_STEREO;case 4:return s.AV_CHANNEL_LAYOUT_QUAD;case 6:return s.AV_CHANNEL_LAYOUT_5POINT1_BACK;case 8:return s.AV_CHANNEL_LAYOUT_7POINT1;default:return{nbChannels:r,order:s.AV_CHANNEL_ORDER_UNSPEC,mask:0n}}},an=0x603n,Lt=r=>{switch(r){case 1:return s.AV_CHANNEL_LAYOUT_MONO;case 2:return s.AV_CHANNEL_LAYOUT_STEREO;case 4:return{nbChannels:4,order:s.AV_CHANNEL_ORDER_NATIVE,mask:an};case 5:return s.AV_CHANNEL_LAYOUT_5POINT0;case 6:return s.AV_CHANNEL_LAYOUT_5POINT1;default:return{nbChannels:r,order:s.AV_CHANNEL_ORDER_UNSPEC,mask:0n}}},Ut=r=>{switch(r){case 1:return s.AV_CHANNEL_LAYOUT_MONO;case 2:return s.AV_CHANNEL_LAYOUT_STEREO;case 3:return s.AV_CHANNEL_LAYOUT_SURROUND;case 4:return s.AV_CHANNEL_LAYOUT_4POINT0;case 5:return s.AV_CHANNEL_LAYOUT_5POINT0;case 6:return s.AV_CHANNEL_LAYOUT_5POINT1;default:return{nbChannels:r,order:s.AV_CHANNEL_ORDER_UNSPEC,mask:0n}}};var z=class z{constructor(){}static get level(){return z._level}static set level(t){if(t!==0&&t!==1&&t!==2&&t!==3)throw new TypeError("Invalid log level. Use one of the values of the LogLevel enum.");z._level=t}static get _emitter(){return z._emitterInstance??=new Fe}static on(t,e,n){return z._emitter.on(t,e,n)}static _error(...t){z._emitter._emit("error",t),z._level>=1&&console.error(...t)}static _warn(...t){z._emitter._emit("warn",t),z._level>=2&&console.warn(...t)}static _info(...t){z._emitter._emit("info",t),z._level>=3&&console.info(...t)}};z._level=3,z._emitterInstance=null;var ie=z;function b(r){if(!r)throw new Error("Assertion failed.")}var vi=Math.PI/180,yi=180/Math.PI;var Ae=r=>r&&r[r.length-1];var p=r=>{let t=0;for(;r.readBits(1)===0&&t<32;)t++;if(t>=32)throw new Error("Invalid exponential-Golomb code.");return 2**t-1+r.readBits(t)};var ee=r=>{let t=p(r);return t%2===0?-(t/2):(t+1)/2};var O=r=>r.constructor===Uint8Array?r:ArrayBuffer.isView(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r),he=r=>r.constructor===DataView?r:ArrayBuffer.isView(r)?new DataView(r.buffer,r.byteOffset,r.byteLength):new DataView(r),_i=typeof globalThis.TextEncoder<"u"?globalThis.TextEncoder:class{constructor(){this.encoding="utf-8"}encode(t=""){let e=new Uint8Array(3*t.length),n=0;for(let i=0;i<t.length;i++){let o=t.charCodeAt(i);if(o<128)e[n++]=o;else if(o<2048)e[n++]=192|o>>6,e[n++]=128|o&63;else if(o<55296||o>57343)e[n++]=224|o>>12,e[n++]=128|o>>6&63,e[n++]=128|o&63;else{let a=i+1<t.length?t.charCodeAt(i+1):0;o<56320&&a>=56320&&a<=57343?(o=65536+(o-55296<<10)+(a-56320),i++,e[n++]=240|o>>18,e[n++]=128|o>>12&63,e[n++]=128|o>>6&63,e[n++]=128|o&63):(e[n++]=239,e[n++]=191,e[n++]=189)}}return e.slice(0,n)}},Ei=typeof globalThis.TextDecoder<"u"?globalThis.TextDecoder:class{constructor(t="utf-8"){let e=t.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 ('${t}') is invalid.`)}decode(t){let e=t?O(t):new Uint8Array(0),n=[];if(this.encoding==="utf-8"){let o=e.length>=3&&e[0]===239&&e[1]===187&&e[2]===191?3:0;for(;o<e.length;){let a=e[o];if(a<128){n.push(a),o++;continue}let c,u;if(a>=194&&a<224)c=1,u=a&31;else if(a>=224&&a<240)c=2,u=a&15;else if(a>=240&&a<245)c=3,u=a&7;else{n.push(65533),o++;continue}let d=a===224?160:a===240?144:128,f=a===237?159:a===244?143:191,m=1;for(;m<=c;m++){let x=o+m<e.length?e[o+m]:0;if(x<d||x>f)break;u=u<<6|x&63,d=128,f=191}o+=m,m<=c?n.push(65533):u>=65536?(u-=65536,n.push(55296|u>>10,56320|u&1023)):n.push(u)}}else{let o=this.encoding==="utf-16le",a=o?255:254,c=o?254:255,u=e.length>=2&&e[0]===a&&e[1]===c?2:0;for(;u+1<e.length;){let d=o?e[u]|e[u+1]<<8:e[u]<<8|e[u+1];if(u+=2,d>=55296&&d<=56319){let f=u+1<e.length?o?e[u]|e[u+1]<<8:e[u]<<8|e[u+1]:-1;f>=56320&&f<=57343?(n.push(d,f),u+=2):n.push(65533)}else d>=56320&&d<=57343?n.push(65533):n.push(d)}u<e.length&&n.push(65533)}let i="";for(let o=0;o<n.length;o+=8192)i+=String.fromCharCode(...n.slice(o,o+8192));return i}};var Ht={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12};var zt={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18};var qt={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9};var nt=r=>r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer||ArrayBuffer.isView(r);var it=r=>[...r].map(t=>t.toString(16).padStart(2,"0")).join("");var ot=r=>(r=r>>1&1431655765|(r&1431655765)<<1,r=r>>2&858993459|(r&858993459)<<2,r=r>>4&252645135|(r&252645135)<<4,r=r>>8&16711935|(r&16711935)<<8,r=r>>16&65535|(r&65535)<<16,r>>>0);var ge=(r,t,e)=>{let n=0,i=r.length-1,o=-1;for(;n<=i;){let a=n+(i-n+1)/2|0;e(r[a])<=t?(o=a,n=a+1):i=a-1}return o};var st=r=>{throw new Error(`Unexpected value: ${r}`)};var Ti=1e6*(1+Number.EPSILON);var rt=null,at=()=>rt!==null?rt:rt=!!(typeof navigator<"u"&&(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent)));var Ii=(async()=>{})().constructor;var _e=r=>{b(Number.isInteger(r.num)),b(Number.isInteger(r.den)),b(r.den!==0);let t=Math.abs(r.num),e=Math.abs(r.den);for(;e!==0;){let i=t%e;t=e,e=i}let n=t||1;return{num:r.num/n,den:r.den/n}};var Fe=class{constructor(){this._listeners=new Map}on(t,e,n){this._listeners.has(t)||this._listeners.set(t,new Set);let i={fn:e,once:n?.once??!1};return this._listeners.get(t).add(i),()=>{this._listeners.get(t)?.delete(i)}}_emit(...t){let[e,n]=t,i=this._listeners.get(e);if(i)for(let o of i){try{o.fn(n)}catch(a){console.error(a)}o.once&&i.delete(o)}}};var ue=I("mediabunny"),A=ae(I("node-av"));var cn=new Set([A.AV_PIX_FMT_YUVJ411P,A.AV_PIX_FMT_YUVJ420P,A.AV_PIX_FMT_YUVJ422P,A.AV_PIX_FMT_YUVJ440P,A.AV_PIX_FMT_YUVJ444P]),G=class r extends ue.VideoSampleResource{get frame(){if(!this._frame)throw new Error("AvFrameVideoSampleResource has been closed.");return this._frame}constructor(t){if(super(),!(t instanceof A.Frame))throw new TypeError("frame must be a NodeAv.Frame.");if(t.getMediaType()!==A.AVMEDIA_TYPE_VIDEO)throw new Error("AvFrameVideoSampleResource must be initialized with a video frame.");this._frame=t}getFormat(){return kt(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 ue.VideoSampleColorSpace({primaries:Pe(this.frame.colorPrimaries),transfer:Re(this.frame.colorTrc),matrix:Be(this.frame.colorSpace),fullRange:this.frame.colorRange===A.AVCOL_RANGE_JPEG||cn.has(this.frame.format)?!0:this.frame.colorRange===A.AVCOL_RANGE_MPEG?!1:null})}close(){this.frame.free(),this._frame=null}getDataPlanes(){return b(this.frame.data),this.frame.data.map((t,e)=>({data:O(t),stride:this.frame.linesize[e]}))}async toRgbSample(t,e){let n=this.frame.width,i=this.frame.height,o=new A.Frame;o.alloc(),o.ref(this.frame);let a=ye(o.format);o.colorPrimaries===A.AVCOL_PRI_UNSPECIFIED&&(o.colorPrimaries=A.AVCOL_PRI_BT709),o.colorTrc===A.AVCOL_TRC_UNSPECIFIED&&(o.colorTrc=a?A.AVCOL_TRC_IEC61966_2_1:A.AVCOL_TRC_BT709),o.colorSpace===A.AVCOL_SPC_UNSPECIFIED&&(o.colorSpace=a?A.AVCOL_SPC_RGB:A.AVCOL_SPC_BT709),o.colorRange===A.AVCOL_RANGE_UNSPECIFIED&&(o.colorRange=a?A.AVCOL_RANGE_JPEG:A.AVCOL_RANGE_MPEG);let c=new A.Frame;c.alloc(),c.width=n,c.height=i,c.format=tt("RGBA"),c.allocBuffer(),c.colorPrimaries=o.colorPrimaries,c.colorTrc=o.colorTrc,c.colorSpace=A.AVCOL_SPC_RGB,c.colorRange=A.AVCOL_RANGE_JPEG;let u=new A.SoftwareScaleContext;u.allocContext(),u.setOption("sws_flags","bilinear");try{let d=await u.scaleFrame(c,o);A.FFmpegError.throwIfError(d,"Scale frame")}finally{u.freeContext(),o.free()}return c.sampleAspectRatio=this.frame.sampleAspectRatio,new ue.VideoSample(new r(c),t)}},ct=(r,t)=>{t.colorPrimaries=Nt(r.colorSpace.primaries??"unknown")??A.AVCOL_PRI_UNSPECIFIED,t.colorSpace=Mt(r.colorSpace.matrix??"unknown")??A.AVCOL_SPC_UNSPECIFIED,t.colorTrc=Vt(r.colorSpace.transfer??"unknown")??A.AVCOL_TRC_UNSPECIFIED,t.colorRange=r.colorSpace.fullRange===!1?A.AVCOL_RANGE_MPEG:r.colorSpace.fullRange===!0?A.AVCOL_RANGE_JPEG:A.AVCOL_RANGE_UNSPECIFIED},Se=async(r,t,e)=>{b(r.format!==null),t.unref(),t.format=tt(r.format),t.width=r.codedWidth,t.height=r.codedHeight,t.sampleAspectRatio=new A.Rational(r.pixelAspectRatio.num,r.pixelAspectRatio.den),ct(r,t);let n=r.allocationSize();return(!e||e.byteLength!==n)&&(e=Buffer.from({length:n})),await r.copyTo(e),t.fromBuffer(e),e},ln=16,ce=[],dn=(r,t)=>{let e=new A.FilterGraph;e.alloc();try{let n=e.createFilter(A.Filter.getByName("buffer"),"src",r),i=e.createFilter(A.Filter.getByName("buffersink"),"sink");b(n&&i);let o=A.FilterInOut.createList([{name:"in",filterCtx:n,padIdx:0}]),a=A.FilterInOut.createList([{name:"out",filterCtx:i,padIdx:0}]),c=e.parsePtr(`[in]${t}[out]`,a,o);return A.FFmpegError.throwIfError(c,"FilterGraph.parsePtr"),A.FFmpegError.throwIfError(e.configSync(),"FilterGraph.config"),{key:`${r}|${t}`,graph:e,src:n,sink:i,busy:!0}}catch(n){throw e.free(),n}},un=(r,t)=>{let e=`${r}|${t}`,n=ce.findIndex(o=>o.key===e&&!o.busy);if(n===-1)return null;let i=ce[n];return i.busy=!0,ce.splice(n,1),ce.push(i),i},fn=r=>{if(ce.length>=ln){let t=ce.findIndex(e=>!e.busy);if(t===-1){r.graph.free();return}ce.splice(t,1)[0].graph.free()}r.busy=!1,ce.push(r)},mn=async(r,t,e)=>{A.FFmpegError.throwIfError(await r.src.buffersrcAddFrame(e),"buffersrcAddFrame");let n=new A.Frame;return n.alloc(),A.FFmpegError.throwIfError(await r.sink.buffersinkGetFrame(n),"buffersinkGetFrame"),new ue.VideoSample(new G(n),{timestamp:t.timestamp,duration:t.duration,rotation:0,flip:!1})},Wt=async(r,t)=>{let e,n=!1;if(r._data instanceof G)e=new A.Frame,e.alloc(),n=!0,A.FFmpegError.throwIfError(e.ref(r._data.frame),"Frame.ref");else{if(r.format===null)return null;e=new A.Frame,e.alloc(),n=!0,await Se(r,e,null)}let i=[];(r.squarePixelWidth!==r.codedWidth||r.squarePixelHeight!==r.codedHeight)&&(i.push(`scale=${r.squarePixelWidth}:${r.squarePixelHeight}`),i.push("setsar=1")),t.rotation===90?i.push("transpose=1"):t.rotation===180?i.push("transpose=1,transpose=1"):t.rotation===270&&i.push("transpose=2"),t.flip&&i.push("hflip"),i.push(`crop=${Math.round(t.crop.width)}:${Math.round(t.crop.height)}:${Math.round(t.crop.left)}:${Math.round(t.crop.top)}`),t.fit==="fill"?i.push(`scale=${t.width}:${t.height}`):t.fit==="contain"?(i.push(`scale=${t.width}:${t.height}:force_original_aspect_ratio=decrease`),i.push(`pad=${t.width}:${t.height}:(ow-iw)/2:(oh-ih)/2:color=black@0`)):t.fit==="cover"&&(i.push(`scale=${t.width}:${t.height}:force_original_aspect_ratio=increase`),i.push(`crop=${t.width}:${t.height}`)),i.push("setsar=1");let o=`video_size=${e.width}x${e.height}:pix_fmt=${e.format}:time_base=1/1000000:pixel_aspect=${r.pixelAspectRatio.num}/${r.pixelAspectRatio.den}:colorspace=${e.colorSpace}:range=${e.colorRange}`,a=i.join(",");try{let c=un(o,a),u=c??dn(o,a);try{return await mn(u,r,e)}finally{c?c.busy=!1:fn(u)}}finally{n&&e.free()}};var X=class r{constructor(t){this.bytes=t;this.pos=0}seekToByte(t){this.pos=8*t}readBit(){let t=Math.floor(this.pos/8),e=this.bytes[t]??0,n=7-(this.pos&7),i=(e&1<<n)>>n;return this.pos++,i}readBits(t){if(t===1)return this.readBit();let e=0;for(let n=0;n<t;n++)e<<=1,e|=this.readBit();return e}writeBits(t,e){let n=this.pos+t;for(let i=this.pos;i<n;i++){let o=Math.floor(i/8),a=this.bytes[o],c=7-(i&7);a&=~(1<<c),a|=(e&1<<n-i-1)>>n-i-1<<c,this.bytes[o]=a}this.pos=n}copyBits(t,e){let n=0;for(n;n<t-7;n+=8)this.writeBits(8,e.readBits(8));let i=t-n;i>0&&this.writeBits(i,e.readBits(i))}readAlignedByte(){if(this.pos%8!==0)throw new Error("Bitstream is not byte-aligned.");let t=this.pos/8,e=this.bytes[t]??0;return this.pos+=8,e}skipBits(t){this.pos+=t}getBitsLeft(){return this.bytes.length*8-this.pos}clone(){let t=new r(this.bytes);return t.pos=this.pos,t}};var $t=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],pn=[-1,1,2,3,4,5,6,8],An=[1,2,3,4,6,7,17,19,20,21,22],Gt=r=>{if(!r||r.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");let t=new X(r),e=lt(t),{frequencyIndex:n,sampleRate:i}=dt(t),o=t.readBits(4),a=null;o>=1&&o<=7&&(a=pn[o]);let c=e,u=!1,d=i;(e===5||e===29)&&(u=e===29,d=dt(t).sampleRate,c=lt(t),c===22&&t.skipBits(4));let f=1024;if(An.includes(c)&&(f=t.readBits(1)?960:1024),e!==5&&e!==29)for(;t.getBitsLeft()>15;){let m=t.pos;if(t.readBits(11)!==695){t.pos=m+1;continue}lt(t)===5&&t.readBits(1)&&(d=dt(t).sampleRate,t.getBitsLeft()>11&&t.readBits(11)===1352&&(u=!!t.readBits(1)));break}return a!==null&&a>1&&(u=!1),{objectType:e,coreObjectType:c,frequencyIndex:n,channelConfiguration:o,coreSampleRate:i,outputSampleRate:d,outputNumberOfChannels:u&&a===1?2:a,frameLength:f}},lt=r=>{let t=r.readBits(5);return t===31?32+r.readBits(6):t},dt=r=>{let t=r.readBits(4);return t===15?{frequencyIndex:t,sampleRate:r.readBits(24)}:{frequencyIndex:t,sampleRate:t<$t.length?$t[t]:null}};var Xt=r=>{let t=new Uint8Array(7),e=new X(t),{coreObjectType:n,frequencyIndex:i,channelConfiguration:o}=r,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,o),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:t,bitstream:e}};var Yt=62,jt=r=>{if(r.length>=2&&r[0]>>1===Yt)return r;let t=new Uint8Array(r.length+2);return t[0]=Yt<<1,t[1]=1,t.set(r,2),t};var gn=["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"],bn=["aac","opus","mp3","vorbis","flac","ac3","eac3","dts","truehd"],Zi=[...bn,...gn];var ft=[{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 fe=[{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 Kt=".01.01.01.01.00",Qt=".0.110.01.01.01.0",Cn=["ap4x","ap4h","apch","apcn","apcs","apco"];var er=[8,10,12];var be=r=>{let{codec:t,codecDescription:e,colorSpace:n,avcCodecInfo:i,hevcCodecInfo:o,vp9CodecInfo:a,av1CodecInfo:c,proresFormat:u}=r;if(t==="avc"){if(b(r.avcType!==null),i){let d=new Uint8Array([i.avcProfileIndication,i.profileCompatibility,i.avcLevelIndication]);return`avc${r.avcType}.${it(d)}`}if(!e||e.byteLength<4)throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${r.avcType}.${it(e.subarray(1,4))}`}else if(t==="hevc"){b(r.hevcType!==null);let d,f,m,x,y,g;if(o)d=o.generalProfileSpace,f=o.generalProfileIdc,m=ot(o.generalProfileCompatibilityFlags),x=o.generalTierFlag,y=o.generalLevelIdc,g=[...o.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 C=he(e),h=C.getUint8(1);d=h>>6&3,f=h&31,m=ot(C.getUint32(2)),x=h>>5&1,y=C.getUint8(12),g=[];for(let S=0;S<6;S++)g.push(C.getUint8(6+S))}let v=`${r.hevcType}.`;for(v+=["","A","B","C"][d]+f,v+=".",v+=m.toString(16).toUpperCase(),v+=".",v+=x===0?"L":"H",v+=y;g.length>0&&g[g.length-1]===0;)g.pop();return g.length>0&&(v+=".",v+=g.map(C=>C.toString(16).toUpperCase()).join(".")),v}else{if(t==="vp8")return"vp8";if(t==="vp9"){if(!a){let S=r.width*r.height,_=Ae(fe).level;for(let N of fe)if(S<=N.maxPictureSize){_=N.level;break}return`vp09.00.${_.toString().padStart(2,"0")}.08`}let d=a.profile.toString().padStart(2,"0"),f=a.level.toString().padStart(2,"0"),m=a.bitDepth.toString().padStart(2,"0"),x=a.chromaSubsampling.toString().padStart(2,"0"),y=a.colourPrimaries.toString().padStart(2,"0"),g=a.transferCharacteristics.toString().padStart(2,"0"),v=a.matrixCoefficients.toString().padStart(2,"0"),C=a.videoFullRangeFlag.toString().padStart(2,"0"),h=`vp09.${d}.${f}.${m}.${x}`;return h+=`.${y}.${g}.${v}.${C}`,h.endsWith(Kt)&&(h=h.slice(0,-Kt.length)),h}else if(t==="av1"){if(!c){let N=r.width*r.height,L=Ae(fe).level;for(let M of fe)if(N<=M.maxPictureSize){L=M.level;break}return`av01.0.${L.toString().padStart(2,"0")}M.08`}let d=c.profile,f=c.level.toString().padStart(2,"0"),m=c.tier?"H":"M",x=c.bitDepth.toString().padStart(2,"0"),y=c.monochrome?"1":"0",g=100*c.chromaSubsamplingX+10*c.chromaSubsamplingY+1*(c.chromaSubsamplingX&&c.chromaSubsamplingY?c.chromaSamplePosition:0),v,C,h,S;or(c)?(v=c.colourPrimaries,C=c.transferCharacteristics,h=c.matrixCoefficients,S=c.videoFullRangeFlag):(v=n?.primaries?Ht[n.primaries]:1,C=n?.transfer?zt[n.transfer]:1,h=n?.matrix?qt[n.matrix]:1,S=n?.fullRange?1:0);let _=`av01.${d}.${f}${m}.${x}`;return _+=`.${y}.${g.toString().padStart(3,"0")}`,_+=`.${v.toString().padStart(2,"0")}`,_+=`.${C.toString().padStart(2,"0")}`,_+=`.${h.toString().padStart(2,"0")}`,_+=`.${S}`,_.endsWith(Qt)&&(_=_.slice(0,-Qt.length)),_}else{if(t==="prores")return u??"apch";t!==null&&st(t)}}throw new TypeError(`Unhandled codec '${t}'.`)};var ut=r=>r.startsWith("avc1")||r.startsWith("avc3")?Number.parseInt(r.slice(5,7),16):r.startsWith("hev1")||r.startsWith("hvc1")?Number(r.split(".")[1]?.replace(/^[ABC]/,"")):null,xn={66:"baseline",77:"main",88:"extended",100:"high",110:"high10",122:"high422",244:"high444"},vn={1:"main",2:"main10",4:"main12"},tr=r=>{let t=ut(r);if(r.startsWith("avc1")||r.startsWith("avc3")){let e=Number.parseInt(r.slice(9,11),16);return{profile:t===null?null:xn[t]??null,level:Number.isNaN(e)||e===0?null:e/10}}if(r.startsWith("hev1")||r.startsWith("hvc1")){let e=Number(r.split(".")[3]?.replace(/^[LH]/,""));return{profile:t===null?null:vn[t]??null,level:Number.isNaN(e)||e===0?null:e/30}}return{profile:null,level:null}},Jt=r=>r===8||r===10||r===12?r:null,Zt=(r,t)=>{let e=O(t);if(r.startsWith("avc1")||r.startsWith("avc3")){let i=rr(e)?.sequenceParameterSets[0],o=i&&mt(i);return o?Jt(8+o.bitDepthLumaMinus8):null}let n=ir(e);return n?Jt(8+n.bitDepthLumaMinus8):null},Ne=r=>{let t=typeof r=="string"?r:r.codec,e=typeof r=="string"?null:r.description;if(t.startsWith("avc1")||t.startsWith("avc3")){if(e&&nt(e)){let n=Zt(t,e);if(n!==null)return n}return[110,122,244].includes(ut(t))?10:8}else if(t.startsWith("hev1")||t.startsWith("hvc1")){if(e&&nt(e)){let n=Zt(t,e);if(n!==null)return n}return ut(t)===2?10:8}else if(t.startsWith("vp09")||t.startsWith("av01")){let n=Number(t.split(".")[3]);return n===10||n===12?n:8}return null};var eo=["avc1","avc3","hev1","hvc1","vp8","vp09","av01",...Cn];var sr=[44100,48e3,88200,96e3,176400,192e3],ar=[1,2,3,4,5,6];var Me=function*(r){let t=0,e=-1;for(;t<r.length-2;){let n=r.indexOf(0,t);if(n===-1||n>=r.length-2)break;t=n;let i=0;if(t+3<r.length&&r[t+1]===0&&r[t+2]===0&&r[t+3]===1?i=4:r[t+1]===0&&r[t+2]===1&&(i=3),i===0){t++;continue}e!==-1&&t>e&&(yield{offset:e,length:t-e}),e=t+i,t=e}e!==-1&&e<r.length&&(yield{offset:e,length:r.length-e})};var pt=r=>r&31,At=r=>{let t=new Uint8Array(r.length),e=r.length,n=0;for(let i=0;i<e;i++)i+2<e&&r[i]===0&&r[i+1]===0&&r[i+2]===3?(t[n++]=0,t[n++]=0,i+=2):t[n++]=r[i];return t.subarray(0,n)};var yo=new Uint8Array([0,0,0,1]);var dr=r=>{try{let t=[],e=[],n=[];for(let c of Me(r)){let u=r.subarray(c.offset,c.offset+c.length),d=pt(u[0]);d===7&&t.length<31?t.push(u):d===8&&e.length<255?e.push(u):d===13&&n.length<255&&n.push(u)}if(t.length===0||e.length===0)return null;let i=t[0],o=mt(i);if(!o)return null;let a=o.profileIdc===100||o.profileIdc===110||o.profileIdc===122||o.profileIdc===144;return{configurationVersion:1,avcProfileIndication:o.profileIdc,profileCompatibility:o.constraintFlags,avcLevelIndication:o.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:t,pictureParameterSets:e,chromaFormat:a?o.chromaFormatIdc:null,bitDepthLumaMinus8:a?o.bitDepthLumaMinus8:null,bitDepthChromaMinus8:a?o.bitDepthChromaMinus8:null,sequenceParameterSetExt:a?n:null}}catch(t){return ie._error("Error building AVC Decoder Configuration Record:",t),null}},ur=r=>{let t=[];t.push(r.configurationVersion),t.push(r.avcProfileIndication),t.push(r.profileCompatibility),t.push(r.avcLevelIndication),t.push(252|r.lengthSizeMinusOne&3),t.push(224|r.sequenceParameterSets.length&31);for(let e of r.sequenceParameterSets){let n=e.byteLength;t.push(n>>8),t.push(n&255);for(let i=0;i<n;i++)t.push(e[i])}t.push(r.pictureParameterSets.length);for(let e of r.pictureParameterSets){let n=e.byteLength;t.push(n>>8),t.push(n&255);for(let i=0;i<n;i++)t.push(e[i])}if((r.avcProfileIndication===100||r.avcProfileIndication===110||r.avcProfileIndication===122||r.avcProfileIndication===144)&&r.chromaFormat!==null){b(r.bitDepthLumaMinus8!==null),b(r.bitDepthChromaMinus8!==null),b(r.sequenceParameterSetExt!==null),t.push(252|r.chromaFormat&3),t.push(248|r.bitDepthLumaMinus8&7),t.push(248|r.bitDepthChromaMinus8&7),t.push(r.sequenceParameterSetExt.length);for(let e of r.sequenceParameterSetExt){let n=e.byteLength;t.push(n>>8),t.push(n&255);for(let i=0;i<n;i++)t.push(e[i])}}return new Uint8Array(t)},rr=r=>{try{let t=he(r),e=0,n=t.getUint8(e++),i=t.getUint8(e++),o=t.getUint8(e++),a=t.getUint8(e++),c=t.getUint8(e++)&3,u=t.getUint8(e++)&31,d=[];for(let y=0;y<u;y++){let g=t.getUint16(e,!1);e+=2,d.push(r.subarray(e,e+g)),e+=g}let f=t.getUint8(e++),m=[];for(let y=0;y<f;y++){let g=t.getUint16(e,!1);e+=2,m.push(r.subarray(e,e+g)),e+=g}let x={configurationVersion:n,avcProfileIndication:i,profileCompatibility:o,avcLevelIndication:a,lengthSizeMinusOne:c,sequenceParameterSets:d,pictureParameterSets:m,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((i===100||i===110||i===122||i===144)&&e+4<=r.length){let y=t.getUint8(e++)&3,g=t.getUint8(e++)&7,v=t.getUint8(e++)&7,C=t.getUint8(e++);x.chromaFormat=y,x.bitDepthLumaMinus8=g,x.bitDepthChromaMinus8=v;let h=[];for(let S=0;S<C;S++){let _=t.getUint16(e,!1);e+=2,h.push(r.subarray(e,e+_)),e+=_}x.sequenceParameterSetExt=h}return x}catch(t){return ie._error("Error deserializing AVC Decoder Configuration Record:",t),null}},fr={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}},mt=r=>{try{let t=At(r),e=new X(t);if(e.skipBits(1),e.skipBits(2),e.readBits(5)!==7)return null;let i=e.readAlignedByte(),o=e.readAlignedByte(),a=e.readAlignedByte();p(e);let c=1,u=0,d=0,f=0;if((i===100||i===110||i===122||i===244||i===44||i===83||i===86||i===118||i===128)&&(c=p(e),c===3&&(f=e.readBits(1)),u=p(e),d=p(e),e.skipBits(1),e.readBits(1))){for(let k=0;k<(c!==3?8:12);k++)if(e.readBits(1)){let ne=k<6?16:64,J=8,H=8;for(let se=0;se<ne;se++){if(H!==0){let le=ee(e);H=(J+le+256)%256}J=H===0?J:H}}}p(e);let m=p(e);if(m===0)p(e);else if(m===1){e.skipBits(1),ee(e),ee(e);let V=p(e);for(let k=0;k<V;k++)ee(e)}p(e),e.skipBits(1);let x=p(e),y=p(e),g=16*(x+1),v=16*(y+1),C=g,h=v,S=e.readBits(1);if(S||e.skipBits(1),e.skipBits(1),e.readBits(1)){let V=p(e),k=p(e),$=p(e),ne=p(e),J,H;if((f===0?c:0)===0)J=1,H=2-S;else{let le=c===3?1:2,we=c===1?2:1;J=le,H=we*(2-S)}C-=J*(V+k),h-=H*($+ne)}if(C<=0||h<=0)return null;let N=2,L=2,M=2,P=null,w={num:1,den:1},R=null,D=null,q=null,F=null,W=e.pos;if(e.readBits(1)){if(e.readBits(1)){let le=e.readBits(8);if(le===255)w={num:e.readBits(16),den:e.readBits(16)};else{let we=fr[le];we&&(w=we)}}e.readBits(1)&&e.skipBits(1),e.readBits(1)&&(e.skipBits(3),P=e.readBits(1),e.readBits(1)&&(N=e.readBits(8),L=e.readBits(8),M=e.readBits(8))),e.readBits(1)&&(p(e),p(e)),e.readBits(1)&&(e.skipBits(32),e.skipBits(32),e.skipBits(1));let H=e.readBits(1);H&&cr(e);let se=e.readBits(1);se&&cr(e),(H||se)&&e.skipBits(1),e.skipBits(1),q=e.pos,F=e.readBits(1),F&&(e.skipBits(1),p(e),p(e),p(e),p(e),R=Math.min(p(e),16),D=Math.min(p(e),16))}if(R===null){b(D===null);let V=o&16;if((i===44||i===86||i===100||i===110||i===122||i===244)&&V)R=0,D=0;else{let k=x+1,$=y+1,ne=(2-S)*$,J=ft.find(se=>se.level>=a)??Ae(ft),H=Math.min(Math.floor(J.maxDpbMbs/(k*ne)),16);R=H,D=H}}return b(D!==null),{emulationUnpreventedBytes:t,profileIdc:i,constraintFlags:o,levelIdc:a,frameMbsOnlyFlag:S,chromaFormatIdc:c,bitDepthLumaMinus8:u,bitDepthChromaMinus8:d,codedWidth:g,codedHeight:v,displayWidth:C,displayHeight:h,pixelAspectRatio:w,colourPrimaries:N,matrixCoefficients:M,transferCharacteristics:L,fullRangeFlag:P,numReorderFrames:R,maxDecFrameBuffering:D,vuiParametersFlagBitOffset:W,bitstreamRestrictionFlagBitOffset:q,bitstreamRestrictionFlag:F}}catch(t){return ie._error("Error parsing AVC SPS:",t),null}},cr=r=>{let t=p(r);r.skipBits(4),r.skipBits(4);for(let e=0;e<=t;e++)p(r),p(r),r.skipBits(1);r.skipBits(5),r.skipBits(5),r.skipBits(5),r.skipBits(5)};var Ve=r=>r>>1&63,nr=r=>{try{let t=new X(At(r));t.skipBits(16),t.readBits(4);let e=t.readBits(3),n=t.readBits(1),{general_profile_space:i,general_tier_flag:o,general_profile_idc:a,general_profile_compatibility_flags:c,general_constraint_indicator_flags:u,general_level_idc:d}=_n(t,e);p(t);let f=p(t),m=0;f===3&&(m=t.readBits(1));let x=p(t),y=p(t),g=x,v=y;if(t.readBits(1)){let F=p(t),W=p(t),Y=p(t),V=p(t),k=1,$=1,ne=m===0?f:0;ne===1?(k=2,$=2):ne===2&&(k=2,$=1),g-=(F+W)*k,v-=(Y+V)*$}if(g<=0||v<=0)return null;let C=p(t),h=p(t);p(t);let _=t.readBits(1)?0:e,N=0;for(let F=_;F<=e;F++)p(t),N=p(t),p(t);p(t),p(t),p(t),p(t),p(t),p(t),t.readBits(1)&&t.readBits(1)&&Sn(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(4),t.skipBits(4),p(t),p(t),t.skipBits(1));let L=p(t);if(En(t,L),t.readBits(1)){let F=p(t);for(let W=0;W<F;W++)p(t),t.skipBits(1)}t.skipBits(1),t.skipBits(1);let M=2,P=2,w=2,R=null,D=0,q={num:1,den:1};if(t.readBits(1)){let F=Tn(t,e);q=F.pixelAspectRatio,M=F.colourPrimaries,P=F.transferCharacteristics,w=F.matrixCoefficients,R=F.fullRangeFlag,D=F.minSpatialSegmentationIdc}return{displayWidth:g,displayHeight:v,pixelAspectRatio:q,colourPrimaries:M,transferCharacteristics:P,matrixCoefficients:w,fullRangeFlag:R,maxDecFrameBuffering:Math.min(N+1,16),numReorderFrames:Math.min(N,16),spsMaxSubLayersMinus1:e,spsTemporalIdNestingFlag:n,generalProfileSpace:i,generalTierFlag:o,generalProfileIdc:a,generalProfileCompatibilityFlags:c,generalConstraintIndicatorFlags:u,generalLevelIdc:d,chromaFormatIdc:f,bitDepthLumaMinus8:C,bitDepthChromaMinus8:h,minSpatialSegmentationIdc:D}}catch(t){return ie._error("Error parsing HEVC SPS:",t),null}},mr=r=>{try{let t=[],e=[],n=[],i=[];for(let f of Me(r)){let m=r.subarray(f.offset,f.offset+f.length),x=Ve(m[0]);x===32&&t.length<65535?t.push(m):x===33&&e.length<65535?e.push(m):x===34&&n.length<65535?n.push(m):(x===39||x===40)&&i.length<65535&&i.push(m)}if(e.length===0||n.length===0)return null;let a=nr(e[0]);if(!a)return null;let c=0;if(n.length>0){let f=n[0],m=new X(At(f));m.skipBits(16),p(m),p(m),m.skipBits(1),m.skipBits(1),m.skipBits(3),m.skipBits(1),m.skipBits(1),p(m),p(m),ee(m),m.skipBits(1),m.skipBits(1),m.readBits(1)&&p(m),ee(m),ee(m),m.skipBits(1),m.skipBits(1),m.skipBits(1),m.skipBits(1);let x=m.readBits(1),y=m.readBits(1);!x&&!y?c=0:x&&!y?c=2:!x&&y?c=3:c=0}let u=[...t.length?[{arrayCompleteness:1,nalUnitType:32,nalUnits:t}]:[],...e.length?[{arrayCompleteness:1,nalUnitType:33,nalUnits:e}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:34,nalUnits:n}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:Ve(i[0][0]),nalUnits:i}]:[]];return{configurationVersion:1,generalProfileSpace:a.generalProfileSpace,generalTierFlag:a.generalTierFlag,generalProfileIdc:a.generalProfileIdc,generalProfileCompatibilityFlags:a.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:a.generalConstraintIndicatorFlags,generalLevelIdc:a.generalLevelIdc,minSpatialSegmentationIdc:a.minSpatialSegmentationIdc,parallelismType:c,chromaFormatIdc:a.chromaFormatIdc,bitDepthLumaMinus8:a.bitDepthLumaMinus8,bitDepthChromaMinus8:a.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:a.spsMaxSubLayersMinus1+1,temporalIdNested:a.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:u}}catch(t){return ie._error("Error building HEVC Decoder Configuration Record:",t),null}},_n=(r,t)=>{let e=r.readBits(2),n=r.readBits(1),i=r.readBits(5),o=0;for(let f=0;f<32;f++)o=o<<1|r.readBits(1);let a=new Uint8Array(6);for(let f=0;f<6;f++)a[f]=r.readBits(8);let c=r.readBits(8),u=[],d=[];for(let f=0;f<t;f++)u.push(r.readBits(1)),d.push(r.readBits(1));if(t>0)for(let f=t;f<8;f++)r.skipBits(2);for(let f=0;f<t;f++)u[f]&&r.skipBits(88),d[f]&&r.skipBits(8);return{general_profile_space:e,general_tier_flag:n,general_profile_idc:i,general_profile_compatibility_flags:o,general_constraint_indicator_flags:a,general_level_idc:c}},Sn=r=>{for(let t=0;t<4;t++)for(let e=0;e<(t===3?2:6);e++)if(!r.readBits(1))p(r);else{let i=Math.min(64,1<<4+(t<<1));t>1&&ee(r);for(let o=0;o<i;o++)ee(r)}},En=(r,t)=>{let e=[];for(let n=0;n<t;n++)e[n]=wn(r,n,t,e)},wn=(r,t,e,n)=>{let i=0,o=0,a=0;if(t!==0&&(o=r.readBits(1)),o){if(t===e){let u=p(r);a=t-(u+1)}else a=t-1;r.readBits(1),p(r);let c=n[a]??0;for(let u=0;u<=c;u++)r.readBits(1)||r.readBits(1);i=n[a]}else{let c=p(r),u=p(r);for(let d=0;d<c;d++)p(r),r.readBits(1);for(let d=0;d<u;d++)p(r),r.readBits(1);i=c+u}return i},Tn=(r,t)=>{let e=2,n=2,i=2,o=null,a=0,c={num:1,den:1};if(r.readBits(1)){let u=r.readBits(8);if(u===255)c={num:r.readBits(16),den:r.readBits(16)};else{let d=fr[u];d&&(c=d)}}return r.readBits(1)&&r.readBits(1),r.readBits(1)&&(r.readBits(3),o=r.readBits(1),r.readBits(1)&&(e=r.readBits(8),n=r.readBits(8),i=r.readBits(8))),r.readBits(1)&&(p(r),p(r)),r.readBits(1),r.readBits(1),r.readBits(1),r.readBits(1)&&(p(r),p(r),p(r),p(r)),r.readBits(1)&&(r.readBits(32),r.readBits(32),r.readBits(1)&&p(r),r.readBits(1)&&In(r,!0,t)),r.readBits(1)&&(r.readBits(1),r.readBits(1),r.readBits(1),a=p(r),p(r),p(r),p(r),p(r)),{pixelAspectRatio:c,colourPrimaries:e,transferCharacteristics:n,matrixCoefficients:i,fullRangeFlag:o,minSpatialSegmentationIdc:a}},In=(r,t,e)=>{let n=!1,i=!1,o=!1;t&&(n=r.readBits(1)===1,i=r.readBits(1)===1,(n||i)&&(o=r.readBits(1)===1,o&&(r.readBits(8),r.readBits(5),r.readBits(1),r.readBits(5)),r.readBits(4),r.readBits(4),o&&r.readBits(4),r.readBits(5),r.readBits(5),r.readBits(5)));for(let a=0;a<=e;a++){let c=r.readBits(1)===1,u=!0;c||(u=r.readBits(1)===1);let d=!1;u?p(r):d=r.readBits(1)===1;let f=1;d||(f=p(r)+1),n&&lr(r,f,o),i&&lr(r,f,o)}},lr=(r,t,e)=>{for(let n=0;n<t;n++)p(r),p(r),e&&(p(r),p(r)),r.readBits(1)},pr=r=>{let t=[];t.push(r.configurationVersion),t.push((r.generalProfileSpace&3)<<6|(r.generalTierFlag&1)<<5|r.generalProfileIdc&31),t.push(r.generalProfileCompatibilityFlags>>>24&255),t.push(r.generalProfileCompatibilityFlags>>>16&255),t.push(r.generalProfileCompatibilityFlags>>>8&255),t.push(r.generalProfileCompatibilityFlags&255),t.push(...r.generalConstraintIndicatorFlags),t.push(r.generalLevelIdc&255),t.push(240|r.minSpatialSegmentationIdc>>8&15),t.push(r.minSpatialSegmentationIdc&255),t.push(252|r.parallelismType&3),t.push(252|r.chromaFormatIdc&3),t.push(248|r.bitDepthLumaMinus8&7),t.push(248|r.bitDepthChromaMinus8&7),t.push(r.avgFrameRate>>8&255),t.push(r.avgFrameRate&255),t.push((r.constantFrameRate&3)<<6|(r.numTemporalLayers&7)<<3|(r.temporalIdNested&1)<<2|r.lengthSizeMinusOne&3),t.push(r.arrays.length&255);for(let e of r.arrays){t.push((e.arrayCompleteness&1)<<7|0|e.nalUnitType&63),t.push(e.nalUnits.length>>8&255),t.push(e.nalUnits.length&255);for(let n of e.nalUnits){t.push(n.length>>8&255),t.push(n.length&255);for(let i=0;i<n.length;i++)t.push(n[i])}}return new Uint8Array(t)},ir=r=>{try{let t=he(r),e=0,n=t.getUint8(e++),i=t.getUint8(e++),o=i>>6&3,a=i>>5&1,c=i&31,u=t.getUint32(e,!1);e+=4;let d=r.subarray(e,e+6);e+=6;let f=t.getUint8(e++),m=(t.getUint8(e++)&15)<<8|t.getUint8(e++),x=t.getUint8(e++)&3,y=t.getUint8(e++)&3,g=t.getUint8(e++)&7,v=t.getUint8(e++)&7,C=t.getUint16(e,!1);e+=2;let h=t.getUint8(e++),S=h>>6&3,_=h>>3&7,N=h>>2&1,L=h&3,M=t.getUint8(e++),P=[];for(let w=0;w<M;w++){let R=t.getUint8(e++),D=R>>7&1,q=R&63,F=t.getUint16(e,!1);e+=2;let W=[];for(let Y=0;Y<F;Y++){let V=t.getUint16(e,!1);e+=2,W.push(r.subarray(e,e+V)),e+=V}P.push({arrayCompleteness:D,nalUnitType:q,nalUnits:W})}return{configurationVersion:n,generalProfileSpace:o,generalTierFlag:a,generalProfileIdc:c,generalProfileCompatibilityFlags:u,generalConstraintIndicatorFlags:d,generalLevelIdc:f,minSpatialSegmentationIdc:m,parallelismType:x,chromaFormatIdc:y,bitDepthLumaMinus8:g,bitDepthChromaMinus8:v,avgFrameRate:C,constantFrameRate:S,numTemporalLayers:_,temporalIdNested:N,lengthSizeMinusOne:L,arrays:P}}catch(t){return ie._error("Error deserializing HEVC Decoder Configuration Record:",t),null}};var Pn={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}},Ar=r=>{let t=new X(r);if(t.readBits(2)!==2)return null;let n=t.readBits(1),o=(t.readBits(1)<<1)+n;if(o===3&&t.skipBits(1),t.readBits(1)===1||t.readBits(1)!==0||(t.skipBits(2),t.readBits(24)!==4817730))return null;let d=8;o>=2&&(d=t.readBits(1)?12:10);let f=t.readBits(3),m=0,x=0;if(f!==7)if(x=t.readBits(1),o===1||o===3){let w=t.readBits(1),R=t.readBits(1);m=!w&&!R?3:w&&!R?2:1,t.skipBits(1)}else m=1;else m=3,x=1;let y=t.readBits(16),g=t.readBits(16),v=y+1,C=g+1,h=v*C,S=Ae(fe).level;for(let P of fe)if(h<=P.maxPictureSize){S=P.level;break}let _=Pn[f],N=_?.colourPrimaries??2,L=_?.transferCharacteristics??2,M=_?.matrixCoefficients??2;return{profile:o,level:S,bitDepth:d,chromaSubsampling:m,videoFullRangeFlag:x,colourPrimaries:N,transferCharacteristics:L,matrixCoefficients:M}};var Rn=function*(r){let t=new X(r),e=()=>{let n=0;for(let i=0;i<8;i++){let o=t.readAlignedByte();if(n+=(o&127)*2**(i*7),!(o&128))break;if(i===7&&o&128)return null}return n>2**32-1?null:n};for(;t.getBitsLeft()>=8;){t.skipBits(1);let n=t.readBits(4),i=t.readBits(1),o=t.readBits(1);t.skipBits(1),i&&t.skipBits(8);let a;if(o){let c=e();if(c===null)return;a=c}else a=Math.floor(t.getBitsLeft()/8);b(t.pos%8===0),yield{type:n,data:r.subarray(t.pos/8,t.pos/8+a)},t.skipBits(a*8)}},hr=r=>{for(let{type:t,data:e}of Rn(r)){if(t!==1)continue;let n=new X(e),i=n.readBits(3),o=n.readBits(1),a=n.readBits(1),c=0,u=0,d=0;if(a)c=n.readBits(5);else{let D=n.readBits(1),q=0;if(D){if(n.skipBits(32),n.skipBits(32),n.readBits(1)){let V=0;for(;V<32&&!n.readBits(1);)V++;V<32&&n.skipBits(V)}q=n.readBits(1),q&&(d=n.readBits(5),n.skipBits(32),n.skipBits(5),n.skipBits(5))}let F=n.readBits(1),W=n.readBits(5);for(let Y=0;Y<=W;Y++){n.skipBits(12);let V=n.readBits(5);if(Y===0&&(c=V),V>7){let k=n.readBits(1);Y===0&&(u=k)}if(q&&n.readBits(1)){let $=d+1;n.skipBits($),n.skipBits($),n.skipBits(1)}F&&n.readBits(1)&&n.skipBits(4)}}let f=n.readBits(4),m=n.readBits(4),x=f+1;n.skipBits(x);let y=m+1;n.skipBits(y);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 D=n.readBits(1);D&&(n.skipBits(1),n.skipBits(1));let q=n.readBits(1),F=0;q?F=2:F=n.readBits(1),F>0&&(n.readBits(1)||n.skipBits(1)),D&&n.skipBits(3)}n.skipBits(1),n.skipBits(1),n.skipBits(1);let v=n.readBits(1),C=8;i===2&&v?C=n.readBits(1)?12:10:i<=2&&(C=v?10:8);let h=0;i!==1&&(h=n.readBits(1));let S=2,_=2,N=2;n.readBits(1)&&(S=n.readBits(8),_=n.readBits(8),N=n.readBits(8));let M=0,P=1,w=1,R=0;return h?M=n.readBits(1):S===1&&_===13&&N===0?(M=1,P=0,w=0):(M=n.readBits(1),i===0?(P=1,w=1):i===1?(P=0,w=0):C===12?(P=n.readBits(1),w=P?n.readBits(1):0):(P=1,w=0),P&&w&&(R=n.readBits(2))),{profile:i,level:c,tier:u,bitDepth:C,monochrome:h,chromaSubsamplingX:P,chromaSubsamplingY:w,chromaSamplePosition:R,videoFullRangeFlag:M,colourPrimaries:S,transferCharacteristics:_,matrixCoefficients:N}}return null},or=r=>r.colourPrimaries!==2||r.transferCharacteristics!==2||r.matrixCoefficients!==2;var gr=(r,t)=>r==="truehd"?(t.byteLength>=8?he(t).getUint32(4):null)===4168249274?"key":"delta":"key";var _o=[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 So=new Uint8Array([5,4,65,67,45,51]),Eo=new Uint8Array([5,4,69,65,67,51]);var Bn=31;var br=r=>{let t=[];for(let e=0;e+2<r.length;e+=3){let n=r[e];(n&4)!==0&&t.push({type:n&3,byte0:r[e+1],byte1:r[e+2]})}return t.length===0||t.length>Bn?null:t};var ke=class extends Oe.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 E.Frame,this.frame.alloc(),this.packet=new E.Packet,this.packet.alloc()}async initCodecContext(e){b(this.codecContext===null);let n=j[this.codec];b(n!==void 0);let i;if(this.codec==="vp9"&&e.sideData.alpha?i=E.Codec.findDecoderByName(E.FF_DECODER_LIBVPX_VP9)??E.Codec.findDecoder(n):this.config.hardwareAcceleration==="prefer-software"||this.codec==="av1"?i=E.Codec.findDecoder(n):i=await Bt(n)??E.Codec.findDecoder(n),!i)throw new Error(`Unable to obtain libav codec for '${this.codec}'.`);let o=new E.CodecContext;o.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}),o.width=this.config.codedWidth??0,o.height=this.config.codedHeight??0,o.codecType=E.AVMEDIA_TYPE_VIDEO,o.codecId=n,o.extraData=this.config.description?Buffer.from(O(this.config.description)):null,o.sampleAspectRatio=new E.Rational(this.pixelAspectRatio.num,this.pixelAspectRatio.den),o.threadCount=0;let a=E.Dictionary.fromObject({strict:E.FF_COMPLIANCE_STRICT}),c=await o.open2(i,a);E.FFmpegError.throwIfError(c,"Open codec context"),this.codecContext=o}async decode(e){if(this.codecContext===null&&await this.initCodecContext(e),b(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=E.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(E.AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL,a)}let n=ge(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 o=await this.codecContext.sendPacket(this.packet);for(E.FFmpegError.throwIfError(o,"Send packet"),this.packet.unref();;){let a=await this.codecContext.receiveFrame(this.frame);if(a===E.AVERROR_EAGAIN||a===E.AVERROR_EOF)break;this.receiveFrame(a)}}receiveFrame(e){E.FFmpegError.throwIfError(e,"Receive frame"),this.frame.sampleAspectRatio=new E.Rational(this.pixelAspectRatio.num,this.pixelAspectRatio.den);let n=Number(this.frame.pts)/1e6,i=Number(this.frame.duration)/1e6,o=ge(this.preciseTimings,Number(this.frame.pts),f=>f.microsecondTimestamp),a=o!==-1?this.preciseTimings[o]: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.");let u=this.frame.getSideData(E.AV_FRAME_DATA_A53_CC),d=this.frame.getSideData(E.AV_FRAME_DATA_DOVI_RPU_BUFFER);this.onSample(new Oe.VideoSample(new G(c),{timestamp:n,duration:i,closedCaptions:u?br(O(u)):null,dolbyVisionRpu:d?jt(O(d)):null}))}async flush(){if(!this.codecContext)return;let e=await this.codecContext.sendPacket(null);for(E.FFmpegError.throwIfError(e,"Flush decoder");;){let n=await this.codecContext.receiveFrame(this.frame);if(n===E.AVERROR_EAGAIN||n===E.AVERROR_EOF)break;this.receiveFrame(n)}this.codecContext.flushBuffers()}close(){this.codecContext?.freeContext(),this.frame.free(),this.packet.free()}};var te=I("mediabunny"),l=ae(I("node-av"));var Cr=new Set(["libx264","libx265"]),Fn={libx264:"x264-params",libx265:"x265-params",libsvtav1:"svtav1-params"},Nn=2**20,Vn={apco:l.AV_PROFILE_PRORES_PROXY,apcs:l.AV_PROFILE_PRORES_LT,apcn:l.AV_PROFILE_PRORES_STANDARD,apch:l.AV_PROFILE_PRORES_HQ,ap4h:l.AV_PROFILE_PRORES_4444,ap4x:l.AV_PROFILE_PRORES_XQ},yr={8:[l.AV_PIX_FMT_YUV420P,l.AV_PIX_FMT_NV12,l.AV_PIX_FMT_YUV422P,l.AV_PIX_FMT_YUV444P],10:[l.AV_PIX_FMT_YUV420P10LE,l.AV_PIX_FMT_P010LE,l.AV_PIX_FMT_YUV422P10LE,l.AV_PIX_FMT_YUV444P10LE],12:[l.AV_PIX_FMT_YUV420P12LE,l.AV_PIX_FMT_YUV422P12LE,l.AV_PIX_FMT_YUV444P12LE]},_r={8:[l.AV_PIX_FMT_YUVA420P,l.AV_PIX_FMT_YUVA422P,l.AV_PIX_FMT_YUVA444P],10:[l.AV_PIX_FMT_YUVA420P10LE,l.AV_PIX_FMT_YUVA422P10LE,l.AV_PIX_FMT_YUVA444P10LE],12:[l.AV_PIX_FMT_YUVA422P12LE,l.AV_PIX_FMT_YUVA444P12LE]},ht=(r,t,e)=>{let n=e?_r[t]:yr[t];return r?n.find(i=>r.includes(i))??null:n[0]},xr=r=>{for(let t of er)if(yr[t].includes(r)||_r[t].includes(r))return t;return null},Mn=(r,t)=>!(r===l.AVCOL_TRC_SMPTE2084||r===l.AVCOL_TRC_ARIB_STD_B67)||t===null||t>=10?r:(te.Logging._warn(`Encoding ${t}-bit output from frames labelled '${r===l.AVCOL_TRC_SMPTE2084?"pq":"hlg"}'. That transfer function needs at least 10 bits, so the output states no transfer instead of claiming one its samples cannot carry.`),l.AVCOL_TRC_UNSPECIFIED),kn=r=>{let{codecName:t,supportedPixelFormats:e,requestedBitDepth:n,incomingBitDepth:i,wantsAlpha:o}=r,a=n??i;if(a!==null){let u=ht(e,a,o);if(u!==null)return u;if(n!==null)throw new Error(`Encoder '${t??"unknown"}' cannot encode ${n}-bit video${o?" with alpha":""}, which the requested codec profile demands.`)}let c=l.AV_PIX_FMT_YUV420P;return e&&(e.includes(l.AV_PIX_FMT_YUV420P)||(c=e[0]),o&&(e.includes(l.AV_PIX_FMT_YUVA420P)?c=l.AV_PIX_FMT_YUVA420P:c=l.avcodecFindBestPixFmtOfList(e,l.AV_PIX_FMT_YUVA444P12LE))),c},De=(r,t)=>{if(r==="prores"){let e=l.Codec.findEncoderByName(l.FF_ENCODER_PRORES_KS);if(e)return e}return l.Codec.findEncoder(t)},On=r=>{let t=Math.round(r*1001);return t%1e3===0&&Math.abs(t/1001-r)<1e-4&&!Number.isInteger(r)?{num:t,den:1001}:_e({num:Math.round(r*1e3),den:1e3})},vr=r=>{let{_maxBitrate:t,_bufferSize:e}=r;return t===void 0?null:{maxBitrate:t,bufferSize:e}},Le=class extends te.CustomVideoEncoder{constructor(){super(...arguments);this.codecContext=null;this.scaler=null;this.dstFrame=null;this.lastBuffer=null;this.packetEmitted=!1;this.quantizer=null;this.preciseTimings=[]}static supports(e,n){if(!(n.bitrateMode==="quantizer"?e==="avc"||e==="hevc"||e==="vp9"||e==="av1":e==="avc"||e==="hevc"||e==="vp8"||e==="vp9"||e==="av1"||e==="prores"))return!1;if(vr(n)){if(n.bitrateMode!=="quantizer")return!1;let u=j[e];if(b(u!==void 0),De(e,u)?.name==="librav1e")return!1}let o=Ne(n.codec);if(o===null)return!0;let a=j[e];b(a!==void 0);let c=De(e,a);return!!c&&ht(c.pixelFormats,o,n.alpha==="keep")!==null}async init(){this.frame=new l.Frame,this.frame.alloc(),this.frame.timeBase=new l.Rational(1,1e6),this.packet=new l.Packet,this.packet.alloc();let e=j[this.codec];b(e!==void 0);let n=this.config.alpha==="keep",i=Ne(this.config.codec),o=null;if(this.codec==="vp9"&&n)o=l.Codec.findEncoderByName(l.FF_ENCODER_LIBVPX_VP9)??l.Codec.findEncoder(e);else if(this.config.hardwareAcceleration==="prefer-software")o=De(this.codec,e);else{let a=await Ft(e);a&&this.config.bitrateMode==="quantizer"&&!a.name?.endsWith("_nvenc")&&(a=null),a&&i!==null&&ht(a.pixelFormats,i,n)===null&&(a=null),o=a??De(this.codec,e)}if(!o)throw new Error(`Unable to obtain libav codec for '${this.codec}'.`);te.Logging._info(`Encoding '${this.codec}' with ${o.name??"unknown codec"}.`),this.avCodec=o}async createCodecContext(){b(this.codecContext===null);let e=new l.CodecContext;e.allocContext3(this.avCodec);let n=xr(this.frame.format),i=kn({codecName:this.avCodec.name,supportedPixelFormats:this.avCodec.pixelFormats,requestedBitDepth:Ne(this.config.codec),incomingBitDepth:n,wantsAlpha:this.config.alpha==="keep"}),o=_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=i,e.threadCount=0,e.timeBase=new l.Rational(1,1e6),e.gopSize=2**30;let a=On(this.config.framerate||30);e.framerate=new l.Rational(a.num,a.den),e.bitRate=this.config.bitrateMode==="quantizer"?0n:BigInt(this.config.bitrate??new te.Quality("medium")._toVideoBitrate(this.codec,this.config.width,this.config.height)),e.sampleAspectRatio=new l.Rational(o.num,o.den);let c=this.frame.colorPrimaries,u=this.frame.colorTrc,d=this.frame.colorSpace,f=this.frame.colorRange,m=ye(this.frame.format),x=ye(i);m&&!x?(c===l.AVCOL_PRI_UNSPECIFIED&&(c=l.AVCOL_PRI_BT709),(u===l.AVCOL_TRC_UNSPECIFIED||u===l.AVCOL_TRC_IEC61966_2_1)&&(u=l.AVCOL_TRC_BT709),c===l.AVCOL_PRI_BT2020?d=l.AVCOL_SPC_BT2020_NCL:c===l.AVCOL_PRI_BT470BG?d=l.AVCOL_SPC_BT470BG:c===l.AVCOL_PRI_SMPTE170M?d=l.AVCOL_SPC_SMPTE170M:d=l.AVCOL_SPC_BT709,f=l.AVCOL_RANGE_MPEG):!m&&x&&(d=l.AVCOL_SPC_RGB,f=l.AVCOL_RANGE_JPEG),e.colorPrimaries=c,e.colorTrc=Mn(u,xr(i)),e.colorSpace=d,e.colorRange=f,this.config.bitrateMode==="constant"&&(e.rcMinRate=e.bitRate,e.rcMaxRate=e.bitRate);let y=this.config.latencyMode==="realtime",g=new Map;if(this.avCodec.name==="libx264"?(g.set("scenecut","0"),y&&(e.setOption("tune","zerolatency"),e.setOption("preset","ultrafast"))):this.avCodec.name==="libx265"?(g.set("log-level","error"),g.set("scenecut","0"),g.set("open-gop","0"),e.setOption("forced-idr","1"),y&&(e.setOption("tune","zerolatency"),e.setOption("preset","ultrafast"))):this.avCodec.name==="libvpx"?(y&&e.setOption("deadline","realtime"),e.setOption("cpu-used","8")):this.avCodec.name==="libvpx-vp9"?(e.setOption("deadline","realtime"),y?e.setOption("cpu-used","8"):e.setOption("cpu-used","5")):this.avCodec.name==="libsvtav1"?(process.env.SVT_LOG="1",y&&e.setOption("preset","12")):(this.avCodec.name==="h264_nvenc"||this.avCodec.name==="hevc_nvenc")&&e.setOption("forced-idr","1"),this.config.bitrateMode==="quantizer"){b(this.quantizer!==null);let C;this.avCodec.name==="libaom-av1"||this.avCodec.name==="libsvtav1"?C=Math.round(this.quantizer/4):C=this.quantizer;let h=vr(this.config);if(h){let S=h.bufferSize??2*h.maxBitrate,_=!1;if(this.avCodec.name==="libx264"||this.avCodec.name==="libx265")e.setOption("crf",String(C)),e.rcMaxRate=BigInt(h.maxBitrate),e.rcBufferSize=S,_=!0;else if(this.avCodec.name==="libsvtav1")e.setOption("crf",String(Math.max(C,1))),e.rcMaxRate=BigInt(h.maxBitrate),e.rcBufferSize=S,_=!0;else if(this.avCodec.name==="libvpx-vp9"||this.avCodec.name==="libaom-av1")e.setOption("crf",String(C)),e.bitRate=BigInt(h.maxBitrate);else if(this.avCodec.name?.endsWith("_nvenc"))e.setOption("rc","vbr"),e.setOption("cq",String(C)),e.rcMaxRate=BigInt(h.maxBitrate);else throw new Error(`Encoder '${this.avCodec.name}' cannot be used for capped quantizer-based encoding.`);h.bufferSize!==void 0&&!_&&te.Logging._warn(`bufferSize has no effect with '${this.avCodec.name}', whose capped mode bounds the bitrate rather than a buffer, so maxBitrate alone is the cap. Encode avc, hevc or av1 with their software encoders for a buffer model.`)}else if(this.avCodec.name==="libx264"||this.avCodec.name==="libx265")e.setOption("crf",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("crf",String(Math.max(C,1)));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.`);!h&&(this.avCodec.name==="librav1e"||this.avCodec.name?.endsWith("_nvenc"))&&(e.qMin=C,e.qMax=C)}if(this.codec==="prores"){let C=Vn[this.config.codec];b(C!==void 0),e.setOption("profile",String(C))}this.applyEncoderControls(e,g);let v=await e.open2();l.FFmpegError.throwIfError(v,"Open codec context"),this.codecContext=e}applyEncoderControls(e,n){let i=this.avCodec.name??"",o=this.config._encoderControls,a=Fn[i]??null,c=g=>{throw new Error(`encoderControls.${g} is not supported by the selected encoder (${i}). Use encoderControls.options to pass an option this encoder has.`)},u=(g,v,C)=>{e.setOption(g,v)<0&&c(C)},f=this.config._codecStringIsDerived?{profile:null,level:null}:tr(this.config.codec),m=o?.profile??f.profile??void 0,x=o?.level??f.level??void 0;m!==void 0&&(o?.profile!==void 0||Cr.has(i))&&u("profile",m,"profile"),x!==void 0&&(o?.level!==void 0||Cr.has(i))&&(i==="libx265"?n.set("level-idc",String(Math.round(x*10))):u("level",x.toFixed(1),"level")),o&&(o.preset!==void 0&&u("preset",o.preset,"preset"),o.tune!==void 0&&u("tune",o.tune,"tune"),o.maxBFrames!==void 0&&u("bf",String(o.maxBFrames),"maxBFrames"),o.closedGop!==void 0&&(a===null&&c("closedGop"),n.set("open-gop",o.closedGop?"0":"1")),o.sceneCut!==void 0&&o.sceneCut!==!1&&(i==="libx264"||i==="libx265"?(n.set("scenecut",String(o.sceneCut)),n.set("min-keyint",String(Nn))):i==="libsvtav1"?n.set("scd","1"):c("sceneCut")),o.pass&&(a===null&&c("pass"),e.flags=e.flags|(o.pass.index===1?l.AV_CODEC_FLAG_PASS1:l.AV_CODEC_FLAG_PASS2),n.set("stats",o.pass.statsPath)));let y={...o?.options};if(a!==null){let g=y[a];delete y[a];for(let v of g?.split(":")??[]){if(v.length===0)continue;let C=v.indexOf("="),h=C===-1?v:v.slice(0,C),S=C===-1?"":v.slice(C+1);if(n.has(h)&&n.get(h)!==S)throw new Error(`encoderControls.options['${a}'] sets '${h}' to '${S}', which conflicts with the '${n.get(h)}' this library needs for key frame alignment. Remove it, or state it through the matching field where one exists.`);n.set(h,S)}}n.size>0&&(b(a!==null),e.setOption(a,[...n].map(([g,v])=>v===""?g:`${g}=${v}`).join(":")));for(let[g,v]of Object.entries(y))e.setOption(g,v)}async encode(e,n){if(this.config.bitrateMode==="quantizer"){let d;if(this.codec==="avc"?d=n.avc?.quantizer:this.codec==="hevc"?d=n.hevc?.quantizer:this.codec==="vp9"?d=n.vp9?.quantizer:d=n.av1?.quantizer,b(d!=null),this.codecContext!==null&&d!==this.quantizer){let f=await this.codecContext.sendFrame(null);for(l.FFmpegError.throwIfError(f,"Send frame");;){let m=await this.codecContext.receivePacket(this.packet);if(m===l.AVERROR_EAGAIN||m===l.AVERROR_EOF)break;this.receivePacket(m)}this.codecContext.freeContext(),this.codecContext=null}this.quantizer=d}if(e._data instanceof G)this.frame.unref(),this.frame.ref(e._data.frame),ct(e,this.frame);else{if(e.format===null)throw new Error("Cannot encode foreign VideoSample with unknown (null) format.");this.lastBuffer=await Se(e,this.frame,this.lastBuffer)}this.codecContext===null&&await this.createCodecContext(),b(this.codecContext);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 l.SoftwareScaleContext,this.scaler.allocContext(),this.scaler.setOption("sws_flags","fast_bilinear")),this.dstFrame||(this.dstFrame=new l.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()),this.dstFrame.copyProps(this.frame),this.dstFrame.colorPrimaries=this.codecContext.colorPrimaries,this.dstFrame.colorTrc=this.codecContext.colorTrc,this.dstFrame.colorSpace=this.codecContext.colorSpace,this.dstFrame.colorRange=this.codecContext.colorRange,this.frame.colorPrimaries=this.codecContext.colorPrimaries,this.frame.colorTrc=this.codecContext.colorTrc;let d=await this.scaler.scaleFrame(this.dstFrame,this.frame);l.FFmpegError.throwIfError(d,"Scale frame"),i=this.dstFrame}i.pts=BigInt(e.microsecondTimestamp),i.duration=BigInt(e.microsecondDuration),i.timeBase=new l.Rational(1,1e6),i.pictType=n?.keyFrame?l.AV_PICTURE_TYPE_I:l.AV_PICTURE_TYPE_NONE,i.keyFrame=n?.keyFrame?1:0;let a=ge(this.preciseTimings,e.microsecondTimestamp,d=>d.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()),i.removeSideData(l.AV_FRAME_DATA_A53_CC);let u=await this.codecContext.sendFrame(i);for(l.FFmpegError.throwIfError(u,"Send frame");;){let d=await this.codecContext.receivePacket(this.packet);if(d===l.AVERROR_EAGAIN||d===l.AVERROR_EOF)break;this.receivePacket(d)}}receivePacket(e){if(b(this.codecContext),l.FFmpegError.throwIfError(e,"Receive packet"),!this.packet.data)return;let n=O(this.packet.data),i=Number(this.packet.pts),o=i/1e6,a=Number(this.packet.duration)/1e6,c=ge(this.preciseTimings,i,h=>h.microsecondTimestamp),u=c!==-1?this.preciseTimings[c]:null;u&&u.microsecondTimestamp===i&&(u.timestampIsValid&&(o=u.timestamp),u.durationIsValid&&(a=u.duration));let d={},f=null,m=null;if(this.codec==="avc"||this.codec==="hevc"){let h=!1;if(this.codec==="avc"?h=this.config.avc?.format==="annexb":h=this.config.hevc?.format==="annexb",!this.packetEmitted){let S;if(this.codec==="avc"){let _=dr(this.packet.data);if(!_)throw new Error("Invalid AVC data, could not extract decoder configuration record.");S=ur(_)}else{let _=mr(this.packet.data);if(!_)throw new Error("Invalid HEVC data, could not extract decoder configuration record.");S=pr(_)}f=be({width:this.config.width,height:this.config.height,codec:this.codec,codecDescription:S,colorSpace:null,avcType:h?3:1,hevcType:h?"hev1":"hvc1",avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null,proresFormat:null}),h||(m=S)}if(!h){let _=[];for(let w of Me(n))if(this.codec==="avc"){let R=pt(n[w.offset]);R!==7&&R!==8&&R!==13&&_.push(w)}else{let R=Ve(n[w.offset]);R!==33&&R!==34&&R!==32&&_.push(w)}let N=0;for(let w of _)N+=4+w.length;let L=new Uint8Array(N),M=new DataView(L.buffer),P=0;for(let w of _){let R=w.length;M.setUint32(P,R,!1),P+=4,L.set(n.subarray(w.offset,w.offset+w.length),P),P+=w.length}n=L}}else if(this.codec==="vp8")this.packetEmitted||(f=be({width:this.config.width,height:this.config.height,codec:"vp8",codecDescription:null,colorSpace:null,avcType:null,hevcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null,proresFormat:null}));else if(this.codec==="vp9"){if(!this.packetEmitted){let h=Ar(n);f=be({width:this.config.width,height:this.config.height,codec:"vp9",codecDescription:null,colorSpace:null,avcType:null,hevcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:h,av1CodecInfo:null,proresFormat:null})}}else if(this.codec==="av1"){if(!this.packetEmitted){let h=hr(n);f=be({width:this.config.width,height:this.config.height,codec:"av1",codecDescription:null,colorSpace:null,avcType:null,hevcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:h,proresFormat:null})}}else if(this.codec==="prores")this.packetEmitted||(f=be({width:this.config.width,height:this.config.height,codec:"prores",codecDescription:null,colorSpace:null,avcType:null,hevcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null,proresFormat:this.config.codec}));else throw new Error("Unreachable.");let x={},y=this.packet.getSideData(l.AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL);y&&(x.alpha=O(y).subarray(8));let g=this.packet.dts,v=g===null||g===l.AV_NOPTS_VALUE?void 0:Number(g)/1e6,C=new te.EncodedPacket(n,this.packet.isKeyframe?"key":"delta",o,a,void 0,void 0,x,v);f!==null&&(d.decoderConfig={codec:f,codedWidth:this.codecContext.width,codedHeight:this.codecContext.height,displayAspectWidth:this.config.displayWidth??this.codecContext.width,displayAspectHeight:this.config.displayHeight??this.codecContext.height,description:m??void 0,colorSpace:{primaries:Pe(this.codecContext.colorPrimaries),matrix:Be(this.codecContext.colorSpace),transfer:Re(this.codecContext.colorTrc),fullRange:this.codecContext.colorRange===l.AVCOL_RANGE_JPEG?!0:this.codecContext.colorRange===l.AVCOL_RANGE_MPEG?!1:void 0}}),this.packetEmitted=!0,this.onPacket(C,d)}async flush(){if(this.codecContext){let e=await this.codecContext.sendFrame(null);for(l.FFmpegError.throwIfError(e,"Send frame");;){let n=await this.codecContext.receivePacket(this.packet);if(n===l.AVERROR_EAGAIN||n===l.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 ze=I("mediabunny"),B=ae(I("node-av"));var Sr=I("mediabunny"),Ce=ae(I("node-av"));var re=class extends Sr.AudioSampleResource{get frame(){if(!this._frame)throw new Error("AvFrameAudioSampleResource has been closed.");return this._frame}constructor(t){if(super(),!(t instanceof Ce.Frame))throw new TypeError("frame must be a NodeAv.Frame.");if(t.getMediaType()!==Ce.AVMEDIA_TYPE_AUDIO)throw new Error("AvFrameAudioSampleResource must be initialized with an audio frame.");this._frame=t}getFormat(){let t=Ot(this.frame.format);if(t===null){let e=Ce.avGetSampleFmtName(this.frame.format);throw new TypeError(`Unsupported audio sample format: ${e} (${this.frame.format})`)}return t}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(t){return b(this.frame.data&&t<this.frame.data.length),O(this.frame.data[t])}},Ue=(r,t)=>{t.unref(),t.format=Dt(r.format),t.nbSamples=r.numberOfFrames,t.sampleRate=r.sampleRate,t.channelLayout=de(r.numberOfChannels),t.allocBuffer(),b(t.data);for(let e=0;e<t.data.length;e++)r.copyTo(t.data[e],{planeIndex:e})};var He=class extends ze.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"||e==="truehd"}async init(){this.frame=new B.Frame,this.frame.alloc(),this.packet=new B.Packet,this.packet.alloc();let e=j[this.codec];b(e!==void 0);let n=B.Codec.findDecoder(e);if(n===null)throw new Error(`Unable to obtain libav codec for '${this.codec}'.`);let i=new B.CodecContext;i.allocContext3(n),i.sampleRate=this.config.sampleRate,i.channelLayout=de(this.config.numberOfChannels),i.timeBase=new B.Rational(1,this.config.sampleRate),i.pktTimebase=new B.Rational(1,this.config.sampleRate),i.codecType=B.AVMEDIA_TYPE_AUDIO,i.codecId=e,i.extraData=this.config.description?Buffer.from(O(this.config.description)):null;let o=await i.open2();B.FFmpegError.throwIfError(o,"Open codec context"),this.codecContext=i}async decode(e){b(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=B.AV_NOPTS_VALUE,this.packet.duration=BigInt(Math.round(e.duration*this.config.sampleRate));let n=await this.codecContext.sendPacket(this.packet);for(B.FFmpegError.throwIfError(n,"Send packet"),this.packet.unref();;){let i=await this.codecContext.receiveFrame(this.frame);if(i===B.AVERROR_EAGAIN||i===B.AVERROR_EOF)break;this.receiveFrame(i)}}receiveFrame(e){B.FFmpegError.throwIfError(e,"Receive frame");let n=this.frame.clone();if(!n)throw new Error("Allocation failure during frame clone.");n.timeBase=new B.Rational(1,this.config.sampleRate),this.onSample(new ze.AudioSample(new re(n)))}async flush(){b(this.codecContext);let e=await this.codecContext.sendPacket(null);for(B.FFmpegError.throwIfError(e,"Flush decoder");;){let n=await this.codecContext.receiveFrame(this.frame);if(n===B.AVERROR_EAGAIN||n===B.AVERROR_EOF)break;this.receiveFrame(n)}this.codecContext.flushBuffers()}close(){this.codecContext?.freeContext(),this.frame.free(),this.packet.free()}};var xe=I("mediabunny"),T=ae(I("node-av"));var Er=[8e3,11025,12e3,16e3,22050,24e3,32e3,44100,48e3],wr=[1,2,4,5,6],Dn=16384,Tr=(r,t,e)=>{if(r<32e3||r>384e4)return!1;let n=e===6,i=e-(n?1:0),o=32*Math.ceil(Math.ceil(r*512/t)/32),a=132+(493+28*32)*i+(n?72:0);return o>=a&&o<=8*Dn};var Ln=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],Un=[8e3,12e3,16e3,24e3,48e3],Hn=[8e3,11025,12e3,16e3,22050,24e3,32e3,44100,48e3],Ir=[32e3,44100,48e3],gt=1024,qe=class extends xe.CustomAudioEncoder{constructor(){super(...arguments);this.codecContext=null;this.resampler=null;this.dstFrame=null;this.inputParametersKey=null;this.resamplerInputSampleRate=null;this.nextResamplerPts=null;this.packetEmitted=!1;this.adtsHeaderTemplate=null}static supports(e,n){let{numberOfChannels:i,sampleRate:o}=n;return e==="aac"&&i>=1&&i<=48&&Ln.includes(o)||e==="opus"&&i>=1&&i<=255&&Un.includes(o)||e==="mp3"&&i>=1&&i<=2&&Hn.includes(o)||e==="vorbis"&&i>=1&&i<=255&&o<=2e5||e==="flac"&&i>=1&&i<=8&&o<=655350||e==="ac3"&&i>=1&&i<=6&&Ir.includes(o)||e==="eac3"&&i>=1&&i<=16&&Ir.includes(o)||e==="dts"&&wr.includes(i)&&Er.includes(o)&&Tr(Pr(n,e),o,i)||e==="truehd"&&ar.includes(i)&&sr.includes(o)}async init(){this.frame=new T.Frame,this.frame.alloc(),this.packet=new T.Packet,this.packet.alloc();let e=j[this.codec];b(e!==void 0);let n=T.Codec.findEncoder(e);if(!n)throw new Error(`Unable to obtain libav codec for '${this.codec}'.`);this.avCodec=n,await this.createCodecContext()}async createCodecContext(){b(this.codecContext===null);let e=new T.CodecContext;e.allocContext3(this.avCodec);let n=T.AV_SAMPLE_FMT_FLTP;this.codec==="truehd"?n=T.AV_SAMPLE_FMT_S32P:this.avCodec.sampleFormats&&!this.avCodec.sampleFormats.includes(T.AV_SAMPLE_FMT_FLTP)&&(n=this.avCodec.sampleFormats[0]),e.sampleRate=this.config.sampleRate,this.codec==="dts"?e.channelLayout=Lt(this.config.numberOfChannels):this.codec==="truehd"?e.channelLayout=Ut(this.config.numberOfChannels):e.channelLayout=de(this.config.numberOfChannels),e.codecType=T.AVMEDIA_TYPE_AUDIO,e.codecId=j[this.codec],e.sampleFormat=n,e.timeBase=new T.Rational(1,this.config.sampleRate),e.bitRate=BigInt(Pr(this.config,this.codec)),this.config.bitrateMode==="constant"&&(e.rcMinRate=e.bitRate,e.rcMaxRate=e.bitRate);let i=this.codec==="dts"||this.codec==="truehd"?T.Dictionary.fromObject({strict:-2}):null,o=await e.open2(this.avCodec,i);T.FFmpegError.throwIfError(o,"Open codec context"),this.codecContext=e}async encode(e){this.codecContext===null&&(await this.createCodecContext(),b(this.codecContext)),e._data instanceof re?(this.frame.unref(),this.frame.ref(e._data.frame)):Ue(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 T.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 T.SoftwareResampleContext,this.resamplerInputSampleRate=this.frame.sampleRate;let a=this.codecContext.channelLayout,c=de(this.frame.channels),u=this.resampler.allocSetOpts2(a,this.codecContext.sampleFormat,this.codecContext.sampleRate,c,this.frame.format,this.frame.sampleRate);T.FFmpegError.throwIfError(u,"allocSetOpts2");let d=this.resampler.init();T.FFmpegError.throwIfError(d,"init"),this.dstFrame=new T.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||gt,this.dstFrame.duration=BigInt(this.dstFrame.nbSamples),this.dstFrame.allocBuffer(),this.nextResamplerPts=this.frame.pts}let o=this.frame.data;if(!o)throw new DOMException("Frame has no data","EncodingError");await this.resampler.convert(null,0,o,this.frame.nbSamples),await this.pullResampledFrames()}else await this.sendFrameAndReceivePackets(this.frame)}async pullResampledFrames(){b(this.codecContext),b(this.resampler),b(this.dstFrame),b(this.nextResamplerPts!==null);let e=this.codecContext.frameSize||gt;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){b(this.codecContext);let n=await this.codecContext.sendFrame(e);for(T.FFmpegError.throwIfError(n,"Send frame");;){let i=await this.codecContext.receivePacket(this.packet);if(i===T.AVERROR_EAGAIN||i===T.AVERROR_EOF)break;this.receivePacket(i)}}receivePacket(e){if(b(this.codecContext),T.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,o=this.packet.data,a;if(this.packetEmitted)a={};else{let u=this.config.codec,d=this.codecContext.extraData?O(this.codecContext.extraData):void 0;if(this.codec==="aac"){if(!d)throw new Error("Extradata expected for AAC.");if(this.config.aac?.format==="adts"){let m=Gt(d);this.adtsHeaderTemplate=Xt(m),d=void 0}}else if(this.codec==="opus"){if(!d)throw new Error("Extradata expected for Opus.")}else if(this.codec==="vorbis"){if(!d)throw new Error("Extradata expected for Vorbis.")}else if(this.codec==="flac"){if(!d)throw new Error("Extradata expected for FLAC.");d=new Uint8Array([102,76,97,67,128,0,0,d.byteLength,...d])}a={decoderConfig:{codec:u,sampleRate:this.codecContext.sampleRate,numberOfChannels:this.codecContext.channels,description:d}}}if(this.adtsHeaderTemplate){let u=o.byteLength+this.adtsHeaderTemplate.header.byteLength;this.adtsHeaderTemplate.bitstream.pos=30,this.adtsHeaderTemplate.bitstream.writeBits(13,u);let d=new Uint8Array(this.adtsHeaderTemplate.header.byteLength+o.byteLength);d.set(this.adtsHeaderTemplate.header,0),d.set(o,this.adtsHeaderTemplate.header.byteLength),o=d}let c=new xe.EncodedPacket(o,gr(this.codec,o),n,i);this.packetEmitted=!0,this.onPacket(c,a)}async flush(){if(this.codecContext){e:if(this.resampler){b(this.resamplerInputSampleRate!==null);let e=this.resampler.getOutSamples(0);if(e===0)break e;let n=this.codecContext.frameSize||gt;b(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.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()}},Pr=(r,t)=>r.bitrate??new xe.Quality("medium")._toAudioBitrate(t)??0;var oe=I("mediabunny"),me=I("turbores");var Br=Symbol.for("@mediabunny/prores loaded");globalThis[Br]&&oe.Logging._error(`[WARNING]
9
- @mediabunny/prores was loaded twice. This will likely cause the decoder not to work correctly. Check if multiple dependencies are importing different versions of @mediabunny/prores, or if something is being bundled incorrectly.`);globalThis[Br]=!0;var ve=class ve extends oe.CustomVideoDecoder{constructor(){super(...arguments);this.decoder=null;this.framePool=[]}static supports(e,n){return e==="prores"}static _determineSupportedVideoFrameFormats(){let e=[],n=new Uint8Array(32);for(let i of me.PIXEL_FORMATS)try{new VideoFrame(n,{format:i,codedWidth:2,codedHeight:2,timestamp:0,duration:0}).close(),e.push(i)}catch{}return e}async init(){typeof VideoFrame<"u"&&(ve._supportedVideoFrameFormats??=ve._determineSupportedVideoFrameFormats());let e=await me.Decoder.create({proresFourCc:this.config.codec,useSharedMemory:me.Decoder.canUseSharedMemory(),allowedOutputFormats:ve._supportedVideoFrameFormats??void 0});if(e instanceof Error)throw e;this.decoder=e}async decode(e){for(b(this.decoder);this.decoder.desiredSize<=0;)await this.decoder.dequeued;this.runDecode(e).catch(n=>this.onError(n))}async runDecode(e){b(this.decoder);let n;this.framePool.length>0?n=this.framePool.shift():n=new me.Frame;let i=await this.decoder.decode(e.data,n);if(this.framePool.push(n),i instanceof Error)throw i;i.visibleHeight<i.codedHeight&&at()&&this.trimCodedHeightToVisibleHeight(i);let o={primaries:i.colorPrimariesString,matrix:i.colorMatrixString,transfer:i.colorTransferString,fullRange:i.colorRangeFull},a=i.visibleWidth,c=i.visibleHeight;i.pixelAspectRatio.num>i.pixelAspectRatio.den?a=Math.round(i.visibleWidth*i.pixelAspectRatio.num/i.pixelAspectRatio.den):c=Math.round(i.visibleHeight*i.pixelAspectRatio.den/i.pixelAspectRatio.num);let u;if(typeof VideoFrame<"u"){let d=new VideoFrame(i.frameData,{format:i.pixelFormat,codedWidth:i.codedWidth,codedHeight:i.codedHeight,displayWidth:a,displayHeight:c,visibleRect:{x:0,y:0,width:i.visibleWidth,height:i.visibleHeight},timestamp:e.microsecondTimestamp,duration:e.microsecondDuration,colorSpace:o});u=new oe.VideoSample(d,{timestamp:e.timestamp,duration:e.duration})}else u=new oe.VideoSample(i.frameData,{format:i.pixelFormat,codedWidth:i.codedWidth,codedHeight:i.codedHeight,displayWidth:a,displayHeight:c,visibleRect:{left:0,top:0,width:i.visibleWidth,height:i.visibleHeight},timestamp:e.timestamp,duration:e.duration,colorSpace:o});this.onSample(u)}trimCodedHeightToVisibleHeight(e){let n=e.pixelFormat.includes("P")?2:1,i=e.pixelFormat.includes("444")?1:2,o=e.pixelFormat.includes("420")?2:1,a=e.codedWidth/i,c=e.codedHeight/o,u=Math.ceil(e.visibleHeight/o),d=e.codedWidth*e.codedHeight,f=e.codedWidth*e.visibleHeight,m=a*c,x=a*u;e.frameData.set(e.frameData.subarray(n*d,n*(d+m)),n*f),e.frameData.set(e.frameData.subarray(n*(d+m),n*(d+2*m)),n*(f+x)),e.codedHeight=e.visibleHeight}async flush(){for(b(this.decoder);this.decoder.decodeQueueSize>0;)await this.decoder.dequeued}async close(){b(this.decoder),await this.decoder.close();for(let e of this.framePool)e.clear()}};ve._supportedVideoFrameFormats=null;var bt=ve,Rr=!1,Fr=()=>{Rr||(Rr=!0,(0,oe.registerDecoder)(bt))};var Vr=I("mediabunny"),Mr=I("node-av"),kr=I("node-av/constants");var zn=1316,qn=1e6,Nr={srt:{accept:{name:"listen_timeout",perSecond:1e6,listenQuery:["mode","listener"]},read:"timeout"},tcp:{accept:{name:"listen_timeout",perSecond:1e3,listenQuery:["listen","1"]},read:"timeout"},udp:{read:"timeout"},rtp:{read:"timeout"},http:{read:"rw_timeout"},https:{read:"rw_timeout"}},Wn=(r,t,e)=>{let n;try{n=new URL(r)}catch{throw new TypeError(`NetworkSource: ${JSON.stringify(r)} is not a URL.`)}let i=n.protocol.slice(0,-1);if(i==="rtmp"||i==="rtmps")throw new TypeError(`NetworkSource: ${i} ignores URL query options, so it cannot be bounded or put into listen mode here.`);let o=Nr[i];if(!o)throw new TypeError(`NetworkSource: unsupported scheme ${JSON.stringify(i)}. Supported: ${Object.keys(Nr).join(", ")}.`);let a=(m,x)=>String(Math.max(1,Math.round(m*x))),[c,u]=o.accept?.listenQuery??[],d=c!==void 0&&n.searchParams.get(c)===u;o.accept&&d&&n.searchParams.set(o.accept.name,a(t,o.accept.perSecond));let f=d?e:Math.max(t,e);return n.searchParams.set(o.read,a(f,qn)),{url:n.toString(),listening:d}},Ct=class{constructor(t,e){this.url=t;this.listening=e;this.pendingRead=null;this.pendingOpen=null;this.opened=!1;this.canceled=!1;this.ioClosed=!1}async closeIo(){!this.io||this.ioClosed||(this.ioClosed=!0,await this.io.closep())}async open(){let t=new Mr.IOContext,e=t.open2(this.url,kr.AVIO_FLAG_READ);this.pendingOpen=e;let n;try{n=await e}finally{this.pendingOpen=null,this.opened=!0}if(n<0)throw new Error(`NetworkSource: could not open ${this.url} (AVERROR ${n}).`);this.io=t}async pull(t){if(this.canceled)return;this.io||await this.open();let e=this.io.read(zn);this.pendingRead=e;let n;try{n=await e}finally{this.pendingRead=null}if(!this.canceled){if(typeof n=="number"||n.length===0){await this.closeIo(),t.close();return}t.enqueue(n)}}async cancel(){this.canceled=!0,this.listening&&!this.opened&&this.pendingOpen&&await Ie(this.url),await this.pendingOpen?.catch(()=>{}),await this.pendingRead?.catch(()=>{}),await this.closeIo()}},$n=(r,t)=>{let e=new Ct(r,t);return new ReadableStream({pull:n=>e.pull(n),cancel:()=>e.cancel()},{highWaterMark:32})},We=class extends Vr.ReadableStreamSource{constructor(t,e={}){if(typeof t!="string")throw new TypeError("url must be a string.");if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.connectTimeout!==void 0&&(!Number.isFinite(e.connectTimeout)||e.connectTimeout<=0))throw new TypeError("options.connectTimeout, when provided, must be a positive number.");if(e.readTimeout!==void 0&&(!Number.isFinite(e.readTimeout)||e.readTimeout<=0))throw new TypeError("options.readTimeout, when provided, must be a positive number.");let n=Wn(t,e.connectTimeout??30,e.readTimeout??30);super($n(n.url,n.listening),{liveRefreshInterval:0,maxCacheSize:e.maxCacheSize})}};var Or=I("mediabunny"),Ge=I("node-av/api"),Dr=I("node-av");var Lr=I("node:stream");var Ur=1e6,Gn="frag_keyframe+empty_moov+default_base_moof",xt=(r,t)=>{if(r!==void 0&&(!Number.isFinite(r)||r<=0))throw new TypeError(`options.${t}, when provided, must be a positive number.`)},Xn=r=>{let t={rw_timeout:String(Math.max(1,Math.round(r.readTimeout*Ur)))};return r.mode==="listener"&&(t.listen="1",t.timeout=String(Math.max(1,Math.round(r.connectTimeout)))),t},Yn=r=>r instanceof Dr.FFmpegError&&(r.isEIO||r.isEPIPE||r.isEOF),vt=class{constructor(t,e){this.url=t;this.options=e;this.pump=null;this.pendingOpen=null;this.canceled=!1;this.notify=null;this.lastByteAt=0;this.silent=!1;this.closed=!1;this.controller=null}closeOnce(){if(!this.closed){this.closed=!0;try{this.controller?.close()}catch{}}}wake(){let t=this.notify;this.notify=null,t?.()}startSilenceClock(){let t=this.options.readTimeout*1e3;this.silenceTimer=setInterval(()=>{this.canceled||this.lastByteAt===0||Date.now()-this.lastByteAt<t||(this.silent=!0,clearInterval(this.silenceTimer),this.closeOnce(),this.wake())},Math.max(50,Math.min(t/4,1e3))),this.silenceTimer.unref?.()}sink(){return new Lr.Writable({write:(t,e,n)=>{!this.canceled&&!this.closed&&(this.lastByteAt=Date.now(),this.controller?.enqueue(new Uint8Array(t)),this.wake()),n()}})}async run(t){this.controller=t,this.startSilenceClock();let e=Ge.Demuxer.open(this.url,{options:Xn(this.options)});this.pendingOpen=e;try{this.demuxer=await e}finally{this.pendingOpen=null}let n=await Ge.Muxer.open(this.sink(),{format:"mp4",options:{movflags:Gn,frag_duration:String(Math.max(1,Math.round(this.options.fragmentDuration*Ur)))}}),i=new Map;for(let o of this.demuxer.streams)i.set(o.index,n.addStream(o));try{for await(let o of this.demuxer.packets()){if(this.canceled||this.silent)break;if(!o)continue;let a=i.get(o.streamIndex);a!==void 0&&await n.writePacket(o,a)}}catch(o){if(!Yn(o))throw o}}pull(t){return this.pump??=this.run(t).then(()=>{this.canceled||this.closeOnce()}).catch(e=>{!this.canceled&&!this.closed&&(this.closed=!0,t.error(e))}).finally(()=>{clearInterval(this.silenceTimer),this.wake()}),new Promise(e=>{this.notify=e})}async cancel(){this.canceled=!0,clearInterval(this.silenceTimer),this.options.mode==="listener"&&this.pendingOpen&&await Ie(this.url),await this.pump?.catch(()=>{}),await this.demuxer?.close().catch(()=>{})}},jn=(r,t)=>{let e=new vt(r,t);return new ReadableStream({pull:n=>e.pull(n),cancel:()=>e.cancel()},{highWaterMark:64})},$e=class extends Or.ReadableStreamSource{constructor(t,e={}){if(typeof t!="string")throw new TypeError("url must be a string.");if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.mode!==void 0&&e.mode!=="listener"&&e.mode!=="caller")throw new TypeError("options.mode, when provided, must be 'listener' or 'caller'.");xt(e.connectTimeout,"connectTimeout"),xt(e.readTimeout,"readTimeout"),xt(e.fragmentDuration,"fragmentDuration");let n=t.slice(0,t.indexOf(":"));if(n!=="rtmp"&&n!=="rtmps")throw new TypeError(`RtmpSource: ${JSON.stringify(t)} is not an rtmp:// or rtmps:// URL.`);super(jn(t,{mode:e.mode??"caller",connectTimeout:e.connectTimeout??30,readTimeout:e.readTimeout??30,fragmentDuration:e.fragmentDuration??.5}),{liveRefreshInterval:0,maxCacheSize:e.maxCacheSize})}};var qr=I("mediabunny"),Wr=I("node:dgram");var St=1e3,$r=2,Hr=12,Kn=200,Qn=201,Gr=202,Jn=204,Zn=205,ei=1,ti=1380537172,yt=(r,t)=>{if(r!==void 0&&(!Number.isFinite(r)||r<=0))throw new TypeError(`options.${t}, when provided, must be a positive number.`)},Ee=(r,t)=>(r-t&65535^32768)-32768,ri=r=>{if(r.length<Hr||r[0]>>6!==$r)return null;let t=Hr+(r[0]&15)*4;if(r[0]&16){if(r.length<t+4)return null;t+=4+(r[t+2]<<8|r[t+3])*4}let e=r.length-(r[0]&32?r[r.length-1]:0);return t>=e?null:{seq:r[2]<<8|r[3],ssrc:(r[8]<<24|r[9]<<16|r[10]<<8|r[11])>>>0,payload:r.subarray(t,e)}},je=(r,t,e,n,i)=>{r[t]=$r<<6|e,r[t+1]=n,r[t+2]=i>>8,r[t+3]=i&255},K=(r,t,e)=>{r[t]=e>>>24&255,r[t+1]=e>>>16&255,r[t+2]=e>>>8&255,r[t+3]=e&255},ni=(r,t,e)=>{let n=[];for(let u of e){let d=n[n.length-1];d&&u===(d.start+d.extra+1&65535)&&d.extra<65535?d.extra++:n.push({start:u,extra:0})}let i=2+e.length,o=2+n.length,a=new Uint8Array((i+1)*4+(o+1)*4);je(a,0,ei,Zn,i),K(a,4,r),K(a,8,t),e.forEach((u,d)=>K(a,12+d*4,u<<16>>>0));let c=(i+1)*4;return je(a,c,0,Jn,o),K(a,c+4,r),K(a,c+8,ti),n.forEach(({start:u,extra:d},f)=>{K(a,c+12+f*4,(u<<16|d)>>>0)}),a},zr=(r,t,e)=>{let n=new TextEncoder().encode("mediabunny"),i=Math.ceil((6+n.length+1)/4),o=new Uint8Array(8*4+(i+1)*4);if(je(o,0,t===0?0:1,Qn,t===0?1:7),K(o,4,r),t!==0){K(o,8,t);let c=Math.max(1,e.received+e.lost);o[12]=Math.min(255,Math.round(e.lost/c*256)),K(o,16,e.lost&16777215),K(o,20,e.highestSeq)}let a=8*4;return je(o,a,1,Gr,i+1),K(o,a+4,r),o[a+8]=1,o[a+9]=n.length,o.set(n,a+10),o},ii=r=>{let t=0;for(;t+8<=r.length;){let e=r[t+2]<<8|r[t+3],n=r[t+1];if(n===Kn||n===Gr)return(r[t+4]<<24|r[t+5]<<16|r[t+6]<<8|r[t+7])>>>0;t+=(e+1)*4}return null},oi=r=>{let t=new URL(r),e=Number(t.port);if(!Number.isInteger(e)||e<=0||e>=65535)throw new TypeError(`RistSource: ${JSON.stringify(r)} must state a port below 65535.`);if(e%2!==0)throw new TypeError(`RistSource: ${JSON.stringify(r)} must state an even port; RTCP uses the next one.`);return{host:t.hostname||"0.0.0.0",port:e}},si=20,Xe=()=>(0,Wr.createSocket)({type:"udp4",reuseAddr:!0}),Ye=(r,t)=>new Promise((e,n)=>{r.once("error",n),r.bind(t,()=>e())}),ai=r=>{try{r.close()}catch{}},ci=async(r,t,e)=>{if(r==="listener"){let i=[Xe(),Xe()];return await Ye(i[0],{address:t,port:e}),await Ye(i[1],{address:t,port:e+1}),i}let n;for(let i=0;i<si;i++){let o=[Xe(),Xe()],a=1024+Math.floor(Math.random()*32e3)*2;try{return await Ye(o[0],{port:a}),await Ye(o[1],{port:a+1}),o}catch(c){n=c,o.forEach(ai)}}throw n},_t=class{constructor(t,e,n){this.host=t;this.port=e;this.options=n;this.ourSsrc=Math.random()*4294967295>>>0;this.closed=!1;this.canceled=!1;this.controller=null;this.buffered=new Map;this.requested=new Map;this.expected=null;this.anchorAt=0;this.senderSsrc=0;this.senderAddress=null;this.learnedControl=!1;this.emittedAny=!1;this.lastByteAt=0;this.received=0;this.lost=0;this.highestSeq=0;this.onMedia=(t,e)=>{let n=ri(new Uint8Array(t));if(n){if(this.lastByteAt=Date.now(),this.received++,this.learnedControl||(this.senderAddress={address:e.address,port:e.port+1}),this.senderSsrc===0&&(this.senderSsrc=n.ssrc),this.expected===null&&(this.expected=n.seq,this.highestSeq=n.seq,this.anchorAt=Date.now()+this.options.bufferMs),Ee(n.seq,this.expected)<0){if(this.emittedAny)return;this.expected=n.seq}Ee(n.seq,this.highestSeq)>0&&(this.highestSeq=n.seq),this.buffered.has(n.seq)||this.buffered.set(n.seq,{payload:n.payload,at:Date.now()}),this.release(),this.sendNacks()}};this.onControl=(t,e)=>{let n=ii(new Uint8Array(t));n!==null&&this.senderSsrc===0&&(this.senderSsrc=n),this.senderAddress={address:e.address,port:e.port},this.learnedControl=!0,this.control?.send(zr(this.ourSsrc,this.senderSsrc,this.reportCounts()),this.senderAddress.port,this.senderAddress.address)}}closeOnce(){if(!this.closed){this.closed=!0;try{this.controller?.close()}catch{}}}stopEverything(){clearInterval(this.silenceTimer),clearInterval(this.releaseTimer),clearInterval(this.keepaliveTimer),this.media?.close(),this.control?.close(),this.media=void 0,this.control=void 0}emit(t){this.canceled||this.closed||(this.emittedAny=!0,this.controller?.enqueue(t))}release(){if(this.expected!==null){if(!this.emittedAny){if(Date.now()<this.anchorAt)return;for(let t of this.buffered.keys())Ee(t,this.expected)<0&&(this.expected=t)}for(;;){let t=this.buffered.get(this.expected);if(t){this.buffered.delete(this.expected),this.requested.delete(this.expected),this.expected=this.expected+1&65535,this.emit(t.payload);continue}if(this.buffered.size===0)return;let e=1/0,n=null;for(let[o,a]of this.buffered)e=Math.min(e,a.at),(n===null||Ee(o,n)<0)&&(n=o);if(Date.now()-e<this.options.bufferMs)return;let i=n;this.lost+=Math.max(1,Ee(i,this.expected));for(let o=this.expected;o!==i;o=o+1&65535)this.requested.delete(o);this.expected=i}}}sendNacks(){if(!this.control||!this.senderAddress||this.expected===null||this.buffered.size===0)return;let t=Date.now(),e=[];for(let n=this.expected;n!==this.highestSeq;n=n+1&65535){if(this.buffered.has(n))continue;let i=this.requested.get(n)??0;if(t-i>=this.options.nackIntervalMs&&(this.requested.set(n,t),e.push(n)),e.length===64)break}e.length>0&&this.control.send(ni(this.ourSsrc,this.senderSsrc,e),this.senderAddress.port,this.senderAddress.address)}reportCounts(){return{highestSeq:this.highestSeq,lost:this.lost,received:this.received}}startAnnouncing(){this.senderAddress={address:this.host,port:this.port+1};let t=()=>{!this.senderAddress||this.received>0||this.control?.send(zr(this.ourSsrc,0,this.reportCounts()),this.senderAddress.port,this.senderAddress.address)};t(),this.keepaliveTimer=setInterval(t,200)}async start(t){this.controller=t;let[e,n]=await ci(this.options.mode,this.host,this.port);this.media=e,this.control=n,e.on("message",this.onMedia),n.on("message",this.onControl),e.on("error",i=>t.error(i)),n.on("error",i=>t.error(i)),this.options.mode==="caller"&&this.startAnnouncing(),this.lastByteAt=Date.now(),this.silenceTimer=setInterval(()=>{!this.closed&&Date.now()-this.lastByteAt>=this.options.readTimeout*1e3&&(this.release(),this.closeOnce(),this.stopEverything())},Math.max(50,Math.min(500,this.options.readTimeout*250))),this.releaseTimer=setInterval(()=>this.release(),Math.max(10,Math.round(this.options.bufferMs/4)))}cancel(){this.canceled=!0,this.closeOnce(),this.stopEverything()}},li=(r,t)=>{let{host:e,port:n}=oi(r),i=new _t(e,n,t);return new ReadableStream({start:o=>i.start(o),cancel:()=>i.cancel()})},Ke=class extends qr.ReadableStreamSource{constructor(t,e={}){if(typeof t!="string")throw new TypeError("url must be a string.");if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.mode!==void 0&&e.mode!=="listener"&&e.mode!=="caller")throw new TypeError("options.mode, when provided, must be 'listener' or 'caller'.");if(yt(e.bufferMs,"bufferMs"),yt(e.readTimeout,"readTimeout"),yt(e.nackIntervalMs,"nackIntervalMs"),t.slice(0,t.indexOf(":"))!=="rist")throw new TypeError(`RistSource: ${JSON.stringify(t)} is not a rist:// URL.`);let i={mode:e.mode??"listener",bufferMs:e.bufferMs??St,readTimeout:e.readTimeout??30,nackIntervalMs:e.nackIntervalMs??20};super(li(t,i),{maxCacheSize:e.maxCacheSize})}};var Xr=I("mediabunny"),Yr=I("node-av"),jr=I("node-av/constants");var pe=1316,di=2*1024*1024,ui=5,Kr={128:16,192:24,256:32},Et=class{constructor(t,e){this.url=t;this.maxQueueBytes=e;this.opening=null;this.pumping=null;this.failure=null;this.closed=!1;this.queue={chunks:[],bytes:0};this.partial=new Uint8Array(pe);this.partialLength=0;this.droppedBytes=0;this.droppedDatagrams=0;this.sentBytes=0;this.writable=new WritableStream({write:n=>this.enqueue(n),close:()=>this.finish(),abort:()=>this.finish(!0)})}async open(){let t=new Yr.IOContext,e=await t.open2(this.url,jr.AVIO_FLAG_WRITE);if(e<0)throw new Error(`SrtTarget: could not open ${this.url} (AVERROR ${e}).`);this.io=t}enqueue(t){if(this.failure)throw this.failure;if(this.queue.bytes+t.byteLength>this.maxQueueBytes){this.droppedBytes+=t.byteLength,this.droppedDatagrams+=Math.ceil(t.byteLength/pe);return}this.queue.chunks.push(t),this.queue.bytes+=t.byteLength,this.pumping??=this.pump().finally(()=>{this.pumping=null})}async writeDatagram(t){let e=this.io;if(await e.write(Buffer.from(t.buffer,t.byteOffset,t.byteLength)),e.error<0)throw new Error(`SrtTarget: the peer stopped accepting data (AVERROR ${e.error}).`);this.sentBytes+=t.byteLength}async pump(){try{for(this.io||(this.opening??=this.open(),await this.opening);this.queue.chunks.length>0;){let t=this.queue.chunks.shift();this.queue.bytes-=t.byteLength;let e=0;for(;e<t.byteLength;){let n=Math.min(pe-this.partialLength,t.byteLength-e);this.partial.set(t.subarray(e,e+n),this.partialLength),this.partialLength+=n,e+=n,this.partialLength===pe&&(this.partialLength=0,await this.writeDatagram(this.partial))}}}catch(t){this.failure??=t instanceof Error?t:new Error(String(t)),this.queue={chunks:[],bytes:0}}}async finish(t=!1){if(!this.closed&&(this.closed=!0,await this.pumping?.catch(()=>{}),!t&&!this.failure&&this.io&&this.partialLength>0&&await this.writeDatagram(this.partial.subarray(0,this.partialLength)).catch(e=>{this.failure??=e instanceof Error?e:new Error(String(e))}),this.io&&(await this.io.flush().catch(()=>{}),await this.io.closep().catch(()=>{})),this.failure&&!t))throw this.failure}},fi=(r,t)=>{let e;try{e=new URL(r)}catch{throw new TypeError(`SrtTarget: ${JSON.stringify(r)} is not a URL.`)}if(e.protocol!=="srt:")throw new TypeError(`SrtTarget: expected an srt:// URL, got ${JSON.stringify(e.protocol)}.`);let n=t.connectTimeout??30,i=o=>String(Math.max(1,Math.round(o*1e6)));return e.searchParams.has("transtype")||e.searchParams.set("transtype","live"),e.searchParams.has("payload_size")||e.searchParams.set("payload_size",String(pe)),e.searchParams.has("mode")||e.searchParams.set("mode","caller"),e.searchParams.has("linger")||e.searchParams.set("linger",String(ui)),t.passphrase!==void 0&&(e.searchParams.set("passphrase",t.passphrase),e.searchParams.set("pbkeylen",String(Kr[t.keyLength??128]))),t.latency!==void 0&&e.searchParams.set("latency",i(t.latency/1e3)),e.searchParams.get("mode")==="listener"&&e.searchParams.set("listen_timeout",i(n)),e.searchParams.set("timeout",i(n)),e.toString()},Qe=class extends Xr.AppendOnlyStreamTarget{constructor(t,e={}){if(typeof t!="string")throw new TypeError("url must be a string.");if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.connectTimeout!==void 0&&(!Number.isFinite(e.connectTimeout)||e.connectTimeout<=0))throw new TypeError("options.connectTimeout, when provided, must be a positive number.");if(e.passphrase!==void 0&&(typeof e.passphrase!="string"||e.passphrase.length<10||e.passphrase.length>79))throw new TypeError("options.passphrase, when provided, must be a string of 10 to 79 characters.");if(e.keyLength!==void 0&&Kr[e.keyLength]===void 0)throw new TypeError("options.keyLength, when provided, must be 128, 192 or 256.");if(e.latency!==void 0&&(!Number.isFinite(e.latency)||e.latency<=0))throw new TypeError("options.latency, when provided, must be a positive number of milliseconds.");if(e.maxQueueBytes!==void 0&&(!Number.isInteger(e.maxQueueBytes)||e.maxQueueBytes<pe))throw new TypeError(`options.maxQueueBytes, when provided, must be an integer of at least ${pe}.`);let n=new Et(fi(t,e),e.maxQueueBytes??di);super(n.writable),this.sink=n}get sentBytes(){return this.sink.sentBytes}get droppedBytes(){return this.sink.droppedBytes}get droppedDatagrams(){return this.sink.droppedDatagrams}};var Jr=Symbol.for("@mediabunny/server loaded");globalThis[Jr]&&U.Logging._error(`[WARNING]
9
+ @mediabunny/prores was loaded twice. This will likely cause the decoder not to work correctly. Check if multiple dependencies are importing different versions of @mediabunny/prores, or if something is being bundled incorrectly.`);globalThis[Br]=!0;var ve=class ve extends oe.CustomVideoDecoder{constructor(){super(...arguments);this.decoder=null;this.framePool=[]}static supports(e,n){return e==="prores"}static _determineSupportedVideoFrameFormats(){let e=[],n=new Uint8Array(32);for(let i of me.PIXEL_FORMATS)try{new VideoFrame(n,{format:i,codedWidth:2,codedHeight:2,timestamp:0,duration:0}).close(),e.push(i)}catch{}return e}async init(){typeof VideoFrame<"u"&&(ve._supportedVideoFrameFormats??=ve._determineSupportedVideoFrameFormats());let e=await me.Decoder.create({proresFourCc:this.config.codec,useSharedMemory:me.Decoder.canUseSharedMemory(),allowedOutputFormats:ve._supportedVideoFrameFormats??void 0});if(e instanceof Error)throw e;this.decoder=e}async decode(e){for(b(this.decoder);this.decoder.desiredSize<=0;)await this.decoder.dequeued;this.runDecode(e).catch(n=>this.onError(n))}async runDecode(e){b(this.decoder);let n;this.framePool.length>0?n=this.framePool.shift():n=new me.Frame;let i=await this.decoder.decode(e.data,n);if(this.framePool.push(n),i instanceof Error)throw i;i.visibleHeight<i.codedHeight&&at()&&this.trimCodedHeightToVisibleHeight(i);let o={primaries:i.colorPrimariesString,matrix:i.colorMatrixString,transfer:i.colorTransferString,fullRange:i.colorRangeFull},a=i.visibleWidth,c=i.visibleHeight;i.pixelAspectRatio.num>i.pixelAspectRatio.den?a=Math.round(i.visibleWidth*i.pixelAspectRatio.num/i.pixelAspectRatio.den):c=Math.round(i.visibleHeight*i.pixelAspectRatio.den/i.pixelAspectRatio.num);let u;if(typeof VideoFrame<"u"){let d=new VideoFrame(i.frameData,{format:i.pixelFormat,codedWidth:i.codedWidth,codedHeight:i.codedHeight,displayWidth:a,displayHeight:c,visibleRect:{x:0,y:0,width:i.visibleWidth,height:i.visibleHeight},timestamp:e.microsecondTimestamp,duration:e.microsecondDuration,colorSpace:o});u=new oe.VideoSample(d,{timestamp:e.timestamp,duration:e.duration})}else u=new oe.VideoSample(i.frameData,{format:i.pixelFormat,codedWidth:i.codedWidth,codedHeight:i.codedHeight,displayWidth:a,displayHeight:c,visibleRect:{left:0,top:0,width:i.visibleWidth,height:i.visibleHeight},timestamp:e.timestamp,duration:e.duration,colorSpace:o});this.onSample(u)}trimCodedHeightToVisibleHeight(e){let n=e.pixelFormat.includes("P")?2:1,i=e.pixelFormat.includes("444")?1:2,o=e.pixelFormat.includes("420")?2:1,a=e.codedWidth/i,c=e.codedHeight/o,u=Math.ceil(e.visibleHeight/o),d=e.codedWidth*e.codedHeight,f=e.codedWidth*e.visibleHeight,m=a*c,x=a*u;e.frameData.set(e.frameData.subarray(n*d,n*(d+m)),n*f),e.frameData.set(e.frameData.subarray(n*(d+m),n*(d+2*m)),n*(f+x)),e.codedHeight=e.visibleHeight}async flush(){for(b(this.decoder);this.decoder.decodeQueueSize>0;)await this.decoder.dequeued}async close(){b(this.decoder),await this.decoder.close();for(let e of this.framePool)e.clear()}};ve._supportedVideoFrameFormats=null;var bt=ve,Rr=!1,Fr=()=>{Rr||(Rr=!0,(0,oe.registerDecoder)(bt))};var Vr=I("mediabunny"),Mr=I("node-av"),kr=I("node-av/constants");var zn=1316,qn=1e6,Nr={srt:{accept:{name:"listen_timeout",perSecond:1e6,listenQuery:["mode","listener"]},read:"timeout"},tcp:{accept:{name:"listen_timeout",perSecond:1e3,listenQuery:["listen","1"]},read:"timeout"},udp:{read:"timeout"},rtp:{read:"timeout"},http:{read:"rw_timeout"},https:{read:"rw_timeout"}},Wn=(r,t,e)=>{let n;try{n=new URL(r)}catch{throw new TypeError(`NetworkSource: ${JSON.stringify(r)} is not a URL.`)}let i=n.protocol.slice(0,-1);if(i==="rtmp"||i==="rtmps")throw new TypeError(`NetworkSource: ${i} ignores URL query options, so it cannot be bounded or put into listen mode here.`);let o=Nr[i];if(!o)throw new TypeError(`NetworkSource: unsupported scheme ${JSON.stringify(i)}. Supported: ${Object.keys(Nr).join(", ")}.`);let a=(m,x)=>String(Math.max(1,Math.round(m*x))),[c,u]=o.accept?.listenQuery??[],d=c!==void 0&&n.searchParams.get(c)===u;o.accept&&d&&n.searchParams.set(o.accept.name,a(t,o.accept.perSecond));let f=d?e:Math.max(t,e);return n.searchParams.set(o.read,a(f,qn)),{url:n.toString(),listening:d}},Ct=class{constructor(t,e){this.url=t;this.listening=e;this.pendingRead=null;this.pendingOpen=null;this.opened=!1;this.canceled=!1;this.ioClosed=!1}async closeIo(){!this.io||this.ioClosed||(this.ioClosed=!0,await this.io.closep())}async open(){let t=new Mr.IOContext,e=t.open2(this.url,kr.AVIO_FLAG_READ);this.pendingOpen=e;let n;try{n=await e}finally{this.pendingOpen=null,this.opened=!0}if(n<0)throw new Error(`NetworkSource: could not open ${this.url} (AVERROR ${n}).`);this.io=t}async pull(t){if(this.canceled)return;this.io||await this.open();let e=this.io.read(zn);this.pendingRead=e;let n;try{n=await e}finally{this.pendingRead=null}if(!this.canceled){if(typeof n=="number"||n.length===0){await this.closeIo(),t.close();return}t.enqueue(n)}}async cancel(){this.canceled=!0,this.listening&&!this.opened&&this.pendingOpen&&await Ie(this.url),await this.pendingOpen?.catch(()=>{}),await this.pendingRead?.catch(()=>{}),await this.closeIo()}},$n=(r,t)=>{let e=new Ct(r,t);return new ReadableStream({pull:n=>e.pull(n),cancel:()=>e.cancel()},{highWaterMark:32})},We=class extends Vr.ReadableStreamSource{constructor(t,e={}){if(typeof t!="string")throw new TypeError("url must be a string.");if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.connectTimeout!==void 0&&(!Number.isFinite(e.connectTimeout)||e.connectTimeout<=0))throw new TypeError("options.connectTimeout, when provided, must be a positive number.");if(e.readTimeout!==void 0&&(!Number.isFinite(e.readTimeout)||e.readTimeout<=0))throw new TypeError("options.readTimeout, when provided, must be a positive number.");let n=Wn(t,e.connectTimeout??30,e.readTimeout??30);super($n(n.url,n.listening),{liveRefreshInterval:0,maxCacheSize:e.maxCacheSize})}};var Or=I("mediabunny"),Ge=I("node-av/api"),Dr=I("node-av");var Lr=I("node:stream");var Ur=1e6,Gn="frag_keyframe+empty_moov+default_base_moof",xt=(r,t)=>{if(r!==void 0&&(!Number.isFinite(r)||r<=0))throw new TypeError(`options.${t}, when provided, must be a positive number.`)},Xn=r=>{let t={rw_timeout:String(Math.max(1,Math.round(r.readTimeout*Ur)))};return r.mode==="listener"&&(t.listen="1",t.timeout=String(Math.max(1,Math.round(r.connectTimeout)))),t},Yn=r=>r instanceof Dr.FFmpegError&&(r.isEIO||r.isEPIPE||r.isEOF),vt=class{constructor(t,e){this.url=t;this.options=e;this.pump=null;this.pendingOpen=null;this.canceled=!1;this.notify=null;this.lastByteAt=0;this.silent=!1;this.closed=!1;this.controller=null}closeOnce(){if(!this.closed){this.closed=!0;try{this.controller?.close()}catch{}}}wake(){let t=this.notify;this.notify=null,t?.()}startSilenceClock(){let t=this.options.readTimeout*1e3;this.silenceTimer=setInterval(()=>{this.canceled||this.lastByteAt===0||Date.now()-this.lastByteAt<t||(this.silent=!0,clearInterval(this.silenceTimer),this.closeOnce(),this.wake())},Math.max(50,Math.min(t/4,1e3))),this.silenceTimer.unref?.()}sink(){return new Lr.Writable({write:(t,e,n)=>{!this.canceled&&!this.closed&&(this.lastByteAt=Date.now(),this.controller?.enqueue(new Uint8Array(t)),this.wake()),n()}})}async run(t){this.controller=t,this.startSilenceClock();let e=Ge.Demuxer.open(this.url,{options:Xn(this.options)});this.pendingOpen=e;try{this.demuxer=await e}finally{this.pendingOpen=null}let n=await Ge.Muxer.open(this.sink(),{format:"mp4",options:{movflags:Gn,frag_duration:String(Math.max(1,Math.round(this.options.fragmentDuration*Ur)))}}),i=new Map;for(let o of this.demuxer.streams)i.set(o.index,n.addStream(o));try{for await(let o of this.demuxer.packets()){if(this.canceled||this.silent)break;if(!o)continue;let a=i.get(o.streamIndex);a!==void 0&&await n.writePacket(o,a)}}catch(o){if(!Yn(o))throw o}}pull(t){return this.pump??=this.run(t).then(()=>{this.canceled||this.closeOnce()}).catch(e=>{!this.canceled&&!this.closed&&(this.closed=!0,t.error(e))}).finally(()=>{clearInterval(this.silenceTimer),this.wake()}),new Promise(e=>{this.notify=e})}async cancel(){this.canceled=!0,clearInterval(this.silenceTimer),this.options.mode==="listener"&&this.pendingOpen&&await Ie(this.url),await this.pump?.catch(()=>{}),await this.demuxer?.close().catch(()=>{})}},jn=(r,t)=>{let e=new vt(r,t);return new ReadableStream({pull:n=>e.pull(n),cancel:()=>e.cancel()},{highWaterMark:64})},$e=class extends Or.ReadableStreamSource{constructor(t,e={}){if(typeof t!="string")throw new TypeError("url must be a string.");if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.mode!==void 0&&e.mode!=="listener"&&e.mode!=="caller")throw new TypeError("options.mode, when provided, must be 'listener' or 'caller'.");xt(e.connectTimeout,"connectTimeout"),xt(e.readTimeout,"readTimeout"),xt(e.fragmentDuration,"fragmentDuration");let n=t.slice(0,t.indexOf(":"));if(n!=="rtmp"&&n!=="rtmps")throw new TypeError(`RtmpSource: ${JSON.stringify(t)} is not an rtmp:// or rtmps:// URL.`);super(jn(t,{mode:e.mode??"caller",connectTimeout:e.connectTimeout??30,readTimeout:e.readTimeout??30,fragmentDuration:e.fragmentDuration??.5}),{liveRefreshInterval:0,maxCacheSize:e.maxCacheSize})}};var qr=I("mediabunny"),Wr=I("node:dgram");var St=1e3,$r=2,Hr=12,Kn=200,Qn=201,Gr=202,Jn=204,Zn=205,ei=1,ti=1380537172,yt=(r,t)=>{if(r!==void 0&&(!Number.isFinite(r)||r<=0))throw new TypeError(`options.${t}, when provided, must be a positive number.`)},Ee=(r,t)=>(r-t&65535^32768)-32768,ri=r=>{if(r.length<Hr||r[0]>>6!==$r)return null;let t=Hr+(r[0]&15)*4;if(r[0]&16){if(r.length<t+4)return null;t+=4+(r[t+2]<<8|r[t+3])*4}let e=r.length-(r[0]&32?r[r.length-1]:0);return t>=e?null:{seq:r[2]<<8|r[3],ssrc:(r[8]<<24|r[9]<<16|r[10]<<8|r[11])>>>0,payload:r.subarray(t,e)}},je=(r,t,e,n,i)=>{r[t]=$r<<6|e,r[t+1]=n,r[t+2]=i>>8,r[t+3]=i&255},K=(r,t,e)=>{r[t]=e>>>24&255,r[t+1]=e>>>16&255,r[t+2]=e>>>8&255,r[t+3]=e&255},ni=(r,t,e)=>{let n=[];for(let u of e){let d=n[n.length-1];d&&u===(d.start+d.extra+1&65535)&&d.extra<65535?d.extra++:n.push({start:u,extra:0})}let i=2+e.length,o=2+n.length,a=new Uint8Array((i+1)*4+(o+1)*4);je(a,0,ei,Zn,i),K(a,4,r),K(a,8,t),e.forEach((u,d)=>K(a,12+d*4,u<<16>>>0));let c=(i+1)*4;return je(a,c,0,Jn,o),K(a,c+4,r),K(a,c+8,ti),n.forEach(({start:u,extra:d},f)=>{K(a,c+12+f*4,(u<<16|d)>>>0)}),a},zr=(r,t,e)=>{let n=new TextEncoder().encode("mediabunny"),i=Math.ceil((6+n.length+1)/4),o=new Uint8Array(8*4+(i+1)*4);if(je(o,0,t===0?0:1,Qn,t===0?1:7),K(o,4,r),t!==0){K(o,8,t);let c=Math.max(1,e.received+e.lost);o[12]=Math.min(255,Math.round(e.lost/c*256)),K(o,16,e.lost&16777215),K(o,20,e.highestSeq)}let a=8*4;return je(o,a,1,Gr,i+1),K(o,a+4,r),o[a+8]=1,o[a+9]=n.length,o.set(n,a+10),o},ii=r=>{let t=0;for(;t+8<=r.length;){let e=r[t+2]<<8|r[t+3],n=r[t+1];if(n===Kn||n===Gr)return(r[t+4]<<24|r[t+5]<<16|r[t+6]<<8|r[t+7])>>>0;t+=(e+1)*4}return null},oi=r=>{let t=new URL(r),e=Number(t.port);if(!Number.isInteger(e)||e<=0||e>=65535)throw new TypeError(`RistSource: ${JSON.stringify(r)} must state a port below 65535.`);if(e%2!==0)throw new TypeError(`RistSource: ${JSON.stringify(r)} must state an even port; RTCP uses the next one.`);return{host:t.hostname||"0.0.0.0",port:e}},si=20,Xe=()=>(0,Wr.createSocket)({type:"udp4",reuseAddr:!0}),Ye=(r,t)=>new Promise((e,n)=>{r.once("error",n),r.bind(t,()=>e())}),ai=r=>{try{r.close()}catch{}},ci=async(r,t,e)=>{if(r==="listener"){let i=[Xe(),Xe()];return await Ye(i[0],{address:t,port:e}),await Ye(i[1],{address:t,port:e+1}),i}let n;for(let i=0;i<si;i++){let o=[Xe(),Xe()],a=1024+Math.floor(Math.random()*32e3)*2;try{return await Ye(o[0],{port:a}),await Ye(o[1],{port:a+1}),o}catch(c){n=c,o.forEach(ai)}}throw n},_t=class{constructor(t,e,n){this.host=t;this.port=e;this.options=n;this.ourSsrc=Math.random()*4294967295>>>0;this.closed=!1;this.canceled=!1;this.controller=null;this.buffered=new Map;this.requested=new Map;this.expected=null;this.anchorAt=0;this.senderSsrc=0;this.senderAddress=null;this.learnedControl=!1;this.emittedAny=!1;this.lastByteAt=0;this.received=0;this.lost=0;this.highestSeq=0;this.onMedia=(t,e)=>{let n=ri(new Uint8Array(t));if(n){if(this.lastByteAt=Date.now(),this.received++,this.learnedControl||(this.senderAddress={address:e.address,port:e.port+1}),this.senderSsrc===0&&(this.senderSsrc=n.ssrc),this.expected===null&&(this.expected=n.seq,this.highestSeq=n.seq,this.anchorAt=Date.now()+this.options.bufferMs),Ee(n.seq,this.expected)<0){if(this.emittedAny)return;this.expected=n.seq}Ee(n.seq,this.highestSeq)>0&&(this.highestSeq=n.seq),this.buffered.has(n.seq)||this.buffered.set(n.seq,{payload:n.payload,at:Date.now()}),this.release(),this.sendNacks()}};this.onControl=(t,e)=>{let n=ii(new Uint8Array(t));n!==null&&this.senderSsrc===0&&(this.senderSsrc=n),this.senderAddress={address:e.address,port:e.port},this.learnedControl=!0,this.control?.send(zr(this.ourSsrc,this.senderSsrc,this.reportCounts()),this.senderAddress.port,this.senderAddress.address)}}closeOnce(){if(!this.closed){this.closed=!0;try{this.controller?.close()}catch{}}}stopEverything(){clearInterval(this.silenceTimer),clearInterval(this.releaseTimer),clearInterval(this.keepaliveTimer),this.media?.close(),this.control?.close(),this.media=void 0,this.control=void 0}emit(t){this.canceled||this.closed||(this.emittedAny=!0,this.controller?.enqueue(t))}release(){if(this.expected!==null){if(!this.emittedAny){if(Date.now()<this.anchorAt)return;for(let t of this.buffered.keys())Ee(t,this.expected)<0&&(this.expected=t)}for(;;){let t=this.buffered.get(this.expected);if(t){this.buffered.delete(this.expected),this.requested.delete(this.expected),this.expected=this.expected+1&65535,this.emit(t.payload);continue}if(this.buffered.size===0)return;let e=1/0,n=null;for(let[o,a]of this.buffered)e=Math.min(e,a.at),(n===null||Ee(o,n)<0)&&(n=o);if(Date.now()-e<this.options.bufferMs)return;let i=n;this.lost+=Math.max(1,Ee(i,this.expected));for(let o=this.expected;o!==i;o=o+1&65535)this.requested.delete(o);this.expected=i}}}sendNacks(){if(!this.control||!this.senderAddress||this.expected===null||this.buffered.size===0)return;let t=Date.now(),e=[];for(let n=this.expected;n!==this.highestSeq;n=n+1&65535){if(this.buffered.has(n))continue;let i=this.requested.get(n)??0;if(t-i>=this.options.nackIntervalMs&&(this.requested.set(n,t),e.push(n)),e.length===64)break}e.length>0&&this.control.send(ni(this.ourSsrc,this.senderSsrc,e),this.senderAddress.port,this.senderAddress.address)}reportCounts(){return{highestSeq:this.highestSeq,lost:this.lost,received:this.received}}startAnnouncing(){this.senderAddress={address:this.host,port:this.port+1};let t=()=>{!this.senderAddress||this.received>0||this.control?.send(zr(this.ourSsrc,0,this.reportCounts()),this.senderAddress.port,this.senderAddress.address)};t(),this.keepaliveTimer=setInterval(t,200)}async start(t){this.controller=t;let[e,n]=await ci(this.options.mode,this.host,this.port);this.media=e,this.control=n,e.on("message",this.onMedia),n.on("message",this.onControl),e.on("error",i=>t.error(i)),n.on("error",i=>t.error(i)),this.options.mode==="caller"&&this.startAnnouncing(),this.lastByteAt=Date.now(),this.silenceTimer=setInterval(()=>{!this.closed&&Date.now()-this.lastByteAt>=this.options.readTimeout*1e3&&(this.release(),this.closeOnce(),this.stopEverything())},Math.max(50,Math.min(500,this.options.readTimeout*250))),this.releaseTimer=setInterval(()=>this.release(),Math.max(10,Math.round(this.options.bufferMs/4)))}cancel(){this.canceled=!0,this.closeOnce(),this.stopEverything()}},li=(r,t)=>{let{host:e,port:n}=oi(r),i=new _t(e,n,t);return new ReadableStream({start:o=>i.start(o),cancel:()=>i.cancel()})},Ke=class extends qr.ReadableStreamSource{constructor(t,e={}){if(typeof t!="string")throw new TypeError("url must be a string.");if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.mode!==void 0&&e.mode!=="listener"&&e.mode!=="caller")throw new TypeError("options.mode, when provided, must be 'listener' or 'caller'.");if(yt(e.bufferMs,"bufferMs"),yt(e.readTimeout,"readTimeout"),yt(e.nackIntervalMs,"nackIntervalMs"),t.slice(0,t.indexOf(":"))!=="rist")throw new TypeError(`RistSource: ${JSON.stringify(t)} is not a rist:// URL.`);let i={mode:e.mode??"listener",bufferMs:e.bufferMs??St,readTimeout:e.readTimeout??30,nackIntervalMs:e.nackIntervalMs??20};super(li(t,i),{maxCacheSize:e.maxCacheSize})}};var Xr=I("mediabunny"),Yr=I("node-av"),jr=I("node-av/constants");var pe=1316,di=2*1024*1024,ui=5,Kr={128:16,192:24,256:32},Et=class{constructor(t,e){this.url=t;this.maxQueueBytes=e;this.opening=null;this.pumping=null;this.failure=null;this.closed=!1;this.queue={chunks:[],bytes:0};this.partial=new Uint8Array(pe);this.partialLength=0;this.droppedBytes=0;this.droppedDatagrams=0;this.sentBytes=0;this.writable=new WritableStream({write:n=>this.enqueue(n),close:()=>this.finish(),abort:()=>this.finish(!0)})}async open(){let t=new Yr.IOContext,e=await t.open2(this.url,jr.AVIO_FLAG_WRITE);if(e<0)throw new Error(`SrtTarget: could not open ${this.url} (AVERROR ${e}).`);this.io=t}enqueue(t){if(this.failure)throw this.failure;if(this.queue.bytes+t.byteLength>this.maxQueueBytes){this.droppedBytes+=t.byteLength,this.droppedDatagrams+=Math.ceil(t.byteLength/pe);return}this.queue.chunks.push(t),this.queue.bytes+=t.byteLength,this.pumping??=this.pump().finally(()=>{this.pumping=null})}async writeDatagram(t){let e=this.io;if(await e.write(Buffer.from(t.buffer,t.byteOffset,t.byteLength)),e.error<0)throw new Error(`SrtTarget: the peer stopped accepting data (AVERROR ${e.error}).`);this.sentBytes+=t.byteLength}async pump(){try{for(this.io||(this.opening??=this.open(),await this.opening);this.queue.chunks.length>0;){let t=this.queue.chunks.shift();this.queue.bytes-=t.byteLength;let e=0;for(;e<t.byteLength;){let n=Math.min(pe-this.partialLength,t.byteLength-e);this.partial.set(t.subarray(e,e+n),this.partialLength),this.partialLength+=n,e+=n,this.partialLength===pe&&(this.partialLength=0,await this.writeDatagram(this.partial))}}}catch(t){this.failure??=t instanceof Error?t:new Error(String(t)),this.queue={chunks:[],bytes:0}}}async finish(t=!1){if(!this.closed){for(this.closed=!0;this.pumping!==null||this.queue.chunks.length>0;)this.pumping??=this.pump().finally(()=>{this.pumping=null}),await this.pumping.catch(()=>{});if(!t&&!this.failure&&this.io&&this.partialLength>0&&await this.writeDatagram(this.partial.subarray(0,this.partialLength)).catch(e=>{this.failure??=e instanceof Error?e:new Error(String(e))}),this.io&&(await this.io.flush().catch(()=>{}),await this.io.closep().catch(()=>{})),this.failure&&!t)throw this.failure}}},fi=(r,t)=>{let e;try{e=new URL(r)}catch{throw new TypeError(`SrtTarget: ${JSON.stringify(r)} is not a URL.`)}if(e.protocol!=="srt:")throw new TypeError(`SrtTarget: expected an srt:// URL, got ${JSON.stringify(e.protocol)}.`);let n=t.connectTimeout??30,i=o=>String(Math.max(1,Math.round(o*1e6)));return e.searchParams.has("transtype")||e.searchParams.set("transtype","live"),e.searchParams.has("payload_size")||e.searchParams.set("payload_size",String(pe)),e.searchParams.has("mode")||e.searchParams.set("mode","caller"),e.searchParams.has("linger")||e.searchParams.set("linger",String(ui)),t.passphrase!==void 0&&(e.searchParams.set("passphrase",t.passphrase),e.searchParams.set("pbkeylen",String(Kr[t.keyLength??128]))),t.latency!==void 0&&e.searchParams.set("latency",i(t.latency/1e3)),e.searchParams.get("mode")==="listener"&&e.searchParams.set("listen_timeout",i(n)),e.searchParams.set("timeout",i(n)),e.toString()},Qe=class extends Xr.AppendOnlyStreamTarget{constructor(t,e={}){if(typeof t!="string")throw new TypeError("url must be a string.");if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.connectTimeout!==void 0&&(!Number.isFinite(e.connectTimeout)||e.connectTimeout<=0))throw new TypeError("options.connectTimeout, when provided, must be a positive number.");if(e.passphrase!==void 0&&(typeof e.passphrase!="string"||e.passphrase.length<10||e.passphrase.length>79))throw new TypeError("options.passphrase, when provided, must be a string of 10 to 79 characters.");if(e.keyLength!==void 0&&Kr[e.keyLength]===void 0)throw new TypeError("options.keyLength, when provided, must be 128, 192 or 256.");if(e.latency!==void 0&&(!Number.isFinite(e.latency)||e.latency<=0))throw new TypeError("options.latency, when provided, must be a positive number of milliseconds.");if(e.maxQueueBytes!==void 0&&(!Number.isInteger(e.maxQueueBytes)||e.maxQueueBytes<pe))throw new TypeError(`options.maxQueueBytes, when provided, must be an integer of at least ${pe}.`);let n=new Et(fi(t,e),e.maxQueueBytes??di);super(n.writable),this.sink=n}get sentBytes(){return this.sink.sentBytes}get droppedBytes(){return this.sink.droppedBytes}get droppedDatagrams(){return this.sink.droppedDatagrams}};var Jr=Symbol.for("@mediabunny/server loaded");globalThis[Jr]&&U.Logging._error(`[WARNING]
10
10
  @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[Jr]=!0;var Qr=!1,Z={},mi=(r={})=>{if(typeof r!="object"||!r)throw new TypeError("options must be an object.");if(r.hardwareContext!=null&&!(r.hardwareContext instanceof Q.HardwareContext||typeof r.hardwareContext=="function"))throw new TypeError("options.hardwareContext, when provided, must be a NodeAv.HardwareContext, a function, or null.");Qr||(Qr=!0,Z=r,Q.Log.setLevel(Q.AV_LOG_ERROR),(0,U.registerDecoder)(ke),Fr(),(0,U.registerEncoder)(Le),(0,U.registerDecoder)(He),(0,U.registerEncoder)(qe),(0,U.registerVideoSampleTransformer)(Wt))},pi=async(r,t)=>{if(!(r instanceof U.VideoSample)&&!(r instanceof U.AudioSample))throw new TypeError("sample must be a VideoSample or an AudioSample.");if(!(t instanceof Q.Frame))throw new TypeError("frame must be a NodeAv.Frame.");if(r instanceof U.VideoSample){if(r._data instanceof G)t.unref(),t.ref(r._data.frame);else{if(r.format===null)throw new Error("Cannot convert foreign VideoSample with unknown (null) format.");await Se(r,t,null)}t.pts=BigInt(r.microsecondTimestamp),t.duration=BigInt(r.microsecondDuration),t.timeBase=new Q.Rational(1,1e6)}else r._data instanceof re?(t.unref(),t.ref(r._data.frame)):Ue(r,t),t.timeBase=new Q.Rational(1,r.sampleRate),t.pts=BigInt(Math.round(r.timestamp*r.sampleRate)),t.duration=BigInt(r.numberOfFrames)};return sn(Ai);})();
11
11
  if (typeof module === "object" && typeof module.exports === "object") Object.assign(module.exports, MediabunnyServer)