OpenTTD Source 20260109-master-g241b5fcdfe
xaudio2_s.cpp
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
10#include "../stdafx.h"
11#include "../openttd.h"
12#include "../driver.h"
13#include "../mixer.h"
14#include "../debug.h"
15#include "../core/bitmath_func.hpp"
16#include "../core/math_func.hpp"
17
18/* Windows 8 SDK required for XAudio2 */
19#undef NTDDI_VERSION
20#undef _WIN32_WINNT
21
22#define NTDDI_VERSION NTDDI_WIN8
23#define _WIN32_WINNT _WIN32_WINNT_WIN8
24
25#include "xaudio2_s.h"
26
27#include <windows.h>
28#include <mmsystem.h>
29#include <wrl\client.h>
30#include <xaudio2.h>
31
32using Microsoft::WRL::ComPtr;
33
34#include "../os/windows/win32.h"
35#include "../safeguards.h"
36
37/* Definition of the "XAudio2Create" call used to initialise XAudio2 */
38typedef HRESULT(__stdcall *API_XAudio2Create)(_Outptr_ IXAudio2 **ppXAudio2, UINT32 Flags, XAUDIO2_PROCESSOR XAudio2Processor);
39
40static FSoundDriver_XAudio2 iFSoundDriver_XAudio2;
41
46class StreamingVoiceContext : public IXAudio2VoiceCallback
47{
48private:
49 std::vector<BYTE> buffer;
50
51public:
52 IXAudio2SourceVoice *source_voice = nullptr;
53
54 StreamingVoiceContext(int buffer_length)
55 {
56 this->buffer.resize(buffer_length);
57 }
58
59 /* This needs to be virtual because the XAudio2 API declares the interface without
60 * a virtual destructor, even though it has functions that need to be overridden. */
61 virtual ~StreamingVoiceContext() = default;
62
63 HRESULT SubmitBuffer()
64 {
65 /* Ensure we do have a valid voice */
66 if (this->source_voice == nullptr) {
67 return E_FAIL;
68 }
69
70 MxMixSamples(this->buffer.data(), static_cast<uint>(this->buffer.size() / 4));
71
72 XAUDIO2_BUFFER buf = { 0 };
73 buf.AudioBytes = static_cast<UINT32>(this->buffer.size());
74 buf.pAudioData = this->buffer.data();
75
76 return source_voice->SubmitSourceBuffer(&buf);
77 }
78
79 STDMETHOD_(void, OnVoiceProcessingPassStart)(UINT32) override
80 {
81 }
82
83 STDMETHOD_(void, OnVoiceProcessingPassEnd)() override
84 {
85 }
86
87 STDMETHOD_(void, OnStreamEnd)() override
88 {
89 }
90
91 STDMETHOD_(void, OnBufferStart)(void*) override
92 {
93 }
94
95 STDMETHOD_(void, OnBufferEnd)(void*) override
96 {
97 SubmitBuffer();
98 }
99
100 STDMETHOD_(void, OnLoopEnd)(void*) override
101 {
102 }
103
104 STDMETHOD_(void, OnVoiceError)(void*, HRESULT) override
105 {
106 }
107};
108
109static HMODULE _xaudio_dll_handle;
110static IXAudio2SourceVoice *_source_voice = nullptr;
111static IXAudio2MasteringVoice *_mastering_voice = nullptr;
112static ComPtr<IXAudio2> _xaudio2;
113static std::unique_ptr<StreamingVoiceContext> _voice_context;
114
116static HRESULT CreateXAudio(API_XAudio2Create xAudio2Create)
117{
118 HRESULT hr;
119 __try {
120 UINT32 flags = 0;
121 hr = xAudio2Create(_xaudio2.GetAddressOf(), flags, XAUDIO2_DEFAULT_PROCESSOR);
122 } __except (EXCEPTION_EXECUTE_HANDLER) {
123 hr = GetExceptionCode();
124 }
125
126 return hr;
127}
128
136std::optional<std::string_view> SoundDriver_XAudio2::Start(const StringList &parm)
137{
138 HRESULT hr = CoInitializeEx(nullptr, COINIT_MULTITHREADED);
139
140 if (FAILED(hr)) {
141 Debug(driver, 0, "xaudio2_s: CoInitializeEx failed ({:08x})", (uint)hr);
142 return "Failed to initialise COM";
143 }
144
145 _xaudio_dll_handle = LoadLibraryA(XAUDIO2_DLL_A);
146
147 if (_xaudio_dll_handle == nullptr) {
148 CoUninitialize();
149
150 Debug(driver, 0, "xaudio2_s: Unable to load " XAUDIO2_DLL_A);
151 return "Failed to load XAudio2 DLL";
152 }
153
154 API_XAudio2Create xAudio2Create = (API_XAudio2Create) GetProcAddress(_xaudio_dll_handle, "XAudio2Create");
155
156 if (xAudio2Create == nullptr) {
157 FreeLibrary(_xaudio_dll_handle);
158 CoUninitialize();
159
160 Debug(driver, 0, "xaudio2_s: Unable to find XAudio2Create function in DLL");
161 return "Failed to load XAudio2 DLL";
162 }
163
164 /* Create the XAudio engine */
165 hr = CreateXAudio(xAudio2Create);
166
167 if (FAILED(hr)) {
168 FreeLibrary(_xaudio_dll_handle);
169 CoUninitialize();
170
171 Debug(driver, 0, "xaudio2_s: XAudio2Create failed ({:08x})", (uint)hr);
172 return "Failed to initialise the XAudio2 engine";
173 }
174
175 /* Create a mastering voice */
176 hr = _xaudio2->CreateMasteringVoice(&_mastering_voice);
177
178 if (FAILED(hr)) {
179 _xaudio2.Reset();
180 FreeLibrary(_xaudio_dll_handle);
181 CoUninitialize();
182
183 Debug(driver, 0, "xaudio2_s: CreateMasteringVoice failed ({:08x})", (uint)hr);
184 return "Failed to create a mastering voice";
185 }
186
187 /* Create a source voice to stream our audio */
188 WAVEFORMATEX wfex;
189
190 wfex.wFormatTag = WAVE_FORMAT_PCM;
191 wfex.nChannels = 2;
192 wfex.wBitsPerSample = 16;
193 wfex.nSamplesPerSec = GetDriverParamInt(parm, "hz", 44100);
194 wfex.nBlockAlign = (wfex.nChannels * wfex.wBitsPerSample) / 8;
195 wfex.nAvgBytesPerSec = wfex.nSamplesPerSec * wfex.nBlockAlign;
196
197 /* Limit buffer size to prevent overflows */
198 int bufsize = GetDriverParamInt(parm, "samples", 1024);
199 bufsize = std::min<int>(bufsize, UINT16_MAX);
200
201 _voice_context = std::make_unique<StreamingVoiceContext>(bufsize * 4);
202
203 if (_voice_context == nullptr) {
204 _mastering_voice->DestroyVoice();
205 _xaudio2.Reset();
206 FreeLibrary(_xaudio_dll_handle);
207 CoUninitialize();
208
209 return "Failed to create streaming voice context";
210 }
211
212 hr = _xaudio2->CreateSourceVoice(&_source_voice, &wfex, 0, 1.0f, _voice_context.get());
213
214 if (FAILED(hr)) {
215 _mastering_voice->DestroyVoice();
216 _xaudio2.Reset();
217 FreeLibrary(_xaudio_dll_handle);
218 CoUninitialize();
219
220 Debug(driver, 0, "xaudio2_s: CreateSourceVoice failed ({:08x})", (uint)hr);
221 return "Failed to create a source voice";
222 }
223
224 _voice_context->source_voice = _source_voice;
225 hr = _source_voice->Start(0, 0);
226
227 if (FAILED(hr)) {
228 Debug(driver, 0, "xaudio2_s: _source_voice->Start failed ({:08x})", (uint)hr);
229
230 Stop();
231 return "Failed to start the source voice";
232 }
233
234 MxInitialize(wfex.nSamplesPerSec);
235
236 /* Submit the first buffer */
237 hr = _voice_context->SubmitBuffer();
238
239 if (FAILED(hr)) {
240 Debug(driver, 0, "xaudio2_s: _voice_context->SubmitBuffer failed ({:08x})", (uint)hr);
241
242 Stop();
243 return "Failed to submit the first audio buffer";
244 }
245
246 return std::nullopt;
247}
248
253{
254 /* Clean up XAudio2 */
255 _source_voice->DestroyVoice();
256
257 _voice_context = nullptr;
258
259 _mastering_voice->DestroyVoice();
260
261 _xaudio2.Reset();
262
263 FreeLibrary(_xaudio_dll_handle);
264 CoUninitialize();
265}
Factory for the XAudio2 sound driver.
Definition xaudio2_s.h:25
std::optional< std::string_view > Start(const StringList &param) override
Initialises the XAudio2 driver.
void Stop() override
Terminates the XAudio2 driver.
Implementation of the IXAudio2VoiceCallback interface.
Definition xaudio2_s.cpp:47
#define Debug(category, level, format_string,...)
Output a line of debugging information.
Definition debug.h:37
int GetDriverParamInt(const StringList &parm, std::string_view name, int def)
Get an integer parameter the list of parameters.
Definition driver.cpp:79
std::vector< std::string > StringList
Type for a list of strings.
Definition string_type.h:60
static HRESULT CreateXAudio(API_XAudio2Create xAudio2Create)
Create XAudio2 context with SEH exception checking.
Base for XAudio2 sound handling.