/*!! flipnote.js v5.11.0 https://flipnote.js.org A JavaScript library for parsing, converting, and in-browser playback of the proprietary animation formats used by Nintendo's Flipnote Studio and Flipnote Studio 3D apps. 2018 - 2022 James Daniel Flipnote Studio is (c) Nintendo Co., Ltd. This project isn't affiliated with or endorsed by them in any way. Keep on Flipnoting! */ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).flipnote={})}(this,(function(t){"use strict";class e{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;ithis.writeUint8(t))}readHex(t,e=!1){const i=this.readBytes(t);let s=[];for(let t=0;ti?i:t}function o(t,e,i){return i<0||i>=e?0:t[i]}function h(t){const e=t.length;let i=0;for(let s=0;s=32767)&&(i+=1)}return i/e}function l(t){const e=t.length;let i=0;for(let s=0;s=e&&t<=i,`${s||"value"} ${t} should be between ${e} and ${i}`)}function u(t,e){try{return t.require(e)}catch(t){throw new Error(`Could not require(${e})`)}}function f(){return g?global:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{}}const p="undefined"!=typeof window&&void 0!==window.document;function m(){return c(p,"This feature is only available in browser environments")}const g="undefined"!=typeof process&&null!=process.versions&&null!=process.versions.node;function y(){return c(g,"This feature is only available in NodeJS environments")}const v="object"==typeof self&&self.constructor&&"DedicatedWorkerGlobalScope"===self.constructor.name,S=p&&(window.requestAnimationFrame||window.webkitRequestAnimationFrame);const b=(()=>{if(p||v){const t=f();return(t.crypto||t.msCrypto).subtle}if(g)return u(module,"crypto").webcrypto.subtle})();async function w(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 b.importKey("spki",r.buffer,{name:"RSASSA-PKCS1-v1_5",hash:e},!1,["verify"])}async function _(t,e,i){return await b.verify("RSASSA-PKCS1-v1_5",t,e,i)}function x(t){return new Date(1e3*(t+946684800))}function E(t,e){return 100*t*(1/e)/100}var P;t.FlipnoteRegion=void 0,(P=t.FlipnoteRegion||(t.FlipnoteRegion={})).EUR="EUR",P.USA="USA",P.JPN="JPN",P.UNKNOWN="UNKNOWN";const F=/^[0159]{1}[0-9A-F]{6}0[0-9A-F]{8}$/,A=/^[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{6}$/,T=/^(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}$/,C=["01FACA7A4367FC5F","03D6E959E2F9A42D","03F80445160587FA","04068426E1008915","092A3EC8199FD5D5","0B8D56BA1BD441B8","0E61C75C9B5AD90B","14E494E35A443235"],k=C.map(t=>R(t));function U(t){return F.test(t)||C.includes(t)}function B(t){return A.test(t)}function L(t){if(T.test(t))return!0;for(let e of k)if(t.endsWith(e))return!0;return!1}function M(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}}function I(e){if(L(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}switch(e.slice(0,2)){case"00":return t.FlipnoteRegion.JPN;case"02":return t.FlipnoteRegion.USA;case"04":return t.FlipnoteRegion.EUR;default:return t.FlipnoteRegion.UNKNOWN}}function N(t){return T.test(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}function R(t){return F.test(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)).toLowerCase():null}var z,O,D,W,V,H=Object.freeze({__proto__:null,get FlipnoteRegion(){return t.FlipnoteRegion},isPpmFsid:U,isKwzFsid:B,isKwzDsiLibraryFsid:L,isFsid:function(t){return U(t)||B(t)},getPpmFsidRegion:M,getKwzFsidRegion:I,convertKwzFsidToPpmFsid:N,convertPpmFsidToKwzFsidSuffix:R,convertPpmFsidToPossibleKwzFsids:function(t){const e=R(t);return e?["00"+e,"10"+e,"12"+e,"14"+e]:null},testKwzFsidMatchesPpmFsid:function(t,e){return N(t)==e},getFsidRegion:function(e){return U(e)?M(e):B(e)?I(e):t.FlipnoteRegion.UNKNOWN}});!function(){if(!p)return function(){};const t=document.createElement("a")}(),t.FlipnoteFormat=void 0,(z=t.FlipnoteFormat||(t.FlipnoteFormat={})).PPM="PPM",z.KWZ="KWZ",function(t){t[t.Jpeg=0]="Jpeg",t[t.Rgba=1]="Rgba"}(O||(O={})),function(t){t[t.Left=0]="Left",t[t.Right=1]="Right"}(D||(D={})),t.FlipnoteAudioTrack=void 0,(W=t.FlipnoteAudioTrack||(t.FlipnoteAudioTrack={}))[W.BGM=0]="BGM",W[W.SE1=1]="SE1",W[W.SE2=2]="SE2",W[W.SE3=3]="SE3",W[W.SE4=4]="SE4",t.FlipnoteSoundEffectTrack=void 0,(V=t.FlipnoteSoundEffectTrack||(t.FlipnoteSoundEffectTrack={}))[V.SE1=1]="SE1",V[V.SE2=2]="SE2",V[V.SE3=3]="SE3",V[V.SE4=4]="SE4";class $ extends i{constructor(){super(...arguments),this[Symbol.toStringTag]="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){if(this.isFolderIcon)return t.ICON;return(this.isComment?t.COMMENT:t.FLIPNOTE).replace("$USERNAME",this.meta.current.username)}toString(){return this.getTitle()}*[Symbol.iterator](){for(let t=0;te[n]=r<<24|s<<16|i<<8|t),e}getSoundEffectFlagsForTrack(t){return this.getSoundEffectFlags().map(e=>e[t])}isSoundEffectUsedOnFrame(t,e){return d(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 K=[.5,.5,1,2,4,6,12,20,30],q={WHITE:[255,255,255,255],BLACK:[14,14,14,255],RED:[255,42,42,255],BLUE:[10,57,255,255]},j=[4294967295,4283585106,4294967295,4288453788,4282665215,4283388360,4289506815,4278255360,4294918216,4290269009,4294945709,4278255360,4290205622,4278255360,4278255360,4278255360],G="-----BEGIN PUBLIC KEY-----\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCPLwTL6oSflv+gjywi/sM0TUB\n90xqOvuCpjduETjPoN2FwMebxNjdKIqHUyDu4AvrQ6BDJc6gKUbZ1E27BGZoCPH4\n9zQRb+zAM6M9EjHwQ6BABr0u2TcF7xGg2uQ9MBWz9AfbVQ91NjfrNWo0f7UPmffv\n1VvixmTk1BCtavZxBwIDAQAB\n-----END PUBLIC KEY-----";class Y extends ${constructor(e,i={}){super(e),this.format=t.FlipnoteFormat.PPM,this[Symbol.toStringTag]="Flipnote Studio PPM animation file",this.imageWidth=Y.width,this.imageHeight=Y.height,this.aspect=Y.aspect,this.imageOffsetX=0,this.imageOffsetY=0,this.numLayers=Y.numLayers,this.numLayerColors=Y.numLayerColors,this.publicKey=Y.publicKey,this.srcWidth=Y.width,this.audioTracks=Y.audioTracks,this.soundEffectTracks=Y.soundEffectTracks,this.rawSampleRate=Y.rawSampleRate,this.sampleRate=Y.sampleRate,this.globalPalette=Y.globalPalette,this.prevDecodedFrame=null,this.decodeHeader(),this.decodeAnimationHeader(),this.decodeSoundHeader(),0!=(this.version>>4&15)&&this.decodeMeta(),this.layerBuffers=[new Uint8Array(Y.width*Y.height),new Uint8Array(Y.width*Y.height)],this.prevLayerBuffers=[new Uint8Array(Y.width*Y.height),new Uint8Array(Y.width*Y.height)],this.lineEncodingBuffers=[new Uint8Array(Y.height),new Uint8Array(Y.height)],this.prevDecodedFrame=null}decodeHeader(){c(16>1&1),isSpinoff:this.isSpinoff,frameCount:this.frameCount,frameSpeed:this.frameSpeed,bgmSpeed:this.bgmSpeed,duration:this.duration,thumbIndex:e,timestamp:d,root:{username:i,fsid:l,region:M(l),filename:null},parent:{username:s,fsid:n,region:M(n),filename:o},current:{username:r,fsid:a,region:M(a),filename:h}}}decodeAnimationHeader(){this.seek(1696);const t=this.readUint16(),e=t/4;c(e<=this.frameCount),this.seek(1704);const i=new Uint32Array(e);for(let s=0;s>7&1}getThumbnailImage(){this.seek(160);const t=this.readBytes(1536),e=new Uint32Array(3072);for(let i=0;i<48;i+=8)for(let s=0;s<64;s+=8)for(let r=0;r<8;r+=1)for(let n=0;n<8;n+=2){const a=s+n,o=i+r;e[64*o+a]=j[15&t[0]],e[64*o+a+1]=j[t[0]<<4&15]}return{format:O.Rgba,width:64,height:48,data:e.buffer}}decodeFrame(t){if(d(t,0,this.frameCount-1,"Frame index"),this.prevDecodedFrame===t)return this.layerBuffers;this.prevDecodedFrame===t-1||this.isKeyFrame(t)||0===t||this.decodeFrame(t-1),this.prevDecodedFrame=t,this.seek(this.frameOffsets[t]);const e=this.readUint8(),i=e>>7&1,s=e>>5&3;this.layerBuffers[0].fill(0),this.layerBuffers[1].fill(0);let r=0,n=0;s&&(r=this.readInt8(),n=this.readInt8());for(let t=0;t<2;t++){const e=this.lineEncodingBuffers[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=this.layerBuffers[t],i=this.lineEncodingBuffers[t];for(let t=0;t>=1)e[s+i]=1&t}break;case 2:e.fill(1,s,s+Y.width);for(a=this.readUint32(!1);0!==a;a<<=1,s+=8)if(2147483648&a){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 o=this.layerBuffers[0],h=this.layerBuffers[1],l=this.prevLayerBuffers[0],c=this.prevLayerBuffers[1];if(i||0!==r||0!==n){if(!i){const t=Y.width,e=Y.height,i=Math.max(r,0),s=Math.max(n,0),a=Math.min(t+r,t),d=Math.min(e+n,e),u=n*t+r;let f,p;for(let e=s;e>1&3],s[e>>3&3]]}getFramePalette(t){d(t,0,this.frameCount-1,"Frame index");return this.getFramePaletteIndices(t).map(t=>this.globalPalette[t])}getIsKeyFrame(t){const e=1===this.isKeyFrame(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!==this.soundFlags)return this.soundFlags;c(1696+this.frameDataLength({[t.FlipnoteSoundEffectTrack.SE1]:e[0],[t.FlipnoteSoundEffectTrack.SE2]:e[1],[t.FlipnoteSoundEffectTrack.SE3]:e[2]}))}getFrameSoundEffectFlags(e){d(e,0,this.frameCount-1,"Frame index"),this.seek(1696+this.frameDataLength+e);const i=this.readUint8();return{[t.FlipnoteSoundEffectTrack.SE1]:0!=(1&i),[t.FlipnoteSoundEffectTrack.SE2]:0!=(2&i),[t.FlipnoteSoundEffectTrack.SE3]:0!=(4&i)}}getAudioTrackRaw(t){const e=this.soundMeta.get(t);return c(e.ptr+e.length>4,u=!u;const t=n[c];let i=t>>3;1&l&&(i+=t>>2),2&l&&(i+=t>>1),4&l&&(i+=t),8&l&&(i=-i),d+=i,d=a(d,-32768,32767),c+=r[l],c=a(c,0,88),s[h++]=d}return s}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?function(t,e,i){const s=t.length,r=s/e*i,n=new Int16Array(r),a=e/i;for(let e=0;er);n++){const s=e[i+n]+t[n]/2;e[i+n]=a(s,-32768,32767)}}getAudioMasterPcm(e=this.sampleRate){const i=Math.ceil(this.duration*e),s=new Int16Array(i),r=this.hasAudioTrack(t.FlipnoteAudioTrack.BGM),n=this.hasAudioTrack(t.FlipnoteAudioTrack.SE1),a=this.hasAudioTrack(t.FlipnoteAudioTrack.SE2),o=this.hasAudioTrack(t.FlipnoteAudioTrack.SE3);if(r){const i=this.getAudioTrackPcm(t.FlipnoteAudioTrack.BGM,e);this.pcmAudioMix(i,s,0)}if(n||a||o){const i=e/this.framerate,r=n?this.getAudioTrackPcm(t.FlipnoteAudioTrack.SE1,e):null,h=a?this.getAudioTrackPcm(t.FlipnoteAudioTrack.SE2,e):null,l=o?this.getAudioTrackPcm(t.FlipnoteAudioTrack.SE3,e):null,c=this.decodeSoundFlags();for(let t=0;t{const i=8*t,s=tt.subarray(i,i+8),r=et.subarray(i,i+8);st.set(s,8*e),rt.set(r,8*e)});class nt extends ${constructor(e,i={}){super(e),this.format=t.FlipnoteFormat.KWZ,this[Symbol.toStringTag]="Flipnote Studio 3D KWZ animation file",this.imageWidth=nt.width,this.imageHeight=nt.height,this.aspect=nt.aspect,this.imageOffsetX=0,this.imageOffsetY=0,this.numLayers=nt.numLayers,this.numLayerColors=nt.numLayerColors,this.publicKey=nt.publicKey,this.srcWidth=nt.width,this.audioTracks=nt.audioTracks,this.soundEffectTracks=nt.soundEffectTracks,this.rawSampleRate=nt.rawSampleRate,this.sampleRate=nt.sampleRate,this.globalPalette=nt.globalPalette,this.prevDecodedFrame=null,this.bitIndex=0,this.bitValue=0,this.settings=Object.assign(Object.assign({},nt.defaultSettings),i),this.layerBuffers=[new Uint8Array(nt.width*nt.height),new Uint8Array(nt.width*nt.height),new Uint8Array(nt.width*nt.height)],this.buildSectionMap(),this.sectionMap.has("KIC")?(this.isFolderIcon=!0,this.imageWidth=24,this.imageHeight=24,this.frameCount=1,this.frameSpeed=0,this.framerate=X[0],this.thumbFrameIndex=0,this.getFrameOffsets()):this.sectionMap.has("KSN")?(this.decodeMeta(),this.getFrameOffsets(),this.decodeSoundHeader()):(this.isComment=!0,this.decodeMeta(),this.getFrameOffsets()),this.settings.dsiLibraryNote&&(this.isDsiLibraryNote=!0),this.settings.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))}buildSectionMap(){const t=this.byteLength-256,e=new Map;let i=0,s=0;for(;s16){const t=this.readUint16();this.bitValue|=t<<16-this.bitIndex,this.bitIndex-=16}const e=this.bitValue&Z[t];return this.bitValue>>=t,this.bitIndex+=t,e}readFsid(){if(this.settings.dsiLibraryNote){return this.readHex(10,!0).slice(2,18)}const t=this.readHex(10);return`${t.slice(0,4)}-${t.slice(4,8)}-${t.slice(8,12)}-${t.slice(12,18)}`.toLowerCase()}readFilename(){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}`}decodeMeta(){if(this.settings.quickMeta)return this.decodeMetaQuick();c(this.sectionMap.has("KFH")),this.seek(this.sectionMap.get("KFH").ptr+12);const t=x(this.readUint32()),e=x(this.readUint32());this.readUint32();const i=this.readFsid(),s=this.readFsid(),r=this.readFsid(),n=this.readWideChars(11),a=this.readWideChars(11),o=this.readWideChars(11),h=this.readFilename(),l=this.readFilename(),d=this.readFilename(),u=this.readUint16(),f=this.readUint16(),p=this.readUint16(),m=this.readUint8(),g=this.readUint8();this.isSpinoff=r!==s||r!==i,this.frameCount=u,this.frameSpeed=m,this.framerate=X[m],this.duration=E(this.frameCount,this.framerate),this.thumbFrameIndex=f,this.layerVisibility={1:0==(1&g),2:0==(2&g),3:0==(3&g)},this.meta={lock:0!=(1&p),loop:0!=(2&p),isSpinoff:this.isSpinoff,frameCount:u,frameSpeed:m,duration:this.duration,thumbIndex:f,timestamp:e,creationTimestamp:t,root:{username:n,fsid:i,region:I(i),filename:h,isDsiFilename:28!==h.length},parent:{username:a,fsid:s,region:I(s),filename:l,isDsiFilename:28!==l.length},current:{username:o,fsid:r,region:I(r),filename:d,isDsiFilename:28!==d.length}}}decodeMetaQuick(){c(this.sectionMap.has("KFH")),this.seek(this.sectionMap.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=X[i],this.duration=E(this.frameCount,this.framerate),this.layerVisibility={1:0==(1&s),2:0==(2&s),3:0==(3&s)}}getFrameOffsets(){c(this.sectionMap.has("KMI")&&this.sectionMap.has("KMC"));const t=this.frameCount,e=this.sectionMap.get("KMI"),i=this.sectionMap.get("KMC");c(e.length/28>=t);const s=new Uint32Array(t),r=new Uint32Array(t),n=[];let a=e.ptr+8,o=i.ptr+12;for(let e=0;e>8&15,e>>12&15,e>>16&15,e>>20&15,e>>24&15,e>>28&15]}getFramePalette(t){d(t,0,this.frameCount-1,"Frame index");return this.getFramePaletteIndices(t).map(t=>this.globalPalette[t])}getFrameDiffingFlag(t){return d(t,0,this.frameCount-1,"Frame index"),this.seek(this.frameMetaOffsets[t]),this.readUint32()>>4&7}getIsKeyFrame(t){const e=this.getFrameDiffingFlag(t);return[0==(1&e),0==(2&e),0==(4&e)]}getFrameLayerDepths(t){return d(t,0,this.frameCount-1,"Frame index"),this.seek(this.frameMetaOffsets[t]+20),[this.readUint8(),this.readUint8(),this.readUint8()]}getFrameAuthor(t){return d(t,0,this.frameCount-1,"Frame index"),this.seek(this.frameMetaOffsets[t]+10),this.readFsid()}getFrameCameraFlags(t){this.seek(this.frameMetaOffsets[t]+26);const e=this.readUint8();return[0!=(1&e),0!=(2&e),0!=(4&e)]}getFrameLayerOrder(t){d(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(d(t,0,this.frameCount-1,"Frame index"),this.prevDecodedFrame===t)return this.layerBuffers;this.prevDecodedFrame!==t-1&&0!==t&&(i&&(e&=~this.getFrameDiffingFlag(t+1)),0!==e&&this.decodeFrame(t-1,e,!0));let s=this.frameDataOffsets[t];const r=this.frameLayerSizes[t];for(let t=0;t<3&&(!this.settings.dsiLibraryNote||3!==t);t++){this.seek(s);let i=r[t];s+=i;const n=this.layerBuffers[t];if(38===i)continue;if(0==(e>>t&1))continue;this.bitIndex=16,this.bitValue=0;let a=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(a>0){a-=1;continue}let r=s*nt.width+i;const o=this.readBits(3);if(0===o){const t=8*this.readBits(5),e=st.subarray(t,t+8);n.set(e,r),n.set(e,r+=320),n.set(e,r+=320),n.set(e,r+=320),n.set(e,r+=320),n.set(e,r+=320),n.set(e,r+=320),n.set(e,r+=320)}else if(1===o){const t=8*this.readBits(13),e=tt.subarray(t,t+8);n.set(e,r),n.set(e,r+=320),n.set(e,r+=320),n.set(e,r+=320),n.set(e,r+=320),n.set(e,r+=320),n.set(e,r+=320),n.set(e,r+=320)}else if(2===o){const t=8*this.readBits(5),e=st.subarray(t,t+8),i=rt.subarray(t,t+8);n.set(e,r),n.set(i,r+=320),n.set(e,r+=320),n.set(i,r+=320),n.set(e,r+=320),n.set(i,r+=320),n.set(e,r+=320),n.set(i,r+=320)}else if(3===o){const t=8*this.readBits(13),e=tt.subarray(t,t+8),i=et.subarray(t,t+8);n.set(e,r),n.set(i,r+=320),n.set(e,r+=320),n.set(i,r+=320),n.set(e,r+=320),n.set(i,r+=320),n.set(e,r+=320),n.set(i,r+=320)}else if(4===o){const t=this.readBits(8);for(let e=1;e<255;e<<=1){if(t&e){const t=8*this.readBits(5),e=st.subarray(t,t+8);n.set(e,r)}else{const t=8*this.readBits(13),e=tt.subarray(t,t+8);n.set(e,r)}r+=320}}else{if(5===o){a=this.readBits(5);continue}if(7===o){let t,e,i=this.readBits(2);if(0!==this.readBits(1)){const s=8*this.readBits(5),r=8*this.readBits(5);t=st.subarray(s,s+8),e=st.subarray(r,r+8),i+=1}else{const i=8*this.readBits(13),s=8*this.readBits(13);t=tt.subarray(i,i+8),e=tt.subarray(s,s+8)}switch(i%4){case 0:n.set(t,r),n.set(e,r+=320),n.set(t,r+=320),n.set(e,r+=320),n.set(t,r+=320),n.set(e,r+=320),n.set(t,r+=320),n.set(e,r+=320);break;case 1:n.set(t,r),n.set(t,r+=320),n.set(e,r+=320),n.set(t,r+=320),n.set(t,r+=320),n.set(e,r+=320),n.set(t,r+=320),n.set(t,r+=320);break;case 2:n.set(t,r),n.set(e,r+=320),n.set(t,r+=320),n.set(t,r+=320),n.set(e,r+=320),n.set(t,r+=320),n.set(t,r+=320),n.set(e,r+=320);break;case 3:n.set(t,r),n.set(e,r+=320),n.set(e,r+=320),n.set(t,r+=320),n.set(e,r+=320),n.set(e,r+=320),n.set(t,r+=320),n.set(e,r+=320)}}}}}}return this.prevDecodedFrame=t,this.layerBuffers}decodeFrameSoundFlags(t){d(t,0,this.frameCount-1,"Frame index"),this.seek(this.frameMetaOffsets[t]+23);const e=this.readUint8();return[0!=(1&e),0!=(2&e),0!=(4&e),0!=(8&e)]}decodeSoundFlags(){return void 0!==this.soundFlags||(this.soundFlags=new Array(this.frameCount).fill(!1).map((t,e)=>this.decodeFrameSoundFlags(e))),this.soundFlags}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]}}getAudioTrackRaw(t){const e=this.soundMeta.get(t);return c(e.ptr+e.length4?(c=3&h,d=n[o],u=d>>3,1&c&&(u+=d),2&c&&(u=-u),i+=u,o+=s[c],h>>=2,p+=2):(c=15&h,d=n[o],u=d>>3,1&c&&(u+=d>>2),2&c&&(u+=d>>1),4&c&&(u+=d),8&c&&(u=-u),i+=u,o+=r[c],h>>=4,p+=4),o=a(o,0,79),i=a(i,-2048,2047),e[l]=16*i,l+=1}return l}decodeAudioTrack(e){const i=this.settings,s=this.getAudioTrackRaw(e),r=60*this.rawSampleRate,n=new Int16Array(r);let a=0,o=40;if(this.isDsiLibraryNote)if(e===t.FlipnoteAudioTrack.BGM){let t=!0;if(null!==i.initialBgmPredictor&&(a=i.initialBgmPredictor,t=!1),null!==i.initialBgmStepIndex&&(o=i.initialBgmStepIndex,t=!1),t&&i.guessInitialBgmState){let t=4294967295,e=0;for(o=0;o<=40;o++){const i=this.decodeAdpcm(s,n,a,o),r=l(n.subarray(0,i));rr);n++){const s=e[i+n]+t[n];e[i+n]=a(s,-32768,32767)}}getAudioMasterPcm(e=this.sampleRate){const i=Math.ceil(this.duration*e),s=new Int16Array(i),r=this.hasAudioTrack(t.FlipnoteAudioTrack.BGM),n=this.hasAudioTrack(t.FlipnoteAudioTrack.SE1),a=this.hasAudioTrack(t.FlipnoteAudioTrack.SE2),o=this.hasAudioTrack(t.FlipnoteAudioTrack.SE3),l=this.hasAudioTrack(t.FlipnoteAudioTrack.SE4);if(r){const i=this.getAudioTrackPcm(t.FlipnoteAudioTrack.BGM,e);this.pcmAudioMix(i,s,0)}if(n||a||o||l){const i=e/this.framerate,r=n?this.getAudioTrackPcm(t.FlipnoteAudioTrack.SE1,e):null,h=a?this.getAudioTrackPcm(t.FlipnoteAudioTrack.SE2,e):null,c=o?this.getAudioTrackPcm(t.FlipnoteAudioTrack.SE3,e):null,d=l?this.getAudioTrackPcm(t.FlipnoteAudioTrack.SE4,e):null,u=this.decodeSoundFlags();for(let t=0;t=200&&s.status<300?e(s.response):i({type:"httpError",status:s.status,statusText:s.statusText}))},s.send(null)}},{matches:function(t){return g&&"string"==typeof t},load:function(t,e,i){y();u(module,"https").get(t,t=>{const s=[];t.on("data",t=>s.push(t)),t.on("end",()=>{const t=Buffer.concat(s);e(t.buffer)}),t.on("error",t=>i(t))})}},{matches:function(t){return p&&"undefined"!=typeof File&&"undefined"!=typeof FileReader&&t instanceof File},load:function(t,e,i){const s=new FileReader;s.onload=t=>{e(s.result)},s.onerror=t=>{i({type:"fileReadError"})},s.readAsArrayBuffer(t)}},{matches:function(t){return p&&"undefined"!=typeof Blob&&"undefined"!=typeof Response&&t instanceof Blob},load:function(t,e,i){new Response(t).arrayBuffer().then(e).catch(i)}},{matches:function(t){return g&&t instanceof Buffer},load:function(t,e,i){e(t.buffer)}},{matches:function(t){return t instanceof ArrayBuffer},load:function(t,e,i){e(t)}}];function ot(t,e=at){return new Promise((i,s)=>{for(let r=0;rot(t,i).then(t=>new Promise((i,s)=>{const r=new Uint8Array(t.slice(0,4)),n=r[0]<<24|r[1]<<16|r[2]<<8|r[3];1346458177===n?i(new Y(t,e)):1262897152==(4294967040&n)||1263092480==(4294967040&n)?i(new nt(t,e)):s("Could not identify source as a valid Flipnote file")}));var lt;t.PlayerEvent=void 0,(lt=t.PlayerEvent||(t.PlayerEvent={})).__Any="any",lt.Play="play",lt.Pause="pause",lt.CanPlay="canplay",lt.CanPlayThrough="canplaythrough",lt.SeekStart="seeking",lt.SeekEnd="seeked",lt.Duration="durationchange",lt.Loop="loop",lt.Ended="ended",lt.VolumeChange="volumechange",lt.Progress="progress",lt.TimeUpdate="timeupdate",lt.FrameUpdate="frameupdate",lt.FrameNext="framenext",lt.FramePrev="frameprev",lt.FrameFirst="framefirst",lt.FrameLast="framelast",lt.Ready="ready",lt.Load="load",lt.LoadStart="loadstart",lt.LoadedData="loadeddata",lt.LoadedMeta="loadedmetadata",lt.Emptied="emptied",lt.Close="close",lt.Error="error",lt.Destroy="destroy";const ct=[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];function dt(t){return{length:t.length,start:e=>t[e][0],end:e=>t[e][1]}}function ut(t,e){return t.toString().padStart(e,"0")}function ft(t){return`${Math.floor(t%3600/60)}:${ut(Math.floor(t%60),2)}`}var pt;!function(t){t[t.None=0]="None",t[t.Dual=1]="Dual",t[t.Anaglyph=2]="Anaglyph"}(pt||(pt={}));function mt(t){if(t instanceof Int8Array)return 5120;if(t instanceof Uint8Array)return 5121;if(t instanceof Uint8ClampedArray)return 5121;if(t instanceof Int16Array)return 5122;if(t instanceof Uint16Array)return 5123;if(t instanceof Int32Array)return 5124;if(t instanceof Uint32Array)return 5125;if(t instanceof Float32Array)return 5126;throw new Error("unsupported typed array type")}const gt="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};function yt(t,e){return"undefined"!=typeof WebGLTexture&&e instanceof WebGLTexture}const vt="";function St(t,e,i,s){if(r=e,"undefined"!=typeof WebGLBuffer&&r instanceof WebGLBuffer)return e;var r;i=i||34962;const n=t.createBuffer();return function(t,e,i,s,r){t.bindBuffer(e,i),t.bufferData(e,s,r||35044)}(t,i,n,e,s),n}function bt(t){return"indices"===t}const wt=/coord|texture/i,_t=/color|colour/i;function xt(t,e){let i;if(i=wt.test(t)?2:_t.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}function Et(t,e){if(gt(t))return t;if(gt(t.data))return t.data;Array.isArray(t)&&(t={data:t});let i=t.type;return i||(i=bt(e)?Uint16Array:Float32Array),new i(t.data)}function Pt(t,e){const i={};return Object.keys(e).forEach((function(s){if(!bt(s)){const n=e[s],a=n.attrib||n.name||n.attribName||vt+s;if(n.value){if(!Array.isArray(n.value)&&!gt(n.value))throw new Error("array.value is not array or typedarray");i[a]={value:n.value}}else{let e,o,h,l;if(n.buffer&&n.buffer instanceof WebGLBuffer)e=n.buffer,l=n.numComponents||n.size,o=n.type,h=n.normalize;else if("number"==typeof n||"number"==typeof n.data){const i=n.data||n,a=n.type||Float32Array,c=i*a.BYTES_PER_ELEMENT;o=function(t){if(t===Int8Array)return 5120;if(t===Uint8Array)return 5121;if(t===Uint8ClampedArray)return 5121;if(t===Int16Array)return 5122;if(t===Uint16Array)return 5123;if(t===Int32Array)return 5124;if(t===Uint32Array)return 5125;if(t===Float32Array)return 5126;throw new Error("unsupported typed array type")}(a),h=void 0!==n.normalize?n.normalize:(r=a)===Int8Array||r===Uint8Array,l=n.numComponents||n.size||xt(s,i),e=t.createBuffer(),t.bindBuffer(34962,e),t.bufferData(34962,c,n.drawType||35044)}else{const i=Et(n,s);e=St(t,i,void 0,n.drawType),o=mt(i),h=void 0!==n.normalize?n.normalize:function(t){return t instanceof Int8Array||t instanceof Uint8Array}(i),l=function(t,e){return t.numComponents||t.size||xt(e,function(t){return t.length?t:t.data}(t).length)}(n,s)}i[a]={buffer:e,numComponents:l,type:o,normalize:h,stride:n.stride||0,offset:n.offset||0,divisor:void 0===n.divisor?void 0:n.divisor,drawType:n.drawType}}}var r})),t.bindBuffer(34962,null),i}const Ft=["position","positions","a_position"];function At(t,e,i){const s=Pt(t,e),r=Object.assign({},i||{});r.attribs=Object.assign({},i?i.attribs:{},s);const n=e.indices;if(n){const e=Et(n,"indices");r.indices=St(t,e,34963),r.numElements=e.length,r.elementType=mt(e)}else r.numElements||(r.numElements=function(t,e){let i,s;for(s=0;s""!==t);let n=0,a="";for(;;){const t=r[n++];a+=t;const h=(o=t[0])>="0"&&o<="9",l=h?parseInt(t):t;h&&(a+=r[n++]);if(n===r.length){i[l]=e;break}{const t=r[n++],e="["===t,o=i[l]||(e?[]:{});i[l]=o,i=o,s[a]=s[a]||function(t){return function(e){qt(t,e)}}(o),a+=t}}var o}function qt(t,e){for(const i in e){const s=t[i];"function"==typeof s?s(e[i]):qt(t[i],e[i])}}function jt(t,...e){const i=t.uniformSetters||t,s=e.length;for(let t=0;t{this.destroy(),t&&t.preventDefault(),this.isCtxLost||this.options.onlost(),this.isCtxLost=!0},this.handleContextRestored=t=>{this.isCtxLost=!1,this.init(),this.options.onrestored()},m(),this.options=Object.assign(Object.assign({},Yt.defaultOptions),s),this.width=e,this.height=i,this.canvas=document.createElement("canvas"),this.canvas.addEventListener("webglcontextlost",this.handleContextLoss,!1),this.canvas.addEventListener("webglcontextrestored",this.handleContextRestored,!1),this.canvas.className="FlipnoteCanvas FlipnoteCanvas--webgl",this.gl=this.canvas.getContext("webgl",{antialias:!1,alpha:!0}),t&&t.appendChild(this.canvas),this.init()}static isSupported(){if(!p)return!1;let t=document.createElement("canvas"),e=t.getContext("2d");const i=null!==e;return t=null,e=null,i}init(){this.setCanvasSize(this.width,this.height);const t=this.gl;this.checkContextLoss()||(this.layerProgram=this.createProgram("#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;}"),this.upscaleProgram=this.createProgram("#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);}"),this.quadBuffer=this.createScreenQuad(-1,-1,2,2,1,1),this.setBuffersAndAttribs(this.layerProgram,this.quadBuffer),this.layerTexture=this.createTexture(t.RGBA,t.LINEAR,t.CLAMP_TO_EDGE),this.frameTexture=this.createTexture(t.RGBA,t.LINEAR,t.CLAMP_TO_EDGE),this.frameBuffer=this.createFramebuffer(this.frameTexture))}createProgram(t,e){if(this.checkContextLoss())return;const i=this.gl,s=this.createShader(i.VERTEX_SHADER,t),r=this.createShader(i.FRAGMENT_SHADER,e),n=i.createProgram();if(i.attachShader(n,s),i.attachShader(n,r),i.linkProgram(n),!i.getProgramParameter(n,i.LINK_STATUS)){const t=i.getProgramInfoLog(n);throw i.deleteProgram(n),new Error(t)}const a=Gt(i,n);return this.refs.programs.push(n),a}createShader(t,e){if(this.checkContextLoss())return;const i=this.gl,s=i.createShader(t);if(i.shaderSource(s,e),i.compileShader(s),!i.getShaderParameter(s,i.COMPILE_STATUS)){const t=i.getShaderInfoLog(s);throw i.deleteShader(s),new Error(t)}return this.refs.shaders.push(s),s}createScreenQuad(t,e,i,s,r,n){if(this.checkContextLoss())return;const a=(r+1)*(n+1),o=r+1,h=new Float32Array(2*a),l=new Float32Array(2*a);let c=0,d=0;for(let a=0;a<=n;a++)for(let o=0;o<=r;o++){const u=o/r,f=a/n;h[c++]=t+i*u,h[c++]=e+s*f,l[d++]=u,l[d++]=f}const u=new Uint16Array(r*n*2*3);let f=0;for(let t=0;tthis.canvas.toBlob(i,t,e))}destroy(){const t=this.refs,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=[],this.paletteBuffer=null,this.layerTexturePixelBuffer=null,this.layerTexturePixels=null,this.textureTypes.clear(),this.textureSizes.clear(),this.frameBufferTextures.clear(),i&&i.parentElement&&(i.width=1,i.height=1,i.parentNode.removeChild(i))}}Yt.defaultOptions={onlost:()=>{},onrestored:()=>{},useDpi:!0};class Xt{constructor(t,e,i,s={}){this.supportedStereoscopeModes=[pt.None],this.stereoscopeMode=pt.None,this.stereoscopeStrength=0,this.paletteBuffer=new Uint32Array(16),m(),this.options=Object.assign(Object.assign({},Xt.defaultOptions),s),this.width=e,this.height=i,this.canvas=document.createElement("canvas"),this.canvas.className="FlipnoteCanvas FlipnoteCanvas--html5",this.ctx=this.canvas.getContext("2d"),this.srcCanvas=document.createElement("canvas"),this.srcCtx=this.srcCanvas.getContext("2d"),c(null!==this.ctx&&null!==this.srcCtx,"Could not create HTML5 canvas"),t&&t.appendChild(this.canvas),this.setCanvasSize(e,i)}static isSupported(){if(!p)return!1;let t=document.createElement("canvas"),e=t.getContext("2d");const i=null!==e;return t=null,e=null,i}setCanvasSize(t,e){const i=this.canvas,s=this.options.useDpi&&window.devicePixelRatio||1,r=t*s,n=e*s;this.width=t,this.height=e,this.dstWidth=r,this.dstHeight=n,i.style.width=t+"px",i.style.height=e+"px",i.width=r,i.height=n}setNote(t){const e=t.imageWidth,i=t.imageHeight;this.note=t,this.srcWidth=e,this.srcHeight=i,this.srcCanvas.width=e,this.srcCanvas.height=i,this.frameImage=this.srcCtx.createImageData(e,i),this.frameBuffer=new Uint32Array(this.frameImage.data.buffer),this.frameIndex=void 0,this.canvas.title=t.getTitle()}clear(t){if(this.frameBuffer.fill(0),this.ctx.clearRect(0,0,this.dstWidth,this.dstHeight),t){const[e,i,s,r]=t;this.ctx.fillStyle=`rgba(${e}, ${i}, ${s}, ${r})`,this.ctx.fillRect(0,0,this.dstWidth,this.dstHeight)}}drawFrame(t){this.clear(),this.options.useSmoothing||(this.ctx.imageSmoothingEnabled=!1),this.note.getFramePixelsRgba(t,this.frameBuffer,this.paletteBuffer),this.srcCtx.putImageData(this.frameImage,0,0),this.ctx.drawImage(this.srcCanvas,0,0,this.srcWidth,this.srcHeight,0,0,this.dstWidth,this.dstHeight),this.frameIndex=t}requestStereoScopeMode(t){this.supportedStereoscopeModes.includes(t)?this.stereoscopeMode=t:this.stereoscopeMode=pt.None,this.forceUpdate()}forceUpdate(){void 0!==this.frameIndex&&this.drawFrame(this.frameIndex)}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(){this.frameImage=null,this.paletteBuffer=null,this.frameBuffer=null,this.canvas.parentNode.removeChild(this.canvas),this.canvas.width=1,this.canvas.height=1,this.canvas=null,this.srcCanvas.width=1,this.srcCanvas.height=1,this.srcCanvas=null}}Xt.defaultOptions={useDpi:!0,useSmoothing:!0};class Qt{constructor(t,e=640,i=480,s={}){this.isReady=!1,this.isHtml5=!1,this.supportedStereoscopeModes=[],this.stereoscopeMode=pt.None,this.stereoscopeStrength=1,this.rendererStack=[Yt,Xt],this.rendererStackIdx=0,this.options={},this.width=e,this.height=i,this.parent=t,this.options=s,this.setSubRenderer(this.rendererStack[0])}setSubRenderer(t){var e;let i=!1;const s=new t(this.parent,this.width,this.height,Object.assign(Object.assign({},this.options),{onlost:()=>{i=!0,this.fallbackIfPossible()}}));i||(this.note&&(s.setNote(this.note),s.frameIndex=null===(e=this.renderer)||void 0===e?void 0:e.frameIndex,s.forceUpdate()),this.renderer&&this.renderer.destroy(),this.isHtml5=s instanceof Xt,this.isReady=!0,this.renderer=s,this.rendererStackIdx=this.rendererStack.indexOf(t),this.supportedStereoscopeModes=s.supportedStereoscopeModes,s.stereoscopeStrength=this.stereoscopeStrength,this.requestStereoScopeMode(this.stereoscopeMode))}fallbackIfPossible(){if(this.rendererStackIdx>=this.rendererStack.length)throw new Error("No renderer to fall back to");this.rendererStackIdx+=1,this.setSubRenderer(this.rendererStack[this.rendererStackIdx])}switchToHtml5(){this.setSubRenderer(Xt)}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}}const Jt=p?window.AudioContext||window.webkitAudioContext:null;class Zt{constructor(){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]],this._volume=1,this._loop=!1,this._startTime=0,this._ctxStartTime=0,this.nodeRefs=[],m()}set volume(t){this.setVolume(t)}get volume(){return this._volume}set loop(t){this._loop=t,this.source&&(this.source.loop=t)}get loop(){return this._loop}getCtx(){return this.ctx||(this.ctx=new Jt),this.ctx}setBuffer(t,e){const i=this.getCtx(),s=t.length,r=i.createBuffer(1,s,e),n=r.getChannelData(0);if(t instanceof Float32Array)n.set(t,0);else if(t instanceof Int16Array)for(let e=0;e{const a=e.createBiquadFilter();this.nodeRefs.push(a),a.frequency.value=t,a.gain.value=r,0===n?a.type="lowshelf":n===i.length-1?a.type="highshelf":a.type="peaking",s.connect(a),s=a}),s}initNodes(){const t=this.getCtx();this.nodeRefs=[];const e=t.createBufferSource();this.nodeRefs.push(e),e.buffer=this.buffer;const i=t.createGain();if(this.nodeRefs.push(i),this.useEq){this.connectEqNodesTo(e).connect(i)}else e.connect(i);if(this.useAnalyser){const e=t.createAnalyser();this.nodeRefs.push(e),this.analyser=e,i.connect(e),e.connect(t.destination)}else this.analyser=void 0,i.connect(t.destination);this.source=e,this.gainNode=i,this.setVolume(this._volume)}setAnalyserEnabled(t){this.useAnalyser=t,this.initNodes()}setVolume(t){this._volume=t,this.gainNode&&(this.gainNode.gain.value=Math.pow(t,2))}playFrom(t){this.initNodes(),this._startTime=t,this._ctxStartTime=this.ctx.currentTime,this.source.loop=this._loop,this.source.start(0,t)}stop(){this.source&&this.source.stop(0)}getCurrentTime(){return this._startTime+(this.ctx.currentTime-this._ctxStartTime)}async destroy(){this.stop();const t=this.getCtx();this.nodeRefs.forEach(t=>t.disconnect()),this.nodeRefs=[],this.analyser=void 0,"closed"!==t.state&&"function"==typeof t.close&&await t.close(),this.buffer=null}}class te{constructor(e,i,s,r={}){this.duration=0,this.autoplay=!1,this.supportedEvents=ct,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.lastParser=void 0,this.lastLoaders=void 0,this.playbackLoop=e=>{if(!this.isPlaying)return;const i=e/1e3,s=this.duration,r=this.audio.getCurrentTime();let n=i-this.playbackStartTime;if(Math.abs(n%s-r%s)>.01&&(n=r),n>=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(n%s),this.playbackLoopId=requestAnimationFrame(this.playbackLoop)},m();const n="string"==typeof e?document.querySelector(e):e;this.parserSettings=r,this.renderer=new Qt(n,i,s,{onlost:()=>this.emit(t.PlayerEvent.Error),onrestored:()=>this.reload()}),this.audio=new Zt,this.el=n}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 dt([[0,this.duration]])}get seekable(){return dt([[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,i,s){if(this.isNoteLoaded&&this.closeNote(),this._src=e,!e)return this.openNote(this.note);this.emit(t.PlayerEvent.LoadStart);const[r,n]=await(async t=>{try{return[null,await t().catch(t=>{throw t})]}catch(t){return[t,null]}})(()=>i(e,this.parserSettings,s));if(r)throw this.emit(t.PlayerEvent.Error,r),new Error("Error loading Flipnote: "+r.message);this.lastParser=i,this.lastLoaders=s,this.openNote(n)}async reload(){if(this.note&&this.lastParser)return await this.load(this.note.buffer,this.lastParser,this.lastLoaders)}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`${ft(Math.max(this.currentTime,0))} / ${ft(this.duration)}`}getFrameCounter(){return`${ut(this.currentFrame+1,3)} / ${ut(this.frameCount,3)}`}setProgress(t){this.assertNoteLoaded(),d(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,this.playAudio(),this.playbackLoop(e),this.emit(t.PlayerEvent.Play)}pause(){this.isPlaying&&(this.isPlaying=!1,null!==this.playbackLoopId&&cancelAnimationFrame(this.playbackLoopId),this.stopAudio(),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])}playAudio(){this.audio.playFrom(this.currentTime)}stopAudio(){this.audio.stop()}toggleAudioEq(){this.setAudioEq(!this.audio.useEq)}setAudioEq(t){this.isPlaying&&(this.wasPlaying=!0,this.stopAudio()),this.audio.useEq=t,this.wasPlaying&&(this.wasPlaying=!1,this.playAudio())}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){d(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";case"video/vnd.nintendo.ugomemo.fykt":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)}if(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()}supports(t){const e=this.supportedEvents.includes(t),i="function"==typeof this[t];return e||i}assertNoteLoaded(){c(this.isNoteLoaded,"No Flipnote is currently loaded in this player")}}function ee(t){class e extends t{get renderer(){return this.player.renderer}get audio(){return this.player.audio}get canvasEl(){return this.player.canvasEl}get note(){return this.player.note}get noteFormat(){return this.player.noteFormat}get meta(){return this.player.meta}get duration(){return this.player.duration}get layerVisibility(){return this.player.layerVisibility}get autoplay(){return this.player.autoplay}set autoplay(t){this.player.autoplay=t}}for(let i of Reflect.ownKeys(te.prototype)){let s=Object.getOwnPropertyDescriptor(te.prototype,i);i in t.prototype||"constructor"===i||"name"===i||"prototype"===i||(s.value&&"function"==typeof s.value?Object.defineProperty(e.prototype,i,Object.assign(Object.assign({},s),{value:function(...t){return this.player[i](...t)}})):(s.get||s.set)&&Object.defineProperty(e.prototype,i,Object.assign(Object.assign({},s),{set:function(t){this.player[i]=t},get:function(){return this.player[i]}})))}return e}class ie{constructor(){this.dataUrl=null}getBuffer(){return y(),Buffer.from(this.getArrayBuffer())}getBlob(){return m(),new Blob([this.getArrayBuffer()],{type:this.mimeType})}getUrl(){return m(),this.dataUrl?this.dataUrl:window.URL.createObjectURL(this.getBlob())}revokeUrl(){m(),this.dataUrl&&window.URL.revokeObjectURL(this.dataUrl)}}const se=[0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535];class re{constructor(t,e,i){this.accum=new Uint8Array(256),this.htab=new Int32Array(5003),this.codetab=new Int32Array(5003),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(5003),this.free_ent=this.ClearCode+2,this.clear_flg=!0,this.output(this.ClearCode,t)}cl_hash(t){for(var e=0;e=0){a=5003-r,0===r&&(a=1);do{if((r-=a)<0&&(r+=5003),this.htab[r]===i){n=this.codetab[r];continue t}}while(this.htab[r]>=0)}this.output(n,e),n=s,this.free_ent<4096?(this.codetab[r]=this.free_ent++,this.htab[r]=i):this.cl_block(e)}else n=this.codetab[r];this.output(n,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)}}}class ne extends ie{constructor(t,i,s={}){super(),this.mimeType="gif/image",this.frameCount=0,this.width=t,this.height=i,this.data=new e,this.settings=Object.assign(Object.assign({},ne.defaultSettings),s),this.compressor=new re(t,i,s.colorDepth)}static fromFlipnote(t,e={}){var i;const s=new ne(t.imageWidth,t.imageHeight,Object.assign({delay:100/t.framerate,repeat:(null===(i=t.meta)||void 0===i?void 0:i.loop)?-1:0},e));s.palette=t.globalPalette;for(let e=0;e=0;o--)(r=t[o])&&(a=(n<3?r(a):n>3?r(e,i,a):r(e,i))||a);return n>3&&a&&Object.defineProperty(e,i,a),a}const he="undefined"!=typeof window&&null!=window.customElements&&void 0!==window.customElements.polyfillWrapFlushCallback,le=(t,e,i=null)=>{for(;e!==i;){const i=e.nextSibling;t.removeChild(e),e=i}},ce=`{{lit-${String(Math.random()).slice(2)}}}`,de=`\x3c!--${ce}--\x3e`,ue=new RegExp(`${ce}|${de}`);class fe{constructor(t,e){this.parts=[],this.element=e;const i=[],s=[],r=document.createTreeWalker(e.content,133,null,!1);let n=0,a=-1,o=0;const{strings:h,values:{length:l}}=t;for(;o0;){const e=h[o],i=ye.exec(e)[2],s=i.toLowerCase()+"$lit$",r=t.getAttribute(s);t.removeAttribute(s);const n=r.split(ue);this.parts.push({type:"attribute",index:a,name:i,strings:n}),o+=n.length-1}}"TEMPLATE"===t.tagName&&(s.push(t),r.currentNode=t.content)}else if(3===t.nodeType){const e=t.data;if(e.indexOf(ce)>=0){const s=t.parentNode,r=e.split(ue),n=r.length-1;for(let e=0;e{const i=t.length-e.length;return i>=0&&t.slice(i)===e},me=t=>-1!==t.index,ge=()=>document.createComment(""),ye=/([ \x09\x0a\x0c\x0d])([^\0-\x1F\x7F-\x9F "'>=/]+)([ \x09\x0a\x0c\x0d]*=[ \x09\x0a\x0c\x0d]*(?:[^ \x09\x0a\x0c\x0d"'`<>=]*|"[^"]*|'[^']*))$/;function ve(t,e){const{element:{content:i},parts:s}=t,r=document.createTreeWalker(i,133,null,!1);let n=be(s),a=s[n],o=-1,h=0;const l=[];let c=null;for(;r.nextNode();){o++;const t=r.currentNode;for(t.previousSibling===c&&(c=null),e.has(t)&&(l.push(t),null===c&&(c=t)),null!==c&&h++;void 0!==a&&a.index===o;)a.index=null!==c?-1:a.index-h,n=be(s,n),a=s[n]}l.forEach(t=>t.parentNode.removeChild(t))}const Se=t=>{let e=11===t.nodeType?0:1;const i=document.createTreeWalker(t,133,null,!1);for(;i.nextNode();)e++;return e},be=(t,e=-1)=>{for(let i=e+1;i(...e)=>{const i=t(...e);return we.set(i,!0),i},xe=t=>"function"==typeof t&&we.has(t),Ee={},Pe={};class Fe{constructor(t,e,i){this.__parts=[],this.template=t,this.processor=e,this.options=i}update(t){let e=0;for(const i of this.__parts)void 0!==i&&i.setValue(t[e]),e++;for(const t of this.__parts)void 0!==t&&t.commit()}_clone(){const t=he?this.template.element.content.cloneNode(!0):document.importNode(this.template.element.content,!0),e=[],i=this.template.parts,s=document.createTreeWalker(t,133,null,!1);let r,n=0,a=0,o=s.nextNode();for(;nt}),Te=` ${ce} `;class Ce{constructor(t,e,i,s){this.strings=t,this.values=e,this.type=i,this.processor=s}getHTML(){const t=this.strings.length-1;let e="",i=!1;for(let s=0;s-1||i)&&-1===t.indexOf("--\x3e",r+1);const n=ye.exec(t);e+=null===n?t+(i?Te:de):t.substr(0,n.index)+n[1]+n[2]+"$lit$"+n[3]+ce}return e+=this.strings[t],e}getTemplateElement(){const t=document.createElement("template");let e=this.getHTML();return void 0!==Ae&&(e=Ae.createHTML(e)),t.innerHTML=e,t}}const ke=t=>null===t||!("object"==typeof t||"function"==typeof t),Ue=t=>Array.isArray(t)||!(!t||!t[Symbol.iterator]);class Be{constructor(t,e,i){this.dirty=!0,this.element=t,this.name=e,this.strings=i,this.parts=[];for(let t=0;t{try{const t={get capture(){return ze=!0,!1}};window.addEventListener("test",t,t),window.removeEventListener("test",t,t)}catch(t){}})();class Oe{constructor(t,e,i){this.value=void 0,this.__pendingValue=void 0,this.element=t,this.eventName=e,this.eventContext=i,this.__boundHandleEvent=t=>this.handleEvent(t)}setValue(t){this.__pendingValue=t}commit(){for(;xe(this.__pendingValue);){const t=this.__pendingValue;this.__pendingValue=Ee,t(this)}if(this.__pendingValue===Ee)return;const t=this.__pendingValue,e=this.value,i=null==t||null!=e&&(t.capture!==e.capture||t.once!==e.once||t.passive!==e.passive),s=null!=t&&(null==e||i);i&&this.element.removeEventListener(this.eventName,this.__boundHandleEvent,this.__options),s&&(this.__options=De(t),this.element.addEventListener(this.eventName,this.__boundHandleEvent,this.__options)),this.value=t,this.__pendingValue=Ee}handleEvent(t){"function"==typeof this.value?this.value.call(this.eventContext||this.element,t):this.value.handleEvent(t)}}const De=t=>t&&(ze?{capture:t.capture,passive:t.passive,once:t.once}:t.capture);function We(t){let e=Ve.get(t.type);void 0===e&&(e={stringsArray:new WeakMap,keyString:new Map},Ve.set(t.type,e));let i=e.stringsArray.get(t.strings);if(void 0!==i)return i;const s=t.strings.join(ce);return i=e.keyString.get(s),void 0===i&&(i=new fe(t,t.getTemplateElement()),e.keyString.set(s,i)),e.stringsArray.set(t.strings,i),i}const Ve=new Map,He=new WeakMap;const $e=new class{handleAttributeExpressions(t,e,i,s){const r=e[0];if("."===r){return new Ne(t,e.slice(1),i).parts}if("@"===r)return[new Oe(t,e.slice(1),s.eventContext)];if("?"===r)return[new Ie(t,e.slice(1),i)];return new Be(t,e,i).parts}handleTextExpression(t){return new Me(t)}};"undefined"!=typeof window&&(window.litHtmlVersions||(window.litHtmlVersions=[])).push("1.4.1");const Ke=(t,...e)=>new Ce(t,e,"html",$e),qe=(t,e)=>`${t}--${e}`;let je=!0;void 0===window.ShadyCSS?je=!1:void 0===window.ShadyCSS.prepareTemplateDom&&(console.warn("Incompatible ShadyCSS version detected. Please update to at least @webcomponents/webcomponentsjs@2.0.2 and @webcomponents/shadycss@1.3.1."),je=!1);const Ge=t=>e=>{const i=qe(e.type,t);let s=Ve.get(i);void 0===s&&(s={stringsArray:new WeakMap,keyString:new Map},Ve.set(i,s));let r=s.stringsArray.get(e.strings);if(void 0!==r)return r;const n=e.strings.join(ce);if(r=s.keyString.get(n),void 0===r){const i=e.getTemplateElement();je&&window.ShadyCSS.prepareTemplateDom(i,t),r=new fe(e,i),s.keyString.set(n,r)}return s.stringsArray.set(e.strings,r),r},Ye=["html","svg"],Xe=new Set,Qe=(t,e,i)=>{Xe.add(t);const s=i?i.element:document.createElement("template"),r=e.querySelectorAll("style"),{length:n}=r;if(0===n)return void window.ShadyCSS.prepareTemplateStyles(s,t);const a=document.createElement("style");for(let t=0;t{Ye.forEach(e=>{const i=Ve.get(qe(e,t));void 0!==i&&i.keyString.forEach(t=>{const{element:{content:e}}=t,i=new Set;Array.from(e.querySelectorAll("style")).forEach(t=>{i.add(t)}),ve(t,i)})})})(t);const o=s.content;i?function(t,e,i=null){const{element:{content:s},parts:r}=t;if(null==i)return void s.appendChild(e);const n=document.createTreeWalker(s,133,null,!1);let a=be(r),o=0,h=-1;for(;n.nextNode();){h++;for(n.currentNode===i&&(o=Se(e),i.parentNode.insertBefore(e,i));-1!==a&&r[a].index===h;){if(o>0){for(;-1!==a;)r[a].index+=o,a=be(r,a);return}a=be(r,a)}}}(i,a,o.firstChild):o.insertBefore(a,o.firstChild),window.ShadyCSS.prepareTemplateStyles(s,t);const h=o.querySelector("style");if(window.ShadyCSS.nativeShadow&&null!==h)e.insertBefore(h.cloneNode(!0),e.firstChild);else if(i){o.insertBefore(a,o.firstChild);const t=new Set;t.add(a),ve(i,t)}};window.JSCompiler_renameProperty=(t,e)=>t;const Je={toAttribute(t,e){switch(e){case Boolean:return t?"":null;case Object:case Array:return null==t?t:JSON.stringify(t)}return t},fromAttribute(t,e){switch(e){case Boolean:return null!==t;case Number:return null===t?null:Number(t);case Object:case Array:return JSON.parse(t)}return t}},Ze=(t,e)=>e!==t&&(e==e||t==t),ti={attribute:!0,type:String,converter:Je,reflect:!1,hasChanged:Ze};class ei extends HTMLElement{constructor(){super(),this.initialize()}static get observedAttributes(){this.finalize();const t=[];return this._classProperties.forEach((e,i)=>{const s=this._attributeNameForProperty(i,e);void 0!==s&&(this._attributeToPropertyMap.set(s,i),t.push(s))}),t}static _ensureClassProperties(){if(!this.hasOwnProperty(JSCompiler_renameProperty("_classProperties",this))){this._classProperties=new Map;const t=Object.getPrototypeOf(this)._classProperties;void 0!==t&&t.forEach((t,e)=>this._classProperties.set(e,t))}}static createProperty(t,e=ti){if(this._ensureClassProperties(),this._classProperties.set(t,e),e.noAccessor||this.prototype.hasOwnProperty(t))return;const i="symbol"==typeof t?Symbol():"__"+t,s=this.getPropertyDescriptor(t,i,e);void 0!==s&&Object.defineProperty(this.prototype,t,s)}static getPropertyDescriptor(t,e,i){return{get(){return this[e]},set(s){const r=this[t];this[e]=s,this.requestUpdateInternal(t,r,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this._classProperties&&this._classProperties.get(t)||ti}static finalize(){const t=Object.getPrototypeOf(this);if(t.hasOwnProperty("finalized")||t.finalize(),this.finalized=!0,this._ensureClassProperties(),this._attributeToPropertyMap=new Map,this.hasOwnProperty(JSCompiler_renameProperty("properties",this))){const t=this.properties,e=[...Object.getOwnPropertyNames(t),..."function"==typeof Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(t):[]];for(const i of e)this.createProperty(i,t[i])}}static _attributeNameForProperty(t,e){const i=e.attribute;return!1===i?void 0:"string"==typeof i?i:"string"==typeof t?t.toLowerCase():void 0}static _valueHasChanged(t,e,i=Ze){return i(t,e)}static _propertyValueFromAttribute(t,e){const i=e.type,s=e.converter||Je,r="function"==typeof s?s:s.fromAttribute;return r?r(t,i):t}static _propertyValueToAttribute(t,e){if(void 0===e.reflect)return;const i=e.type,s=e.converter;return(s&&s.toAttribute||Je.toAttribute)(t,i)}initialize(){this._updateState=0,this._updatePromise=new Promise(t=>this._enableUpdatingResolver=t),this._changedProperties=new Map,this._saveInstanceProperties(),this.requestUpdateInternal()}_saveInstanceProperties(){this.constructor._classProperties.forEach((t,e)=>{if(this.hasOwnProperty(e)){const t=this[e];delete this[e],this._instanceProperties||(this._instanceProperties=new Map),this._instanceProperties.set(e,t)}})}_applyInstanceProperties(){this._instanceProperties.forEach((t,e)=>this[e]=t),this._instanceProperties=void 0}connectedCallback(){this.enableUpdating()}enableUpdating(){void 0!==this._enableUpdatingResolver&&(this._enableUpdatingResolver(),this._enableUpdatingResolver=void 0)}disconnectedCallback(){}attributeChangedCallback(t,e,i){e!==i&&this._attributeToProperty(t,i)}_propertyToAttribute(t,e,i=ti){const s=this.constructor,r=s._attributeNameForProperty(t,i);if(void 0!==r){const t=s._propertyValueToAttribute(e,i);if(void 0===t)return;this._updateState=8|this._updateState,null==t?this.removeAttribute(r):this.setAttribute(r,t),this._updateState=-9&this._updateState}}_attributeToProperty(t,e){if(8&this._updateState)return;const i=this.constructor,s=i._attributeToPropertyMap.get(t);if(void 0!==s){const t=i.getPropertyOptions(s);this._updateState=16|this._updateState,this[s]=i._propertyValueFromAttribute(e,t),this._updateState=-17&this._updateState}}requestUpdateInternal(t,e,i){let s=!0;if(void 0!==t){const r=this.constructor;i=i||r.getPropertyOptions(t),r._valueHasChanged(this[t],e,i.hasChanged)?(this._changedProperties.has(t)||this._changedProperties.set(t,e),!0!==i.reflect||16&this._updateState||(void 0===this._reflectingProperties&&(this._reflectingProperties=new Map),this._reflectingProperties.set(t,i))):s=!1}!this._hasRequestedUpdate&&s&&(this._updatePromise=this._enqueueUpdate())}requestUpdate(t,e){return this.requestUpdateInternal(t,e),this.updateComplete}async _enqueueUpdate(){this._updateState=4|this._updateState;try{await this._updatePromise}catch(t){}const t=this.performUpdate();return null!=t&&await t,!this._hasRequestedUpdate}get _hasRequestedUpdate(){return 4&this._updateState}get hasUpdated(){return 1&this._updateState}performUpdate(){if(!this._hasRequestedUpdate)return;this._instanceProperties&&this._applyInstanceProperties();let t=!1;const e=this._changedProperties;try{t=this.shouldUpdate(e),t?this.update(e):this._markUpdated()}catch(e){throw t=!1,this._markUpdated(),e}t&&(1&this._updateState||(this._updateState=1|this._updateState,this.firstUpdated(e)),this.updated(e))}_markUpdated(){this._changedProperties=new Map,this._updateState=-5&this._updateState}get updateComplete(){return this._getUpdateComplete()}_getUpdateComplete(){return this._updatePromise}shouldUpdate(t){return!0}update(t){void 0!==this._reflectingProperties&&this._reflectingProperties.size>0&&(this._reflectingProperties.forEach((t,e)=>this._propertyToAttribute(e,this[e],t)),this._reflectingProperties=void 0),this._markUpdated()}updated(t){}firstUpdated(t){}}ei.finalized=!0;const ii=t=>e=>"function"==typeof e?((t,e)=>(window.customElements.define(t,e),e))(t,e):((t,e)=>{const{kind:i,elements:s}=e;return{kind:i,elements:s,finisher(e){window.customElements.define(t,e)}}})(t,e),si=(t,e)=>"method"===e.kind&&e.descriptor&&!("value"in e.descriptor)?Object.assign(Object.assign({},e),{finisher(i){i.createProperty(e.key,t)}}):{kind:"field",key:Symbol(),placement:"own",descriptor:{},initializer(){"function"==typeof e.initializer&&(this[e.key]=e.initializer.call(this))},finisher(i){i.createProperty(e.key,t)}};function ri(t){return(e,i)=>void 0!==i?((t,e,i)=>{e.constructor.createProperty(i,t)})(t,e,i):si(t,e)}function ni(t){return ri({attribute:!1,hasChanged:null==t?void 0:t.hasChanged})}function ai(t,e){return(i,s)=>{const r={get(){return this.renderRoot.querySelector(t)},enumerable:!0,configurable:!0};if(e){const e="symbol"==typeof s?Symbol():"__"+s;r.get=function(){return void 0===this[e]&&(this[e]=this.renderRoot.querySelector(t)),this[e]}}return void 0!==s?oi(r,i,s):hi(r,i)}}const oi=(t,e,i)=>{Object.defineProperty(e,i,t)},hi=(t,e)=>({kind:"method",placement:"prototype",key:e.key,descriptor:t}),li=window.ShadowRoot&&(void 0===window.ShadyCSS||window.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,ci=Symbol();class di{constructor(t,e){if(e!==ci)throw new Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t}get styleSheet(){return void 0===this._styleSheet&&(li?(this._styleSheet=new CSSStyleSheet,this._styleSheet.replaceSync(this.cssText)):this._styleSheet=null),this._styleSheet}toString(){return this.cssText}}const ui=(t,...e)=>{const i=e.reduce((e,i,s)=>e+(t=>{if(t instanceof di)return t.cssText;if("number"==typeof t)return t;throw new Error(`Value passed to 'css' function must be a 'css' function result: ${t}. Use 'unsafeCSS' to pass non-literal values, but\n take care to ensure page security.`)})(i)+t[s+1],t[0]);return new di(i,ci)};(window.litElementVersions||(window.litElementVersions=[])).push("2.4.0");const fi={};class pi extends ei{static getStyles(){return this.styles}static _getUniqueStyles(){if(this.hasOwnProperty(JSCompiler_renameProperty("_styles",this)))return;const t=this.getStyles();if(Array.isArray(t)){const e=(t,i)=>t.reduceRight((t,i)=>Array.isArray(i)?e(i,t):(t.add(i),t),i),i=e(t,new Set),s=[];i.forEach(t=>s.unshift(t)),this._styles=s}else this._styles=void 0===t?[]:[t];this._styles=this._styles.map(t=>{if(t instanceof CSSStyleSheet&&!li){const e=Array.prototype.slice.call(t.cssRules).reduce((t,e)=>t+e.cssText,"");return new di(String(e),ci)}return t})}initialize(){super.initialize(),this.constructor._getUniqueStyles(),this.renderRoot=this.createRenderRoot(),window.ShadowRoot&&this.renderRoot instanceof window.ShadowRoot&&this.adoptStyles()}createRenderRoot(){return this.attachShadow({mode:"open"})}adoptStyles(){const t=this.constructor._styles;0!==t.length&&(void 0===window.ShadyCSS||window.ShadyCSS.nativeShadow?li?this.renderRoot.adoptedStyleSheets=t.map(t=>t instanceof CSSStyleSheet?t:t.styleSheet):this._needsShimAdoptedStyleSheets=!0:window.ShadyCSS.ScopingShim.prepareAdoptedCssText(t.map(t=>t.cssText),this.localName))}connectedCallback(){super.connectedCallback(),this.hasUpdated&&void 0!==window.ShadyCSS&&window.ShadyCSS.styleElement(this)}update(t){const e=this.render();super.update(t),e!==fi&&this.constructor.render(e,this.renderRoot,{scopeName:this.localName,eventContext:this}),this._needsShimAdoptedStyleSheets&&(this._needsShimAdoptedStyleSheets=!1,this.constructor._styles.forEach(t=>{const e=document.createElement("style");e.textContent=t.cssText,this.renderRoot.appendChild(e)}))}render(){return fi}}pi.finalized=!0,pi.render=(t,e,i)=>{if(!i||"object"!=typeof i||!i.scopeName)throw new Error("The `scopeName` option is required.");const s=i.scopeName,r=He.has(e),n=je&&11===e.nodeType&&!!e.host,a=n&&!Xe.has(s),o=a?document.createDocumentFragment():e;if(((t,e,i)=>{let s=He.get(e);void 0===s&&(le(e,e.firstChild),He.set(e,s=new Me(Object.assign({templateFactory:We},i))),s.appendInto(e)),s.setValue(t),s.commit()})(t,o,Object.assign({templateFactory:Ge(s)},i)),a){const t=He.get(o);He.delete(o);const i=t.value instanceof Fe?t.value.template:void 0;Qe(s,o,i),le(e,e.firstChild),e.appendChild(o),He.set(e,t)}!r&&n&&window.ShadyCSS.styleElement(e.host)};let mi=class extends(ee(pi)){constructor(){super(),this._width="auto",this._cssWidth="auto",this._progress=0,this._counter="",this._isLoading=!1,this._isError=!1,this._isPlaying=!1,this._isMuted=!1,this._volumeLevel=0,this._isPlayerAvailable=!1,this.handleResize=t=>{this.updateCanvasSize()},this.handleKeyInput=t=>{switch(t.preventDefault(),t.key.toLowerCase()){case" ":this.togglePlay();break;case"a":case"arrowleft":t.shiftKey?this.firstFrame():this.prevFrame();break;case"d":case"arrowright":t.shiftKey?this.lastFrame():this.nextFrame()}},this.handlePlayToggle=t=>{this.focus(),this.togglePlay()},this.handleMuteToggle=t=>{this.focus(),this.toggleMuted()},this.handleProgressSliderChange=t=>{this.focus(),this.seek(t.detail.value)},this.handleProgressSliderInputStart=()=>{this.focus(),this.startSeek()},this.handleProgressSliderInputEnd=()=>{this.focus(),this.endSeek()},this.handleVolumeBarChange=t=>{this.focus(),this.setVolume(t.detail.value)},this._resizeObserver=new ResizeObserver(this.handleResize)}static get styles(){return ui`:host{display:inline-block}.Player{display:inline-block;position:relative;font-family:var(--flipnote-player-font-family,sans-serif)}.CanvasArea{position:relative}.PlayerCanvas{position:relative;display:block}.Overlay{position:absolute;top:0;left:0;background:#ebf0f3;color:#4b4c53;width:100%;height:100%;display:flex;justify-content:center;align-items:center}.Overlay--error{background:#ff8b8b;color:#ca2a32}@keyframes spin{from{transform:rotateZ(0)}to{transform:rotateZ(360deg)}}.LoaderIcon{animation:spin infinite 1.2s linear}.Controls{background:var(--flipnote-player-controls-background,none)}.MuteIcon{width:28px;height:28px}.Controls__groupLeft,.Controls__groupRight,.Controls__row{display:flex;align-items:center}.Controls__groupLeft{margin-right:auto}.Controls__groupRight{margin-left:auto}.Controls__playButton{height:32px;width:32px;padding:2px}.MuteIcon{width:28px;height:28px}.LoaderIcon{width:40px;height:40px}.Controls.Controls--compact{margin:6px 0}.Controls__frameCounter{min-width:90px;font-variant-numeric:tabular-nums}.Controls__progressBar{flex:1}.Controls--compact .Controls__playButton{margin-right:8px}.Controls--compact .Controls__progressBar{flex:1}.Controls--default .Controls__playButton{margin-right:8px}.Controls--default .Controls__volumeBar{width:70px;margin-left:8px}.Button{border:0;padding:0;outline:0;-webkit-appearance:none;display:block;font-family:inherit;font-size:inherit;text-align:center;cursor:pointer;background:var(--flipnote-player-button-background,#ffd3a6);color:var(--flipnote-player-button-color,#f36a2d);border-radius:4px}.Button flipnote-player-icon{display:block}`}get width(){return this._width}set width(t){const e=this._width;var i;this._width=t,this._cssWidth=isNaN(+t)?t:t+"px",i=()=>this.updateCanvasSize(),p?S(()=>S(()=>i())):i(),this.requestUpdate("width",e)}get src(){return this._playerSrc}set src(t){const e=this._playerSrc;this._isPlayerAvailable&&this.player.load(t,ht),this._playerSrc=t,this.requestUpdate("src",e)}get autoplay(){return this.player.autoplay}set autoplay(t){const e=this.player.autoplay;this.player.autoplay=t,this.requestUpdate("autoplay",e)}render(){return Ke`
${this._isLoading?Ke`
`:""} ${this._isError?Ke`
Error
`:""}
${this.renderControls()}
`}renderControls(){return"compact"===this.controls?Ke`
`:Ke`
${this._counter}
`}firstUpdated(e){this.updateSettingsFromProps();const i=new te(this.playerCanvasWrapper,256,192,this.parserSettings);this._resizeObserver.observe(this),this.player=i,i.on(t.PlayerEvent.LoadStart,()=>{this._isLoading=!0}),i.on(t.PlayerEvent.Load,()=>{this.updateCanvasSize()}),i.on(t.PlayerEvent.Error,()=>{this._isLoading=!1,this._isError=!0}),i.on([t.PlayerEvent.Load,t.PlayerEvent.Close,t.PlayerEvent.Progress],()=>{this._isLoading=!1,this._isError=!1,this._progress=i.getProgress()/100,this._counter=i.getFrameCounter()}),i.on(t.PlayerEvent.Play,()=>{this._isPlaying=!0}),i.on(t.PlayerEvent.Pause,()=>{this._isPlaying=!1}),i.on([t.PlayerEvent.Load,t.PlayerEvent.VolumeChange],()=>{this._volumeLevel=i.volume,this._isMuted=i.muted}),i.on(t.PlayerEvent.__Any,(t,e)=>{this.dispatchEvent(new Event(t))}),this._playerSrc&&i.load(this._playerSrc,ht),this._isPlayerAvailable=!0}disconnectedCallback(){this._resizeObserver.disconnect(),this.destroy()}updateSettingsFromProps(){this.parserSettings={dsiLibraryNote:this.dsiLibrary,borderCrop:this.cropBorder,initialBgmPredictor:this.bgmPredictor,initialBgmStepIndex:this.bgmStepIndex,initialSePredictors:this.parseListProp(null==this?void 0:this.sePredictors),initialSeStepIndices:this.parseListProp(null==this?void 0:this.seStepIndices)}}parseListProp(t){if(t)return t.split(",").map(t=>/^\s*$/.test(t)?void 0:parseInt(t))}updateCanvasSize(){const t=this._isPlayerAvailable,e=this.player.note;let i=256;"auto"===this._width&&t&&this.player.isNoteLoaded?i=e.imageWidth:"auto"!==this._width&&(i=this.getBoundingClientRect().width),t&&e&&this.player.resize(i,i*e.aspect)}};oe([ri({type:String})],mi.prototype,"controls",void 0),oe([ri({type:Boolean})],mi.prototype,"dsiLibrary",void 0),oe([ri({type:Boolean})],mi.prototype,"cropBorder",void 0),oe([ri({type:Number})],mi.prototype,"bgmPredictor",void 0),oe([ri({type:Number})],mi.prototype,"bgmStepIndex",void 0),oe([ri({type:String})],mi.prototype,"sePredictors",void 0),oe([ri({type:String})],mi.prototype,"seStepIndices",void 0),oe([ri({type:String})],mi.prototype,"width",null),oe([ri({type:String})],mi.prototype,"src",null),oe([ri({type:Boolean})],mi.prototype,"autoplay",null),oe([ni()],mi.prototype,"_width",void 0),oe([ni()],mi.prototype,"_cssWidth",void 0),oe([ni()],mi.prototype,"_progress",void 0),oe([ni()],mi.prototype,"_counter",void 0),oe([ni()],mi.prototype,"_isLoading",void 0),oe([ni()],mi.prototype,"_isError",void 0),oe([ni()],mi.prototype,"_isPlaying",void 0),oe([ni()],mi.prototype,"_isMuted",void 0),oe([ni()],mi.prototype,"_volumeLevel",void 0),oe([ai("#canvasWrapper")],mi.prototype,"playerCanvasWrapper",void 0),mi=oe([ii("flipnote-player")],mi);class gi{constructor(t){this.classes=new Set,this.changed=!1,this.element=t;const e=(t.getAttribute("class")||"").split(/\s+/);for(const t of e)this.classes.add(t)}add(t){this.classes.add(t),this.changed=!0}remove(t){this.classes.delete(t),this.changed=!0}commit(){if(this.changed){let t="";this.classes.forEach(e=>t+=e+" "),this.element.setAttribute("class",t)}}}const yi=new WeakMap,vi=_e(t=>e=>{if(!(e instanceof Le)||e instanceof Re||"class"!==e.committer.name||e.committer.parts.length>1)throw new Error("The `classMap` directive must be used in the `class` attribute and must be the only part in the attribute.");const{committer:i}=e,{element:s}=i;let r=yi.get(e);void 0===r&&(s.setAttribute("class",i.strings.join(" ")),yi.set(e,r=new Set));const n=s.classList||new gi(s);r.forEach(e=>{e in t||(n.remove(e),r.delete(e))});for(const e in t){const i=t[e];i!=r.has(e)&&(i?(n.add(e),r.add(e)):(n.remove(e),r.delete(e)))}"function"==typeof n.commit&&n.commit()}),Si=new WeakMap,bi=_e(t=>e=>{if(!(e instanceof Le)||e instanceof Re||"style"!==e.committer.name||e.committer.parts.length>1)throw new Error("The `styleMap` directive must be used in the style attribute and must be the only part in the attribute.");const{committer:i}=e,{style:s}=i.element;let r=Si.get(e);void 0===r&&(s.cssText=i.strings.join(" "),Si.set(e,r=new Set)),r.forEach(e=>{e in t||(r.delete(e),-1===e.indexOf("-")?s[e]=null:s.removeProperty(e))});for(const e in t)r.add(e),-1===e.indexOf("-")?s[e]=t[e]:s.setProperty(e,t[e])});let wi=class extends pi{constructor(){super(...arguments),this.value=0,this.orientation="horizontal",this.isActive=!1,this.onSliderMouseStart=t=>{t.preventDefault(),this.isActive=!0,document.addEventListener("mousemove",this.onSliderMouseMove),document.addEventListener("mouseup",this.onSliderMouseEnd),this.dispatch("inputstart"),this.onSliderInput(t.clientX,t.clientY)},this.onSliderMouseEnd=t=>{t.preventDefault(),document.removeEventListener("mousemove",this.onSliderMouseMove),document.removeEventListener("mouseup",this.onSliderMouseEnd),this.dispatch("inputend"),this.onSliderInput(t.clientX,t.clientY),this.isActive=!1},this.onSliderMouseMove=t=>{t.preventDefault(),this.onSliderInput(t.clientX,t.clientY)},this.onSliderTouchStart=t=>{const e=t.changedTouches[0];t.preventDefault(),this.isActive=!0,document.addEventListener("touchmove",this.onSliderTouchMove),document.addEventListener("touchend",this.onSliderTouchEnd),this.dispatch("inputstart"),this.onSliderInput(e.clientX,e.clientY)},this.onSliderTouchEnd=t=>{const e=t.changedTouches[0];t.preventDefault(),document.removeEventListener("touchmove",this.onSliderTouchMove),document.removeEventListener("touchend",this.onSliderTouchEnd),this.dispatch("inputend"),this.onSliderInput(e.clientX,e.clientY),this.isActive=!1},this.onSliderTouchMove=t=>{const e=t.changedTouches[0];t.preventDefault(),this.onSliderInput(e.clientX,e.clientY)},this.onSliderInput=(t,e)=>{const i=this.sliderElement.getBoundingClientRect();let s;if("horizontal"===this.orientation){const e=i.height/2,r=i.width-2*e,n=(t-i.left-e)/r;s=Math.max(0,Math.min(n,1))}else if("vertical"===this.orientation){const t=i.width/2,r=i.height-2*t,n=1-(e-i.top-t)/r;s=Math.max(0,Math.min(n,1))}this.value!==s&&this.dispatch("change",{value:s})}}static get styles(){return ui`.Slider{touch-action:none;padding:4px 0;cursor:pointer}.Slider--vertical{height:100px;width:14px}.Slider__track{position:relative;border-radius:3px;background:var(--flipnote-player-slider-track,#ffd3a6)}.Slider--horizontal .Slider__track{height:4px;margin:6px 0}.Slider--vertical .Slider__track{width:4px;height:100%;margin:0 6px}.Slider__levelWrapper{position:absolute;left:0;right:0;height:6px;margin:-1px}.Slider__level{position:absolute;width:100%;left:0;height:8px;border-radius:8px;background:var(--flipnote-player-slider-level,#f36a2d)}.Slider--horizontal .Slider__level{width:100%;height:6px}.Slider--vertical .Slider__level{width:6px;height:100%;bottom:0}.Slider__handle{display:none;position:absolute;height:10px;width:10px;border-radius:5px;box-sizing:border-box;border:3px solid var(--flipnote-player-slider-handle,#f36a2d);background:var(--flipnote-player-slider-handle-fill,#fff)}.Slider--isActive .Slider__handle,.Slider:hover .Slider__handle{display:block}.Slider--horizontal .Slider__handle{top:0;margin-top:-3px;margin-left:-6px}.Slider--vertical .Slider__handle{left:0;margin-bottom:-6px;margin-left:-3px}`}render(){const t=100*this.value+"%",e="horizontal"===this.orientation?"width":"height",i="horizontal"===this.orientation?"left":"bottom",s={Slider:!0,"Slider--horizontal":"horizontal"===this.orientation,"Slider--vertical":"vertical"===this.orientation,"Slider--isActive":this.isActive};return Ke`
`}dispatch(t,e){const i=new CustomEvent(t,{detail:e});this.dispatchEvent(i)}};oe([ri({type:Number})],wi.prototype,"value",void 0),oe([ri({type:String})],wi.prototype,"orientation",void 0),oe([ni()],wi.prototype,"isActive",void 0),oe([ai(".Slider__track")],wi.prototype,"sliderElement",void 0),wi=oe([ii("flipnote-player-slider")],wi);const _i=new WeakMap,xi=window.navigator.userAgent.indexOf("Trident/")>0,Ei=_e(t=>e=>{if(!(e instanceof Me))throw new Error("unsafeSVG can only be used in text bindings");const i=_i.get(e);if(void 0!==i&&ke(t)&&t===i.value&&e.value===i.fragment)return;const s=document.createElement("template"),r=s.content;let n;xi?(s.innerHTML=`${t}`,n=r.firstChild):(n=document.createElementNS("http://www.w3.org/2000/svg","svg"),r.appendChild(n),n.innerHTML=t),r.removeChild(n),((t,e,i=null,s=null)=>{for(;e!==i;){const i=e.nextSibling;t.insertBefore(e,s),e=i}})(r,n.firstChild);const a=document.importNode(r,!0);e.setValue(a),_i.set(e,{value:t,fragment:a})});function Pi(t){return t.replace(/]*)>/,(t,e)=>``)}const Fi={play:Pi(''),pause:Pi(''),loader:Pi(''),volumeOn:Pi(''),volumeOff:Pi('')};let Ai=class extends pi{constructor(){super(...arguments),this.icon="loader"}static get styles(){return ui`.Icon{width:100%;height:100%;color:var(--flipnote-player-icon-color,#f36a2d)}`}render(){return Ke`${Ei(Fi[this.icon])}`}};oe([ri({type:String})],Ai.prototype,"icon",void 0),Ai=oe([ii("flipnote-player-icon")],Ai);let Ti=class extends pi{constructor(){super(...arguments),this._src="",this._frame="0",this.cropped=!1,this.gifUrl="",this.imgTitle=""}static get styles(){return ui`.Image{width:inherit;height:inherit;image-rendering:-moz-crisp-edges;image-rendering:-webkit-crisp-edges;image-rendering:pixelated;image-rendering:crisp-edges;-ms-interpolation-mode:nearest-neighbor}`}set src(t){this.load(t)}get src(){return this._src}set frame(t){this._frame=t,this.note&&this.loadNote(this.note)}get frame(){return this._frame}render(){return Ke`${this.imgTitle}`}revokeUrl(){this.gif&&this.gif.dataUrl&&(this.gif.revokeUrl(),this.gifUrl="")}loadNote(t){this.note=t,this.revokeUrl();const e=this._frame;if("all"===e)this.gif=ne.fromFlipnote(t),this.gifUrl=this.gif.getUrl();else if("thumb"===e)this.gif=ne.fromFlipnoteFrame(t,t.thumbFrameIndex),this.gifUrl=this.gif.getUrl();else if(!isNaN(+e)){const i=parseInt(e);this.gif=ne.fromFlipnoteFrame(t,i),this.gifUrl=this.gif.getUrl()}this.gifUrl?(this.dispatchLoad(),this.imgTitle=t.getTitle()):this.dispatchError("Invalid frame attribute")}load(t){this._src=t,this.note=void 0;const e="true"===this.getAttribute("cropped");ht(t,{borderCrop:e}).then(t=>this.loadNote(t)).catch(t=>this.dispatchError(t))}disconnectedCallback(){this.revokeUrl()}dispatchLoad(){this.dispatchEvent(new Event("load"))}dispatchError(t){throw this.dispatchEvent(new ErrorEvent("error",{error:t})),new Error(t)}};oe([ri()],Ti.prototype,"src",null),oe([ri()],Ti.prototype,"frame",null),oe([ri({type:Boolean})],Ti.prototype,"cropped",void 0),oe([ni()],Ti.prototype,"gifUrl",void 0),oe([ni()],Ti.prototype,"imgTitle",void 0),Ti=oe([ii("flipnote-image")],Ti);const Ci=mi,ki=Ti;t.CanvasInterface=class{constructor(t,e,i,s){}},t.GifImage=ne,t.Html5Canvas=Xt,t.ImageComponent=ki,t.KwzParser=nt,t.Player=te,t.PlayerComponent=Ci,t.PlayerMixin=ee,t.PpmParser=Y,t.UniversalCanvas=Qt,t.WavAudio=ae,t.WebAudioPlayer=Zt,t.WebglCanvas=Yt,t.loadSource=ot,t.parseSource=ht,t.utils=H,t.version="5.11.0",Object.defineProperty(t,"__esModule",{value:!0})}));