Merge pull request #5 from ahigerd/master
Merge pull request #5 from ahigerd/master

Update for modern compilers, update 2sf core, add MSVC cross-compile support

file:b/.gitmodules (new)
--- /dev/null
+++ b/.gitmodules
@@ -1,1 +1,4 @@
+[submodule "src/in_xsf_framework/zlib"]
+	path = src/in_xsf_framework/zlib
+	url = https://github.com/madler/zlib
 

--- a/src/.gitignore
+++ b/src/.gitignore
@@ -4,3 +4,11 @@
 *.release
 *.aps
 .vs
+*.obj
+*.o
+*.dll
+*.exp
+*.lib
+*.d
+*.swp
+

--- /dev/null
+++ b/src/GNUmakefile.msvc
@@ -1,1 +1,26 @@
+all: in_xsf_framework.lib in_2sf.dll in_gsf.dll in_ncsf.dll in_snsf.dll
 
+in_xsf_framework.lib:
+	$(MAKE) -C in_xsf_framework
+
+in_2sf.dll: in_xsf_framework.lib
+	$(MAKE) -C in_2sf
+
+in_gsf.dll: in_xsf_framework.lib
+	$(MAKE) -C in_gsf
+
+in_ncsf.dll: in_xsf_framework.lib
+	$(MAKE) -C in_ncsf
+
+in_snsf.dll: in_xsf_framework.lib
+	$(MAKE) -C in_snsf
+
+clean:
+	$(MAKE) -C in_xsf_framework clean
+	$(MAKE) -C in_2sf clean
+	$(MAKE) -C in_gsf clean
+	$(MAKE) -C in_ncsf clean
+	$(MAKE) -C in_snsf clean
+
+.PHONY: in_xsf_framework.lib in_2sf.dll in_gsf.dll in_ncsf.dll in_snsf.dll clean
+

--- a/src/Makefile
+++ b/src/Makefile
@@ -2,14 +2,18 @@
 
 SRCDIR:=	$(dir $(abspath $(lastword $(MAKEFILE_LIST))))
 
+ZLIB_SRCS:= $(sort $(wildcard $(SRCDIR)in_xsf_framework/zlib/*.c))
+ZLIB_OBJS:=	$(subst $(SRCDIR),,$(ZLIB_SRCS:%.c=%.o))
 FRAMEWORK_SRCS:=	$(sort $(wildcard $(SRCDIR)in_xsf_framework/*.cpp))
 FRAMEWORK_OBJS:=	$(subst $(SRCDIR),,$(FRAMEWORK_SRCS:%.cpp=%.o))
 
-in_2sf_SRCS:=	$(wildcard $(SRCDIR)in_2sf/*.cpp) $(wildcard $(SRCDIR)in_2sf/desmume/*.cpp) $(wildcard $(SRCDIR)in_2sf/desmume/addons/*.cpp) \
-	$(wildcard $(SRCDIR)in_2sf/desmume/metaspu/*.cpp) $(wildcard $(SRCDIR)in_2sf/desmume/metaspu/SoundTouch/*.cpp) \
-	$(wildcard $(SRCDIR)in_2sf/desmume/utils/*.cpp) $(wildcard $(SRCDIR)in_2sf/desmume/utils/AsmJit/*.cpp) \
-	$(wildcard $(SRCDIR)in_2sf/desmume/utils/AsmJit/base/*.cpp) $(wildcard $(SRCDIR)in_2sf/desmume/utils/AsmJit/x86/*.cpp)
-in_2sf_SRCS:=	$(filter-out $(SRCDIR)in_2sf/desmume/debug.cpp $(SRCDIR)in_2sf/desmume/metaspu/SoundTouch/cpu_detect_x86_win.cpp,$(in_2sf_SRCS))
+in_2sf_SRCS:=	$(wildcard $(SRCDIR)in_2sf/*.cpp \
+	$(SRCDIR)in_2sf/desmume/*.cpp \
+	$(SRCDIR)in_2sf/desmume/*/*.cpp \
+	$(SRCDIR)in_2sf/desmume/*/*/*.cpp \
+	$(SRCDIR)in_2sf/desmume/*/*/*/*.cpp \
+	$(SRCDIR)in_2sf/desmume/*/*/*/*/*.cpp \
+	$(SRCDIR)in_2sf/spu/*.cpp)
 in_gsf_SRCS:=	$(wildcard $(SRCDIR)in_gsf/*.cpp) $(wildcard $(SRCDIR)in_gsf/vbam/apu/*.cpp) $(wildcard $(SRCDIR)in_gsf/vbam/gba/*.cpp)
 in_ncsf_SRCS:=	$(wildcard $(SRCDIR)in_ncsf/*.cpp) $(wildcard $(SRCDIR)in_ncsf/SSEQPlayer/*.cpp)
 in_snsf_SRCS:=	$(wildcard $(SRCDIR)in_snsf/*.cpp) $(wildcard $(SRCDIR)in_snsf/snes9x/*.cpp) $(wildcard $(SRCDIR)in_snsf/snes9x/apu/*.cpp)
@@ -19,12 +23,13 @@
 
 COMPILER:=	$(shell $(CXX) -v 2>/dev/stdout)
 
-MY_CPPFLAGS=	$(CPPFLAGS) -std=gnu++11 -I$(SRCDIR)in_xsf_framework -I/g/Code/Winamp\ SDK -DWINAMP_PLUGIN -DUNICODE_INPUT_PLUGIN
-MY_CXXFLAGS=	$(CXXFLAGS) -std=gnu++11 -pipe -Wall -Wctor-dtor-privacy -Wold-style-cast -Wextra -Wno-div-by-zero -Wfloat-equal -Wshadow -Winit-self -Wcast-qual -Wunreachable-code -Wabi -Woverloaded-virtual -Wno-long-long -Wno-switch -I$(SRCDIR)in_xsf_framework -I/g/Code/Winamp\ SDK -DWINAMP_PLUGIN -DUNICODE_INPUT_PLUGIN
+MY_CPPFLAGS=	$(CPPFLAGS) -std=gnu++17 -DWINAMP_PLUGIN -DUNICODE_INPUT_PLUGIN -D_WINDOWS -I$(SRCDIR)in_xsf_framework -I$(SRCDIR)in_xsf_framework/winamp -I$(SRCDIR)in_xsf_framework/zlib -I$(SRCDIR)in_2sf/desmume
+MY_CXXFLAGS=	$(CXXFLAGS) -std=gnu++17 -DWINAMP_PLUGIN -DUNICODE_INPUT_PLUGIN -D_WINDOWS -I$(SRCDIR)in_xsf_framework -I$(SRCDIR)in_xsf_framework/winamp -I$(SRCDIR)in_xsf_framework/zlib -pipe -Wall -Wctor-dtor-privacy -Wold-style-cast -Wextra -Wno-div-by-zero -Wfloat-equal -Wshadow -Winit-self -Wcast-qual -Wunreachable-code -Woverloaded-virtual -Wno-long-long -Wno-switch
+MY_CFLAGS=	$(CFLAGS) -std=gnu17 -DWINAMP_PLUGIN -DUNICODE_INPUT_PLUGIN -D_WINDOWS -I$(SRCDIR)in_xsf_framework -I$(SRCDIR)in_xsf_framework/winamp -I$(SRCDIR)in_xsf_framework/zlib -pipe -Wall -Wextra -Wno-div-by-zero -Wfloat-equal -Wshadow -Winit-self -Wcast-qual -Wunreachable-code -Wno-long-long -Wno-switch
 ifeq (,$(findstring clang,$(COMPILER)))
 MY_CXXFLAGS+=	-Wlogical-op
 endif
-MY_LDFLAGS=	$(LDFLAGS) -lz
+MY_LDFLAGS=	$(LDFLAGS)
 
 DLL_SRCS_template=	$(1)_SRCS:=	$$(sort $$($(1)_SRCS))
 DLL_OBJS_template=	$(1)_OBJS:=	$$(subst $(SRCDIR),,$$($(1)_SRCS:%.cpp=%.o))
@@ -32,8 +37,8 @@
 $(foreach dll,$(DLLS),$(eval $(call DLL_SRCS_template,$(basename $(notdir $(dll))))))
 $(foreach dll,$(DLLS),$(eval $(call DLL_OBJS_template,$(basename $(notdir $(dll))))))
 
-SRCS:=	$(sort $(FRAMEWORK_SRCS) $(foreach dll,$(DLLS),$($(basename $(notdir $(dll)))_SRCS)))
-OBJS:=	$(sort $(FRAMEWORK_OBJS) $(foreach dll,$(DLLS),$($(basename $(notdir $(dll)))_OBJS)))
+SRCS:=	$(sort $(FRAMEWORK_SRCS) $(ZLIB_SRCS) $(foreach dll,$(DLLS),$($(basename $(notdir $(dll)))_SRCS)))
+OBJS:=	$(sort $(FRAMEWORK_OBJS) $(ZLIB_OBJS) $(foreach dll,$(DLLS),$($(basename $(notdir $(dll)))_OBJS)))
 DEPS:=	$(OBJS:%.o=%.d)
 
 .PHONY: all debug clean
@@ -46,17 +51,27 @@
 debug: all
 
 define DLL_template
-$(1): $$(FRAMEWORK_OBJS) $$($$(basename $$(notdir $(1)))_OBJS)
+$(1): $$(FRAMEWORK_OBJS) $$(ZLIB_OBJS) $$($$(basename $$(notdir $(1)))_OBJS)
 	@echo "Linking $$@..."
-	@$$(CXX) -shared -fPIC $$(MY_CXXFLAGS) -o $$@ $$^ $$(MY_LDFLAGS)
+	$$(CXX) -shared -fPIC $$(MY_CXXFLAGS) -o $$@ $$^ $$(MY_LDFLAGS)
 endef
 define SRC_template
+ifeq ($(findstring .cpp,$(1)),.cpp)
 $$(subst $(SRCDIR),,$(1:%.cpp=%.o)): $(1)
 	@echo "Compiling $$<..."
 	@$$(CXX) $$(MY_CXXFLAGS) -o $$(subst $(SRCDIR),,$$@) -c $$<
+else
+$$(subst $(SRCDIR),,$(1:%.c=%.o)): $(1)
+	@echo "Compiling $$<..."
+	@$$(CC) $$(MY_CFLAGS) -o $$(subst $(SRCDIR),,$$@) -c $$<
+endif
 endef
 define DEP_template
+ifeq ($(findstring .cpp,$(1)),.cpp)
 $$(subst $(SRCDIR),,$(1:%.cpp=%.d)): $(1)
+else
+$$(subst $(SRCDIR),,$(1:%.c=%.d)): $(1)
+endif
 	@echo "Calculating depends for $$<..."
 	-@mkdir -p $$(@D)
 	@$$(CXX) $$(MY_CPPFLAGS) -MM -MF $$(subst $(SRCDIR),,$$@).tmp $$<
@@ -69,20 +84,15 @@
 $(foreach src,$(SRCS),$(eval $(call DEP_template,$(src))))
 
 $(subst $(SRCDIR),,$(in_2sf_SRCS:%.cpp=%.d)): MY_CPPFLAGS+=	-msse
-$(in_2sf_OBJS): MY_CXXFLAGS+=	-msse -DHAVE_LIBZ
+$(in_2sf_OBJS): MY_CXXFLAGS+=	-msse -DHAVE_LIBZ -I$(SRCDIR)/in_2sf/desmume
 
-in_2sf/desmume/MMU.o: MY_CXXFLAGS+=	-Wno-shadow
-in_2sf/desmume/utils/AsmJit/base/codegen.o: MY_CXXFLAGS+=	-Wno-unused-value
-in_2sf/desmume/utils/AsmJit/base/runtime.o: MY_CXXFLAGS+=	-Wno-unused-parameter
-in_2sf/desmume/utils/AsmJit/base/vmem.o: MY_CXXFLAGS+=	-Wno-missing-field-initializers -Wno-unused-function
+in_xsf_framework/zlib/%.o: MY_CFLAGS+= -Wno-implicit-fallthrough -Wno-cast-qual
+in_2sf/desmume/%.o: MY_CXXFLAGS+=	-Wno-shadow -Wno-unused-parameter -Wno-unused-value -Wno-unused-variable -Wno-missing-field-initializers -Wno-unused-function -Wno-implicit-fallthrough -Wno-old-style-cast -Wno-deprecated-copy -Wno-class-memaccess -Wno-sign-compare -Wno-float-equal -Wno-unused-but-set-variable
 ifneq (,$(findstring clang,$(COMPILER)))
-in_2sf/desmume/utils/AsmJit/base/vmem.o: MY_CXXFLAGS+=	-Wno-missing-braces
+in_2sf/desmume/%.o: MY_CXXFLAGS+=	-Wno-missing-braces
 endif
-in_2sf/desmume/utils/AsmJit/x86/x86assembler.o: MY_CXXFLAGS+=	-Wno-unused-variable
-ifneq (,$(findstring clang,$(COMPILER)))
-in_2sf/desmume/utils/AsmJit/x86/x86assembler.o: MY_CXXFLAGS+=	-Wno-missing-braces
-endif
-in_2sf/desmume/utils/AsmJit/x86/x86context.o: MY_CXXFLAGS+=	-Wno-unused-parameter -Wno-unused-value -Wno-unused-variable
+in_snsf/snes9x/%.o: MY_CXXFLAGS+= -Wno-implicit-fallthrough -Wno-shift-negative-value
+in_gsf/vbam/apu/Gb_Apu: MY_CXXFLAGS+=	-Wno-implicit-fallthrough
 in_gsf/vbam/gba/GBA-arm.o: MY_CXXFLAGS+=	-Wno-unused-variable
 ifeq (,$(findstring clang,$(COMPILER)))
 in_gsf/vbam/gba/GBA-arm.o: MY_CXXFLAGS+=	-Wno-unused-but-set-variable
@@ -90,7 +100,7 @@
 
 clean:
 	@echo "Cleaning OBJs and DLLs..."
-	-@rm $(OBJS) $(DLLS)
+	-@rm -f $(OBJS) $(DLLS) $(DEPS)
 
 -include $(DEPS)
 

--- /dev/null
+++ b/src/in_2sf/GNUmakefile
@@ -1,1 +1,11 @@
+../in_2sf.dll: $(patsubst %.cpp, %.obj, $(wildcard desmume/*.cpp desmume/*/*.cpp spu/*.cpp *.cpp)) ../in_xsf_framework.lib
+	$(WINE) link.exe /nologo /dll /machine:x86 user32.lib libucrt.lib libvcruntime.lib libcmt.lib libcpmt.lib /out:$@ $^
 
+%.obj: %.cpp $(wildcard desmume/*.h ../in_xsf_framework/*.h) GNUmakefile
+	$(WINE) cl.exe /nologo /std:c++latest /MT /DUNICODE /D_UNICODE /DNDEBUG /O2 /EHsc /I ../in_xsf_framework /I ../in_xsf_framework/zlib /I spu /I desmume /c /Fo$@ $<
+
+clean:
+	rm -f ../in_2sf.dll ../in_2sf.exp ../in_2sf.lib *.obj desmume/*.obj desmume/*/*.obj
+
+.PHONY: clean
+

--- a/src/in_2sf/XSFConfig_2SF.cpp
+++ b/src/in_2sf/XSFConfig_2SF.cpp
@@ -41,7 +41,7 @@
 	void About(HWND parent);
 };
 
-unsigned XSFConfig::initSampleRate = 44100;
+unsigned XSFConfig::initSampleRate = DESMUME_SAMPLE_RATE;
 std::string XSFConfig::commonName = "2SF Decoder";
 std::string XSFConfig::versionNumber = "0.9b";
 unsigned XSFConfig_2SF::initInterpolation = 2;
@@ -54,7 +54,7 @@
 
 XSFConfig_2SF::XSFConfig_2SF() : XSFConfig(), interpolation(0), mutes()
 {
-	this->supportedSampleRates.push_back(44100);
+	this->supportedSampleRates.push_back(DESMUME_SAMPLE_RATE);
 }
 
 void XSFConfig_2SF::LoadSpecificConfig()
@@ -89,6 +89,7 @@
 			SendMessageW(GetDlgItem(hwndDlg, idInterpolation), CB_ADDSTRING, 0, reinterpret_cast<LPARAM>(L"No Interpolation"));
 			SendMessageW(GetDlgItem(hwndDlg, idInterpolation), CB_ADDSTRING, 0, reinterpret_cast<LPARAM>(L"Linear Interpolation"));
 			SendMessageW(GetDlgItem(hwndDlg, idInterpolation), CB_ADDSTRING, 0, reinterpret_cast<LPARAM>(L"Cosine Interpolation"));
+			SendMessageW(GetDlgItem(hwndDlg, idInterpolation), CB_ADDSTRING, 0, reinterpret_cast<LPARAM>(L"Sharp Interpolation"));
 			SendMessageW(GetDlgItem(hwndDlg, idInterpolation), CB_SETCURSEL, this->interpolation, 0);
 			// Mutes
 			for (size_t x = 0, numMutes = this->mutes.size(); x < numMutes; ++x)

--- a/src/in_2sf/XSFPlayer_2SF.cpp
+++ b/src/in_2sf/XSFPlayer_2SF.cpp
@@ -224,6 +224,7 @@
 	}
 
 	CommonSettings.use_jit = true;
+	CommonSettings.jit_max_block_size = 100;
 	NDS_Reset();
 
 	execute = true;
@@ -236,8 +237,9 @@
 	}
 
 	sndifwork.xfs_load = true;
-	//CommonSettings.spu_advanced = true;
-	//CommonSettings.advanced_timing = false;
+	CommonSettings.rigorous_timing = true;
+	CommonSettings.spu_advanced = true;
+	CommonSettings.advanced_timing = true;
 
 	return XSFPlayer::Load();
 }

--- a/src/in_2sf/desmume/MMU.cpp
+++ b/src/in_2sf/desmume/MMU.cpp
@@ -129,7 +129,7 @@
 		/* 3X*/	DUP16(0x00007FFF),
 		/* 4X*/	DUP16(0x00FFFFFF),
 		/* 5X*/	DUP16(0x000007FF),
-		/* 6X*/	DUP16(0x00FFFFFF),
+		/* 6X*/	DUP16(0x000FFFFF),
 		/* 7X*/	DUP16(0x000007FF),
 		/* 8X*/	DUP16(0x00000003),
 		/* 9X*/	DUP16(0x00000003),
@@ -147,10 +147,10 @@
 		/* 2X*/	DUP16(0x003FFFFF),
 		/* 3X*/	DUP8(0x00007FFF),
 				DUP8(0x0000FFFF),
-		/* 4X*/	DUP8(0x00FFFFFF),
+		/* 4X*/	DUP8(0x0000FFFF),
 				DUP8(0x0000FFFF),
 		/* 5X*/	DUP16(0x00000003),
-		/* 6X*/	DUP16(0x00FFFFFF),
+		/* 6X*/	DUP16(0x000FFFFF),
 		/* 7X*/	DUP16(0x00000003),
 		/* 8X*/	DUP16(0x00000003),
 		/* 9X*/	DUP16(0x00000003),
@@ -671,8 +671,8 @@
 	MMU_VRAMmapRefreshBank(VRAM_BANK_C);
 	MMU_VRAMmapRefreshBank(VRAM_BANK_D);
 
-	//printf(vramConfiguration.describe().c_str());
-	//printf("vram remapped at vcount=%d\n",nds.VCount);
+	//fprintf(stderr, vramConfiguration.describe().c_str());
+	//fprintf(stderr, "vram remapped at vcount=%d\n",nds.VCount);
 
 	// -------------------------------
 	// set up arm9 mirrorings
@@ -1065,7 +1065,7 @@
 	T1WriteLong(MMU.MMU_MEM[TEST_PROCNUM][0x40], 0x1A4, val);
 
 	// Launch DMA if start flag was set to "DS Cart"
-	//printf("triggering card dma\n");
+	//fprintf(stderr, "triggering card dma\n");
 	triggerDma(EDMAMode_Card);
 }
 
@@ -1185,7 +1185,7 @@
 	int32_t diff = (nds.timerCycle[proc][timerIndex] - nds_timer) & 0xFFFFFFFF;
 	assert(diff >= 0);
 	if (diff < 0)
-		printf("NEW EMULOOP BAD NEWS PLEASE REPORT: TIME READ DIFF < 0 (%d) (%d) (%d)\n", diff, timerIndex, MMU.timerMODE[proc][timerIndex]);
+		fprintf(stderr, "NEW EMULOOP BAD NEWS PLEASE REPORT: TIME READ DIFF < 0 (%d) (%d) (%d)\n", diff, timerIndex, MMU.timerMODE[proc][timerIndex]);
 
 	int32_t units = diff / (1 << MMU.timerMODE[proc][timerIndex]);
 	int32_t ret;
@@ -1195,7 +1195,7 @@
 	// whichever instruction setup this counter should advance nds_timer (I think?) and the division should truncate down to 65535 immediately
 	else if (units > 65536)
 	{
-		printf("NEW EMULOOP BAD NEWS PLEASE REPORT: UNITS %d:%d = %d\n", proc, timerIndex, units);
+		fprintf(stderr, "NEW EMULOOP BAD NEWS PLEASE REPORT: UNITS %d:%d = %d\n", proc, timerIndex, units);
 		ret = 0;
 	}
 	else
@@ -1251,7 +1251,7 @@
 
 	ret |= (this->gxfifo_irq & 0x3) << 30; // user's irq flags
 
-	//printf("vc=%03d Returning gxstat read: %08X\n",nds.VCount,ret);
+	//fprintf(stderr, "vc=%03d Returning gxstat read: %08X\n",nds.VCount,ret);
 
 	return ret;
 }
@@ -1266,13 +1266,13 @@
 		//mtxStack[0].position = 0;
 		this->se = 0; // clear stack error flag
 	}
-	//printf("gxstat write: %08X while gxfifo.size=%d\n",val,gxFIFO.size);
+	//fprintf(stderr, "gxstat write: %08X while gxfifo.size=%d\n",val,gxFIFO.size);
 }
 
 // this could be inlined...
 void MMU_struct_new::write_dma(int proc, int size, uint32_t _adr, uint32_t val)
 {
-	//printf("%08lld -- write_dma: %d %d %08X %08X\n",nds_timer,proc,size,_adr,val);
+	//fprintf(stderr, "%08lld -- write_dma: %d %d %08X %08X\n",nds_timer,proc,size,_adr,val);
 	uint32_t adr = _adr - _REG_DMA_CONTROL_MIN;
 	uint32_t chan = adr / 12;
 	uint32_t regnum = (adr - chan * 12) >> 2;
@@ -1288,7 +1288,7 @@
 	uint32_t regnum = (adr - chan * 12) >> 2;
 
 	uint32_t temp = MMU_new.dma[proc][chan].regs[regnum]->read(size, adr);
-	//printf("%08lld --  read_dma: %d %d %08X = %08X\n",nds_timer,proc,size,_adr,temp);
+	//fprintf(stderr, "%08lld --  read_dma: %d %d %08X = %08X\n",nds_timer,proc,size,_adr,temp);
 
 	return temp;
 }
@@ -1305,7 +1305,7 @@
 
 void DmaController::write32(uint32_t val)
 {
-	//printf("dma %d,%d WRITE %08X\n",procnum,chan,val);
+	//fprintf(stderr, "dma %d,%d WRITE %08X\n",procnum,chan,val);
 	this->wordcount = val & 0x1FFFFF;
 	uint8_t wasEnable = this->enable;
 	uint32_t valhi = val >> 16;
@@ -1332,7 +1332,7 @@
 		this->daddr = this->daddr_user;
 	}
 
-	//printf("dma %d,%d set to startmode %d with wordcount set to: %08X\n",procnum,chan,_startmode,wordcount);
+	//fprintf(stderr, "dma %d,%d set to startmode %d with wordcount set to: %08X\n",procnum,chan,_startmode,wordcount);
 	// analyze enabling and startmode.
 	// note that we only do this if the dma was freshly enabled.
 	// we should probably also only be latching these other regs in that case too..
@@ -1463,7 +1463,7 @@
 	// need to figure out what to do about this
 	if (bogarted)
 	{
-		printf("YOUR GAME IS BOGARTED!!! PLEASE REPORT!!!\n");
+		fprintf(stderr, "YOUR GAME IS BOGARTED!!! PLEASE REPORT!!!\n");
 		assert(false);
 		return;
 	}
@@ -1580,7 +1580,7 @@
 	ret |= this->sar << 23;
 	ret |= this->dar << 21;
 	ret |= this->wordcount;
-	//printf("dma %d,%d READ  %08X\n",procnum,chan,ret);
+	//fprintf(stderr, "dma %d,%d READ  %08X\n",procnum,chan,ret);
 	return ret;
 }
 
@@ -1621,30 +1621,30 @@
 		switch (adr)
 		{
 			case REG_SQRTCNT:
-				printf("ERROR 8bit SQRTCNT WRITE\n");
+				fprintf(stderr, "ERROR 8bit SQRTCNT WRITE\n");
 				return;
 			case REG_SQRTCNT + 1:
-				printf("ERROR 8bit SQRTCNT1 WRITE\n");
+				fprintf(stderr, "ERROR 8bit SQRTCNT1 WRITE\n");
 				return;
 			case REG_SQRTCNT + 2:
-				printf("ERROR 8bit SQRTCNT2 WRITE\n");
+				fprintf(stderr, "ERROR 8bit SQRTCNT2 WRITE\n");
 				return;
 			case REG_SQRTCNT + 3:
-				printf("ERROR 8bit SQRTCNT3 WRITE\n");
+				fprintf(stderr, "ERROR 8bit SQRTCNT3 WRITE\n");
 				return;
 
 #if 1
 			case REG_DIVCNT:
-				printf("ERROR 8bit DIVCNT WRITE\n");
+				fprintf(stderr, "ERROR 8bit DIVCNT WRITE\n");
 				return;
 			case REG_DIVCNT + 1:
-				printf("ERROR 8bit DIVCNT+1 WRITE\n");
+				fprintf(stderr, "ERROR 8bit DIVCNT+1 WRITE\n");
 				return;
 			case REG_DIVCNT + 2:
-				printf("ERROR 8bit DIVCNT+2 WRITE\n");
+				fprintf(stderr, "ERROR 8bit DIVCNT+2 WRITE\n");
 				return;
 			case REG_DIVCNT + 3:
-				printf("ERROR 8bit DIVCNT+3 WRITE\n");
+				fprintf(stderr, "ERROR 8bit DIVCNT+3 WRITE\n");
 				return;
 #endif
 
@@ -1734,12 +1734,12 @@
 			case REG_DIVNUMER:
 			case REG_DIVNUMER + 2:
 			case REG_DIVNUMER + 4:
-				printf("DIV: 16 write NUMER %08X. PLEASE REPORT! \n", val);
+				fprintf(stderr, "DIV: 16 write NUMER %08X. PLEASE REPORT! \n", val);
 				break;
 			case REG_DIVDENOM:
 			case REG_DIVDENOM + 2:
 			case REG_DIVDENOM + 4:
-				printf("DIV: 16 write DENOM %08X. PLEASE REPORT! \n", val);
+				fprintf(stderr, "DIV: 16 write DENOM %08X. PLEASE REPORT! \n", val);
 				break;
 #endif
 			case REG_SQRTCNT:
@@ -2024,10 +2024,10 @@
 
 			// sqrtcnt isnt big enough for these to exist. but they'd probably return 0 so its ok
 			case REG_SQRTCNT + 2:
-				printf("ERROR 8bit SQRTCNT+2 READ\n");
+				fprintf(stderr, "ERROR 8bit SQRTCNT+2 READ\n");
 				return 0;
 			case REG_SQRTCNT + 3:
-				printf("ERROR 8bit SQRTCNT+3 READ\n");
+				fprintf(stderr, "ERROR 8bit SQRTCNT+3 READ\n");
 				return 0;
 
 			// Nostalgia's options menu requires that these work
@@ -2038,10 +2038,10 @@
 
 			// divcnt isnt big enough for these to exist. but they'd probably return 0 so its ok
 			case REG_DIVCNT + 2:
-				printf("ERROR 8bit DIVCNT+2 READ\n");
+				fprintf(stderr, "ERROR 8bit DIVCNT+2 READ\n");
 				return 0;
 			case REG_DIVCNT + 3:
-				printf("ERROR 8bit DIVCNT+3 READ\n");
+				fprintf(stderr, "ERROR 8bit DIVCNT+3 READ\n");
 				return 0;
 		}
 	}
@@ -2077,14 +2077,14 @@
 				return MMU_new.sqrt.read16();
 			// sqrtcnt isnt big enough for this to exist. but it'd probably return 0 so its ok
 			case REG_SQRTCNT + 2:
-				printf("ERROR 16bit SQRTCNT+2 READ\n");
+				fprintf(stderr, "ERROR 16bit SQRTCNT+2 READ\n");
 				return 0;
 
 			case REG_DIVCNT:
 				return MMU_new.div.read16();
 			// divcnt isnt big enough for this to exist. but it'd probably return 0 so its ok
 			case REG_DIVCNT + 2:
-				printf("ERROR 16bit DIVCNT+2 READ\n");
+				fprintf(stderr, "ERROR 16bit DIVCNT+2 READ\n");
 				return 0;
 
 			case REG_IME:
@@ -2255,7 +2255,7 @@
 				break;
 
 			case REG_HALTCNT:
-				//printf("halt 0x%02X\n", val);
+				//fprintf(stderr, "halt 0x%02X\n", val);
 				switch (val)
 				{
 					case 0xC0:
@@ -2310,11 +2310,11 @@
 			case REG_DISPA_VCOUNT:
 				if (nds.VCount >= 202 && nds.VCount <= 212)
 				{
-					printf("VCOUNT set to %i (previous value %i)\n", val, nds.VCount);
+					fprintf(stderr, "VCOUNT set to %i (previous value %i)\n", val, nds.VCount);
 					nds.VCount = val;
 				}
 				else
-					printf("Attempt to set VCOUNT while not within 202-212 (%i), ignored\n", nds.VCount);
+					fprintf(stderr, "Attempt to set VCOUNT while not within 202-212 (%i), ignored\n", nds.VCount);
 				return;
 
 			case REG_EXMEMCNT:
@@ -2379,7 +2379,7 @@
 								// our totally pathetic register handling, only the one thing we've wanted so far
 								if (MMU.powerMan_Reg[0] & PM_SYSTEM_PWR)
 								{
-									printf("SYSTEM POWERED OFF VIA ARM7 SPI POWER DEVICE\n");
+									fprintf(stderr, "SYSTEM POWERED OFF VIA ARM7 SPI POWER DEVICE\n");
 									execute = false;
 								}
 							}
@@ -2413,7 +2413,7 @@
 						}
 
 						int channel = (MMU.SPI_CMD & 0x70) >> 4;
-						//printf("%08X\n",channel);
+						//fprintf(stderr, "%08X\n",channel);
 						switch (channel)
 						{
 							case TSC_MEASURE_TEMP1:

--- a/src/in_2sf/desmume/MMU.h
+++ b/src/in_2sf/desmume/MMU.h
@@ -322,7 +322,7 @@
 		// an extra 128KB for blank memory, directly after arm9_lcd, so that
 		// we can easily map things to the end of arm9_lcd to represent
 		// an unmapped state
-		uint8_t blank_memory[0x20000];
+		uint8_t blank_memory[0x100000 - 0xA4000];
 	};
 #include "PACKED_END.h"
 

--- a/src/in_2sf/desmume/MMU_timing.h
+++ b/src/in_2sf/desmume/MMU_timing.h
@@ -129,8 +129,8 @@
 	enum { ASSOCIATIVITY = 1 << ASSOCIATIVESHIFT };
 	enum { BLOCKSIZE = 1 << BLOCKSIZESHIFT };
 	enum { TAGSHIFT = SIZESHIFT - ASSOCIATIVESHIFT };
-	enum { TAGMASK = ~0 << TAGSHIFT };
-	enum { BLOCKMASK = (~0 >> (32 - TAGSHIFT)) & (~0 << BLOCKSIZESHIFT) };
+	enum { TAGMASK = ~0U << TAGSHIFT };
+	enum { BLOCKMASK = (~0U >> (32 - TAGSHIFT)) & (~0U << BLOCKSIZESHIFT) };
 	enum { WORDSIZE = sizeof(uint32_t) };
 	enum { WORDSPERBLOCK = (1 << BLOCKSIZESHIFT) / WORDSIZE };
 	enum { DATAPERWORD = WORDSIZE * ASSOCIATIVITY };

--- a/src/in_2sf/desmume/NDSSystem.cpp
+++ b/src/in_2sf/desmume/NDSSystem.cpp
@@ -38,18 +38,13 @@
 NDSSystem nds;
 static std::unique_ptr<CFIRMWARE> firmware;
 
-namespace DLDI
-{
-	bool tryPatch(void *data, size_t size);
-}
-
 int NDS_Init()
 {
 	MMU_Init();
 	nds.VCount = 0;
 
 	// got to print this somewhere..
-	printf("%s\n", EMU_DESMUME_NAME_AND_VERSION());
+	fprintf(stderr, "%s\n", EMU_DESMUME_NAME_AND_VERSION());
 
 	armcpu_new(&NDS_ARM7, 1);
 	armcpu_new(&NDS_ARM9, 0);
@@ -230,7 +225,7 @@
 				}
 #ifndef NDEBUG
 				if (ctr > 1)
-					printf("yikes!!!!! please report!\n");
+					fprintf(stderr, "yikes!!!!! please report!\n");
 #endif
 			}
 
@@ -267,7 +262,7 @@
 
 	void exec()
 	{
-		//printf("exec from TSequenceItem_DMA: %d %d\n",procnum,chan);
+		//fprintf(stderr, "exec from TSequenceItem_DMA: %d %d\n",procnum,chan);
 		this->controller->exec();
 	}
 };
@@ -453,7 +448,7 @@
 
 static void execHardware_hstart_vblankStart()
 {
-	//printf("--------VBLANK!!!--------\n");
+	//fprintf(stderr, "--------VBLANK!!!--------\n");
 
 	// fire vblank interrupts if necessary
 	for (int i = 0; i < 2; ++i)
@@ -794,7 +789,7 @@
 			uint64_t next = sequencer.findNext();
 			next = std::min(next, nds_timer + kMaxWork); // lets set an upper limit for now
 
-			//printf("%d\n", next - nds_timer);
+			//fprintf(stderr, "%d\n", next - nds_timer);
 
 			sequencer.reschedule = false;
 
@@ -838,7 +833,7 @@
 
 	if (masked && MMU.reg_IME[PROCNUM] && !ARMPROC.CPSR.bits.I)
 	{
-		//printf("Executing IRQ on procnum %d with IF = %08X and IE = %08X\n",PROCNUM,IF,IE);
+		//fprintf(stderr, "Executing IRQ on procnum %d with IF = %08X and IE = %08X\n",PROCNUM,IF,IE);
 		armcpu_irqException(&ARMPROC);
 	}
 }

--- a/src/in_2sf/desmume/NDSSystem.h
+++ b/src/in_2sf/desmume/NDSSystem.h
@@ -21,6 +21,7 @@
 #include <memory>
 #include <string>
 #include <cstring>
+#include <stdlib.h>
 #include "armcpu.h"
 #include "MMU.h"
 #include "SPU.h"
@@ -289,8 +290,34 @@
 		strcpy(this->Firmware, "firmware.bin");
 		NDS_FillDefaultFirmwareConfigData(&this->InternalFirmConf);
 
-		for (int i = 0; i < 16; ++i)
-			this->spu_muteChannels[i] = false;
+    bool solo = false;
+    static char* soloEnv = strdup("SOLO_2SF_n");
+    static char* muteEnv = strdup("MUTE_2SF_n");
+		for (int i = 0; i < 16; ++i) {
+      if (i < 10) {
+        soloEnv[9] = '0' + i;
+      } else {
+        soloEnv[9] = 'A' + (i - 10);
+      }
+      char* soloVal = getenv(soloEnv);
+      if (soloVal && soloVal[0] == '1') {
+        solo = true;
+        this->spu_muteChannels[i] = false;
+      } else {
+        this->spu_muteChannels[i] = true;
+      }
+    }
+    if (!solo) {
+      for (int i = 0; i < 16; ++i) {
+        if (i < 10) {
+          muteEnv[9] = '0' + i;
+        } else {
+          muteEnv[9] = 'A' + (i - 10);
+        }
+        char* muteVal = getenv(muteEnv);
+        this->spu_muteChannels[i] = muteVal && muteVal[0] == '1';
+      }
+    }
 
 #ifdef HAVE_JIT
 		// zero 06-sep-2012 - shouldnt be defaulting this to true for now, since the jit is buggy.

--- a/src/in_2sf/desmume/SPU.cpp
+++ b/src/in_2sf/desmume/SPU.cpp
@@ -1,1542 +1,1481 @@
 /*
-	Copyright (C) 2006 yopyop
-	Copyright (C) 2006 Theo Berkau
-	Copyright (C) 2008-2012 DeSmuME team
-
-	Ideas borrowed from Stephane Dallongeville's SCSP core
-
-	This file is free software: you can redistribute it and/or modify
-	it under the terms of the GNU General Public License as published by
-	the Free Software Foundation, either version 2 of the License, or
-	(at your option) any later version.
-
-	This file is distributed in the hope that it will be useful,
-	but WITHOUT ANY WARRANTY; without even the implied warranty of
-	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-	GNU General Public License for more details.
-
-	You should have received a copy of the GNU General Public License
-	along with the this software.  If not, see <http://www.gnu.org/licenses/>.
-*/
+   Copyright (C) 2006 yopyop
+   Copyright (C) 2006 Theo Berkau
+   Copyright (C) 2008-2017 DeSmuME team
+
+   Ideas borrowed from Stephane Dallongeville's SCSP core
+
+   This file is free software: you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation, either version 2 of the License, or
+   (at your option) any later version.
+
+   This file is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with the this software.  If not, see <http://www.gnu.org/licenses/>.
+   */
 
 #include "XSFCommon.h"
-
+#include "../spu/samplecache.h"
+#include "../spu/interpolator.h"
+
+#define _USE_MATH_DEFINES
+#include <math.h>
+#ifndef M_PI
+#define M_PI 3.1415926535897932386
+#endif
+
+#include <stdlib.h>
+#include <string.h>
 #include <queue>
 #include <vector>
-#include <cstdlib>
-#include <cstring>
-#ifndef M_PI
-static const double M_PI = 3.14159265358979323846;
-#endif
+
 #include "MMU.h"
 #include "SPU.h"
 #include "mem.h"
 #include "readwrite.h"
 #include "armcpu.h"
 #include "NDSSystem.h"
+#include "emufile.h"
 #include "matrix.h"
-
-static inline int16_t read16(uint32_t addr) { return _MMU_read16<ARMCPU_ARM7,MMU_AT_DEBUG>(addr); }
-static inline uint8_t read08(uint32_t addr) { return _MMU_read08<ARMCPU_ARM7,MMU_AT_DEBUG>(addr); }
-static inline int8_t read_s8(uint32_t addr) { return _MMU_read08<ARMCPU_ARM7,MMU_AT_DEBUG>(addr); }
-
-static const int K_ADPCM_LOOPING_RECOVERY_INDEX = 99999;
-static const int COSINE_INTERPOLATION_RESOLUTION = 8192;
-
-static auto synchronizer = std::unique_ptr<ISynchronizingAudioBuffer>(metaspu_construct(ESynchMethod_N));
-
-std::unique_ptr<SPU_struct> SPU_core, SPU_user;
+#include "utils/bits.h"
+
+static inline s16 read16(u32 addr) { return (s16)_MMU_read16<ARMCPU_ARM7,MMU_AT_DEBUG>(addr); }
+static inline u8 read08(u32 addr) { return _MMU_read08<ARMCPU_ARM7,MMU_AT_DEBUG>(addr); }
+static inline s8 read_s8(u32 addr) { return (s8)_MMU_read08<ARMCPU_ARM7,MMU_AT_DEBUG>(addr); }
+
+#define K_ADPCM_LOOPING_RECOVERY_INDEX 99999
+#define COSINE_INTERPOLATION_RESOLUTION 8192
+
+SPU_struct *SPU_core = 0;
 int SPU_currentCoreNum = SNDCORE_DUMMY;
 static int volume = 100;
+static SampleCache sampleCache;
 
 static size_t buffersize = 0;
-static ESynchMode synchmode = ESynchMode_DualSynchAsynch;
-static ESynchMethod synchmethod = ESynchMethod_N;
-
-static int SNDCoreId = -1;
-static SoundInterface_struct *SNDCore = nullptr;
+static ESynchMode synchmode = ESynchMode_Synchronous;
+static ESynchMethod synchmethod = ESynchMethod_0;
+static ISynchronizingAudioBuffer* synchronizer = metaspu_construct(synchmethod);
+
+static int SNDCoreId=-1;
+static SoundInterface_struct *SNDCore=NULL;
 extern SoundInterface_struct *SNDCoreList[];
 
 static const int format_shift[] = { 2, 1, 3, 0 };
-
-static const int8_t indextbl[8] =
-{
-	-1, -1, -1, -1, 2, 4, 6, 8
+static const u8 volume_shift[] = { 0, 1, 2, 4 };
+
+static const s8 indextbl[8] = { -1, -1, -1, -1, 2, 4, 6, 8 };
+
+static const u16 adpcmtbl[89] = {
+  0x0007, 0x0008, 0x0009, 0x000A, 0x000B, 0x000C, 0x000D, 0x000E, 0x0010,
+  0x0011, 0x0013, 0x0015, 0x0017, 0x0019, 0x001C, 0x001F, 0x0022, 0x0025,
+  0x0029, 0x002D, 0x0032, 0x0037, 0x003C, 0x0042, 0x0049, 0x0050, 0x0058,
+  0x0061, 0x006B, 0x0076, 0x0082, 0x008F, 0x009D, 0x00AD, 0x00BE, 0x00D1,
+  0x00E6, 0x00FD, 0x0117, 0x0133, 0x0151, 0x0173, 0x0198, 0x01C1, 0x01EE,
+  0x0220, 0x0256, 0x0292, 0x02D4, 0x031C, 0x036C, 0x03C3, 0x0424, 0x048E,
+  0x0502, 0x0583, 0x0610, 0x06AB, 0x0756, 0x0812, 0x08E0, 0x09C3, 0x0ABD,
+  0x0BD0, 0x0CFF, 0x0E4C, 0x0FBA, 0x114C, 0x1307, 0x14EE, 0x1706, 0x1954,
+  0x1BDC, 0x1EA5, 0x21B6, 0x2515, 0x28CA, 0x2CDF, 0x315B, 0x364B, 0x3BB9,
+  0x41B2, 0x4844, 0x4F7E, 0x5771, 0x602F, 0x69CE, 0x7462, 0x7FFF
 };
 
-static const uint16_t adpcmtbl[89] =
-{
-	0x0007, 0x0008, 0x0009, 0x000A, 0x000B, 0x000C, 0x000D, 0x000E, 0x0010,
-	0x0011, 0x0013, 0x0015, 0x0017, 0x0019, 0x001C, 0x001F, 0x0022, 0x0025,
-	0x0029, 0x002D, 0x0032, 0x0037, 0x003C, 0x0042, 0x0049, 0x0050, 0x0058,
-	0x0061, 0x006B, 0x0076, 0x0082, 0x008F, 0x009D, 0x00AD, 0x00BE, 0x00D1,
-	0x00E6, 0x00FD, 0x0117, 0x0133, 0x0151, 0x0173, 0x0198, 0x01C1, 0x01EE,
-	0x0220, 0x0256, 0x0292, 0x02D4, 0x031C, 0x036C, 0x03C3, 0x0424, 0x048E,
-	0x0502, 0x0583, 0x0610, 0x06AB, 0x0756, 0x0812, 0x08E0, 0x09C3, 0x0ABD,
-	0x0BD0, 0x0CFF, 0x0E4C, 0x0FBA, 0x114C, 0x1307, 0x14EE, 0x1706, 0x1954,
-	0x1BDC, 0x1EA5, 0x21B6, 0x2515, 0x28CA, 0x2CDF, 0x315B, 0x364B, 0x3BB9,
-	0x41B2, 0x4844, 0x4F7E, 0x5771, 0x602F, 0x69CE, 0x7462, 0x7FFF
+static const s16 wavedutytbl[8][8] = {
+  { -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF, 0x7FFF },
+  { -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF, 0x7FFF, 0x7FFF },
+  { -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF },
+  { -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF },
+  { -0x7FFF, -0x7FFF, -0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF },
+  { -0x7FFF, -0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF },
+  { -0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF },
+  { -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF }
 };
 
-static const int16_t wavedutytbl[8][8] = {
-	{ -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF, 0x7FFF },
-	{ -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF, 0x7FFF, 0x7FFF },
-	{ -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF },
-	{ -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF },
-	{ -0x7FFF, -0x7FFF, -0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF },
-	{ -0x7FFF, -0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF },
-	{ -0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF, 0x7FFF },
-	{ -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF, -0x7FFF }
-};
-
-static int32_t precalcdifftbl[89][16];
-static uint8_t precalcindextbl[89][8];
-static double cos_lut[COSINE_INTERPOLATION_RESOLUTION];
-
 static const double ARM7_CLOCK = 33513982;
 
-static const double samples_per_hline = (DESMUME_SAMPLE_RATE / 59.8261f) / 263.0f;
+double DESMUME_SAMPLE_RATE = 32728.498;
+static double samples_per_hline = (DESMUME_SAMPLE_RATE / 59.8261f) / 263.0f;
+static double sampleLength = DESMUME_SAMPLE_RATE / 32728.498;
+
+void SetDesmumeSampleRate(double rate) {
+  DESMUME_SAMPLE_RATE = rate;
+  sampleLength = DESMUME_SAMPLE_RATE / 32728.498;
+  samples_per_hline = (DESMUME_SAMPLE_RATE / 59.8261f) / 263.0f;
+  for (int i = 0; i < 16; i++) {
+    channel_struct *chan = &SPU_core->channels[i];
+  }
+}
 
 static double samples = 0;
 
-template<typename T> static inline T MinMax(T val, T min, T max)
-{
-	if (val < min)
-		return min;
-	else if (val > max)
-		return max;
-	else
-		return val;
+template<typename T>
+static FORCEINLINE T MinMax(T val, T min, T max)
+{
+  if (val < min)
+    return min;
+  else if (val > max)
+    return max;
+
+  return val;
 }
 
 //--------------external spu interface---------------
 
-int SPU_ChangeSoundCore(int coreid, int Buffersize)
-{
-	buffersize = Buffersize;
-
-	SPU_user.reset();
-
-	// Make sure the old core is freed
-	if (SNDCore)
-		SNDCore->DeInit();
-
-	// So which core do we want?
-	if (coreid == SNDCORE_DEFAULT)
-		coreid = 0; // Assume we want the first one
-
-	SPU_currentCoreNum = coreid;
-
-	// Go through core list and find the id
-	for (int i = 0; SNDCoreList[i]; ++i)
-		if (SNDCoreList[i]->id == coreid)
-		{
-			// Set to current core
-			SNDCore = SNDCoreList[i];
-			break;
-		}
-
-	SNDCoreId = coreid;
-
-	// If the user picked the dummy core, disable the user spu
-	if (SNDCore == &SNDDummy)
-		return 0;
-
-	// If the core wasnt found in the list for some reason, disable the user spu
-	if (!SNDCore)
-		return -1;
-
-	// Since it failed, instead of it being fatal, disable the user spu
-	if (SNDCore->Init(buffersize * 2) == -1)
-	{
-		SNDCore = nullptr;
-		return -1;
-	}
-
-	SNDCore->SetVolume(volume);
-
-	SPU_SetSynchMode(synchmode, synchmethod);
-
-	return 0;
-}
-
-void SPU_ReInit()
-{
-	SPU_Init(SNDCoreId, buffersize);
-}
-
-int SPU_Init(int coreid, int Buffersize)
-{
-	// Build the cosine interpolation LUT
-	int i;
-	for (i = 0; i < COSINE_INTERPOLATION_RESOLUTION; ++i)
-		cos_lut[i] = (1.0 - std::cos((static_cast<double>(i) / COSINE_INTERPOLATION_RESOLUTION) * M_PI)) * 0.5;
-
-	SPU_core.reset(new SPU_struct(std::ceil(samples_per_hline)));
-	SPU_Reset();
-
-	int j;
-	// create adpcm decode accelerator lookups
-	for (i = 0; i < 16; ++i)
-		for (j = 0; j < 89; ++j)
-		{
-			precalcdifftbl[j][i] = ((i & 0x7) * 2 + 1) * adpcmtbl[j] / 8;
-			if (i & 0x8)
-				precalcdifftbl[j][i] = -precalcdifftbl[j][i];
-		}
-	for (i = 0; i < 8; ++i)
-		for (j = 0; j < 89; ++j)
-			precalcindextbl[j][i] = MinMax(j + indextbl[i], 0, 88);
-
-	return SPU_ChangeSoundCore(coreid, Buffersize);
-}
-
-void SPU_CloneUser()
-{
-	if (SPU_user)
-	{
-		memcpy(SPU_user->channels, SPU_core->channels, sizeof(SPU_core->channels));
-		SPU_user->regs = SPU_core->regs;
-	}
-}
-
-void SPU_SetSynchMode(ESynchMode mode, ESynchMethod method)
-{
-	synchmode = mode;
-	if (synchmethod != method)
-	{
-		synchmethod = method;
-		// grr does this need to be locked? spu might need a lock method
-		// or maybe not, maybe the platform-specific code that calls this function can deal with it.
-		synchronizer.reset(metaspu_construct(synchmethod));
-	}
-
-	SPU_user.reset();
-
-	if (synchmode == ESynchMode_DualSynchAsynch)
-	{
-		SPU_user.reset(new SPU_struct(buffersize));
-		SPU_CloneUser();
-	}
-}
-
-void SPU_Reset()
-{
-	SPU_core->reset();
-
-	if (SPU_user)
-	{
-		if (SNDCore)
-		{
-			SNDCore->DeInit();
-			SNDCore->Init(SPU_user->bufsize * 2);
-			SNDCore->SetVolume(volume);
-		}
-		SPU_user->reset();
-	}
-
-	// zero - 09-apr-2010: this concerns me, regarding savestate synch.
-	// After 0.9.6, lets experiment with removing it and just properly zapping the spu instead
-	// Reset Registers
-	for (int i = 0x400; i < 0x51D; ++i)
-		T1WriteByte(MMU.ARM7_REG, i, 0);
-
-	samples = 0;
+int SPU_ChangeSoundCore(int coreid, int buffersize)
+{
+  int i;
+
+  ::buffersize = buffersize;
+
+  // Make sure the old core is freed
+  if (SNDCore)
+    SNDCore->DeInit();
+
+  // So which core do we want?
+  if (coreid == SNDCORE_DEFAULT)
+    coreid = 0; // Assume we want the first one
+
+  SPU_currentCoreNum = coreid;
+
+  // Go through core list and find the id
+  for (i = 0; SNDCoreList[i] != NULL; i++)
+  {
+    if (SNDCoreList[i]->id == coreid)
+    {
+      // Set to current core
+      SNDCore = SNDCoreList[i];
+      break;
+    }
+  }
+
+  SNDCoreId = coreid;
+
+  //If the user picked the dummy core, disable the user spu
+  if(SNDCore == &SNDDummy)
+    return 0;
+
+  //If the core wasnt found in the list for some reason, disable the user spu
+  if (SNDCore == NULL)
+    return -1;
+
+  // Since it failed, instead of it being fatal, disable the user spu
+  if (SNDCore->Init(buffersize * 2) == -1)
+  {
+    SNDCore = 0;
+    return -1;
+  }
+
+  SNDCore->SetVolume(volume);
+
+  SPU_SetSynchMode(synchmode,synchmethod);
+
+  return 0;
+}
+
+SoundInterface_struct *SPU_SoundCore()
+{
+  return SNDCore;
+}
+
+void SPU_ReInit(bool fakeBoot)
+{
+  SPU_Init(SNDCoreId, buffersize);
+
+  // Firmware set BIAS to 0x200
+  if (fakeBoot)
+    SPU_WriteWord(0x04000504, 0x0200);
+}
+
+int SPU_Init(int coreid, int buffersize)
+{
+  SPU_core = new SPU_struct((int)ceil(samples_per_hline));
+  SPU_Reset();
+
+  SPU_SetSynchMode(synchmode, synchmethod);
+
+  return SPU_ChangeSoundCore(coreid, buffersize);
+}
+
+void SPU_Pause(int pause)
+{
+  if (SNDCore == NULL) return;
+
+  if(pause)
+    SNDCore->MuteAudio();
+  else
+    SNDCore->UnMuteAudio();
+}
+
+void SPU_SetSynchMode(int mode, int method)
+{
+  synchmode = (ESynchMode)mode;
+  if(synchmethod != (ESynchMethod)method)
+  {
+    synchmethod = (ESynchMethod)method;
+    delete synchronizer;
+    //grr does this need to be locked? spu might need a lock method
+    // or maybe not, maybe the platform-specific code that calls this function can deal with it.
+    synchronizer = metaspu_construct(synchmethod);
+  }
+}
+
+void SPU_ClearOutputBuffer()
+{
+  if(SNDCore && SNDCore->ClearBuffer)
+    SNDCore->ClearBuffer();
+}
+
+void SPU_SetVolume(int volume)
+{
+  ::volume = volume;
+  if (SNDCore)
+    SNDCore->SetVolume(volume);
+}
+
+
+void SPU_Reset(void)
+{
+  int i;
+
+  SPU_core->reset();
+
+  //zero - 09-apr-2010: this concerns me, regarding savestate synch.
+  //After 0.9.6, lets experiment with removing it and just properly zapping the spu instead
+  // Reset Registers
+  for (i = 0x400; i < 0x51D; i++)
+    T1WriteByte(MMU.ARM7_REG, i, 0);
+
+  samples = 0;
 }
 
 //------------------------------------------
 
 void SPU_struct::reset()
 {
-	memset(&this->sndbuf[0], 0, bufsize * 2 * 4);
-	memset(&this->outbuf[0], 0, bufsize * 2 * 2);
-
-	memset(this->channels, 0, sizeof(channel_struct) * 16);
-
-	reconstruct(&this->regs);
-
-	for (int i = 0; i < 16; ++i)
-		this->channels[i].num = i;
-}
-
-SPU_struct::SPU_struct(int Buffersize) : bufpos(0), buflength(0), sndbuf(new int32_t[Buffersize * 2]), outbuf(new int16_t[Buffersize * 2]), bufsize(Buffersize)
-{
-	this->reset();
-}
-
-void SPU_DeInit()
-{
-	if (SNDCore)
-		SNDCore->DeInit();
-	SNDCore = nullptr;
-
-	SPU_core.reset();
-	SPU_user.reset();
+  memset(sndbuf,0,bufsize*2*4);
+  memset(outbuf,0,bufsize*2*2);
+
+  memset((void *)channels, 0, sizeof(channel_struct) * 16);
+
+  reconstruct(&regs);
+
+  for(int i = 0; i < 16; i++)
+  {
+    channels[i].num = i;
+  }
+}
+
+SPU_struct::SPU_struct(int buffersize)
+  : bufpos(0)
+  , buflength(0)
+  , sndbuf(0)
+  , outbuf(0)
+    , bufsize(buffersize)
+{
+  sndbuf = new s32[buffersize*2];
+  outbuf = new s16[buffersize*2];
+  reset();
+}
+
+SPU_struct::~SPU_struct()
+{
+  if(sndbuf) delete[] sndbuf;
+  if(outbuf) delete[] outbuf;
+}
+
+void SPU_DeInit(void)
+{
+  if(SNDCore)
+    SNDCore->DeInit();
+  SNDCore = 0;
+
+  delete SPU_core; SPU_core=0;
 }
 
 //////////////////////////////////////////////////////////////////////////////
 
 void SPU_struct::ShutUp()
 {
-	for (int i = 0; i < 16; ++i)
-		this->channels[i].status = CHANSTAT_STOPPED;
-}
-
-static inline void adjust_channel_timer(channel_struct *chan)
-{
-	chan->sampinc = (ARM7_CLOCK / (DESMUME_SAMPLE_RATE * 2)) / (0x10000 - chan->timer);
+  for(int i=0;i<16;i++)
+    channels[i].status = CHANSTAT_STOPPED;
+}
+
+static FORCEINLINE void adjust_channel_timer(channel_struct *chan)
+{
+  chan->sampinc = (((double)ARM7_CLOCK) / (DESMUME_SAMPLE_RATE * 2)) / (double)(0x10000 - chan->timer);
 }
 
 void SPU_struct::KeyProbe(int chan_num)
 {
-	channel_struct &thischan = this->channels[chan_num];
-	if (thischan.status == CHANSTAT_STOPPED)
-	{
-		if (thischan.keyon && this->regs.masteren)
-			this->KeyOn(chan_num);
-	}
-	else if (thischan.status == CHANSTAT_PLAY)
-	{
-		if (!thischan.keyon || !this->regs.masteren)
-			this->KeyOff(chan_num);
-	}
+  channel_struct &thischan = channels[chan_num];
+  if(thischan.status == CHANSTAT_STOPPED)
+  {
+    if(thischan.keyon && regs.masteren)
+      KeyOn(chan_num);
+  }
+  else if(thischan.status == CHANSTAT_PLAY)
+  {
+    if(!thischan.keyon || !regs.masteren)
+      KeyOff(chan_num);
+  }
 }
 
 void SPU_struct::KeyOff(int channel)
 {
-	//printf("keyoff%d\n",channel);
-	channel_struct &thischan = this->channels[channel];
-	thischan.status = CHANSTAT_STOPPED;
+  channel_struct &thischan = channels[channel];
+  thischan.status = CHANSTAT_STOPPED;
 }
 
 void SPU_struct::KeyOn(int channel)
 {
-	channel_struct &thischan = this->channels[channel];
-	thischan.status = CHANSTAT_PLAY;
-
-	thischan.totlength = thischan.length + thischan.loopstart;
-	adjust_channel_timer(&thischan);
-
-	//printf("keyon %d totlength:%d\n",channel,thischan.totlength);
-
-	//LOG("Channel %d key on: vol = %d, datashift = %d, hold = %d, pan = %d, waveduty = %d, repeat = %d, format = %d, source address = %07X,"
-	//		"timer = %04X, loop start = %04X, length = %06X, MMU.ARM7_REG[0x501] = %02X\n", channel, chan->vol, chan->datashift, chan->hold,
-	//		chan->pan, chan->waveduty, chan->repeat, chan->format, chan->addr, chan->timer, chan->loopstart, chan->length, T1ReadByte(MMU.ARM7_REG, 0x501));
-
-	switch (thischan.format)
-	{
-		case 0: // 8-bit
-			//hischan.loopstart = thischan.loopstart << 2;
-			//hischan.length = (thischan.length << 2) + thischan.loopstart;
-			thischan.sampcnt = -3;
-			break;
-		case 1: // 16-bit
-			//thischan.loopstart = thischan.loopstart << 1;
-			//thischan.length = (thischan.length << 1) + thischan.loopstart;
-			thischan.sampcnt = -3;
-			break;
-		case 2: // ADPCM
-			thischan.pcm16b = read16(thischan.addr);
-			thischan.pcm16b_last = thischan.pcm16b;
-			thischan.index = read08(thischan.addr + 2) & 0x7F;
-			thischan.lastsampcnt = 7;
-			thischan.sampcnt = -3;
-			thischan.loop_index = K_ADPCM_LOOPING_RECOVERY_INDEX;
-			//thischan.loopstart = thischan.loopstart << 3;
-			//hischan.length = (thischan.length << 3) + thischan.loopstart;
-			break;
-		case 3: // PSG
-			thischan.sampcnt = -1;
-			thischan.x = 0x7FFF;
-	}
-
-	thischan.double_totlength_shifted = thischan.totlength << format_shift[thischan.format];
-
-	if (thischan.format != 3 && fEqual(thischan.double_totlength_shifted, 0.0))
-	{
-		printf("INFO: Stopping channel %d due to zero length\n", channel);
-		thischan.status = CHANSTAT_STOPPED;
-	}
+  channel_struct &thischan = channels[channel];
+  thischan.status = CHANSTAT_PLAY;
+
+  thischan.totlength = thischan.length + thischan.loopstart;
+  adjust_channel_timer(&thischan);
+
+  switch(thischan.format)
+  {
+    case 0: // 8-bit
+      thischan.sampcnt = -3;
+      break;
+    case 1: // 16-bit
+      thischan.sampcnt = -3;
+      break;
+    case 2: // ADPCM
+      {
+        thischan.pcm16b = (s16)read16(thischan.addr);
+        thischan.pcm16b_last = thischan.pcm16b;
+        thischan.index = read08(thischan.addr + 2) & 0x7F;;
+        thischan.lastsampcnt = 7;
+        thischan.sampcnt = -3;
+        thischan.loop_index = K_ADPCM_LOOPING_RECOVERY_INDEX;
+        break;
+      }
+    case 3: // PSG
+      {
+        thischan.sampcnt = -1;
+        thischan.x = 0x7FFF;
+        break;
+      }
+    default: break;
+  }
+
+  thischan.double_totlength_shifted = (double)(thischan.totlength << format_shift[thischan.format]);
+
+  if(thischan.format != 3)
+  {
+    if(thischan.double_totlength_shifted == 0)
+    {
+      thischan.status = CHANSTAT_STOPPED;
+    }
+  }
 }
 
 //////////////////////////////////////////////////////////////////////////////
 
-template<typename T> static inline void SETBYTE(uint32_t which, T &oldval, uint8_t newval) { oldval = (oldval & (~(0xFF << (which * 8)))) | (newval << (which * 8)); }
-static inline uint8_t GETBYTE(uint32_t which, uint32_t val) { return (val >> (which * 8)) & 0xFF; }
-
-uint8_t SPU_ReadByte(uint32_t addr)
-{
-	addr &= 0xFFF;
-	return SPU_core->ReadByte(addr);
-}
-uint16_t SPU_ReadWord(uint32_t addr)
-{
-	addr &= 0xFFF;
-	return SPU_core->ReadWord(addr);
-}
-uint32_t SPU_ReadLong(uint32_t addr)
-{
-	addr &= 0xFFF;
-	return SPU_core->ReadLong(addr);
-}
-
-uint16_t SPU_struct::ReadWord(uint32_t addr)
-{
-	return this->ReadByte(addr) | (this->ReadByte(addr + 1) << 8);
-}
-
-uint32_t SPU_struct::ReadLong(uint32_t addr)
-{
-	return this->ReadByte(addr) | (this->ReadByte(addr + 1) << 8) | (this->ReadByte(addr + 2) << 16) | (ReadByte(addr + 3) << 24);
-}
-
-uint8_t SPU_struct::ReadByte(uint32_t addr)
-{
-	switch (addr)
-	{
-		// SOUNDCNT
-		case 0x500:
-			return this->regs.mastervol;
-		case 0x501:
-			return this->regs.ctl_left | (this->regs.ctl_right << 2) | (this->regs.ctl_ch1bypass << 4) | (this->regs.ctl_ch3bypass << 5) | (this->regs.masteren << 7);
-		case 0x502:
-		case 0x503:
-			return 0;
-
-		// SOUNDBIAS
-		case 0x504:
-			return this->regs.soundbias & 0xFF;
-		case 0x505:
-			return (this->regs.soundbias >> 8) & 0xFF;
-		case 0x506:
-		case 0x507:
-			return 0;
-
-		// SNDCAP0CNT/SNDCAP1CNT
-		case 0x508:
-		case 0x509:
-		{
-			uint32_t which = addr - 0x508;
-			return this->regs.cap[which].add | (this->regs.cap[which].source << 1) | (this->regs.cap[which].oneshot << 2) | (this->regs.cap[which].bits8 << 3)
-				//| (regs.cap[which].active<<7); //? which is right? need test
-				| (this->regs.cap[which].runtime.running << 7);
-		}
-
-		// SNDCAP0DAD
-		case 0x510:
-			return GETBYTE(0, this->regs.cap[0].dad);
-		case 0x511:
-			return GETBYTE(1, this->regs.cap[0].dad);
-		case 0x512:
-			return GETBYTE(2, this->regs.cap[0].dad);
-		case 0x513:
-			return GETBYTE(3, this->regs.cap[0].dad);
-
-		// SNDCAP0LEN
-		case 0x514:
-			return GETBYTE(0, this->regs.cap[0].len);
-		case 0x515:
-			return GETBYTE(1, this->regs.cap[0].len);
-		case 0x516:
-		case 0x517:
-			return 0; //not used
-
-		// SNDCAP1DAD
-		case 0x518:
-			return GETBYTE(0, this->regs.cap[1].dad);
-		case 0x519:
-			return GETBYTE(1, this->regs.cap[1].dad);
-		case 0x51A:
-			return GETBYTE(2, this->regs.cap[1].dad);
-		case 0x51B:
-			return GETBYTE(3, this->regs.cap[1].dad);
-
-		// SNDCAP1LEN
-		case 0x51C:
-			return GETBYTE(0, this->regs.cap[1].len);
-		case 0x51D:
-			return GETBYTE(1, this->regs.cap[1].len);
-		case 0x51E:
-		case 0x51F:
-			return 0; //not used
-
-		default:
-		{
-			// individual channel regs
-
-			uint32_t chan_num = (addr >> 4) & 0xF;
-			if (chan_num > 0xF)
-				return 0;
-			channel_struct &thischan = this->channels[chan_num];
-
-			switch (addr & 0xF)
-			{
-				case 0x0:
-					return thischan.vol;
-				case 0x1:
-				{
-					uint8_t ret = thischan.datashift;
-					if (ret == 4)
-						ret = 3;
-					ret |= thischan.hold << 7;
-					return ret;
-				}
-				case 0x2:
-					return thischan.pan;
-				case 0x3:
-					return thischan.waveduty | (thischan.repeat << 3) | (thischan.format << 5) | (thischan.status == CHANSTAT_PLAY ? 0x80 : 0);
-				case 0x4:
-					return 0; //return GETBYTE(0, thischan.addr); //not readable
-				case 0x5:
-					return 0; //return GETBYTE(1, thischan.addr); //not readable
-				case 0x6:
-					return 0; //return GETBYTE(2, thischan.addr); //not readable
-				case 0x7:
-					return 0; //return GETBYTE(3, thischan.addr); //not readable
-				case 0x8:
-					return GETBYTE(0, thischan.timer);
-				case 0x9:
-					return GETBYTE(1, thischan.timer);
-				case 0xA:
-					return GETBYTE(0, thischan.loopstart);
-				case 0xB:
-					return GETBYTE(1, thischan.loopstart);
-				case 0xC:
-					return 0; //return GETBYTE(0, thischan.length); //not readable
-				case 0xD:
-					return 0; //return GETBYTE(1, thischan.length); //not readable
-				case 0xE:
-					return 0; //return GETBYTE(2, thischan.length); //not readable
-				case 0xF:
-					return 0; //return GETBYTE(3, thischan.length); //not readable
-				default:
-					return 0; //impossible
-			} // switch on individual channel regs
-		} // default case
-	} // switch on address
+u8 SPU_struct::ReadByte(u32 addr)
+{
+  //individual channel regs
+  if ((addr & 0x0F00) == 0x0400)
+  {
+    u32 chan_num = (addr >> 4) & 0xF;
+    const channel_struct& thischan = channels[chan_num];
+
+    switch (addr & 0xF)
+    {
+      case 0x0: return thischan.vol;
+      case 0x1: return (thischan.volumeDiv | (thischan.hold << 7));
+      case 0x2: return thischan.pan;
+      case 0x3: return (	thischan.waveduty
+                    | (thischan.repeat << 3)
+                    | (thischan.format << 5)
+                    | ((thischan.status == CHANSTAT_PLAY)?0x80:0)
+                    );
+      case 0x8: return thischan.timer >> 0;
+      case 0x9: return thischan.timer >> 8;
+      case 0xA: return thischan.loopstart >> 0;
+      case 0xB: return thischan.loopstart >> 8;
+    }
+    return 0;
+  }
+
+  switch(addr)
+  {
+    //SOUNDCNT
+    case 0x500: return regs.mastervol;
+    case 0x501: return (regs.ctl_left
+                    | (regs.ctl_right << 2)
+                    | (regs.ctl_ch1bypass << 4)
+                    | (regs.ctl_ch3bypass << 5)
+                    | (regs.masteren << 7)
+                    );
+
+                //SOUNDBIAS
+    case 0x504: return regs.soundbias >> 0;
+    case 0x505: return regs.soundbias >> 8;
+
+                //SNDCAP0CNT/SNDCAP1CNT
+    case 0x508:
+    case 0x509:
+                {
+                  u32 which = (addr - 0x508);
+                  return regs.cap[which].add
+                    | (regs.cap[which].source << 1)
+                    | (regs.cap[which].oneshot << 2)
+                    | (regs.cap[which].bits8 << 3)
+                    | (regs.cap[which].runtime.running << 7);
+                }
+
+                //SNDCAP0DAD
+    case 0x510: return regs.cap[0].dad >> 0;
+    case 0x511: return regs.cap[0].dad >> 8;
+    case 0x512: return regs.cap[0].dad >> 16;
+    case 0x513: return regs.cap[0].dad >> 24;
+
+                //SNDCAP0LEN
+    case 0x514: return regs.cap[0].len >> 0;
+    case 0x515: return regs.cap[0].len >> 8;
+
+                //SNDCAP1DAD
+    case 0x518: return regs.cap[1].dad >> 0;
+    case 0x519: return regs.cap[1].dad >> 8;
+    case 0x51A: return regs.cap[1].dad >> 16;
+    case 0x51B: return regs.cap[1].dad >> 24;
+
+                //SNDCAP1LEN
+    case 0x51C: return regs.cap[1].len >> 0;
+    case 0x51D: return regs.cap[1].len >> 8;
+  } //switch on address
+
+  return 0;
+}
+
+u16 SPU_struct::ReadWord(u32 addr)
+{
+  //individual channel regs
+  if ((addr & 0x0F00) == 0x0400)
+  {
+    u32 chan_num = (addr >> 4) & 0xF;
+    const channel_struct& thischan = channels[chan_num];
+
+    switch (addr & 0xF)
+    {
+      case 0x0: return	(thischan.vol
+                    | (thischan.volumeDiv << 8)
+                    | (thischan.hold << 15)
+                    );
+      case 0x2: return	(thischan.pan
+                    | (thischan.waveduty << 8)
+                    | (thischan.repeat << 11)
+                    | (thischan.format << 13)
+                    | ((thischan.status == CHANSTAT_PLAY)?(1 << 15):0)
+                    );
+      case 0x8: return thischan.timer;
+      case 0xA: return thischan.loopstart;
+    } //switch on individual channel regs
+    return 0;
+  }
+
+  switch(addr)
+  {
+    //SOUNDCNT
+    case 0x500: return	(regs.mastervol
+                    | (regs.ctl_left << 8)
+                    | (regs.ctl_right << 10)
+                    | (regs.ctl_ch1bypass << 12)
+                    | (regs.ctl_ch3bypass << 13)
+                    | (regs.masteren << 15)
+                    );
+
+                //SOUNDBIAS
+    case 0x504: return regs.soundbias;
+
+                //SNDCAP0CNT/SNDCAP1CNT
+    case 0x508:
+                {
+                  u8 val0 =	regs.cap[0].add
+                    | (regs.cap[0].source << 1)
+                    | (regs.cap[0].oneshot << 2)
+                    | (regs.cap[0].bits8 << 3)
+                    | (regs.cap[0].runtime.running << 7);
+                  u8 val1 =	regs.cap[1].add
+                    | (regs.cap[1].source << 1)
+                    | (regs.cap[1].oneshot << 2)
+                    | (regs.cap[1].bits8 << 3)
+                    | (regs.cap[1].runtime.running << 7);
+                  return (u16)(val0 | (val1 << 8));
+                }
+
+                //SNDCAP0DAD
+    case 0x510: return regs.cap[0].dad >> 0;
+    case 0x512: return regs.cap[0].dad >> 16;
+
+                //SNDCAP0LEN
+    case 0x514: return regs.cap[0].len;
+
+                //SNDCAP1DAD
+    case 0x518: return regs.cap[1].dad >> 0;
+    case 0x51A: return regs.cap[1].dad >> 16;
+
+                //SNDCAP1LEN
+    case 0x51C: return regs.cap[1].len;
+  } //switch on address
+
+  return 0;
+}
+
+u32 SPU_struct::ReadLong(u32 addr)
+{
+  //individual channel regs
+  if ((addr & 0x0F00) == 0x0400)
+  {
+    u32 chan_num = (addr >> 4) & 0xF;
+    channel_struct &thischan=channels[chan_num];
+
+    switch (addr & 0xF)
+    {
+      case 0x0: return	(thischan.vol
+                    | (thischan.volumeDiv << 8)
+                    | (thischan.hold << 15)
+                    | (thischan.pan << 16)
+                    | (thischan.waveduty << 24)
+                    | (thischan.repeat << 27)
+                    | (thischan.format << 29)
+                    | ((thischan.status == CHANSTAT_PLAY)?(1 << 31):0)
+                    );
+      case 0x8: return (thischan.timer | (thischan.loopstart << 16));
+    } //switch on individual channel regs
+    return 0;
+  }
+
+  switch(addr)
+  {
+    //SOUNDCNT
+    case 0x500: return	(regs.mastervol
+                    | (regs.ctl_left << 8)
+                    | (regs.ctl_right << 10)
+                    | (regs.ctl_ch1bypass << 12)
+                    | (regs.ctl_ch3bypass << 13)
+                    | (regs.masteren << 15)
+                    );
+
+                //SOUNDBIAS
+    case 0x504: return (u32)regs.soundbias;
+
+                //SNDCAP0CNT/SNDCAP1CNT
+    case 0x508:
+                {
+                  u8 val0 =	regs.cap[0].add
+                    | (regs.cap[0].source << 1)
+                    | (regs.cap[0].oneshot << 2)
+                    | (regs.cap[0].bits8 << 3)
+                    | (regs.cap[0].runtime.running << 7);
+                  u8 val1 =	regs.cap[1].add
+                    | (regs.cap[1].source << 1)
+                    | (regs.cap[1].oneshot << 2)
+                    | (regs.cap[1].bits8 << 3)
+                    | (regs.cap[1].runtime.running << 7);
+                  return (u32)(val0 | (val1 << 8));
+                }
+
+                //SNDCAP0DAD
+    case 0x510: return regs.cap[0].dad;
+
+                //SNDCAP0LEN
+    case 0x514: return (u32)regs.cap[0].len;
+
+                //SNDCAP1DAD
+    case 0x518: return regs.cap[1].dad;
+
+                //SNDCAP1LEN
+    case 0x51C: return (u32)regs.cap[1].len;
+  } //switch on address
+
+  return 0;
 }
 
 SPUFifo::SPUFifo()
 {
-	this->reset();
+  reset();
 }
 
 void SPUFifo::reset()
 {
-	this->head = this->tail = this->size = 0;
-}
-
-void SPUFifo::enqueue(int16_t val)
-{
-	if (this->size == 16)
-		return;
-	this->buffer[this->tail] = val;
-	++this->tail;
-	this->tail &= 15;
-	++this->size;
-}
-
-int16_t SPUFifo::dequeue()
-{
-	if (!this->size)
-		return 0;
-	++this->head;
-	this->head &= 15;
-	int16_t ret = this->buffer[this->head];
-	--this->size;
-	return ret;
+  head = tail = size = 0;
+}
+
+void SPUFifo::enqueue(s16 val)
+{
+  if(size==16) return;
+  buffer[tail] = val;
+  tail++;
+  tail &= 15;
+  size++;
+}
+
+s16 SPUFifo::dequeue()
+{
+  if(size==0) return 0;
+  head++;
+  head &= 15;
+  s16 ret = buffer[head];
+  size--;
+  return ret;
 }
 
 void SPU_struct::ProbeCapture(int which)
 {
-	// VERY UNTESTED -- HOW MUCH OF THIS RESETS, AND WHEN?
-
-	if (!this->regs.cap[which].active)
-	{
-		this->regs.cap[which].runtime.running = 0;
-		return;
-	}
-
-	REGS::CAP &cap = this->regs.cap[which];
-	cap.runtime.running = 1;
-	cap.runtime.curdad = cap.dad;
-	uint32_t len = cap.len;
-	if (!len)
-		len = 1;
-	cap.runtime.maxdad = cap.dad + len * 4;
-	cap.runtime.sampcnt = 0;
-	cap.runtime.fifo.reset();
-}
-
-void SPU_struct::WriteByte(uint32_t addr, uint8_t val)
-{
-	switch (addr)
-	{
-		// SOUNDCNT
-		case 0x500:
-			this->regs.mastervol = val & 0x7F;
-			break;
-		case 0x501:
-			this->regs.ctl_left = val & 3;
-			this->regs.ctl_right = (val >> 2) & 3;
-			this->regs.ctl_ch1bypass = (val >> 4) & 1;
-			this->regs.ctl_ch3bypass = (val >> 5) & 1;
-			this->regs.masteren = (val >> 7) & 1;
-			for (int i = 0; i < 16; ++i)
-				this->KeyProbe(i);
-			break;
-		case 0x502:
-		case 0x503:
-			break; // not used
-
-		// SOUNDBIAS
-		case 0x504:
-			SETBYTE(0, this->regs.soundbias, val);
-			break;
-		case 0x505:
-			SETBYTE(1, this->regs.soundbias, val & 3);
-			break;
-		case 0x506:
-		case 0x507:
-			break; // these dont answer anyway
-
-		// SNDCAP0CNT/SNDCAP1CNT
-		case 0x508:
-		case 0x509:
-		{
-			uint32_t which = addr - 0x508;
-			this->regs.cap[which].add = static_cast<uint8_t>(BIT0(val));
-			this->regs.cap[which].source = static_cast<uint8_t>(BIT1(val));
-			this->regs.cap[which].oneshot = static_cast<uint8_t>(BIT2(val));
-			this->regs.cap[which].bits8 = static_cast<uint8_t>(BIT3(val));
-			this->regs.cap[which].active = static_cast<uint8_t>(BIT7(val));
-			this->ProbeCapture(which);
-			break;
-		}
-
-		// SNDCAP0DAD
-		case 0x510:
-			SETBYTE(0, this->regs.cap[0].dad, val);
-			break;
-		case 0x511:
-			SETBYTE(1, this->regs.cap[0].dad, val);
-			break;
-		case 0x512:
-			SETBYTE(2, this->regs.cap[0].dad, val);
-			break;
-		case 0x513:
-			SETBYTE(3, this->regs.cap[0].dad, val & 7);
-			break;
-
-		// SNDCAP0LEN
-		case 0x514:
-			SETBYTE(0, this->regs.cap[0].len, val);
-			break;
-		case 0x515:
-			SETBYTE(1, this->regs.cap[0].len, val);
-			break;
-		case 0x516:
-		case 0x517:
-			break; // not used
-
-		// SNDCAP1DAD
-		case 0x518:
-			SETBYTE(0, this->regs.cap[1].dad, val);
-			break;
-		case 0x519:
-			SETBYTE(1, this->regs.cap[1].dad, val);
-			break;
-		case 0x51A:
-			SETBYTE(2, this->regs.cap[1].dad, val);
-			break;
-		case 0x51B:
-			SETBYTE(3, this->regs.cap[1].dad, val & 7);
-			break;
-
-		// SNDCAP1LEN
-		case 0x51C:
-			SETBYTE(0, this->regs.cap[1].len, val);
-			break;
-		case 0x51D:
-			SETBYTE(1, this->regs.cap[1].len, val);
-			break;
-		case 0x51E:
-		case 0x51F:
-			break; // not used
-
-		default:
-		{
-			// individual channel regs
-
-			uint32_t chan_num = (addr >> 4) & 0xF;
-			if (chan_num>0xF)
-				break;
-			channel_struct &thischan = this->channels[chan_num];
-
-			switch (addr & 0xF)
-			{
-				case 0x0:
-					thischan.vol = val & 0x7F;
-					break;
-				case 0x1:
-					thischan.datashift = val & 0x3;
-					if (thischan.datashift == 3)
-						thischan.datashift = 4;
-					thischan.hold = (val >> 7) & 0x1;
-					break;
-				case 0x2:
-					thischan.pan = val & 0x7F;
-					break;
-				case 0x3:
-					thischan.waveduty = val & 0x7;
-					thischan.repeat = (val >> 3) & 0x3;
-					thischan.format = (val >> 5) & 0x3;
-					thischan.keyon = static_cast<uint8_t>(BIT7(val));
-					this->KeyProbe(chan_num);
-					break;
-				case 0x4:
-					SETBYTE(0, thischan.addr, val);
-					break;
-				case 0x5:
-					SETBYTE(1, thischan.addr, val);
-					break;
-				case 0x6:
-					SETBYTE(2, thischan.addr, val);
-					break;
-				case 0x7:
-					SETBYTE(3, thischan.addr, val & 0x7);
-					break; // only 27 bits of this register are used
-				case 0x8:
-					SETBYTE(0, thischan.timer, val);
-					adjust_channel_timer(&thischan);
-					break;
-				case 0x9:
-					SETBYTE(1, thischan.timer, val);
-					adjust_channel_timer(&thischan);
-					break;
-				case 0xA:
-					SETBYTE(0, thischan.loopstart, val);
-					break;
-				case 0xB:
-					SETBYTE(1, thischan.loopstart, val);
-					break;
-				case 0xC:
-					SETBYTE(0, thischan.length, val);
-					break;
-				case 0xD:
-					SETBYTE(1, thischan.length, val);
-					break;
-				case 0xE:
-					SETBYTE(2, thischan.length, val & 0x3F);
-					break; // only 22 bits of this register are used
-				case 0xF:
-					SETBYTE(3, thischan.length, 0);
-					break;
-			} // switch on individual channel regs
-		} // default case
-	} // switch on address
-}
-
-void SPU_WriteByte(uint32_t addr, uint8_t val)
-{
-	//printf("%08X: chan:%02X reg:%02X val:%02X\n",addr,(addr>>4)&0xF,addr&0xF,val);
-	addr &= 0xFFF;
-
-	SPU_core->WriteByte(addr, val);
-	if (SPU_user)
-		SPU_user->WriteByte(addr, val);
+  //VERY UNTESTED -- HOW MUCH OF THIS RESETS, AND WHEN?
+
+  if(!regs.cap[which].active)
+  {
+    regs.cap[which].runtime.running = 0;
+    return;
+  }
+
+  REGS::CAP &cap = regs.cap[which];
+  cap.runtime.running = 1;
+  cap.runtime.curdad = cap.dad;
+  u32 len = cap.len;
+  if(len==0) len=1;
+  cap.runtime.maxdad = cap.dad + len*4;
+  cap.runtime.sampcnt = 0;
+  cap.runtime.fifo.reset();
+}
+
+void SPU_struct::WriteByte(u32 addr, u8 val)
+{
+  //individual channel regs
+  if ((addr & 0x0F00) == 0x0400)
+  {
+    u8 chan_num = (addr >> 4) & 0xF;
+    channel_struct &thischan = channels[chan_num];
+
+    switch (addr & 0x000F)
+    {
+      case 0x0: thischan.vol = (val & 0x7F); break;
+      case 0x1:
+                thischan.volumeDiv = (val & 0x03);
+                thischan.hold = (val >> 7) & 0x01;
+                break;
+      case 0x2: thischan.pan = (val & 0x7F); break;
+      case 0x3:
+                thischan.waveduty = (val & 0x07);
+                thischan.repeat = (val >> 3) & 0x03;
+                thischan.format = (val >> 5) & 0x03;
+                thischan.keyon = (val >> 7) & 0x01;
+                KeyProbe(chan_num);
+                break;
+      case 0x4: thischan.addr &= 0xFFFFFF00; thischan.addr |= (val & 0xFC); break;
+      case 0x5: thischan.addr &= 0xFFFF00FF; thischan.addr |= (val << 8); break;
+      case 0x6: thischan.addr &= 0xFF00FFFF; thischan.addr |= (val << 16); break;
+      case 0x7: thischan.addr &= 0x00FFFFFF; thischan.addr |= ((val&7) << 24); break; //only 27 bits of this register are used
+      case 0x8: thischan.timer &= 0xFF00; thischan.timer |= (val << 0); adjust_channel_timer(&thischan); break;
+      case 0x9: thischan.timer &= 0x00FF; thischan.timer |= (val << 8); adjust_channel_timer(&thischan); break;
+
+      case 0xA: thischan.loopstart &= 0xFF00; thischan.loopstart |= (val << 0); break;
+      case 0xB: thischan.loopstart &= 0x00FF; thischan.loopstart |= (val << 8); break;
+      case 0xC: thischan.length &= 0xFFFFFF00; thischan.length |= (val << 0); break;
+      case 0xD: thischan.length &= 0xFFFF00FF; thischan.length |= (val << 8); break;
+      case 0xE: thischan.length &= 0xFF00FFFF; thischan.length |= ((val & 0x3F) << 16); //only 22 bits of this register are used
+      case 0xF: break;
+
+    } //switch on individual channel regs
+
+    return;
+  }
+
+  switch(addr)
+  {
+    //SOUNDCNT
+    case 0x500: regs.mastervol = (val & 0x7F); break;
+    case 0x501:
+                regs.ctl_left  = (val >> 0) & 3;
+                regs.ctl_right = (val >> 2) & 3;
+                regs.ctl_ch1bypass = (val >> 4) & 1;
+                regs.ctl_ch3bypass = (val >> 5) & 1;
+                regs.masteren = (val >> 7) & 1;
+                break;
+
+                //SOUNDBIAS
+    case 0x504: regs.soundbias &= 0xFF00; regs.soundbias |= (val << 0); break;
+    case 0x505: regs.soundbias &= 0x00FF; regs.soundbias |= ((val&3) << 8); break;
+
+                //SNDCAP0CNT/SNDCAP1CNT
+    case 0x508:
+    case 0x509:
+                {
+                  u32 which = (addr - 0x508);
+                  regs.cap[which].add = BIT0(val);
+                  regs.cap[which].source = BIT1(val);
+                  regs.cap[which].oneshot = BIT2(val);
+                  regs.cap[which].bits8 = BIT3(val);
+                  regs.cap[which].active = BIT7(val);
+                  ProbeCapture(which);
+                  break;
+                }
+
+                //SNDCAP0DAD
+    case 0x510: regs.cap[0].dad &= 0xFFFFFF00; regs.cap[0].dad |= (val & 0xFC); break;
+    case 0x511: regs.cap[0].dad &= 0xFFFF00FF; regs.cap[0].dad |= (val << 8); break;
+    case 0x512: regs.cap[0].dad &= 0xFF00FFFF; regs.cap[0].dad |= (val << 16); break;
+    case 0x513: regs.cap[0].dad &= 0x00FFFFFF; regs.cap[0].dad |= ((val&7) << 24); break;
+
+                //SNDCAP0LEN
+    case 0x514: regs.cap[0].len &= 0xFF00; regs.cap[0].len |= (val << 0); break;
+    case 0x515: regs.cap[0].len &= 0x00FF; regs.cap[0].len |= (val << 8); break;
+
+                //SNDCAP1DAD
+    case 0x518: regs.cap[1].dad &= 0xFFFFFF00; regs.cap[1].dad |= (val & 0xFC); break;
+    case 0x519: regs.cap[1].dad &= 0xFFFF00FF; regs.cap[1].dad |= (val << 8); break;
+    case 0x51A: regs.cap[1].dad &= 0xFF00FFFF; regs.cap[1].dad |= (val << 16); break;
+    case 0x51B: regs.cap[1].dad &= 0xFF000000; regs.cap[1].dad |= ((val&7) << 24); break;
+
+                //SNDCAP1LEN
+    case 0x51C: regs.cap[1].len &= 0xFF00; regs.cap[1].len |= (val << 0); break;
+    case 0x51D: regs.cap[1].len &= 0x00FF; regs.cap[1].len |= (val << 8); break;
+  } //switch on address
+}
+
+void SPU_struct::WriteWord(u32 addr, u16 val)
+{
+  //individual channel regs
+  if ((addr & 0x0F00) == 0x0400)
+  {
+    u32 chan_num = (addr >> 4) & 0xF;
+    channel_struct &thischan=channels[chan_num];
+
+    switch (addr & 0xF)
+    {
+      case 0x0:
+        thischan.vol = (val & 0x7F);
+        thischan.volumeDiv = (val >> 8) & 0x3;
+        thischan.hold = (val >> 15) & 0x1;
+        break;
+      case 0x2:
+        thischan.pan = (val & 0x7F);
+        thischan.waveduty = (val >> 8) & 0x7;
+        thischan.repeat = (val >> 11) & 0x3;
+        thischan.format = (val >> 13) & 0x3;
+        thischan.keyon = (val >> 15) & 0x1;
+        KeyProbe(chan_num);
+        break;
+      case 0x4: thischan.addr &= 0xFFFF0000; thischan.addr |= (val & 0xFFFC); break;
+      case 0x6: thischan.addr &= 0x0000FFFF; thischan.addr |= ((val & 0x07FF) << 16); break;
+      case 0x8: thischan.timer = val; adjust_channel_timer(&thischan); break;
+      case 0xA: thischan.loopstart = val; break;
+      case 0xC: thischan.length &= 0xFFFF0000; thischan.length |= (val << 0); break;
+      case 0xE: thischan.length &= 0x0000FFFF; thischan.length |= ((val & 0x003F) << 16); break;
+    } //switch on individual channel regs
+    return;
+  }
+
+  switch (addr)
+  {
+    //SOUNDCNT
+    case 0x500:
+      regs.mastervol = (val & 0x7F);
+      regs.ctl_left  = (val >> 8) & 0x03;
+      regs.ctl_right = (val >> 10) & 0x03;
+      regs.ctl_ch1bypass = (val >> 12) & 0x01;
+      regs.ctl_ch3bypass = (val >> 13) & 0x01;
+      regs.masteren = (val >> 15) & 0x01;
+      for(u8 i=0; i<16; i++)
+        KeyProbe(i);
+      break;
+
+      //SOUNDBIAS
+    case 0x504: regs.soundbias = (val & 0x3FF); break;
+
+                //SNDCAP0CNT/SNDCAP1CNT
+    case 0x508:
+                {
+                  regs.cap[0].add = BIT0(val);
+                  regs.cap[0].source = BIT1(val);
+                  regs.cap[0].oneshot = BIT2(val);
+                  regs.cap[0].bits8 = BIT3(val);
+                  regs.cap[0].active = BIT7(val);
+                  ProbeCapture(0);
+
+                  regs.cap[1].add = BIT8(val);
+                  regs.cap[1].source = BIT9(val);
+                  regs.cap[1].oneshot = BIT10(val);
+                  regs.cap[1].bits8 = BIT11(val);
+                  regs.cap[1].active = BIT15(val);
+                  ProbeCapture(1);
+                  break;
+                }
+
+                //SNDCAP0DAD
+    case 0x510: regs.cap[0].dad &= 0xFFFF0000; regs.cap[0].dad |= (val & 0xFFFC); break;
+    case 0x512: regs.cap[0].dad &= 0x0000FFFF; regs.cap[0].dad |= ((val & 0x07FF) << 16); break;
+
+                //SNDCAP0LEN
+    case 0x514: regs.cap[0].len = val; break;
+
+                //SNDCAP1DAD
+    case 0x518: regs.cap[1].dad &= 0xFFFF0000; regs.cap[1].dad |= (val & 0xFFFC); break;
+    case 0x51A: regs.cap[1].dad &= 0x0000FFFF; regs.cap[1].dad |= ((val & 0x07FF) << 16); break;
+
+                //SNDCAP1LEN
+    case 0x51C: regs.cap[1].len = val; break;
+  } //switch on address
+}
+
+void SPU_struct::WriteLong(u32 addr, u32 val)
+{
+  //individual channel regs
+  if ((addr & 0x0F00) == 0x0400)
+  {
+    u32 chan_num = (addr >> 4) & 0xF;
+    channel_struct &thischan=channels[chan_num];
+
+    switch (addr & 0xF)
+    {
+      case 0x0:
+        thischan.vol = val & 0x7F;
+        thischan.volumeDiv = (val >> 8) & 0x3;
+        thischan.hold = (val >> 15) & 0x1;
+        thischan.pan = (val >> 16) & 0x7F;
+        thischan.waveduty = (val >> 24) & 0x7;
+        thischan.repeat = (val >> 27) & 0x3;
+        thischan.format = (val >> 29) & 0x3;
+        thischan.keyon = (val >> 31) & 0x1;
+        KeyProbe(chan_num);
+        break;
+
+      case 0x4: thischan.addr = (val & 0x07FFFFFC); break;
+      case 0x8:
+                thischan.timer = (val & 0xFFFF);
+                thischan.loopstart = ((val >> 16) & 0xFFFF);
+                adjust_channel_timer(&thischan);
+                break;
+
+      case 0xC: thischan.length = (val & 0x003FFFFF); break; //only 22 bits of this register are used
+    } //switch on individual channel regs
+    return;
+  }
+
+  switch(addr)
+  {
+    //SOUNDCNT
+    case 0x500:
+      regs.mastervol = (val & 0x7F);
+      regs.ctl_left  = ((val >> 8) & 3);
+      regs.ctl_right = ((val>>10) & 3);
+      regs.ctl_ch1bypass = ((val >> 12) & 1);
+      regs.ctl_ch3bypass = ((val >> 13) & 1);
+      regs.masteren = ((val >> 15) & 1);
+      for(u8 i=0; i<16; i++)
+        KeyProbe(i);
+      break;
+
+      //SOUNDBIAS
+    case 0x504: regs.soundbias = (val & 0x3FF);
+
+                //SNDCAP0CNT/SNDCAP1CNT
+    case 0x508:
+                regs.cap[0].add = BIT0(val);
+                regs.cap[0].source = BIT1(val);
+                regs.cap[0].oneshot = BIT2(val);
+                regs.cap[0].bits8 = BIT3(val);
+                regs.cap[0].active = BIT7(val);
+                ProbeCapture(0);
+
+                regs.cap[1].add = BIT8(val);
+                regs.cap[1].source = BIT9(val);
+                regs.cap[1].oneshot = BIT10(val);
+                regs.cap[1].bits8 = BIT11(val);
+                regs.cap[1].active = BIT15(val);
+                ProbeCapture(1);
+                break;
+
+                //SNDCAP0DAD
+    case 0x510: regs.cap[0].dad = (val & 0x07FFFFFC); break;
+
+                //SNDCAP0LEN
+    case 0x514: regs.cap[0].len = (val & 0xFFFF); break;
+
+                //SNDCAP1DAD
+    case 0x518: regs.cap[1].dad = (val & 0x07FFFFFC); break;
+
+                //SNDCAP1LEN
+    case 0x51C: regs.cap[1].len = (val & 0xFFFF); break;
+  } //switch on address
 }
 
 //////////////////////////////////////////////////////////////////////////////
 
-void SPU_struct::WriteWord(uint32_t addr, uint16_t val)
-{
-	this->WriteByte(addr, val & 0xFF);
-	this->WriteByte(addr + 1, (val >> 8) & 0xFF);
-}
-
-void SPU_WriteWord(uint32_t addr, uint16_t val)
-{
-	//printf("%08X: chan:%02X reg:%02X val:%04X\n",addr,(addr>>4)&0xF,addr&0xF,val);
-	addr &= 0xFFF;
-
-	SPU_core->WriteWord(addr, val);
-	if (SPU_user)
-		SPU_user->WriteWord(addr, val);
+static FORCEINLINE void FetchPSGData(channel_struct *chan, s32 *data)
+{
+  if (chan->sampcnt < 0)
+  {
+    *data = 0;
+    return;
+  }
+
+  if(chan->num < 8)
+  {
+    *data = 0;
+  }
+  else if(chan->num < 14)
+  {
+    *data = (s32)wavedutytbl[chan->waveduty][(sputrunc(chan->sampcnt)) & 0x7];
+  }
+  else
+  {
+    if(chan->lastsampcnt == sputrunc(chan->sampcnt))
+    {
+      *data = (s32)chan->psgnoise_last;
+      return;
+    }
+
+    u32 max = sputrunc(chan->sampcnt);
+    for(u32 i = chan->lastsampcnt; i < max; i++)
+    {
+      if(chan->x & 0x1)
+      {
+        chan->x = (chan->x >> 1) ^ 0x6000;
+        chan->psgnoise_last = -0x7FFF;
+      }
+      else
+      {
+        chan->x >>= 1;
+        chan->psgnoise_last = 0x7FFF;
+      }
+    }
+
+    chan->lastsampcnt = sputrunc(chan->sampcnt);
+
+    *data = (s32)chan->psgnoise_last;
+  }
 }
 
 //////////////////////////////////////////////////////////////////////////////
 
-void SPU_struct::WriteLong(uint32_t addr, uint32_t val)
-{
-	this->WriteByte(addr,val & 0xFF);
-	this->WriteByte(addr + 1,(val >> 8) & 0xFF);
-	this->WriteByte(addr + 2,(val >> 16) & 0xFF);
-	this->WriteByte(addr + 3,(val >> 24) & 0xFF);
-}
-
-void SPU_WriteLong(uint32_t addr, uint32_t val)
-{
-	//printf("%08X: chan:%02X reg:%02X val:%08X\n",addr,(addr>>4)&0xF,addr&0xF,val);
-	addr &= 0xFFF;
-
-	SPU_core->WriteLong(addr, val);
-	if (SPU_user)
-		SPU_user->WriteLong(addr, val);
+static FORCEINLINE void MixL(SPU_struct* SPU, channel_struct *chan, s32 data)
+{
+  data = spumuldiv7(data, chan->vol) >> volume_shift[chan->volumeDiv];
+  SPU->sndbuf[SPU->bufpos<<1] += data;
+}
+
+static FORCEINLINE void MixR(SPU_struct* SPU, channel_struct *chan, s32 data)
+{
+  data = spumuldiv7(data, chan->vol) >> volume_shift[chan->volumeDiv];
+  SPU->sndbuf[(SPU->bufpos<<1)+1] += data;
+}
+
+static FORCEINLINE void MixLR(SPU_struct* SPU, channel_struct *chan, s32 data)
+{
+  data = spumuldiv7(data, chan->vol) >> volume_shift[chan->volumeDiv];
+  SPU->sndbuf[SPU->bufpos<<1] += spumuldiv7(data, 127 - chan->pan);
+  SPU->sndbuf[(SPU->bufpos<<1)+1] += spumuldiv7(data, chan->pan);
 }
 
 //////////////////////////////////////////////////////////////////////////////
 
-static inline int32_t Interpolate(int32_t a, int32_t b, double ratio, SPUInterpolationMode INTERPOLATE_MODE)
-{
-	double sampleA = static_cast<double>(a);
-	double sampleB = static_cast<double>(b);
-	ratio = ratio - u32floor(ratio);
-
-	switch (INTERPOLATE_MODE)
-	{
-		case SPUInterpolation_Cosine:
-			// Cosine Interpolation Formula:
-			// ratio2 = (1 - cos(ratio * M_PI)) / 2
-			// sampleI = sampleA * (1 - ratio2) + sampleB * ratio2
-			return s32floor((cos_lut[static_cast<unsigned>(ratio * COSINE_INTERPOLATION_RESOLUTION)] * (sampleB - sampleA)) + sampleA);
-
-		case SPUInterpolation_Linear:
-			// Linear Interpolation Formula:
-			// sampleI = sampleA * (1 - ratio) + sampleB * ratio
-			return s32floor((ratio * (sampleB - sampleA)) + sampleA);
-
-		default:
-			break;
-	}
-
-	return a;
+template<int FORMAT> static FORCEINLINE void TestForLoop(SPU_struct *SPU, channel_struct *chan)
+{
+  const int shift = (FORMAT == 0 ? 2 : 1);
+
+  chan->sampcnt += chan->sampinc;
+
+  if (chan->sampcnt > chan->double_totlength_shifted)
+  {
+    // Do we loop? Or are we done?
+    if (chan->repeat == 1)
+    {
+      while (chan->sampcnt > chan->double_totlength_shifted) {
+        chan->sampcnt -= chan->double_totlength_shifted - (double)(chan->loopstart << shift);
+      }
+    }
+    else
+    {
+      SPU->KeyOff(chan->num);
+      SPU->bufpos = SPU->buflength;
+    }
+  }
+}
+
+static FORCEINLINE void TestForLoop2(SPU_struct *SPU, channel_struct *chan)
+{
+  // Minimum length (the sum of PNT+LEN) is 4 words (16 bytes),
+  // smaller values (0..3 words) are causing hang-ups
+  // (busy bit remains set infinite, but no sound output occurs).
+  // fix: 7th Dragon (JP) - http://sourceforge.net/p/desmume/bugs/1357/
+  if (chan->totlength < 4) return;
+
+  chan->sampcnt += chan->sampinc;
+
+  if (chan->sampcnt > chan->double_totlength_shifted)
+  {
+    // Do we loop? Or are we done?
+    if (chan->repeat == 1)
+    {
+      double step = (chan->double_totlength_shifted - (double)(chan->loopstart << 3));
+
+      while (chan->sampcnt > chan->double_totlength_shifted) chan->sampcnt -= step;
+
+      if(chan->loop_index == K_ADPCM_LOOPING_RECOVERY_INDEX)
+      {
+        chan->pcm16b = (s16)read16(chan->addr);
+        chan->index = read08(chan->addr+2) & 0x7F;
+        chan->lastsampcnt = 7;
+      }
+      else
+      {
+        chan->pcm16b = chan->loop_pcm16b;
+        chan->index = chan->loop_index;
+        chan->lastsampcnt = (chan->loopstart << 3);
+      }
+    }
+    else
+    {
+      chan->status = CHANSTAT_STOPPED;
+      SPU->KeyOff(chan->num);
+      SPU->bufpos = SPU->buflength;
+    }
+  }
+}
+
+template<int CHANNELS> FORCEINLINE static void SPU_Mix(SPU_struct* SPU, channel_struct *chan, s32 data)
+{
+  switch(CHANNELS)
+  {
+    case 0: MixL(SPU, chan, data); break;
+    case 1: MixLR(SPU, chan, data); break;
+    case 2: MixR(SPU, chan, data); break;
+  }
+  SPU->lastdata = data;
+}
+
+//WORK
+  template<int FORMAT, int CHANNELS>
+FORCEINLINE static void ____SPU_ChanUpdate(SPU_struct* const SPU, channel_struct* const chan)
+{
+  for (; SPU->bufpos < SPU->buflength; SPU->bufpos++)
+  {
+    if(CHANNELS != -1)
+    {
+      s32 data;
+      if (chan->sampcnt < 0) {
+        data = 0;
+      } else if (FORMAT == 3) {
+        FetchPSGData(chan, &data);
+      } else {
+        const SampleData& sample = sampleCache.getSample(chan->addr, chan->loopstart, chan->length, SampleData::Format(FORMAT));
+        data = sample.sampleAt(chan->sampcnt, IInterpolator::allInterpolators[CommonSettings.spuInterpolationMode]);
+      }
+      SPU_Mix<CHANNELS>(SPU, chan, data);
+    }
+
+    switch(FORMAT) {
+      case 0: case 1: TestForLoop<FORMAT>(SPU, chan); break;
+      case 2: TestForLoop2(SPU, chan); break;
+      case 3: chan->sampcnt += chan->sampinc; break;
+    }
+  }
+}
+
+template<int FORMAT>
+FORCEINLINE static void ___SPU_ChanUpdate(const bool actuallyMix, SPU_struct* const SPU, channel_struct* const chan)
+{
+  if(!actuallyMix)
+    ____SPU_ChanUpdate<FORMAT,-1>(SPU,chan);
+  else if (chan->pan == 0)
+    ____SPU_ChanUpdate<FORMAT,0>(SPU,chan);
+  else if (chan->pan == 127)
+    ____SPU_ChanUpdate<FORMAT,2>(SPU,chan);
+  else
+    ____SPU_ChanUpdate<FORMAT,1>(SPU,chan);
+}
+
+FORCEINLINE static void _SPU_ChanUpdate(const bool actuallyMix, SPU_struct* const SPU, channel_struct* const chan)
+{
+  switch(chan->format)
+  {
+    case 0: ___SPU_ChanUpdate<0>(actuallyMix, SPU, chan); break;
+    case 1: ___SPU_ChanUpdate<1>(actuallyMix, SPU, chan); break;
+    case 2: ___SPU_ChanUpdate<2>(actuallyMix, SPU, chan); break;
+    case 3: ___SPU_ChanUpdate<3>(actuallyMix, SPU, chan); break;
+    default: assert(false);
+  }
+}
+
+//ENTERNEW
+static void SPU_MixAudio_Advanced(bool actuallyMix, SPU_struct *SPU, int length)
+{
+  //the advanced spu function correctly handles all sound control mixing options, as well as capture
+  //this code is not entirely optimal, as it relies on sort of manhandling the core mixing functions
+  //in order to get the results it needs.
+
+  //THIS IS MAX HACKS!!!!
+  //AND NEEDS TO BE REWRITTEN ALONG WITH THE DEEPEST PARTS OF THE SPU
+  //ONCE WE KNOW THAT IT WORKS
+
+  //BIAS gets ignored since our spu is still not bit perfect,
+  //and it doesnt matter for purposes of capture
+
+  //-----------DEBUG CODE
+  bool skipcap = false;
+  //-----------------
+
+  s32 samp0[2] = {0,0};
+
+  //believe it or not, we are going to do this one sample at a time.
+  //like i said, it is slower.
+  for (int samp = 0; samp < length; samp++)
+  {
+    SPU->sndbuf[0] = 0;
+    SPU->sndbuf[1] = 0;
+    SPU->buflength = 1;
+
+    s32 capmix[2] = {0,0};
+    s32 mix[2] = {0,0};
+    s32 chanout[16];
+    s32 submix[32];
+    static int tsamp = 0;
+    ++tsamp;
+
+    //generate each channel, and helpfully mix it at the same time
+    for (int i = 0; i < 16; i++)
+    {
+      channel_struct *chan = &SPU->channels[i];
+
+      if (chan->status == CHANSTAT_PLAY)
+      {
+        SPU->bufpos = 0;
+
+        bool bypass = false;
+        if (i==1 && SPU->regs.ctl_ch1bypass) bypass=true;
+        if (i==3 && SPU->regs.ctl_ch3bypass) bypass=true;
+
+
+        //output to mixer unless we are bypassed.
+        //dont output to mixer if the user muted us
+        bool outputToMix = true;
+        if (CommonSettings.spu_muteChannels[i]) outputToMix = false;
+        if (bypass) outputToMix = false;
+        bool outputToCap = outputToMix;
+        if (CommonSettings.spu_captureMuted && !bypass) outputToCap = true;
+
+        //channels 1 and 3 should probably always generate their audio
+        //internally at least, just in case they get used by the spu output
+        bool domix = outputToCap || outputToMix || i==1 || i==3;
+
+        //clear the output buffer since this is where _SPU_ChanUpdate wants to accumulate things
+        SPU->sndbuf[0] = SPU->sndbuf[1] = 0;
+
+        //get channel's next output sample.
+        _SPU_ChanUpdate(domix, SPU, chan);
+        chanout[i] = SPU->lastdata >> volume_shift[chan->volumeDiv];
+
+        //save the panned results
+        submix[i*2] = SPU->sndbuf[0];
+        submix[i*2+1] = SPU->sndbuf[1];
+
+        //send sample to our capture mix
+        if (outputToCap)
+        {
+          capmix[0] += submix[i*2];
+          capmix[1] += submix[i*2+1];
+        }
+
+        //send sample to our main mixer
+        if (outputToMix)
+        {
+          mix[0] += submix[i*2];
+          mix[1] += submix[i*2+1];
+        }
+      }
+      else
+      {
+        chanout[i] = 0;
+        submix[i*2] = 0;
+        submix[i*2+1] = 0;
+      }
+    } //foreach channel
+
+    s32 mixout[2] = {mix[0],mix[1]};
+    s32 capmixout[2] = {capmix[0],capmix[1]};
+    s32 sndout[2];
+    s32 capout[2];
+
+    //create SPU output
+    switch (SPU->regs.ctl_left)
+    {
+      case SPU_struct::REGS::LOM_LEFT_MIXER: sndout[0] = mixout[0]; break;
+      case SPU_struct::REGS::LOM_CH1: sndout[0] = submix[1*2+0]; break;
+      case SPU_struct::REGS::LOM_CH3: sndout[0] = submix[3*2+0]; break;
+      case SPU_struct::REGS::LOM_CH1_PLUS_CH3: sndout[0] = submix[1*2+0] + submix[3*2+0]; break;
+    }
+    switch (SPU->regs.ctl_right)
+    {
+      case SPU_struct::REGS::ROM_RIGHT_MIXER: sndout[1] = mixout[1]; break;
+      case SPU_struct::REGS::ROM_CH1: sndout[1] = submix[1*2+1]; break;
+      case SPU_struct::REGS::ROM_CH3: sndout[1] = submix[3*2+1]; break;
+      case SPU_struct::REGS::ROM_CH1_PLUS_CH3: sndout[1] = submix[1*2+1] + submix[3*2+1]; break;
+    }
+
+
+    //generate capture output ("capture bugs" from gbatek are not emulated)
+    if (SPU->regs.cap[0].source == 0)
+      capout[0] = capmixout[0]; //cap0 = L-mix
+    else if (SPU->regs.cap[0].add)
+      capout[0] = chanout[0] + chanout[1]; //cap0 = ch0+ch1
+    else capout[0] = chanout[0]; //cap0 = ch0
+
+    if (SPU->regs.cap[1].source == 0)
+      capout[1] = capmixout[1]; //cap1 = R-mix
+    else if (SPU->regs.cap[1].add)
+      capout[1] = chanout[2] + chanout[3]; //cap1 = ch2+ch3
+    else capout[1] = chanout[2]; //cap1 = ch2
+
+    capout[0] = MinMax(capout[0],-0x8000,0x7FFF);
+    capout[1] = MinMax(capout[1],-0x8000,0x7FFF);
+
+    //write the output sample where it is supposed to go
+    if (samp == 0)
+    {
+      samp0[0] = sndout[0];
+      samp0[1] = sndout[1];
+    }
+    else
+    {
+      SPU->sndbuf[samp*2+0] = sndout[0];
+      SPU->sndbuf[samp*2+1] = sndout[1];
+    }
+
+    for (int capchan = 0; capchan < 2; capchan++)
+    {
+      if (SPU->regs.cap[capchan].runtime.running)
+      {
+        SPU_struct::REGS::CAP& cap = SPU->regs.cap[capchan];
+        u32 last = sputrunc(cap.runtime.sampcnt);
+        cap.runtime.sampcnt += SPU->channels[1+2*capchan].sampinc;
+        u32 curr = sputrunc(cap.runtime.sampcnt);
+        for (u32 j = last; j < curr; j++)
+        {
+          //so, this is a little strange. why go through a fifo?
+          //it seems that some games will set up a reverb effect by capturing
+          //to the nearly same address as playback, but ahead by a couple.
+          //So, playback will always end up being what was captured a couple of samples ago.
+          //This system counts on playback always having read ahead 16 samples.
+          //In that case, playback will end up being what was processed at one entire buffer length ago,
+          //since the 16 samples would have read ahead before they got captured over
+
+          //It's actually the source channels which should have a fifo, but we are
+          //not going to take the hit in speed and complexity. Save it for a future rewrite.
+          //Instead, what we do here is delay the capture by 16 samples to create a similar effect.
+          //Subjectively, it seems to be working.
+
+          //Don't do anything until the fifo is filled, so as to delay it
+          if (cap.runtime.fifo.size < 16)
+          {
+            cap.runtime.fifo.enqueue(capout[capchan]);
+            continue;
+          }
+
+          //(actually capture sample from fifo instead of most recently generated)
+          u32 multiplier;
+          s32 sample = cap.runtime.fifo.dequeue();
+          cap.runtime.fifo.enqueue(capout[capchan]);
+
+          if (cap.bits8)
+          {
+            s8 sample8 = sample >> 8;
+            if (skipcap) _MMU_write08<1,MMU_AT_DMA>(cap.runtime.curdad,0);
+            else _MMU_write08<1,MMU_AT_DMA>(cap.runtime.curdad,sample8);
+            cap.runtime.curdad++;
+            multiplier = 4;
+          }
+          else
+          {
+            s16 sample16 = sample;
+            if (skipcap) _MMU_write16<1,MMU_AT_DMA>(cap.runtime.curdad,0);
+            else _MMU_write16<1,MMU_AT_DMA>(cap.runtime.curdad,sample16);
+            cap.runtime.curdad+=2;
+            multiplier = 2;
+          }
+
+          if (cap.runtime.curdad >= cap.runtime.maxdad)
+          {
+            cap.runtime.curdad = cap.dad;
+            cap.runtime.sampcnt -= cap.len*multiplier;
+          }
+        } //sampinc loop
+      } //if capchan running
+    } //capchan loop
+  } //main sample loop
+
+  SPU->sndbuf[0] = samp0[0];
+  SPU->sndbuf[1] = samp0[1];
+}
+
+//ENTER
+static void SPU_MixAudio(bool actuallyMix, SPU_struct *SPU, int length)
+{
+  if (actuallyMix)
+  {
+    memset(SPU->sndbuf, 0, length*4*2);
+    memset(SPU->outbuf, 0, length*2*2);
+  }
+
+  SPU_MixAudio_Advanced(actuallyMix, SPU, length);
+
+  //we used to bail out if speakers were disabled.
+  //this is technically wrong. sound may still be captured, or something.
+  //in all likelihood, any game doing this probably master disabled the SPU also
+  //so, optimization of this case is probably not necessary.
+  //later, we'll just silence the output
+  bool speakers = T1ReadWord(MMU.ARM7_REG, 0x304) & 0x01;
+
+  u8 vol = SPU->regs.mastervol;
+
+  // convert from 32-bit->16-bit
+  if (actuallyMix && speakers) {
+    for (int i = 0; i < length*2; i++)
+    {
+      // Apply Master Volume
+      SPU->sndbuf[i] = spumuldiv7(SPU->sndbuf[i], vol);
+      s16 outsample = MinMax(SPU->sndbuf[i],-0x8000,0x7FFF);
+      SPU->outbuf[i] = outsample;
+    }
+  }
 }
 
 //////////////////////////////////////////////////////////////////////////////
 
-static inline void Fetch8BitData(const channel_struct *const chan, int32_t *const data, SPUInterpolationMode INTERPOLATE_MODE)
-{
-	if (chan->sampcnt < 0)
-	{
-		*data = 0;
-		return;
-	}
-
-	uint32_t loc = u32floor(chan->sampcnt);
-	if (INTERPOLATE_MODE != SPUInterpolation_None)
-	{
-		int32_t a = static_cast<int32_t>(read_s8(chan->addr + loc) << 8);
-		if (loc < (chan->totlength << 2) - 1)
-		{
-			int32_t b = static_cast<int32_t>(read_s8(chan->addr + loc + 1) << 8);
-			a = Interpolate(a, b, chan->sampcnt, INTERPOLATE_MODE);
-		}
-		*data = a;
-	}
-	else
-		*data = static_cast<int32_t>(read_s8(chan->addr + loc) << 8);
-}
-
-static inline void Fetch16BitData(const channel_struct *const chan, int32_t *const data, SPUInterpolationMode INTERPOLATE_MODE)
-{
-	if (chan->sampcnt < 0)
-	{
-		*data = 0;
-		return;
-	}
-
-	if (INTERPOLATE_MODE != SPUInterpolation_None)
-	{
-		uint32_t loc = u32floor(chan->sampcnt);
-
-		int32_t a = static_cast<int32_t>(read16(loc * 2 + chan->addr));
-		if (loc < (chan->totlength << 1) - 1)
-		{
-			int32_t b = static_cast<int32_t>(read16(loc * 2 + chan->addr + 2));
-			a = Interpolate(a, b, chan->sampcnt, INTERPOLATE_MODE);
-		}
-		*data = a;
-	}
-	else
-		*data = read16(chan->addr + u32floor(chan->sampcnt) * 2);
-}
-
-static inline void FetchADPCMData(channel_struct *const chan, int32_t *const data, SPUInterpolationMode INTERPOLATE_MODE)
-{
-	if (chan->sampcnt < 8)
-	{
-		*data = 0;
-		return;
-	}
-
-	// No sense decoding, just return the last sample
-	if (chan->lastsampcnt != u32floor(chan->sampcnt))
-	{
-		uint32_t endExclusive = u32floor(chan->sampcnt + 1);
-		for (uint32_t i = chan->lastsampcnt + 1; i < endExclusive; ++i)
-		{
-			uint32_t shift = (i & 1) << 2;
-			uint32_t data4bit = static_cast<uint32_t>(read08(chan->addr + (i >> 1))) >> shift;
-
-			int32_t diff = precalcdifftbl[chan->index][data4bit & 0xF];
-			chan->index = precalcindextbl[chan->index][data4bit & 0x7];
-
-			chan->pcm16b_last = chan->pcm16b;
-			chan->pcm16b = MinMax(chan->pcm16b+diff, -0x8000, 0x7FFF);
-
-			if (i == static_cast<uint32_t>(chan->loopstart << 3))
-			{
-				if (chan->loop_index != K_ADPCM_LOOPING_RECOVERY_INDEX)
-					printf("over-snagging\n");
-				chan->loop_pcm16b = chan->pcm16b;
-				chan->loop_index = chan->index;
-			}
-		}
-
-		chan->lastsampcnt = u32floor(chan->sampcnt);
-	}
-
-	if (INTERPOLATE_MODE != SPUInterpolation_None)
-		*data = Interpolate(static_cast<int32_t>(chan->pcm16b_last), static_cast<int32_t>(chan->pcm16b), chan->sampcnt, INTERPOLATE_MODE);
-	else
-		*data = static_cast<int32_t>(chan->pcm16b);
-}
-
-static inline void FetchPSGData(channel_struct *chan, int32_t *data)
-{
-	if (chan->sampcnt < 0)
-	{
-		*data = 0;
-		return;
-	}
-
-	if (chan->num < 8)
-		*data = 0;
-	else if (chan->num < 14)
-		*data = static_cast<int32_t>(wavedutytbl[chan->waveduty][u32floor(chan->sampcnt) & 0x7]);
-	else
-	{
-		if (chan->lastsampcnt == u32floor(chan->sampcnt))
-		{
-			*data = static_cast<int32_t>(chan->psgnoise_last);
-			return;
-		}
-
-		uint32_t max = u32floor(chan->sampcnt);
-		for (uint32_t i = chan->lastsampcnt; i < max; ++i)
-		{
-			if (chan->x & 0x1)
-			{
-				chan->x = (chan->x >> 1) ^ 0x6000;
-				chan->psgnoise_last = -0x7FFF;
-			}
-			else
-			{
-				chan->x >>= 1;
-				chan->psgnoise_last = 0x7FFF;
-			}
-		}
-
-		chan->lastsampcnt = u32floor(chan->sampcnt);
-
-		*data = static_cast<int32_t>(chan->psgnoise_last);
-	}
-}
-
-//////////////////////////////////////////////////////////////////////////////
-
-static inline void MixL(SPU_struct *SPU, channel_struct *chan, int32_t data)
-{
-	data = spumuldiv7(data, chan->vol) >> chan->datashift;
-	SPU->sndbuf[SPU->bufpos << 1] += data;
-}
-
-static inline void MixR(SPU_struct *SPU, channel_struct *chan, int32_t data)
-{
-	data = spumuldiv7(data, chan->vol) >> chan->datashift;
-	SPU->sndbuf[(SPU->bufpos << 1) + 1] += data;
-}
-
-static inline void MixLR(SPU_struct *SPU, channel_struct *chan, int32_t data)
-{
-	data = spumuldiv7(data, chan->vol) >> chan->datashift;
-	SPU->sndbuf[SPU->bufpos << 1] += spumuldiv7(data, 127 - chan->pan);
-	SPU->sndbuf[(SPU->bufpos << 1) + 1] += spumuldiv7(data, chan->pan);
-}
-
-//////////////////////////////////////////////////////////////////////////////
-
-static inline void TestForLoop(SPU_struct *SPU, channel_struct *chan, int FORMAT)
-{
-	int shift = !FORMAT ? 2 : 1;
-
-	chan->sampcnt += chan->sampinc;
-
-	if (chan->sampcnt > chan->double_totlength_shifted)
-	{
-		// Do we loop? Or are we done?
-		if (chan->repeat == 1)
-		{
-			while (chan->sampcnt > chan->double_totlength_shifted)
-				chan->sampcnt -= chan->double_totlength_shifted - static_cast<double>(chan->loopstart << shift);
-			//chan->sampcnt = (double)(chan->loopstart << shift);
-		}
-		else
-		{
-			SPU->KeyOff(chan->num);
-			SPU->bufpos = SPU->buflength;
-		}
-	}
-}
-
-static inline void TestForLoop2(SPU_struct *SPU, channel_struct *chan)
-{
-	chan->sampcnt += chan->sampinc;
-
-	if (chan->sampcnt > chan->double_totlength_shifted)
-	{
-		// Do we loop? Or are we done?
-		if (chan->repeat == 1)
-		{
-			while (chan->sampcnt > chan->double_totlength_shifted)
-				chan->sampcnt -= chan->double_totlength_shifted - static_cast<double>(chan->loopstart << 3);
-
-			if (chan->loop_index == K_ADPCM_LOOPING_RECOVERY_INDEX)
-			{
-				chan->pcm16b = read16(chan->addr);
-				chan->index = read08(chan->addr + 2) & 0x7F;
-				chan->lastsampcnt = 7;
-			}
-			else
-			{
-				chan->pcm16b = chan->loop_pcm16b;
-				chan->index = chan->loop_index;
-				chan->lastsampcnt = chan->loopstart << 3;
-			}
-		}
-		else
-		{
-			chan->status = CHANSTAT_STOPPED;
-			SPU->KeyOff(chan->num);
-			SPU->bufpos = SPU->buflength;
-		}
-	}
-}
-
-static inline void SPU_Mix(SPU_struct *SPU, channel_struct *chan, int32_t data, int CHANNELS)
-{
-	switch (CHANNELS)
-	{
-		case 0:
-			MixL(SPU, chan, data);
-			break;
-		case 1:
-			MixLR(SPU, chan, data);
-			break;
-		case 2:
-			MixR(SPU, chan, data);
-	}
-	SPU->lastdata = data;
-}
-
-// WORK
-static inline void ____SPU_ChanUpdate(SPU_struct *const SPU, channel_struct *const chan, int FORMAT, SPUInterpolationMode INTERPOLATE_MODE, int CHANNELS)
-{
-	for (; SPU->bufpos < SPU->buflength; ++SPU->bufpos)
-	{
-		if (CHANNELS != -1)
-		{
-			int32_t data = 0;
-			switch (FORMAT)
-			{
-				case 0:
-					Fetch8BitData(chan, &data, INTERPOLATE_MODE);
-					break;
-				case 1:
-					Fetch16BitData(chan, &data, INTERPOLATE_MODE);
-					break;
-				case 2:
-					FetchADPCMData(chan, &data, INTERPOLATE_MODE);
-					break;
-				case 3:
-					FetchPSGData(chan, &data);
-			}
-			SPU_Mix(SPU, chan, data, CHANNELS);
-		}
-
-		switch (FORMAT)
-		{
-			case 0:
-			case 1:
-				TestForLoop(SPU, chan, FORMAT);
-				break;
-			case 2:
-				TestForLoop2(SPU, chan);
-				break;
-			case 3:
-				chan->sampcnt += chan->sampinc;
-		}
-	}
-}
-
-static inline void ___SPU_ChanUpdate(bool actuallyMix, SPU_struct *const SPU, channel_struct *const chan, int FORMAT, SPUInterpolationMode INTERPOLATE_MODE)
-{
-	if (!actuallyMix)
-		____SPU_ChanUpdate(SPU, chan, FORMAT, INTERPOLATE_MODE, -1);
-	else if (!chan->pan)
-		____SPU_ChanUpdate(SPU, chan, FORMAT, INTERPOLATE_MODE, 0);
-	else if (chan->pan == 127)
-		____SPU_ChanUpdate(SPU, chan, FORMAT, INTERPOLATE_MODE, 2);
-	else
-		____SPU_ChanUpdate(SPU, chan, FORMAT, INTERPOLATE_MODE, 1);
-}
-
-static inline void __SPU_ChanUpdate(bool actuallyMix, SPU_struct *const SPU, channel_struct *const chan, SPUInterpolationMode INTERPOLATE_MODE)
-{
-	switch (chan->format)
-	{
-		case 0:
-			___SPU_ChanUpdate(actuallyMix, SPU, chan, 0, INTERPOLATE_MODE);
-			break;
-		case 1:
-			___SPU_ChanUpdate(actuallyMix, SPU, chan, 1, INTERPOLATE_MODE);
-			break;
-		case 2:
-			___SPU_ChanUpdate(actuallyMix, SPU, chan, 2, INTERPOLATE_MODE);
-			break;
-		case 3:
-			___SPU_ChanUpdate(actuallyMix, SPU, chan, 3, INTERPOLATE_MODE);
-			break;
-		default:
-			assert(false);
-	}
-}
-
-static inline void _SPU_ChanUpdate(bool actuallyMix, SPU_struct *const SPU, channel_struct *const chan)
-{
-	switch (CommonSettings.spuInterpolationMode)
-	{
-		case SPUInterpolation_None:
-			__SPU_ChanUpdate(actuallyMix, SPU, chan, SPUInterpolation_None);
-			break;
-		case SPUInterpolation_Linear:
-			__SPU_ChanUpdate(actuallyMix, SPU, chan, SPUInterpolation_Linear);
-			break;
-		case SPUInterpolation_Cosine:
-			__SPU_ChanUpdate(actuallyMix, SPU, chan, SPUInterpolation_Cosine);
-			break;
-	}
-}
-
-// ENTERNEW
-static void SPU_MixAudio_Advanced(bool, SPU_struct *SPU, int length)
-{
-	// the advanced spu function correctly handles all sound control mixing options, as well as capture
-	// this code is not entirely optimal, as it relies on sort of manhandling the core mixing functions
-	// in order to get the results it needs.
-
-	// THIS IS MAX HACKS!!!!
-	// AND NEEDS TO BE REWRITTEN ALONG WITH THE DEEPEST PARTS OF THE SPU
-	// ONCE WE KNOW THAT IT WORKS
-
-	// BIAS gets ignored since our spu is still not bit perfect,
-	// and it doesnt matter for purposes of capture
-
-	// -----------DEBUG CODE
-	bool skipcap = false;
-	// -----------------
-
-	int32_t samp0[] = { 0, 0 };
-
-	// believe it or not, we are going to do this one sample at a time.
-	// like i said, it is slower.
-	for (int samp = 0; samp < length; ++samp)
-	{
-		SPU->sndbuf[0] = SPU->sndbuf[1] = 0;
-		SPU->buflength = 1;
-
-		int32_t capmix[] = { 0, 0 }, mix[] = { 0, 0 };
-		int32_t chanout[16];
-		int32_t submix[32];
-
-		// generate each channel, and helpfully mix it at the same time
-		for (int i = 0; i < 16; ++i)
-		{
-			channel_struct *chan = &SPU->channels[i];
-
-			if (chan->status == CHANSTAT_PLAY)
-			{
-				SPU->bufpos = 0;
-
-				bool bypass = false;
-				if (i == 1 && SPU->regs.ctl_ch1bypass)
-					bypass = true;
-				if (i == 3 && SPU->regs.ctl_ch3bypass)
-					bypass = true;
-
-				// output to mixer unless we are bypassed.
-				// dont output to mixer if the user muted us
-				bool outputToMix = true;
-				if (CommonSettings.spu_muteChannels[i])
-					outputToMix = false;
-				if (bypass)
-					outputToMix = false;
-				bool outputToCap = outputToMix;
-				if (CommonSettings.spu_captureMuted && !bypass)
-					outputToCap = true;
-
-				// channels 1 and 3 should probably always generate their audio
-				// internally at least, just in case they get used by the spu output
-				bool domix = outputToCap || outputToMix || i == 1 || i == 3;
-
-				// clear the output buffer since this is where _SPU_ChanUpdate wants to accumulate things
-				SPU->sndbuf[0] = SPU->sndbuf[1] = 0;
-
-				// get channel's next output sample.
-				_SPU_ChanUpdate(domix, SPU, chan);
-				chanout[i] = SPU->lastdata >> chan->datashift;
-
-				// save the panned results
-				submix[i * 2] = SPU->sndbuf[0];
-				submix[i * 2 + 1] = SPU->sndbuf[1];
-
-				// send sample to our capture mix
-				if (outputToCap)
-				{
-					capmix[0] += submix[i * 2];
-					capmix[1] += submix[i * 2 + 1];
-				}
-
-				// send sample to our main mixer
-				if (outputToMix)
-				{
-					mix[0] += submix[i * 2];
-					mix[1] += submix[i * 2 + 1];
-				}
-			}
-			else
-				chanout[i] = submix[i * 2] = submix[i * 2 + 1] = 0;
-		} // foreach channel
-
-		int32_t mixout[] = { mix[0], mix[1] };
-		int32_t capmixout[] = { capmix[0], capmix[1] };
-		int32_t sndout[] = { 0, 0 };
-		int32_t capout[2];
-
-		// create SPU output
-		switch (SPU->regs.ctl_left)
-		{
-			case SPU_struct::REGS::LOM_LEFT_MIXER:
-				sndout[0] = mixout[0];
-				break;
-			case SPU_struct::REGS::LOM_CH1:
-				sndout[0] = submix[2];
-				break;
-			case SPU_struct::REGS::LOM_CH3:
-				sndout[0] = submix[6];
-				break;
-			case SPU_struct::REGS::LOM_CH1_PLUS_CH3:
-				sndout[0] = submix[2] + submix[6];
-		}
-		switch (SPU->regs.ctl_right)
-		{
-			case SPU_struct::REGS::ROM_RIGHT_MIXER:
-				sndout[1] = mixout[1];
-				break;
-			case SPU_struct::REGS::ROM_CH1:
-				sndout[1] = submix[3];
-				break;
-			case SPU_struct::REGS::ROM_CH3:
-				sndout[1] = submix[7];
-				break;
-			case SPU_struct::REGS::ROM_CH1_PLUS_CH3:
-				sndout[1] = submix[3] + submix[7];
-		}
-
-		// generate capture output ("capture bugs" from gbatek are not emulated)
-		if (!SPU->regs.cap[0].source)
-			capout[0] = capmixout[0]; // cap0 = L-mix
-		else if (SPU->regs.cap[0].add)
-			capout[0] = chanout[0] + chanout[1]; // cap0 = ch0+ch1
-		else
-			capout[0] = chanout[0]; // cap0 = ch0
-
-		if (!SPU->regs.cap[1].source)
-			capout[1] = capmixout[1]; // cap1 = R-mix
-		else if (SPU->regs.cap[1].add)
-			capout[1] = chanout[2] + chanout[3]; // cap1 = ch2+ch3
-		else
-			capout[1] = chanout[2]; // cap1 = ch2
-
-		capout[0] = MinMax(capout[0], -0x8000, 0x7FFF);
-		capout[1] = MinMax(capout[1], -0x8000, 0x7FFF);
-
-		// write the output sample where it is supposed to go
-		if (!samp)
-		{
-			samp0[0] = sndout[0];
-			samp0[1] = sndout[1];
-		}
-		else
-		{
-			SPU->sndbuf[samp * 2] = sndout[0];
-			SPU->sndbuf[samp * 2 + 1] = sndout[1];
-		}
-
-		for (int capchan = 0; capchan < 2; ++capchan)
-		{
-			if (SPU->regs.cap[capchan].runtime.running)
-			{
-				SPU_struct::REGS::CAP &cap = SPU->regs.cap[capchan];
-				uint32_t last = u32floor(cap.runtime.sampcnt);
-				cap.runtime.sampcnt += SPU->channels[2 * capchan + 1].sampinc;
-				uint32_t curr = u32floor(cap.runtime.sampcnt);
-				for (uint32_t j = last; j < curr; ++j)
-				{
-					// so, this is a little strange. why go through a fifo?
-					// it seems that some games will set up a reverb effect by capturing
-					// to the nearly same address as playback, but ahead by a couple.
-					// So, playback will always end up being what was captured a couple of samples ago.
-					// This system counts on playback always having read ahead 16 samples.
-					// In that case, playback will end up being what was processed at one entire buffer length ago,
-					// since the 16 samples would have read ahead before they got captured over
-
-					// It's actually the source channels which should have a fifo, but we are
-					// not going to take the hit in speed and complexity. Save it for a future rewrite.
-					// Instead, what we do here is delay the capture by 16 samples to create a similar effect.
-					// Subjectively, it seems to be working.
-
-					// Don't do anything until the fifo is filled, so as to delay it
-					if (cap.runtime.fifo.size < 16)
-					{
-						cap.runtime.fifo.enqueue(static_cast<int16_t>(capout[capchan]));
-						continue;
-					}
-
-					// (actually capture sample from fifo instead of most recently generated)
-					int32_t sample = cap.runtime.fifo.dequeue();
-					cap.runtime.fifo.enqueue(static_cast<int16_t>(capout[capchan]));
-
-					uint32_t multiplier;
-					if (cap.bits8)
-					{
-						int8_t sample8 = static_cast<int8_t>(sample >> 8);
-						if (skipcap)
-							_MMU_write08<1, MMU_AT_DMA>(cap.runtime.curdad, 0);
-						else
-							_MMU_write08<1, MMU_AT_DMA>(cap.runtime.curdad, sample8);
-						++cap.runtime.curdad;
-						multiplier = 4;
-					}
-					else
-					{
-						int16_t sample16 = static_cast<int16_t>(sample);
-						if (skipcap)
-							_MMU_write16<1, MMU_AT_DMA>(cap.runtime.curdad, 0);
-						else
-							_MMU_write16<1, MMU_AT_DMA>(cap.runtime.curdad, sample16);
-						cap.runtime.curdad += 2;
-						multiplier = 2;
-					}
-
-					if (cap.runtime.curdad >= cap.runtime.maxdad)
-					{
-						cap.runtime.curdad = cap.dad;
-						cap.runtime.sampcnt -= cap.len * multiplier;
-					}
-				} // sampinc loop
-			} // if capchan running
-		} // capchan loop
-	} // main sample loop
-
-	SPU->sndbuf[0] = samp0[0];
-	SPU->sndbuf[1] = samp0[1];
-}
-
-// ENTER
-static void SPU_MixAudio(bool actuallyMix, SPU_struct *SPU, int length)
-{
-	if (actuallyMix)
-	{
-		memset(&SPU->sndbuf[0], 0, length * 4 * 2);
-		memset(&SPU->outbuf[0], 0, length * 2 * 2);
-	}
-
-	// we used to use master enable here, and do nothing if audio is disabled.
-	// now, master enable is emulated better..
-	// but for a speed optimization we will still do it
-	if (!SPU->regs.masteren)
-		return;
-
-	bool advanced = CommonSettings.spu_advanced;
-
-	// branch here so that slow computers don't have to take the advanced (slower) codepath.
-	// it remainds to be seen exactly how much slower it is
-	// if it isnt much slower then we should refactor everything to be simpler, once it is working
-	if (advanced && SPU == SPU_core.get())
-		SPU_MixAudio_Advanced(actuallyMix, SPU, length);
-	else
-	{
-		// non-advanced mode
-		for (int i = 0; i < 16; ++i)
-		{
-			channel_struct *chan = &SPU->channels[i];
-
-			if (chan->status != CHANSTAT_PLAY)
-				continue;
-
-			SPU->bufpos = 0;
-			SPU->buflength = length;
-
-			// Mix audio
-			_SPU_ChanUpdate(!CommonSettings.spu_muteChannels[i] && actuallyMix, SPU, chan);
-		}
-	}
-
-	// we used to bail out if speakers were disabled.
-	// this is technically wrong. sound may still be captured, or something.
-	// in all likelihood, any game doing this probably master disabled the SPU also
-	// so, optimization of this case is probably not necessary.
-	// later, we'll just silence the output
-	bool speakers = T1ReadWord(MMU.ARM7_REG, 0x304) & 0x01;
-
-	uint8_t vol = SPU->regs.mastervol;
-
-	// convert from 32-bit->16-bit
-	if (actuallyMix && speakers)
-		for (int i = 0; i < length * 2; ++i)
-		{
-			// Apply Master Volume
-			SPU->sndbuf[i] = spumuldiv7(SPU->sndbuf[i], vol);
-			int16_t outsample = static_cast<int16_t>(MinMax(SPU->sndbuf[i], -0x8000, 0x7FFF));
-			SPU->outbuf[i] = outsample;
-		}
-}
-
-//////////////////////////////////////////////////////////////////////////////
-
-// emulates one hline of the cpu core.
-// this will produce a variable number of samples, calculated to keep a 44100hz output
-// in sync with the emulator framerate
+
+//emulates one hline of the cpu core.
+//this will produce a variable number of samples, calculated to keep a 44100hz output
+//in sync with the emulator framerate
 int spu_core_samples = 0;
 void SPU_Emulate_core()
 {
-	bool needToMix = true;
-
-	samples += samples_per_hline;
-	spu_core_samples = static_cast<int>(samples);
-	samples -= spu_core_samples;
-
-	// We don't need to mix audio for Dual Synch/Asynch mode since we do this
-	// later in SPU_Emulate_user(). Disable mixing here to speed up processing.
-	// However, recording still needs to mix the audio, so make sure we're also
-	// not recording before we disable mixing.
-	if (synchmode == ESynchMode_DualSynchAsynch)
-		needToMix = false;
-
-	SPU_MixAudio(needToMix, SPU_core.get(), spu_core_samples);
-
-	if (!SNDCore)
-		return;
-
-	if (SNDCore->FetchSamples)
-		SNDCore->FetchSamples(&SPU_core->outbuf[0], spu_core_samples, synchmode, synchronizer.get());
-	else
-		SPU_DefaultFetchSamples(&SPU_core->outbuf[0], spu_core_samples, synchmode, synchronizer.get());
-}
-
-void SPU_Emulate_user(bool /*mix*/)
-{
-	static std::vector<int16_t> postProcessBuffer;
-	static size_t postProcessBufferSize = 0;
-	size_t processedSampleCount = 0;
-
-	if (!SNDCore)
-		return;
-
-	// Check to see how many free samples are available.
-	// If there are some, fill up the output buffer.
-	size_t freeSampleCount = SNDCore->GetAudioSpace();
-	if (!freeSampleCount)
-		return;
-
-	//printf("mix %i samples\n", audiosize);
-	if (freeSampleCount > buffersize)
-		freeSampleCount = buffersize;
-
-	// If needed, resize the post-process buffer to guarantee that
-	// we can store all the sound data.
-	if (postProcessBufferSize < freeSampleCount * 2 * sizeof(int16_t))
-	{
-		postProcessBufferSize = freeSampleCount * 2 * sizeof(int16_t);
-		postProcessBuffer.resize(postProcessBufferSize);
-	}
-
-	if (SNDCore->PostProcessSamples)
-		processedSampleCount = SNDCore->PostProcessSamples(&postProcessBuffer[0], freeSampleCount, synchmode, synchronizer.get());
-	else
-		processedSampleCount = SPU_DefaultPostProcessSamples(&postProcessBuffer[0], freeSampleCount, synchmode, synchronizer.get());
-
-	SNDCore->UpdateAudio(&postProcessBuffer[0], processedSampleCount);
-}
-
-void SPU_DefaultFetchSamples(int16_t *sampleBuffer, size_t sampleCount, ESynchMode synchMode, ISynchronizingAudioBuffer *theSynchronizer)
-{
-	if (synchMode == ESynchMode_Synchronous)
-		theSynchronizer->enqueue_samples(sampleBuffer, sampleCount);
-}
-
-size_t SPU_DefaultPostProcessSamples(int16_t *postProcessBuffer, size_t requestedSampleCount, ESynchMode synchMode, ISynchronizingAudioBuffer *theSynchronizer)
-{
-	size_t processedSampleCount = 0;
-
-	switch (synchMode)
-	{
-		case ESynchMode_DualSynchAsynch:
-			if (SPU_user)
-			{
-				SPU_MixAudio(true, SPU_user.get(), requestedSampleCount);
-				memcpy(postProcessBuffer, &SPU_user->outbuf[0], requestedSampleCount * 2 * sizeof(int16_t));
-				processedSampleCount = requestedSampleCount;
-			}
-			break;
-
-		case ESynchMode_Synchronous:
-			processedSampleCount = theSynchronizer->output_samples(postProcessBuffer, requestedSampleCount);
-	}
-
-	return processedSampleCount;
+  bool needToMix = true;
+  SoundInterface_struct *soundProcessor = SPU_SoundCore();
+
+  samples += samples_per_hline;
+  spu_core_samples = (int)(samples);
+  samples -= spu_core_samples;
+
+  SPU_MixAudio(needToMix, SPU_core, spu_core_samples);
+
+  if (soundProcessor == NULL)
+  {
+    return;
+  }
+
+  if (soundProcessor->FetchSamples != NULL)
+  {
+    soundProcessor->FetchSamples(SPU_core->outbuf, spu_core_samples, synchmode, synchronizer);
+  }
+  else
+  {
+    SPU_DefaultFetchSamples(SPU_core->outbuf, spu_core_samples, synchmode, synchronizer);
+  }
+}
+
+void SPU_Emulate_user(bool mix)
+{
+  static s16 *postProcessBuffer = NULL;
+  static size_t postProcessBufferSize = 0;
+  size_t freeSampleCount = 0;
+  size_t processedSampleCount = 0;
+  SoundInterface_struct *soundProcessor = SPU_SoundCore();
+
+  if (soundProcessor == NULL)
+  {
+    return;
+  }
+
+  // Check to see how many free samples are available.
+  // If there are some, fill up the output buffer.
+  freeSampleCount = soundProcessor->GetAudioSpace();
+  if (freeSampleCount == 0)
+  {
+    return;
+  }
+
+  if (freeSampleCount > buffersize)
+  {
+    freeSampleCount = buffersize;
+  }
+
+  // If needed, resize the post-process buffer to guarantee that
+  // we can store all the sound data.
+  if (postProcessBufferSize < freeSampleCount * 2 * sizeof(s16))
+  {
+    postProcessBufferSize = freeSampleCount * 2 * sizeof(s16);
+    postProcessBuffer = (s16 *)realloc(postProcessBuffer, postProcessBufferSize);
+  }
+
+  if (soundProcessor->PostProcessSamples != NULL)
+  {
+    processedSampleCount = soundProcessor->PostProcessSamples(postProcessBuffer, freeSampleCount, synchmode, synchronizer);
+  }
+  else
+  {
+    processedSampleCount = SPU_DefaultPostProcessSamples(postProcessBuffer, freeSampleCount, synchmode, synchronizer);
+  }
+
+  soundProcessor->UpdateAudio(postProcessBuffer, processedSampleCount);
+}
+
+void SPU_DefaultFetchSamples(s16 *sampleBuffer, size_t sampleCount, ESynchMode synchMode, ISynchronizingAudioBuffer *theSynchronizer)
+{
+  theSynchronizer->enqueue_samples(sampleBuffer, sampleCount);
+}
+
+size_t SPU_DefaultPostProcessSamples(s16 *postProcessBuffer, size_t requestedSampleCount, ESynchMode synchMode, ISynchronizingAudioBuffer *theSynchronizer)
+{
+  return theSynchronizer->output_samples(postProcessBuffer, requestedSampleCount);
 }
 
 //////////////////////////////////////////////////////////////////////////////
 // Dummy Sound Interface
 //////////////////////////////////////////////////////////////////////////////
 
-int SNDDummyInit(int) { return 0; }
+int SNDDummyInit(int buffersize);
+void SNDDummyDeInit();
+void SNDDummyUpdateAudio(s16 *buffer, u32 num_samples);
+u32 SNDDummyGetAudioSpace();
+void SNDDummyMuteAudio();
+void SNDDummyUnMuteAudio();
+void SNDDummySetVolume(int volume);
+void SNDDummyClearBuffer();
+void SNDDummyFetchSamples(s16 *sampleBuffer, size_t sampleCount, ESynchMode synchMode, ISynchronizingAudioBuffer *theSynchronizer);
+size_t SNDDummyPostProcessSamples(s16 *postProcessBuffer, size_t requestedSampleCount, ESynchMode synchMode, ISynchronizingAudioBuffer *theSynchronizer);
+
+SoundInterface_struct SNDDummy = {
+  SNDCORE_DUMMY,
+  "Dummy Sound Interface",
+  SNDDummyInit,
+  SNDDummyDeInit,
+  SNDDummyUpdateAudio,
+  SNDDummyGetAudioSpace,
+  SNDDummyMuteAudio,
+  SNDDummyUnMuteAudio,
+  SNDDummySetVolume,
+  SNDDummyClearBuffer,
+  SNDDummyFetchSamples,
+  SNDDummyPostProcessSamples
+};
+
+int SNDDummyInit(int buffersize) { return 0; }
 void SNDDummyDeInit() {}
-void SNDDummyUpdateAudio(int16_t *, uint32_t) { }
-uint32_t SNDDummyGetAudioSpace() { return DESMUME_SAMPLE_RATE / 60 + 5; }
+void SNDDummyUpdateAudio(s16 *buffer, u32 num_samples) { }
+u32 SNDDummyGetAudioSpace() { return DESMUME_SAMPLE_RATE/60 + 5; }
 void SNDDummyMuteAudio() {}
 void SNDDummyUnMuteAudio() {}
-void SNDDummySetVolume(int) {}
+void SNDDummySetVolume(int volume) {}
 void SNDDummyClearBuffer() {}
-void SNDDummyFetchSamples(int16_t *, size_t, ESynchMode, ISynchronizingAudioBuffer *) { }
-size_t SNDDummyPostProcessSamples(int16_t *, size_t, ESynchMode, ISynchronizingAudioBuffer *) { return 0; }
-
-SoundInterface_struct SNDDummy =
-{
-	SNDCORE_DUMMY,
-	"Dummy Sound Interface",
-	SNDDummyInit,
-	SNDDummyDeInit,
-	SNDDummyUpdateAudio,
-	SNDDummyGetAudioSpace,
-	SNDDummyMuteAudio,
-	SNDDummyUnMuteAudio,
-	SNDDummySetVolume,
-	SNDDummyClearBuffer,
-	SNDDummyFetchSamples,
-	SNDDummyPostProcessSamples
-};
-
+void SNDDummyFetchSamples(s16 *sampleBuffer, size_t sampleCount, ESynchMode synchMode, ISynchronizingAudioBuffer *theSynchronizer) {}
+size_t SNDDummyPostProcessSamples(s16 *postProcessBuffer, size_t requestedSampleCount, ESynchMode synchMode, ISynchronizingAudioBuffer *theSynchronizer) { return 0; }
+
+

--- a/src/in_2sf/desmume/SPU.h
+++ b/src/in_2sf/desmume/SPU.h
@@ -1,6 +1,6 @@
 /*
 	Copyright 2006 Theo Berkau
-	Copyright (C) 2006-2010 DeSmuME team
+	Copyright (C) 2006-2015 DeSmuME team
 
 	This file is free software: you can redistribute it and/or modify
 	it under the terms of the GNU General Public License as published by
@@ -16,50 +16,58 @@
 	along with the this software.  If not, see <http://www.gnu.org/licenses/>.
 */
 
-#pragma once
-
-#include <memory>
+#ifndef SPU_H
+#define SPU_H
+
 #include <iosfwd>
 #include <string>
-#include <cassert>
+#include <assert.h>
+#include <stdio.h>
+#include <memory>
+
 #include "types.h"
 #include "matrix.h"
-#include "emufile.h"
 #include "metaspu/metaspu.h"
 
-const int SNDCORE_DEFAULT = -1;
-const int SNDCORE_DUMMY = 0;
-
-const uint8_t CHANSTAT_STOPPED = 0;
-const uint8_t CHANSTAT_PLAY = 1;
-
-inline int32_t spumuldiv7(int32_t val, uint8_t multiplier)
-{
+class EMUFILE;
+
+#define SNDCORE_DEFAULT         -1
+#define SNDCORE_DUMMY           0
+
+#define CHANSTAT_STOPPED          0
+#define CHANSTAT_PLAY             1
+
+
+//who made these static? theyre used in multiple places.
+FORCEINLINE u32 sputrunc(float f) { return u32floor(f); }
+FORCEINLINE u32 sputrunc(double d) { return u32floor(d); }
+FORCEINLINE s32 spumuldiv7(s32 val, u8 multiplier) {
 	assert(multiplier <= 127);
-	return multiplier == 127 ? val : ((val * multiplier) >> 7);
+	return (multiplier == 127) ? val : ((val * multiplier) >> 7);
 }
 
 enum SPUInterpolationMode
 {
-	SPUInterpolation_None,
-	SPUInterpolation_Linear,
-	SPUInterpolation_Cosine
+	SPUInterpolation_None   = 0,
+	SPUInterpolation_Linear = 1,
+	SPUInterpolation_Cosine = 2,
+	SPUInterpolation_Sharp  = 3
 };
 
 struct SoundInterface_struct
 {
-	int id;
-	const char *Name;
-	int (*Init)(int buffersize);
-	void (*DeInit)();
-	void (*UpdateAudio)(int16_t *buffer, uint32_t num_samples);
-	uint32_t (*GetAudioSpace)();
-	void (*MuteAudio)();
-	void (*UnMuteAudio)();
-	void (*SetVolume)(int volume);
-	void (*ClearBuffer)();
-	void (*FetchSamples)(int16_t *sampleBuffer, size_t sampleCount, ESynchMode synchMode, ISynchronizingAudioBuffer *theSynchronizer);
-	size_t (*PostProcessSamples)(int16_t *postProcessBuffer, size_t requestedSampleCount, ESynchMode synchMode, ISynchronizingAudioBuffer *theSynchronizer);
+   int id;
+   const char *Name;
+   int (*Init)(int buffersize);
+   void (*DeInit)();
+   void (*UpdateAudio)(s16 *buffer, u32 num_samples);
+   u32 (*GetAudioSpace)();
+   void (*MuteAudio)();
+   void (*UnMuteAudio)();
+   void (*SetVolume)(int volume);
+   void (*ClearBuffer)();
+   void (*FetchSamples)(s16 *sampleBuffer, size_t sampleCount, ESynchMode synchMode, ISynchronizingAudioBuffer *theSynchronizer);
+   size_t (*PostProcessSamples)(s16 *postProcessBuffer, size_t requestedSampleCount, ESynchMode synchMode, ISynchronizingAudioBuffer *theSynchronizer);
 };
 
 extern SoundInterface_struct SNDDummy;
@@ -68,43 +76,69 @@
 
 struct channel_struct
 {
-	channel_struct() { }
-	uint32_t num;
-	uint8_t vol;
-	uint8_t datashift;
-	uint8_t hold;
-	uint8_t pan;
-	uint8_t waveduty;
-	uint8_t repeat;
-	uint8_t format;
-	uint8_t keyon;
-	uint8_t status;
-	uint32_t addr;
-	uint16_t timer;
-	uint16_t loopstart;
-	uint32_t length;
-	uint32_t totlength;
-	double double_totlength_shifted;
-	double sampcnt;
-	double sampinc;
-	// ADPCM specific
-	uint32_t lastsampcnt;
-	int16_t pcm16b, pcm16b_last;
-	int16_t loop_pcm16b;
-	int32_t index;
-	int loop_index;
-	uint16_t x;
-	int16_t psgnoise_last;
+	channel_struct() :	num(0),
+						vol(0),
+						volumeDiv(0),
+						hold(0),
+						pan(0),
+						waveduty(0),
+						repeat(0),
+						format(0),
+						keyon(0),
+						status(0),
+						addr(0),
+						timer(0),
+						loopstart(0),
+						length(0),
+						totlength(0),
+						double_totlength_shifted(0.0),
+						sampcnt(0.0),
+						sampinc(0.0),
+						lastsampcnt(0),
+						pcm16b(0),
+						pcm16b_last(0),
+						loop_pcm16b(0),
+						index(0),
+						loop_index(0),
+						x(0),
+						psgnoise_last(0)
+	{}
+	u32 num;
+   u8 vol;
+   u8 volumeDiv;
+   u8 hold;
+   u8 pan;
+   u8 waveduty;
+   u8 repeat;
+   u8 format;
+   u8 keyon;
+   u8 status;
+   u32 addr;
+   u16 timer;
+   u16 loopstart;
+   u32 length;
+   u32 totlength;
+   double double_totlength_shifted;
+   double sampcnt;
+   double sampinc;
+   // ADPCM specific
+   u32 lastsampcnt;
+   s16 pcm16b, pcm16b_last;
+   s16 loop_pcm16b;
+   s32 index;
+   int loop_index;
+   u16 x;
+   s16 psgnoise_last;
 };
 
 class SPUFifo
 {
 public:
 	SPUFifo();
-	void enqueue(int16_t val);
-	int16_t dequeue();
-	int16_t buffer[16];
-	int32_t head, tail, size;
+	void enqueue(s16 val);
+	s16 dequeue();
+	s16 buffer[16];
+	s32 head,tail,size;
 	void reset();
 };
 
@@ -112,99 +146,123 @@
 {
 public:
 	SPU_struct(int buffersize);
-	uint32_t bufpos;
-	uint32_t buflength;
-	std::unique_ptr<int32_t[]> sndbuf;
-	int32_t lastdata; //the last sample that a channel generated
-	std::unique_ptr<int16_t[]> outbuf;
-	uint32_t bufsize;
-	channel_struct channels[16];
-
-	// registers
-	struct REGS
-	{
-		REGS() : mastervol(0), ctl_left(0), ctl_right(0), ctl_ch1bypass(0), ctl_ch3bypass(0), masteren(0), soundbias(0) { }
-
-		uint8_t mastervol;
-		uint8_t ctl_left, ctl_right;
-		uint8_t ctl_ch1bypass, ctl_ch3bypass;
-		uint8_t masteren;
-		uint16_t soundbias;
-
-		enum LeftOutputMode
-		{
-			LOM_LEFT_MIXER,
-			LOM_CH1,
-			LOM_CH3,
-			LOM_CH1_PLUS_CH3
-		};
-
-		enum RightOutputMode
-		{
-			ROM_RIGHT_MIXER,
-			ROM_CH1,
-			ROM_CH3,
-			ROM_CH1_PLUS_CH3
-		};
-
-		struct CAP
-		{
-			CAP() : add(0), source(0), oneshot(0), bits8(0), active(0), dad(0), len(0) { }
-			uint8_t add, source, oneshot, bits8, active;
-			uint32_t dad;
-			uint16_t len;
-			struct Runtime
-			{
-				Runtime() : running(0), curdad(0), maxdad(0) { }
-				uint8_t running;
-				uint32_t curdad;
-				uint32_t maxdad;
-				double sampcnt;
-				SPUFifo fifo;
-			} runtime;
-		} cap[2];
-	} regs;
-
-	void reset();
-	void KeyOff(int channel);
-	void KeyOn(int channel);
-	void KeyProbe(int channel);
-	void ProbeCapture(int which);
-	void WriteByte(uint32_t addr, uint8_t val);
-	uint8_t ReadByte(uint32_t addr);
-	uint16_t ReadWord(uint32_t addr);
-	uint32_t ReadLong(uint32_t addr);
-	void WriteWord(uint32_t addr, uint16_t val);
-	void WriteLong(uint32_t addr, uint32_t val);
-
-	// kills all channels but leaves SPU otherwise running normally
-	void ShutUp();
-};
+   u32 bufpos;
+   u32 buflength;
+   s32 *sndbuf;
+   s32 lastdata; //the last sample that a channel generated
+   s16 *outbuf;
+   u32 bufsize;
+   channel_struct channels[16];
+
+   //registers
+   struct REGS {
+	   REGS()
+			: mastervol(0)
+			, ctl_left(0)
+			, ctl_right(0)
+			, ctl_ch1bypass(0)
+			, ctl_ch3bypass(0)
+			, masteren(0)
+			, soundbias(0)
+	   {}
+
+	   u8 mastervol;
+	   u8 ctl_left, ctl_right;
+	   u8 ctl_ch1bypass, ctl_ch3bypass;
+	   u8 masteren;
+	   u16 soundbias;
+
+	   enum LeftOutputMode
+	   {
+		   LOM_LEFT_MIXER=0, LOM_CH1=1, LOM_CH3=2, LOM_CH1_PLUS_CH3=3
+	   };
+
+	   enum RightOutputMode
+	   {
+		   ROM_RIGHT_MIXER=0, ROM_CH1=1, ROM_CH3=2, ROM_CH1_PLUS_CH3=3
+	   };
+
+	   struct CAP {
+		   CAP()
+			   : add(0), source(0), oneshot(0), bits8(0), active(0), dad(0), len(0)
+		   {}
+		   u8 add, source, oneshot, bits8, active;
+		   u32 dad;
+		   u16 len;
+		   struct Runtime {
+			   Runtime()
+				   : running(0), curdad(0), maxdad(0)
+			   {}
+			   u8 running;
+			   u32 curdad;
+			   u32 maxdad;
+			   double sampcnt;
+			   SPUFifo fifo;
+		   } runtime;
+	   } cap[2];
+   } regs;
+
+   void reset();
+   ~SPU_struct();
+   void KeyOff(int channel);
+   void KeyOn(int channel);
+   void KeyProbe(int channel);
+   void ProbeCapture(int which);
+   void WriteByte(u32 addr, u8 val);
+   void WriteWord(u32 addr, u16 val);
+   void WriteLong(u32 addr, u32 val);
+   u8 ReadByte(u32 addr);
+   u16 ReadWord(u32 addr);
+   u32 ReadLong(u32 addr);
+   bool isSPU(u32 addr) { return ((addr >= 0x04000400) && (addr < 0x04000520)); }
+
+   //kills all channels but leaves SPU otherwise running normally
+   void ShutUp();
+};
+
+extern SPU_struct *SPU_core;
+extern int spu_core_samples;
 
 int SPU_ChangeSoundCore(int coreid, int buffersize);
-
-void SPU_ReInit();
+SoundInterface_struct *SPU_SoundCore();
+
+void SPU_ReInit(bool fakeBoot = false);
 int SPU_Init(int coreid, int buffersize);
-void SPU_SetSynchMode(ESynchMode mode, ESynchMethod method);
-void SPU_Reset();
-void SPU_DeInit();
+void SPU_Pause(int pause);
+void SPU_SetVolume(int volume);
+void SPU_SetSynchMode(int mode, int method);
+void SPU_ClearOutputBuffer(void);
+void SPU_Reset(void);
+void SPU_DeInit(void);
 void SPU_KeyOn(int channel);
-void SPU_WriteByte(uint32_t addr, uint8_t val);
-void SPU_WriteWord(uint32_t addr, uint16_t val);
-void SPU_WriteLong(uint32_t addr, uint32_t val);
-uint8_t SPU_ReadByte(uint32_t addr);
-uint16_t SPU_ReadWord(uint32_t addr);
-uint32_t SPU_ReadLong(uint32_t addr);
-void SPU_Emulate_core();
+static FORCEINLINE void SPU_WriteByte(u32 addr, u8 val)
+{
+	addr &= 0xFFF;
+
+	SPU_core->WriteByte(addr,val);
+}
+static FORCEINLINE void SPU_WriteWord(u32 addr, u16 val)
+{
+	addr &= 0xFFF;
+
+	SPU_core->WriteWord(addr,val);
+}
+static FORCEINLINE void SPU_WriteLong(u32 addr, u32 val)
+{
+	addr &= 0xFFF;
+
+	SPU_core->WriteLong(addr,val);
+}
+static FORCEINLINE u8 SPU_ReadByte(u32 addr) { return SPU_core->ReadByte(addr & 0x0FFF); }
+static FORCEINLINE u16 SPU_ReadWord(u32 addr) { return SPU_core->ReadWord(addr & 0x0FFF); }
+static FORCEINLINE u32 SPU_ReadLong(u32 addr) { return SPU_core->ReadLong(addr & 0x0FFF); }
+void SPU_Emulate_core(void);
 void SPU_Emulate_user(bool mix = true);
-void SPU_DefaultFetchSamples(int16_t *sampleBuffer, size_t sampleCount, ESynchMode synchMode, ISynchronizingAudioBuffer *theSynchronizer);
-size_t SPU_DefaultPostProcessSamples(int16_t *postProcessBuffer, size_t requestedSampleCount, ESynchMode synchMode, ISynchronizingAudioBuffer *theSynchronizer);
-
-extern std::unique_ptr<SPU_struct> SPU_core, SPU_user;
-extern int spu_core_samples;
-
-// we should make this configurable eventually
-// but at least defining it somewhere is probably a step in the right direction
-const int DESMUME_SAMPLE_RATE = 44100;
-//#define DESMUME_SAMPLE_RATE 48000
-
+void SPU_DefaultFetchSamples(s16 *sampleBuffer, size_t sampleCount, ESynchMode synchMode, ISynchronizingAudioBuffer *theSynchronizer);
+size_t SPU_DefaultPostProcessSamples(s16 *postProcessBuffer, size_t requestedSampleCount, ESynchMode synchMode, ISynchronizingAudioBuffer *theSynchronizer);
+
+extern double DESMUME_SAMPLE_RATE;
+void SetDesmumeSampleRate(double rate);
+
+#endif
+

--- a/src/in_2sf/desmume/arm_instructions.cpp
+++ b/src/in_2sf/desmume/arm_instructions.cpp
@@ -2997,13 +2997,13 @@
 	uint32_t stateMask = PROCNUM?v4T_STATE_MASK : v5TE_STATE_MASK;
 
 	if (operand & unallocMask)
-		printf("ARM%c: MSR_CPSR_REG UNPREDICTABLE UNALLOC (operand %08X)\n", PROCNUM ? '7' : '9', operand);
+		fprintf(stderr, "ARM%c: MSR_CPSR_REG UNPREDICTABLE UNALLOC (operand %08X)\n", PROCNUM ? '7' : '9', operand);
 	if (cpu->CPSR.bits.mode != USR) // Privileged mode
 	{
 		if (BIT16(i))
 			armcpu_switchMode(cpu, operand & 0x1F);
 		if (operand & stateMask)
-			printf("ARM%c: MSR_CPSR_REG UNPREDICTABLE STATE (operand %08X)\n", PROCNUM ? '7' : '9', operand);
+			fprintf(stderr, "ARM%c: MSR_CPSR_REG UNPREDICTABLE STATE (operand %08X)\n", PROCNUM ? '7' : '9', operand);
 		else
 			mask = byte_mask & (userMask | privMask);
 	}
@@ -3021,7 +3021,7 @@
 
 TEMPLATE static uint32_t FASTCALL OP_MSR_SPSR(uint32_t i)
 {
-	//printf("OP_MSR_SPSR\n");
+	//fprintf(stderr, "OP_MSR_SPSR\n");
 	uint32_t operand = cpu->R[REG_POS(i, 0)];
 	OP_MSR_SPSR_(operand);
 	return 1;
@@ -3029,7 +3029,7 @@
 
 TEMPLATE static uint32_t FASTCALL OP_MSR_CPSR_IMM_VAL(uint32_t i)
 {
-	//printf("OP_MSR_CPSR_IMM_VAL\n");
+	//fprintf(stderr, "OP_MSR_CPSR_IMM_VAL\n");
 	IMM_VALUE;
 	OP_MSR_CPSR_(shift_op);
 	return 1;
@@ -3037,7 +3037,7 @@
 
 TEMPLATE static uint32_t FASTCALL OP_MSR_SPSR_IMM_VAL(uint32_t i)
 {
-	//printf("OP_MSR_SPSR_IMM_VAL\n");
+	//fprintf(stderr, "OP_MSR_SPSR_IMM_VAL\n");
 	IMM_VALUE;
 	OP_MSR_SPSR_(shift_op);
 	return 1;
@@ -3701,7 +3701,7 @@
 // -----------------------------------------------------------------------------
 TEMPLATE static uint32_t FASTCALL OP_LDREX(uint32_t i)
 {
-	printf("LDREX\n");
+	fprintf(stderr, "LDREX\n");
 	uint32_t adr = cpu->R[REG_POS(i, 16)];
 	cpu->R[REG_POS(i, 12)] = ROR(READ32(cpu->mem_if->data, adr), 8 * (adr & 3));
 	return MMU_aluMemAccessCycles<PROCNUM,32, MMU_AD_READ>(3, adr);
@@ -4288,7 +4288,7 @@
 // -----------------------------------------------------------------------------
 TEMPLATE static uint32_t FASTCALL OP_STREX(uint32_t i)
 {
-	printf("STREX\n");
+	fprintf(stderr, "STREX\n");
 	uint32_t adr = cpu->R[REG_POS(i, 16)];
 	WRITE32(cpu->mem_if->data, adr, cpu->R[REG_POS(i, 0)]);
 	cpu->R[REG_POS(i, 12)] = 0;
@@ -5012,7 +5012,7 @@
 	{
 		if (cpu->CPSR.bits.mode == USR || cpu->CPSR.bits.mode == SYS)
 		{
-			printf("ERROR1\n");
+			fprintf(stderr, "ERROR1\n");
 			return 1;
 		}
 		oldmode = armcpu_switchMode(cpu, SYS);
@@ -5064,7 +5064,7 @@
 	{
 		if (cpu->CPSR.bits.mode == USR || cpu->CPSR.bits.mode == SYS)
 		{
-			printf("ERROR1\n");
+			fprintf(stderr, "ERROR1\n");
 			return 1;
 		}
 		oldmode = armcpu_switchMode(cpu, SYS);
@@ -5116,7 +5116,7 @@
 	{
 		if (cpu->CPSR.bits.mode == USR || cpu->CPSR.bits.mode == SYS)
 		{
-			printf("ERROR1\n");
+			fprintf(stderr, "ERROR1\n");
 			return 1;
 		}
 		oldmode = armcpu_switchMode(cpu, SYS);
@@ -5174,7 +5174,7 @@
 	{
 		if (cpu->CPSR.bits.mode == USR || cpu->CPSR.bits.mode == SYS)
 		{
-			printf("ERROR1\n");
+			fprintf(stderr, "ERROR1\n");
 			return 1;
 		}
 		oldmode = armcpu_switchMode(cpu, SYS);
@@ -5233,7 +5233,7 @@
 	{
 		if (cpu->CPSR.bits.mode == USR || cpu->CPSR.bits.mode == SYS)
 		{
-			printf("ERROR1\n");
+			fprintf(stderr, "ERROR1\n");
 			return 1;
 		}
 		oldmode = armcpu_switchMode(cpu, SYS);
@@ -5289,7 +5289,7 @@
 	{
 		if (cpu->CPSR.bits.mode == USR || cpu->CPSR.bits.mode == SYS)
 		{
-			printf("ERROR1\n");
+			fprintf(stderr, "ERROR1\n");
 			return 1;
 		}
 		oldmode = armcpu_switchMode(cpu, SYS);
@@ -5348,7 +5348,7 @@
 	{
 		if (cpu->CPSR.bits.mode == USR || cpu->CPSR.bits.mode == SYS)
 		{
-			printf("ERROR1\n");
+			fprintf(stderr, "ERROR1\n");
 			return 1;
 		}
 		oldmode = armcpu_switchMode(cpu, SYS);
@@ -5359,7 +5359,7 @@
 	if (BIT15(i))
 	{
 		if (BIT_N(i, REG_POS(i, 16)))
-			printf("error1_1\n");
+			fprintf(stderr, "error1_1\n");
 		uint32_t tmp = READ32(cpu->mem_if->data, start);
 		registres[15] = tmp & (0XFFFFFFFC | (BIT0(tmp) << 1));
 		c += MMU_memAccessCycles<PROCNUM, 32, MMU_AD_READ>(start);
@@ -5409,7 +5409,7 @@
 	{
 		if (cpu->CPSR.bits.mode == USR || cpu->CPSR.bits.mode == SYS)
 		{
-			printf("ERROR1\n");
+			fprintf(stderr, "ERROR1\n");
 			return 1;
 		}
 		oldmode = armcpu_switchMode(cpu, SYS);
@@ -5420,7 +5420,7 @@
 	if (BIT15(i))
 	{
 		if (BIT_N(i, REG_POS(i, 16)))
-			printf("error1_2\n");
+			fprintf(stderr, "error1_2\n");
 		start -= 4;
 		uint32_t tmp = READ32(cpu->mem_if->data, start);
 		c += MMU_memAccessCycles<PROCNUM, 32, MMU_AD_READ>(start);
@@ -5811,7 +5811,7 @@
 	uint32_t addr = cpu->R[REG_POS(i, 16)];
 	uint32_t index;
 
-	//printf("%s POST\n", BIT5(i)?"STRD":"LDRD");
+	//fprintf(stderr, "%s POST\n", BIT5(i)?"STRD":"LDRD");
 	/* I bit - immediate or register */
 	if (BIT22(i))
 		index = IMM_OFF;
@@ -5853,7 +5853,7 @@
 	uint32_t addr = cpu->R[REG_POS(i, 16)];
 	uint32_t index;
 
-	//printf("%s PRE\n", BIT5(i)?"STRD":"LDRD");
+	//fprintf(stderr, "%s PRE\n", BIT5(i)?"STRD":"LDRD");
 	// I bit - immediate or register
 	if (BIT22(i))
 		index = IMM_OFF;
@@ -6059,7 +6059,7 @@
 	if (cpu->swi_tab && !bypassBuiltinSWI)
 	{
 		swinum &= 0x1F;
-		//printf("%d ARM SWI %d \n",PROCNUM,swinum);
+		//fprintf(stderr, "%d ARM SWI %d \n",PROCNUM,swinum);
 		return cpu->swi_tab[swinum]() + 3;
 	}
 	else
@@ -6105,7 +6105,7 @@
 	/*
 	static uint32_t last_bkpt = 0xFFFFFFFF;
 	if(i != last_bkpt)
-		printf("ARM OP_BKPT triggered\n");
+		fprintf(stderr, "ARM OP_BKPT triggered\n");
 	last_bkpt = i;
 
 	//this is not 100% correctly emulated, but it does the job
@@ -6113,7 +6113,7 @@
 	return 4;
 	*/
 
-	printf("ARM OP_BKPT triggered\n");
+	fprintf(stderr, "ARM OP_BKPT triggered\n");
 	Status_Reg tmp = cpu->CPSR;
 	armcpu_switchMode(cpu, ABT); // enter abt mode
 	cpu->R[14] = cpu->instruct_adr + 4;

--- a/src/in_2sf/desmume/arm_jit.cpp
+++ b/src/in_2sf/desmume/arm_jit.cpp
@@ -34,7 +34,7 @@
 #include "instruction_attributes.h"
 #include "MMU.h"
 #include "MMU_timing.h"
-#include "utils/AsmJit/asmjit.h"
+#include "utils/AsmJit/AsmJit.h"
 #include "arm_jit.h"
 #include "bios.h"
 
@@ -56,14 +56,14 @@
 	GpVar txt = c.newGpVar(kVarTypeIntPtr); \
 	GpVar data = c.newGpVar(kVarTypeIntPtr); \
 	GpVar io = c.newGpVar(kVarTypeInt32); \
-	c.lea(io, x86::dword_ptr_abs(stdout)); \
+	c.lea(io, x86::dword_ptr_abs(stderr)); \
 	c.lea(txt, x86::dword_ptr_abs(&buf)); \
 	c.mov(data, *reinterpret_cast<GpVar *>(&val)); \
-	auto prn = c.addCall(imm_ptr(fprintf), ASMJIT_CALL_CONV, FuncBuilder3<void, void *, void *, uint32_t>()); \
+	auto prn = c.addCall(imm_ptr(fprintf), ASMJIT_STDLIB_CALL_CONV, FuncBuilder3<void, void *, void *, uint32_t>()); \
 	prn->setArg(0, io); \
 	prn->setArg(1, txt); \
 	prn->setArg(2, data); \
-	auto prn_flush = c.addCall(imm_ptr(fflush), ASMJIT_CALL_CONV, FuncBuilder1<void, void *>()); \
+	auto prn_flush = c.addCall(imm_ptr(fflush), ASMJIT_STDLIB_CALL_CONV, FuncBuilder1<void, void *>()); \
 	prn_flush->setArg(0, io); \
 }
 #else
@@ -194,9 +194,9 @@
 DS_ALIGN(4096) static uint8_t scratchpad[1 << 25];
 static uint8_t *scratchptr;
 
-struct ASMJIT_API StaticCodeGenerator : public Context
-{
-	StaticCodeGenerator()
+struct StaticCodeSetup
+{
+	StaticCodeSetup()
 	{
 		scratchptr = scratchpad;
 		int align = reinterpret_cast<uintptr_t>(scratchpad) & (sysconf(_SC_PAGESIZE) - 1);
@@ -207,32 +207,10 @@
 			abort();
 		}
 	}
-
-	uint32_t generate(void **dest, Assembler *assembler)
-	{
-		uintptr_t size = assembler->getCodeSize();
-		if (!size)
-		{
-			*dest = nullptr;
-			return kErrorNoFunction;
-		}
-		if (size > reinterpret_cast<uintptr_t>(scratchpad + sizeof(scratchpad) - scratchptr))
-		{
-			fprintf(stderr, "Out of memory for asmjit. Clearing code cache.\n");
-			arm_jit_reset(true);
-			// If arm_jit_reset didn't involve recompiling op_cmp, we could keep the current function.
-			*dest = nullptr;
-			return kErrorOk;
-		}
-		void *p = scratchptr;
-		size = assembler->relocCode(p);
-		scratchptr += size;
-		*dest = p;
-		return kErrorOk;
-	}
 };
 
-static StaticCodeGenerator codegen;
+static StaticCodeSetup setup;
+static StaticRuntime codegen(scratchpad, sizeof(scratchpad));
 static X86Compiler c(&codegen);
 #else
 static JitRuntime runtime;
@@ -280,7 +258,7 @@
 // sequencer.reschedule = true;
 #define changeCPSR \
 { \
-	auto ctxCPSR = c.addCall(imm_ptr(NDS_Reschedule), ASMJIT_CALL_CONV, FuncBuilder0<void>()); \
+	auto ctxCPSR = c.addCall(imm_ptr(NDS_Reschedule), ASMJIT_STDLIB_CALL_CONV, FuncBuilder0<void>()); \
 }
 
 #if PROFILER_JIT_LEVEL > 0
@@ -417,7 +395,7 @@
 	c.mov(SPSR, cpu_ptr(SPSR.val)); \
 	c.mov(tmp, SPSR); \
 	c.and_(tmp, 0x1F); \
-	auto ctx = c.addCall(imm_ptr(armcpu_switchMode), ASMJIT_CALL_CONV, FuncBuilder2<void, void *, uint8_t>()); \
+	auto ctx = c.addCall(imm_ptr(armcpu_switchMode), ASMJIT_STDLIB_CALL_CONV, FuncBuilder2<void, void *, uint8_t>()); \
 	ctx->setArg(0, bb_cpu); \
 	ctx->setArg(1, tmp); \
 	c.mov(cpu_ptr(CPSR.val), SPSR); \
@@ -1187,10 +1165,10 @@
 //   QADD / QDADD / QSUB / QDSUB
 // -----------------------------------------------------------------------------
 // TODO
-static int OP_QADD(uint32_t i) { printf("JIT: unimplemented OP_QADD\n"); return 0; }
-static int OP_QSUB(uint32_t i) { printf("JIT: unimplemented OP_QSUB\n"); return 0; }
-static int OP_QDADD(uint32_t i) { printf("JIT: unimplemented OP_QDADD\n"); return 0; }
-static int OP_QDSUB(uint32_t i) { printf("JIT: unimplemented OP_QDSUB\n"); return 0; }
+static int OP_QADD(uint32_t i) { fprintf(stderr, "JIT: unimplemented OP_QADD\n"); return 0; }
+static int OP_QSUB(uint32_t i) { fprintf(stderr, "JIT: unimplemented OP_QSUB\n"); return 0; }
+static int OP_QDADD(uint32_t i) { fprintf(stderr, "JIT: unimplemented OP_QDADD\n"); return 0; }
+static int OP_QDSUB(uint32_t i) { fprintf(stderr, "JIT: unimplemented OP_QDSUB\n"); return 0; }
 
 // -----------------------------------------------------------------------------
 //   MUL
@@ -1423,7 +1401,7 @@
 			{ \
 				c.mov(mode, rhs); \
 				c.and_(mode, 0x1F); \
-				auto ctx = c.addCall(imm_ptr(armcpu_switchMode), ASMJIT_CALL_CONV, \
+				auto ctx = c.addCall(imm_ptr(armcpu_switchMode), ASMJIT_STDLIB_CALL_CONV, \
 					FuncBuilder2<void, void *, uint8_t>()); \
 				ctx->setArg(0, bb_cpu); \
 				ctx->setArg(1, mode); \
@@ -1492,7 +1470,7 @@
 		/* armcpu_switchMode */ \
 		c.mov(mode, rhs); \
 		c.and_(mode, 0x1F); \
-		auto ctx = c.addCall(imm_ptr(armcpu_switchMode), ASMJIT_CALL_CONV, \
+		auto ctx = c.addCall(imm_ptr(armcpu_switchMode), ASMJIT_STDLIB_CALL_CONV, \
 			FuncBuilder2<void, void *, uint8_t>()); \
 		ctx->setArg(0, bb_cpu); \
 		ctx->setArg(1, mode); \
@@ -1925,12 +1903,12 @@
 
 	if (Rd_num == 14)
 	{
-		printf("OP_LDRD_STRD_POST_INDEX: use R14!!!!\n");
+		fprintf(stderr, "OP_LDRD_STRD_POST_INDEX: use R14!!!!\n");
 		return 0; // TODO: exception
 	}
 	if (Rd_num & 0x1)
 	{
-		printf("OP_LDRD_STRD_POST_INDEX: ERROR!!!!\n");
+		fprintf(stderr, "OP_LDRD_STRD_POST_INDEX: ERROR!!!!\n");
 		return 0; // TODO: exception
 	}
 	GpVar Rd = c.newGpVar(kVarTypeInt32);
@@ -1966,12 +1944,12 @@
 
 	if (Rd_num == 14)
 	{
-		printf("OP_LDRD_STRD_OFFSET_PRE_INDEX: use R14!!!!\n");
+		fprintf(stderr, "OP_LDRD_STRD_OFFSET_PRE_INDEX: use R14!!!!\n");
 		return 0; // TODO: exception
 	}
 	if (Rd_num & 0x1)
 	{
-		printf("OP_LDRD_STRD_OFFSET_PRE_INDEX: ERROR!!!!\n");
+		fprintf(stderr, "OP_LDRD_STRD_OFFSET_PRE_INDEX: ERROR!!!!\n");
 		return 0; // TODO: exception
 	}
 	GpVar Rd = c.newGpVar(kVarTypeInt32);
@@ -2089,7 +2067,7 @@
 #define LDM_INLINE inline
 #endif
 
-template<int PROCNUM, bool store, int dir> static LDM_INLINE FASTCALL uint32_t OP_LDM_STM_generic(uint32_t adr, uint64_t regs, int n)
+template<int PROCNUM, bool store, int dir> static LDM_INLINE LDM_FASTCALL uint32_t OP_LDM_STM_generic(uint32_t adr, uint64_t regs, int n)
 {
 	uint32_t cycles = 0;
 	adr &= ~3;
@@ -2112,7 +2090,7 @@
 #define ADV_CYCLES
 #endif
 
-template<int PROCNUM, bool store, int dir> static LDM_INLINE FASTCALL uint32_t OP_LDM_STM_other(uint32_t adr, uint64_t regs, int n)
+template<int PROCNUM, bool store, int dir> static LDM_INLINE LDM_FASTCALL uint32_t OP_LDM_STM_other(uint32_t adr, uint64_t regs, int n)
 {
 	uint32_t cycles = 0;
 	adr &= ~3;
@@ -2142,7 +2120,7 @@
 	return cycles;
 }
 
-template<int PROCNUM, bool store, int dir, bool null_compiled> static FORCEINLINE FASTCALL uint32_t OP_LDM_STM_main(uint32_t adr, uint64_t regs, int n, uint8_t *ptr, uint32_t cycles)
+template<int PROCNUM, bool store, int dir, bool null_compiled> static FORCEINLINE LDM_FASTCALL uint32_t OP_LDM_STM_main(uint32_t adr, uint64_t regs, int n, uint8_t *ptr, uint32_t cycles)
 {
 #ifdef ENABLE_ADVANCED_TIMING
 	cycles = 0;
@@ -2188,7 +2166,7 @@
 #undef ADV_CYCLES
 }
 
-template<int PROCNUM, bool store, int dir> static uint32_t FASTCALL OP_LDM_STM(uint32_t adr, uint64_t regs, int n)
+template<int PROCNUM, bool store, int dir> static uint32_t LDM_FASTCALL OP_LDM_STM(uint32_t adr, uint64_t regs, int n)
 {
 	// TODO use classify_adr?
 	uint32_t cycles;
@@ -2227,7 +2205,8 @@
 	return OP_LDM_STM_main<PROCNUM, store, dir, store>(adr, regs, n, ptr, cycles);
 }
 
-typedef uint32_t FASTCALL (*LDMOpFunc)(uint32_t, uint64_t, int);
+typedef uint32_t LDM_FASTCALL (*LDMOpFunc)(uint32_t, uint64_t, int);
+
 static const LDMOpFunc op_ldm_stm_tab[2][2][2] =
 {
 	{
@@ -2260,7 +2239,7 @@
 		GpVar regs_hi = c.newGpVar(kVarTypeInt32);
 		c.mov(regs_lo, get_reg_list(bitmask, dir) & 0xFFFFFFFF);
 		c.mov(regs_hi, get_reg_list(bitmask, dir) >> 32);
-		auto ctx = c.addCall(imm_ptr(op_ldm_stm_tab[PROCNUM][store][dir > 0]), ASMJIT_CALL_CONV,
+		auto ctx = c.addCall(imm_ptr(op_ldm_stm_tab[PROCNUM][store][dir > 0]), ASMJIT_STDLIB_CALL_CONV,
 			FuncBuilder4<uint32_t, uint32_t, uint32_t, uint32_t, int>());
 		ctx->setArg(0, adr);
 		ctx->setArg(1, regs_lo);
@@ -2339,7 +2318,7 @@
 	uint32_t pop = popcount(bitmask);
 	bool bit15 = !!BIT15(i);
 
-	//printf("ARM%c: %s R%d:%08X, bitmask %02X\n", PROCNUM?'7':'9', (store?"STM":"LDM"), REG_POS(i, 16), cpu->R[REG_POS(i, 16)], bitmask);
+	//fprintf(stderr, "ARM%c: %s R%d:%08X, bitmask %02X\n", PROCNUM?'7':'9', (store?"STM":"LDM"), REG_POS(i, 16), cpu->R[REG_POS(i, 16)], bitmask);
 	uint32_t adr_first = cpu->R[REG_POS(i, 16)];
 
 	GpVar adr = c.newGpVar(kVarTypeInt32);
@@ -2351,10 +2330,10 @@
 
 	if (!bit15 || store)
 	{
-		//if((cpu->CPSR.bits.mode==USR)||(cpu->CPSR.bits.mode==SYS)) { printf("ERROR1\n"); return 1; }
+		//if((cpu->CPSR.bits.mode==USR)||(cpu->CPSR.bits.mode==SYS)) { fprintf(stderr, "ERROR1\n"); return 1; }
 		//oldmode = armcpu_switchMode(cpu, SYS);
 		c.mov(oldmode, SYS);
-		auto ctx = c.addCall(imm_ptr(armcpu_switchMode), ASMJIT_CALL_CONV,
+		auto ctx = c.addCall(imm_ptr(armcpu_switchMode), ASMJIT_STDLIB_CALL_CONV,
 			FuncBuilder2<uint32_t, uint8_t *, uint8_t>());
 		ctx->setArg(0, bb_cpu);
 		ctx->setArg(1, oldmode);
@@ -2366,7 +2345,7 @@
 	if (!bit15 || store)
 	{
 		//armcpu_switchMode(cpu, oldmode);
-		auto ctx = c.addCall(imm_ptr(armcpu_switchMode), ASMJIT_CALL_CONV,
+		auto ctx = c.addCall(imm_ptr(armcpu_switchMode), ASMJIT_STDLIB_CALL_CONV,
 			FuncBuilder2<void, uint8_t *, uint8_t>());
 		ctx->setArg(0, bb_cpu);
 		ctx->setArg(1, oldmode);
@@ -2487,7 +2466,7 @@
 // -----------------------------------------------------------------------------
 #define maskPrecalc \
 { \
-	auto ctxM = c.addCall(imm_ptr(maskPrecalc), ASMJIT_CALL_CONV, FuncBuilder0<void>()); \
+	auto ctxM = c.addCall(imm_ptr(maskPrecalc), ASMJIT_STDLIB_CALL_CONV, FuncBuilder0<void>()); \
 }
 static int OP_MCR(uint32_t i)
 {
@@ -2498,12 +2477,12 @@
 	if (cpnum != 15)
 	{
 		// TODO - exception?
-		printf("JIT: MCR P%i, 0, R%i, C%i, C%i, %i, %i (don't allocated coprocessor)\n", cpnum, REG_POS(i, 12), REG_POS(i, 16), REG_POS(i, 0), (i >> 21) & 0x7, (i >> 5) & 0x7);
+		fprintf(stderr, "JIT: MCR P%i, 0, R%i, C%i, C%i, %i, %i (don't allocated coprocessor)\n", cpnum, REG_POS(i, 12), REG_POS(i, 16), REG_POS(i, 0), (i >> 21) & 0x7, (i >> 5) & 0x7);
 		return 2;
 	}
 	if (REG_POS(i, 12) == 15)
 	{
-		printf("JIT: MCR Rd=R15\n");
+		fprintf(stderr, "JIT: MCR Rd=R15\n");
 		return 2;
 	}
 
@@ -2723,7 +2702,7 @@
 
 	if (bUnknown)
 	{
-		//printf("Unknown MCR command: MRC P15, 0, R%i, C%i, C%i, %i, %i\n", REG_POS(i, 12), CRn, CRm, opcode1, opcode2);
+		//fprintf(stderr, "Unknown MCR command: MRC P15, 0, R%i, C%i, C%i, %i, %i\n", REG_POS(i, 12), CRn, CRm, opcode1, opcode2);
 		return 1;
 	}
 
@@ -2738,7 +2717,7 @@
 	uint32_t cpnum = REG_POS(i, 8);
 	if (cpnum != 15)
 	{
-		printf("MRC P%i, 0, R%i, C%i, C%i, %i, %i (don't allocated coprocessor)\n", cpnum, REG_POS(i, 12), REG_POS(i, 16), REG_POS(i, 0), (i>>21)&0x7, (i>>5)&0x7);
+		fprintf(stderr, "MRC P%i, 0, R%i, C%i, C%i, %i, %i (don't allocated coprocessor)\n", cpnum, REG_POS(i, 12), REG_POS(i, 16), REG_POS(i, 0), (i>>21)&0x7, (i>>5)&0x7);
 		return 2;
 	}
 
@@ -2928,7 +2907,7 @@
 
 	if (bUnknown)
 	{
-		//printf("Unknown MRC command: MRC P15, 0, R%i, C%i, C%i, %i, %i\n", REG_POS(i, 12), CRn, CRm, opcode1, opcode2);
+		//fprintf(stderr, "Unknown MRC command: MRC P15, 0, R%i, C%i, C%i, %i, %i\n", REG_POS(i, 12), CRn, CRm, opcode1, opcode2);
 		return 1;
 	}
 
@@ -2956,7 +2935,7 @@
 		// TODO:
 		return 0;
 #else
-		auto ctx = c.addCall(imm_ptr(ARM_swi_tab[PROCNUM][swinum]), ASMJIT_CALL_CONV, FuncBuilder0<uint32_t>());
+		auto ctx = c.addCall(imm_ptr(ARM_swi_tab[PROCNUM][swinum]), ASMJIT_STDLIB_CALL_CONV, FuncBuilder0<uint32_t>());
 		ctx->setRet(0, bb_cycles);
 		c.add(bb_cycles, 3);
 		return 1;
@@ -2970,7 +2949,7 @@
 	c.mov(oldCPSR, CPSR);
 	JIT_COMMENT("enter SVC mode");
 	c.mov(mode, imm(SVC));
-	auto ctx = c.addCall(imm_ptr(armcpu_switchMode), ASMJIT_CALL_CONV, FuncBuilder2<void, void *, uint8_t>());
+	auto ctx = c.addCall(imm_ptr(armcpu_switchMode), ASMJIT_STDLIB_CALL_CONV, FuncBuilder2<void, void *, uint8_t>());
 	ctx->setArg(0, bb_cpu);
 	ctx->setArg(1, mode);
 	c.unuse(mode);
@@ -2996,7 +2975,7 @@
 // -----------------------------------------------------------------------------
 //   BKPT
 // -----------------------------------------------------------------------------
-static int OP_BKPT(uint32_t i) { printf("JIT: unimplemented OP_BKPT\n"); return 0; }
+static int OP_BKPT(uint32_t i) { fprintf(stderr, "JIT: unimplemented OP_BKPT\n"); return 0; }
 
 // -----------------------------------------------------------------------------
 //   THUMB
@@ -3625,7 +3604,7 @@
 	uint32_t pop = popcount(bitmask);
 
 	//if (BIT_N(i, _REG_NUM(i, 8)))
-	//	printf("WARNING - %sIA with Rb in Rlist (THUMB)\n", store?"STM":"LDM");
+	//	fprintf(stderr, "WARNING - %sIA with Rb in Rlist (THUMB)\n", store?"STM":"LDM");
 
 	GpVar adr = c.newGpVar(kVarTypeInt32);
 	c.mov(adr, reg_pos_thumb(8));
@@ -4025,7 +4004,7 @@
 
 	if (!JIT_MAPPED(start_adr & 0x0FFFFFFF, PROCNUM))
 	{
-		printf("JIT: use unmapped memory address %08X\n", start_adr);
+		fprintf(stderr, "JIT: use unmapped memory address %08X\n", start_adr);
 		execute = false;
 		return 1;
 	}
@@ -4156,7 +4135,7 @@
 #endif
 	c.endFunc();
 
-	ArmOpCompiled f = static_cast<ArmOpCompiled>(c.make());
+	ArmOpCompiled f = (ArmOpCompiled)(c.make());
 	if (c.getError())
 	{
 		fprintf(stderr, "JIT error: %s\n", ErrorUtil::asString(c.getError()));
@@ -4205,13 +4184,14 @@
 #ifdef HAVE_STATIC_CODE_BUFFER
 	scratchptr = scratchpad;
 #endif
-	printf("CPU mode: %s\n", enable ? "JIT" : "Interpreter");
+	fprintf(stderr, "CPU mode: %s\n", enable ? "JIT" : "Interpreter");
 
 	if (enable)
 	{
-		printf("JIT max block size %d instruction(s)\n", CommonSettings.jit_max_block_size);
+		fprintf(stderr, "JIT max block size %d instruction(s)\n", CommonSettings.jit_max_block_size);
 #ifdef MAPPED_JIT_FUNCS
 		// these pointers are allocated by asmjit and need freeing
+#ifndef HAVE_STATIC_CODE_BUFFER
 		#define JITFREE(x)  for (size_t iii = 0; iii < ARRAY_SIZE((x)); ++iii) if ((x)[iii]) runtime.getMemMgr()->release(reinterpret_cast<void *>((x)[iii])); memset((x), 0, sizeof((x)));
 			JITFREE(JIT.MAIN_MEM);
 			JITFREE(JIT.SWIRAM);
@@ -4223,6 +4203,7 @@
 			JITFREE(JIT.ARM7_WIRAM);
 			JITFREE(JIT.ARM7_WRAM);
 		#undef JITFREE
+#endif
 
 		memset(recompile_counts, 0, sizeof(recompile_counts));
 		init_jit_mem();
@@ -4268,7 +4249,7 @@
 void arm_jit_close()
 {
 #if PROFILER_JIT_LEVEL > 0
-	printf("Generating profile report...");
+	fprintf(stderr, "Generating profile report...");
 
 	for (uint8_t proc = 0; proc < 2; ++proc)
 	{
@@ -4393,7 +4374,7 @@
 		}
 #endif
 	}
-	printf(" done.\n");
+	fprintf(stderr, " done.\n");
 #endif
 }
 #endif // HAVE_JIT

--- a/src/in_2sf/desmume/arm_jit.h
+++ b/src/in_2sf/desmume/arm_jit.h
@@ -27,7 +27,7 @@
 void arm_jit_sync();
 template<int PROCNUM> uint32_t arm_jit_compile();
 
-#if defined(_WINDOWS) || defined(DESMUME_COCOA)
+#if defined(_WINDOWS) || defined(DESMUME_COCOA) || defined(HAVE_JIT)
 # define MAPPED_JIT_FUNCS
 #endif
 

--- a/src/in_2sf/desmume/armcpu.cpp
+++ b/src/in_2sf/desmume/armcpu.cpp
@@ -139,7 +139,7 @@
 			armcpu->SPSR_und = armcpu->SPSR;
 			break;
 		default:
-			printf("switchMode: WRONG mode %02X\n",mode);
+			fprintf(stderr, "switchMode: WRONG mode %02X\n",mode);
 	}
 
 	switch (mode)
@@ -275,7 +275,7 @@
 	cpu->changeCPSR();
 	cpu->R[15] = cpu->intVector + number;
 	cpu->next_instruction = cpu->R[15];
-	printf("armcpu_exception!\n");
+	fprintf(stderr, "armcpu_exception!\n");
 
 	// HOW DOES THIS WORTK WITHOUT A PREFETCH, LIKE IRQ BELOW?
 	// I REALLY WISH WE DIDNT PREFETCH BEFORE EXECUTING
@@ -329,7 +329,7 @@
 
 	//cFetch = armcpu_prefetch(&ARMPROC);
 
-	//printf("%d: %08X\n",PROCNUM,ARMPROC.instruct_adr);
+	//fprintf(stderr, "%d: %08X\n",PROCNUM,ARMPROC.instruct_adr);
 
 	if (!ARMPROC.CPSR.bits.T)
 	{

--- a/src/in_2sf/desmume/armcpu.h
+++ b/src/in_2sf/desmume/armcpu.h
@@ -209,7 +209,7 @@
 	int stalled;
 
 #if defined(_M_X64) || defined(__x86_64__)
-	u8 cond_table[16 * 16];
+	uint8_t cond_table[16 * 16];
 #endif
 };
 

--- a/src/in_2sf/desmume/bios.cpp
+++ b/src/in_2sf/desmume/bios.cpp
@@ -23,6 +23,17 @@
 
 #define cpu (&ARMPROC)
 #define TEMPLATE template<int PROCNUM>
+
+struct CompressionHeader
+{
+public:
+	CompressionHeader(u32 _value) : value(_value) {}
+	u32 DataSize() const { return value&15; }
+	u32 Type() const { return (value>>4)&15; }
+	u32 DecompressedSize() const { return value>>24; }
+private:
+	u32 value;
+};
 
 static const uint16_t getsinetbl[] =
 {
@@ -673,7 +684,7 @@
 {
 	uint32_t source = cpu->R[0];
 	uint32_t dest = cpu->R[1];
-	uint32_t header = _MMU_read08<PROCNUM>(source);
+	uint32_t header = _MMU_read32<PROCNUM>(source);
 	source += 4;
 
 	if (!(source & 0xe000000) || !((source + ((header >> 8) & 0x1fffff)) & 0xe000000))
@@ -688,7 +699,7 @@
 	int len = header >> 8;
 
 	uint32_t mask = 0x80000000;
-	uint32_t data = _MMU_read08<PROCNUM>(source);
+	uint32_t data = _MMU_read32<PROCNUM>(source);
 	source += 4;
 
 	int pos = 0;
@@ -738,7 +749,7 @@
 				{
 					byteCount = 0;
 					byteShift = 0;
-					_MMU_write08<PROCNUM>(dest, writeValue & 0xFF);
+					_MMU_write32<PROCNUM>(dest, writeValue);
 					writeValue = 0;
 					dest += 4;
 					len -= 4;
@@ -748,7 +759,7 @@
 			if (!mask)
 			{
 				mask = 0x80000000;
-				data = _MMU_read08<PROCNUM>(source);
+				data = _MMU_read32<PROCNUM>(source);
 				source += 4;
 			}
 		}
@@ -801,7 +812,7 @@
 					{
 						byteCount = 0;
 						byteShift = 0;
-						_MMU_write08<PROCNUM>(dest, writeValue & 0xFF);
+						_MMU_write32<PROCNUM>(dest, writeValue);
 						dest += 4;
 						writeValue = 0;
 						len -= 4;
@@ -815,7 +826,7 @@
 			if (!mask)
 			{
 				mask = 0x80000000;
-				data = _MMU_read08<PROCNUM>(source);
+				data = _MMU_read32<PROCNUM>(source);
 				source += 4;
 			}
 		}
@@ -856,7 +867,7 @@
 	}
 
 	int revbits = 8 - bits;
-	uint32_t base = _MMU_read08<PROCNUM>(header + 4);
+	uint32_t base = _MMU_read32<PROCNUM>(header + 4);
 	int addBase = base & 0x80000000 ? 1 : 0;
 	base &= 0x7fffffff;
 
@@ -875,21 +886,21 @@
 		{
 			if (bitcount >= 8)
 				break;
-			uint32_t d = b & mask;
-			uint32_t temp = d >> bitcount;
-			if (!temp && addBase)
-				temp += base;
+      uint32_t temp = b & mask;
+      if (temp || addBase) {
+        temp += base;
+      }
 			data |= temp << bitwritecount;
 			bitwritecount += dataSize;
 			if (bitwritecount >= 32)
 			{
-				_MMU_write08<PROCNUM>(dest, data);
+				_MMU_write32<PROCNUM>(dest, data);
 				dest += 4;
 				data = 0;
 				bitwritecount = 0;
 			}
-			mask <<= bits;
 			bitcount += bits;
+      b >>= bits;
 		}
 	}
 	return 1;
@@ -899,13 +910,15 @@
 {
 	uint32_t source = cpu->R[0];
 	uint32_t dest = cpu->R[1];
-	uint32_t header = _MMU_read08<PROCNUM>(source);
+	CompressionHeader header(_MMU_read32<PROCNUM>(source));
 	source += 4;
 
-	if (!(source & 0xe000000) || !((source + ((header >> 8) & 0x1fffff)) & 0xe000000))
-		return 0;
-
-	int len = header >> 8;
+	int len = header.DecompressedSize();
+
+  if (PROCNUM == ARMCPU_ARM7) {
+    if (!(source & 0xe000000) || !((source + (len & 0x1fffff)) & 0xe000000))
+      return 0;
+  }
 
 	uint8_t data = _MMU_read08<PROCNUM>(source++);
 	_MMU_write08<PROCNUM>(dest++, data);
@@ -925,13 +938,10 @@
 {
 	uint32_t source = cpu->R[0];
 	uint32_t dest = cpu->R[1];
-	uint32_t header = _MMU_read08<PROCNUM>(source);
+	CompressionHeader header(_MMU_read32<PROCNUM>(source));
 	source += 4;
 
-	if (!(source & 0xe000000) || !((source + ((header >> 8) & 0x1fffff)) & 0xe000000))
-		return 0;
-
-	int len = header >> 8;
+	int len = header.DecompressedSize();
 
 	uint16_t data = _MMU_read16<PROCNUM>(source);
 	source += 2;
@@ -957,9 +967,15 @@
 	return 1;
 }
 
-TEMPLATE static uint32_t setHaltCR()
-{
-	_MMU_write08<PROCNUM>(0x4000300+cpu->proc_ID, cpu->R[0] & 0xFF);
+TEMPLATE static uint32_t CustomPost()
+{
+  _MMU_write08<PROCNUM>(REG_POSTFLG, cpu->R[0]);
+  return 1;
+}
+
+TEMPLATE static uint32_t CustomHalt()
+{
+	_MMU_write08<PROCNUM>(REG_HALTCNT, cpu->R[2]);
 	return 1;
 }
 
@@ -968,7 +984,7 @@
 	// ds returns garbage according to gbatek, but we must protect ourselves
 	if (cpu->R[0] >= ARRAY_SIZE(getsinetbl))
 	{
-		printf("Invalid SWI getSineTab: %08X\n", cpu->R[0]);
+		fprintf(stderr, "Invalid SWI getSineTab: %08X\n", cpu->R[0]);
 		return 1;
 	}
 
@@ -981,7 +997,7 @@
 	// ds returns garbage according to gbatek, but we must protect ourselves
 	if (cpu->R[0] >= ARRAY_SIZE(getpitchtbl))
 	{
-		printf("Invalid SWI getPitchTab: %08X\n", cpu->R[0]);
+		fprintf(stderr, "Invalid SWI getPitchTab: %08X\n", cpu->R[0]);
 		return 1;
 	}
 
@@ -994,7 +1010,7 @@
 	// ds returns garbage according to gbatek, but we must protect ourselves
 	if (cpu->R[0] >= ARRAY_SIZE(getvoltbl))
 	{
-		printf("Invalid SWI getVolumeTab: %08X\n", cpu->R[0]);
+		fprintf(stderr, "Invalid SWI getVolumeTab: %08X\n", cpu->R[0]);
 		return 1;
 	}
 
@@ -1097,7 +1113,7 @@
 		bios_nop<ARMCPU_ARM9>,             // 0x1C
 		bios_nop<ARMCPU_ARM9>,             // 0x1D
 		bios_nop<ARMCPU_ARM9>,             // 0x1E
-		setHaltCR<ARMCPU_ARM9>,            // 0x1F
+		CustomPost<ARMCPU_ARM9>,           // 0x1F
 	},
 	{
 		bios_nop<ARMCPU_ARM7>,             // 0x00
@@ -1122,7 +1138,7 @@
 		UnCompHuffman<ARMCPU_ARM7>,        // 0x13
 		RLUnCompWram<ARMCPU_ARM7>,         // 0x14
 		RLUnCompVram<ARMCPU_ARM7>,         // 0x15
-		Diff8bitUnFilterWram<ARMCPU_ARM7>, // 0x16
+		bios_nop<ARMCPU_ARM7>,             // 0x16
 		bios_nop<ARMCPU_ARM7>,             // 0x17
 		bios_nop<ARMCPU_ARM7>,             // 0x18
 		bios_nop<ARMCPU_ARM7>,             // 0x19
@@ -1131,7 +1147,7 @@
 		getVolumeTab<ARMCPU_ARM7>,         // 0x1C
 		getBootProcs<ARMCPU_ARM7>,         // 0x1D
 		bios_nop<ARMCPU_ARM7>,             // 0x1E
-		setHaltCR<ARMCPU_ARM7>,            // 0x1F
+		CustomHalt<ARMCPU_ARM7>,           // 0x1F
 	}
 };
 

--- a/src/in_2sf/desmume/cp15.cpp
+++ b/src/in_2sf/desmume/cp15.cpp
@@ -24,7 +24,7 @@
 
 bool armcp15_t::reset(armcpu_t *c)
 {
-	//printf("CP15 Reset\n");
+	//fprintf(stderr, "CP15 Reset\n");
 	this->cpu = c;
 	this->IDCode = 0x41059461;
 	this->cacheType = 0x0F0D2112;
@@ -225,7 +225,7 @@
 {
 	if (!this->cpu)
 	{
-		printf("ERROR: cp15 don\'t allocated\n");
+		fprintf(stderr, "ERROR: cp15 don\'t allocated\n");
 		return false;
 	}
 	if (this->cpu->CPSR.bits.mode == USR)
@@ -371,7 +371,7 @@
 {
 	if (!this->cpu)
 	{
-		printf("ERROR: cp15 don\'t allocated\n");
+		fprintf(stderr, "ERROR: cp15 don\'t allocated\n");
 		return false;
 	}
 	if (this->cpu->CPSR.bits.mode == USR)

--- a/src/in_2sf/desmume/mc.cpp
+++ b/src/in_2sf/desmume/mc.cpp
@@ -115,7 +115,7 @@
 			// copy User Settings 1 to User Settings 0 area
 			memcpy(&mc->data[0x3FE00], &mc->data[0x3FF00], 0x100);
 
-			printf("Firmware: save config");
+			fprintf(stderr, "Firmware: save config");
 			FILE *fp = fopen(mc->userfile, "wb");
 			if (fp)
 			{
@@ -124,15 +124,15 @@
 					if (fwrite(&mc->data[0x0002A], 1, 0x1D6, fp) == 0x1D6) // WiFi Settings
 					{
 						if (fwrite(&mc->data[0x3FA00], 1, 0x300, fp) == 0x300)  // WiFi AP Settings
-							printf(" - done\n");
+							fprintf(stderr, " - done\n");
 						else
-							printf(" - failed\n");
+							fprintf(stderr, " - failed\n");
 					}
 				}
 				fclose(fp);
 			}
 			else
-				printf(" - failed\n");
+				fprintf(stderr, " - failed\n");
 		}
 
 		mc->write_enable = false;
@@ -235,7 +235,7 @@
 				break;
 
 			default:
-				printf("Unhandled FW command: %02X\n", data);
+				fprintf(stderr, "Unhandled FW command: %02X\n", data);
 		}
 	}
 
@@ -468,7 +468,7 @@
 		fseek(fsrc, 0, SEEK_END);
 		uint32_t fsize = ftell(fsrc);
 		fseek(fsrc, 0, SEEK_SET);
-		//printf("Open %s file (size %i bytes)\n", fname, fsize);
+		//fprintf(stderr, "Open %s file (size %i bytes)\n", fname, fsize);
 
 		auto in_buf = std::unique_ptr<uint8_t[]>(new uint8_t[fsize]);
 
@@ -480,18 +480,18 @@
 			uint32_t size = 0;
 			if (!no_gba_unpackSAV(&in_buf[0], fsize, &out_buf[0], size))
 			{
-				//printf("New size %i byte(s)\n", size);
+				//fprintf(stderr, "New size %i byte(s)\n", size);
 				size = no_gba_savTrim(&out_buf[0], size);
-				//printf("--- new size after trim %i byte(s)\n", size);
+				//fprintf(stderr, "--- new size after trim %i byte(s)\n", size);
 				size = no_gba_fillLeft(size);
-				//printf("--- new size after fill %i byte(s)\n", size);
+				//fprintf(stderr, "--- new size after fill %i byte(s)\n", size);
 				raw_applyUserSettings(size);
 				this->data.resize(size);
 				for (uint32_t tt = 0; tt < size; ++tt)
 					this->data[tt] = out_buf[tt];
 
 				//dump back out as a dsv, just to keep things sane
-				printf("---- Loaded no$GBA save\n");
+				fprintf(stderr, "---- Loaded no$GBA save\n");
 
 				fclose(fsrc);
 				return true;
@@ -516,7 +516,7 @@
 	if (inf->fail())
 	{
 		// no dsv found; we need to try auto-importing a file with .sav extension
-		printf("DeSmuME .dsv save file not found. Trying to load an old raw .sav file.\n");
+		fprintf(stderr, "DeSmuME .dsv save file not found. Trying to load an old raw .sav file.\n");
 
 		// change extension to sav
 		char tmp[MAX_PATH];
@@ -527,7 +527,7 @@
 		inf.reset(new EMUFILE_FILE(tmp, "rb"));
 		if (inf->fail())
 		{
-			printf("Missing save file %s\n", this->filename.c_str());
+			fprintf(stderr, "Missing save file %s\n", this->filename.c_str());
 			return;
 		}
 
@@ -545,7 +545,7 @@
 		if (cmp)
 		{
 			// maybe it is a misnamed raw save file. try loading it that way
-			printf("Not a DeSmuME .dsv save file. Trying to load as raw.\n");
+			fprintf(stderr, "Not a DeSmuME .dsv save file. Trying to load as raw.\n");
 			if (!this->load_no_gba(this->filename.c_str()))
 				this->load_raw(this->filename.c_str());
 			return;
@@ -557,7 +557,7 @@
 		read32le(&version, inf.get());
 		if (version)
 		{
-			printf("Unknown save file format\n");
+			fprintf(stderr, "Unknown save file format\n");
 			return;
 		}
 		inf->fseek(-24, SEEK_CUR);

--- a/src/in_2sf/desmume/mc.h
+++ b/src/in_2sf/desmume/mc.h
@@ -24,7 +24,7 @@
 #include <cstdio>
 #include "types.h"
 #include "emufile.h"
-#include "windowsh_wrapper.h"
+//#include "windowsh_wrapper.h"
 
 #define MAX_SAVE_TYPES 13
 #define MC_TYPE_AUTODETECT      0x0

--- a/src/in_2sf/desmume/metaspu/SndOut.cpp
+++ /dev/null
@@ -1,227 +1,1 @@
-/* SPU2-X, A plugin for Emulating the Sound Processing Unit of the Playstation 2
- * Developed and maintained by the Pcsx2 Development Team.
- *
- * Original portions from SPU2ghz are (c) 2008 by David Quintana [gigaherz]
- *
- * SPU2-X is free software: you can redistribute it and/or modify it under the terms
- * of the GNU Lesser General Public License as published by the Free Software Found-
- * ation, either version 3 of the License, or (at your option) any later version.
- *
- * SPU2-X is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
- * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
- * PURPOSE.  See the GNU Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with SPU2-X.  If not, see <http://www.gnu.org/licenses/>.
- */
 
-#include <cassert>
-#include "../types.h"
-#include "SndOut.h"
-
-//----------------
-static const int SndOutLatencyMS = 160;
-static bool timeStretchDisabled = false;
-//----------------
-
-StereoOut32 StereoOut32::Empty;
-
-StereoOut32::StereoOut32(const StereoOut16 &src) : Left(src.Left), Right(src.Right)
-{
-}
-
-StereoOut32::StereoOut32(const StereoOutFloat &src) : Left(static_cast<int32_t>(src.Left * 2147483647.0f)), Right(static_cast<int32_t>(src.Right * 2147483647.0f))
-{
-}
-
-StereoOut16 StereoOut32::DownSample() const
-{
-	return StereoOut16((Left >> SndOutVolumeShift) & 0xFFFF, (Right >> SndOutVolumeShift) & 0xFFFF);
-}
-
-std::unique_ptr<StereoOut32[]> SndBuffer::m_buffer;
-int32_t SndBuffer::m_size;
-int32_t SndBuffer::m_rpos;
-int32_t SndBuffer::m_wpos;
-int32_t SndBuffer::m_data;
-
-bool SndBuffer::m_underrun_freeze;
-std::unique_ptr<StereoOut32[]> SndBuffer::sndTempBuffer;
-int SndBuffer::sndTempProgress = 0;
-
-inline int GetAlignedBufferSize(int comp)
-{
-	return (comp + SndOutPacketSize - 1) & ~(SndOutPacketSize - 1);
-}
-
-// Returns true if there is data to be output, or false if no data
-// is available to be copied.
-bool SndBuffer::CheckUnderrunStatus(int &nSamples, int &quietSampleCount)
-{
-	quietSampleCount = 0;
-	if (m_underrun_freeze)
-	{
-		int toFill = static_cast<int>(m_size * (timeStretchDisabled ? 0.50f : 0.1f));
-		toFill = GetAlignedBufferSize(toFill);
-
-		// toFill is now aligned to a SndOutPacket
-
-		if (m_data < toFill)
-		{
-			quietSampleCount = nSamples;
-			return false;
-		}
-
-		m_underrun_freeze = false;
-		//TODO
-		//if( MsgOverruns() )
-			printf(" * SPU2 > Underrun compensation (%d packets buffered)\n", toFill / SndOutPacketSize);
-		lastPct = 0.0; // normalize timestretcher
-	}
-	else if (m_data < nSamples)
-	{
-		nSamples = m_data;
-		quietSampleCount = SndOutPacketSize - m_data;
-		m_underrun_freeze = true;
-
-		if (!timeStretchDisabled)
-			timeStretchUnderrun();
-
-		return !!nSamples;
-	}
-
-	return true;
-}
-
-void SndBuffer::_InitFail()
-{
-	// If a failure occurs, just initialize the NoSound driver.  This'll allow
-	// the game to emulate properly (hopefully), albeit without sound.
-	//OutputModule = FindOutputModuleById( NullOut.GetIdent() );
-	//mods[OutputModule]->Init();
-}
-
-void SndBuffer::_WriteSamples(StereoOut32 *bData, int nSamples)
-{
-	int free = m_size - m_data;
-	m_predictData = 0;
-
-	assert(m_data <= m_size);
-
-	// Problem:
-	//  If the SPU2 gets out of sync with the SndOut device, the writepos of the
-	//  circular buffer will overtake the readpos, leading to a prolonged period
-	//  of hopscotching read/write accesses (ie, lots of staticy crap sound for
-	//  several seconds).
-	//
-	// Compromise:
-	//  When an overrun occurs, we adapt by discarding a portion of the buffer.
-	//  The older portion of the buffer is discarded rather than incoming data,
-	//  so that the overall audio synchronization is better.
-
-	if (free < nSamples)
-	{
-		// Buffer overrun!
-		// Dump samples from the read portion of the buffer instead of dropping
-		// the newly written stuff.
-
-		int32_t comp;
-
-		if (!timeStretchDisabled)
-			comp = timeStretchOverrun();
-		else
-		{
-			// Toss half the buffer plus whatever's being written anew:
-			comp = GetAlignedBufferSize((m_size + nSamples) / 2);
-			if (comp > m_size - SndOutPacketSize)
-				comp = m_size - SndOutPacketSize;
-		}
-
-		m_data -= comp;
-		m_rpos = (m_rpos + comp) % m_size;
-		//TODO
-		//if( MsgOverruns() )
-			printf(" * SPU2 > Overrun Compensation (%d packets tossed)\n", comp / SndOutPacketSize);
-		lastPct = 0.0; // normalize the timestretcher
-	}
-
-	// copy in two phases, since there's a chance the packet
-	// wraps around the buffer (it'd be nice to deal in packets only, but
-	// the timestretcher and DSP options require flexibility).
-
-	int endPos = m_wpos + nSamples;
-	int secondCopyLen = endPos - m_size;
-	StereoOut32 *wposbuffer = &m_buffer[m_wpos];
-
-	m_data += nSamples;
-	if (secondCopyLen > 0)
-	{
-		nSamples -= secondCopyLen;
-		memcpy(m_buffer.get(), &bData[nSamples], secondCopyLen * sizeof(*bData));
-		m_wpos = secondCopyLen;
-	}
-	else
-		m_wpos += nSamples;
-
-	memcpy(wposbuffer, bData, nSamples * sizeof(*bData));
-}
-
-void SndBuffer::Init()
-{
-	// initialize sound buffer
-	// Buffer actually attempts to run ~50%, so allocate near double what
-	// the requested latency is:
-
-	m_rpos = m_wpos = m_data = 0;
-
-	try
-	{
-		float latencyMS = SndOutLatencyMS * (timeStretchDisabled ? 1.5f : 2.0f);
-		m_size = GetAlignedBufferSize(static_cast<int>(latencyMS * SampleRate / 1000.0f));
-		m_buffer.reset(new StereoOut32[m_size]);
-		m_underrun_freeze = false;
-
-		sndTempBuffer.reset(new StereoOut32[SndOutPacketSize]);
-	}
-	catch(const std::bad_alloc &)
-	{
-		// out of memory exception (most likely)
-
-		printf("Out of memory error occurred while initializing SPU2.");
-		_InitFail();
-		return;
-	}
-
-	// clear buffers!
-	// Fixes loopy sounds on emu resets.
-	memset(sndTempBuffer.get(), 0, sizeof(StereoOut32) * SndOutPacketSize);
-
-	sndTempProgress = 0;
-
-	soundtouchInit(); // initializes the timestretching
-
-	// some crap
-	//spdif_set51(mods[OutputModule]->Is51Out());
-
-	// initialize module
-	//if( mods[OutputModule]->Init() == -1 ) _InitFail();
-}
-
-void SndBuffer::Write(const StereoOut32 &Sample)
-{
-	//if(mods[OutputModule] == &NullOut) // null output doesn't need buffering or stretching! :p
-	//	return;
-
-	sndTempBuffer[sndTempProgress++] = Sample;
-
-	// If we haven't accumulated a full packet yet, do nothing more:
-	if (sndTempProgress < SndOutPacketSize)
-		return;
-	sndTempProgress = 0;
-
-	if( !timeStretchDisabled )
-		timeStretchWrite();
-	else
-		_WriteSamples(sndTempBuffer.get(), SndOutPacketSize);
-}
-

--- a/src/in_2sf/desmume/metaspu/SndOut.h
+++ /dev/null
@@ -1,215 +1,1 @@
-/* SPU2-X, A plugin for Emulating the Sound Processing Unit of the Playstation 2
- * Developed and maintained by the Pcsx2 Development Team.
- *
- * Original portions from SPU2ghz are (c) 2008 by David Quintana [gigaherz]
- *
- * SPU2-X is free software: you can redistribute it and/or modify it under the terms
- * of the GNU Lesser General Public License as published by the Free Software Found-
- * ation, either version 3 of the License, or (at your option) any later version.
- *
- * SPU2-X is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
- * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
- * PURPOSE.  See the GNU Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with SPU2-X.  If not, see <http://www.gnu.org/licenses/>.
- */
 
-#pragma once
-
-#include <memory>
-#include <algorithm>
-#include "../types.h"
-
-struct StereoOut16;
-struct StereoOutFloat;
-
-struct StereoOut32
-{
-	static StereoOut32 Empty;
-
-	int32_t Left, Right;
-
-	StereoOut32() : Left(0), Right(0)
-	{
-	}
-
-	StereoOut32(int32_t left, int32_t right) : Left(left), Right(right)
-	{
-	}
-
-	StereoOut32(const StereoOut16 &src);
-	explicit StereoOut32(const StereoOutFloat &src);
-
-	StereoOut16 DownSample() const;
-
-	StereoOut32 operator+(const StereoOut32 &right) const
-	{
-		return StereoOut32(this->Left + right.Left, this->Right + right.Right);
-	}
-
-	StereoOut32 operator/(int src) const
-	{
-		return StereoOut32(this->Left / src, this->Right / src);
-	}
-};
-
-// Number of stereo samples per SndOut block.
-// All drivers must work in units of this size when communicating with
-// SndOut.
-const int SndOutPacketSize = 512;
-
-// edit - zeromus 23-oct-2009
-// this is hardcoded differently for metaspu
-const int SndOutVolumeShift = 0;
-
-// Samplerate of the SPU2. For accurate playback we need to match this
-// exactly.  Trying to scale samplerates and maintain SPU2's Ts timing accuracy
-// is too problematic. :)
-// this is hardcoded differently for metaspu
-// edit - zeromus 23-oct-2009
-//const int SampleRate = 48000;
-//const int SampleRate = 44100;
-// edit - nitsuja: make it use the global sample rate define
-#include "../SPU.h"
-const int SampleRate = DESMUME_SAMPLE_RATE;
-
-struct StereoOut16
-{
-	int16_t Left, Right;
-
-	StereoOut16() : Left(0), Right(0)
-	{
-	}
-
-	StereoOut16(const StereoOut32 &src) : Left(src.Left & 0xFFFF), Right(src.Right & 0xFFFF)
-	{
-	}
-
-	StereoOut16(int16_t left, int16_t right) : Left(left), Right(right)
-	{
-	}
-
-	void ResampleFrom(const StereoOut32 &src)
-	{
-		// Use StereoOut32's built in conversion
-		*this = src.DownSample();
-	}
-};
-
-struct StereoOutFloat
-{
-	float Left, Right;
-
-	StereoOutFloat() : Left(0.0f), Right(0.0f)
-	{
-	}
-
-	explicit StereoOutFloat(const StereoOut32 &src) : Left(src.Left / 2147483647.0f), Right(src.Right / 2147483647.0f)
-	{
-	}
-
-	explicit StereoOutFloat(int32_t left, int32_t right) : Left(left / 2147483647.0f), Right(right / 2147483647.0f)
-	{
-	}
-
-	StereoOutFloat(float left, float right) : Left(left), Right(right)
-	{
-	}
-};
-
-// Developer Note: This is a static class only (all static members).
-class SndBuffer
-{
-private:
-	static bool m_underrun_freeze;
-	static int32_t m_predictData;
-	static float lastPct;
-
-	static std::unique_ptr<StereoOut32[]> sndTempBuffer;
-
-	static int sndTempProgress;
-
-	static std::unique_ptr<StereoOut32[]> m_buffer;
-	static int32_t m_size;
-	static int32_t m_rpos;
-	static int32_t m_wpos;
-	static int32_t m_data;
-
-	static float lastEmergencyAdj;
-	static float cTempo;
-	static float eTempo;
-	static int freezeTempo;
-
-	static void _InitFail();
-	static void _WriteSamples(StereoOut32 *bData, int nSamples);
-	static bool CheckUnderrunStatus(int &nSamples, int &quietSampleCount);
-
-	static void soundtouchInit();
-	static void timeStretchWrite();
-	static void timeStretchUnderrun();
-	static int32_t timeStretchOverrun();
-
-	static void PredictDataWrite(int samples);
-	static float GetStatusPct();
-	static void UpdateTempoChange();
-
-public:
-	static void Init();
-	static void Write(const StereoOut32 &Sample);
-
-	// Note: When using with 32 bit output buffers, the user of this function is responsible
-	// for shifting the values to where they need to be manually.  The fixed point depth of
-	// the sample output is determined by the SndOutVolumeShift, which is the number of bits
-	// to shift right to get a 16 bit result.
-	template<typename T> static void ReadSamples(T *bData)
-	{
-		int nSamples = SndOutPacketSize;
-
-		// Problem:
-		//  If the SPU2 gets even the least bit out of sync with the SndOut device,
-		//  the readpos of the circular buffer will overtake the writepos,
-		//  leading to a prolonged period of hopscotching read/write accesses (ie,
-		//  lots of staticy crap sound for several seconds).
-		//
-		// Fix:
-		//  If the read position overtakes the write position, abort the
-		//  transfer immediately and force the SndOut driver to wait until
-		//  the read buffer has filled up again before proceeding.
-		//  This will cause one brief hiccup that can never exceed the user's
-		//  set buffer length in duration.
-
-		int quietSamples;
-		if (CheckUnderrunStatus(nSamples, quietSamples))
-		{
-			assert(nSamples <= SndOutPacketSize);
-
-			// [Air] [TODO]: This loop is probably a candidate for SSE2 optimization.
-
-			int endPos = m_rpos + nSamples;
-			int secondCopyLen = endPos - m_size;
-			const StereoOut32 *rposbuffer = &m_buffer[m_rpos];
-
-			m_data -= nSamples;
-
-			if (secondCopyLen > 0)
-			{
-				nSamples -= secondCopyLen;
-				for (int i = 0; i < secondCopyLen; ++i)
-					bData[nSamples + i].ResampleFrom(m_buffer[i]);
-				m_rpos = secondCopyLen;
-			}
-			else
-				m_rpos += nSamples;
-
-			for (int i = 0; i < nSamples; ++i)
-				bData[i].ResampleFrom(rposbuffer[i]);
-		}
-
-		// If quietSamples != 0 it means we have an underrun...
-		// Let's just dull out some silence, because that's usually the least
-		// painful way of dealing with underruns:
-		memset(bData, 0, quietSamples * sizeof(T));
-	}
-};
-

--- a/src/in_2sf/desmume/metaspu/SoundTouch/AAFilter.cpp
+++ /dev/null
@@ -1,156 +1,1 @@
-////////////////////////////////////////////////////////////////////////////////
-///
-/// FIR low-pass (anti-alias) filter with filter coefficient design routine and
-/// MMX optimization.
-///
-/// Anti-alias filter is used to prevent folding of high frequencies when
-/// transposing the sample rate with interpolation.
-///
-/// Author        : Copyright (c) Olli Parviainen
-/// Author e-mail : oparviai 'at' iki.fi
-/// SoundTouch WWW: http://www.surina.net/soundtouch
-///
-////////////////////////////////////////////////////////////////////////////////
-//
-// Last changed  : $Date: 2006/02/05 16:44:06 $
-// File revision : $Revision: 1.9 $
-//
-// $Id: AAFilter.cpp,v 1.9 2006/02/05 16:44:06 Olli Exp $
-//
-////////////////////////////////////////////////////////////////////////////////
-//
-// License :
-//
-//  SoundTouch audio processing library
-//  Copyright (c) Olli Parviainen
-//
-//  This library is free software; you can redistribute it and/or
-//  modify it under the terms of the GNU Lesser General Public
-//  License as published by the Free Software Foundation; either
-//  version 2.1 of the License, or (at your option) any later version.
-//
-//  This library is distributed in the hope that it will be useful,
-//  but WITHOUT ANY WARRANTY; without even the implied warranty of
-//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-//  Lesser General Public License for more details.
-//
-//  You should have received a copy of the GNU Lesser General Public
-//  License along with this library; if not, write to the Free Software
-//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
-//
-////////////////////////////////////////////////////////////////////////////////
 
-#include "XSFCommon.h"
-
-#include <vector>
-#include <cassert>
-#include "AAFilter.h"
-
-using namespace soundtouch;
-
-#ifndef M_PI
-static const double M_PI = 3.14159265358979323846;
-#endif
-
-/*****************************************************************************
- *
- * Implementation of the class 'AAFilter'
- *
- *****************************************************************************/
-
-AAFilter::AAFilter(const uint32_t len)
-{
-	this->pFIR.reset(FIRFilter::newInstance());
-	this->cutoffFreq = 0.5;
-	this->setLength(len);
-}
-
-// Sets new anti-alias filter cut-off edge frequency, scaled to
-// sampling frequency (nyquist frequency = 0.5).
-// The filter will cut frequencies higher than the given frequency.
-void AAFilter::setCutoffFreq(double newCutoffFreq)
-{
-	this->cutoffFreq = newCutoffFreq;
-	this->calculateCoeffs();
-}
-
-// Sets number of FIR filter taps
-void AAFilter::setLength(uint32_t newLength)
-{
-	this->length = newLength;
-	this->calculateCoeffs();
-}
-
-// Calculates coefficients for a low-pass FIR filter using Hamming window
-void AAFilter::calculateCoeffs()
-{
-	assert(this->length > 0);
-	assert(!(this->length % 4));
-	assert(this->cutoffFreq >= 0);
-	assert(this->cutoffFreq <= 0.5);
-
-	auto work = std::vector<double>(this->length);
-	auto coeffs = std::vector<SAMPLETYPE>(this->length);
-
-	double fc2 = 2.0 * this->cutoffFreq;
-	double wc = M_PI * fc2;
-	double tempCoeff = 2 * M_PI / this->length;
-
-	double sum = 0.0;
-	for (uint32_t i = 0; i < this->length; ++i)
-	{
-		double cntTemp = i - (this->length / 2);
-
-		double temp = cntTemp * wc, h;
-		if (!fEqual(temp, 0.0))
-			h = fc2 * std::sin(temp) / temp; // sinc function
-		else
-			h = 1.0;
-		double w = 0.54 + 0.46 * std::cos(tempCoeff * cntTemp); // hamming window
-
-		temp = w * h;
-		work[i] = temp;
-
-		// calc net sum of coefficients
-		sum += temp;
-	}
-
-	// ensure the sum of coefficients is larger than zero
-	assert(sum > 0);
-
-	// ensure we've really designed a lowpass filter...
-	assert(work[this->length / 2] > 0);
-	assert(work[this->length / 2 + 1] > -1e-6);
-	assert(work[this->length / 2 - 1] > -1e-6);
-
-	// Calculate a scaling coefficient in such a way that the result can be
-	// divided by 16384
-	double scaleCoeff = 16384.0 / sum;
-
-	for (uint32_t i = 0; i < this->length; ++i)
-	{
-		// scale & round to nearest integer
-		double temp = work[i] * scaleCoeff;
-		temp += temp >= 0 ? 0.5 : -0.5;
-		// ensure no overfloods
-		assert(temp >= -32768 && temp <= 32767);
-		coeffs[i] = static_cast<SAMPLETYPE>(temp);
-	}
-
-	// Set coefficients. Use divide factor 14 => divide result by 2^14 = 16384
-	this->pFIR->setCoefficients(&coeffs[0], length, 14);
-}
-
-// Applies the filter to the given sequence of samples.
-// Note : The amount of outputted samples is by value of 'filter length'
-// smaller than the amount of input samples.
-uint32_t AAFilter::evaluate(SAMPLETYPE *dest, const SAMPLETYPE *src, uint32_t numSamples, uint32_t numChannels) const
-{
-	return this->pFIR->evaluate(dest, src, numSamples, numChannels);
-}
-
-uint32_t AAFilter::getLength() const
-{
-	return this->pFIR->getLength();
-}
-

--- a/src/in_2sf/desmume/metaspu/SoundTouch/AAFilter.h
+++ /dev/null
@@ -1,85 +1,1 @@
-////////////////////////////////////////////////////////////////////////////////
-///
-/// Sampled sound tempo changer/time stretch algorithm. Changes the sound tempo
-/// while maintaining the original pitch by using a time domain WSOLA-like method
-/// with several performance-increasing tweaks.
-///
-/// Anti-alias filter is used to prevent folding of high frequencies when
-/// transposing the sample rate with interpolation.
-///
-/// Author        : Copyright (c) Olli Parviainen
-/// Author e-mail : oparviai 'at' iki.fi
-/// SoundTouch WWW: http://www.surina.net/soundtouch
-///
-////////////////////////////////////////////////////////////////////////////////
-//
-// Last changed  : $Date: 2006/02/05 16:44:06 $
-// File revision : $Revision: 1.10 $
-//
-// $Id: AAFilter.h,v 1.10 2006/02/05 16:44:06 Olli Exp $
-//
-////////////////////////////////////////////////////////////////////////////////
-//
-// License :
-//
-//  SoundTouch audio processing library
-//  Copyright (c) Olli Parviainen
-//
-//  This library is free software; you can redistribute it and/or
-//  modify it under the terms of the GNU Lesser General Public
-//  License as published by the Free Software Foundation; either
-//  version 2.1 of the License, or (at your option) any later version.
-//
-//  This library is distributed in the hope that it will be useful,
-//  but WITHOUT ANY WARRANTY; without even the implied warranty of
-//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-//  Lesser General Public License for more details.
-//
-//  You should have received a copy of the GNU Lesser General Public
-//  License along with this library; if not, write to the Free Software
-//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
-//
-////////////////////////////////////////////////////////////////////////////////
 
-#pragma once
-
-#include "FIRFilter.h"
-
-namespace soundtouch
-{
-
-class AAFilter
-{
-protected:
-	std::unique_ptr<FIRFilter> pFIR;
-
-	/// Low-pass filter cut-off frequency, negative = invalid
-	double cutoffFreq;
-
-	/// num of filter taps
-	uint32_t length;
-
-	/// Calculate the FIR coefficients realizing the given cutoff-frequency
-	void calculateCoeffs();
-
-public:
-	AAFilter(uint32_t length);
-
-	/// Sets new anti-alias filter cut-off edge frequency, scaled to sampling
-	/// frequency (nyquist frequency = 0.5). The filter will cut off the
-	/// frequencies than that.
-	void setCutoffFreq(double newCutoffFreq);
-
-	/// Sets number of FIR filter taps, i.e. ~filter complexity
-	void setLength(uint32_t newLength);
-
-	uint32_t getLength() const;
-
-	/// Applies the filter to the given sequence of samples.
-	/// Note : The amount of outputted samples is by value of 'filter length'
-	/// smaller than the amount of input samples.
-	uint32_t evaluate(SAMPLETYPE *dest, const SAMPLETYPE *src, uint32_t numSamples, uint32_t numChannels) const;
-};
-
-}
-

--- a/src/in_2sf/desmume/metaspu/SoundTouch/FIFOSampleBuffer.cpp
+++ /dev/null
@@ -1,227 +1,1 @@
-////////////////////////////////////////////////////////////////////////////////
-///
-/// A buffer class for temporarily storaging sound samples, operates as a
-/// first-in-first-out pipe.
-///
-/// Samples are added to the end of the sample buffer with the 'putSamples'
-/// function, and are received from the beginning of the buffer by calling
-/// the 'receiveSamples' function. The class automatically removes the
-/// outputted samples from the buffer, as well as grows the buffer size
-/// whenever necessary.
-///
-/// Author        : Copyright (c) Olli Parviainen
-/// Author e-mail : oparviai 'at' iki.fi
-/// SoundTouch WWW: http://www.surina.net/soundtouch
-///
-////////////////////////////////////////////////////////////////////////////////
-//
-// Last changed  : $Date: 2012-11-08 16:53:01 -0200 (qui, 08 nov 2012) $
-// File revision : $Revision: 4 $
-//
-// $Id: FIFOSampleBuffer.cpp 160 2012-11-08 18:53:01Z oparviai $
-//
-////////////////////////////////////////////////////////////////////////////////
-//
-// License :
-//
-//  SoundTouch audio processing library
-//  Copyright (c) Olli Parviainen
-//
-//  This library is free software; you can redistribute it and/or
-//  modify it under the terms of the GNU Lesser General Public
-//  License as published by the Free Software Foundation; either
-//  version 2.1 of the License, or (at your option) any later version.
-//
-//  This library is distributed in the hope that it will be useful,
-//  but WITHOUT ANY WARRANTY; without even the implied warranty of
-//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-//  Lesser General Public License for more details.
-//
-//  You should have received a copy of the GNU Lesser General Public
-//  License along with this library; if not, write to the Free Software
-//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
-//
-////////////////////////////////////////////////////////////////////////////////
 
-#include <stdexcept>
-#include <cstring>
-#include "FIFOSampleBuffer.h"
-
-using namespace soundtouch;
-
-// Constructor
-FIFOSampleBuffer::FIFOSampleBuffer(int32_t numChannels)
-{
-	assert(numChannels > 0);
-	this->sizeInBytes = 0; // reasonable initial value
-	this->buffer = nullptr;
-	this->bufferUnaligned.reset();
-	this->samplesInBuffer = 0;
-	this->bufferPos = 0;
-	this->channels = numChannels;
-	this->ensureCapacity(32); // allocate initial capacity
-}
-
-// Sets number of channels, 1 = mono, 2 = stereo
-void FIFOSampleBuffer::setChannels(int32_t numChannels)
-{
-	assert(numChannels > 0);
-	uint32_t usedBytes = this->channels * this->samplesInBuffer;
-	this->channels = numChannels;
-	this->samplesInBuffer = usedBytes / this->channels;
-}
-
-// if output location pointer 'bufferPos' isn't zero, 'rewinds' the buffer and
-// zeroes this pointer by copying samples from the 'bufferPos' pointer
-// location on to the beginning of the buffer.
-void FIFOSampleBuffer::rewind()
-{
-	if (this->buffer && this->bufferPos)
-	{
-		memmove(this->buffer, this->ptrBegin(), sizeof(SAMPLETYPE) * this->channels * this->samplesInBuffer);
-		this->bufferPos = 0;
-	}
-}
-
-// Adds 'numSamples' pcs of samples from the 'samples' memory position to
-// the sample buffer.
-void FIFOSampleBuffer::putSamples(const SAMPLETYPE *samples, uint32_t nSamples)
-{
-	memcpy(this->ptrEnd(nSamples), samples, sizeof(SAMPLETYPE) * nSamples * this->channels);
-	this->samplesInBuffer += nSamples;
-}
-
-// Increases the number of samples in the buffer without copying any actual
-// samples.
-//
-// This function is used to update the number of samples in the sample buffer
-// when accessing the buffer directly with 'ptrEnd' function. Please be
-// careful though!
-void FIFOSampleBuffer::putSamples(uint32_t nSamples)
-{
-	uint32_t req = this->samplesInBuffer + nSamples;
-	this->ensureCapacity(req);
-	this->samplesInBuffer += nSamples;
-}
-
-// Returns a pointer to the end of the used part of the sample buffer (i.e.
-// where the new samples are to be inserted). This function may be used for
-// inserting new samples into the sample buffer directly. Please be careful!
-//
-// Parameter 'slackCapacity' tells the function how much free capacity (in
-// terms of samples) there _at least_ should be, in order to the caller to
-// succesfully insert all the required samples to the buffer. When necessary,
-// the function grows the buffer size to comply with this requirement.
-//
-// When using this function as means for inserting new samples, also remember
-// to increase the sample count afterwards, by calling  the
-// 'putSamples(numSamples)' function.
-SAMPLETYPE *FIFOSampleBuffer::ptrEnd(uint32_t slackCapacity)
-{
-	this->ensureCapacity(this->samplesInBuffer + slackCapacity);
-	return &this->buffer[this->samplesInBuffer * this->channels];
-}
-
-// Returns a pointer to the beginning of the currently non-outputted samples.
-// This function is provided for accessing the output samples directly.
-// Please be careful!
-//
-// When using this function to output samples, also remember to 'remove' the
-// outputted samples from the buffer by calling the
-// 'receiveSamples(numSamples)' function
-SAMPLETYPE *FIFOSampleBuffer::ptrBegin()
-{
-	assert(this->buffer);
-	return &this->buffer[this->bufferPos * this->channels];
-}
-
-// Ensures that the buffer has enought capacity, i.e. space for _at least_
-// 'capacityRequirement' number of samples. The buffer is grown in steps of
-// 4 kilobytes to eliminate the need for frequently growing up the buffer,
-// as well as to round the buffer size up to the virtual memory page size.
-void FIFOSampleBuffer::ensureCapacity(uint32_t capacityRequirement)
-{
-	if (capacityRequirement > this->getCapacity())
-	{
-		// enlarge the buffer in 4kbyte steps (round up to next 4k boundary)
-		this->sizeInBytes = (capacityRequirement * this->channels * sizeof(SAMPLETYPE) + 4095) & static_cast<uint32_t>(-4096);
-		assert(!(this->sizeInBytes % 2));
-		auto tempUnaligned = std::unique_ptr<SAMPLETYPE[]>(new SAMPLETYPE[(this->sizeInBytes + 16) / sizeof(SAMPLETYPE)]);
-		// Align the buffer to begin at 16byte cache line boundary for optimal performance
-		SAMPLETYPE *temp = reinterpret_cast<SAMPLETYPE *>(SOUNDTOUCH_ALIGN_POINTER_16(tempUnaligned.get()));
-		if (samplesInBuffer)
-			memcpy(temp, this->ptrBegin(), samplesInBuffer * this->channels * sizeof(SAMPLETYPE));
-		this->buffer = temp;
-		this->bufferUnaligned = std::move(tempUnaligned);
-		this->bufferPos = 0;
-	}
-	else
-		// simply rewind the buffer (if necessary)
-		this->rewind();
-}
-
-// Returns the current buffer capacity in terms of samples
-uint32_t FIFOSampleBuffer::getCapacity() const
-{
-	return this->sizeInBytes / (this->channels * sizeof(SAMPLETYPE));
-}
-
-// Returns the number of samples currently in the buffer
-uint32_t FIFOSampleBuffer::numSamples() const
-{
-	return this->samplesInBuffer;
-}
-
-// Output samples from beginning of the sample buffer. Copies demanded number
-// of samples to output and removes them from the sample buffer. If there
-// are less than 'numsample' samples in the buffer, returns all available.
-//
-// Returns number of samples copied.
-uint32_t FIFOSampleBuffer::receiveSamples(SAMPLETYPE *output, uint32_t maxSamples)
-{
-	uint32_t num = maxSamples > this->samplesInBuffer ? this->samplesInBuffer : maxSamples;
-
-	memcpy(output, this->ptrBegin(), this->channels * sizeof(SAMPLETYPE) * num);
-	return this->receiveSamples(num);
-}
-
-// Removes samples from the beginning of the sample buffer without copying them
-// anywhere. Used to reduce the number of samples in the buffer, when accessing
-// the sample buffer with the 'ptrBegin' function.
-uint32_t FIFOSampleBuffer::receiveSamples(uint32_t maxSamples)
-{
-	if (maxSamples >= this->samplesInBuffer)
-	{
-		uint32_t temp = this->samplesInBuffer;
-		this->samplesInBuffer = 0;
-		return temp;
-	}
-
-	this->samplesInBuffer -= maxSamples;
-	this->bufferPos += maxSamples;
-
-	return maxSamples;
-}
-
-// Returns nonzero if the sample buffer is empty
-bool FIFOSampleBuffer::isEmpty() const
-{
-	return !this->samplesInBuffer;
-}
-
-// Clears the sample buffer
-void FIFOSampleBuffer::clear()
-{
-	this->samplesInBuffer = 0;
-	this->bufferPos = 0;
-}
-
-/// allow trimming (downwards) amount of samples in pipeline.
-/// Returns adjusted amount of samples
-uint32_t FIFOSampleBuffer::adjustAmountOfSamples(uint32_t numSmpls)
-{
-	if (numSmpls < this->samplesInBuffer)
-		this->samplesInBuffer = numSmpls;
-	return this->samplesInBuffer;
-}
-

--- a/src/in_2sf/desmume/metaspu/SoundTouch/FIFOSampleBuffer.h
+++ /dev/null
@@ -1,173 +1,1 @@
-////////////////////////////////////////////////////////////////////////////////
-///
-/// A buffer class for temporarily storaging sound samples, operates as a
-/// first-in-first-out pipe.
-///
-/// Samples are added to the end of the sample buffer with the 'putSamples'
-/// function, and are received from the beginning of the buffer by calling
-/// the 'receiveSamples' function. The class automatically removes the
-/// output samples from the buffer as well as grows the storage size
-/// whenever necessary.
-///
-/// Author        : Copyright (c) Olli Parviainen
-/// Author e-mail : oparviai 'at' iki.fi
-/// SoundTouch WWW: http://www.surina.net/soundtouch
-///
-////////////////////////////////////////////////////////////////////////////////
-//
-// Last changed  : $Date: 2012-06-13 16:29:53 -0300 (qua, 13 jun 2012) $
-// File revision : $Revision: 4 $
-//
-// $Id: FIFOSampleBuffer.h 143 2012-06-13 19:29:53Z oparviai $
-//
-////////////////////////////////////////////////////////////////////////////////
-//
-// License :
-//
-//  SoundTouch audio processing library
-//  Copyright (c) Olli Parviainen
-//
-//  This library is free software; you can redistribute it and/or
-//  modify it under the terms of the GNU Lesser General Public
-//  License as published by the Free Software Foundation; either
-//  version 2.1 of the License, or (at your option) any later version.
-//
-//  This library is distributed in the hope that it will be useful,
-//  but WITHOUT ANY WARRANTY; without even the implied warranty of
-//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-//  Lesser General Public License for more details.
-//
-//  You should have received a copy of the GNU Lesser General Public
-//  License along with this library; if not, write to the Free Software
-//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
-//
-////////////////////////////////////////////////////////////////////////////////
 
-#pragma once
-
-#include <memory>
-#include "FIFOSamplePipe.h"
-
-namespace soundtouch
-{
-
-/// Sample buffer working in FIFO (first-in-first-out) principle. The class takes
-/// care of storage size adjustment and data moving during input/output operations.
-///
-/// Notice that in case of stereo audio, one sample is considered to consist of
-/// both channel data.
-class FIFOSampleBuffer : public FIFOSamplePipe
-{
-private:
-	/// Sample buffer.
-	SAMPLETYPE *buffer;
-
-	// Raw unaligned buffer memory. 'buffer' is made aligned by pointing it to first
-	// 16-byte aligned location of this buffer
-	std::unique_ptr<SAMPLETYPE[]> bufferUnaligned;
-
-	/// Sample buffer size in bytes
-	uint32_t sizeInBytes;
-
-	/// How many samples are currently in buffer.
-	uint32_t samplesInBuffer;
-
-	/// Channels, 1=mono, 2=stereo.
-	uint32_t channels;
-
-	/// Current position pointer to the buffer. This pointer is increased when samples are
-	/// removed from the pipe so that it's necessary to actually rewind buffer (move data)
-	/// only new data when is put to the pipe.
-	uint32_t bufferPos;
-
-	/// Rewind the buffer by moving data from position pointed by 'bufferPos' to real
-	/// beginning of the buffer.
-	void rewind();
-
-	/// Ensures that the buffer has capacity for at least this many samples.
-	void ensureCapacity(uint32_t capacityRequirement);
-
-	/// Returns current capacity.
-	uint32_t getCapacity() const;
-
-public:
-	/// Constructor
-	FIFOSampleBuffer(int32_t numChannels = 2     ///< Number of channels, 1=mono, 2=stereo.
-                                              ///< Default is stereo.
-                     );
-
-	/// Returns a pointer to the beginning of the output samples.
-	/// This function is provided for accessing the output samples directly.
-	/// Please be careful for not to corrupt the book-keeping!
-	///
-	/// When using this function to output samples, also remember to 'remove' the
-	/// output samples from the buffer by calling the
-	/// 'receiveSamples(numSamples)' function
-	SAMPLETYPE *ptrBegin();
-
-	/// Returns a pointer to the end of the used part of the sample buffer (i.e.
-	/// where the new samples are to be inserted). This function may be used for
-	/// inserting new samples into the sample buffer directly. Please be careful
-	/// not corrupt the book-keeping!
-	///
-	/// When using this function as means for inserting new samples, also remember
-	/// to increase the sample count afterwards, by calling  the
-	/// 'putSamples(numSamples)' function.
-	SAMPLETYPE *ptrEnd(
-                uint32_t slackCapacity   ///< How much free capacity (in samples) there _at least_
-                                         ///< should be so that the caller can succesfully insert the
-                                         ///< desired samples to the buffer. If necessary, the function
-                                         ///< grows the buffer size to comply with this requirement.
-                );
-
-	/// Adds 'numSamples' pcs of samples from the 'samples' memory position to
-	/// the sample buffer.
-	void putSamples(const SAMPLETYPE *samples,  ///< Pointer to samples.
-                            uint32_t numSamples                         ///< Number of samples to insert.
-                            );
-
-	/// Adjusts the book-keeping to increase number of samples in the buffer without
-	/// copying any actual samples.
-	///
-	/// This function is used to update the number of samples in the sample buffer
-	/// when accessing the buffer directly with 'ptrEnd' function. Please be
-	/// careful though!
-	void putSamples(uint32_t numSamples   ///< Number of samples been inserted.
-                            );
-
-	/// Output samples from beginning of the sample buffer. Copies requested samples to
-	/// output buffer and removes them from the sample buffer. If there are less than
-	/// 'numsample' samples in the buffer, returns all that available.
-	///
-	/// \return Number of samples returned.
-	uint32_t receiveSamples(SAMPLETYPE *output, ///< Buffer where to copy output samples.
-                                uint32_t maxSamples                 ///< How many samples to receive at max.
-                                );
-
-	/// Adjusts book-keeping so that given number of samples are removed from beginning of the
-	/// sample buffer without copying them anywhere.
-	///
-	/// Used to reduce the number of samples in the buffer when accessing the sample buffer directly
-	/// with 'ptrBegin' function.
-	uint32_t receiveSamples(uint32_t maxSamples   ///< Remove this many samples from the beginning of pipe.
-                                );
-
-	/// Returns number of samples currently available.
-	uint32_t numSamples() const;
-
-	/// Sets number of channels, 1 = mono, 2 = stereo.
-	void setChannels(int32_t numChannels);
-
-	/// Returns nonzero if there aren't any samples available for outputting.
-	bool isEmpty() const;
-
-	/// Clears all the samples.
-	void clear();
-
-	/// allow trimming (downwards) amount of samples in pipeline.
-	/// Returns adjusted amount of samples
-	uint32_t adjustAmountOfSamples(uint32_t numSamples);
-};
-
-}
-

--- a/src/in_2sf/desmume/metaspu/SoundTouch/FIFOSamplePipe.h
+++ /dev/null
@@ -1,217 +1,1 @@
-////////////////////////////////////////////////////////////////////////////////
-///
-/// 'FIFOSamplePipe' : An abstract base class for classes that manipulate sound
-/// samples by operating like a first-in-first-out pipe: New samples are fed
-/// into one end of the pipe with the 'putSamples' function, and the processed
-/// samples are received from the other end with the 'receiveSamples' function.
-///
-/// 'FIFOProcessor' : A base class for classes the do signal processing with
-/// the samples while operating like a first-in-first-out pipe. When samples
-/// are input with the 'putSamples' function, the class processes them
-/// and moves the processed samples to the given 'output' pipe object, which
-/// may be either another processing stage, or a fifo sample buffer object.
-///
-/// Author        : Copyright (c) Olli Parviainen
-/// Author e-mail : oparviai 'at' iki.fi
-/// SoundTouch WWW: http://www.surina.net/soundtouch
-///
-////////////////////////////////////////////////////////////////////////////////
-//
-// Last changed  : $Date: 2012-06-13 16:29:53 -0300 (qua, 13 jun 2012) $
-// File revision : $Revision: 4 $
-//
-// $Id: FIFOSamplePipe.h 143 2012-06-13 19:29:53Z oparviai $
-//
-////////////////////////////////////////////////////////////////////////////////
-//
-// License :
-//
-//  SoundTouch audio processing library
-//  Copyright (c) Olli Parviainen
-//
-//  This library is free software; you can redistribute it and/or
-//  modify it under the terms of the GNU Lesser General Public
-//  License as published by the Free Software Foundation; either
-//  version 2.1 of the License, or (at your option) any later version.
-//
-//  This library is distributed in the hope that it will be useful,
-//  but WITHOUT ANY WARRANTY; without even the implied warranty of
-//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-//  Lesser General Public License for more details.
-//
-//  You should have received a copy of the GNU Lesser General Public
-//  License along with this library; if not, write to the Free Software
-//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
-//
-////////////////////////////////////////////////////////////////////////////////
 
-#pragma once
-
-#include <cassert>
-#include "STTypes.h"
-
-namespace soundtouch
-{
-
-/// Abstract base class for FIFO (first-in-first-out) sample processing classes.
-class FIFOSamplePipe
-{
-public:
-	// virtual default destructor
-	virtual ~FIFOSamplePipe() { }
-
-	/// Returns a pointer to the beginning of the output samples.
-	/// This function is provided for accessing the output samples directly.
-	/// Please be careful for not to corrupt the book-keeping!
-	///
-	/// When using this function to output samples, also remember to 'remove' the
-	/// output samples from the buffer by calling the
-	/// 'receiveSamples(numSamples)' function
-	virtual SAMPLETYPE *ptrBegin() = 0;
-
-	/// Adds 'numSamples' pcs of samples from the 'samples' memory position to
-	/// the sample buffer.
-	virtual void putSamples(const SAMPLETYPE *samples,  ///< Pointer to samples.
-                            uint32_t numSamples         ///< Number of samples to insert.
-                            ) = 0;
-
-	// Moves samples from the 'other' pipe instance to this instance.
-	void moveSamples(FIFOSamplePipe &other  ///< Other pipe instance where from the receive the data.
-         )
-	{
-		int oNumSamples = other.numSamples();
-
-		this->putSamples(other.ptrBegin(), oNumSamples);
-		other.receiveSamples(oNumSamples);
-	}
-
-	/// Output samples from beginning of the sample buffer. Copies requested samples to
-	/// output buffer and removes them from the sample buffer. If there are less than
-	/// 'numsample' samples in the buffer, returns all that available.
-	///
-	/// \return Number of samples returned.
-	virtual uint32_t receiveSamples(SAMPLETYPE *output, ///< Buffer where to copy output samples.
-                                uint32_t maxSamples                 ///< How many samples to receive at max.
-                                ) = 0;
-
-	/// Adjusts book-keeping so that given number of samples are removed from beginning of the
-	/// sample buffer without copying them anywhere.
-	///
-	/// Used to reduce the number of samples in the buffer when accessing the sample buffer directly
-	/// with 'ptrBegin' function.
-	virtual uint32_t receiveSamples(uint32_t maxSamples   ///< Remove this many samples from the beginning of pipe.
-                                ) = 0;
-
-	/// Returns number of samples currently available.
-	virtual uint32_t numSamples() const = 0;
-
-	// Returns nonzero if there aren't any samples available for outputting.
-	virtual bool isEmpty() const = 0;
-
-	/// Clears all the samples.
-	virtual void clear() = 0;
-
-	/// allow trimming (downwards) amount of samples in pipeline.
-	/// Returns adjusted amount of samples
-	virtual uint32_t adjustAmountOfSamples(uint32_t numSamples) = 0;
-};
-
-/// Base-class for sound processing routines working in FIFO principle. With this base
-/// class it's easy to implement sound processing stages that can be chained together,
-/// so that samples that are fed into beginning of the pipe automatically go through
-/// all the processing stages.
-///
-/// When samples are input to this class, they're first processed and then put to
-/// the FIFO pipe that's defined as output of this class. This output pipe can be
-/// either other processing stage or a FIFO sample buffer.
-class FIFOProcessor :public FIFOSamplePipe
-{
-protected:
-	/// Internal pipe where processed samples are put.
-	FIFOSamplePipe *output;
-
-	/// Sets output pipe.
-	void setOutPipe(FIFOSamplePipe *pOutput)
-	{
-		assert(!this->output);
-		assert(pOutput);
-		this->output = pOutput;
-	}
-
-	/// Constructor. Doesn't define output pipe; it has to be set be
-	/// 'setOutPipe' function.
-	FIFOProcessor()
-	{
-		this->output = nullptr;
-	}
-
-	/// Constructor. Configures output pipe.
-	FIFOProcessor(FIFOSamplePipe *pOutput   ///< Output pipe.
-                 )
-	{
-		this->output = pOutput;
-	}
-
-	/// Destructor.
-	virtual ~FIFOProcessor()
-	{
-	}
-
-	/// Returns a pointer to the beginning of the output samples.
-	/// This function is provided for accessing the output samples directly.
-	/// Please be careful for not to corrupt the book-keeping!
-	///
-	/// When using this function to output samples, also remember to 'remove' the
-	/// output samples from the buffer by calling the
-	/// 'receiveSamples(numSamples)' function
-	virtual SAMPLETYPE *ptrBegin()
-	{
-		return this->output->ptrBegin();
-	}
-
-public:
-	/// Output samples from beginning of the sample buffer. Copies requested samples to
-	/// output buffer and removes them from the sample buffer. If there are less than
-	/// 'numsample' samples in the buffer, returns all that available.
-	///
-	/// \return Number of samples returned.
-	virtual uint32_t receiveSamples(SAMPLETYPE *outBuffer, ///< Buffer where to copy output samples.
-                                uint32_t maxSamples                    ///< How many samples to receive at max.
-                                )
-	{
-		return this->output->receiveSamples(outBuffer, maxSamples);
-	}
-
-	/// Adjusts book-keeping so that given number of samples are removed from beginning of the
-	/// sample buffer without copying them anywhere.
-	///
-	/// Used to reduce the number of samples in the buffer when accessing the sample buffer directly
-	/// with 'ptrBegin' function.
-	virtual uint32_t receiveSamples(uint32_t maxSamples   ///< Remove this many samples from the beginning of pipe.
-                                )
-	{
-		return this->output->receiveSamples(maxSamples);
-	}
-
-	/// Returns number of samples currently available.
-	virtual uint32_t numSamples() const
-	{
-		return this->output->numSamples();
-	}
-
-	/// Returns nonzero if there aren't any samples available for outputting.
-	virtual bool isEmpty() const
-	{
-		return this->output->isEmpty();
-	}
-
-	/// allow trimming (downwards) amount of samples in pipeline.
-	/// Returns adjusted amount of samples
-	virtual uint32_t adjustAmountOfSamples(uint32_t numSmpls)
-	{
-		return this->output->adjustAmountOfSamples(numSmpls);
-	}
-};
-
-}
-

--- a/src/in_2sf/desmume/metaspu/SoundTouch/FIRFilter.cpp
+++ /dev/null
@@ -1,220 +1,1 @@
-////////////////////////////////////////////////////////////////////////////////
-///
-/// General FIR digital filter routines with MMX optimization.
-///
-/// Note : MMX optimized functions reside in a separate, platform-specific file,
-/// e.g. 'mmx_win.cpp' or 'mmx_gcc.cpp'
-///
-/// Author        : Copyright (c) Olli Parviainen
-/// Author e-mail : oparviai 'at' iki.fi
-/// SoundTouch WWW: http://www.surina.net/soundtouch
-///
-////////////////////////////////////////////////////////////////////////////////
-//
-// Last changed  : $Date: 2011-09-02 15:56:11 -0300 (sex, 02 set 2011) $
-// File revision : $Revision: 4 $
-//
-// $Id: FIRFilter.cpp 131 2011-09-02 18:56:11Z oparviai $
-//
-////////////////////////////////////////////////////////////////////////////////
-//
-// License :
-//
-//  SoundTouch audio processing library
-//  Copyright (c) Olli Parviainen
-//
-//  This library is free software; you can redistribute it and/or
-//  modify it under the terms of the GNU Lesser General Public
-//  License as published by the Free Software Foundation; either
-//  version 2.1 of the License, or (at your option) any later version.
-//
-//  This library is distributed in the hope that it will be useful,
-//  but WITHOUT ANY WARRANTY; without even the implied warranty of
-//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-//  Lesser General Public License for more details.
-//
-//  You should have received a copy of the GNU Lesser General Public
-//  License along with this library; if not, write to the Free Software
-//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
-//
-////////////////////////////////////////////////////////////////////////////////
 
-#include <stdexcept>
-#include <cstring>
-#include <cassert>
-#include <cmath>
-#include "FIRFilter.h"
-#include "cpu_detect.h"
-
-using namespace soundtouch;
-
-/*****************************************************************************
- *
- * Implementation of the class 'FIRFilter'
- *
- *****************************************************************************/
-
-FIRFilter::FIRFilter()
-{
-	this->resultDivFactor = 0;
-	this->resultDivider = 0;
-	this->length = 0;
-	this->lengthDiv8 = 0;
-	this->filterCoeffs.reset();
-}
-
-FIRFilter::~FIRFilter()
-{
-}
-
-// Usual C-version of the filter routine for stereo sound
-uint32_t FIRFilter::evaluateFilterStereo(SAMPLETYPE *dest, const SAMPLETYPE *src, uint32_t numSamples) const
-{
-#ifdef SOUNDTOUCH_FLOAT_SAMPLES
-	// when using floating point samples, use a scaler instead of a divider
-	// because division is much slower operation than multiplying.
-	double dScaler = 1.0 / this->resultDivider;
-#endif
-
-	assert(this->length);
-	assert(!!src);
-	assert(!!dest);
-	assert(!!filterCoeffs);
-
-	uint32_t end = 2 * (numSamples - this->length);
-
-	for (uint32_t j = 0; j < end; j += 2)
-	{
-		LONG_SAMPLETYPE suml = 0, sumr = 0;
-		const SAMPLETYPE *ptr = &src[j];
-
-		for (uint32_t i = 0; i < length; i += 4)
-		{
-			// loop is unrolled by factor of 4 here for efficiency
-			suml += ptr[2 * i] * filterCoeffs[i] + ptr[2 * i + 2] * filterCoeffs[i + 1] + ptr[2 * i + 4] * filterCoeffs[i + 2] + ptr[2 * i + 6] * filterCoeffs[i + 3];
-			sumr += ptr[2 * i + 1] * filterCoeffs[i] + ptr[2 * i + 3] * filterCoeffs[i + 1] + ptr[2 * i + 5] * filterCoeffs[i + 2] + ptr[2 * i + 7] * filterCoeffs[i + 3];
-		}
-
-#ifdef  SOUNDTOUCH_INTEGER_SAMPLES
-		suml >>= this->resultDivFactor;
-		sumr >>= this->resultDivFactor;
-		// saturate to 16 bit integer limits
-		suml = suml < -32768 ? -32768 : (suml > 32767 ? 32767 : suml);
-		// saturate to 16 bit integer limits
-		sumr = sumr < -32768 ? -32768 : (sumr > 32767 ? 32767 : sumr);
-#else
-		suml *= dScaler;
-		sumr *= dScaler;
-#endif //  SOUNDTOUCH_INTEGER_SAMPLES
-		dest[j] = static_cast<SAMPLETYPE>(suml);
-		dest[j + 1] = static_cast<SAMPLETYPE>(sumr);
-	}
-	return numSamples - this->length;
-}
-
-// Usual C-version of the filter routine for mono sound
-uint32_t FIRFilter::evaluateFilterMono(SAMPLETYPE *dest, const SAMPLETYPE *src, uint32_t numSamples) const
-{
-#ifdef SOUNDTOUCH_FLOAT_SAMPLES
-	// when using floating point samples, use a scaler instead of a divider
-	// because division is much slower operation than multiplying.
-	double dScaler = 1.0 / this->resultDivider;
-#endif
-
-	assert(this->length);
-
-	uint32_t end = numSamples - length;
-	for (uint32_t j = 0; j < end; ++j)
-	{
-		LONG_SAMPLETYPE sum = 0;
-		for (uint32_t i = 0; i < length; i += 4)
-		{
-			// loop is unrolled by factor of 4 here for efficiency
-			sum += src[i] * filterCoeffs[i] + src[i + 1] * filterCoeffs[i + 1] + src[i + 2] * filterCoeffs[i + 2] + src[i + 3] * filterCoeffs[i + 3];
-		}
-#ifdef SOUNDTOUCH_INTEGER_SAMPLES
-		sum >>= this->resultDivFactor;
-		// saturate to 16 bit integer limits
-		sum = sum < -32768 ? -32768 : (sum > 32767 ? 32767 : sum);
-#else
-		sum *= dScaler;
-#endif // SOUNDTOUCH_INTEGER_SAMPLES
-		dest[j] = static_cast<SAMPLETYPE>(sum);
-		++src;
-	}
-	return end;
-}
-
-// Set filter coeffiecients and length.
-//
-// Throws an exception if filter length isn't divisible by 8
-void FIRFilter::setCoefficients(const SAMPLETYPE *coeffs, uint32_t newLength, uint32_t uResultDivFactor)
-{
-	assert(newLength > 0);
-	if (newLength % 8)
-		throw std::runtime_error("FIR filter length not divisible by 8");
-
-	this->lengthDiv8 = newLength / 8;
-	this->length = this->lengthDiv8 * 8;
-	assert(this->length == newLength);
-
-	this->resultDivFactor = uResultDivFactor;
-	this->resultDivider = static_cast<SAMPLETYPE>(std::pow(2.0, static_cast<double>(this->resultDivFactor)));
-
-	this->filterCoeffs.reset(new SAMPLETYPE[this->length]);
-	memcpy(this->filterCoeffs.get(), coeffs, this->length * sizeof(SAMPLETYPE));
-}
-
-uint32_t FIRFilter::getLength() const
-{
-	return this->length;
-}
-
-// Applies the filter to the given sequence of samples.
-//
-// Note : The amount of outputted samples is by value of 'filter_length'
-// smaller than the amount of input samples.
-uint32_t FIRFilter::evaluate(SAMPLETYPE *dest, const SAMPLETYPE *src, uint32_t numSamples, uint32_t numChannels) const
-{
-	assert(numChannels == 1 || numChannels == 2);
-
-	assert(this->length > 0);
-	assert(this->lengthDiv8 * 8 == this->length);
-	if (numSamples < this->length)
-		return 0;
-	if (numChannels == 2)
-		return this->evaluateFilterStereo(dest, src, numSamples);
-	else
-		return this->evaluateFilterMono(dest, src, numSamples);
-}
-
-// Operator 'new' is overloaded so that it automatically creates a suitable instance
-// depending on if we've a MMX-capable CPU available or not.
-void *FIRFilter::operator new(size_t)
-{
-	// Notice! don't use "new FIRFilter" directly, use "newInstance" to create a new instance instead!
-	throw std::runtime_error("Don't use 'new FIRFilter', use 'newInstance' member instead!");
-}
-
-FIRFilter *FIRFilter::newInstance()
-{
-	uint32_t uExtensions = detectCPUextensions();
-
-	// Check if MMX/SSE instruction set extensions supported by CPU
-
-#ifdef SOUNDTOUCH_ALLOW_MMX
-	// MMX routines available only with integer sample types
-	if (uExtensions & SUPPORT_MMX)
-		return ::new FIRFilterMMX;
-	else
-#endif // SOUNDTOUCH_ALLOW_MMX
-#ifdef SOUNDTOUCH_ALLOW_SSE
-	if (uExtensions & SUPPORT_SSE)
-		// SSE support
-		return ::new FIRFilterSSE;
-	else
-#endif // SOUNDTOUCH_ALLOW_SSE
-		// ISA optimizations not supported, use plain C version
-		return ::new FIRFilter;
-}
-

--- a/src/in_2sf/desmume/metaspu/SoundTouch/FIRFilter.h
+++ /dev/null
@@ -1,129 +1,1 @@
-////////////////////////////////////////////////////////////////////////////////
-///
-/// General FIR digital filter routines with MMX optimization.
-///
-/// Note : MMX optimized functions reside in a separate, platform-specific file,
-/// e.g. 'mmx_win.cpp' or 'mmx_gcc.cpp'
-///
-/// Author        : Copyright (c) Olli Parviainen
-/// Author e-mail : oparviai 'at' iki.fi
-/// SoundTouch WWW: http://www.surina.net/soundtouch
-///
-////////////////////////////////////////////////////////////////////////////////
-//
-// Last changed  : $Date: 2011-02-13 17:13:57 -0200 (dom, 13 fev 2011) $
-// File revision : $Revision: 4 $
-//
-// $Id: FIRFilter.h 104 2011-02-13 19:13:57Z oparviai $
-//
-////////////////////////////////////////////////////////////////////////////////
-//
-// License :
-//
-//  SoundTouch audio processing library
-//  Copyright (c) Olli Parviainen
-//
-//  This library is free software; you can redistribute it and/or
-//  modify it under the terms of the GNU Lesser General Public
-//  License as published by the Free Software Foundation; either
-//  version 2.1 of the License, or (at your option) any later version.
-//
-//  This library is distributed in the hope that it will be useful,
-//  but WITHOUT ANY WARRANTY; without even the implied warranty of
-//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-//  Lesser General Public License for more details.
-//
-//  You should have received a copy of the GNU Lesser General Public
-//  License along with this library; if not, write to the Free Software
-//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
-//
-////////////////////////////////////////////////////////////////////////////////
 
-#pragma once
-
-#include <memory>
-#include "STTypes.h"
-
-namespace soundtouch
-{
-
-class FIRFilter
-{
-protected:
-	// Number of FIR filter taps
-	uint32_t length;
-	// Number of FIR filter taps divided by 8
-	uint32_t lengthDiv8;
-
-	// Result divider factor in 2^k format
-	uint32_t resultDivFactor;
-
-	// Result divider value.
-	SAMPLETYPE resultDivider;
-
-	// Memory for filter coefficients
-	std::unique_ptr<SAMPLETYPE[]> filterCoeffs;
-
-	virtual uint32_t evaluateFilterStereo(SAMPLETYPE *dest, const SAMPLETYPE *src, uint32_t numSamples) const;
-	virtual uint32_t evaluateFilterMono(SAMPLETYPE *dest, const SAMPLETYPE *src, uint32_t numSamples) const;
-
-public:
-	FIRFilter();
-	virtual ~FIRFilter();
-
-	/// Operator 'new' is overloaded so that it automatically creates a suitable instance
-	/// depending on if we've a MMX-capable CPU available or not.
-	static void *operator new(size_t s);
-
-	static FIRFilter *newInstance();
-
-	/// Applies the filter to the given sequence of samples.
-	/// Note : The amount of outputted samples is by value of 'filter_length'
-	/// smaller than the amount of input samples.
-	///
-	/// \return Number of samples copied to 'dest'.
-	uint32_t evaluate(SAMPLETYPE *dest, const SAMPLETYPE *src, uint32_t numSamples, uint32_t numChannels) const;
-
-	uint32_t getLength() const;
-
-	virtual void setCoefficients(const SAMPLETYPE *coeffs, uint32_t newLength, uint32_t uResultDivFactor);
-};
-
-// Optional subclasses that implement CPU-specific optimizations:
-
-#ifdef SOUNDTOUCH_ALLOW_MMX
-/// Class that implements MMX optimized functions exclusive for 16bit integer samples type.
-class FIRFilterMMX : public FIRFilter
-{
-protected:
-	std::unique_ptr<short[]> filterCoeffsUnalign;
-	short *filterCoeffsAlign;
-
-	virtual uint32_t evaluateFilterStereo(short *dest, const short *src, uint32_t numSamples) const;
-public:
-	FIRFilterMMX();
-	~FIRFilterMMX();
-
-	virtual void setCoefficients(const short *coeffs, uint32_t newLength, uint32_t uResultDivFactor);
-};
-#endif // SOUNDTOUCH_ALLOW_MMX
-
-#ifdef SOUNDTOUCH_ALLOW_SSE
-/// Class that implements SSE optimized functions exclusive for floating point samples type.
-class FIRFilterSSE : public FIRFilter
-{
-protected:
-	std::unique_ptr<float[]> filterCoeffsUnalign;
-	float *filterCoeffsAlign;
-
-	virtual uint32_t evaluateFilterStereo(float *dest, const float *src, uint32_t numSamples) const;
-public:
-	FIRFilterSSE();
-	~FIRFilterSSE();
-
-	virtual void setCoefficients(const float *coeffs, uint32_t newLength, uint32_t uResultDivFactor);
-};
-#endif // SOUNDTOUCH_ALLOW_SSE
-
-}
-

--- a/src/in_2sf/desmume/metaspu/SoundTouch/RateTransposer.cpp
+++ /dev/null
@@ -1,528 +1,1 @@
-////////////////////////////////////////////////////////////////////////////////
-///
-/// Sample rate transposer. Changes sample rate by using linear interpolation
-/// together with anti-alias filtering (first order interpolation with anti-
-/// alias filtering should be quite adequate for this application)
-///
-/// Author        : Copyright (c) Olli Parviainen
-/// Author e-mail : oparviai 'at' iki.fi
-/// SoundTouch WWW: http://www.surina.net/soundtouch
-///
-////////////////////////////////////////////////////////////////////////////////
-//
-// Last changed  : $Date: 2011-09-02 15:56:11 -0300 (sex, 02 set 2011) $
-// File revision : $Revision: 4 $
-//
-// $Id: RateTransposer.cpp 131 2011-09-02 18:56:11Z oparviai $
-//
-////////////////////////////////////////////////////////////////////////////////
-//
-// License :
-//
-//  SoundTouch audio processing library
-//  Copyright (c) Olli Parviainen
-//
-//  This library is free software; you can redistribute it and/or
-//  modify it under the terms of the GNU Lesser General Public
-//  License as published by the Free Software Foundation; either
-//  version 2.1 of the License, or (at your option) any later version.
-//
-//  This library is distributed in the hope that it will be useful,
-//  but WITHOUT ANY WARRANTY; without even the implied warranty of
-//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-//  Lesser General Public License for more details.
-//
-//  You should have received a copy of the GNU Lesser General Public
-//  License along with this library; if not, write to the Free Software
-//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
-//
-////////////////////////////////////////////////////////////////////////////////
 
-#include <stdexcept>
-#include "RateTransposer.h"
-
-using namespace soundtouch;
-
-/// A linear samplerate transposer class that uses integer arithmetics.
-/// for the transposing.
-class RateTransposerInteger : public RateTransposer
-{
-protected:
-	int iSlopeCount;
-	int iRate;
-	SAMPLETYPE sPrevSampleL, sPrevSampleR;
-
-	virtual void resetRegisters();
-
-	virtual uint32_t transposeStereo(SAMPLETYPE *dest, const SAMPLETYPE *src, uint32_t numSamples);
-	virtual uint32_t transposeMono(SAMPLETYPE *dest, const SAMPLETYPE *src, uint32_t numSamples);
-
-public:
-	RateTransposerInteger();
-	virtual ~RateTransposerInteger();
-
-	/// Sets new target rate. Normal rate = 1.0, smaller values represent slower
-	/// rate, larger faster rates.
-	virtual void setRate(float newRate);
-};
-
-/// A linear samplerate transposer class that uses floating point arithmetics
-/// for the transposing.
-class RateTransposerFloat : public RateTransposer
-{
-protected:
-	float fSlopeCount;
-	SAMPLETYPE sPrevSampleL, sPrevSampleR;
-
-	virtual void resetRegisters();
-
-	virtual uint32_t transposeStereo(SAMPLETYPE *dest, const SAMPLETYPE *src, uint32_t numSamples);
-	virtual uint32_t transposeMono(SAMPLETYPE *dest, const SAMPLETYPE *src, uint32_t numSamples);
-
-public:
-	RateTransposerFloat();
-	virtual ~RateTransposerFloat();
-};
-
-// Operator 'new' is overloaded so that it automatically creates a suitable instance
-// depending on if we've a MMX/SSE/etc-capable CPU available or not.
-void *RateTransposer::operator new(size_t)
-{
-	// Notice! don't use "new TDStretch" directly, use "newInstance" to create a new instance instead!
-	//assert(false);
-	//return NULL;
-	throw std::runtime_error("Don't use 'new RateTransposer', use 'newInstance' member instead!");
-}
-
-RateTransposer *RateTransposer::newInstance()
-{
-#ifdef SOUNDTOUCH_INTEGER_SAMPLES
-	return ::new RateTransposerInteger;
-#else
-	return ::new RateTransposerFloat;
-#endif
-}
-
-// Constructor
-RateTransposer::RateTransposer() : FIFOProcessor(&outputBuffer)
-{
-	this->numChannels = 2;
-	this->bUseAAFilter = true;
-	this->fRate = 0;
-
-	// Instantiates the anti-alias filter with default tap length
-	// of 32
-	this->pAAFilter.reset(new AAFilter(32));
-}
-
-RateTransposer::~RateTransposer()
-{
-}
-
-/// Enables/disables the anti-alias filter. Zero to disable, nonzero to enable
-void RateTransposer::enableAAFilter(bool newMode)
-{
-	this->bUseAAFilter = newMode;
-}
-
-/// Returns nonzero if anti-alias filter is enabled.
-bool RateTransposer::isAAFilterEnabled() const
-{
-	return this->bUseAAFilter;
-}
-
-AAFilter *RateTransposer::getAAFilter()
-{
-	return this->pAAFilter.get();
-}
-
-// Sets new target iRate. Normal iRate = 1.0, smaller values represent slower
-// iRate, larger faster iRates.
-void RateTransposer::setRate(float newRate)
-{
-	double fCutoff;
-
-	this->fRate = newRate;
-
-	// design a new anti-alias filter
-	if (newRate > 1.0f)
-		fCutoff = 0.5f / newRate;
-	else
-		fCutoff = 0.5f * newRate;
-    this->pAAFilter->setCutoffFreq(fCutoff);
-}
-
-// Adds 'nSamples' pcs of samples from the 'samples' memory position into
-// the input of the object.
-void RateTransposer::putSamples(const SAMPLETYPE *samples, uint32_t nSamples)
-{
-	this->processSamples(samples, nSamples);
-}
-
-// Transposes up the sample rate, causing the observed playback 'rate' of the
-// sound to decrease
-void RateTransposer::upsample(const SAMPLETYPE *src, uint32_t nSamples)
-{
-	// If the parameter 'uRate' value is smaller than 'SCALE', first transpose
-	// the samples and then apply the anti-alias filter to remove aliasing.
-
-	// First check that there's enough room in 'storeBuffer'
-	// (+16 is to reserve some slack in the destination buffer)
-	uint32_t sizeTemp = static_cast<uint32_t>(nSamples / this->fRate + 16.0f);
-
-	// Transpose the samples, store the result into the end of "storeBuffer"
-	uint32_t count = this->transpose(this->storeBuffer.ptrEnd(sizeTemp), src, nSamples);
-	this->storeBuffer.putSamples(count);
-
-	// Apply the anti-alias filter to samples in "store output", output the
-	// result to "dest"
-	uint32_t num = this->storeBuffer.numSamples();
-	count = this->pAAFilter->evaluate(this->outputBuffer.ptrEnd(num), this->storeBuffer.ptrBegin(), num, this->numChannels);
-	this->outputBuffer.putSamples(count);
-
-	// Remove the processed samples from "storeBuffer"
-	this->storeBuffer.receiveSamples(count);
-}
-
-// Transposes down the sample rate, causing the observed playback 'rate' of the
-// sound to increase
-void RateTransposer::downsample(const SAMPLETYPE *src, uint32_t nSamples)
-{
-	// If the parameter 'uRate' value is larger than 'SCALE', first apply the
-	// anti-alias filter to remove high frequencies (prevent them from folding
-	// over the lover frequencies), then transpose. */
-
-	// Add the new samples to the end of the storeBuffer */
-	this->storeBuffer.putSamples(src, nSamples);
-
-	// Anti-alias filter the samples to prevent folding and output the filtered
-	// data to tempBuffer. Note : because of the FIR filter length, the
-	// filtering routine takes in 'filter_length' more samples than it outputs.
-	assert(this->tempBuffer.isEmpty());
-	uint32_t sizeTemp = this->storeBuffer.numSamples();
-
-	uint32_t count = this->pAAFilter->evaluate(this->tempBuffer.ptrEnd(sizeTemp), this->storeBuffer.ptrBegin(), sizeTemp, this->numChannels);
-
-	// Remove the filtered samples from 'storeBuffer'
-	this->storeBuffer.receiveSamples(count);
-
-	// Transpose the samples (+16 is to reserve some slack in the destination buffer)
-	sizeTemp = static_cast<uint32_t>(nSamples / this->fRate + 16.0f);
-	count = this->transpose(this->outputBuffer.ptrEnd(sizeTemp), this->tempBuffer.ptrBegin(), count);
-	this->outputBuffer.putSamples(count);
-}
-
-// Transposes sample rate by applying anti-alias filter to prevent folding.
-// Returns amount of samples returned in the "dest" buffer.
-// The maximum amount of samples that can be returned at a time is set by
-// the 'set_returnBuffer_size' function.
-void RateTransposer::processSamples(const SAMPLETYPE *src, uint32_t nSamples)
-{
-	if (!nSamples)
-		return;
-	assert(this->pAAFilter);
-
-	// If anti-alias filter is turned off, simply transpose without applying
-	// the filter
-	if (!bUseAAFilter)
-	{
-		uint32_t sizeReq = static_cast<uint32_t>(nSamples / this->fRate + 1.0f);
-		uint32_t count = this->transpose(this->outputBuffer.ptrEnd(sizeReq), src, nSamples);
-		this->outputBuffer.putSamples(count);
-		return;
-	}
-
-	// Transpose with anti-alias filter
-	if (this->fRate < 1.0f)
-		this->upsample(src, nSamples);
-	else
-		this->downsample(src, nSamples);
-}
-
-// Transposes the sample rate of the given samples using linear interpolation.
-// Returns the number of samples returned in the "dest" buffer
-uint32_t RateTransposer::transpose(SAMPLETYPE *dest, const SAMPLETYPE *src, uint32_t nSamples)
-{
-	if (this->numChannels == 2)
-		return this->transposeStereo(dest, src, nSamples);
-	else
-		return this->transposeMono(dest, src, nSamples);
-}
-
-// Sets the number of channels, 1 = mono, 2 = stereo
-void RateTransposer::setChannels(int32_t nChannels)
-{
-	assert(nChannels > 0);
-	if (this->numChannels == nChannels)
-		return;
-
-	assert(nChannels == 1 || nChannels == 2);
-	this->numChannels = nChannels;
-
-	this->storeBuffer.setChannels(this->numChannels);
-	this->tempBuffer.setChannels(this->numChannels);
-	this->outputBuffer.setChannels(this->numChannels);
-
-	// Inits the linear interpolation registers
-	this->resetRegisters();
-}
-
-// Clears all the samples in the object
-void RateTransposer::clear()
-{
-	this->outputBuffer.clear();
-	this->storeBuffer.clear();
-}
-
-// Returns nonzero if there aren't any samples available for outputting.
-bool RateTransposer::isEmpty() const
-{
-	bool res = FIFOProcessor::isEmpty();
-	if (!res)
-		return false;
-	return this->storeBuffer.isEmpty();
-}
-
-//////////////////////////////////////////////////////////////////////////////
-//
-// RateTransposerInteger - integer arithmetic implementation
-//
-
-/// fixed-point interpolation routine precision
-static const int SCALE = 65536;
-
-// Constructor
-RateTransposerInteger::RateTransposerInteger() : RateTransposer()
-{
-	// Notice: use local function calling syntax for sake of clarity,
-	// to indicate the fact that C++ constructor can't call virtual functions.
-	RateTransposerInteger::resetRegisters();
-	RateTransposerInteger::setRate(1.0f);
-}
-
-RateTransposerInteger::~RateTransposerInteger()
-{
-}
-
-void RateTransposerInteger::resetRegisters()
-{
-	this->iSlopeCount = 0;
-	this->sPrevSampleL = this->sPrevSampleR = 0;
-}
-
-// Transposes the sample rate of the given samples using linear interpolation.
-// 'Mono' version of the routine. Returns the number of samples returned in
-// the "dest" buffer
-uint32_t RateTransposerInteger::transposeMono(SAMPLETYPE *dest, const SAMPLETYPE *src, uint32_t nSamples)
-{
-	if (!nSamples)
-		return 0; // no samples, no work
-
-	unsigned used = 0, i = 0;
-
-	// Process the last sample saved from the previous call first...
-	LONG_SAMPLETYPE temp, vol1;
-	while (this->iSlopeCount <= SCALE)
-	{
-		vol1 = SCALE - this->iSlopeCount;
-		temp = vol1 * this->sPrevSampleL + this->iSlopeCount * src[0];
-		dest[i] = static_cast<SAMPLETYPE>(temp / SCALE);
-		++i;
-		this->iSlopeCount += this->iRate;
-	}
-	// now always (iSlopeCount > SCALE)
-	this->iSlopeCount -= SCALE;
-
-	while (1)
-	{
-		while (this->iSlopeCount > SCALE)
-		{
-			this->iSlopeCount -= SCALE;
-			++used;
-			if (used >= nSamples - 1)
-				goto end;
-		}
-		vol1 = SCALE - this->iSlopeCount;
-		temp = src[used] * vol1 + this->iSlopeCount * src[used + 1];
-		dest[i] = static_cast<SAMPLETYPE>(temp / SCALE);
-		++i;
-		this->iSlopeCount += this->iRate;
-	}
-end:
-	// Store the last sample for the next round
-	this->sPrevSampleL = src[nSamples - 1];
-
-	return i;
-}
-
-// Transposes the sample rate of the given samples using linear interpolation.
-// 'Stereo' version of the routine. Returns the number of samples returned in
-// the "dest" buffer
-uint32_t RateTransposerInteger::transposeStereo(SAMPLETYPE *dest, const SAMPLETYPE *src, uint32_t nSamples)
-{
-	if (!nSamples)
-		return 0; // no samples, no work
-
-	unsigned used = 0, i = 0;
-
-	// Process the last sample saved from the sPrevSampleLious call first...
-	LONG_SAMPLETYPE temp, vol1;
-	while (this->iSlopeCount <= SCALE)
-	{
-		vol1 = SCALE - this->iSlopeCount;
-		temp = vol1 * this->sPrevSampleL + this->iSlopeCount * src[0];
-		dest[2 * i] = static_cast<SAMPLETYPE>(temp / SCALE);
-		temp = vol1 * this->sPrevSampleR + this->iSlopeCount * src[1];
-		dest[2 * i + 1] = static_cast<SAMPLETYPE>(temp / SCALE);
-		++i;
-		this->iSlopeCount += this->iRate;
-	}
-	// now always (iSlopeCount > SCALE)
-	this->iSlopeCount -= SCALE;
-
-	while (1)
-	{
-		while (this->iSlopeCount > SCALE)
-		{
-			this->iSlopeCount -= SCALE;
-			++used;
-			if (used >= nSamples - 1)
-				goto end;
-		}
-		unsigned srcPos = 2 * used;
-		vol1 = SCALE - this->iSlopeCount;
-		temp = src[srcPos] * vol1 + this->iSlopeCount * src[srcPos + 2];
-		dest[2 * i] = static_cast<SAMPLETYPE>(temp / SCALE);
-		temp = src[srcPos + 1] * vol1 + this->iSlopeCount * src[srcPos + 3];
-		dest[2 * i + 1] = static_cast<SAMPLETYPE>(temp / SCALE);
-		++i;
-		this->iSlopeCount += this->iRate;
-	}
-end:
-	// Store the last sample for the next round
-	this->sPrevSampleL = src[2 * nSamples - 2];
-	this->sPrevSampleR = src[2 * nSamples - 1];
-
-	return i;
-}
-
-// Sets new target iRate. Normal iRate = 1.0, smaller values represent slower
-// iRate, larger faster iRates.
-void RateTransposerInteger::setRate(float newRate)
-{
-	this->iRate = static_cast<int>(newRate * SCALE + 0.5f);
-	RateTransposer::setRate(newRate);
-}
-
-//////////////////////////////////////////////////////////////////////////////
-//
-// RateTransposerFloat - floating point arithmetic implementation
-//
-//////////////////////////////////////////////////////////////////////////////
-
-// Constructor
-RateTransposerFloat::RateTransposerFloat() : RateTransposer()
-{
-	// Notice: use local function calling syntax for sake of clarity,
-	// to indicate the fact that C++ constructor can't call virtual functions.
-	RateTransposerFloat::resetRegisters();
-	RateTransposerFloat::setRate(1.0f);
-}
-
-RateTransposerFloat::~RateTransposerFloat()
-{
-}
-
-void RateTransposerFloat::resetRegisters()
-{
-	this->fSlopeCount = 0;
-	this->sPrevSampleL = this->sPrevSampleR = 0;
-}
-
-// Transposes the sample rate of the given samples using linear interpolation.
-// 'Mono' version of the routine. Returns the number of samples returned in
-// the "dest" buffer
-uint32_t RateTransposerFloat::transposeMono(SAMPLETYPE *dest, const SAMPLETYPE *src, uint32_t nSamples)
-{
-	unsigned used = 0, i = 0;
-
-	// Process the last sample saved from the previous call first...
-	while (this->fSlopeCount <= 1.0f)
-	{
-		dest[i] = static_cast<SAMPLETYPE>((1.0f - this->fSlopeCount) * this->sPrevSampleL + this->fSlopeCount * src[0]);
-		++i;
-		this->fSlopeCount += this->fRate;
-	}
-	this->fSlopeCount -= 1.0f;
-
-	if (nSamples > 1)
-	{
-		while (1)
-		{
-			while (this->fSlopeCount > 1.0f)
-			{
-				this->fSlopeCount -= 1.0f;
-				++used;
-				if (used >= nSamples - 1)
-					goto end;
-			}
-			dest[i] = static_cast<SAMPLETYPE>((1.0f - this->fSlopeCount) * src[used] + this->fSlopeCount * src[used + 1]);
-			++i;
-			this->fSlopeCount += this->fRate;
-		}
-	}
-end:
-	// Store the last sample for the next round
-	this->sPrevSampleL = src[nSamples - 1];
-
-	return i;
-}
-
-// Transposes the sample rate of the given samples using linear interpolation.
-// 'Mono' version of the routine. Returns the number of samples returned in
-// the "dest" buffer
-uint32_t RateTransposerFloat::transposeStereo(SAMPLETYPE *dest, const SAMPLETYPE *src, uint32_t nSamples)
-{
-	if (!nSamples)
-		return 0; // no samples, no work
-
-	unsigned used = 0, i = 0;
-
-	// Process the last sample saved from the sPrevSampleLious call first...
-	while (this->fSlopeCount <= 1.0f)
-	{
-		dest[2 * i] = static_cast<SAMPLETYPE>((1.0f - this->fSlopeCount) * this->sPrevSampleL + this->fSlopeCount * src[0]);
-		dest[2 * i + 1] = static_cast<SAMPLETYPE>((1.0f - this->fSlopeCount) * this->sPrevSampleR + this->fSlopeCount * src[1]);
-		++i;
-		this->fSlopeCount += this->fRate;
-	}
-	// now always (iSlopeCount > 1.0f)
-	this->fSlopeCount -= 1.0f;
-
-	if (nSamples > 1)
-	{
-		while (1)
-		{
-			while (this->fSlopeCount > 1.0f)
-			{
-				this->fSlopeCount -= 1.0f;
-				++used;
-				if (used >= nSamples - 1)
-					goto end;
-			}
-			unsigned srcPos = 2 * used;
-
-			dest[2 * i] = static_cast<SAMPLETYPE>((1.0f - this->fSlopeCount) * src[srcPos] + this->fSlopeCount * src[srcPos + 2]);
-			dest[2 * i + 1] = static_cast<SAMPLETYPE>((1.0f - this->fSlopeCount) * src[srcPos + 1] + this->fSlopeCount * src[srcPos + 3]);
-			++i;
-			this->fSlopeCount += this->fRate;
-		}
-	}
-end:
-	// Store the last sample for the next round
-	this->sPrevSampleL = src[2 * nSamples - 2];
-	this->sPrevSampleR = src[2 * nSamples - 1];
-
-	return i;
-}
-

--- a/src/in_2sf/desmume/metaspu/SoundTouch/RateTransposer.h
+++ /dev/null
@@ -1,143 +1,1 @@
-////////////////////////////////////////////////////////////////////////////////
-///
-/// Sample rate transposer. Changes sample rate by using linear interpolation
-/// together with anti-alias filtering (first order interpolation with anti-
-/// alias filtering should be quite adequate for this application).
-///
-/// Use either of the derived classes of 'RateTransposerInteger' or
-/// 'RateTransposerFloat' for corresponding integer/floating point tranposing
-/// algorithm implementation.
-///
-/// Author        : Copyright (c) Olli Parviainen
-/// Author e-mail : oparviai 'at' iki.fi
-/// SoundTouch WWW: http://www.surina.net/soundtouch
-///
-////////////////////////////////////////////////////////////////////////////////
-//
-// Last changed  : $Date: 2009-02-21 13:00:14 -0300 (s�b, 21 fev 2009) $
-// File revision : $Revision: 4 $
-//
-// $Id: RateTransposer.h 63 2009-02-21 16:00:14Z oparviai $
-//
-////////////////////////////////////////////////////////////////////////////////
-//
-// License :
-//
-//  SoundTouch audio processing library
-//  Copyright (c) Olli Parviainen
-//
-//  This library is free software; you can redistribute it and/or
-//  modify it under the terms of the GNU Lesser General Public
-//  License as published by the Free Software Foundation; either
-//  version 2.1 of the License, or (at your option) any later version.
-//
-//  This library is distributed in the hope that it will be useful,
-//  but WITHOUT ANY WARRANTY; without even the implied warranty of
-//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-//  Lesser General Public License for more details.
-//
-//  You should have received a copy of the GNU Lesser General Public
-//  License along with this library; if not, write to the Free Software
-//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
-//
-////////////////////////////////////////////////////////////////////////////////
 
-#pragma once
-
-#include "AAFilter.h"
-#include "FIFOSampleBuffer.h"
-
-namespace soundtouch
-{
-
-/// A common linear samplerate transposer class.
-///
-/// Note: Use function "RateTransposer::newInstance()" to create a new class
-/// instance instead of the "new" operator; that function automatically
-/// chooses a correct implementation depending on if integer or floating
-/// arithmetics are to be used.
-class RateTransposer : public FIFOProcessor
-{
-protected:
-	/// Anti-alias filter object
-	std::unique_ptr<AAFilter> pAAFilter;
-
-	float fRate;
-
-	int32_t numChannels;
-
-	/// Buffer for collecting samples to feed the anti-alias filter between
-	/// two batches
-	FIFOSampleBuffer storeBuffer;
-
-	/// Buffer for keeping samples between transposing & anti-alias filter
-	FIFOSampleBuffer tempBuffer;
-
-	/// Output sample buffer
-	FIFOSampleBuffer outputBuffer;
-
-	bool bUseAAFilter;
-
-	virtual void resetRegisters() = 0;
-
-	virtual uint32_t transposeStereo(SAMPLETYPE *dest, const SAMPLETYPE *src, uint32_t numSamples) = 0;
-	virtual uint32_t transposeMono(SAMPLETYPE *dest, const SAMPLETYPE *src, uint32_t numSamples) = 0;
-	uint32_t transpose(SAMPLETYPE *dest, const SAMPLETYPE *src, uint32_t numSamples);
-
-	void downsample(const SAMPLETYPE *src, uint32_t numSamples);
-	void upsample(const SAMPLETYPE *src, uint32_t numSamples);
-
-	/// Transposes sample rate by applying anti-alias filter to prevent folding.
-	/// Returns amount of samples returned in the "dest" buffer.
-	/// The maximum amount of samples that can be returned at a time is set by
-	/// the 'set_returnBuffer_size' function.
-	void processSamples(const SAMPLETYPE *src, uint32_t numSamples);
-
-public:
-	RateTransposer();
-	virtual ~RateTransposer();
-
-	/// Operator 'new' is overloaded so that it automatically creates a suitable instance
-	/// depending on if we're to use integer or floating point arithmetics.
-	static void *operator new(size_t s);
-
-	/// Use this function instead of "new" operator to create a new instance of this class.
-	/// This function automatically chooses a correct implementation, depending on if
-	/// integer ot floating point arithmetics are to be used.
-	static RateTransposer *newInstance();
-
-	/// Returns the output buffer object
-	FIFOSamplePipe *getOutput() { return &this->outputBuffer; }
-
-	/// Returns the store buffer object
-	FIFOSamplePipe *getStore() { return &this->storeBuffer; }
-
-	/// Return anti-alias filter object
-	AAFilter *getAAFilter();
-
-	/// Enables/disables the anti-alias filter. Zero to disable, nonzero to enable
-	void enableAAFilter(bool newMode);
-
-	/// Returns nonzero if anti-alias filter is enabled.
-	bool isAAFilterEnabled() const;
-
-	/// Sets new target rate. Normal rate = 1.0, smaller values represent slower
-	/// rate, larger faster rates.
-	virtual void setRate(float newRate);
-
-	/// Sets the number of channels, 1 = mono, 2 = stereo
-	void setChannels(int32_t channels);
-
-	/// Adds 'numSamples' pcs of samples from the 'samples' memory position into
-	/// the input of the object.
-	void putSamples(const SAMPLETYPE *samples, uint32_t numSamples);
-
-	/// Clears all the samples in the object
-	void clear();
-
-	/// Returns nonzero if there aren't any samples available for outputting.
-	bool isEmpty() const;
-};
-
-}
-

--- a/src/in_2sf/desmume/metaspu/SoundTouch/STTypes.h
+++ /dev/null
@@ -1,132 +1,1 @@
-////////////////////////////////////////////////////////////////////////////////
-///
-/// Common type definitions for SoundTouch audio processing library.
-///
-/// Author        : Copyright (c) Olli Parviainen
-/// Author e-mail : oparviai 'at' iki.fi
-/// SoundTouch WWW: http://www.surina.net/soundtouch
-///
-////////////////////////////////////////////////////////////////////////////////
-//
-// Last changed  : $Date: 2006/02/05 16:44:06 $
-// File revision : $Revision: 1.16 $
-//
-// $Id: STTypes.h,v 1.16 2006/02/05 16:44:06 Olli Exp $
-//
-////////////////////////////////////////////////////////////////////////////////
-//
-// License :
-//
-//  SoundTouch audio processing library
-//  Copyright (c) Olli Parviainen
-//
-//  This library is free software; you can redistribute it and/or
-//  modify it under the terms of the GNU Lesser General Public
-//  License as published by the Free Software Foundation; either
-//  version 2.1 of the License, or (at your option) any later version.
-//
-//  This library is distributed in the hope that it will be useful,
-//  but WITHOUT ANY WARRANTY; without even the implied warranty of
-//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-//  Lesser General Public License for more details.
-//
-//  You should have received a copy of the GNU Lesser General Public
-//  License along with this library; if not, write to the Free Software
-//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
-//
-////////////////////////////////////////////////////////////////////////////////
 
-#pragma once
-
-#include <cstdint>
-
-namespace soundtouch
-{
-
-/// Activate these undef's to overrule the possible sampletype
-/// setting inherited from some other header file:
-//#undef SOUNDTOUCH_INTEGER_SAMPLES
-//#undef SOUNDTOUCH_FLOAT_SAMPLES
-
-#if !defined(SOUNDTOUCH_INTEGER_SAMPLES) || !defined(SOUNDTOUCH_FLOAT_SAMPLES)
-/// Choose either 32bit floating point or 16bit integer sampletype
-/// by choosing one of the following defines, unless this selection
-/// has already been done in some other file.
-////
-/// Notes:
-/// - In Windows environment, choose the sample format with the
-///   following defines.
-/// - In GNU environment, the floating point samples are used by
-///   default, but integer samples can be chosen by giving the
-///   following switch to the configure script:
-///       ./configure --enable-integer-samples
-///   However, if you still prefer to select the sample format here
-///   also in GNU environment, then please #undef the INTEGER_SAMPLE
-///   and FLOAT_SAMPLE defines first as in comments above.
-//# define SOUNDTOUCH_INTEGER_SAMPLES 1 //< 16bit integer samples
-# define SOUNDTOUCH_FLOAT_SAMPLES 1 //< 32bit float samples
-#endif
-
-#if defined(_M_IX86) || defined(__i386__) || defined(__x86_64__) || defined(_M_X64)
-/// Define this to allow X86-specific assembler/intrinsic optimizations.
-/// Notice that library contains also usual C++ versions of each of these
-/// these routines, so if you're having difficulties getting the optimized
-/// routines compiled for whatever reason, you may disable these optimizations
-/// to make the library compile.
-# define SOUNDTOUCH_ALLOW_X86_OPTIMIZATIONS 1
-
-/// In GNU environment, allow the user to override this setting by
-/// giving the following switch to the configure script:
-/// ./configure --disable-x86-optimizations
-/// ./configure --enable-x86-optimizations=no
-# ifdef SOUNDTOUCH_DISABLE_X86_OPTIMIZATIONS
-#  undef SOUNDTOUCH_ALLOW_X86_OPTIMIZATIONS
-# endif
-#else
-/// Always disable optimizations when not using a x86 systems.
-# undef SOUNDTOUCH_ALLOW_X86_OPTIMIZATIONS
-#endif
-
-// If defined, allows the SIMD-optimized routines to take minor shortcuts
-// for improved performance. Undefine to require faithfully similar SIMD
-// calculations as in normal C implementation.
-#define SOUNDTOUCH_ALLOW_NONEXACT_SIMD_OPTIMIZATION 1
-
-#ifdef SOUNDTOUCH_INTEGER_SAMPLES
-// 16bit integer sample type
-typedef short SAMPLETYPE;
-// data type for sample accumulation: Use 32bit integer to prevent overflows
-typedef long LONG_SAMPLETYPE;
-
-# ifdef SOUNDTOUCH_FLOAT_SAMPLES
-// check that only one sample type is defined
-#  error "conflicting sample types defined"
-# endif // SOUNDTOUCH_FLOAT_SAMPLES
-
-# ifdef SOUNDTOUCH_ALLOW_X86_OPTIMIZATIONS
-// Allow MMX optimizations
-#  define SOUNDTOUCH_ALLOW_MMX 1
-# endif
-#else
-// floating point samples
-typedef float SAMPLETYPE;
-// data type for sample accumulation: Use double to utilize full precision.
-typedef double LONG_SAMPLETYPE;
-
-# ifdef SOUNDTOUCH_ALLOW_X86_OPTIMIZATIONS
-// Allow SSE optimizations
-#  define SOUNDTOUCH_ALLOW_SSE 1
-# endif
-#endif // SOUNDTOUCH_INTEGER_SAMPLES
-
-// Helper macro for aligning pointer up to next 16-byte boundary
-inline uintptr_t SOUNDTOUCH_ALIGN_POINTER_16(SAMPLETYPE *x) { return (reinterpret_cast<uintptr_t>(x) + 15) & ~static_cast<uintptr_t>(15); }
-
-// When this #define is active, eliminates a clicking sound when the "rate" or "pitch"
-// parameter setting crosses from value <1 to >=1 or vice versa during processing.
-// Default is off as such crossover is untypical case and involves a slight sound
-// quality compromise.
-//#define SOUNDTOUCH_PREVENT_CLICK_AT_RATE_CROSSOVER 1
-
-}
-

--- a/src/in_2sf/desmume/metaspu/SoundTouch/SoundTouch.cpp
+++ /dev/null
@@ -1,337 +1,1 @@
-//////////////////////////////////////////////////////////////////////////////
-///
-/// SoundTouch - main class for tempo/pitch/rate adjusting routines.
-///
-/// Notes:
-/// - Initialize the SoundTouch object instance by setting up the sound stream
-///   parameters with functions 'setSampleRate' and 'setChannels', then set
-///   desired tempo/pitch/rate settings with the corresponding functions.
-///
-/// - The SoundTouch class behaves like a first-in-first-out pipeline: The
-///   samples that are to be processed are fed into one of the pipe by calling
-///   function 'putSamples', while the ready processed samples can be read
-///   from the other end of the pipeline with function 'receiveSamples'.
-///
-/// - The SoundTouch processing classes require certain sized 'batches' of
-///   samples in order to process the sound. For this reason the classes buffer
-///   incoming samples until there are enough of samples available for
-///   processing, then they carry out the processing step and consequently
-///   make the processed samples available for outputting.
-///
-/// - For the above reason, the processing routines introduce a certain
-///   'latency' between the input and output, so that the samples input to
-///   SoundTouch may not be immediately available in the output, and neither
-///   the amount of outputtable samples may not immediately be in direct
-///   relationship with the amount of previously input samples.
-///
-/// - The tempo/pitch/rate control parameters can be altered during processing.
-///   Please notice though that they aren't currently protected by semaphores,
-///   so in multi-thread application external semaphore protection may be
-///   required.
-///
-/// - This class utilizes classes 'TDStretch' for tempo change (without modifying
-///   pitch) and 'RateTransposer' for changing the playback rate (that is, both
-///   tempo and pitch in the same ratio) of the sound. The third available control
-///   'pitch' (change pitch but maintain tempo) is produced by a combination of
-///   combining the two other controls.
-///
-/// Author        : Copyright (c) Olli Parviainen
-/// Author e-mail : oparviai 'at' iki.fi
-/// SoundTouch WWW: http://www.surina.net/soundtouch
-///
-////////////////////////////////////////////////////////////////////////////////
-//
-// Last changed  : $Date: 2012-06-13 16:29:53 -0300 (qua, 13 jun 2012) $
-// File revision : $Revision: 4 $
-//
-// $Id: SoundTouch.cpp 143 2012-06-13 19:29:53Z oparviai $
-//
-////////////////////////////////////////////////////////////////////////////////
-//
-// License :
-//
-//  SoundTouch audio processing library
-//  Copyright (c) Olli Parviainen
-//
-//  This library is free software; you can redistribute it and/or
-//  modify it under the terms of the GNU Lesser General Public
-//  License as published by the Free Software Foundation; either
-//  version 2.1 of the License, or (at your option) any later version.
-//
-//  This library is distributed in the hope that it will be useful,
-//  but WITHOUT ANY WARRANTY; without even the implied warranty of
-//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-//  Lesser General Public License for more details.
-//
-//  You should have received a copy of the GNU Lesser General Public
-//  License along with this library; if not, write to the Free Software
-//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
-//
-////////////////////////////////////////////////////////////////////////////////
 
-#include "XSFCommon.h"
-
-#include <stdexcept>
-#include <cassert>
-#include <cstdlib>
-#include <cstring>
-#include <cstdio>
-#include "SoundTouch.h"
-#include "cpu_detect.h"
-
-using namespace soundtouch;
-
-SoundTouch::SoundTouch()
-{
-	// Initialize rate transposer and tempo changer instances
-
-	this->pRateTransposer.reset(RateTransposer::newInstance());
-	this->pTDStretch.reset(TDStretch::newInstance());
-
-	this->setOutPipe(this->pTDStretch.get());
-
-	this->rate = this->tempo = 0;
-
-	this->virtualPitch = this->virtualRate = this->virtualTempo = 1.0;
-
-	this->calcEffectiveRateAndTempo();
-
-	this->channels = 0;
-	this->bSrateSet = false;
-}
-
-// Sets the number of channels, 1 = mono, 2 = stereo
-void SoundTouch::setChannels(uint32_t numChannels)
-{
-	if (numChannels != 1 && numChannels != 2)
-		throw std::runtime_error("Illegal number of channels");
-	this->channels = numChannels;
-	this->pRateTransposer->setChannels(numChannels);
-	this->pTDStretch->setChannels(numChannels);
-}
-
-// Sets new rate control value. Normal rate = 1.0, smaller values
-// represent slower rate, larger faster rates.
-void SoundTouch::setRate(float newRate)
-{
-	this->virtualRate = newRate;
-	this->calcEffectiveRateAndTempo();
-}
-
-// Sets new tempo control value. Normal tempo = 1.0, smaller values
-// represent slower tempo, larger faster tempo.
-void SoundTouch::setTempo(float newTempo)
-{
-	this->virtualTempo = newTempo;
-	this->calcEffectiveRateAndTempo();
-}
-
-// Calculates 'effective' rate and tempo values from the
-// nominal control values.
-void SoundTouch::calcEffectiveRateAndTempo()
-{
-	float oldTempo = this->tempo;
-	float oldRate = this->rate;
-
-	this->tempo = this->virtualTempo / this->virtualPitch;
-	this->rate = this->virtualPitch * this->virtualRate;
-
-	if (!fEqual(this->rate, oldRate))
-		this->pRateTransposer->setRate(this->rate);
-	if (!fEqual(this->tempo, oldTempo))
-		this->pTDStretch->setTempo(this->tempo);
-
-#ifndef SOUNDTOUCH_PREVENT_CLICK_AT_RATE_CROSSOVER
-	if (this->rate <= 1.0f)
-	{
-		if (this->output != this->pTDStretch.get())
-		{
-			FIFOSamplePipe *tempoOut;
-
-			assert(this->output == this->pRateTransposer.get());
-			// move samples in the current output buffer to the output of pTDStretch
-			tempoOut = this->pTDStretch->getOutput();
-			tempoOut->moveSamples(*this->output);
-			// move samples in pitch transposer's store buffer to tempo changer's input
-			this->pTDStretch->moveSamples(*this->pRateTransposer->getStore());
-
-			this->output = pTDStretch.get();
-		}
-	}
-	else
-#endif
-	{
-		if (this->output != this->pRateTransposer.get())
-		{
-			assert(this->output == this->pTDStretch.get());
-			// move samples in the current output buffer to the output of pRateTransposer
-			FIFOSamplePipe *transOut = this->pRateTransposer->getOutput();
-			transOut->moveSamples(*this->output);
-			// move samples in tempo changer's input to pitch transposer's input
-			this->pRateTransposer->moveSamples(*this->pTDStretch->getInput());
-
-			this->output = this->pRateTransposer.get();
-		}
-	}
-}
-
-// Sets sample rate.
-void SoundTouch::setSampleRate(uint32_t srate)
-{
-	this->bSrateSet = true;
-	// set sample rate, leave other tempo changer parameters as they are.
-	this->pTDStretch->setParameters(srate);
-}
-
-// Adds 'numSamples' pcs of samples from the 'samples' memory position into
-// the input of the object.
-void SoundTouch::putSamples(const SAMPLETYPE *samples, uint32_t nSamples)
-{
-	if (!this->bSrateSet)
-		throw std::runtime_error("SoundTouch : Sample rate not defined");
-	else if (!this->channels)
-		throw std::runtime_error("SoundTouch : Number of channels not defined");
-
-	// Transpose the rate of the new samples if necessary
-	/* Bypass the nominal setting - can introduce a click in sound when tempo/pitch control crosses the nominal value...
-	if (this->rate == 1.0f)
-	{
-		// The rate value is same as the original, simply evaluate the tempo changer.
-		assert(this->output == this->pTDStretch.get());
-		if (!this->pRateTransposer->isEmpty())
-		{
-			// yet flush the last samples in the pitch transposer buffer
-			// (may happen if 'rate' changes from a non-zero value to zero)
-			this->pTDStretch->moveSamples(*this->pRateTransposer);
-		}
-		this->pTDStretch->putSamples(samples, nSamples);
-	}*/
-#ifndef SOUNDTOUCH_PREVENT_CLICK_AT_RATE_CROSSOVER
-	else if (this->rate <= 1.0f)
-	{
-		// transpose the rate down, output the transposed sound to tempo changer buffer
-		assert(this->output == this->pTDStretch.get());
-		this->pRateTransposer->putSamples(samples, nSamples);
-		this->pTDStretch->moveSamples(*this->pRateTransposer);
-	}
-	else
-#endif
-	{
-		assert(this->rate > 1.0f);
-		// evaluate the tempo changer, then transpose the rate up,
-		assert(this->output == this->pRateTransposer.get());
-		this->pTDStretch->putSamples(samples, nSamples);
-		this->pRateTransposer->moveSamples(*this->pTDStretch);
-	}
-}
-
-// Flushes the last samples from the processing pipeline to the output.
-// Clears also the internal processing buffers.
-//
-// Note: This function is meant for extracting the last samples of a sound
-// stream. This function may introduce additional blank samples in the end
-// of the sound stream, and thus it's not recommended to call this function
-// in the middle of a sound stream.
-void SoundTouch::flush()
-{
-	// check how many samples still await processing, and scale
-	// that by tempo & rate to get expected output sample count
-	int32_t nUnprocessed = this->numUnprocessedSamples();
-	nUnprocessed = static_cast<int32_t>(nUnprocessed / (tempo * rate) + 0.5);
-
-	int32_t nOut = this->numSamples(); // ready samples currently in buffer ...
-	nOut += nUnprocessed; // ... and how many we expect there to be in the end
-
-	// "Push" the last active samples out from the processing pipeline by
-	// feeding blank samples into the processing pipeline until new,
-	// processed samples appear in the output (not however, more than
-	// 8ksamples in any case)
-	SAMPLETYPE buff[128] = { 0 };
-	for (int i = 0; i < 128; ++i)
-	{
-		this->putSamples(buff, 64);
-		if (static_cast<int32_t>(this->numSamples()) >= nOut)
-		{
-			// Enough new samples have appeared into the output!
-			// As samples come from processing with bigger chunks, now truncate it
-			// back to maximum "nOut" samples to improve duration accuracy
-			this->adjustAmountOfSamples(nOut);
-
-			// finish
-			break;
-		}
-	}
-
-	// Clear working buffers
-	this->pRateTransposer->clear();
-	this->pTDStretch->clearInput();
-	// yet leave the 'tempoChanger' output intouched as that's where the
-	// flushed samples are!
-}
-
-// Changes a setting controlling the processing system behaviour. See the
-// 'SETTING_...' defines for available setting ID's.
-bool SoundTouch::setSetting(int32_t settingId, int32_t value)
-{
-	int32_t sampleRate, sequenceMs, seekWindowMs, overlapMs;
-
-	// read current tdstretch routine parameters
-	pTDStretch->getParameters(&sampleRate, &sequenceMs, &seekWindowMs, &overlapMs);
-
-	switch (settingId)
-	{
-		case SETTING_USE_AA_FILTER:
-			// enables / disabless anti-alias filter
-			this->pRateTransposer->enableAAFilter(!!value);
-			return true;
-
-		case SETTING_AA_FILTER_LENGTH:
-			// sets anti-alias filter length
-			this->pRateTransposer->getAAFilter()->setLength(value);
-			return true;
-
-		case SETTING_USE_QUICKSEEK:
-			// enables / disables tempo routine quick seeking algorithm
-			this->pTDStretch->enableQuickSeek(!!value);
-			return true;
-
-		case SETTING_SEQUENCE_MS:
-			// change time-stretch sequence duration parameter
-			this->pTDStretch->setParameters(sampleRate, value, seekWindowMs, overlapMs);
-			return true;
-
-		case SETTING_SEEKWINDOW_MS:
-			// change time-stretch seek window length parameter
-			this->pTDStretch->setParameters(sampleRate, sequenceMs, value, overlapMs);
-			return true;
-
-		case SETTING_OVERLAP_MS:
-			// change time-stretch overlap length parameter
-			this->pTDStretch->setParameters(sampleRate, sequenceMs, seekWindowMs, value);
-			return true;
-
-		default:
-			return false;
-	}
-}
-
-// Clears all the samples in the object's output and internal processing
-// buffers.
-void SoundTouch::clear()
-{
-	this->pRateTransposer->clear();
-	this->pTDStretch->clear();
-}
-
-/// Returns number of samples currently unprocessed.
-uint32_t SoundTouch::numUnprocessedSamples() const
-{
-	if (this->pTDStretch)
-	{
-		FIFOSamplePipe *psp = this->pTDStretch->getInput();
-		if (psp)
-			return psp->numSamples();
-	}
-	return 0;
-}
-

--- a/src/in_2sf/desmume/metaspu/SoundTouch/SoundTouch.h
+++ /dev/null
@@ -1,239 +1,1 @@
-//////////////////////////////////////////////////////////////////////////////
-///
-/// SoundTouch - main class for tempo/pitch/rate adjusting routines.
-///
-/// Notes:
-/// - Initialize the SoundTouch object instance by setting up the sound stream
-///   parameters with functions 'setSampleRate' and 'setChannels', then set
-///   desired tempo/pitch/rate settings with the corresponding functions.
-///
-/// - The SoundTouch class behaves like a first-in-first-out pipeline: The
-///   samples that are to be processed are fed into one of the pipe by calling
-///   function 'putSamples', while the ready processed samples can be read
-///   from the other end of the pipeline with function 'receiveSamples'.
-///
-/// - The SoundTouch processing classes require certain sized 'batches' of
-///   samples in order to process the sound. For this reason the classes buffer
-///   incoming samples until there are enough of samples available for
-///   processing, then they carry out the processing step and consequently
-///   make the processed samples available for outputting.
-///
-/// - For the above reason, the processing routines introduce a certain
-///   'latency' between the input and output, so that the samples input to
-///   SoundTouch may not be immediately available in the output, and neither
-///   the amount of outputtable samples may not immediately be in direct
-///   relationship with the amount of previously input samples.
-///
-/// - The tempo/pitch/rate control parameters can be altered during processing.
-///   Please notice though that they aren't currently protected by semaphores,
-///   so in multi-thread application external semaphore protection may be
-///   required.
-///
-/// - This class utilizes classes 'TDStretch' for tempo change (without modifying
-///   pitch) and 'RateTransposer' for changing the playback rate (that is, both
-///   tempo and pitch in the same ratio) of the sound. The third available control
-///   'pitch' (change pitch but maintain tempo) is produced by a combination of
-///   combining the two other controls.
-///
-/// Author        : Copyright (c) Olli Parviainen
-/// Author e-mail : oparviai 'at' iki.fi
-/// SoundTouch WWW: http://www.surina.net/soundtouch
-///
-////////////////////////////////////////////////////////////////////////////////
-//
-// Last changed  : $Date: 2012-12-28 17:32:59 -0200 (sex, 28 dez 2012) $
-// File revision : $Revision: 4 $
-//
-// $Id: SoundTouch.h 163 2012-12-28 19:32:59Z oparviai $
-//
-////////////////////////////////////////////////////////////////////////////////
-//
-// License :
-//
-//  SoundTouch audio processing library
-//  Copyright (c) Olli Parviainen
-//
-//  This library is free software; you can redistribute it and/or
-//  modify it under the terms of the GNU Lesser General Public
-//  License as published by the Free Software Foundation; either
-//  version 2.1 of the License, or (at your option) any later version.
-//
-//  This library is distributed in the hope that it will be useful,
-//  but WITHOUT ANY WARRANTY; without even the implied warranty of
-//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-//  Lesser General Public License for more details.
-//
-//  You should have received a copy of the GNU Lesser General Public
-//  License along with this library; if not, write to the Free Software
-//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
-//
-////////////////////////////////////////////////////////////////////////////////
 
-#pragma once
-
-#include <memory>
-#include "FIFOSamplePipe.h"
-#include "RateTransposer.h"
-#include "TDStretch.h"
-
-namespace soundtouch
-{
-
-/// Soundtouch library version string
-const char *const SOUNDTOUCH_VERSION = "1.7.1";
-
-/// SoundTouch library version id
-const uint32_t SOUNDTOUCH_VERSION_ID = 010701;
-
-// Available setting IDs for the 'setSetting' & 'get_setting' functions:
-
-/// Enable/disable anti-alias filter in pitch transposer (0 = disable)
-const int32_t SETTING_USE_AA_FILTER = 0;
-
-/// Pitch transposer anti-alias filter length (8 .. 128 taps, default = 32)
-const int32_t SETTING_AA_FILTER_LENGTH = 1;
-
-/// Enable/disable quick seeking algorithm in tempo changer routine
-/// (enabling quick seeking lowers CPU utilization but causes a minor sound
-///  quality compromising)
-const int32_t SETTING_USE_QUICKSEEK = 2;
-
-/// Time-stretch algorithm single processing sequence length in milliseconds. This determines
-/// to how long sequences the original sound is chopped in the time-stretch algorithm.
-/// See "STTypes.h" or README for more information.
-const int32_t SETTING_SEQUENCE_MS = 3;
-
-/// Time-stretch algorithm seeking window length in milliseconds for algorithm that finds the
-/// best possible overlapping location. This determines from how wide window the algorithm
-/// may look for an optimal joining location when mixing the sound sequences back together.
-/// See "STTypes.h" or README for more information.
-const int32_t SETTING_SEEKWINDOW_MS = 4;
-
-/// Time-stretch algorithm overlap length in milliseconds. When the chopped sound sequences
-/// are mixed back together, to form a continuous sound stream, this parameter defines over
-/// how long period the two consecutive sequences are let to overlap each other.
-/// See "STTypes.h" or README for more information.
-const int32_t SETTING_OVERLAP_MS = 5;
-
-/// Call "getSetting" with this ID to query nominal average processing sequence
-/// size in samples. This value tells approcimate value how many input samples
-/// SoundTouch needs to gather before it does DSP processing run for the sample batch.
-///
-/// Notices:
-/// - This is read-only parameter, i.e. setSetting ignores this parameter
-/// - Returned value is approximate average value, exact processing batch
-///   size may wary from time to time
-/// - This parameter value is not constant but may change depending on
-///   tempo/pitch/rate/samplerate settings.
-const int32_t SETTING_NOMINAL_INPUT_SEQUENCE = 6;
-
-/// Call "getSetting" with this ID to query nominal average processing output
-/// size in samples. This value tells approcimate value how many output samples
-/// SoundTouch outputs once it does DSP processing run for a batch of input samples.
-///
-/// Notices:
-/// - This is read-only parameter, i.e. setSetting ignores this parameter
-/// - Returned value is approximate average value, exact processing batch
-///   size may wary from time to time
-/// - This parameter value is not constant but may change depending on
-///   tempo/pitch/rate/samplerate settings.
-const int32_t SETTING_NOMINAL_OUTPUT_SEQUENCE = 7;
-
-class SoundTouch : public FIFOProcessor
-{
-private:
-	/// Rate transposer class instance
-	std::unique_ptr<RateTransposer> pRateTransposer;
-
-	/// Time-stretch class instance
-	std::unique_ptr<TDStretch> pTDStretch;
-
-	/// Virtual pitch parameter. Effective rate & tempo are calculated from these parameters.
-	float virtualRate;
-
-	/// Virtual pitch parameter. Effective rate & tempo are calculated from these parameters.
-	float virtualTempo;
-
-	/// Virtual pitch parameter. Effective rate & tempo are calculated from these parameters.
-	float virtualPitch;
-
-	/// Flag: Has sample rate been set?
-	bool bSrateSet;
-
-	/// Calculates effective rate & tempo valuescfrom 'virtualRate', 'virtualTempo' and
-	/// 'virtualPitch' parameters.
-	void calcEffectiveRateAndTempo();
-
-protected:
-	/// Number of channels
-	uint32_t channels;
-
-	/// Effective 'rate' value calculated from 'virtualRate', 'virtualTempo' and 'virtualPitch'
-	float rate;
-
-	/// Effective 'tempo' value calculated from 'virtualRate', 'virtualTempo' and 'virtualPitch'
-	float tempo;
-
-public:
-	SoundTouch();
-
-	/// Sets new rate control value. Normal rate = 1.0, smaller values
-	/// represent slower rate, larger faster rates.
-	void setRate(float newRate);
-
-	/// Sets new tempo control value. Normal tempo = 1.0, smaller values
-	/// represent slower tempo, larger faster tempo.
-	void setTempo(float newTempo);
-
-	/// Sets the number of channels, 1 = mono, 2 = stereo
-	void setChannels(uint32_t numChannels);
-
-	/// Sets sample rate.
-	void setSampleRate(uint32_t srate);
-
-	/// Flushes the last samples from the processing pipeline to the output.
-	/// Clears also the internal processing buffers.
-	//
-	/// Note: This function is meant for extracting the last samples of a sound
-	/// stream. This function may introduce additional blank samples in the end
-	/// of the sound stream, and thus it's not recommended to call this function
-	/// in the middle of a sound stream.
-	void flush();
-
-	/// Adds 'numSamples' pcs of samples from the 'samples' memory position into
-	/// the input of the object. Notice that sample rate _has_to_ be set before
-	/// calling this function, otherwise throws a runtime_error exception.
-	void putSamples(
-            const SAMPLETYPE *samples,  ///< Pointer to sample buffer.
-            uint32_t numSamples                         ///< Number of samples in buffer. Notice
-                                                        ///< that in case of stereo-sound a single sample
-                                                        ///< contains data for both channels.
-            );
-
-	/// Clears all the samples in the object's output and internal processing
-	/// buffers.
-	void clear();
-
-	/// Changes a setting controlling the processing system behaviour. See the
-	/// 'SETTING_...' defines for available setting ID's.
-	///
-	/// \return 'true' if the setting was succesfully changed
-	bool setSetting(int32_t settingId,   ///< Setting ID number. see SETTING_... defines.
-                    int32_t value        ///< New setting value.
-                    );
-
-	/// Returns number of samples currently unprocessed.
-	uint32_t numUnprocessedSamples() const;
-
-	/// Other handy functions that are implemented in the ancestor classes (see
-	/// classes 'FIFOProcessor' and 'FIFOSamplePipe')
-	///
-	/// - receiveSamples() : Use this function to receive 'ready' processed samples from SoundTouch.
-	/// - numSamples()     : Get number of 'ready' samples that can be received with
-	///                      function 'receiveSamples()'
-	/// - isEmpty()        : Returns nonzero if there aren't any 'ready' samples.
-	/// - clear()          : Clears all samples from ready/processing buffers.
-};
-
-}
-

--- a/src/in_2sf/desmume/metaspu/SoundTouch/TDStretch.cpp
+++ /dev/null
@@ -1,639 +1,1 @@
-////////////////////////////////////////////////////////////////////////////////
-///
-/// Sampled sound tempo changer/time stretch algorithm. Changes the sound tempo
-/// while maintaining the original pitch by using a time domain WSOLA-like
-/// method with several performance-increasing tweaks.
-///
-/// Note : MMX optimized functions reside in a separate, platform-specific
-/// file, e.g. 'mmx_win.cpp' or 'mmx_gcc.cpp'
-///
-/// Author        : Copyright (c) Olli Parviainen
-/// Author e-mail : oparviai 'at' iki.fi
-/// SoundTouch WWW: http://www.surina.net/soundtouch
-///
-////////////////////////////////////////////////////////////////////////////////
-//
-// Last changed  : $Date: 2012-11-08 16:53:01 -0200 (qui, 08 nov 2012) $
-// File revision : $Revision: 1.12 $
-//
-// $Id: TDStretch.cpp 160 2012-11-08 18:53:01Z oparviai $
-//
-////////////////////////////////////////////////////////////////////////////////
-//
-// License :
-//
-//  SoundTouch audio processing library
-//  Copyright (c) Olli Parviainen
-//
-//  This library is free software; you can redistribute it and/or
-//  modify it under the terms of the GNU Lesser General Public
-//  License as published by the Free Software Foundation; either
-//  version 2.1 of the License, or (at your option) any later version.
-//
-//  This library is distributed in the hope that it will be useful,
-//  but WITHOUT ANY WARRANTY; without even the implied warranty of
-//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-//  Lesser General Public License for more details.
-//
-//  You should have received a copy of the GNU Lesser General Public
-//  License along with this library; if not, write to the Free Software
-//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
-//
-////////////////////////////////////////////////////////////////////////////////
 
-#include "XSFCommon.h"
-
-#include <stdexcept>
-#include <limits>
-#include <cstring>
-#include <cstdlib>
-#include <cassert>
-#include "STTypes.h"
-#include "cpu_detect.h"
-#include "TDStretch.h"
-
-using namespace soundtouch;
-
-/*****************************************************************************
- *
- * Constant definitions
- *
- *****************************************************************************/
-
-// Table for the hierarchical mixing position seeking algorithm
-static const short _scanOffsets[][24] =
-{
-	{ 124, 186, 248, 310, 372, 434, 496, 558, 620, 682, 744, 806, 868, 930, 992, 1054, 1116, 1178, 1240, 1302, 1364, 1426, 1488, 0 },
-	{-100, -75, -50, -25, 25, 50, 75, 100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
-	{ -20, -15, -10,  -5, 5, 10, 15, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
-	{ -4, -3, -2, -1, 1, 2, 3, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
-	{ 121, 114, 97, 114, 98, 105, 108, 32, 104, 99, 117, 111, 116, 100, 110, 117, 111, 115, 0, 0, 0, 0, 0, 0 }
-};
-
-/*****************************************************************************
- *
- * Implementation of the class 'TDStretch'
- *
- *****************************************************************************/
-
-
-TDStretch::TDStretch() : FIFOProcessor(&outputBuffer)
-{
-	this->bQuickSeek = false;
-	this->channels = 2;
-
-	this->pMidBuffer = nullptr;
-	this->pMidBufferUnaligned.reset();
-	this->overlapLength = 0;
-
-	this->bAutoSeqSetting = true;
-	this->bAutoSeekSetting = true;
-
-	//this->outDebt = 0;
-	this->skipFract = 0;
-
-	this->tempo = 1.0f;
-	this->setParameters(48000, DEFAULT_SEQUENCE_MS, DEFAULT_SEEKWINDOW_MS, DEFAULT_OVERLAP_MS);
-	this->setTempo(1.0f);
-
-	this->clear();
-}
-
-TDStretch::~TDStretch()
-{
-}
-
-// Sets routine control parameters. These control are certain time constants
-// defining how the sound is stretched to the desired duration.
-//
-// 'sampleRate' = sample rate of the sound
-// 'sequenceMS' = one processing sequence length in milliseconds (default = 82 ms)
-// 'seekwindowMS' = seeking window length for scanning the best overlapping
-//      position (default = 28 ms)
-// 'overlapMS' = overlapping length (default = 12 ms)
-
-void TDStretch::setParameters(int32_t aSampleRate, int32_t aSequenceMS, int32_t aSeekWindowMS, int32_t aOverlapMS)
-{
-	// accept only positive parameter values - if zero or negative, use old values instead
-	if (aSampleRate > 0)
-		this->sampleRate = aSampleRate;
-	if (aOverlapMS > 0)
-		this->overlapMs = aOverlapMS;
-
-	if (aSequenceMS > 0)
-	{
-		this->sequenceMs = aSequenceMS;
-		this->bAutoSeqSetting = false;
-	}
-	else if (!aSequenceMS)
-		// if zero, use automatic setting
-		this->bAutoSeqSetting = true;
-
-	if (aSeekWindowMS > 0)
-	{
-		this->seekWindowMs = aSeekWindowMS;
-		this->bAutoSeekSetting = false;
-	}
-	else if (!aSeekWindowMS)
-		// if zero, use automatic setting
-		this->bAutoSeekSetting = true;
-
-	this->calcSeqParameters();
-
-	this->calculateOverlapLength(this->overlapMs);
-
-	// set tempo to recalculate 'sampleReq'
-	this->setTempo(this->tempo);
-}
-
-/// Get routine control parameters, see setParameters() function.
-/// Any of the parameters to this function can be NULL, in such case corresponding parameter
-/// value isn't returned.
-void TDStretch::getParameters(int32_t *pSampleRate, int32_t *pSequenceMs, int32_t *pSeekWindowMs, int32_t *pOverlapMs)
-{
-	if (pSampleRate)
-		*pSampleRate = this->sampleRate;
-
-	if (pSequenceMs)
-		*pSequenceMs = this->bAutoSeqSetting ? USE_AUTO_SEQUENCE_LEN : sequenceMs;
-
-	if (pSeekWindowMs)
-		*pSeekWindowMs = this->bAutoSeekSetting ? USE_AUTO_SEEKWINDOW_LEN : seekWindowMs;
-
-	if (pOverlapMs)
-		*pOverlapMs = this->overlapMs;
-}
-
-// Overlaps samples in 'midBuffer' with the samples in 'pInput'
-void TDStretch::overlapMono(SAMPLETYPE *pOutput, const SAMPLETYPE *pInput) const
-{
-	SAMPLETYPE m1 = 0;
-	SAMPLETYPE m2 = static_cast<SAMPLETYPE>(this->overlapLength);
-
-	for (int32_t i = 0; i < this->overlapLength; ++i)
-	{
-		pOutput[i] = (pInput[i] * m1 + this->pMidBuffer[i] * m2) / this->overlapLength;
-		++m1;
-		--m2;
-	}
-}
-
-void TDStretch::clearMidBuffer()
-{
-	memset(this->pMidBuffer, 0, 2 * sizeof(SAMPLETYPE) * this->overlapLength);
-}
-
-void TDStretch::clearInput()
-{
-	this->inputBuffer.clear();
-	this->clearMidBuffer();
-}
-
-// Clears the sample buffers
-void TDStretch::clear()
-{
-	this->outputBuffer.clear();
-	this->clearInput();
-}
-
-// Enables/disables the quick position seeking algorithm. Zero to disable, nonzero
-// to enable
-void TDStretch::enableQuickSeek(bool enable)
-{
-	this->bQuickSeek = enable;
-}
-
-// Seeks for the optimal overlap-mixing position.
-int32_t TDStretch::seekBestOverlapPosition(const SAMPLETYPE *refPos)
-{
-	if (this->bQuickSeek)
-		return this->seekBestOverlapPositionQuick(refPos);
-	else
-		return this->seekBestOverlapPositionFull(refPos);
-}
-
-// Overlaps samples in 'midBuffer' with the samples in 'pInputBuffer' at position
-// of 'ovlPos'.
-void TDStretch::overlap(SAMPLETYPE *pOutput, const SAMPLETYPE *pInput, uint32_t ovlPos) const
-{
-	if (this->channels == 2)
-		// stereo sound
-		this->overlapStereo(pOutput, pInput + 2 * ovlPos);
-	else
-		// mono sound.
-		this->overlapMono(pOutput, pInput + ovlPos);
-}
-
-// Seeks for the optimal overlap-mixing position. The 'stereo' version of the
-// routine
-//
-// The best position is determined as the position where the two overlapped
-// sample sequences are 'most alike', in terms of the highest cross-correlation
-// value over the overlapping period
-int32_t TDStretch::seekBestOverlapPositionFull(const SAMPLETYPE *refPos)
-{
-	double bestCorr = std::numeric_limits<float>::min();
-	int32_t bestOffs = 0;
-
-	// Scans for the best correlation value by testing each possible position
-	// over the permitted range.
-	for (int32_t i = 0; i < this->seekLength; ++i)
-	{
-		// Calculates correlation value for the mixing position corresponding
-		// to 'i'
-		double corr = this->calcCrossCorr(refPos + this->channels * i, this->pMidBuffer);
-		// heuristic rule to slightly favour values close to mid of the range
-		double tmp = (2.0 * i - this->seekLength) / this->seekLength;
-		corr = (corr + 0.1) * (1.0 - 0.25 * tmp * tmp);
-
-		// Checks for the highest correlation value
-		if (corr > bestCorr)
-		{
-			bestCorr = corr;
-			bestOffs = i;
-		}
-	}
-	// clear cross correlation routine state if necessary (is so e.g. in MMX routines).
-	this->clearCrossCorrState();
-
-	return bestOffs;
-}
-
-// Seeks for the optimal overlap-mixing position. The 'stereo' version of the
-// routine
-//
-// The best position is determined as the position where the two overlapped
-// sample sequences are 'most alike', in terms of the highest cross-correlation
-// value over the overlapping period
-int32_t TDStretch::seekBestOverlapPositionQuick(const SAMPLETYPE *refPos)
-{
-	double bestCorr = std::numeric_limits<float>::min();
-	int32_t bestOffs = _scanOffsets[0][0], corrOffset = 0;
-
-	// Scans for the best correlation value using four-pass hierarchical search.
-	//
-	// The look-up table 'scans' has hierarchical position adjusting steps.
-	// In first pass the routine searhes for the highest correlation with
-	// relatively coarse steps, then rescans the neighbourhood of the highest
-	// correlation with better resolution and so on.
-	for (uint32_t scanCount = 0; scanCount < 4; ++scanCount)
-	{
-		int32_t j = 0;
-		while (_scanOffsets[scanCount][j])
-		{
-			int32_t tempOffset = corrOffset + _scanOffsets[scanCount][j];
-			if (tempOffset >= this->seekLength)
-				break;
-
-			// Calculates correlation value for the mixing position corresponding
-			// to 'tempOffset'
-			double corr = this->calcCrossCorr(refPos + this->channels * tempOffset, this->pMidBuffer);
-			// heuristic rule to slightly favour values close to mid of the range
-			double tmp = (2.0 * tempOffset - this->seekLength) / seekLength;
-			corr = (corr + 0.1) * (1.0 - 0.25 * tmp * tmp);
-
-			// Checks for the highest correlation value
-			if (corr > bestCorr)
-			{
-				bestCorr = corr;
-				bestOffs = tempOffset;
-			}
-			++j;
-		}
-		corrOffset = bestOffs;
-	}
-	// clear cross correlation routine state if necessary (is so e.g. in MMX routines).
-	this->clearCrossCorrState();
-
-	return bestOffs;
-}
-
-/// clear cross correlation routine state if necessary
-void TDStretch::clearCrossCorrState()
-{
-	// default implementation is empty.
-}
-
-/// Calculates processing sequence length according to tempo setting
-void TDStretch::calcSeqParameters()
-{
-	// Adjust tempo param according to tempo, so that variating processing sequence length is used
-	// at varius tempo settings, between the given low...top limits
-	static const double AUTOSEQ_TEMPO_LOW = 0.5; // auto setting low tempo range (-50%)
-	static const double AUTOSEQ_TEMPO_TOP = 2.0; // auto setting top tempo range (+100%)
-
-	// sequence-ms setting values at above low & top tempo
-	static const double AUTOSEQ_AT_MIN = 125.0;
-	static const double AUTOSEQ_AT_MAX = 50.0;
-	static const double AUTOSEQ_K = (AUTOSEQ_AT_MAX - AUTOSEQ_AT_MIN) / (AUTOSEQ_TEMPO_TOP - AUTOSEQ_TEMPO_LOW);
-	static const double AUTOSEQ_C = AUTOSEQ_AT_MIN - AUTOSEQ_K * AUTOSEQ_TEMPO_LOW;
-
-	// seek-window-ms setting values at above low & top tempo
-	static const double AUTOSEEK_AT_MIN = 25.0;
-	static const double AUTOSEEK_AT_MAX = 15.0;
-	static const double AUTOSEEK_K = (AUTOSEEK_AT_MAX - AUTOSEEK_AT_MIN) / (AUTOSEQ_TEMPO_TOP - AUTOSEQ_TEMPO_LOW);
-	static const double AUTOSEEK_C = AUTOSEEK_AT_MIN - AUTOSEEK_K * AUTOSEQ_TEMPO_LOW;
-
-	auto CHECK_LIMITS = [](double x, double mi, double ma) { return x < mi ? mi : (x > ma ? ma : x); };
-
-	if (this->bAutoSeqSetting)
-	{
-		double seq = AUTOSEQ_C + AUTOSEQ_K * this->tempo;
-		seq = CHECK_LIMITS(seq, AUTOSEQ_AT_MAX, AUTOSEQ_AT_MIN);
-		this->sequenceMs = static_cast<int>(seq + 0.5);
-	}
-
-	if (this->bAutoSeekSetting)
-	{
-		double seek = AUTOSEEK_C + AUTOSEEK_K * this->tempo;
-		seek = CHECK_LIMITS(seek, AUTOSEEK_AT_MAX, AUTOSEEK_AT_MIN);
-		this->seekWindowMs = static_cast<int>(seek + 0.5);
-    }
-
-	// Update seek window lengths
-	this->seekWindowLength = (this->sampleRate * this->sequenceMs) / 1000;
-	if (this->seekWindowLength < 2 * this->overlapLength)
-		this->seekWindowLength = 2 * this->overlapLength;
-	this->seekLength = (this->sampleRate * this->seekWindowMs) / 1000;
-}
-
-// Sets new target tempo. Normal tempo = 'SCALE', smaller values represent slower
-// tempo, larger faster tempo.
-void TDStretch::setTempo(float newTempo)
-{
-	this->tempo = newTempo;
-
-	// Calculate new sequence duration
-	this->calcSeqParameters();
-
-	// Calculate ideal skip length (according to tempo value)
-	this->nominalSkip = this->tempo * (this->seekWindowLength - this->overlapLength);
-	int intskip = static_cast<int>(nominalSkip + 0.5f);
-
-	// Calculate how many samples are needed in the 'inputBuffer' to
-	// process another batch of samples
-	this->sampleReq = std::max(intskip + this->overlapLength, this->seekWindowLength) + this->seekLength;
-}
-
-// Sets the number of channels, 1 = mono, 2 = stereo
-void TDStretch::setChannels(int32_t numChannels)
-{
-	assert(numChannels > 0);
-	if (this->channels == numChannels)
-		return;
-	assert(numChannels == 1 || numChannels == 2);
-
-	this->channels = numChannels;
-	this->inputBuffer.setChannels(channels);
-	this->outputBuffer.setChannels(channels);
-}
-
-// Processes as many processing frames of the samples 'inputBuffer', store
-// the result into 'outputBuffer'
-void TDStretch::processSamples()
-{
-	/* Removed this small optimization - can introduce a click to sound when tempo setting
-	   crosses the nominal value
-	if (this->tempo == 1.0f)
-	{
-		// tempo not changed from the original, so bypass the processing
-		this->processNominalTempo();
-		return;
-	}*/
-
-	// Process samples as long as there are enough samples in 'inputBuffer'
-	// to form a processing frame.
-	while (static_cast<int32_t>(this->inputBuffer.numSamples()) >= this->sampleReq)
-	{
-		// If tempo differs from the normal ('SCALE'), scan for the best overlapping
-		// position
-		int32_t offset = this->seekBestOverlapPosition(this->inputBuffer.ptrBegin());
-
-		// Mix the samples in the 'inputBuffer' at position of 'offset' with the
-		// samples in 'midBuffer' using sliding overlapping
-		// ... first partially overlap with the end of the previous sequence
-		// (that's in 'midBuffer')
-		this->overlap(this->outputBuffer.ptrEnd(this->overlapLength), this->inputBuffer.ptrBegin(), offset);
-		this->outputBuffer.putSamples(this->overlapLength);
-
-		// ... then copy sequence samples from 'inputBuffer' to output:
-
-		// length of sequence
-		int temp = this->seekWindowLength - 2 * this->overlapLength;
-
-		// crosscheck that we don't have buffer overflow...
-		if (static_cast<int32_t>(inputBuffer.numSamples()) < offset + temp + this->overlapLength * 2)
-			continue; // just in case, shouldn't really happen
-
-		this->outputBuffer.putSamples(this->inputBuffer.ptrBegin() + this->channels * (offset + this->overlapLength), temp);
-
-		// Copies the end of the current sequence from 'inputBuffer' to
-		// 'midBuffer' for being mixed with the beginning of the next
-		// processing sequence and so on
-		assert(offset + temp + this->overlapLength * 2 <= static_cast<int32_t>(this->inputBuffer.numSamples()));
-		memcpy(this->pMidBuffer, this->inputBuffer.ptrBegin() + this->channels * (offset + this->seekWindowLength - this->overlapLength), this->channels * sizeof(SAMPLETYPE) * this->overlapLength);
-
-		// Remove the processed samples from the input buffer. Update
-		// the difference between integer & nominal skip step to 'skipFract'
-		// in order to prevent the error from accumulating over time.
-		this->skipFract += this->nominalSkip; // real skip size
-		int ovlSkip = static_cast<int>(skipFract); // rounded to integer skip
-		this->skipFract -= ovlSkip; // maintain the fraction part, i.e. real vs. integer skip
-		this->inputBuffer.receiveSamples(ovlSkip);
-	}
-}
-
-// Adds 'numsamples' pcs of samples from the 'samples' memory position into
-// the input of the object.
-void TDStretch::putSamples(const SAMPLETYPE *samples, uint32_t nSamples)
-{
-	// Add the samples into the input buffer
-	this->inputBuffer.putSamples(samples, nSamples);
-	// Process the samples in input buffer
-	this->processSamples();
-}
-
-/// Set new overlap length parameter & reallocate RefMidBuffer if necessary.
-void TDStretch::acceptNewOverlapLength(int32_t newOverlapLength)
-{
-	assert(newOverlapLength >= 0);
-	int32_t prevOvl = this->overlapLength;
-	this->overlapLength = newOverlapLength;
-
-	if (this->overlapLength > prevOvl)
-	{
-		this->pMidBufferUnaligned.reset(new SAMPLETYPE[this->overlapLength * 2 + 16 / sizeof(SAMPLETYPE)]);
-		// ensure that 'pMidBuffer' is aligned to 16 byte boundary for efficiency
-		this->pMidBuffer = reinterpret_cast<SAMPLETYPE *>(SOUNDTOUCH_ALIGN_POINTER_16(this->pMidBufferUnaligned.get()));
-
-		this->clearMidBuffer();
-	}
-}
-
-// Operator 'new' is overloaded so that it automatically creates a suitable instance
-// depending on if we've a MMX/SSE/etc-capable CPU available or not.
-void *TDStretch::operator new(size_t /*s*/)
-{
-	// Notice! don't use "new TDStretch" directly, use "newInstance" to create a new instance instead!
-	//assert(false);
-	//return NULL;
-	throw std::runtime_error("Don't use 'new TDStretch', use 'newInstance' member instead!");
-}
-
-TDStretch *TDStretch::newInstance()
-{
-	uint32_t uExtensions = detectCPUextensions();
-
-	// Check if MMX/SSE instruction set extensions supported by CPU
-
-#ifdef SOUNDTOUCH_ALLOW_MMX
-	// MMX routines available only with integer sample types
-	if (uExtensions & SUPPORT_MMX)
-		return ::new TDStretchMMX;
-	else
-#endif // SOUNDTOUCH_ALLOW_MMX
-#ifdef SOUNDTOUCH_ALLOW_SSE
-	if (uExtensions & SUPPORT_SSE)
-		// SSE support
-		return ::new TDStretchSSE;
-	else
-#endif //  SOUNDTOUCH_ALLOW_SSE
-		// ISA optimizations not supported, use plain C version
-		return ::new TDStretch;
-}
-
-//////////////////////////////////////////////////////////////////////////////
-//
-// Integer arithmetics specific algorithm implementations.
-//
-//////////////////////////////////////////////////////////////////////////////
-
-#ifdef SOUNDTOUCH_INTEGER_SAMPLES
-
-// Overlaps samples in 'midBuffer' with the samples in 'pinput'. The 'Stereo'
-// version of the routine.
-void TDStretch::overlapStereo(short *poutput, const short *pinput) const
-{
-	for (int32_t i = 0; i < this->overlapLength; ++i)
-	{
-		short temp = this->overlapLength - i;
-		int32_t cnt2 = 2 * i;
-		poutput[cnt2] = (pinput[cnt2] * i + this->pMidBuffer[cnt2] * temp) / this->overlapLength;
-		poutput[cnt2 + 1] = (pinput[cnt2 + 1] * i + this->pMidBuffer[cnt2 + 1] * temp) / this->overlapLength;
-	}
-}
-
-// Calculates the x having the closest 2^x value for the given value
-static int _getClosest2Power(double value)
-{
-	return static_cast<int>(std::log(value) / std::log(2.0) + 0.5);
-}
-
-/// Calculates overlap period length in samples.
-/// Integer version rounds overlap length to closest power of 2
-/// for a divide scaling operation.
-void TDStretch::calculateOverlapLength(int32_t aoverlapMs)
-{
-	assert(aoverlapMs >= 0);
-
-	// calculate overlap length so that it's power of 2 - thus it's easy to do
-	// integer division by right-shifting. Term "-1" at end is to account for
-	// the extra most significatnt bit left unused in result by signed multiplication
-	this->overlapDividerBits = _getClosest2Power((this->sampleRate * aoverlapMs) / 1000.0) - 1;
-	if (this->overlapDividerBits > 9)
-		this->overlapDividerBits = 9;
-	if (this->overlapDividerBits < 3)
-		this->overlapDividerBits = 3;
-	int32_t newOvl = static_cast<int32_t>(std::pow(2, this->overlapDividerBits + 1)); // +1 => account for -1 above
-
-	this->acceptNewOverlapLength(newOvl);
-
-	// calculate sloping divider so that crosscorrelation operation won't
-	// overflow 32-bit register. Max. sum of the crosscorrelation sum without
-	// divider would be 2^30*(N^3-N)/3, where N = overlap length
-	this->slopingDivider = (newOvl * newOvl - 1) / 3;
-}
-
-double TDStretch::calcCrossCorr(const short *mixingPos, const short *compare) const
-{
-	long corr = 0, norm = 0;
-	// Same routine for stereo and mono. For stereo, unroll loop for better
-	// efficiency and gives slightly better resolution against rounding.
-	// For mono it same routine, just  unrolls loop by factor of 4
-	for (int32_t i = 0; i < this->overlapLength; i += 4)
-	{
-		corr += (mixingPos[i] * compare[i] + mixingPos[i + 1] * compare[i + 1] + mixingPos[i + 2] * compare[i + 2] + mixingPos[i + 3] * compare[i + 3]) >> this->overlapDividerBits;
-		norm += (mixingPos[i] * mixingPos[i] + mixingPos[i + 1] * mixingPos[i + 1] + mixingPos[i + 2] * mixingPos[i + 2] + mixingPos[i + 3] * mixingPos[i + 3]) >> this->overlapDividerBits;
-	}
-
-	// Normalize result by dividing by sqrt(norm) - this step is easiest
-	// done using floating point operation
-	if (!norm)
-		norm = 1; // to avoid div by zero
-	return corr / std::sqrt(static_cast<double>(norm));
-}
-
-#endif // SOUNDTOUCH_INTEGER_SAMPLES
-
-//////////////////////////////////////////////////////////////////////////////
-//
-// Floating point arithmetics specific algorithm implementations.
-//
-
-#ifdef SOUNDTOUCH_FLOAT_SAMPLES
-
-// Overlaps samples in 'midBuffer' with the samples in 'pInput'
-void TDStretch::overlapStereo(float *pOutput, const float *pInput) const
-{
-	float fScale = 1.0f / this->overlapLength;
-
-	float f1 = 0, f2 = 1.0f;
-
-	for (int32_t i = 0; i < 2 * this->overlapLength; i += 2)
-	{
-		pOutput[i] = pInput[i] * f1 + this->pMidBuffer[i] * f2;
-		pOutput[i + 1] = pInput[i + 1] * f1 + this->pMidBuffer[i + 1] * f2;
-
-		f1 += fScale;
-		f2 -= fScale;
-	}
-}
-
-/// Calculates overlapInMsec period length in samples.
-void TDStretch::calculateOverlapLength(int32_t overlapInMsec)
-{
-	assert(overlapInMsec >= 0);
-	uint32_t newOvl = (this->sampleRate * overlapInMsec) / 1000;
-	if (newOvl < 16)
-		newOvl = 16;
-
-	// must be divisible by 8
-	newOvl -= newOvl % 8;
-
-	this->acceptNewOverlapLength(newOvl);
-}
-
-double TDStretch::calcCrossCorr(const float *mixingPos, const float *compare) const
-{
-	double corr = 0, norm = 0;
-	// Same routine for stereo and mono. For Stereo, unroll by factor of 2.
-	// For mono it's same routine yet unrollsd by factor of 4.
-	for (int32_t i = 0; i < this->channels * this->overlapLength; i += 4)
-	{
-		corr += mixingPos[i] * compare[i] + mixingPos[i + 1] * compare[i + 1];
-
-		norm += mixingPos[i] * mixingPos[i] +  mixingPos[i + 1] * mixingPos[i + 1];
-
-		// unroll the loop for better CPU efficiency:
-		corr += mixingPos[i + 2] * compare[i + 2] + mixingPos[i + 3] * compare[i + 3];
-
-		norm += mixingPos[i + 2] * mixingPos[i + 2] + mixingPos[i + 3] * mixingPos[i + 3];
-	}
-
-	if (norm < 1e-9)
-		norm = 1.0; // to avoid div by zero
-	return corr / std::sqrt(norm);
-}
-
-#endif // SOUNDTOUCH_FLOAT_SAMPLES
-

--- a/src/in_2sf/desmume/metaspu/SoundTouch/TDStretch.h
+++ /dev/null
@@ -1,245 +1,1 @@
-////////////////////////////////////////////////////////////////////////////////
-///
-/// Sampled sound tempo changer/time stretch algorithm. Changes the sound tempo
-/// while maintaining the original pitch by using a time domain WSOLA-like method
-/// with several performance-increasing tweaks.
-///
-/// Note : MMX/SSE optimized functions reside in separate, platform-specific files
-/// 'mmx_optimized.cpp' and 'sse_optimized.cpp'
-///
-/// Author        : Copyright (c) Olli Parviainen
-/// Author e-mail : oparviai 'at' iki.fi
-/// SoundTouch WWW: http://www.surina.net/soundtouch
-///
-////////////////////////////////////////////////////////////////////////////////
-//
-// Last changed  : $Date: 2012-04-01 16:49:30 -0300 (dom, 01 abr 2012) $
-// File revision : $Revision: 4 $
-//
-// $Id: TDStretch.h 137 2012-04-01 19:49:30Z oparviai $
-//
-////////////////////////////////////////////////////////////////////////////////
-//
-// License :
-//
-//  SoundTouch audio processing library
-//  Copyright (c) Olli Parviainen
-//
-//  This library is free software; you can redistribute it and/or
-//  modify it under the terms of the GNU Lesser General Public
-//  License as published by the Free Software Foundation; either
-//  version 2.1 of the License, or (at your option) any later version.
-//
-//  This library is distributed in the hope that it will be useful,
-//  but WITHOUT ANY WARRANTY; without even the implied warranty of
-//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-//  Lesser General Public License for more details.
-//
-//  You should have received a copy of the GNU Lesser General Public
-//  License along with this library; if not, write to the Free Software
-//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
-//
-////////////////////////////////////////////////////////////////////////////////
 
-#pragma once
-
-#include <memory>
-#include "FIFOSampleBuffer.h"
-
-namespace soundtouch
-{
-
-/// Default values for sound processing parameters:
-/// Notice that the default parameters are tuned for contemporary popular music
-/// processing. For speech processing applications these parameters suit better:
-///     #define DEFAULT_SEQUENCE_MS     40
-///     #define DEFAULT_SEEKWINDOW_MS   15
-///     #define DEFAULT_OVERLAP_MS      8
-///
-
-/// Giving this value for the sequence length sets automatic parameter value
-/// according to tempo setting (recommended)
-const int32_t USE_AUTO_SEQUENCE_LEN = 0;
-
-/// Default length of a single processing sequence, in milliseconds. This determines to how
-/// long sequences the original sound is chopped in the time-stretch algorithm.
-///
-/// The larger this value is, the lesser sequences are used in processing. In principle
-/// a bigger value sounds better when slowing down tempo, but worse when increasing tempo
-/// and vice versa.
-///
-/// Increasing this value reduces computational burden & vice versa.
-//#define DEFAULT_SEQUENCE_MS 40
-const int32_t DEFAULT_SEQUENCE_MS = USE_AUTO_SEQUENCE_LEN;
-
-/// Giving this value for the seek window length sets automatic parameter value
-/// according to tempo setting (recommended)
-const int32_t USE_AUTO_SEEKWINDOW_LEN = 0;
-
-/// Seeking window default length in milliseconds for algorithm that finds the best possible
-/// overlapping location. This determines from how wide window the algorithm may look for an
-/// optimal joining location when mixing the sound sequences back together.
-///
-/// The bigger this window setting is, the higher the possibility to find a better mixing
-/// position will become, but at the same time large values may cause a "drifting" artifact
-/// because consequent sequences will be taken at more uneven intervals.
-///
-/// If there's a disturbing artifact that sounds as if a constant frequency was drifting
-/// around, try reducing this setting.
-///
-/// Increasing this value increases computational burden & vice versa.
-//#define DEFAULT_SEEKWINDOW_MS       15
-const int32_t DEFAULT_SEEKWINDOW_MS = USE_AUTO_SEEKWINDOW_LEN;
-
-/// Overlap length in milliseconds. When the chopped sound sequences are mixed back together,
-/// to form a continuous sound stream, this parameter defines over how long period the two
-/// consecutive sequences are let to overlap each other.
-///
-/// This shouldn't be that critical parameter. If you reduce the DEFAULT_SEQUENCE_MS setting
-/// by a large amount, you might wish to try a smaller value on this.
-///
-/// Increasing this value increases computational burden & vice versa.
-const int32_t DEFAULT_OVERLAP_MS = 8;
-
-/// Class that does the time-stretch (tempo change) effect for the processed
-/// sound.
-class TDStretch : public FIFOProcessor
-{
-protected:
-	int32_t channels;
-	int32_t sampleReq;
-	float tempo;
-
-	SAMPLETYPE *pMidBuffer;
-	std::unique_ptr<SAMPLETYPE[]> pMidBufferUnaligned;
-	int32_t overlapLength;
-	int32_t seekLength;
-	int32_t seekWindowLength;
-	int32_t overlapDividerBits;
-	int32_t slopingDivider;
-	float nominalSkip;
-	float skipFract;
-	FIFOSampleBuffer outputBuffer;
-	FIFOSampleBuffer inputBuffer;
-	bool bQuickSeek;
-
-	int32_t sampleRate;
-	int32_t sequenceMs;
-	int32_t seekWindowMs;
-	int32_t overlapMs;
-	bool bAutoSeqSetting;
-	bool bAutoSeekSetting;
-
-	void acceptNewOverlapLength(int32_t newOverlapLength);
-
-	virtual void clearCrossCorrState();
-	void calculateOverlapLength(int32_t overlapMs);
-
-	virtual double calcCrossCorr(const SAMPLETYPE *mixingPos, const SAMPLETYPE *compare) const;
-
-	virtual int seekBestOverlapPositionFull(const SAMPLETYPE *refPos);
-	virtual int seekBestOverlapPositionQuick(const SAMPLETYPE *refPos);
-	int32_t seekBestOverlapPosition(const SAMPLETYPE *refPos);
-
-	virtual void overlapStereo(SAMPLETYPE *output, const SAMPLETYPE *input) const;
-	virtual void overlapMono(SAMPLETYPE *output, const SAMPLETYPE *input) const;
-
-	void clearMidBuffer();
-	void overlap(SAMPLETYPE *output, const SAMPLETYPE *input, uint32_t ovlPos) const;
-
-	void calcSeqParameters();
-
-	/// Changes the tempo of the given sound samples.
-	/// Returns amount of samples returned in the "output" buffer.
-	/// The maximum amount of samples that can be returned at a time is set by
-	/// the 'set_returnBuffer_size' function.
-	void processSamples();
-
-public:
-	TDStretch();
-	virtual ~TDStretch();
-
-	/// Operator 'new' is overloaded so that it automatically creates a suitable instance
-	/// depending on if we've a MMX/SSE/etc-capable CPU available or not.
-	static void *operator new(size_t s);
-
-	/// Use this function instead of "new" operator to create a new instance of this class.
-	/// This function automatically chooses a correct feature set depending on if the CPU
-	/// supports MMX/SSE/etc extensions.
-	static TDStretch *newInstance();
-
-	/// Returns the output buffer object
-	FIFOSamplePipe *getOutput() { return &this->outputBuffer; }
-
-	/// Returns the input buffer object
-	FIFOSamplePipe *getInput() { return &this->inputBuffer; }
-
-	/// Sets new target tempo. Normal tempo = 'SCALE', smaller values represent slower
-	/// tempo, larger faster tempo.
-	void setTempo(float newTempo);
-
-	/// Returns nonzero if there aren't any samples available for outputting.
-	virtual void clear();
-
-	/// Clears the input buffer
-	void clearInput();
-
-	/// Sets the number of channels, 1 = mono, 2 = stereo
-	void setChannels(int32_t numChannels);
-
-	/// Enables/disables the quick position seeking algorithm. Zero to disable,
-	/// nonzero to enable
-	void enableQuickSeek(bool enable);
-
-	/// Sets routine control parameters. These control are certain time constants
-	/// defining how the sound is stretched to the desired duration.
-	//
-	/// 'sampleRate' = sample rate of the sound
-	/// 'sequenceMS' = one processing sequence length in milliseconds
-	/// 'seekwindowMS' = seeking window length for scanning the best overlapping
-	///      position
-	/// 'overlapMS' = overlapping length
-	void setParameters(int32_t sampleRate,          ///< Samplerate of sound being processed (Hz)
-                       int32_t sequenceMS = -1,     ///< Single processing sequence length (ms)
-                       int32_t seekwindowMS = -1,   ///< Offset seeking window length (ms)
-                       int32_t overlapMS = -1       ///< Sequence overlapping length (ms)
-                       );
-
-	/// Get routine control parameters, see setParameters() function.
-	/// Any of the parameters to this function can be NULL, in such case corresponding parameter
-	/// value isn't returned.
-	void getParameters(int32_t *pSampleRate, int32_t *pSequenceMs, int32_t *pSeekWindowMs, int32_t *pOverlapMs);
-
-	/// Adds 'numsamples' pcs of samples from the 'samples' memory position into
-	/// the input of the object.
-	virtual void putSamples(
-            const SAMPLETYPE *samples,  ///< Input sample data
-            uint32_t numSamples                         ///< Number of samples in 'samples' so that one sample
-                                                       ///< contains both channels if stereo
-            );
-};
-
-// Implementation-specific class declarations:
-
-#ifdef SOUNDTOUCH_ALLOW_MMX
-/// Class that implements MMX optimized routines for 16bit integer samples type.
-class TDStretchMMX : public TDStretch
-{
-protected:
-	double calcCrossCorr(const short *mixingPos, const short *compare) const;
-	virtual void overlapStereo(short *output, const short *input) const;
-	virtual void clearCrossCorrState();
-};
-#endif /// SOUNDTOUCH_ALLOW_MMX
-
-#ifdef SOUNDTOUCH_ALLOW_SSE
-/// Class that implements SSE optimized routines for floating point samples type.
-class TDStretchSSE : public TDStretch
-{
-protected:
-	double calcCrossCorr(const float *mixingPos, const float *compare) const;
-};
-#endif ///  SOUNDTOUCH_ALLOW_SSE
-
-}
-

--- a/src/in_2sf/desmume/metaspu/SoundTouch/cpu_detect.h
+++ /dev/null
@@ -1,58 +1,1 @@
-////////////////////////////////////////////////////////////////////////////////
-///
-/// A header file for detecting the Intel MMX instructions set extension.
-///
-/// Please see 'mmx_win.cpp', 'mmx_cpp.cpp' and 'mmx_non_x86.cpp' for the
-/// routine implementations for x86 Windows, x86 gnu version and non-x86
-/// platforms, respectively.
-///
-/// Author        : Copyright (c) Olli Parviainen
-/// Author e-mail : oparviai 'at' iki.fi
-/// SoundTouch WWW: http://www.surina.net/soundtouch
-///
-////////////////////////////////////////////////////////////////////////////////
-//
-// Last changed  : $Date: 2006/02/05 16:44:06 $
-// File revision : $Revision: 1.4 $
-//
-// $Id: cpu_detect.h,v 1.4 2006/02/05 16:44:06 Olli Exp $
-//
-////////////////////////////////////////////////////////////////////////////////
-//
-// License :
-//
-//  SoundTouch audio processing library
-//  Copyright (c) Olli Parviainen
-//
-//  This library is free software; you can redistribute it and/or
-//  modify it under the terms of the GNU Lesser General Public
-//  License as published by the Free Software Foundation; either
-//  version 2.1 of the License, or (at your option) any later version.
-//
-//  This library is distributed in the hope that it will be useful,
-//  but WITHOUT ANY WARRANTY; without even the implied warranty of
-//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-//  Lesser General Public License for more details.
-//
-//  You should have received a copy of the GNU Lesser General Public
-//  License along with this library; if not, write to the Free Software
-//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
-//
-////////////////////////////////////////////////////////////////////////////////
 
-#pragma once
-
-#include "STTypes.h"
-
-const uint32_t SUPPORT_MMX = 0x0001;
-const uint32_t SUPPORT_3DNOW = 0x0002;
-const uint32_t SUPPORT_SSE = 0x0004;
-
-/// Checks which instruction set extensions are supported by the CPU.
-///
-/// \return A bitmask of supported extensions, see SUPPORT_... defines.
-uint32_t detectCPUextensions();
-
-/// Disables given set of instruction extensions. See SUPPORT_... defines.
-void disableExtensions(uint32_t wDisableMask);
-

--- a/src/in_2sf/desmume/metaspu/SoundTouch/cpu_detect_x86_gcc.cpp
+++ /dev/null
@@ -1,139 +1,1 @@
-////////////////////////////////////////////////////////////////////////////////
-///
-/// gcc version of the x86 CPU detect routine.
-///
-/// This file is to be compiled on any platform with the GNU C compiler.
-/// Compiler. Please see 'cpu_detect_x86_win.cpp' for the x86 Windows version
-/// of this file.
-///
-/// Author        : Copyright (c) Olli Parviainen
-/// Author e-mail : oparviai 'at' iki.fi
-/// SoundTouch WWW: http://www.surina.net/soundtouch
-///
-////////////////////////////////////////////////////////////////////////////////
-//
-// Last changed  : $Date: 2006/02/05 16:44:06 $
-// File revision : $Revision: 1.6 $
-//
-// $Id: cpu_detect_x86_gcc.cpp,v 1.6 2006/02/05 16:44:06 Olli Exp $
-//
-////////////////////////////////////////////////////////////////////////////////
-//
-// License :
-//
-//  SoundTouch audio processing library
-//  Copyright (c) Olli Parviainen
-//
-//  This library is free software; you can redistribute it and/or
-//  modify it under the terms of the GNU Lesser General Public
-//  License as published by the Free Software Foundation; either
-//  version 2.1 of the License, or (at your option) any later version.
-//
-//  This library is distributed in the hope that it will be useful,
-//  but WITHOUT ANY WARRANTY; without even the implied warranty of
-//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-//  Lesser General Public License for more details.
-//
-//  You should have received a copy of the GNU Lesser General Public
-//  License along with this library; if not, write to the Free Software
-//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
-//
-////////////////////////////////////////////////////////////////////////////////
 
-#include <stdexcept>
-#include <string>
-#include "cpu_detect.h"
-
-#ifndef __GNUC__
-#error wrong platform - this source code file is for the GNU C compiler.
-#endif
-
-using namespace std;
-
-#include <stdio.h>
-//////////////////////////////////////////////////////////////////////////////
-//
-// processor instructions extension detection routines
-//
-//////////////////////////////////////////////////////////////////////////////
-
-
-// Flag variable indicating whick ISA extensions are disabled (for debugging)
-static uint32_t _dwDisabledISA = 0x00;      // 0xffffffff; //<- use this to disable all extensions
-
-// Disables given set of instruction extensions. See SUPPORT_... defines.
-void disableExtensions(uint32_t dwDisableMask)
-{
-    _dwDisabledISA = dwDisableMask;
-}
-
-
-
-/// Checks which instruction set extensions are supported by the CPU.
-uint32_t detectCPUextensions(void)
-{
-#ifndef __i386__
-    return 0; // always disable extensions on non-x86 platforms.
-#else
-    uint32_t res = 0;
-
-    if (_dwDisabledISA == 0xffffffff) return 0;
-
-    asm volatile(
-        "\n\txor     %%esi, %%esi"       // clear %%esi = result register
-        // check if 'cpuid' instructions is available by toggling eflags bit 21
-
-        "\n\tpushf"                      // save eflags to stack
-        "\n\tpop     %%eax"              // load eax from stack (with eflags)
-        "\n\tmovl    %%eax, %%ecx"       // save the original eflags values to ecx
-        "\n\txor     $0x00200000, %%eax" // toggle bit 21
-        "\n\tpush    %%eax"              // store toggled eflags to stack
-        "\n\tpopf"                       // load eflags from stack
-        "\n\tpushf"                      // save updated eflags to stack
-        "\n\tpop     %%eax"              // load from stack
-        "\n\txor     %%edx, %%edx"       // clear edx for defaulting no mmx
-        "\n\tcmp     %%ecx, %%eax"       // compare to original eflags values
-        "\n\tjz      end"                // jumps to 'end' if cpuid not present
-
-        // cpuid instruction available, test for presence of mmx instructions
-
-        "\n\tmovl    $1, %%eax"
-        "\n\tcpuid"
-//        movl       $0x00800000, %edx   // force enable MMX
-        "\n\ttest    $0x00800000, %%edx"
-        "\n\tjz      end"                // branch if MMX not available
-
-        "\n\tor      $0x01, %%esi"       // otherwise add MMX support bit
-
-        "\n\ttest    $0x02000000, %%edx"
-        "\n\tjz      test3DNow"          // branch if SSE not available
-
-        "\n\tor      $0x08, %%esi"       // otherwise add SSE support bit
-
-    "\n\ttest3DNow:"
-        // test for precense of AMD extensions
-        "\n\tmov     $0x80000000, %%eax"
-        "\n\tcpuid"
-        "\n\tcmp     $0x80000000, %%eax"
-        "\n\tjbe     end"                 // branch if no AMD extensions detected
-
-        // test for precense of 3DNow! extension
-        "\n\tmov     $0x80000001, %%eax"
-        "\n\tcpuid"
-        "\n\ttest    $0x80000000, %%edx"
-        "\n\tjz      end"                  // branch if 3DNow! not detected
-
-        "\n\tor      $0x02, %%esi"         // otherwise add 3DNow support bit
-
-    "\n\tend:"
-
-        "\n\tmov     %%esi, %0"
-
-      : "=r" (res)
-      : /* no inputs */
-      : "%edx", "%eax", "%ecx", "%esi" );
-
-    return res & ~_dwDisabledISA;
-#endif
-}
-

--- a/src/in_2sf/desmume/metaspu/SoundTouch/cpu_detect_x86_win.cpp
+++ /dev/null
@@ -1,92 +1,1 @@
-////////////////////////////////////////////////////////////////////////////////
-///
-/// Win32 version of the x86 CPU detect routine.
-///
-/// This file is to be compiled in Windows platform with Microsoft Visual C++
-/// Compiler. Please see 'cpu_detect_x86_gcc.cpp' for the gcc compiler version
-/// for all GNU platforms.
-///
-/// Author        : Copyright (c) Olli Parviainen
-/// Author e-mail : oparviai 'at' iki.fi
-/// SoundTouch WWW: http://www.surina.net/soundtouch
-///
-////////////////////////////////////////////////////////////////////////////////
-//
-// Last changed  : $Date: 2006/02/05 16:44:06 $
-// File revision : $Revision: 1.10 $
-//
-// $Id: cpu_detect_x86_win.cpp,v 1.10 2006/02/05 16:44:06 Olli Exp $
-//
-////////////////////////////////////////////////////////////////////////////////
-//
-// License :
-//
-//  SoundTouch audio processing library
-//  Copyright (c) Olli Parviainen
-//
-//  This library is free software; you can redistribute it and/or
-//  modify it under the terms of the GNU Lesser General Public
-//  License as published by the Free Software Foundation; either
-//  version 2.1 of the License, or (at your option) any later version.
-//
-//  This library is distributed in the hope that it will be useful,
-//  but WITHOUT ANY WARRANTY; without even the implied warranty of
-//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-//  Lesser General Public License for more details.
-//
-//  You should have received a copy of the GNU Lesser General Public
-//  License along with this library; if not, write to the Free Software
-//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
-//
-////////////////////////////////////////////////////////////////////////////////
 
-#include "cpu_detect.h"
-#ifdef _MSC_VER
-#include <intrin.h>
-#endif
-
-#ifndef _WIN32
-#error wrong platform - this source code file is exclusively for Win32 platform
-#endif
-
-//////////////////////////////////////////////////////////////////////////////
-//
-// processor instructions extension detection routines
-//
-//////////////////////////////////////////////////////////////////////////////
-
-// Flag variable indicating whick ISA extensions are disabled (for debugging)
-static uint32_t _dwDisabledISA = 0x00; // 0xffffffff; //<- use this to disable all extensions
-
-// Disables given set of instruction extensions. See SUPPORT_... defines.
-void disableExtensions(uint32_t dwDisableMask)
-{
-	_dwDisabledISA = dwDisableMask;
-}
-
-/// Checks which instruction set extensions are supported by the CPU.
-uint32_t detectCPUextensions()
-{
-	uint32_t res = 0;
-
-	if (_dwDisabledISA == 0xffffffff)
-		return 0;
-
-#ifdef _MSC_VER
-	int CPUInfo[4] = { -1 };
-	__cpuid(CPUInfo, 1);
-	res |= (CPUInfo[3] & (1 << 23)) ? SUPPORT_MMX : 0;
-	res |= (CPUInfo[3] & (1 << 25)) ? SUPPORT_SSE : 0;
-
-	// Test 3Dnow
-	__cpuid(CPUInfo, 0x80000000);
-	if (CPUInfo[0] == 0x80000000)
-	{
-		__cpuid(CPUInfo, 0x80000001);
-		res |= (CPUInfo[3] & (1 << 31)) ? SUPPORT_3DNOW : 0;
-	}
-#endif
-
-	return res & ~_dwDisabledISA;
-}
-

--- a/src/in_2sf/desmume/metaspu/SoundTouch/mmx_optimized.cpp
+++ /dev/null
@@ -1,282 +1,1 @@
-////////////////////////////////////////////////////////////////////////////////
-///
-/// MMX optimized routines. All MMX optimized functions have been gathered into
-/// this single source code file, regardless to their class or original source
-/// code file, in order to ease porting the library to other compiler and
-/// processor platforms.
-///
-/// The MMX-optimizations are programmed using MMX compiler intrinsics that
-/// are supported both by Microsoft Visual C++ and GCC compilers, so this file
-/// should compile with both toolsets.
-///
-/// NOTICE: If using Visual Studio 6.0, you'll need to install the "Visual C++
-/// 6.0 processor pack" update to support compiler intrinsic syntax. The update
-/// is available for download at Microsoft Developers Network, see here:
-/// http://msdn.microsoft.com/en-us/vstudio/aa718349.aspx
-///
-/// Author        : Copyright (c) Olli Parviainen
-/// Author e-mail : oparviai 'at' iki.fi
-/// SoundTouch WWW: http://www.surina.net/soundtouch
-///
-////////////////////////////////////////////////////////////////////////////////
-//
-// Last changed  : $Date: 2012-11-08 16:53:01 -0200 (qui, 08 nov 2012) $
-// File revision : $Revision: 4 $
-//
-// $Id: mmx_optimized.cpp 160 2012-11-08 18:53:01Z oparviai $
-//
-////////////////////////////////////////////////////////////////////////////////
-//
-// License :
-//
-//  SoundTouch audio processing library
-//  Copyright (c) Olli Parviainen
-//
-//  This library is free software; you can redistribute it and/or
-//  modify it under the terms of the GNU Lesser General Public
-//  License as published by the Free Software Foundation; either
-//  version 2.1 of the License, or (at your option) any later version.
-//
-//  This library is distributed in the hope that it will be useful,
-//  but WITHOUT ANY WARRANTY; without even the implied warranty of
-//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-//  Lesser General Public License for more details.
-//
-//  You should have received a copy of the GNU Lesser General Public
-//  License along with this library; if not, write to the Free Software
-//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
-//
-////////////////////////////////////////////////////////////////////////////////
 
-#include "STTypes.h"
-
-#ifdef SOUNDTOUCH_ALLOW_MMX
-// MMX routines available only with integer sample type
-
-using namespace soundtouch;
-
-//////////////////////////////////////////////////////////////////////////////
-//
-// implementation of MMX optimized functions of class 'TDStretchMMX'
-//
-//////////////////////////////////////////////////////////////////////////////
-
-#include "TDStretch.h"
-#include <mmintrin.h>
-
-// Calculates cross correlation of two buffers
-double TDStretchMMX::calcCrossCorr(const short *pV1, const short *pV2) const
-{
-	const __m64 *pVec1 = reinterpret_cast<__m64 *>(pV1);
-	const __m64 *pVec2 = reinterpret_cast<__m64 *>(pV2);
-
-	__m64 shifter = _m_from_int(this->overlapDividerBits);
-	__m64 normaccu, accu;
-	normaccu = accu = _mm_setzero_si64();
-
-	// Process 4 parallel sets of 2 * stereo samples or 4 * mono samples
-	// during each round for improved CPU-level parallellization.
-	for (int32_t i = 0; i < this->channels * this->overlapLength / 16; ++i)
-	{
-		// dictionary of instructions:
-		// _m_pmaddwd   : 4*16bit multiply-add, resulting two 32bits = [a0*b0+a1*b1 ; a2*b2+a3*b3]
-		// _mm_add_pi32 : 2*32bit add
-		// _m_psrad     : 32bit right-shift
-
-		__m64 temp = _mm_add_pi32(_mm_madd_pi16(pVec1[0], pVec2[0]), _mm_madd_pi16(pVec1[1], pVec2[1]));
-		__m64 temp2 = _mm_add_pi32(_mm_madd_pi16(pVec1[0], pVec1[0]), _mm_madd_pi16(pVec1[1], pVec1[1]));
-		accu = _mm_add_pi32(accu, _mm_sra_pi32(temp, shifter));
-		normaccu = _mm_add_pi32(normaccu, _mm_sra_pi32(temp2, shifter));
-
-		temp = _mm_add_pi32(_mm_madd_pi16(pVec1[2], pVec2[2]), _mm_madd_pi16(pVec1[3], pVec2[3]));
-		temp2 = _mm_add_pi32(_mm_madd_pi16(pVec1[2], pVec1[2]), _mm_madd_pi16(pVec1[3], pVec1[3]));
-		accu = _mm_add_pi32(accu, _mm_sra_pi32(temp, shifter));
-		normaccu = _mm_add_pi32(normaccu, _mm_sra_pi32(temp2, shifter));
-
-		pVec1 += 4;
-		pVec2 += 4;
-	}
-
-	// copy hi-dword of mm0 to lo-dword of mm1, then sum mmo+mm1
-	// and finally store the result into the variable "corr"
-
-	accu = _mm_add_pi32(accu, _mm_srli_si64(accu, 32));
-	long corr = _m_to_int(accu);
-
-	normaccu = _mm_add_pi32(normaccu, _mm_srli_si64(normaccu, 32));
-	long norm = _m_to_int(normaccu);
-
-	// Clear MMS state
-	_m_empty();
-
-	// Normalize result by dividing by sqrt(norm) - this step is easiest
-	// done using floating point operation
-	if (!norm)
-		norm = 1; // to avoid div by zero
-
-	return corr / std::sqrt(static_cast<double>(norm));
-	// Note: Warning about the missing EMMS instruction is harmless
-	// as it'll be called elsewhere.
-}
-
-void TDStretchMMX::clearCrossCorrState()
-{
-	// Clear MMS state
-	_m_empty();
-	//_asm EMMS;
-}
-
-// MMX-optimized version of the function overlapStereo
-void TDStretchMMX::overlapStereo(short *output, const short *input) const
-{
-	const __m64 *pVinput = reinterpret_cast<const __m64 *>(input);
-	const __m64 *pVMidBuf = reinterpret_cast<const __m64 *>(this->pMidBuffer);
-	__m64 *pVdest = reinterpret_cast<__m64 *>(output);
-
-	// mix1  = mixer values for 1st stereo sample
-	// mix1  = mixer values for 2nd stereo sample
-	// adder = adder for updating mixer values after each round
-
-	__m64 mix1 = _mm_set_pi16(0, this->overlapLength, 0, this->overlapLength);
-	__m64 adder = _mm_set_pi16(1, -1, 1, -1);
-	__m64 mix2 = _mm_add_pi16(mix1, adder);
-	adder = _mm_add_pi16(adder, adder);
-
-	// Overlaplength-division by shifter. "+1" is to account for "-1" deduced in
-	// overlapDividerBits calculation earlier.
-	__m64 shifter = _m_from_int(overlapDividerBits + 1);
-
-	for (int32_t i = 0; i < this->overlapLength / 4; ++i)
-	{
-		// load & shuffle data so that input & mixbuffer data samples are paired
-		__m64 temp1 = _mm_unpacklo_pi16(pVMidBuf[0], pVinput[0]); // = i0l m0l i0r m0r
-		__m64 temp2 = _mm_unpackhi_pi16(pVMidBuf[0], pVinput[0]); // = i1l m1l i1r m1r
-
-		// temp = (temp .* mix) >> shifter
-		temp1 = _mm_sra_pi32(_mm_madd_pi16(temp1, mix1), shifter);
-		temp2 = _mm_sra_pi32(_mm_madd_pi16(temp2, mix2), shifter);
-		pVdest[0] = _mm_packs_pi32(temp1, temp2); // pack 2*2*32bit => 4*16bit
-
-		// update mix += adder
-		mix1 = _mm_add_pi16(mix1, adder);
-		mix2 = _mm_add_pi16(mix2, adder);
-
-		// --- second round begins here ---
-
-		// load & shuffle data so that input & mixbuffer data samples are paired
-		temp1 = _mm_unpacklo_pi16(pVMidBuf[1], pVinput[1]); // = i2l m2l i2r m2r
-		temp2 = _mm_unpackhi_pi16(pVMidBuf[1], pVinput[1]); // = i3l m3l i3r m3r
-
-		// temp = (temp .* mix) >> shifter
-		temp1 = _mm_sra_pi32(_mm_madd_pi16(temp1, mix1), shifter);
-		temp2 = _mm_sra_pi32(_mm_madd_pi16(temp2, mix2), shifter);
-		pVdest[1] = _mm_packs_pi32(temp1, temp2); // pack 2*2*32bit => 4*16bit
-
-		// update mix += adder
-		mix1 = _mm_add_pi16(mix1, adder);
-		mix2 = _mm_add_pi16(mix2, adder);
-
-		pVinput += 2;
-		pVMidBuf += 2;
-		pVdest += 2;
-	}
-
-	_m_empty(); // clear MMS state
-}
-
-//////////////////////////////////////////////////////////////////////////////
-//
-// implementation of MMX optimized functions of class 'FIRFilter'
-//
-//////////////////////////////////////////////////////////////////////////////
-
-#include "FIRFilter.h"
-
-FIRFilterMMX::FIRFilterMMX() : FIRFilter()
-{
-	this->filterCoeffsUnalign.reset();
-}
-
-FIRFilterMMX::~FIRFilterMMX()
-{
-}
-
-// (overloaded) Calculates filter coefficients for MMX routine
-void FIRFilterMMX::setCoefficients(const short *coeffs, uint32_t newLength, uint32_t uResultDivFactor)
-{
-	FIRFilter::setCoefficients(coeffs, newLength, uResultDivFactor);
-
-	// Ensure that filter coeffs array is aligned to 16-byte boundary
-	this->filterCoeffsUnalign.reset(new short[2 * newLength + 8]);
-	this->filterCoeffsAlign = reinterpret_csat<short *>(SOUNDTOUCH_ALIGN_POINTER_16(this->filterCoeffsUnalign.get()));
-
-	// rearrange the filter coefficients for mmx routines
-	for (uint32_t i = 0; i < length; i += 4)
-	{
-		this->filterCoeffsAlign[2 * i ] = coeffs[i];
-		this->filterCoeffsAlign[2 * i + 1] = coeffs[i + 2];
-		this->filterCoeffsAlign[2 * i + 2] = coeffs[i];
-		this->filterCoeffsAlign[2 * i + 3] = coeffs[i + 2];
-
-		this->filterCoeffsAlign[2 * i + 4] = coeffs[i + 1];
-		this->filterCoeffsAlign[2 * i + 5] = coeffs[i + 3];
-		this->filterCoeffsAlign[2 * i + 6] = coeffs[i + 1];
-		this->filterCoeffsAlign[2 * i + 7] = coeffs[i + 3];
-	}
-}
-
-// mmx-optimized version of the filter routine for stereo sound
-uint32_t FIRFilterMMX::evaluateFilterStereo(short *dest, const short *src, uint32_t numSamples) const
-{
-	if (this->length < 2)
-		return 0;
-
-	// Create stack copies of the needed member variables for asm routines :
-	__m64 *pVdest = reinterpret_cast<__m64 *>(dest);
-
-	for (uint32_t i = 0; i < (numSamples - this->length) / 2; ++i)
-	{
-		const __m64 *pVsrc = reinterpret_cast<const __m64 *>(src);
-		const __m64 *pVfilter = reinterpret_cast<const __m64 *>(this->filterCoeffsAlign);
-
-		__m64 accu1, accu2;
-		accu1 = accu2 = _mm_setzero_si64();
-		for (uint32_t j = 0; j < this->lengthDiv8 * 2; ++j)
-		{
-			__m64 temp1 = _mm_unpacklo_pi16(pVsrc[0], pVsrc[1]); // = l2 l0 r2 r0
-			__m64 temp2 = _mm_unpackhi_pi16(pVsrc[0], pVsrc[1]); // = l3 l1 r3 r1
-
-			accu1 = _mm_add_pi32(accu1, _mm_madd_pi16(temp1, pVfilter[0])); // += l2*f2+l0*f0 r2*f2+r0*f0
-			accu1 = _mm_add_pi32(accu1, _mm_madd_pi16(temp2, pVfilter[1])); // += l3*f3+l1*f1 r3*f3+r1*f1
-
-			temp1 = _mm_unpacklo_pi16(pVsrc[1], pVsrc[2]); // = l4 l2 r4 r2
-
-			accu2 = _mm_add_pi32(accu2, _mm_madd_pi16(temp2, pVfilter[0])); // += l3*f2+l1*f0 r3*f2+r1*f0
-			accu2 = _mm_add_pi32(accu2, _mm_madd_pi16(temp1, pVfilter[1])); // += l4*f3+l2*f1 r4*f3+r2*f1
-
-			// accu1 += l2*f2+l0*f0 r2*f2+r0*f0
-			//       += l3*f3+l1*f1 r3*f3+r1*f1
-
-			// accu2 += l3*f2+l1*f0 r3*f2+r1*f0
-			//          l4*f3+l2*f1 r4*f3+r2*f1
-
-			pVfilter += 2;
-			pVsrc += 2;
-		}
-		// accu >>= resultDivFactor
-		accu1 = _mm_srai_pi32(accu1, resultDivFactor);
-		accu2 = _mm_srai_pi32(accu2, resultDivFactor);
-
-		// pack 2*2*32bits => 4*16 bits
-		pVdest[0] = _mm_packs_pi32(accu1, accu2);
-		src += 4;
-		++pVdest;
-	}
-
-	_m_empty(); // clear emms state
-
-	return (numSamples & 0xfffffffe) - this->length;
-}
-
-#endif // SOUNDTOUCH_ALLOW_MMX
-

--- a/src/in_2sf/desmume/metaspu/SoundTouch/sse_optimized.cpp
+++ /dev/null
@@ -1,336 +1,1 @@
-////////////////////////////////////////////////////////////////////////////////
-///
-/// SSE optimized routines for Pentium-III, Athlon-XP and later CPUs. All SSE
-/// optimized functions have been gathered into this single source
-/// code file, regardless to their class or original source code file, in order
-/// to ease porting the library to other compiler and processor platforms.
-///
-/// The SSE-optimizations are programmed using SSE compiler intrinsics that
-/// are supported both by Microsoft Visual C++ and GCC compilers, so this file
-/// should compile with both toolsets.
-///
-/// NOTICE: If using Visual Studio 6.0, you'll need to install the "Visual C++
-/// 6.0 processor pack" update to support SSE instruction set. The update is
-/// available for download at Microsoft Developers Network, see here:
-/// http://msdn.microsoft.com/en-us/vstudio/aa718349.aspx
-///
-/// If the above URL is expired or removed, go to "http://msdn.microsoft.com" and
-/// perform a search with keywords "processor pack".
-///
-/// Author        : Copyright (c) Olli Parviainen
-/// Author e-mail : oparviai 'at' iki.fi
-/// SoundTouch WWW: http://www.surina.net/soundtouch
-///
-////////////////////////////////////////////////////////////////////////////////
-//
-// Last changed  : $Date: 2012-11-08 16:53:01 -0200 (qui, 08 nov 2012) $
-// File revision : $Revision: 4 $
-//
-// $Id: sse_optimized.cpp 160 2012-11-08 18:53:01Z oparviai $
-//
-////////////////////////////////////////////////////////////////////////////////
-//
-// License :
-//
-//  SoundTouch audio processing library
-//  Copyright (c) Olli Parviainen
-//
-//  This library is free software; you can redistribute it and/or
-//  modify it under the terms of the GNU Lesser General Public
-//  License as published by the Free Software Foundation; either
-//  version 2.1 of the License, or (at your option) any later version.
-//
-//  This library is distributed in the hope that it will be useful,
-//  but WITHOUT ANY WARRANTY; without even the implied warranty of
-//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-//  Lesser General Public License for more details.
-//
-//  You should have received a copy of the GNU Lesser General Public
-//  License along with this library; if not, write to the Free Software
-//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
-//
-////////////////////////////////////////////////////////////////////////////////
 
-#include <cmath>
-#include "cpu_detect.h"
-#include "STTypes.h"
-
-using namespace soundtouch;
-
-#ifdef SOUNDTOUCH_ALLOW_SSE
-
-// SSE routines available only with float sample type
-
-//////////////////////////////////////////////////////////////////////////////
-//
-// implementation of SSE optimized functions of class 'TDStretchSSE'
-//
-//////////////////////////////////////////////////////////////////////////////
-
-#include "TDStretch.h"
-#include <xmmintrin.h>
-
-// Calculates cross correlation of two buffers
-double TDStretchSSE::calcCrossCorr(const float *pV1, const float *pV2) const
-{
-	// Note. It means a major slow-down if the routine needs to tolerate
-	// unaligned __m128 memory accesses. It's way faster if we can skip
-	// unaligned slots and use _mm_load_ps instruction instead of _mm_loadu_ps.
-	// This can mean up to ~ 10-fold difference (incl. part of which is
-	// due to skipping every second round for stereo sound though).
-	//
-	// Compile-time define SOUNDTOUCH_ALLOW_NONEXACT_SIMD_OPTIMIZATION is provided
-	// for choosing if this little cheating is allowed.
-
-#ifdef SOUNDTOUCH_ALLOW_NONEXACT_SIMD_OPTIMIZATION
-	// Little cheating allowed, return valid correlation only for
-	// aligned locations, meaning every second round for stereo sound.
-
-	#define _MM_LOAD _mm_load_ps
-
-	if (reinterpret_cast<uintptr_t>(pV1) & 15)
-		return -1e50; // skip unaligned locations
-#else
-	// No cheating allowed, use unaligned load & take the resulting
-	// performance hit.
-	#define _MM_LOAD _mm_loadu_ps
-#endif
-
-	// ensure overlapLength is divisible by 8
-	assert(!(overlapLength % 8));
-
-	// Calculates the cross-correlation value between 'pV1' and 'pV2' vectors
-	// Note: pV2 _must_ be aligned to 16-bit boundary, pV1 need not.
-	const float *pVec1 = pV1;
-	const __m128 *pVec2 = reinterpret_cast<const __m128 *>(pV2);
-	__m128 vSum, vNorm;
-	vSum = vNorm = _mm_setzero_ps();
-
-	// Unroll the loop by factor of 4 * 4 operations. Use same routine for
-	// stereo & mono, for mono it just means twice the amount of unrolling.
-	for (int32_t i = 0; i < this->channels * this->overlapLength / 16; ++i)
-	{
-		// vSum += pV1[0..3] * pV2[0..3]
-		__m128 vTemp = _MM_LOAD(pVec1);
-		vSum = _mm_add_ps(vSum, _mm_mul_ps(vTemp, pVec2[0]));
-		vNorm = _mm_add_ps(vNorm, _mm_mul_ps(vTemp, vTemp));
-
-		// vSum += pV1[4..7] * pV2[4..7]
-		vTemp = _MM_LOAD(pVec1 + 4);
-		vSum = _mm_add_ps(vSum, _mm_mul_ps(vTemp, pVec2[1]));
-		vNorm = _mm_add_ps(vNorm, _mm_mul_ps(vTemp, vTemp));
-
-		// vSum += pV1[8..11] * pV2[8..11]
-		vTemp = _MM_LOAD(pVec1 + 8);
-		vSum = _mm_add_ps(vSum, _mm_mul_ps(vTemp, pVec2[2]));
-		vNorm = _mm_add_ps(vNorm, _mm_mul_ps(vTemp, vTemp));
-
-		// vSum += pV1[12..15] * pV2[12..15]
-		vTemp = _MM_LOAD(pVec1 + 12);
-		vSum = _mm_add_ps(vSum, _mm_mul_ps(vTemp, pVec2[3]));
-		vNorm = _mm_add_ps(vNorm, _mm_mul_ps(vTemp, vTemp));
-
-		pVec1 += 16;
-		pVec2 += 4;
-	}
-
-	// return value = vSum[0] + vSum[1] + vSum[2] + vSum[3]
-	float *pvNorm = reinterpret_cast<float *>(&vNorm);
-	double norm = std::sqrt(pvNorm[0] + pvNorm[1] + pvNorm[2] + pvNorm[3]);
-	if (norm < 1e-9)
-		norm = 1.0; // to avoid div by zero
-
-	float *pvSum = reinterpret_cast<float *>(&vSum);
-	return (pvSum[0] + pvSum[1] + pvSum[2] + pvSum[3]) / norm;
-
-	/* This is approximately corresponding routine in C-language:
-	double corr, norm;
-	uint32_t i;
-
-	// Calculates the cross-correlation value between 'pV1' and 'pV2' vectors
-	corr = norm = 0.0;
-	for (i = 0; i < channels * overlapLength / 16; i ++)
-	{
-		corr += pV1[0] * pV2[0] +
-				pV1[1] * pV2[1] +
-				pV1[2] * pV2[2] +
-				pV1[3] * pV2[3] +
-				pV1[4] * pV2[4] +
-				pV1[5] * pV2[5] +
-				pV1[6] * pV2[6] +
-				pV1[7] * pV2[7] +
-				pV1[8] * pV2[8] +
-				pV1[9] * pV2[9] +
-				pV1[10] * pV2[10] +
-				pV1[11] * pV2[11] +
-				pV1[12] * pV2[12] +
-				pV1[13] * pV2[13] +
-				pV1[14] * pV2[14] +
-				pV1[15] * pV2[15];
-
-		for (j = 0; j < 15; j ++) norm += pV1[j] * pV1[j];
-
-		pV1 += 16;
-		pV2 += 16;
-	}
-	return corr / sqrt(norm);*/
-}
-
-//////////////////////////////////////////////////////////////////////////////
-//
-// implementation of SSE optimized functions of class 'FIRFilter'
-//
-//////////////////////////////////////////////////////////////////////////////
-
-#include "FIRFilter.h"
-
-FIRFilterSSE::FIRFilterSSE() : FIRFilter()
-{
-	this->filterCoeffsAlign = nullptr;
-	this->filterCoeffsUnalign.reset();
-}
-
-FIRFilterSSE::~FIRFilterSSE()
-{
-}
-
-// (overloaded) Calculates filter coefficients for SSE routine
-void FIRFilterSSE::setCoefficients(const float *coeffs, uint32_t newLength, uint32_t uResultDivFactor)
-{
-	FIRFilter::setCoefficients(coeffs, newLength, uResultDivFactor);
-
-	// Scale the filter coefficients so that it won't be necessary to scale the filtering result
-	// also rearrange coefficients suitably for SSE
-	// Ensure that filter coeffs array is aligned to 16-byte boundary
-	this->filterCoeffsUnalign.reset(new float[2 * newLength + 4]);
-	this->filterCoeffsAlign = reinterpret_cast<float *>(SOUNDTOUCH_ALIGN_POINTER_16(this->filterCoeffsUnalign.get()));
-
-	float fDivider = static_cast<float>(this->resultDivider);
-
-	// rearrange the filter coefficients for mmx routines
-	for (uint32_t i = 0; i < newLength; ++i)
-		this->filterCoeffsAlign[2 * i] = this->filterCoeffsAlign[2 * i + 1] = coeffs[i] / fDivider;
-}
-
-// SSE-optimized version of the filter routine for stereo sound
-uint32_t FIRFilterSSE::evaluateFilterStereo(float *dest, const float *source, uint32_t numSamples) const
-{
-	int count = static_cast<int>((numSamples - length) & static_cast<uint32_t>(-2));
-
-	assert(!(count % 2));
-
-	if (count < 2)
-		return 0;
-
-	assert(!!source);
-	assert(!!dest);
-	assert(!(length % 8));
-	assert(!!filterCoeffsAlign);
-	assert(!(reinterpret_cast<uintptr_t>(filterCoeffsAlign) % 16));
-
-	// filter is evaluated for two stereo samples with each iteration, thus use of 'j += 2'
-	for (int j = 0; j < count; j += 2)
-	{
-		const float *pSrc = source; // source audio data
-		const __m128 *pFil = reinterpret_cast<const __m128 *>(this->filterCoeffsAlign); // filter coefficients. NOTE: Assumes coefficients are aligned to 16-byte boundary
-		__m128 sum1, sum2;
-		sum1 = sum2 = _mm_setzero_ps();
-
-		for (uint32_t i = 0; i < length / 8; ++i)
-		{
-			// Unroll loop for efficiency & calculate filter for 2*2 stereo samples
-			// at each pass
-
-			// sum1 is accu for 2*2 filtered stereo sound data at the primary sound data offset
-			// sum2 is accu for 2*2 filtered stereo sound data for the next sound sample offset.
-
-			sum1 = _mm_add_ps(sum1, _mm_mul_ps(_mm_loadu_ps(pSrc), pFil[0]));
-			sum2 = _mm_add_ps(sum2, _mm_mul_ps(_mm_loadu_ps(pSrc + 2), pFil[0]));
-
-			sum1 = _mm_add_ps(sum1, _mm_mul_ps(_mm_loadu_ps(pSrc + 4), pFil[1]));
-			sum2 = _mm_add_ps(sum2, _mm_mul_ps(_mm_loadu_ps(pSrc + 6), pFil[1]));
-
-			sum1 = _mm_add_ps(sum1, _mm_mul_ps(_mm_loadu_ps(pSrc + 8) ,  pFil[2]));
-			sum2 = _mm_add_ps(sum2, _mm_mul_ps(_mm_loadu_ps(pSrc + 10), pFil[2]));
-
-			sum1 = _mm_add_ps(sum1, _mm_mul_ps(_mm_loadu_ps(pSrc + 12), pFil[3]));
-			sum2 = _mm_add_ps(sum2, _mm_mul_ps(_mm_loadu_ps(pSrc + 14), pFil[3]));
-
-			pSrc += 16;
-			pFil += 4;
-		}
-
-		// Now sum1 and sum2 both have a filtered 2-channel sample each, but we still need
-		// to sum the two hi- and lo-floats of these registers together.
-
-		// post-shuffle & add the filtered values and store to dest.
-		_mm_storeu_ps(dest, _mm_add_ps(
-			_mm_shuffle_ps(sum1, sum2, _MM_SHUFFLE(1,0,3,2)),   // s2_1 s2_0 s1_3 s1_2
-			_mm_shuffle_ps(sum1, sum2, _MM_SHUFFLE(3,2,1,0))    // s2_3 s2_2 s1_1 s1_0
-		));
-		source += 4;
-		dest += 4;
-	}
-
-	// Ideas for further improvement:
-	// 1. If it could be guaranteed that 'source' were always aligned to 16-byte
-	//    boundary, a faster aligned '_mm_load_ps' instruction could be used.
-	// 2. If it could be guaranteed that 'dest' were always aligned to 16-byte
-	//    boundary, a faster '_mm_store_ps' instruction could be used.
-
-	return count;
-
-	/* original routine in C-language. please notice the C-version has differently
-	   organized coefficients though.
-	double suml1, suml2;
-	double sumr1, sumr2;
-	uint32_t i, j;
-
-	for (j = 0; j < count; j += 2)
-	{
-		const float *ptr;
-		const float *pFil;
-
-		suml1 = sumr1 = 0.0;
-		suml2 = sumr2 = 0.0;
-		ptr = src;
-		pFil = filterCoeffs;
-		for (i = 0; i < lengthLocal; i ++)
-		{
-			// unroll loop for efficiency.
-
-			suml1 += ptr[0] * pFil[0] +
-						ptr[2] * pFil[2] +
-						ptr[4] * pFil[4] +
-						ptr[6] * pFil[6];
-
-			sumr1 += ptr[1] * pFil[1] +
-						ptr[3] * pFil[3] +
-						ptr[5] * pFil[5] +
-						ptr[7] * pFil[7];
-
-			suml2 += ptr[8] * pFil[0] +
-						ptr[10] * pFil[2] +
-						ptr[12] * pFil[4] +
-						ptr[14] * pFil[6];
-
-			sumr2 += ptr[9] * pFil[1] +
-						ptr[11] * pFil[3] +
-						ptr[13] * pFil[5] +
-						ptr[15] * pFil[7];
-
-			ptr += 16;
-			pFil += 8;
-		}
-		dest[0] = (float)suml1;
-		dest[1] = (float)sumr1;
-		dest[2] = (float)suml2;
-		dest[3] = (float)sumr2;
-
-		src += 4;
-		dest += 4;
-	}*/
-}
-
-#endif  // SOUNDTOUCH_ALLOW_SSE
-

--- a/src/in_2sf/desmume/metaspu/Timestretcher.cpp
+++ /dev/null
@@ -1,316 +1,1 @@
-/* SPU2-X, A plugin for Emulating the Sound Processing Unit of the Playstation 2
-* Developed and maintained by the Pcsx2 Development Team.
-*
-* Original portions from SPU2ghz are (c) 2008 by David Quintana [gigaherz]
-*
-* SPU2-X is free software: you can redistribute it and/or modify it under the terms
-* of the GNU Lesser General Public License as published by the Free Software Found-
-* ation, either version 3 of the License, or (at your option) any later version.
-*
-* SPU2-X is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
-* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
-* PURPOSE.  See the GNU Lesser General Public License for more details.
-*
-* You should have received a copy of the GNU Lesser General Public License
-* along with SPU2-X.  If not, see <http://www.gnu.org/licenses/>.
-*/
 
-#include "XSFCommon.h"
-
-#include "../types.h"
-#include "SoundTouch/SoundTouch.h"
-#include "SndOut.h"
-
-static std::unique_ptr<soundtouch::SoundTouch> pSoundTouch;
-static int ts_stats_stretchblocks = 0;
-static int ts_stats_normalblocks = 0;
-static int ts_stats_logcounter = 0;
-
-// data prediction amount, used to "commit" data that hasn't
-// finished timestretch processing.
-int32_t SndBuffer::m_predictData;
-
-// records last buffer status (fill %, range -100 to 100, with 0 being 50% full)
-float SndBuffer::lastPct;
-float SndBuffer::lastEmergencyAdj;
-
-float SndBuffer::cTempo = 1;
-float SndBuffer::eTempo = 1;
-int SndBuffer::freezeTempo = 0;
-
-void SndBuffer::PredictDataWrite(int samples)
-{
-	m_predictData += samples;
-}
-
-// Calculate the buffer status percentage.
-// Returns range from -1.0 to 1.0
-//    1.0 = buffer overflow!
-//    0.0 = buffer nominal (50% full)
-//   -1.0 = buffer underflow!
-float SndBuffer::GetStatusPct()
-{
-	// Get the buffer status of the output driver too, so that we can
-	// obtain a more accurate overall buffer status.
-
-	int drvempty = 0;
-	//int drvempty = mods[OutputModule]->GetEmptySampleCount(); // / 2;
-	//TODO
-
-	//ConLog( "Data %d >>> driver: %d   predict: %d\n", data, drvempty, predictData );
-
-	float result = static_cast<float>(m_data + m_predictData - drvempty) - (m_size / 2);
-	result /= m_size / 2;
-	return result;
-}
-
-void SndBuffer::UpdateTempoChange()
-{
-	if (--freezeTempo > 0)
-		return;
-
-	float statusPct = GetStatusPct();
-	float pctChange = statusPct - lastPct;
-
-	float tempoChange;
-	float emergencyAdj = 0;
-	float newcee = cTempo; // workspace var. for cTempo
-
-	// IMPORTANT!
-	// If you plan to tweak these values, make sure you're using a release build
-	// OUTSIDE THE DEBUGGER to test it!  The Visual Studio debugger can really cause
-	// erratic behavior in the audio buffers, and makes the timestretcher seem a
-	// lot more inconsistent than it really is.
-
-	// We have two factors.
-	//   * Distance from nominal buffer status (50% full)
-	//   * The change from previous update to this update.
-
-	// Prediction based on the buffer change:
-	// (linear seems to work better here)
-
-	tempoChange = pctChange * 0.75f;
-
-	if (statusPct * tempoChange < 0.0f)
-		// only apply tempo change if it is in synch with the buffer status.
-		// In other words, if the buffer is high (over 0%), and is decreasing,
-		// ignore it.  It'll just muck things up.
-
-		tempoChange = 0;
-
-	// Sudden spikes in framerate can cause the nominal buffer status
-	// to go critical, in which case we have to enact an emergency
-	// stretch. The following cubic formulas do that.  Values near
-	// the extremeites give much larger results than those near 0.
-	// And the value is added only this time, and does not accumulate.
-	// (otherwise a large value like this would cause problems down the road)
-
-	// Constants:
-	// Weight - weights the statusPct's "emergency" consideration.
-	//   higher values here will make the buffer perform more drastic
-	//   compensations at the outer edges of the buffer (at -75 or +75%
-	//   or beyond, for example).
-
-	// Range - scales the adjustment to the given range (more or less).
-	//   The actual range is dependent on the weight used, so if you increase
-	//   Weight you'll usually want to decrease Range somewhat to compensate.
-
-	// Prediction based on the buffer fill status:
-
-	float statusWeight = 2.99f;
-	float statusRange = 0.068f;
-
-	// "non-emergency" deadzone:  In this area stretching will be strongly discouraged.
-	// Note: due tot he nature of timestretch latency, it's always a wee bit harder to
-	// cope with low fps (underruns) than it is high fps (overruns).  So to help out a
-	// little, the low-end portions of this check are less forgiving than the high-sides.
-
-	if (cTempo < 0.965f || cTempo > 1.060f || pctChange < -0.38f || pctChange > 0.54f || statusPct < -0.32f || statusPct > 0.39f || eTempo < 0.89f || eTempo > 1.19f)
-		emergencyAdj = std::pow(statusPct * statusWeight, 3.0f) * statusRange;
-
-	// Smooth things out by factoring our previous adjustment into this one.
-	// It helps make the system 'feel' a little smarter by  giving it at least
-	// one packet worth of history to help work off of:
-
-	emergencyAdj = (emergencyAdj * 0.75f) + (lastEmergencyAdj * 0.25f);
-
-	lastEmergencyAdj = emergencyAdj;
-	lastPct = statusPct;
-
-	// Accumulate a fraction of the tempo change into the tempo itself.
-	// This helps the system run "smarter" to games that run consistently
-	// fast or slow by altering the base tempo to something closer to the
-	// game's active speed.  In tests most games normalize within 2 seconds
-	// at 100ms latency, which is pretty good (larger buffers normalize even
-	// quicker).
-
-	newcee += newcee * (tempoChange + emergencyAdj) * 0.03f;
-
-	// Apply tempoChange as a scale of cTempo.  That way the effect is proportional
-	// to the current tempo.  (otherwise tempos rate of change at the extremes would
-	// be too drastic)
-
-	float newTempo = newcee + (emergencyAdj * cTempo);
-
-	// ... and as a final optimization, only stretch if the new tempo is outside
-	// a nominal threshold.  Keep this threshold check small, because it could
-	// cause some serious side effects otherwise. (enlarging the cTempo check above
-	// is usually better/safer)
-	if (newTempo < 0.970f || newTempo > 1.045f)
-	{
-		cTempo = newcee;
-
-		if (newTempo < 0.10f)
-			newTempo = 0.10f;
-		else if (newTempo > 10.0f)
-			newTempo = 10.0f;
-
-		if (cTempo < 0.15f)
-			cTempo = 0.15f;
-		else if (cTempo > 7.5f)
-			cTempo = 7.5f;
-
-		pSoundTouch->setTempo(eTempo = newTempo);
-		++ts_stats_stretchblocks;
-
-		/*ConLog(" * SPU2: [Nominal %d%%] [Emergency: %d%%] (baseTempo: %d%% ) (newTempo: %d%%) (buffer: %d%%)\n",
-			//(relation < 0.0) ? "Normalize" : "",
-			(int)(tempoChange * 100.0 * 0.03),
-			(int)(emergencyAdj * 100.0),
-			(int)(cTempo * 100.0),
-			(int)(newTempo * 100.0),
-			(int)(statusPct * 100.0)
-		);*/
-	}
-	else
-	{
-		// Nominal operation -- turn off stretching.
-		// note: eTempo 'slides' toward 1.0 for smoother audio and better
-		// protection against spikes.
-		if (!fEqual(cTempo, 1.0f))
-		{
-			cTempo = 1.0f;
-			eTempo = (1.0f + eTempo) * 0.5f;
-			pSoundTouch->setTempo(eTempo);
-		}
-		else
-		{
-			if (!fEqual(eTempo, cTempo))
-				pSoundTouch->setTempo(eTempo = cTempo);
-			++ts_stats_normalblocks;
-		}
-	}
-}
-
-void SndBuffer::timeStretchUnderrun()
-{
-	// timeStretcher failed it's job.  We need to slow down the audio some.
-
-	cTempo -= cTempo * 0.12f;
-	eTempo -= eTempo * 0.30f;
-	if (eTempo < 0.1f)
-		eTempo = 0.1f;
-	pSoundTouch->setTempo(eTempo);
-}
-
-int32_t SndBuffer::timeStretchOverrun()
-{
-	// If we overran it means the timestretcher failed.  We need to speed
-	// up audio playback.
-	cTempo += cTempo * 0.12f;
-	eTempo += eTempo * 0.40f;
-	if (eTempo > 7.5f)
-		eTempo = 7.5f;
-	pSoundTouch->setTempo(eTempo);
-
-	// Throw out just a little bit (two packets worth) to help
-	// give the TS some room to work:
-
-	return SndOutPacketSize * 2;
-}
-
-static void CvtPacketToFloat(StereoOut32 *srcdest)
-{
-	StereoOutFloat *dest = reinterpret_cast<StereoOutFloat *>(srcdest);
-	const StereoOut32 *src = srcdest;
-	for (int i = 0; i < SndOutPacketSize; ++i, ++dest, ++src)
-		*dest = static_cast<StereoOutFloat>(*src);
-}
-
-// Parameter note: Size should always be a multiple of 128, thanks!
-static void CvtPacketToInt(StereoOut32 *srcdest, uint32_t size)
-{
-	//jASSUME( (size & 127) == 0 );
-
-	const StereoOutFloat *src = reinterpret_cast<StereoOutFloat *>(srcdest);
-	StereoOut32 *dest = srcdest;
-
-	for (uint32_t i = 0; i < size; ++i, ++dest, ++src)
-		*dest = static_cast<StereoOut32>(*src);
-}
-
-void SndBuffer::timeStretchWrite()
-{
-	bool progress = false;
-
-	// data prediction helps keep the tempo adjustments more accurate.
-	// The timestretcher returns packets in belated "clump" form.
-	// Meaning that most of the time we'll get nothing back, and then
-	// suddenly we'll get several chunks back at once.  Thus we use
-	// data prediction to make the timestretcher more responsive.
-
-	PredictDataWrite(SndOutPacketSize / eTempo);
-	CvtPacketToFloat(sndTempBuffer.get());
-
-	pSoundTouch->putSamples(reinterpret_cast<float *>(sndTempBuffer.get()), SndOutPacketSize);
-
-	int tempProgress;
-	while (tempProgress = pSoundTouch->receiveSamples(reinterpret_cast<float *>(sndTempBuffer.get()), SndOutPacketSize), !!tempProgress)
-	{
-		// Hint: It's assumed that pSoundTouch will return chunks of 128 bytes (it always does as
-		// long as the SSE optimizations are enabled), which means we can do our own SSE opts here.
-
-		CvtPacketToInt(sndTempBuffer.get(), tempProgress);
-		_WriteSamples(sndTempBuffer.get(), tempProgress);
-		progress = true;
-	}
-
-	UpdateTempoChange();
-
-	//TODO
-	//if( MsgOverruns() )
-	{
-		if(progress)
-		{
-			if (++ts_stats_logcounter > 300)
-			{
-				ts_stats_logcounter = 0;
-				printf(" * SPU2 > Timestretch Stats > %d%% of packets stretched.\n", (ts_stats_stretchblocks * 100) / (ts_stats_normalblocks + ts_stats_stretchblocks));
-				ts_stats_normalblocks = ts_stats_stretchblocks = 0;
-			}
-		}
-	}
-}
-
-void SndBuffer::soundtouchInit()
-{
-	pSoundTouch.reset(new soundtouch::SoundTouch());
-	pSoundTouch->setSampleRate(SampleRate);
-	pSoundTouch->setChannels(2);
-
-	pSoundTouch->setSetting(soundtouch::SETTING_USE_QUICKSEEK, 0);
-	pSoundTouch->setSetting(soundtouch::SETTING_USE_AA_FILTER, 0);
-
-	pSoundTouch->setTempo(1);
-
-	// some timestretch management vars:
-
-	cTempo = eTempo = 1.0;
-	lastPct = lastEmergencyAdj = 0;
-
-	// just freeze tempo changes for a while at startup.
-	// the driver buffers are bogus anyway.
-	freezeTempo = 16;
-	m_predictData = 0;
-}
-

--- a/src/in_2sf/desmume/metaspu/metaspu.cpp
+++ b/src/in_2sf/desmume/metaspu/metaspu.cpp
@@ -1,4 +1,4 @@
-/*  Copyright 2009 DeSmuME team
+/*  Copyright 2009-2015 DeSmuME team
 
     This file is part of DeSmuME
 
@@ -17,475 +17,42 @@
     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
 */
 
+#include "metaspu.h"
+
 #include <queue>
 #include <vector>
-#include <cmath>
-#include "../types.h"
-#include "metaspu.h"
+#include <list>
+#include <cstring>
+#include <assert.h>
 
-//for pcsx2 method
-//(havent bothered to get it compiling in gcc yet)
-#ifdef _MSC_VER
-#include "SndOut.h"
-#endif
-
-class ZeromusSynchronizer : public ISynchronizingAudioBuffer
+class NullSynchronizer : public ISynchronizingAudioBuffer
 {
 public:
-	ZeromusSynchronizer() : mixqueue_go(false),
-#ifdef NDEBUG
-		adjustobuf(200, 1000)
-#else
-		adjustobuf(22000, 44000)
-#endif
-	{
-	}
+  std::queue<uint32_t> buffer;
+  NullSynchronizer() {}
 
-	bool mixqueue_go;
+	virtual void enqueue_samples(s16* buf, int samples_provided) {
+    for (int i = 0; i < samples_provided * 2; i += 2) {
+      uint16_t left = buf[i];
+      uint16_t right = buf[i + 1];
+      buffer.push(left << 16 | right);
+    }
+  }
 
-	virtual void enqueue_samples(int16_t *buf, int samples_provided)
-	{
-		for (int i = 0; i < samples_provided; ++i)
-		{
-			int16_t left = *buf++;
-			int16_t right = *buf++;
-			this->adjustobuf.enqueue(left, right);
-		}
-	}
-
-	// returns the number of samples actually supplied, which may not match the number requested
-	virtual int output_samples(int16_t *buf, int samples_requested)
-	{
-		int done = 0;
-		if (!this->mixqueue_go)
-		{
-			if (this->adjustobuf.size > 200)
-				this->mixqueue_go = true;
-		}
-		else
-		{
-			for (int i = 0; i < samples_requested; ++i)
-			{
-				if (!this->adjustobuf.size)
-				{
-					this->mixqueue_go = false;
-					break;
-				}
-				++done;
-				int16_t left, right;
-				this->adjustobuf.dequeue(left, right);
-				*buf++ = left;
-				*buf++ = right;
-			}
-		}
-
-		return done;
-	}
-
-private:
-	class Adjustobuf
-	{
-	public:
-		Adjustobuf(int _minLatency, int _maxLatency) : minLatency(_minLatency), maxLatency(_maxLatency), size(0)
-		{
-			this->rollingTotalSize = 0;
-			this->targetLatency = (this->maxLatency + this->minLatency) / 2;
-			this->rate = 1.0f;
-			this->cursor = 0.0f;
-			this->curr[0] = this->curr[1] = 0;
-			this->kAverageSize = 80000;
-		}
-
-		float rate, cursor;
-		int minLatency, targetLatency, maxLatency;
-		std::queue<int16_t> buffer;
-		int size;
-		int16_t curr[2];
-
-		std::queue<int> statsHistory;
-
-		void enqueue(int16_t left, int16_t right)
-		{
-			this->buffer.push(left);
-			this->buffer.push(right);
-			++this->size;
-		}
-
-		int64_t rollingTotalSize;
-
-		uint32_t kAverageSize;
-
-		void addStatistic()
-		{
-			this->statsHistory.push(this->size);
-			this->rollingTotalSize += this->size;
-			if (this->statsHistory.size() > this->kAverageSize)
-			{
-				this->rollingTotalSize -= this->statsHistory.front();
-				this->statsHistory.pop();
-
-				float averageSize = rollingTotalSize / kAverageSize;
-				//static int ctr=0;  ctr++; if((ctr&127)==0) printf("avg size: %f curr size: %d rate: %f\n",averageSize,size,rate);
-				{
-					float targetRate;
-					if (averageSize < this->targetLatency)
-						targetRate = 1.0f - (this->targetLatency - averageSize) / this->kAverageSize;
-					else if (averageSize > this->targetLatency)
-						targetRate = 1.0f + (averageSize - this->targetLatency) / this->kAverageSize;
-					else
-						targetRate = 1.0f;
-
-					//rate = moveValueTowards(rate,targetRate,0.001f);
-					this->rate = targetRate;
-				}
-			}
-		}
-
-		void dequeue(int16_t &left, int16_t &right)
-		{
-			left = right = 0;
-			this->addStatistic();
-			if (!this->size)
-				return;
-			this->cursor += this->rate;
-			while (this->cursor > 1.0f)
-			{
-				this->cursor -= 1.0f;
-				if (this->size > 0)
-				{
-					this->curr[0] = this->buffer.front();
-					this->buffer.pop();
-					this->curr[1] = this->buffer.front();
-					this->buffer.pop();
-					--this->size;
-				}
-			}
-			left = this->curr[0];
-			right = this->curr[1];
-		}
-	} adjustobuf;
+	virtual int output_samples(s16* buf, int samples_requested) {
+    int samples = ((samples_requested < buffer.size()) ? samples_requested : buffer.size()) & ~1;
+    for (int offset = 0, i = 0; i < samples; i++) {
+      uint32_t sample = buffer.front();
+      buffer.pop();
+      buf[offset++] = (sample >> 16) & 0xFFFF;
+      buf[offset++] = sample & 0xFFFF;
+    }
+    return samples;
+  }
 };
 
-class NitsujaSynchronizer : public ISynchronizingAudioBuffer
+ISynchronizingAudioBuffer* metaspu_construct(ESynchMethod method)
 {
-private:
-	struct ssamp
-	{
-		int16_t l, r;
-		ssamp() { }
-		ssamp(int16_t ll, int16_t rr) : l(ll), r(rr) { }
-	};
-
-	std::vector<ssamp> sampleQueue;
-
-	// returns values going between 0 and y-1 in a saw wave pattern, based on x
-	static int pingpong(int x, int y)
-	{
-		x %= 2 * y;
-		if (x >= y)
-			x = 2 * y - x - 1;
-		return x;
-
-		// in case we want to switch to odd buffer sizes for more sharpness
-		//x %= 2*(y-1);
-		//if(x >= y)
-		//	x = 2*(y-1) - x;
-		//return x;
-	}
-
-	static ssamp crossfade(const ssamp &lhs, const ssamp &rhs, int cur, int start, int end)
-	{
-		if (cur <= start)
-			return lhs;
-		if (cur >= end)
-			return rhs;
-
-		// in case we want sine wave interpolation instead of linear here
-		//float ang = 3.14159f * (float)(cur - start) / (float)(end - start);
-		//cur = start + (int)((1-cosf(ang))*0.5f * (end - start));
-
-		int inNum = cur - start;
-		int outNum = end - cur;
-		int denom = end - start;
-
-		int lrv = (lhs.l * outNum + rhs.l * inNum) / denom;
-		int rrv = (lhs.r * outNum + rhs.r * inNum) / denom;
-
-		return ssamp(lrv, rrv);
-	}
-
-	static void emit_sample(int16_t *&outbuf, const ssamp &sample)
-	{
-		*outbuf++ = sample.l;
-		*outbuf++ = sample.r;
-	}
-
-	static void emit_samples(int16_t *&outbuf, const ssamp *samplebuf, int samples)
-	{
-		for (int i = 0; i < samples; ++i)
-			NitsujaSynchronizer::emit_sample(outbuf, samplebuf[i]);
-	}
-
-public:
-	NitsujaSynchronizer() { }
-
-	virtual void enqueue_samples(int16_t *buf, int samples_provided)
-	{
-		for (int i = 0; i < samples_provided; ++i)
-		{
-			this->sampleQueue.push_back(ssamp(buf[0], buf[1]));
-			buf += 2;
-		}
-	}
-
-	virtual int output_samples(int16_t *buf, int samples_requested)
-	{
-		int audiosize = samples_requested;
-		int queued = this->sampleQueue.size();
-
-		// I am too lazy to deal with odd numbers
-		audiosize &= ~1;
-		queued &= ~1;
-
-		if (queued > 0x200 && audiosize > 0) // is there any work to do?
-		{
-			// are we going at normal speed?
-			// or more precisely, are the input and output queues/buffers of similar size?
-			if (queued > 900 || audiosize > queued * 2)
-			{
-				// not normal speed. we have to resample it somehow in this case.
-				if (audiosize <= queued)
-				{
-					// fast forward speed
-					// this is the easy case, just crossfade it and it sounds ok
-					for (int i = 0; i < audiosize; ++i)
-					{
-						int j = i + queued - audiosize;
-						ssamp outsamp = this->crossfade(this->sampleQueue[i], this->sampleQueue[j], i, 0, audiosize);
-						this->emit_sample(buf, outsamp);
-					}
-				}
-				else
-				{
-					// slow motion speed
-					// here we take a very different approach,
-					// instead of crossfading it, we select a single sample from the queue
-					// and make sure that the index we use to select a sample is constantly moving
-					// and that it starts at the first sample in the queue and ends on the last one.
-					//
-					// hopefully the index doesn't move discontinuously or we'll get slight crackling
-					// (there might still be a minor bug here that causes this occasionally)
-					//
-					// here's a diagram of how the index we sample from moves:
-					//
-					// queued (this axis represents the index we sample from. the top means the end of the queue)
-					// ^
-					// |   --> audiosize (this axis represents the output index we write to, right meaning forward in output time/position)
-					// |   A           C       C  end
-					//    A A     B   C C     C
-					//   A   A   A B C   C   C
-					//  A     A A   B     C C
-					// A       A           C
-					// start
-					//
-					// yes, this means we are spending some stretches of time playing the sound backwards,
-					// but the stretches are short enough that this doesn't sound weird.
-					// this lets us avoid most crackling problems due to the endpoints matching up.
-
-					// first calculate a shorter-than-full window
-					// that has minimal slope at the endpoints
-					// (to further reduce crackling, especially in sine waves)
-					int beststart = 0, extraAtEnd = 0;
-					{
-						int bestend = queued;
-						static const int worstdiff = 99999999;
-						int beststartdiff = worstdiff;
-						int bestenddiff = worstdiff;
-						for(int i = 0; i < 128; i += 2)
-						{
-							int diff = std::abs(this->sampleQueue[i].l - this->sampleQueue[i + 1].l) + std::abs(this->sampleQueue[i].r - this->sampleQueue[i + 1].r);
-							if (diff < beststartdiff)
-							{
-								beststartdiff = diff;
-								beststart = i;
-							}
-						}
-						for (int i = queued - 3; i > queued - 3 - 128; i -= 2)
-						{
-							int diff = std::abs(this->sampleQueue[i].l - this->sampleQueue[i + 1].l) + std::abs(this->sampleQueue[i].r - this->sampleQueue[i + 1].r);
-							if (diff < bestenddiff)
-							{
-								bestenddiff = diff;
-								bestend = i+1;
-							}
-						}
-
-						extraAtEnd = queued - bestend;
-						queued = bestend - beststart;
-
-						int oksize = queued;
-						while (oksize + queued * 2 + beststart + extraAtEnd <= samples_requested)
-							oksize += queued * 2;
-						audiosize = oksize;
-
-						for (int x = 0; x < beststart; ++x)
-							this->emit_sample(buf, this->sampleQueue[x]);
-						this->sampleQueue.erase(this->sampleQueue.begin(), this->sampleQueue.begin() + beststart);
-					}
-
-					int midpointX = audiosize >> 1;
-					int midpointY = queued >> 1;
-
-					// all we need to do here is calculate the X position of the leftmost "B" in the above diagram.
-					// TODO: we should calculate it with a simple equation like
-					//   midpointXOffset = min(something,somethingElse);
-					// but it's a little difficult to work it out exactly
-					// so here's a stupid search for the value for now:
-
-					int prevA = 999999;
-					int midpointXOffset = queued / 2;
-					while (true)
-					{
-						int a = std::abs(this->pingpong(midpointX - midpointXOffset, queued) - midpointY) - midpointXOffset;
-						if (((a > 0) != (prevA > 0) || (a < 0) != (prevA < 0)) && prevA != 999999)
-						{
-							if ((a + prevA) & 1) // there's some sort of off-by-one problem with this search since we're moving diagonally...
-								++midpointXOffset; // but this fixes it most of the time...
-							break; // found it
-						}
-						prevA = a;
-						--midpointXOffset;
-						if (midpointXOffset < 0)
-						{
-							midpointXOffset = 0;
-							break; // failed to find it. the two sides probably meet exactly in the center.
-						}
-					}
-
-					int leftMidpointX = midpointX - midpointXOffset;
-					int rightMidpointX = midpointX + midpointXOffset;
-					int leftMidpointY = pingpong(leftMidpointX, queued);
-					int rightMidpointY = (queued - 1) - this->pingpong(audiosize - 1 - rightMidpointX + queued * 2, queued);
-
-					// output the left almost-half of the sound (section "A")
-					for (int x = 0; x < leftMidpointX; ++x)
-					{
-						int i = this->pingpong(x, queued);
-						this->emit_sample(buf, this->sampleQueue[i]);
-					}
-
-					// output the middle stretch (section "B")
-					int y = leftMidpointY;
-					int dyMidLeft = leftMidpointY < midpointY ? 1 : -1;
-					int dyMidRight = rightMidpointY > midpointY ? 1 : -1;
-					for (int x = leftMidpointX; x < midpointX; ++x, y += dyMidLeft)
-						this->emit_sample(buf, this->sampleQueue[y]);
-					for (int x = midpointX; x < rightMidpointX; ++x, y += dyMidRight)
-						this->emit_sample(buf, this->sampleQueue[y]);
-
-					// output the end of the queued sound (section "C")
-					for (int x = rightMidpointX; x < audiosize; ++x)
-					{
-						int i = (queued - 1) - this->pingpong(audiosize - 1 - x + queued * 2, queued);
-						this->emit_sample(buf, sampleQueue[i]);
-					}
-
-					for (int x = 0; x < extraAtEnd; ++x)
-					{
-						int i = queued + x;
-						this->emit_sample(buf, this->sampleQueue[i]);
-					}
-					queued += extraAtEnd;
-					audiosize += beststart + extraAtEnd;
-				} //end else
-
-				this->sampleQueue.erase(this->sampleQueue.begin(), this->sampleQueue.begin() + queued);
-				return audiosize;
-			}
-			else
-			{
-				// normal speed
-				// just output the samples straightforwardly.
-				//
-				// at almost-full speeds (like 50/60 FPS)
-				// what will happen is that we rapidly fluctuate between entering this branch
-				// and entering the "slow motion speed" branch above.
-				// but that's ok! because all of these branches sound similar enough that we can get away with it.
-				// so the two cases actually complement each other.
-
-				if (audiosize >= queued)
-				{
-					this->emit_samples(buf, &this->sampleQueue[0], queued);
-					this->sampleQueue.erase(this->sampleQueue.begin(), this->sampleQueue.begin() + queued);
-					return queued;
-				}
-				else
-				{
-					this->emit_samples(buf, &this->sampleQueue[0], audiosize);
-					this->sampleQueue.erase(this->sampleQueue.begin(), this->sampleQueue.begin() + audiosize);
-					return audiosize;
-				}
-			} //end normal speed
-		} //end if there is any work to do
-		else
-			return 0;
-	} //output_samples
-}; //NitsujaSynchronizer
-
-#ifdef _MSC_VER
-class PCSX2Synchronizer : public ISynchronizingAudioBuffer
-{
-public:
-	std::queue<int16_t> readySamples;
-	PCSX2Synchronizer()
-	{
-		SndBuffer::Init();
-	}
-	virtual void enqueue_samples(int16_t *buf, int samples_provided)
-	{
-		for (int i = 0; i < samples_provided; ++i)
-		{
-			auto so32 = StereoOut32(buf[0], buf[1]);
-			SndBuffer::Write(so32);
-			buf += 2;
-		}
-	}
-
-	virtual int output_samples(int16_t *buf, int samples_requested)
-	{
-		for (int i = 0; i < samples_requested; ++i)
-		{
-			if (!this->readySamples.size())
-			{
-				//SndOutPacketSize
-				StereoOut16 temp[SndOutPacketSize * 2];
-				SndBuffer::ReadSamples(temp);
-				for (int i = 0; i < SndOutPacketSize; ++i)
-				{
-					this->readySamples.push(temp[i].Left);
-					this->readySamples.push(temp[i].Right);
-				}
-			}
-			*buf++ = this->readySamples.front();
-			this->readySamples.pop();
-			*buf++ = this->readySamples.front();
-			this->readySamples.pop();
-		}
-		return samples_requested;
-	}
-};
-#endif
-
-ISynchronizingAudioBuffer *metaspu_construct(ESynchMethod method)
-{
-	switch(method)
-	{
-		case ESynchMethod_N: return new NitsujaSynchronizer();
-		case ESynchMethod_Z: return new ZeromusSynchronizer();
-#ifdef _MSC_VER
-		case ESynchMethod_P: return new PCSX2Synchronizer();
-#endif
-		default: return nullptr;
-	}
+	return new NullSynchronizer();
 }
 

--- a/src/in_2sf/desmume/metaspu/metaspu.h
+++ b/src/in_2sf/desmume/metaspu/metaspu.h
@@ -1,52 +1,55 @@
-/*  Copyright 2009-2010 DeSmuME team
+/*  Copyright 2009-2015 DeSmuME team

+

+	This file is free software: you can redistribute it and/or modify

+	it under the terms of the GNU General Public License as published by

+	the Free Software Foundation, either version 2 of the License, or

+	(at your option) any later version.

+

+	This file is distributed in the hope that it will be useful,

+	but WITHOUT ANY WARRANTY; without even the implied warranty of

+	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the

+	GNU General Public License for more details.

+

+	You should have received a copy of the GNU General Public License

+	along with the this software.  If not, see <http://www.gnu.org/licenses/>.

+*/

+

+//-------------------------

+//this file contains the METASPU system

+//which is designed to handle the task of audio synchronization

+//and is designed to be as portable between multiple emulators

+//-------------------------

+

+

+#ifndef _METASPU_H_

+#define _METASPU_H_

+

+#include <algorithm>

+

+#include "types.h"

+

+class ISynchronizingAudioBuffer

+{

+public:

+  virtual ~ISynchronizingAudioBuffer() {}

+

+	virtual void enqueue_samples(s16* buf, int samples_provided) = 0;

+

+	//returns the number of samples actually supplied, which may not match the number requested

+	virtual int output_samples(s16* buf, int samples_requested) = 0;

+};

+

+enum ESynchMode

+{

+	ESynchMode_Synchronous

+};

+

+enum ESynchMethod

+{

+	ESynchMethod_0, //Null

+};

+

+ISynchronizingAudioBuffer* metaspu_construct(ESynchMethod method);

+

+#endif

 
-	This file is free software: you can redistribute it and/or modify
-	it under the terms of the GNU General Public License as published by
-	the Free Software Foundation, either version 2 of the License, or
-	(at your option) any later version.
-
-	This file is distributed in the hope that it will be useful,
-	but WITHOUT ANY WARRANTY; without even the implied warranty of
-	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-	GNU General Public License for more details.
-
-	You should have received a copy of the GNU General Public License
-	along with the this software.  If not, see <http://www.gnu.org/licenses/>.
-*/
-
-// -------------------------
-// this file contains the METASPU system
-// which is designed to handle the task of audio synchronization
-// and is designed to be as portable between multiple emulators
-// -------------------------
-
-#pragma once
-
-#include "../types.h"
-
-class ISynchronizingAudioBuffer
-{
-public:
-	virtual ~ISynchronizingAudioBuffer() { }
-
-	virtual void enqueue_samples(int16_t *buf, int samples_provided) = 0;
-
-	// returns the number of samples actually supplied, which may not match the number requested
-	virtual int output_samples(int16_t *buf, int samples_requested) = 0;
-};
-
-enum ESynchMode
-{
-	ESynchMode_DualSynchAsynch,
-	ESynchMode_Synchronous
-};
-
-enum ESynchMethod
-{
-	ESynchMethod_N, // nitsuja's
-	ESynchMethod_Z, // zero's
-	ESynchMethod_P // PCSX2 spu2-x
-};
-
-ISynchronizingAudioBuffer *metaspu_construct(ESynchMethod method);
-

--- a/src/in_2sf/desmume/thumb_instructions.cpp
+++ b/src/in_2sf/desmume/thumb_instructions.cpp
@@ -928,7 +928,7 @@
 	// ------	* If <Rn> is the lowest-numbered register specified in <registers>, the original value of <Rn> is stored.
 	// ------	* Otherwise, the stored value of <Rn> is UNPREDICTABLE.
 	if (BIT_N(i, REG_NUM(i, 8)))
-		printf("STMIA with Rb in Rlist\n");
+		fprintf(stderr, "STMIA with Rb in Rlist\n");
 
 	for (uint32_t j = 0; j < 8; ++j)
 		if (BIT_N(i, j))
@@ -940,7 +940,7 @@
 		}
 
 	if (erList)
-		 printf("STMIA with Empty Rlist\n");
+		 fprintf(stderr, "STMIA with Empty Rlist\n");
 
 	cpu->R[REG_NUM(i, 8)] = adr;
 	return MMU_aluMemCycles<PROCNUM>(2, c);
@@ -954,7 +954,7 @@
 	bool erList = true; //Empty Register List
 
 	//if (BIT_N(i, regIndex))
-	//	 printf("LDMIA with Rb in Rlist at %08X\n",cpu->instruct_adr);
+	//	 fprintf(stderr, "LDMIA with Rb in Rlist at %08X\n",cpu->instruct_adr);
 
 	for (uint32_t j = 0; j < 8; ++j)
 		if (BIT_N(i, j))
@@ -966,7 +966,7 @@
 		}
 
 	if (erList)
-		 printf("LDMIA with Empty Rlist\n");
+		 fprintf(stderr, "LDMIA with Empty Rlist\n");
 
 	// ARM_REF:	THUMB: Causes base register write-back, and is not optional
 	// ARM_REF:	If the base register <Rn> is specified in <registers>, the final value of <Rn> is the loaded value
@@ -983,7 +983,7 @@
 
 TEMPLATE static uint32_t FASTCALL OP_BKPT_THUMB(uint32_t)
 {
-	printf("THUMB%c: OP_BKPT triggered\n", PROCNUM?'7':'9');
+	fprintf(stderr, "THUMB%c: OP_BKPT triggered\n", PROCNUM?'7':'9');
 	Status_Reg tmp = cpu->CPSR;
 	armcpu_switchMode(cpu, ABT); // enter abt mode
 	cpu->R[14] = cpu->instruct_adr + 4;
@@ -1023,7 +1023,7 @@
 		//zero 30-jun-2009 - but they say that the ideas 0xFF should crash the device...
 		//uint32_t swinum = cpu->instruction & 0xFF;
 		swinum &= 0x1F;
-		//printf("%d ARM SWI %d\n",PROCNUM,swinum);
+		//fprintf(stderr, "%d ARM SWI %d\n",PROCNUM,swinum);
 		return cpu->swi_tab[swinum]() + 3;
 	}
 	else
@@ -1120,7 +1120,7 @@
 	//----- the instruction are UNPREDICTABLE (because the value read for R15 has bits[1:0]==0b10).
 	if (Rm == 15)
 	{
-		printf("THUMB%c: BX using PC as operand\n", PROCNUM?'7':'9');
+		fprintf(stderr, "THUMB%c: BX using PC as operand\n", PROCNUM?'7':'9');
 		//emu_halt();
 	}
 	cpu->CPSR.bits.T = BIT0(Rm);

--- a/src/in_2sf/desmume/types.h
+++ b/src/in_2sf/desmume/types.h
@@ -18,8 +18,31 @@
 
 #pragma once
 
+#include <windows.h>
 #include <cstddef>
 #include <cstdint>
+#include <cstdio>
+#include <algorithm>
+
+#ifdef max
+#undef max
+#endif
+
+#ifdef min
+#undef min
+#endif
+
+using u64 = uint64_t;
+using s64 = int64_t;
+using u32 = uint32_t;
+using s32 = int32_t;
+using u16 = uint16_t;
+using s16 = int16_t;
+using u8 = uint8_t;
+using s8 = int8_t;
+#ifndef FORCEINLINE
+#define FORCEINLINE inline
+#endif
 
 #ifdef _WINDOWS
 # define HAVE_LIBAGG
@@ -35,6 +58,7 @@
 # ifdef __SSE2__
 #  define ENABLE_SSE2
 # endif
+# define HAVE_JIT
 #endif
 
 #ifdef NOSSE
@@ -48,7 +72,9 @@
 #ifdef _MSC_VER
 # define strcasecmp(x, y) _stricmp(x, y)
 # define strncasecmp(x, y, l) strnicmp(x, y, l)
-# define snprintf _snprintf
+# ifndef snprintf
+#  define snprintf _snprintf
+# endif
 #endif
 
 #ifndef MAX_PATH
@@ -74,17 +100,41 @@
 
 #ifdef __MINGW32__
 # undef FASTCALL
+# undef LDM_FASTCALL
 # define FASTCALL __attribute__((fastcall))
+# define LDM_FASTCALL
 # define ASMJIT_CALL_CONV kX86FuncConvGccFastCall
+# define ASMJIT_STDLIB_CALL_CONV kX86FuncConvCDecl
 #elif defined (__i386__) && !defined(__clang__)
 # define FASTCALL __attribute__((regparm(3)))
+# define LDM_FASTCALL
 # define ASMJIT_CALL_CONV kX86FuncConvGccRegParm3
+# define ASMJIT_STDLIB_CALL_CONV kX86FuncConvCDecl
 #elif defined(_MSC_VER) || defined(__INTEL_COMPILER)
 # define FASTCALL
-# define ASMJIT_CALL_CONV kX86FuncConvCDecl
+# define LDM_FASTCALL
+# ifdef _WIN64
+#  define ASMJIT_CALL_CONV kX86FuncConvW64
+#  define ASMJIT_STDLIB_CALL_CONV kX86FuncConvW64
+# else
+#  define ASMJIT_CALL_CONV kX86FuncConvCDecl
+#  define ASMJIT_STDLIB_CALL_CONV kX86FuncConvCDecl
+# endif
 #else
 # define FASTCALL
-# define ASMJIT_CALL_CONV kX86FuncConvCDecl
+# define LDM_FASTCALL
+# if defined(__amd64__) || defined(__x86_64__)
+#  if defined(_WIN64)
+#   define ASMJIT_CALL_CONV kX86FuncConvW64
+#   define ASMJIT_STDLIB_CALL_CONV kX86FuncConvW64
+#  else
+#   define ASMJIT_CALL_CONV kX86FuncConvU64
+#   define ASMJIT_STDLIB_CALL_CONV kX86FuncConvU64
+#  endif
+# else
+#  define ASMJIT_CALL_CONV kX86FuncConvCDecl
+#  define ASMJIT_STDLIB_CALL_CONV kX86FuncConvCDecl
+# endif
 #endif
 
 /*----------------------*/

--- a/src/in_2sf/desmume/utils/AsmJit/AsmJit.h
+++ b/src/in_2sf/desmume/utils/AsmJit/AsmJit.h
@@ -324,7 +324,7 @@
 //! vendor[12] = '\0';
 //!
 //! // Print a CPU vendor retrieved from CPUID.
-//! ::printf("%s", cpuVendor);
+//! ::fprintf(stderr, "%s", cpuVendor);
 //! ~~~
 
 // ============================================================================

--- a/src/in_2sf/desmume/utils/AsmJit/base/operand.h
+++ b/src/in_2sf/desmume/utils/AsmJit/base/operand.h
@@ -1073,7 +1073,8 @@
 }
 
 //! Create void* pointer immediate value operand.
-static ASMJIT_INLINE Imm imm_ptr(void* p) {
+template <typename T>
+static ASMJIT_INLINE Imm imm_ptr(T* p) {
   return Imm(static_cast<int64_t>(reinterpret_cast<intptr_t>(p)));
 }
 

--- a/src/in_2sf/desmume/utils/AsmJit/build.h
+++ b/src/in_2sf/desmume/utils/AsmJit/build.h
@@ -10,7 +10,7 @@
 #ifdef ASMJIT_CONFIG_FILE
 # include ASMJIT_CONFIG_FILE
 #else
-# include "./config.h"
+# include "./Config.h"
 #endif // ASMJIT_CONFIG_FILE
 
 // Turn off deprecation warnings when compiling AsmJit.
@@ -264,7 +264,7 @@
 namespace asmjit { static inline int disabledTrace(...) { return 0; } }
 # ifdef ASMJIT_TRACE
 #  define ASMJIT_TSEC(_Section_) _Section_
-#  define ASMJIT_TLOG ::printf(__VA_ARGS__)
+#  define ASMJIT_TLOG ::fprintf(stderr, __VA_ARGS__)
 # else
 #  define ASMJIT_TSEC(_Section_) do {} while(0)
 #  define ASMJIT_TLOG 0 && ::asmjit::disabledTrace

--- a/src/in_2sf/desmume/utils/AsmJit/x86/x86compiler.cpp
+++ b/src/in_2sf/desmume/utils/AsmJit/x86/x86compiler.cpp
@@ -201,7 +201,7 @@
 
       case kX86FuncConvMsFastCall:
         self->_calleePopsStack = true;
-        self->_passed.set(kX86RegClassGp, IntUtil::mask(R(Cx), R(Cx)));
+        self->_passed.set(kX86RegClassGp, IntUtil::mask(R(Cx), R(Dx)));
         self->_passedOrderGp[0] = R(Cx);
         self->_passedOrderGp[1] = R(Dx);
         break;

--- a/src/in_2sf/desmume/utils/AsmJit/x86/x86scheduler.cpp
+++ b/src/in_2sf/desmume/utils/AsmJit/x86/x86scheduler.cpp
@@ -76,7 +76,7 @@
     Node* next = node_->getNext();
     ASMJIT_ASSERT(node_->getType() == kNodeTypeInst);
 
-    printf("  %s\n", X86Util::getInstInfo(static_cast<InstNode*>(node_)->getCode()).getInstName());
+    fprintf(stderr, "  %s\n", X86Util::getInstInfo(static_cast<InstNode*>(node_)->getCode()).getInstName());
     node_ = next;
   }
 

--- /dev/null
+++ b/src/in_2sf/desmume/utils/bits.h
@@ -1,1 +1,42 @@
+#ifndef BITS_H

+#define BITS_H

+

+#define BIT(n)  (1<<(n))

+

+#define BIT_N(i,n)  (((i)>>(n))&1)

+#define BIT0(i)     ((i)&1)

+#define BIT1(i)     BIT_N(i,1)

+#define BIT2(i)     BIT_N(i,2)

+#define BIT3(i)     BIT_N(i,3)

+#define BIT4(i)     BIT_N(i,4)

+#define BIT5(i)     BIT_N(i,5)

+#define BIT6(i)     BIT_N(i,6)

+#define BIT7(i)     BIT_N(i,7)

+#define BIT8(i)     BIT_N(i,8)

+#define BIT9(i)     BIT_N(i,9)

+#define BIT10(i)     BIT_N(i,10)

+#define BIT11(i)     BIT_N(i,11)

+#define BIT12(i)     BIT_N(i,12)

+#define BIT13(i)     BIT_N(i,13)

+#define BIT14(i)     BIT_N(i,14)

+#define BIT15(i)     BIT_N(i,15)

+#define BIT16(i)     BIT_N(i,16)

+#define BIT17(i)     BIT_N(i,17)

+#define BIT18(i)     BIT_N(i,18)

+#define BIT19(i)     BIT_N(i,19)

+#define BIT20(i)     BIT_N(i,20)

+#define BIT21(i)     BIT_N(i,21)

+#define BIT22(i)     BIT_N(i,22)

+#define BIT23(i)     BIT_N(i,23)

+#define BIT24(i)     BIT_N(i,24)

+#define BIT25(i)     BIT_N(i,25)

+#define BIT26(i)     BIT_N(i,26)

+#define BIT27(i)     BIT_N(i,27)

+#define BIT28(i)     BIT_N(i,28)

+#define BIT29(i)     BIT_N(i,29)

+#define BIT30(i)     BIT_N(i,30)

+#define BIT31(i)    ((i)>>31)

+

+

+#endif

 

--- a/src/in_2sf/desmume/utils/dlditool.cpp
+++ /dev/null
@@ -1,508 +1,1 @@
-/*
-    dlditool - Dynamically Linked Disk Interface patch tool
-    Copyright (C) 2006  Michael Chisholm (Chishm)
 
-	Send all queries to chishm@hotmail.com
-
-    This program is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 2 of the License, or
-    (at your option) any later version.
-
-    This program is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License along
-    with this program; if not, write to the Free Software Foundation, Inc.,
-    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-
-	* v1.24d - 2010-06-14 - zeromus
-		* Modified for inclusion in desmume
-
-	* v1.24 - 2007-08-02 - SmileyDude
-		* Now using EXIT_SUCCESS and EXIT_FAILURE at the suggestion of MachinShin.
-		* Defined EXIT_NO_DLDI_SECTION for when there is no DLDI section in a file.
-		* Added cast to strcmp() call to appease the compiler.
-
-	* v1.23 - 2007-01-23 - Chishm
-		* Fixed bug when DLDI section doesn't exist
-		* addr_t is now a signed int
-
-	* v1.22 - 2007-01-12 - WinterMute
-		* add search paths for dldi files
-
-	* v1.21 - 2007-01-12 - Chishm
-		* Improved error messages
-
-	* v1.20 - 2007-01-11 - Chishm
-		* Changed offset calculation method
-
-	* v1.10 - 2007-01-07 - Chishm
-		* Removed assumptions about endianess of computer
-			* Word size shouldn't matter now either, except that an int type must be at least 32 bits long
-		* Added *.sc.nds and *.gba.nds file extensions
-		* Improved command line argument parsing
-
-	* v1.01 - 2006-12-30 - Chishm
-		* Minor bugfix parsing 3 arguments
-
-	* v1.00 - 2006-12-25 - Chishm
-		* Original release
-*/
-//#define VERSION "v1.24"
-
-#include <cstdio>
-#include <cstring>
-#include <cctype>
-#include <cerrno>
-#include <cstdlib>
-#include <cstdarg>
-
-#include <cstdint>
-#ifndef _MSC_VER
-# include <unistd.h>
-# include <sys/param.h>
-#else
-#define MAXPATHLEN 1024
-#endif
-
-#include <sys/stat.h>
-
-namespace DLDI
-{
-
-typedef int32_t addr_t;
-typedef unsigned char data_t;
-
-#define FIX_ALL 0x01
-#define FIX_GLUE 0x02
-#define FIX_GOT 0x04
-#define FIX_BSS 0x08
-
-enum DldiOffsets
-{
-	DO_magicString = 0x00, // "\xED\xA5\x8D\xBF Chishm"
-	DO_magicToken = 0x00, // 0xBF8DA5ED
-	DO_magicShortString = 0x04, // " Chishm"
-	DO_version = 0x0C,
-	DO_driverSize = 0x0D,
-	DO_fixSections = 0x0E,
-	DO_allocatedSpace = 0x0F,
-
-	DO_friendlyName = 0x10,
-
-	DO_text_start = 0x40, // Data start
-	DO_data_end = 0x44, // Data end
-	DO_glue_start = 0x48, // Interworking glue start -- Needs address fixing
-	DO_glue_end = 0x4C, // Interworking glue end
-	DO_got_start = 0x50, // GOT start -- Needs address fixing
-	DO_got_end = 0x54, // GOT end
-	DO_bss_start = 0x58, // bss start -- Needs setting to zero
-	DO_bss_end = 0x5C, // bss end
-
-	// IO_INTERFACE data
-	DO_ioType = 0x60,
-	DO_features = 0x64,
-	DO_startup = 0x68,
-	DO_isInserted = 0x6C,
-	DO_readSectors = 0x70,
-	DO_writeSectors = 0x74,
-	DO_clearStatus = 0x78,
-	DO_shutdown = 0x7C,
-	DO_code = 0x80
-};
-
-const data_t dldiMagicString[] = "\xED\xA5\x8D\xBF Chishm";
-const char dldiFileExtension[] = ".dldi";
-
-addr_t readAddr(data_t *mem, addr_t offset)
-{
-	return mem[offset + 0] | (mem[offset + 1] << 8) | (mem[offset + 2] << 16) | (mem[offset + 3] << 24);
-}
-
-void writeAddr(data_t *mem, addr_t offset, addr_t value)
-{
-	mem[offset + 0] = value & 0xFF;
-	mem[offset + 1] = (value >> 8) & 0xFF;
-	mem[offset + 2] = (value >> 16) & 0xFF;
-	mem[offset + 3] = (value >> 24) & 0xFF;
-}
-
-int stringCaseInsensitiveCompare(const char *str1, const char *str2)
-{
-	while (tolower(*str1) == tolower(*str2))
-	{
-		if (!*str1)
-			return 0;
-		++str1;
-		++str2;
-	}
-	return tolower(*str1) - tolower(*str2);
-}
-
-bool stringEndsWith(const char *str, const char *end)
-{
-	if (strlen(str) < strlen(end))
-		return false;
-	const char *strEnd = &str[strlen (str) - strlen(end)];
-	return !stringCaseInsensitiveCompare(strEnd, end);
-}
-
-bool stringStartsWith(const char *str, const char *start)
-{
-	return strstr(str, start) == str;
-}
-
-addr_t quickFind(const data_t *data, const data_t *search, size_t dataLen, size_t searchLen)
-{
-	const int32_t *dataChunk = reinterpret_cast<const int32_t *>(data);
-	int searchChunk = reinterpret_cast<const int32_t *>(search)[0];
-	addr_t dataChunkEnd = static_cast<addr_t>(dataLen / sizeof(int32_t));
-
-	for (addr_t i = 0; i < dataChunkEnd; ++i)
-	{
-		if (dataChunk[i] == searchChunk)
-		{
-			if (i * sizeof(int32_t) + searchLen > dataLen)
-				return -1;
-			if (!memcmp(&data[i * sizeof(int32_t)], search, searchLen))
-				return i * sizeof(int32_t);
-		}
-	}
-
-	return -1;
-}
-
-FILE *openDLDIFile(const char *argv0, char *dldiFileName )
-{
-	// add .dldi extension to filename
-	if (!stringEndsWith(dldiFileName, dldiFileExtension))
-		strcat(dldiFileName, dldiFileExtension);
-
-	printf("Trying \"%s\"\n", dldiFileName);
-	// try opening from current directory
-	FILE *dldiFile = fopen(dldiFileName, "rb");
-
-	if (dldiFile)
-		return dldiFile;
-
-	// check if the filename has a path component
-	// check both slash varieties, win32 understands both
-	// if we have a directory separator don't bother with search paths
-	if (strstr(dldiFileName, "\\"))
-		return nullptr;
-	if (strstr(dldiFileName ,"/"))
-		return nullptr;
-
-	// check for DLDIPATH in environment
-	char *dldiPATH = getenv("DLDIPATH");
-
-	char appPath[MAXPATHLEN];
-	if (dldiPATH)
-	{
-		strcpy(appPath, dldiPATH);
-		if (appPath[strlen(appPath)] != '\\' &&  appPath[strlen(appPath)] != '/')
-			strcat(appPath, "/");
-		strcat(appPath, dldiFileName);
-
-		printf("Trying \"%s\"\n", appPath);
-		dldiFile = fopen(appPath,"rb");
-
-		if (dldiFile)
-			return dldiFile;
-	}
-
-	char *lastSlash = nullptr;
-	char *ptr = const_cast<char *>(argv0);
-
-	while (*(ptr++))
-		if (*ptr == '\\' || * ptr == '/')
-			lastSlash = ptr;
-
-	char appName[MAXPATHLEN];
-	char appPathName[MAXPATHLEN];
-	if (lastSlash)
-	{
-		*(lastSlash++) = '\0';
-		strcpy(appPath, argv0);
-		strcpy(appName, lastSlash);
-		strcat(appPath, "/");
-	}
-	else
-	{
-		strcpy(appPath, "");
-		strcpy(appName, argv0);
-	}
-
-	// finally try in the application path
-	// if argv0 contains a directory separator we have a path component
-
-	if (!strstr(appPath,"\\") && !strstr(appPath,"/"))
-	{
-		// no path in argv0 so search system path
-		char *sysPATH = getenv("PATH");
-		char *thisPATH = sysPATH;
-		printf("Searching system path\n%s\n", sysPATH);
-
-		while (1)
-		{
-			char *nextPATH = strstr(thisPATH, ":" ); // find next PATH separator
-
-			if (nextPATH)
-				*(nextPATH++) = '\0'; // terminate string, point to next component
-
-			strcpy(appPath, thisPATH);
-			strcat(appPath, "/");
-			strcpy(appPathName, appPath);
-			strcat(appPathName, appName); // add application name
-
-			struct stat buf;
-			if (!stat(appPathName, &buf)) // if it exists we found the path
-				break;
-
-			thisPATH = nextPATH;
-			strcpy(appPath, "");// empty path
-			if (!thisPATH)
-				break;
-		}
-	}
-
-	strcat(appPath, "dldi/"); // add dldi folder
-	strcat(appPath, dldiFileName); // add dldi filename to path
-	printf("Trying \"%s\"\n", appPath);
-
-	return fopen(appPath, "rb"); // no more places to check, just return this handle
-}
-
-//  Source File: mpcf.dldi
-//         Time: 6/14/2010 9:38 PM
-// Orig. Offset: 0 / 0x00000000
-//       Length: 1876 / 0x00000754 (bytes)
-static data_t mpcf_dldi[] =
-{
-    0xED, 0xA5, 0x8D, 0xBF, 0x20, 0x43, 0x68, 0x69, 0x73, 0x68, 0x6D, 0x00, 0x01, 0x0B, 0x0C, 0x00,
-    0x47, 0x42, 0x41, 0x20, 0x4D, 0x6F, 0x76, 0x69, 0x65, 0x20, 0x50, 0x6C, 0x61, 0x79, 0x65, 0x72,
-    0x20, 0x28, 0x43, 0x6F, 0x6D, 0x70, 0x61, 0x63, 0x74, 0x20, 0x46, 0x6C, 0x61, 0x73, 0x68, 0x29,
-    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-    0x00, 0x00, 0x80, 0xBF, 0x54, 0x07, 0x80, 0xBF, 0x98, 0x00, 0x80, 0xBF, 0x98, 0x00, 0x80, 0xBF,
-    0x50, 0x07, 0x80, 0xBF, 0x50, 0x07, 0x80, 0xBF, 0x54, 0x07, 0x80, 0xBF, 0x70, 0x07, 0x80, 0xBF,
-    0x4D, 0x50, 0x43, 0x46, 0x13, 0x00, 0x00, 0x00, 0x3C, 0x01, 0x80, 0xBF, 0x98, 0x01, 0x80, 0xBF,
-    0x78, 0x02, 0x80, 0xBF, 0xC8, 0x04, 0x80, 0xBF, 0xC8, 0x01, 0x80, 0xBF, 0x10, 0x07, 0x80, 0xBF,
-    0x0D, 0xC0, 0xA0, 0xE1, 0xF8, 0xDF, 0x2D, 0xE9, 0x04, 0xB0, 0x4C, 0xE2, 0x28, 0xD0, 0x4B, 0xE2,
-    0xF0, 0x6F, 0x9D, 0xE8, 0x1E, 0xFF, 0x2F, 0xE1, 0x10, 0x40, 0x2D, 0xE9, 0x2C, 0x40, 0x9F, 0xE5,
-    0x00, 0x30, 0xD4, 0xE5, 0x00, 0x00, 0x53, 0xE3, 0x24, 0x20, 0x9F, 0xE5, 0x05, 0x00, 0x00, 0x1A,
-    0x00, 0x00, 0x52, 0xE3, 0x1C, 0x00, 0x9F, 0xE5, 0x0F, 0xE0, 0xA0, 0x11, 0x12, 0xFF, 0x2F, 0x11,
-    0x01, 0x30, 0xA0, 0xE3, 0x00, 0x30, 0xC4, 0xE5, 0x10, 0x40, 0xBD, 0xE8, 0x1E, 0xFF, 0x2F, 0xE1,
-    0x54, 0x07, 0x80, 0xBF, 0x00, 0x00, 0x00, 0x00, 0x48, 0x07, 0x80, 0xBF, 0x04, 0xE0, 0x2D, 0xE5,
-    0x40, 0x30, 0x9F, 0xE5, 0x00, 0x00, 0x53, 0xE3, 0x04, 0xD0, 0x4D, 0xE2, 0x38, 0x00, 0x9F, 0xE5,
-    0x38, 0x10, 0x9F, 0xE5, 0x0F, 0xE0, 0xA0, 0x11, 0x13, 0xFF, 0x2F, 0x11, 0x30, 0x00, 0x9F, 0xE5,
-    0x00, 0x30, 0x90, 0xE5, 0x00, 0x00, 0x53, 0xE3, 0x28, 0x30, 0x9F, 0xE5, 0x02, 0x00, 0x00, 0x0A,
-    0x00, 0x00, 0x53, 0xE3, 0x0F, 0xE0, 0xA0, 0x11, 0x13, 0xFF, 0x2F, 0x11, 0x04, 0xD0, 0x8D, 0xE2,
-    0x04, 0xE0, 0x9D, 0xE4, 0x1E, 0xFF, 0x2F, 0xE1, 0x00, 0x00, 0x00, 0x00, 0x48, 0x07, 0x80, 0xBF,
-    0x58, 0x07, 0x80, 0xBF, 0x4C, 0x07, 0x80, 0xBF, 0x00, 0x00, 0x00, 0x00, 0x09, 0x14, 0xA0, 0xE3,
-    0x06, 0x18, 0x81, 0xE2, 0xB0, 0x30, 0xD1, 0xE1, 0x03, 0x30, 0xE0, 0xE1, 0x03, 0x38, 0xA0, 0xE1,
-    0x23, 0x38, 0xA0, 0xE1, 0xFF, 0x30, 0x03, 0xE2, 0xB0, 0x30, 0xC1, 0xE1, 0xB0, 0x20, 0xD1, 0xE1,
-    0x04, 0xE0, 0x2D, 0xE5, 0xAA, 0xCC, 0xA0, 0xE3, 0x55, 0xEC, 0xE0, 0xE3, 0x03, 0x00, 0x52, 0xE1,
-    0xAA, 0xE0, 0x4E, 0xE2, 0x55, 0xC0, 0x8C, 0xE2, 0x00, 0x00, 0xA0, 0xE3, 0x03, 0x00, 0x00, 0x1A,
-    0xB0, 0xE0, 0xC1, 0xE1, 0xB0, 0x30, 0xD1, 0xE1, 0x0C, 0x00, 0x53, 0xE0, 0x01, 0x00, 0xA0, 0x13,
-    0x04, 0xE0, 0x9D, 0xE4, 0x1E, 0xFF, 0x2F, 0xE1, 0x26, 0x35, 0xA0, 0xE3, 0x03, 0x37, 0x83, 0xE2,
-    0x50, 0x20, 0xA0, 0xE3, 0xB0, 0x20, 0xC3, 0xE1, 0xB0, 0x00, 0xD3, 0xE1, 0x00, 0x08, 0xA0, 0xE1,
-    0x20, 0x08, 0xA0, 0xE1, 0xFF, 0x00, 0x00, 0xE2, 0x50, 0x00, 0x50, 0xE3, 0x00, 0x00, 0xA0, 0x13,
-    0x01, 0x00, 0xA0, 0x03, 0x1E, 0xFF, 0x2F, 0xE1, 0x09, 0x34, 0xA0, 0xE3, 0x0E, 0x38, 0x83, 0xE2,
-    0xB0, 0x20, 0xD3, 0xE1, 0x80, 0x00, 0x12, 0xE3, 0x0C, 0x00, 0x00, 0x0A, 0x00, 0x00, 0xA0, 0xE3,
-    0x01, 0x00, 0x00, 0xEA, 0x01, 0x00, 0x50, 0xE1, 0x08, 0x00, 0x00, 0x0A, 0x09, 0x34, 0xA0, 0xE3,
-    0x0E, 0x38, 0x83, 0xE2, 0xB0, 0x20, 0xD3, 0xE1, 0x26, 0x17, 0xA0, 0xE3, 0x96, 0x1C, 0x81, 0xE2,
-    0x80, 0x00, 0x12, 0xE3, 0x01, 0x00, 0x80, 0xE2, 0x80, 0x10, 0x81, 0xE2, 0xF4, 0xFF, 0xFF, 0x1A,
-    0x26, 0x15, 0xA0, 0xE3, 0x03, 0x17, 0x81, 0xE2, 0xB0, 0x30, 0xD1, 0xE1, 0x50, 0x30, 0x13, 0xE2,
-    0x01, 0x00, 0xA0, 0x13, 0x1E, 0xFF, 0x2F, 0x11, 0x26, 0x27, 0xA0, 0xE3, 0x96, 0x2C, 0x82, 0xE2,
-    0x03, 0x00, 0xA0, 0xE1, 0x80, 0x20, 0x82, 0xE2, 0x01, 0x00, 0x00, 0xEA, 0x02, 0x00, 0x50, 0xE1,
-    0x0A, 0x00, 0x00, 0x0A, 0xB0, 0x30, 0xD1, 0xE1, 0x50, 0x30, 0x13, 0xE2, 0x01, 0x00, 0x80, 0xE2,
-    0xF9, 0xFF, 0xFF, 0x0A, 0x26, 0x37, 0xA0, 0xE3, 0x96, 0x3C, 0x83, 0xE2, 0x7F, 0x30, 0x83, 0xE2,
-    0x03, 0x00, 0x50, 0xE1, 0x00, 0x00, 0xA0, 0xC3, 0x01, 0x00, 0xA0, 0xD3, 0x1E, 0xFF, 0x2F, 0xE1,
-    0x03, 0x00, 0xA0, 0xE1, 0x1E, 0xFF, 0x2F, 0xE1, 0xF0, 0x4B, 0x2D, 0xE9, 0x09, 0x34, 0xA0, 0xE3,
-    0x0E, 0x38, 0x83, 0xE2, 0xB0, 0xC0, 0xD3, 0xE1, 0x80, 0x00, 0x1C, 0xE3, 0x10, 0xD0, 0x4D, 0xE2,
-    0x01, 0x90, 0xA0, 0xE1, 0x02, 0xE0, 0xA0, 0xE1, 0x0C, 0x00, 0x00, 0x0A, 0x00, 0xC0, 0xA0, 0xE3,
-    0x01, 0x00, 0x00, 0xEA, 0x01, 0x00, 0x5C, 0xE1, 0x08, 0x00, 0x00, 0x0A, 0x09, 0x34, 0xA0, 0xE3,
-    0x0E, 0x38, 0x83, 0xE2, 0xB0, 0x20, 0xD3, 0xE1, 0x26, 0x17, 0xA0, 0xE3, 0x96, 0x1C, 0x81, 0xE2,
-    0x80, 0x00, 0x12, 0xE3, 0x01, 0xC0, 0x8C, 0xE2, 0x80, 0x10, 0x81, 0xE2, 0xF4, 0xFF, 0xFF, 0x1A,
-    0x26, 0xC5, 0xA0, 0xE3, 0x03, 0xC7, 0x8C, 0xE2, 0xB0, 0x30, 0xDC, 0xE1, 0x50, 0x30, 0x13, 0xE2,
-    0x26, 0x17, 0xA0, 0x03, 0x96, 0x1C, 0x81, 0x02, 0x03, 0x20, 0xA0, 0x01, 0x80, 0x10, 0x81, 0x02,
-    0x02, 0x00, 0x00, 0x0A, 0x0A, 0x00, 0x00, 0xEA, 0x01, 0x00, 0x52, 0xE1, 0x67, 0x00, 0x00, 0x0A,
-    0xB0, 0x30, 0xDC, 0xE1, 0x50, 0x00, 0x13, 0xE3, 0x01, 0x20, 0x82, 0xE2, 0xF9, 0xFF, 0xFF, 0x0A,
-    0x26, 0x37, 0xA0, 0xE3, 0x96, 0x3C, 0x83, 0xE2, 0x7F, 0x30, 0x83, 0xE2, 0x03, 0x00, 0x52, 0xE1,
-    0x5E, 0x00, 0x00, 0xCA, 0xFF, 0x00, 0x59, 0xE3, 0x00, 0x30, 0xA0, 0x83, 0x0C, 0x30, 0x8D, 0x85,
-    0x5E, 0x00, 0x00, 0x9A, 0x00, 0x38, 0xA0, 0xE1, 0x23, 0x38, 0xA0, 0xE1, 0xFF, 0x30, 0x03, 0xE2,
-    0x09, 0x54, 0xA0, 0xE3, 0x04, 0x30, 0x8D, 0xE5, 0x0C, 0x30, 0x9D, 0xE5, 0x20, 0x4C, 0xA0, 0xE1,
-    0x0E, 0xB0, 0xA0, 0xE1, 0x05, 0x60, 0xA0, 0xE1, 0x20, 0x74, 0xA0, 0xE1, 0x05, 0x20, 0xA0, 0xE1,
-    0x20, 0x18, 0xA0, 0xE1, 0x05, 0xC0, 0xA0, 0xE1, 0x05, 0x00, 0xA0, 0xE1, 0x05, 0xE0, 0xA0, 0xE1,
-    0x01, 0x57, 0x85, 0xE2, 0xB0, 0x30, 0xC5, 0xE1, 0x04, 0x30, 0x9D, 0xE5, 0x0F, 0x40, 0x04, 0xE2,
-    0x06, 0x68, 0x86, 0xE2, 0xB0, 0x30, 0xC6, 0xE1, 0xFF, 0x70, 0x07, 0xE2, 0x02, 0x27, 0x82, 0xE2,
-    0xFF, 0x10, 0x01, 0xE2, 0x0A, 0x08, 0x80, 0xE2, 0xE0, 0x40, 0x84, 0xE3, 0x03, 0xC7, 0x8C, 0xE2,
-    0x0E, 0xE8, 0x8E, 0xE2, 0x20, 0x30, 0xA0, 0xE3, 0xB0, 0x70, 0xC2, 0xE1, 0xB0, 0x10, 0xC0, 0xE1,
-    0xB0, 0x40, 0xCC, 0xE1, 0xB0, 0x30, 0xCE, 0xE1, 0x0B, 0x80, 0xA0, 0xE1, 0x01, 0x90, 0x59, 0xE2,
-    0x3E, 0x00, 0x00, 0x3A, 0x26, 0x25, 0xA0, 0xE3, 0x03, 0x27, 0x82, 0xE2, 0xB0, 0x30, 0xD2, 0xE1,
-    0x03, 0x38, 0xA0, 0xE1, 0x23, 0x38, 0xA0, 0xE1, 0xFF, 0x30, 0x03, 0xE2, 0x58, 0x00, 0x53, 0xE3,
-    0x26, 0x17, 0xA0, 0x13, 0x96, 0x1C, 0x81, 0x12, 0x02, 0x00, 0xA0, 0x11, 0x80, 0x10, 0x81, 0x12,
-    0x00, 0x20, 0xA0, 0x13, 0x02, 0x00, 0x00, 0x1A, 0x0D, 0x00, 0x00, 0xEA, 0x01, 0x00, 0x52, 0xE1,
-    0x26, 0x00, 0x00, 0x0A, 0xB0, 0x30, 0xD0, 0xE1, 0x03, 0x38, 0xA0, 0xE1, 0x23, 0x38, 0xA0, 0xE1,
-    0xFF, 0x30, 0x03, 0xE2, 0x58, 0x00, 0x53, 0xE3, 0x01, 0x20, 0x82, 0xE2, 0xF6, 0xFF, 0xFF, 0x1A,
-    0x26, 0x37, 0xA0, 0xE3, 0x96, 0x3C, 0x83, 0xE2, 0x7F, 0x30, 0x83, 0xE2, 0x03, 0x00, 0x52, 0xE1,
-    0x1A, 0x00, 0x00, 0xCA, 0x01, 0x00, 0x18, 0xE3, 0x0B, 0x10, 0xA0, 0x01, 0xFF, 0x20, 0xA0, 0x03,
-    0x09, 0x04, 0xA0, 0x03, 0x0E, 0x00, 0x00, 0x0A, 0x08, 0x10, 0xA0, 0xE1, 0xFF, 0x00, 0xA0, 0xE3,
-    0x09, 0xC4, 0xA0, 0xE3, 0xB0, 0x30, 0xDC, 0xE1, 0x03, 0x38, 0xA0, 0xE1, 0x23, 0x38, 0xA0, 0xE1,
-    0x01, 0x00, 0x40, 0xE2, 0x43, 0x24, 0xA0, 0xE1, 0x01, 0x00, 0x70, 0xE3, 0x01, 0x20, 0xC1, 0xE5,
-    0x00, 0x30, 0xC1, 0xE5, 0x02, 0x10, 0x81, 0xE2, 0xF5, 0xFF, 0xFF, 0x1A, 0x02, 0x8C, 0x88, 0xE2,
-    0xCD, 0xFF, 0xFF, 0xEA, 0x01, 0x20, 0x42, 0xE2, 0xB0, 0x30, 0xD0, 0xE1, 0x01, 0x00, 0x72, 0xE3,
-    0xB2, 0x30, 0xC1, 0xE0, 0xFA, 0xFF, 0xFF, 0x1A, 0x02, 0xBC, 0x8B, 0xE2, 0xC6, 0xFF, 0xFF, 0xEA,
-    0x00, 0x00, 0xA0, 0xE3, 0x10, 0xD0, 0x8D, 0xE2, 0xF0, 0x4B, 0xBD, 0xE8, 0x1E, 0xFF, 0x2F, 0xE1,
-    0x09, 0x38, 0xA0, 0xE1, 0x23, 0x38, 0xA0, 0xE1, 0x0C, 0x30, 0x8D, 0xE5, 0x9C, 0xFF, 0xFF, 0xEA,
-    0x01, 0x00, 0xA0, 0xE3, 0xF6, 0xFF, 0xFF, 0xEA, 0xF0, 0x4B, 0x2D, 0xE9, 0x09, 0x34, 0xA0, 0xE3,
-    0x0E, 0x38, 0x83, 0xE2, 0xB0, 0xC0, 0xD3, 0xE1, 0x80, 0x00, 0x1C, 0xE3, 0x10, 0xD0, 0x4D, 0xE2,
-    0x01, 0x90, 0xA0, 0xE1, 0x02, 0xE0, 0xA0, 0xE1, 0x0C, 0x00, 0x00, 0x0A, 0x00, 0xC0, 0xA0, 0xE3,
-    0x01, 0x00, 0x00, 0xEA, 0x01, 0x00, 0x5C, 0xE1, 0x08, 0x00, 0x00, 0x0A, 0x09, 0x34, 0xA0, 0xE3,
-    0x0E, 0x38, 0x83, 0xE2, 0xB0, 0x20, 0xD3, 0xE1, 0x26, 0x17, 0xA0, 0xE3, 0x96, 0x1C, 0x81, 0xE2,
-    0x80, 0x00, 0x12, 0xE3, 0x01, 0xC0, 0x8C, 0xE2, 0x80, 0x10, 0x81, 0xE2, 0xF4, 0xFF, 0xFF, 0x1A,
-    0x26, 0xC5, 0xA0, 0xE3, 0x03, 0xC7, 0x8C, 0xE2, 0xB0, 0x30, 0xDC, 0xE1, 0x50, 0x30, 0x13, 0xE2,
-    0x26, 0x17, 0xA0, 0x03, 0x96, 0x1C, 0x81, 0x02, 0x03, 0x20, 0xA0, 0x01, 0x80, 0x10, 0x81, 0x02,
-    0x02, 0x00, 0x00, 0x0A, 0x0A, 0x00, 0x00, 0xEA, 0x01, 0x00, 0x52, 0xE1, 0x65, 0x00, 0x00, 0x0A,
-    0xB0, 0x30, 0xDC, 0xE1, 0x50, 0x00, 0x13, 0xE3, 0x01, 0x20, 0x82, 0xE2, 0xF9, 0xFF, 0xFF, 0x0A,
-    0x26, 0x37, 0xA0, 0xE3, 0x96, 0x3C, 0x83, 0xE2, 0x7F, 0x30, 0x83, 0xE2, 0x03, 0x00, 0x52, 0xE1,
-    0x5C, 0x00, 0x00, 0xCA, 0xFF, 0x00, 0x59, 0xE3, 0x00, 0x30, 0xA0, 0x83, 0x0C, 0x30, 0x8D, 0x85,
-    0x5C, 0x00, 0x00, 0x9A, 0x00, 0x38, 0xA0, 0xE1, 0x23, 0x38, 0xA0, 0xE1, 0xFF, 0x30, 0x03, 0xE2,
-    0x09, 0x54, 0xA0, 0xE3, 0x04, 0x30, 0x8D, 0xE5, 0x0C, 0x30, 0x9D, 0xE5, 0x20, 0x4C, 0xA0, 0xE1,
-    0x0E, 0xB0, 0xA0, 0xE1, 0x05, 0x60, 0xA0, 0xE1, 0x20, 0x74, 0xA0, 0xE1, 0x05, 0x20, 0xA0, 0xE1,
-    0x20, 0x18, 0xA0, 0xE1, 0x05, 0xC0, 0xA0, 0xE1, 0x05, 0x00, 0xA0, 0xE1, 0x05, 0xE0, 0xA0, 0xE1,
-    0x01, 0x57, 0x85, 0xE2, 0xB0, 0x30, 0xC5, 0xE1, 0x04, 0x30, 0x9D, 0xE5, 0x0F, 0x40, 0x04, 0xE2,
-    0x06, 0x68, 0x86, 0xE2, 0xB0, 0x30, 0xC6, 0xE1, 0xFF, 0x70, 0x07, 0xE2, 0x02, 0x27, 0x82, 0xE2,
-    0xFF, 0x10, 0x01, 0xE2, 0x0A, 0x08, 0x80, 0xE2, 0xE0, 0x40, 0x84, 0xE3, 0x03, 0xC7, 0x8C, 0xE2,
-    0x0E, 0xE8, 0x8E, 0xE2, 0x30, 0x30, 0xA0, 0xE3, 0xB0, 0x70, 0xC2, 0xE1, 0xB0, 0x10, 0xC0, 0xE1,
-    0xB0, 0x40, 0xCC, 0xE1, 0xB0, 0x30, 0xCE, 0xE1, 0x0B, 0x80, 0xA0, 0xE1, 0x01, 0x90, 0x59, 0xE2,
-    0x3C, 0x00, 0x00, 0x3A, 0x26, 0x25, 0xA0, 0xE3, 0x03, 0x27, 0x82, 0xE2, 0xB0, 0x30, 0xD2, 0xE1,
-    0x03, 0x38, 0xA0, 0xE1, 0x23, 0x38, 0xA0, 0xE1, 0xFF, 0x30, 0x03, 0xE2, 0x58, 0x00, 0x53, 0xE3,
-    0x26, 0x17, 0xA0, 0x13, 0x96, 0x1C, 0x81, 0x12, 0x02, 0x00, 0xA0, 0x11, 0x80, 0x10, 0x81, 0x12,
-    0x00, 0x20, 0xA0, 0x13, 0x02, 0x00, 0x00, 0x1A, 0x0D, 0x00, 0x00, 0xEA, 0x01, 0x00, 0x52, 0xE1,
-    0x24, 0x00, 0x00, 0x0A, 0xB0, 0x30, 0xD0, 0xE1, 0x03, 0x38, 0xA0, 0xE1, 0x23, 0x38, 0xA0, 0xE1,
-    0xFF, 0x30, 0x03, 0xE2, 0x58, 0x00, 0x53, 0xE3, 0x01, 0x20, 0x82, 0xE2, 0xF6, 0xFF, 0xFF, 0x1A,
-    0x26, 0x37, 0xA0, 0xE3, 0x96, 0x3C, 0x83, 0xE2, 0x7F, 0x30, 0x83, 0xE2, 0x03, 0x00, 0x52, 0xE1,
-    0x18, 0x00, 0x00, 0xCA, 0x01, 0x00, 0x18, 0xE3, 0x0B, 0x10, 0xA0, 0x01, 0xFF, 0x20, 0xA0, 0x03,
-    0x09, 0x04, 0xA0, 0x03, 0x0C, 0x00, 0x00, 0x0A, 0x08, 0x10, 0xA0, 0xE1, 0xFF, 0x00, 0xA0, 0xE3,
-    0x09, 0xC4, 0xA0, 0xE3, 0x00, 0x30, 0xD1, 0xE5, 0x01, 0x20, 0xD1, 0xE5, 0x01, 0x00, 0x40, 0xE2,
-    0x02, 0x34, 0x83, 0xE1, 0x01, 0x00, 0x70, 0xE3, 0xB0, 0x30, 0xCC, 0xE1, 0x02, 0x10, 0x81, 0xE2,
-    0xF7, 0xFF, 0xFF, 0x1A, 0x02, 0x8C, 0x88, 0xE2, 0xCF, 0xFF, 0xFF, 0xEA, 0x01, 0x20, 0x42, 0xE2,
-    0xB2, 0x30, 0xD1, 0xE0, 0x01, 0x00, 0x72, 0xE3, 0xB0, 0x30, 0xC0, 0xE1, 0xFA, 0xFF, 0xFF, 0x1A,
-    0x02, 0xBC, 0x8B, 0xE2, 0xC8, 0xFF, 0xFF, 0xEA, 0x00, 0x00, 0xA0, 0xE3, 0x10, 0xD0, 0x8D, 0xE2,
-    0xF0, 0x4B, 0xBD, 0xE8, 0x1E, 0xFF, 0x2F, 0xE1, 0x09, 0x38, 0xA0, 0xE1, 0x23, 0x38, 0xA0, 0xE1,
-    0x0C, 0x30, 0x8D, 0xE5, 0x9E, 0xFF, 0xFF, 0xEA, 0x01, 0x00, 0xA0, 0xE3, 0xF6, 0xFF, 0xFF, 0xEA,
-    0x04, 0xE0, 0x2D, 0xE5, 0x04, 0xD0, 0x4D, 0xE2, 0xAA, 0xFE, 0xFF, 0xEB, 0x04, 0xD0, 0x8D, 0xE2,
-    0x04, 0xE0, 0x9D, 0xE4, 0x1E, 0xFF, 0x2F, 0xE1, 0x0D, 0xC0, 0xA0, 0xE1, 0xF8, 0xDF, 0x2D, 0xE9,
-    0x04, 0xB0, 0x4C, 0xE2, 0x28, 0xD0, 0x4B, 0xE2, 0xF0, 0x6F, 0x9D, 0xE8, 0x1E, 0xFF, 0x2F, 0xE1,
-    0xDC, 0x00, 0x80, 0xBF, 0x98, 0x00, 0x80, 0xBF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-    0x00, 0x00, 0x00, 0x00,
-}; //unsigned char mpcf_dldi[1876]
-
-bool tryPatch(void *data, size_t size)
-{
-	// Find the DSDI reserved space in the file
-	addr_t patchOffset = quickFind(static_cast<data_t *>(data), dldiMagicString, size, sizeof(dldiMagicString) / sizeof(char));
-
-	// no DLDI section
-	if (patchOffset < 0)
-		return false;
-
-	data_t *pDH = mpcf_dldi;
-	data_t *pAH = static_cast<data_t *>(data) + patchOffset;
-
-	if (pDH[DO_driverSize] > pAH[DO_allocatedSpace])
-	{
-		printf("Not enough space for patch. Available %d bytes, need %d bytes\n", 1 << pAH[DO_allocatedSpace], 1 << pDH[DO_driverSize]);
-		return false;
-	}
-
-	if (memcmp(&pAH[DO_friendlyName], "Default (No interface)", 22))
-	{
-		printf("Would have been a candidate for auto-patch DLDI, but there was already a patch installed.");
-		return false;
-	}
-
-	//----should be able to patch OK-----
-
-	addr_t memOffset; // Offset of DLDI after the file is loaded into memory
-	addr_t relocationOffset; // Value added to all offsets within the patch to fix it properly
-	addr_t ddmemOffset; // Original offset used in the DLDI file
-	addr_t ddmemStart; // Start of range that offsets can be in the DLDI file
-	addr_t ddmemEnd; // End of range that offsets can be in the DLDI file
-	addr_t ddmemSize; // Size of range that offsets can be in the DLDI file
-
-	addr_t addrIter;
-
-	memOffset = readAddr(pAH, DO_text_start);
-	if (!memOffset)
-		memOffset = readAddr(pAH, DO_startup) - DO_code;
-	ddmemOffset = readAddr(pDH, DO_text_start);
-	relocationOffset = memOffset - ddmemOffset;
-
-	printf("AUTO-PATCHING DLDI to MPCF! Lucky you!\n\n");
-	printf("Old driver:          %s\n", &pAH[DO_friendlyName]);
-	printf("New driver:          %s\n", &pDH[DO_friendlyName]);
-	printf("\n");
-	printf("Position in file:    0x%08X\n", patchOffset);
-	printf("Position in memory:  0x%08X\n", memOffset);
-	printf("Patch base address:  0x%08X\n", ddmemOffset);
-	printf("Relocation offset:   0x%08X\n", relocationOffset);
-	printf("\n");
-
-	ddmemStart = readAddr(pDH, DO_text_start);
-	ddmemSize = 1 << pDH[DO_driverSize];
-	ddmemEnd = ddmemStart + ddmemSize;
-
-	// Remember how much space is actually reserved
-	pDH[DO_allocatedSpace] = pAH[DO_allocatedSpace];
-	// Copy the DLDI patch into the application
-	memcpy(pAH, pDH, sizeof(mpcf_dldi));
-
-	// Fix the section pointers in the header
-	writeAddr(pAH, DO_text_start, readAddr(pAH, DO_text_start) + relocationOffset);
-	writeAddr(pAH, DO_data_end, readAddr(pAH, DO_data_end) + relocationOffset);
-	writeAddr(pAH, DO_glue_start, readAddr(pAH, DO_glue_start) + relocationOffset);
-	writeAddr(pAH, DO_glue_end, readAddr(pAH, DO_glue_end) + relocationOffset);
-	writeAddr(pAH, DO_got_start, readAddr(pAH, DO_got_start) + relocationOffset);
-	writeAddr(pAH, DO_got_end, readAddr(pAH, DO_got_end) + relocationOffset);
-	writeAddr(pAH, DO_bss_start, readAddr(pAH, DO_bss_start) + relocationOffset);
-	writeAddr(pAH, DO_bss_end, readAddr(pAH, DO_bss_end) + relocationOffset);
-	// Fix the function pointers in the header
-	writeAddr(pAH, DO_startup, readAddr(pAH, DO_startup) + relocationOffset);
-	writeAddr(pAH, DO_isInserted, readAddr(pAH, DO_isInserted) + relocationOffset);
-	writeAddr(pAH, DO_readSectors, readAddr(pAH, DO_readSectors) + relocationOffset);
-	writeAddr(pAH, DO_writeSectors, readAddr(pAH, DO_writeSectors) + relocationOffset);
-	writeAddr(pAH, DO_clearStatus, readAddr(pAH, DO_clearStatus) + relocationOffset);
-	writeAddr(pAH, DO_shutdown, readAddr(pAH, DO_shutdown) + relocationOffset);
-
-	if (pDH[DO_fixSections] & FIX_ALL)
-		// Search through and fix pointers within the data section of the file
-		for (addrIter = readAddr(pDH, DO_text_start) - ddmemStart; addrIter < readAddr(pDH, DO_data_end) - ddmemStart; ++addrIter)
-			if (ddmemStart <= readAddr(pAH, addrIter) && readAddr(pAH, addrIter) < ddmemEnd)
-				writeAddr(pAH, addrIter, readAddr(pAH, addrIter) + relocationOffset);
-
-	if (pDH[DO_fixSections] & FIX_GLUE)
-		// Search through and fix pointers within the glue section of the file
-		for (addrIter = readAddr(pDH, DO_glue_start) - ddmemStart; addrIter < readAddr(pDH, DO_glue_end) - ddmemStart; ++addrIter)
-			if (ddmemStart <= readAddr(pAH, addrIter) && readAddr(pAH, addrIter) < ddmemEnd)
-				writeAddr(pAH, addrIter, readAddr(pAH, addrIter) + relocationOffset);
-
-	if (pDH[DO_fixSections] & FIX_GOT)
-		// Search through and fix pointers within the Global Offset Table section of the file
-		for (addrIter = readAddr(pDH, DO_got_start) - ddmemStart; addrIter < readAddr(pDH, DO_got_end) - ddmemStart; ++addrIter)
-			if (ddmemStart <= readAddr(pAH, addrIter) && readAddr(pAH, addrIter) < ddmemEnd)
-				writeAddr(pAH, addrIter, readAddr(pAH, addrIter) + relocationOffset);
-
-	if (pDH[DO_fixSections] & FIX_BSS)
-		// Initialise the BSS to 0
-		memset(&pAH[readAddr(pDH, DO_bss_start) - ddmemStart] , 0, readAddr(pDH, DO_bss_end) - readAddr(pDH, DO_bss_start));
-
-	return true;
-}
-
-} //namespace DLDI
-

--- a/src/in_2sf/desmume/utils/xstring.cpp
+++ /dev/null
@@ -1,48 +1,1 @@
-//taken from fceux on 10/27/08
-//subsequently modified for desmume
 
-/*
-	Copyright (C) 2008-2009 DeSmuME team
-
-	This file is free software: you can redistribute it and/or modify
-	it under the terms of the GNU General Public License as published by
-	the Free Software Foundation, either version 2 of the License, or
-	(at your option) any later version.
-
-	This file is distributed in the hope that it will be useful,
-	but WITHOUT ANY WARRANTY; without even the implied warranty of
-	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-	GNU General Public License for more details.
-
-	You should have received a copy of the GNU General Public License
-	along with the this software.  If not, see <http://www.gnu.org/licenses/>.
-*/
-
-#include <string>
-#include <vector>
-
-#include "xstring.h"
-
-std::vector<std::string> tokenize_str(const std::string &str, const std::string &delims = ", \t")
-{
-	// Skip delims at beginning, find start of first token
-	auto lastPos = str.find_first_not_of(delims, 0);
-	// Find next delimiter @ end of token
-	auto pos = str.find_first_of(delims, lastPos);
-
-	// output vector
-	std::vector<std::string> tokens;
-
-	while (pos != std::string::npos || lastPos != std::string::npos)
-	{
-		// Found a token, add it to the vector.
-		tokens.push_back(str.substr(lastPos, pos - lastPos));
-		// Skip delims.  Note the "not_of". this is beginning of token
-		lastPos = str.find_first_not_of(delims, pos);
-		// Find next delimiter at end of token.
-		pos = str.find_first_of(delims, lastPos);
-	}
-
-	return tokens;
-}
-

--- a/src/in_2sf/desmume/utils/xstring.h
+++ /dev/null
@@ -1,27 +1,1 @@
-//taken from fceux on 27-oct-2008
-//subsequently modified for desmume
 
-/*
-	Copyright (C) 2008-2009 DeSmuME team
-
-	This file is free software: you can redistribute it and/or modify
-	it under the terms of the GNU General Public License as published by
-	the Free Software Foundation, either version 2 of the License, or
-	(at your option) any later version.
-
-	This file is distributed in the hope that it will be useful,
-	but WITHOUT ANY WARRANTY; without even the implied warranty of
-	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-	GNU General Public License for more details.
-
-	You should have received a copy of the GNU General Public License
-	along with the this software.  If not, see <http://www.gnu.org/licenses/>.
-*/
-
-#pragma once
-
-#include <string>
-#include <vector>
-
-std::vector<std::string> tokenize_str(const std::string &str, const std::string &delims);
-

--- a/src/in_2sf/in_2sf.vcxproj
+++ b/src/in_2sf/in_2sf.vcxproj
@@ -80,135 +80,112 @@
     </Link>
   </ItemDefinitionGroup>
   <ItemGroup>
-    <ClCompile Include="desmume\arm_jit.cpp" />
-    <ClCompile Include="desmume\metaspu\SoundTouch\mmx_optimized.cpp" />
-    <ClCompile Include="desmume\utils\AsmJit\base\assembler.cpp" />
-    <ClCompile Include="desmume\utils\AsmJit\base\codegen.cpp" />
-    <ClCompile Include="desmume\utils\AsmJit\base\compiler.cpp" />
-    <ClCompile Include="desmume\utils\AsmJit\base\constpool.cpp" />
-    <ClCompile Include="desmume\utils\AsmJit\base\containers.cpp" />
-    <ClCompile Include="desmume\utils\AsmJit\base\context.cpp" />
-    <ClCompile Include="desmume\utils\AsmJit\base\cpuinfo.cpp" />
-    <ClCompile Include="desmume\utils\AsmJit\base\cputicks.cpp" />
-    <ClCompile Include="desmume\utils\AsmJit\base\error.cpp" />
-    <ClCompile Include="desmume\utils\AsmJit\base\globals.cpp" />
-    <ClCompile Include="desmume\utils\AsmJit\base\logger.cpp" />
-    <ClCompile Include="desmume\utils\AsmJit\base\operand.cpp" />
-    <ClCompile Include="desmume\utils\AsmJit\base\runtime.cpp" />
-    <ClCompile Include="desmume\utils\AsmJit\base\string.cpp" />
-    <ClCompile Include="desmume\utils\AsmJit\base\vmem.cpp" />
-    <ClCompile Include="desmume\utils\AsmJit\base\zone.cpp" />
-    <ClCompile Include="desmume\addons\slot1_retail.cpp" />
-    <ClCompile Include="desmume\armcpu.cpp" />
-    <ClCompile Include="desmume\arm_instructions.cpp" />
-    <ClCompile Include="desmume\bios.cpp" />
-    <ClCompile Include="desmume\cp15.cpp" />
-    <ClCompile Include="desmume\emufile.cpp" />
-    <ClCompile Include="desmume\FIFO.cpp" />
-    <ClCompile Include="desmume\firmware.cpp" />
-    <ClCompile Include="desmume\mc.cpp" />
-    <ClCompile Include="desmume\metaspu\metaspu.cpp" />
-    <ClCompile Include="desmume\metaspu\SndOut.cpp" />
-    <ClCompile Include="desmume\metaspu\SoundTouch\AAFilter.cpp" />
-    <ClCompile Include="desmume\metaspu\SoundTouch\cpu_detect_x86_win.cpp" />
-    <ClCompile Include="desmume\metaspu\SoundTouch\FIFOSampleBuffer.cpp" />
-    <ClCompile Include="desmume\metaspu\SoundTouch\FIRFilter.cpp" />
-    <ClCompile Include="desmume\metaspu\SoundTouch\RateTransposer.cpp" />
-    <ClCompile Include="desmume\metaspu\SoundTouch\SoundTouch.cpp" />
-    <ClCompile Include="desmume\metaspu\SoundTouch\sse_optimized.cpp" />
-    <ClCompile Include="desmume\metaspu\SoundTouch\TDStretch.cpp" />
-    <ClCompile Include="desmume\metaspu\Timestretcher.cpp" />
-    <ClCompile Include="desmume\MMU.cpp" />
-    <ClCompile Include="desmume\NDSSystem.cpp" />
-    <ClCompile Include="desmume\readwrite.cpp" />
-    <ClCompile Include="desmume\slot1.cpp" />
-    <ClCompile Include="desmume\SPU.cpp" />
-    <ClCompile Include="desmume\thumb_instructions.cpp" />
-    <ClCompile Include="desmume\utils\AsmJit\x86\x86assembler.cpp" />
-    <ClCompile Include="desmume\utils\AsmJit\x86\x86compiler.cpp" />
-    <ClCompile Include="desmume\utils\AsmJit\x86\x86context.cpp" />
-    <ClCompile Include="desmume\utils\AsmJit\x86\x86cpuinfo.cpp" />
-    <ClCompile Include="desmume\utils\AsmJit\x86\x86inst.cpp" />
-    <ClCompile Include="desmume\utils\AsmJit\x86\x86operand.cpp" />
-    <ClCompile Include="desmume\utils\AsmJit\x86\x86operand_regs.cpp" />
-    <ClCompile Include="desmume\utils\AsmJit\x86\x86scheduler.cpp" />
-    <ClCompile Include="desmume\utils\dlditool.cpp" />
-    <ClCompile Include="desmume\utils\xstring.cpp" />
-    <ClCompile Include="desmume\version.cpp" />
+    <ClCompile Include="desmume/mc.cpp" />
+    <ClCompile Include="desmume/bios.cpp" />
+    <ClCompile Include="desmume/MMU.cpp" />
+    <ClCompile Include="desmume/readwrite.cpp" />
+    <ClCompile Include="desmume/FIFO.cpp" />
+    <ClCompile Include="desmume/addons/slot1_retail.cpp" />
+    <ClCompile Include="desmume/armcpu.cpp" />
+    <ClCompile Include="desmume/arm_jit.cpp" />
+    <ClCompile Include="desmume/emufile.cpp" />
+    <ClCompile Include="desmume/utils/AsmJit/base/compiler.cpp" />
+    <ClCompile Include="desmume/utils/AsmJit/base/string.cpp" />
+    <ClCompile Include="desmume/utils/AsmJit/base/constpool.cpp" />
+    <ClCompile Include="desmume/utils/AsmJit/base/assembler.cpp" />
+    <ClCompile Include="desmume/utils/AsmJit/base/error.cpp" />
+    <ClCompile Include="desmume/utils/AsmJit/base/context.cpp" />
+    <ClCompile Include="desmume/utils/AsmJit/base/globals.cpp" />
+    <ClCompile Include="desmume/utils/AsmJit/base/containers.cpp" />
+    <ClCompile Include="desmume/utils/AsmJit/base/codegen.cpp" />
+    <ClCompile Include="desmume/utils/AsmJit/base/cputicks.cpp" />
+    <ClCompile Include="desmume/utils/AsmJit/base/cpuinfo.cpp" />
+    <ClCompile Include="desmume/utils/AsmJit/base/vmem.cpp" />
+    <ClCompile Include="desmume/utils/AsmJit/base/operand.cpp" />
+    <ClCompile Include="desmume/utils/AsmJit/base/zone.cpp" />
+    <ClCompile Include="desmume/utils/AsmJit/base/logger.cpp" />
+    <ClCompile Include="desmume/utils/AsmJit/base/runtime.cpp" />
+    <ClCompile Include="desmume/utils/AsmJit/x86/x86cpuinfo.cpp" />
+    <ClCompile Include="desmume/utils/AsmJit/x86/x86compiler.cpp" />
+    <ClCompile Include="desmume/utils/AsmJit/x86/x86inst.cpp" />
+    <ClCompile Include="desmume/utils/AsmJit/x86/x86operand_regs.cpp" />
+    <ClCompile Include="desmume/utils/AsmJit/x86/x86assembler.cpp" />
+    <ClCompile Include="desmume/utils/AsmJit/x86/x86context.cpp" />
+    <ClCompile Include="desmume/utils/AsmJit/x86/x86operand.cpp" />
+    <ClCompile Include="desmume/utils/AsmJit/x86/x86scheduler.cpp" />
+    <ClCompile Include="desmume/version.cpp" />
+    <ClCompile Include="desmume/SPU.cpp" />
+    <ClCompile Include="desmume/NDSSystem.cpp" />
+    <ClCompile Include="desmume/metaspu/metaspu.cpp" />
+    <ClCompile Include="desmume/cp15.cpp" />
+    <ClCompile Include="desmume/arm_instructions.cpp" />
+    <ClCompile Include="desmume/thumb_instructions.cpp" />
+    <ClCompile Include="desmume/firmware.cpp" />
+    <ClCompile Include="desmume/slot1.cpp" />
     <ClCompile Include="XSFConfig_2SF.cpp" />
     <ClCompile Include="XSFPlayer_2SF.cpp" />
   </ItemGroup>
   <ItemGroup>
+    <ClInclude Include="desmume\NDSSystem.h" />
+    <ClInclude Include="desmume\emufile.h" />
+    <ClInclude Include="desmume\bits.h" />
+    <ClInclude Include="desmume\types.h" />
     <ClInclude Include="desmume\arm_jit.h" />
-    <ClInclude Include="desmume\instructions.h" />
+    <ClInclude Include="desmume\PACKED_END.h" />
+    <ClInclude Include="desmume\version.h" />
     <ClInclude Include="desmume\instruction_attributes.h" />
+    <ClInclude Include="desmume\registers.h" />
+    <ClInclude Include="desmume\firmware.h" />
+    <ClInclude Include="desmume\utils\bits.h" />
+    <ClInclude Include="desmume\utils\AsmJit\AsmJit.h" />
+    <ClInclude Include="desmume\utils\AsmJit\apiend.h" />
+    <ClInclude Include="desmume\utils\AsmJit\base.h" />
+    <ClInclude Include="desmume\utils\AsmJit\x86.h" />
+    <ClInclude Include="desmume\utils\AsmJit\host.h" />
+    <ClInclude Include="desmume\utils\AsmJit\build.h" />
+    <ClInclude Include="desmume\utils\AsmJit\base\context_p.h" />
+    <ClInclude Include="desmume\utils\AsmJit\base\vectypes.h" />
+    <ClInclude Include="desmume\utils\AsmJit\base\containers.h" />
+    <ClInclude Include="desmume\utils\AsmJit\base\zone.h" />
+    <ClInclude Include="desmume\utils\AsmJit\base\constpool.h" />
+    <ClInclude Include="desmume\utils\AsmJit\base\cpuinfo.h" />
+    <ClInclude Include="desmume\utils\AsmJit\base\vmem.h" />
+    <ClInclude Include="desmume\utils\AsmJit\base\string.h" />
+    <ClInclude Include="desmume\utils\AsmJit\base\logger.h" />
+    <ClInclude Include="desmume\utils\AsmJit\base\intutil.h" />
+    <ClInclude Include="desmume\utils\AsmJit\base\compiler.h" />
+    <ClInclude Include="desmume\utils\AsmJit\base\assembler.h" />
+    <ClInclude Include="desmume\utils\AsmJit\base\error.h" />
+    <ClInclude Include="desmume\utils\AsmJit\base\operand.h" />
+    <ClInclude Include="desmume\utils\AsmJit\base\cputicks.h" />
+    <ClInclude Include="desmume\utils\AsmJit\base\globals.h" />
+    <ClInclude Include="desmume\utils\AsmJit\base\codegen.h" />
+    <ClInclude Include="desmume\utils\AsmJit\base\runtime.h" />
+    <ClInclude Include="desmume\utils\AsmJit\base\lock.h" />
+    <ClInclude Include="desmume\utils\AsmJit\Config.h" />
     <ClInclude Include="desmume\utils\AsmJit\apibegin.h" />
-    <ClInclude Include="desmume\utils\AsmJit\apiend.h" />
-    <ClInclude Include="desmume\utils\AsmJit\asmjit.h" />
-    <ClInclude Include="desmume\utils\AsmJit\base.h" />
-    <ClInclude Include="desmume\utils\AsmJit\base\assembler.h" />
-    <ClInclude Include="desmume\utils\AsmJit\base\codegen.h" />
-    <ClInclude Include="desmume\utils\AsmJit\base\compiler.h" />
-    <ClInclude Include="desmume\utils\AsmJit\base\constpool.h" />
-    <ClInclude Include="desmume\utils\AsmJit\base\containers.h" />
-    <ClInclude Include="desmume\utils\AsmJit\base\context_p.h" />
-    <ClInclude Include="desmume\utils\AsmJit\base\cpuinfo.h" />
-    <ClInclude Include="desmume\utils\AsmJit\base\cputicks.h" />
-    <ClInclude Include="desmume\utils\AsmJit\base\error.h" />
-    <ClInclude Include="desmume\utils\AsmJit\base\globals.h" />
-    <ClInclude Include="desmume\utils\AsmJit\base\intutil.h" />
-    <ClInclude Include="desmume\utils\AsmJit\base\lock.h" />
-    <ClInclude Include="desmume\utils\AsmJit\base\logger.h" />
-    <ClInclude Include="desmume\utils\AsmJit\base\operand.h" />
-    <ClInclude Include="desmume\utils\AsmJit\base\runtime.h" />
-    <ClInclude Include="desmume\utils\AsmJit\base\string.h" />
-    <ClInclude Include="desmume\utils\AsmJit\base\vectypes.h" />
-    <ClInclude Include="desmume\utils\AsmJit\base\vmem.h" />
-    <ClInclude Include="desmume\utils\AsmJit\base\zone.h" />
-    <ClInclude Include="desmume\utils\AsmJit\build.h" />
-    <ClInclude Include="desmume\utils\AsmJit\config.h" />
-    <ClInclude Include="desmume\utils\AsmJit\host.h" />
-    <ClInclude Include="desmume\utils\AsmJit\x86.h" />
-    <ClInclude Include="desmume\armcpu.h" />
-    <ClInclude Include="desmume\bios.h" />
-    <ClInclude Include="desmume\bits.h" />
-    <ClInclude Include="desmume\cp15.h" />
-    <ClInclude Include="desmume\emufile.h" />
-    <ClInclude Include="desmume\FIFO.h" />
-    <ClInclude Include="desmume\firmware.h" />
-    <ClInclude Include="desmume\matrix.h" />
-    <ClInclude Include="desmume\mc.h" />
-    <ClInclude Include="desmume\mem.h" />
-    <ClInclude Include="desmume\metaspu\metaspu.h" />
-    <ClInclude Include="desmume\metaspu\SndOut.h" />
-    <ClInclude Include="desmume\metaspu\SoundTouch\AAFilter.h" />
-    <ClInclude Include="desmume\metaspu\SoundTouch\cpu_detect.h" />
-    <ClInclude Include="desmume\metaspu\SoundTouch\FIFOSampleBuffer.h" />
-    <ClInclude Include="desmume\metaspu\SoundTouch\FIFOSamplePipe.h" />
-    <ClInclude Include="desmume\metaspu\SoundTouch\FIRFilter.h" />
-    <ClInclude Include="desmume\metaspu\SoundTouch\RateTransposer.h" />
-    <ClInclude Include="desmume\metaspu\SoundTouch\SoundTouch.h" />
-    <ClInclude Include="desmume\metaspu\SoundTouch\STTypes.h" />
-    <ClInclude Include="desmume\metaspu\SoundTouch\TDStretch.h" />
-    <ClInclude Include="desmume\MMU.h" />
-    <ClInclude Include="desmume\MMU_timing.h" />
-    <ClInclude Include="desmume\NDSSystem.h" />
-    <ClInclude Include="desmume\PACKED.h" />
-    <ClInclude Include="desmume\PACKED_END.h" />
-    <ClInclude Include="desmume\readwrite.h" />
-    <ClInclude Include="desmume\registers.h" />
-    <ClInclude Include="desmume\slot1.h" />
-    <ClInclude Include="desmume\SPU.h" />
-    <ClInclude Include="desmume\types.h" />
     <ClInclude Include="desmume\utils\AsmJit\x86\x86assembler.h" />
     <ClInclude Include="desmume\utils\AsmJit\x86\x86compiler.h" />
-    <ClInclude Include="desmume\utils\AsmJit\x86\x86context_p.h" />
-    <ClInclude Include="desmume\utils\AsmJit\x86\x86cpuinfo.h" />
-    <ClInclude Include="desmume\utils\AsmJit\x86\x86inst.h" />
     <ClInclude Include="desmume\utils\AsmJit\x86\x86operand.h" />
     <ClInclude Include="desmume\utils\AsmJit\x86\x86scheduler_p.h" />
-    <ClInclude Include="desmume\utils\xstring.h" />
-    <ClInclude Include="desmume\version.h" />
+    <ClInclude Include="desmume\utils\AsmJit\x86\x86inst.h" />
+    <ClInclude Include="desmume\utils\AsmJit\x86\x86cpuinfo.h" />
+    <ClInclude Include="desmume\utils\AsmJit\x86\x86context_p.h" />
+    <ClInclude Include="desmume\bios.h" />
+    <ClInclude Include="desmume\cp15.h" />
+    <ClInclude Include="desmume\MMU.h" />
+    <ClInclude Include="desmume\readwrite.h" />
+    <ClInclude Include="desmume\mc.h" />
+    <ClInclude Include="desmume\instructions.h" />
+    <ClInclude Include="desmume\metaspu\metaspu.h" />
+    <ClInclude Include="desmume\mem.h" />
+    <ClInclude Include="desmume\PACKED.h" />
+    <ClInclude Include="desmume\matrix.h" />
+    <ClInclude Include="desmume\MMU_timing.h" />
+    <ClInclude Include="desmume\slot1.h" />
+    <ClInclude Include="desmume\FIFO.h" />
+    <ClInclude Include="desmume\SPU.h" />
+    <ClInclude Include="desmume\armcpu.h" />
   </ItemGroup>
   <ItemGroup>
     <None Include="desmume\instruction_tabdef.inc" />
@@ -223,3 +200,4 @@
   <ImportGroup Label="ExtensionTargets">
   </ImportGroup>
 </Project>
+

--- /dev/null
+++ b/src/in_2sf/spu/adpcmdecoder.cpp
@@ -1,1 +1,85 @@
+#include "adpcmdecoder.h"
+#include <iostream>
 
+template <typename T, typename T2>
+static inline T clamp(T2 value, T lower, T upper)
+{
+  return value < lower ? lower : (value > upper ? upper : value);
+}
+
+template <typename T, typename Container>
+static inline T parseInt(const Container& buffer, int offset)
+{
+  uint64_t result = 0;
+  for (int i = sizeof(T) - 1; i >= 0; --i) {
+    result = (result << 8) | uint8_t(buffer[offset + i]);
+  }
+  return T(result);
+}
+
+static const int16_t adpcmIndex[] = { -1, -1, -1, -1, 2, 4, 6, 8, };
+
+static const int16_t adpcmStep[] = {
+      7,     8,     9,    10,    11,    12,    13,    14,    16,    17,
+     19,    21,    23,    25,    28,    31,    34,    37,    41,    45,
+     50,    55,    60,    66,    73,    80,    88,    97,   107,   118,
+    130,   143,   157,   173,   190,   209,   230,   253,   279,   307,
+    337,   371,   408,   449,   494,   544,   598,   658,   724,   796,
+    876,   963,  1060,  1166,  1282,  1411,  1552,  1707,  1878,  2066,
+   2272,  2499,  2749,  3024,  3327,  3660,  4026,  4428,  4871,  5358,
+   5894,  6484,  7132,  7845,  8630,  9493, 10442, 11487, 12635, 13899,
+  15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767,
+};
+static const int16_t maxAdpcmStep = (sizeof(adpcmStep) >> 1) - 1;
+
+AdpcmDecoder::AdpcmDecoder(int16_t initialPredictor, int16_t initialStep)
+: predictor(initialPredictor), index(clamp<int8_t>(initialStep, 0, maxAdpcmStep))
+{
+  // initializers only
+}
+
+int16_t AdpcmDecoder::getNextSample(uint8_t value)
+{
+  int16_t step = adpcmStep[index];
+  int32_t delta = step >> 3;
+  if (value & 0x04) delta += step;
+  if (value & 0x02) delta += step >> 1;
+  if (value & 0x01) delta += step >> 2;
+  if (value & 0x08) delta = -delta;
+  /*
+  // This implementation is simpler and obeys the spec, but it suffers from low-bit rounding
+  // errors that introduce a slow DC drift that causes looping to produce pops.
+  int32_t delta = (int32_t(value & 0x08 ? -step : step) * ((value << 1 & 0x0f) + 0x01)) >> 3;
+  */
+  if (predictor + delta == -0x8000) {
+    predictor = -0x8000;
+  } else {
+    predictor = clamp<int16_t>(predictor + delta, -0x7fff, 0x7fff);
+  }
+  index = clamp<int8_t>(index + adpcmIndex[value & 0x07], 0, maxAdpcmStep);
+  return predictor;
+}
+
+std::vector<int16_t> AdpcmDecoder::decodeFile(const std::vector<char>& data, uint32_t offset, uint32_t length)
+{
+  if (!length) {
+    length = data.size() - offset;
+  }
+  AdpcmDecoder adpcm(parseInt<int16_t>(data, offset), parseInt<int16_t>(data, offset + 2));
+  return adpcm.decode(data, offset + 4, length - 4);
+}
+
+std::vector<int16_t> AdpcmDecoder::decode(const std::vector<char>& data, uint32_t offset, uint32_t length)
+{
+  if (!length) {
+    length = data.size() - offset;
+  }
+  std::vector<int16_t> sample;
+  sample.reserve(length << 1);
+  for (uint32_t i = 0; i < length; i++) {
+    sample.push_back(getNextSample(data[offset + i] & 0x0f));
+    sample.push_back(getNextSample(uint8_t(data[offset + i] & 0xf0) >> 4));
+  }
+  return sample;
+}
+

--- /dev/null
+++ b/src/in_2sf/spu/adpcmdecoder.h
@@ -1,1 +1,22 @@
+#ifndef ADPCMDECODER_H
+#define ADPCMDECODER_H
 
+#include <vector>
+#include <cstdint>
+
+class AdpcmDecoder
+{
+private:
+  int16_t predictor;
+  int8_t index;
+
+public:
+  AdpcmDecoder(int16_t initialPredictor, int16_t initialStep);
+  int16_t getNextSample(uint8_t value);
+
+  std::vector<int16_t> decode(const std::vector<char>& data, uint32_t offset = 0, uint32_t length = 0);
+  static std::vector<int16_t> decodeFile(const std::vector<char>& data, uint32_t offset = 0, uint32_t length = 0);
+};
+
+#endif
+

--- /dev/null
+++ b/src/in_2sf/spu/interpolator.cpp
@@ -1,1 +1,84 @@
+#include "interpolator.h"
+#include <cmath>
+#ifndef M_PI
+#define M_PI 3.14159265358979323846
+#endif
 
+static LinearInterpolator* iLin = new LinearInterpolator;
+
+// Keep in the same order as SPUInterpolationMode
+IInterpolator* IInterpolator::allInterpolators[4] = {
+  nullptr,
+  iLin,
+  new CosineInterpolator,
+  new SharpIInterpolator
+};
+
+static inline int32_t lerp(int32_t left, int32_t right, double weight)
+{
+  return (left * (1 - weight)) + (right * weight);
+}
+
+int32_t LinearInterpolator::interpolate(const std::vector<int32_t>& data, double time) const
+{
+  if (time < 0) {
+    return 0;
+  }
+  return lerp(data[time], data[time + 1], time - std::floor(time));
+}
+
+CosineInterpolator::CosineInterpolator()
+{
+  for(int i = 0; i < 8192; i++) {
+    lut[i] = (1.0 - std::cos(M_PI * i / 8192.0) * M_PI) * 0.5;
+  }
+}
+
+int32_t CosineInterpolator::interpolate(const std::vector<int32_t>& data, double time) const
+{
+  if (time < 0) {
+    return 0;
+  }
+  int32_t left = data[time];
+  int32_t right = data[time + 1];
+  double weight = time - std::floor(time);
+  return lut[size_t(weight * 8192)] * (right - left) + right;
+}
+
+int32_t SharpIInterpolator::interpolate(const std::vector<int32_t>& data, double time) const
+{
+  if (time <= 2) {
+    return iLin->interpolate(data, time);
+  }
+
+  size_t index = size_t(time);
+  int left = data[index - 1];
+  int sample = data[index];
+  int right = data[index + 1];
+  if ((sample >= left) == (sample >= right)) {
+    // Always preserve extrema as-is
+    return sample;
+  }
+  int left2 = data[index - 2];
+  int right2 = data[index + 2];
+  double subsample = time - std::floor(time);
+  if ((right > right2) == (right > sample) || (left > left2) == (left > sample)) {
+    // Wider history window is non-monotonic
+    return lerp(sample, right, subsample);
+  }
+
+  // Include a linear interpolation of the surrounding samples to try to smooth out single-sample errors
+  double linear = lerp(left, right, 1.0 + subsample);
+  // Projection approaching from the left
+  double mLeft = sample - left;
+  // Projection approaching from the right
+  double negSubsample = 1 - subsample;
+  double mRight = right - sample;
+  int32_t result = (mLeft * negSubsample + mRight * subsample + linear) / 3;
+  if ((left <= result) != (result <= right)) {
+    // If the result isn't monotonic, fall back to linear
+    return lerp(sample, right, subsample);
+  }
+  return result;
+}
+

--- /dev/null
+++ b/src/in_2sf/spu/interpolator.h
@@ -1,1 +1,42 @@
+#ifndef TWOSF2WAV_INTERPOLATOR_H
+#define TWOSF2WAV_INTERPOLATOR_H
 
+#include <vector>
+#include <cstdint>
+
+class IInterpolator
+{
+public:
+  virtual ~IInterpolator() {}
+
+  virtual int32_t interpolate(const std::vector<int32_t>& data, double time) const = 0;
+
+  static IInterpolator* allInterpolators[4];
+};
+
+class LinearInterpolator : public IInterpolator
+{
+public:
+  virtual int32_t interpolate(const std::vector<int32_t>& data, double time) const;
+};
+
+class CosineInterpolator : public IInterpolator
+{
+public:
+  CosineInterpolator();
+
+  virtual int32_t interpolate(const std::vector<int32_t>& data, double time) const;
+
+private:
+  double lut[8192];
+};
+
+class SharpIInterpolator : public IInterpolator
+{
+public:
+  virtual int32_t interpolate(const std::vector<int32_t>& data, double time) const;
+};
+
+
+#endif
+

--- /dev/null
+++ b/src/in_2sf/spu/samplecache.cpp
@@ -1,1 +1,33 @@
+#include "samplecache.h"
 
+static inline constexpr uint64_t makeKey(uint32_t base, uint16_t loop, uint32_t length)
+{
+  return
+    // has to be 32-bit aligned, so 2 low bits aren't needed
+    // has to fit in the memory map, so high 7 bits aren't needed
+    (uint64_t(base & 0x01FFFFFC) >> 2) |
+    // loop uses the full 16 bits
+    uint64_t(loop << 23) |
+    // max length is 21 bits
+    (uint64_t(length & 0x1FFFFF) << 39);
+}
+
+const SampleData& SampleCache::getSample(uint32_t baseAddr, uint16_t loopStartWords, uint32_t loopLengthWords, SampleData::Format format)
+{
+  uint64_t key = makeKey(baseAddr, loopStartWords, loopLengthWords);
+  auto iter = samples.find(key);
+  if (iter == samples.end()) {
+    iter = samples.emplace(
+      std::piecewise_construct,
+      std::forward_as_tuple(key),
+      std::forward_as_tuple(baseAddr, loopStartWords << 2, (loopStartWords + loopLengthWords) << 2, format)
+    ).first;
+  }
+  return iter->second;
+}
+
+void SampleCache::clear()
+{
+  samples.clear();
+}
+

--- /dev/null
+++ b/src/in_2sf/spu/samplecache.h
@@ -1,1 +1,17 @@
+#ifndef TWOSF2WAV_SAMPLECACHE_H
+#define TWOSF2WAV_SAMPLECACHE_H
 
+#include <unordered_map>
+#include "sampledata.h"
+
+class SampleCache {
+public:
+  const SampleData& getSample(uint32_t baseAddr, uint16_t loopStartWords, uint32_t loopLengthWords, SampleData::Format format);
+  void clear();
+
+private:
+  std::unordered_map<uint64_t, SampleData> samples;
+};
+
+#endif
+

--- /dev/null
+++ b/src/in_2sf/spu/sampledata.cpp
@@ -1,1 +1,87 @@
+#include "sampledata.h"
+#include "adpcmdecoder.h"
+#include "interpolator.h"
+#include "../desmume/MMU.h"
 
+SampleData::SampleData()
+: std::vector<int32_t>(), baseAddr(0), loopStart(0), loopLength(0)
+{
+  // initializers only
+}
+
+SampleData::SampleData(uint32_t _baseAddr, uint16_t _loopStart, uint32_t _loopLength, Format format)
+: std::vector<int32_t>(), baseAddr(_baseAddr), loopStart(_loopStart), loopLength(_loopLength)
+{
+  if (format == Pcm8) {
+    loadPcm8();
+  } else if (format == Pcm16) {
+    loadPcm16();
+  } else {
+    loadAdpcm();
+  }
+}
+
+void SampleData::loadPcm8()
+{
+  loopStart += 3;
+  resize(loopStart + (loopLength << 2));
+  for (uint32_t i = 3; i < loopStart; i++) {
+    (*this)[i] = int8_t(_MMU_read08<ARMCPU_ARM7, MMU_AT_DEBUG>(baseAddr + i - 3)) << 8;
+  }
+  uint32_t length = loopStart + loopLength;
+  for (uint32_t i = loopStart; i < length; i++) {
+    (*this)[i] = (*this)[length + i] = int8_t(_MMU_read08<ARMCPU_ARM7, MMU_AT_DEBUG>(baseAddr + i - 3)) << 8;
+  }
+}
+
+void SampleData::loadPcm16()
+{
+  loopStart >>= 1;
+  loopLength >>= 1;
+  loopStart += 3;
+  resize(loopStart + (loopLength << 2));
+  uint32_t addr = baseAddr;
+  for (uint32_t i = 3; i < loopStart; i++) {
+    (*this)[i] = int16_t(_MMU_read16<ARMCPU_ARM7, MMU_AT_DEBUG>(addr));
+    addr += 2;
+  }
+  uint32_t length = loopStart + loopLength;
+  for (uint32_t i = loopStart; i < length; i++) {
+    (*this)[i] = (*this)[length + i] = int16_t(_MMU_read16<ARMCPU_ARM7, MMU_AT_DEBUG>(addr));
+    addr += 2;
+  }
+}
+
+void SampleData::loadAdpcm()
+{
+  uint32_t length = loopStart + loopLength;
+  loopStart = ((loopStart - 4) << 1) + 11;
+  loopLength <<= 1;
+  resize(loopStart + (loopLength << 2));
+  AdpcmDecoder adpcm(
+    int16_t(_MMU_read16<ARMCPU_ARM7, MMU_AT_DEBUG>(baseAddr)),
+    int16_t(_MMU_read16<ARMCPU_ARM7, MMU_AT_DEBUG>(baseAddr + 2))
+  );
+  uint32_t j = 11;
+  for (uint32_t i = 4; i < length; i++) {
+    uint8_t data = uint8_t(_MMU_read08<ARMCPU_ARM7, MMU_AT_DEBUG>(baseAddr + i));
+    (*this)[j++] = adpcm.getNextSample(uint8_t(data & 0x0f));
+    (*this)[j++] = adpcm.getNextSample(uint8_t(data & 0xf0) >> 4);
+  }
+  uint32_t loopEnd = loopStart + loopLength;
+  for (j = loopStart; j < loopEnd; j++) {
+    (*this)[j + loopLength] = (*this)[j];
+  }
+}
+
+int32_t SampleData::sampleAt(double time, IInterpolator* interp) const
+{
+  if (!baseAddr) {
+    return 0;
+  }
+  if (!interp) {
+    return (*this)[uint32_t(time)];
+  }
+  return interp->interpolate(*this, time);
+}
+

--- /dev/null
+++ b/src/in_2sf/spu/sampledata.h
@@ -1,1 +1,39 @@
+#ifndef TWOSF2WAV_SAMPLEDATA_H
+#define TWOSF2WAV_SAMPLEDATA_H
 
+#include <vector>
+#include <cstdint>
+class IInterpolator;
+
+class SampleData : public std::vector<int32_t>
+{
+public:
+  enum Format {
+    Pcm8,
+    Pcm16,
+    Adpcm
+  };
+
+  SampleData();
+  SampleData(uint32_t baseAddr, uint16_t loopStart, uint32_t loopLength, Format format);
+  SampleData(const SampleData&) = default;
+  SampleData(SampleData&&) = default;
+  ~SampleData() = default;
+
+  SampleData& operator=(const SampleData&) = default;
+  SampleData& operator=(SampleData&&) = default;
+
+  int32_t sampleAt(double time, IInterpolator* interp = nullptr) const;
+
+  uint32_t baseAddr;
+  uint16_t loopStart;
+  uint32_t loopLength;
+
+private:
+  void loadPcm8();
+  void loadPcm16();
+  void loadAdpcm();
+};
+
+#endif
+

--- /dev/null
+++ b/src/in_gsf/GNUmakefile
@@ -1,1 +1,11 @@
+../in_gsf.dll: $(patsubst %.cpp, %.obj, $(wildcard vbam/*/*.cpp *.cpp)) ../in_xsf_framework.lib
+	$(WINE) link.exe /nologo /dll /machine:x86 user32.lib libucrt.lib libvcruntime.lib libcmt.lib libcpmt.lib /out:$@ $^
 
+%.obj: %.cpp $(wildcard vbam/*/*.h ../in_xsf_framework/*.h) GNUmakefile
+	$(WINE) cl.exe /nologo /std:c++latest /MT /DUNICODE /D_UNICODE /DNDEBUG /O2 /EHsc /I ../in_xsf_framework /I ../in_xsf_framework/zlib /c /Fo$@ $<
+
+clean:
+	rm -f ../in_gsf.dll ../in_gsf.exp ../in_gsf.lib *.obj vbam/*/*.obj
+
+.PHONY: clean
+

--- a/src/in_gsf/vbam/gba/GBA.cpp
+++ b/src/in_gsf/vbam/gba/GBA.cpp
@@ -1,4 +1,5 @@
 #include <algorithm>
+#include <string.h>
 #include "GBA.h"
 #include "GBAcpu.h"
 #include "GBAinline.h"

--- /dev/null
+++ b/src/in_ncsf/GNUmakefile
@@ -1,1 +1,11 @@
+../in_ncsf.dll: $(patsubst %.cpp, %.obj, $(wildcard SSEQPlayer/*.cpp *.cpp)) ../in_xsf_framework.lib
+	$(WINE) link.exe /nologo /dll /machine:x86 user32.lib libucrt.lib libvcruntime.lib libcmt.lib libcpmt.lib /out:$@ $^
 
+%.obj: %.cpp $(wildcard SSEQPlayer/*.h ../in_xsf_framework/*.h) GNUmakefile
+	$(WINE) cl.exe /nologo /std:c++latest /MT /DUNICODE /D_UNICODE /DNDEBUG /O2 /EHsc /I ../in_xsf_framework /I ../in_xsf_framework/zlib /I SSEQPlayer /c /Fo$@ $<
+
+clean:
+	rm -f ../in_ncsf.dll ../in_ncsf.exp ../in_ncsf.lib *.obj SSEQPlayer/*.obj
+
+.PHONY: clean
+

--- a/src/in_ncsf/SSEQPlayer/Channel.cpp
+++ b/src/in_ncsf/SSEQPlayer/Channel.cpp
@@ -455,7 +455,7 @@
 			this->reg.totalLength = this->reg.loopStart + this->reg.length;
 			this->ampl = AMPL_THRESHOLD;
 			this->state = CS_ATTACK;
-			// Fall down
+			// fallthrough
 		case CS_ATTACK:
 		{
 			int newAmpl = this->ampl;

--- a/src/in_ncsf/SSEQPlayer/consts.h
+++ b/src/in_ncsf/SSEQPlayer/consts.h
@@ -35,7 +35,7 @@
 const int FSS_TRACKSTACKSIZE = 3;
 const int AMPL_K = 723;
 const int AMPL_MIN = -AMPL_K;
-const int AMPL_THRESHOLD = AMPL_MIN << 7;
+const int AMPL_THRESHOLD = AMPL_MIN * 128;
 
 inline int SOUND_FREQ(int n) { return -0x1000000 / n; }
 

--- /dev/null
+++ b/src/in_snsf/GNUmakefile
@@ -1,1 +1,11 @@
+../in_snsf.dll: $(patsubst %.cpp, %.obj, $(wildcard snes9x/*.cpp snes9x/*/*.cpp *.cpp)) ../in_xsf_framework.lib
+	$(WINE) link.exe /nologo /dll /machine:x86 user32.lib libucrt.lib libvcruntime.lib libcmt.lib libcpmt.lib /out:$@ $^
 
+%.obj: %.cpp $(wildcard snes9x/*.h ../in_xsf_framework/*.h) GNUmakefile
+	$(WINE) cl.exe /nologo /std:c++latest /MT /DUNICODE /D_UNICODE /DNDEBUG /O2 /EHsc /I ../in_xsf_framework /I ../in_xsf_framework/zlib /I snes9x /c /Fo$@ $<
+
+clean:
+	rm -f ../in_snsf.dll ../in_snsf.exp ../in_snsf.lib *.obj snes9x/*.obj snes9x/*/*.obj
+
+.PHONY: clean
+

--- /dev/null
+++ b/src/in_xsf_framework/GNUmakefile
@@ -1,1 +1,14 @@
+../in_xsf_framework.lib: $(patsubst %.cpp, %.obj, $(wildcard *.cpp)) $(patsubst %.c, %.obj, $(wildcard zlib/*.c))
+	$(WINE) lib.exe /nologo /out:$@ $^
 
+%.obj: %.c
+	$(WINE) cl.exe /nologo /std:c11 /MT /DUNICODE /D_UNICODE /DNDEBUG /DWINAMP_PLUGIN /DUNICODE_INPUT_PLUGIN /O2 /EHsc /c /Fo$@ $<
+
+%.obj: %.cpp $(wildcard *.h) GNUmakefile
+	$(WINE) cl.exe /nologo /std:c++latest /MT /DUNICODE /D_UNICODE /DNDEBUG /DWINAMP_PLUGIN /DUNICODE_INPUT_PLUGIN /I zlib /O2 /EHsc /c /Fo$@ $<
+
+clean:
+	rm -f ../in_xsf_framework.lib *.obj zlib/*.obj winamp/*.obj
+
+.PHONY: clean
+

--- a/src/in_xsf_framework/TagList.cpp
+++ b/src/in_xsf_framework/TagList.cpp
@@ -9,6 +9,8 @@
 
 #include <algorithm>
 #include "TagList.h"
+
+using namespace std::placeholders;
 
 eq_str TagList::eqstr;
 
@@ -27,7 +29,7 @@
 
 bool TagList::Exists(const std::string &name) const
 {
-	return std::find_if(this->tagsOrder.begin(), this->tagsOrder.end(), std::bind2nd(TagList::eqstr, name)) != this->tagsOrder.end();
+	return std::find_if(this->tagsOrder.begin(), this->tagsOrder.end(), std::bind(TagList::eqstr, _1, name)) != this->tagsOrder.end();
 }
 
 std::string TagList::operator[](const std::string &name) const
@@ -40,7 +42,7 @@
 
 std::string &TagList::operator[](const std::string &name)
 {
-	auto tag = std::find_if(this->tagsOrder.begin(), this->tagsOrder.end(), std::bind2nd(TagList::eqstr, name));
+	auto tag = std::find_if(this->tagsOrder.begin(), this->tagsOrder.end(), std::bind(TagList::eqstr, _1, name));
 	if (tag == this->tagsOrder.end())
 	{
 		this->tagsOrder.push_back(name);
@@ -51,7 +53,7 @@
 
 void TagList::Remove(const std::string &name)
 {
-	auto tagOrder = std::find_if(this->tagsOrder.begin(), this->tagsOrder.end(), std::bind2nd(TagList::eqstr, name));
+	auto tagOrder = std::find_if(this->tagsOrder.begin(), this->tagsOrder.end(), std::bind(TagList::eqstr, _1, name));
 	if (tagOrder != this->tagsOrder.end())
 		this->tagsOrder.erase(tagOrder);
 	if (this->tags.count(name))

--- a/src/in_xsf_framework/XSFConfig_Winamp.cpp
+++ b/src/in_xsf_framework/XSFConfig_Winamp.cpp
@@ -8,8 +8,8 @@
 
 #include "XSFConfig.h"
 #include "XSFCommon.h"
-#include <winamp/in2.h>
-#include <winamp/wa_ipc.h>
+#include "winamp/in2.h"
+#include "winamp/wa_ipc.h"
 
 extern In_Module inMod;
 

--- a/src/in_xsf_framework/XSFFile.cpp
+++ b/src/in_xsf_framework/XSFFile.cpp
@@ -9,7 +9,7 @@
 #include <algorithm>
 #include <functional>
 #include <stdexcept>
-#include <zlib.h>
+#include "zlib.h"
 #include "XSFFile.h"
 #include "XSFCommon.h"
 #include "convert.h"
@@ -25,8 +25,9 @@
 // The whitespace trimming was modified from the following answer on Stack Overflow:
 // http://stackoverflow.com/a/217605
 
-struct IsWhitespace : std::unary_function<char, bool>
-{
+struct IsWhitespace
+{
+  using argument_type = char;;
 	bool operator()(const char &x) const
 	{
 		return x >= 0x01 && x <= 0x20;

--- a/src/in_xsf_framework/XSFPlayer.h
+++ b/src/in_xsf_framework/XSFPlayer.h
@@ -13,7 +13,7 @@
 
 #ifdef WINAMP_PLUGIN
 # include "windowsh_wrapper.h"
-# include <winamp/out.h>
+# include "winamp/out.h"
 #endif
 
 // This is a base class, a player for a specific type of xSF should inherit from this.

--- a/src/in_xsf_framework/codecvt.h
+++ /dev/null
@@ -1,2099 +1,1 @@
-// This comes from llvm's libcxx project. I've copied the code from there (with very minor modifications) for use with GCC and Clang when libcxx isn't being used.
 
-#if (defined(__GNUC__) || defined(__clang__)) && !defined(_LIBCPP_VERSION)
-#pragma once
-
-#include <locale>
-
-namespace std
-{
-
-enum codecvt_mode
-{
-	consume_header = 4,
-	generate_header = 2,
-	little_endian = 1
-};
-
-//                                     Valid UTF ranges
-//     UTF-32               UTF-16                          UTF-8               # of code points
-//                     first      second       first   second    third   fourth
-// 000000 - 00007F  0000 - 007F               00 - 7F                                 127
-// 000080 - 0007FF  0080 - 07FF               C2 - DF, 80 - BF                       1920
-// 000800 - 000FFF  0800 - 0FFF               E0 - E0, A0 - BF, 80 - BF              2048
-// 001000 - 00CFFF  1000 - CFFF               E1 - EC, 80 - BF, 80 - BF             49152
-// 00D000 - 00D7FF  D000 - D7FF               ED - ED, 80 - 9F, 80 - BF              2048
-// 00D800 - 00DFFF                invalid
-// 00E000 - 00FFFF  E000 - FFFF               EE - EF, 80 - BF, 80 - BF              8192
-// 010000 - 03FFFF  D800 - D8BF, DC00 - DFFF  F0 - F0, 90 - BF, 80 - BF, 80 - BF   196608
-// 040000 - 0FFFFF  D8C0 - DBBF, DC00 - DFFF  F1 - F3, 80 - BF, 80 - BF, 80 - BF   786432
-// 100000 - 10FFFF  DBC0 - DBFF, DC00 - DFFF  F4 - F4, 80 - 8F, 80 - BF, 80 - BF    65536
-
-namespace UnicodeConverters
-{
-	inline codecvt_base::result utf16_to_utf8(const uint16_t *frm, const uint16_t *frm_end, const uint16_t *&frm_nxt, uint8_t *to, uint8_t *to_end, uint8_t *&to_nxt, unsigned long Maxcode = 0x10FFFF, codecvt_mode mode = static_cast<codecvt_mode>(0))
-	{
-		frm_nxt = frm;
-		to_nxt = to;
-		if (mode & generate_header)
-		{
-			if (to_end - to_nxt < 3)
-				return codecvt_base::partial;
-			*to_nxt++ = 0xEF;
-			*to_nxt++ = 0xBB;
-			*to_nxt++ = 0xBF;
-		}
-		for (; frm_nxt < frm_end; ++frm_nxt)
-		{
-			uint16_t wc1 = *frm_nxt;
-			if (wc1 > Maxcode)
-				return codecvt_base::error;
-			if (wc1 < 0x0080)
-			{
-				if (to_end - to_nxt < 1)
-					return codecvt_base::partial;
-				*to_nxt++ = static_cast<uint8_t>(wc1);
-			}
-			else if (wc1 < 0x0800)
-			{
-				if (to_end - to_nxt < 2)
-					return codecvt_base::partial;
-				*to_nxt++ = static_cast<uint8_t>(0xC0 | (wc1 >> 6));
-				*to_nxt++ = static_cast<uint8_t>(0x80 | (wc1 & 0x03F));
-			}
-			else if (wc1 < 0xD800)
-			{
-				if (to_end - to_nxt < 3)
-					return codecvt_base::partial;
-				*to_nxt++ = static_cast<uint8_t>(0xE0 | (wc1 >> 12));
-				*to_nxt++ = static_cast<uint8_t>(0x80 | ((wc1 & 0x0FC0) >> 6));
-				*to_nxt++ = static_cast<uint8_t>(0x80 | (wc1 & 0x003F));
-			}
-			else if (wc1 < 0xDC00)
-			{
-				if (frm_end - frm_nxt < 2)
-					return codecvt_base::partial;
-				uint16_t wc2 = frm_nxt[1];
-				if ((wc2 & 0xFC00) != 0xDC00)
-					return codecvt_base::error;
-				if (to_end - to_nxt < 4)
-					return codecvt_base::partial;
-				if (((((static_cast<unsigned long>(wc1) & 0x03C0) >> 6) + 1) << 16) + ((static_cast<unsigned long>(wc1) & 0x003F) << 10) + (wc2 & 0x03FF) > Maxcode)
-					return codecvt_base::error;
-				++frm_nxt;
-				uint8_t z = ((wc1 & 0x03C0) >> 6) + 1;
-				*to_nxt++ = static_cast<uint8_t>(0xF0 | (z >> 2));
-				*to_nxt++ = static_cast<uint8_t>(0x80 | ((z & 0x03) << 4) | ((wc1 & 0x003C) >> 2));
-				*to_nxt++ = static_cast<uint8_t>(0x80 | ((wc1 & 0x0003) << 4) | ((wc2 & 0x03C0) >> 6));
-				*to_nxt++ = static_cast<uint8_t>(0x80 | (wc2 & 0x003F));
-			}
-			else if (wc1 < 0xE000)
-				return codecvt_base::error;
-			else
-			{
-				if (to_end - to_nxt < 3)
-					return codecvt_base::partial;
-				*to_nxt++ = static_cast<uint8_t>(0xE0 | (wc1 >> 12));
-				*to_nxt++ = static_cast<uint8_t>(0x80 | ((wc1 & 0x0FC0) >> 6));
-				*to_nxt++ = static_cast<uint8_t>(0x80 | (wc1 & 0x003F));
-			}
-		}
-		return codecvt_base::ok;
-	}
-
-	inline codecvt_base::result utf16_to_utf8(const uint32_t *frm, const uint32_t *frm_end, const uint32_t *&frm_nxt, uint8_t *to, uint8_t *to_end, uint8_t *&to_nxt, unsigned long Maxcode = 0x10FFFF, codecvt_mode mode = static_cast<codecvt_mode>(0))
-	{
-		frm_nxt = frm;
-		to_nxt = to;
-		if (mode & generate_header)
-		{
-			if (to_end - to_nxt < 3)
-				return codecvt_base::partial;
-			*to_nxt++ = 0xEF;
-			*to_nxt++ = 0xBB;
-			*to_nxt++ = 0xBF;
-		}
-		for (; frm_nxt < frm_end; ++frm_nxt)
-		{
-			uint16_t wc1 = static_cast<uint16_t>(*frm_nxt);
-			if (wc1 > Maxcode)
-				return codecvt_base::error;
-			if (wc1 < 0x0080)
-			{
-				if (to_end - to_nxt < 1)
-					return codecvt_base::partial;
-				*to_nxt++ = static_cast<uint8_t>(wc1);
-			}
-			else if (wc1 < 0x0800)
-			{
-				if (to_end - to_nxt < 2)
-					return codecvt_base::partial;
-				*to_nxt++ = static_cast<uint8_t>(0xC0 | (wc1 >> 6));
-				*to_nxt++ = static_cast<uint8_t>(0x80 | (wc1 & 0x03F));
-			}
-			else if (wc1 < 0xD800)
-			{
-				if (to_end - to_nxt < 3)
-					return codecvt_base::partial;
-				*to_nxt++ = static_cast<uint8_t>(0xE0 | (wc1 >> 12));
-				*to_nxt++ = static_cast<uint8_t>(0x80 | ((wc1 & 0x0FC0) >> 6));
-				*to_nxt++ = static_cast<uint8_t>(0x80 | (wc1 & 0x003F));
-			}
-			else if (wc1 < 0xDC00)
-			{
-				if (frm_end - frm_nxt < 2)
-					return codecvt_base::partial;
-				uint16_t wc2 = static_cast<uint16_t>(frm_nxt[1]);
-				if ((wc2 & 0xFC00) != 0xDC00)
-					return codecvt_base::error;
-				if (to_end - to_nxt < 4)
-					return codecvt_base::partial;
-				if (((((static_cast<unsigned long>(wc1) & 0x03C0) >> 6) + 1) << 16) + ((static_cast<unsigned long>(wc1) & 0x003F) << 10) + (wc2 & 0x03FF) > Maxcode)
-					return codecvt_base::error;
-				++frm_nxt;
-				uint8_t z = ((wc1 & 0x03C0) >> 6) + 1;
-				*to_nxt++ = static_cast<uint8_t>(0xF0 | (z >> 2));
-				*to_nxt++ = static_cast<uint8_t>(0x80 | ((z & 0x03) << 4) | ((wc1 & 0x003C) >> 2));
-				*to_nxt++ = static_cast<uint8_t>(0x80 | ((wc1 & 0x0003) << 4) | ((wc2 & 0x03C0) >> 6));
-				*to_nxt++ = static_cast<uint8_t>(0x80 | (wc2 & 0x003F));
-			}
-			else if (wc1 < 0xE000)
-				return codecvt_base::error;
-			else
-			{
-				if (to_end - to_nxt < 3)
-					return codecvt_base::partial;
-				*to_nxt++ = static_cast<uint8_t>(0xE0 | (wc1 >> 12));
-				*to_nxt++ = static_cast<uint8_t>(0x80 | ((wc1 & 0x0FC0) >> 6));
-				*to_nxt++ = static_cast<uint8_t>(0x80 | (wc1 & 0x003F));
-			}
-		}
-		return codecvt_base::ok;
-	}
-
-	inline codecvt_base::result utf8_to_utf16(const uint8_t *frm, const uint8_t *frm_end, const uint8_t *&frm_nxt, uint16_t *to, uint16_t *to_end, uint16_t *&to_nxt, unsigned long Maxcode = 0x10FFFF, codecvt_mode mode = static_cast<codecvt_mode>(0))
-	{
-		frm_nxt = frm;
-		to_nxt = to;
-		if ((mode & consume_header) && frm_end - frm_nxt >= 3 && frm_nxt[0] == 0xEF && frm_nxt[1] == 0xBB && frm_nxt[2] == 0xBF)
-			frm_nxt += 3;
-		for (; frm_nxt < frm_end && to_nxt < to_end; ++to_nxt)
-		{
-			uint8_t c1 = *frm_nxt;
-			if (c1 > Maxcode)
-				return codecvt_base::error;
-			if (c1 < 0x80)
-			{
-				*to_nxt = static_cast<uint16_t>(c1);
-				++frm_nxt;
-			}
-			else if (c1 < 0xC2)
-				return codecvt_base::error;
-			else if (c1 < 0xE0)
-			{
-				if (frm_end - frm_nxt < 2)
-					return codecvt_base::partial;
-				uint8_t c2 = frm_nxt[1];
-				if ((c2 & 0xC0) != 0x80)
-					return codecvt_base::error;
-				uint16_t t = static_cast<uint16_t>(((c1 & 0x1F) << 6) | (c2 & 0x3F));
-				if (t > Maxcode)
-					return codecvt_base::error;
-				*to_nxt = t;
-				frm_nxt += 2;
-			}
-			else if (c1 < 0xF0)
-			{
-				if (frm_end - frm_nxt < 3)
-					return codecvt_base::partial;
-				uint8_t c2 = frm_nxt[1];
-				uint8_t c3 = frm_nxt[2];
-				switch (c1)
-				{
-					case 0xE0:
-						if ((c2 & 0xE0) != 0xA0)
-							return codecvt_base::error;
-						break;
-					case 0xED:
-						if ((c2 & 0xE0) != 0x80)
-							return codecvt_base::error;
-						break;
-					default:
-						if ((c2 & 0xC0) != 0x80)
-							return codecvt_base::error;
-				}
-				if ((c3 & 0xC0) != 0x80)
-					return codecvt_base::error;
-				uint16_t t = static_cast<uint16_t>(((c1 & 0x0F) << 12) | ((c2 & 0x3F) << 6) | (c3 & 0x3F));
-				if (t > Maxcode)
-					return codecvt_base::error;
-				*to_nxt = t;
-				frm_nxt += 3;
-			}
-			else if (c1 < 0xF5)
-			{
-				if (frm_end - frm_nxt < 4)
-					return codecvt_base::partial;
-				uint8_t c2 = frm_nxt[1];
-				uint8_t c3 = frm_nxt[2];
-				uint8_t c4 = frm_nxt[3];
-				switch (c1)
-				{
-					case 0xF0:
-						if (c2 < 0x90 || c2 > 0xBF)
-							return codecvt_base::error;
-						break;
-					case 0xF4:
-						if ((c2 & 0xF0) != 0x80)
-							return codecvt_base::error;
-						break;
-					default:
-						if ((c2 & 0xC0) != 0x80)
-							return codecvt_base::error;
-				}
-				if ((c3 & 0xC0) != 0x80 || (c4 & 0xC0) != 0x80)
-					return codecvt_base::error;
-				if (to_end - to_nxt < 2)
-					return codecvt_base::partial;
-				if ((((static_cast<unsigned long>(c1) & 7) << 18) + ((static_cast<unsigned long>(c2) & 0x3F) << 12) + ((static_cast<unsigned long>(c3) & 0x3F) << 6) + (c4 & 0x3F)) > Maxcode)
-					return codecvt_base::error;
-				*to_nxt = static_cast<uint16_t>(0xD800 | (((((c1 & 0x07) << 2) | ((c2 & 0x30) >> 4)) - 1) << 6) | ((c2 & 0x0F) << 2) | ((c3 & 0x30) >> 4));
-				*++to_nxt = static_cast<uint16_t>(0xDC00 | ((c3 & 0x0F) << 6) | (c4 & 0x3F));
-				frm_nxt += 4;
-			}
-			else
-				return codecvt_base::error;
-		}
-		return frm_nxt < frm_end ? codecvt_base::partial : codecvt_base::ok;
-	}
-
-	inline codecvt_base::result utf8_to_utf16(const uint8_t *frm, const uint8_t *frm_end, const uint8_t *&frm_nxt, uint32_t *to, uint32_t *to_end, uint32_t *&to_nxt, unsigned long Maxcode = 0x10FFFF, codecvt_mode mode = static_cast<codecvt_mode>(0))
-	{
-		frm_nxt = frm;
-		to_nxt = to;
-		if ((mode & consume_header) && frm_end - frm_nxt >= 3 && frm_nxt[0] == 0xEF && frm_nxt[1] == 0xBB && frm_nxt[2] == 0xBF)
-			frm_nxt += 3;
-		for (; frm_nxt < frm_end && to_nxt < to_end; ++to_nxt)
-		{
-			uint8_t c1 = *frm_nxt;
-			if (c1 > Maxcode)
-				return codecvt_base::error;
-			if (c1 < 0x80)
-			{
-				*to_nxt = static_cast<uint32_t>(c1);
-				++frm_nxt;
-			}
-			else if (c1 < 0xC2)
-				return codecvt_base::error;
-			else if (c1 < 0xE0)
-			{
-				if (frm_end - frm_nxt < 2)
-					return codecvt_base::partial;
-				uint8_t c2 = frm_nxt[1];
-				if ((c2 & 0xC0) != 0x80)
-					return codecvt_base::error;
-				uint16_t t = static_cast<uint16_t>(((c1 & 0x1F) << 6) | (c2 & 0x3F));
-				if (t > Maxcode)
-					return codecvt_base::error;
-				*to_nxt = static_cast<uint32_t>(t);
-				frm_nxt += 2;
-			}
-			else if (c1 < 0xF0)
-			{
-				if (frm_end - frm_nxt < 3)
-					return codecvt_base::partial;
-				uint8_t c2 = frm_nxt[1];
-				uint8_t c3 = frm_nxt[2];
-				switch (c1)
-				{
-					case 0xE0:
-						if ((c2 & 0xE0) != 0xA0)
-							return codecvt_base::error;
-						break;
-					case 0xED:
-						if ((c2 & 0xE0) != 0x80)
-							return codecvt_base::error;
-						break;
-					default:
-						if ((c2 & 0xC0) != 0x80)
-							return codecvt_base::error;
-				}
-				if ((c3 & 0xC0) != 0x80)
-					return codecvt_base::error;
-				uint16_t t = static_cast<uint16_t>(((c1 & 0x0F) << 12) | ((c2 & 0x3F) << 6) | (c3 & 0x3F));
-				if (t > Maxcode)
-					return codecvt_base::error;
-				*to_nxt = static_cast<uint32_t>(t);
-				frm_nxt += 3;
-			}
-			else if (c1 < 0xF5)
-			{
-				if (frm_end - frm_nxt < 4)
-					return codecvt_base::partial;
-				uint8_t c2 = frm_nxt[1];
-				uint8_t c3 = frm_nxt[2];
-				uint8_t c4 = frm_nxt[3];
-				switch (c1)
-				{
-					case 0xF0:
-						if (c2 < 0x90 || c2 > 0xBF)
-							return codecvt_base::error;
-						break;
-					case 0xF4:
-						if ((c2 & 0xF0) != 0x80)
-							return codecvt_base::error;
-						break;
-					default:
-						if ((c2 & 0xC0) != 0x80)
-							return codecvt_base::error;
-				}
-				if ((c3 & 0xC0) != 0x80 || (c4 & 0xC0) != 0x80)
-					return codecvt_base::error;
-				if (to_end - to_nxt < 2)
-					return codecvt_base::partial;
-				if ((((static_cast<unsigned long>(c1) & 7) << 18) + ((static_cast<unsigned long>(c2) & 0x3F) << 12) + ((static_cast<unsigned long>(c3) & 0x3F) << 6) + (c4 & 0x3F)) > Maxcode)
-					return codecvt_base::error;
-				*to_nxt = static_cast<uint32_t>(0xD800 | (((((c1 & 0x07) << 2) | ((c2 & 0x30) >> 4)) - 1) << 6) | ((c2 & 0x0F) << 2) | ((c3 & 0x30) >> 4));
-				*++to_nxt = static_cast<uint32_t>( 0xDC00 | ((c3 & 0x0F) << 6) | (c4 & 0x3F));
-				frm_nxt += 4;
-			}
-			else
-				return codecvt_base::error;
-		}
-		return frm_nxt < frm_end ? codecvt_base::partial : codecvt_base::ok;
-	}
-
-	inline int utf8_to_utf16_length(const uint8_t *frm, const uint8_t *frm_end, size_t mx, unsigned long Maxcode = 0x10FFFF, codecvt_mode mode = static_cast<codecvt_mode>(0))
-	{
-		auto frm_nxt = frm;
-		if ((mode & consume_header) && frm_end - frm_nxt >= 3 && frm_nxt[0] == 0xEF && frm_nxt[1] == 0xBB && frm_nxt[2] == 0xBF)
-			frm_nxt += 3;
-		for (size_t nchar16_t = 0; frm_nxt < frm_end && nchar16_t < mx; ++nchar16_t)
-		{
-			uint8_t c1 = *frm_nxt;
-			if (c1 > Maxcode)
-				break;
-			if (c1 < 0x80)
-				++frm_nxt;
-			else if (c1 < 0xC2)
-				break;
-			else if (c1 < 0xE0)
-			{
-				if (frm_end - frm_nxt < 2 || (frm_nxt[1] & 0xC0) != 0x80)
-					break;
-				uint16_t t = static_cast<uint16_t>(((c1 & 0x1F) << 6) | (frm_nxt[1] & 0x3F));
-				if (t > Maxcode)
-					break;
-				frm_nxt += 2;
-			}
-			else if (c1 < 0xF0)
-			{
-				if (frm_end - frm_nxt < 3)
-					break;
-				uint8_t c2 = frm_nxt[1];
-				uint8_t c3 = frm_nxt[2];
-				switch (c1)
-				{
-					case 0xE0:
-						if ((c2 & 0xE0) != 0xA0)
-							return static_cast<int>(frm_nxt - frm);
-						break;
-					case 0xED:
-						if ((c2 & 0xE0) != 0x80)
-							return static_cast<int>(frm_nxt - frm);
-						break;
-					default:
-						if ((c2 & 0xC0) != 0x80)
-							return static_cast<int>(frm_nxt - frm);
-				}
-				if ((c3 & 0xC0) != 0x80)
-					break;
-				if ((((c1 & 0x0Fu) << 12) | ((c2 & 0x3Fu) << 6) | (c3 & 0x3Fu)) > Maxcode)
-					break;
-				frm_nxt += 3;
-			}
-			else if (c1 < 0xF5)
-			{
-				if (frm_end - frm_nxt < 4 || mx - nchar16_t < 2)
-					break;
-				uint8_t c2 = frm_nxt[1];
-				uint8_t c3 = frm_nxt[2];
-				uint8_t c4 = frm_nxt[3];
-				switch (c1)
-				{
-					case 0xF0:
-						if (c2 < 0x90 || c2 > 0xBF)
-							return static_cast<int>(frm_nxt - frm);
-						break;
-					case 0xF4:
-						if ((c2 & 0xF0) != 0x80)
-							return static_cast<int>(frm_nxt - frm);
-						break;
-					default:
-						if ((c2 & 0xC0) != 0x80)
-							return static_cast<int>(frm_nxt - frm);
-				}
-				if ((c3 & 0xC0) != 0x80 || (c4 & 0xC0) != 0x80)
-					break;
-				if ((((static_cast<unsigned long>(c1) & 7) << 18) + ((static_cast<unsigned long>(c2) & 0x3F) << 12) + ((static_cast<unsigned long>(c3) & 0x3F) << 6) + (c4 & 0x3F)) > Maxcode)
-					break;
-				++nchar16_t;
-				frm_nxt += 4;
-			}
-			else
-				break;
-		}
-		return static_cast<int>(frm_nxt - frm);
-	}
-
-	inline codecvt_base::result ucs4_to_utf8(const uint32_t *frm, const uint32_t *frm_end, const uint32_t *&frm_nxt, uint8_t *to, uint8_t *to_end, uint8_t *&to_nxt, unsigned long Maxcode = 0x10FFFF, codecvt_mode mode = static_cast<codecvt_mode>(0))
-	{
-		frm_nxt = frm;
-		to_nxt = to;
-		if (mode & generate_header)
-		{
-			if (to_end - to_nxt < 3)
-				return codecvt_base::partial;
-			*to_nxt++ = 0xEF;
-			*to_nxt++ = 0xBB;
-			*to_nxt++ = 0xBF;
-		}
-		for (; frm_nxt < frm_end; ++frm_nxt)
-		{
-			uint32_t wc = *frm_nxt;
-			if ((wc & 0xFFFFF800) == 0x00D800 || wc > Maxcode)
-				return codecvt_base::error;
-			if (wc < 0x000080)
-			{
-				if (to_end - to_nxt < 1)
-					return codecvt_base::partial;
-				*to_nxt++ = static_cast<uint8_t>(wc);
-			}
-			else if (wc < 0x000800)
-			{
-				if (to_end - to_nxt < 2)
-					return codecvt_base::partial;
-				*to_nxt++ = static_cast<uint8_t>(0xC0 | (wc >> 6));
-				*to_nxt++ = static_cast<uint8_t>(0x80 | (wc & 0x03F));
-			}
-			else if (wc < 0x010000)
-			{
-				if (to_end - to_nxt < 3)
-					return codecvt_base::partial;
-				*to_nxt++ = static_cast<uint8_t>(0xE0 | (wc >> 12));
-				*to_nxt++ = static_cast<uint8_t>(0x80 | ((wc & 0x0FC0) >> 6));
-				*to_nxt++ = static_cast<uint8_t>(0x80 | (wc & 0x003F));
-			}
-			else // if (wc < 0x110000)
-			{
-				if (to_end - to_nxt < 4)
-					return codecvt_base::partial;
-				*to_nxt++ = static_cast<uint8_t>(0xF0 | (wc >> 18));
-				*to_nxt++ = static_cast<uint8_t>(0x80 | ((wc & 0x03F000) >> 12));
-				*to_nxt++ = static_cast<uint8_t>(0x80 | ((wc & 0x000FC0) >> 6));
-				*to_nxt++ = static_cast<uint8_t>(0x80 | (wc & 0x00003F));
-			}
-		}
-		return codecvt_base::ok;
-	}
-
-	inline codecvt_base::result utf8_to_ucs4(const uint8_t *frm, const uint8_t *frm_end, const uint8_t *&frm_nxt, uint32_t *to, uint32_t *to_end, uint32_t *&to_nxt, unsigned long Maxcode = 0x10FFFF, codecvt_mode mode = static_cast<codecvt_mode>(0))
-	{
-		frm_nxt = frm;
-		to_nxt = to;
-		if ((mode & consume_header) && frm_end - frm_nxt >= 3 && frm_nxt[0] == 0xEF && frm_nxt[1] == 0xBB && frm_nxt[2] == 0xBF)
-			frm_nxt += 3;
-		for (; frm_nxt < frm_end && to_nxt < to_end; ++to_nxt)
-		{
-			uint8_t c1 = *frm_nxt;
-			if (c1 < 0x80)
-			{
-				if (c1 > Maxcode)
-					return codecvt_base::error;
-				*to_nxt = static_cast<uint32_t>(c1);
-				++frm_nxt;
-			}
-			else if (c1 < 0xC2)
-				return codecvt_base::error;
-			else if (c1 < 0xE0)
-			{
-				if (frm_end - frm_nxt < 2)
-					return codecvt_base::partial;
-				uint8_t c2 = frm_nxt[1];
-				if ((c2 & 0xC0) != 0x80)
-					return codecvt_base::error;
-				uint32_t t = static_cast<uint32_t>(((c1 & 0x1F) << 6) | (c2 & 0x3F));
-				if (t > Maxcode)
-					return codecvt_base::error;
-				*to_nxt = t;
-				frm_nxt += 2;
-			}
-			else if (c1 < 0xF0)
-			{
-				if (frm_end - frm_nxt < 3)
-					return codecvt_base::partial;
-				uint8_t c2 = frm_nxt[1];
-				uint8_t c3 = frm_nxt[2];
-				switch (c1)
-				{
-					case 0xE0:
-						if ((c2 & 0xE0) != 0xA0)
-							return codecvt_base::error;
-						break;
-					case 0xED:
-						if ((c2 & 0xE0) != 0x80)
-							return codecvt_base::error;
-						break;
-					default:
-						if ((c2 & 0xC0) != 0x80)
-							return codecvt_base::error;
-				}
-				if ((c3 & 0xC0) != 0x80)
-					return codecvt_base::error;
-				uint32_t t = static_cast<uint32_t>(((c1 & 0x0F) << 12) | ((c2 & 0x3F) << 6) |  (c3 & 0x3F));
-				if (t > Maxcode)
-					return codecvt_base::error;
-				*to_nxt = t;
-				frm_nxt += 3;
-			}
-			else if (c1 < 0xF5)
-			{
-				if (frm_end - frm_nxt < 4)
-					return codecvt_base::partial;
-				uint8_t c2 = frm_nxt[1];
-				uint8_t c3 = frm_nxt[2];
-				uint8_t c4 = frm_nxt[3];
-				switch (c1)
-				{
-					case 0xF0:
-						if (c2 < 0x90 || c2 > 0xBF)
-							return codecvt_base::error;
-						break;
-					case 0xF4:
-						if ((c2 & 0xF0) != 0x80)
-							return codecvt_base::error;
-						break;
-					default:
-						if ((c2 & 0xC0) != 0x80)
-							return codecvt_base::error;
-				}
-				if ((c3 & 0xC0) != 0x80 || (c4 & 0xC0) != 0x80)
-					return codecvt_base::error;
-				uint32_t t = static_cast<uint32_t>(((c1 & 0x07) << 18) | ((c2 & 0x3F) << 12) | ((c3 & 0x3F) << 6) |  (c4 & 0x3F));
-				if (t > Maxcode)
-					return codecvt_base::error;
-				*to_nxt = t;
-				frm_nxt += 4;
-			}
-			else
-				return codecvt_base::error;
-		}
-		return frm_nxt < frm_end ? codecvt_base::partial : codecvt_base::ok;
-	}
-
-	inline int utf8_to_ucs4_length(const uint8_t *frm, const uint8_t *frm_end, size_t mx, unsigned long Maxcode = 0x10FFFF, codecvt_mode mode = static_cast<codecvt_mode>(0))
-	{
-		auto frm_nxt = frm;
-		if ((mode & consume_header) && frm_end - frm_nxt >= 3 && frm_nxt[0] == 0xEF && frm_nxt[1] == 0xBB && frm_nxt[2] == 0xBF)
-			frm_nxt += 3;
-		for (size_t nchar32_t = 0; frm_nxt < frm_end && nchar32_t < mx; ++nchar32_t)
-		{
-			uint8_t c1 = *frm_nxt;
-			if (c1 < 0x80)
-			{
-				if (c1 > Maxcode)
-					break;
-				++frm_nxt;
-			}
-			else if (c1 < 0xC2)
-				break;
-			else if (c1 < 0xE0)
-			{
-				if (frm_end - frm_nxt < 2 || (frm_nxt[1] & 0xC0) != 0x80)
-					break;
-				if ((((c1 & 0x1Fu) << 6) | (frm_nxt[1] & 0x3Fu)) > Maxcode)
-					break;
-				frm_nxt += 2;
-			}
-			else if (c1 < 0xF0)
-			{
-				if (frm_end - frm_nxt < 3)
-					break;
-				uint8_t c2 = frm_nxt[1];
-				uint8_t c3 = frm_nxt[2];
-				switch (c1)
-				{
-					case 0xE0:
-						if ((c2 & 0xE0) != 0xA0)
-							return static_cast<int>(frm_nxt - frm);
-						break;
-					case 0xED:
-						if ((c2 & 0xE0) != 0x80)
-							return static_cast<int>(frm_nxt - frm);
-						break;
-					default:
-						if ((c2 & 0xC0) != 0x80)
-							return static_cast<int>(frm_nxt - frm);
-				}
-				if ((c3 & 0xC0) != 0x80)
-					break;
-				if ((((c1 & 0x0Fu) << 12) | ((c2 & 0x3Fu) << 6) | (c3 & 0x3Fu)) > Maxcode)
-					break;
-				frm_nxt += 3;
-			}
-			else if (c1 < 0xF5)
-			{
-				if (frm_end - frm_nxt < 4)
-					break;
-				uint8_t c2 = frm_nxt[1];
-				uint8_t c3 = frm_nxt[2];
-				uint8_t c4 = frm_nxt[3];
-				switch (c1)
-				{
-					case 0xF0:
-						if (c2 < 0x90 || c2 > 0xBF)
-							return static_cast<int>(frm_nxt - frm);
-						break;
-					case 0xF4:
-						if ((c2 & 0xF0) != 0x80)
-							return static_cast<int>(frm_nxt - frm);
-						break;
-					default:
-						if ((c2 & 0xC0) != 0x80)
-							return static_cast<int>(frm_nxt - frm);
-				}
-				if ((c3 & 0xC0) != 0x80 || (c4 & 0xC0) != 0x80)
-					break;
-				if ((((c1 & 0x07u) << 18) | ((c2 & 0x3Fu) << 12) | ((c3 & 0x3Fu) << 6)  |  (c4 & 0x3Fu)) > Maxcode)
-					break;
-				frm_nxt += 4;
-			}
-			else
-				break;
-		}
-		return static_cast<int>(frm_nxt - frm);
-	}
-
-	inline codecvt_base::result ucs2_to_utf8(const uint16_t *frm, const uint16_t *frm_end, const uint16_t *&frm_nxt, uint8_t *to, uint8_t *to_end, uint8_t *&to_nxt, unsigned long Maxcode = 0x10FFFF, codecvt_mode mode = static_cast<codecvt_mode>(0))
-	{
-		frm_nxt = frm;
-		to_nxt = to;
-		if (mode & generate_header)
-		{
-			if (to_end - to_nxt < 3)
-				return codecvt_base::partial;
-			*to_nxt++ = 0xEF;
-			*to_nxt++ = 0xBB;
-			*to_nxt++ = 0xBF;
-		}
-		for (; frm_nxt < frm_end; ++frm_nxt)
-		{
-			uint16_t wc = *frm_nxt;
-			if ((wc & 0xF800) == 0xD800 || wc > Maxcode)
-				return codecvt_base::error;
-			if (wc < 0x0080)
-			{
-				if (to_end - to_nxt < 1)
-					return codecvt_base::partial;
-				*to_nxt++ = static_cast<uint8_t>(wc);
-			}
-			else if (wc < 0x0800)
-			{
-				if (to_end - to_nxt < 2)
-					return codecvt_base::partial;
-				*to_nxt++ = static_cast<uint8_t>(0xC0 | (wc >> 6));
-				*to_nxt++ = static_cast<uint8_t>(0x80 | (wc & 0x03F));
-			}
-			else // if (wc <= 0xFFFF)
-			{
-				if (to_end - to_nxt < 3)
-					return codecvt_base::partial;
-				*to_nxt++ = static_cast<uint8_t>(0xE0 | (wc >> 12));
-				*to_nxt++ = static_cast<uint8_t>(0x80 | ((wc & 0x0FC0) >> 6));
-				*to_nxt++ = static_cast<uint8_t>(0x80 | (wc & 0x003F));
-			}
-		}
-		return codecvt_base::ok;
-	}
-
-	inline codecvt_base::result utf8_to_ucs2(const uint8_t *frm, const uint8_t *frm_end, const uint8_t *&frm_nxt, uint16_t *to, uint16_t *to_end, uint16_t *&to_nxt, unsigned long Maxcode = 0x10FFFF, codecvt_mode mode = static_cast<codecvt_mode>(0))
-	{
-		frm_nxt = frm;
-		to_nxt = to;
-		if ((mode & consume_header) && frm_end - frm_nxt >= 3 && frm_nxt[0] == 0xEF && frm_nxt[1] == 0xBB && frm_nxt[2] == 0xBF)
-			frm_nxt += 3;
-		for (; frm_nxt < frm_end && to_nxt < to_end; ++to_nxt)
-		{
-			uint8_t c1 = *frm_nxt;
-			if (c1 < 0x80)
-			{
-				if (c1 > Maxcode)
-					return codecvt_base::error;
-				*to_nxt = static_cast<uint16_t>(c1);
-				++frm_nxt;
-			}
-			else if (c1 < 0xC2)
-				return codecvt_base::error;
-			else if (c1 < 0xE0)
-			{
-				if (frm_end - frm_nxt < 2)
-					return codecvt_base::partial;
-				uint8_t c2 = frm_nxt[1];
-				if ((c2 & 0xC0) != 0x80)
-					return codecvt_base::error;
-				uint16_t t = static_cast<uint16_t>(((c1 & 0x1F) << 6) | (c2 & 0x3F));
-				if (t > Maxcode)
-					return codecvt_base::error;
-				*to_nxt = t;
-				frm_nxt += 2;
-			}
-			else if (c1 < 0xF0)
-			{
-				if (frm_end - frm_nxt < 3)
-					return codecvt_base::partial;
-				uint8_t c2 = frm_nxt[1];
-				uint8_t c3 = frm_nxt[2];
-				switch (c1)
-				{
-					case 0xE0:
-						if ((c2 & 0xE0) != 0xA0)
-							return codecvt_base::error;
-						break;
-					case 0xED:
-						if ((c2 & 0xE0) != 0x80)
-							return codecvt_base::error;
-						break;
-					default:
-						if ((c2 & 0xC0) != 0x80)
-							return codecvt_base::error;
-				}
-				if ((c3 & 0xC0) != 0x80)
-					return codecvt_base::error;
-				uint16_t t = static_cast<uint16_t>(((c1 & 0x0F) << 12) | ((c2 & 0x3F) << 6) |  (c3 & 0x3F));
-				if (t > Maxcode)
-					return codecvt_base::error;
-				*to_nxt = t;
-				frm_nxt += 3;
-			}
-			else
-				return codecvt_base::error;
-		}
-		return frm_nxt < frm_end ? codecvt_base::partial : codecvt_base::ok;
-	}
-
-	inline int utf8_to_ucs2_length(const uint8_t *frm, const uint8_t *frm_end, size_t mx, unsigned long Maxcode = 0x10FFFF, codecvt_mode mode = static_cast<codecvt_mode>(0))
-	{
-		auto frm_nxt = frm;
-		if ((mode & consume_header) && frm_end - frm_nxt >= 3 && frm_nxt[0] == 0xEF && frm_nxt[1] == 0xBB && frm_nxt[2] == 0xBF)
-			frm_nxt += 3;
-		for (size_t nchar32_t = 0; frm_nxt < frm_end && nchar32_t < mx; ++nchar32_t)
-		{
-			uint8_t c1 = *frm_nxt;
-			if (c1 < 0x80)
-			{
-				if (c1 > Maxcode)
-					break;
-				++frm_nxt;
-			}
-			else if (c1 < 0xC2)
-				break;
-			else if (c1 < 0xE0)
-			{
-				if (frm_end - frm_nxt < 2 || (frm_nxt[1] & 0xC0) != 0x80)
-					break;
-				if ((((c1 & 0x1Fu) << 6) | (frm_nxt[1] & 0x3Fu)) > Maxcode)
-					break;
-				frm_nxt += 2;
-			}
-			else if (c1 < 0xF0)
-			{
-				if (frm_end - frm_nxt < 3)
-					break;
-				uint8_t c2 = frm_nxt[1];
-				uint8_t c3 = frm_nxt[2];
-				switch (c1)
-				{
-					case 0xE0:
-						if ((c2 & 0xE0) != 0xA0)
-							return static_cast<int>(frm_nxt - frm);
-						break;
-					case 0xED:
-						if ((c2 & 0xE0) != 0x80)
-							return static_cast<int>(frm_nxt - frm);
-						break;
-					default:
-						if ((c2 & 0xC0) != 0x80)
-							return static_cast<int>(frm_nxt - frm);
-				}
-				if ((c3 & 0xC0) != 0x80)
-					break;
-				if ((((c1 & 0x0Fu) << 12) | ((c2 & 0x3Fu) << 6) | (c3 & 0x3Fu)) > Maxcode)
-					break;
-				frm_nxt += 3;
-			}
-			else
-				break;
-		}
-		return static_cast<int>(frm_nxt - frm);
-	}
-
-	inline codecvt_base::result ucs4_to_utf16be(const uint32_t *frm, const uint32_t *frm_end, const uint32_t *&frm_nxt, uint8_t *to, uint8_t *to_end, uint8_t *&to_nxt, unsigned long Maxcode = 0x10FFFF, codecvt_mode mode = static_cast<codecvt_mode>(0))
-	{
-		frm_nxt = frm;
-		to_nxt = to;
-		if (mode & generate_header)
-		{
-			if (to_end - to_nxt < 2)
-				return codecvt_base::partial;
-			*to_nxt++ = 0xFE;
-			*to_nxt++ = 0xFF;
-		}
-		for (; frm_nxt < frm_end; ++frm_nxt)
-		{
-			uint32_t wc = *frm_nxt;
-			if ((wc & 0xFFFFF800) == 0x00D800 || wc > Maxcode)
-				return codecvt_base::error;
-			if (wc < 0x010000)
-			{
-				if (to_end - to_nxt < 2)
-					return codecvt_base::partial;
-				*to_nxt++ = static_cast<uint8_t>(wc >> 8);
-				*to_nxt++ = static_cast<uint8_t>(wc);
-			}
-			else
-			{
-				if (to_end - to_nxt < 4)
-					return codecvt_base::partial;
-				uint16_t t = static_cast<uint16_t>(0xD800 | ((((wc & 0x1F0000) >> 16) - 1) << 6) | ((wc & 0x00FC00) >> 10));
-				*to_nxt++ = static_cast<uint8_t>(t >> 8);
-				*to_nxt++ = static_cast<uint8_t>(t);
-				t = static_cast<uint16_t>(0xDC00 | (wc & 0x03FF));
-				*to_nxt++ = static_cast<uint8_t>(t >> 8);
-				*to_nxt++ = static_cast<uint8_t>(t);
-			}
-		}
-		return codecvt_base::ok;
-	}
-
-	inline codecvt_base::result utf16be_to_ucs4(const uint8_t *frm, const uint8_t *frm_end, const uint8_t *&frm_nxt, uint32_t *to, uint32_t *to_end, uint32_t *&to_nxt, unsigned long Maxcode = 0x10FFFF, codecvt_mode mode = static_cast<codecvt_mode>(0))
-	{
-		frm_nxt = frm;
-		to_nxt = to;
-		if ((mode & consume_header) && frm_end - frm_nxt >= 2 && frm_nxt[0] == 0xFE && frm_nxt[1] == 0xFF)
-			frm_nxt += 2;
-		for (; frm_nxt < frm_end - 1 && to_nxt < to_end; ++to_nxt)
-		{
-			uint16_t c1 = static_cast<uint16_t>((frm_nxt[0] << 8) | frm_nxt[1]);
-			if ((c1 & 0xFC00) == 0xDC00)
-				return codecvt_base::error;
-			if ((c1 & 0xFC00) != 0xD800)
-			{
-				if (c1 > Maxcode)
-					return codecvt_base::error;
-				*to_nxt = static_cast<uint32_t>(c1);
-				frm_nxt += 2;
-			}
-			else
-			{
-				if (frm_end - frm_nxt < 4)
-					return codecvt_base::partial;
-				uint16_t c2 = static_cast<uint16_t>((frm_nxt[2] << 8) | frm_nxt[3]);
-				if ((c2 & 0xFC00) != 0xDC00)
-					return codecvt_base::error;
-				uint32_t t = static_cast<uint32_t>(((((c1 & 0x03C0) >> 6) + 1) << 16) | ((c1 & 0x003F) << 10) | (c2 & 0x03FF));
-				if (t > Maxcode)
-					return codecvt_base::error;
-				*to_nxt = t;
-				frm_nxt += 4;
-			}
-		}
-		return frm_nxt < frm_end ? codecvt_base::partial : codecvt_base::ok;
-	}
-
-	inline int utf16be_to_ucs4_length(const uint8_t *frm, const uint8_t *frm_end, size_t mx, unsigned long Maxcode = 0x10FFFF, codecvt_mode mode = static_cast<codecvt_mode>(0))
-	{
-		auto frm_nxt = frm;
-		if ((mode & consume_header) && frm_end - frm_nxt >= 2 && frm_nxt[0] == 0xFE && frm_nxt[1] == 0xFF)
-			frm_nxt += 2;
-		for (size_t nchar32_t = 0; frm_nxt < frm_end - 1 && nchar32_t < mx; ++nchar32_t)
-		{
-			uint16_t c1 = static_cast<uint16_t>((frm_nxt[0] << 8) | frm_nxt[1]);
-			if ((c1 & 0xFC00) == 0xDC00)
-				break;
-			if ((c1 & 0xFC00) != 0xD800)
-			{
-				if (c1 > Maxcode)
-					break;
-				frm_nxt += 2;
-			}
-			else
-			{
-				if (frm_end - frm_nxt < 4)
-					break;
-				uint16_t c2 = static_cast<uint16_t>((frm_nxt[2] << 8) | frm_nxt[3]);
-				if ((c2 & 0xFC00) != 0xDC00)
-					break;
-				uint32_t t = static_cast<uint32_t>(((((c1 & 0x03C0) >> 6) + 1) << 16) | ((c1 & 0x003F) << 10) | (c2 & 0x03FF));
-				if (t > Maxcode)
-					break;
-				frm_nxt += 4;
-			}
-		}
-		return static_cast<int>(frm_nxt - frm);
-	}
-
-	inline codecvt_base::result ucs4_to_utf16le(const uint32_t *frm, const uint32_t *frm_end, const uint32_t *&frm_nxt, uint8_t *to, uint8_t *to_end, uint8_t *&to_nxt, unsigned long Maxcode = 0x10FFFF, codecvt_mode mode = static_cast<codecvt_mode>(0))
-	{
-		frm_nxt = frm;
-		to_nxt = to;
-		if (mode & generate_header)
-		{
-			if (to_end - to_nxt < 2)
-				return codecvt_base::partial;
-			*to_nxt++ = 0xFF;
-			*to_nxt++ = 0xFE;
-		}
-		for (; frm_nxt < frm_end; ++frm_nxt)
-		{
-			uint32_t wc = *frm_nxt;
-			if ((wc & 0xFFFFF800) == 0x00D800 || wc > Maxcode)
-				return codecvt_base::error;
-			if (wc < 0x010000)
-			{
-				if (to_end - to_nxt < 2)
-					return codecvt_base::partial;
-				*to_nxt++ = static_cast<uint8_t>(wc);
-				*to_nxt++ = static_cast<uint8_t>(wc >> 8);
-			}
-			else
-			{
-				if (to_end - to_nxt < 4)
-					return codecvt_base::partial;
-				uint16_t t = static_cast<uint16_t>(0xD800 | ((((wc & 0x1F0000) >> 16) - 1) << 6) | ((wc & 0x00FC00) >> 10));
-				*to_nxt++ = static_cast<uint8_t>(t);
-				*to_nxt++ = static_cast<uint8_t>(t >> 8);
-				t = static_cast<uint16_t>(0xDC00 | (wc & 0x03FF));
-				*to_nxt++ = static_cast<uint8_t>(t);
-				*to_nxt++ = static_cast<uint8_t>(t >> 8);
-			}
-		}
-		return codecvt_base::ok;
-	}
-
-	inline codecvt_base::result utf16le_to_ucs4(const uint8_t *frm, const uint8_t *frm_end, const uint8_t *&frm_nxt, uint32_t *to, uint32_t *to_end, uint32_t *&to_nxt, unsigned long Maxcode = 0x10FFFF, codecvt_mode mode = static_cast<codecvt_mode>(0))
-	{
-		frm_nxt = frm;
-		to_nxt = to;
-		if ((mode & consume_header) && frm_end - frm_nxt >= 2 && frm_nxt[0] == 0xFF && frm_nxt[1] == 0xFE)
-			frm_nxt += 2;
-		for (; frm_nxt < frm_end - 1 && to_nxt < to_end; ++to_nxt)
-		{
-			uint16_t c1 = static_cast<uint16_t>((frm_nxt[1] << 8) | frm_nxt[0]);
-			if ((c1 & 0xFC00) == 0xDC00)
-				return codecvt_base::error;
-			if ((c1 & 0xFC00) != 0xD800)
-			{
-				if (c1 > Maxcode)
-					return codecvt_base::error;
-				*to_nxt = static_cast<uint32_t>(c1);
-				frm_nxt += 2;
-			}
-			else
-			{
-				if (frm_end - frm_nxt < 4)
-					return codecvt_base::partial;
-				uint16_t c2 = static_cast<uint16_t>((frm_nxt[3] << 8) | frm_nxt[2]);
-				if ((c2 & 0xFC00) != 0xDC00)
-					return codecvt_base::error;
-				uint32_t t = static_cast<uint32_t>(((((c1 & 0x03C0) >> 6) + 1) << 16) | ((c1 & 0x003F) << 10) | (c2 & 0x03FF));
-				if (t > Maxcode)
-					return codecvt_base::error;
-				*to_nxt = t;
-				frm_nxt += 4;
-			}
-		}
-		return frm_nxt < frm_end ? codecvt_base::partial : codecvt_base::ok;
-	}
-
-	inline int utf16le_to_ucs4_length(const uint8_t *frm, const uint8_t *frm_end, size_t mx, unsigned long Maxcode = 0x10FFFF, codecvt_mode mode = static_cast<codecvt_mode>(0))
-	{
-		auto frm_nxt = frm;
-		if ((mode & consume_header) && frm_end - frm_nxt >= 2 && frm_nxt[0] == 0xFF && frm_nxt[1] == 0xFE)
-			frm_nxt += 2;
-		for (size_t nchar32_t = 0; frm_nxt < frm_end - 1 && nchar32_t < mx; ++nchar32_t)
-		{
-			uint16_t c1 = static_cast<uint16_t>((frm_nxt[1] << 8) | frm_nxt[0]);
-			if ((c1 & 0xFC00) == 0xDC00)
-				break;
-			if ((c1 & 0xFC00) != 0xD800)
-			{
-				if (c1 > Maxcode)
-					break;
-				frm_nxt += 2;
-			}
-			else
-			{
-				if (frm_end - frm_nxt < 4)
-					break;
-				uint16_t c2 = static_cast<uint16_t>((frm_nxt[3] << 8) | frm_nxt[2]);
-				if ((c2 & 0xFC00) != 0xDC00)
-					break;
-				uint32_t t = static_cast<uint32_t>(((((c1 & 0x03C0) >> 6) + 1) << 16) | ((c1 & 0x003F) << 10) | (c2 & 0x03FF));
-				if (t > Maxcode)
-					break;
-				frm_nxt += 4;
-			}
-		}
-		return static_cast<int>(frm_nxt - frm);
-	}
-
-	inline codecvt_base::result ucs2_to_utf16be(const uint16_t *frm, const uint16_t *frm_end, const uint16_t *&frm_nxt, uint8_t *to, uint8_t *to_end, uint8_t *&to_nxt, unsigned long Maxcode = 0x10FFFF, codecvt_mode mode = static_cast<codecvt_mode>(0))
-	{
-		frm_nxt = frm;
-		to_nxt = to;
-		if (mode & generate_header)
-		{
-			if (to_end - to_nxt < 2)
-				return codecvt_base::partial;
-			*to_nxt++ = 0xFE;
-			*to_nxt++ = 0xFF;
-		}
-		for (; frm_nxt < frm_end; ++frm_nxt)
-		{
-			uint16_t wc = *frm_nxt;
-			if ((wc & 0xF800) == 0xD800 || wc > Maxcode)
-				return codecvt_base::error;
-			if (to_end - to_nxt < 2)
-				return codecvt_base::partial;
-			*to_nxt++ = static_cast<uint8_t>(wc >> 8);
-			*to_nxt++ = static_cast<uint8_t>(wc);
-		}
-		return codecvt_base::ok;
-	}
-
-	inline codecvt_base::result utf16be_to_ucs2(const uint8_t *frm, const uint8_t *frm_end, const uint8_t *&frm_nxt, uint16_t *to, uint16_t *to_end, uint16_t *&to_nxt, unsigned long Maxcode = 0x10FFFF, codecvt_mode mode = static_cast<codecvt_mode>(0))
-	{
-		frm_nxt = frm;
-		to_nxt = to;
-		if ((mode & consume_header) && frm_end - frm_nxt >= 2 && frm_nxt[0] == 0xFE && frm_nxt[1] == 0xFF)
-			frm_nxt += 2;
-		for (; frm_nxt < frm_end - 1 && to_nxt < to_end; ++to_nxt)
-		{
-			uint16_t c1 = static_cast<uint16_t>((frm_nxt[0] << 8) | frm_nxt[1]);
-			if ((c1 & 0xF800) == 0xD800 || c1 > Maxcode)
-				return codecvt_base::error;
-			*to_nxt = c1;
-			frm_nxt += 2;
-		}
-		return frm_nxt < frm_end ? codecvt_base::partial : codecvt_base::ok;
-	}
-
-	inline int utf16be_to_ucs2_length(const uint8_t *frm, const uint8_t *frm_end, size_t mx, unsigned long Maxcode = 0x10FFFF, codecvt_mode mode = static_cast<codecvt_mode>(0))
-	{
-		auto frm_nxt = frm;
-		if ((mode & consume_header) && frm_end - frm_nxt >= 2 && frm_nxt[0] == 0xFE && frm_nxt[1] == 0xFF)
-			frm_nxt += 2;
-		for (size_t nchar16_t = 0; frm_nxt < frm_end - 1 && nchar16_t < mx; ++nchar16_t)
-		{
-			uint16_t c1 = static_cast<uint16_t>((frm_nxt[0] << 8) | frm_nxt[1]);
-			if ((c1 & 0xF800) == 0xD800 || c1 > Maxcode)
-				break;
-			frm_nxt += 2;
-		}
-		return static_cast<int>(frm_nxt - frm);
-	}
-
-	inline codecvt_base::result ucs2_to_utf16le(const uint16_t *frm, const uint16_t *frm_end, const uint16_t *&frm_nxt, uint8_t *to, uint8_t *to_end, uint8_t *&to_nxt, unsigned long Maxcode = 0x10FFFF, codecvt_mode mode = static_cast<codecvt_mode>(0))
-	{
-		frm_nxt = frm;
-		to_nxt = to;
-		if (mode & generate_header)
-		{
-			if (to_end - to_nxt < 2)
-				return codecvt_base::partial;
-			*to_nxt++ = 0xFF;
-			*to_nxt++ = 0xFE;
-		}
-		for (; frm_nxt < frm_end; ++frm_nxt)
-		{
-			uint16_t wc = *frm_nxt;
-			if ((wc & 0xF800) == 0xD800 || wc > Maxcode)
-				return codecvt_base::error;
-			if (to_end - to_nxt < 2)
-				return codecvt_base::partial;
-			*to_nxt++ = static_cast<uint8_t>(wc);
-			*to_nxt++ = static_cast<uint8_t>(wc >> 8);
-		}
-		return codecvt_base::ok;
-	}
-
-	inline codecvt_base::result utf16le_to_ucs2(const uint8_t *frm, const uint8_t *frm_end, const uint8_t *&frm_nxt, uint16_t *to, uint16_t *to_end, uint16_t *&to_nxt, unsigned long Maxcode = 0x10FFFF, codecvt_mode mode = static_cast<codecvt_mode>(0))
-	{
-		frm_nxt = frm;
-		to_nxt = to;
-		if ((mode & consume_header) && frm_end - frm_nxt >= 2 && frm_nxt[0] == 0xFF && frm_nxt[1] == 0xFE)
-			frm_nxt += 2;
-		for (; frm_nxt < frm_end - 1 && to_nxt < to_end; ++to_nxt)
-		{
-			uint16_t c1 = static_cast<uint16_t>((frm_nxt[1] << 8) | frm_nxt[0]);
-			if ((c1 & 0xF800) == 0xD800 || c1 > Maxcode)
-				return codecvt_base::error;
-			*to_nxt = c1;
-			frm_nxt += 2;
-		}
-		return frm_nxt < frm_end ? codecvt_base::partial : codecvt_base::ok;
-	}
-
-	inline int utf16le_to_ucs2_length(const uint8_t *frm, const uint8_t *frm_end, size_t mx, unsigned long Maxcode = 0x10FFFF, codecvt_mode mode = static_cast<codecvt_mode>(0))
-	{
-		auto frm_nxt = frm;
-		if ((mode & consume_header) && frm_end - frm_nxt >= 2 && frm_nxt[0] == 0xFF && frm_nxt[1] == 0xFE)
-			frm_nxt += 2;
-		for (size_t nchar16_t = 0; frm_nxt < frm_end - 1 && nchar16_t < mx; ++nchar16_t)
-		{
-			uint16_t c1 = static_cast<uint16_t>((frm_nxt[1] << 8) | frm_nxt[0]);
-			if ((c1 & 0xF800) == 0xD800 || c1 > Maxcode)
-				break;
-			frm_nxt += 2;
-		}
-		return static_cast<int>(frm_nxt - frm);
-	}
-}
-
-template<> class codecvt<char16_t, char, mbstate_t> : public locale::facet, public codecvt_base
-{
-public:
-	typedef char16_t intern_type;
-	typedef char extern_type;
-	typedef mbstate_t state_type;
-
-	explicit codecvt(size_t __refs = 0) : locale::facet(__refs) { }
-
-	result out(state_type &__st, const intern_type *__frm, const intern_type *__frm_end, const intern_type *&__frm_nxt, extern_type *__to, extern_type *__to_end, extern_type *&__to_nxt) const
-	{
-		return this->do_out(__st, __frm, __frm_end, __frm_nxt, __to, __to_end, __to_nxt);
-	}
-
-	result unshift(state_type &__st, extern_type *__to, extern_type *__to_end, extern_type *&__to_nxt) const
-	{
-		return this->do_unshift(__st, __to, __to_end, __to_nxt);
-	}
-
-	result in(state_type &__st, const extern_type *__frm, const extern_type *__frm_end, const extern_type *&__frm_nxt, intern_type *__to, intern_type *__to_end, intern_type *&__to_nxt) const
-	{
-		return this->do_in(__st, __frm, __frm_end, __frm_nxt, __to, __to_end, __to_nxt);
-	}
-
-	int encoding() const noexcept
-	{
-		return this->do_encoding();
-	}
-
-	bool always_noconv() const noexcept
-	{
-		return this->do_always_noconv();
-	}
-
-	int length(state_type &__st, const extern_type *__frm, const extern_type *__end, size_t __mx) const
-	{
-		return this->do_length(__st, __frm, __end, __mx);
-	}
-
-	int max_length() const noexcept
-	{
-		return this->do_max_length();
-	}
-
-	static locale::id id;
-
-protected:
-	explicit codecvt(const char *, size_t __refs = 0) : locale::facet(__refs) { }
-
-	~codecvt() { }
-
-	virtual result do_out(state_type &, const intern_type *frm, const intern_type *frm_end, const intern_type *&frm_nxt, extern_type *to, extern_type *to_end, extern_type *&to_nxt) const
-	{
-		auto _frm = reinterpret_cast<const uint16_t *>(frm);
-		auto _frm_end = reinterpret_cast<const uint16_t *>(frm_end);
-		auto _frm_nxt = _frm;
-		auto _to = reinterpret_cast<uint8_t *>(to);
-		auto _to_end = reinterpret_cast<uint8_t *>(to_end);
-		auto _to_nxt = _to;
-		auto r = UnicodeConverters::utf16_to_utf8(_frm, _frm_end, _frm_nxt, _to, _to_end, _to_nxt);
-		frm_nxt = frm + (_frm_nxt - _frm);
-		to_nxt = to + (_to_nxt - _to);
-		return r;
-	}
-	virtual result do_in(state_type &, const extern_type *frm, const extern_type *frm_end, const extern_type *&frm_nxt, intern_type *to, intern_type *to_end, intern_type *&to_nxt) const
-	{
-		auto _frm = reinterpret_cast<const uint8_t *>(frm);
-		auto _frm_end = reinterpret_cast<const uint8_t *>(frm_end);
-		auto _frm_nxt = _frm;
-		auto _to = reinterpret_cast<uint16_t *>(to);
-		auto _to_end = reinterpret_cast<uint16_t *>(to_end);
-		auto _to_nxt = _to;
-		auto r = UnicodeConverters::utf8_to_utf16(_frm, _frm_end, _frm_nxt, _to, _to_end, _to_nxt);
-		frm_nxt = frm + (_frm_nxt - _frm);
-		to_nxt = to + (_to_nxt - _to);
-		return r;
-	}
-	virtual result do_unshift(state_type &, extern_type *to, extern_type *, extern_type *&to_nxt) const
-	{
-		to_nxt = to;
-		return noconv;
-	}
-	virtual int do_encoding() const noexcept { return 0; }
-	virtual bool do_always_noconv() const noexcept { return false; }
-	virtual int do_length(state_type &, const extern_type *frm, const extern_type *frm_end, size_t mx) const
-	{
-		auto _frm = reinterpret_cast<const uint8_t *>(frm);
-		auto _frm_end = reinterpret_cast<const uint8_t *>(frm_end);
-		return UnicodeConverters::utf8_to_utf16_length(_frm, _frm_end, mx);
-	}
-	virtual int do_max_length() const noexcept { return 4; }
-};
-
-template<> class codecvt<char32_t, char, mbstate_t> : public locale::facet, public codecvt_base
-{
-public:
-	typedef char32_t intern_type;
-	typedef char extern_type;
-	typedef mbstate_t state_type;
-
-	explicit codecvt(size_t __refs = 0) : locale::facet(__refs) { }
-
-	result out(state_type &__st, const intern_type *__frm, const intern_type *__frm_end, const intern_type *&__frm_nxt, extern_type *__to, extern_type *__to_end, extern_type *&__to_nxt) const
-	{
-		return this->do_out(__st, __frm, __frm_end, __frm_nxt, __to, __to_end, __to_nxt);
-	}
-
-	result unshift(state_type &__st, extern_type *__to, extern_type *__to_end, extern_type *&__to_nxt) const
-	{
-		return this->do_unshift(__st, __to, __to_end, __to_nxt);
-	}
-
-	result in(state_type &__st, const extern_type *__frm, const extern_type *__frm_end, const extern_type *&__frm_nxt, intern_type *__to, intern_type *__to_end, intern_type *&__to_nxt) const
-	{
-		return this->do_in(__st, __frm, __frm_end, __frm_nxt, __to, __to_end, __to_nxt);
-	}
-
-	int encoding() const noexcept
-	{
-		return this->do_encoding();
-	}
-
-	bool always_noconv() const noexcept
-	{
-		return this->do_always_noconv();
-	}
-
-	int length(state_type &__st, const extern_type *__frm, const extern_type *__end, size_t __mx) const
-	{
-		return this->do_length(__st, __frm, __end, __mx);
-	}
-
-	int max_length() const noexcept
-	{
-		return this->do_max_length();
-	}
-
-	static locale::id id;
-
-protected:
-	explicit codecvt(const char *, size_t __refs = 0) : locale::facet(__refs) { }
-
-	~codecvt() { }
-
-	virtual result do_out(state_type &, const intern_type *frm, const intern_type *frm_end, const intern_type *&frm_nxt, extern_type *to, extern_type *to_end, extern_type *&to_nxt) const
-	{
-		auto _frm = reinterpret_cast<const uint32_t *>(frm);
-		auto _frm_end = reinterpret_cast<const uint32_t *>(frm_end);
-		auto _frm_nxt = _frm;
-		auto _to = reinterpret_cast<uint8_t *>(to);
-		auto _to_end = reinterpret_cast<uint8_t *>(to_end);
-		auto _to_nxt = _to;
-		auto r = UnicodeConverters::ucs4_to_utf8(_frm, _frm_end, _frm_nxt, _to, _to_end, _to_nxt);
-		frm_nxt = frm + (_frm_nxt - _frm);
-		to_nxt = to + (_to_nxt - _to);
-		return r;
-	}
-	virtual result do_in(state_type &, const extern_type *frm, const extern_type *frm_end, const extern_type *&frm_nxt, intern_type *to, intern_type *to_end, intern_type *&to_nxt) const
-	{
-		auto _frm = reinterpret_cast<const uint8_t *>(frm);
-		auto _frm_end = reinterpret_cast<const uint8_t *>(frm_end);
-		auto _frm_nxt = _frm;
-		auto _to = reinterpret_cast<uint32_t *>(to);
-		auto _to_end = reinterpret_cast<uint32_t *>(to_end);
-		auto _to_nxt = _to;
-		auto r = UnicodeConverters::utf8_to_ucs4(_frm, _frm_end, _frm_nxt, _to, _to_end, _to_nxt);
-		frm_nxt = frm + (_frm_nxt - _frm);
-		to_nxt = to + (_to_nxt - _to);
-		return r;
-	}
-	virtual result do_unshift(state_type &, extern_type *to, extern_type *, extern_type *&to_nxt) const
-	{
-		to_nxt = to;
-		return noconv;
-	}
-	virtual int do_encoding() const noexcept { return 0; }
-	virtual bool do_always_noconv() const noexcept { return false; }
-	virtual int do_length(state_type &, const extern_type *frm, const extern_type *frm_end, size_t mx) const
-	{
-		auto _frm = reinterpret_cast<const uint8_t *>(frm);
-		auto _frm_end = reinterpret_cast<const uint8_t *>(frm_end);
-		return UnicodeConverters::utf8_to_ucs4_length(_frm, _frm_end, mx);
-	}
-	virtual int do_max_length() const noexcept { return 4; }
-};
-
-template<class _Elem> class __codecvt_utf8;
-
-template<> class __codecvt_utf8<wchar_t> : public codecvt<wchar_t, char, mbstate_t>
-{
-	unsigned long _Maxcode_;
-	codecvt_mode _Mode_;
-public:
-	typedef wchar_t intern_type;
-	typedef char extern_type;
-	typedef mbstate_t state_type;
-
-	explicit __codecvt_utf8(size_t __refs, unsigned long _Maxcode, codecvt_mode _Mode) : codecvt<wchar_t, char, mbstate_t>(__refs), _Maxcode_(_Maxcode), _Mode_(_Mode) { }
-protected:
-	virtual result do_out(state_type &, const intern_type *frm, const intern_type *frm_end, const intern_type *&frm_nxt, extern_type *to, extern_type *to_end, extern_type *&to_nxt) const
-	{
-#ifdef _WIN32
-		auto _frm = reinterpret_cast<const uint16_t *>(frm);
-		auto _frm_end = reinterpret_cast<const uint16_t *>(frm_end);
-#else
-		auto _frm = reinterpret_cast<const uint32_t *>(frm);
-		auto _frm_end = reinterpret_cast<const uint32_t *>(frm_end);
-#endif
-		auto _frm_nxt = _frm;
-		auto _to = reinterpret_cast<uint8_t *>(to);
-		auto _to_end = reinterpret_cast<uint8_t *>(to_end);
-		auto _to_nxt = _to;
-		auto r = UnicodeConverters::
-#ifdef _WIN32
-			ucs2_to_utf8
-#else
-			ucs4_to_utf8
-#endif
-			(_frm, _frm_end, _frm_nxt, _to, _to_end, _to_nxt, this->_Maxcode_, this->_Mode_);
-		frm_nxt = frm + (_frm_nxt - _frm);
-		to_nxt = to + (_to_nxt - _to);
-		return r;
-	}
-	virtual result do_in(state_type &, const extern_type *frm, const extern_type *frm_end, const extern_type *&frm_nxt, intern_type *to, intern_type *to_end, intern_type *&to_nxt) const
-	{
-		auto _frm = reinterpret_cast<const uint8_t *>(frm);
-		auto _frm_end = reinterpret_cast<const uint8_t *>(frm_end);
-		auto _frm_nxt = _frm;
-#ifdef _WIN32
-		auto _to = reinterpret_cast<uint16_t *>(to);
-		auto _to_end = reinterpret_cast<uint16_t *>(to_end);
-#else
-		auto _to = reinterpret_cast<uint32_t *>(to);
-		auto _to_end = reinterpret_cast<uint32_t *>(to_end);
-#endif
-		auto _to_nxt = _to;
-		auto r = UnicodeConverters::
-#ifdef _WIN32
-			utf8_to_ucs2
-#else
-			utf8_to_ucs4
-#endif
-			(_frm, _frm_end, _frm_nxt, _to, _to_end, _to_nxt, this->_Maxcode_, this->_Mode_);
-		frm_nxt = frm + (_frm_nxt - _frm);
-		to_nxt = to + (_to_nxt - _to);
-		return r;
-	}
-	virtual result do_unshift(state_type &, extern_type *to, extern_type *, extern_type *&to_nxt) const
-	{
-		to_nxt = to;
-		return noconv;
-	}
-	virtual int do_encoding() const noexcept { return 0; }
-	virtual bool do_always_noconv() const noexcept { return false; }
-	virtual int do_length(state_type &, const extern_type *frm, const extern_type *frm_end, size_t mx) const
-	{
-		auto _frm = reinterpret_cast<const uint8_t *>(frm);
-		auto _frm_end = reinterpret_cast<const uint8_t *>(frm_end);
-		return UnicodeConverters::utf8_to_ucs4_length(_frm, _frm_end, mx, this->_Maxcode_, this->_Mode_);
-	}
-	virtual int do_max_length() const noexcept
-	{
-		if (this->_Mode_ & consume_header)
-			return 7;
-		return 4;
-	}
-};
-
-template<> class __codecvt_utf8<char16_t> : public codecvt<char16_t, char, mbstate_t>
-{
-	unsigned long _Maxcode_;
-	codecvt_mode _Mode_;
-public:
-	typedef char16_t intern_type;
-	typedef char extern_type;
-	typedef mbstate_t state_type;
-
-	explicit __codecvt_utf8(size_t __refs, unsigned long _Maxcode, codecvt_mode _Mode) : codecvt<char16_t, char, mbstate_t>(__refs), _Maxcode_(_Maxcode), _Mode_(_Mode) { }
-protected:
-	virtual result do_out(state_type &, const intern_type *frm, const intern_type *frm_end, const intern_type *&frm_nxt, extern_type *to, extern_type *to_end, extern_type *&to_nxt) const
-	{
-		auto _frm = reinterpret_cast<const uint16_t *>(frm);
-		auto _frm_end = reinterpret_cast<const uint16_t *>(frm_end);
-		auto _frm_nxt = _frm;
-		auto _to = reinterpret_cast<uint8_t *>(to);
-		auto _to_end = reinterpret_cast<uint8_t *>(to_end);
-		auto _to_nxt = _to;
-		auto r = UnicodeConverters::ucs2_to_utf8(_frm, _frm_end, _frm_nxt, _to, _to_end, _to_nxt, this->_Maxcode_, this->_Mode_);
-		frm_nxt = frm + (_frm_nxt - _frm);
-		to_nxt = to + (_to_nxt - _to);
-		return r;
-	}
-	virtual result do_in(state_type &, const extern_type *frm, const extern_type *frm_end, const extern_type *&frm_nxt, intern_type *to, intern_type *to_end, intern_type *&to_nxt) const
-	{
-		auto _frm = reinterpret_cast<const uint8_t *>(frm);
-		auto _frm_end = reinterpret_cast<const uint8_t *>(frm_end);
-		auto _frm_nxt = _frm;
-		auto _to = reinterpret_cast<uint16_t *>(to);
-		auto _to_end = reinterpret_cast<uint16_t *>(to_end);
-		auto _to_nxt = _to;
-		auto r = UnicodeConverters::utf8_to_ucs2(_frm, _frm_end, _frm_nxt, _to, _to_end, _to_nxt, this->_Maxcode_, this->_Mode_);
-		frm_nxt = frm + (_frm_nxt - _frm);
-		to_nxt = to + (_to_nxt - _to);
-		return r;
-	}
-	virtual result do_unshift(state_type &, extern_type *to, extern_type *, extern_type *&to_nxt) const
-	{
-		to_nxt = to;
-		return noconv;
-	}
-	virtual int do_encoding() const noexcept { return 0; }
-	virtual bool do_always_noconv() const noexcept { return false; }
-	virtual int do_length(state_type &, const extern_type *frm, const extern_type *frm_end, size_t mx) const
-	{
-		auto _frm = reinterpret_cast<const uint8_t *>(frm);
-		auto _frm_end = reinterpret_cast<const uint8_t *>(frm_end);
-		return UnicodeConverters::utf8_to_ucs2_length(_frm, _frm_end, mx, this->_Maxcode_, this->_Mode_);
-	}
-	virtual int do_max_length() const noexcept
-	{
-		if (this->_Mode_ & consume_header)
-			return 6;
-		return 3;
-	}
-};
-
-template<> class __codecvt_utf8<char32_t> : public codecvt<char32_t, char, mbstate_t>
-{
-	unsigned long _Maxcode_;
-	codecvt_mode _Mode_;
-public:
-	typedef char32_t intern_type;
-	typedef char extern_type;
-	typedef mbstate_t state_type;
-
-	explicit __codecvt_utf8(size_t __refs, unsigned long _Maxcode, codecvt_mode _Mode) : codecvt<char32_t, char, mbstate_t>(__refs), _Maxcode_(_Maxcode), _Mode_(_Mode) { }
-protected:
-	virtual result do_out(state_type &, const intern_type *frm, const intern_type *frm_end, const intern_type *&frm_nxt, extern_type *to, extern_type *to_end, extern_type *&to_nxt) const
-	{
-		auto _frm = reinterpret_cast<const uint32_t *>(frm);
-		auto _frm_end = reinterpret_cast<const uint32_t *>(frm_end);
-		auto _frm_nxt = _frm;
-		auto _to = reinterpret_cast<uint8_t *>(to);
-		auto _to_end = reinterpret_cast<uint8_t *>(to_end);
-		auto _to_nxt = _to;
-		auto r = UnicodeConverters::ucs4_to_utf8(_frm, _frm_end, _frm_nxt, _to, _to_end, _to_nxt, this->_Maxcode_, this->_Mode_);
-		frm_nxt = frm + (_frm_nxt - _frm);
-		to_nxt = to + (_to_nxt - _to);
-		return r;
-	}
-	virtual result do_in(state_type &, const extern_type *frm, const extern_type *frm_end, const extern_type *&frm_nxt, intern_type *to, intern_type *to_end, intern_type *&to_nxt) const
-	{
-		auto _frm = reinterpret_cast<const uint8_t *>(frm);
-		auto _frm_end = reinterpret_cast<const uint8_t *>(frm_end);
-		auto _frm_nxt = _frm;
-		auto _to = reinterpret_cast<uint32_t *>(to);
-		auto _to_end = reinterpret_cast<uint32_t *>(to_end);
-		auto _to_nxt = _to;
-		auto r = UnicodeConverters::utf8_to_ucs4(_frm, _frm_end, _frm_nxt, _to, _to_end, _to_nxt, this->_Maxcode_, this->_Mode_);
-		frm_nxt = frm + (_frm_nxt - _frm);
-		to_nxt = to + (_to_nxt - _to);
-		return r;
-	}
-	virtual result do_unshift(state_type &, extern_type *to, extern_type *, extern_type *&to_nxt) const
-	{
-		to_nxt = to;
-		return noconv;
-	}
-	virtual int do_encoding() const noexcept { return 0; }
-	virtual bool do_always_noconv() const noexcept { return false; }
-	virtual int do_length(state_type &, const extern_type *frm, const extern_type *frm_end, size_t mx) const
-	{
-		auto _frm = reinterpret_cast<const uint8_t *>(frm);
-		auto _frm_end = reinterpret_cast<const uint8_t *>(frm_end);
-		return UnicodeConverters::utf8_to_ucs4_length(_frm, _frm_end, mx, this->_Maxcode_, this->_Mode_);
-	}
-	virtual int do_max_length() const noexcept
-	{
-		if (this->_Mode_ & consume_header)
-			return 7;
-		return 4;
-	}
-};
-
-template<class _Elem, unsigned long _Maxcode = 0x10ffff, codecvt_mode _Mode = static_cast<codecvt_mode>(0)> class codecvt_utf8 : public __codecvt_utf8<_Elem>
-{
-public:
-	explicit codecvt_utf8(size_t __refs = 0) : __codecvt_utf8<_Elem>(__refs, _Maxcode, _Mode) { }
-
-	~codecvt_utf8() { }
-};
-
-template<class _Elem, bool _LittleEndian> class __codecvt_utf16;
-
-template<> class __codecvt_utf16<wchar_t, false> : public codecvt<wchar_t, char, mbstate_t>
-{
-	unsigned long _Maxcode_;
-	codecvt_mode _Mode_;
-public:
-	typedef wchar_t intern_type;
-	typedef char extern_type;
-	typedef mbstate_t state_type;
-
-	explicit __codecvt_utf16(size_t __refs, unsigned long _Maxcode, codecvt_mode _Mode) : codecvt<wchar_t, char, mbstate_t>(__refs), _Maxcode_(_Maxcode), _Mode_(_Mode) { }
-protected:
-	virtual result do_out(state_type &, const intern_type *frm, const intern_type *frm_end, const intern_type *&frm_nxt, extern_type *to, extern_type *to_end, extern_type *&to_nxt) const
-	{
-		auto _frm = reinterpret_cast<const uint32_t *>(frm);
-		auto _frm_end = reinterpret_cast<const uint32_t *>(frm_end);
-		auto _frm_nxt = _frm;
-		auto _to = reinterpret_cast<uint8_t *>(to);
-		auto _to_end = reinterpret_cast<uint8_t *>(to_end);
-		auto _to_nxt = _to;
-		auto r = UnicodeConverters::ucs4_to_utf16be(_frm, _frm_end, _frm_nxt, _to, _to_end, _to_nxt, this->_Maxcode_, this->_Mode_);
-		frm_nxt = frm + (_frm_nxt - _frm);
-		to_nxt = to + (_to_nxt - _to);
-		return r;
-	}
-	virtual result do_in(state_type &, const extern_type *frm, const extern_type *frm_end, const extern_type *&frm_nxt, intern_type *to, intern_type *to_end, intern_type *&to_nxt) const
-	{
-		auto _frm = reinterpret_cast<const uint8_t *>(frm);
-		auto _frm_end = reinterpret_cast<const uint8_t *>(frm_end);
-		auto _frm_nxt = _frm;
-		auto _to = reinterpret_cast<uint32_t *>(to);
-		auto _to_end = reinterpret_cast<uint32_t *>(to_end);
-		auto _to_nxt = _to;
-		auto r = UnicodeConverters::utf16be_to_ucs4(_frm, _frm_end, _frm_nxt, _to, _to_end, _to_nxt, this->_Maxcode_, this->_Mode_);
-		frm_nxt = frm + (_frm_nxt - _frm);
-		to_nxt = to + (_to_nxt - _to);
-		return r;
-	}
-	virtual result do_unshift(state_type &, extern_type *to, extern_type *, extern_type *&to_nxt) const
-	{
-		to_nxt = to;
-		return noconv;
-	}
-	virtual int do_encoding() const noexcept { return 0; }
-	virtual bool do_always_noconv() const noexcept { return false; }
-	virtual int do_length(state_type &, const extern_type *frm, const extern_type *frm_end, size_t mx) const
-	{
-		auto _frm = reinterpret_cast<const uint8_t *>(frm);
-		auto _frm_end = reinterpret_cast<const uint8_t *>(frm_end);
-		return UnicodeConverters::utf16be_to_ucs4_length(_frm, _frm_end, mx, this->_Maxcode_, this->_Mode_);
-	}
-	virtual int do_max_length() const noexcept
-	{
-		if (this->_Mode_ & consume_header)
-			return 6;
-		return 4;
-	}
-};
-
-template<> class __codecvt_utf16<wchar_t, true> : public codecvt<wchar_t, char, mbstate_t>
-{
-	unsigned long _Maxcode_;
-	codecvt_mode _Mode_;
-public:
-	typedef wchar_t intern_type;
-	typedef char extern_type;
-	typedef mbstate_t state_type;
-
-	explicit __codecvt_utf16(size_t __refs, unsigned long _Maxcode, codecvt_mode _Mode) : codecvt<wchar_t, char, mbstate_t>(__refs), _Maxcode_(_Maxcode), _Mode_(_Mode) { }
-protected:
-	virtual result do_out(state_type &, const intern_type *frm, const intern_type *frm_end, const intern_type *&frm_nxt, extern_type *to, extern_type *to_end, extern_type *&to_nxt) const
-	{
-		auto _frm = reinterpret_cast<const uint32_t *>(frm);
-		auto _frm_end = reinterpret_cast<const uint32_t *>(frm_end);
-		auto _frm_nxt = _frm;
-		auto _to = reinterpret_cast<uint8_t *>(to);
-		auto _to_end = reinterpret_cast<uint8_t *>(to_end);
-		auto _to_nxt = _to;
-		auto r = UnicodeConverters::ucs4_to_utf16le(_frm, _frm_end, _frm_nxt, _to, _to_end, _to_nxt, this->_Maxcode_, this->_Mode_);
-		frm_nxt = frm + (_frm_nxt - _frm);
-		to_nxt = to + (_to_nxt - _to);
-		return r;
-	}
-	virtual result do_in(state_type &, const extern_type *frm, const extern_type *frm_end, const extern_type *&frm_nxt, intern_type *to, intern_type *to_end, intern_type *&to_nxt) const
-	{
-		auto _frm = reinterpret_cast<const uint8_t *>(frm);
-		auto _frm_end = reinterpret_cast<const uint8_t *>(frm_end);
-		auto _frm_nxt = _frm;
-		auto _to = reinterpret_cast<uint32_t *>(to);
-		auto _to_end = reinterpret_cast<uint32_t *>(to_end);
-		auto _to_nxt = _to;
-		auto r = UnicodeConverters::utf16le_to_ucs4(_frm, _frm_end, _frm_nxt, _to, _to_end, _to_nxt, this->_Maxcode_, this->_Mode_);
-		frm_nxt = frm + (_frm_nxt - _frm);
-		to_nxt = to + (_to_nxt - _to);
-		return r;
-	}
-	virtual result do_unshift(state_type &, extern_type *to, extern_type *, extern_type *&to_nxt) const
-	{
-		to_nxt = to;
-		return noconv;
-	}
-	virtual int do_encoding() const noexcept { return 0; }
-	virtual bool do_always_noconv() const noexcept { return false; }
-	virtual int do_length(state_type &, const extern_type *frm, const extern_type *frm_end, size_t mx) const
-	{
-		auto _frm = reinterpret_cast<const uint8_t *>(frm);
-		auto _frm_end = reinterpret_cast<const uint8_t *>(frm_end);
-		return UnicodeConverters::utf16le_to_ucs4_length(_frm, _frm_end, mx, this->_Maxcode_, this->_Mode_);
-	}
-	virtual int do_max_length() const noexcept
-	{
-		if (this->_Mode_ & consume_header)
-			return 6;
-		return 4;
-	}
-};
-
-template<> class __codecvt_utf16<char16_t, false> : public codecvt<char16_t, char, mbstate_t>
-{
-	unsigned long _Maxcode_;
-	codecvt_mode _Mode_;
-public:
-	typedef char16_t intern_type;
-	typedef char extern_type;
-	typedef mbstate_t state_type;
-
-	explicit __codecvt_utf16(size_t __refs, unsigned long _Maxcode, codecvt_mode _Mode) : codecvt<char16_t, char, mbstate_t>(__refs), _Maxcode_(_Maxcode), _Mode_(_Mode) { }
-protected:
-	virtual result do_out(state_type &, const intern_type *frm, const intern_type *frm_end, const intern_type *&frm_nxt, extern_type *to, extern_type *to_end, extern_type *&to_nxt) const
-	{
-		auto _frm = reinterpret_cast<const uint16_t *>(frm);
-		auto _frm_end = reinterpret_cast<const uint16_t *>(frm_end);
-		auto _frm_nxt = _frm;
-		auto _to = reinterpret_cast<uint8_t *>(to);
-		auto _to_end = reinterpret_cast<uint8_t *>(to_end);
-		auto _to_nxt = _to;
-		auto r = UnicodeConverters::ucs2_to_utf16be(_frm, _frm_end, _frm_nxt, _to, _to_end, _to_nxt, this->_Maxcode_, this->_Mode_);
-		frm_nxt = frm + (_frm_nxt - _frm);
-		to_nxt = to + (_to_nxt - _to);
-		return r;
-	}
-	virtual result do_in(state_type &, const extern_type *frm, const extern_type *frm_end, const extern_type *&frm_nxt, intern_type *to, intern_type *to_end, intern_type *&to_nxt) const
-	{
-		auto _frm = reinterpret_cast<const uint8_t *>(frm);
-		auto _frm_end = reinterpret_cast<const uint8_t *>(frm_end);
-		auto _frm_nxt = _frm;
-		auto _to = reinterpret_cast<uint16_t *>(to);
-		auto _to_end = reinterpret_cast<uint16_t *>(to_end);
-		auto _to_nxt = _to;
-		auto r = UnicodeConverters::utf16be_to_ucs2(_frm, _frm_end, _frm_nxt, _to, _to_end, _to_nxt, this->_Maxcode_, this->_Mode_);
-		frm_nxt = frm + (_frm_nxt - _frm);
-		to_nxt = to + (_to_nxt - _to);
-		return r;
-	}
-	virtual result do_unshift(state_type &, extern_type *to, extern_type *, extern_type *&to_nxt) const
-	{
-		to_nxt = to;
-		return noconv;
-	}
-	virtual int do_encoding() const noexcept { return 0; }
-	virtual bool do_always_noconv() const noexcept { return false; }
-	virtual int do_length(state_type &, const extern_type *frm, const extern_type *frm_end, size_t mx) const
-	{
-		auto _frm = reinterpret_cast<const uint8_t *>(frm);
-		auto _frm_end = reinterpret_cast<const uint8_t *>(frm_end);
-		return UnicodeConverters::utf16be_to_ucs2_length(_frm, _frm_end, mx, this->_Maxcode_, this->_Mode_);
-	}
-	virtual int do_max_length() const noexcept
-	{
-		if (this->_Mode_ & consume_header)
-			return 4;
-		return 2;
-	}
-};
-
-template<> class __codecvt_utf16<char16_t, true> : public codecvt<char16_t, char, mbstate_t>
-{
-	unsigned long _Maxcode_;
-	codecvt_mode _Mode_;
-public:
-	typedef char16_t intern_type;
-	typedef char extern_type;
-	typedef mbstate_t state_type;
-
-	explicit __codecvt_utf16(size_t __refs, unsigned long _Maxcode, codecvt_mode _Mode) : codecvt<char16_t, char, mbstate_t>(__refs), _Maxcode_(_Maxcode), _Mode_(_Mode) { }
-protected:
-	virtual result do_out(state_type &, const intern_type *frm, const intern_type *frm_end, const intern_type *&frm_nxt, extern_type *to, extern_type *to_end, extern_type *&to_nxt) const
-	{
-		auto _frm = reinterpret_cast<const uint16_t *>(frm);
-		auto _frm_end = reinterpret_cast<const uint16_t *>(frm_end);
-		auto _frm_nxt = _frm;
-		auto _to = reinterpret_cast<uint8_t *>(to);
-		auto _to_end = reinterpret_cast<uint8_t *>(to_end);
-		auto _to_nxt = _to;
-		auto r = UnicodeConverters::ucs2_to_utf16le(_frm, _frm_end, _frm_nxt, _to, _to_end, _to_nxt, this->_Maxcode_, this->_Mode_);
-		frm_nxt = frm + (_frm_nxt - _frm);
-		to_nxt = to + (_to_nxt - _to);
-		return r;
-	}
-	virtual result do_in(state_type &, const extern_type *frm, const extern_type *frm_end, const extern_type *&frm_nxt, intern_type *to, intern_type *to_end, intern_type *&to_nxt) const
-	{
-		auto _frm = reinterpret_cast<const uint8_t *>(frm);
-		auto _frm_end = reinterpret_cast<const uint8_t *>(frm_end);
-		auto _frm_nxt = _frm;
-		auto _to = reinterpret_cast<uint16_t *>(to);
-		auto _to_end = reinterpret_cast<uint16_t *>(to_end);
-		auto _to_nxt = _to;
-		auto r = UnicodeConverters::utf16le_to_ucs2(_frm, _frm_end, _frm_nxt, _to, _to_end, _to_nxt, this->_Maxcode_, this->_Mode_);
-		frm_nxt = frm + (_frm_nxt - _frm);
-		to_nxt = to + (_to_nxt - _to);
-		return r;
-	}
-	virtual result do_unshift(state_type &, extern_type *to, extern_type *, extern_type *&to_nxt) const
-	{
-		to_nxt = to;
-		return noconv;
-	}
-	virtual int do_encoding() const noexcept { return 0; }
-	virtual bool do_always_noconv() const noexcept { return false; }
-	virtual int do_length(state_type &, const extern_type *frm, const extern_type *frm_end, size_t mx) const
-	{
-		auto _frm = reinterpret_cast<const uint8_t *>(frm);
-		auto _frm_end = reinterpret_cast<const uint8_t *>(frm_end);
-		return UnicodeConverters::utf16le_to_ucs2_length(_frm, _frm_end, mx, this->_Maxcode_, this->_Mode_);
-	}
-	virtual int do_max_length() const noexcept
-	{
-		if (this->_Mode_ & consume_header)
-			return 4;
-		return 2;
-	}
-};
-
-template<> class __codecvt_utf16<char32_t, false> : public codecvt<char32_t, char, mbstate_t>
-{
-	unsigned long _Maxcode_;
-	codecvt_mode _Mode_;
-public:
-	typedef char32_t intern_type;
-	typedef char extern_type;
-	typedef mbstate_t state_type;
-
-	explicit __codecvt_utf16(size_t __refs, unsigned long _Maxcode, codecvt_mode _Mode) : codecvt<char32_t, char, mbstate_t>(__refs), _Maxcode_(_Maxcode), _Mode_(_Mode) { }
-protected:
-	virtual result do_out(state_type &, const intern_type *frm, const intern_type *frm_end, const intern_type *&frm_nxt, extern_type *to, extern_type *to_end, extern_type *&to_nxt) const
-	{
-		auto _frm = reinterpret_cast<const uint32_t *>(frm);
-		auto _frm_end = reinterpret_cast<const uint32_t *>(frm_end);
-		auto _frm_nxt = _frm;
-		auto _to = reinterpret_cast<uint8_t *>(to);
-		auto _to_end = reinterpret_cast<uint8_t *>(to_end);
-		auto _to_nxt = _to;
-		auto r = UnicodeConverters::ucs4_to_utf16be(_frm, _frm_end, _frm_nxt, _to, _to_end, _to_nxt, this->_Maxcode_, this->_Mode_);
-		frm_nxt = frm + (_frm_nxt - _frm);
-		to_nxt = to + (_to_nxt - _to);
-		return r;
-	}
-	virtual result do_in(state_type &, const extern_type *frm, const extern_type *frm_end, const extern_type *&frm_nxt, intern_type *to, intern_type *to_end, intern_type *&to_nxt) const
-	{
-		auto _frm = reinterpret_cast<const uint8_t *>(frm);
-		auto _frm_end = reinterpret_cast<const uint8_t *>(frm_end);
-		auto _frm_nxt = _frm;
-		auto _to = reinterpret_cast<uint32_t *>(to);
-		auto _to_end = reinterpret_cast<uint32_t *>(to_end);
-		auto _to_nxt = _to;
-		auto r = UnicodeConverters::utf16be_to_ucs4(_frm, _frm_end, _frm_nxt, _to, _to_end, _to_nxt, this->_Maxcode_, this->_Mode_);
-		frm_nxt = frm + (_frm_nxt - _frm);
-		to_nxt = to + (_to_nxt - _to);
-		return r;
-	}
-	virtual result do_unshift(state_type &, extern_type *to, extern_type *, extern_type *&to_nxt) const
-	{
-		to_nxt = to;
-		return noconv;
-	}
-	virtual int do_encoding() const noexcept { return 0; }
-	virtual bool do_always_noconv() const noexcept { return false; }
-	virtual int do_length(state_type &, const extern_type *frm, const extern_type *frm_end, size_t mx) const
-	{
-		auto _frm = reinterpret_cast<const uint8_t *>(frm);
-		auto _frm_end = reinterpret_cast<const uint8_t *>(frm_end);
-		return UnicodeConverters::utf16be_to_ucs4_length(_frm, _frm_end, mx, this->_Maxcode_, this->_Mode_);
-	}
-	virtual int do_max_length() const noexcept
-	{
-		if (this->_Mode_ & consume_header)
-			return 6;
-		return 4;
-	}
-};
-
-template<> class __codecvt_utf16<char32_t, true> : public codecvt<char32_t, char, mbstate_t>
-{
-	unsigned long _Maxcode_;
-	codecvt_mode _Mode_;
-public:
-	typedef char32_t intern_type;
-	typedef char extern_type;
-	typedef mbstate_t state_type;
-
-	explicit __codecvt_utf16(size_t __refs, unsigned long _Maxcode, codecvt_mode _Mode) : codecvt<char32_t, char, mbstate_t>(__refs), _Maxcode_(_Maxcode), _Mode_(_Mode) { }
-protected:
-	virtual result do_out(state_type &, const intern_type *frm, const intern_type *frm_end, const intern_type *&frm_nxt, extern_type *to, extern_type *to_end, extern_type *&to_nxt) const
-	{
-		auto _frm = reinterpret_cast<const uint32_t *>(frm);
-		auto _frm_end = reinterpret_cast<const uint32_t *>(frm_end);
-		auto _frm_nxt = _frm;
-		auto _to = reinterpret_cast<uint8_t *>(to);
-		auto _to_end = reinterpret_cast<uint8_t *>(to_end);
-		auto _to_nxt = _to;
-		auto r = UnicodeConverters::ucs4_to_utf16le(_frm, _frm_end, _frm_nxt, _to, _to_end, _to_nxt, this->_Maxcode_, this->_Mode_);
-		frm_nxt = frm + (_frm_nxt - _frm);
-		to_nxt = to + (_to_nxt - _to);
-		return r;
-	}
-	virtual result do_in(state_type &, const extern_type *frm, const extern_type *frm_end, const extern_type *&frm_nxt, intern_type *to, intern_type *to_end, intern_type *&to_nxt) const
-	{
-		auto _frm = reinterpret_cast<const uint8_t *>(frm);
-		auto _frm_end = reinterpret_cast<const uint8_t *>(frm_end);
-		auto _frm_nxt = _frm;
-		auto _to = reinterpret_cast<uint32_t *>(to);
-		auto _to_end = reinterpret_cast<uint32_t *>(to_end);
-		auto _to_nxt = _to;
-		auto r = UnicodeConverters::utf16le_to_ucs4(_frm, _frm_end, _frm_nxt, _to, _to_end, _to_nxt, this->_Maxcode_, this->_Mode_);
-		frm_nxt = frm + (_frm_nxt - _frm);
-		to_nxt = to + (_to_nxt - _to);
-		return r;
-	}
-	virtual result do_unshift(state_type &, extern_type *to, extern_type *, extern_type *&to_nxt) const
-	{
-		to_nxt = to;
-		return noconv;
-	}
-	virtual int do_encoding() const noexcept { return 0; }
-	virtual bool do_always_noconv() const noexcept { return false; }
-	virtual int do_length(state_type &, const extern_type *frm, const extern_type *frm_end, size_t mx) const
-	{
-		auto _frm = reinterpret_cast<const uint8_t *>(frm);
-		auto _frm_end = reinterpret_cast<const uint8_t *>(frm_end);
-		return UnicodeConverters::utf16le_to_ucs4_length(_frm, _frm_end, mx, this->_Maxcode_, this->_Mode_);
-	}
-	virtual int do_max_length() const noexcept
-	{
-		if (this->_Mode_ & consume_header)
-			return 6;
-		return 4;
-	}
-};
-
-template<class _Elem, unsigned long _Maxcode = 0x10ffff, codecvt_mode _Mode = static_cast<codecvt_mode>(0)> class codecvt_utf16 : public __codecvt_utf16<_Elem, _Mode & little_endian>
-{
-public:
-	explicit codecvt_utf16(size_t __refs = 0) : __codecvt_utf16<_Elem, _Mode & little_endian>(__refs, _Maxcode, _Mode) { }
-
-	~codecvt_utf16() { }
-};
-
-template<class _Elem> class __codecvt_utf8_utf16;
-
-template<> class __codecvt_utf8_utf16<wchar_t> : public codecvt<wchar_t, char, mbstate_t>
-{
-	unsigned long _Maxcode_;
-	codecvt_mode _Mode_;
-public:
-	typedef wchar_t intern_type;
-	typedef char extern_type;
-	typedef mbstate_t state_type;
-
-	explicit __codecvt_utf8_utf16(size_t __refs, unsigned long _Maxcode, codecvt_mode _Mode) : codecvt<wchar_t, char, mbstate_t>(__refs), _Maxcode_(_Maxcode), _Mode_(_Mode) { }
-protected:
-	virtual result do_out(state_type &, const intern_type *frm, const intern_type *frm_end, const intern_type *&frm_nxt, extern_type *to, extern_type *to_end, extern_type *&to_nxt) const
-	{
-		auto _frm = reinterpret_cast<const uint32_t *>(frm);
-		auto _frm_end = reinterpret_cast<const uint32_t *>(frm_end);
-		auto _frm_nxt = _frm;
-		auto _to = reinterpret_cast<uint8_t *>(to);
-		auto _to_end = reinterpret_cast<uint8_t *>(to_end);
-		auto _to_nxt = _to;
-		auto r = UnicodeConverters::utf16_to_utf8(_frm, _frm_end, _frm_nxt, _to, _to_end, _to_nxt, this->_Maxcode_, this->_Mode_);
-		frm_nxt = frm + (_frm_nxt - _frm);
-		to_nxt = to + (_to_nxt - _to);
-		return r;
-	}
-	virtual result do_in(state_type &, const extern_type *frm, const extern_type *frm_end, const extern_type *&frm_nxt, intern_type *to, intern_type *to_end, intern_type *&to_nxt) const
-	{
-		auto _frm = reinterpret_cast<const uint8_t *>(frm);
-		auto _frm_end = reinterpret_cast<const uint8_t *>(frm_end);
-		auto _frm_nxt = _frm;
-		auto _to = reinterpret_cast<uint32_t *>(to);
-		auto _to_end = reinterpret_cast<uint32_t *>(to_end);
-		auto _to_nxt = _to;
-		auto r = UnicodeConverters::utf8_to_utf16(_frm, _frm_end, _frm_nxt, _to, _to_end, _to_nxt, this->_Maxcode_, this->_Mode_);
-		frm_nxt = frm + (_frm_nxt - _frm);
-		to_nxt = to + (_to_nxt - _to);
-		return r;
-	}
-	virtual result do_unshift(state_type &, extern_type *to, extern_type *, extern_type *&to_nxt) const
-	{
-		to_nxt = to;
-		return noconv;
-	}
-	virtual int do_encoding() const noexcept { return 0; }
-	virtual bool do_always_noconv() const noexcept { return false; }
-	virtual int do_length(state_type &, const extern_type *frm, const extern_type *frm_end, size_t mx) const
-	{
-		auto _frm = reinterpret_cast<const uint8_t *>(frm);
-		auto _frm_end = reinterpret_cast<const uint8_t *>(frm_end);
-		return UnicodeConverters::utf8_to_utf16_length(_frm, _frm_end, mx, this->_Maxcode_, this->_Mode_);
-	}
-	virtual int do_max_length() const noexcept
-	{
-		if (this->_Mode_ & consume_header)
-			return 7;
-		return 4;
-	}
-};
-
-template<> class __codecvt_utf8_utf16<char32_t> : public codecvt<char32_t, char, mbstate_t>
-{
-	unsigned long _Maxcode_;
-	codecvt_mode _Mode_;
-public:
-	typedef char32_t intern_type;
-	typedef char extern_type;
-	typedef mbstate_t state_type;
-
-	explicit __codecvt_utf8_utf16(size_t __refs, unsigned long _Maxcode, codecvt_mode _Mode) : codecvt<char32_t, char, mbstate_t>(__refs), _Maxcode_(_Maxcode), _Mode_(_Mode) { }
-protected:
-	virtual result do_out(state_type &, const intern_type *frm, const intern_type *frm_end, const intern_type *&frm_nxt, extern_type *to, extern_type *to_end, extern_type *&to_nxt) const
-	{
-		auto _frm = reinterpret_cast<const uint32_t *>(frm);
-		auto _frm_end = reinterpret_cast<const uint32_t *>(frm_end);
-		auto _frm_nxt = _frm;
-		auto _to = reinterpret_cast<uint8_t *>(to);
-		auto _to_end = reinterpret_cast<uint8_t *>(to_end);
-		auto _to_nxt = _to;
-		auto r = UnicodeConverters::utf16_to_utf8(_frm, _frm_end, _frm_nxt, _to, _to_end, _to_nxt, this->_Maxcode_, this->_Mode_);
-		frm_nxt = frm + (_frm_nxt - _frm);
-		to_nxt = to + (_to_nxt - _to);
-		return r;
-	}
-	virtual result do_in(state_type &, const extern_type *frm, const extern_type *frm_end, const extern_type *&frm_nxt, intern_type *to, intern_type *to_end, intern_type *&to_nxt) const
-	{
-		auto _frm = reinterpret_cast<const uint8_t *>(frm);
-		auto _frm_end = reinterpret_cast<const uint8_t *>(frm_end);
-		auto _frm_nxt = _frm;
-		auto _to = reinterpret_cast<uint32_t *>(to);
-		auto _to_end = reinterpret_cast<uint32_t *>(to_end);
-		auto _to_nxt = _to;
-		auto r = UnicodeConverters::utf8_to_utf16(_frm, _frm_end, _frm_nxt, _to, _to_end, _to_nxt, this->_Maxcode_, this->_Mode_);
-		frm_nxt = frm + (_frm_nxt - _frm);
-		to_nxt = to + (_to_nxt - _to);
-		return r;
-	}
-	virtual result do_unshift(state_type &, extern_type *to, extern_type *, extern_type *&to_nxt) const
-	{
-		to_nxt = to;
-		return noconv;
-	}
-	virtual int do_encoding() const noexcept { return 0; }
-	virtual bool do_always_noconv() const noexcept { return false; }
-	virtual int do_length(state_type &, const extern_type *frm, const extern_type *frm_end, size_t mx) const
-	{
-		auto _frm = reinterpret_cast<const uint8_t *>(frm);
-		auto _frm_end = reinterpret_cast<const uint8_t *>(frm_end);
-		return UnicodeConverters::utf8_to_utf16_length(_frm, _frm_end, mx, this->_Maxcode_, this->_Mode_);
-	}
-	virtual int do_max_length() const noexcept
-	{
-		if (this->_Mode_ & consume_header)
-			return 7;
-		return 4;
-	}
-};
-
-template<> class __codecvt_utf8_utf16<char16_t> : public codecvt<char16_t, char, mbstate_t>
-{
-	unsigned long _Maxcode_;
-	codecvt_mode _Mode_;
-public:
-	typedef char16_t intern_type;
-	typedef char extern_type;
-	typedef mbstate_t state_type;
-
-	explicit __codecvt_utf8_utf16(size_t __refs, unsigned long _Maxcode, codecvt_mode _Mode) : codecvt<char16_t, char, mbstate_t>(__refs), _Maxcode_(_Maxcode), _Mode_(_Mode) { }
-protected:
-	virtual result do_out(state_type &, const intern_type *frm, const intern_type *frm_end, const intern_type *&frm_nxt, extern_type *to, extern_type *to_end, extern_type *&to_nxt) const
-	{
-		auto _frm = reinterpret_cast<const uint16_t *>(frm);
-		auto _frm_end = reinterpret_cast<const uint16_t *>(frm_end);
-		auto _frm_nxt = _frm;
-		auto _to = reinterpret_cast<uint8_t *>(to);
-		auto _to_end = reinterpret_cast<uint8_t *>(to_end);
-		auto _to_nxt = _to;
-		auto r = UnicodeConverters::utf16_to_utf8(_frm, _frm_end, _frm_nxt, _to, _to_end, _to_nxt, this->_Maxcode_, this->_Mode_);
-		frm_nxt = frm + (_frm_nxt - _frm);
-		to_nxt = to + (_to_nxt - _to);
-		return r;
-	}
-	virtual result do_in(state_type &, const extern_type *frm, const extern_type *frm_end, const extern_type *&frm_nxt, intern_type *to, intern_type *to_end, intern_type *&to_nxt) const
-	{
-		auto _frm = reinterpret_cast<const uint8_t *>(frm);
-		auto _frm_end = reinterpret_cast<const uint8_t *>(frm_end);
-		auto _frm_nxt = _frm;
-		auto _to = reinterpret_cast<uint16_t *>(to);
-		auto _to_end = reinterpret_cast<uint16_t *>(to_end);
-		auto _to_nxt = _to;
-		auto r = UnicodeConverters::utf8_to_utf16(_frm, _frm_end, _frm_nxt, _to, _to_end, _to_nxt, this->_Maxcode_, this->_Mode_);
-		frm_nxt = frm + (_frm_nxt - _frm);
-		to_nxt = to + (_to_nxt - _to);
-		return r;
-	}
-	virtual result do_unshift(state_type &, extern_type *to, extern_type *, extern_type *&to_nxt) const
-	{
-		to_nxt = to;
-		return noconv;
-	}
-	virtual int do_encoding() const noexcept { return 0; }
-	virtual bool do_always_noconv() const noexcept { return false; }
-	virtual int do_length(state_type &, const extern_type *frm, const extern_type *frm_end, size_t mx) const
-	{
-		auto _frm = reinterpret_cast<const uint8_t *>(frm);
-		auto _frm_end = reinterpret_cast<const uint8_t *>(frm_end);
-		return UnicodeConverters::utf8_to_utf16_length(_frm, _frm_end, mx, this->_Maxcode_, this->_Mode_);
-	}
-	virtual int do_max_length() const noexcept
-	{
-		if (this->_Mode_ & consume_header)
-			return 7;
-		return 4;
-	}
-};
-
-template<class _Elem, unsigned long _Maxcode = 0x10ffff, codecvt_mode _Mode = static_cast<codecvt_mode>(0)> class codecvt_utf8_utf16 : public __codecvt_utf8_utf16<_Elem>
-{
-public:
-	explicit codecvt_utf8_utf16(size_t __refs = 0) : __codecvt_utf8_utf16<_Elem>(__refs, _Maxcode, _Mode) { }
-
-	~codecvt_utf8_utf16() {}
-};
-
-}
-#endif
-

--- a/src/in_xsf_framework/common.props
+++ b/src/in_xsf_framework/common.props
@@ -2,8 +2,8 @@
 <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
   <ImportGroup Label="PropertySheets" />
   <PropertyGroup Label="UserMacros">
-    <zlibRootDir>ZLIBFIXME</zlibRootDir>
-    <WinampSDKDir>WINAMPSDKFIXME</WinampSDKDir>
+    <zlibRootDir>$(MSBuildThisFileDirectory)\zlib</zlibRootDir>
+    <WinampSDKDir>$(MSBuildThisFileDirectory)\winamp</WinampSDKDir>
   </PropertyGroup>
   <PropertyGroup />
   <ItemDefinitionGroup />

--- a/src/in_xsf_framework/convert.h
+++ b/src/in_xsf_framework/convert.h
@@ -11,12 +11,7 @@
 #include <sstream>
 #include <typeinfo>
 #include <locale>
-#if (defined(__GNUC__) || defined(__clang__)) && !defined(_LIBCPP_VERSION)
-# include "wstring_convert.h"
-# include "codecvt.h"
-#else
-# include <codecvt>
-#endif
+#include <codecvt>
 #include <vector>
 #include <memory>
 #include <cmath>

--- a/src/in_xsf_framework/eqstr.h
+++ b/src/in_xsf_framework/eqstr.h
@@ -15,9 +15,9 @@
 #include <algorithm>
 #include <climits>
 
-struct eq_str : std::binary_function<std::string, std::string, bool>
+struct eq_str
 {
-	struct eq_char : std::binary_function<char, char, bool>
+	struct eq_char
 	{
 		const char *tab;
 		eq_char(const char *t) : tab(t) { }

--- a/src/in_xsf_framework/in_xsf.cpp
+++ b/src/in_xsf_framework/in_xsf.cpp
@@ -10,8 +10,8 @@
 #include "XSFConfig.h"
 #include "XSFCommon.h"
 #include "windowsh_wrapper.h"
-#include <winamp/in2.h>
-#include <winamp/wa_ipc.h>
+#include "winamp/in2.h"
+#include "winamp/wa_ipc.h"
 
 #if (defined(__GNUC__) || defined(__clang__)) && !defined(_LIBCPP_VERSION)
 std::locale::id std::codecvt<char16_t, char, mbstate_t>::id;

--- a/src/in_xsf_framework/ltstr.h
+++ b/src/in_xsf_framework/ltstr.h
@@ -15,9 +15,9 @@
 #include <algorithm>
 #include <climits>
 
-struct lt_str : std::binary_function<std::string, std::string, bool>
+struct lt_str
 {
-	struct lt_char : std::binary_function<char, char, bool>
+	struct lt_char
 	{
 		const char *tab;
 		lt_char(const char *t) : tab(t) { }

--- /dev/null
+++ b/src/in_xsf_framework/winamp/in2.h
@@ -1,1 +1,138 @@
+#ifndef NULLSOFT_WINAMP_IN2H

+#define NULLSOFT_WINAMP_IN2H

+#include "out.h"

+

+// note: exported symbol is now winampGetInModule2.

+

+#define IN_UNICODE 0x0F000000

+

+#ifdef UNICODE_INPUT_PLUGIN

+#define in_char wchar_t

+#define IN_VER (IN_UNICODE | 0x100)

+#else

+#define in_char char

+#define IN_VER 0x100

+#endif

+

+#define IN_MODULE_FLAG_USES_OUTPUT_PLUGIN 1

+// By default, Winamp assumes that your input plugin wants to use Winamp's EQ, and doesn't do replay gain

+// if you handle any of these yourself (EQ, Replay Gain adjustments), then set these flags accordingly

+#define IN_MODULE_FLAG_EQ 2 // set this if you do your own EQ

+#define IN_MODULE_FLAG_REPLAYGAIN 8 // set this if you adjusted volume for replay gain

+                                                                        // for tracks with no replay gain metadata, you should clear this flag

+                                                                        // UNLESS you handle "non_replaygain" gain adjustment yourself

+#define IN_MODULE_FLAG_REPLAYGAIN_PREAMP 16 // use this if you queried for the replay gain preamp parameter and used it

+                                                                                        // this parameter is new to 5.54

+typedef struct 

+{

+    int version;                // module type (IN_VER)

+    char *description;          // description of module, with version string

+

+    HWND hMainWindow;           // winamp's main window (filled in by winamp)

+    HINSTANCE hDllInstance;     // DLL instance handle (Also filled in by winamp)

+

+    char *FileExtensions;       // "mp3\0Layer 3 MPEG\0mp2\0Layer 2 MPEG\0mpg\0Layer 1 MPEG\0"

+                                // May be altered from Config, so the user can select what they want

+

+    int is_seekable;            // is this stream seekable?

+    int UsesOutputPlug;         // does this plug-in use the output plug-ins? (musn't ever change, ever :)

+                                                    // note that this has turned into a "flags" field

+                                                    // see IN_MODULE_FLAG_*

+

+    void (*Config)(HWND hwndParent); // configuration dialog

+    void (*About)(HWND hwndParent);  // about dialog

+

+    void (*Init)();             // called at program init

+    void (*Quit)();             // called at program quit

+

+#define GETFILEINFO_TITLE_LENGTH 2048

+    void (*GetFileInfo)(const in_char *file, in_char *title, int *length_in_ms); // if file == NULL, current playing is used

+

+#define INFOBOX_EDITED 0

+#define INFOBOX_UNCHANGED 1

+    int (*InfoBox)(const in_char *file, HWND hwndParent);

+

+    int (*IsOurFile)(const in_char *fn);    // called before extension checks, to allow detection of mms://, etc

+    // playback stuff

+    int (*Play)(const in_char *fn);     // return zero on success, -1 on file-not-found, some other value on other (stopping winamp) error

+    void (*Pause)();            // pause stream

+    void (*UnPause)();          // unpause stream

+    int (*IsPaused)();          // ispaused? return 1 if paused, 0 if not

+    void (*Stop)();             // stop (unload) stream

+

+    // time stuff

+    int (*GetLength)();         // get length in ms

+    int (*GetOutputTime)();     // returns current output time in ms. (usually returns outMod->GetOutputTime()

+    void (*SetOutputTime)(int time_in_ms);  // seeks to point in stream (in ms). Usually you signal your thread to seek, which seeks and calls outMod->Flush()..

+

+    // volume stuff

+    void (*SetVolume)(int volume);  // from 0 to 255.. usually just call outMod->SetVolume

+    void (*SetPan)(int pan);    // from -127 to 127.. usually just call outMod->SetPan

+

+    // in-window builtin vis stuff

+

+    void (*SAVSAInit)(int maxlatency_in_ms, int srate);     // call once in Play(). maxlatency_in_ms should be the value returned from outMod->Open()

+    // call after opening audio device with max latency in ms and samplerate

+    void (*SAVSADeInit)();  // call in Stop()

+

+

+    // simple vis supplying mode

+    void (*SAAddPCMData)(void *PCMData, int nch, int bps, int timestamp);

+                                            // sets the spec data directly from PCM data

+                                            // quick and easy way to get vis working :)

+                                            // needs at least 576 samples :)

+

+    // advanced vis supplying mode, only use if you're cool. Use SAAddPCMData for most stuff.

+    int (*SAGetMode)();     // gets csa (the current type (4=ws,2=osc,1=spec))

+                            // use when calling SAAdd()

+    int (*SAAdd)(void *data, int timestamp, int csa); // sets the spec data, filled in by winamp

+

+

+    // vis stuff (plug-in)

+    // simple vis supplying mode

+    void (*VSAAddPCMData)(void *PCMData, int nch, int bps, int timestamp); // sets the vis data directly from PCM data

+                                            // quick and easy way to get vis working :)

+                                            // needs at least 576 samples :)

+

+    // advanced vis supplying mode, only use if you're cool. Use VSAAddPCMData for most stuff.

+    int (*VSAGetMode)(int *specNch, int *waveNch); // use to figure out what to give to VSAAdd

+    int (*VSAAdd)(void *data, int timestamp); // filled in by winamp, called by plug-in

+

+

+    // call this in Play() to tell the vis plug-ins the current output params.

+    void (*VSASetInfo)(int srate, int nch); // <-- Correct (benski, dec 2005).. old declaration had the params backwards

+

+

+    // dsp plug-in processing:

+    // (filled in by winamp, calld by input plug)

+

+    // returns 1 if active (which means that the number of samples returned by dsp_dosamples

+    // could be greater than went in.. Use it to estimate if you'll have enough room in the

+    // output buffer

+    int (*dsp_isactive)();

+

+    // returns number of samples to output. This can be as much as twice numsamples.

+    // be sure to allocate enough buffer for samples, then.

+    int (*dsp_dosamples)(short int *samples, int numsamples, int bps, int nch, int srate);

+

+

+    // eq stuff

+    void (*EQSet)(int on, char data[10], int preamp); // 0-64 each, 31 is +0, 0 is +12, 63 is -12. Do nothing to ignore.

+

+    // info setting (filled in by winamp)

+    void (*SetInfo)(int bitrate, int srate, int stereo, int synched); // if -1, changes ignored? :)

+

+    Out_Module *outMod; // filled in by winamp, optionally used :)

+} In_Module;

+

+// return values from the winampUninstallPlugin(HINSTANCE hdll, HWND parent, int param)

+// which determine if we can uninstall the plugin immediately or on winamp restart

+//

+// uninstall support was added from 5.0+ and uninstall now support from 5.5+

+// it is down to you to ensure that if uninstall now is returned that it will not cause a crash

+// (ie don't use if you've been subclassing the main window)

+#define IN_PLUGIN_UNINSTALL_NOW    0x1

+#define IN_PLUGIN_UNINSTALL_REBOOT 0x0

+

+#endif

 

--- /dev/null
+++ b/src/in_xsf_framework/winamp/out.h
@@ -1,1 +1,74 @@
+#ifndef NULLSOFT_OUTH

+#define NULLSOFT_OUTH

+#include <windows.h>

+#include <stddef.h>

+// ids:

+// waveout: 32

+// gapless: 64

+// xfade: 63

+// disk: 33

+// dsound: 38

+// NULL: 65

+// mm2: 69

+

+#if defined(_MSC_VER) && (_MSC_VER <= 1200)

+typedef int intptr_t;

+#endif

+

+#define OUT_VER 0x10

+

+typedef struct

+{

+    int version;                // module version (OUT_VER)

+    char *description;          // description of module, with version string

+    intptr_t id;                        // module id. each input module gets its own. non-nullsoft modules should

+                                // be >= 65536.

+

+    HWND hMainWindow;           // winamp's main window (filled in by winamp)

+    HINSTANCE hDllInstance;     // DLL instance handle (filled in by winamp)

+

+    void (*Config)(HWND hwndParent); // configuration dialog

+    void (*About)(HWND hwndParent);  // about dialog

+

+    void (*Init)();             // called when loaded

+    void (*Quit)();             // called when unloaded

+

+    int (*Open)(int samplerate, int numchannels, int bitspersamp, int bufferlenms, int prebufferms);

+                    // returns >=0 on success, <0 on failure

+

+                    // NOTENOTENOTE: bufferlenms and prebufferms are ignored in most if not all output plug-ins.

+                    //    ... so don't expect the max latency returned to be what you asked for.

+                    // returns max latency in ms (0 for diskwriters, etc)

+                    // bufferlenms and prebufferms must be in ms. 0 to use defaults.

+                    // prebufferms must be <= bufferlenms

+                    // pass bufferlenms==-666 to tell the output plugin that it's clock is going to be used to sync video

+                    //   out_ds turns off silence-eating when -666 is passed

+

+    void (*Close)();    // close the ol' output device.

+

+    int (*Write)(char *buf, int len);

+                    // 0 on success. Len == bytes to write (<= 8192 always). buf is straight audio data.

+                    // 1 returns not able to write (yet). Non-blocking, always.

+

+    int (*CanWrite)();  // returns number of bytes possible to write at a given time.

+                        // Never will decrease unless you call Write (or Close, heh)

+

+    int (*IsPlaying)(); // non0 if output is still going or if data in buffers waiting to be

+                        // written (i.e. closing while IsPlaying() returns 1 would truncate the song

+

+    int (*Pause)(int pause); // returns previous pause state

+

+    void (*SetVolume)(int volume); // volume is 0-255

+    void (*SetPan)(int pan); // pan is -128 to 128

+

+    void (*Flush)(int t);   // flushes buffers and restarts output at time t (in ms)

+                            // (used for seeking)

+

+    int (*GetOutputTime)(); // returns played time in MS

+    int (*GetWrittenTime)(); // returns time written in MS (used for synching up vis stuff)

+

+} Out_Module;

+

+

+#endif

 

--- /dev/null
+++ b/src/in_xsf_framework/winamp/wa_ipc.h
@@ -1,1 +1,2471 @@
+/*

+** Copyright (C) 1997-2008 Nullsoft, Inc.

+**

+** This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held

+** liable for any damages arising from the use of this software.

+**

+** Permission is granted to anyone to use this software for any purpose, including commercial applications, and to

+** alter it and redistribute it freely, subject to the following restrictions:

+**

+**   1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software.

+**      If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.

+**

+**   2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.

+**

+**   3. This notice may not be removed or altered from any source distribution.

+**

+*/

+

+#ifndef _WA_IPC_H_

+#define _WA_IPC_H_

+

+#include <windows.h>

+#include <stddef.h>

+#if defined(_MSC_VER) && (_MSC_VER <= 1200)

+typedef int intptr_t;

+#endif

+/*

+** This is the modern replacement for the classic 'frontend.h'. Most of these

+** updates are designed for in-process use, i.e. from a plugin.

+**

+*/

+

+/* Most of the IPC_* messages involve sending the message in the form of:

+** result = SendMessage(hwnd_winamp,WM_WA_IPC,(parameter),IPC_*);

+** Where different then this is specified (typically with WM_COPYDATA variants)

+**

+** When you use SendMessage(hwnd_winamp,WM_WA_IPC,(parameter),IPC_*) and specify a IPC_*

+** which is not currently implemented/supported by the Winamp version being used then it

+** will return 1 for 'result'. This is a good way of helping to check if an api being

+** used which returns a function pointer, etc is even going to be valid.

+*/

+

+#define WM_WA_IPC WM_USER

+

+#define WINAMP_VERSION_MAJOR(winampVersion) ((winampVersion & 0x0000FF00) >> 12)

+#define WINAMP_VERSION_MINOR(winampVersion) (winampVersion & 0x000000FF)  // returns, i.e. 0x12 for 5.12 and 0x10 for 5.1...

+

+

+#define IPC_GETVERSION 0

+/* int version = SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETVERSION);

+**

+** The version returned will be 0x20yx for Winamp 2.yx.

+** Versions previous to Winamp 2.0 typically (but not always) use 0x1zyx for 1.zx.

+** Just a bit weird but that's the way it goes.

+**

+** For Winamp 5.x it uses the format 0x50yx for Winamp 5.yx

+** e.g.   5.01 -> 0x5001

+**        5.09 -> 0x5009

+**        5.1  -> 0x5010

+**

+** Notes: For 5.02 this api will return the same value as for a 5.01 build.

+**        For 5.07 this api will return the same value as for a 5.06 build.

+*/

+

+

+#define IPC_GETVERSIONSTRING 1

+

+

+#define IPC_GETREGISTEREDVERSION 770

+/* (requires Winamp 5.0+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETREGISTEREDVERSION);

+**

+** This will open the Winamp Preferences and show the Winamp Pro page.

+*/

+

+

+typedef struct {

+  const char *filename;

+  const char *title;

+  int length;

+} enqueueFileWithMetaStruct; // send this to a IPC_PLAYFILE in a non WM_COPYDATA,

+// and you get the nice desired result. if title is NULL, it is treated as a "thing",

+// otherwise it's assumed to be a file (for speed)

+

+typedef struct {

+  const wchar_t *filename;

+  const wchar_t *title;

+  int length;

+} enqueueFileWithMetaStructW;

+

+#define IPC_PLAYFILE 100  // dont be fooled, this is really the same as enqueufile

+#define IPC_ENQUEUEFILE 100

+#define IPC_PLAYFILEW 1100

+#define IPC_ENQUEUEFILEW 1100

+/* This is sent as a WM_COPYDATA with IPC_PLAYFILE as the dwData member and the string

+** of the file / playlist to be enqueued into the playlist editor as the lpData member.

+** This will just enqueue the file or files since you can use this to enqueue a playlist.

+** It will not clear the current playlist or change the playback state.

+**

+** COPYDATASTRUCT cds = {0};

+**   cds.dwData = IPC_ENQUEUEFILE;

+**   cds.lpData = (void*)"c:\\test\\folder\\test.mp3";

+**   cds.cbData = lstrlen((char*)cds.lpData)+1;  // include space for null char

+**   SendMessage(hwnd_winamp,WM_COPYDATA,0,(LPARAM)&cds);

+**

+**

+** With 2.9+ and all of the 5.x versions you can send this as a normal WM_WA_IPC

+** (non WM_COPYDATA) with an enqueueFileWithMetaStruct as the param.

+** If the title member is null then it is treated as a "thing" otherwise it will be

+** assumed to be a file (for speed).

+**

+** enqueueFileWithMetaStruct eFWMS = {0};

+**   eFWMS.filename = "c:\\test\\folder\\test.mp3";

+**   eFWMS.title = "Whipping Good";

+**   eFWMS.length = 300;  // this is the number of seconds for the track

+**   SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)&eFWMS,IPC_ENQUEUEFILE);

+*/

+

+

+#define IPC_DELETE 101

+#define IPC_DELETE_INT 1101

+/* SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_DELETE);

+** Use this api to clear Winamp's internal playlist.

+** You should not need to use IPC_DELETE_INT since it is used internally by Winamp when

+** it is dealing with some lame Windows Explorer issues (hard to believe that!).

+*/

+

+

+#define IPC_STARTPLAY 102

+#define IPC_STARTPLAY_INT 1102

+/* SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_STARTPLAY);

+** Sending this will start playback and is almost the same as hitting the play button.

+** The IPC_STARTPLAY_INT version is used internally and you should not need to use it

+** since it won't be any fun.

+*/

+

+

+#define IPC_CHDIR 103

+/* This is sent as a WM_COPYDATA type message with IPC_CHDIR as the dwData value and the

+** directory you want to change to as the lpData member.

+**

+** COPYDATASTRUCT cds = {0};

+**   cds.dwData = IPC_CHDIR;

+**   cds.lpData = (void*)"c:\\download";

+**   cds.cbData = lstrlen((char*)cds.lpData)+1; // include space for null char

+**   SendMessage(hwnd_winamp,WM_COPYDATA,0,(LPARAM)&cds);

+**

+** The above example will make Winamp change to the directory 'C:\download'.

+*/

+

+

+#define IPC_ISPLAYING 104

+/* int res = SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_ISPLAYING);

+** This is sent to retrieve the current playback state of Winamp.

+** If it returns 1, Winamp is playing.

+** If it returns 3, Winamp is paused.

+** If it returns 0, Winamp is not playing.

+*/

+

+

+#define IPC_GETOUTPUTTIME 105

+/* int res = SendMessage(hwnd_winamp,WM_WA_IPC,mode,IPC_GETOUTPUTTIME);

+** This api can return two different sets of information about current playback status.

+**

+** If mode = 0 then it will return the position (in ms) of the currently playing track.

+** Will return -1 if Winamp is not playing.

+**

+** If mode = 1 then it will return the current track length (in seconds).

+** Will return -1 if there are no tracks (or possibly if Winamp cannot get the length).

+**

+** If mode = 2 then it will return the current track length (in milliseconds).

+** Will return -1 if there are no tracks (or possibly if Winamp cannot get the length).

+*/

+

+

+#define IPC_JUMPTOTIME 106

+/* (requires Winamp 1.60+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,ms,IPC_JUMPTOTIME);

+** This api sets the current position (in milliseconds) for the currently playing song.

+** The resulting playback position may only be an approximate time since some playback

+** formats do not provide exact seeking e.g. mp3

+** This returns -1 if Winamp is not playing, 1 on end of file, or 0 if it was successful.

+*/

+

+

+#define IPC_GETMODULENAME 109

+#define IPC_EX_ISRIGHTEXE 666

+/* usually shouldnt bother using these, but here goes:

+** send a WM_COPYDATA with IPC_GETMODULENAME, and an internal

+** flag gets set, which if you send a normal WM_WA_IPC message with

+** IPC_EX_ISRIGHTEXE, it returns whether or not that filename

+** matches. lame, I know.

+*/

+

+

+#define IPC_WRITEPLAYLIST 120

+/* (requires Winamp 1.666+)

+** int cur = SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_WRITEPLAYLIST);

+**

+** IPC_WRITEPLAYLIST will write the current playlist to '<winampdir>\\Winamp.m3u' and

+** will also return the current playlist position (see IPC_GETLISTPOS).

+**

+** This is kinda obsoleted by some of the newer 2.x api items but it still is good for

+** use with a front-end program (instead of a plug-in) and you want to see what is in the

+** current playlist.

+**

+** This api will only save out extended file information in the #EXTINF entry if Winamp

+** has already read the data such as if the file was played of scrolled into view. If

+** Winamp has not read the data then you will only find the file with its filepath entry

+** (as is the base requirements for a m3u playlist).

+*/

+

+

+#define IPC_SETPLAYLISTPOS 121

+/* (requires Winamp 2.0+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,position,IPC_SETPLAYLISTPOS)

+** IPC_SETPLAYLISTPOS sets the playlist position to the specified 'position'.

+** It will not change playback status or anything else. It will just set the current

+** position in the playlist and will update the playlist view if necessary.

+**

+** If you use SendMessage(hwnd_winamp,WM_COMMAND,MAKEWPARAM(WINAMP_BUTTON2,0),0);

+** after using IPC_SETPLAYLISTPOS then Winamp will start playing the file at 'position'.

+*/

+

+

+#define IPC_SETVOLUME 122

+/* (requires Winamp 2.0+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,volume,IPC_SETVOLUME);

+** IPC_SETVOLUME sets the volume of Winamp (between the range of 0 to 255).

+**

+** If you pass 'volume' as -666 then the message will return the current volume.

+** int curvol = SendMessage(hwnd_winamp,WM_WA_IPC,-666,IPC_SETVOLUME);

+*/

+

+

+#define IPC_GETVOLUME(hwnd_winamp) SendMessage(hwnd_winamp,WM_WA_IPC,-666,IPC_SETVOLUME)

+/* (requires Winamp 2.0+)

+** int curvol = IPC_GETVOLUME(hwnd_winamp);

+** This will return the current volume of Winamp or

+*/

+

+

+#define IPC_SETPANNING 123

+/* (requires Winamp 2.0+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,panning,IPC_SETPANNING);

+** IPC_SETPANNING sets the panning of Winamp from 0 (left) to 255 (right).

+**

+** At least in 5.x+ this works from -127 (left) to 127 (right).

+**

+** If you pass 'panning' as -666 to this api then it will return the current panning.

+** int curpan = SendMessage(hwnd_winamp,WM_WA_IPC,-666,IPC_SETPANNING);

+*/

+

+

+#define IPC_GETLISTLENGTH 124

+/* (requires Winamp 2.0+)

+** int length = SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETLISTLENGTH);

+** IPC_GETLISTLENGTH returns the length of the current playlist as the number of tracks.

+*/

+

+

+#define IPC_GETLISTPOS 125

+/* (requires Winamp 2.05+)

+** int pos=SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETLISTPOS);

+** IPC_GETLISTPOS returns the current playlist position (which is shown in the playlist

+** editor as a differently coloured text entry e.g is yellow for the classic skin).

+**

+** This api is a lot like IPC_WRITEPLAYLIST but a lot faster since it does not have to

+** write out the whole of the current playlist first.

+*/

+

+

+#define IPC_GETINFO 126

+/* (requires Winamp 2.05+)

+** int inf=SendMessage(hwnd_winamp,WM_WA_IPC,mode,IPC_GETINFO);

+** IPC_GETINFO returns info about the current playing song. The value

+** it returns depends on the value of 'mode'.

+** Mode      Meaning

+** ------------------

+** 0         Samplerate, in kilohertz (i.e. 44)

+** 1         Bitrate  (i.e. 128)

+** 2         Channels (i.e. 2)

+** 3 (5+)    Video LOWORD=w HIWORD=h

+** 4 (5+)    > 65536, string (video description)

+** 5 (5.25+) Samplerate, in hertz (i.e. 44100)

+*/

+

+

+#define IPC_GETEQDATA 127

+/* (requires Winamp 2.05+)

+** int data=SendMessage(hwnd_winamp,WM_WA_IPC,pos,IPC_GETEQDATA);

+** IPC_GETEQDATA queries the status of the EQ.

+** The value returned depends on what 'pos' is set to:

+** Value      Meaning

+** ------------------

+** 0-9        The 10 bands of EQ data. 0-63 (+20db - -20db)

+** 10         The preamp value. 0-63 (+20db - -20db)

+** 11         Enabled. zero if disabled, nonzero if enabled.

+** 12         Autoload. zero if disabled, nonzero if enabled.

+*/

+

+

+#define IPC_SETEQDATA 128

+/* (requires Winamp 2.05+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,pos,IPC_GETEQDATA);

+** SendMessage(hwnd_winamp,WM_WA_IPC,value,IPC_SETEQDATA);

+** IPC_SETEQDATA sets the value of the last position retrieved

+** by IPC_GETEQDATA. This is pretty lame, and we should provide

+** an extended version that lets you do a MAKELPARAM(pos,value).

+** someday...

+

+  new (2.92+):

+    if the high byte is set to 0xDB, then the third byte specifies

+    which band, and the bottom word specifies the value.

+*/

+

+

+#define IPC_ADDBOOKMARK 129

+#define IPC_ADDBOOKMARKW 131

+/* (requires Winamp 2.4+)

+** This is sent as a WM_COPYDATA using IPC_ADDBOOKMARK as the dwData value and the

+** directory you want to change to as the lpData member. This will add the specified

+** file / url to the Winamp bookmark list.

+**

+** COPYDATASTRUCT cds = {0};

+**   cds.dwData = IPC_ADDBOOKMARK;

+**   cds.lpData = (void*)"http://www.blah.com/listen.pls";

+**   cds.cbData = lstrlen((char*)cds.lpData)+1; // include space for null char

+**   SendMessage(hwnd_winamp,WM_COPYDATA,0,(LPARAM)&cds);

+**

+**

+** In Winamp 5.0+ we use this as a normal WM_WA_IPC and the string is null separated as

+** the filename and then the title of the entry.

+**

+** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)(char*)"filename\0title\0",IPC_ADDBOOKMARK);

+**

+** This will notify the library / bookmark editor that a bookmark was added.

+** Note that using this message in this context does not actually add the bookmark.

+** Do not use, it is essentially just a notification type message :)

+*/

+

+

+#define IPC_INSTALLPLUGIN 130

+/* This is not implemented (and is very unlikely to be done due to safety concerns).

+** If it was then you could do a WM_COPYDATA with a path to a .wpz and it would then

+** install the plugin for you.

+**

+** COPYDATASTRUCT cds = {0};

+**   cds.dwData = IPC_INSTALLPLUGIN;

+**   cds.lpData = (void*)"c:\\path\\to\\file.wpz";

+**   cds.cbData = lstrlen((char*)cds.lpData)+1; // include space for null char

+**   SendMessage(hwnd_winamp,WM_COPYDATA,0,(LPARAM)&cds);

+*/

+

+

+#define IPC_RESTARTWINAMP 135

+/* (requires Winamp 2.2+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_RESTARTWINAMP);

+** IPC_RESTARTWINAMP will restart Winamp (isn't that obvious ? :) )

+** If this fails to make Winamp start after closing then there is a good chance one (or

+** more) of the currently installed plugins caused Winamp to crash on exit (either as a

+** silent crash or a full crash log report before it could call itself start again.

+*/

+

+

+#define IPC_ISFULLSTOP 400

+/* (requires winamp 2.7+ I think)

+** int ret=SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_ISFULLSTOP);

+** This is useful for when you're an output plugin and you want to see if the stop/close

+** happening is a full stop or if you are just between tracks. This returns non zero if

+** it is a full stop or zero if it is just a new track.

+** benski> i think it's actually the other way around -

+**         !0 for EOF and 0 for user pressing stop

+*/

+

+

+#define IPC_INETAVAILABLE 242

+/* (requires Winamp 2.05+)

+** int val=SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_INETAVAILABLE);

+** IPC_INETAVAILABLE will return 1 if an Internet connection is available for Winamp and

+** relates to the internet connection type setting on the main general preferences page

+** in the Winamp preferences.

+*/

+

+

+#define IPC_UPDTITLE 243

+/* (requires Winamp 2.2+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_UPDTITLE);

+** IPC_UPDTITLE will ask Winamp to update the information about the current title and

+** causes GetFileInfo(..) in the input plugin associated with the current playlist entry

+** to be called. This can be called such as when an input plugin is buffering a file so

+** that it can cause the buffer percentage to appear in the playlist.

+*/

+

+

+#define IPC_REFRESHPLCACHE 247

+/* (requires Winamp 2.2+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_REFRESHPLCACHE);

+** IPC_REFRESHPLCACHE will flush the playlist cache buffer and you send this if you want

+** Winamp to go refetch the titles for all of the entries in the current playlist.

+**

+** 5.3+: pass a wchar_t * string in wParam, and it'll do a strnicmp() before clearing the cache

+*/

+

+

+#define IPC_GET_SHUFFLE 250

+/* (requires Winamp 2.4+)

+** int val=SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GET_SHUFFLE);

+** IPC_GET_SHUFFLE returns the status of the shuffle option.

+** If set then it will return 1 and if not set then it will return 0.

+*/

+

+

+#define IPC_GET_REPEAT 251

+/* (requires Winamp 2.4+)

+** int val=SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GET_REPEAT);

+** IPC_GET_REPEAT returns the status of the repeat option.

+** If set then it will return 1 and if not set then it will return 0.

+*/

+

+

+#define IPC_SET_SHUFFLE 252

+/* (requires Winamp 2.4+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,value,IPC_SET_SHUFFLE);

+** IPC_SET_SHUFFLE sets the status of the shuffle option.

+** If 'value' is 1 then shuffle is turned on.

+** If 'value' is 0 then shuffle is turned off.

+*/

+

+

+#define IPC_SET_REPEAT 253

+/* (requires Winamp 2.4+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,value,IPC_SET_REPEAT);

+** IPC_SET_REPEAT sets the status of the repeat option.

+** If 'value' is 1 then shuffle is turned on.

+** If 'value' is 0 then shuffle is turned off.

+*/

+

+

+#define IPC_ENABLEDISABLE_ALL_WINDOWS 259 // 0xdeadbeef to disable

+/* (requires Winamp 2.9+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,(enable?0:0xdeadbeef),IPC_ENABLEDISABLE_ALL_WINDOWS);

+** Sending this message with 0xdeadbeef as the param will disable all winamp windows and

+** any other values will enable all of the Winamp windows again. When disabled you won't

+** get any response on clicking or trying to do anything to the Winamp windows. If the

+** taskbar icon is shown then you may still have control ;)

+*/

+

+

+#define IPC_GETWND 260

+/* (requires Winamp 2.9+)

+** HWND h=SendMessage(hwnd_winamp,WM_WA_IPC,IPC_GETWND_xxx,IPC_GETWND);

+** returns the HWND of the window specified.

+*/

+  #define IPC_GETWND_EQ 0 // use one of these for the param

+  #define IPC_GETWND_PE 1

+  #define IPC_GETWND_MB 2

+  #define IPC_GETWND_VIDEO 3

+#define IPC_ISWNDVISIBLE 261 // same param as IPC_GETWND

+

+

+/************************************************************************

+***************** in-process only (WE LOVE PLUGINS)

+************************************************************************/

+

+#define IPC_SETSKINW 199

+#define IPC_SETSKIN 200

+/* (requires Winamp 2.04+, only usable from plug-ins (not external apps))

+** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)"skinname",IPC_SETSKIN);

+** IPC_SETSKIN sets the current skin to "skinname". Note that skinname

+** can be the name of a skin, a skin .zip file, with or without path.

+** If path isn't specified, the default search path is the winamp skins

+** directory.

+*/

+

+

+#define IPC_GETSKIN 201

+#define IPC_GETSKINW 1201

+/* (requires Winamp 2.04+, only usable from plug-ins (not external apps))

+** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)skinname_buffer,IPC_GETSKIN);

+** IPC_GETSKIN puts the directory where skin bitmaps can be found

+** into  skinname_buffer.

+** skinname_buffer must be MAX_PATH characters in length.

+** When using a .zip'd skin file, it'll return a temporary directory

+** where the ZIP was decompressed.

+*/

+

+

+#define IPC_EXECPLUG 202

+/* (requires Winamp 2.04+, only usable from plug-ins (not external apps))

+** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)"vis_file.dll",IPC_EXECPLUG);

+** IPC_EXECPLUG executes a visualization plug-in pointed to by WPARAM.

+** the format of this string can be:

+** "vis_whatever.dll"

+** "vis_whatever.dll,0" // (first mod, file in winamp plug-in dir)

+** "C:\\dir\\vis_whatever.dll,1"

+*/

+

+

+#define IPC_GETPLAYLISTFILE 211

+#define IPC_GETPLAYLISTFILEW 214

+/* (requires Winamp 2.04+, only usable from plug-ins (not external apps))

+** char *name=SendMessage(hwnd_winamp,WM_WA_IPC,index,IPC_GETPLAYLISTFILE);

+** IPC_GETPLAYLISTFILE gets the filename of the playlist entry [index].

+** returns a pointer to it. returns NULL on error.

+*/

+

+

+#define IPC_GETPLAYLISTTITLE 212

+#define IPC_GETPLAYLISTTITLEW 213

+/* (requires Winamp 2.04+, only usable from plug-ins (not external apps))

+** char *name=SendMessage(hwnd_winamp,WM_WA_IPC,index,IPC_GETPLAYLISTTITLE);

+**

+** IPC_GETPLAYLISTTITLE gets the title of the playlist entry [index].

+** returns a pointer to it. returns NULL on error.

+*/

+

+

+#define IPC_GETHTTPGETTER 240

+/* retrieves a function pointer to a HTTP retrieval function.

+** if this is unsupported, returns 1 or 0.

+** the function should be:

+** int (*httpRetrieveFile)(HWND hwnd, char *url, char *file, char *dlgtitle);

+** if you call this function, with a parent window, a URL, an output file, and a dialog title,

+** it will return 0 on successful download, 1 on error.

+*/

+

+

+#define IPC_GETHTTPGETTERW 1240

+/* int (*httpRetrieveFileW)(HWND hwnd, char *url, wchar_t *file, wchar_t *dlgtitle); */

+

+

+#define IPC_MBOPEN 241

+/* (requires Winamp 2.05+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_MBOPEN);

+** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)url,IPC_MBOPEN);

+** IPC_MBOPEN will open a new URL in the minibrowser. if url is NULL, it will open the Minibrowser window.

+*/

+

+

+#define IPC_CHANGECURRENTFILE 245

+/* (requires Winamp 2.05+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)file,IPC_CHANGECURRENTFILE);

+** IPC_CHANGECURRENTFILE will set the current playlist item.

+*/

+

+

+#define IPC_CHANGECURRENTFILEW 1245

+/* (requires Winamp 5.3+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)file,IPC_CHANGECURRENTFILEW);

+** IPC_CHANGECURRENTFILEW will set the current playlist item.

+*/

+

+

+#define IPC_GETMBURL 246

+/* (requires Winamp 2.2+)

+** char buffer[4096]; // Urls can be VERY long

+** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)buffer,IPC_GETMBURL);

+** IPC_GETMBURL will retrieve the current Minibrowser URL into buffer.

+** buffer must be at least 4096 bytes long.

+*/

+

+

+#define IPC_MBBLOCK 248

+/* (requires Winamp 2.4+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,value,IPC_MBBLOCK);

+**

+** IPC_MBBLOCK will block the Minibrowser from updates if value is set to 1

+*/

+

+

+#define IPC_MBOPENREAL 249

+/* (requires Winamp 2.4+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)url,IPC_MBOPENREAL);

+**

+** IPC_MBOPENREAL works the same as IPC_MBOPEN except that it will works even if

+** IPC_MBBLOCK has been set to 1

+*/

+

+

+#define IPC_ADJUST_OPTIONSMENUPOS 280

+/* (requires Winamp 2.9+)

+** int newpos=SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)adjust_offset,IPC_ADJUST_OPTIONSMENUPOS);

+** moves where winamp expects the Options menu in the main menu. Useful if you wish to insert a

+** menu item above the options/skins/vis menus.

+*/

+

+

+#define IPC_GET_HMENU 281

+/* (requires Winamp 2.9+)

+** HMENU hMenu=SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)0,IPC_GET_HMENU);

+** values for data:

+** 0 : main popup menu

+** 1 : main menubar file menu

+** 2 : main menubar options menu

+** 3 : main menubar windows menu

+** 4 : main menubar help menu

+** other values will return NULL.

+*/

+

+

+#define IPC_GET_EXTENDED_FILE_INFO 290 //pass a pointer to the following struct in wParam

+#define IPC_GET_EXTENDED_FILE_INFO_HOOKABLE 296

+/* (requires Winamp 2.9+)

+** to use, create an extendedFileInfoStruct, point the values filename and metadata to the

+** filename and metadata field you wish to query, and ret to a buffer, with retlen to the

+** length of that buffer, and then SendMessage(hwnd_winamp,WM_WA_IPC,&struct,IPC_GET_EXTENDED_FILE_INFO);

+** the results should be in the buffer pointed to by ret.

+** returns 1 if the decoder supports a getExtendedFileInfo method

+*/

+typedef struct {

+  const char *filename;

+  const char *metadata;

+  char *ret;

+  size_t retlen;

+} extendedFileInfoStruct;

+

+

+#define IPC_GET_BASIC_FILE_INFO 291 //pass a pointer to the following struct in wParam

+typedef struct {

+  const char *filename;

+

+  int quickCheck; // set to 0 to always get, 1 for quick, 2 for default (if 2, quickCheck will be set to 0 if quick wasnot used)

+

+  // filled in by winamp

+  int length;

+  char *title;

+  int titlelen;

+} basicFileInfoStruct;

+

+

+#define IPC_GET_BASIC_FILE_INFOW 1291 //pass a pointer to the following struct in wParam

+typedef struct {

+  const wchar_t *filename;

+

+  int quickCheck; // set to 0 to always get, 1 for quick, 2 for default (if 2, quickCheck will be set to 0 if quick wasnot used)

+

+  // filled in by winamp

+  int length;

+  wchar_t *title;

+  int titlelen;

+} basicFileInfoStructW;

+

+

+#define IPC_GET_EXTLIST 292 //returns doublenull delimited. GlobalFree() it when done. if data is 0, returns raw extlist, if 1, returns something suitable for getopenfilename

+#define IPC_GET_EXTLISTW 1292 // wide char version of above

+

+

+#define IPC_INFOBOX 293

+typedef struct {

+  HWND parent;

+  char *filename;

+} infoBoxParam;

+

+

+#define IPC_INFOBOXW 1293

+typedef struct {

+  HWND parent;

+  const wchar_t *filename;

+} infoBoxParamW;

+

+

+#define IPC_SET_EXTENDED_FILE_INFO 294 //pass a pointer to the a extendedFileInfoStruct in wParam

+/* (requires Winamp 2.9+)

+** to use, create an extendedFileInfoStruct, point the values filename and metadata to the

+** filename and metadata field you wish to write in ret. (retlen is not used). and then

+** SendMessage(hwnd_winamp,WM_WA_IPC,&struct,IPC_SET_EXTENDED_FILE_INFO);

+** returns 1 if the metadata is supported

+** Call IPC_WRITE_EXTENDED_FILE_INFO once you're done setting all the metadata you want to update

+*/

+

+

+#define IPC_WRITE_EXTENDED_FILE_INFO 295

+/* (requires Winamp 2.9+)

+** writes all the metadata set thru IPC_SET_EXTENDED_FILE_INFO to the file

+** returns 1 if the file has been successfully updated, 0 if error

+*/

+

+

+#define IPC_FORMAT_TITLE 297

+typedef struct

+{

+  char *spec; // NULL=default winamp spec

+  void *p;

+

+  char *out;

+  int out_len;

+

+  char * (*TAGFUNC)(const char * tag, void * p); //return 0 if not found

+  void (*TAGFREEFUNC)(char * tag,void * p);

+} waFormatTitle;

+

+

+#define IPC_FORMAT_TITLE_EXTENDED 298 // similiar to IPC_FORMAT_TITLE, but falls back to Winamp's %tags% if your passed tag function doesn't handle it

+typedef struct

+{

+  const wchar_t *filename;

+  int useExtendedInfo; // set to 1 if you want the Title Formatter to query the input plugins for any tags that your tag function fails on

+  const wchar_t *spec; // NULL=default winamp spec

+  void *p;

+

+  wchar_t *out;

+  int out_len;

+

+  wchar_t * (*TAGFUNC)(const wchar_t * tag, void * p); //return 0 if not found, -1 for empty tag

+  void (*TAGFREEFUNC)(wchar_t *tag, void *p);

+} waFormatTitleExtended;

+

+

+#define IPC_COPY_EXTENDED_FILE_INFO 299

+typedef struct

+{

+  const char *source;

+  const char *dest;

+} copyFileInfoStruct;

+

+

+#define IPC_COPY_EXTENDED_FILE_INFOW 1299

+typedef struct

+{

+  const wchar_t *source;

+  const wchar_t *dest;

+} copyFileInfoStructW;

+

+

+typedef struct {

+  int (*inflateReset)(void *strm);

+  int (*inflateInit_)(void *strm,const char *version, int stream_size);

+  int (*inflate)(void *strm, int flush);

+  int (*inflateEnd)(void *strm);

+  unsigned long (*crc32)(unsigned long crc, const unsigned  char *buf, unsigned int len);

+} wa_inflate_struct;

+

+#define IPC_GETUNCOMPRESSINTERFACE 331

+/* returns a function pointer to uncompress().

+** int (*uncompress)(unsigned char *dest, unsigned long *destLen, const unsigned char *source, unsigned long sourceLen);

+** right out of zlib, useful for decompressing zlibbed data.

+** if you pass the parm of 0x10100000, it will return a wa_inflate_struct * to an inflate API.

+*/

+

+

+typedef struct _prefsDlgRec {

+  HINSTANCE hInst;  // dll instance containing the dialog resource

+  int dlgID;        // resource identifier of the dialog

+  void *proc;       // window proceedure for handling the dialog defined as

+                    // LRESULT CALLBACK PrefsPage(HWND,UINT,WPARAM,LPARAM)

+

+  char *name;       // name shown for the prefs page in the treelist

+  intptr_t where;   // section in the treelist the prefs page is to be added to

+                    // 0 for General Preferences

+                    // 1 for Plugins

+                    // 2 for Skins

+                    // 3 for Bookmarks (no longer in the 5.0+ prefs)

+                    // 4 for Prefs     (the old 'Setup' section - no longer in 5.0+)

+

+  intptr_t _id;

+  struct _prefsDlgRec *next; // no longer implemented as a linked list, now used by Winamp for other means

+} prefsDlgRec;

+

+typedef struct _prefsDlgRecW {

+  HINSTANCE hInst;  // dll instance containing the dialog resource

+  int dlgID;        // resource identifier of the dialog

+  void *proc;       // window proceedure for handling the dialog defined as

+                    // LRESULT CALLBACK PrefsPage(HWND,UINT,WPARAM,LPARAM)

+

+  wchar_t *name;    // name shown for the prefs page in the treelist

+  intptr_t where;   // section in the treelist the prefs page is to be added to

+                    // 0 for General Preferences

+                    // 1 for Plugins

+                    // 2 for Skins

+                    // 3 for Bookmarks (no longer in the 5.0+ prefs)

+                    // 4 for Prefs     (the old 'Setup' section - no longer in 5.0+)

+

+  intptr_t _id;

+  struct _prefsDlgRec *next; // no longer implemented as a linked list, now used by Winamp for other means

+} prefsDlgRecW;

+

+#define IPC_ADD_PREFS_DLG 332

+#define IPC_ADD_PREFS_DLGW 1332

+#define IPC_REMOVE_PREFS_DLG 333

+/* (requires Winamp 2.9+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)&prefsRec,IPC_ADD_PREFS_DLG);

+** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)&prefsRec,IPC_REMOVE_PREFS_DLG);

+**

+** IPC_ADD_PREFS_DLG:

+** To use this you need to allocate a prefsDlgRec structure (either on the heap or with

+** some global data but NOT on the stack) and then initialise the members of the structure

+** (see the definition of the prefsDlgRec structure above).

+**

+**   hInst  -  dll instance of where the dialog resource is located.

+**   dlgID  -  id of the dialog resource.

+**   proc   -  dialog window procedure for the prefs dialog.

+**   name   -  name of the prefs page as shown in the preferences list.

+**   where  -  see above for the valid locations the page can be added.

+**

+** Then you do SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)&prefsRec,IPC_ADD_PREFS_DLG);

+**

+** example:

+**

+** prefsDlgRec* prefsRec = 0;

+**   prefsRec = GlobalAlloc(GPTR,sizeof(prefsDlgRec));

+**   prefsRec->hInst = hInst;

+**   prefsRec->dlgID = IDD_PREFDIALOG;

+**   prefsRec->name = "Pref Page";

+**   prefsRec->where = 0;

+**   prefsRec->proc = PrefsPage;

+**   SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)&prefsRec,IPC_ADD_PREFS_DLG);

+**

+**

+** IPC_REMOVE_PREFS_DLG:

+** To use you pass the address of the same prefsRec you used when adding the prefs page

+** though you shouldn't really ever have to do this but it's good to clean up after you

+** when you're plugin is being unloaded.

+**

+** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)&prefsRec,IPC_REMOVE_PREFS_DLG);

+**

+** IPC_ADD_PREFS_DLGW

+** requires Winamp 5.53+

+*/

+

+

+#define IPC_OPENPREFSTOPAGE 380

+/* SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)&prefsRec,IPC_OPENPREFSTOPAGE);

+**

+** There are two ways of opening a preferences page.

+**

+** The first is to pass an id of a builtin preferences page (see below for ids) or a

+** &prefsDlgRec of the preferences page to open and this is normally done if you are

+** opening a prefs page you added yourself.

+**

+** If the page id does not or the &prefsRec is not valid then the prefs dialog will be

+** opened to the first page available (usually the Winamp Pro page).

+**

+** (requires Winamp 5.04+)

+** Passing -1 for param will open the preferences dialog to the last page viewed.

+**

+** Note: v5.0 to 5.03 had a bug in this api

+**

+** On the first call then the correct prefs page would be opened to but on the next call

+** the prefs dialog would be brought to the front but the page would not be changed to the

+** specified.

+** In 5.04+ it will change to the prefs page specified if the prefs dialog is already open.

+*/

+

+/* Builtin Preference page ids (valid for 5.0+)

+** (stored in the lParam member of the TVITEM structure from the tree item)

+**

+** These can be useful if you want to detect a specific prefs page and add things to it

+** yourself or something like that ;)

+**

+** Winamp Pro           20

+** General Preferences  0

+** File Types           1

+** Playlist             23

+** Titles               21

+** Playback             42 (added in 5.25)

+** Station Info         41 (added in 5.11 & removed in 5.5)

+** Video                24

+** Localization         25 (added in 5.5)

+** Skins                40

+** Classic Skins        22

+** Plugins              30

+** Input                31

+** Output               32

+** Visualisation        33

+** DSP/Effect           34

+** General Purpose      35

+**

+** Note:

+** Custom page ids begin from 60

+** The value of the normal custom pages (Global Hotkeys, Jump To File, etc) is not

+** guaranteed since it depends on the order in which the plugins are loaded which can

+** change on different systems.

+**

+** Global Hotkeys, Jump To File, Media Library (under General Preferences and child pages),

+** Media Library (under Plugins), Portables, CD Ripping and Modern Skins are custom pages

+** created by the plugins shipped with Winamp.

+*/

+

+

+#define IPC_GETINIFILE 334

+/* (requires Winamp 2.9+)

+** char *ini=(char*)SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETINIFILE);

+** This returns a pointer to the full file path of winamp.ini.

+**

+** char ini_path[MAX_PATH] = {0};

+**

+** void GetIniFilePath(HWND hwnd){

+**   if(SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETVERSION) >= 0x2900){

+**     // this gets the string of the full ini file path

+**     lstrcpyn(ini_path,(char*)SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETINIFILE),sizeof(ini_path));

+**   }

+**   else{

+**   char* p = ini_path;

+**     p += GetModuleFileName(0,ini_path,sizeof(ini_path)) - 1;

+**     while(p && *p != '.'){p--;}

+**     lstrcpyn(p+1,"ini",sizeof(ini_path));

+**   }

+** }

+*/

+

+

+#define IPC_GETINIDIRECTORY 335

+/* (requires Winamp 2.9+)

+** char *dir=(char*)SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETINIDIRECTORY);

+** This returns a pointer to the directory where winamp.ini can be found and is

+** useful if you want store config files but you don't want to use winamp.ini.

+*/

+

+

+#define IPC_GETPLUGINDIRECTORY 336

+/* (requires Winamp 5.11+)

+** char *plugdir=(char*)SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETPLUGINDIRECTORY);

+** This returns a pointer to the directory where Winamp has its plugins stored and is

+** useful if you want store config files in plugins.ini in the plugins folder or for

+** accessing any local files in the plugins folder.

+*/

+

+

+#define IPC_GETM3UDIRECTORY 337

+/* (requires Winamp 5.11+)

+** char *m3udir=(char*)SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETM3UDIRECTORY);

+** This returns a pointer to the directory where winamp.m3u (and winamp.m3u8 if supported) is stored in.

+*/

+

+

+#define IPC_GETM3UDIRECTORYW 338

+/* (requires Winamp 5.3+)

+** wchar_t *m3udirW=(wchar_t*)SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETM3UDIRECTORYW);

+** This returns a pointer to the directory where winamp.m3u (and winamp.m3u8 if supported) is stored in.

+*/

+

+

+#define IPC_SPAWNBUTTONPOPUP 361 // param =

+// 0 = eject

+// 1 = previous

+// 2 = next

+// 3 = pause

+// 4 = play

+// 5 = stop

+

+

+#define IPC_OPENURLBOX 360

+/* (requires Winamp 5.0+)

+** HGLOBAL hglobal = (HGLOBAL)SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)(HWND)parent,IPC_OPENURLBOX);

+** You pass a hwnd for the dialog to be parented to (which modern skin support uses).

+** This will return a HGLOBAL that needs to be freed with GlobalFree() if this worked.

+*/

+

+

+#define IPC_OPENFILEBOX 362

+/* (requires Winamp 5.0+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)(HWND)parent,IPC_OPENFILEBOX);

+** You pass a hwnd for the dialog to be parented to (which modern skin support uses).

+*/

+

+

+#define IPC_OPENDIRBOX 363

+/* (requires Winamp 5.0+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)(HWND)parent,IPC_OPENDIRBOX);

+** You pass a hwnd for the dialog to be parented to (which modern skin support uses).

+*/

+

+

+#define IPC_SETDIALOGBOXPARENT 364

+/* (requires Winamp 5.0+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)(HWND)parent,IPC_SETDIALOGBOXPARENT);

+** Pass 'parent' as the window which will be used as the parent for a number of the built

+** in Winamp dialogs and is useful when you are taking over the whole of the UI so that

+** the dialogs will not appear at the bottom right of the screen since the main winamp

+** window is located at 3000x3000 by gen_ff when this is used.  Call this again with

+** parent = null to reset the parent back to the orginal Winamp window.

+*/

+

+#define IPC_GETDIALOGBOXPARENT 365

+/* (requires Winamp 5.51+)

+** HWND hwndParent = SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)0, IPC_GETDIALOGBOXPARENT);

+** hwndParent can/must be passed to all modal dialogs (including MessageBox) thats uses winamp as a parent

+*/

+

+#define IPC_UPDATEDIALOGBOXPARENT 366

+/* (requires Winamp 5.53+)

+** if you previous called IPC_SETDIALOGBOXPARENT, call this every time your window resizes

+*/

+

+#define IPC_DRO_MIN 401 // reserved for DrO

+#define IPC_SET_JTF_COMPARATOR 409

+/* pass me an int (__cdecl *)(const char *, const char *) in wParam */

+#define IPC_SET_JTF_COMPARATOR_W 410

+/* pass me an int (__cdecl *)(const wchar_t *, const wchar_t *) in wParam ... maybe someday :) */

+#define IPC_SET_JTF_DRAWTEXT 416

+

+#define IPC_DRO_MAX 499

+

+

+// pass 0 for a copy of the skin HBITMAP

+// pass 1 for name of font to use for playlist editor likeness

+// pass 2 for font charset

+// pass 3 for font size

+#define IPC_GET_GENSKINBITMAP 503

+

+

+typedef struct

+{

+  HWND me; //hwnd of the window

+

+  #define EMBED_FLAGS_NORESIZE 0x1

+  // set this bit to keep window from being resizable

+

+  #define EMBED_FLAGS_NOTRANSPARENCY 0x2

+  // set this bit to make gen_ff turn transparency off for this window

+

+  #define EMBED_FLAGS_NOWINDOWMENU 0x4

+  // set this bit to prevent gen_ff from automatically adding your window to the right-click menu

+

+  #define EMBED_FLAGS_GUID 0x8

+  // (5.31+) call SET_EMBED_GUID(yourEmbedWindowStateStruct, GUID) to define a GUID for this window

+

+  #define SET_EMBED_GUID(windowState, windowGUID) { windowState->flags |= EMBED_FLAGS_GUID; *((GUID *)&windowState->extra_data[4])=windowGUID; }

+  #define GET_EMBED_GUID(windowState) (*((GUID *)&windowState->extra_data[4]))

+

+  int flags;  // see above

+

+  RECT r;

+  void *user_ptr;       // for application use

+  int extra_data[64];   // for internal winamp use

+} embedWindowState;

+

+#define IPC_GET_EMBEDIF 505

+/* (requires Winamp 2.9+)

+** HWND myframe = (HWND)SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)&wa_wnd,IPC_GET_EMBEDIF);

+**

+** or

+**

+** HWND myframe = 0;

+** HWND (*embed)(embedWindowState *params)=0;

+**   *(void**)&embed = (void*)SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GET_EMBEDIF);

+**   myframe = embed(&wa_wnd);

+**

+** You pass an embedWindowState* and it will return a hwnd for the frame window or if you

+** pass wParam as null then it will return a HWND embedWindow(embedWindowState *);

+*/

+

+#define IPC_SKINWINDOW  534

+

+typedef struct __SKINWINDOWPARAM

+{

+    HWND hwndToSkin;

+    GUID windowGuid;

+} SKINWINDOWPARAM;

+

+

+

+#define IPC_EMBED_ENUM 532

+typedef struct embedEnumStruct

+{

+  int (*enumProc)(embedWindowState *ws, struct embedEnumStruct *param); // return 1 to abort

+  int user_data; // or more :)

+} embedEnumStruct;

+  // pass

+

+

+#define IPC_EMBED_ISVALID 533

+/* (requires Winamp 2.9+)

+** int valid = SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)embedhwnd,IPC_EMBED_ISVALID);

+** Pass a hwnd in the wParam to this to check if the hwnd is a valid embed window or not.

+*/

+

+

+#define IPC_CONVERTFILE 506

+/* (requires Winamp 2.92+)

+** Converts a given file to a different format (PCM, MP3, etc...)

+** To use, pass a pointer to a waFileConvertStruct struct

+** This struct can be either on the heap or some global

+** data, but NOT on the stack. At least, until the conversion is done.

+**

+** eg: SendMessage(hwnd_winamp,WM_WA_IPC,&myConvertStruct,IPC_CONVERTFILE);

+**

+** Return value:

+** 0: Can't start the conversion. Look at myConvertStruct->error for details.

+** 1: Conversion started. Status messages will be sent to the specified callbackhwnd.

+**    Be sure to call IPC_CONVERTFILE_END when your callback window receives the

+**    IPC_CB_CONVERT_DONE message.

+*/

+typedef struct

+{

+  char *sourcefile;  // "c:\\source.mp3"

+  char *destfile;    // "c:\\dest.pcm"

+  intptr_t destformat[8]; // like 'PCM ',srate,nch,bps.

+  //hack alert! you can set destformat[6]=mmioFOURCC('I','N','I',' '); and destformat[7]=(int)my_ini_file; (where my_ini_file is a char*)

+  HWND callbackhwnd; // window that will receive the IPC_CB_CONVERT notification messages

+

+  //filled in by winamp.exe

+  char *error;        //if IPC_CONVERTFILE returns 0, the reason will be here

+

+  int bytes_done;     //you can look at both of these values for speed statistics

+  int bytes_total;

+  int bytes_out;

+

+  int killswitch;     // don't set it manually, use IPC_CONVERTFILE_END

+  intptr_t extra_data[64]; // for internal winamp use

+} convertFileStruct;

+

+

+#define IPC_CONVERTFILEW 515

+// (requires Winamp 5.36+)

+typedef struct

+{

+  wchar_t *sourcefile;  // "c:\\source.mp3"

+  wchar_t *destfile;    // "c:\\dest.pcm"

+  intptr_t destformat[8]; // like 'PCM ',srate,nch,bps.

+  //hack alert! you can set destformat[6]=mmioFOURCC('I','N','I',' '); and destformat[7]=(int)my_ini_file; (where my_ini_file is a char*)

+  HWND callbackhwnd; // window that will receive the IPC_CB_CONVERT notification messages

+

+  //filled in by winamp.exe

+  wchar_t *error;        //if IPC_CONVERTFILE returns 0, the reason will be here

+

+  int bytes_done;     //you can look at both of these values for speed statistics

+  int bytes_total;

+  int bytes_out;

+

+  int killswitch;     // don't set it manually, use IPC_CONVERTFILE_END

+  intptr_t extra_data[64]; // for internal winamp use

+} convertFileStructW;

+

+

+#define IPC_CONVERTFILE_END 507

+/* (requires Winamp 2.92+)

+** Stop/ends a convert process started from IPC_CONVERTFILE

+** You need to call this when you receive the IPC_CB_CONVERTDONE message or when you

+** want to abort a conversion process

+**

+** eg: SendMessage(hwnd_winamp,WM_WA_IPC,&myConvertStruct,IPC_CONVERTFILE_END);

+**

+** No return value

+*/

+

+

+#define IPC_CONVERTFILEW_END 516

+// (requires Winamp 5.36+)

+

+typedef struct {

+  HWND hwndParent;

+  int format;

+

+  //filled in by winamp.exe

+  HWND hwndConfig;

+  int extra_data[8];

+  //hack alert! you can set extra_data[6]=mmioFOURCC('I','N','I',' '); and extra_data[7]=(int)my_ini_file; (where my_ini_file is a char*)

+} convertConfigStruct;

+

+

+#define IPC_CONVERT_CONFIG 508

+#define IPC_CONVERT_CONFIG_END 509

+

+typedef struct

+{

+  void (*enumProc)(intptr_t user_data, const char *desc, int fourcc);

+  intptr_t user_data;

+} converterEnumFmtStruct;

+#define IPC_CONVERT_CONFIG_ENUMFMTS 510

+/* (requires Winamp 2.92+)

+*/

+

+typedef struct

+{

+  char cdletter;

+  char *playlist_file;

+  HWND callback_hwnd;

+

+  //filled in by winamp.exe

+  char *error;

+} burnCDStruct;

+#define IPC_BURN_CD 511

+/* (requires Winamp 5.0+)

+*/

+

+typedef struct

+{

+  convertFileStruct *cfs;

+  int priority;

+} convertSetPriority;

+

+

+#define IPC_CONVERT_SET_PRIORITY 512

+

+typedef struct

+{

+  convertFileStructW *cfs;

+  int priority;

+} convertSetPriorityW;

+

+

+#define IPC_CONVERT_SET_PRIORITYW 517

+// (requires Winamp 5.36+)

+

+typedef struct

+{

+  unsigned int format; //fourcc value

+  char *item; // config item, eg "bitrate"

+  char *data; // buffer to recieve, or buffer that contains the data

+  int len; // length of the data buffer (only used when getting a config item)

+  char *configfile; // config file to read from

+} convertConfigItem;

+

+

+#define IPC_CONVERT_CONFIG_SET_ITEM 513 // returns TRUE if successful

+#define IPC_CONVERT_CONFIG_GET_ITEM 514 // returns TRUE if successful

+

+

+typedef struct

+{

+  const char *filename;

+  char *title; // 2048 bytes

+  int length;

+  int force_useformatting; // can set this to 1 if you want to force a url to use title formatting shit

+} waHookTitleStruct;

+

+#define IPC_HOOK_TITLES 850

+/* (requires Winamp 5.0+)

+** If you hook this message and modify the information then make sure to return TRUE.

+** If you don't hook the message then make sure you pass it on through the subclass chain.

+**

+** LRESULT CALLBACK WinampWndProc(HWND hwnd, UINT umsg, WPARAM wParam, LPARAM lParam)

+** {

+**   LRESULT ret = CallWindowProc((WNDPROC)WinampProc,hwnd,umsg,wParam,lParam);

+**

+**   if(message==WM_WA_IPC && lParam==IPC_HOOK_TITLES)

+**   {

+**     waHookTitleStruct *ht = (waHookTitleStruct *) wParam;

+**     // Doing ATF stuff with ht->title, whatever...

+**     return TRUE;

+**   }

+**   return ret;

+** }

+*/

+

+typedef struct

+{

+  const wchar_t *filename;

+  wchar_t *title; // 2048 characters

+  int length;

+  int force_useformatting; // can set this to 1 if you want to force a url to use title formatting shit

+} waHookTitleStructW;

+#define IPC_HOOK_TITLESW 851

+/* (requires Winamp 5.3+)

+** See information on IPC_HOOK_TITLES for how to process this.

+*/

+

+

+#define IPC_GETSADATAFUNC 800

+// 0: returns a char *export_sa_get() that returns 150 bytes of data

+// 1: returns a export_sa_setreq(int want);

+

+

+#define IPC_GETVUDATAFUNC 801

+// 0: returns a int export_vu_get(int channel) that returns 0-255 (or -1 for bad channel)

+

+

+#define IPC_ISMAINWNDVISIBLE 900

+/* (requires Winamp 5.0+)

+** int visible=SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_ISMAINWNDVISIBLE);

+** You send this to Winamp to query if the main window is visible or not such as by

+** unchecking the option in the main right-click menu. If the main window is visible then

+** this will return 1 otherwise it returns 0.

+*/

+

+

+typedef struct

+{

+  int numElems;

+  int *elems;

+  HBITMAP bm; // set if you want to override

+} waSetPlColorsStruct;

+

+#define IPC_SETPLEDITCOLORS 920

+/* (requires Winamp 5.0+)

+** This is sent by gen_ff when a modern skin is being loaded to set the colour scheme for

+** the playlist editor. When sent numElems is usually 6 and matches with the 6 possible

+** colours which are provided be pledit.txt from the classic skins. The elems array is

+** defined as follows:

+**

+** elems = 0  =>  normal text

+** elems = 1  =>  current text

+** elems = 2  =>  normal background

+** elems = 3  =>  selected background

+** elems = 4  =>  minibroswer foreground

+** elems = 5  =>  minibroswer background

+**

+** if(uMsg == WM_WA_IPC && lParam == IPC_SETPLEDITCOLORS)

+** {

+**   waSetPlColorsStruct* colStr = (waSetPlColorsStruct*)wp;

+**   if(colStr)

+**   {

+**      // set or inspect the colours being used (basically for gen_ff's benefit)

+**   }

+** }

+*/

+

+

+typedef struct

+{

+  HWND wnd;

+  int xpos; // in screen coordinates

+  int ypos;

+} waSpawnMenuParms;

+

+// waSpawnMenuParms2 is used by the menubar submenus

+typedef struct

+{

+  HWND wnd;

+  int xpos; // in screen coordinates

+  int ypos;

+  int width;

+  int height;

+} waSpawnMenuParms2;

+

+// the following IPC use waSpawnMenuParms as parameter

+#define IPC_SPAWNEQPRESETMENU 933

+#define IPC_SPAWNFILEMENU 934 //menubar

+#define IPC_SPAWNOPTIONSMENU 935 //menubar

+#define IPC_SPAWNWINDOWSMENU 936 //menubar

+#define IPC_SPAWNHELPMENU 937 //menubar

+#define IPC_SPAWNPLAYMENU 938 //menubar

+#define IPC_SPAWNPEFILEMENU 939 //menubar

+#define IPC_SPAWNPEPLAYLISTMENU 940 //menubar

+#define IPC_SPAWNPESORTMENU 941 //menubar

+#define IPC_SPAWNPEHELPMENU 942 //menubar

+#define IPC_SPAWNMLFILEMENU 943 //menubar

+#define IPC_SPAWNMLVIEWMENU 944 //menubar

+#define IPC_SPAWNMLHELPMENU 945 //menubar

+#define IPC_SPAWNPELISTOFPLAYLISTS 946

+

+

+#define WM_WA_SYSTRAY WM_USER+1

+/* This is sent by the system tray when an event happens (you might want to simulate it).

+**

+** if(uMsg == WM_WA_SYSTRAY)

+** {

+**   switch(lParam)

+**   {

+**     // process the messages sent from the tray

+**   }

+** }

+*/

+

+

+#define WM_WA_MPEG_EOF WM_USER+2

+/* Input plugins send this when they are done playing back the current file to inform

+** Winamp or anyother installed plugins that the current

+**

+** if(uMsg == WM_WA_MPEG_EOF)

+** {

+**   // do what is needed here

+** }

+*/

+

+

+//// video stuff

+

+#define IPC_IS_PLAYING_VIDEO 501 // returns >1 if playing, 0 if not, 1 if old version (so who knows):)

+#define IPC_GET_IVIDEOOUTPUT 500 // see below for IVideoOutput interface

+#define VIDEO_MAKETYPE(A,B,C,D) ((A) | ((B)<<8) | ((C)<<16) | ((D)<<24))

+#define VIDUSER_SET_INFOSTRING 0x1000

+#define VIDUSER_GET_VIDEOHWND  0x1001

+#define VIDUSER_SET_VFLIP      0x1002

+#define VIDUSER_SET_TRACKSELINTERFACE 0x1003 // give your ITrackSelector interface as param2

+#define VIDUSER_OPENVIDEORENDERER 0x1004

+#define VIDUSER_CLOSEVIDEORENDERER 0x1005

+#define VIDUSER_GETPOPUPMENU 0x1006

+#define VIDUSER_SET_INFOSTRINGW 0x1007

+

+typedef struct

+{

+  int w;

+  int h;

+  int vflip;

+  double aspectratio;

+  unsigned int fmt;

+} VideoOpenStruct;

+

+#ifndef NO_IVIDEO_DECLARE

+#ifdef __cplusplus

+

+class VideoOutput;

+class SubsItem;

+

+#ifndef _NSV_DEC_IF_H_

+struct YV12_PLANE {

+  unsigned char* baseAddr;

+  long rowBytes;

+} ;

+

+struct YV12_PLANES {

+  YV12_PLANE y;

+  YV12_PLANE u;

+  YV12_PLANE v;

+};

+#endif

+

+class IVideoOutput

+{

+  public:

+    virtual ~IVideoOutput() { }

+    virtual int open(int w, int h, int vflip, double aspectratio, unsigned int fmt)=0;

+    virtual void setcallback(LRESULT (*msgcallback)(void *token, HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam), void *token) { (void)token; (void)msgcallback; /* to eliminate warning C4100 */ }

+    virtual void close()=0;

+    virtual void draw(void *frame)=0;

+    virtual void drawSubtitle(SubsItem *item) {UNREFERENCED_PARAMETER(item);  }

+    virtual void showStatusMsg(const char *text) {UNREFERENCED_PARAMETER(text);  }

+    virtual int get_latency() { return 0; }

+    virtual void notifyBufferState(int bufferstate) { UNREFERENCED_PARAMETER(bufferstate); } /* 0-255*/

+    virtual INT_PTR extended(INT_PTR param1, INT_PTR param2, INT_PTR param3) { UNREFERENCED_PARAMETER(param1); UNREFERENCED_PARAMETER(param2); UNREFERENCED_PARAMETER(param3); return 0; } // Dispatchable, eat this!

+};

+

+class ITrackSelector

+{

+  public:

+    virtual int getNumAudioTracks()=0;

+    virtual void enumAudioTrackName(int n, const char *buf, int size)=0;

+    virtual int getCurAudioTrack()=0;

+    virtual int getNumVideoTracks()=0;

+    virtual void enumVideoTrackName(int n, const char *buf, int size)=0;

+    virtual int getCurVideoTrack()=0;

+

+    virtual void setAudioTrack(int n)=0;

+    virtual void setVideoTrack(int n)=0;

+};

+

+#endif //cplusplus

+#endif//NO_IVIDEO_DECLARE

+

+// these messages are callbacks that you can grab by subclassing the winamp window

+

+// wParam =

+#define IPC_CB_WND_EQ 0 // use one of these for the param

+#define IPC_CB_WND_PE 1

+#define IPC_CB_WND_MB 2

+#define IPC_CB_WND_VIDEO 3

+#define IPC_CB_WND_MAIN 4

+

+#define IPC_CB_ONSHOWWND 600

+#define IPC_CB_ONHIDEWND 601

+

+#define IPC_CB_GETTOOLTIP 602

+

+#define IPC_CB_MISC 603

+    #define IPC_CB_MISC_TITLE 0  // start of playing/stop/pause

+    #define IPC_CB_MISC_VOLUME 1 // volume/pan

+    #define IPC_CB_MISC_STATUS 2 // start playing/stop/pause/ffwd/rwd

+    #define IPC_CB_MISC_EQ 3

+    #define IPC_CB_MISC_INFO 4

+    #define IPC_CB_MISC_VIDEOINFO 5

+    #define IPC_CB_MISC_TITLE_RATING 6 // (5.5+ for when the rating is changed via the songticker menu on current file)

+

+/* Example of using IPC_CB_MISC_STATUS to detect the start of track playback with 5.x

+**

+** if(lParam == IPC_CB_MISC && wParam == IPC_CB_MISC_STATUS)

+** {

+**   if(SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_ISPLAYING) == 1 &&

+**      !SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETOUTPUTTIME))

+**   {

+**     char* file = (char*)SendMessage(hwnd_winamp,WM_WA_IPC,

+**                  SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETLISTPOS),IPC_GETPLAYLISTFILE);

+**     // only output if a valid file was found

+**     if(file)

+**     {

+**       MessageBox(hwnd_winamp,file,"starting",0);

+**       // or do something else that you need to do

+**     }

+**   }

+** }

+*/

+

+

+#define IPC_CB_CONVERT_STATUS 604 // param value goes from 0 to 100 (percent)

+#define IPC_CB_CONVERT_DONE   605

+

+

+#define IPC_ADJUST_FFWINDOWSMENUPOS 606

+/* (requires Winamp 2.9+)

+** int newpos=SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)adjust_offset,IPC_ADJUST_FFWINDOWSMENUPOS);

+** This will move where Winamp expects the freeform windows in the menubar windows main

+** menu. This is useful if you wish to insert a menu item above extra freeform windows.

+*/

+

+

+#define IPC_ISDOUBLESIZE 608

+/* (requires Winamp 5.0+)

+** int dsize=SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_ISDOUBLESIZE);

+** You send this to Winamp to query if the double size mode is enabled or not.

+** If it is on then this will return 1 otherwise it will return 0.

+*/

+

+

+#define IPC_ADJUST_FFOPTIONSMENUPOS 609

+/* (requires Winamp 2.9+)

+** int newpos=SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)adjust_offset,IPC_ADJUST_FFOPTIONSMENUPOS);

+** moves where winamp expects the freeform preferences item in the menubar windows main

+** menu. This is useful if you wish to insert a menu item above the preferences item.

+**

+** Note: This setting was ignored by gen_ff until it was fixed in 5.1

+**       gen_ff would assume thatthe menu position was 11 in all cases and so when you

+**       had two plugins attempting to add entries into the main right click menu it

+**       would cause the 'colour themes' submenu to either be incorrectly duplicated or

+**       to just disappear.instead.

+*/

+

+

+#define IPC_GETTIMEDISPLAYMODE 610

+/* (requires Winamp 5.0+)

+** int mode=SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETTIMEDISPLAYMODE);

+** This will return the status of the time display i.e. shows time elapsed or remaining.

+** This returns 0 if Winamp is displaying time elapsed or 1 for the time remaining.

+*/

+

+

+#define IPC_SETVISWND 611

+/* (requires Winamp 5.0+)

+** int viswnd=(HWND)SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)(HWND)viswnd,IPC_SETVISWND);

+** This allows you to set a window to receive the following message commands (which are

+** used as part of the modern skin integration).

+** When you have finished or your visualisation is closed then send wParam as zero to

+** ensure that things are correctly tidied up.

+*/

+

+/* The following messages are received as the LOWORD(wParam) of the WM_COMMAND message.

+** See %SDK%\winamp\wa5vis.txt for more info about visualisation integration in Winamp.

+*/

+#define ID_VIS_NEXT                     40382

+#define ID_VIS_PREV                     40383

+#define ID_VIS_RANDOM                   40384

+#define ID_VIS_FS                       40389

+#define ID_VIS_CFG                      40390

+#define ID_VIS_MENU                     40391

+

+

+#define IPC_GETVISWND 612

+/* (requires Winamp 5.0+)

+** int viswnd=(HWND)SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETVISWND);

+** This returns a HWND to the visualisation command handler window if set by IPC_SETVISWND.

+*/

+

+

+#define IPC_ISVISRUNNING 613

+/* (requires Winamp 5.0+)

+** int visrunning=SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_ISVISRUNNING);

+** This will return 1 if a visualisation is currently running and 0 if one is not running.

+*/

+

+

+#define IPC_CB_VISRANDOM 628 // param is status of random

+

+

+#define IPC_SETIDEALVIDEOSIZE 614

+/* (requires Winamp 5.0+)

+** This is sent by Winamp back to itself so it can be trapped and adjusted as needed with

+** the desired width in HIWORD(wParam) and the desired height in LOWORD(wParam).

+**

+** if(uMsg == WM_WA_IPC){

+**   if(lParam == IPC_SETIDEALVIDEOSIZE){

+**      wParam = MAKEWPARAM(height,width);

+**   }

+** }

+*/

+

+

+#define IPC_GETSTOPONVIDEOCLOSE 615

+/* (requires Winamp 5.0+)

+** int sovc=SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETSTOPONVIDEOCLOSE);

+** This will return 1 if 'stop on video close' is enabled and 0 if it is disabled.

+*/

+

+

+#define IPC_SETSTOPONVIDEOCLOSE 616

+/* (requires Winamp 5.0+)

+** int sovc=SendMessage(hwnd_winamp,WM_WA_IPC,enabled,IPC_SETSTOPONVIDEOCLOSE);

+** Set enabled to 1 to enable and 0 to disable the 'stop on video close' option.

+*/

+

+

+typedef struct {

+  HWND hwnd;

+  int uMsg;

+  WPARAM wParam;

+  LPARAM lParam;

+} transAccelStruct;

+

+#define IPC_TRANSLATEACCELERATOR 617

+/* (requires Winamp 5.0+)

+** (deprecated as of 5.53x+)

+*/

+

+typedef struct {

+  int cmd;

+  int x;

+  int y;

+  int align;

+} windowCommand; // send this as param to an IPC_PLCMD, IPC_MBCMD, IPC_VIDCMD

+

+

+#define IPC_CB_ONTOGGLEAOT 618

+

+

+#define IPC_GETPREFSWND 619

+/* (requires Winamp 5.0+)

+** HWND prefs = (HWND)SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETPREFSWND);

+** This will return a handle to the preferences dialog if it is open otherwise it will

+** return zero. A simple check with the OS api IsWindow(..) is a good test if it's valid.

+**

+** e.g.  this will open (or close if already open) the preferences dialog and show if we

+**       managed to get a valid

+** SendMessage(hwnd_winamp,WM_COMMAND,MAKEWPARAM(WINAMP_OPTIONS_PREFS,0),0);

+** MessageBox(hwnd_winamp,(IsWindow((HWND)SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETPREFSWND))?"Valid":"Not Open"),0,MB_OK);

+*/

+

+

+#define IPC_SET_PE_WIDTHHEIGHT 620

+/* (requires Winamp 5.0+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)&point,IPC_SET_PE_WIDTHHEIGHT);

+** You pass a pointer to a POINT structure which holds the width and height and Winamp

+** will set the playlist editor to that size (this is used by gen_ff on skin changes).

+** There does not appear to be any bounds limiting with this so it is possible to create

+** a zero size playlist editor window (which is a pretty silly thing to do).

+*/

+

+

+#define IPC_GETLANGUAGEPACKINSTANCE 621

+/* (requires Winamp 5.0+)

+** HINSTANCE hInst = (HINSTANCE)SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETLANGUAGEPACKINSTANCE);

+** This will return the HINSTANCE to the currently used language pack file for winamp.exe

+**

+** (5.5+)

+** If you pass 1 in wParam then you will have zero returned if a language pack is in use.

+** if(!SendMessage(hwnd_winamp,WM_WA_IPC,1,IPC_GETLANGUAGEPACKINSTANCE)){

+**   // winamp is currently using a language pack

+** }

+**

+** If you pass 2 in wParam then you will get the path to the language pack folder.

+** wchar_t* lngpackfolder = (wchar_t*)SendMessage(hwnd_winamp,WM_WA_IPC,2,IPC_GETLANGUAGEPACKINSTANCE);

+**

+** If you pass 3 in wParam then you will get the path to the currently extracted language pack.

+** wchar_t* lngpack = (wchar_t*)SendMessage(hwnd_winamp,WM_WA_IPC,3,IPC_GETLANGUAGEPACKINSTANCE);

+**

+** If you pass 4 in wParam then you will get the name of the currently used language pack.

+** wchar_t* lngname = (char*)SendMessage(hwnd_winamp,WM_WA_IPC,4,IPC_GETLANGUAGEPACKINSTANCE);

+*/

+#define LANG_IDENT_STR 0

+#define LANG_LANG_CODE 1

+#define LANG_COUNTRY_CODE 2

+/*

+** (5.51+)

+** If you pass 5 in LOWORD(wParam) then you will get the ident string/code string

+** (based on the param passed in the HIWORD(wParam) of the currently used language pack.

+** The string returned with LANG_IDENT_STR is used to represent the language that the

+** language pack is intended for following ISO naming conventions for consistancy.

+**

+** wchar_t* ident_str = (wchar_t*)SendMessage(hwnd_winamp,WM_WA_IPC,MAKEWPARAM(5,LANG_XXX),IPC_GETLANGUAGEPACKINSTANCE);

+**

+** e.g.

+** For the default language it will return the following for the different LANG_XXX codes

+**    LANG_IDENT_STR ->     "en-US" (max buffer size of this is 9 wchar_t)

+**    LANG_LANG_CODE ->     "en"    (language code)

+**    LANG_COUNTRY_CODE ->  "US"    (country code)

+**

+** On pre 5.51 installs you can get LANG_IDENT_STR using the following method

+** (you'll have to custom process the string returned if you want the langugage or country but that's easy ;) )

+**

+** #define LANG_PACK_LANG_ID 65534 (if you don't have lang.h)

+** HINSTANCE hInst = (HINSTANCE)SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETLANGUAGEPACKINSTANCE);

+** TCHAR buffer[9] = {0};

+** LoadString(hInst,LANG_PACK_LANG_ID,buffer,sizeof(buffer));

+**

+**

+**

+** The following example shows how using the basic api will allow you to load the playlist

+** context menu resource from the currently loaded language pack or it will fallback to

+** the default winamp.exe instance.

+**

+** HINSTANCE lang = (HINSTANCE)SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETLANGUAGEPACKINSTANCE);

+** HMENU popup = GetSubMenu(GetSubMenu((LoadMenu(lang?lang:GetModuleHandle(0),MAKEINTRESOURCE(101))),2),5);

+**   // do processing as needed on the menu before displaying it

+**   TrackPopupMenuEx(orig,TPM_LEFTALIGN|TPM_LEFTBUTTON|TPM_RIGHTBUTTON,rc.left,rc.bottom,hwnd_owner,0);

+**   DestroyMenu(popup);

+**

+** If you need a specific menu handle then look at IPC_GET_HMENU for more information.

+*/

+

+

+#define IPC_CB_PEINFOTEXT 622 // data is a string, ie: "04:21/45:02"

+

+

+#define IPC_CB_OUTPUTCHANGED 623 // output plugin was changed in config

+

+

+#define IPC_GETOUTPUTPLUGIN 625

+/* (requires Winamp 5.0+)

+** char* outdll = (char*)SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETOUTPUTPLUGIN);

+** This returns a string of the current output plugin's dll name.

+** e.g. if the directsound plugin was selected then this would return 'out_ds.dll'.

+*/

+

+

+#define IPC_SETDRAWBORDERS 626

+/* (requires Winamp 5.0+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,enabled,IPC_SETDRAWBORDERS);

+** Set enabled to 1 to enable and 0 to disable drawing of the playlist editor and winamp

+** gen class windows (used by gen_ff to allow it to draw its own window borders).

+*/

+

+

+#define IPC_DISABLESKINCURSORS 627

+/* (requires Winamp 5.0+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,enabled,IPC_DISABLESKINCURSORS);

+** Set enabled to 1 to enable and 0 to disable the use of skinned cursors.

+*/

+

+

+#define IPC_GETSKINCURSORS 628

+/* (requires Winamp 5.36+)

+** data = (WACURSOR)cursorId. (check wa_dlg.h for values)

+*/

+

+

+#define IPC_CB_RESETFONT 629

+

+

+#define IPC_IS_FULLSCREEN 630

+/* (requires Winamp 5.0+)

+** int val=SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_IS_FULLSCREEN);

+** This will return 1 if the video or visualisation is in fullscreen mode or 0 otherwise.

+*/

+

+

+#define IPC_SET_VIS_FS_FLAG 631

+/* (requires Winamp 5.0+)

+** A vis should send this message with 1/as param to notify winamp that it has gone to or has come back from fullscreen mode

+*/

+

+

+#define IPC_SHOW_NOTIFICATION 632

+

+

+#define IPC_GETSKININFO 633

+#define IPC_GETSKININFOW 1633

+/* (requires Winamp 5.0+)

+** This is a notification message sent to the main Winamp window by itself whenever it

+** needs to get information to be shown about the current skin in the 'Current skin

+** information' box on the main Skins page in the Winamp preferences.

+**

+** When this notification is received and the current skin is one you are providing the

+** support for then you return a valid buffer for Winamp to be able to read from with

+** information about it such as the name of the skin file.

+**

+** if(uMsg == WM_WA_IPC && lParam == IPC_GETSKININFO){

+**   if(is_our_skin()){

+**      return is_our_skin_name();

+**   }

+** }

+*/

+

+

+#define IPC_GET_MANUALPLADVANCE 634

+/* (requires Winamp 5.03+)

+** int val=SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GET_MANUALPLADVANCE);

+** IPC_GET_MANUALPLADVANCE returns the status of the Manual Playlist Advance.

+** If enabled this will return 1 otherwise it will return 0.

+*/

+

+

+#define IPC_SET_MANUALPLADVANCE 635

+/* (requires Winamp 5.03+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,value,IPC_SET_MANUALPLADVANCE);

+** IPC_SET_MANUALPLADVANCE sets the status of the Manual Playlist Advance option.

+** Set value = 1 to turn it on and value = 0 to turn it off.

+*/

+

+

+#define IPC_GET_NEXT_PLITEM 636

+/* (requires Winamp 5.04+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_EOF_GET_NEXT_PLITEM);

+**

+** Sent to Winamp's main window when an item has just finished playback or the next

+** button has been pressed and requesting the new playlist item number to go to.

+**

+** Subclass this message in your application to return the new item number.

+** Return -1 for normal Winamp operation (default) or the new item number in

+** the playlist to be played instead of the originally selected next track.

+**

+** This is primarily provided for the JTFE plugin (gen_jumpex.dll).

+*/

+

+

+#define IPC_GET_PREVIOUS_PLITEM 637

+/* (requires Winamp 5.04+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_EOF_GET_PREVIOUS_PLITEM);

+**

+** Sent to Winamp's main window when the previous button has been pressed and Winamp is

+** requesting the new playlist item number to go to.

+**

+** Return -1 for normal Winamp operation (default) or the new item number in

+** the playlist to be played instead of the originally selected previous track.

+**

+** This is primarily provided for the JTFE plugin (gen_jumpex.dll).

+*/

+

+

+#define IPC_IS_WNDSHADE 638

+/* (requires Winamp 5.04+)

+** int is_shaded=SendMessage(hwnd_winamp,WM_WA_IPC,wnd,IPC_IS_WNDSHADE);

+** Pass 'wnd' as an id as defined for IPC_GETWND or pass -1 to query the status of the

+** main window. This returns 1 if the window is in winshade mode and 0 if it is not.

+** Make sure you only test for this on a 5.04+ install otherwise you get a false result.

+** (See the notes about unhandled WM_WA_IPC messages).

+*/

+

+

+#define IPC_SETRATING 639

+/* (requires Winamp 5.04+ with ML)

+** int rating=SendMessage(hwnd_winamp,WM_WA_IPC,rating,IPC_SETRATING);

+** This will allow you to set the 'rating' on the current playlist entry where 'rating'

+** is an integer value from 0 (no rating) to 5 (5 stars).

+**

+** The following example should correctly allow you to set the rating for any specified

+** playlist entry assuming of course that you're trying to get a valid playlist entry.

+**

+** void SetPlaylistItemRating(int item_to_set, int rating_to_set){

+** int cur_pos=SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETLISTPOS);

+**   SendMessage(hwnd_winamp,WM_WA_IPC,item_to_set,IPC_SETPLAYLISTPOS);

+**   SendMessage(hwnd_winamp,WM_WA_IPC,rating_to_set,IPC_SETRATING);

+**   SendMessage(hwnd_winamp,WM_WA_IPC,cur_pos,IPC_SETPLAYLISTPOS);

+** }

+*/

+

+

+#define IPC_GETRATING 640

+/* (requires Winamp 5.04+ with ML)

+** int rating=SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETRATING);

+** This returns the current playlist entry's rating between 0 (no rating) to 5 (5 stars).

+**

+** The following example should correctly allow you to get the rating for any specified

+** playlist entry assuming of course that you're trying to get a valid playlist entry.

+**

+** int GetPlaylistItemRating(int item_to_get, int rating_to_set){

+** int cur_pos=SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETLISTPOS), rating = 0;

+**   SendMessage(hwnd_winamp,WM_WA_IPC,item_to_get,IPC_SETPLAYLISTPOS);

+**   rating = SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETRATING);

+**   SendMessage(hwnd_winamp,WM_WA_IPC,cur_pos,IPC_SETPLAYLISTPOS);

+**   return rating;

+** }

+*/

+

+

+#define IPC_GETNUMAUDIOTRACKS 641

+/* (requires Winamp 5.04+)

+** int n = SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETNUMAUDIOTRACKS);

+** This will return the number of audio tracks available from the currently playing item.

+*/

+

+

+#define IPC_GETNUMVIDEOTRACKS 642

+/* (requires Winamp 5.04+)

+** int n = SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETNUMVIDEOTRACKS);

+** This will return the number of video tracks available from the currently playing item.

+*/

+

+

+#define IPC_GETAUDIOTRACK 643

+/* (requires Winamp 5.04+)

+** int cur = SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETAUDIOTRACK);

+** This will return the id of the current audio track for the currently playing item.

+*/

+

+

+#define IPC_GETVIDEOTRACK 644

+/* (requires Winamp 5.04+)

+** int cur = SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETVIDEOTRACK);

+** This will return the id of the current video track for the currently playing item.

+*/

+

+

+#define IPC_SETAUDIOTRACK 645

+/* (requires Winamp 5.04+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,track,IPC_SETAUDIOTRACK);

+** This allows you to switch to a new audio track (if supported) in the current playing file.

+*/

+

+

+#define IPC_SETVIDEOTRACK 646

+/* (requires Winamp 5.04+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,track,IPC_SETVIDEOTRACK);

+** This allows you to switch to a new video track (if supported) in the current playing file.

+*/

+

+

+#define IPC_PUSH_DISABLE_EXIT 647

+/* (requires Winamp 5.04+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_PUSH_DISABLE_EXIT);

+** This will let you disable or re-enable the UI exit functions (close button, context

+** menu, alt-f4). Remember to call IPC_POP_DISABLE_EXIT when you are done doing whatever

+** was required that needed to prevent exit otherwise you have to kill the Winamp process.

+*/

+

+

+#define IPC_POP_DISABLE_EXIT  648

+/* (requires Winamp 5.04+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_POP_DISABLE_EXIT);

+** See IPC_PUSH_DISABLE_EXIT

+*/

+

+

+#define IPC_IS_EXIT_ENABLED 649

+/* (requires Winamp 5.04+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_IS_EXIT_ENABLED);

+** This will return 0 if the 'exit' option of Winamp's menu is disabled and 1 otherwise.

+*/

+

+

+#define IPC_IS_AOT 650

+/* (requires Winamp 5.04+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_IS_AOT);

+** This will return the status of the always on top flag.

+** Note: This may not match the actual TOPMOST window flag while another fullscreen

+** application is focused if the user has the 'Disable always on top while fullscreen

+** applications are focused' option under the  General Preferences page is checked.

+*/

+

+

+#define IPC_USES_RECYCLEBIN 651

+/* (requires Winamp 5.09+)

+** int use_bin=SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_USES_RECYCLEBIN);

+** This will return 1 if the deleted file should be sent to the recycle bin or

+** 0 if deleted files should be deleted permanently (default action for < 5.09).

+**

+** Note: if you use this on pre 5.09 installs of Winamp then it will return 1 which is

+** not correct but is due to the way that SendMessage(..) handles un-processed messages.

+** Below is a quick case for checking if the returned value is correct.

+**

+** if(SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_USES_RECYCLEBIN) &&

+**    SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETVERSION)>=0x5009)

+** {

+**   // can safely follow the option to recycle the file

+** }

+** else

+*  {

+**   // need to do a permanent delete of the file

+** }

+*/

+

+

+#define IPC_FLUSHAUDITS 652

+/*

+** SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_FLUSHAUDITS);

+**

+** Will flush any pending audits in the global audits queue

+**

+*/

+

+#define IPC_GETPLAYITEM_START 653

+#define IPC_GETPLAYITEM_END   654

+

+

+#define IPC_GETVIDEORESIZE 655

+#define IPC_SETVIDEORESIZE 656

+

+

+#define IPC_INITIAL_SHOW_STATE 657

+/* (requires Winamp 5.36+)

+** int show_state = SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_INITIAL_SHOW_STATE);

+** returns the processed value of nCmdShow when Winamp was started

+** (see MSDN documentation the values passed to WinMain(..) for what this should be)

+**

+** e.g.

+** if(SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_INITIAL_SHOW_STATE) == SW_SHOWMINIMIZED){

+**   // we are starting minimised so process as needed (keep our window hidden)

+** }

+**

+** Useful for seeing if winamp was run minimised on startup so you can act accordingly.

+** On pre-5.36 versions this will effectively return SW_NORMAL/SW_SHOWNORMAL due to the

+** handling of unknown apis returning 1 from Winamp.

+*/

+

+// >>>>>>>>>>> Next is 658

+

+#define IPC_PLCMD  1000

+

+#define PLCMD_ADD  0

+#define PLCMD_REM  1

+#define PLCMD_SEL  2

+#define PLCMD_MISC 3

+#define PLCMD_LIST 4

+

+//#define IPC_MBCMD  1001

+

+#define MBCMD_BACK    0

+#define MBCMD_FORWARD 1

+#define MBCMD_STOP    2

+#define MBCMD_RELOAD  3

+#define MBCMD_MISC  4

+

+#define IPC_VIDCMD 1002

+

+#define VIDCMD_FULLSCREEN 0

+#define VIDCMD_1X         1

+#define VIDCMD_2X         2

+#define VIDCMD_LIB        3

+#define VIDPOPUP_MISC     4

+

+//#define IPC_MBURL       1003 //sets the URL

+//#define IPC_MBGETCURURL 1004 //copies the current URL into wParam (have a 4096 buffer ready)

+//#define IPC_MBGETDESC   1005 //copies the current URL description into wParam (have a 4096 buffer ready)

+//#define IPC_MBCHECKLOCFILE 1006 //checks that the link file is up to date (otherwise updates it). wParam=parent HWND

+//#define IPC_MBREFRESH   1007 //refreshes the "now playing" view in the library

+//#define IPC_MBGETDEFURL 1008 //copies the default URL into wParam (have a 4096 buffer ready)

+

+#define IPC_STATS_LIBRARY_ITEMCNT 1300 // updates library count status

+

+/*

+** IPC's in the message range 2000 - 3000 are reserved internally for freeform messages.

+** These messages are taken from ff_ipc.h which is part of the Modern skin integration.

+*/

+

+#define IPC_FF_FIRST 2000

+

+#define IPC_FF_COLOURTHEME_CHANGE IPC_FF_ONCOLORTHEMECHANGED

+#define IPC_FF_ONCOLORTHEMECHANGED IPC_FF_FIRST + 3

+/*

+** This is a notification message sent when the user changes the colour theme in a Modern

+** skin and can also be detected when the Modern skin is first loaded as the gen_ff plugin

+** applies relevant settings and styles (like the colour theme).

+**

+** The value of wParam is the name of the new color theme being switched to.

+** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)(const char*)colour_theme_name,IPC_FF_ONCOLORTHEMECHANGED);

+**

+** (IPC_FF_COLOURTHEME_CHANGE is the name i (DrO) was using before getting a copy of

+** ff_ipc.h with the proper name in it).

+*/

+

+

+#define IPC_FF_ISMAINWND IPC_FF_FIRST + 4

+/*

+** int ismainwnd = (HWND)SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)(HWND)test_wnd,IPC_FF_ISMAINWND);

+**

+** This allows you to determine if the window handle passed to it is a modern skin main

+** window or not. If it is a main window or any of its windowshade variants then it will

+** return 1.

+**

+** Because of the way modern skins are implemented, it is possible for this message to

+** return a positive test result for a number of window handles within the current Winamp

+** process. This appears to be because you can have a visible main window, a compact main

+** window and also a winshaded version.

+**

+** The following code example below is one way of seeing how this api works since it will

+** enumerate all windows related to Winamp at the time and allows you to process as

+** required when a detection happens.

+**

+**

+** EnumThreadWindows(GetCurrentThreadId(),enumWndProc,0);

+**

+** BOOL CALLBACK enumWndProc(HWND hwnd, LPARAM lParam){

+**

+**   if(SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)hwnd,IPC_FF_ISMAINWND)){

+**     // do processing in here

+**     // or continue the enum for other main windows (if they exist)

+**     // and just comment out the line below

+**     return 0;

+**   }

+**   return 1;

+** }

+*/

+

+

+#define IPC_FF_GETCONTENTWND IPC_FF_FIRST + 5

+/*

+** HWND wa2embed = (HWND)SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)(HWND)test_wnd,IPC_FF_GETCONTENTWND);

+**

+** This will return the Winamp 2 window that is embedded in the window's container

+** i.e. if hwnd is the playlist editor windowshade hwnd then it will return the Winamp 2

+**      playlist editor hwnd.

+**

+** If no content is found such as the window has nothing embedded then this will return

+** the hwnd passed to it.

+*/

+

+

+#define IPC_FF_NOTIFYHOTKEY IPC_FF_FIRST + 6

+/*

+** This is a notification message sent when the user uses a global hotkey combination

+** which had been registered with the gen_hotkeys plugin.

+**

+** The value of wParam is the description of the hotkey as passed to gen_hotkeys.

+** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)(const char*)hotkey_desc,IPC_FF_NOTIFYHOTKEY);

+*/

+

+#define IPC_FF_LAST  3000

+

+

+/*

+** General IPC messages in Winamp

+**

+** All notification messages appear in the lParam of the main window message proceedure.

+*/

+

+

+#define IPC_GETDROPTARGET 3001

+/* (requires Winamp 5.0+)

+** IDropTarget* IDrop = (IDropTarget*)SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETDROPTARGET);

+**

+** You call this to retrieve a copy of the IDropTarget interface which Winamp created for

+** handling external drag and drop operations on to it's Windows. This is only really

+** useful if you're providing an alternate interface and want your Windows to provide the

+** same drag and drop support as Winamp normally provides the user. Check out MSDN or

+** your prefered search facility for more information about the IDropTarget interface and

+** what's needed to handle it in your own instance.

+*/

+

+

+#define IPC_PLAYLIST_MODIFIED 3002

+/* (requires Winamp 5.0+)

+** This is a notification message sent to the main Winamp window whenever the playlist is

+** modified in any way e.g. the addition/removal of a playlist entry.

+**

+** It is not a good idea to do large amounts of processing in this notification since it

+** will slow down Winamp as playlist entries are modified (especially when you're adding

+** in a large playlist).

+**

+** if(uMsg == WM_WA_IPC && lParam == IPC_PLAYLIST_MODIFIED)

+** {

+**   // do what you need to do here

+** }

+*/

+

+

+#define IPC_PLAYING_FILE 3003

+/* (requires Winamp 5.0+)

+** This is a notification message sent to the main Winamp window when playback begins for

+** a file. This passes the full filepath in the wParam of the message received.

+**

+** if(uMsg == WM_WA_IPC && lParam == IPC_PLAYING_FILE)

+** {

+**   // do what you need to do here, e.g.

+**   process_file((char*)wParam);

+** }

+*/

+

+

+#define IPC_PLAYING_FILEW 13003

+/* (requires Winamp 5.0+)

+** This is a notification message sent to the main Winamp window when playback begins for

+** a file. This passes the full filepath in the wParam of the message received.

+**

+** if(uMsg == WM_WA_IPC && lParam == IPC_PLAYING_FILEW)

+** {

+**   // do what you need to do here, e.g.

+**   process_file((wchar_t*)wParam);

+** }

+*/

+

+

+#define IPC_FILE_TAG_MAY_HAVE_UPDATED 3004

+#define IPC_FILE_TAG_MAY_HAVE_UPDATEDW 3005

+/* (requires Winamp 5.0+)

+** This is a notification message sent to the main Winamp window when a file's tag

+** (e.g. id3) may have been updated. This appears to be sent when the InfoBox(..) function

+** of the associated input plugin returns a 1 (which is the file information dialog/editor

+** call normally).

+**

+** if(uMsg == WM_WA_IPC && lParam == IPC_FILE_TAG_MAY_HAVE_UPDATED)

+** {

+**   // do what you need to do here, e.g.

+**   update_info_on_file_update((char*)wParam);

+** }

+*/

+

+

+#define IPC_ALLOW_PLAYTRACKING 3007

+/* (requires Winamp 5.0+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,allow,IPC_ALLOW_PLAYTRACKING);

+** Send allow as nonzero to allow play tracking and zero to disable the mode.

+*/

+

+

+#define IPC_HOOK_OKTOQUIT 3010

+/* (requires Winamp 5.0+)

+** This is a notification message sent to the main Winamp window asking if it's okay to

+** close or not. Return zero to prevent Winamp from closing or return anything non-zero

+** to allow Winamp to close.

+**

+** The best implementation of this option is to let the message pass through to the

+** original window proceedure since another plugin may want to have a say in the matter

+** with regards to Winamp closing.

+**

+** if(uMsg == WM_WA_IPC && lParam == IPC_HOOK_OKTOQUIT)

+** {

+**   // do what you need to do here, e.g.

+**   if(no_shut_down())

+**   {

+**     return 1;

+**   }

+** }

+*/

+

+

+#define IPC_WRITECONFIG 3011

+/* (requires Winamp 5.0+)

+** SendMessage(hwnd_winamp,WM_WA_IPC,write_type,IPC_WRITECONFIG);

+**

+** Send write_type as 2 to write all config settings and the current playlist.

+**

+** Send write_type as 1 to write the playlist and common settings.

+** This won't save the following ini settings::

+**

+**   defext, titlefmt, proxy, visplugin_name, dspplugin_name, check_ft_startup,

+**   visplugin_num, pe_fontsize, visplugin_priority, visplugin_autoexec, dspplugin_num,

+**   sticon, splash, taskbar, dropaotfs, ascb_new, ttips, riol, minst, whichicon,

+**   whichicon2, addtolist, snap, snaplen, parent, hilite, disvis, rofiob, shownumsinpl,

+**   keeponscreen, eqdsize, usecursors, fixtitles, priority, shuffle_morph_rate,

+**   useexttitles, bifont, inet_mode, ospb, embedwnd_freesize, no_visseh

+** (the above was valid for 5.1)

+**

+** Send write_type as 0 to write the common and less common settings and no playlist.

+*/

+

+

+#define IPC_UPDATE_URL 3012

+// pass the URL (char *) in lparam, will be free()'d on done.

+

+

+#define IPC_GET_RANDFUNC 3015 // returns a function to get a random number

+/* (requires Winamp 5.1+)

+** int (*randfunc)(void) = (int(*)(void))SendMessage(plugin.hwndParent,WM_WA_IPC,0,IPC_GET_RANDFUNC);

+** if(randfunc && randfunc != 1){

+**   randfunc();

+** }

+**

+** This will return a positive 32-bit number (essentially 31-bit).

+** The check for a returned value of 1 is because that's the default return value from

+** SendMessage(..) when it is not handled so is good to check for it in this situation.

+*/

+

+

+#define IPC_METADATA_CHANGED 3017

+/* (requires Winamp 5.1+)

+** int changed=SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)(char*)field,IPC_METADATA_CHANGED);

+** a plugin can SendMessage this to winamp if internal metadata has changes.

+** wParam should be a char * of what field changed

+**

+** Currently used for internal actions (and very few at that) the intent of this api is

+** to allow a plugin to call it when metadata has changed in the current playlist entry

+** e.g.a new id3v2 tag was found in a stream

+**

+** The wparam value can either be NULL or a pointer to an ansi string for the metadata

+** which has changed. This can be thought of as an advanced version of IPC_UPDTITLE and

+** could be used to allow for update of the current title when a specific tag changed.

+**

+** Not recommended to be used since there is not the complete handling implemented in

+** Winamp for it at the moment.

+*/

+

+

+#define IPC_SKIN_CHANGED 3018

+/* (requires Winamp 5.1+)

+** This is a notification message sent to the main Winamp window by itself whenever

+** the skin in use is changed. There is no information sent by the wParam for this.

+**

+** if(message == WM_WA_IPC && lparam == IPC_SKIN_CHANGED)

+** {

+**   // do what you need to do to handle skin changes, e.g. call WADlg_init(hwnd_winamp);

+** }

+*/

+

+

+#define IPC_REGISTER_LOWORD_COMMAND 3019

+/* (requires Winamp 5.1+)

+** WORD id = SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_REGISTER_LOWORD_COMMAND);

+** This will assign you a unique id for making your own commands such as for extra menu

+** entries. The starting value returned by this message will potentially change as and

+** when the main resource file of Winamp is updated with extra data so assumptions cannot

+** be made on what will be returned and plugin loading order will affect things as well.

+

+** 5.33+

+** If you want to reserve more than one id, you can pass the number of ids required in wParam

+*/

+

+

+#define IPC_GET_DISPATCH_OBJECT 3020  // gets winamp main IDispatch * (for embedded webpages)

+#define IPC_GET_UNIQUE_DISPATCH_ID 3021 // gives you a unique dispatch ID that won't conflict with anything in winamp's IDispatch *

+#define IPC_ADD_DISPATCH_OBJECT 3022 // add your own dispatch object into winamp's.  This lets embedded webpages access your functions

+// pass a pointer to DispatchInfo (see below).  Winamp makes a copy of all this data so you can safely delete it later

+typedef struct

+{

+  wchar_t *name; // filled in by plugin, make sure it's a unicode string!! (i.e. L"myObject" instead of "myObject).

+  struct IDispatch *dispatch; // filled in by plugin

+  DWORD id; // filled in by winamp on return

+} DispatchInfo;

+

+// see IPC_JSAPI2_GET_DISPATCH_OBJECT for version 2 of the Dispatchable scripting interface

+

+#define IPC_GET_PROXY_STRING 3023

+/* (requires Winamp 5.11+)

+** char* proxy_string=(char*)SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GET_PROXY_STRING);

+** This will return the same string as is shown on the General Preferences page.

+*/

+

+

+#define IPC_USE_REGISTRY 3024

+/* (requires Winamp 5.11+)

+** int reg_enabled=SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_USE_REGISTRY);

+** This will return 0 if you should leave your grubby hands off the registry (i.e. for

+** lockdown mode). This is useful if Winamp is run from a USB drive and you can't alter

+** system settings, etc.

+*/

+

+

+#define IPC_GET_API_SERVICE 3025

+/* (requires Winamp 5.12+)

+** api_service* api_service = (api_service)SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GET_API_SERVICE);

+** This api will return Winamp's api_service pointer (which is what Winamp3 used, heh).

+** If this api is not supported in the Winamp version that is being used at the time then

+** the returned value from this api will be 1 which is a good version check.

+**

+** As of 5.12 there is support for .w5s plugins which reside in %WinampDir%\System and

+** are intended for common code that can be shared amongst other plugins e.g. jnetlib.w5s

+** which contains jnetlib in one instance instead of being duplicated multiple times in

+** all of the plugins which need internet access.

+**

+** Details on the .w5s specifications will come at some stage (possibly).

+*/

+

+

+typedef struct {

+  const wchar_t *filename;

+  const wchar_t *metadata;

+  wchar_t *ret;

+  size_t retlen;

+} extendedFileInfoStructW;

+

+#define IPC_GET_EXTENDED_FILE_INFOW 3026

+/* (requires Winamp 5.13+)

+** Pass a pointer to the above struct in wParam

+*/

+

+

+#define IPC_GET_EXTENDED_FILE_INFOW_HOOKABLE 3027

+#define IPC_SET_EXTENDED_FILE_INFOW 3028

+/* (requires Winamp 5.13+)

+** Pass a pointer to the above struct in wParam

+*/

+

+

+#define IPC_PLAYLIST_GET_NEXT_SELECTED 3029

+/* (requires 5.2+)

+** int pl_item = SendMessage(hwnd_winamp,WM_WA_IPC,start,IPC_PLAYLIST_GET_NEXT_SELECTED);

+**

+** This works just like the ListView_GetNextItem(..) macro for ListView controls.

+** 'start' is the index of the playlist item that you want to begin the search after or

+** set this as -1 for the search to begin with the first item of the current playlist.

+**

+** This will return the index of the selected playlist according to the 'start' value or

+** it returns -1 if there is no selection or no more selected items according to 'start'.

+**

+** Quick example:

+**

+** int sel = -1;

+** // keep incrementing the start of the search so we get all of the selected entries

+** while((sel = SendMessage(hwnd_winamp,WM_WA_IPC,sel,IPC_PLAYLIST_GET_NEXT_SELECTED))!=-1){

+**   // show the playlist file entry of the selected item(s) if there were any

+**   MessageBox(hwnd_winamp,(char*)SendMessage(hwnd_winamp,WM_WA_IPC,sel,IPC_GETPLAYLISTFILE),0,0);

+** }

+*/

+

+

+#define IPC_PLAYLIST_GET_SELECTED_COUNT 3030

+/* (requires 5.2+)

+** int selcnt = SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_PLAYLIST_GET_SELECTED_COUNT);

+** This will return the number of selected playlist entries.

+*/

+

+

+#define IPC_GET_PLAYING_FILENAME 3031

+// returns wchar_t * of the currently playing filename

+

+#define IPC_OPEN_URL 3032

+// send either ANSI or Unicode string (it'll figure it out, but it MUST start with "h"!, so don't send ftp:// or anything funny)

+// you can also send this one from another process via WM_COPYDATA (unicode only)

+

+

+#define IPC_USE_UXTHEME_FUNC 3033

+/* (requires Winamp 5.35+)

+** int ret = SendMessage(hwnd_winamp,WM_WA_IPC,param,IPC_USE_UXTHEME_FUNC);

+** param can be IPC_ISWINTHEMEPRESENT or IPC_ISAEROCOMPOSITIONACTIVE or a valid hwnd.

+**

+** If you pass a hwnd then it will apply EnableThemeDialogTexture(ETDT_ENABLETAB)

+** so your tabbed dialogs can use the correct theme (on supporting OSes ie XP+).

+**

+** Otherwise this will return a value based on the param passed (as defined below).

+** For compatability, the return value will be zero on success (as 1 is returned

+** for unsupported ipc calls on older Winamp versions)

+*/

+  #define IPC_ISWINTHEMEPRESENT 0

+/* This will return 0 if uxtheme.dll is present

+** int isthemethere = !SendMessage(hwnd_winamp,WM_WA_IPC,IPC_ISWINTHEMEPRESENT,IPC_USE_UXTHEME_FUNC);

+*/

+  #define IPC_ISAEROCOMPOSITIONACTIVE 1

+/* This will return 0 if aero composition is active

+** int isaero = !SendMessage(hwnd_winamp,WM_WA_IPC,IPC_ISAEROCOMPOSITIONACTIVE,IPC_USE_UXTHEME_FUNC);

+*/

+

+

+#define IPC_GET_PLAYING_TITLE 3034

+// returns wchar_t * of the current title

+

+

+#define IPC_CANPLAY 3035

+// pass const wchar_t *, returns an in_mod * or 0

+

+

+typedef struct {

+  // fill these in...

+  size_t size; // init to sizeof(artFetchData)

+  HWND parent; // parent window of the dialogue

+

+  // fill as much of these in as you can, otherwise leave them 0

+  const wchar_t *artist;

+  const wchar_t *album;

+  int year, amgArtistId, amgAlbumId;

+

+  int showCancelAll; // if set to 1, this shows a "Cancel All" button on the dialogue

+

+  // winamp will fill these in if the call returns successfully:

+  void* imgData; // a buffer filled with compressed image data. free with WASABI_API_MEMMGR->sysFree()

+  int imgDataLen; // the size of the buffer

+  wchar_t type[10]; // eg: "jpg"

+  const wchar_t *gracenoteFileId; // if you know it

+} artFetchData;

+

+#define IPC_FETCH_ALBUMART 3036

+/* pass an artFetchData*. This will show a dialog guiding the use through choosing art, and return when it's finished

+** return values:

+** 1: error showing dialog

+** 0: success

+** -1: cancel was pressed

+** -2: cancel all was pressed

+*/

+

+#define IPC_JSAPI2_GET_DISPATCH_OBJECT 3037

+/* pass your service's unique ID, as a wchar_t * string, in wParam

+** Winamp will copy the string, so don't worry about keeping it around

+** An IDispatch * object will be returned (cast the return value from SendMessage)

+** This IDispatch can be used for scripting/automation/VB interaction

+** Pass to IE via IDocHostUIHandler::GetExternal and it will become window.external in javscript

+*/

+

+#define IPC_REGISTER_WINAMP_IPCMESSAGE 65536

+/* (requires Winamp 5.0+)

+** DWORD id = SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)name,IPC_REGISTER_WINAMP_IPCMESSAGE);

+** The value 'id' returned is > 65536 and is incremented on subsequent calls for unique

+** 'name' values passed to it. By using the same 'name' in different plugins will allow a

+** common runtime api to be provided for the currently running instance of Winamp

+** e.g.

+**   PostMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)my_param,registered_ipc);

+** Have a look at wa_hotkeys.h for an example on how this api is used in practice for a

+** custom WM_WA_IPC message.

+**

+** if(uMsg == WM_WA_IPC && lParam == id_from_register_winamp_ipcmessage){

+**   // do things

+** }

+*/

+

+#endif//_WA_IPC_H_

 

--- a/src/in_xsf_framework/wstring_convert.h
+++ /dev/null
@@ -1,184 +1,1 @@
-// This comes from llvm's libcxx project. I've copied the code from there (with very minor modifications) for use with GCC and Clang when libcxx isn't being used.
 
-#if (defined(__GNUC__) || defined(__clang__)) && !defined(_LIBCPP_VERSION)
-#pragma once
-
-#include <memory>
-#include <string>
-#include <locale>
-
-namespace std
-{
-
-template<class _Codecvt, class _Elem = wchar_t, class _Wide_alloc = allocator<_Elem>, class _Byte_alloc = allocator<char>> class wstring_convert
-{
-public:
-	typedef basic_string<char, char_traits<char>, _Byte_alloc> byte_string;
-	typedef basic_string<_Elem, char_traits<_Elem>, _Wide_alloc> wide_string;
-	typedef typename _Codecvt::state_type state_type;
-	typedef typename wide_string::traits_type::int_type int_type;
-
-private:
-	byte_string __byte_err_string_;
-	wide_string __wide_err_string_;
-	_Codecvt *__cvtptr_;
-	state_type __cvtstate_;
-	size_t __cvtcount_;
-
-	wstring_convert(const wstring_convert &__wc);
-	wstring_convert& operator=(const wstring_convert &__wc);
-public:
-	wstring_convert(_Codecvt *__pcvt = new _Codecvt) : __cvtptr_(__pcvt), __cvtstate_(), __cvtcount_(0) { }
-	wstring_convert(_Codecvt *__pcvt, state_type __state) : __cvtptr_(__pcvt), __cvtstate_(__state), __cvtcount_(0) { }
-	wstring_convert(const byte_string &__byte_err, const wide_string &__wide_err = wide_string()) : __byte_err_string_(__byte_err), __wide_err_string_(__wide_err), __cvtptr_(new _Codecvt), __cvtstate_(), __cvtcount_(0) { }
-	wstring_convert(wstring_convert &&__wc) : __byte_err_string_(move(__wc.__byte_err_string_)), __wide_err_string_(move(__wc.__wide_err_string_)), __cvtptr_(__wc.__cvtptr_), __cvtstate_(__wc.__cvtstate_), __cvtcount_(__wc.__cvtstate_)
-	{
-		__wc.__cvtptr_ = nullptr;
-	}
-	~wstring_convert() { delete this->__cvtptr_; }
-
-	wide_string from_bytes(char __byte) { return from_bytes(&__byte, &__byte + 1); }
-	wide_string from_bytes(const char *__ptr) { return from_bytes(__ptr, __ptr + char_traits<char>::length(__ptr)); }
-	wide_string from_bytes(const byte_string &__str) { return from_bytes(__str.data(), __str.data() + __str.size()); }
-	wide_string from_bytes(const char *__frm, const char *__frm_end)
-	{
-		this->__cvtcount_ = 0;
-		if (this->__cvtptr_)
-		{
-			wide_string __ws(2 * (__frm_end - __frm), _Elem());
-			if (__frm != __frm_end)
-				__ws.resize(__ws.capacity());
-			auto __r = codecvt_base::ok;
-			auto __st = this->__cvtstate_;
-			if (__frm != __frm_end)
-			{
-				auto __to = &__ws[0];
-				auto __to_end = __to + __ws.size();
-				const char *__frm_nxt;
-				do
-				{
-					_Elem *__to_nxt;
-					__r = this->__cvtptr_->in(__st, __frm, __frm_end, __frm_nxt, __to, __to_end, __to_nxt);
-					this->__cvtcount_ += __frm_nxt - __frm;
-					if (__frm_nxt == __frm)
-						__r = codecvt_base::error;
-					else if (__r == codecvt_base::noconv)
-					{
-						__ws.resize(__to - &__ws[0]);
-						// This only gets executed if _Elem is char
-						__ws.append(reinterpret_cast<const _Elem *>(__frm), reinterpret_cast<const _Elem *>(__frm_end));
-						__frm = __frm_nxt;
-						__r = codecvt_base::ok;
-					}
-					else if (__r == codecvt_base::ok)
-					{
-						__ws.resize(__to_nxt - &__ws[0]);
-						__frm = __frm_nxt;
-					}
-					else if (__r == codecvt_base::partial)
-					{
-						ptrdiff_t __s = __to_nxt - &__ws[0];
-						__ws.resize(2 * __s);
-						__to = &__ws[0] + __s;
-						__to_end = &__ws[0] + __ws.size();
-						__frm = __frm_nxt;
-					}
-				} while (__r == codecvt_base::partial && __frm_nxt < __frm_end);
-			}
-			if (__r == codecvt_base::ok)
-				return __ws;
-		}
-		if (this->__wide_err_string_.empty())
-			throw range_error("wstring_convert: from_bytes error");
-		return this->__wide_err_string_;
-	}
-
-	byte_string to_bytes(_Elem __wchar) { return to_bytes(&__wchar, &__wchar + 1); }
-	byte_string to_bytes(const _Elem *__wptr) { return to_bytes(__wptr, __wptr + char_traits<_Elem>::length(__wptr)); }
-	byte_string to_bytes(const wide_string &__wstr) { return to_bytes(__wstr.data(), __wstr.data() + __wstr.size()); }
-	byte_string to_bytes(const _Elem *__frm, const _Elem *__frm_end)
-	{
-		this->__cvtcount_ = 0;
-		if (this->__cvtptr_)
-		{
-			byte_string __bs(2 * (__frm_end - __frm), char());
-			if (__frm != __frm_end)
-				__bs.resize(__bs.capacity());
-			auto __r = codecvt_base::ok;
-			auto __st = this->__cvtstate_;
-			if (__frm != __frm_end)
-			{
-				auto __to = &__bs[0];
-				auto __to_end = __to + __bs.size();
-				const _Elem *__frm_nxt;
-				do
-				{
-					char *__to_nxt;
-					__r = this->__cvtptr_->out(__st, __frm, __frm_end, __frm_nxt, __to, __to_end, __to_nxt);
-					this->__cvtcount_ += __frm_nxt - __frm;
-					if (__frm_nxt == __frm)
-						__r = codecvt_base::error;
-					else if (__r == codecvt_base::noconv)
-					{
-						__bs.resize(__to - &__bs[0]);
-						// This only gets executed if _Elem is char
-						__bs.append(reinterpret_cast<const char *>(__frm), reinterpret_cast<const char *>(__frm_end));
-						__frm = __frm_nxt;
-						__r = codecvt_base::ok;
-					}
-					else if (__r == codecvt_base::ok)
-					{
-						__bs.resize(__to_nxt - &__bs[0]);
-						__frm = __frm_nxt;
-					}
-					else if (__r == codecvt_base::partial)
-					{
-						ptrdiff_t __s = __to_nxt - &__bs[0];
-						__bs.resize(2 * __s);
-						__to = &__bs[0] + __s;
-						__to_end = &__bs[0] + __bs.size();
-						__frm = __frm_nxt;
-					}
-				} while (__r == codecvt_base::partial && __frm_nxt < __frm_end);
-			}
-			if (__r == codecvt_base::ok)
-			{
-				auto __s = __bs.size();
-				__bs.resize(__bs.capacity());
-				auto __to = &__bs[0] + __s;
-				auto __to_end = __to + __bs.size();
-				do
-				{
-					char *__to_nxt;
-					__r = this->__cvtptr_->unshift(__st, __to, __to_end, __to_nxt);
-					if (__r == codecvt_base::noconv)
-					{
-						__bs.resize(__to - &__bs[0]);
-						__r = codecvt_base::ok;
-					}
-					else if (__r == codecvt_base::ok)
-						__bs.resize(__to_nxt - &__bs[0]);
-					else if (__r == codecvt_base::partial)
-					{
-						ptrdiff_t __sp = __to_nxt - &__bs[0];
-						__bs.resize(2 * __sp);
-						__to = &__bs[0] + __sp;
-						__to_end = &__bs[0] + __bs.size();
-					}
-				} while (__r == codecvt_base::partial);
-				if (__r == codecvt_base::ok)
-					return __bs;
-			}
-		}
-		if (this->__byte_err_string_.empty())
-			throw range_error("wstring_convert: to_bytes error");
-		return this->__byte_err_string_;
-	}
-
-	size_t converted() const noexcept { return this->__cvtcount_; }
-	state_type state() const { return this->__cvtstate_; }
-};
-
-}
-#endif
-

directory:b/src/in_xsf_framework/zlib (new)
--- /dev/null
+++ b/src/in_xsf_framework/zlib