summaryrefslogtreecommitdiff
path: root/audio/tests/HLK/ThirdPartyApoTests/APOStressTest.cpp
blob: 160f488be00a91589d2fcf1d0791d83585713f6f (plain)
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
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
#include <stdafx.h>

#include <initguid.h>
#include "propkey.h"
#include <AudioClient.h>
#include <SpatialAudioClient.h>
#include <functiondiscoverykeys.h>
#include <DevPKey.h>
#include <AudioEngineBaseAPOP.h>
#include "TestMediaType.h"
#include <audioenginebaseapo.h>
#include <MMDeviceAPI.h>
#include <MMDeviceAPIP.h>

#include <WexTestClass.h>

#include <list>
#include <memory>
#include <ctime>
#include <thread>
#include <future>
#include <mutex>
#include <functional>
#include <atlbase.h>

#include "APOStressTest.h"
#include "sinewave.h"
#include "util.h"

#include <psapi.h>
#include <processthreadsapi.h>

using namespace std;
using namespace wil;
using namespace WEX::Logging;
using namespace WEX::Common;

#define NUMBER_OF_TESTS 8
#define THIRTY_MIN_IN_SEC 1800
#define SIXTY_SECONDS 60
#define ONE_SEC_IN_MS 1000
#define THIRTY_MIN_IN_MS 1800000
#define MAX_ALLOWED_PAGEFILE_USAGE_IN_BYTES 300000000

#define IF_FAILED_RETURN(hr) { HRESULT hrCode = hr; if(FAILED(hrCode)) { return hrCode; } }

#define REGKEY_AUDIOSERVICE L"Software\\Microsoft\\Windows\\CurrentVersion\\Audio"
#define REGVALUE_SKIPRTHEAP L"SkipRTHeap"

const DWORD WAIT_TIME_MIN_FOR_THREAD_OPERATION = 3u * 1000u;        //  3 seconds
const DWORD WAIT_TIME_MAX_FOR_THREAD_OPERATION = 10u * 1000u;       // 10 seconds

size_t maxAudioDGPagefileUsage = 0;
std::mutex maxAudioDGPagefileUsage_mutex; // protects maxAudioDGPagefileUsage_mutex 

template <typename T>
inline T RandInRange(T min, T max)
{
    // Treat the value span as a double right away.  Otherwise if min = 0, and max
    // is truly the max for the type, the value span could loop to zero.
    double valueSpan = 1.0f + (double) (max - min);

    // The following had a problem where doubles larger than 0x8000000000000000 were always truncating
    // to 0x8000000000000000 when cast to a DWORD64.  Multiplying by 0.5f and then (T) 2 seemed to
    // get around this problem.
    //return min + (T) ((double) (max - min + 1) * (double) rand() / (double) (RAND_MAX + 1));

    // Then the following had a problem where RandInRange(0, 1) could never return 1.
    //return min + (T) 2 * (T) (0.5f * valueSpan * ((double) rand() / (double) (RAND_MAX + 1)));

    double offset = valueSpan * ((double) rand() / (double) (RAND_MAX + 1));

    if (offset > (double) ((DWORD64) 0x8000000000000000))
    {
        return min + (T) 2 * (T) (0.5f * offset);
    }

    return min + (T) offset;
}

void WriteToAudioObjectBuffer(FLOAT* buffer, UINT frameCount, FLOAT frequency, UINT samplingRate)
{
    const double PI = 4 * atan2(1.0, 1.0);
    static double _radPhase = 0.0;
    double step = 2 * PI * frequency / samplingRate;

    for (UINT i = 0; i < frameCount; i++)
    {
        double sample = sin(_radPhase);
        buffer[i] = FLOAT(sample);
        _radPhase += step; // next frame phase

        if (_radPhase >= 2 * PI)
        {
            _radPhase -= 2 * PI;
        }
    }
}

