VirtualBox

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

Last change on this file since 98063 was 96472, checked in by vboxsync, 2 years ago

ValKit/vkat,Devices/Audio: Made vkat build in no-CRT mode. bugref:10261

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