VirtualBox

source: vbox/trunk/src/VBox/Devices/Audio/DrvHostAudioWasApi.cpp@ 88983

Last change on this file since 88983 was 88959, checked in by vboxsync, 4 years ago

Audio/VaKit: Added driver backends for MacOS and Windows. bugref:10008

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 123.0 KB
Line 
1/* $Id: DrvHostAudioWasApi.cpp 88959 2021-05-10 07:19:31Z vboxsync $ */
2/** @file
3 * Host audio driver - Windows Audio Session API.
4 */
5
6/*
7 * Copyright (C) 2021 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18
19/*********************************************************************************************************************************
20* Header Files *
21*********************************************************************************************************************************/
22#define LOG_GROUP LOG_GROUP_DRV_HOST_AUDIO
23/*#define INITGUID - defined in VBoxhostAudioDSound.cpp already */
24#include <VBox/log.h>
25#include <iprt/win/windows.h>
26#include <Mmdeviceapi.h>
27#include <iprt/win/audioclient.h>
28#include <functiondiscoverykeys_devpkey.h>
29#include <AudioSessionTypes.h>
30#ifndef AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY
31# define AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY UINT32_C(0x08000000)
32#endif
33#ifndef AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM
34# define AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM UINT32_C(0x80000000)
35#endif
36
37#include <VBox/vmm/pdmaudioinline.h>
38#include <VBox/vmm/pdmaudiohostenuminline.h>
39
40#include <iprt/rand.h>
41#include <iprt/semaphore.h>
42#include <iprt/utf16.h>
43#include <iprt/uuid.h>
44
45#include <new> /* std::bad_alloc */
46
47#ifdef VBOX_AUDIO_VKAT
48# include "VBoxDDVKAT.h"
49#else
50# include "VBoxDD.h"
51#endif
52
53
54/*********************************************************************************************************************************
55* Defined Constants And Macros *
56*********************************************************************************************************************************/
57/** Max GetCurrentPadding value we accept (to make sure it's safe to convert to bytes). */
58#define VBOX_WASAPI_MAX_PADDING UINT32_C(0x007fffff)
59
60/** Maximum number of cached device configs in each direction.
61 * The number 4 was picked at random. */
62#define VBOX_WASAPI_MAX_TOTAL_CONFIG_ENTRIES 4
63
64#if 0
65/** @name WM_DRVHOSTAUDIOWAS_XXX - Worker thread messages.
66 * @{ */
67#define WM_DRVHOSTAUDIOWAS_PURGE_CACHE (WM_APP + 3)
68/** @} */
69#endif
70
71
72/** @name DRVHOSTAUDIOWAS_DO_XXX - Worker thread operations.
73 * @{ */
74#define DRVHOSTAUDIOWAS_DO_PURGE_CACHE ((uintptr_t)0x49f37300 + 1)
75#define DRVHOSTAUDIOWAS_DO_PRUNE_CACHE ((uintptr_t)0x49f37300 + 2)
76#define DRVHOSTAUDIOWAS_DO_STREAM_DEV_SWITCH ((uintptr_t)0x49f37300 + 3)
77/** @} */
78
79
80/*********************************************************************************************************************************
81* Structures and Typedefs *
82*********************************************************************************************************************************/
83class DrvHostAudioWasMmNotifyClient;
84
85/** Pointer to the cache entry for a host audio device (+dir). */
86typedef struct DRVHOSTAUDIOWASCACHEDEV *PDRVHOSTAUDIOWASCACHEDEV;
87
88/**
89 * Cached pre-initialized audio client for a device.
90 *
91 * The activation and initialization of an IAudioClient has been observed to be
92 * very very slow (> 100 ms) and not suitable to be done on an EMT. So, we'll
93 * pre-initialize the device clients at construction time and when the default
94 * device changes to try avoid this problem.
95 *
96 * A client is returned to the cache after we're done with it, provided it still
97 * works fine.
98 */
99typedef struct DRVHOSTAUDIOWASCACHEDEVCFG
100{
101 /** Entry in DRVHOSTAUDIOWASCACHEDEV::ConfigList. */
102 RTLISTNODE ListEntry;
103 /** The device. */
104 PDRVHOSTAUDIOWASCACHEDEV pDevEntry;
105 /** The cached audio client. */
106 IAudioClient *pIAudioClient;
107 /** Output streams: The render client interface. */
108 IAudioRenderClient *pIAudioRenderClient;
109 /** Input streams: The capture client interface. */
110 IAudioCaptureClient *pIAudioCaptureClient;
111 /** The configuration. */
112 PDMAUDIOPCMPROPS Props;
113 /** The buffer size in frames. */
114 uint32_t cFramesBufferSize;
115 /** The device/whatever period in frames. */
116 uint32_t cFramesPeriod;
117 /** The setup status code.
118 * This is set to VERR_AUDIO_STREAM_INIT_IN_PROGRESS while the asynchronous
119 * initialization is still running. */
120 int volatile rcSetup;
121 /** Creation timestamp (just for reference). */
122 uint64_t nsCreated;
123 /** Init complete timestamp (just for reference). */
124 uint64_t nsInited;
125 /** When it was last used. */
126 uint64_t nsLastUsed;
127 /** The stringified properties. */
128 char szProps[32];
129} DRVHOSTAUDIOWASCACHEDEVCFG;
130/** Pointer to a pre-initialized audio client. */
131typedef DRVHOSTAUDIOWASCACHEDEVCFG *PDRVHOSTAUDIOWASCACHEDEVCFG;
132
133/**
134 * Per audio device (+ direction) cache entry.
135 */
136typedef struct DRVHOSTAUDIOWASCACHEDEV
137{
138 /** Entry in DRVHOSTAUDIOWAS::CacheHead. */
139 RTLISTNODE ListEntry;
140 /** The MM device associated with the stream. */
141 IMMDevice *pIDevice;
142 /** The direction of the device. */
143 PDMAUDIODIR enmDir;
144#if 0 /* According to https://social.msdn.microsoft.com/Forums/en-US/1d974d90-6636-4121-bba3-a8861d9ab92a,
145 these were always support just missing from the SDK. */
146 /** Support for AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM: -1=unknown, 0=no, 1=yes. */
147 int8_t fSupportsAutoConvertPcm;
148 /** Support for AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY: -1=unknown, 0=no, 1=yes. */
149 int8_t fSupportsSrcDefaultQuality;
150#endif
151 /** List of cached configurations (DRVHOSTAUDIOWASCACHEDEVCFG). */
152 RTLISTANCHOR ConfigList;
153 /** The device ID length in RTUTF16 units. */
154 size_t cwcDevId;
155 /** The device ID. */
156 RTUTF16 wszDevId[RT_FLEXIBLE_ARRAY];
157} DRVHOSTAUDIOWASCACHEDEV;
158
159
160/**
161 * Data for a WASABI stream.
162 */
163typedef struct DRVHOSTAUDIOWASSTREAM
164{
165 /** Common part. */
166 PDMAUDIOBACKENDSTREAM Core;
167
168 /** Entry in DRVHOSTAUDIOWAS::StreamHead. */
169 RTLISTNODE ListEntry;
170 /** The stream's acquired configuration. */
171 PDMAUDIOSTREAMCFG Cfg;
172 /** Cache entry to be relased when destroying the stream. */
173 PDRVHOSTAUDIOWASCACHEDEVCFG pDevCfg;
174
175 /** Set if the stream is enabled. */
176 bool fEnabled;
177 /** Set if the stream is started (playing/capturing). */
178 bool fStarted;
179 /** Set if the stream is draining (output only). */
180 bool fDraining;
181 /** Set if we should restart the stream on resume (saved pause state). */
182 bool fRestartOnResume;
183 /** Set if we're switching to a new output/input device. */
184 bool fSwitchingDevice;
185
186 /** The RTTimeMilliTS() deadline for the draining of this stream (output). */
187 uint64_t msDrainDeadline;
188 /** Internal stream offset (bytes). */
189 uint64_t offInternal;
190 /** The RTTimeMilliTS() at the end of the last transfer. */
191 uint64_t msLastTransfer;
192
193 /** Input: Current capture buffer (advanced as we read). */
194 uint8_t *pbCapture;
195 /** Input: The number of bytes left in the current capture buffer. */
196 uint32_t cbCapture;
197 /** Input: The full size of what pbCapture is part of (for ReleaseBuffer). */
198 uint32_t cFramesCaptureToRelease;
199
200 /** Critical section protecting: . */
201 RTCRITSECT CritSect;
202 /** Buffer that drvHostWasStreamStatusString uses. */
203 char szStatus[128];
204} DRVHOSTAUDIOWASSTREAM;
205/** Pointer to a WASABI stream. */
206typedef DRVHOSTAUDIOWASSTREAM *PDRVHOSTAUDIOWASSTREAM;
207
208
209/**
210 * WASAPI-specific device entry.
211 */
212typedef struct DRVHOSTAUDIOWASDEV
213{
214 /** The core structure. */
215 PDMAUDIOHOSTDEV Core;
216 /** The device ID (flexible length). */
217 RTUTF16 wszDevId[RT_FLEXIBLE_ARRAY];
218} DRVHOSTAUDIOWASDEV;
219/** Pointer to a DirectSound device entry. */
220typedef DRVHOSTAUDIOWASDEV *PDRVHOSTAUDIOWASDEV;
221
222
223/**
224 * Data for a WASAPI host audio instance.
225 */
226typedef struct DRVHOSTAUDIOWAS
227{
228 /** The audio host audio interface we export. */
229 PDMIHOSTAUDIO IHostAudio;
230 /** Pointer to the PDM driver instance. */
231 PPDMDRVINS pDrvIns;
232 /** Audio device enumerator instance that we use for getting the default
233 * devices (or specific ones if overriden by config). Also used for
234 * implementing enumeration. */
235 IMMDeviceEnumerator *pIEnumerator;
236 /** The upwards interface. */
237 PPDMIHOSTAUDIOPORT pIHostAudioPort;
238 /** The output device ID, NULL for default. */
239 PRTUTF16 pwszOutputDevId;
240 /** The input device ID, NULL for default. */
241 PRTUTF16 pwszInputDevId;
242
243 /** Pointer to the MM notification client instance. */
244 DrvHostAudioWasMmNotifyClient *pNotifyClient;
245 /** The input device to use. This can be NULL if there wasn't a suitable one
246 * around when we last looked or if it got removed/disabled/whatever.
247 * All access must be done inside the pNotifyClient critsect. */
248 IMMDevice *pIDeviceInput;
249 /** The output device to use. This can be NULL if there wasn't a suitable one
250 * around when we last looked or if it got removed/disabled/whatever.
251 * All access must be done inside the pNotifyClient critsect. */
252 IMMDevice *pIDeviceOutput;
253
254 /** A drain stop timer that makes sure a draining stream will be properly
255 * stopped (mainly for clean state and to reduce resource usage). */
256 TMTIMERHANDLE hDrainTimer;
257 /** List of streams (DRVHOSTAUDIOWASSTREAM).
258 * Requires CritSect ownership. */
259 RTLISTANCHOR StreamHead;
260 /** Serializing access to StreamHead. */
261 RTCRITSECTRW CritSectStreamList;
262
263 /** List of cached devices (DRVHOSTAUDIOWASCACHEDEV).
264 * Protected by CritSectCache */
265 RTLISTANCHOR CacheHead;
266 /** Serializing access to CacheHead. */
267 RTCRITSECT CritSectCache;
268 /** Semaphore for signalling that cache purge is done and that the destructor
269 * can do cleanups. */
270 RTSEMEVENTMULTI hEvtCachePurge;
271 /** Total number of device config entire for capturing.
272 * This includes in-use ones. */
273 uint32_t volatile cCacheEntriesIn;
274 /** Total number of device config entire for playback.
275 * This includes in-use ones. */
276 uint32_t volatile cCacheEntriesOut;
277
278#if 0
279 /** The worker thread. */
280 RTTHREAD hWorkerThread;
281 /** The TID of the worker thread (for posting messages to it). */
282 DWORD idWorkerThread;
283 /** The fixed wParam value for the worker thread. */
284 WPARAM uWorkerThreadFixedParam;
285#endif
286} DRVHOSTAUDIOWAS;
287/** Pointer to the data for a WASAPI host audio driver instance. */
288typedef DRVHOSTAUDIOWAS *PDRVHOSTAUDIOWAS;
289
290
291
292
293/**
294 * Gets the stream status.
295 *
296 * @returns Pointer to stream status string.
297 * @param pStreamWas The stream to get the status for.
298 */
299static const char *drvHostWasStreamStatusString(PDRVHOSTAUDIOWASSTREAM pStreamWas)
300{
301 static RTSTRTUPLE const s_aEnable[2] =
302 {
303 RT_STR_TUPLE("DISABLED"),
304 RT_STR_TUPLE("ENABLED ")
305 };
306 PCRTSTRTUPLE pTuple = &s_aEnable[pStreamWas->fEnabled];
307 memcpy(pStreamWas->szStatus, pTuple->psz, pTuple->cch);
308 size_t off = pTuple->cch;
309
310 static RTSTRTUPLE const s_aStarted[2] =
311 {
312 RT_STR_TUPLE(" STOPPED"),
313 RT_STR_TUPLE(" STARTED")
314 };
315 pTuple = &s_aStarted[pStreamWas->fStarted];
316 memcpy(&pStreamWas->szStatus[off], pTuple->psz, pTuple->cch);
317 off += pTuple->cch;
318
319 static RTSTRTUPLE const s_aDraining[2] =
320 {
321 RT_STR_TUPLE(""),
322 RT_STR_TUPLE(" DRAINING")
323 };
324 pTuple = &s_aDraining[pStreamWas->fDraining];
325 memcpy(&pStreamWas->szStatus[off], pTuple->psz, pTuple->cch);
326 off += pTuple->cch;
327
328 pStreamWas->szStatus[off] = '\0';
329 return pStreamWas->szStatus;
330}
331
332
333/*********************************************************************************************************************************
334* IMMNotificationClient implementation
335*********************************************************************************************************************************/
336/**
337 * Multimedia notification client.
338 *
339 * We want to know when the default device changes so we can switch running
340 * streams to use the new one and so we can pre-activate it in preparation
341 * for new streams.
342 */
343class DrvHostAudioWasMmNotifyClient : public IMMNotificationClient
344{
345private:
346 /** Reference counter. */
347 uint32_t volatile m_cRefs;
348 /** The WASAPI host audio driver instance data.
349 * @note This can be NULL. Only access after entering critical section. */
350 PDRVHOSTAUDIOWAS m_pDrvWas;
351 /** Critical section serializing access to m_pDrvWas. */
352 RTCRITSECT m_CritSect;
353
354public:
355 /**
356 * @throws int on critical section init failure.
357 */
358 DrvHostAudioWasMmNotifyClient(PDRVHOSTAUDIOWAS a_pDrvWas)
359 : m_cRefs(1)
360 , m_pDrvWas(a_pDrvWas)
361 {
362 int rc = RTCritSectInit(&m_CritSect);
363 AssertRCStmt(rc, throw(rc));
364 }
365
366 virtual ~DrvHostAudioWasMmNotifyClient() RT_NOEXCEPT
367 {
368 RTCritSectDelete(&m_CritSect);
369 }
370
371 /**
372 * Called by drvHostAudioWasDestruct to set m_pDrvWas to NULL.
373 */
374 void notifyDriverDestroyed() RT_NOEXCEPT
375 {
376 RTCritSectEnter(&m_CritSect);
377 m_pDrvWas = NULL;
378 RTCritSectLeave(&m_CritSect);
379 }
380
381 /**
382 * Enters the notification critsect for getting at the IMMDevice members in
383 * PDMHOSTAUDIOWAS.
384 */
385 void lockEnter() RT_NOEXCEPT
386 {
387 RTCritSectEnter(&m_CritSect);
388 }
389
390 /**
391 * Leaves the notification critsect.
392 */
393 void lockLeave() RT_NOEXCEPT
394 {
395 RTCritSectLeave(&m_CritSect);
396 }
397
398 /** @name IUnknown interface
399 * @{ */
400 IFACEMETHODIMP_(ULONG) AddRef()
401 {
402 uint32_t cRefs = ASMAtomicIncU32(&m_cRefs);
403 AssertMsg(cRefs < 64, ("%#x\n", cRefs));
404 Log6Func(("returns %u\n", cRefs));
405 return cRefs;
406 }
407
408 IFACEMETHODIMP_(ULONG) Release()
409 {
410 uint32_t cRefs = ASMAtomicDecU32(&m_cRefs);
411 AssertMsg(cRefs < 64, ("%#x\n", cRefs));
412 if (cRefs == 0)
413 delete this;
414 Log6Func(("returns %u\n", cRefs));
415 return cRefs;
416 }
417
418 IFACEMETHODIMP QueryInterface(const IID &rIID, void **ppvInterface)
419 {
420 if (IsEqualIID(rIID, IID_IUnknown))
421 *ppvInterface = static_cast<IUnknown *>(this);
422 else if (IsEqualIID(rIID, __uuidof(IMMNotificationClient)))
423 *ppvInterface = static_cast<IMMNotificationClient *>(this);
424 else
425 {
426 LogFunc(("Unknown rIID={%RTuuid}\n", &rIID));
427 *ppvInterface = NULL;
428 return E_NOINTERFACE;
429 }
430 Log6Func(("returns S_OK + %p\n", *ppvInterface));
431 return S_OK;
432 }
433 /** @} */
434
435 /** @name IMMNotificationClient interface
436 * @{ */
437 IFACEMETHODIMP OnDeviceStateChanged(LPCWSTR pwszDeviceId, DWORD dwNewState)
438 {
439 RT_NOREF(pwszDeviceId, dwNewState);
440 Log7Func(("pwszDeviceId=%ls dwNewState=%u (%#x)\n", pwszDeviceId, dwNewState, dwNewState));
441
442 /*
443 * Just trigger device re-enumeration.
444 */
445 notifyDeviceChanges();
446
447 /** @todo do we need to check for our devices here too? Not when using a
448 * default device. But when using a specific device, we could perhaps
449 * re-init the stream when dwNewState indicates precense. We might
450 * also take action when a devices ceases to be operating, but again
451 * only for non-default devices, probably... */
452
453 return S_OK;
454 }
455
456 IFACEMETHODIMP OnDeviceAdded(LPCWSTR pwszDeviceId)
457 {
458 RT_NOREF(pwszDeviceId);
459 Log7Func(("pwszDeviceId=%ls\n", pwszDeviceId));
460
461 /*
462 * Is this a device we're interested in? Grab the enumerator if it is.
463 */
464 bool fOutput = false;
465 IMMDeviceEnumerator *pIEnumerator = NULL;
466 RTCritSectEnter(&m_CritSect);
467 if ( m_pDrvWas != NULL
468 && ( (fOutput = RTUtf16ICmp(m_pDrvWas->pwszOutputDevId, pwszDeviceId) == 0)
469 || RTUtf16ICmp(m_pDrvWas->pwszInputDevId, pwszDeviceId) == 0))
470 {
471 pIEnumerator = m_pDrvWas->pIEnumerator;
472 if (pIEnumerator /* paranoia */)
473 pIEnumerator->AddRef();
474 }
475 RTCritSectLeave(&m_CritSect);
476 if (pIEnumerator)
477 {
478 /*
479 * Get the device and update it.
480 */
481 IMMDevice *pIDevice = NULL;
482 HRESULT hrc = pIEnumerator->GetDevice(pwszDeviceId, &pIDevice);
483 if (SUCCEEDED(hrc))
484 setDevice(fOutput, pIDevice, pwszDeviceId, __PRETTY_FUNCTION__);
485 else
486 LogRelMax(64, ("WasAPI: Failed to get %s device '%ls' (OnDeviceAdded): %Rhrc\n",
487 fOutput ? "output" : "input", pwszDeviceId, hrc));
488 pIEnumerator->Release();
489
490 /*
491 * Trigger device re-enumeration.
492 */
493 notifyDeviceChanges();
494 }
495 return S_OK;
496 }
497
498 IFACEMETHODIMP OnDeviceRemoved(LPCWSTR pwszDeviceId)
499 {
500 RT_NOREF(pwszDeviceId);
501 Log7Func(("pwszDeviceId=%ls\n", pwszDeviceId));
502
503 /*
504 * Is this a device we're interested in? Then set it to NULL.
505 */
506 bool fOutput = false;
507 RTCritSectEnter(&m_CritSect);
508 if ( m_pDrvWas != NULL
509 && ( (fOutput = RTUtf16ICmp(m_pDrvWas->pwszOutputDevId, pwszDeviceId) == 0)
510 || RTUtf16ICmp(m_pDrvWas->pwszInputDevId, pwszDeviceId) == 0))
511 {
512 RTCritSectLeave(&m_CritSect);
513 setDevice(fOutput, NULL, pwszDeviceId, __PRETTY_FUNCTION__);
514 }
515 else
516 RTCritSectLeave(&m_CritSect);
517
518 /*
519 * Trigger device re-enumeration.
520 */
521 notifyDeviceChanges();
522 return S_OK;
523 }
524
525 IFACEMETHODIMP OnDefaultDeviceChanged(EDataFlow enmFlow, ERole enmRole, LPCWSTR pwszDefaultDeviceId)
526 {
527 /*
528 * Are we interested in this device? If so grab the enumerator.
529 */
530 IMMDeviceEnumerator *pIEnumerator = NULL;
531 RTCritSectEnter(&m_CritSect);
532 if ( m_pDrvWas != NULL
533 && ( (enmFlow == eRender && enmRole == eMultimedia && !m_pDrvWas->pwszOutputDevId)
534 || (enmFlow == eCapture && enmRole == eMultimedia && !m_pDrvWas->pwszInputDevId)))
535 {
536 pIEnumerator = m_pDrvWas->pIEnumerator;
537 if (pIEnumerator /* paranoia */)
538 pIEnumerator->AddRef();
539 }
540 RTCritSectLeave(&m_CritSect);
541 if (pIEnumerator)
542 {
543 /*
544 * Get the device and update it.
545 */
546 IMMDevice *pIDevice = NULL;
547 HRESULT hrc = pIEnumerator->GetDefaultAudioEndpoint(enmFlow, enmRole, &pIDevice);
548 if (SUCCEEDED(hrc))
549 setDevice(enmFlow == eRender, pIDevice, pwszDefaultDeviceId, __PRETTY_FUNCTION__);
550 else
551 LogRelMax(64, ("WasAPI: Failed to get default %s device (OnDefaultDeviceChange): %Rhrc\n",
552 enmFlow == eRender ? "output" : "input", hrc));
553 pIEnumerator->Release();
554
555 /*
556 * Trigger device re-enumeration.
557 */
558 notifyDeviceChanges();
559 }
560
561 Log7Func(("enmFlow=%d enmRole=%d pwszDefaultDeviceId=%ls\n", enmFlow, enmRole, pwszDefaultDeviceId));
562 return S_OK;
563 }
564
565 IFACEMETHODIMP OnPropertyValueChanged(LPCWSTR pwszDeviceId, const PROPERTYKEY Key)
566 {
567 RT_NOREF(pwszDeviceId, Key);
568 Log7Func(("pwszDeviceId=%ls Key={%RTuuid, %u (%#x)}\n", pwszDeviceId, &Key.fmtid, Key.pid, Key.pid));
569 return S_OK;
570 }
571 /** @} */
572
573private:
574 /**
575 * Sets DRVHOSTAUDIOWAS::pIDeviceOutput or DRVHOSTAUDIOWAS::pIDeviceInput to @a pIDevice.
576 */
577 void setDevice(bool fOutput, IMMDevice *pIDevice, LPCWSTR pwszDeviceId, const char *pszCaller)
578 {
579 RT_NOREF(pszCaller, pwszDeviceId);
580
581 RTCritSectEnter(&m_CritSect);
582
583 /*
584 * Update our internal device reference.
585 */
586 if (m_pDrvWas)
587 {
588 if (fOutput)
589 {
590 Log7((LOG_FN_FMT ": Changing output device from %p to %p (%ls)\n",
591 pszCaller, m_pDrvWas->pIDeviceOutput, pIDevice, pwszDeviceId));
592 if (m_pDrvWas->pIDeviceOutput)
593 m_pDrvWas->pIDeviceOutput->Release();
594 m_pDrvWas->pIDeviceOutput = pIDevice;
595 }
596 else
597 {
598 Log7((LOG_FN_FMT ": Changing input device from %p to %p (%ls)\n",
599 pszCaller, m_pDrvWas->pIDeviceInput, pIDevice, pwszDeviceId));
600 if (m_pDrvWas->pIDeviceInput)
601 m_pDrvWas->pIDeviceInput->Release();
602 m_pDrvWas->pIDeviceInput = pIDevice;
603 }
604 }
605 else if (pIDevice)
606 pIDevice->Release();
607
608 /*
609 * Tell DrvAudio that the device has changed for one of the directions.
610 *
611 * We have to exit the critsect when doing so, or we'll create a locking
612 * order violation. So, try make sure the VM won't be destroyed while
613 * till DrvAudio have entered its critical section...
614 */
615 if (m_pDrvWas)
616 {
617 PPDMIHOSTAUDIOPORT const pIHostAudioPort = m_pDrvWas->pIHostAudioPort;
618 if (pIHostAudioPort)
619 {
620 VMSTATE const enmVmState = PDMDrvHlpVMState(m_pDrvWas->pDrvIns);
621 if (enmVmState < VMSTATE_POWERING_OFF)
622 {
623 RTCritSectLeave(&m_CritSect);
624 pIHostAudioPort->pfnNotifyDeviceChanged(pIHostAudioPort, fOutput ? PDMAUDIODIR_OUT : PDMAUDIODIR_IN, NULL);
625 return;
626 }
627 LogFlowFunc(("Ignoring change: enmVmState=%d\n", enmVmState));
628 }
629 }
630
631 RTCritSectLeave(&m_CritSect);
632 }
633
634 /**
635 * Tell DrvAudio to re-enumerate devices when it get a chance.
636 *
637 * We exit the critsect here too before calling DrvAudio just to be on the safe
638 * side (see setDevice()), even though the current DrvAudio code doesn't take
639 * any critsects.
640 */
641 void notifyDeviceChanges(void)
642 {
643 RTCritSectEnter(&m_CritSect);
644 if (m_pDrvWas)
645 {
646 PPDMIHOSTAUDIOPORT const pIHostAudioPort = m_pDrvWas->pIHostAudioPort;
647 if (pIHostAudioPort)
648 {
649 VMSTATE const enmVmState = PDMDrvHlpVMState(m_pDrvWas->pDrvIns);
650 if (enmVmState < VMSTATE_POWERING_OFF)
651 {
652 RTCritSectLeave(&m_CritSect);
653 pIHostAudioPort->pfnNotifyDevicesChanged(pIHostAudioPort);
654 return;
655 }
656 LogFlowFunc(("Ignoring change: enmVmState=%d\n", enmVmState));
657 }
658 }
659 RTCritSectLeave(&m_CritSect);
660 }
661};
662
663
664/*********************************************************************************************************************************
665* Pre-configured audio client cache. *
666*********************************************************************************************************************************/
667#define WAS_CACHE_MAX_ENTRIES_SAME_DEVICE 2
668
669/**
670 * Converts from PDM stream config to windows WAVEFORMATEX struct.
671 *
672 * @param pProps The PDM audio PCM properties to convert from.
673 * @param pFmt The windows structure to initialize.
674 */
675static void drvHostAudioWasWaveFmtExFromProps(PCPDMAUDIOPCMPROPS pProps, PWAVEFORMATEX pFmt)
676{
677 RT_ZERO(*pFmt);
678 pFmt->wFormatTag = WAVE_FORMAT_PCM;
679 pFmt->nChannels = PDMAudioPropsChannels(pProps);
680 pFmt->wBitsPerSample = PDMAudioPropsSampleBits(pProps);
681 pFmt->nSamplesPerSec = PDMAudioPropsHz(pProps);
682 pFmt->nBlockAlign = PDMAudioPropsFrameSize(pProps);
683 pFmt->nAvgBytesPerSec = PDMAudioPropsFramesToBytes(pProps, PDMAudioPropsHz(pProps));
684 pFmt->cbSize = 0; /* No extra data specified. */
685}
686
687
688#if 0 /* unused */
689/**
690 * Converts from windows WAVEFORMATEX and stream props to PDM audio properties.
691 *
692 * @returns VINF_SUCCESS on success, VERR_AUDIO_STREAM_COULD_NOT_CREATE if not
693 * supported.
694 * @param pProps The output properties structure.
695 * @param pFmt The windows wave format structure.
696 * @param pszStream The stream name for error logging.
697 * @param pwszDevId The device ID for error logging.
698 */
699static int drvHostAudioWasCacheWaveFmtExToProps(PPDMAUDIOPCMPROPS pProps, WAVEFORMATEX const *pFmt,
700 const char *pszStream, PCRTUTF16 pwszDevId)
701{
702 if (pFmt->wFormatTag == WAVE_FORMAT_PCM)
703 {
704 if ( pFmt->wBitsPerSample == 8
705 || pFmt->wBitsPerSample == 16
706 || pFmt->wBitsPerSample == 32)
707 {
708 if (pFmt->nChannels > 0 && pFmt->nChannels < 16)
709 {
710 if (pFmt->nSamplesPerSec >= 4096 && pFmt->nSamplesPerSec <= 768000)
711 {
712 PDMAudioPropsInit(pProps, pFmt->wBitsPerSample / 8, true /*fSigned*/, pFmt->nChannels, pFmt->nSamplesPerSec);
713 if (PDMAudioPropsFrameSize(pProps) == pFmt->nBlockAlign)
714 return VINF_SUCCESS;
715 }
716 }
717 }
718 }
719 LogRelMax(64, ("WasAPI: Error! Unsupported stream format for '%s' suggested by '%ls':\n"
720 "WasAPI: wFormatTag = %RU16 (expected %d)\n"
721 "WasAPI: nChannels = %RU16 (expected 1..15)\n"
722 "WasAPI: nSamplesPerSec = %RU32 (expected 4096..768000)\n"
723 "WasAPI: nAvgBytesPerSec = %RU32\n"
724 "WasAPI: nBlockAlign = %RU16\n"
725 "WasAPI: wBitsPerSample = %RU16 (expected 8, 16, or 32)\n"
726 "WasAPI: cbSize = %RU16\n",
727 pszStream, pwszDevId, pFmt->wFormatTag, WAVE_FORMAT_PCM, pFmt->nChannels, pFmt->nSamplesPerSec, pFmt->nAvgBytesPerSec,
728 pFmt->nBlockAlign, pFmt->wBitsPerSample, pFmt->cbSize));
729 return VERR_AUDIO_STREAM_COULD_NOT_CREATE;
730}
731#endif
732
733
734/**
735 * Destroys a devie config cache entry.
736 *
737 * @param pThis The WASAPI host audio driver instance data.
738 * @param pDevCfg Device config entry. Must not be in the list.
739 */
740static void drvHostAudioWasCacheDestroyDevConfig(PDRVHOSTAUDIOWAS pThis, PDRVHOSTAUDIOWASCACHEDEVCFG pDevCfg)
741{
742 if (pDevCfg->pDevEntry->enmDir == PDMAUDIODIR_IN)
743 ASMAtomicDecU32(&pThis->cCacheEntriesIn);
744 else
745 ASMAtomicDecU32(&pThis->cCacheEntriesOut);
746
747 uint32_t cTypeClientRefs = 0;
748 if (pDevCfg->pIAudioCaptureClient)
749 {
750 cTypeClientRefs = pDevCfg->pIAudioCaptureClient->Release();
751 pDevCfg->pIAudioCaptureClient = NULL;
752 }
753
754 if (pDevCfg->pIAudioRenderClient)
755 {
756 cTypeClientRefs = pDevCfg->pIAudioRenderClient->Release();
757 pDevCfg->pIAudioRenderClient = NULL;
758 }
759
760 uint32_t cClientRefs = 0;
761 if (pDevCfg->pIAudioClient /* paranoia */)
762 {
763 cClientRefs = pDevCfg->pIAudioClient->Release();
764 pDevCfg->pIAudioClient = NULL;
765 }
766
767 Log8Func(("Destroying cache config entry: '%ls: %s' - cClientRefs=%u cTypeClientRefs=%u\n",
768 pDevCfg->pDevEntry->wszDevId, pDevCfg->szProps, cClientRefs, cTypeClientRefs));
769 RT_NOREF(cClientRefs, cTypeClientRefs);
770
771 pDevCfg->pDevEntry = NULL;
772 RTMemFree(pDevCfg);
773}
774
775
776/**
777 * Destroys a device cache entry.
778 *
779 * @param pThis The WASAPI host audio driver instance data.
780 * @param pDevEntry The device entry. Must not be in the cache!
781 */
782static void drvHostAudioWasCacheDestroyDevEntry(PDRVHOSTAUDIOWAS pThis, PDRVHOSTAUDIOWASCACHEDEV pDevEntry)
783{
784 Log8Func(("Destroying cache entry: %p - '%ls'\n", pDevEntry, pDevEntry->wszDevId));
785
786 PDRVHOSTAUDIOWASCACHEDEVCFG pDevCfg, pDevCfgNext;
787 RTListForEachSafe(&pDevEntry->ConfigList, pDevCfg, pDevCfgNext, DRVHOSTAUDIOWASCACHEDEVCFG, ListEntry)
788 {
789 drvHostAudioWasCacheDestroyDevConfig(pThis, pDevCfg);
790 }
791
792 uint32_t cDevRefs = 0;
793 if (pDevEntry->pIDevice /* paranoia */)
794 {
795 cDevRefs = pDevEntry->pIDevice->Release();
796 pDevEntry->pIDevice = NULL;
797 }
798
799 pDevEntry->cwcDevId = 0;
800 pDevEntry->wszDevId[0] = '\0';
801 RTMemFree(pDevEntry);
802 Log8Func(("Destroyed cache entry: %p cDevRefs=%u\n", pDevEntry, cDevRefs));
803}
804
805
806/**
807 * Prunes the cache.
808 */
809static void drvHostAudioWasCachePrune(PDRVHOSTAUDIOWAS pThis)
810{
811 /*
812 * Prune each direction separately.
813 */
814 struct
815 {
816 PDMAUDIODIR enmDir;
817 uint32_t volatile *pcEntries;
818 } aWork[] = { { PDMAUDIODIR_IN, &pThis->cCacheEntriesIn }, { PDMAUDIODIR_OUT, &pThis->cCacheEntriesOut }, };
819 for (uint32_t iWork = 0; iWork < RT_ELEMENTS(aWork); iWork++)
820 {
821 /*
822 * Remove the least recently used entry till we're below the threshold
823 * or there are no more inactive entries.
824 */
825 LogFlowFunc(("iWork=%u cEntries=%u\n", iWork, *aWork[iWork].pcEntries));
826 while (*aWork[iWork].pcEntries > VBOX_WASAPI_MAX_TOTAL_CONFIG_ENTRIES)
827 {
828 RTCritSectEnter(&pThis->CritSectCache);
829 PDRVHOSTAUDIOWASCACHEDEVCFG pLeastRecentlyUsed = NULL;
830 PDRVHOSTAUDIOWASCACHEDEV pDevEntry;
831 RTListForEach(&pThis->CacheHead, pDevEntry, DRVHOSTAUDIOWASCACHEDEV, ListEntry)
832 {
833 if (pDevEntry->enmDir == aWork[iWork].enmDir)
834 {
835 PDRVHOSTAUDIOWASCACHEDEVCFG pHeadCfg = RTListGetFirst(&pDevEntry->ConfigList,
836 DRVHOSTAUDIOWASCACHEDEVCFG, ListEntry);
837 if ( pHeadCfg
838 && (!pLeastRecentlyUsed || pHeadCfg->nsLastUsed < pLeastRecentlyUsed->nsLastUsed))
839 pLeastRecentlyUsed = pHeadCfg;
840 }
841 }
842 if (pLeastRecentlyUsed)
843 RTListNodeRemove(&pLeastRecentlyUsed->ListEntry);
844 RTCritSectLeave(&pThis->CritSectCache);
845
846 if (!pLeastRecentlyUsed)
847 break;
848 drvHostAudioWasCacheDestroyDevConfig(pThis, pLeastRecentlyUsed);
849 }
850 }
851}
852
853
854/**
855 * Purges all the entries in the cache.
856 */
857static void drvHostAudioWasCachePurge(PDRVHOSTAUDIOWAS pThis, bool fOnWorker)
858{
859 for (;;)
860 {
861 RTCritSectEnter(&pThis->CritSectCache);
862 PDRVHOSTAUDIOWASCACHEDEV pDevEntry = RTListRemoveFirst(&pThis->CacheHead, DRVHOSTAUDIOWASCACHEDEV, ListEntry);
863 RTCritSectLeave(&pThis->CritSectCache);
864 if (!pDevEntry)
865 break;
866 drvHostAudioWasCacheDestroyDevEntry(pThis, pDevEntry);
867 }
868
869 if (fOnWorker)
870 {
871 int rc = RTSemEventMultiSignal(pThis->hEvtCachePurge);
872 AssertRC(rc);
873 }
874}
875
876
877/**
878 * Looks up a specific configuration.
879 *
880 * @returns Pointer to the device config (removed from cache) on success. NULL
881 * if no matching config found.
882 * @param pDevEntry Where to perform the lookup.
883 * @param pProps The config properties to match.
884 */
885static PDRVHOSTAUDIOWASCACHEDEVCFG
886drvHostAudioWasCacheLookupLocked(PDRVHOSTAUDIOWASCACHEDEV pDevEntry, PCPDMAUDIOPCMPROPS pProps)
887{
888 PDRVHOSTAUDIOWASCACHEDEVCFG pDevCfg;
889 RTListForEach(&pDevEntry->ConfigList, pDevCfg, DRVHOSTAUDIOWASCACHEDEVCFG, ListEntry)
890 {
891 if (PDMAudioPropsAreEqual(&pDevCfg->Props, pProps))
892 {
893 RTListNodeRemove(&pDevCfg->ListEntry);
894 pDevCfg->nsLastUsed = RTTimeNanoTS();
895 return pDevCfg;
896 }
897 }
898 return NULL;
899}
900
901
902/**
903 * Initializes a device config entry.
904 *
905 * This is usually done on the worker thread.
906 *
907 * @returns VBox status code.
908 * @param pDevCfg The device configuration entry to initialize.
909 */
910static int drvHostAudioWasCacheInitConfig(PDRVHOSTAUDIOWASCACHEDEVCFG pDevCfg)
911{
912 /*
913 * Assert some sanity given that we migth be called on the worker thread
914 * and pDevCfg being a message parameter.
915 */
916 AssertPtrReturn(pDevCfg, VERR_INTERNAL_ERROR_2);
917 AssertReturn(pDevCfg->rcSetup == VERR_AUDIO_STREAM_INIT_IN_PROGRESS, VERR_INTERNAL_ERROR_2);
918 AssertReturn(pDevCfg->pIAudioClient == NULL, VERR_INTERNAL_ERROR_2);
919 AssertReturn(pDevCfg->pIAudioCaptureClient == NULL, VERR_INTERNAL_ERROR_2);
920 AssertReturn(pDevCfg->pIAudioRenderClient == NULL, VERR_INTERNAL_ERROR_2);
921 AssertReturn(PDMAudioPropsAreValid(&pDevCfg->Props), VERR_INTERNAL_ERROR_2);
922
923 PDRVHOSTAUDIOWASCACHEDEV pDevEntry = pDevCfg->pDevEntry;
924 AssertPtrReturn(pDevEntry, VERR_INTERNAL_ERROR_2);
925 AssertPtrReturn(pDevEntry->pIDevice, VERR_INTERNAL_ERROR_2);
926 AssertReturn(pDevEntry->enmDir == PDMAUDIODIR_IN || pDevEntry->enmDir == PDMAUDIODIR_OUT, VERR_INTERNAL_ERROR_2);
927
928 /*
929 * First we need an IAudioClient interface for calling IsFormatSupported
930 * on so we can get guidance as to what to do next.
931 *
932 * Initially, I thought the AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM was not
933 * supported all the way back to Vista and that we'd had to try different
934 * things here to get the most optimal format. However, according to
935 * https://social.msdn.microsoft.com/Forums/en-US/1d974d90-6636-4121-bba3-a8861d9ab92a
936 * it is supported, just maybe missing from the SDK or something...
937 *
938 * I'll leave the IsFormatSupported call here as it gives us a clue as to
939 * what exactly the WAS needs to convert our audio stream into/from.
940 */
941 Log8Func(("Activating an IAudioClient for '%ls' ...\n", pDevEntry->wszDevId));
942 IAudioClient *pIAudioClient = NULL;
943 HRESULT hrc = pDevEntry->pIDevice->Activate(__uuidof(IAudioClient), CLSCTX_ALL,
944 NULL /*pActivationParams*/, (void **)&pIAudioClient);
945 Log8Func(("Activate('%ls', IAudioClient) -> %Rhrc\n", pDevEntry->wszDevId, hrc));
946 if (FAILED(hrc))
947 {
948 LogRelMax(64, ("WasAPI: Activate(%ls, IAudioClient) failed: %Rhrc\n", pDevEntry->wszDevId, hrc));
949 pDevCfg->nsInited = RTTimeNanoTS();
950 pDevCfg->nsLastUsed = pDevCfg->nsInited;
951 return pDevCfg->rcSetup = VERR_AUDIO_STREAM_COULD_NOT_CREATE;
952 }
953
954 WAVEFORMATEX WaveFmtEx;
955 drvHostAudioWasWaveFmtExFromProps(&pDevCfg->Props, &WaveFmtEx);
956
957 PWAVEFORMATEX pClosestMatch = NULL;
958 hrc = pIAudioClient->IsFormatSupported(AUDCLNT_SHAREMODE_SHARED, &WaveFmtEx, &pClosestMatch);
959
960 /*
961 * If the format is supported, go ahead and initialize the client instance.
962 */
963 if (SUCCEEDED(hrc))
964 {
965 if (hrc == S_OK)
966 Log8Func(("IsFormatSupport(,%s,) -> S_OK + %p: requested format is supported\n", pDevCfg->szProps, pClosestMatch));
967 else
968 Log8Func(("IsFormatSupport(,%s,) -> %Rhrc + %p: %uch S%u %uHz\n", pDevCfg->szProps, hrc, pClosestMatch,
969 pClosestMatch ? pClosestMatch->nChannels : 0, pClosestMatch ? pClosestMatch->wBitsPerSample : 0,
970 pClosestMatch ? pClosestMatch->nSamplesPerSec : 0));
971
972 REFERENCE_TIME const cBufferSizeInNtTicks = PDMAudioPropsFramesToNtTicks(&pDevCfg->Props, pDevCfg->cFramesBufferSize);
973 uint32_t fInitFlags = AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM
974 | AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY;
975 hrc = pIAudioClient->Initialize(AUDCLNT_SHAREMODE_SHARED, fInitFlags, cBufferSizeInNtTicks,
976 0 /*cPeriodicityInNtTicks*/, &WaveFmtEx, NULL /*pAudioSessionGuid*/);
977 Log8Func(("Initialize(,%x, %RI64, %s,) -> %Rhrc\n", fInitFlags, cBufferSizeInNtTicks, pDevCfg->szProps, hrc));
978 if (SUCCEEDED(hrc))
979 {
980 /*
981 * The direction specific client interface.
982 */
983 if (pDevEntry->enmDir == PDMAUDIODIR_IN)
984 hrc = pIAudioClient->GetService(__uuidof(IAudioCaptureClient), (void **)&pDevCfg->pIAudioCaptureClient);
985 else
986 hrc = pIAudioClient->GetService(__uuidof(IAudioRenderClient), (void **)&pDevCfg->pIAudioRenderClient);
987 Log8Func(("GetService -> %Rhrc + %p\n", hrc, pDevEntry->enmDir == PDMAUDIODIR_IN
988 ? (void *)pDevCfg->pIAudioCaptureClient : (void *)pDevCfg->pIAudioRenderClient));
989 if (SUCCEEDED(hrc))
990 {
991 /*
992 * Obtain the actual stream format and buffer config.
993 */
994 UINT32 cFramesBufferSize = 0;
995 REFERENCE_TIME cDefaultPeriodInNtTicks = 0;
996 REFERENCE_TIME cMinimumPeriodInNtTicks = 0;
997 REFERENCE_TIME cLatencyinNtTicks = 0;
998 hrc = pIAudioClient->GetBufferSize(&cFramesBufferSize);
999 if (SUCCEEDED(hrc))
1000 {
1001 hrc = pIAudioClient->GetDevicePeriod(&cDefaultPeriodInNtTicks, &cMinimumPeriodInNtTicks);
1002 if (SUCCEEDED(hrc))
1003 {
1004 hrc = pIAudioClient->GetStreamLatency(&cLatencyinNtTicks);
1005 if (SUCCEEDED(hrc))
1006 {
1007 LogRel2(("WasAPI: Aquired buffer parameters for %s:\n"
1008 "WasAPI: cFramesBufferSize = %RU32\n"
1009 "WasAPI: cDefaultPeriodInNtTicks = %RI64\n"
1010 "WasAPI: cMinimumPeriodInNtTicks = %RI64\n"
1011 "WasAPI: cLatencyinNtTicks = %RI64\n",
1012 pDevCfg->szProps, cFramesBufferSize, cDefaultPeriodInNtTicks,
1013 cMinimumPeriodInNtTicks, cLatencyinNtTicks));
1014
1015 pDevCfg->pIAudioClient = pIAudioClient;
1016 pDevCfg->cFramesBufferSize = cFramesBufferSize;
1017 pDevCfg->cFramesPeriod = PDMAudioPropsNanoToFrames(&pDevCfg->Props,
1018 cDefaultPeriodInNtTicks * 100);
1019 pDevCfg->nsInited = RTTimeNanoTS();
1020 pDevCfg->nsLastUsed = pDevCfg->nsInited;
1021 pDevCfg->rcSetup = VINF_SUCCESS;
1022
1023 if (pClosestMatch)
1024 CoTaskMemFree(pClosestMatch);
1025 Log8Func(("returns VINF_SUCCESS (%p (%s) inited in %'RU64 ns)\n",
1026 pDevCfg, pDevCfg->szProps, pDevCfg->nsInited - pDevCfg->nsCreated));
1027 return VINF_SUCCESS;
1028 }
1029 LogRelMax(64, ("WasAPI: GetStreamLatency failed: %Rhrc\n", hrc));
1030 }
1031 else
1032 LogRelMax(64, ("WasAPI: GetDevicePeriod failed: %Rhrc\n", hrc));
1033 }
1034 else
1035 LogRelMax(64, ("WasAPI: GetBufferSize failed: %Rhrc\n", hrc));
1036
1037 if (pDevCfg->pIAudioCaptureClient)
1038 {
1039 pDevCfg->pIAudioCaptureClient->Release();
1040 pDevCfg->pIAudioCaptureClient = NULL;
1041 }
1042
1043 if (pDevCfg->pIAudioRenderClient)
1044 {
1045 pDevCfg->pIAudioRenderClient->Release();
1046 pDevCfg->pIAudioRenderClient = NULL;
1047 }
1048 }
1049 else
1050 LogRelMax(64, ("WasAPI: IAudioClient::GetService(%s) failed: %Rhrc\n", pDevCfg->szProps, hrc));
1051 }
1052 else
1053 LogRelMax(64, ("WasAPI: IAudioClient::Initialize(%s) failed: %Rhrc\n", pDevCfg->szProps, hrc));
1054 }
1055 else
1056 LogRelMax(64,("WasAPI: IAudioClient::IsFormatSupport(,%s,) failed: %Rhrc\n", pDevCfg->szProps, hrc));
1057
1058 pIAudioClient->Release();
1059 if (pClosestMatch)
1060 CoTaskMemFree(pClosestMatch);
1061 pDevCfg->nsInited = RTTimeNanoTS();
1062 pDevCfg->nsLastUsed = 0;
1063 Log8Func(("returns VERR_AUDIO_STREAM_COULD_NOT_CREATE (inited in %'RU64 ns)\n", pDevCfg->nsInited - pDevCfg->nsCreated));
1064 return pDevCfg->rcSetup = VERR_AUDIO_STREAM_COULD_NOT_CREATE;
1065}
1066
1067
1068/**
1069 * Worker for drvHostAudioWasCacheLookupOrCreate.
1070 *
1071 * If lookup fails, a new entry will be created.
1072 *
1073 * @note Called holding the lock, returning without holding it!
1074 */
1075static int drvHostAudioWasCacheLookupOrCreateConfig(PDRVHOSTAUDIOWAS pThis, PDRVHOSTAUDIOWASCACHEDEV pDevEntry,
1076 PCPDMAUDIOSTREAMCFG pCfgReq, bool fOnWorker,
1077 PDRVHOSTAUDIOWASCACHEDEVCFG *ppDevCfg)
1078{
1079 /*
1080 * Check if we've got a matching config.
1081 */
1082 PDRVHOSTAUDIOWASCACHEDEVCFG pDevCfg = drvHostAudioWasCacheLookupLocked(pDevEntry, &pCfgReq->Props);
1083 if (pDevCfg)
1084 {
1085 *ppDevCfg = pDevCfg;
1086 RTCritSectLeave(&pThis->CritSectCache);
1087 Log8Func(("Config cache hit '%s' on '%ls': %p\n", pDevCfg->szProps, pDevEntry->wszDevId, pDevCfg));
1088 return VINF_SUCCESS;
1089 }
1090
1091 RTCritSectLeave(&pThis->CritSectCache);
1092
1093 /*
1094 * Allocate an device config entry and hand the creation task over to the
1095 * worker thread, unless we're already on it.
1096 */
1097 pDevCfg = (PDRVHOSTAUDIOWASCACHEDEVCFG)RTMemAllocZ(sizeof(*pDevCfg));
1098 AssertReturn(pDevCfg, VERR_NO_MEMORY);
1099 RTListInit(&pDevCfg->ListEntry);
1100 pDevCfg->pDevEntry = pDevEntry;
1101 pDevCfg->rcSetup = VERR_AUDIO_STREAM_INIT_IN_PROGRESS;
1102 pDevCfg->Props = pCfgReq->Props;
1103 pDevCfg->cFramesBufferSize = pCfgReq->Backend.cFramesBufferSize;
1104 PDMAudioPropsToString(&pDevCfg->Props, pDevCfg->szProps, sizeof(pDevCfg->szProps));
1105 pDevCfg->nsCreated = RTTimeNanoTS();
1106 pDevCfg->nsLastUsed = pDevCfg->nsCreated;
1107
1108 uint32_t cCacheEntries;
1109 if (pDevCfg->pDevEntry->enmDir == PDMAUDIODIR_IN)
1110 cCacheEntries = ASMAtomicIncU32(&pThis->cCacheEntriesIn);
1111 else
1112 cCacheEntries = ASMAtomicIncU32(&pThis->cCacheEntriesOut);
1113 if (cCacheEntries > VBOX_WASAPI_MAX_TOTAL_CONFIG_ENTRIES)
1114 {
1115 LogFlowFunc(("Trigger cache pruning.\n"));
1116 int rc2 = pThis->pIHostAudioPort->pfnDoOnWorkerThread(pThis->pIHostAudioPort, NULL /*pStream*/,
1117 DRVHOSTAUDIOWAS_DO_PRUNE_CACHE, NULL /*pvUser*/);
1118 AssertRCStmt(rc2, drvHostAudioWasCachePrune(pThis));
1119 }
1120
1121 if (!fOnWorker)
1122 {
1123 *ppDevCfg = pDevCfg;
1124 LogFlowFunc(("Doing the rest of the work on %p via pfnStreamInitAsync...\n", pDevCfg));
1125 return VINF_AUDIO_STREAM_ASYNC_INIT_NEEDED;
1126 }
1127
1128 /*
1129 * Initialize the entry on the calling thread.
1130 */
1131 int rc = drvHostAudioWasCacheInitConfig(pDevCfg);
1132 AssertRC(pDevCfg->rcSetup == rc);
1133 if (RT_SUCCESS(rc))
1134 rc = pDevCfg->rcSetup; /* paranoia */
1135 if (RT_SUCCESS(rc))
1136 {
1137 *ppDevCfg = pDevCfg;
1138 LogFlowFunc(("Returning %p\n", pDevCfg));
1139 return VINF_SUCCESS;
1140 }
1141 RTMemFree(pDevCfg);
1142 *ppDevCfg = NULL;
1143 return rc;
1144}
1145
1146
1147/**
1148 * Looks up the given device + config combo in the cache, creating a new entry
1149 * if missing.
1150 *
1151 * @returns VBox status code.
1152 * @retval VINF_AUDIO_STREAM_ASYNC_INIT_NEEDED if @a fOnWorker is @c false and
1153 * we created a new entry that needs initalization by calling
1154 * drvHostAudioWasCacheInitConfig() on it.
1155 * @param pThis The WASAPI host audio driver instance data.
1156 * @param pIDevice The device to look up.
1157 * @param pCfgReq The configuration to look up.
1158 * @param fOnWorker Set if we're on a worker thread, otherwise false. When
1159 * set to @c true, VINF_AUDIO_STREAM_ASYNC_INIT_NEEDED will
1160 * not be returned and a new entry will be fully
1161 * initialized before returning.
1162 * @param ppDevCfg Where to return the requested device config.
1163 */
1164static int drvHostAudioWasCacheLookupOrCreate(PDRVHOSTAUDIOWAS pThis, IMMDevice *pIDevice, PCPDMAUDIOSTREAMCFG pCfgReq,
1165 bool fOnWorker, PDRVHOSTAUDIOWASCACHEDEVCFG *ppDevCfg)
1166{
1167 *ppDevCfg = NULL;
1168
1169 /*
1170 * Get the device ID so we can perform the lookup.
1171 */
1172 int rc = VERR_AUDIO_STREAM_COULD_NOT_CREATE;
1173 LPWSTR pwszDevId = NULL;
1174 HRESULT hrc = pIDevice->GetId(&pwszDevId);
1175 if (SUCCEEDED(hrc))
1176 {
1177 size_t cwcDevId = RTUtf16Len(pwszDevId);
1178
1179 /*
1180 * The cache has two levels, so first the device entry.
1181 */
1182 PDRVHOSTAUDIOWASCACHEDEV pDevEntry;
1183 RTCritSectEnter(&pThis->CritSectCache);
1184 RTListForEach(&pThis->CacheHead, pDevEntry, DRVHOSTAUDIOWASCACHEDEV, ListEntry)
1185 {
1186 if ( pDevEntry->cwcDevId == cwcDevId
1187 && pDevEntry->enmDir == pCfgReq->enmDir
1188 && RTUtf16Cmp(pDevEntry->wszDevId, pwszDevId) == 0)
1189 {
1190 CoTaskMemFree(pwszDevId);
1191 Log8Func(("Cache hit for device '%ls': %p\n", pDevEntry->wszDevId, pDevEntry));
1192 return drvHostAudioWasCacheLookupOrCreateConfig(pThis, pDevEntry, pCfgReq, fOnWorker, ppDevCfg);
1193 }
1194 }
1195 RTCritSectLeave(&pThis->CritSectCache);
1196
1197 /*
1198 * Device not in the cache, add it.
1199 */
1200 pDevEntry = (PDRVHOSTAUDIOWASCACHEDEV)RTMemAllocZVar(RT_UOFFSETOF_DYN(DRVHOSTAUDIOWASCACHEDEV, wszDevId[cwcDevId + 1]));
1201 if (pDevEntry)
1202 {
1203 pIDevice->AddRef();
1204 pDevEntry->pIDevice = pIDevice;
1205 pDevEntry->enmDir = pCfgReq->enmDir;
1206 pDevEntry->cwcDevId = cwcDevId;
1207#if 0
1208 pDevEntry->fSupportsAutoConvertPcm = -1;
1209 pDevEntry->fSupportsSrcDefaultQuality = -1;
1210#endif
1211 RTListInit(&pDevEntry->ConfigList);
1212 memcpy(pDevEntry->wszDevId, pwszDevId, cwcDevId * sizeof(RTUTF16));
1213 pDevEntry->wszDevId[cwcDevId] = '\0';
1214
1215 CoTaskMemFree(pwszDevId);
1216 pwszDevId = NULL;
1217
1218 /*
1219 * Before adding the device, check that someone didn't race us adding it.
1220 */
1221 RTCritSectEnter(&pThis->CritSectCache);
1222 PDRVHOSTAUDIOWASCACHEDEV pDevEntry2;
1223 RTListForEach(&pThis->CacheHead, pDevEntry2, DRVHOSTAUDIOWASCACHEDEV, ListEntry)
1224 {
1225 if ( pDevEntry2->cwcDevId == cwcDevId
1226 && pDevEntry2->enmDir == pCfgReq->enmDir
1227 && RTUtf16Cmp(pDevEntry2->wszDevId, pDevEntry->wszDevId) == 0)
1228 {
1229 pIDevice->Release();
1230 RTMemFree(pDevEntry);
1231 pDevEntry = NULL;
1232
1233 Log8Func(("Lost race adding device '%ls': %p\n", pDevEntry2->wszDevId, pDevEntry2));
1234 return drvHostAudioWasCacheLookupOrCreateConfig(pThis, pDevEntry2, pCfgReq, fOnWorker, ppDevCfg);
1235 }
1236 }
1237 RTListPrepend(&pThis->CacheHead, &pDevEntry->ListEntry);
1238
1239 Log8Func(("Added device '%ls' to cache: %p\n", pDevEntry->wszDevId, pDevEntry));
1240 return drvHostAudioWasCacheLookupOrCreateConfig(pThis, pDevEntry, pCfgReq, fOnWorker, ppDevCfg);
1241 }
1242 CoTaskMemFree(pwszDevId);
1243 }
1244 else
1245 LogRelMax(64, ("WasAPI: GetId failed (lookup): %Rhrc\n", hrc));
1246 return rc;
1247}
1248
1249
1250/**
1251 * Return the given config to the cache.
1252 *
1253 * @param pThis The WASAPI host audio driver instance data.
1254 * @param pDevCfg The device config to put back.
1255 */
1256static void drvHostAudioWasCachePutBack(PDRVHOSTAUDIOWAS pThis, PDRVHOSTAUDIOWASCACHEDEVCFG pDevCfg)
1257{
1258 /*
1259 * Reset the audio client to see that it works and to make sure it's in a sensible state.
1260 */
1261 HRESULT hrc = pDevCfg->pIAudioClient ? pDevCfg->pIAudioClient->Reset()
1262 : pDevCfg->rcSetup == VERR_AUDIO_STREAM_INIT_IN_PROGRESS ? S_OK : E_FAIL;
1263 if (SUCCEEDED(hrc))
1264 {
1265 Log8Func(("Putting %p/'%s' back\n", pDevCfg, pDevCfg->szProps));
1266 RTCritSectEnter(&pThis->CritSectCache);
1267 RTListAppend(&pDevCfg->pDevEntry->ConfigList, &pDevCfg->ListEntry);
1268 uint32_t const cEntries = pDevCfg->pDevEntry->enmDir == PDMAUDIODIR_IN ? pThis->cCacheEntriesIn : pThis->cCacheEntriesOut;
1269 RTCritSectLeave(&pThis->CritSectCache);
1270
1271 /* Trigger pruning if we're over the threshold. */
1272 if (cEntries > VBOX_WASAPI_MAX_TOTAL_CONFIG_ENTRIES)
1273 {
1274 LogFlowFunc(("Trigger cache pruning.\n"));
1275 int rc2 = pThis->pIHostAudioPort->pfnDoOnWorkerThread(pThis->pIHostAudioPort, NULL /*pStream*/,
1276 DRVHOSTAUDIOWAS_DO_PRUNE_CACHE, NULL /*pvUser*/);
1277 AssertRCStmt(rc2, drvHostAudioWasCachePrune(pThis));
1278 }
1279 }
1280 else
1281 {
1282 Log8Func(("IAudioClient::Reset failed (%Rhrc) on %p/'%s', destroying it.\n", hrc, pDevCfg, pDevCfg->szProps));
1283 drvHostAudioWasCacheDestroyDevConfig(pThis, pDevCfg);
1284 }
1285}
1286
1287
1288static void drvHostWasCacheConfigHinting(PDRVHOSTAUDIOWAS pThis, PPDMAUDIOSTREAMCFG pCfgReq, bool fOnWorker)
1289{
1290 /*
1291 * Get the device.
1292 */
1293 pThis->pNotifyClient->lockEnter();
1294 IMMDevice *pIDevice = pCfgReq->enmDir == PDMAUDIODIR_IN ? pThis->pIDeviceInput : pThis->pIDeviceOutput;
1295 if (pIDevice)
1296 pIDevice->AddRef();
1297 pThis->pNotifyClient->lockLeave();
1298 if (pIDevice)
1299 {
1300 /*
1301 * Look up the config and put it back.
1302 */
1303 PDRVHOSTAUDIOWASCACHEDEVCFG pDevCfg = NULL;
1304 int rc = drvHostAudioWasCacheLookupOrCreate(pThis, pIDevice, pCfgReq, fOnWorker, &pDevCfg);
1305 LogFlowFunc(("pDevCfg=%p rc=%Rrc\n", pDevCfg, rc));
1306 if (pDevCfg && RT_SUCCESS(rc))
1307 drvHostAudioWasCachePutBack(pThis, pDevCfg);
1308 pIDevice->Release();
1309 }
1310}
1311
1312
1313/**
1314 * Prefills the cache.
1315 *
1316 * @param pThis The WASAPI host audio driver instance data.
1317 */
1318static void drvHostAudioWasCacheFill(PDRVHOSTAUDIOWAS pThis)
1319{
1320#if 0 /* we don't have the buffer config nor do we really know which frequences to expect */
1321 Log8Func(("enter\n"));
1322 struct
1323 {
1324 PCRTUTF16 pwszDevId;
1325 PDMAUDIODIR enmDir;
1326 } aToCache[] =
1327 {
1328 { pThis->pwszInputDevId, PDMAUDIODIR_IN },
1329 { pThis->pwszOutputDevId, PDMAUDIODIR_OUT }
1330 };
1331 for (unsigned i = 0; i < RT_ELEMENTS(aToCache); i++)
1332 {
1333 PCRTUTF16 pwszDevId = aToCache[i].pwszDevId;
1334 IMMDevice *pIDevice = NULL;
1335 HRESULT hrc;
1336 if (pwszDevId)
1337 hrc = pThis->pIEnumerator->GetDevice(pwszDevId, &pIDevice);
1338 else
1339 {
1340 hrc = pThis->pIEnumerator->GetDefaultAudioEndpoint(aToCache[i].enmDir == PDMAUDIODIR_IN ? eCapture : eRender,
1341 eMultimedia, &pIDevice);
1342 pwszDevId = aToCache[i].enmDir == PDMAUDIODIR_IN ? L"{Default-In}" : L"{Default-Out}";
1343 }
1344 if (SUCCEEDED(hrc))
1345 {
1346 PDMAUDIOSTREAMCFG Cfg = { aToCache[i].enmDir, { PDMAUDIOPLAYBACKDST_INVALID },
1347 PDMAUDIOPCMPROPS_INITIALIZER(2, true, 2, 44100, false) };
1348 Cfg.Backend.cFramesBufferSize = PDMAudioPropsMilliToFrames(&Cfg.Props, 300);
1349 PDRVHOSTAUDIOWASCACHEDEVCFG pDevCfg = drvHostAudioWasCacheLookupOrCreate(pThis, pIDevice, &Cfg);
1350 if (pDevCfg)
1351 drvHostAudioWasCachePutBack(pThis, pDevCfg);
1352
1353 pIDevice->Release();
1354 }
1355 else
1356 LogRelMax(64, ("WasAPI: Failed to open audio device '%ls' (pre-caching): %Rhrc\n", pwszDevId, hrc));
1357 }
1358 Log8Func(("leave\n"));
1359#else
1360 RT_NOREF(pThis);
1361#endif
1362}
1363
1364
1365/*********************************************************************************************************************************
1366* Worker thread *
1367*********************************************************************************************************************************/
1368#if 0
1369
1370/**
1371 * @callback_method_impl{FNRTTHREAD,
1372 * Asynchronous thread for setting up audio client configs.}
1373 */
1374static DECLCALLBACK(int) drvHostWasWorkerThread(RTTHREAD hThreadSelf, void *pvUser)
1375{
1376 PDRVHOSTAUDIOWAS pThis = (PDRVHOSTAUDIOWAS)pvUser;
1377
1378 /*
1379 * We need to set the thread ID so others can post us thread messages.
1380 * And before we signal that we're ready, make sure we've got a message queue.
1381 */
1382 pThis->idWorkerThread = GetCurrentThreadId();
1383 LogFunc(("idWorkerThread=%#x (%u)\n", pThis->idWorkerThread, pThis->idWorkerThread));
1384
1385 MSG Msg;
1386 PeekMessageW(&Msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);
1387
1388 int rc = RTThreadUserSignal(hThreadSelf);
1389 AssertRC(rc);
1390
1391 /*
1392 * Message loop.
1393 */
1394 BOOL fRet;
1395 while ((fRet = GetMessageW(&Msg, NULL, 0, 0)) != FALSE)
1396 {
1397 if (fRet != -1)
1398 {
1399 TranslateMessage(&Msg);
1400 Log9Func(("Msg: time=%u: msg=%#x l=%p w=%p for hwnd=%p\n", Msg.time, Msg.message, Msg.lParam, Msg.wParam, Msg.hwnd));
1401 switch (Msg.message)
1402 {
1403 case WM_DRVHOSTAUDIOWAS_PURGE_CACHE:
1404 {
1405 AssertMsgBreak(Msg.wParam == pThis->uWorkerThreadFixedParam, ("%p\n", Msg.wParam));
1406 AssertBreak(Msg.hwnd == NULL);
1407 AssertBreak(Msg.lParam == 0);
1408
1409 drvHostAudioWasCachePurge(pThis, false /*fOnWorker*/);
1410 break;
1411 }
1412
1413 default:
1414 break;
1415 }
1416 DispatchMessageW(&Msg);
1417 }
1418 else
1419 AssertMsgFailed(("GetLastError()=%u\n", GetLastError()));
1420 }
1421
1422 LogFlowFunc(("Pre-quit cache purge...\n"));
1423 drvHostAudioWasCachePurge(pThis, false /*fOnWorker*/);
1424
1425 LogFunc(("Quits\n"));
1426 return VINF_SUCCESS;
1427}
1428#endif
1429
1430
1431/*********************************************************************************************************************************
1432* PDMIHOSTAUDIO *
1433*********************************************************************************************************************************/
1434
1435/**
1436 * @interface_method_impl{PDMIHOSTAUDIO,pfnGetConfig}
1437 */
1438static DECLCALLBACK(int) drvHostAudioWasHA_GetConfig(PPDMIHOSTAUDIO pInterface, PPDMAUDIOBACKENDCFG pBackendCfg)
1439{
1440 RT_NOREF(pInterface);
1441 AssertPtrReturn(pInterface, VERR_INVALID_POINTER);
1442 AssertPtrReturn(pBackendCfg, VERR_INVALID_POINTER);
1443
1444
1445 /*
1446 * Fill in the config structure.
1447 */
1448 RTStrCopy(pBackendCfg->szName, sizeof(pBackendCfg->szName), "WasAPI");
1449 pBackendCfg->cbStream = sizeof(DRVHOSTAUDIOWASSTREAM);
1450 pBackendCfg->fFlags = PDMAUDIOBACKEND_F_ASYNC_HINT;
1451 pBackendCfg->cMaxStreamsIn = UINT32_MAX;
1452 pBackendCfg->cMaxStreamsOut = UINT32_MAX;
1453
1454 return VINF_SUCCESS;
1455}
1456
1457
1458/**
1459 * Queries information for @a pDevice and adds an entry to the enumeration.
1460 *
1461 * @returns VBox status code.
1462 * @param pDevEnm The enumeration to add the device to.
1463 * @param pIDevice The device.
1464 * @param enmType The type of device.
1465 * @param fDefault Whether it's the default device.
1466 */
1467static int drvHostWasEnumAddDev(PPDMAUDIOHOSTENUM pDevEnm, IMMDevice *pIDevice, EDataFlow enmType, bool fDefault)
1468{
1469 int rc = VINF_SUCCESS; /* ignore most errors */
1470 RT_NOREF(fDefault); /** @todo default device marking/skipping. */
1471
1472 /*
1473 * Gather the necessary properties.
1474 */
1475 IPropertyStore *pProperties = NULL;
1476 HRESULT hrc = pIDevice->OpenPropertyStore(STGM_READ, &pProperties);
1477 if (SUCCEEDED(hrc))
1478 {
1479 /* Get the friendly name (string). */
1480 PROPVARIANT VarName;
1481 PropVariantInit(&VarName);
1482 hrc = pProperties->GetValue(PKEY_Device_FriendlyName, &VarName);
1483 if (SUCCEEDED(hrc))
1484 {
1485 /* Get the device ID (string). */
1486 LPWSTR pwszDevId = NULL;
1487 hrc = pIDevice->GetId(&pwszDevId);
1488 if (SUCCEEDED(hrc))
1489 {
1490 size_t const cwcDevId = RTUtf16Len(pwszDevId);
1491
1492 /* Get the device format (blob). */
1493 PROPVARIANT VarFormat;
1494 PropVariantInit(&VarFormat);
1495 hrc = pProperties->GetValue(PKEY_AudioEngine_DeviceFormat, &VarFormat);
1496 if (SUCCEEDED(hrc))
1497 {
1498 WAVEFORMATEX const * const pFormat = (WAVEFORMATEX const *)VarFormat.blob.pBlobData;
1499 AssertPtr(pFormat);
1500
1501 /*
1502 * Create a enumeration entry for it.
1503 */
1504 size_t const cbDev = RT_ALIGN_Z( RT_OFFSETOF(DRVHOSTAUDIOWASDEV, wszDevId)
1505 + (cwcDevId + 1) * sizeof(RTUTF16),
1506 64);
1507 PDRVHOSTAUDIOWASDEV pDev = (PDRVHOSTAUDIOWASDEV)PDMAudioHostDevAlloc(cbDev);
1508 if (pDev)
1509 {
1510 pDev->Core.enmUsage = enmType == eRender ? PDMAUDIODIR_OUT : PDMAUDIODIR_IN;
1511 pDev->Core.enmType = PDMAUDIODEVICETYPE_BUILTIN;
1512 if (enmType == eRender)
1513 pDev->Core.cMaxOutputChannels = pFormat->nChannels;
1514 else
1515 pDev->Core.cMaxInputChannels = pFormat->nChannels;
1516
1517 memcpy(pDev->wszDevId, pwszDevId, cwcDevId * sizeof(RTUTF16));
1518 pDev->wszDevId[cwcDevId] = '\0';
1519
1520 char *pszName;
1521 rc = RTUtf16ToUtf8(VarName.pwszVal, &pszName);
1522 if (RT_SUCCESS(rc))
1523 {
1524 RTStrCopy(pDev->Core.szName, sizeof(pDev->Core.szName), pszName);
1525 RTStrFree(pszName);
1526
1527 PDMAudioHostEnumAppend(pDevEnm, &pDev->Core);
1528 }
1529 else
1530 PDMAudioHostDevFree(&pDev->Core);
1531 }
1532 else
1533 rc = VERR_NO_MEMORY;
1534 PropVariantClear(&VarFormat);
1535 }
1536 else
1537 LogFunc(("Failed to get PKEY_AudioEngine_DeviceFormat: %Rhrc\n", hrc));
1538 CoTaskMemFree(pwszDevId);
1539 }
1540 else
1541 LogFunc(("Failed to get the device ID: %Rhrc\n", hrc));
1542 PropVariantClear(&VarName);
1543 }
1544 else
1545 LogFunc(("Failed to get PKEY_Device_FriendlyName: %Rhrc\n", hrc));
1546 pProperties->Release();
1547 }
1548 else
1549 LogFunc(("OpenPropertyStore failed: %Rhrc\n", hrc));
1550
1551 if (hrc == E_OUTOFMEMORY && RT_SUCCESS_NP(rc))
1552 rc = VERR_NO_MEMORY;
1553 return rc;
1554}
1555
1556
1557/**
1558 * Does a (Re-)enumeration of the host's playback + capturing devices.
1559 *
1560 * @return VBox status code.
1561 * @param pThis The WASAPI host audio driver instance data.
1562 * @param pDevEnm Where to store the enumerated devices.
1563 */
1564static int drvHostWasEnumerateDevices(PDRVHOSTAUDIOWAS pThis, PPDMAUDIOHOSTENUM pDevEnm)
1565{
1566 LogRel2(("WasAPI: Enumerating devices ...\n"));
1567
1568 int rc = VINF_SUCCESS;
1569 for (unsigned idxPass = 0; idxPass < 2 && RT_SUCCESS(rc); idxPass++)
1570 {
1571 EDataFlow const enmType = idxPass == 0 ? EDataFlow::eRender : EDataFlow::eCapture;
1572
1573 /* Get the default device first. */
1574 IMMDevice *pIDefaultDevice = NULL;
1575 HRESULT hrc = pThis->pIEnumerator->GetDefaultAudioEndpoint(enmType, eMultimedia, &pIDefaultDevice);
1576 if (SUCCEEDED(hrc))
1577 rc = drvHostWasEnumAddDev(pDevEnm, pIDefaultDevice, enmType, true);
1578 else
1579 pIDefaultDevice = NULL;
1580
1581 /* Enumerate the devices. */
1582 IMMDeviceCollection *pCollection = NULL;
1583 hrc = pThis->pIEnumerator->EnumAudioEndpoints(enmType, DEVICE_STATE_ACTIVE /*| DEVICE_STATE_UNPLUGGED?*/, &pCollection);
1584 if (SUCCEEDED(hrc) && pCollection != NULL)
1585 {
1586 UINT cDevices = 0;
1587 hrc = pCollection->GetCount(&cDevices);
1588 if (SUCCEEDED(hrc))
1589 {
1590 for (UINT idxDevice = 0; idxDevice < cDevices && RT_SUCCESS(rc); idxDevice++)
1591 {
1592 IMMDevice *pIDevice = NULL;
1593 hrc = pCollection->Item(idxDevice, &pIDevice);
1594 if (SUCCEEDED(hrc) && pIDevice)
1595 {
1596 if (pIDevice != pIDefaultDevice)
1597 rc = drvHostWasEnumAddDev(pDevEnm, pIDevice, enmType, false);
1598 pIDevice->Release();
1599 }
1600 }
1601 }
1602 pCollection->Release();
1603 }
1604 else
1605 LogRelMax(10, ("EnumAudioEndpoints(%s) failed: %Rhrc\n", idxPass == 0 ? "output" : "input", hrc));
1606
1607 if (pIDefaultDevice)
1608 pIDefaultDevice->Release();
1609 }
1610
1611 LogRel2(("WasAPI: Enumerating devices done - %u device (%Rrc)\n", pDevEnm->cDevices, rc));
1612 return rc;
1613}
1614
1615
1616/**
1617 * @interface_method_impl{PDMIHOSTAUDIO,pfnGetDevices}
1618 */
1619static DECLCALLBACK(int) drvHostAudioWasHA_GetDevices(PPDMIHOSTAUDIO pInterface, PPDMAUDIOHOSTENUM pDeviceEnum)
1620{
1621 PDRVHOSTAUDIOWAS pThis = RT_FROM_MEMBER(pInterface, DRVHOSTAUDIOWAS, IHostAudio);
1622 AssertPtrReturn(pDeviceEnum, VERR_INVALID_POINTER);
1623
1624 PDMAudioHostEnumInit(pDeviceEnum);
1625 int rc = drvHostWasEnumerateDevices(pThis, pDeviceEnum);
1626 if (RT_FAILURE(rc))
1627 PDMAudioHostEnumDelete(pDeviceEnum);
1628
1629 LogFlowFunc(("Returning %Rrc\n", rc));
1630 return rc;
1631}
1632
1633
1634/**
1635 * @interface_method_impl{PDMIHOSTAUDIO,pfnGetStatus}
1636 */
1637static DECLCALLBACK(PDMAUDIOBACKENDSTS) drvHostAudioWasHA_GetStatus(PPDMIHOSTAUDIO pInterface, PDMAUDIODIR enmDir)
1638{
1639 RT_NOREF(pInterface, enmDir);
1640 return PDMAUDIOBACKENDSTS_RUNNING;
1641}
1642
1643
1644/**
1645 * Performs the actual switching of device config.
1646 *
1647 * Worker for drvHostAudioWasDoStreamDevSwitch() and
1648 * drvHostAudioWasHA_StreamNotifyDeviceChanged().
1649 */
1650static void drvHostAudioWasCompleteStreamDevSwitch(PDRVHOSTAUDIOWAS pThis, PDRVHOSTAUDIOWASSTREAM pStreamWas,
1651 PDRVHOSTAUDIOWASCACHEDEVCFG pDevCfg)
1652{
1653 RTCritSectEnter(&pStreamWas->CritSect);
1654
1655 /* Do the switch. */
1656 PDRVHOSTAUDIOWASCACHEDEVCFG pDevCfgOld = pStreamWas->pDevCfg;
1657 pStreamWas->pDevCfg = pDevCfg;
1658
1659 /* The new stream is neither started nor draining. */
1660 pStreamWas->fStarted = false;
1661 pStreamWas->fDraining = false;
1662
1663 /* Device switching is done now. */
1664 pStreamWas->fSwitchingDevice = false;
1665
1666 /* Stop the old stream or Reset() will fail when putting it back into the cache. */
1667 if (pStreamWas->fEnabled && pDevCfgOld->pIAudioClient)
1668 pDevCfgOld->pIAudioClient->Stop();
1669
1670 RTCritSectLeave(&pStreamWas->CritSect);
1671
1672 /* Notify DrvAudio. */
1673 pThis->pIHostAudioPort->pfnStreamNotifyDeviceChanged(pThis->pIHostAudioPort, &pStreamWas->Core, false /*fReInit*/);
1674
1675 /* Put the old config back into the cache. */
1676 drvHostAudioWasCachePutBack(pThis, pDevCfgOld);
1677
1678 LogFlowFunc(("returns with '%s' state: %s\n", pStreamWas->Cfg.szName, drvHostWasStreamStatusString(pStreamWas) ));
1679}
1680
1681
1682/**
1683 * Called on a worker thread to initialize a new device config and switch the
1684 * given stream to using it.
1685 *
1686 * @sa drvHostAudioWasHA_StreamNotifyDeviceChanged
1687 */
1688static void drvHostAudioWasDoStreamDevSwitch(PDRVHOSTAUDIOWAS pThis, PDRVHOSTAUDIOWASSTREAM pStreamWas,
1689 PDRVHOSTAUDIOWASCACHEDEVCFG pDevCfg)
1690{
1691 /*
1692 * Do the initializing.
1693 */
1694 int rc = drvHostAudioWasCacheInitConfig(pDevCfg);
1695 if (RT_SUCCESS(rc))
1696 drvHostAudioWasCompleteStreamDevSwitch(pThis, pStreamWas, pDevCfg);
1697 else
1698 {
1699 LogRelMax(64, ("WasAPI: Failed to set up new device config '%ls:%s' for stream '%s': %Rrc\n",
1700 pDevCfg->pDevEntry->wszDevId, pDevCfg->szProps, pStreamWas->Cfg.szName, rc));
1701 drvHostAudioWasCacheDestroyDevConfig(pThis, pDevCfg);
1702 pThis->pIHostAudioPort->pfnStreamNotifyDeviceChanged(pThis->pIHostAudioPort, &pStreamWas->Core, true /*fReInit*/);
1703 }
1704}
1705
1706
1707/**
1708 * @interface_method_impl{PDMIHOSTAUDIO,pfnDoOnWorkerThread}
1709 */
1710static DECLCALLBACK(void) drvHostAudioWasHA_DoOnWorkerThread(PPDMIHOSTAUDIO pInterface, PPDMAUDIOBACKENDSTREAM pStream,
1711 uintptr_t uUser, void *pvUser)
1712{
1713 PDRVHOSTAUDIOWAS pThis = RT_FROM_MEMBER(pInterface, DRVHOSTAUDIOWAS, IHostAudio);
1714 LogFlowFunc(("uUser=%#zx pStream=%p pvUser=%p\n", uUser, pStream, pvUser));
1715
1716 switch (uUser)
1717 {
1718 case DRVHOSTAUDIOWAS_DO_PURGE_CACHE:
1719 Assert(pStream == NULL);
1720 Assert(pvUser == NULL);
1721 drvHostAudioWasCachePurge(pThis, true /*fOnWorker*/);
1722 break;
1723
1724 case DRVHOSTAUDIOWAS_DO_PRUNE_CACHE:
1725 Assert(pStream == NULL);
1726 Assert(pvUser == NULL);
1727 drvHostAudioWasCachePrune(pThis);
1728 break;
1729
1730 case DRVHOSTAUDIOWAS_DO_STREAM_DEV_SWITCH:
1731 AssertPtr(pStream);
1732 AssertPtr(pvUser);
1733 drvHostAudioWasDoStreamDevSwitch(pThis, (PDRVHOSTAUDIOWASSTREAM)pStream, (PDRVHOSTAUDIOWASCACHEDEVCFG)pvUser);
1734 break;
1735
1736 default:
1737 AssertMsgFailedBreak(("%#zx\n", uUser));
1738 }
1739}
1740
1741
1742/**
1743 * @interface_method_impl{PDMIHOSTAUDIO,pfnStreamConfigHint}
1744 *
1745 * @note This is called on a DrvAudio worker thread.
1746 */
1747static DECLCALLBACK(void) drvHostAudioWasHA_StreamConfigHint(PPDMIHOSTAUDIO pInterface, PPDMAUDIOSTREAMCFG pCfg)
1748{
1749#if 0 /* disable to test async stream creation. */
1750 PDRVHOSTAUDIOWAS pThis = RT_FROM_MEMBER(pInterface, DRVHOSTAUDIOWAS, IHostAudio);
1751 LogFlowFunc(("pCfg=%p\n", pCfg));
1752
1753 drvHostWasCacheConfigHinting(pThis, pCfg);
1754#else
1755 RT_NOREF(pInterface, pCfg);
1756#endif
1757}
1758
1759
1760/**
1761 * @interface_method_impl{PDMIHOSTAUDIO,pfnStreamCreate}
1762 */
1763static DECLCALLBACK(int) drvHostAudioWasHA_StreamCreate(PPDMIHOSTAUDIO pInterface, PPDMAUDIOBACKENDSTREAM pStream,
1764 PPDMAUDIOSTREAMCFG pCfgReq, PPDMAUDIOSTREAMCFG pCfgAcq)
1765{
1766 PDRVHOSTAUDIOWAS pThis = RT_FROM_MEMBER(pInterface, DRVHOSTAUDIOWAS, IHostAudio);
1767 PDRVHOSTAUDIOWASSTREAM pStreamWas = (PDRVHOSTAUDIOWASSTREAM)pStream;
1768 AssertPtrReturn(pStreamWas, VERR_INVALID_POINTER);
1769 AssertPtrReturn(pCfgReq, VERR_INVALID_POINTER);
1770 AssertPtrReturn(pCfgAcq, VERR_INVALID_POINTER);
1771 AssertReturn(pCfgReq->enmDir == PDMAUDIODIR_IN || pCfgReq->enmDir == PDMAUDIODIR_OUT, VERR_INVALID_PARAMETER);
1772 Assert(PDMAudioStrmCfgEquals(pCfgReq, pCfgAcq));
1773
1774 const char * const pszStreamType = pCfgReq->enmDir == PDMAUDIODIR_IN ? "capture" : "playback"; RT_NOREF(pszStreamType);
1775 LogFlowFunc(("enmSrc/Dst=%s '%s'\n",
1776 pCfgReq->enmDir == PDMAUDIODIR_IN ? PDMAudioRecSrcGetName(pCfgReq->u.enmSrc)
1777 : PDMAudioPlaybackDstGetName(pCfgReq->u.enmDst), pCfgReq->szName));
1778#if defined(RTLOG_REL_ENABLED) || defined(LOG_ENABLED)
1779 char szTmp[64];
1780#endif
1781 LogRel2(("WasAPI: Opening %s stream '%s' (%s)\n", pCfgReq->szName, pszStreamType,
1782 PDMAudioPropsToString(&pCfgReq->Props, szTmp, sizeof(szTmp))));
1783
1784 RTListInit(&pStreamWas->ListEntry);
1785
1786 /*
1787 * Do configuration conversion.
1788 */
1789 WAVEFORMATEX WaveFmtX;
1790 drvHostAudioWasWaveFmtExFromProps(&pCfgReq->Props, &WaveFmtX);
1791 LogRel2(("WasAPI: Requested %s format for '%s':\n"
1792 "WasAPI: wFormatTag = %RU16\n"
1793 "WasAPI: nChannels = %RU16\n"
1794 "WasAPI: nSamplesPerSec = %RU32\n"
1795 "WasAPI: nAvgBytesPerSec = %RU32\n"
1796 "WasAPI: nBlockAlign = %RU16\n"
1797 "WasAPI: wBitsPerSample = %RU16\n"
1798 "WasAPI: cbSize = %RU16\n"
1799 "WasAPI: cBufferSizeInNtTicks = %RU64\n",
1800 pszStreamType, pCfgReq->szName, WaveFmtX.wFormatTag, WaveFmtX.nChannels, WaveFmtX.nSamplesPerSec,
1801 WaveFmtX.nAvgBytesPerSec, WaveFmtX.nBlockAlign, WaveFmtX.wBitsPerSample, WaveFmtX.cbSize,
1802 PDMAudioPropsFramesToNtTicks(&pCfgReq->Props, pCfgReq->Backend.cFramesBufferSize) ));
1803
1804 /*
1805 * Get the device we're supposed to use.
1806 * (We cache this as it takes ~2ms to get the default device on a random W10 19042 system.)
1807 */
1808 pThis->pNotifyClient->lockEnter();
1809 IMMDevice *pIDevice = pCfgReq->enmDir == PDMAUDIODIR_IN ? pThis->pIDeviceInput : pThis->pIDeviceOutput;
1810 if (pIDevice)
1811 pIDevice->AddRef();
1812 pThis->pNotifyClient->lockLeave();
1813
1814 PRTUTF16 pwszDevId = pCfgReq->enmDir == PDMAUDIODIR_IN ? pThis->pwszInputDevId : pThis->pwszOutputDevId;
1815 PRTUTF16 const pwszDevIdDesc = pwszDevId ? pwszDevId : pCfgReq->enmDir == PDMAUDIODIR_IN ? L"{Default-In}" : L"{Default-Out}";
1816 if (!pIDevice)
1817 {
1818 /** @todo we can eliminate this too... */
1819 HRESULT hrc;
1820 if (pwszDevId)
1821 hrc = pThis->pIEnumerator->GetDevice(pwszDevId, &pIDevice);
1822 else
1823 hrc = pThis->pIEnumerator->GetDefaultAudioEndpoint(pCfgReq->enmDir == PDMAUDIODIR_IN ? eCapture : eRender,
1824 eMultimedia, &pIDevice);
1825 LogFlowFunc(("Got device %p (%Rhrc)\n", pIDevice, hrc));
1826 if (FAILED(hrc))
1827 {
1828 LogRelMax(64, ("WasAPI: Failed to open audio %s device '%ls': %Rhrc\n", pszStreamType, pwszDevIdDesc, hrc));
1829 return VERR_AUDIO_STREAM_COULD_NOT_CREATE;
1830 }
1831 }
1832
1833 /*
1834 * Ask the cache to retrieve or instantiate the requested configuration.
1835 */
1836 /** @todo make it return a status code too and retry if the default device
1837 * was invalidated/changed while we where working on it here. */
1838 PDRVHOSTAUDIOWASCACHEDEVCFG pDevCfg = NULL;
1839 int rc = drvHostAudioWasCacheLookupOrCreate(pThis, pIDevice, pCfgReq, false /*fOnWorker*/, &pDevCfg);
1840
1841 pIDevice->Release();
1842 pIDevice = NULL;
1843
1844 if (pDevCfg && RT_SUCCESS(rc))
1845 {
1846 pStreamWas->pDevCfg = pDevCfg;
1847
1848 pCfgAcq->Props = pDevCfg->Props;
1849 pCfgAcq->Backend.cFramesBufferSize = pDevCfg->cFramesBufferSize;
1850 pCfgAcq->Backend.cFramesPeriod = pDevCfg->cFramesPeriod;
1851 pCfgAcq->Backend.cFramesPreBuffering = pCfgReq->Backend.cFramesPreBuffering * pDevCfg->cFramesBufferSize
1852 / RT_MAX(pCfgReq->Backend.cFramesBufferSize, 1);
1853
1854 PDMAudioStrmCfgCopy(&pStreamWas->Cfg, pCfgAcq);
1855
1856 /* Finally, the critical section. */
1857 int rc2 = RTCritSectInit(&pStreamWas->CritSect);
1858 if (RT_SUCCESS(rc2))
1859 {
1860 RTCritSectRwEnterExcl(&pThis->CritSectStreamList);
1861 RTListAppend(&pThis->StreamHead, &pStreamWas->ListEntry);
1862 RTCritSectRwLeaveExcl(&pThis->CritSectStreamList);
1863
1864 if (pStreamWas->pDevCfg->pIAudioClient != NULL)
1865 {
1866 LogFlowFunc(("returns VINF_SUCCESS\n", rc));
1867 return VINF_SUCCESS;
1868 }
1869 LogFlowFunc(("returns VINF_AUDIO_STREAM_ASYNC_INIT_NEEDED\n", rc));
1870 return VINF_AUDIO_STREAM_ASYNC_INIT_NEEDED;
1871 }
1872
1873 LogRelMax(64, ("WasAPI: Failed to create critical section for stream.\n"));
1874 drvHostAudioWasCachePutBack(pThis, pDevCfg);
1875 pStreamWas->pDevCfg = NULL;
1876 }
1877 else
1878 LogRelMax(64, ("WasAPI: Failed to setup %s on audio device '%ls' (%Rrc).\n", pszStreamType, pwszDevIdDesc, rc));
1879
1880 LogFlowFunc(("returns %Rrc\n", rc));
1881 return rc;
1882}
1883
1884
1885/**
1886 * @interface_method_impl{PDMIHOSTAUDIO,pfnStreamInitAsync}
1887 */
1888static DECLCALLBACK(int) drvHostAudioWasHA_StreamInitAsync(PPDMIHOSTAUDIO pInterface, PPDMAUDIOBACKENDSTREAM pStream,
1889 bool fDestroyed)
1890{
1891 RT_NOREF(pInterface);
1892 PDRVHOSTAUDIOWASSTREAM pStreamWas = (PDRVHOSTAUDIOWASSTREAM)pStream;
1893 AssertPtrReturn(pStreamWas, VERR_INVALID_POINTER);
1894 LogFlowFunc(("Stream '%s'%s\n", pStreamWas->Cfg.szName, fDestroyed ? " - destroyed!" : ""));
1895
1896 /*
1897 * Assert sane preconditions for this call.
1898 */
1899 AssertPtrReturn(pStreamWas->Core.pStream, VERR_INTERNAL_ERROR);
1900 AssertPtrReturn(pStreamWas->pDevCfg, VERR_INTERNAL_ERROR_2);
1901 AssertPtrReturn(pStreamWas->pDevCfg->pDevEntry, VERR_INTERNAL_ERROR_3);
1902 AssertPtrReturn(pStreamWas->pDevCfg->pDevEntry->pIDevice, VERR_INTERNAL_ERROR_4);
1903 AssertReturn(pStreamWas->pDevCfg->pDevEntry->enmDir == pStreamWas->Core.pStream->enmDir, VERR_INTERNAL_ERROR_4);
1904 AssertReturn(pStreamWas->pDevCfg->pIAudioClient == NULL, VERR_INTERNAL_ERROR_5);
1905 AssertReturn(pStreamWas->pDevCfg->pIAudioRenderClient == NULL, VERR_INTERNAL_ERROR_5);
1906 AssertReturn(pStreamWas->pDevCfg->pIAudioCaptureClient == NULL, VERR_INTERNAL_ERROR_5);
1907
1908 /*
1909 * Do the job.
1910 */
1911 int rc;
1912 if (!fDestroyed)
1913 rc = drvHostAudioWasCacheInitConfig(pStreamWas->pDevCfg);
1914 else
1915 {
1916 AssertReturn(pStreamWas->pDevCfg->rcSetup == VERR_AUDIO_STREAM_INIT_IN_PROGRESS, VERR_INTERNAL_ERROR_2);
1917 pStreamWas->pDevCfg->rcSetup = VERR_WRONG_ORDER;
1918 rc = VINF_SUCCESS;
1919 }
1920
1921 LogFlowFunc(("returns %Rrc (%s)\n", rc, pStreamWas->Cfg.szName));
1922 return rc;
1923}
1924
1925
1926/**
1927 * @interface_method_impl{PDMIHOSTAUDIO,pfnStreamDestroy}
1928 */
1929static DECLCALLBACK(int) drvHostAudioWasHA_StreamDestroy(PPDMIHOSTAUDIO pInterface, PPDMAUDIOBACKENDSTREAM pStream)
1930{
1931 PDRVHOSTAUDIOWAS pThis = RT_FROM_MEMBER(pInterface, DRVHOSTAUDIOWAS, IHostAudio);
1932 PDRVHOSTAUDIOWASSTREAM pStreamWas = (PDRVHOSTAUDIOWASSTREAM)pStream;
1933 AssertPtrReturn(pStreamWas, VERR_INVALID_POINTER);
1934 LogFlowFunc(("Stream '%s'\n", pStreamWas->Cfg.szName));
1935 HRESULT hrc;
1936
1937 if (RTCritSectIsInitialized(&pStreamWas->CritSect))
1938 {
1939 RTCritSectRwEnterExcl(&pThis->CritSectStreamList);
1940 RTListNodeRemove(&pStreamWas->ListEntry);
1941 RTCritSectRwLeaveExcl(&pThis->CritSectStreamList);
1942
1943 RTCritSectDelete(&pStreamWas->CritSect);
1944 }
1945
1946 if (pStreamWas->fStarted && pStreamWas->pDevCfg && pStreamWas->pDevCfg->pIAudioClient)
1947 {
1948 hrc = pStreamWas->pDevCfg->pIAudioClient->Stop();
1949 LogFunc(("Stop('%s') -> %Rhrc\n", pStreamWas->Cfg.szName, hrc));
1950 pStreamWas->fStarted = false;
1951 }
1952
1953 if (pStreamWas->cFramesCaptureToRelease)
1954 {
1955 hrc = pStreamWas->pDevCfg->pIAudioCaptureClient->ReleaseBuffer(0);
1956 Log4Func(("Releasing capture buffer (%#x frames): %Rhrc\n", pStreamWas->cFramesCaptureToRelease, hrc));
1957 pStreamWas->cFramesCaptureToRelease = 0;
1958 pStreamWas->pbCapture = NULL;
1959 pStreamWas->cbCapture = 0;
1960 }
1961
1962 if (pStreamWas->pDevCfg)
1963 {
1964 drvHostAudioWasCachePutBack(pThis, pStreamWas->pDevCfg);
1965 pStreamWas->pDevCfg = NULL;
1966 }
1967
1968 LogFlowFunc(("returns\n"));
1969 return VINF_SUCCESS;
1970}
1971
1972
1973/**
1974 * @interface_method_impl{PDMIHOSTAUDIO,pfnStreamNotifyDeviceChanged}
1975 */
1976static DECLCALLBACK(void) drvHostAudioWasHA_StreamNotifyDeviceChanged(PPDMIHOSTAUDIO pInterface,
1977 PPDMAUDIOBACKENDSTREAM pStream, void *pvUser)
1978{
1979 PDRVHOSTAUDIOWAS pThis = RT_FROM_MEMBER(pInterface, DRVHOSTAUDIOWAS, IHostAudio);
1980 PDRVHOSTAUDIOWASSTREAM pStreamWas = (PDRVHOSTAUDIOWASSTREAM)pStream;
1981 LogFlowFunc(("pStreamWas=%p (%s)\n", pStreamWas, pStreamWas->Cfg.szName));
1982 RT_NOREF(pvUser);
1983
1984 /*
1985 * See if we've got a cached config for the new device around.
1986 * We ignore this entirely, for now at least, if the device was
1987 * disconnected and there is no replacement.
1988 */
1989 pThis->pNotifyClient->lockEnter();
1990 IMMDevice *pIDevice = pStreamWas->Cfg.enmDir == PDMAUDIODIR_IN ? pThis->pIDeviceInput : pThis->pIDeviceOutput;
1991 if (pIDevice)
1992 pIDevice->AddRef();
1993 pThis->pNotifyClient->lockLeave();
1994 if (pIDevice)
1995 {
1996 PDRVHOSTAUDIOWASCACHEDEVCFG pDevCfg = NULL;
1997 int rc = drvHostAudioWasCacheLookupOrCreate(pThis, pIDevice, &pStreamWas->Cfg, false /*fOnWorker*/, &pDevCfg);
1998
1999 pIDevice->Release();
2000 pIDevice = NULL;
2001
2002 /*
2003 * If we have a working audio client, just do the switch.
2004 */
2005 if (RT_SUCCESS(rc) && pDevCfg->pIAudioClient)
2006 {
2007 LogFlowFunc(("New device config is ready already!\n"));
2008 Assert(rc == VINF_SUCCESS);
2009 drvHostAudioWasCompleteStreamDevSwitch(pThis, pStreamWas, pDevCfg);
2010 }
2011 /*
2012 * Otherwise create one asynchronously on a worker thread.
2013 */
2014 else if (RT_SUCCESS(rc))
2015 {
2016 LogFlowFunc(("New device config needs async init ...\n"));
2017 Assert(rc == VINF_AUDIO_STREAM_ASYNC_INIT_NEEDED);
2018
2019 RTCritSectEnter(&pStreamWas->CritSect);
2020 pStreamWas->fSwitchingDevice = true;
2021 RTCritSectLeave(&pStreamWas->CritSect);
2022
2023 pThis->pIHostAudioPort->pfnStreamNotifyPreparingDeviceSwitch(pThis->pIHostAudioPort, &pStreamWas->Core);
2024
2025 rc = pThis->pIHostAudioPort->pfnDoOnWorkerThread(pThis->pIHostAudioPort, &pStreamWas->Core,
2026 DRVHOSTAUDIOWAS_DO_STREAM_DEV_SWITCH, pDevCfg);
2027 AssertRCStmt(rc, drvHostAudioWasDoStreamDevSwitch(pThis, pStreamWas, pDevCfg));
2028 }
2029 else
2030 {
2031 LogRelMax(64, ("WasAPI: Failed to create new device config '%ls:%s' for stream '%s': %Rrc\n",
2032 pDevCfg->pDevEntry->wszDevId, pDevCfg->szProps, pStreamWas->Cfg.szName, rc));
2033
2034 pThis->pIHostAudioPort->pfnStreamNotifyDeviceChanged(pThis->pIHostAudioPort, &pStreamWas->Core, true /*fReInit*/);
2035 }
2036 }
2037 else
2038 LogFlowFunc(("no new device, leaving it as-is\n"));
2039}
2040
2041
2042/**
2043 * Wrapper for starting a stream.
2044 *
2045 * @returns VBox status code.
2046 * @param pThis The WASAPI host audio driver instance data.
2047 * @param pStreamWas The stream.
2048 * @param pszOperation The operation we're doing.
2049 */
2050static int drvHostAudioWasStreamStartWorker(PDRVHOSTAUDIOWAS pThis, PDRVHOSTAUDIOWASSTREAM pStreamWas, const char *pszOperation)
2051{
2052 HRESULT hrc = pStreamWas->pDevCfg->pIAudioClient->Start();
2053 LogFlow(("%s: Start(%s) returns %Rhrc\n", pszOperation, pStreamWas->Cfg.szName, hrc));
2054 AssertStmt(hrc != AUDCLNT_E_NOT_STOPPED, hrc = S_OK);
2055 if (SUCCEEDED(hrc))
2056 {
2057 pStreamWas->fStarted = true;
2058 return VINF_SUCCESS;
2059 }
2060
2061 /** @todo try re-setup the stuff on AUDCLNT_E_DEVICEINVALIDATED.
2062 * Need some way of telling the caller (e.g. playback, capture) so they can
2063 * retry what they're doing */
2064 RT_NOREF(pThis);
2065
2066 pStreamWas->fStarted = false;
2067 LogRelMax(64, ("WasAPI: Starting '%s' failed (%s): %Rhrc\n", pStreamWas->Cfg.szName, pszOperation, hrc));
2068 return VERR_AUDIO_STREAM_NOT_READY;
2069}
2070
2071
2072/**
2073 * @ interface_method_impl{PDMIHOSTAUDIO,pfnStreamEnable}
2074 */
2075static DECLCALLBACK(int) drvHostAudioWasHA_StreamEnable(PPDMIHOSTAUDIO pInterface, PPDMAUDIOBACKENDSTREAM pStream)
2076{
2077 PDRVHOSTAUDIOWAS pThis = RT_FROM_MEMBER(pInterface, DRVHOSTAUDIOWAS, IHostAudio);
2078 PDRVHOSTAUDIOWASSTREAM pStreamWas = (PDRVHOSTAUDIOWASSTREAM)pStream;
2079 LogFlowFunc(("Stream '%s' {%s}\n", pStreamWas->Cfg.szName, drvHostWasStreamStatusString(pStreamWas)));
2080 HRESULT hrc;
2081 RTCritSectEnter(&pStreamWas->CritSect);
2082
2083 Assert(!pStreamWas->fEnabled);
2084 Assert(!pStreamWas->fStarted);
2085
2086 /*
2087 * We always reset the buffer before enabling the stream (normally never necessary).
2088 */
2089 if (pStreamWas->cFramesCaptureToRelease)
2090 {
2091 hrc = pStreamWas->pDevCfg->pIAudioCaptureClient->ReleaseBuffer(pStreamWas->cFramesCaptureToRelease);
2092 Log4Func(("Releasing capture buffer (%#x frames): %Rhrc\n", pStreamWas->cFramesCaptureToRelease, hrc));
2093 pStreamWas->cFramesCaptureToRelease = 0;
2094 pStreamWas->pbCapture = NULL;
2095 pStreamWas->cbCapture = 0;
2096 }
2097
2098 hrc = pStreamWas->pDevCfg->pIAudioClient->Reset();
2099 if (FAILED(hrc))
2100 LogRelMax(64, ("WasAPI: Stream reset failed when enabling '%s': %Rhrc\n", pStreamWas->Cfg.szName, hrc));
2101 pStreamWas->offInternal = 0;
2102 pStreamWas->fDraining = false;
2103 pStreamWas->fEnabled = true;
2104 pStreamWas->fRestartOnResume = false;
2105
2106 /*
2107 * Input streams will start capturing, while output streams will only start
2108 * playing once we get some audio data to play.
2109 */
2110 int rc = VINF_SUCCESS;
2111 if (pStreamWas->Cfg.enmDir == PDMAUDIODIR_IN)
2112 rc = drvHostAudioWasStreamStartWorker(pThis, pStreamWas, "enable");
2113 else
2114 Assert(pStreamWas->Cfg.enmDir == PDMAUDIODIR_OUT);
2115
2116 RTCritSectLeave(&pStreamWas->CritSect);
2117 LogFlowFunc(("returns %Rrc\n", rc));
2118 return rc;
2119}
2120
2121
2122/**
2123 * @ interface_method_impl{PDMIHOSTAUDIO,pfnStreamDisable}
2124 */
2125static DECLCALLBACK(int) drvHostAudioWasHA_StreamDisable(PPDMIHOSTAUDIO pInterface, PPDMAUDIOBACKENDSTREAM pStream)
2126{
2127 RT_NOREF(pInterface);
2128 PDRVHOSTAUDIOWASSTREAM pStreamWas = (PDRVHOSTAUDIOWASSTREAM)pStream;
2129 LogFlowFunc(("cMsLastTransfer=%RI64 ms, stream '%s' {%s} \n",
2130 pStreamWas->msLastTransfer ? RTTimeMilliTS() - pStreamWas->msLastTransfer : -1,
2131 pStreamWas->Cfg.szName, drvHostWasStreamStatusString(pStreamWas) ));
2132 RTCritSectEnter(&pStreamWas->CritSect);
2133
2134 /*
2135 * We will not stop a draining output stream, otherwise the actions are the same here.
2136 */
2137 pStreamWas->fEnabled = false;
2138 pStreamWas->fRestartOnResume = false;
2139 Assert(!pStreamWas->fDraining || pStreamWas->Cfg.enmDir == PDMAUDIODIR_OUT);
2140
2141 int rc = VINF_SUCCESS;
2142 if (!pStreamWas->fDraining)
2143 {
2144 if (pStreamWas->fStarted)
2145 {
2146 HRESULT hrc = pStreamWas->pDevCfg->pIAudioClient->Stop();
2147 LogFlowFunc(("Stop(%s) returns %Rhrc\n", pStreamWas->Cfg.szName, hrc));
2148 if (FAILED(hrc))
2149 {
2150 LogRelMax(64, ("WasAPI: Stopping '%s' failed (disable): %Rhrc\n", pStreamWas->Cfg.szName, hrc));
2151 rc = VERR_GENERAL_FAILURE;
2152 }
2153 pStreamWas->fStarted = false;
2154 }
2155 }
2156 else
2157 {
2158 LogFunc(("Stream '%s' is still draining...\n", pStreamWas->Cfg.szName));
2159 Assert(pStreamWas->fStarted);
2160 }
2161
2162 RTCritSectLeave(&pStreamWas->CritSect);
2163 LogFlowFunc(("returns %Rrc {%s}\n", rc, drvHostWasStreamStatusString(pStreamWas)));
2164 return rc;
2165}
2166
2167
2168/**
2169 * @ interface_method_impl{PDMIHOSTAUDIO,pfnStreamPause}
2170 *
2171 * @note Basically the same as drvHostAudioWasHA_StreamDisable, just w/o the
2172 * buffer resetting and fEnabled change.
2173 */
2174static DECLCALLBACK(int) drvHostAudioWasHA_StreamPause(PPDMIHOSTAUDIO pInterface, PPDMAUDIOBACKENDSTREAM pStream)
2175{
2176 RT_NOREF(pInterface);
2177 PDRVHOSTAUDIOWASSTREAM pStreamWas = (PDRVHOSTAUDIOWASSTREAM)pStream;
2178 LogFlowFunc(("cMsLastTransfer=%RI64 ms, stream '%s' {%s} \n",
2179 pStreamWas->msLastTransfer ? RTTimeMilliTS() - pStreamWas->msLastTransfer : -1,
2180 pStreamWas->Cfg.szName, drvHostWasStreamStatusString(pStreamWas) ));
2181 RTCritSectEnter(&pStreamWas->CritSect);
2182
2183 /*
2184 * Unless we're draining the stream, stop it if it's started.
2185 */
2186 int rc = VINF_SUCCESS;
2187 if (pStreamWas->fStarted && !pStreamWas->fDraining)
2188 {
2189 pStreamWas->fRestartOnResume = true;
2190
2191 HRESULT hrc = pStreamWas->pDevCfg->pIAudioClient->Stop();
2192 LogFlowFunc(("Stop(%s) returns %Rhrc\n", pStreamWas->Cfg.szName, hrc));
2193 if (FAILED(hrc))
2194 {
2195 LogRelMax(64, ("WasAPI: Stopping '%s' failed (pause): %Rhrc\n", pStreamWas->Cfg.szName, hrc));
2196 rc = VERR_GENERAL_FAILURE;
2197 }
2198 pStreamWas->fStarted = false;
2199 }
2200 else
2201 {
2202 pStreamWas->fRestartOnResume = false;
2203 if (pStreamWas->fDraining)
2204 {
2205 LogFunc(("Stream '%s' is draining\n", pStreamWas->Cfg.szName));
2206 Assert(pStreamWas->fStarted);
2207 }
2208 }
2209
2210 RTCritSectLeave(&pStreamWas->CritSect);
2211 LogFlowFunc(("returns %Rrc {%s}\n", rc, drvHostWasStreamStatusString(pStreamWas)));
2212 return rc;
2213}
2214
2215
2216/**
2217 * @ interface_method_impl{PDMIHOSTAUDIO,pfnStreamResume}
2218 */
2219static DECLCALLBACK(int) drvHostAudioWasHA_StreamResume(PPDMIHOSTAUDIO pInterface, PPDMAUDIOBACKENDSTREAM pStream)
2220{
2221 PDRVHOSTAUDIOWAS pThis = RT_FROM_MEMBER(pInterface, DRVHOSTAUDIOWAS, IHostAudio);
2222 PDRVHOSTAUDIOWASSTREAM pStreamWas = (PDRVHOSTAUDIOWASSTREAM)pStream;
2223 LogFlowFunc(("Stream '%s' {%s}\n", pStreamWas->Cfg.szName, drvHostWasStreamStatusString(pStreamWas)));
2224 RTCritSectEnter(&pStreamWas->CritSect);
2225
2226 /*
2227 * Resume according to state saved by drvHostAudioWasHA_StreamPause.
2228 */
2229 int rc;
2230 if (pStreamWas->fRestartOnResume)
2231 rc = drvHostAudioWasStreamStartWorker(pThis, pStreamWas, "resume");
2232 else
2233 rc = VINF_SUCCESS;
2234 pStreamWas->fRestartOnResume = false;
2235
2236 RTCritSectLeave(&pStreamWas->CritSect);
2237 LogFlowFunc(("returns %Rrc {%s}\n", rc, drvHostWasStreamStatusString(pStreamWas)));
2238 return rc;
2239}
2240
2241
2242/**
2243 * This is used by the timer function as well as when arming the timer.
2244 *
2245 * @param pThis The DSound host audio driver instance data.
2246 * @param msNow A current RTTimeMilliTS() value.
2247 */
2248static void drvHostWasDrainTimerWorker(PDRVHOSTAUDIOWAS pThis, uint64_t msNow)
2249{
2250 /*
2251 * Go thru the stream list and look at draining streams.
2252 */
2253 uint64_t msNext = UINT64_MAX;
2254 RTCritSectRwEnterShared(&pThis->CritSectStreamList);
2255 PDRVHOSTAUDIOWASSTREAM pCur;
2256 RTListForEach(&pThis->StreamHead, pCur, DRVHOSTAUDIOWASSTREAM, ListEntry)
2257 {
2258 if ( pCur->fDraining
2259 && pCur->Cfg.enmDir == PDMAUDIODIR_OUT)
2260 {
2261 Assert(pCur->fStarted);
2262 uint64_t msCurDeadline = pCur->msDrainDeadline;
2263 if (msCurDeadline > 0 && msCurDeadline < msNext)
2264 {
2265 /* Take the lock and recheck: */
2266 RTCritSectEnter(&pCur->CritSect);
2267 msCurDeadline = pCur->msDrainDeadline;
2268 if ( pCur->fDraining
2269 && msCurDeadline > 0
2270 && msCurDeadline < msNext)
2271 {
2272 if (msCurDeadline > msNow)
2273 msNext = pCur->msDrainDeadline;
2274 else
2275 {
2276 LogRel2(("WasAPI: Stopping draining of '%s' {%s} ...\n",
2277 pCur->Cfg.szName, drvHostWasStreamStatusString(pCur)));
2278 HRESULT hrc = pCur->pDevCfg->pIAudioClient->Stop();
2279 if (FAILED(hrc))
2280 LogRelMax(64, ("WasAPI: Failed to stop draining stream '%s': %Rhrc\n", pCur->Cfg.szName, hrc));
2281 pCur->fDraining = false;
2282 pCur->fStarted = false;
2283 }
2284 }
2285 RTCritSectLeave(&pCur->CritSect);
2286 }
2287 }
2288 }
2289
2290 /*
2291 * Re-arm the timer if necessary.
2292 */
2293 if (msNext != UINT64_MAX)
2294 PDMDrvHlpTimerSetMillies(pThis->pDrvIns, pThis->hDrainTimer, msNext - msNow);
2295 RTCritSectRwLeaveShared(&pThis->CritSectStreamList);
2296}
2297
2298
2299/**
2300 * @callback_method_impl{FNTMTIMERDRV,
2301 * This is to ensure that draining streams stop properly.}
2302 */
2303static DECLCALLBACK(void) drvHostWasDrainStopTimer(PPDMDRVINS pDrvIns, TMTIMERHANDLE hTimer, void *pvUser)
2304{
2305 PDRVHOSTAUDIOWAS pThis = PDMINS_2_DATA(pDrvIns, PDRVHOSTAUDIOWAS);
2306 RT_NOREF(hTimer, pvUser);
2307 drvHostWasDrainTimerWorker(pThis, RTTimeMilliTS());
2308}
2309
2310
2311/**
2312 * @ interface_method_impl{PDMIHOSTAUDIO,pfnStreamDrain}
2313 */
2314static DECLCALLBACK(int) drvHostAudioWasHA_StreamDrain(PPDMIHOSTAUDIO pInterface, PPDMAUDIOBACKENDSTREAM pStream)
2315{
2316 PDRVHOSTAUDIOWAS pThis = RT_FROM_MEMBER(pInterface, DRVHOSTAUDIOWAS, IHostAudio);
2317 PDRVHOSTAUDIOWASSTREAM pStreamWas = (PDRVHOSTAUDIOWASSTREAM)pStream;
2318 AssertReturn(pStreamWas->Cfg.enmDir == PDMAUDIODIR_OUT, VERR_INVALID_PARAMETER);
2319 LogFlowFunc(("cMsLastTransfer=%RI64 ms, stream '%s' {%s} \n",
2320 pStreamWas->msLastTransfer ? RTTimeMilliTS() - pStreamWas->msLastTransfer : -1,
2321 pStreamWas->Cfg.szName, drvHostWasStreamStatusString(pStreamWas) ));
2322
2323 /*
2324 * If the stram was started, calculate when the buffered data has finished
2325 * playing and switch to drain mode. Use the drain timer callback worker
2326 * to re-arm the timer or to stop the playback.
2327 */
2328 RTCritSectEnter(&pStreamWas->CritSect);
2329 int rc = VINF_SUCCESS;
2330 if (pStreamWas->fStarted)
2331 {
2332 if (!pStreamWas->fDraining)
2333 {
2334 if (pStreamWas->fStarted)
2335 {
2336 uint64_t const msNow = RTTimeMilliTS();
2337 uint64_t msDrainDeadline = 0;
2338 UINT32 cFramesPending = 0;
2339 HRESULT hrc = pStreamWas->pDevCfg->pIAudioClient->GetCurrentPadding(&cFramesPending);
2340 if (SUCCEEDED(hrc))
2341 msDrainDeadline = msNow
2342 + PDMAudioPropsFramesToMilli(&pStreamWas->Cfg.Props,
2343 RT_MIN(cFramesPending,
2344 pStreamWas->Cfg.Backend.cFramesBufferSize * 2))
2345 + 1 /*fudge*/;
2346 else
2347 {
2348 msDrainDeadline = msNow;
2349 LogRelMax(64, ("WasAPI: GetCurrentPadding fail on '%s' when starting draining: %Rhrc\n",
2350 pStreamWas->Cfg.szName, hrc));
2351 }
2352 pStreamWas->msDrainDeadline = msDrainDeadline;
2353 pStreamWas->fDraining = true;
2354 }
2355 else
2356 LogFlowFunc(("Drain requested for '%s', but not started playback...\n", pStreamWas->Cfg.szName));
2357 }
2358 else
2359 LogFlowFunc(("Already draining '%s' ...\n", pStreamWas->Cfg.szName));
2360 }
2361 else
2362 AssertStmt(!pStreamWas->fDraining, pStreamWas->fDraining = false);
2363 RTCritSectLeave(&pStreamWas->CritSect);
2364
2365 /*
2366 * Always do drain timer processing to re-arm the timer or actually stop
2367 * this stream (and others). (Must be done _after_ unlocking the stream.)
2368 */
2369 drvHostWasDrainTimerWorker(pThis, RTTimeMilliTS());
2370
2371 LogFlowFunc(("returns %Rrc {%s}\n", rc, drvHostWasStreamStatusString(pStreamWas)));
2372 return rc;
2373}
2374
2375
2376/**
2377 * @interface_method_impl{PDMIHOSTAUDIO,pfnStreamControl}
2378 */
2379static DECLCALLBACK(int) drvHostAudioWasHA_StreamControl(PPDMIHOSTAUDIO pInterface,
2380 PPDMAUDIOBACKENDSTREAM pStream, PDMAUDIOSTREAMCMD enmStreamCmd)
2381{
2382 /** @todo r=bird: I'd like to get rid of this pfnStreamControl method,
2383 * replacing it with individual StreamXxxx methods. That would save us
2384 * potentally huge switches and more easily see which drivers implement
2385 * which operations (grep for pfnStreamXxxx). */
2386 switch (enmStreamCmd)
2387 {
2388 case PDMAUDIOSTREAMCMD_ENABLE:
2389 return drvHostAudioWasHA_StreamEnable(pInterface, pStream);
2390 case PDMAUDIOSTREAMCMD_DISABLE:
2391 return drvHostAudioWasHA_StreamDisable(pInterface, pStream);
2392 case PDMAUDIOSTREAMCMD_PAUSE:
2393 return drvHostAudioWasHA_StreamPause(pInterface, pStream);
2394 case PDMAUDIOSTREAMCMD_RESUME:
2395 return drvHostAudioWasHA_StreamResume(pInterface, pStream);
2396 case PDMAUDIOSTREAMCMD_DRAIN:
2397 return drvHostAudioWasHA_StreamDrain(pInterface, pStream);
2398
2399 case PDMAUDIOSTREAMCMD_END:
2400 case PDMAUDIOSTREAMCMD_32BIT_HACK:
2401 case PDMAUDIOSTREAMCMD_INVALID:
2402 /* no default*/
2403 break;
2404 }
2405 return VERR_NOT_SUPPORTED;
2406}
2407
2408
2409/**
2410 * @interface_method_impl{PDMIHOSTAUDIO,pfnStreamGetReadable}
2411 */
2412static DECLCALLBACK(uint32_t) drvHostAudioWasHA_StreamGetReadable(PPDMIHOSTAUDIO pInterface, PPDMAUDIOBACKENDSTREAM pStream)
2413{
2414 RT_NOREF(pInterface);
2415 PDRVHOSTAUDIOWASSTREAM pStreamWas = (PDRVHOSTAUDIOWASSTREAM)pStream;
2416 AssertPtrReturn(pStreamWas, 0);
2417 Assert(pStreamWas->Cfg.enmDir == PDMAUDIODIR_IN);
2418
2419 uint32_t cbReadable = 0;
2420 RTCritSectEnter(&pStreamWas->CritSect);
2421
2422 if (pStreamWas->pDevCfg->pIAudioCaptureClient /* paranoia */)
2423 {
2424 UINT32 cFramesInNextPacket = 0;
2425 HRESULT hrc = pStreamWas->pDevCfg->pIAudioCaptureClient->GetNextPacketSize(&cFramesInNextPacket);
2426 if (SUCCEEDED(hrc))
2427 cbReadable = PDMAudioPropsFramesToBytes(&pStreamWas->Cfg.Props,
2428 RT_MIN(cFramesInNextPacket,
2429 pStreamWas->Cfg.Backend.cFramesBufferSize * 16 /* paranoia */));
2430 else
2431 LogRelMax(64, ("WasAPI: GetNextPacketSize failed on '%s': %Rhrc\n", pStreamWas->Cfg.szName, hrc));
2432 }
2433
2434 RTCritSectLeave(&pStreamWas->CritSect);
2435
2436 LogFlowFunc(("returns %#x (%u) {%s}\n", cbReadable, cbReadable, drvHostWasStreamStatusString(pStreamWas)));
2437 return cbReadable;
2438}
2439
2440
2441/**
2442 * @interface_method_impl{PDMIHOSTAUDIO,pfnStreamGetWritable}
2443 */
2444static DECLCALLBACK(uint32_t) drvHostAudioWasHA_StreamGetWritable(PPDMIHOSTAUDIO pInterface, PPDMAUDIOBACKENDSTREAM pStream)
2445{
2446 RT_NOREF(pInterface);
2447 PDRVHOSTAUDIOWASSTREAM pStreamWas = (PDRVHOSTAUDIOWASSTREAM)pStream;
2448 AssertPtrReturn(pStreamWas, 0);
2449 LogFlowFunc(("Stream '%s' {%s}\n", pStreamWas->Cfg.szName, drvHostWasStreamStatusString(pStreamWas)));
2450 Assert(pStreamWas->Cfg.enmDir == PDMAUDIODIR_OUT);
2451
2452 uint32_t cbWritable = 0;
2453 RTCritSectEnter(&pStreamWas->CritSect);
2454
2455 if ( pStreamWas->Cfg.enmDir == PDMAUDIODIR_OUT
2456 && pStreamWas->pDevCfg->pIAudioClient /* paranoia */)
2457 {
2458 UINT32 cFramesPending = 0;
2459 HRESULT hrc = pStreamWas->pDevCfg->pIAudioClient->GetCurrentPadding(&cFramesPending);
2460 if (SUCCEEDED(hrc))
2461 {
2462 if (cFramesPending < pStreamWas->Cfg.Backend.cFramesBufferSize)
2463 cbWritable = PDMAudioPropsFramesToBytes(&pStreamWas->Cfg.Props,
2464 pStreamWas->Cfg.Backend.cFramesBufferSize - cFramesPending);
2465 else if (cFramesPending > pStreamWas->Cfg.Backend.cFramesBufferSize)
2466 {
2467 LogRelMax(64, ("WasAPI: Warning! GetCurrentPadding('%s') return too high: cFramesPending=%#x > cFramesBufferSize=%#x\n",
2468 pStreamWas->Cfg.szName, cFramesPending, pStreamWas->Cfg.Backend.cFramesBufferSize));
2469 AssertMsgFailed(("cFramesPending=%#x > cFramesBufferSize=%#x\n",
2470 cFramesPending, pStreamWas->Cfg.Backend.cFramesBufferSize));
2471 }
2472 }
2473 else
2474 LogRelMax(64, ("WasAPI: GetCurrentPadding failed on '%s': %Rhrc\n", pStreamWas->Cfg.szName, hrc));
2475 }
2476
2477 RTCritSectLeave(&pStreamWas->CritSect);
2478
2479 LogFlowFunc(("returns %#x (%u) {%s}\n", cbWritable, cbWritable, drvHostWasStreamStatusString(pStreamWas)));
2480 return cbWritable;
2481}
2482
2483
2484/**
2485 * @interface_method_impl{PDMIHOSTAUDIO,pfnStreamGetPending}
2486 */
2487static DECLCALLBACK(uint32_t) drvHostAudioWasHA_StreamGetPending(PPDMIHOSTAUDIO pInterface, PPDMAUDIOBACKENDSTREAM pStream)
2488{
2489 RT_NOREF(pInterface);
2490 PDRVHOSTAUDIOWASSTREAM pStreamWas = (PDRVHOSTAUDIOWASSTREAM)pStream;
2491 AssertPtrReturn(pStreamWas, 0);
2492 LogFlowFunc(("Stream '%s' {%s}\n", pStreamWas->Cfg.szName, drvHostWasStreamStatusString(pStreamWas)));
2493 AssertReturn(pStreamWas->Cfg.enmDir == PDMAUDIODIR_OUT, 0);
2494
2495 uint32_t cbPending = 0;
2496 RTCritSectEnter(&pStreamWas->CritSect);
2497
2498 if ( pStreamWas->Cfg.enmDir == PDMAUDIODIR_OUT
2499 && pStreamWas->pDevCfg->pIAudioClient /* paranoia */)
2500 {
2501 if (pStreamWas->fStarted)
2502 {
2503 UINT32 cFramesPending = 0;
2504 HRESULT hrc = pStreamWas->pDevCfg->pIAudioClient->GetCurrentPadding(&cFramesPending);
2505 if (SUCCEEDED(hrc))
2506 {
2507 AssertMsg(cFramesPending <= pStreamWas->Cfg.Backend.cFramesBufferSize,
2508 ("cFramesPending=%#x cFramesBufferSize=%#x\n",
2509 cFramesPending, pStreamWas->Cfg.Backend.cFramesBufferSize));
2510 cbPending = PDMAudioPropsFramesToBytes(&pStreamWas->Cfg.Props, RT_MIN(cFramesPending, VBOX_WASAPI_MAX_PADDING));
2511 }
2512 else
2513 LogRelMax(64, ("WasAPI: GetCurrentPadding failed on '%s': %Rhrc\n", pStreamWas->Cfg.szName, hrc));
2514 }
2515 }
2516
2517 RTCritSectLeave(&pStreamWas->CritSect);
2518
2519 LogFlowFunc(("returns %#x (%u) {%s}\n", cbPending, cbPending, drvHostWasStreamStatusString(pStreamWas)));
2520 return cbPending;
2521}
2522
2523
2524/**
2525 * @interface_method_impl{PDMIHOSTAUDIO,pfnStreamGetState}
2526 */
2527static DECLCALLBACK(PDMHOSTAUDIOSTREAMSTATE) drvHostAudioWasHA_StreamGetState(PPDMIHOSTAUDIO pInterface,
2528 PPDMAUDIOBACKENDSTREAM pStream)
2529{
2530 RT_NOREF(pInterface);
2531 PDRVHOSTAUDIOWASSTREAM pStreamWas = (PDRVHOSTAUDIOWASSTREAM)pStream;
2532 AssertPtrReturn(pStreamWas, PDMHOSTAUDIOSTREAMSTATE_INVALID);
2533
2534 PDMHOSTAUDIOSTREAMSTATE enmState;
2535 AssertPtr(pStreamWas->pDevCfg);
2536 if (pStreamWas->pDevCfg /*paranoia*/)
2537 {
2538 if (RT_SUCCESS(pStreamWas->pDevCfg->rcSetup))
2539 enmState = PDMHOSTAUDIOSTREAMSTATE_OKAY;
2540 else if ( pStreamWas->pDevCfg->rcSetup == VERR_AUDIO_STREAM_INIT_IN_PROGRESS
2541 || pStreamWas->fSwitchingDevice )
2542 enmState = PDMHOSTAUDIOSTREAMSTATE_INITIALIZING;
2543 else
2544 enmState = PDMHOSTAUDIOSTREAMSTATE_NOT_WORKING;
2545 }
2546 else if (pStreamWas->fSwitchingDevice)
2547 enmState = PDMHOSTAUDIOSTREAMSTATE_INITIALIZING;
2548 else
2549 enmState = PDMHOSTAUDIOSTREAMSTATE_NOT_WORKING;
2550
2551 LogFlowFunc(("returns %d for '%s' {%s}\n", enmState, pStreamWas->Cfg.szName, drvHostWasStreamStatusString(pStreamWas)));
2552 return enmState;
2553}
2554
2555
2556/**
2557 * @interface_method_impl{PDMIHOSTAUDIO,pfnStreamPlay}
2558 */
2559static DECLCALLBACK(int) drvHostAudioWasHA_StreamPlay(PPDMIHOSTAUDIO pInterface, PPDMAUDIOBACKENDSTREAM pStream,
2560 const void *pvBuf, uint32_t cbBuf, uint32_t *pcbWritten)
2561{
2562 PDRVHOSTAUDIOWAS pThis = RT_FROM_MEMBER(pInterface, DRVHOSTAUDIOWAS, IHostAudio);
2563 PDRVHOSTAUDIOWASSTREAM pStreamWas = (PDRVHOSTAUDIOWASSTREAM)pStream;
2564 AssertPtrReturn(pStreamWas, VERR_INVALID_POINTER);
2565 AssertPtrReturn(pvBuf, VERR_INVALID_POINTER);
2566 AssertReturn(cbBuf, VERR_INVALID_PARAMETER);
2567 AssertPtrReturn(pcbWritten, VERR_INVALID_POINTER);
2568 Assert(PDMAudioPropsIsSizeAligned(&pStreamWas->Cfg.Props, cbBuf));
2569
2570 RTCritSectEnter(&pStreamWas->CritSect);
2571 if (pStreamWas->fEnabled)
2572 { /* likely */ }
2573 else
2574 {
2575 RTCritSectLeave(&pStreamWas->CritSect);
2576 *pcbWritten = 0;
2577 LogFunc(("Skipping %#x byte write to disabled stream {%s}\n", cbBuf, drvHostWasStreamStatusString(pStreamWas)));
2578 return VINF_SUCCESS;
2579 }
2580 Log4Func(("cbBuf=%#x stream '%s' {%s}\n", cbBuf, pStreamWas->Cfg.szName, drvHostWasStreamStatusString(pStreamWas) ));
2581
2582 /*
2583 * Transfer loop.
2584 */
2585 int rc = VINF_SUCCESS;
2586 uint32_t cReInits = 0;
2587 uint32_t cbWritten = 0;
2588 while (cbBuf > 0)
2589 {
2590 AssertBreakStmt(pStreamWas->pDevCfg && pStreamWas->pDevCfg->pIAudioRenderClient && pStreamWas->pDevCfg->pIAudioClient,
2591 rc = VERR_AUDIO_STREAM_NOT_READY);
2592
2593 /*
2594 * Figure out how much we can possibly write.
2595 */
2596 UINT32 cFramesPending = 0;
2597 uint32_t cbWritable = 0;
2598 HRESULT hrc = pStreamWas->pDevCfg->pIAudioClient->GetCurrentPadding(&cFramesPending);
2599 if (SUCCEEDED(hrc))
2600 cbWritable = PDMAudioPropsFramesToBytes(&pStreamWas->Cfg.Props,
2601 pStreamWas->Cfg.Backend.cFramesBufferSize
2602 - RT_MIN(cFramesPending, pStreamWas->Cfg.Backend.cFramesBufferSize));
2603 else
2604 {
2605 LogRelMax(64, ("WasAPI: GetCurrentPadding(%s) failed during playback: %Rhrc (@%#RX64)\n",
2606 pStreamWas->Cfg.szName, hrc, pStreamWas->offInternal));
2607 /** @todo reinit on AUDCLNT_E_DEVICEINVALIDATED? */
2608 rc = VERR_AUDIO_STREAM_NOT_READY;
2609 break;
2610 }
2611 if (cbWritable <= PDMAudioPropsFrameSize(&pStreamWas->Cfg.Props))
2612 break;
2613
2614 uint32_t const cbToWrite = PDMAudioPropsFloorBytesToFrame(&pStreamWas->Cfg.Props, RT_MIN(cbWritable, cbBuf));
2615 uint32_t const cFramesToWrite = PDMAudioPropsBytesToFrames(&pStreamWas->Cfg.Props, cbToWrite);
2616 Assert(PDMAudioPropsFramesToBytes(&pStreamWas->Cfg.Props, cFramesToWrite) == cbToWrite);
2617 Log3Func(("@%RX64: cFramesPending=%#x -> cbWritable=%#x cbToWrite=%#x cFramesToWrite=%#x {%s}\n",
2618 pStreamWas->offInternal, cFramesPending, cbWritable, cbToWrite, cFramesToWrite,
2619 drvHostWasStreamStatusString(pStreamWas) ));
2620
2621 /*
2622 * Get the buffer, copy the data into it, and relase it back to the WAS machinery.
2623 */
2624 BYTE *pbData = NULL;
2625 hrc = pStreamWas->pDevCfg->pIAudioRenderClient->GetBuffer(cFramesToWrite, &pbData);
2626 if (SUCCEEDED(hrc))
2627 {
2628 memcpy(pbData, pvBuf, cbToWrite);
2629 hrc = pStreamWas->pDevCfg->pIAudioRenderClient->ReleaseBuffer(cFramesToWrite, 0 /*fFlags*/);
2630 if (SUCCEEDED(hrc))
2631 {
2632 /*
2633 * Before we advance the buffer position (so we can resubmit it
2634 * after re-init), make sure we've successfully started stream.
2635 */
2636 if (pStreamWas->fStarted)
2637 { }
2638 else
2639 {
2640 rc = drvHostAudioWasStreamStartWorker(pThis, pStreamWas, "play");
2641 if (rc == VINF_SUCCESS)
2642 { /* likely */ }
2643 else if (RT_SUCCESS(rc) && ++cReInits < 5)
2644 continue; /* re-submit buffer after re-init */
2645 else
2646 break;
2647 }
2648
2649 /* advance. */
2650 pvBuf = (uint8_t *)pvBuf + cbToWrite;
2651 cbBuf -= cbToWrite;
2652 cbWritten += cbToWrite;
2653 pStreamWas->offInternal += cbToWrite;
2654 }
2655 else
2656 {
2657 LogRelMax(64, ("WasAPI: ReleaseBuffer(%#x) failed on '%s' during playback: %Rhrc (@%#RX64)\n",
2658 cFramesToWrite, pStreamWas->Cfg.szName, hrc, pStreamWas->offInternal));
2659 /** @todo reinit on AUDCLNT_E_DEVICEINVALIDATED? */
2660 rc = VERR_AUDIO_STREAM_NOT_READY;
2661 break;
2662 }
2663 }
2664 else
2665 {
2666 LogRelMax(64, ("WasAPI: GetBuffer(%#x) failed on '%s' during playback: %Rhrc (@%#RX64)\n",
2667 cFramesToWrite, pStreamWas->Cfg.szName, hrc, pStreamWas->offInternal));
2668 /** @todo reinit on AUDCLNT_E_DEVICEINVALIDATED? */
2669 rc = VERR_AUDIO_STREAM_NOT_READY;
2670 break;
2671 }
2672 }
2673
2674 /*
2675 * Done.
2676 */
2677 uint64_t const msPrev = pStreamWas->msLastTransfer;
2678 uint64_t const msNow = RTTimeMilliTS();
2679 if (cbWritten)
2680 pStreamWas->msLastTransfer = msNow;
2681
2682 RTCritSectLeave(&pStreamWas->CritSect);
2683
2684 *pcbWritten = cbWritten;
2685 if (RT_SUCCESS(rc) || !cbWritten)
2686 { }
2687 else
2688 {
2689 LogFlowFunc(("Suppressing %Rrc to report %#x bytes written\n", rc, cbWritten));
2690 rc = VINF_SUCCESS;
2691 }
2692 LogFlowFunc(("@%#RX64: cbWritten=%RU32 cMsDelta=%RU64 (%RU64 -> %RU64) {%s}\n", pStreamWas->offInternal, cbWritten,
2693 msPrev ? msNow - msPrev : 0, msPrev, pStreamWas->msLastTransfer, drvHostWasStreamStatusString(pStreamWas) ));
2694 return VINF_SUCCESS;
2695}
2696
2697
2698/**
2699 * @interface_method_impl{PDMIHOSTAUDIO,pfnStreamCapture}
2700 */
2701static DECLCALLBACK(int) drvHostAudioWasHA_StreamCapture(PPDMIHOSTAUDIO pInterface, PPDMAUDIOBACKENDSTREAM pStream,
2702 void *pvBuf, uint32_t cbBuf, uint32_t *pcbRead)
2703{
2704 RT_NOREF(pInterface); //PDRVHOSTAUDIOWAS pThis = RT_FROM_MEMBER(pInterface, DRVHOSTAUDIOWAS, IHostAudio);
2705 PDRVHOSTAUDIOWASSTREAM pStreamWas = (PDRVHOSTAUDIOWASSTREAM)pStream;
2706 AssertPtrReturn(pStreamWas, 0);
2707 AssertPtrReturn(pvBuf, VERR_INVALID_POINTER);
2708 AssertReturn(cbBuf, VERR_INVALID_PARAMETER);
2709 AssertPtrReturn(pcbRead, VERR_INVALID_POINTER);
2710 Assert(PDMAudioPropsIsSizeAligned(&pStreamWas->Cfg.Props, cbBuf));
2711
2712 RTCritSectEnter(&pStreamWas->CritSect);
2713 if (pStreamWas->fEnabled)
2714 { /* likely */ }
2715 else
2716 {
2717 RTCritSectLeave(&pStreamWas->CritSect);
2718 *pcbRead = 0;
2719 LogFunc(("Skipping %#x byte read from disabled stream {%s}\n", cbBuf, drvHostWasStreamStatusString(pStreamWas)));
2720 return VINF_SUCCESS;
2721 }
2722 Log4Func(("cbBuf=%#x stream '%s' {%s}\n", cbBuf, pStreamWas->Cfg.szName, drvHostWasStreamStatusString(pStreamWas) ));
2723
2724
2725 /*
2726 * Transfer loop.
2727 */
2728 int rc = VINF_SUCCESS;
2729 //uint32_t cReInits = 0;
2730 uint32_t cbRead = 0;
2731 uint32_t const cbFrame = PDMAudioPropsFrameSize(&pStreamWas->Cfg.Props);
2732 while (cbBuf > cbFrame)
2733 {
2734 AssertBreakStmt(pStreamWas->pDevCfg->pIAudioCaptureClient && pStreamWas->pDevCfg->pIAudioClient, rc = VERR_AUDIO_STREAM_NOT_READY);
2735
2736 /*
2737 * Anything pending from last call?
2738 * (This is rather similar to the Pulse interface.)
2739 */
2740 if (pStreamWas->cFramesCaptureToRelease)
2741 {
2742 uint32_t const cbToCopy = RT_MIN(pStreamWas->cbCapture, cbBuf);
2743 memcpy(pvBuf, pStreamWas->pbCapture, cbToCopy);
2744 pvBuf = (uint8_t *)pvBuf + cbToCopy;
2745 cbBuf -= cbToCopy;
2746 cbRead += cbToCopy;
2747 pStreamWas->offInternal += cbToCopy;
2748 pStreamWas->pbCapture += cbToCopy;
2749 pStreamWas->cbCapture -= cbToCopy;
2750 if (!pStreamWas->cbCapture)
2751 {
2752 HRESULT hrc = pStreamWas->pDevCfg->pIAudioCaptureClient->ReleaseBuffer(pStreamWas->cFramesCaptureToRelease);
2753 Log4Func(("@%#RX64: Releasing capture buffer (%#x frames): %Rhrc\n",
2754 pStreamWas->offInternal, pStreamWas->cFramesCaptureToRelease, hrc));
2755 if (SUCCEEDED(hrc))
2756 {
2757 pStreamWas->cFramesCaptureToRelease = 0;
2758 pStreamWas->pbCapture = NULL;
2759 }
2760 else
2761 {
2762 LogRelMax(64, ("WasAPI: ReleaseBuffer(%s) failed during capture: %Rhrc (@%#RX64)\n",
2763 pStreamWas->Cfg.szName, hrc, pStreamWas->offInternal));
2764 /** @todo reinit on AUDCLNT_E_DEVICEINVALIDATED? */
2765 rc = VERR_AUDIO_STREAM_NOT_READY;
2766 break;
2767 }
2768 }
2769 if (cbBuf < cbFrame)
2770 break;
2771 }
2772
2773 /*
2774 * Figure out if there is any data available to be read now. (Docs hint that we can not
2775 * skip this and go straight for GetBuffer or we risk getting unwritten buffer space back).
2776 */
2777 UINT32 cFramesCaptured = 0;
2778 HRESULT hrc = pStreamWas->pDevCfg->pIAudioCaptureClient->GetNextPacketSize(&cFramesCaptured);
2779 if (SUCCEEDED(hrc))
2780 {
2781 if (!cFramesCaptured)
2782 break;
2783 }
2784 else
2785 {
2786 LogRelMax(64, ("WasAPI: GetNextPacketSize(%s) failed during capture: %Rhrc (@%#RX64)\n",
2787 pStreamWas->Cfg.szName, hrc, pStreamWas->offInternal));
2788 /** @todo reinit on AUDCLNT_E_DEVICEINVALIDATED? */
2789 rc = VERR_AUDIO_STREAM_NOT_READY;
2790 break;
2791 }
2792
2793 /*
2794 * Get the buffer.
2795 */
2796 cFramesCaptured = 0;
2797 UINT64 uQpsNtTicks = 0;
2798 UINT64 offDevice = 0;
2799 DWORD fBufFlags = 0;
2800 BYTE *pbData = NULL;
2801 hrc = pStreamWas->pDevCfg->pIAudioCaptureClient->GetBuffer(&pbData, &cFramesCaptured, &fBufFlags, &offDevice, &uQpsNtTicks);
2802 Log4Func(("@%#RX64: GetBuffer -> %Rhrc pbData=%p cFramesCaptured=%#x fBufFlags=%#x offDevice=%#RX64 uQpcNtTicks=%#RX64\n",
2803 pStreamWas->offInternal, hrc, pbData, cFramesCaptured, fBufFlags, offDevice, uQpsNtTicks));
2804 if (SUCCEEDED(hrc))
2805 {
2806 Assert(cFramesCaptured < VBOX_WASAPI_MAX_PADDING);
2807 pStreamWas->pbCapture = pbData;
2808 pStreamWas->cFramesCaptureToRelease = cFramesCaptured;
2809 pStreamWas->cbCapture = PDMAudioPropsFramesToBytes(&pStreamWas->Cfg.Props, cFramesCaptured);
2810 /* Just loop and re-use the copying code above. Can optimize later. */
2811 }
2812 else
2813 {
2814 LogRelMax(64, ("WasAPI: GetBuffer() failed on '%s' during capture: %Rhrc (@%#RX64)\n",
2815 pStreamWas->Cfg.szName, hrc, pStreamWas->offInternal));
2816 /** @todo reinit on AUDCLNT_E_DEVICEINVALIDATED? */
2817 rc = VERR_AUDIO_STREAM_NOT_READY;
2818 break;
2819 }
2820 }
2821
2822 /*
2823 * Done.
2824 */
2825 uint64_t const msPrev = pStreamWas->msLastTransfer;
2826 uint64_t const msNow = RTTimeMilliTS();
2827 if (cbRead)
2828 pStreamWas->msLastTransfer = msNow;
2829
2830 RTCritSectLeave(&pStreamWas->CritSect);
2831
2832 *pcbRead = cbRead;
2833 if (RT_SUCCESS(rc) || !cbRead)
2834 { }
2835 else
2836 {
2837 LogFlowFunc(("Suppressing %Rrc to report %#x bytes read\n", rc, cbRead));
2838 rc = VINF_SUCCESS;
2839 }
2840 LogFlowFunc(("@%#RX64: cbRead=%RU32 cMsDelta=%RU64 (%RU64 -> %RU64) {%s}\n", pStreamWas->offInternal, cbRead,
2841 msPrev ? msNow - msPrev : 0, msPrev, pStreamWas->msLastTransfer, drvHostWasStreamStatusString(pStreamWas) ));
2842 return rc;
2843}
2844
2845
2846/*********************************************************************************************************************************
2847* PDMDRVINS::IBase Interface *
2848*********************************************************************************************************************************/
2849
2850/**
2851 * @callback_method_impl{PDMIBASE,pfnQueryInterface}
2852 */
2853static DECLCALLBACK(void *) drvHostAudioWasQueryInterface(PPDMIBASE pInterface, const char *pszIID)
2854{
2855 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
2856 PDRVHOSTAUDIOWAS pThis = PDMINS_2_DATA(pDrvIns, PDRVHOSTAUDIOWAS);
2857
2858 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pDrvIns->IBase);
2859 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIHOSTAUDIO, &pThis->IHostAudio);
2860 return NULL;
2861}
2862
2863
2864/*********************************************************************************************************************************
2865* PDMDRVREG Interface *
2866*********************************************************************************************************************************/
2867
2868/**
2869 * @callback_method_impl{FNPDMDRVDESTRUCT, pfnDestruct}
2870 */
2871static DECLCALLBACK(void) drvHostAudioWasPowerOff(PPDMDRVINS pDrvIns)
2872{
2873 PDRVHOSTAUDIOWAS pThis = PDMINS_2_DATA(pDrvIns, PDRVHOSTAUDIOWAS);
2874
2875 /*
2876 * Start purging the cache asynchronously before we get to destruct.
2877 * This might speed up VM shutdown a tiny fraction and also stress
2878 * the shutting down of the thread pool a little.
2879 */
2880#if 0
2881 if (pThis->hWorkerThread != NIL_RTTHREAD)
2882 {
2883 BOOL fRc = PostThreadMessageW(pThis->idWorkerThread, WM_DRVHOSTAUDIOWAS_PURGE_CACHE, pThis->uWorkerThreadFixedParam, 0);
2884 LogFlowFunc(("Posted WM_DRVHOSTAUDIOWAS_PURGE_CACHE: %d\n", fRc));
2885 Assert(fRc); RT_NOREF(fRc);
2886 }
2887#else
2888 if (!RTListIsEmpty(&pThis->CacheHead) && pThis->pIHostAudioPort)
2889 {
2890 int rc = RTSemEventMultiCreate(&pThis->hEvtCachePurge);
2891 if (RT_SUCCESS(rc))
2892 {
2893 rc = pThis->pIHostAudioPort->pfnDoOnWorkerThread(pThis->pIHostAudioPort, NULL/*pStream*/,
2894 DRVHOSTAUDIOWAS_DO_PURGE_CACHE, NULL /*pvUser*/);
2895 AssertRC(rc);
2896 }
2897 }
2898#endif
2899
2900 /*
2901 * Deregister the notification client to reduce the risk of notifications
2902 * comming in while we're being detatched or the VM is being destroyed.
2903 */
2904 if (pThis->pNotifyClient)
2905 {
2906 pThis->pNotifyClient->notifyDriverDestroyed();
2907 pThis->pIEnumerator->UnregisterEndpointNotificationCallback(pThis->pNotifyClient);
2908 pThis->pNotifyClient->Release();
2909 pThis->pNotifyClient = NULL;
2910 }
2911}
2912
2913
2914/**
2915 * @callback_method_impl{FNPDMDRVDESTRUCT, pfnDestruct}
2916 */
2917static DECLCALLBACK(void) drvHostAudioWasDestruct(PPDMDRVINS pDrvIns)
2918{
2919 PDRVHOSTAUDIOWAS pThis = PDMINS_2_DATA(pDrvIns, PDRVHOSTAUDIOWAS);
2920 PDMDRV_CHECK_VERSIONS_RETURN_VOID(pDrvIns);
2921 LogFlowFuncEnter();
2922
2923 /*
2924 * Release the notification client first.
2925 */
2926 if (pThis->pNotifyClient)
2927 {
2928 pThis->pNotifyClient->notifyDriverDestroyed();
2929 pThis->pIEnumerator->UnregisterEndpointNotificationCallback(pThis->pNotifyClient);
2930 pThis->pNotifyClient->Release();
2931 pThis->pNotifyClient = NULL;
2932 }
2933
2934#if 0
2935 if (pThis->hWorkerThread != NIL_RTTHREAD)
2936 {
2937 BOOL fRc = PostThreadMessageW(pThis->idWorkerThread, WM_QUIT, 0, 0);
2938 Assert(fRc); RT_NOREF(fRc);
2939
2940 int rc = RTThreadWait(pThis->hWorkerThread, RT_MS_15SEC, NULL);
2941 AssertRC(rc);
2942 }
2943#endif
2944
2945 if (RTCritSectIsInitialized(&pThis->CritSectCache))
2946 {
2947 drvHostAudioWasCachePurge(pThis, false /*fOnWorker*/);
2948 if (pThis->hEvtCachePurge != NIL_RTSEMEVENTMULTI)
2949 RTSemEventMultiWait(pThis->hEvtCachePurge, RT_MS_30SEC);
2950 RTCritSectDelete(&pThis->CritSectCache);
2951 }
2952
2953 if (pThis->hEvtCachePurge != NIL_RTSEMEVENTMULTI)
2954 {
2955 RTSemEventMultiDestroy(pThis->hEvtCachePurge);
2956 pThis->hEvtCachePurge = NIL_RTSEMEVENTMULTI;
2957 }
2958
2959 if (pThis->pIEnumerator)
2960 {
2961 uint32_t cRefs = pThis->pIEnumerator->Release(); RT_NOREF(cRefs);
2962 LogFlowFunc(("cRefs=%d\n", cRefs));
2963 }
2964
2965 if (pThis->pIDeviceOutput)
2966 {
2967 pThis->pIDeviceOutput->Release();
2968 pThis->pIDeviceOutput = NULL;
2969 }
2970
2971 if (pThis->pIDeviceInput)
2972 {
2973 pThis->pIDeviceInput->Release();
2974 pThis->pIDeviceInput = NULL;
2975 }
2976
2977
2978 if (RTCritSectRwIsInitialized(&pThis->CritSectStreamList))
2979 RTCritSectRwDelete(&pThis->CritSectStreamList);
2980
2981 LogFlowFuncLeave();
2982}
2983
2984
2985/**
2986 * @callback_method_impl{FNPDMDRVCONSTRUCT, pfnConstruct}
2987 */
2988static DECLCALLBACK(int) drvHostAudioWasConstruct(PPDMDRVINS pDrvIns, PCFGMNODE pCfg, uint32_t fFlags)
2989{
2990 PDMDRV_CHECK_VERSIONS_RETURN(pDrvIns);
2991 PDRVHOSTAUDIOWAS pThis = PDMINS_2_DATA(pDrvIns, PDRVHOSTAUDIOWAS);
2992 RT_NOREF(fFlags, pCfg);
2993
2994 /*
2995 * Init basic data members and interfaces.
2996 */
2997 pThis->pDrvIns = pDrvIns;
2998 pThis->hDrainTimer = NIL_TMTIMERHANDLE;
2999 pThis->hEvtCachePurge = NIL_RTSEMEVENTMULTI;
3000#if 0
3001 pThis->hWorkerThread = NIL_RTTHREAD;
3002 pThis->idWorkerThread = 0;
3003#endif
3004 RTListInit(&pThis->StreamHead);
3005 RTListInit(&pThis->CacheHead);
3006 /* IBase */
3007 pDrvIns->IBase.pfnQueryInterface = drvHostAudioWasQueryInterface;
3008 /* IHostAudio */
3009 pThis->IHostAudio.pfnGetConfig = drvHostAudioWasHA_GetConfig;
3010 pThis->IHostAudio.pfnGetDevices = drvHostAudioWasHA_GetDevices;
3011 pThis->IHostAudio.pfnGetStatus = drvHostAudioWasHA_GetStatus;
3012 pThis->IHostAudio.pfnDoOnWorkerThread = drvHostAudioWasHA_DoOnWorkerThread;
3013 pThis->IHostAudio.pfnStreamConfigHint = drvHostAudioWasHA_StreamConfigHint;
3014 pThis->IHostAudio.pfnStreamCreate = drvHostAudioWasHA_StreamCreate;
3015 pThis->IHostAudio.pfnStreamInitAsync = drvHostAudioWasHA_StreamInitAsync;
3016 pThis->IHostAudio.pfnStreamDestroy = drvHostAudioWasHA_StreamDestroy;
3017 pThis->IHostAudio.pfnStreamNotifyDeviceChanged = drvHostAudioWasHA_StreamNotifyDeviceChanged;
3018 pThis->IHostAudio.pfnStreamControl = drvHostAudioWasHA_StreamControl;
3019 pThis->IHostAudio.pfnStreamGetReadable = drvHostAudioWasHA_StreamGetReadable;
3020 pThis->IHostAudio.pfnStreamGetWritable = drvHostAudioWasHA_StreamGetWritable;
3021 pThis->IHostAudio.pfnStreamGetPending = drvHostAudioWasHA_StreamGetPending;
3022 pThis->IHostAudio.pfnStreamGetState = drvHostAudioWasHA_StreamGetState;
3023 pThis->IHostAudio.pfnStreamPlay = drvHostAudioWasHA_StreamPlay;
3024 pThis->IHostAudio.pfnStreamCapture = drvHostAudioWasHA_StreamCapture;
3025
3026 /*
3027 * Validate and read the configuration.
3028 */
3029 /** @todo We need a UUID for the session, while Pulse want some kind of name
3030 * when creating the streams. "StreamName" is confusing and a little
3031 * misleading though, unless used only for Pulse. Simply "VmName"
3032 * would be a lot better and more generic. */
3033 PDMDRV_VALIDATE_CONFIG_RETURN(pDrvIns, "VmName|VmUuid", "");
3034 /** @todo make it possible to override the default device selection. */
3035
3036 AssertMsgReturn(PDMDrvHlpNoAttach(pDrvIns) == VERR_PDM_NO_ATTACHED_DRIVER,
3037 ("Configuration error: Not possible to attach anything to this driver!\n"),
3038 VERR_PDM_DRVINS_NO_ATTACH);
3039
3040 /*
3041 * Initialize the critical sections early.
3042 */
3043 int rc = RTCritSectRwInit(&pThis->CritSectStreamList);
3044 AssertRCReturn(rc, rc);
3045
3046 rc = RTCritSectInit(&pThis->CritSectCache);
3047 AssertRCReturn(rc, rc);
3048
3049 /*
3050 * Create an enumerator instance that we can get the default devices from
3051 * as well as do enumeration thru.
3052 */
3053 HRESULT hrc = CoCreateInstance(__uuidof(MMDeviceEnumerator), 0, CLSCTX_ALL, __uuidof(IMMDeviceEnumerator),
3054 (void **)&pThis->pIEnumerator);
3055 if (FAILED(hrc))
3056 {
3057 pThis->pIEnumerator = NULL;
3058 LogRel(("WasAPI: Failed to create an MMDeviceEnumerator object: %Rhrc\n", hrc));
3059 return VERR_AUDIO_BACKEND_INIT_FAILED;
3060 }
3061 AssertPtr(pThis->pIEnumerator);
3062
3063 /*
3064 * Resolve the interface to the driver above us.
3065 */
3066 pThis->pIHostAudioPort = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMIHOSTAUDIOPORT);
3067 AssertPtrReturn(pThis->pIHostAudioPort, VERR_PDM_MISSING_INTERFACE_ABOVE);
3068
3069 /*
3070 * Instantiate and register the notification client with the enumerator.
3071 *
3072 * Failure here isn't considered fatal at this time as we'll just miss
3073 * default device changes.
3074 */
3075 try
3076 {
3077 pThis->pNotifyClient = new DrvHostAudioWasMmNotifyClient(pThis);
3078 }
3079 catch (std::bad_alloc &)
3080 {
3081 return VERR_NO_MEMORY;
3082 }
3083 catch (int rcXcpt)
3084 {
3085 return rcXcpt;
3086 }
3087 hrc = pThis->pIEnumerator->RegisterEndpointNotificationCallback(pThis->pNotifyClient);
3088 AssertMsg(SUCCEEDED(hrc), ("%Rhrc\n", hrc));
3089 if (FAILED(hrc))
3090 {
3091 LogRel(("WasAPI: RegisterEndpointNotificationCallback failed: %Rhrc (ignored)\n"
3092 "WasAPI: Warning! Will not be able to detect default device changes!\n"));
3093 pThis->pNotifyClient->notifyDriverDestroyed();
3094 pThis->pNotifyClient->Release();
3095 pThis->pNotifyClient = NULL;
3096 }
3097
3098 /*
3099 * Retrieve the input and output device.
3100 */
3101 IMMDevice *pIDeviceInput = NULL;
3102 if (pThis->pwszInputDevId)
3103 hrc = pThis->pIEnumerator->GetDevice(pThis->pwszInputDevId, &pIDeviceInput);
3104 else
3105 hrc = pThis->pIEnumerator->GetDefaultAudioEndpoint(eCapture, eMultimedia, &pIDeviceInput);
3106 if (SUCCEEDED(hrc))
3107 LogFlowFunc(("pIDeviceInput=%p\n", pIDeviceInput));
3108 else
3109 {
3110 LogRel(("WasAPI: Failed to get audio input device '%ls': %Rhrc\n",
3111 pThis->pwszInputDevId ? pThis->pwszInputDevId : L"{Default}", hrc));
3112 pIDeviceInput = NULL;
3113 }
3114
3115 IMMDevice *pIDeviceOutput = NULL;
3116 if (pThis->pwszOutputDevId)
3117 hrc = pThis->pIEnumerator->GetDevice(pThis->pwszOutputDevId, &pIDeviceOutput);
3118 else
3119 hrc = pThis->pIEnumerator->GetDefaultAudioEndpoint(eRender, eMultimedia, &pIDeviceOutput);
3120 if (SUCCEEDED(hrc))
3121 LogFlowFunc(("pIDeviceOutput=%p\n", pIDeviceOutput));
3122 else
3123 {
3124 LogRel(("WasAPI: Failed to get audio output device '%ls': %Rhrc\n",
3125 pThis->pwszOutputDevId ? pThis->pwszOutputDevId : L"{Default}", hrc));
3126 pIDeviceOutput = NULL;
3127 }
3128
3129 /* Carefully place them in the instance data: */
3130 pThis->pNotifyClient->lockEnter();
3131
3132 if (pThis->pIDeviceInput)
3133 pThis->pIDeviceInput->Release();
3134 pThis->pIDeviceInput = pIDeviceInput;
3135
3136 if (pThis->pIDeviceOutput)
3137 pThis->pIDeviceOutput->Release();
3138 pThis->pIDeviceOutput = pIDeviceOutput;
3139
3140 pThis->pNotifyClient->lockLeave();
3141
3142 /*
3143 * We need a timer for draining streams.
3144 */
3145 rc = PDMDrvHlpTMTimerCreate(pDrvIns, TMCLOCK_REAL, drvHostWasDrainStopTimer, NULL /*pvUser*/, 0 /*fFlags*/,
3146 "WasAPI drain", &pThis->hDrainTimer);
3147 AssertRCReturn(rc, rc);
3148
3149#if 0
3150 /*
3151 * Create the worker thread. This thread has a message loop and will be
3152 * signalled by DrvHostAudioWasMmNotifyClient while the VM is paused/whatever,
3153 * so better make it a regular thread rather than PDM thread.
3154 */
3155 pThis->uWorkerThreadFixedParam = (WPARAM)RTRandU64();
3156 rc = RTThreadCreateF(&pThis->hWorkerThread, drvHostWasWorkerThread, pThis, 0 /*cbStack*/, RTTHREADTYPE_DEFAULT,
3157 RTTHREADFLAGS_WAITABLE | RTTHREADFLAGS_COM_MTA, "WasWork%u", pDrvIns->iInstance);
3158 AssertRCReturn(rc, rc);
3159
3160 rc = RTThreadUserWait(pThis->hWorkerThread, RT_MS_10SEC);
3161 AssertRC(rc);
3162#endif
3163
3164 /*
3165 * Prime the cache.
3166 */
3167 drvHostAudioWasCacheFill(pThis);
3168
3169 return VINF_SUCCESS;
3170}
3171
3172
3173/**
3174 * PDM driver registration for WasAPI.
3175 */
3176const PDMDRVREG g_DrvHostAudioWas =
3177{
3178 /* u32Version */
3179 PDM_DRVREG_VERSION,
3180 /* szName */
3181 "HostAudioWas",
3182 /* szRCMod */
3183 "",
3184 /* szR0Mod */
3185 "",
3186 /* pszDescription */
3187 "Windows Audio Session API (WASAPI) host audio driver",
3188 /* fFlags */
3189 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
3190 /* fClass. */
3191 PDM_DRVREG_CLASS_AUDIO,
3192 /* cMaxInstances */
3193 ~0U,
3194 /* cbInstance */
3195 sizeof(DRVHOSTAUDIOWAS),
3196 /* pfnConstruct */
3197 drvHostAudioWasConstruct,
3198 /* pfnDestruct */
3199 drvHostAudioWasDestruct,
3200 /* pfnRelocate */
3201 NULL,
3202 /* pfnIOCtl */
3203 NULL,
3204 /* pfnPowerOn */
3205 NULL,
3206 /* pfnReset */
3207 NULL,
3208 /* pfnSuspend */
3209 NULL,
3210 /* pfnResume */
3211 NULL,
3212 /* pfnAttach */
3213 NULL,
3214 /* pfnDetach */
3215 NULL,
3216 /* pfnPowerOff */
3217 drvHostAudioWasPowerOff,
3218 /* pfnSoftReset */
3219 NULL,
3220 /* u32EndVersion */
3221 PDM_DRVREG_VERSION
3222};
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette