VirtualBox

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

Last change on this file since 89234 was 89229, checked in by vboxsync, 4 years ago

Audio: Must have a PDMAUDIOHOSTDEV_F_DEFAULT flag for each direction or we'll mess up when two duplex devices are default devices for one direction each. Added a pszId member to the enumeration entires. Rewrote the core audio enumeration code. bugref:9890

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