diff --git a/plugins/spu2-x/src/ADSR.cpp b/plugins/spu2-x/src/ADSR.cpp index beb0219de3..d24d80ebcb 100644 --- a/plugins/spu2-x/src/ADSR.cpp +++ b/plugins/spu2-x/src/ADSR.cpp @@ -19,219 +19,201 @@ static const s32 ADSR_MAX_VOL = 0x7fffffff; -static const int InvExpOffsets[] = { 0,4,6,8,9,10,11,12 }; +static const int InvExpOffsets[] = {0, 4, 6, 8, 9, 10, 11, 12}; static u32 PsxRates[160]; -void InitADSR() // INIT ADSR +void InitADSR() // INIT ADSR { - for (int i=0; i<(32+128); i++) - { - int shift=(i-32)>>2; - s64 rate=(i&3)+4; - if (shift<0) - rate >>= -shift; - else - rate <<= shift; + for (int i = 0; i < (32 + 128); i++) { + int shift = (i - 32) >> 2; + s64 rate = (i & 3) + 4; + if (shift < 0) + rate >>= -shift; + else + rate <<= shift; - PsxRates[i] = (int)std::min( rate, (s64)0x3fffffffLL ); - } + PsxRates[i] = (int)std::min(rate, (s64)0x3fffffffLL); + } } // Returns the linear slide value for AR and SR inputs. // (currently not used, it's buggy) -static int GetLinearSrAr( uint SrAr ) +static int GetLinearSrAr(uint SrAr) { - // The Sr/Ar settings work in quarter steps, which means - // the bottom 2 bits go on the left side of the shift, and - // the right side of the shift gets divided by 4: + // The Sr/Ar settings work in quarter steps, which means + // the bottom 2 bits go on the left side of the shift, and + // the right side of the shift gets divided by 4: - const uint newSr = 0x7f - SrAr; - return ((1|(newSr&3)) << (newSr>>2)); + const uint newSr = 0x7f - SrAr; + return ((1 | (newSr & 3)) << (newSr >> 2)); } bool V_ADSR::Calculate() { - pxAssume( Phase != 0 ); + pxAssume(Phase != 0); - if(Releasing && (Phase < 5)) - Phase = 5; + if (Releasing && (Phase < 5)) + Phase = 5; - switch (Phase) - { - case 1: // attack - if( Value == ADSR_MAX_VOL ) - { - // Already maxed out. Progress phase and nothing more: - Phase++; - break; - } + switch (Phase) { + case 1: // attack + if (Value == ADSR_MAX_VOL) { + // Already maxed out. Progress phase and nothing more: + Phase++; + break; + } - // Case 1 below is for pseudo exponential below 75%. - // Pseudo Exp > 75% and Linear are the same. + // Case 1 below is for pseudo exponential below 75%. + // Pseudo Exp > 75% and Linear are the same. - if( AttackMode && (Value>=0x60000000) ) - Value += PsxRates[(AttackRate^0x7f)-0x18+32]; - else - Value += PsxRates[(AttackRate^0x7f)-0x10+32]; + if (AttackMode && (Value >= 0x60000000)) + Value += PsxRates[(AttackRate ^ 0x7f) - 0x18 + 32]; + else + Value += PsxRates[(AttackRate ^ 0x7f) - 0x10 + 32]; - if( Value < 0 ) - { - // We hit the ceiling. - Phase++; - Value = ADSR_MAX_VOL; - } - break; + if (Value < 0) { + // We hit the ceiling. + Phase++; + Value = ADSR_MAX_VOL; + } + break; - case 2: // decay - { - u32 off = InvExpOffsets[(Value>>28)&7]; - Value -= PsxRates[((DecayRate^0x1f)*4)-0x18+off+32]; + case 2: // decay + { + u32 off = InvExpOffsets[(Value >> 28) & 7]; + Value -= PsxRates[((DecayRate ^ 0x1f) * 4) - 0x18 + off + 32]; - // calculate sustain level as a factor of the ADSR maximum volume. + // calculate sustain level as a factor of the ADSR maximum volume. - s32 suslev = ((0x80000000 / 0x10 ) * (SustainLevel+1)) - 1; + s32 suslev = ((0x80000000 / 0x10) * (SustainLevel + 1)) - 1; - if( Value <= suslev ) - { - if (Value < 0) - Value = 0; - Phase++; - } - } - break; + if (Value <= suslev) { + if (Value < 0) + Value = 0; + Phase++; + } + } break; - case 3: // sustain - { - // 0x7f disables sustain (infinite sustain) - if( SustainRate == 0x7f ) return true; + case 3: // sustain + { + // 0x7f disables sustain (infinite sustain) + if (SustainRate == 0x7f) + return true; - if (SustainMode&2) // decreasing - { - if (SustainMode&4) // exponential - { - u32 off = InvExpOffsets[(Value>>28)&7]; - Value -= PsxRates[(SustainRate^0x7f)-0x1b+off+32]; - } - else // linear - Value -= PsxRates[(SustainRate^0x7f)-0xf+32]; + if (SustainMode & 2) // decreasing + { + if (SustainMode & 4) // exponential + { + u32 off = InvExpOffsets[(Value >> 28) & 7]; + Value -= PsxRates[(SustainRate ^ 0x7f) - 0x1b + off + 32]; + } else // linear + Value -= PsxRates[(SustainRate ^ 0x7f) - 0xf + 32]; - if( Value <= 0 ) - { - Value = 0; - Phase++; - } - } - else // increasing - { - if( (SustainMode&4) && (Value>=0x60000000) ) - Value += PsxRates[(SustainRate^0x7f)-0x18+32]; - else - // linear / Pseudo below 75% (they're the same) - Value += PsxRates[(SustainRate^0x7f)-0x10+32]; + if (Value <= 0) { + Value = 0; + Phase++; + } + } else { // increasing + if ((SustainMode & 4) && (Value >= 0x60000000)) + Value += PsxRates[(SustainRate ^ 0x7f) - 0x18 + 32]; + else + // linear / Pseudo below 75% (they're the same) + Value += PsxRates[(SustainRate ^ 0x7f) - 0x10 + 32]; - if( Value < 0 ) - { - Value = ADSR_MAX_VOL; - Phase++; - } - } - } - break; + if (Value < 0) { + Value = ADSR_MAX_VOL; + Phase++; + } + } + } break; - case 4: // sustain end - Value = (SustainMode&2) ? 0 : ADSR_MAX_VOL; - if(Value==0) - Phase=6; - break; + case 4: // sustain end + Value = (SustainMode & 2) ? 0 : ADSR_MAX_VOL; + if (Value == 0) + Phase = 6; + break; - case 5: // release - if (ReleaseMode) // exponential - { - u32 off=InvExpOffsets[(Value>>28)&7]; - Value-=PsxRates[((ReleaseRate^0x1f)*4)-0x18+off+32]; - } - else // linear - { - //Value-=PsxRates[((ReleaseRate^0x1f)*4)-0xc+32]; - if( ReleaseRate != 0x1f ) - Value -= (1 << (0x1f-ReleaseRate)); - } + case 5: // release + if (ReleaseMode) // exponential + { + u32 off = InvExpOffsets[(Value >> 28) & 7]; + Value -= PsxRates[((ReleaseRate ^ 0x1f) * 4) - 0x18 + off + 32]; + } else { // linear + //Value-=PsxRates[((ReleaseRate^0x1f)*4)-0xc+32]; + if (ReleaseRate != 0x1f) + Value -= (1 << (0x1f - ReleaseRate)); + } - if( Value <= 0 ) - { - Value=0; - Phase++; - } - break; + if (Value <= 0) { + Value = 0; + Phase++; + } + break; - case 6: // release end - Value=0; - break; + case 6: // release end + Value = 0; + break; - jNO_DEFAULT - } + jNO_DEFAULT + } - // returns true if the voice is active, or false if it's stopping. - return Phase != 6; + // returns true if the voice is active, or false if it's stopping. + return Phase != 6; } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// // // -#define VOLFLAG_REVERSE_PHASE (1ul<<0) -#define VOLFLAG_DECREMENT (1ul<<1) -#define VOLFLAG_EXPONENTIAL (1ul<<2) -#define VOLFLAG_SLIDE_ENABLE (1ul<<3) +#define VOLFLAG_REVERSE_PHASE (1ul << 0) +#define VOLFLAG_DECREMENT (1ul << 1) +#define VOLFLAG_EXPONENTIAL (1ul << 2) +#define VOLFLAG_SLIDE_ENABLE (1ul << 3) void V_VolumeSlide::Update() { - if( !(Mode & VOLFLAG_SLIDE_ENABLE) ) return; + if (!(Mode & VOLFLAG_SLIDE_ENABLE)) + return; - // Volume slides use the same basic logic as ADSR, but simplified (single-stage - // instead of multi-stage) + // Volume slides use the same basic logic as ADSR, but simplified (single-stage + // instead of multi-stage) - if( Increment == 0x7f ) return; + if (Increment == 0x7f) + return; - s32 value = abs(Value); + s32 value = abs(Value); - if (Mode & VOLFLAG_DECREMENT) - { - // Decrement + if (Mode & VOLFLAG_DECREMENT) { + // Decrement - if(Mode & VOLFLAG_EXPONENTIAL) - { - u32 off = InvExpOffsets[(value>>28)&7]; - value -= PsxRates[(Increment^0x7f)-0x1b+off+32]; - } - else - value -= PsxRates[(Increment^0x7f)-0xf+32]; + if (Mode & VOLFLAG_EXPONENTIAL) { + u32 off = InvExpOffsets[(value >> 28) & 7]; + value -= PsxRates[(Increment ^ 0x7f) - 0x1b + off + 32]; + } else + value -= PsxRates[(Increment ^ 0x7f) - 0xf + 32]; - if (value < 0) - { - value = 0; - Mode = 0; // disable slide - } - } - else - { - // Increment - // Pseudo-exponential increments, as done by the SPU2 (really!) - // Above 75% slides slow, below 75% slides fast. It's exponential, pseudo'ly speaking. + if (value < 0) { + value = 0; + Mode = 0; // disable slide + } + } else { + // Increment + // Pseudo-exponential increments, as done by the SPU2 (really!) + // Above 75% slides slow, below 75% slides fast. It's exponential, pseudo'ly speaking. - if( (Mode & VOLFLAG_EXPONENTIAL) && (value>=0x60000000)) - value += PsxRates[(Increment^0x7f)-0x18+32]; - else - // linear / Pseudo below 75% (they're the same) - value += PsxRates[(Increment^0x7f)-0x10+32]; + if ((Mode & VOLFLAG_EXPONENTIAL) && (value >= 0x60000000)) + value += PsxRates[(Increment ^ 0x7f) - 0x18 + 32]; + else + // linear / Pseudo below 75% (they're the same) + value += PsxRates[(Increment ^ 0x7f) - 0x10 + 32]; - if( value < 0 ) // wrapped around the "top"? - { - value = 0x7fffffff; - Mode = 0; // disable slide - } - } - - Value = (Value < 0) ? -value : value; + if (value < 0) // wrapped around the "top"? + { + value = 0x7fffffff; + Mode = 0; // disable slide + } + } + + Value = (Value < 0) ? -value : value; } diff --git a/plugins/spu2-x/src/Config.h b/plugins/spu2-x/src/Config.h index f8ff31fe5f..a8e714e669 100644 --- a/plugins/spu2-x/src/Config.h +++ b/plugins/spu2-x/src/Config.h @@ -36,23 +36,23 @@ extern bool _MemDump; extern bool _RegDump; extern bool _visual_debug_enabled; -static __forceinline bool MsgToConsole() { return _MsgToConsole & DebugEnabled; } +static __forceinline bool MsgToConsole() { return _MsgToConsole & DebugEnabled; } -static __forceinline bool MsgKeyOnOff() { return _MsgKeyOnOff & MsgToConsole(); } -static __forceinline bool MsgVoiceOff() { return _MsgVoiceOff & MsgToConsole(); } -static __forceinline bool MsgDMA() { return _MsgDMA & MsgToConsole(); } -static __forceinline bool MsgAutoDMA() { return _MsgAutoDMA & MsgToConsole(); } -static __forceinline bool MsgOverruns() { return _MsgOverruns & MsgToConsole(); } -static __forceinline bool MsgCache() { return _MsgCache & MsgToConsole(); } +static __forceinline bool MsgKeyOnOff() { return _MsgKeyOnOff & MsgToConsole(); } +static __forceinline bool MsgVoiceOff() { return _MsgVoiceOff & MsgToConsole(); } +static __forceinline bool MsgDMA() { return _MsgDMA & MsgToConsole(); } +static __forceinline bool MsgAutoDMA() { return _MsgAutoDMA & MsgToConsole(); } +static __forceinline bool MsgOverruns() { return _MsgOverruns & MsgToConsole(); } +static __forceinline bool MsgCache() { return _MsgCache & MsgToConsole(); } -static __forceinline bool AccessLog() { return _AccessLog & DebugEnabled; } -static __forceinline bool DMALog() { return _DMALog & DebugEnabled; } -static __forceinline bool WaveLog() { return _WaveLog & DebugEnabled; } +static __forceinline bool AccessLog() { return _AccessLog & DebugEnabled; } +static __forceinline bool DMALog() { return _DMALog & DebugEnabled; } +static __forceinline bool WaveLog() { return _WaveLog & DebugEnabled; } -static __forceinline bool CoresDump() { return _CoresDump & DebugEnabled; } -static __forceinline bool MemDump() { return _MemDump & DebugEnabled; } -static __forceinline bool RegDump() { return _RegDump & DebugEnabled; } -static __forceinline bool VisualDebug() { return _visual_debug_enabled & DebugEnabled; } +static __forceinline bool CoresDump() { return _CoresDump & DebugEnabled; } +static __forceinline bool MemDump() { return _MemDump & DebugEnabled; } +static __forceinline bool RegDump() { return _RegDump & DebugEnabled; } +static __forceinline bool VisualDebug() { return _visual_debug_enabled & DebugEnabled; } extern wxString AccessLogFileName; extern wxString DMA4LogFileName; @@ -64,7 +64,7 @@ extern wxString RegDumpFileName; extern int Interpolation; extern int numSpeakers; extern bool EffectsDisabled; -extern float FinalVolume; // Global / pre-scale +extern float FinalVolume; // Global / pre-scale extern bool AdvancedVolumeControl; extern float VolumeAdjustFLdb; extern float VolumeAdjustCdb; @@ -85,14 +85,14 @@ extern int SynchMode; #ifndef __POSIX__ extern wchar_t dspPlugin[]; -extern int dspPluginModule; +extern int dspPluginModule; -extern bool dspPluginEnabled; +extern bool dspPluginEnabled; #endif namespace SoundtouchCfg { - extern void ApplySettings( soundtouch::SoundTouch& sndtouch ); +extern void ApplySettings(soundtouch::SoundTouch &sndtouch); } ////// diff --git a/plugins/spu2-x/src/DPLII.h b/plugins/spu2-x/src/DPLII.h index 22adf28f21..54bb005c68 100644 --- a/plugins/spu2-x/src/DPLII.h +++ b/plugins/spu2-x/src/DPLII.h @@ -24,28 +24,28 @@ class DPLII { public: - static const bool UseAveraging = false; + static const bool UseAveraging = false; protected: - s32 LAccum; - s32 RAccum; - s32 ANum; + s32 LAccum; + s32 RAccum; + s32 ANum; - LPF_data lpf_l; - LPF_data lpf_r; + LPF_data lpf_l; + LPF_data lpf_r; - u8 bufdone; - s32 Gfl,Gfr; + u8 bufdone; + s32 Gfl, Gfr; - s32 spdif_data[6]; - s32 LMax,RMax; + s32 spdif_data[6]; + s32 LMax, RMax; - s32 LBuff[128]; - s32 RBuff[128]; + s32 LBuff[128]; + s32 RBuff[128]; public: - DPLII( s32 lowpass_freq, s32 samplerate ); - void Convert( s16 *obuffer, s32 ValL, s32 ValR ); + DPLII(s32 lowpass_freq, s32 samplerate); + void Convert(s16 *obuffer, s32 ValL, s32 ValR); }; #endif diff --git a/plugins/spu2-x/src/Debug.cpp b/plugins/spu2-x/src/Debug.cpp index edd78a64c4..db3127f586 100644 --- a/plugins/spu2-x/src/Debug.cpp +++ b/plugins/spu2-x/src/Debug.cpp @@ -17,25 +17,28 @@ #include "Global.h" -int crazy_debug=0; +int crazy_debug = 0; char s[4096]; FILE *spu2Log = NULL; -void FileLog(const char *fmt, ...) { +void FileLog(const char *fmt, ...) +{ #ifdef SPU2_LOG - va_list list; + va_list list; - if(!AccessLog()) return; - if(!spu2Log) return; + if (!AccessLog()) + return; + if (!spu2Log) + return; - va_start(list, fmt); - vsprintf(s,fmt, list); - va_end(list); + va_start(list, fmt); + vsprintf(s, fmt, list); + va_end(list); - fputs(s,spu2Log); - fflush(spu2Log); + fputs(s, spu2Log); + fflush(spu2Log); #if 0 if(crazy_debug) @@ -51,212 +54,205 @@ void FileLog(const char *fmt, ...) { // while ConLog doesn't print anything if messages to console are disabled at the GUI, // it's still better to outright not call it on tight loop scenarios, by testing MsgToConsole() (which is inline and very quick). // Else, there's some (small) overhead in calling and returning from ConLog. -void ConLog(const char *fmt, ...) { - if(!MsgToConsole()) return; +void ConLog(const char *fmt, ...) +{ + if (!MsgToConsole()) + return; - va_list list; - va_start(list, fmt); - vsprintf(s,fmt, list); - va_end(list); + va_list list; + va_start(list, fmt); + vsprintf(s, fmt, list); + va_end(list); - fputs(s,stderr); - fflush(stderr); + fputs(s, stderr); + fflush(stderr); - if(spu2Log) - { - fputs(s,spu2Log); - fflush(spu2Log); - } + if (spu2Log) { + fputs(s, spu2Log); + fflush(spu2Log); + } } -void V_VolumeSlide::DebugDump( FILE* dump, const char* title, const char* nameLR ) +void V_VolumeSlide::DebugDump(FILE *dump, const char *title, const char *nameLR) { - fprintf( dump, "%s Volume for %s Channel:\t%x\n" - " - Value: %x\n" - " - Mode: %x\n" - " - Increment: %x\n", - title, nameLR, Reg_VOL, Value, Mode, Increment); + fprintf(dump, "%s Volume for %s Channel:\t%x\n" + " - Value: %x\n" + " - Mode: %x\n" + " - Increment: %x\n", + title, nameLR, Reg_VOL, Value, Mode, Increment); } -void V_VolumeSlideLR::DebugDump( FILE* dump, const char* title ) +void V_VolumeSlideLR::DebugDump(FILE *dump, const char *title) { - Left.DebugDump( dump, title, "Left" ); - Right.DebugDump( dump, title, "Right" ); + Left.DebugDump(dump, title, "Left"); + Right.DebugDump(dump, title, "Right"); } -void V_VolumeLR::DebugDump( FILE* dump, const char* title ) +void V_VolumeLR::DebugDump(FILE *dump, const char *title) { - fprintf( dump, "Volume for %s (%s Channel):\t%x\n", title, "Left", Left ); - fprintf( dump, "Volume for %s (%s Channel):\t%x\n", title, "Right", Right ); + fprintf(dump, "Volume for %s (%s Channel):\t%x\n", title, "Left", Left); + fprintf(dump, "Volume for %s (%s Channel):\t%x\n", title, "Right", Right); } void DoFullDump() { #ifdef _MSC_VER #ifdef SPU2_LOG - FILE *dump; - u8 c=0, v=0; + FILE *dump; + u8 c = 0, v = 0; - if(MemDump()) - { - dump = fopen( wxString(MemDumpFileName).ToUTF8(), "wb" ); - if (dump) - { - fwrite(_spu2mem,0x200000,1,dump); - fclose(dump); - } - } - if(RegDump()) - { - dump = fopen( wxString(RegDumpFileName).ToUTF8(), "wb" ); - if (dump) - { - fwrite(spu2regs,0x2000,1,dump); - fclose(dump); - } - } + if (MemDump()) { + dump = fopen(wxString(MemDumpFileName).ToUTF8(), "wb"); + if (dump) { + fwrite(_spu2mem, 0x200000, 1, dump); + fclose(dump); + } + } + if (RegDump()) { + dump = fopen(wxString(RegDumpFileName).ToUTF8(), "wb"); + if (dump) { + fwrite(spu2regs, 0x2000, 1, dump); + fclose(dump); + } + } - if(!CoresDump()) return; - dump = fopen( wxString(CoresDumpFileName).ToUTF8(), "wt" ); - if (dump) - { - for(c=0;c<2;c++) - { - fprintf(dump,"#### CORE %d DUMP.\n",c); + if (!CoresDump()) + return; + dump = fopen(wxString(CoresDumpFileName).ToUTF8(), "wt"); + if (dump) { + for (c = 0; c < 2; c++) { + fprintf(dump, "#### CORE %d DUMP.\n", c); - Cores[c].MasterVol.DebugDump( dump, "Master" ); + Cores[c].MasterVol.DebugDump(dump, "Master"); - Cores[c].ExtVol.DebugDump( dump, "External Data Input" ); - Cores[c].InpVol.DebugDump( dump, "Voice Data Input [dry]" ); - Cores[c].FxVol.DebugDump( dump, "Effects/Reverb [wet]" ); + Cores[c].ExtVol.DebugDump(dump, "External Data Input"); + Cores[c].InpVol.DebugDump(dump, "Voice Data Input [dry]"); + Cores[c].FxVol.DebugDump(dump, "Effects/Reverb [wet]"); - fprintf(dump,"Interrupt Address: %x\n",Cores[c].IRQA); - fprintf(dump,"DMA Transfer Start Address: %x\n",Cores[c].TSA); - fprintf(dump,"External Input to Direct Output (Left): %s\n",Cores[c].DryGate.ExtL?"Yes":"No"); - fprintf(dump,"External Input to Direct Output (Right): %s\n",Cores[c].DryGate.ExtR?"Yes":"No"); - fprintf(dump,"External Input to Effects (Left): %s\n",Cores[c].WetGate.ExtL?"Yes":"No"); - fprintf(dump,"External Input to Effects (Right): %s\n",Cores[c].WetGate.ExtR?"Yes":"No"); - fprintf(dump,"Sound Data Input to Direct Output (Left): %s\n",Cores[c].DryGate.SndL?"Yes":"No"); - fprintf(dump,"Sound Data Input to Direct Output (Right): %s\n",Cores[c].DryGate.SndR?"Yes":"No"); - fprintf(dump,"Sound Data Input to Effects (Left): %s\n",Cores[c].WetGate.SndL?"Yes":"No"); - fprintf(dump,"Sound Data Input to Effects (Right): %s\n",Cores[c].WetGate.SndR?"Yes":"No"); - fprintf(dump,"Voice Data Input to Direct Output (Left): %s\n",Cores[c].DryGate.InpL?"Yes":"No"); - fprintf(dump,"Voice Data Input to Direct Output (Right): %s\n",Cores[c].DryGate.InpR?"Yes":"No"); - fprintf(dump,"Voice Data Input to Effects (Left): %s\n",Cores[c].WetGate.InpL?"Yes":"No"); - fprintf(dump,"Voice Data Input to Effects (Right): %s\n",Cores[c].WetGate.InpR?"Yes":"No"); - fprintf(dump,"IRQ Enabled: %s\n",Cores[c].IRQEnable?"Yes":"No"); - fprintf(dump,"Effects Enabled: %s\n",Cores[c].FxEnable?"Yes":"No"); - fprintf(dump,"Mute Enabled: %s\n",Cores[c].Mute?"Yes":"No"); - fprintf(dump,"Noise Clock: %d\n",Cores[c].NoiseClk); - fprintf(dump,"DMA Bits: %d\n",Cores[c].DMABits); - fprintf(dump,"Effects Start: %x\n",Cores[c].EffectsStartA); - fprintf(dump,"Effects End: %x\n",Cores[c].EffectsEndA); - fprintf(dump,"Registers:\n"); - fprintf(dump," - PMON: %x\n",Cores[c].Regs.PMON); - fprintf(dump," - NON: %x\n",Cores[c].Regs.NON); - fprintf(dump," - VMIXL: %x\n",Cores[c].Regs.VMIXL); - fprintf(dump," - VMIXR: %x\n",Cores[c].Regs.VMIXR); - fprintf(dump," - VMIXEL: %x\n",Cores[c].Regs.VMIXEL); - fprintf(dump," - VMIXER: %x\n",Cores[c].Regs.VMIXER); - fprintf(dump," - MMIX: %x\n",Cores[c].Regs.VMIXEL); - fprintf(dump," - ENDX: %x\n",Cores[c].Regs.VMIXER); - fprintf(dump," - STATX: %x\n",Cores[c].Regs.VMIXEL); - fprintf(dump," - ATTR: %x\n",Cores[c].Regs.VMIXER); - for(v=0;v<24;v++) - { - fprintf(dump,"Voice %d:\n",v); - Cores[c].Voices[v].Volume.DebugDump( dump, "" ); + fprintf(dump, "Interrupt Address: %x\n", Cores[c].IRQA); + fprintf(dump, "DMA Transfer Start Address: %x\n", Cores[c].TSA); + fprintf(dump, "External Input to Direct Output (Left): %s\n", Cores[c].DryGate.ExtL ? "Yes" : "No"); + fprintf(dump, "External Input to Direct Output (Right): %s\n", Cores[c].DryGate.ExtR ? "Yes" : "No"); + fprintf(dump, "External Input to Effects (Left): %s\n", Cores[c].WetGate.ExtL ? "Yes" : "No"); + fprintf(dump, "External Input to Effects (Right): %s\n", Cores[c].WetGate.ExtR ? "Yes" : "No"); + fprintf(dump, "Sound Data Input to Direct Output (Left): %s\n", Cores[c].DryGate.SndL ? "Yes" : "No"); + fprintf(dump, "Sound Data Input to Direct Output (Right): %s\n", Cores[c].DryGate.SndR ? "Yes" : "No"); + fprintf(dump, "Sound Data Input to Effects (Left): %s\n", Cores[c].WetGate.SndL ? "Yes" : "No"); + fprintf(dump, "Sound Data Input to Effects (Right): %s\n", Cores[c].WetGate.SndR ? "Yes" : "No"); + fprintf(dump, "Voice Data Input to Direct Output (Left): %s\n", Cores[c].DryGate.InpL ? "Yes" : "No"); + fprintf(dump, "Voice Data Input to Direct Output (Right): %s\n", Cores[c].DryGate.InpR ? "Yes" : "No"); + fprintf(dump, "Voice Data Input to Effects (Left): %s\n", Cores[c].WetGate.InpL ? "Yes" : "No"); + fprintf(dump, "Voice Data Input to Effects (Right): %s\n", Cores[c].WetGate.InpR ? "Yes" : "No"); + fprintf(dump, "IRQ Enabled: %s\n", Cores[c].IRQEnable ? "Yes" : "No"); + fprintf(dump, "Effects Enabled: %s\n", Cores[c].FxEnable ? "Yes" : "No"); + fprintf(dump, "Mute Enabled: %s\n", Cores[c].Mute ? "Yes" : "No"); + fprintf(dump, "Noise Clock: %d\n", Cores[c].NoiseClk); + fprintf(dump, "DMA Bits: %d\n", Cores[c].DMABits); + fprintf(dump, "Effects Start: %x\n", Cores[c].EffectsStartA); + fprintf(dump, "Effects End: %x\n", Cores[c].EffectsEndA); + fprintf(dump, "Registers:\n"); + fprintf(dump, " - PMON: %x\n", Cores[c].Regs.PMON); + fprintf(dump, " - NON: %x\n", Cores[c].Regs.NON); + fprintf(dump, " - VMIXL: %x\n", Cores[c].Regs.VMIXL); + fprintf(dump, " - VMIXR: %x\n", Cores[c].Regs.VMIXR); + fprintf(dump, " - VMIXEL: %x\n", Cores[c].Regs.VMIXEL); + fprintf(dump, " - VMIXER: %x\n", Cores[c].Regs.VMIXER); + fprintf(dump, " - MMIX: %x\n", Cores[c].Regs.VMIXEL); + fprintf(dump, " - ENDX: %x\n", Cores[c].Regs.VMIXER); + fprintf(dump, " - STATX: %x\n", Cores[c].Regs.VMIXEL); + fprintf(dump, " - ATTR: %x\n", Cores[c].Regs.VMIXER); + for (v = 0; v < 24; v++) { + fprintf(dump, "Voice %d:\n", v); + Cores[c].Voices[v].Volume.DebugDump(dump, ""); - fprintf(dump," - ADSR Envelope: %x & %x\n" - " - Ar: %x\n" - " - Am: %x\n" - " - Dr: %x\n" - " - Sl: %x\n" - " - Sr: %x\n" - " - Sm: %x\n" - " - Rr: %x\n" - " - Rm: %x\n" - " - Phase: %x\n" - " - Value: %x\n", - Cores[c].Voices[v].ADSR.regADSR1, - Cores[c].Voices[v].ADSR.regADSR2, - Cores[c].Voices[v].ADSR.AttackRate, - Cores[c].Voices[v].ADSR.AttackMode, - Cores[c].Voices[v].ADSR.DecayRate, - Cores[c].Voices[v].ADSR.SustainLevel, - Cores[c].Voices[v].ADSR.SustainRate, - Cores[c].Voices[v].ADSR.SustainMode, - Cores[c].Voices[v].ADSR.ReleaseRate, - Cores[c].Voices[v].ADSR.ReleaseMode, - Cores[c].Voices[v].ADSR.Phase, - Cores[c].Voices[v].ADSR.Value); + fprintf(dump, " - ADSR Envelope: %x & %x\n" + " - Ar: %x\n" + " - Am: %x\n" + " - Dr: %x\n" + " - Sl: %x\n" + " - Sr: %x\n" + " - Sm: %x\n" + " - Rr: %x\n" + " - Rm: %x\n" + " - Phase: %x\n" + " - Value: %x\n", + Cores[c].Voices[v].ADSR.regADSR1, + Cores[c].Voices[v].ADSR.regADSR2, + Cores[c].Voices[v].ADSR.AttackRate, + Cores[c].Voices[v].ADSR.AttackMode, + Cores[c].Voices[v].ADSR.DecayRate, + Cores[c].Voices[v].ADSR.SustainLevel, + Cores[c].Voices[v].ADSR.SustainRate, + Cores[c].Voices[v].ADSR.SustainMode, + Cores[c].Voices[v].ADSR.ReleaseRate, + Cores[c].Voices[v].ADSR.ReleaseMode, + Cores[c].Voices[v].ADSR.Phase, + Cores[c].Voices[v].ADSR.Value); - fprintf(dump," - Pitch: %x\n",Cores[c].Voices[v].Pitch); - fprintf(dump," - Modulated: %s\n",Cores[c].Voices[v].Modulated?"Yes":"No"); - fprintf(dump," - Source: %s\n",Cores[c].Voices[v].Noise?"Noise":"Wave"); - fprintf(dump," - Direct Output for Left Channel: %s\n",Cores[c].VoiceGates[v].DryL?"Yes":"No"); - fprintf(dump," - Direct Output for Right Channel: %s\n",Cores[c].VoiceGates[v].DryR?"Yes":"No"); - fprintf(dump," - Effects Output for Left Channel: %s\n",Cores[c].VoiceGates[v].WetL?"Yes":"No"); - fprintf(dump," - Effects Output for Right Channel: %s\n",Cores[c].VoiceGates[v].WetR?"Yes":"No"); - fprintf(dump," - Loop Start Address: %x\n",Cores[c].Voices[v].LoopStartA); - fprintf(dump," - Sound Start Address: %x\n",Cores[c].Voices[v].StartA); - fprintf(dump," - Next Data Address: %x\n",Cores[c].Voices[v].NextA); - fprintf(dump," - Play Start Cycle: %d\n",Cores[c].Voices[v].PlayCycle); - fprintf(dump," - Play Status: %s\n",(Cores[c].Voices[v].ADSR.Phase>0)?"Playing":"Not Playing"); - fprintf(dump," - Block Sample: %d\n",Cores[c].Voices[v].SCurrent); - } - fprintf(dump,"#### END OF DUMP.\n\n"); - } - fclose(dump); - } - - dump = fopen( "logs/effects.txt", "wt" ); - if (dump) - { - for(c=0;c<2;c++) - { - fprintf(dump,"#### CORE %d EFFECTS PROCESSOR DUMP.\n",c); + fprintf(dump, " - Pitch: %x\n", Cores[c].Voices[v].Pitch); + fprintf(dump, " - Modulated: %s\n", Cores[c].Voices[v].Modulated ? "Yes" : "No"); + fprintf(dump, " - Source: %s\n", Cores[c].Voices[v].Noise ? "Noise" : "Wave"); + fprintf(dump, " - Direct Output for Left Channel: %s\n", Cores[c].VoiceGates[v].DryL ? "Yes" : "No"); + fprintf(dump, " - Direct Output for Right Channel: %s\n", Cores[c].VoiceGates[v].DryR ? "Yes" : "No"); + fprintf(dump, " - Effects Output for Left Channel: %s\n", Cores[c].VoiceGates[v].WetL ? "Yes" : "No"); + fprintf(dump, " - Effects Output for Right Channel: %s\n", Cores[c].VoiceGates[v].WetR ? "Yes" : "No"); + fprintf(dump, " - Loop Start Address: %x\n", Cores[c].Voices[v].LoopStartA); + fprintf(dump, " - Sound Start Address: %x\n", Cores[c].Voices[v].StartA); + fprintf(dump, " - Next Data Address: %x\n", Cores[c].Voices[v].NextA); + fprintf(dump, " - Play Start Cycle: %d\n", Cores[c].Voices[v].PlayCycle); + fprintf(dump, " - Play Status: %s\n", (Cores[c].Voices[v].ADSR.Phase > 0) ? "Playing" : "Not Playing"); + fprintf(dump, " - Block Sample: %d\n", Cores[c].Voices[v].SCurrent); + } + fprintf(dump, "#### END OF DUMP.\n\n"); + } + fclose(dump); + } - fprintf(dump," - IN_COEF_L: %x\n",Cores[c].Revb.IN_COEF_R); - fprintf(dump," - IN_COEF_R: %x\n",Cores[c].Revb.IN_COEF_L); + dump = fopen("logs/effects.txt", "wt"); + if (dump) { + for (c = 0; c < 2; c++) { + fprintf(dump, "#### CORE %d EFFECTS PROCESSOR DUMP.\n", c); - fprintf(dump," - FB_ALPHA: %x\n",Cores[c].Revb.FB_ALPHA); - fprintf(dump," - FB_X: %x\n",Cores[c].Revb.FB_X); - fprintf(dump," - FB_SRC_A: %x\n",Cores[c].Revb.FB_SRC_A); - fprintf(dump," - FB_SRC_B: %x\n",Cores[c].Revb.FB_SRC_B); + fprintf(dump, " - IN_COEF_L: %x\n", Cores[c].Revb.IN_COEF_R); + fprintf(dump, " - IN_COEF_R: %x\n", Cores[c].Revb.IN_COEF_L); - fprintf(dump," - IIR_ALPHA: %x\n",Cores[c].Revb.IIR_ALPHA); - fprintf(dump," - IIR_COEF: %x\n",Cores[c].Revb.IIR_COEF); - fprintf(dump," - IIR_SRC_A0: %x\n",Cores[c].Revb.IIR_SRC_A0); - fprintf(dump," - IIR_SRC_A1: %x\n",Cores[c].Revb.IIR_SRC_A1); - fprintf(dump," - IIR_SRC_B1: %x\n",Cores[c].Revb.IIR_SRC_B0); - fprintf(dump," - IIR_SRC_B0: %x\n",Cores[c].Revb.IIR_SRC_B1); - fprintf(dump," - IIR_DEST_A0: %x\n",Cores[c].Revb.IIR_DEST_A0); - fprintf(dump," - IIR_DEST_A1: %x\n",Cores[c].Revb.IIR_DEST_A1); - fprintf(dump," - IIR_DEST_B0: %x\n",Cores[c].Revb.IIR_DEST_B0); - fprintf(dump," - IIR_DEST_B1: %x\n",Cores[c].Revb.IIR_DEST_B1); + fprintf(dump, " - FB_ALPHA: %x\n", Cores[c].Revb.FB_ALPHA); + fprintf(dump, " - FB_X: %x\n", Cores[c].Revb.FB_X); + fprintf(dump, " - FB_SRC_A: %x\n", Cores[c].Revb.FB_SRC_A); + fprintf(dump, " - FB_SRC_B: %x\n", Cores[c].Revb.FB_SRC_B); - fprintf(dump," - ACC_COEF_A: %x\n",Cores[c].Revb.ACC_COEF_A); - fprintf(dump," - ACC_COEF_B: %x\n",Cores[c].Revb.ACC_COEF_B); - fprintf(dump," - ACC_COEF_C: %x\n",Cores[c].Revb.ACC_COEF_C); - fprintf(dump," - ACC_COEF_D: %x\n",Cores[c].Revb.ACC_COEF_D); - fprintf(dump," - ACC_SRC_A0: %x\n",Cores[c].Revb.ACC_SRC_A0); - fprintf(dump," - ACC_SRC_A1: %x\n",Cores[c].Revb.ACC_SRC_A1); - fprintf(dump," - ACC_SRC_B0: %x\n",Cores[c].Revb.ACC_SRC_B0); - fprintf(dump," - ACC_SRC_B1: %x\n",Cores[c].Revb.ACC_SRC_B1); - fprintf(dump," - ACC_SRC_C0: %x\n",Cores[c].Revb.ACC_SRC_C0); - fprintf(dump," - ACC_SRC_C1: %x\n",Cores[c].Revb.ACC_SRC_C1); - fprintf(dump," - ACC_SRC_D0: %x\n",Cores[c].Revb.ACC_SRC_D0); - fprintf(dump," - ACC_SRC_D1: %x\n",Cores[c].Revb.ACC_SRC_D1); + fprintf(dump, " - IIR_ALPHA: %x\n", Cores[c].Revb.IIR_ALPHA); + fprintf(dump, " - IIR_COEF: %x\n", Cores[c].Revb.IIR_COEF); + fprintf(dump, " - IIR_SRC_A0: %x\n", Cores[c].Revb.IIR_SRC_A0); + fprintf(dump, " - IIR_SRC_A1: %x\n", Cores[c].Revb.IIR_SRC_A1); + fprintf(dump, " - IIR_SRC_B1: %x\n", Cores[c].Revb.IIR_SRC_B0); + fprintf(dump, " - IIR_SRC_B0: %x\n", Cores[c].Revb.IIR_SRC_B1); + fprintf(dump, " - IIR_DEST_A0: %x\n", Cores[c].Revb.IIR_DEST_A0); + fprintf(dump, " - IIR_DEST_A1: %x\n", Cores[c].Revb.IIR_DEST_A1); + fprintf(dump, " - IIR_DEST_B0: %x\n", Cores[c].Revb.IIR_DEST_B0); + fprintf(dump, " - IIR_DEST_B1: %x\n", Cores[c].Revb.IIR_DEST_B1); - fprintf(dump," - MIX_DEST_A0: %x\n",Cores[c].Revb.MIX_DEST_A0); - fprintf(dump," - MIX_DEST_A1: %x\n",Cores[c].Revb.MIX_DEST_A1); - fprintf(dump," - MIX_DEST_B0: %x\n",Cores[c].Revb.MIX_DEST_B0); - fprintf(dump," - MIX_DEST_B1: %x\n",Cores[c].Revb.MIX_DEST_B1); - fprintf(dump,"#### END OF DUMP.\n\n"); - } - fclose(dump); - } + fprintf(dump, " - ACC_COEF_A: %x\n", Cores[c].Revb.ACC_COEF_A); + fprintf(dump, " - ACC_COEF_B: %x\n", Cores[c].Revb.ACC_COEF_B); + fprintf(dump, " - ACC_COEF_C: %x\n", Cores[c].Revb.ACC_COEF_C); + fprintf(dump, " - ACC_COEF_D: %x\n", Cores[c].Revb.ACC_COEF_D); + fprintf(dump, " - ACC_SRC_A0: %x\n", Cores[c].Revb.ACC_SRC_A0); + fprintf(dump, " - ACC_SRC_A1: %x\n", Cores[c].Revb.ACC_SRC_A1); + fprintf(dump, " - ACC_SRC_B0: %x\n", Cores[c].Revb.ACC_SRC_B0); + fprintf(dump, " - ACC_SRC_B1: %x\n", Cores[c].Revb.ACC_SRC_B1); + fprintf(dump, " - ACC_SRC_C0: %x\n", Cores[c].Revb.ACC_SRC_C0); + fprintf(dump, " - ACC_SRC_C1: %x\n", Cores[c].Revb.ACC_SRC_C1); + fprintf(dump, " - ACC_SRC_D0: %x\n", Cores[c].Revb.ACC_SRC_D0); + fprintf(dump, " - ACC_SRC_D1: %x\n", Cores[c].Revb.ACC_SRC_D1); + + fprintf(dump, " - MIX_DEST_A0: %x\n", Cores[c].Revb.MIX_DEST_A0); + fprintf(dump, " - MIX_DEST_A1: %x\n", Cores[c].Revb.MIX_DEST_A1); + fprintf(dump, " - MIX_DEST_B0: %x\n", Cores[c].Revb.MIX_DEST_B0); + fprintf(dump, " - MIX_DEST_B1: %x\n", Cores[c].Revb.MIX_DEST_B1); + fprintf(dump, "#### END OF DUMP.\n\n"); + } + fclose(dump); + } #endif #endif } diff --git a/plugins/spu2-x/src/Debug.h b/plugins/spu2-x/src/Debug.h index 2d1b283b66..26eee13b3b 100644 --- a/plugins/spu2-x/src/Debug.h +++ b/plugins/spu2-x/src/Debug.h @@ -26,40 +26,39 @@ extern void ConLog(const char *fmt, ...); extern void DoFullDump(); -extern FILE* OpenBinaryLog( const wxString& logfile ); -extern FILE* OpenLog( const wxString& logfile ); -extern FILE* OpenDump( const wxString& logfile ); +extern FILE *OpenBinaryLog(const wxString &logfile); +extern FILE *OpenLog(const wxString &logfile); +extern FILE *OpenDump(const wxString &logfile); namespace WaveDump { - enum CoreSourceType - { - // Core's input stream, usually pulled from ADMA streams. - CoreSrc_Input = 0 +enum CoreSourceType { + // Core's input stream, usually pulled from ADMA streams. + CoreSrc_Input = 0, - // Output of the actual 24 input voices which have dry output enabled. - , CoreSrc_DryVoiceMix + // Output of the actual 24 input voices which have dry output enabled. + CoreSrc_DryVoiceMix, - // Output of the actual 24 input voices that have wet output enabled. - , CoreSrc_WetVoiceMix + // Output of the actual 24 input voices that have wet output enabled. + CoreSrc_WetVoiceMix, - // Wet mix including inputs and externals, prior to the application of reverb. - , CoreSrc_PreReverb + // Wet mix including inputs and externals, prior to the application of reverb. + CoreSrc_PreReverb, - // Wet mix after reverb has turned it into a pile of garbly gook. - , CoreSrc_PostReverb + // Wet mix after reverb has turned it into a pile of garbly gook. + CoreSrc_PostReverb, - // Final output of the core. For core 0, it's the feed into Core1. - // For Core1, it's the feed into SndOut. - , CoreSrc_External + // Final output of the core. For core 0, it's the feed into Core1. + // For Core1, it's the feed into SndOut. + CoreSrc_External, - , CoreSrc_Count - }; + CoreSrc_Count +}; - extern void Open(); - extern void Close(); - extern void WriteCore( uint coreidx, CoreSourceType src, s16 left, s16 right ); - extern void WriteCore( uint coreidx, CoreSourceType src, const StereoOut16& sample ); +extern void Open(); +extern void Close(); +extern void WriteCore(uint coreidx, CoreSourceType src, s16 left, s16 right); +extern void WriteCore(uint coreidx, CoreSourceType src, const StereoOut16 &sample); } using WaveDump::CoreSrc_Input; @@ -69,4 +68,4 @@ using WaveDump::CoreSrc_PreReverb; using WaveDump::CoreSrc_PostReverb; using WaveDump::CoreSrc_External; -#endif // DEBUG_H_INCLUDED // +#endif // DEBUG_H_INCLUDED // diff --git a/plugins/spu2-x/src/DecodeDPLII.cpp b/plugins/spu2-x/src/DecodeDPLII.cpp index 57e89ba3b5..01f3f3ca00 100644 --- a/plugins/spu2-x/src/DecodeDPLII.cpp +++ b/plugins/spu2-x/src/DecodeDPLII.cpp @@ -23,131 +23,132 @@ #include static const u8 sLogTable[256] = { - 0x00,0x3C,0x60,0x78,0x8C,0x9C,0xA8,0xB4,0xBE,0xC8,0xD0,0xD8,0xDE,0xE4,0xEA,0xF0, - 0xF6,0xFA,0xFE,0x04,0x08,0x0C,0x10,0x14,0x16,0x1A,0x1E,0x20,0x24,0x26,0x2A,0x2C, - 0x2E,0x32,0x34,0x36,0x38,0x3A,0x3E,0x40,0x42,0x44,0x46,0x48,0x4A,0x4C,0x4E,0x50, - 0x50,0x52,0x54,0x56,0x58,0x5A,0x5A,0x5C,0x5E,0x60,0x60,0x62,0x64,0x66,0x66,0x68, - 0x6A,0x6A,0x6C,0x6E,0x6E,0x70,0x70,0x72,0x74,0x74,0x76,0x76,0x78,0x7A,0x7A,0x7C, - 0x7C,0x7E,0x7E,0x80,0x80,0x82,0x82,0x84,0x84,0x86,0x86,0x88,0x88,0x8A,0x8A,0x8C, - 0x8C,0x8C,0x8E,0x8E,0x90,0x90,0x92,0x92,0x92,0x94,0x94,0x96,0x96,0x96,0x98,0x98, - 0x9A,0x9A,0x9A,0x9C,0x9C,0x9C,0x9E,0x9E,0xA0,0xA0,0xA0,0xA2,0xA2,0xA2,0xA4,0xA4, - 0xA4,0xA6,0xA6,0xA6,0xA8,0xA8,0xA8,0xAA,0xAA,0xAA,0xAC,0xAC,0xAC,0xAC,0xAE,0xAE, - 0xAE,0xB0,0xB0,0xB0,0xB2,0xB2,0xB2,0xB2,0xB4,0xB4,0xB4,0xB6,0xB6,0xB6,0xB6,0xB8, - 0xB8,0xB8,0xB8,0xBA,0xBA,0xBA,0xBC,0xBC,0xBC,0xBC,0xBE,0xBE,0xBE,0xBE,0xC0,0xC0, - 0xC0,0xC0,0xC2,0xC2,0xC2,0xC2,0xC2,0xC4,0xC4,0xC4,0xC4,0xC6,0xC6,0xC6,0xC6,0xC8, - 0xC8,0xC8,0xC8,0xC8,0xCA,0xCA,0xCA,0xCA,0xCC,0xCC,0xCC,0xCC,0xCC,0xCE,0xCE,0xCE, - 0xCE,0xCE,0xD0,0xD0,0xD0,0xD0,0xD0,0xD2,0xD2,0xD2,0xD2,0xD2,0xD4,0xD4,0xD4,0xD4, - 0xD4,0xD6,0xD6,0xD6,0xD6,0xD6,0xD8,0xD8,0xD8,0xD8,0xD8,0xD8,0xDA,0xDA,0xDA,0xDA, - 0xDA,0xDC,0xDC,0xDC,0xDC,0xDC,0xDC,0xDE,0xDE,0xDE,0xDE,0xDE,0xDE,0xE0,0xE0,0xE0, + 0x00, 0x3C, 0x60, 0x78, 0x8C, 0x9C, 0xA8, 0xB4, 0xBE, 0xC8, 0xD0, 0xD8, 0xDE, 0xE4, 0xEA, 0xF0, + 0xF6, 0xFA, 0xFE, 0x04, 0x08, 0x0C, 0x10, 0x14, 0x16, 0x1A, 0x1E, 0x20, 0x24, 0x26, 0x2A, 0x2C, + 0x2E, 0x32, 0x34, 0x36, 0x38, 0x3A, 0x3E, 0x40, 0x42, 0x44, 0x46, 0x48, 0x4A, 0x4C, 0x4E, 0x50, + 0x50, 0x52, 0x54, 0x56, 0x58, 0x5A, 0x5A, 0x5C, 0x5E, 0x60, 0x60, 0x62, 0x64, 0x66, 0x66, 0x68, + 0x6A, 0x6A, 0x6C, 0x6E, 0x6E, 0x70, 0x70, 0x72, 0x74, 0x74, 0x76, 0x76, 0x78, 0x7A, 0x7A, 0x7C, + 0x7C, 0x7E, 0x7E, 0x80, 0x80, 0x82, 0x82, 0x84, 0x84, 0x86, 0x86, 0x88, 0x88, 0x8A, 0x8A, 0x8C, + 0x8C, 0x8C, 0x8E, 0x8E, 0x90, 0x90, 0x92, 0x92, 0x92, 0x94, 0x94, 0x96, 0x96, 0x96, 0x98, 0x98, + 0x9A, 0x9A, 0x9A, 0x9C, 0x9C, 0x9C, 0x9E, 0x9E, 0xA0, 0xA0, 0xA0, 0xA2, 0xA2, 0xA2, 0xA4, 0xA4, + 0xA4, 0xA6, 0xA6, 0xA6, 0xA8, 0xA8, 0xA8, 0xAA, 0xAA, 0xAA, 0xAC, 0xAC, 0xAC, 0xAC, 0xAE, 0xAE, + 0xAE, 0xB0, 0xB0, 0xB0, 0xB2, 0xB2, 0xB2, 0xB2, 0xB4, 0xB4, 0xB4, 0xB6, 0xB6, 0xB6, 0xB6, 0xB8, + 0xB8, 0xB8, 0xB8, 0xBA, 0xBA, 0xBA, 0xBC, 0xBC, 0xBC, 0xBC, 0xBE, 0xBE, 0xBE, 0xBE, 0xC0, 0xC0, + 0xC0, 0xC0, 0xC2, 0xC2, 0xC2, 0xC2, 0xC2, 0xC4, 0xC4, 0xC4, 0xC4, 0xC6, 0xC6, 0xC6, 0xC6, 0xC8, + 0xC8, 0xC8, 0xC8, 0xC8, 0xCA, 0xCA, 0xCA, 0xCA, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCE, 0xCE, 0xCE, + 0xCE, 0xCE, 0xD0, 0xD0, 0xD0, 0xD0, 0xD0, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD4, 0xD4, 0xD4, 0xD4, + 0xD4, 0xD6, 0xD6, 0xD6, 0xD6, 0xD6, 0xD8, 0xD8, 0xD8, 0xD8, 0xD8, 0xD8, 0xDA, 0xDA, 0xDA, 0xDA, + 0xDA, 0xDC, 0xDC, 0xDC, 0xDC, 0xDC, 0xDC, 0xDE, 0xDE, 0xDE, 0xDE, 0xDE, 0xDE, 0xE0, 0xE0, 0xE0, }; -DPLII::DPLII( s32 lowpass_freq, s32 samplerate ) : - LAccum( 0 ), - RAccum( 0 ), - ANum( 0 ), - lpf_l( lowpass_freq, samplerate ), - lpf_r( lowpass_freq, samplerate ), - bufdone( 1 ), - Gfl( 0 ), - Gfr( 0 ), - LMax( 0 ), - RMax( 0 ) +DPLII::DPLII(s32 lowpass_freq, s32 samplerate) + : LAccum(0) + , RAccum(0) + , ANum(0) + , lpf_l(lowpass_freq, samplerate) + , lpf_r(lowpass_freq, samplerate) + , bufdone(1) + , Gfl(0) + , Gfr(0) + , LMax(0) + , RMax(0) { - memset( LBuff, 0, sizeof( LBuff ) ); - memset( RBuff, 0, sizeof( RBuff ) ); - memset( spdif_data, 0, sizeof( spdif_data ) ); + memset(LBuff, 0, sizeof(LBuff)); + memset(RBuff, 0, sizeof(RBuff)); + memset(spdif_data, 0, sizeof(spdif_data)); } // Takes a single stereo input sample and translates it into six output samples // for 5.1 audio support on non-DPL2 hardware. -void DPLII::Convert( s16 *obuffer, s32 ValL, s32 ValR ) +void DPLII::Convert(s16 *obuffer, s32 ValL, s32 ValR) { - ValL >>= 2; - ValR >>= 2; - if(PlayMode&4) - { - spdif_get_samples(spdif_data); - } - else - { - spdif_data[0]=0; - spdif_data[1]=0; - spdif_data[2]=0; - spdif_data[3]=0; - spdif_data[4]=0; - spdif_data[5]=0; - } + ValL >>= 2; + ValR >>= 2; + if (PlayMode & 4) { + spdif_get_samples(spdif_data); + } else { + spdif_data[0] = 0; + spdif_data[1] = 0; + spdif_data[2] = 0; + spdif_data[3] = 0; + spdif_data[4] = 0; + spdif_data[5] = 0; + } - //const u8 shift = SndOutVolumeShift; + //const u8 shift = SndOutVolumeShift; - s32 XL = abs(ValL>>8); - s32 XR = abs(ValR>>8); + s32 XL = abs(ValL >> 8); + s32 XR = abs(ValR >> 8); - if(XL>LMax) LMax = XL; - if(XR>RMax) RMax = XR; + if (XL > LMax) + LMax = XL; + if (XR > RMax) + RMax = XR; - ANum++; - if(ANum>=128) - { - ANum=0; - LAccum = 1+((LAccum * 224 + LMax * 31)>>8); - RAccum = 1+((RAccum * 224 + RMax * 31)>>8); + ANum++; + if (ANum >= 128) { + ANum = 0; + LAccum = 1 + ((LAccum * 224 + LMax * 31) >> 8); + RAccum = 1 + ((RAccum * 224 + RMax * 31) >> 8); - LMax = 0; - RMax = 0; + LMax = 0; + RMax = 0; - s32 Tfl=(RAccum)*255/(LAccum); - s32 Tfr=(LAccum)*255/(RAccum); + s32 Tfl = (RAccum)*255 / (LAccum); + s32 Tfr = (LAccum)*255 / (RAccum); - int gMax = max(Tfl,Tfr); - Tfl=Tfl*255/gMax; - Tfr=Tfr*255/gMax; + int gMax = max(Tfl, Tfr); + Tfl = Tfl * 255 / gMax; + Tfr = Tfr * 255 / gMax; - if(Tfl>255) Tfl=255; - if(Tfr>255) Tfr=255; - if(Tfl<1) Tfl=1; - if(Tfr<1) Tfr=1; + if (Tfl > 255) + Tfl = 255; + if (Tfr > 255) + Tfr = 255; + if (Tfl < 1) + Tfl = 1; + if (Tfr < 1) + Tfr = 1; - Gfl = (Gfl * 200 + Tfl * 56)>>8; - Gfr = (Gfr * 200 + Tfr * 56)>>8; + Gfl = (Gfl * 200 + Tfl * 56) >> 8; + Gfr = (Gfr * 200 + Tfr * 56) >> 8; + } - } + s32 L, R, C, LFE, SL, SR, LL, LR; - s32 L,R,C,LFE,SL,SR,LL,LR; + extern double pow_2_31; + LL = (s32)(lpf_l.sample((ValL >> 4) / pow_2_31) * pow_2_31); + LR = (s32)(lpf_r.sample((ValR >> 4) / pow_2_31) * pow_2_31); + LFE = (LL + LR) >> 4; - extern double pow_2_31; - LL = (s32)(lpf_l.sample((ValL>>4)/pow_2_31)*pow_2_31); - LR = (s32)(lpf_r.sample((ValR>>4)/pow_2_31)*pow_2_31); - LFE = (LL + LR)>>4; + C = (ValL + ValR) >> 1; //16.8 - C=(ValL+ValR)>>1; //16.8 + ValL -= C; //16.8 + ValR -= C; //16.8 - ValL-=C;//16.8 - ValR-=C;//16.8 + L = ValL >> 8; //16.0 + R = ValR >> 8; //16.0 + C = C >> 8; //16.0 - L=ValL>>8; //16.0 - R=ValR>>8; //16.0 - C=C>>8; //16.0 + const s32 Cfl = 1 + sLogTable[Gfl]; + const s32 Cfr = 1 + sLogTable[Gfr]; - const s32 Cfl = 1 + sLogTable[Gfl]; - const s32 Cfr = 1 + sLogTable[Gfr]; + const s32 VL = (ValL >> 4) * Cfl; //16.12 + const s32 VR = (ValR >> 4) * Cfr; - const s32 VL = (ValL>>4) * Cfl; //16.12 - const s32 VR = (ValR>>4) * Cfr; + const s32 SC = (VL - VR) >> 15; - const s32 SC = (VL-VR)>>15; + SL = (((VR / 148 - VL / 209) >> 4) * Cfr) >> 8; + SR = (((VR / 209 - VL / 148) >> 4) * Cfl) >> 8; - SL = (((VR/148 - VL/209)>>4)*Cfr)>>8; - SR = (((VR/209 - VL/148)>>4)*Cfl)>>8; + int AddCX = (C * Config_DSound51.AddCLR) >> 8; - int AddCX = (C * Config_DSound51.AddCLR)>>8; - - obuffer[0]=spdif_data[0] + (((L * Config_DSound51.GainL ))>>8) + AddCX; - obuffer[1]=spdif_data[1] + (((R * Config_DSound51.GainR ))>>8) + AddCX; - obuffer[2]=spdif_data[2] + (((C * Config_DSound51.GainC ))>>8); // - AddCX; - obuffer[3]=spdif_data[3] + (((LFE * Config_DSound51.GainLFE))>>8); - obuffer[4]=spdif_data[4] + (((SL * Config_DSound51.GainSL ))>>8); - obuffer[5]=spdif_data[5] + (((SR * Config_DSound51.GainSR ))>>8); + obuffer[0] = spdif_data[0] + (((L * Config_DSound51.GainL)) >> 8) + AddCX; + obuffer[1] = spdif_data[1] + (((R * Config_DSound51.GainR)) >> 8) + AddCX; + obuffer[2] = spdif_data[2] + (((C * Config_DSound51.GainC)) >> 8); // - AddCX; + obuffer[3] = spdif_data[3] + (((LFE * Config_DSound51.GainLFE)) >> 8); + obuffer[4] = spdif_data[4] + (((SL * Config_DSound51.GainSL)) >> 8); + obuffer[5] = spdif_data[5] + (((SR * Config_DSound51.GainSR)) >> 8); #if 0 if( UseAveraging ) diff --git a/plugins/spu2-x/src/Dma.cpp b/plugins/spu2-x/src/Dma.cpp index 766816c5f1..7b61095d23 100644 --- a/plugins/spu2-x/src/Dma.cpp +++ b/plugins/spu2-x/src/Dma.cpp @@ -18,158 +18,160 @@ #include "Global.h" #include "Dma.h" -#include "PS2E-spu2.h" // temporary until I resolve cyclePtr/TimeUpdate dependencies. +#include "PS2E-spu2.h" // temporary until I resolve cyclePtr/TimeUpdate dependencies. extern u8 callirq; -static FILE *DMA4LogFile = NULL; -static FILE *DMA7LogFile = NULL; -static FILE *ADMA4LogFile = NULL; -static FILE *ADMA7LogFile = NULL; -static FILE *ADMAOutLogFile = NULL; +static FILE *DMA4LogFile = NULL; +static FILE *DMA7LogFile = NULL; +static FILE *ADMA4LogFile = NULL; +static FILE *ADMA7LogFile = NULL; +static FILE *ADMAOutLogFile = NULL; -static FILE *REGWRTLogFile[2] = {0,0}; +static FILE *REGWRTLogFile[2] = {0, 0}; void DMALogOpen() { - if(!DMALog()) return; - DMA4LogFile = OpenBinaryLog( DMA4LogFileName ); - DMA7LogFile = OpenBinaryLog( DMA7LogFileName ); - ADMA4LogFile = OpenBinaryLog( L"adma4.raw" ); - ADMA7LogFile = OpenBinaryLog( L"adma7.raw" ); - ADMAOutLogFile = OpenBinaryLog( L"admaOut.raw" ); + if (!DMALog()) + return; + DMA4LogFile = OpenBinaryLog(DMA4LogFileName); + DMA7LogFile = OpenBinaryLog(DMA7LogFileName); + ADMA4LogFile = OpenBinaryLog(L"adma4.raw"); + ADMA7LogFile = OpenBinaryLog(L"adma7.raw"); + ADMAOutLogFile = OpenBinaryLog(L"admaOut.raw"); } -void DMA4LogWrite(void *lpData, u32 ulSize) { - if(!DMALog()) return; - if (!DMA4LogFile) return; - fwrite(lpData,ulSize,1,DMA4LogFile); -} - -void DMA7LogWrite(void *lpData, u32 ulSize) { - if(!DMALog()) return; - if (!DMA7LogFile) return; - fwrite(lpData,ulSize,1,DMA7LogFile); -} - -void ADMAOutLogWrite(void *lpData, u32 ulSize) { - if(!DMALog()) return; - if (!ADMAOutLogFile) return; - fwrite(lpData,ulSize,1,ADMAOutLogFile); -} - -void RegWriteLog(u32 core,u16 value) +void DMA4LogWrite(void *lpData, u32 ulSize) { - if(!DMALog()) return; - if (!REGWRTLogFile[core]) return; - fwrite(&value,2,1,REGWRTLogFile[core]); + if (!DMALog()) + return; + if (!DMA4LogFile) + return; + fwrite(lpData, ulSize, 1, DMA4LogFile); +} + +void DMA7LogWrite(void *lpData, u32 ulSize) +{ + if (!DMALog()) + return; + if (!DMA7LogFile) + return; + fwrite(lpData, ulSize, 1, DMA7LogFile); +} + +void ADMAOutLogWrite(void *lpData, u32 ulSize) +{ + if (!DMALog()) + return; + if (!ADMAOutLogFile) + return; + fwrite(lpData, ulSize, 1, ADMAOutLogFile); +} + +void RegWriteLog(u32 core, u16 value) +{ + if (!DMALog()) + return; + if (!REGWRTLogFile[core]) + return; + fwrite(&value, 2, 1, REGWRTLogFile[core]); } void DMALogClose() { - safe_fclose(DMA4LogFile); - safe_fclose(DMA7LogFile); - safe_fclose(REGWRTLogFile[0]); - safe_fclose(REGWRTLogFile[1]); - safe_fclose(ADMA4LogFile); - safe_fclose(ADMA7LogFile); - safe_fclose(ADMAOutLogFile); + safe_fclose(DMA4LogFile); + safe_fclose(DMA7LogFile); + safe_fclose(REGWRTLogFile[0]); + safe_fclose(REGWRTLogFile[1]); + safe_fclose(ADMA4LogFile); + safe_fclose(ADMA7LogFile); + safe_fclose(ADMAOutLogFile); } -void V_Core::LogAutoDMA( FILE* fp ) +void V_Core::LogAutoDMA(FILE *fp) { - if( !DMALog() || !fp || !DMAPtr ) return; - fwrite( DMAPtr+InputDataProgress, 0x400, 1, fp ); + if (!DMALog() || !fp || !DMAPtr) + return; + fwrite(DMAPtr + InputDataProgress, 0x400, 1, fp); } -void V_Core::AutoDMAReadBuffer(int mode) //mode: 0= split stereo; 1 = do not split stereo +void V_Core::AutoDMAReadBuffer(int mode) //mode: 0= split stereo; 1 = do not split stereo { #ifndef ENABLE_NEW_IOPDMA_SPU2 - int spos = ((InputPosRead+0xff)&0x100); //starting position of the free buffer + int spos = ((InputPosRead + 0xff) & 0x100); //starting position of the free buffer - LogAutoDMA( Index ? ADMA7LogFile : ADMA4LogFile ); + LogAutoDMA(Index ? ADMA7LogFile : ADMA4LogFile); - // HACKFIX!! DMAPtr can be invalid after a savestate load, so the savestate just forces it - // to NULL and we ignore it here. (used to work in old VM editions of PCSX2 with fixed - // addressing, but new PCSX2s have dynamic memory addressing). + // HACKFIX!! DMAPtr can be invalid after a savestate load, so the savestate just forces it + // to NULL and we ignore it here. (used to work in old VM editions of PCSX2 with fixed + // addressing, but new PCSX2s have dynamic memory addressing). - if(mode) - { - if( DMAPtr != NULL ) - //memcpy((ADMATempBuffer+(spos<<1)),DMAPtr+InputDataProgress,0x400); - memcpy(GetMemPtr(0x2000+(Index<<10)+spos),DMAPtr+InputDataProgress,0x400); - MADR+=0x400; - InputDataLeft-=0x200; - InputDataProgress+=0x200; - } - else - { - if( DMAPtr != NULL ) - //memcpy((ADMATempBuffer+spos),DMAPtr+InputDataProgress,0x200); - memcpy(GetMemPtr(0x2000+(Index<<10)+spos),DMAPtr+InputDataProgress,0x200); - MADR+=0x200; - InputDataLeft-=0x100; - InputDataProgress+=0x100; + if (mode) { + if (DMAPtr != NULL) + //memcpy((ADMATempBuffer+(spos<<1)),DMAPtr+InputDataProgress,0x400); + memcpy(GetMemPtr(0x2000 + (Index << 10) + spos), DMAPtr + InputDataProgress, 0x400); + MADR += 0x400; + InputDataLeft -= 0x200; + InputDataProgress += 0x200; + } else { + if (DMAPtr != NULL) + //memcpy((ADMATempBuffer+spos),DMAPtr+InputDataProgress,0x200); + memcpy(GetMemPtr(0x2000 + (Index << 10) + spos), DMAPtr + InputDataProgress, 0x200); + MADR += 0x200; + InputDataLeft -= 0x100; + InputDataProgress += 0x100; - if( DMAPtr != NULL ) - //memcpy((ADMATempBuffer+spos+0x200),DMAPtr+InputDataProgress,0x200); - memcpy(GetMemPtr(0x2200+(Index<<10)+spos),DMAPtr+InputDataProgress,0x200); - MADR+=0x200; - InputDataLeft-=0x100; - InputDataProgress+=0x100; - } - // See ReadInput at mixer.cpp for explanation on the commented out lines - // + if (DMAPtr != NULL) + //memcpy((ADMATempBuffer+spos+0x200),DMAPtr+InputDataProgress,0x200); + memcpy(GetMemPtr(0x2200 + (Index << 10) + spos), DMAPtr + InputDataProgress, 0x200); + MADR += 0x200; + InputDataLeft -= 0x100; + InputDataProgress += 0x100; + } +// See ReadInput at mixer.cpp for explanation on the commented out lines +// #endif } void V_Core::StartADMAWrite(u16 *pMem, u32 sz) { #ifndef ENABLE_NEW_IOPDMA_SPU2 - int size = (sz)&(~511); + int size = (sz) & (~511); - if(MsgAutoDMA()) ConLog("* SPU2-X: DMA%c AutoDMA Transfer of %d bytes to %x (%02x %x %04x).\n", - GetDmaIndexChar(), size<<1, TSA, DMABits, AutoDMACtrl, (~Regs.ATTR)&0x7fff); + if (MsgAutoDMA()) + ConLog("* SPU2-X: DMA%c AutoDMA Transfer of %d bytes to %x (%02x %x %04x).\n", + GetDmaIndexChar(), size << 1, TSA, DMABits, AutoDMACtrl, (~Regs.ATTR) & 0x7fff); - InputDataProgress = 0; - if((AutoDMACtrl&(Index+1))==0) - { - TSA = 0x2000 + (Index<<10); - DMAICounter = size; - } - else if(size>=512) - { - InputDataLeft = size; - if(AdmaInProgress==0) - { + InputDataProgress = 0; + if ((AutoDMACtrl & (Index + 1)) == 0) { + TSA = 0x2000 + (Index << 10); + DMAICounter = size; + } else if (size >= 512) { + InputDataLeft = size; + if (AdmaInProgress == 0) { #ifdef PCM24_S1_INTERLEAVE - if((Index==1)&&((PlayMode&8)==8)) - { - AutoDMAReadBuffer(Index,1); - } - else - { - AutoDMAReadBuffer(Index,0); - } + if ((Index == 1) && ((PlayMode & 8) == 8)) { + AutoDMAReadBuffer(Index, 1); + } else { + AutoDMAReadBuffer(Index, 0); + } #else - if( ((PlayMode&4)==4) && (Index==0) ) - Cores[0].InputPosRead=0; + if (((PlayMode & 4) == 4) && (Index == 0)) + Cores[0].InputPosRead = 0; - AutoDMAReadBuffer(0); + AutoDMAReadBuffer(0); #endif - // Klonoa 2 - if(size==512) - DMAICounter = size; - } + // Klonoa 2 + if (size == 512) + DMAICounter = size; + } - AdmaInProgress = 1; - } - else - { - InputDataLeft = 0; - DMAICounter = 1; - } - TADR = MADR + (size<<1); + AdmaInProgress = 1; + } else { + InputDataLeft = 0; + DMAICounter = 1; + } + TADR = MADR + (size << 1); #endif } @@ -188,489 +190,442 @@ void V_Core::StartADMAWrite(u16 *pMem, u32 sz) // by the grace of not being used." // // Update: This hack is no longer needed when we don't do a core reset. Guess the null pc was in spu2 memory? -#define NO_BIOS_HACKFIX 1 // set to 1 to disable the hackfix +#define NO_BIOS_HACKFIX 1 // set to 1 to disable the hackfix void V_Core::PlainDMAWrite(u16 *pMem, u32 size) { - // Perform an alignment check. - // Not really important. Everything should work regardless, - // but it could be indicative of an emulation foopah elsewhere. + // Perform an alignment check. + // Not really important. Everything should work regardless, + // but it could be indicative of an emulation foopah elsewhere. - if(MsgToConsole()) { - // Don't need this anymore. Target may still be good to know though. - /*if((uptr)pMem & 15) + if (MsgToConsole()) { + // Don't need this anymore. Target may still be good to know though. + /*if((uptr)pMem & 15) { ConLog("* SPU2 DMA Write > Misaligned source. Core: %d IOP: %p TSA: 0x%x Size: 0x%x\n", Index, (void*)pMem, TSA, size); }*/ - if(TSA & 7) - { - ConLog("* SPU2 DMA Write > Misaligned target. Core: %d IOP: %p TSA: 0x%x Size: 0x%x\n", Index, (void*)pMem, TSA, size ); - } - } + if (TSA & 7) { + ConLog("* SPU2 DMA Write > Misaligned target. Core: %d IOP: %p TSA: 0x%x Size: 0x%x\n", Index, (void *)pMem, TSA, size); + } + } - if(Index==0) - DMA4LogWrite(pMem,size<<1); - else - DMA7LogWrite(pMem,size<<1); + if (Index == 0) + DMA4LogWrite(pMem, size << 1); + else + DMA7LogWrite(pMem, size << 1); - TSA &= 0xfffff; + TSA &= 0xfffff; - u32 buff1end = TSA + size; - u32 buff2end=0; - if( buff1end > 0x100000 ) - { - buff2end = buff1end - 0x100000; - buff1end = 0x100000; - } + u32 buff1end = TSA + size; + u32 buff2end = 0; + if (buff1end > 0x100000) { + buff2end = buff1end - 0x100000; + buff1end = 0x100000; + } - const int cacheIdxStart = TSA / pcm_WordsPerBlock; - const int cacheIdxEnd = (buff1end+pcm_WordsPerBlock-1) / pcm_WordsPerBlock; - PcmCacheEntry* cacheLine = &pcm_cache_data[cacheIdxStart]; - PcmCacheEntry& cacheEnd = pcm_cache_data[cacheIdxEnd]; + const int cacheIdxStart = TSA / pcm_WordsPerBlock; + const int cacheIdxEnd = (buff1end + pcm_WordsPerBlock - 1) / pcm_WordsPerBlock; + PcmCacheEntry *cacheLine = &pcm_cache_data[cacheIdxStart]; + PcmCacheEntry &cacheEnd = pcm_cache_data[cacheIdxEnd]; - do - { - cacheLine->Validated = false; - cacheLine++; - } while ( cacheLine != &cacheEnd ); + do { + cacheLine->Validated = false; + cacheLine++; + } while (cacheLine != &cacheEnd); - //ConLog( "* SPU2-X: Cache Clear Range! TSA=0x%x, TDA=0x%x (low8=0x%x, high8=0x%x, len=0x%x)\n", - // TSA, buff1end, flagTSA, flagTDA, clearLen ); + //ConLog( "* SPU2-X: Cache Clear Range! TSA=0x%x, TDA=0x%x (low8=0x%x, high8=0x%x, len=0x%x)\n", + // TSA, buff1end, flagTSA, flagTDA, clearLen ); - // First Branch needs cleared: - // It starts at TSA and goes to buff1end. + // First Branch needs cleared: + // It starts at TSA and goes to buff1end. - const u32 buff1size = (buff1end-TSA); - memcpy( GetMemPtr( TSA ), pMem, buff1size*2 ); + const u32 buff1size = (buff1end - TSA); + memcpy(GetMemPtr(TSA), pMem, buff1size * 2); - u32 TDA; + u32 TDA; - if( buff2end > 0 ) - { - // second branch needs copied: - // It starts at the beginning of memory and moves forward to buff2end + if (buff2end > 0) { + // second branch needs copied: + // It starts at the beginning of memory and moves forward to buff2end - // endpoint cache should be irrelevant, since it's almost certainly dynamic - // memory below 0x2800 (registers and such) - //const u32 endpt2 = (buff2end + roundUp) / indexer_scalar; - //memset( pcm_cache_flags, 0, endpt2 ); + // endpoint cache should be irrelevant, since it's almost certainly dynamic + // memory below 0x2800 (registers and such) + //const u32 endpt2 = (buff2end + roundUp) / indexer_scalar; + //memset( pcm_cache_flags, 0, endpt2 ); - // Emulation Grayarea: Should addresses wrap around to zero, or wrap around to - // 0x2800? Hard to know for sure (almost no games depend on this) + // Emulation Grayarea: Should addresses wrap around to zero, or wrap around to + // 0x2800? Hard to know for sure (almost no games depend on this) - memcpy( GetMemPtr( 0 ), &pMem[buff1size], buff2end*2 ); - TDA = (buff2end+1) & 0xfffff; + memcpy(GetMemPtr(0), &pMem[buff1size], buff2end * 2); + TDA = (buff2end + 1) & 0xfffff; - // Flag interrupt? If IRQA occurs between start and dest, flag it. - // Important: Test both core IRQ settings for either DMA! - // Note: Because this buffer wraps, we use || instead of && +// Flag interrupt? If IRQA occurs between start and dest, flag it. +// Important: Test both core IRQ settings for either DMA! +// Note: Because this buffer wraps, we use || instead of && #if NO_BIOS_HACKFIX - for( int i=0; i<2; i++ ) - { - // Start is exclusive and end is inclusive... maybe? The end is documented to be inclusive, - // which suggests that memory access doesn't trigger interrupts, incrementing registers does - // (which would mean that if TSA=IRQA an interrupt doesn't fire... I guess?) - // Chaos Legion uses interrupt addresses set to the beginning of the two buffers in a double - // buffer scheme and sets LSA of one of the voices to the start of the opposite buffer. - // However it transfers to the same address right after setting IRQA, which by our previous - // understanding would trigger the interrupt early causing it to switch buffers again immediately - // and an interrupt never fires again, leaving the voices looping the same samples forever. + for (int i = 0; i < 2; i++) { + // Start is exclusive and end is inclusive... maybe? The end is documented to be inclusive, + // which suggests that memory access doesn't trigger interrupts, incrementing registers does + // (which would mean that if TSA=IRQA an interrupt doesn't fire... I guess?) + // Chaos Legion uses interrupt addresses set to the beginning of the two buffers in a double + // buffer scheme and sets LSA of one of the voices to the start of the opposite buffer. + // However it transfers to the same address right after setting IRQA, which by our previous + // understanding would trigger the interrupt early causing it to switch buffers again immediately + // and an interrupt never fires again, leaving the voices looping the same samples forever. - if (Cores[i].IRQEnable && (Cores[i].IRQA > TSA || Cores[i].IRQA <= TDA)) - { - //ConLog("DMAwrite Core %d: IRQ Called (IRQ passed). IRQA = %x Cycles = %d\n", i, Cores[i].IRQA, Cycles ); - SetIrqCall(i); - } - } + if (Cores[i].IRQEnable && (Cores[i].IRQA > TSA || Cores[i].IRQA <= TDA)) { + //ConLog("DMAwrite Core %d: IRQ Called (IRQ passed). IRQA = %x Cycles = %d\n", i, Cores[i].IRQA, Cycles ); + SetIrqCall(i); + } + } #else - if ((IRQEnable && (IRQA > TSA || IRQA <= TDA)) + if ((IRQEnable && (IRQA > TSA || IRQA <= TDA)) { - SetIrqCall(Index); + SetIrqCall(Index); } #endif - } - else - { - // Buffer doesn't wrap/overflow! - // Just set the TDA and check for an IRQ... + } else { + // Buffer doesn't wrap/overflow! + // Just set the TDA and check for an IRQ... - TDA = (buff1end + 1) & 0xfffff; + TDA = (buff1end + 1) & 0xfffff; - // Flag interrupt? If IRQA occurs between start and dest, flag it. - // Important: Test both core IRQ settings for either DMA! +// Flag interrupt? If IRQA occurs between start and dest, flag it. +// Important: Test both core IRQ settings for either DMA! #if NO_BIOS_HACKFIX - for( int i=0; i<2; i++ ) - { - if (Cores[i].IRQEnable && (Cores[i].IRQA > TSA && Cores[i].IRQA <= TDA)) - { - //ConLog("DMAwrite Core %d: IRQ Called (IRQ passed). IRQA = %x Cycles = %d\n", i, Cores[i].IRQA, Cycles ); - SetIrqCall(i); - } - } + for (int i = 0; i < 2; i++) { + if (Cores[i].IRQEnable && (Cores[i].IRQA > TSA && Cores[i].IRQA <= TDA)) { + //ConLog("DMAwrite Core %d: IRQ Called (IRQ passed). IRQA = %x Cycles = %d\n", i, Cores[i].IRQA, Cycles ); + SetIrqCall(i); + } + } #else - if( IRQEnable && (IRQA > TSA) && (IRQA <= TDA) ) - { - SetIrqCall(Index); - } + if (IRQEnable && (IRQA > TSA) && (IRQA <= TDA)) { + SetIrqCall(Index); + } #endif - } + } - TSA = TDA; - DMAICounter = size; - TADR = MADR + (size<<1); + TSA = TDA; + DMAICounter = size; + TADR = MADR + (size << 1); } -void V_Core::DoDMAread(u16* pMem, u32 size) +void V_Core::DoDMAread(u16 *pMem, u32 size) { #ifndef ENABLE_NEW_IOPDMA_SPU2 - TSA &= 0xfffff; + TSA &= 0xfffff; - u32 buff1end = TSA + size; - u32 buff2end = 0; - if( buff1end > 0x100000 ) - { - buff2end = buff1end - 0x100000; - buff1end = 0x100000; - } + u32 buff1end = TSA + size; + u32 buff2end = 0; + if (buff1end > 0x100000) { + buff2end = buff1end - 0x100000; + buff1end = 0x100000; + } - const u32 buff1size = (buff1end-TSA); - memcpy( pMem, GetMemPtr( TSA ), buff1size*2 ); + const u32 buff1size = (buff1end - TSA); + memcpy(pMem, GetMemPtr(TSA), buff1size * 2); - // Note on TSA's position after our copy finishes: - // IRQA should be measured by the end of the writepos+0x20. But the TDA - // should be written back at the precise endpoint of the xfer. + // Note on TSA's position after our copy finishes: + // IRQA should be measured by the end of the writepos+0x20. But the TDA + // should be written back at the precise endpoint of the xfer. - u32 TDA; + u32 TDA; - if( buff2end > 0 ) - { - // second branch needs cleared: - // It starts at the beginning of memory and moves forward to buff2end + if (buff2end > 0) { + // second branch needs cleared: + // It starts at the beginning of memory and moves forward to buff2end - memcpy( &pMem[buff1size], GetMemPtr( 0 ), buff2end*2 ); + memcpy(&pMem[buff1size], GetMemPtr(0), buff2end * 2); - TDA = (buff2end+0x20) & 0xfffff; + TDA = (buff2end + 0x20) & 0xfffff; - // Flag interrupt? If IRQA occurs between start and dest, flag it. - // Important: Test both core IRQ settings for either DMA! - // Note: Because this buffer wraps, we use || instead of && + // Flag interrupt? If IRQA occurs between start and dest, flag it. + // Important: Test both core IRQ settings for either DMA! + // Note: Because this buffer wraps, we use || instead of && - for( int i=0; i<2; i++ ) - { - if (Cores[i].IRQEnable && (Cores[i].IRQA > TSA || Cores[i].IRQA <= TDA)) - { - SetIrqCall(i); - } - } - } - else - { - // Buffer doesn't wrap/overflow! - // Just set the TDA and check for an IRQ... + for (int i = 0; i < 2; i++) { + if (Cores[i].IRQEnable && (Cores[i].IRQA > TSA || Cores[i].IRQA <= TDA)) { + SetIrqCall(i); + } + } + } else { + // Buffer doesn't wrap/overflow! + // Just set the TDA and check for an IRQ... - TDA = (buff1end + 0x20) & 0xfffff; + TDA = (buff1end + 0x20) & 0xfffff; - // Flag interrupt? If IRQA occurs between start and dest, flag it. - // Important: Test both core IRQ settings for either DMA! + // Flag interrupt? If IRQA occurs between start and dest, flag it. + // Important: Test both core IRQ settings for either DMA! - for( int i=0; i<2; i++ ) - { - if (Cores[i].IRQEnable && (Cores[i].IRQA > TSA && Cores[i].IRQA <= TDA)) - { - SetIrqCall(i); - } - } - } + for (int i = 0; i < 2; i++) { + if (Cores[i].IRQEnable && (Cores[i].IRQA > TSA && Cores[i].IRQA <= TDA)) { + SetIrqCall(i); + } + } + } - TSA = TDA; + TSA = TDA; - DMAICounter = size; - Regs.STATX &= ~0x80; - //Regs.ATTR |= 0x30; - TADR = MADR + (size<<1); + DMAICounter = size; + Regs.STATX &= ~0x80; + //Regs.ATTR |= 0x30; + TADR = MADR + (size << 1); #endif } -void V_Core::DoDMAwrite(u16* pMem, u32 size) +void V_Core::DoDMAwrite(u16 *pMem, u32 size) { #ifndef ENABLE_NEW_IOPDMA_SPU2 - DMAPtr = pMem; + DMAPtr = pMem; - if(size<2) { - //if(dma7callback) dma7callback(); - Regs.STATX &= ~0x80; - //Regs.ATTR |= 0x30; - DMAICounter=1; + if (size < 2) { + //if(dma7callback) dma7callback(); + Regs.STATX &= ~0x80; + //Regs.ATTR |= 0x30; + DMAICounter = 1; - return; - } + return; + } - if( IsDevBuild ) - { - DebugCores[Index].lastsize = size; - DebugCores[Index].dmaFlag = 2; - } + if (IsDevBuild) { + DebugCores[Index].lastsize = size; + DebugCores[Index].dmaFlag = 2; + } - if(MsgToConsole()) - { - if (TSA > 0xfffff){ - ConLog("* SPU2-X: Transfer Start Address out of bounds. TSA is %x\n", TSA); - } - } + if (MsgToConsole()) { + if (TSA > 0xfffff) { + ConLog("* SPU2-X: Transfer Start Address out of bounds. TSA is %x\n", TSA); + } + } - TSA &= 0xfffff; + TSA &= 0xfffff; - bool adma_enable = ((AutoDMACtrl&(Index+1))==(Index+1)); + bool adma_enable = ((AutoDMACtrl & (Index + 1)) == (Index + 1)); - if(adma_enable) - { - TSA&=0x1fff; - StartADMAWrite(pMem,size); - } - else - { - if(MsgDMA()) ConLog("* SPU2-X: DMA%c Transfer of %d bytes to %x (%02x %x %04x). IRQE = %d IRQA = %x \n", - GetDmaIndexChar(),size<<1,TSA,DMABits,AutoDMACtrl,(~Regs.ATTR)&0x7fff, - Cores[0].IRQEnable, Cores[0].IRQA); + if (adma_enable) { + TSA &= 0x1fff; + StartADMAWrite(pMem, size); + } else { + if (MsgDMA()) + ConLog("* SPU2-X: DMA%c Transfer of %d bytes to %x (%02x %x %04x). IRQE = %d IRQA = %x \n", + GetDmaIndexChar(), size << 1, TSA, DMABits, AutoDMACtrl, (~Regs.ATTR) & 0x7fff, + Cores[0].IRQEnable, Cores[0].IRQA); - PlainDMAWrite(pMem,size); - } - Regs.STATX &= ~0x80; - //Regs.ATTR |= 0x30; + PlainDMAWrite(pMem, size); + } + Regs.STATX &= ~0x80; +//Regs.ATTR |= 0x30; #endif } -s32 V_Core::NewDmaRead(u32* data, u32 bytesLeft, u32* bytesProcessed) +s32 V_Core::NewDmaRead(u32 *data, u32 bytesLeft, u32 *bytesProcessed) { #ifdef ENABLE_NEW_IOPDMA_SPU2 - bool DmaStarting = !DmaStarted; - DmaStarted = true; + bool DmaStarting = !DmaStarted; + DmaStarted = true; - TSA &= 0xfffff; + TSA &= 0xfffff; - u16* pMem = (u16*)data; + u16 *pMem = (u16 *)data; - u32 buff1end = TSA + bytesLeft; - u32 buff2end = 0; - if( buff1end > 0x100000 ) - { - buff2end = buff1end - 0x100000; - buff1end = 0x100000; - } + u32 buff1end = TSA + bytesLeft; + u32 buff2end = 0; + if (buff1end > 0x100000) { + buff2end = buff1end - 0x100000; + buff1end = 0x100000; + } - const u32 buff1size = (buff1end-TSA); - memcpy( pMem, GetMemPtr( TSA ), buff1size*2 ); + const u32 buff1size = (buff1end - TSA); + memcpy(pMem, GetMemPtr(TSA), buff1size * 2); - // Note on TSA's position after our copy finishes: - // IRQA should be measured by the end of the writepos+0x20. But the TDA - // should be written back at the precise endpoint of the xfer. + // Note on TSA's position after our copy finishes: + // IRQA should be measured by the end of the writepos+0x20. But the TDA + // should be written back at the precise endpoint of the xfer. - u32 TDA; + u32 TDA; - if( buff2end > 0 ) - { - // second branch needs cleared: - // It starts at the beginning of memory and moves forward to buff2end + if (buff2end > 0) { + // second branch needs cleared: + // It starts at the beginning of memory and moves forward to buff2end - memcpy( &pMem[buff1size], GetMemPtr( 0 ), buff2end*2 ); + memcpy(&pMem[buff1size], GetMemPtr(0), buff2end * 2); - TDA = (buff2end+0x20) & 0xfffff; + TDA = (buff2end + 0x20) & 0xfffff; - // Flag interrupt? If IRQA occurs between start and dest, flag it. - // Important: Test both core IRQ settings for either DMA! - // Note: Because this buffer wraps, we use || instead of && + // Flag interrupt? If IRQA occurs between start and dest, flag it. + // Important: Test both core IRQ settings for either DMA! + // Note: Because this buffer wraps, we use || instead of && - for( int i=0; i<2; i++ ) - { - if( Cores[i].IRQEnable && (Cores[i].IRQA > TSA || Cores[i].IRQA <= TDA) ) - { - SetIrqCall(i); - } - } - } - else - { - // Buffer doesn't wrap/overflow! - // Just set the TDA and check for an IRQ... + for (int i = 0; i < 2; i++) { + if (Cores[i].IRQEnable && (Cores[i].IRQA > TSA || Cores[i].IRQA <= TDA)) { + SetIrqCall(i); + } + } + } else { + // Buffer doesn't wrap/overflow! + // Just set the TDA and check for an IRQ... - TDA = (buff1end + 0x20) & 0xfffff; + TDA = (buff1end + 0x20) & 0xfffff; - // Flag interrupt? If IRQA occurs between start and dest, flag it. - // Important: Test both core IRQ settings for either DMA! + // Flag interrupt? If IRQA occurs between start and dest, flag it. + // Important: Test both core IRQ settings for either DMA! - for( int i=0; i<2; i++ ) - { - if( Cores[i].IRQEnable && (Cores[i].IRQA > TSA) && (Cores[i].IRQA <= TDA) ) - { - SetIrqCall(i); - } - } - } + for (int i = 0; i < 2; i++) { + if (Cores[i].IRQEnable && (Cores[i].IRQA > TSA) && (Cores[i].IRQA <= TDA)) { + SetIrqCall(i); + } + } + } - TSA = TDA; + TSA = TDA; - Regs.STATX &= ~0x80; - Regs.STATX |= 0x400; + Regs.STATX &= ~0x80; + Regs.STATX |= 0x400; #endif - *bytesProcessed = bytesLeft; - return 0; + *bytesProcessed = bytesLeft; + return 0; } -s32 V_Core::NewDmaWrite(u32* data, u32 bytesLeft, u32* bytesProcessed) +s32 V_Core::NewDmaWrite(u32 *data, u32 bytesLeft, u32 *bytesProcessed) { #ifdef ENABLE_NEW_IOPDMA_SPU2 - bool DmaStarting = !DmaStarted; - DmaStarted = true; + bool DmaStarting = !DmaStarted; + DmaStarted = true; - if(bytesLeft<2) - { - // execute interrupt code early - NewDmaInterrupt(); + if (bytesLeft < 2) { + // execute interrupt code early + NewDmaInterrupt(); - *bytesProcessed = bytesLeft; - return 0; - } + *bytesProcessed = bytesLeft; + return 0; + } - if( IsDevBuild ) - { - DebugCores[Index].lastsize = bytesLeft; - DebugCores[Index].dmaFlag = 1; - } + if (IsDevBuild) { + DebugCores[Index].lastsize = bytesLeft; + DebugCores[Index].dmaFlag = 1; + } - TSA &= 0xfffff; + TSA &= 0xfffff; - bool adma_enable = ((AutoDMACtrl&(Index+1))==(Index+1)); + bool adma_enable = ((AutoDMACtrl & (Index + 1)) == (Index + 1)); - if(adma_enable) - { - TSA&=0x1fff; + if (adma_enable) { + TSA &= 0x1fff; - if(MsgAutoDMA() && DmaStarting) ConLog("* SPU2-X: DMA%c AutoDMA Transfer of %d bytes to %x (%02x %x %04x).\n", - GetDmaIndexChar(), bytesLeft<<1, TSA, DMABits, AutoDMACtrl, (~Regs.ATTR)&0x7fff); + if (MsgAutoDMA() && DmaStarting) + ConLog("* SPU2-X: DMA%c AutoDMA Transfer of %d bytes to %x (%02x %x %04x).\n", + GetDmaIndexChar(), bytesLeft << 1, TSA, DMABits, AutoDMACtrl, (~Regs.ATTR) & 0x7fff); - u32 processed = 0; - while((AutoDmaFree>0)&&(bytesLeft>=0x400)) - { - // copy block + u32 processed = 0; + while ((AutoDmaFree > 0) && (bytesLeft >= 0x400)) { + // copy block - LogAutoDMA( Index ? ADMA7LogFile : ADMA4LogFile ); + LogAutoDMA(Index ? ADMA7LogFile : ADMA4LogFile); - // HACKFIX!! DMAPtr can be invalid after a savestate load, so the savestate just forces it - // to NULL and we ignore it here. (used to work in old VM editions of PCSX2 with fixed - // addressing, but new PCSX2s have dynamic memory addressing). + // HACKFIX!! DMAPtr can be invalid after a savestate load, so the savestate just forces it + // to NULL and we ignore it here. (used to work in old VM editions of PCSX2 with fixed + // addressing, but new PCSX2s have dynamic memory addressing). - s16* mptr = (s16*)data; + s16 *mptr = (s16 *)data; - if(false)//(mode) - { - //memcpy((ADMATempBuffer+(InputPosWrite<<1)),mptr,0x400); - memcpy(GetMemPtr(0x2000+(Index<<10)+InputPosWrite),mptr,0x400); - mptr+=0x200; + if (false) //(mode) + { + //memcpy((ADMATempBuffer+(InputPosWrite<<1)),mptr,0x400); + memcpy(GetMemPtr(0x2000 + (Index << 10) + InputPosWrite), mptr, 0x400); + mptr += 0x200; - // Flag interrupt? If IRQA occurs between start and dest, flag it. - // Important: Test both core IRQ settings for either DMA! + // Flag interrupt? If IRQA occurs between start and dest, flag it. + // Important: Test both core IRQ settings for either DMA! - u32 dummyTSA = 0x2000+(Index<<10)+InputPosWrite; - u32 dummyTDA = 0x2000+(Index<<10)+InputPosWrite+0x200; + u32 dummyTSA = 0x2000 + (Index << 10) + InputPosWrite; + u32 dummyTDA = 0x2000 + (Index << 10) + InputPosWrite + 0x200; - for( int i=0; i<2; i++ ) - { - if( Cores[i].IRQEnable && (Cores[i].IRQA > dummyTSA) && (Cores[i].IRQA <= dummyTDA) ) - { - SetIrqCall(i); - } - } - } - else - { - //memcpy((ADMATempBuffer+InputPosWrite),mptr,0x200); - memcpy(GetMemPtr(0x2000+(Index<<10)+InputPosWrite),mptr,0x200); - mptr+=0x100; + for (int i = 0; i < 2; i++) { + if (Cores[i].IRQEnable && (Cores[i].IRQA > dummyTSA) && (Cores[i].IRQA <= dummyTDA)) { + SetIrqCall(i); + } + } + } else { + //memcpy((ADMATempBuffer+InputPosWrite),mptr,0x200); + memcpy(GetMemPtr(0x2000 + (Index << 10) + InputPosWrite), mptr, 0x200); + mptr += 0x100; - // Flag interrupt? If IRQA occurs between start and dest, flag it. - // Important: Test both core IRQ settings for either DMA! + // Flag interrupt? If IRQA occurs between start and dest, flag it. + // Important: Test both core IRQ settings for either DMA! - u32 dummyTSA = 0x2000+(Index<<10)+InputPosWrite; - u32 dummyTDA = 0x2000+(Index<<10)+InputPosWrite+0x100; + u32 dummyTSA = 0x2000 + (Index << 10) + InputPosWrite; + u32 dummyTDA = 0x2000 + (Index << 10) + InputPosWrite + 0x100; - for( int i=0; i<2; i++ ) - { - if( Cores[i].IRQEnable && (Cores[i].IRQA > dummyTSA) && (Cores[i].IRQA <= dummyTDA) ) - { - SetIrqCall(i); - } - } + for (int i = 0; i < 2; i++) { + if (Cores[i].IRQEnable && (Cores[i].IRQA > dummyTSA) && (Cores[i].IRQA <= dummyTDA)) { + SetIrqCall(i); + } + } - //memcpy((ADMATempBuffer+InputPosWrite+0x200),mptr,0x200); - memcpy(GetMemPtr(0x2200+(Index<<10)+InputPosWrite),mptr,0x200); - mptr+=0x100; + //memcpy((ADMATempBuffer+InputPosWrite+0x200),mptr,0x200); + memcpy(GetMemPtr(0x2200 + (Index << 10) + InputPosWrite), mptr, 0x200); + mptr += 0x100; - // Flag interrupt? If IRQA occurs between start and dest, flag it. - // Important: Test both core IRQ settings for either DMA! + // Flag interrupt? If IRQA occurs between start and dest, flag it. + // Important: Test both core IRQ settings for either DMA! - dummyTSA = 0x2200+(Index<<10)+InputPosWrite; - dummyTDA = 0x2200+(Index<<10)+InputPosWrite+0x100; + dummyTSA = 0x2200 + (Index << 10) + InputPosWrite; + dummyTDA = 0x2200 + (Index << 10) + InputPosWrite + 0x100; - for( int i=0; i<2; i++ ) - { - if( Cores[i].IRQEnable && (Cores[i].IRQA > dummyTSA) && (Cores[i].IRQA <= dummyTDA) ) - { - SetIrqCall(i); - } - } + for (int i = 0; i < 2; i++) { + if (Cores[i].IRQEnable && (Cores[i].IRQA > dummyTSA) && (Cores[i].IRQA <= dummyTDA)) { + SetIrqCall(i); + } + } + } + // See ReadInput at mixer.cpp for explanation on the commented out lines + // - } - // See ReadInput at mixer.cpp for explanation on the commented out lines - // + InputPosWrite = (InputPosWrite + 0x100) & 0x1ff; + AutoDmaFree -= 0x200; + processed += 0x400; + bytesLeft -= 0x400; + } - InputPosWrite = (InputPosWrite + 0x100) & 0x1ff; - AutoDmaFree -= 0x200; - processed += 0x400; - bytesLeft -= 0x400; - } + if (processed == 0) { + *bytesProcessed = 0; + return 768 * 15; // pause a bit + } else { + *bytesProcessed = processed; + return 0; // auto pause + } + } else { + if (MsgDMA() && DmaStarting) + ConLog("* SPU2-X: DMA%c Transfer of %d bytes to %x (%02x %x %04x).\n", + GetDmaIndexChar(), bytesLeft, TSA, DMABits, AutoDMACtrl, (~Regs.ATTR) & 0x7fff); - if(processed==0) - { - *bytesProcessed = 0; - return 768*15; // pause a bit - } - else - { - *bytesProcessed = processed; - return 0; // auto pause - } - } - else - { - if(MsgDMA() && DmaStarting) ConLog("* SPU2-X: DMA%c Transfer of %d bytes to %x (%02x %x %04x).\n", - GetDmaIndexChar(),bytesLeft,TSA,DMABits,AutoDMACtrl,(~Regs.ATTR)&0x7fff); + if (bytesLeft > 2048) + bytesLeft = 2048; - if(bytesLeft> 2048) - bytesLeft = 2048; - - // TODO: Sliced transfers? - PlainDMAWrite((u16*)data,bytesLeft/2); - } - Regs.STATX &= ~0x80; - Regs.STATX |= 0x400; + // TODO: Sliced transfers? + PlainDMAWrite((u16 *)data, bytesLeft / 2); + } + Regs.STATX &= ~0x80; + Regs.STATX |= 0x400; #endif - *bytesProcessed = bytesLeft; - return 0; + *bytesProcessed = bytesLeft; + return 0; } void V_Core::NewDmaInterrupt() { #ifdef ENABLE_NEW_IOPDMA_SPU2 - FileLog("[%10d] SPU2 interruptDMA4\n",Cycles); - Regs.STATX |= 0x80; - Regs.STATX &= ~0x400; - //Regs.ATTR &= ~0x30; - DmaStarted = false; + FileLog("[%10d] SPU2 interruptDMA4\n", Cycles); + Regs.STATX |= 0x80; + Regs.STATX &= ~0x400; + //Regs.ATTR &= ~0x30; + DmaStarted = false; #endif } diff --git a/plugins/spu2-x/src/DplIIdecoder.cpp b/plugins/spu2-x/src/DplIIdecoder.cpp index c010541155..32183d5fd2 100644 --- a/plugins/spu2-x/src/DplIIdecoder.cpp +++ b/plugins/spu2-x/src/DplIIdecoder.cpp @@ -21,154 +21,154 @@ #include "Global.h" static const u8 sLogTable[256] = { - 0x00,0x3C,0x60,0x78,0x8C,0x9C,0xA8,0xB4,0xBE,0xC8,0xD0,0xD8,0xDE,0xE4,0xEA,0xF0, - 0xF6,0xFA,0xFE,0x04,0x08,0x0C,0x10,0x14,0x16,0x1A,0x1E,0x20,0x24,0x26,0x2A,0x2C, - 0x2E,0x32,0x34,0x36,0x38,0x3A,0x3E,0x40,0x42,0x44,0x46,0x48,0x4A,0x4C,0x4E,0x50, - 0x50,0x52,0x54,0x56,0x58,0x5A,0x5A,0x5C,0x5E,0x60,0x60,0x62,0x64,0x66,0x66,0x68, - 0x6A,0x6A,0x6C,0x6E,0x6E,0x70,0x70,0x72,0x74,0x74,0x76,0x76,0x78,0x7A,0x7A,0x7C, - 0x7C,0x7E,0x7E,0x80,0x80,0x82,0x82,0x84,0x84,0x86,0x86,0x88,0x88,0x8A,0x8A,0x8C, - 0x8C,0x8C,0x8E,0x8E,0x90,0x90,0x92,0x92,0x92,0x94,0x94,0x96,0x96,0x96,0x98,0x98, - 0x9A,0x9A,0x9A,0x9C,0x9C,0x9C,0x9E,0x9E,0xA0,0xA0,0xA0,0xA2,0xA2,0xA2,0xA4,0xA4, - 0xA4,0xA6,0xA6,0xA6,0xA8,0xA8,0xA8,0xAA,0xAA,0xAA,0xAC,0xAC,0xAC,0xAC,0xAE,0xAE, - 0xAE,0xB0,0xB0,0xB0,0xB2,0xB2,0xB2,0xB2,0xB4,0xB4,0xB4,0xB6,0xB6,0xB6,0xB6,0xB8, - 0xB8,0xB8,0xB8,0xBA,0xBA,0xBA,0xBC,0xBC,0xBC,0xBC,0xBE,0xBE,0xBE,0xBE,0xC0,0xC0, - 0xC0,0xC0,0xC2,0xC2,0xC2,0xC2,0xC2,0xC4,0xC4,0xC4,0xC4,0xC6,0xC6,0xC6,0xC6,0xC8, - 0xC8,0xC8,0xC8,0xC8,0xCA,0xCA,0xCA,0xCA,0xCC,0xCC,0xCC,0xCC,0xCC,0xCE,0xCE,0xCE, - 0xCE,0xCE,0xD0,0xD0,0xD0,0xD0,0xD0,0xD2,0xD2,0xD2,0xD2,0xD2,0xD4,0xD4,0xD4,0xD4, - 0xD4,0xD6,0xD6,0xD6,0xD6,0xD6,0xD8,0xD8,0xD8,0xD8,0xD8,0xD8,0xDA,0xDA,0xDA,0xDA, - 0xDA,0xDC,0xDC,0xDC,0xDC,0xDC,0xDC,0xDE,0xDE,0xDE,0xDE,0xDE,0xDE,0xE0,0xE0,0xE0, + 0x00, 0x3C, 0x60, 0x78, 0x8C, 0x9C, 0xA8, 0xB4, 0xBE, 0xC8, 0xD0, 0xD8, 0xDE, 0xE4, 0xEA, 0xF0, + 0xF6, 0xFA, 0xFE, 0x04, 0x08, 0x0C, 0x10, 0x14, 0x16, 0x1A, 0x1E, 0x20, 0x24, 0x26, 0x2A, 0x2C, + 0x2E, 0x32, 0x34, 0x36, 0x38, 0x3A, 0x3E, 0x40, 0x42, 0x44, 0x46, 0x48, 0x4A, 0x4C, 0x4E, 0x50, + 0x50, 0x52, 0x54, 0x56, 0x58, 0x5A, 0x5A, 0x5C, 0x5E, 0x60, 0x60, 0x62, 0x64, 0x66, 0x66, 0x68, + 0x6A, 0x6A, 0x6C, 0x6E, 0x6E, 0x70, 0x70, 0x72, 0x74, 0x74, 0x76, 0x76, 0x78, 0x7A, 0x7A, 0x7C, + 0x7C, 0x7E, 0x7E, 0x80, 0x80, 0x82, 0x82, 0x84, 0x84, 0x86, 0x86, 0x88, 0x88, 0x8A, 0x8A, 0x8C, + 0x8C, 0x8C, 0x8E, 0x8E, 0x90, 0x90, 0x92, 0x92, 0x92, 0x94, 0x94, 0x96, 0x96, 0x96, 0x98, 0x98, + 0x9A, 0x9A, 0x9A, 0x9C, 0x9C, 0x9C, 0x9E, 0x9E, 0xA0, 0xA0, 0xA0, 0xA2, 0xA2, 0xA2, 0xA4, 0xA4, + 0xA4, 0xA6, 0xA6, 0xA6, 0xA8, 0xA8, 0xA8, 0xAA, 0xAA, 0xAA, 0xAC, 0xAC, 0xAC, 0xAC, 0xAE, 0xAE, + 0xAE, 0xB0, 0xB0, 0xB0, 0xB2, 0xB2, 0xB2, 0xB2, 0xB4, 0xB4, 0xB4, 0xB6, 0xB6, 0xB6, 0xB6, 0xB8, + 0xB8, 0xB8, 0xB8, 0xBA, 0xBA, 0xBA, 0xBC, 0xBC, 0xBC, 0xBC, 0xBE, 0xBE, 0xBE, 0xBE, 0xC0, 0xC0, + 0xC0, 0xC0, 0xC2, 0xC2, 0xC2, 0xC2, 0xC2, 0xC4, 0xC4, 0xC4, 0xC4, 0xC6, 0xC6, 0xC6, 0xC6, 0xC8, + 0xC8, 0xC8, 0xC8, 0xC8, 0xCA, 0xCA, 0xCA, 0xCA, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCE, 0xCE, 0xCE, + 0xCE, 0xCE, 0xD0, 0xD0, 0xD0, 0xD0, 0xD0, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD4, 0xD4, 0xD4, 0xD4, + 0xD4, 0xD6, 0xD6, 0xD6, 0xD6, 0xD6, 0xD8, 0xD8, 0xD8, 0xD8, 0xD8, 0xD8, 0xDA, 0xDA, 0xDA, 0xDA, + 0xDA, 0xDC, 0xDC, 0xDC, 0xDC, 0xDC, 0xDC, 0xDE, 0xDE, 0xDE, 0xDE, 0xDE, 0xDE, 0xE0, 0xE0, 0xE0, }; -static float Gfl=0,Gfr=0; -static float LMax=0,RMax=0; +static float Gfl = 0, Gfr = 0; +static float LMax = 0, RMax = 0; -static float AccL=0; -static float AccR=0; +static float AccL = 0; +static float AccR = 0; -const float Scale = 4294967296.0f; // tweak this value to change the overall output volume +const float Scale = 4294967296.0f; // tweak this value to change the overall output volume -const float GainL = 0.80f * Scale; -const float GainR = 0.80f * Scale; +const float GainL = 0.80f * Scale; +const float GainR = 0.80f * Scale; -const float GainC = 0.75f * Scale; +const float GainC = 0.75f * Scale; const float GainSL = 0.90f * Scale; const float GainSR = 0.90f * Scale; -const float GainLFE= 0.90f * Scale; +const float GainLFE = 0.90f * Scale; -const float AddCLR = 0.20f * Scale; // Stereo expansion +const float AddCLR = 0.20f * Scale; // Stereo expansion extern void ResetDplIIDecoder() { - Gfl=0; - Gfr=0; - LMax=0; - RMax=0; - AccL=0; - AccR=0; + Gfl = 0; + Gfr = 0; + LMax = 0; + RMax = 0; + AccL = 0; + AccR = 0; } -void ProcessDplIISample32( const StereoOut32& src, Stereo51Out32DplII * s) +void ProcessDplIISample32(const StereoOut32 &src, Stereo51Out32DplII *s) { - float IL = src.Left / (float)(1<<(SndOutVolumeShift+16)); - float IR = src.Right / (float)(1<<(SndOutVolumeShift+16)); + float IL = src.Left / (float)(1 << (SndOutVolumeShift + 16)); + float IR = src.Right / (float)(1 << (SndOutVolumeShift + 16)); - // Calculate center channel and LFE - float C = (IL+IR) * 0.5f; - float SUB = C; // no need to lowpass, the speaker amplifier should take care of it + // Calculate center channel and LFE + float C = (IL + IR) * 0.5f; + float SUB = C; // no need to lowpass, the speaker amplifier should take care of it - float L = IL - C; // Effective L/R data - float R = IR - C; + float L = IL - C; // Effective L/R data + float R = IR - C; - // Peak L/R - float PL = std::abs(L); - float PR = std::abs(R); + // Peak L/R + float PL = std::abs(L); + float PR = std::abs(R); - AccL += (PL-AccL)*0.1f; - AccR += (PR-AccR)*0.1f; - - // Calculate power balance - float Balance = (AccR-AccL); // -1 .. 1 + AccL += (PL - AccL) * 0.1f; + AccR += (PR - AccR) * 0.1f; - // If the power levels are different, then the audio is meant for the front speakers - float Frontness = std::abs(Balance); - float Rearness = 1-Frontness; // And the other way around + // Calculate power balance + float Balance = (AccR - AccL); // -1 .. 1 - // Equalize the power levels for L/R - float B = std::min(0.9f,std::max(-0.9f,Balance)); + // If the power levels are different, then the audio is meant for the front speakers + float Frontness = std::abs(Balance); + float Rearness = 1 - Frontness; // And the other way around - float VL = L / (1-B); // if B>0, it means R>L, so increase L, else decrease L - float VR = R / (1+B); // vice-versa + // Equalize the power levels for L/R + float B = std::min(0.9f, std::max(-0.9f, Balance)); - // 1.73+1.22 = 2.94; 2.94 = 0.34 = 0.9996; Close enough. - // The range for VL/VR is approximately 0..1, - // But in the cases where VL/VR are > 0.5, Rearness is 0 so it should never overflow. - const float RearScale = 0.34f * 2; + float VL = L / (1 - B); // if B>0, it means R>L, so increase L, else decrease L + float VR = R / (1 + B); // vice-versa - float SL = (VR*1.73f - VL*1.22f) * RearScale * Rearness; - float SR = (VR*1.22f - VL*1.73f) * RearScale * Rearness; - // Possible experiment: Play with stereo expension levels on rear + // 1.73+1.22 = 2.94; 2.94 = 0.34 = 0.9996; Close enough. + // The range for VL/VR is approximately 0..1, + // But in the cases where VL/VR are > 0.5, Rearness is 0 so it should never overflow. + const float RearScale = 0.34f * 2; - // Adjust the volume of the front speakers based on what we calculated above - L *= Frontness; - R *= Frontness; - - s32 CX = (s32)(C * AddCLR); + float SL = (VR * 1.73f - VL * 1.22f) * RearScale * Rearness; + float SR = (VR * 1.22f - VL * 1.73f) * RearScale * Rearness; + // Possible experiment: Play with stereo expension levels on rear - s->Left = (s32)(L * GainL ) + CX; - s->Right = (s32)(R * GainR ) + CX; - s->Center = (s32)(C * GainC ); - s->LFE = (s32)(SUB * GainLFE); - s->LeftBack = (s32)(SL * GainSL ); - s->RightBack = (s32)(SR * GainSR ); + // Adjust the volume of the front speakers based on what we calculated above + L *= Frontness; + R *= Frontness; + + s32 CX = (s32)(C * AddCLR); + + s->Left = (s32)(L * GainL) + CX; + s->Right = (s32)(R * GainR) + CX; + s->Center = (s32)(C * GainC); + s->LFE = (s32)(SUB * GainLFE); + s->LeftBack = (s32)(SL * GainSL); + s->RightBack = (s32)(SR * GainSR); } -void ProcessDplIISample16( const StereoOut32& src, Stereo51Out16DplII * s) +void ProcessDplIISample16(const StereoOut32 &src, Stereo51Out16DplII *s) { - Stereo51Out32DplII ss; - ProcessDplIISample32(src, &ss); + Stereo51Out32DplII ss; + ProcessDplIISample32(src, &ss); - s->Left = ss.Left >> 16; - s->Right = ss.Right >> 16; - s->Center = ss.Center >> 16; - s->LFE = ss.LFE >> 16; - s->LeftBack = ss.LeftBack >> 16; - s->RightBack = ss.RightBack >> 16; + s->Left = ss.Left >> 16; + s->Right = ss.Right >> 16; + s->Center = ss.Center >> 16; + s->LFE = ss.LFE >> 16; + s->LeftBack = ss.LeftBack >> 16; + s->RightBack = ss.RightBack >> 16; } -void ProcessDplSample32( const StereoOut32& src, Stereo51Out32Dpl * s) +void ProcessDplSample32(const StereoOut32 &src, Stereo51Out32Dpl *s) { - float ValL = src.Left / (float)(1<<(SndOutVolumeShift+16)); - float ValR = src.Right / (float)(1<<(SndOutVolumeShift+16)); + float ValL = src.Left / (float)(1 << (SndOutVolumeShift + 16)); + float ValR = src.Right / (float)(1 << (SndOutVolumeShift + 16)); - float C = (ValL+ValR)*0.5f; //+15.8 - float S = (ValL-ValR)*0.5f; + float C = (ValL + ValR) * 0.5f; //+15.8 + float S = (ValL - ValR) * 0.5f; - float L=ValL-C; //+15.8 - float R=ValR-C; + float L = ValL - C; //+15.8 + float R = ValR - C; - float SUB = C; - - s32 CX = (s32)(C * AddCLR); // +15.16 + float SUB = C; - s->Left = (s32)(L * GainL ) + CX; // +15.16 = +31, can grow to +32 if (GainL + AddCLR)>255 - s->Right = (s32)(R * GainR ) + CX; - s->Center = (s32)(C * GainC ); // +15.16 = +31 - s->LFE = (s32)(SUB * GainLFE); - s->LeftBack = (s32)(S * GainSL ); - s->RightBack = (s32)(S * GainSR ); + s32 CX = (s32)(C * AddCLR); // +15.16 + + s->Left = (s32)(L * GainL) + CX; // +15.16 = +31, can grow to +32 if (GainL + AddCLR)>255 + s->Right = (s32)(R * GainR) + CX; + s->Center = (s32)(C * GainC); // +15.16 = +31 + s->LFE = (s32)(SUB * GainLFE); + s->LeftBack = (s32)(S * GainSL); + s->RightBack = (s32)(S * GainSR); } -void ProcessDplSample16( const StereoOut32& src, Stereo51Out16Dpl * s) +void ProcessDplSample16(const StereoOut32 &src, Stereo51Out16Dpl *s) { - Stereo51Out32Dpl ss; - ProcessDplSample32(src, &ss); + Stereo51Out32Dpl ss; + ProcessDplSample32(src, &ss); - s->Left = ss.Left >> 16; - s->Right = ss.Right >> 16; - s->Center = ss.Center >> 16; - s->LFE = ss.LFE >> 16; - s->LeftBack = ss.LeftBack >> 16; - s->RightBack = ss.RightBack >> 16; + s->Left = ss.Left >> 16; + s->Right = ss.Right >> 16; + s->Center = ss.Center >> 16; + s->LFE = ss.LFE >> 16; + s->LeftBack = ss.LeftBack >> 16; + s->RightBack = ss.RightBack >> 16; } diff --git a/plugins/spu2-x/src/Global.h b/plugins/spu2-x/src/Global.h index e79d2b520d..fecf1b3d1b 100644 --- a/plugins/spu2-x/src/Global.h +++ b/plugins/spu2-x/src/Global.h @@ -30,7 +30,7 @@ struct V_Core; namespace soundtouch { - class SoundTouch; +class SoundTouch; } #include @@ -47,8 +47,8 @@ namespace soundtouch namespace VersionInfo { - static const u8 Release = 2; - static const u8 Revision = 0; // increase that with each version +static const u8 Release = 2; +static const u8 Revision = 0; // increase that with each version } ////////////////////////////////////////////////////////////////////////// @@ -58,16 +58,16 @@ namespace VersionInfo #undef min #undef max -template< typename T > -static __forceinline void Clampify( T& src, T min, T max ) +template +static __forceinline void Clampify(T &src, T min, T max) { - src = std::min( std::max( src, min ), max ); + src = std::min(std::max(src, min), max); } -template< typename T > -static __forceinline T GetClamped( T src, T min, T max ) +template +static __forceinline T GetClamped(T src, T min, T max) { - return std::min( std::max( src, min ), max ); + return std::min(std::max(src, min), max); } #ifdef __WXMAC__ @@ -83,13 +83,13 @@ extern void SysMessage(const wchar_t *fmt, ...); // Abbreviated macros for dev/debug only consoles and msgboxes. #ifdef PCSX2_DEVBUILD -# define DevMsg MsgBox +#define DevMsg MsgBox #else -# define DevMsg +#define DevMsg #endif #ifdef PCSX2_DEVBUILD -# define SPU2_LOG +#define SPU2_LOG #endif // Uncomment to enable debug keys on numpad (0 to 5) diff --git a/plugins/spu2-x/src/Linux/AboutBox.cpp b/plugins/spu2-x/src/Linux/AboutBox.cpp index d71653af2c..a425a74967 100644 --- a/plugins/spu2-x/src/Linux/AboutBox.cpp +++ b/plugins/spu2-x/src/Linux/AboutBox.cpp @@ -15,9 +15,9 @@ * along with SPU2-X. If not, see . */ - #include "Dialogs.h" +#include "Dialogs.h" void AboutBox() { - SysMessage("Yay: Aboutbox."); + SysMessage("Yay: Aboutbox."); } diff --git a/plugins/spu2-x/src/Linux/Alsa.cpp b/plugins/spu2-x/src/Linux/Alsa.cpp index 107c6e89e7..325a83bf68 100644 --- a/plugins/spu2-x/src/Linux/Alsa.cpp +++ b/plugins/spu2-x/src/Linux/Alsa.cpp @@ -15,7 +15,7 @@ * along with SPU2-X. If not, see . */ - // Adapted from ZeroSPU2 code by Zerofrog. Heavily modified by Arcum42. +// Adapted from ZeroSPU2 code by Zerofrog. Heavily modified by Arcum42. #ifdef __linux__ @@ -24,241 +24,229 @@ #include "Global.h" #include "Alsa.h" #include "SndOut.h" - + // Does not work, except as effectively a null plugin. -class AlsaMod: public SndOutModule +class AlsaMod : public SndOutModule { protected: - static const int PacketsPerBuffer = 1; // increase this if ALSA can't keep up with 512-sample packets - static const int MAX_BUFFER_COUNT = 4; - static const int NumBuffers = 4; // TODO: this should be configurable someday -- lower values reduce latency. - unsigned int pspeed; + static const int PacketsPerBuffer = 1; // increase this if ALSA can't keep up with 512-sample packets + static const int MAX_BUFFER_COUNT = 4; + static const int NumBuffers = 4; // TODO: this should be configurable someday -- lower values reduce latency. + unsigned int pspeed; - snd_pcm_t *handle; - snd_pcm_uframes_t buffer_size; - snd_async_handler_t *pcm_callback; + snd_pcm_t *handle; + snd_pcm_uframes_t buffer_size; + snd_async_handler_t *pcm_callback; - uint period_time; - uint buffer_time; + uint period_time; + uint buffer_time; protected: - // Invoked by the static ExternalCallback method below. - void _InternalCallback() - { - snd_pcm_sframes_t avail; - fprintf(stderr,"* SPU2-X:Iz in your internal callback.\n"); + // Invoked by the static ExternalCallback method below. + void _InternalCallback() + { + snd_pcm_sframes_t avail; + fprintf(stderr, "* SPU2-X:Iz in your internal callback.\n"); - avail = snd_pcm_avail_update( handle ); - while (avail >= (int)period_time ) - { - StereoOut16 buff[PacketsPerBuffer * SndOutPacketSize]; - StereoOut16* p1 = buff; + avail = snd_pcm_avail_update(handle); + while (avail >= (int)period_time) { + StereoOut16 buff[PacketsPerBuffer * SndOutPacketSize]; + StereoOut16 *p1 = buff; - for( int p=0; phandle == snd_async_handler_get_pcm(pcm_call) ); + pxAssume(data != NULL); + //pxAssume( data->handle == snd_async_handler_get_pcm(pcm_call) ); - // Not sure if we just need an assert, or something like this: - if (data->handle != snd_async_handler_get_pcm(pcm_call)) - { - fprintf(stderr,"* SPU2-X: Failed to handle sound.\n"); - return; - } + // Not sure if we just need an assert, or something like this: + if (data->handle != snd_async_handler_get_pcm(pcm_call)) { + fprintf(stderr, "* SPU2-X: Failed to handle sound.\n"); + return; + } - data->_InternalCallback(); - } + data->_InternalCallback(); + } public: + s32 Init() + { + //fprintf(stderr,"* SPU2-X: Initing Alsa\n"); + snd_pcm_hw_params_t *hwparams; + snd_pcm_sw_params_t *swparams; + snd_pcm_status_t *status; + int pchannels = 2; + snd_pcm_format_t format = SND_PCM_FORMAT_S16_LE; - s32 Init() - { - //fprintf(stderr,"* SPU2-X: Initing Alsa\n"); - snd_pcm_hw_params_t *hwparams; - snd_pcm_sw_params_t *swparams; - snd_pcm_status_t *status; - int pchannels = 2; - snd_pcm_format_t format = SND_PCM_FORMAT_S16_LE; + handle = NULL; + pcm_callback = NULL; + pspeed = SAMPLE_RATE; - handle = NULL; - pcm_callback = NULL; - pspeed = SAMPLE_RATE; + // buffer time and period time are in microseconds... + // (don't simplify the equation below -- it'll just cause integer rounding errors. + period_time = (SndOutPacketSize * 1000) / (SampleRate / 1000); + buffer_time = period_time * NumBuffers; - // buffer time and period time are in microseconds... - // (don't simplify the equation below -- it'll just cause integer rounding errors. - period_time = (SndOutPacketSize*1000) / (SampleRate / 1000); - buffer_time = period_time * NumBuffers; + int err; - int err; + err = snd_pcm_open(&handle, "default", SND_PCM_STREAM_PLAYBACK, SND_PCM_ASYNC /*| SND_PCM_NONBLOCK*/); + if (err < 0) { + fprintf(stderr, "Audio open error: %s\n", snd_strerror(err)); + return -1; + } - err = snd_pcm_open(&handle, "default", SND_PCM_STREAM_PLAYBACK, SND_PCM_ASYNC /*| SND_PCM_NONBLOCK*/); - if(err < 0) - { - fprintf(stderr,"Audio open error: %s\n", snd_strerror(err)); - return -1; - } + err = snd_pcm_nonblock(handle, 0); + if (err < 0) { + fprintf(stderr, "Can't set blocking mode: %s\n", snd_strerror(err)); + return -1; + } - err = snd_pcm_nonblock(handle, 0); - if(err < 0) - { - fprintf(stderr,"Can't set blocking mode: %s\n", snd_strerror(err)); - return -1; - } + snd_pcm_hw_params_alloca(&hwparams); + snd_pcm_sw_params_alloca(&swparams); - snd_pcm_hw_params_alloca(&hwparams); - snd_pcm_sw_params_alloca(&swparams); + err = snd_pcm_hw_params_any(handle, hwparams); + if (err < 0) { + fprintf(stderr, "Broken configuration for this PCM: %s\n", snd_strerror(err)); + return -1; + } - err = snd_pcm_hw_params_any(handle, hwparams); - if (err < 0) - { - fprintf(stderr,"Broken configuration for this PCM: %s\n", snd_strerror(err)); - return -1; - } + err = snd_pcm_hw_params_set_access(handle, hwparams, SND_PCM_ACCESS_RW_INTERLEAVED); + if (err < 0) { + fprintf(stderr, "Access type not available: %s\n", snd_strerror(err)); + return -1; + } - err = snd_pcm_hw_params_set_access(handle, hwparams, SND_PCM_ACCESS_RW_INTERLEAVED); - if (err < 0) - { - fprintf(stderr,"Access type not available: %s\n", snd_strerror(err)); - return -1; - } + err = snd_pcm_hw_params_set_format(handle, hwparams, format); + if (err < 0) { + fprintf(stderr, "Sample format not available: %s\n", snd_strerror(err)); + return -1; + } - err = snd_pcm_hw_params_set_format(handle, hwparams, format); - if (err < 0) - { - fprintf(stderr,"Sample format not available: %s\n", snd_strerror(err)); - return -1; - } + err = snd_pcm_hw_params_set_channels(handle, hwparams, pchannels); + if (err < 0) { + fprintf(stderr, "Channels count not available: %s\n", snd_strerror(err)); + return -1; + } + err = snd_pcm_hw_params_set_rate_near(handle, hwparams, &pspeed, 0); + if (err < 0) { + fprintf(stderr, "Rate not available: %s\n", snd_strerror(err)); + return -1; + } - err = snd_pcm_hw_params_set_channels(handle, hwparams, pchannels); - if (err < 0) - { - fprintf(stderr,"Channels count not available: %s\n", snd_strerror(err)); - return -1; - } - err = snd_pcm_hw_params_set_rate_near(handle, hwparams, &pspeed, 0); - if (err < 0) - { - fprintf(stderr,"Rate not available: %s\n", snd_strerror(err)); - return -1; - } + err = snd_pcm_hw_params_set_buffer_time_near(handle, hwparams, &buffer_time, 0); + if (err < 0) { + fprintf(stderr, "Buffer time error: %s\n", snd_strerror(err)); + return -1; + } - err = snd_pcm_hw_params_set_buffer_time_near(handle, hwparams, &buffer_time, 0); - if(err < 0) { - fprintf(stderr,"Buffer time error: %s\n", snd_strerror(err)); - return -1; - } + err = snd_pcm_hw_params_set_period_time_near(handle, hwparams, &period_time, 0); + if (err < 0) { + fprintf(stderr, "Period time error: %s\n", snd_strerror(err)); + return -1; + } - err = snd_pcm_hw_params_set_period_time_near(handle, hwparams, &period_time, 0); - if (err < 0) - { - fprintf(stderr,"Period time error: %s\n", snd_strerror(err)); - return -1; - } + err = snd_pcm_hw_params(handle, hwparams); + if (err < 0) { + fprintf(stderr, "Unable to install hw params: %s\n", snd_strerror(err)); + return -1; + } - err = snd_pcm_hw_params(handle, hwparams); - if (err < 0) - { - fprintf(stderr,"Unable to install hw params: %s\n", snd_strerror(err)); - return -1; - } + snd_pcm_status_alloca(&status); + err = snd_pcm_status(handle, status); + if (err < 0) { + fprintf(stderr, "Unable to get status: %s\n", snd_strerror(err)); + return -1; + } - snd_pcm_status_alloca(&status); - err = snd_pcm_status(handle, status); - if(err < 0) - { - fprintf(stderr,"Unable to get status: %s\n", snd_strerror(err)); - return -1; - } + // Bind our asynchronous callback magic: - // Bind our asynchronous callback magic: + if (handle == NULL) + fprintf(stderr, "No handle."); - if (handle == NULL) fprintf(stderr, "No handle."); - - //fprintf(stderr,"* SPU2-X:Iz setting your internal callback.\n"); - // The external handler never seems to get called after this. - snd_async_add_pcm_handler( &pcm_callback, handle, ExternalCallback, this ); - err = snd_pcm_start( handle ); - if(err < 0) - { - fprintf(stderr,"Pcm start failed: %s\n", snd_strerror(err)); - return -1; - } - // Diagnostic code: - //buffer_size = snd_pcm_status_get_avail(status); - - //fprintf(stderr,"All set up.\n"); - return 0; - } + //fprintf(stderr,"* SPU2-X:Iz setting your internal callback.\n"); + // The external handler never seems to get called after this. + snd_async_add_pcm_handler(&pcm_callback, handle, ExternalCallback, this); + err = snd_pcm_start(handle); + if (err < 0) { + fprintf(stderr, "Pcm start failed: %s\n", snd_strerror(err)); + return -1; + } + // Diagnostic code: + //buffer_size = snd_pcm_status_get_avail(status); - void Close() - { - //fprintf(stderr,"* SPU2-X: Closing Alsa\n"); - if(handle == NULL) return; + //fprintf(stderr,"All set up.\n"); + return 0; + } - snd_pcm_drop(handle); - snd_pcm_close(handle); - handle = NULL; - } + void Close() + { + //fprintf(stderr,"* SPU2-X: Closing Alsa\n"); + if (handle == NULL) + return; - virtual void Configure(uptr parent) - { - } + snd_pcm_drop(handle); + snd_pcm_close(handle); + handle = NULL; + } - virtual bool Is51Out() const { return false; } + virtual void Configure(uptr parent) + { + } - s32 Test() const - { - return 0; - } + virtual bool Is51Out() const { return false; } - int GetEmptySampleCount() - { - if(handle == NULL) - { - fprintf(stderr,"Handle is NULL!\n"); - return 0; - } + s32 Test() const + { + return 0; + } - // Returns the amount of free buffer space, in samples. - int l = snd_pcm_avail_update(handle); - if( l < 0 ) return 0; - return (l / 1000) * (SampleRate / 1000); - } + int GetEmptySampleCount() + { + if (handle == NULL) { + fprintf(stderr, "Handle is NULL!\n"); + return 0; + } - const wchar_t* GetIdent() const - { - return L"Alsa"; - } + // Returns the amount of free buffer space, in samples. + int l = snd_pcm_avail_update(handle); + if (l < 0) + return 0; + return (l / 1000) * (SampleRate / 1000); + } - const wchar_t* GetLongName() const - { - return L"Alsa"; - } + const wchar_t *GetIdent() const + { + return L"Alsa"; + } - void ReadSettings() - { - } + const wchar_t *GetLongName() const + { + return L"Alsa"; + } - void SetApiSettings(wxString api) - { - } + void ReadSettings() + { + } - void WriteSettings() const - { - } + void SetApiSettings(wxString api) + { + } + + void WriteSettings() const + { + } } static Alsa; SndOutModule *AlsaOut = &Alsa; diff --git a/plugins/spu2-x/src/Linux/Alsa.h b/plugins/spu2-x/src/Linux/Alsa.h index 22d5fd02a8..6ed497e68b 100644 --- a/plugins/spu2-x/src/Linux/Alsa.h +++ b/plugins/spu2-x/src/Linux/Alsa.h @@ -15,8 +15,8 @@ * along with SPU2-X. If not, see . */ - #ifndef __LINUX_H__ - #define __LINUX_H__ +#ifndef __LINUX_H__ +#define __LINUX_H__ #include #include @@ -32,11 +32,11 @@ extern int AlsaSetupSound(); extern void AlsaRemoveSound(); extern int AlsaSoundGetBytesBuffered(); -extern void AlsaSoundFeedVoiceData(unsigned char* pSound,long lBytes); +extern void AlsaSoundFeedVoiceData(unsigned char *pSound, long lBytes); extern int SetupSound(); extern void RemoveSound(); extern int SoundGetBytesBuffered(); -extern void SoundFeedVoiceData(unsigned char* pSound,long lBytes); +extern void SoundFeedVoiceData(unsigned char *pSound, long lBytes); -#endif // __LINUX_H__ +#endif // __LINUX_H__ diff --git a/plugins/spu2-x/src/Linux/CfgHelpers.cpp b/plugins/spu2-x/src/Linux/CfgHelpers.cpp index f326dbdfa0..eaebc075fa 100644 --- a/plugins/spu2-x/src/Linux/CfgHelpers.cpp +++ b/plugins/spu2-x/src/Linux/CfgHelpers.cpp @@ -15,93 +15,94 @@ * along with SPU2-X. If not, see . */ - #include "Dialogs.h" - #include +#include "Dialogs.h" +#include - wxFileConfig *spuConfig = NULL; - wxString path(L"~/.pcsx2/inis/spu2-x.ini"); - bool pathSet = false; +wxFileConfig *spuConfig = NULL; +wxString path(L"~/.pcsx2/inis/spu2-x.ini"); +bool pathSet = false; void initIni() { - if (spuConfig == NULL) spuConfig = new wxFileConfig(L"", L"", path, L"", wxCONFIG_USE_LOCAL_FILE); + if (spuConfig == NULL) + spuConfig = new wxFileConfig(L"", L"", path, L"", wxCONFIG_USE_LOCAL_FILE); } -void setIni(const wchar_t* Section) - { - initIni(); - spuConfig->SetPath(wxsFormat(L"/%s", Section)); - } - -void CfgSetSettingsDir(const char* dir) +void setIni(const wchar_t *Section) { - FileLog("CfgSetSettingsDir(%s)\n", dir); - path = wxString::FromAscii(dir) + L"/spu2-x.ini"; - pathSet = true; + initIni(); + spuConfig->SetPath(wxsFormat(L"/%s", Section)); } -void CfgWriteBool(const wchar_t* Section, const wchar_t* Name, bool Value) +void CfgSetSettingsDir(const char *dir) { - setIni(Section); - spuConfig->Write(Name, Value); + FileLog("CfgSetSettingsDir(%s)\n", dir); + path = wxString::FromAscii(dir) + L"/spu2-x.ini"; + pathSet = true; } -void CfgWriteInt(const wchar_t* Section, const wchar_t* Name, int Value) +void CfgWriteBool(const wchar_t *Section, const wchar_t *Name, bool Value) { - setIni(Section); - spuConfig->Write(Name, Value); + setIni(Section); + spuConfig->Write(Name, Value); } -void CfgWriteFloat(const wchar_t* Section, const wchar_t* Name, float Value) +void CfgWriteInt(const wchar_t *Section, const wchar_t *Name, int Value) { - setIni(Section); - spuConfig->Write(Name, (double)Value); + setIni(Section); + spuConfig->Write(Name, Value); } -void CfgWriteStr(const wchar_t* Section, const wchar_t* Name, const wxString& Data) +void CfgWriteFloat(const wchar_t *Section, const wchar_t *Name, float Value) { - setIni(Section); - spuConfig->Write(Name, Data); + setIni(Section); + spuConfig->Write(Name, (double)Value); } -bool CfgReadBool(const wchar_t *Section,const wchar_t* Name, bool Default) +void CfgWriteStr(const wchar_t *Section, const wchar_t *Name, const wxString &Data) { - bool ret; - - setIni(Section); - spuConfig->Read(Name, &ret, Default); - - return ret; + setIni(Section); + spuConfig->Write(Name, Data); } -int CfgReadInt(const wchar_t* Section, const wchar_t* Name,int Default) +bool CfgReadBool(const wchar_t *Section, const wchar_t *Name, bool Default) { - int ret; + bool ret; - setIni(Section); - spuConfig->Read(Name, &ret, Default); + setIni(Section); + spuConfig->Read(Name, &ret, Default); - return ret; + return ret; } -float CfgReadFloat(const wchar_t* Section, const wchar_t* Name, float Default) +int CfgReadInt(const wchar_t *Section, const wchar_t *Name, int Default) { - double ret; + int ret; - setIni(Section); - spuConfig->Read(Name, &ret, (double)Default); + setIni(Section); + spuConfig->Read(Name, &ret, Default); - return (float)ret; + return ret; } -void CfgReadStr(const wchar_t* Section, const wchar_t* Name, wchar_t* Data, int DataSize, const wchar_t* Default) +float CfgReadFloat(const wchar_t *Section, const wchar_t *Name, float Default) { - setIni(Section); - wcscpy(Data, spuConfig->Read(Name, Default).wc_str()); + double ret; + + setIni(Section); + spuConfig->Read(Name, &ret, (double)Default); + + return (float)ret; } -void CfgReadStr(const wchar_t* Section, const wchar_t* Name, wxString& Data, const wchar_t* Default) +void CfgReadStr(const wchar_t *Section, const wchar_t *Name, wchar_t *Data, int DataSize, const wchar_t *Default) { - setIni(Section); - Data = spuConfig->Read(Name, Default); + setIni(Section); + wcscpy(Data, spuConfig->Read(Name, Default).wc_str()); +} + +void CfgReadStr(const wchar_t *Section, const wchar_t *Name, wxString &Data, const wchar_t *Default) +{ + setIni(Section); + Data = spuConfig->Read(Name, Default); } diff --git a/plugins/spu2-x/src/Linux/Config.cpp b/plugins/spu2-x/src/Linux/Config.cpp index e6d766168e..14247b6245 100644 --- a/plugins/spu2-x/src/Linux/Config.cpp +++ b/plugins/spu2-x/src/Linux/Config.cpp @@ -32,7 +32,7 @@ static const int LATENCY_MAX = 750; static const int LATENCY_MIN = 15; -int AutoDMAPlayRate[2] = {0,0}; +int AutoDMAPlayRate[2] = {0, 0}; // Default settings. @@ -47,9 +47,9 @@ int Interpolation = 4; */ bool EffectsDisabled = false; -float FinalVolume; // global +float FinalVolume; // global bool AdvancedVolumeControl; -float VolumeAdjustFLdb; // decibels settings, cos audiophiles love that +float VolumeAdjustFLdb; // decibels settings, cos audiophiles love that float VolumeAdjustCdb; float VolumeAdjustFRdb; float VolumeAdjustBLdb; @@ -57,7 +57,7 @@ float VolumeAdjustBRdb; float VolumeAdjustSLdb; float VolumeAdjustSRdb; float VolumeAdjustLFEdb; -float VolumeAdjustFL; // linear coefs calcualted from decibels, +float VolumeAdjustFL; // linear coefs calcualted from decibels, float VolumeAdjustC; float VolumeAdjustFR; float VolumeAdjustBL; @@ -69,12 +69,12 @@ unsigned int delayCycles; bool postprocess_filter_enabled = true; bool postprocess_filter_dealias = false; -bool _visual_debug_enabled = false; // windows only feature +bool _visual_debug_enabled = false; // windows only feature // OUTPUT u32 OutputModule = 0; int SndOutLatencyMS = 300; -int SynchMode = 0; // Time Stretch, Async or Disabled +int SynchMode = 0; // Time Stretch, Async or Disabled static u32 OutputAPI = 0; static u32 SdlOutputAPI = 0; @@ -84,135 +84,138 @@ int dplLevel = 0; void ReadSettings() { - // For some reason this can be called before we know what ini file we're writing to. - // Lets not try to read it if that happens. - if (!pathSet) - { - FileLog("Read called without the path set.\n"); - return; - } - - Interpolation = CfgReadInt( L"MIXING",L"Interpolation", 4 ); - EffectsDisabled = CfgReadBool( L"MIXING", L"Disable_Effects", false ); - postprocess_filter_dealias = CfgReadBool( L"MIXING", L"DealiasFilter", false ); - FinalVolume = ((float)CfgReadInt( L"MIXING", L"FinalVolume", 100 )) / 100; - if ( FinalVolume > 1.0f) FinalVolume = 1.0f; + // For some reason this can be called before we know what ini file we're writing to. + // Lets not try to read it if that happens. + if (!pathSet) { + FileLog("Read called without the path set.\n"); + return; + } - AdvancedVolumeControl = CfgReadBool(L"MIXING", L"AdvancedVolumeControl", false); - VolumeAdjustCdb = CfgReadFloat(L"MIXING", L"VolumeAdjustC(dB)", 0); - VolumeAdjustFLdb = CfgReadFloat(L"MIXING", L"VolumeAdjustFL(dB)", 0); - VolumeAdjustFRdb = CfgReadFloat(L"MIXING", L"VolumeAdjustFR(dB)", 0); - VolumeAdjustBLdb = CfgReadFloat(L"MIXING", L"VolumeAdjustBL(dB)", 0); - VolumeAdjustBRdb = CfgReadFloat(L"MIXING", L"VolumeAdjustBR(dB)", 0); - VolumeAdjustSLdb = CfgReadFloat(L"MIXING", L"VolumeAdjustSL(dB)", 0); - VolumeAdjustSRdb = CfgReadFloat(L"MIXING", L"VolumeAdjustSR(dB)", 0); - VolumeAdjustLFEdb = CfgReadFloat(L"MIXING", L"VolumeAdjustLFE(dB)", 0); - VolumeAdjustC = powf(10, VolumeAdjustCdb / 10); - VolumeAdjustFL = powf(10, VolumeAdjustFLdb / 10); - VolumeAdjustFR = powf(10, VolumeAdjustFRdb / 10); - VolumeAdjustBL = powf(10, VolumeAdjustBLdb / 10); - VolumeAdjustBR = powf(10, VolumeAdjustBRdb / 10); - VolumeAdjustSL = powf(10, VolumeAdjustSLdb / 10); - VolumeAdjustSR = powf(10, VolumeAdjustSRdb / 10); - VolumeAdjustLFE = powf(10, VolumeAdjustLFEdb / 10); - delayCycles = CfgReadInt(L"DEBUG", L"DelayCycles", 4); + Interpolation = CfgReadInt(L"MIXING", L"Interpolation", 4); + EffectsDisabled = CfgReadBool(L"MIXING", L"Disable_Effects", false); + postprocess_filter_dealias = CfgReadBool(L"MIXING", L"DealiasFilter", false); + FinalVolume = ((float)CfgReadInt(L"MIXING", L"FinalVolume", 100)) / 100; + if (FinalVolume > 1.0f) + FinalVolume = 1.0f; + + AdvancedVolumeControl = CfgReadBool(L"MIXING", L"AdvancedVolumeControl", false); + VolumeAdjustCdb = CfgReadFloat(L"MIXING", L"VolumeAdjustC(dB)", 0); + VolumeAdjustFLdb = CfgReadFloat(L"MIXING", L"VolumeAdjustFL(dB)", 0); + VolumeAdjustFRdb = CfgReadFloat(L"MIXING", L"VolumeAdjustFR(dB)", 0); + VolumeAdjustBLdb = CfgReadFloat(L"MIXING", L"VolumeAdjustBL(dB)", 0); + VolumeAdjustBRdb = CfgReadFloat(L"MIXING", L"VolumeAdjustBR(dB)", 0); + VolumeAdjustSLdb = CfgReadFloat(L"MIXING", L"VolumeAdjustSL(dB)", 0); + VolumeAdjustSRdb = CfgReadFloat(L"MIXING", L"VolumeAdjustSR(dB)", 0); + VolumeAdjustLFEdb = CfgReadFloat(L"MIXING", L"VolumeAdjustLFE(dB)", 0); + VolumeAdjustC = powf(10, VolumeAdjustCdb / 10); + VolumeAdjustFL = powf(10, VolumeAdjustFLdb / 10); + VolumeAdjustFR = powf(10, VolumeAdjustFRdb / 10); + VolumeAdjustBL = powf(10, VolumeAdjustBLdb / 10); + VolumeAdjustBR = powf(10, VolumeAdjustBRdb / 10); + VolumeAdjustSL = powf(10, VolumeAdjustSLdb / 10); + VolumeAdjustSR = powf(10, VolumeAdjustSRdb / 10); + VolumeAdjustLFE = powf(10, VolumeAdjustLFEdb / 10); + delayCycles = CfgReadInt(L"DEBUG", L"DelayCycles", 4); - wxString temp; - CfgReadStr( L"OUTPUT", L"Output_Module", temp, PortaudioOut->GetIdent() ); - OutputModule = FindOutputModuleById( temp.c_str() );// find the driver index of this module + wxString temp; + CfgReadStr(L"OUTPUT", L"Output_Module", temp, PortaudioOut->GetIdent()); + OutputModule = FindOutputModuleById(temp.c_str()); // find the driver index of this module - // find current API +// find current API #ifdef __linux__ - CfgReadStr( L"PORTAUDIO", L"HostApi", temp, L"ALSA" ); - OutputAPI = -1; - if (temp == L"ALSA") OutputAPI = 0; - if (temp == L"OSS") OutputAPI = 1; - if (temp == L"JACK") OutputAPI = 2; + CfgReadStr(L"PORTAUDIO", L"HostApi", temp, L"ALSA"); + OutputAPI = -1; + if (temp == L"ALSA") + OutputAPI = 0; + if (temp == L"OSS") + OutputAPI = 1; + if (temp == L"JACK") + OutputAPI = 2; #else - CfgReadStr( L"PORTAUDIO", L"HostApi", temp, L"OSS" ); - OutputAPI = -1; + CfgReadStr(L"PORTAUDIO", L"HostApi", temp, L"OSS"); + OutputAPI = -1; - if (temp == L"OSS") OutputAPI = 0; + if (temp == L"OSS") + OutputAPI = 0; #endif #ifdef __linux__ - CfgReadStr( L"SDL", L"HostApi", temp, L"pulseaudio" ); - SdlOutputAPI = -1; + CfgReadStr(L"SDL", L"HostApi", temp, L"pulseaudio"); + SdlOutputAPI = -1; #if SDL_MAJOR_VERSION >= 2 - // YES It sucks ... - for (int i = 0; i < SDL_GetNumAudioDrivers(); ++i) { - if (!temp.Cmp(wxString(SDL_GetAudioDriver(i), wxConvUTF8))) - SdlOutputAPI = i; - } + // YES It sucks ... + for (int i = 0; i < SDL_GetNumAudioDrivers(); ++i) { + if (!temp.Cmp(wxString(SDL_GetAudioDriver(i), wxConvUTF8))) + SdlOutputAPI = i; + } #endif #endif - SndOutLatencyMS = CfgReadInt(L"OUTPUT",L"Latency", 300); - SynchMode = CfgReadInt( L"OUTPUT", L"Synch_Mode", 0); + SndOutLatencyMS = CfgReadInt(L"OUTPUT", L"Latency", 300); + SynchMode = CfgReadInt(L"OUTPUT", L"Synch_Mode", 0); - PortaudioOut->ReadSettings(); + PortaudioOut->ReadSettings(); #ifdef __linux__ - SDLOut->ReadSettings(); + SDLOut->ReadSettings(); #endif - SoundtouchCfg::ReadSettings(); - DebugConfig::ReadSettings(); + SoundtouchCfg::ReadSettings(); + DebugConfig::ReadSettings(); - // Sanity Checks - // ------------- + // Sanity Checks + // ------------- - Clampify( SndOutLatencyMS, LATENCY_MIN, LATENCY_MAX ); + Clampify(SndOutLatencyMS, LATENCY_MIN, LATENCY_MAX); - WriteSettings(); - spuConfig->Flush(); + WriteSettings(); + spuConfig->Flush(); } /*****************************************************************************/ void WriteSettings() { - if (!pathSet) - { - FileLog("Write called without the path set.\n"); - return; - } + if (!pathSet) { + FileLog("Write called without the path set.\n"); + return; + } - CfgWriteInt(L"MIXING",L"Interpolation",Interpolation); - CfgWriteBool(L"MIXING",L"Disable_Effects",EffectsDisabled); - CfgWriteBool(L"MIXING",L"DealiasFilter",postprocess_filter_dealias); - CfgWriteInt(L"MIXING",L"FinalVolume",(int)(FinalVolume * 100 +0.5f)); + CfgWriteInt(L"MIXING", L"Interpolation", Interpolation); + CfgWriteBool(L"MIXING", L"Disable_Effects", EffectsDisabled); + CfgWriteBool(L"MIXING", L"DealiasFilter", postprocess_filter_dealias); + CfgWriteInt(L"MIXING", L"FinalVolume", (int)(FinalVolume * 100 + 0.5f)); - CfgWriteBool(L"MIXING", L"AdvancedVolumeControl", AdvancedVolumeControl); - CfgWriteFloat(L"MIXING", L"VolumeAdjustC(dB)", VolumeAdjustCdb); - CfgWriteFloat(L"MIXING", L"VolumeAdjustFL(dB)", VolumeAdjustFLdb); - CfgWriteFloat(L"MIXING", L"VolumeAdjustFR(dB)", VolumeAdjustFRdb); - CfgWriteFloat(L"MIXING", L"VolumeAdjustBL(dB)", VolumeAdjustBLdb); - CfgWriteFloat(L"MIXING", L"VolumeAdjustBR(dB)", VolumeAdjustBRdb); - CfgWriteFloat(L"MIXING", L"VolumeAdjustSL(dB)", VolumeAdjustSLdb); - CfgWriteFloat(L"MIXING", L"VolumeAdjustSR(dB)", VolumeAdjustSRdb); - CfgWriteFloat(L"MIXING", L"VolumeAdjustLFE(dB)", VolumeAdjustLFEdb); + CfgWriteBool(L"MIXING", L"AdvancedVolumeControl", AdvancedVolumeControl); + CfgWriteFloat(L"MIXING", L"VolumeAdjustC(dB)", VolumeAdjustCdb); + CfgWriteFloat(L"MIXING", L"VolumeAdjustFL(dB)", VolumeAdjustFLdb); + CfgWriteFloat(L"MIXING", L"VolumeAdjustFR(dB)", VolumeAdjustFRdb); + CfgWriteFloat(L"MIXING", L"VolumeAdjustBL(dB)", VolumeAdjustBLdb); + CfgWriteFloat(L"MIXING", L"VolumeAdjustBR(dB)", VolumeAdjustBRdb); + CfgWriteFloat(L"MIXING", L"VolumeAdjustSL(dB)", VolumeAdjustSLdb); + CfgWriteFloat(L"MIXING", L"VolumeAdjustSR(dB)", VolumeAdjustSRdb); + CfgWriteFloat(L"MIXING", L"VolumeAdjustLFE(dB)", VolumeAdjustLFEdb); - CfgWriteStr(L"OUTPUT",L"Output_Module", mods[OutputModule]->GetIdent() ); - CfgWriteInt(L"OUTPUT",L"Latency", SndOutLatencyMS); - CfgWriteInt(L"OUTPUT",L"Synch_Mode", SynchMode); - CfgWriteInt(L"DEBUG", L"DelayCycles", delayCycles); + CfgWriteStr(L"OUTPUT", L"Output_Module", mods[OutputModule]->GetIdent()); + CfgWriteInt(L"OUTPUT", L"Latency", SndOutLatencyMS); + CfgWriteInt(L"OUTPUT", L"Synch_Mode", SynchMode); + CfgWriteInt(L"DEBUG", L"DelayCycles", delayCycles); - PortaudioOut->WriteSettings(); + PortaudioOut->WriteSettings(); #ifdef __linux__ - SDLOut->WriteSettings(); + SDLOut->WriteSettings(); #endif - SoundtouchCfg::WriteSettings(); - DebugConfig::WriteSettings(); + SoundtouchCfg::WriteSettings(); + DebugConfig::WriteSettings(); } void advanced_dialog() { - SoundtouchCfg::DisplayDialog(); + SoundtouchCfg::DisplayDialog(); } void debug_dialog() { - DebugConfig::DisplayDialog(); + DebugConfig::DisplayDialog(); } #if defined(__unix__) @@ -241,16 +244,16 @@ void DisplayDialog() GtkWidget *advanced_button; /* Create the widgets */ - dialog = gtk_dialog_new_with_buttons ( - "SPU2-X Config", - NULL, /* parent window*/ - (GtkDialogFlags)(GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT), - "OK", GTK_RESPONSE_ACCEPT, - "Cancel", GTK_RESPONSE_REJECT, - NULL); + dialog = gtk_dialog_new_with_buttons( + "SPU2-X Config", + NULL, /* parent window*/ + (GtkDialogFlags)(GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT), + "OK", GTK_RESPONSE_ACCEPT, + "Cancel", GTK_RESPONSE_REJECT, + NULL); - int_label = gtk_label_new ("Interpolation:"); - int_box = gtk_combo_box_text_new (); + int_label = gtk_label_new("Interpolation:"); + int_box = gtk_combo_box_text_new(); gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(int_box), "0 - Nearest (fastest/bad quality)"); gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(int_box), "1 - Linear (simple/okay sound)"); gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(int_box), "2 - Cubic (artificial highs)"); @@ -262,10 +265,10 @@ void DisplayDialog() dealias_filter = gtk_check_button_new_with_label("Use the de-alias filter (overemphasizes the highs)"); debug_check = gtk_check_button_new_with_label("Enable Debug Options"); - debug_button = gtk_button_new_with_label("Debug..."); + debug_button = gtk_button_new_with_label("Debug..."); - mod_label = gtk_label_new ("Module:"); - mod_box = gtk_combo_box_text_new (); + mod_label = gtk_label_new("Module:"); + mod_box = gtk_combo_box_text_new(); gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(mod_box), "0 - No Sound (emulate SPU2 only)"); gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(mod_box), "1 - PortAudio (cross-platform)"); #ifdef __linux__ @@ -274,10 +277,10 @@ void DisplayDialog() //gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(mod_box), "3 - Alsa (probably doesn't work)"); gtk_combo_box_set_active(GTK_COMBO_BOX(mod_box), OutputModule); - api_label = gtk_label_new ("PortAudio API:"); - api_box = gtk_combo_box_text_new (); + api_label = gtk_label_new("PortAudio API:"); + api_box = gtk_combo_box_text_new(); #ifdef __linux__ - // In order to keep it the menu light, I only put linux major api + // In order to keep it the menu light, I only put linux major api gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(api_box), "0 - ALSA (recommended)"); gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(api_box), "1 - OSS (legacy)"); gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(api_box), "2 - JACK"); @@ -287,8 +290,8 @@ void DisplayDialog() gtk_combo_box_set_active(GTK_COMBO_BOX(api_box), OutputAPI); #if SDL_MAJOR_VERSION >= 2 - sdl_api_label = gtk_label_new ("SDL API:"); - sdl_api_box = gtk_combo_box_text_new (); + sdl_api_label = gtk_label_new("SDL API:"); + sdl_api_box = gtk_combo_box_text_new(); // YES It sucks ... for (int i = 0; i < SDL_GetNumAudioDrivers(); ++i) { gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(sdl_api_box), SDL_GetAudioDriver(i)); @@ -296,7 +299,7 @@ void DisplayDialog() gtk_combo_box_set_active(GTK_COMBO_BOX(sdl_api_box), SdlOutputAPI); #endif - latency_label = gtk_label_new ("Latency:"); + latency_label = gtk_label_new("Latency:"); #if GTK_MAJOR_VERSION < 3 latency_slide = gtk_hscale_new_with_range(LATENCY_MIN, LATENCY_MAX, 5); #else @@ -304,123 +307,131 @@ void DisplayDialog() #endif gtk_range_set_value(GTK_RANGE(latency_slide), SndOutLatencyMS); - sync_label = gtk_label_new ("Synchronization Mode:"); - sync_box = gtk_combo_box_text_new (); + sync_label = gtk_label_new("Synchronization Mode:"); + sync_box = gtk_combo_box_text_new(); gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(sync_box), "TimeStretch (Recommended)"); gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(sync_box), "Async Mix (Breaks some games!)"); gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(sync_box), "None (Audio can skip.)"); gtk_combo_box_set_active(GTK_COMBO_BOX(sync_box), SynchMode); - advanced_button = gtk_button_new_with_label("Advanced..."); + advanced_button = gtk_button_new_with_label("Advanced..."); main_box = gtk_hbox_new(false, 5); - main_frame = gtk_frame_new ("SPU2-X Config"); - gtk_container_add (GTK_CONTAINER(main_frame), main_box); + main_frame = gtk_frame_new("SPU2-X Config"); + gtk_container_add(GTK_CONTAINER(main_frame), main_box); mixing_box = gtk_vbox_new(false, 5); - mixing_frame = gtk_frame_new ("Mixing Settings:"); - gtk_container_add (GTK_CONTAINER(mixing_frame), mixing_box); + mixing_frame = gtk_frame_new("Mixing Settings:"); + gtk_container_add(GTK_CONTAINER(mixing_frame), mixing_box); output_box = gtk_vbox_new(false, 5); - output_frame = gtk_frame_new ("Output Settings:"); - gtk_container_add (GTK_CONTAINER(output_frame), output_box); + output_frame = gtk_frame_new("Output Settings:"); + gtk_container_add(GTK_CONTAINER(output_frame), output_box); - gtk_container_add(GTK_CONTAINER(mixing_box), int_label); - gtk_container_add(GTK_CONTAINER(mixing_box), int_box); - gtk_container_add(GTK_CONTAINER(mixing_box), effects_check); - gtk_container_add(GTK_CONTAINER(mixing_box), dealias_filter); - gtk_container_add(GTK_CONTAINER(mixing_box), debug_check); - gtk_container_add(GTK_CONTAINER(mixing_box), debug_button); + gtk_container_add(GTK_CONTAINER(mixing_box), int_label); + gtk_container_add(GTK_CONTAINER(mixing_box), int_box); + gtk_container_add(GTK_CONTAINER(mixing_box), effects_check); + gtk_container_add(GTK_CONTAINER(mixing_box), dealias_filter); + gtk_container_add(GTK_CONTAINER(mixing_box), debug_check); + gtk_container_add(GTK_CONTAINER(mixing_box), debug_button); - gtk_container_add(GTK_CONTAINER(output_box), mod_label); - gtk_container_add(GTK_CONTAINER(output_box), mod_box); - gtk_container_add(GTK_CONTAINER(output_box), api_label); - gtk_container_add(GTK_CONTAINER(output_box), api_box); + gtk_container_add(GTK_CONTAINER(output_box), mod_label); + gtk_container_add(GTK_CONTAINER(output_box), mod_box); + gtk_container_add(GTK_CONTAINER(output_box), api_label); + gtk_container_add(GTK_CONTAINER(output_box), api_box); #if SDL_MAJOR_VERSION >= 2 - gtk_container_add(GTK_CONTAINER(output_box), sdl_api_label); - gtk_container_add(GTK_CONTAINER(output_box), sdl_api_box); + gtk_container_add(GTK_CONTAINER(output_box), sdl_api_label); + gtk_container_add(GTK_CONTAINER(output_box), sdl_api_box); #endif - gtk_container_add(GTK_CONTAINER(output_box), sync_label); - gtk_container_add(GTK_CONTAINER(output_box), sync_box); - gtk_container_add(GTK_CONTAINER(output_box), latency_label); - gtk_container_add(GTK_CONTAINER(output_box), latency_slide); - gtk_container_add(GTK_CONTAINER(output_box), advanced_button); + gtk_container_add(GTK_CONTAINER(output_box), sync_label); + gtk_container_add(GTK_CONTAINER(output_box), sync_box); + gtk_container_add(GTK_CONTAINER(output_box), latency_label); + gtk_container_add(GTK_CONTAINER(output_box), latency_slide); + gtk_container_add(GTK_CONTAINER(output_box), advanced_button); - gtk_container_add(GTK_CONTAINER(main_box), mixing_frame); - gtk_container_add(GTK_CONTAINER(main_box), output_frame); + gtk_container_add(GTK_CONTAINER(main_box), mixing_frame); + gtk_container_add(GTK_CONTAINER(main_box), output_frame); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(effects_check), EffectsDisabled); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(dealias_filter), postprocess_filter_dealias); - //FinalVolume; + //FinalVolume; gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(debug_check), DebugEnabled); - gtk_container_add (GTK_CONTAINER(gtk_dialog_get_content_area(GTK_DIALOG(dialog))), main_frame); - gtk_widget_show_all (dialog); + gtk_container_add(GTK_CONTAINER(gtk_dialog_get_content_area(GTK_DIALOG(dialog))), main_frame); + gtk_widget_show_all(dialog); g_signal_connect_swapped(advanced_button, "clicked", G_CALLBACK(advanced_dialog), advanced_button); g_signal_connect_swapped(debug_button, "clicked", G_CALLBACK(debug_dialog), debug_button); - return_value = gtk_dialog_run (GTK_DIALOG (dialog)); + return_value = gtk_dialog_run(GTK_DIALOG(dialog)); - if (return_value == GTK_RESPONSE_ACCEPT) - { - DebugEnabled = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(debug_check)); - postprocess_filter_dealias = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(dealias_filter)); - if (gtk_combo_box_get_active(GTK_COMBO_BOX(int_box)) != -1) - Interpolation = gtk_combo_box_get_active(GTK_COMBO_BOX(int_box)); + if (return_value == GTK_RESPONSE_ACCEPT) { + DebugEnabled = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(debug_check)); + postprocess_filter_dealias = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(dealias_filter)); + if (gtk_combo_box_get_active(GTK_COMBO_BOX(int_box)) != -1) + Interpolation = gtk_combo_box_get_active(GTK_COMBO_BOX(int_box)); - EffectsDisabled = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(effects_check)); - //FinalVolume; + EffectsDisabled = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(effects_check)); + //FinalVolume; - if (gtk_combo_box_get_active(GTK_COMBO_BOX(mod_box)) != -1) - OutputModule = gtk_combo_box_get_active(GTK_COMBO_BOX(mod_box)); + if (gtk_combo_box_get_active(GTK_COMBO_BOX(mod_box)) != -1) + OutputModule = gtk_combo_box_get_active(GTK_COMBO_BOX(mod_box)); - if (gtk_combo_box_get_active(GTK_COMBO_BOX(api_box)) != -1) { - OutputAPI = gtk_combo_box_get_active(GTK_COMBO_BOX(api_box)); + if (gtk_combo_box_get_active(GTK_COMBO_BOX(api_box)) != -1) { + OutputAPI = gtk_combo_box_get_active(GTK_COMBO_BOX(api_box)); #ifdef __linux__ - switch(OutputAPI) { - case 0: PortaudioOut->SetApiSettings(L"ALSA"); break; - case 1: PortaudioOut->SetApiSettings(L"OSS"); break; - case 2: PortaudioOut->SetApiSettings(L"JACK"); break; - default: PortaudioOut->SetApiSettings(L"Unknown"); - } + switch (OutputAPI) { + case 0: + PortaudioOut->SetApiSettings(L"ALSA"); + break; + case 1: + PortaudioOut->SetApiSettings(L"OSS"); + break; + case 2: + PortaudioOut->SetApiSettings(L"JACK"); + break; + default: + PortaudioOut->SetApiSettings(L"Unknown"); + } #else - switch(OutputAPI) { - case 0: PortaudioOut->SetApiSettings(L"OSS"); break; - default: PortaudioOut->SetApiSettings(L"Unknown"); - } + switch (OutputAPI) { + case 0: + PortaudioOut->SetApiSettings(L"OSS"); + break; + default: + PortaudioOut->SetApiSettings(L"Unknown"); + } #endif - } + } #if SDL_MAJOR_VERSION >= 2 - if (gtk_combo_box_get_active(GTK_COMBO_BOX(sdl_api_box)) != -1) { - SdlOutputAPI = gtk_combo_box_get_active(GTK_COMBO_BOX(sdl_api_box)); - // YES It sucks ... - SDLOut->SetApiSettings(wxString(SDL_GetAudioDriver(SdlOutputAPI), wxConvUTF8)); - } + if (gtk_combo_box_get_active(GTK_COMBO_BOX(sdl_api_box)) != -1) { + SdlOutputAPI = gtk_combo_box_get_active(GTK_COMBO_BOX(sdl_api_box)); + // YES It sucks ... + SDLOut->SetApiSettings(wxString(SDL_GetAudioDriver(SdlOutputAPI), wxConvUTF8)); + } #endif - SndOutLatencyMS = gtk_range_get_value(GTK_RANGE(latency_slide)); - - if (gtk_combo_box_get_active(GTK_COMBO_BOX(sync_box)) != -1) - SynchMode = gtk_combo_box_get_active(GTK_COMBO_BOX(sync_box)); + SndOutLatencyMS = gtk_range_get_value(GTK_RANGE(latency_slide)); + + if (gtk_combo_box_get_active(GTK_COMBO_BOX(sync_box)) != -1) + SynchMode = gtk_combo_box_get_active(GTK_COMBO_BOX(sync_box)); } - gtk_widget_destroy (dialog); + gtk_widget_destroy(dialog); } #else void DisplayDialog() { - } #endif void configure() { - initIni(); - ReadSettings(); - DisplayDialog(); - WriteSettings(); - delete spuConfig; - spuConfig = NULL; + initIni(); + ReadSettings(); + DisplayDialog(); + WriteSettings(); + delete spuConfig; + spuConfig = NULL; } diff --git a/plugins/spu2-x/src/Linux/Config.h b/plugins/spu2-x/src/Linux/Config.h index 28e015ee94..077153931f 100644 --- a/plugins/spu2-x/src/Linux/Config.h +++ b/plugins/spu2-x/src/Linux/Config.h @@ -82,16 +82,16 @@ extern u32 OutputModule; extern int SndOutLatencyMS; extern wchar_t dspPlugin[]; -extern int dspPluginModule; +extern int dspPluginModule; -extern bool dspPluginEnabled; +extern bool dspPluginEnabled; extern int SynchMode; namespace SoundtouchCfg { - void ReadSettings(); - void WriteSettings(); - void DisplayDialog(); +void ReadSettings(); +void WriteSettings(); +void DisplayDialog(); }; void ReadSettings(); @@ -101,4 +101,4 @@ void AboutBox(); extern wxFileConfig *spuConfig; extern bool pathSet; extern void initIni(); -#endif // CONFIG_H_INCLUDED +#endif // CONFIG_H_INCLUDED diff --git a/plugins/spu2-x/src/Linux/ConfigDebug.cpp b/plugins/spu2-x/src/Linux/ConfigDebug.cpp index bdc5449bef..ed8eeb7850 100644 --- a/plugins/spu2-x/src/Linux/ConfigDebug.cpp +++ b/plugins/spu2-x/src/Linux/ConfigDebug.cpp @@ -20,22 +20,22 @@ #include "Config.h" #include "Utilities/Path.h" -bool DebugEnabled=false; -bool _MsgToConsole=false; -bool _MsgKeyOnOff=false; -bool _MsgVoiceOff=false; -bool _MsgDMA=false; -bool _MsgAutoDMA=false; -bool _MsgOverruns=false; -bool _MsgCache=false; +bool DebugEnabled = false; +bool _MsgToConsole = false; +bool _MsgKeyOnOff = false; +bool _MsgVoiceOff = false; +bool _MsgDMA = false; +bool _MsgAutoDMA = false; +bool _MsgOverruns = false; +bool _MsgCache = false; -bool _AccessLog=false; -bool _DMALog=false; -bool _WaveLog=false; +bool _AccessLog = false; +bool _DMALog = false; +bool _WaveLog = false; -bool _CoresDump=false; -bool _MemDump=false; -bool _RegDump=false; +bool _CoresDump = false; +bool _MemDump = false; +bool _RegDump = false; // this is set true if PCSX2 invokes the SetLogDir callback, which tells SPU2-X to use that over // the configured crap in the ini file. @@ -53,105 +53,105 @@ wxString CoresDumpFileName; wxString MemDumpFileName; wxString RegDumpFileName; -void CfgSetLogDir( const char* dir ) +void CfgSetLogDir(const char *dir) { - LogsFolder = (dir==NULL) ? wxString(L"logs") : fromUTF8(dir); - DumpsFolder = (dir==NULL) ? wxString(L"logs") : fromUTF8(dir); - LogLocationSetByPcsx2 = (dir!=NULL); + LogsFolder = (dir == NULL) ? wxString(L"logs") : fromUTF8(dir); + DumpsFolder = (dir == NULL) ? wxString(L"logs") : fromUTF8(dir); + LogLocationSetByPcsx2 = (dir != NULL); } -FILE* OpenBinaryLog( const wxString& logfile ) +FILE *OpenBinaryLog(const wxString &logfile) { - return wxFopen( Path::Combine(LogsFolder, logfile), L"wb" ); + return wxFopen(Path::Combine(LogsFolder, logfile), L"wb"); } -FILE* OpenLog( const wxString& logfile ) +FILE *OpenLog(const wxString &logfile) { - return wxFopen( Path::Combine(LogsFolder, logfile), L"w" ); + return wxFopen(Path::Combine(LogsFolder, logfile), L"w"); } -FILE* OpenDump( const wxString& logfile ) +FILE *OpenDump(const wxString &logfile) { - return wxFopen( Path::Combine(DumpsFolder, logfile), L"w" ); + return wxFopen(Path::Combine(DumpsFolder, logfile), L"w"); } -namespace DebugConfig { -static const wchar_t* Section = L"DEBUG"; +namespace DebugConfig +{ +static const wchar_t *Section = L"DEBUG"; static void set_default_filenames() { - AccessLogFileName = L"SPU2Log.txt"; - WaveLogFileName = L"SPU2log.wav"; - DMA4LogFileName = L"SPU2dma4.dat"; - DMA7LogFileName = L"SPU2dma7.dat"; + AccessLogFileName = L"SPU2Log.txt"; + WaveLogFileName = L"SPU2log.wav"; + DMA4LogFileName = L"SPU2dma4.dat"; + DMA7LogFileName = L"SPU2dma7.dat"; - CoresDumpFileName = L"SPU2Cores.txt"; - MemDumpFileName = L"SPU2mem.dat"; - RegDumpFileName = L"SPU2regs.dat"; + CoresDumpFileName = L"SPU2Cores.txt"; + MemDumpFileName = L"SPU2mem.dat"; + RegDumpFileName = L"SPU2regs.dat"; } void ReadSettings() { - DebugEnabled = CfgReadBool(Section, L"Global_Enable",0); - _MsgToConsole= CfgReadBool(Section, L"Show_Messages",0); - _MsgKeyOnOff = CfgReadBool(Section, L"Show_Messages_Key_On_Off",0); - _MsgVoiceOff = CfgReadBool(Section, L"Show_Messages_Voice_Off",0); - _MsgDMA = CfgReadBool(Section, L"Show_Messages_DMA_Transfer",0); - _MsgAutoDMA = CfgReadBool(Section, L"Show_Messages_AutoDMA",0); - _MsgOverruns = CfgReadBool(Section, L"Show_Messages_Overruns",0); - _MsgCache = CfgReadBool(Section, L"Show_Messages_CacheStats",0); + DebugEnabled = CfgReadBool(Section, L"Global_Enable", 0); + _MsgToConsole = CfgReadBool(Section, L"Show_Messages", 0); + _MsgKeyOnOff = CfgReadBool(Section, L"Show_Messages_Key_On_Off", 0); + _MsgVoiceOff = CfgReadBool(Section, L"Show_Messages_Voice_Off", 0); + _MsgDMA = CfgReadBool(Section, L"Show_Messages_DMA_Transfer", 0); + _MsgAutoDMA = CfgReadBool(Section, L"Show_Messages_AutoDMA", 0); + _MsgOverruns = CfgReadBool(Section, L"Show_Messages_Overruns", 0); + _MsgCache = CfgReadBool(Section, L"Show_Messages_CacheStats", 0); - _AccessLog = CfgReadBool(Section, L"Log_Register_Access",0); - _DMALog = CfgReadBool(Section, L"Log_DMA_Transfers",0); - _WaveLog = CfgReadBool(Section, L"Log_WAVE_Output",0); + _AccessLog = CfgReadBool(Section, L"Log_Register_Access", 0); + _DMALog = CfgReadBool(Section, L"Log_DMA_Transfers", 0); + _WaveLog = CfgReadBool(Section, L"Log_WAVE_Output", 0); - _CoresDump = CfgReadBool(Section, L"Dump_Info",0); - _MemDump = CfgReadBool(Section, L"Dump_Memory",0); - _RegDump = CfgReadBool(Section, L"Dump_Regs",0); + _CoresDump = CfgReadBool(Section, L"Dump_Info", 0); + _MemDump = CfgReadBool(Section, L"Dump_Memory", 0); + _RegDump = CfgReadBool(Section, L"Dump_Regs", 0); - set_default_filenames(); + set_default_filenames(); - CfgReadStr(Section,L"Access_Log_Filename",AccessLogFileName, L"logs/SPU2Log.txt"); - CfgReadStr(Section,L"WaveLog_Filename", WaveLogFileName, L"logs/SPU2log.wav"); - CfgReadStr(Section,L"DMA4Log_Filename", DMA4LogFileName, L"logs/SPU2dma4.dat"); - CfgReadStr(Section,L"DMA7Log_Filename", DMA7LogFileName, L"logs/SPU2dma7.dat"); + CfgReadStr(Section, L"Access_Log_Filename", AccessLogFileName, L"logs/SPU2Log.txt"); + CfgReadStr(Section, L"WaveLog_Filename", WaveLogFileName, L"logs/SPU2log.wav"); + CfgReadStr(Section, L"DMA4Log_Filename", DMA4LogFileName, L"logs/SPU2dma4.dat"); + CfgReadStr(Section, L"DMA7Log_Filename", DMA7LogFileName, L"logs/SPU2dma7.dat"); - CfgReadStr(Section,L"Info_Dump_Filename",CoresDumpFileName, L"logs/SPU2Cores.txt"); - CfgReadStr(Section,L"Mem_Dump_Filename", MemDumpFileName, L"logs/SPU2mem.dat"); - CfgReadStr(Section,L"Reg_Dump_Filename", RegDumpFileName, L"logs/SPU2regs.dat"); + CfgReadStr(Section, L"Info_Dump_Filename", CoresDumpFileName, L"logs/SPU2Cores.txt"); + CfgReadStr(Section, L"Mem_Dump_Filename", MemDumpFileName, L"logs/SPU2mem.dat"); + CfgReadStr(Section, L"Reg_Dump_Filename", RegDumpFileName, L"logs/SPU2regs.dat"); } void WriteSettings() { - CfgWriteBool(Section,L"Global_Enable",DebugEnabled); + CfgWriteBool(Section, L"Global_Enable", DebugEnabled); - CfgWriteBool(Section,L"Show_Messages", _MsgToConsole); - CfgWriteBool(Section,L"Show_Messages_Key_On_Off", _MsgKeyOnOff); - CfgWriteBool(Section,L"Show_Messages_Voice_Off", _MsgVoiceOff); - CfgWriteBool(Section,L"Show_Messages_DMA_Transfer",_MsgDMA); - CfgWriteBool(Section,L"Show_Messages_AutoDMA", _MsgAutoDMA); - CfgWriteBool(Section,L"Show_Messages_Overruns", _MsgOverruns); - CfgWriteBool(Section,L"Show_Messages_CacheStats", _MsgCache); + CfgWriteBool(Section, L"Show_Messages", _MsgToConsole); + CfgWriteBool(Section, L"Show_Messages_Key_On_Off", _MsgKeyOnOff); + CfgWriteBool(Section, L"Show_Messages_Voice_Off", _MsgVoiceOff); + CfgWriteBool(Section, L"Show_Messages_DMA_Transfer", _MsgDMA); + CfgWriteBool(Section, L"Show_Messages_AutoDMA", _MsgAutoDMA); + CfgWriteBool(Section, L"Show_Messages_Overruns", _MsgOverruns); + CfgWriteBool(Section, L"Show_Messages_CacheStats", _MsgCache); - CfgWriteBool(Section,L"Log_Register_Access",_AccessLog); - CfgWriteBool(Section,L"Log_DMA_Transfers", _DMALog); - CfgWriteBool(Section,L"Log_WAVE_Output", _WaveLog); + CfgWriteBool(Section, L"Log_Register_Access", _AccessLog); + CfgWriteBool(Section, L"Log_DMA_Transfers", _DMALog); + CfgWriteBool(Section, L"Log_WAVE_Output", _WaveLog); - CfgWriteBool(Section,L"Dump_Info", _CoresDump); - CfgWriteBool(Section,L"Dump_Memory",_MemDump); - CfgWriteBool(Section,L"Dump_Regs", _RegDump); + CfgWriteBool(Section, L"Dump_Info", _CoresDump); + CfgWriteBool(Section, L"Dump_Memory", _MemDump); + CfgWriteBool(Section, L"Dump_Regs", _RegDump); - set_default_filenames(); - CfgWriteStr(Section,L"Access_Log_Filename",AccessLogFileName); - CfgWriteStr(Section,L"WaveLog_Filename", WaveLogFileName); - CfgWriteStr(Section,L"DMA4Log_Filename", DMA4LogFileName); - CfgWriteStr(Section,L"DMA7Log_Filename", DMA7LogFileName); - - CfgWriteStr(Section,L"Info_Dump_Filename",CoresDumpFileName); - CfgWriteStr(Section,L"Mem_Dump_Filename", MemDumpFileName); - CfgWriteStr(Section,L"Reg_Dump_Filename", RegDumpFileName); + set_default_filenames(); + CfgWriteStr(Section, L"Access_Log_Filename", AccessLogFileName); + CfgWriteStr(Section, L"WaveLog_Filename", WaveLogFileName); + CfgWriteStr(Section, L"DMA4Log_Filename", DMA4LogFileName); + CfgWriteStr(Section, L"DMA7Log_Filename", DMA7LogFileName); + CfgWriteStr(Section, L"Info_Dump_Filename", CoresDumpFileName); + CfgWriteStr(Section, L"Mem_Dump_Filename", MemDumpFileName); + CfgWriteStr(Section, L"Reg_Dump_Filename", RegDumpFileName); } #ifdef __unix__ @@ -169,26 +169,26 @@ void DisplayDialog() GtkWidget *log_access_check, *log_dma_check, *log_wave_check; GtkWidget *dump_core_check, *dump_mem_check, *dump_reg_check; - ReadSettings(); + ReadSettings(); // Create the widgets - dialog = gtk_dialog_new_with_buttons ( - "Spu2-X Config", - NULL, // parent window - (GtkDialogFlags)(GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT), - "OK", GTK_RESPONSE_ACCEPT, - "Cancel", GTK_RESPONSE_REJECT, - NULL); + dialog = gtk_dialog_new_with_buttons( + "Spu2-X Config", + NULL, // parent window + (GtkDialogFlags)(GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT), + "OK", GTK_RESPONSE_ACCEPT, + "Cancel", GTK_RESPONSE_REJECT, + NULL); main_box = gtk_hbox_new(false, 5); - main_frame = gtk_frame_new ("Spu2-X Config"); - gtk_container_add (GTK_CONTAINER(main_frame), main_box); + main_frame = gtk_frame_new("Spu2-X Config"); + gtk_container_add(GTK_CONTAINER(main_frame), main_box); // Message Section - msg_box = gtk_vbox_new(false, 5); + msg_box = gtk_vbox_new(false, 5); - msg_console_check = gtk_check_button_new_with_label("Show In Console"); + msg_console_check = gtk_check_button_new_with_label("Show In Console"); msg_key_check = gtk_check_button_new_with_label("KeyOn/Off Events"); msg_voice_check = gtk_check_button_new_with_label("Voice Stop Events"); msg_dma_check = gtk_check_button_new_with_label("DMA Operations"); @@ -196,13 +196,13 @@ void DisplayDialog() msg_overrun_check = gtk_check_button_new_with_label("Buffer Over/Underruns"); msg_cache_check = gtk_check_button_new_with_label("ADPCM Cache Statistics"); - gtk_container_add(GTK_CONTAINER(msg_box), msg_console_check); - gtk_container_add(GTK_CONTAINER(msg_box), msg_key_check); - gtk_container_add(GTK_CONTAINER(msg_box), msg_voice_check); - gtk_container_add(GTK_CONTAINER(msg_box), msg_dma_check); - gtk_container_add(GTK_CONTAINER(msg_box), msg_autodma_check); - gtk_container_add(GTK_CONTAINER(msg_box), msg_overrun_check); - gtk_container_add(GTK_CONTAINER(msg_box), msg_cache_check); + gtk_container_add(GTK_CONTAINER(msg_box), msg_console_check); + gtk_container_add(GTK_CONTAINER(msg_box), msg_key_check); + gtk_container_add(GTK_CONTAINER(msg_box), msg_voice_check); + gtk_container_add(GTK_CONTAINER(msg_box), msg_dma_check); + gtk_container_add(GTK_CONTAINER(msg_box), msg_autodma_check); + gtk_container_add(GTK_CONTAINER(msg_box), msg_overrun_check); + gtk_container_add(GTK_CONTAINER(msg_box), msg_cache_check); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(msg_console_check), _MsgToConsole); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(msg_key_check), _MsgKeyOnOff); @@ -212,26 +212,26 @@ void DisplayDialog() gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(msg_overrun_check), _MsgOverruns); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(msg_cache_check), _MsgCache); - msg_frame = gtk_frame_new ("Message/Log Options"); - gtk_container_add (GTK_CONTAINER(msg_frame), msg_box); + msg_frame = gtk_frame_new("Message/Log Options"); + gtk_container_add(GTK_CONTAINER(msg_frame), msg_box); // Log Section - log_box = gtk_vbox_new(false, 5); + log_box = gtk_vbox_new(false, 5); log_access_check = gtk_check_button_new_with_label("Log Register/DMA Actions"); log_dma_check = gtk_check_button_new_with_label("Log DMA Writes"); log_wave_check = gtk_check_button_new_with_label("Log Audio Output"); - gtk_container_add(GTK_CONTAINER(log_box), log_access_check); - gtk_container_add(GTK_CONTAINER(log_box), log_dma_check); - gtk_container_add(GTK_CONTAINER(log_box), log_wave_check); + gtk_container_add(GTK_CONTAINER(log_box), log_access_check); + gtk_container_add(GTK_CONTAINER(log_box), log_dma_check); + gtk_container_add(GTK_CONTAINER(log_box), log_wave_check); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(log_access_check), _AccessLog); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(log_dma_check), _DMALog); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(log_wave_check), _WaveLog); - log_frame = gtk_frame_new ("Log Options"); - gtk_container_add (GTK_CONTAINER(log_frame), log_box); + log_frame = gtk_frame_new("Log Options"); + gtk_container_add(GTK_CONTAINER(log_frame), log_box); // Dump Section dump_box = gtk_vbox_new(false, 5); @@ -240,56 +240,54 @@ void DisplayDialog() dump_mem_check = gtk_check_button_new_with_label("Dump Memory Contents"); dump_reg_check = gtk_check_button_new_with_label("Dump Register Data"); - gtk_container_add(GTK_CONTAINER(dump_box), dump_core_check); - gtk_container_add(GTK_CONTAINER(dump_box), dump_mem_check); - gtk_container_add(GTK_CONTAINER(dump_box), dump_reg_check); + gtk_container_add(GTK_CONTAINER(dump_box), dump_core_check); + gtk_container_add(GTK_CONTAINER(dump_box), dump_mem_check); + gtk_container_add(GTK_CONTAINER(dump_box), dump_reg_check); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(dump_core_check), _CoresDump); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(dump_mem_check), _MemDump); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(dump_reg_check), _RegDump); - dump_frame = gtk_frame_new ("Dumps (on close)"); - gtk_container_add (GTK_CONTAINER(dump_frame), dump_box); + dump_frame = gtk_frame_new("Dumps (on close)"); + gtk_container_add(GTK_CONTAINER(dump_frame), dump_box); // Add everything - gtk_container_add (GTK_CONTAINER(main_box), msg_frame); - gtk_container_add (GTK_CONTAINER(main_box), log_frame); - gtk_container_add (GTK_CONTAINER(main_box), dump_frame); + gtk_container_add(GTK_CONTAINER(main_box), msg_frame); + gtk_container_add(GTK_CONTAINER(main_box), log_frame); + gtk_container_add(GTK_CONTAINER(main_box), dump_frame); // Add all our widgets, and show everything we've added to the dialog. - gtk_container_add (GTK_CONTAINER(gtk_dialog_get_content_area(GTK_DIALOG(dialog))), main_frame); - gtk_widget_show_all (dialog); + gtk_container_add(GTK_CONTAINER(gtk_dialog_get_content_area(GTK_DIALOG(dialog))), main_frame); + gtk_widget_show_all(dialog); - return_value = gtk_dialog_run (GTK_DIALOG (dialog)); + return_value = gtk_dialog_run(GTK_DIALOG(dialog)); - if (return_value == GTK_RESPONSE_ACCEPT) - { - _MsgToConsole = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(msg_console_check)); - _MsgKeyOnOff = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(msg_key_check)); - _MsgVoiceOff = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(msg_voice_check)); - _MsgDMA = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(msg_dma_check)); - _MsgAutoDMA = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(msg_autodma_check)); - _MsgOverruns = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(msg_overrun_check)); - _MsgCache = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(msg_cache_check)); + if (return_value == GTK_RESPONSE_ACCEPT) { + _MsgToConsole = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(msg_console_check)); + _MsgKeyOnOff = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(msg_key_check)); + _MsgVoiceOff = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(msg_voice_check)); + _MsgDMA = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(msg_dma_check)); + _MsgAutoDMA = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(msg_autodma_check)); + _MsgOverruns = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(msg_overrun_check)); + _MsgCache = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(msg_cache_check)); - _AccessLog = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(log_access_check)); - _DMALog = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(log_dma_check)); - _WaveLog = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(log_wave_check)); + _AccessLog = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(log_access_check)); + _DMALog = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(log_dma_check)); + _WaveLog = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(log_wave_check)); - _CoresDump = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(dump_core_check)); - _MemDump = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(dump_mem_check)); - _RegDump = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(dump_reg_check)); + _CoresDump = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(dump_core_check)); + _MemDump = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(dump_mem_check)); + _RegDump = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(dump_reg_check)); } - gtk_widget_destroy (dialog); + gtk_widget_destroy(dialog); WriteSettings(); } #else void DisplayDialog() { - } #endif } diff --git a/plugins/spu2-x/src/Linux/ConfigSoundTouch.cpp b/plugins/spu2-x/src/Linux/ConfigSoundTouch.cpp index 2c799a2ee9..fe5e786e6a 100644 --- a/plugins/spu2-x/src/Linux/ConfigSoundTouch.cpp +++ b/plugins/spu2-x/src/Linux/ConfigSoundTouch.cpp @@ -26,150 +26,147 @@ namespace SoundtouchCfg { - // Timestretch Slider Bounds, Min/Max - static const int SequenceLen_Min = 20; - static const int SequenceLen_Max = 100; +// Timestretch Slider Bounds, Min/Max +static const int SequenceLen_Min = 20; +static const int SequenceLen_Max = 100; - static const int SeekWindow_Min = 10; - static const int SeekWindow_Max = 30; +static const int SeekWindow_Min = 10; +static const int SeekWindow_Max = 30; - static const int Overlap_Min = 5; - static const int Overlap_Max = 15; +static const int Overlap_Min = 5; +static const int Overlap_Max = 15; - static int SequenceLenMS = 30; - static int SeekWindowMS = 20; - static int OverlapMS = 10; +static int SequenceLenMS = 30; +static int SeekWindowMS = 20; +static int OverlapMS = 10; - static void ClampValues() - { - Clampify( SequenceLenMS, SequenceLen_Min, SequenceLen_Max ); - Clampify( SeekWindowMS, SeekWindow_Min, SeekWindow_Max ); - Clampify( OverlapMS, Overlap_Min, Overlap_Max ); - } +static void ClampValues() +{ + Clampify(SequenceLenMS, SequenceLen_Min, SequenceLen_Max); + Clampify(SeekWindowMS, SeekWindow_Min, SeekWindow_Max); + Clampify(OverlapMS, Overlap_Min, Overlap_Max); +} - void ApplySettings( soundtouch::SoundTouch& sndtouch ) - { - sndtouch.setSetting( SETTING_SEQUENCE_MS, SequenceLenMS ); - sndtouch.setSetting( SETTING_SEEKWINDOW_MS, SeekWindowMS ); - sndtouch.setSetting( SETTING_OVERLAP_MS, OverlapMS ); - } +void ApplySettings(soundtouch::SoundTouch &sndtouch) +{ + sndtouch.setSetting(SETTING_SEQUENCE_MS, SequenceLenMS); + sndtouch.setSetting(SETTING_SEEKWINDOW_MS, SeekWindowMS); + sndtouch.setSetting(SETTING_OVERLAP_MS, OverlapMS); +} - void ReadSettings() - { - SequenceLenMS = CfgReadInt( L"SOUNDTOUCH", L"SequenceLengthMS", 30 ); - SeekWindowMS = CfgReadInt( L"SOUNDTOUCH", L"SeekWindowMS", 20 ); - OverlapMS = CfgReadInt( L"SOUNDTOUCH", L"OverlapMS", 10 ); +void ReadSettings() +{ + SequenceLenMS = CfgReadInt(L"SOUNDTOUCH", L"SequenceLengthMS", 30); + SeekWindowMS = CfgReadInt(L"SOUNDTOUCH", L"SeekWindowMS", 20); + OverlapMS = CfgReadInt(L"SOUNDTOUCH", L"OverlapMS", 10); - ClampValues(); - WriteSettings(); - } + ClampValues(); + WriteSettings(); +} - void WriteSettings() - { - CfgWriteInt( L"SOUNDTOUCH", L"SequenceLengthMS", SequenceLenMS ); - CfgWriteInt( L"SOUNDTOUCH", L"SeekWindowMS", SeekWindowMS ); - CfgWriteInt( L"SOUNDTOUCH", L"OverlapMS", OverlapMS ); - } +void WriteSettings() +{ + CfgWriteInt(L"SOUNDTOUCH", L"SequenceLengthMS", SequenceLenMS); + CfgWriteInt(L"SOUNDTOUCH", L"SeekWindowMS", SeekWindowMS); + CfgWriteInt(L"SOUNDTOUCH", L"OverlapMS", OverlapMS); +} #ifdef __unix__ - static GtkWidget *seq_label, *seek_label, *over_label; - static GtkWidget *seq_slide, *seek_slide, *over_slide; +static GtkWidget *seq_label, *seek_label, *over_label; +static GtkWidget *seq_slide, *seek_slide, *over_slide; - void restore_defaults() - { - gtk_range_set_value(GTK_RANGE(seq_slide), 30); - gtk_range_set_value(GTK_RANGE(seek_slide), 20); - gtk_range_set_value(GTK_RANGE(over_slide), 10); - } +void restore_defaults() +{ + gtk_range_set_value(GTK_RANGE(seq_slide), 30); + gtk_range_set_value(GTK_RANGE(seek_slide), 20); + gtk_range_set_value(GTK_RANGE(over_slide), 10); +} - void DisplayDialog() - { - int return_value; - GtkWidget *dialog, *main_label, *main_frame, *main_box; - GtkWidget *default_button; +void DisplayDialog() +{ + int return_value; + GtkWidget *dialog, *main_label, *main_frame, *main_box; + GtkWidget *default_button; - ReadSettings(); + ReadSettings(); - /* Create the widgets */ - dialog = gtk_dialog_new_with_buttons ( - "Advanced Settings", - NULL, /* parent window*/ - (GtkDialogFlags)(GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT), - "OK", GTK_RESPONSE_ACCEPT, - "Cancel", GTK_RESPONSE_REJECT, - NULL); + /* Create the widgets */ + dialog = gtk_dialog_new_with_buttons( + "Advanced Settings", + NULL, /* parent window*/ + (GtkDialogFlags)(GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT), + "OK", GTK_RESPONSE_ACCEPT, + "Cancel", GTK_RESPONSE_REJECT, + NULL); - main_label = gtk_label_new ("These are advanced configuration options fine tuning time stretching behavior. Larger values are better for slowdown, while smaller values are better for speedup (more then 60 fps.). All options are in microseconds."); - gtk_label_set_line_wrap (GTK_LABEL(main_label), true); + main_label = gtk_label_new("These are advanced configuration options fine tuning time stretching behavior. Larger values are better for slowdown, while smaller values are better for speedup (more then 60 fps.). All options are in microseconds."); + gtk_label_set_line_wrap(GTK_LABEL(main_label), true); - default_button = gtk_button_new_with_label("Reset to Defaults"); + default_button = gtk_button_new_with_label("Reset to Defaults"); - seq_label = gtk_label_new("Sequence Length"); + seq_label = gtk_label_new("Sequence Length"); #if GTK_MAJOR_VERSION < 3 - seq_slide = gtk_hscale_new_with_range(SequenceLen_Min, SequenceLen_Max, 2); + seq_slide = gtk_hscale_new_with_range(SequenceLen_Min, SequenceLen_Max, 2); #else - seq_slide = gtk_scale_new_with_range(GTK_ORIENTATION_HORIZONTAL, SequenceLen_Min, SequenceLen_Max, 2); + seq_slide = gtk_scale_new_with_range(GTK_ORIENTATION_HORIZONTAL, SequenceLen_Min, SequenceLen_Max, 2); #endif - gtk_range_set_value(GTK_RANGE(seq_slide), SequenceLenMS); + gtk_range_set_value(GTK_RANGE(seq_slide), SequenceLenMS); - seek_label = gtk_label_new("Seek Window Size"); + seek_label = gtk_label_new("Seek Window Size"); #if GTK_MAJOR_VERSION < 3 - seek_slide = gtk_hscale_new_with_range(SeekWindow_Min, SeekWindow_Max, 1); + seek_slide = gtk_hscale_new_with_range(SeekWindow_Min, SeekWindow_Max, 1); #else - seek_slide = gtk_scale_new_with_range(GTK_ORIENTATION_HORIZONTAL, SeekWindow_Min, SeekWindow_Max, 1); + seek_slide = gtk_scale_new_with_range(GTK_ORIENTATION_HORIZONTAL, SeekWindow_Min, SeekWindow_Max, 1); #endif - gtk_range_set_value(GTK_RANGE(seek_slide), SeekWindowMS); + gtk_range_set_value(GTK_RANGE(seek_slide), SeekWindowMS); - over_label = gtk_label_new("Overlap"); + over_label = gtk_label_new("Overlap"); #if GTK_MAJOR_VERSION < 3 - over_slide = gtk_hscale_new_with_range(Overlap_Min, Overlap_Max, 1); + over_slide = gtk_hscale_new_with_range(Overlap_Min, Overlap_Max, 1); #else - over_slide = gtk_scale_new_with_range(GTK_ORIENTATION_HORIZONTAL, Overlap_Min, Overlap_Max, 1); + over_slide = gtk_scale_new_with_range(GTK_ORIENTATION_HORIZONTAL, Overlap_Min, Overlap_Max, 1); #endif - gtk_range_set_value(GTK_RANGE(over_slide), OverlapMS); + gtk_range_set_value(GTK_RANGE(over_slide), OverlapMS); - main_box = gtk_vbox_new(false, 5); - main_frame = gtk_frame_new ("Spu2-X Config"); + main_box = gtk_vbox_new(false, 5); + main_frame = gtk_frame_new("Spu2-X Config"); - gtk_container_add(GTK_CONTAINER (main_box), default_button); - gtk_container_add(GTK_CONTAINER (main_box), seq_label); - gtk_container_add(GTK_CONTAINER (main_box), seq_slide); - gtk_container_add(GTK_CONTAINER (main_box), seek_label); - gtk_container_add(GTK_CONTAINER (main_box), seek_slide); - gtk_container_add(GTK_CONTAINER (main_box), over_label); - gtk_container_add(GTK_CONTAINER (main_box), over_slide); - gtk_container_add(GTK_CONTAINER(main_frame), main_box); + gtk_container_add(GTK_CONTAINER(main_box), default_button); + gtk_container_add(GTK_CONTAINER(main_box), seq_label); + gtk_container_add(GTK_CONTAINER(main_box), seq_slide); + gtk_container_add(GTK_CONTAINER(main_box), seek_label); + gtk_container_add(GTK_CONTAINER(main_box), seek_slide); + gtk_container_add(GTK_CONTAINER(main_box), over_label); + gtk_container_add(GTK_CONTAINER(main_box), over_slide); + gtk_container_add(GTK_CONTAINER(main_frame), main_box); - gtk_container_add(GTK_CONTAINER(gtk_dialog_get_content_area(GTK_DIALOG(dialog))), main_label); - gtk_container_add (GTK_CONTAINER(gtk_dialog_get_content_area(GTK_DIALOG(dialog))), main_frame); - gtk_widget_show_all (dialog); + gtk_container_add(GTK_CONTAINER(gtk_dialog_get_content_area(GTK_DIALOG(dialog))), main_label); + gtk_container_add(GTK_CONTAINER(gtk_dialog_get_content_area(GTK_DIALOG(dialog))), main_frame); + gtk_widget_show_all(dialog); - g_signal_connect_swapped(default_button, "clicked", G_CALLBACK(restore_defaults), default_button); + g_signal_connect_swapped(default_button, "clicked", G_CALLBACK(restore_defaults), default_button); - return_value = gtk_dialog_run (GTK_DIALOG (dialog)); + return_value = gtk_dialog_run(GTK_DIALOG(dialog)); - if (return_value == GTK_RESPONSE_ACCEPT) - { - SequenceLenMS = gtk_range_get_value(GTK_RANGE(seq_slide));; - SeekWindowMS = gtk_range_get_value(GTK_RANGE(seek_slide));; - OverlapMS = gtk_range_get_value(GTK_RANGE(over_slide));; - } - - gtk_widget_destroy (dialog); - - WriteSettings(); - } -#else - void DisplayDialog() - { - + if (return_value == GTK_RESPONSE_ACCEPT) { + SequenceLenMS = gtk_range_get_value(GTK_RANGE(seq_slide)); + SeekWindowMS = gtk_range_get_value(GTK_RANGE(seek_slide)); + OverlapMS = gtk_range_get_value(GTK_RANGE(over_slide)); } - void restore_defaults() - { - - } + gtk_widget_destroy(dialog); + + WriteSettings(); +} +#else +void DisplayDialog() +{ +} + +void restore_defaults() +{ +} #endif } diff --git a/plugins/spu2-x/src/Linux/Dialogs.cpp b/plugins/spu2-x/src/Linux/Dialogs.cpp index 74acd6e527..981ffe97e4 100644 --- a/plugins/spu2-x/src/Linux/Dialogs.cpp +++ b/plugins/spu2-x/src/Linux/Dialogs.cpp @@ -15,7 +15,7 @@ * along with SPU2-X. If not, see . */ - // To be continued... +// To be continued... #include "Dialogs.h" #include @@ -32,34 +32,35 @@ void SysMessage(const char *fmt, ...) vsprintf(msg, fmt, list); va_end(list); - if (msg[strlen(msg)-1] == '\n') msg[strlen(msg)-1] = 0; + if (msg[strlen(msg) - 1] == '\n') + msg[strlen(msg) - 1] = 0; GtkWidget *dialog; - dialog = gtk_message_dialog_new (NULL, - GTK_DIALOG_DESTROY_WITH_PARENT, - GTK_MESSAGE_INFO, - GTK_BUTTONS_OK, - "%s", msg); - gtk_dialog_run (GTK_DIALOG (dialog)); - gtk_widget_destroy (dialog); + dialog = gtk_message_dialog_new(NULL, + GTK_DIALOG_DESTROY_WITH_PARENT, + GTK_MESSAGE_INFO, + GTK_BUTTONS_OK, + "%s", msg); + gtk_dialog_run(GTK_DIALOG(dialog)); + gtk_widget_destroy(dialog); } void SysMessage(const wchar_t *fmt, ...) { - va_list list; - va_start(list,fmt); - wxString msg; - msg.PrintfV( fmt, list ); - va_end(list); + va_list list; + va_start(list, fmt); + wxString msg; + msg.PrintfV(fmt, list); + va_end(list); GtkWidget *dialog; - dialog = gtk_message_dialog_new (NULL, - GTK_DIALOG_DESTROY_WITH_PARENT, - GTK_MESSAGE_INFO, - GTK_BUTTONS_OK, - "%s", msg.ToUTF8().data()); - gtk_dialog_run (GTK_DIALOG (dialog)); - gtk_widget_destroy (dialog); + dialog = gtk_message_dialog_new(NULL, + GTK_DIALOG_DESTROY_WITH_PARENT, + GTK_MESSAGE_INFO, + GTK_BUTTONS_OK, + "%s", msg.ToUTF8().data()); + gtk_dialog_run(GTK_DIALOG(dialog)); + gtk_widget_destroy(dialog); } #endif @@ -67,8 +68,7 @@ void DspUpdate() { } -s32 DspLoadLibrary(wchar_t* fileName, int modnum) +s32 DspLoadLibrary(wchar_t *fileName, int modnum) { - return 0; + return 0; } - diff --git a/plugins/spu2-x/src/Linux/Dialogs.h b/plugins/spu2-x/src/Linux/Dialogs.h index d163f401b9..ed9ebc1c69 100644 --- a/plugins/spu2-x/src/Linux/Dialogs.h +++ b/plugins/spu2-x/src/Linux/Dialogs.h @@ -23,23 +23,23 @@ namespace DebugConfig { - extern void ReadSettings(); - extern void WriteSettings(); - extern void DisplayDialog(); +extern void ReadSettings(); +extern void WriteSettings(); +extern void DisplayDialog(); } -extern void CfgSetSettingsDir(const char* dir); -extern void CfgSetLogDir(const char* dir); +extern void CfgSetSettingsDir(const char *dir); +extern void CfgSetLogDir(const char *dir); -extern void CfgWriteBool(const wchar_t* Section, const wchar_t* Name, bool Value); -extern void CfgWriteInt(const wchar_t* Section, const wchar_t* Name, int Value); -extern void CfgWriteFloat(const wchar_t* Section, const wchar_t* Name, float Value); -extern void CfgWriteStr(const wchar_t* Section, const wchar_t* Name, const wxString& Data); +extern void CfgWriteBool(const wchar_t *Section, const wchar_t *Name, bool Value); +extern void CfgWriteInt(const wchar_t *Section, const wchar_t *Name, int Value); +extern void CfgWriteFloat(const wchar_t *Section, const wchar_t *Name, float Value); +extern void CfgWriteStr(const wchar_t *Section, const wchar_t *Name, const wxString &Data); -extern bool CfgReadBool(const wchar_t *Section,const wchar_t* Name, bool Default); -extern void CfgReadStr(const wchar_t* Section, const wchar_t* Name, wxString& Data, const wchar_t* Default); +extern bool CfgReadBool(const wchar_t *Section, const wchar_t *Name, bool Default); +extern void CfgReadStr(const wchar_t *Section, const wchar_t *Name, wxString &Data, const wchar_t *Default); //extern void CfgReadStr(const wchar_t* Section, const wchar_t* Name, wchar_t* Data, int DataSize, const wchar_t* Default); -extern int CfgReadInt(const wchar_t* Section, const wchar_t* Name,int Default) ; -extern float CfgReadFloat(const wchar_t* Section, const wchar_t* Name, float Default); +extern int CfgReadInt(const wchar_t *Section, const wchar_t *Name, int Default); +extern float CfgReadFloat(const wchar_t *Section, const wchar_t *Name, float Default); #endif diff --git a/plugins/spu2-x/src/Lowpass.cpp b/plugins/spu2-x/src/Lowpass.cpp index 1a0be8c065..ca526e5f76 100644 --- a/plugins/spu2-x/src/Lowpass.cpp +++ b/plugins/spu2-x/src/Lowpass.cpp @@ -20,75 +20,75 @@ #include #include -template< typename FloatType > __forceinline -LowPassFilter::LowPassFilter( FloatType freq, FloatType srate ) +template +__forceinline LowPassFilter::LowPassFilter(FloatType freq, FloatType srate) { - typedef FloatType FT; + typedef FloatType FT; - FloatType omega = (FT)2.0 * freq / srate; - static const FloatType g = (FT)1.0; + FloatType omega = (FT)2.0 * freq / srate; + static const FloatType g = (FT)1.0; - // calculating coefficients: + // calculating coefficients: - FloatType k,p,q,a; - FloatType a0,a1,a2,a3,a4; + FloatType k, p, q, a; + FloatType a0, a1, a2, a3, a4; - k = ((FT)4.0*g-(FT)3.0)/(g+(FT)1.0); - p = (FT)1.0-(FT)0.25*k; - p *= p; + k = ((FT)4.0 * g - (FT)3.0) / (g + (FT)1.0); + p = (FT)1.0 - (FT)0.25 * k; + p *= p; - // LP: - a = (FT)1.0/(tan((FT)0.5*omega)*((FT)1.0+p)); - p = (FT)1.0+a; - q = (FT)1.0-a; + // LP: + a = (FT)1.0 / (tan((FT)0.5 * omega) * ((FT)1.0 + p)); + p = (FT)1.0 + a; + q = (FT)1.0 - a; - a0 = (FT)1.0/(k+p*p*p*p); - a1 = (FT)4.0*(k+p*p*p*q); - a2 = (FT)6.0*(k+p*p*q*q); - a3 = (FT)4.0*(k+p*q*q*q); - a4 = (k+q*q*q*q); - p = a0*(k+(FT)1.0); + a0 = (FT)1.0 / (k + p * p * p * p); + a1 = (FT)4.0 * (k + p * p * p * q); + a2 = (FT)6.0 * (k + p * p * q * q); + a3 = (FT)4.0 * (k + p * q * q * q); + a4 = (k + q * q * q * q); + p = a0 * (k + (FT)1.0); - coef[0] = p; - coef[1] = (FT)4.0*p; - coef[2] = (FT)6.0*p; - coef[3] = (FT)4.0*p; - coef[4] = p; - coef[5] = -a1*a0; - coef[6] = -a2*a0; - coef[7] = -a3*a0; - coef[8] = -a4*a0; + coef[0] = p; + coef[1] = (FT)4.0 * p; + coef[2] = (FT)6.0 * p; + coef[3] = (FT)4.0 * p; + coef[4] = p; + coef[5] = -a1 * a0; + coef[6] = -a2 * a0; + coef[7] = -a3 * a0; + coef[8] = -a4 * a0; } // Processes a single sample into the LPF. -template< typename FloatType > __forceinline -FloatType LowPassFilter::sample( FloatType inval ) +template +__forceinline FloatType LowPassFilter::sample(FloatType inval) { - const FloatType out = (coef[0]*inval) + d[0]; - d[0] = (coef[1]*inval) + (coef[5]*out) + d[1]; - d[1] = (coef[2]*inval) + (coef[6]*out) + d[2]; - d[2] = (coef[3]*inval) + (coef[7]*out) + d[3]; - d[3] = (coef[4]*inval) + (coef[8]*out); + const FloatType out = (coef[0] * inval) + d[0]; + d[0] = (coef[1] * inval) + (coef[5] * out) + d[1]; + d[1] = (coef[2] * inval) + (coef[6] * out) + d[2]; + d[2] = (coef[3] * inval) + (coef[7] * out) + d[3]; + d[3] = (coef[4] * inval) + (coef[8] * out); - return out; + return out; } -LowPassFilter32::LowPassFilter32( float freq, float srate ) : - impl_lpf( freq, srate ) +LowPassFilter32::LowPassFilter32(float freq, float srate) + : impl_lpf(freq, srate) { } -LowPassFilter64::LowPassFilter64( double freq, double srate ) : - impl_lpf( freq, srate ) +LowPassFilter64::LowPassFilter64(double freq, double srate) + : impl_lpf(freq, srate) { } -float LowPassFilter32::sample( float inval ) +float LowPassFilter32::sample(float inval) { - return impl_lpf.sample( inval ); + return impl_lpf.sample(inval); } -double LowPassFilter64::sample( double inval ) +double LowPassFilter64::sample(double inval) { - return impl_lpf.sample( inval ); + return impl_lpf.sample(inval); } diff --git a/plugins/spu2-x/src/Lowpass.h b/plugins/spu2-x/src/Lowpass.h index 1d969926c2..d20d9bc717 100644 --- a/plugins/spu2-x/src/Lowpass.h +++ b/plugins/spu2-x/src/Lowpass.h @@ -17,28 +17,28 @@ #pragma once -template< typename FloatType > +template struct LowPassFilter { - FloatType coef[9]; - FloatType d[4]; + FloatType coef[9]; + FloatType d[4]; - LowPassFilter( FloatType freq, FloatType srate ); - FloatType sample( FloatType inval ); + LowPassFilter(FloatType freq, FloatType srate); + FloatType sample(FloatType inval); }; struct LowPassFilter32 { - LowPassFilter impl_lpf; + LowPassFilter impl_lpf; - LowPassFilter32( float freq, float srate ); - float sample( float inval ); + LowPassFilter32(float freq, float srate); + float sample(float inval); }; struct LowPassFilter64 { - LowPassFilter impl_lpf; + LowPassFilter impl_lpf; - LowPassFilter64( double freq, double srate ); - double sample( double inval ); + LowPassFilter64(double freq, double srate); + double sample(double inval); }; diff --git a/plugins/spu2-x/src/Mixer.cpp b/plugins/spu2-x/src/Mixer.cpp index 84affe3197..83273babe5 100644 --- a/plugins/spu2-x/src/Mixer.cpp +++ b/plugins/spu2-x/src/Mixer.cpp @@ -25,13 +25,12 @@ void ADMAOutLogWrite(void *lpData, u32 ulSize); static const s32 tbl_XA_Factor[16][2] = -{ - { 0, 0 }, - { 60, 0 }, - { 115, -52 }, - { 98, -55 }, - { 122, -60 } -}; + { + {0, 0}, + {60, 0}, + {115, -52}, + {98, -55}, + {122, -60}}; // Performs a 64-bit multiplication between two values and returns the @@ -47,88 +46,85 @@ static const s32 tbl_XA_Factor[16][2] = // caller to extend the inputs so that they make use of all 32 bits of // precision. // -static __forceinline s32 MulShr32( s32 srcval, s32 mulval ) +static __forceinline s32 MulShr32(s32 srcval, s32 mulval) { - return (s64)srcval * mulval >> 32; + return (s64)srcval * mulval >> 32; } -__forceinline s32 clamp_mix( s32 x, u8 bitshift ) +__forceinline s32 clamp_mix(s32 x, u8 bitshift) { - return GetClamped( x, -0x8000<> 4 & 0xF; - if (id > 4 && MsgToConsole()) - ConLog("* SPU2-X: Unknown ADPCM coefficients table id %d\n", id); - const s32 pred1 = tbl_XA_Factor[id][0]; - const s32 pred2 = tbl_XA_Factor[id][1]; + const s32 header = *block; + const s32 shift = (header & 0xF) + 16; + const int id = header >> 4 & 0xF; + if (id > 4 && MsgToConsole()) + ConLog("* SPU2-X: Unknown ADPCM coefficients table id %d\n", id); + const s32 pred1 = tbl_XA_Factor[id][0]; + const s32 pred2 = tbl_XA_Factor[id][1]; - const s8* blockbytes = (s8*)&block[1]; - const s8* blockend = &blockbytes[13]; + const s8 *blockbytes = (s8 *)&block[1]; + const s8 *blockend = &blockbytes[13]; - for(; blockbytes<=blockend; ++blockbytes) - { - s32 data = ((*blockbytes)<<28) & 0xF0000000; - s32 pcm = (data >> shift) + (((pred1*prev1)+(pred2*prev2)+32) >> 6); + for (; blockbytes <= blockend; ++blockbytes) { + s32 data = ((*blockbytes) << 28) & 0xF0000000; + s32 pcm = (data >> shift) + (((pred1 * prev1) + (pred2 * prev2) + 32) >> 6); - Clampify( pcm, -0x8000, 0x7fff ); - *(buffer++) = pcm; + Clampify(pcm, -0x8000, 0x7fff); + *(buffer++) = pcm; - data = ((*blockbytes)<<24) & 0xF0000000; - s32 pcm2 = (data >> shift) + (((pred1*pcm)+(pred2*prev1)+32) >> 6); + data = ((*blockbytes) << 24) & 0xF0000000; + s32 pcm2 = (data >> shift) + (((pred1 * pcm) + (pred2 * prev1) + 32) >> 6); - Clampify( pcm2, -0x8000, 0x7fff ); - *(buffer++) = pcm2; + Clampify(pcm2, -0x8000, 0x7fff); + *(buffer++) = pcm2; - prev2 = pcm; - prev1 = pcm2; - } + prev2 = pcm; + prev1 = pcm2; + } } -static void __forceinline IncrementNextA(V_Core& thiscore, uint voiceidx) +static void __forceinline IncrementNextA(V_Core &thiscore, uint voiceidx) { - V_Voice &vc(thiscore.Voices[voiceidx]); + V_Voice &vc(thiscore.Voices[voiceidx]); - // Important! Both cores signal IRQ when an address is read, regardless of - // which core actually reads the address. + // Important! Both cores signal IRQ when an address is read, regardless of + // which core actually reads the address. - for( int i=0; i<2; i++ ) - { - if( Cores[i].IRQEnable && (vc.NextA==Cores[i].IRQA ) ) - { - //if( IsDevBuild ) - // ConLog(" * SPU2 Core %d: IRQ Requested (IRQA (%05X) passed; voice %d).\n", i, Cores[i].IRQA, thiscore.Index * 24 + voiceidx); + for (int i = 0; i < 2; i++) { + if (Cores[i].IRQEnable && (vc.NextA == Cores[i].IRQA)) { + //if( IsDevBuild ) + // ConLog(" * SPU2 Core %d: IRQ Requested (IRQA (%05X) passed; voice %d).\n", i, Cores[i].IRQA, thiscore.Index * 24 + voiceidx); - SetIrqCall(i); - } - } + SetIrqCall(i); + } + } - vc.NextA++; - vc.NextA&=0xFFFFF; + vc.NextA++; + vc.NextA &= 0xFFFFF; } // decoded pcm data, used to cache the decoded data so that it needn't be decoded @@ -145,126 +141,114 @@ int g_counter_cache_ignores = 0; // (the documented requirement that every block in a loop has the LOOP bit set is nonsense according to tests) // LOOP/START sets LSA to NAX unless LSA was written manually since sound generation started // (see LoopMode, the method by which this is achieved on the real SPU2 is unknown) -#define XAFLAG_LOOP_END (1ul<<0) -#define XAFLAG_LOOP (1ul<<1) -#define XAFLAG_LOOP_START (1ul<<2) +#define XAFLAG_LOOP_END (1ul << 0) +#define XAFLAG_LOOP (1ul << 1) +#define XAFLAG_LOOP_START (1ul << 2) -static __forceinline s32 GetNextDataBuffered( V_Core& thiscore, uint voiceidx ) +static __forceinline s32 GetNextDataBuffered(V_Core &thiscore, uint voiceidx) { - V_Voice& vc( thiscore.Voices[voiceidx] ); + V_Voice &vc(thiscore.Voices[voiceidx]); - if( (vc.SCurrent&3) == 0 ) - { - IncrementNextA( thiscore, voiceidx ); - - if ((vc.NextA & 7) == 0) // vc.SCurrent == 24 equivalent - { - if(vc.LoopFlags & XAFLAG_LOOP_END) - { - thiscore.Regs.ENDX |= (1 << voiceidx); - vc.NextA = vc.LoopStartA | 1; - if (!(vc.LoopFlags & XAFLAG_LOOP)) - { - vc.Stop(); + if ((vc.SCurrent & 3) == 0) { + IncrementNextA(thiscore, voiceidx); - if( IsDevBuild ) - { - if(MsgVoiceOff()) ConLog("* SPU2-X: Voice Off by EndPoint: %d \n", voiceidx); - } - } - } - else - vc.NextA++; // no, don't IncrementNextA here. We haven't read the header yet. - } - } + if ((vc.NextA & 7) == 0) // vc.SCurrent == 24 equivalent + { + if (vc.LoopFlags & XAFLAG_LOOP_END) { + thiscore.Regs.ENDX |= (1 << voiceidx); + vc.NextA = vc.LoopStartA | 1; + if (!(vc.LoopFlags & XAFLAG_LOOP)) { + vc.Stop(); - if( vc.SCurrent == 28 ) - { - vc.SCurrent = 0; + if (IsDevBuild) { + if (MsgVoiceOff()) + ConLog("* SPU2-X: Voice Off by EndPoint: %d \n", voiceidx); + } + } + } else + vc.NextA++; // no, don't IncrementNextA here. We haven't read the header yet. + } + } - // We'll need the loop flags and buffer pointers regardless of cache status: + if (vc.SCurrent == 28) { + vc.SCurrent = 0; - for (int i=0; i<2; i++) - if (Cores[i].IRQEnable && Cores[i].IRQA == (vc.NextA & 0xFFFF8)) - SetIrqCall(i); + // We'll need the loop flags and buffer pointers regardless of cache status: - s16* memptr = GetMemPtr(vc.NextA & 0xFFFF8); - vc.LoopFlags = *memptr >> 8; // grab loop flags from the upper byte. + for (int i = 0; i < 2; i++) + if (Cores[i].IRQEnable && Cores[i].IRQA == (vc.NextA & 0xFFFF8)) + SetIrqCall(i); - if( (vc.LoopFlags & XAFLAG_LOOP_START) && !vc.LoopMode ) - vc.LoopStartA = vc.NextA & 0xFFFF8; + s16 *memptr = GetMemPtr(vc.NextA & 0xFFFF8); + vc.LoopFlags = *memptr >> 8; // grab loop flags from the upper byte. - const int cacheIdx = vc.NextA / pcm_WordsPerBlock; - PcmCacheEntry& cacheLine = pcm_cache_data[cacheIdx]; - vc.SBuffer = cacheLine.Sampledata; + if ((vc.LoopFlags & XAFLAG_LOOP_START) && !vc.LoopMode) + vc.LoopStartA = vc.NextA & 0xFFFF8; - if( cacheLine.Validated ) - { - // Cached block! Read from the cache directly. - // Make sure to propagate the prev1/prev2 ADPCM: + const int cacheIdx = vc.NextA / pcm_WordsPerBlock; + PcmCacheEntry &cacheLine = pcm_cache_data[cacheIdx]; + vc.SBuffer = cacheLine.Sampledata; - vc.Prev1 = vc.SBuffer[27]; - vc.Prev2 = vc.SBuffer[26]; + if (cacheLine.Validated) { + // Cached block! Read from the cache directly. + // Make sure to propagate the prev1/prev2 ADPCM: - //ConLog( "* SPU2-X: Cache Hit! NextA=0x%x, cacheIdx=0x%x\n", vc.NextA, cacheIdx ); + vc.Prev1 = vc.SBuffer[27]; + vc.Prev2 = vc.SBuffer[26]; - if( IsDevBuild ) - g_counter_cache_hits++; - } - else - { - // Only flag the cache if it's a non-dynamic memory range. - if( vc.NextA >= SPU2_DYN_MEMLINE ) - cacheLine.Validated = true; + //ConLog( "* SPU2-X: Cache Hit! NextA=0x%x, cacheIdx=0x%x\n", vc.NextA, cacheIdx ); - if( IsDevBuild ) - { - if( vc.NextA < SPU2_DYN_MEMLINE ) - g_counter_cache_ignores++; - else - g_counter_cache_misses++; - } + if (IsDevBuild) + g_counter_cache_hits++; + } else { + // Only flag the cache if it's a non-dynamic memory range. + if (vc.NextA >= SPU2_DYN_MEMLINE) + cacheLine.Validated = true; - XA_decode_block( vc.SBuffer, memptr, vc.Prev1, vc.Prev2 ); - } - } + if (IsDevBuild) { + if (vc.NextA < SPU2_DYN_MEMLINE) + g_counter_cache_ignores++; + else + g_counter_cache_misses++; + } - return vc.SBuffer[vc.SCurrent++]; + XA_decode_block(vc.SBuffer, memptr, vc.Prev1, vc.Prev2); + } + } + + return vc.SBuffer[vc.SCurrent++]; } -static __forceinline void GetNextDataDummy(V_Core& thiscore, uint voiceidx) +static __forceinline void GetNextDataDummy(V_Core &thiscore, uint voiceidx) { - V_Voice& vc( thiscore.Voices[voiceidx] ); + V_Voice &vc(thiscore.Voices[voiceidx]); - IncrementNextA( thiscore, voiceidx ); - - if ((vc.NextA & 7) == 0) // vc.SCurrent == 24 equivalent - { - if(vc.LoopFlags & XAFLAG_LOOP_END) - { - thiscore.Regs.ENDX |= (1 << voiceidx); - vc.NextA = vc.LoopStartA | 1; - } - else - vc.NextA++; // no, don't IncrementNextA here. We haven't read the header yet. - } + IncrementNextA(thiscore, voiceidx); - if (vc.SCurrent == 28) - { - for (int i=0; i<2; i++) - if (Cores[i].IRQEnable && Cores[i].IRQA == (vc.NextA & 0xFFFF8)) - SetIrqCall(i); + if ((vc.NextA & 7) == 0) // vc.SCurrent == 24 equivalent + { + if (vc.LoopFlags & XAFLAG_LOOP_END) { + thiscore.Regs.ENDX |= (1 << voiceidx); + vc.NextA = vc.LoopStartA | 1; + } else + vc.NextA++; // no, don't IncrementNextA here. We haven't read the header yet. + } - vc.LoopFlags = *GetMemPtr(vc.NextA&0xFFFF8) >> 8; // grab loop flags from the upper byte. + if (vc.SCurrent == 28) { + for (int i = 0; i < 2; i++) + if (Cores[i].IRQEnable && Cores[i].IRQA == (vc.NextA & 0xFFFF8)) + SetIrqCall(i); - if ((vc.LoopFlags & XAFLAG_LOOP_START) && !vc.LoopMode) - vc.LoopStartA = vc.NextA & 0xFFFF8; + vc.LoopFlags = *GetMemPtr(vc.NextA & 0xFFFF8) >> 8; // grab loop flags from the upper byte. - vc.SCurrent = 0; - } + if ((vc.LoopFlags & XAFLAG_LOOP_START) && !vc.LoopMode) + vc.LoopStartA = vc.NextA & 0xFFFF8; - vc.SP -= 4096 * (4 - (vc.SCurrent & 3)); - vc.SCurrent += 4 - (vc.SCurrent & 3); + vc.SCurrent = 0; + } + + vc.SP -= 4096 * (4 - (vc.SCurrent & 3)); + vc.SCurrent += 4 - (vc.SCurrent & 3); } ///////////////////////////////////////////////////////////////////////////////////////// @@ -272,22 +256,22 @@ static __forceinline void GetNextDataDummy(V_Core& thiscore, uint voiceidx) static s32 __forceinline GetNoiseValues() { - static s32 Seed = 0x41595321; - s32 retval = 0x8000; - - if( Seed&0x100 ) - retval = (Seed&0xff) << 8; - else if( Seed&0xffff ) - retval = 0x7fff; + static s32 Seed = 0x41595321; + s32 retval = 0x8000; - s32 x = _rotr(Seed, 0x5); - x ^= 0x9a; - s32 y = _rotl(x, 0x2); - y += x; - y ^= x; - Seed = _rotr(y, 0x3); + if (Seed & 0x100) + retval = (Seed & 0xff) << 8; + else if (Seed & 0xffff) + retval = 0x7fff; - return retval; + s32 x = _rotr(Seed, 0x5); + x ^= 0x9a; + s32 y = _rotl(x, 0x2); + y += x; + y ^= x; + Seed = _rotr(y, 0x3); + + return retval; } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// @@ -298,197 +282,192 @@ static s32 __forceinline GetNoiseValues() // Data is shifted up by 1 bit to give the output an effective 16 bit range. static __forceinline s32 ApplyVolume(s32 data, s32 volume) { - //return (volume * data) >> 15; - return MulShr32( data<<1, volume ); + //return (volume * data) >> 15; + return MulShr32(data << 1, volume); } -static __forceinline StereoOut32 ApplyVolume( const StereoOut32& data, const V_VolumeLR& volume ) +static __forceinline StereoOut32 ApplyVolume(const StereoOut32 &data, const V_VolumeLR &volume) { - return StereoOut32( - ApplyVolume( data.Left, volume.Left ), - ApplyVolume( data.Right, volume.Right ) - ); + return StereoOut32( + ApplyVolume(data.Left, volume.Left), + ApplyVolume(data.Right, volume.Right)); } -static __forceinline StereoOut32 ApplyVolume( const StereoOut32& data, const V_VolumeSlideLR& volume ) +static __forceinline StereoOut32 ApplyVolume(const StereoOut32 &data, const V_VolumeSlideLR &volume) { - return StereoOut32( - ApplyVolume( data.Left, volume.Left.Value ), - ApplyVolume( data.Right, volume.Right.Value ) - ); + return StereoOut32( + ApplyVolume(data.Left, volume.Left.Value), + ApplyVolume(data.Right, volume.Right.Value)); } -static void __forceinline UpdatePitch( uint coreidx, uint voiceidx ) +static void __forceinline UpdatePitch(uint coreidx, uint voiceidx) { - V_Voice& vc( Cores[coreidx].Voices[voiceidx] ); - s32 pitch; + V_Voice &vc(Cores[coreidx].Voices[voiceidx]); + s32 pitch; - // [Air] : re-ordered comparisons: Modulated is much more likely to be zero than voice, - // and so the way it was before it's have to check both voice and modulated values - // most of the time. Now it'll just check Modulated and short-circuit past the voice - // check (not that it amounts to much, but eh every little bit helps). - if( (vc.Modulated==0) || (voiceidx==0) ) - pitch = vc.Pitch; - else - pitch = GetClamped((vc.Pitch*(32768 + Cores[coreidx].Voices[voiceidx-1].OutX))>>15, 0, 0x3fff); + // [Air] : re-ordered comparisons: Modulated is much more likely to be zero than voice, + // and so the way it was before it's have to check both voice and modulated values + // most of the time. Now it'll just check Modulated and short-circuit past the voice + // check (not that it amounts to much, but eh every little bit helps). + if ((vc.Modulated == 0) || (voiceidx == 0)) + pitch = vc.Pitch; + else + pitch = GetClamped((vc.Pitch * (32768 + Cores[coreidx].Voices[voiceidx - 1].OutX)) >> 15, 0, 0x3fff); - vc.SP+=pitch; + vc.SP += pitch; } -static __forceinline void CalculateADSR( V_Core& thiscore, uint voiceidx ) +static __forceinline void CalculateADSR(V_Core &thiscore, uint voiceidx) { - V_Voice& vc( thiscore.Voices[voiceidx] ); + V_Voice &vc(thiscore.Voices[voiceidx]); - if( vc.ADSR.Phase==0 ) - { - vc.ADSR.Value = 0; - return; - } + if (vc.ADSR.Phase == 0) { + vc.ADSR.Value = 0; + return; + } - if( !vc.ADSR.Calculate() ) - { - if( IsDevBuild ) - { - if(MsgVoiceOff()) ConLog("* SPU2-X: Voice Off by ADSR: %d \n", voiceidx); - } - vc.Stop(); - } + if (!vc.ADSR.Calculate()) { + if (IsDevBuild) { + if (MsgVoiceOff()) + ConLog("* SPU2-X: Voice Off by ADSR: %d \n", voiceidx); + } + vc.Stop(); + } - pxAssume( vc.ADSR.Value >= 0 ); // ADSR should never be negative... + pxAssume(vc.ADSR.Value >= 0); // ADSR should never be negative... } /* Tension: 65535 is high, 32768 is normal, 0 is low */ -template - __forceinline -static s32 HermiteInterpolate( - s32 y0, // 16.0 - s32 y1, // 16.0 - s32 y2, // 16.0 - s32 y3, // 16.0 - s32 mu // 0.12 - ) +template +__forceinline static s32 HermiteInterpolate( + s32 y0, // 16.0 + s32 y1, // 16.0 + s32 y2, // 16.0 + s32 y3, // 16.0 + s32 mu // 0.12 + ) { - s32 m00 = ((y1-y0)*i_tension) >> 16; // 16.0 - s32 m01 = ((y2-y1)*i_tension) >> 16; // 16.0 - s32 m0 = m00 + m01; + s32 m00 = ((y1 - y0) * i_tension) >> 16; // 16.0 + s32 m01 = ((y2 - y1) * i_tension) >> 16; // 16.0 + s32 m0 = m00 + m01; - s32 m10 = ((y2-y1)*i_tension) >> 16; // 16.0 - s32 m11 = ((y3-y2)*i_tension) >> 16; // 16.0 - s32 m1 = m10 + m11; + s32 m10 = ((y2 - y1) * i_tension) >> 16; // 16.0 + s32 m11 = ((y3 - y2) * i_tension) >> 16; // 16.0 + s32 m1 = m10 + m11; - s32 val = (( 2*y1 + m0 + m1 - 2*y2) * mu) >> 12; // 16.0 - val = ((val - 3*y1 - 2*m0 - m1 + 3*y2) * mu) >> 12; // 16.0 - val = ((val + m0 ) * mu) >> 11; // 16.0 + s32 val = ((2 * y1 + m0 + m1 - 2 * y2) * mu) >> 12; // 16.0 + val = ((val - 3 * y1 - 2 * m0 - m1 + 3 * y2) * mu) >> 12; // 16.0 + val = ((val + m0) * mu) >> 11; // 16.0 - return(val + (y1<<1)); + return (val + (y1 << 1)); } -__forceinline -static s32 CatmullRomInterpolate( - s32 y0, // 16.0 - s32 y1, // 16.0 - s32 y2, // 16.0 - s32 y3, // 16.0 - s32 mu // 0.12 - ) +__forceinline static s32 CatmullRomInterpolate( + s32 y0, // 16.0 + s32 y1, // 16.0 + s32 y2, // 16.0 + s32 y3, // 16.0 + s32 mu // 0.12 + ) { - //q(t) = 0.5 *( (2 * P1) + - // (-P0 + P2) * t + - // (2*P0 - 5*P1 + 4*P2 - P3) * t2 + - // (-P0 + 3*P1- 3*P2 + P3) * t3) + //q(t) = 0.5 *( (2 * P1) + + // (-P0 + P2) * t + + // (2*P0 - 5*P1 + 4*P2 - P3) * t2 + + // (-P0 + 3*P1- 3*P2 + P3) * t3) - s32 a3 = (- y0 + 3*y1 - 3*y2 + y3); - s32 a2 = ( 2*y0 - 5*y1 + 4*y2 - y3); - s32 a1 = (- y0 + y2 ); - s32 a0 = ( 2*y1 ); + s32 a3 = (-y0 + 3 * y1 - 3 * y2 + y3); + s32 a2 = (2 * y0 - 5 * y1 + 4 * y2 - y3); + s32 a1 = (-y0 + y2); + s32 a0 = (2 * y1); - s32 val = ((a3 ) * mu) >> 12; - val = ((a2 + val) * mu) >> 12; - val = ((a1 + val) * mu) >> 12; + s32 val = ((a3)*mu) >> 12; + val = ((a2 + val) * mu) >> 12; + val = ((a1 + val) * mu) >> 12; - return (a0 + val); + return (a0 + val); } -__forceinline -static s32 CubicInterpolate( - s32 y0, // 16.0 - s32 y1, // 16.0 - s32 y2, // 16.0 - s32 y3, // 16.0 - s32 mu // 0.12 - ) +__forceinline static s32 CubicInterpolate( + s32 y0, // 16.0 + s32 y1, // 16.0 + s32 y2, // 16.0 + s32 y3, // 16.0 + s32 mu // 0.12 + ) { - const s32 a0 = y3 - y2 - y0 + y1; - const s32 a1 = y0 - y1 - a0; - const s32 a2 = y2 - y0; + const s32 a0 = y3 - y2 - y0 + y1; + const s32 a1 = y0 - y1 - a0; + const s32 a2 = y2 - y0; - s32 val = (( a0) * mu) >> 12; - val = ((val + a1) * mu) >> 12; - val = ((val + a2) * mu) >> 11; + s32 val = ((a0)*mu) >> 12; + val = ((val + a1) * mu) >> 12; + val = ((val + a2) * mu) >> 11; - return(val + (y1<<1)); + return (val + (y1 << 1)); } // Returns a 16 bit result in Value. // Uses standard template-style optimization techniques to statically generate five different // versions of this function (one for each type of interpolation). -template< int InterpType > -static __forceinline s32 GetVoiceValues( V_Core& thiscore, uint voiceidx ) +template +static __forceinline s32 GetVoiceValues(V_Core &thiscore, uint voiceidx) { - V_Voice& vc( thiscore.Voices[voiceidx] ); + V_Voice &vc(thiscore.Voices[voiceidx]); - while( vc.SP > 0 ) - { - if( InterpType >= 2 ) - { - vc.PV4 = vc.PV3; - vc.PV3 = vc.PV2; - } - vc.PV2 = vc.PV1; - vc.PV1 = GetNextDataBuffered( thiscore, voiceidx ); - vc.SP -= 4096; - } + while (vc.SP > 0) { + if (InterpType >= 2) { + vc.PV4 = vc.PV3; + vc.PV3 = vc.PV2; + } + vc.PV2 = vc.PV1; + vc.PV1 = GetNextDataBuffered(thiscore, voiceidx); + vc.SP -= 4096; + } - const s32 mu = vc.SP + 4096; + const s32 mu = vc.SP + 4096; - switch( InterpType ) - { - case 0: return vc.PV1<<1; - case 1: return (vc.PV1<<1) - (( (vc.PV2 - vc.PV1) * vc.SP)>>11); + switch (InterpType) { + case 0: + return vc.PV1 << 1; + case 1: + return (vc.PV1 << 1) - (((vc.PV2 - vc.PV1) * vc.SP) >> 11); - case 2: return CubicInterpolate (vc.PV4, vc.PV3, vc.PV2, vc.PV1, mu); - case 3: return HermiteInterpolate<16384> (vc.PV4, vc.PV3, vc.PV2, vc.PV1, mu); - case 4: return CatmullRomInterpolate (vc.PV4, vc.PV3, vc.PV2, vc.PV1, mu); + case 2: + return CubicInterpolate(vc.PV4, vc.PV3, vc.PV2, vc.PV1, mu); + case 3: + return HermiteInterpolate<16384>(vc.PV4, vc.PV3, vc.PV2, vc.PV1, mu); + case 4: + return CatmullRomInterpolate(vc.PV4, vc.PV3, vc.PV2, vc.PV1, mu); - jNO_DEFAULT; - } + jNO_DEFAULT; + } - return 0; // technically unreachable! + return 0; // technically unreachable! } // Noise values need to be mixed without going through interpolation, since it // can wreak havoc on the noise (causing muffling or popping). Not that this noise // generator is accurate in its own right.. but eh, ah well :) -static __forceinline s32 GetNoiseValues( V_Core& thiscore, uint voiceidx ) +static __forceinline s32 GetNoiseValues(V_Core &thiscore, uint voiceidx) { - V_Voice& vc( thiscore.Voices[voiceidx] ); + V_Voice &vc(thiscore.Voices[voiceidx]); - s32 retval = GetNoiseValues(); + s32 retval = GetNoiseValues(); - /*while(vc.SP>=4096) + /*while(vc.SP>=4096) { retval = GetNoiseValues(); vc.SP-=4096; }*/ - // GetNoiseValues can't set the phase zero on us unexpectedly - // like GetVoiceValues can. Better assert just in case though.. - pxAssume( vc.ADSR.Phase != 0 ); + // GetNoiseValues can't set the phase zero on us unexpectedly + // like GetVoiceValues can. Better assert just in case though.. + pxAssume(vc.ADSR.Phase != 0); - return retval; + return retval; } ///////////////////////////////////////////////////////////////////////////////////////// @@ -498,225 +477,228 @@ static __forceinline s32 GetNoiseValues( V_Core& thiscore, uint voiceidx ) // writes a signed value to the SPU2 ram // Performs no cache invalidation -- use only for dynamic memory ranges // of the SPU2 (between 0x0000 and SPU2_DYN_MEMLINE) -static __forceinline void spu2M_WriteFast( u32 addr, s16 value ) -{ - // Fixes some of the oldest hangs in pcsx2's history! :p - for( int i=0; i<2; i++ ) - { - if( Cores[i].IRQEnable && Cores[i].IRQA == addr ) - { - //printf("Core %d special write IRQ Called (IRQ passed). IRQA = %x\n",i,addr); - SetIrqCall(i); - } - } - // throw an assertion if the memory range is invalid: +static __forceinline void spu2M_WriteFast(u32 addr, s16 value) +{ + // Fixes some of the oldest hangs in pcsx2's history! :p + for (int i = 0; i < 2; i++) { + if (Cores[i].IRQEnable && Cores[i].IRQA == addr) { + //printf("Core %d special write IRQ Called (IRQ passed). IRQA = %x\n",i,addr); + SetIrqCall(i); + } + } +// throw an assertion if the memory range is invalid: #ifndef DEBUG_FAST - pxAssume( addr < SPU2_DYN_MEMLINE ); + pxAssume(addr < SPU2_DYN_MEMLINE); #endif - *GetMemPtr( addr ) = value; + *GetMemPtr(addr) = value; } -static __forceinline StereoOut32 MixVoice( uint coreidx, uint voiceidx ) +static __forceinline StereoOut32 MixVoice(uint coreidx, uint voiceidx) { - V_Core& thiscore( Cores[coreidx] ); - V_Voice& vc( thiscore.Voices[voiceidx] ); + V_Core &thiscore(Cores[coreidx]); + V_Voice &vc(thiscore.Voices[voiceidx]); - // If this assertion fails, it mans SCurrent is being corrupted somewhere, or is not initialized - // properly. Invalid values in SCurrent will cause errant IRQs and corrupted audio. - pxAssertMsg( (vc.SCurrent <= 28) && (vc.SCurrent != 0), "Current sample should always range from 1->28" ); + // If this assertion fails, it mans SCurrent is being corrupted somewhere, or is not initialized + // properly. Invalid values in SCurrent will cause errant IRQs and corrupted audio. + pxAssertMsg((vc.SCurrent <= 28) && (vc.SCurrent != 0), "Current sample should always range from 1->28"); - // Most games don't use much volume slide effects. So only call the UpdateVolume - // methods when needed by checking the flag outside the method here... - // (Note: Ys 6 : Ark of Nephistm uses these effects) + // Most games don't use much volume slide effects. So only call the UpdateVolume + // methods when needed by checking the flag outside the method here... + // (Note: Ys 6 : Ark of Nephistm uses these effects) - vc.Volume.Update(); + vc.Volume.Update(); - // SPU2 Note: The spu2 continues to process voices for eternity, always, so we - // have to run through all the motions of updating the voice regardless of it's - // audible status. Otherwise IRQs might not trigger and emulation might fail. + // SPU2 Note: The spu2 continues to process voices for eternity, always, so we + // have to run through all the motions of updating the voice regardless of it's + // audible status. Otherwise IRQs might not trigger and emulation might fail. - if( vc.ADSR.Phase > 0 ) - { - UpdatePitch( coreidx, voiceidx ); + if (vc.ADSR.Phase > 0) { + UpdatePitch(coreidx, voiceidx); - s32 Value = 0; + s32 Value = 0; - if( vc.Noise ) - Value = GetNoiseValues( thiscore, voiceidx ); - else - { - // Optimization : Forceinline'd Templated Dispatch Table. Any halfwit compiler will - // turn this into a clever jump dispatch table (no call/rets, no compares, uber-efficient!) + if (vc.Noise) + Value = GetNoiseValues(thiscore, voiceidx); + else { + // Optimization : Forceinline'd Templated Dispatch Table. Any halfwit compiler will + // turn this into a clever jump dispatch table (no call/rets, no compares, uber-efficient!) - switch( Interpolation ) - { - case 0: Value = GetVoiceValues<0>( thiscore, voiceidx ); break; - case 1: Value = GetVoiceValues<1>( thiscore, voiceidx ); break; - case 2: Value = GetVoiceValues<2>( thiscore, voiceidx ); break; - case 3: Value = GetVoiceValues<3>( thiscore, voiceidx ); break; - case 4: Value = GetVoiceValues<4>( thiscore, voiceidx ); break; + switch (Interpolation) { + case 0: + Value = GetVoiceValues<0>(thiscore, voiceidx); + break; + case 1: + Value = GetVoiceValues<1>(thiscore, voiceidx); + break; + case 2: + Value = GetVoiceValues<2>(thiscore, voiceidx); + break; + case 3: + Value = GetVoiceValues<3>(thiscore, voiceidx); + break; + case 4: + Value = GetVoiceValues<4>(thiscore, voiceidx); + break; - jNO_DEFAULT; - } - } + jNO_DEFAULT; + } + } - // Update and Apply ADSR (applies to normal and noise sources) - // - // Note! It's very important that ADSR stay as accurate as possible. By the way - // it is used, various sound effects can end prematurely if we truncate more than - // one or two bits. Best result comes from no truncation at all, which is why we - // use a full 64-bit multiply/result here. + // Update and Apply ADSR (applies to normal and noise sources) + // + // Note! It's very important that ADSR stay as accurate as possible. By the way + // it is used, various sound effects can end prematurely if we truncate more than + // one or two bits. Best result comes from no truncation at all, which is why we + // use a full 64-bit multiply/result here. - CalculateADSR( thiscore, voiceidx ); - Value = MulShr32( Value, vc.ADSR.Value ); - - // Store Value for eventual modulation later - // Pseudonym's Crest calculation idea. Actually calculates a crest, unlike the old code which was just peak. - if(vc.PV1 < vc.NextCrest) - { - vc.OutX = MulShr32(vc.NextCrest, vc.ADSR.Value); - vc.NextCrest = -0x8000; - } - if(vc.PV1 > vc.PV2) - { - vc.NextCrest = vc.PV1; - } + CalculateADSR(thiscore, voiceidx); + Value = MulShr32(Value, vc.ADSR.Value); - if( IsDevBuild ) - DebugCores[coreidx].Voices[voiceidx].displayPeak = std::max(DebugCores[coreidx].Voices[voiceidx].displayPeak,(s32)vc.OutX); + // Store Value for eventual modulation later + // Pseudonym's Crest calculation idea. Actually calculates a crest, unlike the old code which was just peak. + if (vc.PV1 < vc.NextCrest) { + vc.OutX = MulShr32(vc.NextCrest, vc.ADSR.Value); + vc.NextCrest = -0x8000; + } + if (vc.PV1 > vc.PV2) { + vc.NextCrest = vc.PV1; + } - // Write-back of raw voice data (post ADSR applied) + if (IsDevBuild) + DebugCores[coreidx].Voices[voiceidx].displayPeak = std::max(DebugCores[coreidx].Voices[voiceidx].displayPeak, (s32)vc.OutX); - if (voiceidx==1) spu2M_WriteFast( ( (0==coreidx) ? 0x400 : 0xc00 ) + OutPos, vc.OutX ); - else if (voiceidx==3) spu2M_WriteFast( ( (0==coreidx) ? 0x600 : 0xe00 ) + OutPos, vc.OutX ); - - return ApplyVolume( StereoOut32( Value, Value ), vc.Volume ); - } - else - { - // Continue processing voice, even if it's "off". Or else we miss interrupts! (Fatal Frame engine died because of this.) - if (NEVER_SKIP_VOICES - || (*GetMemPtr(vc.NextA & 0xFFFF8) >> 8 & 3) != 3 || vc.LoopStartA != (vc.NextA & ~7) // not in a tight loop - || (Cores[0].IRQEnable && (Cores[0].IRQA & ~7) == vc.LoopStartA) // or should be interrupting regularly - || (Cores[1].IRQEnable && (Cores[1].IRQA & ~7) == vc.LoopStartA) - || !(thiscore.Regs.ENDX & 1 << voiceidx)) // or isn't currently flagged as having passed the endpoint - { - UpdatePitch(coreidx, voiceidx); + // Write-back of raw voice data (post ADSR applied) - while (vc.SP > 0) - GetNextDataDummy(thiscore, voiceidx); // Dummy is enough - } + if (voiceidx == 1) + spu2M_WriteFast(((0 == coreidx) ? 0x400 : 0xc00) + OutPos, vc.OutX); + else if (voiceidx == 3) + spu2M_WriteFast(((0 == coreidx) ? 0x600 : 0xe00) + OutPos, vc.OutX); - // Write-back of raw voice data (some zeros since the voice is "dead") - if (voiceidx==1) spu2M_WriteFast( ( (0==coreidx) ? 0x400 : 0xc00 ) + OutPos, 0 ); - else if (voiceidx==3) spu2M_WriteFast( ( (0==coreidx) ? 0x600 : 0xe00 ) + OutPos, 0 ); + return ApplyVolume(StereoOut32(Value, Value), vc.Volume); + } else { + // Continue processing voice, even if it's "off". Or else we miss interrupts! (Fatal Frame engine died because of this.) + if (NEVER_SKIP_VOICES || (*GetMemPtr(vc.NextA & 0xFFFF8) >> 8 & 3) != 3 || vc.LoopStartA != (vc.NextA & ~7) // not in a tight loop + || (Cores[0].IRQEnable && (Cores[0].IRQA & ~7) == vc.LoopStartA) // or should be interrupting regularly + || (Cores[1].IRQEnable && (Cores[1].IRQA & ~7) == vc.LoopStartA) || !(thiscore.Regs.ENDX & 1 << voiceidx)) // or isn't currently flagged as having passed the endpoint + { + UpdatePitch(coreidx, voiceidx); - return StereoOut32( 0, 0 ); - } + while (vc.SP > 0) + GetNextDataDummy(thiscore, voiceidx); // Dummy is enough + } + + // Write-back of raw voice data (some zeros since the voice is "dead") + if (voiceidx == 1) + spu2M_WriteFast(((0 == coreidx) ? 0x400 : 0xc00) + OutPos, 0); + else if (voiceidx == 3) + spu2M_WriteFast(((0 == coreidx) ? 0x600 : 0xe00) + OutPos, 0); + + return StereoOut32(0, 0); + } } -const VoiceMixSet VoiceMixSet::Empty( (StereoOut32()), (StereoOut32()) ); // Don't use SteroOut32::Empty because C++ doesn't make any dep/order checks on global initializers. +const VoiceMixSet VoiceMixSet::Empty((StereoOut32()), (StereoOut32())); // Don't use SteroOut32::Empty because C++ doesn't make any dep/order checks on global initializers. -static __forceinline void MixCoreVoices( VoiceMixSet& dest, const uint coreidx ) +static __forceinline void MixCoreVoices(VoiceMixSet &dest, const uint coreidx) { - V_Core& thiscore( Cores[coreidx] ); + V_Core &thiscore(Cores[coreidx]); - for( uint voiceidx=0; voiceidx= 0x100000) return TD; + Reverb_AdvanceBuffer(); // Updates the reverb work area as well, if needed. - StereoOut32 TW; + // ToDo: + // Bad EndA causes memory corruption. Bad for us, unknown on PS2! + if (!FxEnable || EffectsEndA >= 0x100000) + return TD; - // Mix Input, Voice, and External data: + StereoOut32 TW; - TW.Left = Input.Left & WetGate.InpL; - TW.Right = Input.Right & WetGate.InpR; + // Mix Input, Voice, and External data: - TW.Left += Voices.Wet.Left & WetGate.SndL; - TW.Right += Voices.Wet.Right & WetGate.SndR; - TW.Left += Ext.Left & WetGate.ExtL; - TW.Right += Ext.Right & WetGate.ExtR; + TW.Left = Input.Left & WetGate.InpL; + TW.Right = Input.Right & WetGate.InpR; - WaveDump::WriteCore( Index, CoreSrc_PreReverb, TW ); + TW.Left += Voices.Wet.Left & WetGate.SndL; + TW.Right += Voices.Wet.Right & WetGate.SndR; + TW.Left += Ext.Left & WetGate.ExtL; + TW.Right += Ext.Right & WetGate.ExtR; - StereoOut32 RV = DoReverb( TW ); + WaveDump::WriteCore(Index, CoreSrc_PreReverb, TW); - WaveDump::WriteCore( Index, CoreSrc_PostReverb, RV ); + StereoOut32 RV = DoReverb(TW); - // Mix Dry + Wet - // (master volume is applied later to the result of both outputs added together). - return TD + ApplyVolume( RV, FxVol ); + WaveDump::WriteCore(Index, CoreSrc_PostReverb, RV); + + // Mix Dry + Wet + // (master volume is applied later to the result of both outputs added together). + return TD + ApplyVolume(RV, FxVol); } // Filters that work on the final output to de-alias and equlize it. @@ -725,185 +707,184 @@ StereoOut32 V_Core::Mix( const VoiceMixSet& inVoices, const StereoOut32& Input, StereoOut32 Apply_Frequency_Response_Filter(StereoOut32 &SoundStream) { - static FrequencyResponseFilter FRF = FrequencyResponseFilter(); + static FrequencyResponseFilter FRF = FrequencyResponseFilter(); - s32 in, out; - s32 l, r; - s32 mid, side; + s32 in, out; + s32 l, r; + s32 mid, side; - l = SoundStream.Left; - r = SoundStream.Right; + l = SoundStream.Left; + r = SoundStream.Right; - mid = l + r; - side = l - r; + mid = l + r; + side = l - r; - in = mid; - out = FRF.la0 * in + FRF.la1 * FRF.lx1 + FRF.la2 * FRF.lx2 - FRF.lb1 * FRF.ly1 - FRF.lb2 * FRF.ly2; + in = mid; + out = FRF.la0 * in + FRF.la1 * FRF.lx1 + FRF.la2 * FRF.lx2 - FRF.lb1 * FRF.ly1 - FRF.lb2 * FRF.ly2; - FRF.lx2 = FRF.lx1; - FRF.lx1 = in; + FRF.lx2 = FRF.lx1; + FRF.lx1 = in; - FRF.ly2 = FRF.ly1; - FRF.ly1 = out; + FRF.ly2 = FRF.ly1; + FRF.ly1 = out; - mid = out; + mid = out; - l = ((0.5) * (OVERALL_SCALE)) * (mid + side); - r = ((0.5) * (OVERALL_SCALE)) * (mid - side); + l = ((0.5) * (OVERALL_SCALE)) * (mid + side); + r = ((0.5) * (OVERALL_SCALE)) * (mid - side); - in = l; - out = FRF.ha0 * in + FRF.ha1 * FRF.History_One_In.Left + FRF.ha2 * FRF.History_Two_In.Left - FRF.hb1 * FRF.History_One_Out.Left - FRF.hb2 * FRF.History_Two_Out.Left; - FRF.History_Two_In.Left = FRF.History_One_In.Left; FRF.History_One_In.Left = in; - FRF.History_Two_Out.Left = FRF.History_One_Out.Left; FRF.History_One_Out.Left = out; - l = out; + in = l; + out = FRF.ha0 * in + FRF.ha1 * FRF.History_One_In.Left + FRF.ha2 * FRF.History_Two_In.Left - FRF.hb1 * FRF.History_One_Out.Left - FRF.hb2 * FRF.History_Two_Out.Left; + FRF.History_Two_In.Left = FRF.History_One_In.Left; + FRF.History_One_In.Left = in; + FRF.History_Two_Out.Left = FRF.History_One_Out.Left; + FRF.History_One_Out.Left = out; + l = out; - in = r; - out = FRF.ha0 * in + FRF.ha1 * FRF.History_One_In.Right + FRF.ha2 * FRF.History_Two_In.Right - FRF.hb1 * FRF.History_One_Out.Right - FRF.hb2 * FRF.History_Two_Out.Right; - FRF.History_Two_In.Right = FRF.History_One_In.Right; FRF.History_One_In.Right = in; - FRF.History_Two_Out.Right = FRF.History_One_Out.Right; FRF.History_One_Out.Right = out; - r = out; + in = r; + out = FRF.ha0 * in + FRF.ha1 * FRF.History_One_In.Right + FRF.ha2 * FRF.History_Two_In.Right - FRF.hb1 * FRF.History_One_Out.Right - FRF.hb2 * FRF.History_Two_Out.Right; + FRF.History_Two_In.Right = FRF.History_One_In.Right; + FRF.History_One_In.Right = in; + FRF.History_Two_Out.Right = FRF.History_One_Out.Right; + FRF.History_One_Out.Right = out; + r = out; - //clamp_mix(l); - //clamp_mix(r); + //clamp_mix(l); + //clamp_mix(r); - SoundStream.Left = l; - SoundStream.Right = r; + SoundStream.Left = l; + SoundStream.Right = r; - return SoundStream; + return SoundStream; } StereoOut32 Apply_Dealias_Filter(StereoOut32 &SoundStream) { - static StereoOut32 Old = StereoOut32::Empty; + static StereoOut32 Old = StereoOut32::Empty; - s32 l, r; + s32 l, r; - l = SoundStream.Left; - r = SoundStream.Right; + l = SoundStream.Left; + r = SoundStream.Right; - l += (l - Old.Left); - r += (r - Old.Right); + l += (l - Old.Left); + r += (r - Old.Right); - Old.Left = SoundStream.Left; - Old.Right = SoundStream.Right; + Old.Left = SoundStream.Left; + Old.Right = SoundStream.Right; - SoundStream.Left = l; - SoundStream.Right = r; + SoundStream.Left = l; + SoundStream.Right = r; - return SoundStream; + return SoundStream; } // used to throttle the output rate of cache stat reports -static int p_cachestat_counter=0; +static int p_cachestat_counter = 0; // Gcc does not want to inline it when lto is enabled because some functions growth too much. // The function is big enought to see any speed impact. -- Gregory #ifndef __POSIX__ __forceinline #endif -void Mix() + void + Mix() { - // Note: Playmode 4 is SPDIF, which overrides other inputs. - StereoOut32 InputData[2] = - { - // SPDIF is on Core 0: - // Fixme: - // 1. We do not have an AC3 decoder for the bitstream. - // 2. Games usually provide a normal ADMA stream as well and want to see it getting read! - /*(PlayMode&4) ? StereoOut32::Empty : */ApplyVolume( Cores[0].ReadInput(), Cores[0].InpVol ), + // Note: Playmode 4 is SPDIF, which overrides other inputs. + StereoOut32 InputData[2] = + { + // SPDIF is on Core 0: + // Fixme: + // 1. We do not have an AC3 decoder for the bitstream. + // 2. Games usually provide a normal ADMA stream as well and want to see it getting read! + /*(PlayMode&4) ? StereoOut32::Empty : */ ApplyVolume(Cores[0].ReadInput(), Cores[0].InpVol), - // CDDA is on Core 1: - (PlayMode&8) ? StereoOut32::Empty : ApplyVolume( Cores[1].ReadInput(), Cores[1].InpVol ) - }; + // CDDA is on Core 1: + (PlayMode & 8) ? StereoOut32::Empty : ApplyVolume(Cores[1].ReadInput(), Cores[1].InpVol)}; - WaveDump::WriteCore( 0, CoreSrc_Input, InputData[0] ); - WaveDump::WriteCore( 1, CoreSrc_Input, InputData[1] ); + WaveDump::WriteCore(0, CoreSrc_Input, InputData[0]); + WaveDump::WriteCore(1, CoreSrc_Input, InputData[1]); - // Todo: Replace me with memzero initializer! - VoiceMixSet VoiceData[2] = { VoiceMixSet::Empty, VoiceMixSet::Empty }; // mixed voice data for each core. - MixCoreVoices( VoiceData[0], 0 ); - MixCoreVoices( VoiceData[1], 1 ); + // Todo: Replace me with memzero initializer! + VoiceMixSet VoiceData[2] = {VoiceMixSet::Empty, VoiceMixSet::Empty}; // mixed voice data for each core. + MixCoreVoices(VoiceData[0], 0); + MixCoreVoices(VoiceData[1], 1); - StereoOut32 Ext( Cores[0].Mix( VoiceData[0], InputData[0], StereoOut32::Empty ) ); + StereoOut32 Ext(Cores[0].Mix(VoiceData[0], InputData[0], StereoOut32::Empty)); - if( (PlayMode & 4) || (Cores[0].Mute!=0) ) - Ext = StereoOut32::Empty; - else - { - Ext = clamp_mix( ApplyVolume( Ext, Cores[0].MasterVol ) ); - } + if ((PlayMode & 4) || (Cores[0].Mute != 0)) + Ext = StereoOut32::Empty; + else { + Ext = clamp_mix(ApplyVolume(Ext, Cores[0].MasterVol)); + } - // Commit Core 0 output to ram before mixing Core 1: - spu2M_WriteFast(0x800 + OutPos, Ext.Left); - spu2M_WriteFast(0xA00 + OutPos, Ext.Right); + // Commit Core 0 output to ram before mixing Core 1: + spu2M_WriteFast(0x800 + OutPos, Ext.Left); + spu2M_WriteFast(0xA00 + OutPos, Ext.Right); - WaveDump::WriteCore( 0, CoreSrc_External, Ext ); + WaveDump::WriteCore(0, CoreSrc_External, Ext); - Ext = ApplyVolume( Ext, Cores[1].ExtVol ); - StereoOut32 Out( Cores[1].Mix( VoiceData[1], InputData[1], Ext ) ); + Ext = ApplyVolume(Ext, Cores[1].ExtVol); + StereoOut32 Out(Cores[1].Mix(VoiceData[1], InputData[1], Ext)); - if( PlayMode & 8 ) - { - // Experimental CDDA support - // The CDDA overrides all other mixer output. It's a direct feed! + if (PlayMode & 8) { + // Experimental CDDA support + // The CDDA overrides all other mixer output. It's a direct feed! - Out = Cores[1].ReadInput_HiFi(); - //WaveLog::WriteCore( 1, "CDDA-32", OutL, OutR ); - } - else - { - Out.Left = MulShr32( Out.Left<<(SndOutVolumeShift+1), Cores[1].MasterVol.Left.Value ); - Out.Right = MulShr32( Out.Right<<(SndOutVolumeShift+1), Cores[1].MasterVol.Right.Value ); + Out = Cores[1].ReadInput_HiFi(); + //WaveLog::WriteCore( 1, "CDDA-32", OutL, OutR ); + } else { + Out.Left = MulShr32(Out.Left << (SndOutVolumeShift + 1), Cores[1].MasterVol.Left.Value); + Out.Right = MulShr32(Out.Right << (SndOutVolumeShift + 1), Cores[1].MasterVol.Right.Value); - #ifdef DEBUG_KEYS - if(postprocess_filter_enabled) - #endif - { - if(postprocess_filter_dealias) - { - // Dealias filter emphasizes the highs too much. - Out = Apply_Dealias_Filter ( Out ); - } - Out = Apply_Frequency_Response_Filter ( Out ); - } +#ifdef DEBUG_KEYS + if (postprocess_filter_enabled) +#endif + { + if (postprocess_filter_dealias) { + // Dealias filter emphasizes the highs too much. + Out = Apply_Dealias_Filter(Out); + } + Out = Apply_Frequency_Response_Filter(Out); + } - // Final Clamp! - // Like any good audio system, the PS2 pumps the volume and incurs some distortion in its - // output, giving us a nice thumpy sound at times. So we add 1 above (2x volume pump) and - // then clamp it all here. - - // Edit: I'm sorry Jake, but I know of no good audio system that arbitrary distorts and clips - // output by design. - // Good thing though that this code gets the volume exactly right, as per tests :) - Out = clamp_mix( Out, SndOutVolumeShift ); - } - - // Configurable output volume - Out.Left *= FinalVolume; - Out.Right *= FinalVolume; - - SndBuffer::Write( Out ); + // Final Clamp! + // Like any good audio system, the PS2 pumps the volume and incurs some distortion in its + // output, giving us a nice thumpy sound at times. So we add 1 above (2x volume pump) and + // then clamp it all here. - // Update AutoDMA output positioning - OutPos++; - if (OutPos>=0x200) OutPos=0; + // Edit: I'm sorry Jake, but I know of no good audio system that arbitrary distorts and clips + // output by design. + // Good thing though that this code gets the volume exactly right, as per tests :) + Out = clamp_mix(Out, SndOutVolumeShift); + } - if( IsDevBuild ) - { - p_cachestat_counter++; - if(p_cachestat_counter > (48000*10) ) - { - p_cachestat_counter = 0; - if( MsgCache() ) ConLog( " * SPU2 > CacheStats > Hits: %d Misses: %d Ignores: %d\n", - g_counter_cache_hits, - g_counter_cache_misses, - g_counter_cache_ignores ); + // Configurable output volume + Out.Left *= FinalVolume; + Out.Right *= FinalVolume; - g_counter_cache_hits = - g_counter_cache_misses = - g_counter_cache_ignores = 0; - } - } + SndBuffer::Write(Out); + + // Update AutoDMA output positioning + OutPos++; + if (OutPos >= 0x200) + OutPos = 0; + + if (IsDevBuild) { + p_cachestat_counter++; + if (p_cachestat_counter > (48000 * 10)) { + p_cachestat_counter = 0; + if (MsgCache()) + ConLog(" * SPU2 > CacheStats > Hits: %d Misses: %d Ignores: %d\n", + g_counter_cache_hits, + g_counter_cache_misses, + g_counter_cache_ignores); + + g_counter_cache_hits = + g_counter_cache_misses = + g_counter_cache_ignores = 0; + } + } } ///////////////////////////////////////////////////////////////////////////////////////// diff --git a/plugins/spu2-x/src/Mixer.h b/plugins/spu2-x/src/Mixer.h index fb4ebf649c..296d7c096a 100644 --- a/plugins/spu2-x/src/Mixer.h +++ b/plugins/spu2-x/src/Mixer.h @@ -24,115 +24,112 @@ extern float VolumeAdjustFR; struct StereoOut32 { - static StereoOut32 Empty; + static StereoOut32 Empty; - s32 Left; - s32 Right; + s32 Left; + s32 Right; - StereoOut32() : - Left( 0 ), - Right( 0 ) - { - } + StereoOut32() + : Left(0) + , Right(0) + { + } - StereoOut32( s32 left, s32 right ) : - Left( left ), - Right( right ) - { - } + StereoOut32(s32 left, s32 right) + : Left(left) + , Right(right) + { + } - StereoOut32( const StereoOut16& src ); - explicit StereoOut32( const StereoOutFloat& src ); + StereoOut32(const StereoOut16 &src); + explicit StereoOut32(const StereoOutFloat &src); - StereoOut16 DownSample() const; + StereoOut16 DownSample() const; - StereoOut32 operator*( const int& factor ) const - { - return StereoOut32( - Left * factor, - Right * factor - ); - } + StereoOut32 operator*(const int &factor) const + { + return StereoOut32( + Left * factor, + Right * factor); + } - StereoOut32& operator*=( const int& factor ) - { - Left *= factor; - Right *= factor; - return *this; - } + StereoOut32 &operator*=(const int &factor) + { + Left *= factor; + Right *= factor; + return *this; + } - StereoOut32 operator+( const StereoOut32& right ) const - { - return StereoOut32( - Left + right.Left, - Right + right.Right - ); - } + StereoOut32 operator+(const StereoOut32 &right) const + { + return StereoOut32( + Left + right.Left, + Right + right.Right); + } - StereoOut32 operator/( int src ) const - { - return StereoOut32( Left / src, Right / src ); - } + StereoOut32 operator/(int src) const + { + return StereoOut32(Left / src, Right / src); + } - void ResampleFrom( const StereoOut32& src ) - { - this->Left = src.Left << 2; - this->Right = src.Right << 2; - } + void ResampleFrom(const StereoOut32 &src) + { + this->Left = src.Left << 2; + this->Right = src.Right << 2; + } - void AdjustFrom(const StereoOut32& src) - { - ResampleFrom(src); + void AdjustFrom(const StereoOut32 &src) + { + ResampleFrom(src); - Left = (s32) (Left * VolumeAdjustFL); - Right = (s32) (Right * VolumeAdjustFR); - } + Left = (s32)(Left * VolumeAdjustFL); + Right = (s32)(Right * VolumeAdjustFR); + } }; struct FrequencyResponseFilter { - static FrequencyResponseFilter Empty; + static FrequencyResponseFilter Empty; - StereoOut32 History_One_In; - StereoOut32 History_One_Out; - StereoOut32 History_Two_In; - StereoOut32 History_Two_Out; + StereoOut32 History_One_In; + StereoOut32 History_One_Out; + StereoOut32 History_Two_In; + StereoOut32 History_Two_Out; - s32 lx1; - s32 lx2; - s32 ly1; - s32 ly2; + s32 lx1; + s32 lx2; + s32 ly1; + s32 ly2; - float la0, la1, la2, lb1, lb2; - float ha0, ha1, ha2, hb1, hb2; + float la0, la1, la2, lb1, lb2; + float ha0, ha1, ha2, hb1, hb2; - FrequencyResponseFilter() : - History_One_In( 0, 0 ), - History_One_Out( 0, 0 ), - History_Two_In( 0, 0 ), - History_Two_Out( 0, 0 ), - lx1 ( 0 ), - lx2 ( 0 ), - ly1 ( 0 ), - ly2 ( 0 ), - - la0 ( 1.00320890889339290000f ), - la1 ( -1.97516434134506300000f ), - la2 ( 0.97243484967313087000f ), - lb1 ( -1.97525280404731810000f ), - lb2 ( 0.97555529586426892000f ), + FrequencyResponseFilter() + : History_One_In(0, 0) + , History_One_Out(0, 0) + , History_Two_In(0, 0) + , History_Two_Out(0, 0) + , lx1(0) + , lx2(0) + , ly1(0) + , ly2(0) - ha0 ( 1.52690772687271160000f ), - ha1 ( -1.62653918974914990000f ), //-1.72 = "common equilizer curve" --____-- - ha2 ( 0.57997976029249387000f ), - hb1 ( -0.80955590379048203000f ), - hb2 ( 0.28990420120653748000f ) - { - } + , la0(1.00320890889339290000f) + , la1(-1.97516434134506300000f) + , la2(0.97243484967313087000f) + , lb1(-1.97525280404731810000f) + , lb2(0.97555529586426892000f) + , ha0(1.52690772687271160000f) + , ha1(-1.62653918974914990000f) //-1.72 = "common equilizer curve" --____-- + , ha2(0.57997976029249387000f) + , hb1(-0.80955590379048203000f) + , hb2(0.28990420120653748000f) + { + } }; -extern void Mix(); -extern s32 clamp_mix( s32 x, u8 bitshift=0 ); +extern void Mix(); +extern s32 clamp_mix(s32 x, u8 bitshift = 0); -extern StereoOut32 clamp_mix( const StereoOut32& sample, u8 bitshift=0 ); +extern StereoOut32 clamp_mix(const StereoOut32 &sample, u8 bitshift = 0); diff --git a/plugins/spu2-x/src/PS2E-spu2.cpp b/plugins/spu2-x/src/PS2E-spu2.cpp index 4fe428c1bd..c1c05e6d65 100644 --- a/plugins/spu2-x/src/PS2E-spu2.cpp +++ b/plugins/spu2-x/src/PS2E-spu2.cpp @@ -33,28 +33,25 @@ static char libraryName[256]; -static bool IsOpened = false; -static bool IsInitialized = false; +static bool IsOpened = false; +static bool IsInitialized = false; -static u32 pClocks = 0; +static u32 pClocks = 0; -u32* cyclePtr = NULL; -u32 lClocks = 0; +u32 *cyclePtr = NULL; +u32 lClocks = 0; #ifdef _MSC_VER HINSTANCE hInstance; BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD dwReason, LPVOID lpvReserved) { - if( dwReason == DLL_PROCESS_ATTACH ) - { - hInstance = hinstDLL; - } - else if( dwReason == DLL_PROCESS_DETACH ) - { - // TODO : perform shutdown procedure, just in case PCSX2 itself failed - // to for some reason.. - } - return TRUE; + if (dwReason == DLL_PROCESS_ATTACH) { + hInstance = hinstDLL; + } else if (dwReason == DLL_PROCESS_DETACH) { + // TODO : perform shutdown procedure, just in case PCSX2 itself failed + // to for some reason.. + } + return TRUE; } #endif @@ -62,59 +59,58 @@ static void InitLibraryName() { #ifdef SPU2X_PUBLIC_RELEASE - // Public Release! - // Output a simplified string that's just our name: + // Public Release! + // Output a simplified string that's just our name: - strcpy( libraryName, "SPU2-X" ); + strcpy(libraryName, "SPU2-X"); #else - #ifdef SVN_REV_UNKNOWN +#ifdef SVN_REV_UNKNOWN - // Unknown revision. - // Output a name that includes devbuild status but not - // subversion revision tags: + // Unknown revision. + // Output a name that includes devbuild status but not + // subversion revision tags: - strcpy( libraryName, "SPU2-X" - #ifdef DEBUG_FAST - "-Debug" - #elif defined( PCSX2_DEBUG ) - "-Debug/Strict" // strict debugging is slow! - #elif defined( PCSX2_DEVBUILD ) - "-Dev" - #else - "" - #endif - ); - - #else - - // Use TortoiseSVN's SubWCRev utility's output - // to label the specific revision: - - snprintf( libraryName, 255, "SPU2-X %lld%s" - #ifdef DEBUG_FAST - "-Debug" - #elif defined( PCSX2_DEBUG ) - "-Debug/Strict" // strict debugging is slow! - #elif defined( PCSX2_DEVBUILD ) - "-Dev" - #else - "" - #endif - ,SVN_REV, SVN_MODS ? "m" : "" - ); - #endif + strcpy(libraryName, "SPU2-X" +#ifdef DEBUG_FAST + "-Debug" +#elif defined(PCSX2_DEBUG) + "-Debug/Strict" // strict debugging is slow! +#elif defined(PCSX2_DEVBUILD) + "-Dev" +#else + "" #endif + ); +#else + + // Use TortoiseSVN's SubWCRev utility's output + // to label the specific revision: + + snprintf(libraryName, 255, "SPU2-X %lld%s" +#ifdef DEBUG_FAST + "-Debug" +#elif defined(PCSX2_DEBUG) + "-Debug/Strict" // strict debugging is slow! +#elif defined(PCSX2_DEVBUILD) + "-Dev" +#else + "" +#endif + , + SVN_REV, SVN_MODS ? "m" : ""); +#endif +#endif } //static bool cpu_detected = false; static bool CheckSSE() { - return true; + return true; - #if 0 +#if 0 if( !cpu_detected ) { cpudetectInit(); @@ -126,263 +122,286 @@ static bool CheckSSE() return false; } return true; - #endif +#endif } -EXPORT_C_(u32) PS2EgetLibType() +EXPORT_C_(u32) +PS2EgetLibType() { - return PS2E_LT_SPU2; + return PS2E_LT_SPU2; } -EXPORT_C_(char*) PS2EgetLibName() +EXPORT_C_(char *) +PS2EgetLibName() { - InitLibraryName(); - return libraryName; + InitLibraryName(); + return libraryName; } -EXPORT_C_(u32) PS2EgetLibVersion2(u32 type) +EXPORT_C_(u32) +PS2EgetLibVersion2(u32 type) { - return (PS2E_SPU2_VERSION<<16) | (VersionInfo::Release<<8) | VersionInfo::Revision; + return (PS2E_SPU2_VERSION << 16) | (VersionInfo::Release << 8) | VersionInfo::Revision; } -EXPORT_C_(void) SPU2configure() +EXPORT_C_(void) +SPU2configure() { - if( !CheckSSE() ) return; - configure(); + if (!CheckSSE()) + return; + configure(); } -EXPORT_C_(void) SPU2about() +EXPORT_C_(void) +SPU2about() { - AboutBox(); + AboutBox(); } -EXPORT_C_(s32) SPU2test() +EXPORT_C_(s32) +SPU2test() { - if( !CheckSSE() ) return -1; + if (!CheckSSE()) + return -1; #ifdef _WIN32 - if (IsWindows8OrGreater()) - { - for (int n = 0; mods[n] != nullptr; ++n) - { - if (mods[n] == XAudio2_27_Out) - { - mods[n] = XAudio2Out; - break; - } - } - } + if (IsWindows8OrGreater()) { + for (int n = 0; mods[n] != nullptr; ++n) { + if (mods[n] == XAudio2_27_Out) { + mods[n] = XAudio2Out; + break; + } + } + } #endif - ReadSettings(); - if( SndBuffer::Test() != 0 ) - { - // TODO : Implement a proper dialog that allows the user to test different audio out drivers. - const wchar_t* wtf = mods[OutputModule]->GetIdent(); - SysMessage( L"The '%s' driver test failed. Please configure\na different SoundOut module and try again.", wtf ); - return -1; - } + ReadSettings(); + if (SndBuffer::Test() != 0) { + // TODO : Implement a proper dialog that allows the user to test different audio out drivers. + const wchar_t *wtf = mods[OutputModule]->GetIdent(); + SysMessage(L"The '%s' driver test failed. Please configure\na different SoundOut module and try again.", wtf); + return -1; + } - return 0; + return 0; } // -------------------------------------------------------------------------------------- // DMA 4/7 Callbacks from Core Emulator // -------------------------------------------------------------------------------------- -u16* DMABaseAddr; -void (* _irqcallback)(); -void (* dma4callback)(); -void (* dma7callback)(); +u16 *DMABaseAddr; +void (*_irqcallback)(); +void (*dma4callback)(); +void (*dma7callback)(); -EXPORT_C_(u32) CALLBACK SPU2ReadMemAddr(int core) +EXPORT_C_(u32) +CALLBACK SPU2ReadMemAddr(int core) { - return Cores[core].MADR; + return Cores[core].MADR; } -EXPORT_C_(void) CALLBACK SPU2WriteMemAddr(int core,u32 value) +EXPORT_C_(void) +CALLBACK SPU2WriteMemAddr(int core, u32 value) { - Cores[core].MADR = value; + Cores[core].MADR = value; } -EXPORT_C_(void) CALLBACK SPU2setDMABaseAddr(uptr baseaddr) +EXPORT_C_(void) +CALLBACK SPU2setDMABaseAddr(uptr baseaddr) { - DMABaseAddr = (u16*)baseaddr; + DMABaseAddr = (u16 *)baseaddr; } -EXPORT_C_(void) CALLBACK SPU2setSettingsDir(const char* dir) +EXPORT_C_(void) +CALLBACK SPU2setSettingsDir(const char *dir) { - CfgSetSettingsDir( dir ); + CfgSetSettingsDir(dir); } -EXPORT_C_(void) CALLBACK SPU2setLogDir(const char* dir) +EXPORT_C_(void) +CALLBACK SPU2setLogDir(const char *dir) { - CfgSetLogDir( dir ); + CfgSetLogDir(dir); } -EXPORT_C_(s32) SPU2dmaRead(s32 channel, u32* data, u32 bytesLeft, u32* bytesProcessed) +EXPORT_C_(s32) +SPU2dmaRead(s32 channel, u32 *data, u32 bytesLeft, u32 *bytesProcessed) { - if(channel==4) - return Cores[0].NewDmaRead(data,bytesLeft, bytesProcessed); - else - return Cores[1].NewDmaRead(data,bytesLeft, bytesProcessed); + if (channel == 4) + return Cores[0].NewDmaRead(data, bytesLeft, bytesProcessed); + else + return Cores[1].NewDmaRead(data, bytesLeft, bytesProcessed); } -EXPORT_C_(s32) SPU2dmaWrite(s32 channel, u32* data, u32 bytesLeft, u32* bytesProcessed) +EXPORT_C_(s32) +SPU2dmaWrite(s32 channel, u32 *data, u32 bytesLeft, u32 *bytesProcessed) { - if(channel==4) - return Cores[0].NewDmaWrite(data,bytesLeft, bytesProcessed); - else - return Cores[1].NewDmaWrite(data,bytesLeft, bytesProcessed); + if (channel == 4) + return Cores[0].NewDmaWrite(data, bytesLeft, bytesProcessed); + else + return Cores[1].NewDmaWrite(data, bytesLeft, bytesProcessed); } -EXPORT_C_(void) SPU2dmaInterrupt(s32 channel) +EXPORT_C_(void) +SPU2dmaInterrupt(s32 channel) { - if(channel==4) - return Cores[0].NewDmaInterrupt(); - else - return Cores[1].NewDmaInterrupt(); + if (channel == 4) + return Cores[0].NewDmaInterrupt(); + else + return Cores[1].NewDmaInterrupt(); } #ifdef ENABLE_NEW_IOPDMA_SPU2 -EXPORT_C_(void) SPU2irqCallback(void (*SPU2callback)()) +EXPORT_C_(void) +SPU2irqCallback(void (*SPU2callback)()) { - _irqcallback = SPU2callback; + _irqcallback = SPU2callback; } #else -EXPORT_C_(void) SPU2irqCallback(void (*SPU2callback)(),void (*DMA4callback)(),void (*DMA7callback)()) +EXPORT_C_(void) +SPU2irqCallback(void (*SPU2callback)(), void (*DMA4callback)(), void (*DMA7callback)()) { - _irqcallback = SPU2callback; - dma4callback = DMA4callback; - dma7callback = DMA7callback; + _irqcallback = SPU2callback; + dma4callback = DMA4callback; + dma7callback = DMA7callback; } #endif -EXPORT_C_(void) CALLBACK SPU2readDMA4Mem(u16 *pMem, u32 size) // size now in 16bit units +EXPORT_C_(void) +CALLBACK SPU2readDMA4Mem(u16 *pMem, u32 size) // size now in 16bit units { - if( cyclePtr != NULL ) TimeUpdate( *cyclePtr ); + if (cyclePtr != NULL) + TimeUpdate(*cyclePtr); - FileLog("[%10d] SPU2 readDMA4Mem size %x\n",Cycles, size<<1); - Cores[0].DoDMAread(pMem, size); + FileLog("[%10d] SPU2 readDMA4Mem size %x\n", Cycles, size << 1); + Cores[0].DoDMAread(pMem, size); } -EXPORT_C_(void) CALLBACK SPU2writeDMA4Mem(u16* pMem, u32 size) // size now in 16bit units +EXPORT_C_(void) +CALLBACK SPU2writeDMA4Mem(u16 *pMem, u32 size) // size now in 16bit units { - if( cyclePtr != NULL ) TimeUpdate( *cyclePtr ); + if (cyclePtr != NULL) + TimeUpdate(*cyclePtr); - FileLog("[%10d] SPU2 writeDMA4Mem size %x at address %x\n",Cycles, size<<1, Cores[0].TSA); + FileLog("[%10d] SPU2 writeDMA4Mem size %x at address %x\n", Cycles, size << 1, Cores[0].TSA); #ifdef S2R_ENABLE - if(!replay_mode) - s2r_writedma4(Cycles,pMem,size); + if (!replay_mode) + s2r_writedma4(Cycles, pMem, size); #endif - Cores[0].DoDMAwrite(pMem,size); + Cores[0].DoDMAwrite(pMem, size); } -EXPORT_C_(void) CALLBACK SPU2interruptDMA4() +EXPORT_C_(void) +CALLBACK SPU2interruptDMA4() { - FileLog("[%10d] SPU2 interruptDMA4\n",Cycles); - Cores[0].Regs.STATX |= 0x80; - //Cores[0].Regs.ATTR &= ~0x30; + FileLog("[%10d] SPU2 interruptDMA4\n", Cycles); + Cores[0].Regs.STATX |= 0x80; + //Cores[0].Regs.ATTR &= ~0x30; } -EXPORT_C_(void) CALLBACK SPU2interruptDMA7() +EXPORT_C_(void) +CALLBACK SPU2interruptDMA7() { - FileLog("[%10d] SPU2 interruptDMA7\n",Cycles); - Cores[1].Regs.STATX |= 0x80; - //Cores[1].Regs.ATTR &= ~0x30; + FileLog("[%10d] SPU2 interruptDMA7\n", Cycles); + Cores[1].Regs.STATX |= 0x80; + //Cores[1].Regs.ATTR &= ~0x30; } -EXPORT_C_(void) CALLBACK SPU2readDMA7Mem(u16* pMem, u32 size) +EXPORT_C_(void) +CALLBACK SPU2readDMA7Mem(u16 *pMem, u32 size) { - if( cyclePtr != NULL ) TimeUpdate( *cyclePtr ); + if (cyclePtr != NULL) + TimeUpdate(*cyclePtr); - FileLog("[%10d] SPU2 readDMA7Mem size %x\n",Cycles, size<<1); - Cores[1].DoDMAread(pMem,size); + FileLog("[%10d] SPU2 readDMA7Mem size %x\n", Cycles, size << 1); + Cores[1].DoDMAread(pMem, size); } -EXPORT_C_(void) CALLBACK SPU2writeDMA7Mem(u16* pMem, u32 size) +EXPORT_C_(void) +CALLBACK SPU2writeDMA7Mem(u16 *pMem, u32 size) { - if( cyclePtr != NULL ) TimeUpdate( *cyclePtr ); + if (cyclePtr != NULL) + TimeUpdate(*cyclePtr); - FileLog("[%10d] SPU2 writeDMA7Mem size %x at address %x\n",Cycles, size<<1, Cores[1].TSA); + FileLog("[%10d] SPU2 writeDMA7Mem size %x at address %x\n", Cycles, size << 1, Cores[1].TSA); #ifdef S2R_ENABLE - if(!replay_mode) - s2r_writedma7(Cycles,pMem,size); + if (!replay_mode) + s2r_writedma7(Cycles, pMem, size); #endif - Cores[1].DoDMAwrite(pMem,size); + Cores[1].DoDMAwrite(pMem, size); } -EXPORT_C_(void) SPU2reset() +EXPORT_C_(void) +SPU2reset() { - memset(spu2regs, 0, 0x010000); - memset(_spu2mem, 0, 0x200000); - memset(_spu2mem + 0x2800, 7, 0x10); // from BIOS reversal. Locks the voices so they don't run free. - Cores[0].Init(0); - Cores[1].Init(1); + memset(spu2regs, 0, 0x010000); + memset(_spu2mem, 0, 0x200000); + memset(_spu2mem + 0x2800, 7, 0x10); // from BIOS reversal. Locks the voices so they don't run free. + Cores[0].Init(0); + Cores[1].Init(1); } -EXPORT_C_(s32) SPU2init() +EXPORT_C_(s32) +SPU2init() { - assert( regtable[0x400] == NULL ); + assert(regtable[0x400] == NULL); - if (IsInitialized) - { - printf( " * SPU2-X: Already initialized - Ignoring SPU2init signal." ); - return 0; - } + if (IsInitialized) { + printf(" * SPU2-X: Already initialized - Ignoring SPU2init signal."); + return 0; + } - IsInitialized = true; + IsInitialized = true; - ReadSettings(); + ReadSettings(); #ifdef SPU2_LOG - if(AccessLog()) - { - spu2Log = OpenLog( AccessLogFileName ); - setvbuf(spu2Log, NULL, _IONBF, 0); - FileLog("SPU2init\n"); - } + if (AccessLog()) { + spu2Log = OpenLog(AccessLogFileName); + setvbuf(spu2Log, NULL, _IONBF, 0); + FileLog("SPU2init\n"); + } #endif - srand((unsigned)time(NULL)); + srand((unsigned)time(NULL)); - spu2regs = (s16*)malloc(0x010000); - _spu2mem = (s16*)malloc(0x200000); + spu2regs = (s16 *)malloc(0x010000); + _spu2mem = (s16 *)malloc(0x200000); - // adpcm decoder cache: - // the cache data size is determined by taking the number of adpcm blocks - // (2MB / 16) and multiplying it by the decoded block size (28 samples). - // Thus: pcm_cache_data = 7,340,032 bytes (ouch!) - // Expanded: 16 bytes expands to 56 bytes [3.5:1 ratio] - // Resulting in 2MB * 3.5. + // adpcm decoder cache: + // the cache data size is determined by taking the number of adpcm blocks + // (2MB / 16) and multiplying it by the decoded block size (28 samples). + // Thus: pcm_cache_data = 7,340,032 bytes (ouch!) + // Expanded: 16 bytes expands to 56 bytes [3.5:1 ratio] + // Resulting in 2MB * 3.5. - pcm_cache_data = (PcmCacheEntry*)calloc( pcm_BlockCount, sizeof(PcmCacheEntry) ); + pcm_cache_data = (PcmCacheEntry *)calloc(pcm_BlockCount, sizeof(PcmCacheEntry)); - if( (spu2regs == NULL) || (_spu2mem == NULL) || (pcm_cache_data == NULL) ) - { - SysMessage("SPU2-X: Error allocating Memory\n"); return -1; - } - - // Patch up a copy of regtable that directly maps "NULLs" to SPU2 memory. - - memcpy(regtable, regtable_original, sizeof(regtable)); + if ((spu2regs == NULL) || (_spu2mem == NULL) || (pcm_cache_data == NULL)) { + SysMessage("SPU2-X: Error allocating Memory\n"); + return -1; + } - for(uint mem=0;mem<0x800;mem++) - { - u16 *ptr = regtable[mem>>1]; - if(!ptr) { - regtable[mem>>1] = &(spu2Ru16(mem)); - } - } + // Patch up a copy of regtable that directly maps "NULLs" to SPU2 memory. - SPU2reset(); + memcpy(regtable, regtable_original, sizeof(regtable)); - DMALogOpen(); - InitADSR(); + for (uint mem = 0; mem < 0x800; mem++) { + u16 *ptr = regtable[mem >> 1]; + if (!ptr) { + regtable[mem >> 1] = &(spu2Ru16(mem)); + } + } + + SPU2reset(); + + DMALogOpen(); + InitADSR(); #ifdef S2R_ENABLE - if(!replay_mode) - s2r_open(Cycles,"replay_dump.s2r"); + if (!replay_mode) + s2r_open(Cycles, "replay_dump.s2r"); #endif - return 0; + return 0; } #ifdef _MSC_VER @@ -390,150 +409,148 @@ EXPORT_C_(s32) SPU2init() extern bool debugDialogOpen; extern HWND hDebugDialog; -static INT_PTR CALLBACK DebugProc(HWND hWnd,UINT uMsg,WPARAM wParam,LPARAM lParam) +static INT_PTR CALLBACK DebugProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { - int wmId; + int wmId; - switch(uMsg) - { - case WM_PAINT: - return FALSE; - case WM_INITDIALOG: - { - debugDialogOpen=true; - } - break; + switch (uMsg) { + case WM_PAINT: + return FALSE; + case WM_INITDIALOG: { + debugDialogOpen = true; + } break; - case WM_COMMAND: - wmId = LOWORD(wParam); - // Parse the menu selections: - switch (wmId) - { - case IDOK: - case IDCANCEL: - debugDialogOpen=false; - EndDialog(hWnd,0); - break; - default: - return FALSE; - } - break; + case WM_COMMAND: + wmId = LOWORD(wParam); + // Parse the menu selections: + switch (wmId) { + case IDOK: + case IDCANCEL: + debugDialogOpen = false; + EndDialog(hWnd, 0); + break; + default: + return FALSE; + } + break; - default: - return FALSE; - } - return TRUE; + default: + return FALSE; + } + return TRUE; } #endif uptr gsWindowHandle = 0; -EXPORT_C_(s32) SPU2open(void *pDsp) +EXPORT_C_(s32) +SPU2open(void *pDsp) { - if( IsOpened ) return 0; + if (IsOpened) + return 0; - FileLog("[%10d] SPU2 Open\n",Cycles); + FileLog("[%10d] SPU2 Open\n", Cycles); - if( pDsp != NULL ) - gsWindowHandle = *(uptr*)pDsp; - else - gsWindowHandle = 0; + if (pDsp != NULL) + gsWindowHandle = *(uptr *)pDsp; + else + gsWindowHandle = 0; #ifdef _MSC_VER -#ifdef PCSX2_DEVBUILD // Define may not be needed but not tested yet. Better make sure. - if( IsDevBuild && VisualDebug() ) - { - if(debugDialogOpen==0) - { - hDebugDialog = CreateDialogParam(hInstance,MAKEINTRESOURCE(IDD_DEBUG),0,DebugProc,0); - ShowWindow(hDebugDialog,SW_SHOWNORMAL); - debugDialogOpen=1; - } - } - else if(debugDialogOpen) - { - DestroyWindow(hDebugDialog); - debugDialogOpen=0; - } +#ifdef PCSX2_DEVBUILD // Define may not be needed but not tested yet. Better make sure. + if (IsDevBuild && VisualDebug()) { + if (debugDialogOpen == 0) { + hDebugDialog = CreateDialogParam(hInstance, MAKEINTRESOURCE(IDD_DEBUG), 0, DebugProc, 0); + ShowWindow(hDebugDialog, SW_SHOWNORMAL); + debugDialogOpen = 1; + } + } else if (debugDialogOpen) { + DestroyWindow(hDebugDialog); + debugDialogOpen = 0; + } #endif #endif - IsOpened = true; - lClocks = (cyclePtr!=NULL) ? *cyclePtr : 0; + IsOpened = true; + lClocks = (cyclePtr != NULL) ? *cyclePtr : 0; - try - { - SndBuffer::Init(); - -#ifndef __POSIX__ - DspLoadLibrary(dspPlugin,dspPluginModule); -#endif - WaveDump::Open(); - } - catch( std::exception& ex ) - { - fprintf( stderr, "SPU2-X Error: Could not initialize device, or something.\nReason: %s", ex.what() ); - SPU2close(); - return -1; - } - return 0; -} - -EXPORT_C_(void) SPU2close() -{ - if( !IsOpened ) return; - IsOpened = false; - - FileLog("[%10d] SPU2 Close\n",Cycles); + try { + SndBuffer::Init(); #ifndef __POSIX__ - DspCloseLibrary(); + DspLoadLibrary(dspPlugin, dspPluginModule); #endif - - SndBuffer::Cleanup(); + WaveDump::Open(); + } catch (std::exception &ex) { + fprintf(stderr, "SPU2-X Error: Could not initialize device, or something.\nReason: %s", ex.what()); + SPU2close(); + return -1; + } + return 0; } -EXPORT_C_(void) SPU2shutdown() +EXPORT_C_(void) +SPU2close() { - if(!IsInitialized) return; - IsInitialized = false; + if (!IsOpened) + return; + IsOpened = false; - ConLog( "* SPU2-X: Shutting down.\n" ); + FileLog("[%10d] SPU2 Close\n", Cycles); - SPU2close(); +#ifndef __POSIX__ + DspCloseLibrary(); +#endif + + SndBuffer::Cleanup(); +} + +EXPORT_C_(void) +SPU2shutdown() +{ + if (!IsInitialized) + return; + IsInitialized = false; + + ConLog("* SPU2-X: Shutting down.\n"); + + SPU2close(); #ifdef S2R_ENABLE - if(!replay_mode) - s2r_close(); + if (!replay_mode) + s2r_close(); #endif - DoFullDump(); + DoFullDump(); #ifdef STREAM_DUMP - fclose(il0); - fclose(il1); + fclose(il0); + fclose(il1); #endif #ifdef EFFECTS_DUMP - fclose(el0); - fclose(el1); + fclose(el0); + fclose(el1); #endif - WaveDump::Close(); + WaveDump::Close(); - DMALogClose(); + DMALogClose(); - safe_free(spu2regs); - safe_free(_spu2mem); - safe_free( pcm_cache_data ); + safe_free(spu2regs); + safe_free(_spu2mem); + safe_free(pcm_cache_data); #ifdef SPU2_LOG - if(!AccessLog()) return; - FileLog("[%10d] SPU2shutdown\n",Cycles); - if(spu2Log) fclose(spu2Log); + if (!AccessLog()) + return; + FileLog("[%10d] SPU2shutdown\n", Cycles); + if (spu2Log) + fclose(spu2Log); #endif } -EXPORT_C_(void) SPU2setClockPtr(u32 *ptr) +EXPORT_C_(void) +SPU2setClockPtr(u32 *ptr) { - cyclePtr = ptr; + cyclePtr = ptr; } #ifdef DEBUG_KEYS @@ -541,167 +558,169 @@ static u32 lastTicks; static bool lState[6]; #endif -EXPORT_C_(void) SPU2async(u32 cycles) +EXPORT_C_(void) +SPU2async(u32 cycles) { - DspUpdate(); + DspUpdate(); - if(cyclePtr != NULL) - { - TimeUpdate( *cyclePtr ); - } - else - { - pClocks += cycles; - TimeUpdate( pClocks ); - } + if (cyclePtr != NULL) { + TimeUpdate(*cyclePtr); + } else { + pClocks += cycles; + TimeUpdate(pClocks); + } #ifdef DEBUG_KEYS - u32 curTicks = GetTickCount(); - if((curTicks - lastTicks) >= 50) - { - int oldI = Interpolation; - bool cState[6]; - for(int i=0;i<6;i++) - { - cState[i] = !!(GetAsyncKeyState(VK_NUMPAD0+i)&0x8000); + u32 curTicks = GetTickCount(); + if ((curTicks - lastTicks) >= 50) { + int oldI = Interpolation; + bool cState[6]; + for (int i = 0; i < 6; i++) { + cState[i] = !!(GetAsyncKeyState(VK_NUMPAD0 + i) & 0x8000); - if((cState[i] && !lState[i]) && i != 5) - Interpolation = i; + if ((cState[i] && !lState[i]) && i != 5) + Interpolation = i; - if((cState[i] && !lState[i]) && i == 5) - { - postprocess_filter_enabled = !postprocess_filter_enabled; - printf("Post process filters %s \n", postprocess_filter_enabled? "enabled" : "disabled"); - } + if ((cState[i] && !lState[i]) && i == 5) { + postprocess_filter_enabled = !postprocess_filter_enabled; + printf("Post process filters %s \n", postprocess_filter_enabled ? "enabled" : "disabled"); + } - lState[i] = cState[i]; - } + lState[i] = cState[i]; + } - if(Interpolation != oldI) - { - printf("Interpolation set to %d", Interpolation); - switch(Interpolation) - { - case 0: printf(" - Nearest.\n"); break; - case 1: printf(" - Linear.\n"); break; - case 2: printf(" - Cubic.\n"); break; - case 3: printf(" - Hermite.\n"); break; - case 4: printf(" - Catmull-Rom.\n"); break; - default: printf(" (unknown).\n"); break; - } - } + if (Interpolation != oldI) { + printf("Interpolation set to %d", Interpolation); + switch (Interpolation) { + case 0: + printf(" - Nearest.\n"); + break; + case 1: + printf(" - Linear.\n"); + break; + case 2: + printf(" - Cubic.\n"); + break; + case 3: + printf(" - Hermite.\n"); + break; + case 4: + printf(" - Catmull-Rom.\n"); + break; + default: + printf(" (unknown).\n"); + break; + } + } - lastTicks = curTicks; - } + lastTicks = curTicks; + } #endif } -EXPORT_C_(u16) SPU2read(u32 rmem) +EXPORT_C_(u16) +SPU2read(u32 rmem) { - // if(!replay_mode) - // s2r_readreg(Cycles,rmem); + // if(!replay_mode) + // s2r_readreg(Cycles,rmem); - u16 ret=0xDEAD; u32 core=0, mem=rmem&0xFFFF, omem=mem; - if (mem & 0x400) { omem^=0x400; core=1; } + u16 ret = 0xDEAD; + u32 core = 0, mem = rmem & 0xFFFF, omem = mem; + if (mem & 0x400) { + omem ^= 0x400; + core = 1; + } - if(omem == 0x1f9001AC) - { - ret = Cores[core].DmaRead(); - } - else - { - if( cyclePtr != NULL ) - TimeUpdate( *cyclePtr ); + if (omem == 0x1f9001AC) { + ret = Cores[core].DmaRead(); + } else { + if (cyclePtr != NULL) + TimeUpdate(*cyclePtr); - if (rmem>>16 == 0x1f80) - { - ret = Cores[0].ReadRegPS1(rmem); - } - else if (mem >= 0x800) - { - ret = spu2Ru16(mem); - ConLog("* SPU2-X: Read from reg>=0x800: %x value %x\n",mem,ret); - } - else - { - ret = *(regtable[(mem>>1)]); - //FileLog("[%10d] SPU2 read mem %x (core %d, register %x): %x\n",Cycles, mem, core, (omem & 0x7ff), ret); - SPU2writeLog( "read", rmem, ret ); - } - } + if (rmem >> 16 == 0x1f80) { + ret = Cores[0].ReadRegPS1(rmem); + } else if (mem >= 0x800) { + ret = spu2Ru16(mem); + ConLog("* SPU2-X: Read from reg>=0x800: %x value %x\n", mem, ret); + } else { + ret = *(regtable[(mem >> 1)]); + //FileLog("[%10d] SPU2 read mem %x (core %d, register %x): %x\n",Cycles, mem, core, (omem & 0x7ff), ret); + SPU2writeLog("read", rmem, ret); + } + } - return ret; + return ret; } -EXPORT_C_(void) SPU2write(u32 rmem, u16 value) +EXPORT_C_(void) +SPU2write(u32 rmem, u16 value) { #ifdef S2R_ENABLE - if(!replay_mode) - s2r_writereg(Cycles,rmem,value); + if (!replay_mode) + s2r_writereg(Cycles, rmem, value); #endif - // Note: Reverb/Effects are very sensitive to having precise update timings. - // If the SPU2 isn't in in sync with the IOP, samples can end up playing at rather - // incorrect pitches and loop lengths. + // Note: Reverb/Effects are very sensitive to having precise update timings. + // If the SPU2 isn't in in sync with the IOP, samples can end up playing at rather + // incorrect pitches and loop lengths. - if( cyclePtr != NULL ) - TimeUpdate( *cyclePtr ); + if (cyclePtr != NULL) + TimeUpdate(*cyclePtr); - if (rmem>>16 == 0x1f80) - Cores[0].WriteRegPS1(rmem,value); - else - { - SPU2writeLog( "write", rmem, value ); - SPU2_FastWrite( rmem, value ); - } + if (rmem >> 16 == 0x1f80) + Cores[0].WriteRegPS1(rmem, value); + else { + SPU2writeLog("write", rmem, value); + SPU2_FastWrite(rmem, value); + } } // if start is 1, starts recording spu2 data, else stops // returns a non zero value if successful // for now, pData is not used -EXPORT_C_(int) SPU2setupRecording(int start, void* pData) +EXPORT_C_(int) +SPU2setupRecording(int start, void *pData) { - if(start==0) - RecordStop(); - else if(start==1) - RecordStart(); + if (start == 0) + RecordStop(); + else if (start == 1) + RecordStart(); - return 0; + return 0; } -EXPORT_C_(s32) SPU2freeze(int mode, freezeData *data) +EXPORT_C_(s32) +SPU2freeze(int mode, freezeData *data) { - pxAssume( data != NULL ); - if ( !data ) - { - printf("SPU2-X savestate null pointer!\n"); - return -1; - } + pxAssume(data != NULL); + if (!data) { + printf("SPU2-X savestate null pointer!\n"); + return -1; + } - if( mode == FREEZE_SIZE ) - { - data->size = Savestate::SizeIt(); - return 0; - } + if (mode == FREEZE_SIZE) { + data->size = Savestate::SizeIt(); + return 0; + } - pxAssume( mode == FREEZE_LOAD || mode == FREEZE_SAVE ); + pxAssume(mode == FREEZE_LOAD || mode == FREEZE_SAVE); - if( data->data == NULL ) - { - printf("SPU2-X savestate null pointer!\n"); - return -1; - } + if (data->data == NULL) { + printf("SPU2-X savestate null pointer!\n"); + return -1; + } - Savestate::DataBlock& spud = (Savestate::DataBlock&)*(data->data); + Savestate::DataBlock &spud = (Savestate::DataBlock &)*(data->data); - switch( mode ) - { - case FREEZE_LOAD: return Savestate::ThawIt( spud ); - case FREEZE_SAVE: return Savestate::FreezeIt( spud ); + switch (mode) { + case FREEZE_LOAD: + return Savestate::ThawIt(spud); + case FREEZE_SAVE: + return Savestate::FreezeIt(spud); - jNO_DEFAULT; - } + jNO_DEFAULT; + } - // technically unreachable, but kills a warning: - return 0; + // technically unreachable, but kills a warning: + return 0; } diff --git a/plugins/spu2-x/src/PS2E-spu2.h b/plugins/spu2-x/src/PS2E-spu2.h index d01f10147c..1c50c9054d 100644 --- a/plugins/spu2-x/src/PS2E-spu2.h +++ b/plugins/spu2-x/src/PS2E-spu2.h @@ -28,42 +28,62 @@ #ifdef _MSC_VER #define EXPORT_C_(type) extern "C" type CALLBACK #else -#define EXPORT_C_(type) extern "C" __attribute__((stdcall,externally_visible,visibility("default"))) type +#define EXPORT_C_(type) extern "C" __attribute__((stdcall, externally_visible, visibility("default"))) type #endif // We have our own versions that have the DLLExport attribute configured: -EXPORT_C_(s32) SPU2init(); -EXPORT_C_(void) SPU2reset(); -EXPORT_C_(s32) SPU2open(void *pDsp); -EXPORT_C_(void) SPU2close(); -EXPORT_C_(void) SPU2shutdown(); -EXPORT_C_(void) SPU2write(u32 mem, u16 value); -EXPORT_C_(u16) SPU2read(u32 mem); +EXPORT_C_(s32) +SPU2init(); +EXPORT_C_(void) +SPU2reset(); +EXPORT_C_(s32) +SPU2open(void *pDsp); +EXPORT_C_(void) +SPU2close(); +EXPORT_C_(void) +SPU2shutdown(); +EXPORT_C_(void) +SPU2write(u32 mem, u16 value); +EXPORT_C_(u16) +SPU2read(u32 mem); #ifdef ENABLE_NEW_IOPDMA_SPU2 -EXPORT_C_(s32) SPU2dmaRead(s32 channel, u32* data, u32 bytesLeft, u32* bytesProcessed); -EXPORT_C_(s32) SPU2dmaWrite(s32 channel, u32* data, u32 bytesLeft, u32* bytesProcessed); -EXPORT_C_(void) SPU2dmaInterrupt(s32 channel); +EXPORT_C_(s32) +SPU2dmaRead(s32 channel, u32 *data, u32 bytesLeft, u32 *bytesProcessed); +EXPORT_C_(s32) +SPU2dmaWrite(s32 channel, u32 *data, u32 bytesLeft, u32 *bytesProcessed); +EXPORT_C_(void) +SPU2dmaInterrupt(s32 channel); // dma irq callbacks not needed anymore, they are handled by the dmac -EXPORT_C_(void) SPU2irqCallback(void (*SPU2callback)()); +EXPORT_C_(void) +SPU2irqCallback(void (*SPU2callback)()); #else // These defines are useless and gcc-4.6 complain about redefinition // so we remove them on linux #ifndef __POSIX__ -EXPORT_C_(void) SPU2readDMA4Mem(u16 *pMem, u32 size); -EXPORT_C_(void) SPU2writeDMA4Mem(u16 *pMem, u32 size); -EXPORT_C_(void) SPU2interruptDMA4(); -EXPORT_C_(void) SPU2readDMA7Mem(u16* pMem, u32 size); -EXPORT_C_(void) SPU2writeDMA7Mem(u16 *pMem, u32 size); -EXPORT_C_(void) SPU2interruptDMA7(); +EXPORT_C_(void) +SPU2readDMA4Mem(u16 *pMem, u32 size); +EXPORT_C_(void) +SPU2writeDMA4Mem(u16 *pMem, u32 size); +EXPORT_C_(void) +SPU2interruptDMA4(); +EXPORT_C_(void) +SPU2readDMA7Mem(u16 *pMem, u32 size); +EXPORT_C_(void) +SPU2writeDMA7Mem(u16 *pMem, u32 size); +EXPORT_C_(void) +SPU2interruptDMA7(); // all addresses passed by dma will be pointers to the array starting at baseaddr // This function is necessary to successfully save and reload the spu2 state -EXPORT_C_(u32) SPU2ReadMemAddr(int core); -EXPORT_C_(void) SPU2WriteMemAddr(int core,u32 value); -EXPORT_C_(void) SPU2irqCallback(void (*SPU2callback)(),void (*DMA4callback)(),void (*DMA7callback)()); +EXPORT_C_(u32) +SPU2ReadMemAddr(int core); +EXPORT_C_(void) +SPU2WriteMemAddr(int core, u32 value); +EXPORT_C_(void) +SPU2irqCallback(void (*SPU2callback)(), void (*DMA4callback)(), void (*DMA7callback)()); #endif #endif @@ -71,25 +91,32 @@ EXPORT_C_(void) SPU2irqCallback(void (*SPU2callback)(),void (*DMA4callback)(),vo // if start is 1, starts recording spu2 data, else stops // returns a non zero value if successful // for now, pData is not used -EXPORT_C_(int) SPU2setupRecording(int start, void* pData); +EXPORT_C_(int) +SPU2setupRecording(int start, void *pData); -EXPORT_C_(void) SPU2setClockPtr(u32* ptr); +EXPORT_C_(void) +SPU2setClockPtr(u32 *ptr); -EXPORT_C_(void) SPU2async(u32 cycles); -EXPORT_C_(s32) SPU2freeze(int mode, freezeData *data); -EXPORT_C_(void) SPU2configure(); -EXPORT_C_(void) SPU2about(); -EXPORT_C_(s32) SPU2test(); +EXPORT_C_(void) +SPU2async(u32 cycles); +EXPORT_C_(s32) +SPU2freeze(int mode, freezeData *data); +EXPORT_C_(void) +SPU2configure(); +EXPORT_C_(void) +SPU2about(); +EXPORT_C_(s32) +SPU2test(); #include "Spu2replay.h" extern u8 callirq; -extern void (* _irqcallback)(); +extern void (*_irqcallback)(); #ifndef ENABLE_NEW_IOPDMA_SPU2 -extern void (* dma4callback)(); -extern void (* dma7callback)(); +extern void (*dma4callback)(); +extern void (*dma7callback)(); extern s16 *input_data; extern u32 input_data_ptr; @@ -99,11 +126,11 @@ extern double srate_pv; extern int recording; extern u32 lClocks; -extern u32* cyclePtr; +extern u32 *cyclePtr; -extern void SPU2writeLog( const char* action, u32 rmem, u16 value ); +extern void SPU2writeLog(const char *action, u32 rmem, u16 value); extern void TimeUpdate(u32 cClocks); -extern void SPU2_FastWrite( u32 rmem, u16 value ); +extern void SPU2_FastWrite(u32 rmem, u16 value); extern void LowPassFilterInit(); diff --git a/plugins/spu2-x/src/ReadInput.cpp b/plugins/spu2-x/src/ReadInput.cpp index 78a3b81a21..8b1a72a585 100644 --- a/plugins/spu2-x/src/ReadInput.cpp +++ b/plugins/spu2-x/src/ReadInput.cpp @@ -18,7 +18,7 @@ #include "Global.h" #include "Dma.h" -#include "PS2E-spu2.h" // required for ENABLE_NEW_IOPDMA_SPU2 define +#include "PS2E-spu2.h" // required for ENABLE_NEW_IOPDMA_SPU2 define // Core 0 Input is "SPDIF mode" - Source audio is AC3 compressed. @@ -31,148 +31,147 @@ // StereoOut32 V_Core::ReadInput_HiFi() { - if (psxmode)ConLog("ReadInput_HiFi!!!!!\n"); - InputPosRead &= ~1; -// -//#ifdef PCM24_S1_INTERLEAVE -// StereoOut32 retval( -// *((s32*)(ADMATempBuffer+(InputPosRead<<1))), -// *((s32*)(ADMATempBuffer+(InputPosRead<<1)+2)) -// ); -//#else -// StereoOut32 retval( -// (s32&)(ADMATempBuffer[InputPosRead]), -// (s32&)(ADMATempBuffer[InputPosRead+0x200]) -// ); -//#endif + if (psxmode) + ConLog("ReadInput_HiFi!!!!!\n"); + InputPosRead &= ~1; + // + //#ifdef PCM24_S1_INTERLEAVE + // StereoOut32 retval( + // *((s32*)(ADMATempBuffer+(InputPosRead<<1))), + // *((s32*)(ADMATempBuffer+(InputPosRead<<1)+2)) + // ); + //#else + // StereoOut32 retval( + // (s32&)(ADMATempBuffer[InputPosRead]), + // (s32&)(ADMATempBuffer[InputPosRead+0x200]) + // ); + //#endif - StereoOut32 retval( - (s32&)(*GetMemPtr(0x2000 + (Index<<10) + InputPosRead)), - (s32&)(*GetMemPtr(0x2200 + (Index<<10) + InputPosRead)) - ); + StereoOut32 retval( + (s32 &)(*GetMemPtr(0x2000 + (Index << 10) + InputPosRead)), + (s32 &)(*GetMemPtr(0x2200 + (Index << 10) + InputPosRead))); - if( Index == 1 ) - { - // CDDA Mode: - // give 30 bit data (SndOut downsamples the rest of the way) - // HACKFIX: 28 bits seems better according to rama. I should take some time and do some - // bitcounting on this one. --air - retval.Left >>= 4; - retval.Right >>= 4; - } + if (Index == 1) { + // CDDA Mode: + // give 30 bit data (SndOut downsamples the rest of the way) + // HACKFIX: 28 bits seems better according to rama. I should take some time and do some + // bitcounting on this one. --air + retval.Left >>= 4; + retval.Right >>= 4; + } - InputPosRead += 2; + InputPosRead += 2; - // Why does CDDA mode check for InputPos == 0x100? In the old code, SPDIF mode did not but CDDA did. - // One of these seems wrong, they should be the same. Since standard ADMA checks too I'm assuming that as default. -- air + // Why does CDDA mode check for InputPos == 0x100? In the old code, SPDIF mode did not but CDDA did. + // One of these seems wrong, they should be the same. Since standard ADMA checks too I'm assuming that as default. -- air - if( (InputPosRead==0x100) || (InputPosRead>=0x200) ) - { + if ((InputPosRead == 0x100) || (InputPosRead >= 0x200)) { #ifdef ENABLE_NEW_IOPDMA_SPU2 - // WARNING: Assumes this to be in the same thread as the dmas - AutoDmaFree += 0x200; + // WARNING: Assumes this to be in the same thread as the dmas + AutoDmaFree += 0x200; #else - AdmaInProgress = 0; - if(InputDataLeft >= 0x200) - { + AdmaInProgress = 0; + if (InputDataLeft >= 0x200) { #ifdef PCM24_S1_INTERLEAVE - AutoDMAReadBuffer(1); + AutoDMAReadBuffer(1); #else - AutoDMAReadBuffer(0); + AutoDMAReadBuffer(0); #endif - AdmaInProgress = 1; + AdmaInProgress = 1; - TSA = (Index<<10) + InputPosRead; + TSA = (Index << 10) + InputPosRead; - if (InputDataLeft < 0x200) - { - FileLog("[%10d] %s AutoDMA%c block end.\n", (Index==1) ? "CDDA" : "SPDIF", Cycles, GetDmaIndexChar()); + if (InputDataLeft < 0x200) { + FileLog("[%10d] %s AutoDMA%c block end.\n", (Index == 1) ? "CDDA" : "SPDIF", Cycles, GetDmaIndexChar()); - if( IsDevBuild ) - { - if(InputDataLeft > 0) - { - if(MsgAutoDMA()) ConLog("WARNING: adma buffer didn't finish with a whole block!!\n"); - } - } - InputDataLeft = 0; - // Hack, kinda. We call the interrupt early here, since PCSX2 doesn't like them delayed. - //DMAICounter = 1; - if(Index == 0) { if(dma4callback) dma4callback(); } - else { if(dma7callback) dma7callback(); } - } - } + if (IsDevBuild) { + if (InputDataLeft > 0) { + if (MsgAutoDMA()) + ConLog("WARNING: adma buffer didn't finish with a whole block!!\n"); + } + } + InputDataLeft = 0; + // Hack, kinda. We call the interrupt early here, since PCSX2 doesn't like them delayed. + //DMAICounter = 1; + if (Index == 0) { + if (dma4callback) + dma4callback(); + } else { + if (dma7callback) + dma7callback(); + } + } + } #endif - InputPosRead &= 0x1ff; - } - return retval; + InputPosRead &= 0x1ff; + } + return retval; } StereoOut32 V_Core::ReadInput() { - StereoOut32 retval; + StereoOut32 retval; - if( (Index!=1) || ((PlayMode&2)==0) ) - { - for (int i=0; i<2; i++) - if (Cores[i].IRQEnable && 0x2000 + (Index << 10) + InputPosRead == (Cores[i].IRQA & 0xfffffdff)) - SetIrqCall(i); + if ((Index != 1) || ((PlayMode & 2) == 0)) { + for (int i = 0; i < 2; i++) + if (Cores[i].IRQEnable && 0x2000 + (Index << 10) + InputPosRead == (Cores[i].IRQA & 0xfffffdff)) + SetIrqCall(i); - //retval = StereoOut32( - // (s32)ADMATempBuffer[InputPosRead], - // (s32)ADMATempBuffer[InputPosRead+0x200] - //); - retval = StereoOut32( - (s32)(*GetMemPtr(0x2000 + (Index<<10) + InputPosRead)), - (s32)(*GetMemPtr(0x2200 + (Index<<10) + InputPosRead)) - ); - } + //retval = StereoOut32( + // (s32)ADMATempBuffer[InputPosRead], + // (s32)ADMATempBuffer[InputPosRead+0x200] + //); + retval = StereoOut32( + (s32)(*GetMemPtr(0x2000 + (Index << 10) + InputPosRead)), + (s32)(*GetMemPtr(0x2200 + (Index << 10) + InputPosRead))); + } #ifdef PCSX2_DEVBUILD - DebugCores[Index].admaWaveformL[InputPosRead%0x100]=retval.Left; - DebugCores[Index].admaWaveformR[InputPosRead%0x100]=retval.Right; + DebugCores[Index].admaWaveformL[InputPosRead % 0x100] = retval.Left; + DebugCores[Index].admaWaveformR[InputPosRead % 0x100] = retval.Right; #endif - InputPosRead++; + InputPosRead++; - if (AutoDMACtrl & (Index + 1) && (InputPosRead == 0x100 || InputPosRead == 0x200)) - { + if (AutoDMACtrl & (Index + 1) && (InputPosRead == 0x100 || InputPosRead == 0x200)) { #ifdef ENABLE_NEW_IOPDMA_SPU2 - // WARNING: Assumes this to be in the same thread as the dmas - AutoDmaFree += 0x200; + // WARNING: Assumes this to be in the same thread as the dmas + AutoDmaFree += 0x200; #else - AdmaInProgress = 0; - if(InputDataLeft >= 0x200) - { - //u8 k=InputDataLeft>=InputDataProgress; + AdmaInProgress = 0; + if (InputDataLeft >= 0x200) { + //u8 k=InputDataLeft>=InputDataProgress; - AutoDMAReadBuffer(0); + AutoDMAReadBuffer(0); - AdmaInProgress = 1; - TSA = (Index<<10) + InputPosRead; + AdmaInProgress = 1; + TSA = (Index << 10) + InputPosRead; - if (InputDataLeft < 0x200) - { - AutoDMACtrl |= ~3; + if (InputDataLeft < 0x200) { + AutoDMACtrl |= ~3; - if( IsDevBuild ) - { - FileLog("[%10d] AutoDMA%c block end.\n",Cycles, GetDmaIndexChar()); - if(InputDataLeft>0) - { - if(MsgAutoDMA()) ConLog("WARNING: adma buffer didn't finish with a whole block!!\n"); - } - } + if (IsDevBuild) { + FileLog("[%10d] AutoDMA%c block end.\n", Cycles, GetDmaIndexChar()); + if (InputDataLeft > 0) { + if (MsgAutoDMA()) + ConLog("WARNING: adma buffer didn't finish with a whole block!!\n"); + } + } - InputDataLeft = 0; - // Hack, kinda. We call the interrupt early here, since PCSX2 doesn't like them delayed. - //DMAICounter = 1; - if(Index == 0) { if(dma4callback) dma4callback(); } - else { if(dma7callback) dma7callback(); } - } - } + InputDataLeft = 0; + // Hack, kinda. We call the interrupt early here, since PCSX2 doesn't like them delayed. + //DMAICounter = 1; + if (Index == 0) { + if (dma4callback) + dma4callback(); + } else { + if (dma7callback) + dma7callback(); + } + } + } #endif - } - InputPosRead &= 0x1ff; - return retval; + } + InputPosRead &= 0x1ff; + return retval; } diff --git a/plugins/spu2-x/src/RegLog.cpp b/plugins/spu2-x/src/RegLog.cpp index a9f17fc776..2431b21981 100644 --- a/plugins/spu2-x/src/RegLog.cpp +++ b/plugins/spu2-x/src/RegLog.cpp @@ -17,238 +17,280 @@ #include "Global.h" -const char *ParamNames[8]={"VOLL","VOLR","PITCH","ADSR1","ADSR2","ENVX","VOLXL","VOLXR"}; -const char *AddressNames[6]={"SSAH","SSAL","LSAH","LSAL","NAXH","NAXL"}; +const char *ParamNames[8] = {"VOLL", "VOLR", "PITCH", "ADSR1", "ADSR2", "ENVX", "VOLXL", "VOLXR"}; +const char *AddressNames[6] = {"SSAH", "SSAL", "LSAH", "LSAL", "NAXH", "NAXL"}; -__forceinline void _RegLog_( const char* action, int level, const char *RName, u32 mem, u32 core, u16 value ) +__forceinline void _RegLog_(const char *action, int level, const char *RName, u32 mem, u32 core, u16 value) { - if( level > 1 ) - FileLog("[%10d] SPU2 %s mem %08x (core %d, register %s) value %04x\n", - Cycles, action, mem, core, RName, value); + if (level > 1) + FileLog("[%10d] SPU2 %s mem %08x (core %d, register %s) value %04x\n", + Cycles, action, mem, core, RName, value); } -#define RegLog( lev, rname, mem, core, val ) _RegLog_( action, lev, rname, mem, core, val ) +#define RegLog(lev, rname, mem, core, val) _RegLog_(action, lev, rname, mem, core, val) -void SPU2writeLog( const char* action, u32 rmem, u16 value ) +void SPU2writeLog(const char *action, u32 rmem, u16 value) { - if( !IsDevBuild ) return; + if (!IsDevBuild) + return; - //u32 vx=0, vc=0; - u32 core=0, omem, mem; - omem=mem=rmem & 0x7FF; //FFFF; - if (mem & 0x400) { omem^=0x400; core=1; } + //u32 vx=0, vc=0; + u32 core = 0, omem, mem; + omem = mem = rmem & 0x7FF; //FFFF; + if (mem & 0x400) { + omem ^= 0x400; + core = 1; + } - if( omem < 0x0180 ) // Voice Params (VP) - { - const u32 voice = (omem & 0x1F0) >> 4; - const u32 param = (omem & 0xF) >> 1; - char dest[192]; - sprintf( dest, "Voice %d %s", voice,ParamNames[param] ); - RegLog( 2, dest, rmem, core, value ); - } - else if ((omem >= 0x01C0) && (omem < 0x02E0)) // Voice Addressing Params (VA) - { - const u32 voice = ((omem-0x01C0) / 12); - const u32 address = ((omem-0x01C0) % 12)>>1; + if (omem < 0x0180) // Voice Params (VP) + { + const u32 voice = (omem & 0x1F0) >> 4; + const u32 param = (omem & 0xF) >> 1; + char dest[192]; + sprintf(dest, "Voice %d %s", voice, ParamNames[param]); + RegLog(2, dest, rmem, core, value); + } else if ((omem >= 0x01C0) && (omem < 0x02E0)) // Voice Addressing Params (VA) + { + const u32 voice = ((omem - 0x01C0) / 12); + const u32 address = ((omem - 0x01C0) % 12) >> 1; - char dest[192]; - sprintf( dest, "Voice %d %s", voice, AddressNames[address] ); - RegLog( 2, dest, rmem, core, value ); - } - else if ((mem >= 0x0760) && (mem < 0x07b0)) - { - omem=mem; core=0; - if (mem >= 0x0788) {omem-=0x28; core=1;} - switch(omem) - { - case REG_P_EVOLL: RegLog(2,"EVOLL",rmem,core,value); break; - case REG_P_EVOLR: RegLog(2,"EVOLR",rmem,core,value); break; - case REG_P_AVOLL: if (core) { RegLog(2,"AVOLL",rmem,core,value); } break; - case REG_P_AVOLR: if (core) { RegLog(2,"AVOLR",rmem,core,value); } break; - case REG_P_BVOLL: RegLog(2,"BVOLL",rmem,core,value); break; - case REG_P_BVOLR: RegLog(2,"BVOLR",rmem,core,value); break; - case REG_P_MVOLXL: RegLog(2,"MVOLXL",rmem,core,value); break; - case REG_P_MVOLXR: RegLog(2,"MVOLXR",rmem,core,value); break; - case R_IIR_ALPHA: RegLog(2,"IIR_ALPHA",rmem,core,value); break; - case R_ACC_COEF_A: RegLog(2,"ACC_COEF_A",rmem,core,value); break; - case R_ACC_COEF_B: RegLog(2,"ACC_COEF_B",rmem,core,value); break; - case R_ACC_COEF_C: RegLog(2,"ACC_COEF_C",rmem,core,value); break; - case R_ACC_COEF_D: RegLog(2,"ACC_COEF_D",rmem,core,value); break; - case R_IIR_COEF: RegLog(2,"IIR_COEF",rmem,core,value); break; - case R_FB_ALPHA: RegLog(2,"FB_ALPHA",rmem,core,value); break; - case R_FB_X: RegLog(2,"FB_X",rmem,core,value); break; - case R_IN_COEF_L: RegLog(2,"IN_COEF_L",rmem,core,value); break; - case R_IN_COEF_R: RegLog(2,"IN_COEF_R",rmem,core,value); break; + char dest[192]; + sprintf(dest, "Voice %d %s", voice, AddressNames[address]); + RegLog(2, dest, rmem, core, value); + } else if ((mem >= 0x0760) && (mem < 0x07b0)) { + omem = mem; + core = 0; + if (mem >= 0x0788) { + omem -= 0x28; + core = 1; + } + switch (omem) { + case REG_P_EVOLL: + RegLog(2, "EVOLL", rmem, core, value); + break; + case REG_P_EVOLR: + RegLog(2, "EVOLR", rmem, core, value); + break; + case REG_P_AVOLL: + if (core) { + RegLog(2, "AVOLL", rmem, core, value); + } + break; + case REG_P_AVOLR: + if (core) { + RegLog(2, "AVOLR", rmem, core, value); + } + break; + case REG_P_BVOLL: + RegLog(2, "BVOLL", rmem, core, value); + break; + case REG_P_BVOLR: + RegLog(2, "BVOLR", rmem, core, value); + break; + case REG_P_MVOLXL: + RegLog(2, "MVOLXL", rmem, core, value); + break; + case REG_P_MVOLXR: + RegLog(2, "MVOLXR", rmem, core, value); + break; + case R_IIR_ALPHA: + RegLog(2, "IIR_ALPHA", rmem, core, value); + break; + case R_ACC_COEF_A: + RegLog(2, "ACC_COEF_A", rmem, core, value); + break; + case R_ACC_COEF_B: + RegLog(2, "ACC_COEF_B", rmem, core, value); + break; + case R_ACC_COEF_C: + RegLog(2, "ACC_COEF_C", rmem, core, value); + break; + case R_ACC_COEF_D: + RegLog(2, "ACC_COEF_D", rmem, core, value); + break; + case R_IIR_COEF: + RegLog(2, "IIR_COEF", rmem, core, value); + break; + case R_FB_ALPHA: + RegLog(2, "FB_ALPHA", rmem, core, value); + break; + case R_FB_X: + RegLog(2, "FB_X", rmem, core, value); + break; + case R_IN_COEF_L: + RegLog(2, "IN_COEF_L", rmem, core, value); + break; + case R_IN_COEF_R: + RegLog(2, "IN_COEF_R", rmem, core, value); + break; + } + } else if ((mem >= 0x07C0) && (mem < 0x07CE)) { + switch (mem) { + case SPDIF_OUT: + RegLog(2, "SPDIF_OUT", rmem, -1, value); + break; + case SPDIF_IRQINFO: + RegLog(2, "SPDIF_IRQINFO", rmem, -1, value); + break; + case 0x7c4: + if (Spdif.Unknown1 != value) + ConLog("* SPU2-X: SPDIF Unknown Register 1 set to %04x\n", value); + RegLog(2, "SPDIF_UNKNOWN1", rmem, -1, value); + break; + case SPDIF_MODE: + if (Spdif.Mode != value) + ConLog("* SPU2-X: SPDIF Mode set to %04x\n", value); + RegLog(2, "SPDIF_MODE", rmem, -1, value); + break; + case SPDIF_MEDIA: + if (Spdif.Media != value) + ConLog("* SPU2-X: SPDIF Media set to %04x\n", value); + RegLog(2, "SPDIF_MEDIA", rmem, -1, value); + break; + case 0x7ca: + if (Spdif.Unknown2 != value) + ConLog("* SPU2-X: SPDIF Unknown Register 2 set to %04x\n", value); + RegLog(2, "SPDIF_UNKNOWN2", rmem, -1, value); + break; + case SPDIF_PROTECT: + if (Spdif.Protection != value) + ConLog("* SPU2-X: SPDIF Copy set to %04x\n", value); + RegLog(2, "SPDIF_PROTECT", rmem, -1, value); + break; + } + UpdateSpdifMode(); + } else { + switch (omem) { + case REG_C_ATTR: + RegLog(4, "ATTR", rmem, core, value); + break; + case REG_S_PMON: + RegLog(1, "PMON0", rmem, core, value); + break; + case (REG_S_PMON + 2): + RegLog(1, "PMON1", rmem, core, value); + break; + case REG_S_NON: + RegLog(1, "NON0", rmem, core, value); + break; + case (REG_S_NON + 2): + RegLog(1, "NON1", rmem, core, value); + break; + case REG_S_VMIXL: + RegLog(1, "VMIXL0", rmem, core, value); + case (REG_S_VMIXL + 2): + RegLog(1, "VMIXL1", rmem, core, value); + break; + case REG_S_VMIXEL: + RegLog(1, "VMIXEL0", rmem, core, value); + break; + case (REG_S_VMIXEL + 2): + RegLog(1, "VMIXEL1", rmem, core, value); + break; + case REG_S_VMIXR: + RegLog(1, "VMIXR0", rmem, core, value); + break; + case (REG_S_VMIXR + 2): + RegLog(1, "VMIXR1", rmem, core, value); + break; + case REG_S_VMIXER: + RegLog(1, "VMIXER0", rmem, core, value); + break; + case (REG_S_VMIXER + 2): + RegLog(1, "VMIXER1", rmem, core, value); + break; + case REG_P_MMIX: + RegLog(1, "MMIX", rmem, core, value); + break; + case REG_A_IRQA: + RegLog(2, "IRQAH", rmem, core, value); + break; + case (REG_A_IRQA + 2): + RegLog(2, "IRQAL", rmem, core, value); + break; + case (REG_S_KON + 2): + RegLog(1, "KON1", rmem, core, value); + break; + case REG_S_KON: + RegLog(1, "KON0", rmem, core, value); + break; + case (REG_S_KOFF + 2): + RegLog(1, "KOFF1", rmem, core, value); + break; + case REG_S_KOFF: + RegLog(1, "KOFF0", rmem, core, value); + break; + case REG_A_TSA: + RegLog(2, "TSAH", rmem, core, value); + break; + case (REG_A_TSA + 2): + RegLog(2, "TSAL", rmem, core, value); + break; + case REG_S_ENDX: + //ConLog("* SPU2-X: Core %d ENDX cleared!\n",core); + RegLog(2, "ENDX0", rmem, core, value); + break; + case (REG_S_ENDX + 2): + //ConLog("* SPU2-X: Core %d ENDX cleared!\n",core); + RegLog(2, "ENDX1", rmem, core, value); + break; + case REG_P_MVOLL: + RegLog(1, "MVOLL", rmem, core, value); + break; + case REG_P_MVOLR: + RegLog(1, "MVOLR", rmem, core, value); + break; + case REG_S_ADMAS: + RegLog(3, "ADMAS", rmem, core, value); + //ConLog("* SPU2-X: Core %d AutoDMAControl set to %d\n",core,value); + break; + case REG_P_STATX: + RegLog(3, "STATX", rmem, core, value); + break; + case REG_A_ESA: + RegLog(2, "ESAH", rmem, core, value); + break; + case (REG_A_ESA + 2): + RegLog(2, "ESAL", rmem, core, value); + break; + case REG_A_EEA: + RegLog(2, "EEAH", rmem, core, value); + break; - } - } - else if ((mem>=0x07C0) && (mem<0x07CE)) - { - switch(mem) - { - case SPDIF_OUT: - RegLog(2,"SPDIF_OUT",rmem,-1,value); - break; - case SPDIF_IRQINFO: - RegLog(2,"SPDIF_IRQINFO",rmem,-1,value); - break; - case 0x7c4: - if(Spdif.Unknown1 != value) ConLog("* SPU2-X: SPDIF Unknown Register 1 set to %04x\n",value); - RegLog(2,"SPDIF_UNKNOWN1",rmem,-1,value); - break; - case SPDIF_MODE: - if(Spdif.Mode != value) ConLog("* SPU2-X: SPDIF Mode set to %04x\n",value); - RegLog(2,"SPDIF_MODE",rmem,-1,value); - break; - case SPDIF_MEDIA: - if(Spdif.Media != value) ConLog("* SPU2-X: SPDIF Media set to %04x\n",value); - RegLog(2,"SPDIF_MEDIA",rmem,-1,value); - break; - case 0x7ca: - if(Spdif.Unknown2 != value) ConLog("* SPU2-X: SPDIF Unknown Register 2 set to %04x\n",value); - RegLog(2,"SPDIF_UNKNOWN2",rmem,-1,value); - break; - case SPDIF_PROTECT: - if(Spdif.Protection != value) ConLog("* SPU2-X: SPDIF Copy set to %04x\n",value); - RegLog(2,"SPDIF_PROTECT",rmem,-1,value); - break; - } - UpdateSpdifMode(); - } - else - { - switch(omem) - { - case REG_C_ATTR: - RegLog(4,"ATTR",rmem,core,value); - break; - case REG_S_PMON: - RegLog(1,"PMON0",rmem,core,value); - break; - case (REG_S_PMON + 2): - RegLog(1,"PMON1",rmem,core,value); - break; - case REG_S_NON: - RegLog(1,"NON0",rmem,core,value); - break; - case (REG_S_NON + 2): - RegLog(1,"NON1",rmem,core,value); - break; - case REG_S_VMIXL: - RegLog(1,"VMIXL0",rmem,core,value); - case (REG_S_VMIXL + 2): - RegLog(1,"VMIXL1",rmem,core,value); - break; - case REG_S_VMIXEL: - RegLog(1,"VMIXEL0",rmem,core,value); - break; - case (REG_S_VMIXEL + 2): - RegLog(1,"VMIXEL1",rmem,core,value); - break; - case REG_S_VMIXR: - RegLog(1,"VMIXR0",rmem,core,value); - break; - case (REG_S_VMIXR + 2): - RegLog(1,"VMIXR1",rmem,core,value); - break; - case REG_S_VMIXER: - RegLog(1,"VMIXER0",rmem,core,value); - break; - case (REG_S_VMIXER + 2): - RegLog(1,"VMIXER1",rmem,core,value); - break; - case REG_P_MMIX: - RegLog(1,"MMIX",rmem,core,value); - break; - case REG_A_IRQA: - RegLog(2,"IRQAH",rmem,core,value); - break; - case (REG_A_IRQA + 2): - RegLog(2,"IRQAL",rmem,core,value); - break; - case (REG_S_KON + 2): - RegLog(1,"KON1",rmem,core,value); - break; - case REG_S_KON: - RegLog(1,"KON0",rmem,core,value); - break; - case (REG_S_KOFF + 2): - RegLog(1,"KOFF1",rmem,core,value); - break; - case REG_S_KOFF: - RegLog(1,"KOFF0",rmem,core,value); - break; - case REG_A_TSA: - RegLog(2,"TSAH",rmem,core,value); - break; - case (REG_A_TSA + 2): - RegLog(2,"TSAL",rmem,core,value); - break; - case REG_S_ENDX: - //ConLog("* SPU2-X: Core %d ENDX cleared!\n",core); - RegLog(2,"ENDX0",rmem,core,value); - break; - case (REG_S_ENDX + 2): - //ConLog("* SPU2-X: Core %d ENDX cleared!\n",core); - RegLog(2,"ENDX1",rmem,core,value); - break; - case REG_P_MVOLL: - RegLog(1,"MVOLL",rmem,core,value); - break; - case REG_P_MVOLR: - RegLog(1,"MVOLR",rmem,core,value); - break; - case REG_S_ADMAS: - RegLog(3,"ADMAS",rmem,core,value); - //ConLog("* SPU2-X: Core %d AutoDMAControl set to %d\n",core,value); - break; - case REG_P_STATX: - RegLog(3,"STATX",rmem,core,value); - break; - case REG_A_ESA: - RegLog(2,"ESAH",rmem,core,value); - break; - case (REG_A_ESA + 2): - RegLog(2,"ESAL",rmem,core,value); - break; - case REG_A_EEA: - RegLog(2,"EEAH",rmem,core,value); - break; +#define LOG_REVB_REG(n, t) \ + case R_##n: \ + RegLog(2, t "H", mem, core, value); \ + break; \ + case (R_##n + 2): \ + RegLog(2, t "L", mem, core, value); \ + break; - #define LOG_REVB_REG(n,t) \ - case R_##n: \ - RegLog(2,t "H",mem,core,value); \ - break; \ - case (R_##n + 2): \ - RegLog(2,t "L",mem,core,value); \ - break; + LOG_REVB_REG(FB_SRC_A, "FB_SRC_A") + LOG_REVB_REG(FB_SRC_B, "FB_SRC_B") + LOG_REVB_REG(IIR_SRC_A0, "IIR_SRC_A0") + LOG_REVB_REG(IIR_SRC_A1, "IIR_SRC_A1") + LOG_REVB_REG(IIR_SRC_B1, "IIR_SRC_B1") + LOG_REVB_REG(IIR_SRC_B0, "IIR_SRC_B0") + LOG_REVB_REG(IIR_DEST_A0, "IIR_DEST_A0") + LOG_REVB_REG(IIR_DEST_A1, "IIR_DEST_A1") + LOG_REVB_REG(IIR_DEST_B0, "IIR_DEST_B0") + LOG_REVB_REG(IIR_DEST_B1, "IIR_DEST_B1") + LOG_REVB_REG(ACC_SRC_A0, "ACC_SRC_A0") + LOG_REVB_REG(ACC_SRC_A1, "ACC_SRC_A1") + LOG_REVB_REG(ACC_SRC_B0, "ACC_SRC_B0") + LOG_REVB_REG(ACC_SRC_B1, "ACC_SRC_B1") + LOG_REVB_REG(ACC_SRC_C0, "ACC_SRC_C0") + LOG_REVB_REG(ACC_SRC_C1, "ACC_SRC_C1") + LOG_REVB_REG(ACC_SRC_D0, "ACC_SRC_D0") + LOG_REVB_REG(ACC_SRC_D1, "ACC_SRC_D1") + LOG_REVB_REG(MIX_DEST_A0, "MIX_DEST_A0") + LOG_REVB_REG(MIX_DEST_A1, "MIX_DEST_A1") + LOG_REVB_REG(MIX_DEST_B0, "MIX_DEST_B0") + LOG_REVB_REG(MIX_DEST_B1, "MIX_DEST_B1") - LOG_REVB_REG(FB_SRC_A,"FB_SRC_A") - LOG_REVB_REG(FB_SRC_B,"FB_SRC_B") - LOG_REVB_REG(IIR_SRC_A0,"IIR_SRC_A0") - LOG_REVB_REG(IIR_SRC_A1,"IIR_SRC_A1") - LOG_REVB_REG(IIR_SRC_B1,"IIR_SRC_B1") - LOG_REVB_REG(IIR_SRC_B0,"IIR_SRC_B0") - LOG_REVB_REG(IIR_DEST_A0,"IIR_DEST_A0") - LOG_REVB_REG(IIR_DEST_A1,"IIR_DEST_A1") - LOG_REVB_REG(IIR_DEST_B0,"IIR_DEST_B0") - LOG_REVB_REG(IIR_DEST_B1,"IIR_DEST_B1") - LOG_REVB_REG(ACC_SRC_A0,"ACC_SRC_A0") - LOG_REVB_REG(ACC_SRC_A1,"ACC_SRC_A1") - LOG_REVB_REG(ACC_SRC_B0,"ACC_SRC_B0") - LOG_REVB_REG(ACC_SRC_B1,"ACC_SRC_B1") - LOG_REVB_REG(ACC_SRC_C0,"ACC_SRC_C0") - LOG_REVB_REG(ACC_SRC_C1,"ACC_SRC_C1") - LOG_REVB_REG(ACC_SRC_D0,"ACC_SRC_D0") - LOG_REVB_REG(ACC_SRC_D1,"ACC_SRC_D1") - LOG_REVB_REG(MIX_DEST_A0,"MIX_DEST_A0") - LOG_REVB_REG(MIX_DEST_A1,"MIX_DEST_A1") - LOG_REVB_REG(MIX_DEST_B0,"MIX_DEST_B0") - LOG_REVB_REG(MIX_DEST_B1,"MIX_DEST_B1") - - default: - RegLog(2,"UNKNOWN",rmem,core,value); spu2Ru16(mem) = value; - } - } + default: + RegLog(2, "UNKNOWN", rmem, core, value); + spu2Ru16(mem) = value; + } + } } - diff --git a/plugins/spu2-x/src/RegTable.cpp b/plugins/spu2-x/src/RegTable.cpp index 7dea39a03d..adfaeb1da3 100644 --- a/plugins/spu2-x/src/RegTable.cpp +++ b/plugins/spu2-x/src/RegTable.cpp @@ -17,287 +17,287 @@ #include "Global.h" -#define PCORE(c,p) \ - U16P(Cores[c].p) +#define PCORE(c, p) \ + U16P(Cores[c].p) -#define PVCP(c,v,p) \ - PCORE(c,Voices[v].p) +#define PVCP(c, v, p) \ + PCORE(c, Voices[v].p) -#define PVC(c,v) \ - PVCP(c,v,Volume.Left.Reg_VOL), \ - PVCP(c,v,Volume.Right.Reg_VOL), \ - PVCP(c,v,Pitch), \ - PVCP(c,v,ADSR.regADSR1), \ - PVCP(c,v,ADSR.regADSR2), \ - PVCP(c,v,ADSR.Value)+1, \ - PVCP(c,v,Volume.Left.Value)+1, \ - PVCP(c,v,Volume.Right.Value)+1 +#define PVC(c, v) \ + PVCP(c, v, Volume.Left.Reg_VOL) \ + , \ + PVCP(c, v, Volume.Right.Reg_VOL), \ + PVCP(c, v, Pitch), \ + PVCP(c, v, ADSR.regADSR1), \ + PVCP(c, v, ADSR.regADSR2), \ + PVCP(c, v, ADSR.Value) + 1, \ + PVCP(c, v, Volume.Left.Value) + 1, \ + PVCP(c, v, Volume.Right.Value) + 1 -#define PVCA(c,v) \ - PVCP(c,v,StartA)+1, \ - PVCP(c,v,StartA), \ - PVCP(c,v,LoopStartA)+1, \ - PVCP(c,v,LoopStartA), \ - PVCP(c,v,NextA)+1, \ - PVCP(c,v,NextA) +#define PVCA(c, v) \ + PVCP(c, v, StartA) + 1, \ + PVCP(c, v, StartA), \ + PVCP(c, v, LoopStartA) + 1, \ + PVCP(c, v, LoopStartA), \ + PVCP(c, v, NextA) + 1, \ + PVCP(c, v, NextA) #define PRAW(a) \ - ((u16*)NULL) + ((u16 *)NULL) -#define PREVB_REG(c,n) \ - PCORE(c,Revb.n)+1, \ - PCORE(c,Revb.n) +#define PREVB_REG(c, n) \ + PCORE(c, Revb.n) + 1, \ + PCORE(c, Revb.n) -u16* regtable[0x401]; +u16 *regtable[0x401]; -u16 const* const regtable_original[0x401] = -{ - // Voice Params: 8 params, 24 voices = 0x180 bytes - PVC(0, 0),PVC(0, 1),PVC(0, 2),PVC(0, 3),PVC(0, 4),PVC(0, 5), - PVC(0, 6),PVC(0, 7),PVC(0, 8),PVC(0, 9),PVC(0,10),PVC(0,11), - PVC(0,12),PVC(0,13),PVC(0,14),PVC(0,15),PVC(0,16),PVC(0,17), - PVC(0,18),PVC(0,19),PVC(0,20),PVC(0,21),PVC(0,22),PVC(0,23), +u16 const *const regtable_original[0x401] = + { + // Voice Params: 8 params, 24 voices = 0x180 bytes + PVC(0, 0), PVC(0, 1), PVC(0, 2), PVC(0, 3), PVC(0, 4), PVC(0, 5), + PVC(0, 6), PVC(0, 7), PVC(0, 8), PVC(0, 9), PVC(0, 10), PVC(0, 11), + PVC(0, 12), PVC(0, 13), PVC(0, 14), PVC(0, 15), PVC(0, 16), PVC(0, 17), + PVC(0, 18), PVC(0, 19), PVC(0, 20), PVC(0, 21), PVC(0, 22), PVC(0, 23), - PCORE(0,Regs.PMON), - PCORE(0,Regs.PMON)+1, - PCORE(0,Regs.NON), - PCORE(0,Regs.NON)+1, - PCORE(0,Regs.VMIXL), - PCORE(0,Regs.VMIXL)+1, - PCORE(0,Regs.VMIXEL), - PCORE(0,Regs.VMIXEL)+1, - PCORE(0,Regs.VMIXR), - PCORE(0,Regs.VMIXR)+1, - PCORE(0,Regs.VMIXER), - PCORE(0,Regs.VMIXER)+1, + PCORE(0, Regs.PMON), + PCORE(0, Regs.PMON) + 1, + PCORE(0, Regs.NON), + PCORE(0, Regs.NON) + 1, + PCORE(0, Regs.VMIXL), + PCORE(0, Regs.VMIXL) + 1, + PCORE(0, Regs.VMIXEL), + PCORE(0, Regs.VMIXEL) + 1, + PCORE(0, Regs.VMIXR), + PCORE(0, Regs.VMIXR) + 1, + PCORE(0, Regs.VMIXER), + PCORE(0, Regs.VMIXER) + 1, - PCORE(0,Regs.MMIX), - PCORE(0,Regs.ATTR), + PCORE(0, Regs.MMIX), + PCORE(0, Regs.ATTR), - PCORE(0,IRQA)+1, - PCORE(0,IRQA), + PCORE(0, IRQA) + 1, + PCORE(0, IRQA), - NULL, NULL, - NULL, NULL, + NULL, NULL, + NULL, NULL, - PCORE(0,TSA)+1, - PCORE(0,TSA), + PCORE(0, TSA) + 1, + PCORE(0, TSA), - PRAW(REG__1AC), PRAW(REG__1AE), + PRAW(REG__1AC), PRAW(REG__1AE), - PCORE(0,AutoDMACtrl), + PCORE(0, AutoDMACtrl), - PRAW(0x1b2), PRAW(0x1b4), PRAW(0x1b6), PRAW(0x1b8), PRAW(0x1ba), PRAW(0x1bc), PRAW(0x1be), // unknown + PRAW(0x1b2), PRAW(0x1b4), PRAW(0x1b6), PRAW(0x1b8), PRAW(0x1ba), PRAW(0x1bc), PRAW(0x1be), // unknown - // Voice Addresses - PVCA(0, 0),PVCA(0, 1),PVCA(0, 2),PVCA(0, 3),PVCA(0, 4),PVCA(0, 5), - PVCA(0, 6),PVCA(0, 7),PVCA(0, 8),PVCA(0, 9),PVCA(0,10),PVCA(0,11), - PVCA(0,12),PVCA(0,13),PVCA(0,14),PVCA(0,15),PVCA(0,16),PVCA(0,17), - PVCA(0,18),PVCA(0,19),PVCA(0,20),PVCA(0,21),PVCA(0,22),PVCA(0,23), + // Voice Addresses + PVCA(0, 0), PVCA(0, 1), PVCA(0, 2), PVCA(0, 3), PVCA(0, 4), PVCA(0, 5), + PVCA(0, 6), PVCA(0, 7), PVCA(0, 8), PVCA(0, 9), PVCA(0, 10), PVCA(0, 11), + PVCA(0, 12), PVCA(0, 13), PVCA(0, 14), PVCA(0, 15), PVCA(0, 16), PVCA(0, 17), + PVCA(0, 18), PVCA(0, 19), PVCA(0, 20), PVCA(0, 21), PVCA(0, 22), PVCA(0, 23), - PCORE(0,ExtEffectsStartA)+1, - PCORE(0,ExtEffectsStartA), + PCORE(0, ExtEffectsStartA) + 1, + PCORE(0, ExtEffectsStartA), - PREVB_REG(0,FB_SRC_A), - PREVB_REG(0,FB_SRC_B), - PREVB_REG(0,IIR_DEST_A0), - PREVB_REG(0,IIR_DEST_A1), - PREVB_REG(0,ACC_SRC_A0), - PREVB_REG(0,ACC_SRC_A1), - PREVB_REG(0,ACC_SRC_B0), - PREVB_REG(0,ACC_SRC_B1), - PREVB_REG(0,IIR_SRC_A0), - PREVB_REG(0,IIR_SRC_A1), - PREVB_REG(0,IIR_DEST_B0), - PREVB_REG(0,IIR_DEST_B1), - PREVB_REG(0,ACC_SRC_C0), - PREVB_REG(0,ACC_SRC_C1), - PREVB_REG(0,ACC_SRC_D0), - PREVB_REG(0,ACC_SRC_D1), - PREVB_REG(0,IIR_SRC_B0), - PREVB_REG(0,IIR_SRC_B1), - PREVB_REG(0,MIX_DEST_A0), - PREVB_REG(0,MIX_DEST_A1), - PREVB_REG(0,MIX_DEST_B0), - PREVB_REG(0,MIX_DEST_B1), + PREVB_REG(0, FB_SRC_A), + PREVB_REG(0, FB_SRC_B), + PREVB_REG(0, IIR_DEST_A0), + PREVB_REG(0, IIR_DEST_A1), + PREVB_REG(0, ACC_SRC_A0), + PREVB_REG(0, ACC_SRC_A1), + PREVB_REG(0, ACC_SRC_B0), + PREVB_REG(0, ACC_SRC_B1), + PREVB_REG(0, IIR_SRC_A0), + PREVB_REG(0, IIR_SRC_A1), + PREVB_REG(0, IIR_DEST_B0), + PREVB_REG(0, IIR_DEST_B1), + PREVB_REG(0, ACC_SRC_C0), + PREVB_REG(0, ACC_SRC_C1), + PREVB_REG(0, ACC_SRC_D0), + PREVB_REG(0, ACC_SRC_D1), + PREVB_REG(0, IIR_SRC_B0), + PREVB_REG(0, IIR_SRC_B1), + PREVB_REG(0, MIX_DEST_A0), + PREVB_REG(0, MIX_DEST_A1), + PREVB_REG(0, MIX_DEST_B0), + PREVB_REG(0, MIX_DEST_B1), - PCORE(0,ExtEffectsEndA)+1, - PCORE(0,ExtEffectsEndA), + PCORE(0, ExtEffectsEndA) + 1, + PCORE(0, ExtEffectsEndA), - PCORE(0,Regs.ENDX), - PCORE(0,Regs.ENDX)+1, - PCORE(0,Regs.STATX), + PCORE(0, Regs.ENDX), + PCORE(0, Regs.ENDX) + 1, + PCORE(0, Regs.STATX), - //0x346 here - PRAW(0x346), - PRAW(0x348),PRAW(0x34A),PRAW(0x34C),PRAW(0x34E), - PRAW(0x350),PRAW(0x352),PRAW(0x354),PRAW(0x356), - PRAW(0x358),PRAW(0x35A),PRAW(0x35C),PRAW(0x35E), - PRAW(0x360),PRAW(0x362),PRAW(0x364),PRAW(0x366), - PRAW(0x368),PRAW(0x36A),PRAW(0x36C),PRAW(0x36E), - PRAW(0x370),PRAW(0x372),PRAW(0x374),PRAW(0x376), - PRAW(0x378),PRAW(0x37A),PRAW(0x37C),PRAW(0x37E), - PRAW(0x380),PRAW(0x382),PRAW(0x384),PRAW(0x386), - PRAW(0x388),PRAW(0x38A),PRAW(0x38C),PRAW(0x38E), - PRAW(0x390),PRAW(0x392),PRAW(0x394),PRAW(0x396), - PRAW(0x398),PRAW(0x39A),PRAW(0x39C),PRAW(0x39E), - PRAW(0x3A0),PRAW(0x3A2),PRAW(0x3A4),PRAW(0x3A6), - PRAW(0x3A8),PRAW(0x3AA),PRAW(0x3AC),PRAW(0x3AE), - PRAW(0x3B0),PRAW(0x3B2),PRAW(0x3B4),PRAW(0x3B6), - PRAW(0x3B8),PRAW(0x3BA),PRAW(0x3BC),PRAW(0x3BE), - PRAW(0x3C0),PRAW(0x3C2),PRAW(0x3C4),PRAW(0x3C6), - PRAW(0x3C8),PRAW(0x3CA),PRAW(0x3CC),PRAW(0x3CE), - PRAW(0x3D0),PRAW(0x3D2),PRAW(0x3D4),PRAW(0x3D6), - PRAW(0x3D8),PRAW(0x3DA),PRAW(0x3DC),PRAW(0x3DE), - PRAW(0x3E0),PRAW(0x3E2),PRAW(0x3E4),PRAW(0x3E6), - PRAW(0x3E8),PRAW(0x3EA),PRAW(0x3EC),PRAW(0x3EE), - PRAW(0x3F0),PRAW(0x3F2),PRAW(0x3F4),PRAW(0x3F6), - PRAW(0x3F8),PRAW(0x3FA),PRAW(0x3FC),PRAW(0x3FE), + //0x346 here + PRAW(0x346), + PRAW(0x348), PRAW(0x34A), PRAW(0x34C), PRAW(0x34E), + PRAW(0x350), PRAW(0x352), PRAW(0x354), PRAW(0x356), + PRAW(0x358), PRAW(0x35A), PRAW(0x35C), PRAW(0x35E), + PRAW(0x360), PRAW(0x362), PRAW(0x364), PRAW(0x366), + PRAW(0x368), PRAW(0x36A), PRAW(0x36C), PRAW(0x36E), + PRAW(0x370), PRAW(0x372), PRAW(0x374), PRAW(0x376), + PRAW(0x378), PRAW(0x37A), PRAW(0x37C), PRAW(0x37E), + PRAW(0x380), PRAW(0x382), PRAW(0x384), PRAW(0x386), + PRAW(0x388), PRAW(0x38A), PRAW(0x38C), PRAW(0x38E), + PRAW(0x390), PRAW(0x392), PRAW(0x394), PRAW(0x396), + PRAW(0x398), PRAW(0x39A), PRAW(0x39C), PRAW(0x39E), + PRAW(0x3A0), PRAW(0x3A2), PRAW(0x3A4), PRAW(0x3A6), + PRAW(0x3A8), PRAW(0x3AA), PRAW(0x3AC), PRAW(0x3AE), + PRAW(0x3B0), PRAW(0x3B2), PRAW(0x3B4), PRAW(0x3B6), + PRAW(0x3B8), PRAW(0x3BA), PRAW(0x3BC), PRAW(0x3BE), + PRAW(0x3C0), PRAW(0x3C2), PRAW(0x3C4), PRAW(0x3C6), + PRAW(0x3C8), PRAW(0x3CA), PRAW(0x3CC), PRAW(0x3CE), + PRAW(0x3D0), PRAW(0x3D2), PRAW(0x3D4), PRAW(0x3D6), + PRAW(0x3D8), PRAW(0x3DA), PRAW(0x3DC), PRAW(0x3DE), + PRAW(0x3E0), PRAW(0x3E2), PRAW(0x3E4), PRAW(0x3E6), + PRAW(0x3E8), PRAW(0x3EA), PRAW(0x3EC), PRAW(0x3EE), + PRAW(0x3F0), PRAW(0x3F2), PRAW(0x3F4), PRAW(0x3F6), + PRAW(0x3F8), PRAW(0x3FA), PRAW(0x3FC), PRAW(0x3FE), - //AND... we reached 0x400! - // Voice Params: 8 params, 24 voices = 0x180 bytes - PVC(1, 0),PVC(1, 1),PVC(1, 2),PVC(1, 3),PVC(1, 4),PVC(1, 5), - PVC(1, 6),PVC(1, 7),PVC(1, 8),PVC(1, 9),PVC(1,10),PVC(1,11), - PVC(1,12),PVC(1,13),PVC(1,14),PVC(1,15),PVC(1,16),PVC(1,17), - PVC(1,18),PVC(1,19),PVC(1,20),PVC(1,21),PVC(1,22),PVC(1,23), + //AND... we reached 0x400! + // Voice Params: 8 params, 24 voices = 0x180 bytes + PVC(1, 0), PVC(1, 1), PVC(1, 2), PVC(1, 3), PVC(1, 4), PVC(1, 5), + PVC(1, 6), PVC(1, 7), PVC(1, 8), PVC(1, 9), PVC(1, 10), PVC(1, 11), + PVC(1, 12), PVC(1, 13), PVC(1, 14), PVC(1, 15), PVC(1, 16), PVC(1, 17), + PVC(1, 18), PVC(1, 19), PVC(1, 20), PVC(1, 21), PVC(1, 22), PVC(1, 23), - PCORE(1,Regs.PMON), - PCORE(1,Regs.PMON)+1, - PCORE(1,Regs.NON), - PCORE(1,Regs.NON)+1, - PCORE(1,Regs.VMIXL), - PCORE(1,Regs.VMIXL)+1, - PCORE(1,Regs.VMIXEL), - PCORE(1,Regs.VMIXEL)+1, - PCORE(1,Regs.VMIXR), - PCORE(1,Regs.VMIXR)+1, - PCORE(1,Regs.VMIXER), - PCORE(1,Regs.VMIXER)+1, - PCORE(1,Regs.MMIX), + PCORE(1, Regs.PMON), + PCORE(1, Regs.PMON) + 1, + PCORE(1, Regs.NON), + PCORE(1, Regs.NON) + 1, + PCORE(1, Regs.VMIXL), + PCORE(1, Regs.VMIXL) + 1, + PCORE(1, Regs.VMIXEL), + PCORE(1, Regs.VMIXEL) + 1, + PCORE(1, Regs.VMIXR), + PCORE(1, Regs.VMIXR) + 1, + PCORE(1, Regs.VMIXER), + PCORE(1, Regs.VMIXER) + 1, + PCORE(1, Regs.MMIX), - PCORE(1,Regs.ATTR), + PCORE(1, Regs.ATTR), - PCORE(1,IRQA)+1, - PCORE(1,IRQA), + PCORE(1, IRQA) + 1, + PCORE(1, IRQA), - NULL, NULL, - NULL, NULL, + NULL, NULL, + NULL, NULL, - PCORE(1,TSA)+1, - PCORE(1,TSA), + PCORE(1, TSA) + 1, + PCORE(1, TSA), - PRAW(0x5ac), PRAW(0x5ae), + PRAW(0x5ac), PRAW(0x5ae), - PCORE(1,AutoDMACtrl), + PCORE(1, AutoDMACtrl), - PRAW(0x5b2), PRAW(0x5b4), PRAW(0x5b6), PRAW(0x5b8), PRAW(0x5ba), PRAW(0x5bc), PRAW(0x5be), // unknown + PRAW(0x5b2), PRAW(0x5b4), PRAW(0x5b6), PRAW(0x5b8), PRAW(0x5ba), PRAW(0x5bc), PRAW(0x5be), // unknown - // Voice Addresses - PVCA(1, 0),PVCA(1, 1),PVCA(1, 2),PVCA(1, 3),PVCA(1, 4),PVCA(1, 5), - PVCA(1, 6),PVCA(1, 7),PVCA(1, 8),PVCA(1, 9),PVCA(1,10),PVCA(1,11), - PVCA(1,12),PVCA(1,13),PVCA(1,14),PVCA(1,15),PVCA(1,16),PVCA(1,17), - PVCA(1,18),PVCA(1,19),PVCA(1,20),PVCA(1,21),PVCA(1,22),PVCA(1,23), + // Voice Addresses + PVCA(1, 0), PVCA(1, 1), PVCA(1, 2), PVCA(1, 3), PVCA(1, 4), PVCA(1, 5), + PVCA(1, 6), PVCA(1, 7), PVCA(1, 8), PVCA(1, 9), PVCA(1, 10), PVCA(1, 11), + PVCA(1, 12), PVCA(1, 13), PVCA(1, 14), PVCA(1, 15), PVCA(1, 16), PVCA(1, 17), + PVCA(1, 18), PVCA(1, 19), PVCA(1, 20), PVCA(1, 21), PVCA(1, 22), PVCA(1, 23), - PCORE(1,ExtEffectsStartA)+1, - PCORE(1,ExtEffectsStartA), + PCORE(1, ExtEffectsStartA) + 1, + PCORE(1, ExtEffectsStartA), - PREVB_REG(1,FB_SRC_A), - PREVB_REG(1,FB_SRC_B), - PREVB_REG(1,IIR_DEST_A0), - PREVB_REG(1,IIR_DEST_A1), - PREVB_REG(1,ACC_SRC_A0), - PREVB_REG(1,ACC_SRC_A1), - PREVB_REG(1,ACC_SRC_B0), - PREVB_REG(1,ACC_SRC_B1), - PREVB_REG(1,IIR_SRC_A0), - PREVB_REG(1,IIR_SRC_A1), - PREVB_REG(1,IIR_DEST_B0), - PREVB_REG(1,IIR_DEST_B1), - PREVB_REG(1,ACC_SRC_C0), - PREVB_REG(1,ACC_SRC_C1), - PREVB_REG(1,ACC_SRC_D0), - PREVB_REG(1,ACC_SRC_D1), - PREVB_REG(1,IIR_SRC_B0), - PREVB_REG(1,IIR_SRC_B1), - PREVB_REG(1,MIX_DEST_A0), - PREVB_REG(1,MIX_DEST_A1), - PREVB_REG(1,MIX_DEST_B0), - PREVB_REG(1,MIX_DEST_B1), + PREVB_REG(1, FB_SRC_A), + PREVB_REG(1, FB_SRC_B), + PREVB_REG(1, IIR_DEST_A0), + PREVB_REG(1, IIR_DEST_A1), + PREVB_REG(1, ACC_SRC_A0), + PREVB_REG(1, ACC_SRC_A1), + PREVB_REG(1, ACC_SRC_B0), + PREVB_REG(1, ACC_SRC_B1), + PREVB_REG(1, IIR_SRC_A0), + PREVB_REG(1, IIR_SRC_A1), + PREVB_REG(1, IIR_DEST_B0), + PREVB_REG(1, IIR_DEST_B1), + PREVB_REG(1, ACC_SRC_C0), + PREVB_REG(1, ACC_SRC_C1), + PREVB_REG(1, ACC_SRC_D0), + PREVB_REG(1, ACC_SRC_D1), + PREVB_REG(1, IIR_SRC_B0), + PREVB_REG(1, IIR_SRC_B1), + PREVB_REG(1, MIX_DEST_A0), + PREVB_REG(1, MIX_DEST_A1), + PREVB_REG(1, MIX_DEST_B0), + PREVB_REG(1, MIX_DEST_B1), - PCORE(1,ExtEffectsEndA)+1, - PCORE(1,ExtEffectsEndA), + PCORE(1, ExtEffectsEndA) + 1, + PCORE(1, ExtEffectsEndA), - PCORE(1,Regs.ENDX), - PCORE(1,Regs.ENDX)+1, - PCORE(1,Regs.STATX), + PCORE(1, Regs.ENDX), + PCORE(1, Regs.ENDX) + 1, + PCORE(1, Regs.STATX), - PRAW(0x746), - PRAW(0x748),PRAW(0x74A),PRAW(0x74C),PRAW(0x74E), - PRAW(0x750),PRAW(0x752),PRAW(0x754),PRAW(0x756), - PRAW(0x758),PRAW(0x75A),PRAW(0x75C),PRAW(0x75E), + PRAW(0x746), + PRAW(0x748), PRAW(0x74A), PRAW(0x74C), PRAW(0x74E), + PRAW(0x750), PRAW(0x752), PRAW(0x754), PRAW(0x756), + PRAW(0x758), PRAW(0x75A), PRAW(0x75C), PRAW(0x75E), - //0x760: weird area - PCORE(0,MasterVol.Left.Reg_VOL), - PCORE(0,MasterVol.Right.Reg_VOL), - PCORE(0,FxVol.Left)+1, - PCORE(0,FxVol.Right)+1, - PCORE(0,ExtVol.Left)+1, - PCORE(0,ExtVol.Right)+1, - PCORE(0,InpVol.Left)+1, - PCORE(0,InpVol.Right)+1, - PCORE(0,MasterVol.Left.Value)+1, - PCORE(0,MasterVol.Right.Value)+1, - PCORE(0,Revb.IIR_ALPHA), - PCORE(0,Revb.ACC_COEF_A), - PCORE(0,Revb.ACC_COEF_B), - PCORE(0,Revb.ACC_COEF_C), - PCORE(0,Revb.ACC_COEF_D), - PCORE(0,Revb.IIR_COEF), - PCORE(0,Revb.FB_ALPHA), - PCORE(0,Revb.FB_X), - PCORE(0,Revb.IN_COEF_L), - PCORE(0,Revb.IN_COEF_R), + //0x760: weird area + PCORE(0, MasterVol.Left.Reg_VOL), + PCORE(0, MasterVol.Right.Reg_VOL), + PCORE(0, FxVol.Left) + 1, + PCORE(0, FxVol.Right) + 1, + PCORE(0, ExtVol.Left) + 1, + PCORE(0, ExtVol.Right) + 1, + PCORE(0, InpVol.Left) + 1, + PCORE(0, InpVol.Right) + 1, + PCORE(0, MasterVol.Left.Value) + 1, + PCORE(0, MasterVol.Right.Value) + 1, + PCORE(0, Revb.IIR_ALPHA), + PCORE(0, Revb.ACC_COEF_A), + PCORE(0, Revb.ACC_COEF_B), + PCORE(0, Revb.ACC_COEF_C), + PCORE(0, Revb.ACC_COEF_D), + PCORE(0, Revb.IIR_COEF), + PCORE(0, Revb.FB_ALPHA), + PCORE(0, Revb.FB_X), + PCORE(0, Revb.IN_COEF_L), + PCORE(0, Revb.IN_COEF_R), - PCORE(1,MasterVol.Left.Reg_VOL), - PCORE(1,MasterVol.Right.Reg_VOL), - PCORE(1,FxVol.Left)+1, - PCORE(1,FxVol.Right)+1, - PCORE(1,ExtVol.Left)+1, - PCORE(1,ExtVol.Right)+1, - PCORE(1,InpVol.Left)+1, - PCORE(1,InpVol.Right)+1, - PCORE(1,MasterVol.Left.Value)+1, - PCORE(1,MasterVol.Right.Value)+1, - PCORE(1,Revb.IIR_ALPHA), - PCORE(1,Revb.ACC_COEF_A), - PCORE(1,Revb.ACC_COEF_B), - PCORE(1,Revb.ACC_COEF_C), - PCORE(1,Revb.ACC_COEF_D), - PCORE(1,Revb.IIR_COEF), - PCORE(1,Revb.FB_ALPHA), - PCORE(1,Revb.FB_X), - PCORE(1,Revb.IN_COEF_L), - PCORE(1,Revb.IN_COEF_R), + PCORE(1, MasterVol.Left.Reg_VOL), + PCORE(1, MasterVol.Right.Reg_VOL), + PCORE(1, FxVol.Left) + 1, + PCORE(1, FxVol.Right) + 1, + PCORE(1, ExtVol.Left) + 1, + PCORE(1, ExtVol.Right) + 1, + PCORE(1, InpVol.Left) + 1, + PCORE(1, InpVol.Right) + 1, + PCORE(1, MasterVol.Left.Value) + 1, + PCORE(1, MasterVol.Right.Value) + 1, + PCORE(1, Revb.IIR_ALPHA), + PCORE(1, Revb.ACC_COEF_A), + PCORE(1, Revb.ACC_COEF_B), + PCORE(1, Revb.ACC_COEF_C), + PCORE(1, Revb.ACC_COEF_D), + PCORE(1, Revb.IIR_COEF), + PCORE(1, Revb.FB_ALPHA), + PCORE(1, Revb.FB_X), + PCORE(1, Revb.IN_COEF_L), + PCORE(1, Revb.IN_COEF_R), - PRAW(0x7B0),PRAW(0x7B2),PRAW(0x7B4),PRAW(0x7B6), - PRAW(0x7B8),PRAW(0x7BA),PRAW(0x7BC),PRAW(0x7BE), + PRAW(0x7B0), PRAW(0x7B2), PRAW(0x7B4), PRAW(0x7B6), + PRAW(0x7B8), PRAW(0x7BA), PRAW(0x7BC), PRAW(0x7BE), - // SPDIF interface - U16P(Spdif.Out), - U16P(Spdif.Info), - U16P(Spdif.Unknown1), - U16P(Spdif.Mode), - U16P(Spdif.Media), - U16P(Spdif.Unknown2), - U16P(Spdif.Protection), + // SPDIF interface + U16P(Spdif.Out), + U16P(Spdif.Info), + U16P(Spdif.Unknown1), + U16P(Spdif.Mode), + U16P(Spdif.Media), + U16P(Spdif.Unknown2), + U16P(Spdif.Protection), - PRAW(0x7CE), - PRAW(0x7D0),PRAW(0x7D2),PRAW(0x7D4),PRAW(0x7D6), - PRAW(0x7D8),PRAW(0x7DA),PRAW(0x7DC),PRAW(0x7DE), - PRAW(0x7E0),PRAW(0x7E2),PRAW(0x7E4),PRAW(0x7E6), - PRAW(0x7E8),PRAW(0x7EA),PRAW(0x7EC),PRAW(0x7EE), - PRAW(0x7F0),PRAW(0x7F2),PRAW(0x7F4),PRAW(0x7F6), - PRAW(0x7F8),PRAW(0x7FA),PRAW(0x7FC),PRAW(0x7FE), + PRAW(0x7CE), + PRAW(0x7D0), PRAW(0x7D2), PRAW(0x7D4), PRAW(0x7D6), + PRAW(0x7D8), PRAW(0x7DA), PRAW(0x7DC), PRAW(0x7DE), + PRAW(0x7E0), PRAW(0x7E2), PRAW(0x7E4), PRAW(0x7E6), + PRAW(0x7E8), PRAW(0x7EA), PRAW(0x7EC), PRAW(0x7EE), + PRAW(0x7F0), PRAW(0x7F2), PRAW(0x7F4), PRAW(0x7F6), + PRAW(0x7F8), PRAW(0x7FA), PRAW(0x7FC), PRAW(0x7FE), - NULL -}; + NULL}; diff --git a/plugins/spu2-x/src/Reverb.cpp b/plugins/spu2-x/src/Reverb.cpp index a56bf2de07..c88b7888ad 100644 --- a/plugins/spu2-x/src/Reverb.cpp +++ b/plugins/spu2-x/src/Reverb.cpp @@ -24,38 +24,37 @@ //static LowPassFilter64 lowpass_left( 11000, SampleRate ); //static LowPassFilter64 lowpass_right( 11000, SampleRate ); -__forceinline s32 V_Core::RevbGetIndexer( s32 offset ) +__forceinline s32 V_Core::RevbGetIndexer(s32 offset) { - u32 pos = ReverbX + offset; + u32 pos = ReverbX + offset; - // Fast and simple single step wrapping, made possible by the preparation of the - // effects buffer addresses. + // Fast and simple single step wrapping, made possible by the preparation of the + // effects buffer addresses. - if( pos > EffectsEndA ) - { - pos -= EffectsEndA+1; - pos += EffectsStartA; - } + if (pos > EffectsEndA) { + pos -= EffectsEndA + 1; + pos += EffectsStartA; + } - assert(pos >= EffectsStartA && pos <= EffectsEndA); - return pos; + assert(pos >= EffectsStartA && pos <= EffectsEndA); + return pos; } void V_Core::Reverb_AdvanceBuffer() { - if( RevBuffers.NeedsUpdated ) - UpdateEffectsBufferSize(); + if (RevBuffers.NeedsUpdated) + UpdateEffectsBufferSize(); - if( (Cycles & 1) && (EffectsBufferSize > 0) ) - { - ReverbX += 1; - if( ReverbX >= (u32)EffectsBufferSize ) ReverbX = 0; - } + if ((Cycles & 1) && (EffectsBufferSize > 0)) { + ReverbX += 1; + if (ReverbX >= (u32)EffectsBufferSize) + ReverbX = 0; + } } ///////////////////////////////////////////////////////////////////////////////////////// -StereoOut32 V_Core::DoReverb( const StereoOut32& Input ) +StereoOut32 V_Core::DoReverb(const StereoOut32 &Input) { #if 0 static const s32 downcoeffs[8] = @@ -64,222 +63,208 @@ StereoOut32 V_Core::DoReverb( const StereoOut32& Input ) 15243, 10895, 5344, 1283 }; #else - // 2/3 of the above - static const s32 downcoeffs[8] = - { - 855, 3562, 7263, 10163, - 10163, 7263, 3562, 855 - }; + // 2/3 of the above + static const s32 downcoeffs[8] = + { + 855, 3562, 7263, 10163, + 10163, 7263, 3562, 855}; #endif - downbuf[dbpos] = Input; - dbpos = (dbpos+1) & 7; + downbuf[dbpos] = Input; + dbpos = (dbpos + 1) & 7; - // Reverb processing occurs at 24khz, so we skip processing every other sample, - // and use the previous calculation for this core instead. + // Reverb processing occurs at 24khz, so we skip processing every other sample, + // and use the previous calculation for this core instead. - if( (Cycles&1) == 0 ) - { - // Important: Factor silence into the upsampler here, otherwise the reverb engine - // develops a nasty feedback loop. + if ((Cycles & 1) == 0) { + // Important: Factor silence into the upsampler here, otherwise the reverb engine + // develops a nasty feedback loop. - upbuf[ubpos] = StereoOut32::Empty; - } - else - { - if( EffectsBufferSize <= 0 ) - { - ubpos = (ubpos+1) & 7; - return StereoOut32::Empty; - } + upbuf[ubpos] = StereoOut32::Empty; + } else { + if (EffectsBufferSize <= 0) { + ubpos = (ubpos + 1) & 7; + return StereoOut32::Empty; + } - // Advance the current reverb buffer pointer, and cache the read/write addresses we'll be - // needing for this session of reverb. + // Advance the current reverb buffer pointer, and cache the read/write addresses we'll be + // needing for this session of reverb. - const u32 src_a0 = RevbGetIndexer( RevBuffers.IIR_SRC_A0 ); - const u32 src_a1 = RevbGetIndexer( RevBuffers.IIR_SRC_A1 ); - const u32 src_b0 = RevbGetIndexer( RevBuffers.IIR_SRC_B0 ); - const u32 src_b1 = RevbGetIndexer( RevBuffers.IIR_SRC_B1 ); + const u32 src_a0 = RevbGetIndexer(RevBuffers.IIR_SRC_A0); + const u32 src_a1 = RevbGetIndexer(RevBuffers.IIR_SRC_A1); + const u32 src_b0 = RevbGetIndexer(RevBuffers.IIR_SRC_B0); + const u32 src_b1 = RevbGetIndexer(RevBuffers.IIR_SRC_B1); - const u32 dest_a0 = RevbGetIndexer( RevBuffers.IIR_DEST_A0 ); - const u32 dest_a1 = RevbGetIndexer( RevBuffers.IIR_DEST_A1 ); - const u32 dest_b0 = RevbGetIndexer( RevBuffers.IIR_DEST_B0 ); - const u32 dest_b1 = RevbGetIndexer( RevBuffers.IIR_DEST_B1 ); + const u32 dest_a0 = RevbGetIndexer(RevBuffers.IIR_DEST_A0); + const u32 dest_a1 = RevbGetIndexer(RevBuffers.IIR_DEST_A1); + const u32 dest_b0 = RevbGetIndexer(RevBuffers.IIR_DEST_B0); + const u32 dest_b1 = RevbGetIndexer(RevBuffers.IIR_DEST_B1); - const u32 dest2_a0 = RevbGetIndexer( RevBuffers.IIR_DEST_A0 + 1 ); - const u32 dest2_a1 = RevbGetIndexer( RevBuffers.IIR_DEST_A1 + 1 ); - const u32 dest2_b0 = RevbGetIndexer( RevBuffers.IIR_DEST_B0 + 1 ); - const u32 dest2_b1 = RevbGetIndexer( RevBuffers.IIR_DEST_B1 + 1 ); + const u32 dest2_a0 = RevbGetIndexer(RevBuffers.IIR_DEST_A0 + 1); + const u32 dest2_a1 = RevbGetIndexer(RevBuffers.IIR_DEST_A1 + 1); + const u32 dest2_b0 = RevbGetIndexer(RevBuffers.IIR_DEST_B0 + 1); + const u32 dest2_b1 = RevbGetIndexer(RevBuffers.IIR_DEST_B1 + 1); - const u32 acc_src_a0 = RevbGetIndexer( RevBuffers.ACC_SRC_A0 ); - const u32 acc_src_b0 = RevbGetIndexer( RevBuffers.ACC_SRC_B0 ); - const u32 acc_src_c0 = RevbGetIndexer( RevBuffers.ACC_SRC_C0 ); - const u32 acc_src_d0 = RevbGetIndexer( RevBuffers.ACC_SRC_D0 ); + const u32 acc_src_a0 = RevbGetIndexer(RevBuffers.ACC_SRC_A0); + const u32 acc_src_b0 = RevbGetIndexer(RevBuffers.ACC_SRC_B0); + const u32 acc_src_c0 = RevbGetIndexer(RevBuffers.ACC_SRC_C0); + const u32 acc_src_d0 = RevbGetIndexer(RevBuffers.ACC_SRC_D0); - const u32 acc_src_a1 = RevbGetIndexer( RevBuffers.ACC_SRC_A1 ); - const u32 acc_src_b1 = RevbGetIndexer( RevBuffers.ACC_SRC_B1 ); - const u32 acc_src_c1 = RevbGetIndexer( RevBuffers.ACC_SRC_C1 ); - const u32 acc_src_d1 = RevbGetIndexer( RevBuffers.ACC_SRC_D1 ); + const u32 acc_src_a1 = RevbGetIndexer(RevBuffers.ACC_SRC_A1); + const u32 acc_src_b1 = RevbGetIndexer(RevBuffers.ACC_SRC_B1); + const u32 acc_src_c1 = RevbGetIndexer(RevBuffers.ACC_SRC_C1); + const u32 acc_src_d1 = RevbGetIndexer(RevBuffers.ACC_SRC_D1); - const u32 fb_src_a0 = RevbGetIndexer( RevBuffers.FB_SRC_A0 ); - const u32 fb_src_a1 = RevbGetIndexer( RevBuffers.FB_SRC_A1 ); - const u32 fb_src_b0 = RevbGetIndexer( RevBuffers.FB_SRC_B0 ); - const u32 fb_src_b1 = RevbGetIndexer( RevBuffers.FB_SRC_B1 ); + const u32 fb_src_a0 = RevbGetIndexer(RevBuffers.FB_SRC_A0); + const u32 fb_src_a1 = RevbGetIndexer(RevBuffers.FB_SRC_A1); + const u32 fb_src_b0 = RevbGetIndexer(RevBuffers.FB_SRC_B0); + const u32 fb_src_b1 = RevbGetIndexer(RevBuffers.FB_SRC_B1); - const u32 mix_dest_a0 = RevbGetIndexer( RevBuffers.MIX_DEST_A0 ); - const u32 mix_dest_a1 = RevbGetIndexer( RevBuffers.MIX_DEST_A1 ); - const u32 mix_dest_b0 = RevbGetIndexer( RevBuffers.MIX_DEST_B0 ); - const u32 mix_dest_b1 = RevbGetIndexer( RevBuffers.MIX_DEST_B1 ); + const u32 mix_dest_a0 = RevbGetIndexer(RevBuffers.MIX_DEST_A0); + const u32 mix_dest_a1 = RevbGetIndexer(RevBuffers.MIX_DEST_A1); + const u32 mix_dest_b0 = RevbGetIndexer(RevBuffers.MIX_DEST_B0); + const u32 mix_dest_b1 = RevbGetIndexer(RevBuffers.MIX_DEST_B1); - // ----------------------------------------- - // Optimized IRQ Testing ! - // ----------------------------------------- + // ----------------------------------------- + // Optimized IRQ Testing ! + // ----------------------------------------- - // This test is enhanced by using the reverb effects area begin/end test as a - // shortcut, since all buffer addresses are within that area. If the IRQA isn't - // within that zone then the "bulk" of the test is skipped, so this should only - // be a slowdown on a few evil games. + // This test is enhanced by using the reverb effects area begin/end test as a + // shortcut, since all buffer addresses are within that area. If the IRQA isn't + // within that zone then the "bulk" of the test is skipped, so this should only + // be a slowdown on a few evil games. - for( int i=0; i<2; i++ ) - { - if( Cores[i].IRQEnable && ((Cores[i].IRQA >= EffectsStartA) && (Cores[i].IRQA <= EffectsEndA)) ) - { - if( (Cores[i].IRQA == src_a0) || (Cores[i].IRQA == src_a1) || - (Cores[i].IRQA == src_b0) || (Cores[i].IRQA == src_b1) || + for (int i = 0; i < 2; i++) { + if (Cores[i].IRQEnable && ((Cores[i].IRQA >= EffectsStartA) && (Cores[i].IRQA <= EffectsEndA))) { + if ((Cores[i].IRQA == src_a0) || (Cores[i].IRQA == src_a1) || + (Cores[i].IRQA == src_b0) || (Cores[i].IRQA == src_b1) || - (Cores[i].IRQA == dest_a0) || (Cores[i].IRQA == dest_a1) || - (Cores[i].IRQA == dest_b0) || (Cores[i].IRQA == dest_b1) || + (Cores[i].IRQA == dest_a0) || (Cores[i].IRQA == dest_a1) || + (Cores[i].IRQA == dest_b0) || (Cores[i].IRQA == dest_b1) || - (Cores[i].IRQA == dest2_a0) || (Cores[i].IRQA == dest2_a1) || - (Cores[i].IRQA == dest2_b0) || (Cores[i].IRQA == dest2_b1) || + (Cores[i].IRQA == dest2_a0) || (Cores[i].IRQA == dest2_a1) || + (Cores[i].IRQA == dest2_b0) || (Cores[i].IRQA == dest2_b1) || - (Cores[i].IRQA == acc_src_a0) || (Cores[i].IRQA == acc_src_a1) || - (Cores[i].IRQA == acc_src_b0) || (Cores[i].IRQA == acc_src_b1) || - (Cores[i].IRQA == acc_src_c0) || (Cores[i].IRQA == acc_src_c1) || - (Cores[i].IRQA == acc_src_d0) || (Cores[i].IRQA == acc_src_d1) || + (Cores[i].IRQA == acc_src_a0) || (Cores[i].IRQA == acc_src_a1) || + (Cores[i].IRQA == acc_src_b0) || (Cores[i].IRQA == acc_src_b1) || + (Cores[i].IRQA == acc_src_c0) || (Cores[i].IRQA == acc_src_c1) || + (Cores[i].IRQA == acc_src_d0) || (Cores[i].IRQA == acc_src_d1) || - (Cores[i].IRQA == fb_src_a0) || (Cores[i].IRQA == fb_src_a1) || - (Cores[i].IRQA == fb_src_b0) || (Cores[i].IRQA == fb_src_b1) || + (Cores[i].IRQA == fb_src_a0) || (Cores[i].IRQA == fb_src_a1) || + (Cores[i].IRQA == fb_src_b0) || (Cores[i].IRQA == fb_src_b1) || - (Cores[i].IRQA == mix_dest_a0) || (Cores[i].IRQA == mix_dest_a1) || - (Cores[i].IRQA == mix_dest_b0) || (Cores[i].IRQA == mix_dest_b1) ) - { - //printf("Core %d IRQ Called (Reverb). IRQA = %x\n",i,addr); - SetIrqCall(i); - } - } - } + (Cores[i].IRQA == mix_dest_a0) || (Cores[i].IRQA == mix_dest_a1) || + (Cores[i].IRQA == mix_dest_b0) || (Cores[i].IRQA == mix_dest_b1)) { + //printf("Core %d IRQ Called (Reverb). IRQA = %x\n",i,addr); + SetIrqCall(i); + } + } + } - // ----------------------------------------- - // Begin Reverb Processing ! - // ----------------------------------------- + // ----------------------------------------- + // Begin Reverb Processing ! + // ----------------------------------------- - StereoOut32 INPUT_SAMPLE; + StereoOut32 INPUT_SAMPLE; - for( int x=0; x<8; ++x ) - { - INPUT_SAMPLE.Left += (downbuf[(dbpos+x)&7].Left * downcoeffs[x]); - INPUT_SAMPLE.Right += (downbuf[(dbpos+x)&7].Right * downcoeffs[x]); - } + for (int x = 0; x < 8; ++x) { + INPUT_SAMPLE.Left += (downbuf[(dbpos + x) & 7].Left * downcoeffs[x]); + INPUT_SAMPLE.Right += (downbuf[(dbpos + x) & 7].Right * downcoeffs[x]); + } - INPUT_SAMPLE.Left >>= 16; - INPUT_SAMPLE.Right >>= 16; + INPUT_SAMPLE.Left >>= 16; + INPUT_SAMPLE.Right >>= 16; - s32 input_L = INPUT_SAMPLE.Left * Revb.IN_COEF_L; - s32 input_R = INPUT_SAMPLE.Right * Revb.IN_COEF_R; + s32 input_L = INPUT_SAMPLE.Left * Revb.IN_COEF_L; + s32 input_R = INPUT_SAMPLE.Right * Revb.IN_COEF_R; - const s32 IIR_INPUT_A0 = clamp_mix((((s32)_spu2mem[src_a0] * Revb.IIR_COEF) + input_L)>>15); - const s32 IIR_INPUT_A1 = clamp_mix((((s32)_spu2mem[src_a1] * Revb.IIR_COEF) + input_L)>>15); - const s32 IIR_INPUT_B0 = clamp_mix((((s32)_spu2mem[src_b0] * Revb.IIR_COEF) + input_R)>>15); - const s32 IIR_INPUT_B1 = clamp_mix((((s32)_spu2mem[src_b1] * Revb.IIR_COEF) + input_R)>>15); + const s32 IIR_INPUT_A0 = clamp_mix((((s32)_spu2mem[src_a0] * Revb.IIR_COEF) + input_L) >> 15); + const s32 IIR_INPUT_A1 = clamp_mix((((s32)_spu2mem[src_a1] * Revb.IIR_COEF) + input_L) >> 15); + const s32 IIR_INPUT_B0 = clamp_mix((((s32)_spu2mem[src_b0] * Revb.IIR_COEF) + input_R) >> 15); + const s32 IIR_INPUT_B1 = clamp_mix((((s32)_spu2mem[src_b1] * Revb.IIR_COEF) + input_R) >> 15); - const s32 src_dest_a0 = _spu2mem[dest_a0]; - const s32 src_dest_a1 = _spu2mem[dest_a1]; - const s32 src_dest_b0 = _spu2mem[dest_b0]; - const s32 src_dest_b1 = _spu2mem[dest_b1]; + const s32 src_dest_a0 = _spu2mem[dest_a0]; + const s32 src_dest_a1 = _spu2mem[dest_a1]; + const s32 src_dest_b0 = _spu2mem[dest_b0]; + const s32 src_dest_b1 = _spu2mem[dest_b1]; - // This section differs from Neill's doc as it uses single-mul interpolation instead - // of 0x8000-val inversion. (same result, faster) - const s32 IIR_A0 = src_dest_a0 + (((IIR_INPUT_A0 - src_dest_a0) * Revb.IIR_ALPHA)>>15); - const s32 IIR_A1 = src_dest_a1 + (((IIR_INPUT_A1 - src_dest_a1) * Revb.IIR_ALPHA)>>15); - const s32 IIR_B0 = src_dest_b0 + (((IIR_INPUT_B0 - src_dest_b0) * Revb.IIR_ALPHA)>>15); - const s32 IIR_B1 = src_dest_b1 + (((IIR_INPUT_B1 - src_dest_b1) * Revb.IIR_ALPHA)>>15); - _spu2mem[dest2_a0] = clamp_mix( IIR_A0 ); - _spu2mem[dest2_a1] = clamp_mix( IIR_A1 ); - _spu2mem[dest2_b0] = clamp_mix( IIR_B0 ); - _spu2mem[dest2_b1] = clamp_mix( IIR_B1 ); + // This section differs from Neill's doc as it uses single-mul interpolation instead + // of 0x8000-val inversion. (same result, faster) + const s32 IIR_A0 = src_dest_a0 + (((IIR_INPUT_A0 - src_dest_a0) * Revb.IIR_ALPHA) >> 15); + const s32 IIR_A1 = src_dest_a1 + (((IIR_INPUT_A1 - src_dest_a1) * Revb.IIR_ALPHA) >> 15); + const s32 IIR_B0 = src_dest_b0 + (((IIR_INPUT_B0 - src_dest_b0) * Revb.IIR_ALPHA) >> 15); + const s32 IIR_B1 = src_dest_b1 + (((IIR_INPUT_B1 - src_dest_b1) * Revb.IIR_ALPHA) >> 15); + _spu2mem[dest2_a0] = clamp_mix(IIR_A0); + _spu2mem[dest2_a1] = clamp_mix(IIR_A1); + _spu2mem[dest2_b0] = clamp_mix(IIR_B0); + _spu2mem[dest2_b1] = clamp_mix(IIR_B1); - const s32 ACC0 = clamp_mix( - ((_spu2mem[acc_src_a0] * Revb.ACC_COEF_A) >> 15) + - ((_spu2mem[acc_src_b0] * Revb.ACC_COEF_B) >> 15) + - ((_spu2mem[acc_src_c0] * Revb.ACC_COEF_C) >> 15) + - ((_spu2mem[acc_src_d0] * Revb.ACC_COEF_D) >> 15) - ); + const s32 ACC0 = clamp_mix( + ((_spu2mem[acc_src_a0] * Revb.ACC_COEF_A) >> 15) + + ((_spu2mem[acc_src_b0] * Revb.ACC_COEF_B) >> 15) + + ((_spu2mem[acc_src_c0] * Revb.ACC_COEF_C) >> 15) + + ((_spu2mem[acc_src_d0] * Revb.ACC_COEF_D) >> 15)); - const s32 ACC1 = clamp_mix( - ((_spu2mem[acc_src_a1] * Revb.ACC_COEF_A) >> 15) + - ((_spu2mem[acc_src_b1] * Revb.ACC_COEF_B) >> 15) + - ((_spu2mem[acc_src_c1] * Revb.ACC_COEF_C) >> 15) + - ((_spu2mem[acc_src_d1] * Revb.ACC_COEF_D) >> 15) - ); + const s32 ACC1 = clamp_mix( + ((_spu2mem[acc_src_a1] * Revb.ACC_COEF_A) >> 15) + + ((_spu2mem[acc_src_b1] * Revb.ACC_COEF_B) >> 15) + + ((_spu2mem[acc_src_c1] * Revb.ACC_COEF_C) >> 15) + + ((_spu2mem[acc_src_d1] * Revb.ACC_COEF_D) >> 15)); - // The following code differs from Neill's doc as it uses the more natural single-mul - // interpolative, instead of the funky ^0x8000 stuff. (better result, faster) + // The following code differs from Neill's doc as it uses the more natural single-mul + // interpolative, instead of the funky ^0x8000 stuff. (better result, faster) - const s32 FB_A0 = _spu2mem[fb_src_a0]; - const s32 FB_A1 = _spu2mem[fb_src_a1]; - const s32 FB_B0 = _spu2mem[fb_src_b0]; - const s32 FB_B1 = _spu2mem[fb_src_b1]; + const s32 FB_A0 = _spu2mem[fb_src_a0]; + const s32 FB_A1 = _spu2mem[fb_src_a1]; + const s32 FB_B0 = _spu2mem[fb_src_b0]; + const s32 FB_B1 = _spu2mem[fb_src_b1]; - const s32 mix_a0 = clamp_mix(ACC0 - ((FB_A0 * Revb.FB_ALPHA) >> 15)); - const s32 mix_a1 = clamp_mix(ACC1 - ((FB_A1 * Revb.FB_ALPHA) >> 15)); - const s32 mix_b0 = clamp_mix(FB_A0 + (((ACC0 - FB_A0) * Revb.FB_ALPHA - FB_B0 * Revb.FB_X) >> 15)); - const s32 mix_b1 = clamp_mix(FB_A1 + (((ACC1 - FB_A1) * Revb.FB_ALPHA - FB_B1 * Revb.FB_X) >> 15)); + const s32 mix_a0 = clamp_mix(ACC0 - ((FB_A0 * Revb.FB_ALPHA) >> 15)); + const s32 mix_a1 = clamp_mix(ACC1 - ((FB_A1 * Revb.FB_ALPHA) >> 15)); + const s32 mix_b0 = clamp_mix(FB_A0 + (((ACC0 - FB_A0) * Revb.FB_ALPHA - FB_B0 * Revb.FB_X) >> 15)); + const s32 mix_b1 = clamp_mix(FB_A1 + (((ACC1 - FB_A1) * Revb.FB_ALPHA - FB_B1 * Revb.FB_X) >> 15)); - _spu2mem[mix_dest_a0] = mix_a0; - _spu2mem[mix_dest_a1] = mix_a1; - _spu2mem[mix_dest_b0] = mix_b0; - _spu2mem[mix_dest_b1] = mix_b1; + _spu2mem[mix_dest_a0] = mix_a0; + _spu2mem[mix_dest_a1] = mix_a1; + _spu2mem[mix_dest_b0] = mix_b0; + _spu2mem[mix_dest_b1] = mix_b1; - upbuf[ubpos] = clamp_mix( StereoOut32( - mix_a0 + mix_b0, // left - mix_a1 + mix_b1 // right - ) ); - } + upbuf[ubpos] = clamp_mix(StereoOut32( + mix_a0 + mix_b0, // left + mix_a1 + mix_b1 // right + )); + } - StereoOut32 retval; + StereoOut32 retval; - //for( int x=0; x<8; ++x ) - //{ - // retval.Left += (upbuf[(ubpos+x)&7].Left*downcoeffs[x]); - // retval.Right += (upbuf[(ubpos+x)&7].Right*downcoeffs[x]); - //} + //for( int x=0; x<8; ++x ) + //{ + // retval.Left += (upbuf[(ubpos+x)&7].Left*downcoeffs[x]); + // retval.Right += (upbuf[(ubpos+x)&7].Right*downcoeffs[x]); + //} - if( (Cycles&1) == 0 ) - { - retval.Left = (upbuf[(ubpos+5)&7].Left + upbuf[(ubpos+7)&7].Left)>>1; - retval.Right = (upbuf[(ubpos+5)&7].Right + upbuf[(ubpos+7)&7].Right)>>1; - } - else - { - retval.Left = upbuf[(ubpos+6)&7].Left; - retval.Right = upbuf[(ubpos+6)&7].Right; - } + if ((Cycles & 1) == 0) { + retval.Left = (upbuf[(ubpos + 5) & 7].Left + upbuf[(ubpos + 7) & 7].Left) >> 1; + retval.Right = (upbuf[(ubpos + 5) & 7].Right + upbuf[(ubpos + 7) & 7].Right) >> 1; + } else { + retval.Left = upbuf[(ubpos + 6) & 7].Left; + retval.Right = upbuf[(ubpos + 6) & 7].Right; + } - // Notes: - // the first -1 is to adjust for the null padding in every other upbuf sample (which - // halves the overall volume). - // The second +1 divides by two, which is part of Neill's suggestion to divide by 3. - // - // According Neill the final result should be divided by 3, but currently the output - // is way too quiet for that to fly. In fact no division at all might be better. - // In any case the problem always seems to be that the reverb isn't resonating enough - // (indicating short buffers or bad coefficient math?), not that it isn't loud enough. + // Notes: + // the first -1 is to adjust for the null padding in every other upbuf sample (which + // halves the overall volume). + // The second +1 divides by two, which is part of Neill's suggestion to divide by 3. + // + // According Neill the final result should be divided by 3, but currently the output + // is way too quiet for that to fly. In fact no division at all might be better. + // In any case the problem always seems to be that the reverb isn't resonating enough + // (indicating short buffers or bad coefficient math?), not that it isn't loud enough. - //retval.Left >>= (16-1 + 1); - //retval.Right >>= (16-1 + 1); + //retval.Left >>= (16-1 + 1); + //retval.Right >>= (16-1 + 1); - ubpos = (ubpos+1) & 7; + ubpos = (ubpos + 1) & 7; - return retval; + return retval; } \ No newline at end of file diff --git a/plugins/spu2-x/src/SndOut.cpp b/plugins/spu2-x/src/SndOut.cpp index 2dc18268b8..dc0ced5b19 100644 --- a/plugins/spu2-x/src/SndOut.cpp +++ b/plugins/spu2-x/src/SndOut.cpp @@ -18,99 +18,95 @@ #include "Global.h" -StereoOut32 StereoOut32::Empty( 0, 0 ); +StereoOut32 StereoOut32::Empty(0, 0); -StereoOut32::StereoOut32( const StereoOut16& src ) : - Left( src.Left ), - Right( src.Right ) +StereoOut32::StereoOut32(const StereoOut16 &src) + : Left(src.Left) + , Right(src.Right) { } -StereoOut32::StereoOut32( const StereoOutFloat& src ) : - Left( (s32)(src.Left * 2147483647.0f) ), - Right( (s32)(src.Right * 2147483647.0f) ) +StereoOut32::StereoOut32(const StereoOutFloat &src) + : Left((s32)(src.Left * 2147483647.0f)) + , Right((s32)(src.Right * 2147483647.0f)) { } StereoOut16 StereoOut32::DownSample() const { - return StereoOut16( - Left >> SndOutVolumeShift, - Right >> SndOutVolumeShift - ); + return StereoOut16( + Left >> SndOutVolumeShift, + Right >> SndOutVolumeShift); } StereoOut32 StereoOut16::UpSample() const { - return StereoOut32( - Left << SndOutVolumeShift, - Right << SndOutVolumeShift - ); - + return StereoOut32( + Left << SndOutVolumeShift, + Right << SndOutVolumeShift); } -class NullOutModule: public SndOutModule +class NullOutModule : public SndOutModule { public: - s32 Init() { return 0; } - void Close() { } - s32 Test() const { return 0; } - void Configure(uptr parent) { } - int GetEmptySampleCount() { return 0; } + s32 Init() { return 0; } + void Close() {} + s32 Test() const { return 0; } + void Configure(uptr parent) {} + int GetEmptySampleCount() { return 0; } - const wchar_t* GetIdent() const - { - return L"nullout"; - } + const wchar_t *GetIdent() const + { + return L"nullout"; + } - const wchar_t* GetLongName() const - { - return L"No Sound (Emulate SPU2 only)"; - } + const wchar_t *GetLongName() const + { + return L"No Sound (Emulate SPU2 only)"; + } - void ReadSettings() - { - } + void ReadSettings() + { + } - void SetApiSettings(wxString api) - { - } + void SetApiSettings(wxString api) + { + } - void WriteSettings() const - { - } + void WriteSettings() const + { + } } NullOut; -SndOutModule* mods[]= -{ - &NullOut, +SndOutModule *mods[] = + { + &NullOut, #ifdef _MSC_VER - XAudio2_27_Out, - DSoundOut, - WaveOut, + XAudio2_27_Out, + DSoundOut, + WaveOut, #endif - PortaudioOut, + PortaudioOut, #if defined(SPU2X_SDL) || defined(SPU2X_SDL2) - SDLOut, + SDLOut, #endif #if defined(__linux__) /* && defined(__ALSA__)*/ - AlsaOut, + AlsaOut, #endif - NULL // signals the end of our list + NULL // signals the end of our list }; -int FindOutputModuleById( const wchar_t* omodid ) +int FindOutputModuleById(const wchar_t *omodid) { - int modcnt = 0; - while( mods[modcnt] != NULL ) - { - if( wcscmp( mods[modcnt]->GetIdent(), omodid ) == 0 ) - break; - ++modcnt; - } - return modcnt; + int modcnt = 0; + while (mods[modcnt] != NULL) { + if (wcscmp(mods[modcnt]->GetIdent(), omodid) == 0) + break; + ++modcnt; + } + return modcnt; } StereoOut32 *SndBuffer::m_buffer; @@ -119,229 +115,215 @@ __aligned(4) volatile s32 SndBuffer::m_rpos; __aligned(4) volatile s32 SndBuffer::m_wpos; bool SndBuffer::m_underrun_freeze; -StereoOut32* SndBuffer::sndTempBuffer = NULL; -StereoOut16* SndBuffer::sndTempBuffer16 = NULL; +StereoOut32 *SndBuffer::sndTempBuffer = NULL; +StereoOut16 *SndBuffer::sndTempBuffer16 = NULL; int SndBuffer::sndTempProgress = 0; -int GetAlignedBufferSize( int comp ) +int GetAlignedBufferSize(int comp) { - return (comp + SndOutPacketSize-1) & ~(SndOutPacketSize-1); + 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 ) +bool SndBuffer::CheckUnderrunStatus(int &nSamples, int &quietSampleCount) { - quietSampleCount = 0; + quietSampleCount = 0; - int data = _GetApproximateDataInBuffer(); - if( m_underrun_freeze ) - { - int toFill = m_size / ( (SynchMode == 2) ? 32 : 400); // TimeStretch and Async off? - toFill = GetAlignedBufferSize( toFill ); + int data = _GetApproximateDataInBuffer(); + if (m_underrun_freeze) { + int toFill = m_size / ((SynchMode == 2) ? 32 : 400); // TimeStretch and Async off? + toFill = GetAlignedBufferSize(toFill); - // toFill is now aligned to a SndOutPacket + // toFill is now aligned to a SndOutPacket - if( data < toFill ) - { - quietSampleCount = nSamples; - return false; - } + if (data < toFill) { + quietSampleCount = nSamples; + return false; + } - m_underrun_freeze = false; - if( MsgOverruns() ) - ConLog(" * SPU2 > Underrun compensation (%d packets buffered)\n", toFill / SndOutPacketSize ); - lastPct = 0.0; // normalize timestretcher - } - else if( data < nSamples ) - { - nSamples = data; - quietSampleCount = SndOutPacketSize - data; - m_underrun_freeze = true; + m_underrun_freeze = false; + if (MsgOverruns()) + ConLog(" * SPU2 > Underrun compensation (%d packets buffered)\n", toFill / SndOutPacketSize); + lastPct = 0.0; // normalize timestretcher + } else if (data < nSamples) { + nSamples = data; + quietSampleCount = SndOutPacketSize - data; + m_underrun_freeze = true; - if( SynchMode == 0 ) // TimeStrech on - timeStretchUnderrun(); + if (SynchMode == 0) // TimeStrech on + timeStretchUnderrun(); - return nSamples != 0; - } + return nSamples != 0; + } - return true; + 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(); + // 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(); } int SndBuffer::_GetApproximateDataInBuffer() { - // WARNING: not necessarily 100% up to date by the time it's used, but it will have to do. - return (m_wpos + m_size - m_rpos) % m_size; + // WARNING: not necessarily 100% up to date by the time it's used, but it will have to do. + return (m_wpos + m_size - m_rpos) % m_size; } void SndBuffer::_WriteSamples_Internal(StereoOut32 *bData, int nSamples) { - // WARNING: This assumes the write will NOT wrap around, - // and also assumes there's enough free space in the buffer. + // WARNING: This assumes the write will NOT wrap around, + // and also assumes there's enough free space in the buffer. - memcpy(m_buffer + m_wpos, bData, nSamples * sizeof(StereoOut32)); - m_wpos = (m_wpos + nSamples) % m_size; + memcpy(m_buffer + m_wpos, bData, nSamples * sizeof(StereoOut32)); + m_wpos = (m_wpos + nSamples) % m_size; } void SndBuffer::_DropSamples_Internal(int nSamples) { - m_rpos = (m_rpos + nSamples) % m_size; + m_rpos = (m_rpos + nSamples) % m_size; } void SndBuffer::_ReadSamples_Internal(StereoOut32 *bData, int nSamples) { - // WARNING: This assumes the read will NOT wrap around, - // and also assumes there's enough data in the buffer. - memcpy(bData, m_buffer + m_rpos, nSamples * sizeof(StereoOut32)); - _DropSamples_Internal(nSamples); + // WARNING: This assumes the read will NOT wrap around, + // and also assumes there's enough data in the buffer. + memcpy(bData, m_buffer + m_rpos, nSamples * sizeof(StereoOut32)); + _DropSamples_Internal(nSamples); } void SndBuffer::_WriteSamples_Safe(StereoOut32 *bData, int nSamples) { - // WARNING: This code assumes there's only ONE writing process. - if( (m_size - m_wpos) < nSamples) - { - int b1 = m_size - m_wpos; - int b2 = nSamples - b1; + // WARNING: This code assumes there's only ONE writing process. + if ((m_size - m_wpos) < nSamples) { + int b1 = m_size - m_wpos; + int b2 = nSamples - b1; - _WriteSamples_Internal(bData, b1); - _WriteSamples_Internal(bData+b1, b2); - } - else - { - _WriteSamples_Internal(bData, nSamples); - } + _WriteSamples_Internal(bData, b1); + _WriteSamples_Internal(bData + b1, b2); + } else { + _WriteSamples_Internal(bData, nSamples); + } } -void SndBuffer::_ReadSamples_Safe(StereoOut32* bData, int nSamples) +void SndBuffer::_ReadSamples_Safe(StereoOut32 *bData, int nSamples) { - // WARNING: This code assumes there's only ONE reading process. - if( (m_size - m_rpos) < nSamples) - { - int b1 = m_size - m_rpos; - int b2 = nSamples - b1; + // WARNING: This code assumes there's only ONE reading process. + if ((m_size - m_rpos) < nSamples) { + int b1 = m_size - m_rpos; + int b2 = nSamples - b1; - _ReadSamples_Internal(bData, b1); - _ReadSamples_Internal(bData+b1, b2); - } - else - { - _ReadSamples_Internal(bData, nSamples); - } + _ReadSamples_Internal(bData, b1); + _ReadSamples_Internal(bData + b1, b2); + } else { + _ReadSamples_Internal(bData, nSamples); + } } // 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 void SndBuffer::ReadSamples(T* bData) +template +void SndBuffer::ReadSamples(T *bData) { - int nSamples = SndOutPacketSize; + 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. + // 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 ) ) - { - pxAssume( nSamples <= SndOutPacketSize ); + int quietSamples; + if (CheckUnderrunStatus(nSamples, quietSamples)) { + pxAssume(nSamples <= SndOutPacketSize); - // WARNING: This code assumes there's only ONE reading process. - int b1 = m_size - m_rpos; + // WARNING: This code assumes there's only ONE reading process. + int b1 = m_size - m_rpos; - if(b1 > nSamples) - b1 = nSamples; + if (b1 > nSamples) + b1 = nSamples; - if (AdvancedVolumeControl) - { - // First part - for (int i = 0; i < b1; i++) - bData[i].AdjustFrom(m_buffer[i + m_rpos]); + if (AdvancedVolumeControl) { + // First part + for (int i = 0; i < b1; i++) + bData[i].AdjustFrom(m_buffer[i + m_rpos]); - // Second part - int b2 = nSamples - b1; - for (int i = 0; i < b2; i++) - bData[i + b1].AdjustFrom(m_buffer[i]); - } - else - { - // First part - for (int i = 0; i < b1; i++) - bData[i].ResampleFrom(m_buffer[i + m_rpos]); + // Second part + int b2 = nSamples - b1; + for (int i = 0; i < b2; i++) + bData[i + b1].AdjustFrom(m_buffer[i]); + } else { + // First part + for (int i = 0; i < b1; i++) + bData[i].ResampleFrom(m_buffer[i + m_rpos]); - // Second part - int b2 = nSamples - b1; - for (int i = 0; i < b2; i++) - bData[i + b1].ResampleFrom(m_buffer[i]); - } + // Second part + int b2 = nSamples - b1; + for (int i = 0; i < b2; i++) + bData[i + b1].ResampleFrom(m_buffer[i]); + } - _DropSamples_Internal(nSamples); - } + _DropSamples_Internal(nSamples); + } - // 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) ); + // 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)); } -template void SndBuffer::ReadSamples(StereoOut16*); -template void SndBuffer::ReadSamples(StereoOut32*); +template void SndBuffer::ReadSamples(StereoOut16 *); +template void SndBuffer::ReadSamples(StereoOut32 *); //template void SndBuffer::ReadSamples(StereoOutFloat*); -template void SndBuffer::ReadSamples(Stereo21Out16*); -template void SndBuffer::ReadSamples(Stereo40Out16*); -template void SndBuffer::ReadSamples(Stereo41Out16*); -template void SndBuffer::ReadSamples(Stereo51Out16*); -template void SndBuffer::ReadSamples(Stereo51Out16Dpl*); -template void SndBuffer::ReadSamples(Stereo51Out16DplII*); -template void SndBuffer::ReadSamples(Stereo71Out16*); +template void SndBuffer::ReadSamples(Stereo21Out16 *); +template void SndBuffer::ReadSamples(Stereo40Out16 *); +template void SndBuffer::ReadSamples(Stereo41Out16 *); +template void SndBuffer::ReadSamples(Stereo51Out16 *); +template void SndBuffer::ReadSamples(Stereo51Out16Dpl *); +template void SndBuffer::ReadSamples(Stereo51Out16DplII *); +template void SndBuffer::ReadSamples(Stereo71Out16 *); -template void SndBuffer::ReadSamples(Stereo20Out32*); -template void SndBuffer::ReadSamples(Stereo21Out32*); -template void SndBuffer::ReadSamples(Stereo40Out32*); -template void SndBuffer::ReadSamples(Stereo41Out32*); -template void SndBuffer::ReadSamples(Stereo51Out32*); -template void SndBuffer::ReadSamples(Stereo51Out32Dpl*); -template void SndBuffer::ReadSamples(Stereo51Out32DplII*); -template void SndBuffer::ReadSamples(Stereo71Out32*); +template void SndBuffer::ReadSamples(Stereo20Out32 *); +template void SndBuffer::ReadSamples(Stereo21Out32 *); +template void SndBuffer::ReadSamples(Stereo40Out32 *); +template void SndBuffer::ReadSamples(Stereo41Out32 *); +template void SndBuffer::ReadSamples(Stereo51Out32 *); +template void SndBuffer::ReadSamples(Stereo51Out32Dpl *); +template void SndBuffer::ReadSamples(Stereo51Out32DplII *); +template void SndBuffer::ReadSamples(Stereo71Out32 *); void SndBuffer::_WriteSamples(StereoOut32 *bData, int nSamples) { - m_predictData = 0; + m_predictData = 0; - // 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. + // 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. - int free = m_size - _GetApproximateDataInBuffer(); // -1, but the <= handles that - if( free <= nSamples ) - { - // Disabled since the lock-free queue can't handle changing the read end from the write thread + int free = m_size - _GetApproximateDataInBuffer(); // -1, but the <= handles that + if (free <= nSamples) { +// Disabled since the lock-free queue can't handle changing the read end from the write thread #if 0 // Buffer overrun! // Dump samples from the read portion of the buffer instead of dropping @@ -366,72 +348,69 @@ void SndBuffer::_WriteSamples(StereoOut32 *bData, int nSamples) ConLog(" * SPU2 > Overrun Compensation (%d packets tossed)\n", comp / SndOutPacketSize ); lastPct = 0.0; // normalize the timestretcher #else - if( MsgOverruns() ) - ConLog(" * SPU2 > Overrun! 1 packet tossed)\n"); - lastPct = 0.0; // normalize the timestretcher - return; + if (MsgOverruns()) + ConLog(" * SPU2 > Overrun! 1 packet tossed)\n"); + lastPct = 0.0; // normalize the timestretcher + return; #endif - } + } - _WriteSamples_Safe(bData, nSamples); + _WriteSamples_Safe(bData, nSamples); } void SndBuffer::Init() { - if( mods[OutputModule] == NULL ) - { - _InitFail(); - return; - } + if (mods[OutputModule] == NULL) { + _InitFail(); + return; + } - // initialize sound buffer - // Buffer actually attempts to run ~50%, so allocate near double what - // the requested latency is: - - m_rpos = 0; - m_wpos = 0; + // initialize sound buffer + // Buffer actually attempts to run ~50%, so allocate near double what + // the requested latency is: - try - { - const float latencyMS = SndOutLatencyMS * 16; - m_size = GetAlignedBufferSize( (int)(latencyMS * SampleRate / 1000.0f ) ); - m_buffer = new StereoOut32[m_size]; - m_underrun_freeze = false; + m_rpos = 0; + m_wpos = 0; - sndTempBuffer = new StereoOut32[SndOutPacketSize]; - sndTempBuffer16 = new StereoOut16[SndOutPacketSize * 2]; // in case of leftovers. - } - catch( std::bad_alloc& ) - { - // out of memory exception (most likely) + try { + const float latencyMS = SndOutLatencyMS * 16; + m_size = GetAlignedBufferSize((int)(latencyMS * SampleRate / 1000.0f)); + m_buffer = new StereoOut32[m_size]; + m_underrun_freeze = false; - SysMessage( "Out of memory error occurred while initializing SPU2." ); - _InitFail(); - return; - } + sndTempBuffer = new StereoOut32[SndOutPacketSize]; + sndTempBuffer16 = new StereoOut16[SndOutPacketSize * 2]; // in case of leftovers. + } catch (std::bad_alloc &) { + // out of memory exception (most likely) - // clear buffers! - // Fixes loopy sounds on emu resets. - memset( sndTempBuffer, 0, sizeof(StereoOut32) * SndOutPacketSize ); - memset( sndTempBuffer16, 0, sizeof(StereoOut16) * SndOutPacketSize ); + SysMessage("Out of memory error occurred while initializing SPU2."); + _InitFail(); + return; + } - sndTempProgress = 0; + // clear buffers! + // Fixes loopy sounds on emu resets. + memset(sndTempBuffer, 0, sizeof(StereoOut32) * SndOutPacketSize); + memset(sndTempBuffer16, 0, sizeof(StereoOut16) * SndOutPacketSize); - soundtouchInit(); // initializes the timestretching + sndTempProgress = 0; - // initialize module - if( mods[OutputModule]->Init() == -1 ) _InitFail(); + soundtouchInit(); // initializes the timestretching + + // initialize module + if (mods[OutputModule]->Init() == -1) + _InitFail(); } void SndBuffer::Cleanup() { - mods[OutputModule]->Close(); + mods[OutputModule]->Close(); - soundtouchCleanup(); + soundtouchCleanup(); - safe_delete_array( m_buffer ); - safe_delete_array( sndTempBuffer ); - safe_delete_array( sndTempBuffer16 ); + safe_delete_array(m_buffer); + safe_delete_array(sndTempBuffer); + safe_delete_array(sndTempBuffer16); } int SndBuffer::m_dsp_progress = 0; @@ -441,77 +420,77 @@ int SndBuffer::ssFreeze = 0; void SndBuffer::ClearContents() { - SndBuffer::soundtouchClearContents(); - SndBuffer::ssFreeze = 256; //Delays sound output for about 1 second. + SndBuffer::soundtouchClearContents(); + SndBuffer::ssFreeze = 256; //Delays sound output for about 1 second. } -void SndBuffer::Write( const StereoOut32& Sample ) +void SndBuffer::Write(const StereoOut32 &Sample) { - // Log final output to wavefile. - WaveDump::WriteCore( 1, CoreSrc_External, Sample.DownSample() ); + // Log final output to wavefile. + WaveDump::WriteCore(1, CoreSrc_External, Sample.DownSample()); - if( WavRecordEnabled ) RecordWrite( Sample.DownSample() ); + if (WavRecordEnabled) + RecordWrite(Sample.DownSample()); - if(mods[OutputModule] == &NullOut) // null output doesn't need buffering or stretching! :p - return; + if (mods[OutputModule] == &NullOut) // null output doesn't need buffering or stretching! :p + return; - sndTempBuffer[sndTempProgress++] = Sample; + sndTempBuffer[sndTempProgress++] = Sample; - // If we haven't accumulated a full packet yet, do nothing more: - if(sndTempProgress < SndOutPacketSize) return; - sndTempProgress = 0; + // If we haven't accumulated a full packet yet, do nothing more: + if (sndTempProgress < SndOutPacketSize) + return; + sndTempProgress = 0; - //Don't play anything directly after loading a savestate, avoids static killing your speakers. - if ( ssFreeze > 0 ) - { - ssFreeze--; - memset( sndTempBuffer, 0, sizeof(StereoOut32) * SndOutPacketSize ); // Play silence - } + //Don't play anything directly after loading a savestate, avoids static killing your speakers. + if (ssFreeze > 0) { + ssFreeze--; + memset(sndTempBuffer, 0, sizeof(StereoOut32) * SndOutPacketSize); // Play silence + } #ifndef __POSIX__ - if( dspPluginEnabled ) - { - // Convert in, send to winamp DSP, and convert out. + if (dspPluginEnabled) { + // Convert in, send to winamp DSP, and convert out. - int ei= m_dsp_progress; - for( int i=0; i= SndOutPacketSize ) - { - for( int i=0; i= SndOutPacketSize) { + for (int i = 0; i < SndOutPacketSize; ++i, ++ei) { + sndTempBuffer[i] = sndTempBuffer16[ei].UpSample(); + } - if( SynchMode == 0 ) // TimeStrech on - timeStretchWrite(); - else - _WriteSamples(sndTempBuffer, SndOutPacketSize); + if (SynchMode == 0) // TimeStrech on + timeStretchWrite(); + else + _WriteSamples(sndTempBuffer, SndOutPacketSize); - m_dsp_progress -= SndOutPacketSize; - } + m_dsp_progress -= SndOutPacketSize; + } - // copy any leftovers to the front of the dsp buffer. - if( m_dsp_progress > 0 ) - { - memcpy( sndTempBuffer16, &sndTempBuffer16[ei], - sizeof(sndTempBuffer16[0]) * m_dsp_progress - ); - } - } + // copy any leftovers to the front of the dsp buffer. + if (m_dsp_progress > 0) { + memcpy(sndTempBuffer16, &sndTempBuffer16[ei], + sizeof(sndTempBuffer16[0]) * m_dsp_progress); + } + } #endif - else - { - if( SynchMode == 0 ) // TimeStrech on - timeStretchWrite(); - else - _WriteSamples(sndTempBuffer, SndOutPacketSize); - } + else { + if (SynchMode == 0) // TimeStrech on + timeStretchWrite(); + else + _WriteSamples(sndTempBuffer, SndOutPacketSize); + } } s32 SndBuffer::Test() { - if( mods[OutputModule] == NULL ) - return -1; + if (mods[OutputModule] == NULL) + return -1; - return mods[OutputModule]->Test(); + return mods[OutputModule]->Test(); } diff --git a/plugins/spu2-x/src/SndOut.h b/plugins/spu2-x/src/SndOut.h index 8cfab252b9..b33cb58a61 100644 --- a/plugins/spu2-x/src/SndOut.h +++ b/plugins/spu2-x/src/SndOut.h @@ -27,14 +27,14 @@ static const int SndOutPacketSize = 64; // downsamples 32 bit samples to 16 bit sound driver output (this way timestretching and // DSP effects get better precision results) static const int SndOutVolumeShift = 12; -static const int SndOutVolumeShift32 = 16-SndOutVolumeShift; // shift up, not down +static const int SndOutVolumeShift32 = 16 - SndOutVolumeShift; // shift up, not down // 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. :) static const int SampleRate = 48000; -extern int FindOutputModuleById( const wchar_t* omodid ); +extern int FindOutputModuleById(const wchar_t *omodid); // Implemented in Config.cpp extern float VolumeAdjustFL; @@ -50,638 +50,638 @@ extern unsigned int delayCycles; struct Stereo51Out16DplII; struct Stereo51Out32DplII; -struct Stereo51Out16Dpl; // similar to DplII but without rear balancing +struct Stereo51Out16Dpl; // similar to DplII but without rear balancing struct Stereo51Out32Dpl; extern void ResetDplIIDecoder(); -extern void ProcessDplIISample16( const StereoOut32& src, Stereo51Out16DplII * s); -extern void ProcessDplIISample32( const StereoOut32& src, Stereo51Out32DplII * s); -extern void ProcessDplSample16( const StereoOut32& src, Stereo51Out16Dpl * s); -extern void ProcessDplSample32( const StereoOut32& src, Stereo51Out32Dpl * s); +extern void ProcessDplIISample16(const StereoOut32 &src, Stereo51Out16DplII *s); +extern void ProcessDplIISample32(const StereoOut32 &src, Stereo51Out32DplII *s); +extern void ProcessDplSample16(const StereoOut32 &src, Stereo51Out16Dpl *s); +extern void ProcessDplSample32(const StereoOut32 &src, Stereo51Out32Dpl *s); struct StereoOut16 { - s16 Left; - s16 Right; + s16 Left; + s16 Right; - StereoOut16() : - Left( 0 ), - Right( 0 ) - { - } + StereoOut16() + : Left(0) + , Right(0) + { + } - StereoOut16( const StereoOut32& src ) : - Left( (s16)src.Left ), - Right( (s16)src.Right ) - { - } + StereoOut16(const StereoOut32 &src) + : Left((s16)src.Left) + , Right((s16)src.Right) + { + } - StereoOut16( s16 left, s16 right ) : - Left( left ), - Right( right ) - { - } + StereoOut16(s16 left, s16 right) + : Left(left) + , Right(right) + { + } - StereoOut32 UpSample() const; + StereoOut32 UpSample() const; - void ResampleFrom( const StereoOut32& src ) - { - // Use StereoOut32's built in conversion - *this = src.DownSample(); - } + void ResampleFrom(const StereoOut32 &src) + { + // Use StereoOut32's built in conversion + *this = src.DownSample(); + } - void AdjustFrom(const StereoOut32& src) - { - ResampleFrom(src); + void AdjustFrom(const StereoOut32 &src) + { + ResampleFrom(src); - Left = (s16) (Left * VolumeAdjustFL); - Right = (s16) (Right * VolumeAdjustFR); - } + Left = (s16)(Left * VolumeAdjustFL); + Right = (s16)(Right * VolumeAdjustFR); + } }; struct StereoOutFloat { - float Left; - float Right; + float Left; + float Right; - StereoOutFloat() : - Left( 0 ), - Right( 0 ) - { - } + StereoOutFloat() + : Left(0) + , Right(0) + { + } - explicit StereoOutFloat( const StereoOut32& src ) : - Left( src.Left / 2147483647.0f ), - Right( src.Right / 2147483647.0f ) - { - } + explicit StereoOutFloat(const StereoOut32 &src) + : Left(src.Left / 2147483647.0f) + , Right(src.Right / 2147483647.0f) + { + } - explicit StereoOutFloat( s32 left, s32 right ) : - Left( left / 2147483647.0f ), - Right( right / 2147483647.0f ) - { - } + explicit StereoOutFloat(s32 left, s32 right) + : Left(left / 2147483647.0f) + , Right(right / 2147483647.0f) + { + } - StereoOutFloat( float left, float right ) : - Left( left ), - Right( right ) - { - } + StereoOutFloat(float left, float right) + : Left(left) + , Right(right) + { + } }; struct Stereo21Out16 { - s16 Left; - s16 Right; - s16 LFE; + s16 Left; + s16 Right; + s16 LFE; - void ResampleFrom( const StereoOut32& src ) - { - Left = src.Left >> SndOutVolumeShift; - Right = src.Right >> SndOutVolumeShift; - LFE = (src.Left + src.Right) >> (SndOutVolumeShift + 1); - } + void ResampleFrom(const StereoOut32 &src) + { + Left = src.Left >> SndOutVolumeShift; + Right = src.Right >> SndOutVolumeShift; + LFE = (src.Left + src.Right) >> (SndOutVolumeShift + 1); + } - void AdjustFrom(const StereoOut32& src) - { - ResampleFrom(src); + void AdjustFrom(const StereoOut32 &src) + { + ResampleFrom(src); - Left = (s16) (Left * VolumeAdjustFL); - Right = (s16) (Right * VolumeAdjustFR); - LFE = (s16) (LFE * VolumeAdjustLFE); - } + Left = (s16)(Left * VolumeAdjustFL); + Right = (s16)(Right * VolumeAdjustFR); + LFE = (s16)(LFE * VolumeAdjustLFE); + } }; struct Stereo40Out16 { - s16 Left; - s16 Right; - s16 LeftBack; - s16 RightBack; + s16 Left; + s16 Right; + s16 LeftBack; + s16 RightBack; - void ResampleFrom( const StereoOut32& src ) - { - Left = src.Left >> SndOutVolumeShift; - Right = src.Right >> SndOutVolumeShift; - LeftBack = src.Left >> SndOutVolumeShift; - RightBack = src.Right >> SndOutVolumeShift; - } + void ResampleFrom(const StereoOut32 &src) + { + Left = src.Left >> SndOutVolumeShift; + Right = src.Right >> SndOutVolumeShift; + LeftBack = src.Left >> SndOutVolumeShift; + RightBack = src.Right >> SndOutVolumeShift; + } - void AdjustFrom(const StereoOut32& src) - { - ResampleFrom(src); + void AdjustFrom(const StereoOut32 &src) + { + ResampleFrom(src); - Left = (s16) (Left * VolumeAdjustFL); - Right = (s16) (Right * VolumeAdjustFR); - LeftBack = (s16) (LeftBack * VolumeAdjustBL); - RightBack = (s16) (RightBack * VolumeAdjustBR); - } + Left = (s16)(Left * VolumeAdjustFL); + Right = (s16)(Right * VolumeAdjustFR); + LeftBack = (s16)(LeftBack * VolumeAdjustBL); + RightBack = (s16)(RightBack * VolumeAdjustBR); + } }; struct Stereo40Out32 { - s32 Left; - s32 Right; - s32 LeftBack; - s32 RightBack; + s32 Left; + s32 Right; + s32 LeftBack; + s32 RightBack; - void ResampleFrom( const StereoOut32& src ) - { - Left = src.Left << SndOutVolumeShift32; - Right = src.Right << SndOutVolumeShift32; - LeftBack = src.Left << SndOutVolumeShift32; - RightBack = src.Right << SndOutVolumeShift32; - } + void ResampleFrom(const StereoOut32 &src) + { + Left = src.Left << SndOutVolumeShift32; + Right = src.Right << SndOutVolumeShift32; + LeftBack = src.Left << SndOutVolumeShift32; + RightBack = src.Right << SndOutVolumeShift32; + } - void AdjustFrom(const StereoOut32& src) - { - ResampleFrom(src); + void AdjustFrom(const StereoOut32 &src) + { + ResampleFrom(src); - Left = (s32) (Left * VolumeAdjustFL); - Right = (s32) (Right * VolumeAdjustFR); - LeftBack = (s32) (LeftBack * VolumeAdjustBL); - RightBack = (s32) (RightBack * VolumeAdjustBR); - } + Left = (s32)(Left * VolumeAdjustFL); + Right = (s32)(Right * VolumeAdjustFR); + LeftBack = (s32)(LeftBack * VolumeAdjustBL); + RightBack = (s32)(RightBack * VolumeAdjustBR); + } }; struct Stereo41Out16 { - s16 Left; - s16 Right; - s16 LFE; - s16 LeftBack; - s16 RightBack; + s16 Left; + s16 Right; + s16 LFE; + s16 LeftBack; + s16 RightBack; - void ResampleFrom( const StereoOut32& src ) - { - Left = src.Left >> SndOutVolumeShift; - Right = src.Right >> SndOutVolumeShift; - LFE = (src.Left + src.Right) >> (SndOutVolumeShift + 1); - LeftBack = src.Left >> SndOutVolumeShift; - RightBack = src.Right >> SndOutVolumeShift; - } + void ResampleFrom(const StereoOut32 &src) + { + Left = src.Left >> SndOutVolumeShift; + Right = src.Right >> SndOutVolumeShift; + LFE = (src.Left + src.Right) >> (SndOutVolumeShift + 1); + LeftBack = src.Left >> SndOutVolumeShift; + RightBack = src.Right >> SndOutVolumeShift; + } - void AdjustFrom(const StereoOut32& src) - { - ResampleFrom(src); + void AdjustFrom(const StereoOut32 &src) + { + ResampleFrom(src); - Left = (s32) (Left * VolumeAdjustFL); - Right = (s32) (Right * VolumeAdjustFR); - LeftBack = (s32) (LeftBack * VolumeAdjustBL); - RightBack = (s32) (RightBack * VolumeAdjustBR); - LFE = (s32) (LFE * VolumeAdjustLFE); - } + Left = (s32)(Left * VolumeAdjustFL); + Right = (s32)(Right * VolumeAdjustFR); + LeftBack = (s32)(LeftBack * VolumeAdjustBL); + RightBack = (s32)(RightBack * VolumeAdjustBR); + LFE = (s32)(LFE * VolumeAdjustLFE); + } }; struct Stereo51Out16 { - s16 Left; - s16 Right; - s16 Center; - s16 LFE; - s16 LeftBack; - s16 RightBack; + s16 Left; + s16 Right; + s16 Center; + s16 LFE; + s16 LeftBack; + s16 RightBack; - // Implementation Note: Center and Subwoofer/LFE --> - // This method is simple and sounds nice. It relies on the speaker/soundcard - // systems do to their own low pass / crossover. Manual lowpass is wasted effort - // and can't match solid state results anyway. + // Implementation Note: Center and Subwoofer/LFE --> + // This method is simple and sounds nice. It relies on the speaker/soundcard + // systems do to their own low pass / crossover. Manual lowpass is wasted effort + // and can't match solid state results anyway. - void ResampleFrom( const StereoOut32& src ) - { - Left = src.Left >> SndOutVolumeShift; - Right = src.Right >> SndOutVolumeShift; - Center = (src.Left + src.Right) >> (SndOutVolumeShift + 1); - LFE = Center; - LeftBack = src.Left >> SndOutVolumeShift; - RightBack = src.Right >> SndOutVolumeShift; - } + void ResampleFrom(const StereoOut32 &src) + { + Left = src.Left >> SndOutVolumeShift; + Right = src.Right >> SndOutVolumeShift; + Center = (src.Left + src.Right) >> (SndOutVolumeShift + 1); + LFE = Center; + LeftBack = src.Left >> SndOutVolumeShift; + RightBack = src.Right >> SndOutVolumeShift; + } - void AdjustFrom(const StereoOut32& src) - { - ResampleFrom(src); + void AdjustFrom(const StereoOut32 &src) + { + ResampleFrom(src); - Left = (s16) (Left * VolumeAdjustFL); - Right = (s16) (Right * VolumeAdjustFR); - LeftBack = (s16) (LeftBack * VolumeAdjustBL); - RightBack = (s16) (RightBack * VolumeAdjustBR); - Center = (s16) (Center * VolumeAdjustC); - LFE = (s16) (LFE * VolumeAdjustLFE); - } + Left = (s16)(Left * VolumeAdjustFL); + Right = (s16)(Right * VolumeAdjustFR); + LeftBack = (s16)(LeftBack * VolumeAdjustBL); + RightBack = (s16)(RightBack * VolumeAdjustBR); + Center = (s16)(Center * VolumeAdjustC); + LFE = (s16)(LFE * VolumeAdjustLFE); + } }; struct Stereo51Out16DplII { - s16 Left; - s16 Right; - s16 Center; - s16 LFE; - s16 LeftBack; - s16 RightBack; + s16 Left; + s16 Right; + s16 Center; + s16 LFE; + s16 LeftBack; + s16 RightBack; - void ResampleFrom( const StereoOut32& src ) - { - ProcessDplIISample16(src, this); - } + void ResampleFrom(const StereoOut32 &src) + { + ProcessDplIISample16(src, this); + } - void AdjustFrom(const StereoOut32& src) - { - ResampleFrom(src); + void AdjustFrom(const StereoOut32 &src) + { + ResampleFrom(src); - Left = (s32) (Left * VolumeAdjustFL); - Right = (s32) (Right * VolumeAdjustFR); - LeftBack = (s32) (LeftBack * VolumeAdjustBL); - RightBack = (s32) (RightBack * VolumeAdjustBR); - Center = (s32) (Center * VolumeAdjustC); - LFE = (s32) (LFE * VolumeAdjustLFE); - } + Left = (s32)(Left * VolumeAdjustFL); + Right = (s32)(Right * VolumeAdjustFR); + LeftBack = (s32)(LeftBack * VolumeAdjustBL); + RightBack = (s32)(RightBack * VolumeAdjustBR); + Center = (s32)(Center * VolumeAdjustC); + LFE = (s32)(LFE * VolumeAdjustLFE); + } }; struct Stereo51Out32DplII { - s32 Left; - s32 Right; - s32 Center; - s32 LFE; - s32 LeftBack; - s32 RightBack; + s32 Left; + s32 Right; + s32 Center; + s32 LFE; + s32 LeftBack; + s32 RightBack; - void ResampleFrom( const StereoOut32& src ) - { - ProcessDplIISample32(src, this); - } + void ResampleFrom(const StereoOut32 &src) + { + ProcessDplIISample32(src, this); + } - void AdjustFrom(const StereoOut32& src) - { - ResampleFrom(src); + void AdjustFrom(const StereoOut32 &src) + { + ResampleFrom(src); - Left = (s32) (Left * VolumeAdjustFL); - Right = (s32) (Right * VolumeAdjustFR); - LeftBack = (s32) (LeftBack * VolumeAdjustBL); - RightBack = (s32) (RightBack * VolumeAdjustBR); - Center = (s32) (Center * VolumeAdjustC); - LFE = (s32) (LFE * VolumeAdjustLFE); - } + Left = (s32)(Left * VolumeAdjustFL); + Right = (s32)(Right * VolumeAdjustFR); + LeftBack = (s32)(LeftBack * VolumeAdjustBL); + RightBack = (s32)(RightBack * VolumeAdjustBR); + Center = (s32)(Center * VolumeAdjustC); + LFE = (s32)(LFE * VolumeAdjustLFE); + } }; struct Stereo51Out16Dpl { - s16 Left; - s16 Right; - s16 Center; - s16 LFE; - s16 LeftBack; - s16 RightBack; + s16 Left; + s16 Right; + s16 Center; + s16 LFE; + s16 LeftBack; + s16 RightBack; - void ResampleFrom( const StereoOut32& src ) - { - ProcessDplSample16(src, this); - } + void ResampleFrom(const StereoOut32 &src) + { + ProcessDplSample16(src, this); + } - void AdjustFrom(const StereoOut32& src) - { - ResampleFrom(src); + void AdjustFrom(const StereoOut32 &src) + { + ResampleFrom(src); - Left = (s32) (Left * VolumeAdjustFL); - Right = (s32) (Right * VolumeAdjustFR); - LeftBack = (s32) (LeftBack * VolumeAdjustBL); - RightBack = (s32) (RightBack * VolumeAdjustBR); - Center = (s32) (Center * VolumeAdjustC); - LFE = (s32) (LFE * VolumeAdjustLFE); - } + Left = (s32)(Left * VolumeAdjustFL); + Right = (s32)(Right * VolumeAdjustFR); + LeftBack = (s32)(LeftBack * VolumeAdjustBL); + RightBack = (s32)(RightBack * VolumeAdjustBR); + Center = (s32)(Center * VolumeAdjustC); + LFE = (s32)(LFE * VolumeAdjustLFE); + } }; struct Stereo51Out32Dpl { - s32 Left; - s32 Right; - s32 Center; - s32 LFE; - s32 LeftBack; - s32 RightBack; + s32 Left; + s32 Right; + s32 Center; + s32 LFE; + s32 LeftBack; + s32 RightBack; - void ResampleFrom( const StereoOut32& src ) - { - ProcessDplSample32(src, this); - } + void ResampleFrom(const StereoOut32 &src) + { + ProcessDplSample32(src, this); + } - void AdjustFrom(const StereoOut32& src) - { - ResampleFrom(src); + void AdjustFrom(const StereoOut32 &src) + { + ResampleFrom(src); - Left = (s32) (Left * VolumeAdjustFL); - Right = (s32) (Right * VolumeAdjustFR); - LeftBack = (s32) (LeftBack * VolumeAdjustBL); - RightBack = (s32) (RightBack * VolumeAdjustBR); - Center = (s32) (Center * VolumeAdjustC); - LFE = (s32) (LFE * VolumeAdjustLFE); - } + Left = (s32)(Left * VolumeAdjustFL); + Right = (s32)(Right * VolumeAdjustFR); + LeftBack = (s32)(LeftBack * VolumeAdjustBL); + RightBack = (s32)(RightBack * VolumeAdjustBR); + Center = (s32)(Center * VolumeAdjustC); + LFE = (s32)(LFE * VolumeAdjustLFE); + } }; struct Stereo71Out16 { - s16 Left; - s16 Right; - s16 Center; - s16 LFE; - s16 LeftBack; - s16 RightBack; - s16 LeftSide; - s16 RightSide; + s16 Left; + s16 Right; + s16 Center; + s16 LFE; + s16 LeftBack; + s16 RightBack; + s16 LeftSide; + s16 RightSide; - void ResampleFrom( const StereoOut32& src ) - { - Left = src.Left >> SndOutVolumeShift; - Right = src.Right >> SndOutVolumeShift; - Center = (src.Left + src.Right) >> (SndOutVolumeShift + 1); - LFE = Center; - LeftBack = src.Left >> SndOutVolumeShift; - RightBack = src.Right >> SndOutVolumeShift; + void ResampleFrom(const StereoOut32 &src) + { + Left = src.Left >> SndOutVolumeShift; + Right = src.Right >> SndOutVolumeShift; + Center = (src.Left + src.Right) >> (SndOutVolumeShift + 1); + LFE = Center; + LeftBack = src.Left >> SndOutVolumeShift; + RightBack = src.Right >> SndOutVolumeShift; - LeftSide = src.Left >> (SndOutVolumeShift+1); - RightSide = src.Right >> (SndOutVolumeShift+1); - } + LeftSide = src.Left >> (SndOutVolumeShift + 1); + RightSide = src.Right >> (SndOutVolumeShift + 1); + } - void AdjustFrom(const StereoOut32& src) - { - ResampleFrom(src); + void AdjustFrom(const StereoOut32 &src) + { + ResampleFrom(src); - Left = (s16) (Left * VolumeAdjustFL); - Right = (s16) (Right * VolumeAdjustFR); - LeftBack = (s16) (LeftBack * VolumeAdjustBL); - RightBack = (s16) (RightBack * VolumeAdjustBR); - LeftSide = (s16) (LeftBack * VolumeAdjustSL); - RightSide = (s16) (RightBack * VolumeAdjustSR); - Center = (s16) (Center * VolumeAdjustC); - LFE = (s16) (LFE * VolumeAdjustLFE); - } + Left = (s16)(Left * VolumeAdjustFL); + Right = (s16)(Right * VolumeAdjustFR); + LeftBack = (s16)(LeftBack * VolumeAdjustBL); + RightBack = (s16)(RightBack * VolumeAdjustBR); + LeftSide = (s16)(LeftBack * VolumeAdjustSL); + RightSide = (s16)(RightBack * VolumeAdjustSR); + Center = (s16)(Center * VolumeAdjustC); + LFE = (s16)(LFE * VolumeAdjustLFE); + } }; struct Stereo71Out32 { - s32 Left; - s32 Right; - s32 Center; - s32 LFE; - s32 LeftBack; - s32 RightBack; - s32 LeftSide; - s32 RightSide; + s32 Left; + s32 Right; + s32 Center; + s32 LFE; + s32 LeftBack; + s32 RightBack; + s32 LeftSide; + s32 RightSide; - void ResampleFrom( const StereoOut32& src ) - { - Left = src.Left << SndOutVolumeShift32; - Right = src.Right << SndOutVolumeShift32; - Center = (src.Left + src.Right) << (SndOutVolumeShift32 - 1); - LFE = Center; - LeftBack = src.Left << SndOutVolumeShift32; - RightBack = src.Right << SndOutVolumeShift32; + void ResampleFrom(const StereoOut32 &src) + { + Left = src.Left << SndOutVolumeShift32; + Right = src.Right << SndOutVolumeShift32; + Center = (src.Left + src.Right) << (SndOutVolumeShift32 - 1); + LFE = Center; + LeftBack = src.Left << SndOutVolumeShift32; + RightBack = src.Right << SndOutVolumeShift32; - LeftSide = src.Left << (SndOutVolumeShift32 - 1); - RightSide = src.Right << (SndOutVolumeShift32 - 1); - } + LeftSide = src.Left << (SndOutVolumeShift32 - 1); + RightSide = src.Right << (SndOutVolumeShift32 - 1); + } - void AdjustFrom(const StereoOut32& src) - { - ResampleFrom(src); + void AdjustFrom(const StereoOut32 &src) + { + ResampleFrom(src); - Left = (s32) (Left * VolumeAdjustFL); - Right = (s32) (Right * VolumeAdjustFR); - LeftBack = (s32) (LeftBack * VolumeAdjustBL); - RightBack = (s32) (RightBack * VolumeAdjustBR); - LeftSide = (s32) (LeftBack * VolumeAdjustSL); - RightSide = (s32) (RightBack * VolumeAdjustSR); - Center = (s32) (Center * VolumeAdjustC); - LFE = (s32) (LFE * VolumeAdjustLFE); - } + Left = (s32)(Left * VolumeAdjustFL); + Right = (s32)(Right * VolumeAdjustFR); + LeftBack = (s32)(LeftBack * VolumeAdjustBL); + RightBack = (s32)(RightBack * VolumeAdjustBR); + LeftSide = (s32)(LeftBack * VolumeAdjustSL); + RightSide = (s32)(RightBack * VolumeAdjustSR); + Center = (s32)(Center * VolumeAdjustC); + LFE = (s32)(LFE * VolumeAdjustLFE); + } }; struct Stereo20Out32 { - s32 Left; - s32 Right; + s32 Left; + s32 Right; - void ResampleFrom( const StereoOut32& src ) - { - Left = src.Left << SndOutVolumeShift32; - Right = src.Right << SndOutVolumeShift32; - } + void ResampleFrom(const StereoOut32 &src) + { + Left = src.Left << SndOutVolumeShift32; + Right = src.Right << SndOutVolumeShift32; + } - void AdjustFrom(const StereoOut32& src) - { - ResampleFrom(src); + void AdjustFrom(const StereoOut32 &src) + { + ResampleFrom(src); - Left = (s32) (Left * VolumeAdjustFL); - Right = (s32) (Right * VolumeAdjustFR); - } + Left = (s32)(Left * VolumeAdjustFL); + Right = (s32)(Right * VolumeAdjustFR); + } }; struct Stereo21Out32 { - s32 Left; - s32 Right; - s32 LFE; + s32 Left; + s32 Right; + s32 LFE; - void ResampleFrom( const StereoOut32& src ) - { - Left = src.Left << SndOutVolumeShift32; - Right = src.Right << SndOutVolumeShift32; - LFE = (src.Left + src.Right) << (SndOutVolumeShift32 - 1); - } + void ResampleFrom(const StereoOut32 &src) + { + Left = src.Left << SndOutVolumeShift32; + Right = src.Right << SndOutVolumeShift32; + LFE = (src.Left + src.Right) << (SndOutVolumeShift32 - 1); + } - void AdjustFrom(const StereoOut32& src) - { - ResampleFrom(src); + void AdjustFrom(const StereoOut32 &src) + { + ResampleFrom(src); - Left = (s32) (Left * VolumeAdjustFL); - Right = (s32) (Right * VolumeAdjustFR); - LFE = (s32) (LFE * VolumeAdjustLFE); - } + Left = (s32)(Left * VolumeAdjustFL); + Right = (s32)(Right * VolumeAdjustFR); + LFE = (s32)(LFE * VolumeAdjustLFE); + } }; struct Stereo41Out32 { - s32 Left; - s32 Right; - s32 LFE; - s32 LeftBack; - s32 RightBack; + s32 Left; + s32 Right; + s32 LFE; + s32 LeftBack; + s32 RightBack; - void ResampleFrom( const StereoOut32& src ) - { - Left = src.Left << SndOutVolumeShift32; - Right = src.Right << SndOutVolumeShift32; - LFE = (src.Left + src.Right) << (SndOutVolumeShift32 - 1); + void ResampleFrom(const StereoOut32 &src) + { + Left = src.Left << SndOutVolumeShift32; + Right = src.Right << SndOutVolumeShift32; + LFE = (src.Left + src.Right) << (SndOutVolumeShift32 - 1); - LeftBack = src.Left << SndOutVolumeShift32; - RightBack = src.Right << SndOutVolumeShift32; - } + LeftBack = src.Left << SndOutVolumeShift32; + RightBack = src.Right << SndOutVolumeShift32; + } - void AdjustFrom(const StereoOut32& src) - { - ResampleFrom(src); + void AdjustFrom(const StereoOut32 &src) + { + ResampleFrom(src); - Left = (s32) (Left * VolumeAdjustFL); - Right = (s32) (Right * VolumeAdjustFR); - LeftBack = (s32) (LeftBack * VolumeAdjustBL); - RightBack = (s32) (RightBack * VolumeAdjustBR); - LFE = (s32) (LFE * VolumeAdjustLFE); - } + Left = (s32)(Left * VolumeAdjustFL); + Right = (s32)(Right * VolumeAdjustFR); + LeftBack = (s32)(LeftBack * VolumeAdjustBL); + RightBack = (s32)(RightBack * VolumeAdjustBR); + LFE = (s32)(LFE * VolumeAdjustLFE); + } }; struct Stereo51Out32 { - s32 Left; - s32 Right; - s32 Center; - s32 LFE; - s32 LeftBack; - s32 RightBack; + s32 Left; + s32 Right; + s32 Center; + s32 LFE; + s32 LeftBack; + s32 RightBack; - void ResampleFrom( const StereoOut32& src ) - { - Left = src.Left << SndOutVolumeShift32; - Right = src.Right << SndOutVolumeShift32; - Center = (src.Left + src.Right) << (SndOutVolumeShift32 - 1); - LFE = Center; - LeftBack = src.Left << SndOutVolumeShift32; - RightBack = src.Right << SndOutVolumeShift32; - } + void ResampleFrom(const StereoOut32 &src) + { + Left = src.Left << SndOutVolumeShift32; + Right = src.Right << SndOutVolumeShift32; + Center = (src.Left + src.Right) << (SndOutVolumeShift32 - 1); + LFE = Center; + LeftBack = src.Left << SndOutVolumeShift32; + RightBack = src.Right << SndOutVolumeShift32; + } - void AdjustFrom(const StereoOut32& src) - { - ResampleFrom(src); + void AdjustFrom(const StereoOut32 &src) + { + ResampleFrom(src); - Left = (s32) (Left * VolumeAdjustFL); - Right = (s32) (Right * VolumeAdjustFR); - LeftBack = (s32) (LeftBack * VolumeAdjustBL); - RightBack = (s32) (RightBack * VolumeAdjustBR); - Center = (s32) (Center * VolumeAdjustC); - LFE = (s32) (LFE * VolumeAdjustLFE); - } + Left = (s32)(Left * VolumeAdjustFL); + Right = (s32)(Right * VolumeAdjustFR); + LeftBack = (s32)(LeftBack * VolumeAdjustBL); + RightBack = (s32)(RightBack * VolumeAdjustBR); + Center = (s32)(Center * VolumeAdjustC); + LFE = (s32)(LFE * VolumeAdjustLFE); + } }; // Developer Note: This is a static class only (all static members). class SndBuffer { private: - static bool m_underrun_freeze; - static s32 m_predictData; - static float lastPct; + static bool m_underrun_freeze; + static s32 m_predictData; + static float lastPct; - static StereoOut32* sndTempBuffer; - static StereoOut16* sndTempBuffer16; - - static int sndTempProgress; - static int m_dsp_progress; + static StereoOut32 *sndTempBuffer; + static StereoOut16 *sndTempBuffer16; - static int m_timestretch_progress; - static int m_timestretch_writepos; + static int sndTempProgress; + static int m_dsp_progress; - static StereoOut32 *m_buffer; - static s32 m_size; + static int m_timestretch_progress; + static int m_timestretch_writepos; - static __aligned(4) volatile s32 m_rpos; - static __aligned(4) volatile s32 m_wpos; - - static float lastEmergencyAdj; - static float cTempo; - static float eTempo; - static int ssFreeze; + static StereoOut32 *m_buffer; + static s32 m_size; - static void _InitFail(); - static bool CheckUnderrunStatus( int& nSamples, int& quietSampleCount ); + static __aligned(4) volatile s32 m_rpos; + static __aligned(4) volatile s32 m_wpos; - static void soundtouchInit(); - static void soundtouchClearContents(); - static void soundtouchCleanup(); - static void timeStretchWrite(); - static void timeStretchUnderrun(); - static s32 timeStretchOverrun(); + static float lastEmergencyAdj; + static float cTempo; + static float eTempo; + static int ssFreeze; - static void PredictDataWrite( int samples ); - static float GetStatusPct(); - static void UpdateTempoChangeSoundTouch(); - static void UpdateTempoChangeSoundTouch2(); + static void _InitFail(); + static bool CheckUnderrunStatus(int &nSamples, int &quietSampleCount); - static void _WriteSamples(StereoOut32* bData, int nSamples); - - static void _WriteSamples_Safe(StereoOut32* bData, int nSamples); - static void _ReadSamples_Safe(StereoOut32* bData, int nSamples); + static void soundtouchInit(); + static void soundtouchClearContents(); + static void soundtouchCleanup(); + static void timeStretchWrite(); + static void timeStretchUnderrun(); + static s32 timeStretchOverrun(); - static void _WriteSamples_Internal(StereoOut32 *bData, int nSamples); - static void _DropSamples_Internal(int nSamples); - static void _ReadSamples_Internal(StereoOut32 *bData, int nSamples); + static void PredictDataWrite(int samples); + static float GetStatusPct(); + static void UpdateTempoChangeSoundTouch(); + static void UpdateTempoChangeSoundTouch2(); + + static void _WriteSamples(StereoOut32 *bData, int nSamples); + + static void _WriteSamples_Safe(StereoOut32 *bData, int nSamples); + static void _ReadSamples_Safe(StereoOut32 *bData, int nSamples); + + static void _WriteSamples_Internal(StereoOut32 *bData, int nSamples); + static void _DropSamples_Internal(int nSamples); + static void _ReadSamples_Internal(StereoOut32 *bData, int nSamples); + + static int _GetApproximateDataInBuffer(); - static int _GetApproximateDataInBuffer(); - public: - static void UpdateTempoChangeAsyncMixing(); - static void Init(); - static void Cleanup(); - static void Write( const StereoOut32& Sample ); - static s32 Test(); - static void ClearContents(); + static void UpdateTempoChangeAsyncMixing(); + static void Init(); + static void Cleanup(); + static void Write(const StereoOut32 &Sample); + static s32 Test(); + static void ClearContents(); - // 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 ); + // 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 + static void ReadSamples(T *bData); }; class SndOutModule { public: - // Virtual destructor, because it helps fight C+++ funny-business. - virtual ~SndOutModule() {} + // Virtual destructor, because it helps fight C+++ funny-business. + virtual ~SndOutModule() {} - // Returns a unique identification string for this driver. - // (usually just matches the driver's cpp filename) - virtual const wchar_t* GetIdent() const=0; + // Returns a unique identification string for this driver. + // (usually just matches the driver's cpp filename) + virtual const wchar_t *GetIdent() const = 0; - // Returns the long name / description for this driver. - // (for use in configuration screen) - virtual const wchar_t* GetLongName() const=0; + // Returns the long name / description for this driver. + // (for use in configuration screen) + virtual const wchar_t *GetLongName() const = 0; - virtual s32 Init()=0; - virtual void Close()=0; - virtual s32 Test() const=0; + virtual s32 Init() = 0; + virtual void Close() = 0; + virtual s32 Test() const = 0; - // Gui function: Used to open the configuration box for this driver. - virtual void Configure(uptr parent)=0; + // Gui function: Used to open the configuration box for this driver. + virtual void Configure(uptr parent) = 0; - // Loads settings from the INI file for this driver - virtual void ReadSettings()=0; + // Loads settings from the INI file for this driver + virtual void ReadSettings() = 0; - // Set output API for this driver - virtual void SetApiSettings(wxString api) =0; + // Set output API for this driver + virtual void SetApiSettings(wxString api) = 0; - // Saves settings to the INI file for this driver - virtual void WriteSettings() const=0; - - // Returns the number of empty samples in the output buffer. - // (which is effectively the amount of data played since the last update) - virtual int GetEmptySampleCount() =0; + // Saves settings to the INI file for this driver + virtual void WriteSettings() const = 0; + + // Returns the number of empty samples in the output buffer. + // (which is effectively the amount of data played since the last update) + virtual int GetEmptySampleCount() = 0; }; #ifdef _MSC_VER //internal -extern SndOutModule* WaveOut; -extern SndOutModule* DSoundOut; -extern SndOutModule* XAudio2_27_Out; -extern SndOutModule* XAudio2Out; +extern SndOutModule *WaveOut; +extern SndOutModule *DSoundOut; +extern SndOutModule *XAudio2_27_Out; +extern SndOutModule *XAudio2Out; #endif -extern SndOutModule* PortaudioOut; +extern SndOutModule *PortaudioOut; #if defined(SPU2X_SDL) || defined(SPU2X_SDL2) -extern SndOutModule * const SDLOut; +extern SndOutModule *const SDLOut; #endif #ifdef __linux__ -extern SndOutModule* AlsaOut; +extern SndOutModule *AlsaOut; #endif -extern SndOutModule* mods[]; +extern SndOutModule *mods[]; // ===================================================================================================== @@ -689,9 +689,9 @@ extern bool WavRecordEnabled; extern void RecordStart(); extern void RecordStop(); -extern void RecordWrite( const StereoOut16& sample ); +extern void RecordWrite(const StereoOut16 &sample); -extern s32 DspLoadLibrary(wchar_t *fileName, int modNum); +extern s32 DspLoadLibrary(wchar_t *fileName, int modNum); extern void DspCloseLibrary(); -extern int DspProcess(s16 *buffer, int samples); -extern void DspUpdate(); // to let the Dsp process window messages +extern int DspProcess(s16 *buffer, int samples); +extern void DspUpdate(); // to let the Dsp process window messages diff --git a/plugins/spu2-x/src/SndOut_Portaudio.cpp b/plugins/spu2-x/src/SndOut_Portaudio.cpp index 0273e02527..9136a2f095 100644 --- a/plugins/spu2-x/src/SndOut_Portaudio.cpp +++ b/plugins/spu2-x/src/SndOut_Portaudio.cpp @@ -30,646 +30,655 @@ #include "pa_win_wasapi.h" #endif -int PaCallback( const void *inputBuffer, void *outputBuffer, - unsigned long framesPerBuffer, - const PaStreamCallbackTimeInfo* timeInfo, - PaStreamCallbackFlags statusFlags, - void *userData ); +int PaCallback(const void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + const PaStreamCallbackTimeInfo *timeInfo, + PaStreamCallbackFlags statusFlags, + void *userData); class Portaudio : public SndOutModule { private: - ////////////////////////////////////////////////////////////////////////////////////////// - // Configuration Vars (unused still) + ////////////////////////////////////////////////////////////////////////////////////////// + // Configuration Vars (unused still) - int m_ApiId; - wxString m_Device; + int m_ApiId; + wxString m_Device; - bool m_UseHardware; + bool m_UseHardware; - bool m_WasapiExclusiveMode; - - bool m_SuggestedLatencyMinimal; - int m_SuggestedLatencyMS; + bool m_WasapiExclusiveMode; - ////////////////////////////////////////////////////////////////////////////////////////// - // Instance vars + bool m_SuggestedLatencyMinimal; + int m_SuggestedLatencyMS; - int writtenSoFar; - int writtenLastTime; - int availableLastTime; + ////////////////////////////////////////////////////////////////////////////////////////// + // Instance vars - int actualUsedChannels; + int writtenSoFar; + int writtenLastTime; + int availableLastTime; - bool started; - PaStream* stream; + int actualUsedChannels; - ////////////////////////////////////////////////////////////////////////////////////////// - // Stuff necessary for speaker expansion - class SampleReader - { - public: - virtual int ReadSamples( const void *inputBuffer, void *outputBuffer, - unsigned long framesPerBuffer, - const PaStreamCallbackTimeInfo* timeInfo, - PaStreamCallbackFlags statusFlags, - void *userData ) = 0; - }; + bool started; + PaStream *stream; - template - class ConvertedSampleReader : public SampleReader - { - int* written; - public: - ConvertedSampleReader(int* pWritten) - { - written = pWritten; - } + ////////////////////////////////////////////////////////////////////////////////////////// + // Stuff necessary for speaker expansion + class SampleReader + { + public: + virtual int ReadSamples(const void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + const PaStreamCallbackTimeInfo *timeInfo, + PaStreamCallbackFlags statusFlags, + void *userData) = 0; + }; - virtual int ReadSamples( const void *inputBuffer, void *outputBuffer, - unsigned long framesPerBuffer, - const PaStreamCallbackTimeInfo* timeInfo, - PaStreamCallbackFlags statusFlags, - void *userData ) - { - T* p1 = (T*)outputBuffer; + template + class ConvertedSampleReader : public SampleReader + { + int *written; - int packets = framesPerBuffer / SndOutPacketSize; + public: + ConvertedSampleReader(int *pWritten) + { + written = pWritten; + } - for(int p=0; pmaxOutputChannels > 0) - { - const PaHostApiInfo * apiinfo = Pa_GetHostApiInfo(info->hostApi); + if (info->maxOutputChannels > 0) { + const PaHostApiInfo *apiinfo = Pa_GetHostApiInfo(info->hostApi); - fprintf(stderr," *** Device %d: '%s' (%s)", j, info->name, apiinfo->name); + fprintf(stderr, " *** Device %d: '%s' (%s)", j, info->name, apiinfo->name); - if(apiinfo->type == m_ApiId) - { - if(m_Device == wxString::FromUTF8(info->name)) - { - deviceIndex = i; - fprintf(stderr," (selected)"); - } + if (apiinfo->type == m_ApiId) { + if (m_Device == wxString::FromUTF8(info->name)) { + deviceIndex = i; + fprintf(stderr, " (selected)"); + } + } + fprintf(stderr, "\n"); - } - fprintf(stderr,"\n"); + j++; + } + } + fflush(stderr); - j++; - } - } - fflush(stderr); + if (deviceIndex < 0 && m_ApiId >= 0) { + for (int i = 0; i < Pa_GetHostApiCount(); i++) { + const PaHostApiInfo *apiinfo = Pa_GetHostApiInfo(i); + if (apiinfo->type == m_ApiId) { + deviceIndex = apiinfo->defaultOutputDevice; + } + } + } - if(deviceIndex<0 && m_ApiId>=0) - { - for(int i=0;itype == m_ApiId) - { - deviceIndex = apiinfo->defaultOutputDevice; - } - } - } + if (deviceIndex >= 0) { + void *infoPtr = NULL; - if(deviceIndex>=0) - { - void* infoPtr = NULL; - - const PaDeviceInfo * devinfo = Pa_GetDeviceInfo(deviceIndex); - - int speakers; - switch(numSpeakers) // speakers = (numSpeakers + 1) *2; ? - { - case 0: speakers = 2; break; // Stereo - case 1: speakers = 4; break; // Quadrafonic - case 2: speakers = 6; break; // Surround 5.1 - case 3: speakers = 8; break; // Surround 7.1 - default: speakers = 2; - } - actualUsedChannels = std::min(speakers, devinfo->maxOutputChannels); + const PaDeviceInfo *devinfo = Pa_GetDeviceInfo(deviceIndex); - switch( actualUsedChannels ) - { - case 2: - ConLog( "* SPU2 > Using normal 2 speaker stereo output.\n" ); - ActualPaCallback = new ConvertedSampleReader(&writtenSoFar); - break; + int speakers; + switch (numSpeakers) // speakers = (numSpeakers + 1) *2; ? + { + case 0: + speakers = 2; + break; // Stereo + case 1: + speakers = 4; + break; // Quadrafonic + case 2: + speakers = 6; + break; // Surround 5.1 + case 3: + speakers = 8; + break; // Surround 7.1 + default: + speakers = 2; + } + actualUsedChannels = std::min(speakers, devinfo->maxOutputChannels); - case 3: - ConLog( "* SPU2 > 2.1 speaker expansion enabled.\n" ); - ActualPaCallback = new ConvertedSampleReader(&writtenSoFar); - break; + switch (actualUsedChannels) { + case 2: + ConLog("* SPU2 > Using normal 2 speaker stereo output.\n"); + ActualPaCallback = new ConvertedSampleReader(&writtenSoFar); + break; - case 4: - ConLog( "* SPU2 > 4 speaker expansion enabled [quadraphenia]\n" ); - ActualPaCallback = new ConvertedSampleReader(&writtenSoFar); - break; + case 3: + ConLog("* SPU2 > 2.1 speaker expansion enabled.\n"); + ActualPaCallback = new ConvertedSampleReader(&writtenSoFar); + break; - case 5: - ConLog( "* SPU2 > 4.1 speaker expansion enabled.\n" ); - ActualPaCallback = new ConvertedSampleReader(&writtenSoFar); - break; + case 4: + ConLog("* SPU2 > 4 speaker expansion enabled [quadraphenia]\n"); + ActualPaCallback = new ConvertedSampleReader(&writtenSoFar); + break; - case 6: - case 7: - switch(dplLevel) - { - case 0: - ConLog( "* SPU2 > 5.1 speaker expansion enabled.\n" ); - ActualPaCallback = new ConvertedSampleReader(&writtenSoFar); //"normal" stereo upmix - break; - case 1: - ConLog( "* SPU2 > 5.1 speaker expansion with basic ProLogic dematrixing enabled.\n" ); - ActualPaCallback = new ConvertedSampleReader(&writtenSoFar); // basic Dpl decoder without rear stereo balancing - break; - case 2: - ConLog( "* SPU2 > 5.1 speaker expansion with experimental ProLogicII dematrixing enabled.\n" ); - ActualPaCallback = new ConvertedSampleReader(&writtenSoFar); //gigas PLII - break; - } - actualUsedChannels = 6; // we do not support 7.0 or 6.2 configurations, downgrade to 5.1 - break; + case 5: + ConLog("* SPU2 > 4.1 speaker expansion enabled.\n"); + ActualPaCallback = new ConvertedSampleReader(&writtenSoFar); + break; - default: // anything 8 or more gets the 7.1 treatment! - ConLog( "* SPU2 > 7.1 speaker expansion enabled.\n" ); - ActualPaCallback = new ConvertedSampleReader(&writtenSoFar); - actualUsedChannels = 8; // we do not support 7.2 or more, downgrade to 7.1 - break; - } + case 6: + case 7: + switch (dplLevel) { + case 0: + ConLog("* SPU2 > 5.1 speaker expansion enabled.\n"); + ActualPaCallback = new ConvertedSampleReader(&writtenSoFar); //"normal" stereo upmix + break; + case 1: + ConLog("* SPU2 > 5.1 speaker expansion with basic ProLogic dematrixing enabled.\n"); + ActualPaCallback = new ConvertedSampleReader(&writtenSoFar); // basic Dpl decoder without rear stereo balancing + break; + case 2: + ConLog("* SPU2 > 5.1 speaker expansion with experimental ProLogicII dematrixing enabled.\n"); + ActualPaCallback = new ConvertedSampleReader(&writtenSoFar); //gigas PLII + break; + } + actualUsedChannels = 6; // we do not support 7.0 or 6.2 configurations, downgrade to 5.1 + break; + + default: // anything 8 or more gets the 7.1 treatment! + ConLog("* SPU2 > 7.1 speaker expansion enabled.\n"); + ActualPaCallback = new ConvertedSampleReader(&writtenSoFar); + actualUsedChannels = 8; // we do not support 7.2 or more, downgrade to 7.1 + break; + } #ifdef _WIN32 - PaWasapiStreamInfo info = { - sizeof(PaWasapiStreamInfo), - paWASAPI, - 1, - paWinWasapiExclusive - }; + PaWasapiStreamInfo info = { + sizeof(PaWasapiStreamInfo), + paWASAPI, + 1, + paWinWasapiExclusive}; - if((m_ApiId == paWASAPI) && m_WasapiExclusiveMode) - { - // Pass it the Exclusive mode enable flag - infoPtr = &info; - } + if ((m_ApiId == paWASAPI) && m_WasapiExclusiveMode) { + // Pass it the Exclusive mode enable flag + infoPtr = &info; + } #endif - PaStreamParameters outParams = { + PaStreamParameters outParams = { - // PaDeviceIndex device; - // int channelCount; - // PaSampleFormat sampleFormat; - // PaTime suggestedLatency; - // void *hostApiSpecificStreamInfo; - deviceIndex, - actualUsedChannels, - paInt32, - m_SuggestedLatencyMinimal?(SndOutPacketSize/(float)SampleRate):(m_SuggestedLatencyMS/1000.0f), - infoPtr - }; + // PaDeviceIndex device; + // int channelCount; + // PaSampleFormat sampleFormat; + // PaTime suggestedLatency; + // void *hostApiSpecificStreamInfo; + deviceIndex, + actualUsedChannels, + paInt32, + m_SuggestedLatencyMinimal ? (SndOutPacketSize / (float)SampleRate) : (m_SuggestedLatencyMS / 1000.0f), + infoPtr}; - err = Pa_OpenStream(&stream, - NULL, &outParams, SampleRate, - SndOutPacketSize, - paNoFlag, - PaCallback, + err = Pa_OpenStream(&stream, + NULL, &outParams, SampleRate, + SndOutPacketSize, + paNoFlag, + PaCallback, - NULL); - } - else - { - err = Pa_OpenDefaultStream( &stream, - 0, actualUsedChannels, paInt32, 48000, - SndOutPacketSize, - PaCallback, - NULL ); - } - if( err != paNoError ) - { - fprintf(stderr,"* SPU2-X: PortAudio error: %s\n", Pa_GetErrorText( err ) ); - Pa_Terminate(); - return -1; - } + NULL); + } else { + err = Pa_OpenDefaultStream(&stream, + 0, actualUsedChannels, paInt32, 48000, + SndOutPacketSize, + PaCallback, + NULL); + } + if (err != paNoError) { + fprintf(stderr, "* SPU2-X: PortAudio error: %s\n", Pa_GetErrorText(err)); + Pa_Terminate(); + return -1; + } - err = Pa_StartStream( stream ); - if( err != paNoError ) - { - fprintf(stderr,"* SPU2-X: PortAudio error: %s\n", Pa_GetErrorText( err ) ); - Pa_CloseStream(stream); - stream=NULL; - Pa_Terminate(); - return -1; - } + err = Pa_StartStream(stream); + if (err != paNoError) { + fprintf(stderr, "* SPU2-X: PortAudio error: %s\n", Pa_GetErrorText(err)); + Pa_CloseStream(stream); + stream = NULL; + Pa_Terminate(); + return -1; + } - return 0; - } + return 0; + } - void Close() - { - PaError err; - if(started) - { - if(stream) - { - if(Pa_IsStreamActive(stream)) - { - err = Pa_StopStream(stream); - if( err != paNoError ) - fprintf(stderr,"* SPU2-X: PortAudio error: %s\n", Pa_GetErrorText( err ) ); - } + void Close() + { + PaError err; + if (started) { + if (stream) { + if (Pa_IsStreamActive(stream)) { + err = Pa_StopStream(stream); + if (err != paNoError) + fprintf(stderr, "* SPU2-X: PortAudio error: %s\n", Pa_GetErrorText(err)); + } - err = Pa_CloseStream(stream); - if( err != paNoError ) - fprintf(stderr,"* SPU2-X: PortAudio error: %s\n", Pa_GetErrorText( err ) ); + err = Pa_CloseStream(stream); + if (err != paNoError) + fprintf(stderr, "* SPU2-X: PortAudio error: %s\n", Pa_GetErrorText(err)); - stream=NULL; - } + stream = NULL; + } - // Seems to do more harm than good. - //PaError err = Pa_Terminate(); - //if( err != paNoError ) - // fprintf(stderr,"* SPU2-X: PortAudio error: %s\n", Pa_GetErrorText( err ) ); + // Seems to do more harm than good. + //PaError err = Pa_Terminate(); + //if( err != paNoError ) + // fprintf(stderr,"* SPU2-X: PortAudio error: %s\n", Pa_GetErrorText( err ) ); - started=false; - } - } + started = false; + } + } - //////////////////////////////////////////////////////////////// - //////////////////////////////////////////////////////////////// - //////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////// #ifdef _WIN32 private: - - bool _ConfigProc(HWND hWnd,UINT uMsg,WPARAM wParam,LPARAM lParam) - { - int wmId,wmEvent; - int tSel = 0; + bool _ConfigProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) + { + int wmId, wmEvent; + int tSel = 0; - switch(uMsg) - { - case WM_INITDIALOG: - { - wchar_t temp[128]; - - SendMessage(GetDlgItem(hWnd,IDC_PA_DEVICE),CB_RESETCONTENT,0,0); - SendMessageA(GetDlgItem(hWnd,IDC_PA_DEVICE),CB_ADDSTRING,0,(LPARAM)"Default Device"); - SendMessage(GetDlgItem(hWnd,IDC_PA_DEVICE),CB_SETCURSEL,0,0); + switch (uMsg) { + case WM_INITDIALOG: { + wchar_t temp[128]; - SendMessage(GetDlgItem(hWnd,IDC_PA_HOSTAPI),CB_RESETCONTENT,0,0); - SendMessageA(GetDlgItem(hWnd,IDC_PA_HOSTAPI),CB_ADDSTRING,0,(LPARAM)"Unspecified"); - int idx = 0; - for(int i=0;ideviceCount > 0) - { - SendMessageA(GetDlgItem(hWnd,IDC_PA_HOSTAPI),CB_ADDSTRING,0,(LPARAM)apiinfo->name); - SendMessageA(GetDlgItem(hWnd,IDC_PA_HOSTAPI),CB_SETITEMDATA,i+1,apiinfo->type); - } - if(apiinfo->type == m_ApiId) - { - idx = i+1; - } - } - SendMessage(GetDlgItem(hWnd,IDC_PA_HOSTAPI),CB_SETCURSEL,idx,0); - - if(idx > 0) - { - int api_idx = idx-1; - SendMessage(GetDlgItem(hWnd,IDC_PA_DEVICE),CB_RESETCONTENT,0,0); - SendMessageA(GetDlgItem(hWnd,IDC_PA_DEVICE),CB_ADDSTRING,0,(LPARAM)"Default Device"); - SendMessage(GetDlgItem(hWnd,IDC_PA_DEVICE),CB_SETITEMDATA,0,0); - int _idx=0; - int i=1; - for(int j=0;jhostApi == api_idx && info->maxOutputChannels > 0) - { - SendMessage(GetDlgItem(hWnd,IDC_PA_DEVICE),CB_ADDSTRING,0,(LPARAM)wxString::FromUTF8(info->name).wc_str()); - SendMessage(GetDlgItem(hWnd,IDC_PA_DEVICE),CB_SETITEMDATA,i,(LPARAM)info); - if(wxString::FromUTF8(info->name) == m_Device) - { - _idx = i; - } - i++; - } - } - SendMessage(GetDlgItem(hWnd,IDC_PA_DEVICE),CB_SETCURSEL,_idx,0); - } + SendMessage(GetDlgItem(hWnd, IDC_PA_DEVICE), CB_RESETCONTENT, 0, 0); + SendMessageA(GetDlgItem(hWnd, IDC_PA_DEVICE), CB_ADDSTRING, 0, (LPARAM) "Default Device"); + SendMessage(GetDlgItem(hWnd, IDC_PA_DEVICE), CB_SETCURSEL, 0, 0); - INIT_SLIDER( IDC_LATENCY, 10, 200, 10, 1, 1 ); - SendMessage(GetDlgItem(hWnd,IDC_LATENCY),TBM_SETPOS,TRUE,m_SuggestedLatencyMS); - swprintf_s(temp, L"%d ms",m_SuggestedLatencyMS); - SetWindowText(GetDlgItem(hWnd,IDC_LATENCY_LABEL),temp); + SendMessage(GetDlgItem(hWnd, IDC_PA_HOSTAPI), CB_RESETCONTENT, 0, 0); + SendMessageA(GetDlgItem(hWnd, IDC_PA_HOSTAPI), CB_ADDSTRING, 0, (LPARAM) "Unspecified"); + int idx = 0; + for (int i = 0; i < Pa_GetHostApiCount(); i++) { + const PaHostApiInfo *apiinfo = Pa_GetHostApiInfo(i); + if (apiinfo->deviceCount > 0) { + SendMessageA(GetDlgItem(hWnd, IDC_PA_HOSTAPI), CB_ADDSTRING, 0, (LPARAM)apiinfo->name); + SendMessageA(GetDlgItem(hWnd, IDC_PA_HOSTAPI), CB_SETITEMDATA, i + 1, apiinfo->type); + } + if (apiinfo->type == m_ApiId) { + idx = i + 1; + } + } + SendMessage(GetDlgItem(hWnd, IDC_PA_HOSTAPI), CB_SETCURSEL, idx, 0); - if(m_SuggestedLatencyMinimal) - SET_CHECK( IDC_MINIMIZE, true ); - else - SET_CHECK( IDC_MANUAL, true ); - - SET_CHECK( IDC_EXCLUSIVE, m_WasapiExclusiveMode ); - } - break; + if (idx > 0) { + int api_idx = idx - 1; + SendMessage(GetDlgItem(hWnd, IDC_PA_DEVICE), CB_RESETCONTENT, 0, 0); + SendMessageA(GetDlgItem(hWnd, IDC_PA_DEVICE), CB_ADDSTRING, 0, (LPARAM) "Default Device"); + SendMessage(GetDlgItem(hWnd, IDC_PA_DEVICE), CB_SETITEMDATA, 0, 0); + int _idx = 0; + int i = 1; + for (int j = 0; j < Pa_GetDeviceCount(); j++) { + const PaDeviceInfo *info = Pa_GetDeviceInfo(j); + if (info->hostApi == api_idx && info->maxOutputChannels > 0) { + SendMessage(GetDlgItem(hWnd, IDC_PA_DEVICE), CB_ADDSTRING, 0, (LPARAM)wxString::FromUTF8(info->name).wc_str()); + SendMessage(GetDlgItem(hWnd, IDC_PA_DEVICE), CB_SETITEMDATA, i, (LPARAM)info); + if (wxString::FromUTF8(info->name) == m_Device) { + _idx = i; + } + i++; + } + } + SendMessage(GetDlgItem(hWnd, IDC_PA_DEVICE), CB_SETCURSEL, _idx, 0); + } - case WM_COMMAND: - { - //wchar_t temp[128]; + INIT_SLIDER(IDC_LATENCY, 10, 200, 10, 1, 1); + SendMessage(GetDlgItem(hWnd, IDC_LATENCY), TBM_SETPOS, TRUE, m_SuggestedLatencyMS); + swprintf_s(temp, L"%d ms", m_SuggestedLatencyMS); + SetWindowText(GetDlgItem(hWnd, IDC_LATENCY_LABEL), temp); - wmId = LOWORD(wParam); - wmEvent = HIWORD(wParam); - // Parse the menu selections: - switch (wmId) - { - case IDOK: - { - int idx = (int)SendMessage(GetDlgItem(hWnd,IDC_PA_HOSTAPI),CB_GETCURSEL,0,0); - m_ApiId = SendMessage(GetDlgItem(hWnd,IDC_PA_HOSTAPI),CB_GETITEMDATA,idx,0); + if (m_SuggestedLatencyMinimal) + SET_CHECK(IDC_MINIMIZE, true); + else + SET_CHECK(IDC_MANUAL, true); - idx = (int)SendMessage(GetDlgItem(hWnd,IDC_PA_DEVICE),CB_GETCURSEL,0,0); - const PaDeviceInfo * info = (const PaDeviceInfo *)SendMessage(GetDlgItem(hWnd,IDC_PA_DEVICE),CB_GETITEMDATA,idx,0); - if(info) - m_Device = wxString::FromUTF8( info->name ); - else - m_Device = L"default"; - - m_SuggestedLatencyMS = (int)SendMessage( GetDlgItem( hWnd, IDC_LATENCY ), TBM_GETPOS, 0, 0 ); + SET_CHECK(IDC_EXCLUSIVE, m_WasapiExclusiveMode); + } break; - if( m_SuggestedLatencyMS < 10 ) m_SuggestedLatencyMS = 10; - if( m_SuggestedLatencyMS > 200 ) m_SuggestedLatencyMS = 200; + case WM_COMMAND: { + //wchar_t temp[128]; - m_SuggestedLatencyMinimal = SendMessage(GetDlgItem(hWnd,IDC_MINIMIZE),BM_GETCHECK,0,0)==BST_CHECKED; - - m_WasapiExclusiveMode = SendMessage(GetDlgItem(hWnd,IDC_EXCLUSIVE),BM_GETCHECK,0,0)==BST_CHECKED; + wmId = LOWORD(wParam); + wmEvent = HIWORD(wParam); + // Parse the menu selections: + switch (wmId) { + case IDOK: { + int idx = (int)SendMessage(GetDlgItem(hWnd, IDC_PA_HOSTAPI), CB_GETCURSEL, 0, 0); + m_ApiId = SendMessage(GetDlgItem(hWnd, IDC_PA_HOSTAPI), CB_GETITEMDATA, idx, 0); - EndDialog(hWnd,0); - } - break; + idx = (int)SendMessage(GetDlgItem(hWnd, IDC_PA_DEVICE), CB_GETCURSEL, 0, 0); + const PaDeviceInfo *info = (const PaDeviceInfo *)SendMessage(GetDlgItem(hWnd, IDC_PA_DEVICE), CB_GETITEMDATA, idx, 0); + if (info) + m_Device = wxString::FromUTF8(info->name); + else + m_Device = L"default"; - case IDCANCEL: - EndDialog(hWnd,0); - break; + m_SuggestedLatencyMS = (int)SendMessage(GetDlgItem(hWnd, IDC_LATENCY), TBM_GETPOS, 0, 0); - case IDC_PA_HOSTAPI: - { - if(wmEvent == CBN_SELCHANGE) - { - int api_idx = (int)SendMessage(GetDlgItem(hWnd,IDC_PA_HOSTAPI),CB_GETCURSEL,0,0)-1; - int apiId = SendMessageA(GetDlgItem(hWnd,IDC_PA_HOSTAPI),CB_GETITEMDATA,api_idx,0); - SendMessage(GetDlgItem(hWnd,IDC_PA_DEVICE),CB_RESETCONTENT,0,0); - SendMessageA(GetDlgItem(hWnd,IDC_PA_DEVICE),CB_ADDSTRING,0,(LPARAM)"Default Device"); - SendMessage(GetDlgItem(hWnd,IDC_PA_DEVICE),CB_SETITEMDATA,0,0); - int idx=0; - int i=1; - for(int j=0;jhostApi == api_idx && info->maxOutputChannels > 0) - { - SendMessage(GetDlgItem(hWnd,IDC_PA_DEVICE),CB_ADDSTRING,0,(LPARAM)wxString::FromUTF8(info->name).wc_str()); - SendMessage(GetDlgItem(hWnd,IDC_PA_DEVICE),CB_SETITEMDATA,i,(LPARAM)info); - i++; - } - } - SendMessage(GetDlgItem(hWnd,IDC_PA_DEVICE),CB_SETCURSEL,idx,0); - } - } - break; + if (m_SuggestedLatencyMS < 10) + m_SuggestedLatencyMS = 10; + if (m_SuggestedLatencyMS > 200) + m_SuggestedLatencyMS = 200; - default: - return FALSE; - } - } - break; + m_SuggestedLatencyMinimal = SendMessage(GetDlgItem(hWnd, IDC_MINIMIZE), BM_GETCHECK, 0, 0) == BST_CHECKED; - case WM_HSCROLL: - { - wmId = LOWORD(wParam); - wmEvent = HIWORD(wParam); - switch(wmId) - { - //case TB_ENDTRACK: - //case TB_THUMBPOSITION: - case TB_LINEUP: - case TB_LINEDOWN: - case TB_PAGEUP: - case TB_PAGEDOWN: - wmEvent = (int)SendMessage((HWND)lParam,TBM_GETPOS,0,0); - case TB_THUMBTRACK: - { - wchar_t temp[128]; - if( wmEvent < 10 ) wmEvent = 10; - if( wmEvent > 200 ) wmEvent = 200; - SendMessage((HWND)lParam,TBM_SETPOS,TRUE,wmEvent); - swprintf_s(temp, L"%d ms",wmEvent); - SetWindowText(GetDlgItem(hWnd,IDC_LATENCY_LABEL),temp); - break; - } - default: - return FALSE; - } - } - break; + m_WasapiExclusiveMode = SendMessage(GetDlgItem(hWnd, IDC_EXCLUSIVE), BM_GETCHECK, 0, 0) == BST_CHECKED; - default: - return FALSE; - } - return TRUE; - } + EndDialog(hWnd, 0); + } break; - static BOOL CALLBACK ConfigProc(HWND hWnd,UINT uMsg,WPARAM wParam,LPARAM lParam); - static BOOL CALLBACK DSEnumCallback( LPGUID lpGuid, LPCTSTR lpcstrDescription, LPCTSTR lpcstrModule, LPVOID lpContext ); + case IDCANCEL: + EndDialog(hWnd, 0); + break; + + case IDC_PA_HOSTAPI: { + if (wmEvent == CBN_SELCHANGE) { + int api_idx = (int)SendMessage(GetDlgItem(hWnd, IDC_PA_HOSTAPI), CB_GETCURSEL, 0, 0) - 1; + int apiId = SendMessageA(GetDlgItem(hWnd, IDC_PA_HOSTAPI), CB_GETITEMDATA, api_idx, 0); + SendMessage(GetDlgItem(hWnd, IDC_PA_DEVICE), CB_RESETCONTENT, 0, 0); + SendMessageA(GetDlgItem(hWnd, IDC_PA_DEVICE), CB_ADDSTRING, 0, (LPARAM) "Default Device"); + SendMessage(GetDlgItem(hWnd, IDC_PA_DEVICE), CB_SETITEMDATA, 0, 0); + int idx = 0; + int i = 1; + for (int j = 0; j < Pa_GetDeviceCount(); j++) { + const PaDeviceInfo *info = Pa_GetDeviceInfo(j); + if (info->hostApi == api_idx && info->maxOutputChannels > 0) { + SendMessage(GetDlgItem(hWnd, IDC_PA_DEVICE), CB_ADDSTRING, 0, (LPARAM)wxString::FromUTF8(info->name).wc_str()); + SendMessage(GetDlgItem(hWnd, IDC_PA_DEVICE), CB_SETITEMDATA, i, (LPARAM)info); + i++; + } + } + SendMessage(GetDlgItem(hWnd, IDC_PA_DEVICE), CB_SETCURSEL, idx, 0); + } + } break; + + default: + return FALSE; + } + } break; + + case WM_HSCROLL: { + wmId = LOWORD(wParam); + wmEvent = HIWORD(wParam); + switch (wmId) { + //case TB_ENDTRACK: + //case TB_THUMBPOSITION: + case TB_LINEUP: + case TB_LINEDOWN: + case TB_PAGEUP: + case TB_PAGEDOWN: + wmEvent = (int)SendMessage((HWND)lParam, TBM_GETPOS, 0, 0); + case TB_THUMBTRACK: { + wchar_t temp[128]; + if (wmEvent < 10) + wmEvent = 10; + if (wmEvent > 200) + wmEvent = 200; + SendMessage((HWND)lParam, TBM_SETPOS, TRUE, wmEvent); + swprintf_s(temp, L"%d ms", wmEvent); + SetWindowText(GetDlgItem(hWnd, IDC_LATENCY_LABEL), temp); + break; + } + default: + return FALSE; + } + } break; + + default: + return FALSE; + } + return TRUE; + } + + static BOOL CALLBACK ConfigProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam); + static BOOL CALLBACK DSEnumCallback(LPGUID lpGuid, LPCTSTR lpcstrDescription, LPCTSTR lpcstrModule, LPVOID lpContext); public: - virtual void Configure(uptr parent) - { - PaError err = Pa_Initialize(); // Initialization can be done multiple times, PA keeps a counter - if( err != paNoError ) - { - fprintf(stderr,"* SPU2-X: PortAudio error: %s\n", Pa_GetErrorText( err ) ); - return; - } - // keep portaudio initialized until the dialog closes + virtual void Configure(uptr parent) + { + PaError err = Pa_Initialize(); // Initialization can be done multiple times, PA keeps a counter + if (err != paNoError) { + fprintf(stderr, "* SPU2-X: PortAudio error: %s\n", Pa_GetErrorText(err)); + return; + } + // keep portaudio initialized until the dialog closes - INT_PTR ret; - ret=DialogBoxParam(hInstance,MAKEINTRESOURCE(IDD_PORTAUDIO),(HWND)parent,(DLGPROC)ConfigProc,1); - if(ret==-1) - { - MessageBox((HWND)parent,L"Error Opening the config dialog.",L"OMG ERROR!",MB_OK | MB_SETFOREGROUND); - return; - } + INT_PTR ret; + ret = DialogBoxParam(hInstance, MAKEINTRESOURCE(IDD_PORTAUDIO), (HWND)parent, (DLGPROC)ConfigProc, 1); + if (ret == -1) { + MessageBox((HWND)parent, L"Error Opening the config dialog.", L"OMG ERROR!", MB_OK | MB_SETFOREGROUND); + return; + } - Pa_Terminate(); - } + Pa_Terminate(); + } #else - virtual void Configure(uptr parent) - { - } + virtual void Configure(uptr parent) + { + } #endif - - s32 Test() const - { - return 0; - } - int GetEmptySampleCount() - { - long availableNow = Pa_GetStreamWriteAvailable(stream); + s32 Test() const + { + return 0; + } - int playedSinceLastTime = (writtenSoFar - writtenLastTime) + (availableNow - availableLastTime); - writtenLastTime = writtenSoFar; - availableLastTime = availableNow; + int GetEmptySampleCount() + { + long availableNow = Pa_GetStreamWriteAvailable(stream); - // Lowest resolution here is the SndOutPacketSize we use. - return playedSinceLastTime; - } + int playedSinceLastTime = (writtenSoFar - writtenLastTime) + (availableNow - availableLastTime); + writtenLastTime = writtenSoFar; + availableLastTime = availableNow; - const wchar_t* GetIdent() const - { - return L"portaudio"; - } + // Lowest resolution here is the SndOutPacketSize we use. + return playedSinceLastTime; + } - const wchar_t* GetLongName() const - { - return L"Portaudio (crossplatform)"; - } + const wchar_t *GetIdent() const + { + return L"portaudio"; + } - void ReadSettings() - { - wxString api( L"EMPTYEMPTYEMPTY" ); - m_Device = L"EMPTYEMPTYEMPTY"; + const wchar_t *GetLongName() const + { + return L"Portaudio (crossplatform)"; + } + + void ReadSettings() + { + wxString api(L"EMPTYEMPTYEMPTY"); + m_Device = L"EMPTYEMPTYEMPTY"; #ifdef __linux__ - // By default on linux use the ALSA API (+99% users) -- Gregory - CfgReadStr( L"PORTAUDIO", L"HostApi", api, L"ALSA" ); + // By default on linux use the ALSA API (+99% users) -- Gregory + CfgReadStr(L"PORTAUDIO", L"HostApi", api, L"ALSA"); #elif defined(__APPLE__) - // Suppose OSX only has CoreAudio... - CfgReadStr( L"PORTAUDIO", L"HostApi", api, L"CoreAudio" ); + // Suppose OSX only has CoreAudio... + CfgReadStr(L"PORTAUDIO", L"HostApi", api, L"CoreAudio"); #else - CfgReadStr( L"PORTAUDIO", L"HostApi", api, L"WASAPI" ); + CfgReadStr(L"PORTAUDIO", L"HostApi", api, L"WASAPI"); #endif - CfgReadStr( L"PORTAUDIO", L"Device", m_Device, L"default" ); + CfgReadStr(L"PORTAUDIO", L"Device", m_Device, L"default"); - SetApiSettings(api); + SetApiSettings(api); - m_WasapiExclusiveMode = CfgReadBool( L"PORTAUDIO", L"Wasapi_Exclusive_Mode", false); - m_SuggestedLatencyMinimal = CfgReadBool( L"PORTAUDIO", L"Minimal_Suggested_Latency", true); - m_SuggestedLatencyMS = CfgReadInt( L"PORTAUDIO", L"Manual_Suggested_Latency_MS", 20); - - if( m_SuggestedLatencyMS < 10 ) m_SuggestedLatencyMS = 10; - if( m_SuggestedLatencyMS > 200 ) m_SuggestedLatencyMS = 200; - } + m_WasapiExclusiveMode = CfgReadBool(L"PORTAUDIO", L"Wasapi_Exclusive_Mode", false); + m_SuggestedLatencyMinimal = CfgReadBool(L"PORTAUDIO", L"Minimal_Suggested_Latency", true); + m_SuggestedLatencyMS = CfgReadInt(L"PORTAUDIO", L"Manual_Suggested_Latency_MS", 20); - void SetApiSettings(wxString api) - { - m_ApiId = -1; - if(api == L"InDevelopment") m_ApiId = paInDevelopment; /* use while developing support for a new host API */ - if(api == L"DirectSound") m_ApiId = paDirectSound; - if(api == L"MME") m_ApiId = paMME; - if(api == L"ASIO") m_ApiId = paASIO; - if(api == L"SoundManager") m_ApiId = paSoundManager; - if(api == L"CoreAudio") m_ApiId = paCoreAudio; - if(api == L"OSS") m_ApiId = paOSS; - if(api == L"ALSA") m_ApiId = paALSA; - if(api == L"AL") m_ApiId = paAL; - if(api == L"BeOS") m_ApiId = paBeOS; - if(api == L"WDMKS") m_ApiId = paWDMKS; - if(api == L"JACK") m_ApiId = paJACK; - if(api == L"WASAPI") m_ApiId = paWASAPI; - if(api == L"AudioScienceHPI") m_ApiId = paAudioScienceHPI; - } + if (m_SuggestedLatencyMS < 10) + m_SuggestedLatencyMS = 10; + if (m_SuggestedLatencyMS > 200) + m_SuggestedLatencyMS = 200; + } - void WriteSettings() const - { - wxString api; - switch(m_ApiId) - { - case paInDevelopment: api = L"InDevelopment"; break; /* use while developing support for a new host API */ - case paDirectSound: api = L"DirectSound"; break; - case paMME: api = L"MME"; break; - case paASIO: api = L"ASIO"; break; - case paSoundManager: api = L"SoundManager"; break; - case paCoreAudio: api = L"CoreAudio"; break; - case paOSS: api = L"OSS"; break; - case paALSA: api = L"ALSA"; break; - case paAL: api = L"AL"; break; - case paBeOS: api = L"BeOS"; break; - case paWDMKS: api = L"WDMKS"; break; - case paJACK: api = L"JACK"; break; - case paWASAPI: api = L"WASAPI"; break; - case paAudioScienceHPI: api = L"AudioScienceHPI"; break; - default: api = L"Unknown"; - } + void SetApiSettings(wxString api) + { + m_ApiId = -1; + if (api == L"InDevelopment") + m_ApiId = paInDevelopment; /* use while developing support for a new host API */ + if (api == L"DirectSound") + m_ApiId = paDirectSound; + if (api == L"MME") + m_ApiId = paMME; + if (api == L"ASIO") + m_ApiId = paASIO; + if (api == L"SoundManager") + m_ApiId = paSoundManager; + if (api == L"CoreAudio") + m_ApiId = paCoreAudio; + if (api == L"OSS") + m_ApiId = paOSS; + if (api == L"ALSA") + m_ApiId = paALSA; + if (api == L"AL") + m_ApiId = paAL; + if (api == L"BeOS") + m_ApiId = paBeOS; + if (api == L"WDMKS") + m_ApiId = paWDMKS; + if (api == L"JACK") + m_ApiId = paJACK; + if (api == L"WASAPI") + m_ApiId = paWASAPI; + if (api == L"AudioScienceHPI") + m_ApiId = paAudioScienceHPI; + } - CfgWriteStr( L"PORTAUDIO", L"HostApi", api); - CfgWriteStr( L"PORTAUDIO", L"Device", m_Device); + void WriteSettings() const + { + wxString api; + switch (m_ApiId) { + case paInDevelopment: + api = L"InDevelopment"; + break; /* use while developing support for a new host API */ + case paDirectSound: + api = L"DirectSound"; + break; + case paMME: + api = L"MME"; + break; + case paASIO: + api = L"ASIO"; + break; + case paSoundManager: + api = L"SoundManager"; + break; + case paCoreAudio: + api = L"CoreAudio"; + break; + case paOSS: + api = L"OSS"; + break; + case paALSA: + api = L"ALSA"; + break; + case paAL: + api = L"AL"; + break; + case paBeOS: + api = L"BeOS"; + break; + case paWDMKS: + api = L"WDMKS"; + break; + case paJACK: + api = L"JACK"; + break; + case paWASAPI: + api = L"WASAPI"; + break; + case paAudioScienceHPI: + api = L"AudioScienceHPI"; + break; + default: + api = L"Unknown"; + } - CfgWriteBool( L"PORTAUDIO", L"Wasapi_Exclusive_Mode", m_WasapiExclusiveMode); - CfgWriteBool( L"PORTAUDIO", L"Minimal_Suggested_Latency", m_SuggestedLatencyMinimal); - CfgWriteInt( L"PORTAUDIO", L"Manual_Suggested_Latency_MS", m_SuggestedLatencyMS); - } + CfgWriteStr(L"PORTAUDIO", L"HostApi", api); + CfgWriteStr(L"PORTAUDIO", L"Device", m_Device); + + CfgWriteBool(L"PORTAUDIO", L"Wasapi_Exclusive_Mode", m_WasapiExclusiveMode); + CfgWriteBool(L"PORTAUDIO", L"Minimal_Suggested_Latency", m_SuggestedLatencyMinimal); + CfgWriteInt(L"PORTAUDIO", L"Manual_Suggested_Latency_MS", m_SuggestedLatencyMS); + } } static PA; -int PaCallback( const void *inputBuffer, void *outputBuffer, - unsigned long framesPerBuffer, - const PaStreamCallbackTimeInfo* timeInfo, - PaStreamCallbackFlags statusFlags, - void *userData ) +int PaCallback(const void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + const PaStreamCallbackTimeInfo *timeInfo, + PaStreamCallbackFlags statusFlags, + void *userData) { - return PA.ActualPaCallback->ReadSamples(inputBuffer,outputBuffer,framesPerBuffer,timeInfo,statusFlags,userData); + return PA.ActualPaCallback->ReadSamples(inputBuffer, outputBuffer, framesPerBuffer, timeInfo, statusFlags, userData); } #ifdef _WIN32 -BOOL CALLBACK Portaudio::ConfigProc(HWND hWnd,UINT uMsg,WPARAM wParam,LPARAM lParam) +BOOL CALLBACK Portaudio::ConfigProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { - return PA._ConfigProc( hWnd, uMsg, wParam, lParam ); + return PA._ConfigProc(hWnd, uMsg, wParam, lParam); } #endif diff --git a/plugins/spu2-x/src/SndOut_SDL.cpp b/plugins/spu2-x/src/SndOut_SDL.cpp index 2645717ac4..60b21c4e19 100644 --- a/plugins/spu2-x/src/SndOut_SDL.cpp +++ b/plugins/spu2-x/src/SndOut_SDL.cpp @@ -29,152 +29,161 @@ #include typedef StereoOut16 StereoOut_SDL; -namespace { - /* Since spu2 only ever outputs stereo, we don't worry about emitting surround sound +namespace +{ +/* Since spu2 only ever outputs stereo, we don't worry about emitting surround sound * even though SDL2 supports it */ - const Uint8 channels = 2; - /* SDL2 supports s32 audio */ - /* Samples should vary from [512,8192] according to SDL spec. Take note this is the desired +const Uint8 channels = 2; +/* SDL2 supports s32 audio */ +/* Samples should vary from [512,8192] according to SDL spec. Take note this is the desired * sample count and SDL may provide otherwise. Pulseaudio will cut this value in half if * PA_STREAM_ADJUST_LATENCY is set in the backened, for example. */ - const Uint16 desiredSamples = 2048; - const Uint16 format = AUDIO_S16SYS; +const Uint16 desiredSamples = 2048; +const Uint16 format = AUDIO_S16SYS; - Uint16 samples = desiredSamples; +Uint16 samples = desiredSamples; - std::unique_ptr buffer; +std::unique_ptr buffer; - void callback_fillBuffer(void *userdata, Uint8 *stream, int len) { - Uint16 sdl_samples = samples; +void callback_fillBuffer(void *userdata, Uint8 *stream, int len) +{ + Uint16 sdl_samples = samples; #if SDL_MAJOR_VERSION >= 2 - memset(stream, 0, len); - // As of SDL 2.0.4 the buffer is too small to contains all samples - // len is 2048, samples is 1024 and sizeof(StereoOut_SDL) is 4 - sdl_samples = len / sizeof(StereoOut_SDL); + memset(stream, 0, len); + // As of SDL 2.0.4 the buffer is too small to contains all samples + // len is 2048, samples is 1024 and sizeof(StereoOut_SDL) is 4 + sdl_samples = len / sizeof(StereoOut_SDL); #endif - // Length should always be samples in bytes. - assert(len / sizeof(StereoOut_SDL) == sdl_samples); + // Length should always be samples in bytes. + assert(len / sizeof(StereoOut_SDL) == sdl_samples); - for(Uint16 i = 0; i < sdl_samples; i += SndOutPacketSize) - SndBuffer::ReadSamples(&buffer[i]); - SDL_MixAudio(stream, (Uint8*) buffer.get() , len, SDL_MIX_MAXVOLUME); - } + for (Uint16 i = 0; i < sdl_samples; i += SndOutPacketSize) + SndBuffer::ReadSamples(&buffer[i]); + SDL_MixAudio(stream, (Uint8 *)buffer.get(), len, SDL_MIX_MAXVOLUME); +} } -struct SDLAudioMod : public SndOutModule { - static SDLAudioMod mod; - std::string m_api; +struct SDLAudioMod : public SndOutModule +{ + static SDLAudioMod mod; + std::string m_api; - s32 Init() { - ReadSettings(); + s32 Init() + { + ReadSettings(); #if SDL_MAJOR_VERSION >= 2 - std::cerr << "Request SDL audio driver: " << m_api.c_str() << std::endl; + std::cerr << "Request SDL audio driver: " << m_api.c_str() << std::endl; #endif - /* SDL backends will mangle the AudioSpec and change the sample count. If we reopen + /* SDL backends will mangle the AudioSpec and change the sample count. If we reopen * the audio backend, we need to make sure we keep our desired samples in the spec */ - spec.samples = desiredSamples; + spec.samples = desiredSamples; - // Mandatory otherwise, init will be redone in SDL_OpenAudio - if (SDL_Init(SDL_INIT_AUDIO) < 0) { - std::cerr << "SPU2-X: SDL INIT audio error: " << SDL_GetError() << std::endl; - return -1; - } + // Mandatory otherwise, init will be redone in SDL_OpenAudio + if (SDL_Init(SDL_INIT_AUDIO) < 0) { + std::cerr << "SPU2-X: SDL INIT audio error: " << SDL_GetError() << std::endl; + return -1; + } #if SDL_MAJOR_VERSION >= 2 - if (m_api.compare("pulseaudio")) { - // Close the audio, but keep the subsystem open - SDL_AudioQuit(); - // Reopen the audio - if (SDL_AudioInit(m_api.c_str()) < 0) { - std::cerr << "SPU2-X: SDL audio init error: " << SDL_GetError() << std::endl; - return -1; - } - } + if (m_api.compare("pulseaudio")) { + // Close the audio, but keep the subsystem open + SDL_AudioQuit(); + // Reopen the audio + if (SDL_AudioInit(m_api.c_str()) < 0) { + std::cerr << "SPU2-X: SDL audio init error: " << SDL_GetError() << std::endl; + return -1; + } + } #endif - if (SDL_OpenAudio(&spec, NULL) < 0) { - std::cerr << "SPU2-X: SDL audio error: " << SDL_GetError() << std::endl; - return -1; - } + if (SDL_OpenAudio(&spec, NULL) < 0) { + std::cerr << "SPU2-X: SDL audio error: " << SDL_GetError() << std::endl; + return -1; + } #if SDL_MAJOR_VERSION >= 2 - std::cerr << "Opened SDL audio driver: " << SDL_GetCurrentAudioDriver() << std::endl; + std::cerr << "Opened SDL audio driver: " << SDL_GetCurrentAudioDriver() << std::endl; #endif - /* This is so ugly. It is hilariously ugly. I didn't use a vector to save reallocs. */ - if(samples != spec.samples || buffer == NULL) - buffer = std::unique_ptr(new StereoOut_SDL[spec.samples]); - if(samples != spec.samples) { - fprintf(stderr, "SPU2-X: SDL failed to get desired samples (%d) got %d samples instead\n", samples, spec.samples); + /* This is so ugly. It is hilariously ugly. I didn't use a vector to save reallocs. */ + if (samples != spec.samples || buffer == NULL) + buffer = std::unique_ptr(new StereoOut_SDL[spec.samples]); + if (samples != spec.samples) { + fprintf(stderr, "SPU2-X: SDL failed to get desired samples (%d) got %d samples instead\n", samples, spec.samples); - // Samples must always be a multiple of packet size. - assert(spec.samples % SndOutPacketSize == 0); - samples = spec.samples; - } - SDL_PauseAudio(0); - return 0; - } + // Samples must always be a multiple of packet size. + assert(spec.samples % SndOutPacketSize == 0); + samples = spec.samples; + } + SDL_PauseAudio(0); + return 0; + } - const wchar_t* GetIdent() const { return L"SDLAudio"; } - const wchar_t* GetLongName() const { return L"SDL Audio"; } + const wchar_t *GetIdent() const { return L"SDLAudio"; } + const wchar_t *GetLongName() const { return L"SDL Audio"; } - void Close() { - // Related to SDL_Init(SDL_INIT_AUDIO) - SDL_QuitSubSystem(SDL_INIT_AUDIO); - } + void Close() + { + // Related to SDL_Init(SDL_INIT_AUDIO) + SDL_QuitSubSystem(SDL_INIT_AUDIO); + } - ~SDLAudioMod() { Close(); } + ~SDLAudioMod() { Close(); } - s32 Test() const { return 0; } - int GetEmptySampleCount() { return 0; } + s32 Test() const { return 0; } + int GetEmptySampleCount() { return 0; } - void Configure(uptr parent) {} + void Configure(uptr parent) {} - void ReadSettings() { - wxString api(L"EMPTYEMPTYEMPTY"); - CfgReadStr(L"SDL", L"HostApi", api, L"pulseaudio"); - SetApiSettings(api); - } + void ReadSettings() + { + wxString api(L"EMPTYEMPTYEMPTY"); + CfgReadStr(L"SDL", L"HostApi", api, L"pulseaudio"); + SetApiSettings(api); + } - void WriteSettings() const { - CfgWriteStr(L"SDL", L"HostApi", wxString(m_api.c_str(), wxConvUTF8)); - }; + void WriteSettings() const + { + CfgWriteStr(L"SDL", L"HostApi", wxString(m_api.c_str(), wxConvUTF8)); + }; - void SetApiSettings(wxString api) { + void SetApiSettings(wxString api) + { #if SDL_MAJOR_VERSION >= 2 - // Validate the api name - bool valid = false; - std::string api_name = std::string(api.utf8_str()); - for (int i = 0; i < SDL_GetNumAudioDrivers(); ++i) { - valid |= (api_name.compare(SDL_GetAudioDriver(i)) == 0); - } - if (valid) { - m_api = api.utf8_str(); - } else { - std::cerr << "SDL audio driver configuration is invalid!" << std::endl - << "It will be replaced by pulseaudio!" << std::endl; - m_api = "pulseaudio"; - } + // Validate the api name + bool valid = false; + std::string api_name = std::string(api.utf8_str()); + for (int i = 0; i < SDL_GetNumAudioDrivers(); ++i) { + valid |= (api_name.compare(SDL_GetAudioDriver(i)) == 0); + } + if (valid) { + m_api = api.utf8_str(); + } else { + std::cerr << "SDL audio driver configuration is invalid!" << std::endl + << "It will be replaced by pulseaudio!" << std::endl; + m_api = "pulseaudio"; + } #endif - } + } - private: - SDL_AudioSpec spec; +private: + SDL_AudioSpec spec; - SDLAudioMod() : m_api("pulseaudio"), - spec({SampleRate, format, channels, 0, - desiredSamples, 0, 0, &callback_fillBuffer, nullptr}) - { - // Number of samples must be a multiple of packet size. - assert(samples % SndOutPacketSize == 0); - } + SDLAudioMod() + : m_api("pulseaudio") + , spec({SampleRate, format, channels, 0, + desiredSamples, 0, 0, &callback_fillBuffer, nullptr}) + { + // Number of samples must be a multiple of packet size. + assert(samples % SndOutPacketSize == 0); + } }; SDLAudioMod SDLAudioMod::mod; -SndOutModule * const SDLOut = &SDLAudioMod::mod; +SndOutModule *const SDLOut = &SDLAudioMod::mod; diff --git a/plugins/spu2-x/src/Spu2replay.cpp b/plugins/spu2-x/src/Spu2replay.cpp index 03c698fb5c..76a5ec312a 100644 --- a/plugins/spu2-x/src/Spu2replay.cpp +++ b/plugins/spu2-x/src/Spu2replay.cpp @@ -20,73 +20,78 @@ #include "PS2E-spu2.h" #ifdef _MSC_VER -# include "Windows.h" +#include "Windows.h" #endif -FILE* s2rfile; +FILE *s2rfile; void s2r_write16(s16 data) { - fwrite(&data,2,1,s2rfile); + fwrite(&data, 2, 1, s2rfile); } void s2r_write32(u32 data) { - fwrite(&data,4,1,s2rfile); + fwrite(&data, 4, 1, s2rfile); } static void EMITC(u32 i, u32 a) { - s2r_write32(((i&0x7u)<<29u)|(a&0x1FFFFFFFu)); + s2r_write32(((i & 0x7u) << 29u) | (a & 0x1FFFFFFFu)); } int s2r_open(u32 ticks, char *filename) { - s2rfile=fopen(filename,"wb"); - if(s2rfile) - s2r_write32(ticks); - return s2rfile?0:-1; + s2rfile = fopen(filename, "wb"); + if (s2rfile) + s2r_write32(ticks); + return s2rfile ? 0 : -1; } -void s2r_readreg(u32 ticks,u32 addr) +void s2r_readreg(u32 ticks, u32 addr) { - if(!s2rfile) return; - s2r_write32(ticks); - EMITC(0,addr); + if (!s2rfile) + return; + s2r_write32(ticks); + EMITC(0, addr); } -void s2r_writereg(u32 ticks,u32 addr,s16 value) +void s2r_writereg(u32 ticks, u32 addr, s16 value) { - if(!s2rfile) return; - s2r_write32(ticks); - EMITC(1,addr); - s2r_write16(value); + if (!s2rfile) + return; + s2r_write32(ticks); + EMITC(1, addr); + s2r_write16(value); } -void s2r_writedma4(u32 ticks,u16*data,u32 len) +void s2r_writedma4(u32 ticks, u16 *data, u32 len) { - u32 i; - if(!s2rfile) return; - s2r_write32(ticks); - EMITC(2,len); - for(i=0;i 10) - WaitTime = 10; - if(WaitTime == 0) - WaitTime = 1; - SleepEx(WaitTime, TRUE); + u32 WaitCycles = (TargetCycle - CurrentIOPCycle); + u32 WaitTime = WaitCycles / IOPCiclesPerMS; + if (WaitTime > 10) + WaitTime = 10; + if (WaitTime == 0) + WaitTime = 1; + SleepEx(WaitTime, TRUE); - // Refresh current time after sleeping - u64 Current = HighResCounter(); - u32 delta = (u32)floor((Current-HighResPrev) / HighResScale + 0.5); // We lose some precision here, cycles might drift away over long periods of time ;P + // Refresh current time after sleeping + u64 Current = HighResCounter(); + u32 delta = (u32)floor((Current - HighResPrev) / HighResScale + 0.5); // We lose some precision here, cycles might drift away over long periods of time ;P - // Calculate time delta - CurrentIOPCycle += delta; - HighResPrev += (u64)floor(delta * HighResScale + 0.5); // Trying to compensate drifting mentioned above, not necessarily useful. + // Calculate time delta + CurrentIOPCycle += delta; + HighResPrev += (u64)floor(delta * HighResScale + 0.5); // Trying to compensate drifting mentioned above, not necessarily useful. - return delta; + return delta; } #ifdef _WIN32 BOOL WINAPI HandlerRoutine(DWORD dwCtrlType) { - Running = false; - return TRUE; + Running = false; + return TRUE; } #endif #include "Windows/Dialogs.h" -EXPORT_C_(void) s2r_replay(HWND hwnd, HINSTANCE hinst, LPSTR filename, int nCmdShow) +EXPORT_C_(void) +s2r_replay(HWND hwnd, HINSTANCE hinst, LPSTR filename, int nCmdShow) { #ifndef ENABLE_NEW_IOPDMA_SPU2 - int events=0; + int events = 0; - Running = true; + Running = true; #ifdef _WIN32 - AllocConsole(); - SetConsoleCtrlHandler(HandlerRoutine, TRUE); - - conprintf("Playing %s file on %x...",filename,hwnd); + AllocConsole(); + SetConsoleCtrlHandler(HandlerRoutine, TRUE); - if (IsWindows8OrGreater()) - { - for (int n = 0; mods[n] != nullptr; ++n) - { - if (mods[n] == XAudio2_27_Out) - { - mods[n] = XAudio2Out; - break; - } - } - } + conprintf("Playing %s file on %x...", filename, hwnd); + + if (IsWindows8OrGreater()) { + for (int n = 0; mods[n] != nullptr; ++n) { + if (mods[n] == XAudio2_27_Out) { + mods[n] = XAudio2Out; + break; + } + } + } #endif - // load file - FILE *file=fopen(filename,"rb"); + // load file + FILE *file = fopen(filename, "rb"); - if(!file) - { - conprintf("Could not open the replay file."); - return; - } - // if successful, init the plugin + if (!file) { + conprintf("Could not open the replay file."); + return; + } +// if successful, init the plugin -#define TryRead(dest,size,count,file) if(fread(dest,size,count,file)>29; - sval&=0x1FFFFFFF; + TryRead(&ccycle, 4, 1, file); + TryRead(&sval, 4, 1, file); - u32 TargetCycle = ccycle * 768; + evid = sval >> 29; + sval &= 0x1FFFFFFF; - while(TargetCycle > CurrentIOPCycle) - { - u32 delta = WaitSync(TargetCycle); - SPU2async(delta); - } - - switch(evid) - { - case 0: - SPU2read(sval); - break; - case 1: - TryRead(&tval,2,1,file); - SPU2write(sval,tval); - break; - case 2: - TryRead(dmabuffer,sval,2,file); - SPU2writeDMA4Mem(dmabuffer,sval); - break; - case 3: - TryRead(dmabuffer,sval,2,file); - SPU2writeDMA7Mem(dmabuffer,sval); - break; - default: - // not implemented - return; - break; - } - events++; - } + u32 TargetCycle = ccycle * 768; + + while (TargetCycle > CurrentIOPCycle) { + u32 delta = WaitSync(TargetCycle); + SPU2async(delta); + } + + switch (evid) { + case 0: + SPU2read(sval); + break; + case 1: + TryRead(&tval, 2, 1, file); + SPU2write(sval, tval); + break; + case 2: + TryRead(dmabuffer, sval, 2, file); + SPU2writeDMA4Mem(dmabuffer, sval); + break; + case 3: + TryRead(dmabuffer, sval, 2, file); + SPU2writeDMA7Mem(dmabuffer, sval); + break; + default: + // not implemented + return; + break; + } + events++; + } Finish: - //shutdown - SPU2close(); - SPU2shutdown(); - fclose(file); + //shutdown + SPU2close(); + SPU2shutdown(); + fclose(file); - conprintf("Finished playing %s file (%d cycles, %d events).",filename,CurrentIOPCycle,events); + conprintf("Finished playing %s file (%d cycles, %d events).", filename, CurrentIOPCycle, events); #ifdef _WIN32 - FreeConsole(); + FreeConsole(); #endif - replay_mode=false; + replay_mode = false; #endif } #endif diff --git a/plugins/spu2-x/src/Spu2replay.h b/plugins/spu2-x/src/Spu2replay.h index dff6b3c694..af62856c9e 100644 --- a/plugins/spu2-x/src/Spu2replay.h +++ b/plugins/spu2-x/src/Spu2replay.h @@ -22,10 +22,10 @@ // s2r dumping int s2r_open(u32 ticks, char *filename); -void s2r_readreg(u32 ticks,u32 addr); -void s2r_writereg(u32 ticks,u32 addr,s16 value); -void s2r_writedma4(u32 ticks,u16*data,u32 len); -void s2r_writedma7(u32 ticks,u16*data,u32 len); +void s2r_readreg(u32 ticks, u32 addr); +void s2r_writereg(u32 ticks, u32 addr, s16 value); +void s2r_writedma4(u32 ticks, u16 *data, u32 len); +void s2r_writedma7(u32 ticks, u16 *data, u32 len); void s2r_close(); extern bool replay_mode; diff --git a/plugins/spu2-x/src/Timestretcher.cpp b/plugins/spu2-x/src/Timestretcher.cpp index 0b912735c0..1035e3b3cf 100644 --- a/plugins/spu2-x/src/Timestretcher.cpp +++ b/plugins/spu2-x/src/Timestretcher.cpp @@ -23,7 +23,7 @@ //Uncomment the next line to use the old time stretcher //#define SPU2X_USE_OLD_STRETCHER -static soundtouch::SoundTouch* pSoundTouch = NULL; +static soundtouch::SoundTouch *pSoundTouch = NULL; // data prediction amount, used to "commit" data that hasn't // finished timestretch processing. @@ -36,9 +36,9 @@ float SndBuffer::lastEmergencyAdj; float SndBuffer::cTempo = 1; float SndBuffer::eTempo = 1; -void SndBuffer::PredictDataWrite( int samples ) +void SndBuffer::PredictDataWrite(int samples) { - m_predictData += samples; + m_predictData += samples; } // Calculate the buffer status percentage. @@ -48,17 +48,17 @@ void SndBuffer::PredictDataWrite( int samples ) // -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. + // Get the buffer status of the output driver too, so that we can + // obtain a more accurate overall buffer status. - int drvempty = mods[OutputModule]->GetEmptySampleCount(); // / 2; + int drvempty = mods[OutputModule]->GetEmptySampleCount(); // / 2; - //ConLog( "Data %d >>> driver: %d predict: %d\n", m_data, drvempty, m_predictData ); + //ConLog( "Data %d >>> driver: %d predict: %d\n", m_data, drvempty, m_predictData ); - int data = _GetApproximateDataInBuffer(); - float result = (float)( data + m_predictData - drvempty) - (m_size/16); - result /= (m_size/16); - return result; + int data = _GetApproximateDataInBuffer(); + float result = (float)(data + m_predictData - drvempty) - (m_size / 16); + result /= (m_size / 16); + return result; } @@ -87,7 +87,7 @@ float SndBuffer::GetStatusPct() // These params were tested to show good respond and stability, on all audio systems (dsound, wav, port audio, xaudio2), // even at extreme small latency of 50ms which can handle 50%-100% variations without audible glitches. -int targetIPS=750; +int targetIPS = 750; //Dynamic tuning changes the values of the base algorithm parameters (derived from targetIPS) to adapt, in real time, to // different number of invocations/sec (mostly affects number of iterations to average). @@ -99,277 +99,277 @@ int targetIPS=750; //#define NEWSTRETCHER_USE_DYNAMIC_TUNING -//Additional performance note: since MAX_STRETCH_AVERAGE_LEN = 128 (or any power of 2), the '%' below +//Additional performance note: since MAX_STRETCH_AVERAGE_LEN = 128 (or any power of 2), the '%' below //could be replaced with a faster '&'. The compiler is highly likely to do it since all the values are unsigned. #define AVERAGING_BUFFER_SIZE 256U -unsigned int AVERAGING_WINDOW = 50.0 * targetIPS/750; +unsigned int AVERAGING_WINDOW = 50.0 * targetIPS / 750; #define STRETCHER_RESET_THRESHOLD 5 int gRequestStretcherReset = STRETCHER_RESET_THRESHOLD; //Adds a value to the running average buffer, and return the new running average. -float addToAvg(float val){ - static float avg_fullness[AVERAGING_BUFFER_SIZE]; - static unsigned int nextAvgPos = 0; - static unsigned int available = 0; // Make sure we're not averaging AVERAGING_WINDOW items if we inserted less. - if (gRequestStretcherReset >= STRETCHER_RESET_THRESHOLD) - available = 0; +float addToAvg(float val) +{ + static float avg_fullness[AVERAGING_BUFFER_SIZE]; + static unsigned int nextAvgPos = 0; + static unsigned int available = 0; // Make sure we're not averaging AVERAGING_WINDOW items if we inserted less. + if (gRequestStretcherReset >= STRETCHER_RESET_THRESHOLD) + available = 0; - if (available < AVERAGING_BUFFER_SIZE) - available++; + if (available < AVERAGING_BUFFER_SIZE) + available++; - avg_fullness[nextAvgPos] = val; - nextAvgPos = (nextAvgPos + 1U) % AVERAGING_BUFFER_SIZE; - - unsigned int actualWindow = std::min(available, AVERAGING_WINDOW); - unsigned int first = (nextAvgPos - actualWindow + AVERAGING_BUFFER_SIZE) - % AVERAGING_BUFFER_SIZE; + avg_fullness[nextAvgPos] = val; + nextAvgPos = (nextAvgPos + 1U) % AVERAGING_BUFFER_SIZE; - // Possible optimization: if we know that actualWindow hasn't changed since - // last invocation, we could calculate the running average in O(1) instead of O(N) - // by keeping a running sum between invocations, and then - // do "runningSum = runningSum + val - avg_fullness[(first-1)%...]" instead of the following loop. - // Few gotchas: val overwrites first-1, handling actualWindow changes, etc. - // However, this isn't hot code, so unless proven otherwise, we can live with unoptimized code. - float sum = 0; - for(unsigned int i = first; i < first + actualWindow; i++) { - sum += avg_fullness[i % AVERAGING_BUFFER_SIZE]; - } - sum = sum / actualWindow; + unsigned int actualWindow = std::min(available, AVERAGING_WINDOW); + unsigned int first = (nextAvgPos - actualWindow + AVERAGING_BUFFER_SIZE) % AVERAGING_BUFFER_SIZE; - return sum ? sum : 1; // 1 because that's the 100% perfect speed value + // Possible optimization: if we know that actualWindow hasn't changed since + // last invocation, we could calculate the running average in O(1) instead of O(N) + // by keeping a running sum between invocations, and then + // do "runningSum = runningSum + val - avg_fullness[(first-1)%...]" instead of the following loop. + // Few gotchas: val overwrites first-1, handling actualWindow changes, etc. + // However, this isn't hot code, so unless proven otherwise, we can live with unoptimized code. + float sum = 0; + for (unsigned int i = first; i < first + actualWindow; i++) { + sum += avg_fullness[i % AVERAGING_BUFFER_SIZE]; + } + sum = sum / actualWindow; + + return sum ? sum : 1; // 1 because that's the 100% perfect speed value } template -bool IsInRange(const T& val, const T& min, const T& max) +bool IsInRange(const T &val, const T &min, const T &max) { - return ( min <= val && val <= max ); + return (min <= val && val <= max); } //actual stretch algorithm implementation void SndBuffer::UpdateTempoChangeSoundTouch2() { - long targetSamplesReservoir=48*SndOutLatencyMS;//48000*SndOutLatencyMS/1000 - //base aim at buffer filled % - float baseTargetFullness=(double)targetSamplesReservoir;///(double)m_size;//0.05; + long targetSamplesReservoir = 48 * SndOutLatencyMS; //48000*SndOutLatencyMS/1000 + //base aim at buffer filled % + float baseTargetFullness = (double)targetSamplesReservoir; ///(double)m_size;//0.05; - //state vars - static bool inside_hysteresis;//=false; - static int hys_ok_count;//=0; - static float dynamicTargetFullness;//=baseTargetFullness; - if (gRequestStretcherReset >= STRETCHER_RESET_THRESHOLD) { - ConLog("______> stretch: Reset.\n"); - inside_hysteresis=false; - hys_ok_count=0; - dynamicTargetFullness=baseTargetFullness; - } + //state vars + static bool inside_hysteresis; //=false; + static int hys_ok_count; //=0; + static float dynamicTargetFullness; //=baseTargetFullness; + if (gRequestStretcherReset >= STRETCHER_RESET_THRESHOLD) { + ConLog("______> stretch: Reset.\n"); + inside_hysteresis = false; + hys_ok_count = 0; + dynamicTargetFullness = baseTargetFullness; + } - int data = _GetApproximateDataInBuffer(); - float bufferFullness=(float)data;///(float)m_size; + int data = _GetApproximateDataInBuffer(); + float bufferFullness = (float)data; ///(float)m_size; #ifdef NEWSTRETCHER_USE_DYNAMIC_TUNING - {//test current iterations/sec every 0.5s, and change algo params accordingly if different than previous IPS more than 30% - static long iters=0; - static wxDateTime last=wxDateTime::UNow(); - wxDateTime unow=wxDateTime::UNow(); - wxTimeSpan delta = unow.Subtract(last); - if( delta.GetMilliseconds()>500 ){ - int pot_targetIPS=1000.0/delta.GetMilliseconds().ToDouble()*iters; - if(!IsInRange(pot_targetIPS, int((float)targetIPS/1.3f), int((float)targetIPS*1.3f)) ){ - if(MsgOverruns()) ConLog("Stretcher: setting iters/sec from %d to %d\n", targetIPS, pot_targetIPS); - targetIPS=pot_targetIPS; - AVERAGING_WINDOW=GetClamped((int)(50.0f *(float)targetIPS/750.0f), 3, (int)AVERAGING_BUFFER_SIZE); - } - last=unow; - iters=0; - } - iters++; - } + { //test current iterations/sec every 0.5s, and change algo params accordingly if different than previous IPS more than 30% + static long iters = 0; + static wxDateTime last = wxDateTime::UNow(); + wxDateTime unow = wxDateTime::UNow(); + wxTimeSpan delta = unow.Subtract(last); + if (delta.GetMilliseconds() > 500) { + int pot_targetIPS = 1000.0 / delta.GetMilliseconds().ToDouble() * iters; + if (!IsInRange(pot_targetIPS, int((float)targetIPS / 1.3f), int((float)targetIPS * 1.3f))) { + if (MsgOverruns()) + ConLog("Stretcher: setting iters/sec from %d to %d\n", targetIPS, pot_targetIPS); + targetIPS = pot_targetIPS; + AVERAGING_WINDOW = GetClamped((int)(50.0f * (float)targetIPS / 750.0f), 3, (int)AVERAGING_BUFFER_SIZE); + } + last = unow; + iters = 0; + } + iters++; + } #endif - //Algorithm params: (threshold params (hysteresis), etc) - const float hys_ok_factor = 1.04f; - const float hys_bad_factor = 1.2f; - int hys_min_ok_count = GetClamped((int)(50.0 *(float)targetIPS/750.0), 2, 100); //consecutive iterations within hys_ok before going to 1:1 mode - int compensationDivider = GetClamped((int)(100.0 *(float)targetIPS/750), 15, 150); + //Algorithm params: (threshold params (hysteresis), etc) + const float hys_ok_factor = 1.04f; + const float hys_bad_factor = 1.2f; + int hys_min_ok_count = GetClamped((int)(50.0 * (float)targetIPS / 750.0), 2, 100); //consecutive iterations within hys_ok before going to 1:1 mode + int compensationDivider = GetClamped((int)(100.0 * (float)targetIPS / 750), 15, 150); - float tempoAdjust=bufferFullness/dynamicTargetFullness; - float avgerage = addToAvg(tempoAdjust); - tempoAdjust = avgerage; + float tempoAdjust = bufferFullness / dynamicTargetFullness; + float avgerage = addToAvg(tempoAdjust); + tempoAdjust = avgerage; - // Dampen the adjustment to avoid overshoots (this means the average will compensate to the other side). - // This is different than simply bigger averaging window since bigger window also has bigger "momentum", - // so it's slower to slow down when it gets close to the equilibrium state and can therefore resonate. - // The dampening (sqrt was chosen for no very good reason) manages to mostly prevent that. - tempoAdjust = sqrt(tempoAdjust); + // Dampen the adjustment to avoid overshoots (this means the average will compensate to the other side). + // This is different than simply bigger averaging window since bigger window also has bigger "momentum", + // so it's slower to slow down when it gets close to the equilibrium state and can therefore resonate. + // The dampening (sqrt was chosen for no very good reason) manages to mostly prevent that. + tempoAdjust = sqrt(tempoAdjust); - tempoAdjust = GetClamped( tempoAdjust, 0.05f, 10.0f); - - if (tempoAdjust < 1) - baseTargetFullness /= sqrt(tempoAdjust); // slightly increase latency when running slow. - - dynamicTargetFullness += (baseTargetFullness/tempoAdjust - dynamicTargetFullness)/(double)compensationDivider; - if( IsInRange(tempoAdjust, 0.9f, 1.1f) && IsInRange( dynamicTargetFullness, baseTargetFullness*0.9f, baseTargetFullness*1.1f) ) - dynamicTargetFullness=baseTargetFullness; + tempoAdjust = GetClamped(tempoAdjust, 0.05f, 10.0f); - if( !inside_hysteresis ) - { - if( IsInRange( tempoAdjust, 1.0f/hys_ok_factor, hys_ok_factor ) ) - hys_ok_count++; - else - hys_ok_count=0; + if (tempoAdjust < 1) + baseTargetFullness /= sqrt(tempoAdjust); // slightly increase latency when running slow. - if( hys_ok_count >= hys_min_ok_count ){ - inside_hysteresis=true; - if(MsgOverruns()) ConLog("======> stretch: None (1:1)\n"); - } + dynamicTargetFullness += (baseTargetFullness / tempoAdjust - dynamicTargetFullness) / (double)compensationDivider; + if (IsInRange(tempoAdjust, 0.9f, 1.1f) && IsInRange(dynamicTargetFullness, baseTargetFullness * 0.9f, baseTargetFullness * 1.1f)) + dynamicTargetFullness = baseTargetFullness; - } - else if( !IsInRange( tempoAdjust, 1.0f/hys_bad_factor, hys_bad_factor ) ){ - if(MsgOverruns()) ConLog("~~~~~~> stretch: Dynamic\n"); - inside_hysteresis=false; - hys_ok_count=0; - } + if (!inside_hysteresis) { + if (IsInRange(tempoAdjust, 1.0f / hys_ok_factor, hys_ok_factor)) + hys_ok_count++; + else + hys_ok_count = 0; - if(inside_hysteresis) - tempoAdjust=1.0; + if (hys_ok_count >= hys_min_ok_count) { + inside_hysteresis = true; + if (MsgOverruns()) + ConLog("======> stretch: None (1:1)\n"); + } - if(MsgOverruns()){ - static int iters=0; - static wxDateTime last=wxDateTime::UNow(); - wxDateTime unow=wxDateTime::UNow(); - wxTimeSpan delta = unow.Subtract(last); + } else if (!IsInRange(tempoAdjust, 1.0f / hys_bad_factor, hys_bad_factor)) { + if (MsgOverruns()) + ConLog("~~~~~~> stretch: Dynamic\n"); + inside_hysteresis = false; + hys_ok_count = 0; + } - if(delta.GetMilliseconds()>1000){//report buffers state and tempo adjust every second - ConLog("buffers: %4d ms (%3.0f%%), tempo: %f, comp: %2.3f, iters: %d, (N-IPS:%d -> avg:%d, minokc:%d, div:%d) reset:%d\n", - (int)(data/48), (double)(100.0*bufferFullness/baseTargetFullness), (double)tempoAdjust, (double)(dynamicTargetFullness/baseTargetFullness), iters, (int)targetIPS - , AVERAGING_WINDOW, hys_min_ok_count, compensationDivider, gRequestStretcherReset - ); - last=unow; - iters=0; - } - iters++; - } + if (inside_hysteresis) + tempoAdjust = 1.0; - pSoundTouch->setTempo(tempoAdjust); - if (gRequestStretcherReset >= STRETCHER_RESET_THRESHOLD) - gRequestStretcherReset = 0; + if (MsgOverruns()) { + static int iters = 0; + static wxDateTime last = wxDateTime::UNow(); + wxDateTime unow = wxDateTime::UNow(); + wxTimeSpan delta = unow.Subtract(last); - return; + if (delta.GetMilliseconds() > 1000) { //report buffers state and tempo adjust every second + ConLog("buffers: %4d ms (%3.0f%%), tempo: %f, comp: %2.3f, iters: %d, (N-IPS:%d -> avg:%d, minokc:%d, div:%d) reset:%d\n", + (int)(data / 48), (double)(100.0 * bufferFullness / baseTargetFullness), (double)tempoAdjust, (double)(dynamicTargetFullness / baseTargetFullness), iters, (int)targetIPS, AVERAGING_WINDOW, hys_min_ok_count, compensationDivider, gRequestStretcherReset); + last = unow; + iters = 0; + } + iters++; + } + + pSoundTouch->setTempo(tempoAdjust); + if (gRequestStretcherReset >= STRETCHER_RESET_THRESHOLD) + gRequestStretcherReset = 0; + + return; } void SndBuffer::UpdateTempoChangeSoundTouch() { - float statusPct = GetStatusPct(); - float pctChange = statusPct - lastPct; + float statusPct = GetStatusPct(); + float pctChange = statusPct - lastPct; - float tempoChange; - float emergencyAdj = 0; - float newcee = cTempo; // workspace var. for cTempo + 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. + // 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. + // 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) + // Prediction based on the buffer change: + // (linear seems to work better here) - tempoChange = pctChange * 0.75f; + 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. + 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; - } + 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) + // 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). + // 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. + // 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: + // Prediction based on the buffer fill status: - const float statusWeight = 2.99f; - const float statusRange = 0.068f; + const float statusWeight = 2.99f; + const 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. + // "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.42f || statusPct > 0.70f || - eTempo < 0.89f || eTempo > 1.19f ) - { - //printf("Emergency stretch: cTempo = %f eTempo = %f pctChange = %f statusPct = %f\n",cTempo,eTempo,pctChange,statusPct); - emergencyAdj = ( pow( statusPct*statusWeight, 3.0f ) * statusRange); - } + if (cTempo < 0.965f || cTempo > 1.060f || + pctChange < -0.38f || pctChange > 0.54f || + statusPct < -0.42f || statusPct > 0.70f || + eTempo < 0.89f || eTempo > 1.19f) { + //printf("Emergency stretch: cTempo = %f eTempo = %f pctChange = %f statusPct = %f\n",cTempo,eTempo,pctChange,statusPct); + emergencyAdj = (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: + // 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 ); + emergencyAdj = (emergencyAdj * 0.75f) + (lastEmergencyAdj * 0.25f); - lastEmergencyAdj = emergencyAdj; - lastPct = statusPct; + 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). + // 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; + 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) + // 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 ); + 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 = (float)newcee; + // ... 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 = (float)newcee; - if( newTempo < 0.10f ) newTempo = 0.10f; - else if( newTempo > 10.0f ) newTempo = 10.0f; + 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; + if (cTempo < 0.15f) + cTempo = 0.15f; + else if (cTempo > 7.5f) + cTempo = 7.5f; - pSoundTouch->setTempo( eTempo = (float)newTempo ); + pSoundTouch->setTempo(eTempo = (float)newTempo); - /*ConLog("* SPU2-X: [Nominal %d%%] [Emergency: %d%%] (baseTempo: %d%% ) (newTempo: %d%%) (buffer: %d%%)\n", + /*ConLog("* SPU2-X: [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), @@ -377,168 +377,164 @@ void SndBuffer::UpdateTempoChangeSoundTouch() (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( cTempo != 1.0f ) - { - cTempo = 1.0f; - eTempo = ( 1.0f + eTempo ) * 0.5f; - pSoundTouch->setTempo( eTempo ); - } - else - { - if( eTempo != cTempo ) - pSoundTouch->setTempo( eTempo=cTempo ); - } - } + } else { + // Nominal operation -- turn off stretching. + // note: eTempo 'slides' toward 1.0 for smoother audio and better + // protection against spikes. + if (cTempo != 1.0f) { + cTempo = 1.0f; + eTempo = (1.0f + eTempo) * 0.5f; + pSoundTouch->setTempo(eTempo); + } else { + if (eTempo != cTempo) + pSoundTouch->setTempo(eTempo = cTempo); + } + } } extern uint TickInterval; void SndBuffer::UpdateTempoChangeAsyncMixing() { - float statusPct = GetStatusPct(); + float statusPct = GetStatusPct(); - lastPct = statusPct; - if( statusPct < -0.1f ) - { - TickInterval -= 4; - if( statusPct < -0.3f ) TickInterval = 64; - if( TickInterval < 64 ) TickInterval = 64; - //printf("-- %d, %f\n",TickInterval,statusPct); - } - else if( statusPct > 0.2f ) - { - TickInterval += 1; - if( TickInterval >= 7000 ) TickInterval = 7000; - //printf("++ %d, %f\n",TickInterval,statusPct); - } - else TickInterval = 768; + lastPct = statusPct; + if (statusPct < -0.1f) { + TickInterval -= 4; + if (statusPct < -0.3f) + TickInterval = 64; + if (TickInterval < 64) + TickInterval = 64; + //printf("-- %d, %f\n",TickInterval,statusPct); + } else if (statusPct > 0.2f) { + TickInterval += 1; + if (TickInterval >= 7000) + TickInterval = 7000; + //printf("++ %d, %f\n",TickInterval,statusPct); + } else + TickInterval = 768; } void SndBuffer::timeStretchUnderrun() { - gRequestStretcherReset++; - // timeStretcher failed it's job. We need to slow down the audio some. + gRequestStretcherReset++; + // 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 ); - //pSoundTouch->setTempoChange(-30); // temporary (until stretcher is called) slow down + cTempo -= (cTempo * 0.12f); + eTempo -= (eTempo * 0.30f); + if (eTempo < 0.1f) + eTempo = 0.1f; + // pSoundTouch->setTempo( eTempo ); + //pSoundTouch->setTempoChange(-30); // temporary (until stretcher is called) slow down } s32 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 ); - //pSoundTouch->setTempoChange(30);// temporary (until stretcher is called) speed up + // 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 ); + //pSoundTouch->setTempoChange(30);// temporary (until stretcher is called) speed up - // Throw out just a little bit (two packets worth) to help - // give the TS some room to work: - gRequestStretcherReset++; - return SndOutPacketSize*2; + // Throw out just a little bit (two packets worth) to help + // give the TS some room to work: + gRequestStretcherReset++; + return SndOutPacketSize * 2; } -static void CvtPacketToFloat( StereoOut32* srcdest ) +static void CvtPacketToFloat(StereoOut32 *srcdest) { - StereoOutFloat* dest = (StereoOutFloat*)srcdest; - const StereoOut32* src = (StereoOut32*)srcdest; - for( uint i=0; iputSamples( (float*)sndTempBuffer, SndOutPacketSize ); + pSoundTouch->putSamples((float *)sndTempBuffer, SndOutPacketSize); - int tempProgress; - while( tempProgress = pSoundTouch->receiveSamples( (float*)sndTempBuffer, SndOutPacketSize), - tempProgress != 0 ) - { - // 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. + int tempProgress; + while (tempProgress = pSoundTouch->receiveSamples((float *)sndTempBuffer, SndOutPacketSize), + tempProgress != 0) { + // 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, tempProgress ); - _WriteSamples( sndTempBuffer, tempProgress ); - } + CvtPacketToInt(sndTempBuffer, tempProgress); + _WriteSamples(sndTempBuffer, tempProgress); + } #ifdef SPU2X_USE_OLD_STRETCHER - UpdateTempoChangeSoundTouch(); + UpdateTempoChangeSoundTouch(); #else - UpdateTempoChangeSoundTouch2(); + UpdateTempoChangeSoundTouch2(); #endif - } void SndBuffer::soundtouchInit() { - pSoundTouch = new soundtouch::SoundTouch(); - pSoundTouch->setSampleRate(SampleRate); - pSoundTouch->setChannels(2); + pSoundTouch = new soundtouch::SoundTouch(); + pSoundTouch->setSampleRate(SampleRate); + pSoundTouch->setChannels(2); - pSoundTouch->setSetting( SETTING_USE_QUICKSEEK, 0 ); - pSoundTouch->setSetting( SETTING_USE_AA_FILTER, 0 ); + pSoundTouch->setSetting(SETTING_USE_QUICKSEEK, 0); + pSoundTouch->setSetting(SETTING_USE_AA_FILTER, 0); - SoundtouchCfg::ApplySettings( *pSoundTouch ); + SoundtouchCfg::ApplySettings(*pSoundTouch); - pSoundTouch->setTempo(1); + pSoundTouch->setTempo(1); - // some timestretch management vars: + // some timestretch management vars: - cTempo = 1.0; - eTempo = 1.0; - lastPct = 0; - lastEmergencyAdj = 0; + cTempo = 1.0; + eTempo = 1.0; + lastPct = 0; + lastEmergencyAdj = 0; - m_predictData = 0; + m_predictData = 0; } // reset timestretch management vars, and delay updates a bit: void SndBuffer::soundtouchClearContents() { - if( pSoundTouch == NULL ) return; + if (pSoundTouch == NULL) + return; - pSoundTouch->clear(); - pSoundTouch->setTempo(1); + pSoundTouch->clear(); + pSoundTouch->setTempo(1); - cTempo = 1.0; - eTempo = 1.0; - lastPct = 0; - lastEmergencyAdj = 0; + cTempo = 1.0; + eTempo = 1.0; + lastPct = 0; + lastEmergencyAdj = 0; - m_predictData = 0; + m_predictData = 0; } void SndBuffer::soundtouchCleanup() { - safe_delete( pSoundTouch ); + safe_delete(pSoundTouch); } diff --git a/plugins/spu2-x/src/WavFile.cpp b/plugins/spu2-x/src/WavFile.cpp index d44e58d4a7..dfaf6db9b4 100644 --- a/plugins/spu2-x/src/WavFile.cpp +++ b/plugins/spu2-x/src/WavFile.cpp @@ -16,7 +16,7 @@ * along with SPU2-X. If not, see . */ -// Note the file is mostly a copy paste of the WavFile.h from SoundTouch library. It was +// Note the file is mostly a copy paste of the WavFile.h from SoundTouch library. It was // shrunken to support only output 16 bits wav files #include @@ -32,7 +32,7 @@ using namespace std; static const char riffStr[] = "RIFF"; static const char waveStr[] = "WAVE"; -static const char fmtStr[] = "fmt "; +static const char fmtStr[] = "fmt "; static const char dataStr[] = "data"; ////////////////////////////////////////////////////////////////////////////// @@ -44,8 +44,7 @@ WavOutFile::WavOutFile(const char *fileName, int sampleRate, int bits, int chann { bytesWritten = 0; fptr = fopen(fileName, "wb"); - if (fptr == NULL) - { + if (fptr == NULL) { string msg = "Error : Unable to open file \""; msg += fileName; msg += "\" for writing."; @@ -60,8 +59,7 @@ WavOutFile::WavOutFile(const char *fileName, int sampleRate, int bits, int chann WavOutFile::~WavOutFile() { - if (fptr) - { + if (fptr) { finishHeader(); fclose(fptr); } @@ -122,8 +120,7 @@ void WavOutFile::writeHeader() // write the supplemented header in the beginning of the file fseek(fptr, 0, SEEK_SET); res = fwrite(&header, sizeof(header), 1, fptr); - if (res != 1) - { + if (res != 1) { throw runtime_error("Error while writing to a wav file."); } @@ -139,12 +136,12 @@ void WavOutFile::write(const short *buffer, int numElems) // 16bit format & 16 bit samples assert(header.format.bits_per_sample == 16); - if (numElems < 1) return; // nothing to do + if (numElems < 1) + return; // nothing to do res = fwrite(buffer, 2, numElems, fptr); - if (res != numElems) - { + if (res != numElems) { throw runtime_error("Error while writing to a wav file."); } bytesWritten += 2 * numElems; diff --git a/plugins/spu2-x/src/WavFile.h b/plugins/spu2-x/src/WavFile.h index 2e07f97edb..d599886b37 100644 --- a/plugins/spu2-x/src/WavFile.h +++ b/plugins/spu2-x/src/WavFile.h @@ -16,7 +16,7 @@ * along with SPU2-X. If not, see . */ -// Note the file is mostly a copy paste of the WavFile.h from SoundTouch library. It was +// Note the file is mostly a copy paste of the WavFile.h from SoundTouch library. It was // shrunken to support only output 16 bits wav files #ifndef WAVFILE_H @@ -26,44 +26,44 @@ #ifndef uint typedef unsigned int uint; -#endif +#endif /// WAV audio file 'riff' section header -typedef struct +typedef struct { char riff_char[4]; - int package_len; + int package_len; char wave[4]; } WavRiff; /// WAV audio file 'format' section header -typedef struct +typedef struct { - char fmt[4]; - int format_len; + char fmt[4]; + int format_len; short fixed; short channel_number; - int sample_rate; - int byte_rate; + int sample_rate; + int byte_rate; short byte_per_sample; short bits_per_sample; } WavFormat; /// WAV audio file 'data' section header -typedef struct +typedef struct { - char data_field[4]; - uint data_len; + char data_field[4]; + uint data_len; } WavData; /// WAV audio file header -typedef struct +typedef struct { - WavRiff riff; + WavRiff riff; WavFormat format; - WavData data; + WavData data; } WavHeader; @@ -91,12 +91,12 @@ private: void writeHeader(); public: - /// Constructor: Creates a new WAV file. Throws a 'runtime_error' exception + /// Constructor: Creates a new WAV file. Throws a 'runtime_error' exception /// if file creation fails. - WavOutFile(const char *fileName, ///< Filename - int sampleRate, ///< Sample rate (e.g. 44100 etc) - int bits, ///< Bits per sample (8 or 16 bits) - int channels ///< Number of channels (1=mono, 2=stereo) + WavOutFile(const char *fileName, ///< Filename + int sampleRate, ///< Sample rate (e.g. 44100 etc) + int bits, ///< Bits per sample (8 or 16 bits) + int channels ///< Number of channels (1=mono, 2=stereo) ); /// Destructor: Finalizes & closes the WAV file. @@ -104,10 +104,9 @@ public: /// Write data to WAV file. Throws a 'runtime_error' exception if writing to /// file fails. - void write(const short *buffer, ///< Pointer to sample data buffer. - int numElems ///< How many array items are to be written to file. + void write(const short *buffer, ///< Pointer to sample data buffer. + int numElems ///< How many array items are to be written to file. ); - }; #endif diff --git a/plugins/spu2-x/src/Wavedump_wav.cpp b/plugins/spu2-x/src/Wavedump_wav.cpp index 90f2fc9aad..c53e6e2d31 100644 --- a/plugins/spu2-x/src/Wavedump_wav.cpp +++ b/plugins/spu2-x/src/Wavedump_wav.cpp @@ -22,81 +22,77 @@ #include "soundtouch/source/SoundStretch/WavFile.h" #endif -static WavOutFile* _new_WavOutFile( const char* destfile ) +static WavOutFile *_new_WavOutFile(const char *destfile) { - return new WavOutFile( destfile, 48000, 16, 2 ); + return new WavOutFile(destfile, 48000, 16, 2); } namespace WaveDump { - static WavOutFile* m_CoreWav[2][CoreSrc_Count] = { NULL }; +static WavOutFile *m_CoreWav[2][CoreSrc_Count] = {NULL}; - static const char* m_tbl_CoreOutputTypeNames[CoreSrc_Count] = - { - "Input", - "DryVoiceMix", - "WetVoiceMix", - "PreReverb", - "PostReverb", - "External" - }; +static const char *m_tbl_CoreOutputTypeNames[CoreSrc_Count] = + { + "Input", + "DryVoiceMix", + "WetVoiceMix", + "PreReverb", + "PostReverb", + "External"}; - void Open() - { - if( !IsDevBuild ) return; - if( !WaveLog() ) return; +void Open() +{ + if (!IsDevBuild) + return; + if (!WaveLog()) + return; - char wavfilename[256]; + char wavfilename[256]; - for( uint cidx=0; cidx<2; cidx++ ) - { - for( int srcidx=0; srcidx %s.\n\tWave Log for this core source disabled.", ex.what() ); - m_CoreWav[cidx][srcidx] = NULL; - } - } - } - } + try { + m_CoreWav[cidx][srcidx] = _new_WavOutFile(wavfilename); + } catch (std::runtime_error &ex) { + printf("SPU2-X > %s.\n\tWave Log for this core source disabled.", ex.what()); + m_CoreWav[cidx][srcidx] = NULL; + } + } + } +} - void Close() - { - if( !IsDevBuild ) return; - for( uint cidx=0; cidx<2; cidx++ ) - { - for( int srcidx=0; srcidxwrite( (s16*)&sample, 2 ); - } +void WriteCore(uint coreidx, CoreSourceType src, const StereoOut16 &sample) +{ + if (!IsDevBuild) + return; + if (m_CoreWav[coreidx][src] != NULL) + m_CoreWav[coreidx][src]->write((s16 *)&sample, 2); +} - void WriteCore( uint coreidx, CoreSourceType src, s16 left, s16 right ) - { - WriteCore( coreidx, src, StereoOut16( left, right ) ); - } +void WriteCore(uint coreidx, CoreSourceType src, s16 left, s16 right) +{ + WriteCore(coreidx, src, StereoOut16(left, right)); +} } #include "Utilities/Threading.h" @@ -105,37 +101,35 @@ using namespace Threading; bool WavRecordEnabled = false; -static WavOutFile* m_wavrecord = NULL; -static Mutex WavRecordMutex; +static WavOutFile *m_wavrecord = NULL; +static Mutex WavRecordMutex; void RecordStart() { - WavRecordEnabled = false; + WavRecordEnabled = false; - try - { - ScopedLock lock( WavRecordMutex ); - safe_delete( m_wavrecord ); - m_wavrecord = new WavOutFile( "recording.wav", 48000, 16, 2 ); - WavRecordEnabled = true; - } - catch( std::runtime_error& ) - { - m_wavrecord = NULL; // not needed, but what the heck. :) - SysMessage("SPU2-X couldn't open file for recording: %s.\nRecording to wavfile disabled.", "recording.wav"); - } + try { + ScopedLock lock(WavRecordMutex); + safe_delete(m_wavrecord); + m_wavrecord = new WavOutFile("recording.wav", 48000, 16, 2); + WavRecordEnabled = true; + } catch (std::runtime_error &) { + m_wavrecord = NULL; // not needed, but what the heck. :) + SysMessage("SPU2-X couldn't open file for recording: %s.\nRecording to wavfile disabled.", "recording.wav"); + } } void RecordStop() { - WavRecordEnabled = false; - ScopedLock lock( WavRecordMutex ); - safe_delete( m_wavrecord ); + WavRecordEnabled = false; + ScopedLock lock(WavRecordMutex); + safe_delete(m_wavrecord); } -void RecordWrite( const StereoOut16& sample ) +void RecordWrite(const StereoOut16 &sample) { - ScopedLock lock( WavRecordMutex ); - if( m_wavrecord == NULL ) return; - m_wavrecord->write( (s16*)&sample, 2 ); + ScopedLock lock(WavRecordMutex); + if (m_wavrecord == NULL) + return; + m_wavrecord->write((s16 *)&sample, 2); } diff --git a/plugins/spu2-x/src/Windows/AboutBox.cpp b/plugins/spu2-x/src/Windows/AboutBox.cpp index 7405355c7f..f45c5707fb 100644 --- a/plugins/spu2-x/src/Windows/AboutBox.cpp +++ b/plugins/spu2-x/src/Windows/AboutBox.cpp @@ -22,48 +22,45 @@ static LRESULT WINAPI AboutProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) { - switch(uMsg) - { - case WM_INITDIALOG: - { - wchar_t outstr[256]; - if( IsDevBuild ) - swprintf_s( outstr, L"Build %lld -- Compiled on " _T(__DATE__), SVN_REV ); - else - swprintf_s( outstr, L"Release v%d.%d -- Compiled on " _T(__DATE__), - VersionInfo::Release, VersionInfo::Revision ); + switch (uMsg) { + case WM_INITDIALOG: { + wchar_t outstr[256]; + if (IsDevBuild) + swprintf_s(outstr, L"Build %lld -- Compiled on " _T(__DATE__), SVN_REV); + else + swprintf_s(outstr, L"Release v%d.%d -- Compiled on " _T(__DATE__), + VersionInfo::Release, VersionInfo::Revision); - SetWindowText( GetDlgItem(hDlg, IDC_LABEL_VERSION_INFO), outstr ); - ShowWindow( hDlg, true ); - } - return TRUE; + SetWindowText(GetDlgItem(hDlg, IDC_LABEL_VERSION_INFO), outstr); + ShowWindow(hDlg, true); + } + return TRUE; - case WM_COMMAND: - switch( LOWORD(wParam) ) - { - case IDOK: - EndDialog(hDlg, TRUE ); - return TRUE; + case WM_COMMAND: + switch (LOWORD(wParam)) { + case IDOK: + EndDialog(hDlg, TRUE); + return TRUE; - case IDC_LINK_WEBSITE: - ShellExecute(hDlg, L"open", L"http://www.pcsx2.net/", - NULL, NULL, SW_SHOWNORMAL); - return TRUE; + case IDC_LINK_WEBSITE: + ShellExecute(hDlg, L"open", L"http://www.pcsx2.net/", + NULL, NULL, SW_SHOWNORMAL); + return TRUE; - case IDC_LINK_GOOGLECODE: - ShellExecute(hDlg, L"open", L"https://github.com/PCSX2/pcsx2", - NULL, NULL, SW_SHOWNORMAL); - return TRUE; - } - break; + case IDC_LINK_GOOGLECODE: + ShellExecute(hDlg, L"open", L"https://github.com/PCSX2/pcsx2", + NULL, NULL, SW_SHOWNORMAL); + return TRUE; + } + break; - default: - return FALSE; - } - return TRUE; + default: + return FALSE; + } + return TRUE; } void AboutBox() { - DialogBox( hInstance, MAKEINTRESOURCE(IDD_ABOUT), GetActiveWindow(), (DLGPROC)AboutProc ); + DialogBox(hInstance, MAKEINTRESOURCE(IDD_ABOUT), GetActiveWindow(), (DLGPROC)AboutProc); } diff --git a/plugins/spu2-x/src/Windows/CfgHelpers.cpp b/plugins/spu2-x/src/Windows/CfgHelpers.cpp index 70b4fbd78c..4fbe96fe5d 100644 --- a/plugins/spu2-x/src/Windows/CfgHelpers.cpp +++ b/plugins/spu2-x/src/Windows/CfgHelpers.cpp @@ -24,38 +24,38 @@ extern uptr gsWindowHandle; void SysMessage(const char *fmt, ...) { - va_list list; - char tmp[512]; - wchar_t wtmp[512]; + va_list list; + char tmp[512]; + wchar_t wtmp[512]; - va_start(list,fmt); - vsprintf_s(tmp,fmt,list); - va_end(list); - swprintf_s(wtmp, L"%S", tmp); - MessageBox( (!!gsWindowHandle) ? (HWND)gsWindowHandle : GetActiveWindow(), wtmp, - L"SPU2-X System Message", MB_OK | MB_SETFOREGROUND); + va_start(list, fmt); + vsprintf_s(tmp, fmt, list); + va_end(list); + swprintf_s(wtmp, L"%S", tmp); + MessageBox((!!gsWindowHandle) ? (HWND)gsWindowHandle : GetActiveWindow(), wtmp, + L"SPU2-X System Message", MB_OK | MB_SETFOREGROUND); } void SysMessage(const wchar_t *fmt, ...) { - va_list list; - va_start(list,fmt); - wxString wtmp; - wtmp.PrintfV( fmt, list ); - va_end(list); - MessageBox( (!!gsWindowHandle) ? (HWND)gsWindowHandle : GetActiveWindow(), wtmp, - L"SPU2-X System Message", MB_OK | MB_SETFOREGROUND); + va_list list; + va_start(list, fmt); + wxString wtmp; + wtmp.PrintfV(fmt, list); + va_end(list); + MessageBox((!!gsWindowHandle) ? (HWND)gsWindowHandle : GetActiveWindow(), wtmp, + L"SPU2-X System Message", MB_OK | MB_SETFOREGROUND); } ////// #include "Utilities/Path.h" -static wxString CfgFile( L"inis/SPU2-X.ini" ); +static wxString CfgFile(L"inis/SPU2-X.ini"); -void CfgSetSettingsDir( const char* dir ) +void CfgSetSettingsDir(const char *dir) { - CfgFile = Path::Combine( (dir==NULL) ? wxString(L"inis") : wxString(dir, wxConvFile), L"SPU2-X.ini" ); + CfgFile = Path::Combine((dir == NULL) ? wxString(L"inis") : wxString(dir, wxConvFile), L"SPU2-X.ini"); } @@ -74,24 +74,24 @@ void CfgSetSettingsDir( const char* dir ) \*_____________________________________________*/ -void CfgWriteBool(const TCHAR* Section, const TCHAR* Name, bool Value) +void CfgWriteBool(const TCHAR *Section, const TCHAR *Name, bool Value) { - const TCHAR *Data = Value ? L"TRUE" : L"FALSE"; - WritePrivateProfileString( Section, Name, Data, CfgFile ); + const TCHAR *Data = Value ? L"TRUE" : L"FALSE"; + WritePrivateProfileString(Section, Name, Data, CfgFile); } -void CfgWriteInt(const TCHAR* Section, const TCHAR* Name, int Value) +void CfgWriteInt(const TCHAR *Section, const TCHAR *Name, int Value) { - TCHAR Data[32]; - _itow( Value, Data, 10 ); - WritePrivateProfileString(Section,Name,Data,CfgFile); + TCHAR Data[32]; + _itow(Value, Data, 10); + WritePrivateProfileString(Section, Name, Data, CfgFile); } -void CfgWriteFloat(const TCHAR* Section, const TCHAR* Name, float Value) +void CfgWriteFloat(const TCHAR *Section, const TCHAR *Name, float Value) { - TCHAR Data[32]; - _swprintf(Data, L"%f", Value); - WritePrivateProfileString(Section, Name, Data, CfgFile); + TCHAR Data[32]; + _swprintf(Data, L"%f", Value); + WritePrivateProfileString(Section, Name, Data, CfgFile); } /*void CfgWriteStr(const TCHAR* Section, const TCHAR* Name, const TCHAR *Data) @@ -99,94 +99,99 @@ void CfgWriteFloat(const TCHAR* Section, const TCHAR* Name, float Value) WritePrivateProfileString( Section, Name, Data, CfgFile ); }*/ -void CfgWriteStr(const TCHAR* Section, const TCHAR* Name, const wxString& Data) +void CfgWriteStr(const TCHAR *Section, const TCHAR *Name, const wxString &Data) { - WritePrivateProfileString( Section, Name, Data, CfgFile ); + WritePrivateProfileString(Section, Name, Data, CfgFile); } /*****************************************************************************/ -bool CfgReadBool(const TCHAR *Section,const TCHAR* Name, bool Default) +bool CfgReadBool(const TCHAR *Section, const TCHAR *Name, bool Default) { - TCHAR Data[255] = {0}; + TCHAR Data[255] = {0}; - GetPrivateProfileString( Section, Name, L"", Data, 255, CfgFile ); - Data[254]=0; - if(wcslen(Data)==0) { - CfgWriteBool(Section,Name,Default); - return Default; - } + GetPrivateProfileString(Section, Name, L"", Data, 255, CfgFile); + Data[254] = 0; + if (wcslen(Data) == 0) { + CfgWriteBool(Section, Name, Default); + return Default; + } - if(wcscmp(Data,L"1")==0) return true; - if(wcscmp(Data,L"Y")==0) return true; - if(wcscmp(Data,L"T")==0) return true; - if(wcscmp(Data,L"YES")==0) return true; - if(wcscmp(Data,L"TRUE")==0) return true; - return false; + if (wcscmp(Data, L"1") == 0) + return true; + if (wcscmp(Data, L"Y") == 0) + return true; + if (wcscmp(Data, L"T") == 0) + return true; + if (wcscmp(Data, L"YES") == 0) + return true; + if (wcscmp(Data, L"TRUE") == 0) + return true; + return false; } -int CfgReadInt(const TCHAR* Section, const TCHAR* Name,int Default) +int CfgReadInt(const TCHAR *Section, const TCHAR *Name, int Default) { - TCHAR Data[255]={0}; - GetPrivateProfileString(Section,Name,L"",Data,255,CfgFile); - Data[254]=0; + TCHAR Data[255] = {0}; + GetPrivateProfileString(Section, Name, L"", Data, 255, CfgFile); + Data[254] = 0; - if(wcslen(Data)==0) { - CfgWriteInt(Section,Name,Default); - return Default; - } + if (wcslen(Data) == 0) { + CfgWriteInt(Section, Name, Default); + return Default; + } - return _wtoi(Data); + return _wtoi(Data); } -float CfgReadFloat(const TCHAR* Section, const TCHAR* Name, float Default) +float CfgReadFloat(const TCHAR *Section, const TCHAR *Name, float Default) { - TCHAR Data[255] = { 0 }; - GetPrivateProfileString(Section, Name, L"", Data, 255, CfgFile); - Data[254] = 0; + TCHAR Data[255] = {0}; + GetPrivateProfileString(Section, Name, L"", Data, 255, CfgFile); + Data[254] = 0; - if (wcslen(Data) == 0) { - CfgWriteFloat(Section, Name, Default); - return Default; - } + if (wcslen(Data) == 0) { + CfgWriteFloat(Section, Name, Default); + return Default; + } - return (float)_wtof(Data); + return (float)_wtof(Data); } -void CfgReadStr(const TCHAR* Section, const TCHAR* Name, TCHAR* Data, int DataSize, const TCHAR* Default) +void CfgReadStr(const TCHAR *Section, const TCHAR *Name, TCHAR *Data, int DataSize, const TCHAR *Default) { - GetPrivateProfileString(Section,Name,L"",Data,DataSize,CfgFile); + GetPrivateProfileString(Section, Name, L"", Data, DataSize, CfgFile); - if(wcslen(Data)==0) { - swprintf_s( Data, DataSize, L"%s", Default ); - CfgWriteStr( Section, Name, Data ); - } + if (wcslen(Data) == 0) { + swprintf_s(Data, DataSize, L"%s", Default); + CfgWriteStr(Section, Name, Data); + } } -void CfgReadStr(const TCHAR* Section, const TCHAR* Name, wxString& Data, const TCHAR* Default) +void CfgReadStr(const TCHAR *Section, const TCHAR *Name, wxString &Data, const TCHAR *Default) { - wchar_t workspace[512]; - GetPrivateProfileString(Section,Name,L"",workspace,ArraySize(workspace),CfgFile); + wchar_t workspace[512]; + GetPrivateProfileString(Section, Name, L"", workspace, ArraySize(workspace), CfgFile); - Data = workspace; + Data = workspace; - if(Data.empty()) - { - Data = Default; - CfgWriteStr( Section, Name, Default ); - } + if (Data.empty()) { + Data = Default; + CfgWriteStr(Section, Name, Default); + } } // Tries to read the requested value. // Returns FALSE if the value isn't found. -bool CfgFindName( const TCHAR *Section, const TCHAR* Name) +bool CfgFindName(const TCHAR *Section, const TCHAR *Name) { - // Only load 24 characters. No need to load more. - TCHAR Data[24]={0}; - GetPrivateProfileString(Section,Name,L"",Data,24,CfgFile); - Data[23]=0; + // Only load 24 characters. No need to load more. + TCHAR Data[24] = {0}; + GetPrivateProfileString(Section, Name, L"", Data, 24, CfgFile); + Data[23] = 0; - if(wcslen(Data)==0) return false; - return true; + if (wcslen(Data) == 0) + return false; + return true; } diff --git a/plugins/spu2-x/src/Windows/Config.cpp b/plugins/spu2-x/src/Windows/Config.cpp index c7d4f2cbd8..949019a821 100644 --- a/plugins/spu2-x/src/Windows/Config.cpp +++ b/plugins/spu2-x/src/Windows/Config.cpp @@ -40,9 +40,9 @@ int Interpolation = 4; bool EffectsDisabled = false; -float FinalVolume; // Global +float FinalVolume; // Global bool AdvancedVolumeControl; -float VolumeAdjustFLdb; // decibels settings, cos audiophiles love that +float VolumeAdjustFLdb; // decibels settings, cos audiophiles love that float VolumeAdjustCdb; float VolumeAdjustFRdb; float VolumeAdjustBLdb; @@ -50,7 +50,7 @@ float VolumeAdjustBRdb; float VolumeAdjustSLdb; float VolumeAdjustSRdb; float VolumeAdjustLFEdb; -float VolumeAdjustFL; // linear coefs calcualted from decibels, +float VolumeAdjustFL; // linear coefs calcualted from decibels, float VolumeAdjustC; float VolumeAdjustFR; float VolumeAdjustBL; @@ -65,7 +65,7 @@ bool postprocess_filter_dealias = false; // OUTPUT int SndOutLatencyMS = 100; -int SynchMode = 0; // Time Stretch, Async or Disabled +int SynchMode = 0; // Time Stretch, Async or Disabled u32 OutputModule = 0; @@ -74,7 +74,7 @@ CONFIG_XAUDIO2 Config_XAudio2; // DSP bool dspPluginEnabled = false; -int dspPluginModule = 0; +int dspPluginModule = 0; wchar_t dspPlugin[256]; int numSpeakers = 0; @@ -85,344 +85,324 @@ int dplLevel = 0; void ReadSettings() { - Interpolation = CfgReadInt( L"MIXING",L"Interpolation", 4 ); + Interpolation = CfgReadInt(L"MIXING", L"Interpolation", 4); - EffectsDisabled = CfgReadBool( L"MIXING", L"Disable_Effects", false ); - postprocess_filter_dealias = CfgReadBool( L"MIXING", L"DealiasFilter", false ); - FinalVolume = ((float)CfgReadInt( L"MIXING", L"FinalVolume", 100 )) / 100; - if ( FinalVolume > 1.0f) FinalVolume = 1.0f; + EffectsDisabled = CfgReadBool(L"MIXING", L"Disable_Effects", false); + postprocess_filter_dealias = CfgReadBool(L"MIXING", L"DealiasFilter", false); + FinalVolume = ((float)CfgReadInt(L"MIXING", L"FinalVolume", 100)) / 100; + if (FinalVolume > 1.0f) + FinalVolume = 1.0f; - AdvancedVolumeControl = CfgReadBool(L"MIXING", L"AdvancedVolumeControl", false); - VolumeAdjustCdb = CfgReadFloat(L"MIXING", L"VolumeAdjustC(dB)", 0); - VolumeAdjustFLdb = CfgReadFloat(L"MIXING", L"VolumeAdjustFL(dB)", 0); - VolumeAdjustFRdb = CfgReadFloat(L"MIXING", L"VolumeAdjustFR(dB)", 0); - VolumeAdjustBLdb = CfgReadFloat(L"MIXING", L"VolumeAdjustBL(dB)", 0); - VolumeAdjustBRdb = CfgReadFloat(L"MIXING", L"VolumeAdjustBR(dB)", 0); - VolumeAdjustSLdb = CfgReadFloat(L"MIXING", L"VolumeAdjustSL(dB)", 0); - VolumeAdjustSRdb = CfgReadFloat(L"MIXING", L"VolumeAdjustSR(dB)", 0); - VolumeAdjustLFEdb = CfgReadFloat(L"MIXING", L"VolumeAdjustLFE(dB)", 0); - delayCycles = CfgReadInt(L"DEBUG", L"DelayCycles", 4); - VolumeAdjustC = powf(10, VolumeAdjustCdb / 10); - VolumeAdjustFL = powf(10, VolumeAdjustFLdb / 10); - VolumeAdjustFR = powf(10, VolumeAdjustFRdb / 10); - VolumeAdjustBL = powf(10, VolumeAdjustBLdb / 10); - VolumeAdjustBR = powf(10, VolumeAdjustBRdb / 10); - VolumeAdjustSL = powf(10, VolumeAdjustSLdb / 10); - VolumeAdjustSR = powf(10, VolumeAdjustSRdb / 10); - VolumeAdjustLFE = powf(10, VolumeAdjustLFEdb / 10); + AdvancedVolumeControl = CfgReadBool(L"MIXING", L"AdvancedVolumeControl", false); + VolumeAdjustCdb = CfgReadFloat(L"MIXING", L"VolumeAdjustC(dB)", 0); + VolumeAdjustFLdb = CfgReadFloat(L"MIXING", L"VolumeAdjustFL(dB)", 0); + VolumeAdjustFRdb = CfgReadFloat(L"MIXING", L"VolumeAdjustFR(dB)", 0); + VolumeAdjustBLdb = CfgReadFloat(L"MIXING", L"VolumeAdjustBL(dB)", 0); + VolumeAdjustBRdb = CfgReadFloat(L"MIXING", L"VolumeAdjustBR(dB)", 0); + VolumeAdjustSLdb = CfgReadFloat(L"MIXING", L"VolumeAdjustSL(dB)", 0); + VolumeAdjustSRdb = CfgReadFloat(L"MIXING", L"VolumeAdjustSR(dB)", 0); + VolumeAdjustLFEdb = CfgReadFloat(L"MIXING", L"VolumeAdjustLFE(dB)", 0); + delayCycles = CfgReadInt(L"DEBUG", L"DelayCycles", 4); + VolumeAdjustC = powf(10, VolumeAdjustCdb / 10); + VolumeAdjustFL = powf(10, VolumeAdjustFLdb / 10); + VolumeAdjustFR = powf(10, VolumeAdjustFRdb / 10); + VolumeAdjustBL = powf(10, VolumeAdjustBLdb / 10); + VolumeAdjustBR = powf(10, VolumeAdjustBRdb / 10); + VolumeAdjustSL = powf(10, VolumeAdjustSLdb / 10); + VolumeAdjustSR = powf(10, VolumeAdjustSRdb / 10); + VolumeAdjustLFE = powf(10, VolumeAdjustLFEdb / 10); - SynchMode = CfgReadInt( L"OUTPUT", L"Synch_Mode", 0); - numSpeakers = CfgReadInt( L"OUTPUT", L"SpeakerConfiguration", 0); - dplLevel = CfgReadInt( L"OUTPUT", L"DplDecodingLevel", 0); - SndOutLatencyMS = CfgReadInt(L"OUTPUT",L"Latency", 100); + SynchMode = CfgReadInt(L"OUTPUT", L"Synch_Mode", 0); + numSpeakers = CfgReadInt(L"OUTPUT", L"SpeakerConfiguration", 0); + dplLevel = CfgReadInt(L"OUTPUT", L"DplDecodingLevel", 0); + SndOutLatencyMS = CfgReadInt(L"OUTPUT", L"Latency", 100); - if((SynchMode == 0) && (SndOutLatencyMS < LATENCY_MIN_TS)) // can't use low-latency with timestretcher atm - SndOutLatencyMS = LATENCY_MIN_TS; - else if(SndOutLatencyMS < LATENCY_MIN) - SndOutLatencyMS = LATENCY_MIN; + if ((SynchMode == 0) && (SndOutLatencyMS < LATENCY_MIN_TS)) // can't use low-latency with timestretcher atm + SndOutLatencyMS = LATENCY_MIN_TS; + else if (SndOutLatencyMS < LATENCY_MIN) + SndOutLatencyMS = LATENCY_MIN; - wchar_t omodid[128]; + wchar_t omodid[128]; - // portaudio occasionally has issues selecting the proper default audio device. - // let's use xaudio2 until this is sorted (rama) + // portaudio occasionally has issues selecting the proper default audio device. + // let's use xaudio2 until this is sorted (rama) -// CfgReadStr(L"OUTPUT", L"Output_Module", omodid, 127, PortaudioOut->GetIdent()); - if (IsWindows8OrGreater()) - CfgReadStr(L"OUTPUT", L"Output_Module", omodid, 127, XAudio2Out->GetIdent()); - else - CfgReadStr(L"OUTPUT", L"Output_Module", omodid, 127, XAudio2_27_Out->GetIdent()); + // CfgReadStr(L"OUTPUT", L"Output_Module", omodid, 127, PortaudioOut->GetIdent()); + if (IsWindows8OrGreater()) + CfgReadStr(L"OUTPUT", L"Output_Module", omodid, 127, XAudio2Out->GetIdent()); + else + CfgReadStr(L"OUTPUT", L"Output_Module", omodid, 127, XAudio2_27_Out->GetIdent()); - // find the driver index of this module: - OutputModule = FindOutputModuleById( omodid ); + // find the driver index of this module: + OutputModule = FindOutputModuleById(omodid); - CfgReadStr( L"DSP PLUGIN",L"Filename",dspPlugin,255,L""); - dspPluginModule = CfgReadInt(L"DSP PLUGIN",L"ModuleNum",0); - dspPluginEnabled= CfgReadBool(L"DSP PLUGIN",L"Enabled",false); + CfgReadStr(L"DSP PLUGIN", L"Filename", dspPlugin, 255, L""); + dspPluginModule = CfgReadInt(L"DSP PLUGIN", L"ModuleNum", 0); + dspPluginEnabled = CfgReadBool(L"DSP PLUGIN", L"Enabled", false); - // Read DSOUNDOUT and WAVEOUT configs: - CfgReadStr( L"WAVEOUT", L"Device", Config_WaveOut.Device, L"default" ); - Config_WaveOut.NumBuffers = CfgReadInt( L"WAVEOUT", L"Buffer_Count", 4 ); + // Read DSOUNDOUT and WAVEOUT configs: + CfgReadStr(L"WAVEOUT", L"Device", Config_WaveOut.Device, L"default"); + Config_WaveOut.NumBuffers = CfgReadInt(L"WAVEOUT", L"Buffer_Count", 4); - DSoundOut->ReadSettings(); - PortaudioOut->ReadSettings(); + DSoundOut->ReadSettings(); + PortaudioOut->ReadSettings(); - SoundtouchCfg::ReadSettings(); - DebugConfig::ReadSettings(); + SoundtouchCfg::ReadSettings(); + DebugConfig::ReadSettings(); - // Sanity Checks - // ------------- + // Sanity Checks + // ------------- - Clampify( SndOutLatencyMS, LATENCY_MIN, LATENCY_MAX ); + Clampify(SndOutLatencyMS, LATENCY_MIN, LATENCY_MAX); - if( mods[OutputModule] == NULL ) - { - // Unsupported or legacy module. - fwprintf( stderr, L"* SPU2-X: Unknown output module '%s' specified in configuration file.\n", omodid ); - fprintf( stderr, "* SPU2-X: Defaulting to DirectSound (%S).\n", DSoundOut->GetIdent() ); - OutputModule = FindOutputModuleById( DSoundOut->GetIdent() ); - } + if (mods[OutputModule] == NULL) { + // Unsupported or legacy module. + fwprintf(stderr, L"* SPU2-X: Unknown output module '%s' specified in configuration file.\n", omodid); + fprintf(stderr, "* SPU2-X: Defaulting to DirectSound (%S).\n", DSoundOut->GetIdent()); + OutputModule = FindOutputModuleById(DSoundOut->GetIdent()); + } } /*****************************************************************************/ void WriteSettings() { - CfgWriteInt(L"MIXING",L"Interpolation",Interpolation); + CfgWriteInt(L"MIXING", L"Interpolation", Interpolation); - CfgWriteBool(L"MIXING",L"Disable_Effects",EffectsDisabled); - CfgWriteBool(L"MIXING",L"DealiasFilter",postprocess_filter_dealias); - CfgWriteInt(L"MIXING",L"FinalVolume",(int)(FinalVolume * 100 + 0.5f)); + CfgWriteBool(L"MIXING", L"Disable_Effects", EffectsDisabled); + CfgWriteBool(L"MIXING", L"DealiasFilter", postprocess_filter_dealias); + CfgWriteInt(L"MIXING", L"FinalVolume", (int)(FinalVolume * 100 + 0.5f)); - CfgWriteBool(L"MIXING", L"AdvancedVolumeControl", AdvancedVolumeControl); - CfgWriteFloat(L"MIXING", L"VolumeAdjustC(dB)", VolumeAdjustCdb); - CfgWriteFloat(L"MIXING", L"VolumeAdjustFL(dB)", VolumeAdjustFLdb); - CfgWriteFloat(L"MIXING", L"VolumeAdjustFR(dB)", VolumeAdjustFRdb); - CfgWriteFloat(L"MIXING", L"VolumeAdjustBL(dB)", VolumeAdjustBLdb); - CfgWriteFloat(L"MIXING", L"VolumeAdjustBR(dB)", VolumeAdjustBRdb); - CfgWriteFloat(L"MIXING", L"VolumeAdjustSL(dB)", VolumeAdjustSLdb); - CfgWriteFloat(L"MIXING", L"VolumeAdjustSR(dB)", VolumeAdjustSRdb); - CfgWriteFloat(L"MIXING", L"VolumeAdjustLFE(dB)", VolumeAdjustLFEdb); + CfgWriteBool(L"MIXING", L"AdvancedVolumeControl", AdvancedVolumeControl); + CfgWriteFloat(L"MIXING", L"VolumeAdjustC(dB)", VolumeAdjustCdb); + CfgWriteFloat(L"MIXING", L"VolumeAdjustFL(dB)", VolumeAdjustFLdb); + CfgWriteFloat(L"MIXING", L"VolumeAdjustFR(dB)", VolumeAdjustFRdb); + CfgWriteFloat(L"MIXING", L"VolumeAdjustBL(dB)", VolumeAdjustBLdb); + CfgWriteFloat(L"MIXING", L"VolumeAdjustBR(dB)", VolumeAdjustBRdb); + CfgWriteFloat(L"MIXING", L"VolumeAdjustSL(dB)", VolumeAdjustSLdb); + CfgWriteFloat(L"MIXING", L"VolumeAdjustSR(dB)", VolumeAdjustSRdb); + CfgWriteFloat(L"MIXING", L"VolumeAdjustLFE(dB)", VolumeAdjustLFEdb); - CfgWriteStr(L"OUTPUT",L"Output_Module", mods[OutputModule]->GetIdent() ); - CfgWriteInt(L"OUTPUT",L"Latency", SndOutLatencyMS); - CfgWriteInt(L"OUTPUT",L"Synch_Mode", SynchMode); - CfgWriteInt(L"OUTPUT",L"SpeakerConfiguration", numSpeakers); - CfgWriteInt( L"OUTPUT", L"DplDecodingLevel", dplLevel); - CfgWriteInt(L"DEBUG", L"DelayCycles", delayCycles); + CfgWriteStr(L"OUTPUT", L"Output_Module", mods[OutputModule]->GetIdent()); + CfgWriteInt(L"OUTPUT", L"Latency", SndOutLatencyMS); + CfgWriteInt(L"OUTPUT", L"Synch_Mode", SynchMode); + CfgWriteInt(L"OUTPUT", L"SpeakerConfiguration", numSpeakers); + CfgWriteInt(L"OUTPUT", L"DplDecodingLevel", dplLevel); + CfgWriteInt(L"DEBUG", L"DelayCycles", delayCycles); - if( Config_WaveOut.Device.empty() ) Config_WaveOut.Device = L"default"; - CfgWriteStr(L"WAVEOUT",L"Device",Config_WaveOut.Device); - CfgWriteInt(L"WAVEOUT",L"Buffer_Count",Config_WaveOut.NumBuffers); + if (Config_WaveOut.Device.empty()) + Config_WaveOut.Device = L"default"; + CfgWriteStr(L"WAVEOUT", L"Device", Config_WaveOut.Device); + CfgWriteInt(L"WAVEOUT", L"Buffer_Count", Config_WaveOut.NumBuffers); - CfgWriteStr(L"DSP PLUGIN",L"Filename",dspPlugin); - CfgWriteInt(L"DSP PLUGIN",L"ModuleNum",dspPluginModule); - CfgWriteBool(L"DSP PLUGIN",L"Enabled",dspPluginEnabled); - - PortaudioOut->WriteSettings(); - DSoundOut->WriteSettings(); - SoundtouchCfg::WriteSettings(); - DebugConfig::WriteSettings(); + CfgWriteStr(L"DSP PLUGIN", L"Filename", dspPlugin); + CfgWriteInt(L"DSP PLUGIN", L"ModuleNum", dspPluginModule); + CfgWriteBool(L"DSP PLUGIN", L"Enabled", dspPluginEnabled); + PortaudioOut->WriteSettings(); + DSoundOut->WriteSettings(); + SoundtouchCfg::WriteSettings(); + DebugConfig::WriteSettings(); } -BOOL CALLBACK ConfigProc(HWND hWnd,UINT uMsg,WPARAM wParam,LPARAM lParam) +BOOL CALLBACK ConfigProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { - int wmId,wmEvent; - wchar_t temp[384]={0}; + int wmId, wmEvent; + wchar_t temp[384] = {0}; - switch(uMsg) - { - case WM_PAINT: - return FALSE; + switch (uMsg) { + case WM_PAINT: + return FALSE; - case WM_INITDIALOG: - { - SendDialogMsg( hWnd, IDC_INTERPOLATE, CB_RESETCONTENT,0,0 ); - SendDialogMsg( hWnd, IDC_INTERPOLATE, CB_ADDSTRING,0,(LPARAM) L"0 - Nearest (fastest/bad quality)" ); - SendDialogMsg( hWnd, IDC_INTERPOLATE, CB_ADDSTRING,0,(LPARAM) L"1 - Linear (simple/okay sound)" ); - SendDialogMsg( hWnd, IDC_INTERPOLATE, CB_ADDSTRING,0,(LPARAM) L"2 - Cubic (artificial highs)" ); - SendDialogMsg( hWnd, IDC_INTERPOLATE, CB_ADDSTRING,0,(LPARAM) L"3 - Hermite (better highs)" ); - SendDialogMsg( hWnd, IDC_INTERPOLATE, CB_ADDSTRING,0,(LPARAM) L"4 - Catmull-Rom (PS2-like/slow)" ); - SendDialogMsg( hWnd, IDC_INTERPOLATE, CB_SETCURSEL,Interpolation,0 ); + case WM_INITDIALOG: { + SendDialogMsg(hWnd, IDC_INTERPOLATE, CB_RESETCONTENT, 0, 0); + SendDialogMsg(hWnd, IDC_INTERPOLATE, CB_ADDSTRING, 0, (LPARAM)L"0 - Nearest (fastest/bad quality)"); + SendDialogMsg(hWnd, IDC_INTERPOLATE, CB_ADDSTRING, 0, (LPARAM)L"1 - Linear (simple/okay sound)"); + SendDialogMsg(hWnd, IDC_INTERPOLATE, CB_ADDSTRING, 0, (LPARAM)L"2 - Cubic (artificial highs)"); + SendDialogMsg(hWnd, IDC_INTERPOLATE, CB_ADDSTRING, 0, (LPARAM)L"3 - Hermite (better highs)"); + SendDialogMsg(hWnd, IDC_INTERPOLATE, CB_ADDSTRING, 0, (LPARAM)L"4 - Catmull-Rom (PS2-like/slow)"); + SendDialogMsg(hWnd, IDC_INTERPOLATE, CB_SETCURSEL, Interpolation, 0); - SendDialogMsg( hWnd, IDC_SYNCHMODE, CB_RESETCONTENT,0,0 ); - SendDialogMsg( hWnd, IDC_SYNCHMODE, CB_ADDSTRING,0,(LPARAM) L"TimeStretch (Recommended)" ); - SendDialogMsg( hWnd, IDC_SYNCHMODE, CB_ADDSTRING,0,(LPARAM) L"Async Mix (Breaks some games!)" ); - SendDialogMsg( hWnd, IDC_SYNCHMODE, CB_ADDSTRING,0,(LPARAM) L"None (Audio can skip.)" ); - SendDialogMsg( hWnd, IDC_SYNCHMODE, CB_SETCURSEL,SynchMode,0 ); - - SendDialogMsg( hWnd, IDC_SPEAKERS, CB_RESETCONTENT,0,0 ); - SendDialogMsg( hWnd, IDC_SPEAKERS, CB_ADDSTRING,0,(LPARAM) L"Stereo (none, default)" ); - SendDialogMsg( hWnd, IDC_SPEAKERS, CB_ADDSTRING,0,(LPARAM) L"Quadrafonic" ); - SendDialogMsg( hWnd, IDC_SPEAKERS, CB_ADDSTRING,0,(LPARAM) L"Surround 5.1" ); - SendDialogMsg( hWnd, IDC_SPEAKERS, CB_ADDSTRING,0,(LPARAM) L"Surround 7.1" ); - SendDialogMsg( hWnd, IDC_SPEAKERS, CB_SETCURSEL,numSpeakers,0 ); + SendDialogMsg(hWnd, IDC_SYNCHMODE, CB_RESETCONTENT, 0, 0); + SendDialogMsg(hWnd, IDC_SYNCHMODE, CB_ADDSTRING, 0, (LPARAM)L"TimeStretch (Recommended)"); + SendDialogMsg(hWnd, IDC_SYNCHMODE, CB_ADDSTRING, 0, (LPARAM)L"Async Mix (Breaks some games!)"); + SendDialogMsg(hWnd, IDC_SYNCHMODE, CB_ADDSTRING, 0, (LPARAM)L"None (Audio can skip.)"); + SendDialogMsg(hWnd, IDC_SYNCHMODE, CB_SETCURSEL, SynchMode, 0); - SendDialogMsg( hWnd, IDC_OUTPUT, CB_RESETCONTENT,0,0 ); + SendDialogMsg(hWnd, IDC_SPEAKERS, CB_RESETCONTENT, 0, 0); + SendDialogMsg(hWnd, IDC_SPEAKERS, CB_ADDSTRING, 0, (LPARAM)L"Stereo (none, default)"); + SendDialogMsg(hWnd, IDC_SPEAKERS, CB_ADDSTRING, 0, (LPARAM)L"Quadrafonic"); + SendDialogMsg(hWnd, IDC_SPEAKERS, CB_ADDSTRING, 0, (LPARAM)L"Surround 5.1"); + SendDialogMsg(hWnd, IDC_SPEAKERS, CB_ADDSTRING, 0, (LPARAM)L"Surround 7.1"); + SendDialogMsg(hWnd, IDC_SPEAKERS, CB_SETCURSEL, numSpeakers, 0); - int modidx = 0; - while( mods[modidx] != NULL ) - { - swprintf_s( temp, 72, L"%d - %s", modidx, mods[modidx]->GetLongName() ); - SendDialogMsg( hWnd, IDC_OUTPUT, CB_ADDSTRING,0,(LPARAM)temp ); - ++modidx; - } - SendDialogMsg( hWnd, IDC_OUTPUT, CB_SETCURSEL, OutputModule, 0 ); + SendDialogMsg(hWnd, IDC_OUTPUT, CB_RESETCONTENT, 0, 0); - double minlat = (SynchMode == 0)?LATENCY_MIN_TS:LATENCY_MIN; - int minexp = (int)(pow( minlat+1, 1.0/3.0 ) * 128.0); - int maxexp = (int)(pow( (double)LATENCY_MAX+2, 1.0/3.0 ) * 128.0); - INIT_SLIDER( IDC_LATENCY_SLIDER, minexp, maxexp, 200, 42, 1 ); + int modidx = 0; + while (mods[modidx] != NULL) { + swprintf_s(temp, 72, L"%d - %s", modidx, mods[modidx]->GetLongName()); + SendDialogMsg(hWnd, IDC_OUTPUT, CB_ADDSTRING, 0, (LPARAM)temp); + ++modidx; + } + SendDialogMsg(hWnd, IDC_OUTPUT, CB_SETCURSEL, OutputModule, 0); - SendDialogMsg( hWnd, IDC_LATENCY_SLIDER, TBM_SETPOS, TRUE, (int)((pow( (double)SndOutLatencyMS, 1.0/3.0 ) * 128.0) + 1) ); - swprintf_s(temp,L"%d ms (avg)",SndOutLatencyMS); - SetWindowText(GetDlgItem(hWnd,IDC_LATENCY_LABEL),temp); + double minlat = (SynchMode == 0) ? LATENCY_MIN_TS : LATENCY_MIN; + int minexp = (int)(pow(minlat + 1, 1.0 / 3.0) * 128.0); + int maxexp = (int)(pow((double)LATENCY_MAX + 2, 1.0 / 3.0) * 128.0); + INIT_SLIDER(IDC_LATENCY_SLIDER, minexp, maxexp, 200, 42, 1); - int configvol = (int)(FinalVolume * 100 + 0.5f); - INIT_SLIDER( IDC_VOLUME_SLIDER, 0, 100, 10, 42, 1 ); + SendDialogMsg(hWnd, IDC_LATENCY_SLIDER, TBM_SETPOS, TRUE, (int)((pow((double)SndOutLatencyMS, 1.0 / 3.0) * 128.0) + 1)); + swprintf_s(temp, L"%d ms (avg)", SndOutLatencyMS); + SetWindowText(GetDlgItem(hWnd, IDC_LATENCY_LABEL), temp); - SendDialogMsg( hWnd, IDC_VOLUME_SLIDER, TBM_SETPOS, TRUE, configvol ); - swprintf_s(temp,L"%d%%",configvol); - SetWindowText(GetDlgItem(hWnd,IDC_VOLUME_LABEL),temp); - - EnableWindow( GetDlgItem( hWnd, IDC_OPEN_CONFIG_SOUNDTOUCH ), (SynchMode == 0) ); - EnableWindow( GetDlgItem( hWnd, IDC_OPEN_CONFIG_DEBUG ), DebugEnabled ); + int configvol = (int)(FinalVolume * 100 + 0.5f); + INIT_SLIDER(IDC_VOLUME_SLIDER, 0, 100, 10, 42, 1); - SET_CHECK(IDC_EFFECTS_DISABLE, EffectsDisabled); - SET_CHECK(IDC_DEALIASFILTER, postprocess_filter_dealias); - SET_CHECK(IDC_DEBUG_ENABLE, DebugEnabled); - SET_CHECK(IDC_DSP_ENABLE, dspPluginEnabled); - } - break; + SendDialogMsg(hWnd, IDC_VOLUME_SLIDER, TBM_SETPOS, TRUE, configvol); + swprintf_s(temp, L"%d%%", configvol); + SetWindowText(GetDlgItem(hWnd, IDC_VOLUME_LABEL), temp); - case WM_COMMAND: - wmId = LOWORD(wParam); - wmEvent = HIWORD(wParam); - // Parse the menu selections: - switch (wmId) - { - case IDOK: - { - double res = ((int)SendDialogMsg( hWnd, IDC_LATENCY_SLIDER, TBM_GETPOS, 0, 0 )) / 128.0; - SndOutLatencyMS = (int)pow( res, 3.0 ); - Clampify( SndOutLatencyMS, LATENCY_MIN, LATENCY_MAX ); - FinalVolume = (float)(SendDialogMsg( hWnd, IDC_VOLUME_SLIDER, TBM_GETPOS, 0, 0 )) / 100; - Interpolation = (int)SendDialogMsg( hWnd, IDC_INTERPOLATE, CB_GETCURSEL,0,0 ); - OutputModule = (int)SendDialogMsg( hWnd, IDC_OUTPUT, CB_GETCURSEL,0,0 ); - SynchMode = (int)SendDialogMsg( hWnd, IDC_SYNCHMODE, CB_GETCURSEL,0,0 ); - numSpeakers = (int)SendDialogMsg( hWnd, IDC_SPEAKERS, CB_GETCURSEL,0,0 ); + EnableWindow(GetDlgItem(hWnd, IDC_OPEN_CONFIG_SOUNDTOUCH), (SynchMode == 0)); + EnableWindow(GetDlgItem(hWnd, IDC_OPEN_CONFIG_DEBUG), DebugEnabled); - WriteSettings(); - EndDialog(hWnd,0); - } - break; + SET_CHECK(IDC_EFFECTS_DISABLE, EffectsDisabled); + SET_CHECK(IDC_DEALIASFILTER, postprocess_filter_dealias); + SET_CHECK(IDC_DEBUG_ENABLE, DebugEnabled); + SET_CHECK(IDC_DSP_ENABLE, dspPluginEnabled); + } break; - case IDCANCEL: - EndDialog(hWnd,0); - break; + case WM_COMMAND: + wmId = LOWORD(wParam); + wmEvent = HIWORD(wParam); + // Parse the menu selections: + switch (wmId) { + case IDOK: { + double res = ((int)SendDialogMsg(hWnd, IDC_LATENCY_SLIDER, TBM_GETPOS, 0, 0)) / 128.0; + SndOutLatencyMS = (int)pow(res, 3.0); + Clampify(SndOutLatencyMS, LATENCY_MIN, LATENCY_MAX); + FinalVolume = (float)(SendDialogMsg(hWnd, IDC_VOLUME_SLIDER, TBM_GETPOS, 0, 0)) / 100; + Interpolation = (int)SendDialogMsg(hWnd, IDC_INTERPOLATE, CB_GETCURSEL, 0, 0); + OutputModule = (int)SendDialogMsg(hWnd, IDC_OUTPUT, CB_GETCURSEL, 0, 0); + SynchMode = (int)SendDialogMsg(hWnd, IDC_SYNCHMODE, CB_GETCURSEL, 0, 0); + numSpeakers = (int)SendDialogMsg(hWnd, IDC_SPEAKERS, CB_GETCURSEL, 0, 0); - case IDC_OUTCONF: - { - const int module = (int)SendMessage(GetDlgItem(hWnd,IDC_OUTPUT),CB_GETCURSEL,0,0); - if( mods[module] == NULL ) break; - mods[module]->Configure((uptr)hWnd); - } - break; + WriteSettings(); + EndDialog(hWnd, 0); + } break; - case IDC_OPEN_CONFIG_DEBUG: - { - // Quick Hack -- DebugEnabled is re-loaded with the DebugConfig's API, - // so we need to override it here: + case IDCANCEL: + EndDialog(hWnd, 0); + break; - bool dbgtmp = DebugEnabled; - DebugConfig::OpenDialog(); - DebugEnabled = dbgtmp; - } - break; + case IDC_OUTCONF: { + const int module = (int)SendMessage(GetDlgItem(hWnd, IDC_OUTPUT), CB_GETCURSEL, 0, 0); + if (mods[module] == NULL) + break; + mods[module]->Configure((uptr)hWnd); + } break; - case IDC_SYNCHMODE: - { - if(wmEvent == CBN_SELCHANGE) - { - int sMode = (int)SendDialogMsg( hWnd, IDC_SYNCHMODE, CB_GETCURSEL,0,0 ); - double minlat = (sMode == 0)?LATENCY_MIN_TS:LATENCY_MIN; - int minexp = (int)(pow( minlat+1, 1.0/3.0 ) * 128.0); - int maxexp = (int)(pow( (double)LATENCY_MAX+2, 1.0/3.0 ) * 128.0); - INIT_SLIDER( IDC_LATENCY_SLIDER, minexp, maxexp, 200, 42, 1 ); - - int curpos = (int)SendMessage(GetDlgItem( hWnd, IDC_LATENCY_SLIDER ),TBM_GETPOS,0,0); - double res = pow( curpos / 128.0, 3.0 ); - curpos = (int)res; - swprintf_s(temp,L"%d ms (avg)",curpos); - SetDlgItemText(hWnd,IDC_LATENCY_LABEL,temp); - bool soundtouch = sMode == 0; - EnableWindow(GetDlgItem(hWnd, IDC_OPEN_CONFIG_SOUNDTOUCH), soundtouch); - } - } - break; + case IDC_OPEN_CONFIG_DEBUG: { + // Quick Hack -- DebugEnabled is re-loaded with the DebugConfig's API, + // so we need to override it here: + + bool dbgtmp = DebugEnabled; + DebugConfig::OpenDialog(); + DebugEnabled = dbgtmp; + } break; + + case IDC_SYNCHMODE: { + if (wmEvent == CBN_SELCHANGE) { + int sMode = (int)SendDialogMsg(hWnd, IDC_SYNCHMODE, CB_GETCURSEL, 0, 0); + double minlat = (sMode == 0) ? LATENCY_MIN_TS : LATENCY_MIN; + int minexp = (int)(pow(minlat + 1, 1.0 / 3.0) * 128.0); + int maxexp = (int)(pow((double)LATENCY_MAX + 2, 1.0 / 3.0) * 128.0); + INIT_SLIDER(IDC_LATENCY_SLIDER, minexp, maxexp, 200, 42, 1); + + int curpos = (int)SendMessage(GetDlgItem(hWnd, IDC_LATENCY_SLIDER), TBM_GETPOS, 0, 0); + double res = pow(curpos / 128.0, 3.0); + curpos = (int)res; + swprintf_s(temp, L"%d ms (avg)", curpos); + SetDlgItemText(hWnd, IDC_LATENCY_LABEL, temp); + bool soundtouch = sMode == 0; + EnableWindow(GetDlgItem(hWnd, IDC_OPEN_CONFIG_SOUNDTOUCH), soundtouch); + } + } break; - case IDC_OPEN_CONFIG_SOUNDTOUCH: - SoundtouchCfg::OpenDialog( hWnd ); - break; + case IDC_OPEN_CONFIG_SOUNDTOUCH: + SoundtouchCfg::OpenDialog(hWnd); + break; - HANDLE_CHECK(IDC_EFFECTS_DISABLE,EffectsDisabled); - HANDLE_CHECK(IDC_DEALIASFILTER,postprocess_filter_dealias); - HANDLE_CHECK(IDC_DSP_ENABLE,dspPluginEnabled); - HANDLE_CHECKNB(IDC_DEBUG_ENABLE,DebugEnabled); - DebugConfig::EnableControls( hWnd ); - EnableWindow( GetDlgItem( hWnd, IDC_OPEN_CONFIG_DEBUG ), DebugEnabled ); - break; + HANDLE_CHECK(IDC_EFFECTS_DISABLE, EffectsDisabled); + HANDLE_CHECK(IDC_DEALIASFILTER, postprocess_filter_dealias); + HANDLE_CHECK(IDC_DSP_ENABLE, dspPluginEnabled); + HANDLE_CHECKNB(IDC_DEBUG_ENABLE, DebugEnabled); + DebugConfig::EnableControls(hWnd); + EnableWindow(GetDlgItem(hWnd, IDC_OPEN_CONFIG_DEBUG), DebugEnabled); + break; - default: - return FALSE; - } - break; + default: + return FALSE; + } + break; - case WM_HSCROLL: - { - wmEvent = LOWORD(wParam); - HWND hwndDlg = (HWND)lParam; + case WM_HSCROLL: { + wmEvent = LOWORD(wParam); + HWND hwndDlg = (HWND)lParam; - // TB_THUMBTRACK passes the curpos in wParam. Other messages - // have to use TBM_GETPOS, so they will override this assignment (see below) + // TB_THUMBTRACK passes the curpos in wParam. Other messages + // have to use TBM_GETPOS, so they will override this assignment (see below) - int curpos = HIWORD( wParam ); + int curpos = HIWORD(wParam); - switch( wmEvent ) - { - //case TB_ENDTRACK: - //case TB_THUMBPOSITION: - case TB_LINEUP: - case TB_LINEDOWN: - case TB_PAGEUP: - case TB_PAGEDOWN: - curpos = (int)SendMessage(hwndDlg,TBM_GETPOS,0,0); + switch (wmEvent) { + //case TB_ENDTRACK: + //case TB_THUMBPOSITION: + case TB_LINEUP: + case TB_LINEDOWN: + case TB_PAGEUP: + case TB_PAGEDOWN: + curpos = (int)SendMessage(hwndDlg, TBM_GETPOS, 0, 0); - case TB_THUMBTRACK: - Clampify( curpos, - (int)SendMessage(hwndDlg,TBM_GETRANGEMIN,0,0), - (int)SendMessage(hwndDlg,TBM_GETRANGEMAX,0,0) - ); + case TB_THUMBTRACK: + Clampify(curpos, + (int)SendMessage(hwndDlg, TBM_GETRANGEMIN, 0, 0), + (int)SendMessage(hwndDlg, TBM_GETRANGEMAX, 0, 0)); - SendMessage((HWND)lParam,TBM_SETPOS,TRUE,curpos); + SendMessage((HWND)lParam, TBM_SETPOS, TRUE, curpos); - if( hwndDlg == GetDlgItem( hWnd, IDC_LATENCY_SLIDER ) ) - { - double res = pow( curpos / 128.0, 3.0 ); - curpos = (int)res; - swprintf_s(temp,L"%d ms (avg)",curpos); - SetDlgItemText(hWnd,IDC_LATENCY_LABEL,temp); - } - - if( hwndDlg == GetDlgItem( hWnd, IDC_VOLUME_SLIDER ) ) - { - swprintf_s(temp,L"%d%%",curpos); - SetDlgItemText(hWnd,IDC_VOLUME_LABEL,temp); - } - break; + if (hwndDlg == GetDlgItem(hWnd, IDC_LATENCY_SLIDER)) { + double res = pow(curpos / 128.0, 3.0); + curpos = (int)res; + swprintf_s(temp, L"%d ms (avg)", curpos); + SetDlgItemText(hWnd, IDC_LATENCY_LABEL, temp); + } - default: - return FALSE; - } - } - break; + if (hwndDlg == GetDlgItem(hWnd, IDC_VOLUME_SLIDER)) { + swprintf_s(temp, L"%d%%", curpos); + SetDlgItemText(hWnd, IDC_VOLUME_LABEL, temp); + } + break; - default: - return FALSE; - } - return TRUE; + default: + return FALSE; + } + } break; + + default: + return FALSE; + } + return TRUE; } void configure() { - INT_PTR ret; - ReadSettings(); - ret = DialogBoxParam(hInstance,MAKEINTRESOURCE(IDD_CONFIG),GetActiveWindow(),(DLGPROC)ConfigProc,1); - if(ret==-1) - { - MessageBox(GetActiveWindow(),L"Error Opening the config dialog.",L"OMG ERROR!",MB_OK | MB_SETFOREGROUND); - return; - } - ReadSettings(); + INT_PTR ret; + ReadSettings(); + ret = DialogBoxParam(hInstance, MAKEINTRESOURCE(IDD_CONFIG), GetActiveWindow(), (DLGPROC)ConfigProc, 1); + if (ret == -1) { + MessageBox(GetActiveWindow(), L"Error Opening the config dialog.", L"OMG ERROR!", MB_OK | MB_SETFOREGROUND); + return; + } + ReadSettings(); } diff --git a/plugins/spu2-x/src/Windows/ConfigDebug.cpp b/plugins/spu2-x/src/Windows/ConfigDebug.cpp index 69f4c2de2e..765e0f89b4 100644 --- a/plugins/spu2-x/src/Windows/ConfigDebug.cpp +++ b/plugins/spu2-x/src/Windows/ConfigDebug.cpp @@ -20,24 +20,24 @@ #include "Utilities\Path.h" -bool DebugEnabled=false; -bool _MsgToConsole=false; -bool _MsgKeyOnOff=false; -bool _MsgVoiceOff=false; -bool _MsgDMA=false; -bool _MsgAutoDMA=false; -bool _MsgOverruns=false; -bool _MsgCache=false; +bool DebugEnabled = false; +bool _MsgToConsole = false; +bool _MsgKeyOnOff = false; +bool _MsgVoiceOff = false; +bool _MsgDMA = false; +bool _MsgAutoDMA = false; +bool _MsgOverruns = false; +bool _MsgCache = false; -bool _AccessLog=false; -bool _DMALog=false; -bool _WaveLog=false; +bool _AccessLog = false; +bool _DMALog = false; +bool _WaveLog = false; -bool _CoresDump=false; -bool _MemDump=false; -bool _RegDump=false; +bool _CoresDump = false; +bool _MemDump = false; +bool _RegDump = false; -bool _visual_debug_enabled=false; +bool _visual_debug_enabled = false; // this is set true if PCSX2 invokes the SetLogDir callback, which tells SPU2-X to use that over // the configured crap in the ini file. @@ -57,220 +57,213 @@ wxString CoresDumpFileName; wxString MemDumpFileName; wxString RegDumpFileName; -void CfgSetLogDir( const char* dir ) +void CfgSetLogDir(const char *dir) { - LogsFolder = (dir==NULL) ? wxString(L"logs") : wxString(dir, wxConvFile); - DumpsFolder = (dir==NULL) ? wxString(L"logs") : wxString(dir, wxConvFile); - LogLocationSetByPcsx2 = (dir!=NULL); + LogsFolder = (dir == NULL) ? wxString(L"logs") : wxString(dir, wxConvFile); + DumpsFolder = (dir == NULL) ? wxString(L"logs") : wxString(dir, wxConvFile); + LogLocationSetByPcsx2 = (dir != NULL); } -FILE* OpenBinaryLog( const wxString& logfile ) +FILE *OpenBinaryLog(const wxString &logfile) { - return wxFopen( Path::Combine(LogsFolder, logfile), L"wb" ); + return wxFopen(Path::Combine(LogsFolder, logfile), L"wb"); } -FILE* OpenLog( const wxString& logfile ) +FILE *OpenLog(const wxString &logfile) { - return wxFopen( Path::Combine(LogsFolder, logfile), L"w" ); + return wxFopen(Path::Combine(LogsFolder, logfile), L"w"); } -FILE* OpenDump( const wxString& logfile ) +FILE *OpenDump(const wxString &logfile) { - return wxFopen( Path::Combine(DumpsFolder, logfile), L"w" ); + return wxFopen(Path::Combine(DumpsFolder, logfile), L"w"); } -namespace DebugConfig { +namespace DebugConfig +{ -static const wxChar* Section = L"DEBUG"; +static const wxChar *Section = L"DEBUG"; void ReadSettings() { - DebugEnabled = CfgReadBool(Section, L"Global_Enable",0); - _MsgToConsole= CfgReadBool(Section, L"Show_Messages",0); - _MsgKeyOnOff = CfgReadBool(Section, L"Show_Messages_Key_On_Off",0); - _MsgVoiceOff = CfgReadBool(Section, L"Show_Messages_Voice_Off",0); - _MsgDMA = CfgReadBool(Section, L"Show_Messages_DMA_Transfer",0); - _MsgAutoDMA = CfgReadBool(Section, L"Show_Messages_AutoDMA",0); - _MsgOverruns = CfgReadBool(Section, L"Show_Messages_Overruns",0); - _MsgCache = CfgReadBool(Section, L"Show_Messages_CacheStats",0); + DebugEnabled = CfgReadBool(Section, L"Global_Enable", 0); + _MsgToConsole = CfgReadBool(Section, L"Show_Messages", 0); + _MsgKeyOnOff = CfgReadBool(Section, L"Show_Messages_Key_On_Off", 0); + _MsgVoiceOff = CfgReadBool(Section, L"Show_Messages_Voice_Off", 0); + _MsgDMA = CfgReadBool(Section, L"Show_Messages_DMA_Transfer", 0); + _MsgAutoDMA = CfgReadBool(Section, L"Show_Messages_AutoDMA", 0); + _MsgOverruns = CfgReadBool(Section, L"Show_Messages_Overruns", 0); + _MsgCache = CfgReadBool(Section, L"Show_Messages_CacheStats", 0); - _AccessLog = CfgReadBool(Section, L"Log_Register_Access",0); - _DMALog = CfgReadBool(Section, L"Log_DMA_Transfers",0); - _WaveLog = CfgReadBool(Section, L"Log_WAVE_Output",0); + _AccessLog = CfgReadBool(Section, L"Log_Register_Access", 0); + _DMALog = CfgReadBool(Section, L"Log_DMA_Transfers", 0); + _WaveLog = CfgReadBool(Section, L"Log_WAVE_Output", 0); - _CoresDump = CfgReadBool(Section, L"Dump_Info",0); - _MemDump = CfgReadBool(Section, L"Dump_Memory",0); - _RegDump = CfgReadBool(Section, L"Dump_Regs",0); + _CoresDump = CfgReadBool(Section, L"Dump_Info", 0); + _MemDump = CfgReadBool(Section, L"Dump_Memory", 0); + _RegDump = CfgReadBool(Section, L"Dump_Regs", 0); - _visual_debug_enabled = CfgReadBool(Section, L"Visual_Debug_Enabled",0); + _visual_debug_enabled = CfgReadBool(Section, L"Visual_Debug_Enabled", 0); - CfgReadStr(Section,L"Logs_Folder", CfgLogsFolder, L"logs"); - CfgReadStr(Section,L"Dumps_Folder",CfgDumpsFolder,L"logs"); + CfgReadStr(Section, L"Logs_Folder", CfgLogsFolder, L"logs"); + CfgReadStr(Section, L"Dumps_Folder", CfgDumpsFolder, L"logs"); - CfgReadStr(Section,L"Access_Log_Filename",AccessLogFileName, L"SPU2Log.txt"); - CfgReadStr(Section,L"DMA4Log_Filename", DMA4LogFileName, L"SPU2dma4.dat"); - CfgReadStr(Section,L"DMA7Log_Filename", DMA7LogFileName, L"SPU2dma7.dat"); + CfgReadStr(Section, L"Access_Log_Filename", AccessLogFileName, L"SPU2Log.txt"); + CfgReadStr(Section, L"DMA4Log_Filename", DMA4LogFileName, L"SPU2dma4.dat"); + CfgReadStr(Section, L"DMA7Log_Filename", DMA7LogFileName, L"SPU2dma7.dat"); - CfgReadStr(Section,L"Info_Dump_Filename", CoresDumpFileName, L"SPU2Cores.txt"); - CfgReadStr(Section,L"Mem_Dump_Filename", MemDumpFileName, L"SPU2mem.dat"); - CfgReadStr(Section,L"Reg_Dump_Filename", RegDumpFileName, L"SPU2regs.dat"); + CfgReadStr(Section, L"Info_Dump_Filename", CoresDumpFileName, L"SPU2Cores.txt"); + CfgReadStr(Section, L"Mem_Dump_Filename", MemDumpFileName, L"SPU2mem.dat"); + CfgReadStr(Section, L"Reg_Dump_Filename", RegDumpFileName, L"SPU2regs.dat"); - if( !LogLocationSetByPcsx2 ) - { - LogsFolder = CfgLogsFolder; - DumpsFolder = CfgLogsFolder; - } + if (!LogLocationSetByPcsx2) { + LogsFolder = CfgLogsFolder; + DumpsFolder = CfgLogsFolder; + } } void WriteSettings() { - CfgWriteBool(Section,L"Global_Enable",DebugEnabled); + CfgWriteBool(Section, L"Global_Enable", DebugEnabled); - CfgWriteBool(Section,L"Show_Messages", _MsgToConsole); - CfgWriteBool(Section,L"Show_Messages_Key_On_Off", _MsgKeyOnOff); - CfgWriteBool(Section,L"Show_Messages_Voice_Off", _MsgVoiceOff); - CfgWriteBool(Section,L"Show_Messages_DMA_Transfer",_MsgDMA); - CfgWriteBool(Section,L"Show_Messages_AutoDMA", _MsgAutoDMA); - CfgWriteBool(Section,L"Show_Messages_Overruns", _MsgOverruns); - CfgWriteBool(Section,L"Show_Messages_CacheStats", _MsgCache); + CfgWriteBool(Section, L"Show_Messages", _MsgToConsole); + CfgWriteBool(Section, L"Show_Messages_Key_On_Off", _MsgKeyOnOff); + CfgWriteBool(Section, L"Show_Messages_Voice_Off", _MsgVoiceOff); + CfgWriteBool(Section, L"Show_Messages_DMA_Transfer", _MsgDMA); + CfgWriteBool(Section, L"Show_Messages_AutoDMA", _MsgAutoDMA); + CfgWriteBool(Section, L"Show_Messages_Overruns", _MsgOverruns); + CfgWriteBool(Section, L"Show_Messages_CacheStats", _MsgCache); - CfgWriteBool(Section,L"Log_Register_Access",_AccessLog); - CfgWriteBool(Section,L"Log_DMA_Transfers", _DMALog); - CfgWriteBool(Section,L"Log_WAVE_Output", _WaveLog); + CfgWriteBool(Section, L"Log_Register_Access", _AccessLog); + CfgWriteBool(Section, L"Log_DMA_Transfers", _DMALog); + CfgWriteBool(Section, L"Log_WAVE_Output", _WaveLog); - CfgWriteBool(Section,L"Dump_Info", _CoresDump); - CfgWriteBool(Section,L"Dump_Memory",_MemDump); - CfgWriteBool(Section,L"Dump_Regs", _RegDump); + CfgWriteBool(Section, L"Dump_Info", _CoresDump); + CfgWriteBool(Section, L"Dump_Memory", _MemDump); + CfgWriteBool(Section, L"Dump_Regs", _RegDump); - CfgWriteBool(Section,L"Visual_Debug_Enabled", _visual_debug_enabled); + CfgWriteBool(Section, L"Visual_Debug_Enabled", _visual_debug_enabled); - // None of the logs strings are changable via GUI, so no point in bothering to - // write them back out. - CfgWriteStr(Section,L"Logs_Folder", CfgLogsFolder); - CfgWriteStr(Section,L"Dumps_Folder",CfgDumpsFolder); + // None of the logs strings are changable via GUI, so no point in bothering to + // write them back out. + CfgWriteStr(Section, L"Logs_Folder", CfgLogsFolder); + CfgWriteStr(Section, L"Dumps_Folder", CfgDumpsFolder); - CfgWriteStr(Section,L"Access_Log_Filename",AccessLogFileName); - CfgWriteStr(Section,L"DMA4Log_Filename", DMA4LogFileName); - CfgWriteStr(Section,L"DMA7Log_Filename", DMA7LogFileName); + CfgWriteStr(Section, L"Access_Log_Filename", AccessLogFileName); + CfgWriteStr(Section, L"DMA4Log_Filename", DMA4LogFileName); + CfgWriteStr(Section, L"DMA7Log_Filename", DMA7LogFileName); - CfgWriteStr(Section,L"Info_Dump_Filename",CoresDumpFileName); - CfgWriteStr(Section,L"Mem_Dump_Filename", MemDumpFileName); - CfgWriteStr(Section,L"Reg_Dump_Filename", RegDumpFileName); + CfgWriteStr(Section, L"Info_Dump_Filename", CoresDumpFileName); + CfgWriteStr(Section, L"Mem_Dump_Filename", MemDumpFileName); + CfgWriteStr(Section, L"Reg_Dump_Filename", RegDumpFileName); } -static void EnableMessages( HWND hWnd ) +static void EnableMessages(HWND hWnd) { - ENABLE_CONTROL(IDC_MSGSHOW, DebugEnabled); - ENABLE_CONTROL(IDC_MSGKEY, MsgToConsole()); - ENABLE_CONTROL(IDC_MSGVOICE,MsgToConsole()); - ENABLE_CONTROL(IDC_MSGDMA, MsgToConsole()); - ENABLE_CONTROL(IDC_MSGADMA, MsgToConsole()); - ENABLE_CONTROL(IDC_DBG_OVERRUNS, MsgToConsole()); - ENABLE_CONTROL(IDC_DBG_CACHE, MsgToConsole()); + ENABLE_CONTROL(IDC_MSGSHOW, DebugEnabled); + ENABLE_CONTROL(IDC_MSGKEY, MsgToConsole()); + ENABLE_CONTROL(IDC_MSGVOICE, MsgToConsole()); + ENABLE_CONTROL(IDC_MSGDMA, MsgToConsole()); + ENABLE_CONTROL(IDC_MSGADMA, MsgToConsole()); + ENABLE_CONTROL(IDC_DBG_OVERRUNS, MsgToConsole()); + ENABLE_CONTROL(IDC_DBG_CACHE, MsgToConsole()); } -void EnableControls( HWND hWnd ) +void EnableControls(HWND hWnd) { - EnableMessages( hWnd ); - ENABLE_CONTROL(IDC_LOGDMA, DebugEnabled); - ENABLE_CONTROL(IDC_LOGREGS, IsDevBuild ? DebugEnabled : false); - ENABLE_CONTROL(IDC_LOGWAVE, IsDevBuild ? DebugEnabled : false); - ENABLE_CONTROL(IDC_DUMPCORE,DebugEnabled); - ENABLE_CONTROL(IDC_DUMPMEM, DebugEnabled); - ENABLE_CONTROL(IDC_DUMPREGS,DebugEnabled); - ENABLE_CONTROL(IDC_DEBUG_VISUAL, IsDevBuild ? DebugEnabled : false); + EnableMessages(hWnd); + ENABLE_CONTROL(IDC_LOGDMA, DebugEnabled); + ENABLE_CONTROL(IDC_LOGREGS, IsDevBuild ? DebugEnabled : false); + ENABLE_CONTROL(IDC_LOGWAVE, IsDevBuild ? DebugEnabled : false); + ENABLE_CONTROL(IDC_DUMPCORE, DebugEnabled); + ENABLE_CONTROL(IDC_DUMPMEM, DebugEnabled); + ENABLE_CONTROL(IDC_DUMPREGS, DebugEnabled); + ENABLE_CONTROL(IDC_DEBUG_VISUAL, IsDevBuild ? DebugEnabled : false); } -static BOOL CALLBACK DialogProc(HWND hWnd,UINT uMsg,WPARAM wParam,LPARAM lParam) +static BOOL CALLBACK DialogProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { - int wmId; - //wchar_t temp[384]={0}; + int wmId; + //wchar_t temp[384]={0}; - switch(uMsg) - { - case WM_PAINT: - return FALSE; + switch (uMsg) { + case WM_PAINT: + return FALSE; - case WM_INITDIALOG: - { - EnableControls( hWnd ); + case WM_INITDIALOG: { + EnableControls(hWnd); - // Debugging / Logging Flags: - SET_CHECK(IDC_DEBUG, DebugEnabled); - SET_CHECK(IDC_MSGSHOW, _MsgToConsole); - SET_CHECK(IDC_MSGKEY, _MsgKeyOnOff); - SET_CHECK(IDC_MSGVOICE,_MsgVoiceOff); - SET_CHECK(IDC_MSGDMA, _MsgDMA); - SET_CHECK(IDC_MSGADMA, _MsgAutoDMA); - SET_CHECK(IDC_DBG_OVERRUNS, _MsgOverruns ); - SET_CHECK(IDC_DBG_CACHE, _MsgCache ); - SET_CHECK(IDC_LOGREGS, _AccessLog); - SET_CHECK(IDC_LOGDMA, _DMALog); - SET_CHECK(IDC_LOGWAVE, _WaveLog); - SET_CHECK(IDC_DUMPCORE,_CoresDump); - SET_CHECK(IDC_DUMPMEM, _MemDump); - SET_CHECK(IDC_DUMPREGS,_RegDump); - SET_CHECK(IDC_DEBUG_VISUAL,_visual_debug_enabled); + // Debugging / Logging Flags: + SET_CHECK(IDC_DEBUG, DebugEnabled); + SET_CHECK(IDC_MSGSHOW, _MsgToConsole); + SET_CHECK(IDC_MSGKEY, _MsgKeyOnOff); + SET_CHECK(IDC_MSGVOICE, _MsgVoiceOff); + SET_CHECK(IDC_MSGDMA, _MsgDMA); + SET_CHECK(IDC_MSGADMA, _MsgAutoDMA); + SET_CHECK(IDC_DBG_OVERRUNS, _MsgOverruns); + SET_CHECK(IDC_DBG_CACHE, _MsgCache); + SET_CHECK(IDC_LOGREGS, _AccessLog); + SET_CHECK(IDC_LOGDMA, _DMALog); + SET_CHECK(IDC_LOGWAVE, _WaveLog); + SET_CHECK(IDC_DUMPCORE, _CoresDump); + SET_CHECK(IDC_DUMPMEM, _MemDump); + SET_CHECK(IDC_DUMPREGS, _RegDump); + SET_CHECK(IDC_DEBUG_VISUAL, _visual_debug_enabled); - ShowWindow( GetDlgItem( hWnd, IDC_MSG_PUBLIC_BUILD ), !IsDevBuild ); - } - break; + ShowWindow(GetDlgItem(hWnd, IDC_MSG_PUBLIC_BUILD), !IsDevBuild); + } break; - case WM_COMMAND: - wmId = LOWORD(wParam); - // Parse the menu selections: - switch (wmId) - { - case IDOK: - WriteSettings(); - EndDialog(hWnd,0); - break; + case WM_COMMAND: + wmId = LOWORD(wParam); + // Parse the menu selections: + switch (wmId) { + case IDOK: + WriteSettings(); + EndDialog(hWnd, 0); + break; - case IDCANCEL: - EndDialog(hWnd,0); - break; + case IDCANCEL: + EndDialog(hWnd, 0); + break; - HANDLE_CHECKNB(IDC_MSGSHOW,_MsgToConsole); - EnableMessages( hWnd ); - break; + HANDLE_CHECKNB(IDC_MSGSHOW, _MsgToConsole); + EnableMessages(hWnd); + break; - HANDLE_CHECK(IDC_MSGKEY,_MsgKeyOnOff); - HANDLE_CHECK(IDC_MSGVOICE,_MsgVoiceOff); - HANDLE_CHECK(IDC_MSGDMA,_MsgDMA); - HANDLE_CHECK(IDC_MSGADMA,_MsgAutoDMA); - break; + HANDLE_CHECK(IDC_MSGKEY, _MsgKeyOnOff); + HANDLE_CHECK(IDC_MSGVOICE, _MsgVoiceOff); + HANDLE_CHECK(IDC_MSGDMA, _MsgDMA); + HANDLE_CHECK(IDC_MSGADMA, _MsgAutoDMA); + break; - HANDLE_CHECK(IDC_DBG_OVERRUNS,_MsgOverruns); - HANDLE_CHECK(IDC_DBG_CACHE,_MsgCache); - HANDLE_CHECK(IDC_LOGREGS,_AccessLog); - HANDLE_CHECK(IDC_LOGDMA, _DMALog); - HANDLE_CHECK(IDC_LOGWAVE,_WaveLog); - HANDLE_CHECK(IDC_DUMPCORE,_CoresDump); - HANDLE_CHECK(IDC_DUMPMEM, _MemDump); - HANDLE_CHECK(IDC_DUMPREGS,_RegDump); - HANDLE_CHECK(IDC_DEBUG_VISUAL,_visual_debug_enabled); - default: - return FALSE; - } - break; - - default: - return FALSE; - } - return TRUE; + HANDLE_CHECK(IDC_DBG_OVERRUNS, _MsgOverruns); + HANDLE_CHECK(IDC_DBG_CACHE, _MsgCache); + HANDLE_CHECK(IDC_LOGREGS, _AccessLog); + HANDLE_CHECK(IDC_LOGDMA, _DMALog); + HANDLE_CHECK(IDC_LOGWAVE, _WaveLog); + HANDLE_CHECK(IDC_DUMPCORE, _CoresDump); + HANDLE_CHECK(IDC_DUMPMEM, _MemDump); + HANDLE_CHECK(IDC_DUMPREGS, _RegDump); + HANDLE_CHECK(IDC_DEBUG_VISUAL, _visual_debug_enabled); + default: + return FALSE; + } + break; + default: + return FALSE; + } + return TRUE; } void OpenDialog() { - INT_PTR ret = DialogBoxParam(hInstance,MAKEINTRESOURCE(IDD_CONFIG_DEBUG),GetActiveWindow(),(DLGPROC)DialogProc,1); - if(ret == -1) - { - MessageBox(GetActiveWindow(),L"Error Opening the debug configuration dialog.",L"OMG ERROR!",MB_OK | MB_SETFOREGROUND); - return; - } - ReadSettings(); + INT_PTR ret = DialogBoxParam(hInstance, MAKEINTRESOURCE(IDD_CONFIG_DEBUG), GetActiveWindow(), (DLGPROC)DialogProc, 1); + if (ret == -1) { + MessageBox(GetActiveWindow(), L"Error Opening the debug configuration dialog.", L"OMG ERROR!", MB_OK | MB_SETFOREGROUND); + return; + } + ReadSettings(); } - } diff --git a/plugins/spu2-x/src/Windows/ConfigSoundtouch.cpp b/plugins/spu2-x/src/Windows/ConfigSoundtouch.cpp index f23d6a4d91..ec19b402da 100644 --- a/plugins/spu2-x/src/Windows/ConfigSoundtouch.cpp +++ b/plugins/spu2-x/src/Windows/ConfigSoundtouch.cpp @@ -34,106 +34,98 @@ static const int SeekWindow_Max = 30; static const int Overlap_Min = 5; static const int Overlap_Max = 15; -void SoundtouchCfg::ApplySettings( soundtouch::SoundTouch& sndtouch ) +void SoundtouchCfg::ApplySettings(soundtouch::SoundTouch &sndtouch) { - sndtouch.setSetting( SETTING_SEQUENCE_MS, SequenceLenMS ); - sndtouch.setSetting( SETTING_SEEKWINDOW_MS, SeekWindowMS ); - sndtouch.setSetting( SETTING_OVERLAP_MS, OverlapMS ); + sndtouch.setSetting(SETTING_SEQUENCE_MS, SequenceLenMS); + sndtouch.setSetting(SETTING_SEEKWINDOW_MS, SeekWindowMS); + sndtouch.setSetting(SETTING_OVERLAP_MS, OverlapMS); } static void ClampValues() { - Clampify( SequenceLenMS, SequenceLen_Min, SequenceLen_Max ); - Clampify( SeekWindowMS, SeekWindow_Min, SeekWindow_Max ); - Clampify( OverlapMS, Overlap_Min, Overlap_Max ); + Clampify(SequenceLenMS, SequenceLen_Min, SequenceLen_Max); + Clampify(SeekWindowMS, SeekWindow_Min, SeekWindow_Max); + Clampify(OverlapMS, Overlap_Min, Overlap_Max); } void SoundtouchCfg::ReadSettings() { - SequenceLenMS = CfgReadInt( L"SOUNDTOUCH", L"SequenceLengthMS", 30 ); - SeekWindowMS = CfgReadInt( L"SOUNDTOUCH", L"SeekWindowMS", 20 ); - OverlapMS = CfgReadInt( L"SOUNDTOUCH", L"OverlapMS", 10 ); + SequenceLenMS = CfgReadInt(L"SOUNDTOUCH", L"SequenceLengthMS", 30); + SeekWindowMS = CfgReadInt(L"SOUNDTOUCH", L"SeekWindowMS", 20); + OverlapMS = CfgReadInt(L"SOUNDTOUCH", L"OverlapMS", 10); - ClampValues(); + ClampValues(); } void SoundtouchCfg::WriteSettings() { - CfgWriteInt( L"SOUNDTOUCH", L"SequenceLengthMS", SequenceLenMS ); - CfgWriteInt( L"SOUNDTOUCH", L"SeekWindowMS", SeekWindowMS ); - CfgWriteInt( L"SOUNDTOUCH", L"OverlapMS", OverlapMS ); + CfgWriteInt(L"SOUNDTOUCH", L"SequenceLengthMS", SequenceLenMS); + CfgWriteInt(L"SOUNDTOUCH", L"SeekWindowMS", SeekWindowMS); + CfgWriteInt(L"SOUNDTOUCH", L"OverlapMS", OverlapMS); } -BOOL CALLBACK SoundtouchCfg::DialogProc(HWND hWnd,UINT uMsg,WPARAM wParam,LPARAM lParam) +BOOL CALLBACK SoundtouchCfg::DialogProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { - int wmId; - //wchar_t temp[384]={0}; + int wmId; + //wchar_t temp[384]={0}; - switch(uMsg) - { - case WM_PAINT: - return FALSE; + switch (uMsg) { + case WM_PAINT: + return FALSE; - case WM_INITDIALOG: - { - INIT_SLIDER( IDC_SEQLEN_SLIDER, SequenceLen_Min, SequenceLen_Max, 20, 5, 1 ); - INIT_SLIDER( IDC_SEEKWIN_SLIDER, SeekWindow_Min, SeekWindow_Max, 5, 2, 1 ); - INIT_SLIDER( IDC_OVERLAP_SLIDER, Overlap_Min, Overlap_Max, 3, 2, 1 ); + case WM_INITDIALOG: { + INIT_SLIDER(IDC_SEQLEN_SLIDER, SequenceLen_Min, SequenceLen_Max, 20, 5, 1); + INIT_SLIDER(IDC_SEEKWIN_SLIDER, SeekWindow_Min, SeekWindow_Max, 5, 2, 1); + INIT_SLIDER(IDC_OVERLAP_SLIDER, Overlap_Min, Overlap_Max, 3, 2, 1); - SendDialogMsg( hWnd, IDC_SEQLEN_SLIDER, TBM_SETPOS, TRUE, SequenceLenMS ); - SendDialogMsg( hWnd, IDC_SEEKWIN_SLIDER, TBM_SETPOS, TRUE, SeekWindowMS ); - SendDialogMsg( hWnd, IDC_OVERLAP_SLIDER, TBM_SETPOS, TRUE, OverlapMS ); - } + SendDialogMsg(hWnd, IDC_SEQLEN_SLIDER, TBM_SETPOS, TRUE, SequenceLenMS); + SendDialogMsg(hWnd, IDC_SEEKWIN_SLIDER, TBM_SETPOS, TRUE, SeekWindowMS); + SendDialogMsg(hWnd, IDC_OVERLAP_SLIDER, TBM_SETPOS, TRUE, OverlapMS); + } - case WM_COMMAND: - wmId = LOWORD(wParam); - // Parse the menu selections: - if( wmId == IDOK ) - { - SequenceLenMS = (int)SendDialogMsg( hWnd, IDC_SEQLEN_SLIDER, TBM_GETPOS, 0, 0 ); - SeekWindowMS = (int)SendDialogMsg( hWnd, IDC_SEEKWIN_SLIDER, TBM_GETPOS, 0, 0 ); - OverlapMS = (int)SendDialogMsg( hWnd, IDC_OVERLAP_SLIDER, TBM_GETPOS, 0, 0 ); + case WM_COMMAND: + wmId = LOWORD(wParam); + // Parse the menu selections: + if (wmId == IDOK) { + SequenceLenMS = (int)SendDialogMsg(hWnd, IDC_SEQLEN_SLIDER, TBM_GETPOS, 0, 0); + SeekWindowMS = (int)SendDialogMsg(hWnd, IDC_SEEKWIN_SLIDER, TBM_GETPOS, 0, 0); + OverlapMS = (int)SendDialogMsg(hWnd, IDC_OVERLAP_SLIDER, TBM_GETPOS, 0, 0); - ClampValues(); - WriteSettings(); - EndDialog(hWnd,0); - } - else if( wmId == IDC_RESET_DEFAULTS ) - { - SequenceLenMS = 30; - SeekWindowMS = 20; - OverlapMS = 10; + ClampValues(); + WriteSettings(); + EndDialog(hWnd, 0); + } else if (wmId == IDC_RESET_DEFAULTS) { + SequenceLenMS = 30; + SeekWindowMS = 20; + OverlapMS = 10; - SendDialogMsg( hWnd, IDC_SEQLEN_SLIDER, TBM_SETPOS, TRUE, SequenceLenMS ); - SendDialogMsg( hWnd, IDC_SEEKWIN_SLIDER, TBM_SETPOS, TRUE, SeekWindowMS ); - SendDialogMsg( hWnd, IDC_OVERLAP_SLIDER, TBM_SETPOS, TRUE, OverlapMS ); + SendDialogMsg(hWnd, IDC_SEQLEN_SLIDER, TBM_SETPOS, TRUE, SequenceLenMS); + SendDialogMsg(hWnd, IDC_SEEKWIN_SLIDER, TBM_SETPOS, TRUE, SeekWindowMS); + SendDialogMsg(hWnd, IDC_OVERLAP_SLIDER, TBM_SETPOS, TRUE, OverlapMS); - AssignSliderValue((HWND)lParam, hWnd, SequenceLenMS); - } - else if( wmId == IDCANCEL ) - { - EndDialog(hWnd,0); - } - break; + AssignSliderValue((HWND)lParam, hWnd, SequenceLenMS); + } else if (wmId == IDCANCEL) { + EndDialog(hWnd, 0); + } + break; - case WM_HSCROLL: - DoHandleScrollMessage( hWnd, wParam, lParam ); - break; + case WM_HSCROLL: + DoHandleScrollMessage(hWnd, wParam, lParam); + break; - default: - return FALSE; - } - return TRUE; + default: + return FALSE; + } + return TRUE; } -void SoundtouchCfg::OpenDialog( HWND hWnd ) +void SoundtouchCfg::OpenDialog(HWND hWnd) { - INT_PTR ret; - ret = DialogBox( hInstance, MAKEINTRESOURCE(IDD_CONFIG_SOUNDTOUCH), hWnd, (DLGPROC)DialogProc ); - if(ret==-1) - { - MessageBox(GetActiveWindow(), L"Error Opening the Soundtouch advanced dialog.", L"OMG ERROR!", MB_OK | MB_SETFOREGROUND); - return; - } - ReadSettings(); + INT_PTR ret; + ret = DialogBox(hInstance, MAKEINTRESOURCE(IDD_CONFIG_SOUNDTOUCH), hWnd, (DLGPROC)DialogProc); + if (ret == -1) { + MessageBox(GetActiveWindow(), L"Error Opening the Soundtouch advanced dialog.", L"OMG ERROR!", MB_OK | MB_SETFOREGROUND); + return; + } + ReadSettings(); } diff --git a/plugins/spu2-x/src/Windows/Dialogs.h b/plugins/spu2-x/src/Windows/Dialogs.h index 6a7d9f5600..94886ebf5f 100644 --- a/plugins/spu2-x/src/Windows/Dialogs.h +++ b/plugins/spu2-x/src/Windows/Dialogs.h @@ -18,61 +18,60 @@ #pragma once #ifdef _WIN32 -# include "WinConfig.h" +#include "WinConfig.h" #else -# include "LnxConfig.h" +#include "LnxConfig.h" #endif namespace DebugConfig { - extern void ReadSettings(); - extern void WriteSettings(); - extern void OpenDialog(); - extern void EnableControls( HWND hWnd ); +extern void ReadSettings(); +extern void WriteSettings(); +extern void OpenDialog(); +extern void EnableControls(HWND hWnd); } namespace SoundtouchCfg { - extern void ReadSettings(); - extern void WriteSettings(); - extern void OpenDialog( HWND hWnd ); - extern BOOL CALLBACK DialogProc(HWND hWnd,UINT uMsg,WPARAM wParam,LPARAM lParam); +extern void ReadSettings(); +extern void WriteSettings(); +extern void OpenDialog(HWND hWnd); +extern BOOL CALLBACK DialogProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam); } -extern int SendDialogMsg( HWND hwnd, int dlgId, UINT code, WPARAM wParam, LPARAM lParam); -extern HRESULT GUIDFromString( const wchar_t *str, LPGUID guid ); +extern int SendDialogMsg(HWND hwnd, int dlgId, UINT code, WPARAM wParam, LPARAM lParam); +extern HRESULT GUIDFromString(const wchar_t *str, LPGUID guid); -extern void AssignSliderValue( HWND idcwnd, HWND hwndDisplay, int value ); -extern void AssignSliderValue( HWND hWnd, int idc, int editbox, int value ); -extern int GetSliderValue( HWND hWnd, int idc ); -extern BOOL DoHandleScrollMessage( HWND hwndDisplay, WPARAM wParam, LPARAM lParam ); +extern void AssignSliderValue(HWND idcwnd, HWND hwndDisplay, int value); +extern void AssignSliderValue(HWND hWnd, int idc, int editbox, int value); +extern int GetSliderValue(HWND hWnd, int idc); +extern BOOL DoHandleScrollMessage(HWND hwndDisplay, WPARAM wParam, LPARAM lParam); -extern void CfgSetSettingsDir( const char* dir ); -extern void CfgSetLogDir( const char* dir ); +extern void CfgSetSettingsDir(const char *dir); +extern void CfgSetLogDir(const char *dir); -extern bool CfgFindName( const TCHAR *Section, const TCHAR* Name); +extern bool CfgFindName(const TCHAR *Section, const TCHAR *Name); -extern void CfgWriteBool(const TCHAR* Section, const TCHAR* Name, bool Value); -extern void CfgWriteInt(const TCHAR* Section, const TCHAR* Name, int Value); -extern void CfgWriteFloat(const TCHAR* Section, const TCHAR* Name, float Value); -extern void CfgWriteStr(const TCHAR* Section, const TCHAR* Name, const wxString& Data); +extern void CfgWriteBool(const TCHAR *Section, const TCHAR *Name, bool Value); +extern void CfgWriteInt(const TCHAR *Section, const TCHAR *Name, int Value); +extern void CfgWriteFloat(const TCHAR *Section, const TCHAR *Name, float Value); +extern void CfgWriteStr(const TCHAR *Section, const TCHAR *Name, const wxString &Data); -extern bool CfgReadBool(const TCHAR *Section,const TCHAR* Name, bool Default); -extern void CfgReadStr(const TCHAR* Section, const TCHAR* Name, wxString& Data, const TCHAR* Default); -extern void CfgReadStr(const TCHAR* Section, const TCHAR* Name, TCHAR* Data, int DataSize, const TCHAR* Default); -extern int CfgReadInt(const TCHAR* Section, const TCHAR* Name, int Default); -extern float CfgReadFloat(const TCHAR* Section, const TCHAR* Name, float Default); +extern bool CfgReadBool(const TCHAR *Section, const TCHAR *Name, bool Default); +extern void CfgReadStr(const TCHAR *Section, const TCHAR *Name, wxString &Data, const TCHAR *Default); +extern void CfgReadStr(const TCHAR *Section, const TCHAR *Name, TCHAR *Data, int DataSize, const TCHAR *Default); +extern int CfgReadInt(const TCHAR *Section, const TCHAR *Name, int Default); +extern float CfgReadFloat(const TCHAR *Section, const TCHAR *Name, float Default); // Items Specific to DirectSound #define STRFY(x) #x -#define verifyc(x) Verifyc(x,STRFY(x)) +#define verifyc(x) Verifyc(x, STRFY(x)) -extern void Verifyc(HRESULT hr, const char* fn); +extern void Verifyc(HRESULT hr, const char *fn); struct ds_device_data { - wxString name; - GUID guid; - bool hasGuid; + wxString name; + GUID guid; + bool hasGuid; }; - diff --git a/plugins/spu2-x/src/Windows/RealtimeDebugger.cpp b/plugins/spu2-x/src/Windows/RealtimeDebugger.cpp index 64be714416..8151344863 100644 --- a/plugins/spu2-x/src/Windows/RealtimeDebugger.cpp +++ b/plugins/spu2-x/src/Windows/RealtimeDebugger.cpp @@ -18,75 +18,72 @@ #include "Global.h" #include "Dialogs.h" -bool debugDialogOpen=false; -HWND hDebugDialog=NULL; +bool debugDialogOpen = false; +HWND hDebugDialog = NULL; #ifdef PCSX2_DEVBUILD int FillRectangle(HDC dc, int left, int top, int width, int height) { - RECT r = { left, top, left+width, top+height }; + RECT r = {left, top, left + width, top + height}; - return FillRect(dc, &r, (HBRUSH)GetStockObject(DC_BRUSH)); + return FillRect(dc, &r, (HBRUSH)GetStockObject(DC_BRUSH)); } BOOL DrawRectangle(HDC dc, int left, int top, int width, int height) { - RECT r = { left, top, left+width, top+height }; + RECT r = {left, top, left + width, top + height}; - POINT p[5] = { - { r.left, r.top }, - { r.right, r.top }, - { r.right, r.bottom }, - { r.left, r.bottom }, - { r.left, r.top }, - }; + POINT p[5] = { + {r.left, r.top}, + {r.right, r.top}, + {r.right, r.bottom}, + {r.left, r.bottom}, + {r.left, r.top}, + }; - return Polyline(dc, p, 5); + return Polyline(dc, p, 5); } HFONT hf = NULL; -int lCount=0; +int lCount = 0; void UpdateDebugDialog() { - if(!debugDialogOpen) return; + if (!debugDialogOpen) + return; - lCount++; - if(lCount>=(SampleRate/100)) // Increase to SampleRate/200 for smooth display. - { - HDC hdc = GetDC(hDebugDialog); + lCount++; + if (lCount >= (SampleRate / 100)) // Increase to SampleRate/200 for smooth display. + { + HDC hdc = GetDC(hDebugDialog); - if(!hf) - { - hf = CreateFont( 12, 0, 0, 0, 0, FALSE, FALSE, FALSE, ANSI_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, - DEFAULT_QUALITY, DEFAULT_PITCH | FF_SWISS, L"Lucida Console" ); - } + if (!hf) { + hf = CreateFont(12, 0, 0, 0, 0, FALSE, FALSE, FALSE, ANSI_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, + DEFAULT_QUALITY, DEFAULT_PITCH | FF_SWISS, L"Lucida Console"); + } - SelectObject(hdc,hf); - SelectObject(hdc,GetStockObject(DC_BRUSH)); - SelectObject(hdc,GetStockObject(DC_PEN)); + SelectObject(hdc, hf); + SelectObject(hdc, GetStockObject(DC_BRUSH)); + SelectObject(hdc, GetStockObject(DC_PEN)); - for(int c=0;c<2;c++) - { - V_Core& cx(Cores[c]); - V_CoreDebug& cd(DebugCores[c]); + for (int c = 0; c < 2; c++) { + V_Core &cx(Cores[c]); + V_CoreDebug &cd(DebugCores[c]); - for(int v=0;v<24;v++) - { - int cc = c*2 + (v/12); - int vv = v % 12; - int IX = 8+128*cc; - int IY = 8+ 48*vv; - V_Voice& vc(cx.Voices[v]); - V_VoiceDebug& vcd(cd.Voices[v] ); + for (int v = 0; v < 24; v++) { + int cc = c * 2 + (v / 12); + int vv = v % 12; + int IX = 8 + 128 * cc; + int IY = 8 + 48 * vv; + V_Voice &vc(cx.Voices[v]); + V_VoiceDebug &vcd(cd.Voices[v]); - SetDCBrushColor(hdc,RGB( 0, 0, 0)); - if((vc.ADSR.Phase>0)&&(vc.ADSR.Phase<6)) - { - SetDCBrushColor(hdc,RGB( 0, 0,128)); - } - /* + SetDCBrushColor(hdc, RGB(0, 0, 0)); + if ((vc.ADSR.Phase > 0) && (vc.ADSR.Phase < 6)) { + SetDCBrushColor(hdc, RGB(0, 0, 128)); + } + /* else { if(vcd.lastStopReason==1) @@ -99,181 +96,168 @@ void UpdateDebugDialog() } }*/ - FillRectangle(hdc,IX,IY,124,46); + FillRectangle(hdc, IX, IY, 124, 46); - SetDCPenColor(hdc,RGB( 255, 128, 32)); + SetDCPenColor(hdc, RGB(255, 128, 32)); - DrawRectangle(hdc,IX,IY,124,46); + DrawRectangle(hdc, IX, IY, 124, 46); - SetDCBrushColor(hdc,RGB( 0,255, 0)); + SetDCBrushColor(hdc, RGB(0, 255, 0)); - int vl = abs(((vc.Volume.Left.Value >> 16) * 38) >> 15); - int vr = abs(((vc.Volume.Right.Value >> 16) * 38) >> 15); + int vl = abs(((vc.Volume.Left.Value >> 16) * 38) >> 15); + int vr = abs(((vc.Volume.Right.Value >> 16) * 38) >> 15); - FillRectangle(hdc,IX+58,IY+42 - vl, 4, vl); - FillRectangle(hdc,IX+62,IY+42 - vr, 4, vr); + FillRectangle(hdc, IX + 58, IY + 42 - vl, 4, vl); + FillRectangle(hdc, IX + 62, IY + 42 - vr, 4, vr); - int adsr = ((vc.ADSR.Value>>16) * 38) / 32768; + int adsr = ((vc.ADSR.Value >> 16) * 38) / 32768; - FillRectangle(hdc,IX+66,IY+42 - adsr, 4, adsr); + FillRectangle(hdc, IX + 66, IY + 42 - adsr, 4, adsr); - int peak = (vcd.displayPeak * 38) / 32768; + int peak = (vcd.displayPeak * 38) / 32768; - if(vcd.displayPeak >= 32700) // leave a little bit of margin - { - SetDCBrushColor(hdc,RGB( 255, 0, 0)); - } + if (vcd.displayPeak >= 32700) // leave a little bit of margin + { + SetDCBrushColor(hdc, RGB(255, 0, 0)); + } - FillRectangle(hdc,IX+70,IY+42 - peak, 4, peak); + FillRectangle(hdc, IX + 70, IY + 42 - peak, 4, peak); - if(vc.ADSR.Value>0) - { - if(vc.SBuffer) - for(int i=0;i<28;i++) - { - int val = ((int)vc.SBuffer[i] * 20) / 32768; + if (vc.ADSR.Value > 0) { + if (vc.SBuffer) + for (int i = 0; i < 28; i++) { + int val = ((int)vc.SBuffer[i] * 20) / 32768; - int y=0; + int y = 0; - if(val>0) - { - y=val; - } - else - val=-val; - - if(val!=0) - { - FillRectangle(hdc,IX+90+i,IY+24-y, 1, val); - } - } - } + if (val > 0) { + y = val; + } else + val = -val; - SetTextColor(hdc,RGB( 0,255, 0)); - SetBkColor (hdc,RGB( 0, 0, 0)); + if (val != 0) { + FillRectangle(hdc, IX + 90 + i, IY + 24 - y, 1, val); + } + } + } - static wchar_t t[256]; + SetTextColor(hdc, RGB(0, 255, 0)); + SetBkColor(hdc, RGB(0, 0, 0)); - swprintf_s(t,L"%06x",vc.StartA); - TextOut(hdc,IX+4,IY+4,t,6); + static wchar_t t[256]; - swprintf_s(t,L"%06x",vc.NextA); - TextOut(hdc,IX+4,IY+18,t,6); + swprintf_s(t, L"%06x", vc.StartA); + TextOut(hdc, IX + 4, IY + 4, t, 6); - swprintf_s(t,L"%06x",vc.LoopStartA); - TextOut(hdc,IX+4,IY+32,t,6); + swprintf_s(t, L"%06x", vc.NextA); + TextOut(hdc, IX + 4, IY + 18, t, 6); - vcd.displayPeak = 0; - } + swprintf_s(t, L"%06x", vc.LoopStartA); + TextOut(hdc, IX + 4, IY + 32, t, 6); - // top now: 400 - int JX = 8 + c * 256; - int JY = 584; + vcd.displayPeak = 0; + } - SetDCBrushColor(hdc,RGB( 0, 0, 0)); - SetDCPenColor(hdc,RGB( 255, 128, 32)); + // top now: 400 + int JX = 8 + c * 256; + int JY = 584; - FillRectangle(hdc,JX,JY,252,60); - DrawRectangle(hdc,JX,JY,252,60); + SetDCBrushColor(hdc, RGB(0, 0, 0)); + SetDCPenColor(hdc, RGB(255, 128, 32)); - SetTextColor(hdc,RGB(255,255,255)); - SetBkColor (hdc,RGB( 0, 0, 0)); + FillRectangle(hdc, JX, JY, 252, 60); + DrawRectangle(hdc, JX, JY, 252, 60); - static wchar_t t[256]; - TextOut(hdc,JX+4,JY+ 4,L"REVB",4); - TextOut(hdc,JX+4,JY+18,L"IRQE",4); - TextOut(hdc,JX+4,JY+32,L"ADMA",4); - swprintf_s(t,L"DMA%s",c==0 ? L"4" : L"7"); - TextOut(hdc,JX+4,JY+46,t, 4); - - SetTextColor(hdc,RGB( 0,255, 0)); - memset(t, 0, sizeof(t)); - swprintf_s(t,L"ESA %x",cx.EffectsStartA); - TextOut(hdc,JX+56,JY+ 4,t, 9); - memset(t, 0, sizeof(t)); - swprintf_s(t,L"EEA %x",cx.EffectsEndA); - TextOut(hdc,JX+128,JY+ 4,t, 9); + SetTextColor(hdc, RGB(255, 255, 255)); + SetBkColor(hdc, RGB(0, 0, 0)); + + static wchar_t t[256]; + TextOut(hdc, JX + 4, JY + 4, L"REVB", 4); + TextOut(hdc, JX + 4, JY + 18, L"IRQE", 4); + TextOut(hdc, JX + 4, JY + 32, L"ADMA", 4); + swprintf_s(t, L"DMA%s", c == 0 ? L"4" : L"7"); + TextOut(hdc, JX + 4, JY + 46, t, 4); + + SetTextColor(hdc, RGB(0, 255, 0)); memset(t, 0, sizeof(t)); - swprintf_s(t,L"(%x)",cx.EffectsBufferSize); - TextOut(hdc,JX+200,JY+ 4,t,7); + swprintf_s(t, L"ESA %x", cx.EffectsStartA); + TextOut(hdc, JX + 56, JY + 4, t, 9); + memset(t, 0, sizeof(t)); + swprintf_s(t, L"EEA %x", cx.EffectsEndA); + TextOut(hdc, JX + 128, JY + 4, t, 9); + memset(t, 0, sizeof(t)); + swprintf_s(t, L"(%x)", cx.EffectsBufferSize); + TextOut(hdc, JX + 200, JY + 4, t, 7); memset(t, 0, sizeof(t)); - swprintf_s(t,L"IRQA %x",cx.IRQA); - TextOut(hdc,JX+56,JY+18,t, 12); + swprintf_s(t, L"IRQA %x", cx.IRQA); + TextOut(hdc, JX + 56, JY + 18, t, 12); - SetTextColor(hdc,RGB(255,255,255)); - SetDCBrushColor(hdc,RGB( 255,0, 0)); + SetTextColor(hdc, RGB(255, 255, 255)); + SetDCBrushColor(hdc, RGB(255, 0, 0)); - if(cx.FxEnable) - { - FillRectangle(hdc,JX+40,JY+4,10,10); - } - if(cx.IRQEnable) - { - FillRectangle(hdc,JX+40,JY+18,10,10); - } - if(cx.AutoDMACtrl != 0) - { - FillRectangle(hdc,JX+40,JY+32,10,10); + if (cx.FxEnable) { + FillRectangle(hdc, JX + 40, JY + 4, 10, 10); + } + if (cx.IRQEnable) { + FillRectangle(hdc, JX + 40, JY + 18, 10, 10); + } + if (cx.AutoDMACtrl != 0) { + FillRectangle(hdc, JX + 40, JY + 32, 10, 10); - for(int j=0;j<64;j++) - { - int i=j*256/64; - int val = (cd.admaWaveformL[i] * 26) / 32768; - int y=0; + for (int j = 0; j < 64; j++) { + int i = j * 256 / 64; + int val = (cd.admaWaveformL[i] * 26) / 32768; + int y = 0; - if(val>0) - y=val; - else - val=-val; + if (val > 0) + y = val; + else + val = -val; - if(val!=0) - { - FillRectangle(hdc,JX+60+j,JY+30-y, 1, val); - } - } + if (val != 0) { + FillRectangle(hdc, JX + 60 + j, JY + 30 - y, 1, val); + } + } - for(int j=0;j<64;j++) - { - int i=j*256/64; - int val = (cd.admaWaveformR[i] * 26) / 32768; - int y=0; + for (int j = 0; j < 64; j++) { + int i = j * 256 / 64; + int val = (cd.admaWaveformR[i] * 26) / 32768; + int y = 0; - if(val>0) - y=val; - else - val=-val; + if (val > 0) + y = val; + else + val = -val; - if(val!=0) - { - FillRectangle(hdc,JX+136+j,JY+30-y, 1, val); - } - } - } - if(cd.dmaFlag > 0) // So it shows x times this is called, since dmas are so fast - { - swprintf_s(t,L"size = %d",cd.lastsize); - - TextOut(hdc,JX+64,JY+46,t,wcslen(t)); - FillRectangle(hdc,JX+40,JY+46,10,10); - cd.dmaFlag--; - } - } + if (val != 0) { + FillRectangle(hdc, JX + 136 + j, JY + 30 - y, 1, val); + } + } + } + if (cd.dmaFlag > 0) // So it shows x times this is called, since dmas are so fast + { + swprintf_s(t, L"size = %d", cd.lastsize); - ReleaseDC(hDebugDialog,hdc); - lCount=0; - } + TextOut(hdc, JX + 64, JY + 46, t, wcslen(t)); + FillRectangle(hdc, JX + 40, JY + 46, 10, 10); + cd.dmaFlag--; + } + } - MSG msg; - while(PeekMessage(&msg,hDebugDialog,0,0,PM_REMOVE)) - { - TranslateMessage(&msg); - DispatchMessage(&msg); - } + ReleaseDC(hDebugDialog, hdc); + lCount = 0; + } + + MSG msg; + while (PeekMessage(&msg, hDebugDialog, 0, 0, PM_REMOVE)) { + TranslateMessage(&msg); + DispatchMessage(&msg); + } } #else void UpdateDebugDialog() { - // Release mode. Nothing to do + // Release mode. Nothing to do } #endif diff --git a/plugins/spu2-x/src/Windows/SndOut_DSound.cpp b/plugins/spu2-x/src/Windows/SndOut_DSound.cpp index a706959e0d..4d6e7a626b 100644 --- a/plugins/spu2-x/src/Windows/SndOut_DSound.cpp +++ b/plugins/spu2-x/src/Windows/SndOut_DSound.cpp @@ -26,458 +26,431 @@ class DSound : public SndOutModule { private: - static const uint MAX_BUFFER_COUNT = 8; - static const int PacketsPerBuffer = 8; - static const int BufferSize = SndOutPacketSize * PacketsPerBuffer; + static const uint MAX_BUFFER_COUNT = 8; + static const int PacketsPerBuffer = 8; + static const int BufferSize = SndOutPacketSize * PacketsPerBuffer; - ////////////////////////////////////////////////////////////////////////////////////////// - // Configuration Vars + ////////////////////////////////////////////////////////////////////////////////////////// + // Configuration Vars - wxString m_Device; - u8 m_NumBuffers; - bool m_DisableGlobalFocus; - bool m_UseHardware; + wxString m_Device; + u8 m_NumBuffers; + bool m_DisableGlobalFocus; + bool m_UseHardware; - ds_device_data m_devices[32]; - int ndevs; - GUID DevGuid; // currently employed GUID. - bool haveGuid; + ds_device_data m_devices[32]; + int ndevs; + GUID DevGuid; // currently employed GUID. + bool haveGuid; - ////////////////////////////////////////////////////////////////////////////////////////// - // Instance vars + ////////////////////////////////////////////////////////////////////////////////////////// + // Instance vars - int channel; - int myLastWrite; // last write position, in bytes + int channel; + int myLastWrite; // last write position, in bytes - bool dsound_running; - HANDLE thread; - DWORD tid; + bool dsound_running; + HANDLE thread; + DWORD tid; - IDirectSound8* dsound; - IDirectSoundBuffer8* buffer; - IDirectSoundNotify8* buffer_notify; - HANDLE buffer_events[MAX_BUFFER_COUNT]; + IDirectSound8 *dsound; + IDirectSoundBuffer8 *buffer; + IDirectSoundNotify8 *buffer_notify; + HANDLE buffer_events[MAX_BUFFER_COUNT]; - WAVEFORMATEX wfx; + WAVEFORMATEX wfx; - HANDLE waitEvent; + HANDLE waitEvent; - template< typename T > - static DWORD CALLBACK RThread( DSound* obj ) - { - return obj->Thread(); - } + template + static DWORD CALLBACK RThread(DSound *obj) + { + return obj->Thread(); + } - template< typename T > - DWORD CALLBACK Thread() - { - static const int BufferSizeBytes = BufferSize * sizeof( T ); + template + DWORD CALLBACK Thread() + { + static const int BufferSizeBytes = BufferSize * sizeof(T); - while( dsound_running ) - { - u32 rv = WaitForMultipleObjects(m_NumBuffers,buffer_events,FALSE,200); + while (dsound_running) { + u32 rv = WaitForMultipleObjects(m_NumBuffers, buffer_events, FALSE, 200); - T* p1, *oldp1; - LPVOID p2; - DWORD s1,s2; + T *p1, *oldp1; + LPVOID p2; + DWORD s1, s2; - u32 poffset = BufferSizeBytes * rv; + u32 poffset = BufferSizeBytes * rv; - if( FAILED(buffer->Lock(poffset,BufferSizeBytes,(LPVOID*)&p1,&s1,&p2,&s2,0) ) ) - { - assert( 0 ); - fputs( "* SPU2-X: Directsound Warning > Buffer lock failure. You may need to increase\n\tyour configured DSound buffer count.\n", stderr ); - continue; - } - oldp1 = p1; + if (FAILED(buffer->Lock(poffset, BufferSizeBytes, (LPVOID *)&p1, &s1, &p2, &s2, 0))) { + assert(0); + fputs("* SPU2-X: Directsound Warning > Buffer lock failure. You may need to increase\n\tyour configured DSound buffer count.\n", stderr); + continue; + } + oldp1 = p1; - for(int p=0; pUnlock( oldp1, s1, p2, s2 ); + buffer->Unlock(oldp1, s1, p2, s2); - // Set the write pointer to the beginning of the next block. - myLastWrite = (poffset + BufferSizeBytes) & ~BufferSizeBytes; - } - return 0; - } + // Set the write pointer to the beginning of the next block. + myLastWrite = (poffset + BufferSizeBytes) & ~BufferSizeBytes; + } + return 0; + } public: - s32 Init() - { - CoInitializeEx( NULL, COINIT_MULTITHREADED ); + s32 Init() + { + CoInitializeEx(NULL, COINIT_MULTITHREADED); - // - // Initialize DSound - // - GUID cGuid; + // + // Initialize DSound + // + GUID cGuid; - try - { - if( m_Device.empty() ) - throw std::runtime_error( "screw it" ); + try { + if (m_Device.empty()) + throw std::runtime_error("screw it"); - if ((FAILED(GUIDFromString(m_Device, &cGuid))) || - FAILED( DirectSoundCreate8(&cGuid,&dsound,NULL) ) ) - throw std::runtime_error( "try again?" ); - } - catch( std::runtime_error& ) - { - // if the GUID failed, just open up the default dsound driver: - if( FAILED(DirectSoundCreate8(NULL,&dsound,NULL) ) ) - throw std::runtime_error( "DirectSound failed to initialize!" ); - } + if ((FAILED(GUIDFromString(m_Device, &cGuid))) || + FAILED(DirectSoundCreate8(&cGuid, &dsound, NULL))) + throw std::runtime_error("try again?"); + } catch (std::runtime_error &) { + // if the GUID failed, just open up the default dsound driver: + if (FAILED(DirectSoundCreate8(NULL, &dsound, NULL))) + throw std::runtime_error("DirectSound failed to initialize!"); + } - if( FAILED(dsound->SetCooperativeLevel(GetDesktopWindow(),DSSCL_PRIORITY)) ) - throw std::runtime_error( "DirectSound Error: Cooperative level could not be set." ); + if (FAILED(dsound->SetCooperativeLevel(GetDesktopWindow(), DSSCL_PRIORITY))) + throw std::runtime_error("DirectSound Error: Cooperative level could not be set."); - // Determine the user's speaker configuration, and select an expansion option as needed. - // FAIL : Directsound doesn't appear to support audio expansion >_< + // Determine the user's speaker configuration, and select an expansion option as needed. + // FAIL : Directsound doesn't appear to support audio expansion >_< - DWORD speakerConfig = 2; - //dsound->GetSpeakerConfig( &speakerConfig ); + DWORD speakerConfig = 2; + //dsound->GetSpeakerConfig( &speakerConfig ); - IDirectSoundBuffer* buffer_; - DSBUFFERDESC desc; + IDirectSoundBuffer *buffer_; + DSBUFFERDESC desc; - // Set up WAV format structure. + // Set up WAV format structure. - memset(&wfx, 0, sizeof(WAVEFORMATEX)); - wfx.wFormatTag = WAVE_FORMAT_PCM; - wfx.nSamplesPerSec = SampleRate; - wfx.nChannels = (WORD)speakerConfig; - wfx.wBitsPerSample = 16; - wfx.nBlockAlign = 2*(WORD)speakerConfig; - wfx.nAvgBytesPerSec = SampleRate * wfx.nBlockAlign; - wfx.cbSize = 0; + memset(&wfx, 0, sizeof(WAVEFORMATEX)); + wfx.wFormatTag = WAVE_FORMAT_PCM; + wfx.nSamplesPerSec = SampleRate; + wfx.nChannels = (WORD)speakerConfig; + wfx.wBitsPerSample = 16; + wfx.nBlockAlign = 2 * (WORD)speakerConfig; + wfx.nAvgBytesPerSec = SampleRate * wfx.nBlockAlign; + wfx.cbSize = 0; - uint BufferSizeBytes = BufferSize * wfx.nBlockAlign; + uint BufferSizeBytes = BufferSize * wfx.nBlockAlign; - // Set up DSBUFFERDESC structure. + // Set up DSBUFFERDESC structure. - memset(&desc, 0, sizeof(DSBUFFERDESC)); - desc.dwSize = sizeof(DSBUFFERDESC); - desc.dwFlags = DSBCAPS_GETCURRENTPOSITION2 | DSBCAPS_CTRLPOSITIONNOTIFY; - desc.dwBufferBytes = BufferSizeBytes * m_NumBuffers; - desc.lpwfxFormat = &wfx; + memset(&desc, 0, sizeof(DSBUFFERDESC)); + desc.dwSize = sizeof(DSBUFFERDESC); + desc.dwFlags = DSBCAPS_GETCURRENTPOSITION2 | DSBCAPS_CTRLPOSITIONNOTIFY; + desc.dwBufferBytes = BufferSizeBytes * m_NumBuffers; + desc.lpwfxFormat = &wfx; - // Try a hardware buffer first, and then fall back on a software buffer if - // that one fails. + // Try a hardware buffer first, and then fall back on a software buffer if + // that one fails. - desc.dwFlags |= m_UseHardware ? DSBCAPS_LOCHARDWARE : DSBCAPS_LOCSOFTWARE; - desc.dwFlags |= m_DisableGlobalFocus ? DSBCAPS_STICKYFOCUS : DSBCAPS_GLOBALFOCUS; + desc.dwFlags |= m_UseHardware ? DSBCAPS_LOCHARDWARE : DSBCAPS_LOCSOFTWARE; + desc.dwFlags |= m_DisableGlobalFocus ? DSBCAPS_STICKYFOCUS : DSBCAPS_GLOBALFOCUS; - if( FAILED(dsound->CreateSoundBuffer(&desc, &buffer_, 0) ) ) - { - if( m_UseHardware ) - { - desc.dwFlags = DSBCAPS_GETCURRENTPOSITION2 | DSBCAPS_CTRLPOSITIONNOTIFY | DSBCAPS_LOCSOFTWARE; - desc.dwFlags |= m_DisableGlobalFocus ? DSBCAPS_STICKYFOCUS : DSBCAPS_GLOBALFOCUS; + if (FAILED(dsound->CreateSoundBuffer(&desc, &buffer_, 0))) { + if (m_UseHardware) { + desc.dwFlags = DSBCAPS_GETCURRENTPOSITION2 | DSBCAPS_CTRLPOSITIONNOTIFY | DSBCAPS_LOCSOFTWARE; + desc.dwFlags |= m_DisableGlobalFocus ? DSBCAPS_STICKYFOCUS : DSBCAPS_GLOBALFOCUS; - if( FAILED(dsound->CreateSoundBuffer(&desc, &buffer_, 0) ) ) - throw std::runtime_error( "DirectSound Error: Buffer could not be created." ); - } + if (FAILED(dsound->CreateSoundBuffer(&desc, &buffer_, 0))) + throw std::runtime_error("DirectSound Error: Buffer could not be created."); + } - throw std::runtime_error( "DirectSound Error: Buffer could not be created." ); - } - if( FAILED(buffer_->QueryInterface(IID_IDirectSoundBuffer8,(void**)&buffer)) || buffer == NULL ) - throw std::runtime_error( "DirectSound Error: Interface could not be queried." ); + throw std::runtime_error("DirectSound Error: Buffer could not be created."); + } + if (FAILED(buffer_->QueryInterface(IID_IDirectSoundBuffer8, (void **)&buffer)) || buffer == NULL) + throw std::runtime_error("DirectSound Error: Interface could not be queried."); - buffer_->Release(); - verifyc( buffer->QueryInterface(IID_IDirectSoundNotify8,(void**)&buffer_notify) ); + buffer_->Release(); + verifyc(buffer->QueryInterface(IID_IDirectSoundNotify8, (void **)&buffer_notify)); - DSBPOSITIONNOTIFY not[MAX_BUFFER_COUNT]; + DSBPOSITIONNOTIFY not[MAX_BUFFER_COUNT]; - for(uint i=0;iSetNotificationPositions(m_NumBuffers,not); + buffer_notify->SetNotificationPositions(m_NumBuffers, not); - LPVOID p1=0,p2=0; - DWORD s1=0,s2=0; + LPVOID p1 = 0, p2 = 0; + DWORD s1 = 0, s2 = 0; - verifyc(buffer->Lock(0,desc.dwBufferBytes,&p1,&s1,&p2,&s2,0)); - assert(p2==0); - memset(p1,0,s1); - verifyc(buffer->Unlock(p1,s1,p2,s2)); + verifyc(buffer->Lock(0, desc.dwBufferBytes, &p1, &s1, &p2, &s2, 0)); + assert(p2 == 0); + memset(p1, 0, s1); + verifyc(buffer->Unlock(p1, s1, p2, s2)); - //Play the buffer ! - verifyc(buffer->Play(0,0,DSBPLAY_LOOPING)); + //Play the buffer ! + verifyc(buffer->Play(0, 0, DSBPLAY_LOOPING)); - // Start Thread - myLastWrite = 0; - dsound_running = true; - thread = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)RThread,this,0,&tid); - SetThreadPriority(thread,THREAD_PRIORITY_ABOVE_NORMAL); + // Start Thread + myLastWrite = 0; + dsound_running = true; + thread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)RThread, this, 0, &tid); + SetThreadPriority(thread, THREAD_PRIORITY_ABOVE_NORMAL); - return 0; - } + return 0; + } - void Close() - { - // Stop Thread - fprintf(stderr,"* SPU2-X: Waiting for DSound thread to finish..."); - dsound_running=false; + void Close() + { + // Stop Thread + fprintf(stderr, "* SPU2-X: Waiting for DSound thread to finish..."); + dsound_running = false; - WaitForSingleObject(thread,INFINITE); - CloseHandle(thread); + WaitForSingleObject(thread, INFINITE); + CloseHandle(thread); - fprintf(stderr," Done.\n"); + fprintf(stderr, " Done.\n"); - // - // Clean up - // - if( buffer != NULL ) - { - buffer->Stop(); + // + // Clean up + // + if (buffer != NULL) { + buffer->Stop(); - for(u32 i=0;i= 0) + SendMessage(GetDlgItem(hWnd, IDC_DS_DEVICE), CB_SETCURSEL, tSel, 0); - if(tSel>=0) - SendMessage(GetDlgItem(hWnd,IDC_DS_DEVICE),CB_SETCURSEL,tSel,0); + INIT_SLIDER(IDC_BUFFERS_SLIDER, 2, MAX_BUFFER_COUNT, 2, 1, 1); + SendMessage(GetDlgItem(hWnd, IDC_BUFFERS_SLIDER), TBM_SETPOS, TRUE, m_NumBuffers); + swprintf_s(temp, L"%d (%d ms latency)", m_NumBuffers, 1000 / (96000 / (m_NumBuffers * BufferSize))); + SetWindowText(GetDlgItem(hWnd, IDC_LATENCY_LABEL), temp); - INIT_SLIDER( IDC_BUFFERS_SLIDER, 2, MAX_BUFFER_COUNT, 2, 1, 1 ); - SendMessage(GetDlgItem(hWnd,IDC_BUFFERS_SLIDER),TBM_SETPOS,TRUE,m_NumBuffers); - swprintf_s(temp, L"%d (%d ms latency)",m_NumBuffers, 1000 / (96000 / (m_NumBuffers * BufferSize))); - SetWindowText(GetDlgItem(hWnd,IDC_LATENCY_LABEL),temp); + SET_CHECK(IDC_GLOBALFOCUS_DISABLE, m_DisableGlobalFocus); + SET_CHECK(IDC_USE_HARDWARE, m_UseHardware); + } break; - SET_CHECK( IDC_GLOBALFOCUS_DISABLE, m_DisableGlobalFocus ); - SET_CHECK( IDC_USE_HARDWARE, m_UseHardware ); - } - break; + case WM_COMMAND: { + wchar_t temp[128]; - case WM_COMMAND: - { - wchar_t temp[128]; + wmId = LOWORD(wParam); + wmEvent = HIWORD(wParam); + // Parse the menu selections: + switch (wmId) { + case IDOK: { + int i = (int)SendMessage(GetDlgItem(hWnd, IDC_DS_DEVICE), CB_GETCURSEL, 0, 0); - wmId = LOWORD(wParam); - wmEvent = HIWORD(wParam); - // Parse the menu selections: - switch (wmId) - { - case IDOK: - { - int i = (int)SendMessage(GetDlgItem(hWnd,IDC_DS_DEVICE),CB_GETCURSEL,0,0); + if (!m_devices[i].hasGuid) { + m_Device[0] = 0; // clear device name to "" + } else { + swprintf_s(temp, L"{%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}", + m_devices[i].guid.Data1, + m_devices[i].guid.Data2, + m_devices[i].guid.Data3, + m_devices[i].guid.Data4[0], + m_devices[i].guid.Data4[1], + m_devices[i].guid.Data4[2], + m_devices[i].guid.Data4[3], + m_devices[i].guid.Data4[4], + m_devices[i].guid.Data4[5], + m_devices[i].guid.Data4[6], + m_devices[i].guid.Data4[7]); + m_Device = temp; + } - if(!m_devices[i].hasGuid) - { - m_Device[0] = 0; // clear device name to "" - } - else - { - swprintf_s(temp, L"{%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}", - m_devices[i].guid.Data1, - m_devices[i].guid.Data2, - m_devices[i].guid.Data3, - m_devices[i].guid.Data4[0], - m_devices[i].guid.Data4[1], - m_devices[i].guid.Data4[2], - m_devices[i].guid.Data4[3], - m_devices[i].guid.Data4[4], - m_devices[i].guid.Data4[5], - m_devices[i].guid.Data4[6], - m_devices[i].guid.Data4[7] - ); - m_Device = temp; - } + m_NumBuffers = (int)SendMessage(GetDlgItem(hWnd, IDC_BUFFERS_SLIDER), TBM_GETPOS, 0, 0); - m_NumBuffers = (int)SendMessage( GetDlgItem( hWnd, IDC_BUFFERS_SLIDER ), TBM_GETPOS, 0, 0 ); + if (m_NumBuffers < 2) + m_NumBuffers = 2; + if (m_NumBuffers > MAX_BUFFER_COUNT) + m_NumBuffers = MAX_BUFFER_COUNT; - if( m_NumBuffers < 2 ) m_NumBuffers = 2; - if( m_NumBuffers > MAX_BUFFER_COUNT ) m_NumBuffers = MAX_BUFFER_COUNT; + EndDialog(hWnd, 0); + } break; - EndDialog(hWnd,0); - } - break; + case IDCANCEL: + EndDialog(hWnd, 0); + break; - case IDCANCEL: - EndDialog(hWnd,0); - break; + HANDLE_CHECK(IDC_GLOBALFOCUS_DISABLE, m_DisableGlobalFocus); + HANDLE_CHECK(IDC_USE_HARDWARE, m_UseHardware); - HANDLE_CHECK( IDC_GLOBALFOCUS_DISABLE, m_DisableGlobalFocus ); - HANDLE_CHECK( IDC_USE_HARDWARE, m_UseHardware ); + default: + return FALSE; + } + } break; - default: - return FALSE; - } - } - break; + case WM_HSCROLL: { + wmId = LOWORD(wParam); + wmEvent = HIWORD(wParam); + switch (wmId) { + //case TB_ENDTRACK: + //case TB_THUMBPOSITION: + case TB_LINEUP: + case TB_LINEDOWN: + case TB_PAGEUP: + case TB_PAGEDOWN: + wmEvent = (int)SendMessage((HWND)lParam, TBM_GETPOS, 0, 0); + case TB_THUMBTRACK: { + wchar_t temp[128]; + if (wmEvent < 2) + wmEvent = 2; + if (wmEvent > MAX_BUFFER_COUNT) + wmEvent = MAX_BUFFER_COUNT; + SendMessage((HWND)lParam, TBM_SETPOS, TRUE, wmEvent); + swprintf_s(temp, L"%d (%d ms latency)", wmEvent, 1000 / (96000 / (wmEvent * BufferSize))); + SetWindowText(GetDlgItem(hWnd, IDC_LATENCY_LABEL), temp); + break; + } + default: + return FALSE; + } + } break; - case WM_HSCROLL: - { - wmId = LOWORD(wParam); - wmEvent = HIWORD(wParam); - switch(wmId) - { - //case TB_ENDTRACK: - //case TB_THUMBPOSITION: - case TB_LINEUP: - case TB_LINEDOWN: - case TB_PAGEUP: - case TB_PAGEDOWN: - wmEvent = (int)SendMessage((HWND)lParam,TBM_GETPOS,0,0); - case TB_THUMBTRACK: - { - wchar_t temp[128]; - if( wmEvent < 2 ) wmEvent = 2; - if( wmEvent > MAX_BUFFER_COUNT ) wmEvent = MAX_BUFFER_COUNT; - SendMessage((HWND)lParam,TBM_SETPOS,TRUE,wmEvent); - swprintf_s(temp,L"%d (%d ms latency)",wmEvent, 1000 / (96000 / (wmEvent * BufferSize))); - SetWindowText(GetDlgItem(hWnd,IDC_LATENCY_LABEL),temp); - break; - } - default: - return FALSE; - } - } - break; + default: + return FALSE; + } + return TRUE; + } - default: - return FALSE; - } - return TRUE; - } - - static BOOL CALLBACK ConfigProc(HWND hWnd,UINT uMsg,WPARAM wParam,LPARAM lParam); - static BOOL CALLBACK DSEnumCallback( LPGUID lpGuid, LPCTSTR lpcstrDescription, LPCTSTR lpcstrModule, LPVOID lpContext ); + static BOOL CALLBACK ConfigProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam); + static BOOL CALLBACK DSEnumCallback(LPGUID lpGuid, LPCTSTR lpcstrDescription, LPCTSTR lpcstrModule, LPVOID lpContext); public: - virtual void Configure(uptr parent) - { - INT_PTR ret; - ret=DialogBoxParam(hInstance,MAKEINTRESOURCE(IDD_DSOUND),(HWND)parent,(DLGPROC)ConfigProc,1); - if(ret==-1) - { - MessageBox((HWND)parent,L"Error Opening the config dialog.",L"OMG ERROR!",MB_OK | MB_SETFOREGROUND); - return; - } - } - - s32 Test() const - { - return 0; - } + virtual void Configure(uptr parent) + { + INT_PTR ret; + ret = DialogBoxParam(hInstance, MAKEINTRESOURCE(IDD_DSOUND), (HWND)parent, (DLGPROC)ConfigProc, 1); + if (ret == -1) { + MessageBox((HWND)parent, L"Error Opening the config dialog.", L"OMG ERROR!", MB_OK | MB_SETFOREGROUND); + return; + } + } - int GetEmptySampleCount() - { - DWORD play, write; - buffer->GetCurrentPosition( &play, &write ); + s32 Test() const + { + return 0; + } - // Note: Dsound's write cursor is bogus. Use our own instead: + int GetEmptySampleCount() + { + DWORD play, write; + buffer->GetCurrentPosition(&play, &write); - int empty = play - myLastWrite; - if( empty < 0 ) - empty = -empty; + // Note: Dsound's write cursor is bogus. Use our own instead: - return empty / 2; - } + int empty = play - myLastWrite; + if (empty < 0) + empty = -empty; - const wchar_t* GetIdent() const - { - return L"dsound"; - } + return empty / 2; + } - const wchar_t* GetLongName() const - { - return L"DirectSound (nice)"; - } + const wchar_t *GetIdent() const + { + return L"dsound"; + } - void ReadSettings() - { - CfgReadStr( L"DSOUNDOUT", L"Device", m_Device, L"default" ); - m_NumBuffers = CfgReadInt( L"DSOUNDOUT", L"Buffer_Count", 5 ); - m_DisableGlobalFocus = CfgReadBool( L"DSOUNDOUT", L"Disable_Global_Focus", false ); - m_UseHardware = CfgReadBool( L"DSOUNDOUT", L"Use_Hardware", false ); + const wchar_t *GetLongName() const + { + return L"DirectSound (nice)"; + } - Clampify( m_NumBuffers, (u8)3, (u8)8 ); - } + void ReadSettings() + { + CfgReadStr(L"DSOUNDOUT", L"Device", m_Device, L"default"); + m_NumBuffers = CfgReadInt(L"DSOUNDOUT", L"Buffer_Count", 5); + m_DisableGlobalFocus = CfgReadBool(L"DSOUNDOUT", L"Disable_Global_Focus", false); + m_UseHardware = CfgReadBool(L"DSOUNDOUT", L"Use_Hardware", false); - void SetApiSettings(wxString api) - { - } + Clampify(m_NumBuffers, (u8)3, (u8)8); + } - void WriteSettings() const - { - CfgWriteStr( L"DSOUNDOUT", L"Device", m_Device.empty() ? L"default" : m_Device ); - CfgWriteInt( L"DSOUNDOUT", L"Buffer_Count", m_NumBuffers ); - CfgWriteBool( L"DSOUNDOUT", L"Disable_Global_Focus", m_DisableGlobalFocus ); - CfgWriteBool( L"DSOUNDOUT", L"Use_Hardware", m_UseHardware ); - } + void SetApiSettings(wxString api) + { + } + + void WriteSettings() const + { + CfgWriteStr(L"DSOUNDOUT", L"Device", m_Device.empty() ? L"default" : m_Device); + CfgWriteInt(L"DSOUNDOUT", L"Buffer_Count", m_NumBuffers); + CfgWriteBool(L"DSOUNDOUT", L"Disable_Global_Focus", m_DisableGlobalFocus); + CfgWriteBool(L"DSOUNDOUT", L"Use_Hardware", m_UseHardware); + } } static DS; -BOOL CALLBACK DSound::ConfigProc(HWND hWnd,UINT uMsg,WPARAM wParam,LPARAM lParam) +BOOL CALLBACK DSound::ConfigProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { - return DS._ConfigProc( hWnd, uMsg, wParam, lParam ); + return DS._ConfigProc(hWnd, uMsg, wParam, lParam); } -BOOL CALLBACK DSound::DSEnumCallback( LPGUID lpGuid, LPCTSTR lpcstrDescription, LPCTSTR lpcstrModule, LPVOID lpContext ) +BOOL CALLBACK DSound::DSEnumCallback(LPGUID lpGuid, LPCTSTR lpcstrDescription, LPCTSTR lpcstrModule, LPVOID lpContext) { - pxAssume( DSoundOut != NULL ); - return DS._DSEnumCallback( lpGuid, lpcstrDescription, lpcstrModule, lpContext ); + pxAssume(DSoundOut != NULL); + return DS._DSEnumCallback(lpGuid, lpcstrDescription, lpcstrModule, lpContext); } SndOutModule *DSoundOut = &DS; diff --git a/plugins/spu2-x/src/Windows/SndOut_XAudio2.cpp b/plugins/spu2-x/src/Windows/SndOut_XAudio2.cpp index 2398b58d85..7b03f60b1a 100644 --- a/plugins/spu2-x/src/Windows/SndOut_XAudio2.cpp +++ b/plugins/spu2-x/src/Windows/SndOut_XAudio2.cpp @@ -26,41 +26,41 @@ namespace Exception { - class XAudio2Error : public std::runtime_error - { - protected: - static const char* SomeKindaErrorString(HRESULT hr) - { - switch (hr) { - case XAUDIO2_E_INVALID_CALL: - return "Invalid call for the XA2 object state."; +class XAudio2Error : public std::runtime_error +{ +protected: + static const char *SomeKindaErrorString(HRESULT hr) + { + switch (hr) { + case XAUDIO2_E_INVALID_CALL: + return "Invalid call for the XA2 object state."; - case XAUDIO2_E_DEVICE_INVALIDATED: - return "Device is unavailable, unplugged, unsupported, or has been consumed by The Nothing."; - } - return "Unknown error code!"; - } + case XAUDIO2_E_DEVICE_INVALIDATED: + return "Device is unavailable, unplugged, unsupported, or has been consumed by The Nothing."; + } + return "Unknown error code!"; + } - public: - const HRESULT ErrorCode; - std::string m_Message; +public: + const HRESULT ErrorCode; + std::string m_Message; - const char* CMessage() const - { - return m_Message.c_str(); - } + const char *CMessage() const + { + return m_Message.c_str(); + } - virtual ~XAudio2Error() throw() {} - XAudio2Error(const HRESULT result, const std::string& msg) : - runtime_error(msg), - ErrorCode(result), - m_Message() - { - char omg[1024]; - sprintf_s(omg, "%s (code 0x%x)\n\n%s", what(), ErrorCode, SomeKindaErrorString(ErrorCode)); - m_Message = omg; - } - }; + virtual ~XAudio2Error() throw() {} + XAudio2Error(const HRESULT result, const std::string &msg) + : runtime_error(msg) + , ErrorCode(result) + , m_Message() + { + char omg[1024]; + sprintf_s(omg, "%s (code 0x%x)\n\n%s", what(), ErrorCode, SomeKindaErrorString(ErrorCode)); + m_Message = omg; + } +}; } static const double SndOutNormalizer = (double)(1UL << (SndOutVolumeShift + 16)); @@ -68,334 +68,364 @@ static const double SndOutNormalizer = (double)(1UL << (SndOutVolumeShift + 16)) class XAudio2Mod : public SndOutModule { private: - static const int PacketsPerBuffer = 8; - static const int MAX_BUFFER_COUNT = 3; + static const int PacketsPerBuffer = 8; + static const int MAX_BUFFER_COUNT = 3; - class BaseStreamingVoice : public IXAudio2VoiceCallback - { - protected: - IXAudio2SourceVoice* pSourceVoice; - s16* qbuffer; + class BaseStreamingVoice : public IXAudio2VoiceCallback + { + protected: + IXAudio2SourceVoice *pSourceVoice; + s16 *qbuffer; - const uint m_nBuffers; - const uint m_nChannels; - const uint m_BufferSize; - const uint m_BufferSizeBytes; + const uint m_nBuffers; + const uint m_nChannels; + const uint m_BufferSize; + const uint m_BufferSizeBytes; - CRITICAL_SECTION cs; + CRITICAL_SECTION cs; - public: - int GetEmptySampleCount() - { - XAUDIO2_VOICE_STATE state; - pSourceVoice->GetState(&state); - return state.SamplesPlayed & (m_BufferSize - 1); - } + public: + int GetEmptySampleCount() + { + XAUDIO2_VOICE_STATE state; + pSourceVoice->GetState(&state); + return state.SamplesPlayed & (m_BufferSize - 1); + } - virtual ~BaseStreamingVoice() - { - } + virtual ~BaseStreamingVoice() + { + } - BaseStreamingVoice(uint numChannels) : - m_nBuffers(Config_XAudio2.NumBuffers), - m_nChannels(numChannels), - m_BufferSize(SndOutPacketSize * m_nChannels * PacketsPerBuffer), - m_BufferSizeBytes(m_BufferSize * sizeof(s16)) - { - } + BaseStreamingVoice(uint numChannels) + : m_nBuffers(Config_XAudio2.NumBuffers) + , m_nChannels(numChannels) + , m_BufferSize(SndOutPacketSize * m_nChannels * PacketsPerBuffer) + , m_BufferSizeBytes(m_BufferSize * sizeof(s16)) + { + } - virtual void Init(IXAudio2* pXAudio2) = 0; + virtual void Init(IXAudio2 *pXAudio2) = 0; - protected: - // Several things must be initialized separate of the constructor, due to the fact that - // virtual calls can't be made from the constructor's context. - void _init(IXAudio2* pXAudio2, uint chanConfig) - { - WAVEFORMATEXTENSIBLE wfx; + protected: + // Several things must be initialized separate of the constructor, due to the fact that + // virtual calls can't be made from the constructor's context. + void _init(IXAudio2 *pXAudio2, uint chanConfig) + { + WAVEFORMATEXTENSIBLE wfx; - memset(&wfx, 0, sizeof(WAVEFORMATEXTENSIBLE)); - wfx.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE; - wfx.Format.nSamplesPerSec = SampleRate; - wfx.Format.nChannels = m_nChannels; - wfx.Format.wBitsPerSample = 16; - wfx.Format.nBlockAlign = wfx.Format.nChannels * wfx.Format.wBitsPerSample / 8; - wfx.Format.nAvgBytesPerSec = SampleRate * wfx.Format.nBlockAlign; - wfx.Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX); - wfx.Samples.wValidBitsPerSample = 16; - wfx.dwChannelMask = chanConfig; - wfx.SubFormat = KSDATAFORMAT_SUBTYPE_PCM; + memset(&wfx, 0, sizeof(WAVEFORMATEXTENSIBLE)); + wfx.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE; + wfx.Format.nSamplesPerSec = SampleRate; + wfx.Format.nChannels = m_nChannels; + wfx.Format.wBitsPerSample = 16; + wfx.Format.nBlockAlign = wfx.Format.nChannels * wfx.Format.wBitsPerSample / 8; + wfx.Format.nAvgBytesPerSec = SampleRate * wfx.Format.nBlockAlign; + wfx.Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX); + wfx.Samples.wValidBitsPerSample = 16; + wfx.dwChannelMask = chanConfig; + wfx.SubFormat = KSDATAFORMAT_SUBTYPE_PCM; - // - // Create an XAudio2 voice to stream this wave - // - HRESULT hr; - if (FAILED(hr = pXAudio2->CreateSourceVoice(&pSourceVoice, (WAVEFORMATEX*)&wfx, - XAUDIO2_VOICE_NOSRC, 1.0f, this))) { - throw Exception::XAudio2Error(hr, "XAudio2 CreateSourceVoice failure."); - } + // + // Create an XAudio2 voice to stream this wave + // + HRESULT hr; + if (FAILED(hr = pXAudio2->CreateSourceVoice(&pSourceVoice, (WAVEFORMATEX *)&wfx, + XAUDIO2_VOICE_NOSRC, 1.0f, this))) { + throw Exception::XAudio2Error(hr, "XAudio2 CreateSourceVoice failure."); + } - InitializeCriticalSection(&cs); - EnterCriticalSection(&cs); + InitializeCriticalSection(&cs); + EnterCriticalSection(&cs); - pSourceVoice->FlushSourceBuffers(); - pSourceVoice->Start(0, 0); + pSourceVoice->FlushSourceBuffers(); + pSourceVoice->Start(0, 0); - qbuffer = new s16[m_nBuffers * m_BufferSize]; - ZeroMemory(qbuffer, m_BufferSizeBytes * m_nBuffers); + qbuffer = new s16[m_nBuffers * m_BufferSize]; + ZeroMemory(qbuffer, m_BufferSizeBytes * m_nBuffers); - // Start some buffers. + // Start some buffers. - for (uint i = 0; i < m_nBuffers; i++) { - XAUDIO2_BUFFER buf = { 0 }; - buf.AudioBytes = m_BufferSizeBytes; - buf.pContext = &qbuffer[i*m_BufferSize]; - buf.pAudioData = (BYTE*)buf.pContext; - pSourceVoice->SubmitSourceBuffer(&buf); - } + for (uint i = 0; i < m_nBuffers; i++) { + XAUDIO2_BUFFER buf = {0}; + buf.AudioBytes = m_BufferSizeBytes; + buf.pContext = &qbuffer[i * m_BufferSize]; + buf.pAudioData = (BYTE *)buf.pContext; + pSourceVoice->SubmitSourceBuffer(&buf); + } - LeaveCriticalSection(&cs); - } + LeaveCriticalSection(&cs); + } - STDMETHOD_(void, OnVoiceProcessingPassStart) () {} - STDMETHOD_(void, OnVoiceProcessingPassStart) (UINT32) {} - STDMETHOD_(void, OnVoiceProcessingPassEnd) () {} - STDMETHOD_(void, OnStreamEnd) () {} - STDMETHOD_(void, OnBufferStart) (void*) {} - STDMETHOD_(void, OnLoopEnd) (void*) {} - STDMETHOD_(void, OnVoiceError) (THIS_ void* pBufferContext, HRESULT Error) {} - }; + STDMETHOD_(void, OnVoiceProcessingPassStart) + () {} + STDMETHOD_(void, OnVoiceProcessingPassStart) + (UINT32) {} + STDMETHOD_(void, OnVoiceProcessingPassEnd) + () {} + STDMETHOD_(void, OnStreamEnd) + () {} + STDMETHOD_(void, OnBufferStart) + (void *) {} + STDMETHOD_(void, OnLoopEnd) + (void *) {} + STDMETHOD_(void, OnVoiceError) + (THIS_ void *pBufferContext, HRESULT Error) {} + }; - template< typename T > - class StreamingVoice : public BaseStreamingVoice - { - public: - StreamingVoice(IXAudio2* pXAudio2) : - BaseStreamingVoice(sizeof(T) / sizeof(s16)) - { - } + template + class StreamingVoice : public BaseStreamingVoice + { + public: + StreamingVoice(IXAudio2 *pXAudio2) + : BaseStreamingVoice(sizeof(T) / sizeof(s16)) + { + } - virtual ~StreamingVoice() - { - IXAudio2SourceVoice* killMe = pSourceVoice; - pSourceVoice = NULL; - killMe->FlushSourceBuffers(); - killMe->DestroyVoice(); + virtual ~StreamingVoice() + { + IXAudio2SourceVoice *killMe = pSourceVoice; + pSourceVoice = NULL; + killMe->FlushSourceBuffers(); + killMe->DestroyVoice(); - EnterCriticalSection(&cs); - safe_delete_array(qbuffer); - LeaveCriticalSection(&cs); - DeleteCriticalSection(&cs); - } + EnterCriticalSection(&cs); + safe_delete_array(qbuffer); + LeaveCriticalSection(&cs); + DeleteCriticalSection(&cs); + } - void Init(IXAudio2* pXAudio2) - { - int chanMask = 0; - switch (m_nChannels) { - case 1: chanMask |= SPEAKER_FRONT_CENTER; break; - case 2: chanMask |= SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; break; - case 3: chanMask |= SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_LOW_FREQUENCY; break; - case 4: chanMask |= SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break; - case 5: chanMask |= SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break; - case 6: chanMask |= SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT | SPEAKER_LOW_FREQUENCY; break; - case 8: chanMask |= SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT | SPEAKER_SIDE_LEFT | SPEAKER_SIDE_RIGHT | SPEAKER_LOW_FREQUENCY; break; - } - _init(pXAudio2, chanMask); - } + void Init(IXAudio2 *pXAudio2) + { + int chanMask = 0; + switch (m_nChannels) { + case 1: + chanMask |= SPEAKER_FRONT_CENTER; + break; + case 2: + chanMask |= SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; + break; + case 3: + chanMask |= SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_LOW_FREQUENCY; + break; + case 4: + chanMask |= SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; + break; + case 5: + chanMask |= SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; + break; + case 6: + chanMask |= SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT | SPEAKER_LOW_FREQUENCY; + break; + case 8: + chanMask |= SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT | SPEAKER_SIDE_LEFT | SPEAKER_SIDE_RIGHT | SPEAKER_LOW_FREQUENCY; + break; + } + _init(pXAudio2, chanMask); + } - protected: - STDMETHOD_(void, OnBufferEnd) (void* context) - { - EnterCriticalSection(&cs); + protected: + STDMETHOD_(void, OnBufferEnd) + (void *context) + { + EnterCriticalSection(&cs); - // All of these checks are necessary because XAudio2 is wonky shizat. - if (pSourceVoice == NULL || context == NULL) { - LeaveCriticalSection(&cs); - return; - } + // All of these checks are necessary because XAudio2 is wonky shizat. + if (pSourceVoice == NULL || context == NULL) { + LeaveCriticalSection(&cs); + return; + } - T* qb = (T*)context; + T *qb = (T *)context; - for (int p = 0; p < PacketsPerBuffer; p++, qb += SndOutPacketSize) - SndBuffer::ReadSamples(qb); + for (int p = 0; p < PacketsPerBuffer; p++, qb += SndOutPacketSize) + SndBuffer::ReadSamples(qb); - XAUDIO2_BUFFER buf = { 0 }; - buf.AudioBytes = m_BufferSizeBytes; - buf.pAudioData = (BYTE*)context; - buf.pContext = context; + XAUDIO2_BUFFER buf = {0}; + buf.AudioBytes = m_BufferSizeBytes; + buf.pAudioData = (BYTE *)context; + buf.pContext = context; - pSourceVoice->SubmitSourceBuffer(&buf); - LeaveCriticalSection(&cs); - } + pSourceVoice->SubmitSourceBuffer(&buf); + LeaveCriticalSection(&cs); + } + }; - }; - - HMODULE xAudio2DLL; - decltype(&XAudio2Create) pXAudio2Create; - CComPtr pXAudio2; - IXAudio2MasteringVoice* pMasteringVoice; - BaseStreamingVoice* voiceContext; + HMODULE xAudio2DLL; + decltype(&XAudio2Create) pXAudio2Create; + CComPtr pXAudio2; + IXAudio2MasteringVoice *pMasteringVoice; + BaseStreamingVoice *voiceContext; public: + s32 Init() + { + HRESULT hr; - s32 Init() - { - HRESULT hr; + pxAssume(pXAudio2 == NULL); - pxAssume(pXAudio2 == NULL); + xAudio2DLL = LoadLibraryEx(XAUDIO2_DLL, nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); + if (xAudio2DLL == nullptr) + throw std::runtime_error("Could not load " XAUDIO2_DLL_A ". Error code:" + std::to_string(GetLastError())); - xAudio2DLL = LoadLibraryEx(XAUDIO2_DLL, nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); - if (xAudio2DLL == nullptr) - throw std::runtime_error("Could not load " XAUDIO2_DLL_A ". Error code:" + std::to_string(GetLastError())); + pXAudio2Create = reinterpret_cast(GetProcAddress(xAudio2DLL, "XAudio2Create")); + if (pXAudio2Create == nullptr) + throw std::runtime_error("XAudio2Create not found. Error code: " + std::to_string(GetLastError())); - pXAudio2Create = reinterpret_cast(GetProcAddress(xAudio2DLL, "XAudio2Create")); - if (pXAudio2Create == nullptr) - throw std::runtime_error("XAudio2Create not found. Error code: " + std::to_string(GetLastError())); + // + // Initialize XAudio2 + // + CoInitializeEx(NULL, COINIT_MULTITHREADED); - // - // Initialize XAudio2 - // - CoInitializeEx(NULL, COINIT_MULTITHREADED); + try { + if (FAILED(hr = pXAudio2Create(&pXAudio2, 0, XAUDIO2_DEFAULT_PROCESSOR))) + throw Exception::XAudio2Error(hr, "Failed to init XAudio2 engine. Error Details:"); - try { - if (FAILED(hr = pXAudio2Create(&pXAudio2, 0, XAUDIO2_DEFAULT_PROCESSOR))) - throw Exception::XAudio2Error(hr, "Failed to init XAudio2 engine. Error Details:"); + // Stereo Expansion was planned to grab the currently configured number of + // Speakers from Windows's audio config. + // This doesn't always work though, so let it be a user configurable option. - // Stereo Expansion was planned to grab the currently configured number of - // Speakers from Windows's audio config. - // This doesn't always work though, so let it be a user configurable option. + int speakers; + switch (numSpeakers) // speakers = (numSpeakers + 1) *2; ? + { + case 0: + speakers = 2; + break; // Stereo + case 1: + speakers = 4; + break; // Quadrafonic + case 2: + speakers = 6; + break; // Surround 5.1 + case 3: + speakers = 8; + break; // Surround 7.1 + default: + speakers = 2; + } - int speakers; - switch (numSpeakers) // speakers = (numSpeakers + 1) *2; ? - { - case 0: speakers = 2; break; // Stereo - case 1: speakers = 4; break; // Quadrafonic - case 2: speakers = 6; break; // Surround 5.1 - case 3: speakers = 8; break; // Surround 7.1 - default: speakers = 2; - } + // + // Create a mastering voice + // + if (FAILED(hr = pXAudio2->CreateMasteringVoice(&pMasteringVoice, speakers, SampleRate))) { + SysMessage("Failed creating mastering voice: %#X\n", hr); + CoUninitialize(); + return -1; + } - // - // Create a mastering voice - // - if (FAILED(hr = pXAudio2->CreateMasteringVoice(&pMasteringVoice, speakers, SampleRate))) { - SysMessage("Failed creating mastering voice: %#X\n", hr); - CoUninitialize(); - return -1; - } + switch (speakers) { + case 2: + ConLog("* SPU2 > Using normal 2 speaker stereo output.\n"); + voiceContext = new StreamingVoice(pXAudio2); + break; - switch (speakers) { - case 2: - ConLog("* SPU2 > Using normal 2 speaker stereo output.\n"); - voiceContext = new StreamingVoice(pXAudio2); - break; + case 3: + ConLog("* SPU2 > 2.1 speaker expansion enabled.\n"); + voiceContext = new StreamingVoice(pXAudio2); + break; - case 3: - ConLog("* SPU2 > 2.1 speaker expansion enabled.\n"); - voiceContext = new StreamingVoice(pXAudio2); - break; + case 4: + ConLog("* SPU2 > 4 speaker expansion enabled [quadraphenia]\n"); + voiceContext = new StreamingVoice(pXAudio2); + break; - case 4: - ConLog("* SPU2 > 4 speaker expansion enabled [quadraphenia]\n"); - voiceContext = new StreamingVoice(pXAudio2); - break; + case 5: + ConLog("* SPU2 > 4.1 speaker expansion enabled.\n"); + voiceContext = new StreamingVoice(pXAudio2); + break; - case 5: - ConLog("* SPU2 > 4.1 speaker expansion enabled.\n"); - voiceContext = new StreamingVoice(pXAudio2); - break; + case 6: + case 7: + switch (dplLevel) { + case 0: + ConLog("* SPU2 > 5.1 speaker expansion enabled.\n"); + voiceContext = new StreamingVoice(pXAudio2); //"normal" stereo upmix + break; + case 1: + ConLog("* SPU2 > 5.1 speaker expansion with basic ProLogic dematrixing enabled.\n"); + voiceContext = new StreamingVoice(pXAudio2); // basic Dpl decoder without rear stereo balancing + break; + case 2: + ConLog("* SPU2 > 5.1 speaker expansion with experimental ProLogicII dematrixing enabled.\n"); + voiceContext = new StreamingVoice(pXAudio2); //gigas PLII + break; + } + break; - case 6: - case 7: - switch (dplLevel) { - case 0: - ConLog("* SPU2 > 5.1 speaker expansion enabled.\n"); - voiceContext = new StreamingVoice(pXAudio2); //"normal" stereo upmix - break; - case 1: - ConLog("* SPU2 > 5.1 speaker expansion with basic ProLogic dematrixing enabled.\n"); - voiceContext = new StreamingVoice(pXAudio2); // basic Dpl decoder without rear stereo balancing - break; - case 2: - ConLog("* SPU2 > 5.1 speaker expansion with experimental ProLogicII dematrixing enabled.\n"); - voiceContext = new StreamingVoice(pXAudio2); //gigas PLII - break; - } - break; + default: // anything 8 or more gets the 7.1 treatment! + ConLog("* SPU2 > 7.1 speaker expansion enabled.\n"); + voiceContext = new StreamingVoice(pXAudio2); + break; + } - default: // anything 8 or more gets the 7.1 treatment! - ConLog("* SPU2 > 7.1 speaker expansion enabled.\n"); - voiceContext = new StreamingVoice(pXAudio2); - break; - } + voiceContext->Init(pXAudio2); + } catch (Exception::XAudio2Error &ex) { + SysMessage(ex.CMessage()); + pXAudio2.Release(); + CoUninitialize(); + return -1; + } - voiceContext->Init(pXAudio2); - } catch (Exception::XAudio2Error& ex) { - SysMessage(ex.CMessage()); - pXAudio2.Release(); - CoUninitialize(); - return -1; - } + return 0; + } - return 0; - } + void Close() + { + safe_delete(voiceContext); - void Close() - { - safe_delete(voiceContext); + voiceContext = NULL; - voiceContext = NULL; + if (pMasteringVoice != NULL) + pMasteringVoice->DestroyVoice(); - if (pMasteringVoice != NULL) - pMasteringVoice->DestroyVoice(); + pMasteringVoice = NULL; - pMasteringVoice = NULL; + pXAudio2.Release(); + CoUninitialize(); - pXAudio2.Release(); - CoUninitialize(); + if (xAudio2DLL) { + FreeLibrary(xAudio2DLL); + xAudio2DLL = nullptr; + pXAudio2Create = nullptr; + } + } - if (xAudio2DLL) { - FreeLibrary(xAudio2DLL); - xAudio2DLL = nullptr; - pXAudio2Create = nullptr; - } - } + virtual void Configure(uptr parent) + { + } - virtual void Configure(uptr parent) - { - } + s32 Test() const + { + return 0; + } - s32 Test() const - { - return 0; - } + int GetEmptySampleCount() + { + if (voiceContext == NULL) + return 0; + return voiceContext->GetEmptySampleCount(); + } - int GetEmptySampleCount() - { - if (voiceContext == NULL) return 0; - return voiceContext->GetEmptySampleCount(); - } + const wchar_t *GetIdent() const + { + return L"xaudio2"; + } - const wchar_t* GetIdent() const - { - return L"xaudio2"; - } + const wchar_t *GetLongName() const + { + return L"XAudio 2 (Recommended)"; + } - const wchar_t* GetLongName() const - { - return L"XAudio 2 (Recommended)"; - } + void ReadSettings() + { + } - void ReadSettings() - { - } + void SetApiSettings(wxString api) + { + } - void SetApiSettings(wxString api) - { - } - - void WriteSettings() const - { - } + void WriteSettings() const + { + } } static XA2; diff --git a/plugins/spu2-x/src/Windows/SndOut_XAudio2_27.cpp b/plugins/spu2-x/src/Windows/SndOut_XAudio2_27.cpp index b79d9fe97e..0a8a6980b9 100644 --- a/plugins/spu2-x/src/Windows/SndOut_XAudio2_27.cpp +++ b/plugins/spu2-x/src/Windows/SndOut_XAudio2_27.cpp @@ -24,410 +24,428 @@ namespace Exception { - class XAudio2_27Error : public std::runtime_error - { - protected: - static const char* SomeKindaErrorString( HRESULT hr ) - { - switch( hr ) - { - case XAUDIO2_E_INVALID_CALL: - return "Invalid call for the XA2 object state."; - - case XAUDIO2_E_DEVICE_INVALIDATED: - return "Device is unavailable, unplugged, unsupported, or has been consumed by The Nothing."; - } - return "Unknown error code!"; - } - - public: - const HRESULT ErrorCode; - std::string m_Message; - - const char* CMessage() const - { - return m_Message.c_str(); - } - - virtual ~XAudio2_27Error() throw() {} - XAudio2_27Error( const HRESULT result, const std::string& msg ) : - runtime_error( msg ), - ErrorCode( result ), - m_Message() - { - char omg[1024]; - sprintf_s( omg, "%s (code 0x%x)\n\n%s", what(), ErrorCode, SomeKindaErrorString( ErrorCode ) ); - m_Message = omg; - } - }; -} - -static const double SndOutNormalizer = (double)(1UL<<(SndOutVolumeShift+16)); - -class XAudio2_27_Mod: public SndOutModule +class XAudio2_27Error : public std::runtime_error { -private: - static const int PacketsPerBuffer = 8; - static const int MAX_BUFFER_COUNT = 3; +protected: + static const char *SomeKindaErrorString(HRESULT hr) + { + switch (hr) { + case XAUDIO2_E_INVALID_CALL: + return "Invalid call for the XA2 object state."; - class BaseStreamingVoice : public IXAudio2VoiceCallback - { - protected: - IXAudio2SourceVoice* pSourceVoice; - s16* qbuffer; - - const uint m_nBuffers; - const uint m_nChannels; - const uint m_BufferSize; - const uint m_BufferSizeBytes; - - CRITICAL_SECTION cs; - - public: - int GetEmptySampleCount() - { - XAUDIO2_VOICE_STATE state; - pSourceVoice->GetState( &state ); - return state.SamplesPlayed & (m_BufferSize-1); - } - - virtual ~BaseStreamingVoice() - { - } - - BaseStreamingVoice( uint numChannels ) : - m_nBuffers( Config_XAudio2.NumBuffers ), - m_nChannels( numChannels ), - m_BufferSize( SndOutPacketSize * m_nChannels * PacketsPerBuffer ), - m_BufferSizeBytes( m_BufferSize * sizeof(s16) ) - { - } - - virtual void Init( IXAudio2* pXAudio2 ) = 0; - - protected: - // Several things must be initialized separate of the constructor, due to the fact that - // virtual calls can't be made from the constructor's context. - void _init( IXAudio2* pXAudio2, uint chanConfig ) - { - WAVEFORMATEXTENSIBLE wfx; - - memset(&wfx, 0, sizeof(WAVEFORMATEXTENSIBLE)); - wfx.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE; - wfx.Format.nSamplesPerSec = SampleRate; - wfx.Format.nChannels = m_nChannels; - wfx.Format.wBitsPerSample = 16; - wfx.Format.nBlockAlign = wfx.Format.nChannels*wfx.Format.wBitsPerSample/8; - wfx.Format.nAvgBytesPerSec = SampleRate * wfx.Format.nBlockAlign; - wfx.Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE)-sizeof(WAVEFORMATEX); - wfx.Samples.wValidBitsPerSample = 16; - wfx.dwChannelMask = chanConfig; - wfx.SubFormat = KSDATAFORMAT_SUBTYPE_PCM; - - // - // Create an XAudio2 voice to stream this wave - // - HRESULT hr; - if( FAILED(hr = pXAudio2->CreateSourceVoice( &pSourceVoice, (WAVEFORMATEX*)&wfx, - XAUDIO2_VOICE_NOSRC, 1.0f, this ) ) ) - { - throw Exception::XAudio2_27Error( hr, "XAudio2 CreateSourceVoice failure." ); - } - - InitializeCriticalSection( &cs ); - EnterCriticalSection( &cs ); - - pSourceVoice->FlushSourceBuffers(); - pSourceVoice->Start( 0, 0 ); - - qbuffer = new s16[m_nBuffers * m_BufferSize]; - ZeroMemory( qbuffer, m_BufferSizeBytes * m_nBuffers ); - - // Start some buffers. - - for( uint i=0; iSubmitSourceBuffer( &buf ); - } - - LeaveCriticalSection( &cs ); - } - - STDMETHOD_(void, OnVoiceProcessingPassStart) () {} - STDMETHOD_(void, OnVoiceProcessingPassStart) (UINT32) { }; - STDMETHOD_(void, OnVoiceProcessingPassEnd) () {} - STDMETHOD_(void, OnStreamEnd) () {} - STDMETHOD_(void, OnBufferStart) ( void* ) {} - STDMETHOD_(void, OnLoopEnd) ( void* ) {} - STDMETHOD_(void, OnVoiceError) (THIS_ void* pBufferContext, HRESULT Error) { }; - }; - - template< typename T > - class StreamingVoice : public BaseStreamingVoice - { - public: - StreamingVoice( IXAudio2* pXAudio2 ) : - BaseStreamingVoice( sizeof(T) / sizeof( s16 ) ) - { - } - - virtual ~StreamingVoice() - { - IXAudio2SourceVoice* killMe = pSourceVoice; - pSourceVoice = NULL; - killMe->FlushSourceBuffers(); - killMe->DestroyVoice(); - - EnterCriticalSection( &cs ); - safe_delete_array( qbuffer ); - LeaveCriticalSection( &cs ); - DeleteCriticalSection( &cs ); - } - - void Init( IXAudio2* pXAudio2 ) - { - int chanMask = 0; - switch(m_nChannels) - { - case 1: chanMask |= SPEAKER_FRONT_CENTER; break; - case 2: chanMask |= SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; break; - case 3: chanMask |= SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_LOW_FREQUENCY; break; - case 4: chanMask |= SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break; - case 5: chanMask |= SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break; - case 6: chanMask |= SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT | SPEAKER_LOW_FREQUENCY; break; - case 8: chanMask |= SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT | SPEAKER_SIDE_LEFT | SPEAKER_SIDE_RIGHT | SPEAKER_LOW_FREQUENCY; break; - } - _init( pXAudio2, chanMask ); - } - - protected: - STDMETHOD_(void, OnBufferEnd) ( void* context ) - { - EnterCriticalSection( &cs ); - - // All of these checks are necessary because XAudio2 is wonky shizat. - if( pSourceVoice == NULL || context == NULL ) - { - LeaveCriticalSection( &cs ); - return; - } - - T* qb = (T*)context; - - for(int p=0; pSubmitSourceBuffer( &buf ); - LeaveCriticalSection( &cs ); - } - - }; - - HMODULE xAudio2DLL; - CComPtr pXAudio2; - IXAudio2MasteringVoice* pMasteringVoice; - BaseStreamingVoice* voiceContext; + case XAUDIO2_E_DEVICE_INVALIDATED: + return "Device is unavailable, unplugged, unsupported, or has been consumed by The Nothing."; + } + return "Unknown error code!"; + } public: + const HRESULT ErrorCode; + std::string m_Message; - s32 Init() - { - HRESULT hr; + const char *CMessage() const + { + return m_Message.c_str(); + } - pxAssume( pXAudio2 == NULL ); + virtual ~XAudio2_27Error() throw() {} + XAudio2_27Error(const HRESULT result, const std::string &msg) + : runtime_error(msg) + , ErrorCode(result) + , m_Message() + { + char omg[1024]; + sprintf_s(omg, "%s (code 0x%x)\n\n%s", what(), ErrorCode, SomeKindaErrorString(ErrorCode)); + m_Message = omg; + } +}; +} - // On some systems XAudio2.7 can unload itself and cause PCSX2 to crash. - // Maintain an extra library reference so it can't do so. Does not - // affect XAudio 2.8+, but that's Win8+. See - // http://blogs.msdn.com/b/chuckw/archive/2015/10/09/known-issues-xaudio-2-7.aspx +static const double SndOutNormalizer = (double)(1UL << (SndOutVolumeShift + 16)); + +class XAudio2_27_Mod : public SndOutModule +{ +private: + static const int PacketsPerBuffer = 8; + static const int MAX_BUFFER_COUNT = 3; + + class BaseStreamingVoice : public IXAudio2VoiceCallback + { + protected: + IXAudio2SourceVoice *pSourceVoice; + s16 *qbuffer; + + const uint m_nBuffers; + const uint m_nChannels; + const uint m_BufferSize; + const uint m_BufferSizeBytes; + + CRITICAL_SECTION cs; + + public: + int GetEmptySampleCount() + { + XAUDIO2_VOICE_STATE state; + pSourceVoice->GetState(&state); + return state.SamplesPlayed & (m_BufferSize - 1); + } + + virtual ~BaseStreamingVoice() + { + } + + BaseStreamingVoice(uint numChannels) + : m_nBuffers(Config_XAudio2.NumBuffers) + , m_nChannels(numChannels) + , m_BufferSize(SndOutPacketSize * m_nChannels * PacketsPerBuffer) + , m_BufferSizeBytes(m_BufferSize * sizeof(s16)) + { + } + + virtual void Init(IXAudio2 *pXAudio2) = 0; + + protected: + // Several things must be initialized separate of the constructor, due to the fact that + // virtual calls can't be made from the constructor's context. + void _init(IXAudio2 *pXAudio2, uint chanConfig) + { + WAVEFORMATEXTENSIBLE wfx; + + memset(&wfx, 0, sizeof(WAVEFORMATEXTENSIBLE)); + wfx.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE; + wfx.Format.nSamplesPerSec = SampleRate; + wfx.Format.nChannels = m_nChannels; + wfx.Format.wBitsPerSample = 16; + wfx.Format.nBlockAlign = wfx.Format.nChannels * wfx.Format.wBitsPerSample / 8; + wfx.Format.nAvgBytesPerSec = SampleRate * wfx.Format.nBlockAlign; + wfx.Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX); + wfx.Samples.wValidBitsPerSample = 16; + wfx.dwChannelMask = chanConfig; + wfx.SubFormat = KSDATAFORMAT_SUBTYPE_PCM; + + // + // Create an XAudio2 voice to stream this wave + // + HRESULT hr; + if (FAILED(hr = pXAudio2->CreateSourceVoice(&pSourceVoice, (WAVEFORMATEX *)&wfx, + XAUDIO2_VOICE_NOSRC, 1.0f, this))) { + throw Exception::XAudio2_27Error(hr, "XAudio2 CreateSourceVoice failure."); + } + + InitializeCriticalSection(&cs); + EnterCriticalSection(&cs); + + pSourceVoice->FlushSourceBuffers(); + pSourceVoice->Start(0, 0); + + qbuffer = new s16[m_nBuffers * m_BufferSize]; + ZeroMemory(qbuffer, m_BufferSizeBytes * m_nBuffers); + + // Start some buffers. + + for (uint i = 0; i < m_nBuffers; i++) { + XAUDIO2_BUFFER buf = {0}; + buf.AudioBytes = m_BufferSizeBytes; + buf.pContext = &qbuffer[i * m_BufferSize]; + buf.pAudioData = (BYTE *)buf.pContext; + pSourceVoice->SubmitSourceBuffer(&buf); + } + + LeaveCriticalSection(&cs); + } + + STDMETHOD_(void, OnVoiceProcessingPassStart) + () {} + STDMETHOD_(void, OnVoiceProcessingPassStart) + (UINT32){}; + STDMETHOD_(void, OnVoiceProcessingPassEnd) + () {} + STDMETHOD_(void, OnStreamEnd) + () {} + STDMETHOD_(void, OnBufferStart) + (void *) {} + STDMETHOD_(void, OnLoopEnd) + (void *) {} + STDMETHOD_(void, OnVoiceError) + (THIS_ void *pBufferContext, HRESULT Error){}; + }; + + template + class StreamingVoice : public BaseStreamingVoice + { + public: + StreamingVoice(IXAudio2 *pXAudio2) + : BaseStreamingVoice(sizeof(T) / sizeof(s16)) + { + } + + virtual ~StreamingVoice() + { + IXAudio2SourceVoice *killMe = pSourceVoice; + pSourceVoice = NULL; + killMe->FlushSourceBuffers(); + killMe->DestroyVoice(); + + EnterCriticalSection(&cs); + safe_delete_array(qbuffer); + LeaveCriticalSection(&cs); + DeleteCriticalSection(&cs); + } + + void Init(IXAudio2 *pXAudio2) + { + int chanMask = 0; + switch (m_nChannels) { + case 1: + chanMask |= SPEAKER_FRONT_CENTER; + break; + case 2: + chanMask |= SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; + break; + case 3: + chanMask |= SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_LOW_FREQUENCY; + break; + case 4: + chanMask |= SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; + break; + case 5: + chanMask |= SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; + break; + case 6: + chanMask |= SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT | SPEAKER_LOW_FREQUENCY; + break; + case 8: + chanMask |= SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT | SPEAKER_SIDE_LEFT | SPEAKER_SIDE_RIGHT | SPEAKER_LOW_FREQUENCY; + break; + } + _init(pXAudio2, chanMask); + } + + protected: + STDMETHOD_(void, OnBufferEnd) + (void *context) + { + EnterCriticalSection(&cs); + + // All of these checks are necessary because XAudio2 is wonky shizat. + if (pSourceVoice == NULL || context == NULL) { + LeaveCriticalSection(&cs); + return; + } + + T *qb = (T *)context; + + for (int p = 0; p < PacketsPerBuffer; p++, qb += SndOutPacketSize) + SndBuffer::ReadSamples(qb); + + XAUDIO2_BUFFER buf = {0}; + buf.AudioBytes = m_BufferSizeBytes; + buf.pAudioData = (BYTE *)context; + buf.pContext = context; + + pSourceVoice->SubmitSourceBuffer(&buf); + LeaveCriticalSection(&cs); + } + }; + + HMODULE xAudio2DLL; + CComPtr pXAudio2; + IXAudio2MasteringVoice *pMasteringVoice; + BaseStreamingVoice *voiceContext; + +public: + s32 Init() + { + HRESULT hr; + + pxAssume(pXAudio2 == NULL); + +// On some systems XAudio2.7 can unload itself and cause PCSX2 to crash. +// Maintain an extra library reference so it can't do so. Does not +// affect XAudio 2.8+, but that's Win8+. See +// http://blogs.msdn.com/b/chuckw/archive/2015/10/09/known-issues-xaudio-2-7.aspx #ifdef _DEBUG - xAudio2DLL = LoadLibrary(L"XAudioD2_7.dll"); + xAudio2DLL = LoadLibrary(L"XAudioD2_7.dll"); #else - xAudio2DLL = LoadLibrary(L"XAudio2_7.dll"); + xAudio2DLL = LoadLibrary(L"XAudio2_7.dll"); #endif - // - // Initialize XAudio2 - // - CoInitializeEx( NULL, COINIT_MULTITHREADED ); + // + // Initialize XAudio2 + // + CoInitializeEx(NULL, COINIT_MULTITHREADED); - UINT32 flags = 0; - if( IsDebugBuild ) - flags |= XAUDIO2_DEBUG_ENGINE; + UINT32 flags = 0; + if (IsDebugBuild) + flags |= XAUDIO2_DEBUG_ENGINE; - try - { - if ( FAILED(hr = XAudio2Create( &pXAudio2, flags ) ) ) - throw Exception::XAudio2_27Error( hr, - "Failed to init XAudio2 engine. XA2 may not be available on your system.\n" - "Ensure that you have the latest DirectX runtimes installed, or use \n" - "DirectX / WaveOut drivers instead. Error Details:" - ); + try { + if (FAILED(hr = XAudio2Create(&pXAudio2, flags))) + throw Exception::XAudio2_27Error(hr, + "Failed to init XAudio2 engine. XA2 may not be available on your system.\n" + "Ensure that you have the latest DirectX runtimes installed, or use \n" + "DirectX / WaveOut drivers instead. Error Details:"); - XAUDIO2_DEVICE_DETAILS deviceDetails; - pXAudio2->GetDeviceDetails( 0, &deviceDetails ); + XAUDIO2_DEVICE_DETAILS deviceDetails; + pXAudio2->GetDeviceDetails(0, &deviceDetails); - // Stereo Expansion was planned to grab the currently configured number of - // Speakers from Windows's audio config. - // This doesn't always work though, so let it be a user configurable option. + // Stereo Expansion was planned to grab the currently configured number of + // Speakers from Windows's audio config. + // This doesn't always work though, so let it be a user configurable option. - int speakers; - switch(numSpeakers) // speakers = (numSpeakers + 1) *2; ? - { - case 0: speakers = 2; break; // Stereo - case 1: speakers = 4; break; // Quadrafonic - case 2: speakers = 6; break; // Surround 5.1 - case 3: speakers = 8; break; // Surround 7.1 - default: speakers = 2; - } + int speakers; + switch (numSpeakers) // speakers = (numSpeakers + 1) *2; ? + { + case 0: + speakers = 2; + break; // Stereo + case 1: + speakers = 4; + break; // Quadrafonic + case 2: + speakers = 6; + break; // Surround 5.1 + case 3: + speakers = 8; + break; // Surround 7.1 + default: + speakers = 2; + } - // Any windows driver should support stereo at the software level, I should think! - pxAssume( deviceDetails.OutputFormat.Format.nChannels > 1 ); + // Any windows driver should support stereo at the software level, I should think! + pxAssume(deviceDetails.OutputFormat.Format.nChannels > 1); - // - // Create a mastering voice - // - if ( FAILED(hr = pXAudio2->CreateMasteringVoice( &pMasteringVoice, speakers, SampleRate ) ) ) - { - SysMessage( "Failed creating mastering voice: %#X\n", hr ); - CoUninitialize(); - return -1; - } + // + // Create a mastering voice + // + if (FAILED(hr = pXAudio2->CreateMasteringVoice(&pMasteringVoice, speakers, SampleRate))) { + SysMessage("Failed creating mastering voice: %#X\n", hr); + CoUninitialize(); + return -1; + } - switch( speakers ) - { - case 2: - ConLog( "* SPU2 > Using normal 2 speaker stereo output.\n" ); - voiceContext = new StreamingVoice( pXAudio2 ); - break; + switch (speakers) { + case 2: + ConLog("* SPU2 > Using normal 2 speaker stereo output.\n"); + voiceContext = new StreamingVoice(pXAudio2); + break; - case 3: - ConLog( "* SPU2 > 2.1 speaker expansion enabled.\n" ); - voiceContext = new StreamingVoice( pXAudio2 ); - break; + case 3: + ConLog("* SPU2 > 2.1 speaker expansion enabled.\n"); + voiceContext = new StreamingVoice(pXAudio2); + break; - case 4: - ConLog( "* SPU2 > 4 speaker expansion enabled [quadraphenia]\n" ); - voiceContext = new StreamingVoice( pXAudio2 ); - break; + case 4: + ConLog("* SPU2 > 4 speaker expansion enabled [quadraphenia]\n"); + voiceContext = new StreamingVoice(pXAudio2); + break; - case 5: - ConLog( "* SPU2 > 4.1 speaker expansion enabled.\n" ); - voiceContext = new StreamingVoice( pXAudio2 ); - break; + case 5: + ConLog("* SPU2 > 4.1 speaker expansion enabled.\n"); + voiceContext = new StreamingVoice(pXAudio2); + break; - case 6: - case 7: - switch(dplLevel) - { - case 0: - ConLog( "* SPU2 > 5.1 speaker expansion enabled.\n" ); - voiceContext = new StreamingVoice( pXAudio2 ); //"normal" stereo upmix - break; - case 1: - ConLog( "* SPU2 > 5.1 speaker expansion with basic ProLogic dematrixing enabled.\n" ); - voiceContext = new StreamingVoice( pXAudio2 ); // basic Dpl decoder without rear stereo balancing - break; - case 2: - ConLog( "* SPU2 > 5.1 speaker expansion with experimental ProLogicII dematrixing enabled.\n" ); - voiceContext = new StreamingVoice( pXAudio2 ); //gigas PLII - break; - } - break; + case 6: + case 7: + switch (dplLevel) { + case 0: + ConLog("* SPU2 > 5.1 speaker expansion enabled.\n"); + voiceContext = new StreamingVoice(pXAudio2); //"normal" stereo upmix + break; + case 1: + ConLog("* SPU2 > 5.1 speaker expansion with basic ProLogic dematrixing enabled.\n"); + voiceContext = new StreamingVoice(pXAudio2); // basic Dpl decoder without rear stereo balancing + break; + case 2: + ConLog("* SPU2 > 5.1 speaker expansion with experimental ProLogicII dematrixing enabled.\n"); + voiceContext = new StreamingVoice(pXAudio2); //gigas PLII + break; + } + break; - default: // anything 8 or more gets the 7.1 treatment! - ConLog( "* SPU2 > 7.1 speaker expansion enabled.\n" ); - voiceContext = new StreamingVoice( pXAudio2 ); - break; - } + default: // anything 8 or more gets the 7.1 treatment! + ConLog("* SPU2 > 7.1 speaker expansion enabled.\n"); + voiceContext = new StreamingVoice(pXAudio2); + break; + } - voiceContext->Init( pXAudio2 ); - } - catch( Exception::XAudio2_27Error& ex ) - { - SysMessage( ex.CMessage() ); - pXAudio2.Release(); - CoUninitialize(); - return -1; - } + voiceContext->Init(pXAudio2); + } catch (Exception::XAudio2_27Error &ex) { + SysMessage(ex.CMessage()); + pXAudio2.Release(); + CoUninitialize(); + return -1; + } - return 0; - } + return 0; + } - void Close() - { - // Clean up? - // All XAudio2 interfaces are released when the engine is destroyed, - // but being tidy never hurt. + void Close() + { + // Clean up? + // All XAudio2 interfaces are released when the engine is destroyed, + // but being tidy never hurt. - // Actually it can hurt. As of DXSDK Aug 2008, doing a full cleanup causes - // XA2 on Vista to crash. Even if you copy/paste code directly from Microsoft. - // But doing no cleanup at all causes XA2 under XP to crash. So after much trial - // and error we found a happy compromise as follows: + // Actually it can hurt. As of DXSDK Aug 2008, doing a full cleanup causes + // XA2 on Vista to crash. Even if you copy/paste code directly from Microsoft. + // But doing no cleanup at all causes XA2 under XP to crash. So after much trial + // and error we found a happy compromise as follows: - safe_delete( voiceContext ); + safe_delete(voiceContext); - voiceContext = NULL; + voiceContext = NULL; - if( pMasteringVoice != NULL ) - pMasteringVoice->DestroyVoice(); + if (pMasteringVoice != NULL) + pMasteringVoice->DestroyVoice(); - pMasteringVoice = NULL; + pMasteringVoice = NULL; - pXAudio2.Release(); - CoUninitialize(); + pXAudio2.Release(); + CoUninitialize(); - if (xAudio2DLL) { - FreeLibrary(xAudio2DLL); - xAudio2DLL = nullptr; - } - } + if (xAudio2DLL) { + FreeLibrary(xAudio2DLL); + xAudio2DLL = nullptr; + } + } - virtual void Configure(uptr parent) - { - } + virtual void Configure(uptr parent) + { + } - s32 Test() const - { - return 0; - } + s32 Test() const + { + return 0; + } - int GetEmptySampleCount() - { - if( voiceContext == NULL ) return 0; - return voiceContext->GetEmptySampleCount(); - } + int GetEmptySampleCount() + { + if (voiceContext == NULL) + return 0; + return voiceContext->GetEmptySampleCount(); + } - const wchar_t* GetIdent() const - { - return L"xaudio2"; - } + const wchar_t *GetIdent() const + { + return L"xaudio2"; + } - const wchar_t* GetLongName() const - { - return L"XAudio 2.7 (Recommended)"; - } + const wchar_t *GetLongName() const + { + return L"XAudio 2.7 (Recommended)"; + } - void ReadSettings() - { - } + void ReadSettings() + { + } - void SetApiSettings(wxString api) - { - } + void SetApiSettings(wxString api) + { + } - void WriteSettings() const - { - } + void WriteSettings() const + { + } } static XA2; diff --git a/plugins/spu2-x/src/Windows/SndOut_waveOut.cpp b/plugins/spu2-x/src/Windows/SndOut_waveOut.cpp index 9bf512b3d5..a068c159c3 100644 --- a/plugins/spu2-x/src/Windows/SndOut_waveOut.cpp +++ b/plugins/spu2-x/src/Windows/SndOut_waveOut.cpp @@ -19,80 +19,80 @@ #include "Dialogs.h" -class WaveOutModule: public SndOutModule +class WaveOutModule : public SndOutModule { private: - static const uint MAX_BUFFER_COUNT = 8; + static const uint MAX_BUFFER_COUNT = 8; - static const int PacketsPerBuffer = (1024 / SndOutPacketSize); - static const int BufferSize = SndOutPacketSize*PacketsPerBuffer; + static const int PacketsPerBuffer = (1024 / SndOutPacketSize); + static const int BufferSize = SndOutPacketSize * PacketsPerBuffer; - u32 numBuffers; - HWAVEOUT hwodevice; - WAVEFORMATEX wformat; - WAVEHDR whbuffer[MAX_BUFFER_COUNT]; + u32 numBuffers; + HWAVEOUT hwodevice; + WAVEFORMATEX wformat; + WAVEHDR whbuffer[MAX_BUFFER_COUNT]; - StereoOut16* qbuffer; + StereoOut16 *qbuffer; - #define QBUFFER(x) (qbuffer + BufferSize * (x)) +#define QBUFFER(x) (qbuffer + BufferSize * (x)) - bool waveout_running; - HANDLE thread; - DWORD tid; + bool waveout_running; + HANDLE thread; + DWORD tid; - wchar_t ErrText[256]; + wchar_t ErrText[256]; - template< typename T > - DWORD CALLBACK Thread() - { - static const int BufferSizeBytes = BufferSize * sizeof( T ); + template + DWORD CALLBACK Thread() + { + static const int BufferSizeBytes = BufferSize * sizeof(T); - while( waveout_running ) - { - bool didsomething = false; - for(u32 i=0;idwBytesRecorded = buf->dwBufferLength; + buf->dwBytesRecorded = buf->dwBufferLength; - T* t = (T*)buf->lpData; - for(int p=0; plpData; + for (int p = 0; p < PacketsPerBuffer; p++, t += SndOutPacketSize) + SndBuffer::ReadSamples(t); - whbuffer[i].dwFlags &= ~WHDR_DONE; - waveOutWrite( hwodevice, buf, sizeof(WAVEHDR) ); - didsomething = true; - } + whbuffer[i].dwFlags &= ~WHDR_DONE; + waveOutWrite(hwodevice, buf, sizeof(WAVEHDR)); + didsomething = true; + } - if( didsomething ) - Sleep(1); - else - Sleep(0); - } - return 0; - } + if (didsomething) + Sleep(1); + else + Sleep(0); + } + return 0; + } - template< typename T > - static DWORD CALLBACK RThread(WaveOutModule*obj) - { - return obj->Thread(); - } + template + static DWORD CALLBACK RThread(WaveOutModule *obj) + { + return obj->Thread(); + } public: - s32 Init() - { - numBuffers = Config_WaveOut.NumBuffers; + s32 Init() + { + numBuffers = Config_WaveOut.NumBuffers; - MMRESULT woores; + MMRESULT woores; - if (Test()) return -1; + if (Test()) + return -1; - // TODO : Use dsound to determine the speaker configuration, and expand audio from there. +// TODO : Use dsound to determine the speaker configuration, and expand audio from there. - #if 0 +#if 0 int speakerConfig; //if( StereoExpansionEnabled ) @@ -129,197 +129,193 @@ public: speakerConfig = 8; break; } - #endif +#endif - wformat.wFormatTag = WAVE_FORMAT_PCM; - wformat.nSamplesPerSec = SampleRate; - wformat.wBitsPerSample = 16; - wformat.nChannels = 2; - wformat.nBlockAlign = ((wformat.wBitsPerSample * wformat.nChannels) / 8); - wformat.nAvgBytesPerSec = (wformat.nSamplesPerSec * wformat.nBlockAlign); - wformat.cbSize = 0; + wformat.wFormatTag = WAVE_FORMAT_PCM; + wformat.nSamplesPerSec = SampleRate; + wformat.wBitsPerSample = 16; + wformat.nChannels = 2; + wformat.nBlockAlign = ((wformat.wBitsPerSample * wformat.nChannels) / 8); + wformat.nAvgBytesPerSec = (wformat.nSamplesPerSec * wformat.nBlockAlign); + wformat.cbSize = 0; - qbuffer = new StereoOut16[BufferSize*numBuffers]; + qbuffer = new StereoOut16[BufferSize * numBuffers]; - woores = waveOutOpen(&hwodevice,WAVE_MAPPER,&wformat,0,0,0); - if (woores != MMSYSERR_NOERROR) - { - waveOutGetErrorText(woores,(wchar_t *)&ErrText,255); - SysMessage("WaveOut Error: %s",ErrText); - return -1; - } + woores = waveOutOpen(&hwodevice, WAVE_MAPPER, &wformat, 0, 0, 0); + if (woores != MMSYSERR_NOERROR) { + waveOutGetErrorText(woores, (wchar_t *)&ErrText, 255); + SysMessage("WaveOut Error: %s", ErrText); + return -1; + } - const int BufferSizeBytes = wformat.nBlockAlign * BufferSize; + const int BufferSizeBytes = wformat.nBlockAlign * BufferSize; - for(u32 i=0;i,this,0,&tid); + // Start Thread + // [Air]: The waveout code does not use wait objects, so setting a time critical + // priority level is a bad idea. Standard priority will do fine. The buffer will get the + // love it needs and won't suck resources idling pointlessly. Just don't try to + // run it in uber-low-latency mode. + waveout_running = true; + thread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)RThread, this, 0, &tid); - return 0; - } + return 0; + } - void Close() - { - // Stop Thread - fprintf(stderr,"* SPU2-X: Waiting for waveOut thread to finish..."); - waveout_running=false; + void Close() + { + // Stop Thread + fprintf(stderr, "* SPU2-X: Waiting for waveOut thread to finish..."); + waveout_running = false; - WaitForSingleObject(thread,INFINITE); - CloseHandle(thread); + WaitForSingleObject(thread, INFINITE); + CloseHandle(thread); - fprintf(stderr," Done.\n"); + fprintf(stderr, " Done.\n"); - // - // Clean up - // - waveOutReset(hwodevice); - for(u32 i=0;i MAX_BUFFER_COUNT) + Config_WaveOut.NumBuffers = MAX_BUFFER_COUNT; + } + EndDialog(hWnd, 0); + break; + case IDCANCEL: + EndDialog(hWnd, 0); + break; + default: + return FALSE; + } + break; - if( Config_WaveOut.NumBuffers < 3 ) Config_WaveOut.NumBuffers = 3; - if( Config_WaveOut.NumBuffers > MAX_BUFFER_COUNT ) Config_WaveOut.NumBuffers = MAX_BUFFER_COUNT; - } - EndDialog(hWnd,0); - break; - case IDCANCEL: - EndDialog(hWnd,0); - break; - default: - return FALSE; - } - break; + case WM_HSCROLL: + wmId = LOWORD(wParam); + wmEvent = HIWORD(wParam); + switch (wmId) { + //case TB_ENDTRACK: + //case TB_THUMBPOSITION: + case TB_LINEUP: + case TB_LINEDOWN: + case TB_PAGEUP: + case TB_PAGEDOWN: + wmEvent = (int)SendMessage((HWND)lParam, TBM_GETPOS, 0, 0); + case TB_THUMBTRACK: + if (wmEvent < 3) + wmEvent = 3; + if (wmEvent > MAX_BUFFER_COUNT) + wmEvent = MAX_BUFFER_COUNT; + SendMessage((HWND)lParam, TBM_SETPOS, TRUE, wmEvent); + swprintf_s(temp, L"%d (%d ms latency)", wmEvent, 1000 / (96000 / (wmEvent * BufferSize))); + SetWindowText(GetDlgItem(hWnd, IDC_LATENCY_LABEL), temp); + break; + default: + return FALSE; + } + break; - case WM_HSCROLL: - wmId = LOWORD(wParam); - wmEvent = HIWORD(wParam); - switch(wmId) { - //case TB_ENDTRACK: - //case TB_THUMBPOSITION: - case TB_LINEUP: - case TB_LINEDOWN: - case TB_PAGEUP: - case TB_PAGEDOWN: - wmEvent=(int)SendMessage((HWND)lParam,TBM_GETPOS,0,0); - case TB_THUMBTRACK: - if( wmEvent < 3 ) wmEvent = 3; - if( wmEvent > MAX_BUFFER_COUNT ) wmEvent = MAX_BUFFER_COUNT; - SendMessage((HWND)lParam,TBM_SETPOS,TRUE,wmEvent); - swprintf_s(temp, L"%d (%d ms latency)",wmEvent, 1000 / (96000 / (wmEvent * BufferSize))); - SetWindowText(GetDlgItem(hWnd,IDC_LATENCY_LABEL),temp); - break; - default: - return FALSE; - } - break; - - default: - return FALSE; - } - return TRUE; - } + default: + return FALSE; + } + return TRUE; + } public: - virtual void Configure(uptr parent) - { - INT_PTR ret; - ret=DialogBoxParam(hInstance,MAKEINTRESOURCE(IDD_WAVEOUT), (HWND)parent, (DLGPROC)ConfigProc,1); - if(ret==-1) - { - MessageBox((HWND)parent, L"Error Opening the config dialog.", L"OMG ERROR!", MB_OK | MB_SETFOREGROUND); - return; - } - } - - s32 Test() const - { - if (waveOutGetNumDevs() == 0) { - SysMessage("No waveOut Devices Present\n"); return -1; - } - return 0; - } + virtual void Configure(uptr parent) + { + INT_PTR ret; + ret = DialogBoxParam(hInstance, MAKEINTRESOURCE(IDD_WAVEOUT), (HWND)parent, (DLGPROC)ConfigProc, 1); + if (ret == -1) { + MessageBox((HWND)parent, L"Error Opening the config dialog.", L"OMG ERROR!", MB_OK | MB_SETFOREGROUND); + return; + } + } - int GetEmptySampleCount() - { - int result = 0; - for(int i=0;iData1 = guid_u32; - guid->Data2 = guid_u16[0]; - guid->Data3 = guid_u16[1]; - guid->Data4[0] = (u8)guid_u8[0]; - guid->Data4[1] = (u8)guid_u8[1]; - guid->Data4[2] = (u8)guid_u8[2]; - guid->Data4[3] = (u8)guid_u8[3]; - guid->Data4[4] = (u8)guid_u8[4]; - guid->Data4[5] = (u8)guid_u8[5]; - guid->Data4[6] = (u8)guid_u8[6]; - guid->Data4[7] = (u8)guid_u8[7]; - return 0; + guid->Data1 = guid_u32; + guid->Data2 = guid_u16[0]; + guid->Data3 = guid_u16[1]; + guid->Data4[0] = (u8)guid_u8[0]; + guid->Data4[1] = (u8)guid_u8[1]; + guid->Data4[2] = (u8)guid_u8[2]; + guid->Data4[3] = (u8)guid_u8[3]; + guid->Data4[4] = (u8)guid_u8[4]; + guid->Data4[5] = (u8)guid_u8[5]; + guid->Data4[6] = (u8)guid_u8[6]; + guid->Data4[7] = (u8)guid_u8[7]; + return 0; } -__forceinline void Verifyc(HRESULT hr, const char* fn) +__forceinline void Verifyc(HRESULT hr, const char *fn) { - if(FAILED(hr)) - { - assert( 0 ); - throw std::runtime_error( "DirectSound returned an error from %s" ); - } + if (FAILED(hr)) { + assert(0); + throw std::runtime_error("DirectSound returned an error from %s"); + } } -void AssignSliderValue( HWND idcwnd, HWND hwndDisplay, int value ) +void AssignSliderValue(HWND idcwnd, HWND hwndDisplay, int value) { - value = std::min( std::max( value, 0 ), 512 ); - SendMessage(idcwnd,TBM_SETPOS,TRUE,value); + value = std::min(std::max(value, 0), 512); + SendMessage(idcwnd, TBM_SETPOS, TRUE, value); - wchar_t tbox[32]; - swprintf_s( tbox, L"%d", value ); - SetWindowText( hwndDisplay, tbox ); + wchar_t tbox[32]; + swprintf_s(tbox, L"%d", value); + SetWindowText(hwndDisplay, tbox); } -void AssignSliderValue( HWND hWnd, int idc, int editbox, int value ) +void AssignSliderValue(HWND hWnd, int idc, int editbox, int value) { - AssignSliderValue( GetDlgItem( hWnd, idc ), GetDlgItem( hWnd, editbox ), value ); + AssignSliderValue(GetDlgItem(hWnd, idc), GetDlgItem(hWnd, editbox), value); } // Generic slider/scroller message handler. This is succient so long as you // don't need some kind of secondary event handling functionality, such as // updating a custom label. -BOOL DoHandleScrollMessage( HWND hwndDisplay, WPARAM wParam, LPARAM lParam ) +BOOL DoHandleScrollMessage(HWND hwndDisplay, WPARAM wParam, LPARAM lParam) { - int wmId = LOWORD(wParam); - int wmEvent = HIWORD(wParam); - - switch(wmId) - { - //case TB_ENDTRACK: - //case TB_THUMBPOSITION: - case TB_LINEUP: - case TB_LINEDOWN: - case TB_PAGEUP: - case TB_PAGEDOWN: - wmEvent = (int)SendMessage((HWND)lParam,TBM_GETPOS,0,0); - case TB_THUMBTRACK: - AssignSliderValue( (HWND)lParam, hwndDisplay, wmEvent ); - break; + int wmId = LOWORD(wParam); + int wmEvent = HIWORD(wParam); - default: - return FALSE; - } - return TRUE; + switch (wmId) { + //case TB_ENDTRACK: + //case TB_THUMBPOSITION: + case TB_LINEUP: + case TB_LINEDOWN: + case TB_PAGEUP: + case TB_PAGEDOWN: + wmEvent = (int)SendMessage((HWND)lParam, TBM_GETPOS, 0, 0); + case TB_THUMBTRACK: + AssignSliderValue((HWND)lParam, hwndDisplay, wmEvent); + break; + + default: + return FALSE; + } + return TRUE; } -int GetSliderValue( HWND hWnd, int idc ) +int GetSliderValue(HWND hWnd, int idc) { - int retval = (int)SendMessage( GetDlgItem( hWnd, idc ), TBM_GETPOS, 0, 0 ); - return GetClamped( retval, 0, 512 ); + int retval = (int)SendMessage(GetDlgItem(hWnd, idc), TBM_GETPOS, 0, 0); + return GetClamped(retval, 0, 512); } - diff --git a/plugins/spu2-x/src/Windows/WinConfig.h b/plugins/spu2-x/src/Windows/WinConfig.h index 3169a9d4e2..e3b8888ebe 100644 --- a/plugins/spu2-x/src/Windows/WinConfig.h +++ b/plugins/spu2-x/src/Windows/WinConfig.h @@ -31,20 +31,28 @@ extern HINSTANCE hInstance; -#define SET_CHECK(idc,value) SendMessage(GetDlgItem(hWnd,idc),BM_SETCHECK,((value)==0)?BST_UNCHECKED:BST_CHECKED,0) -#define HANDLE_CHECK(idc,hvar) case idc: (hvar) = !(hvar); SendMessage(GetDlgItem(hWnd,idc),BM_SETCHECK,(hvar)?BST_CHECKED:BST_UNCHECKED,0); break -#define HANDLE_CHECKNB(idc,hvar)case idc: (hvar) = !(hvar); SendMessage(GetDlgItem(hWnd,idc),BM_SETCHECK,(hvar)?BST_CHECKED:BST_UNCHECKED,0) -#define ENABLE_CONTROL(idc,value) EnableWindow(GetDlgItem(hWnd,idc),value) +#define SET_CHECK(idc, value) SendMessage(GetDlgItem(hWnd, idc), BM_SETCHECK, ((value) == 0) ? BST_UNCHECKED : BST_CHECKED, 0) +#define HANDLE_CHECK(idc, hvar) \ + case idc: \ + (hvar) = !(hvar); \ + SendMessage(GetDlgItem(hWnd, idc), BM_SETCHECK, (hvar) ? BST_CHECKED : BST_UNCHECKED, 0); \ + break +#define HANDLE_CHECKNB(idc, hvar) \ + case idc: \ + (hvar) = !(hvar); \ + SendMessage(GetDlgItem(hWnd, idc), BM_SETCHECK, (hvar) ? BST_CHECKED : BST_UNCHECKED, 0) +#define ENABLE_CONTROL(idc, value) EnableWindow(GetDlgItem(hWnd, idc), value) -#define INIT_SLIDER(idc,minrange,maxrange,tickfreq,pagesize,linesize) \ - SendMessage(GetDlgItem(hWnd,idc),TBM_SETRANGEMIN,FALSE,minrange); \ - SendMessage(GetDlgItem(hWnd,idc),TBM_SETRANGEMAX,FALSE,maxrange); \ - SendMessage(GetDlgItem(hWnd,idc),TBM_SETTICFREQ,tickfreq,0); \ - SendMessage(GetDlgItem(hWnd,idc),TBM_SETPAGESIZE,0,pagesize); \ - SendMessage(GetDlgItem(hWnd,idc),TBM_SETLINESIZE,0,linesize) +#define INIT_SLIDER(idc, minrange, maxrange, tickfreq, pagesize, linesize) \ + SendMessage(GetDlgItem(hWnd, idc), TBM_SETRANGEMIN, FALSE, minrange); \ + SendMessage(GetDlgItem(hWnd, idc), TBM_SETRANGEMAX, FALSE, maxrange); \ + SendMessage(GetDlgItem(hWnd, idc), TBM_SETTICFREQ, tickfreq, 0); \ + SendMessage(GetDlgItem(hWnd, idc), TBM_SETPAGESIZE, 0, pagesize); \ + SendMessage(GetDlgItem(hWnd, idc), TBM_SETLINESIZE, 0, linesize) -#define HANDLE_SCROLL_MESSAGE(idc,idcDisplay) \ - if((HWND)lParam == GetDlgItem(hWnd,idc)) return DoHandleScrollMessage( GetDlgItem(hWnd,idcDisplay), wParam, lParam ) +#define HANDLE_SCROLL_MESSAGE(idc, idcDisplay) \ + if ((HWND)lParam == GetDlgItem(hWnd, idc)) \ + return DoHandleScrollMessage(GetDlgItem(hWnd, idcDisplay), wParam, lParam) // *** BEGIN DRIVER-SPECIFIC CONFIGURATION *** @@ -52,26 +60,26 @@ extern HINSTANCE hInstance; struct CONFIG_XAUDIO2 { - wxString Device; - s8 NumBuffers; + wxString Device; + s8 NumBuffers; - CONFIG_XAUDIO2() : - Device(), - NumBuffers( 2 ) - { - } + CONFIG_XAUDIO2() + : Device() + , NumBuffers(2) + { + } }; struct CONFIG_WAVEOUT { - wxString Device; - s8 NumBuffers; + wxString Device; + s8 NumBuffers; - CONFIG_WAVEOUT() : - Device(), - NumBuffers( 4 ) - { - } + CONFIG_WAVEOUT() + : Device() + , NumBuffers(4) + { + } }; extern CONFIG_WAVEOUT Config_WaveOut; diff --git a/plugins/spu2-x/src/Windows/dsp.cpp b/plugins/spu2-x/src/Windows/dsp.cpp index db8debf23e..0a863cebba 100644 --- a/plugins/spu2-x/src/Windows/dsp.cpp +++ b/plugins/spu2-x/src/Windows/dsp.cpp @@ -26,14 +26,14 @@ extern "C" { #include "dsp.h" -typedef winampDSPHeader* (*pWinampDSPGetHeader2)(); +typedef winampDSPHeader *(*pWinampDSPGetHeader2)(); } HMODULE hLib = NULL; pWinampDSPGetHeader2 pGetHeader = NULL; -winampDSPHeader* pHeader = NULL; +winampDSPHeader *pHeader = NULL; -winampDSPModule* pModule = NULL; +winampDSPModule *pModule = NULL; HWND hTemp; @@ -50,92 +50,91 @@ DWORD WINAPI DspUpdateThread(PVOID param); s32 DspLoadLibrary(wchar_t *fileName, int modNum) #ifdef USE_A_THREAD { - if(!dspPluginEnabled) return -1; + if (!dspPluginEnabled) + return -1; - running=true; - hUpdateThread = CreateThread(NULL,0,DspUpdateThread,NULL,0,&UpdateThreadId); - return (hUpdateThread==INVALID_HANDLE_VALUE); + running = true; + hUpdateThread = CreateThread(NULL, 0, DspUpdateThread, NULL, 0, &UpdateThreadId); + return (hUpdateThread == INVALID_HANDLE_VALUE); } -s32 DspLoadLibrary2( wchar_t *fileName, int modNum ) +s32 DspLoadLibrary2(wchar_t *fileName, int modNum) #endif { - if( !dspPluginEnabled ) return -1; + if (!dspPluginEnabled) + return -1; - hLib = LoadLibraryW( fileName ); - if(!hLib) - { - return 1; - } + hLib = LoadLibraryW(fileName); + if (!hLib) { + return 1; + } - pGetHeader = (pWinampDSPGetHeader2)GetProcAddress(hLib,"winampDSPGetHeader2"); + pGetHeader = (pWinampDSPGetHeader2)GetProcAddress(hLib, "winampDSPGetHeader2"); - if(!pGetHeader) - { - FreeLibrary(hLib); - hLib=NULL; - return 1; - } + if (!pGetHeader) { + FreeLibrary(hLib); + hLib = NULL; + return 1; + } - pHeader = pGetHeader(); + pHeader = pGetHeader(); - pModule = pHeader->getModule(modNum); + pModule = pHeader->getModule(modNum); - if(!pModule) - { - pGetHeader=NULL; - pHeader=NULL; - FreeLibrary(hLib); - hLib=NULL; - return -1; - } + if (!pModule) { + pGetHeader = NULL; + pHeader = NULL; + FreeLibrary(hLib); + hLib = NULL; + return -1; + } - pModule->hDllInstance = hLib; - pModule->hwndParent=0; - pModule->Init(pModule); + pModule->hDllInstance = hLib; + pModule->hwndParent = 0; + pModule->Init(pModule); - return 0; + return 0; } void DspCloseLibrary() #ifdef USE_A_THREAD { - if(!dspPluginEnabled) return ; + if (!dspPluginEnabled) + return; - PostThreadMessage(UpdateThreadId,WM_QUIT,0,0); - running=false; - if(WaitForSingleObject(hUpdateThread,1000)==WAIT_TIMEOUT) - { - ConLog("SPU2-X: WARNING: DSP Thread did not close itself in time. Assuming hung. Terminating.\n"); - TerminateThread(hUpdateThread,1); - } + PostThreadMessage(UpdateThreadId, WM_QUIT, 0, 0); + running = false; + if (WaitForSingleObject(hUpdateThread, 1000) == WAIT_TIMEOUT) { + ConLog("SPU2-X: WARNING: DSP Thread did not close itself in time. Assuming hung. Terminating.\n"); + TerminateThread(hUpdateThread, 1); + } } void DspCloseLibrary2() #endif { - if(!dspPluginEnabled) return ; + if (!dspPluginEnabled) + return; - if(hLib) - { - pModule->Quit(pModule); - FreeLibrary(hLib); - } - pModule=NULL; - pHeader=NULL; - pGetHeader=NULL; - hLib=NULL; + if (hLib) { + pModule->Quit(pModule); + FreeLibrary(hLib); + } + pModule = NULL; + pHeader = NULL; + pGetHeader = NULL; + hLib = NULL; } int DspProcess(s16 *buffer, int samples) { - if(!dspPluginEnabled) return samples; + if (!dspPluginEnabled) + return samples; - if(hLib) - { - return pModule->ModifySamples(pModule,buffer,samples,16,2,SampleRate); - } - return samples; + if (hLib) { + return pModule->ModifySamples(pModule, buffer, samples, 16, 2, SampleRate); + } + return samples; } void DspUpdate() @@ -145,37 +144,36 @@ void DspUpdate() DWORD WINAPI DspUpdateThread(PVOID param) { - if( !dspPluginEnabled ) return -1; + if (!dspPluginEnabled) + return -1; - if( DspLoadLibrary2( dspPlugin, dspPluginModule ) ) - return -1; + if (DspLoadLibrary2(dspPlugin, dspPluginModule)) + return -1; - MSG msg; - while(running) - { - GetMessage(&msg,0,0,0); - if((msg.hwnd==NULL)&&(msg.message==WM_QUIT)) - { - break; - } - TranslateMessage(&msg); - DispatchMessage(&msg); - } + MSG msg; + while (running) { + GetMessage(&msg, 0, 0, 0); + if ((msg.hwnd == NULL) && (msg.message == WM_QUIT)) { + break; + } + TranslateMessage(&msg); + DispatchMessage(&msg); + } - DspCloseLibrary2(); - return 0; + DspCloseLibrary2(); + return 0; } #else { - if(!dspPluginEnabled) return; + if (!dspPluginEnabled) + return; - MSG msg; - while(PeekMessage(&msg,0,0,0,PM_REMOVE)) - { - TranslateMessage(&msg); - DispatchMessage(&msg); - } + MSG msg; + while (PeekMessage(&msg, 0, 0, 0, PM_REMOVE)) { + TranslateMessage(&msg); + DispatchMessage(&msg); + } } #endif \ No newline at end of file diff --git a/plugins/spu2-x/src/Windows/dsp.h b/plugins/spu2-x/src/Windows/dsp.h index 08e65d739c..feb1463895 100644 --- a/plugins/spu2-x/src/Windows/dsp.h +++ b/plugins/spu2-x/src/Windows/dsp.h @@ -27,32 +27,34 @@ #pragma once -typedef struct winampDSPModule { - char *description; // description - HWND hwndParent; // parent window (filled in by calling app) - HINSTANCE hDllInstance; // instance handle to this DLL (filled in by calling app) +typedef struct winampDSPModule +{ + char *description; // description + HWND hwndParent; // parent window (filled in by calling app) + HINSTANCE hDllInstance; // instance handle to this DLL (filled in by calling app) - void (*Config)(struct winampDSPModule *this_mod); // configuration dialog (if needed) - int (*Init)(struct winampDSPModule *this_mod); // 0 on success, creates window, etc (if needed) + void (*Config)(struct winampDSPModule *this_mod); // configuration dialog (if needed) + int (*Init)(struct winampDSPModule *this_mod); // 0 on success, creates window, etc (if needed) - // modify waveform samples: returns number of samples to actually write - // (typically numsamples, but no more than twice numsamples, and no less than half numsamples) - // numsamples should always be at least 128. should, but I'm not sure - int (*ModifySamples)(struct winampDSPModule *this_mod, short int *samples, int numsamples, int bps, int nch, int srate); + // modify waveform samples: returns number of samples to actually write + // (typically numsamples, but no more than twice numsamples, and no less than half numsamples) + // numsamples should always be at least 128. should, but I'm not sure + int (*ModifySamples)(struct winampDSPModule *this_mod, short int *samples, int numsamples, int bps, int nch, int srate); - void (*Quit)(struct winampDSPModule *this_mod); // called when unloading + void (*Quit)(struct winampDSPModule *this_mod); // called when unloading - void *userData; // user data, optional + void *userData; // user data, optional } winampDSPModule; -typedef struct { - int version; // DSP_HDRVER - char *description; // description of library - winampDSPModule* (*getModule)(int); // module retrieval function +typedef struct +{ + int version; // DSP_HDRVER + char *description; // description of library + winampDSPModule *(*getModule)(int); // module retrieval function } winampDSPHeader; // exported symbols -typedef winampDSPHeader* (*winampDSPGetHeaderType)(); +typedef winampDSPHeader *(*winampDSPGetHeaderType)(); // header version: 0x20 == 0.20 == winamp 2.0 #define DSP_HDRVER 0x20 diff --git a/plugins/spu2-x/src/defs.h b/plugins/spu2-x/src/defs.h index 96996b2840..1117515e5b 100644 --- a/plugins/spu2-x/src/defs.h +++ b/plugins/spu2-x/src/defs.h @@ -23,176 +23,176 @@ // SPU2 Memory Indexers // -------------------------------------------------------------------------------------- -#define spu2Rs16(mmem) (*(s16 *)((s8 *)spu2regs + ((mmem) & 0x1fff))) -#define spu2Ru16(mmem) (*(u16 *)((s8 *)spu2regs + ((mmem) & 0x1fff))) +#define spu2Rs16(mmem) (*(s16 *)((s8 *)spu2regs + ((mmem)&0x1fff))) +#define spu2Ru16(mmem) (*(u16 *)((s8 *)spu2regs + ((mmem)&0x1fff))) -extern s16* GetMemPtr(u32 addr); -extern s16 spu2M_Read( u32 addr ); -extern void spu2M_Write( u32 addr, s16 value ); -extern void spu2M_Write( u32 addr, u16 value ); +extern s16 *GetMemPtr(u32 addr); +extern s16 spu2M_Read(u32 addr); +extern void spu2M_Write(u32 addr, s16 value); +extern void spu2M_Write(u32 addr, u16 value); struct V_VolumeLR { - static V_VolumeLR Max; + static V_VolumeLR Max; - s32 Left; - s32 Right; + s32 Left; + s32 Right; - V_VolumeLR() {} - V_VolumeLR( s32 both ) : - Left( both ), - Right( both ) - { - } + V_VolumeLR() {} + V_VolumeLR(s32 both) + : Left(both) + , Right(both) + { + } - void DebugDump( FILE* dump, const char* title ); + void DebugDump(FILE *dump, const char *title); }; struct V_VolumeSlide { - // Holds the "original" value of the volume for this voice, prior to slides. - // (ie, the volume as written to the register) + // Holds the "original" value of the volume for this voice, prior to slides. + // (ie, the volume as written to the register) - s16 Reg_VOL; - s32 Value; - s8 Increment; - s8 Mode; + s16 Reg_VOL; + s32 Value; + s8 Increment; + s8 Mode; public: - V_VolumeSlide() {} - V_VolumeSlide( s16 regval, s32 fullvol ) : - Reg_VOL( regval ), - Value( fullvol ), - Increment( 0 ), - Mode( 0 ) - { - } + V_VolumeSlide() {} + V_VolumeSlide(s16 regval, s32 fullvol) + : Reg_VOL(regval) + , Value(fullvol) + , Increment(0) + , Mode(0) + { + } - void Update(); - void RegSet( u16 src ); // used to set the volume from a register source (16 bit signed) - void DebugDump( FILE* dump, const char* title, const char* nameLR ); + void Update(); + void RegSet(u16 src); // used to set the volume from a register source (16 bit signed) + void DebugDump(FILE *dump, const char *title, const char *nameLR); }; struct V_VolumeSlideLR { - static V_VolumeSlideLR Max; + static V_VolumeSlideLR Max; - V_VolumeSlide Left; - V_VolumeSlide Right; + V_VolumeSlide Left; + V_VolumeSlide Right; public: - V_VolumeSlideLR() {} + V_VolumeSlideLR() {} - V_VolumeSlideLR( s16 regval, s32 bothval ) : - Left( regval, bothval ), - Right( regval, bothval ) - { - } + V_VolumeSlideLR(s16 regval, s32 bothval) + : Left(regval, bothval) + , Right(regval, bothval) + { + } - void Update() - { - Left.Update(); - Right.Update(); - } + void Update() + { + Left.Update(); + Right.Update(); + } - void DebugDump( FILE* dump, const char* title ); + void DebugDump(FILE *dump, const char *title); }; struct V_ADSR { - union - { - u32 reg32; + union + { + u32 reg32; - struct - { - u16 regADSR1; - u16 regADSR2; - }; + struct + { + u16 regADSR1; + u16 regADSR2; + }; - struct - { - u32 SustainLevel:4, - DecayRate:4, - AttackRate:7, - AttackMode:1, // 0 for linear (+lin), 1 for pseudo exponential (+exp) + struct + { + u32 SustainLevel : 4, + DecayRate : 4, + AttackRate : 7, + AttackMode : 1, // 0 for linear (+lin), 1 for pseudo exponential (+exp) - ReleaseRate:5, - ReleaseMode:1, // 0 for linear (-lin), 1 for exponential (-exp) - SustainRate:7, - SustainMode:3; // 0 = +lin, 1 = -lin, 2 = +exp, 3 = -exp - }; - }; + ReleaseRate : 5, + ReleaseMode : 1, // 0 for linear (-lin), 1 for exponential (-exp) + SustainRate : 7, + SustainMode : 3; // 0 = +lin, 1 = -lin, 2 = +exp, 3 = -exp + }; + }; - s32 Value; // Ranges from 0 to 0x7fffffff (signed values are clamped to 0) [Reg_ENVX] - u8 Phase; // monitors current phase of ADSR envelope - bool Releasing; // Ready To Release, triggered by Voice.Stop(); + s32 Value; // Ranges from 0 to 0x7fffffff (signed values are clamped to 0) [Reg_ENVX] + u8 Phase; // monitors current phase of ADSR envelope + bool Releasing; // Ready To Release, triggered by Voice.Stop(); public: - bool Calculate(); + bool Calculate(); }; struct V_Voice { - u32 PlayCycle; // SPU2 cycle where the Playing started + u32 PlayCycle; // SPU2 cycle where the Playing started - V_VolumeSlideLR Volume; + V_VolumeSlideLR Volume; -// Envelope - V_ADSR ADSR; -// Pitch (also Reg_PITCH) - u16 Pitch; -// Loop Start address (also Reg_LSAH/L) - u32 LoopStartA; -// Sound Start address (also Reg_SSAH/L) - u32 StartA; -// Next Read Data address (also Reg_NAXH/L) - u32 NextA; -// Voice Decoding State - s32 Prev1; - s32 Prev2; + // Envelope + V_ADSR ADSR; + // Pitch (also Reg_PITCH) + u16 Pitch; + // Loop Start address (also Reg_LSAH/L) + u32 LoopStartA; + // Sound Start address (also Reg_SSAH/L) + u32 StartA; + // Next Read Data address (also Reg_NAXH/L) + u32 NextA; + // Voice Decoding State + s32 Prev1; + s32 Prev2; - // Pitch Modulated by previous voice - bool Modulated; - // Source (Wave/Noise) - bool Noise; + // Pitch Modulated by previous voice + bool Modulated; + // Source (Wave/Noise) + bool Noise; - s8 LoopMode; - s8 LoopFlags; + s8 LoopMode; + s8 LoopFlags; -// Sample pointer (19:12 bit fixed point) - s32 SP; + // Sample pointer (19:12 bit fixed point) + s32 SP; -// Sample pointer for Cubic Interpolation -// Cubic interpolation mixes a sample behind Linear, so that it -// can have sample data to either side of the end points from which -// to extrapolate. This SP represents that late sample position. - s32 SPc; + // Sample pointer for Cubic Interpolation + // Cubic interpolation mixes a sample behind Linear, so that it + // can have sample data to either side of the end points from which + // to extrapolate. This SP represents that late sample position. + s32 SPc; -// Previous sample values - used for interpolation -// Inverted order of these members to match the access order in the -// code (might improve cache hits). - s32 PV4; - s32 PV3; - s32 PV2; - s32 PV1; + // Previous sample values - used for interpolation + // Inverted order of these members to match the access order in the + // code (might improve cache hits). + s32 PV4; + s32 PV3; + s32 PV2; + s32 PV1; -// Last outputted audio value, used for voice modulation. - s32 OutX; - s32 NextCrest; // temp value for Crest calculation + // Last outputted audio value, used for voice modulation. + s32 OutX; + s32 NextCrest; // temp value for Crest calculation -// SBuffer now points directly to an ADPCM cache entry. - s16 *SBuffer; + // SBuffer now points directly to an ADPCM cache entry. + s16 *SBuffer; -// sample position within the current decoded packet. - s32 SCurrent; + // sample position within the current decoded packet. + s32 SCurrent; - // it takes a few ticks for voices to start on the real SPU2? - void QueueStart(); - bool Start(); - void Stop(); + // it takes a few ticks for voices to start on the real SPU2? + void QueueStart(); + bool Start(); + void Stop(); }; // ** Begin Debug-only variables section ** @@ -200,25 +200,25 @@ struct V_Voice // the Public Release build. struct V_VoiceDebug { - s8 FirstBlock; - s32 SampleData; - s32 PeakX; - s32 displayPeak; - s32 lastSetStartA; + s8 FirstBlock; + s32 SampleData; + s32 PeakX; + s32 displayPeak; + s32 lastSetStartA; }; struct V_CoreDebug { - V_VoiceDebug Voices[24]; -// Last Transfer Size - u32 lastsize; + V_VoiceDebug Voices[24]; + // Last Transfer Size + u32 lastsize; - // draw adma waveform in the visual debugger - s32 admaWaveformL[0x100]; - s32 admaWaveformR[0x100]; + // draw adma waveform in the visual debugger + s32 admaWaveformL[0x100]; + s32 admaWaveformR[0x100]; - // Enabled when a dma write starts, disabled when the visual debugger showed it once - s32 dmaFlag; + // Enabled when a dma write starts, disabled when the visual debugger showed it once + s32 dmaFlag; }; // Debug tracking information - 24 voices and 2 cores. @@ -226,338 +226,343 @@ extern V_CoreDebug DebugCores[2]; struct V_Reverb { - s16 IN_COEF_L; - s16 IN_COEF_R; + s16 IN_COEF_L; + s16 IN_COEF_R; - u32 FB_SRC_A; - u32 FB_SRC_B; + u32 FB_SRC_A; + u32 FB_SRC_B; - s16 FB_ALPHA; - s16 FB_X; + s16 FB_ALPHA; + s16 FB_X; - u32 IIR_SRC_A0; - u32 IIR_SRC_A1; - u32 IIR_SRC_B1; - u32 IIR_SRC_B0; - u32 IIR_DEST_A0; - u32 IIR_DEST_A1; - u32 IIR_DEST_B0; - u32 IIR_DEST_B1; + u32 IIR_SRC_A0; + u32 IIR_SRC_A1; + u32 IIR_SRC_B1; + u32 IIR_SRC_B0; + u32 IIR_DEST_A0; + u32 IIR_DEST_A1; + u32 IIR_DEST_B0; + u32 IIR_DEST_B1; - s16 IIR_ALPHA; - s16 IIR_COEF; + s16 IIR_ALPHA; + s16 IIR_COEF; - u32 ACC_SRC_A0; - u32 ACC_SRC_A1; - u32 ACC_SRC_B0; - u32 ACC_SRC_B1; - u32 ACC_SRC_C0; - u32 ACC_SRC_C1; - u32 ACC_SRC_D0; - u32 ACC_SRC_D1; + u32 ACC_SRC_A0; + u32 ACC_SRC_A1; + u32 ACC_SRC_B0; + u32 ACC_SRC_B1; + u32 ACC_SRC_C0; + u32 ACC_SRC_C1; + u32 ACC_SRC_D0; + u32 ACC_SRC_D1; - s16 ACC_COEF_A; - s16 ACC_COEF_B; - s16 ACC_COEF_C; - s16 ACC_COEF_D; + s16 ACC_COEF_A; + s16 ACC_COEF_B; + s16 ACC_COEF_C; + s16 ACC_COEF_D; - u32 MIX_DEST_A0; - u32 MIX_DEST_A1; - u32 MIX_DEST_B0; - u32 MIX_DEST_B1; + u32 MIX_DEST_A0; + u32 MIX_DEST_A1; + u32 MIX_DEST_B0; + u32 MIX_DEST_B1; }; struct V_ReverbBuffers { - s32 FB_SRC_A0; - s32 FB_SRC_B0; - s32 FB_SRC_A1; - s32 FB_SRC_B1; + s32 FB_SRC_A0; + s32 FB_SRC_B0; + s32 FB_SRC_A1; + s32 FB_SRC_B1; - s32 IIR_SRC_A0; - s32 IIR_SRC_A1; - s32 IIR_SRC_B0; - s32 IIR_SRC_B1; - s32 IIR_DEST_A0; - s32 IIR_DEST_A1; - s32 IIR_DEST_B0; - s32 IIR_DEST_B1; + s32 IIR_SRC_A0; + s32 IIR_SRC_A1; + s32 IIR_SRC_B0; + s32 IIR_SRC_B1; + s32 IIR_DEST_A0; + s32 IIR_DEST_A1; + s32 IIR_DEST_B0; + s32 IIR_DEST_B1; - s32 ACC_SRC_A0; - s32 ACC_SRC_A1; - s32 ACC_SRC_B0; - s32 ACC_SRC_B1; - s32 ACC_SRC_C0; - s32 ACC_SRC_C1; - s32 ACC_SRC_D0; - s32 ACC_SRC_D1; + s32 ACC_SRC_A0; + s32 ACC_SRC_A1; + s32 ACC_SRC_B0; + s32 ACC_SRC_B1; + s32 ACC_SRC_C0; + s32 ACC_SRC_C1; + s32 ACC_SRC_D0; + s32 ACC_SRC_D1; - s32 MIX_DEST_A0; - s32 MIX_DEST_A1; - s32 MIX_DEST_B0; - s32 MIX_DEST_B1; + s32 MIX_DEST_A0; + s32 MIX_DEST_A1; + s32 MIX_DEST_B0; + s32 MIX_DEST_B1; - bool NeedsUpdated; + bool NeedsUpdated; }; struct V_SPDIF { - u16 Out; - u16 Info; - u16 Unknown1; - u16 Mode; - u16 Media; - u16 Unknown2; - u16 Protection; + u16 Out; + u16 Info; + u16 Unknown1; + u16 Mode; + u16 Media; + u16 Unknown2; + u16 Protection; }; struct V_CoreRegs { - u32 PMON; - u32 NON; - u32 VMIXL; - u32 VMIXR; - u32 VMIXEL; - u32 VMIXER; - u32 ENDX; + u32 PMON; + u32 NON; + u32 VMIXL; + u32 VMIXR; + u32 VMIXEL; + u32 VMIXER; + u32 ENDX; - u16 MMIX; - u16 STATX; - u16 ATTR; - u16 _1AC; + u16 MMIX; + u16 STATX; + u16 ATTR; + u16 _1AC; }; struct V_VoiceGates { - s16 DryL; // 'AND Gate' for Direct Output to Left Channel - s16 DryR; // 'AND Gate' for Direct Output for Right Channel - s16 WetL; // 'AND Gate' for Effect Output for Left Channel - s16 WetR; // 'AND Gate' for Effect Output for Right Channel + s16 DryL; // 'AND Gate' for Direct Output to Left Channel + s16 DryR; // 'AND Gate' for Direct Output for Right Channel + s16 WetL; // 'AND Gate' for Effect Output for Left Channel + s16 WetR; // 'AND Gate' for Effect Output for Right Channel }; struct V_CoreGates { - union - { - u128 v128; - - struct - { - s16 InpL; // Sound Data Input to Direct Output (Left) - s16 InpR; // Sound Data Input to Direct Output (Right) - s16 SndL; // Voice Data to Direct Output (Left) - s16 SndR; // Voice Data to Direct Output (Right) - s16 ExtL; // External Input to Direct Output (Left) - s16 ExtR; // External Input to Direct Output (Right) - }; - }; + union + { + u128 v128; + struct + { + s16 InpL; // Sound Data Input to Direct Output (Left) + s16 InpR; // Sound Data Input to Direct Output (Right) + s16 SndL; // Voice Data to Direct Output (Left) + s16 SndR; // Voice Data to Direct Output (Right) + s16 ExtL; // External Input to Direct Output (Left) + s16 ExtR; // External Input to Direct Output (Right) + }; + }; }; struct VoiceMixSet { - static const VoiceMixSet Empty; - StereoOut32 Dry, Wet; + static const VoiceMixSet Empty; + StereoOut32 Dry, Wet; - VoiceMixSet() {} - VoiceMixSet( const StereoOut32& dry, const StereoOut32& wet ) : - Dry( dry ), - Wet( wet ) - { - } + VoiceMixSet() {} + VoiceMixSet(const StereoOut32 &dry, const StereoOut32 &wet) + : Dry(dry) + , Wet(wet) + { + } }; struct V_Core { - static const uint NumVoices = 24; + static const uint NumVoices = 24; - int Index; // Core index identifier. + int Index; // Core index identifier. - // Voice Gates -- These are SSE-related values, and must always be - // first to ensure 16 byte alignment + // Voice Gates -- These are SSE-related values, and must always be + // first to ensure 16 byte alignment - V_VoiceGates VoiceGates[NumVoices]; - V_CoreGates DryGate; - V_CoreGates WetGate; + V_VoiceGates VoiceGates[NumVoices]; + V_CoreGates DryGate; + V_CoreGates WetGate; - V_VolumeSlideLR MasterVol; // Master Volume - V_VolumeLR ExtVol; // Volume for External Data Input - V_VolumeLR InpVol; // Volume for Sound Data Input - V_VolumeLR FxVol; // Volume for Output from Effects + V_VolumeSlideLR MasterVol; // Master Volume + V_VolumeLR ExtVol; // Volume for External Data Input + V_VolumeLR InpVol; // Volume for Sound Data Input + V_VolumeLR FxVol; // Volume for Output from Effects - V_Voice Voices[NumVoices]; + V_Voice Voices[NumVoices]; - u32 IRQA; // Interrupt Address - u32 TSA; // DMA Transfer Start Address + u32 IRQA; // Interrupt Address + u32 TSA; // DMA Transfer Start Address - bool IRQEnable; // Interrupt Enable - bool FxEnable; // Effect Enable - bool Mute; // Mute - bool AdmaInProgress; + bool IRQEnable; // Interrupt Enable + bool FxEnable; // Effect Enable + bool Mute; // Mute + bool AdmaInProgress; - s8 DMABits; // DMA related? - s8 NoiseClk; // Noise Clock - u16 AutoDMACtrl; // AutoDMA Status - s32 DMAICounter; // DMA Interrupt Counter - u32 InputDataLeft; // Input Buffer - u32 InputPosRead; - u32 InputPosWrite; - u32 InputDataProgress; + s8 DMABits; // DMA related? + s8 NoiseClk; // Noise Clock + u16 AutoDMACtrl; // AutoDMA Status + s32 DMAICounter; // DMA Interrupt Counter + u32 InputDataLeft; // Input Buffer + u32 InputPosRead; + u32 InputPosWrite; + u32 InputDataProgress; - V_Reverb Revb; // Reverb Registers - V_ReverbBuffers RevBuffers; // buffer pointers for reverb, pre-calculated and pre-clipped. - u32 EffectsStartA; - u32 EffectsEndA; - u32 ExtEffectsStartA; - u32 ExtEffectsEndA; - u32 ReverbX; + V_Reverb Revb; // Reverb Registers + V_ReverbBuffers RevBuffers; // buffer pointers for reverb, pre-calculated and pre-clipped. + u32 EffectsStartA; + u32 EffectsEndA; + u32 ExtEffectsStartA; + u32 ExtEffectsEndA; + u32 ReverbX; - // Current size of and position of the effects buffer. Pre-caculated when the effects start - // or end position registers are written. CAN BE NEGATIVE OR ZERO, in which - // case reverb should be disabled. - s32 EffectsBufferSize; - u32 EffectsBufferStart; + // Current size of and position of the effects buffer. Pre-caculated when the effects start + // or end position registers are written. CAN BE NEGATIVE OR ZERO, in which + // case reverb should be disabled. + s32 EffectsBufferSize; + u32 EffectsBufferStart; - V_CoreRegs Regs; // Registers + V_CoreRegs Regs; // Registers - // Last samples to pass through the effects processor. - // Used because the effects processor works at 24khz and just pulls - // from this for the odd Ts. - StereoOut32 LastEffect; + // Last samples to pass through the effects processor. + // Used because the effects processor works at 24khz and just pulls + // from this for the odd Ts. + StereoOut32 LastEffect; - u8 CoreEnabled; + u8 CoreEnabled; - u8 AttrBit0; - u8 DmaMode; + u8 AttrBit0; + u8 DmaMode; - // new dma only - bool DmaStarted; - u32 AutoDmaFree; + // new dma only + bool DmaStarted; + u32 AutoDmaFree; - // old dma only - u16* DMAPtr; - u32 MADR; - u32 TADR; + // old dma only + u16 *DMAPtr; + u32 MADR; + u32 TADR; - u32 KeyOn; // not the KON register (though maybe it is) + u32 KeyOn; // not the KON register (though maybe it is) - // psxmode caches - u16 psxSoundDataTransferControl; - u16 psxSPUSTAT; + // psxmode caches + u16 psxSoundDataTransferControl; + u16 psxSPUSTAT; - StereoOut32 downbuf[8]; - StereoOut32 upbuf[8]; - int dbpos, ubpos; + StereoOut32 downbuf[8]; + StereoOut32 upbuf[8]; + int dbpos, ubpos; - // HACK -- This is a temp buffer which is (or isn't?) used to circumvent some memory - // corruption that originates elsewhere in the plugin. >_< The actual ADMA buffer - // is an area mapped to SPU2 main memory. - //s16 ADMATempBuffer[0x1000]; + // HACK -- This is a temp buffer which is (or isn't?) used to circumvent some memory + // corruption that originates elsewhere in the plugin. >_< The actual ADMA buffer + // is an area mapped to SPU2 main memory. + //s16 ADMATempBuffer[0x1000]; -// ---------------------------------------------------------------------------------- -// V_Core Methods -// ---------------------------------------------------------------------------------- + // ---------------------------------------------------------------------------------- + // V_Core Methods + // ---------------------------------------------------------------------------------- - // uninitialized constructor - V_Core() : Index( -1 ), DMAPtr( NULL ) {} - V_Core( int idx ); // our badass constructor - ~V_Core() throw(); + // uninitialized constructor + V_Core() + : Index(-1) + , DMAPtr(NULL) + { + } + V_Core(int idx); // our badass constructor + ~V_Core() throw(); - void Init( int index ); - void UpdateEffectsBufferSize(); - void AnalyzeReverbPreset(); + void Init(int index); + void UpdateEffectsBufferSize(); + void AnalyzeReverbPreset(); - s32 EffectsBufferIndexer( s32 offset ) const; - void UpdateFeedbackBuffersA(); - void UpdateFeedbackBuffersB(); + s32 EffectsBufferIndexer(s32 offset) const; + void UpdateFeedbackBuffersA(); + void UpdateFeedbackBuffersB(); - void WriteRegPS1( u32 mem, u16 value ); - u16 ReadRegPS1( u32 mem ); + void WriteRegPS1(u32 mem, u16 value); + u16 ReadRegPS1(u32 mem); -// -------------------------------------------------------------------------------------- -// Mixer Section -// -------------------------------------------------------------------------------------- + // -------------------------------------------------------------------------------------- + // Mixer Section + // -------------------------------------------------------------------------------------- - StereoOut32 Mix( const VoiceMixSet& inVoices, const StereoOut32& Input, const StereoOut32& Ext ); - void Reverb_AdvanceBuffer(); - StereoOut32 DoReverb( const StereoOut32& Input ); - s32 RevbGetIndexer( s32 offset ); + StereoOut32 Mix(const VoiceMixSet &inVoices, const StereoOut32 &Input, const StereoOut32 &Ext); + void Reverb_AdvanceBuffer(); + StereoOut32 DoReverb(const StereoOut32 &Input); + s32 RevbGetIndexer(s32 offset); - StereoOut32 ReadInput(); - StereoOut32 ReadInput_HiFi(); + StereoOut32 ReadInput(); + StereoOut32 ReadInput_HiFi(); -// -------------------------------------------------------------------------- -// DMA Section -// -------------------------------------------------------------------------- + // -------------------------------------------------------------------------- + // DMA Section + // -------------------------------------------------------------------------- - // Returns the index of the DMA channel (4 for Core 0, or 7 for Core 1) - int GetDmaIndex() const - { - return (Index == 0) ? 4 : 7; - } + // Returns the index of the DMA channel (4 for Core 0, or 7 for Core 1) + int GetDmaIndex() const + { + return (Index == 0) ? 4 : 7; + } - // returns either '4' or '7' - char GetDmaIndexChar() const - { - return 0x30 + GetDmaIndex(); - } + // returns either '4' or '7' + char GetDmaIndexChar() const + { + return 0x30 + GetDmaIndex(); + } - __forceinline u16 DmaRead() - { - const u16 ret = (u16)spu2M_Read(TSA); - ++TSA; TSA &= 0xfffff; - return ret; - } + __forceinline u16 DmaRead() + { + const u16 ret = (u16)spu2M_Read(TSA); + ++TSA; + TSA &= 0xfffff; + return ret; + } - __forceinline void DmaWrite(u16 value) - { - spu2M_Write( TSA, value ); - ++TSA; TSA &= 0xfffff; - } + __forceinline void DmaWrite(u16 value) + { + spu2M_Write(TSA, value); + ++TSA; + TSA &= 0xfffff; + } - void LogAutoDMA( FILE* fp ); + void LogAutoDMA(FILE *fp); - s32 NewDmaRead(u32* data, u32 bytesLeft, u32* bytesProcessed); - s32 NewDmaWrite(u32* data, u32 bytesLeft, u32* bytesProcessed); - void NewDmaInterrupt(); + s32 NewDmaRead(u32 *data, u32 bytesLeft, u32 *bytesProcessed); + s32 NewDmaWrite(u32 *data, u32 bytesLeft, u32 *bytesProcessed); + void NewDmaInterrupt(); - // old dma only - void DoDMAwrite(u16* pMem, u32 size); - void DoDMAread(u16* pMem, u32 size); + // old dma only + void DoDMAwrite(u16 *pMem, u32 size); + void DoDMAread(u16 *pMem, u32 size); - void AutoDMAReadBuffer(int mode); - void StartADMAWrite(u16 *pMem, u32 sz); - void PlainDMAWrite(u16 *pMem, u32 sz); + void AutoDMAReadBuffer(int mode); + void StartADMAWrite(u16 *pMem, u32 sz); + void PlainDMAWrite(u16 *pMem, u32 sz); }; -extern V_Core Cores[2]; -extern V_SPDIF Spdif; +extern V_Core Cores[2]; +extern V_SPDIF Spdif; // Output Buffer Writing Position (the same for all data); -extern s16 OutPos; +extern s16 OutPos; // Input Buffer Reading Position (the same for all data); -extern s16 InputPos; +extern s16 InputPos; // SPU Mixing Cycles ("Ticks mixed" counter) -extern u32 Cycles; +extern u32 Cycles; -extern s16* spu2regs; -extern s16* _spu2mem; -extern int PlayMode; +extern s16 *spu2regs; +extern s16 *_spu2mem; +extern int PlayMode; extern void SetIrqCall(int core); extern void StartVoices(int core, u32 value); extern void StopVoices(int core, u32 value); extern void InitADSR(); -extern void CalculateADSR( V_Voice& vc ); +extern void CalculateADSR(V_Voice &vc); extern void UpdateSpdifMode(); namespace Savestate { - struct DataBlock; +struct DataBlock; - extern s32 __fastcall FreezeIt( DataBlock& spud ); - extern s32 __fastcall ThawIt( DataBlock& spud ); - extern s32 __fastcall SizeIt(); +extern s32 __fastcall FreezeIt(DataBlock &spud); +extern s32 __fastcall ThawIt(DataBlock &spud); +extern s32 __fastcall SizeIt(); } // -------------------------------------------------------------------------------------- @@ -580,8 +585,8 @@ static const int pcm_DecodedSamplesPerBlock = 28; struct PcmCacheEntry { - bool Validated; - s16 Sampledata[pcm_DecodedSamplesPerBlock]; + bool Validated; + s16 Sampledata[pcm_DecodedSamplesPerBlock]; }; -extern PcmCacheEntry* pcm_cache_data; +extern PcmCacheEntry *pcm_cache_data; diff --git a/plugins/spu2-x/src/regs.h b/plugins/spu2-x/src/regs.h index 342fe255ac..62e7b55457 100644 --- a/plugins/spu2-x/src/regs.h +++ b/plugins/spu2-x/src/regs.h @@ -17,78 +17,78 @@ #pragma once -#define SPU2_CORE0 0x00000000 -#define SPU2_CORE1 0x00000400 +#define SPU2_CORE0 0x00000000 +#define SPU2_CORE1 0x00000400 -#define SPU2_VP(voice) ((voice) * 16) -#define SPU2_VA(voice) ((voice) * 12) +#define SPU2_VP(voice) ((voice)*16) +#define SPU2_VA(voice) ((voice)*12) -#define REG_VP_VOLL 0x0000 // Voice Volume Left -#define REG_VP_VOLR 0x0002 // Voice Volume Right -#define REG_VP_PITCH 0x0004 // Pitch -#define REG_VP_ADSR1 0x0006 // Envelope 1 (Attack-Decay-Sustain-Release) -#define REG_VP_ADSR2 0x0008 // Envelope 2 (Attack-Decay-Sustain-Release) -#define REG_VP_ENVX 0x000A // Current Envelope -#define REG_VP_VOLXL 0x000C // Current Voice Volume Left -#define REG_VP_VOLXR 0x000E // Current Voice Volume Right +#define REG_VP_VOLL 0x0000 // Voice Volume Left +#define REG_VP_VOLR 0x0002 // Voice Volume Right +#define REG_VP_PITCH 0x0004 // Pitch +#define REG_VP_ADSR1 0x0006 // Envelope 1 (Attack-Decay-Sustain-Release) +#define REG_VP_ADSR2 0x0008 // Envelope 2 (Attack-Decay-Sustain-Release) +#define REG_VP_ENVX 0x000A // Current Envelope +#define REG_VP_VOLXL 0x000C // Current Voice Volume Left +#define REG_VP_VOLXR 0x000E // Current Voice Volume Right // .. repeated for each voice .. -#define REG_S_PMON 0x0180 // Pitch Modulation Spec. -#define REG_S_NON 0x0184 // Alloc Noise Generator -#define REG_S_VMIXL 0x0188 // Voice Output Mix Left (Dry) -#define REG_S_VMIXEL 0x018C // Voice Output Mix Left (Wet) -#define REG_S_VMIXR 0x0190 // Voice Output Mix Right (Dry) -#define REG_S_VMIXER 0x0194 // Voice Output Mix Right (Wet) +#define REG_S_PMON 0x0180 // Pitch Modulation Spec. +#define REG_S_NON 0x0184 // Alloc Noise Generator +#define REG_S_VMIXL 0x0188 // Voice Output Mix Left (Dry) +#define REG_S_VMIXEL 0x018C // Voice Output Mix Left (Wet) +#define REG_S_VMIXR 0x0190 // Voice Output Mix Right (Dry) +#define REG_S_VMIXER 0x0194 // Voice Output Mix Right (Wet) -#define REG_P_MMIX 0x0198 // Output Spec. After Voice Mix -#define REG_C_ATTR 0x019A // Core X Attrib -#define REG_A_IRQA 0x019C // Interrupt Address Spec. +#define REG_P_MMIX 0x0198 // Output Spec. After Voice Mix +#define REG_C_ATTR 0x019A // Core X Attrib +#define REG_A_IRQA 0x019C // Interrupt Address Spec. -#define REG_S_KON 0x01A0 // Key On 0/1 -#define REG_S_KOFF 0x01A4 // Key Off 0/1 +#define REG_S_KON 0x01A0 // Key On 0/1 +#define REG_S_KOFF 0x01A4 // Key Off 0/1 -#define REG_A_TSA 0x01A8 // Transfer starting address -#define REG__1AC 0x01AC // Transfer data -#define REG__1AE 0x01AE -#define REG_S_ADMAS 0x01B0 // AutoDMA Status +#define REG_A_TSA 0x01A8 // Transfer starting address +#define REG__1AC 0x01AC // Transfer data +#define REG__1AE 0x01AE +#define REG_S_ADMAS 0x01B0 // AutoDMA Status // 1b2, 1b4, 1b6, 1b8, 1ba, 1bc, 1be are unknown -#define REG_VA_SSA 0x01C0 // Waveform data starting address -#define REG_VA_LSAX 0x01C4 // Loop point address -#define REG_VA_NAX 0x01C8 // Waveform data that should be read next +#define REG_VA_SSA 0x01C0 // Waveform data starting address +#define REG_VA_LSAX 0x01C4 // Loop point address +#define REG_VA_NAX 0x01C8 // Waveform data that should be read next // .. repeated for each voice .. -#define REG_A_ESA 0x02E0 //Address: Top address of working area for effects processing -#define R_FB_SRC_A 0x02E4 // Feedback Source A -#define R_FB_SRC_B 0x02E8 // Feedback Source B -#define R_IIR_DEST_A0 0x02EC -#define R_IIR_DEST_A1 0x02F0 -#define R_ACC_SRC_A0 0x02F4 -#define R_ACC_SRC_A1 0x02F8 -#define R_ACC_SRC_B0 0x02FC -#define R_ACC_SRC_B1 0x0300 -#define R_IIR_SRC_A0 0x0304 -#define R_IIR_SRC_A1 0x0308 -#define R_IIR_DEST_B0 0x030C -#define R_IIR_DEST_B1 0x0310 -#define R_ACC_SRC_C0 0x0314 -#define R_ACC_SRC_C1 0x0318 -#define R_ACC_SRC_D0 0x031C -#define R_ACC_SRC_D1 0x0320 -#define R_IIR_SRC_B0 0x0324 // Some sources have R_IIR_SRC_B0 and R_IIR_SRC_B1 swapped >< -#define R_IIR_SRC_B1 0x0328 // Assume a typo in the docs and B0 is actually at 324, B1 at 328 in the HW. -#define R_MIX_DEST_A0 0x032C -#define R_MIX_DEST_A1 0x0330 -#define R_MIX_DEST_B0 0x0334 -#define R_MIX_DEST_B1 0x0338 -#define REG_A_EEA 0x033C // Address: End address of working area for effects processing (upper part of address only!) +#define REG_A_ESA 0x02E0 //Address: Top address of working area for effects processing +#define R_FB_SRC_A 0x02E4 // Feedback Source A +#define R_FB_SRC_B 0x02E8 // Feedback Source B +#define R_IIR_DEST_A0 0x02EC +#define R_IIR_DEST_A1 0x02F0 +#define R_ACC_SRC_A0 0x02F4 +#define R_ACC_SRC_A1 0x02F8 +#define R_ACC_SRC_B0 0x02FC +#define R_ACC_SRC_B1 0x0300 +#define R_IIR_SRC_A0 0x0304 +#define R_IIR_SRC_A1 0x0308 +#define R_IIR_DEST_B0 0x030C +#define R_IIR_DEST_B1 0x0310 +#define R_ACC_SRC_C0 0x0314 +#define R_ACC_SRC_C1 0x0318 +#define R_ACC_SRC_D0 0x031C +#define R_ACC_SRC_D1 0x0320 +#define R_IIR_SRC_B0 0x0324 // Some sources have R_IIR_SRC_B0 and R_IIR_SRC_B1 swapped >< +#define R_IIR_SRC_B1 0x0328 // Assume a typo in the docs and B0 is actually at 324, B1 at 328 in the HW. +#define R_MIX_DEST_A0 0x032C +#define R_MIX_DEST_A1 0x0330 +#define R_MIX_DEST_B0 0x0334 +#define R_MIX_DEST_B1 0x0338 +#define REG_A_EEA 0x033C // Address: End address of working area for effects processing (upper part of address only!) -#define REG_S_ENDX 0x0340 // End Point passed flag +#define REG_S_ENDX 0x0340 // End Point passed flag -#define REG_P_STATX 0x0344 // Status register? +#define REG_P_STATX 0x0344 // Status register? // 0x346 .. 0x3fe are unknown (unused?) @@ -99,38 +99,38 @@ // "Different" register area -#define REG_P_MVOLL 0x0760 // Master Volume Left -#define REG_P_MVOLR 0x0762 // Master Volume Right -#define REG_P_EVOLL 0x0764 // Effect Volume Left -#define REG_P_EVOLR 0x0766 // Effect Volume Right -#define REG_P_AVOLL 0x0768 // Core External Input Volume Left (Only Core 1) -#define REG_P_AVOLR 0x076A // Core External Input Volume Right (Only Core 1) -#define REG_P_BVOLL 0x076C // Sound Data Volume Left -#define REG_P_BVOLR 0x076E // Sound Data Volume Right -#define REG_P_MVOLXL 0x0770 // Current Master Volume Left -#define REG_P_MVOLXR 0x0772 // Current Master Volume Right +#define REG_P_MVOLL 0x0760 // Master Volume Left +#define REG_P_MVOLR 0x0762 // Master Volume Right +#define REG_P_EVOLL 0x0764 // Effect Volume Left +#define REG_P_EVOLR 0x0766 // Effect Volume Right +#define REG_P_AVOLL 0x0768 // Core External Input Volume Left (Only Core 1) +#define REG_P_AVOLR 0x076A // Core External Input Volume Right (Only Core 1) +#define REG_P_BVOLL 0x076C // Sound Data Volume Left +#define REG_P_BVOLR 0x076E // Sound Data Volume Right +#define REG_P_MVOLXL 0x0770 // Current Master Volume Left +#define REG_P_MVOLXR 0x0772 // Current Master Volume Right -#define R_IIR_ALPHA 0x0774 //IIR alpha (% used) -#define R_ACC_COEF_A 0x0776 -#define R_ACC_COEF_B 0x0778 -#define R_ACC_COEF_C 0x077A -#define R_ACC_COEF_D 0x077C -#define R_IIR_COEF 0x077E -#define R_FB_ALPHA 0x0780 //feedback alpha (% used) -#define R_FB_X 0x0782 //feedback -#define R_IN_COEF_L 0x0784 -#define R_IN_COEF_R 0x0786 +#define R_IIR_ALPHA 0x0774 //IIR alpha (% used) +#define R_ACC_COEF_A 0x0776 +#define R_ACC_COEF_B 0x0778 +#define R_ACC_COEF_C 0x077A +#define R_ACC_COEF_D 0x077C +#define R_IIR_COEF 0x077E +#define R_FB_ALPHA 0x0780 //feedback alpha (% used) +#define R_FB_X 0x0782 //feedback +#define R_IN_COEF_L 0x0784 +#define R_IN_COEF_R 0x0786 // values repeat for core1 // End OF "Different" register area // SPDIF interface -#define SPDIF_OUT 0x07C0 // SPDIF Out: OFF/'PCM'/Bitstream/Bypass -#define SPDIF_IRQINFO 0x07C2 -#define SPDIF_MODE 0x07C6 -#define SPDIF_MEDIA 0x07C8 // SPDIF Media: 'CD'/DVD -#define SPDIF_PROTECT 0x07CC // SPDIF Copy Protection +#define SPDIF_OUT 0x07C0 // SPDIF Out: OFF/'PCM'/Bitstream/Bypass +#define SPDIF_IRQINFO 0x07C2 +#define SPDIF_MODE 0x07C6 +#define SPDIF_MEDIA 0x07C8 // SPDIF Media: 'CD'/DVD +#define SPDIF_PROTECT 0x07CC // SPDIF Copy Protection /********************************************************************* @@ -147,38 +147,38 @@ Core attributes (SD_C) *********************************************************************/ -#define SPDIF_OUT_OFF 0x0000 // no spdif output -#define SPDIF_OUT_PCM 0x0020 // encode spdif from spu2 pcm output -#define SPDIF_OUT_BYPASS 0x0100 // bypass spu2 processing +#define SPDIF_OUT_OFF 0x0000 // no spdif output +#define SPDIF_OUT_PCM 0x0020 // encode spdif from spu2 pcm output +#define SPDIF_OUT_BYPASS 0x0100 // bypass spu2 processing -#define SPDIF_MODE_BYPASS_BITSTREAM 0x0002 // bypass mode for digital bitstream data -#define SPDIF_MODE_BYPASS_PCM 0x0000 // bypass mode for pcm data (using analog output) +#define SPDIF_MODE_BYPASS_BITSTREAM 0x0002 // bypass mode for digital bitstream data +#define SPDIF_MODE_BYPASS_PCM 0x0000 // bypass mode for pcm data (using analog output) -#define SPDIF_MODE_MEDIA_CD 0x0800 // source media is a CD -#define SPDIF_MODE_MEDIA_DVD 0x0000 // source media is a DVD +#define SPDIF_MODE_MEDIA_CD 0x0800 // source media is a CD +#define SPDIF_MODE_MEDIA_DVD 0x0000 // source media is a DVD -#define SPDIF_MEDIA_CDVD 0x0200 -#define SPDIF_MEDIA_400 0x0000 +#define SPDIF_MEDIA_CDVD 0x0200 +#define SPDIF_MEDIA_400 0x0000 -#define SPDIF_PROTECT_NORMAL 0x0000 // spdif stream is not protected -#define SPDIF_PROTECT_PROHIBIT 0x8000 // spdif stream can't be copied +#define SPDIF_PROTECT_NORMAL 0x0000 // spdif stream is not protected +#define SPDIF_PROTECT_PROHIBIT 0x8000 // spdif stream can't be copied /********************************************************************/ -#define VOICE_PARAM_VOLL 0x0 // Voice Volume Left -#define VOICE_PARAM_VOLR 0x2 // Voice Volume Right -#define VOICE_PARAM_PITCH 0x4 // Pitch -#define VOICE_PARAM_ADSR1 0x6 // Envelope 1 (Attack-Delay-Sustain-Release) -#define VOICE_PARAM_ADSR2 0x8 // Envelope 2 (Attack-Delay-Sustain-Release) -#define VOICE_PARAM_ENVX 0xA // Current Envelope -#define VOICE_PARAM_VOLXL 0xC // Current Voice Volume Left -#define VOICE_PARAM_VOLXR 0xE // Current Voice Volume Right +#define VOICE_PARAM_VOLL 0x0 // Voice Volume Left +#define VOICE_PARAM_VOLR 0x2 // Voice Volume Right +#define VOICE_PARAM_PITCH 0x4 // Pitch +#define VOICE_PARAM_ADSR1 0x6 // Envelope 1 (Attack-Delay-Sustain-Release) +#define VOICE_PARAM_ADSR2 0x8 // Envelope 2 (Attack-Delay-Sustain-Release) +#define VOICE_PARAM_ENVX 0xA // Current Envelope +#define VOICE_PARAM_VOLXL 0xC // Current Voice Volume Left +#define VOICE_PARAM_VOLXR 0xE // Current Voice Volume Right /********************************************************************/ -#define VOICE_ADDR_SSA 0x0 // Waveform data starting address -#define VOICE_ADDR_LSAX 0x4 // Loop point address -#define VOICE_ADDR_NAX 0x8 // Waveform data that should be read next +#define VOICE_ADDR_SSA 0x0 // Waveform data starting address +#define VOICE_ADDR_LSAX 0x4 // Loop point address +#define VOICE_ADDR_NAX 0x8 // Waveform data that should be read next @@ -186,11 +186,10 @@ Core attributes (SD_C) // SPU2-X Register Table LUT // -------------------------------------------------------------------------------------- -#define U16P(x) ( (u16*)&(x) ) +#define U16P(x) ((u16 *)&(x)) // Returns the hiword of a 32 bit integer. -#define U16P_HI(x) ( ((u16*)&(x))+1 ) - -extern u16* regtable[0x401]; -extern u16 const* const regtable_original[0x401]; +#define U16P_HI(x) (((u16 *)&(x)) + 1) +extern u16 *regtable[0x401]; +extern u16 const *const regtable_original[0x401]; diff --git a/plugins/spu2-x/src/spdif.h b/plugins/spu2-x/src/spdif.h index fd51c94865..032cf5f9e3 100644 --- a/plugins/spu2-x/src/spdif.h +++ b/plugins/spu2-x/src/spdif.h @@ -70,13 +70,13 @@ Preamble W: Marks a word containing data for channel B. typedef struct _subframe { - u32 preamble:4; - u32 aux_data:4; - u32 snd_data:20; - u32 validity:1; - u32 subcode:1; - u32 chstatus:1; - u32 parity:1; + u32 preamble : 4; + u32 aux_data : 4; + u32 snd_data : 20; + u32 validity : 1; + u32 subcode : 1; + u32 chstatus : 1; + u32 parity : 1; } subframe; /* @@ -103,9 +103,8 @@ typedef struct _subframe typedef struct _chstatus { - u8 ctrlbits:4; - u8 reservd1:4; - u8 category; - u8 reservd2[22]; + u8 ctrlbits : 4; + u8 reservd1 : 4; + u8 category; + u8 reservd2[22]; } chstatus: - diff --git a/plugins/spu2-x/src/spu2freeze.cpp b/plugins/spu2-x/src/spu2freeze.cpp index 3c3b68cdce..67372b39fb 100644 --- a/plugins/spu2-x/src/spu2freeze.cpp +++ b/plugins/spu2-x/src/spu2freeze.cpp @@ -16,134 +16,132 @@ */ #include "Global.h" -#include "PS2E-spu2.h" // hopefully temporary, until I resolve lClocks depdendency +#include "PS2E-spu2.h" // hopefully temporary, until I resolve lClocks depdendency namespace Savestate { - // Arbitrary ID to identify SPU2-X saves. - static const u32 SAVE_ID = 0x1227521; +// Arbitrary ID to identify SPU2-X saves. +static const u32 SAVE_ID = 0x1227521; - // versioning for saves. - // Increment this when changes to the savestate system are made. - static const u32 SAVE_VERSION = 0x000d; +// versioning for saves. +// Increment this when changes to the savestate system are made. +static const u32 SAVE_VERSION = 0x000d; - static void wipe_the_cache() - { - memset( pcm_cache_data, 0, pcm_BlockCount * sizeof(PcmCacheEntry) ); - } +static void wipe_the_cache() +{ + memset(pcm_cache_data, 0, pcm_BlockCount * sizeof(PcmCacheEntry)); +} } struct Savestate::DataBlock { - u32 spu2id; // SPU2-X state identifier lets ZeroGS/PeopsSPU2 know this isn't their state) - u8 unkregs[0x10000]; // SPU2 raw register memory - u8 mem[0x200000]; // SPU2 raw sample memory + u32 spu2id; // SPU2-X state identifier lets ZeroGS/PeopsSPU2 know this isn't their state) + u8 unkregs[0x10000]; // SPU2 raw register memory + u8 mem[0x200000]; // SPU2 raw sample memory - u32 version; // SPU2-X version identifier - V_Core Cores[2]; - V_SPDIF Spdif; - s16 OutPos; - s16 InputPos; - u32 Cycles; - u32 lClocks; - int PlayMode; + u32 version; // SPU2-X version identifier + V_Core Cores[2]; + V_SPDIF Spdif; + s16 OutPos; + s16 InputPos; + u32 Cycles; + u32 lClocks; + int PlayMode; }; -s32 __fastcall Savestate::FreezeIt( DataBlock& spud ) +s32 __fastcall Savestate::FreezeIt(DataBlock &spud) { - spud.spu2id = SAVE_ID; - spud.version = SAVE_VERSION; + spud.spu2id = SAVE_ID; + spud.version = SAVE_VERSION; - pxAssertMsg( spu2regs && _spu2mem, "Looks like PCSX2 is trying to savestate while pluigns are shut down. That's a no-no! It shouldn't crash, but the savestate will probably be corrupted." ); + pxAssertMsg(spu2regs && _spu2mem, "Looks like PCSX2 is trying to savestate while pluigns are shut down. That's a no-no! It shouldn't crash, but the savestate will probably be corrupted."); - if( spu2regs != NULL ) memcpy(spud.unkregs, spu2regs, sizeof(spud.unkregs)); - if( _spu2mem != NULL ) memcpy(spud.mem, _spu2mem, sizeof(spud.mem)); + if (spu2regs != NULL) + memcpy(spud.unkregs, spu2regs, sizeof(spud.unkregs)); + if (_spu2mem != NULL) + memcpy(spud.mem, _spu2mem, sizeof(spud.mem)); - memcpy(spud.Cores, Cores, sizeof(Cores)); - memcpy(&spud.Spdif, &Spdif, sizeof(Spdif)); + memcpy(spud.Cores, Cores, sizeof(Cores)); + memcpy(&spud.Spdif, &Spdif, sizeof(Spdif)); - spud.OutPos = OutPos; - spud.InputPos = InputPos; - spud.Cycles = Cycles; - spud.lClocks = lClocks; - spud.PlayMode = PlayMode; + spud.OutPos = OutPos; + spud.InputPos = InputPos; + spud.Cycles = Cycles; + spud.lClocks = lClocks; + spud.PlayMode = PlayMode; - // note: Don't save the cache. PCSX2 doesn't offer a safe method of predicting - // the required size of the savestate prior to saving, plus this is just too - // "implementation specific" for the intended spec of a savestate. Let's just - // force the user to rebuild their cache instead. + // note: Don't save the cache. PCSX2 doesn't offer a safe method of predicting + // the required size of the savestate prior to saving, plus this is just too + // "implementation specific" for the intended spec of a savestate. Let's just + // force the user to rebuild their cache instead. - return 0; + return 0; } -s32 __fastcall Savestate::ThawIt( DataBlock& spud ) +s32 __fastcall Savestate::ThawIt(DataBlock &spud) { - if( spud.spu2id != SAVE_ID || spud.version < SAVE_VERSION ) - { - fprintf(stderr, "\n*** SPU2-X Warning:\n"); - if( spud.spu2id == SAVE_ID ) - fprintf(stderr, "\tSavestate version is from an older version of this plugin.\n"); - else - fprintf(stderr, "\tThe savestate you are trying to load was not made with this plugin.\n"); + if (spud.spu2id != SAVE_ID || spud.version < SAVE_VERSION) { + fprintf(stderr, "\n*** SPU2-X Warning:\n"); + if (spud.spu2id == SAVE_ID) + fprintf(stderr, "\tSavestate version is from an older version of this plugin.\n"); + else + fprintf(stderr, "\tThe savestate you are trying to load was not made with this plugin.\n"); - fprintf(stderr, - "\tAudio may not recover correctly. Save your game to memorycard, reset,\n\n" - "\tand then continue from there.\n\n" - ); + fprintf(stderr, + "\tAudio may not recover correctly. Save your game to memorycard, reset,\n\n" + "\tand then continue from there.\n\n"); - // Do *not* reset the cores. - // We'll need some "hints" as to how the cores should be initialized, and the - // only way to get that is to use the game's existing core settings and hope - // they kinda match the settings for the savestate (IRQ enables and such). + // Do *not* reset the cores. + // We'll need some "hints" as to how the cores should be initialized, and the + // only way to get that is to use the game's existing core settings and hope + // they kinda match the settings for the savestate (IRQ enables and such). - // adpcm cache : Clear all the cache flags and buffers. + // adpcm cache : Clear all the cache flags and buffers. - wipe_the_cache(); - } - else - { - SndBuffer::ClearContents(); + wipe_the_cache(); + } else { + SndBuffer::ClearContents(); - pxAssertMsg( spu2regs && _spu2mem, "Looks like PCSX2 is trying to loadstate while pluigns are shut down. That's a no-no! It shouldn't crash, but the savestate will probably be corrupted." ); + pxAssertMsg(spu2regs && _spu2mem, "Looks like PCSX2 is trying to loadstate while pluigns are shut down. That's a no-no! It shouldn't crash, but the savestate will probably be corrupted."); - // base stuff - if( spu2regs ) memcpy(spu2regs, spud.unkregs, sizeof(spud.unkregs)); - if( _spu2mem ) memcpy(_spu2mem, spud.mem, sizeof(spud.mem)); + // base stuff + if (spu2regs) + memcpy(spu2regs, spud.unkregs, sizeof(spud.unkregs)); + if (_spu2mem) + memcpy(_spu2mem, spud.mem, sizeof(spud.mem)); - memcpy(Cores, spud.Cores, sizeof(Cores)); - memcpy(&Spdif, &spud.Spdif, sizeof(Spdif)); + memcpy(Cores, spud.Cores, sizeof(Cores)); + memcpy(&Spdif, &spud.Spdif, sizeof(Spdif)); - OutPos = spud.OutPos; - InputPos = spud.InputPos; - Cycles = spud.Cycles; - lClocks = spud.lClocks; - PlayMode = spud.PlayMode; + OutPos = spud.OutPos; + InputPos = spud.InputPos; + Cycles = spud.Cycles; + lClocks = spud.lClocks; + PlayMode = spud.PlayMode; - wipe_the_cache(); + wipe_the_cache(); - // Go through the V_Voice structs and recalculate SBuffer pointer from - // the NextA setting. + // Go through the V_Voice structs and recalculate SBuffer pointer from + // the NextA setting. - for( int c=0; c<2; c++ ) - { - for( int v=0; v<24; v++ ) - { - const int cacheIdx = Cores[c].Voices[v].NextA / pcm_WordsPerBlock; - Cores[c].Voices[v].SBuffer = pcm_cache_data[cacheIdx].Sampledata; - } - } + for (int c = 0; c < 2; c++) { + for (int v = 0; v < 24; v++) { + const int cacheIdx = Cores[c].Voices[v].NextA / pcm_WordsPerBlock; + Cores[c].Voices[v].SBuffer = pcm_cache_data[cacheIdx].Sampledata; + } + } - // HACKFIX!! DMAPtr can be invalid after a savestate load, so force it to NULL and - // ignore it on any pending ADMA writes. (the DMAPtr concept used to work in old VM - // editions of PCSX2 with fixed addressing, but new PCSX2s have dynamic memory - // addressing). + // HACKFIX!! DMAPtr can be invalid after a savestate load, so force it to NULL and + // ignore it on any pending ADMA writes. (the DMAPtr concept used to work in old VM + // editions of PCSX2 with fixed addressing, but new PCSX2s have dynamic memory + // addressing). - Cores[0].DMAPtr = Cores[1].DMAPtr = NULL; - } - return 0; + Cores[0].DMAPtr = Cores[1].DMAPtr = NULL; + } + return 0; } s32 __fastcall Savestate::SizeIt() { - return sizeof(DataBlock); + return sizeof(DataBlock); } diff --git a/plugins/spu2-x/src/spu2sys.cpp b/plugins/spu2-x/src/spu2sys.cpp index 895ed4372b..e24ecdd460 100644 --- a/plugins/spu2-x/src/spu2sys.cpp +++ b/plugins/spu2-x/src/spu2sys.cpp @@ -25,336 +25,330 @@ #include "Global.h" #include "Dma.h" -#include "PS2E-spu2.h" // needed until I figure out a nice solution for irqcallback dependencies. +#include "PS2E-spu2.h" // needed until I figure out a nice solution for irqcallback dependencies. -s16* spu2regs = NULL; -s16* _spu2mem = NULL; +s16 *spu2regs = NULL; +s16 *_spu2mem = NULL; -V_CoreDebug DebugCores[2]; -V_Core Cores[2]; -V_SPDIF Spdif; +V_CoreDebug DebugCores[2]; +V_Core Cores[2]; +V_SPDIF Spdif; -s16 OutPos; -s16 InputPos; -u32 Cycles; +s16 OutPos; +s16 InputPos; +u32 Cycles; -int PlayMode; +int PlayMode; -bool has_to_call_irq=false; +bool has_to_call_irq = false; bool psxmode = false; void SetIrqCall(int core) { - // reset by an irq disable/enable cycle, behaviour found by - // test programs that bizarrely only fired one interrupt - if (Spdif.Info & 4 << core) - return; - Spdif.Info |= 4 << core; - has_to_call_irq=true; + // reset by an irq disable/enable cycle, behaviour found by + // test programs that bizarrely only fired one interrupt + if (Spdif.Info & 4 << core) + return; + Spdif.Info |= 4 << core; + has_to_call_irq = true; } -__forceinline s16* GetMemPtr(u32 addr) +__forceinline s16 *GetMemPtr(u32 addr) { #ifndef DEBUG_FAST - // In case you're wondering, this assert is the reason SPU2-X - // runs so incrediously slow in Debug mode. :P - pxAssume( addr < 0x100000 ); + // In case you're wondering, this assert is the reason SPU2-X + // runs so incrediously slow in Debug mode. :P + pxAssume(addr < 0x100000); #endif - return (_spu2mem+addr); + return (_spu2mem + addr); } -__forceinline s16 spu2M_Read( u32 addr ) +__forceinline s16 spu2M_Read(u32 addr) { - return *GetMemPtr( addr & 0xfffff ); + return *GetMemPtr(addr & 0xfffff); } // writes a signed value to the SPU2 ram // Invalidates the ADPCM cache in the process. -__forceinline void spu2M_Write( u32 addr, s16 value ) +__forceinline void spu2M_Write(u32 addr, s16 value) { - // Make sure the cache is invalidated: - // (note to self : addr address WORDs, not bytes) + // Make sure the cache is invalidated: + // (note to self : addr address WORDs, not bytes) - addr &= 0xfffff; - if( addr >= SPU2_DYN_MEMLINE ) - { - const int cacheIdx = addr / pcm_WordsPerBlock; - pcm_cache_data[cacheIdx].Validated = false; + addr &= 0xfffff; + if (addr >= SPU2_DYN_MEMLINE) { + const int cacheIdx = addr / pcm_WordsPerBlock; + pcm_cache_data[cacheIdx].Validated = false; - if(MsgToConsole() && MsgCache()) ConLog( "* SPU2-X: PcmCache Block Clear at 0x%x (cacheIdx=0x%x)\n", addr, cacheIdx); - } - *GetMemPtr( addr ) = value; + if (MsgToConsole() && MsgCache()) + ConLog("* SPU2-X: PcmCache Block Clear at 0x%x (cacheIdx=0x%x)\n", addr, cacheIdx); + } + *GetMemPtr(addr) = value; } // writes an unsigned value to the SPU2 ram -__forceinline void spu2M_Write( u32 addr, u16 value ) +__forceinline void spu2M_Write(u32 addr, u16 value) { - spu2M_Write( addr, (s16)value ); + spu2M_Write(addr, (s16)value); } -V_VolumeLR V_VolumeLR::Max( 0x7FFFFFFF ); -V_VolumeSlideLR V_VolumeSlideLR::Max( 0x3FFF, 0x7FFFFFFF ); +V_VolumeLR V_VolumeLR::Max(0x7FFFFFFF); +V_VolumeSlideLR V_VolumeSlideLR::Max(0x3FFF, 0x7FFFFFFF); -V_Core::V_Core( int coreidx ) : Index( coreidx ) - //LogFile_AutoDMA( NULL ) +V_Core::V_Core(int coreidx) + : Index(coreidx) +//LogFile_AutoDMA( NULL ) { - /*char fname[128]; + /*char fname[128]; sprintf( fname, "logs/adma%d.raw", GetDmaIndex() ); LogFile_AutoDMA = fopen( fname, "wb" );*/ } V_Core::~V_Core() throw() { - // Can't use this yet because we dumb V_Core into savestates >_< - /*if( LogFile_AutoDMA != NULL ) + // Can't use this yet because we dumb V_Core into savestates >_< + /*if( LogFile_AutoDMA != NULL ) { fclose( LogFile_AutoDMA ); LogFile_AutoDMA = NULL; }*/ } -void V_Core::Init( int index ) +void V_Core::Init(int index) { - ConLog( "* SPU2-X: Init SPU2 core %d \n", index ); - memset( this, 0, sizeof(V_Core) ); - psxmode = false; + ConLog("* SPU2-X: Init SPU2 core %d \n", index); + memset(this, 0, sizeof(V_Core)); + psxmode = false; - const int c = Index = index; + const int c = Index = index; - Regs.STATX = 0; - Regs.ATTR = 0; - ExtVol = V_VolumeLR::Max; - InpVol = V_VolumeLR::Max; - FxVol = V_VolumeLR(0); + Regs.STATX = 0; + Regs.ATTR = 0; + ExtVol = V_VolumeLR::Max; + InpVol = V_VolumeLR::Max; + FxVol = V_VolumeLR(0); - MasterVol = V_VolumeSlideLR(0,0); + MasterVol = V_VolumeSlideLR(0, 0); - memset( &DryGate, -1, sizeof(DryGate) ); - memset( &WetGate, -1, sizeof(WetGate) ); - DryGate.ExtL = 0; - DryGate.ExtR = 0; - if (!c) - { - WetGate.ExtL = 0; - WetGate.ExtR = 0; - } + memset(&DryGate, -1, sizeof(DryGate)); + memset(&WetGate, -1, sizeof(WetGate)); + DryGate.ExtL = 0; + DryGate.ExtR = 0; + if (!c) { + WetGate.ExtL = 0; + WetGate.ExtR = 0; + } - Regs.MMIX = c ? 0xFFC : 0xFF0; // PS2 confirmed (f3c and f30 after BIOS ran, ffc and ff0 after sdinit) - Regs.VMIXL = 0xFFFFFF; - Regs.VMIXR = 0xFFFFFF; - Regs.VMIXEL = 0xFFFFFF; - Regs.VMIXER = 0xFFFFFF; - EffectsStartA = c ? 0xFFFF8 : 0xEFFF8; - EffectsEndA = c ? 0xFFFFF : 0xEFFFF; - ExtEffectsStartA = EffectsStartA; - ExtEffectsEndA = EffectsEndA; + Regs.MMIX = c ? 0xFFC : 0xFF0; // PS2 confirmed (f3c and f30 after BIOS ran, ffc and ff0 after sdinit) + Regs.VMIXL = 0xFFFFFF; + Regs.VMIXR = 0xFFFFFF; + Regs.VMIXEL = 0xFFFFFF; + Regs.VMIXER = 0xFFFFFF; + EffectsStartA = c ? 0xFFFF8 : 0xEFFF8; + EffectsEndA = c ? 0xFFFFF : 0xEFFFF; + ExtEffectsStartA = EffectsStartA; + ExtEffectsEndA = EffectsEndA; - FxEnable = 0; // Uninitialized it's 0 for both cores. Resetting libs however may set this to 0 or 1. - // These are real PS2 values, mainly constant apart from a few bits: 0x3220EAA4, 0x40505E9C. - // These values mean nothing. They do not reflect the actual address the SPU2 is testing, - // it would seem that reading the IRQA register returns the last written value, not the - // value of the internal register. Rewriting the registers with their current values changes - // whether interrupts fire (they do while uninitialised, but do not when rewritten). - // The exact boot value is unknown and probably unknowable, but it seems to be somewhere - // in the input or output areas, so we're using 0x800. - // F1 2005 is known to rely on an uninitialised IRQA being an address which will be hit. - IRQA = 0x800; - IRQEnable = 0; // PS2 confirmed + FxEnable = 0; // Uninitialized it's 0 for both cores. Resetting libs however may set this to 0 or 1. + // These are real PS2 values, mainly constant apart from a few bits: 0x3220EAA4, 0x40505E9C. + // These values mean nothing. They do not reflect the actual address the SPU2 is testing, + // it would seem that reading the IRQA register returns the last written value, not the + // value of the internal register. Rewriting the registers with their current values changes + // whether interrupts fire (they do while uninitialised, but do not when rewritten). + // The exact boot value is unknown and probably unknowable, but it seems to be somewhere + // in the input or output areas, so we're using 0x800. + // F1 2005 is known to rely on an uninitialised IRQA being an address which will be hit. + IRQA = 0x800; + IRQEnable = 0; // PS2 confirmed - for( uint v=0; v EffectsEndA ) - { - pos = EffectsStartA + (offset % EffectsBufferSize); - } - else if( pos < EffectsStartA ) - { - pos = EffectsEndA+1 - (offset % EffectsBufferSize ); - } - return pos; + // Need to use modulus here, because games can and will drop the buffer size + // without notice, and it leads to offsets several times past the end of the buffer. + + if (pos > EffectsEndA) { + pos = EffectsStartA + (offset % EffectsBufferSize); + } else if (pos < EffectsStartA) { + pos = EffectsEndA + 1 - (offset % EffectsBufferSize); + } + return pos; } void V_Core::UpdateFeedbackBuffersA() { - RevBuffers.FB_SRC_A0 = EffectsBufferIndexer( Revb.MIX_DEST_A0 - Revb.FB_SRC_A ); - RevBuffers.FB_SRC_A1 = EffectsBufferIndexer( Revb.MIX_DEST_A1 - Revb.FB_SRC_A ); + RevBuffers.FB_SRC_A0 = EffectsBufferIndexer(Revb.MIX_DEST_A0 - Revb.FB_SRC_A); + RevBuffers.FB_SRC_A1 = EffectsBufferIndexer(Revb.MIX_DEST_A1 - Revb.FB_SRC_A); } void V_Core::UpdateFeedbackBuffersB() { - RevBuffers.FB_SRC_B0 = EffectsBufferIndexer( Revb.MIX_DEST_B0 - Revb.FB_SRC_B ); - RevBuffers.FB_SRC_B1 = EffectsBufferIndexer( Revb.MIX_DEST_B1 - Revb.FB_SRC_B ); + RevBuffers.FB_SRC_B0 = EffectsBufferIndexer(Revb.MIX_DEST_B0 - Revb.FB_SRC_B); + RevBuffers.FB_SRC_B1 = EffectsBufferIndexer(Revb.MIX_DEST_B1 - Revb.FB_SRC_B); } void V_Core::UpdateEffectsBufferSize() { - const s32 newbufsize = EffectsEndA - EffectsStartA + 1; + const s32 newbufsize = EffectsEndA - EffectsStartA + 1; - if( (newbufsize*2) > 0x20000 ) // max 128kb per core - { - //printf("too big, returning\n"); - //return; - } + if ((newbufsize * 2) > 0x20000) // max 128kb per core + { + //printf("too big, returning\n"); + //return; + } - // bad optimization? - //if (newbufsize == EffectsBufferSize && EffectsStartA == EffectsBufferStart) return; + // bad optimization? + //if (newbufsize == EffectsBufferSize && EffectsStartA == EffectsBufferStart) return; - //printf("Rvb Area change: ESA = %x, EEA = %x, Size(dec) = %d, Size(hex) = %x FxEnable = %d\n", EffectsStartA, EffectsEndA, newbufsize * 2, newbufsize * 2, FxEnable); + //printf("Rvb Area change: ESA = %x, EEA = %x, Size(dec) = %d, Size(hex) = %x FxEnable = %d\n", EffectsStartA, EffectsEndA, newbufsize * 2, newbufsize * 2, FxEnable); - RevBuffers.NeedsUpdated = false; - EffectsBufferSize = newbufsize; - EffectsBufferStart = EffectsStartA; + RevBuffers.NeedsUpdated = false; + EffectsBufferSize = newbufsize; + EffectsBufferStart = EffectsStartA; - if( EffectsBufferSize <= 0 ) return; + if (EffectsBufferSize <= 0) + return; - // debug: shows reverb parameters in console - if(MsgToConsole()) AnalyzeReverbPreset(); + // debug: shows reverb parameters in console + if (MsgToConsole()) + AnalyzeReverbPreset(); - // Rebuild buffer indexers. - RevBuffers.ACC_SRC_A0 = EffectsBufferIndexer( Revb.ACC_SRC_A0 ); - RevBuffers.ACC_SRC_A1 = EffectsBufferIndexer( Revb.ACC_SRC_A1 ); - RevBuffers.ACC_SRC_B0 = EffectsBufferIndexer( Revb.ACC_SRC_B0 ); - RevBuffers.ACC_SRC_B1 = EffectsBufferIndexer( Revb.ACC_SRC_B1 ); - RevBuffers.ACC_SRC_C0 = EffectsBufferIndexer( Revb.ACC_SRC_C0 ); - RevBuffers.ACC_SRC_C1 = EffectsBufferIndexer( Revb.ACC_SRC_C1 ); - RevBuffers.ACC_SRC_D0 = EffectsBufferIndexer( Revb.ACC_SRC_D0 ); - RevBuffers.ACC_SRC_D1 = EffectsBufferIndexer( Revb.ACC_SRC_D1 ); + // Rebuild buffer indexers. + RevBuffers.ACC_SRC_A0 = EffectsBufferIndexer(Revb.ACC_SRC_A0); + RevBuffers.ACC_SRC_A1 = EffectsBufferIndexer(Revb.ACC_SRC_A1); + RevBuffers.ACC_SRC_B0 = EffectsBufferIndexer(Revb.ACC_SRC_B0); + RevBuffers.ACC_SRC_B1 = EffectsBufferIndexer(Revb.ACC_SRC_B1); + RevBuffers.ACC_SRC_C0 = EffectsBufferIndexer(Revb.ACC_SRC_C0); + RevBuffers.ACC_SRC_C1 = EffectsBufferIndexer(Revb.ACC_SRC_C1); + RevBuffers.ACC_SRC_D0 = EffectsBufferIndexer(Revb.ACC_SRC_D0); + RevBuffers.ACC_SRC_D1 = EffectsBufferIndexer(Revb.ACC_SRC_D1); - UpdateFeedbackBuffersA(); - UpdateFeedbackBuffersB(); + UpdateFeedbackBuffersA(); + UpdateFeedbackBuffersB(); - RevBuffers.IIR_DEST_A0 = EffectsBufferIndexer( Revb.IIR_DEST_A0 ); - RevBuffers.IIR_DEST_A1 = EffectsBufferIndexer( Revb.IIR_DEST_A1 ); - RevBuffers.IIR_DEST_B0 = EffectsBufferIndexer( Revb.IIR_DEST_B0 ); - RevBuffers.IIR_DEST_B1 = EffectsBufferIndexer( Revb.IIR_DEST_B1 ); + RevBuffers.IIR_DEST_A0 = EffectsBufferIndexer(Revb.IIR_DEST_A0); + RevBuffers.IIR_DEST_A1 = EffectsBufferIndexer(Revb.IIR_DEST_A1); + RevBuffers.IIR_DEST_B0 = EffectsBufferIndexer(Revb.IIR_DEST_B0); + RevBuffers.IIR_DEST_B1 = EffectsBufferIndexer(Revb.IIR_DEST_B1); - RevBuffers.IIR_SRC_A0 = EffectsBufferIndexer( Revb.IIR_SRC_A0 ); - RevBuffers.IIR_SRC_A1 = EffectsBufferIndexer( Revb.IIR_SRC_A1 ); - RevBuffers.IIR_SRC_B0 = EffectsBufferIndexer( Revb.IIR_SRC_B0 ); - RevBuffers.IIR_SRC_B1 = EffectsBufferIndexer( Revb.IIR_SRC_B1 ); + RevBuffers.IIR_SRC_A0 = EffectsBufferIndexer(Revb.IIR_SRC_A0); + RevBuffers.IIR_SRC_A1 = EffectsBufferIndexer(Revb.IIR_SRC_A1); + RevBuffers.IIR_SRC_B0 = EffectsBufferIndexer(Revb.IIR_SRC_B0); + RevBuffers.IIR_SRC_B1 = EffectsBufferIndexer(Revb.IIR_SRC_B1); - RevBuffers.MIX_DEST_A0 = EffectsBufferIndexer( Revb.MIX_DEST_A0 ); - RevBuffers.MIX_DEST_A1 = EffectsBufferIndexer( Revb.MIX_DEST_A1 ); - RevBuffers.MIX_DEST_B0 = EffectsBufferIndexer( Revb.MIX_DEST_B0 ); - RevBuffers.MIX_DEST_B1 = EffectsBufferIndexer( Revb.MIX_DEST_B1 ); + RevBuffers.MIX_DEST_A0 = EffectsBufferIndexer(Revb.MIX_DEST_A0); + RevBuffers.MIX_DEST_A1 = EffectsBufferIndexer(Revb.MIX_DEST_A1); + RevBuffers.MIX_DEST_B0 = EffectsBufferIndexer(Revb.MIX_DEST_B0); + RevBuffers.MIX_DEST_B1 = EffectsBufferIndexer(Revb.MIX_DEST_B1); } void V_Voice::QueueStart() { - if (Cycles - PlayCycle < delayCycles) - { - // Required by The Legend of Spyro: The Eternal Night (probably the other two legend games too) - ConLog(" *** KeyOn after less than %d T disregarded.\n", delayCycles); - return; - } - PlayCycle = Cycles; + if (Cycles - PlayCycle < delayCycles) { + // Required by The Legend of Spyro: The Eternal Night (probably the other two legend games too) + ConLog(" *** KeyOn after less than %d T disregarded.\n", delayCycles); + return; + } + PlayCycle = Cycles; } bool V_Voice::Start() { - if((Cycles-PlayCycle)>= delayCycles) - { - if(StartA&7) - { - fprintf( stderr, " *** Misaligned StartA %05x!\n",StartA); - StartA=(StartA+0xFFFF8)+0x8; - } + if ((Cycles - PlayCycle) >= delayCycles) { + if (StartA & 7) { + fprintf(stderr, " *** Misaligned StartA %05x!\n", StartA); + StartA = (StartA + 0xFFFF8) + 0x8; + } - ADSR.Releasing = false; - ADSR.Value = 1; - ADSR.Phase = 1; - SCurrent = 28; - LoopMode = 0; - LoopFlags = 0; - NextA = StartA | 1; - Prev1 = 0; - Prev2 = 0; + ADSR.Releasing = false; + ADSR.Value = 1; + ADSR.Phase = 1; + SCurrent = 28; + LoopMode = 0; + LoopFlags = 0; + NextA = StartA | 1; + Prev1 = 0; + Prev2 = 0; - PV1 = PV2 = 0; - PV3 = PV4 = 0; - NextCrest = -0x8000; - return true; - } - else - return false; + PV1 = PV2 = 0; + PV3 = PV4 = 0; + NextCrest = -0x8000; + return true; + } else + return false; } void V_Voice::Stop() { - ADSR.Value = 0; - ADSR.Phase = 0; + ADSR.Value = 0; + ADSR.Phase = 0; } uint TickInterval = 768; @@ -363,1093 +357,1156 @@ extern void UpdateDebugDialog(); __forceinline void TimeUpdate(u32 cClocks) { - u32 dClocks = cClocks - lClocks; + u32 dClocks = cClocks - lClocks; - // Sanity Checks: - // It's not totally uncommon for the IOP's clock to jump backwards a cycle or two, and in - // such cases we just want to ignore the TimeUpdate call. + // Sanity Checks: + // It's not totally uncommon for the IOP's clock to jump backwards a cycle or two, and in + // such cases we just want to ignore the TimeUpdate call. - if( dClocks > (u32)-15 ) return; + if (dClocks > (u32)-15) + return; - // But if for some reason our clock value seems way off base (typically due to bad dma - // timings from PCSX2), just mix out a little bit, skip the rest, and hope the ship - // "rights" itself later on. + // But if for some reason our clock value seems way off base (typically due to bad dma + // timings from PCSX2), just mix out a little bit, skip the rest, and hope the ship + // "rights" itself later on. - if( dClocks > (u32)(TickInterval*SanityInterval) ) - { - if(MsgToConsole()) ConLog( " * SPU2 > TimeUpdate Sanity Check (Tick Delta: %d) (PS2 Ticks: %d)\n", dClocks/TickInterval, cClocks/TickInterval ); - dClocks = TickInterval * SanityInterval; - lClocks = cClocks - dClocks; - } + if (dClocks > (u32)(TickInterval * SanityInterval)) { + if (MsgToConsole()) + ConLog(" * SPU2 > TimeUpdate Sanity Check (Tick Delta: %d) (PS2 Ticks: %d)\n", dClocks / TickInterval, cClocks / TickInterval); + dClocks = TickInterval * SanityInterval; + lClocks = cClocks - dClocks; + } - // Visual debug display showing all core's activity! Disabled via #define on release builds. +// Visual debug display showing all core's activity! Disabled via #define on release builds. #ifdef _WIN32 - UpdateDebugDialog(); + UpdateDebugDialog(); #endif - if( SynchMode == 1 ) // AsyncMix on - SndBuffer::UpdateTempoChangeAsyncMixing(); - else TickInterval = 768; // Reset to default, in case the user hotswitched from async to something else. + if (SynchMode == 1) // AsyncMix on + SndBuffer::UpdateTempoChangeAsyncMixing(); + else + TickInterval = 768; // Reset to default, in case the user hotswitched from async to something else. - //Update Mixing Progress - while(dClocks>=TickInterval) - { - if(has_to_call_irq) - { - //ConLog("* SPU2-X: Irq Called (%04x) at cycle %d.\n", Spdif.Info, Cycles); - has_to_call_irq=false; - if(_irqcallback) _irqcallback(); - } + //Update Mixing Progress + while (dClocks >= TickInterval) { + if (has_to_call_irq) { + //ConLog("* SPU2-X: Irq Called (%04x) at cycle %d.\n", Spdif.Info, Cycles); + has_to_call_irq = false; + if (_irqcallback) + _irqcallback(); + } #ifndef ENABLE_NEW_IOPDMA_SPU2 - //Update DMA4 interrupt delay counter - if(Cores[0].DMAICounter>0) - { - Cores[0].DMAICounter-=TickInterval; - if(Cores[0].DMAICounter<=0) - { - //ConLog("counter set and callback!\n"); - Cores[0].MADR=Cores[0].TADR; - Cores[0].DMAICounter=0; - if(dma4callback) dma4callback(); - } - else { - Cores[0].MADR+=TickInterval<<1; - } - } + //Update DMA4 interrupt delay counter + if (Cores[0].DMAICounter > 0) { + Cores[0].DMAICounter -= TickInterval; + if (Cores[0].DMAICounter <= 0) { + //ConLog("counter set and callback!\n"); + Cores[0].MADR = Cores[0].TADR; + Cores[0].DMAICounter = 0; + if (dma4callback) + dma4callback(); + } else { + Cores[0].MADR += TickInterval << 1; + } + } - //Update DMA7 interrupt delay counter - if(Cores[1].DMAICounter>0) - { - Cores[1].DMAICounter-=TickInterval; - if(Cores[1].DMAICounter<=0) - { - Cores[1].MADR=Cores[1].TADR; - Cores[1].DMAICounter=0; - //ConLog( "* SPU2 > DMA 7 Callback! %d\n", Cycles ); - if(dma7callback) dma7callback(); - } - else { - Cores[1].MADR+=TickInterval<<1; - } - } + //Update DMA7 interrupt delay counter + if (Cores[1].DMAICounter > 0) { + Cores[1].DMAICounter -= TickInterval; + if (Cores[1].DMAICounter <= 0) { + Cores[1].MADR = Cores[1].TADR; + Cores[1].DMAICounter = 0; + //ConLog( "* SPU2 > DMA 7 Callback! %d\n", Cycles ); + if (dma7callback) + dma7callback(); + } else { + Cores[1].MADR += TickInterval << 1; + } + } #endif - dClocks -= TickInterval; - lClocks += TickInterval; - Cycles++; + dClocks -= TickInterval; + lClocks += TickInterval; + Cycles++; - for (int i = 0; i < 2; i++) - if (Cores[i].KeyOn) - for (int j = 0; j < 24; j++) - if (Cores[i].KeyOn >> j & 1) - if (Cores[i].Voices[j].Start()) - Cores[i].KeyOn &= ~(1 << j); + for (int i = 0; i < 2; i++) + if (Cores[i].KeyOn) + for (int j = 0; j < 24; j++) + if (Cores[i].KeyOn >> j & 1) + if (Cores[i].Voices[j].Start()) + Cores[i].KeyOn &= ~(1 << j); - // Note: IOP does not use MMX regs, so no need to save them. - //SaveMMXRegs(); - Mix(); - //RestoreMMXRegs(); - } + // Note: IOP does not use MMX regs, so no need to save them. + //SaveMMXRegs(); + Mix(); + //RestoreMMXRegs(); + } } __forceinline void UpdateSpdifMode() { - int OPM=PlayMode; + int OPM = PlayMode; - if(Spdif.Out&0x4) // use 24/32bit PCM data streaming - { - PlayMode=8; - ConLog("* SPU2-X: WARNING: Possibly CDDA mode set!\n"); - return; - } + if (Spdif.Out & 0x4) // use 24/32bit PCM data streaming + { + PlayMode = 8; + ConLog("* SPU2-X: WARNING: Possibly CDDA mode set!\n"); + return; + } - if(Spdif.Out&SPDIF_OUT_BYPASS) - { - PlayMode=2; - if(!(Spdif.Mode&SPDIF_MODE_BYPASS_BITSTREAM)) - PlayMode=4; //bitstream bypass - } - else - { - PlayMode=0; //normal processing - if(Spdif.Out&SPDIF_OUT_PCM) - { - PlayMode=1; - } - } - if(OPM!=PlayMode) - { - ConLog("* SPU2-X: Play Mode Set to %s (%d).\n", - (PlayMode==0) ? "Normal" : ((PlayMode==1) ? "PCM Clone" : ((PlayMode==2) ? "PCM Bypass" : "BitStream Bypass")),PlayMode); - } + if (Spdif.Out & SPDIF_OUT_BYPASS) { + PlayMode = 2; + if (!(Spdif.Mode & SPDIF_MODE_BYPASS_BITSTREAM)) + PlayMode = 4; //bitstream bypass + } else { + PlayMode = 0; //normal processing + if (Spdif.Out & SPDIF_OUT_PCM) { + PlayMode = 1; + } + } + if (OPM != PlayMode) { + ConLog("* SPU2-X: Play Mode Set to %s (%d).\n", + (PlayMode == 0) ? "Normal" : ((PlayMode == 1) ? "PCM Clone" : ((PlayMode == 2) ? "PCM Bypass" : "BitStream Bypass")), PlayMode); + } } // Converts an SPU2 register volume write into a 32 bit SPU2-X volume. The value is extended // properly into the lower 16 bits of the value to provide a full spectrum of volumes. -static s32 GetVol32( u16 src ) +static s32 GetVol32(u16 src) { - return (((s32)src) << 16 ) | ((src<<1) & 0xffff); + return (((s32)src) << 16) | ((src << 1) & 0xffff); } -void V_VolumeSlide::RegSet( u16 src ) +void V_VolumeSlide::RegSet(u16 src) { - Value = GetVol32( src ); + Value = GetVol32(src); } static u32 map_spu1to2(u32 addr) { - return addr * 4 + (addr >= 0x200 ? 0xc0000 : 0); + return addr * 4 + (addr >= 0x200 ? 0xc0000 : 0); } static u32 map_spu2to1(u32 addr) { - // if (addr >= 0x800 && addr < 0xc0000) oh dear - return (addr - (addr >= 0xc0000 ? 0xc0000 : 0)) / 4; + // if (addr >= 0x800 && addr < 0xc0000) oh dear + return (addr - (addr >= 0xc0000 ? 0xc0000 : 0)) / 4; } -void V_Core::WriteRegPS1( u32 mem, u16 value ) +void V_Core::WriteRegPS1(u32 mem, u16 value) { - pxAssume( Index == 0 ); // Valid on Core 0 only! + pxAssume(Index == 0); // Valid on Core 0 only! - bool show = true; - u32 reg = mem & 0xffff; + bool show = true; + u32 reg = mem & 0xffff; - if((reg>=0x1c00)&&(reg<0x1d80)) - { - //voice values - u8 voice = ((reg-0x1c00)>>4); - u8 vval = reg&0xf; - switch(vval) - { - case 0x0: //VOLL (Volume L) - case 0x2: //VOLR (Volume R) - { - V_VolumeSlide& thisvol = vval == 0 ? Voices[voice].Volume.Left : Voices[voice].Volume.Right; - thisvol.Reg_VOL = value; + if ((reg >= 0x1c00) && (reg < 0x1d80)) { + //voice values + u8 voice = ((reg - 0x1c00) >> 4); + u8 vval = reg & 0xf; + switch (vval) { + case 0x0: //VOLL (Volume L) + case 0x2: //VOLR (Volume R) + { + V_VolumeSlide &thisvol = vval == 0 ? Voices[voice].Volume.Left : Voices[voice].Volume.Right; + thisvol.Reg_VOL = value; - if (value & 0x8000) // +Lin/-Lin/+Exp/-Exp - { - thisvol.Mode = (value & 0xF000) >> 12; - thisvol.Increment = (value & 0x7F); - // We're not sure slides work 100% - if (IsDevBuild) ConLog("* SPU2: Voice uses Slides in Mode = %x, Increment = %x\n", thisvol.Mode, thisvol.Increment); - } - else - { - // Constant Volume mode (no slides or envelopes) - // Volumes range from 0x3fff to 0x7fff, with 0x4000 serving as - // the "sign" bit, so a simple bitwise extension will do the trick: + if (value & 0x8000) // +Lin/-Lin/+Exp/-Exp + { + thisvol.Mode = (value & 0xF000) >> 12; + thisvol.Increment = (value & 0x7F); + // We're not sure slides work 100% + if (IsDevBuild) + ConLog("* SPU2: Voice uses Slides in Mode = %x, Increment = %x\n", thisvol.Mode, thisvol.Increment); + } else { + // Constant Volume mode (no slides or envelopes) + // Volumes range from 0x3fff to 0x7fff, with 0x4000 serving as + // the "sign" bit, so a simple bitwise extension will do the trick: - thisvol.RegSet(value << 1); - thisvol.Mode = 0; - thisvol.Increment = 0; - } - //ConLog("voice %x VOL%c write: %x\n", voice, vval == 0 ? 'L' : 'R', value); - break; - } - case 0x4: - if (value > 0x3fff) ConLog("* SPU2: Pitch setting too big: 0x%x\n", value); - Voices[voice].Pitch = value & 0x3fff; - //ConLog("voice %x Pitch write: %x\n", voice, Voices[voice].Pitch); - break; - case 0x6: - Voices[voice].StartA = map_spu1to2(value); - //ConLog("voice %x StartA write: %x\n", voice, Voices[voice].StartA); - break; + thisvol.RegSet(value << 1); + thisvol.Mode = 0; + thisvol.Increment = 0; + } + //ConLog("voice %x VOL%c write: %x\n", voice, vval == 0 ? 'L' : 'R', value); + break; + } + case 0x4: + if (value > 0x3fff) + ConLog("* SPU2: Pitch setting too big: 0x%x\n", value); + Voices[voice].Pitch = value & 0x3fff; + //ConLog("voice %x Pitch write: %x\n", voice, Voices[voice].Pitch); + break; + case 0x6: + Voices[voice].StartA = map_spu1to2(value); + //ConLog("voice %x StartA write: %x\n", voice, Voices[voice].StartA); + break; - case 0x8: // ADSR1 (Envelope) - Voices[voice].ADSR.regADSR1 = value; - //ConLog("voice %x regADSR1 write: %x\n", voice, Voices[voice].ADSR.regADSR1); - break; + case 0x8: // ADSR1 (Envelope) + Voices[voice].ADSR.regADSR1 = value; + //ConLog("voice %x regADSR1 write: %x\n", voice, Voices[voice].ADSR.regADSR1); + break; - case 0xa: // ADSR2 (Envelope) - Voices[voice].ADSR.regADSR2 = value; - //ConLog("voice %x regADSR2 write: %x\n", voice, Voices[voice].ADSR.regADSR2); - break; - case 0xc: // Voice 0..23 ADSR Current Volume - // not commonly set by games - Voices[voice].ADSR.Value = value * 0x10001U; - ConLog("voice %x ADSR.Value write: %x\n", voice, Voices[voice].ADSR.Value); - break; - case 0xe: - Voices[voice].LoopStartA = map_spu1to2(value); - //ConLog("voice %x LoopStartA write: %x\n", voice, Voices[voice].LoopStartA); - break; + case 0xa: // ADSR2 (Envelope) + Voices[voice].ADSR.regADSR2 = value; + //ConLog("voice %x regADSR2 write: %x\n", voice, Voices[voice].ADSR.regADSR2); + break; + case 0xc: // Voice 0..23 ADSR Current Volume + // not commonly set by games + Voices[voice].ADSR.Value = value * 0x10001U; + ConLog("voice %x ADSR.Value write: %x\n", voice, Voices[voice].ADSR.Value); + break; + case 0xe: + Voices[voice].LoopStartA = map_spu1to2(value); + //ConLog("voice %x LoopStartA write: %x\n", voice, Voices[voice].LoopStartA); + break; - jNO_DEFAULT; - } - } + jNO_DEFAULT; + } + } - else switch(reg) - { - case 0x1d80:// Mainvolume left - MasterVol.Left.Mode = 0; - MasterVol.Left.RegSet( value ); - break; + else + switch (reg) { + case 0x1d80: // Mainvolume left + MasterVol.Left.Mode = 0; + MasterVol.Left.RegSet(value); + break; - case 0x1d82:// Mainvolume right - MasterVol.Right.Mode = 0; - MasterVol.Right.RegSet( value ); - break; + case 0x1d82: // Mainvolume right + MasterVol.Right.Mode = 0; + MasterVol.Right.RegSet(value); + break; - case 0x1d84:// Reverberation depth left - FxVol.Left = GetVol32( value ); - break; + case 0x1d84: // Reverberation depth left + FxVol.Left = GetVol32(value); + break; - case 0x1d86:// Reverberation depth right - FxVol.Right = GetVol32( value ); - break; + case 0x1d86: // Reverberation depth right + FxVol.Right = GetVol32(value); + break; - case 0x1d88:// Voice ON (0-15) - SPU2_FastWrite(REG_S_KON,value); - break; - case 0x1d8a:// Voice ON (16-23) - SPU2_FastWrite(REG_S_KON+2,value); - break; + case 0x1d88: // Voice ON (0-15) + SPU2_FastWrite(REG_S_KON, value); + break; + case 0x1d8a: // Voice ON (16-23) + SPU2_FastWrite(REG_S_KON + 2, value); + break; - case 0x1d8c:// Voice OFF (0-15) - SPU2_FastWrite(REG_S_KOFF,value); - break; - case 0x1d8e:// Voice OFF (16-23) - SPU2_FastWrite(REG_S_KOFF+2,value); - break; + case 0x1d8c: // Voice OFF (0-15) + SPU2_FastWrite(REG_S_KOFF, value); + break; + case 0x1d8e: // Voice OFF (16-23) + SPU2_FastWrite(REG_S_KOFF + 2, value); + break; - case 0x1d90:// Channel FM (pitch lfo) mode (0-15) - SPU2_FastWrite(REG_S_PMON,value); - if (value!=0)ConLog("spu2x warning: wants to set Pitch Modulation reg1 to %x \n", value); - break; + case 0x1d90: // Channel FM (pitch lfo) mode (0-15) + SPU2_FastWrite(REG_S_PMON, value); + if (value != 0) + ConLog("spu2x warning: wants to set Pitch Modulation reg1 to %x \n", value); + break; - case 0x1d92:// Channel FM (pitch lfo) mode (16-23) - SPU2_FastWrite(REG_S_PMON+2,value); - if (value != 0)ConLog("spu2x warning: wants to set Pitch Modulation reg2 to %x \n", value); - break; + case 0x1d92: // Channel FM (pitch lfo) mode (16-23) + SPU2_FastWrite(REG_S_PMON + 2, value); + if (value != 0) + ConLog("spu2x warning: wants to set Pitch Modulation reg2 to %x \n", value); + break; - case 0x1d94:// Channel Noise mode (0-15) - SPU2_FastWrite(REG_S_NON,value); - if (value != 0) ConLog("spu2x warning: wants to set Channel Noise mode reg1 to %x\n", value); - break; + case 0x1d94: // Channel Noise mode (0-15) + SPU2_FastWrite(REG_S_NON, value); + if (value != 0) + ConLog("spu2x warning: wants to set Channel Noise mode reg1 to %x\n", value); + break; - case 0x1d96:// Channel Noise mode (16-23) - SPU2_FastWrite(REG_S_NON+2,value); - if (value != 0) ConLog("spu2x warning: wants to set Channel Noise mode reg2 to %x\n", value); - break; + case 0x1d96: // Channel Noise mode (16-23) + SPU2_FastWrite(REG_S_NON + 2, value); + if (value != 0) + ConLog("spu2x warning: wants to set Channel Noise mode reg2 to %x\n", value); + break; - case 0x1d98:// 1F801D98h - Voice 0..23 Reverb mode aka Echo On (EON) (R/W) - //Regs.VMIXEL = value & 0xFFFF; - SPU2_FastWrite(REG_S_VMIXEL,value); - SPU2_FastWrite(REG_S_VMIXER,value); - //ConLog("spu2x warning: setting reverb mode reg1 to %x \n", Regs.VMIXEL); - break; + case 0x1d98: // 1F801D98h - Voice 0..23 Reverb mode aka Echo On (EON) (R/W) + //Regs.VMIXEL = value & 0xFFFF; + SPU2_FastWrite(REG_S_VMIXEL, value); + SPU2_FastWrite(REG_S_VMIXER, value); + //ConLog("spu2x warning: setting reverb mode reg1 to %x \n", Regs.VMIXEL); + break; - case 0x1d9a:// 1F801D98h + 2 - Voice 0..23 Reverb mode aka Echo On (EON) (R/W) - //Regs.VMIXEL = value << 16; - SPU2_FastWrite(REG_S_VMIXEL+2,value); - SPU2_FastWrite(REG_S_VMIXER+2,value); - //ConLog("spu2x warning: setting reverb mode reg2 to %x \n", Regs.VMIXEL); - break; + case 0x1d9a: // 1F801D98h + 2 - Voice 0..23 Reverb mode aka Echo On (EON) (R/W) + //Regs.VMIXEL = value << 16; + SPU2_FastWrite(REG_S_VMIXEL + 2, value); + SPU2_FastWrite(REG_S_VMIXER + 2, value); + //ConLog("spu2x warning: setting reverb mode reg2 to %x \n", Regs.VMIXEL); + break; - // this was wrong? // edit: appears so! - //case 0x1d9c:// Channel Reverb mode (0-15) - // SPU2_FastWrite(REG_S_VMIXL,value); - // SPU2_FastWrite(REG_S_VMIXR,value); - //break; + // this was wrong? // edit: appears so! + //case 0x1d9c:// Channel Reverb mode (0-15) + // SPU2_FastWrite(REG_S_VMIXL,value); + // SPU2_FastWrite(REG_S_VMIXR,value); + //break; - //case 0x1d9e:// Channel Reverb mode (16-23) - // SPU2_FastWrite(REG_S_VMIXL+2,value); - // SPU2_FastWrite(REG_S_VMIXR+2,value); - //break; - case 0x1d9c: // Voice 0..15 ON/OFF (status) (ENDX) (R) // writeable but hw overrides it shortly after - //Regs.ENDX &= 0xff0000; - ConLog("spu2x warning: wants to set ENDX reg1 to %x \n", value); - break; + //case 0x1d9e:// Channel Reverb mode (16-23) + // SPU2_FastWrite(REG_S_VMIXL+2,value); + // SPU2_FastWrite(REG_S_VMIXR+2,value); + //break; + case 0x1d9c: // Voice 0..15 ON/OFF (status) (ENDX) (R) // writeable but hw overrides it shortly after + //Regs.ENDX &= 0xff0000; + ConLog("spu2x warning: wants to set ENDX reg1 to %x \n", value); + break; - case 0x1d9e:// // Voice 15..23 ON/OFF (status) (ENDX) (R) // writeable but hw overrides it shortly after - //Regs.ENDX &= 0xffff; - ConLog("spu2x warning: wants to set ENDX reg2 to %x \n", value); - break; + case 0x1d9e: // // Voice 15..23 ON/OFF (status) (ENDX) (R) // writeable but hw overrides it shortly after + //Regs.ENDX &= 0xffff; + ConLog("spu2x warning: wants to set ENDX reg2 to %x \n", value); + break; - case 0x1da2:// Reverb work area start - { - EffectsStartA = map_spu1to2(value); - //EffectsEndA = 0xFFFFF; // fixed EndA in psx mode - Cores[0].RevBuffers.NeedsUpdated = true; - ReverbX = 0; - } - break; + case 0x1da2: // Reverb work area start + { + EffectsStartA = map_spu1to2(value); + //EffectsEndA = 0xFFFFF; // fixed EndA in psx mode + Cores[0].RevBuffers.NeedsUpdated = true; + ReverbX = 0; + } break; - case 0x1da4: - IRQA = map_spu1to2(value); - //ConLog("SPU2-X Setting IRQA to %x \n", IRQA); - break; + case 0x1da4: + IRQA = map_spu1to2(value); + //ConLog("SPU2-X Setting IRQA to %x \n", IRQA); + break; - case 0x1da6: - TSA = map_spu1to2(value); - //ConLog("SPU2-X Setting TSA to %x \n", TSA); - break; + case 0x1da6: + TSA = map_spu1to2(value); + //ConLog("SPU2-X Setting TSA to %x \n", TSA); + break; - case 0x1da8: // Spu Write to Memory - //ConLog("SPU direct DMA Write. Current TSA = %x\n", TSA); - if (Cores[0].IRQEnable && (Cores[0].IRQA <= Cores[0].TSA)) - { - SetIrqCall(0); - _irqcallback(); - } - DmaWrite(value); - show = false; - break; + case 0x1da8: // Spu Write to Memory + //ConLog("SPU direct DMA Write. Current TSA = %x\n", TSA); + if (Cores[0].IRQEnable && (Cores[0].IRQA <= Cores[0].TSA)) { + SetIrqCall(0); + _irqcallback(); + } + DmaWrite(value); + show = false; + break; - case 0x1daa: - SPU2_FastWrite(REG_C_ATTR, value); - break; + case 0x1daa: + SPU2_FastWrite(REG_C_ATTR, value); + break; - case 0x1dac: // 1F801DACh - Sound RAM Data Transfer Control (should be 0004h) - ConLog("SPU Sound RAM Data Transfer Control (should be 4) : value = %x \n", value); - psxSoundDataTransferControl = value; - break; + case 0x1dac: // 1F801DACh - Sound RAM Data Transfer Control (should be 0004h) + ConLog("SPU Sound RAM Data Transfer Control (should be 4) : value = %x \n", value); + psxSoundDataTransferControl = value; + break; - case 0x1dae: // 1F801DAEh - SPU Status Register (SPUSTAT) (R) - // The SPUSTAT register should be treated read-only (writing is possible in so far that the written - // value can be read-back for a short moment, however, thereafter the hardware is overwriting that value). - //Regs.STATX = value; - break; + case 0x1dae: // 1F801DAEh - SPU Status Register (SPUSTAT) (R) + // The SPUSTAT register should be treated read-only (writing is possible in so far that the written + // value can be read-back for a short moment, however, thereafter the hardware is overwriting that value). + //Regs.STATX = value; + break; - case 0x1DB0: // 1F801DB0h 4 CD Volume Left/Right - break; // cd left? - case 0x1DB2: - break;// cd right? - case 0x1DB4: // 1F801DB4h 4 Extern Volume Left / Right - break; // Extern left? - case 0x1DB6: - break; // Extern right? - case 0x1DB8: // 1F801DB8h 4 Current Main Volume Left/Right - break; // Current left? - case 0x1DBA: - break; // Current right? - case 0x1DBC: // 1F801DBCh 4 Unknown? (R/W) - break; - case 0x1DBE: - break; + case 0x1DB0: // 1F801DB0h 4 CD Volume Left/Right + break; // cd left? + case 0x1DB2: + break; // cd right? + case 0x1DB4: // 1F801DB4h 4 Extern Volume Left / Right + break; // Extern left? + case 0x1DB6: + break; // Extern right? + case 0x1DB8: // 1F801DB8h 4 Current Main Volume Left/Right + break; // Current left? + case 0x1DBA: + break; // Current right? + case 0x1DBC: // 1F801DBCh 4 Unknown? (R/W) + break; + case 0x1DBE: + break; - case 0x1DC0: Revb.FB_SRC_A = value * 4; break; - case 0x1DC2: Revb.FB_SRC_B = value * 4; break; - case 0x1DC4: Revb.IIR_ALPHA = value; break; - case 0x1DC6: Revb.ACC_COEF_A = value; break; - case 0x1DC8: Revb.ACC_COEF_B = value; break; - case 0x1DCA: Revb.ACC_COEF_C = value; break; - case 0x1DCC: Revb.ACC_COEF_D = value; break; - case 0x1DCE: Revb.IIR_COEF = value; break; - case 0x1DD0: Revb.FB_ALPHA = value; break; - case 0x1DD2: Revb.FB_X = value; break; - case 0x1DD4: Revb.IIR_DEST_A0 = value * 4; break; - case 0x1DD6: Revb.IIR_DEST_A1 = value * 4; break; - case 0x1DD8: Revb.ACC_SRC_A0 = value * 4; break; - case 0x1DDA: Revb.ACC_SRC_A1 = value * 4; break; - case 0x1DDC: Revb.ACC_SRC_B0 = value * 4; break; - case 0x1DDE: Revb.ACC_SRC_B1 = value * 4; break; - case 0x1DE0: Revb.IIR_SRC_A0 = value * 4; break; - case 0x1DE2: Revb.IIR_SRC_A1 = value * 4; break; - case 0x1DE4: Revb.IIR_DEST_B0 = value * 4; break; - case 0x1DE6: Revb.IIR_DEST_B1 = value * 4; break; - case 0x1DE8: Revb.ACC_SRC_C0 = value * 4; break; - case 0x1DEA: Revb.ACC_SRC_C1 = value * 4; break; - case 0x1DEC: Revb.ACC_SRC_D0 = value * 4; break; - case 0x1DEE: Revb.ACC_SRC_D1 = value * 4; break; - case 0x1DF0: Revb.IIR_SRC_B0 = value * 4; break; // IIR_SRC_B0 and IIR_SRC_B1 supposedly swapped on SPU2 - case 0x1DF2: Revb.IIR_SRC_B1 = value * 4; break; // but I don't believe it! (games in psxmode sound better unswapped) - case 0x1DF4: Revb.MIX_DEST_A0 = value * 4; break; - case 0x1DF6: Revb.MIX_DEST_A1 = value * 4; break; - case 0x1DF8: Revb.MIX_DEST_B0 = value * 4; break; - case 0x1DFA: Revb.MIX_DEST_B1 = value * 4; break; - case 0x1DFC: Revb.IN_COEF_L = value; break; - case 0x1DFE: Revb.IN_COEF_R = value; break; + case 0x1DC0: + Revb.FB_SRC_A = value * 4; + break; + case 0x1DC2: + Revb.FB_SRC_B = value * 4; + break; + case 0x1DC4: + Revb.IIR_ALPHA = value; + break; + case 0x1DC6: + Revb.ACC_COEF_A = value; + break; + case 0x1DC8: + Revb.ACC_COEF_B = value; + break; + case 0x1DCA: + Revb.ACC_COEF_C = value; + break; + case 0x1DCC: + Revb.ACC_COEF_D = value; + break; + case 0x1DCE: + Revb.IIR_COEF = value; + break; + case 0x1DD0: + Revb.FB_ALPHA = value; + break; + case 0x1DD2: + Revb.FB_X = value; + break; + case 0x1DD4: + Revb.IIR_DEST_A0 = value * 4; + break; + case 0x1DD6: + Revb.IIR_DEST_A1 = value * 4; + break; + case 0x1DD8: + Revb.ACC_SRC_A0 = value * 4; + break; + case 0x1DDA: + Revb.ACC_SRC_A1 = value * 4; + break; + case 0x1DDC: + Revb.ACC_SRC_B0 = value * 4; + break; + case 0x1DDE: + Revb.ACC_SRC_B1 = value * 4; + break; + case 0x1DE0: + Revb.IIR_SRC_A0 = value * 4; + break; + case 0x1DE2: + Revb.IIR_SRC_A1 = value * 4; + break; + case 0x1DE4: + Revb.IIR_DEST_B0 = value * 4; + break; + case 0x1DE6: + Revb.IIR_DEST_B1 = value * 4; + break; + case 0x1DE8: + Revb.ACC_SRC_C0 = value * 4; + break; + case 0x1DEA: + Revb.ACC_SRC_C1 = value * 4; + break; + case 0x1DEC: + Revb.ACC_SRC_D0 = value * 4; + break; + case 0x1DEE: + Revb.ACC_SRC_D1 = value * 4; + break; + case 0x1DF0: + Revb.IIR_SRC_B0 = value * 4; + break; // IIR_SRC_B0 and IIR_SRC_B1 supposedly swapped on SPU2 + case 0x1DF2: + Revb.IIR_SRC_B1 = value * 4; + break; // but I don't believe it! (games in psxmode sound better unswapped) + case 0x1DF4: + Revb.MIX_DEST_A0 = value * 4; + break; + case 0x1DF6: + Revb.MIX_DEST_A1 = value * 4; + break; + case 0x1DF8: + Revb.MIX_DEST_B0 = value * 4; + break; + case 0x1DFA: + Revb.MIX_DEST_B1 = value * 4; + break; + case 0x1DFC: + Revb.IN_COEF_L = value; + break; + case 0x1DFE: + Revb.IN_COEF_R = value; + break; + } - } + if (show) + FileLog("[%10d] (!) SPU write mem %08x value %04x\n", Cycles, mem, value); - if(show) FileLog("[%10d] (!) SPU write mem %08x value %04x\n",Cycles,mem,value); - - spu2Ru16(mem)=value; + spu2Ru16(mem) = value; } u16 V_Core::ReadRegPS1(u32 mem) { - pxAssume( Index == 0 ); // Valid on Core 0 only! + pxAssume(Index == 0); // Valid on Core 0 only! - bool show=true; - u16 value = spu2Ru16(mem); + bool show = true; + u16 value = spu2Ru16(mem); - u32 reg = mem&0xffff; + u32 reg = mem & 0xffff; - if((reg>=0x1c00)&&(reg<0x1d80)) - { - //voice values - u8 voice = ((reg-0x1c00)>>4); - u8 vval = reg&0xf; - switch(vval) - { - case 0x0: //VOLL (Volume L) - //value=Voices[voice].VolumeL.Mode; - //value=Voices[voice].VolumeL.Value; - value = Voices[voice].Volume.Left.Reg_VOL; - break; + if ((reg >= 0x1c00) && (reg < 0x1d80)) { + //voice values + u8 voice = ((reg - 0x1c00) >> 4); + u8 vval = reg & 0xf; + switch (vval) { + case 0x0: //VOLL (Volume L) + //value=Voices[voice].VolumeL.Mode; + //value=Voices[voice].VolumeL.Value; + value = Voices[voice].Volume.Left.Reg_VOL; + break; - case 0x2: //VOLR (Volume R) - //value=Voices[voice].VolumeR.Mode; - //value=Voices[voice].VolumeR.Value; - value = Voices[voice].Volume.Right.Reg_VOL; - break; + case 0x2: //VOLR (Volume R) + //value=Voices[voice].VolumeR.Mode; + //value=Voices[voice].VolumeR.Value; + value = Voices[voice].Volume.Right.Reg_VOL; + break; - case 0x4: - value = Voices[voice].Pitch; - //ConLog("voice %d read pitch result = %x\n", voice, value); - break; - case 0x6: - value = map_spu2to1(Voices[voice].StartA); - //ConLog("voice %d read StartA result = %x\n", voice, value); - break; - case 0x8: - value = Voices[voice].ADSR.regADSR1; - break; - case 0xa: - value = Voices[voice].ADSR.regADSR2; - break; - case 0xc: // Voice 0..23 ADSR Current Volume - value = Voices[voice].ADSR.Value >> 16; // no clue - //if (value != 0) ConLog("voice %d read ADSR.Value result = %x\n", voice, value); - break; - case 0xe: - value = map_spu2to1(Voices[voice].LoopStartA); - //ConLog("voice %d read LoopStartA result = %x\n", voice, value); - break; + case 0x4: + value = Voices[voice].Pitch; + //ConLog("voice %d read pitch result = %x\n", voice, value); + break; + case 0x6: + value = map_spu2to1(Voices[voice].StartA); + //ConLog("voice %d read StartA result = %x\n", voice, value); + break; + case 0x8: + value = Voices[voice].ADSR.regADSR1; + break; + case 0xa: + value = Voices[voice].ADSR.regADSR2; + break; + case 0xc: // Voice 0..23 ADSR Current Volume + value = Voices[voice].ADSR.Value >> 16; // no clue + //if (value != 0) ConLog("voice %d read ADSR.Value result = %x\n", voice, value); + break; + case 0xe: + value = map_spu2to1(Voices[voice].LoopStartA); + //ConLog("voice %d read LoopStartA result = %x\n", voice, value); + break; - jNO_DEFAULT; - } - } - else switch(reg) - { - case 0x1d80: value = MasterVol.Left.Value >> 16; break; - case 0x1d82: value = MasterVol.Right.Value >> 16; break; - case 0x1d84: value = FxVol.Left >> 16; break; - case 0x1d86: value = FxVol.Right >> 16; break; + jNO_DEFAULT; + } + } else + switch (reg) { + case 0x1d80: + value = MasterVol.Left.Value >> 16; + break; + case 0x1d82: + value = MasterVol.Right.Value >> 16; + break; + case 0x1d84: + value = FxVol.Left >> 16; + break; + case 0x1d86: + value = FxVol.Right >> 16; + break; - case 0x1d88: value = 0; break; // Voice 0..23 Key ON(Start Attack / Decay / Sustain) (W) - case 0x1d8a: value = 0; break; - case 0x1d8c: value = 0; break; // Voice 0..23 Key OFF (Start Release) (W) - case 0x1d8e: value = 0; break; + case 0x1d88: + value = 0; + break; // Voice 0..23 Key ON(Start Attack / Decay / Sustain) (W) + case 0x1d8a: + value = 0; + break; + case 0x1d8c: + value = 0; + break; // Voice 0..23 Key OFF (Start Release) (W) + case 0x1d8e: + value = 0; + break; - case 0x1d90: value = Regs.PMON&0xFFFF; break; // Voice 0..23 Channel FM(pitch lfo) mode(R / W) - case 0x1d92: value = Regs.PMON>>16; break; + case 0x1d90: + value = Regs.PMON & 0xFFFF; + break; // Voice 0..23 Channel FM(pitch lfo) mode(R / W) + case 0x1d92: + value = Regs.PMON >> 16; + break; - case 0x1d94: value = Regs.NON&0xFFFF; break; // Voice 0..23 Channel Noise mode (R/W) - case 0x1d96: value = Regs.NON>>16; break; + case 0x1d94: + value = Regs.NON & 0xFFFF; + break; // Voice 0..23 Channel Noise mode (R/W) + case 0x1d96: + value = Regs.NON >> 16; + break; - case 0x1d98: value = Regs.VMIXEL&0xFFFF; break; // Voice 0..23 Channel Reverb mode (R/W) - case 0x1d9a: value = Regs.VMIXEL>>16; break; - /*case 0x1d9c: value = Regs.VMIXL&0xFFFF; break;*/ // this is wrong? - /*case 0x1d9e: value = Regs.VMIXL >> 16; break;*/ - case 0x1d9c: value = Regs.ENDX & 0xFFFF; break;// Voice 0..23 Channel ON / OFF(status) (R) (ENDX) - case 0x1d9e: value = Regs.ENDX >> 16; + case 0x1d98: + value = Regs.VMIXEL & 0xFFFF; + break; // Voice 0..23 Channel Reverb mode (R/W) + case 0x1d9a: + value = Regs.VMIXEL >> 16; + break; + /*case 0x1d9c: value = Regs.VMIXL&0xFFFF; break;*/ // this is wrong? + /*case 0x1d9e: value = Regs.VMIXL >> 16; break;*/ + case 0x1d9c: + value = Regs.ENDX & 0xFFFF; + break; // Voice 0..23 Channel ON / OFF(status) (R) (ENDX) + case 0x1d9e: + value = Regs.ENDX >> 16; - case 0x1da2: - value = map_spu2to1(EffectsStartA); - break; - case 0x1da4: - value = map_spu2to1(IRQA); - //ConLog("SPU2-X IRQA read: 0x1da4 = %x , (IRQA = %x)\n", value, IRQA); - break; - case 0x1da6: - value = map_spu2to1(TSA); - //ConLog("SPU2-X TSA read: 0x1da6 = %x , (TSA = %x)\n", value, TSA); - break; - case 0x1da8: - value = DmaRead(); - show=false; - break; - case 0x1daa: - value = Cores[0].Regs.ATTR; - //ConLog("SPU2-X ps1 reg psxSPUCNT read return value: %x\n", value); - break; - case 0x1dac: // 1F801DACh - Sound RAM Data Transfer Control (should be 0004h) - value = psxSoundDataTransferControl; - break; - case 0x1dae: - value = Cores[0].Regs.STATX; - //ConLog("SPU2-X ps1 reg REG_P_STATX read return value: %x\n", value); - break; - } + case 0x1da2: + value = map_spu2to1(EffectsStartA); + break; + case 0x1da4: + value = map_spu2to1(IRQA); + //ConLog("SPU2-X IRQA read: 0x1da4 = %x , (IRQA = %x)\n", value, IRQA); + break; + case 0x1da6: + value = map_spu2to1(TSA); + //ConLog("SPU2-X TSA read: 0x1da6 = %x , (TSA = %x)\n", value, TSA); + break; + case 0x1da8: + value = DmaRead(); + show = false; + break; + case 0x1daa: + value = Cores[0].Regs.ATTR; + //ConLog("SPU2-X ps1 reg psxSPUCNT read return value: %x\n", value); + break; + case 0x1dac: // 1F801DACh - Sound RAM Data Transfer Control (should be 0004h) + value = psxSoundDataTransferControl; + break; + case 0x1dae: + value = Cores[0].Regs.STATX; + //ConLog("SPU2-X ps1 reg REG_P_STATX read return value: %x\n", value); + break; + } - if(show) FileLog("[%10d] (!) SPU read mem %08x value %04x\n",Cycles,mem,value); - return value; + if (show) + FileLog("[%10d] (!) SPU read mem %08x value %04x\n", Cycles, mem, value); + return value; } // Ah the joys of endian-specific code! :D -static __forceinline void SetHiWord( u32& src, u16 value ) +static __forceinline void SetHiWord(u32 &src, u16 value) { - ((u16*)&src)[1] = value; + ((u16 *)&src)[1] = value; } -static __forceinline void SetLoWord( u32& src, u16 value ) +static __forceinline void SetLoWord(u32 &src, u16 value) { - ((u16*)&src)[0] = value; + ((u16 *)&src)[0] = value; } -static __forceinline u16 GetHiWord( u32& src ) +static __forceinline u16 GetHiWord(u32 &src) { - return ((u16*)&src)[1]; + return ((u16 *)&src)[1]; } -static __forceinline u16 GetLoWord( u32& src ) +static __forceinline u16 GetLoWord(u32 &src) { - return ((u16*)&src)[0]; + return ((u16 *)&src)[0]; } -template< int CoreIdx, int VoiceIdx, int param > -static void __fastcall RegWrite_VoiceParams( u16 value ) +template +static void __fastcall RegWrite_VoiceParams(u16 value) { - const int core = CoreIdx; - const int voice = VoiceIdx; + const int core = CoreIdx; + const int voice = VoiceIdx; - V_Voice& thisvoice = Cores[core].Voices[voice]; + V_Voice &thisvoice = Cores[core].Voices[voice]; - switch (param) - { - case 0: //VOLL (Volume L) - case 1: //VOLR (Volume R) - { - V_VolumeSlide& thisvol = (param==0) ? thisvoice.Volume.Left : thisvoice.Volume.Right; - thisvol.Reg_VOL = value; + switch (param) { + case 0: //VOLL (Volume L) + case 1: //VOLR (Volume R) + { + V_VolumeSlide &thisvol = (param == 0) ? thisvoice.Volume.Left : thisvoice.Volume.Right; + thisvol.Reg_VOL = value; - if (value & 0x8000) // +Lin/-Lin/+Exp/-Exp - { - thisvol.Mode = (value & 0xF000)>>12; - thisvol.Increment = (value & 0x7F); - // We're not sure slides work 100% - if( IsDevBuild ) ConLog("* SPU2: Voice uses Slides in Mode = %x, Increment = %x\n",thisvol.Mode,thisvol.Increment); - } - else - { - // Constant Volume mode (no slides or envelopes) - // Volumes range from 0x3fff to 0x7fff, with 0x4000 serving as - // the "sign" bit, so a simple bitwise extension will do the trick: + if (value & 0x8000) // +Lin/-Lin/+Exp/-Exp + { + thisvol.Mode = (value & 0xF000) >> 12; + thisvol.Increment = (value & 0x7F); + // We're not sure slides work 100% + if (IsDevBuild) + ConLog("* SPU2: Voice uses Slides in Mode = %x, Increment = %x\n", thisvol.Mode, thisvol.Increment); + } else { + // Constant Volume mode (no slides or envelopes) + // Volumes range from 0x3fff to 0x7fff, with 0x4000 serving as + // the "sign" bit, so a simple bitwise extension will do the trick: - thisvol.RegSet( value<<1 ); - thisvol.Mode = 0; - thisvol.Increment = 0; - } - } - break; + thisvol.RegSet(value << 1); + thisvol.Mode = 0; + thisvol.Increment = 0; + } + } break; - case 2: - if (value > 0x3fff) ConLog( "* SPU2: Pitch setting too big: 0x%x\n", value); - thisvoice.Pitch = value & 0x3fff; - break; + case 2: + if (value > 0x3fff) + ConLog("* SPU2: Pitch setting too big: 0x%x\n", value); + thisvoice.Pitch = value & 0x3fff; + break; - case 3: // ADSR1 (Envelope) - thisvoice.ADSR.regADSR1 = value; - break; + case 3: // ADSR1 (Envelope) + thisvoice.ADSR.regADSR1 = value; + break; - case 4: // ADSR2 (Envelope) - thisvoice.ADSR.regADSR2 = value; - break; + case 4: // ADSR2 (Envelope) + thisvoice.ADSR.regADSR2 = value; + break; - case 5: - // [Air] : Mysterious ADSR set code. Too bad none of my games ever use it. - // (as usual... ) - thisvoice.ADSR.Value = (value << 16) | value; - ConLog( "* SPU2: Mysterious ADSR Volume Set to 0x%x\n", value ); - break; + case 5: + // [Air] : Mysterious ADSR set code. Too bad none of my games ever use it. + // (as usual... ) + thisvoice.ADSR.Value = (value << 16) | value; + ConLog("* SPU2: Mysterious ADSR Volume Set to 0x%x\n", value); + break; - case 6: thisvoice.Volume.Left.RegSet( value ); break; - case 7: thisvoice.Volume.Right.RegSet( value ); break; + case 6: + thisvoice.Volume.Left.RegSet(value); + break; + case 7: + thisvoice.Volume.Right.RegSet(value); + break; - jNO_DEFAULT; - } + jNO_DEFAULT; + } } -template< int CoreIdx, int VoiceIdx, int address > -static void __fastcall RegWrite_VoiceAddr( u16 value ) +template +static void __fastcall RegWrite_VoiceAddr(u16 value) { - const int core = CoreIdx; - const int voice = VoiceIdx; + const int core = CoreIdx; + const int voice = VoiceIdx; - V_Voice& thisvoice = Cores[core].Voices[voice]; + V_Voice &thisvoice = Cores[core].Voices[voice]; - switch (address) - { - case 0: // SSA (Waveform Start Addr) (hiword, 4 bits only) - thisvoice.StartA = ((value & 0x0F) << 16) | (thisvoice.StartA & 0xFFF8); - if( IsDevBuild ) - DebugCores[core].Voices[voice].lastSetStartA = thisvoice.StartA; - break; + switch (address) { + case 0: // SSA (Waveform Start Addr) (hiword, 4 bits only) + thisvoice.StartA = ((value & 0x0F) << 16) | (thisvoice.StartA & 0xFFF8); + if (IsDevBuild) + DebugCores[core].Voices[voice].lastSetStartA = thisvoice.StartA; + break; - case 1: // SSA (loword) - thisvoice.StartA = (thisvoice.StartA & 0x0F0000) | (value & 0xFFF8); - if( IsDevBuild ) - DebugCores[core].Voices[voice].lastSetStartA = thisvoice.StartA; - break; + case 1: // SSA (loword) + thisvoice.StartA = (thisvoice.StartA & 0x0F0000) | (value & 0xFFF8); + if (IsDevBuild) + DebugCores[core].Voices[voice].lastSetStartA = thisvoice.StartA; + break; - case 2: - thisvoice.LoopStartA = ((value & 0x0F) << 16) | (thisvoice.LoopStartA & 0xFFF8); - thisvoice.LoopMode = 1; - break; + case 2: + thisvoice.LoopStartA = ((value & 0x0F) << 16) | (thisvoice.LoopStartA & 0xFFF8); + thisvoice.LoopMode = 1; + break; - case 3: - thisvoice.LoopStartA = (thisvoice.LoopStartA & 0x0F0000) | (value & 0xFFF8); - thisvoice.LoopMode = 1; - break; + case 3: + thisvoice.LoopStartA = (thisvoice.LoopStartA & 0x0F0000) | (value & 0xFFF8); + thisvoice.LoopMode = 1; + break; - // Note that there's no proof that I know of that writing to NextA is - // even allowed or handled by the SPU2 (it might be disabled or ignored, - // for example). Tests should be done to find games that write to this - // reg, and see if they're buggy or not. --air + // Note that there's no proof that I know of that writing to NextA is + // even allowed or handled by the SPU2 (it might be disabled or ignored, + // for example). Tests should be done to find games that write to this + // reg, and see if they're buggy or not. --air - case 4: - thisvoice.NextA = ((value & 0x0F) << 16) | (thisvoice.NextA & 0xFFF8) | 1; - thisvoice.SCurrent = 28; - break; + case 4: + thisvoice.NextA = ((value & 0x0F) << 16) | (thisvoice.NextA & 0xFFF8) | 1; + thisvoice.SCurrent = 28; + break; - case 5: - thisvoice.NextA = (thisvoice.NextA & 0x0F0000) | (value & 0xFFF8) | 1; - thisvoice.SCurrent = 28; - break; - } + case 5: + thisvoice.NextA = (thisvoice.NextA & 0x0F0000) | (value & 0xFFF8) | 1; + thisvoice.SCurrent = 28; + break; + } } -template< int CoreIdx, int cAddr > -static void __fastcall RegWrite_Core( u16 value ) +template +static void __fastcall RegWrite_Core(u16 value) { - const int omem = cAddr; - const int core = CoreIdx; - V_Core& thiscore = Cores[core]; + const int omem = cAddr; + const int core = CoreIdx; + V_Core &thiscore = Cores[core]; - switch(omem) - { - case REG__1AC: - // ---------------------------------------------------------------------------- - // 0x1ac / 0x5ac : direct-write to DMA address : special register (undocumented) - // ---------------------------------------------------------------------------- - // On the GS, DMAs are actually pushed through a hardware register. Chances are the - // SPU works the same way, and "technically" *all* DMA data actually passes through - // the HW registers at 0x1ac (core0) and 0x5ac (core1). We handle normal DMAs in - // optimized block copy fashion elsewhere, but some games will write this register - // directly, so handle those here: + switch (omem) { + case REG__1AC: + // ---------------------------------------------------------------------------- + // 0x1ac / 0x5ac : direct-write to DMA address : special register (undocumented) + // ---------------------------------------------------------------------------- + // On the GS, DMAs are actually pushed through a hardware register. Chances are the + // SPU works the same way, and "technically" *all* DMA data actually passes through + // the HW registers at 0x1ac (core0) and 0x5ac (core1). We handle normal DMAs in + // optimized block copy fashion elsewhere, but some games will write this register + // directly, so handle those here: - // Performance Note: The PS2 Bios uses this extensively right before booting games, - // causing massive slowdown if we don't shortcut it here. + // Performance Note: The PS2 Bios uses this extensively right before booting games, + // causing massive slowdown if we don't shortcut it here. - for( int i=0; i<2; i++ ) - { - if(Cores[i].IRQEnable && (Cores[i].IRQA == thiscore.TSA)) - { - SetIrqCall(i); - } - } - thiscore.DmaWrite( value ); - break; + for (int i = 0; i < 2; i++) { + if (Cores[i].IRQEnable && (Cores[i].IRQA == thiscore.TSA)) { + SetIrqCall(i); + } + } + thiscore.DmaWrite(value); + break; - case REG_C_ATTR: - { - bool irqe = thiscore.IRQEnable; - int bit0 = thiscore.AttrBit0; - bool fxenable = thiscore.FxEnable; - u8 oldDmaMode = thiscore.DmaMode; - - thiscore.AttrBit0 =(value>> 0) & 0x01; //1 bit - thiscore.DMABits =(value>> 1) & 0x07; //3 bits - thiscore.DmaMode =(value>> 4) & 0x03; //2 bit (not necessary, we get the direction from the iop) - thiscore.IRQEnable =(value>> 6) & 0x01; //1 bit - thiscore.FxEnable =(value>> 7) & 0x01; //1 bit - thiscore.NoiseClk =(value>> 8) & 0x3f; //6 bits - //thiscore.Mute =(value>>14) & 0x01; //1 bit - thiscore.Mute =0; - //thiscore.CoreEnabled=(value>>15) & 0x01; //1 bit - // no clue - if (value>>15) - thiscore.Regs.STATX = 0; - thiscore.Regs.ATTR =value&0x7fff; + case REG_C_ATTR: { + bool irqe = thiscore.IRQEnable; + int bit0 = thiscore.AttrBit0; + bool fxenable = thiscore.FxEnable; + u8 oldDmaMode = thiscore.DmaMode; - if (fxenable && !thiscore.FxEnable - && (thiscore.EffectsStartA != thiscore.ExtEffectsStartA - || thiscore.EffectsEndA != thiscore.ExtEffectsEndA)) - { - thiscore.EffectsStartA = thiscore.ExtEffectsStartA; - thiscore.EffectsEndA = thiscore.ExtEffectsEndA; - thiscore.ReverbX = 0; - thiscore.RevBuffers.NeedsUpdated = true; - } + thiscore.AttrBit0 = (value >> 0) & 0x01; //1 bit + thiscore.DMABits = (value >> 1) & 0x07; //3 bits + thiscore.DmaMode = (value >> 4) & 0x03; //2 bit (not necessary, we get the direction from the iop) + thiscore.IRQEnable = (value >> 6) & 0x01; //1 bit + thiscore.FxEnable = (value >> 7) & 0x01; //1 bit + thiscore.NoiseClk = (value >> 8) & 0x3f; //6 bits + //thiscore.Mute =(value>>14) & 0x01; //1 bit + thiscore.Mute = 0; + //thiscore.CoreEnabled=(value>>15) & 0x01; //1 bit + // no clue + if (value >> 15) + thiscore.Regs.STATX = 0; + thiscore.Regs.ATTR = value & 0x7fff; - if(oldDmaMode != thiscore.DmaMode) - { - // FIXME... maybe: if this mode was cleared in the middle of a DMA, should we interrupt it? - thiscore.Regs.STATX &= ~0x400; // ready to transfer - } + if (fxenable && !thiscore.FxEnable && (thiscore.EffectsStartA != thiscore.ExtEffectsStartA || thiscore.EffectsEndA != thiscore.ExtEffectsEndA)) { + thiscore.EffectsStartA = thiscore.ExtEffectsStartA; + thiscore.EffectsEndA = thiscore.ExtEffectsEndA; + thiscore.ReverbX = 0; + thiscore.RevBuffers.NeedsUpdated = true; + } - if(value&0x000E) - { - if(MsgToConsole()) ConLog("* SPU2-X: Core %d ATTR unknown bits SET! value=%04x\n",core,value); - } + if (oldDmaMode != thiscore.DmaMode) { + // FIXME... maybe: if this mode was cleared in the middle of a DMA, should we interrupt it? + thiscore.Regs.STATX &= ~0x400; // ready to transfer + } - if(thiscore.AttrBit0!=bit0) - { - if(MsgToConsole()) ConLog("* SPU2-X: ATTR bit 0 set to %d\n",thiscore.AttrBit0); - } - if(thiscore.IRQEnable!=irqe) - { - //ConLog("* SPU2-X: Core%d IRQ %s at cycle %d. Current IRQA = %x Current EffectA = %x\n", - // core, ((thiscore.IRQEnable==0)?"disabled":"enabled"), Cycles, thiscore.IRQA, thiscore.EffectsStartA); - - if(!thiscore.IRQEnable) - Spdif.Info &= ~(4 << thiscore.Index); - } + if (value & 0x000E) { + if (MsgToConsole()) + ConLog("* SPU2-X: Core %d ATTR unknown bits SET! value=%04x\n", core, value); + } - } - break; + if (thiscore.AttrBit0 != bit0) { + if (MsgToConsole()) + ConLog("* SPU2-X: ATTR bit 0 set to %d\n", thiscore.AttrBit0); + } + if (thiscore.IRQEnable != irqe) { + //ConLog("* SPU2-X: Core%d IRQ %s at cycle %d. Current IRQA = %x Current EffectA = %x\n", + // core, ((thiscore.IRQEnable==0)?"disabled":"enabled"), Cycles, thiscore.IRQA, thiscore.EffectsStartA); - case REG_S_PMON: - for( int vc=1; vc<16; ++vc ) - thiscore.Voices[vc].Modulated = (value >> vc) & 1; - SetLoWord( thiscore.Regs.PMON, value ); - break; + if (!thiscore.IRQEnable) + Spdif.Info &= ~(4 << thiscore.Index); + } - case (REG_S_PMON + 2): - for( int vc=0; vc<8; ++vc ) - thiscore.Voices[vc+16].Modulated = (value >> vc) & 1; - SetHiWord( thiscore.Regs.PMON, value ); - break; + } break; - case REG_S_NON: - for( int vc=0; vc<16; ++vc) - thiscore.Voices[vc].Noise = (value >> vc) & 1; - SetLoWord( thiscore.Regs.NON, value ); - break; + case REG_S_PMON: + for (int vc = 1; vc < 16; ++vc) + thiscore.Voices[vc].Modulated = (value >> vc) & 1; + SetLoWord(thiscore.Regs.PMON, value); + break; - case (REG_S_NON + 2): - for( int vc=0; vc<8; ++vc ) - thiscore.Voices[vc+16].Noise = (value >> vc) & 1; - SetHiWord( thiscore.Regs.NON, value ); - break; + case (REG_S_PMON + 2): + for (int vc = 0; vc < 8; ++vc) + thiscore.Voices[vc + 16].Modulated = (value >> vc) & 1; + SetHiWord(thiscore.Regs.PMON, value); + break; + + case REG_S_NON: + for (int vc = 0; vc < 16; ++vc) + thiscore.Voices[vc].Noise = (value >> vc) & 1; + SetLoWord(thiscore.Regs.NON, value); + break; + + case (REG_S_NON + 2): + for (int vc = 0; vc < 8; ++vc) + thiscore.Voices[vc + 16].Noise = (value >> vc) & 1; + SetHiWord(thiscore.Regs.NON, value); + break; // Games like to repeatedly write these regs over and over with the same value, hence // the shortcut that skips the bitloop if the values are equal. -#define vx_SetSomeBits( reg_out, mask_out, hiword ) \ -{ \ - const u32 result = thiscore.Regs.reg_out; \ - if( hiword ) \ - SetHiWord( thiscore.Regs.reg_out, value ); \ - else \ - SetLoWord( thiscore.Regs.reg_out, value ); \ - if( result == thiscore.Regs.reg_out ) break; \ - \ - const uint start_bit = (hiword) ? 16 : 0; \ - const uint end_bit = (hiword) ? 24 : 16; \ - for (uint vc=start_bit, vx=1; vc> 1 | core * 0x200] = value; + break; + + case REG_S_KON: + StartVoices(core, ((u32)value)); + spu2regs[omem >> 1 | core * 0x200] = value; + break; + + case (REG_S_KOFF + 2): + StopVoices(core, ((u32)value) << 16); + spu2regs[omem >> 1 | core * 0x200] = value; + break; + + case REG_S_KOFF: + StopVoices(core, ((u32)value)); + spu2regs[omem >> 1 | core * 0x200] = value; + break; + + case REG_S_ENDX: + thiscore.Regs.ENDX &= 0xff0000; + break; + + case (REG_S_ENDX + 2): + thiscore.Regs.ENDX &= 0xffff; + break; + + // Reverb Start and End Address Writes! + // * These regs are only writable when Effects are *DISABLED* (FxEnable is false). + // Writes while enabled should be ignored. + // NOTE: Above is false by testing but there are references saying this, so for + // now we think that writing is allowed but the internal register doesn't reflect + // the value until effects area writing is disabled. + // * Yes, these are backwards from all the volumes -- the hiword comes FIRST (wtf!) + // * End position is a hiword only! Loword is always ffff. + // * The Reverb buffer position resets on writes to StartA. It probably resets + // on writes to End too. Docs don't say, but they're for PSX, which couldn't + // change the end address anyway. + // + case REG_A_ESA: + SetHiWord(thiscore.ExtEffectsStartA, value); + if (!thiscore.FxEnable) { + thiscore.EffectsStartA = thiscore.ExtEffectsStartA; + thiscore.ReverbX = 0; + thiscore.RevBuffers.NeedsUpdated = true; + } + break; + + case (REG_A_ESA + 2): + SetLoWord(thiscore.ExtEffectsStartA, value); + if (!thiscore.FxEnable) { + thiscore.EffectsStartA = thiscore.ExtEffectsStartA; + thiscore.ReverbX = 0; + thiscore.RevBuffers.NeedsUpdated = true; + } + break; + + case REG_A_EEA: + thiscore.ExtEffectsEndA = ((u32)value << 16) | 0xFFFF; + if (!thiscore.FxEnable) { + thiscore.EffectsEndA = thiscore.ExtEffectsEndA; + thiscore.ReverbX = 0; + thiscore.RevBuffers.NeedsUpdated = true; + } + break; + + case REG_S_ADMAS: + if (MsgToConsole()) + ConLog("* SPU2-X: Core %d AutoDMAControl set to %d (at cycle %d)\n", core, value, Cycles); + + if (psxmode) + ConLog("* SPU2-X: Writing to REG_S_ADMAS while in PSX mode! value: %x", value); + // hack for ps1driver which writes -1 (and never turns the adma off after psxlogo). + // adma isn't available in psx mode either + if (value == 32767) { + psxmode = true; + //memset(_spu2mem, 0, 0x200000); + Cores[1].FxEnable = 0; + Cores[1].EffectsStartA = 0x7FFF8; // park core1 effect area in inaccessible mem + Cores[1].EffectsEndA = 0x7FFFF; + Cores[1].ExtEffectsStartA = 0x7FFF8; // park core1 ext effect area in high mem + Cores[1].ExtEffectsStartA = 0x7FFFF; + Cores[1].ReverbX = 0; + Cores[1].RevBuffers.NeedsUpdated = true; + Cores[0].ReverbX = 0; + Cores[0].RevBuffers.NeedsUpdated = true; + for (uint v = 0; v < 24; ++v) { + Cores[1].Voices[v].Volume = V_VolumeSlideLR(0, 0); // V_VolumeSlideLR::Max; + Cores[1].Voices[v].SCurrent = 28; + + Cores[1].Voices[v].ADSR.Value = 0; + Cores[1].Voices[v].ADSR.Phase = 0; + Cores[1].Voices[v].Pitch = 0x0; + Cores[1].Voices[v].NextA = 0x6FFFF; + Cores[1].Voices[v].StartA = 0x6FFFF; + Cores[1].Voices[v].LoopStartA = 0x6FFFF; + Cores[1].Voices[v].Modulated = 0; + } + return; + } + thiscore.AutoDMACtrl = value; + + if (value == 0) { + thiscore.AdmaInProgress = 0; + } + break; + + default: { + const int addr = omem | ((core == 1) ? 0x400 : 0); + *(regtable[addr >> 1]) = value; + } break; + } } - case REG_S_VMIXL: - vx_SetSomeBits( VMIXL, DryL, false ); - break; - - case (REG_S_VMIXL + 2): - vx_SetSomeBits( VMIXL, DryL, true ); - break; - - case REG_S_VMIXEL: - vx_SetSomeBits( VMIXEL, WetL, false ); - break; - - case (REG_S_VMIXEL + 2): - vx_SetSomeBits( VMIXEL, WetL, true ); - break; - - case REG_S_VMIXR: - vx_SetSomeBits( VMIXR, DryR, false ); - break; - - case (REG_S_VMIXR + 2): - vx_SetSomeBits( VMIXR, DryR, true ); - break; - - case REG_S_VMIXER: - vx_SetSomeBits( VMIXER, WetR, false ); - break; - - case (REG_S_VMIXER + 2): - vx_SetSomeBits( VMIXER, WetR, true ); - break; - - case REG_P_MMIX: - { - // Each MMIX gate is assigned either 0 or 0xffffffff depending on the status - // of the MMIX bits. I use -1 below as a shorthand for 0xffffffff. :) - - const int vx = value & ((core==0) ? 0xFF0 : 0xFFF); - thiscore.WetGate.ExtR = (vx & 0x001) ? -1 : 0; - thiscore.WetGate.ExtL = (vx & 0x002) ? -1 : 0; - thiscore.DryGate.ExtR = (vx & 0x004) ? -1 : 0; - thiscore.DryGate.ExtL = (vx & 0x008) ? -1 : 0; - thiscore.WetGate.InpR = (vx & 0x010) ? -1 : 0; - thiscore.WetGate.InpL = (vx & 0x020) ? -1 : 0; - thiscore.DryGate.InpR = (vx & 0x040) ? -1 : 0; - thiscore.DryGate.InpL = (vx & 0x080) ? -1 : 0; - thiscore.WetGate.SndR = (vx & 0x100) ? -1 : 0; - thiscore.WetGate.SndL = (vx & 0x200) ? -1 : 0; - thiscore.DryGate.SndR = (vx & 0x400) ? -1 : 0; - thiscore.DryGate.SndL = (vx & 0x800) ? -1 : 0; - thiscore.Regs.MMIX = value; - } - break; - - case (REG_S_KON + 2): - StartVoices(core,((u32)value)<<16); - spu2regs[omem >> 1 | core * 0x200] = value; - break; - - case REG_S_KON: - StartVoices(core,((u32)value)); - spu2regs[omem >> 1 | core * 0x200] = value; - break; - - case (REG_S_KOFF + 2): - StopVoices(core,((u32)value)<<16); - spu2regs[omem >> 1 | core * 0x200] = value; - break; - - case REG_S_KOFF: - StopVoices(core,((u32)value)); - spu2regs[omem >> 1 | core * 0x200] = value; - break; - - case REG_S_ENDX: - thiscore.Regs.ENDX &= 0xff0000; - break; - - case (REG_S_ENDX + 2): - thiscore.Regs.ENDX &= 0xffff; - break; - - // Reverb Start and End Address Writes! - // * These regs are only writable when Effects are *DISABLED* (FxEnable is false). - // Writes while enabled should be ignored. - // NOTE: Above is false by testing but there are references saying this, so for - // now we think that writing is allowed but the internal register doesn't reflect - // the value until effects area writing is disabled. - // * Yes, these are backwards from all the volumes -- the hiword comes FIRST (wtf!) - // * End position is a hiword only! Loword is always ffff. - // * The Reverb buffer position resets on writes to StartA. It probably resets - // on writes to End too. Docs don't say, but they're for PSX, which couldn't - // change the end address anyway. - // - case REG_A_ESA: - SetHiWord( thiscore.ExtEffectsStartA, value ); - if (!thiscore.FxEnable) - { - thiscore.EffectsStartA = thiscore.ExtEffectsStartA; - thiscore.ReverbX = 0; - thiscore.RevBuffers.NeedsUpdated = true; - } - break; - - case (REG_A_ESA + 2): - SetLoWord( thiscore.ExtEffectsStartA, value ); - if (!thiscore.FxEnable) - { - thiscore.EffectsStartA = thiscore.ExtEffectsStartA; - thiscore.ReverbX = 0; - thiscore.RevBuffers.NeedsUpdated = true; - } - break; - - case REG_A_EEA: - thiscore.ExtEffectsEndA = ((u32)value<<16) | 0xFFFF; - if (!thiscore.FxEnable) - { - thiscore.EffectsEndA = thiscore.ExtEffectsEndA; - thiscore.ReverbX = 0; - thiscore.RevBuffers.NeedsUpdated = true; - } - break; - - case REG_S_ADMAS: - if ( MsgToConsole() ) ConLog("* SPU2-X: Core %d AutoDMAControl set to %d (at cycle %d)\n",core,value, Cycles); - - if (psxmode) ConLog("* SPU2-X: Writing to REG_S_ADMAS while in PSX mode! value: %x",value); - // hack for ps1driver which writes -1 (and never turns the adma off after psxlogo). - // adma isn't available in psx mode either - if (value == 32767) { - psxmode = true; - //memset(_spu2mem, 0, 0x200000); - Cores[1].FxEnable = 0; - Cores[1].EffectsStartA = 0x7FFF8; // park core1 effect area in inaccessible mem - Cores[1].EffectsEndA = 0x7FFFF; - Cores[1].ExtEffectsStartA = 0x7FFF8; // park core1 ext effect area in high mem - Cores[1].ExtEffectsStartA = 0x7FFFF; - Cores[1].ReverbX = 0; - Cores[1].RevBuffers.NeedsUpdated = true; - Cores[0].ReverbX = 0; - Cores[0].RevBuffers.NeedsUpdated = true; - for (uint v = 0; v < 24; ++v) - { - Cores[1].Voices[v].Volume = V_VolumeSlideLR(0, 0); // V_VolumeSlideLR::Max; - Cores[1].Voices[v].SCurrent = 28; - - Cores[1].Voices[v].ADSR.Value = 0; - Cores[1].Voices[v].ADSR.Phase = 0; - Cores[1].Voices[v].Pitch = 0x0; - Cores[1].Voices[v].NextA = 0x6FFFF; - Cores[1].Voices[v].StartA = 0x6FFFF; - Cores[1].Voices[v].LoopStartA = 0x6FFFF; - Cores[1].Voices[v].Modulated = 0; - } - return; - } - thiscore.AutoDMACtrl=value; - - if(value==0) - { - thiscore.AdmaInProgress=0; - } - break; - - default: - { - const int addr = omem | ( (core == 1) ? 0x400 : 0 ); - *(regtable[addr>>1]) = value; - } - break; - } -} - -template< int CoreIdx, int addr > -static void __fastcall RegWrite_CoreExt( u16 value ) +template +static void __fastcall RegWrite_CoreExt(u16 value) { - V_Core& thiscore = Cores[CoreIdx]; - const int core = CoreIdx; + V_Core &thiscore = Cores[CoreIdx]; + const int core = CoreIdx; - switch(addr) - { - // Master Volume Address Write! + switch (addr) { + // Master Volume Address Write! - case REG_P_MVOLL: - case REG_P_MVOLR: - { - V_VolumeSlide& thisvol = (addr==REG_P_MVOLL) ? thiscore.MasterVol.Left : thiscore.MasterVol.Right; + case REG_P_MVOLL: + case REG_P_MVOLR: { + V_VolumeSlide &thisvol = (addr == REG_P_MVOLL) ? thiscore.MasterVol.Left : thiscore.MasterVol.Right; - if (value & 0x8000) // +Lin/-Lin/+Exp/-Exp - { - thisvol.Mode = (value & 0xF000)>>12; - thisvol.Increment = (value & 0x7F); - //printf("slides Mode = %x, Increment = %x\n",thisvol.Mode,thisvol.Increment); - } - else - { - // Constant Volume mode (no slides or envelopes) - // Volumes range from 0x3fff to 0x7fff, with 0x4000 serving as - // the "sign" bit, so a simple bitwise extension will do the trick: + if (value & 0x8000) // +Lin/-Lin/+Exp/-Exp + { + thisvol.Mode = (value & 0xF000) >> 12; + thisvol.Increment = (value & 0x7F); + //printf("slides Mode = %x, Increment = %x\n",thisvol.Mode,thisvol.Increment); + } else { + // Constant Volume mode (no slides or envelopes) + // Volumes range from 0x3fff to 0x7fff, with 0x4000 serving as + // the "sign" bit, so a simple bitwise extension will do the trick: - thisvol.Value = GetVol32( value<<1 ); - thisvol.Mode = 0; - thisvol.Increment = 0; - } - thisvol.Reg_VOL = value; - } - break; + thisvol.Value = GetVol32(value << 1); + thisvol.Mode = 0; + thisvol.Increment = 0; + } + thisvol.Reg_VOL = value; + } break; - case REG_P_EVOLL: - thiscore.FxVol.Left = GetVol32( value ); - break; + case REG_P_EVOLL: + thiscore.FxVol.Left = GetVol32(value); + break; - case REG_P_EVOLR: - thiscore.FxVol.Right = GetVol32( value ); - break; + case REG_P_EVOLR: + thiscore.FxVol.Right = GetVol32(value); + break; - case REG_P_AVOLL: - thiscore.ExtVol.Left = GetVol32( value ); - break; + case REG_P_AVOLL: + thiscore.ExtVol.Left = GetVol32(value); + break; - case REG_P_AVOLR: - thiscore.ExtVol.Right = GetVol32( value ); - break; + case REG_P_AVOLR: + thiscore.ExtVol.Right = GetVol32(value); + break; - case REG_P_BVOLL: - thiscore.InpVol.Left = GetVol32( value ); - break; + case REG_P_BVOLL: + thiscore.InpVol.Left = GetVol32(value); + break; - case REG_P_BVOLR: - thiscore.InpVol.Right = GetVol32( value ); - break; + case REG_P_BVOLR: + thiscore.InpVol.Right = GetVol32(value); + break; - default: - { - const int raddr = addr + ((core==1) ? 0x28 : 0 ); - *(regtable[raddr>>1]) = value; - } - break; - } + default: { + const int raddr = addr + ((core == 1) ? 0x28 : 0); + *(regtable[raddr >> 1]) = value; + } break; + } } -template< int core, int addr > -static void __fastcall RegWrite_Reverb( u16 value ) +template +static void __fastcall RegWrite_Reverb(u16 value) { - // Signal to the Reverb code that the effects buffers need to be re-aligned. - // This is both simple, efficient, and safe, since we only want to re-align - // buffers after both hi and lo words have been written. + // Signal to the Reverb code that the effects buffers need to be re-aligned. + // This is both simple, efficient, and safe, since we only want to re-align + // buffers after both hi and lo words have been written. - // Update: This may have been written when it wasn't yet known that games - // have to disable the Reverb Engine to change settings. - // As such we only need to update buffers and parameters when we see - // the FxEnable bit go down, then high again. (rama) - *(regtable[addr>>1]) = value; - //Cores[core].RevBuffers.NeedsUpdated = true; // See update above + // Update: This may have been written when it wasn't yet known that games + // have to disable the Reverb Engine to change settings. + // As such we only need to update buffers and parameters when we see + // the FxEnable bit go down, then high again. (rama) + *(regtable[addr >> 1]) = value; + //Cores[core].RevBuffers.NeedsUpdated = true; // See update above } -template< int addr > -static void __fastcall RegWrite_SPDIF( u16 value ) +template +static void __fastcall RegWrite_SPDIF(u16 value) { - *(regtable[addr>>1]) = value; - UpdateSpdifMode(); + *(regtable[addr >> 1]) = value; + UpdateSpdifMode(); } -template< int addr > -static void __fastcall RegWrite_Raw( u16 value ) +template +static void __fastcall RegWrite_Raw(u16 value) { - *(regtable[addr>>1]) = value; + *(regtable[addr >> 1]) = value; } -static void __fastcall RegWrite_Null( u16 value ) +static void __fastcall RegWrite_Null(u16 value) { } // -------------------------------------------------------------------------------------- // Macros for tbl_reg_writes // -------------------------------------------------------------------------------------- -#define VoiceParamsSet( core, voice ) \ - RegWrite_VoiceParams, RegWrite_VoiceParams, \ - RegWrite_VoiceParams, RegWrite_VoiceParams, \ - RegWrite_VoiceParams, RegWrite_VoiceParams, \ - RegWrite_VoiceParams, RegWrite_VoiceParams +#define VoiceParamsSet(core, voice) \ + RegWrite_VoiceParams, RegWrite_VoiceParams, \ + RegWrite_VoiceParams, RegWrite_VoiceParams, \ + RegWrite_VoiceParams, RegWrite_VoiceParams, \ + RegWrite_VoiceParams, RegWrite_VoiceParams -#define VoiceParamsCore( core ) \ - VoiceParamsSet(core, 0), VoiceParamsSet(core, 1), VoiceParamsSet(core, 2), VoiceParamsSet(core, 3 ), \ - VoiceParamsSet(core, 4), VoiceParamsSet(core, 5), VoiceParamsSet(core, 6), VoiceParamsSet(core, 7 ), \ - VoiceParamsSet(core, 8), VoiceParamsSet(core, 9), VoiceParamsSet(core, 10),VoiceParamsSet(core, 11 ), \ - VoiceParamsSet(core, 12),VoiceParamsSet(core, 13),VoiceParamsSet(core, 14),VoiceParamsSet(core, 15 ), \ - VoiceParamsSet(core, 16),VoiceParamsSet(core, 17),VoiceParamsSet(core, 18),VoiceParamsSet(core, 19 ), \ - VoiceParamsSet(core, 20),VoiceParamsSet(core, 21),VoiceParamsSet(core, 22),VoiceParamsSet(core, 23 ) +#define VoiceParamsCore(core) \ + VoiceParamsSet(core, 0), VoiceParamsSet(core, 1), VoiceParamsSet(core, 2), VoiceParamsSet(core, 3), \ + VoiceParamsSet(core, 4), VoiceParamsSet(core, 5), VoiceParamsSet(core, 6), VoiceParamsSet(core, 7), \ + VoiceParamsSet(core, 8), VoiceParamsSet(core, 9), VoiceParamsSet(core, 10), VoiceParamsSet(core, 11), \ + VoiceParamsSet(core, 12), VoiceParamsSet(core, 13), VoiceParamsSet(core, 14), VoiceParamsSet(core, 15), \ + VoiceParamsSet(core, 16), VoiceParamsSet(core, 17), VoiceParamsSet(core, 18), VoiceParamsSet(core, 19), \ + VoiceParamsSet(core, 20), VoiceParamsSet(core, 21), VoiceParamsSet(core, 22), VoiceParamsSet(core, 23) -#define VoiceAddrSet( core, voice ) \ - RegWrite_VoiceAddr, RegWrite_VoiceAddr, \ - RegWrite_VoiceAddr, RegWrite_VoiceAddr, \ - RegWrite_VoiceAddr, RegWrite_VoiceAddr +#define VoiceAddrSet(core, voice) \ + RegWrite_VoiceAddr, RegWrite_VoiceAddr, \ + RegWrite_VoiceAddr, RegWrite_VoiceAddr, \ + RegWrite_VoiceAddr, RegWrite_VoiceAddr -#define CoreParamsPair( core, omem ) \ - RegWrite_Core, RegWrite_Core +#define CoreParamsPair(core, omem) \ + RegWrite_Core, RegWrite_Core -#define ReverbPair( core, mem ) \ - RegWrite_Reverb, RegWrite_Core +#define ReverbPair(core, mem) \ + RegWrite_Reverb, RegWrite_Core #define REGRAW(addr) RegWrite_Raw @@ -1457,286 +1514,288 @@ static void __fastcall RegWrite_Null( u16 value ) // tbl_reg_writes - Register Write Function Invocation LUT // -------------------------------------------------------------------------------------- -typedef void __fastcall RegWriteHandler( u16 value ); -static RegWriteHandler * const tbl_reg_writes[0x401] = -{ - VoiceParamsCore(0), // 0x000 -> 0x180 - CoreParamsPair(0,REG_S_PMON), - CoreParamsPair(0,REG_S_NON), - CoreParamsPair(0,REG_S_VMIXL), - CoreParamsPair(0,REG_S_VMIXEL), - CoreParamsPair(0,REG_S_VMIXR), - CoreParamsPair(0,REG_S_VMIXER), +typedef void __fastcall RegWriteHandler(u16 value); +static RegWriteHandler *const tbl_reg_writes[0x401] = + { + VoiceParamsCore(0), // 0x000 -> 0x180 + CoreParamsPair(0, REG_S_PMON), + CoreParamsPair(0, REG_S_NON), + CoreParamsPair(0, REG_S_VMIXL), + CoreParamsPair(0, REG_S_VMIXEL), + CoreParamsPair(0, REG_S_VMIXR), + CoreParamsPair(0, REG_S_VMIXER), - RegWrite_Core<0,REG_P_MMIX>, - RegWrite_Core<0,REG_C_ATTR>, + RegWrite_Core<0, REG_P_MMIX>, + RegWrite_Core<0, REG_C_ATTR>, - CoreParamsPair(0,REG_A_IRQA), - CoreParamsPair(0,REG_S_KON), - CoreParamsPair(0,REG_S_KOFF), - CoreParamsPair(0,REG_A_TSA), - CoreParamsPair(0,REG__1AC), + CoreParamsPair(0, REG_A_IRQA), + CoreParamsPair(0, REG_S_KON), + CoreParamsPair(0, REG_S_KOFF), + CoreParamsPair(0, REG_A_TSA), + CoreParamsPair(0, REG__1AC), - RegWrite_Core<0,REG_S_ADMAS>, - REGRAW(0x1b2), + RegWrite_Core<0, REG_S_ADMAS>, + REGRAW(0x1b2), - REGRAW(0x1b4), REGRAW(0x1b6), - REGRAW(0x1b8), REGRAW(0x1ba), - REGRAW(0x1bc), REGRAW(0x1be), + REGRAW(0x1b4), REGRAW(0x1b6), + REGRAW(0x1b8), REGRAW(0x1ba), + REGRAW(0x1bc), REGRAW(0x1be), - // 0x1c0! + // 0x1c0! - VoiceAddrSet(0, 0),VoiceAddrSet(0, 1),VoiceAddrSet(0, 2),VoiceAddrSet(0, 3),VoiceAddrSet(0, 4),VoiceAddrSet(0, 5), - VoiceAddrSet(0, 6),VoiceAddrSet(0, 7),VoiceAddrSet(0, 8),VoiceAddrSet(0, 9),VoiceAddrSet(0,10),VoiceAddrSet(0,11), - VoiceAddrSet(0,12),VoiceAddrSet(0,13),VoiceAddrSet(0,14),VoiceAddrSet(0,15),VoiceAddrSet(0,16),VoiceAddrSet(0,17), - VoiceAddrSet(0,18),VoiceAddrSet(0,19),VoiceAddrSet(0,20),VoiceAddrSet(0,21),VoiceAddrSet(0,22),VoiceAddrSet(0,23), + VoiceAddrSet(0, 0), VoiceAddrSet(0, 1), VoiceAddrSet(0, 2), VoiceAddrSet(0, 3), VoiceAddrSet(0, 4), VoiceAddrSet(0, 5), + VoiceAddrSet(0, 6), VoiceAddrSet(0, 7), VoiceAddrSet(0, 8), VoiceAddrSet(0, 9), VoiceAddrSet(0, 10), VoiceAddrSet(0, 11), + VoiceAddrSet(0, 12), VoiceAddrSet(0, 13), VoiceAddrSet(0, 14), VoiceAddrSet(0, 15), VoiceAddrSet(0, 16), VoiceAddrSet(0, 17), + VoiceAddrSet(0, 18), VoiceAddrSet(0, 19), VoiceAddrSet(0, 20), VoiceAddrSet(0, 21), VoiceAddrSet(0, 22), VoiceAddrSet(0, 23), - CoreParamsPair(0,REG_A_ESA), + CoreParamsPair(0, REG_A_ESA), - ReverbPair(0,R_FB_SRC_A), // 0x02E4 // Feedback Source A - ReverbPair(0,R_FB_SRC_B), // 0x02E8 // Feedback Source B - ReverbPair(0,R_IIR_DEST_A0), // 0x02EC - ReverbPair(0,R_IIR_DEST_A1), // 0x02F0 - ReverbPair(0,R_ACC_SRC_A0), // 0x02F4 - ReverbPair(0,R_ACC_SRC_A1), // 0x02F8 - ReverbPair(0,R_ACC_SRC_B0), // 0x02FC - ReverbPair(0,R_ACC_SRC_B1), // 0x0300 - ReverbPair(0,R_IIR_SRC_A0), // 0x0304 - ReverbPair(0,R_IIR_SRC_A1), // 0x0308 - ReverbPair(0,R_IIR_DEST_B0), // 0x030C - ReverbPair(0,R_IIR_DEST_B1), // 0x0310 - ReverbPair(0,R_ACC_SRC_C0), // 0x0314 - ReverbPair(0,R_ACC_SRC_C1), // 0x0318 - ReverbPair(0,R_ACC_SRC_D0), // 0x031C - ReverbPair(0,R_ACC_SRC_D1), // 0x0320 - ReverbPair(0,R_IIR_SRC_B0), // 0x0324 - ReverbPair(0,R_IIR_SRC_B1), // 0x0328 - ReverbPair(0,R_MIX_DEST_A0), // 0x032C - ReverbPair(0,R_MIX_DEST_A1), // 0x0330 - ReverbPair(0,R_MIX_DEST_B0), // 0x0334 - ReverbPair(0,R_MIX_DEST_B1), // 0x0338 + ReverbPair(0, R_FB_SRC_A), // 0x02E4 // Feedback Source A + ReverbPair(0, R_FB_SRC_B), // 0x02E8 // Feedback Source B + ReverbPair(0, R_IIR_DEST_A0), // 0x02EC + ReverbPair(0, R_IIR_DEST_A1), // 0x02F0 + ReverbPair(0, R_ACC_SRC_A0), // 0x02F4 + ReverbPair(0, R_ACC_SRC_A1), // 0x02F8 + ReverbPair(0, R_ACC_SRC_B0), // 0x02FC + ReverbPair(0, R_ACC_SRC_B1), // 0x0300 + ReverbPair(0, R_IIR_SRC_A0), // 0x0304 + ReverbPair(0, R_IIR_SRC_A1), // 0x0308 + ReverbPair(0, R_IIR_DEST_B0), // 0x030C + ReverbPair(0, R_IIR_DEST_B1), // 0x0310 + ReverbPair(0, R_ACC_SRC_C0), // 0x0314 + ReverbPair(0, R_ACC_SRC_C1), // 0x0318 + ReverbPair(0, R_ACC_SRC_D0), // 0x031C + ReverbPair(0, R_ACC_SRC_D1), // 0x0320 + ReverbPair(0, R_IIR_SRC_B0), // 0x0324 + ReverbPair(0, R_IIR_SRC_B1), // 0x0328 + ReverbPair(0, R_MIX_DEST_A0), // 0x032C + ReverbPair(0, R_MIX_DEST_A1), // 0x0330 + ReverbPair(0, R_MIX_DEST_B0), // 0x0334 + ReverbPair(0, R_MIX_DEST_B1), // 0x0338 - RegWrite_Core<0,REG_A_EEA>, RegWrite_Null, + RegWrite_Core<0, REG_A_EEA>, RegWrite_Null, - CoreParamsPair(0,REG_S_ENDX), // 0x0340 // End Point passed flag - RegWrite_Core<0,REG_P_STATX>, // 0x0344 // Status register? + CoreParamsPair(0, REG_S_ENDX), // 0x0340 // End Point passed flag + RegWrite_Core<0, REG_P_STATX>, // 0x0344 // Status register? - //0x346 here - REGRAW(0x346), - REGRAW(0x348),REGRAW(0x34A),REGRAW(0x34C),REGRAW(0x34E), - REGRAW(0x350),REGRAW(0x352),REGRAW(0x354),REGRAW(0x356), - REGRAW(0x358),REGRAW(0x35A),REGRAW(0x35C),REGRAW(0x35E), - REGRAW(0x360),REGRAW(0x362),REGRAW(0x364),REGRAW(0x366), - REGRAW(0x368),REGRAW(0x36A),REGRAW(0x36C),REGRAW(0x36E), - REGRAW(0x370),REGRAW(0x372),REGRAW(0x374),REGRAW(0x376), - REGRAW(0x378),REGRAW(0x37A),REGRAW(0x37C),REGRAW(0x37E), - REGRAW(0x380),REGRAW(0x382),REGRAW(0x384),REGRAW(0x386), - REGRAW(0x388),REGRAW(0x38A),REGRAW(0x38C),REGRAW(0x38E), - REGRAW(0x390),REGRAW(0x392),REGRAW(0x394),REGRAW(0x396), - REGRAW(0x398),REGRAW(0x39A),REGRAW(0x39C),REGRAW(0x39E), - REGRAW(0x3A0),REGRAW(0x3A2),REGRAW(0x3A4),REGRAW(0x3A6), - REGRAW(0x3A8),REGRAW(0x3AA),REGRAW(0x3AC),REGRAW(0x3AE), - REGRAW(0x3B0),REGRAW(0x3B2),REGRAW(0x3B4),REGRAW(0x3B6), - REGRAW(0x3B8),REGRAW(0x3BA),REGRAW(0x3BC),REGRAW(0x3BE), - REGRAW(0x3C0),REGRAW(0x3C2),REGRAW(0x3C4),REGRAW(0x3C6), - REGRAW(0x3C8),REGRAW(0x3CA),REGRAW(0x3CC),REGRAW(0x3CE), - REGRAW(0x3D0),REGRAW(0x3D2),REGRAW(0x3D4),REGRAW(0x3D6), - REGRAW(0x3D8),REGRAW(0x3DA),REGRAW(0x3DC),REGRAW(0x3DE), - REGRAW(0x3E0),REGRAW(0x3E2),REGRAW(0x3E4),REGRAW(0x3E6), - REGRAW(0x3E8),REGRAW(0x3EA),REGRAW(0x3EC),REGRAW(0x3EE), - REGRAW(0x3F0),REGRAW(0x3F2),REGRAW(0x3F4),REGRAW(0x3F6), - REGRAW(0x3F8),REGRAW(0x3FA),REGRAW(0x3FC),REGRAW(0x3FE), + //0x346 here + REGRAW(0x346), + REGRAW(0x348), REGRAW(0x34A), REGRAW(0x34C), REGRAW(0x34E), + REGRAW(0x350), REGRAW(0x352), REGRAW(0x354), REGRAW(0x356), + REGRAW(0x358), REGRAW(0x35A), REGRAW(0x35C), REGRAW(0x35E), + REGRAW(0x360), REGRAW(0x362), REGRAW(0x364), REGRAW(0x366), + REGRAW(0x368), REGRAW(0x36A), REGRAW(0x36C), REGRAW(0x36E), + REGRAW(0x370), REGRAW(0x372), REGRAW(0x374), REGRAW(0x376), + REGRAW(0x378), REGRAW(0x37A), REGRAW(0x37C), REGRAW(0x37E), + REGRAW(0x380), REGRAW(0x382), REGRAW(0x384), REGRAW(0x386), + REGRAW(0x388), REGRAW(0x38A), REGRAW(0x38C), REGRAW(0x38E), + REGRAW(0x390), REGRAW(0x392), REGRAW(0x394), REGRAW(0x396), + REGRAW(0x398), REGRAW(0x39A), REGRAW(0x39C), REGRAW(0x39E), + REGRAW(0x3A0), REGRAW(0x3A2), REGRAW(0x3A4), REGRAW(0x3A6), + REGRAW(0x3A8), REGRAW(0x3AA), REGRAW(0x3AC), REGRAW(0x3AE), + REGRAW(0x3B0), REGRAW(0x3B2), REGRAW(0x3B4), REGRAW(0x3B6), + REGRAW(0x3B8), REGRAW(0x3BA), REGRAW(0x3BC), REGRAW(0x3BE), + REGRAW(0x3C0), REGRAW(0x3C2), REGRAW(0x3C4), REGRAW(0x3C6), + REGRAW(0x3C8), REGRAW(0x3CA), REGRAW(0x3CC), REGRAW(0x3CE), + REGRAW(0x3D0), REGRAW(0x3D2), REGRAW(0x3D4), REGRAW(0x3D6), + REGRAW(0x3D8), REGRAW(0x3DA), REGRAW(0x3DC), REGRAW(0x3DE), + REGRAW(0x3E0), REGRAW(0x3E2), REGRAW(0x3E4), REGRAW(0x3E6), + REGRAW(0x3E8), REGRAW(0x3EA), REGRAW(0x3EC), REGRAW(0x3EE), + REGRAW(0x3F0), REGRAW(0x3F2), REGRAW(0x3F4), REGRAW(0x3F6), + REGRAW(0x3F8), REGRAW(0x3FA), REGRAW(0x3FC), REGRAW(0x3FE), - // AND... we reached 0x400! - // Last verse, same as the first: + // AND... we reached 0x400! + // Last verse, same as the first: - VoiceParamsCore(1), // 0x000 -> 0x180 - CoreParamsPair(1,REG_S_PMON), - CoreParamsPair(1,REG_S_NON), - CoreParamsPair(1,REG_S_VMIXL), - CoreParamsPair(1,REG_S_VMIXEL), - CoreParamsPair(1,REG_S_VMIXR), - CoreParamsPair(1,REG_S_VMIXER), + VoiceParamsCore(1), // 0x000 -> 0x180 + CoreParamsPair(1, REG_S_PMON), + CoreParamsPair(1, REG_S_NON), + CoreParamsPair(1, REG_S_VMIXL), + CoreParamsPair(1, REG_S_VMIXEL), + CoreParamsPair(1, REG_S_VMIXR), + CoreParamsPair(1, REG_S_VMIXER), - RegWrite_Core<1,REG_P_MMIX>, - RegWrite_Core<1,REG_C_ATTR>, + RegWrite_Core<1, REG_P_MMIX>, + RegWrite_Core<1, REG_C_ATTR>, - CoreParamsPair(1,REG_A_IRQA), - CoreParamsPair(1,REG_S_KON), - CoreParamsPair(1,REG_S_KOFF), - CoreParamsPair(1,REG_A_TSA), - CoreParamsPair(1,REG__1AC), + CoreParamsPair(1, REG_A_IRQA), + CoreParamsPair(1, REG_S_KON), + CoreParamsPair(1, REG_S_KOFF), + CoreParamsPair(1, REG_A_TSA), + CoreParamsPair(1, REG__1AC), - RegWrite_Core<1,REG_S_ADMAS>, - REGRAW(0x5b2), + RegWrite_Core<1, REG_S_ADMAS>, + REGRAW(0x5b2), - REGRAW(0x5b4), REGRAW(0x5b6), - REGRAW(0x5b8), REGRAW(0x5ba), - REGRAW(0x5bc), REGRAW(0x5be), + REGRAW(0x5b4), REGRAW(0x5b6), + REGRAW(0x5b8), REGRAW(0x5ba), + REGRAW(0x5bc), REGRAW(0x5be), - // 0x1c0! + // 0x1c0! - VoiceAddrSet(1, 0),VoiceAddrSet(1, 1),VoiceAddrSet(1, 2),VoiceAddrSet(1, 3),VoiceAddrSet(1, 4),VoiceAddrSet(1, 5), - VoiceAddrSet(1, 6),VoiceAddrSet(1, 7),VoiceAddrSet(1, 8),VoiceAddrSet(1, 9),VoiceAddrSet(1,10),VoiceAddrSet(1,11), - VoiceAddrSet(1,12),VoiceAddrSet(1,13),VoiceAddrSet(1,14),VoiceAddrSet(1,15),VoiceAddrSet(1,16),VoiceAddrSet(1,17), - VoiceAddrSet(1,18),VoiceAddrSet(1,19),VoiceAddrSet(1,20),VoiceAddrSet(1,21),VoiceAddrSet(1,22),VoiceAddrSet(1,23), + VoiceAddrSet(1, 0), VoiceAddrSet(1, 1), VoiceAddrSet(1, 2), VoiceAddrSet(1, 3), VoiceAddrSet(1, 4), VoiceAddrSet(1, 5), + VoiceAddrSet(1, 6), VoiceAddrSet(1, 7), VoiceAddrSet(1, 8), VoiceAddrSet(1, 9), VoiceAddrSet(1, 10), VoiceAddrSet(1, 11), + VoiceAddrSet(1, 12), VoiceAddrSet(1, 13), VoiceAddrSet(1, 14), VoiceAddrSet(1, 15), VoiceAddrSet(1, 16), VoiceAddrSet(1, 17), + VoiceAddrSet(1, 18), VoiceAddrSet(1, 19), VoiceAddrSet(1, 20), VoiceAddrSet(1, 21), VoiceAddrSet(1, 22), VoiceAddrSet(1, 23), - CoreParamsPair(1,REG_A_ESA), + CoreParamsPair(1, REG_A_ESA), - ReverbPair(1,R_FB_SRC_A), // 0x02E4 // Feedback Source A - ReverbPair(1,R_FB_SRC_B), // 0x02E8 // Feedback Source B - ReverbPair(1,R_IIR_DEST_A0), // 0x02EC - ReverbPair(1,R_IIR_DEST_A1), // 0x02F0 - ReverbPair(1,R_ACC_SRC_A0), // 0x02F4 - ReverbPair(1,R_ACC_SRC_A1), // 0x02F8 - ReverbPair(1,R_ACC_SRC_B0), // 0x02FC - ReverbPair(1,R_ACC_SRC_B1), // 0x0300 - ReverbPair(1,R_IIR_SRC_A0), // 0x0304 - ReverbPair(1,R_IIR_SRC_A1), // 0x0308 - ReverbPair(1,R_IIR_DEST_B0), // 0x030C - ReverbPair(1,R_IIR_DEST_B1), // 0x0310 - ReverbPair(1,R_ACC_SRC_C0), // 0x0314 - ReverbPair(1,R_ACC_SRC_C1), // 0x0318 - ReverbPair(1,R_ACC_SRC_D0), // 0x031C - ReverbPair(1,R_ACC_SRC_D1), // 0x0320 - ReverbPair(1,R_IIR_SRC_B0), // 0x0324 - ReverbPair(1,R_IIR_SRC_B1), // 0x0328 - ReverbPair(1,R_MIX_DEST_A0), // 0x032C - ReverbPair(1,R_MIX_DEST_A1), // 0x0330 - ReverbPair(1,R_MIX_DEST_B0), // 0x0334 - ReverbPair(1,R_MIX_DEST_B1), // 0x0338 + ReverbPair(1, R_FB_SRC_A), // 0x02E4 // Feedback Source A + ReverbPair(1, R_FB_SRC_B), // 0x02E8 // Feedback Source B + ReverbPair(1, R_IIR_DEST_A0), // 0x02EC + ReverbPair(1, R_IIR_DEST_A1), // 0x02F0 + ReverbPair(1, R_ACC_SRC_A0), // 0x02F4 + ReverbPair(1, R_ACC_SRC_A1), // 0x02F8 + ReverbPair(1, R_ACC_SRC_B0), // 0x02FC + ReverbPair(1, R_ACC_SRC_B1), // 0x0300 + ReverbPair(1, R_IIR_SRC_A0), // 0x0304 + ReverbPair(1, R_IIR_SRC_A1), // 0x0308 + ReverbPair(1, R_IIR_DEST_B0), // 0x030C + ReverbPair(1, R_IIR_DEST_B1), // 0x0310 + ReverbPair(1, R_ACC_SRC_C0), // 0x0314 + ReverbPair(1, R_ACC_SRC_C1), // 0x0318 + ReverbPair(1, R_ACC_SRC_D0), // 0x031C + ReverbPair(1, R_ACC_SRC_D1), // 0x0320 + ReverbPair(1, R_IIR_SRC_B0), // 0x0324 + ReverbPair(1, R_IIR_SRC_B1), // 0x0328 + ReverbPair(1, R_MIX_DEST_A0), // 0x032C + ReverbPair(1, R_MIX_DEST_A1), // 0x0330 + ReverbPair(1, R_MIX_DEST_B0), // 0x0334 + ReverbPair(1, R_MIX_DEST_B1), // 0x0338 - RegWrite_Core<1,REG_A_EEA>, RegWrite_Null, + RegWrite_Core<1, REG_A_EEA>, RegWrite_Null, - CoreParamsPair(1,REG_S_ENDX), // 0x0340 // End Point passed flag - RegWrite_Core<1,REG_P_STATX>, // 0x0344 // Status register? + CoreParamsPair(1, REG_S_ENDX), // 0x0340 // End Point passed flag + RegWrite_Core<1, REG_P_STATX>, // 0x0344 // Status register? - REGRAW(0x746), - REGRAW(0x748),REGRAW(0x74A),REGRAW(0x74C),REGRAW(0x74E), - REGRAW(0x750),REGRAW(0x752),REGRAW(0x754),REGRAW(0x756), - REGRAW(0x758),REGRAW(0x75A),REGRAW(0x75C),REGRAW(0x75E), + REGRAW(0x746), + REGRAW(0x748), REGRAW(0x74A), REGRAW(0x74C), REGRAW(0x74E), + REGRAW(0x750), REGRAW(0x752), REGRAW(0x754), REGRAW(0x756), + REGRAW(0x758), REGRAW(0x75A), REGRAW(0x75C), REGRAW(0x75E), - // ------ ------- + // ------ ------- - RegWrite_CoreExt<0,REG_P_MVOLL>, // 0x0760 // Master Volume Left - RegWrite_CoreExt<0,REG_P_MVOLR>, // 0x0762 // Master Volume Right - RegWrite_CoreExt<0,REG_P_EVOLL>, // 0x0764 // Effect Volume Left - RegWrite_CoreExt<0,REG_P_EVOLR>, // 0x0766 // Effect Volume Right - RegWrite_CoreExt<0,REG_P_AVOLL>, // 0x0768 // Core External Input Volume Left (Only Core 1) - RegWrite_CoreExt<0,REG_P_AVOLR>, // 0x076A // Core External Input Volume Right (Only Core 1) - RegWrite_CoreExt<0,REG_P_BVOLL>, // 0x076C // Sound Data Volume Left - RegWrite_CoreExt<0,REG_P_BVOLR>, // 0x076E // Sound Data Volume Right - RegWrite_CoreExt<0,REG_P_MVOLXL>, // 0x0770 // Current Master Volume Left - RegWrite_CoreExt<0,REG_P_MVOLXR>, // 0x0772 // Current Master Volume Right + RegWrite_CoreExt<0, REG_P_MVOLL>, // 0x0760 // Master Volume Left + RegWrite_CoreExt<0, REG_P_MVOLR>, // 0x0762 // Master Volume Right + RegWrite_CoreExt<0, REG_P_EVOLL>, // 0x0764 // Effect Volume Left + RegWrite_CoreExt<0, REG_P_EVOLR>, // 0x0766 // Effect Volume Right + RegWrite_CoreExt<0, REG_P_AVOLL>, // 0x0768 // Core External Input Volume Left (Only Core 1) + RegWrite_CoreExt<0, REG_P_AVOLR>, // 0x076A // Core External Input Volume Right (Only Core 1) + RegWrite_CoreExt<0, REG_P_BVOLL>, // 0x076C // Sound Data Volume Left + RegWrite_CoreExt<0, REG_P_BVOLR>, // 0x076E // Sound Data Volume Right + RegWrite_CoreExt<0, REG_P_MVOLXL>, // 0x0770 // Current Master Volume Left + RegWrite_CoreExt<0, REG_P_MVOLXR>, // 0x0772 // Current Master Volume Right - RegWrite_CoreExt<0,R_IIR_ALPHA>, // 0x0774 //IIR alpha (% used) - RegWrite_CoreExt<0,R_ACC_COEF_A>, // 0x0776 - RegWrite_CoreExt<0,R_ACC_COEF_B>, // 0x0778 - RegWrite_CoreExt<0,R_ACC_COEF_C>, // 0x077A - RegWrite_CoreExt<0,R_ACC_COEF_D>, // 0x077C - RegWrite_CoreExt<0,R_IIR_COEF>, // 0x077E - RegWrite_CoreExt<0,R_FB_ALPHA>, // 0x0780 //feedback alpha (% used) - RegWrite_CoreExt<0,R_FB_X>, // 0x0782 //feedback - RegWrite_CoreExt<0,R_IN_COEF_L>, // 0x0784 - RegWrite_CoreExt<0,R_IN_COEF_R>, // 0x0786 + RegWrite_CoreExt<0, R_IIR_ALPHA>, // 0x0774 //IIR alpha (% used) + RegWrite_CoreExt<0, R_ACC_COEF_A>, // 0x0776 + RegWrite_CoreExt<0, R_ACC_COEF_B>, // 0x0778 + RegWrite_CoreExt<0, R_ACC_COEF_C>, // 0x077A + RegWrite_CoreExt<0, R_ACC_COEF_D>, // 0x077C + RegWrite_CoreExt<0, R_IIR_COEF>, // 0x077E + RegWrite_CoreExt<0, R_FB_ALPHA>, // 0x0780 //feedback alpha (% used) + RegWrite_CoreExt<0, R_FB_X>, // 0x0782 //feedback + RegWrite_CoreExt<0, R_IN_COEF_L>, // 0x0784 + RegWrite_CoreExt<0, R_IN_COEF_R>, // 0x0786 - // ------ ------- + // ------ ------- - RegWrite_CoreExt<1,REG_P_MVOLL>, // 0x0788 // Master Volume Left - RegWrite_CoreExt<1,REG_P_MVOLR>, // 0x078A // Master Volume Right - RegWrite_CoreExt<1,REG_P_EVOLL>, // 0x0764 // Effect Volume Left - RegWrite_CoreExt<1,REG_P_EVOLR>, // 0x0766 // Effect Volume Right - RegWrite_CoreExt<1,REG_P_AVOLL>, // 0x0768 // Core External Input Volume Left (Only Core 1) - RegWrite_CoreExt<1,REG_P_AVOLR>, // 0x076A // Core External Input Volume Right (Only Core 1) - RegWrite_CoreExt<1,REG_P_BVOLL>, // 0x076C // Sound Data Volume Left - RegWrite_CoreExt<1,REG_P_BVOLR>, // 0x076E // Sound Data Volume Right - RegWrite_CoreExt<1,REG_P_MVOLXL>, // 0x0770 // Current Master Volume Left - RegWrite_CoreExt<1,REG_P_MVOLXR>, // 0x0772 // Current Master Volume Right + RegWrite_CoreExt<1, REG_P_MVOLL>, // 0x0788 // Master Volume Left + RegWrite_CoreExt<1, REG_P_MVOLR>, // 0x078A // Master Volume Right + RegWrite_CoreExt<1, REG_P_EVOLL>, // 0x0764 // Effect Volume Left + RegWrite_CoreExt<1, REG_P_EVOLR>, // 0x0766 // Effect Volume Right + RegWrite_CoreExt<1, REG_P_AVOLL>, // 0x0768 // Core External Input Volume Left (Only Core 1) + RegWrite_CoreExt<1, REG_P_AVOLR>, // 0x076A // Core External Input Volume Right (Only Core 1) + RegWrite_CoreExt<1, REG_P_BVOLL>, // 0x076C // Sound Data Volume Left + RegWrite_CoreExt<1, REG_P_BVOLR>, // 0x076E // Sound Data Volume Right + RegWrite_CoreExt<1, REG_P_MVOLXL>, // 0x0770 // Current Master Volume Left + RegWrite_CoreExt<1, REG_P_MVOLXR>, // 0x0772 // Current Master Volume Right - RegWrite_CoreExt<1,R_IIR_ALPHA>, // 0x0774 //IIR alpha (% used) - RegWrite_CoreExt<1,R_ACC_COEF_A>, // 0x0776 - RegWrite_CoreExt<1,R_ACC_COEF_B>, // 0x0778 - RegWrite_CoreExt<1,R_ACC_COEF_C>, // 0x077A - RegWrite_CoreExt<1,R_ACC_COEF_D>, // 0x077C - RegWrite_CoreExt<1,R_IIR_COEF>, // 0x077E - RegWrite_CoreExt<1,R_FB_ALPHA>, // 0x0780 //feedback alpha (% used) - RegWrite_CoreExt<1,R_FB_X>, // 0x0782 //feedback - RegWrite_CoreExt<1,R_IN_COEF_L>, // 0x0784 - RegWrite_CoreExt<1,R_IN_COEF_R>, // 0x0786 + RegWrite_CoreExt<1, R_IIR_ALPHA>, // 0x0774 //IIR alpha (% used) + RegWrite_CoreExt<1, R_ACC_COEF_A>, // 0x0776 + RegWrite_CoreExt<1, R_ACC_COEF_B>, // 0x0778 + RegWrite_CoreExt<1, R_ACC_COEF_C>, // 0x077A + RegWrite_CoreExt<1, R_ACC_COEF_D>, // 0x077C + RegWrite_CoreExt<1, R_IIR_COEF>, // 0x077E + RegWrite_CoreExt<1, R_FB_ALPHA>, // 0x0780 //feedback alpha (% used) + RegWrite_CoreExt<1, R_FB_X>, // 0x0782 //feedback + RegWrite_CoreExt<1, R_IN_COEF_L>, // 0x0784 + RegWrite_CoreExt<1, R_IN_COEF_R>, // 0x0786 - REGRAW(0x7B0),REGRAW(0x7B2),REGRAW(0x7B4),REGRAW(0x7B6), - REGRAW(0x7B8),REGRAW(0x7BA),REGRAW(0x7BC),REGRAW(0x7BE), + REGRAW(0x7B0), REGRAW(0x7B2), REGRAW(0x7B4), REGRAW(0x7B6), + REGRAW(0x7B8), REGRAW(0x7BA), REGRAW(0x7BC), REGRAW(0x7BE), - // SPDIF interface + // SPDIF interface - RegWrite_SPDIF, // 0x07C0 // SPDIF Out: OFF/'PCM'/Bitstream/Bypass - RegWrite_SPDIF, // 0x07C2 - REGRAW(0x7C4), - RegWrite_SPDIF, // 0x07C6 - RegWrite_SPDIF, // 0x07C8 // SPDIF Media: 'CD'/DVD - REGRAW(0x7CA), - RegWrite_SPDIF, // 0x07CC // SPDIF Copy Protection + RegWrite_SPDIF, // 0x07C0 // SPDIF Out: OFF/'PCM'/Bitstream/Bypass + RegWrite_SPDIF, // 0x07C2 + REGRAW(0x7C4), + RegWrite_SPDIF, // 0x07C6 + RegWrite_SPDIF, // 0x07C8 // SPDIF Media: 'CD'/DVD + REGRAW(0x7CA), + RegWrite_SPDIF, // 0x07CC // SPDIF Copy Protection - REGRAW(0x7CE), - REGRAW(0x7D0),REGRAW(0x7D2),REGRAW(0x7D4),REGRAW(0x7D6), - REGRAW(0x7D8),REGRAW(0x7DA),REGRAW(0x7DC),REGRAW(0x7DE), - REGRAW(0x7E0),REGRAW(0x7E2),REGRAW(0x7E4),REGRAW(0x7E6), - REGRAW(0x7E8),REGRAW(0x7EA),REGRAW(0x7EC),REGRAW(0x7EE), - REGRAW(0x7F0),REGRAW(0x7F2),REGRAW(0x7F4),REGRAW(0x7F6), - REGRAW(0x7F8),REGRAW(0x7FA),REGRAW(0x7FC),REGRAW(0x7FE), + REGRAW(0x7CE), + REGRAW(0x7D0), REGRAW(0x7D2), REGRAW(0x7D4), REGRAW(0x7D6), + REGRAW(0x7D8), REGRAW(0x7DA), REGRAW(0x7DC), REGRAW(0x7DE), + REGRAW(0x7E0), REGRAW(0x7E2), REGRAW(0x7E4), REGRAW(0x7E6), + REGRAW(0x7E8), REGRAW(0x7EA), REGRAW(0x7EC), REGRAW(0x7EE), + REGRAW(0x7F0), REGRAW(0x7F2), REGRAW(0x7F4), REGRAW(0x7F6), + REGRAW(0x7F8), REGRAW(0x7FA), REGRAW(0x7FC), REGRAW(0x7FE), - NULL // should be at 0x400! (we assert check it on startup) + NULL // should be at 0x400! (we assert check it on startup) }; -void SPU2_FastWrite( u32 rmem, u16 value ) +void SPU2_FastWrite(u32 rmem, u16 value) { - tbl_reg_writes[(rmem&0x7ff)/2]( value ); + tbl_reg_writes[(rmem & 0x7ff) / 2](value); } void StartVoices(int core, u32 value) { - // Optimization: Games like to write zero to the KeyOn reg a lot, so shortcut - // this loop if value is zero. + // Optimization: Games like to write zero to the KeyOn reg a lot, so shortcut + // this loop if value is zero. - if( value == 0 ) return; + if (value == 0) + return; - Cores[core].Regs.ENDX &= ~value; + Cores[core].Regs.ENDX &= ~value; - Cores[core].KeyOn |= value; + Cores[core].KeyOn |= value; - for( u8 vc=0; vc>vc) & 1) ) continue; + for (u8 vc = 0; vc < V_Core::NumVoices; vc++) { + if (!((value >> vc) & 1)) + continue; - Cores[core].Voices[vc].QueueStart(); + Cores[core].Voices[vc].QueueStart(); - if( IsDevBuild ) - { - V_Voice& thisvc( Cores[core].Voices[vc] ); + if (IsDevBuild) { + V_Voice &thisvc(Cores[core].Voices[vc]); - if(MsgKeyOnOff()) ConLog("* SPU2-X: KeyOn: C%dV%02d: SSA: %8x; M: %s%s%s%s; H: %04x; P: %04x V: %04x/%04x; ADSR: %04x%04x\n", - core,vc,thisvc.StartA, - (Cores[core].VoiceGates[vc].DryL)?"+":"-",(Cores[core].VoiceGates[vc].DryR)?"+":"-", - (Cores[core].VoiceGates[vc].WetL)?"+":"-",(Cores[core].VoiceGates[vc].WetR)?"+":"-", - *(u16*)GetMemPtr(thisvc.StartA), - thisvc.Pitch, - thisvc.Volume.Left.Value>>16,thisvc.Volume.Right.Value>>16, - thisvc.ADSR.regADSR1,thisvc.ADSR.regADSR2); - } - } + if (MsgKeyOnOff()) + ConLog("* SPU2-X: KeyOn: C%dV%02d: SSA: %8x; M: %s%s%s%s; H: %04x; P: %04x V: %04x/%04x; ADSR: %04x%04x\n", + core, vc, thisvc.StartA, + (Cores[core].VoiceGates[vc].DryL) ? "+" : "-", (Cores[core].VoiceGates[vc].DryR) ? "+" : "-", + (Cores[core].VoiceGates[vc].WetL) ? "+" : "-", (Cores[core].VoiceGates[vc].WetR) ? "+" : "-", + *(u16 *)GetMemPtr(thisvc.StartA), + thisvc.Pitch, + thisvc.Volume.Left.Value >> 16, thisvc.Volume.Right.Value >> 16, + thisvc.ADSR.regADSR1, thisvc.ADSR.regADSR2); + } + } } void StopVoices(int core, u32 value) { - if( value == 0 ) return; - for( u8 vc=0; vc>vc) & 1) ) continue; + if (value == 0) + return; + for (u8 vc = 0; vc < V_Core::NumVoices; vc++) { + if (!((value >> vc) & 1)) + continue; - Cores[core].Voices[vc].ADSR.Releasing = true; - if(MsgKeyOnOff()) ConLog("* SPU2-X: KeyOff: Core %d; Voice %d.\n",core,vc); - } + Cores[core].Voices[vc].ADSR.Releasing = true; + if (MsgKeyOnOff()) + ConLog("* SPU2-X: KeyOff: Core %d; Voice %d.\n", core, vc); + } } -