bool SetupSkipRTHeap()
{
    DWORD dwValue = 1;
    DWORD cbData = sizeof(dwValue);

    DWORD result = RegSetKeyValueW(HKEY_LOCAL_MACHINE, REGKEY_AUDIOSERVICE, REGVALUE_SKIPRTHEAP, REG_DWORD, &dwValue, cbData);

    RestartAudioService();

    return (result == ERROR_SUCCESS);
}

bool CleanupSkipRTHeap()
{
    DWORD result = RegDeleteKeyValueW(HKEY_LOCAL_MACHINE, REGKEY_AUDIOSERVICE, REGVALUE_SKIPRTHEAP);

    RestartAudioService();

    return (result == ERROR_SUCCESS);
}

bool CAPOStressTest::setUpMethod()
{
    return SetupSkipRTHeap();
}

bool CAPOStressTest::tearDownMethod()
{
    return CleanupSkipRTHeap();
}

void CAPOStressTest::AudioAPOStressTest()
{

    UINT cDevices = 0;
    com_ptr_nothrow<IMMDeviceEnumerator> spEnumerator;
    com_ptr_nothrow<IMMDeviceCollection> spDevices;
    vector<com_ptr<IMMDevice>> sEndpoints;

    VERIFY_SUCCEEDED(CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr, CLSCTX_ALL, IID_PPV_ARGS(&spEnumerator)));
    VERIFY_SUCCEEDED(spEnumerator->EnumAudioEndpoints(eAll, DEVICE_STATE_ACTIVE, &spDevices));
    VERIFY_SUCCEEDED(spDevices->GetCount(&cDevices));

    for (UINT i = 0; i < cDevices; i++)
    {
        wil::com_ptr<IMMDevice> pEndpoint = nullptr;

        VERIFY_SUCCEEDED(spDevices->Item(i, &pEndpoint));

        sEndpoints.push_back(pEndpoint);
    }

    RunStressTest(THIRTY_MIN_IN_SEC, sEndpoints);
}

std::wstring QueryProcessName(const DWORD pid)
{
    wil::unique_handle hProcess(OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid));
    if(NULL == hProcess)
    {
        return L"err " + std::to_wstring(GetLastError());
    }
    else
    {
        WCHAR szProcessName[1024];
        DWORD cchSize = ARRAYSIZE(szProcessName);
        if (0 == QueryFullProcessImageNameW(hProcess.get(), 0, szProcessName, &cchSize))
        {
            return L"err " + std::to_wstring(GetLastError());
        }

        PWSTR fileName = szProcessName + cchSize;
        while (fileName != szProcessName && *fileName != L'\\') fileName--;
        
        return (*fileName == L'\\') ? fileName + 1 : fileName;
    }
}

DWORD GetAudioDGProcessID()
{
    // Get the list of process identifiers.

    DWORD aProcesses[1024], cbNeeded, cProcesses;
    unsigned int i;

    if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) )
    {
        return 0;
    }

    // Calculate how many process identifiers were returned.

    cProcesses = cbNeeded / sizeof(DWORD);

    // Look for AudioDG name and process identifier on each process.

    for ( i = 0; i < cProcesses; i++ )
    {
        if( aProcesses[i] != 0 && 0 == _wcsicmp(QueryProcessName(aProcesses[i]).c_str(), L"AUDIODG.EXE"))
        {
            return aProcesses[i];
        }
    }

    return 0;
}

void GetAudioDGMemoryUsageSample()
{
    // Get the AudioDG process ID
    DWORD audioDGProcessID = GetAudioDGProcessID();

    if (audioDGProcessID != 0)
    {
        std::lock_guard<std::mutex> autoLock(maxAudioDGPagefileUsage_mutex);

        // Memory PagefileUsage snapshot 
        PROCESS_MEMORY_COUNTERS pmc;

        HANDLE hProcess = OpenProcess(  PROCESS_QUERY_INFORMATION |
                                        PROCESS_VM_READ,
                                        FALSE, audioDGProcessID );

        if (hProcess != NULL && GetProcessMemoryInfo( hProcess, &pmc, sizeof(pmc)) )
        {
            maxAudioDGPagefileUsage = max(maxAudioDGPagefileUsage, pmc.PagefileUsage);
        }

        VERIFY_IS_TRUE(maxAudioDGPagefileUsage < MAX_ALLOWED_PAGEFILE_USAGE_IN_BYTES);

        CloseHandle( hProcess );
    }
    else
    {
        Log::Warning(L"Unable to find AudioDG PID");
    }
}

