VirtualBox

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

Last change on this file since 102612 was 102612, checked in by vboxsync, 6 months ago

Audio/WAS: Attempt to fix crashes when invalidating the cached audio interfaces of the device entry configurations. This is needed when the audio interface becomes invalid on a host device switch. Extended logging a bit. ​bugref:10503

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

© 2023 Oracle
ContactPrivacy policyTerms of Use