VirtualBox

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

Last change on this file since 89414 was 89411, checked in by vboxsync, 4 years ago

DrvHostAudioWasApi: Ignore AUDCLNT_E_UNSUPPORTED_FORMAT. bugref:9890

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

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