HRESULT BasicAudioStreaming(IMMDevice* pEndpoint)
{
    com_ptr_nothrow<IAudioClient2> pAudioClient;
    wil::unique_cotaskmem_ptr<WAVEFORMATEX> mixFormat;

    if (pEndpoint == nullptr)
    {
        return E_INVALIDARG;
    }

    IF_FAILED_RETURN(pEndpoint->Activate(__uuidof(IAudioClient2), CLSCTX_ALL, NULL, (void**)&pAudioClient));

    AudioClientProperties clientProperties = { 0 };
    clientProperties.cbSize = sizeof(AudioClientProperties);
    clientProperties.bIsOffload = false;
    clientProperties.eCategory = (AUDIO_STREAM_CATEGORY) RandInRange(0, 11);

    IF_FAILED_RETURN(pAudioClient->SetClientProperties(&clientProperties));

    IF_FAILED_RETURN(pAudioClient->GetMixFormat(wil::out_param_ptr<WAVEFORMATEX **>(mixFormat)));

    IF_FAILED_RETURN(pAudioClient->Initialize(
        AUDCLNT_SHAREMODE_SHARED,
        AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
        0,
        0,
        mixFormat.get(),
        nullptr));

    com_ptr_nothrow<IAudioRenderClient> pRenderClient;
    IF_FAILED_RETURN(pAudioClient->GetService(_uuidof(IAudioRenderClient), wil::out_param_ptr<void **>(pRenderClient)));

    wil::unique_event bufferCompleteEvent;
    bufferCompleteEvent.create();
    IF_FAILED_RETURN(pAudioClient->SetEventHandle(bufferCompleteEvent.get()));

    UINT32 bufferFrameCount;
    REFERENCE_TIME duration = RandInRange(WAIT_TIME_MIN_FOR_THREAD_OPERATION, WAIT_TIME_MAX_FOR_THREAD_OPERATION);
    IF_FAILED_RETURN(pAudioClient->GetBufferSize(&bufferFrameCount));

    SineWave sw(mixFormat->nChannels, mixFormat->nSamplesPerSec);
    for (unsigned i = 0; i < mixFormat->nChannels; ++i)
    {
        sw.SetChannel(i, 400, 0.25f);
    }

    BYTE* data{};
    IF_FAILED_RETURN(pRenderClient->GetBuffer(bufferFrameCount, &data));

    sw.FillFrames(data, bufferFrameCount);
    IF_FAILED_RETURN(pRenderClient->ReleaseBuffer(bufferFrameCount, 0));

    IF_FAILED_RETURN(pAudioClient->Start());

    unsigned c = 0;
    while (c++ < duration)
    {
        if (WaitForSingleObject(bufferCompleteEvent.get(), ONE_SEC_IN_MS) != WAIT_OBJECT_0)
        {
            break;
        }

        unsigned numFramesPadding{};
        IF_FAILED_RETURN(pAudioClient->GetCurrentPadding(&numFramesPadding));
        auto numFramesAvailable = bufferFrameCount - numFramesPadding;

        IF_FAILED_RETURN(pRenderClient->GetBuffer(numFramesAvailable, &data));
        sw.FillFrames(data, numFramesAvailable);
        IF_FAILED_RETURN(pRenderClient->ReleaseBuffer(numFramesAvailable, 0));
    }

    // Get a sample of the current AudioDG memory usage
    GetAudioDGMemoryUsageSample();

    IF_FAILED_RETURN(pAudioClient->Stop());

    return S_OK;
}

