-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAudioPlayer.cpp
556 lines (462 loc) · 10.2 KB
/
AudioPlayer.cpp
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
#include "stdafx.h"
#include "AudioPlayer.h"
#pragma comment(lib, "Winmm.lib")
using namespace local_utils;
////////////////////////////////////////////////////////////////
// CWaveQueueItem
class CWaveQueueItem
{
public:
CWaveQueueItem()
{
m_nLen = 0;
InitNew();
}
inline bool IsPlayed() const
{
return m_bPlayed;
}
inline bool IsDone() const
{
return m_WaveHeader.dwFlags & WHDR_DONE ? true : false;
}
inline void InitNew()
{
memset(&m_WaveHeader, 0, sizeof(m_WaveHeader));
m_bPlayed = false;
}
bool Prepare(HWAVEOUT hWaveOut);
void UnPrepare(HWAVEOUT hWaveOut);
bool Play(HWAVEOUT hWaveOut);
void WaitIfPlayed();
void Mute();
public:
CTempBuffer<uint8_t> m_Blob;
ULONG m_nLen;
private:
WAVEHDR m_WaveHeader;
bool m_bPlayed;
};
///////////////////////////////////////////////////////////
// CWavePlayThread
class CWavePlayThread : protected CMyThread
{
public:
typedef std::function<void(uint8_t* pStream, ULONG dwLen)> callback_t;
CWavePlayThread(UINT nDeviceID = WAVE_MAPPER);
~CWavePlayThread();
void Init(ULONG nFreq = (ULONG)SAMPLE_FREQ, ULONG nChannels = NUM_CHANNELS, ULONG nSampleSizeBits = SAMPLE_SIZE);
bool Start(callback_t callback, size_t nThreshold = 16);
void Stop();
void Pause();
inline bool IsPaused() const
{
return m_bPaused;
}
void Mute(bool bMute);
inline bool IsMuted() const
{
return m_bMuted;
}
void SetVolume(WORD wVolume);
WORD GetVolume();
private:
bool Alloc(std::shared_ptr<CWaveQueueItem>& pItem);
void Free(std::shared_ptr<CWaveQueueItem>& pItem);
protected:
virtual bool OnStart();
virtual void OnStop();
virtual void OnEvent();
protected:
HWAVEOUT m_hWaveOut;
typedef CMyQueue< std::shared_ptr<CWaveQueueItem>, CDummyLock > CWaveQueueItemList;
CWaveQueueItemList m_Queue;
CWaveQueueItemList m_Pool;
CHandle m_hStarted;
UINT m_nDeviceID;
size_t m_nThreshold;
volatile bool m_bPaused;
volatile bool m_bMuted;
callback_t m_callback;
public:
WAVEFORMATEX m_format;
UINT m_nRealDeviceID;
};
/////////////////////////////////////////////////////////////////////////////////
// CWaveQueueItem
bool CWaveQueueItem::Prepare(HWAVEOUT hWaveOut)
{
bool bResult = true;
if ((m_WaveHeader.dwFlags & WHDR_PREPARED) == 0)
{
m_WaveHeader.dwBufferLength = m_nLen;
m_WaveHeader.lpData = (LPSTR)(uint8_t*) m_Blob;
if (MMSYSERR_NOERROR != waveOutPrepareHeader(hWaveOut, &m_WaveHeader, sizeof(m_WaveHeader)))
{
bResult = false;
memset(&m_WaveHeader, 0, sizeof(m_WaveHeader));
}
}
else
{
m_WaveHeader.dwBufferLength = m_nLen;
}
m_bPlayed = false;
return bResult;
}
void CWaveQueueItem::UnPrepare(HWAVEOUT hWaveOut)
{
if (m_WaveHeader.dwFlags & WHDR_PREPARED)
{
while (waveOutUnprepareHeader(hWaveOut, &m_WaveHeader, sizeof(m_WaveHeader)) != MMSYSERR_NOERROR)
Sleep(10);
InitNew();
}
}
bool CWaveQueueItem::Play(HWAVEOUT hWaveOut)
{
m_WaveHeader.dwFlags &= ~WHDR_DONE;
if (waveOutWrite(hWaveOut, &m_WaveHeader, sizeof(WAVEHDR)) == MMSYSERR_NOERROR)
{
m_bPlayed = true;
return true;
}
return false;
}
void CWaveQueueItem::WaitIfPlayed()
{
if (m_bPlayed)
{
while (!(m_WaveHeader.dwFlags & WHDR_DONE))
{
Sleep(10);
}
}
}
void CWaveQueueItem::Mute()
{
memset(m_Blob, 0, m_nLen);
}
/////////////////////////////////////////////////////////////////////////////////
// CWavePlayThread
CWavePlayThread::CWavePlayThread(UINT nDeviceID /*= WAVE_MAPPER*/)
{
m_hWaveOut = NULL;
m_nDeviceID = nDeviceID;
m_nRealDeviceID = 0;
m_nThreshold = 16;
Init();
m_bPaused = false;
m_bMuted = false;
}
CWavePlayThread::~CWavePlayThread()
{
Stop();
}
void CWavePlayThread::Init(ULONG nFreq /*= 44100*/, ULONG nChannels /*= 2*/, ULONG nSampleSizeBits /*= 16*/)
{
memset(&m_format, 0, sizeof(m_format));
m_format.cbSize = 0;
m_format.wFormatTag = WAVE_FORMAT_PCM;
m_format.nSamplesPerSec = nFreq;
m_format.nChannels = (WORD) nChannels;
m_format.wBitsPerSample = (WORD) nSampleSizeBits;
m_format.nBlockAlign = (WORD) (nChannels * (nSampleSizeBits >> 3));
m_format.nAvgBytesPerSec = nFreq * m_format.nBlockAlign;
m_Pool.clear();
}
bool CWavePlayThread::Alloc(std::shared_ptr<CWaveQueueItem>& pItem)
{
if (pItem)
pItem.reset();
m_Pool.unqueue(pItem);
if (!pItem)
{
pItem = std::make_shared<CWaveQueueItem>();
if (!pItem)
return false;
pItem->m_nLen = 4096;
if (!pItem->m_Blob.Allocate(pItem->m_nLen))
return false;
}
memset(pItem->m_Blob, 0, pItem->m_nLen);
return true;
}
void CWavePlayThread::Free(std::shared_ptr<CWaveQueueItem>& pItem)
{
ATLASSERT(pItem);
pItem->InitNew();
m_Pool.queue(move(pItem));
ATLASSERT(!pItem);
}
bool CWavePlayThread::Start(callback_t callback, size_t nThreshold /*= 16*/)
{
if (IsRunning())
return true;
bool bResult = false;
m_nThreshold = nThreshold;
m_callback = callback;
ATLASSERT(m_callback);
// create a manual reset event
ATLASSERT(!m_hStarted);
m_hStarted.Attach(::CreateEvent(NULL, TRUE, FALSE, NULL));
HANDLE hEvent = ::CreateEvent(NULL, TRUE, FALSE, NULL);
if (__super::Start(hEvent))
{
// sync with OnStart
::WaitForSingleObject(m_hStarted, INFINITE);
// succeeded?
bResult = m_hWaveOut != NULL ? true : false;
if (!bResult)
Stop();
}
m_hStarted.Close();
CloseHandle(hEvent);
return bResult;
}
void CWavePlayThread::Stop()
{
__super::Stop();
}
bool CWavePlayThread::OnStart()
{
bool bResult = false;
ATLASSERT(m_hWaveOut == NULL);
m_bPaused = false;
m_bMuted = false;
if (MMSYSERR_NOERROR != waveOutOpen(&m_hWaveOut, m_nDeviceID, &m_format, (DWORD_PTR)(HANDLE)m_hEvent, NULL, CALLBACK_EVENT))
{
m_hWaveOut = NULL;
}
else
{
// suspend player, so we can control when to start
if (waveOutPause(m_hWaveOut) == MMSYSERR_NOERROR)
{
::ResetEvent(m_hEvent);
m_bPaused = true;
}
else
{
// unexpected
ATLASSERT(FALSE);
::SetEvent(m_hEvent);
}
bResult = true;
if (MMSYSERR_NOERROR != waveOutGetID(m_hWaveOut, &m_nRealDeviceID))
{
m_nRealDeviceID = m_nDeviceID;
}
}
::SetEvent(m_hStarted);
return bResult;
}
void CWavePlayThread::OnStop()
{
if (m_hWaveOut)
{
// waveOutReset will abort all queued items
ATLVERIFY(waveOutReset(m_hWaveOut) == MMSYSERR_NOERROR);
std::shared_ptr<CWaveQueueItem> pItem;
// wait for abortion to complete
while(m_Queue.unqueue(pItem))
{
pItem->WaitIfPlayed();
pItem->UnPrepare(m_hWaveOut);
pItem.reset();
}
m_Pool.clear();
ATLVERIFY(waveOutClose(m_hWaveOut) == MMSYSERR_NOERROR);
m_hWaveOut = NULL;
m_bPaused = false;
}
}
void CWavePlayThread::OnEvent()
{
::ResetEvent(m_hEvent);
std::shared_ptr<CWaveQueueItem> pItem;
while (m_Queue.peek(pItem))
{
if (pItem->IsDone())
{
m_Queue.unqueue();
Free(pItem);
}
else
{
pItem.reset();
break;
}
}
if (!m_bPaused)
{
while (m_nThreshold >= m_Queue.size())
{
if (!Alloc(pItem))
break;
m_callback(pItem->m_Blob, pItem->m_nLen);
if (pItem->Prepare(m_hWaveOut))
{
m_Queue.queue(move(pItem));
}
else
{
ATLASSERT(FALSE);
}
}
for (auto i = m_Queue.begin(); i != m_Queue.end(); ++i)
{
if (!(*i)->IsPlayed())
{
if (m_bMuted)
{
(*i)->Mute();
}
(*i)->Play(m_hWaveOut);
}
}
}
}
void CWavePlayThread::Pause()
{
if (m_hWaveOut != NULL)
{
if (m_bPaused)
{
m_bPaused = false;
// signal worker thread to fill the queue
::SetEvent(m_hEvent);
Sleep(0);
ATLVERIFY(waveOutRestart(m_hWaveOut) == MMSYSERR_NOERROR);
}
else
{
if (waveOutPause(m_hWaveOut) == MMSYSERR_NOERROR)
{
m_bPaused = true;
::ResetEvent(m_hEvent);
}
}
}
}
void CWavePlayThread::Mute(bool bMute)
{
m_bMuted = bMute;
}
void CWavePlayThread::SetVolume(WORD wVolume)
{
ATLASSERT(m_hWaveOut != NULL);
DWORD dwVolume = ((DWORD) wVolume) | (((DWORD) wVolume) << 16);
ATLVERIFY(waveOutSetVolume(m_hWaveOut, dwVolume) == MMSYSERR_NOERROR);
}
WORD CWavePlayThread::GetVolume()
{
ATLASSERT(m_hWaveOut != NULL);
DWORD dwVolume = 0;
ATLVERIFY(waveOutGetVolume(m_hWaveOut, &dwVolume) == MMSYSERR_NOERROR);
return (WORD) (dwVolume & 0x0000ffff);
}
//////////////////////////////////////////////////////////
// CAudioPlayer
CAudioPlayer::CAudioPlayer()
{
}
CAudioPlayer::~CAudioPlayer()
{
Close();
}
void CAudioPlayer::Mute(bool bMute)
{
if (m_threadWavePlay)
m_threadWavePlay->Mute(bMute);
}
bool CAudioPlayer::IsMuted() const
{
if (m_threadWavePlay)
return m_threadWavePlay->IsMuted();
return false;
}
bool CAudioPlayer::Init(HANDLE hDataSource)
{
if (!hDataSource)
{
::SetLastError(ERROR_INVALID_PARAMETER);
return false;
}
Close();
m_hAudioData.Attach(DuplicateHandle(hDataSource));
if (!m_hAudioData)
return false;
m_threadWavePlay = std::make_shared<CWavePlayThread>();
if (!m_threadWavePlay)
{
Close();
return false;
}
m_threadWavePlay->Init();
return m_threadWavePlay->Start([this](uint8_t* pStream, ULONG dwLen) -> void { OnPlayAudio(pStream, dwLen); });
}
void CAudioPlayer::Play()
{
if (m_threadWavePlay && m_threadWavePlay->IsPaused())
m_threadWavePlay->Pause();
}
void CAudioPlayer::Pause()
{
if (m_threadWavePlay && !m_threadWavePlay->IsPaused())
m_threadWavePlay->Pause();
}
void CAudioPlayer::Close()
{
if (m_threadWavePlay)
{
m_threadWavePlay->Stop();
m_threadWavePlay.reset();
}
if (m_hAudioData)
m_hAudioData.Close();
}
void CAudioPlayer::FadeSamples(void* pDest, const uint8_t* pSrc, ULONG dwBytes, double lfVolume)
{
ATLASSERT(pDest && pSrc && dwBytes % SAMPLE_FACTOR == 0 && lfVolume >= 0);
if (dwBytes)
{
const short* sample_in = (const short*)pSrc;
short* sample_out = (short*)pDest;
dwBytes /= SAMPLE_FACTOR;
do
{
for (auto i = 0; i < NUM_CHANNELS; ++i)
{
*sample_out++ = (short) (((double)*sample_in++) * lfVolume);
}
}
while (--dwBytes);
}
}
void CAudioPlayer::OnPlayAudio(uint8_t* pStream, ULONG dwLen)
{
if (dwLen)
{
memset(pStream, 0, dwLen);
int nTry = 5;
DWORD dwRead = 0;
DWORD dwReadTotal = 0;
// read PCM data from handle directly to the sound buffer in mem
while (nTry > 0 && dwLen && ::ReadFile(m_hAudioData, pStream + dwReadTotal, dwLen, &dwRead, NULL))
{
if (dwRead == 0)
{
// the input handle may be a pipe ... give it some time to deliver the data (over all 25ms)
nTry--;
Sleep(5);
}
else
{
nTry = 5;
dwLen -= dwRead;
dwReadTotal += dwRead;
}
}
}
}