bsnes/ruby/audio/xaudio2.cpp

182 lines
5.3 KiB
C++
Raw Normal View History

#include "xaudio2.hpp"
#include <windows.h>
struct AudioXAudio2 : Audio, public IXAudio2VoiceCallback {
AudioXAudio2() { initialize(); }
~AudioXAudio2() { terminate(); }
Update to v104r06 release. byuu says: Changelog: - gba,ws: removed Thread::step() override¹ - processor/m68k: move.b (a7)+ and move.b (a7)- adjust a7 by two, not by one² - tomoko: created new initialize(Video,Audio,Input)Driver() functions³ - ruby/audio: split Audio::information into Audio::available(Devices,Frequencies,Latencies,Channels)³ - ws: added Model::(WonderSwan,WonderSwanColor,SwanCrystal)() functions for consistency with other cores ¹: this should hopefully fix GBA Pokemon Pinball. Thanks to SuperMikeMan for pointing out the underlying cause. ²: this fixes A Ressaha de Ikou, Mega Bomberman, and probably more games. ³: this is the big change: so there was a problem with WASAPI where you might change your device under the audio settings panel. And your new device may not support the frequency that your old device used. This would end up not updating the frequency, and the pitch would be distorted. The old Audio::information() couldn't tell you what frequencies, latencies, or channels were available for all devices simultaneously, so I had to split them up. The new initializeAudioDriver() function validates you have a correct driver, or it defaults to none. Then it validates a correct device name, or it defaults to the first entry in the list. Then it validates a correct frequency, or defaults to the first in the list. Then finally it validates a correct latency, or defaults to the first in the list. In this way ... we have a clear path now with no API changes required to select default devices, frequencies, latencies, channel counts: they need to be the first items in their respective lists. So, what we need to do now is go through and for every audio driver that enumerates devices, we need to make sure the default device gets added to the top of the list. I'm ... not really sure how to do this with most drivers, so this is definitely going to take some time. Also, when you change a device, initializeAudioDriver() is called again, so if it's a bad device, it will disable the audio driver instead of continuing to send samples at it and hoping that the driver blocked those API calls when it failed to initialize properly. Now then ... since it was a decently-sized API change, it's possible I've broken compilation of the Linux drivers, so please report any compilation errors so that I can fix them.
2017-08-26 01:15:49 +00:00
auto availableDevices() -> string_vector {
return {"Default"};
}
auto availableFrequencies() -> vector<double> {
return {44100.0, 48000.0, 96000.0};
}
Update to v104r06 release. byuu says: Changelog: - gba,ws: removed Thread::step() override¹ - processor/m68k: move.b (a7)+ and move.b (a7)- adjust a7 by two, not by one² - tomoko: created new initialize(Video,Audio,Input)Driver() functions³ - ruby/audio: split Audio::information into Audio::available(Devices,Frequencies,Latencies,Channels)³ - ws: added Model::(WonderSwan,WonderSwanColor,SwanCrystal)() functions for consistency with other cores ¹: this should hopefully fix GBA Pokemon Pinball. Thanks to SuperMikeMan for pointing out the underlying cause. ²: this fixes A Ressaha de Ikou, Mega Bomberman, and probably more games. ³: this is the big change: so there was a problem with WASAPI where you might change your device under the audio settings panel. And your new device may not support the frequency that your old device used. This would end up not updating the frequency, and the pitch would be distorted. The old Audio::information() couldn't tell you what frequencies, latencies, or channels were available for all devices simultaneously, so I had to split them up. The new initializeAudioDriver() function validates you have a correct driver, or it defaults to none. Then it validates a correct device name, or it defaults to the first entry in the list. Then it validates a correct frequency, or defaults to the first in the list. Then finally it validates a correct latency, or defaults to the first in the list. In this way ... we have a clear path now with no API changes required to select default devices, frequencies, latencies, channel counts: they need to be the first items in their respective lists. So, what we need to do now is go through and for every audio driver that enumerates devices, we need to make sure the default device gets added to the top of the list. I'm ... not really sure how to do this with most drivers, so this is definitely going to take some time. Also, when you change a device, initializeAudioDriver() is called again, so if it's a bad device, it will disable the audio driver instead of continuing to send samples at it and hoping that the driver blocked those API calls when it failed to initialize properly. Now then ... since it was a decently-sized API change, it's possible I've broken compilation of the Linux drivers, so please report any compilation errors so that I can fix them.
2017-08-26 01:15:49 +00:00
auto availableLatencies() -> vector<uint> {
return {20, 40, 60, 80, 100};
}
Update to v104r06 release. byuu says: Changelog: - gba,ws: removed Thread::step() override¹ - processor/m68k: move.b (a7)+ and move.b (a7)- adjust a7 by two, not by one² - tomoko: created new initialize(Video,Audio,Input)Driver() functions³ - ruby/audio: split Audio::information into Audio::available(Devices,Frequencies,Latencies,Channels)³ - ws: added Model::(WonderSwan,WonderSwanColor,SwanCrystal)() functions for consistency with other cores ¹: this should hopefully fix GBA Pokemon Pinball. Thanks to SuperMikeMan for pointing out the underlying cause. ²: this fixes A Ressaha de Ikou, Mega Bomberman, and probably more games. ³: this is the big change: so there was a problem with WASAPI where you might change your device under the audio settings panel. And your new device may not support the frequency that your old device used. This would end up not updating the frequency, and the pitch would be distorted. The old Audio::information() couldn't tell you what frequencies, latencies, or channels were available for all devices simultaneously, so I had to split them up. The new initializeAudioDriver() function validates you have a correct driver, or it defaults to none. Then it validates a correct device name, or it defaults to the first entry in the list. Then it validates a correct frequency, or defaults to the first in the list. Then finally it validates a correct latency, or defaults to the first in the list. In this way ... we have a clear path now with no API changes required to select default devices, frequencies, latencies, channel counts: they need to be the first items in their respective lists. So, what we need to do now is go through and for every audio driver that enumerates devices, we need to make sure the default device gets added to the top of the list. I'm ... not really sure how to do this with most drivers, so this is definitely going to take some time. Also, when you change a device, initializeAudioDriver() is called again, so if it's a bad device, it will disable the audio driver instead of continuing to send samples at it and hoping that the driver blocked those API calls when it failed to initialize properly. Now then ... since it was a decently-sized API change, it's possible I've broken compilation of the Linux drivers, so please report any compilation errors so that I can fix them.
2017-08-26 01:15:49 +00:00
auto availableChannels() -> vector<uint> {
return {2};
}
auto ready() -> bool { return _ready; }
auto blocking() -> bool { return _blocking; }
auto channels() -> uint { return _channels; }
auto frequency() -> double { return _frequency; }
auto latency() -> uint { return _latency; }
auto setBlocking(bool blocking) -> bool {
if(_blocking == blocking) return true;
_blocking = blocking;
return true;
}
auto setFrequency(double frequency) -> bool {
if(_frequency == frequency) return true;
_frequency = frequency;
return initialize();
}
auto setLatency(uint latency) -> bool {
if(_latency == latency) return true;
_latency = latency;
return initialize();
}
auto clear() -> void {
if(!_sourceVoice) return;
_sourceVoice->Stop(0);
_sourceVoice->FlushSourceBuffers(); //calls OnBufferEnd for all currently submitted buffers
_bufferIndex = 0;
_bufferOffset = 0;
if(_buffer) memory::fill(_buffer, _period * _bufferCount * sizeof(uint32_t));
_sourceVoice->Start(0);
}
auto output(const double samples[]) -> void {
Update to v105 release. byuu says: This release provides several major improvements to Mega Drive emulation which enhances compatibility a good deal. It also includes important Super Famicom mosaic emulation improvements, plus a much-needed SuperFX save state issue fix. Changelog (since v104): - higan: many improvements to Emulator::Interface to support forks/frontends - higan: refreshed program icon - icarus: new program icon - Game Boy Advance: slight emulation speedup over v104 - Game Boy Advance: synchronize APU FIFO updates better - Mega Drive: added automatic region detection [hex_usr] - Mega Drive: support 8-bit SRAM - Game Boy Advance: fixed bug when changing to THUMB mode via MSR [MerryMage] - Master System: fix bug in backdrop color and background 0 priority [hex_usr] - Mega Drive: backgrounds always update output priority bit [Cydrak] - Mega Drive: emulated interlaced video output - Mega Drive: emulated shadow/highlight mode [Cydrak] - Super Famicom: auto joypad polling clears the shift register when starting - Super Famicom: added new low-entropy RAM initialization mode to more closely match hardware - Game Boy Advance: rumble will now time out after being left on for 500ms - ruby: improved rumble support in udev input driver [ma_rysia] - M68K: `move.b (a7)[+/-]` adjust a7 by two - M68K: illegal/lineA/lineF opcodes do not modify the stack register - Mega Drive: emulate VIP status bit - uPD7725: improved emulation of OV1/S1 flags [byuu, AWJ, Lord Nightmare] - uPD7725: improved handling of DP, RP updates [Jonas Quinn] - Super Famicom: improved emulation of mosaic effects in hires, interlace, and offset-per-tile modes [byuu, Cydrak] - ruby: improved Direct3D exclusive mode monitor selection [Cydrak] - Super Famicom: fixed save state bug affecting SuperFX games [Cydrak] - Mega Drive: added workaround for Clang compiler bug; allowing this core to work on macOS [Cydrak, Sintendo] - higan: hotkeys now also trigger when the main window lacks focus yet higan is set to allow input on focus loss - higan: fixed an edge case where `int16_t` ↔ `double` audio conversion could possibly result in overflows - higan: fixed a crash on macOS when choosing quit from the application menu [ncbncb] Changelog (since the previous WIP): - higan: restored `make console=true` - tomoko: if you allow input when main window focus is lost, hotkeys can now be triggered without focus as well - hiro/cocoa: fix crash on exit from menu [ncbncb] - ruby: smarter `double` → `int16_t` conversion to prevent underflow/overflow
2017-10-07 07:28:12 +00:00
_buffer[_bufferIndex * _period + _bufferOffset] = (uint16_t)sclamp<16>(samples[0] * 32767.0) << 0;
_buffer[_bufferIndex * _period + _bufferOffset] |= (uint16_t)sclamp<16>(samples[1] * 32767.0) << 16;
if(++_bufferOffset < _period) return;
_bufferOffset = 0;
if(_bufferQueue == _bufferCount - 1) {
if(_blocking) {
//wait until there is at least one other free buffer for the next sample
while(_bufferQueue == _bufferCount - 1);
} else { //we need one free buffer for the next sample, so ignore the current contents
return;
}
}
pushBuffer(_period * 4, _buffer + _bufferIndex * _period);
_bufferIndex = (_bufferIndex + 1) % _bufferCount;
}
private:
auto initialize() -> bool {
terminate();
_bufferCount = 8;
_period = _frequency * _latency / _bufferCount / 1000.0 + 0.5;
_buffer = new uint32_t[_period * _bufferCount];
_bufferOffset = 0;
_bufferIndex = 0;
_bufferQueue = 0;
if(FAILED(XAudio2Create(&_interface, 0 , XAUDIO2_DEFAULT_PROCESSOR))) return false;
uint deviceCount = 0;
_interface->GetDeviceCount(&deviceCount);
if(deviceCount == 0) return terminate(), false;
uint deviceID = 0;
for(uint deviceIndex : range(deviceCount)) {
XAUDIO2_DEVICE_DETAILS deviceDetails = {};
_interface->GetDeviceDetails(deviceIndex, &deviceDetails);
if(deviceDetails.Role & DefaultGameDevice) deviceID = deviceIndex;
}
if(FAILED(_interface->CreateMasteringVoice(&_masterVoice, _channels, (uint)_frequency, 0, deviceID, nullptr))) return terminate(), false;
WAVEFORMATEX waveFormat;
waveFormat.wFormatTag = WAVE_FORMAT_PCM;
waveFormat.nChannels = _channels;
waveFormat.nSamplesPerSec = (uint)_frequency;
waveFormat.nBlockAlign = 4;
waveFormat.wBitsPerSample = 16;
waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign;
waveFormat.cbSize = 0;
if(FAILED(_interface->CreateSourceVoice(&_sourceVoice, (WAVEFORMATEX*)&waveFormat, XAUDIO2_VOICE_NOSRC, XAUDIO2_DEFAULT_FREQ_RATIO, this, nullptr, nullptr))) return terminate(), false;
clear();
return _ready = true;
}
auto terminate() -> void {
_ready = false;
if(_sourceVoice) {
_sourceVoice->Stop(0);
_sourceVoice->DestroyVoice();
_sourceVoice = nullptr;
}
if(_masterVoice) {
_masterVoice->DestroyVoice();
_masterVoice = nullptr;
}
if(_interface) {
_interface->Release();
_interface = nullptr;
}
delete[] _buffer;
_buffer = nullptr;
}
auto pushBuffer(uint bytes, uint32_t* _audioData) -> void {
XAUDIO2_BUFFER buffer = {};
buffer.AudioBytes = bytes;
buffer.pAudioData = reinterpret_cast<BYTE*>(_audioData);
buffer.pContext = 0;
InterlockedIncrement(&_bufferQueue);
_sourceVoice->SubmitSourceBuffer(&buffer);
}
bool _ready = false;
bool _blocking = true;
uint _channels = 2;
double _frequency = 48000.0;
uint _latency = 80;
uint32_t* _buffer = nullptr;
uint _period = 0;
uint _bufferCount = 0;
uint _bufferOffset = 0;
uint _bufferIndex = 0;
volatile long _bufferQueue = 0; //how many buffers are queued and ready for playback
IXAudio2* _interface = nullptr;
IXAudio2MasteringVoice* _masterVoice = nullptr;
IXAudio2SourceVoice* _sourceVoice = nullptr;
//inherited from IXAudio2VoiceCallback
STDMETHODIMP_(void) OnBufferStart(void* pBufferContext){}
STDMETHODIMP_(void) OnLoopEnd(void* pBufferContext){}
STDMETHODIMP_(void) OnStreamEnd() {}
STDMETHODIMP_(void) OnVoiceError(void* pBufferContext, HRESULT Error) {}
STDMETHODIMP_(void) OnVoiceProcessingPassEnd() {}
STDMETHODIMP_(void) OnVoiceProcessingPassStart(UINT32 BytesRequired) {}
STDMETHODIMP_(void) OnBufferEnd(void* pBufferContext) {
InterlockedDecrement(&_bufferQueue);
}
};