/*!! * flipnote.js v6.3.0 * https://flipnote.js.org * A JavaScript library for Flipnote Studio animation files * 2018 - 2025 James Daniel * Flipnote Studio is (c) Nintendo Co., Ltd. This project isn't affiliated with or endorsed by them in any way. */ !function(t){var e,i,s,r,a,n;function o(t,e,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!s:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(t):s?s.value:e.get(t)}function h(t,e,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(t,i):r?r.value=i:e.set(t,i),i}t.FlipnoteRegion=void 0,(e=t.FlipnoteRegion||(t.FlipnoteRegion={})).EUR="EUR",e.USA="USA",e.JPN="JPN",e.UNKNOWN="UNKNOWN",t.FlipnoteFormat=void 0,(i=t.FlipnoteFormat||(t.FlipnoteFormat={})).PPM="PPM",i.KWZ="KWZ",t.FlipnoteThumbImageFormat=void 0,(s=t.FlipnoteThumbImageFormat||(t.FlipnoteThumbImageFormat={}))[s.Jpeg=0]="Jpeg",s[s.Rgba=1]="Rgba",t.FlipnoteStereoscopicEye=void 0,(r=t.FlipnoteStereoscopicEye||(t.FlipnoteStereoscopicEye={}))[r.Left=0]="Left",r[r.Right=1]="Right",t.FlipnoteAudioTrack=void 0,(a=t.FlipnoteAudioTrack||(t.FlipnoteAudioTrack={}))[a.BGM=0]="BGM",a[a.SE1=1]="SE1",a[a.SE2=2]="SE2",a[a.SE3=3]="SE3",a[a.SE4=4]="SE4",t.FlipnoteSoundEffectTrack=void 0,(n=t.FlipnoteSoundEffectTrack||(t.FlipnoteSoundEffectTrack={}))[n.SE1=1]="SE1",n[n.SE2=2]="SE2",n[n.SE3=3]="SE3",n[n.SE4=4]="SE4","function"==typeof SuppressedError&&SuppressedError;class ByteArray{constructor(){this.pageSize=4096,this.allocSize=0,this.realSize=0,this.pages=[],this.numPages=0,this.pageIdx=0,this.pagePtr=0,this.realPtr=0,this.newPage()}set pointer(t){this.setPointer(t)}get pointer(){return this.realPtr}newPage(){this.pages[this.numPages]=new Uint8Array(this.pageSize),this.numPages=this.pages.length,this.allocSize=this.numPages*this.pageSize}setPointer(t){for(;t>=this.allocSize;)this.newPage();t>this.realSize&&(this.realSize=t),this.pageIdx=Math.floor(t/this.pageSize),this.pagePtr=t%this.pageSize,this.realPtr=t}writeByte(t){this.pages[this.pageIdx][this.pagePtr]=t,this.setPointer(this.realPtr+1)}writeBytes(t,e,i){for(let s=i||t.length,r=e||0;r>>0&255),this.writeByte(t>>>8&255)}writeU32(t){this.writeByte(t>>>0&255),this.writeByte(t>>>8&255),this.writeByte(t>>>16&255),this.writeByte(t>>>24&255)}getBytes(){const t=new Uint8Array(this.realSize),e=this.numPages;for(let i=0;i{let i=[];for(let e=0;ethis.writeUint8(t)))}readHex(t,e=!1){const i=this.readBytes(t);return l(i,e)}readChar(){const t=this.readUint8();return String.fromCharCode(t)}readWideChar(){const t=this.readUint16();return String.fromCharCode(t)}readChars(t){const e=this.readBytes(t);let i="";for(let t=0;t=this.data.byteLength}}const c=(t,e,i)=>ti?i:t;function u(t,e="Assert failed"){t||d(e)}const f=(t,e,i,s="")=>u(t>=e&&t<=i,`flipnote.js error: ${s||"value"} ${t} should be between ${e} and ${i}`),d=(t="Assert failed")=>{throw new Error("flipnote.js error: "+t)},m=()=>y?global:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{},p="undefined"!=typeof window&&void 0!==window.document,g=()=>u(p,"This feature is only available in browser environments"),y="undefined"!=typeof process&&null!=process.versions&&null!=process.versions.node,w="object"==typeof self&&self.constructor&&"DedicatedWorkerGlobalScope"===self.constructor.name;var v;!function(){if(!p)return function(){};document.createElement("a")}();class BaseParser extends DataStream{constructor(){super(...arguments),this[v]="Flipnote",this.titleFormats={COMMENT:"Comment by $USERNAME",FLIPNOTE:"Flipnote by $USERNAME",ICON:"Folder icon"},this.soundMeta=new Map,this.layerVisibility={1:!0,2:!0,3:!0},this.isFolderIcon=!1,this.isComment=!1,this.isDsiLibraryNote=!1}getTitle(t=this.titleFormats){return this.isFolderIcon?t.ICON:(this.isComment?t.COMMENT:t.FLIPNOTE).replace("$USERNAME",this.meta.current.username)}toString(){return this.getTitle()}*[(v=Symbol.toStringTag,Symbol.iterator)](){for(let t=0;te[a]=r<<24|s<<16|i<<8|t)),e}getSoundEffectFlagsForTrack(t){return this.getSoundEffectFlags().map((e=>e[t]))}isSoundEffectUsedOnFrame(t,e){return f(e,0,this.frameCount-1,"Frame index"),!!this.soundEffectTracks.includes(t)&&this.getFrameSoundEffectFlags(e)[t]}hasAudioTrack(t){return this.soundMeta.has(t)&&this.soundMeta.get(t).length>0}}const b=/^[0159]{1}[0-9A-F]{6}0[0-9A-F]{8}$/,P=["01FACA7A4367FC5F","03D6E959E2F9A42D","03F80445160587FA","04068426E1008915","092A3EC8199FD5D5","0B8D56BA1BD441B8","0E61C75C9B5AD90B","14E494E35A443235"],S=t=>b.test(t)||P.includes(t),F=e=>{switch(e.charAt(0)){case"0":case"1":return t.FlipnoteRegion.JPN;case"5":return t.FlipnoteRegion.USA;case"9":return t.FlipnoteRegion.EUR;default:return t.FlipnoteRegion.UNKNOWN}},E=new Int8Array([-1,2,-1,2]),A=new Int8Array([-1,-1,-1,-1,2,4,6,8,-1,-1,-1,-1,2,4,6,8]),T=new Int16Array([7,8,9,10,11,12,13,14,16,17,19,21,23,25,28,31,34,37,41,45,50,55,60,66,73,80,88,97,107,118,130,143,157,173,190,209,230,253,279,307,337,371,408,449,494,544,598,658,724,796,876,963,1060,1166,1282,1411,1552,1707,1878,2066,2272,2499,2749,3024,3327,3660,4026,4428,4871,5358,5894,6484,7132,7845,8630,9493,10442,11487,12635,13899,15289,16818,18500,20350,22385,24623,27086,29794,32767,0]),k=(t,e,i)=>i<0||i>=e?0:t[i],U=t=>{const e=t.length;let i=0;for(let s=0;s=32767)&&(i+=1)}return i/e},C=t=>{const e=t.length;let i=0;for(let s=0;snew Date(1e3*(t+x)),_=t=>Math.floor(t.getTime()/1e3-x),B=(t,e)=>100*t*(1/e)/100,L=(()=>{if(p||w){const t=m();return(t.crypto||t.msCrypto).subtle}if(y)return((t,e)=>{try{return t.require(e)}catch{throw new Error(`Could not require(${e})`)}})(module,"crypto").webcrypto.subtle})(),z="RSASSA-PKCS1-v1_5",I=async(t,e)=>{const i=t.split("\n").filter((t=>!t.startsWith("-----")&&!t.endsWith("-----"))).join(""),s=atob(i),r=new Uint8Array(s.length).map(((t,e)=>s.charCodeAt(e)));return await L.importKey("spki",r.buffer,{name:z,hash:e},!1,["verify"])},W=async(t,e,i)=>await L.verify(z,t,e,i);var R,N,D,K,O,H,$,G,V,j,q,Y,X,Q,J,Z,tt,et;const it=[.5,.5,1,2,4,6,12,20,30],st={WHITE:[255,255,255,255],BLACK:[14,14,14,255],RED:[255,42,42,255],BLUE:[10,57,255,255]},rt=[4294967295,4283585106,4294967295,4288453788,4282665215,4283388360,4289506815,4278255360,4294918216,4290269009,4294945709,4278255360,4290205622,4278255360,4278255360,4278255360],at="-----BEGIN PUBLIC KEY-----\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCPLwTL6oSflv+gjywi/sM0TUB\n90xqOvuCpjduETjPoN2FwMebxNjdKIqHUyDu4AvrQ6BDJc6gKUbZ1E27BGZoCPH4\n9zQRb+zAM6M9EjHwQ6BABr0u2TcF7xGg2uQ9MBWz9AfbVQ91NjfrNWo0f7UPmffv\n1VvixmTk1BCtavZxBwIDAQAB\n-----END PUBLIC KEY-----";class PpmParser extends BaseParser{static matchBuffer(t){const e=new Uint8Array(t.slice(0,4));return 1346458177==(e[0]<<24|e[1]<<16|e[2]<<8|e[3])}constructor(e,i={}){super(e),R.add(this),this.format=t.FlipnoteFormat.PPM,this[et]="Flipnote Studio PPM animation file",this.imageWidth=PpmParser.width,this.imageHeight=PpmParser.height,this.aspect=PpmParser.aspect,this.imageOffsetX=0,this.imageOffsetY=0,this.numLayers=PpmParser.numLayers,this.numLayerColors=PpmParser.numLayerColors,this.publicKey=PpmParser.publicKey,this.srcWidth=PpmParser.width,this.audioTracks=PpmParser.audioTracks,this.soundEffectTracks=PpmParser.soundEffectTracks,this.rawSampleRate=PpmParser.rawSampleRate,this.sampleRate=PpmParser.sampleRate,this.globalPalette=PpmParser.globalPalette,N.set(this,void 0),D.set(this,void 0),K.set(this,void 0),O.set(this,void 0),H.set(this,null),$.set(this,void 0),G.set(this,void 0),V.set(this,void 0),j.set(this,void 0),o(this,R,"m",q).call(this),o(this,R,"m",Q).call(this),o(this,R,"m",J).call(this),this.version>>4&15&&o(this,R,"m",X).call(this),h(this,N,[new Uint8Array(PpmParser.width*PpmParser.height),new Uint8Array(PpmParser.width*PpmParser.height)],"f"),h(this,K,[new Uint8Array(PpmParser.width*PpmParser.height),new Uint8Array(PpmParser.width*PpmParser.height)],"f"),h(this,O,[new Uint8Array(PpmParser.height),new Uint8Array(PpmParser.height)],"f"),h(this,H,null,"f")}getThumbnailImage(){this.seek(160);const e=this.readBytes(1536),i=new Uint32Array(3072);for(let t=0;t<48;t+=8)for(let s=0;s<64;s+=8)for(let r=0;r<8;r+=1)for(let a=0;a<8;a+=2){const n=s+a,o=t+r;i[64*o+n]=rt[15&e[0]],i[64*o+n+1]=rt[e[0]<<4&15]}return{format:t.FlipnoteThumbImageFormat.Rgba,width:64,height:48,data:i.buffer}}getMemoryMeterLevel(){const t=o(this,$,"f")/736800;return t<0?0:t}decodeFrame(t){if(f(t,0,this.frameCount-1,"Frame index"),o(this,H,"f")===t)return o(this,N,"f");o(this,H,"f")===t-1||o(this,R,"m",Z).call(this,t)||0===t||this.decodeFrame(t-1),h(this,H,t,"f"),this.seek(o(this,j,"f")[t]);const e=this.readUint8(),i=e>>7&1,s=e>>5&3;o(this,N,"f")[0].fill(0),o(this,N,"f")[1].fill(0);let r=0,a=0;s&&(r=this.readInt8(),a=this.readInt8());for(let t=0;t<2;t++){const e=o(this,O,"f")[t];e.fill(0);for(let t=0;t>2&3,e[t++]=i>>4&3,e[t++]=i>>6&3):t+=4}}for(let t=0;t<2;t++){const e=o(this,N,"f")[t],i=o(this,O,"f")[t];for(let t=0;t>=1)e[s+i]=1&t}break;case 2:for(e.fill(1,s,s+PpmParser.width),n=this.readUint32(!1);0!==n;n<<=1,s+=8)if(2147483648&n){let t=this.readUint8();for(let i=0;i<8;i++,t>>=1)e[s+i]=1&t}break;case 3:for(let t=0,i=0;i>=1}}}const l=o(this,N,"f")[0],c=o(this,N,"f")[1],u=o(this,K,"f")[0],d=o(this,K,"f")[1];if(i||0!==r||0!==a){if(!i){const t=PpmParser.width,e=PpmParser.height,i=Math.max(r,0),s=Math.max(a,0),n=Math.min(t+r,t),o=Math.min(e+a,e),h=a*t+r;let f,m;for(let e=s;e>1&3],s[e>>3&3]]}getFramePalette(t){return f(t,0,this.frameCount-1,"Frame index"),this.getFramePaletteIndices(t).map((t=>this.globalPalette[t]))}getIsKeyFrame(t){const e=1===o(this,R,"m",Z).call(this,t);return[e,e]}getFrameLayerDepths(t){return[0,0]}getFrameAuthor(t){return this.meta.current.fsid}getFrameCameraFlags(t){return[!1,!1]}getFrameLayerOrder(t){return[1,0]}decodeSoundFlags(){if(void 0!==o(this,D,"f"))return o(this,D,"f");u(1696+o(this,$,"f")({[t.FlipnoteSoundEffectTrack.SE1]:e[0],[t.FlipnoteSoundEffectTrack.SE2]:e[1],[t.FlipnoteSoundEffectTrack.SE3]:e[2],[t.FlipnoteSoundEffectTrack.SE4]:!1})))}getFrameSoundEffectFlags(e){f(e,0,this.frameCount-1,"Frame index"),this.seek(1696+o(this,$,"f")+e);const i=this.readUint8();return{[t.FlipnoteSoundEffectTrack.SE1]:!!(1&i),[t.FlipnoteSoundEffectTrack.SE2]:!!(2&i),[t.FlipnoteSoundEffectTrack.SE3]:!!(4&i),[t.FlipnoteSoundEffectTrack.SE4]:!1}}getAudioTrackDuration(e){const i=this.soundMeta.get(e);if(0===i.length)return 0;if(e===t.FlipnoteAudioTrack.BGM){const t=1/this.bgmrate/(1/this.framerate),e=this.rawSampleRate*t;return 2*(i.length-4)/e}return 2*(i.length-4)/this.sampleRate}getAudioTrackRaw(t){const e=this.soundMeta.get(t);return u(e.ptr+e.length>4,f=!f;const t=T[n];let e=t>>3;1&r&&(e+=t>>2),2&r&&(e+=t>>1),4&r&&(e+=t),8&r&&(e=-e),a+=e,a=c(a,-32768,32767),n+=A[r],n=c(n,0,88),l[s++]=a}return l}getAudioTrackPcm(e,i=this.sampleRate){const s=this.decodeAudioTrack(e);let r=this.rawSampleRate;if(e===t.FlipnoteAudioTrack.BGM){const t=1/this.bgmrate/(1/this.framerate);r=this.rawSampleRate*t}return r!==i?((t,e,i)=>{const s=t.length,r=s/e*i,a=new Int16Array(r),n=e/i;for(let e=0;e>1&1),advancedTools:void 0,isSpinoff:this.isSpinoff,frameCount:this.frameCount,frameSpeed:this.frameSpeed,bgmSpeed:this.bgmSpeed,duration:this.duration,thumbIndex:e,timestamp:f,root:{username:i,fsid:c,region:F(c),filename:null},parent:{username:s,fsid:a,region:F(a),filename:h},current:{username:r,fsid:n,region:F(n),filename:l}}},Q=function(){this.seek(1696);const t=this.readUint16(),e=t/4;u(e<=this.frameCount),this.seek(1704);const i=new Uint32Array(e);for(let s=0;s>7&1},tt=function(t,e,i=0){const s=t.length,r=e.length;for(let a=0;ar);a++){const s=e[i+a]+t[a]/2;e[i+a]=c(s,-32768,32767)}},PpmParser.defaultSettings={},PpmParser.format=t.FlipnoteFormat.PPM,PpmParser.width=256,PpmParser.height=192,PpmParser.aspect=3/4,PpmParser.numLayers=2,PpmParser.numLayerColors=1,PpmParser.rawSampleRate=8180,PpmParser.sampleRate=32768,PpmParser.audioTracks=[t.FlipnoteAudioTrack.BGM,t.FlipnoteAudioTrack.SE1,t.FlipnoteAudioTrack.SE2,t.FlipnoteAudioTrack.SE3],PpmParser.soundEffectTracks=[t.FlipnoteSoundEffectTrack.SE1,t.FlipnoteSoundEffectTrack.SE2,t.FlipnoteSoundEffectTrack.SE3],PpmParser.globalPalette=[st.WHITE,st.BLACK,st.RED,st.BLUE],PpmParser.publicKey=at;const nt=/^[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{6}$/,ot=/^(00|10|12|14)[0-9a-f]{2}-[0-9a-f]{4}-[0-9a-f]{3}0-[0-9a-f]{4}[0159]{1}[0-9a-f]{1}$/,ht=["5f-fc67-437a-cafa01","2d-a4f9-e259-e9d603","fa-8705-1645-04f803","15-8900-e126-840604","d5-d59f-19c8-3e2a09","b8-41d4-1bba-568d0b","0b-d95a-9b5c-c7610e","35-3244-5ae3-94e414"],lt=t=>nt.test(t),ct=t=>{if(ot.test(t))return!0;for(let e of ht)if(t.endsWith(e))return!0;return!1},ut=e=>{if(ct(e))switch(e.charAt(19)){case"0":case"1":return t.FlipnoteRegion.JPN;case"5":return t.FlipnoteRegion.USA;case"9":return t.FlipnoteRegion.EUR;default:return t.FlipnoteRegion.UNKNOWN}return t.FlipnoteRegion.UNKNOWN},ft=t=>`${t.slice(0,4)}-${t.slice(4,8)}-${t.slice(8,12)}-${t.slice(12,18)}`.toLowerCase(),dt=t=>t.replace(/-/g,"").toUpperCase();var mt,pt,gt,yt,wt,vt,bt,Pt,St,Ft,Et,At,Tt,kt,Ut,Ct,xt,Mt,_t,Bt,Lt,zt;const It=[.2,.5,1,2,4,6,8,12,20,24,30],Wt={WHITE:[255,255,255,255],BLACK:[16,16,16,255],RED:[255,16,16,255],YELLOW:[255,231,0,255],GREEN:[0,134,49,255],BLUE:[0,56,206,255],NONE:[255,255,255,0]},Rt="-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuv+zHAXXvbbtRqxADDeJ\nArX2b9RMxj3T+qpRg3FnIE/jeU3tj7eoDzsMduY+D/UT9CSnP+QHYY/vf0n5lqX9\ns6ljoZAmyUuruyj1e5Bg+fkDEu/yPEPQjqhbyywCyYL4TEAOJveopUBx9fdQxUJ6\nJ4J5oCE/Im1kFrlGW+puARiHmt3mmUyNzO8bI/Jx3cGSfoOHJG1foEaQsI5aaKqA\npBqxtzvwqMhudcZtAWSyRMBMlndvkRnVTDNTfTXLOYdHShCIgnKULCTH87uLBIP/\nnsmr4/bnQz8q2rp/HyVO+0yjR6mVr0NX5APJQ+6riJmGg3t3VOldhKP7aTHDUW+h\nkQIDAQAB\n-----END PUBLIC KEY-----",Nt=new Uint16Array(16);for(let t=0;t<16;t++)Nt[t]=(1<{const i=8*t,s=Dt.subarray(i,i+8),r=Kt.subarray(i,i+8);Ht.set(s,8*e),$t.set(r,8*e)}));class KwzParser extends BaseParser{static matchBuffer(t){const e=new Uint8Array(t.slice(0,4)),i=e[0]<<24|e[1]<<16|e[2]<<8;return 1262897152===i||1263092480===i}constructor(e,i={}){super(e),mt.add(this),this.format=t.FlipnoteFormat.KWZ,this[zt]="Flipnote Studio 3D KWZ animation file",this.imageWidth=KwzParser.width,this.imageHeight=KwzParser.height,this.aspect=KwzParser.aspect,this.imageOffsetX=0,this.imageOffsetY=0,this.numLayers=KwzParser.numLayers,this.numLayerColors=KwzParser.numLayerColors,this.publicKey=KwzParser.publicKey,this.srcWidth=KwzParser.width,this.audioTracks=KwzParser.audioTracks,this.soundEffectTracks=KwzParser.soundEffectTracks,this.rawSampleRate=KwzParser.rawSampleRate,this.sampleRate=KwzParser.sampleRate,this.globalPalette=KwzParser.globalPalette,pt.set(this,void 0),gt.set(this,void 0),yt.set(this,void 0),wt.set(this,void 0),vt.set(this,void 0),bt.set(this,null),Pt.set(this,void 0),St.set(this,void 0),Ft.set(this,void 0),Et.set(this,void 0),At.set(this,0),Tt.set(this,0),h(this,pt,{...KwzParser.defaultSettings,...i},"f"),h(this,wt,[new Uint8Array(KwzParser.width*KwzParser.height),new Uint8Array(KwzParser.width*KwzParser.height),new Uint8Array(KwzParser.width*KwzParser.height)],"f"),o(this,mt,"m",kt).call(this),o(this,gt,"f").has("KIC")?(this.isFolderIcon=!0,this.imageWidth=24,this.imageHeight=24,this.frameCount=1,this.frameSpeed=0,this.framerate=It[0],this.thumbFrameIndex=0,o(this,mt,"m",Bt).call(this)):o(this,gt,"f").has("KSN")?(o(this,mt,"m",Mt).call(this),o(this,mt,"m",Bt).call(this),o(this,mt,"m",Lt).call(this)):(this.isComment=!0,o(this,mt,"m",Mt).call(this),o(this,mt,"m",Bt).call(this)),o(this,pt,"f").dsiLibraryNote&&(this.isDsiLibraryNote=!0),o(this,pt,"f").borderCrop&&(this.isDsiLibraryNote?(this.imageOffsetX=32,this.imageOffsetY=24,this.imageWidth=256,this.imageHeight=192):this.isFolderIcon||(this.imageOffsetX=5,this.imageOffsetY=5,this.imageWidth=310,this.imageHeight=230))}getThumbnailImage(){u(o(this,gt,"f").has("KTN"),"KTN section missing - Note that folder icons and comments do not contain thumbnail data");const e=o(this,gt,"f").get("KTN");this.seek(e.ptr+12);const i=this.readBytes(e.length-12);return{format:t.FlipnoteThumbImageFormat.Jpeg,width:80,height:64,data:i.buffer}}getMemoryMeterLevel(){u(o(this,gt,"f").has("KMI")&&o(this,gt,"f").has("KMC"));const t=this.rawSampleRate/2,e=60*t+2*t*4;return(o(this,Et,"f")+57600)/(4219447-(e+39&4294967292))}getFramePaletteIndices(t){f(t,0,this.frameCount-1,"Frame index"),this.seek(o(this,Pt,"f")[t]);const e=this.readUint32();return[15&e,e>>8&15,e>>12&15,e>>16&15,e>>20&15,e>>24&15,e>>28&15]}getFramePalette(t){return f(t,0,this.frameCount-1,"Frame index"),this.getFramePaletteIndices(t).map((t=>this.globalPalette[t]))}getFrameDiffingFlag(t){return f(t,0,this.frameCount-1,"Frame index"),this.seek(o(this,Pt,"f")[t]),this.readUint32()>>4&7}getIsKeyFrame(t){const e=this.getFrameDiffingFlag(t);return[!(1&e),!(2&e),!(4&e)]}getFrameLayerDepths(t){return f(t,0,this.frameCount-1,"Frame index"),this.seek(o(this,Pt,"f")[t]+20),[this.readUint8(),this.readUint8(),this.readUint8()]}getFrameAuthor(t){return f(t,0,this.frameCount-1,"Frame index"),this.seek(o(this,Pt,"f")[t]+10),o(this,mt,"m",Ct).call(this)}getFrameCameraFlags(t){this.seek(o(this,Pt,"f")[t]+26);const e=this.readUint8();return[!!(1&e),!!(2&e),!!(4&e)]}getFrameLayerOrder(t){f(t,0,this.frameCount-1,"Frame index");const e=this.getFrameLayerDepths(t);return[2,1,0].sort(((t,i)=>e[i]-e[t]))}decodeFrame(t,e=7,i=!1){if(f(t,0,this.frameCount-1,"Frame index"),o(this,bt,"f")===t)return o(this,wt,"f");o(this,bt,"f")!==t-1&&0!==t&&(i&&(e&=~this.getFrameDiffingFlag(t+1)),0!==e&&this.decodeFrame(t-1,e,!0));let s=o(this,St,"f")[t];const r=o(this,Ft,"f")[t];for(let t=0;t<3&&(!o(this,pt,"f").dsiLibraryNote||3!==t);t++){this.seek(s);let i=r[t];s+=i;const a=o(this,wt,"f")[t];if(38===i)continue;if(!(e>>t&1))continue;h(this,At,16,"f"),h(this,Tt,0,"f");let n=0;for(let t=0;t<240;t+=128)for(let e=0;e<320;e+=128)for(let i=0;i<128;i+=8){const s=t+i;if(s>=240)break;for(let t=0;t<128;t+=8){const i=e+t;if(i>=320)break;if(n>0){n-=1;continue}let r=s*KwzParser.width+i;const h=o(this,mt,"m",Ut).call(this,3);if(0===h){const t=8*o(this,mt,"m",Ut).call(this,5),e=Ht.subarray(t,t+8);a.set(e,r),a.set(e,r+=320),a.set(e,r+=320),a.set(e,r+=320),a.set(e,r+=320),a.set(e,r+=320),a.set(e,r+=320),a.set(e,r+=320)}else if(1===h){const t=8*o(this,mt,"m",Ut).call(this,13),e=Dt.subarray(t,t+8);a.set(e,r),a.set(e,r+=320),a.set(e,r+=320),a.set(e,r+=320),a.set(e,r+=320),a.set(e,r+=320),a.set(e,r+=320),a.set(e,r+=320)}else if(2===h){const t=8*o(this,mt,"m",Ut).call(this,5),e=Ht.subarray(t,t+8),i=$t.subarray(t,t+8);a.set(e,r),a.set(i,r+=320),a.set(e,r+=320),a.set(i,r+=320),a.set(e,r+=320),a.set(i,r+=320),a.set(e,r+=320),a.set(i,r+=320)}else if(3===h){const t=8*o(this,mt,"m",Ut).call(this,13),e=Dt.subarray(t,t+8),i=Kt.subarray(t,t+8);a.set(e,r),a.set(i,r+=320),a.set(e,r+=320),a.set(i,r+=320),a.set(e,r+=320),a.set(i,r+=320),a.set(e,r+=320),a.set(i,r+=320)}else if(4===h){const t=o(this,mt,"m",Ut).call(this,8);for(let e=1;e<255;e<<=1){if(t&e){const t=8*o(this,mt,"m",Ut).call(this,5),e=Ht.subarray(t,t+8);a.set(e,r)}else{const t=8*o(this,mt,"m",Ut).call(this,13),e=Dt.subarray(t,t+8);a.set(e,r)}r+=320}}else{if(5===h){n=o(this,mt,"m",Ut).call(this,5);continue}if(7===h){let t,e,i=o(this,mt,"m",Ut).call(this,2);if(0!==o(this,mt,"m",Ut).call(this,1)){const s=8*o(this,mt,"m",Ut).call(this,5),r=8*o(this,mt,"m",Ut).call(this,5);t=Ht.subarray(s,s+8),e=Ht.subarray(r,r+8),i+=1}else{const i=8*o(this,mt,"m",Ut).call(this,13),s=8*o(this,mt,"m",Ut).call(this,13);t=Dt.subarray(i,i+8),e=Dt.subarray(s,s+8)}switch(i%4){case 0:a.set(t,r),a.set(e,r+=320),a.set(t,r+=320),a.set(e,r+=320),a.set(t,r+=320),a.set(e,r+=320),a.set(t,r+=320),a.set(e,r+=320);break;case 1:a.set(t,r),a.set(t,r+=320),a.set(e,r+=320),a.set(t,r+=320),a.set(t,r+=320),a.set(e,r+=320),a.set(t,r+=320),a.set(t,r+=320);break;case 2:a.set(t,r),a.set(e,r+=320),a.set(t,r+=320),a.set(t,r+=320),a.set(e,r+=320),a.set(t,r+=320),a.set(t,r+=320),a.set(e,r+=320);break;case 3:a.set(t,r),a.set(e,r+=320),a.set(e,r+=320),a.set(t,r+=320),a.set(e,r+=320),a.set(e,r+=320),a.set(t,r+=320),a.set(e,r+=320)}}}}}}return h(this,bt,t,"f"),o(this,wt,"f")}decodeFrameSoundFlags(t){f(t,0,this.frameCount-1,"Frame index"),this.seek(o(this,Pt,"f")[t]+23);const e=this.readUint8();return[!!(1&e),!!(2&e),!!(4&e),!!(8&e)]}decodeSoundFlags(){return void 0!==o(this,vt,"f")||h(this,vt,new Array(this.frameCount).fill(!1).map(((t,e)=>this.decodeFrameSoundFlags(e))),"f"),o(this,vt,"f")}getSoundEffectFlags(){return this.decodeSoundFlags().map((e=>({[t.FlipnoteSoundEffectTrack.SE1]:e[0],[t.FlipnoteSoundEffectTrack.SE2]:e[1],[t.FlipnoteSoundEffectTrack.SE3]:e[2],[t.FlipnoteSoundEffectTrack.SE4]:e[3]})))}getFrameSoundEffectFlags(e){const i=this.decodeFrameSoundFlags(e);return{[t.FlipnoteSoundEffectTrack.SE1]:i[0],[t.FlipnoteSoundEffectTrack.SE2]:i[1],[t.FlipnoteSoundEffectTrack.SE3]:i[2],[t.FlipnoteSoundEffectTrack.SE4]:i[3]}}getAudioTrackDuration(e){if(0===this.soundMeta.get(e).length)return 0;const i=this.decodeAudioTrack(e);if(e===t.FlipnoteAudioTrack.BGM){const t=1/this.bgmrate/(1/this.framerate),e=this.rawSampleRate*t;return i.length/e}return i.length/this.sampleRate}getAudioTrackRaw(t){const e=this.soundMeta.get(t);return u(e.ptr+e.length4?(n=3&r,o=T[s],h=o>>3,1&n&&(h+=o),2&n&&(h=-h),i+=h,s+=E[n],r>>=2,u+=2):(n=15&r,o=T[s],h=o>>3,1&n&&(h+=o>>2),2&n&&(h+=o>>1),4&n&&(h+=o),8&n&&(h=-h),i+=h,s+=A[n],r>>=4,u+=4),s=c(s,0,79),i=c(i,-2048,2047),e[a]=16*i,a+=1}return a}decodeAudioTrack(e){const i=o(this,pt,"f"),s=this.getAudioTrackRaw(e),r=60*this.rawSampleRate,a=new Int16Array(r);let n=0,h=40;if(this.isDsiLibraryNote)if(e===t.FlipnoteAudioTrack.BGM){let t=!0;if(null!==i.initialBgmPredictor&&(n=i.initialBgmPredictor,t=!1),null!==i.initialBgmStepIndex&&(h=i.initialBgmStepIndex,t=!1),t&&i.guessInitialBgmState){let t=4294967295,e=0;for(h=0;h<=40;h++){const i=this.decodeAdpcm(s,a,n,h),r=C(a.subarray(0,i));r{const s=t.length,r=s/e*i,a=new Int16Array(r),n=e/i;for(let e=0,i=0,h=0,l=0;er);a++){const s=e[i+a]+t[a];e[i+a]=c(s,-32768,32767)}}getAudioMasterPcm(e=this.sampleRate){const i=Math.ceil(this.duration*e),s=new Int16Array(i),r=this.hasAudioTrack(t.FlipnoteAudioTrack.BGM),a=this.hasAudioTrack(t.FlipnoteAudioTrack.SE1),n=this.hasAudioTrack(t.FlipnoteAudioTrack.SE2),o=this.hasAudioTrack(t.FlipnoteAudioTrack.SE3),h=this.hasAudioTrack(t.FlipnoteAudioTrack.SE4);if(r){const i=this.getAudioTrackPcm(t.FlipnoteAudioTrack.BGM,e);this.pcmAudioMix(i,s,0)}if(a||n||o||h){const i=e/this.framerate,r=a?this.getAudioTrackPcm(t.FlipnoteAudioTrack.SE1,e):null,l=n?this.getAudioTrackPcm(t.FlipnoteAudioTrack.SE2,e):null,c=o?this.getAudioTrackPcm(t.FlipnoteAudioTrack.SE3,e):null,u=h?this.getAudioTrackPcm(t.FlipnoteAudioTrack.SE4,e):null,f=this.decodeSoundFlags();for(let t=0;t16){const t=this.readUint16();h(this,Tt,o(this,Tt,"f")|t<<16-o(this,At,"f"),"f"),h(this,At,o(this,At,"f")-16,"f")}const e=o(this,Tt,"f")&Nt[t];return h(this,Tt,o(this,Tt,"f")>>t,"f"),h(this,At,o(this,At,"f")+t,"f"),e},Ct=function(){return o(this,pt,"f").dsiLibraryNote?this.readHex(10,!0).slice(2,18):ft(this.readHex(10))},xt=function(){const t=this.pointer,e=this.readChars(28);if(28===e.length)return e;this.seek(t);const i=this.readHex(3),s=this.readChars(13),r=this.readUint16().toString().padStart(3,"0");return this.seek(t+28),`${i}_${s}_${r}`},Mt=function(){if(o(this,pt,"f").quickMeta)return o(this,mt,"m",_t).call(this);u(o(this,gt,"f").has("KFH")),this.seek(o(this,gt,"f").get("KFH").ptr+12);const t=M(this.readUint32()),e=M(this.readUint32());this.readUint32();const i=o(this,mt,"m",Ct).call(this),s=o(this,mt,"m",Ct).call(this),r=o(this,mt,"m",Ct).call(this),a=this.readWideChars(11),n=this.readWideChars(11),h=this.readWideChars(11),l=o(this,mt,"m",xt).call(this),c=o(this,mt,"m",xt).call(this),f=o(this,mt,"m",xt).call(this),d=this.readUint16(),m=this.readUint16(),p=this.readUint16(),g=this.readUint8(),y=this.readUint8();this.isSpinoff=r!==s||r!==i,this.frameCount=d,this.frameSpeed=g,this.framerate=It[g],this.duration=B(this.frameCount,this.framerate),this.thumbFrameIndex=m,this.layerVisibility={1:!(1&y),2:!(2&y),3:!(3&y)},this.meta={lock:!!(1&p),loop:!!(2&p),advancedTools:!!(4&p),isSpinoff:this.isSpinoff,frameCount:d,frameSpeed:g,duration:this.duration,thumbIndex:m,timestamp:e,creationTimestamp:t,root:{username:a,fsid:i,region:ut(i),filename:l,isDsiFilename:28!==l.length},parent:{username:n,fsid:s,region:ut(s),filename:c,isDsiFilename:28!==c.length},current:{username:h,fsid:r,region:ut(r),filename:f,isDsiFilename:28!==f.length}}},_t=function(){u(o(this,gt,"f").has("KFH")),this.seek(o(this,gt,"f").get("KFH").ptr+8+196);const t=this.readUint16(),e=this.readUint16();this.readUint16();const i=this.readUint8(),s=this.readUint8();this.frameCount=t,this.thumbFrameIndex=e,this.frameSpeed=i,this.framerate=It[i],this.duration=B(this.frameCount,this.framerate),this.layerVisibility={1:!(1&s),2:!(2&s),3:!(3&s)}},Bt=function(){u(o(this,gt,"f").has("KMI")&&o(this,gt,"f").has("KMC"));const t=this.frameCount,e=o(this,gt,"f").get("KMI"),i=o(this,gt,"f").get("KMC");u(e.length/28>=t);const s=new Uint32Array(t),r=new Uint32Array(t),a=[];let n=e.ptr+8,l=i.ptr+12,c=0;for(let e=0;eS(t)?`${t.slice(14,16)}-${t.slice(12,14)}${t.slice(10,12)}-${t.slice(8,10)}${t.slice(6,8)}-${t.slice(4,6)}${t.slice(2,4)}${t.slice(0,2)}`.toLocaleLowerCase():null;var Vt=Object.freeze({__proto__:null,getFsidRegion:e=>S(e)?F(e):lt(e)?ut(e):t.FlipnoteRegion.UNKNOWN,getKwzFsidRegion:ut,getPpmFsidRegion:F,isFsid:t=>S(t)||lt(t),isKwzDsiLibraryFsid:ct,isKwzFsid:lt,isPpmFsid:S,kwzFsidFormat:ft,kwzFsidToPpmFsid:t=>ct(t)?`${t.slice(19,21)}${t.slice(17,19)}${t.slice(15,17)}${t.slice(12,14)}${t.slice(10,12)}${t.slice(7,9)}${t.slice(5,7)}${t.slice(2,4)}`.toUpperCase():null,kwzFsidUnformat:dt,ppmFsidToKwzFsidSuffix:Gt,ppmFsidToPossibleKwzFsids(t){const e=Gt(t);return e?["00"+e,"10"+e,"12"+e,"14"+e]:null}});const jt=/^[0-9A-Z]{1}[0-9A-F]{5}_[0-9A-F]{13}_[0-9]{3}$/,qt=/^[0-9A-F]{6}_[0-9A-F]{13}_[0-9]{3}$/,Yt=/^[0-5a-z]{28}$/,Xt="cwmfjordvegbalksnthpyxquiz012345";var Qt=Object.freeze({__proto__:null,isKwzFilename:t=>Yt.test(t),isPpmBasicFilename:t=>qt.test(t),isPpmFilename:t=>jt.test(t),kwzFilenameDecode(t){const e=(t=>{const e=t.length;let i=0;const s=new Uint8Array(5*e/8);let r=0,a=0;for(let n=0;n=8&&(s[r++]=a>>>i-8&255,i-=8);return s})(t),i=new DataView(e.buffer);return{fsid:ft(l(e.slice(0,9))),created:M(i.getUint32(9,!0)),edited:M(i.getUint32(13,!0))}},kwzFilenameEncode(t){const e=new Uint8Array(17),i=new DataView(e.buffer),s=dt(t.fsid);return e.set(((t,e=!1)=>{const i=t.length,s=new Uint8Array(i/2);for(let e=0,r=0;e{const e=t.byteLength;let i=0,s="",r=0;for(let a=0;a=5;)s+=Xt[r>>>i-5&31],i-=5;return i>0&&(s+=Xt[r<<5-i&31]),s})(e)},ppmFilenameCalculateCheckDigit(t){let e=parseInt(t.slice(0,2),16);for(let i=1;i<16;i++)e=e+t.charCodeAt(i)&255;return"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"[e%36]},ppmFilenameDecode:t=>({macSuffix:t.slice(0,6),random1:t.slice(7,12),random2:t.slice(12,19),edits:parseInt(t.slice(-3))}),ppmFilenameEncode(t){const e=t.edits.toString().padEnd(3,"0");return`${t.macSuffix}_${t.random1}_${t.random2}_${e}`}});const Jt=[247,76,106,58,251,130,166,55,110,17,56,207,160,221,133,192,199,155,196,216,221,40,138,135,83,32,238,224,11,235,67,160,219,85,15,117,54,55,235,53,106,52,127,181,15,153,247,239,67,37,206,160,41,70,217,212,77,187,4,102,104,8,241,248];class BasePlaylistParser extends DataStream{constructor(t){super(t),this.entries=[]}addEntry(t){const e=t.split("/"),i=e.at(-1),s=t.lastIndexOf(".");this.entries.push({full:t,name:i,base:t.slice(0,s),ext:t.slice(s+1),folder:e.at(-2),parentFolder:e.at(-3)})}}class PpmPlaylist extends BasePlaylistParser{constructor(e){super(e),this.format=t.FlipnoteFormat.PPM;const i=this.bytes,s=this.numBytes;for(let t=0;t=200&&e.status<300,`Failed to load Flipnote from URL, response failed with status ${e.status}`),await e.arrayBuffer()}},te={name:"file",matches(t){return p&&"undefined"!=typeof File&&"undefined"!=typeof FileReader&&t instanceof File},async load(t){return t.arrayBuffer()}},ee={name:"blob",matches(t){return p&&"undefined"!=typeof Blob&&"undefined"!=typeof Response&&t instanceof Blob},async load(t){return t.arrayBuffer()}},ie={name:"node-buffer",matches(t){return y&&t instanceof Buffer},async load(t){return t.buffer}},se={name:"array-buffer",matches(t){return t instanceof ArrayBuffer},async load(t){return t}},re=new Map,ae=t=>{for(let[e,i]of re)if(i.matches(t))try{return i.load(t)}catch(t){d(`Failed to load Flipnote from source, loader "${e}" failed with error ${d}`)}d("No loader available for source type")},ne=t=>{re.set(t.name,t)};ne(se),ne(ie),ne(ee),ne(te),ne(Zt);var oe=Object.freeze({__proto__:null,clear:()=>re.clear(),list:()=>Object.fromEntries(re.entries()),load:ae,register:ne}),he=Object.freeze({__proto__:null,KwzPlaylist,PpmPlaylist,async parse(e,i){const s=await ae(i);return e===t.FlipnoteFormat.PPM||"ppm"===e?new PpmPlaylist(s):e===t.FlipnoteFormat.KWZ||"kwz"===e?new KwzPlaylist(s):void 0}});const le=async(t,e)=>{const i=await ae(t);return PpmParser.matchBuffer(i)?new PpmParser(i,e):KwzParser.matchBuffer(i)?new KwzParser(i,e):void d("Could not identify source as a valid Flipnote file")};var ce;t.PlayerEvent=void 0,(ce=t.PlayerEvent||(t.PlayerEvent={})).__Any="any",ce.Play="play",ce.Pause="pause",ce.CanPlay="canplay",ce.CanPlayThrough="canplaythrough",ce.SeekStart="seeking",ce.SeekEnd="seeked",ce.Duration="durationchange",ce.Loop="loop",ce.Ended="ended",ce.VolumeChange="volumechange",ce.Progress="progress",ce.TimeUpdate="timeupdate",ce.FrameUpdate="frameupdate",ce.FrameNext="framenext",ce.FramePrev="frameprev",ce.FrameFirst="framefirst",ce.FrameLast="framelast",ce.Ready="ready",ce.Load="load",ce.LoadStart="loadstart",ce.LoadedData="loadeddata",ce.LoadedMeta="loadedmetadata",ce.Emptied="emptied",ce.Close="close",ce.Error="error",ce.Destroy="destroy";const ue=[t.PlayerEvent.Play,t.PlayerEvent.Pause,t.PlayerEvent.CanPlay,t.PlayerEvent.CanPlayThrough,t.PlayerEvent.SeekStart,t.PlayerEvent.SeekEnd,t.PlayerEvent.Duration,t.PlayerEvent.Loop,t.PlayerEvent.Ended,t.PlayerEvent.VolumeChange,t.PlayerEvent.Progress,t.PlayerEvent.TimeUpdate,t.PlayerEvent.FrameUpdate,t.PlayerEvent.FrameNext,t.PlayerEvent.FramePrev,t.PlayerEvent.FrameFirst,t.PlayerEvent.FrameLast,t.PlayerEvent.Ready,t.PlayerEvent.Load,t.PlayerEvent.LoadStart,t.PlayerEvent.LoadedData,t.PlayerEvent.LoadedMeta,t.PlayerEvent.Emptied,t.PlayerEvent.Close,t.PlayerEvent.Error],fe=t=>({length:t.length,start:e=>t[e][0],end:e=>t[e][1]}),de=(t,e)=>t.toString().padStart(e,"0"),me=t=>{const e=Math.floor(t%3600/60),i=Math.floor(t%60);return`${e}:${de(i,2)}`};var pe;t.CanvasStereoscopicMode=void 0,(pe=t.CanvasStereoscopicMode||(t.CanvasStereoscopicMode={}))[pe.None=0]="None",pe[pe.Dual=1]="Dual",pe[pe.Anaglyph=2]="Anaglyph";const ge=5120,ye=5121,we=5122,ve=5123,be=5124,Pe=5125,Se=5126,Fe={};{const t=Fe;t[ge]=Int8Array,t[ye]=Uint8Array,t[we]=Int16Array,t[ve]=Uint16Array,t[be]=Int32Array,t[Pe]=Uint32Array,t[Se]=Float32Array,t[32819]=Uint16Array,t[32820]=Uint16Array,t[33635]=Uint16Array,t[5131]=Uint16Array,t[33640]=Uint32Array,t[35899]=Uint32Array,t[35902]=Uint32Array,t[36269]=Uint32Array,t[34042]=Uint32Array}function Ee(t){if(t instanceof Int8Array)return ge;if(t instanceof Uint8Array)return ye;if(t instanceof Uint8ClampedArray)return ye;if(t instanceof Int16Array)return we;if(t instanceof Uint16Array)return ve;if(t instanceof Int32Array)return be;if(t instanceof Uint32Array)return Pe;if(t instanceof Float32Array)return Se;throw new Error("unsupported typed array type")}function Ae(t){if(t===Int8Array)return ge;if(t===Uint8Array)return ye;if(t===Uint8ClampedArray)return ye;if(t===Int16Array)return we;if(t===Uint16Array)return ve;if(t===Int32Array)return be;if(t===Uint32Array)return Pe;if(t===Float32Array)return Se;throw new Error("unsupported typed array type")}const Te="undefined"!=typeof SharedArrayBuffer?function(t){return t&&t.buffer&&(t.buffer instanceof ArrayBuffer||t.buffer instanceof SharedArrayBuffer)}:function(t){return t&&t.buffer&&t.buffer instanceof ArrayBuffer},ke=new Map;function Ue(t,e){if(!t||"object"!=typeof t)return!1;let i=ke.get(e);i||(i=new WeakMap,ke.set(e,i));let s=i.get(t);if(void 0===s){const r=Object.prototype.toString.call(t);s=r.substring(8,r.length-1)===e,i.set(t,s)}return s}function Ce(t,e){return"undefined"!=typeof WebGLTexture&&Ue(e,"WebGLTexture")}const xe=35044,Me=34962,_e=5126,Be="";function Le(t,e,i,s){if("undefined"!=typeof WebGLBuffer&&Ue(e,"WebGLBuffer"))return e;i=i||Me;const r=t.createBuffer();return function(t,e,i,s,r){t.bindBuffer(e,i),t.bufferData(e,s,r||xe)}(t,i,r,e,s),r}function ze(t){return"indices"===t}const Ie=/coord|texture/i,We=/color|colour/i;function Re(t,e){if(Te(t))return t;if(Te(t.data))return t.data;Array.isArray(t)&&(t={data:t});let i=t.type?Ne(t.type):void 0;return i||(i=ze(e)?Uint16Array:Float32Array),new i(t.data)}function Ne(t){return"number"==typeof t?function(t){const e=Fe[t];if(!e)throw new Error("unknown gl type");return e}(t):t||Float32Array}function De(t,e){return{buffer:e.buffer,numValues:24,type:(i=e.type,"number"==typeof i?i:i?Ae(i):_e),arrayType:Ne(e.type)};var i}function Ke(t,e){const i=e.data||e,s=Ne(e.type),r=i*s.BYTES_PER_ELEMENT,a=t.createBuffer();return t.bindBuffer(Me,a),t.bufferData(Me,r,e.drawType||xe),{buffer:a,numValues:i,type:Ae(s),arrayType:s}}function Oe(t,e,i){const s=Re(e,i);return{arrayType:s.constructor,buffer:Le(t,s,void 0,e.drawType),type:Ee(s),numValues:0}}function He(t,e){const i={};return Object.keys(e).forEach((function(s){if(!ze(s)){const a=e[s],n=a.attrib||a.name||a.attribName||Be+s;if(a.value){if(!Array.isArray(a.value)&&!Te(a.value))throw new Error("array.value is not array or typedarray");i[n]={value:a.value}}else{let e;e=a.buffer&&a.buffer instanceof WebGLBuffer?De:"number"==typeof a||"number"==typeof a.data?Ke:Oe;const{buffer:o,type:h,numValues:l,arrayType:c}=e(t,a,s),u=void 0!==a.normalize?a.normalize:(r=c)===Int8Array||r===Uint8Array,f=function(t,e,i){return t.numComponents||t.size||function(t,e){let i;if(i=Ie.test(t)?2:We.test(t)?4:3,e%i>0)throw new Error(`Can not guess numComponents for attribute '${t}'. Tried ${i} but ${e} values is not evenly divisible by ${i}. You should specify it.`);return i}(e,i||function(t){return t.length?t:t.data}(t).length)}(a,s,l);i[n]={buffer:o,numComponents:f,type:h,normalize:u,stride:a.stride||0,offset:a.offset||0,divisor:void 0===a.divisor?void 0:a.divisor,drawType:a.drawType}}}var r})),t.bindBuffer(Me,null),i}const $e=["position","positions","a_position"];function Ge(t){return!!t.texStorage2D}const Ve=33984,je=34962,qe=5124,Ye=3553,Xe=34067,Qe=32879,Je=35866,Ze={};function ti(t,e){return Ze[e].bindPoint}function ei(t,e){return function(i){t.uniform1i(e,i)}}function ii(t,e){return function(i){t.uniform1iv(e,i)}}function si(t,e){return function(i){t.uniform2iv(e,i)}}function ri(t,e){return function(i){t.uniform3iv(e,i)}}function ai(t,e){return function(i){t.uniform4iv(e,i)}}function ni(t,e,i,s){const r=ti(0,e);return Ge(t)?function(e){let a,n;!e||Ce(0,e)?(a=e,n=null):(a=e.texture,n=e.sampler),t.uniform1i(s,i),t.activeTexture(Ve+i),t.bindTexture(r,a),t.bindSampler(i,n)}:function(e){t.uniform1i(s,i),t.activeTexture(Ve+i),t.bindTexture(r,e)}}function oi(t,e,i,s,r){const a=ti(0,e),n=new Int32Array(r);for(let t=0;tfunction(i){t.uniform1f(e,i)},arraySetter:(t,e)=>function(i){t.uniform1fv(e,i)}},Ze[35664]={Type:Float32Array,size:8,setter:(t,e)=>function(i){t.uniform2fv(e,i)},cols:2},Ze[35665]={Type:Float32Array,size:12,setter:(t,e)=>function(i){t.uniform3fv(e,i)},cols:3},Ze[35666]={Type:Float32Array,size:16,setter:(t,e)=>function(i){t.uniform4fv(e,i)},cols:4},Ze[qe]={Type:Int32Array,size:4,setter:ei,arraySetter:ii},Ze[35667]={Type:Int32Array,size:8,setter:si,cols:2},Ze[35668]={Type:Int32Array,size:12,setter:ri,cols:3},Ze[35669]={Type:Int32Array,size:16,setter:ai,cols:4},Ze[5125]={Type:Uint32Array,size:4,setter:(t,e)=>function(i){t.uniform1ui(e,i)},arraySetter:(t,e)=>function(i){t.uniform1uiv(e,i)}},Ze[36294]={Type:Uint32Array,size:8,setter:(t,e)=>function(i){t.uniform2uiv(e,i)},cols:2},Ze[36295]={Type:Uint32Array,size:12,setter:(t,e)=>function(i){t.uniform3uiv(e,i)},cols:3},Ze[36296]={Type:Uint32Array,size:16,setter:(t,e)=>function(i){t.uniform4uiv(e,i)},cols:4},Ze[35670]={Type:Uint32Array,size:4,setter:ei,arraySetter:ii},Ze[35671]={Type:Uint32Array,size:8,setter:si,cols:2},Ze[35672]={Type:Uint32Array,size:12,setter:ri,cols:3},Ze[35673]={Type:Uint32Array,size:16,setter:ai,cols:4},Ze[35674]={Type:Float32Array,size:32,setter:(t,e)=>function(i){t.uniformMatrix2fv(e,!1,i)},rows:2,cols:2},Ze[35675]={Type:Float32Array,size:48,setter:(t,e)=>function(i){t.uniformMatrix3fv(e,!1,i)},rows:3,cols:3},Ze[35676]={Type:Float32Array,size:64,setter:(t,e)=>function(i){t.uniformMatrix4fv(e,!1,i)},rows:4,cols:4},Ze[35685]={Type:Float32Array,size:32,setter:(t,e)=>function(i){t.uniformMatrix2x3fv(e,!1,i)},rows:2,cols:3},Ze[35686]={Type:Float32Array,size:32,setter:(t,e)=>function(i){t.uniformMatrix2x4fv(e,!1,i)},rows:2,cols:4},Ze[35687]={Type:Float32Array,size:48,setter:(t,e)=>function(i){t.uniformMatrix3x2fv(e,!1,i)},rows:3,cols:2},Ze[35688]={Type:Float32Array,size:48,setter:(t,e)=>function(i){t.uniformMatrix3x4fv(e,!1,i)},rows:3,cols:4},Ze[35689]={Type:Float32Array,size:64,setter:(t,e)=>function(i){t.uniformMatrix4x2fv(e,!1,i)},rows:4,cols:2},Ze[35690]={Type:Float32Array,size:64,setter:(t,e)=>function(i){t.uniformMatrix4x3fv(e,!1,i)},rows:4,cols:3},Ze[35678]={Type:null,size:0,setter:ni,arraySetter:oi,bindPoint:Ye},Ze[35680]={Type:null,size:0,setter:ni,arraySetter:oi,bindPoint:Xe},Ze[35679]={Type:null,size:0,setter:ni,arraySetter:oi,bindPoint:Qe},Ze[35682]={Type:null,size:0,setter:ni,arraySetter:oi,bindPoint:Ye},Ze[36289]={Type:null,size:0,setter:ni,arraySetter:oi,bindPoint:Je},Ze[36292]={Type:null,size:0,setter:ni,arraySetter:oi,bindPoint:Je},Ze[36293]={Type:null,size:0,setter:ni,arraySetter:oi,bindPoint:Xe},Ze[36298]={Type:null,size:0,setter:ni,arraySetter:oi,bindPoint:Ye},Ze[36299]={Type:null,size:0,setter:ni,arraySetter:oi,bindPoint:Qe},Ze[36300]={Type:null,size:0,setter:ni,arraySetter:oi,bindPoint:Xe},Ze[36303]={Type:null,size:0,setter:ni,arraySetter:oi,bindPoint:Je},Ze[36306]={Type:null,size:0,setter:ni,arraySetter:oi,bindPoint:Ye},Ze[36307]={Type:null,size:0,setter:ni,arraySetter:oi,bindPoint:Qe},Ze[36308]={Type:null,size:0,setter:ni,arraySetter:oi,bindPoint:Xe},Ze[36311]={Type:null,size:0,setter:ni,arraySetter:oi,bindPoint:Je};const fi={};function di(t){const e=t.name;return e.startsWith("gl_")||e.startsWith("webgl_")}fi[5126]={size:4,setter:hi},fi[35664]={size:8,setter:hi},fi[35665]={size:12,setter:hi},fi[35666]={size:16,setter:hi},fi[qe]={size:4,setter:li},fi[35667]={size:8,setter:li},fi[35668]={size:12,setter:li},fi[35669]={size:16,setter:li},fi[5125]={size:4,setter:ci},fi[36294]={size:8,setter:ci},fi[36295]={size:12,setter:ci},fi[36296]={size:16,setter:ci},fi[35670]={size:4,setter:li},fi[35671]={size:8,setter:li},fi[35672]={size:12,setter:li},fi[35673]={size:16,setter:li},fi[35674]={size:4,setter:ui,count:2},fi[35675]={size:9,setter:ui,count:3},fi[35676]={size:16,setter:ui,count:4};const mi=/(\.|\[|]|\w+)/g,pi=t=>t>="0"&&t<="9";function gi(t,e,i,s){const r=t.split(mi).filter((t=>""!==t));let a=0,n="";for(;;){const t=r[a++];n+=t;const o=pi(t[0]),h=o?parseInt(t):t;if(o&&(n+=r[a++]),a===r.length){i[h]=e;break}{const t=r[a++],e="["===t,o=i[h]||(e?[]:{});i[h]=o,i=o,s[n]=s[n]||function(t){return function(e){yi(t,e)}}(o),n+=t}}}function yi(t,e){for(const i in e){const s=t[i];"function"==typeof s?s(e[i]):yi(t[i],e[i])}}function wi(t,...e){const i=t.uniformSetters||t,s=e.length;for(let t=0;t{this.destroy(),t&&t.preventDefault(),o(this,zi,"f")||o(this,bi,"f").onlost(),h(this,zi,!0,"f")})),Xi.set(this,(t=>{h(this,zi,!1,"f"),o(this,vi,"m",Ii).call(this),o(this,bi,"f").onrestored()})),g(),h(this,bi,{...WebglCanvas.defaultOptions,...r},"f"),this.width=i,this.height=s,this.canvas=document.createElement("canvas"),this.canvas.addEventListener("webglcontextlost",o(this,Yi,"f"),!1),this.canvas.addEventListener("webglcontextrestored",o(this,Xi,"f"),!1),this.canvas.className="FlipnoteCanvas FlipnoteCanvas--webgl",this.gl=this.canvas.getContext("webgl",{antialias:!1,alpha:!0}),e&&e.appendChild(this.canvas),o(this,vi,"m",Ii).call(this)}setCanvasSize(t,e){const i=o(this,bi,"f").useDpi&&window.devicePixelRatio||1,s=t*i,r=e*i;this.width=t,this.height=e,this.canvas.width=s,this.canvas.height=r,this.dstWidth=s,this.dstHeight=r,this.canvas.style.width=`${t}px`,this.canvas.style.height=`${e}px`,o(this,vi,"m",qi).call(this)}setNote(t){if(o(this,vi,"m",qi).call(this))return;const e=t.imageWidth,i=t.imageHeight;this.note=t,this.srcWidth=e,this.srcHeight=i,o(this,vi,"m",ji).call(this,o(this,Ci,"f"),e,i),o(this,vi,"m",$i).call(this,o(this,Ai,"f"),e,i),h(this,Ti,new Uint32Array(e*i),"f"),h(this,ki,new Uint8Array(o(this,Ti,"f").buffer),"f"),this.frameIndex=void 0,this.canvas.title=t.getTitle()}clear(t){if(o(this,vi,"m",qi).call(this))return;const e=this.gl,i=t??this.note.getFramePalette(this.frameIndex)[0],[s,r,a,n]=i;e.clearColor(s/255,r/255,a/255,n/255),e.clear(e.COLOR_BUFFER_BIT)}drawFrame(e){if(o(this,vi,"m",qi).call(this))return;const i=this.gl,s=this.stereoscopeMode,r=this.stereoscopeStrength;this.frameIndex=e,s===t.CanvasStereoscopicMode.None?(o(this,vi,"m",Wi).call(this,e),o(this,vi,"m",Vi).call(this,null),o(this,vi,"m",Ri).call(this,i.drawingBufferWidth,i.drawingBufferHeight)):s===t.CanvasStereoscopicMode.Dual&&(o(this,vi,"m",Wi).call(this,e,r,t.FlipnoteStereoscopicEye.Left),o(this,vi,"m",Vi).call(this,null,0,0,i.drawingBufferWidth/2,i.drawingBufferHeight),o(this,vi,"m",Ri).call(this,i.drawingBufferWidth/2,i.drawingBufferHeight),o(this,vi,"m",Wi).call(this,e,r,t.FlipnoteStereoscopicEye.Right),o(this,vi,"m",Vi).call(this,null,i.drawingBufferWidth/2,0,i.drawingBufferWidth/2,i.drawingBufferHeight),o(this,vi,"m",Ri).call(this,i.drawingBufferWidth/2,i.drawingBufferHeight))}requestStereoScopeMode(e){this.supportedStereoscopeModes.includes(e)?this.stereoscopeMode=e:this.stereoscopeMode=t.CanvasStereoscopicMode.None,this.forceUpdate()}forceUpdate(){void 0!==this.frameIndex&&this.drawFrame(this.frameIndex)}isErrorState(){const t=this.gl;return null===t||t.getError()!==t.NO_ERROR}getDataUrl(t,e){return this.canvas.toDataURL(t,e)}async getBlob(t,e){return new Promise(((i,s)=>this.canvas.toBlob(i,t,e)))}destroy(){const t=o(this,Li,"f"),e=this.gl,i=this.canvas;t.shaders.forEach((t=>{e.deleteShader(t)})),t.shaders=[],t.textures.forEach((t=>{e.deleteTexture(t)})),t.textures=[],t.buffers.forEach((t=>{e.deleteBuffer(t)})),t.buffers=[],t.frameBuffers.forEach((t=>{e.deleteFramebuffer(t)})),t.frameBuffers=[],t.programs.forEach((t=>{e.deleteProgram(t)})),t.programs=[],h(this,Ei,null,"f"),h(this,Ti,null,"f"),h(this,ki,null,"f"),o(this,xi,"f").clear(),o(this,Mi,"f").clear(),o(this,_i,"f").clear(),i&&i.parentElement&&(i.width=1,i.height=1,i.parentNode.removeChild(i))}}bi=new WeakMap,Pi=new WeakMap,Si=new WeakMap,Fi=new WeakMap,Ei=new WeakMap,Ai=new WeakMap,Ti=new WeakMap,ki=new WeakMap,Ui=new WeakMap,Ci=new WeakMap,xi=new WeakMap,Mi=new WeakMap,_i=new WeakMap,Bi=new WeakMap,Li=new WeakMap,zi=new WeakMap,Yi=new WeakMap,Xi=new WeakMap,vi=new WeakSet,Ii=function(){this.setCanvasSize(this.width,this.height);const t=this.gl;if(o(this,vi,"m",qi).call(this))return;h(this,Pi,o(this,vi,"m",Ni).call(this,"#define GLSLIFY 1\nattribute vec4 position;attribute vec2 texcoord;varying vec2 v_uv;uniform bool u_flipY;uniform vec2 u_textureSize;uniform int u_3d_eye;uniform float u_3d_depth;uniform float u_3d_strength;void main(){vec4 pos=position;float depthDirection=u_3d_eye==0 ?-1.0 : 1.0;float depthShift=floor(u_3d_depth*u_3d_strength)/(u_textureSize.x/2.0)*depthDirection;pos.x+=depthShift;pos.y*=u_flipY ?-1.0 : 1.0;v_uv=texcoord;gl_Position=pos;}","precision highp float;\n#define GLSLIFY 1\nvarying vec2 v_uv;uniform sampler2D u_tex;uniform int u_3d_mode;void main(){vec4 col=texture2D(u_tex,v_uv);if(col.a==0.0){discard;}gl_FragColor=col;}"),"f"),h(this,Si,o(this,vi,"m",Ni).call(this,"#define GLSLIFY 1\nattribute vec4 position;attribute vec2 texcoord;varying vec2 v_texel;varying vec2 v_uv;varying float v_scale;uniform bool u_flipY;uniform vec2 u_textureSize;uniform vec2 u_screenSize;void main(){v_uv=texcoord;v_scale=floor(u_screenSize.y/u_textureSize.y+0.01);gl_Position=position;if(u_flipY){gl_Position.y*=-1.;}}","precision highp float;\n#define GLSLIFY 1\nvarying vec2 v_uv;uniform sampler2D u_tex;varying float v_scale;uniform vec2 u_textureSize;uniform vec2 u_screenSize;void main(){vec2 v_texel=v_uv*u_textureSize;vec2 texel_floored=floor(v_texel);vec2 s=fract(v_texel);float region_range=0.5-0.5/v_scale;vec2 center_dist=s-0.5;vec2 f=(center_dist-clamp(center_dist,-region_range,region_range))*v_scale+0.5;vec2 mod_texel=texel_floored+f;vec2 coord=mod_texel.xy/u_textureSize.xy;gl_FragColor=texture2D(u_tex,coord);}"),"f"),h(this,Fi,o(this,vi,"m",Ki).call(this,-1,-1,2,2,1,1),"f"),o(this,vi,"m",Oi).call(this,o(this,Pi,"f"),o(this,Fi,"f")),h(this,Ai,o(this,vi,"m",Hi).call(this,t.RGBA,t.LINEAR,t.CLAMP_TO_EDGE),"f"),h(this,Ui,o(this,vi,"m",Hi).call(this,t.RGBA,t.LINEAR,t.CLAMP_TO_EDGE),"f"),h(this,Ci,o(this,vi,"m",Gi).call(this,o(this,Ui,"f")),"f");const e=t.getExtension("WEBGL_debug_renderer_info"),i=t.getParameter(e.UNMASKED_RENDERER_WEBGL),s=navigator.userAgent,r=s.includes("Firefox")&&s.includes("Mac");h(this,Bi,r&&i.includes("Apple M"),"f")},Wi=function(e,i=0,s=t.FlipnoteStereoscopicEye.Left,r=!0){const a=this.gl,n=this.note,h=this.srcWidth,l=this.srcHeight,c=n.numLayers,u=n.getFrameLayerOrder(e),f=n.getFrameLayerDepths(e);o(this,vi,"m",Vi).call(this,o(this,Ci,"f")),r&&this.clear(),a.useProgram(o(this,Pi,"f").program);for(let t=0;tthis.canvas.toBlob(i,t,e)))}destroy(){h(this,ts,null,"f"),h(this,es,null,"f"),h(this,is,null,"f"),this.canvas.parentNode.removeChild(this.canvas),this.canvas.width=1,this.canvas.height=1,this.canvas=null,o(this,Ji,"f").width=1,o(this,Ji,"f").height=1,h(this,Ji,null,"f")}}Qi=new WeakMap,Ji=new WeakMap,Zi=new WeakMap,ts=new WeakMap,es=new WeakMap,is=new WeakMap,Html5Canvas.defaultOptions={useDpi:!0,useSmoothing:!0};class UniversalCanvas{constructor(e,i=640,s=480,r={}){ss.add(this),this.isReady=!1,this.isHtml5=!1,this.supportedStereoscopeModes=[],this.stereoscopeMode=t.CanvasStereoscopicMode.None,this.stereoscopeStrength=1,rs.set(this,[WebglCanvas,Html5Canvas]),as.set(this,0),ns.set(this,void 0),os.set(this,{}),this.width=i,this.height=s,h(this,ns,e,"f"),h(this,os,r,"f"),o(this,ss,"m",hs).call(this,o(this,rs,"f")[0])}fallbackIfPossible(){if(o(this,as,"f")>=o(this,rs,"f").length)throw new Error("No renderer to fall back to");h(this,as,o(this,as,"f")+1,"f"),o(this,ss,"m",hs).call(this,o(this,rs,"f")[o(this,as,"f")])}switchToHtml5(){o(this,ss,"m",hs).call(this,Html5Canvas)}setCanvasSize(t,e){const i=this.renderer;i.setCanvasSize(t,e),this.width=t,this.width=e,this.dstWidth=i.dstWidth,this.dstHeight=i.dstHeight}setNote(t){this.note=t,this.renderer.setNote(t),this.frameIndex=void 0,this.srcWidth=this.renderer.srcWidth,this.srcHeight=this.renderer.srcHeight}clear(t){this.renderer.clear(t)}drawFrame(t){this.renderer.drawFrame(t),this.frameIndex=t}forceUpdate(){this.renderer.forceUpdate()}requestStereoScopeMode(t){this.renderer.requestStereoScopeMode(t),this.stereoscopeMode=this.renderer.stereoscopeMode}getDataUrl(t,e){return this.renderer.getDataUrl()}async getBlob(t,e){return this.renderer.getBlob()}destroy(){this.renderer.destroy(),this.note=null}}rs=new WeakMap,as=new WeakMap,ns=new WeakMap,os=new WeakMap,ss=new WeakSet,hs=function(t){let e=!1;const i=new t(o(this,ns,"f"),this.width,this.height,{...o(this,os,"f"),onlost:()=>{e=!0,this.fallbackIfPossible()}});e||(this.note&&(i.setNote(this.note),i.frameIndex=this.renderer?.frameIndex,i.forceUpdate()),this.renderer&&this.renderer.destroy(),this.isHtml5=i instanceof Html5Canvas,this.isReady=!0,this.renderer=i,h(this,as,o(this,rs,"f").indexOf(t),"f"),this.supportedStereoscopeModes=i.supportedStereoscopeModes,i.stereoscopeStrength=this.stereoscopeStrength,this.requestStereoScopeMode(this.stereoscopeMode))};const Ps=p?window.AudioContext||window.webkitAudioContext:null;class WebAudioPlayer{constructor(){ls.add(this),this.useEq=!1,this.useAnalyser=!1,this.eqSettings=[[31.25,4.1],[62.5,1.2],[125,0],[250,-4.1],[500,-2.3],[1e3,.5],[2e3,6.5],[8e3,5.1],[16e3,5.1]],cs.set(this,1),us.set(this,!1),fs.set(this,0),ds.set(this,0),ms.set(this,[]),ps.set(this,void 0),gs.set(this,void 0),ys.set(this,void 0),g()}set volume(t){this.setVolume(t)}get volume(){return o(this,cs,"f")}set loop(t){h(this,us,t,"f"),o(this,ys,"f")&&(o(this,ys,"f").loop=t)}get loop(){return o(this,us,"f")}setBuffer(t,e){const i=o(this,ls,"m",ws).call(this),s=t.length,r=i.createBuffer(1,s,e),a=r.getChannelData(0);if(t instanceof Float32Array)a.set(t,0);else if(t instanceof Int16Array)for(let e=0;et.disconnect())),h(this,ms,[],"f"),this.analyser=void 0,"closed"!==t.state&&"function"==typeof t.close&&await t.close(),h(this,ps,null,"f")}}var Ss,Fs,Es;cs=new WeakMap,us=new WeakMap,fs=new WeakMap,ds=new WeakMap,ms=new WeakMap,ps=new WeakMap,gs=new WeakMap,ys=new WeakMap,ls=new WeakSet,ws=function(){return this.ctx||(this.ctx=new Ps),this.ctx},vs=function(t){const e=o(this,ls,"m",ws).call(this),i=this.eqSettings;let s=t;return i.forEach((([t,r],a)=>{const n=e.createBiquadFilter();o(this,ms,"f").push(n),n.frequency.value=t,n.gain.value=r,0===a?n.type="lowshelf":a===i.length-1?n.type="highshelf":n.type="peaking",s.connect(n),s=n})),s},bs=function(){const t=o(this,ls,"m",ws).call(this);h(this,ms,[],"f");const e=t.createBufferSource();o(this,ms,"f").push(e),e.buffer=o(this,ps,"f");const i=t.createGain();if(o(this,ms,"f").push(i),this.useEq?o(this,ls,"m",vs).call(this,e).connect(i):e.connect(i),this.useAnalyser){const e=t.createAnalyser();o(this,ms,"f").push(e),this.analyser=e,i.connect(e),e.connect(t.destination)}else this.analyser=void 0,i.connect(t.destination);h(this,ys,e,"f"),h(this,gs,i,"f"),this.setVolume(o(this,cs,"f"))};class Player{constructor(e,i,s,r={}){Ss.add(this),this.duration=0,this.autoplay=!1,this.supportedEvents=ue,this._src=null,this._loop=!1,this._volume=1,this._muted=!1,this._frame=null,this._hasEnded=!1,this.isNoteLoaded=!1,this.events=new Map,this.playbackStartTime=0,this.playbackTime=0,this.playbackLoopId=null,this.showThumbnail=!0,this.hasPlaybackStarted=!1,this.isPlaying=!1,this.wasPlaying=!1,this.isSeeking=!1,this.playbackLoop=e=>{if(!this.isPlaying)return;const i=e/1e3,s=this.duration,r=this.audio.getCurrentTime();let a=i-this.playbackStartTime;if(Math.abs(a%s-r%s)>.01&&(a=r),a>=s){if(!this.loop)return this.pause(),this._hasEnded=!0,void this.emit(t.PlayerEvent.Ended);this.playbackStartTime=i,this.emit(t.PlayerEvent.Loop)}this.setCurrentTime(a%s),this.playbackLoopId=requestAnimationFrame(this.playbackLoop)},g();const a="string"==typeof e?document.querySelector(e):e;this.parserSettings=r,this.renderer=new UniversalCanvas(a,i,s,{onlost:()=>this.emit(t.PlayerEvent.Error),onrestored:()=>this.reload()}),this.audio=new WebAudioPlayer,this.el=a}get src(){return this._src}set src(t){throw new Error("Setting a Player source has been deprecated, please use the load() method instead")}get paused(){return!this.isPlaying}set paused(t){t?this.pause():this.play()}get currentFrame(){return this._frame}set currentFrame(t){this.setCurrentFrame(t)}get currentTime(){return this.isNoteLoaded?this.playbackTime:null}set currentTime(t){this.setCurrentTime(t)}get progress(){return this.isNoteLoaded?this.playbackTime/this.duration*100:null}set progress(t){this.setProgress(t)}get volume(){return this.getVolume()}set volume(t){this.setVolume(t)}get muted(){return this.getMuted()}set muted(t){this.setMuted(t)}get loop(){return this.getLoop()}set loop(t){this.setLoop(t)}get framerate(){return this.note.framerate}get frameCount(){return this.note.frameCount}get frameSpeed(){return this.note.frameSpeed}get buffered(){return fe([[0,this.duration]])}get seekable(){return fe([[0,this.duration]])}get currentSrc(){return this._src}get videoWidth(){return this.isNoteLoaded?this.note.imageWidth:0}get videoHeight(){return this.isNoteLoaded?this.note.imageHeight:0}async load(e){if(this.isNoteLoaded&&this.closeNote(),this._src=e,!e)return this.openNote(this.note);this.emit(t.PlayerEvent.LoadStart);const[i,s]=await(async t=>{try{return[null,await t().catch((t=>{throw t}))]}catch(t){return[t,null]}})((()=>le(e,this.parserSettings)));if(i)throw this.emit(t.PlayerEvent.Error,i),new Error(`Error loading Flipnote: ${i.message}`);this.openNote(s)}async reload(){if(this.note)return await this.load(this.note.buffer)}async updateSettings(t){return this.parserSettings=t,await this.reload()}closeNote(){this.pause(),this.note=null,this.isNoteLoaded=!1,this.meta=null,this._src=null,this._frame=0,this.playbackTime=0,this.duration=0,this.loop=!1,this.isPlaying=!1,this.wasPlaying=!1,this.hasPlaybackStarted=!1,this.showThumbnail=!0,this.renderer.clear()}openNote(e){this.isNoteLoaded&&this.closeNote(),this.note=e,this.meta=e.meta,this.emit(t.PlayerEvent.LoadedMeta),this.noteFormat=e.format,this.duration=e.duration,this.playbackTime=0,this._frame=0,this.isNoteLoaded=!0,this.isPlaying=!1,this.wasPlaying=!1,this.hasPlaybackStarted=!1,this.layerVisibility=e.layerVisibility,this.showThumbnail=!0,this.audio.setBuffer(e.getAudioMasterPcm(),e.sampleRate),this.emit(t.PlayerEvent.CanPlay),this.emit(t.PlayerEvent.CanPlayThrough),this.setLoop(e.meta.loop),this.renderer.setNote(e),this.drawFrame(e.thumbFrameIndex),this.emit(t.PlayerEvent.LoadedData),this.emit(t.PlayerEvent.Load),this.emit(t.PlayerEvent.Ready),this.autoplay&&this.play()}setCurrentTime(e){this.assertNoteLoaded();const i=Math.floor(e/(1/this.framerate));this.setCurrentFrame(i),this.playbackTime=e,this.emit(t.PlayerEvent.Progress,this.progress)}getCurrentTime(){return this.currentTime}getTimeCounter(){return`${me(Math.max(this.currentTime,0))} / ${me(this.duration)}`}getFrameCounter(){return`${de(this.currentFrame+1,3)} / ${de(this.frameCount,3)}`}setProgress(t){this.assertNoteLoaded(),f(t,0,100,"progress"),this.currentTime=this.duration*(t/100)}getProgress(){return this.progress}async play(){if(this.assertNoteLoaded(),this.isPlaying)return;this._hasEnded&&(this.playbackTime=0,this._hasEnded=!1);const e=performance.now();this.playbackStartTime=e/1e3-this.playbackTime,this.isPlaying=!0,this.hasPlaybackStarted=!0,o(this,Ss,"m",Fs).call(this),this.playbackLoop(e),this.emit(t.PlayerEvent.Play)}pause(){this.isPlaying&&(this.isPlaying=!1,null!==this.playbackLoopId&&cancelAnimationFrame(this.playbackLoopId),o(this,Ss,"m",Es).call(this),this.emit(t.PlayerEvent.Pause))}togglePlay(){this.isPlaying?this.pause():this.play()}getPaused(){return!this.isPlaying}getDuration(){return this.duration}getLoop(){return this._loop}setLoop(t){this._loop=t,this.audio.loop=t}toggleLoop(){this.setLoop(!this._loop)}setCurrentFrame(e){this.assertNoteLoaded();const i=Math.max(0,Math.min(Math.floor(e),this.frameCount-1));(i!==this.currentFrame||this.showThumbnail)&&(this._frame=i,this.drawFrame(i),this.showThumbnail=!1,this.isPlaying||(this.playbackTime=i*(1/this.framerate),this.emit(t.PlayerEvent.SeekEnd)),this.emit(t.PlayerEvent.FrameUpdate,this.currentFrame),this.emit(t.PlayerEvent.Progress,this.progress),this.emit(t.PlayerEvent.TimeUpdate,this.currentFrame))}nextFrame(){this.loop&&this.currentFrame===this.frameCount-1?this.currentFrame=0:this.currentFrame+=1,this.emit(t.PlayerEvent.FrameNext)}prevFrame(){this.loop&&0===this.currentFrame?this.currentFrame=this.frameCount-1:this.currentFrame-=1,this.emit(t.PlayerEvent.FramePrev)}lastFrame(){this.currentFrame=this.frameCount-1,this.emit(t.PlayerEvent.FrameLast)}firstFrame(){this.currentFrame=0,this.emit(t.PlayerEvent.FrameFirst)}thumbnailFrame(){this.currentFrame=this.note.thumbFrameIndex}startSeek(){this.isSeeking||(this.emit(t.PlayerEvent.SeekStart),this.wasPlaying=this.isPlaying,this.pause(),this.isSeeking=!0)}seek(t){this.isSeeking&&(this.progress=100*t)}endSeek(){this.isSeeking&&!0===this.wasPlaying&&this.play(),this.wasPlaying=!1,this.isSeeking=!1}drawFrame(t){this.renderer.drawFrame(t)}forceUpdate(){this.renderer.forceUpdate()}resize(t,e){e!==.75*t&&console.warn(`Canvas width to height ratio should be 3:4 for best results (got ${t}x${e})`),this.renderer.setCanvasSize(t,e),this.forceUpdate()}setLayerVisibility(t,e){this.note.layerVisibility[t]=e,this.layerVisibility[t]=e,this.forceUpdate()}getLayerVisibility(t){return this.layerVisibility[t]}toggleLayerVisibility(t){this.setLayerVisibility(t,!this.layerVisibility[t])}toggleAudioEq(){this.setAudioEq(!this.audio.useEq)}setAudioEq(t){this.isPlaying&&(this.wasPlaying=!0,o(this,Ss,"m",Es).call(this)),this.audio.useEq=t,this.wasPlaying&&(this.wasPlaying=!1,o(this,Ss,"m",Fs).call(this))}mute(){this.setMuted(!0)}unmute(){this.setMuted(!1)}setMuted(e){this.audio.volume=e?0:this._volume,this._muted=e,this.emit(t.PlayerEvent.VolumeChange,this.audio.volume)}getMuted(){return 0===this.volume||this._muted}toggleMuted(){this.setMuted(!this._muted)}setVolume(e){f(e,0,1,"volume"),this._volume=e,this.audio.volume=e,this.emit(t.PlayerEvent.VolumeChange,this.audio.volume)}getVolume(){return this._muted?0:this._volume}seekToNextFrame(){this.nextFrame()}fastSeek(t){this.currentTime=t}canPlayType(t){switch(t){case"application/x-ppm":case"application/x-kwz":case"video/x-ppm":case"video/x-kwz":case"video/vnd.nintendo.ugomemo.ppm":case"video/vnd.nintendo.ugomemo.kwz":return"probably";case"application/octet-stream":return"maybe";default:return""}}getVideoPlaybackQuality(){return{creationTime:0,droppedVideoFrames:0,corruptedVideoFrames:0,totalVideoFrames:this.frameCount}}requestPictureInPicture(){throw new Error("Not implemented")}captureStream(){throw new Error("Not implemented")}on(t,e){const i=this.events;(Array.isArray(t)?t:[t]).forEach((t=>{i.has(t)?i.get(t).push(e):i.set(t,[e])}))}off(t,e){const i=this.events;(Array.isArray(t)?t:[t]).forEach((t=>{if(!i.has(t))return;const s=i.get(t);i.set(t,s.splice(s.indexOf(e),1))}))}emit(e,...i){const s=this.events;if(e!==t.PlayerEvent.__Any&&s.has(e)){s.get(e).forEach((t=>t.apply(null,i)));const t=`on${e}`,r=this;"function"==typeof r[t]&&r[t].apply(null,i)}s.has(t.PlayerEvent.__Any)&&s.get(t.PlayerEvent.__Any).forEach((t=>t.apply(null,[e,...i])))}clearEvents(){this.events.clear()}async destroy(){this.clearEvents(),this.emit(t.PlayerEvent.Destroy),this.closeNote(),await this.renderer.destroy(),await this.audio.destroy()}assertNoteLoaded(){u(this.isNoteLoaded,"No Flipnote is currently loaded in this player")}}Ss=new WeakSet,Fs=function(){this.audio.playFrom(this.currentTime)},Es=function(){this.audio.stop()};class EncoderBase{constructor(){this.dataUrl=null}getBuffer(){return u(y,"This feature is only available in NodeJS environments"),Buffer.from(this.getArrayBuffer())}getBlob(){return g(),new Blob([this.getArrayBuffer()],{type:this.mimeType})}getUrl(){return g(),this.dataUrl?this.dataUrl:window.URL.createObjectURL(this.getBlob())}revokeUrl(){g(),this.dataUrl&&window.URL.revokeObjectURL(this.dataUrl)}}const As=5003,Ts=[0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535];class LzwCompressor{constructor(t,e,i){this.accum=new Uint8Array(256),this.htab=new Int32Array(As),this.codetab=new Int32Array(As),this.cur_accum=0,this.cur_bits=0,this.curPixel=0,this.free_ent=0,this.clear_flg=!1,this.g_init_bits=void 0,this.ClearCode=void 0,this.EOFCode=void 0,this.width=t,this.height=e,this.colorDepth=i,this.reset()}reset(){this.initCodeSize=Math.max(2,this.colorDepth),this.accum.fill(0),this.htab.fill(0),this.codetab.fill(0),this.cur_accum=0,this.cur_bits=0,this.curPixel=0,this.free_ent=0,this.maxcode,this.clear_flg=!1,this.g_init_bits=void 0,this.ClearCode=void 0,this.EOFCode=void 0}char_out(t,e){this.accum[this.a_count++]=t,this.a_count>=254&&this.flush_char(e)}cl_block(t){this.cl_hash(As),this.free_ent=this.ClearCode+2,this.clear_flg=!0,this.output(this.ClearCode,t)}cl_hash(t){for(var e=0;e=0){n=o-r,0===r&&(n=1);do{if((r-=n)<0&&(r+=o),this.htab[r]===i){a=this.codetab[r];continue t}}while(this.htab[r]>=0)}this.output(a,e),a=s,this.free_ent<4096?(this.codetab[r]=this.free_ent++,this.htab[r]=i):this.cl_block(e)}else a=this.codetab[r];this.output(a,e),this.output(this.EOFCode,e)}encode(t,e){this.pixels=t,e.writeByte(this.initCodeSize),this.remaining=this.width*this.height,this.curPixel=0,this.compress(this.initCodeSize+1,e),e.writeByte(0)}flush_char(t){this.a_count>0&&(t.writeByte(this.a_count),t.writeBytes(this.accum,0,this.a_count),this.a_count=0)}get_maxcode(t){return(1<0?this.cur_accum|=t<=8;)this.char_out(255&this.cur_accum,e),this.cur_accum>>=8,this.cur_bits-=8;if((this.free_ent>this.maxcode||this.clear_flg)&&(this.clear_flg?(this.maxcode=this.get_maxcode(this.n_bits=this.g_init_bits),this.clear_flg=!1):(++this.n_bits,12==this.n_bits?this.maxcode=4096:this.maxcode=this.get_maxcode(this.n_bits))),t==this.EOFCode){for(;this.cur_bits>0;)this.char_out(255&this.cur_accum,e),this.cur_accum>>=8,this.cur_bits-=8;this.flush_char(e)}}}var ks,Us,Cs,xs,Ms,_s,Bs,Ls,zs,Is,Ws,Rs,Ns,Ds,Ks;class GifImage extends EncoderBase{constructor(t,e,i={}){super(),ks.add(this),this.mimeType="gif/image",this.frameCount=0,Us.set(this,void 0),Cs.set(this,void 0),this.width=t,this.height=e,h(this,Us,new ByteArray,"f"),this.settings={...GifImage.defaultSettings,...i},h(this,Cs,new LzwCompressor(t,e,i.colorDepth),"f")}static fromFlipnote(t,e={}){const i=new GifImage(t.imageWidth,t.imageHeight,{delay:100/t.framerate,repeat:t.meta?.loop?-1:0,...e});i.palette=t.globalPalette;for(let e=0;e(console.warn("parseSource() is deprecated, please use parse() instead"),le(...t)),t.playlist=he,t.supportedEvents=ue,t.version="6.3.0"}({}); //# sourceMappingURL=flipnote.min.js.map