From c5618cff7882d8372b4afa90ee05170fce236a2d Mon Sep 17 00:00:00 2001 From: spessasus Date: Sat, 14 Sep 2024 18:34:45 +0200 Subject: [PATCH] Fix audio normalization --- package.json | 2 +- src/spessasynth_lib/utils/buffer_to_wav.js | 4 ++-- src/website/minified/demo_main.min.js | 2 +- src/website/minified/local_main.min.js | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/package.json b/package.json index ddf117e0..e2284499 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "SpessaSynth", - "version": "3.20.17", + "version": "3.20.18", "type": "module", "scripts": { "start": "node src/website/server/server.js" diff --git a/src/spessasynth_lib/utils/buffer_to_wav.js b/src/spessasynth_lib/utils/buffer_to_wav.js index 95fcf8b7..f2d91991 100644 --- a/src/spessasynth_lib/utils/buffer_to_wav.js +++ b/src/spessasynth_lib/utils/buffer_to_wav.js @@ -123,8 +123,8 @@ export function audioBufferToWav(audioBuffer, normalizeAudio = true, channelOffs for (let i = 0; i < length; i++) { // interleave both channels - const sample1 = Math.min(1, Math.max(-1, channel1Data[i])) * multiplier; - const sample2 = Math.min(1, Math.max(-1,channel2Data[i])) * multiplier; + const sample1 = Math.min(32767, Math.max(-37268, channel1Data[i] * multiplier)); + const sample2 = Math.min(32767, Math.max(-37268, channel2Data[i] * multiplier)); // convert to 16-bit wavData[offset++] = sample1 & 0xff; diff --git a/src/website/minified/demo_main.min.js b/src/website/minified/demo_main.min.js index c2a345d9..9d64dd5d 100644 --- a/src/website/minified/demo_main.min.js +++ b/src/website/minified/demo_main.min.js @@ -256,7 +256,7 @@ var hm=(A=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(A,{get:(r,l)=>( `;for(let g of this.mainDiv.querySelectorAll("*[translate-path]"))l.bindObjectProperty(g,"textContent",g.getAttribute("translate-path"));for(let g of this.mainDiv.querySelectorAll("*[translate-path-title]"))l.bindObjectProperty(g,"textContent",g.getAttribute("translate-path-title")+".title"),l.bindObjectProperty(g,"title",g.getAttribute("translate-path-title")+".description");this.timeoutId=-1,this.visible=!1,this.locale=l}toggleDarkMode(){this.mainDiv.getElementsByClassName("player_info_wrapper")[0].classList.toggle("light_mode")}setTitle(r){document.getElementById("player_info_title").textContent=r}connectSequencer(r){this.seq=r,this.seq.addOnSongChangeEvent(l=>{let g=l.copyright.replaceAll(` `,""),d=(_0,k1,h2=!0)=>{let R1=document.getElementById(_0);if(k1.length>0)if(R1.parentElement.classList.remove("hidden"),R1.innerHTML="",k1.length>30&&h2){R1.classList.add("marquee");let _5=document.createElement("span");_5.textContent=k1,R1.appendChild(_5)}else R1.textContent=k1;else R1.parentElement.classList.add("hidden")};d("player_info_detail",g),d("player_info_time",f$(this.seq.duration).time),d("player_info_file_name",l.fileName,!1);let b=(_0,k1,h2,R1="")=>this.seq.midiData.RMIDInfo?.[_0]===void 0?k1:R1+h2.decode(this.seq.midiData.RMIDInfo?.[_0]).replace(/\0$/,""),h0=b("IENC","ascii",new TextDecoder),b0=new TextDecoder(h0);d("player_info_album",b("IPRD","",b0)),d("player_info_artist",b("IART","",b0)),d("player_info_genre",b("IGNR","",b0)),d("player_info_creation",b("ICRD","",b0)+b("ICRT","",b0,` -`)),d("player_info_comment",b("ICMT","",b0));let p0=this.mainDiv.getElementsByTagName("svg")[0],R0=this.mainDiv.getElementsByTagName("img")[0],E1=document.getElementById("player_info_background_image");if(!l.isEmbedded){p0.style.display="",R0.style.display="none",E1.style.setProperty("--bg-image","undefined");return}if(l.RMIDInfo.IPIC===void 0){p0.style.display="",R0.style.display="none",E1.style.setProperty("--bg-image","undefined");return}p0.style.display="none",R0.style.display="";let M=new Blob([l.RMIDInfo.IPIC.buffer]),K0=URL.createObjectURL(M);R0.src=K0,E1.style.setProperty("--bg-image",`url('${K0}')`)},"player-js-song-change")}setVisibility(r,l){if(r===this.visible)return;this.visible=r,this.timeoutId&&clearTimeout(this.timeoutId);let g=this.mainDiv;if(r){l.classList.add("out_animation"),this.savedCKWrapperHeight=l.clientHeight;let d=l.clientHeight,b=l.getBoundingClientRect().top;g.style.position="absolute",g.style.top=`${b}px`,g.style.height=`${d}px`,g.style.display="flex",setTimeout(()=>{g.classList.add("player_info_show"),document.body.style.overflow="hidden"},75),this.timeoutId=setTimeout(async()=>{l.style.display="none",g.style.position="",g.style.top="",g.style.height="",document.body.style.overflow=""},Tw*1e3)}else{let d=g.getBoundingClientRect().top;l.style.display="",l.style.position="absolute",l.style.top=`${d}px`,l.style.height=`${this.savedCKWrapperHeight}px`,g.classList.remove("player_info_show"),setTimeout(()=>{l.classList.remove("out_animation"),document.body.style.overflow="hidden"},75),this.timeoutId=setTimeout(()=>{g.style.display="none",l.style.position="",l.style.top="",l.style.height="",document.body.style.overflow=""},Tw*1e3)}}};var Fm=class{constructor(r){this.locale=Q$[r]||Q$[OB],this.fallbackLocale=Q$[OB],this.localeCode=r,this._boundObjectProperties=[]}getLocaleString(r,l=[]){let g=this._resolveLocalePath(r);return l.length>0?this._formatLocale(g,l):g}_applyPropertyInternal(r){if(r.isEdited)return;let l=this._resolveLocalePath(r.localePath);r.formattingArguments.length>0&&(l=this._formatLocale(l,r.formattingArguments)),r.object[r.propertyName]=l}_validatePropertyIntegrity(r){let l=this._resolveLocalePath(r.localePath);r.formattingArguments.length>0&&(l=this._formatLocale(l,r.formattingArguments)),r.object[r.propertyName]!==l&&(r.isEdited=!0)}onLocaleChanged=[];_formatLocale(r,l){return r.replace(/{(\d+)}/g,(g,d)=>typeof l[d]<"u"?l[d]:g)}bindObjectProperty(r,l,g,d=[]){let b={object:r,propertyName:l,localePath:g,formattingArguments:d,isEdited:!1};this._applyPropertyInternal(b),this._boundObjectProperties.push(b)}_resolveLocalePath(r,l=!1){if(!r.startsWith("locale."))throw new Error(`Invalid locale path: ${r} (it should start with "locale.")`);let g=r.split("."),d=l?this.fallbackLocale:this.locale;for(let b=1;b{this._validatePropertyIntegrity(d)}),this.locale=g,this._boundObjectProperties.forEach(d=>{this._applyPropertyInternal(d)}),this.onLocaleChanged.forEach(d=>d())}};function PB(A,r=!0,l=0,g={}){let d=A.getChannelData(l),b=A.getChannelData(l+1),h0=d.length,b0=2,p0=new n6(0),R0=Object.keys(g).length>0;if(R0){let J2=new TextEncoder,n3=[So("INFO"),a8("ICMT",J2.encode("Created with SpessaSynth"),!0)];g.artist&&n3.push(a8("IART",J2.encode(g.artist),!0)),g.album&&n3.push(a8("IPRD",J2.encode(g.album),!0)),g.genre&&n3.push(a8("IGNR",J2.encode(g.genre),!0)),g.title&&n3.push(a8("INAM",J2.encode(g.title),!0)),p0=a8("LIST",bs(n3))}let E1=44,M=h0*2*b0,K0=E1+M+p0.length-8,_0=new Uint8Array(E1);_0.set([82,73,70,70],0),_0.set(new Uint8Array([K0&255,K0>>8&255,K0>>16&255,K0>>24&255]),4),_0.set([87,65,86,69],8),_0.set([102,109,116,32],12),_0.set([16,0,0,0],16),_0.set([1,0],20),_0.set([2,0],22);let k1=A.sampleRate;_0.set(new Uint8Array([k1&255,k1>>8&255,k1>>16&255,k1>>24&255]),24);let h2=k1*2*b0;_0.set(new Uint8Array([h2&255,h2>>8&255,h2>>16&255,h2>>24&255]),28),_0.set([4,0],32),_0.set([16,0],34),_0.set([100,97,116,97],36),_0.set(new Uint8Array([M&255,M>>8&255,M>>16&255,M>>24&255]),40);let R1,_5=E1;R0?R1=new Uint8Array(E1+M+p0.length):R1=new Uint8Array(E1+M),R1.set(_0,0);let v2=32767;if(r){let J2=d.map((n3,U5)=>Math.max(Math.abs(n3),Math.abs(b[U5]))).reduce((n3,U5)=>Math.max(n3,U5));v2=J2>0?32767/J2:1}for(let J2=0;J2>8&255,R1[_5++]=U5&255,R1[_5++]=U5>>8&255}return R0&&R1.set(p0,_5),new Blob([R1.buffer],{type:"audio/wav"})}var Mm="synthetizer/worklet_processor.min.js";var Nw=1e3;async function Gw(A=!0,r=2,l=!1,g={}){if(this.isExporting=!0,!this.seq)throw new Error("No sequencer active");let d=manager.localeManager.getLocaleString("locale.exportAudio.formats.formats.wav.exportMessage.message"),b=manager.localeManager.getLocaleString("locale.exportAudio.formats.formats.wav.exportMessage.estimated"),h0=manager.localeManager.getLocaleString("locale.synthInit.genericLoading"),b0=E7(d,[{type:"text",textContent:h0},{type:"progress"}],9999999,!1),p0=await this.seq.getMIDI(),R0=p0.duration+r,E1=new OfflineAudioContext({numberOfChannels:l?32:2,sampleRate:this.context.sampleRate,length:this.context.sampleRate*R0});await E1.audioWorklet.addModule(new URL("../../spessasynth_lib/"+Mm,import.meta.url));let M=await this.synth.getSynthesizerSnapshot(),K0=this.soundFont,_0;try{_0=new ah(E1.destination,K0,!1,{parsedMIDI:p0,snapshot:M,oneOutput:l},{reverbEnabled:!0,chorusEnabled:!0,chorusConfig:void 0,reverbImpulseResponse:this.impulseResponse})}catch(a0){throw E7(this.localeManager.getLocaleString("locale.warnings.warning"),[{type:"text",textContent:this.localeManager.getLocaleString("locale.warnings.outOfMemory")}]),a0}let k1=b0.div.getElementsByTagName("p")[0],h2=b0.div.getElementsByClassName("notification_progress")[0],R1=Nw/1e3,_5=_0.currentTime,v2=R0,J2=.1,n3=setInterval(()=>{let a0=_0.currentTime-_5;_5=_0.currentTime;let J5=_0.currentTime/R0;h2.style.width=`${J5*100}%`;let s6=a0/R1,c6=(1-J5)/s6*R0;c6!==1/0&&(v2=J2*c6+(1-J2)*v2,k1.innerText=`${b} ${f$(v2).time}`)},Nw),U5=await E1.startRendering();if(h2.style.width="100%",clearInterval(n3),k1.innerText=this.localeManager.getLocaleString("locale.exportAudio.formats.formats.wav.exportMessage.convertWav"),await new Promise(a0=>setTimeout(a0,75)),!l)this.saveBlob(PB(U5,A,0,g),`${this.seqUI.currentSongTitle||"unnamed_song"}.wav`);else{let a0="locale.exportAudio.formats.formats.wav.options.separateChannels.saving.",J5=[],s6=new Set;for(let O6 of p0.usedChannelsOnTrack)O6.forEach(g6=>s6.add(g6));for(let O6=0;O6<16;O6++){let g6=!0;for(let u4=O6;u4{let J4=Ke.textContent;Ke.textContent=this.localeManager.getLocaleString("locale.exportAudio.formats.formats.wav.exportMessage.convertWav"),await new Promise(To=>setTimeout(To,75));let p9=PB(U5,!1,O6*2),_t=`${O6+1} - ${M.channelSnapshots[O6].patchName}.wav`;this.saveBlob(p9,_t),Ke.classList.add("green_button"),Ke.textContent=J4}})}let c6=E7(this.localeManager.getLocaleString(a0+"title"),J5,99999999,!0,void 0,{display:"flex",flexWrap:"wrap",flexDirection:"row"});c6.div.style.width="30rem"}O7(b0.id),this.isExporting=!1}async function Uw(){if(this.isExporting)return;let A="locale.exportAudio.formats.formats.wav.options.",r="locale.exportAudio.formats.metadata.",l=(R0,E1,M)=>this.seq.midiData.RMIDInfo?.[R0]===void 0?E1:M.decode(this.seq.midiData.RMIDInfo?.[R0]).replace(/\0$/,""),g=l("IENC","ascii",new TextDecoder),d=new TextDecoder(g),b=l("IPRD","",d),h0=l("IART","",d),b0=l("IGNR","",d),p0=[{type:"toggle",translatePathTitle:A+"normalizeVolume",attributes:{"normalize-volume-toggle":"1",checked:"true"}},{type:"input",translatePathTitle:A+"additionalTime",attributes:{value:"2",type:"number"}},{type:"toggle",translatePathTitle:A+"separateChannels",attributes:{"separate-channels-toggle":"1"}},{type:"input",translatePathTitle:r+"songTitle",attributes:{name:"song_title",type:"text",value:this.seqUI.currentSongTitle}},{type:"input",translatePathTitle:r+"album",attributes:{value:b,name:"album",type:"text"}},{type:"input",translatePathTitle:r+"artist",attributes:{value:h0,name:"artist",type:"text"}},{type:"input",translatePathTitle:r+"genre",attributes:{value:b0,name:"genre",type:"text"}},{type:"button",textContent:this.localeManager.getLocaleString(A+"confirm"),onClick:R0=>{O7(R0.id);let E1=R0.div.querySelector("input[normalize-volume-toggle]").checked,M=R0.div.querySelector("input[type='number']").value,K0=R0.div.querySelector("input[separate-channels-toggle]").checked,_0=R0.div.querySelector("input[name='artist']").value,k1=R0.div.querySelector("input[name='album']").value,h2=R0.div.querySelector("input[name='song_title']").value,R1=R0.div.querySelector("input[name='genre']").value,_5={artist:_0.length>0?_0:void 0,album:k1.length>0?k1:void 0,title:h2.length>0?h2:void 0,genre:R1.length>0?R1:void 0};this._doExportAudioData(E1,parseInt(M),K0,_5)}}];E7(this.localeManager.getLocaleString(A+"title"),p0,9999999,!0,this.localeManager)}async function Ow(){let A=await this.seq.getMIDI();ch(A,await this.synth.getSynthesizerSnapshot());let r=mm(A),l=new Blob([r],{type:"audio/mid"});this.saveBlob(l,`${this.seqUI.currentSongTitle||"unnamed_song"}.mid`)}function Pw(A,r){ei("%cSearching for all used programs and keys...",D1.info);let l=16+A.midiPortChannelOffsets.reduce((M,K0)=>K0>M?K0:M),g=[];for(let M=0;M{h0[k1]>=_0.length||_0[h0[k1]].ticks0;){let M=p0(),K0=A.tracks[M];if(h0[M]>=K0.length){b0--;continue}let _0=K0[h0[M]];if(h0[M]++,_0.messageStatusByte===J3.midiPort){R0[M]=_0.messageData[0];continue}let k1=_0.messageStatusByte&240;if(k1!==J3.noteOn&&k1!==J3.controllerChange&&k1!==J3.programChange&&k1!==J3.systemExclusive)continue;let h2=(_0.messageStatusByte&15)+A.midiPortChannelOffsets[R0[M]]||0,R1=g[h2];switch(k1){case J3.programChange:R1.program=_0.messageData[0],d(R1);break;case J3.controllerChange:if(_0.messageData[0]!==o6.bankSelect||E1==="gs"&&R1.drums)continue;let _5=_0.messageData[1],v2=Math.max(0,_5-A.bankOffset);if(E1==="xg"){let U5=_5===120||_5===126||_5===127;U5!==R1.drums?(R1.drums=U5,R1.bank=R1.drums?128:v2,d(R1)):R1.bank=R1.drums?128:v2;continue}g[h2].bank=v2;break;case J3.noteOn:if(_0.messageData[1]===0)continue;d(R1),b[R1.string].add(`${_0.messageData[0]}-${_0.messageData[1]}`);break;case J3.systemExclusive:if(_0.messageData[0]!==65||_0.messageData[2]!==66||_0.messageData[3]!==18||_0.messageData[4]!==64||!(_0.messageData[5]&16)||_0.messageData[6]!==21){_0.messageData[0]===67&&_0.messageData[2]===76&&_0.messageData[5]===126&&_0.messageData[6]===0&&(E1="xg");continue}let J2=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][_0.messageData[5]&15]+A.midiPortChannelOffsets[R0[M]],n3=!!(_0.messageData[7]>0&&_0.messageData[5]>>4);R1=g[J2],R1.drums=n3,R1.bank=n3?128:0,d(R1);break}}for(let M of Object.keys(b))b[M].size===0&&(Y5(`%cDetected change but no keys for %c${M}`,D1.info,D1.value),delete b[M]);return t4(),b}function Tm(A,r){function l(d,b){let h0=0;for(let b0=0;b0=R0.min&&K0.key<=R0.max&&K0.velocity>=E1.min&&K0.velocity<=E1.max){M=!0;break}M||(Y5(`%c${p0.sample.sampleName} %cremoved from %c${d.instrumentName}%c. Use count: %c${p0.useCount-1}`,D1.recognized,D1.info,D1.recognized,D1.info,D1.recognized),d.safeDeleteZone(b0)&&(h0++,b0--,Y5(`%c${p0.sample.sampleName} %cdeleted`,D1.recognized,D1.info)),p0.sample.useCount<1&&A.deleteSample(p0.sample))}return h0}ar("%cTrimming soundfont...",D1.info);let g=Pw(r,A);ei("%cModifying soundfont...",D1.info),Y5("Detected keys for midi:",g);for(let d=0;d{let M=E1.split("-");return{key:parseInt(M[0]),velocity:parseInt(M[1])}});ei(`%cTrimming %c${b.presetName}`,D1.info,D1.recognized),Y5(`Keys for ${b.presetName}:`,p0);let R0=0;for(let E1=0;E1=K0.min&&h2.key<=K0.max&&h2.velocity>=_0.min&&h2.velocity<=_0.max){k1=!0;let R1=l(M.instrument,p0);Y5(`%cTrimmed off %c${R1}%c zones from %c${M.instrument.instrumentName}`,D1.info,D1.recognized,D1.info,D1.recognized);break}k1||(R0++,b.deleteZone(E1),M.instrument.useCount<1&&A.deleteInstrument(M.instrument),E1--)}Y5(`%cTrimmed off %c${R0}%c zones from %c${b.presetName}`,D1.info,D1.recognized,D1.info,D1.recognized),t4()}}A.removeUnusedElements(),A.soundFontInfo.ICMT=`NOTE: This soundfont was trimmed by SpessaSynth to only contain presets used in "${r.midiName}" +`)),d("player_info_comment",b("ICMT","",b0));let p0=this.mainDiv.getElementsByTagName("svg")[0],R0=this.mainDiv.getElementsByTagName("img")[0],E1=document.getElementById("player_info_background_image");if(!l.isEmbedded){p0.style.display="",R0.style.display="none",E1.style.setProperty("--bg-image","undefined");return}if(l.RMIDInfo.IPIC===void 0){p0.style.display="",R0.style.display="none",E1.style.setProperty("--bg-image","undefined");return}p0.style.display="none",R0.style.display="";let M=new Blob([l.RMIDInfo.IPIC.buffer]),K0=URL.createObjectURL(M);R0.src=K0,E1.style.setProperty("--bg-image",`url('${K0}')`)},"player-js-song-change")}setVisibility(r,l){if(r===this.visible)return;this.visible=r,this.timeoutId&&clearTimeout(this.timeoutId);let g=this.mainDiv;if(r){l.classList.add("out_animation"),this.savedCKWrapperHeight=l.clientHeight;let d=l.clientHeight,b=l.getBoundingClientRect().top;g.style.position="absolute",g.style.top=`${b}px`,g.style.height=`${d}px`,g.style.display="flex",setTimeout(()=>{g.classList.add("player_info_show"),document.body.style.overflow="hidden"},75),this.timeoutId=setTimeout(async()=>{l.style.display="none",g.style.position="",g.style.top="",g.style.height="",document.body.style.overflow=""},Tw*1e3)}else{let d=g.getBoundingClientRect().top;l.style.display="",l.style.position="absolute",l.style.top=`${d}px`,l.style.height=`${this.savedCKWrapperHeight}px`,g.classList.remove("player_info_show"),setTimeout(()=>{l.classList.remove("out_animation"),document.body.style.overflow="hidden"},75),this.timeoutId=setTimeout(()=>{g.style.display="none",l.style.position="",l.style.top="",l.style.height="",document.body.style.overflow=""},Tw*1e3)}}};var Fm=class{constructor(r){this.locale=Q$[r]||Q$[OB],this.fallbackLocale=Q$[OB],this.localeCode=r,this._boundObjectProperties=[]}getLocaleString(r,l=[]){let g=this._resolveLocalePath(r);return l.length>0?this._formatLocale(g,l):g}_applyPropertyInternal(r){if(r.isEdited)return;let l=this._resolveLocalePath(r.localePath);r.formattingArguments.length>0&&(l=this._formatLocale(l,r.formattingArguments)),r.object[r.propertyName]=l}_validatePropertyIntegrity(r){let l=this._resolveLocalePath(r.localePath);r.formattingArguments.length>0&&(l=this._formatLocale(l,r.formattingArguments)),r.object[r.propertyName]!==l&&(r.isEdited=!0)}onLocaleChanged=[];_formatLocale(r,l){return r.replace(/{(\d+)}/g,(g,d)=>typeof l[d]<"u"?l[d]:g)}bindObjectProperty(r,l,g,d=[]){let b={object:r,propertyName:l,localePath:g,formattingArguments:d,isEdited:!1};this._applyPropertyInternal(b),this._boundObjectProperties.push(b)}_resolveLocalePath(r,l=!1){if(!r.startsWith("locale."))throw new Error(`Invalid locale path: ${r} (it should start with "locale.")`);let g=r.split("."),d=l?this.fallbackLocale:this.locale;for(let b=1;b{this._validatePropertyIntegrity(d)}),this.locale=g,this._boundObjectProperties.forEach(d=>{this._applyPropertyInternal(d)}),this.onLocaleChanged.forEach(d=>d())}};function PB(A,r=!0,l=0,g={}){let d=A.getChannelData(l),b=A.getChannelData(l+1),h0=d.length,b0=2,p0=new n6(0),R0=Object.keys(g).length>0;if(R0){let J2=new TextEncoder,n3=[So("INFO"),a8("ICMT",J2.encode("Created with SpessaSynth"),!0)];g.artist&&n3.push(a8("IART",J2.encode(g.artist),!0)),g.album&&n3.push(a8("IPRD",J2.encode(g.album),!0)),g.genre&&n3.push(a8("IGNR",J2.encode(g.genre),!0)),g.title&&n3.push(a8("INAM",J2.encode(g.title),!0)),p0=a8("LIST",bs(n3))}let E1=44,M=h0*2*b0,K0=E1+M+p0.length-8,_0=new Uint8Array(E1);_0.set([82,73,70,70],0),_0.set(new Uint8Array([K0&255,K0>>8&255,K0>>16&255,K0>>24&255]),4),_0.set([87,65,86,69],8),_0.set([102,109,116,32],12),_0.set([16,0,0,0],16),_0.set([1,0],20),_0.set([2,0],22);let k1=A.sampleRate;_0.set(new Uint8Array([k1&255,k1>>8&255,k1>>16&255,k1>>24&255]),24);let h2=k1*2*b0;_0.set(new Uint8Array([h2&255,h2>>8&255,h2>>16&255,h2>>24&255]),28),_0.set([4,0],32),_0.set([16,0],34),_0.set([100,97,116,97],36),_0.set(new Uint8Array([M&255,M>>8&255,M>>16&255,M>>24&255]),40);let R1,_5=E1;R0?R1=new Uint8Array(E1+M+p0.length):R1=new Uint8Array(E1+M),R1.set(_0,0);let v2=32767;if(r){let J2=d.map((n3,U5)=>Math.max(Math.abs(n3),Math.abs(b[U5]))).reduce((n3,U5)=>Math.max(n3,U5));v2=J2>0?32767/J2:1}for(let J2=0;J2>8&255,R1[_5++]=U5&255,R1[_5++]=U5>>8&255}return R0&&R1.set(p0,_5),new Blob([R1.buffer],{type:"audio/wav"})}var Mm="synthetizer/worklet_processor.min.js";var Nw=1e3;async function Gw(A=!0,r=2,l=!1,g={}){if(this.isExporting=!0,!this.seq)throw new Error("No sequencer active");let d=manager.localeManager.getLocaleString("locale.exportAudio.formats.formats.wav.exportMessage.message"),b=manager.localeManager.getLocaleString("locale.exportAudio.formats.formats.wav.exportMessage.estimated"),h0=manager.localeManager.getLocaleString("locale.synthInit.genericLoading"),b0=E7(d,[{type:"text",textContent:h0},{type:"progress"}],9999999,!1),p0=await this.seq.getMIDI(),R0=p0.duration+r,E1=new OfflineAudioContext({numberOfChannels:l?32:2,sampleRate:this.context.sampleRate,length:this.context.sampleRate*R0});await E1.audioWorklet.addModule(new URL("../../spessasynth_lib/"+Mm,import.meta.url));let M=await this.synth.getSynthesizerSnapshot(),K0=this.soundFont,_0;try{_0=new ah(E1.destination,K0,!1,{parsedMIDI:p0,snapshot:M,oneOutput:l},{reverbEnabled:!0,chorusEnabled:!0,chorusConfig:void 0,reverbImpulseResponse:this.impulseResponse})}catch(a0){throw E7(this.localeManager.getLocaleString("locale.warnings.warning"),[{type:"text",textContent:this.localeManager.getLocaleString("locale.warnings.outOfMemory")}]),a0}let k1=b0.div.getElementsByTagName("p")[0],h2=b0.div.getElementsByClassName("notification_progress")[0],R1=Nw/1e3,_5=_0.currentTime,v2=R0,J2=.1,n3=setInterval(()=>{let a0=_0.currentTime-_5;_5=_0.currentTime;let J5=_0.currentTime/R0;h2.style.width=`${J5*100}%`;let s6=a0/R1,c6=(1-J5)/s6*R0;c6!==1/0&&(v2=J2*c6+(1-J2)*v2,k1.innerText=`${b} ${f$(v2).time}`)},Nw),U5=await E1.startRendering();if(h2.style.width="100%",clearInterval(n3),k1.innerText=this.localeManager.getLocaleString("locale.exportAudio.formats.formats.wav.exportMessage.convertWav"),await new Promise(a0=>setTimeout(a0,75)),!l)this.saveBlob(PB(U5,A,0,g),`${this.seqUI.currentSongTitle||"unnamed_song"}.wav`);else{let a0="locale.exportAudio.formats.formats.wav.options.separateChannels.saving.",J5=[],s6=new Set;for(let O6 of p0.usedChannelsOnTrack)O6.forEach(g6=>s6.add(g6));for(let O6=0;O6<16;O6++){let g6=!0;for(let u4=O6;u4{let J4=Ke.textContent;Ke.textContent=this.localeManager.getLocaleString("locale.exportAudio.formats.formats.wav.exportMessage.convertWav"),await new Promise(To=>setTimeout(To,75));let p9=PB(U5,!1,O6*2),_t=`${O6+1} - ${M.channelSnapshots[O6].patchName}.wav`;this.saveBlob(p9,_t),Ke.classList.add("green_button"),Ke.textContent=J4}})}let c6=E7(this.localeManager.getLocaleString(a0+"title"),J5,99999999,!0,void 0,{display:"flex",flexWrap:"wrap",flexDirection:"row"});c6.div.style.width="30rem"}O7(b0.id),this.isExporting=!1}async function Uw(){if(this.isExporting)return;let A="locale.exportAudio.formats.formats.wav.options.",r="locale.exportAudio.formats.metadata.",l=(R0,E1,M)=>this.seq.midiData.RMIDInfo?.[R0]===void 0?E1:M.decode(this.seq.midiData.RMIDInfo?.[R0]).replace(/\0$/,""),g=l("IENC","ascii",new TextDecoder),d=new TextDecoder(g),b=l("IPRD","",d),h0=l("IART","",d),b0=l("IGNR","",d),p0=[{type:"toggle",translatePathTitle:A+"normalizeVolume",attributes:{"normalize-volume-toggle":"1",checked:"true"}},{type:"input",translatePathTitle:A+"additionalTime",attributes:{value:"2",type:"number"}},{type:"toggle",translatePathTitle:A+"separateChannels",attributes:{"separate-channels-toggle":"1"}},{type:"input",translatePathTitle:r+"songTitle",attributes:{name:"song_title",type:"text",value:this.seqUI.currentSongTitle}},{type:"input",translatePathTitle:r+"album",attributes:{value:b,name:"album",type:"text"}},{type:"input",translatePathTitle:r+"artist",attributes:{value:h0,name:"artist",type:"text"}},{type:"input",translatePathTitle:r+"genre",attributes:{value:b0,name:"genre",type:"text"}},{type:"button",textContent:this.localeManager.getLocaleString(A+"confirm"),onClick:R0=>{O7(R0.id);let E1=R0.div.querySelector("input[normalize-volume-toggle]").checked,M=R0.div.querySelector("input[type='number']").value,K0=R0.div.querySelector("input[separate-channels-toggle]").checked,_0=R0.div.querySelector("input[name='artist']").value,k1=R0.div.querySelector("input[name='album']").value,h2=R0.div.querySelector("input[name='song_title']").value,R1=R0.div.querySelector("input[name='genre']").value,_5={artist:_0.length>0?_0:void 0,album:k1.length>0?k1:void 0,title:h2.length>0?h2:void 0,genre:R1.length>0?R1:void 0};this._doExportAudioData(E1,parseInt(M),K0,_5)}}];E7(this.localeManager.getLocaleString(A+"title"),p0,9999999,!0,this.localeManager)}async function Ow(){let A=await this.seq.getMIDI();ch(A,await this.synth.getSynthesizerSnapshot());let r=mm(A),l=new Blob([r],{type:"audio/mid"});this.saveBlob(l,`${this.seqUI.currentSongTitle||"unnamed_song"}.mid`)}function Pw(A,r){ei("%cSearching for all used programs and keys...",D1.info);let l=16+A.midiPortChannelOffsets.reduce((M,K0)=>K0>M?K0:M),g=[];for(let M=0;M{h0[k1]>=_0.length||_0[h0[k1]].ticks0;){let M=p0(),K0=A.tracks[M];if(h0[M]>=K0.length){b0--;continue}let _0=K0[h0[M]];if(h0[M]++,_0.messageStatusByte===J3.midiPort){R0[M]=_0.messageData[0];continue}let k1=_0.messageStatusByte&240;if(k1!==J3.noteOn&&k1!==J3.controllerChange&&k1!==J3.programChange&&k1!==J3.systemExclusive)continue;let h2=(_0.messageStatusByte&15)+A.midiPortChannelOffsets[R0[M]]||0,R1=g[h2];switch(k1){case J3.programChange:R1.program=_0.messageData[0],d(R1);break;case J3.controllerChange:if(_0.messageData[0]!==o6.bankSelect||E1==="gs"&&R1.drums)continue;let _5=_0.messageData[1],v2=Math.max(0,_5-A.bankOffset);if(E1==="xg"){let U5=_5===120||_5===126||_5===127;U5!==R1.drums?(R1.drums=U5,R1.bank=R1.drums?128:v2,d(R1)):R1.bank=R1.drums?128:v2;continue}g[h2].bank=v2;break;case J3.noteOn:if(_0.messageData[1]===0)continue;d(R1),b[R1.string].add(`${_0.messageData[0]}-${_0.messageData[1]}`);break;case J3.systemExclusive:if(_0.messageData[0]!==65||_0.messageData[2]!==66||_0.messageData[3]!==18||_0.messageData[4]!==64||!(_0.messageData[5]&16)||_0.messageData[6]!==21){_0.messageData[0]===67&&_0.messageData[2]===76&&_0.messageData[5]===126&&_0.messageData[6]===0&&(E1="xg");continue}let J2=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][_0.messageData[5]&15]+A.midiPortChannelOffsets[R0[M]],n3=!!(_0.messageData[7]>0&&_0.messageData[5]>>4);R1=g[J2],R1.drums=n3,R1.bank=n3?128:0,d(R1);break}}for(let M of Object.keys(b))b[M].size===0&&(Y5(`%cDetected change but no keys for %c${M}`,D1.info,D1.value),delete b[M]);return t4(),b}function Tm(A,r){function l(d,b){let h0=0;for(let b0=0;b0=R0.min&&K0.key<=R0.max&&K0.velocity>=E1.min&&K0.velocity<=E1.max){M=!0;break}M||(Y5(`%c${p0.sample.sampleName} %cremoved from %c${d.instrumentName}%c. Use count: %c${p0.useCount-1}`,D1.recognized,D1.info,D1.recognized,D1.info,D1.recognized),d.safeDeleteZone(b0)&&(h0++,b0--,Y5(`%c${p0.sample.sampleName} %cdeleted`,D1.recognized,D1.info)),p0.sample.useCount<1&&A.deleteSample(p0.sample))}return h0}ar("%cTrimming soundfont...",D1.info);let g=Pw(r,A);ei("%cModifying soundfont...",D1.info),Y5("Detected keys for midi:",g);for(let d=0;d{let M=E1.split("-");return{key:parseInt(M[0]),velocity:parseInt(M[1])}});ei(`%cTrimming %c${b.presetName}`,D1.info,D1.recognized),Y5(`Keys for ${b.presetName}:`,p0);let R0=0;for(let E1=0;E1=K0.min&&h2.key<=K0.max&&h2.velocity>=_0.min&&h2.velocity<=_0.max){k1=!0;let R1=l(M.instrument,p0);Y5(`%cTrimmed off %c${R1}%c zones from %c${M.instrument.instrumentName}`,D1.info,D1.recognized,D1.info,D1.recognized);break}k1||(R0++,b.deleteZone(E1),M.instrument.useCount<1&&A.deleteInstrument(M.instrument),E1--)}Y5(`%cTrimmed off %c${R0}%c zones from %c${b.presetName}`,D1.info,D1.recognized,D1.info,D1.recognized),t4()}}A.removeUnusedElements(),A.soundFontInfo.ICMT=`NOTE: This soundfont was trimmed by SpessaSynth to only contain presets used in "${r.midiName}" `+A.soundFontInfo.ICMT,Y5("%cSoundfont modified!",D1.recognized),t4(),t4()}function Hw(){let A=4;for(let g of this.instruments)A+=g.instrumentZones.reduce((d,b)=>(b.generators=b.generators.filter(h0=>h0.generatorType!==b1.sampleID&&h0.generatorType!==b1.keyRange&&h0.generatorType!==b1.velRange),(b.velRange.max!==127||b.velRange.min!==0)&&b.generators.unshift({generatorType:b1.velRange,generatorValue:b.velRange.max<<8|b.velRange.min}),(b.keyRange.max!==127||b.keyRange.min!==0)&&b.generators.unshift({generatorType:b1.keyRange,generatorValue:b.keyRange.max<<8|b.keyRange.min}),b.isGlobal||b.generators.push({generatorType:b1.sampleID,generatorValue:this.samples.indexOf(b.sample)}),b.generators.length*4+d),0);let r=new n6(A),l=0;for(let g of this.instruments)for(let d of g.instrumentZones){d.generatorZoneStartIndex=l;for(let b of d.generators)B9(r,b.generatorType),B9(r,b.generatorValue),l++}return $t(r,0),o8(new ye("igen",r.length,r))}function qw(A,r,l,g,d){let b=this.samples.map((R0,E1)=>{l&&R0.compressSample(g,d);let M=R0.getRawData();return Y5(`%cEncoded sample %c${E1}. ${R0.sampleName}%c of %c${this.samples.length}`,D1.info,D1.recognized,D1.info,D1.recognized),M}),h0=this.samples.reduce((R0,E1,M)=>R0+b[M].length+46,0),b0=new n6(h0);this.samples.forEach((R0,E1)=>{let M=b[E1],K0,_0,k1=M.length;R0.isCompressed?(K0=b0.currentIndex,_0=K0+M.length):(K0=b0.currentIndex/2,_0=K0+M.length/2,k1+=46),A.push(K0),b0.set(M,b0.currentIndex),b0.currentIndex+=k1,r.push(_0)});let p0=o8(new ye("smpl",b0.length,b0),new n6([115,100,116,97]));return o8(new ye("LIST",p0.length,p0))}function Yw(A,r){let g=new n6(46*(this.samples.length+1));return this.samples.forEach((d,b)=>{di(g,d.sampleName,20);let h0=A[b];$t(g,h0);let b0=r[b];$t(g,b0);let p0=d.sampleLoopStartIndex/2+h0,R0=d.sampleLoopEndIndex/2+h0;d.isCompressed&&(p0-=h0,R0-=h0),$t(g,p0),$t(g,R0),$t(g,d.sampleRate),g[g.currentIndex++]=d.samplePitch,g[g.currentIndex++]=d.samplePitchCorrection,B9(g,d.sampleLink),B9(g,d.sampleType)}),di(g,"EOS",46),o8(new ye("shdr",g.length,g))}function Jw(){let A=10;for(let g of this.instruments)A+=g.instrumentZones.reduce((d,b)=>b.modulators.length*10+d,0);let r=new n6(A),l=0;for(let g of this.instruments)for(let d of g.instrumentZones){d.modulatorZoneStartIndex=l;for(let b of d.modulators)B9(r,b.modulatorSource),B9(r,b.modulatorDestination),B9(r,b.transformAmount),B9(r,b.modulationSecondarySrc),B9(r,b.transformType),l++}return C$(r,0,10),o8(new ye("imod",r.length,r))}function Kw(){let A=this.instruments.reduce((b,h0)=>h0.instrumentZones.length*4+b,4),r=new n6(A),l=0,g=0,d=0;for(let b of this.instruments){b.instrumentZoneIndex=l;for(let h0 of b.instrumentZones)h0.zoneID=l,B9(r,g),B9(r,d),g+=h0.generators.length,d+=h0.modulators.length,l++}return B9(r,g),B9(r,d),o8(new ye("ibag",r.length,r))}function Vw(){let A=this.instruments.length*22+22,r=new n6(A),l=0,g=0;for(let d of this.instruments)di(r,d.instrumentName,20),B9(r,l),l+=d.instrumentZones.length,d.instrumentID=g,g++;return di(r,"EOI",20),B9(r,l),o8(new ye("inst",r.length,r))}function zw(){let A=4;for(let g of this.presets)A+=g.presetZones.reduce((d,b)=>(b.generators=b.generators.filter(h0=>h0.generatorType!==b1.instrument&&h0.generatorType!==b1.keyRange&&h0.generatorType!==b1.velRange),(b.velRange.max!==127||b.velRange.min!==0)&&b.generators.unshift({generatorType:b1.velRange,generatorValue:b.velRange.max<<8|b.velRange.min}),(b.keyRange.max!==127||b.keyRange.min!==0)&&b.generators.unshift({generatorType:b1.keyRange,generatorValue:b.keyRange.max<<8|b.keyRange.min}),b.isGlobal||b.generators.push({generatorType:b1.instrument,generatorValue:this.instruments.indexOf(b.instrument)}),b.generators.length*4+d),0);let r=new n6(A),l=0;for(let g of this.presets)for(let d of g.presetZones){d.generatorZoneStartIndex=l;for(let b of d.generators)B9(r,b.generatorType),B9(r,b.generatorValue);l+=d.generators.length}return B9(r,0),B9(r,0),o8(new ye("pgen",r.length,r))}function Zw(){let A=10;for(let g of this.presets)A+=g.presetZones.reduce((d,b)=>b.modulators.length*10+d,0);let r=new n6(A),l=0;for(let g of this.presets)for(let d of g.presetZones){d.modulatorZoneStartIndex=l;for(let b of d.modulators)B9(r,b.modulatorSource),B9(r,b.modulatorDestination),B9(r,b.transformAmount),B9(r,b.modulationSecondarySrc),B9(r,b.transformType),l++}return C$(r,0,10),o8(new ye("pmod",r.length,r))}function Ww(){let A=this.presets.reduce((b,h0)=>h0.presetZones.length*4+b,4),r=new n6(A),l=0,g=0,d=0;for(let b of this.presets){b.presetZoneStartIndex=l;for(let h0 of b.presetZones)h0.zoneID=l,B9(r,g),B9(r,d),g+=h0.generators.length,d+=h0.modulators.length,l++}return B9(r,g),B9(r,d),o8(new ye("pbag",r.length,r))}function jw(){let A=this.presets.length*38+38,r=new n6(A),l=0;for(let g of this.presets)di(r,g.presetName,20),B9(r,g.program),B9(r,g.bank),B9(r,l),$t(r,g.library),$t(r,g.genre),$t(r,g.morphology),l+=g.presetZones.length;return di(r,"EOP",20),B9(r,0),B9(r,0),B9(r,l),$t(r,0),$t(r,0),$t(r,0),o8(new ye("phdr",r.length,r))}var KD={compress:!1,compressionQuality:.5,compressionFunction:void 0};function Xw(A=KD){if(A.compress&&typeof A.compressionFunction!="function")throw new TypeError("No compression function supplied but compression enabled.");ei("%cSaving soundfont...",D1.info),Y5(`%cCompression: %c${A?.compress||"false"}%c quality: %c${A?.compressionQuality||"none"}`,D1.info,D1.recognized,D1.info,D1.recognized),Y5("%cWriting INFO...",D1.info);let r=[];this.soundFontInfo.ISFT="SpessaSynth",A?.compress&&(this.soundFontInfo.ifil="3.0");for(let[n3,U5]of Object.entries(this.soundFontInfo))if(n3==="ifil"||n3==="iver"){let a0=parseInt(U5.split(".")[0]),J5=parseInt(U5.split(".")[1]),s6=new n6(4);B9(s6,a0),B9(s6,J5),r.push(o8(new ye(n3,4,s6)))}else{let a0=new n6(U5.length);di(a0,U5),r.push(o8(new ye(n3,U5.length,a0)))}let l=bs([new n6([73,78,70,79]),...r]),g=o8(new ye("LIST",l.length,l));Y5("%cWriting SDTA...",D1.info);let d=[],b=[],h0=qw.call(this,d,b,A?.compress,A?.compressionQuality||.5,A.compressionFunction);Y5("%cWriting PDTA...",D1.info),Y5("%cWriting SHDR...",D1.info);let b0=Yw.call(this,d,b);Y5("%cWriting IGEN...",D1.info);let p0=Hw.call(this);Y5("%cWriting IMOD...",D1.info);let R0=Jw.call(this);Y5("%cWriting IBAG...",D1.info);let E1=Kw.call(this);Y5("%cWriting INST...",D1.info);let M=Vw.call(this),K0=zw.call(this);Y5("%cWriting PMOD...",D1.info);let _0=Zw.call(this);Y5("%cWriting PBAG...",D1.info);let k1=Ww.call(this);Y5("%cWriting PHDR...",D1.info);let h2=jw.call(this),R1=bs([new n6([112,100,116,97]),h2,k1,_0,K0,M,E1,R0,p0,b0]),_5=o8(new ye("LIST",R1.length,R1));Y5("%cWriting the output file...",D1.info);let v2=bs([new n6([115,102,98,107]),g,h0,_5]),J2=o8(new ye("RIFF",v2.length,v2));return Y5(`%cSaved succesfully! Final file size: %c${J2.length}`,D1.info,D1.recognized),t4(),J2}var y$=class A{constructor(r=void 0){this.soundFontInfo={},this.presets=[],this.samples=[],this.instruments=[],r?.presets&&(this.presets.push(...r.presets),this.soundFontInfo=r.info)}removeUnusedElements(){this.instruments.forEach(r=>{r.useCount<1&&r.instrumentZones.forEach(l=>{l.isGlobal||l.sample.useCount--})}),this.instruments=this.instruments.filter(r=>r.useCount>0),this.samples=this.samples.filter(r=>r.useCount>0)}deleteInstrument(r){if(r.useCount>0)throw new Error(`Cannot delete an instrument that has ${r.useCount} usages.`);this.instruments.splice(this.instruments.indexOf(r),1),r.deleteInstrument(),this.removeUnusedElements()}deleteSample(r){if(r.useCount>0)throw new Error(`Cannot delete sample that has ${r.useCount} usages.`);this.samples.splice(this.samples.indexOf(r),1),this.removeUnusedElements()}deletePreset(r){r.deletePreset(),this.presets.splice(this.presets.indexOf(r),1),this.removeUnusedElements()}getPresetNoFallback(r,l,g=!1){let d=this.presets.find(b=>b.bank===r&&b.program===l);if(d)return d;if(g!==!1)return r===128?this.presets.find(b=>b.bank===128):this.presets.find(b=>b.program===l)}setSampleIDOffset(r){this.presets.forEach(l=>l.sampleIDOffset=r)}getPreset(r,l){let g=this.presets.find(d=>d.bank===r&&d.program===l);return g||(g=this.presets.find(d=>d.program===l&&d.bank!==128),r===128&&(g=this.presets.find(d=>d.bank===128&&d.program===l),g||(g=this.presets.find(d=>d.bank===128))),g&&_4(`%cPreset ${r}.${l} not found. Replaced with %c${g.presetName} (${g.bank}.${g.program})`,D1.warn,D1.recognized)),g||(_4(`Preset ${l} not found. Defaulting to`,this.presets[0].presetName),g=this.presets[0]),g}getPresetByName(r){let l=this.presets.find(g=>g.presetName===r);return l||(_4("Preset not found. Defaulting to:",this.presets[0].presetName),l=this.presets[0]),l}static mergeSoundfonts(...r){let l=r.shift(),g=l.presets;for(;r.length;)r.shift().presets.forEach(b=>{g.find(h0=>h0.bank===b.bank&&h0.program===b.program)===void 0&&g.push(b)});return new A({presets:g,info:l.soundFontInfo})}};y$.prototype.write=Xw;function ek(A){ei("%cLoading instruments...",D1.info);for(let r=0;rr.deleteZone()),this.presetZones.length=0}deleteZone(r){this.presetZones[r].deleteZone(),this.presetZones.splice(r,1)}preload(r,l){for(let g=r;g{b.sample.isSampleLoaded||b.sample.getAudioData()})}preloadSpecific(r,l){this.getSamplesAndGenerators(r,l).forEach(g=>{g.sample.isSampleLoaded||g.sample.getAudioData()})}getSamplesAndGenerators(r,l){let g=this.foundSamplesAndGenerators[r][l];if(g)return g;if(this.presetZones.length<1)return[];function d(K0,_0,k1){return k1>=K0&&k1<=_0}function b(K0,_0){return K0.modulatorSource===_0.modulatorSource&&K0.modulatorDestination===_0.modulatorDestination&&K0.modulationSecondarySrc===_0.modulationSecondarySrc&&K0.transformType===_0.transformType}function h0(K0,_0){K0.push(..._0.filter(k1=>!K0.find(h2=>h2.generatorType===k1.generatorType)))}function b0(K0,_0){K0.push(..._0.filter(k1=>!K0.find(h2=>b(k1,h2))))}let p0=[],R0=this.presetZones[0].isGlobal?[...this.presetZones[0].generators]:[],E1=this.presetZones[0].isGlobal?[...this.presetZones[0].modulators]:[];return this.presetZones.filter(K0=>d(K0.keyRange.min,K0.keyRange.max,r)&&d(K0.velRange.min,K0.velRange.max,l)&&!K0.isGlobal).forEach(K0=>{if(K0.instrument.instrumentZones.length<1)return;let _0=K0.generators,k1=K0.modulators,h2=K0.instrument.instrumentZones[0].isGlobal?[...K0.instrument.instrumentZones[0].generators]:[],R1=K0.instrument.instrumentZones[0].isGlobal?[...K0.instrument.instrumentZones[0].modulators]:[];K0.instrument.instrumentZones.filter(v2=>d(v2.keyRange.min,v2.keyRange.max,r)&&d(v2.velRange.min,v2.velRange.max,l)&&!v2.isGlobal).forEach(v2=>{let J2=[...v2.generators],n3=[...v2.modulators];h0(_0,R0),h0(J2,h2),b0(k1,E1),b0(n3,R1),b0(n3,fy);let U5=[...n3];for(let a0=0;a0b(J5,c6));s6!==-1?U5[s6]=U5[s6].sumTransform(J5):U5.push(J5)}p0.push({instrumentGenerators:J2,presetGenerators:_0,modulators:U5,sample:v2.sample,sampleID:v2.generators.find(a0=>a0.generatorType===b1.sampleID).generatorValue})})}),this.foundSamplesAndGenerators[r][l]=p0,p0}};var vC=class{velRange={min:0,max:127};keyRange={min:0,max:127};isGlobal=!1;generators=[];modulators=[]};var Lo=class extends vC{sample=void 0;useCount=0;deleteZone(){this.useCount--,!this.isGlobal&&this.sample.useCount--}},uh=class extends vC{instrument=void 0;deleteZone(){this.isGlobal||this.instrument.removeUseCount()}};var dh=class{constructor(){this.instrumentName="",this.instrumentZones=[],this._useCount=0}addUseCount(){this._useCount++,this.instrumentZones.forEach(r=>r.useCount++)}removeUseCount(){this._useCount--;for(let r=0;rr.deleteZone()),this.instrumentZones.length=0}safeDeleteZone(r){return this.instrumentZones[r].useCount--,this.instrumentZones[r].useCount<1?(this.deleteZone(r),!0):!1}deleteZone(r){this.instrumentZones[r].deleteZone(),this.instrumentZones.splice(r,1)}};var Nm=class extends fh{constructor(r,l){super(),this.program=l&127,this.bank=r>>8&127,r>>31&&(this.bank=128),this.DLSInstrument=new dh,this.DLSInstrument.addUseCount();let d=new uh;d.instrument=this.DLSInstrument,this.presetZones=[d]}};function tk(A){this.verifyHeader(A,"LIST"),this.verifyText(ue(A.chunkData,4),"ins ");let r=[];for(;A.chunkData.length>A.chunkData.currentIndex;)r.push(f4(A.chunkData));let l=r.find(_0=>_0.header==="insh");if(!l)throw t4(),new Error("No instrument header!");let g=r3(l.chunkData,4),d=r3(l.chunkData,4),b=r3(l.chunkData,4),h0=new Nm(d,b),b0="unnamedPreset",p0=Si(r,"INFO");if(p0){let _0=f4(p0.chunkData);for(;_0.header!=="INAM";)_0=f4(p0.chunkData);b0=ue(_0.chunkData,_0.chunkData.length).trim()}h0.presetName=b0,h0.DLSInstrument.instrumentName=b0,ar(`%cParsing %c"${b0}"%c...`,D1.info,D1.recognized,D1.info);let R0=Si(r,"lrgn");if(!R0)throw t4(),new Error("No region list!");let E1=new Lo;E1.isGlobal=!0;let M=Si(r,"lart"),K0=Si(r,"lar2");this.readLart(M,K0,E1),h0.DLSInstrument.instrumentZones.push(E1);for(let _0=0;_0>10&15;_5===Qn.linear&&R1!==Qn.linear&&(_5=R1);let v2=g>>14&1,J2=g>>15&1;h0===b1.initialAttenuation&&(J2=!J2),M=pn(_5,v2,J2,b0.isCC,b0.enum)}let K0=g>>4&15,_0=g>>8&1,k1=g>>9&1,h2=pn(K0,_0,k1,E1.isCC,E1.enum);if(p0){let R1=h2;h2=M,M=R1}return new o7({srcEnum:M,secSrcEnum:h2,dest:h0,transform:0,amt:d})}function HB(A,r){let l=A.chunkData,g=[],d=[];r3(l,4);let b=r3(l,4);for(let h0=0;h0>16;if(b0===0&&p0===0&&E1===0){let _0;switch(R0){case C6.pan:_0=new n9(b1.pan,K0);break;case C6.gain:_0=new n9(b1.initialAttenuation,-K0*10/.4);break;case C6.filterCutoff:_0=new n9(b1.initialFilterFc,K0);break;case C6.filterQ:_0=new n9(b1.initialFilterQ,K0);break;case C6.modLfoFreq:_0=new n9(b1.freqModLFO,K0);break;case C6.modLfoDelay:_0=new n9(b1.delayModLFO,K0);break;case C6.vibLfoFreq:_0=new n9(b1.freqVibLFO,K0);break;case C6.vibLfoDelay:_0=new n9(b1.delayVibLFO,K0);break;case C6.volEnvDelay:_0=new n9(b1.delayVolEnv,K0);break;case C6.volEnvAttack:_0=new n9(b1.attackVolEnv,K0);break;case C6.volEnvHold:_0=new n9(b1.holdVolEnv,K0);break;case C6.volEnvDecay:_0=new n9(b1.decayVolEnv,K0);break;case C6.volEnvRelease:_0=new n9(b1.releaseVolEnv,K0);break;case C6.volEnvSustain:let k1=(1e3-K0)/10;_0=new n9(b1.sustainVolEnv,k1*10);break;case C6.modEnvDelay:_0=new n9(b1.delayModEnv,K0);break;case C6.modEnvAttack:_0=new n9(b1.attackModEnv,K0);break;case C6.modEnvHold:_0=new n9(b1.holdModEnv,K0);break;case C6.modEnvDecay:_0=new n9(b1.decayModEnv,K0);break;case C6.modEnvRelease:_0=new n9(b1.releaseModEnv,K0);break;case C6.modEnvSustain:let h2=1e3-K0;_0=new n9(b1.sustainModEnv,h2);break;case C6.reverbSend:_0=new n9(b1.reverbEffectsSend,K0);break;case C6.chorusSend:_0=new n9(b1.chorusEffectsSend,K0);break;case C6.pitch:let R1=Math.floor(K0/100),_5=Math.floor(K0-R1*100);_0=new n9(b1.fineTune,_5),g.push(new n9(b1.coarseTune,R1));break}_0&&g.push(_0)}else{let _0=!0;if(p0===y4.none)if(b0===y4.modLfo&&R0===C6.pitch)g.push(new n9(b1.modLfoToPitch,K0));else if(b0===y4.modLfo&&R0===C6.gain)g.push(new n9(b1.modLfoToVolume,K0));else if(b0===y4.modLfo&&R0===C6.filterCutoff)g.push(new n9(b1.modLfoToFilterFc,K0));else if(b0===y4.vibratoLfo&&R0===C6.pitch)g.push(new n9(b1.vibLfoToPitch,K0));else if(b0===y4.modEnv&&R0===C6.pitch)g.push(new n9(b1.modEnvToPitch,K0));else if(b0===y4.modEnv&&R0===C6.filterCutoff)g.push(new n9(b1.modEnvToFilterFc,K0));else if(b0===y4.keyNum&&R0===C6.volEnvHold){g.push(new n9(b1.keyNumToVolEnvHold,K0/-128));let k1=Math.round(60/128*K0);g.forEach(h2=>{h2.generatorType===b1.holdVolEnv&&(h2.generatorValue+=k1)})}else if(b0===y4.keyNum&&R0===C6.volEnvDecay){g.push(new n9(b1.keyNumToVolEnvDecay,K0/-128));let k1=Math.round(60/128*K0);g.forEach(h2=>{h2.generatorType===b1.decayVolEnv&&(h2.generatorValue+=k1)})}else if(b0===y4.keyNum&&R0===C6.modEnvHold){g.push(new n9(b1.keyNumToModEnvHold,K0/-128));let k1=Math.round(60/128*K0);g.forEach(h2=>{h2.generatorType===b1.holdModEnv&&(h2.generatorValue+=k1)})}else if(b0===y4.keyNum&&R0===C6.modEnvDecay){g.push(new n9(b1.keyNumToModEnvDecay,K0/-128));let k1=Math.round(60/128*K0);g.forEach(h2=>{h2.generatorType===b1.decayModEnv&&(h2.generatorValue+=k1)})}else _0=!1;else _0=!1;if(_0===!1){let k1=rk(b0,p0,R0,E1,K0);k1?(d.push(k1),Y5("%cSucceeded converting to SF2 Modulator!",D1.recognized)):_4("Failed converting to SF2 Modulator!")}}}return d.find(h0=>h0.modulatorDestination===b1.reverbEffectsSend)===void 0&&d.push(new o7({srcEnum:219,dest:b1.reverbEffectsSend,amt:1e3,secSrcEnum:0,transform:0})),d.find(h0=>h0.modulatorDestination===b1.chorusEffectsSend)===void 0&&d.push(new o7({srcEnum:221,dest:b1.chorusEffectsSend,amt:1e3,secSrcEnum:0,transform:0})),r&&d.push(new o7({srcEnum:129,dest:b1.vibLfoToPitch,amt:0,secSrcEnum:0,transform:0}),new o7({srcEnum:13,dest:b1.vibLfoToPitch,amt:0,secSrcEnum:0,transform:0})),{modulators:d,generators:g}}function nk(A,r,l){if(A)for(;A.chunkData.currentIndexA.chunkData.currentIndex;)r.push(f4(A.chunkData));let l=r.find(a0=>a0.header==="rgnh"),g=r3(l.chunkData,2),d=r3(l.chunkData,2),b=r3(l.chunkData,2),h0=r3(l.chunkData,2),b0=new Gm({min:g,max:d},{min:b,max:h0});r3(l.chunkData,2);let p0=r3(l.chunkData,2);p0!==0&&b0.generators.push(new n9(b1.exclusiveClass,p0));let R0=Si(r,"lart"),E1=Si(r,"lar2");this.readLart(R0,E1,b0),b0.isGlobal=!1;let M=r.find(a0=>a0.header==="wsmp");r3(M.chunkData,4);let K0=r3(M.chunkData,2);r3(M.chunkData,2);let h2=(r3(M.chunkData,4)|0)/-655360*10/.4;r3(M.chunkData,4);let R1=r3(M.chunkData,4),_5,v2={start:0,end:0};if(R1===0)_5=0;else{r3(M.chunkData,4),r3(M.chunkData,4)===0?_5=1:_5=3,v2.start=r3(M.chunkData,4);let J5=r3(M.chunkData,4);v2.end=v2.start+J5}let J2=r.find(a0=>a0.header==="wlnk");if(J2===void 0)return;r3(J2.chunkData,2),r3(J2.chunkData,2),r3(J2.chunkData,4);let n3=r3(J2.chunkData,4),U5=this.samples[n3];if(U5===void 0)throw new Error("Invalid sample ID!");return b0.setWavesample(h2,_5,v2,K0,U5,n3),b0}var Ih=class{constructor(r,l,g,d,b,h0,b0,p0){this.sampleName=r,this.sampleRate=l,this.samplePitch=g,this.samplePitchCorrection=d,this.sampleLink=b,this.sampleType=h0,this.sampleLoopStartIndex=b0,this.sampleLoopEndIndex=p0,this.isCompressed=(h0&16)>0,this.compressedData=void 0,this.useCount=0}getRawData(){let r=new Error("Not implemented");throw r.name="NotImplementedError",r}compressSample(r,l){if(!this.isCompressed)try{this.compressedData=l([this.getAudioData()],1,this.sampleRate,r),this.sampleType|=16,this.isCompressed=!0}catch{_4(`Failed to compress ${this.sampleName}. Leaving as uncompressed!`),this.isCompressed=!1,this.compressedData=void 0,this.sampleType&=-17}}getAudioData(){let r=new Error("Not implemented");throw r.name="NotImplementedError",r}};var Um=class extends Ih{constructor(r,l,g,d,b,h0,b0){super(r,l,g,d,0,1,b*2,(h0-1)*2),this.sampleData=b0}getAudioData(){return this.sampleData}sampleData;getRawData(){if(this.isCompressed){if(!this.compressedData)throw new Error("Compressed but no data??");return this.compressedData}let r=new Uint8Array(this.sampleData.length*2);for(let l=0;l>8&255}return r}};function Ak(A){ei("%cLoading Wave samples...",D1.recognized);let r=0;for(;A.chunkData.currentIndexs6.header==="fmt ");if(!d)throw new Error("No fmt chunk in the wave file!");if(r3(d.chunkData,2)!==1)throw new Error("Only PCM format in WAVE is supported.");if(r3(d.chunkData,2)!==1)throw new Error("Only mono samples are supported.");let b0=r3(d.chunkData,4);r3(d.chunkData,4),r3(d.chunkData,2);let p0=r3(d.chunkData,2),R0=p0/8,E1=Math.pow(2,R0*8-1),M=Math.pow(2,R0*8),K0,_0=!1;p0===8?(K0=255,_0=!0):K0=E1;let k1=g.find(s6=>s6.header==="data");if(!k1)throw new Error("No data chunk in the wave chunk!");let h2=k1.size/R0,R1=new Float32Array(h2);for(let s6=0;s6=E1&&(c6-=M),R1[s6]=c6/K0)}let _5=60,v2=0,J2=0,n3=R1.length-1,U5=g.find(s6=>s6.header==="wsmp");if(U5){if(r3(U5.chunkData,4),_5=r3(U5.chunkData,2),v2=lh(U5.chunkData[U5.chunkData.currentIndex++],U5.chunkData[U5.chunkData.currentIndex++]),r3(U5.chunkData,4),r3(U5.chunkData,4),r3(U5.chunkData,4)===1){r3(U5.chunkData,8),J2=r3(U5.chunkData,4);let c6=r3(U5.chunkData,4);n3=J2+c6}}else _4("No wsmp chunk in wave... using sane defaults.");let a0=Si(g,"INFO"),J5=`Unnamed ${r}`;if(a0){let s6=f4(a0.chunkData);for(;s6.header!=="INAM"&&a0.chunkData.currentIndextypeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(r,l)=>( `;for(let g of this.mainDiv.querySelectorAll("*[translate-path]"))l.bindObjectProperty(g,"textContent",g.getAttribute("translate-path"));for(let g of this.mainDiv.querySelectorAll("*[translate-path-title]"))l.bindObjectProperty(g,"textContent",g.getAttribute("translate-path-title")+".title"),l.bindObjectProperty(g,"title",g.getAttribute("translate-path-title")+".description");this.timeoutId=-1,this.visible=!1,this.locale=l}toggleDarkMode(){this.mainDiv.getElementsByClassName("player_info_wrapper")[0].classList.toggle("light_mode")}setTitle(r){document.getElementById("player_info_title").textContent=r}connectSequencer(r){this.seq=r,this.seq.addOnSongChangeEvent(l=>{let g=l.copyright.replaceAll(` `,""),E=(_0,k1,h2=!0)=>{let R1=document.getElementById(_0);if(k1.length>0)if(R1.parentElement.classList.remove("hidden"),R1.innerHTML="",k1.length>30&&h2){R1.classList.add("marquee");let _5=document.createElement("span");_5.textContent=k1,R1.appendChild(_5)}else R1.textContent=k1;else R1.parentElement.classList.add("hidden")};E("player_info_detail",g),E("player_info_time",h$(this.seq.duration).time),E("player_info_file_name",l.fileName,!1);let x=(_0,k1,h2,R1="")=>this.seq.midiData.RMIDInfo?.[_0]===void 0?k1:R1+h2.decode(this.seq.midiData.RMIDInfo?.[_0]).replace(/\0$/,""),u0=x("IENC","ascii",new TextDecoder),R0=new TextDecoder(u0);E("player_info_album",x("IPRD","",R0)),E("player_info_artist",x("IART","",R0)),E("player_info_genre",x("IGNR","",R0)),E("player_info_creation",x("ICRD","",R0)+x("ICRT","",R0,` -`)),E("player_info_comment",x("ICMT","",R0));let p0=this.mainDiv.getElementsByTagName("svg")[0],D0=this.mainDiv.getElementsByTagName("img")[0],E1=document.getElementById("player_info_background_image");if(!l.isEmbedded){p0.style.display="",D0.style.display="none",E1.style.setProperty("--bg-image","undefined");return}if(l.RMIDInfo.IPIC===void 0){p0.style.display="",D0.style.display="none",E1.style.setProperty("--bg-image","undefined");return}p0.style.display="none",D0.style.display="";let M=new Blob([l.RMIDInfo.IPIC.buffer]),K0=URL.createObjectURL(M);D0.src=K0,E1.style.setProperty("--bg-image",`url('${K0}')`)},"player-js-song-change")}setVisibility(r,l){if(r===this.visible)return;this.visible=r,this.timeoutId&&clearTimeout(this.timeoutId);let g=this.mainDiv;if(r){l.classList.add("out_animation"),this.savedCKWrapperHeight=l.clientHeight;let E=l.clientHeight,x=l.getBoundingClientRect().top;g.style.position="absolute",g.style.top=`${x}px`,g.style.height=`${E}px`,g.style.display="flex",setTimeout(()=>{g.classList.add("player_info_show"),document.body.style.overflow="hidden"},75),this.timeoutId=setTimeout(async()=>{l.style.display="none",g.style.position="",g.style.top="",g.style.height="",document.body.style.overflow=""},Dw*1e3)}else{let E=g.getBoundingClientRect().top;l.style.display="",l.style.position="absolute",l.style.top=`${E}px`,l.style.height=`${this.savedCKWrapperHeight}px`,g.classList.remove("player_info_show"),setTimeout(()=>{l.classList.remove("out_animation"),document.body.style.overflow="hidden"},75),this.timeoutId=setTimeout(()=>{g.style.display="none",l.style.position="",l.style.top="",l.style.height="",document.body.style.overflow=""},Dw*1e3)}}};var bm=class{constructor(r){this.locale=p$[r]||p$[FB],this.fallbackLocale=p$[FB],this.localeCode=r,this._boundObjectProperties=[]}getLocaleString(r,l=[]){let g=this._resolveLocalePath(r);return l.length>0?this._formatLocale(g,l):g}_applyPropertyInternal(r){if(r.isEdited)return;let l=this._resolveLocalePath(r.localePath);r.formattingArguments.length>0&&(l=this._formatLocale(l,r.formattingArguments)),r.object[r.propertyName]=l}_validatePropertyIntegrity(r){let l=this._resolveLocalePath(r.localePath);r.formattingArguments.length>0&&(l=this._formatLocale(l,r.formattingArguments)),r.object[r.propertyName]!==l&&(r.isEdited=!0)}onLocaleChanged=[];_formatLocale(r,l){return r.replace(/{(\d+)}/g,(g,E)=>typeof l[E]<"u"?l[E]:g)}bindObjectProperty(r,l,g,E=[]){let x={object:r,propertyName:l,localePath:g,formattingArguments:E,isEdited:!1};this._applyPropertyInternal(x),this._boundObjectProperties.push(x)}_resolveLocalePath(r,l=!1){if(!r.startsWith("locale."))throw new Error(`Invalid locale path: ${r} (it should start with "locale.")`);let g=r.split("."),E=l?this.fallbackLocale:this.locale;for(let x=1;x{this._validatePropertyIntegrity(E)}),this.locale=g,this._boundObjectProperties.forEach(E=>{this._applyPropertyInternal(E)}),this.onLocaleChanged.forEach(E=>E())}};function LB(o,r=!0,l=0,g={}){let E=o.getChannelData(l),x=o.getChannelData(l+1),u0=E.length,R0=2,p0=new n6(0),D0=Object.keys(g).length>0;if(D0){let J2=new TextEncoder,n3=[So("INFO"),a8("ICMT",J2.encode("Created with SpessaSynth"),!0)];g.artist&&n3.push(a8("IART",J2.encode(g.artist),!0)),g.album&&n3.push(a8("IPRD",J2.encode(g.album),!0)),g.genre&&n3.push(a8("IGNR",J2.encode(g.genre),!0)),g.title&&n3.push(a8("INAM",J2.encode(g.title),!0)),p0=a8("LIST",Ds(n3))}let E1=44,M=u0*2*R0,K0=E1+M+p0.length-8,_0=new Uint8Array(E1);_0.set([82,73,70,70],0),_0.set(new Uint8Array([K0&255,K0>>8&255,K0>>16&255,K0>>24&255]),4),_0.set([87,65,86,69],8),_0.set([102,109,116,32],12),_0.set([16,0,0,0],16),_0.set([1,0],20),_0.set([2,0],22);let k1=o.sampleRate;_0.set(new Uint8Array([k1&255,k1>>8&255,k1>>16&255,k1>>24&255]),24);let h2=k1*2*R0;_0.set(new Uint8Array([h2&255,h2>>8&255,h2>>16&255,h2>>24&255]),28),_0.set([4,0],32),_0.set([16,0],34),_0.set([100,97,116,97],36),_0.set(new Uint8Array([M&255,M>>8&255,M>>16&255,M>>24&255]),40);let R1,_5=E1;D0?R1=new Uint8Array(E1+M+p0.length):R1=new Uint8Array(E1+M),R1.set(_0,0);let v2=32767;if(r){let J2=E.map((n3,U5)=>Math.max(Math.abs(n3),Math.abs(x[U5]))).reduce((n3,U5)=>Math.max(n3,U5));v2=J2>0?32767/J2:1}for(let J2=0;J2>8&255,R1[_5++]=U5&255,R1[_5++]=U5>>8&255}return D0&&R1.set(p0,_5),new Blob([R1.buffer],{type:"audio/wav"})}var _m="synthetizer/worklet_processor.min.js";var bw=1e3;async function _w(o=!0,r=2,l=!1,g={}){if(this.isExporting=!0,!this.seq)throw new Error("No sequencer active");let E=manager.localeManager.getLocaleString("locale.exportAudio.formats.formats.wav.exportMessage.message"),x=manager.localeManager.getLocaleString("locale.exportAudio.formats.formats.wav.exportMessage.estimated"),u0=manager.localeManager.getLocaleString("locale.synthInit.genericLoading"),R0=U7(E,[{type:"text",textContent:u0},{type:"progress"}],9999999,!1),p0=await this.seq.getMIDI(),D0=p0.duration+r,E1=new OfflineAudioContext({numberOfChannels:l?32:2,sampleRate:this.context.sampleRate,length:this.context.sampleRate*D0});await E1.audioWorklet.addModule(new URL("../../spessasynth_lib/"+_m,import.meta.url));let M=await this.synth.getSynthesizerSnapshot(),K0=this.soundFont,_0;try{_0=new sh(E1.destination,K0,!1,{parsedMIDI:p0,snapshot:M,oneOutput:l},{reverbEnabled:!0,chorusEnabled:!0,chorusConfig:void 0,reverbImpulseResponse:this.impulseResponse})}catch(a0){throw U7(this.localeManager.getLocaleString("locale.warnings.warning"),[{type:"text",textContent:this.localeManager.getLocaleString("locale.warnings.outOfMemory")}]),a0}let k1=R0.div.getElementsByTagName("p")[0],h2=R0.div.getElementsByClassName("notification_progress")[0],R1=bw/1e3,_5=_0.currentTime,v2=D0,J2=.1,n3=setInterval(()=>{let a0=_0.currentTime-_5;_5=_0.currentTime;let Y5=_0.currentTime/D0;h2.style.width=`${Y5*100}%`;let s6=a0/R1,c6=(1-Y5)/s6*D0;c6!==1/0&&(v2=J2*c6+(1-J2)*v2,k1.innerText=`${x} ${h$(v2).time}`)},bw),U5=await E1.startRendering();if(h2.style.width="100%",clearInterval(n3),k1.innerText=this.localeManager.getLocaleString("locale.exportAudio.formats.formats.wav.exportMessage.convertWav"),await new Promise(a0=>setTimeout(a0,75)),!l)this.saveBlob(LB(U5,o,0,g),`${this.seqUI.currentSongTitle||"unnamed_song"}.wav`);else{let a0="locale.exportAudio.formats.formats.wav.options.separateChannels.saving.",Y5=[],s6=new Set;for(let O6 of p0.usedChannelsOnTrack)O6.forEach(g6=>s6.add(g6));for(let O6=0;O6<16;O6++){let g6=!0;for(let u4=O6;u4{let Y4=Ke.textContent;Ke.textContent=this.localeManager.getLocaleString("locale.exportAudio.formats.formats.wav.exportMessage.convertWav"),await new Promise(Mo=>setTimeout(Mo,75));let p9=LB(U5,!1,O6*2),_t=`${O6+1} - ${M.channelSnapshots[O6].patchName}.wav`;this.saveBlob(p9,_t),Ke.classList.add("green_button"),Ke.textContent=Y4}})}let c6=U7(this.localeManager.getLocaleString(a0+"title"),Y5,99999999,!0,void 0,{display:"flex",flexWrap:"wrap",flexDirection:"row"});c6.div.style.width="30rem"}$t(R0.id),this.isExporting=!1}async function Rw(){if(this.isExporting)return;let o="locale.exportAudio.formats.formats.wav.options.",r="locale.exportAudio.formats.metadata.",l=(D0,E1,M)=>this.seq.midiData.RMIDInfo?.[D0]===void 0?E1:M.decode(this.seq.midiData.RMIDInfo?.[D0]).replace(/\0$/,""),g=l("IENC","ascii",new TextDecoder),E=new TextDecoder(g),x=l("IPRD","",E),u0=l("IART","",E),R0=l("IGNR","",E),p0=[{type:"toggle",translatePathTitle:o+"normalizeVolume",attributes:{"normalize-volume-toggle":"1",checked:"true"}},{type:"input",translatePathTitle:o+"additionalTime",attributes:{value:"2",type:"number"}},{type:"toggle",translatePathTitle:o+"separateChannels",attributes:{"separate-channels-toggle":"1"}},{type:"input",translatePathTitle:r+"songTitle",attributes:{name:"song_title",type:"text",value:this.seqUI.currentSongTitle}},{type:"input",translatePathTitle:r+"album",attributes:{value:x,name:"album",type:"text"}},{type:"input",translatePathTitle:r+"artist",attributes:{value:u0,name:"artist",type:"text"}},{type:"input",translatePathTitle:r+"genre",attributes:{value:R0,name:"genre",type:"text"}},{type:"button",textContent:this.localeManager.getLocaleString(o+"confirm"),onClick:D0=>{$t(D0.id);let E1=D0.div.querySelector("input[normalize-volume-toggle]").checked,M=D0.div.querySelector("input[type='number']").value,K0=D0.div.querySelector("input[separate-channels-toggle]").checked,_0=D0.div.querySelector("input[name='artist']").value,k1=D0.div.querySelector("input[name='album']").value,h2=D0.div.querySelector("input[name='song_title']").value,R1=D0.div.querySelector("input[name='genre']").value,_5={artist:_0.length>0?_0:void 0,album:k1.length>0?k1:void 0,title:h2.length>0?h2:void 0,genre:R1.length>0?R1:void 0};this._doExportAudioData(E1,parseInt(M),K0,_5)}}];U7(this.localeManager.getLocaleString(o+"title"),p0,9999999,!0,this.localeManager)}async function xw(){let o=await this.seq.getMIDI();ah(o,await this.synth.getSynthesizerSnapshot());let r=um(o),l=new Blob([r],{type:"audio/mid"});this.saveBlob(l,`${this.seqUI.currentSongTitle||"unnamed_song"}.mid`)}function Fw(o,r){ei("%cSearching for all used programs and keys...",D1.info);let l=16+o.midiPortChannelOffsets.reduce((M,K0)=>K0>M?K0:M),g=[];for(let M=0;M{u0[k1]>=_0.length||_0[u0[k1]].ticks0;){let M=p0(),K0=o.tracks[M];if(u0[M]>=K0.length){R0--;continue}let _0=K0[u0[M]];if(u0[M]++,_0.messageStatusByte===J3.midiPort){D0[M]=_0.messageData[0];continue}let k1=_0.messageStatusByte&240;if(k1!==J3.noteOn&&k1!==J3.controllerChange&&k1!==J3.programChange&&k1!==J3.systemExclusive)continue;let h2=(_0.messageStatusByte&15)+o.midiPortChannelOffsets[D0[M]]||0,R1=g[h2];switch(k1){case J3.programChange:R1.program=_0.messageData[0],E(R1);break;case J3.controllerChange:if(_0.messageData[0]!==o6.bankSelect||E1==="gs"&&R1.drums)continue;let _5=_0.messageData[1],v2=Math.max(0,_5-o.bankOffset);if(E1==="xg"){let U5=_5===120||_5===126||_5===127;U5!==R1.drums?(R1.drums=U5,R1.bank=R1.drums?128:v2,E(R1)):R1.bank=R1.drums?128:v2;continue}g[h2].bank=v2;break;case J3.noteOn:if(_0.messageData[1]===0)continue;E(R1),x[R1.string].add(`${_0.messageData[0]}-${_0.messageData[1]}`);break;case J3.systemExclusive:if(_0.messageData[0]!==65||_0.messageData[2]!==66||_0.messageData[3]!==18||_0.messageData[4]!==64||!(_0.messageData[5]&16)||_0.messageData[6]!==21){_0.messageData[0]===67&&_0.messageData[2]===76&&_0.messageData[5]===126&&_0.messageData[6]===0&&(E1="xg");continue}let J2=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][_0.messageData[5]&15]+o.midiPortChannelOffsets[D0[M]],n3=!!(_0.messageData[7]>0&&_0.messageData[5]>>4);R1=g[J2],R1.drums=n3,R1.bank=n3?128:0,E(R1);break}}for(let M of Object.keys(x))x[M].size===0&&(j5(`%cDetected change but no keys for %c${M}`,D1.info,D1.value),delete x[M]);return t4(),x}function Rm(o,r){function l(E,x){let u0=0;for(let R0=0;R0=D0.min&&K0.key<=D0.max&&K0.velocity>=E1.min&&K0.velocity<=E1.max){M=!0;break}M||(j5(`%c${p0.sample.sampleName} %cremoved from %c${E.instrumentName}%c. Use count: %c${p0.useCount-1}`,D1.recognized,D1.info,D1.recognized,D1.info,D1.recognized),E.safeDeleteZone(R0)&&(u0++,R0--,j5(`%c${p0.sample.sampleName} %cdeleted`,D1.recognized,D1.info)),p0.sample.useCount<1&&o.deleteSample(p0.sample))}return u0}or("%cTrimming soundfont...",D1.info);let g=Fw(r,o);ei("%cModifying soundfont...",D1.info),j5("Detected keys for midi:",g);for(let E=0;E{let M=E1.split("-");return{key:parseInt(M[0]),velocity:parseInt(M[1])}});ei(`%cTrimming %c${x.presetName}`,D1.info,D1.recognized),j5(`Keys for ${x.presetName}:`,p0);let D0=0;for(let E1=0;E1=K0.min&&h2.key<=K0.max&&h2.velocity>=_0.min&&h2.velocity<=_0.max){k1=!0;let R1=l(M.instrument,p0);j5(`%cTrimmed off %c${R1}%c zones from %c${M.instrument.instrumentName}`,D1.info,D1.recognized,D1.info,D1.recognized);break}k1||(D0++,x.deleteZone(E1),M.instrument.useCount<1&&o.deleteInstrument(M.instrument),E1--)}j5(`%cTrimmed off %c${D0}%c zones from %c${x.presetName}`,D1.info,D1.recognized,D1.info,D1.recognized),t4()}}o.removeUnusedElements(),o.soundFontInfo.ICMT=`NOTE: This soundfont was trimmed by SpessaSynth to only contain presets used in "${r.midiName}" +`)),E("player_info_comment",x("ICMT","",R0));let p0=this.mainDiv.getElementsByTagName("svg")[0],D0=this.mainDiv.getElementsByTagName("img")[0],E1=document.getElementById("player_info_background_image");if(!l.isEmbedded){p0.style.display="",D0.style.display="none",E1.style.setProperty("--bg-image","undefined");return}if(l.RMIDInfo.IPIC===void 0){p0.style.display="",D0.style.display="none",E1.style.setProperty("--bg-image","undefined");return}p0.style.display="none",D0.style.display="";let M=new Blob([l.RMIDInfo.IPIC.buffer]),K0=URL.createObjectURL(M);D0.src=K0,E1.style.setProperty("--bg-image",`url('${K0}')`)},"player-js-song-change")}setVisibility(r,l){if(r===this.visible)return;this.visible=r,this.timeoutId&&clearTimeout(this.timeoutId);let g=this.mainDiv;if(r){l.classList.add("out_animation"),this.savedCKWrapperHeight=l.clientHeight;let E=l.clientHeight,x=l.getBoundingClientRect().top;g.style.position="absolute",g.style.top=`${x}px`,g.style.height=`${E}px`,g.style.display="flex",setTimeout(()=>{g.classList.add("player_info_show"),document.body.style.overflow="hidden"},75),this.timeoutId=setTimeout(async()=>{l.style.display="none",g.style.position="",g.style.top="",g.style.height="",document.body.style.overflow=""},Dw*1e3)}else{let E=g.getBoundingClientRect().top;l.style.display="",l.style.position="absolute",l.style.top=`${E}px`,l.style.height=`${this.savedCKWrapperHeight}px`,g.classList.remove("player_info_show"),setTimeout(()=>{l.classList.remove("out_animation"),document.body.style.overflow="hidden"},75),this.timeoutId=setTimeout(()=>{g.style.display="none",l.style.position="",l.style.top="",l.style.height="",document.body.style.overflow=""},Dw*1e3)}}};var bm=class{constructor(r){this.locale=p$[r]||p$[FB],this.fallbackLocale=p$[FB],this.localeCode=r,this._boundObjectProperties=[]}getLocaleString(r,l=[]){let g=this._resolveLocalePath(r);return l.length>0?this._formatLocale(g,l):g}_applyPropertyInternal(r){if(r.isEdited)return;let l=this._resolveLocalePath(r.localePath);r.formattingArguments.length>0&&(l=this._formatLocale(l,r.formattingArguments)),r.object[r.propertyName]=l}_validatePropertyIntegrity(r){let l=this._resolveLocalePath(r.localePath);r.formattingArguments.length>0&&(l=this._formatLocale(l,r.formattingArguments)),r.object[r.propertyName]!==l&&(r.isEdited=!0)}onLocaleChanged=[];_formatLocale(r,l){return r.replace(/{(\d+)}/g,(g,E)=>typeof l[E]<"u"?l[E]:g)}bindObjectProperty(r,l,g,E=[]){let x={object:r,propertyName:l,localePath:g,formattingArguments:E,isEdited:!1};this._applyPropertyInternal(x),this._boundObjectProperties.push(x)}_resolveLocalePath(r,l=!1){if(!r.startsWith("locale."))throw new Error(`Invalid locale path: ${r} (it should start with "locale.")`);let g=r.split("."),E=l?this.fallbackLocale:this.locale;for(let x=1;x{this._validatePropertyIntegrity(E)}),this.locale=g,this._boundObjectProperties.forEach(E=>{this._applyPropertyInternal(E)}),this.onLocaleChanged.forEach(E=>E())}};function LB(o,r=!0,l=0,g={}){let E=o.getChannelData(l),x=o.getChannelData(l+1),u0=E.length,R0=2,p0=new n6(0),D0=Object.keys(g).length>0;if(D0){let J2=new TextEncoder,n3=[So("INFO"),a8("ICMT",J2.encode("Created with SpessaSynth"),!0)];g.artist&&n3.push(a8("IART",J2.encode(g.artist),!0)),g.album&&n3.push(a8("IPRD",J2.encode(g.album),!0)),g.genre&&n3.push(a8("IGNR",J2.encode(g.genre),!0)),g.title&&n3.push(a8("INAM",J2.encode(g.title),!0)),p0=a8("LIST",Ds(n3))}let E1=44,M=u0*2*R0,K0=E1+M+p0.length-8,_0=new Uint8Array(E1);_0.set([82,73,70,70],0),_0.set(new Uint8Array([K0&255,K0>>8&255,K0>>16&255,K0>>24&255]),4),_0.set([87,65,86,69],8),_0.set([102,109,116,32],12),_0.set([16,0,0,0],16),_0.set([1,0],20),_0.set([2,0],22);let k1=o.sampleRate;_0.set(new Uint8Array([k1&255,k1>>8&255,k1>>16&255,k1>>24&255]),24);let h2=k1*2*R0;_0.set(new Uint8Array([h2&255,h2>>8&255,h2>>16&255,h2>>24&255]),28),_0.set([4,0],32),_0.set([16,0],34),_0.set([100,97,116,97],36),_0.set(new Uint8Array([M&255,M>>8&255,M>>16&255,M>>24&255]),40);let R1,_5=E1;D0?R1=new Uint8Array(E1+M+p0.length):R1=new Uint8Array(E1+M),R1.set(_0,0);let v2=32767;if(r){let J2=E.map((n3,U5)=>Math.max(Math.abs(n3),Math.abs(x[U5]))).reduce((n3,U5)=>Math.max(n3,U5));v2=J2>0?32767/J2:1}for(let J2=0;J2>8&255,R1[_5++]=U5&255,R1[_5++]=U5>>8&255}return D0&&R1.set(p0,_5),new Blob([R1.buffer],{type:"audio/wav"})}var _m="synthetizer/worklet_processor.min.js";var bw=1e3;async function _w(o=!0,r=2,l=!1,g={}){if(this.isExporting=!0,!this.seq)throw new Error("No sequencer active");let E=manager.localeManager.getLocaleString("locale.exportAudio.formats.formats.wav.exportMessage.message"),x=manager.localeManager.getLocaleString("locale.exportAudio.formats.formats.wav.exportMessage.estimated"),u0=manager.localeManager.getLocaleString("locale.synthInit.genericLoading"),R0=U7(E,[{type:"text",textContent:u0},{type:"progress"}],9999999,!1),p0=await this.seq.getMIDI(),D0=p0.duration+r,E1=new OfflineAudioContext({numberOfChannels:l?32:2,sampleRate:this.context.sampleRate,length:this.context.sampleRate*D0});await E1.audioWorklet.addModule(new URL("../../spessasynth_lib/"+_m,import.meta.url));let M=await this.synth.getSynthesizerSnapshot(),K0=this.soundFont,_0;try{_0=new sh(E1.destination,K0,!1,{parsedMIDI:p0,snapshot:M,oneOutput:l},{reverbEnabled:!0,chorusEnabled:!0,chorusConfig:void 0,reverbImpulseResponse:this.impulseResponse})}catch(a0){throw U7(this.localeManager.getLocaleString("locale.warnings.warning"),[{type:"text",textContent:this.localeManager.getLocaleString("locale.warnings.outOfMemory")}]),a0}let k1=R0.div.getElementsByTagName("p")[0],h2=R0.div.getElementsByClassName("notification_progress")[0],R1=bw/1e3,_5=_0.currentTime,v2=D0,J2=.1,n3=setInterval(()=>{let a0=_0.currentTime-_5;_5=_0.currentTime;let Y5=_0.currentTime/D0;h2.style.width=`${Y5*100}%`;let s6=a0/R1,c6=(1-Y5)/s6*D0;c6!==1/0&&(v2=J2*c6+(1-J2)*v2,k1.innerText=`${x} ${h$(v2).time}`)},bw),U5=await E1.startRendering();if(h2.style.width="100%",clearInterval(n3),k1.innerText=this.localeManager.getLocaleString("locale.exportAudio.formats.formats.wav.exportMessage.convertWav"),await new Promise(a0=>setTimeout(a0,75)),!l)this.saveBlob(LB(U5,o,0,g),`${this.seqUI.currentSongTitle||"unnamed_song"}.wav`);else{let a0="locale.exportAudio.formats.formats.wav.options.separateChannels.saving.",Y5=[],s6=new Set;for(let O6 of p0.usedChannelsOnTrack)O6.forEach(g6=>s6.add(g6));for(let O6=0;O6<16;O6++){let g6=!0;for(let u4=O6;u4{let Y4=Ke.textContent;Ke.textContent=this.localeManager.getLocaleString("locale.exportAudio.formats.formats.wav.exportMessage.convertWav"),await new Promise(Mo=>setTimeout(Mo,75));let p9=LB(U5,!1,O6*2),_t=`${O6+1} - ${M.channelSnapshots[O6].patchName}.wav`;this.saveBlob(p9,_t),Ke.classList.add("green_button"),Ke.textContent=Y4}})}let c6=U7(this.localeManager.getLocaleString(a0+"title"),Y5,99999999,!0,void 0,{display:"flex",flexWrap:"wrap",flexDirection:"row"});c6.div.style.width="30rem"}$t(R0.id),this.isExporting=!1}async function Rw(){if(this.isExporting)return;let o="locale.exportAudio.formats.formats.wav.options.",r="locale.exportAudio.formats.metadata.",l=(D0,E1,M)=>this.seq.midiData.RMIDInfo?.[D0]===void 0?E1:M.decode(this.seq.midiData.RMIDInfo?.[D0]).replace(/\0$/,""),g=l("IENC","ascii",new TextDecoder),E=new TextDecoder(g),x=l("IPRD","",E),u0=l("IART","",E),R0=l("IGNR","",E),p0=[{type:"toggle",translatePathTitle:o+"normalizeVolume",attributes:{"normalize-volume-toggle":"1",checked:"true"}},{type:"input",translatePathTitle:o+"additionalTime",attributes:{value:"2",type:"number"}},{type:"toggle",translatePathTitle:o+"separateChannels",attributes:{"separate-channels-toggle":"1"}},{type:"input",translatePathTitle:r+"songTitle",attributes:{name:"song_title",type:"text",value:this.seqUI.currentSongTitle}},{type:"input",translatePathTitle:r+"album",attributes:{value:x,name:"album",type:"text"}},{type:"input",translatePathTitle:r+"artist",attributes:{value:u0,name:"artist",type:"text"}},{type:"input",translatePathTitle:r+"genre",attributes:{value:R0,name:"genre",type:"text"}},{type:"button",textContent:this.localeManager.getLocaleString(o+"confirm"),onClick:D0=>{$t(D0.id);let E1=D0.div.querySelector("input[normalize-volume-toggle]").checked,M=D0.div.querySelector("input[type='number']").value,K0=D0.div.querySelector("input[separate-channels-toggle]").checked,_0=D0.div.querySelector("input[name='artist']").value,k1=D0.div.querySelector("input[name='album']").value,h2=D0.div.querySelector("input[name='song_title']").value,R1=D0.div.querySelector("input[name='genre']").value,_5={artist:_0.length>0?_0:void 0,album:k1.length>0?k1:void 0,title:h2.length>0?h2:void 0,genre:R1.length>0?R1:void 0};this._doExportAudioData(E1,parseInt(M),K0,_5)}}];U7(this.localeManager.getLocaleString(o+"title"),p0,9999999,!0,this.localeManager)}async function xw(){let o=await this.seq.getMIDI();ah(o,await this.synth.getSynthesizerSnapshot());let r=um(o),l=new Blob([r],{type:"audio/mid"});this.saveBlob(l,`${this.seqUI.currentSongTitle||"unnamed_song"}.mid`)}function Fw(o,r){ei("%cSearching for all used programs and keys...",D1.info);let l=16+o.midiPortChannelOffsets.reduce((M,K0)=>K0>M?K0:M),g=[];for(let M=0;M{u0[k1]>=_0.length||_0[u0[k1]].ticks0;){let M=p0(),K0=o.tracks[M];if(u0[M]>=K0.length){R0--;continue}let _0=K0[u0[M]];if(u0[M]++,_0.messageStatusByte===J3.midiPort){D0[M]=_0.messageData[0];continue}let k1=_0.messageStatusByte&240;if(k1!==J3.noteOn&&k1!==J3.controllerChange&&k1!==J3.programChange&&k1!==J3.systemExclusive)continue;let h2=(_0.messageStatusByte&15)+o.midiPortChannelOffsets[D0[M]]||0,R1=g[h2];switch(k1){case J3.programChange:R1.program=_0.messageData[0],E(R1);break;case J3.controllerChange:if(_0.messageData[0]!==o6.bankSelect||E1==="gs"&&R1.drums)continue;let _5=_0.messageData[1],v2=Math.max(0,_5-o.bankOffset);if(E1==="xg"){let U5=_5===120||_5===126||_5===127;U5!==R1.drums?(R1.drums=U5,R1.bank=R1.drums?128:v2,E(R1)):R1.bank=R1.drums?128:v2;continue}g[h2].bank=v2;break;case J3.noteOn:if(_0.messageData[1]===0)continue;E(R1),x[R1.string].add(`${_0.messageData[0]}-${_0.messageData[1]}`);break;case J3.systemExclusive:if(_0.messageData[0]!==65||_0.messageData[2]!==66||_0.messageData[3]!==18||_0.messageData[4]!==64||!(_0.messageData[5]&16)||_0.messageData[6]!==21){_0.messageData[0]===67&&_0.messageData[2]===76&&_0.messageData[5]===126&&_0.messageData[6]===0&&(E1="xg");continue}let J2=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][_0.messageData[5]&15]+o.midiPortChannelOffsets[D0[M]],n3=!!(_0.messageData[7]>0&&_0.messageData[5]>>4);R1=g[J2],R1.drums=n3,R1.bank=n3?128:0,E(R1);break}}for(let M of Object.keys(x))x[M].size===0&&(j5(`%cDetected change but no keys for %c${M}`,D1.info,D1.value),delete x[M]);return t4(),x}function Rm(o,r){function l(E,x){let u0=0;for(let R0=0;R0=D0.min&&K0.key<=D0.max&&K0.velocity>=E1.min&&K0.velocity<=E1.max){M=!0;break}M||(j5(`%c${p0.sample.sampleName} %cremoved from %c${E.instrumentName}%c. Use count: %c${p0.useCount-1}`,D1.recognized,D1.info,D1.recognized,D1.info,D1.recognized),E.safeDeleteZone(R0)&&(u0++,R0--,j5(`%c${p0.sample.sampleName} %cdeleted`,D1.recognized,D1.info)),p0.sample.useCount<1&&o.deleteSample(p0.sample))}return u0}or("%cTrimming soundfont...",D1.info);let g=Fw(r,o);ei("%cModifying soundfont...",D1.info),j5("Detected keys for midi:",g);for(let E=0;E{let M=E1.split("-");return{key:parseInt(M[0]),velocity:parseInt(M[1])}});ei(`%cTrimming %c${x.presetName}`,D1.info,D1.recognized),j5(`Keys for ${x.presetName}:`,p0);let D0=0;for(let E1=0;E1=K0.min&&h2.key<=K0.max&&h2.velocity>=_0.min&&h2.velocity<=_0.max){k1=!0;let R1=l(M.instrument,p0);j5(`%cTrimmed off %c${R1}%c zones from %c${M.instrument.instrumentName}`,D1.info,D1.recognized,D1.info,D1.recognized);break}k1||(D0++,x.deleteZone(E1),M.instrument.useCount<1&&o.deleteInstrument(M.instrument),E1--)}j5(`%cTrimmed off %c${D0}%c zones from %c${x.presetName}`,D1.info,D1.recognized,D1.info,D1.recognized),t4()}}o.removeUnusedElements(),o.soundFontInfo.ICMT=`NOTE: This soundfont was trimmed by SpessaSynth to only contain presets used in "${r.midiName}" `+o.soundFontInfo.ICMT,j5("%cSoundfont modified!",D1.recognized),t4(),t4()}function Lw(){let o=4;for(let g of this.instruments)o+=g.instrumentZones.reduce((E,x)=>(x.generators=x.generators.filter(u0=>u0.generatorType!==b1.sampleID&&u0.generatorType!==b1.keyRange&&u0.generatorType!==b1.velRange),(x.velRange.max!==127||x.velRange.min!==0)&&x.generators.unshift({generatorType:b1.velRange,generatorValue:x.velRange.max<<8|x.velRange.min}),(x.keyRange.max!==127||x.keyRange.min!==0)&&x.generators.unshift({generatorType:b1.keyRange,generatorValue:x.keyRange.max<<8|x.keyRange.min}),x.isGlobal||x.generators.push({generatorType:b1.sampleID,generatorValue:this.samples.indexOf(x.sample)}),x.generators.length*4+E),0);let r=new n6(o),l=0;for(let g of this.instruments)for(let E of g.instrumentZones){E.generatorZoneStartIndex=l;for(let x of E.generators)B9(r,x.generatorType),B9(r,x.generatorValue),l++}return at(r,0),o8(new ye("igen",r.length,r))}function Mw(o,r,l,g,E){let x=this.samples.map((D0,E1)=>{l&&D0.compressSample(g,E);let M=D0.getRawData();return j5(`%cEncoded sample %c${E1}. ${D0.sampleName}%c of %c${this.samples.length}`,D1.info,D1.recognized,D1.info,D1.recognized),M}),u0=this.samples.reduce((D0,E1,M)=>D0+x[M].length+46,0),R0=new n6(u0);this.samples.forEach((D0,E1)=>{let M=x[E1],K0,_0,k1=M.length;D0.isCompressed?(K0=R0.currentIndex,_0=K0+M.length):(K0=R0.currentIndex/2,_0=K0+M.length/2,k1+=46),o.push(K0),R0.set(M,R0.currentIndex),R0.currentIndex+=k1,r.push(_0)});let p0=o8(new ye("smpl",R0.length,R0),new n6([115,100,116,97]));return o8(new ye("LIST",p0.length,p0))}function Tw(o,r){let g=new n6(46*(this.samples.length+1));return this.samples.forEach((E,x)=>{Ii(g,E.sampleName,20);let u0=o[x];at(g,u0);let R0=r[x];at(g,R0);let p0=E.sampleLoopStartIndex/2+u0,D0=E.sampleLoopEndIndex/2+u0;E.isCompressed&&(p0-=u0,D0-=u0),at(g,p0),at(g,D0),at(g,E.sampleRate),g[g.currentIndex++]=E.samplePitch,g[g.currentIndex++]=E.samplePitchCorrection,B9(g,E.sampleLink),B9(g,E.sampleType)}),Ii(g,"EOS",46),o8(new ye("shdr",g.length,g))}function Gw(){let o=10;for(let g of this.instruments)o+=g.instrumentZones.reduce((E,x)=>x.modulators.length*10+E,0);let r=new n6(o),l=0;for(let g of this.instruments)for(let E of g.instrumentZones){E.modulatorZoneStartIndex=l;for(let x of E.modulators)B9(r,x.modulatorSource),B9(r,x.modulatorDestination),B9(r,x.transformAmount),B9(r,x.modulationSecondarySrc),B9(r,x.transformType),l++}return E$(r,0,10),o8(new ye("imod",r.length,r))}function Nw(){let o=this.instruments.reduce((x,u0)=>u0.instrumentZones.length*4+x,4),r=new n6(o),l=0,g=0,E=0;for(let x of this.instruments){x.instrumentZoneIndex=l;for(let u0 of x.instrumentZones)u0.zoneID=l,B9(r,g),B9(r,E),g+=u0.generators.length,E+=u0.modulators.length,l++}return B9(r,g),B9(r,E),o8(new ye("ibag",r.length,r))}function Uw(){let o=this.instruments.length*22+22,r=new n6(o),l=0,g=0;for(let E of this.instruments)Ii(r,E.instrumentName,20),B9(r,l),l+=E.instrumentZones.length,E.instrumentID=g,g++;return Ii(r,"EOI",20),B9(r,l),o8(new ye("inst",r.length,r))}function Ow(){let o=4;for(let g of this.presets)o+=g.presetZones.reduce((E,x)=>(x.generators=x.generators.filter(u0=>u0.generatorType!==b1.instrument&&u0.generatorType!==b1.keyRange&&u0.generatorType!==b1.velRange),(x.velRange.max!==127||x.velRange.min!==0)&&x.generators.unshift({generatorType:b1.velRange,generatorValue:x.velRange.max<<8|x.velRange.min}),(x.keyRange.max!==127||x.keyRange.min!==0)&&x.generators.unshift({generatorType:b1.keyRange,generatorValue:x.keyRange.max<<8|x.keyRange.min}),x.isGlobal||x.generators.push({generatorType:b1.instrument,generatorValue:this.instruments.indexOf(x.instrument)}),x.generators.length*4+E),0);let r=new n6(o),l=0;for(let g of this.presets)for(let E of g.presetZones){E.generatorZoneStartIndex=l;for(let x of E.generators)B9(r,x.generatorType),B9(r,x.generatorValue);l+=E.generators.length}return B9(r,0),B9(r,0),o8(new ye("pgen",r.length,r))}function Pw(){let o=10;for(let g of this.presets)o+=g.presetZones.reduce((E,x)=>x.modulators.length*10+E,0);let r=new n6(o),l=0;for(let g of this.presets)for(let E of g.presetZones){E.modulatorZoneStartIndex=l;for(let x of E.modulators)B9(r,x.modulatorSource),B9(r,x.modulatorDestination),B9(r,x.transformAmount),B9(r,x.modulationSecondarySrc),B9(r,x.transformType),l++}return E$(r,0,10),o8(new ye("pmod",r.length,r))}function Hw(){let o=this.presets.reduce((x,u0)=>u0.presetZones.length*4+x,4),r=new n6(o),l=0,g=0,E=0;for(let x of this.presets){x.presetZoneStartIndex=l;for(let u0 of x.presetZones)u0.zoneID=l,B9(r,g),B9(r,E),g+=u0.generators.length,E+=u0.modulators.length,l++}return B9(r,g),B9(r,E),o8(new ye("pbag",r.length,r))}function qw(){let o=this.presets.length*38+38,r=new n6(o),l=0;for(let g of this.presets)Ii(r,g.presetName,20),B9(r,g.program),B9(r,g.bank),B9(r,l),at(r,g.library),at(r,g.genre),at(r,g.morphology),l+=g.presetZones.length;return Ii(r,"EOP",20),B9(r,0),B9(r,0),B9(r,l),at(r,0),at(r,0),at(r,0),o8(new ye("phdr",r.length,r))}var UD={compress:!1,compressionQuality:.5,compressionFunction:void 0};function Yw(o=UD){if(o.compress&&typeof o.compressionFunction!="function")throw new TypeError("No compression function supplied but compression enabled.");ei("%cSaving soundfont...",D1.info),j5(`%cCompression: %c${o?.compress||"false"}%c quality: %c${o?.compressionQuality||"none"}`,D1.info,D1.recognized,D1.info,D1.recognized),j5("%cWriting INFO...",D1.info);let r=[];this.soundFontInfo.ISFT="SpessaSynth",o?.compress&&(this.soundFontInfo.ifil="3.0");for(let[n3,U5]of Object.entries(this.soundFontInfo))if(n3==="ifil"||n3==="iver"){let a0=parseInt(U5.split(".")[0]),Y5=parseInt(U5.split(".")[1]),s6=new n6(4);B9(s6,a0),B9(s6,Y5),r.push(o8(new ye(n3,4,s6)))}else{let a0=new n6(U5.length);Ii(a0,U5),r.push(o8(new ye(n3,U5.length,a0)))}let l=Ds([new n6([73,78,70,79]),...r]),g=o8(new ye("LIST",l.length,l));j5("%cWriting SDTA...",D1.info);let E=[],x=[],u0=Mw.call(this,E,x,o?.compress,o?.compressionQuality||.5,o.compressionFunction);j5("%cWriting PDTA...",D1.info),j5("%cWriting SHDR...",D1.info);let R0=Tw.call(this,E,x);j5("%cWriting IGEN...",D1.info);let p0=Lw.call(this);j5("%cWriting IMOD...",D1.info);let D0=Gw.call(this);j5("%cWriting IBAG...",D1.info);let E1=Nw.call(this);j5("%cWriting INST...",D1.info);let M=Uw.call(this),K0=Ow.call(this);j5("%cWriting PMOD...",D1.info);let _0=Pw.call(this);j5("%cWriting PBAG...",D1.info);let k1=Hw.call(this);j5("%cWriting PHDR...",D1.info);let h2=qw.call(this),R1=Ds([new n6([112,100,116,97]),h2,k1,_0,K0,M,E1,D0,p0,R0]),_5=o8(new ye("LIST",R1.length,R1));j5("%cWriting the output file...",D1.info);let v2=Ds([new n6([115,102,98,107]),g,u0,_5]),J2=o8(new ye("RIFF",v2.length,v2));return j5(`%cSaved succesfully! Final file size: %c${J2.length}`,D1.info,D1.recognized),t4(),J2}var Q$=class o{constructor(r=void 0){this.soundFontInfo={},this.presets=[],this.samples=[],this.instruments=[],r?.presets&&(this.presets.push(...r.presets),this.soundFontInfo=r.info)}removeUnusedElements(){this.instruments.forEach(r=>{r.useCount<1&&r.instrumentZones.forEach(l=>{l.isGlobal||l.sample.useCount--})}),this.instruments=this.instruments.filter(r=>r.useCount>0),this.samples=this.samples.filter(r=>r.useCount>0)}deleteInstrument(r){if(r.useCount>0)throw new Error(`Cannot delete an instrument that has ${r.useCount} usages.`);this.instruments.splice(this.instruments.indexOf(r),1),r.deleteInstrument(),this.removeUnusedElements()}deleteSample(r){if(r.useCount>0)throw new Error(`Cannot delete sample that has ${r.useCount} usages.`);this.samples.splice(this.samples.indexOf(r),1),this.removeUnusedElements()}deletePreset(r){r.deletePreset(),this.presets.splice(this.presets.indexOf(r),1),this.removeUnusedElements()}getPresetNoFallback(r,l,g=!1){let E=this.presets.find(x=>x.bank===r&&x.program===l);if(E)return E;if(g!==!1)return r===128?this.presets.find(x=>x.bank===128):this.presets.find(x=>x.program===l)}setSampleIDOffset(r){this.presets.forEach(l=>l.sampleIDOffset=r)}getPreset(r,l){let g=this.presets.find(E=>E.bank===r&&E.program===l);return g||(g=this.presets.find(E=>E.program===l&&E.bank!==128),r===128&&(g=this.presets.find(E=>E.bank===128&&E.program===l),g||(g=this.presets.find(E=>E.bank===128))),g&&fe(`%cPreset ${r}.${l} not found. Replaced with %c${g.presetName} (${g.bank}.${g.program})`,D1.warn,D1.recognized)),g||(fe(`Preset ${l} not found. Defaulting to`,this.presets[0].presetName),g=this.presets[0]),g}getPresetByName(r){let l=this.presets.find(g=>g.presetName===r);return l||(fe("Preset not found. Defaulting to:",this.presets[0].presetName),l=this.presets[0]),l}static mergeSoundfonts(...r){let l=r.shift(),g=l.presets;for(;r.length;)r.shift().presets.forEach(x=>{g.find(u0=>u0.bank===x.bank&&u0.program===x.program)===void 0&&g.push(x)});return new o({presets:g,info:l.soundFontInfo})}};Q$.prototype.write=Yw;function Jw(o){ei("%cLoading instruments...",D1.info);for(let r=0;rr.deleteZone()),this.presetZones.length=0}deleteZone(r){this.presetZones[r].deleteZone(),this.presetZones.splice(r,1)}preload(r,l){for(let g=r;g{x.sample.isSampleLoaded||x.sample.getAudioData()})}preloadSpecific(r,l){this.getSamplesAndGenerators(r,l).forEach(g=>{g.sample.isSampleLoaded||g.sample.getAudioData()})}getSamplesAndGenerators(r,l){let g=this.foundSamplesAndGenerators[r][l];if(g)return g;if(this.presetZones.length<1)return[];function E(K0,_0,k1){return k1>=K0&&k1<=_0}function x(K0,_0){return K0.modulatorSource===_0.modulatorSource&&K0.modulatorDestination===_0.modulatorDestination&&K0.modulationSecondarySrc===_0.modulationSecondarySrc&&K0.transformType===_0.transformType}function u0(K0,_0){K0.push(..._0.filter(k1=>!K0.find(h2=>h2.generatorType===k1.generatorType)))}function R0(K0,_0){K0.push(..._0.filter(k1=>!K0.find(h2=>x(k1,h2))))}let p0=[],D0=this.presetZones[0].isGlobal?[...this.presetZones[0].generators]:[],E1=this.presetZones[0].isGlobal?[...this.presetZones[0].modulators]:[];return this.presetZones.filter(K0=>E(K0.keyRange.min,K0.keyRange.max,r)&&E(K0.velRange.min,K0.velRange.max,l)&&!K0.isGlobal).forEach(K0=>{if(K0.instrument.instrumentZones.length<1)return;let _0=K0.generators,k1=K0.modulators,h2=K0.instrument.instrumentZones[0].isGlobal?[...K0.instrument.instrumentZones[0].generators]:[],R1=K0.instrument.instrumentZones[0].isGlobal?[...K0.instrument.instrumentZones[0].modulators]:[];K0.instrument.instrumentZones.filter(v2=>E(v2.keyRange.min,v2.keyRange.max,r)&&E(v2.velRange.min,v2.velRange.max,l)&&!v2.isGlobal).forEach(v2=>{let J2=[...v2.generators],n3=[...v2.modulators];u0(_0,D0),u0(J2,h2),R0(k1,E1),R0(n3,R1),R0(n3,oy);let U5=[...n3];for(let a0=0;a0x(Y5,c6));s6!==-1?U5[s6]=U5[s6].sumTransform(Y5):U5.push(Y5)}p0.push({instrumentGenerators:J2,presetGenerators:_0,modulators:U5,sample:v2.sample,sampleID:v2.generators.find(a0=>a0.generatorType===b1.sampleID).generatorValue})})}),this.foundSamplesAndGenerators[r][l]=p0,p0}};var QC=class{velRange={min:0,max:127};keyRange={min:0,max:127};isGlobal=!1;generators=[];modulators=[]};var Fo=class extends QC{sample=void 0;useCount=0;deleteZone(){this.useCount--,!this.isGlobal&&this.sample.useCount--}},gh=class extends QC{instrument=void 0;deleteZone(){this.isGlobal||this.instrument.removeUseCount()}};var hh=class{constructor(){this.instrumentName="",this.instrumentZones=[],this._useCount=0}addUseCount(){this._useCount++,this.instrumentZones.forEach(r=>r.useCount++)}removeUseCount(){this._useCount--;for(let r=0;rr.deleteZone()),this.instrumentZones.length=0}safeDeleteZone(r){return this.instrumentZones[r].useCount--,this.instrumentZones[r].useCount<1?(this.deleteZone(r),!0):!1}deleteZone(r){this.instrumentZones[r].deleteZone(),this.instrumentZones.splice(r,1)}};var xm=class extends ch{constructor(r,l){super(),this.program=l&127,this.bank=r>>8&127,r>>31&&(this.bank=128),this.DLSInstrument=new hh,this.DLSInstrument.addUseCount();let E=new gh;E.instrument=this.DLSInstrument,this.presetZones=[E]}};function Kw(o){this.verifyHeader(o,"LIST"),this.verifyText(ue(o.chunkData,4),"ins ");let r=[];for(;o.chunkData.length>o.chunkData.currentIndex;)r.push(f4(o.chunkData));let l=r.find(_0=>_0.header==="insh");if(!l)throw t4(),new Error("No instrument header!");let g=r3(l.chunkData,4),E=r3(l.chunkData,4),x=r3(l.chunkData,4),u0=new xm(E,x),R0="unnamedPreset",p0=Si(r,"INFO");if(p0){let _0=f4(p0.chunkData);for(;_0.header!=="INAM";)_0=f4(p0.chunkData);R0=ue(_0.chunkData,_0.chunkData.length).trim()}u0.presetName=R0,u0.DLSInstrument.instrumentName=R0,or(`%cParsing %c"${R0}"%c...`,D1.info,D1.recognized,D1.info);let D0=Si(r,"lrgn");if(!D0)throw t4(),new Error("No region list!");let E1=new Fo;E1.isGlobal=!0;let M=Si(r,"lart"),K0=Si(r,"lar2");this.readLart(M,K0,E1),u0.DLSInstrument.instrumentZones.push(E1);for(let _0=0;_0>10&15;_5===Qn.linear&&R1!==Qn.linear&&(_5=R1);let v2=g>>14&1,J2=g>>15&1;u0===b1.initialAttenuation&&(J2=!J2),M=pn(_5,v2,J2,R0.isCC,R0.enum)}let K0=g>>4&15,_0=g>>8&1,k1=g>>9&1,h2=pn(K0,_0,k1,E1.isCC,E1.enum);if(p0){let R1=h2;h2=M,M=R1}return new o7({srcEnum:M,secSrcEnum:h2,dest:u0,transform:0,amt:E})}function MB(o,r){let l=o.chunkData,g=[],E=[];r3(l,4);let x=r3(l,4);for(let u0=0;u0>16;if(R0===0&&p0===0&&E1===0){let _0;switch(D0){case C6.pan:_0=new n9(b1.pan,K0);break;case C6.gain:_0=new n9(b1.initialAttenuation,-K0*10/.4);break;case C6.filterCutoff:_0=new n9(b1.initialFilterFc,K0);break;case C6.filterQ:_0=new n9(b1.initialFilterQ,K0);break;case C6.modLfoFreq:_0=new n9(b1.freqModLFO,K0);break;case C6.modLfoDelay:_0=new n9(b1.delayModLFO,K0);break;case C6.vibLfoFreq:_0=new n9(b1.freqVibLFO,K0);break;case C6.vibLfoDelay:_0=new n9(b1.delayVibLFO,K0);break;case C6.volEnvDelay:_0=new n9(b1.delayVolEnv,K0);break;case C6.volEnvAttack:_0=new n9(b1.attackVolEnv,K0);break;case C6.volEnvHold:_0=new n9(b1.holdVolEnv,K0);break;case C6.volEnvDecay:_0=new n9(b1.decayVolEnv,K0);break;case C6.volEnvRelease:_0=new n9(b1.releaseVolEnv,K0);break;case C6.volEnvSustain:let k1=(1e3-K0)/10;_0=new n9(b1.sustainVolEnv,k1*10);break;case C6.modEnvDelay:_0=new n9(b1.delayModEnv,K0);break;case C6.modEnvAttack:_0=new n9(b1.attackModEnv,K0);break;case C6.modEnvHold:_0=new n9(b1.holdModEnv,K0);break;case C6.modEnvDecay:_0=new n9(b1.decayModEnv,K0);break;case C6.modEnvRelease:_0=new n9(b1.releaseModEnv,K0);break;case C6.modEnvSustain:let h2=1e3-K0;_0=new n9(b1.sustainModEnv,h2);break;case C6.reverbSend:_0=new n9(b1.reverbEffectsSend,K0);break;case C6.chorusSend:_0=new n9(b1.chorusEffectsSend,K0);break;case C6.pitch:let R1=Math.floor(K0/100),_5=Math.floor(K0-R1*100);_0=new n9(b1.fineTune,_5),g.push(new n9(b1.coarseTune,R1));break}_0&&g.push(_0)}else{let _0=!0;if(p0===y4.none)if(R0===y4.modLfo&&D0===C6.pitch)g.push(new n9(b1.modLfoToPitch,K0));else if(R0===y4.modLfo&&D0===C6.gain)g.push(new n9(b1.modLfoToVolume,K0));else if(R0===y4.modLfo&&D0===C6.filterCutoff)g.push(new n9(b1.modLfoToFilterFc,K0));else if(R0===y4.vibratoLfo&&D0===C6.pitch)g.push(new n9(b1.vibLfoToPitch,K0));else if(R0===y4.modEnv&&D0===C6.pitch)g.push(new n9(b1.modEnvToPitch,K0));else if(R0===y4.modEnv&&D0===C6.filterCutoff)g.push(new n9(b1.modEnvToFilterFc,K0));else if(R0===y4.keyNum&&D0===C6.volEnvHold){g.push(new n9(b1.keyNumToVolEnvHold,K0/-128));let k1=Math.round(60/128*K0);g.forEach(h2=>{h2.generatorType===b1.holdVolEnv&&(h2.generatorValue+=k1)})}else if(R0===y4.keyNum&&D0===C6.volEnvDecay){g.push(new n9(b1.keyNumToVolEnvDecay,K0/-128));let k1=Math.round(60/128*K0);g.forEach(h2=>{h2.generatorType===b1.decayVolEnv&&(h2.generatorValue+=k1)})}else if(R0===y4.keyNum&&D0===C6.modEnvHold){g.push(new n9(b1.keyNumToModEnvHold,K0/-128));let k1=Math.round(60/128*K0);g.forEach(h2=>{h2.generatorType===b1.holdModEnv&&(h2.generatorValue+=k1)})}else if(R0===y4.keyNum&&D0===C6.modEnvDecay){g.push(new n9(b1.keyNumToModEnvDecay,K0/-128));let k1=Math.round(60/128*K0);g.forEach(h2=>{h2.generatorType===b1.decayModEnv&&(h2.generatorValue+=k1)})}else _0=!1;else _0=!1;if(_0===!1){let k1=zw(R0,p0,D0,E1,K0);k1?(E.push(k1),j5("%cSucceeded converting to SF2 Modulator!",D1.recognized)):fe("Failed converting to SF2 Modulator!")}}}return E.find(u0=>u0.modulatorDestination===b1.reverbEffectsSend)===void 0&&E.push(new o7({srcEnum:219,dest:b1.reverbEffectsSend,amt:1e3,secSrcEnum:0,transform:0})),E.find(u0=>u0.modulatorDestination===b1.chorusEffectsSend)===void 0&&E.push(new o7({srcEnum:221,dest:b1.chorusEffectsSend,amt:1e3,secSrcEnum:0,transform:0})),r&&E.push(new o7({srcEnum:129,dest:b1.vibLfoToPitch,amt:0,secSrcEnum:0,transform:0}),new o7({srcEnum:13,dest:b1.vibLfoToPitch,amt:0,secSrcEnum:0,transform:0})),{modulators:E,generators:g}}function Zw(o,r,l){if(o)for(;o.chunkData.currentIndexo.chunkData.currentIndex;)r.push(f4(o.chunkData));let l=r.find(a0=>a0.header==="rgnh"),g=r3(l.chunkData,2),E=r3(l.chunkData,2),x=r3(l.chunkData,2),u0=r3(l.chunkData,2),R0=new Fm({min:g,max:E},{min:x,max:u0});r3(l.chunkData,2);let p0=r3(l.chunkData,2);p0!==0&&R0.generators.push(new n9(b1.exclusiveClass,p0));let D0=Si(r,"lart"),E1=Si(r,"lar2");this.readLart(D0,E1,R0),R0.isGlobal=!1;let M=r.find(a0=>a0.header==="wsmp");r3(M.chunkData,4);let K0=r3(M.chunkData,2);r3(M.chunkData,2);let h2=(r3(M.chunkData,4)|0)/-655360*10/.4;r3(M.chunkData,4);let R1=r3(M.chunkData,4),_5,v2={start:0,end:0};if(R1===0)_5=0;else{r3(M.chunkData,4),r3(M.chunkData,4)===0?_5=1:_5=3,v2.start=r3(M.chunkData,4);let Y5=r3(M.chunkData,4);v2.end=v2.start+Y5}let J2=r.find(a0=>a0.header==="wlnk");if(J2===void 0)return;r3(J2.chunkData,2),r3(J2.chunkData,2),r3(J2.chunkData,4);let n3=r3(J2.chunkData,4),U5=this.samples[n3];if(U5===void 0)throw new Error("Invalid sample ID!");return R0.setWavesample(h2,_5,v2,K0,U5,n3),R0}var fh=class{constructor(r,l,g,E,x,u0,R0,p0){this.sampleName=r,this.sampleRate=l,this.samplePitch=g,this.samplePitchCorrection=E,this.sampleLink=x,this.sampleType=u0,this.sampleLoopStartIndex=R0,this.sampleLoopEndIndex=p0,this.isCompressed=(u0&16)>0,this.compressedData=void 0,this.useCount=0}getRawData(){let r=new Error("Not implemented");throw r.name="NotImplementedError",r}compressSample(r,l){if(!this.isCompressed)try{this.compressedData=l([this.getAudioData()],1,this.sampleRate,r),this.sampleType|=16,this.isCompressed=!0}catch{fe(`Failed to compress ${this.sampleName}. Leaving as uncompressed!`),this.isCompressed=!1,this.compressedData=void 0,this.sampleType&=-17}}getAudioData(){let r=new Error("Not implemented");throw r.name="NotImplementedError",r}};var Lm=class extends fh{constructor(r,l,g,E,x,u0,R0){super(r,l,g,E,0,1,x*2,(u0-1)*2),this.sampleData=R0}getAudioData(){return this.sampleData}sampleData;getRawData(){if(this.isCompressed){if(!this.compressedData)throw new Error("Compressed but no data??");return this.compressedData}let r=new Uint8Array(this.sampleData.length*2);for(let l=0;l>8&255}return r}};function jw(o){ei("%cLoading Wave samples...",D1.recognized);let r=0;for(;o.chunkData.currentIndexs6.header==="fmt ");if(!E)throw new Error("No fmt chunk in the wave file!");if(r3(E.chunkData,2)!==1)throw new Error("Only PCM format in WAVE is supported.");if(r3(E.chunkData,2)!==1)throw new Error("Only mono samples are supported.");let R0=r3(E.chunkData,4);r3(E.chunkData,4),r3(E.chunkData,2);let p0=r3(E.chunkData,2),D0=p0/8,E1=Math.pow(2,D0*8-1),M=Math.pow(2,D0*8),K0,_0=!1;p0===8?(K0=255,_0=!0):K0=E1;let k1=g.find(s6=>s6.header==="data");if(!k1)throw new Error("No data chunk in the wave chunk!");let h2=k1.size/D0,R1=new Float32Array(h2);for(let s6=0;s6=E1&&(c6-=M),R1[s6]=c6/K0)}let _5=60,v2=0,J2=0,n3=R1.length-1,U5=g.find(s6=>s6.header==="wsmp");if(U5){if(r3(U5.chunkData,4),_5=r3(U5.chunkData,2),v2=oh(U5.chunkData[U5.chunkData.currentIndex++],U5.chunkData[U5.chunkData.currentIndex++]),r3(U5.chunkData,4),r3(U5.chunkData,4),r3(U5.chunkData,4)===1){r3(U5.chunkData,8),J2=r3(U5.chunkData,4);let c6=r3(U5.chunkData,4);n3=J2+c6}}else fe("No wsmp chunk in wave... using sane defaults.");let a0=Si(g,"INFO"),Y5=`Unnamed ${r}`;if(a0){let s6=f4(a0.chunkData);for(;s6.header!=="INAM"&&a0.chunkData.currentIndex