mirror of
https://github.com/zhw2590582/ArtPlayer.git
synced 2026-10-08 19:06:15 -08:00
8 lines
234 KiB
JavaScript
8 lines
234 KiB
JavaScript
|
|
/*!
|
|
* artplayer-proxy-webav.js v1.0.0
|
|
* Github: https://github.com/zhw2590582/ArtPlayer
|
|
* (c) 2017-2025 Harvey Zack
|
|
* Released under the MIT License.
|
|
*/
|
|
!function(t,e,r,s,a,n,o,l){var h="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:{},d="function"==typeof h[s]&&h[s],u=d.i||{},p=d.cache||{},c="undefined"!=typeof module&&"function"==typeof module.require&&module.require.bind(module);function f(e,r){if(!p[e]){if(!t[e]){if(a[e])return a[e];var n="function"==typeof h[s]&&h[s];if(!r&&n)return n(e,!0);if(d)return d(e,!0);if(c&&"string"==typeof e)return c(e);var o=Error("Cannot find module '"+e+"'");throw o.code="MODULE_NOT_FOUND",o}u.resolve=function(r){var s=t[e][1][r];return null!=s?s:r},u.cache={};var l=p[e]=new f.Module(e);t[e][0].call(l.exports,u,l,l.exports,h)}return p[e].exports;function u(t){var e=u.resolve(t);return!1===e?{}:f(e)}}f.isParcelRequire=!0,f.Module=function(t){this.id=t,this.bundle=f,this.require=c,this.exports={}},f.modules=t,f.cache=p,f.parent=d,f.distDir=void 0,f.publicUrl=void 0,f.devServer=void 0,f.i=u,f.register=function(e,r){t[e]=[function(t,e){e.exports=r},{}]},Object.defineProperty(f,"root",{get:function(){return h[s]}}),h[s]=f;for(var m=0;m<e.length;m++)f(e[m]);if(r){var _=f(r);"object"==typeof exports&&"undefined"!=typeof module?module.exports=_:"function"==typeof define&&define.amd&&define(function(){return _})}}({"3E1Az":[function(t,e,r,s){var a=t("@parcel/transformer-js/src/esmodule-helpers.js");a.defineInteropFlag(r),a.export(r,"default",()=>o);var n=t("@webav/av-cliper");function o(t={}){return e=>{let r,s,{option:a,constructor:o}=e,{createElement:l,def:h}=o.utils,d=l("canvas"),u=d.getContext("2d"),p=null,c=null,f=null,m=null,_=0,g={playing:!1,duration:0,videoWidth:0,videoHeight:0,currentTime:0,playbackRate:1,paused:!0,ended:!1,readyState:0,buffered:0,muted:a.muted,volume:a.volume,autoplay:a.autoplay};function y(){f&&(clearInterval(f),f=null),c&&(c.stop(),c=null)}function w(){if(s){let t=g.muted?0:g.volume;s.gain.setValueAtTime(t,r.currentTime)}}async function b(){r||(s=(r=new AudioContext).createGain()).connect(r.destination);let t=1e6*g.currentTime,a=0,n=!0,o=performance.now();async function l(){if(!g.playing)return;let l=performance.now(),h=l-o;o=l,null!==m?(t=1e6*m,m=null,n=!0):t+=1e3*h*g.playbackRate,g.currentTime=t/1e6;let{state:d,video:f,audio:_}=await p.tick(Math.round(t));if(e.emit("video:timeupdate",{type:"timeupdate"}),"done"===d){y(),g.ended=!0,g.playing=!1,g.paused=!0,e.emit("video:ended",{type:"ended"});return}if(f&&"success"===d&&(u.clearRect(0,0,g.videoWidth,g.videoHeight),u.drawImage(f,0,0,g.videoWidth,g.videoHeight),f.close()),n)n=!1;else if(_?.[0]?.length){let t=r.createBuffer(2,_[0].length,48e3);t.copyToChannel(_[0],0),t.copyToChannel(_[1],1),(c=r.createBufferSource()).buffer=t,c.connect(s),c.playbackRate.setValueAtTime(g.playbackRate,r.currentTime),a=Math.max(r.currentTime,a),c.start(a),a+=t.duration/g.playbackRate}}y(),w(),g.playing=!0,g.paused=!1,f=setInterval(l,1e3/60)}async function v(t){let{video:e}=await p.tick(1e6*t);e&&(u.clearRect(0,0,d.width,d.height),u.drawImage(e,0,0,d.width,d.height),e.close())}function S(){let t=e.template?.$player;if(!t||a.autoSize)return;let r=d.videoWidth/d.videoHeight,s=t.clientWidth,n=t.clientHeight,o=0,l=0;s/n>r?o=(s-n*r)/2:l=(n-s/r)/2,Object.assign(d.style,{padding:`${l}px ${o}px`})}async function x(){if(!await n.Combinator.isSupported())throw e.notice.show="WebAV is not supported",Error("WebAV is not supported");y(),Object.assign(g,{playing:!1,duration:0,videoWidth:0,videoHeight:0,currentTime:0,playbackRate:1,paused:!0,ended:!1,readyState:0,buffered:0,muted:a.muted,volume:a.volume,autoplay:a.autoplay}),p&&(p.destroy(),e.emit("video:abort",{type:"abort"}),e.emit("video:emptied",{type:"emptied"}));try{await Promise.resolve(),g.readyState=1,e.emit("video:loadstart",{type:"loadstart"});let r=await fetch(a.url);if(!r.body)throw Error("No response body");p=new(0,n.MP4Clip)(r.body,t)}catch(t){throw g.readyState=0,e.emit("video:error",t),t}let r=await p.ready;Object.assign(g,{readyState:4,duration:Math.round(r.duration/1e6),videoWidth:r.width,videoHeight:r.height}),d.width=g.videoWidth,d.height=g.videoHeight,await v(.1),S(),e.emit("video:loadedmetadata",{type:"loadedmetadata"}),e.emit("video:durationchange",{type:"durationchange"}),e.emit("video:loadeddata",{type:"loadeddata"}),e.emit("video:canplay",{type:"canplay"}),e.emit("video:canplaythrough",{type:"canplaythrough"})}return h(d,"duration",{get:()=>g.duration}),h(d,"videoWidth",{get:()=>g.videoWidth}),h(d,"videoHeight",{get:()=>g.videoHeight}),h(d,"volume",{get:()=>g.volume,set:t=>{g.volume=Math.max(0,Math.min(1,t)),w(),e.emit("video:volumechange",{type:"volumechange"})}}),h(d,"currentTime",{get:()=>g.currentTime,set:t=>{if(g.readyState<4)return;let r=Math.max(0,Math.min(t,g.duration)),s=performance.now();s-_>16&&(_=s,m=r,g.currentTime=r,g.playing||v(r),e.emit("video:timeupdate",{type:"timeupdate"}))}}),h(d,"autoplay",{get:()=>g.autoplay,set:t=>{g.autoplay=t,t&&g.readyState>=4&&d.play()}}),h(d,"src",{get:()=>a.url,set:t=>{a.url=t,x().then(()=>{a.autoplay&&d.play()})}}),h(d,"playbackRate",{get:()=>g.playbackRate,set:t=>{g.playbackRate=Math.max(.25,Math.min(2,t)),c&&c.playbackRate.setValueAtTime(g.playbackRate,r.currentTime),e.emit("video:ratechange",{type:"ratechange"})}}),h(d,"playing",{get:()=>g.playing}),h(d,"paused",{get:()=>g.paused}),h(d,"ended",{get:()=>g.ended}),h(d,"readyState",{get:()=>g.readyState}),h(d,"muted",{get:()=>g.muted,set:t=>{g.muted=t,w(),e.emit("video:volumechange",{type:"volumechange"})}}),h(d,"buffered",{get:()=>({start:()=>0,end:()=>g.buffered,length:1})}),h(d,"play",{value:async()=>!(g.readyState<4)&&(await b(),e.emit("video:play",{type:"play"}),e.emit("video:playing",{type:"playing"}),!0)}),h(d,"pause",{value:()=>{y(),g.playing=!1,g.paused=!0,e.emit("video:pause",{type:"pause"})}}),e.on("destroy",()=>{y(),p&&p.destroy()}),e.on("resize",S),d}}"undefined"!=typeof window&&(window.artplayerProxyWebAV=o)},{"@webav/av-cliper":"4Axd9","@parcel/transformer-js/src/esmodule-helpers.js":"6ykb1"}],"4Axd9":[function(t,e,r,s){var a,n,o,l,h,d,u,p,c,f,m,_,g,y,w,b,v,S,x,U,E,A,C,T,k,B,F,I,z,P,L,R,M,D,O,N,G,W,Y,H,V,j,Z,X,$,K,J,Q,q,tt,te,ti,tr,ts,ta,tn,to,tl,th,td,tu,tp,tc,tf,tm,t_,tg,ty,tw,tb,tv,tS,tx,tU,tE,tA,tC,tT,tk,tB,tF,tI,tz,tP,tL,tR,tM,tD,tO,tN,tG,tW,tY,tH,tV,tj,tZ,tX,t$,tK,tJ,tQ,tq,t0,t1,t2,t3,t6=t("@parcel/transformer-js/src/esmodule-helpers.js");t6.defineInteropFlag(r),t6.export(r,"AudioClip",()=>eO),t6.export(r,"Combinator",()=>ii),t6.export(r,"EmbedSubtitlesClip",()=>eH),t6.export(r,"ImgClip",()=>eM),t6.export(r,"Log",()=>t5.Log),t6.export(r,"MP4Clip",()=>eA),t6.export(r,"MediaStreamClip",()=>eW),t6.export(r,"OffscreenSprite",()=>e5),t6.export(r,"Rect",()=>e6),t6.export(r,"VisibleSprite",()=>e9),t6.export(r,"createChromakey",()=>e2),t6.export(r,"fastConcatMP4",()=>eZ),t6.export(r,"fixFMP4Duration",()=>e$),t6.export(r,"mixinMP4AndAudio",()=>eK),t6.export(r,"renderTxt2ImgBitmap",()=>eh);var t8=t("@webav/mp4box.js"),t4=t6.interopDefault(t8),t5=t("@webav/internal-utils"),t7=t("wave-resampler"),t9=t("opfs-tools"),et=Object.defineProperty,ee=t=>{throw TypeError(t)},ei=(t,e,r)=>e in t?et(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,er=(t,e,r)=>ei(t,"symbol"!=typeof e?e+"":e,r),es=(t,e,r)=>e.has(t)||ee("Cannot "+r),ea=(t,e,r)=>(es(t,e,"read from private field"),r?r.call(t):e.get(t)),en=(t,e,r)=>e.has(t)?ee("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),eo=(t,e,r,s)=>(es(t,e,"write to private field"),s?s.call(t,r):e.set(t,r),r),el=(t,e,r)=>(es(t,e,"access private method"),r);async function eh(t,e){let r=function(t,e){let r=document.createElement("pre");r.style.cssText=`margin: 0; ${e}; visibility: hidden; position: fixed;`,r.textContent=t,document.body.appendChild(r);let{width:s,height:a}=r.getBoundingClientRect();r.remove(),r.style.visibility="visible";let n=new Image;n.width=s,n.height=a;let o=`<svg xmlns="http://www.w3.org/2000/svg" width="${s}" height="${a}"><foreignObject width="100%" height="100%"><div xmlns="http://www.w3.org/1999/xhtml">${r.outerHTML}</div></foreignObject></svg>`.replace(/\t/g,"").replace(/#/g,"%23");return n.src=`data:image/svg+xml;charset=utf-8,${o}`,n}(t,e);await new Promise(t=>{r.onload=t});let s=new OffscreenCanvas(r.width,r.height),a=s.getContext("2d");return null==a||a.drawImage(r,0,0,r.width,r.height),await createImageBitmap(s)}function ed(t){let e=new Float32Array(t.map(t=>t.length).reduce((t,e)=>t+e)),r=0;for(let s of t)e.set(s,r),r+=s.length;return e}function eu(t){if("f32-planar"===t.format){let e=[];for(let r=0;r<t.numberOfChannels;r+=1){let s=new ArrayBuffer(t.allocationSize({planeIndex:r}));t.copyTo(s,{planeIndex:r}),e.push(new Float32Array(s))}return e}if("f32"===t.format){let e=new ArrayBuffer(t.allocationSize({planeIndex:0}));return t.copyTo(e,{planeIndex:0}),function(t,e){let r=t.length/e,s=Array.from({length:e},()=>new Float32Array(r));for(let a=0;a<r;a++)for(let r=0;r<e;r++)s[r][a]=t[a*e+r];return s}(new Float32Array(e),t.numberOfChannels)}if("s16"===t.format){let e=new ArrayBuffer(t.allocationSize({planeIndex:0}));return t.copyTo(e,{planeIndex:0}),function(t,e){let r=t.length/e,s=Array.from({length:e},()=>new Float32Array(r));for(let a=0;a<r;a++)for(let r=0;r<e;r++){let n=t[a*e+r];s[r][a]=n/32768}return s}(new Int16Array(e),t.numberOfChannels)}throw Error("Unsupported audio data format")}function ep(t){return Array(t.numberOfChannels).fill(0).map((e,r)=>t.getChannelData(r))}async function ec(t,e){var r;let s=new ImageDecoder({type:e,data:t});await Promise.all([s.completed,s.tracks.ready]);let a=(null==(r=s.tracks.selectedTrack)?void 0:r.frameCount)??1,n=[];for(let t=0;t<a;t+=1)n.push((await s.decode({frameIndex:t})).image);return n}function ef(t){var e,r;let s=Math.max(...t.map(t=>{var e;return(null==(e=t[0])?void 0:e.length)??0})),a=new Float32Array(2*s);for(let n=0;n<s;n++){let o=0,l=0;for(let s=0;s<t.length;s++){let a=(null==(e=t[s][0])?void 0:e[n])??0,h=(null==(r=t[s][1])?void 0:r[n])??a;o+=a,l+=h}a[n]=o,a[n+s]=l}return a}async function em(t,e,r){let s=t.length,a=Array(r.chanCount).fill(0).map(()=>new Float32Array(0));if(0===s)return a;let n=Math.max(...t.map(t=>t.length));if(0===n)return a;if(null==globalThis.OfflineAudioContext)return t.map(t=>new Float32Array(t7.resample(t,e,r.rate,{method:"sinc",LPF:!1})));let o=new globalThis.OfflineAudioContext(r.chanCount,n*r.rate/e,r.rate),l=o.createBufferSource(),h=o.createBuffer(s,n,e);return t.forEach((t,e)=>h.copyToChannel(t,e)),l.buffer=h,l.connect(o.destination),l.start(),ep(await o.startRendering())}function e_(t){return new Promise(e=>{let r=(0,t5.workerTimer)(()=>{r(),e()},t)})}function eg(t,e,r){let s=r-e,a=new Float32Array(s),n=0;for(;n<s;)a[n]=t[(e+n)%t.length],n+=1;return a}function ey(t,e){let r=Math.floor(t.length/e),s=new Float32Array(r);for(let a=0;a<r;a++){let r=a*e,n=Math.floor(r),o=r-n;n+1<t.length?s[a]=t[n]*(1-o)+t[n+1]*o:s[a]=t[n]}return s}let ew={sampleRate:48e3,channelCount:2,codec:"mp4a.40.2"};function eb(t,e){let r=e.videoTracks[0],s={};if(null!=r){let a=function(t){for(let e of t.mdia.minf.stbl.stsd.entries){let t=e.avcC??e.hvcC??e.av1C??e.vpcC;if(null!=t){let e=new t4.default.DataStream(void 0,0,t4.default.DataStream.BIG_ENDIAN);return t.write(e),new Uint8Array(e.buffer.slice(8))}}throw Error("avcC, hvcC, av1C or VPX not found")}(t.getTrackById(r.id)).buffer,{descKey:n,type:o}=r.codec.startsWith("avc1")?{descKey:"avcDecoderConfigRecord",type:"avc1"}:r.codec.startsWith("hvc1")?{descKey:"hevcDecoderConfigRecord",type:"hvc1"}:{descKey:"",type:""};""!==n&&(s.videoTrackConf={timescale:r.timescale,duration:r.duration,width:r.video.width,height:r.video.height,brands:e.brands,type:o,[n]:a}),s.videoDecoderConf={codec:r.codec,codedHeight:r.video.height,codedWidth:r.video.width,description:a}}let a=e.audioTracks[0];if(null!=a){let e=ev(t);s.audioTrackConf={timescale:a.timescale,samplerate:a.audio.sample_rate,channel_count:a.audio.channel_count,hdlr:"soun",type:a.codec.startsWith("mp4a")?"mp4a":a.codec,description:ev(t)},s.audioDecoderConf={codec:a.codec.startsWith("mp4a")?ew.codec:a.codec,numberOfChannels:a.audio.channel_count,sampleRate:a.audio.sample_rate,...null==e?{}:function(t){var e;let r=null==(e=t.esd.descs[0])?void 0:e.descs[0];if(null==r)return{};let[s,a]=r.data;return{sampleRate:[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][((7&s)<<1)+(a>>7)],numberOfChannels:(127&a)>>3}}(e)}}return s}function ev(t,e="mp4a"){var r;let s=null==(r=t.moov)?void 0:r.traks.map(t=>t.mdia.minf.stbl.stsd.entries).flat().find(({type:t})=>t===e);return null==s?void 0:s.esds}async function eS(t,e,r){let s=t4.default.createFile(!1);async function a(){let e=0;for(;;){let r=await t.read(0x1e00000,{at:e});if(0===r.byteLength)break;r.fileStart=e;let a=s.appendBuffer(r);if(null==a)break;e=a}s.stop()}s.onReady=t=>{var r,a;e({mp4boxFile:s,info:t});let n=null==(r=t.videoTracks[0])?void 0:r.id;null!=n&&s.setExtractionOptions(n,"video",{nbSamples:100});let o=null==(a=t.audioTracks[0])?void 0:a.id;null!=o&&s.setExtractionOptions(o,"audio",{nbSamples:100}),s.start()},s.onSamples=r,await a()}let ex=0;function eU(t){return"file"===t.kind&&t.createReader instanceof Function}let eE=class t{constructor(t,e={}){if(en(this,a,ex++),en(this,n,t5.Log.create(`MP4Clip id:${ea(this,a)},`)),er(this,"ready"),en(this,o,!1),en(this,l,{duration:0,width:0,height:0,audioSampleRate:0,audioChanCount:0}),en(this,h),en(this,d,[]),en(this,u,1),en(this,p,[]),en(this,c,[]),en(this,f,null),en(this,m,null),en(this,_,{video:null,audio:null}),en(this,g,{audio:!0}),er(this,"tickInterceptor",async(t,e)=>e),en(this,y,new AbortController),!(t instanceof ReadableStream)&&!eU(t)&&!Array.isArray(t.videoSamples))throw Error("Illegal argument");eo(this,g,{audio:!0,...e}),eo(this,u,"object"==typeof e.audio&&"volume"in e.audio?e.audio.volume:1);let r=async t=>(await (0,t9.write)(ea(this,h),t),ea(this,h));eo(this,h,eU(t)?t:"localFile"in t?t.localFile:(0,t9.tmpfile)()),this.ready=(t instanceof ReadableStream?r(t).then(t=>eC(t,ea(this,g))):eU(t)?eC(t,ea(this,g)):Promise.resolve(t)).then(async({videoSamples:t,audioSamples:e,decoderConf:r,headerBoxPos:s})=>{var a,o,y,w,b;eo(this,p,t),eo(this,c,e),eo(this,_,r),eo(this,d,s);let{videoFrameFinder:v,audioFrameFinder:S}=(a={video:null==r.video?null:{...r.video,hardwareAcceleration:ea(this,g).__unsafe_hardwareAcceleration__},audio:r.audio},o=await ea(this,h).createReader(),y=t,w=e,{audioFrameFinder:0===(b=!1!==ea(this,g).audio?ea(this,u):0)||null==a.audio||0===w.length?null:new ek(o,w,a.audio,{volume:b,targetSampleRate:ew.sampleRate}),videoFrameFinder:null==a.video||0===y.length?null:new eT(o,y,a.video)});return eo(this,f,v),eo(this,m,S),eo(this,l,function(t,e,r){let s={duration:0,width:0,height:0,audioSampleRate:0,audioChanCount:0};null!=t.video&&e.length>0&&(s.width=t.video.codedWidth??0,s.height=t.video.codedHeight??0),null!=t.audio&&r.length>0&&(s.audioSampleRate=ew.sampleRate,s.audioChanCount=ew.channelCount);let a=0,n=0;if(e.length>0)for(let t=e.length-1;t>=0;t--){let r=e[t];if(!r.deleted){a=r.cts+r.duration;break}}if(r.length>0){let t=r.at(-1);n=t.cts+t.duration}return s.duration=Math.max(a,n),s}(r,t,e)),ea(this,n).info("MP4Clip meta:",ea(this,l)),{...ea(this,l)}})}get meta(){return{...ea(this,l)}}async getFileHeaderBinData(){await this.ready;let t=await ea(this,h).getOriginFile();if(null==t)throw Error("MP4Clip localFile is not origin file");return await new Blob(ea(this,d).map(({start:e,size:r})=>t.slice(e,e+r))).arrayBuffer()}async tick(t){var e,r,s;if(t>=ea(this,l).duration)return await this.tickInterceptor(t,{audio:await (null==(e=ea(this,m))?void 0:e.find(t))??[],state:"done"});let[a,n]=await Promise.all([(null==(r=ea(this,m))?void 0:r.find(t))??[],null==(s=ea(this,f))?void 0:s.find(t)]);return null==n?await this.tickInterceptor(t,{audio:a,state:"success"}):await this.tickInterceptor(t,{video:n,audio:a,state:"success"})}async thumbnails(t=100,e){ea(this,y).abort(),eo(this,y,new AbortController);let r=ea(this,y).signal;await this.ready;let s="generate thumbnails aborted";if(r.aborted)throw Error(s);let{width:a,height:n}=ea(this,l),o=function(t,e,r){let s=new OffscreenCanvas(t,e),a=s.getContext("2d");return async n=>(a.drawImage(n,0,0,t,e),n.close(),await s.convertToBlob(r))}(t,Math.round(t/a*n),{quality:.1,type:"image/png"});return new Promise(async(t,a)=>{let n=[],d=ea(this,_).video;if(null==d||0===ea(this,p).length)return void u();async function u(){r.aborted||t(await Promise.all(n.map(async t=>({ts:t.ts,img:await t.img}))))}function c(t){n.push({ts:t.timestamp,img:o(t)})}r.addEventListener("abort",()=>{a(Error(s))});let{start:f=0,end:m=ea(this,l).duration,step:y}=e??{};if(y){let t=f,e=new eT(await ea(this,h).createReader(),ea(this,p),{...d,hardwareAcceleration:ea(this,g).__unsafe_hardwareAcceleration__});for(;t<=m&&!r.aborted;){let r=await e.find(t);r&&c(r),t+=y}e.destroy(),u()}else await ez(ea(this,p),ea(this,h),d,r,{start:f,end:m},(t,e)=>{null!=t&&c(t),e&&u()})})}async split(e){if(await this.ready,e<=0||e>=ea(this,l).duration)throw Error('"time" out of bounds');let[r,s]=function(t,e){if(0===t.length)return[];let r=0,s=0,a=-1;for(let n=0;n<t.length;n++){let o=t[n];if(-1===a&&e<o.cts&&(a=n-1),o.is_idr)if(-1===a)r=n;else{s=n;break}}let n=t[a];if(null==n)throw Error("Not found video sample by time");let o=t.slice(0,0===s?t.length:s).map(t=>({...t}));for(let t=r;t<o.length;t++){let r=o[t];e<r.cts&&(r.deleted=!0,r.cts=-1)}eP(o);let l=t.slice(n.is_idr?a:r).map(t=>({...t,cts:t.cts-e}));for(let t of l)t.cts<0&&(t.deleted=!0,t.cts=-1);return eP(l),[o,l]}(ea(this,p),e),[a,n]=function(t,e){if(0===t.length)return[];let r=-1;for(let s=0;s<t.length;s++)if(!(e>t[s].cts)){r=s;break}if(-1===r)throw Error("Not found audio sample by time");return[t.slice(0,r).map(t=>({...t})),t.slice(r).map(t=>({...t,cts:t.cts-e}))]}(ea(this,c),e),o=new t({localFile:ea(this,h),videoSamples:r??[],audioSamples:a??[],decoderConf:ea(this,_),headerBoxPos:ea(this,d)},ea(this,g)),u=new t({localFile:ea(this,h),videoSamples:s??[],audioSamples:n??[],decoderConf:ea(this,_),headerBoxPos:ea(this,d)},ea(this,g));return await Promise.all([o.ready,u.ready]),[o,u]}async clone(){await this.ready;let e=new t({localFile:ea(this,h),videoSamples:[...ea(this,p)],audioSamples:[...ea(this,c)],decoderConf:ea(this,_),headerBoxPos:ea(this,d)},ea(this,g));return await e.ready,e.tickInterceptor=this.tickInterceptor,e}async splitTrack(){await this.ready;let e=[];if(ea(this,p).length>0){let r=new t({localFile:ea(this,h),videoSamples:[...ea(this,p)],audioSamples:[],decoderConf:{video:ea(this,_).video,audio:null},headerBoxPos:ea(this,d)},ea(this,g));await r.ready,r.tickInterceptor=this.tickInterceptor,e.push(r)}if(ea(this,c).length>0){let r=new t({localFile:ea(this,h),videoSamples:[],audioSamples:[...ea(this,c)],decoderConf:{audio:ea(this,_).audio,video:null},headerBoxPos:ea(this,d)},ea(this,g));await r.ready,r.tickInterceptor=this.tickInterceptor,e.push(r)}return e}destroy(){var t,e;ea(this,o)||(ea(this,n).info("MP4Clip destroy"),eo(this,o,!0),null==(t=ea(this,f))||t.destroy(),null==(e=ea(this,m))||e.destroy())}};a=new WeakMap,n=new WeakMap,o=new WeakMap,l=new WeakMap,h=new WeakMap,d=new WeakMap,u=new WeakMap,p=new WeakMap,c=new WeakMap,f=new WeakMap,m=new WeakMap,_=new WeakMap,g=new WeakMap,y=new WeakMap;let eA=eE;async function eC(t,e={}){let r=null,s={video:null,audio:null},a=[],n=[],o=[],l=-1,h=-1,d=await t.createReader();await eS(d,t=>{r=t.info;let e=t.mp4boxFile.ftyp;o.push({start:e.start,size:e.size});let a=t.mp4boxFile.moov;o.push({start:a.start,size:a.size});let{videoDecoderConf:n,audioDecoderConf:l}=eb(t.mp4boxFile,t.info);s.video=n??null,s.audio=l??null,null==n&&null==l&&t5.Log.error("MP4Clip no video and audio track"),t5.Log.info("mp4BoxFile moov ready",{...t.info,tracks:null,videoTracks:null,audioTracks:null},s)},(t,r,s)=>{if("video"===r)for(let t of(-1===l&&(l=s[0].dts),s))a.push(p(t,l,"video"));else if("audio"===r&&e.audio)for(let t of(-1===h&&(h=s[0].dts),s))n.push(p(t,h,"audio"))}),await d.close();let u=a.at(-1)??n.at(-1);if(null==r)throw Error("MP4Clip stream is done, but not emit ready");if(null==u)throw Error("MP4Clip stream not contain any sample");return eP(a),t5.Log.info("mp4 stream parsed"),{videoSamples:a,audioSamples:n,decoderConf:s,headerBoxPos:o};function p(t,e=0,r){let s="video"===r&&t.is_sync?function(t,e){if("avc1"!==e&&"hvc1"!==e)return 0;let r=new DataView(t.buffer),s=0;for(;s<t.byteLength-4;){if("avc1"===e&&(31&r.getUint8(s+4))==5)return s;if("hvc1"===e){let t=r.getUint8(s+4)>>1&63;if(19===t||20===t)return s}s+=r.getUint32(s)+4}return -1}(t.data,t.description.type):-1,a=t.offset,n=t.size;return s>=0&&(a+=s,n-=s),{...t,is_idr:s>=0,offset:a,size:n,cts:(t.cts-e)/t.timescale*1e6,dts:(t.dts-e)/t.timescale*1e6,duration:t.duration/t.timescale*1e6,timescale:1e6,data:"video"===r?null:t.data}}}class eT{constructor(t,e,r){en(this,w,null),en(this,b,0),en(this,v,{abort:!1,st:performance.now()}),er(this,"find",async t=>{(null==ea(this,w)||"closed"===ea(this,w).state||t<=ea(this,b)||t-ea(this,b)>3e6)&&ea(this,z).call(this,t),ea(this,v).abort=!0,eo(this,b,t),eo(this,v,{abort:!1,st:performance.now()});let e=await ea(this,B).call(this,t,ea(this,w),ea(this,v));return eo(this,T,0),e}),en(this,S,0),en(this,x,!1),en(this,U,0),en(this,E,[]),en(this,A,0),en(this,C,0),en(this,T,0),en(this,k,!1),en(this,B,async(t,e,r)=>{if(null==e||"closed"===e.state||r.abort)return null;if(ea(this,E).length>0){let s=ea(this,E)[0];return t<s.timestamp?null:(ea(this,E).shift(),t>s.timestamp+(s.duration??0)?(s.close(),await ea(this,B).call(this,t,e,r)):(!ea(this,k)&&ea(this,E).length<10&&ea(this,I).call(this,e).catch(e=>{throw eo(this,k,!0),ea(this,z).call(this,t),e}),s))}if(ea(this,F)||ea(this,A)<ea(this,C)&&e.decodeQueueSize>0){if(performance.now()-r.st>6e3)throw Error(`MP4Clip.tick video timeout, ${JSON.stringify(ea(this,P).call(this))}`);eo(this,T,ea(this,T)+1),await e_(15)}else{if(ea(this,U)>=this.samples.length)return null;try{await ea(this,I).call(this,e)}catch(e){throw ea(this,z).call(this,t),e}}return await ea(this,B).call(this,t,e,r)}),en(this,F,!1),en(this,I,async t=>{var e,r;if(ea(this,F)||t.decodeQueueSize>600)return;let s=ea(this,U)+1;if(s>this.samples.length)return;eo(this,F,!0);let a=!1;for(;s<this.samples.length;s++){let t=this.samples[s];if(a||t.deleted||(a=!0),t.is_idr)break}if(a){let a=this.samples.slice(ea(this,U),s);if((null==(e=a[0])?void 0:e.is_idr)!==!0)t5.Log.warn("First sample not idr frame");else{let e=performance.now(),s=await eF(a,this.localFileReader),n=performance.now()-e;if(n>1e3){let t=a[0],e=a.at(-1),r=e.offset+e.size-t.offset;t5.Log.warn(`Read video samples time cost: ${Math.round(n)}ms, file chunk size: ${r}`)}if("closed"===t.state)return;eo(this,S,(null==(r=s[0])?void 0:r.duration)??0),eI(t,s,{onDecodingError:t=>{if(ea(this,x))throw t;0===ea(this,A)&&(eo(this,x,!0),t5.Log.warn("Downgrade to software decode"),ea(this,z).call(this))}}),eo(this,C,ea(this,C)+s.length)}}eo(this,U,s),eo(this,F,!1)}),en(this,z,t=>{var e,r;if(eo(this,F,!1),ea(this,E).forEach(t=>t.close()),eo(this,E,[]),null==t||0===t)eo(this,U,0);else{let e=0;for(let r=0;r<this.samples.length;r++){let s=this.samples[r];if(s.is_idr&&(e=r),!(s.cts<t)){eo(this,U,e);break}}}eo(this,C,0),eo(this,A,0),(null==(e=ea(this,w))?void 0:e.state)!=="closed"&&(null==(r=ea(this,w))||r.close());let s={...this.conf,...ea(this,x)?{hardwareAcceleration:"prefer-software"}:{}};eo(this,w,new VideoDecoder({output:t=>{if(eo(this,A,ea(this,A)+1),-1===t.timestamp)return void t.close();let e=t;null==t.duration&&(e=new VideoFrame(t,{duration:ea(this,S)}),t.close()),ea(this,E).push(e)},error:t=>{if(t.message.includes("Codec reclaimed due to inactivity")){eo(this,w,null),t5.Log.warn(t.message);return}let e=`VideoFinder VideoDecoder err: ${t.message}, config: ${JSON.stringify(s)}, state: ${JSON.stringify(ea(this,P).call(this))}`;throw t5.Log.error(e),Error(e)}})),ea(this,w).configure(s)}),en(this,P,()=>{var t,e;return{time:ea(this,b),decState:null==(t=ea(this,w))?void 0:t.state,decQSize:null==(e=ea(this,w))?void 0:e.decodeQueueSize,decCusorIdx:ea(this,U),sampleLen:this.samples.length,inputCnt:ea(this,C),outputCnt:ea(this,A),cacheFrameLen:ea(this,E).length,softDeocde:ea(this,x),clipIdCnt:ex,sleepCnt:ea(this,T),memInfo:eL()}}),er(this,"destroy",()=>{var t,e;(null==(t=ea(this,w))?void 0:t.state)!=="closed"&&(null==(e=ea(this,w))||e.close()),eo(this,w,null),ea(this,v).abort=!0,ea(this,E).forEach(t=>t.close()),eo(this,E,[]),this.localFileReader.close()}),this.localFileReader=t,this.samples=e,this.conf=r}}w=new WeakMap,b=new WeakMap,v=new WeakMap,S=new WeakMap,x=new WeakMap,U=new WeakMap,E=new WeakMap,A=new WeakMap,C=new WeakMap,T=new WeakMap,k=new WeakMap,B=new WeakMap,F=new WeakMap,I=new WeakMap,z=new WeakMap,P=new WeakMap;class ek{constructor(t,e,r,s){en(this,L,1),en(this,R),en(this,M,null),en(this,D,{abort:!1,st:performance.now()}),er(this,"find",async t=>{let e=t<=ea(this,O)||t-ea(this,O)>1e5;(null==ea(this,M)||"closed"===ea(this,M).state||e)&&ea(this,V).call(this),e&&(eo(this,O,t),eo(this,N,function(t,e){for(let r=0;r<e.length;r++){let s=e[r];if(t>=s.cts&&t<s.cts+s.duration)return r;if(s.cts>t)break}return 0}(t,this.samples))),ea(this,D).abort=!0;let r=t-ea(this,O);eo(this,O,t),eo(this,D,{abort:!1,st:performance.now()});let s=await ea(this,Y).call(this,Math.ceil(r*(ea(this,R)/1e6)),ea(this,M),ea(this,D));return eo(this,W,0),s}),en(this,O,0),en(this,N,0),en(this,G,{frameCnt:0,data:[]}),en(this,W,0),en(this,Y,async(t,e=null,r)=>{if(null==e||r.abort||"closed"===e.state||0===t)return[];let s=ea(this,G).frameCnt-t;if(s>0)return s<ew.sampleRate/10&&ea(this,H).call(this,e),eB(ea(this,G),t);if(e.decoding){if(performance.now()-r.st>3e3)throw r.abort=!0,Error(`MP4Clip.tick audio timeout, ${JSON.stringify(ea(this,j).call(this))}`);eo(this,W,ea(this,W)+1),await e_(15)}else{if(ea(this,N)>=this.samples.length-1)return eB(ea(this,G),ea(this,G).frameCnt);ea(this,H).call(this,e)}return ea(this,Y).call(this,t,e,r)}),en(this,H,t=>{if(t.decodeQueueSize>10)return;let e=[],r=ea(this,N);for(;r<this.samples.length;){let t=this.samples[r];if(r+=1,!t.deleted&&(e.push(t),e.length>=10))break}eo(this,N,r),t.decode(e.map(t=>new EncodedAudioChunk({type:"key",timestamp:t.cts,duration:t.duration,data:t.data})))}),en(this,V,()=>{var t;eo(this,O,0),eo(this,N,0),eo(this,G,{frameCnt:0,data:[]}),null==(t=ea(this,M))||t.close(),eo(this,M,function(t,e,r){let s=0,a=0,n=t=>{if(a+=1,0!==t.length){if(1!==e.volume)for(let r of t)for(let t=0;t<r.length;t++)r[t]*=e.volume;1===t.length&&(t=[t[0],t[0]]),r(t)}},o=function(t){let e=[],r=0;function s(){let a=e[r];null!=a&&(t(a),r+=1,s())}let a=0;return t=>{let r=a;a+=1,t().then(t=>{e[r]=t,s()}).catch(t=>{e[r]=t,s()})}}(n),l=e.resampleRate!==t.sampleRate,h=new AudioDecoder({output:t=>{let r=eu(t);l?o(()=>em(r,t.sampleRate,{rate:e.resampleRate,chanCount:t.numberOfChannels})):n(r),t.close()},error:t=>{t.message.includes("Codec reclaimed due to inactivity")||d("MP4Clip AudioDecoder err",t)}});function d(t,e){let r=`${t}: ${e.message}, state: ${JSON.stringify({qSize:h.decodeQueueSize,state:h.state,inputCnt:s,outputCnt:a})}`;throw t5.Log.error(r),Error(r)}return h.configure(t),{decode(t){s+=t.length;try{for(let e of t)h.decode(e)}catch(t){d("decode audio chunk error",t)}},close(){"closed"!==h.state&&h.close()},get decoding(){return s>a&&h.decodeQueueSize>0},get state(){return h.state},get decodeQueueSize(){return h.decodeQueueSize}}}(this.conf,{resampleRate:ew.sampleRate,volume:ea(this,L)},t=>{ea(this,G).data.push(t),ea(this,G).frameCnt+=t[0].length}))}),en(this,j,()=>{var t,e;return{time:ea(this,O),decState:null==(t=ea(this,M))?void 0:t.state,decQSize:null==(e=ea(this,M))?void 0:e.decodeQueueSize,decCusorIdx:ea(this,N),sampleLen:this.samples.length,pcmLen:ea(this,G).frameCnt,clipIdCnt:ex,sleepCnt:ea(this,W),memInfo:eL()}}),er(this,"destroy",()=>{eo(this,M,null),ea(this,D).abort=!0,eo(this,G,{frameCnt:0,data:[]}),this.localFileReader.close()}),this.localFileReader=t,this.samples=e,this.conf=r,eo(this,L,s.volume),eo(this,R,s.targetSampleRate)}}function eB(t,e){let r=[new Float32Array(e),new Float32Array(e)],s=0,a=0;for(;a<t.data.length;){let[n,o]=t.data[a];if(s+n.length>e){let l=e-s;r[0].set(n.subarray(0,l),s),r[1].set(o.subarray(0,l),s),t.data[a][0]=n.subarray(l,n.length),t.data[a][1]=o.subarray(l,o.length);break}r[0].set(n,s),r[1].set(o,s),s+=n.length,a++}return t.data=t.data.slice(a),t.frameCnt-=e,r}async function eF(t,e){let r=t[0],s=t.at(-1);if(null==s)return[];let a=s.offset+s.size-r.offset;if(a<3e7){let s=new Uint8Array(await e.read(a,{at:r.offset}));return t.map(t=>{let e=t.offset-r.offset;return new EncodedVideoChunk({type:t.is_sync?"key":"delta",timestamp:t.cts,duration:t.duration,data:s.subarray(e,e+t.size)})})}return await Promise.all(t.map(async t=>new EncodedVideoChunk({type:t.is_sync?"key":"delta",timestamp:t.cts,duration:t.duration,data:await e.read(t.size,{at:t.offset})})))}function eI(t,e,r){let s=0;if("configured"===t.state){for(;s<e.length;s++)t.decode(e[s]);t.flush().catch(t=>{if(!(t instanceof Error))throw t;if(t.message.includes("Decoding error")&&null!=r.onDecodingError)return void r.onDecodingError(t);if(!t.message.includes("Aborted due to close"))throw t})}}async function ez(t,e,r,s,a,n){let o=await e.createReader(),l=await eF(t.filter(t=>!t.deleted&&t.is_sync&&t.cts>=a.start&&t.cts<=a.end),o);if(0===l.length||s.aborted)return;let h=0;function d(t=!1){let e={...r,...t?{hardwareAcceleration:"prefer-software"}:{}},a=new VideoDecoder({output:t=>{let e=(h+=1)===l.length;n(t,e),e&&(o.close(),"closed"!==a.state&&a.close())},error:t=>{let r=`thumbnails decoder error: ${t.message}, config: ${JSON.stringify(e)}, state: ${JSON.stringify({qSize:a.decodeQueueSize,state:a.state,outputCnt:h,inputCnt:l.length})}`;throw t5.Log.error(r),Error(r)}});return s.addEventListener("abort",()=>{o.close(),"closed"!==a.state&&a.close()}),a.configure(e),a}eI(d(),l,{onDecodingError:t=>{t5.Log.warn("thumbnailsByKeyFrame",t),0===h?eI(d(!0),l,{onDecodingError:t=>{o.close(),t5.Log.error("thumbnailsByKeyFrame retry soft deocde",t)}}):(n(null,!0),o.close())}})}function eP(t){let e=0,r=null;for(let s of t)if(!s.deleted){if(s.is_sync&&(e+=1),e>=2)break;(null==r||s.cts<r.cts)&&(r=s)}null!=r&&r.cts<2e5&&(r.duration+=r.cts,r.cts=0)}function eL(){try{let t=performance.memory;return{jsHeapSizeLimit:t.jsHeapSizeLimit,totalJSHeapSize:t.totalJSHeapSize,usedJSHeapSize:t.usedJSHeapSize,percentUsed:(t.usedJSHeapSize/t.jsHeapSizeLimit).toFixed(3),percentTotal:(t.totalJSHeapSize/t.jsHeapSizeLimit).toFixed(3)}}catch{return{}}}L=new WeakMap,R=new WeakMap,M=new WeakMap,D=new WeakMap,O=new WeakMap,N=new WeakMap,G=new WeakMap,W=new WeakMap,Y=new WeakMap,H=new WeakMap,V=new WeakMap,j=new WeakMap;let eR=class t{constructor(t){en(this,K),er(this,"ready"),en(this,Z,{duration:0,width:0,height:0}),en(this,X,null),en(this,$,[]),er(this,"tickInterceptor",async(t,e)=>e);let e=t=>(eo(this,X,t),ea(this,Z).width=t.width,ea(this,Z).height=t.height,ea(this,Z).duration=1/0,{...ea(this,Z)});if(t instanceof ReadableStream)this.ready=new Response(t).blob().then(t=>createImageBitmap(t)).then(e);else if(t instanceof ImageBitmap)this.ready=Promise.resolve(e(t));else if(Array.isArray(t)&&t.every(t=>t instanceof VideoFrame)){eo(this,$,t);let e=ea(this,$)[0];if(null==e)throw Error("The frame count must be greater than 0");eo(this,Z,{width:e.displayWidth,height:e.displayHeight,duration:ea(this,$).reduce((t,e)=>t+(e.duration??0),0)}),this.ready=Promise.resolve({...ea(this,Z),duration:1/0})}else if("type"in t)this.ready=el(this,K,J).call(this,t.stream,t.type).then(()=>({width:ea(this,Z).width,height:ea(this,Z).height,duration:1/0}));else throw Error("Illegal arguments")}get meta(){return{...ea(this,Z)}}async tick(t){if(null!=ea(this,X))return await this.tickInterceptor(t,{video:await createImageBitmap(ea(this,X)),state:"success"});let e=t%ea(this,Z).duration;return await this.tickInterceptor(t,{video:(ea(this,$).find(t=>e>=t.timestamp&&e<=t.timestamp+(t.duration??0))??ea(this,$)[0]).clone(),state:"success"})}async split(e){if(await this.ready,null!=ea(this,X))return[new t(await createImageBitmap(ea(this,X))),new t(await createImageBitmap(ea(this,X)))];let r=-1;for(let t=0;t<ea(this,$).length;t++)if(!(e>ea(this,$)[t].timestamp)){r=t;break}if(-1===r)throw Error("Not found frame by time");let s=ea(this,$).slice(0,r).map(t=>new VideoFrame(t)),a=ea(this,$).slice(r).map(t=>new VideoFrame(t,{timestamp:t.timestamp-e}));return[new t(s),new t(a)]}async clone(){return await this.ready,new t(null==ea(this,X)?ea(this,$).map(t=>t.clone()):await createImageBitmap(ea(this,X)))}destroy(){var t;t5.Log.info("ImgClip destroy"),null==(t=ea(this,X))||t.close(),ea(this,$).forEach(t=>t.close())}};Z=new WeakMap,X=new WeakMap,$=new WeakMap,K=new WeakSet,J=async function(t,e){eo(this,$,await ec(t,e));let r=ea(this,$)[0];if(null==r)throw Error("No frame available in gif");eo(this,Z,{duration:ea(this,$).reduce((t,e)=>t+(e.duration??0),0),width:r.codedWidth,height:r.codedHeight}),t5.Log.info("ImgClip ready:",ea(this,Z))};let eM=eR,eD=class t{constructor(t,e={}){en(this,ti),er(this,"ready"),en(this,Q,{duration:0,width:0,height:0}),en(this,q,new Float32Array),en(this,tt,new Float32Array),en(this,te),er(this,"tickInterceptor",async(t,e)=>e),en(this,ts,0),en(this,ta,0),eo(this,te,{loop:!1,volume:1,...e}),this.ready=el(this,ti,tr).call(this,t).then(()=>({width:0,height:0,duration:e.loop?1/0:ea(this,Q).duration}))}get meta(){return{...ea(this,Q),sampleRate:ew.sampleRate,chanCount:2}}getPCMData(){return[ea(this,q),ea(this,tt)]}async tick(t){if(!ea(this,te).loop&&t>=ea(this,Q).duration)return await this.tickInterceptor(t,{audio:[],state:"done"});let e=t-ea(this,ts);if(t<ea(this,ts)||e>3e6)return eo(this,ts,t),eo(this,ta,Math.ceil(ea(this,ts)/1e6*ew.sampleRate)),await this.tickInterceptor(t,{audio:[new Float32Array(0),new Float32Array(0)],state:"success"});eo(this,ts,t);let r=Math.ceil(e/1e6*ew.sampleRate),s=ea(this,ta)+r,a=ea(this,te).loop?[eg(ea(this,q),ea(this,ta),s),eg(ea(this,tt),ea(this,ta),s)]:[ea(this,q).slice(ea(this,ta),s),ea(this,tt).slice(ea(this,ta),s)];return eo(this,ta,s),await this.tickInterceptor(t,{audio:a,state:"success"})}async split(e){await this.ready;let r=Math.ceil(e/1e6*ew.sampleRate);return[new t(this.getPCMData().map(t=>t.slice(0,r)),ea(this,te)),new t(this.getPCMData().map(t=>t.slice(r)),ea(this,te))]}async clone(){await this.ready;let e=new t(this.getPCMData(),ea(this,te));return await e.ready,e}destroy(){eo(this,q,new Float32Array(0)),eo(this,tt,new Float32Array(0)),t5.Log.info("---- audioclip destroy ----")}};Q=new WeakMap,q=new WeakMap,tt=new WeakMap,te=new WeakMap,ti=new WeakSet,tr=async function(t){null==eD.ctx&&(eD.ctx=new AudioContext({sampleRate:ew.sampleRate}));let e=performance.now(),r=t instanceof ReadableStream?await eN(t,eD.ctx):t;t5.Log.info("Audio clip decoded complete:",performance.now()-e);let s=ea(this,te).volume;if(1!==s)for(let t of r)for(let e=0;e<t.length;e+=1)t[e]*=s;ea(this,Q).duration=r[0].length/ew.sampleRate*1e6,eo(this,q,r[0]),eo(this,tt,r[1]??ea(this,q)),t5.Log.info("Audio clip convert to AudioData, time:",performance.now()-e)},ts=new WeakMap,ta=new WeakMap,er(eD,"ctx",null);let eO=eD;async function eN(t,e){let r=await new Response(t).arrayBuffer();return ep(await e.decodeAudioData(r))}let eG=class t{constructor(t){er(this,"ready"),en(this,tn,{duration:0,width:0,height:0}),en(this,to,()=>{}),er(this,"audioTrack"),en(this,tl,null),en(this,th),eo(this,th,t),this.audioTrack=t.getAudioTracks()[0]??null,ea(this,tn).duration=1/0;let e=t.getVideoTracks()[0];null!=e?(e.contentHint="motion",this.ready=new Promise(t=>{var r,s;let a,n;eo(this,to,(r=e,s=e=>{ea(this,tn).width=e.width,ea(this,tn).height=e.height,eo(this,tl,e),t(this.meta)},a=!1,(0,t5.autoReadStream)(new MediaStreamTrackProcessor({track:r}).readable,{onChunk:async t=>{if(!a){let{displayHeight:e,displayWidth:r}=t,o=new OffscreenCanvas(r??0,e??0);n=o.getContext("2d"),s(o),a=!0}n.drawImage(t,0,0),t.close()},onDone:async()=>{}})))})):this.ready=Promise.resolve(this.meta)}get meta(){return{...ea(this,tn)}}async tick(){return{video:null==ea(this,tl)?null:await createImageBitmap(ea(this,tl)),audio:[],state:"success"}}async split(){return[await this.clone(),await this.clone()]}async clone(){return new t(ea(this,th).clone())}destroy(){ea(this,th).getTracks().forEach(t=>t.stop()),ea(this,to).call(this)}};tn=new WeakMap,to=new WeakMap,tl=new WeakMap,th=new WeakMap,er(eG,"ctx",null);let eW=eG,eY=class t{constructor(t,e){var r;if(en(this,ty),er(this,"ready"),en(this,td,[]),en(this,tu,{width:0,height:0,duration:0}),en(this,tp,{color:"#FFF",textBgColor:null,type:"srt",fontSize:30,letterSpacing:null,bottomOffset:30,fontFamily:"Noto Sans SC",strokeStyle:"#000",lineWidth:null,lineCap:null,lineJoin:null,textShadow:{offsetX:2,offsetY:2,blur:4,color:"#000"},videoWidth:1280,videoHeight:720}),en(this,tc),en(this,tf),en(this,tm,null),en(this,t_,0),en(this,tg,0),eo(this,td,Array.isArray(t)?t:t.split(/\r|\n/).map(t=>t.trim()).filter(t=>t.length>0).map(t=>({lineStr:t,match:t.match(/(\d{2}:\d{2}:\d{2},\d{3}) --> (\d{2}:\d{2}:\d{2},\d{3})/)})).filter(({lineStr:t},e,r)=>{var s;return!(/^\d+$/.test(t)&&(null==(s=r[e+1])?void 0:s.match)!=null)}).reduce((t,{lineStr:e,match:r})=>{if(null==r){let r=t.at(-1);if(null==r)return t;r.text+=0===r.text.length?e:` ${e}`}else t.push({start:eV(r[1]),end:eV(r[2]),text:""});return t},[]).map(({start:t,end:e,text:r})=>({start:1e6*t,end:1e6*e,text:r}))),0===ea(this,td).length)throw Error("No subtitles content");eo(this,tp,Object.assign(ea(this,tp),e)),eo(this,tg,null==e.textBgColor?0:(e.fontSize??50)*.2);let{fontSize:s,fontFamily:a,videoWidth:n,videoHeight:o,letterSpacing:l}=ea(this,tp);eo(this,t_,s+2*ea(this,tg)),eo(this,tc,new OffscreenCanvas(n,o)),eo(this,tf,ea(this,tc).getContext("2d")),ea(this,tf).font=`${s}px ${a}`,ea(this,tf).textAlign="center",ea(this,tf).textBaseline="top",ea(this,tf).letterSpacing=l??"0px",eo(this,tu,{width:n,height:o,duration:(null==(r=ea(this,td).at(-1))?void 0:r.end)??0}),this.ready=Promise.resolve(this.meta)}get meta(){return{...ea(this,tu)}}async tick(t){var e,r;if(null!=ea(this,tm)&&t>=ea(this,tm).timestamp&&t<=ea(this,tm).timestamp+(ea(this,tm).duration??0))return{video:ea(this,tm).clone(),state:"success"};let s=0;for(;s<ea(this,td).length&&!(t<=ea(this,td)[s].end);s+=1);let a=ea(this,td)[s]??ea(this,td).at(-1);if(t>a.end)return{state:"done"};if(t<a.start){ea(this,tf).clearRect(0,0,ea(this,tc).width,ea(this,tc).height);let r=new VideoFrame(ea(this,tc),{timestamp:t,duration:a.start-t});return null==(e=ea(this,tm))||e.close(),eo(this,tm,r),{video:r.clone(),state:"success"}}el(this,ty,tw).call(this,a.text);let n=new VideoFrame(ea(this,tc),{timestamp:t,duration:a.end-t});return null==(r=ea(this,tm))||r.close(),eo(this,tm,n),{video:n.clone(),state:"success"}}async split(e){await this.ready;let r=-1;for(let t=0;t<ea(this,td).length;t++)if(!(e>ea(this,td)[t].start)){r=t;break}if(-1===r)throw Error("Not found subtitle by time");let s=ea(this,td).slice(0,r).map(t=>({...t})),a=s.at(-1),n=null;null!=a&&a.end>e&&(n={start:0,end:a.end-e,text:a.text},a.end=e);let o=ea(this,td).slice(r).map(t=>({...t,start:t.start-e,end:t.end-e}));return null!=n&&o.unshift(n),[new t(s,ea(this,tp)),new t(o,ea(this,tp))]}async clone(){return new t(ea(this,td).slice(0),ea(this,tp))}destroy(){var t;null==(t=ea(this,tm))||t.close()}};td=new WeakMap,tu=new WeakMap,tp=new WeakMap,tc=new WeakMap,tf=new WeakMap,tm=new WeakMap,t_=new WeakMap,tg=new WeakMap,ty=new WeakSet,tw=function(t){let e=t.split(` `).reverse().map(t=>t.trim()),{width:r,height:s}=ea(this,tc),{color:a,fontSize:n,textBgColor:o,textShadow:l,strokeStyle:h,lineWidth:d,lineCap:u,lineJoin:p,bottomOffset:c}=ea(this,tp),f=ea(this,tf);f.clearRect(0,0,r,s),f.globalAlpha=.6;let m=c;for(let t of e){let e=f.measureText(t),c=r/2;null!=o&&(f.shadowOffsetX=0,f.shadowOffsetY=0,f.shadowBlur=0,f.fillStyle=o,f.globalAlpha=.5,f.fillRect(c-e.actualBoundingBoxLeft-ea(this,tg),s-m-ea(this,t_),e.width+2*ea(this,tg),ea(this,t_))),f.shadowColor=l.color,f.shadowOffsetX=l.offsetX,f.shadowOffsetY=l.offsetY,f.shadowBlur=l.blur,f.globalAlpha=1,null!=h&&(f.lineWidth=d??n/6,null!=u&&(f.lineCap=u),null!=p&&(f.lineJoin=p),f.strokeStyle=h,f.strokeText(t,c,s-m-ea(this,t_)+ea(this,tg))),f.fillStyle=a,f.fillText(t,c,s-m-ea(this,t_)+ea(this,tg)),m+=ea(this,t_)+.2*n}};let eH=eY;function eV(t){let e=t.match(/(\d{2}):(\d{2}):(\d{2}),(\d{3})/);if(null==e)throw Error(`time format error: ${t}`);let r=Number(e[1]),s=Number(e[2]);return 3600*r+60*s+Number(e[3])+Number(e[4])/1e3}class ej{constructor(){er(this,"readable"),er(this,"writable"),en(this,tb,0);let t=t4.default.createFile(),e=!1;this.readable=new ReadableStream({start:e=>{t.onReady=r=>{var s,a;let n=null==(s=r.videoTracks[0])?void 0:s.id;null!=n&&t.setExtractionOptions(n,"video",{nbSamples:100});let o=null==(a=r.audioTracks[0])?void 0:a.id;null!=o&&t.setExtractionOptions(o,"audio",{nbSamples:100}),e.enqueue({chunkType:"ready",data:{info:r,file:t}}),t.start()};let r={};t.onSamples=(s,a,n)=>{e.enqueue({chunkType:"samples",data:{id:s,type:a,samples:n.map(t=>({...t}))}}),r[s]=(r[s]??0)+n.length,t.releaseUsedSamples(s,r[s])},t.onFlush=()=>{e.close()}},cancel:()=>{t.stop(),e=!0}},{highWaterMark:50}),this.writable=new WritableStream({write:async r=>{if(e)return void this.writable.abort();let s=r.buffer;s.fileStart=ea(this,tb),eo(this,tb,ea(this,tb)+s.byteLength),t.appendBuffer(s)},close:()=>{var e;t.flush(),t.stop(),null==(e=t.onFlush)||e.call(t)}})}}async function eZ(t){let e=t4.default.createFile(),r=function(t){let e=0,r=t.boxes,s=[],a=0;async function n(){let n=f(r,e);e=r.length,s.forEach(({track:e,id:r})=>{let s=e.samples.at(-1);null!=s&&(a=Math.max(a,s.cts+s.duration)),t.releaseUsedSamples(r,e.samples.length),e.samples=[]}),t.mdats=[],t.moofs=[],null!=n&&await (null==u?void 0:u.write(n))}let o=[];function l(){if(o.length>0)return!0;let a=r.findIndex(t=>"moov"===t.type);if(-1===a)return!1;if(o=r.slice(0,a+1),e=a+1,0===s.length)for(let e=1;;e+=1){let r=t.getTrackById(e);if(null==r)break;s.push({track:r,id:e})}return!0}let h=0,d=(0,t9.tmpfile)(),u=null,p=(async()=>{u=await d.createWriter(),h=self.setInterval(()=>{l()&&n()},100)})(),c=!1;return async()=>{if(c)throw Error("File exported");if(c=!0,await p,clearInterval(h),!l()||null==u)return null;t.flush(),await n(),await (null==u?void 0:u.close());let e=o.find(t=>"moov"===t.type);if(null==e)return null;e.mvhd.duration=a;let r=(0,t9.tmpfile)(),s=f(o,0);return await (0,t9.write)(r,s),await (0,t9.write)(r,d,{overwrite:!1}),await r.stream()};function f(t,e){if(e>=t.length)return null;let r=new t4.default.DataStream;r.endianness=t4.default.DataStream.BIG_ENDIAN;for(let s=e;s<t.length;s++)null!==t[s]&&(t[s].write(r),delete t[s]);return new Uint8Array(r.buffer)}}(e);await eX(t,e);let s=await r();if(null==s)throw Error("Can not generate file from streams");return s}async function eX(t,e){let r=0,s=0,a=0,n=0,o=0,l=0,h=null,d=null;for(let u of t)await new Promise(async t=>{(0,t5.autoReadStream)(u.pipeThrough(new ej),{onDone:t,onChunk:async({chunkType:t,data:u})=>{if("ready"===t){let{videoTrackConf:t,audioTrackConf:s}=eb(u.file,u.info);0===r&&null!=t&&(r=e.addTrack(t)),0===n&&null!=s&&(n=e.addTrack(s))}else if("samples"===t){let{type:t,samples:p}=u,c="video"===t?r:n,f="video"===t?s:o,m="video"===t?a:l;p.forEach(t=>{e.addSample(c,t.data,{duration:t.duration,dts:t.dts+f,cts:t.cts+m,is_sync:t.is_sync})});let _=p.at(-1);if(null==_)return;"video"===t?h=_:"audio"===t&&(d=_)}}})}),null!=h&&(s+=h.dts,a+=h.cts),null!=d&&(o+=d.dts,l+=d.cts)}async function e$(t){return await eZ([t])}function eK(t,e){t5.Log.info("mixinMP4AndAudio, opts:",{volume:e.volume,loop:e.loop});let r=t4.default.createFile(),{stream:s,stop:a}=(0,t5.file2stream)(r,500),n=null,o=null,l=[],h=0,d=0,u=0,p=!0,c=ew.sampleRate;function f(t){let r=l.map(r=>e.loop?eg(r,u,u+t):r.slice(u,u+t));if(u+=t,1!==e.volume)for(let t of r)for(let r=0;r<t.length;r++)t[r]*=e.volume;return r}async function m(t){let e=t[0],r=t[t.length-1],s=ef([f(Math.floor((r.cts+r.duration-e.cts)/r.timescale*c))]);0!==s.length&&(null==o||o.encode(s,e.cts/e.timescale*1e6))}async function _(t){if(null==n)return;let e=function(t){let e=[];for(let r=0;r<t.length;r+=1)for(let s=0;s<t[r].length;s+=1)null==e[s]&&(e[s]=[]),e[s].push(t[r][s]);return e.map(ed)}((await n.decode(t)).map(eu)),r=f(e[0].length),s=t[0];null==o||o.encode(ef([e,r]),s.cts/s.timescale*1e6)}return(0,t5.autoReadStream)(t.pipeThrough(new ej),{onDone:async()=>{await (null==o?void 0:o.stop()),null==n||n.close(),a()},onChunk:async({chunkType:t,data:s})=>{if("ready"===t){let{videoTrackConf:t,audioTrackConf:a,audioDecoderConf:u}=eb(s.file,s.info);0===h&&null!=t&&(h=r.addTrack(t));let f=a??{timescale:1e6,samplerate:c,channel_count:ew.channelCount,hdlr:"soun",name:"SoundHandler",type:"mp4a"};0===d&&(d=r.addTrack(f),c=(null==a?void 0:a.samplerate)??c,p=null!=a);let m=new AudioContext({sampleRate:c});l=ep(await m.decodeAudioData(await new Response(e.stream).arrayBuffer())),null!=u&&(n=function(t){let e=[],r=new AudioDecoder({output:t=>{e.push(t)},error:t5.Log.error});return r.configure(t),{decode:async t=>{t.forEach(t=>{r.decode(new EncodedAudioChunk({type:t.is_sync?"key":"delta",timestamp:1e6*t.cts/t.timescale,duration:1e6*t.duration/t.timescale,data:t.data}))}),await r.flush();let s=e;return e=[],s},close:()=>{r.close()}}}(u)),o=function(t,e){let r={codec:t.codec,sampleRate:t.sampleRate,numberOfChannels:t.numberOfChannels},s=new AudioEncoder({output:t=>{e(function(t){let e=new ArrayBuffer(t.byteLength);t.copyTo(e);let r=t.timestamp;return{duration:t.duration??0,dts:r,cts:r,is_sync:"key"===t.type,data:e}}(t))},error:t=>{t5.Log.error("AudioEncoder error:",t,", config:",r)}});s.configure(r);let a=null;function n(e,r){return new AudioData({timestamp:r,numberOfChannels:t.numberOfChannels,numberOfFrames:e.length/t.numberOfChannels,sampleRate:t.sampleRate,format:"f32-planar",data:e})}return{encode:async(t,e)=>{null!=a&&s.encode(n(a.data,a.ts)),a={data:t,ts:e}},stop:async()=>{null!=a&&(function(t,e,r){let s=t.length-1,a=Math.min(r/2,s);for(let r=0;r<a;r++)for(let n=1;n<=e;n++)t[Math.floor(s/n)-r]*=r/a}(a.data,t.numberOfChannels,t.sampleRate),s.encode(n(a.data,a.ts)),a=null),await s.flush(),s.close()}}}(u??{codec:"mp4a"===f.type?ew.codec:f.type,numberOfChannels:f.channel_count,sampleRate:f.samplerate},t=>r.addSample(d,t.data,t))}else if("samples"===t){let{id:t,type:e,samples:a}=s;if("video"===e){a.forEach(e=>r.addSample(t,e.data,e)),p||await m(a);return}"audio"===e&&await _(a)}}}),s}tb=new WeakMap;let eJ=`#version 300 es layout (location = 0) in vec4 a_position; layout (location = 1) in vec2 a_texCoord; out vec2 v_texCoord; void main () { gl_Position = a_position; v_texCoord = a_texCoord; } `,eQ=`#version 300 es precision mediump float; out vec4 FragColor; in vec2 v_texCoord; uniform sampler2D frameTexture; uniform vec3 keyColor; // \u{8272}\u{5EA6}\u{7684}\u{76F8}\u{4F3C}\u{5EA6}\u{8BA1}\u{7B97} uniform float similarity; // \u{900F}\u{660E}\u{5EA6}\u{7684}\u{5E73}\u{6ED1}\u{5EA6}\u{8BA1}\u{7B97} uniform float smoothness; // \u{964D}\u{4F4E}\u{7EFF}\u{5E55}\u{9971}\u{548C}\u{5EA6}\u{FF0C}\u{63D0}\u{9AD8}\u{62A0}\u{56FE}\u{51C6}\u{786E}\u{5EA6} uniform float spill; vec2 RGBtoUV(vec3 rgb) { return vec2( rgb.r * -0.169 + rgb.g * -0.331 + rgb.b * 0.5 + 0.5, rgb.r * 0.5 + rgb.g * -0.419 + rgb.b * -0.081 + 0.5 ); } void main() { // \u{83B7}\u{53D6}\u{5F53}\u{524D}\u{50CF}\u{7D20}\u{7684}rgba\u{503C} vec4 rgba = texture(frameTexture, v_texCoord); // \u{8BA1}\u{7B97}\u{5F53}\u{524D}\u{50CF}\u{7D20}\u{4E0E}\u{7EFF}\u{5E55}\u{50CF}\u{7D20}\u{7684}\u{8272}\u{5EA6}\u{5DEE}\u{503C} vec2 chromaVec = RGBtoUV(rgba.rgb) - RGBtoUV(keyColor); // \u{8BA1}\u{7B97}\u{5F53}\u{524D}\u{50CF}\u{7D20}\u{4E0E}\u{7EFF}\u{5E55}\u{50CF}\u{7D20}\u{7684}\u{8272}\u{5EA6}\u{8DDD}\u{79BB}\u{FF08}\u{5411}\u{91CF}\u{957F}\u{5EA6}\u{FF09}, \u{8D8A}\u{76F8}\u{50CF}\u{5219}\u{8272}\u{5EA6}\u{8DDD}\u{79BB}\u{8D8A}\u{5C0F} float chromaDist = sqrt(dot(chromaVec, chromaVec)); // \u{8BBE}\u{7F6E}\u{4E86}\u{4E00}\u{4E2A}\u{76F8}\u{4F3C}\u{5EA6}\u{9608}\u{503C}\u{FF0C}baseMask\u{4E3A}\u{8D1F}\u{FF0C}\u{5219}\u{8868}\u{660E}\u{662F}\u{7EFF}\u{5E55}\u{FF0C}\u{4E3A}\u{6B63}\u{5219}\u{8868}\u{660E}\u{4E0D}\u{662F}\u{7EFF}\u{5E55} float baseMask = chromaDist - similarity; // \u{5982}\u{679C}baseMask\u{4E3A}\u{8D1F}\u{6570}\u{FF0C}fullMask\u{7B49}\u{4E8E}0\u{FF1B}baseMask\u{4E3A}\u{6B63}\u{6570}\u{FF0C}\u{8D8A}\u{5927}\u{FF0C}\u{5219}\u{900F}\u{660E}\u{5EA6}\u{8D8A}\u{4F4E} float fullMask = pow(clamp(baseMask / smoothness, 0., 1.), 1.5); rgba.a = fullMask; // \u{8BBE}\u{7F6E}\u{900F}\u{660E}\u{5EA6} // \u{5982}\u{679C}baseMask\u{4E3A}\u{8D1F}\u{6570}\u{FF0C}spillVal\u{7B49}\u{4E8E}0\u{FF1B}baseMask\u{4E3A}\u{6574}\u{6570}\u{FF0C}\u{8D8A}\u{5C0F}\u{FF0C}\u{9971}\u{548C}\u{5EA6}\u{8D8A}\u{4F4E} float spillVal = pow(clamp(baseMask / spill, 0., 1.), 1.5); float desat = clamp(rgba.r * 0.2126 + rgba.g * 0.7152 + rgba.b * 0.0722, 0., 1.); // \u{8BA1}\u{7B97}\u{5F53}\u{524D}\u{50CF}\u{7D20}\u{7684}\u{7070}\u{5EA6}\u{503C} rgba.rgb = mix(vec3(desat, desat, desat), rgba.rgb, spillVal); FragColor = rgba; } `,eq=[-1,1,-1,-1,1,-1,1,-1,1,1,-1,1],e0=[0,1,0,0,1,0,1,0,1,1,0,1];function e1(t,e,r){let s=t.createShader(e);if(t.shaderSource(s,r),t.compileShader(s),!t.getShaderParameter(s,t.COMPILE_STATUS)){let e=t.getShaderInfoLog(s);throw t.deleteShader(s),Error(e??"An error occurred compiling the shaders")}return s}let e2=t=>{let e=null,r=null,s=t.keyColor,a=null;return async n=>{var o,l;if((null==e||null==r||null==a)&&(null==s&&(s=function(t){let e=new OffscreenCanvas(1,1).getContext("2d");e.drawImage(t,0,0);let{data:[r,s,a]}=e.getImageData(0,0,1,1);return[r,s,a]}(n)),{cvs:e,gl:r}=function(t){let e="document"in globalThis?globalThis.document.createElement("canvas"):new OffscreenCanvas(t.width,t.height);e.width=t.width,e.height=t.height;let r=e.getContext("webgl2",{premultipliedAlpha:!1,alpha:!0});if(null==r)throw Error("Cant create gl context");let s=function(t,e,r){let s=e1(t,t.VERTEX_SHADER,e),a=e1(t,t.FRAGMENT_SHADER,r),n=t.createProgram();if(t.attachShader(n,s),t.attachShader(n,a),t.linkProgram(n),!t.getProgramParameter(n,t.LINK_STATUS))throw Error(t.getProgramInfoLog(n)??"Unable to initialize the shader program");return n}(r,eJ,eQ);r.useProgram(s),r.uniform3fv(r.getUniformLocation(s,"keyColor"),t.keyColor.map(t=>t/255)),r.uniform1f(r.getUniformLocation(s,"similarity"),t.similarity),r.uniform1f(r.getUniformLocation(s,"smoothness"),t.smoothness),r.uniform1f(r.getUniformLocation(s,"spill"),t.spill);let a=r.createBuffer();r.bindBuffer(r.ARRAY_BUFFER,a),r.bufferData(r.ARRAY_BUFFER,new Float32Array(eq),r.STATIC_DRAW);let n=r.getAttribLocation(s,"a_position");r.vertexAttribPointer(n,2,r.FLOAT,!1,2*Float32Array.BYTES_PER_ELEMENT,0),r.enableVertexAttribArray(n);let o=r.createBuffer();r.bindBuffer(r.ARRAY_BUFFER,o),r.bufferData(r.ARRAY_BUFFER,new Float32Array(e0),r.STATIC_DRAW);let l=r.getAttribLocation(s,"a_texCoord");return r.vertexAttribPointer(l,2,r.FLOAT,!1,2*Float32Array.BYTES_PER_ELEMENT,0),r.enableVertexAttribArray(l),r.pixelStorei(r.UNPACK_FLIP_Y_WEBGL,1),{cvs:e,gl:r}}({...n instanceof VideoFrame?{width:n.codedWidth,height:n.codedHeight}:{width:n.width,height:n.height},keyColor:s,...t}),a=function(t){let e=t.createTexture();if(null==e)throw Error("Create WebGL texture error");t.bindTexture(t.TEXTURE_2D,e);let r=t.RGBA,s=t.RGBA,a=t.UNSIGNED_BYTE,n=new Uint8Array([0,0,255,255]);return t.texImage2D(t.TEXTURE_2D,0,r,1,1,0,s,a,n),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),e}(r)),o=r,l=a,o.bindTexture(o.TEXTURE_2D,l),o.texImage2D(o.TEXTURE_2D,0,o.RGBA,o.RGBA,o.UNSIGNED_BYTE,n),o.drawArrays(o.TRIANGLES,0,6),null!=globalThis.VideoFrame&&n instanceof globalThis.VideoFrame){let t=new VideoFrame(e,{alpha:"keep",timestamp:n.timestamp,duration:n.duration??void 0});return n.close(),t}return createImageBitmap(e,{imageOrientation:n instanceof ImageBitmap?"flipY":"none"})}},e3=class t{constructor(t,e,r,s,a){en(this,tC),en(this,tv,new(0,t5.EventTool)),er(this,"on",ea(this,tv).on),en(this,tS,0),en(this,tx,0),en(this,tU,0),en(this,tE,0),en(this,tA,0),en(this,tk,null),er(this,"fixedAspectRatio",!1),er(this,"fixedScaleCenter",!1),this.x=t??0,this.y=e??0,this.w=r??0,this.h=s??0,eo(this,tk,a??null)}get x(){return ea(this,tS)}set x(t){el(this,tC,tT).call(this,"x",t)}get y(){return ea(this,tx)}set y(t){el(this,tC,tT).call(this,"y",t)}get w(){return ea(this,tU)}set w(t){el(this,tC,tT).call(this,"w",t)}get h(){return ea(this,tE)}set h(t){el(this,tC,tT).call(this,"h",t)}get angle(){return ea(this,tA)}set angle(t){el(this,tC,tT).call(this,"angle",t)}get center(){let{x:t,y:e,w:r,h:s}=this;return{x:t+r/2,y:e+s/2}}clone(){let{x:e,y:r,w:s,h:a}=this,n=new t(e,r,s,a,ea(this,tk));return n.angle=this.angle,n.fixedAspectRatio=this.fixedAspectRatio,n.fixedScaleCenter=this.fixedScaleCenter,n}checkHit(t,e){var r,s;let{angle:a,center:n,x:o,y:l,w:h,h:d}=this,u=(null==(r=ea(this,tk))?void 0:r.center)??n,p=(null==(s=ea(this,tk))?void 0:s.angle)??a;null==ea(this,tk)&&(o-=u.x,l-=u.y);let c=t-u.x,f=e-u.y,m=c,_=f;return 0!==p&&(m=c*Math.cos(p)+f*Math.sin(p),_=f*Math.cos(p)-c*Math.sin(p)),!(m<o||m>o+h||_<l||_>l+d)}};tv=new WeakMap,tS=new WeakMap,tx=new WeakMap,tU=new WeakMap,tE=new WeakMap,tA=new WeakMap,tC=new WeakSet,tT=function(t,e){let r=this[t]!==e;switch(t){case"x":eo(this,tS,e);break;case"y":eo(this,tx,e);break;case"w":eo(this,tU,e);break;case"h":eo(this,tE,e);break;case"angle":eo(this,tA,e)}r&&ea(this,tv).emit("propsChange",{[t]:e})},tk=new WeakMap;let e6=e3;class e8{constructor(){er(this,"rect",new e6),en(this,tB,{offset:0,duration:0,playbackRate:1}),en(this,tF,new(0,t5.EventTool)),er(this,"on",ea(this,tF).on),en(this,tI,0),er(this,"opacity",1),er(this,"flip",null),en(this,tz,null),en(this,tP,null),er(this,"ready",Promise.resolve()),this.rect.on("propsChange",t=>{ea(this,tF).emit("propsChange",{rect:t})})}get time(){return ea(this,tB)}set time(t){Object.assign(ea(this,tB),t)}get zIndex(){return ea(this,tI)}set zIndex(t){let e=ea(this,tI)!==t;eo(this,tI,t),e&&ea(this,tF).emit("propsChange",{zIndex:t})}_render(t){let{rect:{center:e,angle:r}}=this;t.setTransform("horizontal"===this.flip?-1:1,0,0,"vertical"===this.flip?-1:1,e.x,e.y),t.rotate((null==this.flip?1:-1)*r),t.globalAlpha=this.opacity}setAnimation(t,e){eo(this,tz,Object.entries(t).map(([t,e])=>{let r={from:0,to:100}[t]??Number(t.slice(0,-1));if(isNaN(r)||r>100||r<0)throw Error("keyFrame must between 0~100");return[r/100,e]})),eo(this,tP,Object.assign({},ea(this,tP),{duration:e.duration,delay:e.delay??0,iterCount:e.iterCount??1/0}))}animate(t){if(null==ea(this,tz)||null==ea(this,tP)||t<ea(this,tP).delay)return;let e=function(t,e,r){let s=t-r.delay;if(s/r.duration>=r.iterCount)return{};let a=s%r.duration,n=s===r.duration?1:a/r.duration,o=e.findIndex(t=>t[0]>=n);if(-1===o)return{};let l=e[o-1],h=e[o],d=h[1];if(null==l)return d;let u=l[1],p={},c=(n-l[0])/(h[0]-l[0]);for(let t in d)null!=u[t]&&(p[t]=(d[t]-u[t])*c+u[t]);return p}(t,ea(this,tz),ea(this,tP));for(let t in e)switch(t){case"opacity":this.opacity=e[t];break;case"x":case"y":case"w":case"h":case"angle":this.rect[t]=e[t]}}copyStateTo(t){eo(t,tz,ea(this,tz)),eo(t,tP,ea(this,tP)),t.zIndex=this.zIndex,t.opacity=this.opacity,t.flip=this.flip,t.rect=this.rect.clone(),t.time={...this.time}}destroy(){ea(this,tF).destroy()}}tB=new WeakMap,tF=new WeakMap,tI=new WeakMap,tz=new WeakMap,tP=new WeakMap;let e4=class t extends e8{constructor(t){super(),en(this,tL),en(this,tR,null),en(this,tM,!1),eo(this,tL,t),this.ready=t.ready.then(({width:t,height:e,duration:r})=>{this.rect.w=0===this.rect.w?t:this.rect.w,this.rect.h=0===this.rect.h?e:this.rect.h,this.time.duration=0===this.time.duration?r:this.time.duration})}async offscreenRender(t,e){var r;let s=e*this.time.playbackRate;this.animate(s),super._render(t);let{w:a,h:n}=this.rect,{video:o,audio:l,state:h}=await ea(this,tL).tick(s),d=l??[];if(null!=l&&1!==this.time.playbackRate&&(d=l.map(t=>ey(t,this.time.playbackRate))),"done"===h)return{audio:d,done:!0};let u=o??ea(this,tR);return null!=u&&t.drawImage(u,-a/2,-n/2,a,n),null!=o&&(null==(r=ea(this,tR))||r.close(),eo(this,tR,o)),{audio:d,done:!1}}async clone(){let e=new t(await ea(this,tL).clone());return await e.ready,this.copyStateTo(e),e}destroy(){var t;ea(this,tM)||(eo(this,tM,!0),t5.Log.info("OffscreenSprite destroy"),super.destroy(),null==(t=ea(this,tR))||t.close(),eo(this,tR,null),ea(this,tL).destroy())}};tL=new WeakMap,tR=new WeakMap,tM=new WeakMap;let e5=e4,e7=class t extends e8{constructor(t){super(),en(this,tW),en(this,tD),er(this,"visible",!0),en(this,tO,null),en(this,tN,[]),en(this,tG,!1),en(this,tH,-1),en(this,tV,!1),eo(this,tD,t),this.ready=t.ready.then(({width:t,height:e,duration:r})=>{this.rect.w=0===this.rect.w?t:this.rect.w,this.rect.h=0===this.rect.h?e:this.rect.h,this.time.duration=0===this.time.duration?r:this.time.duration})}getClip(){return ea(this,tD)}preFrame(t){el(this,tW,tY).call(this,t)}render(t,e){this.animate(e),super._render(t);let{w:r,h:s}=this.rect;ea(this,tH)!==e&&el(this,tW,tY).call(this,e),eo(this,tH,e);let a=ea(this,tN);eo(this,tN,[]);let n=ea(this,tO);return null!=n&&t.drawImage(n,-r/2,-s/2,r,s),{audio:a}}copyStateTo(e){super.copyStateTo(e),e instanceof t&&(e.visible=this.visible)}destroy(){var t;ea(this,tV)||(eo(this,tV,!0),t5.Log.info("VisibleSprite destroy"),super.destroy(),null==(t=ea(this,tO))||t.close(),eo(this,tO,null),ea(this,tD).destroy())}};tD=new WeakMap,tO=new WeakMap,tN=new WeakMap,tG=new WeakMap,tW=new WeakSet,tY=function(t){ea(this,tG)||(eo(this,tG,!0),ea(this,tD).tick(t*this.time.playbackRate).then(({video:t,audio:e})=>{var r;null!=t&&(null==(r=ea(this,tO))||r.close(),eo(this,tO,t??null)),eo(this,tN,e??[]),null!=e&&1!==this.time.playbackRate&&eo(this,tN,e.map(t=>ey(t,this.time.playbackRate)))}).finally(()=>{eo(this,tG,!1)}))},tH=new WeakMap,tV=new WeakMap;let e9=e7,it=0;async function ie(t){t()>50&&(await e_(15),await ie(t))}class ii{constructor(t={}){en(this,t1),en(this,tj,t5.Log.create(`id:${it++},`)),en(this,tZ,!1),en(this,tX,[]),en(this,t$),en(this,tK),en(this,tJ,null),en(this,tQ),en(this,tq),en(this,t0,new(0,t5.EventTool)),er(this,"on",ea(this,t0).on);let{width:e=0,height:r=0}=t;eo(this,t$,new OffscreenCanvas(e,r));let s=ea(this,t$).getContext("2d",{alpha:!1});if(null==s)throw Error("Can not create 2d offscreen context");eo(this,tK,s),eo(this,tQ,Object.assign({bgColor:"#000",width:0,height:0,videoCodec:"avc1.42E032",audio:!0,bitrate:5e6,fps:30,metaDataTags:null},t)),eo(this,tq,e*r>0)}static async isSupported(t={}){return(null!=self.OffscreenCanvas&&null!=self.VideoEncoder&&null!=self.VideoDecoder&&null!=self.VideoFrame&&null!=self.AudioEncoder&&null!=self.AudioDecoder&&null!=self.AudioData&&((await self.VideoEncoder.isConfigSupported({codec:t.videoCodec??"avc1.42E032",width:t.width??1920,height:t.height??1080,bitrate:t.bitrate??7e6})).supported??!1)&&(await self.AudioEncoder.isConfigSupported({codec:ew.codec,sampleRate:ew.sampleRate,numberOfChannels:ew.channelCount})).supported)??!1}async addSprite(t,e={}){var r,s;let a={rect:(r=["x","y","w","h"],s=t.rect,r.reduce((t,e)=>(t[e]=s[e],t),{})),time:{...t.time},zIndex:t.zIndex};ea(this,tj).info("Combinator add sprite",a);let n=await t.clone();ea(this,tj).info("Combinator add sprite ready"),ea(this,tX).push(Object.assign(n,{main:e.main??!1,expired:!1})),ea(this,tX).sort((t,e)=>t.zIndex-e.zIndex)}output(){if(0===ea(this,tX).length)throw Error("No sprite added");let t=ea(this,tX).find(t=>t.main),e=null!=t?t.time.offset+t.time.duration:Math.max(...ea(this,tX).map(t=>t.time.offset+t.time.duration));if(e===1/0)throw Error("Unable to determine the end time, please specify a main sprite, or limit the duration of ImgClip, AudioCli");-1===e&&ea(this,tj).warn("Unable to determine the end time, process value don't update"),ea(this,tj).info(`start combinate video, maxTime:${e}`);let r=el(this,t1,t2).call(this,e),s=performance.now(),a=el(this,t1,t3).call(this,r,e,{onProgress:t=>{ea(this,tj).debug("OutputProgress:",t),ea(this,t0).emit("OutputProgress",t)},onEnded:async()=>{await r.flush(),ea(this,tj).info("===== output ended =====, cost:",performance.now()-s),ea(this,t0).emit("OutputProgress",1),this.destroy()},onError:t=>{ea(this,t0).emit("error",t),o(t),this.destroy()}});eo(this,tJ,()=>{a(),r.close(),o()});let{stream:n,stop:o}=(0,t5.file2stream)(r.mp4file,500,this.destroy);return n}destroy(){var t;ea(this,tZ)||(eo(this,tZ,!0),null==(t=ea(this,tJ))||t.call(this),ea(this,t0).destroy())}}tj=new WeakMap,tZ=new WeakMap,tX=new WeakMap,t$=new WeakMap,tK=new WeakMap,tJ=new WeakMap,tQ=new WeakMap,tq=new WeakMap,t0=new WeakMap,t1=new WeakSet,t2=function(t){let{fps:e,width:r,height:s,videoCodec:a,bitrate:n,audio:o,metaDataTags:l}=ea(this,tQ);return(0,t5.recodemux)({video:ea(this,tq)?{width:r,height:s,expectFPS:e,codec:a,bitrate:n,__unsafe_hardwareAcceleration__:ea(this,tQ).__unsafe_hardwareAcceleration__}:null,audio:!1===o?null:{codec:"aac",sampleRate:ew.sampleRate,channelCount:ew.channelCount},duration:t,metaDataTags:l})},t3=function(t,e,{onProgress:r,onEnded:s,onError:a}){let n=0,o={aborted:!1},l=null;(async()=>{let{fps:r,bgColor:a,audio:h}=ea(this,tQ),u=Math.round(1e6/r),p=ea(this,tK),c=function(t){let{ctx:e,bgColor:r,sprites:s,aborter:a}=t,{width:n,height:o}=e.canvas;return async t=>{e.fillStyle=r,e.fillRect(0,0,n,o);let l=[],h=!1;for(let r of s){if(a.aborted)break;if(t<r.time.offset||r.expired)continue;e.save();let{audio:s,done:n}=await r.offscreenRender(e,t-r.time.offset);l.push(s),e.restore(),(r.time.duration>0&&t>r.time.offset+r.time.duration||n)&&(r.main&&(h=!0),r.destroy(),r.expired=!0)}return{audios:l,mainSprDone:h}}}({ctx:p,bgColor:a,sprites:ea(this,tX),aborter:o}),f=function(t){let{ctx:e,cvs:r,outputAudio:s,remux:a,hasVideoTrack:n,timeSlice:o}=t,{width:l,height:h}=r,d=0,u=Math.floor(3*t.fps),p=function(t){let e=1024*ew.channelCount,r=new Float32Array(3*e),s=0,a=0,n=t/ew.sampleRate*1e6,o=new Float32Array(e),l=l=>{let h=0,d=Math.floor(s/e),u=[];for(let s=0;s<d;s++)u.push(new AudioData({timestamp:a,numberOfChannels:ew.channelCount,numberOfFrames:t,sampleRate:ew.sampleRate,format:"f32",data:r.subarray(h,h+e)})),h+=e,a+=n;for(r.set(r.subarray(h,s),0),s-=h;l-a>n;)u.push(new AudioData({timestamp:a,numberOfChannels:ew.channelCount,numberOfFrames:t,sampleRate:ew.sampleRate,format:"f32",data:o})),a+=n;return u};return(t,e)=>{var a,n;let o=Math.max(...e.map(t=>{var e;return(null==(e=t[0])?void 0:e.length)??0}));for(let t=0;t<o;t++){let o=0,l=0;for(let r=0;r<e.length;r++){let s=(null==(a=e[r][0])?void 0:a[t])??0,h=(null==(n=e[r][1])?void 0:n[t])??s;o+=s,l+=h}r[s]=o,r[s+1]=l,s+=2}return l(t)}}(1024);return(t,c)=>{if(!1!==s)for(let e of p(t,c))a.encodeAudio(e);if(n){let s=new VideoFrame(r,{duration:o,timestamp:t});a.encodeVideo(s,{keyFrame:d%u==0}),e.resetTransform(),e.clearRect(0,0,l,h),d+=1}}}({remux:t,ctx:p,cvs:ea(this,t$),outputAudio:h,hasVideoTrack:ea(this,tq),timeSlice:u,fps:r}),m=0;for(;;){if(null!=l)return;if(o.aborted||-1!==e&&m>e||0===ea(this,tX).length){d(),await s();return}n=m/e;let{audios:r,mainSprDone:a}=await c(m);if(a){d(),await s();return}if(o.aborted)return;f(m,r),m+=u,await ie(t.getEncodeQueueSize)}})().catch(t=>{l=t,ea(this,tj).error(t),d(),a(t)});let h=setInterval(()=>{r(n)},500),d=()=>{o.aborted||(o.aborted=!0,clearInterval(h),ea(this,tX).forEach(t=>t.destroy()))};return d}},{"@webav/mp4box.js":"1bsIP","@webav/internal-utils":"1pMSt","wave-resampler":"2LcA0","opfs-tools":"7yncN","@parcel/transformer-js/src/esmodule-helpers.js":"6ykb1"}],"1bsIP":[function(t,e,r,s){var a,n,o=(a=new Date,n=4,{setLogLevel:function(t){t==this.debug?n=1:t==this.info?n=2:t==this.warn?n=3:(this.error,n=4)},debug:function(t,e){void 0===console.debug&&(console.debug=console.log),1>=n&&console.debug("["+o.getDurationString(new Date-a,1e3)+"]","["+t+"]",e)},log:function(t,e){this.debug(t.msg)},info:function(t,e){2>=n&&console.info("["+o.getDurationString(new Date-a,1e3)+"]","["+t+"]",e)},warn:function(t,e){3>=n&&console.warn("["+o.getDurationString(new Date-a,1e3)+"]","["+t+"]",e)},error:function(t,e){4>=n&&console.error("["+o.getDurationString(new Date-a,1e3)+"]","["+t+"]",e)}});o.getDurationString=function(t,e){function r(t,e){for(var r=(""+t).split(".");r[0].length<e;)r[0]="0"+r[0];return r.join(".")}t<0?(s=!0,t=-t):s=!1;var s,a=t/(e||1),n=Math.floor(a/3600),o=Math.floor((a-=3600*n)/60),l=1e3*(a-=60*o);return l-=1e3*(a=Math.floor(a)),l=Math.floor(l),(s?"-":"")+n+":"+r(o,2)+":"+r(a,2)+"."+r(l,3)},o.printRanges=function(t){var e=t.length;if(!(e>0))return"(empty)";for(var r="",s=0;s<e;s++)s>0&&(r+=","),r+="["+o.getDurationString(t.start(s))+","+o.getDurationString(t.end(s))+"]";return r},r.Log=o;var l=function(t){if(t instanceof ArrayBuffer)this.buffer=t,this.dataview=new DataView(t);else throw"Needs an array buffer";this.position=0};l.prototype.getPosition=function(){return this.position},l.prototype.getEndPosition=function(){return this.buffer.byteLength},l.prototype.getLength=function(){return this.buffer.byteLength},l.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},l.prototype.isEos=function(){return this.getPosition()>=this.getEndPosition()},l.prototype.readAnyInt=function(t,e){var r=0;if(this.position+t<=this.buffer.byteLength){switch(t){case 1:r=e?this.dataview.getInt8(this.position):this.dataview.getUint8(this.position);break;case 2:r=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";r=this.dataview.getUint8(this.position)<<16|this.dataview.getUint8(this.position+1)<<8|this.dataview.getUint8(this.position+2);break;case 4:r=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";r=this.dataview.getUint32(this.position)<<32|this.dataview.getUint32(this.position+4);break;default:throw"readInt method not implemented for size: "+t}return this.position+=t,r}throw"Not enough bytes in buffer"},l.prototype.readUint8=function(){return this.readAnyInt(1,!1)},l.prototype.readUint16=function(){return this.readAnyInt(2,!1)},l.prototype.readUint24=function(){return this.readAnyInt(3,!1)},l.prototype.readUint32=function(){return this.readAnyInt(4,!1)},l.prototype.readUint64=function(){return this.readAnyInt(8,!1)},l.prototype.readString=function(t){if(this.position+t<=this.buffer.byteLength){for(var e="",r=0;r<t;r++)e+=String.fromCharCode(this.readUint8());return e}throw"Not enough bytes in buffer"},l.prototype.readCString=function(){for(var t=[];;){var e=this.readUint8();if(0!==e)t.push(e);else break}return String.fromCharCode.apply(null,t)},l.prototype.readInt8=function(){return this.readAnyInt(1,!0)},l.prototype.readInt16=function(){return this.readAnyInt(2,!0)},l.prototype.readInt32=function(){return this.readAnyInt(4,!0)},l.prototype.readInt64=function(){return this.readAnyInt(8,!1)},l.prototype.readUint8Array=function(t){for(var e=new Uint8Array(t),r=0;r<t;r++)e[r]=this.readUint8();return e},l.prototype.readInt16Array=function(t){for(var e=new Int16Array(t),r=0;r<t;r++)e[r]=this.readInt16();return e},l.prototype.readUint16Array=function(t){for(var e=new Int16Array(t),r=0;r<t;r++)e[r]=this.readUint16();return e},l.prototype.readUint32Array=function(t){for(var e=new Uint32Array(t),r=0;r<t;r++)e[r]=this.readUint32();return e},l.prototype.readInt32Array=function(t){for(var e=new Int32Array(t),r=0;r<t;r++)e[r]=this.readInt32();return e},r.MP4BoxStream=l;var h=function(t,e,r){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==r?h.LITTLE_ENDIAN:r};h.prototype={},h.prototype.getPosition=function(){return this.position},h.prototype._realloc=function(t){if(this._dynamicSize){var e=this._byteOffset+this.position+t,r=this._buffer.byteLength;if(e<=r){e>this._byteLength&&(this._byteLength=e);return}for(r<1&&(r=1);e>r;)r*=2;var s=new ArrayBuffer(r),a=new Uint8Array(this._buffer);new Uint8Array(s,0,a.length).set(a),this.buffer=s,this._byteLength=e}},h.prototype._trimAlloc=function(){if(this._byteLength!=this._buffer.byteLength){var t=new ArrayBuffer(this._byteLength),e=new Uint8Array(t),r=new Uint8Array(this._buffer,0,e.length);e.set(r),this.buffer=t}},h.BIG_ENDIAN=!1,h.LITTLE_ENDIAN=!0,h.prototype._byteLength=0,Object.defineProperty(h.prototype,"byteLength",{get:function(){return this._byteLength-this._byteOffset}}),Object.defineProperty(h.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(h.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(h.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}}),h.prototype.seek=function(t){var e=Math.max(0,Math.min(this.byteLength,t));this.position=isNaN(e)||!isFinite(e)?0:e},h.prototype.isEof=function(){return this.position>=this._byteLength},h.prototype.mapUint8Array=function(t){this._realloc(+t);var e=new Uint8Array(this._buffer,this.byteOffset+this.position,t);return this.position+=+t,e},h.prototype.readInt32Array=function(t,e){var r=new Int32Array(t=null==t?this.byteLength-this.position/4:t);return h.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,t*r.BYTES_PER_ELEMENT),h.arrayToNative(r,null==e?this.endianness:e),this.position+=r.byteLength,r},h.prototype.readInt16Array=function(t,e){var r=new Int16Array(t=null==t?this.byteLength-this.position/2:t);return h.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,t*r.BYTES_PER_ELEMENT),h.arrayToNative(r,null==e?this.endianness:e),this.position+=r.byteLength,r},h.prototype.readInt8Array=function(t){var e=new Int8Array(t=null==t?this.byteLength-this.position:t);return h.memcpy(e.buffer,0,this.buffer,this.byteOffset+this.position,t*e.BYTES_PER_ELEMENT),this.position+=e.byteLength,e},h.prototype.readUint32Array=function(t,e){var r=new Uint32Array(t=null==t?this.byteLength-this.position/4:t);return h.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,t*r.BYTES_PER_ELEMENT),h.arrayToNative(r,null==e?this.endianness:e),this.position+=r.byteLength,r},h.prototype.readUint16Array=function(t,e){var r=new Uint16Array(t=null==t?this.byteLength-this.position/2:t);return h.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,t*r.BYTES_PER_ELEMENT),h.arrayToNative(r,null==e?this.endianness:e),this.position+=r.byteLength,r},h.prototype.readUint8Array=function(t){var e=new Uint8Array(t=null==t?this.byteLength-this.position:t);return h.memcpy(e.buffer,0,this.buffer,this.byteOffset+this.position,t*e.BYTES_PER_ELEMENT),this.position+=e.byteLength,e},h.prototype.readFloat64Array=function(t,e){var r=new Float64Array(t=null==t?this.byteLength-this.position/8:t);return h.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,t*r.BYTES_PER_ELEMENT),h.arrayToNative(r,null==e?this.endianness:e),this.position+=r.byteLength,r},h.prototype.readFloat32Array=function(t,e){var r=new Float32Array(t=null==t?this.byteLength-this.position/4:t);return h.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,t*r.BYTES_PER_ELEMENT),h.arrayToNative(r,null==e?this.endianness:e),this.position+=r.byteLength,r},h.prototype.readInt32=function(t){var e=this._dataView.getInt32(this.position,null==t?this.endianness:t);return this.position+=4,e},h.prototype.readInt16=function(t){var e=this._dataView.getInt16(this.position,null==t?this.endianness:t);return this.position+=2,e},h.prototype.readInt8=function(){var t=this._dataView.getInt8(this.position);return this.position+=1,t},h.prototype.readUint32=function(t){var e=this._dataView.getUint32(this.position,null==t?this.endianness:t);return this.position+=4,e},h.prototype.readUint16=function(t){var e=this._dataView.getUint16(this.position,null==t?this.endianness:t);return this.position+=2,e},h.prototype.readUint8=function(){var t=this._dataView.getUint8(this.position);return this.position+=1,t},h.prototype.readFloat32=function(t){var e=this._dataView.getFloat32(this.position,null==t?this.endianness:t);return this.position+=4,e},h.prototype.readFloat64=function(t){var e=this._dataView.getFloat64(this.position,null==t?this.endianness:t);return this.position+=8,e},h.endianness=new Int8Array(new Int16Array([1]).buffer)[0]>0,h.memcpy=function(t,e,r,s,a){var n=new Uint8Array(t,e,a),o=new Uint8Array(r,s,a);n.set(o)},h.arrayToNative=function(t,e){return e==this.endianness?t:this.flipArrayEndianness(t)},h.nativeToEndian=function(t,e){return this.endianness==e?t:this.flipArrayEndianness(t)},h.flipArrayEndianness=function(t){for(var e=new Uint8Array(t.buffer,t.byteOffset,t.byteLength),r=0;r<t.byteLength;r+=t.BYTES_PER_ELEMENT)for(var s=r+t.BYTES_PER_ELEMENT-1,a=r;s>a;s--,a++){var n=e[a];e[a]=e[s],e[s]=n}return t},h.prototype.failurePosition=0,String.fromCharCodeUint8=function(t){for(var e=[],r=0;r<t.length;r++)e[r]=t[r];return String.fromCharCode.apply(null,e)},h.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))},h.prototype.readCString=function(t){var e=this.byteLength-this.position,r=new Uint8Array(this._buffer,this._byteOffset+this.position),s=e;null!=t&&(s=Math.min(t,e));for(var a=0;a<s&&0!==r[a];a++);var n=String.fromCharCodeUint8.apply(null,[this.mapUint8Array(a)]);return null!=t?this.position+=s-a:a!=e&&(this.position+=1),n},h.prototype.readInt64=function(){return 0x100000000*this.readInt32()+this.readUint32()},h.prototype.readUint64=function(){return 0x100000000*this.readUint32()+this.readUint32()},h.prototype.readInt64=function(){return 0x100000000*this.readUint32()+this.readUint32()},h.prototype.readUint24=function(){return(this.readUint8()<<16)+(this.readUint8()<<8)+this.readUint8()},r.DataStream=h,h.prototype.save=function(t){var e=new Blob([this.buffer]);if(window.URL&&URL.createObjectURL){var r=window.URL.createObjectURL(e),s=document.createElement("a");document.body.appendChild(s),s.setAttribute("href",r),s.setAttribute("download",t),s.setAttribute("target","_self"),s.click(),window.URL.revokeObjectURL(r)}else throw"DataStream.save: Can't create object URL."},h.prototype._dynamicSize=!0,Object.defineProperty(h.prototype,"dynamicSize",{get:function(){return this._dynamicSize},set:function(t){t||this._trimAlloc(),this._dynamicSize=t}}),h.prototype.shift=function(t){var e=new ArrayBuffer(this._byteLength-t),r=new Uint8Array(e),s=new Uint8Array(this._buffer,t,r.length);r.set(s),this.buffer=e,this.position-=t},h.prototype.writeInt32Array=function(t,e){if(this._realloc(4*t.length),t instanceof Int32Array&&this.byteOffset+this.position%t.BYTES_PER_ELEMENT===0)h.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,0,t.byteLength),this.mapInt32Array(t.length,e);else for(var r=0;r<t.length;r++)this.writeInt32(t[r],e)},h.prototype.writeInt16Array=function(t,e){if(this._realloc(2*t.length),t instanceof Int16Array&&this.byteOffset+this.position%t.BYTES_PER_ELEMENT===0)h.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,0,t.byteLength),this.mapInt16Array(t.length,e);else for(var r=0;r<t.length;r++)this.writeInt16(t[r],e)},h.prototype.writeInt8Array=function(t){if(this._realloc(+t.length),t instanceof Int8Array&&this.byteOffset+this.position%t.BYTES_PER_ELEMENT===0)h.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])},h.prototype.writeUint32Array=function(t,e){if(this._realloc(4*t.length),t instanceof Uint32Array&&this.byteOffset+this.position%t.BYTES_PER_ELEMENT===0)h.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,0,t.byteLength),this.mapUint32Array(t.length,e);else for(var r=0;r<t.length;r++)this.writeUint32(t[r],e)},h.prototype.writeUint16Array=function(t,e){if(this._realloc(2*t.length),t instanceof Uint16Array&&this.byteOffset+this.position%t.BYTES_PER_ELEMENT===0)h.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,0,t.byteLength),this.mapUint16Array(t.length,e);else for(var r=0;r<t.length;r++)this.writeUint16(t[r],e)},h.prototype.writeUint8Array=function(t){if(this._realloc(+t.length),t instanceof Uint8Array&&this.byteOffset+this.position%t.BYTES_PER_ELEMENT===0)h.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])},h.prototype.writeFloat64Array=function(t,e){if(this._realloc(8*t.length),t instanceof Float64Array&&this.byteOffset+this.position%t.BYTES_PER_ELEMENT===0)h.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,0,t.byteLength),this.mapFloat64Array(t.length,e);else for(var r=0;r<t.length;r++)this.writeFloat64(t[r],e)},h.prototype.writeFloat32Array=function(t,e){if(this._realloc(4*t.length),t instanceof Float32Array&&this.byteOffset+this.position%t.BYTES_PER_ELEMENT===0)h.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,0,t.byteLength),this.mapFloat32Array(t.length,e);else for(var r=0;r<t.length;r++)this.writeFloat32(t[r],e)},h.prototype.writeInt32=function(t,e){this._realloc(4),this._dataView.setInt32(this.position,t,null==e?this.endianness:e),this.position+=4},h.prototype.writeInt16=function(t,e){this._realloc(2),this._dataView.setInt16(this.position,t,null==e?this.endianness:e),this.position+=2},h.prototype.writeInt8=function(t){this._realloc(1),this._dataView.setInt8(this.position,t),this.position+=1},h.prototype.writeUint32=function(t,e){this._realloc(4),this._dataView.setUint32(this.position,t,null==e?this.endianness:e),this.position+=4},h.prototype.writeUint16=function(t,e){this._realloc(2),this._dataView.setUint16(this.position,t,null==e?this.endianness:e),this.position+=2},h.prototype.writeUint8=function(t){this._realloc(1),this._dataView.setUint8(this.position,t),this.position+=1},h.prototype.writeFloat32=function(t,e){this._realloc(4),this._dataView.setFloat32(this.position,t,null==e?this.endianness:e),this.position+=4},h.prototype.writeFloat64=function(t,e){this._realloc(8),this._dataView.setFloat64(this.position,t,null==e?this.endianness:e),this.position+=8},h.prototype.writeUCS2String=function(t,e,r){null==r&&(r=t.length);for(var s=0;s<t.length&&s<r;s++)this.writeUint16(t.charCodeAt(s),e);for(;s<r;s++)this.writeUint16(0)},h.prototype.writeString=function(t,e,r){var s=0;if(null==e||"ASCII"==e)if(null!=r){var a=Math.min(t.length,r);for(s=0;s<a;s++)this.writeUint8(t.charCodeAt(s));for(;s<r;s++)this.writeUint8(0)}else for(s=0;s<t.length;s++)this.writeUint8(t.charCodeAt(s));else this.writeUint8Array(new TextEncoder(e).encode(t.substring(0,r)))},h.prototype.writeCString=function(t,e){var r=0;if(null!=e){var s=Math.min(t.length,e);for(r=0;r<s;r++)this.writeUint8(t.charCodeAt(r));for(;r<e;r++)this.writeUint8(0)}else{for(r=0;r<t.length;r++)this.writeUint8(t.charCodeAt(r));this.writeUint8(0)}},h.prototype.writeStruct=function(t,e){for(var r=0;r<t.length;r+=2){var s=t[r+1];this.writeType(s,e[t[r]],e)}},h.prototype.writeType=function(t,e,r){if("function"==typeof t)return t(this,e);if("object"==typeof t&&!(t instanceof Array))return t.set(this,e,r);var s,a=null,n="ASCII",o=this.position;switch("string"==typeof t&&/:/.test(t)&&(t=(s=t.split(":"))[0],a=parseInt(s[1])),"string"==typeof t&&/,/.test(t)&&(t=(s=t.split(","))[0],n=parseInt(s[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,h.BIG_ENDIAN);break;case"int16be":this.writeInt16(e,h.BIG_ENDIAN);break;case"uint32be":this.writeUint32(e,h.BIG_ENDIAN);break;case"int32be":this.writeInt32(e,h.BIG_ENDIAN);break;case"float32be":this.writeFloat32(e,h.BIG_ENDIAN);break;case"float64be":this.writeFloat64(e,h.BIG_ENDIAN);break;case"uint16le":this.writeUint16(e,h.LITTLE_ENDIAN);break;case"int16le":this.writeInt16(e,h.LITTLE_ENDIAN);break;case"uint32le":this.writeUint32(e,h.LITTLE_ENDIAN);break;case"int32le":this.writeInt32(e,h.LITTLE_ENDIAN);break;case"float32le":this.writeFloat32(e,h.LITTLE_ENDIAN);break;case"float64le":this.writeFloat64(e,h.LITTLE_ENDIAN);break;case"cstring":this.writeCString(e,a);break;case"string":this.writeString(e,n,a);break;case"u16string":this.writeUCS2String(e,this.endianness,a);break;case"u16stringle":this.writeUCS2String(e,h.LITTLE_ENDIAN,a);break;case"u16stringbe":this.writeUCS2String(e,h.BIG_ENDIAN,a);break;default:if(3==t.length)for(var l=t[1],d=0;d<e.length;d++)this.writeType(l,e[d]);else this.writeStruct(t,e)}null!=a&&(this.position=o,this._realloc(a),this.position=o+a)},h.prototype.writeUint64=function(t){var e=Math.floor(t/0x100000000);this.writeUint32(e),this.writeUint32(0|t)},h.prototype.writeUint24=function(t){this.writeUint8((0xff0000&t)>>16),this.writeUint8((65280&t)>>8),this.writeUint8(255&t)},h.prototype.adjustUint32=function(t,e){var r=this.position;this.seek(t),this.writeUint32(e),this.seek(r)},h.prototype.mapInt32Array=function(t,e){this._realloc(4*t);var r=new Int32Array(this._buffer,this.byteOffset+this.position,t);return h.arrayToNative(r,null==e?this.endianness:e),this.position+=4*t,r},h.prototype.mapInt16Array=function(t,e){this._realloc(2*t);var r=new Int16Array(this._buffer,this.byteOffset+this.position,t);return h.arrayToNative(r,null==e?this.endianness:e),this.position+=2*t,r},h.prototype.mapInt8Array=function(t){this._realloc(+t);var e=new Int8Array(this._buffer,this.byteOffset+this.position,t);return this.position+=+t,e},h.prototype.mapUint32Array=function(t,e){this._realloc(4*t);var r=new Uint32Array(this._buffer,this.byteOffset+this.position,t);return h.arrayToNative(r,null==e?this.endianness:e),this.position+=4*t,r},h.prototype.mapUint16Array=function(t,e){this._realloc(2*t);var r=new Uint16Array(this._buffer,this.byteOffset+this.position,t);return h.arrayToNative(r,null==e?this.endianness:e),this.position+=2*t,r},h.prototype.mapFloat64Array=function(t,e){this._realloc(8*t);var r=new Float64Array(this._buffer,this.byteOffset+this.position,t);return h.arrayToNative(r,null==e?this.endianness:e),this.position+=8*t,r},h.prototype.mapFloat32Array=function(t,e){this._realloc(4*t);var r=new Float32Array(this._buffer,this.byteOffset+this.position,t);return h.arrayToNative(r,null==e?this.endianness:e),this.position+=4*t,r};var d=function(t){this.buffers=[],this.bufferIndex=-1,t&&(this.insertBuffer(t),this.bufferIndex=0)};d.prototype=new h(new ArrayBuffer,0,h.BIG_ENDIAN),d.prototype.initialized=function(){var t;return!!(this.bufferIndex>-1)||(this.buffers.length>0?0===(t=this.buffers[0]).fileStart?(this.buffer=t,this.bufferIndex=0,o.debug("MultiBufferStream","Stream ready for parsing"),!0):(o.warn("MultiBufferStream","The first buffer should have a fileStart of 0"),this.logBufferLevel(),!1):(o.warn("MultiBufferStream","No buffer to start parsing from"),this.logBufferLevel(),!1))},ArrayBuffer.concat=function(t,e){o.debug("ArrayBuffer","Trying to create a new buffer of size: "+(t.byteLength+e.byteLength));var r=new Uint8Array(t.byteLength+e.byteLength);return r.set(new Uint8Array(t),0),r.set(new Uint8Array(e),t.byteLength),r.buffer},d.prototype.reduceBuffer=function(t,e,r){var s;return(s=new Uint8Array(r)).set(new Uint8Array(t,e,r)),s.buffer.fileStart=t.fileStart+e,s.buffer.usedBytes=0,s.buffer},d.prototype.insertBuffer=function(t){for(var e=!0,r=0;r<this.buffers.length;r++){var s=this.buffers[r];if(t.fileStart<=s.fileStart){if(t.fileStart===s.fileStart)if(t.byteLength>s.byteLength){this.buffers.splice(r,1),r--;continue}else o.warn("MultiBufferStream","Buffer (fileStart: "+t.fileStart+" - Length: "+t.byteLength+") already appended, ignoring");else t.fileStart+t.byteLength<=s.fileStart||(t=this.reduceBuffer(t,0,s.fileStart-t.fileStart)),o.debug("MultiBufferStream","Appending new buffer (fileStart: "+t.fileStart+" - Length: "+t.byteLength+")"),this.buffers.splice(r,0,t),0===r&&(this.buffer=t);e=!1;break}if(t.fileStart<s.fileStart+s.byteLength){var a=s.fileStart+s.byteLength-t.fileStart,n=t.byteLength-a;if(n>0)t=this.reduceBuffer(t,a,n);else{e=!1;break}}}e&&(o.debug("MultiBufferStream","Appending new buffer (fileStart: "+t.fileStart+" - Length: "+t.byteLength+")"),this.buffers.push(t),0===r&&(this.buffer=t))},d.prototype.logBufferLevel=function(t){var e,r,s,a,n,l=[],h="";for(e=0,s=0,a=0;e<this.buffers.length;e++)r=this.buffers[e],0===e?(l.push(n={}),n.start=r.fileStart,n.end=r.fileStart+r.byteLength,h+="["+n.start+"-"):n.end===r.fileStart?n.end=r.fileStart+r.byteLength:((n={}).start=r.fileStart,h+=l[l.length-1].end-1+"], ["+n.start+"-",n.end=r.fileStart+r.byteLength,l.push(n)),s+=r.usedBytes,a+=r.byteLength;l.length>0&&(h+=n.end-1+"]"),(t?o.info:o.debug)("MultiBufferStream",0===this.buffers.length?"No more buffer in memory":""+this.buffers.length+" stored buffer(s) ("+s+"/"+a+" bytes), continuous ranges: "+h)},d.prototype.cleanBuffers=function(){var t,e;for(t=0;t<this.buffers.length;t++)(e=this.buffers[t]).usedBytes===e.byteLength&&(o.debug("MultiBufferStream","Removing buffer #"+t),this.buffers.splice(t,1),t--)},d.prototype.mergeNextBuffer=function(){if(!(this.bufferIndex+1<this.buffers.length)||(t=this.buffers[this.bufferIndex+1]).fileStart!==this.buffer.fileStart+this.buffer.byteLength)return!1;var t,e=this.buffer.byteLength,r=this.buffer.usedBytes,s=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=r,this.buffer.fileStart=s,o.debug("ISOFile","Concatenating buffer for box parsing (length: "+e+"->"+this.buffer.byteLength+")"),!0},d.prototype.findPosition=function(t,e,r){var s,a=null,n=-1;for(s=!0===t?0:this.bufferIndex;s<this.buffers.length&&(a=this.buffers[s]).fileStart<=e;)n=s,r&&(a.fileStart+a.byteLength<=e?a.usedBytes=a.byteLength:a.usedBytes=e-a.fileStart,this.logBufferLevel()),s++;return -1===n?-1:(a=this.buffers[n]).fileStart+a.byteLength>=e?(o.debug("MultiBufferStream","Found position in existing buffer #"+n),n):-1},d.prototype.findEndContiguousBuf=function(t){var e,r,s,a=void 0!==t?t:this.bufferIndex;if(r=this.buffers[a],this.buffers.length>a+1)for(e=a+1;e<this.buffers.length;e++)if((s=this.buffers[e]).fileStart===r.fileStart+r.byteLength)r=s;else break;return r.fileStart+r.byteLength},d.prototype.getEndFilePositionAfter=function(t){var e=this.findPosition(!0,t,!1);return -1!==e?this.findEndContiguousBuf(e):t},d.prototype.addUsedBytes=function(t){this.buffer.usedBytes+=t,this.logBufferLevel()},d.prototype.setAllUsedBytes=function(){this.buffer.usedBytes=this.buffer.byteLength,this.logBufferLevel()},d.prototype.seek=function(t,e,r){var s;return -1!==(s=this.findPosition(e,t,r))?(this.buffer=this.buffers[s],this.bufferIndex=s,this.position=t-this.buffer.fileStart,o.debug("MultiBufferStream","Repositioning parser at buffer position: "+this.position),!0):(o.debug("MultiBufferStream","Position "+t+" not found in buffered data"),!1)},d.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},d.prototype.getLength=function(){return this.byteLength},d.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},r.MultiBufferStream=d;var u=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,r={};return this.parseOneDescriptor=function(e){var s,a,n,l=0,h=0;for(s=e.readUint8(),l++,n=e.readUint8(),l++;128&n;)h=(127&n)<<7,n=e.readUint8(),l++;return h+=127&n,o.debug("MPEG4DescriptorParser","Found "+(t[s]||"Descriptor "+s)+", size "+h+" at position "+e.getPosition()),(a=t[s]?new r[t[s]](h):new r.Descriptor(h)).parse(e),a},r.Descriptor=function(t,e){this.tag=t,this.size=e,this.descs=[]},r.Descriptor.prototype.parse=function(t){this.data=t.readUint8Array(this.size)},r.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},r.Descriptor.prototype.parseRemainingDescriptors=function(t){for(var r=t.position;t.position<r+this.size;){var s=e.parseOneDescriptor(t);this.descs.push(s)}},r.ES_Descriptor=function(t){r.Descriptor.call(this,3,t)},r.ES_Descriptor.prototype=new r.Descriptor,r.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)},r.ES_Descriptor.prototype.getOTI=function(t){var e=this.findDescriptor(4);return e?e.oti:0},r.ES_Descriptor.prototype.getAudioConfig=function(t){var e=this.findDescriptor(4);if(!e)return null;var r=e.findDescriptor(5);if(!r||!r.data)return null;var s=(248&r.data[0])>>3;return 31===s&&r.data.length>=2&&(s=32+((7&r.data[0])<<3)+((224&r.data[1])>>5)),s},r.DecoderConfigDescriptor=function(t){r.Descriptor.call(this,4,t)},r.DecoderConfigDescriptor.prototype=new r.Descriptor,r.DecoderConfigDescriptor.prototype.parse=function(t){this.oti=t.readUint8(),this.streamType=t.readUint8(),this.upStream=(this.streamType>>1&1)!=0,this.streamType=this.streamType>>>2,this.bufferSize=t.readUint24(),this.maxBitrate=t.readUint32(),this.avgBitrate=t.readUint32(),this.size-=13,this.parseRemainingDescriptors(t)},r.DecoderSpecificInfo=function(t){r.Descriptor.call(this,5,t)},r.DecoderSpecificInfo.prototype=new r.Descriptor,r.SLConfigDescriptor=function(t){r.Descriptor.call(this,6,t)},r.SLConfigDescriptor.prototype=new r.Descriptor,this};r.MPEG4DescriptorParser=u;var p={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"],["grpl"],["j2kH"],["etyp",["tyco"]]],boxCodes:[],fullBoxCodes:[],containerBoxCodes:[],sampleEntryCodes:{},sampleGroupEntryCodes:[],trackGroupTypes:[],UUIDBoxes:{},UUIDs:[],initialize:function(){p.FullBox.prototype=new p.Box,p.ContainerBox.prototype=new p.Box,p.SampleEntry.prototype=new p.Box,p.TrackGroupTypeBox.prototype=new p.FullBox,p.BASIC_BOXES.forEach(function(t){p.createBoxCtor(t)}),p.FULL_BOXES.forEach(function(t){p.createFullBoxCtor(t)}),p.CONTAINER_BOXES.forEach(function(t){p.createContainerBoxCtor(t[0],null,t[1])})},Box:function(t,e,r){this.type=t,this.size=e,this.uuid=r},FullBox:function(t,e,r){p.Box.call(this,t,e,r),this.flags=0,this.version=0},ContainerBox:function(t,e,r){p.Box.call(this,t,e,r),this.boxes=[]},SampleEntry:function(t,e,r,s){p.ContainerBox.call(this,t,e),this.hdr_size=r,this.start=s},SampleGroupEntry:function(t){this.grouping_type=t},TrackGroupTypeBox:function(t,e){p.FullBox.call(this,t,e)},createBoxCtor:function(t,e){p.boxCodes.push(t),p[t+"Box"]=function(e){p.Box.call(this,t,e)},p[t+"Box"].prototype=new p.Box,e&&(p[t+"Box"].prototype.parse=e)},createFullBoxCtor:function(t,e){p[t+"Box"]=function(e){p.FullBox.call(this,t,e)},p[t+"Box"].prototype=new p.FullBox,p[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,r=0;r<e;r++)this[t[r]+"s"]=[]}},createContainerBoxCtor:function(t,e,r){p[t+"Box"]=function(e){p.ContainerBox.call(this,t,e),p.addSubBoxArrays.call(this,r)},p[t+"Box"].prototype=new p.ContainerBox,e&&(p[t+"Box"].prototype.parse=e)},createMediaSampleEntryCtor:function(t,e,r){p.sampleEntryCodes[t]=[],p[t+"SampleEntry"]=function(t,e){p.SampleEntry.call(this,t,e),p.addSubBoxArrays.call(this,r)},p[t+"SampleEntry"].prototype=new p.SampleEntry,e&&(p[t+"SampleEntry"].prototype.parse=e)},createSampleEntryCtor:function(t,e,r,s){p.sampleEntryCodes[t].push(e),p[e+"SampleEntry"]=function(r){p[t+"SampleEntry"].call(this,e,r),p.addSubBoxArrays.call(this,s)},p[e+"SampleEntry"].prototype=new p[t+"SampleEntry"],r&&(p[e+"SampleEntry"].prototype.parse=r)},createEncryptedSampleEntryCtor:function(t,e,r){p.createSampleEntryCtor.call(this,t,e,r,["sinf"])},createSampleGroupCtor:function(t,e){p[t+"SampleGroupEntry"]=function(e){p.SampleGroupEntry.call(this,t,e)},p[t+"SampleGroupEntry"].prototype=new p.SampleGroupEntry,e&&(p[t+"SampleGroupEntry"].prototype.parse=e)},createTrackGroupCtor:function(t,e){p[t+"TrackGroupTypeBox"]=function(e){p.TrackGroupTypeBox.call(this,t,e)},p[t+"TrackGroupTypeBox"].prototype=new p.TrackGroupTypeBox,e&&(p[t+"TrackGroupTypeBox"].prototype.parse=e)},createUUIDBox:function(t,e,r,s){p.UUIDs.push(t),p.UUIDBoxes[t]=function(s){e?p.FullBox.call(this,"uuid",s,t):r?p.ContainerBox.call(this,"uuid",s,t):p.Box.call(this,"uuid",s,t)},p.UUIDBoxes[t].prototype=e?new p.FullBox:r?new p.ContainerBox:new p.Box,s&&(e?p.UUIDBoxes[t].prototype.parse=function(t){this.parseFullHeader(t),s&&s.call(this,t)}:p.UUIDBoxes[t].prototype.parse=s)}};function c(t,e){this.x=t,this.y=e}function f(t,e){this.bad_pixel_row=t,this.bad_pixel_column=e}p.initialize(),p.TKHD_FLAG_ENABLED=1,p.TKHD_FLAG_IN_MOVIE=2,p.TKHD_FLAG_IN_PREVIEW=4,p.TFHD_FLAG_BASE_DATA_OFFSET=1,p.TFHD_FLAG_SAMPLE_DESC=2,p.TFHD_FLAG_SAMPLE_DUR=8,p.TFHD_FLAG_SAMPLE_SIZE=16,p.TFHD_FLAG_SAMPLE_FLAGS=32,p.TFHD_FLAG_DUR_EMPTY=65536,p.TFHD_FLAG_DEFAULT_BASE_IS_MOOF=131072,p.TRUN_FLAGS_DATA_OFFSET=1,p.TRUN_FLAGS_FIRST_FLAG=4,p.TRUN_FLAGS_DURATION=256,p.TRUN_FLAGS_SIZE=512,p.TRUN_FLAGS_FLAGS=1024,p.TRUN_FLAGS_CTS_OFFSET=2048,p.Box.prototype.add=function(t){return this.addBox(new p[t+"Box"])},p.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},p.Box.prototype.set=function(t,e){return this[t]=e,this},p.Box.prototype.addEntry=function(t,e){var r=e||"entries";return this[r]||(this[r]=[]),this[r].push(t),this},r.BoxParser=p,p.parseUUID=function(t){return p.parseHex16(t)},p.parseHex16=function(t){for(var e="",r=0;r<16;r++){var s=t.readUint8().toString(16);e+=1===s.length?"0"+s:s}return e},p.parseOneBox=function(t,e,r){var s,a,n,l=t.getPosition(),h=0;if(t.getEndPosition()-l<8)return o.debug("BoxParser","Not enough data in stream to parse the type and size of the box"),{code:p.ERR_NOT_ENOUGH_DATA};if(r&&r<8)return o.debug("BoxParser","Not enough bytes left in the parent box to parse a new box"),{code:p.ERR_NOT_ENOUGH_DATA};var d=t.readUint32(),u=t.readString(4),c=u;if(o.debug("BoxParser","Found box of type '"+u+"' and size "+d+" at position "+l),h=8,"uuid"==u){if(t.getEndPosition()-t.getPosition()<16||r-h<16)return t.seek(l),o.debug("BoxParser","Not enough bytes left in the parent box to parse a UUID box"),{code:p.ERR_NOT_ENOUGH_DATA};n=p.parseUUID(t),h+=16,c=n}if(1==d){if(t.getEndPosition()-t.getPosition()<8||r&&r-h<8)return t.seek(l),o.warn("BoxParser",'Not enough data in stream to parse the extended size of the "'+u+'" box'),{code:p.ERR_NOT_ENOUGH_DATA};d=t.readUint64(),h+=8}else if(0===d){if(r)d=r;else if("mdat"!==u)return o.error("BoxParser","Unlimited box size not supported for type: '"+u+"'"),s=new p.Box(u,d),{code:p.OK,box:s,size:s.size}}return 0!==d&&d<h?(o.error("BoxParser","Box of type "+u+" has an invalid size "+d+" (too small to be a box)"),{code:p.ERR_NOT_ENOUGH_DATA,type:u,size:d,hdr_size:h,start:l}):0!==d&&r&&d>r?(o.error("BoxParser","Box of type '"+u+"' has a size "+d+" greater than its container size "+r),{code:p.ERR_NOT_ENOUGH_DATA,type:u,size:d,hdr_size:h,start:l}):0!==d&&l+d>t.getEndPosition()?(t.seek(l),o.info("BoxParser","Not enough data in stream to parse the entire '"+u+"' box"),{code:p.ERR_NOT_ENOUGH_DATA,type:u,size:d,hdr_size:h,start:l}):e?{code:p.OK,type:u,size:d,hdr_size:h,start:l}:(p[u+"Box"]?s=new p[u+"Box"](d):"uuid"!==u?(o.warn("BoxParser","Unknown box type: '"+u+"'"),(s=new p.Box(u,d)).has_unparsed_data=!0):p.UUIDBoxes[n]?s=new p.UUIDBoxes[n](d):(o.warn("BoxParser","Unknown uuid type: '"+n+"'"),(s=new p.Box(u,d)).uuid=n,s.has_unparsed_data=!0),s.hdr_size=h,s.start=l,s.write===p.Box.prototype.write&&"mdat"!==s.type&&(o.info("BoxParser","'"+c+"' box writing not yet implemented, keeping unparsed data in memory for later write"),s.parseDataAndRewind(t)),s.parse(t),(a=t.getPosition()-(s.start+s.size))<0?(o.warn("BoxParser","Parsing of box '"+c+"' did not read the entire indicated box data size (missing "+-a+" bytes), seeking forward"),t.seek(s.start+s.size)):a>0&&(o.error("BoxParser","Parsing of box '"+c+"' read "+a+" more bytes than the indicated box data size, seeking backwards"),0!==s.size&&t.seek(s.start+s.size)),{code:p.OK,box:s,size:s.size})},p.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)},p.Box.prototype.parseDataAndRewind=function(t){this.data=t.readUint8Array(this.size-this.hdr_size),t.position-=this.size-this.hdr_size},p.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},p.FullBox.prototype.parseFullHeader=function(t){this.version=t.readUint8(),this.flags=t.readUint24(),this.hdr_size+=4},p.FullBox.prototype.parse=function(t){this.parseFullHeader(t),this.data=t.readUint8Array(this.size-this.hdr_size)},p.ContainerBox.prototype.parse=function(t){for(;t.getPosition()<this.start+this.size;){if((e=p.parseOneBox(t,!1,this.size-(t.getPosition()-this.start))).code!==p.OK)return;if(r=e.box,this.boxes.push(r),this.subBoxNames&&-1!=this.subBoxNames.indexOf(r.type))this[this.subBoxNames[this.subBoxNames.indexOf(r.type)]+"s"].push(r);else{var e,r,s="uuid"!==r.type?r.type:r.uuid;this[s]?o.warn("Box of type "+s+" already stored in field of this type"):this[s]=r}}},p.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)},p.SAMPLE_ENTRY_TYPE_VISUAL="Visual",p.SAMPLE_ENTRY_TYPE_AUDIO="Audio",p.SAMPLE_ENTRY_TYPE_HINT="Hint",p.SAMPLE_ENTRY_TYPE_METADATA="Metadata",p.SAMPLE_ENTRY_TYPE_SUBTITLE="Subtitle",p.SAMPLE_ENTRY_TYPE_SYSTEM="System",p.SAMPLE_ENTRY_TYPE_TEXT="Text",p.SampleEntry.prototype.parseHeader=function(t){t.readUint8Array(6),this.data_reference_index=t.readUint16(),this.hdr_size+=8},p.SampleEntry.prototype.parse=function(t){this.parseHeader(t),this.data=t.readUint8Array(this.size-this.hdr_size)},p.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},p.SampleEntry.prototype.parseFooter=function(t){p.ContainerBox.prototype.parse.call(this,t)},p.createMediaSampleEntryCtor(p.SAMPLE_ENTRY_TYPE_HINT),p.createMediaSampleEntryCtor(p.SAMPLE_ENTRY_TYPE_METADATA),p.createMediaSampleEntryCtor(p.SAMPLE_ENTRY_TYPE_SUBTITLE),p.createMediaSampleEntryCtor(p.SAMPLE_ENTRY_TYPE_SYSTEM),p.createMediaSampleEntryCtor(p.SAMPLE_ENTRY_TYPE_TEXT),p.createMediaSampleEntryCtor(p.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)}),p.createMediaSampleEntryCtor(p.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)}),p.createSampleEntryCtor(p.SAMPLE_ENTRY_TYPE_VISUAL,"avc1"),p.createSampleEntryCtor(p.SAMPLE_ENTRY_TYPE_VISUAL,"avc2"),p.createSampleEntryCtor(p.SAMPLE_ENTRY_TYPE_VISUAL,"avc3"),p.createSampleEntryCtor(p.SAMPLE_ENTRY_TYPE_VISUAL,"avc4"),p.createSampleEntryCtor(p.SAMPLE_ENTRY_TYPE_VISUAL,"av01"),p.createSampleEntryCtor(p.SAMPLE_ENTRY_TYPE_VISUAL,"dav1"),p.createSampleEntryCtor(p.SAMPLE_ENTRY_TYPE_VISUAL,"hvc1"),p.createSampleEntryCtor(p.SAMPLE_ENTRY_TYPE_VISUAL,"hev1"),p.createSampleEntryCtor(p.SAMPLE_ENTRY_TYPE_VISUAL,"hvt1"),p.createSampleEntryCtor(p.SAMPLE_ENTRY_TYPE_VISUAL,"lhe1"),p.createSampleEntryCtor(p.SAMPLE_ENTRY_TYPE_VISUAL,"dvh1"),p.createSampleEntryCtor(p.SAMPLE_ENTRY_TYPE_VISUAL,"dvhe"),p.createSampleEntryCtor(p.SAMPLE_ENTRY_TYPE_VISUAL,"vvc1"),p.createSampleEntryCtor(p.SAMPLE_ENTRY_TYPE_VISUAL,"vvi1"),p.createSampleEntryCtor(p.SAMPLE_ENTRY_TYPE_VISUAL,"vvs1"),p.createSampleEntryCtor(p.SAMPLE_ENTRY_TYPE_VISUAL,"vvcN"),p.createSampleEntryCtor(p.SAMPLE_ENTRY_TYPE_VISUAL,"vp08"),p.createSampleEntryCtor(p.SAMPLE_ENTRY_TYPE_VISUAL,"vp09"),p.createSampleEntryCtor(p.SAMPLE_ENTRY_TYPE_VISUAL,"avs3"),p.createSampleEntryCtor(p.SAMPLE_ENTRY_TYPE_VISUAL,"j2ki"),p.createSampleEntryCtor(p.SAMPLE_ENTRY_TYPE_VISUAL,"mjp2"),p.createSampleEntryCtor(p.SAMPLE_ENTRY_TYPE_VISUAL,"mjpg"),p.createSampleEntryCtor(p.SAMPLE_ENTRY_TYPE_VISUAL,"uncv"),p.createSampleEntryCtor(p.SAMPLE_ENTRY_TYPE_AUDIO,"mp4a"),p.createSampleEntryCtor(p.SAMPLE_ENTRY_TYPE_AUDIO,"ac-3"),p.createSampleEntryCtor(p.SAMPLE_ENTRY_TYPE_AUDIO,"ac-4"),p.createSampleEntryCtor(p.SAMPLE_ENTRY_TYPE_AUDIO,"ec-3"),p.createSampleEntryCtor(p.SAMPLE_ENTRY_TYPE_AUDIO,"Opus"),p.createSampleEntryCtor(p.SAMPLE_ENTRY_TYPE_AUDIO,"mha1"),p.createSampleEntryCtor(p.SAMPLE_ENTRY_TYPE_AUDIO,"mha2"),p.createSampleEntryCtor(p.SAMPLE_ENTRY_TYPE_AUDIO,"mhm1"),p.createSampleEntryCtor(p.SAMPLE_ENTRY_TYPE_AUDIO,"mhm2"),p.createSampleEntryCtor(p.SAMPLE_ENTRY_TYPE_AUDIO,"fLaC"),p.createEncryptedSampleEntryCtor(p.SAMPLE_ENTRY_TYPE_VISUAL,"encv"),p.createEncryptedSampleEntryCtor(p.SAMPLE_ENTRY_TYPE_AUDIO,"enca"),p.createEncryptedSampleEntryCtor(p.SAMPLE_ENTRY_TYPE_SUBTITLE,"encu"),p.createEncryptedSampleEntryCtor(p.SAMPLE_ENTRY_TYPE_SYSTEM,"encs"),p.createEncryptedSampleEntryCtor(p.SAMPLE_ENTRY_TYPE_TEXT,"enct"),p.createEncryptedSampleEntryCtor(p.SAMPLE_ENTRY_TYPE_METADATA,"encm"),p.createBoxCtor("a1lx",function(t){var e=((1&(1&t.readUint8()))+1)*16;this.layer_size=[];for(var r=0;r<3;r++)16==e?this.layer_size[r]=t.readUint16():this.layer_size[r]=t.readUint32()}),p.createBoxCtor("a1op",function(t){this.op_index=t.readUint8()}),p.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)}),p.createBoxCtor("av1C",function(t){var e=t.readUint8();if(e>>7&!1)return void o.error("av1C marker problem");if(this.version=127&e,1!==this.version)return void o.error("av1C version "+this.version+" not supported");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)return void o.error("av1C reserved_1 parsing problem");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 o.error("av1C reserved_2 parsing problem");var r=this.size-this.hdr_size-4;this.configOBUs=t.readUint8Array(r)}),p.createBoxCtor("avcC",function(t){var e,r;for(e=0,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(),r=this.size-this.hdr_size-6,this.SPS=[];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),r-=2+this.SPS[e].length;for(this.nb_PPS_nalus=t.readUint8(),r--,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),r-=2+this.PPS[e].length;r>0&&(this.ext=t.readUint8Array(r))}),p.createBoxCtor("btrt",function(t){this.bufferSizeDB=t.readUint32(),this.maxBitrate=t.readUint32(),this.avgBitrate=t.readUint32()}),p.createFullBoxCtor("ccst",function(t){var e=t.readUint8();this.all_ref_pics_intra=(128&e)==128,this.intra_pred_used=(64&e)==64,this.max_ref_per_pic=(63&e)>>2,t.readUint24()}),p.createBoxCtor("cdef",function(t){var e;for(e=0,this.channel_count=t.readUint16(),this.channel_indexes=[],this.channel_types=[],this.channel_associations=[];e<this.channel_count;e++)this.channel_indexes.push(t.readUint16()),this.channel_types.push(t.readUint16()),this.channel_associations.push(t.readUint16())}),p.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()}),p.createBoxCtor("clli",function(t){this.max_content_light_level=t.readUint16(),this.max_pic_average_light_level=t.readUint16()}),p.createFullBoxCtor("cmex",function(t){1&this.flags&&(this.pos_x=t.readInt32()),2&this.flags&&(this.pos_y=t.readInt32()),4&this.flags&&(this.pos_z=t.readInt32()),8&this.flags&&(0==this.version?16&this.flags?(this.quat_x=t.readInt32(),this.quat_y=t.readInt32(),this.quat_z=t.readInt32()):(this.quat_x=t.readInt16(),this.quat_y=t.readInt16(),this.quat_z=t.readInt16()):this.version),32&this.flags&&(this.id=t.readUint32())}),p.createFullBoxCtor("cmin",function(t){this.focal_length_x=t.readInt32(),this.principal_point_x=t.readInt32(),this.principal_point_y=t.readInt32(),1&this.flags&&(this.focal_length_y=t.readInt32(),this.skew_factor=t.readInt32())}),p.createBoxCtor("cmpd",function(t){for(i=0,this.component_count=t.readUint32(),this.component_types=[],this.component_type_urls=[];i<this.component_count;i++){var e=t.readUint16();this.component_types.push(e),e>=32768&&this.component_type_urls.push(t.readCString())}}),p.createFullBoxCtor("co64",function(t){var e,r;if(e=t.readUint32(),this.chunk_offsets=[],0===this.version)for(r=0;r<e;r++)this.chunk_offsets.push(t.readUint64())}),p.createFullBoxCtor("CoLL",function(t){this.maxCLL=t.readUint16(),this.maxFALL=t.readUint16()}),p.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?this.ICC_profile=t.readUint8Array(this.size-4):"prof"===this.colour_type&&(this.ICC_profile=t.readUint8Array(this.size-4))}),p.createFullBoxCtor("cprt",function(t){this.parseLanguage(t),this.notice=t.readCString()}),p.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())}),p.createFullBoxCtor("ctts",function(t){if(e=t.readUint32(),this.sample_counts=[],this.sample_offsets=[],0===this.version)for(r=0;r<e;r++){this.sample_counts.push(t.readUint32());var e,r,s=t.readInt32();s<0&&o.warn("BoxParser","ctts box uses negative values without using version 1"),this.sample_offsets.push(s)}else if(1==this.version)for(r=0;r<e;r++)this.sample_counts.push(t.readUint32()),this.sample_offsets.push(t.readInt32())}),p.createBoxCtor("dac3",function(t){var e=t.readUint8(),r=t.readUint8(),s=t.readUint8();this.fscod=e>>6,this.bsid=e>>1&31,this.bsmod=(1&e)<<2|r>>6&3,this.acmod=r>>3&7,this.lfeon=r>>2&1,this.bit_rate_code=3&r|s>>5&7}),p.createBoxCtor("dec3",function(t){var e=t.readUint16();this.data_rate=e>>3,this.num_ind_sub=7&e,this.ind_subs=[];for(var r=0;r<this.num_ind_sub+1;r++){var s={};this.ind_subs.push(s);var a=t.readUint8(),n=t.readUint8(),o=t.readUint8();s.fscod=a>>6,s.bsid=a>>1&31,s.bsmod=(1&a)<<4|n>>4&15,s.acmod=n>>1&7,s.lfeon=1&n,s.num_dep_sub=o>>1&15,s.num_dep_sub>0&&(s.chan_loc=(1&o)<<8|t.readUint8())}}),p.createFullBoxCtor("dfLa",function(t){for(var e=[],r=["STREAMINFO","PADDING","APPLICATION","SEEKTABLE","VORBIS_COMMENT","CUESHEET","PICTURE","RESERVED"];;){var s=t.readUint8(),a=Math.min(127&s,r.length-1);if(a?t.readUint8Array(t.readUint24()):(t.readUint8Array(13),this.samplerate=t.readUint32()>>12,t.readUint8Array(20)),e.push(r[a]),128&s)break}this.numMetadataBlocks=e.length+" ("+e.join(", ")+")"}),p.createBoxCtor("dimm",function(t){this.bytessent=t.readUint64()}),p.createBoxCtor("dmax",function(t){this.time=t.readUint32()}),p.createBoxCtor("dmed",function(t){this.bytessent=t.readUint64()}),p.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()}}),p.createFullBoxCtor("dref",function(t){this.entries=[];for(var e,r,s=t.readUint32(),a=0;a<s;a++){if((e=p.parseOneBox(t,!1,this.size-(t.getPosition()-this.start))).code!==p.OK)return;r=e.box,this.entries.push(r)}}),p.createBoxCtor("drep",function(t){this.bytessent=t.readUint64()}),p.createFullBoxCtor("elng",function(t){this.extended_language=t.readString(this.size-this.hdr_size)}),p.createFullBoxCtor("elst",function(t){this.entries=[];for(var e=t.readUint32(),r=0;r<e;r++){var s={};this.entries.push(s),1===this.version?(s.segment_duration=t.readUint64(),s.media_time=t.readInt64()):(s.segment_duration=t.readUint32(),s.media_time=t.readInt32()),s.media_rate_integer=t.readInt16(),s.media_rate_fraction=t.readInt16()}}),p.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)}),p.createEntityToGroupCtor=function(t,e){p[t+"Box"]=function(e){p.FullBox.call(this,t,e)},p[t+"Box"].prototype=new p.FullBox,p[t+"Box"].prototype.parse=function(t){if(this.parseFullHeader(t),e)e.call(this,t);else for(i=0,this.group_id=t.readUint32(),this.num_entities_in_group=t.readUint32(),this.entity_ids=[];i<this.num_entities_in_group;i++){var r=t.readUint32();this.entity_ids.push(r)}}},p.createEntityToGroupCtor("aebr"),p.createEntityToGroupCtor("afbr"),p.createEntityToGroupCtor("albc"),p.createEntityToGroupCtor("altr"),p.createEntityToGroupCtor("brst"),p.createEntityToGroupCtor("dobr"),p.createEntityToGroupCtor("eqiv"),p.createEntityToGroupCtor("favc"),p.createEntityToGroupCtor("fobr"),p.createEntityToGroupCtor("iaug"),p.createEntityToGroupCtor("pano"),p.createEntityToGroupCtor("slid"),p.createEntityToGroupCtor("ster"),p.createEntityToGroupCtor("tsyn"),p.createEntityToGroupCtor("wbbr"),p.createEntityToGroupCtor("prgr"),p.createEntityToGroupCtor("pymd",function(t){this.group_id=t.readUint32(),this.num_entities_in_group=t.readUint32(),this.entity_ids=[];for(var e=0;e<this.num_entities_in_group;e++){var r=t.readUint32();this.entity_ids.push(r)}for(e=0,this.tile_size_x=t.readUint16(),this.tile_size_y=t.readUint16(),this.layer_binning=[],this.tiles_in_layer_column_minus1=[],this.tiles_in_layer_row_minus1=[];e<this.num_entities_in_group;e++)this.layer_binning[e]=t.readUint16(),this.tiles_in_layer_row_minus1[e]=t.readUint16(),this.tiles_in_layer_column_minus1[e]=t.readUint16()}),p.createFullBoxCtor("esds",function(t){var e=t.readUint8Array(this.size-this.hdr_size);if(this.data=e,void 0!==u){var r=new u;this.esd=r.parseOneDescriptor(new h(e.buffer,0,h.BIG_ENDIAN))}}),p.createBoxCtor("fiel",function(t){this.fieldCount=t.readUint8(),this.fieldOrdering=t.readUint8()}),p.createBoxCtor("frma",function(t){this.data_format=t.readString(4)}),p.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 r=0;e>=4;)this.compatible_brands[r]=t.readString(4),e-=4,r++}),p.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)))}),p.createBoxCtor("hvcC",function(t){this.configurationVersion=t.readUint8(),a=t.readUint8(),this.general_profile_space=a>>6,this.general_tier_flag=(32&a)>>5,this.general_profile_idc=31&a,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(),a=t.readUint8(),this.constantFrameRate=a>>6,this.numTemporalLayers=(13&a)>>3,this.temporalIdNested=(4&a)>>2,this.lengthSizeMinusOne=3&a,this.nalu_arrays=[];var e,r,s,a,n=t.readUint8();for(e=0;e<n;e++){var o=[];this.nalu_arrays.push(o),o.completeness=(128&(a=t.readUint8()))>>7,o.nalu_type=63&a;var l=t.readUint16();for(r=0;r<l;r++){var h={};o.push(h),s=t.readUint16(),h.data=t.readUint8Array(s)}}}),p.createFullBoxCtor("iinf",function(t){var e;0===this.version?this.entry_count=t.readUint16():this.entry_count=t.readUint32(),this.item_infos=[];for(var r=0;r<this.entry_count;r++){if((e=p.parseOneBox(t,!1,this.size-(t.getPosition()-this.start))).code!==p.OK)return;"infe"!==e.box.type&&o.error("BoxParser","Expected 'infe' box, got "+e.box.type),this.item_infos[r]=e.box}}),p.createFullBoxCtor("iloc",function(t){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 e,r=0;if(this.version<2)r=t.readUint16();else if(2===this.version)r=t.readUint32();else throw"version of iloc box not supported";for(var s=0;s<r;s++){var a={};if(this.items.push(a),this.version<2)a.item_ID=t.readUint16();else if(2===this.version)a.item_ID=t.readUint32();else throw"version of iloc box not supported";switch(1===this.version||2===this.version?a.construction_method=15&t.readUint16():a.construction_method=0,a.data_reference_index=t.readUint16(),this.base_offset_size){case 0:a.base_offset=0;break;case 4:a.base_offset=t.readUint32();break;case 8:a.base_offset=t.readUint64();break;default:throw"Error reading base offset size"}var n=t.readUint16();a.extents=[];for(var o=0;o<n;o++){var l={};if(a.extents.push(l),1===this.version||2===this.version)switch(this.index_size){case 0:l.extent_index=0;break;case 4:l.extent_index=t.readUint32();break;case 8:l.extent_index=t.readUint64();break;default:throw"Error reading extent index"}switch(this.offset_size){case 0:l.extent_offset=0;break;case 4:l.extent_offset=t.readUint32();break;case 8:l.extent_offset=t.readUint64();break;default:throw"Error reading extent index"}switch(this.length_size){case 0:l.extent_length=0;break;case 4:l.extent_length=t.readUint32();break;case 8:l.extent_length=t.readUint64();break;default:throw"Error reading extent index"}}}}),p.createBoxCtor("imir",function(t){var e=t.readUint8();this.reserved=e>>7,this.axis=1&e}),p.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){this.extension_type=t.readString(4),o.warn("BoxParser","Cannot parse extension type"),t.seek(this.start+this.size);return}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()))}),p.createFullBoxCtor("ipma",function(t){var e,r;for(e=0,entry_count=t.readUint32(),this.associations=[];e<entry_count;e++){var s={};this.associations.push(s),this.version<1?s.id=t.readUint16():s.id=t.readUint32();var a=t.readUint8();for(r=0,s.props=[];r<a;r++){var n=t.readUint8(),o={};s.props.push(o),o.essential=(128&n)>>7==1,1&this.flags?o.property_index=(127&n)<<8|t.readUint8():o.property_index=127&n}}}),p.createFullBoxCtor("iref",function(t){var e,r;for(this.references=[];t.getPosition()<this.start+this.size;){if((e=p.parseOneBox(t,!0,this.size-(t.getPosition()-this.start))).code!==p.OK)return;(r=0===this.version?new p.SingleItemTypeReferenceBox(e.type,e.size,e.hdr_size,e.start):new p.SingleItemTypeReferenceBoxLarge(e.type,e.size,e.hdr_size,e.start)).write===p.Box.prototype.write&&"mdat"!==r.type&&(o.warn("BoxParser",r.type+" box writing not yet implemented, keeping unparsed data in memory for later write"),r.parseDataAndRewind(t)),r.parse(t),this.references.push(r)}}),p.createBoxCtor("irot",function(t){this.angle=3&t.readUint8()}),p.createFullBoxCtor("ispe",function(t){this.image_width=t.readUint32(),this.image_height=t.readUint32()}),p.createFullBoxCtor("kind",function(t){this.schemeURI=t.readCString(),this.value=t.readCString()}),p.createFullBoxCtor("leva",function(t){var e=t.readUint8();this.levels=[];for(var r=0;r<e;r++){var s={};this.levels[r]=s,s.track_ID=t.readUint32();var a=t.readUint8();switch(s.padding_flag=a>>7,s.assignment_type=127&a,s.assignment_type){case 0:s.grouping_type=t.readString(4);break;case 1:s.grouping_type=t.readString(4),s.grouping_type_parameter=t.readUint32();break;case 2:case 3:break;case 4:s.sub_track_id=t.readUint32();break;default:o.warn("BoxParser","Unknown leva assignement type")}}}),p.createBoxCtor("lhvC",function(t){this.configurationVersion=t.readUint8(),this.min_spatial_segmentation_idc=4095&t.readUint16(),this.parallelismType=3&t.readUint8(),s=t.readUint8(),this.numTemporalLayers=(13&s)>>3,this.temporalIdNested=(4&s)>>2,this.lengthSizeMinusOne=3&s,this.nalu_arrays=[];var e,r,s,a=t.readUint8();for(e=0;e<a;e++){var n=[];this.nalu_arrays.push(n),n.completeness=(128&(s=t.readUint8()))>>7,n.nalu_type=63&s;var o=t.readUint16();for(r=0;r<o;r++){var l={};n.push(l);var h=t.readUint16();l.data=t.readUint8Array(h)}}}),p.createBoxCtor("lsel",function(t){this.layer_id=t.readUint16()}),p.createBoxCtor("maxr",function(t){this.period=t.readUint32(),this.bytes=t.readUint32()}),c.prototype.toString=function(){return"("+this.x+","+this.y+")"},p.createBoxCtor("mdcv",function(t){this.display_primaries=[],this.display_primaries[0]=new c(t.readUint16(),t.readUint16()),this.display_primaries[1]=new c(t.readUint16(),t.readUint16()),this.display_primaries[2]=new c(t.readUint16(),t.readUint16()),this.white_point=new c(t.readUint16(),t.readUint16()),this.max_display_mastering_luminance=t.readUint32(),this.min_display_mastering_luminance=t.readUint32()}),p.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()}),p.createFullBoxCtor("mehd",function(t){1&this.flags&&(o.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()}),p.createFullBoxCtor("meta",function(t){this.boxes=[],p.ContainerBox.prototype.parse.call(this,t)}),p.createFullBoxCtor("mfhd",function(t){this.sequence_number=t.readUint32()}),p.createFullBoxCtor("mfro",function(t){this._size=t.readUint32()}),p.createFullBoxCtor("mskC",function(t){this.bits_per_pixel=t.readUint8()}),p.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()}),p.createBoxCtor("npck",function(t){this.packetssent=t.readUint32()}),p.createBoxCtor("nump",function(t){this.packetssent=t.readUint64()}),p.createFullBoxCtor("padb",function(t){var e=t.readUint32();this.padbits=[];for(var r=0;r<Math.floor((e+1)/2);r++)this.padbits=t.readUint8()}),p.createBoxCtor("pasp",function(t){this.hSpacing=t.readUint32(),this.vSpacing=t.readUint32()}),p.createBoxCtor("payl",function(t){this.text=t.readString(this.size-this.hdr_size)}),p.createBoxCtor("payt",function(t){this.payloadID=t.readUint32();var e=t.readUint8();this.rtpmap_string=t.readString(e)}),p.createFullBoxCtor("pdin",function(t){var e=(this.size-this.hdr_size)/8;this.rate=[],this.initial_delay=[];for(var r=0;r<e;r++)this.rate[r]=t.readUint32(),this.initial_delay[r]=t.readUint32()}),p.createFullBoxCtor("pitm",function(t){0===this.version?this.item_id=t.readUint16():this.item_id=t.readUint32()}),p.createFullBoxCtor("pixi",function(t){var e;for(e=0,this.num_channels=t.readUint8(),this.bits_per_channels=[];e<this.num_channels;e++)this.bits_per_channels[e]=t.readUint8()}),p.createBoxCtor("pmax",function(t){this.bytes=t.readUint32()}),p.createFullBoxCtor("prdi",function(t){if(this.step_count=t.readUint16(),this.item_count=[],2&this.flags)for(var e=0;e<this.step_count;e++)this.item_count[e]=t.readUint16()}),p.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()}),p.createFullBoxCtor("pssh",function(t){if(this.system_id=p.parseHex16(t),this.version>0){var e=t.readUint32();this.kid=[];for(var r=0;r<e;r++)this.kid[r]=p.parseHex16(t)}var s=t.readUint32();s>0&&(this.data=t.readUint8Array(s))}),p.createFullBoxCtor("clef",function(t){this.width=t.readUint32(),this.height=t.readUint32()}),p.createFullBoxCtor("enof",function(t){this.width=t.readUint32(),this.height=t.readUint32()}),p.createFullBoxCtor("prof",function(t){this.width=t.readUint32(),this.height=t.readUint32()}),p.createContainerBoxCtor("tapt",null,["clef","prof","enof"]),p.createBoxCtor("rtp ",function(t){this.descriptionformat=t.readString(4),this.sdptext=t.readString(this.size-this.hdr_size-4)}),p.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 r=0;r<e;r++)0===this.version?this.offset[r]=t.readUint32():this.offset[r]=t.readUint64()}),p.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 r=0;r<e;r++)this.sample_info_size[r]=t.readUint8()}),p.createSampleEntryCtor(p.SAMPLE_ENTRY_TYPE_METADATA,"mett",function(t){this.parseHeader(t),this.content_encoding=t.readCString(),this.mime_format=t.readCString(),this.parseFooter(t)}),p.createSampleEntryCtor(p.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)}),p.createSampleEntryCtor(p.SAMPLE_ENTRY_TYPE_SUBTITLE,"sbtt",function(t){this.parseHeader(t),this.content_encoding=t.readCString(),this.mime_format=t.readCString(),this.parseFooter(t)}),p.createSampleEntryCtor(p.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)}),p.createSampleEntryCtor(p.SAMPLE_ENTRY_TYPE_SUBTITLE,"stxt",function(t){this.parseHeader(t),this.content_encoding=t.readCString(),this.mime_format=t.readCString(),this.parseFooter(t)}),p.createSampleEntryCtor(p.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)}),p.createSampleEntryCtor(p.SAMPLE_ENTRY_TYPE_METADATA,"wvtt",function(t){this.parseHeader(t),this.parseFooter(t)}),p.createSampleGroupCtor("alst",function(t){var e,r=t.readUint16();for(e=0,this.first_output_sample=t.readUint16(),this.sample_offset=[];e<r;e++)this.sample_offset[e]=t.readUint32();var s=this.description_length-4-4*r;for(e=0,this.num_output_samples=[],this.num_total_samples=[];e<s/4;e++)this.num_output_samples[e]=t.readUint16(),this.num_total_samples[e]=t.readUint16()}),p.createSampleGroupCtor("avll",function(t){this.layerNumber=t.readUint8(),this.accurateStatisticsFlag=t.readUint8(),this.avgBitRate=t.readUint16(),this.avgFrameRate=t.readUint16()}),p.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 r=t.readUint8(),s=0;s<r;s++){var a={};this.dependency.push(a),a.subSeqDirectionFlag=t.readUint8(),a.layerNumber=t.readUint8(),a.subSequenceIdentifier=t.readUint16()}}),p.createSampleGroupCtor("dtrt",function(t){o.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),p.createSampleGroupCtor("mvif",function(t){o.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),p.createSampleGroupCtor("prol",function(t){this.roll_distance=t.readInt16()}),p.createSampleGroupCtor("rap ",function(t){var e=t.readUint8();this.num_leading_samples_known=e>>7,this.num_leading_samples=127&e}),p.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)o.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()}}),p.createSampleGroupCtor("roll",function(t){this.roll_distance=t.readInt16()}),p.SampleGroupEntry.prototype.parse=function(t){o.warn("BoxParser","Unknown Sample Group type: "+this.grouping_type),this.data=t.readUint8Array(this.description_length)},p.createSampleGroupCtor("scif",function(t){o.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),p.createSampleGroupCtor("scnm",function(t){o.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),p.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=p.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))}),p.createSampleGroupCtor("stsa",function(t){o.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),p.createSampleGroupCtor("sync",function(t){var e=t.readUint8();this.NAL_unit_type=63&e}),p.createSampleGroupCtor("tele",function(t){var e=t.readUint8();this.level_independently_decodable=e>>7}),p.createSampleGroupCtor("tsas",function(t){o.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),p.createSampleGroupCtor("tscl",function(t){o.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),p.createSampleGroupCtor("vipr",function(t){o.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),p.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(),r=0;r<e;r++){var s={};this.entries.push(s),s.sample_count=t.readInt32(),s.group_description_index=t.readInt32()}}),f.prototype.toString=function(){return"[row: "+this.bad_pixel_row+", column: "+this.bad_pixel_column+"]"},p.createFullBoxCtor("sbpm",function(t){for(e=0,this.component_count=t.readUint16(),this.component_index=[];e<this.component_count;e++)this.component_index.push(t.readUint16());var e,r=t.readUint8();for(e=0,this.correction_applied=128==(128&r),this.num_bad_rows=t.readUint32(),this.num_bad_cols=t.readUint32(),this.num_bad_pixels=t.readUint32(),this.bad_rows=[],this.bad_columns=[],this.bad_pixels=[];e<this.num_bad_rows;e++)this.bad_rows.push(t.readUint32());for(e=0;e<this.num_bad_cols;e++)this.bad_columns.push(t.readUint32());for(e=0;e<this.num_bad_pixels;e++){var s=t.readUint32(),a=t.readUint32();this.bad_pixels.push(new f(s,a))}}),p.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))}),p.createBoxCtor("sdp ",function(t){this.sdptext=t.readString(this.size-this.hdr_size)}),p.createFullBoxCtor("sdtp",function(t){var e,r=this.size-this.hdr_size;this.is_leading=[],this.sample_depends_on=[],this.sample_is_depended_on=[],this.sample_has_redundancy=[];for(var s=0;s<r;s++)e=t.readUint8(),this.is_leading[s]=e>>6,this.sample_depends_on[s]=e>>4&3,this.sample_is_depended_on[s]=e>>2&3,this.sample_has_redundancy[s]=3&e}),p.createFullBoxCtor("senc"),p.createFullBoxCtor("sgpd",function(t){this.grouping_type=t.readString(4),o.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,r=t.readUint32(),s=0;s<r;s++)e=p[this.grouping_type+"SampleGroupEntry"]?new p[this.grouping_type+"SampleGroupEntry"](this.grouping_type):new p.SampleGroupEntry(this.grouping_type),this.entries.push(e),1===this.version&&0===this.default_length?e.description_length=t.readUint32():e.description_length=this.default_length,e.write===p.SampleGroupEntry.prototype.write&&(o.info("BoxParser","SampleGroup for type "+this.grouping_type+" writing not yet implemented, keeping unparsed data in memory for later write"),e.data=t.readUint8Array(e.description_length),t.position-=e.description_length),e.parse(t)}),p.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(),r=0;r<e;r++){var s={};this.references.push(s);var a=t.readUint32();s.reference_type=a>>31&1,s.referenced_size=0x7fffffff&a,s.subsegment_duration=t.readUint32(),s.starts_with_SAP=(a=t.readUint32())>>31&1,s.SAP_type=a>>28&7,s.SAP_delta_time=0xfffffff&a}}),p.SingleItemTypeReferenceBox=function(t,e,r,s){p.Box.call(this,t,e),this.hdr_size=r,this.start=s},p.SingleItemTypeReferenceBox.prototype=new p.Box,p.SingleItemTypeReferenceBox.prototype.parse=function(t){this.from_item_ID=t.readUint16();var e=t.readUint16();this.references=[];for(var r=0;r<e;r++)this.references[r]={},this.references[r].to_item_ID=t.readUint16()},p.SingleItemTypeReferenceBoxLarge=function(t,e,r,s){p.Box.call(this,t,e),this.hdr_size=r,this.start=s},p.SingleItemTypeReferenceBoxLarge.prototype=new p.Box,p.SingleItemTypeReferenceBoxLarge.prototype.parse=function(t){this.from_item_ID=t.readUint32();var e=t.readUint16();this.references=[];for(var r=0;r<e;r++)this.references[r]={},this.references[r].to_item_ID=t.readUint32()},p.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()}),p.createFullBoxCtor("smhd",function(t){this.balance=t.readUint16(),t.readUint16()}),p.createFullBoxCtor("ssix",function(t){this.subsegments=[];for(var e=t.readUint32(),r=0;r<e;r++){var s={};this.subsegments.push(s),s.ranges=[];for(var a=t.readUint32(),n=0;n<a;n++){var o={};s.ranges.push(o),o.level=t.readUint8(),o.range_size=t.readUint24()}}}),p.createFullBoxCtor("stco",function(t){var e;if(e=t.readUint32(),this.chunk_offsets=[],0===this.version)for(var r=0;r<e;r++)this.chunk_offsets.push(t.readUint32())}),p.createFullBoxCtor("stdp",function(t){var e=(this.size-this.hdr_size)/2;this.priority=[];for(var r=0;r<e;r++)this.priority[r]=t.readUint16()}),p.createFullBoxCtor("sthd"),p.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 r=0;r<e;r++)this.attribute_list[r]=t.readUint32()}),p.createFullBoxCtor("stsc",function(t){var e,r;if(e=t.readUint32(),this.first_chunk=[],this.samples_per_chunk=[],this.sample_description_index=[],0===this.version)for(r=0;r<e;r++)this.first_chunk.push(t.readUint32()),this.samples_per_chunk.push(t.readUint32()),this.sample_description_index.push(t.readUint32())}),p.createFullBoxCtor("stsd",function(t){var e,r,s,a;for(e=1,this.entries=[],s=t.readUint32();e<=s;e++){if((r=p.parseOneBox(t,!0,this.size-(t.getPosition()-this.start))).code!==p.OK)return;p[r.type+"SampleEntry"]?((a=new p[r.type+"SampleEntry"](r.size)).hdr_size=r.hdr_size,a.start=r.start):(o.warn("BoxParser","Unknown sample entry type: "+r.type),a=new p.SampleEntry(r.type,r.size,r.hdr_size,r.start)),a.write===p.SampleEntry.prototype.write&&(o.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)}}),p.createFullBoxCtor("stsg",function(t){this.grouping_type=t.readUint32();var e=t.readUint16();this.group_description_index=[];for(var r=0;r<e;r++)this.group_description_index[r]=t.readUint32()}),p.createFullBoxCtor("stsh",function(t){var e,r;if(e=t.readUint32(),this.shadowed_sample_numbers=[],this.sync_sample_numbers=[],0===this.version)for(r=0;r<e;r++)this.shadowed_sample_numbers.push(t.readUint32()),this.sync_sample_numbers.push(t.readUint32())}),p.createFullBoxCtor("stss",function(t){var e,r;if(r=t.readUint32(),0===this.version)for(e=0,this.sample_numbers=[];e<r;e++)this.sample_numbers.push(t.readUint32())}),p.createFullBoxCtor("stsz",function(t){var e;if(this.sample_sizes=[],0===this.version)for(e=0,this.sample_size=t.readUint32(),this.sample_count=t.readUint32();e<this.sample_count;e++)0===this.sample_size?this.sample_sizes.push(t.readUint32()):this.sample_sizes[e]=this.sample_size}),p.createFullBoxCtor("stts",function(t){var e,r,s;if(e=t.readUint32(),this.sample_counts=[],this.sample_deltas=[],0===this.version)for(r=0;r<e;r++)this.sample_counts.push(t.readUint32()),(s=t.readInt32())<0&&(o.warn("BoxParser","File uses negative stts sample delta, using value 1 instead, sync may be lost!"),s=1),this.sample_deltas.push(s)}),p.createFullBoxCtor("stvi",function(t){var e,r,s=t.readUint32();this.single_view_allowed=3&s,this.stereo_scheme=t.readUint32();var a=t.readUint32();for(this.stereo_indication_type=t.readString(a),this.boxes=[];t.getPosition()<this.start+this.size;){if((e=p.parseOneBox(t,!1,this.size-(t.getPosition()-this.start))).code!==p.OK)return;r=e.box,this.boxes.push(r),this[r.type]=r}}),p.createBoxCtor("styp",function(t){p.ftypBox.prototype.parse.call(this,t)}),p.createFullBoxCtor("stz2",function(t){if(this.sample_sizes=[],0===this.version)if(this.reserved=t.readUint24(),this.field_size=t.readUint8(),r=t.readUint32(),4===this.field_size)for(e=0;e<r;e+=2){var e,r,s=t.readUint8();this.sample_sizes[e]=s>>4&15,this.sample_sizes[e+1]=15&s}else if(8===this.field_size)for(e=0;e<r;e++)this.sample_sizes[e]=t.readUint8();else if(16===this.field_size)for(e=0;e<r;e++)this.sample_sizes[e]=t.readUint16();else o.error("BoxParser","Error in length field in stz2 box")}),p.createFullBoxCtor("subs",function(t){for(e=0,s=t.readUint32(),this.entries=[];e<s;e++){var e,r,s,a,n={};if(this.entries[e]=n,n.sample_delta=t.readUint32(),n.subsamples=[],(a=t.readUint16())>0)for(r=0;r<a;r++){var o={};n.subsamples.push(o),1==this.version?o.size=t.readUint32():o.size=t.readUint16(),o.priority=t.readUint8(),o.discardable=t.readUint8(),o.codec_specific_parameters=t.readUint32()}}}),p.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=p.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))}),p.createFullBoxCtor("tfdt",function(t){1==this.version?this.baseMediaDecodeTime=t.readUint64():this.baseMediaDecodeTime=t.readUint32()}),p.createFullBoxCtor("tfhd",function(t){var e=0;this.track_id=t.readUint32(),this.size-this.hdr_size>e&&this.flags&p.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&p.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&p.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&p.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&p.TFHD_FLAG_SAMPLE_FLAGS?(this.default_sample_flags=t.readUint32(),e+=4):this.default_sample_flags=0}),p.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 r=t.readUint32(),s=0;s<r;s++)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)]()}),p.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()}),p.createBoxCtor("tmax",function(t){this.time=t.readUint32()}),p.createBoxCtor("tmin",function(t){this.time=t.readUint32()}),p.createBoxCtor("totl",function(t){this.bytessent=t.readUint32()}),p.createBoxCtor("tpay",function(t){this.bytessent=t.readUint32()}),p.createBoxCtor("tpyl",function(t){this.bytessent=t.readUint64()}),p.TrackGroupTypeBox.prototype.parse=function(t){this.parseFullHeader(t),this.track_group_id=t.readUint32()},p.createTrackGroupCtor("msrc"),p.TrackReferenceTypeBox=function(t,e,r,s){p.Box.call(this,t,e),this.hdr_size=r,this.start=s},p.TrackReferenceTypeBox.prototype=new p.Box,p.TrackReferenceTypeBox.prototype.parse=function(t){this.track_ids=t.readUint32Array((this.size-this.hdr_size)/4)},p.trefBox.prototype.parse=function(t){for(var e,r;t.getPosition()<this.start+this.size;){if((e=p.parseOneBox(t,!0,this.size-(t.getPosition()-this.start))).code!==p.OK)return;(r=new p.TrackReferenceTypeBox(e.type,e.size,e.hdr_size,e.start)).write===p.Box.prototype.write&&"mdat"!==r.type&&(o.info("BoxParser","TrackReference "+r.type+" box writing not yet implemented, keeping unparsed data in memory for later write"),r.parseDataAndRewind(t)),r.parse(t),this.boxes.push(r)}},p.createFullBoxCtor("trep",function(t){for(this.track_ID=t.readUint32(),this.boxes=[];t.getPosition()<this.start+this.size;){if((ret=p.parseOneBox(t,!1,this.size-(t.getPosition()-this.start))).code!==p.OK)return;box=ret.box,this.boxes.push(box)}}),p.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()}),p.createBoxCtor("trpy",function(t){this.bytessent=t.readUint64()}),p.createFullBoxCtor("trun",function(t){var e=0;if(this.sample_count=t.readUint32(),e+=4,this.size-this.hdr_size>e&&this.flags&p.TRUN_FLAGS_DATA_OFFSET?(this.data_offset=t.readInt32(),e+=4):this.data_offset=0,this.size-this.hdr_size>e&&this.flags&p.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 r=0;r<this.sample_count;r++)this.flags&p.TRUN_FLAGS_DURATION&&(this.sample_duration[r]=t.readUint32()),this.flags&p.TRUN_FLAGS_SIZE&&(this.sample_size[r]=t.readUint32()),this.flags&p.TRUN_FLAGS_FLAGS&&(this.sample_flags[r]=t.readUint32()),this.flags&p.TRUN_FLAGS_CTS_OFFSET&&(0===this.version?this.sample_composition_time_offset[r]=t.readUint32():this.sample_composition_time_offset[r]=t.readInt32())}),p.createFullBoxCtor("tsel",function(t){this.switch_group=t.readUint32();var e=(this.size-this.hdr_size-4)/4;this.attribute_list=[];for(var r=0;r<e;r++)this.attribute_list[r]=t.readUint32()}),p.createFullBoxCtor("txtC",function(t){this.config=t.readCString()}),p.createBoxCtor("tyco",function(t){var e=(this.size-this.hdr_size)/4;this.compatible_brands=[];for(var r=0;r<e;r++)this.compatible_brands[r]=t.readString(4)}),p.createFullBoxCtor("udes",function(t){this.lang=t.readCString(),this.name=t.readCString(),this.description=t.readCString(),this.tags=t.readCString()}),p.createFullBoxCtor("uncC",function(t){var e;if(this.profile=t.readUint32(),1==this.version);else if(0==this.version){for(e=0,this.component_count=t.readUint32(),this.component_index=[],this.component_bit_depth_minus_one=[],this.component_format=[],this.component_align_size=[];e<this.component_count;e++)this.component_index.push(t.readUint16()),this.component_bit_depth_minus_one.push(t.readUint8()),this.component_format.push(t.readUint8()),this.component_align_size.push(t.readUint8());this.sampling_type=t.readUint8(),this.interleave_type=t.readUint8(),this.block_size=t.readUint8();var r=t.readUint8();this.component_little_endian=r>>7&1,this.block_pad_lsb=r>>6&1,this.block_little_endian=r>>5&1,this.block_reversed=r>>4&1,this.pad_unknown=r>>3&1,this.pixel_size=t.readUint32(),this.row_align_size=t.readUint32(),this.tile_align_size=t.readUint32(),this.num_tile_cols_minus_one=t.readUint32(),this.num_tile_rows_minus_one=t.readUint32()}}),p.createFullBoxCtor("url ",function(t){1!==this.flags&&(this.location=t.readCString())}),p.createFullBoxCtor("urn ",function(t){this.name=t.readCString(),this.size-this.hdr_size-this.name.length-1>0&&(this.location=t.readCString())}),p.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,"'")}),p.createUUIDBox("d08a4f1810f34a82b6c832d8aba183d3",!0,!1,function(t){this.system_id=p.parseHex16(t);var e=t.readUint32();e>0&&(this.data=t.readUint8Array(e))}),p.createUUIDBox("a2394f525a9b4f14a2446c427c648df4",!0,!1),p.createUUIDBox("8974dbce7be74c5184f97148f9882554",!0,!1,function(t){this.default_AlgorithmID=t.readUint24(),this.default_IV_size=t.readUint8(),this.default_KID=p.parseHex16(t)}),p.createUUIDBox("d4807ef2ca3946958e5426cb9e46a79f",!0,!1,function(t){this.fragment_count=t.readUint8(),this.entries=[];for(var e=0;e<this.fragment_count;e++){var r={},s=0,a=0;1===this.version?(s=t.readUint64(),a=t.readUint64()):(s=t.readUint32(),a=t.readUint32()),r.absolute_time=s,r.absolute_duration=a,this.entries.push(r)}}),p.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())}),p.createFullBoxCtor("vmhd",function(t){this.graphicsmode=t.readUint16(),this.opcolor=t.readUint16Array(3)}),p.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.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)}),p.createBoxCtor("vttC",function(t){this.text=t.readString(this.size-this.hdr_size)}),p.createFullBoxCtor("vvcC",function(t){var e,r,s={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(s.stream_read_1_bytes(t),s.extract_bits(5),this.lengthSizeMinusOne=s.extract_bits(2),this.ptl_present_flag=s.extract_bits(1),this.ptl_present_flag){if(s.stream_read_2_bytes(t),this.ols_idx=s.extract_bits(9),this.num_sublayers=s.extract_bits(3),this.constant_frame_rate=s.extract_bits(2),this.chroma_format_idc=s.extract_bits(2),s.stream_read_1_bytes(t),this.bit_depth_minus8=s.extract_bits(3),s.extract_bits(5),s.stream_read_2_bytes(t),s.extract_bits(2),this.num_bytes_constraint_info=s.extract_bits(6),this.general_profile_idc=s.extract_bits(7),this.general_tier_flag=s.extract_bits(1),this.general_level_idc=t.readUint8(),s.stream_read_1_bytes(t),this.ptl_frame_only_constraint_flag=s.extract_bits(1),this.ptl_multilayer_enabled_flag=s.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 a=s.extract_bits(6);s.stream_read_1_bytes(t);var n=s.extract_bits(2);this.general_constraint_info[e]=a<<2|n}this.general_constraint_info[this.num_bytes_constraint_info-1]=s.extract_bits(6)}else s.extract_bits(6);if(this.num_sublayers>1){for(s.stream_read_1_bytes(t),this.ptl_sublayer_present_mask=0,r=this.num_sublayers-2;r>=0;--r){var o=s.extract_bits(1);this.ptl_sublayer_present_mask|=o<<r}for(r=this.num_sublayers;r<=8&&this.num_sublayers>1;++r)s.extract_bits(1);for(this.sublayer_level_idc=[],r=this.num_sublayers-2;r>=0;--r)this.ptl_sublayer_present_mask&1<<r&&(this.sublayer_level_idc[r]=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 l=t.readUint8();for(e=0;e<l;e++){var h=[];this.nalu_arrays.push(h),s.stream_read_1_bytes(t),h.completeness=s.extract_bits(1),s.extract_bits(2),h.nalu_type=s.extract_bits(5);var d=1;for(13!=h.nalu_type&&12!=h.nalu_type&&(d=t.readUint16()),r=0;r<d;r++){var u=t.readUint16();h.push({data:t.readUint8Array(u),length:u})}}}),p.createFullBoxCtor("vvnC",function(t){var e=strm.readUint8();this.lengthSizeMinusOne=3&e}),p.SampleEntry.prototype.isVideo=function(){return!1},p.SampleEntry.prototype.isAudio=function(){return!1},p.SampleEntry.prototype.isSubtitle=function(){return!1},p.SampleEntry.prototype.isMetadata=function(){return!1},p.SampleEntry.prototype.isHint=function(){return!1},p.SampleEntry.prototype.getCodec=function(){return this.type.replace(".","")},p.SampleEntry.prototype.getWidth=function(){return""},p.SampleEntry.prototype.getHeight=function(){return""},p.SampleEntry.prototype.getChannelCount=function(){return""},p.SampleEntry.prototype.getSampleRate=function(){return""},p.SampleEntry.prototype.getSampleSize=function(){return""},p.VisualSampleEntry.prototype.isVideo=function(){return!0},p.VisualSampleEntry.prototype.getWidth=function(){return this.width},p.VisualSampleEntry.prototype.getHeight=function(){return this.height},p.AudioSampleEntry.prototype.isAudio=function(){return!0},p.AudioSampleEntry.prototype.getChannelCount=function(){return this.channel_count},p.AudioSampleEntry.prototype.getSampleRate=function(){return this.samplerate},p.AudioSampleEntry.prototype.getSampleSize=function(){return this.samplesize},p.SubtitleSampleEntry.prototype.isSubtitle=function(){return!0},p.MetadataSampleEntry.prototype.isMetadata=function(){return!0},p.decimalToHex=function(t,e){var r=Number(t).toString(16);for(e=null==e?e=2:e;r.length<e;)r="0"+r;return r},p.avc1SampleEntry.prototype.getCodec=p.avc2SampleEntry.prototype.getCodec=p.avc3SampleEntry.prototype.getCodec=p.avc4SampleEntry.prototype.getCodec=function(){var t=p.SampleEntry.prototype.getCodec.call(this);return this.avcC?t+"."+p.decimalToHex(this.avcC.AVCProfileIndication)+p.decimalToHex(this.avcC.profile_compatibility)+p.decimalToHex(this.avcC.AVCLevelIndication):t},p.hev1SampleEntry.prototype.getCodec=p.hvc1SampleEntry.prototype.getCodec=function(){var t,e=p.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 r=this.hvcC.general_profile_compatibility,s=0;for(t=0;t<32&&(s|=1&r,31!=t);t++)s<<=1,r>>=1;e+=p.decimalToHex(s,0),e+=".",0===this.hvcC.general_tier_flag?e+="L":e+="H",e+=this.hvcC.general_level_idc;var a=!1,n="";for(t=5;t>=0;t--)(this.hvcC.general_constraint_indicator[t]||a)&&(n="."+p.decimalToHex(this.hvcC.general_constraint_indicator[t],0)+n,a=!0);e+=n}return e},p.vvc1SampleEntry.prototype.getCodec=p.vvi1SampleEntry.prototype.getCodec=function(){var t=p.SampleEntry.prototype.getCodec.call(this);if(this.vvcC){t+="."+this.vvcC.general_profile_idc,this.vvcC.general_tier_flag?t+=".H":t+=".L",t+=this.vvcC.general_level_idc;var e="";if(this.vvcC.general_constraint_info){var r,s,a,n=[];for(s=0,r=this.vvcC.ptl_frame_only_constraint<<7|this.vvcC.ptl_multilayer_enabled<<6;s<this.vvcC.general_constraint_info.length;++s)r|=this.vvcC.general_constraint_info[s]>>2&63,n.push(r),r&&(a=s),r=this.vvcC.general_constraint_info[s]>>2&3;if(void 0===a)e=".CA";else{e=".C";var o="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",l=0,h=0;for(s=0;s<=a;++s)for(l=l<<8|n[s],h+=8;h>=5;)e+=o[l>>h-5&31],h-=5,l&=(1<<h)-1;h&&(l<<=5-h,e+=o[31&l])}}t+=e}return t},p.mp4aSampleEntry.prototype.getCodec=function(){var t=p.SampleEntry.prototype.getCodec.call(this);if(!this.esds||!this.esds.esd)return t;var e=this.esds.esd.getOTI(),r=this.esds.esd.getAudioConfig();return t+"."+p.decimalToHex(e)+(r?"."+r:"")},p.stxtSampleEntry.prototype.getCodec=function(){var t=p.SampleEntry.prototype.getCodec.call(this);return this.mime_format?t+"."+this.mime_format:t},p.vp08SampleEntry.prototype.getCodec=p.vp09SampleEntry.prototype.getCodec=function(){var t=p.SampleEntry.prototype.getCodec.call(this),e=this.vpcC.level;0==e&&(e="00");var r=this.vpcC.bitDepth;return 8==r&&(r="08"),t+".0"+this.vpcC.profile+"."+e+"."+r},p.av01SampleEntry.prototype.getCodec=function(){var t,e=p.SampleEntry.prototype.getCodec.call(this),r=this.av1C.seq_level_idx_0;return r<10&&(r="0"+r),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+"."+r+(this.av1C.seq_tier_0?"H":"M")+"."+t},p.Box.prototype.writeHeader=function(t,e){this.size+=8,this.size>0x100000000&&(this.size+=8),"uuid"===this.type&&(this.size+=16),o.debug("BoxWriter","Writing box "+this.type+" of size: "+this.size+" at position "+t.getPosition()+(e||"")),this.size>0x100000000?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>0x100000000&&t.writeUint64(this.size)},p.FullBox.prototype.writeHeader=function(t){this.size+=4,p.Box.prototype.writeHeader.call(this,t," v="+this.version+" f="+this.flags),t.writeUint8(this.version),t.writeUint24(this.flags)},p.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))},p.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);o.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),t.adjustUint32(this.sizePosition,this.size)},p.TrackReferenceTypeBox.prototype.write=function(t){this.size=4*this.track_ids.length,this.writeHeader(t),t.writeUint32Array(this.track_ids)},p.avcCBox.prototype.write=function(t){var e;for(e=0,this.size=7;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)},p.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])},p.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)},p.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])},p.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;o.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),t.adjustUint32(this.sizePosition,this.size)},p.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)},p.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 r=this.entries[e];t.writeUint32(r.segment_duration),t.writeInt32(r.media_time),t.writeInt16(r.media_rate_integer),t.writeInt16(r.media_rate_fraction)}},p.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)},p.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)},p.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)},p.hvcCBox.prototype.write=function(t){var e,r;for(e=0,this.size=23;e<this.nalu_arrays.length;e++)for(this.size+=3,r=0;r<this.nalu_arrays[e].length;r++)this.size+=2+this.nalu_arrays[e][r].data.length;for(this.writeHeader(t),t.writeUint8(this.configurationVersion),t.writeUint8((this.general_profile_space<<6)+(this.general_tier_flag<<5)+this.general_profile_idc),t.writeUint32(this.general_profile_compatibility),t.writeUint8Array(this.general_constraint_indicator),t.writeUint8(this.general_level_idc),t.writeUint16(this.min_spatial_segmentation_idc+0xf000000),t.writeUint8(this.parallelismType+252),t.writeUint8(this.chroma_format_idc+252),t.writeUint8(this.bit_depth_luma_minus8+248),t.writeUint8(this.bit_depth_chroma_minus8+248),t.writeUint16(this.avgFrameRate),t.writeUint8((this.constantFrameRate<<6)+(this.numTemporalLayers<<3)+(this.temporalIdNested<<2)+this.lengthSizeMinusOne),t.writeUint8(this.nalu_arrays.length),e=0;e<this.nalu_arrays.length;e++)for(t.writeUint8((this.nalu_arrays[e].completeness<<7)+this.nalu_arrays[e].nalu_type),t.writeUint16(this.nalu_arrays[e].length),r=0;r<this.nalu_arrays[e].length;r++)t.writeUint16(this.nalu_arrays[e][r].data.length),t.writeUint8Array(this.nalu_arrays[e][r].data)},p.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)},p.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)},p.mehdBox.prototype.write=function(t){this.version=0,this.flags=0,this.size=4,this.writeHeader(t),t.writeUint32(this.fragment_duration)},p.mfhdBox.prototype.write=function(t){this.version=0,this.flags=0,this.size=4,this.writeHeader(t),t.writeUint32(this.sequence_number)},p.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)},p.SampleEntry.prototype.writeHeader=function(t){this.size=8,p.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)},p.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;o.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),t.adjustUint32(this.sizePosition,this.size)},p.SampleEntry.prototype.write=function(t){this.writeHeader(t),t.writeUint8Array(this.data),this.size+=this.data.length,o.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),t.adjustUint32(this.sizePosition,this.size)},p.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)},p.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)},p.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)},p.SampleGroupEntry.prototype.write=function(t){t.writeUint8Array(this.data)},p.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 r=this.entries[e];t.writeInt32(r.sample_count),t.writeInt32(r.group_description_index)}},p.sgpdBox.prototype.write=function(t){var e,r;for(e=0,this.flags=0,this.size=12;e<this.entries.length;e++)r=this.entries[e],1===this.version&&(0===this.default_length&&(this.size+=4),this.size+=r.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++)r=this.entries[e],1===this.version&&0===this.default_length&&t.writeUint32(r.description_length),r.write(t)},p.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 r=this.references[e];t.writeUint32(r.reference_type<<31|r.referenced_size),t.writeUint32(r.subsegment_duration),t.writeUint32(r.starts_with_SAP<<31|r.SAP_type<<28|r.SAP_delta_time)}},p.smhdBox.prototype.write=function(t){this.version=0,this.flags=1,this.size=4,this.writeHeader(t),t.writeUint16(this.balance),t.writeUint16(0)},p.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)},p.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])},p.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;o.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),t.adjustUint32(this.sizePosition,this.size)},p.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])},p.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)},p.stszBox.prototype.write=function(t){var e,r=!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]){r=!1;break}else e++;else r=!1;this.size=8,r||(this.size+=4*this.sample_sizes.length),this.writeHeader(t),r?t.writeUint32(this.sample_sizes[0]):t.writeUint32(0),t.writeUint32(this.sample_sizes.length),r||t.writeUint32Array(this.sample_sizes)},p.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])},p.tfdtBox.prototype.write=function(t){this.version=+(this.baseMediaDecodeTime>0xffffffff),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)},p.tfhdBox.prototype.write=function(t){this.version=0,this.size=4,this.flags&p.TFHD_FLAG_BASE_DATA_OFFSET&&(this.size+=8),this.flags&p.TFHD_FLAG_SAMPLE_DESC&&(this.size+=4),this.flags&p.TFHD_FLAG_SAMPLE_DUR&&(this.size+=4),this.flags&p.TFHD_FLAG_SAMPLE_SIZE&&(this.size+=4),this.flags&p.TFHD_FLAG_SAMPLE_FLAGS&&(this.size+=4),this.writeHeader(t),t.writeUint32(this.track_id),this.flags&p.TFHD_FLAG_BASE_DATA_OFFSET&&t.writeUint64(this.base_data_offset),this.flags&p.TFHD_FLAG_SAMPLE_DESC&&t.writeUint32(this.default_sample_description_index),this.flags&p.TFHD_FLAG_SAMPLE_DUR&&t.writeUint32(this.default_sample_duration),this.flags&p.TFHD_FLAG_SAMPLE_SIZE&&t.writeUint32(this.default_sample_size),this.flags&p.TFHD_FLAG_SAMPLE_FLAGS&&t.writeUint32(this.default_sample_flags)},p.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)},p.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)},p.trunBox.prototype.write=function(t){this.version=0,this.size=4,this.flags&p.TRUN_FLAGS_DATA_OFFSET&&(this.size+=4),this.flags&p.TRUN_FLAGS_FIRST_FLAG&&(this.size+=4),this.flags&p.TRUN_FLAGS_DURATION&&(this.size+=4*this.sample_duration.length),this.flags&p.TRUN_FLAGS_SIZE&&(this.size+=4*this.sample_size.length),this.flags&p.TRUN_FLAGS_FLAGS&&(this.size+=4*this.sample_flags.length),this.flags&p.TRUN_FLAGS_CTS_OFFSET&&(this.size+=4*this.sample_composition_time_offset.length),this.writeHeader(t),t.writeUint32(this.sample_count),this.flags&p.TRUN_FLAGS_DATA_OFFSET&&(this.data_offset_position=t.getPosition(),t.writeInt32(this.data_offset)),this.flags&p.TRUN_FLAGS_FIRST_FLAG&&t.writeUint32(this.first_sample_flags);for(var e=0;e<this.sample_count;e++)this.flags&p.TRUN_FLAGS_DURATION&&t.writeUint32(this.sample_duration[e]),this.flags&p.TRUN_FLAGS_SIZE&&t.writeUint32(this.sample_size[e]),this.flags&p.TRUN_FLAGS_FLAGS&&t.writeUint32(this.sample_flags[e]),this.flags&p.TRUN_FLAGS_CTS_OFFSET&&(0===this.version?t.writeUint32(this.sample_composition_time_offset[e]):t.writeInt32(this.sample_composition_time_offset[e]))},p["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)},p["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)},p.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)},p.cttsBox.prototype.unpack=function(t){var e,r,s;for(e=0,s=0;e<this.sample_counts.length;e++)for(r=0;r<this.sample_counts[e];r++)t[s].pts=t[s].dts+this.sample_offsets[e],s++},p.sttsBox.prototype.unpack=function(t){var e,r,s;for(e=0,s=0;e<this.sample_counts.length;e++)for(r=0;r<this.sample_counts[e];r++)0===s?t[s].dts=0:t[s].dts=t[s-1].dts+this.sample_deltas[e],s++},p.stcoBox.prototype.unpack=function(t){var e;for(e=0;e<this.chunk_offsets.length;e++)t[e].offset=this.chunk_offsets[e]},p.stscBox.prototype.unpack=function(t){var e,r,s,a,n;for(e=0,a=0,n=0;e<this.first_chunk.length;e++)for(r=0;r<(e+1<this.first_chunk.length?this.first_chunk[e+1]:1/0);r++)for(n++,s=0;s<this.samples_per_chunk[e];s++){if(!t[a])return;t[a].description_index=this.sample_description_index[e],t[a].chunk_index=n,a++}},p.stszBox.prototype.unpack=function(t){var e;for(e=0;e<this.sample_sizes.length;e++)t[e].size=this.sample_sizes[e]},p.DIFF_BOXES_PROP_NAMES=["boxes","entries","references","subsamples","items","item_infos","extents","associations","subsegments","ranges","seekLists","seekPoints","esd","levels"],p.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"],p.boxEqualFields=function(t,e){var r;if(t&&!e)return!1;for(r in t)if(p.DIFF_BOXES_PROP_NAMES.indexOf(r)>-1)continue;else if(t[r]instanceof p.Box||e[r]instanceof p.Box)continue;else if(void 0===t[r]||void 0===e[r])continue;else if("function"==typeof t[r]||"function"==typeof e[r])continue;else if(t.subBoxNames&&t.subBoxNames.indexOf(r.slice(0,4))>-1||e.subBoxNames&&e.subBoxNames.indexOf(r.slice(0,4))>-1)continue;else if("data"===r||"start"===r||"size"===r||"creation_time"===r||"modification_time"===r)continue;else if(p.DIFF_PRIMITIVE_ARRAY_PROP_NAMES.indexOf(r)>-1)continue;else if(t[r]!==e[r])return!1;return!0},p.boxEqual=function(t,e){if(!p.boxEqualFields(t,e))return!1;for(var r=0;r<p.DIFF_BOXES_PROP_NAMES.length;r++){var s=p.DIFF_BOXES_PROP_NAMES[r];if(t[s]&&e[s]&&!p.boxEqual(t[s],e[s]))return!1}return!0};var m=function(){};m.prototype.parseSample=function(t){var e,r,s=new l(t.buffer);for(e=[];!s.isEos();)(r=p.parseOneBox(s,!1)).code===p.OK&&"vttc"===r.box.type&&e.push(r.box);return e},m.prototype.getText=function(t,e,r){function s(t,e,r){return r=r||"0",(t+="").length>=e?t:Array(e-t.length+1).join(r)+t}function a(t){var e=Math.floor(t/3600),r=Math.floor((t-3600*e)/60),a=Math.floor(t-3600*e-60*r),n=Math.floor((t-3600*e-60*r-a)*1e3);return""+s(e,2)+":"+s(r,2)+":"+s(a,2)+"."+s(n,3)}for(var n=this.parseSample(r),o="",l=0;l<n.length;l++){var h=n[l];o+=a(t)+" --\x3e "+a(e)+"\r\n",o+=h.payl.text}return o};var _=function(){};_.prototype.parseSample=function(t){var e,r={};r.resources=[];var s=new l(t.data.buffer);if(t.subsamples&&0!==t.subsamples.length){if(r.documentString=s.readString(t.subsamples[0].size),t.subsamples.length>1)for(e=1;e<t.subsamples.length;e++)r.resources[e]=s.readUint8Array(t.subsamples[e].size)}else r.documentString=s.readString(t.data.length);return"undefined"!=typeof DOMParser&&(r.document=new DOMParser().parseFromString(r.documentString,"application/xml")),r};var g=function(){};g.prototype.parseSample=function(t){return new l(t.data.buffer).readString(t.data.length)},g.prototype.parseConfig=function(t){var e=new l(t.buffer);return e.readUint32(),e.readCString()},r.XMLSubtitlein4Parser=_,r.Textin4Parser=g;var y=function(t){this.stream=t||new d,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};y.prototype.setSegmentOptions=function(t,e,r){var s=this.getTrackById(t);if(s){var a={};this.fragmentedTracks.push(a),a.id=t,a.user=e,a.trak=s,s.nextSample=0,a.segmentStream=null,a.nb_samples=1e3,a.rapAlignement=!0,r&&(r.nbSamples&&(a.nb_samples=r.nbSamples),r.rapAlignement&&(a.rapAlignement=r.rapAlignement))}},y.prototype.unsetSegmentOptions=function(t){for(var e=-1,r=0;r<this.fragmentedTracks.length;r++)this.fragmentedTracks[r].id==t&&(e=r);e>-1&&this.fragmentedTracks.splice(e,1)},y.prototype.setExtractionOptions=function(t,e,r){var s=this.getTrackById(t);if(s){var a={};this.extractedTracks.push(a),a.id=t,a.user=e,a.trak=s,s.nextSample=0,a.nb_samples=1e3,a.samples=[],r&&r.nbSamples&&(a.nb_samples=r.nbSamples)}},y.prototype.unsetExtractionOptions=function(t){for(var e=-1,r=0;r<this.extractedTracks.length;r++)this.extractedTracks[r].id==t&&(e=r);e>-1&&this.extractedTracks.splice(e,1)},y.prototype.parse=function(){var t,e,r;if(!this.restoreParsePosition||this.restoreParsePosition())for(;;)if(this.hasIncompleteMdat&&this.hasIncompleteMdat())if(this.processIncompleteMdat())continue;else return;else{if(this.saveParsePosition&&this.saveParsePosition(),(t=p.parseOneBox(this.stream,!1)).code===p.ERR_NOT_ENOUGH_DATA)if(!this.processIncompleteBox)return;else if(this.processIncompleteBox(t))continue;else return;switch(r="uuid"!==(e=t.box).type?e.type:e.uuid,this.boxes.push(e),r){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[r]&&o.warn("ISOFile","Duplicate Box of type: "+r+", overriding previous occurrence"),this[r]=e}this.updateUsedBytes&&this.updateUsedBytes(e,t)}},y.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?(o.warn("ISOFile","Ignoring empty buffer (fileStart: "+t.fileStart+")"),this.stream.logBufferLevel(),!1):(o.info("ISOFile","Processing buffer (fileStart: "+t.fileStart+")"),t.usedBytes=0,this.stream.insertBuffer(t),this.stream.logBufferLevel(),!!this.stream.initialized()||(o.warn("ISOFile","Not ready to start parsing"),!1))},y.prototype.appendBuffer=function(t,e){var r;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?(r=this.nextSeekPosition,this.nextSeekPosition=void 0):r=this.nextParsePosition,this.stream.getEndFilePositionAfter&&(r=this.stream.getEndFilePositionAfter(r))):r=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&&(o.info("ISOFile","Done processing buffer (fileStart: "+t.fileStart+") - next buffer to fetch should have a fileStart position of "+r),this.stream.logBufferLevel(),this.stream.cleanBuffers(),this.stream.logBufferLevel(!0),o.info("ISOFile","Sample data size in memory: "+this.getAllocatedSampleDataSize())),r},y.prototype.getInfo=function(){var t,e,r,s,a,n,o={},l=new Date("1904-01-01T00:00:00Z").getTime();if(this.moov)for(o.hasMoov=!0,o.duration=this.moov.mvhd.duration,o.timescale=this.moov.mvhd.timescale,o.isFragmented=null!=this.moov.mvex,o.isFragmented&&this.moov.mvex.mehd&&(o.fragment_duration=this.moov.mvex.mehd.fragment_duration),o.isProgressive=this.isProgressive,o.hasIOD=null!=this.moov.iods,o.brands=[],o.brands.push(this.ftyp.major_brand),o.brands=o.brands.concat(this.ftyp.compatible_brands),o.created=new Date(l+1e3*this.moov.mvhd.creation_time),o.modified=new Date(l+1e3*this.moov.mvhd.modification_time),o.tracks=[],o.audioTracks=[],o.videoTracks=[],o.subtitleTracks=[],o.metadataTracks=[],o.hintTracks=[],o.otherTracks=[],t=0;t<this.moov.traks.length;t++){if(n=(r=this.moov.traks[t]).mdia.minf.stbl.stsd.entries[0],s={},o.tracks.push(s),s.id=r.tkhd.track_id,s.name=r.mdia.hdlr.name,s.references=[],r.tref)for(e=0;e<r.tref.boxes.length;e++)a={},s.references.push(a),a.type=r.tref.boxes[e].type,a.track_ids=r.tref.boxes[e].track_ids;r.edts&&(s.edits=r.edts.elst.entries),s.created=new Date(l+1e3*r.tkhd.creation_time),s.modified=new Date(l+1e3*r.tkhd.modification_time),s.movie_duration=r.tkhd.duration,s.movie_timescale=o.timescale,s.layer=r.tkhd.layer,s.alternate_group=r.tkhd.alternate_group,s.volume=r.tkhd.volume,s.matrix=r.tkhd.matrix,s.track_width=r.tkhd.width/65536,s.track_height=r.tkhd.height/65536,s.timescale=r.mdia.mdhd.timescale,s.cts_shift=r.mdia.minf.stbl.cslg,s.duration=r.mdia.mdhd.duration,s.samples_duration=r.samples_duration,s.codec=n.getCodec(),s.kind=r.udta&&r.udta.kinds.length?r.udta.kinds[0]:{schemeURI:"",value:""},s.language=r.mdia.elng?r.mdia.elng.extended_language:r.mdia.mdhd.languageString,s.nb_samples=r.samples.length,s.size=r.samples_size,s.bitrate=8*s.size*s.timescale/s.samples_duration,n.isAudio()?(s.type="audio",o.audioTracks.push(s),s.audio={},s.audio.sample_rate=n.getSampleRate(),s.audio.channel_count=n.getChannelCount(),s.audio.sample_size=n.getSampleSize()):n.isVideo()?(s.type="video",o.videoTracks.push(s),s.video={},s.video.width=n.getWidth(),s.video.height=n.getHeight()):n.isSubtitle()?(s.type="subtitles",o.subtitleTracks.push(s)):n.isHint()?(s.type="metadata",o.hintTracks.push(s)):n.isMetadata()?(s.type="metadata",o.metadataTracks.push(s)):(s.type="metadata",o.otherTracks.push(s))}else o.hasMoov=!1;if(o.mime="",o.hasMoov&&o.tracks){for(o.videoTracks&&o.videoTracks.length>0?o.mime+='video/mp4; codecs="':o.audioTracks&&o.audioTracks.length>0?o.mime+='audio/mp4; codecs="':o.mime+='application/mp4; codecs="',t=0;t<o.tracks.length;t++)0!==t&&(o.mime+=","),o.mime+=o.tracks[t].codec;o.mime+='"; profiles="',o.mime+=this.ftyp.compatible_brands.join(),o.mime+='"'}return o},y.prototype.setNextSeekPositionFromSample=function(t){t&&(this.nextSeekPosition?this.nextSeekPosition=Math.min(t.offset+t.alreadyRead,this.nextSeekPosition):this.nextSeekPosition=t.offset+t.alreadyRead)},y.prototype.processSamples=function(t){if(this.sampleProcessingStarted){if(this.isFragmentationInitialized&&null!==this.onSegment)for(e=0;e<this.fragmentedTracks.length;e++){var e,r,s=this.fragmentedTracks[e];for(r=s.trak;r.nextSample<r.samples.length&&this.sampleProcessingStarted;){o.debug("ISOFile","Creating media fragment on track #"+s.id+" for sample "+r.nextSample);var a=this.createFragment(s.id,r.nextSample,s.segmentStream);if(a)s.segmentStream=a,r.nextSample++;else break;if((r.nextSample%s.nb_samples==0||t||r.nextSample>=r.samples.length)&&(o.info("ISOFile","Sending fragmented data on track #"+s.id+" for samples ["+Math.max(0,r.nextSample-s.nb_samples)+","+(r.nextSample-1)+"]"),o.info("ISOFile","Sample data size in memory: "+this.getAllocatedSampleDataSize()),this.onSegment&&this.onSegment(s.id,s.user,s.segmentStream.buffer,r.nextSample,t||r.nextSample>=r.samples.length),s.segmentStream=null,s!==this.fragmentedTracks[e]))break}}if(null!==this.onSamples)for(e=0;e<this.extractedTracks.length;e++){var n=this.extractedTracks[e];for(r=n.trak;r.nextSample<r.samples.length&&this.sampleProcessingStarted;){o.debug("ISOFile","Exporting on track #"+n.id+" sample #"+r.nextSample);var l=this.getSample(r,r.nextSample);if(l)r.nextSample++,n.samples.push(l);else{this.setNextSeekPositionFromSample(r.samples[r.nextSample]);break}if((r.nextSample%n.nb_samples==0||r.nextSample>=r.samples.length)&&(o.debug("ISOFile","Sending samples on track #"+n.id+" for sample "+r.nextSample),this.onSamples&&this.onSamples(n.id,n.user,n.samples),n.samples=[],n!==this.extractedTracks[e]))break}}}},y.prototype.getBox=function(t){var e=this.getBoxes(t,!0);return e.length?e[0]:null},y.prototype.getBoxes=function(t,e){var r=[];return y._sweep.call(this,t,r,e),r},y._sweep=function(t,e,r){for(var s in this.type&&this.type==t&&e.push(this),this.boxes){if(e.length&&r)return;y._sweep.call(this.boxes[s],t,e,r)}},y.prototype.getTrackSamplesInfo=function(t){var e=this.getTrackById(t);return e?e.samples:void 0},y.prototype.getTrackSample=function(t,e){var r=this.getTrackById(t);return this.getSample(r,e)},y.prototype.releaseUsedSamples=function(t,e){var r=0,s=this.getTrackById(t);s.lastValidSample||(s.lastValidSample=0);for(var a=s.lastValidSample;a<e;a++)r+=this.releaseSample(s,a);o.info("ISOFile","Track #"+t+" released samples up to "+e+" (released size: "+r+", remaining: "+this.samplesDataSize+")"),s.lastValidSample=e},y.prototype.start=function(){this.sampleProcessingStarted=!0,this.processSamples(!1)},y.prototype.stop=function(){this.sampleProcessingStarted=!1},y.prototype.flush=function(){o.info("ISOFile","Flushing remaining samples"),this.updateSampleLists(),this.processSamples(!0),this.stream.cleanBuffers(),this.stream.logBufferLevel(!0)},y.prototype.seekTrack=function(t,e,r){var s,a,n,l=1/0,h=0,d=0;if(0===r.samples.length)return o.info("ISOFile","No sample in track, cannot seek! Using time "+o.getDurationString(0,1)+" and offset: 0"),{offset:0,time:0};for(s=0;s<r.samples.length;s++){if(a=r.samples[s],0===s)d=0,n=a.timescale;else if(a.cts>t*a.timescale){d=s-1;break}e&&a.is_sync&&(h=s)}for(e&&(d=h),t=r.samples[d].cts,r.nextSample=d;r.samples[d].alreadyRead===r.samples[d].size&&r.samples[d+1];)d++;return l=r.samples[d].offset+r.samples[d].alreadyRead,o.info("ISOFile","Seeking to "+(e?"RAP":"")+" sample #"+r.nextSample+" on track "+r.tkhd.track_id+", time "+o.getDurationString(t,n)+" and offset: "+l),{offset:l,time:t/n}},y.prototype.getTrackDuration=function(t){var e;return t.samples?((e=t.samples[t.samples.length-1]).cts+e.duration)/e.timescale:1/0},y.prototype.seek=function(t,e){var r,s,a,n=this.moov,l={offset:1/0,time:1/0};if(this.moov){for(a=0;a<n.traks.length;a++)r=n.traks[a],!(t>this.getTrackDuration(r))&&((s=this.seekTrack(t,e,r)).offset<l.offset&&(l.offset=s.offset),s.time<l.time&&(l.time=s.time));return o.info("ISOFile","Seeking at time "+o.getDurationString(l.time,1)+" needs a buffer with a fileStart position of "+l.offset),l.offset===1/0?l={offset:this.nextParsePosition,time:0}:l.offset=this.stream.getEndFilePositionAfter(l.offset),o.info("ISOFile","Adjusted seek position (after checking data already in buffer): "+l.offset),l}throw"Cannot seek: moov not received!"},y.prototype.equal=function(t){for(var e=0;e<this.boxes.length&&e<t.boxes.length;){var r=this.boxes[e],s=t.boxes[e];if(!p.boxEqual(r,s))return!1;e++}return!0},r.ISOFile=y,y.prototype.lastBoxStartPosition=0,y.prototype.parsingMdat=null,y.prototype.nextParsePosition=0,y.prototype.discardMdatData=!1,y.prototype.processIncompleteBox=function(t){var e;return"mdat"===t.type?(e=new p[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)},y.prototype.hasIncompleteMdat=function(){return null!==this.parsingMdat},y.prototype.processIncompleteMdat=function(){var t;return(t=this.parsingMdat,this.stream.seek(t.start+t.size,!1,this.discardMdatData))?(o.debug("ISOFile","Found 'mdat' end in buffered data"),this.parsingMdat=null,!0):(this.nextParsePosition=this.stream.findEndContiguousBuf(),!1)},y.prototype.restoreParsePosition=function(){return this.stream.seek(this.lastBoxStartPosition,!0,this.discardMdatData)},y.prototype.saveParsePosition=function(){this.lastBoxStartPosition=this.stream.getPosition()},y.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))},y.prototype.add=p.Box.prototype.add,y.prototype.addBox=p.Box.prototype.addBox,y.prototype.init=function(t){var e=t||{};this.add("ftyp").set("major_brand",e.brands&&e.brands[0]||"iso4").set("minor_version",0).set("compatible_brands",e.brands||["iso4"]);var r=this.add("moov");return r.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",256*!e.width).set("matrix",[65536,0,0,0,65536,0,0,0,0x40000000]).set("next_track_id",1),r.add("mvex"),this},y.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 r=this.moov.add("trak");this.moov.mvhd.next_track_id=e.id+1,r.add("tkhd").set("flags",p.TKHD_FLAG_ENABLED|p.TKHD_FLAG_IN_MOVIE|p.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",[65536,0,0,0,65536,0,0,0,0x40000000]).set("width",e.width<<16).set("height",e.height<<16);var s=r.add("mdia");s.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"),s.add("hdlr").set("handler",e.hdlr||"vide").set("name",e.name||"Track created with MP4Box.js"),s.add("elng").set("extended_language",e.language||"fr-FR");var a=s.add("minf");if(void 0!==p[e.type+"SampleEntry"]){var n=new p[e.type+"SampleEntry"];n.data_reference_index=1;var o="";for(var h in p.sampleEntryCodes)for(var d=p.sampleEntryCodes[h],u=0;u<d.length;u++)if(d.indexOf(e.type)>-1){o=h;break}switch(o){case"Visual":if(a.add("vmhd").set("graphicsmode",0).set("opcolor",[0,0,0]),n.set("width",e.width).set("height",e.height).set("horizresolution",4718592).set("vertresolution",4718592).set("frame_count",1).set("compressorname",e.type+" Compressor").set("depth",24),e.avcDecoderConfigRecord){var c=new p.avcCBox;c.parse(new l(e.avcDecoderConfigRecord)),n.addBox(c)}else if(e.hevcDecoderConfigRecord){var f=new p.hvcCBox;f.parse(new l(e.hevcDecoderConfigRecord)),n.addBox(f)}break;case"Audio":a.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":a.add("hmhd");break;case"Subtitle":a.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:a.add("nmhd")}e.description&&n.addBox(e.description),e.description_boxes&&e.description_boxes.forEach(function(t){n.addBox(t)}),a.add("dinf").add("dref").addEntry(new p["url Box"]().set("flags",1));var m=a.add("stbl");return m.add("stsd").addEntry(n),m.add("stts").set("sample_counts",[]).set("sample_deltas",[]),m.add("stsc").set("first_chunk",[]).set("samples_per_chunk",[]).set("sample_description_index",[]),m.add("stco").set("chunk_offsets",[]),m.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(r),e.id}},p.Box.prototype.computeSize=function(t){var e=t||new h;e.endianness=h.BIG_ENDIAN,this.write(e)},y.prototype.addSample=function(t,e,r){var s=r||{},a={},n=this.getTrackById(t);if(null!==n){a.number=n.samples.length,a.track_id=n.tkhd.track_id,a.timescale=n.mdia.mdhd.timescale,a.description_index=s.sample_description_index?s.sample_description_index-1:0,a.description=n.mdia.minf.stbl.stsd.entries[a.description_index],a.data=e,a.size=e.byteLength,a.alreadyRead=a.size,a.duration=s.duration||1,a.cts=s.cts||0,a.dts=s.dts||0,a.is_sync=s.is_sync||!1,a.is_leading=s.is_leading||0,a.depends_on=s.depends_on||0,a.is_depended_on=s.is_depended_on||0,a.has_redundancy=s.has_redundancy||0,a.degradation_priority=s.degradation_priority||0,a.offset=0,a.subsamples=s.subsamples,n.samples.push(a),n.samples_size+=a.size,n.samples_duration+=a.duration,void 0===n.first_dts&&(n.first_dts=s.dts),this.processSamples();var o=this.createSingleSampleMoof(a);return this.addBox(o),o.computeSize(),o.trafs[0].truns[0].data_offset=o.size+8,this.add("mdat").data=new Uint8Array(e),a}},y.prototype.createSingleSampleMoof=function(t){var e=0;e=t.is_sync?0x2000000:65536;var r=new p.moofBox;r.add("mfhd").set("sequence_number",this.nextMoofNumber),this.nextMoofNumber++;var s=r.add("traf"),a=this.getTrackById(t.track_id);return s.add("tfhd").set("track_id",t.track_id).set("flags",p.TFHD_FLAG_DEFAULT_BASE_IS_MOOF),s.add("tfdt").set("baseMediaDecodeTime",t.dts-(a.first_dts||0)),s.add("trun").set("flags",p.TRUN_FLAGS_DATA_OFFSET|p.TRUN_FLAGS_DURATION|p.TRUN_FLAGS_SIZE|p.TRUN_FLAGS_FLAGS|p.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]),r},y.prototype.lastMoofIndex=0,y.prototype.samplesDataSize=0,y.prototype.resetTables=function(){for(t=0,this.initial_duration=this.moov.mvhd.duration,this.moov.mvhd.duration=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=[],(r=e.mdia.minf.stbl.stsc).first_chunk=[],r.samples_per_chunk=[],r.sample_description_index=[],(e.mdia.minf.stbl.stsz||e.mdia.minf.stbl.stz2).sample_sizes=[],(s=e.mdia.minf.stbl.stts).sample_counts=[],s.sample_deltas=[],(a=e.mdia.minf.stbl.ctts)&&(a.sample_counts=[],a.sample_offsets=[]);var t,e,r,s,a,n=e.mdia.minf.stbl.stss,o=e.mdia.minf.stbl.boxes.indexOf(n);-1!=o&&(e.mdia.minf.stbl.boxes[o]=null)}},y.initSampleGroups=function(t,e,r,s,a){var n,o,l,h;function d(t,e,r){this.grouping_type=t,this.grouping_type_parameter=e,this.sbgp=r,this.last_sample_in_run=-1,this.entry_index=-1}for(e&&(e.sample_groups_info=[]),t.sample_groups_info||(t.sample_groups_info=[]),o=0;o<r.length;o++){for(h=r[o].grouping_type+"/"+r[o].grouping_type_parameter,l=new d(r[o].grouping_type,r[o].grouping_type_parameter,r[o]),e&&(e.sample_groups_info[h]=l),t.sample_groups_info[h]||(t.sample_groups_info[h]=l),n=0;n<s.length;n++)s[n].grouping_type===r[o].grouping_type&&(l.description=s[n],l.description.used=!0);if(a)for(n=0;n<a.length;n++)a[n].grouping_type===r[o].grouping_type&&(l.fragment_description=a[n],l.fragment_description.used=!0,l.is_fragment=!0)}if(e){if(a)for(o=0;o<a.length;o++)!a[o].used&&a[o].version>=2&&(h=a[o].grouping_type+"/0",(l=new d(a[o].grouping_type,0)).is_fragment=!0,e.sample_groups_info[h]||(e.sample_groups_info[h]=l))}else for(o=0;o<s.length;o++)!s[o].used&&s[o].version>=2&&(h=s[o].grouping_type+"/0",l=new d(s[o].grouping_type,0),t.sample_groups_info[h]||(t.sample_groups_info[h]=l))},y.setSampleGroupProperties=function(t,e,r,s){var a,n,o;for(a in e.sample_groups=[],s)e.sample_groups[a]={},e.sample_groups[a].grouping_type=s[a].grouping_type,e.sample_groups[a].grouping_type_parameter=s[a].grouping_type_parameter,r>=s[a].last_sample_in_run&&(s[a].last_sample_in_run<0&&(s[a].last_sample_in_run=0),s[a].entry_index++,s[a].entry_index<=s[a].sbgp.entries.length-1&&(s[a].last_sample_in_run+=s[a].sbgp.entries[s[a].entry_index].sample_count)),s[a].entry_index<=s[a].sbgp.entries.length-1?e.sample_groups[a].group_description_index=s[a].sbgp.entries[s[a].entry_index].group_description_index:e.sample_groups[a].group_description_index=-1,0!==e.sample_groups[a].group_description_index&&(o=s[a].fragment_description?s[a].fragment_description:s[a].description,e.sample_groups[a].group_description_index>0?(n=e.sample_groups[a].group_description_index>65535?(e.sample_groups[a].group_description_index>>16)-1:e.sample_groups[a].group_description_index-1,o&&n>=0&&(e.sample_groups[a].description=o.entries[n])):o&&o.version>=2&&o.default_group_description_index>0&&(e.sample_groups[a].description=o.entries[o.default_group_description_index-1]))},y.process_sdtp=function(t,e,r){e&&(t?(e.is_leading=t.is_leading[r],e.depends_on=t.sample_depends_on[r],e.is_depended_on=t.sample_is_depended_on[r],e.has_redundancy=t.sample_has_redundancy[r]):(e.is_leading=0,e.depends_on=0,e.is_depended_on=0,e.has_redundancy=0))},y.prototype.buildSampleLists=function(){var t,e;for(t=0;t<this.moov.traks.length;t++)e=this.moov.traks[t],this.buildTrakSampleLists(e)},y.prototype.buildTrakSampleLists=function(t){if(t.samples=[],t.samples_duration=0,t.samples_size=0,r=t.mdia.minf.stbl.stco||t.mdia.minf.stbl.co64,s=t.mdia.minf.stbl.stsc,a=t.mdia.minf.stbl.stsz||t.mdia.minf.stbl.stz2,n=t.mdia.minf.stbl.stts,o=t.mdia.minf.stbl.ctts,l=t.mdia.minf.stbl.stss,h=t.mdia.minf.stbl.stsd,d=t.mdia.minf.stbl.subs,c=t.mdia.minf.stbl.stdp,u=t.mdia.minf.stbl.sbgps,p=t.mdia.minf.stbl.sgpds,b=-1,v=-1,S=-1,x=-1,U=0,E=0,A=0,y.initSampleGroups(t,null,u,p),void 0!==a){for(e=0;e<a.sample_sizes.length;e++){var e,r,s,a,n,o,l,h,d,u,p,c,f,m,_,g,w,b,v,S,x,U,E,A,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=a.sample_sizes[e],t.samples_size+=C.size,0===e?(f=0,C.chunk_index=m=1,C.chunk_run_index=f,w=s.samples_per_chunk[f],g=0,_=f+1<s.first_chunk.length?s.first_chunk[f+1]-1:1/0):e<w?(C.chunk_index=m,C.chunk_run_index=f):(C.chunk_index=++m,g=0,m<=_||(_=++f+1<s.first_chunk.length?s.first_chunk[f+1]-1:1/0),C.chunk_run_index=f,w+=s.samples_per_chunk[f]),C.description_index=s.sample_description_index[C.chunk_run_index]-1,C.description=h.entries[C.description_index],C.offset=r.chunk_offsets[C.chunk_index-1]+g,g+=C.size,e>b&&(v++,b<0&&(b=0),b+=n.sample_counts[v]),e>0?(t.samples[e-1].duration=n.sample_deltas[v],t.samples_duration+=t.samples[e-1].duration,C.dts=t.samples[e-1].dts+t.samples[e-1].duration):C.dts=0,o?(e>=S&&(x++,S<0&&(S=0),S+=o.sample_counts[x]),C.cts=t.samples[e].dts+o.sample_offsets[x]):C.cts=C.dts,l?(e==l.sample_numbers[U]-1?(C.is_sync=!0,U++):(C.is_sync=!1,C.degradation_priority=0),d&&d.entries[E].sample_delta+A==e+1&&(C.subsamples=d.entries[E].subsamples,A+=d.entries[E].sample_delta,E++)):C.is_sync=!0,y.process_sdtp(t.mdia.minf.stbl.sdtp,C,C.number),c?C.degradation_priority=c.priority[e]:C.degradation_priority=0,d&&d.entries[E].sample_delta+A==e&&(C.subsamples=d.entries[E].subsamples,A+=d.entries[E].sample_delta),(u.length>0||p.length>0)&&y.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)}},y.prototype.updateSampleLists=function(){if(void 0!==this.moov){for(;this.lastMoofIndex<this.moofs.length;)if(h=this.moofs[this.lastMoofIndex],this.lastMoofIndex++,"moof"==h.type)for(t=0;t<h.trafs.length;t++){for(d=h.trafs[t],null==(u=this.getTrackById(d.tfhd.track_id)).samples&&(u.samples=[]),c=this.getTrexById(d.tfhd.track_id),s=d.tfhd.flags&p.TFHD_FLAG_SAMPLE_DESC?d.tfhd.default_sample_description_index:c?c.default_sample_description_index:1,a=d.tfhd.flags&p.TFHD_FLAG_SAMPLE_DUR?d.tfhd.default_sample_duration:c?c.default_sample_duration:0,n=d.tfhd.flags&p.TFHD_FLAG_SAMPLE_SIZE?d.tfhd.default_sample_size:c?c.default_sample_size:0,o=d.tfhd.flags&p.TFHD_FLAG_SAMPLE_FLAGS?d.tfhd.default_sample_flags:c?c.default_sample_flags:0,d.sample_number=0,d.sbgps.length>0&&y.initSampleGroups(u,d,d.sbgps,u.mdia.minf.stbl.sgpds,d.sgpds),e=0;e<d.truns.length;e++){var t,e,r,s,a,n,o,l,h,d,u,c,f,m,_=d.truns[e];for(r=0;r<_.sample_count;r++){(f={}).moof_number=this.lastMoofIndex,f.number_in_traf=d.sample_number,d.sample_number++,f.number=u.samples.length,d.first_sample_index=u.samples.length,u.samples.push(f),f.track_id=u.tkhd.track_id,f.timescale=u.mdia.mdhd.timescale,f.description_index=s-1,f.description=u.mdia.minf.stbl.stsd.entries[f.description_index],f.size=n,_.flags&p.TRUN_FLAGS_SIZE&&(f.size=_.sample_size[r]),u.samples_size+=f.size,f.duration=a,_.flags&p.TRUN_FLAGS_DURATION&&(f.duration=_.sample_duration[r]),u.samples_duration+=f.duration,u.first_traf_merged||r>0?f.dts=u.samples[u.samples.length-2].dts+u.samples[u.samples.length-2].duration:(d.tfdt?f.dts=d.tfdt.baseMediaDecodeTime:f.dts=0,u.first_traf_merged=!0),f.cts=f.dts,_.flags&p.TRUN_FLAGS_CTS_OFFSET&&(f.cts=f.dts+_.sample_composition_time_offset[r]),m=o,_.flags&p.TRUN_FLAGS_FLAGS?m=_.sample_flags[r]:0===r&&_.flags&p.TRUN_FLAGS_FIRST_FLAG&&(m=_.first_sample_flags),f.is_sync=!(m>>16&1),f.is_leading=m>>26&3,f.depends_on=m>>24&3,f.is_depended_on=m>>22&3,f.has_redundancy=m>>20&3,f.degradation_priority=65535&m;var g=!!(d.tfhd.flags&p.TFHD_FLAG_BASE_DATA_OFFSET),w=!!(d.tfhd.flags&p.TFHD_FLAG_DEFAULT_BASE_IS_MOOF),b=!!(_.flags&p.TRUN_FLAGS_DATA_OFFSET),v=0;v=g?d.tfhd.base_data_offset:w||0===e?h.start:l,0===e&&0===r?b?f.offset=v+_.data_offset:f.offset=v:f.offset=l,l=f.offset+f.size,(d.sbgps.length>0||d.sgpds.length>0||u.mdia.minf.stbl.sbgps.length>0||u.mdia.minf.stbl.sgpds.length>0)&&y.setSampleGroupProperties(u,f,f.number_in_traf,d.sample_groups_info)}}if(d.subs){u.has_fragment_subsamples=!0;var S=d.first_sample_index;for(e=0;e<d.subs.entries.length;e++)S+=d.subs.entries[e].sample_delta,(f=u.samples[S-1]).subsamples=d.subs.entries[e].subsamples}}}},y.prototype.getSample=function(t,e){var r,s=t.samples[e];if(!this.moov)return null;if(s.data){if(s.alreadyRead==s.size)return s}else s.data=new Uint8Array(s.size),s.alreadyRead=0,this.samplesDataSize+=s.size,o.debug("ISOFile","Allocating sample #"+e+" on track #"+t.tkhd.track_id+" of size "+s.size+" (total: "+this.samplesDataSize+")");for(;;){var a=this.stream.findPosition(!0,s.offset+s.alreadyRead,!1);if(!(a>-1))return null;var n=(r=this.stream.buffers[a]).byteLength-(s.offset+s.alreadyRead-r.fileStart);if(s.size-s.alreadyRead<=n)return o.debug("ISOFile","Getting sample #"+e+" data (alreadyRead: "+s.alreadyRead+" offset: "+(s.offset+s.alreadyRead-r.fileStart)+" read size: "+(s.size-s.alreadyRead)+" full size: "+s.size+")"),h.memcpy(s.data.buffer,s.alreadyRead,r,s.offset+s.alreadyRead-r.fileStart,s.size-s.alreadyRead),r.usedBytes+=s.size-s.alreadyRead,this.stream.logBufferLevel(),s.alreadyRead=s.size,s;if(0===n)return null;o.debug("ISOFile","Getting sample #"+e+" partial data (alreadyRead: "+s.alreadyRead+" offset: "+(s.offset+s.alreadyRead-r.fileStart)+" read size: "+n+" full size: "+s.size+")"),h.memcpy(s.data.buffer,s.alreadyRead,r,s.offset+s.alreadyRead-r.fileStart,n),s.alreadyRead+=n,r.usedBytes+=n,this.stream.logBufferLevel()}},y.prototype.releaseSample=function(t,e){var r=t.samples[e];return r.data?(this.samplesDataSize-=r.size,r.data=null,r.alreadyRead=0,r.size):0},y.prototype.getAllocatedSampleDataSize=function(){return this.samplesDataSize},y.prototype.getCodecs=function(){var t,e="";for(t=0;t<this.moov.traks.length;t++){var r=this.moov.traks[t];t>0&&(e+=","),e+=r.mdia.minf.stbl.stsd.entries[0].getCodec()}return e},y.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 r=this.moov.mvex.trexs[e];if(r.track_id==t)return r}return null},y.prototype.getTrackById=function(t){if(void 0===this.moov)return null;for(var e=0;e<this.moov.traks.length;e++){var r=this.moov.traks[e];if(r.tkhd.track_id==t)return r}return null},y.prototype.items=[],y.prototype.entity_groups=[],y.prototype.itemsDataSize=0,y.prototype.flattenItemInfo=function(){var t,e,r,s=this.items,a=this.entity_groups,n=this.meta;if(null!=n&&void 0!==n.hdlr&&void 0!==n.iinf){for(t=0;t<n.iinf.item_infos.length;t++)(r={}).id=n.iinf.item_infos[t].item_ID,s[r.id]=r,r.ref_to=[],r.name=n.iinf.item_infos[t].item_name,n.iinf.item_infos[t].protection_index>0&&(r.protection=n.ipro.protections[n.iinf.item_infos[t].protection_index-1]),n.iinf.item_infos[t].item_type?r.type=n.iinf.item_infos[t].item_type:r.type="mime",r.content_type=n.iinf.item_infos[t].content_type,r.content_encoding=n.iinf.item_infos[t].content_encoding;if(n.grpl)for(t=0;t<n.grpl.boxes.length;t++)(entity_group={}).id=n.grpl.boxes[t].group_id,entity_group.entity_ids=n.grpl.boxes[t].entity_ids,entity_group.type=n.grpl.boxes[t].type,a[entity_group.id]=entity_group;if(n.iloc)for(t=0;t<n.iloc.items.length;t++){var l=n.iloc.items[t];switch(r=s[l.item_ID],0!==l.data_reference_index&&(o.warn("Item storage with reference to other files: not supported"),r.source=n.dinf.boxes[l.data_reference_index-1]),l.construction_method){case 0:break;case 1:case 2:o.warn("Item storage with construction_method : not supported")}for(e=0,r.extents=[],r.size=0;e<l.extents.length;e++)r.extents[e]={},r.extents[e].offset=l.extents[e].extent_offset+l.base_offset,r.extents[e].length=l.extents[e].extent_length,r.extents[e].alreadyRead=0,r.size+=r.extents[e].length}if(n.pitm&&(s[n.pitm.item_id].primary=!0),n.iref)for(t=0;t<n.iref.references.length;t++){var h=n.iref.references[t];for(e=0;e<h.references.length;e++)s[h.from_item_ID].ref_to.push({type:h.type,id:h.references[e]})}if(n.iprp)for(var d=0;d<n.iprp.ipmas.length;d++){var u=n.iprp.ipmas[d];for(t=0;t<u.associations.length;t++){var p=u.associations[t];if((r=s[p.id])||(r=a[p.id]),r)for(void 0===r.properties&&(r.properties={},r.properties.boxes=[]),e=0;e<p.props.length;e++){var c=p.props[e];if(c.property_index>0&&c.property_index-1<n.iprp.ipco.boxes.length){var f=n.iprp.ipco.boxes[c.property_index-1];r.properties[f.type]=f,r.properties.boxes.push(f)}}}}}},y.prototype.getItem=function(t){if(!this.meta)return null;if(!(r=this.items[t]).data&&r.size)r.data=new Uint8Array(r.size),r.alreadyRead=0,this.itemsDataSize+=r.size,o.debug("ISOFile","Allocating item #"+t+" of size "+r.size+" (total: "+this.itemsDataSize+")");else if(r.alreadyRead===r.size)return r;for(var e,r,s=0;s<r.extents.length;s++){var a=r.extents[s];if(a.alreadyRead!==a.length){var n=this.stream.findPosition(!0,a.offset+a.alreadyRead,!1);if(!(n>-1))return null;var l=(e=this.stream.buffers[n]).byteLength-(a.offset+a.alreadyRead-e.fileStart);if(!(a.length-a.alreadyRead<=l))return o.debug("ISOFile","Getting item #"+t+" extent #"+s+" partial data (alreadyRead: "+a.alreadyRead+" offset: "+(a.offset+a.alreadyRead-e.fileStart)+" read size: "+l+" full extent size: "+a.length+" full item size: "+r.size+")"),h.memcpy(r.data.buffer,r.alreadyRead,e,a.offset+a.alreadyRead-e.fileStart,l),a.alreadyRead+=l,r.alreadyRead+=l,e.usedBytes+=l,this.stream.logBufferLevel(),null;o.debug("ISOFile","Getting item #"+t+" extent #"+s+" 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: "+r.size+")"),h.memcpy(r.data.buffer,r.alreadyRead,e,a.offset+a.alreadyRead-e.fileStart,a.length-a.alreadyRead),e.usedBytes+=a.length-a.alreadyRead,this.stream.logBufferLevel(),r.alreadyRead+=a.length-a.alreadyRead,a.alreadyRead=a.length}}return r.alreadyRead===r.size?r:null},y.prototype.releaseItem=function(t){var e=this.items[t];if(!e.data)return 0;this.itemsDataSize-=e.size,e.data=null,e.alreadyRead=0;for(var r=0;r<e.extents.length;r++)e.extents[r].alreadyRead=0;return e.size},y.prototype.processItems=function(t){for(var e in this.items){var r=this.items[e];this.getItem(r.id),t&&!r.sent&&(t(r),r.sent=!0,r.data=null)}},y.prototype.hasItem=function(t){for(var e in this.items){var r=this.items[e];if(r.name===t)return r.id}return -1},y.prototype.getMetaHandler=function(){return this.meta?this.meta.hdlr.handler:null},y.prototype.getPrimaryItem=function(){return this.meta&&this.meta.pitm?this.getItem(this.meta.pitm.item_id):null},y.prototype.itemToFragmentedTrackFile=function(t){var e=t||{},r=null;if(null==(r=e.itemId?this.getItem(e.itemId):this.getPrimaryItem()))return null;var s=new y;s.discardMdatData=!1;var a={type:r.type,description_boxes:r.properties.boxes};r.properties.ispe&&(a.width=r.properties.ispe.image_width,a.height=r.properties.ispe.image_height);var n=s.addTrack(a);return n?(s.addSample(n,r.data),s):null},y.prototype.write=function(t){for(var e=0;e<this.boxes.length;e++)this.boxes[e].write(t)},y.prototype.createFragment=function(t,e,r){var s=this.getTrackById(t),a=this.getSample(s,e);if(null==a)return this.setNextSeekPositionFromSample(s.samples[e]),null;var n=r||new h;n.endianness=h.BIG_ENDIAN;var l=this.createSingleSampleMoof(a);l.write(n),l.trafs[0].truns[0].data_offset=l.size+8,o.debug("MP4Box","Adjusting data_offset with new value "+l.trafs[0].truns[0].data_offset),n.adjustUint32(l.trafs[0].truns[0].data_offset_position,l.trafs[0].truns[0].data_offset);var d=new p.mdatBox;return d.data=a.data,d.write(n),n},y.writeInitializationSegment=function(t,e,r,s){o.debug("ISOFile","Generating initialization segment");var a,n=new h;n.endianness=h.BIG_ENDIAN,t.write(n);var l=e.add("mvex");for(r&&l.add("mehd").set("fragment_duration",r),a=0;a<e.traks.length;a++)l.add("trex").set("track_id",e.traks[a].tkhd.track_id).set("default_sample_description_index",1).set("default_sample_duration",s).set("default_sample_size",0).set("default_sample_flags",65536);return e.write(n),n.buffer},y.prototype.save=function(t){var e=new h;e.endianness=h.BIG_ENDIAN,this.write(e),e.save(t)},y.prototype.getBuffer=function(){var t=new h;return t.endianness=h.BIG_ENDIAN,this.write(t),t.buffer},y.prototype.initializeSegmentation=function(){for(null===this.onSegment&&o.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 t,e,r,s,a=new p.moovBox;a.mvhd=this.moov.mvhd,a.boxes.push(a.mvhd),r=this.getTrackById(this.fragmentedTracks[t].id),a.boxes.push(r),a.traks.push(r),(s={}).id=r.tkhd.track_id,s.user=this.fragmentedTracks[t].user,s.buffer=y.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(s)}return e},p.Box.prototype.printHeader=function(t){this.size+=8,this.size>0x100000000&&(this.size+=8),"uuid"===this.type&&(this.size+=16),t.log(t.indent+"size:"+this.size),t.log(t.indent+"type:"+this.type)},p.FullBox.prototype.printHeader=function(t){this.size+=4,p.Box.prototype.printHeader.call(this,t),t.log(t.indent+"version:"+this.version),t.log(t.indent+"flags:"+this.flags)},p.Box.prototype.print=function(t){this.printHeader(t)},p.ContainerBox.prototype.print=function(t){this.printHeader(t);for(var e=0;e<this.boxes.length;e++)if(this.boxes[e]){var r=t.indent;t.indent+=" ",this.boxes[e].print(t),t.indent=r}},y.prototype.print=function(t){t.indent="";for(var e=0;e<this.boxes.length;e++)this.boxes[e]&&this.boxes[e].print(t)},p.mvhdBox.prototype.print=function(t){p.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)},p.tkhdBox.prototype.print=function(t){p.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)};var w={};w.createFile=function(t,e){var r=new y(e);return r.discardMdatData=!(void 0===t||t),r},r.createFile=w.createFile},{}],"1pMSt":[function(t,e,r,s){var a,n=t("@parcel/transformer-js/src/esmodule-helpers.js");n.defineInteropFlag(r),n.export(r,"EventTool",()=>_),n.export(r,"Log",()=>z),n.export(r,"autoReadStream",()=>S),n.export(r,"file2stream",()=>x),n.export(r,"recodemux",()=>P),n.export(r,"workerTimer",()=>v);var o=t("@webav/mp4box.js"),l=n.interopDefault(o),h=Object.defineProperty,d=t=>{throw TypeError(t)},u=(t,e,r)=>e in t?h(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,p=(t,e,r)=>u(t,"symbol"!=typeof e?e+"":e,r),c=(t,e,r)=>e.has(t)||d("Cannot "+r),f=(t,e,r)=>(c(t,e,"read from private field"),r?r.call(t):e.get(t)),m=(t,e,r)=>e.has(t)?d("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r);class _{constructor(){m(this,a,new Map),p(this,"on",(t,e)=>{let r=f(this,a).get(t)??new Set;return r.add(e),f(this,a).has(t)||f(this,a).set(t,r),()=>{r.delete(e),0===r.size&&f(this,a).delete(t)}}),p(this,"once",(t,e)=>{let r=this.on(t,(...t)=>{r(),e(...t)});return r}),p(this,"emit",(t,...e)=>{let r=f(this,a).get(t);null!=r&&r.forEach(t=>t(...e))})}static forwardEvent(t,e,r){let s=r.map(r=>{let[s,a]=Array.isArray(r)?r:[r,r];return t.on(s,(...t)=>{e.emit(a,...t)})});return()=>{s.forEach(t=>t())}}destroy(){f(this,a).clear()}}a=new WeakMap;let g=()=>{let t;self.onmessage=e=>{"start"===e.data.event&&(self.clearInterval(t),t=self.setInterval(()=>{self.postMessage({})},16.6)),"stop"===e.data.event&&self.clearInterval(t)}},y=new Map,w=1,b=null;null!=globalThis.Worker&&((b=(()=>{let t=new Blob([`(${g.toString()})()`]);return new Worker(URL.createObjectURL(t))})()).onmessage=()=>{for(let[t,e]of(w+=1,y))if(w%t==0)for(let t of e)t()});let v=(t,e)=>{let r=Math.round(e/16.6),s=y.get(r)??new Set;return s.add(t),y.set(r,s),1===y.size&&1===s.size&&(null==b||b.postMessage({event:"start"})),()=>{s.delete(t),0===s.size&&y.delete(r),0===y.size&&(w=0,null==b||b.postMessage({event:"stop"}))}};function S(t,e){let r=!1;return(async function(){let s=t.getReader();for(;!r;){let{value:t,done:r}=await s.read();if(r)return void e.onDone();await e.onChunk(t)}s.releaseLock(),await t.cancel()})().catch(console.error),()=>{r=!0}}function x(t,e,r){let s=0,a=0,n=t.boxes,o=!1,h=()=>{var e;if(!o)if(null==n.find(t=>"moof"===t.type))return null;else o=!0;if(a>=n.length)return null;let r=new l.default.DataStream;r.endianness=l.default.DataStream.BIG_ENDIAN;let s=a;try{for(;s<n.length;)n[s].write(r),delete n[s],s+=1}catch(r){let t=n[s];throw r instanceof Error&&null!=t?Error(`${r.message} | deltaBuf( boxType: ${t.type}, boxSize: ${t.size}, boxDataLen: ${(null==(e=t.data)?void 0:e.length)??-1})`):r}return function(t){if(null!=t.moov){for(var e=0;e<t.moov.traks.length;e++)t.moov.traks[e].samples=[];t.mdats=[],t.moofs=[]}}(t),a=n.length,new Uint8Array(r.buffer)},d=!1,u=!1,p=null;return{stream:new ReadableStream({start(r){s=self.setInterval(()=>{let t=h();null==t||u||r.enqueue(t)},e),p=e=>{if(clearInterval(s),t.flush(),null!=e)return void r.error(e);let a=h();null==a||u||r.enqueue(a),u||r.close()},d&&p()},cancel(){u=!0,clearInterval(s),null==r||r()}}),stop:t=>{d||(d=!0,null==p||p(t))}}}let U=(t,e)=>{let r=new Uint8Array(8);new DataView(r.buffer).setUint32(0,e);for(let e=0;e<4;e++)r[4+e]=t.charCodeAt(e);return r},E=()=>{let t=new TextEncoder,e=t.encode("mdta"),r=t.encode("mp4 handler"),s=32+r.byteLength+1,a=new Uint8Array(s),n=new DataView(a.buffer);return a.set(U("hdlr",s),0),n.setUint32(8,0),a.set(e,16),a.set(r,32),a},A=t=>{let e=new TextEncoder,r=e.encode("mdta"),s=t.map(t=>{let s=e.encode(t),a=8+s.byteLength,n=new Uint8Array(a);return new DataView(n.buffer).setUint32(0,a),n.set(r,4),n.set(s,4+r.byteLength),n}),a=16+s.reduce((t,e)=>t+e.byteLength,0),n=new Uint8Array(a),o=new DataView(n.buffer);n.set(U("keys",a),0),o.setUint32(8,0),o.setUint32(12,t.length);let l=16;for(let t of s)n.set(t,l),l+=t.byteLength;return n},C=t=>{let e=new TextEncoder,r=e.encode("data"),s=Object.entries(t).map(([t,s],a)=>{let n=e.encode(s),o=24+n.byteLength,l=new Uint8Array(o),h=new DataView(l.buffer);return h.setUint32(0,o),h.setUint32(4,a+1),h.setUint32(8,16+n.byteLength),l.set(r,12),h.setUint32(16,1),l.set(n,24),l}),a=8+s.reduce((t,e)=>t+e.byteLength,0),n=new Uint8Array(a);n.set(U("ilst",a),0);let o=8;for(let t of s)n.set(t,o),o+=t.byteLength;return n},T=t=>{let e=E(),r=A(Object.keys(t)),s=C(t),a=new Uint8Array(e.length+r.length+s.length);return a.set(e,0),a.set(r,e.length),a.set(s,e.length+r.length),a},k=1,B=[],F=["debug","info","warn","error"].reduce((t,e,r)=>Object.assign(t,{[e]:(...t)=>{k<=r&&(console[e](...t),B.push({lvName:e,timeStr:function(){let t=new Date;return`${t.getHours()}:${t.getMinutes()}:${t.getSeconds()}.${t.getMilliseconds()}`}(),args:t}))}}),{}),I=new Map,z={setLogLevel:t=>{k=I.get(t)??1},...F,create:t=>Object.fromEntries(Object.entries(F).map(([e,r])=>[e,(...e)=>r(t,...e)])),dump:async()=>B.reduce((t,{lvName:e,timeStr:r,args:s})=>t+`[${e}][${r}] ${s.map(t=>t instanceof Error?String(t):"object"==typeof t?JSON.stringify(t,(t,e)=>e instanceof Error?String(e):e):String(t)).join(" ")} `,"")};function P(t){z.info("recodemux opts:",t);let e=l.default.createFile(),r=new _,s=(t,e)=>{let r=t.add("udta").add("meta");r.data=T(e),r.size=r.data.byteLength},a=!1,n=()=>{null==e.moov||a||(a=!0,null!=t.metaDataTags&&s(e.moov,t.metaDataTags),null!=t.duration&&(e.moov.mvhd.duration=t.duration))};r.once("VideoReady",n),r.once("AudioReady",n);let o=null!=t.video?function(t,e,r){let s={timescale:1e6,width:t.width,height:t.height,brands:["isom","iso2","avc1","mp42","mp41"],avcDecoderConfigRecord:null,name:"Track created with WebAV"},a=-1,n=!1;r.once("AudioReady",()=>{n=!0});let o={encoder0:[],encoder1:[]},l=(t,n,l)=>{var h;if(-1===a&&null!=l){let t=null==(h=l.decoderConfig)?void 0:h.description;(function(t){let e=new Uint8Array(t);e[2].toString(2).slice(-2).includes("1")&&(e[2]=0)})(t),s.avcDecoderConfigRecord=t,a=e.addTrack(s),r.emit("VideoReady"),z.info("VideoEncoder, video track ready, trackId:",a)}o[t].push(R(n))},h="encoder1",d=0,u=Math.floor(1e3/t.expectFPS*1e3);function p(){if(!n)return;let t="encoder1"===h?"encoder0":"encoder1",e=o[h],r=o[t];if(0===e.length&&0===r.length)return;let s=e[0];if(null!=s&&(!s.is_sync||s.cts-d<u)){let t=c(e);t>d&&(d=t)}let a=r[0];if(null!=a&&a.is_sync&&a.cts-d<u){h=t,p();return}if(null!=s&&s.is_sync&&null!=a&&a.is_sync)if(s.cts<=a.cts){let t=c(e);t>d&&(d=t)}else{h=t,p();return}}function c(t){let r=-1,s=0;for(;s<t.length;s++){let n=t[s];if(s>0&&n.is_sync)break;e.addSample(a,n.data,n),r=n.cts+n.duration}return t.splice(0,s),r}let f=v(p,15),m=L(t,(t,e)=>l("encoder0",t,e)),_=L(t,(t,e)=>l("encoder1",t,e)),g=0;return{get encodeQueueSize(){return m.encodeQueueSize+_.encodeQueueSize},encode:(t,e)=>{try{e.keyFrame&&(g+=1),(g%2==0?m:_).encode(t,e)}catch(s){let r=`encode video frame error: ${s.message}, state: ${JSON.stringify({ts:t.timestamp,keyFrame:e.keyFrame,duration:t.duration,gopId:g})}`;throw z.error(r),Error(r)}},flush:async()=>{await Promise.all(["configured"===m.state?await m.flush():null,"configured"===_.state?await _.flush():null]),f(),p()},close:()=>{"configured"===m.state&&m.close(),"configured"===_.state&&_.close()}}}(t.video,e,r):null,h=null!=t.audio?function(t,e,r){let s={timescale:1e6,samplerate:t.sampleRate,channel_count:t.channelCount,hdlr:"soun",type:"aac"===t.codec?"mp4a":"Opus",name:"Track created with WebAV"},a=-1,n=[],o=!1;r.once("VideoReady",()=>{o=!0,n.forEach(t=>{let r=R(t);e.addSample(a,r.data,r)}),n=[]});let h={codec:"aac"===t.codec?"mp4a.40.2":"opus",sampleRate:t.sampleRate,numberOfChannels:t.channelCount,bitrate:128e3},d=new AudioEncoder({error:t=>{let e=`AudioEncoder error: ${t.message}, config: ${JSON.stringify(h)}, state: ${JSON.stringify({qSize:d.encodeQueueSize,state:d.state})}`;throw z.error(e),Error(e)},output:(t,h)=>{var d;if(-1===a){let t=null==(d=h.decoderConfig)?void 0:d.description;a=e.addTrack({...s,description:null==t?void 0:function(t){let e=t.byteLength,r=new Uint8Array([0,0,0,0,3,23+e,0,2,0,4,18+e,64,21,0,0,0,0,0,0,0,0,0,0,0,5,e,...new Uint8Array(t instanceof ArrayBuffer?t:t.buffer),6,1,2]),s=new l.default.BoxParser.esdsBox(r.byteLength);return s.hdr_size=0,s.parse(new l.default.DataStream(r,0,l.default.DataStream.BIG_ENDIAN)),s}(t)}),r.emit("AudioReady"),z.info("AudioEncoder, audio track ready, trackId:",a)}if(o){let r=R(t);e.addSample(a,r.data,r)}else n.push(t)}});return d.configure(h),d}(t.audio,e,r):null;return null==t.video&&r.emit("VideoReady"),null==t.audio&&r.emit("AudioReady"),{encodeVideo:(t,e)=>{null==o||o.encode(t,e),t.close()},encodeAudio:t=>{if(null!=h)try{h.encode(t),t.close()}catch(e){let t=`encode audio chunk error: ${e.message}, state: ${JSON.stringify({qSize:h.encodeQueueSize,state:h.state})}`;throw z.error(t),Error(t)}},getEncodeQueueSize:()=>(null==o?void 0:o.encodeQueueSize)??(null==h?void 0:h.encodeQueueSize)??0,flush:async()=>{await Promise.all([null==o?void 0:o.flush(),(null==h?void 0:h.state)==="configured"?h.flush():null])},close:()=>{r.destroy(),null==o||o.close(),(null==h?void 0:h.state)==="configured"&&h.close()},mp4file:e}}function L(t,e){let r={codec:t.codec,framerate:t.expectFPS,hardwareAcceleration:t.__unsafe_hardwareAcceleration__,bitrate:t.bitrate,width:t.width,height:t.height,alpha:"discard",avc:{format:"avc"}},s=new VideoEncoder({error:t=>{let e=`VideoEncoder error: ${t.message}, config: ${JSON.stringify(r)}, state: ${JSON.stringify({qSize:s.encodeQueueSize,state:s.state})}`;throw z.error(e),Error(e)},output:e});return s.configure(r),s}function R(t){let e=new ArrayBuffer(t.byteLength);t.copyTo(e);let r=t.timestamp;return{duration:t.duration??0,dts:r,cts:r,is_sync:"key"===t.type,data:e}}I.set(z.debug,0),I.set(z.info,1),I.set(z.warn,2),I.set(z.error,3),async function(){await Promise.resolve(),null!=globalThis.navigator&&null!=globalThis.document&&(z.info(`@webav version: 1.1.0, date: ${new Date().toLocaleDateString()}`),z.info(globalThis.navigator.userAgent),document.addEventListener("visibilitychange",()=>{z.info(`visibilitychange: ${document.visibilityState}`)}),"PressureObserver"in globalThis&&new PressureObserver(t=>{z.info(`cpu state change: ${JSON.stringify(t.map(t=>t.state))}`)}).observe("cpu"))}()},{"@webav/mp4box.js":"1bsIP","@parcel/transformer-js/src/esmodule-helpers.js":"6ykb1"}],"6ykb1":[function(t,e,r,s){r.interopDefault=function(t){return t&&t.__esModule?t:{default:t}},r.defineInteropFlag=function(t){Object.defineProperty(t,"__esModule",{value:!0})},r.exportAll=function(t,e){return Object.keys(t).forEach(function(r){"default"===r||"__esModule"===r||Object.prototype.hasOwnProperty.call(e,r)||Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[r]}})}),e},r.export=function(t,e,r){Object.defineProperty(t,e,{enumerable:!0,get:r})}},{}],"2LcA0":[function(t,e,r,s){var a=t("@parcel/transformer-js/src/esmodule-helpers.js");a.defineInteropFlag(r),a.export(r,"resample",()=>p);var n=t("./lib/interpolator"),o=t("./lib/fir-lpf"),l=t("./lib/butterworth-lpf");let h={point:!1,linear:!1,cubic:!0,sinc:!0},d={IIR:16,FIR:71},u={IIR:l.ButterworthLPF,FIR:o.FIRLPF};function p(t,e,r,s={}){let a=(r-e)/e+1,o=new Float64Array(t.length*a);s.method=s.method||"cubic";let l=new(0,n.Interpolator)(t.length,o.length,{method:s.method,tension:s.tension||0,sincFilterSize:s.sincFilterSize||6,sincWindow:s.sincWindow||void 0});if(void 0===s.LPF&&(s.LPF=h[s.method]),s.LPF){s.LPFType=s.LPFType||"IIR";let a=u[s.LPFType];r>e?function(t,e,r,s){for(let a=0,n=e.length;a<n;a++)e[a]=s.filter(r.interpolate(a,t));s.reset();for(let t=e.length-1;t>=0;t--)e[t]=s.filter(e[t])}(t,o,l,new a(s.LPFOrder||d[s.LPFType],r,e/2)):function(t,e,r,s){for(let e=0,r=t.length;e<r;e++)t[e]=s.filter(t[e]);s.reset();for(let e=t.length-1;e>=0;e--)t[e]=s.filter(t[e]);c(t,e,r)}(t,o,l,new a(s.LPFOrder||d[s.LPFType],e,r/2))}else c(t,o,l);return o}function c(t,e,r){for(let s=0,a=e.length;s<a;s++)e[s]=r.interpolate(s,t)}},{"./lib/interpolator":"2RltM","./lib/fir-lpf":"hAIpN","./lib/butterworth-lpf":"iicyt","@parcel/transformer-js/src/esmodule-helpers.js":"6ykb1"}],"2RltM":[function(t,e,r,s){var a=t("@parcel/transformer-js/src/esmodule-helpers.js");a.defineInteropFlag(r),a.export(r,"Interpolator",()=>n);class n{constructor(t,e,r){var s;this.length_=t,this.scaleFactor_=(t-1)/e,this.interpolate=this.cubic,"point"===r.method?this.interpolate=this.point:"linear"===r.method?this.interpolate=this.linear:"sinc"===r.method&&(this.interpolate=this.sinc),this.tangentFactor_=1-Math.max(0,Math.min(1,r.tension||0)),this.sincFilterSize_=r.sincFilterSize||1,this.kernel_=(s=r.sincWindow||o,function(t){var e;return(0===(e=t)?1:Math.sin(Math.PI*e)/(Math.PI*e))*s(t)})}point(t,e){return this.getClippedInput_(Math.round(this.scaleFactor_*t),e)}linear(t,e){let r=Math.floor(t=this.scaleFactor_*t);return(1-(t-=r))*this.getClippedInput_(r,e)+t*this.getClippedInput_(r+1,e)}cubic(t,e){let r=Math.floor(t=this.scaleFactor_*t),s=[this.getTangent_(r,e),this.getTangent_(r+1,e)],a=[this.getClippedInput_(r,e),this.getClippedInput_(r+1,e)],n=(t-=r)*t,o=t*n;return(2*o-3*n+1)*a[0]+(o-2*n+t)*s[0]+(-2*o+3*n)*a[1]+(o-n)*s[1]}sinc(t,e){let r=Math.floor(t=this.scaleFactor_*t),s=r-this.sincFilterSize_+1,a=r+this.sincFilterSize_,n=0;for(let r=s;r<=a;r++)n+=this.kernel_(t-r)*this.getClippedInput_(r,e);return n}getTangent_(t,e){return this.tangentFactor_*(this.getClippedInput_(t+1,e)-this.getClippedInput_(t-1,e))/2}getClippedInput_(t,e){return 0<=t&&t<this.length_?e[t]:0}}function o(t){return Math.exp(-t/2*t/2)}},{"@parcel/transformer-js/src/esmodule-helpers.js":"6ykb1"}],hAIpN:[function(t,e,r,s){var a=t("@parcel/transformer-js/src/esmodule-helpers.js");a.defineInteropFlag(r),a.export(r,"FIRLPF",()=>n);class n{constructor(t,e,r){let s=2*Math.PI*r/e,a=0;this.filters=[];for(let e=0;e<=t;e++)e-t/2==0?this.filters[e]=s:(this.filters[e]=Math.sin(s*(e-t/2))/(e-t/2),this.filters[e]*=.54-.46*Math.cos(2*Math.PI*e/t)),a+=this.filters[e];for(let e=0;e<=t;e++)this.filters[e]/=a;this.z=this.initZ_()}filter(t){this.z.buf[this.z.pointer]=t;let e=0;for(let t=0,r=this.z.buf.length;t<r;t++)e+=this.filters[t]*this.z.buf[(this.z.pointer+t)%this.z.buf.length];return this.z.pointer=(this.z.pointer+1)%this.z.buf.length,e}reset(){this.z=this.initZ_()}initZ_(){let t=[];for(let e=0;e<this.filters.length-1;e++)t.push(0);return{buf:t,pointer:0}}}},{"@parcel/transformer-js/src/esmodule-helpers.js":"6ykb1"}],iicyt:[function(t,e,r,s){var a=t("@parcel/transformer-js/src/esmodule-helpers.js");a.defineInteropFlag(r),a.export(r,"ButterworthLPF",()=>n);class n{constructor(t,e,r){let s=[];for(let a=0;a<t;a++)s.push(this.getCoeffs_({Fs:e,Fc:r,Q:.5/Math.sin(Math.PI/(2*t)*(a+.5))}));this.stages=[];for(let t=0;t<s.length;t++)this.stages[t]={b0:s[t].b[0],b1:s[t].b[1],b2:s[t].b[2],a1:s[t].a[0],a2:s[t].a[1],k:s[t].k,z:[0,0]}}filter(t){let e=t;for(let t=0,r=this.stages.length;t<r;t++)e=this.runStage_(t,e);return e}getCoeffs_(t){let e={};e.z=[0,0],e.a=[],e.b=[];let r=this.preCalc_(t,e);return e.k=1,e.b.push((1-r.cw)/(2*r.a0)),e.b.push(2*e.b[0]),e.b.push(e.b[0]),e}preCalc_(t,e){let r={},s=2*Math.PI*t.Fc/t.Fs;return r.alpha=Math.sin(s)/(2*t.Q),r.cw=Math.cos(s),r.a0=1+r.alpha,e.a0=r.a0,e.a.push(-2*r.cw/r.a0),e.k=1,e.a.push((1-r.alpha)/r.a0),r}runStage_(t,e){let r=e*this.stages[t].k-this.stages[t].a1*this.stages[t].z[0]-this.stages[t].a2*this.stages[t].z[1],s=this.stages[t].b0*r+this.stages[t].b1*this.stages[t].z[0]+this.stages[t].b2*this.stages[t].z[1];return this.stages[t].z[1]=this.stages[t].z[0],this.stages[t].z[0]=r,s}reset(){for(let t=0;t<this.stages.length;t++)this.stages[t].z=[0,0]}}},{"@parcel/transformer-js/src/esmodule-helpers.js":"6ykb1"}],"7yncN":[function(t,e,r,s){var a,n,o,l,h,d,u,p,c,f,m,_=t("@parcel/transformer-js/src/esmodule-helpers.js");_.defineInteropFlag(r),_.export(r,"dir",()=>I),_.export(r,"file",()=>R),_.export(r,"rollfile",()=>X),_.export(r,"tmpfile",()=>Z),_.export(r,"write",()=>M);var g=t=>{throw TypeError(t)},y=(t,e,r)=>e.has(t)||g("Cannot "+r),w=(t,e,r)=>(y(t,e,"read from private field"),r?r.call(t):e.get(t)),b=(t,e,r)=>e.has(t)?g("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),v=(t,e,r,s)=>(y(t,e,"write to private field"),s?s.call(t,r):e.set(t,r),r);let S="KGZ1bmN0aW9uKCl7InVzZSBzdHJpY3QiO2Z1bmN0aW9uIHUobil7aWYobj09PSIvIilyZXR1cm57cGFyZW50Om51bGwsbmFtZToiIn07Y29uc3QgZT1uLnNwbGl0KCIvIikuZmlsdGVyKGk9PmkubGVuZ3RoPjApO2lmKGUubGVuZ3RoPT09MCl0aHJvdyBFcnJvcigiSW52YWxpZCBwYXRoIik7Y29uc3QgYT1lW2UubGVuZ3RoLTFdLHI9Ii8iK2Uuc2xpY2UoMCwtMSkuam9pbigiLyIpO3JldHVybntuYW1lOmEscGFyZW50OnJ9fWFzeW5jIGZ1bmN0aW9uIHcobixlKXtjb25zdHtwYXJlbnQ6YSxuYW1lOnJ9PXUobik7aWYoYT09bnVsbClyZXR1cm4gYXdhaXQgbmF2aWdhdG9yLnN0b3JhZ2UuZ2V0RGlyZWN0b3J5KCk7Y29uc3QgaT1hLnNwbGl0KCIvIikuZmlsdGVyKHQ9PnQubGVuZ3RoPjApO3RyeXtsZXQgdD1hd2FpdCBuYXZpZ2F0b3Iuc3RvcmFnZS5nZXREaXJlY3RvcnkoKTtmb3IoY29uc3QgcyBvZiBpKXQ9YXdhaXQgdC5nZXREaXJlY3RvcnlIYW5kbGUocyx7Y3JlYXRlOmUuY3JlYXRlfSk7aWYoZS5pc0ZpbGUpcmV0dXJuIGF3YWl0IHQuZ2V0RmlsZUhhbmRsZShyLHtjcmVhdGU6ZS5jcmVhdGV9KX1jYXRjaCh0KXtpZih0Lm5hbWU9PT0iTm90Rm91bmRFcnJvciIpcmV0dXJuIG51bGw7dGhyb3cgdH19Y29uc3QgZj17fTtzZWxmLm9ubWVzc2FnZT1hc3luYyBuPT57dmFyIGk7Y29uc3R7ZXZ0VHlwZTplLGFyZ3M6YX09bi5kYXRhO2xldCByPWZbYS5maWxlSWRdO3RyeXtsZXQgdDtjb25zdCBzPVtdO2lmKGU9PT0icmVnaXN0ZXIiKXtjb25zdCBsPWF3YWl0IHcoYS5maWxlUGF0aCx7Y3JlYXRlOiEwLGlzRmlsZTohMH0pO2lmKGw9PW51bGwpdGhyb3cgRXJyb3IoYG5vdCBmb3VuZCBmaWxlOiAke2EuZmlsZUlkfWApO3I9YXdhaXQgbC5jcmVhdGVTeW5jQWNjZXNzSGFuZGxlKHttb2RlOmEubW9kZX0pLGZbYS5maWxlSWRdPXJ9ZWxzZSBpZihlPT09ImNsb3NlIilhd2FpdCByLmNsb3NlKCksZGVsZXRlIGZbYS5maWxlSWRdO2Vsc2UgaWYoZT09PSJ0cnVuY2F0ZSIpYXdhaXQgci50cnVuY2F0ZShhLm5ld1NpemUpO2Vsc2UgaWYoZT09PSJ3cml0ZSIpe2NvbnN0e2RhdGE6bCxvcHRzOm99PW4uZGF0YS5hcmdzO3Q9YXdhaXQgci53cml0ZShsLG8pfWVsc2UgaWYoZT09PSJyZWFkIil7Y29uc3R7b2Zmc2V0Omwsc2l6ZTpvfT1uLmRhdGEuYXJncyxnPW5ldyBVaW50OEFycmF5KG8pLGQ9YXdhaXQgci5yZWFkKGcse2F0Omx9KSxjPWcuYnVmZmVyO3Q9ZD09PW8/YzooKGk9Yy50cmFuc2Zlcik9PW51bGw/dm9pZCAwOmkuY2FsbChjLGQpKT8/Yy5zbGljZSgwLGQpLHMucHVzaCh0KX1lbHNlIGU9PT0iZ2V0U2l6ZSI/dD1hd2FpdCByLmdldFNpemUoKTplPT09ImZsdXNoIiYmYXdhaXQgci5mbHVzaCgpO3NlbGYucG9zdE1lc3NhZ2Uoe2V2dFR5cGU6ImNhbGxiYWNrIixjYklkOm4uZGF0YS5jYklkLHJldHVyblZhbDp0fSxzKX1jYXRjaCh0KXtjb25zdCBzPXQ7c2VsZi5wb3N0TWVzc2FnZSh7ZXZ0VHlwZToidGhyb3dFcnJvciIsY2JJZDpuLmRhdGEuY2JJZCxlcnJNc2c6cy5uYW1lKyI6ICIrcy5tZXNzYWdlK2AKYCtKU09OLnN0cmluZ2lmeShuLmRhdGEpfSl9fX0pKCk7Ci8vIyBzb3VyY2VNYXBwaW5nVVJMPW9wZnMtd29ya2VyLUY0UldscWNfLmpzLm1hcAo=",x="u">typeof self&&self.Blob&&new Blob([Uint8Array.from(atob(S),t=>t.charCodeAt(0))],{type:"text/javascript;charset=utf-8"});function U(t){let e;try{if(!(e=x&&(self.URL||self.webkitURL).createObjectURL(x)))throw"";let r=new Worker(e,{name:null==t?void 0:t.name});return r.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(e)}),r}catch{return new Worker("data:text/javascript;base64,"+S,{name:null==t?void 0:t.name})}finally{e&&(self.URL||self.webkitURL).revokeObjectURL(e)}}async function E(t,e,r){let s=function(){if(A.length<3){let t=function(){let t=new U,e=0,r={};return t.onmessage=({data:t})=>{var e,s;"callback"===t.evtType?null==(e=r[t.cbId])||e.resolve(t.returnVal):"throwError"===t.evtType&&(null==(s=r[t.cbId])||s.reject(Error(t.errMsg))),delete r[t.cbId]},async function(s,a,n=[]){e+=1;let o=new Promise((t,s)=>{r[e]={resolve:t,reject:s}});return t.postMessage({cbId:e,evtType:s,args:a},n),o}}();return A.push(t),t}{let t=A[C];return C=(C+1)%A.length,t}}();return await s("register",{fileId:t,filePath:e,mode:r}),{read:async(e,r)=>await s("read",{fileId:t,offset:e,size:r}),write:async(e,r)=>await s("write",{fileId:t,data:e,opts:r},[ArrayBuffer.isView(e)?e.buffer:e]),close:async()=>await s("close",{fileId:t}),truncate:async e=>await s("truncate",{fileId:t,newSize:e}),getSize:async()=>await s("getSize",{fileId:t}),flush:async()=>await s("flush",{fileId:t})}}let A=[],C=0;function T(t){if("/"===t)return{parent:null,name:""};let e=t.split("/").filter(t=>t.length>0);if(0===e.length)throw Error("Invalid path");return{name:e[e.length-1],parent:"/"+e.slice(0,-1).join("/")}}async function k(t,e){let{parent:r,name:s}=T(t);if(null==r)return await navigator.storage.getDirectory();let a=r.split("/").filter(t=>t.length>0);try{let t=await navigator.storage.getDirectory();for(let r of a)t=await t.getDirectoryHandle(r,{create:e.create});return e.isFile?await t.getFileHandle(s,{create:e.create}):await t.getDirectoryHandle(s,{create:e.create})}catch(t){if("NotFoundError"===t.name)return null;throw t}}async function B(t){let{parent:e,name:r}=T(t);if(null==e){let t=await navigator.storage.getDirectory();for await(let e of t.keys())await t.removeEntry(e,{recursive:!0});return}let s=await k(e,{create:!1,isFile:!1});if(null!=s)try{await s.removeEntry(r,{recursive:!0})}catch(t){if("NotFoundError"===t.name)return;throw t}}function F(t,e){return`${t}/${e}`.replace("//","/")}function I(t){return new P(t)}let z=class t{constructor(t){b(this,a),b(this,n),b(this,o),v(this,a,t);let{parent:e,name:r}=T(t);v(this,n,r),v(this,o,e)}get kind(){return"dir"}get name(){return w(this,n)}get path(){return w(this,a)}get parent(){return null==w(this,o)?null:I(w(this,o))}async create(){return await k(w(this,a),{create:!0,isFile:!1}),I(w(this,a))}async exists(){return await k(w(this,a),{create:!1,isFile:!1}) instanceof FileSystemDirectoryHandle}async remove(){for(let t of(await this.children()))try{await t.remove()}catch(t){console.warn(t)}try{await B(w(this,a))}catch(t){console.warn(t)}}async children(){let t=await k(w(this,a),{create:!1,isFile:!1});if(null==t)return[];let e=[];for await(let r of t.values())e.push(("file"===r.kind?R:I)(F(w(this,a),r.name)));return e}async copyTo(e){if(!await this.exists())throw Error(`dir ${this.path} not exists`);if(e instanceof t){let t=await e.exists()?I(F(e.path,this.name)):e;return await t.create(),await Promise.all((await this.children()).map(e=>e.copyTo(t))),t}if(e instanceof FileSystemDirectoryHandle)return await Promise.all((await this.children()).map(async t=>{"file"===t.kind?await t.copyTo(await e.getFileHandle(t.name,{create:!0})):await t.copyTo(await e.getDirectoryHandle(t.name,{create:!0}))})),null;throw Error("Illegal target type")}async moveTo(t){let e=await this.copyTo(t);return await this.remove(),e}};a=new WeakMap,n=new WeakMap,o=new WeakMap;let P=z,L=new Map;function R(t,e="rw"){if("rw"===e){let r=L.get(t)??new G(t,e);return L.set(t,r),r}return new G(t,e)}async function M(t,e,r={overwrite:!0}){if(e instanceof G)return void await M(t,await e.stream(),r);let s=await (t instanceof G?t:R(t,"rw")).createWriter();try{if(r.overwrite&&await s.truncate(0),e instanceof ReadableStream){let t=e.getReader();for(;;){let{done:e,value:r}=await t.read();if(e)break;await s.write(r)}}else await s.write(e)}catch(t){throw t}finally{await s.close()}}let D=0,O=()=>++D,N=class t{constructor(t,e){let r;b(this,l),b(this,h),b(this,d),b(this,u),b(this,p),b(this,c,0),b(this,f,(r=null,()=>(v(this,c,w(this,c)+1),r??(r=new Promise(async(t,e)=>{try{let e=await E(w(this,p),w(this,l),w(this,u));t([e,async()=>{v(this,c,w(this,c)-1),w(this,c)>0||(r=null,await e.close())}])}catch(t){e(t)}}))))),b(this,m,!1),v(this,p,O()),v(this,l,t),v(this,u,{r:"read-only",rw:"readwrite","rw-unsafe":"readwrite-unsafe"}[e]);let{parent:s,name:a}=T(t);if(null==s)throw Error("Invalid path");v(this,d,a),v(this,h,s)}get kind(){return"file"}get path(){return w(this,l)}get name(){return w(this,d)}get parent(){return null==w(this,h)?null:I(w(this,h))}async createWriter(){if("read-only"===w(this,u))throw Error("file is read-only");if(w(this,m))throw Error("Other writer have not been closed");v(this,m,!0);let t=new TextEncoder,[e,r]=await w(this,f).call(this),s=await e.getSize(),a=!1;return{write:async(r,n={})=>{if(a)throw Error("Writer is closed");let o="string"==typeof r?t.encode(r):r,l=n.at??s;return s=l+o.byteLength,await e.write(o,{at:l})},truncate:async t=>{if(a)throw Error("Writer is closed");await e.truncate(t),s>t&&(s=t)},flush:async()=>{if(a)throw Error("Writer is closed");await e.flush()},close:async()=>{if(a)throw Error("Writer is closed");a=!0,v(this,m,!1),await r()}}}async createReader(){let[t,e]=await w(this,f).call(this),r=!1,s=0;return{read:async(e,a={})=>{if(r)throw Error("Reader is closed");let n=a.at??s,o=await t.read(n,e);return s=n+o.byteLength,o},getSize:async()=>{if(r)throw Error("Reader is closed");return await t.getSize()},close:async()=>{r||(r=!0,await e())}}}async text(){return new TextDecoder().decode(await this.arrayBuffer())}async arrayBuffer(){let t=await k(w(this,l),{create:!1,isFile:!0});return null==t?new ArrayBuffer(0):(await t.getFile()).arrayBuffer()}async stream(){let t=await this.getOriginFile();return null==t?new ReadableStream({pull:t=>{t.close()}}):t.stream()}async getOriginFile(){var t;return null==(t=await k(w(this,l),{create:!1,isFile:!0}))?void 0:t.getFile()}async getSize(){let t=await k(w(this,l),{create:!1,isFile:!0});return null==t?0:(await t.getFile()).size}async exists(){return await k(w(this,l),{create:!1,isFile:!0}) instanceof FileSystemFileHandle}async remove(){if(w(this,c))throw Error("exists unclosed reader/writer");await B(w(this,l))}async copyTo(e){if(e instanceof t)return e.path===this.path?this:(await M(e.path,this),R(e.path));if(e instanceof P){if(!await this.exists())throw Error(`file ${this.path} not exists`);return await this.copyTo(R(F(e.path,this.name)))}if(e instanceof FileSystemFileHandle)return await (await this.stream()).pipeTo(await e.createWritable()),null;throw Error("Illegal target type")}async moveTo(t){let e=await this.copyTo(t);return await this.remove(),e}};l=new WeakMap,h=new WeakMap,d=new WeakMap,u=new WeakMap,p=new WeakMap,c=new WeakMap,f=new WeakMap,m=new WeakMap;let G=N,W="/.opfs-tools-temp-dir";async function Y(t){try{if("file"===t.kind){if(!await t.exists())return!0;let e=await t.createWriter();await e.truncate(0),await e.close(),await t.remove()}else await t.remove();return!0}catch(t){return console.warn(t),!1}}let H=[],V=!1;async function j(){if(null==globalThis.localStorage)return;let t="OPFS_TOOLS_EXPIRES_TMP_FILES";V||(V=!0,globalThis.addEventListener("unload",()=>{0!==H.length&&localStorage.setItem(t,`${localStorage.getItem(t)??""},${H.join(",")}`)}));let e=localStorage.getItem(t)??"";for(let t of e.split(","))0!==t.length&&await Y(R(`${W}/${t}`))&&(e=e.replace(t,""));localStorage.setItem(t,e.replace(/,{2,}/g,","))}function Z(){let t=`${Math.random().toString().slice(2)}-${Date.now()}`;return H.push(t),R(`${W}/${t}`)}function X(t,e){let r=R(t),s=0,a=r.createWriter(),n=r.createReader(),o=async t=>{let e=await (await n).read(s,{at:Math.round(.3*s)});s=await t.write(e,{at:0}),await t.truncate(s)};return{append:async t=>{let r=await a;(s+=await r.write(t))>=e&&await o(r)},text:r.text.bind(r),remove:async()=>{await (await n).close(),await (await a).close(),await r.remove()},getSize:async()=>s}}!async function(){var t;!0!==globalThis.__opfs_tools_tmpfile_init__&&(globalThis.__opfs_tools_tmpfile_init__=!0,null!=globalThis.FileSystemDirectoryHandle&&null!=globalThis.FileSystemFileHandle&&(null==(t=globalThis.navigator)?void 0:t.storage.getDirectory)!=null&&(setInterval(async()=>{for(let t of(await I(W).children())){let e=/^\d+-(\d+)$/.exec(t.name);(null==e||Date.now()-Number(e[1])>2592e5)&&await Y(t)}},6e4),await j()))}()},{"@parcel/transformer-js/src/esmodule-helpers.js":"6ykb1"}]},["3E1Az"],"3E1Az","parcelRequire4dc0",{}); |