HRESULT DisableEnableEndpoint(IMMDevice* pEndpoint)
{
    com_ptr_nothrow<IMMEndpointManager> pManager = nullptr;

    if (pEndpoint == nullptr)
    {
        return E_INVALIDARG;
    }

    IF_FAILED_RETURN(CoCreateInstance(__uuidof(MMEndpointManager), nullptr, CLSCTX_ALL, IID_PPV_ARGS(&pManager)));

    IF_FAILED_RETURN(pManager->SetEndpointState(pEndpoint, DEVICE_STATE_DISABLED));

    Sleep(1000);

    IF_FAILED_RETURN(pManager->SetEndpointState(pEndpoint, DEVICE_STATE_ACTIVE));

    return S_OK;
}

HRESULT BasicAudioCapture(IMMDevice* pEndpoint)
{
    com_ptr_nothrow<IAudioClient> pAudioClient;
    wil::unique_cotaskmem_ptr<WAVEFORMATEX> mixFormat;

    if (pEndpoint == nullptr)
    {
        return E_INVALIDARG;
    }

    IF_FAILED_RETURN(pEndpoint->Activate(__uuidof(IAudioClient), CLSCTX_ALL, NULL, (void**)&pAudioClient));

    IF_FAILED_RETURN(pAudioClient->GetMixFormat(wil::out_param_ptr<WAVEFORMATEX **>(mixFormat)));

    IF_FAILED_RETURN(pAudioClient->Initialize(
        AUDCLNT_SHAREMODE_SHARED,
        AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
        0,
        0,
        mixFormat.get(),
        nullptr));

    com_ptr_nothrow<IAudioCaptureClient> pCaptureClient;
    IF_FAILED_RETURN(pAudioClient->GetService(_uuidof(IAudioCaptureClient), wil::out_param_ptr<void **>(pCaptureClient)));

    wil::unique_event bufferCompleteEvent;
    bufferCompleteEvent.create();
    IF_FAILED_RETURN(pAudioClient->SetEventHandle(bufferCompleteEvent.get()));

    UINT32 bufferFrameCount;
    REFERENCE_TIME duration = RandInRange(WAIT_TIME_MIN_FOR_THREAD_OPERATION, WAIT_TIME_MAX_FOR_THREAD_OPERATION);
    IF_FAILED_RETURN(pAudioClient->GetBufferSize(&bufferFrameCount));

    BYTE* data{};
    DWORD dwFlags = 0;
    UINT32 numFramesInNextPacket = 0;

    IF_FAILED_RETURN(pCaptureClient->GetNextPacketSize(&numFramesInNextPacket));
    IF_FAILED_RETURN(pCaptureClient->GetBuffer(&data, &numFramesInNextPacket, &dwFlags, NULL, NULL)); 

    IF_FAILED_RETURN(pAudioClient->Start());

    unsigned c = 0;
    while (c++ < duration)
    {
       if (WaitForSingleObject(bufferCompleteEvent.get(), ONE_SEC_IN_MS) != WAIT_OBJECT_0)
        {
            break;
        }

        IF_FAILED_RETURN(pCaptureClient->ReleaseBuffer(numFramesInNextPacket));

        IF_FAILED_RETURN(pCaptureClient->GetBuffer(&data, &numFramesInNextPacket, &dwFlags, NULL, NULL));
    }

    // Get a sample of the current AudioDG memory usage
    GetAudioDGMemoryUsageSample();
    
    IF_FAILED_RETURN(pAudioClient->Stop());

    return S_OK;
}

