VirtualBox

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

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

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