VirtualBox

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

Last change on this file since 89092 was 89089, checked in by vboxsync, 4 years ago

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