HRESULT BasicAudioLoopback(IMMDevice* pEndpoint)
{
    com_ptr_nothrow<IAudioClient> pAudioClient;
    wil::unique_cotaskmem_ptr<WAVEFORMATEX> mixFormat;

    if (pEndpoint == nullptr)
    {
        return E_INVALIDARG;
    }

    IF_FAILED_RETURN(pEndpoint->Activate(__uuidof(IAudioClient), CLSCTX_ALL, NULL, (void**)&pAudioClient));

    IF_FAILED_RETURN(pAudioClient->GetMixFormat(wil::out_param_ptr<WAVEFORMATEX **>(mixFormat)));

    IF_FAILED_RETURN(pAudioClient->Initialize(
        AUDCLNT_SHAREMODE_SHARED,
        AUDCLNT_STREAMFLAGS_LOOPBACK | AUDCLNT_STREAMFLAGS_EVENTCALLBACK | AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM,
        0,
        0,
        mixFormat.get(),
        nullptr));

    com_ptr_nothrow<IAudioCaptureClient> pCaptureClient;
    IF_FAILED_RETURN(pAudioClient->GetService(__uuidof(IAudioCaptureClient), wil::out_param_ptr<void **>(pCaptureClient)));

    wil::unique_event bufferCompleteEvent;
    bufferCompleteEvent.create();
    IF_FAILED_RETURN(pAudioClient->SetEventHandle(bufferCompleteEvent.get()));

    UINT32 bufferFrameCount;
    IF_FAILED_RETURN(pAudioClient->GetBufferSize(&bufferFrameCount));

    BYTE* data{};
    DWORD dwFlags = 0;
    UINT32 numFramesInNextPacket = 0;

    IF_FAILED_RETURN(pCaptureClient->GetNextPacketSize(&numFramesInNextPacket));

    IF_FAILED_RETURN(pAudioClient->Start());

    while (numFramesInNextPacket != 0)
    {
        IF_FAILED_RETURN(pCaptureClient->GetBuffer(&data, &numFramesInNextPacket, &dwFlags, NULL, NULL));

        IF_FAILED_RETURN(pCaptureClient->ReleaseBuffer(numFramesInNextPacket));

        IF_FAILED_RETURN(pCaptureClient->GetNextPacketSize(&numFramesInNextPacket));
    }

    // Get a sample of the current AudioDG memory usage
    GetAudioDGMemoryUsageSample();

    IF_FAILED_RETURN(pAudioClient->Stop());

    return S_OK;
}

