VirtualBox

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

Last change on this file since 107911 was 107911, checked in by vboxsync, 4 months ago

Audio/DrvHostAudioWasApi.cpp: Don't take the device role into account in DrvHostAudioWasMmNotifyClient::OnDefaultDeviceChanged() and (release) log what has changed. This at least fixes default device change notifications when running via VKAT (device role is eConsole and *not* eMultimedia in that case). bugref:10844

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

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