/*! * 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;mo);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=`
${r.outerHTML}
`.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;rnew Float32Array(r));for(let a=0;anew Float32Array(r));for(let a=0;at.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{var e;return(null==(e=t[0])?void 0:e.length)??0})),a=new Float32Array(2*s);for(let n=0;nnew 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>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}));for(let t=r;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;st[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>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 ts.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)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(;s1e3){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{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=s.cts&&tt)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 s3e3)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=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{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(;ae){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{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.ctse);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;tea(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(t3e6)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{}),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(;sa.end)return{state:"done"};if(tea(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{(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{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;rr.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)),!(mo+h||_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=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(t0&&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;sn;)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{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].length0))return"(empty)";for(var r="",s=0;s0&&(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;rthis._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;ra;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>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;rs.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.fileStart0)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;e0&&(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.buffer.byteLength+")"),!0},d.prototype.findPosition=function(t,e,r){var s,a=null,n=-1;for(s=!0===t?0:this.bufferIndex;s=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>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;rr?(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()>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=[];e0&&(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=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>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>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>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=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>7,o.nalu_type=63&a;var l=t.readUint16();for(r=0;r>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>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>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()>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>7,n.nalu_type=63&s;var o=t.readUint16();for(r=0;r>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;r0){var e=t.readUint32();this.kid=[];for(var r=0;r0&&(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>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>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>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>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>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>4&15,this.sample_sizes[e+1]=15&s}else if(8===this.field_size)for(e=0;e0)for(r=0;r>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>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()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>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,"'")}),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>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<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<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<>=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>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<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=2&&t.writeUint32(this.default_sample_description_index),t.writeUint32(this.entries.length),e=0;e0)for(e=0;e+10xffffffff),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-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=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;l1)for(e=1;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-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;t0?o.mime+='video/mp4; codecs="':o.audioTracks&&o.audioTracks.length>0?o.mime+='audio/mp4; codecs="':o.mime+='application/mp4; codecs="',t=0;t=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=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;at*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;athis.getTrackDuration(r))&&((s=this.seekTrack(t,e,r)).offset-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=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=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;tb&&(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.lastMoofIndex0&&y.initSampleGroups(u,d,d.sbgps,u.mdia.minf.stbl.sgpds,d.sgpds),e=0;e0?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-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;t0&&(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;e0&&(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;t0&&c.property_index-1-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;r0?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>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{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-dd&&(d=t)}let a=r[0];if(null!=a&&a.is_sync&&a.cts-dd&&(d=t)}else{h=t,p();return}}function c(t){let r=-1,s=0;for(;s0&&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=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=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;sn);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&&tn);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;tn);class n{constructor(t,e,r){let s=[];for(let a=0;aI),_.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",{});