HRESULT BasicSpatialAudio(IMMDevice* pEndpoint)
{
#ifdef LNM
    EnableSpatialAudio();
#endif

    if (pEndpoint == nullptr)
    {
        return E_INVALIDARG;
    }

    com_ptr_nothrow<ISpatialAudioClient> client;
    IF_FAILED_RETURN(pEndpoint->Activate(__uuidof(ISpatialAudioClient), CLSCTX_ALL, nullptr, wil::out_param_ptr<void **>(client)));

    com_ptr_nothrow<IAudioFormatEnumerator> enumer;
    IF_FAILED_RETURN(client->GetSupportedAudioObjectFormatEnumerator(&enumer));

    wil::unique_cotaskmem_ptr<WAVEFORMATEX> fmt;
    IF_FAILED_RETURN(enumer->GetFormat(0, wil::out_param_ptr<WAVEFORMATEX **>(fmt)));

    unique_event event;
    event.create();
    if (event == nullptr)
    {
        HRESULT_FROM_WIN32(GetLastError());
    }

    unique_prop_variant pv;
    auto params = reinterpret_cast<SpatialAudioObjectRenderStreamActivationParams *>(CoTaskMemAlloc(sizeof(SpatialAudioObjectRenderStreamActivationParams)));
    *params = SpatialAudioObjectRenderStreamActivationParams{fmt.get(), (AudioObjectType)AudioObjectType_FrontLeft, 0, 0, AudioCategory_Other, event.get(), nullptr};
    pv.vt = VT_BLOB;
    pv.blob.cbSize = sizeof(*params);
    pv.blob.pBlobData = reinterpret_cast<BYTE *>(params);

    com_ptr_nothrow<ISpatialAudioObjectRenderStream> stream;
    IF_FAILED_RETURN(client->ActivateSpatialAudioStream(&pv, __uuidof(ISpatialAudioObjectRenderStream), wil::out_param_ptr<void **>(stream)));

    com_ptr_nothrow<ISpatialAudioObject> audioObjectFrontLeft;
    IF_FAILED_RETURN(stream->ActivateSpatialAudioObject(AudioObjectType_FrontLeft, &audioObjectFrontLeft));

    IF_FAILED_RETURN(stream->Start());

    UINT totalFrameCount = fmt->nSamplesPerSec * 2;

    bool isRendering = true;
    while (isRendering)
    {
        // Wait for a signal from the audio-engine to start the next processing pass
        if (WaitForSingleObject(event.get(), 100) != WAIT_OBJECT_0)
        {
            IF_FAILED_RETURN(stream->Reset());
        }
    
        UINT32 availableDynamicObjectCount = 0;
        UINT32 frameCount = 0;
    
        // Begin the process of sending object data and metadata
        // Get the number of dynamic objects that can be used to send object-data
        // Get the frame count that each buffer will be filled with 
        IF_FAILED_RETURN(stream->BeginUpdatingAudioObjects(&availableDynamicObjectCount, &frameCount));
    
        BYTE* buffer = nullptr;
        UINT32 bufferLength = 0;
    
        if (audioObjectFrontLeft == nullptr)
        {
            IF_FAILED_RETURN(stream->ActivateSpatialAudioObject(AudioObjectType::AudioObjectType_FrontLeft, &audioObjectFrontLeft));
        }
    
        // Get the buffer to write audio data
        IF_FAILED_RETURN(audioObjectFrontLeft->GetBuffer(&buffer, &bufferLength));
    
        if (totalFrameCount >= frameCount)
        {
            // Write audio data to the buffer
            WriteToAudioObjectBuffer(reinterpret_cast<float*>(buffer), frameCount, 200.0f, fmt->nSamplesPerSec);
    
            totalFrameCount -= frameCount;
        }
        else
        {
            // Write audio data to the buffer
            WriteToAudioObjectBuffer(reinterpret_cast<float*>(buffer), totalFrameCount, 750.0f, fmt->nSamplesPerSec);
    
            // Get a sample of the current AudioDG memory usage
            GetAudioDGMemoryUsageSample();

            // Set end of stream for the last buffer 
            IF_FAILED_RETURN(audioObjectFrontLeft->SetEndOfStream(totalFrameCount));
    
            audioObjectFrontLeft = nullptr; // Release the object
    
            isRendering = false;
        }
    
        // Let the audio engine know that the object data are available for processing now
        IF_FAILED_RETURN(stream->EndUpdatingAudioObjects());
    }

    return S_OK;
}

