1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
|
// license:BSD-3-Clause
// copyright-holders:Brad Hughes
//====================================================================
//
// xaudio2_sound.cpp - XAudio2 implementation of MAME sound routines
//
//====================================================================
#include "sound_module.h"
#include "modules/osdmodule.h"
#if defined(OSD_WINDOWS)
// standard windows headers
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
// XAudio2 include
#include <xaudio2.h>
// stdlib includes
#include <mutex>
#include <thread>
#include <queue>
#undef interface
// MAME headers
#include "emu.h"
#include "osdepend.h"
#include "winutil.h"
//============================================================
// Constants
//============================================================
#define INITIAL_BUFFER_COUNT 4
#define SUBMIT_FREQUENCY_TARGET_MS 20
//============================================================
// Macros
//============================================================
// Check HRESULT result and log if error, then take an optional action on failure
#define HR_LOG( CALL, LOGFN, ONFAIL ) do { \
result = CALL; \
if (FAILED(result)) { \
LOGFN(#CALL " failed with error 0x%X\n", (unsigned int)result); \
ONFAIL; } \
} while (0)
// Variant of HR_LOG to log using osd_printf_error
#define HR_LOGE( CALL, ONFAIL ) HR_LOG(CALL, osd_printf_error, ONFAIL)
// Variant of HR_LOG to log using osd_printf_verbose
#define HR_LOGV( CALL, ONFAIL ) HR_LOG(CALL, osd_printf_verbose, ONFAIL)
// Macro to check for a failed HRESULT and if failed, goto a label called Error:
#define HR_GOERR( CALL ) HR_LOGE( CALL, goto Error;)
// Macro to check for a failed HRESULT and if failed, return the specified value
#define HR_RET( CALL, ret ) HR_LOGE(CALL, return ret;)
// Macro to check for a failed HRESULT and if failed, return nothing (void function)
#define HR_RETV( CALL ) HR_RET(CALL,)
// Macro to check for a failed HRESULT and if failed, return 0
#define HR_RET0( CALL ) HR_RET(CALL, 0)
// Macro to check for a failed HRESULT and if failed, return the HRESULT
#define HR_RETHR( CALL ) HR_RET(CALL, result)
// Macro to check for a failed HRESULT and if failed, return 1
#define HR_RET1( CALL ) HR_RET(CALL, 1)
// Macro to check for a failed HRESULT and if failed, log verbose, and proceed as normal
#define HR_IGNORE( CALL ) HR_LOGV(CALL,)
//============================================================
// Structs and typedefs
//============================================================
// A stucture to hold a pointer and the count of bytes of the data it points to
struct xaudio2_buffer
{
std::unique_ptr<BYTE[]> AudioData;
DWORD AudioSize;
};
// Custom deleter with overloads to free smart pointer types used in the implementations
struct xaudio2_custom_deleter
{
public:
void operator()(IXAudio2* obj) const
{
if (obj != nullptr)
{
obj->Release();
}
}
void operator()(IXAudio2MasteringVoice* obj) const
{
if (obj != nullptr)
{
obj->DestroyVoice();
}
}
void operator()(IXAudio2SourceVoice* obj) const
{
if (obj != nullptr)
{
obj->Stop(0);
obj->FlushSourceBuffers();
obj->DestroyVoice();
}
}
};
// Typedefs for smart pointers used with customer deleters
typedef std::unique_ptr<IXAudio2, xaudio2_custom_deleter> xaudio2_ptr;
typedef std::unique_ptr<IXAudio2MasteringVoice, xaudio2_custom_deleter> mastering_voice_ptr;
typedef std::unique_ptr<IXAudio2SourceVoice, xaudio2_custom_deleter> src_voice_ptr;
// Typedef for pointer to XAudio2Create
typedef lazy_loaded_function_p3<HRESULT, IXAudio2**, UINT32, XAUDIO2_PROCESSOR> xaudio2_create_ptr;
//============================================================
// Helper classes
//============================================================
// Provides a pool of buffers
class bufferpool
{
private:
int m_initial;
int m_buffersize;
std::queue<std::unique_ptr<BYTE[]>> m_queue;
public:
// constructor
bufferpool(int capacity, int bufferSize) :
m_initial(capacity),
m_buffersize(bufferSize)
{
for (int i = 0; i < m_initial; i++)
{
auto newBuffer = std::make_unique<BYTE[]>(m_buffersize);
memset(newBuffer.get(), 0, m_buffersize);
m_queue.push(std::move(newBuffer));
}
}
// get next buffer element from the pool
BYTE* next()
{
BYTE* next_buffer;
if (!m_queue.empty())
{
next_buffer = m_queue.front().release();
m_queue.pop();
}
else
{
next_buffer = new BYTE[m_buffersize];
memset(next_buffer, 0, m_buffersize);
}
return next_buffer;
}
// release element, make it available back in the pool
void return_to_pool(BYTE* buffer)
{
auto returned_buf = std::unique_ptr<BYTE[]>(buffer);
memset(returned_buf.get(), 0, m_buffersize);
m_queue.push(std::move(returned_buf));
}
};
//============================================================
// sound_xaudio2 class
//============================================================
// The main class for the XAudio2 sound module implementation
class sound_xaudio2 : public osd_module, public sound_module, public IXAudio2VoiceCallback
{
private:
const wchar_t* XAUDIO_DLLS[2] = { L"XAudio2_9.dll", L"XAudio2_8.dll" };
xaudio2_ptr m_xAudio2;
mastering_voice_ptr m_masterVoice;
src_voice_ptr m_sourceVoice;
DWORD m_sample_bytes;
std::unique_ptr<BYTE[]> m_buffer;
DWORD m_buffer_size;
DWORD m_buffer_count;
DWORD m_writepos;
std::mutex m_buffer_lock;
HANDLE m_hEventBufferCompleted;
HANDLE m_hEventDataAvailable;
HANDLE m_hEventExiting;
std::thread m_audioThread;
std::queue<xaudio2_buffer> m_queue;
std::unique_ptr<bufferpool> m_buffer_pool;
UINT32 m_overflows;
UINT32 m_underflows;
BOOL m_in_underflow;
xaudio2_create_ptr XAudio2Create;
public:
sound_xaudio2() :
osd_module(OSD_SOUND_PROVIDER, "xaudio2"),
sound_module(),
m_xAudio2(nullptr),
m_masterVoice(nullptr),
m_sourceVoice(nullptr),
m_sample_bytes(0),
m_buffer(nullptr),
m_buffer_size(0),
m_buffer_count(0),
m_writepos(0),
m_hEventBufferCompleted(nullptr),
m_hEventDataAvailable(nullptr),
m_hEventExiting(nullptr),
m_buffer_pool(nullptr),
m_overflows(0),
m_underflows(0),
m_in_underflow(FALSE),
XAudio2Create("XAudio2Create", XAUDIO_DLLS, ARRAY_LENGTH(XAUDIO_DLLS))
{
}
bool probe() override;
int init(osd_options const &options) override;
void exit() override;
// sound_module
void update_audio_stream(bool is_throttled, INT16 const *buffer, int samples_this_frame) override;
void set_mastervolume(int attenuation) override;
// Xaudio callbacks
void STDAPICALLTYPE OnVoiceProcessingPassStart(UINT32 bytes_required) override;
void STDAPICALLTYPE OnVoiceProcessingPassEnd() override {}
void STDAPICALLTYPE OnStreamEnd() override {}
void STDAPICALLTYPE OnBufferStart(void* pBufferContext) override {}
void STDAPICALLTYPE OnLoopEnd(void* pBufferContext) override {}
void STDAPICALLTYPE OnVoiceError(void* pBufferContext, HRESULT error) override {}
void STDAPICALLTYPE OnBufferEnd(void *pBufferContext) override;
private:
void create_buffers(const WAVEFORMATEX &format);
HRESULT create_voices(const WAVEFORMATEX &format);
void process_audio();
void submit_buffer(std::unique_ptr<BYTE[]> audioData, DWORD audioLength) const;
void submit_needed();
void roll_buffer();
BOOL submit_next_queued();
};
//============================================================
// probe
//============================================================
bool sound_xaudio2::probe()
{
int status = XAudio2Create.initialize();
return status == 0;
}
//============================================================
// init
//============================================================
int sound_xaudio2::init(osd_options const &options)
{
HRESULT result;
// Make sure our XAudio2Create entrypoint is bound
int status = XAudio2Create.initialize();
if (status != 0)
{
osd_printf_error("Could not find XAudio2 library\n");
return 1;
}
// Create the IXAudio2 object
IXAudio2 *temp_xaudio2 = nullptr;
HR_RET1(this->XAudio2Create(&temp_xaudio2, 0, XAUDIO2_DEFAULT_PROCESSOR));
m_xAudio2 = xaudio2_ptr(temp_xaudio2);
// make a format description for what we want
WAVEFORMATEX format = { 0 };
format.wBitsPerSample = 16;
format.wFormatTag = WAVE_FORMAT_PCM;
format.nChannels = 2;
format.nSamplesPerSec = sample_rate();
format.nBlockAlign = format.wBitsPerSample * format.nChannels / 8;
format.nAvgBytesPerSec = format.nSamplesPerSec * format.nBlockAlign;
m_sample_bytes = format.nBlockAlign;
// Create the buffers
create_buffers(format);
// Initialize our events
m_hEventBufferCompleted = CreateEvent(nullptr, FALSE, FALSE, nullptr);
m_hEventDataAvailable = CreateEvent(nullptr, FALSE, FALSE, nullptr);
m_hEventExiting = CreateEvent(nullptr, FALSE, FALSE, nullptr);
// create the voices and start them
HR_RET1(create_voices(format));
HR_RET1(m_sourceVoice->Start());
// Start the thread listening
m_audioThread = std::thread([](sound_xaudio2* self) { self->process_audio(); }, this);
osd_printf_verbose("Sound: XAudio2 initialized\n");
return 0;
}
//============================================================
// exit
//============================================================
void sound_xaudio2::exit()
{
// Wait on processing thread to end
SetEvent(m_hEventExiting);
m_audioThread.join();
CloseHandle(m_hEventBufferCompleted);
CloseHandle(m_hEventDataAvailable);
CloseHandle(m_hEventExiting);
m_sourceVoice.reset();
m_masterVoice.reset();
m_xAudio2.reset();
m_buffer.reset();
m_buffer_pool.reset();
if (m_overflows != 0 || m_underflows != 0)
osd_printf_verbose("Sound: overflows=%u, underflows=%u\n", m_overflows, m_underflows);
osd_printf_verbose("Sound: XAudio2 deinitialized\n");
}
//============================================================
// update_audio_stream
//============================================================
void sound_xaudio2::update_audio_stream(
bool is_throttled,
INT16 const *buffer,
int samples_this_frame)
{
if ((sample_rate() == 0) || !m_buffer)
return;
UINT32 const bytes_this_frame = samples_this_frame * m_sample_bytes;
std::lock_guard<std::mutex> lock(m_buffer_lock);
UINT32 bytes_left = bytes_this_frame;
while (bytes_left > 0)
{
UINT32 chunk = MIN(m_buffer_size, bytes_left);
// Roll the buffer if needed
if (m_writepos + chunk >= m_buffer_size)
{
roll_buffer();
}
// Copy in the data
memcpy(m_buffer.get() + m_writepos, buffer, chunk);
m_writepos += chunk;
bytes_left -= chunk;
}
// Signal data available
SetEvent(m_hEventDataAvailable);
}
//============================================================
// set_mastervolume
//============================================================
void sound_xaudio2::set_mastervolume(int attenuation)
{
assert(m_sourceVoice);
HRESULT result;
// clamp the attenuation to 0-32 range
attenuation = MAX(MIN(attenuation, 0), -32);
// Ranges from 1.0 to XAUDIO2_MAX_VOLUME_LEVEL indicate additional gain
// Ranges from 0 to 1.0 indicate a reduced volume level
// 0 indicates silence
// We only support a reduction from 1.0, so we generate values in the range 0.0 to 1.0
float scaledVolume = (32.0f + attenuation) / 32.0f;
// set the master volume
HR_RETV(m_sourceVoice->SetVolume(scaledVolume));
}
//============================================================
// IXAudio2VoiceCallback::OnBufferEnd
//============================================================
// The XAudio2 voice callback triggered when a buffer finishes playing
void sound_xaudio2::OnBufferEnd(void *pBufferContext)
{
BYTE* completed_buffer = static_cast<BYTE*>(pBufferContext);
if (completed_buffer != nullptr)
{
std::lock_guard<std::mutex> lock(m_buffer_lock);
m_buffer_pool->return_to_pool(completed_buffer);
}
SetEvent(m_hEventBufferCompleted);
}
//============================================================
// IXAudio2VoiceCallback::OnVoiceProcessingPassStart
//============================================================
// The XAudio2 voice callback triggered on every pass
void sound_xaudio2::OnVoiceProcessingPassStart(UINT32 bytes_required)
{
if (bytes_required == 0)
{
// Reset underflow indicator if we're caught up
if (m_in_underflow) m_in_underflow = FALSE;
return;
}
// Since there are bytes required, we're going to be in underflow
if (!m_in_underflow)
{
m_underflows++;
m_in_underflow = TRUE;
}
}
//============================================================
// create_buffers
//============================================================
void sound_xaudio2::create_buffers(const WAVEFORMATEX &format)
{
// Compute the buffer size
// buffer size is equal to the bytes we need to hold in memory per X tenths of a second where X is audio_latency
float audio_latency_in_seconds = m_audio_latency / 10.0f;
UINT32 format_bytes_per_second = format.nSamplesPerSec * format.nBlockAlign;
UINT32 total_buffer_size = format_bytes_per_second * audio_latency_in_seconds;
// We want to be able to submit buffers every X milliseconds
// I want to divide these up into "packets" so figure out how many buffers we need
m_buffer_count = (audio_latency_in_seconds * 1000.0f) / SUBMIT_FREQUENCY_TARGET_MS;
// Now record the size of the individual buffers
m_buffer_size = MAX(1024, total_buffer_size / m_buffer_count);
// Make the buffer a multiple of the format size bytes (rounding up)
UINT32 remainder = m_buffer_size % format.nBlockAlign;
if (remainder != 0)
m_buffer_size += format.nBlockAlign - remainder;
// get our initial buffer pool and our first buffer
m_buffer_pool = std::make_unique<bufferpool>(m_buffer_count + 1, m_buffer_size);
m_buffer = std::unique_ptr<BYTE[]>(m_buffer_pool->next());
osd_printf_verbose(
"Sound: XAudio2 created initial buffers. total size: %u, count %u, size each %u\n",
static_cast<unsigned int>(total_buffer_size),
static_cast<unsigned int>(m_buffer_count),
static_cast<unsigned int>(m_buffer_size));
// reset buffer states
m_writepos = 0;
m_overflows = 0;
m_underflows = 0;
}
//============================================================
// create_voices
//============================================================
HRESULT sound_xaudio2::create_voices(const WAVEFORMATEX &format)
{
assert(m_xAudio2);
assert(!m_masterVoice);
HRESULT result;
IXAudio2MasteringVoice *temp_master_voice = nullptr;
HR_RET1(
m_xAudio2->CreateMasteringVoice(
&temp_master_voice,
format.nChannels,
sample_rate()));
m_masterVoice = mastering_voice_ptr(temp_master_voice);
// create the source voice
IXAudio2SourceVoice *temp_source_voice = nullptr;
HR_RET1(m_xAudio2->CreateSourceVoice(
&temp_source_voice,
&format,
XAUDIO2_VOICE_NOSRC | XAUDIO2_VOICE_NOPITCH,
1.0,
this));
m_sourceVoice = src_voice_ptr(temp_source_voice);
return S_OK;
}
//============================================================
// process_audio
//============================================================
// submits audio events on another thread in a loop
void sound_xaudio2::process_audio()
{
BOOL exiting = FALSE;
HANDLE hEvents[] = { m_hEventBufferCompleted, m_hEventDataAvailable, m_hEventExiting };
while (!exiting)
{
DWORD wait_result = WaitForMultipleObjects(3, hEvents, FALSE, INFINITE);
switch (wait_result)
{
// Buffer is complete or new data is available
case 0:
case 1:
submit_needed();
break;
case 2:
// exiting
exiting = TRUE;
break;
}
}
}
//============================================================
// submit_needed
//============================================================
// Submits any buffers that have currently been queued,
// assuming they are needed based on current queue depth
void sound_xaudio2::submit_needed()
{
XAUDIO2_VOICE_STATE state;
m_sourceVoice->GetState(&state, XAUDIO2_VOICE_NOSAMPLESPLAYED);
// If we have a buffer on the queue, no reason to submit
if (state.BuffersQueued >= 1)
return;
std::lock_guard<std::mutex> lock(m_buffer_lock);
// Roll the buffer
roll_buffer();
// Submit the next buffer
submit_next_queued();
}
//============================================================
// submit_buffer
//============================================================
void sound_xaudio2::submit_buffer(std::unique_ptr<BYTE[]> audioData, DWORD audioLength) const
{
assert(audioLength != 0);
XAUDIO2_BUFFER buf = { 0 };
buf.AudioBytes = audioLength;
buf.pAudioData = audioData.get();
buf.PlayBegin = 0;
buf.PlayLength = audioLength / m_sample_bytes;
buf.Flags = XAUDIO2_END_OF_STREAM;
buf.pContext = audioData.get();
HRESULT result;
if (FAILED(result = m_sourceVoice->SubmitSourceBuffer(&buf)))
{
osd_printf_verbose("Sound: XAudio2 failed to submit source buffer (non-fatal). Error: 0x%X\n", static_cast<unsigned int>(result));
m_buffer_pool->return_to_pool(audioData.release());
return;
}
// If we succeeded, relinquish the buffer allocation to the XAudio2 runtime
// The buffer will be freed on the OnBufferCompleted callback
audioData.release();
}
//============================================================
// submit_next_queued
//============================================================
BOOL sound_xaudio2::submit_next_queued()
{
if (!m_queue.empty())
{
// Get a reference to the buffer
auto buf = &m_queue.front();
// submit the buffer data
submit_buffer(std::move(buf->AudioData), buf->AudioSize);
// Remove it from the queue
assert(buf->AudioSize > 0);
m_queue.pop();
return !m_queue.empty();
}
// queue was already empty
return FALSE;
}
//============================================================
// roll_buffer
//============================================================
// Queues the current buffer, and gets a new write buffer
void sound_xaudio2::roll_buffer()
{
// Don't queue a buffer if it is empty
if (m_writepos == 0)
return;
// Queue the current buffer
xaudio2_buffer buf;
buf.AudioData = std::move(m_buffer);
buf.AudioSize = m_writepos;
m_queue.push(std::move(buf));
// Get a new buffer
m_buffer = std::unique_ptr<BYTE[]>(m_buffer_pool->next());
m_writepos = 0;
// We only want to keep a maximum number of buffers at any given time
// so remove any from queue greater than MAX_QUEUED_BUFFERS
if (m_queue.size() > m_buffer_count)
{
xaudio2_buffer *next_buffer = &m_queue.front();
// return the oldest buffer to the pool, and remove it from queue
m_buffer_pool->return_to_pool(next_buffer->AudioData.release());
m_queue.pop();
m_overflows++;
}
}
#else
MODULE_NOT_SUPPORTED(sound_xaudio2, OSD_SOUND_PROVIDER, "xaudio2")
#endif
MODULE_DEFINITION(SOUND_XAUDIO2, sound_xaudio2)
|