VirtualBox

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

最後變更 在這個檔案從89504是 89504,由 vboxsync 提交於 4 年 前

Audio: Re-ordering some methods, no real change. bugref:9890

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

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