HRESULT BasicOffloadStreaming(IMMDevice* pEndpoint)
{
    com_ptr_nothrow<IAudioClient2> pAudioClient;
    wil::unique_cotaskmem_ptr<WAVEFORMATEX> mixFormat;
    BOOL bOffloadCapable = FALSE;

    if (pEndpoint == nullptr)
    {
        return E_INVALIDARG;
    }

    IF_FAILED_RETURN(pEndpoint->Activate(__uuidof(IAudioClient2), CLSCTX_ALL, NULL, (void**)&pAudioClient));
    IF_FAILED_RETURN(pAudioClient->IsOffloadCapable(AudioCategory_Media, &bOffloadCapable));

    AudioClientProperties clientProperties = { 0 };
    clientProperties.cbSize = sizeof(AudioClientProperties);
    clientProperties.bIsOffload = bOffloadCapable ? true : false;
    clientProperties.eCategory = AudioCategory_Media;

    if (bOffloadCapable)
    {
        clientProperties.bIsOffload = true;
    }

    IF_FAILED_RETURN(pAudioClient->SetClientProperties(&clientProperties));

    IF_FAILED_RETURN(pAudioClient->GetMixFormat(wil::out_param_ptr<WAVEFORMATEX **>(mixFormat)));

    IF_FAILED_RETURN(pAudioClient->Initialize(
        AUDCLNT_SHAREMODE_SHARED,
        AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
        0,
        0,
        mixFormat.get(),
        nullptr));

    com_ptr_nothrow<IAudioRenderClient> pRenderClient;
    IF_FAILED_RETURN(pAudioClient->GetService(_uuidof(IAudioRenderClient), wil::out_param_ptr<void **>(pRenderClient)));

    wil::unique_event bufferCompleteEvent;
    bufferCompleteEvent.create();
    IF_FAILED_RETURN(pAudioClient->SetEventHandle(bufferCompleteEvent.get()));

    UINT32 bufferFrameCount;
    REFERENCE_TIME duration = RandInRange(WAIT_TIME_MIN_FOR_THREAD_OPERATION, WAIT_TIME_MAX_FOR_THREAD_OPERATION);
    IF_FAILED_RETURN(pAudioClient->GetBufferSize(&bufferFrameCount));

    SineWave sw(mixFormat->nChannels, mixFormat->nSamplesPerSec);
    for (unsigned i = 0; i < mixFormat->nChannels; ++i)
    {
        sw.SetChannel(i, 400, 0.25f);
    }

    BYTE* data{};
    IF_FAILED_RETURN(pRenderClient->GetBuffer(bufferFrameCount, &data));

    sw.FillFrames(data, bufferFrameCount);
    IF_FAILED_RETURN(pRenderClient->ReleaseBuffer(bufferFrameCount, 0));

    IF_FAILED_RETURN(pAudioClient->Start());

    unsigned c = 0;
    while (c++ < duration)
    {
        if (WaitForSingleObject(bufferCompleteEvent.get(), ONE_SEC_IN_MS) != WAIT_OBJECT_0)
        {
            break;
        }

        unsigned numFramesPadding{};
        IF_FAILED_RETURN(pAudioClient->GetCurrentPadding(&numFramesPadding));
        auto numFramesAvailable = bufferFrameCount - numFramesPadding;

        IF_FAILED_RETURN(pRenderClient->GetBuffer(numFramesAvailable, &data));
        sw.FillFrames(data, numFramesAvailable);
        IF_FAILED_RETURN(pRenderClient->ReleaseBuffer(numFramesAvailable, 0));
    }

    // Get a sample of the current AudioDG memory usage
    GetAudioDGMemoryUsageSample();

    IF_FAILED_RETURN(pAudioClient->Stop());

    return S_OK;
}

