mirror of
https://github.com/zhw2590582/ArtPlayer.git
synced 2026-10-08 10:56:15 -08:00
1 line
372 KiB
JavaScript
1 line
372 KiB
JavaScript
(globalThis.webpackChunkfree_video_upscaler=globalThis.webpackChunkfree_video_upscaler||[]).push([[869],{41:(t,e)=>{var i,r,s=(i=new Date,r=4,{setLogLevel:function(t){r=t==this.debug?1:t==this.info?2:t==this.warn?3:(this.error,4)},debug:function(t,e){void 0===console.debug&&(console.debug=console.log),1>=r&&console.debug("["+s.getDurationString(new Date-i,1e3)+"]","["+t+"]",e)},log:function(t,e){this.debug(t.msg)},info:function(t,e){2>=r&&console.info("["+s.getDurationString(new Date-i,1e3)+"]","["+t+"]",e)},warn:function(t,e){3>=r&&console.warn("["+s.getDurationString(new Date-i,1e3)+"]","["+t+"]",e)},error:function(t,e){4>=r&&console.error("["+s.getDurationString(new Date-i,1e3)+"]","["+t+"]",e)}});s.getDurationString=function(t,e){var i;function r(t,e){for(var i=(""+t).split(".");i[0].length<e;)i[0]="0"+i[0];return i.join(".")}t<0?(i=!0,t=-t):i=!1;var s=t/(e||1),a=Math.floor(s/3600);s-=3600*a;var n=Math.floor(s/60),o=1e3*(s-=60*n);return o-=1e3*(s=Math.floor(s)),o=Math.floor(o),(i?"-":"")+a+":"+r(n,2)+":"+r(s,2)+"."+r(o,3)},s.printRanges=function(t){var e=t.length;if(e>0){for(var i="",r=0;r<e;r++)r>0&&(i+=","),i+="["+s.getDurationString(t.start(r))+","+s.getDurationString(t.end(r))+"]";return i}return"(empty)"},e.Log=s;var a=function(t){if(!(t instanceof ArrayBuffer))throw"Needs an array buffer";this.buffer=t,this.dataview=new DataView(t),this.position=0};a.prototype.getPosition=function(){return this.position},a.prototype.getEndPosition=function(){return this.buffer.byteLength},a.prototype.getLength=function(){return this.buffer.byteLength},a.prototype.seek=function(t){var e=Math.max(0,Math.min(this.buffer.byteLength,t));return this.position=isNaN(e)||!isFinite(e)?0:e,!0},a.prototype.isEos=function(){return this.getPosition()>=this.getEndPosition()},a.prototype.readAnyInt=function(t,e){var i=0;if(this.position+t<=this.buffer.byteLength){switch(t){case 1:i=e?this.dataview.getInt8(this.position):this.dataview.getUint8(this.position);break;case 2:i=e?this.dataview.getInt16(this.position):this.dataview.getUint16(this.position);break;case 3:if(e)throw"No method for reading signed 24 bits values";i=this.dataview.getUint8(this.position)<<16,i|=this.dataview.getUint8(this.position+1)<<8,i|=this.dataview.getUint8(this.position+2);break;case 4:i=e?this.dataview.getInt32(this.position):this.dataview.getUint32(this.position);break;case 8:if(e)throw"No method for reading signed 64 bits values";i=this.dataview.getUint32(this.position)<<32,i|=this.dataview.getUint32(this.position+4);break;default:throw"readInt method not implemented for size: "+t}return this.position+=t,i}throw"Not enough bytes in buffer"},a.prototype.readUint8=function(){return this.readAnyInt(1,!1)},a.prototype.readUint16=function(){return this.readAnyInt(2,!1)},a.prototype.readUint24=function(){return this.readAnyInt(3,!1)},a.prototype.readUint32=function(){return this.readAnyInt(4,!1)},a.prototype.readUint64=function(){return this.readAnyInt(8,!1)},a.prototype.readString=function(t){if(this.position+t<=this.buffer.byteLength){for(var e="",i=0;i<t;i++)e+=String.fromCharCode(this.readUint8());return e}throw"Not enough bytes in buffer"},a.prototype.readCString=function(){for(var t=[];;){var e=this.readUint8();if(0===e)break;t.push(e)}return String.fromCharCode.apply(null,t)},a.prototype.readInt8=function(){return this.readAnyInt(1,!0)},a.prototype.readInt16=function(){return this.readAnyInt(2,!0)},a.prototype.readInt32=function(){return this.readAnyInt(4,!0)},a.prototype.readInt64=function(){return this.readAnyInt(8,!1)},a.prototype.readUint8Array=function(t){for(var e=new Uint8Array(t),i=0;i<t;i++)e[i]=this.readUint8();return e},a.prototype.readInt16Array=function(t){for(var e=new Int16Array(t),i=0;i<t;i++)e[i]=this.readInt16();return e},a.prototype.readUint16Array=function(t){for(var e=new Int16Array(t),i=0;i<t;i++)e[i]=this.readUint16();return e},a.prototype.readUint32Array=function(t){for(var e=new Uint32Array(t),i=0;i<t;i++)e[i]=this.readUint32();return e},a.prototype.readInt32Array=function(t){for(var e=new Int32Array(t),i=0;i<t;i++)e[i]=this.readInt32();return e},e.MP4BoxStream=a;var n=function(t,e,i){this._byteOffset=e||0,t instanceof ArrayBuffer?this.buffer=t:"object"==typeof t?(this.dataView=t,e&&(this._byteOffset+=e)):this.buffer=new ArrayBuffer(t||0),this.position=0,this.endianness=null==i?n.LITTLE_ENDIAN:i};n.prototype={},n.prototype.getPosition=function(){return this.position},n.prototype._realloc=function(t){if(this._dynamicSize){var e=this._byteOffset+this.position+t,i=this._buffer.byteLength;if(e<=i)e>this._byteLength&&(this._byteLength=e);else{for(i<1&&(i=1);e>i;)i*=2;var r=new ArrayBuffer(i),s=new Uint8Array(this._buffer);new Uint8Array(r,0,s.length).set(s),this.buffer=r,this._byteLength=e}}},n.prototype._trimAlloc=function(){if(this._byteLength!=this._buffer.byteLength){var t=new ArrayBuffer(this._byteLength),e=new Uint8Array(t),i=new Uint8Array(this._buffer,0,e.length);e.set(i),this.buffer=t}},n.BIG_ENDIAN=!1,n.LITTLE_ENDIAN=!0,n.prototype._byteLength=0,Object.defineProperty(n.prototype,"byteLength",{get:function(){return this._byteLength-this._byteOffset}}),Object.defineProperty(n.prototype,"buffer",{get:function(){return this._trimAlloc(),this._buffer},set:function(t){this._buffer=t,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._buffer.byteLength}}),Object.defineProperty(n.prototype,"byteOffset",{get:function(){return this._byteOffset},set:function(t){this._byteOffset=t,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._buffer.byteLength}}),Object.defineProperty(n.prototype,"dataView",{get:function(){return this._dataView},set:function(t){this._byteOffset=t.byteOffset,this._buffer=t.buffer,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._byteOffset+t.byteLength}}),n.prototype.seek=function(t){var e=Math.max(0,Math.min(this.byteLength,t));this.position=isNaN(e)||!isFinite(e)?0:e},n.prototype.isEof=function(){return this.position>=this._byteLength},n.prototype.mapUint8Array=function(t){this._realloc(1*t);var e=new Uint8Array(this._buffer,this.byteOffset+this.position,t);return this.position+=1*t,e},n.prototype.readInt32Array=function(t,e){t=null==t?this.byteLength-this.position/4:t;var i=new Int32Array(t);return n.memcpy(i.buffer,0,this.buffer,this.byteOffset+this.position,t*i.BYTES_PER_ELEMENT),n.arrayToNative(i,null==e?this.endianness:e),this.position+=i.byteLength,i},n.prototype.readInt16Array=function(t,e){t=null==t?this.byteLength-this.position/2:t;var i=new Int16Array(t);return n.memcpy(i.buffer,0,this.buffer,this.byteOffset+this.position,t*i.BYTES_PER_ELEMENT),n.arrayToNative(i,null==e?this.endianness:e),this.position+=i.byteLength,i},n.prototype.readInt8Array=function(t){t=null==t?this.byteLength-this.position:t;var e=new Int8Array(t);return n.memcpy(e.buffer,0,this.buffer,this.byteOffset+this.position,t*e.BYTES_PER_ELEMENT),this.position+=e.byteLength,e},n.prototype.readUint32Array=function(t,e){t=null==t?this.byteLength-this.position/4:t;var i=new Uint32Array(t);return n.memcpy(i.buffer,0,this.buffer,this.byteOffset+this.position,t*i.BYTES_PER_ELEMENT),n.arrayToNative(i,null==e?this.endianness:e),this.position+=i.byteLength,i},n.prototype.readUint16Array=function(t,e){t=null==t?this.byteLength-this.position/2:t;var i=new Uint16Array(t);return n.memcpy(i.buffer,0,this.buffer,this.byteOffset+this.position,t*i.BYTES_PER_ELEMENT),n.arrayToNative(i,null==e?this.endianness:e),this.position+=i.byteLength,i},n.prototype.readUint8Array=function(t){t=null==t?this.byteLength-this.position:t;var e=new Uint8Array(t);return n.memcpy(e.buffer,0,this.buffer,this.byteOffset+this.position,t*e.BYTES_PER_ELEMENT),this.position+=e.byteLength,e},n.prototype.readFloat64Array=function(t,e){t=null==t?this.byteLength-this.position/8:t;var i=new Float64Array(t);return n.memcpy(i.buffer,0,this.buffer,this.byteOffset+this.position,t*i.BYTES_PER_ELEMENT),n.arrayToNative(i,null==e?this.endianness:e),this.position+=i.byteLength,i},n.prototype.readFloat32Array=function(t,e){t=null==t?this.byteLength-this.position/4:t;var i=new Float32Array(t);return n.memcpy(i.buffer,0,this.buffer,this.byteOffset+this.position,t*i.BYTES_PER_ELEMENT),n.arrayToNative(i,null==e?this.endianness:e),this.position+=i.byteLength,i},n.prototype.readInt32=function(t){var e=this._dataView.getInt32(this.position,null==t?this.endianness:t);return this.position+=4,e},n.prototype.readInt16=function(t){var e=this._dataView.getInt16(this.position,null==t?this.endianness:t);return this.position+=2,e},n.prototype.readInt8=function(){var t=this._dataView.getInt8(this.position);return this.position+=1,t},n.prototype.readUint32=function(t){var e=this._dataView.getUint32(this.position,null==t?this.endianness:t);return this.position+=4,e},n.prototype.readUint16=function(t){var e=this._dataView.getUint16(this.position,null==t?this.endianness:t);return this.position+=2,e},n.prototype.readUint8=function(){var t=this._dataView.getUint8(this.position);return this.position+=1,t},n.prototype.readFloat32=function(t){var e=this._dataView.getFloat32(this.position,null==t?this.endianness:t);return this.position+=4,e},n.prototype.readFloat64=function(t){var e=this._dataView.getFloat64(this.position,null==t?this.endianness:t);return this.position+=8,e},n.endianness=new Int8Array(new Int16Array([1]).buffer)[0]>0,n.memcpy=function(t,e,i,r,s){var a=new Uint8Array(t,e,s),n=new Uint8Array(i,r,s);a.set(n)},n.arrayToNative=function(t,e){return e==this.endianness?t:this.flipArrayEndianness(t)},n.nativeToEndian=function(t,e){return this.endianness==e?t:this.flipArrayEndianness(t)},n.flipArrayEndianness=function(t){for(var e=new Uint8Array(t.buffer,t.byteOffset,t.byteLength),i=0;i<t.byteLength;i+=t.BYTES_PER_ELEMENT)for(var r=i+t.BYTES_PER_ELEMENT-1,s=i;r>s;r--,s++){var a=e[s];e[s]=e[r],e[r]=a}return t},n.prototype.failurePosition=0,String.fromCharCodeUint8=function(t){for(var e=[],i=0;i<t.length;i++)e[i]=t[i];return String.fromCharCode.apply(null,e)},n.prototype.readString=function(t,e){return null==e||"ASCII"==e?String.fromCharCodeUint8.apply(null,[this.mapUint8Array(null==t?this.byteLength-this.position:t)]):new TextDecoder(e).decode(this.mapUint8Array(t))},n.prototype.readCString=function(t){var e=this.byteLength-this.position,i=new Uint8Array(this._buffer,this._byteOffset+this.position),r=e;null!=t&&(r=Math.min(t,e));for(var s=0;s<r&&0!==i[s];s++);var a=String.fromCharCodeUint8.apply(null,[this.mapUint8Array(s)]);return null!=t?this.position+=r-s:s!=e&&(this.position+=1),a};var o=Math.pow(2,32);n.prototype.readInt64=function(){return this.readInt32()*o+this.readUint32()},n.prototype.readUint64=function(){return this.readUint32()*o+this.readUint32()},n.prototype.readInt64=function(){return this.readUint32()*o+this.readUint32()},n.prototype.readUint24=function(){return(this.readUint8()<<16)+(this.readUint8()<<8)+this.readUint8()},e.DataStream=n,n.prototype.save=function(t){var e=new Blob([this.buffer]);if(!window.URL||!URL.createObjectURL)throw"DataStream.save: Can't create object URL.";var i=window.URL.createObjectURL(e),r=document.createElement("a");document.body.appendChild(r),r.setAttribute("href",i),r.setAttribute("download",t),r.setAttribute("target","_self"),r.click(),window.URL.revokeObjectURL(i)},n.prototype._dynamicSize=!0,Object.defineProperty(n.prototype,"dynamicSize",{get:function(){return this._dynamicSize},set:function(t){t||this._trimAlloc(),this._dynamicSize=t}}),n.prototype.shift=function(t){var e=new ArrayBuffer(this._byteLength-t),i=new Uint8Array(e),r=new Uint8Array(this._buffer,t,i.length);i.set(r),this.buffer=e,this.position-=t},n.prototype.writeInt32Array=function(t,e){if(this._realloc(4*t.length),t instanceof Int32Array&&this.byteOffset+this.position%t.BYTES_PER_ELEMENT===0)n.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,0,t.byteLength),this.mapInt32Array(t.length,e);else for(var i=0;i<t.length;i++)this.writeInt32(t[i],e)},n.prototype.writeInt16Array=function(t,e){if(this._realloc(2*t.length),t instanceof Int16Array&&this.byteOffset+this.position%t.BYTES_PER_ELEMENT===0)n.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,0,t.byteLength),this.mapInt16Array(t.length,e);else for(var i=0;i<t.length;i++)this.writeInt16(t[i],e)},n.prototype.writeInt8Array=function(t){if(this._realloc(1*t.length),t instanceof Int8Array&&this.byteOffset+this.position%t.BYTES_PER_ELEMENT===0)n.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,0,t.byteLength),this.mapInt8Array(t.length);else for(var e=0;e<t.length;e++)this.writeInt8(t[e])},n.prototype.writeUint32Array=function(t,e){if(this._realloc(4*t.length),t instanceof Uint32Array&&this.byteOffset+this.position%t.BYTES_PER_ELEMENT===0)n.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,0,t.byteLength),this.mapUint32Array(t.length,e);else for(var i=0;i<t.length;i++)this.writeUint32(t[i],e)},n.prototype.writeUint16Array=function(t,e){if(this._realloc(2*t.length),t instanceof Uint16Array&&this.byteOffset+this.position%t.BYTES_PER_ELEMENT===0)n.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,0,t.byteLength),this.mapUint16Array(t.length,e);else for(var i=0;i<t.length;i++)this.writeUint16(t[i],e)},n.prototype.writeUint8Array=function(t){if(this._realloc(1*t.length),t instanceof Uint8Array&&this.byteOffset+this.position%t.BYTES_PER_ELEMENT===0)n.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,0,t.byteLength),this.mapUint8Array(t.length);else for(var e=0;e<t.length;e++)this.writeUint8(t[e])},n.prototype.writeFloat64Array=function(t,e){if(this._realloc(8*t.length),t instanceof Float64Array&&this.byteOffset+this.position%t.BYTES_PER_ELEMENT===0)n.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,0,t.byteLength),this.mapFloat64Array(t.length,e);else for(var i=0;i<t.length;i++)this.writeFloat64(t[i],e)},n.prototype.writeFloat32Array=function(t,e){if(this._realloc(4*t.length),t instanceof Float32Array&&this.byteOffset+this.position%t.BYTES_PER_ELEMENT===0)n.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,0,t.byteLength),this.mapFloat32Array(t.length,e);else for(var i=0;i<t.length;i++)this.writeFloat32(t[i],e)},n.prototype.writeInt32=function(t,e){this._realloc(4),this._dataView.setInt32(this.position,t,null==e?this.endianness:e),this.position+=4},n.prototype.writeInt16=function(t,e){this._realloc(2),this._dataView.setInt16(this.position,t,null==e?this.endianness:e),this.position+=2},n.prototype.writeInt8=function(t){this._realloc(1),this._dataView.setInt8(this.position,t),this.position+=1},n.prototype.writeUint32=function(t,e){this._realloc(4),this._dataView.setUint32(this.position,t,null==e?this.endianness:e),this.position+=4},n.prototype.writeUint16=function(t,e){this._realloc(2),this._dataView.setUint16(this.position,t,null==e?this.endianness:e),this.position+=2},n.prototype.writeUint8=function(t){this._realloc(1),this._dataView.setUint8(this.position,t),this.position+=1},n.prototype.writeFloat32=function(t,e){this._realloc(4),this._dataView.setFloat32(this.position,t,null==e?this.endianness:e),this.position+=4},n.prototype.writeFloat64=function(t,e){this._realloc(8),this._dataView.setFloat64(this.position,t,null==e?this.endianness:e),this.position+=8},n.prototype.writeUCS2String=function(t,e,i){null==i&&(i=t.length);for(var r=0;r<t.length&&r<i;r++)this.writeUint16(t.charCodeAt(r),e);for(;r<i;r++)this.writeUint16(0)},n.prototype.writeString=function(t,e,i){var r=0;if(null==e||"ASCII"==e)if(null!=i){var s=Math.min(t.length,i);for(r=0;r<s;r++)this.writeUint8(t.charCodeAt(r));for(;r<i;r++)this.writeUint8(0)}else for(r=0;r<t.length;r++)this.writeUint8(t.charCodeAt(r));else this.writeUint8Array(new TextEncoder(e).encode(t.substring(0,i)))},n.prototype.writeCString=function(t,e){var i=0;if(null!=e){var r=Math.min(t.length,e);for(i=0;i<r;i++)this.writeUint8(t.charCodeAt(i));for(;i<e;i++)this.writeUint8(0)}else{for(i=0;i<t.length;i++)this.writeUint8(t.charCodeAt(i));this.writeUint8(0)}},n.prototype.writeStruct=function(t,e){for(var i=0;i<t.length;i+=2){var r=t[i+1];this.writeType(r,e[t[i]],e)}},n.prototype.writeType=function(t,e,i){var r;if("function"==typeof t)return t(this,e);if("object"==typeof t&&!(t instanceof Array))return t.set(this,e,i);var s=null,a="ASCII",o=this.position;switch("string"==typeof t&&/:/.test(t)&&(r=t.split(":"),t=r[0],s=parseInt(r[1])),"string"==typeof t&&/,/.test(t)&&(r=t.split(","),t=r[0],a=parseInt(r[1])),t){case"uint8":this.writeUint8(e);break;case"int8":this.writeInt8(e);break;case"uint16":this.writeUint16(e,this.endianness);break;case"int16":this.writeInt16(e,this.endianness);break;case"uint32":this.writeUint32(e,this.endianness);break;case"int32":this.writeInt32(e,this.endianness);break;case"float32":this.writeFloat32(e,this.endianness);break;case"float64":this.writeFloat64(e,this.endianness);break;case"uint16be":this.writeUint16(e,n.BIG_ENDIAN);break;case"int16be":this.writeInt16(e,n.BIG_ENDIAN);break;case"uint32be":this.writeUint32(e,n.BIG_ENDIAN);break;case"int32be":this.writeInt32(e,n.BIG_ENDIAN);break;case"float32be":this.writeFloat32(e,n.BIG_ENDIAN);break;case"float64be":this.writeFloat64(e,n.BIG_ENDIAN);break;case"uint16le":this.writeUint16(e,n.LITTLE_ENDIAN);break;case"int16le":this.writeInt16(e,n.LITTLE_ENDIAN);break;case"uint32le":this.writeUint32(e,n.LITTLE_ENDIAN);break;case"int32le":this.writeInt32(e,n.LITTLE_ENDIAN);break;case"float32le":this.writeFloat32(e,n.LITTLE_ENDIAN);break;case"float64le":this.writeFloat64(e,n.LITTLE_ENDIAN);break;case"cstring":this.writeCString(e,s);break;case"string":this.writeString(e,a,s);break;case"u16string":this.writeUCS2String(e,this.endianness,s);break;case"u16stringle":this.writeUCS2String(e,n.LITTLE_ENDIAN,s);break;case"u16stringbe":this.writeUCS2String(e,n.BIG_ENDIAN,s);break;default:if(3==t.length){for(var h=t[1],c=0;c<e.length;c++)this.writeType(h,e[c]);break}this.writeStruct(t,e)}null!=s&&(this.position=o,this._realloc(s),this.position=o+s)},n.prototype.writeUint64=function(t){var e=Math.floor(t/o);this.writeUint32(e),this.writeUint32(4294967295&t)},n.prototype.writeUint24=function(t){this.writeUint8((16711680&t)>>16),this.writeUint8((65280&t)>>8),this.writeUint8(255&t)},n.prototype.adjustUint32=function(t,e){var i=this.position;this.seek(t),this.writeUint32(e),this.seek(i)},n.prototype.mapInt32Array=function(t,e){this._realloc(4*t);var i=new Int32Array(this._buffer,this.byteOffset+this.position,t);return n.arrayToNative(i,null==e?this.endianness:e),this.position+=4*t,i},n.prototype.mapInt16Array=function(t,e){this._realloc(2*t);var i=new Int16Array(this._buffer,this.byteOffset+this.position,t);return n.arrayToNative(i,null==e?this.endianness:e),this.position+=2*t,i},n.prototype.mapInt8Array=function(t){this._realloc(1*t);var e=new Int8Array(this._buffer,this.byteOffset+this.position,t);return this.position+=1*t,e},n.prototype.mapUint32Array=function(t,e){this._realloc(4*t);var i=new Uint32Array(this._buffer,this.byteOffset+this.position,t);return n.arrayToNative(i,null==e?this.endianness:e),this.position+=4*t,i},n.prototype.mapUint16Array=function(t,e){this._realloc(2*t);var i=new Uint16Array(this._buffer,this.byteOffset+this.position,t);return n.arrayToNative(i,null==e?this.endianness:e),this.position+=2*t,i},n.prototype.mapFloat64Array=function(t,e){this._realloc(8*t);var i=new Float64Array(this._buffer,this.byteOffset+this.position,t);return n.arrayToNative(i,null==e?this.endianness:e),this.position+=8*t,i},n.prototype.mapFloat32Array=function(t,e){this._realloc(4*t);var i=new Float32Array(this._buffer,this.byteOffset+this.position,t);return n.arrayToNative(i,null==e?this.endianness:e),this.position+=4*t,i};var h=function(t){this.buffers=[],this.bufferIndex=-1,t&&(this.insertBuffer(t),this.bufferIndex=0)};(h.prototype=new n(new ArrayBuffer,0,n.BIG_ENDIAN)).initialized=function(){var t;return this.bufferIndex>-1||(this.buffers.length>0?0===(t=this.buffers[0]).fileStart?(this.buffer=t,this.bufferIndex=0,s.debug("MultiBufferStream","Stream ready for parsing"),!0):(s.warn("MultiBufferStream","The first buffer should have a fileStart of 0"),this.logBufferLevel(),!1):(s.warn("MultiBufferStream","No buffer to start parsing from"),this.logBufferLevel(),!1))},ArrayBuffer.concat=function(t,e){s.debug("ArrayBuffer","Trying to create a new buffer of size: "+(t.byteLength+e.byteLength));var i=new Uint8Array(t.byteLength+e.byteLength);return i.set(new Uint8Array(t),0),i.set(new Uint8Array(e),t.byteLength),i.buffer},h.prototype.reduceBuffer=function(t,e,i){var r;return(r=new Uint8Array(i)).set(new Uint8Array(t,e,i)),r.buffer.fileStart=t.fileStart+e,r.buffer.usedBytes=0,r.buffer},h.prototype.insertBuffer=function(t){for(var e=!0,i=0;i<this.buffers.length;i++){var r=this.buffers[i];if(t.fileStart<=r.fileStart){if(t.fileStart===r.fileStart){if(t.byteLength>r.byteLength){this.buffers.splice(i,1),i--;continue}s.warn("MultiBufferStream","Buffer (fileStart: "+t.fileStart+" - Length: "+t.byteLength+") already appended, ignoring")}else t.fileStart+t.byteLength<=r.fileStart||(t=this.reduceBuffer(t,0,r.fileStart-t.fileStart)),s.debug("MultiBufferStream","Appending new buffer (fileStart: "+t.fileStart+" - Length: "+t.byteLength+")"),this.buffers.splice(i,0,t),0===i&&(this.buffer=t);e=!1;break}if(t.fileStart<r.fileStart+r.byteLength){var a=r.fileStart+r.byteLength-t.fileStart,n=t.byteLength-a;if(!(n>0)){e=!1;break}t=this.reduceBuffer(t,a,n)}}e&&(s.debug("MultiBufferStream","Appending new buffer (fileStart: "+t.fileStart+" - Length: "+t.byteLength+")"),this.buffers.push(t),0===i&&(this.buffer=t))},h.prototype.logBufferLevel=function(t){var e,i,r,a,n,o=[],h="";for(r=0,a=0,e=0;e<this.buffers.length;e++)i=this.buffers[e],0===e?(n={},o.push(n),n.start=i.fileStart,n.end=i.fileStart+i.byteLength,h+="["+n.start+"-"):n.end===i.fileStart?n.end=i.fileStart+i.byteLength:((n={}).start=i.fileStart,h+=o[o.length-1].end-1+"], ["+n.start+"-",n.end=i.fileStart+i.byteLength,o.push(n)),r+=i.usedBytes,a+=i.byteLength;o.length>0&&(h+=n.end-1+"]");var c=t?s.info:s.debug;0===this.buffers.length?c("MultiBufferStream","No more buffer in memory"):c("MultiBufferStream",this.buffers.length+" stored buffer(s) ("+r+"/"+a+" bytes), continuous ranges: "+h)},h.prototype.cleanBuffers=function(){var t,e;for(t=0;t<this.buffers.length;t++)(e=this.buffers[t]).usedBytes===e.byteLength&&(s.debug("MultiBufferStream","Removing buffer #"+t),this.buffers.splice(t,1),t--)},h.prototype.mergeNextBuffer=function(){var t;if(this.bufferIndex+1<this.buffers.length){if((t=this.buffers[this.bufferIndex+1]).fileStart===this.buffer.fileStart+this.buffer.byteLength){var e=this.buffer.byteLength,i=this.buffer.usedBytes,r=this.buffer.fileStart;return this.buffers[this.bufferIndex]=ArrayBuffer.concat(this.buffer,t),this.buffer=this.buffers[this.bufferIndex],this.buffers.splice(this.bufferIndex+1,1),this.buffer.usedBytes=i,this.buffer.fileStart=r,s.debug("ISOFile","Concatenating buffer for box parsing (length: "+e+"->"+this.buffer.byteLength+")"),!0}return!1}return!1},h.prototype.findPosition=function(t,e,i){var r,a=null,n=-1;for(r=!0===t?0:this.bufferIndex;r<this.buffers.length&&(a=this.buffers[r]).fileStart<=e;)n=r,i&&(a.fileStart+a.byteLength<=e?a.usedBytes=a.byteLength:a.usedBytes=e-a.fileStart,this.logBufferLevel()),r++;return-1!==n&&(a=this.buffers[n]).fileStart+a.byteLength>=e?(s.debug("MultiBufferStream","Found position in existing buffer #"+n),n):-1},h.prototype.findEndContiguousBuf=function(t){var e,i,r,s=void 0!==t?t:this.bufferIndex;if(i=this.buffers[s],this.buffers.length>s+1)for(e=s+1;e<this.buffers.length&&(r=this.buffers[e]).fileStart===i.fileStart+i.byteLength;e++)i=r;return i.fileStart+i.byteLength},h.prototype.getEndFilePositionAfter=function(t){var e=this.findPosition(!0,t,!1);return-1!==e?this.findEndContiguousBuf(e):t},h.prototype.addUsedBytes=function(t){this.buffer.usedBytes+=t,this.logBufferLevel()},h.prototype.setAllUsedBytes=function(){this.buffer.usedBytes=this.buffer.byteLength,this.logBufferLevel()},h.prototype.seek=function(t,e,i){var r;return-1!==(r=this.findPosition(e,t,i))?(this.buffer=this.buffers[r],this.bufferIndex=r,this.position=t-this.buffer.fileStart,s.debug("MultiBufferStream","Repositioning parser at buffer position: "+this.position),!0):(s.debug("MultiBufferStream","Position "+t+" not found in buffered data"),!1)},h.prototype.getPosition=function(){if(-1===this.bufferIndex||null===this.buffers[this.bufferIndex])throw"Error accessing position in the MultiBufferStream";return this.buffers[this.bufferIndex].fileStart+this.position},h.prototype.getLength=function(){return this.byteLength},h.prototype.getEndPosition=function(){if(-1===this.bufferIndex||null===this.buffers[this.bufferIndex])throw"Error accessing position in the MultiBufferStream";return this.buffers[this.bufferIndex].fileStart+this.byteLength},e.MultiBufferStream=h;var c=function(){var t=[];t[3]="ES_Descriptor",t[4]="DecoderConfigDescriptor",t[5]="DecoderSpecificInfo",t[6]="SLConfigDescriptor",this.getDescriptorName=function(e){return t[e]};var e=this,i={};return this.parseOneDescriptor=function(e){var r,a,n,o=0;for(r=e.readUint8(),n=e.readUint8();128&n;)o=(127&n)<<7,n=e.readUint8();return o+=127&n,s.debug("MPEG4DescriptorParser","Found "+(t[r]||"Descriptor "+r)+", size "+o+" at position "+e.getPosition()),(a=t[r]?new i[t[r]](o):new i.Descriptor(o)).parse(e),a},i.Descriptor=function(t,e){this.tag=t,this.size=e,this.descs=[]},i.Descriptor.prototype.parse=function(t){this.data=t.readUint8Array(this.size)},i.Descriptor.prototype.findDescriptor=function(t){for(var e=0;e<this.descs.length;e++)if(this.descs[e].tag==t)return this.descs[e];return null},i.Descriptor.prototype.parseRemainingDescriptors=function(t){for(var i=t.position;t.position<i+this.size;){var r=e.parseOneDescriptor(t);this.descs.push(r)}},i.ES_Descriptor=function(t){i.Descriptor.call(this,3,t)},i.ES_Descriptor.prototype=new i.Descriptor,i.ES_Descriptor.prototype.parse=function(t){if(this.ES_ID=t.readUint16(),this.flags=t.readUint8(),this.size-=3,128&this.flags?(this.dependsOn_ES_ID=t.readUint16(),this.size-=2):this.dependsOn_ES_ID=0,64&this.flags){var e=t.readUint8();this.URL=t.readString(e),this.size-=e+1}else this.URL="";32&this.flags?(this.OCR_ES_ID=t.readUint16(),this.size-=2):this.OCR_ES_ID=0,this.parseRemainingDescriptors(t)},i.ES_Descriptor.prototype.getOTI=function(t){var e=this.findDescriptor(4);return e?e.oti:0},i.ES_Descriptor.prototype.getAudioConfig=function(t){var e=this.findDescriptor(4);if(!e)return null;var i=e.findDescriptor(5);if(i&&i.data){var r=(248&i.data[0])>>3;return 31===r&&i.data.length>=2&&(r=32+((7&i.data[0])<<3)+((224&i.data[1])>>5)),r}return null},i.DecoderConfigDescriptor=function(t){i.Descriptor.call(this,4,t)},i.DecoderConfigDescriptor.prototype=new i.Descriptor,i.DecoderConfigDescriptor.prototype.parse=function(t){this.oti=t.readUint8(),this.streamType=t.readUint8(),this.bufferSize=t.readUint24(),this.maxBitrate=t.readUint32(),this.avgBitrate=t.readUint32(),this.size-=13,this.parseRemainingDescriptors(t)},i.DecoderSpecificInfo=function(t){i.Descriptor.call(this,5,t)},i.DecoderSpecificInfo.prototype=new i.Descriptor,i.SLConfigDescriptor=function(t){i.Descriptor.call(this,6,t)},i.SLConfigDescriptor.prototype=new i.Descriptor,this};e.MPEG4DescriptorParser=c;var d={ERR_INVALID_DATA:-1,ERR_NOT_ENOUGH_DATA:0,OK:1,BASIC_BOXES:["mdat","idat","free","skip","meco","strk"],FULL_BOXES:["hmhd","nmhd","iods","xml ","bxml","ipro","mere"],CONTAINER_BOXES:[["moov",["trak","pssh"]],["trak"],["edts"],["mdia"],["minf"],["dinf"],["stbl",["sgpd","sbgp"]],["mvex",["trex"]],["moof",["traf"]],["traf",["trun","sgpd","sbgp"]],["vttc"],["tref"],["iref"],["mfra",["tfra"]],["meco"],["hnti"],["hinf"],["strk"],["strd"],["sinf"],["rinf"],["schi"],["trgr"],["udta",["kind"]],["iprp",["ipma"]],["ipco"]],boxCodes:[],fullBoxCodes:[],containerBoxCodes:[],sampleEntryCodes:{},sampleGroupEntryCodes:[],trackGroupTypes:[],UUIDBoxes:{},UUIDs:[],initialize:function(){d.FullBox.prototype=new d.Box,d.ContainerBox.prototype=new d.Box,d.SampleEntry.prototype=new d.Box,d.TrackGroupTypeBox.prototype=new d.FullBox,d.BASIC_BOXES.forEach(function(t){d.createBoxCtor(t)}),d.FULL_BOXES.forEach(function(t){d.createFullBoxCtor(t)}),d.CONTAINER_BOXES.forEach(function(t){d.createContainerBoxCtor(t[0],null,t[1])})},Box:function(t,e,i){this.type=t,this.size=e,this.uuid=i},FullBox:function(t,e,i){d.Box.call(this,t,e,i),this.flags=0,this.version=0},ContainerBox:function(t,e,i){d.Box.call(this,t,e,i),this.boxes=[]},SampleEntry:function(t,e,i,r){d.ContainerBox.call(this,t,e),this.hdr_size=i,this.start=r},SampleGroupEntry:function(t){this.grouping_type=t},TrackGroupTypeBox:function(t,e){d.FullBox.call(this,t,e)},createBoxCtor:function(t,e){d.boxCodes.push(t),d[t+"Box"]=function(e){d.Box.call(this,t,e)},d[t+"Box"].prototype=new d.Box,e&&(d[t+"Box"].prototype.parse=e)},createFullBoxCtor:function(t,e){d[t+"Box"]=function(e){d.FullBox.call(this,t,e)},d[t+"Box"].prototype=new d.FullBox,d[t+"Box"].prototype.parse=function(t){this.parseFullHeader(t),e&&e.call(this,t)}},addSubBoxArrays:function(t){if(t){this.subBoxNames=t;for(var e=t.length,i=0;i<e;i++)this[t[i]+"s"]=[]}},createContainerBoxCtor:function(t,e,i){d[t+"Box"]=function(e){d.ContainerBox.call(this,t,e),d.addSubBoxArrays.call(this,i)},d[t+"Box"].prototype=new d.ContainerBox,e&&(d[t+"Box"].prototype.parse=e)},createMediaSampleEntryCtor:function(t,e,i){d.sampleEntryCodes[t]=[],d[t+"SampleEntry"]=function(t,e){d.SampleEntry.call(this,t,e),d.addSubBoxArrays.call(this,i)},d[t+"SampleEntry"].prototype=new d.SampleEntry,e&&(d[t+"SampleEntry"].prototype.parse=e)},createSampleEntryCtor:function(t,e,i,r){d.sampleEntryCodes[t].push(e),d[e+"SampleEntry"]=function(i){d[t+"SampleEntry"].call(this,e,i),d.addSubBoxArrays.call(this,r)},d[e+"SampleEntry"].prototype=new d[t+"SampleEntry"],i&&(d[e+"SampleEntry"].prototype.parse=i)},createEncryptedSampleEntryCtor:function(t,e,i){d.createSampleEntryCtor.call(this,t,e,i,["sinf"])},createSampleGroupCtor:function(t,e){d[t+"SampleGroupEntry"]=function(e){d.SampleGroupEntry.call(this,t,e)},d[t+"SampleGroupEntry"].prototype=new d.SampleGroupEntry,e&&(d[t+"SampleGroupEntry"].prototype.parse=e)},createTrackGroupCtor:function(t,e){d[t+"TrackGroupTypeBox"]=function(e){d.TrackGroupTypeBox.call(this,t,e)},d[t+"TrackGroupTypeBox"].prototype=new d.TrackGroupTypeBox,e&&(d[t+"TrackGroupTypeBox"].prototype.parse=e)},createUUIDBox:function(t,e,i,r){d.UUIDs.push(t),d.UUIDBoxes[t]=function(r){e?d.FullBox.call(this,"uuid",r,t):i?d.ContainerBox.call(this,"uuid",r,t):d.Box.call(this,"uuid",r,t)},d.UUIDBoxes[t].prototype=e?new d.FullBox:i?new d.ContainerBox:new d.Box,r&&(d.UUIDBoxes[t].prototype.parse=e?function(t){this.parseFullHeader(t),r&&r.call(this,t)}:r)}};d.initialize(),d.TKHD_FLAG_ENABLED=1,d.TKHD_FLAG_IN_MOVIE=2,d.TKHD_FLAG_IN_PREVIEW=4,d.TFHD_FLAG_BASE_DATA_OFFSET=1,d.TFHD_FLAG_SAMPLE_DESC=2,d.TFHD_FLAG_SAMPLE_DUR=8,d.TFHD_FLAG_SAMPLE_SIZE=16,d.TFHD_FLAG_SAMPLE_FLAGS=32,d.TFHD_FLAG_DUR_EMPTY=65536,d.TFHD_FLAG_DEFAULT_BASE_IS_MOOF=131072,d.TRUN_FLAGS_DATA_OFFSET=1,d.TRUN_FLAGS_FIRST_FLAG=4,d.TRUN_FLAGS_DURATION=256,d.TRUN_FLAGS_SIZE=512,d.TRUN_FLAGS_FLAGS=1024,d.TRUN_FLAGS_CTS_OFFSET=2048,d.Box.prototype.add=function(t){return this.addBox(new d[t+"Box"])},d.Box.prototype.addBox=function(t){return this.boxes.push(t),this[t.type+"s"]?this[t.type+"s"].push(t):this[t.type]=t,t},d.Box.prototype.set=function(t,e){return this[t]=e,this},d.Box.prototype.addEntry=function(t,e){var i=e||"entries";return this[i]||(this[i]=[]),this[i].push(t),this},e.BoxParser=d,d.parseUUID=function(t){return d.parseHex16(t)},d.parseHex16=function(t){for(var e="",i=0;i<16;i++){var r=t.readUint8().toString(16);e+=1===r.length?"0"+r:r}return e},d.parseOneBox=function(t,e,i){var r,a,n,o=t.getPosition(),h=0;if(t.getEndPosition()-o<8)return s.debug("BoxParser","Not enough data in stream to parse the type and size of the box"),{code:d.ERR_NOT_ENOUGH_DATA};if(i&&i<8)return s.debug("BoxParser","Not enough bytes left in the parent box to parse a new box"),{code:d.ERR_NOT_ENOUGH_DATA};var c=t.readUint32(),l=t.readString(4),u=l;if(s.debug("BoxParser","Found box of type '"+l+"' and size "+c+" at position "+o),h=8,"uuid"==l){if(t.getEndPosition()-t.getPosition()<16||i-h<16)return t.seek(o),s.debug("BoxParser","Not enough bytes left in the parent box to parse a UUID box"),{code:d.ERR_NOT_ENOUGH_DATA};h+=16,u=n=d.parseUUID(t)}if(1==c){if(t.getEndPosition()-t.getPosition()<8||i&&i-h<8)return t.seek(o),s.warn("BoxParser",'Not enough data in stream to parse the extended size of the "'+l+'" box'),{code:d.ERR_NOT_ENOUGH_DATA};c=t.readUint64(),h+=8}else if(0===c)if(i)c=i;else if("mdat"!==l)return s.error("BoxParser","Unlimited box size not supported for type: '"+l+"'"),r=new d.Box(l,c),{code:d.OK,box:r,size:r.size};return 0!==c&&c<h?(s.error("BoxParser","Box of type "+l+" has an invalid size "+c+" (too small to be a box)"),{code:d.ERR_NOT_ENOUGH_DATA,type:l,size:c,hdr_size:h,start:o}):0!==c&&i&&c>i?(s.error("BoxParser","Box of type '"+l+"' has a size "+c+" greater than its container size "+i),{code:d.ERR_NOT_ENOUGH_DATA,type:l,size:c,hdr_size:h,start:o}):0!==c&&o+c>t.getEndPosition()?(t.seek(o),s.info("BoxParser","Not enough data in stream to parse the entire '"+l+"' box"),{code:d.ERR_NOT_ENOUGH_DATA,type:l,size:c,hdr_size:h,start:o}):e?{code:d.OK,type:l,size:c,hdr_size:h,start:o}:(d[l+"Box"]?r=new d[l+"Box"](c):"uuid"!==l?(s.warn("BoxParser","Unknown box type: '"+l+"'"),(r=new d.Box(l,c)).has_unparsed_data=!0):d.UUIDBoxes[n]?r=new d.UUIDBoxes[n](c):(s.warn("BoxParser","Unknown uuid type: '"+n+"'"),(r=new d.Box(l,c)).uuid=n,r.has_unparsed_data=!0),r.hdr_size=h,r.start=o,r.write===d.Box.prototype.write&&"mdat"!==r.type&&(s.info("BoxParser","'"+u+"' box writing not yet implemented, keeping unparsed data in memory for later write"),r.parseDataAndRewind(t)),r.parse(t),(a=t.getPosition()-(r.start+r.size))<0?(s.warn("BoxParser","Parsing of box '"+u+"' did not read the entire indicated box data size (missing "+-a+" bytes), seeking forward"),t.seek(r.start+r.size)):a>0&&(s.error("BoxParser","Parsing of box '"+u+"' read "+a+" more bytes than the indicated box data size, seeking backwards"),0!==r.size&&t.seek(r.start+r.size)),{code:d.OK,box:r,size:r.size})},d.Box.prototype.parse=function(t){"mdat"!=this.type?this.data=t.readUint8Array(this.size-this.hdr_size):0===this.size?t.seek(t.getEndPosition()):t.seek(this.start+this.size)},d.Box.prototype.parseDataAndRewind=function(t){this.data=t.readUint8Array(this.size-this.hdr_size),t.position-=this.size-this.hdr_size},d.FullBox.prototype.parseDataAndRewind=function(t){this.parseFullHeader(t),this.data=t.readUint8Array(this.size-this.hdr_size),this.hdr_size-=4,t.position-=this.size-this.hdr_size},d.FullBox.prototype.parseFullHeader=function(t){this.version=t.readUint8(),this.flags=t.readUint24(),this.hdr_size+=4},d.FullBox.prototype.parse=function(t){this.parseFullHeader(t),this.data=t.readUint8Array(this.size-this.hdr_size)},d.ContainerBox.prototype.parse=function(t){for(var e,i;t.getPosition()<this.start+this.size;){if((e=d.parseOneBox(t,!1,this.size-(t.getPosition()-this.start))).code!==d.OK)return;if(i=e.box,this.boxes.push(i),this.subBoxNames&&-1!=this.subBoxNames.indexOf(i.type))this[this.subBoxNames[this.subBoxNames.indexOf(i.type)]+"s"].push(i);else{var r="uuid"!==i.type?i.type:i.uuid;this[r]?s.warn("Box of type "+r+" already stored in field of this type"):this[r]=i}}},d.Box.prototype.parseLanguage=function(t){this.language=t.readUint16();var e=[];e[0]=this.language>>10&31,e[1]=this.language>>5&31,e[2]=31&this.language,this.languageString=String.fromCharCode(e[0]+96,e[1]+96,e[2]+96)},d.SAMPLE_ENTRY_TYPE_VISUAL="Visual",d.SAMPLE_ENTRY_TYPE_AUDIO="Audio",d.SAMPLE_ENTRY_TYPE_HINT="Hint",d.SAMPLE_ENTRY_TYPE_METADATA="Metadata",d.SAMPLE_ENTRY_TYPE_SUBTITLE="Subtitle",d.SAMPLE_ENTRY_TYPE_SYSTEM="System",d.SAMPLE_ENTRY_TYPE_TEXT="Text",d.SampleEntry.prototype.parseHeader=function(t){t.readUint8Array(6),this.data_reference_index=t.readUint16(),this.hdr_size+=8},d.SampleEntry.prototype.parse=function(t){this.parseHeader(t),this.data=t.readUint8Array(this.size-this.hdr_size)},d.SampleEntry.prototype.parseDataAndRewind=function(t){this.parseHeader(t),this.data=t.readUint8Array(this.size-this.hdr_size),this.hdr_size-=8,t.position-=this.size-this.hdr_size},d.SampleEntry.prototype.parseFooter=function(t){d.ContainerBox.prototype.parse.call(this,t)},d.createMediaSampleEntryCtor(d.SAMPLE_ENTRY_TYPE_HINT),d.createMediaSampleEntryCtor(d.SAMPLE_ENTRY_TYPE_METADATA),d.createMediaSampleEntryCtor(d.SAMPLE_ENTRY_TYPE_SUBTITLE),d.createMediaSampleEntryCtor(d.SAMPLE_ENTRY_TYPE_SYSTEM),d.createMediaSampleEntryCtor(d.SAMPLE_ENTRY_TYPE_TEXT),d.createMediaSampleEntryCtor(d.SAMPLE_ENTRY_TYPE_VISUAL,function(t){var e;this.parseHeader(t),t.readUint16(),t.readUint16(),t.readUint32Array(3),this.width=t.readUint16(),this.height=t.readUint16(),this.horizresolution=t.readUint32(),this.vertresolution=t.readUint32(),t.readUint32(),this.frame_count=t.readUint16(),e=Math.min(31,t.readUint8()),this.compressorname=t.readString(e),e<31&&t.readString(31-e),this.depth=t.readUint16(),t.readUint16(),this.parseFooter(t)}),d.createMediaSampleEntryCtor(d.SAMPLE_ENTRY_TYPE_AUDIO,function(t){this.parseHeader(t),t.readUint32Array(2),this.channel_count=t.readUint16(),this.samplesize=t.readUint16(),t.readUint16(),t.readUint16(),this.samplerate=t.readUint32()/65536,this.parseFooter(t)}),d.createSampleEntryCtor(d.SAMPLE_ENTRY_TYPE_VISUAL,"avc1"),d.createSampleEntryCtor(d.SAMPLE_ENTRY_TYPE_VISUAL,"avc2"),d.createSampleEntryCtor(d.SAMPLE_ENTRY_TYPE_VISUAL,"avc3"),d.createSampleEntryCtor(d.SAMPLE_ENTRY_TYPE_VISUAL,"avc4"),d.createSampleEntryCtor(d.SAMPLE_ENTRY_TYPE_VISUAL,"av01"),d.createSampleEntryCtor(d.SAMPLE_ENTRY_TYPE_VISUAL,"hvc1"),d.createSampleEntryCtor(d.SAMPLE_ENTRY_TYPE_VISUAL,"hev1"),d.createSampleEntryCtor(d.SAMPLE_ENTRY_TYPE_VISUAL,"vvc1"),d.createSampleEntryCtor(d.SAMPLE_ENTRY_TYPE_VISUAL,"vvi1"),d.createSampleEntryCtor(d.SAMPLE_ENTRY_TYPE_VISUAL,"vvs1"),d.createSampleEntryCtor(d.SAMPLE_ENTRY_TYPE_VISUAL,"vvcN"),d.createSampleEntryCtor(d.SAMPLE_ENTRY_TYPE_VISUAL,"vp08"),d.createSampleEntryCtor(d.SAMPLE_ENTRY_TYPE_VISUAL,"vp09"),d.createSampleEntryCtor(d.SAMPLE_ENTRY_TYPE_AUDIO,"mp4a"),d.createSampleEntryCtor(d.SAMPLE_ENTRY_TYPE_AUDIO,"ac-3"),d.createSampleEntryCtor(d.SAMPLE_ENTRY_TYPE_AUDIO,"ec-3"),d.createSampleEntryCtor(d.SAMPLE_ENTRY_TYPE_AUDIO,"Opus"),d.createEncryptedSampleEntryCtor(d.SAMPLE_ENTRY_TYPE_VISUAL,"encv"),d.createEncryptedSampleEntryCtor(d.SAMPLE_ENTRY_TYPE_AUDIO,"enca"),d.createEncryptedSampleEntryCtor(d.SAMPLE_ENTRY_TYPE_SUBTITLE,"encu"),d.createEncryptedSampleEntryCtor(d.SAMPLE_ENTRY_TYPE_SYSTEM,"encs"),d.createEncryptedSampleEntryCtor(d.SAMPLE_ENTRY_TYPE_TEXT,"enct"),d.createEncryptedSampleEntryCtor(d.SAMPLE_ENTRY_TYPE_METADATA,"encm"),d.createBoxCtor("a1lx",function(t){var e=16*(1+(1&t.readUint8()));this.layer_size=[];for(var i=0;i<3;i++)this.layer_size[i]=16==e?t.readUint16():t.readUint32()}),d.createBoxCtor("a1op",function(t){this.op_index=t.readUint8()}),d.createFullBoxCtor("auxC",function(t){this.aux_type=t.readCString();var e=this.size-this.hdr_size-(this.aux_type.length+1);this.aux_subtype=t.readUint8Array(e)}),d.createBoxCtor("av1C",function(t){var e=t.readUint8();if(e>>7&!1)s.error("av1C marker problem");else if(this.version=127&e,1===this.version)if(e=t.readUint8(),this.seq_profile=e>>5&7,this.seq_level_idx_0=31&e,e=t.readUint8(),this.seq_tier_0=e>>7&1,this.high_bitdepth=e>>6&1,this.twelve_bit=e>>5&1,this.monochrome=e>>4&1,this.chroma_subsampling_x=e>>3&1,this.chroma_subsampling_y=e>>2&1,this.chroma_sample_position=3&e,e=t.readUint8(),this.reserved_1=e>>5&7,0===this.reserved_1){if(this.initial_presentation_delay_present=e>>4&1,1===this.initial_presentation_delay_present)this.initial_presentation_delay_minus_one=15&e;else if(this.reserved_2=15&e,0!==this.reserved_2)return void s.error("av1C reserved_2 parsing problem");var i=this.size-this.hdr_size-4;this.configOBUs=t.readUint8Array(i)}else s.error("av1C reserved_1 parsing problem");else s.error("av1C version "+this.version+" not supported")}),d.createBoxCtor("avcC",function(t){var e,i;for(this.configurationVersion=t.readUint8(),this.AVCProfileIndication=t.readUint8(),this.profile_compatibility=t.readUint8(),this.AVCLevelIndication=t.readUint8(),this.lengthSizeMinusOne=3&t.readUint8(),this.nb_SPS_nalus=31&t.readUint8(),i=this.size-this.hdr_size-6,this.SPS=[],e=0;e<this.nb_SPS_nalus;e++)this.SPS[e]={},this.SPS[e].length=t.readUint16(),this.SPS[e].nalu=t.readUint8Array(this.SPS[e].length),i-=2+this.SPS[e].length;for(this.nb_PPS_nalus=t.readUint8(),i--,this.PPS=[],e=0;e<this.nb_PPS_nalus;e++)this.PPS[e]={},this.PPS[e].length=t.readUint16(),this.PPS[e].nalu=t.readUint8Array(this.PPS[e].length),i-=2+this.PPS[e].length;i>0&&(this.ext=t.readUint8Array(i))}),d.createBoxCtor("btrt",function(t){this.bufferSizeDB=t.readUint32(),this.maxBitrate=t.readUint32(),this.avgBitrate=t.readUint32()}),d.createBoxCtor("clap",function(t){this.cleanApertureWidthN=t.readUint32(),this.cleanApertureWidthD=t.readUint32(),this.cleanApertureHeightN=t.readUint32(),this.cleanApertureHeightD=t.readUint32(),this.horizOffN=t.readUint32(),this.horizOffD=t.readUint32(),this.vertOffN=t.readUint32(),this.vertOffD=t.readUint32()}),d.createBoxCtor("clli",function(t){this.max_content_light_level=t.readUint16(),this.max_pic_average_light_level=t.readUint16()}),d.createFullBoxCtor("co64",function(t){var e,i;if(e=t.readUint32(),this.chunk_offsets=[],0===this.version)for(i=0;i<e;i++)this.chunk_offsets.push(t.readUint64())}),d.createFullBoxCtor("CoLL",function(t){this.maxCLL=t.readUint16(),this.maxFALL=t.readUint16()}),d.createBoxCtor("colr",function(t){if(this.colour_type=t.readString(4),"nclx"===this.colour_type){this.colour_primaries=t.readUint16(),this.transfer_characteristics=t.readUint16(),this.matrix_coefficients=t.readUint16();var e=t.readUint8();this.full_range_flag=e>>7}else("rICC"===this.colour_type||"prof"===this.colour_type)&&(this.ICC_profile=t.readUint8Array(this.size-4))}),d.createFullBoxCtor("cprt",function(t){this.parseLanguage(t),this.notice=t.readCString()}),d.createFullBoxCtor("cslg",function(t){0===this.version&&(this.compositionToDTSShift=t.readInt32(),this.leastDecodeToDisplayDelta=t.readInt32(),this.greatestDecodeToDisplayDelta=t.readInt32(),this.compositionStartTime=t.readInt32(),this.compositionEndTime=t.readInt32())}),d.createFullBoxCtor("ctts",function(t){var e,i;if(e=t.readUint32(),this.sample_counts=[],this.sample_offsets=[],0===this.version)for(i=0;i<e;i++){this.sample_counts.push(t.readUint32());var r=t.readInt32();r<0&&s.warn("BoxParser","ctts box uses negative values without using version 1"),this.sample_offsets.push(r)}else if(1==this.version)for(i=0;i<e;i++)this.sample_counts.push(t.readUint32()),this.sample_offsets.push(t.readInt32())}),d.createBoxCtor("dac3",function(t){var e=t.readUint8(),i=t.readUint8(),r=t.readUint8();this.fscod=e>>6,this.bsid=e>>1&31,this.bsmod=(1&e)<<2|i>>6&3,this.acmod=i>>3&7,this.lfeon=i>>2&1,this.bit_rate_code=3&i|r>>5&7}),d.createBoxCtor("dec3",function(t){var e=t.readUint16();this.data_rate=e>>3,this.num_ind_sub=7&e,this.ind_subs=[];for(var i=0;i<this.num_ind_sub+1;i++){var r={};this.ind_subs.push(r);var s=t.readUint8(),a=t.readUint8(),n=t.readUint8();r.fscod=s>>6,r.bsid=s>>1&31,r.bsmod=(1&s)<<4|a>>4&15,r.acmod=a>>1&7,r.lfeon=1&a,r.num_dep_sub=n>>1&15,r.num_dep_sub>0&&(r.chan_loc=(1&n)<<8|t.readUint8())}}),d.createFullBoxCtor("dfLa",function(t){var e=[],i=["STREAMINFO","PADDING","APPLICATION","SEEKTABLE","VORBIS_COMMENT","CUESHEET","PICTURE","RESERVED"];for(this.parseFullHeader(t);;){var r=t.readUint8(),s=Math.min(127&r,i.length-1);if(s?t.readUint8Array(t.readUint24()):(t.readUint8Array(13),this.samplerate=t.readUint32()>>12,t.readUint8Array(20)),e.push(i[s]),128&r)break}this.numMetadataBlocks=e.length+" ("+e.join(", ")+")"}),d.createBoxCtor("dimm",function(t){this.bytessent=t.readUint64()}),d.createBoxCtor("dmax",function(t){this.time=t.readUint32()}),d.createBoxCtor("dmed",function(t){this.bytessent=t.readUint64()}),d.createBoxCtor("dOps",function(t){if(this.Version=t.readUint8(),this.OutputChannelCount=t.readUint8(),this.PreSkip=t.readUint16(),this.InputSampleRate=t.readUint32(),this.OutputGain=t.readInt16(),this.ChannelMappingFamily=t.readUint8(),0!==this.ChannelMappingFamily){this.StreamCount=t.readUint8(),this.CoupledCount=t.readUint8(),this.ChannelMapping=[];for(var e=0;e<this.OutputChannelCount;e++)this.ChannelMapping[e]=t.readUint8()}}),d.createFullBoxCtor("dref",function(t){var e,i;this.entries=[];for(var r=t.readUint32(),s=0;s<r;s++){if((e=d.parseOneBox(t,!1,this.size-(t.getPosition()-this.start))).code!==d.OK)return;i=e.box,this.entries.push(i)}}),d.createBoxCtor("drep",function(t){this.bytessent=t.readUint64()}),d.createFullBoxCtor("elng",function(t){this.extended_language=t.readString(this.size-this.hdr_size)}),d.createFullBoxCtor("elst",function(t){this.entries=[];for(var e=t.readUint32(),i=0;i<e;i++){var r={};this.entries.push(r),1===this.version?(r.segment_duration=t.readUint64(),r.media_time=t.readInt64()):(r.segment_duration=t.readUint32(),r.media_time=t.readInt32()),r.media_rate_integer=t.readInt16(),r.media_rate_fraction=t.readInt16()}}),d.createFullBoxCtor("emsg",function(t){1==this.version?(this.timescale=t.readUint32(),this.presentation_time=t.readUint64(),this.event_duration=t.readUint32(),this.id=t.readUint32(),this.scheme_id_uri=t.readCString(),this.value=t.readCString()):(this.scheme_id_uri=t.readCString(),this.value=t.readCString(),this.timescale=t.readUint32(),this.presentation_time_delta=t.readUint32(),this.event_duration=t.readUint32(),this.id=t.readUint32());var e=this.size-this.hdr_size-(16+(this.scheme_id_uri.length+1)+(this.value.length+1));1==this.version&&(e-=4),this.message_data=t.readUint8Array(e)}),d.createFullBoxCtor("esds",function(t){var e=t.readUint8Array(this.size-this.hdr_size);if(void 0!==c){var i=new c;this.esd=i.parseOneDescriptor(new n(e.buffer,0,n.BIG_ENDIAN))}}),d.createBoxCtor("fiel",function(t){this.fieldCount=t.readUint8(),this.fieldOrdering=t.readUint8()}),d.createBoxCtor("frma",function(t){this.data_format=t.readString(4)}),d.createBoxCtor("ftyp",function(t){var e=this.size-this.hdr_size;this.major_brand=t.readString(4),this.minor_version=t.readUint32(),e-=8,this.compatible_brands=[];for(var i=0;e>=4;)this.compatible_brands[i]=t.readString(4),e-=4,i++}),d.createFullBoxCtor("hdlr",function(t){0===this.version&&(t.readUint32(),this.handler=t.readString(4),t.readUint32Array(3),this.name=t.readString(this.size-this.hdr_size-20),"\0"===this.name[this.name.length-1]&&(this.name=this.name.slice(0,-1)))}),d.createBoxCtor("hvcC",function(t){var e,i,r,s;this.configurationVersion=t.readUint8(),s=t.readUint8(),this.general_profile_space=s>>6,this.general_tier_flag=(32&s)>>5,this.general_profile_idc=31&s,this.general_profile_compatibility=t.readUint32(),this.general_constraint_indicator=t.readUint8Array(6),this.general_level_idc=t.readUint8(),this.min_spatial_segmentation_idc=4095&t.readUint16(),this.parallelismType=3&t.readUint8(),this.chroma_format_idc=3&t.readUint8(),this.bit_depth_luma_minus8=7&t.readUint8(),this.bit_depth_chroma_minus8=7&t.readUint8(),this.avgFrameRate=t.readUint16(),s=t.readUint8(),this.constantFrameRate=s>>6,this.numTemporalLayers=(13&s)>>3,this.temporalIdNested=(4&s)>>2,this.lengthSizeMinusOne=3&s,this.nalu_arrays=[];var a=t.readUint8();for(e=0;e<a;e++){var n=[];this.nalu_arrays.push(n),s=t.readUint8(),n.completeness=(128&s)>>7,n.nalu_type=63&s;var o=t.readUint16();for(i=0;i<o;i++){var h={};n.push(h),r=t.readUint16(),h.data=t.readUint8Array(r)}}}),d.createFullBoxCtor("iinf",function(t){var e;0===this.version?this.entry_count=t.readUint16():this.entry_count=t.readUint32(),this.item_infos=[];for(var i=0;i<this.entry_count;i++){if((e=d.parseOneBox(t,!1,this.size-(t.getPosition()-this.start))).code!==d.OK)return;"infe"!==e.box.type&&s.error("BoxParser","Expected 'infe' box, got "+e.box.type),this.item_infos[i]=e.box}}),d.createFullBoxCtor("iloc",function(t){var e;e=t.readUint8(),this.offset_size=e>>4&15,this.length_size=15&e,e=t.readUint8(),this.base_offset_size=e>>4&15,1===this.version||2===this.version?this.index_size=15&e:this.index_size=0,this.items=[];var i=0;if(this.version<2)i=t.readUint16();else{if(2!==this.version)throw"version of iloc box not supported";i=t.readUint32()}for(var r=0;r<i;r++){var s={};if(this.items.push(s),this.version<2)s.item_ID=t.readUint16();else{if(2!==this.version)throw"version of iloc box not supported";s.item_ID=t.readUint16()}switch(1===this.version||2===this.version?s.construction_method=15&t.readUint16():s.construction_method=0,s.data_reference_index=t.readUint16(),this.base_offset_size){case 0:s.base_offset=0;break;case 4:s.base_offset=t.readUint32();break;case 8:s.base_offset=t.readUint64();break;default:throw"Error reading base offset size"}var a=t.readUint16();s.extents=[];for(var n=0;n<a;n++){var o={};if(s.extents.push(o),1===this.version||2===this.version)switch(this.index_size){case 0:o.extent_index=0;break;case 4:o.extent_index=t.readUint32();break;case 8:o.extent_index=t.readUint64();break;default:throw"Error reading extent index"}switch(this.offset_size){case 0:o.extent_offset=0;break;case 4:o.extent_offset=t.readUint32();break;case 8:o.extent_offset=t.readUint64();break;default:throw"Error reading extent index"}switch(this.length_size){case 0:o.extent_length=0;break;case 4:o.extent_length=t.readUint32();break;case 8:o.extent_length=t.readUint64();break;default:throw"Error reading extent index"}}}}),d.createBoxCtor("imir",function(t){var e=t.readUint8();this.reserved=e>>7,this.axis=1&e}),d.createFullBoxCtor("infe",function(t){if(0!==this.version&&1!==this.version||(this.item_ID=t.readUint16(),this.item_protection_index=t.readUint16(),this.item_name=t.readCString(),this.content_type=t.readCString(),this.content_encoding=t.readCString()),1===this.version)return this.extension_type=t.readString(4),s.warn("BoxParser","Cannot parse extension type"),void t.seek(this.start+this.size);this.version>=2&&(2===this.version?this.item_ID=t.readUint16():3===this.version&&(this.item_ID=t.readUint32()),this.item_protection_index=t.readUint16(),this.item_type=t.readString(4),this.item_name=t.readCString(),"mime"===this.item_type?(this.content_type=t.readCString(),this.content_encoding=t.readCString()):"uri "===this.item_type&&(this.item_uri_type=t.readCString()))}),d.createFullBoxCtor("ipma",function(t){var e,i;for(entry_count=t.readUint32(),this.associations=[],e=0;e<entry_count;e++){var r={};this.associations.push(r),this.version<1?r.id=t.readUint16():r.id=t.readUint32();var s=t.readUint8();for(r.props=[],i=0;i<s;i++){var a=t.readUint8(),n={};r.props.push(n),n.essential=(128&a)>>7==1,1&this.flags?n.property_index=(127&a)<<8|t.readUint8():n.property_index=127&a}}}),d.createFullBoxCtor("iref",function(t){var e,i;for(this.references=[];t.getPosition()<this.start+this.size;){if((e=d.parseOneBox(t,!0,this.size-(t.getPosition()-this.start))).code!==d.OK)return;(i=0===this.version?new d.SingleItemTypeReferenceBox(e.type,e.size,e.hdr_size,e.start):new d.SingleItemTypeReferenceBoxLarge(e.type,e.size,e.hdr_size,e.start)).write===d.Box.prototype.write&&"mdat"!==i.type&&(s.warn("BoxParser",i.type+" box writing not yet implemented, keeping unparsed data in memory for later write"),i.parseDataAndRewind(t)),i.parse(t),this.references.push(i)}}),d.createBoxCtor("irot",function(t){this.angle=3&t.readUint8()}),d.createFullBoxCtor("ispe",function(t){this.image_width=t.readUint32(),this.image_height=t.readUint32()}),d.createFullBoxCtor("kind",function(t){this.schemeURI=t.readCString(),this.value=t.readCString()}),d.createFullBoxCtor("leva",function(t){var e=t.readUint8();this.levels=[];for(var i=0;i<e;i++){var r={};this.levels[i]=r,r.track_ID=t.readUint32();var a=t.readUint8();switch(r.padding_flag=a>>7,r.assignment_type=127&a,r.assignment_type){case 0:r.grouping_type=t.readString(4);break;case 1:r.grouping_type=t.readString(4),r.grouping_type_parameter=t.readUint32();break;case 2:case 3:break;case 4:r.sub_track_id=t.readUint32();break;default:s.warn("BoxParser","Unknown leva assignement type")}}}),d.createBoxCtor("lsel",function(t){this.layer_id=t.readUint16()}),d.createBoxCtor("maxr",function(t){this.period=t.readUint32(),this.bytes=t.readUint32()}),d.createBoxCtor("mdcv",function(t){this.display_primaries=[],this.display_primaries[0]={},this.display_primaries[0].x=t.readUint16(),this.display_primaries[0].y=t.readUint16(),this.display_primaries[1]={},this.display_primaries[1].x=t.readUint16(),this.display_primaries[1].y=t.readUint16(),this.display_primaries[2]={},this.display_primaries[2].x=t.readUint16(),this.display_primaries[2].y=t.readUint16(),this.white_point={},this.white_point.x=t.readUint16(),this.white_point.y=t.readUint16(),this.max_display_mastering_luminance=t.readUint32(),this.min_display_mastering_luminance=t.readUint32()}),d.createFullBoxCtor("mdhd",function(t){1==this.version?(this.creation_time=t.readUint64(),this.modification_time=t.readUint64(),this.timescale=t.readUint32(),this.duration=t.readUint64()):(this.creation_time=t.readUint32(),this.modification_time=t.readUint32(),this.timescale=t.readUint32(),this.duration=t.readUint32()),this.parseLanguage(t),t.readUint16()}),d.createFullBoxCtor("mehd",function(t){1&this.flags&&(s.warn("BoxParser","mehd box incorrectly uses flags set to 1, converting version to 1"),this.version=1),1==this.version?this.fragment_duration=t.readUint64():this.fragment_duration=t.readUint32()}),d.createFullBoxCtor("meta",function(t){this.boxes=[],d.ContainerBox.prototype.parse.call(this,t)}),d.createFullBoxCtor("mfhd",function(t){this.sequence_number=t.readUint32()}),d.createFullBoxCtor("mfro",function(t){this._size=t.readUint32()}),d.createFullBoxCtor("mvhd",function(t){1==this.version?(this.creation_time=t.readUint64(),this.modification_time=t.readUint64(),this.timescale=t.readUint32(),this.duration=t.readUint64()):(this.creation_time=t.readUint32(),this.modification_time=t.readUint32(),this.timescale=t.readUint32(),this.duration=t.readUint32()),this.rate=t.readUint32(),this.volume=t.readUint16()>>8,t.readUint16(),t.readUint32Array(2),this.matrix=t.readUint32Array(9),t.readUint32Array(6),this.next_track_id=t.readUint32()}),d.createBoxCtor("npck",function(t){this.packetssent=t.readUint32()}),d.createBoxCtor("nump",function(t){this.packetssent=t.readUint64()}),d.createFullBoxCtor("padb",function(t){var e=t.readUint32();this.padbits=[];for(var i=0;i<Math.floor((e+1)/2);i++)this.padbits=t.readUint8()}),d.createBoxCtor("pasp",function(t){this.hSpacing=t.readUint32(),this.vSpacing=t.readUint32()}),d.createBoxCtor("payl",function(t){this.text=t.readString(this.size-this.hdr_size)}),d.createBoxCtor("payt",function(t){this.payloadID=t.readUint32();var e=t.readUint8();this.rtpmap_string=t.readString(e)}),d.createFullBoxCtor("pdin",function(t){var e=(this.size-this.hdr_size)/8;this.rate=[],this.initial_delay=[];for(var i=0;i<e;i++)this.rate[i]=t.readUint32(),this.initial_delay[i]=t.readUint32()}),d.createFullBoxCtor("pitm",function(t){0===this.version?this.item_id=t.readUint16():this.item_id=t.readUint32()}),d.createFullBoxCtor("pixi",function(t){var e;for(this.num_channels=t.readUint8(),this.bits_per_channels=[],e=0;e<this.num_channels;e++)this.bits_per_channels[e]=t.readUint8()}),d.createBoxCtor("pmax",function(t){this.bytes=t.readUint32()}),d.createFullBoxCtor("prft",function(t){this.ref_track_id=t.readUint32(),this.ntp_timestamp=t.readUint64(),0===this.version?this.media_time=t.readUint32():this.media_time=t.readUint64()}),d.createFullBoxCtor("pssh",function(t){if(this.system_id=d.parseHex16(t),this.version>0){var e=t.readUint32();this.kid=[];for(var i=0;i<e;i++)this.kid[i]=d.parseHex16(t)}var r=t.readUint32();r>0&&(this.data=t.readUint8Array(r))}),d.createFullBoxCtor("clef",function(t){this.width=t.readUint32(),this.height=t.readUint32()}),d.createFullBoxCtor("enof",function(t){this.width=t.readUint32(),this.height=t.readUint32()}),d.createFullBoxCtor("prof",function(t){this.width=t.readUint32(),this.height=t.readUint32()}),d.createContainerBoxCtor("tapt",null,["clef","prof","enof"]),d.createBoxCtor("rtp ",function(t){this.descriptionformat=t.readString(4),this.sdptext=t.readString(this.size-this.hdr_size-4)}),d.createFullBoxCtor("saio",function(t){1&this.flags&&(this.aux_info_type=t.readUint32(),this.aux_info_type_parameter=t.readUint32());var e=t.readUint32();this.offset=[];for(var i=0;i<e;i++)0===this.version?this.offset[i]=t.readUint32():this.offset[i]=t.readUint64()}),d.createFullBoxCtor("saiz",function(t){1&this.flags&&(this.aux_info_type=t.readUint32(),this.aux_info_type_parameter=t.readUint32()),this.default_sample_info_size=t.readUint8();var e=t.readUint32();if(this.sample_info_size=[],0===this.default_sample_info_size)for(var i=0;i<e;i++)this.sample_info_size[i]=t.readUint8()}),d.createSampleEntryCtor(d.SAMPLE_ENTRY_TYPE_METADATA,"mett",function(t){this.parseHeader(t),this.content_encoding=t.readCString(),this.mime_format=t.readCString(),this.parseFooter(t)}),d.createSampleEntryCtor(d.SAMPLE_ENTRY_TYPE_METADATA,"metx",function(t){this.parseHeader(t),this.content_encoding=t.readCString(),this.namespace=t.readCString(),this.schema_location=t.readCString(),this.parseFooter(t)}),d.createSampleEntryCtor(d.SAMPLE_ENTRY_TYPE_SUBTITLE,"sbtt",function(t){this.parseHeader(t),this.content_encoding=t.readCString(),this.mime_format=t.readCString(),this.parseFooter(t)}),d.createSampleEntryCtor(d.SAMPLE_ENTRY_TYPE_SUBTITLE,"stpp",function(t){this.parseHeader(t),this.namespace=t.readCString(),this.schema_location=t.readCString(),this.auxiliary_mime_types=t.readCString(),this.parseFooter(t)}),d.createSampleEntryCtor(d.SAMPLE_ENTRY_TYPE_SUBTITLE,"stxt",function(t){this.parseHeader(t),this.content_encoding=t.readCString(),this.mime_format=t.readCString(),this.parseFooter(t)}),d.createSampleEntryCtor(d.SAMPLE_ENTRY_TYPE_SUBTITLE,"tx3g",function(t){this.parseHeader(t),this.displayFlags=t.readUint32(),this.horizontal_justification=t.readInt8(),this.vertical_justification=t.readInt8(),this.bg_color_rgba=t.readUint8Array(4),this.box_record=t.readInt16Array(4),this.style_record=t.readUint8Array(12),this.parseFooter(t)}),d.createSampleEntryCtor(d.SAMPLE_ENTRY_TYPE_METADATA,"wvtt",function(t){this.parseHeader(t),this.parseFooter(t)}),d.createSampleGroupCtor("alst",function(t){var e,i=t.readUint16();for(this.first_output_sample=t.readUint16(),this.sample_offset=[],e=0;e<i;e++)this.sample_offset[e]=t.readUint32();var r=this.description_length-4-4*i;for(this.num_output_samples=[],this.num_total_samples=[],e=0;e<r/4;e++)this.num_output_samples[e]=t.readUint16(),this.num_total_samples[e]=t.readUint16()}),d.createSampleGroupCtor("avll",function(t){this.layerNumber=t.readUint8(),this.accurateStatisticsFlag=t.readUint8(),this.avgBitRate=t.readUint16(),this.avgFrameRate=t.readUint16()}),d.createSampleGroupCtor("avss",function(t){this.subSequenceIdentifier=t.readUint16(),this.layerNumber=t.readUint8();var e=t.readUint8();this.durationFlag=e>>7,this.avgRateFlag=e>>6&1,this.durationFlag&&(this.duration=t.readUint32()),this.avgRateFlag&&(this.accurateStatisticsFlag=t.readUint8(),this.avgBitRate=t.readUint16(),this.avgFrameRate=t.readUint16()),this.dependency=[];for(var i=t.readUint8(),r=0;r<i;r++){var s={};this.dependency.push(s),s.subSeqDirectionFlag=t.readUint8(),s.layerNumber=t.readUint8(),s.subSequenceIdentifier=t.readUint16()}}),d.createSampleGroupCtor("dtrt",function(t){s.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),d.createSampleGroupCtor("mvif",function(t){s.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),d.createSampleGroupCtor("prol",function(t){this.roll_distance=t.readInt16()}),d.createSampleGroupCtor("rap ",function(t){var e=t.readUint8();this.num_leading_samples_known=e>>7,this.num_leading_samples=127&e}),d.createSampleGroupCtor("rash",function(t){if(this.operation_point_count=t.readUint16(),this.description_length!==2+(1===this.operation_point_count?2:6*this.operation_point_count)+9)s.warn("BoxParser","Mismatch in "+this.grouping_type+" sample group length"),this.data=t.readUint8Array(this.description_length-2);else{if(1===this.operation_point_count)this.target_rate_share=t.readUint16();else{this.target_rate_share=[],this.available_bitrate=[];for(var e=0;e<this.operation_point_count;e++)this.available_bitrate[e]=t.readUint32(),this.target_rate_share[e]=t.readUint16()}this.maximum_bitrate=t.readUint32(),this.minimum_bitrate=t.readUint32(),this.discard_priority=t.readUint8()}}),d.createSampleGroupCtor("roll",function(t){this.roll_distance=t.readInt16()}),d.SampleGroupEntry.prototype.parse=function(t){s.warn("BoxParser","Unknown Sample Group type: "+this.grouping_type),this.data=t.readUint8Array(this.description_length)},d.createSampleGroupCtor("scif",function(t){s.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),d.createSampleGroupCtor("scnm",function(t){s.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),d.createSampleGroupCtor("seig",function(t){this.reserved=t.readUint8();var e=t.readUint8();this.crypt_byte_block=e>>4,this.skip_byte_block=15&e,this.isProtected=t.readUint8(),this.Per_Sample_IV_Size=t.readUint8(),this.KID=d.parseHex16(t),this.constant_IV_size=0,this.constant_IV=0,1===this.isProtected&&0===this.Per_Sample_IV_Size&&(this.constant_IV_size=t.readUint8(),this.constant_IV=t.readUint8Array(this.constant_IV_size))}),d.createSampleGroupCtor("stsa",function(t){s.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),d.createSampleGroupCtor("sync",function(t){var e=t.readUint8();this.NAL_unit_type=63&e}),d.createSampleGroupCtor("tele",function(t){var e=t.readUint8();this.level_independently_decodable=e>>7}),d.createSampleGroupCtor("tsas",function(t){s.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),d.createSampleGroupCtor("tscl",function(t){s.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),d.createSampleGroupCtor("vipr",function(t){s.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),d.createFullBoxCtor("sbgp",function(t){this.grouping_type=t.readString(4),1===this.version?this.grouping_type_parameter=t.readUint32():this.grouping_type_parameter=0,this.entries=[];for(var e=t.readUint32(),i=0;i<e;i++){var r={};this.entries.push(r),r.sample_count=t.readInt32(),r.group_description_index=t.readInt32()}}),d.createFullBoxCtor("schm",function(t){this.scheme_type=t.readString(4),this.scheme_version=t.readUint32(),1&this.flags&&(this.scheme_uri=t.readString(this.size-this.hdr_size-8))}),d.createBoxCtor("sdp ",function(t){this.sdptext=t.readString(this.size-this.hdr_size)}),d.createFullBoxCtor("sdtp",function(t){var e,i=this.size-this.hdr_size;this.is_leading=[],this.sample_depends_on=[],this.sample_is_depended_on=[],this.sample_has_redundancy=[];for(var r=0;r<i;r++)e=t.readUint8(),this.is_leading[r]=e>>6,this.sample_depends_on[r]=e>>4&3,this.sample_is_depended_on[r]=e>>2&3,this.sample_has_redundancy[r]=3&e}),d.createFullBoxCtor("senc"),d.createFullBoxCtor("sgpd",function(t){this.grouping_type=t.readString(4),s.debug("BoxParser","Found Sample Groups of type "+this.grouping_type),1===this.version?this.default_length=t.readUint32():this.default_length=0,this.version>=2&&(this.default_group_description_index=t.readUint32()),this.entries=[];for(var e=t.readUint32(),i=0;i<e;i++){var r;r=d[this.grouping_type+"SampleGroupEntry"]?new d[this.grouping_type+"SampleGroupEntry"](this.grouping_type):new d.SampleGroupEntry(this.grouping_type),this.entries.push(r),1===this.version&&0===this.default_length?r.description_length=t.readUint32():r.description_length=this.default_length,r.write===d.SampleGroupEntry.prototype.write&&(s.info("BoxParser","SampleGroup for type "+this.grouping_type+" writing not yet implemented, keeping unparsed data in memory for later write"),r.data=t.readUint8Array(r.description_length),t.position-=r.description_length),r.parse(t)}}),d.createFullBoxCtor("sidx",function(t){this.reference_ID=t.readUint32(),this.timescale=t.readUint32(),0===this.version?(this.earliest_presentation_time=t.readUint32(),this.first_offset=t.readUint32()):(this.earliest_presentation_time=t.readUint64(),this.first_offset=t.readUint64()),t.readUint16(),this.references=[];for(var e=t.readUint16(),i=0;i<e;i++){var r={};this.references.push(r);var s=t.readUint32();r.reference_type=s>>31&1,r.referenced_size=2147483647&s,r.subsegment_duration=t.readUint32(),s=t.readUint32(),r.starts_with_SAP=s>>31&1,r.SAP_type=s>>28&7,r.SAP_delta_time=268435455&s}}),d.SingleItemTypeReferenceBox=function(t,e,i,r){d.Box.call(this,t,e),this.hdr_size=i,this.start=r},d.SingleItemTypeReferenceBox.prototype=new d.Box,d.SingleItemTypeReferenceBox.prototype.parse=function(t){this.from_item_ID=t.readUint16();var e=t.readUint16();this.references=[];for(var i=0;i<e;i++)this.references[i]=t.readUint16()},d.SingleItemTypeReferenceBoxLarge=function(t,e,i,r){d.Box.call(this,t,e),this.hdr_size=i,this.start=r},d.SingleItemTypeReferenceBoxLarge.prototype=new d.Box,d.SingleItemTypeReferenceBoxLarge.prototype.parse=function(t){this.from_item_ID=t.readUint32();var e=t.readUint16();this.references=[];for(var i=0;i<e;i++)this.references[i]=t.readUint32()},d.createFullBoxCtor("SmDm",function(t){this.primaryRChromaticity_x=t.readUint16(),this.primaryRChromaticity_y=t.readUint16(),this.primaryGChromaticity_x=t.readUint16(),this.primaryGChromaticity_y=t.readUint16(),this.primaryBChromaticity_x=t.readUint16(),this.primaryBChromaticity_y=t.readUint16(),this.whitePointChromaticity_x=t.readUint16(),this.whitePointChromaticity_y=t.readUint16(),this.luminanceMax=t.readUint32(),this.luminanceMin=t.readUint32()}),d.createFullBoxCtor("smhd",function(t){this.balance=t.readUint16(),t.readUint16()}),d.createFullBoxCtor("ssix",function(t){this.subsegments=[];for(var e=t.readUint32(),i=0;i<e;i++){var r={};this.subsegments.push(r),r.ranges=[];for(var s=t.readUint32(),a=0;a<s;a++){var n={};r.ranges.push(n),n.level=t.readUint8(),n.range_size=t.readUint24()}}}),d.createFullBoxCtor("stco",function(t){var e;if(e=t.readUint32(),this.chunk_offsets=[],0===this.version)for(var i=0;i<e;i++)this.chunk_offsets.push(t.readUint32())}),d.createFullBoxCtor("stdp",function(t){var e=(this.size-this.hdr_size)/2;this.priority=[];for(var i=0;i<e;i++)this.priority[i]=t.readUint16()}),d.createFullBoxCtor("sthd"),d.createFullBoxCtor("stri",function(t){this.switch_group=t.readUint16(),this.alternate_group=t.readUint16(),this.sub_track_id=t.readUint32();var e=(this.size-this.hdr_size-8)/4;this.attribute_list=[];for(var i=0;i<e;i++)this.attribute_list[i]=t.readUint32()}),d.createFullBoxCtor("stsc",function(t){var e,i;if(e=t.readUint32(),this.first_chunk=[],this.samples_per_chunk=[],this.sample_description_index=[],0===this.version)for(i=0;i<e;i++)this.first_chunk.push(t.readUint32()),this.samples_per_chunk.push(t.readUint32()),this.sample_description_index.push(t.readUint32())}),d.createFullBoxCtor("stsd",function(t){var e,i,r,a;for(this.entries=[],r=t.readUint32(),e=1;e<=r;e++){if((i=d.parseOneBox(t,!0,this.size-(t.getPosition()-this.start))).code!==d.OK)return;d[i.type+"SampleEntry"]?((a=new d[i.type+"SampleEntry"](i.size)).hdr_size=i.hdr_size,a.start=i.start):(s.warn("BoxParser","Unknown sample entry type: "+i.type),a=new d.SampleEntry(i.type,i.size,i.hdr_size,i.start)),a.write===d.SampleEntry.prototype.write&&(s.info("BoxParser","SampleEntry "+a.type+" box writing not yet implemented, keeping unparsed data in memory for later write"),a.parseDataAndRewind(t)),a.parse(t),this.entries.push(a)}}),d.createFullBoxCtor("stsg",function(t){this.grouping_type=t.readUint32();var e=t.readUint16();this.group_description_index=[];for(var i=0;i<e;i++)this.group_description_index[i]=t.readUint32()}),d.createFullBoxCtor("stsh",function(t){var e,i;if(e=t.readUint32(),this.shadowed_sample_numbers=[],this.sync_sample_numbers=[],0===this.version)for(i=0;i<e;i++)this.shadowed_sample_numbers.push(t.readUint32()),this.sync_sample_numbers.push(t.readUint32())}),d.createFullBoxCtor("stss",function(t){var e,i;if(i=t.readUint32(),0===this.version)for(this.sample_numbers=[],e=0;e<i;e++)this.sample_numbers.push(t.readUint32())}),d.createFullBoxCtor("stsz",function(t){var e;if(this.sample_sizes=[],0===this.version)for(this.sample_size=t.readUint32(),this.sample_count=t.readUint32(),e=0;e<this.sample_count;e++)0===this.sample_size?this.sample_sizes.push(t.readUint32()):this.sample_sizes[e]=this.sample_size}),d.createFullBoxCtor("stts",function(t){var e,i,r;if(e=t.readUint32(),this.sample_counts=[],this.sample_deltas=[],0===this.version)for(i=0;i<e;i++)this.sample_counts.push(t.readUint32()),(r=t.readInt32())<0&&(s.warn("BoxParser","File uses negative stts sample delta, using value 1 instead, sync may be lost!"),r=1),this.sample_deltas.push(r)}),d.createFullBoxCtor("stvi",function(t){var e=t.readUint32();this.single_view_allowed=3&e,this.stereo_scheme=t.readUint32();var i,r,s=t.readUint32();for(this.stereo_indication_type=t.readString(s),this.boxes=[];t.getPosition()<this.start+this.size;){if((i=d.parseOneBox(t,!1,this.size-(t.getPosition()-this.start))).code!==d.OK)return;r=i.box,this.boxes.push(r),this[r.type]=r}}),d.createBoxCtor("styp",function(t){d.ftypBox.prototype.parse.call(this,t)}),d.createFullBoxCtor("stz2",function(t){var e,i;if(this.sample_sizes=[],0===this.version)if(this.reserved=t.readUint24(),this.field_size=t.readUint8(),i=t.readUint32(),4===this.field_size)for(e=0;e<i;e+=2){var r=t.readUint8();this.sample_sizes[e]=r>>4&15,this.sample_sizes[e+1]=15&r}else if(8===this.field_size)for(e=0;e<i;e++)this.sample_sizes[e]=t.readUint8();else if(16===this.field_size)for(e=0;e<i;e++)this.sample_sizes[e]=t.readUint16();else s.error("BoxParser","Error in length field in stz2 box")}),d.createFullBoxCtor("subs",function(t){var e,i,r,s;for(r=t.readUint32(),this.entries=[],e=0;e<r;e++){var a={};if(this.entries[e]=a,a.sample_delta=t.readUint32(),a.subsamples=[],(s=t.readUint16())>0)for(i=0;i<s;i++){var n={};a.subsamples.push(n),1==this.version?n.size=t.readUint32():n.size=t.readUint16(),n.priority=t.readUint8(),n.discardable=t.readUint8(),n.codec_specific_parameters=t.readUint32()}}}),d.createFullBoxCtor("tenc",function(t){if(t.readUint8(),0===this.version)t.readUint8();else{var e=t.readUint8();this.default_crypt_byte_block=e>>4&15,this.default_skip_byte_block=15&e}this.default_isProtected=t.readUint8(),this.default_Per_Sample_IV_Size=t.readUint8(),this.default_KID=d.parseHex16(t),1===this.default_isProtected&&0===this.default_Per_Sample_IV_Size&&(this.default_constant_IV_size=t.readUint8(),this.default_constant_IV=t.readUint8Array(this.default_constant_IV_size))}),d.createFullBoxCtor("tfdt",function(t){1==this.version?this.baseMediaDecodeTime=t.readUint64():this.baseMediaDecodeTime=t.readUint32()}),d.createFullBoxCtor("tfhd",function(t){var e=0;this.track_id=t.readUint32(),this.size-this.hdr_size>e&&this.flags&d.TFHD_FLAG_BASE_DATA_OFFSET?(this.base_data_offset=t.readUint64(),e+=8):this.base_data_offset=0,this.size-this.hdr_size>e&&this.flags&d.TFHD_FLAG_SAMPLE_DESC?(this.default_sample_description_index=t.readUint32(),e+=4):this.default_sample_description_index=0,this.size-this.hdr_size>e&&this.flags&d.TFHD_FLAG_SAMPLE_DUR?(this.default_sample_duration=t.readUint32(),e+=4):this.default_sample_duration=0,this.size-this.hdr_size>e&&this.flags&d.TFHD_FLAG_SAMPLE_SIZE?(this.default_sample_size=t.readUint32(),e+=4):this.default_sample_size=0,this.size-this.hdr_size>e&&this.flags&d.TFHD_FLAG_SAMPLE_FLAGS?(this.default_sample_flags=t.readUint32(),e+=4):this.default_sample_flags=0}),d.createFullBoxCtor("tfra",function(t){this.track_ID=t.readUint32(),t.readUint24();var e=t.readUint8();this.length_size_of_traf_num=e>>4&3,this.length_size_of_trun_num=e>>2&3,this.length_size_of_sample_num=3&e,this.entries=[];for(var i=t.readUint32(),r=0;r<i;r++)1===this.version?(this.time=t.readUint64(),this.moof_offset=t.readUint64()):(this.time=t.readUint32(),this.moof_offset=t.readUint32()),this.traf_number=t["readUint"+8*(this.length_size_of_traf_num+1)](),this.trun_number=t["readUint"+8*(this.length_size_of_trun_num+1)](),this.sample_number=t["readUint"+8*(this.length_size_of_sample_num+1)]()}),d.createFullBoxCtor("tkhd",function(t){1==this.version?(this.creation_time=t.readUint64(),this.modification_time=t.readUint64(),this.track_id=t.readUint32(),t.readUint32(),this.duration=t.readUint64()):(this.creation_time=t.readUint32(),this.modification_time=t.readUint32(),this.track_id=t.readUint32(),t.readUint32(),this.duration=t.readUint32()),t.readUint32Array(2),this.layer=t.readInt16(),this.alternate_group=t.readInt16(),this.volume=t.readInt16()>>8,t.readUint16(),this.matrix=t.readInt32Array(9),this.width=t.readUint32(),this.height=t.readUint32()}),d.createBoxCtor("tmax",function(t){this.time=t.readUint32()}),d.createBoxCtor("tmin",function(t){this.time=t.readUint32()}),d.createBoxCtor("totl",function(t){this.bytessent=t.readUint32()}),d.createBoxCtor("tpay",function(t){this.bytessent=t.readUint32()}),d.createBoxCtor("tpyl",function(t){this.bytessent=t.readUint64()}),d.TrackGroupTypeBox.prototype.parse=function(t){this.parseFullHeader(t),this.track_group_id=t.readUint32()},d.createTrackGroupCtor("msrc"),d.TrackReferenceTypeBox=function(t,e,i,r){d.Box.call(this,t,e),this.hdr_size=i,this.start=r},d.TrackReferenceTypeBox.prototype=new d.Box,d.TrackReferenceTypeBox.prototype.parse=function(t){this.track_ids=t.readUint32Array((this.size-this.hdr_size)/4)},d.trefBox.prototype.parse=function(t){for(var e,i;t.getPosition()<this.start+this.size;){if((e=d.parseOneBox(t,!0,this.size-(t.getPosition()-this.start))).code!==d.OK)return;(i=new d.TrackReferenceTypeBox(e.type,e.size,e.hdr_size,e.start)).write===d.Box.prototype.write&&"mdat"!==i.type&&(s.info("BoxParser","TrackReference "+i.type+" box writing not yet implemented, keeping unparsed data in memory for later write"),i.parseDataAndRewind(t)),i.parse(t),this.boxes.push(i)}},d.createFullBoxCtor("trep",function(t){for(this.track_ID=t.readUint32(),this.boxes=[];t.getPosition()<this.start+this.size;){if(ret=d.parseOneBox(t,!1,this.size-(t.getPosition()-this.start)),ret.code!==d.OK)return;box=ret.box,this.boxes.push(box)}}),d.createFullBoxCtor("trex",function(t){this.track_id=t.readUint32(),this.default_sample_description_index=t.readUint32(),this.default_sample_duration=t.readUint32(),this.default_sample_size=t.readUint32(),this.default_sample_flags=t.readUint32()}),d.createBoxCtor("trpy",function(t){this.bytessent=t.readUint64()}),d.createFullBoxCtor("trun",function(t){var e=0;if(this.sample_count=t.readUint32(),e+=4,this.size-this.hdr_size>e&&this.flags&d.TRUN_FLAGS_DATA_OFFSET?(this.data_offset=t.readInt32(),e+=4):this.data_offset=0,this.size-this.hdr_size>e&&this.flags&d.TRUN_FLAGS_FIRST_FLAG?(this.first_sample_flags=t.readUint32(),e+=4):this.first_sample_flags=0,this.sample_duration=[],this.sample_size=[],this.sample_flags=[],this.sample_composition_time_offset=[],this.size-this.hdr_size>e)for(var i=0;i<this.sample_count;i++)this.flags&d.TRUN_FLAGS_DURATION&&(this.sample_duration[i]=t.readUint32()),this.flags&d.TRUN_FLAGS_SIZE&&(this.sample_size[i]=t.readUint32()),this.flags&d.TRUN_FLAGS_FLAGS&&(this.sample_flags[i]=t.readUint32()),this.flags&d.TRUN_FLAGS_CTS_OFFSET&&(0===this.version?this.sample_composition_time_offset[i]=t.readUint32():this.sample_composition_time_offset[i]=t.readInt32())}),d.createFullBoxCtor("tsel",function(t){this.switch_group=t.readUint32();var e=(this.size-this.hdr_size-4)/4;this.attribute_list=[];for(var i=0;i<e;i++)this.attribute_list[i]=t.readUint32()}),d.createFullBoxCtor("txtC",function(t){this.config=t.readCString()}),d.createFullBoxCtor("url ",function(t){1!==this.flags&&(this.location=t.readCString())}),d.createFullBoxCtor("urn ",function(t){this.name=t.readCString(),this.size-this.hdr_size-this.name.length-1>0&&(this.location=t.readCString())}),d.createUUIDBox("a5d40b30e81411ddba2f0800200c9a66",!0,!1,function(t){this.LiveServerManifest=t.readString(this.size-this.hdr_size).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}),d.createUUIDBox("d08a4f1810f34a82b6c832d8aba183d3",!0,!1,function(t){this.system_id=d.parseHex16(t);var e=t.readUint32();e>0&&(this.data=t.readUint8Array(e))}),d.createUUIDBox("a2394f525a9b4f14a2446c427c648df4",!0,!1),d.createUUIDBox("8974dbce7be74c5184f97148f9882554",!0,!1,function(t){this.default_AlgorithmID=t.readUint24(),this.default_IV_size=t.readUint8(),this.default_KID=d.parseHex16(t)}),d.createUUIDBox("d4807ef2ca3946958e5426cb9e46a79f",!0,!1,function(t){this.fragment_count=t.readUint8(),this.entries=[];for(var e=0;e<this.fragment_count;e++){var i={},r=0,s=0;1===this.version?(r=t.readUint64(),s=t.readUint64()):(r=t.readUint32(),s=t.readUint32()),i.absolute_time=r,i.absolute_duration=s,this.entries.push(i)}}),d.createUUIDBox("6d1d9b0542d544e680e2141daff757b2",!0,!1,function(t){1===this.version?(this.absolute_time=t.readUint64(),this.duration=t.readUint64()):(this.absolute_time=t.readUint32(),this.duration=t.readUint32())}),d.createFullBoxCtor("vmhd",function(t){this.graphicsmode=t.readUint16(),this.opcolor=t.readUint16Array(3)}),d.createFullBoxCtor("vpcC",function(t){var e;1===this.version?(this.profile=t.readUint8(),this.level=t.readUint8(),e=t.readUint8(),this.bitDepth=e>>4,this.chromaSubsampling=e>>1&7,this.videoFullRangeFlag=1&e,this.colourPrimaries=t.readUint8(),this.transferCharacteristics=t.readUint8(),this.matrixCoefficients=t.readUint8(),this.codecIntializationDataSize=t.readUint16(),this.codecIntializationData=t.readUint8Array(this.codecIntializationDataSize)):(this.profile=t.readUint8(),this.level=t.readUint8(),e=t.readUint8(),this.bitDepth=e>>4&15,this.colorSpace=15&e,e=t.readUint8(),this.chromaSubsampling=e>>4&15,this.transferFunction=e>>1&7,this.videoFullRangeFlag=1&e,this.codecIntializationDataSize=t.readUint16(),this.codecIntializationData=t.readUint8Array(this.codecIntializationDataSize))}),d.createBoxCtor("vttC",function(t){this.text=t.readString(this.size-this.hdr_size)}),d.createFullBoxCtor("vvcC",function(t){var e,i,r={held_bits:void 0,num_held_bits:0,stream_read_1_bytes:function(t){this.held_bits=t.readUint8(),this.num_held_bits=8},stream_read_2_bytes:function(t){this.held_bits=t.readUint16(),this.num_held_bits=16},extract_bits:function(t){var e=this.held_bits>>this.num_held_bits-t&(1<<t)-1;return this.num_held_bits-=t,e}};if(r.stream_read_1_bytes(t),r.extract_bits(5),this.lengthSizeMinusOne=r.extract_bits(2),this.ptl_present_flag=r.extract_bits(1),this.ptl_present_flag){if(r.stream_read_2_bytes(t),this.ols_idx=r.extract_bits(9),this.num_sublayers=r.extract_bits(3),this.constant_frame_rate=r.extract_bits(2),this.chroma_format_idc=r.extract_bits(2),r.stream_read_1_bytes(t),this.bit_depth_minus8=r.extract_bits(3),r.extract_bits(5),r.stream_read_2_bytes(t),r.extract_bits(2),this.num_bytes_constraint_info=r.extract_bits(6),this.general_profile_idc=r.extract_bits(7),this.general_tier_flag=r.extract_bits(1),this.general_level_idc=t.readUint8(),r.stream_read_1_bytes(t),this.ptl_frame_only_constraint_flag=r.extract_bits(1),this.ptl_multilayer_enabled_flag=r.extract_bits(1),this.general_constraint_info=new Uint8Array(this.num_bytes_constraint_info),this.num_bytes_constraint_info){for(e=0;e<this.num_bytes_constraint_info-1;e++){var s=r.extract_bits(6);r.stream_read_1_bytes(t);var a=r.extract_bits(2);this.general_constraint_info[e]=s<<2|a}this.general_constraint_info[this.num_bytes_constraint_info-1]=r.extract_bits(6)}else r.extract_bits(6);for(r.stream_read_1_bytes(t),this.ptl_sublayer_present_mask=0,i=this.num_sublayers-2;i>=0;--i){var n=r.extract_bits(1);this.ptl_sublayer_present_mask|=n<<i}for(i=this.num_sublayers;i<=8&&this.num_sublayers>1;++i)r.extract_bits(1);for(i=this.num_sublayers-2;i>=0;--i)this.ptl_sublayer_present_mask&1<<i&&(this.sublayer_level_idc[i]=t.readUint8());if(this.ptl_num_sub_profiles=t.readUint8(),this.general_sub_profile_idc=[],this.ptl_num_sub_profiles)for(e=0;e<this.ptl_num_sub_profiles;e++)this.general_sub_profile_idc.push(t.readUint32());this.max_picture_width=t.readUint16(),this.max_picture_height=t.readUint16(),this.avg_frame_rate=t.readUint16()}this.nalu_arrays=[];var o=t.readUint8();for(e=0;e<o;e++){var h=[];this.nalu_arrays.push(h),r.stream_read_1_bytes(t),h.completeness=r.extract_bits(1),r.extract_bits(2),h.nalu_type=r.extract_bits(5);var c=1;for(13!=h.nalu_type&&12!=h.nalu_type&&(c=t.readUint16()),i=0;i<c;i++){var d=t.readUint16();h.push({data:t.readUint8Array(d),length:d})}}}),d.createFullBoxCtor("vvnC",function(t){var e=strm.readUint8();this.lengthSizeMinusOne=3&e}),d.SampleEntry.prototype.isVideo=function(){return!1},d.SampleEntry.prototype.isAudio=function(){return!1},d.SampleEntry.prototype.isSubtitle=function(){return!1},d.SampleEntry.prototype.isMetadata=function(){return!1},d.SampleEntry.prototype.isHint=function(){return!1},d.SampleEntry.prototype.getCodec=function(){return this.type.replace(".","")},d.SampleEntry.prototype.getWidth=function(){return""},d.SampleEntry.prototype.getHeight=function(){return""},d.SampleEntry.prototype.getChannelCount=function(){return""},d.SampleEntry.prototype.getSampleRate=function(){return""},d.SampleEntry.prototype.getSampleSize=function(){return""},d.VisualSampleEntry.prototype.isVideo=function(){return!0},d.VisualSampleEntry.prototype.getWidth=function(){return this.width},d.VisualSampleEntry.prototype.getHeight=function(){return this.height},d.AudioSampleEntry.prototype.isAudio=function(){return!0},d.AudioSampleEntry.prototype.getChannelCount=function(){return this.channel_count},d.AudioSampleEntry.prototype.getSampleRate=function(){return this.samplerate},d.AudioSampleEntry.prototype.getSampleSize=function(){return this.samplesize},d.SubtitleSampleEntry.prototype.isSubtitle=function(){return!0},d.MetadataSampleEntry.prototype.isMetadata=function(){return!0},d.decimalToHex=function(t,e){var i=Number(t).toString(16);for(e=null==e?e=2:e;i.length<e;)i="0"+i;return i},d.avc1SampleEntry.prototype.getCodec=d.avc2SampleEntry.prototype.getCodec=d.avc3SampleEntry.prototype.getCodec=d.avc4SampleEntry.prototype.getCodec=function(){var t=d.SampleEntry.prototype.getCodec.call(this);return this.avcC?t+"."+d.decimalToHex(this.avcC.AVCProfileIndication)+d.decimalToHex(this.avcC.profile_compatibility)+d.decimalToHex(this.avcC.AVCLevelIndication):t},d.hev1SampleEntry.prototype.getCodec=d.hvc1SampleEntry.prototype.getCodec=function(){var t,e=d.SampleEntry.prototype.getCodec.call(this);if(this.hvcC){switch(e+=".",this.hvcC.general_profile_space){case 0:e+="";break;case 1:e+="A";break;case 2:e+="B";break;case 3:e+="C"}e+=this.hvcC.general_profile_idc,e+=".";var i=this.hvcC.general_profile_compatibility,r=0;for(t=0;t<32&&(r|=1&i,31!=t);t++)r<<=1,i>>=1;e+=d.decimalToHex(r,0),e+=".",0===this.hvcC.general_tier_flag?e+="L":e+="H",e+=this.hvcC.general_level_idc;var s=!1,a="";for(t=5;t>=0;t--)(this.hvcC.general_constraint_indicator[t]||s)&&(a="."+d.decimalToHex(this.hvcC.general_constraint_indicator[t],0)+a,s=!0);e+=a}return e},d.vvc1SampleEntry.prototype.getCodec=d.vvi1SampleEntry.prototype.getCodec=function(){var t,e=d.SampleEntry.prototype.getCodec.call(this);if(this.vvcC){e+="."+this.vvcC.general_profile_idc,this.vvcC.general_tier_flag?e+=".H":e+=".L",e+=this.vvcC.general_level_idc;var i="";if(this.vvcC.general_constraint_info){var r,s=[],a=0;for(a|=this.vvcC.ptl_frame_only_constraint<<7,a|=this.vvcC.ptl_multilayer_enabled<<6,t=0;t<this.vvcC.general_constraint_info.length;++t)a|=this.vvcC.general_constraint_info[t]>>2&63,s.push(a),a&&(r=t),a=this.vvcC.general_constraint_info[t]>>2&3;if(void 0===r)i=".CA";else{i=".C";var n="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",o=0,h=0;for(t=0;t<=r;++t)for(o=o<<8|s[t],h+=8;h>=5;)i+=n[o>>h-5&31],o&=(1<<(h-=5))-1;h&&(i+=n[31&(o<<=5-h)])}}e+=i}return e},d.mp4aSampleEntry.prototype.getCodec=function(){var t=d.SampleEntry.prototype.getCodec.call(this);if(this.esds&&this.esds.esd){var e=this.esds.esd.getOTI(),i=this.esds.esd.getAudioConfig();return t+"."+d.decimalToHex(e)+(i?"."+i:"")}return t},d.stxtSampleEntry.prototype.getCodec=function(){var t=d.SampleEntry.prototype.getCodec.call(this);return this.mime_format?t+"."+this.mime_format:t},d.vp08SampleEntry.prototype.getCodec=d.vp09SampleEntry.prototype.getCodec=function(){var t=d.SampleEntry.prototype.getCodec.call(this),e=this.vpcC.level;0==e&&(e="00");var i=this.vpcC.bitDepth;return 8==i&&(i="08"),t+".0"+this.vpcC.profile+"."+e+"."+i},d.av01SampleEntry.prototype.getCodec=function(){var t,e=d.SampleEntry.prototype.getCodec.call(this),i=this.av1C.seq_level_idx_0;return i<10&&(i="0"+i),2===this.av1C.seq_profile&&1===this.av1C.high_bitdepth?t=1===this.av1C.twelve_bit?"12":"10":this.av1C.seq_profile<=2&&(t=1===this.av1C.high_bitdepth?"10":"08"),e+"."+this.av1C.seq_profile+"."+i+(this.av1C.seq_tier_0?"H":"M")+"."+t},d.Box.prototype.writeHeader=function(t,e){this.size+=8,this.size>o&&(this.size+=8),"uuid"===this.type&&(this.size+=16),s.debug("BoxWriter","Writing box "+this.type+" of size: "+this.size+" at position "+t.getPosition()+(e||"")),this.size>o?t.writeUint32(1):(this.sizePosition=t.getPosition(),t.writeUint32(this.size)),t.writeString(this.type,null,4),"uuid"===this.type&&t.writeUint8Array(this.uuid),this.size>o&&t.writeUint64(this.size)},d.FullBox.prototype.writeHeader=function(t){this.size+=4,d.Box.prototype.writeHeader.call(this,t," v="+this.version+" f="+this.flags),t.writeUint8(this.version),t.writeUint24(this.flags)},d.Box.prototype.write=function(t){"mdat"===this.type?this.data&&(this.size=this.data.length,this.writeHeader(t),t.writeUint8Array(this.data)):(this.size=this.data?this.data.length:0,this.writeHeader(t),this.data&&t.writeUint8Array(this.data))},d.ContainerBox.prototype.write=function(t){this.size=0,this.writeHeader(t);for(var e=0;e<this.boxes.length;e++)this.boxes[e]&&(this.boxes[e].write(t),this.size+=this.boxes[e].size);s.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),t.adjustUint32(this.sizePosition,this.size)},d.TrackReferenceTypeBox.prototype.write=function(t){this.size=4*this.track_ids.length,this.writeHeader(t),t.writeUint32Array(this.track_ids)},d.avcCBox.prototype.write=function(t){var e;for(this.size=7,e=0;e<this.SPS.length;e++)this.size+=2+this.SPS[e].length;for(e=0;e<this.PPS.length;e++)this.size+=2+this.PPS[e].length;for(this.ext&&(this.size+=this.ext.length),this.writeHeader(t),t.writeUint8(this.configurationVersion),t.writeUint8(this.AVCProfileIndication),t.writeUint8(this.profile_compatibility),t.writeUint8(this.AVCLevelIndication),t.writeUint8(this.lengthSizeMinusOne+252),t.writeUint8(this.SPS.length+224),e=0;e<this.SPS.length;e++)t.writeUint16(this.SPS[e].length),t.writeUint8Array(this.SPS[e].nalu);for(t.writeUint8(this.PPS.length),e=0;e<this.PPS.length;e++)t.writeUint16(this.PPS[e].length),t.writeUint8Array(this.PPS[e].nalu);this.ext&&t.writeUint8Array(this.ext)},d.co64Box.prototype.write=function(t){var e;for(this.version=0,this.flags=0,this.size=4+8*this.chunk_offsets.length,this.writeHeader(t),t.writeUint32(this.chunk_offsets.length),e=0;e<this.chunk_offsets.length;e++)t.writeUint64(this.chunk_offsets[e])},d.cslgBox.prototype.write=function(t){this.version=0,this.flags=0,this.size=20,this.writeHeader(t),t.writeInt32(this.compositionToDTSShift),t.writeInt32(this.leastDecodeToDisplayDelta),t.writeInt32(this.greatestDecodeToDisplayDelta),t.writeInt32(this.compositionStartTime),t.writeInt32(this.compositionEndTime)},d.cttsBox.prototype.write=function(t){var e;for(this.version=0,this.flags=0,this.size=4+8*this.sample_counts.length,this.writeHeader(t),t.writeUint32(this.sample_counts.length),e=0;e<this.sample_counts.length;e++)t.writeUint32(this.sample_counts[e]),1===this.version?t.writeInt32(this.sample_offsets[e]):t.writeUint32(this.sample_offsets[e])},d.drefBox.prototype.write=function(t){this.version=0,this.flags=0,this.size=4,this.writeHeader(t),t.writeUint32(this.entries.length);for(var e=0;e<this.entries.length;e++)this.entries[e].write(t),this.size+=this.entries[e].size;s.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),t.adjustUint32(this.sizePosition,this.size)},d.elngBox.prototype.write=function(t){this.version=0,this.flags=0,this.size=this.extended_language.length,this.writeHeader(t),t.writeString(this.extended_language)},d.elstBox.prototype.write=function(t){this.version=0,this.flags=0,this.size=4+12*this.entries.length,this.writeHeader(t),t.writeUint32(this.entries.length);for(var e=0;e<this.entries.length;e++){var i=this.entries[e];t.writeUint32(i.segment_duration),t.writeInt32(i.media_time),t.writeInt16(i.media_rate_integer),t.writeInt16(i.media_rate_fraction)}},d.emsgBox.prototype.write=function(t){this.version=0,this.flags=0,this.size=16+this.message_data.length+(this.scheme_id_uri.length+1)+(this.value.length+1),this.writeHeader(t),t.writeCString(this.scheme_id_uri),t.writeCString(this.value),t.writeUint32(this.timescale),t.writeUint32(this.presentation_time_delta),t.writeUint32(this.event_duration),t.writeUint32(this.id),t.writeUint8Array(this.message_data)},d.ftypBox.prototype.write=function(t){this.size=8+4*this.compatible_brands.length,this.writeHeader(t),t.writeString(this.major_brand,null,4),t.writeUint32(this.minor_version);for(var e=0;e<this.compatible_brands.length;e++)t.writeString(this.compatible_brands[e],null,4)},d.hdlrBox.prototype.write=function(t){this.size=20+this.name.length+1,this.version=0,this.flags=0,this.writeHeader(t),t.writeUint32(0),t.writeString(this.handler,null,4),t.writeUint32(0),t.writeUint32(0),t.writeUint32(0),t.writeCString(this.name)},d.kindBox.prototype.write=function(t){this.version=0,this.flags=0,this.size=this.schemeURI.length+1+(this.value.length+1),this.writeHeader(t),t.writeCString(this.schemeURI),t.writeCString(this.value)},d.mdhdBox.prototype.write=function(t){this.size=20,this.flags=0,this.version=0,this.writeHeader(t),t.writeUint32(this.creation_time),t.writeUint32(this.modification_time),t.writeUint32(this.timescale),t.writeUint32(this.duration),t.writeUint16(this.language),t.writeUint16(0)},d.mehdBox.prototype.write=function(t){this.version=0,this.flags=0,this.size=4,this.writeHeader(t),t.writeUint32(this.fragment_duration)},d.mfhdBox.prototype.write=function(t){this.version=0,this.flags=0,this.size=4,this.writeHeader(t),t.writeUint32(this.sequence_number)},d.mvhdBox.prototype.write=function(t){this.version=0,this.flags=0,this.size=96,this.writeHeader(t),t.writeUint32(this.creation_time),t.writeUint32(this.modification_time),t.writeUint32(this.timescale),t.writeUint32(this.duration),t.writeUint32(this.rate),t.writeUint16(this.volume<<8),t.writeUint16(0),t.writeUint32(0),t.writeUint32(0),t.writeUint32Array(this.matrix),t.writeUint32(0),t.writeUint32(0),t.writeUint32(0),t.writeUint32(0),t.writeUint32(0),t.writeUint32(0),t.writeUint32(this.next_track_id)},d.SampleEntry.prototype.writeHeader=function(t){this.size=8,d.Box.prototype.writeHeader.call(this,t),t.writeUint8(0),t.writeUint8(0),t.writeUint8(0),t.writeUint8(0),t.writeUint8(0),t.writeUint8(0),t.writeUint16(this.data_reference_index)},d.SampleEntry.prototype.writeFooter=function(t){for(var e=0;e<this.boxes.length;e++)this.boxes[e].write(t),this.size+=this.boxes[e].size;s.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),t.adjustUint32(this.sizePosition,this.size)},d.SampleEntry.prototype.write=function(t){this.writeHeader(t),t.writeUint8Array(this.data),this.size+=this.data.length,s.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),t.adjustUint32(this.sizePosition,this.size)},d.VisualSampleEntry.prototype.write=function(t){this.writeHeader(t),this.size+=70,t.writeUint16(0),t.writeUint16(0),t.writeUint32(0),t.writeUint32(0),t.writeUint32(0),t.writeUint16(this.width),t.writeUint16(this.height),t.writeUint32(this.horizresolution),t.writeUint32(this.vertresolution),t.writeUint32(0),t.writeUint16(this.frame_count),t.writeUint8(Math.min(31,this.compressorname.length)),t.writeString(this.compressorname,null,31),t.writeUint16(this.depth),t.writeInt16(-1),this.writeFooter(t)},d.AudioSampleEntry.prototype.write=function(t){this.writeHeader(t),this.size+=20,t.writeUint32(0),t.writeUint32(0),t.writeUint16(this.channel_count),t.writeUint16(this.samplesize),t.writeUint16(0),t.writeUint16(0),t.writeUint32(this.samplerate<<16),this.writeFooter(t)},d.stppSampleEntry.prototype.write=function(t){this.writeHeader(t),this.size+=this.namespace.length+1+this.schema_location.length+1+this.auxiliary_mime_types.length+1,t.writeCString(this.namespace),t.writeCString(this.schema_location),t.writeCString(this.auxiliary_mime_types),this.writeFooter(t)},d.SampleGroupEntry.prototype.write=function(t){t.writeUint8Array(this.data)},d.sbgpBox.prototype.write=function(t){this.version=1,this.flags=0,this.size=12+8*this.entries.length,this.writeHeader(t),t.writeString(this.grouping_type,null,4),t.writeUint32(this.grouping_type_parameter),t.writeUint32(this.entries.length);for(var e=0;e<this.entries.length;e++){var i=this.entries[e];t.writeInt32(i.sample_count),t.writeInt32(i.group_description_index)}},d.sgpdBox.prototype.write=function(t){var e,i;for(this.flags=0,this.size=12,e=0;e<this.entries.length;e++)i=this.entries[e],1===this.version&&(0===this.default_length&&(this.size+=4),this.size+=i.data.length);for(this.writeHeader(t),t.writeString(this.grouping_type,null,4),1===this.version&&t.writeUint32(this.default_length),this.version>=2&&t.writeUint32(this.default_sample_description_index),t.writeUint32(this.entries.length),e=0;e<this.entries.length;e++)i=this.entries[e],1===this.version&&0===this.default_length&&t.writeUint32(i.description_length),i.write(t)},d.sidxBox.prototype.write=function(t){this.version=0,this.flags=0,this.size=20+12*this.references.length,this.writeHeader(t),t.writeUint32(this.reference_ID),t.writeUint32(this.timescale),t.writeUint32(this.earliest_presentation_time),t.writeUint32(this.first_offset),t.writeUint16(0),t.writeUint16(this.references.length);for(var e=0;e<this.references.length;e++){var i=this.references[e];t.writeUint32(i.reference_type<<31|i.referenced_size),t.writeUint32(i.subsegment_duration),t.writeUint32(i.starts_with_SAP<<31|i.SAP_type<<28|i.SAP_delta_time)}},d.smhdBox.prototype.write=function(t){this.version=0,this.flags=1,this.size=4,this.writeHeader(t),t.writeUint16(this.balance),t.writeUint16(0)},d.stcoBox.prototype.write=function(t){this.version=0,this.flags=0,this.size=4+4*this.chunk_offsets.length,this.writeHeader(t),t.writeUint32(this.chunk_offsets.length),t.writeUint32Array(this.chunk_offsets)},d.stscBox.prototype.write=function(t){var e;for(this.version=0,this.flags=0,this.size=4+12*this.first_chunk.length,this.writeHeader(t),t.writeUint32(this.first_chunk.length),e=0;e<this.first_chunk.length;e++)t.writeUint32(this.first_chunk[e]),t.writeUint32(this.samples_per_chunk[e]),t.writeUint32(this.sample_description_index[e])},d.stsdBox.prototype.write=function(t){var e;for(this.version=0,this.flags=0,this.size=0,this.writeHeader(t),t.writeUint32(this.entries.length),this.size+=4,e=0;e<this.entries.length;e++)this.entries[e].write(t),this.size+=this.entries[e].size;s.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),t.adjustUint32(this.sizePosition,this.size)},d.stshBox.prototype.write=function(t){var e;for(this.version=0,this.flags=0,this.size=4+8*this.shadowed_sample_numbers.length,this.writeHeader(t),t.writeUint32(this.shadowed_sample_numbers.length),e=0;e<this.shadowed_sample_numbers.length;e++)t.writeUint32(this.shadowed_sample_numbers[e]),t.writeUint32(this.sync_sample_numbers[e])},d.stssBox.prototype.write=function(t){this.version=0,this.flags=0,this.size=4+4*this.sample_numbers.length,this.writeHeader(t),t.writeUint32(this.sample_numbers.length),t.writeUint32Array(this.sample_numbers)},d.stszBox.prototype.write=function(t){var e,i=!0;if(this.version=0,this.flags=0,this.sample_sizes.length>0)for(e=0;e+1<this.sample_sizes.length;){if(this.sample_sizes[e+1]!==this.sample_sizes[0]){i=!1;break}e++}else i=!1;this.size=8,i||(this.size+=4*this.sample_sizes.length),this.writeHeader(t),i?t.writeUint32(this.sample_sizes[0]):t.writeUint32(0),t.writeUint32(this.sample_sizes.length),i||t.writeUint32Array(this.sample_sizes)},d.sttsBox.prototype.write=function(t){var e;for(this.version=0,this.flags=0,this.size=4+8*this.sample_counts.length,this.writeHeader(t),t.writeUint32(this.sample_counts.length),e=0;e<this.sample_counts.length;e++)t.writeUint32(this.sample_counts[e]),t.writeUint32(this.sample_deltas[e])},d.tfdtBox.prototype.write=function(t){var e=Math.pow(2,32)-1;this.version=this.baseMediaDecodeTime>e?1:0,this.flags=0,this.size=4,1===this.version&&(this.size+=4),this.writeHeader(t),1===this.version?t.writeUint64(this.baseMediaDecodeTime):t.writeUint32(this.baseMediaDecodeTime)},d.tfhdBox.prototype.write=function(t){this.version=0,this.size=4,this.flags&d.TFHD_FLAG_BASE_DATA_OFFSET&&(this.size+=8),this.flags&d.TFHD_FLAG_SAMPLE_DESC&&(this.size+=4),this.flags&d.TFHD_FLAG_SAMPLE_DUR&&(this.size+=4),this.flags&d.TFHD_FLAG_SAMPLE_SIZE&&(this.size+=4),this.flags&d.TFHD_FLAG_SAMPLE_FLAGS&&(this.size+=4),this.writeHeader(t),t.writeUint32(this.track_id),this.flags&d.TFHD_FLAG_BASE_DATA_OFFSET&&t.writeUint64(this.base_data_offset),this.flags&d.TFHD_FLAG_SAMPLE_DESC&&t.writeUint32(this.default_sample_description_index),this.flags&d.TFHD_FLAG_SAMPLE_DUR&&t.writeUint32(this.default_sample_duration),this.flags&d.TFHD_FLAG_SAMPLE_SIZE&&t.writeUint32(this.default_sample_size),this.flags&d.TFHD_FLAG_SAMPLE_FLAGS&&t.writeUint32(this.default_sample_flags)},d.tkhdBox.prototype.write=function(t){this.version=0,this.size=80,this.writeHeader(t),t.writeUint32(this.creation_time),t.writeUint32(this.modification_time),t.writeUint32(this.track_id),t.writeUint32(0),t.writeUint32(this.duration),t.writeUint32(0),t.writeUint32(0),t.writeInt16(this.layer),t.writeInt16(this.alternate_group),t.writeInt16(this.volume<<8),t.writeUint16(0),t.writeInt32Array(this.matrix),t.writeUint32(this.width),t.writeUint32(this.height)},d.trexBox.prototype.write=function(t){this.version=0,this.flags=0,this.size=20,this.writeHeader(t),t.writeUint32(this.track_id),t.writeUint32(this.default_sample_description_index),t.writeUint32(this.default_sample_duration),t.writeUint32(this.default_sample_size),t.writeUint32(this.default_sample_flags)},d.trunBox.prototype.write=function(t){this.version=0,this.size=4,this.flags&d.TRUN_FLAGS_DATA_OFFSET&&(this.size+=4),this.flags&d.TRUN_FLAGS_FIRST_FLAG&&(this.size+=4),this.flags&d.TRUN_FLAGS_DURATION&&(this.size+=4*this.sample_duration.length),this.flags&d.TRUN_FLAGS_SIZE&&(this.size+=4*this.sample_size.length),this.flags&d.TRUN_FLAGS_FLAGS&&(this.size+=4*this.sample_flags.length),this.flags&d.TRUN_FLAGS_CTS_OFFSET&&(this.size+=4*this.sample_composition_time_offset.length),this.writeHeader(t),t.writeUint32(this.sample_count),this.flags&d.TRUN_FLAGS_DATA_OFFSET&&(this.data_offset_position=t.getPosition(),t.writeInt32(this.data_offset)),this.flags&d.TRUN_FLAGS_FIRST_FLAG&&t.writeUint32(this.first_sample_flags);for(var e=0;e<this.sample_count;e++)this.flags&d.TRUN_FLAGS_DURATION&&t.writeUint32(this.sample_duration[e]),this.flags&d.TRUN_FLAGS_SIZE&&t.writeUint32(this.sample_size[e]),this.flags&d.TRUN_FLAGS_FLAGS&&t.writeUint32(this.sample_flags[e]),this.flags&d.TRUN_FLAGS_CTS_OFFSET&&(0===this.version?t.writeUint32(this.sample_composition_time_offset[e]):t.writeInt32(this.sample_composition_time_offset[e]))},d["url Box"].prototype.write=function(t){this.version=0,this.location?(this.flags=0,this.size=this.location.length+1):(this.flags=1,this.size=0),this.writeHeader(t),this.location&&t.writeCString(this.location)},d["urn Box"].prototype.write=function(t){this.version=0,this.flags=0,this.size=this.name.length+1+(this.location?this.location.length+1:0),this.writeHeader(t),t.writeCString(this.name),this.location&&t.writeCString(this.location)},d.vmhdBox.prototype.write=function(t){this.version=0,this.flags=1,this.size=8,this.writeHeader(t),t.writeUint16(this.graphicsmode),t.writeUint16Array(this.opcolor)},d.cttsBox.prototype.unpack=function(t){var e,i,r;for(r=0,e=0;e<this.sample_counts.length;e++)for(i=0;i<this.sample_counts[e];i++)t[r].pts=t[r].dts+this.sample_offsets[e],r++},d.sttsBox.prototype.unpack=function(t){var e,i,r;for(r=0,e=0;e<this.sample_counts.length;e++)for(i=0;i<this.sample_counts[e];i++)t[r].dts=0===r?0:t[r-1].dts+this.sample_deltas[e],r++},d.stcoBox.prototype.unpack=function(t){var e;for(e=0;e<this.chunk_offsets.length;e++)t[e].offset=this.chunk_offsets[e]},d.stscBox.prototype.unpack=function(t){var e,i,r,s,a;for(s=0,a=0,e=0;e<this.first_chunk.length;e++)for(i=0;i<(e+1<this.first_chunk.length?this.first_chunk[e+1]:1/0);i++)for(a++,r=0;r<this.samples_per_chunk[e];r++){if(!t[s])return;t[s].description_index=this.sample_description_index[e],t[s].chunk_index=a,s++}},d.stszBox.prototype.unpack=function(t){var e;for(e=0;e<this.sample_sizes.length;e++)t[e].size=this.sample_sizes[e]},d.DIFF_BOXES_PROP_NAMES=["boxes","entries","references","subsamples","items","item_infos","extents","associations","subsegments","ranges","seekLists","seekPoints","esd","levels"],d.DIFF_PRIMITIVE_ARRAY_PROP_NAMES=["compatible_brands","matrix","opcolor","sample_counts","sample_counts","sample_deltas","first_chunk","samples_per_chunk","sample_sizes","chunk_offsets","sample_offsets","sample_description_index","sample_duration"],d.boxEqualFields=function(t,e){if(t&&!e)return!1;var i;for(i in t)if(!(d.DIFF_BOXES_PROP_NAMES.indexOf(i)>-1||t[i]instanceof d.Box||e[i]instanceof d.Box||void 0===t[i]||void 0===e[i]||"function"==typeof t[i]||"function"==typeof e[i]||t.subBoxNames&&t.subBoxNames.indexOf(i.slice(0,4))>-1||e.subBoxNames&&e.subBoxNames.indexOf(i.slice(0,4))>-1||"data"===i||"start"===i||"size"===i||"creation_time"===i||"modification_time"===i||d.DIFF_PRIMITIVE_ARRAY_PROP_NAMES.indexOf(i)>-1||t[i]===e[i]))return!1;return!0},d.boxEqual=function(t,e){if(!d.boxEqualFields(t,e))return!1;for(var i=0;i<d.DIFF_BOXES_PROP_NAMES.length;i++){var r=d.DIFF_BOXES_PROP_NAMES[i];if(t[r]&&e[r]&&!d.boxEqual(t[r],e[r]))return!1}return!0};var l=function(){};l.prototype.parseSample=function(t){var e,i,r=new a(t.buffer);for(e=[];!r.isEos();)(i=d.parseOneBox(r,!1)).code===d.OK&&"vttc"===i.box.type&&e.push(i.box);return e},l.prototype.getText=function(t,e,i){function r(t,e,i){return i=i||"0",(t+="").length>=e?t:new Array(e-t.length+1).join(i)+t}function s(t){var e=Math.floor(t/3600),i=Math.floor((t-3600*e)/60),s=Math.floor(t-3600*e-60*i),a=Math.floor(1e3*(t-3600*e-60*i-s));return r(e,2)+":"+r(i,2)+":"+r(s,2)+"."+r(a,3)}for(var a=this.parseSample(i),n="",o=0;o<a.length;o++){var h=a[o];n+=s(t)+" --\x3e "+s(e)+"\r\n",n+=h.payl.text}return n};var u=function(){};u.prototype.parseSample=function(t){var e,i={resources:[]},r=new a(t.data.buffer);if(t.subsamples&&0!==t.subsamples.length){if(i.documentString=r.readString(t.subsamples[0].size),t.subsamples.length>1)for(e=1;e<t.subsamples.length;e++)i.resources[e]=r.readUint8Array(t.subsamples[e].size)}else i.documentString=r.readString(t.data.length);return"undefined"!=typeof DOMParser&&(i.document=(new DOMParser).parseFromString(i.documentString,"application/xml")),i};var p=function(){};p.prototype.parseSample=function(t){return new a(t.data.buffer).readString(t.data.length)},p.prototype.parseConfig=function(t){var e=new a(t.buffer);return e.readUint32(),e.readCString()},e.XMLSubtitlein4Parser=u,e.Textin4Parser=p;var f=function(t){this.stream=t||new h,this.boxes=[],this.mdats=[],this.moofs=[],this.isProgressive=!1,this.moovStartFound=!1,this.onMoovStart=null,this.moovStartSent=!1,this.onReady=null,this.readySent=!1,this.onSegment=null,this.onSamples=null,this.onError=null,this.sampleListBuilt=!1,this.fragmentedTracks=[],this.extractedTracks=[],this.isFragmentationInitialized=!1,this.sampleProcessingStarted=!1,this.nextMoofNumber=0,this.itemListBuilt=!1,this.onSidx=null,this.sidxSent=!1};f.prototype.setSegmentOptions=function(t,e,i){var r=this.getTrackById(t);if(r){var s={};this.fragmentedTracks.push(s),s.id=t,s.user=e,s.trak=r,r.nextSample=0,s.segmentStream=null,s.nb_samples=1e3,s.rapAlignement=!0,i&&(i.nbSamples&&(s.nb_samples=i.nbSamples),i.rapAlignement&&(s.rapAlignement=i.rapAlignement))}},f.prototype.unsetSegmentOptions=function(t){for(var e=-1,i=0;i<this.fragmentedTracks.length;i++)this.fragmentedTracks[i].id==t&&(e=i);e>-1&&this.fragmentedTracks.splice(e,1)},f.prototype.setExtractionOptions=function(t,e,i){var r=this.getTrackById(t);if(r){var s={};this.extractedTracks.push(s),s.id=t,s.user=e,s.trak=r,r.nextSample=0,s.nb_samples=1e3,s.samples=[],i&&i.nbSamples&&(s.nb_samples=i.nbSamples)}},f.prototype.unsetExtractionOptions=function(t){for(var e=-1,i=0;i<this.extractedTracks.length;i++)this.extractedTracks[i].id==t&&(e=i);e>-1&&this.extractedTracks.splice(e,1)},f.prototype.parse=function(){var t,e;if(!this.restoreParsePosition||this.restoreParsePosition())for(;;){if(this.hasIncompleteMdat&&this.hasIncompleteMdat()){if(this.processIncompleteMdat())continue;return}if(this.saveParsePosition&&this.saveParsePosition(),(t=d.parseOneBox(this.stream,!1)).code===d.ERR_NOT_ENOUGH_DATA){if(this.processIncompleteBox){if(this.processIncompleteBox(t))continue;return}return}var i;switch(i="uuid"!==(e=t.box).type?e.type:e.uuid,this.boxes.push(e),i){case"mdat":this.mdats.push(e);break;case"moof":this.moofs.push(e);break;case"moov":this.moovStartFound=!0,0===this.mdats.length&&(this.isProgressive=!0);default:void 0!==this[i]&&s.warn("ISOFile","Duplicate Box of type: "+i+", overriding previous occurrence"),this[i]=e}this.updateUsedBytes&&this.updateUsedBytes(e,t)}},f.prototype.checkBuffer=function(t){if(null==t)throw"Buffer must be defined and non empty";if(void 0===t.fileStart)throw"Buffer must have a fileStart property";return 0===t.byteLength?(s.warn("ISOFile","Ignoring empty buffer (fileStart: "+t.fileStart+")"),this.stream.logBufferLevel(),!1):(s.info("ISOFile","Processing buffer (fileStart: "+t.fileStart+")"),t.usedBytes=0,this.stream.insertBuffer(t),this.stream.logBufferLevel(),!!this.stream.initialized()||(s.warn("ISOFile","Not ready to start parsing"),!1))},f.prototype.appendBuffer=function(t,e){var i;if(this.checkBuffer(t))return this.parse(),this.moovStartFound&&!this.moovStartSent&&(this.moovStartSent=!0,this.onMoovStart&&this.onMoovStart()),this.moov?(this.sampleListBuilt||(this.buildSampleLists(),this.sampleListBuilt=!0),this.updateSampleLists(),this.onReady&&!this.readySent&&(this.readySent=!0,this.onReady(this.getInfo())),this.processSamples(e),this.nextSeekPosition?(i=this.nextSeekPosition,this.nextSeekPosition=void 0):i=this.nextParsePosition,this.stream.getEndFilePositionAfter&&(i=this.stream.getEndFilePositionAfter(i))):i=this.nextParsePosition?this.nextParsePosition:0,this.sidx&&this.onSidx&&!this.sidxSent&&(this.onSidx(this.sidx),this.sidxSent=!0),this.meta&&(this.flattenItemInfo&&!this.itemListBuilt&&(this.flattenItemInfo(),this.itemListBuilt=!0),this.processItems&&this.processItems(this.onItem)),this.stream.cleanBuffers&&(s.info("ISOFile","Done processing buffer (fileStart: "+t.fileStart+") - next buffer to fetch should have a fileStart position of "+i),this.stream.logBufferLevel(),this.stream.cleanBuffers(),this.stream.logBufferLevel(!0),s.info("ISOFile","Sample data size in memory: "+this.getAllocatedSampleDataSize())),i},f.prototype.getInfo=function(){var t,e,i,r,s,a,n={},o=new Date("1904-01-01T00:00:00Z").getTime();if(this.moov)for(n.hasMoov=!0,n.duration=this.moov.mvhd.duration,n.timescale=this.moov.mvhd.timescale,n.isFragmented=null!=this.moov.mvex,n.isFragmented&&this.moov.mvex.mehd&&(n.fragment_duration=this.moov.mvex.mehd.fragment_duration),n.isProgressive=this.isProgressive,n.hasIOD=null!=this.moov.iods,n.brands=[],n.brands.push(this.ftyp.major_brand),n.brands=n.brands.concat(this.ftyp.compatible_brands),n.created=new Date(o+1e3*this.moov.mvhd.creation_time),n.modified=new Date(o+1e3*this.moov.mvhd.modification_time),n.tracks=[],n.audioTracks=[],n.videoTracks=[],n.subtitleTracks=[],n.metadataTracks=[],n.hintTracks=[],n.otherTracks=[],t=0;t<this.moov.traks.length;t++){if(a=(i=this.moov.traks[t]).mdia.minf.stbl.stsd.entries[0],r={},n.tracks.push(r),r.id=i.tkhd.track_id,r.name=i.mdia.hdlr.name,r.references=[],i.tref)for(e=0;e<i.tref.boxes.length;e++)s={},r.references.push(s),s.type=i.tref.boxes[e].type,s.track_ids=i.tref.boxes[e].track_ids;i.edts&&(r.edits=i.edts.elst.entries),r.created=new Date(o+1e3*i.tkhd.creation_time),r.modified=new Date(o+1e3*i.tkhd.modification_time),r.movie_duration=i.tkhd.duration,r.movie_timescale=n.timescale,r.layer=i.tkhd.layer,r.alternate_group=i.tkhd.alternate_group,r.volume=i.tkhd.volume,r.matrix=i.tkhd.matrix,r.track_width=i.tkhd.width/65536,r.track_height=i.tkhd.height/65536,r.timescale=i.mdia.mdhd.timescale,r.cts_shift=i.mdia.minf.stbl.cslg,r.duration=i.mdia.mdhd.duration,r.samples_duration=i.samples_duration,r.codec=a.getCodec(),r.kind=i.udta&&i.udta.kinds.length?i.udta.kinds[0]:{schemeURI:"",value:""},r.language=i.mdia.elng?i.mdia.elng.extended_language:i.mdia.mdhd.languageString,r.nb_samples=i.samples.length,r.size=i.samples_size,r.bitrate=8*r.size*r.timescale/r.samples_duration,a.isAudio()?(r.type="audio",n.audioTracks.push(r),r.audio={},r.audio.sample_rate=a.getSampleRate(),r.audio.channel_count=a.getChannelCount(),r.audio.sample_size=a.getSampleSize()):a.isVideo()?(r.type="video",n.videoTracks.push(r),r.video={},r.video.width=a.getWidth(),r.video.height=a.getHeight()):a.isSubtitle()?(r.type="subtitles",n.subtitleTracks.push(r)):a.isHint()?(r.type="metadata",n.hintTracks.push(r)):a.isMetadata()?(r.type="metadata",n.metadataTracks.push(r)):(r.type="metadata",n.otherTracks.push(r))}else n.hasMoov=!1;if(n.mime="",n.hasMoov&&n.tracks){for(n.videoTracks&&n.videoTracks.length>0?n.mime+='video/mp4; codecs="':n.audioTracks&&n.audioTracks.length>0?n.mime+='audio/mp4; codecs="':n.mime+='application/mp4; codecs="',t=0;t<n.tracks.length;t++)0!==t&&(n.mime+=","),n.mime+=n.tracks[t].codec;n.mime+='"; profiles="',n.mime+=this.ftyp.compatible_brands.join(),n.mime+='"'}return n},f.prototype.processSamples=function(t){var e,i;if(this.sampleProcessingStarted){if(this.isFragmentationInitialized&&null!==this.onSegment)for(e=0;e<this.fragmentedTracks.length;e++){var r=this.fragmentedTracks[e];for(i=r.trak;i.nextSample<i.samples.length&&this.sampleProcessingStarted;){s.debug("ISOFile","Creating media fragment on track #"+r.id+" for sample "+i.nextSample);var a=this.createFragment(r.id,i.nextSample,r.segmentStream);if(!a)break;if(r.segmentStream=a,i.nextSample++,(i.nextSample%r.nb_samples==0||t||i.nextSample>=i.samples.length)&&(s.info("ISOFile","Sending fragmented data on track #"+r.id+" for samples ["+Math.max(0,i.nextSample-r.nb_samples)+","+(i.nextSample-1)+"]"),s.info("ISOFile","Sample data size in memory: "+this.getAllocatedSampleDataSize()),this.onSegment&&this.onSegment(r.id,r.user,r.segmentStream.buffer,i.nextSample,t||i.nextSample>=i.samples.length),r.segmentStream=null,r!==this.fragmentedTracks[e]))break}}if(null!==this.onSamples)for(e=0;e<this.extractedTracks.length;e++){var n=this.extractedTracks[e];for(i=n.trak;i.nextSample<i.samples.length&&this.sampleProcessingStarted;){s.debug("ISOFile","Exporting on track #"+n.id+" sample #"+i.nextSample);var o=this.getSample(i,i.nextSample);if(!o)break;if(i.nextSample++,n.samples.push(o),(i.nextSample%n.nb_samples==0||i.nextSample>=i.samples.length)&&(s.debug("ISOFile","Sending samples on track #"+n.id+" for sample "+i.nextSample),this.onSamples&&this.onSamples(n.id,n.user,n.samples),n.samples=[],n!==this.extractedTracks[e]))break}}}},f.prototype.getBox=function(t){var e=this.getBoxes(t,!0);return e.length?e[0]:null},f.prototype.getBoxes=function(t,e){var i=[];return f._sweep.call(this,t,i,e),i},f._sweep=function(t,e,i){for(var r in this.type&&this.type==t&&e.push(this),this.boxes){if(e.length&&i)return;f._sweep.call(this.boxes[r],t,e,i)}},f.prototype.getTrackSamplesInfo=function(t){var e=this.getTrackById(t);return e?e.samples:void 0},f.prototype.getTrackSample=function(t,e){var i=this.getTrackById(t);return this.getSample(i,e)},f.prototype.releaseUsedSamples=function(t,e){var i=0,r=this.getTrackById(t);r.lastValidSample||(r.lastValidSample=0);for(var a=r.lastValidSample;a<e;a++)i+=this.releaseSample(r,a);s.info("ISOFile","Track #"+t+" released samples up to "+e+" (released size: "+i+", remaining: "+this.samplesDataSize+")"),r.lastValidSample=e},f.prototype.start=function(){this.sampleProcessingStarted=!0,this.processSamples(!1)},f.prototype.stop=function(){this.sampleProcessingStarted=!1},f.prototype.flush=function(){s.info("ISOFile","Flushing remaining samples"),this.updateSampleLists(),this.processSamples(!0),this.stream.cleanBuffers(),this.stream.logBufferLevel(!0)},f.prototype.seekTrack=function(t,e,i){var r,a,n,o,h=0,c=0;if(0===i.samples.length)return s.info("ISOFile","No sample in track, cannot seek! Using time "+s.getDurationString(0,1)+" and offset: 0"),{offset:0,time:0};for(r=0;r<i.samples.length;r++){if(a=i.samples[r],0===r)c=0,o=a.timescale;else if(a.cts>t*a.timescale){c=r-1;break}e&&a.is_sync&&(h=r)}for(e&&(c=h),t=i.samples[c].cts,i.nextSample=c;i.samples[c].alreadyRead===i.samples[c].size&&i.samples[c+1];)c++;return n=i.samples[c].offset+i.samples[c].alreadyRead,s.info("ISOFile","Seeking to "+(e?"RAP":"")+" sample #"+i.nextSample+" on track "+i.tkhd.track_id+", time "+s.getDurationString(t,o)+" and offset: "+n),{offset:n,time:t/o}},f.prototype.seek=function(t,e){var i,r,a,n=this.moov,o={offset:1/0,time:1/0};if(this.moov){for(a=0;a<n.traks.length;a++)i=n.traks[a],(r=this.seekTrack(t,e,i)).offset<o.offset&&(o.offset=r.offset),r.time<o.time&&(o.time=r.time);return s.info("ISOFile","Seeking at time "+s.getDurationString(o.time,1)+" needs a buffer with a fileStart position of "+o.offset),o.offset===1/0?o={offset:this.nextParsePosition,time:0}:o.offset=this.stream.getEndFilePositionAfter(o.offset),s.info("ISOFile","Adjusted seek position (after checking data already in buffer): "+o.offset),o}throw"Cannot seek: moov not received!"},f.prototype.equal=function(t){for(var e=0;e<this.boxes.length&&e<t.boxes.length;){var i=this.boxes[e],r=t.boxes[e];if(!d.boxEqual(i,r))return!1;e++}return!0},e.ISOFile=f,f.prototype.lastBoxStartPosition=0,f.prototype.parsingMdat=null,f.prototype.nextParsePosition=0,f.prototype.discardMdatData=!1,f.prototype.processIncompleteBox=function(t){var e;return"mdat"===t.type?(e=new d[t.type+"Box"](t.size),this.parsingMdat=e,this.boxes.push(e),this.mdats.push(e),e.start=t.start,e.hdr_size=t.hdr_size,this.stream.addUsedBytes(e.hdr_size),this.lastBoxStartPosition=e.start+e.size,this.stream.seek(e.start+e.size,!1,this.discardMdatData)?(this.parsingMdat=null,!0):(this.moovStartFound?this.nextParsePosition=this.stream.findEndContiguousBuf():this.nextParsePosition=e.start+e.size,!1)):("moov"===t.type&&(this.moovStartFound=!0,0===this.mdats.length&&(this.isProgressive=!0)),this.stream.mergeNextBuffer&&this.stream.mergeNextBuffer()?(this.nextParsePosition=this.stream.getEndPosition(),!0):(t.type?this.moovStartFound?this.nextParsePosition=this.stream.getEndPosition():this.nextParsePosition=this.stream.getPosition()+t.size:this.nextParsePosition=this.stream.getEndPosition(),!1))},f.prototype.hasIncompleteMdat=function(){return null!==this.parsingMdat},f.prototype.processIncompleteMdat=function(){var t;return t=this.parsingMdat,this.stream.seek(t.start+t.size,!1,this.discardMdatData)?(s.debug("ISOFile","Found 'mdat' end in buffered data"),this.parsingMdat=null,!0):(this.nextParsePosition=this.stream.findEndContiguousBuf(),!1)},f.prototype.restoreParsePosition=function(){return this.stream.seek(this.lastBoxStartPosition,!0,this.discardMdatData)},f.prototype.saveParsePosition=function(){this.lastBoxStartPosition=this.stream.getPosition()},f.prototype.updateUsedBytes=function(t,e){this.stream.addUsedBytes&&("mdat"===t.type?(this.stream.addUsedBytes(t.hdr_size),this.discardMdatData&&this.stream.addUsedBytes(t.size-t.hdr_size)):this.stream.addUsedBytes(t.size))},f.prototype.add=d.Box.prototype.add,f.prototype.addBox=d.Box.prototype.addBox,f.prototype.init=function(t){var e=t||{},i=(this.add("ftyp").set("major_brand",e.brands&&e.brands[0]||"iso4").set("minor_version",0).set("compatible_brands",e.brands||["iso4"]),this.add("moov"));return i.add("mvhd").set("timescale",e.timescale||600).set("rate",e.rate||65536).set("creation_time",0).set("modification_time",0).set("duration",e.duration||0).set("volume",e.width?0:256).set("matrix",[65536,0,0,0,65536,0,0,0,1073741824]).set("next_track_id",1),i.add("mvex"),this},f.prototype.addTrack=function(t){this.moov||this.init(t);var e=t||{};e.width=e.width||320,e.height=e.height||320,e.id=e.id||this.moov.mvhd.next_track_id,e.type=e.type||"avc1";var i=this.moov.add("trak");this.moov.mvhd.next_track_id=e.id+1,i.add("tkhd").set("flags",d.TKHD_FLAG_ENABLED|d.TKHD_FLAG_IN_MOVIE|d.TKHD_FLAG_IN_PREVIEW).set("creation_time",0).set("modification_time",0).set("track_id",e.id).set("duration",e.duration||0).set("layer",e.layer||0).set("alternate_group",0).set("volume",1).set("matrix",[0,0,0,0,0,0,0,0,0]).set("width",e.width<<16).set("height",e.height<<16);var r=i.add("mdia");r.add("mdhd").set("creation_time",0).set("modification_time",0).set("timescale",e.timescale||1).set("duration",e.media_duration||0).set("language",e.language||"und"),r.add("hdlr").set("handler",e.hdlr||"vide").set("name",e.name||"Track created with MP4Box.js"),r.add("elng").set("extended_language",e.language||"fr-FR");var s=r.add("minf");if(void 0!==d[e.type+"SampleEntry"]){var n=new d[e.type+"SampleEntry"];n.data_reference_index=1;var o="";for(var h in d.sampleEntryCodes)for(var c=d.sampleEntryCodes[h],l=0;l<c.length;l++)if(c.indexOf(e.type)>-1){o=h;break}switch(o){case"Visual":if(s.add("vmhd").set("graphicsmode",0).set("opcolor",[0,0,0]),n.set("width",e.width).set("height",e.height).set("horizresolution",72<<16).set("vertresolution",72<<16).set("frame_count",1).set("compressorname",e.type+" Compressor").set("depth",24),e.avcDecoderConfigRecord){var u=new d.avcCBox,p=new a(e.avcDecoderConfigRecord);u.parse(p),n.addBox(u)}break;case"Audio":s.add("smhd").set("balance",e.balance||0),n.set("channel_count",e.channel_count||2).set("samplesize",e.samplesize||16).set("samplerate",e.samplerate||65536);break;case"Hint":s.add("hmhd");break;case"Subtitle":s.add("sthd"),"stpp"===e.type&&n.set("namespace",e.namespace||"nonamespace").set("schema_location",e.schema_location||"").set("auxiliary_mime_types",e.auxiliary_mime_types||"");break;default:s.add("nmhd")}e.description&&n.addBox(e.description),e.description_boxes&&e.description_boxes.forEach(function(t){n.addBox(t)}),s.add("dinf").add("dref").addEntry((new d["url Box"]).set("flags",1));var f=s.add("stbl");return f.add("stsd").addEntry(n),f.add("stts").set("sample_counts",[]).set("sample_deltas",[]),f.add("stsc").set("first_chunk",[]).set("samples_per_chunk",[]).set("sample_description_index",[]),f.add("stco").set("chunk_offsets",[]),f.add("stsz").set("sample_sizes",[]),this.moov.mvex.add("trex").set("track_id",e.id).set("default_sample_description_index",e.default_sample_description_index||1).set("default_sample_duration",e.default_sample_duration||0).set("default_sample_size",e.default_sample_size||0).set("default_sample_flags",e.default_sample_flags||0),this.buildTrakSampleLists(i),e.id}},d.Box.prototype.computeSize=function(t){var e=t||new n;e.endianness=n.BIG_ENDIAN,this.write(e)},f.prototype.addSample=function(t,e,i){var r=i||{},s={},a=this.getTrackById(t);if(null!==a){s.number=a.samples.length,s.track_id=a.tkhd.track_id,s.timescale=a.mdia.mdhd.timescale,s.description_index=r.sample_description_index?r.sample_description_index-1:0,s.description=a.mdia.minf.stbl.stsd.entries[s.description_index],s.data=e,s.size=e.byteLength,s.alreadyRead=s.size,s.duration=r.duration||1,s.cts=r.cts||0,s.dts=r.dts||0,s.is_sync=r.is_sync||!1,s.is_leading=r.is_leading||0,s.depends_on=r.depends_on||0,s.is_depended_on=r.is_depended_on||0,s.has_redundancy=r.has_redundancy||0,s.degradation_priority=r.degradation_priority||0,s.offset=0,s.subsamples=r.subsamples,a.samples.push(s),a.samples_size+=s.size,a.samples_duration+=s.duration,a.first_dts||(a.first_dts=r.dts),this.processSamples();var n=this.createSingleSampleMoof(s);return this.addBox(n),n.computeSize(),n.trafs[0].truns[0].data_offset=n.size+8,this.add("mdat").data=new Uint8Array(e),s}},f.prototype.createSingleSampleMoof=function(t){var e;e=t.is_sync?1<<25:65536;var i=new d.moofBox;i.add("mfhd").set("sequence_number",this.nextMoofNumber),this.nextMoofNumber++;var r=i.add("traf"),s=this.getTrackById(t.track_id);return r.add("tfhd").set("track_id",t.track_id).set("flags",d.TFHD_FLAG_DEFAULT_BASE_IS_MOOF),r.add("tfdt").set("baseMediaDecodeTime",t.dts-(s.first_dts||0)),r.add("trun").set("flags",d.TRUN_FLAGS_DATA_OFFSET|d.TRUN_FLAGS_DURATION|d.TRUN_FLAGS_SIZE|d.TRUN_FLAGS_FLAGS|d.TRUN_FLAGS_CTS_OFFSET).set("data_offset",0).set("first_sample_flags",0).set("sample_count",1).set("sample_duration",[t.duration]).set("sample_size",[t.size]).set("sample_flags",[e]).set("sample_composition_time_offset",[t.cts-t.dts]),i},f.prototype.lastMoofIndex=0,f.prototype.samplesDataSize=0,f.prototype.resetTables=function(){var t,e,i,r,s,a;for(this.initial_duration=this.moov.mvhd.duration,this.moov.mvhd.duration=0,t=0;t<this.moov.traks.length;t++){(e=this.moov.traks[t]).tkhd.duration=0,e.mdia.mdhd.duration=0,(e.mdia.minf.stbl.stco||e.mdia.minf.stbl.co64).chunk_offsets=[],(i=e.mdia.minf.stbl.stsc).first_chunk=[],i.samples_per_chunk=[],i.sample_description_index=[],(e.mdia.minf.stbl.stsz||e.mdia.minf.stbl.stz2).sample_sizes=[],(r=e.mdia.minf.stbl.stts).sample_counts=[],r.sample_deltas=[],(s=e.mdia.minf.stbl.ctts)&&(s.sample_counts=[],s.sample_offsets=[]),a=e.mdia.minf.stbl.stss;var n=e.mdia.minf.stbl.boxes.indexOf(a);-1!=n&&(e.mdia.minf.stbl.boxes[n]=null)}},f.initSampleGroups=function(t,e,i,r,s){var a,n,o,h;function c(t,e,i){this.grouping_type=t,this.grouping_type_parameter=e,this.sbgp=i,this.last_sample_in_run=-1,this.entry_index=-1}for(e&&(e.sample_groups_info=[]),t.sample_groups_info||(t.sample_groups_info=[]),n=0;n<i.length;n++){for(h=i[n].grouping_type+"/"+i[n].grouping_type_parameter,o=new c(i[n].grouping_type,i[n].grouping_type_parameter,i[n]),e&&(e.sample_groups_info[h]=o),t.sample_groups_info[h]||(t.sample_groups_info[h]=o),a=0;a<r.length;a++)r[a].grouping_type===i[n].grouping_type&&(o.description=r[a],o.description.used=!0);if(s)for(a=0;a<s.length;a++)s[a].grouping_type===i[n].grouping_type&&(o.fragment_description=s[a],o.fragment_description.used=!0,o.is_fragment=!0)}if(e){if(s)for(n=0;n<s.length;n++)!s[n].used&&s[n].version>=2&&(h=s[n].grouping_type+"/0",(o=new c(s[n].grouping_type,0)).is_fragment=!0,e.sample_groups_info[h]||(e.sample_groups_info[h]=o))}else for(n=0;n<r.length;n++)!r[n].used&&r[n].version>=2&&(h=r[n].grouping_type+"/0",o=new c(r[n].grouping_type,0),t.sample_groups_info[h]||(t.sample_groups_info[h]=o))},f.setSampleGroupProperties=function(t,e,i,r){var s,a;for(s in e.sample_groups=[],r){var n;e.sample_groups[s]={},e.sample_groups[s].grouping_type=r[s].grouping_type,e.sample_groups[s].grouping_type_parameter=r[s].grouping_type_parameter,i>=r[s].last_sample_in_run&&(r[s].last_sample_in_run<0&&(r[s].last_sample_in_run=0),r[s].entry_index++,r[s].entry_index<=r[s].sbgp.entries.length-1&&(r[s].last_sample_in_run+=r[s].sbgp.entries[r[s].entry_index].sample_count)),r[s].entry_index<=r[s].sbgp.entries.length-1?e.sample_groups[s].group_description_index=r[s].sbgp.entries[r[s].entry_index].group_description_index:e.sample_groups[s].group_description_index=-1,0!==e.sample_groups[s].group_description_index&&(n=r[s].fragment_description?r[s].fragment_description:r[s].description,e.sample_groups[s].group_description_index>0?(a=e.sample_groups[s].group_description_index>65535?(e.sample_groups[s].group_description_index>>16)-1:e.sample_groups[s].group_description_index-1,n&&a>=0&&(e.sample_groups[s].description=n.entries[a])):n&&n.version>=2&&n.default_group_description_index>0&&(e.sample_groups[s].description=n.entries[n.default_group_description_index-1]))}},f.process_sdtp=function(t,e,i){e&&(t?(e.is_leading=t.is_leading[i],e.depends_on=t.sample_depends_on[i],e.is_depended_on=t.sample_is_depended_on[i],e.has_redundancy=t.sample_has_redundancy[i]):(e.is_leading=0,e.depends_on=0,e.is_depended_on=0,e.has_redundancy=0))},f.prototype.buildSampleLists=function(){var t,e;for(t=0;t<this.moov.traks.length;t++)e=this.moov.traks[t],this.buildTrakSampleLists(e)},f.prototype.buildTrakSampleLists=function(t){var e,i,r,s,a,n,o,h,c,d,l,u,p,m,g,y,_,b,w,v,k,S,T,x;if(t.samples=[],t.samples_duration=0,t.samples_size=0,i=t.mdia.minf.stbl.stco||t.mdia.minf.stbl.co64,r=t.mdia.minf.stbl.stsc,s=t.mdia.minf.stbl.stsz||t.mdia.minf.stbl.stz2,a=t.mdia.minf.stbl.stts,n=t.mdia.minf.stbl.ctts,o=t.mdia.minf.stbl.stss,h=t.mdia.minf.stbl.stsd,c=t.mdia.minf.stbl.subs,u=t.mdia.minf.stbl.stdp,d=t.mdia.minf.stbl.sbgps,l=t.mdia.minf.stbl.sgpds,b=-1,w=-1,v=-1,k=-1,S=0,T=0,x=0,f.initSampleGroups(t,null,d,l),void 0!==s){for(e=0;e<s.sample_sizes.length;e++){var C={};C.number=e,C.track_id=t.tkhd.track_id,C.timescale=t.mdia.mdhd.timescale,C.alreadyRead=0,t.samples[e]=C,C.size=s.sample_sizes[e],t.samples_size+=C.size,0===e?(m=1,p=0,C.chunk_index=m,C.chunk_run_index=p,_=r.samples_per_chunk[p],y=0,g=p+1<r.first_chunk.length?r.first_chunk[p+1]-1:1/0):e<_?(C.chunk_index=m,C.chunk_run_index=p):(m++,C.chunk_index=m,y=0,m<=g||(g=1+ ++p<r.first_chunk.length?r.first_chunk[p+1]-1:1/0),C.chunk_run_index=p,_+=r.samples_per_chunk[p]),C.description_index=r.sample_description_index[C.chunk_run_index]-1,C.description=h.entries[C.description_index],C.offset=i.chunk_offsets[C.chunk_index-1]+y,y+=C.size,e>b&&(w++,b<0&&(b=0),b+=a.sample_counts[w]),e>0?(t.samples[e-1].duration=a.sample_deltas[w],t.samples_duration+=t.samples[e-1].duration,C.dts=t.samples[e-1].dts+t.samples[e-1].duration):C.dts=0,n?(e>=v&&(k++,v<0&&(v=0),v+=n.sample_counts[k]),C.cts=t.samples[e].dts+n.sample_offsets[k]):C.cts=C.dts,o?(e==o.sample_numbers[S]-1?(C.is_sync=!0,S++):(C.is_sync=!1,C.degradation_priority=0),c&&c.entries[T].sample_delta+x==e+1&&(C.subsamples=c.entries[T].subsamples,x+=c.entries[T].sample_delta,T++)):C.is_sync=!0,f.process_sdtp(t.mdia.minf.stbl.sdtp,C,C.number),C.degradation_priority=u?u.priority[e]:0,c&&c.entries[T].sample_delta+x==e&&(C.subsamples=c.entries[T].subsamples,x+=c.entries[T].sample_delta),(d.length>0||l.length>0)&&f.setSampleGroupProperties(t,C,e,t.sample_groups_info)}e>0&&(t.samples[e-1].duration=Math.max(t.mdia.mdhd.duration-t.samples[e-1].dts,0),t.samples_duration+=t.samples[e-1].duration)}},f.prototype.updateSampleLists=function(){var t,e,i,r,s,a,n,o,h,c,l,u,p,m,g;if(void 0!==this.moov)for(;this.lastMoofIndex<this.moofs.length;)if(h=this.moofs[this.lastMoofIndex],this.lastMoofIndex++,"moof"==h.type)for(c=h,t=0;t<c.trafs.length;t++){for(l=c.trafs[t],u=this.getTrackById(l.tfhd.track_id),p=this.getTrexById(l.tfhd.track_id),r=l.tfhd.flags&d.TFHD_FLAG_SAMPLE_DESC?l.tfhd.default_sample_description_index:p?p.default_sample_description_index:1,s=l.tfhd.flags&d.TFHD_FLAG_SAMPLE_DUR?l.tfhd.default_sample_duration:p?p.default_sample_duration:0,a=l.tfhd.flags&d.TFHD_FLAG_SAMPLE_SIZE?l.tfhd.default_sample_size:p?p.default_sample_size:0,n=l.tfhd.flags&d.TFHD_FLAG_SAMPLE_FLAGS?l.tfhd.default_sample_flags:p?p.default_sample_flags:0,l.sample_number=0,l.sbgps.length>0&&f.initSampleGroups(u,l,l.sbgps,u.mdia.minf.stbl.sgpds,l.sgpds),e=0;e<l.truns.length;e++){var y=l.truns[e];for(i=0;i<y.sample_count;i++){(m={}).moof_number=this.lastMoofIndex,m.number_in_traf=l.sample_number,l.sample_number++,m.number=u.samples.length,l.first_sample_index=u.samples.length,u.samples.push(m),m.track_id=u.tkhd.track_id,m.timescale=u.mdia.mdhd.timescale,m.description_index=r-1,m.description=u.mdia.minf.stbl.stsd.entries[m.description_index],m.size=a,y.flags&d.TRUN_FLAGS_SIZE&&(m.size=y.sample_size[i]),u.samples_size+=m.size,m.duration=s,y.flags&d.TRUN_FLAGS_DURATION&&(m.duration=y.sample_duration[i]),u.samples_duration+=m.duration,u.first_traf_merged||i>0?m.dts=u.samples[u.samples.length-2].dts+u.samples[u.samples.length-2].duration:(l.tfdt?m.dts=l.tfdt.baseMediaDecodeTime:m.dts=0,u.first_traf_merged=!0),m.cts=m.dts,y.flags&d.TRUN_FLAGS_CTS_OFFSET&&(m.cts=m.dts+y.sample_composition_time_offset[i]),g=n,y.flags&d.TRUN_FLAGS_FLAGS?g=y.sample_flags[i]:0===i&&y.flags&d.TRUN_FLAGS_FIRST_FLAG&&(g=y.first_sample_flags),m.is_sync=!(g>>16&1),m.is_leading=g>>26&3,m.depends_on=g>>24&3,m.is_depended_on=g>>22&3,m.has_redundancy=g>>20&3,m.degradation_priority=65535&g;var _,b=!!(l.tfhd.flags&d.TFHD_FLAG_BASE_DATA_OFFSET),w=!!(l.tfhd.flags&d.TFHD_FLAG_DEFAULT_BASE_IS_MOOF),v=!!(y.flags&d.TRUN_FLAGS_DATA_OFFSET);_=b?l.tfhd.base_data_offset:w||0===e?c.start:o,m.offset=0===e&&0===i?v?_+y.data_offset:_:o,o=m.offset+m.size,(l.sbgps.length>0||l.sgpds.length>0||u.mdia.minf.stbl.sbgps.length>0||u.mdia.minf.stbl.sgpds.length>0)&&f.setSampleGroupProperties(u,m,m.number_in_traf,l.sample_groups_info)}}if(l.subs){u.has_fragment_subsamples=!0;var k=l.first_sample_index;for(e=0;e<l.subs.entries.length;e++)k+=l.subs.entries[e].sample_delta,(m=u.samples[k-1]).subsamples=l.subs.entries[e].subsamples}}},f.prototype.getSample=function(t,e){var i,r=t.samples[e];if(!this.moov)return null;if(r.data){if(r.alreadyRead==r.size)return r}else r.data=new Uint8Array(r.size),r.alreadyRead=0,this.samplesDataSize+=r.size,s.debug("ISOFile","Allocating sample #"+e+" on track #"+t.tkhd.track_id+" of size "+r.size+" (total: "+this.samplesDataSize+")");for(;;){var a=this.stream.findPosition(!0,r.offset+r.alreadyRead,!1);if(!(a>-1))return null;var o=(i=this.stream.buffers[a]).byteLength-(r.offset+r.alreadyRead-i.fileStart);if(r.size-r.alreadyRead<=o)return s.debug("ISOFile","Getting sample #"+e+" data (alreadyRead: "+r.alreadyRead+" offset: "+(r.offset+r.alreadyRead-i.fileStart)+" read size: "+(r.size-r.alreadyRead)+" full size: "+r.size+")"),n.memcpy(r.data.buffer,r.alreadyRead,i,r.offset+r.alreadyRead-i.fileStart,r.size-r.alreadyRead),i.usedBytes+=r.size-r.alreadyRead,this.stream.logBufferLevel(),r.alreadyRead=r.size,r;if(0===o)return null;s.debug("ISOFile","Getting sample #"+e+" partial data (alreadyRead: "+r.alreadyRead+" offset: "+(r.offset+r.alreadyRead-i.fileStart)+" read size: "+o+" full size: "+r.size+")"),n.memcpy(r.data.buffer,r.alreadyRead,i,r.offset+r.alreadyRead-i.fileStart,o),r.alreadyRead+=o,i.usedBytes+=o,this.stream.logBufferLevel()}},f.prototype.releaseSample=function(t,e){var i=t.samples[e];return i.data?(this.samplesDataSize-=i.size,i.data=null,i.alreadyRead=0,i.size):0},f.prototype.getAllocatedSampleDataSize=function(){return this.samplesDataSize},f.prototype.getCodecs=function(){var t,e="";for(t=0;t<this.moov.traks.length;t++)t>0&&(e+=","),e+=this.moov.traks[t].mdia.minf.stbl.stsd.entries[0].getCodec();return e},f.prototype.getTrexById=function(t){var e;if(!this.moov||!this.moov.mvex)return null;for(e=0;e<this.moov.mvex.trexs.length;e++){var i=this.moov.mvex.trexs[e];if(i.track_id==t)return i}return null},f.prototype.getTrackById=function(t){if(void 0===this.moov)return null;for(var e=0;e<this.moov.traks.length;e++){var i=this.moov.traks[e];if(i.tkhd.track_id==t)return i}return null},f.prototype.items=[],f.prototype.itemsDataSize=0,f.prototype.flattenItemInfo=function(){var t,e,i,r=this.items,a=this.meta;if(null!=a&&void 0!==a.hdlr&&void 0!==a.iinf){for(t=0;t<a.iinf.item_infos.length;t++)(i={}).id=a.iinf.item_infos[t].item_ID,r[i.id]=i,i.ref_to=[],i.name=a.iinf.item_infos[t].item_name,a.iinf.item_infos[t].protection_index>0&&(i.protection=a.ipro.protections[a.iinf.item_infos[t].protection_index-1]),a.iinf.item_infos[t].item_type?i.type=a.iinf.item_infos[t].item_type:i.type="mime",i.content_type=a.iinf.item_infos[t].content_type,i.content_encoding=a.iinf.item_infos[t].content_encoding;if(a.iloc)for(t=0;t<a.iloc.items.length;t++){var n=a.iloc.items[t];switch(i=r[n.item_ID],0!==n.data_reference_index&&(s.warn("Item storage with reference to other files: not supported"),i.source=a.dinf.boxes[n.data_reference_index-1]),n.construction_method){case 0:break;case 1:case 2:s.warn("Item storage with construction_method : not supported")}for(i.extents=[],i.size=0,e=0;e<n.extents.length;e++)i.extents[e]={},i.extents[e].offset=n.extents[e].extent_offset+n.base_offset,i.extents[e].length=n.extents[e].extent_length,i.extents[e].alreadyRead=0,i.size+=i.extents[e].length}if(a.pitm&&(r[a.pitm.item_id].primary=!0),a.iref)for(t=0;t<a.iref.references.length;t++){var o=a.iref.references[t];for(e=0;e<o.references.length;e++)r[o.from_item_ID].ref_to.push({type:o.type,id:o.references[e]})}if(a.iprp)for(var h=0;h<a.iprp.ipmas.length;h++){var c=a.iprp.ipmas[h];for(t=0;t<c.associations.length;t++){var d=c.associations[t];for(void 0===(i=r[d.id]).properties&&(i.properties={},i.properties.boxes=[]),e=0;e<d.props.length;e++){var l=d.props[e];if(l.property_index>0&&l.property_index-1<a.iprp.ipco.boxes.length){var u=a.iprp.ipco.boxes[l.property_index-1];i.properties[u.type]=u,i.properties.boxes.push(u)}}}}}},f.prototype.getItem=function(t){var e,i;if(!this.meta)return null;if(!(i=this.items[t]).data&&i.size)i.data=new Uint8Array(i.size),i.alreadyRead=0,this.itemsDataSize+=i.size,s.debug("ISOFile","Allocating item #"+t+" of size "+i.size+" (total: "+this.itemsDataSize+")");else if(i.alreadyRead===i.size)return i;for(var r=0;r<i.extents.length;r++){var a=i.extents[r];if(a.alreadyRead!==a.length){var o=this.stream.findPosition(!0,a.offset+a.alreadyRead,!1);if(!(o>-1))return null;var h=(e=this.stream.buffers[o]).byteLength-(a.offset+a.alreadyRead-e.fileStart);if(!(a.length-a.alreadyRead<=h))return s.debug("ISOFile","Getting item #"+t+" extent #"+r+" partial data (alreadyRead: "+a.alreadyRead+" offset: "+(a.offset+a.alreadyRead-e.fileStart)+" read size: "+h+" full extent size: "+a.length+" full item size: "+i.size+")"),n.memcpy(i.data.buffer,i.alreadyRead,e,a.offset+a.alreadyRead-e.fileStart,h),a.alreadyRead+=h,i.alreadyRead+=h,e.usedBytes+=h,this.stream.logBufferLevel(),null;s.debug("ISOFile","Getting item #"+t+" extent #"+r+" data (alreadyRead: "+a.alreadyRead+" offset: "+(a.offset+a.alreadyRead-e.fileStart)+" read size: "+(a.length-a.alreadyRead)+" full extent size: "+a.length+" full item size: "+i.size+")"),n.memcpy(i.data.buffer,i.alreadyRead,e,a.offset+a.alreadyRead-e.fileStart,a.length-a.alreadyRead),e.usedBytes+=a.length-a.alreadyRead,this.stream.logBufferLevel(),i.alreadyRead+=a.length-a.alreadyRead,a.alreadyRead=a.length}}return i.alreadyRead===i.size?i:null},f.prototype.releaseItem=function(t){var e=this.items[t];if(e.data){this.itemsDataSize-=e.size,e.data=null,e.alreadyRead=0;for(var i=0;i<e.extents.length;i++)e.extents[i].alreadyRead=0;return e.size}return 0},f.prototype.processItems=function(t){for(var e in this.items){var i=this.items[e];this.getItem(i.id),t&&!i.sent&&(t(i),i.sent=!0,i.data=null)}},f.prototype.hasItem=function(t){for(var e in this.items){var i=this.items[e];if(i.name===t)return i.id}return-1},f.prototype.getMetaHandler=function(){return this.meta?this.meta.hdlr.handler:null},f.prototype.getPrimaryItem=function(){return this.meta&&this.meta.pitm?this.getItem(this.meta.pitm.item_id):null},f.prototype.itemToFragmentedTrackFile=function(t){var e,i=t||{};if(null==(e=i.itemId?this.getItem(i.itemId):this.getPrimaryItem()))return null;var r=new f;r.discardMdatData=!1;var s={type:e.type,description_boxes:e.properties.boxes};e.properties.ispe&&(s.width=e.properties.ispe.image_width,s.height=e.properties.ispe.image_height);var a=r.addTrack(s);return a?(r.addSample(a,e.data),r):null},f.prototype.write=function(t){for(var e=0;e<this.boxes.length;e++)this.boxes[e].write(t)},f.prototype.createFragment=function(t,e,i){var r=this.getTrackById(t),a=this.getSample(r,e);if(null==a)return a=r.samples[e],this.nextSeekPosition?this.nextSeekPosition=Math.min(a.offset+a.alreadyRead,this.nextSeekPosition):this.nextSeekPosition=r.samples[e].offset+a.alreadyRead,null;var o=i||new n;o.endianness=n.BIG_ENDIAN;var h=this.createSingleSampleMoof(a);h.write(o),h.trafs[0].truns[0].data_offset=h.size+8,s.debug("MP4Box","Adjusting data_offset with new value "+h.trafs[0].truns[0].data_offset),o.adjustUint32(h.trafs[0].truns[0].data_offset_position,h.trafs[0].truns[0].data_offset);var c=new d.mdatBox;return c.data=a.data,c.write(o),o},f.writeInitializationSegment=function(t,e,i,r){var a;s.debug("ISOFile","Generating initialization segment");var o=new n;o.endianness=n.BIG_ENDIAN,t.write(o);var h=e.add("mvex");for(i&&h.add("mehd").set("fragment_duration",i),a=0;a<e.traks.length;a++)h.add("trex").set("track_id",e.traks[a].tkhd.track_id).set("default_sample_description_index",1).set("default_sample_duration",r).set("default_sample_size",0).set("default_sample_flags",65536);return e.write(o),o.buffer},f.prototype.save=function(t){var e=new n;e.endianness=n.BIG_ENDIAN,this.write(e),e.save(t)},f.prototype.getBuffer=function(){var t=new n;return t.endianness=n.BIG_ENDIAN,this.write(t),t.buffer},f.prototype.initializeSegmentation=function(){var t,e,i,r;for(null===this.onSegment&&s.warn("MP4Box","No segmentation callback set!"),this.isFragmentationInitialized||(this.isFragmentationInitialized=!0,this.nextMoofNumber=0,this.resetTables()),e=[],t=0;t<this.fragmentedTracks.length;t++){var a=new d.moovBox;a.mvhd=this.moov.mvhd,a.boxes.push(a.mvhd),i=this.getTrackById(this.fragmentedTracks[t].id),a.boxes.push(i),a.traks.push(i),(r={}).id=i.tkhd.track_id,r.user=this.fragmentedTracks[t].user,r.buffer=f.writeInitializationSegment(this.ftyp,a,this.moov.mvex&&this.moov.mvex.mehd?this.moov.mvex.mehd.fragment_duration:void 0,this.moov.traks[t].samples.length>0?this.moov.traks[t].samples[0].duration:0),e.push(r)}return e},d.Box.prototype.printHeader=function(t){this.size+=8,this.size>o&&(this.size+=8),"uuid"===this.type&&(this.size+=16),t.log(t.indent+"size:"+this.size),t.log(t.indent+"type:"+this.type)},d.FullBox.prototype.printHeader=function(t){this.size+=4,d.Box.prototype.printHeader.call(this,t),t.log(t.indent+"version:"+this.version),t.log(t.indent+"flags:"+this.flags)},d.Box.prototype.print=function(t){this.printHeader(t)},d.ContainerBox.prototype.print=function(t){this.printHeader(t);for(var e=0;e<this.boxes.length;e++)if(this.boxes[e]){var i=t.indent;t.indent+=" ",this.boxes[e].print(t),t.indent=i}},f.prototype.print=function(t){t.indent="";for(var e=0;e<this.boxes.length;e++)this.boxes[e]&&this.boxes[e].print(t)},d.mvhdBox.prototype.print=function(t){d.FullBox.prototype.printHeader.call(this,t),t.log(t.indent+"creation_time: "+this.creation_time),t.log(t.indent+"modification_time: "+this.modification_time),t.log(t.indent+"timescale: "+this.timescale),t.log(t.indent+"duration: "+this.duration),t.log(t.indent+"rate: "+this.rate),t.log(t.indent+"volume: "+(this.volume>>8)),t.log(t.indent+"matrix: "+this.matrix.join(", ")),t.log(t.indent+"next_track_id: "+this.next_track_id)},d.tkhdBox.prototype.print=function(t){d.FullBox.prototype.printHeader.call(this,t),t.log(t.indent+"creation_time: "+this.creation_time),t.log(t.indent+"modification_time: "+this.modification_time),t.log(t.indent+"track_id: "+this.track_id),t.log(t.indent+"duration: "+this.duration),t.log(t.indent+"volume: "+(this.volume>>8)),t.log(t.indent+"matrix: "+this.matrix.join(", ")),t.log(t.indent+"layer: "+this.layer),t.log(t.indent+"alternate_group: "+this.alternate_group),t.log(t.indent+"width: "+this.width),t.log(t.indent+"height: "+this.height)};e.createFile=function(t,e){var i=void 0===t||t,r=new f(e);return r.discardMdatData=!i,r}},273:(t,e,i)=>{i.d(e,{Ls:()=>a,MB:()=>n,gM:()=>o});var r=i(583),s=i(481);const a=7,n=9,o=t=>{const e=t.filePos,i=(0,s.sB)(t,9),a=new r.Zi(i);if(4095!==a.readBits(12))return null;if(a.skipBits(1),0!==a.readBits(2))return null;const n=a.readBits(1),o=a.readBits(2)+1,h=a.readBits(4);if(15===h)return null;a.skipBits(1);const c=a.readBits(3);if(0===c)throw new Error("ADTS frames with channel configuration 0 are not supported.");a.skipBits(1),a.skipBits(1),a.skipBits(1),a.skipBits(1);const d=a.readBits(13);a.skipBits(11);const l=a.readBits(2)+1;if(1!==l)throw new Error("ADTS frames with more than one AAC frame are not supported.");let u=null;return 1===n?t.filePos-=2:u=a.readBits(16),{objectType:o,samplingFrequencyIndex:h,channelConfiguration:c,frameLength:d,numberOfAacFrames:l,crcCheck:u,startPos:e}}},139:(t,e,i)=>{i.d(e,{$9:()=>s,$W:()=>F,Al:()=>P,BT:()=>H,BW:()=>S,Bc:()=>d,Dg:()=>f,E3:()=>m,FE:()=>L,H:()=>I,HS:()=>y,Nt:()=>k,Q3:()=>p,RG:()=>g,RO:()=>N,Sq:()=>c,Tn:()=>w,UB:()=>v,bO:()=>o,d:()=>D,d$:()=>_,qr:()=>O,vY:()=>r,zg:()=>R});var r,s,a=i(797),n=i(583);!function(t){t[t.NON_IDR_SLICE=1]="NON_IDR_SLICE",t[t.SLICE_DPA=2]="SLICE_DPA",t[t.SLICE_DPB=3]="SLICE_DPB",t[t.SLICE_DPC=4]="SLICE_DPC",t[t.IDR=5]="IDR",t[t.SEI=6]="SEI",t[t.SPS=7]="SPS",t[t.PPS=8]="PPS",t[t.AUD=9]="AUD",t[t.SPS_EXT=13]="SPS_EXT"}(r||(r={})),function(t){t[t.RASL_N=8]="RASL_N",t[t.RASL_R=9]="RASL_R",t[t.BLA_W_LP=16]="BLA_W_LP",t[t.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",t[t.VPS_NUT=32]="VPS_NUT",t[t.SPS_NUT=33]="SPS_NUT",t[t.PPS_NUT=34]="PPS_NUT",t[t.AUD_NUT=35]="AUD_NUT",t[t.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",t[t.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"}(s||(s={}));const o=function*(t){let e=0,i=-1;for(;e<t.length-2;){const r=t.indexOf(0,e);if(-1===r||r>=t.length-2)break;e=r;let s=0;e+3<t.length&&0===t[e+1]&&0===t[e+2]&&1===t[e+3]?s=4:0===t[e+1]&&1===t[e+2]&&(s=3),0!==s?(-1!==i&&e>i&&(yield{offset:i,length:e-i}),i=e+s,e=i):e++}-1!==i&&i<t.length&&(yield{offset:i,length:t.length-i})},h=function*(t,e){let i=0;const r=new DataView(t.buffer,t.byteOffset,t.byteLength);for(;i+e<=t.length;){let t;1===e?t=r.getUint8(i):2===e?t=r.getUint16(i,!1):3===e?t=(0,n.rB)(r,i,!1):((0,n.hu)(4===e),t=r.getUint32(i,!1)),i+=e,yield{offset:i,length:t},i+=t}},c=(t,e)=>{if(e.description){const i=3&(0,n._f)(e.description)[4];return h(t,i+1)}return o(t)},d=t=>31&t,l=t=>{const e=[],i=t.length;for(let r=0;r<i;r++)r+2<i&&0===t[r]&&0===t[r+1]&&3===t[r+2]?(e.push(0,0),r+=2):e.push(t[r]);return new Uint8Array(e)},u=new Uint8Array([0,0,0,1]),p=(t,e)=>{const i=t.reduce((t,i)=>t+e+i.byteLength,0),r=new Uint8Array(i);let s=0;for(const i of t){const t=new DataView(r.buffer,r.byteOffset,r.byteLength);switch(e){case 1:t.setUint8(s,i.byteLength);break;case 2:t.setUint16(s,i.byteLength,!1);break;case 3:(0,n.qN)(t,s,i.byteLength,!1);break;case 4:t.setUint32(s,i.byteLength,!1)}s+=e,r.set(i,s),s+=i.byteLength}return r},f=(t,e)=>{if(e.description){const i=3&(0,n._f)(e.description)[4];return p(t,i+1)}return(t=>{const e=t.reduce((t,e)=>t+u.byteLength+e.byteLength,0),i=new Uint8Array(e);let r=0;for(const e of t)i.set(u,r),r+=u.byteLength,i.set(e,r),r+=e.byteLength;return i})(t)},m=t=>{try{const e=[],i=[],s=[];for(const a of o(t)){const n=t.subarray(a.offset,a.offset+a.length),o=d(n[0]);o===r.SPS?e.push(n):o===r.PPS?i.push(n):o===r.SPS_EXT&&s.push(n)}if(0===e.length)return null;if(0===i.length)return null;const a=e[0],h=_(a);(0,n.hu)(null!==h);const c=100===h.profileIdc||110===h.profileIdc||122===h.profileIdc||144===h.profileIdc;return{configurationVersion:1,avcProfileIndication:h.profileIdc,profileCompatibility:h.constraintFlags,avcLevelIndication:h.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:e,pictureParameterSets:i,chromaFormat:c?h.chromaFormatIdc:null,bitDepthLumaMinus8:c?h.bitDepthLumaMinus8:null,bitDepthChromaMinus8:c?h.bitDepthChromaMinus8:null,sequenceParameterSetExt:c?s:null}}catch(t){return console.error("Error building AVC Decoder Configuration Record:",t),null}},g=t=>{const e=[];e.push(t.configurationVersion),e.push(t.avcProfileIndication),e.push(t.profileCompatibility),e.push(t.avcLevelIndication),e.push(252|3&t.lengthSizeMinusOne),e.push(224|31&t.sequenceParameterSets.length);for(const i of t.sequenceParameterSets){const t=i.byteLength;e.push(t>>8),e.push(255&t);for(let r=0;r<t;r++)e.push(i[r])}e.push(t.pictureParameterSets.length);for(const i of t.pictureParameterSets){const t=i.byteLength;e.push(t>>8),e.push(255&t);for(let r=0;r<t;r++)e.push(i[r])}if(100===t.avcProfileIndication||110===t.avcProfileIndication||122===t.avcProfileIndication||144===t.avcProfileIndication){(0,n.hu)(null!==t.chromaFormat),(0,n.hu)(null!==t.bitDepthLumaMinus8),(0,n.hu)(null!==t.bitDepthChromaMinus8),(0,n.hu)(null!==t.sequenceParameterSetExt),e.push(252|3&t.chromaFormat),e.push(248|7&t.bitDepthLumaMinus8),e.push(248|7&t.bitDepthChromaMinus8),e.push(t.sequenceParameterSetExt.length);for(const i of t.sequenceParameterSetExt){const t=i.byteLength;e.push(t>>8),e.push(255&t);for(let r=0;r<t;r++)e.push(i[r])}}return new Uint8Array(e)},y=t=>{try{const e=(0,n.NK)(t);let i=0;const r=e.getUint8(i++),s=e.getUint8(i++),a=e.getUint8(i++),o=e.getUint8(i++),h=3&e.getUint8(i++),c=31&e.getUint8(i++),d=[];for(let r=0;r<c;r++){const r=e.getUint16(i,!1);i+=2,d.push(t.subarray(i,i+r)),i+=r}const l=e.getUint8(i++),u=[];for(let r=0;r<l;r++){const r=e.getUint16(i,!1);i+=2,u.push(t.subarray(i,i+r)),i+=r}const p={configurationVersion:r,avcProfileIndication:s,profileCompatibility:a,avcLevelIndication:o,lengthSizeMinusOne:h,sequenceParameterSets:d,pictureParameterSets:u,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((100===s||110===s||122===s||144===s)&&i+4<=t.length){const r=3&e.getUint8(i++),s=7&e.getUint8(i++),a=7&e.getUint8(i++),n=e.getUint8(i++);p.chromaFormat=r,p.bitDepthLumaMinus8=s,p.bitDepthChromaMinus8=a;const o=[];for(let r=0;r<n;r++){const r=e.getUint16(i,!1);i+=2,o.push(t.subarray(i,i+r)),i+=r}p.sequenceParameterSetExt=o}return p}catch(t){return console.error("Error deserializing AVC Decoder Configuration Record:",t),null}},_=t=>{try{const e=new n.Zi(l(t));if(e.skipBits(1),e.skipBits(2),7!==e.readBits(5))return null;const i=e.readAlignedByte(),r=e.readAlignedByte(),s=e.readAlignedByte();(0,n.SI)(e);let o=1,h=0,c=0,d=0;if((100===i||110===i||122===i||244===i||44===i||83===i||86===i||118===i||128===i)&&(o=(0,n.SI)(e),3===o&&(d=e.readBits(1)),h=(0,n.SI)(e),c=(0,n.SI)(e),e.skipBits(1),e.readBits(1)))for(let t=0;t<(3!==o?8:12);t++)if(e.readBits(1)){const i=t<6?16:64;let r=8,s=8;for(let t=0;t<i;t++)0!==s&&(s=(r+(0,n.bJ)(e)+256)%256),r=0===s?r:s}(0,n.SI)(e);const u=(0,n.SI)(e);if(0===u)(0,n.SI)(e);else if(1===u){e.skipBits(1),(0,n.bJ)(e),(0,n.bJ)(e);const t=(0,n.SI)(e);for(let i=0;i<t;i++)(0,n.bJ)(e)}(0,n.SI)(e),e.skipBits(1);const p=(0,n.SI)(e),f=(0,n.SI)(e),m=16*(p+1),g=16*(f+1);let y=m,_=g;const w=e.readBits(1);if(w||e.skipBits(1),e.skipBits(1),e.readBits(1)){const t=(0,n.SI)(e),i=(0,n.SI)(e),r=(0,n.SI)(e),s=(0,n.SI)(e);let a,h;0===(0===d?o:0)?(a=1,h=2-w):(a=3===o?1:2,h=(1===o?2:1)*(2-w)),y-=a*(t+i),_-=h*(r+s)}let v=2,k=2,S=2,T=0,x=null,C=null;if(e.readBits(1)){e.readBits(1)&&255===e.readBits(8)&&(e.skipBits(16),e.skipBits(16)),e.readBits(1)&&e.skipBits(1),e.readBits(1)&&(e.skipBits(3),T=e.readBits(1),e.readBits(1)&&(v=e.readBits(8),k=e.readBits(8),S=e.readBits(8))),e.readBits(1)&&((0,n.SI)(e),(0,n.SI)(e)),e.readBits(1)&&(e.skipBits(32),e.skipBits(32),e.skipBits(1));const t=e.readBits(1);t&&b(e);const i=e.readBits(1);i&&b(e),(t||i)&&e.skipBits(1),e.skipBits(1),e.readBits(1)&&(e.skipBits(1),(0,n.SI)(e),(0,n.SI)(e),(0,n.SI)(e),(0,n.SI)(e),x=(0,n.SI)(e),C=(0,n.SI)(e))}if(null===x)if((0,n.hu)(null===C),(44===i||86===i||100===i||110===i||122===i||244===i)&&16&r)x=0,C=0;else{const t=p+1,e=(2-w)*(f+1),i=a.sP.find(t=>t.level>=s)??(0,n.Z$)(a.sP),r=Math.min(Math.floor(i.maxDpbMbs/(t*e)),16);x=r,C=r}return(0,n.hu)(null!==C),{profileIdc:i,constraintFlags:r,levelIdc:s,frameMbsOnlyFlag:w,chromaFormatIdc:o,bitDepthLumaMinus8:h,bitDepthChromaMinus8:c,codedWidth:m,codedHeight:g,displayWidth:y,displayHeight:_,colourPrimaries:v,matrixCoefficients:S,transferCharacteristics:k,fullRangeFlag:T,numReorderFrames:x,maxDecFrameBuffering:C}}catch(t){return console.error("Error parsing AVC SPS:",t),null}},b=t=>{const e=(0,n.SI)(t);t.skipBits(4),t.skipBits(4);for(let i=0;i<=e;i++)(0,n.SI)(t),(0,n.SI)(t),t.skipBits(1);t.skipBits(5),t.skipBits(5),t.skipBits(5),t.skipBits(5)},w=(t,e)=>{if(e.description){const i=3&(0,n._f)(e.description)[21];return h(t,i+1)}return o(t)},v=t=>t>>1&63,k=t=>{try{const e=new n.Zi(l(t));e.skipBits(16),e.readBits(4);const i=e.readBits(3),r=e.readBits(1),{general_profile_space:s,general_tier_flag:a,general_profile_idc:o,general_profile_compatibility_flags:h,general_constraint_indicator_flags:c,general_level_idc:d}=T(e,i);(0,n.SI)(e);const u=(0,n.SI)(e);let p=0;3===u&&(p=e.readBits(1));const f=(0,n.SI)(e),m=(0,n.SI)(e);let g=f,y=m;if(e.readBits(1)){const t=(0,n.SI)(e),i=(0,n.SI)(e),r=(0,n.SI)(e),s=(0,n.SI)(e);let a=1,o=1;const h=0===p?u:0;1===h?(a=2,o=2):2===h&&(a=2,o=1),g-=(t+i)*a,y-=(r+s)*o}const _=(0,n.SI)(e),b=(0,n.SI)(e);(0,n.SI)(e);const w=e.readBits(1);let v=0;for(let t=w?0:i;t<=i;t++)(0,n.SI)(e),v=(0,n.SI)(e),(0,n.SI)(e);(0,n.SI)(e),(0,n.SI)(e),(0,n.SI)(e),(0,n.SI)(e),(0,n.SI)(e),(0,n.SI)(e),e.readBits(1)&&e.readBits(1)&&x(e),e.skipBits(1),e.skipBits(1),e.readBits(1)&&(e.skipBits(4),e.skipBits(4),(0,n.SI)(e),(0,n.SI)(e),e.skipBits(1));const k=(0,n.SI)(e);if(C(e,k),e.readBits(1)){const t=(0,n.SI)(e);for(let i=0;i<t;i++)(0,n.SI)(e),e.skipBits(1)}e.skipBits(1),e.skipBits(1);let S=2,E=2,B=2,A=0,I=0;if(e.readBits(1)){const t=U(e,i);S=t.colourPrimaries,E=t.transferCharacteristics,B=t.matrixCoefficients,A=t.fullRangeFlag,I=t.minSpatialSegmentationIdc}return{displayWidth:g,displayHeight:y,colourPrimaries:S,transferCharacteristics:E,matrixCoefficients:B,fullRangeFlag:A,maxDecFrameBuffering:v+1,spsMaxSubLayersMinus1:i,spsTemporalIdNestingFlag:r,generalProfileSpace:s,generalTierFlag:a,generalProfileIdc:o,generalProfileCompatibilityFlags:h,generalConstraintIndicatorFlags:c,generalLevelIdc:d,chromaFormatIdc:u,bitDepthLumaMinus8:_,bitDepthChromaMinus8:b,minSpatialSegmentationIdc:I}}catch(t){return console.error("Error parsing HEVC SPS:",t),null}},S=t=>{try{const e=[],i=[],r=[],a=[];for(const n of o(t)){const o=t.subarray(n.offset,n.offset+n.length),h=v(o[0]);h===s.VPS_NUT?e.push(o):h===s.SPS_NUT?i.push(o):h===s.PPS_NUT?r.push(o):h!==s.PREFIX_SEI_NUT&&h!==s.SUFFIX_SEI_NUT||a.push(o)}if(0===i.length||0===r.length)return null;const h=k(i[0]);if(!h)return null;let c=0;if(r.length>0){const t=r[0],e=new n.Zi(l(t));e.skipBits(16),(0,n.SI)(e),(0,n.SI)(e),e.skipBits(1),e.skipBits(1),e.skipBits(3),e.skipBits(1),e.skipBits(1),(0,n.SI)(e),(0,n.SI)(e),(0,n.bJ)(e),e.skipBits(1),e.skipBits(1),e.readBits(1)&&(0,n.SI)(e),(0,n.bJ)(e),(0,n.bJ)(e),e.skipBits(1),e.skipBits(1),e.skipBits(1),e.skipBits(1);const i=e.readBits(1),s=e.readBits(1);c=i||s?i&&!s?2:!i&&s?3:0:0}const d=[...e.length?[{arrayCompleteness:1,nalUnitType:s.VPS_NUT,nalUnits:e}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:s.SPS_NUT,nalUnits:i}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:s.PPS_NUT,nalUnits:r}]:[],...a.length?[{arrayCompleteness:1,nalUnitType:v(a[0][0]),nalUnits:a}]:[]];return{configurationVersion:1,generalProfileSpace:h.generalProfileSpace,generalTierFlag:h.generalTierFlag,generalProfileIdc:h.generalProfileIdc,generalProfileCompatibilityFlags:h.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:h.generalConstraintIndicatorFlags,generalLevelIdc:h.generalLevelIdc,minSpatialSegmentationIdc:h.minSpatialSegmentationIdc,parallelismType:c,chromaFormatIdc:h.chromaFormatIdc,bitDepthLumaMinus8:h.bitDepthLumaMinus8,bitDepthChromaMinus8:h.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:h.spsMaxSubLayersMinus1+1,temporalIdNested:h.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:d}}catch(t){return console.error("Error building HEVC Decoder Configuration Record:",t),null}},T=(t,e)=>{const i=t.readBits(2),r=t.readBits(1),s=t.readBits(5);let a=0;for(let e=0;e<32;e++)a=a<<1|t.readBits(1);const n=new Uint8Array(6);for(let e=0;e<6;e++)n[e]=t.readBits(8);const o=t.readBits(8),h=[],c=[];for(let i=0;i<e;i++)h.push(t.readBits(1)),c.push(t.readBits(1));if(e>0)for(let i=e;i<8;i++)t.skipBits(2);for(let i=0;i<e;i++)h[i]&&t.skipBits(88),c[i]&&t.skipBits(8);return{general_profile_space:i,general_tier_flag:r,general_profile_idc:s,general_profile_compatibility_flags:a,general_constraint_indicator_flags:n,general_level_idc:o}},x=t=>{for(let e=0;e<4;e++)for(let i=0;i<(3===e?2:6);i++)if(t.readBits(1)){const i=Math.min(64,1<<4+(e<<1));e>1&&(0,n.bJ)(t);for(let e=0;e<i;e++)(0,n.bJ)(t)}else(0,n.SI)(t)},C=(t,e)=>{const i=[];for(let r=0;r<e;r++)i[r]=E(t,r,e,i)},E=(t,e,i,r)=>{let s=0,a=0,o=0;if(0!==e&&(a=t.readBits(1)),a){o=e===i?e-((0,n.SI)(t)+1):e-1,t.readBits(1),(0,n.SI)(t);const a=r[o]??0;for(let e=0;e<=a;e++)t.readBits(1)||t.readBits(1);s=r[o]}else{const e=(0,n.SI)(t),i=(0,n.SI)(t);for(let i=0;i<e;i++)(0,n.SI)(t),t.readBits(1);for(let e=0;e<i;e++)(0,n.SI)(t),t.readBits(1);s=e+i}return s},U=(t,e)=>{let i=2,r=2,s=2,a=0,o=0;return t.readBits(1)&&255===t.readBits(8)&&(t.readBits(16),t.readBits(16)),t.readBits(1)&&t.readBits(1),t.readBits(1)&&(t.readBits(3),a=t.readBits(1),t.readBits(1)&&(i=t.readBits(8),r=t.readBits(8),s=t.readBits(8))),t.readBits(1)&&((0,n.SI)(t),(0,n.SI)(t)),t.readBits(1),t.readBits(1),t.readBits(1),t.readBits(1)&&((0,n.SI)(t),(0,n.SI)(t),(0,n.SI)(t),(0,n.SI)(t)),t.readBits(1)&&(t.readBits(32),t.readBits(32),t.readBits(1)&&(0,n.SI)(t),t.readBits(1)&&B(t,!0,e)),t.readBits(1)&&(t.readBits(1),t.readBits(1),t.readBits(1),o=(0,n.SI)(t),(0,n.SI)(t),(0,n.SI)(t),(0,n.SI)(t),(0,n.SI)(t)),{colourPrimaries:i,transferCharacteristics:r,matrixCoefficients:s,fullRangeFlag:a,minSpatialSegmentationIdc:o}},B=(t,e,i)=>{let r=!1,s=!1,a=!1;e&&(r=1===t.readBits(1),s=1===t.readBits(1),(r||s)&&(a=1===t.readBits(1),a&&(t.readBits(8),t.readBits(5),t.readBits(1),t.readBits(5)),t.readBits(4),t.readBits(4),a&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5)));for(let e=0;e<=i;e++){let e=!0;1===t.readBits(1)||(e=1===t.readBits(1));let i=!1;e?(0,n.SI)(t):i=1===t.readBits(1);let o=1;i||(o=(0,n.SI)(t)+1),r&&A(t,o,a),s&&A(t,o,a)}},A=(t,e,i)=>{for(let r=0;r<e;r++)(0,n.SI)(t),(0,n.SI)(t),i&&((0,n.SI)(t),(0,n.SI)(t)),t.readBits(1)},I=t=>{const e=[];e.push(t.configurationVersion),e.push((3&t.generalProfileSpace)<<6|(1&t.generalTierFlag)<<5|31&t.generalProfileIdc),e.push(t.generalProfileCompatibilityFlags>>>24&255),e.push(t.generalProfileCompatibilityFlags>>>16&255),e.push(t.generalProfileCompatibilityFlags>>>8&255),e.push(255&t.generalProfileCompatibilityFlags),e.push(...t.generalConstraintIndicatorFlags),e.push(255&t.generalLevelIdc),e.push(240|t.minSpatialSegmentationIdc>>8&15),e.push(255&t.minSpatialSegmentationIdc),e.push(252|3&t.parallelismType),e.push(252|3&t.chromaFormatIdc),e.push(248|7&t.bitDepthLumaMinus8),e.push(248|7&t.bitDepthChromaMinus8),e.push(t.avgFrameRate>>8&255),e.push(255&t.avgFrameRate),e.push((3&t.constantFrameRate)<<6|(7&t.numTemporalLayers)<<3|(1&t.temporalIdNested)<<2|3&t.lengthSizeMinusOne),e.push(255&t.arrays.length);for(const i of t.arrays){e.push((1&i.arrayCompleteness)<<7|63&i.nalUnitType),e.push(i.nalUnits.length>>8&255),e.push(255&i.nalUnits.length);for(const t of i.nalUnits){e.push(t.length>>8&255),e.push(255&t.length);for(let i=0;i<t.length;i++)e.push(t[i])}}return new Uint8Array(e)},P=t=>{const e=new n.Zi(t);if(2!==e.readBits(2))return null;const i=e.readBits(1),r=(e.readBits(1)<<1)+i;if(3===r&&e.skipBits(1),1===e.readBits(1))return null;if(0!==e.readBits(1))return null;if(e.skipBits(2),4817730!==e.readBits(24))return null;let s=8;r>=2&&(s=e.readBits(1)?12:10);const o=e.readBits(3);let h=0,c=0;if(7!==o)if(c=e.readBits(1),1===r||3===r){const t=e.readBits(1),i=e.readBits(1);h=t||i?t&&!i?2:1:3,e.skipBits(1)}else h=1;else h=3,c=1;const d=(e.readBits(16)+1)*(e.readBits(16)+1);let l=(0,n.Z$)(a.Am).level;for(const t of a.Am)if(d<=t.maxPictureSize){l=t.level;break}return{profile:r,level:l,bitDepth:s,chromaSubsampling:h,videoFullRangeFlag:c,colourPrimaries:2===o?1:1===o?6:2,transferCharacteristics:2===o?1:1===o?6:2,matrixCoefficients:7===o?0:2===o?1:1===o?6:2}},z=function*(t){const e=new n.Zi(t),i=()=>{let t=0;for(let i=0;i<8;i++){const r=e.readAlignedByte();if(t|=(127&r)<<7*i,!(128&r))break;if(7===i&&128&r)return null}return t>=2**32-1?null:t};for(;e.getBitsLeft()>=8;){e.skipBits(1);const r=e.readBits(4),s=e.readBits(1),a=e.readBits(1);let o;if(e.skipBits(1),s&&e.skipBits(8),a){const t=i();if(null===t)return;o=t}else o=Math.floor(e.getBitsLeft()/8);(0,n.hu)(e.pos%8==0),yield{type:r,data:t.subarray(e.pos/8,e.pos/8+o)},e.skipBits(8*o)}},F=t=>{for(const{type:e,data:i}of z(t)){if(1!==e)continue;const t=new n.Zi(i),r=t.readBits(3),s=(t.readBits(1),t.readBits(1));let a=0,o=0,h=0;if(s)a=t.readBits(5);else{if(t.readBits(1)&&(t.skipBits(32),t.skipBits(32),t.readBits(1)))return null;const e=t.readBits(1);e&&(h=t.readBits(5),t.skipBits(32),t.skipBits(5),t.skipBits(5));const i=t.readBits(5);for(let r=0;r<=i;r++){t.skipBits(12);const i=t.readBits(5);if(0===r&&(a=i),i>7){const e=t.readBits(1);0===r&&(o=e)}if(e&&t.readBits(1)){const e=h+1;t.skipBits(e),t.skipBits(e),t.skipBits(1)}t.readBits(1)&&t.skipBits(4)}}const c=t.readBits(4),d=t.readBits(4),l=c+1;t.skipBits(l);const u=d+1;t.skipBits(u);let p=0;if(p=s?0:t.readBits(1),p&&(t.skipBits(4),t.skipBits(3)),t.skipBits(1),t.skipBits(1),t.skipBits(1),!s){t.skipBits(1),t.skipBits(1),t.skipBits(1),t.skipBits(1);const e=t.readBits(1);e&&(t.skipBits(1),t.skipBits(1));let i=0;i=t.readBits(1)?2:t.readBits(1),i>0&&(t.readBits(1)||t.skipBits(1)),e&&t.skipBits(3)}t.skipBits(1),t.skipBits(1),t.skipBits(1);const f=t.readBits(1);let m=8;2===r&&f?m=t.readBits(1)?12:10:r<=2&&(m=f?10:8);let g=0;1!==r&&(g=t.readBits(1));let y=1,_=1,b=0;return g||(0===r?(y=1,_=1):1===r?(y=0,_=0):12===m&&(y=t.readBits(1),y&&(_=t.readBits(1))),y&&_&&(b=t.readBits(2))),{profile:r,level:a,tier:o,bitDepth:m,monochrome:g,chromaSubsamplingX:y,chromaSubsamplingY:_,chromaSamplePosition:b}}return null},D=t=>{const e=(0,n.NK)(t),i=e.getUint8(9),r=e.getUint16(10,!0),s=e.getUint32(12,!0),a=e.getInt16(16,!0),o=e.getUint8(18);let h=null;return o&&(h=t.subarray(19,21+i)),{outputChannelCount:i,preSkip:r,inputSampleRate:s,outputGain:a,channelMappingFamily:o,channelMappingTable:h}},M=[480,960,1920,2880,480,960,1920,2880,480,960,1920,2880,480,960,480,960,120,240,480,960,120,240,480,960,120,240,480,960,120,240,480,960],L=t=>{const e=t[0]>>3;return{durationInSamples:M[e]}},R=t=>{if(t.length<7)throw new Error("Setup header is too short.");if(5!==t[0])throw new Error("Wrong packet type in Setup header.");if("vorbis"!==String.fromCharCode(...t.slice(1,7)))throw new Error("Invalid packet signature in Setup header.");const e=t.length,i=new Uint8Array(e);for(let r=0;r<e;r++)i[r]=t[e-1-r];const r=new n.Zi(i);let s=0;for(;r.getBitsLeft()>97;)if(1===r.readBits(1)){s=r.pos;break}if(0===s)throw new Error("Invalid Setup header: framing bit not found.");let a=0,o=!1,h=0;for(;r.getBitsLeft()>=97;){const t=r.pos,e=r.readBits(8),i=r.readBits(16),s=r.readBits(16);if(e>63||0!==i||0!==s){r.pos=t;break}if(r.skipBits(1),a++,a>64)break;r.clone().readBits(6)+1===a&&(o=!0,h=a)}if(!o)throw new Error("Invalid Setup header: mode header not found.");if(h>63)throw new Error(`Unsupported mode count: ${h}.`);const c=h;r.pos=0,r.skipBits(s);const d=Array(c).fill(0);for(let t=c-1;t>=0;t--)r.skipBits(40),d[t]=r.readBits(1);return{modeBlockflags:d}},N=(t,e,i)=>{switch(t){case"avc":for(const t of c(i,e)){const e=i[t.offset],s=d(e);if(s>=r.NON_IDR_SLICE&&s<=r.SLICE_DPC)return"delta";if(s===r.IDR)return"key";if(s===r.SEI&&(!(0,n.mJ)()||(0,n.AH)()>=144)){const e=i.subarray(t.offset,t.offset+t.length),r=l(e);let s=1;do{let t=0;for(;;){const e=r[s++];if(void 0===e)break;if(t+=e,e<255)break}let e=0;for(;;){const t=r[s++];if(void 0===t)break;if(e+=t,t<255)break}if(6===t){const t=new n.Zi(r);t.pos=8*s;const e=(0,n.SI)(t),i=t.readBits(1);if(0===e&&1===i)return"key"}s+=e}while(s<r.length-1)}}return"delta";case"hevc":for(const t of w(i,e)){const e=v(i[t.offset]);if(e<s.BLA_W_LP)return"delta";if(e<=s.RSV_IRAP_VCL23)return"key"}return"delta";case"vp8":return 1&i[0]?"delta":"key";case"vp9":{const t=new n.Zi(i);if(2!==t.readBits(2))return null;const e=t.readBits(1);return 3===(t.readBits(1)<<1)+e&&t.skipBits(1),t.readBits(1)?null:0===t.readBits(1)?"key":"delta"}case"av1":{let t=!1;for(const{type:e,data:r}of z(i))if(1===e){const e=new n.Zi(r);e.skipBits(4),t=!!e.readBits(1)}else if(3===e||6===e||7===e){if(t)return"key";const e=new n.Zi(r);return e.readBits(1)?null:0===e.readBits(2)?"key":"delta"}return null}default:(0,n.vE)(t),(0,n.hu)(!1)}};var O;!function(t){t[t.STREAMINFO=0]="STREAMINFO",t[t.VORBIS_COMMENT=4]="VORBIS_COMMENT",t[t.PICTURE=6]="PICTURE"}(O||(O={}));const H=(t,e)=>{const i=(0,n.NK)(t);let r=0;const s=i.getUint32(r,!0);r+=4;const a=n.zN.decode(t.subarray(r,r+s));r+=s,s>0&&(e.raw??={},e.raw.vendor??=a);const o=i.getUint32(r,!0);r+=4;for(let s=0;s<o;s++){const s=i.getUint32(r,!0);r+=4;const a=n.zN.decode(t.subarray(r,r+s));r+=s;const o=a.indexOf("=");if(-1===o)continue;const h=a.slice(0,o).toUpperCase(),c=a.slice(o+1);switch(e.raw??={},e.raw[h]??=c,h){case"TITLE":e.title??=c;break;case"DESCRIPTION":e.description??=c;break;case"ARTIST":e.artist??=c;break;case"ALBUM":e.album??=c;break;case"ALBUMARTIST":e.albumArtist??=c;break;case"COMMENT":e.comment??=c;break;case"LYRICS":e.lyrics??=c;break;case"TRACKNUMBER":{const t=c.split("/"),i=Number.parseInt(t[0],10),r=t[1]&&Number.parseInt(t[1],10);Number.isInteger(i)&&i>0&&(e.trackNumber??=i),r&&Number.isInteger(r)&&r>0&&(e.tracksTotal??=r)}break;case"TRACKTOTAL":{const t=Number.parseInt(c,10);Number.isInteger(t)&&t>0&&(e.tracksTotal??=t)}break;case"DISCNUMBER":{const t=c.split("/"),i=Number.parseInt(t[0],10),r=t[1]&&Number.parseInt(t[1],10);Number.isInteger(i)&&i>0&&(e.discNumber??=i),r&&Number.isInteger(r)&&r>0&&(e.discsTotal??=r)}break;case"DISCTOTAL":{const t=Number.parseInt(c,10);Number.isInteger(t)&&t>0&&(e.discsTotal??=t)}break;case"DATE":{const t=new Date(c);Number.isNaN(t.getTime())||(e.date??=t)}break;case"GENRE":e.genre??=c;break;case"METADATA_BLOCK_PICTURE":{const t=(0,n.K9)(c),i=(0,n.NK)(t),r=i.getUint32(0,!1),s=i.getUint32(4,!1),a=String.fromCharCode(...t.subarray(8,8+s)),o=i.getUint32(8+s,!1),h=n.zN.decode(t.subarray(12+s,12+s+o)),d=i.getUint32(s+o+28),l=t.subarray(s+o+32,s+o+32+d);e.images??=[],e.images.push({data:l,mimeType:a,kind:3===r?"coverFront":4===r?"coverBack":"unknown",name:void 0,description:h||void 0})}}}}},797:(t,e,i)=>{i.d(e,{$G:()=>x,AS:()=>S,Ah:()=>m,Am:()=>l,Au:()=>s,Cd:()=>T,L3:()=>v,NQ:()=>z,QK:()=>w,Vr:()=>n,Wn:()=>I,YV:()=>g,_8:()=>b,eY:()=>o,fQ:()=>p,no:()=>f,sG:()=>F,sP:()=>c,tW:()=>h,v6:()=>y,y7:()=>_,zE:()=>a});var r=i(583);const s=["avc","hevc","vp9","av1","vp8"],a=["pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be","pcm-u8","pcm-s8","ulaw","alaw"],n=["aac","opus","mp3","vorbis","flac"],o=[...n,...a],h=["webvtt"],c=[{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}],d=[{maxPictureSize:36864,maxBitrate:128e3,tier:"L",level:30},{maxPictureSize:122880,maxBitrate:15e5,tier:"L",level:60},{maxPictureSize:245760,maxBitrate:3e6,tier:"L",level:63},{maxPictureSize:552960,maxBitrate:6e6,tier:"L",level:90},{maxPictureSize:983040,maxBitrate:1e7,tier:"L",level:93},{maxPictureSize:2228224,maxBitrate:12e6,tier:"L",level:120},{maxPictureSize:2228224,maxBitrate:3e7,tier:"H",level:120},{maxPictureSize:2228224,maxBitrate:2e7,tier:"L",level:123},{maxPictureSize:2228224,maxBitrate:5e7,tier:"H",level:123},{maxPictureSize:8912896,maxBitrate:25e6,tier:"L",level:150},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:150},{maxPictureSize:8912896,maxBitrate:4e7,tier:"L",level:153},{maxPictureSize:8912896,maxBitrate:16e7,tier:"H",level:153},{maxPictureSize:8912896,maxBitrate:6e7,tier:"L",level:156},{maxPictureSize:8912896,maxBitrate:24e7,tier:"H",level:156},{maxPictureSize:35651584,maxBitrate:6e7,tier:"L",level:180},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:180},{maxPictureSize:35651584,maxBitrate:12e7,tier:"L",level:183},{maxPictureSize:35651584,maxBitrate:48e7,tier:"H",level:183},{maxPictureSize:35651584,maxBitrate:24e7,tier:"L",level:186},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:186}],l=[{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}],u=[{maxPictureSize:147456,maxBitrate:15e5,tier:"M",level:0},{maxPictureSize:278784,maxBitrate:3e6,tier:"M",level:1},{maxPictureSize:665856,maxBitrate:6e6,tier:"M",level:4},{maxPictureSize:1065024,maxBitrate:1e7,tier:"M",level:5},{maxPictureSize:2359296,maxBitrate:12e6,tier:"M",level:8},{maxPictureSize:2359296,maxBitrate:3e7,tier:"H",level:8},{maxPictureSize:2359296,maxBitrate:2e7,tier:"M",level:9},{maxPictureSize:2359296,maxBitrate:5e7,tier:"H",level:9},{maxPictureSize:8912896,maxBitrate:3e7,tier:"M",level:12},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:12},{maxPictureSize:8912896,maxBitrate:4e7,tier:"M",level:13},{maxPictureSize:8912896,maxBitrate:16e7,tier:"H",level:13},{maxPictureSize:8912896,maxBitrate:6e7,tier:"M",level:14},{maxPictureSize:8912896,maxBitrate:24e7,tier:"H",level:14},{maxPictureSize:35651584,maxBitrate:6e7,tier:"M",level:15},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:15},{maxPictureSize:35651584,maxBitrate:6e7,tier:"M",level:16},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:16},{maxPictureSize:35651584,maxBitrate:1e8,tier:"M",level:17},{maxPictureSize:35651584,maxBitrate:48e7,tier:"H",level:17},{maxPictureSize:35651584,maxBitrate:16e7,tier:"M",level:18},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:18},{maxPictureSize:35651584,maxBitrate:16e7,tier:"M",level:19},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:19}],p=(t,e,i,s)=>{if("avc"===t){const t=100,a=Math.ceil(e/16)*Math.ceil(i/16),n=c.find(t=>a<=t.maxMacroblocks&&s<=t.maxBitrate)??(0,r.Z$)(c),o=n?n.level:0;return`avc1.${t.toString(16).padStart(2,"0")}00${o.toString(16).padStart(2,"0")}`}if("hevc"===t){const t="",a=1,n="6",o=e*i,h=d.find(t=>o<=t.maxPictureSize&&s<=t.maxBitrate)??(0,r.Z$)(d),c="B0";return`hev1.${t}${a}.${n}.${h.tier}${h.level}.${c}`}if("vp8"===t)return"vp8";if("vp9"===t){const t=e*i,a="08";return`vp09.00.${(l.find(e=>t<=e.maxPictureSize&&s<=e.maxBitrate)??(0,r.Z$)(l)).level.toString().padStart(2,"0")}.${a}`}if("av1"===t){const t=0,a=e*i,n=u.find(t=>a<=t.maxPictureSize&&s<=t.maxBitrate)??(0,r.Z$)(u),o="08";return`av01.${t}.${n.level.toString().padStart(2,"0")}${n.tier}.${o}`}throw new TypeError(`Unhandled codec '${t}'.`)},f=t=>{const e=t.split("."),i=Number(e[1]),r=e[2];return[129,(i<<5)+Number(r.slice(0,-1)),(("H"===r.slice(-1)?1:0)<<7)+((8===Number(e[3])?0:1)<<6)+0+((e[4]?Number(e[4]):0)<<4)+((e[5]?Number(e[5][0]):1)<<3)+((e[5]?Number(e[5][1]):1)<<2)+(e[5]?Number(e[5][2]):0),0]},m=t=>{const{codec:e,codecDescription:i,colorSpace:s,avcCodecInfo:a,hevcCodecInfo:n,vp9CodecInfo:o,av1CodecInfo:h}=t;if("avc"===e){if((0,r.hu)(null!==t.avcType),a){const e=new Uint8Array([a.avcProfileIndication,a.profileCompatibility,a.avcLevelIndication]);return`avc${t.avcType}.${(0,r.G3)(e)}`}if(!i||i.byteLength<4)throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${t.avcType}.${(0,r.G3)(i.subarray(1,4))}`}if("hevc"===e){let t,e,s,a,o,h;if(n)t=n.generalProfileSpace,e=n.generalProfileIdc,s=(0,r.Sf)(n.generalProfileCompatibilityFlags),a=n.generalTierFlag,o=n.generalLevelIdc,h=[...n.generalConstraintIndicatorFlags];else{if(!i||i.byteLength<23)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");const n=(0,r.NK)(i),c=n.getUint8(1);t=c>>6&3,e=31&c,s=(0,r.Sf)(n.getUint32(2)),a=c>>5&1,o=n.getUint8(12),h=[];for(let t=0;t<6;t++)h.push(n.getUint8(6+t))}let c="hev1.";for(c+=["","A","B","C"][t]+e,c+=".",c+=s.toString(16).toUpperCase(),c+=".",c+=0===a?"L":"H",c+=o;h.length>0&&0===h[h.length-1];)h.pop();return h.length>0&&(c+=".",c+=h.map(t=>t.toString(16).toUpperCase()).join(".")),c}if("vp8"===e)return"vp8";if("vp9"===e){if(!o){const e=t.width*t.height;let i=(0,r.Z$)(l).level;for(const t of l)if(e<=t.maxPictureSize){i=t.level;break}return`vp09.00.${i.toString().padStart(2,"0")}.08`}let e=`vp09.${o.profile.toString().padStart(2,"0")}.${o.level.toString().padStart(2,"0")}.${o.bitDepth.toString().padStart(2,"0")}.${o.chromaSubsampling.toString().padStart(2,"0")}`;return e+=`.${o.colourPrimaries.toString().padStart(2,"0")}.${o.transferCharacteristics.toString().padStart(2,"0")}.${o.matrixCoefficients.toString().padStart(2,"0")}.${o.videoFullRangeFlag.toString().padStart(2,"0")}`,e.endsWith(".01.01.01.01.00")&&(e=e.slice(0,-15)),e}if("av1"===e){if(!h){const e=t.width*t.height;let i=(0,r.Z$)(l).level;for(const t of l)if(e<=t.maxPictureSize){i=t.level;break}return`av01.0.${i.toString().padStart(2,"0")}M.08`}const e=h.profile,i=h.level.toString().padStart(2,"0"),a=h.tier?"H":"M",n=h.bitDepth.toString().padStart(2,"0"),o=h.monochrome?"1":"0",c=100*h.chromaSubsamplingX+10*h.chromaSubsamplingY+1*(h.chromaSubsamplingX&&h.chromaSubsamplingY?h.chromaSamplePosition:0),d=s?.primaries?r.$9[s.primaries]:1,u=s?.transfer?r.V3[s.transfer]:1,p=s?.matrix?r.P0[s.matrix]:1,f=s?.fullRange?1:0;let m=`av01.${e}.${i}${a}.${n}`;return m+=`.${o}.${c.toString().padStart(3,"0")}`,m+=`.${d.toString().padStart(2,"0")}`,m+=`.${u.toString().padStart(2,"0")}`,m+=`.${p.toString().padStart(2,"0")}`,m+=`.${f}`,m.endsWith(".0.110.01.01.01.0")&&(m=m.slice(0,-17)),m}throw new TypeError(`Unhandled codec '${e}'.`)},g=t=>{const{codec:e,codecDescription:i,aacCodecInfo:r}=t;if("aac"===e){if(!r)throw new TypeError("AAC codec info must be provided.");if(r.isMpeg2)return"mp4a.67";{let t;return t=null!==r.objectType?r.objectType:b(i).objectType,`mp4a.40.${t}`}}if("mp3"===e)return"mp3";if("opus"===e)return"opus";if("vorbis"===e)return"vorbis";if("flac"===e)return"flac";if(e&&a.includes(e))return e;throw new TypeError(`Unhandled codec '${e}'.`)},y=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],_=[-1,1,2,3,4,5,6,8],b=t=>{if(!t||t.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");const e=new r.Zi(t);let i=e.readBits(5);31===i&&(i=32+e.readBits(6));const s=e.readBits(4);let a=null;15===s?a=e.readBits(24):s<y.length&&(a=y[s]);const n=e.readBits(4);let o=null;return n>=1&&n<=7&&(o=_[n]),{objectType:i,frequencyIndex:s,sampleRate:a,channelConfiguration:n,numberOfChannels:o}},w=t=>{let e=y.indexOf(t.sampleRate),i=null;-1===e&&(e=15,i=t.sampleRate);const s=_.indexOf(t.numberOfChannels);if(-1===s)throw new TypeError(`Unsupported number of channels: ${t.numberOfChannels}`);let a=13;t.objectType>=32&&(a+=6),15===e&&(a+=24);const n=Math.ceil(a/8),o=new Uint8Array(n),h=new r.Zi(o);return t.objectType<32?h.writeBits(5,t.objectType):(h.writeBits(5,31),h.writeBits(6,t.objectType-32)),h.writeBits(4,e),15===e&&h.writeBits(24,i),h.writeBits(4,s),o},v=48e3,k=/^pcm-([usf])(\d+)+(be)?$/,S=t=>{if((0,r.hu)(a.includes(t)),"ulaw"===t)return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if("alaw"===t)return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};const e=k.exec(t);let i;return(0,r.hu)(e),i="u"===e[1]?"unsigned":"s"===e[1]?"signed":"float",{dataType:i,sampleSize:Number(e[2])/8,littleEndian:"be"!==e[3],silentValue:"pcm-u8"===t?128:0}},T=t=>t.startsWith("avc1")||t.startsWith("avc3")?"avc":t.startsWith("hev1")||t.startsWith("hvc1")?"hevc":"vp8"===t?"vp8":t.startsWith("vp09")?"vp9":t.startsWith("av01")?"av1":t.startsWith("mp4a.40")||"mp4a.67"===t?"aac":"mp3"===t||"mp4a.69"===t||"mp4a.6B"===t||"mp4a.6b"===t?"mp3":"opus"===t?"opus":"vorbis"===t?"vorbis":"flac"===t?"flac":"ulaw"===t?"ulaw":"alaw"===t?"alaw":k.test(t)?t:"webvtt"===t?"webvtt":null,x=t=>"avc"===t?{avc:{format:"avc"}}:"hevc"===t?{hevc:{format:"hevc"}}:{},C=["avc1","avc3","hev1","hvc1","vp8","vp09","av01"],E=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,U=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,B=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,A=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,I=t=>{if(!t)throw new TypeError("Video chunk metadata must be provided.");if("object"!=typeof t)throw new TypeError("Video chunk metadata must be an object.");if(!t.decoderConfig)throw new TypeError("Video chunk metadata must include a decoder configuration.");if("object"!=typeof t.decoderConfig)throw new TypeError("Video chunk metadata decoder configuration must be an object.");if("string"!=typeof t.decoderConfig.codec)throw new TypeError("Video chunk metadata decoder configuration must specify a codec string.");if(!C.some(e=>t.decoderConfig.codec.startsWith(e)))throw new TypeError("Video chunk metadata decoder configuration codec string must be a valid video codec string as specified in the WebCodecs Codec Registry.");if(!Number.isInteger(t.decoderConfig.codedWidth)||t.decoderConfig.codedWidth<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).");if(!Number.isInteger(t.decoderConfig.codedHeight)||t.decoderConfig.codedHeight<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).");if(void 0!==t.decoderConfig.description&&!(0,r.n0)(t.decoderConfig.description))throw new TypeError("Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(void 0!==t.decoderConfig.colorSpace){const{colorSpace:e}=t.decoderConfig;if("object"!=typeof e)throw new TypeError("Video chunk metadata decoder configuration colorSpace, when provided, must be an object.");const i=Object.keys(r.$9);if(null!=e.primaries&&!i.includes(e.primaries))throw new TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${i.join(", ")}.`);const s=Object.keys(r.V3);if(null!=e.transfer&&!s.includes(e.transfer))throw new TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${s.join(", ")}.`);const a=Object.keys(r.P0);if(null!=e.matrix&&!a.includes(e.matrix))throw new TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${a.join(", ")}.`);if(null!=e.fullRange&&"boolean"!=typeof e.fullRange)throw new TypeError("Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean.")}if(t.decoderConfig.codec.startsWith("avc1")||t.decoderConfig.codec.startsWith("avc3")){if(!E.test(t.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for AVC must be a valid AVC codec string as specified in Section 3.4 of RFC 6381.")}else if(t.decoderConfig.codec.startsWith("hev1")||t.decoderConfig.codec.startsWith("hvc1")){if(!U.test(t.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for HEVC must be a valid HEVC codec string as specified in Section E.3 of ISO 14496-15.")}else if(t.decoderConfig.codec.startsWith("vp8")){if("vp8"!==t.decoderConfig.codec)throw new TypeError('Video chunk metadata decoder configuration codec string for VP8 must be "vp8".')}else if(t.decoderConfig.codec.startsWith("vp09")){if(!B.test(t.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for VP9 must be a valid VP9 codec string as specified in Section "Codecs Parameter String" of https://www.webmproject.org/vp9/mp4/.')}else if(t.decoderConfig.codec.startsWith("av01")&&!A.test(t.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for AV1 must be a valid AV1 codec string as specified in Section "Codecs Parameter String" of https://aomediacodec.github.io/av1-isobmff/.')},P=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm"],z=t=>{if(!t)throw new TypeError("Audio chunk metadata must be provided.");if("object"!=typeof t)throw new TypeError("Audio chunk metadata must be an object.");if(!t.decoderConfig)throw new TypeError("Audio chunk metadata must include a decoder configuration.");if("object"!=typeof t.decoderConfig)throw new TypeError("Audio chunk metadata decoder configuration must be an object.");if("string"!=typeof t.decoderConfig.codec)throw new TypeError("Audio chunk metadata decoder configuration must specify a codec string.");if(!P.some(e=>t.decoderConfig.codec.startsWith(e)))throw new TypeError("Audio chunk metadata decoder configuration codec string must be a valid audio codec string as specified in the WebCodecs Codec Registry.");if(!Number.isInteger(t.decoderConfig.sampleRate)||t.decoderConfig.sampleRate<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).");if(!Number.isInteger(t.decoderConfig.numberOfChannels)||t.decoderConfig.numberOfChannels<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).");if(void 0!==t.decoderConfig.description&&!(0,r.n0)(t.decoderConfig.description))throw new TypeError("Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(t.decoderConfig.codec.startsWith("mp4a")&&"mp4a.69"!==t.decoderConfig.codec&&"mp4a.6B"!==t.decoderConfig.codec&&"mp4a.6b"!==t.decoderConfig.codec){if(!["mp4a.40.2","mp4a.40.02","mp4a.40.5","mp4a.40.05","mp4a.40.29","mp4a.67"].includes(t.decoderConfig.codec))throw new TypeError("Audio chunk metadata decoder configuration codec string for AAC must be a valid AAC codec string as specified in https://www.w3.org/TR/webcodecs-aac-codec-registration/.")}else if(t.decoderConfig.codec.startsWith("mp3")||t.decoderConfig.codec.startsWith("mp4a")){if("mp3"!==t.decoderConfig.codec&&"mp4a.69"!==t.decoderConfig.codec&&"mp4a.6B"!==t.decoderConfig.codec&&"mp4a.6b"!==t.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for MP3 must be "mp3", "mp4a.69" or "mp4a.6B".')}else if(t.decoderConfig.codec.startsWith("opus")){if("opus"!==t.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for Opus must be "opus".');if(t.decoderConfig.description&&t.decoderConfig.description.byteLength<18)throw new TypeError("Audio chunk metadata decoder configuration description, when specified, is expected to be an Identification Header as specified in Section 5.1 of RFC 7845.")}else if(t.decoderConfig.codec.startsWith("vorbis")){if("vorbis"!==t.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".');if(!t.decoderConfig.description)throw new TypeError("Audio chunk metadata decoder configuration for Vorbis must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-vorbis-codec-registration/.")}else if(t.decoderConfig.codec.startsWith("flac")){if("flac"!==t.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for FLAC must be "flac".');const e=42;if(!t.decoderConfig.description||t.decoderConfig.description.byteLength<e)throw new TypeError("Audio chunk metadata decoder configuration for FLAC must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-flac-codec-registration/.")}else if((t.decoderConfig.codec.startsWith("pcm")||t.decoderConfig.codec.startsWith("ulaw")||t.decoderConfig.codec.startsWith("alaw"))&&!a.includes(t.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${a.join(", ")}).`)},F=t=>{if(!t)throw new TypeError("Subtitle metadata must be provided.");if("object"!=typeof t)throw new TypeError("Subtitle metadata must be an object.");if(!t.config)throw new TypeError("Subtitle metadata must include a config object.");if("object"!=typeof t.config)throw new TypeError("Subtitle metadata config must be an object.");if("string"!=typeof t.config.description)throw new TypeError("Subtitle metadata config description must be a string.")}},812:(t,e,i)=>{i.d(e,{Ms:()=>r,c6:()=>a,hg:()=>s});const r=[],s=[],a=[]},690:(t,e,i)=>{i.d(e,{bj:()=>s,ew:()=>n,n1:()=>h});var r=i(797);const s=t=>{if(!t||"object"!=typeof t)throw new TypeError("Encoding config must be an object.");if(!r.Au.includes(t.codec))throw new TypeError(`Invalid video codec '${t.codec}'. Must be one of: ${r.Au.join(", ")}.`);if(!(t.bitrate instanceof o)&&(!Number.isInteger(t.bitrate)||t.bitrate<=0))throw new TypeError("config.bitrate must be a positive integer or a quality.");if(void 0!==t.keyFrameInterval&&(!Number.isFinite(t.keyFrameInterval)||t.keyFrameInterval<0))throw new TypeError("config.keyFrameInterval, when provided, must be a non-negative number.");if(void 0!==t.sizeChangeBehavior&&!["deny","passThrough","fill","contain","cover"].includes(t.sizeChangeBehavior))throw new TypeError("config.sizeChangeBehavior, when provided, must be 'deny', 'passThrough', 'fill', 'contain' or 'cover'.");if(void 0!==t.onEncodedPacket&&"function"!=typeof t.onEncodedPacket)throw new TypeError("config.onEncodedChunk, when provided, must be a function.");if(void 0!==t.onEncoderConfig&&"function"!=typeof t.onEncoderConfig)throw new TypeError("config.onEncoderConfig, when provided, must be a function.");a(t.codec,t)},a=(t,e)=>{if(!e||"object"!=typeof e)throw new TypeError("Encoding options must be an object.");if(void 0!==e.alpha&&!["discard","keep"].includes(e.alpha))throw new TypeError("options.alpha, when provided, must be 'discard' or 'keep'.");if(void 0!==e.bitrateMode&&!["constant","variable"].includes(e.bitrateMode))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(void 0!==e.latencyMode&&!["quality","realtime"].includes(e.latencyMode))throw new TypeError("latencyMode, when provided, must be 'quality' or 'realtime'.");if(void 0!==e.fullCodecString&&"string"!=typeof e.fullCodecString)throw new TypeError("fullCodecString, when provided, must be a string.");if(void 0!==e.fullCodecString&&(0,r.Cd)(e.fullCodecString)!==t)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${t}).`);if(void 0!==e.hardwareAcceleration&&!["no-preference","prefer-hardware","prefer-software"].includes(e.hardwareAcceleration))throw new TypeError("hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(void 0!==e.scalabilityMode&&"string"!=typeof e.scalabilityMode)throw new TypeError("scalabilityMode, when provided, must be a string.");if(void 0!==e.contentHint&&"string"!=typeof e.contentHint)throw new TypeError("contentHint, when provided, must be a string.")},n=t=>{const e=t.bitrate instanceof o?t.bitrate._toVideoBitrate(t.codec,t.width,t.height):t.bitrate;return{codec:t.fullCodecString??(0,r.fQ)(t.codec,t.width,t.height,e),width:t.width,height:t.height,bitrate:e,bitrateMode:t.bitrateMode,alpha:t.alpha??"discard",framerate:t.framerate,latencyMode:t.latencyMode,hardwareAcceleration:t.hardwareAcceleration,scalabilityMode:t.scalabilityMode,contentHint:t.contentHint,...(0,r.$G)(t.codec)}};class o{constructor(t){this._factor=t}_toVideoBitrate(t,e,i){const r=e*i,s=3e6*Math.pow(r/2073600,.95)*{avc:1,hevc:.6,vp9:.6,av1:.4,vp8:1.2}[t]*this._factor;return 1e3*Math.ceil(s/1e3)}_toAudioBitrate(t){if(r.zE.includes(t)||"flac"===t)return;const e={aac:128e3,opus:64e3,mp3:16e4,vorbis:64e3}[t];if(!e)throw new Error(`Unhandled codec: ${t}`);let i=e*this._factor;return"aac"===t?i=[96e3,128e3,16e4,192e3].reduce((t,e)=>Math.abs(e-i)<Math.abs(t-i)?e:t):"opus"===t||"vorbis"===t?i=Math.max(6e3,i):"mp3"===t&&(i=[8e3,16e3,24e3,32e3,4e4,48e3,64e3,8e4,96e3,112e3,128e3,16e4,192e3,224e3,256e3,32e4].reduce((t,e)=>Math.abs(e-i)<Math.abs(t-i)?e:t)),1e3*Math.round(i/1e3)}}const h=new o(2)},176:(t,e,i)=>{i.d(e,{B1:()=>P,bJ:()=>F});var r=i(797),s=i(139);class a{constructor(t){this.input=t}}var n=i(71),o=i(583),h=i(38),c=i(370),d=i(267),l=i(481),u=i(653);class p extends a{constructor(t){super(t),this.moovSlice=null,this.currentTrack=null,this.tracks=[],this.metadataPromise=null,this.movieTimescale=-1,this.movieDurationInTimescale=-1,this.isQuickTime=!1,this.metadataTags={},this.currentMetadataKeys=null,this.isFragmented=!1,this.fragmentTrackDefaults=[],this.currentFragment=null,this.lastReadFragment=null,this.reader=t._reader}async computeDuration(){const t=await this.getTracks(),e=await Promise.all(t.map(t=>t.computeDuration()));return Math.max(0,...e)}async getTracks(){return await this.readMetadata(),this.tracks.map(t=>t.inputTrack)}async getMimeType(){await this.readMetadata();const t=await Promise.all(this.tracks.map(t=>t.inputTrack.getCodecParameterString()));return(0,c.o)({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some(t=>"video"===t.info?.type),hasAudio:this.tracks.some(t=>"audio"===t.info?.type),codecStrings:t.filter(Boolean)})}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}readMetadata(){return this.metadataPromise??=(async()=>{let t=0;for(;;){let e=this.reader.requestSliceRange(t,d.PM,d.cq);if(e instanceof Promise&&(e=await e),!e)break;const i=t,r=(0,d.mc)(e);if(!r)break;if("ftyp"===r.name){const t=(0,l.yn)(e,4);this.isQuickTime="qt "===t}else if("moov"===r.name){let t=this.reader.requestSlice(e.filePos,r.contentSize);if(t instanceof Promise&&(t=await t),!t)break;this.moovSlice=t,this.readContiguousBoxes(this.moovSlice),this.tracks.sort((t,e)=>Number(e.disposition.default)-Number(t.disposition.default));for(const t of this.tracks){const e=t.editListPreviousSegmentDurations/this.movieTimescale;t.editListOffset-=Math.round(e*t.timescale)}break}t=i+r.totalSize}if(this.isFragmented&&null!==this.reader.fileSize){let t=this.reader.requestSlice(this.reader.fileSize-4,4);t instanceof Promise&&(t=await t),(0,o.hu)(t);const e=(0,l.dd)(t),i=this.reader.fileSize-e;if(i>=0&&i<=this.reader.fileSize-d.cq){let t=this.reader.requestSliceRange(i,d.PM,d.cq);if(t instanceof Promise&&(t=await t),t){const e=(0,d.mc)(t);if(e&&"mfra"===e.name){let i=this.reader.requestSlice(t.filePos,e.contentSize);i instanceof Promise&&(i=await i),i&&this.readContiguousBoxes(i)}}}}})()}getSampleTableForTrack(t){if(t.sampleTable)return t.sampleTable;const e={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};t.sampleTable=e,(0,o.hu)(this.moovSlice);const i=this.moovSlice.slice(t.sampleTableByteOffset);if(this.currentTrack=t,this.traverseBox(i),this.currentTrack=null,"audio"===t.info?.type&&t.info.codec&&r.zE.includes(t.info.codec)&&0===e.sampleCompositionTimeOffsets.length){(0,o.hu)("audio"===t.info?.type);const i=(0,r.AS)(t.info.codec),s=[],a=[];for(let r=0;r<e.sampleToChunk.length;r++){const n=e.sampleToChunk[r],h=e.sampleToChunk[r+1],c=(h?h.startChunkIndex:e.chunkOffsets.length)-n.startChunkIndex;for(let r=0;r<c;r++){const h=n.startSampleIndex+r*n.samplesPerChunk,c=h+n.samplesPerChunk,d=(0,o.sF)(e.sampleTimingEntries,h,t=>t.startIndex),l=e.sampleTimingEntries[d],u=(0,o.sF)(e.sampleTimingEntries,c,t=>t.startIndex),p=e.sampleTimingEntries[u],f=l.startDecodeTimestamp+(h-l.startIndex)*l.delta,m=p.startDecodeTimestamp+(c-p.startIndex)*p.delta-f,g=(0,o.Z$)(s);g&&g.delta===m?g.count++:s.push({startIndex:n.startChunkIndex+r,startDecodeTimestamp:f,count:1,delta:m});const y=n.samplesPerChunk*i.sampleSize*t.info.numberOfChannels;a.push(y)}n.startSampleIndex=n.startChunkIndex,n.samplesPerChunk=1}e.sampleTimingEntries=s,e.sampleSizes=a}if(e.sampleCompositionTimeOffsets.length>0){e.presentationTimestamps=[];for(const t of e.sampleTimingEntries)for(let i=0;i<t.count;i++)e.presentationTimestamps.push({presentationTimestamp:t.startDecodeTimestamp+i*t.delta,sampleIndex:t.startIndex+i});for(const t of e.sampleCompositionTimeOffsets)for(let i=0;i<t.count;i++){const r=t.startIndex+i,s=e.presentationTimestamps[r];s&&(s.presentationTimestamp+=t.offset)}e.presentationTimestamps.sort((t,e)=>t.presentationTimestamp-e.presentationTimestamp),e.presentationTimestampIndexMap=Array(e.presentationTimestamps.length).fill(-1);for(let t=0;t<e.presentationTimestamps.length;t++)e.presentationTimestampIndexMap[e.presentationTimestamps[t].sampleIndex]=t}return e}async readFragment(t){if(this.lastReadFragment?.moofOffset===t)return this.lastReadFragment;let e=this.reader.requestSliceRange(t,d.PM,d.cq);e instanceof Promise&&(e=await e),(0,o.hu)(e);const i=(0,d.mc)(e);(0,o.hu)("moof"===i?.name);let r=this.reader.requestSlice(t,i.totalSize);r instanceof Promise&&(r=await r),(0,o.hu)(r),this.traverseBox(r);const s=this.lastReadFragment;(0,o.hu)(s&&s.moofOffset===t);for(const[,t]of s.trackData){const e=t.track,{fragmentPositionCache:i}=e;if(!t.startTimestampIsFinal){const r=e.fragmentLookupTable.find(t=>t.moofOffset===s.moofOffset);if(r)v(t,r.timestamp);else{const e=(0,o.sF)(i,s.moofOffset-1,t=>t.moofOffset);if(-1!==e){const r=i[e];v(t,r.endTimestamp)}}t.startTimestampIsFinal=!0}const r=(0,o.sF)(i,t.startTimestamp,t=>t.startTimestamp);-1!==r&&i[r].moofOffset===s.moofOffset||i.splice(r+1,0,{moofOffset:s.moofOffset,startTimestamp:t.startTimestamp,endTimestamp:t.endTimestamp})}return s}readContiguousBoxes(t){const e=t.filePos;for(;t.filePos-e<=t.length-d.PM&&this.traverseBox(t););}*iterateContiguousBoxes(t){const e=t.filePos;for(;t.filePos-e<=t.length-d.PM;){const e=t.filePos,i=(0,d.mc)(t);if(!i)break;yield{boxInfo:i,slice:t},t.filePos=e+i.totalSize}}traverseBox(t){const e=t.filePos,i=(0,d.mc)(t);if(!i)return!1;const a=t.filePos,h=e+i.totalSize;switch(i.name){case"mdia":case"minf":case"dinf":case"mfra":case"edts":case"wave":this.readContiguousBoxes(t.slice(a,i.contentSize));break;case"mvhd":{const e=(0,l.s3)(t);t.skip(3),1===e?(t.skip(16),this.movieTimescale=(0,l.dd)(t),this.movieDurationInTimescale=(0,l.Fk)(t)):(t.skip(8),this.movieTimescale=(0,l.dd)(t),this.movieDurationInTimescale=(0,l.dd)(t))}break;case"trak":{const e={id:-1,demuxer:this,inputTrack:null,disposition:{...u.CN},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,internalCodecId:null,name:null,languageCode:o.n3,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0};if(this.currentTrack=e,this.readContiguousBoxes(t.slice(a,i.contentSize)),-1!==e.id&&-1!==e.timescale&&null!==e.info)if("video"===e.info.type&&-1!==e.info.width){const t=e;e.inputTrack=new n.mC(this.input,new m(t)),this.tracks.push(e)}else if("audio"===e.info.type&&-1!==e.info.numberOfChannels){const t=e;e.inputTrack=new n.Rq(this.input,new g(t)),this.tracks.push(e)}this.currentTrack=null}break;case"tkhd":{const e=this.currentTrack;if(!e)break;const i=(0,l.s3)(t),r=!!(1&(0,l.ZC)(t));if(e.disposition.default=r,0===i)t.skip(8),e.id=(0,l.dd)(t),t.skip(4),e.durationInMovieTimescale=(0,l.dd)(t);else{if(1!==i)throw new Error(`Incorrect track header version ${i}.`);t.skip(16),e.id=(0,l.dd)(t),t.skip(4),e.durationInMovieTimescale=(0,l.Fk)(t)}t.skip(16);const s=[(0,d.bm)(t),(0,d.bm)(t),(0,d.gV)(t),(0,d.bm)(t),(0,d.bm)(t),(0,d.gV)(t),(0,d.bm)(t),(0,d.bm)(t),(0,d.gV)(t)],a=(0,o.lP)((0,o.O9)(k(s),90));(0,o.hu)(0===a||90===a||180===a||270===a),e.rotation=a}break;case"elst":{const e=this.currentTrack;if(!e)break;const i=(0,l.s3)(t);t.skip(3);let r=!1,s=0;const a=(0,l.dd)(t);for(let n=0;n<a;n++){const a=1===i?(0,l.Fk)(t):(0,l.dd)(t),n=1===i?(0,l.NN)(t):(0,l.c_)(t),o=(0,d.bm)(t);if(0!==a){if(r){console.warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit.");break}if(-1!==n){if(1!==o){console.warn("Unsupported edit list entry: media rate must be 1.");break}e.editListPreviousSegmentDurations=s,e.editListOffset=n,r=!0}else s+=a}}}break;case"mdhd":{const e=this.currentTrack;if(!e)break;const i=(0,l.s3)(t);t.skip(3),0===i?(t.skip(8),e.timescale=(0,l.dd)(t),e.durationInMediaTimescale=(0,l.dd)(t)):1===i&&(t.skip(16),e.timescale=(0,l.dd)(t),e.durationInMediaTimescale=(0,l.Fk)(t));let r=(0,l.jG)(t);if(r>0){e.languageCode="";for(let t=0;t<3;t++)e.languageCode=String.fromCharCode(96+(31&r))+e.languageCode,r>>=5;(0,o.Rh)(e.languageCode)||(e.languageCode=o.n3)}}break;case"hdlr":{const e=this.currentTrack;if(!e)break;t.skip(8);const i=(0,l.yn)(t,4);"vide"===i?e.info={type:"video",width:-1,height:-1,codec:null,codecDescription:null,colorSpace:null,avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null}:"soun"===i&&(e.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case"stbl":{const r=this.currentTrack;if(!r)break;r.sampleTableByteOffset=e,this.readContiguousBoxes(t.slice(a,i.contentSize))}break;case"stsd":{const e=this.currentTrack;if(!e)break;if(null===e.info||e.sampleTable)break;const i=(0,l.s3)(t);t.skip(3);const s=(0,l.dd)(t);for(let a=0;a<s;a++){const s=t.filePos,a=(0,d.mc)(t);if(!a)break;e.internalCodecId=a.name;const n=a.name.toLowerCase();if("video"===e.info.type)"avc1"===n||"avc3"===n?(e.info.codec="avc",e.info.avcType="avc1"===n?1:3):"hvc1"===n||"hev1"===n?e.info.codec="hevc":"vp08"===n?e.info.codec="vp8":"vp09"===n?e.info.codec="vp9":"av01"===n?e.info.codec="av1":console.warn(`Unsupported video codec (sample entry type '${a.name}').`),t.skip(24),e.info.width=(0,l.jG)(t),e.info.height=(0,l.jG)(t),t.skip(50),this.readContiguousBoxes(t.slice(t.filePos,s+a.totalSize-t.filePos));else{"mp4a"===n||("opus"===n?e.info.codec="opus":"flac"===n?e.info.codec="flac":"twos"===n||"sowt"===n||"raw "===n||"in24"===n||"in32"===n||"fl32"===n||"fl64"===n||"lpcm"===n||"ipcm"===n||"fpcm"===n||("ulaw"===n?e.info.codec="ulaw":"alaw"===n?e.info.codec="alaw":console.warn(`Unsupported audio codec (sample entry type '${a.name}').`))),t.skip(8);const o=(0,l.jG)(t);t.skip(6);let h=(0,l.jG)(t),c=(0,l.jG)(t);t.skip(4);let d=(0,l.dd)(t)/65536;if(0===i&&o>0)if(1===o)t.skip(4),c=8*(0,l.dd)(t),t.skip(8);else if(2===o){t.skip(4),d=(0,l.Ss)(t),h=(0,l.dd)(t),t.skip(4),c=(0,l.dd)(t);const i=(0,l.dd)(t);if(t.skip(8),"lpcm"===n){const t=c+7>>3,r=Boolean(1&i),s=Boolean(2&i),a=4&i?-1:0;c>0&&c<=64&&(r?32===c&&(e.info.codec=s?"pcm-f32be":"pcm-f32"):a&1<<t-1?1===t?e.info.codec="pcm-s8":2===t?e.info.codec=s?"pcm-s16be":"pcm-s16":3===t?e.info.codec=s?"pcm-s24be":"pcm-s24":4===t&&(e.info.codec=s?"pcm-s32be":"pcm-s32"):1===t&&(e.info.codec="pcm-u8")),null===e.info.codec&&console.warn("Unsupported PCM format.")}}"opus"===e.info.codec&&(d=r.L3),e.info.numberOfChannels=h,e.info.sampleRate=d,"twos"===n?8===c?e.info.codec="pcm-s8":16===c?e.info.codec="pcm-s16be":(console.warn(`Unsupported sample size ${c} for codec 'twos'.`),e.info.codec=null):"sowt"===n?8===c?e.info.codec="pcm-s8":16===c?e.info.codec="pcm-s16":(console.warn(`Unsupported sample size ${c} for codec 'sowt'.`),e.info.codec=null):"raw "===n?e.info.codec="pcm-u8":"in24"===n?e.info.codec="pcm-s24be":"in32"===n?e.info.codec="pcm-s32be":"fl32"===n?e.info.codec="pcm-f32be":"fl64"===n?e.info.codec="pcm-f64be":"ipcm"===n?e.info.codec="pcm-s16be":"fpcm"===n&&(e.info.codec="pcm-f32be"),this.readContiguousBoxes(t.slice(t.filePos,s+a.totalSize-t.filePos))}}}break;case"avcC":{const e=this.currentTrack;if(!e)break;(0,o.hu)(e.info),e.info.codecDescription=(0,l.sB)(t,i.contentSize)}break;case"hvcC":{const e=this.currentTrack;if(!e)break;(0,o.hu)(e.info),e.info.codecDescription=(0,l.sB)(t,i.contentSize)}break;case"vpcC":{const e=this.currentTrack;if(!e)break;(0,o.hu)("video"===e.info?.type),t.skip(4);const i=(0,l.s3)(t),r=(0,l.s3)(t),s=(0,l.s3)(t),a=s>>4,n=s>>1&7,h=1&s,c=(0,l.s3)(t),d=(0,l.s3)(t),u=(0,l.s3)(t);e.info.vp9CodecInfo={profile:i,level:r,bitDepth:a,chromaSubsampling:n,videoFullRangeFlag:h,colourPrimaries:c,transferCharacteristics:d,matrixCoefficients:u}}break;case"av1C":{const e=this.currentTrack;if(!e)break;(0,o.hu)("video"===e.info?.type),t.skip(1);const i=(0,l.s3)(t),r=i>>5,s=31&i,a=(0,l.s3)(t),n=a>>7,h=a>>6&1,c=a>>4&1,d=a>>3&1,u=a>>2&1,p=3&a,f=2===r&&h?a>>5&1?12:10:h?10:8;e.info.av1CodecInfo={profile:r,level:s,tier:n,bitDepth:f,monochrome:c,chromaSubsamplingX:d,chromaSubsamplingY:u,chromaSamplePosition:p}}break;case"colr":{const e=this.currentTrack;if(!e)break;if((0,o.hu)("video"===e.info?.type),"nclx"!==(0,l.yn)(t,4))break;const i=(0,l.jG)(t),r=(0,l.jG)(t),s=(0,l.jG)(t),a=Boolean(128&(0,l.s3)(t));e.info.colorSpace={primaries:o.vX[i],transfer:o.LT[r],matrix:o.KE[s],fullRange:a}}break;case"esds":{const e=this.currentTrack;if(!e)break;(0,o.hu)("audio"===e.info?.type),t.skip(4);const i=(0,l.s3)(t);(0,o.hu)(3===i),(0,d.aU)(t),t.skip(2);const s=(0,l.s3)(t),a=!!(64&s),n=!!(32&s);if(!!(128&s)&&t.skip(2),a){const e=(0,l.s3)(t);t.skip(e)}n&&t.skip(2);const h=(0,l.s3)(t);(0,o.hu)(4===h);const c=(0,d.aU)(t),u=t.filePos,p=(0,l.s3)(t);if(64===p||103===p?(e.info.codec="aac",e.info.aacCodecInfo={isMpeg2:103===p,objectType:null}):105===p||107===p?e.info.codec="mp3":221===p?e.info.codec="vorbis":console.warn(`Unsupported audio codec (objectTypeIndication ${p}) - discarding track.`),t.skip(12),c>t.filePos-u){const i=(0,l.s3)(t);(0,o.hu)(5===i);const s=(0,d.aU)(t);if(e.info.codecDescription=(0,l.sB)(t,s),"aac"===e.info.codec){const t=(0,r._8)(e.info.codecDescription);null!==t.numberOfChannels&&(e.info.numberOfChannels=t.numberOfChannels),null!==t.sampleRate&&(e.info.sampleRate=t.sampleRate)}}}break;case"enda":{const e=this.currentTrack;if(!e)break;(0,o.hu)("audio"===e.info?.type),255&(0,l.jG)(t)&&("pcm-s16be"===e.info.codec?e.info.codec="pcm-s16":"pcm-s24be"===e.info.codec?e.info.codec="pcm-s24":"pcm-s32be"===e.info.codec?e.info.codec="pcm-s32":"pcm-f32be"===e.info.codec?e.info.codec="pcm-f32":"pcm-f64be"===e.info.codec&&(e.info.codec="pcm-f64"))}break;case"pcmC":{const e=this.currentTrack;if(!e)break;(0,o.hu)("audio"===e.info?.type),t.skip(4);const i=(0,l.s3)(t),r=Boolean(1&i),s=(0,l.s3)(t);"pcm-s16be"===e.info.codec?r?16===s?e.info.codec="pcm-s16":24===s?e.info.codec="pcm-s24":32===s?e.info.codec="pcm-s32":(console.warn(`Invalid ipcm sample size ${s}.`),e.info.codec=null):16===s?e.info.codec="pcm-s16be":24===s?e.info.codec="pcm-s24be":32===s?e.info.codec="pcm-s32be":(console.warn(`Invalid ipcm sample size ${s}.`),e.info.codec=null):"pcm-f32be"===e.info.codec&&(r?32===s?e.info.codec="pcm-f32":64===s?e.info.codec="pcm-f64":(console.warn(`Invalid fpcm sample size ${s}.`),e.info.codec=null):32===s?e.info.codec="pcm-f32be":64===s?e.info.codec="pcm-f64be":(console.warn(`Invalid fpcm sample size ${s}.`),e.info.codec=null));break}case"dOps":{const e=this.currentTrack;if(!e)break;(0,o.hu)("audio"===e.info?.type),t.skip(1);const i=(0,l.s3)(t),r=(0,l.jG)(t),s=(0,l.dd)(t),a=(0,l.ww)(t),n=(0,l.s3)(t);let h;h=0!==n?(0,l.sB)(t,2+i):new Uint8Array(0);const c=new Uint8Array(19+h.byteLength),d=new DataView(c.buffer);d.setUint32(0,1332770163,!1),d.setUint32(4,1214603620,!1),d.setUint8(8,1),d.setUint8(9,i),d.setUint16(10,r,!0),d.setUint32(12,s,!0),d.setInt16(16,a,!0),d.setUint8(18,n),c.set(h,19),e.info.codecDescription=c,e.info.numberOfChannels=i}break;case"dfLa":{const e=this.currentTrack;if(!e)break;(0,o.hu)("audio"===e.info?.type),t.skip(4);const i=127,r=128,a=t.filePos;for(;t.filePos<h;){const a=(0,l.s3)(t),n=(0,l.ZC)(t);if((a&i)===s.qr.STREAMINFO){t.skip(10);const i=(0,l.dd)(t),r=i>>>12,s=1+(i>>9&7);e.info.sampleRate=r,e.info.numberOfChannels=s,t.skip(20)}else t.skip(n);if(a&r)break}const n=t.filePos;t.filePos=a;const c=(0,l.sB)(t,n-a),d=new Uint8Array(4+c.byteLength);new DataView(d.buffer).setUint32(0,1716281667,!1),d.set(c,4),e.info.codecDescription=d}break;case"stts":{const e=this.currentTrack;if(!e)break;if(!e.sampleTable)break;t.skip(4);const i=(0,l.dd)(t);let r=0,s=0;for(let a=0;a<i;a++){const i=(0,l.dd)(t),a=(0,l.dd)(t);e.sampleTable.sampleTimingEntries.push({startIndex:r,startDecodeTimestamp:s,count:i,delta:a}),r+=i,s+=i*a}}break;case"ctts":{const e=this.currentTrack;if(!e)break;if(!e.sampleTable)break;t.skip(4);const i=(0,l.dd)(t);let r=0;for(let s=0;s<i;s++){const i=(0,l.dd)(t),s=(0,l.c_)(t);e.sampleTable.sampleCompositionTimeOffsets.push({startIndex:r,count:i,offset:s}),r+=i}}break;case"stsz":{const e=this.currentTrack;if(!e)break;if(!e.sampleTable)break;t.skip(4);const i=(0,l.dd)(t),r=(0,l.dd)(t);if(0===i)for(let i=0;i<r;i++){const i=(0,l.dd)(t);e.sampleTable.sampleSizes.push(i)}else e.sampleTable.sampleSizes.push(i)}break;case"stz2":{const e=this.currentTrack;if(!e)break;if(!e.sampleTable)break;t.skip(4),t.skip(3);const i=(0,l.s3)(t),r=(0,l.dd)(t),s=(0,l.sB)(t,Math.ceil(r*i/8)),a=new o.Zi(s);for(let t=0;t<r;t++){const t=a.readBits(i);e.sampleTable.sampleSizes.push(t)}}break;case"stss":{const e=this.currentTrack;if(!e)break;if(!e.sampleTable)break;t.skip(4),e.sampleTable.keySampleIndices=[];const i=(0,l.dd)(t);for(let r=0;r<i;r++){const i=(0,l.dd)(t)-1;e.sampleTable.keySampleIndices.push(i)}0!==e.sampleTable.keySampleIndices[0]&&e.sampleTable.keySampleIndices.unshift(0)}break;case"stsc":{const e=this.currentTrack;if(!e)break;if(!e.sampleTable)break;t.skip(4);const i=(0,l.dd)(t);for(let r=0;r<i;r++){const i=(0,l.dd)(t)-1,r=(0,l.dd)(t),s=(0,l.dd)(t);e.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:i,samplesPerChunk:r,sampleDescriptionIndex:s})}let r=0;for(let t=0;t<e.sampleTable.sampleToChunk.length;t++)e.sampleTable.sampleToChunk[t].startSampleIndex=r,t<e.sampleTable.sampleToChunk.length-1&&(r+=(e.sampleTable.sampleToChunk[t+1].startChunkIndex-e.sampleTable.sampleToChunk[t].startChunkIndex)*e.sampleTable.sampleToChunk[t].samplesPerChunk)}break;case"stco":{const e=this.currentTrack;if(!e)break;if(!e.sampleTable)break;t.skip(4);const i=(0,l.dd)(t);for(let r=0;r<i;r++){const i=(0,l.dd)(t);e.sampleTable.chunkOffsets.push(i)}}break;case"co64":{const e=this.currentTrack;if(!e)break;if(!e.sampleTable)break;t.skip(4);const i=(0,l.dd)(t);for(let r=0;r<i;r++){const i=(0,l.Fk)(t);e.sampleTable.chunkOffsets.push(i)}}break;case"mvex":this.isFragmented=!0,this.readContiguousBoxes(t.slice(a,i.contentSize));break;case"mehd":{const e=(0,l.s3)(t);t.skip(3);const i=1===e?(0,l.Fk)(t):(0,l.dd)(t);this.movieDurationInTimescale=i}break;case"trex":{t.skip(4);const e=(0,l.dd)(t),i=(0,l.dd)(t),r=(0,l.dd)(t),s=(0,l.dd)(t),a=(0,l.dd)(t);this.fragmentTrackDefaults.push({trackId:e,defaultSampleDescriptionIndex:i,defaultSampleDuration:r,defaultSampleSize:s,defaultSampleFlags:a})}break;case"tfra":{const e=(0,l.s3)(t);t.skip(3);const i=(0,l.dd)(t),r=this.tracks.find(t=>t.id===i);if(!r)break;const s=(0,l.dd)(t),a=(48&s)>>4,n=(12&s)>>2,o=3&s,h=[l.s3,l.jG,l.ZC,l.dd],c=h[a],d=h[n],u=h[o],p=(0,l.dd)(t);for(let i=0;i<p;i++){const i=1===e?(0,l.Fk)(t):(0,l.dd)(t),s=1===e?(0,l.Fk)(t):(0,l.dd)(t);c(t),d(t),u(t),r.fragmentLookupTable.push({timestamp:i,moofOffset:s})}r.fragmentLookupTable.sort((t,e)=>t.timestamp-e.timestamp);for(let t=0;t<r.fragmentLookupTable.length-1;t++){const e=r.fragmentLookupTable[t],i=r.fragmentLookupTable[t+1];e.timestamp===i.timestamp&&(r.fragmentLookupTable.splice(t+1,1),t--)}}break;case"moof":this.currentFragment={moofOffset:e,moofSize:i.totalSize,implicitBaseDataOffset:e,trackData:new Map},this.readContiguousBoxes(t.slice(a,i.contentSize)),this.lastReadFragment=this.currentFragment,this.currentFragment=null;break;case"traf":if((0,o.hu)(this.currentFragment),this.readContiguousBoxes(t.slice(a,i.contentSize)),this.currentTrack){const t=this.currentFragment.trackData.get(this.currentTrack.id);if(t){const{currentFragmentState:e}=this.currentTrack;(0,o.hu)(e),null!==e.startTimestamp&&(v(t,e.startTimestamp),t.startTimestampIsFinal=!0)}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case"tfhd":{(0,o.hu)(this.currentFragment),t.skip(1);const e=(0,l.ZC)(t),i=Boolean(1&e),r=Boolean(2&e),s=Boolean(8&e),a=Boolean(16&e),n=Boolean(32&e),h=Boolean(65536&e),c=Boolean(131072&e),d=(0,l.dd)(t),u=this.tracks.find(t=>t.id===d);if(!u)break;const p=this.fragmentTrackDefaults.find(t=>t.trackId===d);this.currentTrack=u,u.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:p?.defaultSampleDescriptionIndex??null,defaultSampleDuration:p?.defaultSampleDuration??null,defaultSampleSize:p?.defaultSampleSize??null,defaultSampleFlags:p?.defaultSampleFlags??null,startTimestamp:null},i?u.currentFragmentState.baseDataOffset=(0,l.Fk)(t):c&&(u.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),r&&(u.currentFragmentState.sampleDescriptionIndex=(0,l.dd)(t)),s&&(u.currentFragmentState.defaultSampleDuration=(0,l.dd)(t)),a&&(u.currentFragmentState.defaultSampleSize=(0,l.dd)(t)),n&&(u.currentFragmentState.defaultSampleFlags=(0,l.dd)(t)),h&&(u.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{const e=this.currentTrack;if(!e)break;(0,o.hu)(e.currentFragmentState);const i=(0,l.s3)(t);t.skip(3);const r=0===i?(0,l.dd)(t):(0,l.Fk)(t);e.currentFragmentState.startTimestamp=r}break;case"trun":{const e=this.currentTrack;if(!e)break;if((0,o.hu)(this.currentFragment),(0,o.hu)(e.currentFragmentState),this.currentFragment.trackData.has(e.id)){console.warn("Can't have two trun boxes for the same track in one fragment. Ignoring...");break}const i=(0,l.s3)(t),r=(0,l.ZC)(t),s=Boolean(1&r),a=Boolean(4&r),n=Boolean(256&r),h=Boolean(512&r),c=Boolean(1024&r),d=Boolean(2048&r),u=(0,l.dd)(t);let p=e.currentFragmentState.baseDataOffset;s&&(p+=(0,l.c_)(t));let f=null;a&&(f=(0,l.dd)(t));let m=p;if(0===u){this.currentFragment.implicitBaseDataOffset=m;break}let g=0;const y={track:e,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1};this.currentFragment.trackData.set(e.id,y);for(let r=0;r<u;r++){let s,a,u;n?s=(0,l.dd)(t):((0,o.hu)(null!==e.currentFragmentState.defaultSampleDuration),s=e.currentFragmentState.defaultSampleDuration),h?a=(0,l.dd)(t):((0,o.hu)(null!==e.currentFragmentState.defaultSampleSize),a=e.currentFragmentState.defaultSampleSize),c?u=(0,l.dd)(t):((0,o.hu)(null!==e.currentFragmentState.defaultSampleFlags),u=e.currentFragmentState.defaultSampleFlags),0===r&&null!==f&&(u=f);let p=0;d&&(p=0===i?(0,l.dd)(t):(0,l.c_)(t));const _=!(65536&u);y.samples.push({presentationTimestamp:g+p,duration:s,byteOffset:m,byteSize:a,isKeyFrame:_}),m+=a,g+=s}y.presentationTimestamps=y.samples.map((t,e)=>({presentationTimestamp:t.presentationTimestamp,sampleIndex:e})).sort((t,e)=>t.presentationTimestamp-e.presentationTimestamp);for(let t=0;t<y.presentationTimestamps.length;t++){const e=y.presentationTimestamps[t],i=y.samples[e.sampleIndex];if(null===y.firstKeyFrameTimestamp&&i.isKeyFrame&&(y.firstKeyFrameTimestamp=i.presentationTimestamp),t<y.presentationTimestamps.length-1){const r=y.presentationTimestamps[t+1];i.duration=r.presentationTimestamp-e.presentationTimestamp}}const _=y.samples[y.presentationTimestamps[0].sampleIndex],b=y.samples[(0,o.Z$)(y.presentationTimestamps).sampleIndex];y.startTimestamp=_.presentationTimestamp,y.endTimestamp=b.presentationTimestamp+b.duration,this.currentFragment.implicitBaseDataOffset=m}break;case"udta":{const e=this.iterateContiguousBoxes(t.slice(a,i.contentSize));for(const{boxInfo:t,slice:i}of e){if("meta"!==t.name&&!this.currentTrack){const e=i.filePos;this.metadataTags.raw??={},"©"===t.name[0]?this.metadataTags.raw[t.name]??=(0,d.d5)(i):this.metadataTags.raw[t.name]??=(0,l.sB)(i,t.contentSize),i.filePos=e}switch(t.name){case"meta":i.skip(-t.headerSize),this.traverseBox(i);break;case"©nam":case"name":this.currentTrack?this.currentTrack.name=o.zN.decode((0,l.sB)(i,t.contentSize)):this.metadataTags.title??=(0,d.d5)(i);break;case"©des":this.currentTrack||(this.metadataTags.description??=(0,d.d5)(i));break;case"©ART":this.currentTrack||(this.metadataTags.artist??=(0,d.d5)(i));break;case"©alb":this.currentTrack||(this.metadataTags.album??=(0,d.d5)(i));break;case"albr":this.currentTrack||(this.metadataTags.albumArtist??=(0,d.d5)(i));break;case"©gen":this.currentTrack||(this.metadataTags.genre??=(0,d.d5)(i));break;case"©day":if(!this.currentTrack){const t=new Date((0,d.d5)(i));Number.isNaN(t.getTime())||(this.metadataTags.date??=t)}break;case"©cmt":this.currentTrack||(this.metadataTags.comment??=(0,d.d5)(i));break;case"©lyr":this.currentTrack||(this.metadataTags.lyrics??=(0,d.d5)(i))}}}break;case"meta":{if(this.currentTrack)break;const e=0!==(0,l.dd)(t);this.currentMetadataKeys=new Map,e?this.readContiguousBoxes(t.slice(a,i.contentSize)):this.readContiguousBoxes(t.slice(a+4,i.contentSize-4)),this.currentMetadataKeys=null}break;case"keys":{if(!this.currentMetadataKeys)break;t.skip(4);const e=(0,l.dd)(t);for(let i=0;i<e;i++){const e=(0,l.dd)(t);t.skip(4);const r=o.zN.decode((0,l.sB)(t,e-8));this.currentMetadataKeys.set(i+1,r)}}break;case"ilst":{if(!this.currentMetadataKeys)break;const e=this.iterateContiguousBoxes(t.slice(a,i.contentSize));for(const{boxInfo:t,slice:i}of e){let e=t.name;const r=(e.charCodeAt(0)<<24)+(e.charCodeAt(1)<<16)+(e.charCodeAt(2)<<8)+e.charCodeAt(3);this.currentMetadataKeys.has(r)&&(e=this.currentMetadataKeys.get(r));const s=(0,d.pF)(i);switch(this.metadataTags.raw??={},this.metadataTags.raw[e]??=s,e){case"©nam":case"titl":case"com.apple.quicktime.title":case"title":"string"==typeof s&&(this.metadataTags.title??=s);break;case"©des":case"desc":case"dscp":case"com.apple.quicktime.description":case"description":"string"==typeof s&&(this.metadataTags.description??=s);break;case"©ART":case"com.apple.quicktime.artist":case"artist":"string"==typeof s&&(this.metadataTags.artist??=s);break;case"©alb":case"albm":case"com.apple.quicktime.album":case"album":"string"==typeof s&&(this.metadataTags.album??=s);break;case"aART":case"album_artist":"string"==typeof s&&(this.metadataTags.albumArtist??=s);break;case"©cmt":case"com.apple.quicktime.comment":case"comment":"string"==typeof s&&(this.metadataTags.comment??=s);break;case"©gen":case"gnre":case"com.apple.quicktime.genre":case"genre":"string"==typeof s&&(this.metadataTags.genre??=s);break;case"©lyr":case"lyrics":"string"==typeof s&&(this.metadataTags.lyrics??=s);break;case"©day":case"rldt":case"com.apple.quicktime.creationdate":case"date":if("string"==typeof s){const t=new Date(s);Number.isNaN(t.getTime())||(this.metadataTags.date??=t)}break;case"covr":case"com.apple.quicktime.artwork":s instanceof u.jC?(this.metadataTags.images??=[],this.metadataTags.images.push({data:s.data,kind:"coverFront",mimeType:s.mimeType})):s instanceof Uint8Array&&(this.metadataTags.images??=[],this.metadataTags.images.push({data:s,kind:"coverFront",mimeType:"image/*"}));break;case"track":if("string"==typeof s){const t=s.split("/"),e=Number.parseInt(t[0],10),i=t[1]&&Number.parseInt(t[1],10);Number.isInteger(e)&&e>0&&(this.metadataTags.trackNumber??=e),i&&Number.isInteger(i)&&i>0&&(this.metadataTags.tracksTotal??=i)}break;case"trkn":if(s instanceof Uint8Array&&s.length>=6){const t=(0,o.NK)(s),e=t.getUint16(2,!1),i=t.getUint16(4,!1);e>0&&(this.metadataTags.trackNumber??=e),i>0&&(this.metadataTags.tracksTotal??=i)}break;case"disc":case"disk":if(s instanceof Uint8Array&&s.length>=6){const t=(0,o.NK)(s),e=t.getUint16(2,!1),i=t.getUint16(4,!1);e>0&&(this.metadataTags.discNumber??=e),i>0&&(this.metadataTags.discsTotal??=i)}}}}}return t.filePos=h,!0}}class f{constructor(t){this.internalTrack=t,this.packetToSampleIndex=new WeakMap,this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){const t=this.internalTrack.demuxer,e=this.internalTrack.inputTrack.type;let i=0;for(const r of t.tracks)if(r.inputTrack.type===e&&i++,r===this.internalTrack)break;return i}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.internalCodecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}getDisposition(){return this.internalTrack.disposition}async computeDuration(){const t=await this.getPacket(1/0,{metadataOnly:!0});return(t?.timestamp??0)+(t?.duration??0)}async getFirstTimestamp(){const t=await this.getFirstPacket({metadataOnly:!0});return t?.timestamp??0}async getFirstPacket(t){const e=await this.fetchPacketForSampleIndex(0,t);return e||!this.internalTrack.demuxer.isFragmented?e:this.performFragmentedLookup(null,t=>t.trackData.get(this.internalTrack.id)?{sampleIndex:0,correctSampleFound:!0}:{sampleIndex:-1,correctSampleFound:!1},-1/0,1/0,t)}mapTimestampIntoTimescale(t){return(0,o.F3)(t*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(t,e){const i=this.mapTimestampIntoTimescale(t),r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),s=y(r,i),a=await this.fetchPacketForSampleIndex(s,e);return S(r)&&this.internalTrack.demuxer.isFragmented?this.performFragmentedLookup(null,t=>{const e=t.trackData.get(this.internalTrack.id);if(!e)return{sampleIndex:-1,correctSampleFound:!1};const r=(0,o.sF)(e.presentationTimestamps,i,t=>t.presentationTimestamp);return{sampleIndex:-1!==r?e.presentationTimestamps[r].sampleIndex:-1,correctSampleFound:-1!==r&&i<e.endTimestamp}},i,i,e):a}async getNextPacket(t,e){const i=this.packetToSampleIndex.get(t);if(void 0!==i)return this.fetchPacketForSampleIndex(i+1,e);const r=this.packetToFragmentLocation.get(t);if(void 0===r)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(r.fragment,t=>{if(t===r.fragment){const e=t.trackData.get(this.internalTrack.id);if(r.sampleIndex+1<e.samples.length)return{sampleIndex:r.sampleIndex+1,correctSampleFound:!0}}else if(t.trackData.get(this.internalTrack.id))return{sampleIndex:0,correctSampleFound:!0};return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,e)}async getKeyPacket(t,e){const i=this.mapTimestampIntoTimescale(t),r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),s=_(r,i),a=await this.fetchPacketForSampleIndex(s,e);return S(r)&&this.internalTrack.demuxer.isFragmented?this.performFragmentedLookup(null,t=>{const e=t.trackData.get(this.internalTrack.id);if(!e)return{sampleIndex:-1,correctSampleFound:!1};const r=(0,o.qr)(e.presentationTimestamps,t=>e.samples[t.sampleIndex].isKeyFrame&&t.presentationTimestamp<=i);return{sampleIndex:-1!==r?e.presentationTimestamps[r].sampleIndex:-1,correctSampleFound:-1!==r&&i<e.endTimestamp}},i,i,e):a}async getNextKeyPacket(t,e){const i=this.packetToSampleIndex.get(t);if(void 0!==i){const t=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),r=w(t,i);return this.fetchPacketForSampleIndex(r,e)}const r=this.packetToFragmentLocation.get(t);if(void 0===r)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(r.fragment,t=>{if(t===r.fragment){const e=t.trackData.get(this.internalTrack.id).samples.findIndex((t,e)=>t.isKeyFrame&&e>r.sampleIndex);if(-1!==e)return{sampleIndex:e,correctSampleFound:!0}}else{const e=t.trackData.get(this.internalTrack.id);if(e&&null!==e.firstKeyFrameTimestamp){const t=e.samples.findIndex(t=>t.isKeyFrame);return(0,o.hu)(-1!==t),{sampleIndex:t,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,e)}async fetchPacketForSampleIndex(t,e){if(-1===t)return null;const i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),r=b(i,t);if(!r)return null;let s;if(e.metadataOnly)s=h.L;else{let t=this.internalTrack.demuxer.reader.requestSlice(r.sampleOffset,r.sampleSize);t instanceof Promise&&(t=await t),(0,o.hu)(t),s=(0,l.sB)(t,r.sampleSize)}const a=(r.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,n=r.duration/this.internalTrack.timescale,c=new h.H(s,r.isKeyFrame?"key":"delta",a,n,t,r.sampleSize);return this.packetToSampleIndex.set(c,t),c}async fetchPacketInFragment(t,e,i){if(-1===e)return null;const r=t.trackData.get(this.internalTrack.id).samples[e];let s;if((0,o.hu)(r),i.metadataOnly)s=h.L;else{let t=this.internalTrack.demuxer.reader.requestSlice(r.byteOffset,r.byteSize);t instanceof Promise&&(t=await t),(0,o.hu)(t),s=(0,l.sB)(t,r.byteSize)}const a=(r.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,n=r.duration/this.internalTrack.timescale,c=new h.H(s,r.isKeyFrame?"key":"delta",a,n,t.moofOffset+e,r.byteSize);return this.packetToFragmentLocation.set(c,{fragment:t,sampleIndex:e}),c}async performFragmentedLookup(t,e,i,r,s){const a=this.internalTrack.demuxer;let n=null,h=null,c=-1;if(t){const{sampleIndex:i,correctSampleFound:r}=e(t);if(r)return this.fetchPacketInFragment(t,i,s);-1!==i&&(h=t,c=i)}const l=(0,o.sF)(this.internalTrack.fragmentLookupTable,i,t=>t.timestamp),u=-1!==l?this.internalTrack.fragmentLookupTable[l]:null,p=(0,o.sF)(this.internalTrack.fragmentPositionCache,i,t=>t.startTimestamp),f=-1!==p?this.internalTrack.fragmentPositionCache[p]:null,m=Math.max(u?.moofOffset??0,f?.moofOffset??0)||null;let g;for(t?null===m||t.moofOffset>=m?(g=t.moofOffset+t.moofSize,n=t):g=m:g=m??0;;){if(n){const t=n.trackData.get(this.internalTrack.id);if(t&&t.startTimestamp>r)break}let t=a.reader.requestSliceRange(g,d.PM,d.cq);if(t instanceof Promise&&(t=await t),!t)break;const i=g,o=(0,d.mc)(t);if(!o)break;if("moof"===o.name){n=await a.readFragment(i);const{sampleIndex:t,correctSampleFound:r}=e(n);if(r)return this.fetchPacketInFragment(n,t,s);-1!==t&&(h=n,c=t)}g=i+o.totalSize}if(u&&(!h||h.moofOffset<u.moofOffset)){const t=this.internalTrack.fragmentLookupTable[l-1];(0,o.hu)(!t||t.timestamp<u.timestamp);const i=t?.timestamp??-1/0;return this.performFragmentedLookup(null,e,i,r,s)}return h?this.fetchPacketInFragment(h,c,s):null}}class m extends f{constructor(t){super(t),this.decoderConfigPromise=null,this.internalTrack=t}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getRotation(){return this.internalTrack.rotation}async getColorSpace(){return{primaries:this.internalTrack.info.colorSpace?.primaries,transfer:this.internalTrack.info.colorSpace?.transfer,matrix:this.internalTrack.info.colorSpace?.matrix,fullRange:this.internalTrack.info.colorSpace?.fullRange}}async canBeTransparent(){return!1}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{if("vp9"!==this.internalTrack.info.codec||this.internalTrack.info.vp9CodecInfo){if("av1"===this.internalTrack.info.codec&&!this.internalTrack.info.av1CodecInfo){const t=await this.getFirstPacket({});this.internalTrack.info.av1CodecInfo=t&&(0,s.$W)(t.data)}}else{const t=await this.getFirstPacket({});this.internalTrack.info.vp9CodecInfo=t&&(0,s.Al)(t.data)}return{codec:(0,r.Ah)(this.internalTrack.info),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0}})():null}}class g extends f{constructor(t){super(t),this.decoderConfig=null,this.internalTrack=t}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfig??={codec:(0,r.YV)(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}}const y=(t,e)=>{if(t.presentationTimestamps){const i=(0,o.sF)(t.presentationTimestamps,e,t=>t.presentationTimestamp);return-1===i?-1:t.presentationTimestamps[i].sampleIndex}{const i=(0,o.sF)(t.sampleTimingEntries,e,t=>t.startDecodeTimestamp);if(-1===i)return-1;const r=t.sampleTimingEntries[i];return r.startIndex+Math.min(Math.floor((e-r.startDecodeTimestamp)/r.delta),r.count-1)}},_=(t,e)=>{if(!t.keySampleIndices)return y(t,e);if(t.presentationTimestamps){const i=(0,o.sF)(t.presentationTimestamps,e,t=>t.presentationTimestamp);if(-1===i)return-1;for(let e=i;e>=0;e--){const i=t.presentationTimestamps[e].sampleIndex;if(-1!==(0,o.Jy)(t.keySampleIndices,i,t=>t))return i}return-1}{const i=y(t,e),r=(0,o.sF)(t.keySampleIndices,i,t=>t);return t.keySampleIndices[r]??-1}},b=(t,e)=>{const i=(0,o.sF)(t.sampleTimingEntries,e,t=>t.startIndex),r=t.sampleTimingEntries[i];if(!r||r.startIndex+r.count<=e)return null;let s=r.startDecodeTimestamp+(e-r.startIndex)*r.delta;const a=(0,o.sF)(t.sampleCompositionTimeOffsets,e,t=>t.startIndex),n=t.sampleCompositionTimeOffsets[a];n&&e-n.startIndex<n.count&&(s+=n.offset);const h=t.sampleSizes[Math.min(e,t.sampleSizes.length-1)],c=(0,o.sF)(t.sampleToChunk,e,t=>t.startSampleIndex),d=t.sampleToChunk[c];(0,o.hu)(d);const l=d.startChunkIndex+Math.floor((e-d.startSampleIndex)/d.samplesPerChunk),u=t.chunkOffsets[l],p=d.startSampleIndex+(l-d.startChunkIndex)*d.samplesPerChunk;let f=0,m=u;if(1===t.sampleSizes.length)m+=h*(e-p),f+=h*d.samplesPerChunk;else for(let i=p;i<p+d.samplesPerChunk;i++){const r=t.sampleSizes[i];i<e&&(m+=r),f+=r}let g=r.delta;if(t.presentationTimestamps){const i=t.presentationTimestampIndexMap[e];(0,o.hu)(void 0!==i),i<t.presentationTimestamps.length-1&&(g=t.presentationTimestamps[i+1].presentationTimestamp-s)}return{presentationTimestamp:s,duration:g,sampleOffset:m,sampleSize:h,chunkOffset:u,chunkSize:f,isKeyFrame:!t.keySampleIndices||-1!==(0,o.Jy)(t.keySampleIndices,e,t=>t)}},w=(t,e)=>{if(!t.keySampleIndices)return e+1;const i=(0,o.sF)(t.keySampleIndices,e,t=>t);return t.keySampleIndices[i+1]??-1},v=(t,e)=>{t.startTimestamp+=e,t.endTimestamp+=e;for(const i of t.samples)i.presentationTimestamp+=e;for(const i of t.presentationTimestamps)i.presentationTimestamp+=e},k=t=>{const[e,,,i]=t,r=Math.hypot(e,i),s=e/r,a=i/r,n=-Math.atan2(a,s)*(180/Math.PI);return Number.isFinite(n)?n:0},S=t=>0===t.sampleSizes.length;var T,x,C,E,U,B;!function(t){t[t.EBML=440786851]="EBML",t[t.EBMLVersion=17030]="EBMLVersion",t[t.EBMLReadVersion=17143]="EBMLReadVersion",t[t.EBMLMaxIDLength=17138]="EBMLMaxIDLength",t[t.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",t[t.DocType=17026]="DocType",t[t.DocTypeVersion=17031]="DocTypeVersion",t[t.DocTypeReadVersion=17029]="DocTypeReadVersion",t[t.Void=236]="Void",t[t.Segment=408125543]="Segment",t[t.SeekHead=290298740]="SeekHead",t[t.Seek=19899]="Seek",t[t.SeekID=21419]="SeekID",t[t.SeekPosition=21420]="SeekPosition",t[t.Duration=17545]="Duration",t[t.Info=357149030]="Info",t[t.TimestampScale=2807729]="TimestampScale",t[t.MuxingApp=19840]="MuxingApp",t[t.WritingApp=22337]="WritingApp",t[t.Tracks=374648427]="Tracks",t[t.TrackEntry=174]="TrackEntry",t[t.TrackNumber=215]="TrackNumber",t[t.TrackUID=29637]="TrackUID",t[t.TrackType=131]="TrackType",t[t.FlagEnabled=185]="FlagEnabled",t[t.FlagDefault=136]="FlagDefault",t[t.FlagForced=21930]="FlagForced",t[t.FlagOriginal=21934]="FlagOriginal",t[t.FlagHearingImpaired=21931]="FlagHearingImpaired",t[t.FlagVisualImpaired=21932]="FlagVisualImpaired",t[t.FlagCommentary=21935]="FlagCommentary",t[t.FlagLacing=156]="FlagLacing",t[t.Name=21358]="Name",t[t.Language=2274716]="Language",t[t.LanguageBCP47=2274717]="LanguageBCP47",t[t.CodecID=134]="CodecID",t[t.CodecPrivate=25506]="CodecPrivate",t[t.CodecDelay=22186]="CodecDelay",t[t.SeekPreRoll=22203]="SeekPreRoll",t[t.DefaultDuration=2352003]="DefaultDuration",t[t.Video=224]="Video",t[t.PixelWidth=176]="PixelWidth",t[t.PixelHeight=186]="PixelHeight",t[t.AlphaMode=21440]="AlphaMode",t[t.Audio=225]="Audio",t[t.SamplingFrequency=181]="SamplingFrequency",t[t.Channels=159]="Channels",t[t.BitDepth=25188]="BitDepth",t[t.SimpleBlock=163]="SimpleBlock",t[t.BlockGroup=160]="BlockGroup",t[t.Block=161]="Block",t[t.BlockAdditions=30113]="BlockAdditions",t[t.BlockMore=166]="BlockMore",t[t.BlockAdditional=165]="BlockAdditional",t[t.BlockAddID=238]="BlockAddID",t[t.BlockDuration=155]="BlockDuration",t[t.ReferenceBlock=251]="ReferenceBlock",t[t.Cluster=524531317]="Cluster",t[t.Timestamp=231]="Timestamp",t[t.Cues=475249515]="Cues",t[t.CuePoint=187]="CuePoint",t[t.CueTime=179]="CueTime",t[t.CueTrackPositions=183]="CueTrackPositions",t[t.CueTrack=247]="CueTrack",t[t.CueClusterPosition=241]="CueClusterPosition",t[t.Colour=21936]="Colour",t[t.MatrixCoefficients=21937]="MatrixCoefficients",t[t.TransferCharacteristics=21946]="TransferCharacteristics",t[t.Primaries=21947]="Primaries",t[t.Range=21945]="Range",t[t.Projection=30320]="Projection",t[t.ProjectionType=30321]="ProjectionType",t[t.ProjectionPoseRoll=30325]="ProjectionPoseRoll",t[t.Attachments=423732329]="Attachments",t[t.AttachedFile=24999]="AttachedFile",t[t.FileDescription=18046]="FileDescription",t[t.FileName=18030]="FileName",t[t.FileMediaType=18016]="FileMediaType",t[t.FileData=18012]="FileData",t[t.FileUID=18094]="FileUID",t[t.Chapters=272869232]="Chapters",t[t.Tags=307544935]="Tags",t[t.Tag=29555]="Tag",t[t.Targets=25536]="Targets",t[t.TargetTypeValue=26826]="TargetTypeValue",t[t.TargetType=25546]="TargetType",t[t.TagTrackUID=25541]="TagTrackUID",t[t.TagEditionUID=25545]="TagEditionUID",t[t.TagChapterUID=25540]="TagChapterUID",t[t.TagAttachmentUID=25542]="TagAttachmentUID",t[t.SimpleTag=26568]="SimpleTag",t[t.TagName=17827]="TagName",t[t.TagLanguage=17530]="TagLanguage",t[t.TagString=17543]="TagString",t[t.TagBinary=17541]="TagBinary",t[t.ContentEncodings=28032]="ContentEncodings",t[t.ContentEncoding=25152]="ContentEncoding",t[t.ContentEncodingOrder=20529]="ContentEncodingOrder",t[t.ContentEncodingScope=20530]="ContentEncodingScope",t[t.ContentCompression=20532]="ContentCompression",t[t.ContentCompAlgo=16980]="ContentCompAlgo",t[t.ContentCompSettings=16981]="ContentCompSettings",t[t.ContentEncryption=20533]="ContentEncryption"}(T||(T={})),T.EBML,T.Segment,T.SeekHead,T.Info,T.Cluster,T.Tracks,T.Cues,T.Attachments,T.Chapters,T.Tags,function(t){t[t.None=0]="None",t[t.Xiph=1]="Xiph",t[t.FixedSize=2]="FixedSize",t[t.Ebml=3]="Ebml"}(x||(x={})),function(t){t[t.Block=1]="Block",t[t.Private=2]="Private",t[t.Next=4]="Next"}(C||(C={})),function(t){t[t.Zlib=0]="Zlib",t[t.Bzlib=1]="Bzlib",t[t.lzo1x=2]="lzo1x",t[t.HeaderStripping=3]="HeaderStripping"}(E||(E={})),T.SeekHead,T.Info,T.Tracks,T.Cues,function(t){t[t.Unsynchronisation=128]="Unsynchronisation",t[t.ExtendedHeader=64]="ExtendedHeader",t[t.ExperimentalIndicator=32]="ExperimentalIndicator",t[t.Footer=16]="Footer"}(U||(U={})),function(t){t[t.ISO_8859_1=0]="ISO_8859_1",t[t.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",t[t.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",t[t.UTF_8=3]="UTF_8"}(B||(B={}));const A=new Uint32Array(256);for(let t=0;t<256;t++){let e=t<<24;for(let t=0;t<8;t++)e=2147483648&e?e<<1^79764919:e<<1;A[t]=e>>>0&4294967295}var I;!function(t){t[t.PCM=1]="PCM",t[t.IEEE_FLOAT=3]="IEEE_FLOAT",t[t.ALAW=6]="ALAW",t[t.MULAW=7]="MULAW",t[t.EXTENSIBLE=65534]="EXTENSIBLE"}(I||(I={})),i(273);class P{}class z extends P{async _getMajorBrand(t){let e=t._reader.requestSlice(0,12);return e instanceof Promise&&(e=await e),e?(e.skip(4),"ftyp"!==(0,l.yn)(e,4)?null:(0,l.yn)(e,4)):null}_createDemuxer(t){return new p(t)}}const F=new class extends z{async _canReadInput(t){const e=await this._getMajorBrand(t);return!!e&&"qt "!==e}get name(){return"MP4"}get mimeType(){return"video/mp4"}}},71:(t,e,i)=>{i.d(e,{Rq:()=>d,mC:()=>c,u:()=>h});var r=i(139),s=i(812),a=i(291),n=i(583),o=i(38);class h{constructor(t,e){this.input=t,this._backing=e}isVideoTrack(){return this instanceof c}isAudioTrack(){return this instanceof d}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}get internalCodecId(){return this._backing.getInternalCodecId()}get languageCode(){return this._backing.getLanguageCode()}get name(){return this._backing.getName()}get timeResolution(){return this._backing.getTimeResolution()}get disposition(){return this._backing.getDisposition()}getFirstTimestamp(){return this._backing.getFirstTimestamp()}computeDuration(){return this._backing.computeDuration()}async computePacketStats(t=1/0){const e=new a.a6(this);let i=1/0,r=-1/0,s=0,n=0;for await(const a of e.packets(void 0,void 0,{metadataOnly:!0})){if(s>=t&&a.timestamp>=r)break;i=Math.min(i,a.timestamp),r=Math.max(r,a.timestamp+a.duration),s++,n+=a.byteLength}return{packetCount:s,averagePacketRate:s?Number((s/(r-i)).toPrecision(16)):0,averageBitrate:s?Number((8*n/(r-i)).toPrecision(16)):0}}}class c extends h{constructor(t,e){super(t,e),this._backing=e}get type(){return"video"}get codec(){return this._backing.getCodec()}get codedWidth(){return this._backing.getCodedWidth()}get codedHeight(){return this._backing.getCodedHeight()}get rotation(){return this._backing.getRotation()}get displayWidth(){return this._backing.getRotation()%180==0?this._backing.getCodedWidth():this._backing.getCodedHeight()}get displayHeight(){return this._backing.getRotation()%180==0?this._backing.getCodedHeight():this._backing.getCodedWidth()}getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){const t=await this._backing.getColorSpace();return"bt2020"===t.primaries||"smpte432"===t.primaries||"pg"===t.transfer||"hlg"===t.transfer||"bt2020-ncl"===t.matrix}canBeTransparent(){return this._backing.canBeTransparent()}getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){const t=await this._backing.getDecoderConfig();return t?.codec??null}async canDecode(){try{const t=await this._backing.getDecoderConfig();if(!t)return!1;const e=this._backing.getCodec();return(0,n.hu)(null!==e),!!s.Ms.some(i=>i.supports(e,t))||"undefined"!=typeof VideoDecoder&&!0===(await VideoDecoder.isConfigSupported(t)).supported}catch(t){return console.error("Error during decodability check:",t),!1}}async determinePacketType(t){if(!(t instanceof o.H))throw new TypeError("packet must be an EncodedPacket.");if(t.isMetadataOnly)throw new TypeError("packet must not be metadata-only to determine its type.");if(null===this.codec)return null;const e=await this.getDecoderConfig();return(0,n.hu)(e),(0,r.RO)(this.codec,e,t.data)}}class d extends h{constructor(t,e){super(t,e),this._backing=e}get type(){return"audio"}get codec(){return this._backing.getCodec()}get numberOfChannels(){return this._backing.getNumberOfChannels()}get sampleRate(){return this._backing.getSampleRate()}getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){const t=await this._backing.getDecoderConfig();return t?.codec??null}async canDecode(){try{const t=await this._backing.getDecoderConfig();if(!t)return!1;const e=this._backing.getCodec();return(0,n.hu)(null!==e),!!s.hg.some(i=>i.supports(e,t))||(!!t.codec.startsWith("pcm-")||"undefined"!=typeof AudioDecoder&&!0===(await AudioDecoder.isConfigSupported(t)).supported)}catch(t){return console.error("Error during decodability check:",t),!1}}async determinePacketType(t){if(!(t instanceof o.H))throw new TypeError("packet must be an EncodedPacket.");return null===this.codec?null:"key"}}},700:(t,e,i)=>{i.d(e,{I:()=>o,x:()=>h});var r=i(176),s=i(583),a=i(481),n=i(219);(0,s.un)();class o{get disposed(){return this._disposed}constructor(t){if(this._demuxerPromise=null,this._format=null,this._disposed=!1,!t||"object"!=typeof t)throw new TypeError("options must be an object.");if(!Array.isArray(t.formats)||t.formats.some(t=>!(t instanceof r.B1)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(t.source instanceof n.Hw))throw new TypeError("options.source must be a Source.");if(t.source._disposed)throw new Error("options.source must not be disposed.");this._formats=t.formats,this._source=t.source,this._reader=new a.Ej(t.source)}_getDemuxer(){return this._demuxerPromise??=(async()=>{this._reader.fileSize=await this._source.getSizeOrNull();for(const t of this._formats)if(await t._canReadInput(this))return this._format=t,t._createDemuxer(this);throw new Error("Input has an unsupported or unrecognizable format.")})()}get source(){return this._source}async getFormat(){return await this._getDemuxer(),(0,s.hu)(this._format),this._format}async computeDuration(){return(await this._getDemuxer()).computeDuration()}async getFirstTimestamp(){const t=await this.getTracks();if(0===t.length)return 0;const e=await Promise.all(t.map(t=>t.getFirstTimestamp()));return Math.min(...e)}async getTracks(){return(await this._getDemuxer()).getTracks()}async getVideoTracks(){return(await this.getTracks()).filter(t=>t.isVideoTrack())}async getAudioTracks(){return(await this.getTracks()).filter(t=>t.isAudioTrack())}async getPrimaryVideoTrack(){return(await this.getTracks()).find(t=>t.isVideoTrack())??null}async getPrimaryAudioTrack(){return(await this.getTracks()).find(t=>t.isAudioTrack())??null}async getMimeType(){return(await this._getDemuxer()).getMimeType()}async getMetadataTags(){return(await this._getDemuxer()).getMetadataTags()}dispose(){this._disposed||(this._disposed=!0,this._source._disposed=!0,this._source._dispose())}[Symbol.dispose](){this.dispose()}}class h extends Error{constructor(t="Input has been disposed."){super(t),this.name="InputDisposedError"}}},370:(t,e,i)=>{i.d(e,{o:()=>r});const r=t=>{let e=(t.hasVideo?"video/":t.hasAudio?"audio/":"application/")+(t.isQuickTime?"quicktime":"mp4");return t.codecStrings.length>0&&(e+=`; codecs="${[...new Set(t.codecStrings)].join(", ")}"`),e}},267:(t,e,i)=>{i.d(e,{PM:()=>n,aU:()=>l,bm:()=>c,cq:()=>o,d5:()=>u,gV:()=>d,mc:()=>h,pF:()=>p});var r=i(653),s=i(583),a=i(481);const n=8,o=16,h=t=>{let e=(0,a.dd)(t);const i=(0,a.yn)(t,4);let r=8;1===e&&(e=(0,a.Fk)(t),r=16);const s=e-r;return s<0?null:{name:i,totalSize:e,headerSize:r,contentSize:s}},c=t=>(0,a.c_)(t)/65536,d=t=>(0,a.c_)(t)/1073741824,l=t=>{let e=0;for(let i=0;i<4;i++){e<<=7;const i=(0,a.s3)(t);if(e|=127&i,!(128&i))break}return e},u=t=>{let e=(0,a.jG)(t);return t.skip(2),e=Math.min(e,t.remainingLength),s.zN.decode((0,a.sB)(t,e))},p=t=>{const e=h(t);if(!e||"data"!==e.name)return null;if(t.remainingLength<8)return null;const i=(0,a.dd)(t);t.skip(4);const n=(0,a.sB)(t,e.contentSize-8);switch(i){case 1:return s.zN.decode(n);case 2:return new TextDecoder("utf-16be").decode(n);case 13:return new r.jC(n,"image/jpeg");case 14:return new r.jC(n,"image/png");case 27:return new r.jC(n,"image/bmp");default:return n}}},291:(t,e,i)=>{i.d(e,{a6:()=>p,dL:()=>b});var r=i(139),s=i(812),a=i(700),n=i(71),o=i(583),h=i(38),c=i(348);const d=t=>{if(!t||"object"!=typeof t)throw new TypeError("options must be an object.");if(void 0!==t.metadataOnly&&"boolean"!=typeof t.metadataOnly)throw new TypeError("options.metadataOnly, when defined, must be a boolean.");if(void 0!==t.verifyKeyPackets&&"boolean"!=typeof t.verifyKeyPackets)throw new TypeError("options.verifyKeyPackets, when defined, must be a boolean.");if(t.verifyKeyPackets&&t.metadataOnly)throw new TypeError("options.verifyKeyPackets and options.metadataOnly cannot be enabled together.")},l=t=>{if(!(0,o.hj)(t))throw new TypeError("timestamp must be a number.")},u=(t,e,i)=>i.verifyKeyPackets?e.then(async e=>{if(!e||"delta"===e.type)return e;const i=await t.determinePacketType(e);return i&&(e.type=i),e}):e;class p{constructor(t){if(!(t instanceof n.u))throw new TypeError("track must be an InputTrack.");this._track=t}getFirstPacket(t={}){if(d(t),this._track.input._disposed)throw new a.x;return u(this._track,this._track._backing.getFirstPacket(t),t)}getPacket(t,e={}){if(l(t),d(e),this._track.input._disposed)throw new a.x;return u(this._track,this._track._backing.getPacket(t,e),e)}getNextPacket(t,e={}){if(!(t instanceof h.H))throw new TypeError("packet must be an EncodedPacket.");if(d(e),this._track.input._disposed)throw new a.x;return u(this._track,this._track._backing.getNextPacket(t,e),e)}async getKeyPacket(t,e={}){if(l(t),d(e),this._track.input._disposed)throw new a.x;if(!e.verifyKeyPackets)return this._track._backing.getKeyPacket(t,e);const i=await this._track._backing.getKeyPacket(t,e);return i?((0,o.hu)("key"===i.type),"delta"===await this._track.determinePacketType(i)?this.getKeyPacket(i.timestamp-1/this._track.timeResolution,e):i):i}async getNextKeyPacket(t,e={}){if(!(t instanceof h.H))throw new TypeError("packet must be an EncodedPacket.");if(d(e),this._track.input._disposed)throw new a.x;if(!e.verifyKeyPackets)return this._track._backing.getNextKeyPacket(t,e);const i=await this._track._backing.getNextKeyPacket(t,e);return i?((0,o.hu)("key"===i.type),"delta"===await this._track.determinePacketType(i)?this.getNextKeyPacket(i,e):i):i}packets(t,e,i={}){if(void 0!==t&&!(t instanceof h.H))throw new TypeError("startPacket must be an EncodedPacket.");if(void 0!==t&&t.isMetadataOnly&&!i?.metadataOnly)throw new TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(void 0!==e&&!(e instanceof h.H))throw new TypeError("endPacket must be an EncodedPacket.");if(d(i),this._track.input._disposed)throw new a.x;const r=[];let{promise:s,resolve:n}=(0,o.Bw)(),{promise:c,resolve:l}=(0,o.Bw)(),u=!1,p=!1,f=null;const m=[];(async()=>{let a=t??await this.getFirstPacket(i);for(;a&&!p&&!this._track.input._disposed&&!(e&&a.sequenceNumber>=e?.sequenceNumber);)r.length>Math.max(2,m.length)?(({promise:c,resolve:l}=(0,o.Bw)()),await c):(r.push(a),n(),({promise:s,resolve:n}=(0,o.Bw)()),a=await this.getNextPacket(a,i));u=!0,n()})().catch(t=>{f||(f=t,n())});const g=this._track;return{async next(){for(;;){if(g.input._disposed)throw new a.x;if(p)return{value:void 0,done:!0};if(f)throw f;if(r.length>0){const t=r.shift(),e=performance.now();for(m.push(e);m.length>0&&e-m[0]>=1e3;)m.shift();return l(),{value:t,done:!1}}if(u)return{value:void 0,done:!0};await s}},return:async()=>(p=!0,l(),n(),{value:void 0,done:!0}),async throw(t){throw t},[Symbol.asyncIterator](){return this}}}}class f{constructor(t,e){this.onSample=t,this.onError=e}}class m{mediaSamplesInRange(t=0,e=1/0){l(t),l(e);const i=[];let r=!1,s=null,{promise:n,resolve:h}=(0,o.Bw)(),{promise:c,resolve:d}=(0,o.Bw)(),u=!1,p=!1,f=!1,m=null;(async()=>{const a=await this._createDecoder(a=>{d(),a.timestamp>=e&&(p=!0),p?a.close():(s&&(a.timestamp>t?(i.push(s),r=!0):s.close()),a.timestamp>=t&&(i.push(a),r=!0),s=r?null:a,i.length>0&&(h(),({promise:n,resolve:h}=(0,o.Bw)())))},t=>{m||(m=t,h())}),l=this._createPacketSink(),y=await l.getKeyPacket(t,{verifyKeyPackets:!0})??await l.getFirstPacket();let _=y;const b=l.packets(y??void 0,void 0);for(await b.next();_&&!p&&!this._track.input._disposed;){const t=g(i.length);if(i.length+a.getDecodeQueueSize()>t){({promise:c,resolve:d}=(0,o.Bw)()),await c;continue}a.decode(_);const e=await b.next();if(e.done)break;_=e.value}await b.return(),f||this._track.input._disposed||await a.flush(),a.close(),!r&&s&&i.push(s),u=!0,h()})().catch(t=>{m||(m=t,h())});const y=this._track,_=()=>{s?.close();for(const t of i)t.close()};return{async next(){for(;;){if(y.input._disposed)throw _(),new a.x;if(f)return{value:void 0,done:!0};if(m)throw _(),m;if(i.length>0){const t=i.shift();return d(),{value:t,done:!1}}if(u)return{value:void 0,done:!0};await n}},return:async()=>(f=!0,p=!0,d(),h(),_(),{value:void 0,done:!0}),async throw(t){throw t},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(t){(0,o.SC)(t);const e=(0,o.B2)(t),i=[],r=[];let{promise:s,resolve:n}=(0,o.Bw)(),{promise:h,resolve:c}=(0,o.Bw)(),d=!1,u=!1,p=null;const f=t=>{r.push(t),n(),({promise:s,resolve:n}=(0,o.Bw)())};(async()=>{const t=await this._createDecoder(t=>{if(c(),u)return void t.close();let e=0;for(;i.length>0&&t.timestamp-i[0]>-1e-10;)e++,i.shift();if(e>0)for(let i=0;i<e;i++)f(i<e-1?t.clone():t);else t.close()},t=>{p||(p=t,n())}),s=this._createPacketSink();let a=null,m=null,y=-1;const _=async()=>{(0,o.hu)(m);let e=m;for(t.decode(e);e.sequenceNumber<y;){const i=g(r.length);for(;r.length+t.getDecodeQueueSize()>i&&!u;)({promise:h,resolve:c}=(0,o.Bw)()),await h;if(u)break;const a=await s.getNextPacket(e);(0,o.hu)(a),t.decode(a),e=a}y=-1},b=async()=>{await t.flush();for(let t=0;t<i.length;t++)f(null);i.length=0};for await(const t of e){if(l(t),u||this._track.input._disposed)break;const e=await s.getPacket(t),r=e&&await s.getKeyPacket(t,{verifyKeyPackets:!0});r?(a&&(r.sequenceNumber!==m.sequenceNumber||e.timestamp<a.timestamp)&&(await _(),await b()),i.push(e.timestamp),y=Math.max(e.sequenceNumber,y),a=e,m=r):(-1!==y&&(await _(),await b()),f(null),a=null)}u||this._track.input._disposed||(-1!==y&&await _(),await b()),t.close(),d=!0,n()})().catch(t=>{p||(p=t,n())});const m=this._track,y=()=>{for(const t of r)t?.close()};return{async next(){for(;;){if(m.input._disposed)throw y(),new a.x;if(u)return{value:void 0,done:!0};if(p)throw y(),p;if(r.length>0){const t=r.shift();return(0,o.hu)(void 0!==t),c(),{value:t,done:!1}}if(d)return{value:void 0,done:!0};await s}},return:async()=>(u=!0,c(),n(),y(),{value:void 0,done:!0}),async throw(t){throw t},[Symbol.asyncIterator](){return this}}}}const g=t=>0===t?40:8;class y extends f{constructor(t,e,i,a,n,h){super(t,e),this.codec=i,this.decoderConfig=a,this.rotation=n,this.timeResolution=h,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new o.I1,this.customDecoderQueueSize=0,this.inputTimestamps=[],this.sampleQueue=[],this.currentPacketIndex=0,this.raslSkipped=!1,this.alphaDecoder=null,this.alphaHadKeyframe=!1,this.colorQueue=[],this.alphaQueue=[],this.merger=null,this.mergerCreationFailed=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue=[],this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1;const d=s.Ms.find(t=>t.supports(i,a));if(d)this.customDecoder=new d,this.customDecoder.codec=i,this.customDecoder.config=a,this.customDecoder.onSample=t=>{if(!(t instanceof c._A))throw new TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(t)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{const t=t=>{if(this.alphaQueue.length>0){const e=this.alphaQueue.shift();(0,o.hu)(void 0!==e),this.mergeAlpha(t,e)}else this.colorQueue.push(t)};if("avc"===i&&this.decoderConfig.description&&(0,o.mJ)()){const t=(0,r.HS)((0,o._f)(this.decoderConfig.description));if(t&&t.sequenceParameterSets.length>0){const e=(0,r.d$)(t.sequenceParameterSets[0]);e&&0===e.frameMbsOnlyFlag&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"})}}const e=new Error("Decoding error").stack;this.decoder=new VideoDecoder({output:e=>{try{t(e)}catch(t){this.onError(t)}},error:t=>{t.stack=e,this.onError(t)}}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:((0,o.hu)(this.decoder),Math.max(this.decoder.decodeQueueSize,this.alphaDecoder?.decodeQueueSize??0))}decode(t){if("hevc"===this.codec&&this.currentPacketIndex>0&&!this.raslSkipped){if(this.hasHevcRaslPicture(t.data))return;this.raslSkipped=!0}if(this.customDecoder)this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(t)).then(()=>this.customDecoderQueueSize--);else{if((0,o.hu)(this.decoder),(0,o.Pf)()||(0,o.yg)(this.inputTimestamps,t.timestamp,t=>t),(0,o.mJ)()&&0===this.currentPacketIndex&&"avc"===this.codec){const e=[];for(const i of(0,r.Sq)(t.data,this.decoderConfig)){const s=(0,r.Bc)(t.data[i.offset]);s>=20&&s<=31||e.push(t.data.subarray(i.offset,i.offset+i.length))}const i=(0,r.Dg)(e,this.decoderConfig);t=new h.H(i,t.type,t.timestamp,t.duration)}this.decoder.decode(t.toEncodedVideoChunk()),this.decodeAlphaData(t)}this.currentPacketIndex++}decodeAlphaData(t){if(!t.sideData.alpha||this.mergerCreationFailed)return void this.pushNullAlphaFrame();if(!this.merger)try{this.merger=new _}catch(e){return console.error("Due to an error, only color data will be decoded.",e),this.mergerCreationFailed=!0,void this.decodeAlphaData(t)}if(!this.alphaDecoder){const t=t=>{if(this.alphaDecoderQueueSize--,this.colorQueue.length>0){const e=this.colorQueue.shift();(0,o.hu)(void 0!==e),this.mergeAlpha(e,t)}else this.alphaQueue.push(t);for(this.decodedAlphaChunkCount++;this.nullAlphaFrameQueue.length>0&&this.nullAlphaFrameQueue[0]===this.decodedAlphaChunkCount;)if(this.nullAlphaFrameQueue.shift(),this.colorQueue.length>0){const t=this.colorQueue.shift();(0,o.hu)(void 0!==t),this.mergeAlpha(t,null)}else this.alphaQueue.push(null)},e=new Error("Decoding error").stack;this.alphaDecoder=new VideoDecoder({output:e=>{try{t(e)}catch(t){this.onError(t)}},error:t=>{t.stack=e,this.onError(t)}}),this.alphaDecoder.configure(this.decoderConfig)}const e=(0,r.RO)(this.codec,this.decoderConfig,t.sideData.alpha);if(this.alphaHadKeyframe||(this.alphaHadKeyframe="key"===e),this.alphaHadKeyframe){if("hevc"===this.codec&&this.currentAlphaPacketIndex>0&&!this.alphaRaslSkipped){if(this.hasHevcRaslPicture(t.sideData.alpha))return void this.pushNullAlphaFrame();this.alphaRaslSkipped=!0}this.currentAlphaPacketIndex++,this.alphaDecoder.decode(t.alphaToEncodedVideoChunk(e??t.type)),this.alphaDecoderQueueSize++}else this.pushNullAlphaFrame()}pushNullAlphaFrame(){0===this.alphaDecoderQueueSize?this.alphaQueue.push(null):this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture(t){for(const e of(0,r.Tn)(t,this.decoderConfig)){const i=(0,r.UB)(t[e.offset]);if(i===r.$9.RASL_N||i===r.$9.RASL_R)return!0}return!1}sampleHandler(t){if((0,o.Pf)()){if(this.sampleQueue.length>0&&t.timestamp>=(0,o.Z$)(this.sampleQueue).timestamp){for(const t of this.sampleQueue)this.finalizeAndEmitSample(t);this.sampleQueue.length=0}(0,o.yg)(this.sampleQueue,t,t=>t.timestamp)}else{const e=this.inputTimestamps.shift();(0,o.hu)(void 0!==e),t.setTimestamp(e),this.finalizeAndEmitSample(t)}}finalizeAndEmitSample(t){t.setTimestamp(Math.round(t.timestamp*this.timeResolution)/this.timeResolution),t.setDuration(Math.round(t.duration*this.timeResolution)/this.timeResolution),t.setRotation(this.rotation),this.onSample(t)}mergeAlpha(t,e){if(!e){const e=new c._A(t);return void this.sampleHandler(e)}(0,o.hu)(this.merger),this.merger.update(t,e),t.close(),e.close();const i=new VideoFrame(this.merger.canvas,{timestamp:t.timestamp,duration:t.duration??void 0}),r=new c._A(i);this.sampleHandler(r)}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):((0,o.hu)(this.decoder),await Promise.all([this.decoder.flush(),this.alphaDecoder?.flush()]),this.colorQueue.forEach(t=>t.close()),this.colorQueue.length=0,this.alphaQueue.forEach(t=>t?.close()),this.alphaQueue.length=0,this.alphaHadKeyframe=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue.length=0,this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1),(0,o.Pf)()){for(const t of this.sampleQueue)this.finalizeAndEmitSample(t);this.sampleQueue.length=0}this.currentPacketIndex=0,this.raslSkipped=!1}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):((0,o.hu)(this.decoder),this.decoder.close(),this.alphaDecoder?.close(),this.colorQueue.forEach(t=>t.close()),this.colorQueue.length=0,this.alphaQueue.forEach(t=>t?.close()),this.alphaQueue.length=0,this.merger?.close());for(const t of this.sampleQueue)t.close();this.sampleQueue.length=0}}class _{constructor(){"undefined"!=typeof OffscreenCanvas?this.canvas=new OffscreenCanvas(300,150):this.canvas=document.createElement("canvas");const t=this.canvas.getContext("webgl2",{premultipliedAlpha:!1});if(!t)throw new Error("Couldn't acquire WebGL 2 context.");this.gl=t,this.program=this.createProgram(),this.vao=this.createVAO(),this.colorTexture=this.createTexture(),this.alphaTexture=this.createTexture(),this.gl.useProgram(this.program),this.gl.uniform1i(this.gl.getUniformLocation(this.program,"u_colorTexture"),0),this.gl.uniform1i(this.gl.getUniformLocation(this.program,"u_alphaTexture"),1)}createProgram(){const t=this.createShader(this.gl.VERTEX_SHADER,"#version 300 es\n\t\t\tin vec2 a_position;\n\t\t\tin vec2 a_texCoord;\n\t\t\tout vec2 v_texCoord;\n\t\t\t\n\t\t\tvoid main() {\n\t\t\t\tgl_Position = vec4(a_position, 0.0, 1.0);\n\t\t\t\tv_texCoord = a_texCoord;\n\t\t\t}\n\t\t"),e=this.createShader(this.gl.FRAGMENT_SHADER,"#version 300 es\n\t\t\tprecision highp float;\n\t\t\t\n\t\t\tuniform sampler2D u_colorTexture;\n\t\t\tuniform sampler2D u_alphaTexture;\n\t\t\tin vec2 v_texCoord;\n\t\t\tout vec4 fragColor;\n\t\t\t\n\t\t\tvoid main() {\n\t\t\t\tvec3 color = texture(u_colorTexture, v_texCoord).rgb;\n\t\t\t\tfloat alpha = texture(u_alphaTexture, v_texCoord).r;\n\t\t\t\tfragColor = vec4(color, alpha);\n\t\t\t}\n\t\t"),i=this.gl.createProgram();return this.gl.attachShader(i,t),this.gl.attachShader(i,e),this.gl.linkProgram(i),i}createShader(t,e){const i=this.gl.createShader(t);return this.gl.shaderSource(i,e),this.gl.compileShader(i),i}createVAO(){const t=this.gl.createVertexArray();this.gl.bindVertexArray(t);const e=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),i=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,i),this.gl.bufferData(this.gl.ARRAY_BUFFER,e,this.gl.STATIC_DRAW);const r=this.gl.getAttribLocation(this.program,"a_position"),s=this.gl.getAttribLocation(this.program,"a_texCoord");return this.gl.enableVertexAttribArray(r),this.gl.vertexAttribPointer(r,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(s),this.gl.vertexAttribPointer(s,2,this.gl.FLOAT,!1,16,8),t}createTexture(){const t=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,t),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),t}update(t,e){t.displayWidth===this.canvas.width&&t.displayHeight===this.canvas.height||(this.canvas.width=t.displayWidth,this.canvas.height=t.displayHeight),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.colorTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,t),this.gl.activeTexture(this.gl.TEXTURE1),this.gl.bindTexture(this.gl.TEXTURE_2D,this.alphaTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4)}close(){this.gl.getExtension("WEBGL_lose_context")?.loseContext(),this.gl=null}}class b extends m{constructor(t){if(!(t instanceof n.mC))throw new TypeError("videoTrack must be an InputVideoTrack.");super(),this._track=t}async _createDecoder(t,e){if(!await this._track.canDecode())throw new Error("This video track cannot be decoded by this browser. Make sure to check decodability before using a track.");const i=this._track.codec,r=this._track.rotation,s=await this._track.getDecoderConfig(),a=this._track.timeResolution;return(0,o.hu)(i&&s),new y(t,e,i,s,r,a)}_createPacketSink(){return new p(this._track)}async getSample(t){l(t);for await(const e of this.mediaSamplesAtTimestamps([t]))return e;throw new Error("Internal error: Iterator returned nothing.")}samples(t=0,e=1/0){return this.mediaSamplesInRange(t,e)}samplesAtTimestamps(t){return this.mediaSamplesAtTimestamps(t)}}},689:(t,e,i)=>{i.d(e,{$8:()=>y,CS:()=>m,D0:()=>f,Dg:()=>p,LG:()=>d,p7:()=>g});var r=i(797),s=i(583),a=i(812),n=i(38),o=i(348),h=i(690);class c{constructor(){this._connectedTrack=null,this._closingPromise=null,this._closed=!1,this._timestampOffset=0}_ensureValidAdd(){if(!this._connectedTrack)throw new Error("Source is not connected to an output track.");if("canceled"===this._connectedTrack.output.state)throw new Error("Output has been canceled.");if("finalizing"===this._connectedTrack.output.state||"finalized"===this._connectedTrack.output.state)throw new Error("Output has been finalized.");if("pending"===this._connectedTrack.output.state)throw new Error("Output has not started.");if(this._closed)throw new Error("Source is closed.")}async _start(){}async _flushAndClose(t){}close(){if(this._closingPromise)return;const t=this._connectedTrack;if(!t)throw new Error("Cannot call close without connecting the source to an output track.");if("pending"===t.output.state)throw new Error("Cannot call close before output has been started.");this._closingPromise=(async()=>{await this._flushAndClose(!1),this._closed=!0,"finalizing"!==t.output.state&&"finalized"!==t.output.state&&t.output._muxer.onTrackClose(t)})()}async _flushOrWaitForOngoingClose(t){return this._closingPromise??=(async()=>{await this._flushAndClose(t),this._closed=!0})()}}class d extends c{constructor(t){if(super(),this._connectedTrack=null,!r.Au.includes(t))throw new TypeError(`Invalid video codec '${t}'. Must be one of: ${r.Au.join(", ")}.`);this._codec=t}}class l{constructor(t,e){this.source=t,this.encodingConfig=e,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastMultipleOfKeyFrameInterval=-1,this.codedWidth=null,this.codedHeight=null,this.resizeCanvas=null,this.customEncoder=null,this.customEncoderCallSerializer=new s.I1,this.customEncoderQueueSize=0,this.alphaEncoder=null,this.splitter=null,this.splitterCreationFailed=!1,this.alphaFrameQueue=[],this.error=null,this.errorNeedsNewStack=!0}async add(t,e,i){try{if(this.checkForEncoderError(),this.source._ensureValidAdd(),null!==this.codedWidth&&null!==this.codedHeight){if(t.codedWidth!==this.codedWidth||t.codedHeight!==this.codedHeight){const i=this.encodingConfig.sizeChangeBehavior??"deny";if("passThrough"===i);else{if("deny"===i)throw new Error(`Video sample size must remain constant. Expected ${this.codedWidth}x${this.codedHeight}, got ${t.codedWidth}x${t.codedHeight}. To allow the sample size to change over time, set \`sizeChangeBehavior\` to a value other than 'strict' in the encoding options.`);{let r=!1;this.resizeCanvas||("undefined"!=typeof document?(this.resizeCanvas=document.createElement("canvas"),this.resizeCanvas.width=this.codedWidth,this.resizeCanvas.height=this.codedHeight):this.resizeCanvas=new OffscreenCanvas(this.codedWidth,this.codedHeight),r=!0);const a=this.resizeCanvas.getContext("2d",{alpha:(0,s.vU)()});(0,s.hu)(a),r||((0,s.vU)()?(a.fillStyle="black",a.fillRect(0,0,this.codedWidth,this.codedHeight)):a.clearRect(0,0,this.codedWidth,this.codedHeight)),t.drawWithFit(a,{fit:i}),e&&t.close(),t=new o._A(this.resizeCanvas,{timestamp:t.timestamp,duration:t.duration,rotation:t.rotation}),e=!0}}}}else this.codedWidth=t.codedWidth,this.codedHeight=t.codedHeight;this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(t),this.encoderInitialized||await this.ensureEncoderPromise),(0,s.hu)(this.encoderInitialized);const r=this.encodingConfig.keyFrameInterval??5,a=Math.floor(t.timestamp/r),n={...i,keyFrame:i?.keyFrame||0===r||a!==this.lastMultipleOfKeyFrameInterval};if(this.lastMultipleOfKeyFrameInterval=a,this.customEncoder){this.customEncoderQueueSize++;const e=t.clone(),i=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(e,n)).then(()=>this.customEncoderQueueSize--).catch(t=>this.error??=t).finally(()=>{e.close()});this.customEncoderQueueSize>=4&&await i}else{(0,s.hu)(this.encoder);const i=t.toVideoFrame();if(this.alphaEncoder)if(i.format&&!i.format.includes("A")||this.splitterCreationFailed)this.alphaFrameQueue.push(null),this.encoder.encode(i,n),i.close();else{const e=i.displayWidth,r=i.displayHeight;if(!this.splitter)try{this.splitter=new u(e,r)}catch(t){console.error("Due to an error, only color data will be encoded.",t),this.splitterCreationFailed=!0,this.alphaFrameQueue.push(null),this.encoder.encode(i,n),i.close()}if(this.splitter){const t=this.splitter.extractColor(i),e=this.splitter.extractAlpha(i);this.alphaFrameQueue.push(e),this.encoder.encode(t,n),t.close(),i.close()}}else this.encoder.encode(i,n),i.close();e&&t.close(),this.encoder.encodeQueueSize>=4&&await new Promise(t=>this.encoder.addEventListener("dequeue",t,{once:!0}))}await this.muxer.mutex.currentPromise}finally{e&&t.close()}}ensureEncoder(t){const e=new Error;this.ensureEncoderPromise=(async()=>{const i=(0,h.ew)({width:t.codedWidth,height:t.codedHeight,...this.encodingConfig,framerate:this.source._connectedTrack?.metadata.frameRate});this.encodingConfig.onEncoderConfig?.(i);const r=a.c6.find(t=>t.supports(this.encodingConfig.codec,i));if(r)this.customEncoder=new r,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=i,this.customEncoder.onPacket=(t,e)=>{if(!(t instanceof n.H))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(void 0!==e&&(!e||"object"!=typeof e))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");this.encodingConfig.onEncodedPacket?.(t,e),this.muxer.addEncodedVideoPacket(this.source._connectedTrack,t,e).catch(t=>{this.error??=t,this.errorNeedsNewStack=!1})},await this.customEncoder.init();else{if("undefined"==typeof VideoEncoder)throw new Error("VideoEncoder is not supported by this browser.");if(i.alpha="discard","keep"===this.encodingConfig.alpha&&(i.latencyMode="quality"),!(i.width%2!=1&&i.height%2!=1||"avc"!==this.encodingConfig.codec&&"hevc"!==this.encodingConfig.codec))throw new Error(`The dimensions ${i.width}x${i.height} are not supported for codec '${this.encodingConfig.codec}'; both width and height must be even numbers. Make sure to round your dimensions to the nearest even number.`);if(!(await VideoEncoder.isConfigSupported(i)).supported)throw new Error(`This specific encoder configuration (${i.codec}, ${i.bitrate} bps, ${i.width}x${i.height}, hardware acceleration: ${i.hardwareAcceleration??"no-preference"}) is not supported by this browser. Consider using another codec or changing your video parameters.`);const t=[],r=[];let a=0,o=0;const h=(t,e,i)=>{const r={};if(e){const t=new Uint8Array(e.byteLength);e.copyTo(t),r.alpha=t}const s=n.H.fromEncodedChunk(t,r);this.encodingConfig.onEncodedPacket?.(s,i),this.muxer.addEncodedVideoPacket(this.source._connectedTrack,s,i).catch(t=>{this.error??=t,this.errorNeedsNewStack=!1})};this.encoder=new VideoEncoder({output:(e,i)=>{if(!this.alphaEncoder)return void h(e,null,i);const n=this.alphaFrameQueue.shift();(0,s.hu)(void 0!==n),n?(this.alphaEncoder.encode(n,{keyFrame:"key"===e.type}),o++,n.close(),t.push({chunk:e,meta:i})):0===o?h(e,null,i):(r.push(a+o),t.push({chunk:e,meta:i}))},error:t=>{t.stack=e.stack,this.error??=t}}),this.encoder.configure(i),"keep"===this.encodingConfig.alpha&&(this.alphaEncoder=new VideoEncoder({output:(e,i)=>{o--;const n=t.shift();for((0,s.hu)(void 0!==n),h(n.chunk,e,n.meta),a++;r.length>0&&r[0]===a;){r.shift();const e=t.shift();(0,s.hu)(void 0!==e),h(e.chunk,null,e.meta)}},error:t=>{t.stack=e.stack,this.error??=t}}),this.alphaEncoder.configure(i))}(0,s.hu)(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}async flushAndClose(t){t||this.checkForEncoderError(),this.customEncoder?(t||this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()),await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())):this.encoder&&(t||(await this.encoder.flush(),await(this.alphaEncoder?.flush())),"closed"!==this.encoder.state&&this.encoder.close(),this.alphaEncoder&&"closed"!==this.alphaEncoder.state&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(t=>t?.close()),this.splitter?.close()),t||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.error)throw this.errorNeedsNewStack&&(this.error.stack=(new Error).stack),this.error}}class u{constructor(t,e){this.lastFrame=null,"undefined"!=typeof OffscreenCanvas?this.canvas=new OffscreenCanvas(t,e):(this.canvas=document.createElement("canvas"),this.canvas.width=t,this.canvas.height=e);const i=this.canvas.getContext("webgl2",{alpha:!0});if(!i)throw new Error("Couldn't acquire WebGL 2 context.");this.gl=i,this.colorProgram=this.createColorProgram(),this.alphaProgram=this.createAlphaProgram(),this.vao=this.createVAO(),this.sourceTexture=this.createTexture(),this.alphaResolutionLocation=this.gl.getUniformLocation(this.alphaProgram,"u_resolution"),this.gl.useProgram(this.colorProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.colorProgram,"u_sourceTexture"),0),this.gl.useProgram(this.alphaProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.alphaProgram,"u_sourceTexture"),0)}createVertexShader(){return this.createShader(this.gl.VERTEX_SHADER,"#version 300 es\n\t\t\tin vec2 a_position;\n\t\t\tin vec2 a_texCoord;\n\t\t\tout vec2 v_texCoord;\n\t\t\t\n\t\t\tvoid main() {\n\t\t\t\tgl_Position = vec4(a_position, 0.0, 1.0);\n\t\t\t\tv_texCoord = a_texCoord;\n\t\t\t}\n\t\t")}createColorProgram(){const t=this.createVertexShader(),e=this.createShader(this.gl.FRAGMENT_SHADER,"#version 300 es\n\t\t\tprecision highp float;\n\t\t\t\n\t\t\tuniform sampler2D u_sourceTexture;\n\t\t\tin vec2 v_texCoord;\n\t\t\tout vec4 fragColor;\n\t\t\t\n\t\t\tvoid main() {\n\t\t\t\tvec4 source = texture(u_sourceTexture, v_texCoord);\n\t\t\t\tfragColor = vec4(source.rgb, 1.0);\n\t\t\t}\n\t\t"),i=this.gl.createProgram();return this.gl.attachShader(i,t),this.gl.attachShader(i,e),this.gl.linkProgram(i),i}createAlphaProgram(){const t=this.createVertexShader(),e=this.createShader(this.gl.FRAGMENT_SHADER,"#version 300 es\n\t\t\tprecision highp float;\n\t\t\t\n\t\t\tuniform sampler2D u_sourceTexture;\n\t\t\tuniform vec2 u_resolution; // The width and height of the canvas\n\t\t\tin vec2 v_texCoord;\n\t\t\tout vec4 fragColor;\n\n\t\t\t// This function determines the value for a single byte in the YUV stream\n\t\t\tfloat getByteValue(float byteOffset) {\n\t\t\t\tfloat width = u_resolution.x;\n\t\t\t\tfloat height = u_resolution.y;\n\n\t\t\t\tfloat yPlaneSize = width * height;\n\n\t\t\t\tif (byteOffset < yPlaneSize) {\n\t\t\t\t\t// This byte is in the luma plane. Find the corresponding pixel coordinates to sample from\n\t\t\t\t\tfloat y = floor(byteOffset / width);\n\t\t\t\t\tfloat x = mod(byteOffset, width);\n\t\t\t\t\t\n\t\t\t\t\t// Add 0.5 to sample the center of the texel\n\t\t\t\t\tvec2 sampleCoord = (vec2(x, y) + 0.5) / u_resolution;\n\t\t\t\t\t\n\t\t\t\t\t// The luma value is the alpha from the source texture\n\t\t\t\t\treturn texture(u_sourceTexture, sampleCoord).a;\n\t\t\t\t} else {\n\t\t\t\t\t// Write a fixed value for chroma and beyond\n\t\t\t\t\treturn 128.0 / 255.0;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tvoid main() {\n\t\t\t\t// Each fragment writes 4 bytes (R, G, B, A)\n\t\t\t\tfloat pixelIndex = floor(gl_FragCoord.y) * u_resolution.x + floor(gl_FragCoord.x);\n\t\t\t\tfloat baseByteOffset = pixelIndex * 4.0;\n\n\t\t\t\tvec4 result;\n\t\t\t\tfor (int i = 0; i < 4; i++) {\n\t\t\t\t\tfloat currentByteOffset = baseByteOffset + float(i);\n\t\t\t\t\tresult[i] = getByteValue(currentByteOffset);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tfragColor = result;\n\t\t\t}\n\t\t"),i=this.gl.createProgram();return this.gl.attachShader(i,t),this.gl.attachShader(i,e),this.gl.linkProgram(i),i}createShader(t,e){const i=this.gl.createShader(t);return this.gl.shaderSource(i,e),this.gl.compileShader(i),this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS)||console.error("Shader compile error:",this.gl.getShaderInfoLog(i)),i}createVAO(){const t=this.gl.createVertexArray();this.gl.bindVertexArray(t);const e=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),i=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,i),this.gl.bufferData(this.gl.ARRAY_BUFFER,e,this.gl.STATIC_DRAW);const r=this.gl.getAttribLocation(this.colorProgram,"a_position"),s=this.gl.getAttribLocation(this.colorProgram,"a_texCoord");return this.gl.enableVertexAttribArray(r),this.gl.vertexAttribPointer(r,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(s),this.gl.vertexAttribPointer(s,2,this.gl.FLOAT,!1,16,8),t}createTexture(){const t=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,t),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),t}updateTexture(t){this.lastFrame!==t&&(t.displayWidth===this.canvas.width&&t.displayHeight===this.canvas.height||(this.canvas.width=t.displayWidth,this.canvas.height=t.displayHeight),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.sourceTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,t),this.lastFrame=t)}extractColor(t){return this.updateTexture(t),this.gl.useProgram(this.colorProgram),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4),new VideoFrame(this.canvas,{timestamp:t.timestamp,duration:t.duration??void 0,alpha:"discard"})}extractAlpha(t){this.updateTexture(t),this.gl.useProgram(this.alphaProgram),this.gl.uniform2f(this.alphaResolutionLocation,this.canvas.width,this.canvas.height),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4);const{width:e,height:i}=this.canvas,r=e*i+Math.ceil(e/2)*Math.ceil(i/2)*2,a=Math.ceil(r/(4*e));let n=new Uint8Array(4*e*a);this.gl.readPixels(0,0,e,a,this.gl.RGBA,this.gl.UNSIGNED_BYTE,n),n=n.subarray(0,r),(0,s.hu)(128===n[e*i]),(0,s.hu)(128===n[n.length-1]);const o={format:"I420",codedWidth:e,codedHeight:i,timestamp:t.timestamp,duration:t.duration??void 0,transfer:[n.buffer]};return new VideoFrame(n,o)}close(){this.gl.getExtension("WEBGL_lose_context")?.loseContext(),this.gl=null}}class p extends d{constructor(t){(0,h.bj)(t),super(t.codec),this._encoder=new l(this,t)}add(t,e){if(!(t instanceof o._A))throw new TypeError("videoSample must be a VideoSample.");return this._encoder.add(t,!1,e)}_flushAndClose(t){return this._encoder.flushAndClose(t)}}class f extends d{constructor(t,e){if(!("undefined"!=typeof HTMLCanvasElement&&t instanceof HTMLCanvasElement||"undefined"!=typeof OffscreenCanvas&&t instanceof OffscreenCanvas))throw new TypeError("canvas must be an HTMLCanvasElement or OffscreenCanvas.");(0,h.bj)(e),super(e.codec),this._encoder=new l(this,e),this._canvas=t}add(t,e=0,i){if(!Number.isFinite(t)||t<0)throw new TypeError("timestamp must be a non-negative number.");if(!Number.isFinite(e)||e<0)throw new TypeError("duration must be a non-negative number.");const r=new o._A(this._canvas,{timestamp:t,duration:e});return this._encoder.add(r,!0,i)}_flushAndClose(t){return this._encoder.flushAndClose(t)}}class m extends c{constructor(t){if(super(),this._connectedTrack=null,!r.eY.includes(t))throw new TypeError(`Invalid audio codec '${t}'. Must be one of: ${r.eY.join(", ")}.`);this._codec=t}}class g extends m{constructor(t){super(t)}add(t,e){if(!(t instanceof n.H))throw new TypeError("packet must be an EncodedPacket.");if(t.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be added.");if(void 0!==e&&(!e||"object"!=typeof e))throw new TypeError("meta, when provided, must be an object.");return this._ensureValidAdd(),this._connectedTrack.output._muxer.addEncodedAudioPacket(this._connectedTrack,t,e)}}class y extends c{constructor(t){if(super(),this._connectedTrack=null,!r.tW.includes(t))throw new TypeError(`Invalid subtitle codec '${t}'. Must be one of: ${r.tW.join(", ")}.`);this._codec=t}}},653:(t,e,i)=>{i.d(e,{CN:()=>n,RE:()=>a,jC:()=>r,kG:()=>o,sZ:()=>s});class r{constructor(t,e){if(this.data=t,this.mimeType=e,!(t instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if("string"!=typeof e)throw new TypeError("mimeType must be a string.")}}class s{constructor(t,e,i,r){if(this.data=t,this.mimeType=e,this.name=i,this.description=r,!(t instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(void 0!==e&&"string"!=typeof e)throw new TypeError("mimeType, when provided, must be a string.");if(void 0!==i&&"string"!=typeof i)throw new TypeError("name, when provided, must be a string.");if(void 0!==r&&"string"!=typeof r)throw new TypeError("description, when provided, must be a string.")}}const a=t=>{if(!t||"object"!=typeof t)throw new TypeError("tags must be an object.");if(void 0!==t.title&&"string"!=typeof t.title)throw new TypeError("tags.title, when provided, must be a string.");if(void 0!==t.description&&"string"!=typeof t.description)throw new TypeError("tags.description, when provided, must be a string.");if(void 0!==t.artist&&"string"!=typeof t.artist)throw new TypeError("tags.artist, when provided, must be a string.");if(void 0!==t.album&&"string"!=typeof t.album)throw new TypeError("tags.album, when provided, must be a string.");if(void 0!==t.albumArtist&&"string"!=typeof t.albumArtist)throw new TypeError("tags.albumArtist, when provided, must be a string.");if(void 0!==t.trackNumber&&(!Number.isInteger(t.trackNumber)||t.trackNumber<=0))throw new TypeError("tags.trackNumber, when provided, must be a positive integer.");if(void 0!==t.tracksTotal&&(!Number.isInteger(t.tracksTotal)||t.tracksTotal<=0))throw new TypeError("tags.tracksTotal, when provided, must be a positive integer.");if(void 0!==t.discNumber&&(!Number.isInteger(t.discNumber)||t.discNumber<=0))throw new TypeError("tags.discNumber, when provided, must be a positive integer.");if(void 0!==t.discsTotal&&(!Number.isInteger(t.discsTotal)||t.discsTotal<=0))throw new TypeError("tags.discsTotal, when provided, must be a positive integer.");if(void 0!==t.genre&&"string"!=typeof t.genre)throw new TypeError("tags.genre, when provided, must be a string.");if(void 0!==t.date&&(!(t.date instanceof Date)||Number.isNaN(t.date.getTime())))throw new TypeError("tags.date, when provided, must be a valid Date.");if(void 0!==t.lyrics&&"string"!=typeof t.lyrics)throw new TypeError("tags.lyrics, when provided, must be a string.");if(void 0!==t.images){if(!Array.isArray(t.images))throw new TypeError("tags.images, when provided, must be an array.");for(const e of t.images){if(!e||"object"!=typeof e)throw new TypeError("Each image in tags.images must be an object.");if(!(e.data instanceof Uint8Array))throw new TypeError("Each image.data must be a Uint8Array.");if("string"!=typeof e.mimeType)throw new TypeError("Each image.mimeType must be a string.");if(!["coverFront","coverBack","unknown"].includes(e.kind))throw new TypeError("Each image.kind must be 'coverFront', 'coverBack', or 'unknown'.")}}if(void 0!==t.comment&&"string"!=typeof t.comment)throw new TypeError("tags.comment, when provided, must be a string.");if(void 0!==t.raw){if(!t.raw||"object"!=typeof t.raw)throw new TypeError("tags.raw, when provided, must be an object.");for(const e of Object.values(t.raw))if(!(null===e||"string"==typeof e||e instanceof Uint8Array||e instanceof r||e instanceof s))throw new TypeError("Each value in tags.raw must be a string, Uint8Array, RichImageData, AttachedFile, or null.")}},n={default:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1},o=t=>{if(!t||"object"!=typeof t)throw new TypeError("disposition must be an object.");if(void 0!==t.default&&"boolean"!=typeof t.default)throw new TypeError("disposition.default must be a boolean.");if(void 0!==t.forced&&"boolean"!=typeof t.forced)throw new TypeError("disposition.forced must be a boolean.");if(void 0!==t.original&&"boolean"!=typeof t.original)throw new TypeError("disposition.original must be a boolean.");if(void 0!==t.commentary&&"boolean"!=typeof t.commentary)throw new TypeError("disposition.commentary must be a boolean.");if(void 0!==t.hearingImpaired&&"boolean"!=typeof t.hearingImpaired)throw new TypeError("disposition.hearingImpaired must be a boolean.");if(void 0!==t.visuallyImpaired&&"boolean"!=typeof t.visuallyImpaired)throw new TypeError("disposition.visuallyImpaired must be a boolean.")}},583:(t,e,i)=>{function r(t){if(!t)throw new Error("Assertion failed.")}i.d(e,{$9:()=>m,AH:()=>et,B2:()=>P,Bw:()=>B,F3:()=>N,G3:()=>T,I1:()=>Y,Ih:()=>$,Jy:()=>C,K9:()=>at,KE:()=>w,LD:()=>n,LT:()=>_,NK:()=>l,O9:()=>O,P0:()=>b,Pf:()=>Q,Rh:()=>G,SC:()=>z,SI:()=>h,Sf:()=>x,Ue:()=>j,V3:()=>y,We:()=>v,Z$:()=>a,Zi:()=>o,_f:()=>d,bJ:()=>c,bL:()=>rt,dF:()=>A,hj:()=>ot,hu:()=>r,lP:()=>s,lY:()=>st,mJ:()=>J,n0:()=>k,n1:()=>V,n3:()=>R,oL:()=>p,p0:()=>H,q9:()=>S,qN:()=>M,qr:()=>I,rB:()=>D,sF:()=>E,uZ:()=>L,un:()=>nt,vE:()=>F,vU:()=>X,vX:()=>g,y$:()=>it,yg:()=>U,zN:()=>u});const s=t=>{const e=(t%360+360)%360;if(0===e||90===e||180===e||270===e)return e;throw new Error(`Invalid rotation ${t}.`)},a=t=>t&&t[t.length-1],n=t=>t>=0&&t<2**32;class o{constructor(t){this.bytes=t,this.pos=0}seekToByte(t){this.pos=8*t}readBit(){const t=Math.floor(this.pos/8),e=this.bytes[t]??0,i=7-(7&this.pos),r=(e&1<<i)>>i;return this.pos++,r}readBits(t){if(1===t)return this.readBit();let e=0;for(let i=0;i<t;i++)e<<=1,e|=this.readBit();return e}writeBits(t,e){const i=this.pos+t;for(let t=this.pos;t<i;t++){const r=Math.floor(t/8);let s=this.bytes[r];const a=7-(7&t);s&=~(1<<a),s|=(e&1<<i-t-1)>>i-t-1<<a,this.bytes[r]=s}this.pos=i}readAlignedByte(){if(this.pos%8!=0)throw new Error("Bitstream is not byte-aligned.");const t=this.pos/8,e=this.bytes[t]??0;return this.pos+=8,e}skipBits(t){this.pos+=t}getBitsLeft(){return 8*this.bytes.length-this.pos}clone(){const t=new o(this.bytes);return t.pos=this.pos,t}}const h=t=>{let e=0;for(;0===t.readBits(1)&&e<32;)e++;if(e>=32)throw new Error("Invalid exponential-Golomb code.");return(1<<e)-1+t.readBits(e)},c=t=>{const e=h(t);return 1&e?e+1>>1:-(e>>1)},d=t=>t.constructor===Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t),l=t=>t.constructor===DataView?t:ArrayBuffer.isView(t)?new DataView(t.buffer,t.byteOffset,t.byteLength):new DataView(t),u=new TextDecoder,p=new TextEncoder,f=t=>Object.fromEntries(Object.entries(t).map(([t,e])=>[e,t])),m={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},g=f(m),y={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},_=f(y),b={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},w=f(b),v=t=>!!(t&&t.primaries&&t.transfer&&t.matrix&&void 0!==t.fullRange),k=t=>t instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&t instanceof SharedArrayBuffer||ArrayBuffer.isView(t);class S{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}async acquire(){let t;const e=new Promise(e=>{let i=!1;t=()=>{i||(e(),this.pending--,i=!0)}}),i=this.currentPromise;return this.currentPromise=e,this.pending++,await i,t}}const T=t=>[...t].map(t=>t.toString(16).padStart(2,"0")).join(""),x=t=>(t=(t=(t=(t=(t=t>>1&1431655765|(1431655765&t)<<1)>>2&858993459|(858993459&t)<<2)>>4&252645135|(252645135&t)<<4)>>8&16711935|(16711935&t)<<8)>>16&65535|(65535&t)<<16)>>>0,C=(t,e,i)=>{let r=0,s=t.length-1,a=-1;for(;r<=s;){const n=r+s>>1,o=i(t[n]);o===e?(a=n,s=n-1):o<e?r=n+1:s=n-1}return a},E=(t,e,i)=>{let r=0,s=t.length-1,a=-1;for(;r<=s;){const n=r+(s-r+1)/2|0;i(t[n])<=e?(a=n,r=n+1):s=n-1}return a},U=(t,e,i)=>{const r=E(t,i(e),i);t.splice(r+1,0,e)},B=()=>{let t,e;return{promise:new Promise((i,r)=>{t=i,e=r}),resolve:t,reject:e}},A=(t,e)=>{for(let i=t.length-1;i>=0;i--)if(e(t[i]))return t[i]},I=(t,e)=>{for(let i=t.length-1;i>=0;i--)if(e(t[i]))return i;return-1},P=async function*(t){Symbol.iterator in t?yield*t[Symbol.iterator]():yield*t[Symbol.asyncIterator]()},z=t=>{if(!(Symbol.iterator in t)&&!(Symbol.asyncIterator in t))throw new TypeError("Argument must be an iterable or async iterable.")},F=t=>{throw new Error(`Unexpected value: ${t}`)},D=(t,e,i)=>{const r=t.getUint8(e),s=t.getUint8(e+1),a=t.getUint8(e+2);return i?r|s<<8|a<<16:r<<16|s<<8|a},M=(t,e,i,r)=>{i>>>=0,i&=16777215,r?(t.setUint8(e,255&i),t.setUint8(e+1,i>>>8&255),t.setUint8(e+2,i>>>16&255)):(t.setUint8(e,i>>>16&255),t.setUint8(e+1,i>>>8&255),t.setUint8(e+2,255&i))},L=(t,e,i)=>Math.max(e,Math.min(i,t)),R="und",N=t=>{const e=Math.round(t);return Math.abs(t/e-1)<10*Number.EPSILON?e:t},O=(t,e)=>Math.round(t/e)*e,H=(t,e)=>Math.floor(t/e)*e,V=t=>{let e=0;for(;t;)e++,t>>=1;return e},W=/^[a-z]{3}$/,G=t=>W.test(t),j=1e6*(1+Number.EPSILON),$=(t,e)=>{const i=t<0?-1:1;let r=0,s=1,a=1,n=0,o=t=Math.abs(t);for(;;){const t=Math.floor(o),h=t*a+r,c=t*n+s;if(c>e)return{numerator:i*a,denominator:n};if(r=a,s=n,a=h,n=c,o=1/(o-t),!isFinite(o))break}return{numerator:i*a,denominator:n}};class Y{constructor(){this.currentPromise=Promise.resolve()}call(t){return this.currentPromise=this.currentPromise.then(t)}}let q=null;const Q=()=>null!==q?q:q=!("undefined"==typeof navigator||!(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent)));let K=null;const X=()=>null!==K?K:K="undefined"!=typeof navigator&&navigator.userAgent?.includes("Firefox");let Z=null;const J=()=>null!==Z?Z:Z=!("undefined"==typeof navigator||!navigator.vendor?.includes("Google Inc")&&!/Chrome/.test(navigator.userAgent));let tt=null;const et=()=>{if(null!==tt)return tt;if("undefined"==typeof navigator)return null;const t=/\bChrome\/(\d+)/.exec(navigator.userAgent);return t?tt=Number(t[1]):null},it=(t,e)=>-1!==t?t:e,rt=(t,e,i,r)=>t<=r&&i<=e,st=function*(t){for(const e in t){const i=t[e];void 0!==i&&(yield{key:e,value:i})}},at=t=>{const e=atob(t),i=new Uint8Array(e.length);for(let t=0;t<e.length;t++)i[t]=e.charCodeAt(t);return i},nt=()=>{Symbol.dispose??=Symbol("Symbol.dispose")},ot=t=>"number"==typeof t&&!Number.isNaN(t)},547:(t,e,i)=>{i.d(e,{WC:()=>te,E1:()=>Jt,WJ:()=>Xt});var r=i(797),s=i(583);const a=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,n=t=>{const e=Math.floor(t/36e5),i=Math.floor(t%36e5/6e4),r=Math.floor(t%6e4/1e3),s=t%1e3;return e.toString().padStart(2,"0")+":"+i.toString().padStart(2,"0")+":"+r.toString().padStart(2,"0")+"."+s.toString().padStart(3,"0")};var o=i(139),h=i(653);class c{constructor(t){this.writer=t,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=new WeakMap}writeU32(t){this.helperView.setUint32(0,t,!1),this.writer.write(this.helper.subarray(0,4))}writeU64(t){this.helperView.setUint32(0,Math.floor(t/2**32),!1),this.helperView.setUint32(4,t,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii(t){for(let e=0;e<t.length;e++)this.helperView.setUint8(e%8,t.charCodeAt(e)),e%8==7&&this.writer.write(this.helper);t.length%8!=0&&this.writer.write(this.helper.subarray(0,t.length%8))}writeBox(t){if(this.offsets.set(t,this.writer.getPos()),t.contents&&!t.children)this.writeBoxHeader(t,t.size??t.contents.byteLength+8),this.writer.write(t.contents);else{const e=this.writer.getPos();if(this.writeBoxHeader(t,0),t.contents&&this.writer.write(t.contents),t.children)for(const e of t.children)e&&this.writeBox(e);const i=this.writer.getPos(),r=t.size??i-e;this.writer.seek(e),this.writeBoxHeader(t,r),this.writer.seek(i)}}writeBoxHeader(t,e){this.writeU32(t.largeSize?1:e),this.writeAscii(t.type),t.largeSize&&this.writeU64(e)}measureBoxHeader(t){return 8+(t.largeSize?8:0)}patchBox(t){const e=this.offsets.get(t);(0,s.hu)(void 0!==e);const i=this.writer.getPos();this.writer.seek(e),this.writeBox(t),this.writer.seek(i)}measureBox(t){if(t.contents&&!t.children)return this.measureBoxHeader(t)+t.contents.byteLength;{let e=this.measureBoxHeader(t);if(t.contents&&(e+=t.contents.byteLength),t.children)for(const i of t.children)i&&(e+=this.measureBox(i));return e}}}const d=new Uint8Array(8),l=new DataView(d.buffer),u=t=>[(t%256+256)%256],p=t=>(l.setUint16(0,t,!1),[d[0],d[1]]),f=t=>(l.setInt16(0,t,!1),[d[0],d[1]]),m=t=>(l.setUint32(0,t,!1),[d[1],d[2],d[3]]),g=t=>(l.setUint32(0,t,!1),[d[0],d[1],d[2],d[3]]),y=t=>(l.setInt32(0,t,!1),[d[0],d[1],d[2],d[3]]),_=t=>(l.setUint32(0,Math.floor(t/2**32),!1),l.setUint32(4,t,!1),[d[0],d[1],d[2],d[3],d[4],d[5],d[6],d[7]]),b=t=>(l.setInt16(0,256*t,!1),[d[0],d[1]]),w=t=>(l.setInt32(0,65536*t,!1),[d[0],d[1],d[2],d[3]]),v=t=>(l.setInt32(0,2**30*t,!1),[d[0],d[1],d[2],d[3]]),k=(t,e)=>{const i=[];let r=t;do{let t=127&r;r>>=7,i.length>0&&(t|=128),i.push(t),void 0!==e&&e--}while(r>0||e);return i.reverse()},S=(t,e=!1)=>{const i=Array(t.length).fill(null).map((e,i)=>t.charCodeAt(i));return e&&i.push(0),i},T=t=>{let e=null;for(const i of t)(!e||i.timestamp>e.timestamp)&&(e=i);return e},x=t=>{const e=t*(Math.PI/180),i=Math.round(Math.cos(e)),r=Math.round(Math.sin(e));return[i,r,0,-r,i,0,0,0,1]},C=x(0),E=t=>[w(t[0]),w(t[1]),v(t[2]),w(t[3]),w(t[4]),v(t[5]),w(t[6]),w(t[7]),v(t[8])],U=(t,e,i)=>({type:t,contents:e&&new Uint8Array(e.flat(10)),children:i}),B=(t,e,i,r,s)=>U(t,[u(e),m(i),r??[]],s),A=t=>({type:"mdat",largeSize:t}),I=t=>U("moov",void 0,[P(t.creationTime,t.trackDatas),...t.trackDatas.map(e=>z(e,t.creationTime)),t.isFragmented?ut(t.trackDatas):null,xt(t)]),P=(t,e)=>{const i=Qt(Math.max(0,...e.filter(t=>t.samples.length>0).map(t=>{const e=T(t.samples);return e.timestamp+e.duration})),Yt),r=Math.max(0,...e.map(t=>t.track.id))+1,a=!(0,s.LD)(t)||!(0,s.LD)(i),n=a?_:g;return B("mvhd",+a,0,[n(t),n(t),g(Yt),n(i),w(1),b(1),Array(10).fill(0),E(C),Array(24).fill(0),g(r)])},z=(t,e)=>{const i=qt(t);return U("trak",void 0,[F(t,e),D(t,e),void 0!==i.name?U("udta",void 0,[U("name",[...s.oL.encode(i.name)])]):null])},F=(t,e)=>{const i=T(t.samples),r=Qt(i?i.timestamp+i.duration:0,Yt),a=!(0,s.LD)(e)||!(0,s.LD)(r),n=a?_:g;let o;if("video"===t.type){const e=t.track.metadata.rotation;o=x(e??0)}else o=C;let h=2;return!1!==t.track.metadata.disposition?.default&&(h|=1),B("tkhd",+a,h,[n(e),n(e),g(t.track.id),g(0),n(r),Array(8).fill(0),p(0),p(t.track.id),b("audio"===t.type?1:0),p(0),E(o),w("video"===t.type?t.info.width:0),w("video"===t.type?t.info.height:0)])},D=(t,e)=>U("mdia",void 0,[M(t,e),N(!0,L[t.type],R[t.type]),O(t)]),M=(t,e)=>{const i=T(t.samples),r=Qt(i?i.timestamp+i.duration:0,t.timescale),a=!(0,s.LD)(e)||!(0,s.LD)(r),n=a?_:g;return B("mdhd",+a,0,[n(e),n(e),g(t.timescale),n(r),p(Nt(t.track.metadata.languageCode??s.n3)),p(0)])},L={video:"vide",audio:"soun",subtitle:"text"},R={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},N=(t,e,i,r="\0\0\0\0")=>B("hdlr",0,0,[t?S("mhlr"):g(0),S(e),S(r),g(0),g(0),S(i,!0)]),O=t=>U("minf",void 0,[H[t.type](),V(),j(t)]),H={video:()=>B("vmhd",0,1,[p(0),p(0),p(0),p(0)]),audio:()=>B("smhd",0,0,[p(0),p(0)]),subtitle:()=>B("nmhd",0,0)},V=()=>U("dinf",void 0,[W()]),W=()=>B("dref",0,0,[g(1)],[G()]),G=()=>B("url ",0,1),j=t=>{const e=t.compositionTimeOffsetTable.length>1||t.compositionTimeOffsetTable.some(t=>0!==t.sampleCompositionTimeOffset);return U("stbl",void 0,[$(t),at(t),e?dt(t):null,e?lt(t):null,ot(t),ht(t),ct(t),nt(t)])},$=t=>{let e;if("video"===t.type)e=Y(zt(t.track.source._codec,t.info.decoderConfig.codec),t);else if("audio"===t.type){const i=Dt(t.track.source._codec,t.muxer.isQuickTime);(0,s.hu)(i),e=K(i,t)}else"subtitle"===t.type&&(e=st(Lt[t.track.source._codec],t));return(0,s.hu)(e),B("stsd",0,0,[g(1)],[e])},Y=(t,e)=>U(t,[Array(6).fill(0),p(1),p(0),p(0),Array(12).fill(0),p(e.info.width),p(e.info.height),g(4718592),g(4718592),g(0),p(1),Array(32).fill(0),p(24),f(65535)],[Ft[e.track.source._codec](e),(0,s.We)(e.info.decoderConfig.colorSpace)?q(e):null]),q=t=>U("colr",[S("nclx"),p(s.$9[t.info.decoderConfig.colorSpace.primaries]),p(s.V3[t.info.decoderConfig.colorSpace.transfer]),p(s.P0[t.info.decoderConfig.colorSpace.matrix]),u((t.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),Q=t=>{if(!t.info.decoderConfig)return null;const e=t.info.decoderConfig,i=e.codec.split("."),r=Number(i[1]),a=Number(i[2]),n=(Number(i[3])<<4)+((i[4]?Number(i[4]):1)<<1)+(i[8]?Number(i[8]):Number(e.colorSpace?.fullRange??0)),o=i[5]?Number(i[5]):e.colorSpace?.primaries?s.$9[e.colorSpace.primaries]:2,h=i[6]?Number(i[6]):e.colorSpace?.transfer?s.V3[e.colorSpace.transfer]:2,c=i[7]?Number(i[7]):e.colorSpace?.matrix?s.P0[e.colorSpace.matrix]:2;return B("vpcC",1,0,[u(r),u(a),u(n),u(o),u(h),u(c),p(0)])},K=(t,e)=>{let i,s=0,a=16;if(r.zE.includes(e.track.source._codec)){const t=e.track.source._codec,{sampleSize:i}=(0,r.AS)(t);a=8*i,a>16&&(s=1)}return i=0===s?[Array(6).fill(0),p(1),p(s),p(0),g(0),p(e.info.numberOfChannels),p(a),p(0),p(0),p(e.info.sampleRate<65536?e.info.sampleRate:0),p(0)]:[Array(6).fill(0),p(1),p(s),p(0),g(0),p(e.info.numberOfChannels),p(Math.min(a,16)),p(0),p(0),p(e.info.sampleRate<65536?e.info.sampleRate:0),p(0),g(1),g(a/8),g(e.info.numberOfChannels*a/8),g(2)],U(t,i,[Mt(e.track.source._codec,e.muxer.isQuickTime)?.(e)??null])},X=t=>{let e;switch(t.track.source._codec){case"aac":e=64;break;case"mp3":e=107;break;case"vorbis":e=221;break;default:throw new Error(`Unhandled audio codec: ${t.track.source._codec}`)}let i=[...u(e),...u(21),...m(0),...g(0),...g(0)];if(t.info.decoderConfig.description){const e=(0,s._f)(t.info.decoderConfig.description);i=[...i,...u(5),...k(e.byteLength),...e]}return i=[...p(1),...u(0),...u(4),...k(i.length),...i,...u(6),...u(1),...u(2)],i=[...u(3),...k(i.length),...i],B("esds",0,0,i)},Z=t=>U("wave",void 0,[J(t),tt(t),U("\0\0\0\0")]),J=t=>U("frma",[S(Dt(t.track.source._codec,t.muxer.isQuickTime))]),tt=t=>{const{littleEndian:e}=(0,r.AS)(t.track.source._codec);return U("enda",[p(+e)])},et=t=>{let e=t.info.numberOfChannels,i=3840,r=t.info.sampleRate,a=0,n=0,h=new Uint8Array(0);const c=t.info.decoderConfig?.description;if(c){(0,s.hu)(c.byteLength>=18);const t=(0,s._f)(c),d=(0,o.d)(t);e=d.outputChannelCount,i=d.preSkip,r=d.inputSampleRate,a=d.outputGain,n=d.channelMappingFamily,d.channelMappingTable&&(h=d.channelMappingTable)}return U("dOps",[u(0),u(e),p(i),g(r),f(a),u(n),...h])},it=t=>{const e=t.info.decoderConfig?.description;(0,s.hu)(e);const i=(0,s._f)(e);return B("dfLa",0,0,[...i.subarray(4)])},rt=t=>{const{littleEndian:e,sampleSize:i}=(0,r.AS)(t.track.source._codec);return B("pcmC",0,0,[u(+e),u(8*i)])},st=(t,e)=>U(t,[Array(6).fill(0),p(1)],[Rt[e.track.source._codec](e)]),at=t=>B("stts",0,0,[g(t.timeToSampleTable.length),t.timeToSampleTable.map(t=>[g(t.sampleCount),g(t.sampleDelta)])]),nt=t=>{if(t.samples.every(t=>"key"===t.type))return null;const e=[...t.samples.entries()].filter(([,t])=>"key"===t.type);return B("stss",0,0,[g(e.length),e.map(([t])=>g(t+1))])},ot=t=>B("stsc",0,0,[g(t.compactlyCodedChunkTable.length),t.compactlyCodedChunkTable.map(t=>[g(t.firstChunk),g(t.samplesPerChunk),g(1)])]),ht=t=>{if("audio"===t.type&&t.info.requiresPcmTransformation){const{sampleSize:e}=(0,r.AS)(t.track.source._codec);return B("stsz",0,0,[g(e*t.info.numberOfChannels),g(t.samples.reduce((e,i)=>e+Qt(i.duration,t.timescale),0))])}return B("stsz",0,0,[g(0),g(t.samples.length),t.samples.map(t=>g(t.size))])},ct=t=>t.finalizedChunks.length>0&&(0,s.Z$)(t.finalizedChunks).offset>=2**32?B("co64",0,0,[g(t.finalizedChunks.length),t.finalizedChunks.map(t=>_(t.offset))]):B("stco",0,0,[g(t.finalizedChunks.length),t.finalizedChunks.map(t=>g(t.offset))]),dt=t=>B("ctts",1,0,[g(t.compositionTimeOffsetTable.length),t.compositionTimeOffsetTable.map(t=>[g(t.sampleCount),y(t.sampleCompositionTimeOffset)])]),lt=t=>{let e=1/0,i=-1/0,r=1/0,a=-1/0;(0,s.hu)(t.compositionTimeOffsetTable.length>0),(0,s.hu)(t.samples.length>0);for(let r=0;r<t.compositionTimeOffsetTable.length;r++){const s=t.compositionTimeOffsetTable[r];e=Math.min(e,s.sampleCompositionTimeOffset),i=Math.max(i,s.sampleCompositionTimeOffset)}for(let e=0;e<t.samples.length;e++){const i=t.samples[e];r=Math.min(r,Qt(i.timestamp,t.timescale)),a=Math.max(a,Qt(i.timestamp+i.duration,t.timescale))}const n=Math.max(-e,0);return a>=2**31?null:B("cslg",0,0,[y(n),y(e),y(i),y(r),y(a)])},ut=t=>U("mvex",void 0,t.map(pt)),pt=t=>B("trex",0,0,[g(t.track.id),g(1),g(0),g(0),g(0)]),ft=(t,e)=>U("moof",void 0,[mt(t),...e.map(yt)]),mt=t=>B("mfhd",0,0,[g(t)]),gt=t=>{let e=0,i=0;const r="delta"===t.type;return i|=+r,e|=r?1:2,e<<24|i<<16},yt=t=>U("traf",void 0,[_t(t),bt(t),wt(t)]),_t=t=>{(0,s.hu)(t.currentChunk);let e=0;e|=8,e|=16,e|=32,e|=131072;const i=t.currentChunk.samples[1]??t.currentChunk.samples[0],r={duration:i.timescaleUnitsToNextSample,size:i.size,flags:gt(i)};return B("tfhd",0,131128,[g(t.track.id),g(r.duration),g(r.size),g(r.flags)])},bt=t=>((0,s.hu)(t.currentChunk),B("tfdt",1,0,[_(Qt(t.currentChunk.startTimestamp,t.timescale))])),wt=t=>{(0,s.hu)(t.currentChunk);const e=t.currentChunk.samples.map(t=>t.timescaleUnitsToNextSample),i=t.currentChunk.samples.map(t=>t.size),r=t.currentChunk.samples.map(gt),a=t.currentChunk.samples.map(e=>Qt(e.timestamp-e.decodeTimestamp,t.timescale)),n=new Set(e),o=new Set(i),h=new Set(r),c=new Set(a),d=2===h.size&&r[0]!==r[1],l=n.size>1,u=o.size>1,p=!d&&h.size>1,f=c.size>1||[...c].some(t=>0!==t);let m=0;return m|=1,m|=4*+d,m|=256*+l,m|=512*+u,m|=1024*+p,m|=2048*+f,B("trun",1,m,[g(t.currentChunk.samples.length),g(t.currentChunk.offset-t.currentChunk.moofOffset||0),d?g(r[0]):[],t.currentChunk.samples.map((t,s)=>[l?g(e[s]):[],u?g(i[s]):[],p?g(r[s]):[],f?y(a[s]):[]])])},vt=(t,e)=>B("tfra",1,0,[g(t.track.id),g(63),g(t.finalizedChunks.length),t.finalizedChunks.map(i=>[_(Qt(i.samples[0].timestamp,t.timescale)),_(i.moofOffset),g(e+1),g(1),g(1)])]),kt=()=>U("vtte"),St=(t,e,i,r,a)=>U("vttc",void 0,[null!==a?U("vsid",[y(a)]):null,null!==i?U("iden",[...s.oL.encode(i)]):null,null!==e?U("ctim",[...s.oL.encode(n(e))]):null,null!==r?U("sttg",[...s.oL.encode(r)]):null,U("payl",[...s.oL.encode(t)])]),Tt=t=>U("vtta",[...s.oL.encode(t)]),xt=t=>{const e=[],i=t.format._options.metadataFormat??"auto",r=t.output._metadataTags;if("mdir"===i||"auto"===i&&!t.isQuickTime){const t=At(r);t&&e.push(t)}else if("mdta"===i){const t=It(r);t&&e.push(t)}else("udta"===i||"auto"===i&&t.isQuickTime)&&Ct(e,t.output._metadataTags);return 0===e.length?null:U("udta",void 0,e)},Ct=(t,e)=>{for(const{key:i,value:r}of(0,s.lY)(e))switch(i){case"title":t.push(Et("©nam",r));break;case"description":t.push(Et("©des",r));break;case"artist":t.push(Et("©ART",r));break;case"album":t.push(Et("©alb",r));break;case"albumArtist":t.push(Et("albr",r));break;case"genre":t.push(Et("©gen",r));break;case"date":t.push(Et("©day",r.toISOString().slice(0,10)));break;case"comment":t.push(Et("©cmt",r));break;case"lyrics":t.push(Et("©lyr",r));break;case"raw":case"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"images":break;default:(0,s.vE)(i)}if(e.raw)for(const i in e.raw){const r=e.raw[i];null==r||4!==i.length||t.some(t=>t.type===i)||("string"==typeof r?t.push(Et(i,r)):r instanceof Uint8Array&&t.push(U(i,Array.from(r))))}},Et=(t,e)=>{const i=s.oL.encode(e);return U(t,[p(i.length),p(Nt("und")),Array.from(i)])},Ut={"image/jpeg":13,"image/png":14,"image/bmp":27},Bt=(t,e)=>{const i=[];for(const{key:r,value:a}of(0,s.lY)(t))switch(r){case"title":i.push({key:e?"title":"©nam",value:Pt(a)});break;case"description":i.push({key:e?"description":"©des",value:Pt(a)});break;case"artist":i.push({key:e?"artist":"©ART",value:Pt(a)});break;case"album":i.push({key:e?"album":"©alb",value:Pt(a)});break;case"albumArtist":i.push({key:e?"album_artist":"aART",value:Pt(a)});break;case"comment":i.push({key:e?"comment":"©cmt",value:Pt(a)});break;case"genre":i.push({key:e?"genre":"©gen",value:Pt(a)});break;case"lyrics":i.push({key:e?"lyrics":"©lyr",value:Pt(a)});break;case"date":i.push({key:e?"date":"©day",value:Pt(a.toISOString().slice(0,10))});break;case"images":for(const t of a)"coverFront"===t.kind&&i.push({key:"covr",value:U("data",[g(Ut[t.mimeType]??0),g(0),Array.from(t.data)])});break;case"trackNumber":if(e){const e=void 0!==t.tracksTotal?`${a}/${t.tracksTotal}`:a.toString();i.push({key:"track",value:Pt(e)})}else i.push({key:"trkn",value:U("data",[g(0),g(0),p(0),p(a),p(t.tracksTotal??0),p(0)])});break;case"discNumber":e||i.push({key:"disc",value:U("data",[g(0),g(0),p(0),p(a),p(t.discsTotal??0),p(0)])});break;case"tracksTotal":case"discsTotal":case"raw":break;default:(0,s.vE)(r)}if(t.raw)for(const r in t.raw){const s=t.raw[r];null==s||!e&&4!==r.length||i.some(t=>t.key===r)||("string"==typeof s?i.push({key:r,value:Pt(s)}):s instanceof Uint8Array?i.push({key:r,value:U("data",[g(0),g(0),Array.from(s)])}):s instanceof h.jC&&i.push({key:r,value:U("data",[g(Ut[s.mimeType]??0),g(0),Array.from(s.data)])}))}return i},At=t=>{const e=Bt(t,!1);return 0===e.length?null:B("meta",0,0,void 0,[N(!1,"mdir","","appl"),U("ilst",void 0,e.map(t=>U(t.key,void 0,[t.value])))])},It=t=>{const e=Bt(t,!0);return 0===e.length?null:U("meta",void 0,[N(!1,"mdta",""),B("keys",0,0,[g(e.length)],e.map(t=>U("mdta",[...s.oL.encode(t.key)]))),U("ilst",void 0,e.map((t,e)=>{const i=String.fromCharCode(...g(e+1));return U(i,void 0,[t.value])}))])},Pt=t=>U("data",[g(1),g(0),...s.oL.encode(t)]),zt=(t,e)=>{switch(t){case"avc":return e.startsWith("avc3")?"avc3":"avc1";case"hevc":return"hvc1";case"vp8":return"vp08";case"vp9":return"vp09";case"av1":return"av01"}},Ft={avc:t=>t.info.decoderConfig&&U("avcC",[...(0,s._f)(t.info.decoderConfig.description)]),hevc:t=>t.info.decoderConfig&&U("hvcC",[...(0,s._f)(t.info.decoderConfig.description)]),vp8:Q,vp9:Q,av1:t=>U("av1C",(0,r.no)(t.info.decoderConfig.codec))},Dt=(t,e)=>{switch(t){case"aac":case"mp3":case"vorbis":return"mp4a";case"opus":return"Opus";case"flac":return"fLaC";case"ulaw":return"ulaw";case"alaw":return"alaw";case"pcm-u8":return"raw ";case"pcm-s8":return"sowt"}if(e)switch(t){case"pcm-s16":return"sowt";case"pcm-s16be":return"twos";case"pcm-s24":case"pcm-s24be":return"in24";case"pcm-s32":case"pcm-s32be":return"in32";case"pcm-f32":case"pcm-f32be":return"fl32";case"pcm-f64":case"pcm-f64be":return"fl64"}else switch(t){case"pcm-s16":case"pcm-s16be":case"pcm-s24":case"pcm-s24be":case"pcm-s32":case"pcm-s32be":return"ipcm";case"pcm-f32":case"pcm-f32be":case"pcm-f64":case"pcm-f64be":return"fpcm"}},Mt=(t,e)=>{switch(t){case"aac":case"mp3":case"vorbis":return X;case"opus":return et;case"flac":return it}if(e)switch(t){case"pcm-s24":case"pcm-s24be":case"pcm-s32":case"pcm-s32be":case"pcm-f32":case"pcm-f32be":case"pcm-f64":case"pcm-f64be":return Z}else switch(t){case"pcm-s16":case"pcm-s16be":case"pcm-s24":case"pcm-s24be":case"pcm-s32":case"pcm-s32be":case"pcm-f32":case"pcm-f32be":case"pcm-f64":case"pcm-f64be":return rt}return null},Lt={webvtt:"wvtt"},Rt={webvtt:t=>U("vttC",[...s.oL.encode(t.info.config.description)])},Nt=t=>{(0,s.hu)(3===t.length);let e=0;for(let i=0;i<3;i++)e<<=5,e+=t.charCodeAt(i)-96;return e};class Ot{constructor(t){this.mutex=new s.q9,this.firstMediaStreamTimestamp=null,this.trackTimestampInfo=new WeakMap,this.output=t}onTrackClose(t){}validateAndNormalizeTimestamp(t,e,i){e+=t.source._timestampOffset;let r=this.trackTimestampInfo.get(t);if(!r){if(!i)throw new Error("First packet must be a key packet.");r={maxTimestamp:e,maxTimestampBeforeLastKeyPacket:e},this.trackTimestampInfo.set(t,r)}if(e<0)throw new Error(`Timestamps must be non-negative (got ${e}s).`);if(i&&(r.maxTimestampBeforeLastKeyPacket=r.maxTimestamp),e<r.maxTimestampBeforeLastKeyPacket)throw new Error(`Timestamps cannot be smaller than the largest timestamp of the previous GOP (a GOP begins with a key packet and ends right before the next key packet). Got ${e}s, but largest timestamp is ${r.maxTimestampBeforeLastKeyPacket}s.`);return r.maxTimestamp=Math.max(r.maxTimestamp,e),e}}var Ht=i(840),Vt=i(273),Wt=i(481),Gt=i(709),jt=i(370),$t=i(267);const Yt=1e3,qt=t=>{const e={},i=t.track;return void 0!==i.metadata.name&&(e.name=i.metadata.name),e},Qt=(t,e,i=!0)=>{const r=t*e;return i?Math.round(r):r};class Kt extends Ot{constructor(t,e){super(t),this.auxTarget=new Gt.Vl,this.auxWriter=this.auxTarget._createWriter(),this.auxBoxWriter=new c(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=(0,s.Bw)(),this.creationTime=Math.floor(Date.now()/1e3)+2082844800,this.finalizedChunks=[],this.nextFragmentNumber=1,this.maxWrittenTimestamp=-1/0,this.format=e,this.writer=t._writer,this.boxWriter=new c(this.writer),this.isQuickTime=e instanceof te;const i=this.writer instanceof Ht.Ak&&"in-memory";this.fastStart=e._options.fastStart??i,this.isFragmented="fragmented"===this.fastStart,("in-memory"===this.fastStart||this.isFragmented)&&(this.writer.ensureMonotonicity=!0),this.minimumFragmentDuration=e._options.minimumFragmentDuration??1}async start(){const t=await this.mutex.acquire(),e=this.output._tracks.some(t=>"video"===t.type&&"avc"===t.source._codec);if(this.format._options.onFtyp&&this.writer.startTrackingWrites(),this.boxWriter.writeBox((i={isQuickTime:this.isQuickTime,holdsAvc:e,fragmented:this.isFragmented}).isQuickTime?U("ftyp",[S("qt "),g(512),S("qt ")]):U("ftyp",i.fragmented?[S("iso5"),g(512),S("iso5"),S("iso6"),S("mp41")]:[S("isom"),g(512),S("isom"),i.holdsAvc?S("avc1"):[],S("mp41")])),this.format._options.onFtyp){const{data:t,start:e}=this.writer.stopTrackingWrites();this.format._options.onFtyp(t,e)}var i;if(this.ftypSize=this.writer.getPos(),"in-memory"===this.fastStart);else if("reserve"===this.fastStart){for(const t of this.output._tracks)if(void 0===t.metadata.maximumPacketCount)throw new Error("All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.")}else this.isFragmented||(this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=A(!0),this.boxWriter.writeBox(this.mdat));await this.writer.flush(),t()}allTracksAreKnown(){for(const t of this.output._tracks)if(!t.source._closed&&!this.trackDatas.some(e=>e.track===t))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;const t=this.trackDatas.map(t=>"video"===t.type||"audio"===t.type?t.info.decoderConfig.codec:{webvtt:"wvtt"}[t.track.source._codec]);return(0,jt.o)({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(t=>"video"===t.type),hasAudio:this.trackDatas.some(t=>"audio"===t.type),codecStrings:t})}getVideoTrackData(t,e,i){const a=this.trackDatas.find(e=>e.track===t);if(a)return a;(0,r.Wn)(i),(0,s.hu)(i),(0,s.hu)(i.decoderConfig);const n={...i.decoderConfig};(0,s.hu)(void 0!==n.codedWidth),(0,s.hu)(void 0!==n.codedHeight);let h=!1;if("avc"!==t.source._codec||n.description){if("hevc"===t.source._codec&&!n.description){const t=(0,o.BW)(e.data);if(!t)throw new Error("Couldn't extract an HEVCDecoderConfigurationRecord from the HEVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.265) when not providing a description, or provide a description (must be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in HEVC format.");n.description=(0,o.H)(t),h=!0}}else{const t=(0,o.E3)(e.data);if(!t)throw new Error("Couldn't extract an AVCDecoderConfigurationRecord from the AVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.264) when not providing a description, or provide a description (must be an AVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in AVCC format.");n.description=(0,o.RG)(t),h=!0}const c=(0,s.Ih)(1/(t.metadata.frameRate??57600),1e6).denominator,d={muxer:this,track:t,type:"video",info:{width:n.codedWidth,height:n.codedHeight,decoderConfig:n,requiresAnnexBTransformation:h},timescale:c,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};return this.trackDatas.push(d),this.trackDatas.sort((t,e)=>t.track.id-e.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),d}getAudioTrackData(t,e,i){const a=this.trackDatas.find(e=>e.track===t);if(a)return a;(0,r.NQ)(i),(0,s.hu)(i),(0,s.hu)(i.decoderConfig);const n={...i.decoderConfig};let o=!1;if("aac"===t.source._codec&&!n.description){const t=(0,Vt.gM)(Wt.CJ.tempFromBytes(e.data));if(!t)throw new Error("Couldn't parse ADTS header from the AAC packet. Make sure the packets are in ADTS format (as specified in ISO 13818-7) when not providing a description, or provide a description (must be an AudioSpecificConfig as specified in ISO 14496-3) and ensure the packets are raw AAC data.");const i=r.v6[t.samplingFrequencyIndex],s=r.y7[t.channelConfiguration];if(void 0===i||void 0===s)throw new Error("Invalid ADTS frame header.");n.description=(0,r.QK)({objectType:t.objectType,sampleRate:i,numberOfChannels:s}),o=!0}const h={muxer:this,track:t,type:"audio",info:{numberOfChannels:i.decoderConfig.numberOfChannels,sampleRate:i.decoderConfig.sampleRate,decoderConfig:n,requiresPcmTransformation:!this.isFragmented&&r.zE.includes(t.source._codec),requiresAdtsStripping:o},timescale:i.decoderConfig.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};return this.trackDatas.push(h),this.trackDatas.sort((t,e)=>t.track.id-e.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),h}getSubtitleTrackData(t,e){const i=this.trackDatas.find(e=>e.track===t);if(i)return i;(0,r.sG)(e),(0,s.hu)(e),(0,s.hu)(e.config);const a={muxer:this,track:t,type:"subtitle",info:{config:e.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],lastCueEndTimestamp:0,cueQueue:[],nextSourceId:0,cueToSourceId:new WeakMap};return this.trackDatas.push(a),this.trackDatas.sort((t,e)=>t.track.id-e.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),a}async addEncodedVideoPacket(t,e,i){const r=await this.mutex.acquire();try{const r=this.getVideoTrackData(t,e,i);let s=e.data;if(r.info.requiresAnnexBTransformation){const t=[...(0,o.bO)(s)].map(t=>s.subarray(t.offset,t.offset+t.length));if(0===t.length)throw new Error("Failed to transform packet data. Make sure all packets are provided in Annex B format, as specified in ITU-T-REC-H.264 and ITU-T-REC-H.265.");s=(0,o.Q3)(t,4)}const a=this.validateAndNormalizeTimestamp(r.track,e.timestamp,"key"===e.type),n=this.createSampleForTrack(r,s,a,e.duration,e.type);await this.registerSample(r,n)}finally{r()}}async addEncodedAudioPacket(t,e,i){const r=await this.mutex.acquire();try{const r=this.getAudioTrackData(t,e,i);let s=e.data;if(r.info.requiresAdtsStripping){const t=(0,Vt.gM)(Wt.CJ.tempFromBytes(s));if(!t)throw new Error("Expected ADTS frame, didn't get one.");const e=null===t.crcCheck?Vt.Ls:Vt.MB;s=s.subarray(e)}const a=this.validateAndNormalizeTimestamp(r.track,e.timestamp,"key"===e.type),n=this.createSampleForTrack(r,s,a,e.duration,e.type);r.info.requiresPcmTransformation&&await this.maybePadWithSilence(r,a),await this.registerSample(r,n)}finally{r()}}async maybePadWithSilence(t,e){const i=(0,s.Z$)(t.samples),a=i?i.timestamp+i.duration:0,n=e-a,o=Qt(n,t.timescale);if(o>0){const{sampleSize:e,silentValue:i}=(0,r.AS)(t.info.decoderConfig.codec),s=o*t.info.numberOfChannels,h=new Uint8Array(e*s).fill(i),c=this.createSampleForTrack(t,new Uint8Array(h.buffer),a,n,"key");await this.registerSample(t,c)}}async addSubtitleCue(t,e,i){const r=await this.mutex.acquire();try{const r=this.getSubtitleTrackData(t,i);this.validateAndNormalizeTimestamp(r.track,e.timestamp,!0),"webvtt"===t.source._codec&&(r.cueQueue.push(e),await this.processWebVTTCues(r,e.timestamp))}finally{r()}}async processWebVTTCues(t,e){for(;t.cueQueue.length>0;){const i=new Set([]);for(const r of t.cueQueue)(0,s.hu)(r.timestamp<=e),(0,s.hu)(t.lastCueEndTimestamp<=r.timestamp+r.duration),i.add(Math.max(r.timestamp,t.lastCueEndTimestamp)),i.add(r.timestamp+r.duration);const r=[...i].sort((t,e)=>t-e),n=r[0],o=r[1]??n;if(e<o)break;if(t.lastCueEndTimestamp<n){this.auxWriter.seek(0);const e=kt();this.auxBoxWriter.writeBox(e);const i=this.auxWriter.getSlice(0,this.auxWriter.getPos()),r=this.createSampleForTrack(t,i,t.lastCueEndTimestamp,n-t.lastCueEndTimestamp,"key");await this.registerSample(t,r),t.lastCueEndTimestamp=n}this.auxWriter.seek(0);for(let e=0;e<t.cueQueue.length;e++){const i=t.cueQueue[e];if(i.timestamp>=o)break;a.lastIndex=0;const r=a.test(i.text),s=i.timestamp+i.duration;let h=t.cueToSourceId.get(i);if(void 0===h&&o<s&&(h=t.nextSourceId++,t.cueToSourceId.set(i,h)),i.notes){const t=Tt(i.notes);this.auxBoxWriter.writeBox(t)}const c=St(i.text,r?n:null,i.identifier??null,i.settings??null,h??null);this.auxBoxWriter.writeBox(c),s===o&&t.cueQueue.splice(e--,1)}const h=this.auxWriter.getSlice(0,this.auxWriter.getPos()),c=this.createSampleForTrack(t,h,n,o-n,"key");await this.registerSample(t,c),t.lastCueEndTimestamp=o}}createSampleForTrack(t,e,i,r,s){return{timestamp:i,decodeTimestamp:i,duration:r,data:e,size:e.byteLength,type:s,timescaleUnitsToNextSample:Qt(r,t.timescale)}}processTimestamps(t,e){if(0===t.timestampProcessingQueue.length)return;if("audio"===t.type&&t.info.requiresPcmTransformation){let e=0;for(let i=0;i<t.timestampProcessingQueue.length;i++){const r=t.timestampProcessingQueue[i];e+=Qt(r.duration,t.timescale)}return 0===t.timeToSampleTable.length?t.timeToSampleTable.push({sampleCount:e,sampleDelta:1}):(0,s.Z$)(t.timeToSampleTable).sampleCount+=e,void(t.timestampProcessingQueue.length=0)}const i=t.timestampProcessingQueue.map(t=>t.timestamp).sort((t,e)=>t-e);for(let e=0;e<t.timestampProcessingQueue.length;e++){const r=t.timestampProcessingQueue[e];r.decodeTimestamp=i[e],this.isFragmented||null!==t.lastTimescaleUnits||(r.decodeTimestamp=0);const a=Qt(r.timestamp-r.decodeTimestamp,t.timescale),n=Qt(r.duration,t.timescale);if(null!==t.lastTimescaleUnits){(0,s.hu)(t.lastSample);const e=Qt(r.decodeTimestamp,t.timescale,!1),i=Math.round(e-t.lastTimescaleUnits);if((0,s.hu)(i>=0),t.lastTimescaleUnits+=i,t.lastSample.timescaleUnitsToNextSample=i,!this.isFragmented){let e=(0,s.Z$)(t.timeToSampleTable);if((0,s.hu)(e),1===e.sampleCount){e.sampleDelta=i;const r=t.timeToSampleTable[t.timeToSampleTable.length-2];r&&r.sampleDelta===i&&(r.sampleCount++,t.timeToSampleTable.pop(),e=r)}else e.sampleDelta!==i&&(e.sampleCount--,t.timeToSampleTable.push(e={sampleCount:1,sampleDelta:i}));e.sampleDelta===n?e.sampleCount++:t.timeToSampleTable.push({sampleCount:1,sampleDelta:n});const r=(0,s.Z$)(t.compositionTimeOffsetTable);(0,s.hu)(r),r.sampleCompositionTimeOffset===a?r.sampleCount++:t.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:a})}}else t.lastTimescaleUnits=Qt(r.decodeTimestamp,t.timescale,!1),this.isFragmented||(t.timeToSampleTable.push({sampleCount:1,sampleDelta:n}),t.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:a}));t.lastSample=r}if(t.timestampProcessingQueue.length=0,(0,s.hu)(t.lastSample),(0,s.hu)(null!==t.lastTimescaleUnits),void 0!==e&&0===t.lastSample.timescaleUnitsToNextSample){(0,s.hu)("key"===e.type);const i=Qt(e.timestamp,t.timescale,!1),r=Math.round(i-t.lastTimescaleUnits);t.lastSample.timescaleUnitsToNextSample=r}}async registerSample(t,e){"key"===e.type&&this.processTimestamps(t,e),t.timestampProcessingQueue.push(e),this.isFragmented?(t.sampleQueue.push(e),await this.interleaveSamples()):"reserve"===this.fastStart?await this.registerSampleFastStartReserve(t,e):await this.addSampleToTrack(t,e)}async addSampleToTrack(t,e){if(!this.isFragmented&&(t.samples.push(e),"reserve"===this.fastStart)){const e=t.track.metadata.maximumPacketCount;if((0,s.hu)(void 0!==e),t.samples.length>e)throw new Error(`Track #${t.track.id} has already reached the maximum packet count (${e}). Either add less packets or increase the maximum packet count.`)}let i=!1;if(t.currentChunk){t.currentChunk.startTimestamp=Math.min(t.currentChunk.startTimestamp,e.timestamp);const r=e.timestamp-t.currentChunk.startTimestamp;if(this.isFragmented){const s=this.trackDatas.every(i=>{if(t===i)return"key"===e.type;const r=i.sampleQueue[0];return r?"key"===r.type:i.track.source._closed});r>=this.minimumFragmentDuration&&s&&e.timestamp>this.maxWrittenTimestamp&&(i=!0,await this.finalizeFragment())}else i=r>=.5}else i=!0;i&&(t.currentChunk&&await this.finalizeCurrentChunk(t),t.currentChunk={startTimestamp:e.timestamp,samples:[],offset:null,moofOffset:null}),(0,s.hu)(t.currentChunk),t.currentChunk.samples.push(e),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,e.timestamp))}async finalizeCurrentChunk(t){if((0,s.hu)(!this.isFragmented),!t.currentChunk)return;t.finalizedChunks.push(t.currentChunk),this.finalizedChunks.push(t.currentChunk);let e=t.currentChunk.samples.length;if("audio"===t.type&&t.info.requiresPcmTransformation&&(e=t.currentChunk.samples.reduce((e,i)=>e+Qt(i.duration,t.timescale),0)),0!==t.compactlyCodedChunkTable.length&&(0,s.Z$)(t.compactlyCodedChunkTable).samplesPerChunk===e||t.compactlyCodedChunkTable.push({firstChunk:t.finalizedChunks.length,samplesPerChunk:e}),"in-memory"!==this.fastStart){t.currentChunk.offset=this.writer.getPos();for(const e of t.currentChunk.samples)(0,s.hu)(e.data),this.writer.write(e.data),e.data=null;await this.writer.flush()}else t.currentChunk.offset=0}async interleaveSamples(t=!1){if((0,s.hu)(this.isFragmented),t||this.allTracksAreKnown())t:for(;;){let e=null,i=1/0;for(const r of this.trackDatas){if(!t&&0===r.sampleQueue.length&&!r.track.source._closed)break t;r.sampleQueue.length>0&&r.sampleQueue[0].timestamp<i&&(e=r,i=r.sampleQueue[0].timestamp)}if(!e)break;const r=e.sampleQueue.shift();await this.addSampleToTrack(e,r)}}async finalizeFragment(t=!0){(0,s.hu)(this.isFragmented);const e=this.nextFragmentNumber++;if(1===e){this.format._options.onMoov&&this.writer.startTrackingWrites();const t=I(this);if(this.boxWriter.writeBox(t),this.format._options.onMoov){const{data:t,start:e}=this.writer.stopTrackingWrites();this.format._options.onMoov(t,e)}}const i=this.trackDatas.filter(t=>t.currentChunk),r=ft(e,i),a=this.writer.getPos(),n=a+this.boxWriter.measureBox(r);let o=n+$t.PM,h=1/0;for(const t of i){t.currentChunk.offset=o,t.currentChunk.moofOffset=a;for(const e of t.currentChunk.samples)o+=e.size;h=Math.min(h,t.currentChunk.startTimestamp)}const c=o-n,d=c>=2**32;if(d)for(const t of i)t.currentChunk.offset+=$t.cq-$t.PM;this.format._options.onMoof&&this.writer.startTrackingWrites();const l=ft(e,i);if(this.boxWriter.writeBox(l),this.format._options.onMoof){const{data:t,start:e}=this.writer.stopTrackingWrites();this.format._options.onMoof(t,e,h)}(0,s.hu)(this.writer.getPos()===n),this.format._options.onMdat&&this.writer.startTrackingWrites();const u=A(d);u.size=c,this.boxWriter.writeBox(u),this.writer.seek(n+(d?$t.cq:$t.PM));for(const t of i)for(const e of t.currentChunk.samples)this.writer.write(e.data),e.data=null;if(this.format._options.onMdat){const{data:t,start:e}=this.writer.stopTrackingWrites();this.format._options.onMdat(t,e)}for(const t of i)t.finalizedChunks.push(t.currentChunk),this.finalizedChunks.push(t.currentChunk),t.currentChunk=null;t&&await this.writer.flush()}async registerSampleFastStartReserve(t,e){if(this.allTracksAreKnown()){if(!this.mdat){const t=I(this),e=this.boxWriter.measureBox(t)+this.computeSampleTableSizeUpperBound()+4096;(0,s.hu)(null!==this.ftypSize),this.writer.seek(this.ftypSize+e),this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=A(!0),this.boxWriter.writeBox(this.mdat);for(const t of this.trackDatas){for(const e of t.sampleQueue)await this.addSampleToTrack(t,e);t.sampleQueue.length=0}}await this.addSampleToTrack(t,e)}else t.sampleQueue.push(e)}computeSampleTableSizeUpperBound(){(0,s.hu)("reserve"===this.fastStart);let t=0;for(const e of this.trackDatas){const i=e.track.metadata.maximumPacketCount;(0,s.hu)(void 0!==i),t+=8*Math.ceil(2/3*i),t+=4*i,t+=8*Math.ceil(2/3*i),t+=12*Math.ceil(2/3*i),t+=4*i,t+=8*i}return t}async onTrackClose(t){const e=await this.mutex.acquire();if("subtitle"===t.type&&"webvtt"===t.source._codec){const e=this.trackDatas.find(e=>e.track===t);e&&await this.processWebVTTCues(e,1/0)}this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),e()}async finalize(){const t=await this.mutex.acquire();this.allTracksKnown.resolve();for(const t of this.trackDatas)"subtitle"===t.type&&"webvtt"===t.track.source._codec&&await this.processWebVTTCues(t,1/0);if(this.isFragmented){await this.interleaveSamples(!0);for(const t of this.trackDatas)this.processTimestamps(t);await this.finalizeFragment(!1)}else for(const t of this.trackDatas)this.processTimestamps(t),await this.finalizeCurrentChunk(t);if("in-memory"===this.fastStart){let t;this.mdat=A(!1);for(let e=0;e<2;e++){const e=I(this),i=this.boxWriter.measureBox(e);t=this.boxWriter.measureBox(this.mdat);let r=this.writer.getPos()+i+t;for(const e of this.finalizedChunks){e.offset=r;for(const{data:i}of e.samples)(0,s.hu)(i),r+=i.byteLength,t+=i.byteLength}if(r<2**32)break;t>=2**32&&(this.mdat.largeSize=!0)}this.format._options.onMoov&&this.writer.startTrackingWrites();const e=I(this);if(this.boxWriter.writeBox(e),this.format._options.onMoov){const{data:t,start:e}=this.writer.stopTrackingWrites();this.format._options.onMoov(t,e)}this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=t,this.boxWriter.writeBox(this.mdat);for(const t of this.finalizedChunks)for(const e of t.samples)(0,s.hu)(e.data),this.writer.write(e.data),e.data=null;if(this.format._options.onMdat){const{data:t,start:e}=this.writer.stopTrackingWrites();this.format._options.onMdat(t,e)}}else if(this.isFragmented){const t=this.writer.getPos(),i=(e=this.trackDatas,U("mfra",void 0,[...e.map(vt),B("mfro",0,0,[g(0)])]));this.boxWriter.writeBox(i);const r=this.writer.getPos()-t;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(r)}else{(0,s.hu)(this.mdat);const t=this.boxWriter.offsets.get(this.mdat);(0,s.hu)(void 0!==t);const e=this.writer.getPos()-t;if(this.mdat.size=e,this.mdat.largeSize=e>=2**32,this.boxWriter.patchBox(this.mdat),this.format._options.onMdat){const{data:t,start:e}=this.writer.stopTrackingWrites();this.format._options.onMdat(t,e)}const i=I(this);if("reserve"===this.fastStart){(0,s.hu)(null!==this.ftypSize),this.writer.seek(this.ftypSize),this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(i);const t=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox({type:"free",size:t})}else this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(i);if(this.format._options.onMoov){const{data:t,start:e}=this.writer.stopTrackingWrites();this.format._options.onMoov(t,e)}}var e;t()}}class Xt{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(t=>r.Au.includes(t))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(t=>r.eY.includes(t))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(t=>r.tW.includes(t))}_codecUnsupportedHint(t){return""}}class Zt extends Xt{constructor(t={}){if(!t||"object"!=typeof t)throw new TypeError("options must be an object.");if(void 0!==t.fastStart&&![!1,"in-memory","reserve","fragmented"].includes(t.fastStart))throw new TypeError("options.fastStart, when provided, must be false, 'in-memory', 'reserve', or 'fragmented'.");if(void 0!==t.minimumFragmentDuration&&(!Number.isFinite(t.minimumFragmentDuration)||t.minimumFragmentDuration<0))throw new TypeError("options.minimumFragmentDuration, when provided, must be a non-negative number.");if(void 0!==t.onFtyp&&"function"!=typeof t.onFtyp)throw new TypeError("options.onFtyp, when provided, must be a function.");if(void 0!==t.onMoov&&"function"!=typeof t.onMoov)throw new TypeError("options.onMoov, when provided, must be a function.");if(void 0!==t.onMdat&&"function"!=typeof t.onMdat)throw new TypeError("options.onMdat, when provided, must be a function.");if(void 0!==t.onMoof&&"function"!=typeof t.onMoof)throw new TypeError("options.onMoof, when provided, must be a function.");if(void 0!==t.metadataFormat&&!["mdir","mdta","udta","auto"].includes(t.metadataFormat))throw new TypeError("options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.");super(),this._options=t}getSupportedTrackCounts(){const t=2**32-1;return{video:{min:0,max:t},audio:{min:0,max:t},subtitle:{min:0,max:t},total:{min:1,max:t}}}get supportsVideoRotationMetadata(){return!0}_createMuxer(t){return new Kt(t,this)}}class Jt extends Zt{constructor(t){super(t)}get _name(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...r.Au,...r.Vr,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...r.tW]}_codecUnsupportedHint(t){return(new te).getSupportedCodecs().includes(t)?" Switching to MOV will grant support for this codec.":""}}class te extends Zt{constructor(t){super(t)}get _name(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...r.Au,...r.eY]}_codecUnsupportedHint(t){return(new Jt).getSupportedCodecs().includes(t)?" Switching to MP4 will grant support for this codec.":""}}},192:(t,e,i)=>{i.d(e,{r:()=>d});var r=i(583),s=i(653),a=i(547),n=i(689),o=i(709);const h=["video","audio","subtitle"],c=t=>{if(!t||"object"!=typeof t)throw new TypeError("metadata must be an object.");if(void 0!==t.languageCode&&!(0,r.Rh)(t.languageCode))throw new TypeError("metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.");if(void 0!==t.name&&"string"!=typeof t.name)throw new TypeError("metadata.name, when provided, must be a string.");if(void 0!==t.disposition&&(0,s.kG)(t.disposition),void 0!==t.maximumPacketCount&&(!Number.isInteger(t.maximumPacketCount)||t.maximumPacketCount<0))throw new TypeError("metadata.maximumPacketCount, when provided, must be a non-negative integer.")};class d{constructor(t){if(this.state="pending",this._tracks=[],this._startPromise=null,this._cancelPromise=null,this._finalizePromise=null,this._mutex=new r.q9,this._metadataTags={},!t||"object"!=typeof t)throw new TypeError("options must be an object.");if(!(t.format instanceof a.WJ))throw new TypeError("options.format must be an OutputFormat.");if(!(t.target instanceof o.Vz))throw new TypeError("options.target must be a Target.");if(t.target._output)throw new Error("Target is already used for another output.");t.target._output=this,this.format=t.format,this.target=t.target,this._writer=t.target._createWriter(),this._muxer=t.format._createMuxer(this)}addVideoTrack(t,e={}){if(!(t instanceof n.LG))throw new TypeError("source must be a VideoSource.");if(c(e),void 0!==e.rotation&&![0,90,180,270].includes(e.rotation))throw new TypeError(`Invalid video rotation: ${e.rotation}. Has to be 0, 90, 180 or 270.`);if(!this.format.supportsVideoRotationMetadata&&e.rotation)throw new Error(`${this.format._name} does not support video rotation metadata.`);if(void 0!==e.frameRate&&(!Number.isFinite(e.frameRate)||e.frameRate<=0))throw new TypeError(`Invalid video frame rate: ${e.frameRate}. Must be a positive number.`);this._addTrack("video",t,e)}addAudioTrack(t,e={}){if(!(t instanceof n.CS))throw new TypeError("source must be an AudioSource.");c(e),this._addTrack("audio",t,e)}addSubtitleTrack(t,e={}){if(!(t instanceof n.$8))throw new TypeError("source must be a SubtitleSource.");c(e),this._addTrack("subtitle",t,e)}setMetadataTags(t){if((0,s.RE)(t),"pending"!==this.state)throw new Error("Cannot set metadata tags after output has been started or canceled.");this._metadataTags=t}_addTrack(t,e,i){if("pending"!==this.state)throw new Error("Cannot add track after output has been started or canceled.");if(e._connectedTrack)throw new Error("Source is already used for a track.");const r=this.format.getSupportedTrackCounts(),s=this._tracks.reduce((e,i)=>e+(i.type===t?1:0),0),a=r[t].max;if(s===a)throw new Error(0===a?`${this.format._name} does not support ${t} tracks.`:`${this.format._name} does not support more than ${a} ${t} track`+(1===a?"":"s")+".");const n=r.total.max;if(this._tracks.length===n)throw new Error(`${this.format._name} does not support more than ${n} tracks`+(1===n?"":"s")+" in total.");const o={id:this._tracks.length+1,output:this,type:t,source:e,metadata:i};if("video"===o.type){const t=this.format.getSupportedVideoCodecs();if(0===t.length)throw new Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(o.source._codec));if(!t.includes(o.source._codec))throw new Error(`Codec '${o.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${t.map(t=>`'${t}'`).join(", ")}.`+this.format._codecUnsupportedHint(o.source._codec))}else if("audio"===o.type){const t=this.format.getSupportedAudioCodecs();if(0===t.length)throw new Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(o.source._codec));if(!t.includes(o.source._codec))throw new Error(`Codec '${o.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${t.map(t=>`'${t}'`).join(", ")}.`+this.format._codecUnsupportedHint(o.source._codec))}else if("subtitle"===o.type){const t=this.format.getSupportedSubtitleCodecs();if(0===t.length)throw new Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(o.source._codec));if(!t.includes(o.source._codec))throw new Error(`Codec '${o.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${t.map(t=>`'${t}'`).join(", ")}.`+this.format._codecUnsupportedHint(o.source._codec))}this._tracks.push(o),e._connectedTrack=o}async start(){const t=this.format.getSupportedTrackCounts();for(const e of h){const i=this._tracks.reduce((t,i)=>t+(i.type===e?1:0),0),r=t[e].min;if(i<r)throw new Error(r===t[e].max?`${this.format._name} requires exactly ${r} ${e} track${1===r?"":"s"}.`:`${this.format._name} requires at least ${r} ${e} track${1===r?"":"s"}.`)}const e=t.total.min;if(this._tracks.length<e)throw new Error(e===t.total.max?`${this.format._name} requires exactly ${e} track`+(1===e?"":"s")+".":`${this.format._name} requires at least ${e} track`+(1===e?"":"s")+".");if("canceled"===this.state)throw new Error("Output has been canceled.");return this._startPromise?(console.warn("Output has already been started."),this._startPromise):this._startPromise=(async()=>{this.state="started",this._writer.start();const t=await this._mutex.acquire();await this._muxer.start();const e=this._tracks.map(t=>t.source._start());await Promise.all(e),t()})()}getMimeType(){return this._muxer.getMimeType()}async cancel(){return this._cancelPromise?(console.warn("Output has already been canceled."),this._cancelPromise):"finalizing"!==this.state&&"finalized"!==this.state?this._cancelPromise=(async()=>{this.state="canceled";const t=await this._mutex.acquire(),e=this._tracks.map(t=>t.source._flushOrWaitForOngoingClose(!0));await Promise.all(e),await this._writer.close(),t()})():void console.warn("Output has already been finalized.")}async finalize(){if("pending"===this.state)throw new Error("Cannot finalize before starting.");if("canceled"===this.state)throw new Error("Cannot finalize after canceling.");return this._finalizePromise?(console.warn("Output has already been finalized."),this._finalizePromise):this._finalizePromise=(async()=>{this.state="finalizing";const t=await this._mutex.acquire(),e=this._tracks.map(t=>t.source._flushOrWaitForOngoingClose(!1));await Promise.all(e),await this._muxer.finalize(),await this._writer.flush(),await this._writer.finalize(),this.state="finalized",t()})()}}},38:(t,e,i)=>{i.d(e,{H:()=>a,L:()=>s});var r=i(583);const s=new Uint8Array(0);class a{constructor(t,e,i,r,a=-1,n,o){if(this.data=t,this.type=e,this.timestamp=i,this.duration=r,this.sequenceNumber=a,t===s&&void 0===n)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(void 0===n&&(n=t.byteLength),!(t instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if("key"!==e&&"delta"!==e)throw new TypeError('type must be either "key" or "delta".');if(!Number.isFinite(i))throw new TypeError("timestamp must be a number.");if(!Number.isFinite(r)||r<0)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(a))throw new TypeError("sequenceNumber must be a number.");if(!Number.isInteger(n)||n<0)throw new TypeError("byteLength must be a non-negative integer.");if(void 0!==o&&("object"!=typeof o||!o))throw new TypeError("sideData, when provided, must be an object.");if(void 0!==o?.alpha&&!(o.alpha instanceof Uint8Array))throw new TypeError("sideData.alpha, when provided, must be a Uint8Array.");if(void 0!==o?.alphaByteLength&&(!Number.isInteger(o.alphaByteLength)||o.alphaByteLength<0))throw new TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=n,this.sideData=o??{},this.sideData.alpha&&void 0===this.sideData.alphaByteLength&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===s}get microsecondTimestamp(){return Math.trunc(r.Ue*this.timestamp)}get microsecondDuration(){return Math.trunc(r.Ue*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if("undefined"==typeof EncodedVideoChunk)throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(t=this.type){if(!this.sideData.alpha)throw new TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if("undefined"==typeof EncodedVideoChunk)throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.sideData.alpha,type:t,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to an audio chunk.");if("undefined"==typeof EncodedAudioChunk)throw new Error("Your browser does not support EncodedAudioChunk.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(t,e){if(!(t instanceof EncodedVideoChunk||t instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");const i=new Uint8Array(t.byteLength);return t.copyTo(i),new a(i,t.type,t.timestamp/1e6,(t.duration??0)/1e6,void 0,void 0,e)}clone(t){if(void 0!==t&&("object"!=typeof t||null===t))throw new TypeError("options, when provided, must be an object.");if(void 0!==t?.data&&!(t.data instanceof Uint8Array))throw new TypeError("options.data, when provided, must be a Uint8Array.");if(void 0!==t?.type&&"key"!==t.type&&"delta"!==t.type)throw new TypeError('options.type, when provided, must be either "key" or "delta".');if(void 0!==t?.timestamp&&!Number.isFinite(t.timestamp))throw new TypeError("options.timestamp, when provided, must be a number.");if(void 0!==t?.duration&&!Number.isFinite(t.duration))throw new TypeError("options.duration, when provided, must be a number.");if(void 0!==t?.sequenceNumber&&!Number.isFinite(t.sequenceNumber))throw new TypeError("options.sequenceNumber, when provided, must be a number.");if(void 0!==t?.sideData&&("object"!=typeof t.sideData||null===t.sideData))throw new TypeError("options.sideData, when provided, must be an object.");return new a(t?.data??this.data,t?.type??this.type,t?.timestamp??this.timestamp,t?.duration??this.duration,t?.sequenceNumber??this.sequenceNumber,this.byteLength,t?.sideData??this.sideData)}}},481:(t,e,i)=>{i.d(e,{CJ:()=>n,Ej:()=>a,Fk:()=>b,NN:()=>w,NX:()=>d,Ry:()=>_,Ss:()=>S,ZC:()=>u,c_:()=>y,dd:()=>m,ff:()=>v,jG:()=>l,qx:()=>f,s3:()=>c,sB:()=>h,wr:()=>g,ww:()=>p,yn:()=>T,z$:()=>k});var r=i(700),s=i(583);class a{constructor(t){this.source=t}requestSlice(t,e){if(this.source._disposed)throw new r.x;if(t<0)return null;if(null!==this.fileSize&&t+e>this.fileSize)return null;const i=t+e,s=this.source._read(t,i);return s instanceof Promise?s.then(e=>e?new n(e.bytes,e.view,e.offset,t,i):null):s?new n(s.bytes,s.view,s.offset,t,i):null}requestSliceRange(t,e,i){if(this.source._disposed)throw new r.x;if(t<0)return null;if(null!==this.fileSize)return this.requestSlice(t,(0,s.uZ)(this.fileSize-t,e,i));{const r=this.requestSlice(t,i),a=r=>{if(r)return r;const a=r=>((0,s.hu)(null!==r),this.requestSlice(t,(0,s.uZ)(r-t,e,i))),n=this.source._retrieveSize();return n instanceof Promise?n.then(a):a(n)};return r instanceof Promise?r.then(a):a(r)}}}class n{constructor(t,e,i,r,s){this.bytes=t,this.view=e,this.offset=i,this.start=r,this.end=s,this.bufferPos=r-i}static tempFromBytes(t){return new n(t,(0,s.NK)(t),0,0,t.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos(t){this.bufferPos=t-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip(t){this.bufferPos+=t}slice(t,e=this.end-t){if(t<this.start||t+e>this.end)throw new RangeError("Slicing outside of original slice.");return new n(this.bytes,this.view,this.offset,t,t+e)}}const o=(t,e)=>{if(t.filePos<t.start||t.filePos+e>t.end)throw new RangeError(`Tried reading [${t.filePos}, ${t.filePos+e}), but slice is [${t.start}, ${t.end}). This is likely an internal error, please report it alongside the file that caused it.`)},h=(t,e)=>{o(t,e);const i=t.bytes.subarray(t.bufferPos,t.bufferPos+e);return t.bufferPos+=e,i},c=t=>(o(t,1),t.view.getUint8(t.bufferPos++)),d=(t,e)=>{o(t,2);const i=t.view.getUint16(t.bufferPos,e);return t.bufferPos+=2,i},l=t=>{o(t,2);const e=t.view.getUint16(t.bufferPos,!1);return t.bufferPos+=2,e},u=t=>{o(t,3);const e=(0,s.rB)(t.view,t.bufferPos,!1);return t.bufferPos+=3,e},p=t=>{o(t,2);const e=t.view.getInt16(t.bufferPos,!1);return t.bufferPos+=2,e},f=(t,e)=>{o(t,4);const i=t.view.getUint32(t.bufferPos,e);return t.bufferPos+=4,i},m=t=>{o(t,4);const e=t.view.getUint32(t.bufferPos,!1);return t.bufferPos+=4,e},g=t=>{o(t,4);const e=t.view.getUint32(t.bufferPos,!0);return t.bufferPos+=4,e},y=t=>{o(t,4);const e=t.view.getInt32(t.bufferPos,!1);return t.bufferPos+=4,e},_=(t,e)=>{let i,r;return e?(i=f(t,!0),r=f(t,!0)):(r=f(t,!1),i=f(t,!1)),4294967296*r+i},b=t=>4294967296*m(t)+m(t),w=t=>4294967296*y(t)+m(t),v=t=>{const e=g(t),i=(t=>{o(t,4);const e=t.view.getInt32(t.bufferPos,!0);return t.bufferPos+=4,e})(t);return 4294967296*i+e},k=t=>{o(t,4);const e=t.view.getFloat32(t.bufferPos,!1);return t.bufferPos+=4,e},S=t=>{o(t,8);const e=t.view.getFloat64(t.bufferPos,!1);return t.bufferPos+=8,e},T=(t,e)=>{o(t,e);let i="";for(let r=0;r<e;r++)i+=String.fromCharCode(t.bytes[t.bufferPos++]);return i}},348:(t,e,i)=>{i.d(e,{_A:()=>c});var r=i(583);(0,r.un)();let s=-1/0,a=-1/0,n=null;"undefined"!=typeof FinalizationRegistry&&(n=new FinalizationRegistry(t=>{const e=Date.now();"video"===t.type?(e-s>=1e3&&(console.error("A VideoSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your VideoSamples as soon as you're done using them."),s=e),"undefined"!=typeof VideoFrame&&t.data instanceof VideoFrame&&t.data.close()):(e-a>=1e3&&(console.error("An AudioSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your AudioSamples as soon as you're done using them."),a=e),"undefined"!=typeof AudioData&&t.data instanceof AudioData&&t.data.close())}));const o=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],h=new Set(o);class c{get displayWidth(){return this.rotation%180==0?this.codedWidth:this.codedHeight}get displayHeight(){return this.rotation%180==0?this.codedHeight:this.codedWidth}get microsecondTimestamp(){return Math.trunc(r.Ue*this.timestamp)}get microsecondDuration(){return Math.trunc(r.Ue*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor(t,e){if(this._closed=!1,t instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&t instanceof SharedArrayBuffer||ArrayBuffer.isView(t)){if(!e||"object"!=typeof e)throw new TypeError("init must be an object.");if(void 0===e.format||!h.has(e.format))throw new TypeError("init.format must be one of: "+o.join(", "));if(!Number.isInteger(e.codedWidth)||e.codedWidth<=0)throw new TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(e.codedHeight)||e.codedHeight<=0)throw new TypeError("init.codedHeight must be a positive integer.");if(void 0!==e.rotation&&![0,90,180,270].includes(e.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(e.timestamp))throw new TypeError("init.timestamp must be a number.");if(void 0!==e.duration&&(!Number.isFinite(e.duration)||e.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");this._data=(0,r._f)(t).slice(),this._layout=e.layout??m(e.format,e.codedWidth,e.codedHeight),this.format=e.format,this.codedWidth=e.codedWidth,this.codedHeight=e.codedHeight,this.rotation=e.rotation??0,this.timestamp=e.timestamp,this.duration=e.duration??0,this.colorSpace=new d(e.colorSpace)}else if("undefined"!=typeof VideoFrame&&t instanceof VideoFrame){if(void 0!==e?.rotation&&![0,90,180,270].includes(e.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(void 0!==e?.timestamp&&!Number.isFinite(e?.timestamp))throw new TypeError("init.timestamp, when provided, must be a number.");if(void 0!==e?.duration&&(!Number.isFinite(e.duration)||e.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");this._data=t,this._layout=null,this.format=t.format,this.codedWidth=t.displayWidth,this.codedHeight=t.displayHeight,this.rotation=e?.rotation??0,this.timestamp=e?.timestamp??t.timestamp/1e6,this.duration=e?.duration??(t.duration??0)/1e6,this.colorSpace=new d(t.colorSpace)}else{if(!("undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement||"undefined"!=typeof SVGImageElement&&t instanceof SVGImageElement||"undefined"!=typeof ImageBitmap&&t instanceof ImageBitmap||"undefined"!=typeof HTMLVideoElement&&t instanceof HTMLVideoElement||"undefined"!=typeof HTMLCanvasElement&&t instanceof HTMLCanvasElement||"undefined"!=typeof OffscreenCanvas&&t instanceof OffscreenCanvas))throw new TypeError("Invalid data type: Must be a BufferSource or CanvasImageSource.");{if(!e||"object"!=typeof e)throw new TypeError("init must be an object.");if(void 0!==e.rotation&&![0,90,180,270].includes(e.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(e.timestamp))throw new TypeError("init.timestamp must be a number.");if(void 0!==e.duration&&(!Number.isFinite(e.duration)||e.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if("undefined"!=typeof VideoFrame)return new c(new VideoFrame(t,{timestamp:Math.trunc(e.timestamp*r.Ue),duration:Math.trunc((e.duration??0)*r.Ue)||void 0}),e);let i=0,s=0;if("naturalWidth"in t?(i=t.naturalWidth,s=t.naturalHeight):"videoWidth"in t?(i=t.videoWidth,s=t.videoHeight):"width"in t&&(i=Number(t.width),s=Number(t.height)),!i||!s)throw new TypeError("Could not determine dimensions.");const a=new OffscreenCanvas(i,s),n=a.getContext("2d",{alpha:(0,r.vU)(),willReadFrequently:!0});(0,r.hu)(n),n.drawImage(t,0,0),this._data=a,this._layout=null,this.format="RGBX",this.codedWidth=i,this.codedHeight=s,this.rotation=e.rotation??0,this.timestamp=e.timestamp,this.duration=e.duration??0,this.colorSpace=new d({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}}n?.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return(0,r.hu)(null!==this._data),l(this._data)?new c(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation}):this._data instanceof Uint8Array?((0,r.hu)(this._layout),new c(this._data,{format:this.format,layout:this._layout,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation})):new c(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation})}close(){this._closed||(n?.unregister(this),l(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(t={}){if(f(t),this._closed)throw new Error("VideoSample is closed.");if(null===this.format)throw new Error("Cannot get allocation size when format is null. Sorry!");if((0,r.hu)(null!==this._data),!l(this._data)&&(t.colorSpace||t.format&&t.format!==this.format||t.layout||t.rect)){const e=this.toVideoFrame(),i=e.allocationSize(t);return e.close(),i}return l(this._data)?this._data.allocationSize(t):this._data instanceof Uint8Array?this._data.byteLength:this.codedWidth*this.codedHeight*4}async copyTo(t,e={}){if(!(0,r.n0)(t))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(f(e),this._closed)throw new Error("VideoSample is closed.");if(null===this.format)throw new Error("Cannot copy video sample data when format is null. Sorry!");if((0,r.hu)(null!==this._data),!l(this._data)&&(e.colorSpace||e.format&&e.format!==this.format||e.layout||e.rect)){const i=this.toVideoFrame(),r=await i.copyTo(t,e);return i.close(),r}if(l(this._data))return this._data.copyTo(t,e);if(this._data instanceof Uint8Array)return(0,r.hu)(this._layout),(0,r._f)(t).set(this._data),this._layout;{const e=this._data.getContext("2d");(0,r.hu)(e);const i=e.getImageData(0,0,this.codedWidth,this.codedHeight);return(0,r._f)(t).set(i.data),[{offset:0,stride:4*this.codedWidth}]}}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");return(0,r.hu)(null!==this._data),l(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace}):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(t,e,i,r,s,a,n,o,h){let c=0,d=0,l=this.displayWidth,u=this.displayHeight,p=0,f=0,m=this.displayWidth,g=this.displayHeight;if(void 0!==a?(c=e,d=i,l=r,u=s,p=a,f=n,void 0!==o?(m=o,g=h):(m=l,g=u)):(p=e,f=i,void 0!==r&&(m=r,g=s)),!("undefined"!=typeof CanvasRenderingContext2D&&t instanceof CanvasRenderingContext2D||"undefined"!=typeof OffscreenCanvasRenderingContext2D&&t instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(c))throw new TypeError("sx must be a number.");if(!Number.isFinite(d))throw new TypeError("sy must be a number.");if(!Number.isFinite(l)||l<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(u)||u<0)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(p))throw new TypeError("dx must be a number.");if(!Number.isFinite(f))throw new TypeError("dy must be a number.");if(!Number.isFinite(m)||m<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(g)||g<0)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw new Error("VideoSample is closed.");({sx:c,sy:d,sWidth:l,sHeight:u}=this._rotateSourceRegion(c,d,l,u,this.rotation));const y=this.toCanvasImageSource();t.save();const _=p+m/2,b=f+g/2;t.translate(_,b),t.rotate(this.rotation*Math.PI/180);const w=this.rotation%180==0?1:m/g;t.scale(1/w,w),t.drawImage(y,c,d,l,u,-m/2,-g/2,m,g),t.restore()}drawWithFit(t,e){if(!("undefined"!=typeof CanvasRenderingContext2D&&t instanceof CanvasRenderingContext2D||"undefined"!=typeof OffscreenCanvasRenderingContext2D&&t instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!e||"object"!=typeof e)throw new TypeError("options must be an object.");if(!["fill","contain","cover"].includes(e.fit))throw new TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(void 0!==e.rotation&&![0,90,180,270].includes(e.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");void 0!==e.crop&&p(e.crop,"options.");const i=t.canvas.width,r=t.canvas.height,s=e.rotation??this.rotation,[a,n]=s%180==0?[this.codedWidth,this.codedHeight]:[this.codedHeight,this.codedWidth];let o,h,c,d;e.crop&&u(e.crop,a,n);const{sx:l,sy:f,sWidth:m,sHeight:g}=this._rotateSourceRegion(e.crop?.left??0,e.crop?.top??0,e.crop?.width??a,e.crop?.height??n,s);if("fill"===e.fit)o=0,h=0,c=i,d=r;else{const[t,s]=e.crop?[e.crop.width,e.crop.height]:[a,n],l="contain"===e.fit?Math.min(i/t,r/s):Math.max(i/t,r/s);c=t*l,d=s*l,o=(i-c)/2,h=(r-d)/2}t.save();const y=s%180==0?1:c/d;t.translate(i/2,r/2),t.rotate(s*Math.PI/180),t.scale(1/y,y),t.translate(-i/2,-r/2),t.drawImage(this.toCanvasImageSource(),l,f,m,g,o,h,c,d),t.restore()}_rotateSourceRegion(t,e,i,r,s){return 90===s?[t,e,i,r]=[e,this.codedHeight-t-i,r,i]:180===s?[t,e]=[this.codedWidth-t-i,this.codedHeight-e-r]:270===s&&([t,e,i,r]=[this.codedWidth-e-r,t,r,i]),{sx:t,sy:e,sWidth:i,sHeight:r}}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if((0,r.hu)(null!==this._data),this._data instanceof Uint8Array){const t=this.toVideoFrame();return queueMicrotask(()=>t.close()),t}return this._data}setRotation(t){if(![0,90,180,270].includes(t))throw new TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=t}setTimestamp(t){if(!Number.isFinite(t))throw new TypeError("newTimestamp must be a number.");this.timestamp=t}setDuration(t){if(!Number.isFinite(t)||t<0)throw new TypeError("newDuration must be a non-negative number.");this.duration=t}[Symbol.dispose](){this.close()}}class d{constructor(t){this.primaries=t?.primaries??null,this.transfer=t?.transfer??null,this.matrix=t?.matrix??null,this.fullRange=t?.fullRange??null}toJSON(){return{primaries:this.primaries,transfer:this.transfer,matrix:this.matrix,fullRange:this.fullRange}}}const l=t=>"undefined"!=typeof VideoFrame&&t instanceof VideoFrame,u=(t,e,i)=>{t.left=Math.min(t.left,e),t.top=Math.min(t.top,i),t.width=Math.min(t.width,e-t.left),t.height=Math.min(t.height,i-t.top),(0,r.hu)(t.width>=0),(0,r.hu)(t.height>=0)},p=(t,e)=>{if(!t||"object"!=typeof t)throw new TypeError(e+"crop, when provided, must be an object.");if(!Number.isInteger(t.left)||t.left<0)throw new TypeError(e+"crop.left must be a non-negative integer.");if(!Number.isInteger(t.top)||t.top<0)throw new TypeError(e+"crop.top must be a non-negative integer.");if(!Number.isInteger(t.width)||t.width<0)throw new TypeError(e+"crop.width must be a non-negative integer.");if(!Number.isInteger(t.height)||t.height<0)throw new TypeError(e+"crop.height must be a non-negative integer.")},f=t=>{if(!t||"object"!=typeof t)throw new TypeError("options must be an object.");if(void 0!==t.colorSpace&&!["display-p3","srgb"].includes(t.colorSpace))throw new TypeError("options.colorSpace, when provided, must be 'display-p3' or 'srgb'.");if(void 0!==t.format&&"string"!=typeof t.format)throw new TypeError("options.format, when provided, must be a string.");if(void 0!==t.layout){if(!Array.isArray(t.layout))throw new TypeError("options.layout, when provided, must be an array.");for(const e of t.layout){if(!e||"object"!=typeof e)throw new TypeError("Each entry in options.layout must be an object.");if(!Number.isInteger(e.offset)||e.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(e.stride)||e.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(void 0!==t.rect){if(!t.rect||"object"!=typeof t.rect)throw new TypeError("options.rect, when provided, must be an object.");if(void 0!==t.rect.x&&(!Number.isInteger(t.rect.x)||t.rect.x<0))throw new TypeError("options.rect.x, when provided, must be a non-negative integer.");if(void 0!==t.rect.y&&(!Number.isInteger(t.rect.y)||t.rect.y<0))throw new TypeError("options.rect.y, when provided, must be a non-negative integer.");if(void 0!==t.rect.width&&(!Number.isInteger(t.rect.width)||t.rect.width<0))throw new TypeError("options.rect.width, when provided, must be a non-negative integer.");if(void 0!==t.rect.height&&(!Number.isInteger(t.rect.height)||t.rect.height<0))throw new TypeError("options.rect.height, when provided, must be a non-negative integer.")}},m=(t,e,i)=>{const r=g(t),s=[];let a=0;for(const t of r){const r=Math.ceil(e/t.widthDivisor),n=Math.ceil(i/t.heightDivisor),o=r*t.sampleBytes,h=o*n;s.push({offset:a,stride:o}),a+=h}return s},g=t=>{const e=(t,e,i,r,s)=>{const a=[{sampleBytes:t,widthDivisor:1,heightDivisor:1},{sampleBytes:e,widthDivisor:i,heightDivisor:r},{sampleBytes:e,widthDivisor:i,heightDivisor:r}];return s&&a.push({sampleBytes:t,widthDivisor:1,heightDivisor:1}),a};switch(t){case"I420":return e(1,1,2,2,!1);case"I420P10":case"I420P12":return e(2,2,2,2,!1);case"I420A":return e(1,1,2,2,!0);case"I420AP10":case"I420AP12":return e(2,2,2,2,!0);case"I422":return e(1,1,2,1,!1);case"I422P10":case"I422P12":return e(2,2,2,1,!1);case"I422A":return e(1,1,2,1,!0);case"I422AP10":case"I422AP12":return e(2,2,2,1,!0);case"I444":return e(1,1,1,1,!1);case"I444P10":case"I444P12":return e(2,2,1,1,!1);case"I444A":return e(1,1,1,1,!0);case"I444AP10":case"I444AP12":return e(2,2,1,1,!0);case"NV12":return[{sampleBytes:1,widthDivisor:1,heightDivisor:1},{sampleBytes:2,widthDivisor:2,heightDivisor:2}];case"RGBA":case"RGBX":case"BGRA":case"BGRX":return[{sampleBytes:4,widthDivisor:1,heightDivisor:1}];default:(0,r.vE)(t),(0,r.hu)(!1)}};new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]),Symbol.dispose},219:(t,e,i)=>{var r;i.d(e,{Hw:()=>o,pC:()=>h});var s=i(583),a=i(501),n=i(700);void 0!==(r||(r=i.t(a,2)))&&(r||(r=i.t(a,2)));class o{constructor(){this._disposed=!1,this._sizePromise=null,this.onread=null}async getSizeOrNull(){if(this._disposed)throw new n.x;return this._sizePromise??=Promise.resolve(this._retrieveSize())}async getSize(){if(this._disposed)throw new n.x;const t=await this.getSizeOrNull();if(null===t)throw new Error("Cannot determine the size of an unsized source.");return t}}class h extends o{constructor(t,e={}){if(!(t instanceof Blob))throw new TypeError("blob must be a Blob.");if(!e||"object"!=typeof e)throw new TypeError("options must be an object.");if(void 0!==e.maxCacheSize&&(!(0,s.hj)(e.maxCacheSize)||e.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");super(),this._readers=new WeakMap,this._blob=t,this._orchestrator=new d({maxCacheSize:e.maxCacheSize??8388608,maxWorkerCount:4,runWorker:this._runWorker.bind(this),prefetchProfile:c.fileSystem})}_retrieveSize(){const t=this._blob.size;return this._orchestrator.fileSize=t,t}_read(t,e){return this._orchestrator.read(t,e)}async _runWorker(t){let e=this._readers.get(t);void 0===e&&(e="stream"in this._blob&&!(0,s.Pf)()?this._blob.slice(t.currentPos).stream().getReader():null,this._readers.set(t,e));for(;t.currentPos<t.targetPos&&!t.aborted;)if(e){const{done:i,value:r}=await e.read();if(i)throw this._orchestrator.forgetWorker(t),new Error("Blob reader stopped unexpectedly before all requested data was read.");if(t.aborted)break;this.onread?.(t.currentPos,t.currentPos+r.length),this._orchestrator.supplyWorkerData(t,r)}else{const e=await this._blob.slice(t.currentPos,t.targetPos).arrayBuffer();if(t.aborted)break;this.onread?.(t.currentPos,t.currentPos+e.byteLength),this._orchestrator.supplyWorkerData(t,new Uint8Array(e))}t.running=!1,t.aborted&&await(e?.cancel())}_dispose(){this._orchestrator.dispose()}}const c={none:(t,e)=>({start:t,end:e}),fileSystem:(t,e)=>{const i=65536;return{start:t=Math.floor((t-i)/i)*i,end:e=Math.ceil((e+i)/i)*i}},network:(t,e,i)=>{const r=65536;t=Math.max(0,Math.floor((t-r)/r)*r);for(const r of i){const i=8388608,a=Math.max((r.startPos+r.targetPos)/2,r.targetPos-i);if((0,s.bL)(t,e,a,r.targetPos)){const t=r.targetPos-r.startPos,s=Math.ceil((t+1)/i)*i,a=2**Math.ceil(Math.log2(t+1)),n=Math.min(a,s);e=Math.max(e,r.startPos+n)}}return{start:t,end:e=Math.max(e,t+524288)}}};class d{constructor(t){this.options=t,this.fileSize=null,this.nextAge=0,this.workers=[],this.cache=[],this.currentCacheSize=0,this.disposed=!1}read(t,e){(0,s.hu)(null!==this.fileSize);const i=this.options.prefetchProfile(t,e,this.workers),r=Math.max(i.start,0),a=Math.min(i.end,this.fileSize);(0,s.hu)(r<=t&&e<=a);let n=null;const o=(0,s.sF)(this.cache,t,t=>t.start),h=-1!==o?this.cache[o]:null;h&&h.start<=t&&e<=h.end&&(h.age=this.nextAge++,n={bytes:h.bytes,view:h.view,offset:h.start});const c=(0,s.sF)(this.cache,r,t=>t.start),d=n?null:new Uint8Array(e-t);let l=0,u=r;const p=[];if(-1!==c){for(let i=c;i<this.cache.length;i++){const n=this.cache[i];if(n.start>=a)break;if(n.end<=r)continue;const o=Math.max(r,n.start),h=Math.min(a,n.end);if((0,s.hu)(o<=h),u<o&&p.push({start:u,end:o}),u=h,d){const i=Math.max(t,n.start),r=Math.min(e,n.end);if(i<r){const e=i-t;d.set(n.bytes.subarray(i-n.start,r-n.start),e),e===l&&(l=r-t)}}n.age=this.nextAge++}u<a&&p.push({start:u,end:a})}else p.push({start:r,end:a});if(d&&l>=d.length&&(n={bytes:d,view:(0,s.NK)(d),offset:t}),0===p.length)return(0,s.hu)(n),n;const{promise:f,resolve:m,reject:g}=(0,s.Bw)(),y=[];for(const i of p){const r=Math.max(t,i.start),s=Math.min(e,i.end);r===i.start&&s===i.end?y.push(i):r<s&&y.push({start:r,end:s})}for(const e of p){const i=d&&{start:t,bytes:d,holes:y,resolve:m,reject:g};let r=!1;for(const t of this.workers){const a=2**17;if((0,s.bL)(e.start-a,e.start,t.currentPos,t.targetPos)){t.targetPos=Math.max(t.targetPos,e.end),r=!0,i&&!t.pendingSlices.includes(i)&&t.pendingSlices.push(i),t.running||this.runWorker(t);break}}if(!r){const t=this.createWorker(e.start,e.end);i&&(t.pendingSlices=[i]),this.runWorker(t)}}return n||((0,s.hu)(d),n=f.then(e=>({bytes:e,view:(0,s.NK)(e),offset:t}))),n}createWorker(t,e){const i={startPos:t,currentPos:t,targetPos:e,running:!1,aborted:this.disposed,pendingSlices:[],age:this.nextAge++};for(this.workers.push(i);this.workers.length>this.options.maxWorkerCount;){let t=0,e=this.workers[0];for(let i=1;i<this.workers.length;i++){const r=this.workers[i];r.age<e.age&&(t=i,e=r)}if(e.running&&e.pendingSlices.length>0)break;e.aborted=!0,this.workers.splice(t,1)}return i}runWorker(t){(0,s.hu)(!t.running),(0,s.hu)(t.currentPos<t.targetPos),t.running=!0,t.age=this.nextAge++,this.options.runWorker(t).catch(e=>{if(t.running=!1,!(t.pendingSlices.length>0))throw e;t.pendingSlices.forEach(t=>t.reject(e)),t.pendingSlices.length=0})}supplyWorkerData(t,e){(0,s.hu)(!t.aborted);const i=t.currentPos,r=i+e.length;this.insertIntoCache({start:i,end:r,bytes:e,view:(0,s.NK)(e),age:this.nextAge++}),t.currentPos+=e.length,t.targetPos=Math.max(t.targetPos,t.currentPos);for(let s=0;s<t.pendingSlices.length;s++){const a=t.pendingSlices[s],n=Math.max(i,a.start),o=Math.min(r,a.start+a.bytes.length);n<o&&a.bytes.set(e.subarray(n-i,o-i),n-a.start);for(let t=0;t<a.holes.length;t++){const e=a.holes[t];i<=e.start&&r>e.start&&(e.start=r),e.end<=e.start&&(a.holes.splice(t,1),t--)}0===a.holes.length&&(a.resolve(a.bytes),t.pendingSlices.splice(s,1),s--)}for(let e=0;e<this.workers.length;e++){const a=this.workers[e];t===a||a.running||(0,s.bL)(i,r,a.currentPos,a.targetPos)&&(this.workers.splice(e,1),e--)}}forgetWorker(t){const e=this.workers.indexOf(t);(0,s.hu)(-1!==e),this.workers.splice(e,1)}insertIntoCache(t){if(0===this.options.maxCacheSize)return;let e=(0,s.sF)(this.cache,t.start,t=>t.start)+1;if(e>0){const i=this.cache[e-1];if(i.end>=t.end)return;if(i.end>t.start){const r=new Uint8Array(t.end-i.start);r.set(i.bytes,0),r.set(t.bytes,t.start-i.start),this.currentCacheSize+=t.end-i.end,i.bytes=r,i.view=(0,s.NK)(r),i.end=t.end,e--,t=i}else this.cache.splice(e,0,t),this.currentCacheSize+=t.bytes.length}else this.cache.splice(e,0,t),this.currentCacheSize+=t.bytes.length;for(let i=e+1;i<this.cache.length;i++){const e=this.cache[i];if(t.end<=e.start)break;if(t.end>=e.end){this.cache.splice(i,1),this.currentCacheSize-=e.bytes.length,i--;continue}const r=new Uint8Array(e.end-t.start);r.set(t.bytes,0),r.set(e.bytes,e.start-t.start),this.currentCacheSize-=t.end-e.start,t.bytes=r,t.view=(0,s.NK)(r),t.end=e.end,this.cache.splice(i,1);break}for(;this.currentCacheSize>this.options.maxCacheSize;){let t=0,e=this.cache[0];for(let i=1;i<this.cache.length;i++){const r=this.cache[i];r.age<e.age&&(t=i,e=r)}if(this.currentCacheSize-e.bytes.length<=this.options.maxCacheSize)break;this.cache.splice(t,1),this.currentCacheSize-=e.bytes.length}}dispose(){for(const t of this.workers)t.aborted=!0;this.workers.length=0,this.cache.length=0,this.disposed=!0}}},709:(t,e,i)=>{var r;i.d(e,{Pl:()=>h,Vl:()=>o,Vz:()=>n});var s=i(840),a=i(501);void 0!==(r||(r=i.t(a,2)))&&(r||(r=i.t(a,2)));class n{constructor(){this._output=null,this.onwrite=null}}class o extends n{constructor(){super(...arguments),this.buffer=null}_createWriter(){return new s.Ak(this)}}class h extends n{constructor(t,e={}){if(super(),!(t instanceof WritableStream))throw new TypeError("StreamTarget requires a WritableStream instance.");if(null!=e&&"object"!=typeof e)throw new TypeError("StreamTarget options, when provided, must be an object.");if(void 0!==e.chunked&&"boolean"!=typeof e.chunked)throw new TypeError("options.chunked, when provided, must be a boolean.");if(void 0!==e.chunkSize&&(!Number.isInteger(e.chunkSize)||e.chunkSize<1024))throw new TypeError("options.chunkSize, when provided, must be an integer and not smaller than 1024.");this._writable=t,this._options=e}_createWriter(){return new s.PS(this)}}},840:(t,e,i)=>{i.d(e,{Ak:()=>o,PS:()=>h});var r=i(583);class s{constructor(){this.ensureMonotonicity=!1,this.trackedWrites=null,this.trackedStart=-1,this.trackedEnd=-1}start(){}maybeTrackWrites(t){if(!this.trackedWrites)return;let e=this.getPos();if(e<this.trackedStart){if(e+t.byteLength<=this.trackedStart)return;t=t.subarray(this.trackedStart-e),e=0}const i=e+t.byteLength-this.trackedStart;let r=this.trackedWrites.byteLength;for(;r<i;)r*=2;if(r!==this.trackedWrites.byteLength){const t=new Uint8Array(r);t.set(this.trackedWrites,0),this.trackedWrites=t}this.trackedWrites.set(t,e-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,e+t.byteLength)}startTrackingWrites(){this.trackedWrites=new Uint8Array(1024),this.trackedStart=this.getPos(),this.trackedEnd=this.trackedStart}stopTrackingWrites(){if(!this.trackedWrites)throw new Error("Internal error: Can't get tracked writes since nothing was tracked.");const t={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,t}}const a=65536,n=2**32;class o extends s{constructor(t){if(super(),this.pos=0,this.maxPos=0,this.target=t,this.supportsResize="resize"in new ArrayBuffer(0),this.supportsResize)try{this.buffer=new ArrayBuffer(a,{maxByteLength:n})}catch{this.buffer=new ArrayBuffer(a),this.supportsResize=!1}else this.buffer=new ArrayBuffer(a);this.bytes=new Uint8Array(this.buffer)}ensureSize(t){let e=this.buffer.byteLength;for(;e<t;)e*=2;if(e!==this.buffer.byteLength){if(e>n)throw new Error("ArrayBuffer exceeded maximum size of 4294967296 bytes. Please consider using another target.");if(this.supportsResize)this.buffer.resize(e);else{const t=new ArrayBuffer(e),i=new Uint8Array(t);i.set(this.bytes,0),this.buffer=t,this.bytes=i}}}write(t){this.maybeTrackWrites(t),this.ensureSize(this.pos+t.byteLength),this.bytes.set(t,this.pos),this.target.onwrite?.(this.pos,this.pos+t.byteLength),this.pos+=t.byteLength,this.maxPos=Math.max(this.maxPos,this.pos)}seek(t){this.pos=t}getPos(){return this.pos}async flush(){}async finalize(){this.ensureSize(this.pos),this.target.buffer=this.buffer.slice(0,Math.max(this.maxPos,this.pos))}async close(){}getSlice(t,e){return this.bytes.slice(t,e)}}class h extends s{constructor(t){super(),this.pos=0,this.sections=[],this.lastWriteEnd=0,this.lastFlushEnd=0,this.writer=null,this.chunks=[],this.target=t,this.chunked=t._options.chunked??!1,this.chunkSize=t._options.chunkSize??16777216}start(){this.writer=this.target._writable.getWriter()}write(t){if(this.pos>this.lastWriteEnd){const t=this.pos-this.lastWriteEnd;this.pos=this.lastWriteEnd,this.write(new Uint8Array(t))}this.maybeTrackWrites(t),this.sections.push({data:t.slice(),start:this.pos}),this.target.onwrite?.(this.pos,this.pos+t.byteLength),this.pos+=t.byteLength,this.lastWriteEnd=Math.max(this.lastWriteEnd,this.pos)}seek(t){this.pos=t}getPos(){return this.pos}async flush(){if(this.pos>this.lastWriteEnd){const t=this.pos-this.lastWriteEnd;this.pos=this.lastWriteEnd,this.write(new Uint8Array(t))}if((0,r.hu)(this.writer),0===this.sections.length)return;const t=[],e=[...this.sections].sort((t,e)=>t.start-e.start);t.push({start:e[0].start,size:e[0].data.byteLength});for(let i=1;i<e.length;i++){const r=t[t.length-1],s=e[i];s.start<=r.start+r.size?r.size=Math.max(r.size,s.start+s.data.byteLength-r.start):t.push({start:s.start,size:s.data.byteLength})}for(const e of t){e.data=new Uint8Array(e.size);for(const t of this.sections)e.start<=t.start&&t.start<e.start+e.size&&e.data.set(t.data,t.start-e.start);if(null!==this.writer.desiredSize&&this.writer.desiredSize<=0&&await this.writer.ready,this.chunked)this.writeDataIntoChunks(e.data,e.start),this.tryToFlushChunks();else{if(this.ensureMonotonicity&&e.start!==this.lastFlushEnd)throw new Error("Internal error: Monotonicity violation.");this.writer.write({type:"write",data:e.data,position:e.start}),this.lastFlushEnd=e.start+e.data.byteLength}}this.sections.length=0}writeDataIntoChunks(t,e){let i=this.chunks.findIndex(t=>t.start<=e&&e<t.start+this.chunkSize);-1===i&&(i=this.createChunk(e));const r=this.chunks[i],s=e-r.start,a=t.subarray(0,Math.min(this.chunkSize-s,t.byteLength));r.data.set(a,s);const n={start:s,end:s+a.byteLength};if(this.insertSectionIntoChunk(r,n),0===r.written[0].start&&r.written[0].end===this.chunkSize&&(r.shouldFlush=!0),this.chunks.length>2){for(let t=0;t<this.chunks.length-1;t++)this.chunks[t].shouldFlush=!0;this.tryToFlushChunks()}a.byteLength<t.byteLength&&this.writeDataIntoChunks(t.subarray(a.byteLength),e+a.byteLength)}insertSectionIntoChunk(t,e){let i=0,r=t.written.length-1,s=-1;for(;i<=r;){const a=Math.floor(i+(r-i+1)/2);t.written[a].start<=e.start?(i=a+1,s=a):r=a-1}for(t.written.splice(s+1,0,e),(-1===s||t.written[s].end<e.start)&&s++;s<t.written.length-1&&t.written[s].end>=t.written[s+1].start;)t.written[s].end=Math.max(t.written[s].end,t.written[s+1].end),t.written.splice(s+1,1)}createChunk(t){const e={start:Math.floor(t/this.chunkSize)*this.chunkSize,data:new Uint8Array(this.chunkSize),written:[],shouldFlush:!1};return this.chunks.push(e),this.chunks.sort((t,e)=>t.start-e.start),this.chunks.indexOf(e)}tryToFlushChunks(t=!1){(0,r.hu)(this.writer);for(let e=0;e<this.chunks.length;e++){const i=this.chunks[e];if(i.shouldFlush||t){for(const t of i.written){const e=i.start+t.start;if(this.ensureMonotonicity&&e!==this.lastFlushEnd)throw new Error("Internal error: Monotonicity violation.");this.writer.write({type:"write",data:i.data.subarray(t.start,t.end),position:e}),this.lastFlushEnd=i.start+t.end}this.chunks.splice(e--,1)}}}finalize(){return this.chunked&&this.tryToFlushChunks(!0),(0,r.hu)(this.writer),this.writer.close()}async close(){return this.writer?.close()}}},232:(t,e,i)=>{i.d(e,{Pl:()=>ht,fX:()=>oe});var r,s,a,n,o,h,c,d,l=(t,e,i)=>{if(!e.has(t))throw TypeError("Cannot "+i)},u=(t,e,i)=>(l(t,e,"read from private field"),i?i.call(t):e.get(t)),p=(t,e,i)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,i)},f=(t,e,i,r)=>(l(t,e,"write to private field"),r?r.call(t,i):e.set(t,i),i),m=(t,e,i)=>(l(t,e,"access private method"),i),g=new Uint8Array(8),y=new DataView(g.buffer),_=t=>[(t%256+256)%256],b=t=>(y.setUint16(0,t,!1),[g[0],g[1]]),w=t=>(y.setUint32(0,t,!1),[g[1],g[2],g[3]]),v=t=>(y.setUint32(0,t,!1),[g[0],g[1],g[2],g[3]]),k=t=>(y.setInt16(0,256*t,!1),[g[0],g[1]]),S=t=>(y.setInt32(0,65536*t,!1),[g[0],g[1],g[2],g[3]]),T=t=>(y.setInt32(0,2**30*t,!1),[g[0],g[1],g[2],g[3]]),x=(t,e=!1)=>{let i=Array(t.length).fill(null).map((e,i)=>t.charCodeAt(i));return e&&i.push(0),i},C=t=>t&&t[t.length-1],E=(t,e,i=!0)=>{let r=t*e;return i?Math.round(r):r},U=t=>{let e=t*(Math.PI/180),i=Math.cos(e),r=Math.sin(e);return[i,r,0,-r,i,0,0,0,1]},B=U(0),A=t=>[S(t[0]),S(t[1]),T(t[2]),S(t[3]),S(t[4]),T(t[5]),S(t[6]),S(t[7]),T(t[8])],I=t=>t?"object"!=typeof t?t:Array.isArray(t)?t.map(I):Object.fromEntries(Object.entries(t).map(([t,e])=>[t,I(e)])):t,P=(t,e,i)=>({type:t,contents:e&&new Uint8Array(e.flat(10)),children:i}),z=(t,e,i,r,s)=>P(t,[_(e),w(i),r??[]],s),F=t=>({type:"mdat",largeSize:t}),D=(t,e)=>P("moov",null,[M(e,t),...t.map(t=>L(t,e))]),M=(t,e)=>{let i=E(Math.max(0,...e.filter(t=>t.samples.length>0).map(t=>C(t.samples).timestamp+C(t.samples).duration)),re),r=Math.max(...e.map(t=>t.id))+1;return z("mvhd",0,0,[v(t),v(t),v(re),v(i),S(1),k(1),Array(10).fill(0),A(B),Array(24).fill(0),v(r)])},L=(t,e)=>P("trak",null,[R(t,e),N(t,e)]),R=(t,e)=>{let i=C(t.samples),r=E(i?i.timestamp+i.duration:0,re);return z("tkhd",0,3,[v(e),v(e),v(t.id),v(0),v(r),Array(8).fill(0),b(0),b(0),k("audio"===t.info.type?1:0),b(0),A(U("video"===t.info.type?t.info.rotation:0)),S("video"===t.info.type?t.info.width:0),S("video"===t.info.type?t.info.height:0)])},N=(t,e)=>P("mdia",null,[O(t,e),H("video"===t.info.type?"vide":"soun"),V(t)]),O=(t,e)=>{let i=C(t.samples),r=E(i?i.timestamp+i.duration:0,t.timescale);return z("mdhd",0,0,[v(e),v(e),v(t.timescale),v(r),b(21956),b(0)])},H=t=>z("hdlr",0,0,[x("mhlr"),x(t),v(0),v(0),v(0),x("mp4-muxer-hdlr")]),V=t=>P("minf",null,["video"===t.info.type?W():G(),j(),q(t)]),W=()=>z("vmhd",0,1,[b(0),b(0),b(0),b(0)]),G=()=>z("smhd",0,0,[b(0),b(0)]),j=()=>P("dinf",null,[$()]),$=()=>z("dref",0,0,[v(1)],[Y()]),Y=()=>z("url ",0,1),q=t=>P("stbl",null,[Q(t),Z(t),J(t),tt(t),et(t),it(t)]),Q=t=>z("stsd",0,0,[v(1)],["video"===t.info.type?K(rt[t.info.codec],t):X(at[t.info.codec],t)]),K=(t,e)=>P(t,[Array(6).fill(0),b(1),b(0),b(0),Array(12).fill(0),b(e.info.width),b(e.info.height),v(4718592),v(4718592),v(0),b(1),Array(32).fill(0),b(24),(y.setInt16(0,65535,!1),[g[0],g[1]])],[st[e.info.codec](e)]),X=(t,e)=>P(t,[Array(6).fill(0),b(1),b(0),b(0),v(0),b(e.info.numberOfChannels),b(16),b(0),b(0),S(e.info.sampleRate)],[nt[e.info.codec](e)]),Z=t=>z("stts",0,0,[v(t.timeToSampleTable.length),t.timeToSampleTable.map(t=>[v(t.sampleCount),v(t.sampleDelta)])]),J=t=>{if(t.samples.every(t=>"key"===t.type))return null;let e=[...t.samples.entries()].filter(([,t])=>"key"===t.type);return z("stss",0,0,[v(e.length),e.map(([t])=>v(t+1))])},tt=t=>z("stsc",0,0,[v(t.compactlyCodedChunkTable.length),t.compactlyCodedChunkTable.map(t=>[v(t.firstChunk),v(t.samplesPerChunk),v(1)])]),et=t=>z("stsz",0,0,[v(0),v(t.samples.length),t.samples.map(t=>v(t.size))]),it=t=>t.finalizedChunks.length>0&&C(t.finalizedChunks).offset>=2**32?z("co64",0,0,[v(t.finalizedChunks.length),t.finalizedChunks.map(t=>{return e=t.offset,y.setUint32(0,Math.floor(e/2**32),!1),y.setUint32(4,e,!1),[g[0],g[1],g[2],g[3],g[4],g[5],g[6],g[7]];var e})]):z("stco",0,0,[v(t.finalizedChunks.length),t.finalizedChunks.map(t=>v(t.offset))]),rt={avc:"avc1",hevc:"hvc1",vp9:"vp09",av1:"av01"},st={avc:t=>t.codecPrivate&&P("avcC",[...t.codecPrivate]),hevc:t=>t.codecPrivate&&P("hvcC",[...t.codecPrivate]),vp9:t=>t.codecPrivate&&P("vpcC",[...t.codecPrivate]),av1:t=>t.codecPrivate&&P("av1C",[...t.codecPrivate])},at={aac:"mp4a",opus:"opus"},nt={aac:t=>z("esds",0,0,[v(58753152),_(32+t.codecPrivate.byteLength),b(1),_(0),v(75530368),_(18+t.codecPrivate.byteLength),_(64),_(21),w(0),v(130071),v(130071),v(92307584),_(t.codecPrivate.byteLength),...t.codecPrivate,v(109084800),_(1),_(2)]),opus:t=>P("dOps",[_(0),_(t.info.numberOfChannels),b(3840),v(t.info.sampleRate),k(0),_(0)])},ot=class{constructor(){this.buffer=null}},ht=class{constructor(t,e,i){this.onData=t,this.onDone=e,this.options=i}},ct=class{constructor(t,e){this.stream=t,this.options=e}},dt=class{constructor(){this.pos=0,p(this,r,new Uint8Array(8)),p(this,s,new DataView(u(this,r).buffer)),this.offsets=new WeakMap}seek(t){this.pos=t}writeU32(t){u(this,s).setUint32(0,t,!1),this.write(u(this,r).subarray(0,4))}writeU64(t){u(this,s).setUint32(0,Math.floor(t/2**32),!1),u(this,s).setUint32(4,t,!1),this.write(u(this,r).subarray(0,8))}writeAscii(t){for(let e=0;e<t.length;e++)u(this,s).setUint8(e%8,t.charCodeAt(e)),e%8==7&&this.write(u(this,r));t.length%8!=0&&this.write(u(this,r).subarray(0,t.length%8))}writeBox(t){if(this.offsets.set(t,this.pos),t.contents&&!t.children)this.writeBoxHeader(t,t.size??t.contents.byteLength+8),this.write(t.contents);else{let e=this.pos;if(this.writeBoxHeader(t,0),t.contents&&this.write(t.contents),t.children)for(let e of t.children)e&&this.writeBox(e);let i=this.pos,r=t.size??i-e;this.seek(e),this.writeBoxHeader(t,r),this.seek(i)}}writeBoxHeader(t,e){this.writeU32(t.largeSize?1:e),this.writeAscii(t.type),t.largeSize&&this.writeU64(e)}measureBoxHeader(t){return 8+(t.largeSize?8:0)}patchBox(t){let e=this.pos;this.seek(this.offsets.get(t)),this.writeBox(t),this.seek(e)}measureBox(t){if(t.contents&&!t.children)return this.measureBoxHeader(t)+t.contents.byteLength;{let e=this.measureBoxHeader(t);if(t.contents&&(e+=t.contents.byteLength),t.children)for(let i of t.children)i&&(e+=this.measureBox(i));return e}}};r=new WeakMap,s=new WeakMap;var lt,ut,pt=class extends dt{constructor(t){super(),p(this,c),p(this,a,void 0),p(this,n,new ArrayBuffer(65536)),p(this,o,new Uint8Array(u(this,n))),p(this,h,0),f(this,a,t)}write(t){m(this,c,d).call(this,this.pos+t.byteLength),u(this,o).set(t,this.pos),this.pos+=t.byteLength,f(this,h,Math.max(u(this,h),this.pos))}finalize(){m(this,c,d).call(this,this.pos),u(this,a).buffer=u(this,n).slice(0,Math.max(u(this,h),this.pos))}};a=new WeakMap,n=new WeakMap,o=new WeakMap,h=new WeakMap,c=new WeakSet,d=function(t){let e=u(this,n).byteLength;for(;e<t;)e*=2;if(e===u(this,n).byteLength)return;let i=new ArrayBuffer(e),r=new Uint8Array(i);r.set(u(this,o),0),f(this,n,i),f(this,o,r)};var ft=class extends dt{constructor(t){super(),p(this,lt,void 0),p(this,ut,[]),f(this,lt,t)}write(t){u(this,ut).push({data:t.slice(),start:this.pos}),this.pos+=t.byteLength}flush(){if(0===u(this,ut).length)return;let t=[],e=[...u(this,ut)].sort((t,e)=>t.start-e.start);t.push({start:e[0].start,size:e[0].data.byteLength});for(let i=1;i<e.length;i++){let r=t[t.length-1],s=e[i];s.start<=r.start+r.size?r.size=Math.max(r.size,s.start+s.data.byteLength-r.start):t.push({start:s.start,size:s.data.byteLength})}for(let e of t){e.data=new Uint8Array(e.size);for(let t of u(this,ut))e.start<=t.start&&t.start<e.start+e.size&&e.data.set(t.data,t.start-e.start);u(this,lt).onData(e.data,e.start)}u(this,ut).length=0}finalize(){u(this,lt).onDone?.()}};lt=new WeakMap,ut=new WeakMap;var mt,gt,yt,_t,bt,wt,vt,kt,St,Tt,xt,Ct=class extends dt{constructor(t){if(super(),p(this,_t),p(this,wt),p(this,kt),p(this,Tt),p(this,mt,void 0),p(this,gt,void 0),p(this,yt,[]),f(this,mt,t),f(this,gt,t.options?.chunkSize??16777216),!Number.isInteger(u(this,gt))||u(this,gt)<1024)throw new Error("Invalid StreamTarget options: chunkSize must be an integer not smaller than 1024.")}write(t){m(this,_t,bt).call(this,t,this.pos),m(this,Tt,xt).call(this),this.pos+=t.byteLength}finalize(){m(this,Tt,xt).call(this,!0),u(this,mt).onDone?.()}};mt=new WeakMap,gt=new WeakMap,yt=new WeakMap,_t=new WeakSet,bt=function(t,e){let i=u(this,yt).findIndex(t=>t.start<=e&&e<t.start+u(this,gt));-1===i&&(i=m(this,kt,St).call(this,e));let r=u(this,yt)[i],s=e-r.start,a=t.subarray(0,Math.min(u(this,gt)-s,t.byteLength));r.data.set(a,s);let n={start:s,end:s+a.byteLength};if(m(this,wt,vt).call(this,r,n),0===r.written[0].start&&r.written[0].end===u(this,gt)&&(r.shouldFlush=!0),u(this,yt).length>2){for(let t=0;t<u(this,yt).length-1;t++)u(this,yt)[t].shouldFlush=!0;m(this,Tt,xt).call(this)}a.byteLength<t.byteLength&&m(this,_t,bt).call(this,t.subarray(a.byteLength),e+a.byteLength)},wt=new WeakSet,vt=function(t,e){let i=0,r=t.written.length-1,s=-1;for(;i<=r;){let a=Math.floor(i+(r-i+1)/2);t.written[a].start<=e.start?(i=a+1,s=a):r=a-1}for(t.written.splice(s+1,0,e),(-1===s||t.written[s].end<e.start)&&s++;s<t.written.length-1&&t.written[s].end>=t.written[s+1].start;)t.written[s].end=Math.max(t.written[s].end,t.written[s+1].end),t.written.splice(s+1,1)},kt=new WeakSet,St=function(t){let e={start:Math.floor(t/u(this,gt))*u(this,gt),data:new Uint8Array(u(this,gt)),written:[],shouldFlush:!1};return u(this,yt).push(e),u(this,yt).sort((t,e)=>t.start-e.start),u(this,yt).indexOf(e)},Tt=new WeakSet,xt=function(t=!1){for(let e=0;e<u(this,yt).length;e++){let i=u(this,yt)[e];if(i.shouldFlush||t){for(let t of i.written)u(this,mt).onData(i.data.subarray(t.start,t.end),i.start+t.start);u(this,yt).splice(e--,1)}}};var Et,Ut,Bt,At,It,Pt,zt,Ft,Dt,Mt,Lt,Rt,Nt,Ot,Ht,Vt,Wt,Gt,jt,$t,Yt,qt,Qt,Kt,Xt,Zt,Jt,te,ee,ie=class extends Ct{constructor(t){super(new ht((e,i)=>t.stream.write({type:"write",data:e,position:i}),void 0,{chunkSize:t.options?.chunkSize}))}},re=1e3,se=["avc","hevc","vp9","av1"],ae=["aac","opus"],ne=["strict","offset"],oe=class{constructor(t){if(p(this,Mt),p(this,Rt),p(this,Ot),p(this,Vt),p(this,Gt),p(this,$t),p(this,qt),p(this,Kt),p(this,Zt),p(this,te),p(this,Et,void 0),p(this,Ut,void 0),p(this,Bt,void 0),p(this,At,void 0),p(this,It,null),p(this,Pt,null),p(this,zt,Math.floor(Date.now()/1e3)+2082844800),p(this,Ft,[]),p(this,Dt,!1),m(this,Mt,Lt).call(this,t),t.video=I(t.video),t.audio=I(t.audio),t.fastStart=I(t.fastStart),this.target=t.target,f(this,Et,{firstTimestampBehavior:"strict",...t}),t.target instanceof ot)f(this,Ut,new pt(t.target));else if(t.target instanceof ht)f(this,Ut,t.target.options?.chunked?new Ct(t.target):new ft(t.target));else{if(!(t.target instanceof ct))throw new Error(`Invalid target: ${t.target}`);f(this,Ut,new ie(t.target))}m(this,Rt,Nt).call(this),m(this,Vt,Wt).call(this)}addVideoChunk(t,e,i){let r=new Uint8Array(t.byteLength);t.copyTo(r),this.addVideoChunkRaw(r,t.type,i??t.timestamp,t.duration,e)}addVideoChunkRaw(t,e,i,r,s){if(m(this,te,ee).call(this),!u(this,Et).video)throw new Error("No video track declared.");if("object"==typeof u(this,Et).fastStart&&u(this,It).samples.length===u(this,Et).fastStart.expectedVideoChunks)throw new Error(`Cannot add more video chunks than specified in 'fastStart' (${u(this,Et).fastStart.expectedVideoChunks}).`);m(this,$t,Yt).call(this,u(this,It),t,e,i,r,s)}addAudioChunk(t,e,i){let r=new Uint8Array(t.byteLength);t.copyTo(r),this.addAudioChunkRaw(r,t.type,i??t.timestamp,t.duration,e)}addAudioChunkRaw(t,e,i,r,s){if(m(this,te,ee).call(this),!u(this,Et).audio)throw new Error("No audio track declared.");if("object"==typeof u(this,Et).fastStart&&u(this,Pt).samples.length===u(this,Et).fastStart.expectedAudioChunks)throw new Error(`Cannot add more audio chunks than specified in 'fastStart' (${u(this,Et).fastStart.expectedAudioChunks}).`);m(this,$t,Yt).call(this,u(this,Pt),t,e,i,r,s)}finalize(){u(this,It)&&m(this,Kt,Xt).call(this,u(this,It)),u(this,Pt)&&m(this,Kt,Xt).call(this,u(this,Pt));let t=[u(this,It),u(this,Pt)].filter(Boolean);if("in-memory"===u(this,Et).fastStart){let e;for(let i=0;i<2;i++){let i=D(t,u(this,zt)),r=u(this,Ut).measureBox(i);e=u(this,Ut).measureBox(u(this,At));let s=u(this,Ut).pos+r+e;for(let t of u(this,Ft)){t.offset=s;for(let i of t.sampleData)s+=i.byteLength,e+=i.byteLength}if(s<2**32)break;e>=2**32&&(u(this,At).largeSize=!0)}let i=D(t,u(this,zt));u(this,Ut).writeBox(i),u(this,At).size=e,u(this,Ut).writeBox(u(this,At));for(let t of u(this,Ft)){for(let e of t.sampleData)u(this,Ut).write(e);t.sampleData=null}}else{let e=u(this,Ut).offsets.get(u(this,At)),i=u(this,Ut).pos-e;u(this,At).size=i,u(this,At).largeSize=i>=2**32,u(this,Ut).patchBox(u(this,At));let r=D(t,u(this,zt));if("object"==typeof u(this,Et).fastStart){u(this,Ut).seek(u(this,Bt)),u(this,Ut).writeBox(r);let t=e-u(this,Ut).pos;u(this,Ut).writeBox({type:"free",size:t})}else u(this,Ut).writeBox(r)}m(this,Zt,Jt).call(this),u(this,Ut).finalize(),f(this,Dt,!0)}};Et=new WeakMap,Ut=new WeakMap,Bt=new WeakMap,At=new WeakMap,It=new WeakMap,Pt=new WeakMap,zt=new WeakMap,Ft=new WeakMap,Dt=new WeakMap,Mt=new WeakSet,Lt=function(t){if(t.video){if(!se.includes(t.video.codec))throw new Error(`Unsupported video codec: ${t.video.codec}`);if(void 0!==t.video.rotation&&![0,90,180,270].includes(t.video.rotation))throw new Error(`Invalid video rotation: ${t.video.rotation}. Has to be 0, 90, 180 or 270.`)}if(t.audio&&!ae.includes(t.audio.codec))throw new Error(`Unsupported audio codec: ${t.audio.codec}`);if(t.firstTimestampBehavior&&!ne.includes(t.firstTimestampBehavior))throw new Error(`Invalid first timestamp behavior: ${t.firstTimestampBehavior}`);if("object"==typeof t.fastStart){if(t.video&&void 0===t.fastStart.expectedVideoChunks)throw new Error("'fastStart' is an object but is missing property 'expectedVideoChunks'.");if(t.audio&&void 0===t.fastStart.expectedAudioChunks)throw new Error("'fastStart' is an object but is missing property 'expectedAudioChunks'.")}else if(![!1,"in-memory"].includes(t.fastStart))throw new Error("'fastStart' option must be false, 'in-memory' or an object.")},Rt=new WeakSet,Nt=function(){let t="hevc"===u(this,Et).video?.codec;if(u(this,Ut).writeBox((t=>P("ftyp",t?[x("isom"),v(0),x("iso4"),x("hvc1")]:[x("isom"),v(0),x("isom"),x("avc1"),x("mp41")]))(t)),f(this,Bt,u(this,Ut).pos),"in-memory"===u(this,Et).fastStart)f(this,At,F(!1));else{if("object"==typeof u(this,Et).fastStart){let t=m(this,Ot,Ht).call(this);u(this,Ut).seek(u(this,Ut).pos+t)}f(this,At,F(!0)),u(this,Ut).writeBox(u(this,At))}m(this,Zt,Jt).call(this)},Ot=new WeakSet,Ht=function(){if("object"!=typeof u(this,Et).fastStart)return;let t=0,e=[u(this,Et).fastStart.expectedVideoChunks,u(this,Et).fastStart.expectedAudioChunks];for(let i of e)i&&(t+=8*Math.ceil(2/3*i),t+=4*i,t+=12*Math.ceil(2/3*i),t+=4*i,t+=8*i);return t+=4096,t},Vt=new WeakSet,Wt=function(){if(u(this,Et).video&&f(this,It,{id:1,info:{type:"video",codec:u(this,Et).video.codec,width:u(this,Et).video.width,height:u(this,Et).video.height,rotation:u(this,Et).video.rotation??0},timescale:720,codecPrivate:new Uint8Array(0),samples:[],finalizedChunks:[],currentChunk:null,firstTimestamp:void 0,lastTimestamp:-1,timeToSampleTable:[],lastTimescaleUnits:null,compactlyCodedChunkTable:[]}),u(this,Et).audio){let t=m(this,Gt,jt).call(this,2,u(this,Et).audio.sampleRate,u(this,Et).audio.numberOfChannels);f(this,Pt,{id:u(this,Et).video?2:1,info:{type:"audio",codec:u(this,Et).audio.codec,numberOfChannels:u(this,Et).audio.numberOfChannels,sampleRate:u(this,Et).audio.sampleRate},timescale:u(this,Et).audio.sampleRate,codecPrivate:t,samples:[],finalizedChunks:[],currentChunk:null,firstTimestamp:void 0,lastTimestamp:-1,timeToSampleTable:[],lastTimescaleUnits:null,compactlyCodedChunkTable:[]})}},Gt=new WeakSet,jt=function(t,e,i){let r=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350].indexOf(e),s=i,a="";a+=t.toString(2).padStart(5,"0"),a+=r.toString(2).padStart(4,"0"),15===r&&(a+=e.toString(2).padStart(24,"0")),a+=s.toString(2).padStart(4,"0");let n=8*Math.ceil(a.length/8);a=a.padEnd(n,"0");let o=new Uint8Array(a.length/8);for(let t=0;t<a.length;t+=8)o[t/8]=parseInt(a.slice(t,t+8),2);return o},$t=new WeakSet,Yt=function(t,e,i,r,s,a){let n=r/1e6,o=s/1e6;if(void 0===t.firstTimestamp&&(t.firstTimestamp=n),n=m(this,qt,Qt).call(this,n,t),t.lastTimestamp=n,(!t.currentChunk||n-t.currentChunk.startTimestamp>=.5)&&(t.currentChunk&&m(this,Kt,Xt).call(this,t),t.currentChunk={startTimestamp:n,sampleData:[],sampleCount:0}),t.currentChunk.sampleData.push(e),t.currentChunk.sampleCount++,a?.decoderConfig?.description&&(t.codecPrivate=new Uint8Array(a.decoderConfig.description)),t.samples.push({timestamp:n,duration:o,size:e.byteLength,type:i}),null!==t.lastTimescaleUnits){let e=E(n,t.timescale,!1),i=Math.round(e-t.lastTimescaleUnits);t.lastTimescaleUnits+=i;let r=C(t.timeToSampleTable);1===r.sampleCount?(r.sampleDelta=i,r.sampleCount++):r.sampleDelta===i?r.sampleCount++:(r.sampleCount--,t.timeToSampleTable.push({sampleCount:2,sampleDelta:i}))}else t.lastTimescaleUnits=0,t.timeToSampleTable.push({sampleCount:1,sampleDelta:E(o,t.timescale)})},qt=new WeakSet,Qt=function(t,e){if("strict"===u(this,Et).firstTimestampBehavior&&-1===e.lastTimestamp&&0!==t)throw new Error(`The first chunk for your media track must have a timestamp of 0 (received ${t}). Non-zero first timestamps are often caused by directly piping frames or audio data from a MediaStreamTrack into the encoder. Their timestamps are typically relative to the age of the document, which is probably what you want.\n\nIf you want to offset all timestamps of a track such that the first one is zero, set firstTimestampBehavior: 'offset' in the options.\n`);if("offset"===u(this,Et).firstTimestampBehavior&&(t-=e.firstTimestamp),t<e.lastTimestamp)throw new Error(`Timestamps must be monotonically increasing (went from ${1e6*e.lastTimestamp} to ${1e6*t}).`);return t},Kt=new WeakSet,Xt=function(t){if(t.currentChunk)if(0!==t.compactlyCodedChunkTable.length&&C(t.compactlyCodedChunkTable).samplesPerChunk===t.currentChunk.sampleCount||t.compactlyCodedChunkTable.push({firstChunk:t.finalizedChunks.length+1,samplesPerChunk:t.currentChunk.sampleCount}),t.finalizedChunks.push(t.currentChunk),u(this,Ft).push(t.currentChunk),"in-memory"!==u(this,Et).fastStart){t.currentChunk.offset=u(this,Ut).pos;for(let e of t.currentChunk.sampleData)u(this,Ut).write(e);t.currentChunk.sampleData=null,m(this,Zt,Jt).call(this)}else t.currentChunk.offset=0},Zt=new WeakSet,Jt=function(){u(this,Ut)instanceof ft&&u(this,Ut).flush()},te=new WeakSet,ee=function(){if(u(this,Dt))throw new Error("Cannot add new video or audio chunks after the file has been finalized.")}}}]); |