This repository has been archived by the owner on Dec 2, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 225
/
WASAPIRenderer.cpp
634 lines (534 loc) · 17 KB
/
WASAPIRenderer.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
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
//--------------------------------------------------------------------------------------
//
// WASAPIRenderer.cpp
//
// Advanced Technology Group (ATG)
// Copyright (C) Microsoft Corporation. All rights reserved.
//--------------------------------------------------------------------------------------
#include "pch.h"
#include "WASAPIRenderer.h"
using namespace Windows::System::Threading;
using namespace Windows::Media::Devices;
using Microsoft::WRL::ComPtr;
//
// WASAPIRenderer()
//
WASAPIRenderer::WASAPIRenderer() :
m_BufferFrames( 0 ),
m_DeviceStateChanged( nullptr ),
m_AudioClient( nullptr ),
m_AudioRenderClient( nullptr ),
m_SampleReadyAsyncResult( nullptr ),
m_ToneSource( nullptr )
{
// Create events for sample ready or user stop
m_SampleReadyEvent = CreateEventEx( nullptr, nullptr, 0, EVENT_ALL_ACCESS );
if (nullptr == m_SampleReadyEvent)
{
DX::ThrowIfFailed( HRESULT_FROM_WIN32( GetLastError() ) );
}
m_DeviceStateChanged = ref new DeviceStateChangedEvent();
if (nullptr == m_DeviceStateChanged)
{
DX::ThrowIfFailed( E_OUTOFMEMORY );
}
}
//
// ~WASAPIRenderer()
//
WASAPIRenderer::~WASAPIRenderer()
{
if (INVALID_HANDLE_VALUE != m_SampleReadyEvent)
{
CloseHandle( m_SampleReadyEvent );
m_SampleReadyEvent = INVALID_HANDLE_VALUE;
}
m_DeviceStateChanged = nullptr;
}
//
// InitializeAudioDeviceAsync()
//
// Activates the default audio renderer on a asynchronous callback thread. This needs
// to be called from the main UI thread.
//
HRESULT WASAPIRenderer::InitializeAudioDeviceAsync()
{
ComPtr<IActivateAudioInterfaceAsyncOperation> asyncOp;
HRESULT hr = S_OK;
// Get a string representing the Default Audio Device Renderer
m_DeviceIdString = MediaDevice::GetDefaultAudioRenderId( Windows::Media::Devices::AudioDeviceRole::Default );
// This call must be made on the main UI thread. Async operation will call back to
// IActivateAudioInterfaceCompletionHandler::ActivateCompleted, which must be an agile interface implementation
hr = ActivateAudioInterfaceAsync( m_DeviceIdString->Data(), __uuidof(IAudioClient2), nullptr, this, &asyncOp );
if (FAILED( hr ))
{
m_DeviceStateChanged->SetState( DeviceState::DeviceStateInError, hr, true );
}
return hr;
}
//
// ActivateCompleted()
//
// Callback implementation of ActivateAudioInterfaceAsync function. This will be called on MTA thread
// when results of the activation are available.
//
HRESULT WASAPIRenderer::ActivateCompleted( IActivateAudioInterfaceAsyncOperation *operation )
{
HRESULT hr = S_OK;
HRESULT hrActivateResult = S_OK;
ComPtr<IUnknown> punkAudioInterface = nullptr;
if (m_DeviceStateChanged->GetState() != DeviceState::DeviceStateUnInitialized)
{
hr = E_NOT_VALID_STATE;
goto exit;
}
// Check for a successful activation result
hr = operation->GetActivateResult( &hrActivateResult, &punkAudioInterface );
if (SUCCEEDED( hr ) && SUCCEEDED( hrActivateResult ))
{
m_DeviceStateChanged->SetState( DeviceState::DeviceStateActivated, S_OK, false );
// Get the pointer for the Audio Client
punkAudioInterface.Get()->QueryInterface( IID_PPV_ARGS(&m_AudioClient) );
if( nullptr == m_AudioClient )
{
hr = E_FAIL;
goto exit;
}
// Configure user defined properties
hr = ConfigureDeviceInternal();
if (FAILED( hr ))
{
goto exit;
}
// Initialize the AudioClient in Shared Mode with the user specified buffer
hr = m_AudioClient->Initialize( AUDCLNT_SHAREMODE_SHARED,
AUDCLNT_STREAMFLAGS_EVENTCALLBACK | AUDCLNT_STREAMFLAGS_NOPERSIST,
m_DeviceProps.hnsBufferDuration,
m_DeviceProps.hnsBufferDuration,
m_MixFormat,
nullptr );
if (FAILED( hr ))
{
goto exit;
}
// Get the maximum size of the AudioClient Buffer
hr = m_AudioClient->GetBufferSize( &m_BufferFrames );
if (FAILED( hr ))
{
goto exit;
}
// Get the render client
hr = m_AudioClient->GetService( __uuidof(IAudioRenderClient), (void**) &m_AudioRenderClient );
if (FAILED( hr ))
{
goto exit;
}
// Create Async callback for sample events
hr = MFCreateAsyncResult( nullptr, &m_xSampleReady, nullptr, &m_SampleReadyAsyncResult );
if (FAILED( hr ))
{
goto exit;
}
// Sets the event handle that the system signals when an audio buffer is ready to be processed by the client
hr = m_AudioClient->SetEventHandle( m_SampleReadyEvent );
if (FAILED( hr ))
{
goto exit;
}
// Everything succeeded
m_DeviceStateChanged->SetState( DeviceState::DeviceStateInitialized, S_OK, true );
}
exit:
if (FAILED( hr ))
{
m_DeviceStateChanged->SetState( DeviceState::DeviceStateInError, hr, true );
}
// Need to return S_OK
return S_OK;
}
//
// SetProperties()
//
// Sets various properties that the user defines in the scenario
//
HRESULT WASAPIRenderer::SetProperties( DEVICEPROPS props )
{
m_DeviceProps = props;
return S_OK;
}
//
// GetBufferFramesPerPeriod()
//
// Get the time in seconds between passes of the audio device
//
UINT32 WASAPIRenderer::GetBufferFramesPerPeriod()
{
REFERENCE_TIME defaultDevicePeriod = 0;
REFERENCE_TIME minimumDevicePeriod = 0;
if (m_DeviceProps.IsHWOffload)
{
return m_BufferFrames;
}
// Get the audio device period
HRESULT hr = m_AudioClient->GetDevicePeriod( &defaultDevicePeriod, &minimumDevicePeriod);
if (FAILED( hr ))
{
return 0;
}
double devicePeriodInSeconds = defaultDevicePeriod / (10000.0*1000.0);
return static_cast<unsigned int>( m_MixFormat->nSamplesPerSec * devicePeriodInSeconds + 0.5 );
}
//
// ConfigureDeviceInternal()
//
// Sets additional playback parameters and opts into hardware offload
//
HRESULT WASAPIRenderer::ConfigureDeviceInternal()
{
if (m_DeviceStateChanged->GetState() != DeviceState::DeviceStateActivated)
{
return E_NOT_VALID_STATE;
}
HRESULT hr = S_OK;
// Opt into HW Offloading. If the endpoint does not support offload it will return AUDCLNT_E_ENDPOINT_OFFLOAD_NOT_CAPABLE
AudioClientProperties audioProps = {};
audioProps.cbSize = sizeof( AudioClientProperties );
audioProps.bIsOffload = m_DeviceProps.IsHWOffload;
audioProps.eCategory = AudioCategory_ForegroundOnlyMedia;
if (m_DeviceProps.IsRawChosen && m_DeviceProps.IsRawSupported)
{
audioProps.Options = AUDCLNT_STREAMOPTIONS_RAW;
}
hr = m_AudioClient->SetClientProperties( &audioProps );
if (FAILED( hr ))
{
return hr;
}
// This sample opens the device is shared mode so we need to find the supported WAVEFORMATEX mix format
hr = m_AudioClient->GetMixFormat( &m_MixFormat );
if (FAILED( hr ))
{
return hr;
}
// Verify the user defined value for hardware buffer
hr = ValidateBufferValue();
return hr;
}
//
// ValidateBufferValue()
//
// Verifies the user specified buffer value for hardware offload
//
HRESULT WASAPIRenderer::ValidateBufferValue()
{
HRESULT hr = S_OK;
if (!m_DeviceProps.IsHWOffload)
{
// If we aren't using HW Offload, set this to 0 to use the default value
m_DeviceProps.hnsBufferDuration = 0;
return hr;
}
REFERENCE_TIME hnsMinBufferDuration;
REFERENCE_TIME hnsMaxBufferDuration;
hr = m_AudioClient->GetBufferSizeLimits( m_MixFormat, true, &hnsMinBufferDuration, &hnsMaxBufferDuration );
if (SUCCEEDED( hr ))
{
if (m_DeviceProps.hnsBufferDuration < hnsMinBufferDuration)
{
// using MINIMUM size instead
m_DeviceProps.hnsBufferDuration = hnsMinBufferDuration;
}
else if (m_DeviceProps.hnsBufferDuration > hnsMaxBufferDuration)
{
// using MAXIMUM size instead
m_DeviceProps.hnsBufferDuration = hnsMaxBufferDuration;
}
}
return hr;
}
//
// SetVolumeOnSession()
//
HRESULT WASAPIRenderer::SetVolumeOnSession(unsigned int volume )
{
if (volume > 100)
{
return E_INVALIDARG;
}
HRESULT hr = S_OK;
ComPtr<ISimpleAudioVolume> SessionAudioVolume = nullptr;
float ChannelVolume = 0.0;
hr = m_AudioClient->GetService( __uuidof(ISimpleAudioVolume), reinterpret_cast<void**>(SessionAudioVolume.Get()) );
if (FAILED( hr ))
{
goto exit;
}
ChannelVolume = volume / (float)100.0;
// Set the session volume on the endpoint
hr = SessionAudioVolume->SetMasterVolume( ChannelVolume, nullptr );
exit:
return hr;
}
//
// ConfigureSource()
//
// Configures tone or file playback
//
HRESULT WASAPIRenderer::ConfigureSource()
{
HRESULT hr = S_OK;
UINT32 FramesPerPeriod = GetBufferFramesPerPeriod();
// Generate the sine wave sample buffer
m_ToneSource = std::make_unique<ToneSampleGenerator>();
if (m_ToneSource)
{
hr = m_ToneSource->GenerateSampleBuffer( m_DeviceProps.Frequency, FramesPerPeriod, m_MixFormat );
}
else
{
hr = E_OUTOFMEMORY;
}
return hr;
}
//
// StartPlaybackAsync()
//
// Starts asynchronous playback on a separate thread via MF Work Item
//
HRESULT WASAPIRenderer::StartPlaybackAsync()
{
HRESULT hr = S_OK;
// We should be stopped if the user stopped playback, or we should be
// initialzied if this is the first time through getting ready to playback.
if ( (m_DeviceStateChanged->GetState() == DeviceState::DeviceStateStopped) ||
(m_DeviceStateChanged->GetState() == DeviceState::DeviceStateInitialized) )
{
// Setup either ToneGeneration or File Playback
hr = ConfigureSource();
if (FAILED( hr ))
{
m_DeviceStateChanged->SetState( DeviceState::DeviceStateInError, hr, true );
return hr;
}
m_DeviceStateChanged->SetState( DeviceState::DeviceStateStarting, S_OK, true );
return MFPutWorkItem2( MFASYNC_CALLBACK_QUEUE_MULTITHREADED, 0, &m_xStartPlayback, nullptr );
}
else if (m_DeviceStateChanged->GetState() == DeviceState::DeviceStatePaused)
{
return MFPutWorkItem2( MFASYNC_CALLBACK_QUEUE_MULTITHREADED, 0, &m_xStartPlayback, nullptr );
}
// Otherwise something else happened
return E_FAIL;
}
//
// OnStartPlayback()
//
// Callback method to start playback
//
HRESULT WASAPIRenderer::OnStartPlayback( IMFAsyncResult* )
{
HRESULT hr = S_OK;
// Pre-Roll the buffer with silence
hr = OnAudioSampleRequested( true );
if (FAILED( hr ))
{
goto exit;
}
// Actually start the playback
hr = m_AudioClient->Start();
if (SUCCEEDED( hr ))
{
m_DeviceStateChanged->SetState( DeviceState::DeviceStatePlaying, S_OK, true );
hr = MFPutWaitingWorkItem( m_SampleReadyEvent, 0, m_SampleReadyAsyncResult.Get(), &m_SampleReadyKey );
}
exit:
if (FAILED( hr ))
{
m_DeviceStateChanged->SetState( DeviceState::DeviceStateInError, hr, true );
}
return S_OK;
}
//
// StopPlaybackAsync()
//
// Stop playback asynchronously via MF Work Item
//
HRESULT WASAPIRenderer::StopPlaybackAsync()
{
if ( (m_DeviceStateChanged->GetState() != DeviceState::DeviceStatePlaying) &&
(m_DeviceStateChanged->GetState() != DeviceState::DeviceStatePaused) &&
(m_DeviceStateChanged->GetState() != DeviceState::DeviceStateInError) )
{
return E_NOT_VALID_STATE;
}
m_DeviceStateChanged->SetState( DeviceState::DeviceStateStopping, S_OK, true );
return MFPutWorkItem2( MFASYNC_CALLBACK_QUEUE_MULTITHREADED, 0, &m_xStopPlayback, nullptr );
}
//
// OnStopPlayback()
//
// Callback method to stop playback
//
HRESULT WASAPIRenderer::OnStopPlayback( IMFAsyncResult* )
{
// Stop playback by cancelling Work Item
// Cancel the queued work item (if any)
if (0 != m_SampleReadyKey)
{
MFCancelWorkItem( m_SampleReadyKey );
m_SampleReadyKey = 0;
}
// Flush anything left in buffer with silence
OnAudioSampleRequested( true );
m_AudioClient->Stop();
m_ToneSource->Flush();
m_DeviceStateChanged->SetState( DeviceState::DeviceStateStopped, S_OK, true );
return S_OK;
}
//
// PausePlaybackAsync()
//
// Pause playback asynchronously via MF Work Item
//
HRESULT WASAPIRenderer::PausePlaybackAsync()
{
if ( (m_DeviceStateChanged->GetState() != DeviceState::DeviceStatePlaying) &&
(m_DeviceStateChanged->GetState() != DeviceState::DeviceStateInError) )
{
return E_NOT_VALID_STATE;
}
// Change state to stop automatic queueing of samples
m_DeviceStateChanged->SetState( DeviceState::DeviceStatePausing, S_OK, false );
return MFPutWorkItem2( MFASYNC_CALLBACK_QUEUE_MULTITHREADED, 0, &m_xPausePlayback, nullptr );
}
//
// OnPausePlayback()
//
// Callback method to pause playback
//
HRESULT WASAPIRenderer::OnPausePlayback( IMFAsyncResult* )
{
m_AudioClient->Stop();
m_DeviceStateChanged->SetState( DeviceState::DeviceStatePaused, S_OK, true );
return S_OK;
}
//
// OnSampleReady()
//
// Callback method when ready to fill sample buffer
//
HRESULT WASAPIRenderer::OnSampleReady( IMFAsyncResult* )
{
HRESULT hr = S_OK;
hr = OnAudioSampleRequested( false );
if (SUCCEEDED( hr ))
{
// Re-queue work item for next sample
if (m_DeviceStateChanged->GetState() == DeviceState::DeviceStatePlaying)
{
hr = MFPutWaitingWorkItem( m_SampleReadyEvent, 0, m_SampleReadyAsyncResult.Get(), &m_SampleReadyKey );
}
}
else
{
m_DeviceStateChanged->SetState( DeviceState::DeviceStateInError, hr, true );
}
return hr;
}
//
// OnAudioSampleRequested()
//
// Called when audio device fires m_SampleReadyEvent
//
HRESULT WASAPIRenderer::OnAudioSampleRequested( bool IsSilence )
{
HRESULT hr = S_OK;
UINT32 PaddingFrames = 0;
UINT32 FramesAvailable = 0;
std::lock_guard<std::mutex> lck(m_mutex);
// Get padding in existing buffer
hr = m_AudioClient->GetCurrentPadding( &PaddingFrames );
if (FAILED( hr ))
{
goto exit;
}
// Audio frames available in buffer
if (m_DeviceProps.IsHWOffload)
{
// In HW mode, GetCurrentPadding returns the number of available frames in the
// buffer, so we can just use that directly
FramesAvailable = PaddingFrames;
}
else
{
// In non-HW shared mode, GetCurrentPadding represents the number of queued frames
// so we can subtract that from the overall number of frames we have
FramesAvailable = m_BufferFrames - PaddingFrames;
}
// Only continue if we have buffer to write data
if (FramesAvailable > 0)
{
if (IsSilence)
{
BYTE *Data;
// Fill the buffer with silence
hr = m_AudioRenderClient->GetBuffer( FramesAvailable, &Data );
if (FAILED( hr ))
{
goto exit;
}
hr = m_AudioRenderClient->ReleaseBuffer( FramesAvailable, AUDCLNT_BUFFERFLAGS_SILENT );
goto exit;
}
// Even if we cancel a work item, this may still fire due to the async
// nature of things. There should be a queued work item already to handle
// the process of stopping or stopped
if (m_DeviceStateChanged->GetState() == DeviceState::DeviceStatePlaying)
{
hr = GetToneSample( FramesAvailable );
}
}
exit:
if (AUDCLNT_E_RESOURCES_INVALIDATED == hr)
{
m_DeviceStateChanged->SetState( DeviceState::DeviceStateUnInitialized, hr, false );
hr = InitializeAudioDeviceAsync();
}
return hr;
}
//
// GetToneSample()
//
// Fills buffer with a tone sample
//
HRESULT WASAPIRenderer::GetToneSample( unsigned int FramesAvailable )
{
HRESULT hr = S_OK;
BYTE *Data;
// Post-Roll Silence
if (m_ToneSource->IsEOF())
{
hr = m_AudioRenderClient->GetBuffer( FramesAvailable, &Data );
if (SUCCEEDED( hr ))
{
// Ignore the return
hr = m_AudioRenderClient->ReleaseBuffer( FramesAvailable, AUDCLNT_BUFFERFLAGS_SILENT );
}
StopPlaybackAsync();
}
else if (m_ToneSource->GetBufferLength() <= ( FramesAvailable * m_MixFormat->nBlockAlign ))
{
UINT32 ActualFramesToRead = m_ToneSource->GetBufferLength() / m_MixFormat->nBlockAlign;
UINT32 ActualBytesToRead = ActualFramesToRead * m_MixFormat->nBlockAlign;
hr = m_AudioRenderClient->GetBuffer( ActualFramesToRead, &Data );
if (SUCCEEDED( hr ))
{
hr = m_ToneSource->FillSampleBuffer( ActualBytesToRead, Data );
if (SUCCEEDED( hr ))
{
hr = m_AudioRenderClient->ReleaseBuffer( ActualFramesToRead, 0 );
}
}
}
return hr;
}