void RunStressTest(int timeInSeconds, std::vector<wil::com_ptr<IMMDevice>>& pEndpoints)
{
    const UINT num = static_cast<UINT>(pEndpoints.size()) * NUMBER_OF_TESTS;

    std::vector<std::thread> threads(num);

    for (UINT i = 0; i < pEndpoints.size(); i++)
    {
        threads[i * NUMBER_OF_TESTS + 0] = std::thread([=](){
            BasicAudioStreaming(pEndpoints[i].get());
        });

        threads[i * NUMBER_OF_TESTS + 1] = std::thread([=](){
            BasicAudioStreaming(pEndpoints[i].get());
        });

        threads[i * NUMBER_OF_TESTS + 2] = std::thread([=](){
            BasicAudioStreaming(pEndpoints[i].get());
        });

        threads[i * NUMBER_OF_TESTS + 3] = std::thread([=](){
            BasicAudioCapture(pEndpoints[i].get());
        });

        threads[i * NUMBER_OF_TESTS + 4] = std::thread([=](){
            BasicAudioLoopback(pEndpoints[i].get());
        });

        threads[i * NUMBER_OF_TESTS + 5] = std::thread([=](){
            DisableEnableEndpoint(pEndpoints[i].get());
        });

        threads[i * NUMBER_OF_TESTS + 6] = std::thread([=](){
            BasicSpatialAudio(pEndpoints[i].get());
        });

        threads[i * NUMBER_OF_TESTS + 7] = std::thread([=](){
            BasicOffloadStreaming(pEndpoints[i].get());
        });
    }

    time_t timer;
    time(&timer);

    time_t endTime = timer + timeInSeconds;

    while (timer < endTime) 
    {
        for (UINT i = 0; i < num; i++)
        {
            if (threads[i].joinable())
            {
                UINT testNumber = i % NUMBER_OF_TESTS;
                UINT k = i / NUMBER_OF_TESTS;

                threads[i].join();

                switch (testNumber)
                {
                case 0:
                    threads[i] = std::thread([=]() {
                        Sleep(RandInRange(WAIT_TIME_MIN_FOR_THREAD_OPERATION, WAIT_TIME_MAX_FOR_THREAD_OPERATION));
                        BasicAudioStreaming(pEndpoints[k].get());
                    });
                    break;
                case 1:
                    threads[i] = std::thread([=]() {
                        Sleep(RandInRange(WAIT_TIME_MIN_FOR_THREAD_OPERATION, WAIT_TIME_MAX_FOR_THREAD_OPERATION));
                        BasicAudioStreaming(pEndpoints[k].get());
                    });
                    break;
                case 2:
                    threads[i] = std::thread([=]() {
                        Sleep(RandInRange(WAIT_TIME_MIN_FOR_THREAD_OPERATION, WAIT_TIME_MAX_FOR_THREAD_OPERATION));
                        BasicAudioStreaming(pEndpoints[k].get());
                    });
                    break;
                case 3:
                    threads[i] = std::thread([=]() {
                        Sleep(RandInRange(WAIT_TIME_MIN_FOR_THREAD_OPERATION, WAIT_TIME_MAX_FOR_THREAD_OPERATION));
                        BasicAudioCapture(pEndpoints[k].get());
                    });
                    break;
                case 4:
                    threads[i] = std::thread([=]() {
                        Sleep(RandInRange(WAIT_TIME_MIN_FOR_THREAD_OPERATION, WAIT_TIME_MAX_FOR_THREAD_OPERATION));
                        BasicAudioLoopback(pEndpoints[k].get());
                    });
                    break;
                case 5:
                    threads[i] = std::thread([=]() {
                        Sleep(RandInRange(WAIT_TIME_MIN_FOR_THREAD_OPERATION, WAIT_TIME_MAX_FOR_THREAD_OPERATION));
                        DisableEnableEndpoint(pEndpoints[k].get());
                    });
                    break;
                case 6:
                    threads[i] = std::thread([=]() {
                        Sleep(RandInRange(WAIT_TIME_MIN_FOR_THREAD_OPERATION, WAIT_TIME_MAX_FOR_THREAD_OPERATION));
                        BasicSpatialAudio(pEndpoints[k].get());
                    });
                    break;
                case 7:
                    threads[i] = std::thread([=]() {
                        Sleep(RandInRange(WAIT_TIME_MIN_FOR_THREAD_OPERATION, WAIT_TIME_MAX_FOR_THREAD_OPERATION));
                        BasicOffloadStreaming(pEndpoints[k].get());
                    });
                    break;
                }
            }
        }

        time(&timer);
    }

    for (UINT j = 0; j < num; j++)
    {
        if (threads[j].joinable())
        {
            threads[j].join();
        }
    }

    std::lock_guard<std::mutex> autoLock(maxAudioDGPagefileUsage_mutex);

    // If we were not able to open the AudioDG handle process we should have 0 as memory usage
    VERIFY_IS_TRUE(maxAudioDGPagefileUsage > 0);

    // Adding the maxPagefileUsageValue to the VERIFY as a string
    wchar_t maxAudioDGPagefileUsageString[32];
    swprintf_s(maxAudioDGPagefileUsageString, L"%u", maxAudioDGPagefileUsage);

    VERIFY_IS_TRUE(maxAudioDGPagefileUsage < MAX_ALLOWED_PAGEFILE_USAGE_IN_BYTES, maxAudioDGPagefileUsageString);
}