VirtualBox

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

最後變更 在這個檔案從108236是 107925,由 vboxsync 提交於 7 週 前

Audio: Added a new, optional config option 'CacheEnabled' (via global/per-VM 'VBoxInternal2/Audio/CacheEnabled') for audio drivers to disable caching code (if any). Currently only supported by DrvHostAudioWasApi, ignored everywhere else. bugref:10844

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

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