VirtualBox

source: vbox/trunk/src/VBox/Devices/Audio/DrvHostDSound.cpp@ 80596

Last change on this file since 80596 was 80500, checked in by vboxsync, 5 years ago

Audio/DrvHostDSound.cpp: Logging nits.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 88.0 KB
Line 
1/* $Id: DrvHostDSound.cpp 80500 2019-08-29 15:26:27Z vboxsync $ */
2/** @file
3 * Windows host backend driver using DirectSound.
4 */
5
6/*
7 * Copyright (C) 2006-2019 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18
19/*********************************************************************************************************************************
20* Header Files *
21*********************************************************************************************************************************/
22#define LOG_GROUP LOG_GROUP_DRV_HOST_AUDIO
23#include <VBox/log.h>
24#include <iprt/win/windows.h>
25#include <dsound.h>
26
27#include <iprt/alloc.h>
28#include <iprt/system.h>
29#include <iprt/uuid.h>
30#include <iprt/utf16.h>
31
32#include "DrvAudio.h"
33#include "VBoxDD.h"
34#ifdef VBOX_WITH_AUDIO_MMNOTIFICATION_CLIENT
35# include <new> /* For bad_alloc. */
36# include "VBoxMMNotificationClient.h"
37#endif
38
39
40/*********************************************************************************************************************************
41* Defined Constants And Macros *
42*********************************************************************************************************************************/
43/*
44 * IDirectSound* interface uses HRESULT status codes and the driver callbacks use
45 * the IPRT status codes. To minimize HRESULT->IPRT conversion most internal functions
46 * in the driver return HRESULT and conversion is done in the driver callbacks.
47 *
48 * Naming convention:
49 * 'dsound*' functions return IPRT status code;
50 * 'directSound*' - return HRESULT.
51 */
52
53/*
54 * Optional release logging, which a user can turn on with the
55 * 'VBoxManage debugvm' command.
56 * Debug logging still uses the common Log* macros from IPRT.
57 * Messages which always should go to the release log use LogRel.
58 */
59/* General code behavior. */
60#define DSLOG(a) do { LogRel2(a); } while(0)
61/* Something which produce a lot of logging during playback/recording. */
62#define DSLOGF(a) do { LogRel3(a); } while(0)
63/* Important messages like errors. Limited in the default release log to avoid log flood. */
64#define DSLOGREL(a) \
65 do { \
66 static int8_t s_cLogged = 0; \
67 if (s_cLogged < 8) { \
68 ++s_cLogged; \
69 LogRel(a); \
70 } else DSLOG(a); \
71 } while (0)
72
73/** Maximum number of attempts to restore the sound buffer before giving up. */
74#define DRV_DSOUND_RESTORE_ATTEMPTS_MAX 3
75/** Default input latency (in ms). */
76#define DRV_DSOUND_DEFAULT_LATENCY_MS_IN 50
77/** Default output latency (in ms). */
78#define DRV_DSOUND_DEFAULT_LATENCY_MS_OUT 50
79
80/** Makes DRVHOSTDSOUND out of PDMIHOSTAUDIO. */
81#define PDMIHOSTAUDIO_2_DRVHOSTDSOUND(pInterface) \
82 ( (PDRVHOSTDSOUND)((uintptr_t)pInterface - RT_UOFFSETOF(DRVHOSTDSOUND, IHostAudio)) )
83
84
85/*********************************************************************************************************************************
86* Structures and Typedefs *
87*********************************************************************************************************************************/
88/* Dynamically load dsound.dll. */
89typedef HRESULT WINAPI FNDIRECTSOUNDENUMERATEW(LPDSENUMCALLBACKW pDSEnumCallback, PVOID pContext);
90typedef FNDIRECTSOUNDENUMERATEW *PFNDIRECTSOUNDENUMERATEW;
91typedef HRESULT WINAPI FNDIRECTSOUNDCAPTUREENUMERATEW(LPDSENUMCALLBACKW pDSEnumCallback, PVOID pContext);
92typedef FNDIRECTSOUNDCAPTUREENUMERATEW *PFNDIRECTSOUNDCAPTUREENUMERATEW;
93typedef HRESULT WINAPI FNDIRECTSOUNDCAPTURECREATE8(LPCGUID lpcGUID, LPDIRECTSOUNDCAPTURE8 *lplpDSC, LPUNKNOWN pUnkOuter);
94typedef FNDIRECTSOUNDCAPTURECREATE8 *PFNDIRECTSOUNDCAPTURECREATE8;
95
96#define VBOX_DSOUND_MAX_EVENTS 3
97
98typedef enum DSOUNDEVENT
99{
100 DSOUNDEVENT_NOTIFY = 0,
101 DSOUNDEVENT_INPUT,
102 DSOUNDEVENT_OUTPUT,
103} DSOUNDEVENT;
104
105typedef struct DSOUNDHOSTCFG
106{
107 RTUUID uuidPlay;
108 LPCGUID pGuidPlay;
109 RTUUID uuidCapture;
110 LPCGUID pGuidCapture;
111} DSOUNDHOSTCFG, *PDSOUNDHOSTCFG;
112
113typedef struct DSOUNDSTREAM
114{
115 /** The stream's acquired configuration. */
116 PDMAUDIOSTREAMCFG Cfg;
117 /** Buffer alignment. */
118 uint8_t uAlign;
119 /** Whether this stream is in an enable state on the DirectSound side. */
120 bool fEnabled;
121 /** The stream's critical section for synchronizing access. */
122 RTCRITSECT CritSect;
123 /** The internal playback / capturing buffer. */
124 PRTCIRCBUF pCircBuf;
125 /** Size (in bytes) of the DirectSound buffer.
126 * Note: This in *not* the size of the circular buffer above! */
127 DWORD cbBufSize;
128 union
129 {
130 struct
131 {
132 /** The actual DirectSound Buffer (DSB) used for the capturing.
133 * This is a secondary buffer and is used as a streaming buffer. */
134 LPDIRECTSOUNDCAPTUREBUFFER8 pDSCB;
135 /** Current read offset (in bytes) within the DSB. */
136 DWORD offReadPos;
137 /** Number of buffer overruns happened. Used for logging. */
138 uint8_t cOverruns;
139 } In;
140 struct
141 {
142 /** The actual DirectSound Buffer (DSB) used for playback.
143 * This is a secondary buffer and is used as a streaming buffer. */
144 LPDIRECTSOUNDBUFFER8 pDSB;
145 /** Current write offset (in bytes) within the DSB. */
146 DWORD offWritePos;
147 /** Offset of last play cursor within the DSB when checked for pending. */
148 DWORD offPlayCursorLastPending;
149 /** Offset of last play cursor within the DSB when last played. */
150 DWORD offPlayCursorLastPlayed;
151 /** Total amount (in bytes) written to our internal ring buffer. */
152 uint64_t cbWritten;
153 /** Total amount (in bytes) played (to the DirectSound buffer). */
154 uint64_t cbTransferred;
155 /** Flag indicating whether playback was just (re)started. */
156 bool fFirstTransfer;
157 /** Flag indicating whether this stream is in draining mode, e.g. no new
158 * data is being written to it but DirectSound still needs to be able to
159 * play its remaining (buffered) data. */
160 bool fDrain;
161 /** How much (in bytes) the last transfer from the internal buffer
162 * to the DirectSound buffer was. */
163 uint32_t cbLastTransferred;
164 /** Timestamp (in ms) of the last transfer from the internal buffer
165 * to the DirectSound buffer. */
166 uint64_t tsLastTransferredMs;
167 /** Number of buffer underruns happened. Used for logging. */
168 uint8_t cUnderruns;
169 } Out;
170 };
171#ifdef LOG_ENABLED
172 struct
173 {
174 uint64_t tsLastTransferredMs;
175 } Dbg;
176#endif
177} DSOUNDSTREAM, *PDSOUNDSTREAM;
178
179/**
180 * Structure for keeping a DirectSound-specific device entry.
181 * This is then bound to the PDMAUDIODEVICE's pvData area.
182 */
183typedef struct DSOUNDDEV
184{
185 GUID Guid;
186} DSOUNDDEV, *PDSOUNDDEV;
187
188/**
189 * Structure for holding a device enumeration context.
190 */
191typedef struct DSOUNDENUMCBCTX
192{
193 /** Enumeration flags. */
194 uint32_t fFlags;
195 /** Pointer to device list to populate. */
196 PPDMAUDIODEVICEENUM pDevEnm;
197} DSOUNDENUMCBCTX, *PDSOUNDENUMCBCTX;
198
199typedef struct DRVHOSTDSOUND
200{
201 /** Pointer to the driver instance structure. */
202 PPDMDRVINS pDrvIns;
203 /** Our audio host audio interface. */
204 PDMIHOSTAUDIO IHostAudio;
205 /** Critical section to serialize access. */
206 RTCRITSECT CritSect;
207 /** DirectSound configuration options. */
208 DSOUNDHOSTCFG Cfg;
209 /** List of devices of last enumeration. */
210 PDMAUDIODEVICEENUM DeviceEnum;
211 /** Whether this backend supports any audio input. */
212 bool fEnabledIn;
213 /** Whether this backend supports any audio output. */
214 bool fEnabledOut;
215 /** The Direct Sound playback interface. */
216 LPDIRECTSOUND8 pDS;
217 /** The Direct Sound capturing interface. */
218 LPDIRECTSOUNDCAPTURE8 pDSC;
219#ifdef VBOX_WITH_AUDIO_MMNOTIFICATION_CLIENT
220 VBoxMMNotificationClient *m_pNotificationClient;
221#endif
222#ifdef VBOX_WITH_AUDIO_CALLBACKS
223 /** Callback function to the upper driver.
224 * Can be NULL if not being used / registered. */
225 PFNPDMHOSTAUDIOCALLBACK pfnCallback;
226#endif
227 /** Pointer to the input stream. */
228 PDSOUNDSTREAM pDSStrmIn;
229 /** Pointer to the output stream. */
230 PDSOUNDSTREAM pDSStrmOut;
231} DRVHOSTDSOUND, *PDRVHOSTDSOUND;
232
233
234/*********************************************************************************************************************************
235* Internal Functions *
236*********************************************************************************************************************************/
237static HRESULT directSoundPlayRestore(PDRVHOSTDSOUND pThis, LPDIRECTSOUNDBUFFER8 pDSB);
238static HRESULT directSoundPlayStart(PDRVHOSTDSOUND pThis, PDSOUNDSTREAM pStreamDS);
239static HRESULT directSoundPlayStop(PDRVHOSTDSOUND pThis, PDSOUNDSTREAM pStreamDS, bool fFlush);
240static HRESULT directSoundCaptureStop(PDRVHOSTDSOUND pThis, PDSOUNDSTREAM pStreamDS, bool fFlush);
241
242static int dsoundDevicesEnumerate(PDRVHOSTDSOUND pThis, PDMAUDIODEVICEENUM pDevEnm, uint32_t fEnum);
243
244static int dsoundStreamEnable(PDRVHOSTDSOUND pThis, PDSOUNDSTREAM pStreamDS, bool fEnable);
245static void dsoundStreamReset(PDRVHOSTDSOUND pThis, PDSOUNDSTREAM pStreamDS);
246static void dsoundUpdateStatusInternal(PDRVHOSTDSOUND pThis);
247
248
249static DWORD dsoundRingDistance(DWORD offEnd, DWORD offBegin, DWORD cSize)
250{
251 AssertReturn(offEnd <= cSize, 0);
252 AssertReturn(offBegin <= cSize, 0);
253
254 return offEnd >= offBegin ? offEnd - offBegin : cSize - offBegin + offEnd;
255}
256
257static int dsoundWaveFmtFromCfg(PPDMAUDIOSTREAMCFG pCfg, PWAVEFORMATEX pFmt)
258{
259 AssertPtrReturn(pCfg, VERR_INVALID_POINTER);
260 AssertPtrReturn(pFmt, VERR_INVALID_POINTER);
261
262 RT_BZERO(pFmt, sizeof(WAVEFORMATEX));
263
264 pFmt->wFormatTag = WAVE_FORMAT_PCM;
265 pFmt->nChannels = pCfg->Props.cChannels;
266 pFmt->wBitsPerSample = pCfg->Props.cBytes * 8;
267 pFmt->nSamplesPerSec = pCfg->Props.uHz;
268 pFmt->nBlockAlign = pFmt->nChannels * pFmt->wBitsPerSample / 8;
269 pFmt->nAvgBytesPerSec = pFmt->nSamplesPerSec * pFmt->nBlockAlign;
270 pFmt->cbSize = 0; /* No extra data specified. */
271
272 return VINF_SUCCESS;
273}
274
275/**
276 * Retrieves the number of free bytes available for writing to a DirectSound output stream.
277 *
278 * @return IPRT status code. VERR_NOT_AVAILABLE if unable to determine or the buffer was not recoverable.
279 * @param pThis Host audio driver instance.
280 * @param pStreamDS DirectSound output stream to retrieve number for.
281 * @param pdwFree Where to return the free amount on success.
282 */
283static int dsoundGetFreeOut(PDRVHOSTDSOUND pThis, PDSOUNDSTREAM pStreamDS, DWORD *pdwFree)
284{
285 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
286 AssertPtrReturn(pStreamDS, VERR_INVALID_POINTER);
287 AssertPtrReturn(pdwFree, VERR_INVALID_POINTER);
288
289 Assert(pStreamDS->Cfg.enmDir == PDMAUDIODIR_OUT); /* Paranoia. */
290
291 LPDIRECTSOUNDBUFFER8 pDSB = pStreamDS->Out.pDSB;
292 if (!pDSB)
293 {
294 AssertPtr(pDSB);
295 return VERR_INVALID_POINTER;
296 }
297
298 HRESULT hr = S_OK;
299
300 /* Get the current play position which is used for calculating the free space in the buffer. */
301 for (unsigned i = 0; i < DRV_DSOUND_RESTORE_ATTEMPTS_MAX; i++)
302 {
303 DWORD cbPlayCursor, cbWriteCursor;
304 hr = IDirectSoundBuffer8_GetCurrentPosition(pDSB, &cbPlayCursor, &cbWriteCursor);
305 if (SUCCEEDED(hr))
306 {
307 int32_t cbDiff = cbWriteCursor - cbPlayCursor;
308 if (cbDiff < 0)
309 cbDiff += pStreamDS->cbBufSize;
310
311 int32_t cbFree = cbPlayCursor - pStreamDS->Out.offWritePos;
312 if (cbFree < 0)
313 cbFree += pStreamDS->cbBufSize;
314
315 if (cbFree > (int32_t)pStreamDS->cbBufSize - cbDiff)
316 {
317 pStreamDS->Out.offWritePos = cbWriteCursor;
318 cbFree = pStreamDS->cbBufSize - cbDiff;
319 }
320
321 /* When starting to use a DirectSound buffer, cbPlayCursor and cbWriteCursor
322 * both point at position 0, so we won't be able to detect how many bytes
323 * are writable that way.
324 *
325 * So use our per-stream written indicator to see if we just started a stream. */
326 if (pStreamDS->Out.cbWritten == 0)
327 cbFree = pStreamDS->cbBufSize;
328
329 DSLOGREL(("DSound: cbPlayCursor=%RU32, cbWriteCursor=%RU32, offWritePos=%RU32 -> cbFree=%RI32\n",
330 cbPlayCursor, cbWriteCursor, pStreamDS->Out.offWritePos, cbFree));
331
332 *pdwFree = cbFree;
333
334 return VINF_SUCCESS;
335 }
336
337 if (hr != DSERR_BUFFERLOST) /** @todo MSDN doesn't state this error for GetCurrentPosition(). */
338 break;
339
340 LogFunc(("Getting playing position failed due to lost buffer, restoring ...\n"));
341
342 directSoundPlayRestore(pThis, pDSB);
343 }
344
345 if (hr != DSERR_BUFFERLOST) /* Avoid log flooding if the error is still there. */
346 DSLOGREL(("DSound: Getting current playback position failed with %Rhrc\n", hr));
347
348 LogFunc(("Failed with %Rhrc\n", hr));
349
350 return VERR_NOT_AVAILABLE;
351}
352
353static char *dsoundGUIDToUtf8StrA(LPCGUID pGUID)
354{
355 if (pGUID)
356 {
357 LPOLESTR lpOLEStr;
358 HRESULT hr = StringFromCLSID(*pGUID, &lpOLEStr);
359 if (SUCCEEDED(hr))
360 {
361 char *pszGUID;
362 int rc = RTUtf16ToUtf8(lpOLEStr, &pszGUID);
363 CoTaskMemFree(lpOLEStr);
364
365 return RT_SUCCESS(rc) ? pszGUID : NULL;
366 }
367 }
368
369 return RTStrDup("{Default device}");
370}
371
372static HRESULT directSoundPlayRestore(PDRVHOSTDSOUND pThis, LPDIRECTSOUNDBUFFER8 pDSB)
373{
374 RT_NOREF(pThis);
375 HRESULT hr = IDirectSoundBuffer8_Restore(pDSB);
376 if (FAILED(hr))
377 DSLOG(("DSound: Restoring playback buffer\n"));
378 else
379 DSLOGREL(("DSound: Restoring playback buffer failed with %Rhrc\n", hr));
380
381 return hr;
382}
383
384static HRESULT directSoundPlayUnlock(PDRVHOSTDSOUND pThis, LPDIRECTSOUNDBUFFER8 pDSB,
385 PVOID pv1, PVOID pv2,
386 DWORD cb1, DWORD cb2)
387{
388 RT_NOREF(pThis);
389 HRESULT hr = IDirectSoundBuffer8_Unlock(pDSB, pv1, cb1, pv2, cb2);
390 if (FAILED(hr))
391 DSLOGREL(("DSound: Unlocking playback buffer failed with %Rhrc\n", hr));
392 return hr;
393}
394
395static HRESULT directSoundCaptureUnlock(LPDIRECTSOUNDCAPTUREBUFFER8 pDSCB,
396 PVOID pv1, PVOID pv2,
397 DWORD cb1, DWORD cb2)
398{
399 HRESULT hr = IDirectSoundCaptureBuffer8_Unlock(pDSCB, pv1, cb1, pv2, cb2);
400 if (FAILED(hr))
401 DSLOGREL(("DSound: Unlocking capture buffer failed with %Rhrc\n", hr));
402 return hr;
403}
404
405static HRESULT directSoundPlayLock(PDRVHOSTDSOUND pThis, PDSOUNDSTREAM pStreamDS,
406 DWORD dwOffset, DWORD dwBytes,
407 PVOID *ppv1, PVOID *ppv2,
408 DWORD *pcb1, DWORD *pcb2,
409 DWORD dwFlags)
410{
411 AssertReturn(dwBytes, VERR_INVALID_PARAMETER);
412
413 HRESULT hr = E_FAIL;
414 AssertCompile(DRV_DSOUND_RESTORE_ATTEMPTS_MAX > 0);
415 for (unsigned i = 0; i < DRV_DSOUND_RESTORE_ATTEMPTS_MAX; i++)
416 {
417 PVOID pv1, pv2;
418 DWORD cb1, cb2;
419 hr = IDirectSoundBuffer8_Lock(pStreamDS->Out.pDSB, dwOffset, dwBytes, &pv1, &cb1, &pv2, &cb2, dwFlags);
420 if (SUCCEEDED(hr))
421 {
422 if ( (!pv1 || !(cb1 & pStreamDS->uAlign))
423 && (!pv2 || !(cb2 & pStreamDS->uAlign)))
424 {
425 if (ppv1)
426 *ppv1 = pv1;
427 if (ppv2)
428 *ppv2 = pv2;
429 if (pcb1)
430 *pcb1 = cb1;
431 if (pcb2)
432 *pcb2 = cb2;
433 return S_OK;
434 }
435 DSLOGREL(("DSound: Locking playback buffer returned misaligned buffer: cb1=%#RX32, cb2=%#RX32 (alignment: %#RX32)\n",
436 *pcb1, *pcb2, pStreamDS->uAlign));
437 directSoundPlayUnlock(pThis, pStreamDS->Out.pDSB, pv1, pv2, cb1, cb2);
438 return E_FAIL;
439 }
440
441 if (hr != DSERR_BUFFERLOST)
442 break;
443
444 LogFlowFunc(("Locking failed due to lost buffer, restoring ...\n"));
445 directSoundPlayRestore(pThis, pStreamDS->Out.pDSB);
446 }
447
448 DSLOGREL(("DSound: Locking playback buffer failed with %Rhrc (dwOff=%ld, dwBytes=%ld)\n", hr, dwOffset, dwBytes));
449 return hr;
450}
451
452static HRESULT directSoundCaptureLock(PDSOUNDSTREAM pStreamDS,
453 DWORD dwOffset, DWORD dwBytes,
454 PVOID *ppv1, PVOID *ppv2,
455 DWORD *pcb1, DWORD *pcb2,
456 DWORD dwFlags)
457{
458 PVOID pv1 = NULL;
459 PVOID pv2 = NULL;
460 DWORD cb1 = 0;
461 DWORD cb2 = 0;
462
463 HRESULT hr = IDirectSoundCaptureBuffer8_Lock(pStreamDS->In.pDSCB, dwOffset, dwBytes,
464 &pv1, &cb1, &pv2, &cb2, dwFlags);
465 if (FAILED(hr))
466 {
467 DSLOGREL(("DSound: Locking capture buffer failed with %Rhrc\n", hr));
468 return hr;
469 }
470
471 if ( (pv1 && (cb1 & pStreamDS->uAlign))
472 || (pv2 && (cb2 & pStreamDS->uAlign)))
473 {
474 DSLOGREL(("DSound: Locking capture buffer returned misaligned buffer: cb1=%RI32, cb2=%RI32 (alignment: %RU32)\n",
475 cb1, cb2, pStreamDS->uAlign));
476 directSoundCaptureUnlock(pStreamDS->In.pDSCB, pv1, pv2, cb1, cb2);
477 return E_FAIL;
478 }
479
480 *ppv1 = pv1;
481 *ppv2 = pv2;
482 *pcb1 = cb1;
483 *pcb2 = cb2;
484
485 return S_OK;
486}
487
488/*
489 * DirectSound playback
490 */
491
492/**
493 * Destroys a DirectSound playback interface.
494 *
495 * @param pDS Playback interface to destroy.
496 */
497static void directSoundPlayInterfaceDestroy(LPDIRECTSOUND8 pDS)
498{
499 if (pDS)
500 {
501 LogFlowFuncEnter();
502
503 IDirectSound8_Release(pDS);
504 pDS = NULL;
505 }
506}
507
508/**
509 * Creates a DirectSound playback interface.
510 *
511 * @return HRESULT
512 * @param pGUID GUID of device to create the playback interface for.
513 * @param ppDS Where to store the created interface. Optional.
514 */
515static HRESULT directSoundPlayInterfaceCreate(LPCGUID pGUID, LPDIRECTSOUND8 *ppDS)
516{
517 /* pGUID can be NULL, if this is the default device. */
518 /* ppDS is optional. */
519
520 LogFlowFuncEnter();
521
522 LPDIRECTSOUND8 pDS;
523 HRESULT hr = CoCreateInstance(CLSID_DirectSound8, NULL, CLSCTX_ALL,
524 IID_IDirectSound8, (void **)&pDS);
525 if (FAILED(hr))
526 {
527 DSLOGREL(("DSound: Creating playback instance failed with %Rhrc\n", hr));
528 }
529 else
530 {
531 hr = IDirectSound8_Initialize(pDS, pGUID);
532 if (SUCCEEDED(hr))
533 {
534 HWND hWnd = GetDesktopWindow();
535 hr = IDirectSound8_SetCooperativeLevel(pDS, hWnd, DSSCL_PRIORITY);
536 if (FAILED(hr))
537 DSLOGREL(("DSound: Setting cooperative level for window %p failed with %Rhrc\n", hWnd, hr));
538 }
539
540 if (FAILED(hr))
541 {
542 if (hr == DSERR_NODRIVER) /* Usually means that no playback devices are attached. */
543 DSLOGREL(("DSound: DirectSound playback is currently unavailable\n"));
544 else
545 DSLOGREL(("DSound: DirectSound playback initialization failed with %Rhrc\n", hr));
546
547 directSoundPlayInterfaceDestroy(pDS);
548 }
549 else if (ppDS)
550 {
551 *ppDS = pDS;
552 }
553 }
554
555 LogFlowFunc(("Returning %Rhrc\n", hr));
556 return hr;
557}
558
559static HRESULT directSoundPlayClose(PDRVHOSTDSOUND pThis, PDSOUNDSTREAM pStreamDS)
560{
561 AssertPtrReturn(pThis, E_POINTER);
562 AssertPtrReturn(pStreamDS, E_POINTER);
563
564 LogFlowFuncEnter();
565
566 HRESULT hr = directSoundPlayStop(pThis, pStreamDS, true /* fFlush */);
567 if (FAILED(hr))
568 return hr;
569
570 DSLOG(("DSound: Closing playback stream\n"));
571
572 if (pStreamDS->pCircBuf)
573 Assert(RTCircBufUsed(pStreamDS->pCircBuf) == 0);
574
575 if (SUCCEEDED(hr))
576 {
577 RTCritSectEnter(&pThis->CritSect);
578
579 if (pStreamDS->pCircBuf)
580 {
581 RTCircBufDestroy(pStreamDS->pCircBuf);
582 pStreamDS->pCircBuf = NULL;
583 }
584
585 if (pStreamDS->Out.pDSB)
586 {
587 IDirectSoundBuffer8_Release(pStreamDS->Out.pDSB);
588 pStreamDS->Out.pDSB = NULL;
589 }
590
591 pThis->pDSStrmOut = NULL;
592
593 RTCritSectLeave(&pThis->CritSect);
594 }
595
596 if (FAILED(hr))
597 DSLOGREL(("DSound: Stopping playback stream %p failed with %Rhrc\n", pStreamDS, hr));
598
599 return hr;
600}
601
602static HRESULT directSoundPlayOpen(PDRVHOSTDSOUND pThis, PDSOUNDSTREAM pStreamDS,
603 PPDMAUDIOSTREAMCFG pCfgReq, PPDMAUDIOSTREAMCFG pCfgAcq)
604{
605 AssertPtrReturn(pThis, E_POINTER);
606 AssertPtrReturn(pStreamDS, E_POINTER);
607 AssertPtrReturn(pCfgReq, E_POINTER);
608 AssertPtrReturn(pCfgAcq, E_POINTER);
609
610 LogFlowFuncEnter();
611
612 Assert(pStreamDS->Out.pDSB == NULL);
613
614 DSLOG(("DSound: Opening playback stream (uHz=%RU32, cChannels=%RU8, cBits=%RU8, fSigned=%RTbool)\n",
615 pCfgReq->Props.uHz,
616 pCfgReq->Props.cChannels,
617 pCfgReq->Props.cBytes * 8,
618 pCfgReq->Props.fSigned));
619
620 WAVEFORMATEX wfx;
621 int rc = dsoundWaveFmtFromCfg(pCfgReq, &wfx);
622 if (RT_FAILURE(rc))
623 return E_INVALIDARG;
624
625 DSLOG(("DSound: Requested playback format:\n"
626 " wFormatTag = %RI16\n"
627 " nChannels = %RI16\n"
628 " nSamplesPerSec = %RU32\n"
629 " nAvgBytesPerSec = %RU32\n"
630 " nBlockAlign = %RI16\n"
631 " wBitsPerSample = %RI16\n"
632 " cbSize = %RI16\n",
633 wfx.wFormatTag,
634 wfx.nChannels,
635 wfx.nSamplesPerSec,
636 wfx.nAvgBytesPerSec,
637 wfx.nBlockAlign,
638 wfx.wBitsPerSample,
639 wfx.cbSize));
640
641 dsoundUpdateStatusInternal(pThis);
642
643 HRESULT hr = directSoundPlayInterfaceCreate(pThis->Cfg.pGuidPlay, &pThis->pDS);
644 if (FAILED(hr))
645 return hr;
646
647 do /* To use breaks. */
648 {
649 LPDIRECTSOUNDBUFFER pDSB = NULL;
650
651 DSBUFFERDESC bd;
652 RT_ZERO(bd);
653 bd.dwSize = sizeof(bd);
654 bd.lpwfxFormat = &wfx;
655
656 /*
657 * As we reuse our (secondary) buffer for playing out data as it comes in,
658 * we're using this buffer as a so-called streaming buffer.
659 *
660 * See https://msdn.microsoft.com/en-us/library/windows/desktop/ee419014(v=vs.85).aspx
661 *
662 * However, as we do not want to use memory on the sound device directly
663 * (as most modern audio hardware on the host doesn't have this anyway),
664 * we're *not* going to use DSBCAPS_STATIC for that.
665 *
666 * Instead we're specifying DSBCAPS_LOCSOFTWARE, as this fits the bill
667 * of copying own buffer data to our secondary's Direct Sound buffer.
668 */
669 bd.dwFlags = DSBCAPS_GLOBALFOCUS | DSBCAPS_GETCURRENTPOSITION2 | DSBCAPS_LOCSOFTWARE;
670 bd.dwBufferBytes = DrvAudioHlpFramesToBytes(pCfgReq->Backend.cfBufferSize, &pCfgReq->Props);
671
672 DSLOG(("DSound: Requested playback buffer is %RU64ms (%ld bytes)\n",
673 DrvAudioHlpBytesToMilli(bd.dwBufferBytes, &pCfgReq->Props), bd.dwBufferBytes));
674
675 hr = IDirectSound8_CreateSoundBuffer(pThis->pDS, &bd, &pDSB, NULL);
676 if (FAILED(hr))
677 {
678 DSLOGREL(("DSound: Creating playback sound buffer failed with %Rhrc\n", hr));
679 break;
680 }
681
682 /* "Upgrade" to IDirectSoundBuffer8 interface. */
683 hr = IDirectSoundBuffer_QueryInterface(pDSB, IID_IDirectSoundBuffer8, (PVOID *)&pStreamDS->Out.pDSB);
684 IDirectSoundBuffer_Release(pDSB);
685 if (FAILED(hr))
686 {
687 DSLOGREL(("DSound: Querying playback sound buffer interface failed with %Rhrc\n", hr));
688 break;
689 }
690
691 /*
692 * Query the actual parameters set for this stream.
693 * Those might be different than the initially requested parameters.
694 */
695 RT_ZERO(wfx);
696 hr = IDirectSoundBuffer8_GetFormat(pStreamDS->Out.pDSB, &wfx, sizeof(wfx), NULL);
697 if (FAILED(hr))
698 {
699 DSLOGREL(("DSound: Getting playback format failed with %Rhrc\n", hr));
700 break;
701 }
702
703 DSBCAPS bc;
704 RT_ZERO(bc);
705 bc.dwSize = sizeof(bc);
706
707 hr = IDirectSoundBuffer8_GetCaps(pStreamDS->Out.pDSB, &bc);
708 if (FAILED(hr))
709 {
710 DSLOGREL(("DSound: Getting playback capabilities failed with %Rhrc\n", hr));
711 break;
712 }
713
714 DSLOG(("DSound: Acquired playback buffer is %RU64ms (%ld bytes)\n",
715 DrvAudioHlpBytesToMilli(bc.dwBufferBytes, &pCfgReq->Props), bc.dwBufferBytes));
716
717 DSLOG(("DSound: Acquired playback format:\n"
718 " dwBufferBytes = %RI32\n"
719 " dwFlags = 0x%x\n"
720 " wFormatTag = %RI16\n"
721 " nChannels = %RI16\n"
722 " nSamplesPerSec = %RU32\n"
723 " nAvgBytesPerSec = %RU32\n"
724 " nBlockAlign = %RI16\n"
725 " wBitsPerSample = %RI16\n"
726 " cbSize = %RI16\n",
727 bc.dwBufferBytes,
728 bc.dwFlags,
729 wfx.wFormatTag,
730 wfx.nChannels,
731 wfx.nSamplesPerSec,
732 wfx.nAvgBytesPerSec,
733 wfx.nBlockAlign,
734 wfx.wBitsPerSample,
735 wfx.cbSize));
736
737 if (bc.dwBufferBytes & pStreamDS->uAlign)
738 DSLOGREL(("DSound: Playback capabilities returned misaligned buffer: size %RU32, alignment %RU32\n",
739 bc.dwBufferBytes, pStreamDS->uAlign + 1));
740
741 /*
742 * Initial state.
743 * dsoundPlayStart initializes part of it to make sure that Stop/Start continues with a correct
744 * playback buffer position.
745 */
746 pStreamDS->cbBufSize = bc.dwBufferBytes;
747
748 rc = RTCircBufCreate(&pStreamDS->pCircBuf, pStreamDS->cbBufSize) * 2; /* Use "double buffering" */
749 AssertRC(rc);
750
751 pThis->pDSStrmOut = pStreamDS;
752
753 const uint32_t cfBufSize = PDMAUDIOSTREAMCFG_B2F(pCfgAcq, pStreamDS->cbBufSize);
754
755 pCfgAcq->Backend.cfBufferSize = cfBufSize;
756 pCfgAcq->Backend.cfPeriod = cfBufSize / 4;
757 pCfgAcq->Backend.cfPreBuf = pCfgAcq->Backend.cfPeriod * 2;
758
759 } while (0);
760
761 if (FAILED(hr))
762 directSoundPlayClose(pThis, pStreamDS);
763
764 return hr;
765}
766
767static void dsoundPlayClearBuffer(PDRVHOSTDSOUND pThis, PDSOUNDSTREAM pStreamDS)
768{
769 AssertPtrReturnVoid(pStreamDS);
770
771 PPDMAUDIOPCMPROPS pProps = &pStreamDS->Cfg.Props;
772
773 HRESULT hr = IDirectSoundBuffer_SetCurrentPosition(pStreamDS->Out.pDSB, 0 /* Position */);
774 if (FAILED(hr))
775 DSLOGREL(("DSound: Setting current position to 0 when clearing buffer failed with %Rhrc\n", hr));
776
777 PVOID pv1;
778 hr = directSoundPlayLock(pThis, pStreamDS,
779 0 /* dwOffset */, pStreamDS->cbBufSize,
780 &pv1, NULL, 0, 0, DSBLOCK_ENTIREBUFFER);
781 if (SUCCEEDED(hr))
782 {
783 DrvAudioHlpClearBuf(pProps, pv1, pStreamDS->cbBufSize, PDMAUDIOPCMPROPS_B2F(pProps, pStreamDS->cbBufSize));
784
785 directSoundPlayUnlock(pThis, pStreamDS->Out.pDSB, pv1, NULL, 0, 0);
786
787 /* Make sure to get the last playback position and current write position from DirectSound again.
788 * Those positions in theory could have changed, re-fetch them to be sure. */
789 hr = IDirectSoundBuffer_GetCurrentPosition(pStreamDS->Out.pDSB,
790 &pStreamDS->Out.offPlayCursorLastPlayed, &pStreamDS->Out.offWritePos);
791 if (FAILED(hr))
792 DSLOGREL(("DSound: Re-fetching current position when clearing buffer failed with %Rhrc\n", hr));
793 }
794}
795
796/**
797 * Transfers audio data from the internal buffer to the DirectSound playback instance.
798 * Due to internal accounting and querying DirectSound, this function knows how much it can transfer at once.
799 *
800 * @return IPRT status code.
801 * @param pThis Host audio driver instance.
802 * @param pStreamDS Stream to transfer playback data for.
803 */
804static int dsoundPlayTransfer(PDRVHOSTDSOUND pThis, PDSOUNDSTREAM pStreamDS)
805{
806 if (!pStreamDS->fEnabled)
807 {
808 Log2Func(("Stream disabled, skipping\n"));
809 return VINF_SUCCESS;
810 }
811
812 uint32_t cbTransferred = 0;
813
814 PRTCIRCBUF pCircBuf = pStreamDS->pCircBuf;
815 AssertPtr(pCircBuf);
816
817 LPDIRECTSOUNDBUFFER8 pDSB = pStreamDS->Out.pDSB;
818 AssertPtr(pDSB);
819
820 int rc = VINF_SUCCESS;
821
822 DWORD offPlayCursor, offWriteCursor;
823 HRESULT hr = IDirectSoundBuffer8_GetCurrentPosition(pDSB, &offPlayCursor, &offWriteCursor);
824 if (FAILED(hr))
825 {
826 rc = VERR_ACCESS_DENIED; /** @todo Find a better rc. */
827 return rc;
828 }
829
830 DWORD cbFree, cbRemaining;
831 if (pStreamDS->Out.fFirstTransfer)
832 {
833 cbRemaining = 0;
834 cbFree = pStreamDS->cbBufSize;
835 }
836 else
837 {
838 cbFree = dsoundRingDistance(offPlayCursor, pStreamDS->Out.offWritePos, pStreamDS->cbBufSize);
839 cbRemaining = dsoundRingDistance(pStreamDS->Out.offWritePos, offPlayCursor, pStreamDS->cbBufSize);
840 }
841
842 uint32_t cbAvail = (uint32_t)RTCircBufUsed(pCircBuf);
843 uint32_t cbToTransfer = RT_MIN(cbFree, cbAvail);
844
845#ifdef LOG_ENABLED
846 if (!pStreamDS->Dbg.tsLastTransferredMs)
847 pStreamDS->Dbg.tsLastTransferredMs = RTTimeMilliTS();
848 Log3Func(("offPlay=%RU32, offWrite=%RU32, tsLastTransferredMs=%RU64ms, cbAvail=%RU32, cbFree=%RU32 -> cbToTransfer=%RU32 "
849 "(fFirst=%RTbool, fDrain=%RTbool)\n",
850 offPlayCursor, offWriteCursor, RTTimeMilliTS() - pStreamDS->Dbg.tsLastTransferredMs, cbAvail, cbFree, cbToTransfer,
851 pStreamDS->Out.fFirstTransfer, pStreamDS->Out.fDrain));
852 pStreamDS->Dbg.tsLastTransferredMs = RTTimeMilliTS();
853#endif
854
855 while (cbToTransfer)
856 {
857 DWORD cb1 = 0;
858 DWORD cb2 = 0;
859
860 void *pvBuf;
861 size_t cbBuf;
862 RTCircBufAcquireReadBlock(pCircBuf, cbToTransfer, &pvBuf, &cbBuf);
863
864 if (cbBuf)
865 {
866 PVOID pv1, pv2;
867 hr = directSoundPlayLock(pThis, pStreamDS, pStreamDS->Out.offWritePos, (DWORD)cbBuf,
868 &pv1, &pv2, &cb1, &cb2, 0 /* dwFlags */);
869 if (FAILED(hr))
870 {
871 rc = VERR_ACCESS_DENIED;
872 break;
873 }
874
875 AssertPtr(pv1);
876 Assert(cb1);
877
878 memcpy(pv1, pvBuf, cb1);
879
880 if (pv2 && cb2) /* Buffer wrap-around? Write second part. */
881 memcpy(pv2, (uint8_t *)pvBuf + cb1, cb2);
882
883 directSoundPlayUnlock(pThis, pDSB, pv1, pv2, cb1, cb2);
884
885 pStreamDS->Out.offWritePos = (pStreamDS->Out.offWritePos + cb1 + cb2) % pStreamDS->cbBufSize;
886
887 Assert(cbToTransfer >= cbBuf);
888 cbToTransfer -= (uint32_t)cbBuf;
889
890 cbTransferred += cb1 + cb2;
891 }
892
893 RTCircBufReleaseReadBlock(pCircBuf, cb1 + cb2);
894 }
895
896 pStreamDS->Out.cbTransferred += cbTransferred;
897
898 if ( pStreamDS->Out.fFirstTransfer
899 && pStreamDS->Out.cbTransferred >= DrvAudioHlpFramesToBytes(pStreamDS->Cfg.Backend.cfPreBuf, &pStreamDS->Cfg.Props))
900 {
901 hr = directSoundPlayStart(pThis, pStreamDS);
902 if (SUCCEEDED(hr))
903 {
904 pStreamDS->Out.fFirstTransfer = false;
905 }
906 else
907 rc = VERR_ACCESS_DENIED; /** @todo Find a better rc. */
908 }
909
910 cbAvail = (uint32_t)RTCircBufUsed(pCircBuf);
911 if ( !cbAvail
912 && cbTransferred)
913 {
914 pStreamDS->Out.cbLastTransferred = cbTransferred;
915 pStreamDS->Out.tsLastTransferredMs = RTTimeMilliTS();
916
917 LogFlowFunc(("cbLastTransferred=%RU32, tsLastTransferredMs=%RU64\n",
918 pStreamDS->Out.cbLastTransferred, pStreamDS->Out.tsLastTransferredMs));
919 }
920
921 LogFlowFunc(("cbTransferred=%RU32, cbAvail=%RU32, rc=%Rrc\n", cbTransferred, cbAvail, rc));
922 return rc;
923}
924
925static HRESULT directSoundPlayGetStatus(PDRVHOSTDSOUND pThis, LPDIRECTSOUNDBUFFER8 pDSB, DWORD *pdwStatus)
926{
927 AssertPtrReturn(pThis, E_POINTER);
928 AssertPtrReturn(pDSB, E_POINTER);
929
930 AssertPtrNull(pdwStatus);
931
932 DWORD dwStatus = 0;
933 HRESULT hr = E_FAIL;
934 for (unsigned i = 0; i < DRV_DSOUND_RESTORE_ATTEMPTS_MAX; i++)
935 {
936 hr = IDirectSoundBuffer8_GetStatus(pDSB, &dwStatus);
937 if ( hr == DSERR_BUFFERLOST
938 || ( SUCCEEDED(hr)
939 && (dwStatus & DSBSTATUS_BUFFERLOST)))
940 {
941 LogFlowFunc(("Getting status failed due to lost buffer, restoring ...\n"));
942 directSoundPlayRestore(pThis, pDSB);
943 }
944 else
945 break;
946 }
947
948 if (SUCCEEDED(hr))
949 {
950 if (pdwStatus)
951 *pdwStatus = dwStatus;
952 }
953 else
954 DSLOGREL(("DSound: Retrieving playback status failed with %Rhrc\n", hr));
955
956 return hr;
957}
958
959static HRESULT directSoundPlayStop(PDRVHOSTDSOUND pThis, PDSOUNDSTREAM pStreamDS, bool fFlush)
960{
961 AssertPtrReturn(pThis, E_POINTER);
962 AssertPtrReturn(pStreamDS, E_POINTER);
963
964 HRESULT hr = S_OK;
965
966 if (pStreamDS->Out.pDSB)
967 {
968 DSLOG(("DSound: Stopping playback\n"));
969 hr = IDirectSoundBuffer8_Stop(pStreamDS->Out.pDSB);
970 if (FAILED(hr))
971 {
972 hr = directSoundPlayRestore(pThis, pStreamDS->Out.pDSB);
973 if (FAILED(hr))
974 hr = IDirectSoundBuffer8_Stop(pStreamDS->Out.pDSB);
975 }
976 }
977
978 if (SUCCEEDED(hr))
979 {
980 if (fFlush)
981 dsoundStreamReset(pThis, pStreamDS);
982 }
983
984 if (FAILED(hr))
985 DSLOGREL(("DSound: %s playback failed with %Rhrc\n", fFlush ? "Stopping" : "Pausing", hr));
986
987 return hr;
988}
989
990/**
991 * Enables or disables a stream.
992 *
993 * @return IPRT status code.
994 * @param pThis Host audio driver instance.
995 * @param pStreamDS Stream to enable / disable.
996 * @param fEnable Whether to enable or disable the stream.
997 */
998static int dsoundStreamEnable(PDRVHOSTDSOUND pThis, PDSOUNDSTREAM pStreamDS, bool fEnable)
999{
1000 RT_NOREF(pThis);
1001
1002 LogFunc(("%s %s\n",
1003 fEnable ? "Enabling" : "Disabling",
1004 pStreamDS->Cfg.enmDir == PDMAUDIODIR_IN ? "capture" : "playback"));
1005
1006 if (fEnable)
1007 dsoundStreamReset(pThis, pStreamDS);
1008
1009 pStreamDS->fEnabled = fEnable;
1010
1011 return VINF_SUCCESS;
1012}
1013
1014
1015/**
1016 * Resets the state of a DirectSound stream.
1017 *
1018 * @param pThis Host audio driver instance.
1019 * @param pStreamDS Stream to reset state for.
1020 */
1021static void dsoundStreamReset(PDRVHOSTDSOUND pThis, PDSOUNDSTREAM pStreamDS)
1022{
1023 RT_NOREF(pThis);
1024
1025 LogFunc(("Resetting %s\n",
1026 pStreamDS->Cfg.enmDir == PDMAUDIODIR_IN ? "capture" : "playback"));
1027
1028 if (pStreamDS->pCircBuf)
1029 RTCircBufReset(pStreamDS->pCircBuf);
1030
1031 if (pStreamDS->Cfg.enmDir == PDMAUDIODIR_IN)
1032 {
1033 pStreamDS->In.offReadPos = 0;
1034 pStreamDS->In.cOverruns = 0;
1035
1036 /* Also reset the DirectSound Capture Buffer (DSCB) by clearing all data to make sure
1037 * not stale audio data is left. */
1038 if (pStreamDS->In.pDSCB)
1039 {
1040 PVOID pv1; PVOID pv2; DWORD cb1; DWORD cb2;
1041 HRESULT hr = directSoundCaptureLock(pStreamDS, 0 /* Offset */, pStreamDS->cbBufSize, &pv1, &pv2, &cb1, &cb2,
1042 0 /* Flags */);
1043 if (SUCCEEDED(hr))
1044 {
1045 DrvAudioHlpClearBuf(&pStreamDS->Cfg.Props, pv1, cb1, PDMAUDIOPCMPROPS_B2F(&pStreamDS->Cfg.Props, cb1));
1046 if (pv2 && cb2)
1047 DrvAudioHlpClearBuf(&pStreamDS->Cfg.Props, pv2, cb2, PDMAUDIOPCMPROPS_B2F(&pStreamDS->Cfg.Props, cb2));
1048 directSoundCaptureUnlock(pStreamDS->In.pDSCB, pv1, pv2, cb1, cb2);
1049 }
1050 }
1051 }
1052 else if (pStreamDS->Cfg.enmDir == PDMAUDIODIR_OUT)
1053 {
1054 pStreamDS->Out.fFirstTransfer = true;
1055 pStreamDS->Out.fDrain = false;
1056 pStreamDS->Out.cUnderruns = 0;
1057
1058 pStreamDS->Out.cbLastTransferred = 0;
1059 pStreamDS->Out.tsLastTransferredMs = 0;
1060
1061 pStreamDS->Out.cbTransferred = 0;
1062 pStreamDS->Out.cbWritten = 0;
1063
1064 pStreamDS->Out.offWritePos = 0;
1065 pStreamDS->Out.offPlayCursorLastPending = 0;
1066 pStreamDS->Out.offPlayCursorLastPlayed = 0;
1067
1068 /* Also reset the DirectSound Buffer (DSB) by setting the position to 0 and clear all data to make sure
1069 * not stale audio data is left. */
1070 if (pStreamDS->Out.pDSB)
1071 {
1072 HRESULT hr = IDirectSoundBuffer8_SetCurrentPosition(pStreamDS->Out.pDSB, 0);
1073 if (SUCCEEDED(hr))
1074 {
1075 PVOID pv1; PVOID pv2; DWORD cb1; DWORD cb2;
1076 hr = directSoundPlayLock(pThis, pStreamDS, 0 /* Offset */, pStreamDS->cbBufSize, &pv1, &pv2, &cb1, &cb2,
1077 0 /* Flags */);
1078 if (SUCCEEDED(hr))
1079 {
1080 DrvAudioHlpClearBuf(&pStreamDS->Cfg.Props, pv1, cb1, PDMAUDIOPCMPROPS_B2F(&pStreamDS->Cfg.Props, cb1));
1081 if (pv2 && cb2)
1082 DrvAudioHlpClearBuf(&pStreamDS->Cfg.Props, pv2, cb2, PDMAUDIOPCMPROPS_B2F(&pStreamDS->Cfg.Props, cb2));
1083 directSoundPlayUnlock(pThis, pStreamDS->Out.pDSB, pv1, pv2, cb1, cb2);
1084 }
1085 }
1086 }
1087 }
1088
1089#ifdef LOG_ENABLED
1090 pStreamDS->Dbg.tsLastTransferredMs = 0;
1091#endif
1092}
1093
1094
1095/**
1096 * Starts playing a DirectSound stream.
1097 *
1098 * @return HRESULT
1099 * @param pThis Host audio driver instance.
1100 * @param pStreamDS Stream to start playing.
1101 */
1102static HRESULT directSoundPlayStart(PDRVHOSTDSOUND pThis, PDSOUNDSTREAM pStreamDS)
1103{
1104 HRESULT hr = S_OK;
1105
1106 DWORD fFlags = DSCBSTART_LOOPING;
1107
1108 for (unsigned i = 0; i < DRV_DSOUND_RESTORE_ATTEMPTS_MAX; i++)
1109 {
1110 DSLOG(("DSound: Starting playback\n"));
1111 hr = IDirectSoundBuffer8_Play(pStreamDS->Out.pDSB, 0, 0, fFlags);
1112 if ( SUCCEEDED(hr)
1113 || hr != DSERR_BUFFERLOST)
1114 break;
1115 else
1116 {
1117 LogFunc(("Restarting playback failed due to lost buffer, restoring ...\n"));
1118 directSoundPlayRestore(pThis, pStreamDS->Out.pDSB);
1119 }
1120 }
1121
1122 return hr;
1123}
1124
1125
1126/*
1127 * DirectSoundCapture
1128 */
1129
1130static LPCGUID dsoundCaptureSelectDevice(PDRVHOSTDSOUND pThis, PPDMAUDIOSTREAMCFG pCfg)
1131{
1132 AssertPtrReturn(pThis, NULL);
1133 AssertPtrReturn(pCfg, NULL);
1134
1135 int rc = VINF_SUCCESS;
1136
1137 LPCGUID pGUID = pThis->Cfg.pGuidCapture;
1138 if (!pGUID)
1139 {
1140 PPDMAUDIODEVICE pDev = NULL;
1141
1142 switch (pCfg->DestSource.Source)
1143 {
1144 case PDMAUDIORECSOURCE_LINE:
1145 /*
1146 * At the moment we're only supporting line-in in the HDA emulation,
1147 * and line-in + mic-in in the AC'97 emulation both are expected
1148 * to use the host's mic-in as well.
1149 *
1150 * So the fall through here is intentional for now.
1151 */
1152 case PDMAUDIORECSOURCE_MIC:
1153 {
1154 pDev = DrvAudioHlpDeviceEnumGetDefaultDevice(&pThis->DeviceEnum, PDMAUDIODIR_IN);
1155 break;
1156 }
1157
1158 default:
1159 AssertFailedStmt(rc = VERR_NOT_SUPPORTED);
1160 break;
1161 }
1162
1163 if ( RT_SUCCESS(rc)
1164 && pDev)
1165 {
1166 DSLOG(("DSound: Guest source '%s' is using host recording device '%s'\n",
1167 DrvAudioHlpRecSrcToStr(pCfg->DestSource.Source), pDev->szName));
1168
1169 PDSOUNDDEV pDSoundDev = (PDSOUNDDEV )pDev->pvData;
1170 AssertPtr(pDSoundDev);
1171
1172 pGUID = &pDSoundDev->Guid;
1173 }
1174 }
1175
1176 if (RT_FAILURE(rc))
1177 {
1178 LogRel(("DSound: Selecting recording device failed with %Rrc\n", rc));
1179 return NULL;
1180 }
1181
1182 char *pszGUID = dsoundGUIDToUtf8StrA(pGUID);
1183
1184 /* This always has to be in the release log. */
1185 LogRel(("DSound: Guest source '%s' is using host recording device with GUID '%s'\n",
1186 DrvAudioHlpRecSrcToStr(pCfg->DestSource.Source), pszGUID ? pszGUID: "{?}"));
1187
1188 if (pszGUID)
1189 {
1190 RTStrFree(pszGUID);
1191 pszGUID = NULL;
1192 }
1193
1194 return pGUID;
1195}
1196
1197/**
1198 * Transfers audio data from the DirectSound capture instance to the internal buffer.
1199 * Due to internal accounting and querying DirectSound, this function knows how much it can transfer at once.
1200 *
1201 * @return IPRT status code.
1202 * @param pThis Host audio driver instance.
1203 * @param pStreamDS Stream to capture audio data for.
1204 */
1205static int dsoundCaptureTransfer(PDRVHOSTDSOUND pThis, PDSOUNDSTREAM pStreamDS)
1206{
1207 RT_NOREF(pThis);
1208
1209 LPDIRECTSOUNDCAPTUREBUFFER8 pDSCB = pStreamDS->In.pDSCB;
1210 AssertPtr(pDSCB);
1211
1212 DWORD offCaptureCursor;
1213 HRESULT hr = IDirectSoundCaptureBuffer_GetCurrentPosition(pDSCB, NULL, &offCaptureCursor);
1214 if (FAILED(hr))
1215 {
1216 AssertFailed();
1217 return VERR_ACCESS_DENIED; /** @todo Find a better rc. */
1218 }
1219
1220 DWORD cbUsed = dsoundRingDistance(offCaptureCursor, pStreamDS->In.offReadPos, pStreamDS->cbBufSize);
1221
1222 PRTCIRCBUF pCircBuf = pStreamDS->pCircBuf;
1223 AssertPtr(pCircBuf);
1224
1225 uint32_t cbFree = (uint32_t)RTCircBufFree(pCircBuf);
1226 if ( !cbFree
1227 && pStreamDS->In.cOverruns < 32) /** @todo Make this configurable. */
1228 {
1229 DSLOG(("DSound: Warning: Ring buffer full, skipping to record data (overflow #%RU32)\n", pStreamDS->In.cOverruns));
1230 DSLOG(("DSound: DSound capture buffer currently uses %RU32/%RU32 bytes\n", cbUsed, pStreamDS->cbBufSize));
1231 pStreamDS->In.cOverruns++;
1232 }
1233
1234 DWORD cbToCapture = RT_MIN(cbUsed, cbFree);
1235
1236 Log3Func(("cbUsed=%ld, cbToCapture=%ld\n", cbUsed, cbToCapture));
1237
1238 while (cbToCapture)
1239 {
1240 void *pvBuf;
1241 size_t cbBuf;
1242 RTCircBufAcquireWriteBlock(pCircBuf, cbToCapture, &pvBuf, &cbBuf);
1243
1244 if (cbBuf)
1245 {
1246 PVOID pv1, pv2;
1247 DWORD cb1, cb2;
1248 hr = directSoundCaptureLock(pStreamDS, pStreamDS->In.offReadPos, (DWORD)cbBuf,
1249 &pv1, &pv2, &cb1, &cb2, 0 /* dwFlags */);
1250 if (FAILED(hr))
1251 break;
1252
1253 AssertPtr(pv1);
1254 Assert(cb1);
1255
1256 memcpy(pvBuf, pv1, cb1);
1257
1258 if (pv2 && cb2) /* Buffer wrap-around? Write second part. */
1259 memcpy((uint8_t *)pvBuf + cb1, pv2, cb2);
1260
1261 directSoundCaptureUnlock(pDSCB, pv1, pv2, cb1, cb2);
1262
1263 pStreamDS->In.offReadPos = (pStreamDS->In.offReadPos + cb1 + cb2) % pStreamDS->cbBufSize;
1264
1265 Assert(cbToCapture >= cbBuf);
1266 cbToCapture -= (uint32_t)cbBuf;
1267 }
1268
1269#ifdef VBOX_AUDIO_DEBUG_DUMP_PCM_DATA
1270 if (cbBuf)
1271 {
1272 RTFILE fh;
1273 int rc2 = RTFileOpen(&fh, VBOX_AUDIO_DEBUG_DUMP_PCM_DATA_PATH "dsoundCapture.pcm",
1274 RTFILE_O_OPEN_CREATE | RTFILE_O_APPEND | RTFILE_O_WRITE | RTFILE_O_DENY_NONE);
1275 if (RT_SUCCESS(rc2))
1276 {
1277 RTFileWrite(fh, pvBuf, cbBuf, NULL);
1278 RTFileClose(fh);
1279 }
1280 }
1281#endif
1282 RTCircBufReleaseWriteBlock(pCircBuf, cbBuf);
1283 }
1284
1285 return VINF_SUCCESS;
1286}
1287
1288/**
1289 * Destroys a DirectSound capture interface.
1290 *
1291 * @param pDSC Capture interface to destroy.
1292 */
1293static void directSoundCaptureInterfaceDestroy(LPDIRECTSOUNDCAPTURE8 pDSC)
1294{
1295 if (pDSC)
1296 {
1297 LogFlowFuncEnter();
1298
1299 IDirectSoundCapture_Release(pDSC);
1300 pDSC = NULL;
1301 }
1302}
1303
1304/**
1305 * Creates a DirectSound capture interface.
1306 *
1307 * @return HRESULT
1308 * @param pGUID GUID of device to create the capture interface for.
1309 * @param ppDSC Where to store the created interface. Optional.
1310 */
1311static HRESULT directSoundCaptureInterfaceCreate(LPCGUID pGUID, LPDIRECTSOUNDCAPTURE8 *ppDSC)
1312{
1313 /* pGUID can be NULL, if this is the default device. */
1314 /* ppDSC is optional. */
1315
1316 LogFlowFuncEnter();
1317
1318 LPDIRECTSOUNDCAPTURE8 pDSC;
1319 HRESULT hr = CoCreateInstance(CLSID_DirectSoundCapture8, NULL, CLSCTX_ALL,
1320 IID_IDirectSoundCapture8, (void **)&pDSC);
1321 if (FAILED(hr))
1322 {
1323 DSLOGREL(("DSound: Creating capture instance failed with %Rhrc\n", hr));
1324 }
1325 else
1326 {
1327 hr = IDirectSoundCapture_Initialize(pDSC, pGUID);
1328 if (FAILED(hr))
1329 {
1330 if (hr == DSERR_NODRIVER) /* Usually means that no capture devices are attached. */
1331 DSLOGREL(("DSound: Capture device currently is unavailable\n"));
1332 else
1333 DSLOGREL(("DSound: Initializing capturing device failed with %Rhrc\n", hr));
1334
1335 directSoundCaptureInterfaceDestroy(pDSC);
1336 }
1337 else if (ppDSC)
1338 {
1339 *ppDSC = pDSC;
1340 }
1341 }
1342
1343 LogFlowFunc(("Returning %Rhrc\n", hr));
1344 return hr;
1345}
1346
1347static HRESULT directSoundCaptureClose(PDRVHOSTDSOUND pThis, PDSOUNDSTREAM pStreamDS)
1348{
1349 AssertPtrReturn(pThis, E_POINTER);
1350 AssertPtrReturn(pStreamDS, E_POINTER);
1351
1352 LogFlowFuncEnter();
1353
1354 HRESULT hr = directSoundCaptureStop(pThis, pStreamDS, true /* fFlush */);
1355 if (FAILED(hr))
1356 return hr;
1357
1358 if ( pStreamDS
1359 && pStreamDS->In.pDSCB)
1360 {
1361 DSLOG(("DSound: Closing capturing stream\n"));
1362
1363 IDirectSoundCaptureBuffer8_Release(pStreamDS->In.pDSCB);
1364 pStreamDS->In.pDSCB = NULL;
1365 }
1366
1367 LogFlowFunc(("Returning %Rhrc\n", hr));
1368 return hr;
1369}
1370
1371static HRESULT directSoundCaptureOpen(PDRVHOSTDSOUND pThis, PDSOUNDSTREAM pStreamDS,
1372 PPDMAUDIOSTREAMCFG pCfgReq, PPDMAUDIOSTREAMCFG pCfgAcq)
1373{
1374 AssertPtrReturn(pThis, E_POINTER);
1375 AssertPtrReturn(pStreamDS, E_POINTER);
1376 AssertPtrReturn(pCfgReq, E_POINTER);
1377 AssertPtrReturn(pCfgAcq, E_POINTER);
1378
1379 LogFlowFuncEnter();
1380
1381 Assert(pStreamDS->In.pDSCB == NULL);
1382
1383 DSLOG(("DSound: Opening capturing stream (uHz=%RU32, cChannels=%RU8, cBits=%RU8, fSigned=%RTbool)\n",
1384 pCfgReq->Props.uHz,
1385 pCfgReq->Props.cChannels,
1386 pCfgReq->Props.cBytes * 8,
1387 pCfgReq->Props.fSigned));
1388
1389 WAVEFORMATEX wfx;
1390 int rc = dsoundWaveFmtFromCfg(pCfgReq, &wfx);
1391 if (RT_FAILURE(rc))
1392 return E_INVALIDARG;
1393
1394 dsoundUpdateStatusInternal(pThis);
1395
1396 HRESULT hr = directSoundCaptureInterfaceCreate(pThis->Cfg.pGuidCapture, &pThis->pDSC);
1397 if (FAILED(hr))
1398 return hr;
1399
1400 do /* To use breaks. */
1401 {
1402 DSCBUFFERDESC bd;
1403 RT_ZERO(bd);
1404
1405 bd.dwSize = sizeof(bd);
1406 bd.lpwfxFormat = &wfx;
1407 bd.dwBufferBytes = DrvAudioHlpFramesToBytes(pCfgReq->Backend.cfBufferSize, &pCfgReq->Props);
1408
1409 DSLOG(("DSound: Requested capture buffer is %RU64ms (%ld bytes)\n",
1410 DrvAudioHlpBytesToMilli(bd.dwBufferBytes, &pCfgReq->Props), bd.dwBufferBytes));
1411
1412 LPDIRECTSOUNDCAPTUREBUFFER pDSCB;
1413 hr = IDirectSoundCapture_CreateCaptureBuffer(pThis->pDSC, &bd, &pDSCB, NULL);
1414 if (FAILED(hr))
1415 {
1416 if (hr == E_ACCESSDENIED)
1417 {
1418 DSLOGREL(("DSound: Capturing input from host not possible, access denied\n"));
1419 }
1420 else
1421 DSLOGREL(("DSound: Creating capture buffer failed with %Rhrc\n", hr));
1422 break;
1423 }
1424
1425 hr = IDirectSoundCaptureBuffer_QueryInterface(pDSCB, IID_IDirectSoundCaptureBuffer8, (void **)&pStreamDS->In.pDSCB);
1426 IDirectSoundCaptureBuffer_Release(pDSCB);
1427 if (FAILED(hr))
1428 {
1429 DSLOGREL(("DSound: Querying interface for capture buffer failed with %Rhrc\n", hr));
1430 break;
1431 }
1432
1433 /*
1434 * Query the actual parameters.
1435 */
1436 DWORD offByteReadPos = 0;
1437 hr = IDirectSoundCaptureBuffer8_GetCurrentPosition(pStreamDS->In.pDSCB, NULL, &offByteReadPos);
1438 if (FAILED(hr))
1439 {
1440 offByteReadPos = 0;
1441 DSLOGREL(("DSound: Getting capture position failed with %Rhrc\n", hr));
1442 }
1443
1444 RT_ZERO(wfx);
1445 hr = IDirectSoundCaptureBuffer8_GetFormat(pStreamDS->In.pDSCB, &wfx, sizeof(wfx), NULL);
1446 if (FAILED(hr))
1447 {
1448 DSLOGREL(("DSound: Getting capture format failed with %Rhrc\n", hr));
1449 break;
1450 }
1451
1452 DSCBCAPS bc;
1453 RT_ZERO(bc);
1454 bc.dwSize = sizeof(bc);
1455 hr = IDirectSoundCaptureBuffer8_GetCaps(pStreamDS->In.pDSCB, &bc);
1456 if (FAILED(hr))
1457 {
1458 DSLOGREL(("DSound: Getting capture capabilities failed with %Rhrc\n", hr));
1459 break;
1460 }
1461
1462 DSLOG(("DSound: Acquired capture buffer is %RU64ms (%ld bytes)\n",
1463 DrvAudioHlpBytesToMilli(bc.dwBufferBytes, &pCfgReq->Props), bc.dwBufferBytes));
1464
1465 DSLOG(("DSound: Capture format:\n"
1466 " dwBufferBytes = %RI32\n"
1467 " dwFlags = 0x%x\n"
1468 " wFormatTag = %RI16\n"
1469 " nChannels = %RI16\n"
1470 " nSamplesPerSec = %RU32\n"
1471 " nAvgBytesPerSec = %RU32\n"
1472 " nBlockAlign = %RI16\n"
1473 " wBitsPerSample = %RI16\n"
1474 " cbSize = %RI16\n",
1475 bc.dwBufferBytes,
1476 bc.dwFlags,
1477 wfx.wFormatTag,
1478 wfx.nChannels,
1479 wfx.nSamplesPerSec,
1480 wfx.nAvgBytesPerSec,
1481 wfx.nBlockAlign,
1482 wfx.wBitsPerSample,
1483 wfx.cbSize));
1484
1485 if (bc.dwBufferBytes & pStreamDS->uAlign)
1486 DSLOGREL(("DSound: Capture GetCaps returned misaligned buffer: size %RU32, alignment %RU32\n",
1487 bc.dwBufferBytes, pStreamDS->uAlign + 1));
1488
1489 /* Initial state: reading at the initial capture position, no error. */
1490 pStreamDS->In.offReadPos = 0;
1491 pStreamDS->cbBufSize = bc.dwBufferBytes;
1492
1493 rc = RTCircBufCreate(&pStreamDS->pCircBuf, pStreamDS->cbBufSize) * 2; /* Use "double buffering". */
1494 AssertRC(rc);
1495
1496 pThis->pDSStrmIn = pStreamDS;
1497
1498 pCfgAcq->Backend.cfBufferSize = PDMAUDIOSTREAMCFG_B2F(pCfgAcq, pStreamDS->cbBufSize);
1499
1500 } while (0);
1501
1502 if (FAILED(hr))
1503 directSoundCaptureClose(pThis, pStreamDS);
1504
1505 LogFlowFunc(("Returning %Rhrc\n", hr));
1506 return hr;
1507}
1508
1509static HRESULT directSoundCaptureStop(PDRVHOSTDSOUND pThis, PDSOUNDSTREAM pStreamDS, bool fFlush)
1510{
1511 AssertPtrReturn(pThis, E_POINTER);
1512 AssertPtrReturn(pStreamDS, E_POINTER);
1513
1514 RT_NOREF(pThis);
1515
1516 HRESULT hr = S_OK;
1517
1518 if (pStreamDS->In.pDSCB)
1519 {
1520 DSLOG(("DSound: Stopping capture\n"));
1521 hr = IDirectSoundCaptureBuffer_Stop(pStreamDS->In.pDSCB);
1522 }
1523
1524 if (SUCCEEDED(hr))
1525 {
1526 if (fFlush)
1527 dsoundStreamReset(pThis, pStreamDS);
1528 }
1529
1530 if (FAILED(hr))
1531 DSLOGREL(("DSound: Stopping capture buffer failed with %Rhrc\n", hr));
1532
1533 return hr;
1534}
1535
1536static HRESULT directSoundCaptureStart(PDRVHOSTDSOUND pThis, PDSOUNDSTREAM pStreamDS)
1537{
1538 AssertPtrReturn(pThis, E_POINTER);
1539 AssertPtrReturn(pStreamDS, E_POINTER);
1540
1541 HRESULT hr;
1542 if (pStreamDS->In.pDSCB)
1543 {
1544 DWORD dwStatus;
1545 hr = IDirectSoundCaptureBuffer8_GetStatus(pStreamDS->In.pDSCB, &dwStatus);
1546 if (FAILED(hr))
1547 {
1548 DSLOGREL(("DSound: Retrieving capture status failed with %Rhrc\n", hr));
1549 }
1550 else
1551 {
1552 if (dwStatus & DSCBSTATUS_CAPTURING)
1553 {
1554 DSLOG(("DSound: Already capturing\n"));
1555 }
1556 else
1557 {
1558 const DWORD fFlags = DSCBSTART_LOOPING;
1559
1560 DSLOG(("DSound: Starting to capture\n"));
1561 hr = IDirectSoundCaptureBuffer8_Start(pStreamDS->In.pDSCB, fFlags);
1562 if (FAILED(hr))
1563 DSLOGREL(("DSound: Starting to capture failed with %Rhrc\n", hr));
1564 }
1565 }
1566 }
1567 else
1568 hr = E_UNEXPECTED;
1569
1570 LogFlowFunc(("Returning %Rhrc\n", hr));
1571 return hr;
1572}
1573
1574/**
1575 * Callback for the playback device enumeration.
1576 *
1577 * @return TRUE if continuing enumeration, FALSE if not.
1578 * @param pGUID Pointer to GUID of enumerated device. Can be NULL.
1579 * @param pwszDescription Pointer to (friendly) description of enumerated device.
1580 * @param pwszModule Pointer to module name of enumerated device.
1581 * @param lpContext Pointer to PDSOUNDENUMCBCTX context for storing the enumerated information.
1582 */
1583static BOOL CALLBACK dsoundDevicesEnumCbPlayback(LPGUID pGUID, LPCWSTR pwszDescription, LPCWSTR pwszModule, PVOID lpContext)
1584{
1585 RT_NOREF(pwszModule);
1586
1587 PDSOUNDENUMCBCTX pEnumCtx = (PDSOUNDENUMCBCTX)lpContext;
1588 AssertPtrReturn(pEnumCtx , FALSE);
1589
1590 PPDMAUDIODEVICEENUM pDevEnm = pEnumCtx->pDevEnm;
1591 AssertPtrReturn(pDevEnm, FALSE);
1592
1593 /* pGUID can be NULL for default device(s). */
1594 AssertPtrReturn(pwszDescription, FALSE);
1595 /* Do not care about pwszModule. */
1596
1597 int rc;
1598
1599 PPDMAUDIODEVICE pDev = DrvAudioHlpDeviceAlloc(sizeof(DSOUNDDEV));
1600 if (pDev)
1601 {
1602 pDev->enmUsage = PDMAUDIODIR_OUT;
1603 pDev->enmType = PDMAUDIODEVICETYPE_BUILTIN;
1604
1605 if (pGUID == NULL)
1606 pDev->fFlags = PDMAUDIODEV_FLAGS_DEFAULT;
1607
1608 char *pszName;
1609 rc = RTUtf16ToUtf8(pwszDescription, &pszName);
1610 if (RT_SUCCESS(rc))
1611 {
1612 RTStrCopy(pDev->szName, sizeof(pDev->szName), pszName);
1613 RTStrFree(pszName);
1614
1615 PDSOUNDDEV pDSoundDev = (PDSOUNDDEV)pDev->pvData;
1616
1617 if (pGUID)
1618 memcpy(&pDSoundDev->Guid, pGUID, sizeof(GUID));
1619
1620 LPDIRECTSOUND8 pDS;
1621 HRESULT hr = directSoundPlayInterfaceCreate(pGUID, &pDS);
1622 if (SUCCEEDED(hr))
1623 {
1624 do
1625 {
1626 DSCAPS DSCaps;
1627 RT_ZERO(DSCaps);
1628 DSCaps.dwSize = sizeof(DSCAPS);
1629 hr = IDirectSound_GetCaps(pDS, &DSCaps);
1630 if (FAILED(hr))
1631 break;
1632
1633 pDev->cMaxOutputChannels = DSCaps.dwFlags & DSCAPS_PRIMARYSTEREO ? 2 : 1;
1634
1635 DWORD dwSpeakerCfg;
1636 hr = IDirectSound_GetSpeakerConfig(pDS, &dwSpeakerCfg);
1637 if (FAILED(hr))
1638 break;
1639
1640 unsigned uSpeakerCount = 0;
1641 switch (DSSPEAKER_CONFIG(dwSpeakerCfg))
1642 {
1643 case DSSPEAKER_MONO: uSpeakerCount = 1; break;
1644 case DSSPEAKER_HEADPHONE: uSpeakerCount = 2; break;
1645 case DSSPEAKER_STEREO: uSpeakerCount = 2; break;
1646 case DSSPEAKER_QUAD: uSpeakerCount = 4; break;
1647 case DSSPEAKER_SURROUND: uSpeakerCount = 4; break;
1648 case DSSPEAKER_5POINT1: uSpeakerCount = 6; break;
1649 case DSSPEAKER_5POINT1_SURROUND: uSpeakerCount = 6; break;
1650 case DSSPEAKER_7POINT1: uSpeakerCount = 8; break;
1651 case DSSPEAKER_7POINT1_SURROUND: uSpeakerCount = 8; break;
1652 default: break;
1653 }
1654
1655 if (uSpeakerCount) /* Do we need to update the channel count? */
1656 pDev->cMaxOutputChannels = uSpeakerCount;
1657
1658 } while (0);
1659
1660 directSoundPlayInterfaceDestroy(pDS);
1661
1662 rc = VINF_SUCCESS;
1663 }
1664 else
1665 rc = VERR_GENERAL_FAILURE;
1666
1667 if (RT_SUCCESS(rc))
1668 rc = DrvAudioHlpDeviceEnumAdd(pDevEnm, pDev);
1669 }
1670 }
1671 else
1672 rc = VERR_NO_MEMORY;
1673
1674 if (RT_FAILURE(rc))
1675 {
1676 LogRel(("DSound: Error enumeration playback device '%ls', rc=%Rrc\n", pwszDescription, rc));
1677 return FALSE; /* Abort enumeration. */
1678 }
1679
1680 return TRUE;
1681}
1682
1683/**
1684 * Callback for the capture device enumeration.
1685 *
1686 * @return TRUE if continuing enumeration, FALSE if not.
1687 * @param pGUID Pointer to GUID of enumerated device. Can be NULL.
1688 * @param pwszDescription Pointer to (friendly) description of enumerated device.
1689 * @param pwszModule Pointer to module name of enumerated device.
1690 * @param lpContext Pointer to PDSOUNDENUMCBCTX context for storing the enumerated information.
1691 */
1692static BOOL CALLBACK dsoundDevicesEnumCbCapture(LPGUID pGUID, LPCWSTR pwszDescription, LPCWSTR pwszModule, PVOID lpContext)
1693{
1694 RT_NOREF(pwszModule);
1695
1696 PDSOUNDENUMCBCTX pEnumCtx = (PDSOUNDENUMCBCTX )lpContext;
1697 AssertPtrReturn(pEnumCtx , FALSE);
1698
1699 PPDMAUDIODEVICEENUM pDevEnm = pEnumCtx->pDevEnm;
1700 AssertPtrReturn(pDevEnm, FALSE);
1701
1702 /* pGUID can be NULL for default device(s). */
1703 AssertPtrReturn(pwszDescription, FALSE);
1704 /* Do not care about pwszModule. */
1705
1706 int rc;
1707
1708 PPDMAUDIODEVICE pDev = DrvAudioHlpDeviceAlloc(sizeof(DSOUNDDEV));
1709 if (pDev)
1710 {
1711 pDev->enmUsage = PDMAUDIODIR_IN;
1712 pDev->enmType = PDMAUDIODEVICETYPE_BUILTIN;
1713
1714 char *pszName;
1715 rc = RTUtf16ToUtf8(pwszDescription, &pszName);
1716 if (RT_SUCCESS(rc))
1717 {
1718 RTStrCopy(pDev->szName, sizeof(pDev->szName), pszName);
1719 RTStrFree(pszName);
1720
1721 PDSOUNDDEV pDSoundDev = (PDSOUNDDEV)pDev->pvData;
1722
1723 if (pGUID)
1724 memcpy(&pDSoundDev->Guid, pGUID, sizeof(GUID));
1725
1726 LPDIRECTSOUNDCAPTURE8 pDSC;
1727 HRESULT hr = directSoundCaptureInterfaceCreate(pGUID, &pDSC);
1728 if (SUCCEEDED(hr))
1729 {
1730 do
1731 {
1732 DSCCAPS DSCCaps;
1733 RT_ZERO(DSCCaps);
1734 DSCCaps.dwSize = sizeof(DSCCAPS);
1735 hr = IDirectSoundCapture_GetCaps(pDSC, &DSCCaps);
1736 if (FAILED(hr))
1737 break;
1738
1739 pDev->cMaxInputChannels = DSCCaps.dwChannels;
1740
1741 } while (0);
1742
1743 directSoundCaptureInterfaceDestroy(pDSC);
1744
1745 rc = VINF_SUCCESS;
1746 }
1747 else
1748 rc = VERR_GENERAL_FAILURE;
1749
1750 if (RT_SUCCESS(rc))
1751 rc = DrvAudioHlpDeviceEnumAdd(pDevEnm, pDev);
1752 }
1753 }
1754 else
1755 rc = VERR_NO_MEMORY;
1756
1757 if (RT_FAILURE(rc))
1758 {
1759 LogRel(("DSound: Error enumeration capture device '%ls', rc=%Rrc\n", pwszDescription, rc));
1760 return FALSE; /* Abort enumeration. */
1761 }
1762
1763 return TRUE;
1764}
1765
1766/**
1767 * Does a (Re-)enumeration of the host's playback + capturing devices.
1768 *
1769 * @return IPRT status code.
1770 * @param pThis Host audio driver instance.
1771 * @param pDevEnm Where to store the enumerated devices.
1772 */
1773static int dsoundDevicesEnumerate(PDRVHOSTDSOUND pThis, PPDMAUDIODEVICEENUM pDevEnm)
1774{
1775 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
1776
1777 DSLOG(("DSound: Enumerating devices ...\n"));
1778
1779 RTLDRMOD hDSound = NULL;
1780 int rc = RTLdrLoadSystem("dsound.dll", true /*fNoUnload*/, &hDSound);
1781 if (RT_SUCCESS(rc))
1782 {
1783 DSOUNDENUMCBCTX EnumCtx;
1784 EnumCtx.fFlags = 0;
1785 EnumCtx.pDevEnm = pDevEnm;
1786
1787 PFNDIRECTSOUNDENUMERATEW pfnDirectSoundEnumerateW = NULL;
1788 rc = RTLdrGetSymbol(hDSound, "DirectSoundEnumerateW", (void**)&pfnDirectSoundEnumerateW);
1789 if (RT_SUCCESS(rc))
1790 {
1791 HRESULT hr = pfnDirectSoundEnumerateW(&dsoundDevicesEnumCbPlayback, &EnumCtx);
1792 if (FAILED(hr))
1793 LogRel(("DSound: Error enumerating host playback devices: %Rhrc\n", hr));
1794 }
1795 else
1796 LogRel(("DSound: Error starting to enumerate host playback devices: %Rrc\n", rc));
1797
1798 PFNDIRECTSOUNDCAPTUREENUMERATEW pfnDirectSoundCaptureEnumerateW = NULL;
1799 rc = RTLdrGetSymbol(hDSound, "DirectSoundCaptureEnumerateW", (void**)&pfnDirectSoundCaptureEnumerateW);
1800 if (RT_SUCCESS(rc))
1801 {
1802 HRESULT hr = pfnDirectSoundCaptureEnumerateW(&dsoundDevicesEnumCbCapture, &EnumCtx);
1803 if (FAILED(hr))
1804 LogRel(("DSound: Error enumerating host capture devices: %Rhrc\n", hr));
1805 }
1806 else
1807 LogRel(("DSound: Error starting to enumerate host capture devices: %Rrc\n", rc));
1808
1809 RTLdrClose(hDSound);
1810 }
1811 else
1812 {
1813 /* No dsound.dll on this system. */
1814 LogRel(("DSound: Could not load dsound.dll: %Rrc\n", rc));
1815 }
1816
1817 DSLOG(("DSound: Enumerating devices done\n"));
1818
1819 return rc;
1820}
1821
1822/**
1823 * Updates this host driver's internal status, according to the global, overall input/output
1824 * state and all connected (native) audio streams.
1825 *
1826 * @param pThis Host audio driver instance.
1827 */
1828static void dsoundUpdateStatusInternal(PDRVHOSTDSOUND pThis)
1829{
1830 AssertPtrReturnVoid(pThis);
1831 /* pCfg is optional. */
1832
1833 LogFlowFuncEnter();
1834
1835 int rc = dsoundDevicesEnumerate(pThis, &pThis->DeviceEnum);
1836 if (RT_SUCCESS(rc))
1837 {
1838#if 0
1839 if ( pThis->fEnabledOut != RT_BOOL(cbCtx.cDevOut)
1840 || pThis->fEnabledIn != RT_BOOL(cbCtx.cDevIn))
1841 {
1842 /** @todo Use a registered callback to the audio connector (e.g "OnConfigurationChanged") to
1843 * let the connector know that something has changed within the host backend. */
1844 }
1845#endif
1846 pThis->fEnabledIn = RT_BOOL(DrvAudioHlpDeviceEnumGetDeviceCount(&pThis->DeviceEnum, PDMAUDIODIR_IN));
1847 pThis->fEnabledOut = RT_BOOL(DrvAudioHlpDeviceEnumGetDeviceCount(&pThis->DeviceEnum, PDMAUDIODIR_OUT));
1848 }
1849
1850 LogFlowFuncLeaveRC(rc);
1851}
1852
1853static int dsoundCreateStreamOut(PDRVHOSTDSOUND pThis, PDSOUNDSTREAM pStreamDS,
1854 PPDMAUDIOSTREAMCFG pCfgReq, PPDMAUDIOSTREAMCFG pCfgAcq)
1855{
1856 LogFlowFunc(("pStreamDS=%p, pCfgReq=%p\n", pStreamDS, pCfgReq));
1857
1858 int rc = VINF_SUCCESS;
1859
1860 /* Try to open playback in case the device is already there. */
1861 HRESULT hr = directSoundPlayOpen(pThis, pStreamDS, pCfgReq, pCfgAcq);
1862 if (SUCCEEDED(hr))
1863 {
1864 rc = DrvAudioHlpStreamCfgCopy(&pStreamDS->Cfg, pCfgAcq);
1865 if (RT_SUCCESS(rc))
1866 dsoundStreamReset(pThis, pStreamDS);
1867 }
1868 else
1869 rc = VERR_AUDIO_STREAM_COULD_NOT_CREATE;
1870
1871 LogFlowFuncLeaveRC(rc);
1872 return rc;
1873}
1874
1875static int dsoundControlStreamOut(PDRVHOSTDSOUND pThis, PDSOUNDSTREAM pStreamDS, PDMAUDIOSTREAMCMD enmStreamCmd)
1876{
1877 LogFlowFunc(("pStreamDS=%p, cmd=%d\n", pStreamDS, enmStreamCmd));
1878
1879 int rc = VINF_SUCCESS;
1880
1881 HRESULT hr;
1882 switch (enmStreamCmd)
1883 {
1884 case PDMAUDIOSTREAMCMD_ENABLE:
1885 {
1886 dsoundStreamEnable(pThis, pStreamDS, true /* fEnable */);
1887 break;
1888 }
1889
1890 case PDMAUDIOSTREAMCMD_RESUME:
1891 {
1892 hr = directSoundPlayStart(pThis, pStreamDS);
1893 if (FAILED(hr))
1894 rc = VERR_NOT_SUPPORTED; /** @todo Fix this. */
1895 break;
1896 }
1897
1898 case PDMAUDIOSTREAMCMD_DISABLE:
1899 {
1900 dsoundStreamEnable(pThis, pStreamDS, false /* fEnable */);
1901 hr = directSoundPlayStop(pThis, pStreamDS, true /* fFlush */);
1902 if (FAILED(hr))
1903 rc = VERR_NOT_SUPPORTED;
1904 break;
1905 }
1906
1907 case PDMAUDIOSTREAMCMD_PAUSE:
1908 {
1909 hr = directSoundPlayStop(pThis, pStreamDS, false /* fFlush */);
1910 if (FAILED(hr))
1911 rc = VERR_NOT_SUPPORTED;
1912 break;
1913 }
1914
1915 case PDMAUDIOSTREAMCMD_DRAIN:
1916 {
1917 /* Make sure we transferred everything. */
1918 pStreamDS->fEnabled = true;
1919 pStreamDS->Out.fDrain = true;
1920 rc = dsoundPlayTransfer(pThis, pStreamDS);
1921 if ( RT_SUCCESS(rc)
1922 && pStreamDS->Out.fFirstTransfer)
1923 {
1924 /* If this was the first transfer ever for this stream, make sure to also play the (short) audio data. */
1925 DSLOG(("DSound: Started playing output (short sound)\n"));
1926
1927 pStreamDS->Out.fFirstTransfer = false;
1928 pStreamDS->Out.cbLastTransferred = pStreamDS->Out.cbTransferred; /* All transferred audio data must be played. */
1929 pStreamDS->Out.tsLastTransferredMs = RTTimeMilliTS();
1930
1931 hr = directSoundPlayStart(pThis, pStreamDS);
1932 if (FAILED(hr))
1933 rc = VERR_ACCESS_DENIED; /** @todo Find a better rc. */
1934 }
1935 break;
1936 }
1937
1938 case PDMAUDIOSTREAMCMD_DROP:
1939 {
1940 pStreamDS->Out.cbLastTransferred = 0;
1941 pStreamDS->Out.tsLastTransferredMs = 0;
1942 RTCircBufReset(pStreamDS->pCircBuf);
1943 break;
1944 }
1945
1946 default:
1947 rc = VERR_NOT_SUPPORTED;
1948 break;
1949 }
1950
1951 LogFlowFuncLeaveRC(rc);
1952 return rc;
1953}
1954
1955/**
1956 * @interface_method_impl{PDMIHOSTAUDIO,pfnStreamPlay}
1957 */
1958int drvHostDSoundStreamPlay(PPDMIHOSTAUDIO pInterface,
1959 PPDMAUDIOBACKENDSTREAM pStream, const void *pvBuf, uint32_t cxBuf, uint32_t *pcxWritten)
1960{
1961 AssertPtrReturn(pInterface, VERR_INVALID_POINTER);
1962 AssertPtrReturn(pStream, VERR_INVALID_POINTER);
1963 AssertPtrReturn(pvBuf, VERR_INVALID_POINTER);
1964 AssertReturn(cxBuf, VERR_INVALID_PARAMETER);
1965 /* pcxWritten is optional. */
1966
1967 PDRVHOSTDSOUND pThis = PDMIHOSTAUDIO_2_DRVHOSTDSOUND(pInterface);
1968 PDSOUNDSTREAM pStreamDS = (PDSOUNDSTREAM)pStream;
1969
1970 int rc = VINF_SUCCESS;
1971
1972 uint32_t cbWrittenTotal = 0;
1973
1974 uint8_t *pbBuf = (uint8_t *)pvBuf;
1975 PRTCIRCBUF pCircBuf = pStreamDS->pCircBuf;
1976
1977 uint32_t cbToPlay = RT_MIN(cxBuf, (uint32_t)RTCircBufFree(pCircBuf));
1978 while (cbToPlay)
1979 {
1980 void *pvChunk;
1981 size_t cbChunk;
1982 RTCircBufAcquireWriteBlock(pCircBuf, cbToPlay, &pvChunk, &cbChunk);
1983
1984 if (cbChunk)
1985 {
1986 memcpy(pvChunk, pbBuf, cbChunk);
1987
1988 pbBuf += cbChunk;
1989 Assert(cbToPlay >= cbChunk);
1990 cbToPlay -= (uint32_t)cbChunk;
1991
1992 cbWrittenTotal += (uint32_t)cbChunk;
1993 }
1994
1995 RTCircBufReleaseWriteBlock(pCircBuf, cbChunk);
1996 }
1997
1998 Assert(cbWrittenTotal <= cxBuf);
1999 Assert(cbWrittenTotal == cxBuf);
2000
2001 pStreamDS->Out.cbWritten += cbWrittenTotal;
2002
2003 if (RT_SUCCESS(rc))
2004 {
2005 if (pcxWritten)
2006 *pcxWritten = cbWrittenTotal;
2007 }
2008 else
2009 dsoundUpdateStatusInternal(pThis);
2010
2011 return rc;
2012}
2013
2014static int dsoundDestroyStreamOut(PDRVHOSTDSOUND pThis, PPDMAUDIOBACKENDSTREAM pStream)
2015{
2016 PDSOUNDSTREAM pStreamDS = (PDSOUNDSTREAM)pStream;
2017
2018 LogFlowFuncEnter();
2019
2020 HRESULT hr = directSoundPlayStop(pThis, pStreamDS, true /* fFlush */);
2021 if (SUCCEEDED(hr))
2022 {
2023 hr = directSoundPlayClose(pThis, pStreamDS);
2024 if (FAILED(hr))
2025 return VERR_GENERAL_FAILURE; /** @todo Fix. */
2026 }
2027
2028 return VINF_SUCCESS;
2029}
2030
2031static int dsoundCreateStreamIn(PDRVHOSTDSOUND pThis, PDSOUNDSTREAM pStreamDS,
2032 PPDMAUDIOSTREAMCFG pCfgReq, PPDMAUDIOSTREAMCFG pCfgAcq)
2033{
2034 LogFunc(("pStreamDS=%p, pCfgReq=%p, enmRecSource=%s\n",
2035 pStreamDS, pCfgReq, DrvAudioHlpRecSrcToStr(pCfgReq->DestSource.Source)));
2036
2037 int rc = VINF_SUCCESS;
2038
2039 /* Try to open capture in case the device is already there. */
2040 HRESULT hr = directSoundCaptureOpen(pThis, pStreamDS, pCfgReq, pCfgAcq);
2041 if (SUCCEEDED(hr))
2042 {
2043 rc = DrvAudioHlpStreamCfgCopy(&pStreamDS->Cfg, pCfgAcq);
2044 if (RT_SUCCESS(rc))
2045 dsoundStreamReset(pThis, pStreamDS);
2046 }
2047 else
2048 rc = VERR_AUDIO_STREAM_COULD_NOT_CREATE;
2049
2050 return rc;
2051}
2052
2053static int dsoundControlStreamIn(PDRVHOSTDSOUND pThis, PDSOUNDSTREAM pStreamDS, PDMAUDIOSTREAMCMD enmStreamCmd)
2054{
2055 LogFlowFunc(("pStreamDS=%p, enmStreamCmd=%ld\n", pStreamDS, enmStreamCmd));
2056
2057 int rc = VINF_SUCCESS;
2058
2059 HRESULT hr;
2060 switch (enmStreamCmd)
2061 {
2062 case PDMAUDIOSTREAMCMD_ENABLE:
2063 dsoundStreamEnable(pThis, pStreamDS, true /* fEnable */);
2064 RT_FALL_THROUGH();
2065 case PDMAUDIOSTREAMCMD_RESUME:
2066 {
2067 /* Try to start capture. If it fails, then reopen and try again. */
2068 hr = directSoundCaptureStart(pThis, pStreamDS);
2069 if (FAILED(hr))
2070 {
2071 hr = directSoundCaptureClose(pThis, pStreamDS);
2072 if (SUCCEEDED(hr))
2073 {
2074 PDMAUDIOSTREAMCFG CfgAcq;
2075 hr = directSoundCaptureOpen(pThis, pStreamDS, &pStreamDS->Cfg /* pCfgReq */, &CfgAcq);
2076 if (SUCCEEDED(hr))
2077 {
2078 rc = DrvAudioHlpStreamCfgCopy(&pStreamDS->Cfg, &CfgAcq);
2079 if (RT_FAILURE(rc))
2080 break;
2081
2082 /** @todo What to do if the format has changed? */
2083
2084 hr = directSoundCaptureStart(pThis, pStreamDS);
2085 }
2086 }
2087 }
2088
2089 if (FAILED(hr))
2090 rc = VERR_NOT_SUPPORTED;
2091 break;
2092 }
2093
2094 case PDMAUDIOSTREAMCMD_DISABLE:
2095 dsoundStreamEnable(pThis, pStreamDS, false /* fEnable */);
2096 RT_FALL_THROUGH();
2097 case PDMAUDIOSTREAMCMD_PAUSE:
2098 {
2099 directSoundCaptureStop(pThis, pStreamDS,
2100 enmStreamCmd == PDMAUDIOSTREAMCMD_DISABLE /* fFlush */);
2101
2102 /* Return success in any case, as stopping the capture can fail if
2103 * the capture buffer is not around anymore.
2104 *
2105 * This can happen if the host's capturing device has been changed suddenly. */
2106 rc = VINF_SUCCESS;
2107 break;
2108 }
2109
2110 default:
2111 rc = VERR_NOT_SUPPORTED;
2112 break;
2113 }
2114
2115 return rc;
2116}
2117
2118/**
2119 * @interface_method_impl{PDMIHOSTAUDIO,pfnStreamCapture}
2120 */
2121int drvHostDSoundStreamCapture(PPDMIHOSTAUDIO pInterface,
2122 PPDMAUDIOBACKENDSTREAM pStream, void *pvBuf, uint32_t cxBuf, uint32_t *pcxRead)
2123{
2124
2125 AssertPtrReturn(pInterface, VERR_INVALID_POINTER);
2126 AssertPtrReturn(pStream, VERR_INVALID_POINTER);
2127 AssertPtrReturn(pvBuf, VERR_INVALID_POINTER);
2128 AssertReturn(cxBuf, VERR_INVALID_PARAMETER);
2129
2130 PDRVHOSTDSOUND pThis = PDMIHOSTAUDIO_2_DRVHOSTDSOUND(pInterface);
2131 PDSOUNDSTREAM pStreamDS = (PDSOUNDSTREAM)pStream;
2132
2133 int rc = VINF_SUCCESS;
2134
2135 uint32_t cbReadTotal = 0;
2136
2137 uint32_t cbToRead = RT_MIN((uint32_t)RTCircBufUsed(pStreamDS->pCircBuf), cxBuf);
2138 while (cbToRead)
2139 {
2140 void *pvChunk;
2141 size_t cbChunk;
2142 RTCircBufAcquireReadBlock(pStreamDS->pCircBuf, cbToRead, &pvChunk, &cbChunk);
2143
2144 if (cbChunk)
2145 {
2146 memcpy((uint8_t *)pvBuf + cbReadTotal, pvChunk, cbChunk);
2147 cbReadTotal += (uint32_t)cbChunk;
2148 Assert(cbToRead >= cbChunk);
2149 cbToRead -= (uint32_t)cbChunk;
2150 }
2151
2152 RTCircBufReleaseReadBlock(pStreamDS->pCircBuf, cbChunk);
2153 }
2154
2155 if (RT_SUCCESS(rc))
2156 {
2157 if (pcxRead)
2158 *pcxRead = cbReadTotal;
2159 }
2160 else
2161 dsoundUpdateStatusInternal(pThis);
2162
2163 return rc;
2164}
2165
2166static int dsoundDestroyStreamIn(PDRVHOSTDSOUND pThis, PDSOUNDSTREAM pStreamDS)
2167{
2168 LogFlowFuncEnter();
2169
2170 directSoundCaptureClose(pThis, pStreamDS);
2171
2172 return VINF_SUCCESS;
2173}
2174
2175/**
2176 * @interface_method_impl{PDMIHOSTAUDIO,pfnGetConfig}
2177 */
2178int drvHostDSoundGetConfig(PPDMIHOSTAUDIO pInterface, PPDMAUDIOBACKENDCFG pBackendCfg)
2179{
2180 RT_NOREF(pInterface);
2181 AssertPtrReturn(pInterface, VERR_INVALID_POINTER);
2182 AssertPtrReturn(pBackendCfg, VERR_INVALID_POINTER);
2183
2184 RT_BZERO(pBackendCfg, sizeof(PPDMAUDIOBACKENDCFG));
2185
2186 pBackendCfg->cbStreamOut = sizeof(DSOUNDSTREAM);
2187 pBackendCfg->cbStreamIn = sizeof(DSOUNDSTREAM);
2188
2189 RTStrPrintf2(pBackendCfg->szName, sizeof(pBackendCfg->szName), "DirectSound audio driver");
2190
2191 pBackendCfg->cMaxStreamsIn = UINT32_MAX;
2192 pBackendCfg->cMaxStreamsOut = UINT32_MAX;
2193
2194 return VINF_SUCCESS;
2195}
2196
2197/**
2198 * @interface_method_impl{PDMIHOSTAUDIO,pfnGetDevices}
2199 */
2200static DECLCALLBACK(int) drvHostDSoundGetDevices(PPDMIHOSTAUDIO pInterface, PPDMAUDIODEVICEENUM pDeviceEnum)
2201{
2202 AssertPtrReturn(pInterface, VERR_INVALID_POINTER);
2203 AssertPtrReturn(pDeviceEnum, VERR_INVALID_POINTER);
2204
2205 PDRVHOSTDSOUND pThis = PDMIHOSTAUDIO_2_DRVHOSTDSOUND(pInterface);
2206
2207 int rc = RTCritSectEnter(&pThis->CritSect);
2208 if (RT_SUCCESS(rc))
2209 {
2210 rc = DrvAudioHlpDeviceEnumInit(pDeviceEnum);
2211 if (RT_SUCCESS(rc))
2212 {
2213 rc = dsoundDevicesEnumerate(pThis, pDeviceEnum);
2214 if (RT_FAILURE(rc))
2215 DrvAudioHlpDeviceEnumFree(pDeviceEnum);
2216 }
2217
2218 int rc2 = RTCritSectLeave(&pThis->CritSect);
2219 AssertRC(rc2);
2220 }
2221
2222 LogFlowFunc(("Returning %Rrc\n", rc));
2223 return rc;
2224}
2225
2226/**
2227 * @interface_method_impl{PDMIHOSTAUDIO,pfnShutdown}
2228 */
2229void drvHostDSoundShutdown(PPDMIHOSTAUDIO pInterface)
2230{
2231 PDRVHOSTDSOUND pThis = PDMIHOSTAUDIO_2_DRVHOSTDSOUND(pInterface);
2232
2233 LogFlowFuncEnter();
2234
2235 RT_NOREF(pThis);
2236
2237 LogFlowFuncLeave();
2238}
2239
2240/**
2241 * @interface_method_impl{PDMIHOSTAUDIO,pfnInit}
2242 */
2243static DECLCALLBACK(int) drvHostDSoundInit(PPDMIHOSTAUDIO pInterface)
2244{
2245 PDRVHOSTDSOUND pThis = PDMIHOSTAUDIO_2_DRVHOSTDSOUND(pInterface);
2246 LogFlowFuncEnter();
2247
2248 int rc;
2249
2250 /* Verify that IDirectSound is available. */
2251 LPDIRECTSOUND pDirectSound = NULL;
2252 HRESULT hr = CoCreateInstance(CLSID_DirectSound, NULL, CLSCTX_ALL, IID_IDirectSound, (void **)&pDirectSound);
2253 if (SUCCEEDED(hr))
2254 {
2255 IDirectSound_Release(pDirectSound);
2256
2257 rc = VINF_SUCCESS;
2258
2259 dsoundUpdateStatusInternal(pThis);
2260 }
2261 else
2262 {
2263 DSLOGREL(("DSound: DirectSound not available: %Rhrc\n", hr));
2264 rc = VERR_NOT_SUPPORTED;
2265 }
2266
2267 LogFlowFuncLeaveRC(rc);
2268 return rc;
2269}
2270
2271static LPCGUID dsoundConfigQueryGUID(PCFGMNODE pCfg, const char *pszName, RTUUID *pUuid)
2272{
2273 LPCGUID pGuid = NULL;
2274
2275 char *pszGuid = NULL;
2276 int rc = CFGMR3QueryStringAlloc(pCfg, pszName, &pszGuid);
2277 if (RT_SUCCESS(rc))
2278 {
2279 rc = RTUuidFromStr(pUuid, pszGuid);
2280 if (RT_SUCCESS(rc))
2281 pGuid = (LPCGUID)&pUuid;
2282 else
2283 DSLOGREL(("DSound: Error parsing device GUID for device '%s': %Rrc\n", pszName, rc));
2284
2285 RTStrFree(pszGuid);
2286 }
2287
2288 return pGuid;
2289}
2290
2291static int dsoundConfigInit(PDRVHOSTDSOUND pThis, PCFGMNODE pCfg)
2292{
2293 pThis->Cfg.pGuidPlay = dsoundConfigQueryGUID(pCfg, "DeviceGuidOut", &pThis->Cfg.uuidPlay);
2294 pThis->Cfg.pGuidCapture = dsoundConfigQueryGUID(pCfg, "DeviceGuidIn", &pThis->Cfg.uuidCapture);
2295
2296 DSLOG(("DSound: Configuration: DeviceGuidOut {%RTuuid}, DeviceGuidIn {%RTuuid}\n",
2297 &pThis->Cfg.uuidPlay,
2298 &pThis->Cfg.uuidCapture));
2299
2300 return VINF_SUCCESS;
2301}
2302
2303/**
2304 * @interface_method_impl{PDMIHOSTAUDIO,pfnGetStatus}
2305 */
2306static DECLCALLBACK(PDMAUDIOBACKENDSTS) drvHostDSoundGetStatus(PPDMIHOSTAUDIO pInterface, PDMAUDIODIR enmDir)
2307{
2308 RT_NOREF(enmDir);
2309 AssertPtrReturn(pInterface, PDMAUDIOBACKENDSTS_UNKNOWN);
2310
2311 return PDMAUDIOBACKENDSTS_RUNNING;
2312}
2313
2314/**
2315 * @interface_method_impl{PDMIHOSTAUDIO,pfnStreamCreate}
2316 */
2317static DECLCALLBACK(int) drvHostDSoundStreamCreate(PPDMIHOSTAUDIO pInterface, PPDMAUDIOBACKENDSTREAM pStream,
2318 PPDMAUDIOSTREAMCFG pCfgReq, PPDMAUDIOSTREAMCFG pCfgAcq)
2319{
2320 AssertPtrReturn(pInterface, VERR_INVALID_POINTER);
2321 AssertPtrReturn(pStream, VERR_INVALID_POINTER);
2322 AssertPtrReturn(pCfgReq, VERR_INVALID_POINTER);
2323 AssertPtrReturn(pCfgAcq, VERR_INVALID_POINTER);
2324
2325 PDRVHOSTDSOUND pThis = PDMIHOSTAUDIO_2_DRVHOSTDSOUND(pInterface);
2326 PDSOUNDSTREAM pStreamDS = (PDSOUNDSTREAM)pStream;
2327
2328 int rc;
2329 if (pCfgReq->enmDir == PDMAUDIODIR_IN)
2330 rc = dsoundCreateStreamIn(pThis, pStreamDS, pCfgReq, pCfgAcq);
2331 else
2332 rc = dsoundCreateStreamOut(pThis, pStreamDS, pCfgReq, pCfgAcq);
2333
2334 if (RT_SUCCESS(rc))
2335 {
2336 rc = DrvAudioHlpStreamCfgCopy(&pStreamDS->Cfg, pCfgAcq);
2337 if (RT_SUCCESS(rc))
2338 rc = RTCritSectInit(&pStreamDS->CritSect);
2339 }
2340
2341 return rc;
2342}
2343
2344/**
2345 * @interface_method_impl{PDMIHOSTAUDIO,pfnStreamDestroy}
2346 */
2347static DECLCALLBACK(int) drvHostDSoundStreamDestroy(PPDMIHOSTAUDIO pInterface, PPDMAUDIOBACKENDSTREAM pStream)
2348{
2349 AssertPtrReturn(pInterface, VERR_INVALID_POINTER);
2350 AssertPtrReturn(pStream, VERR_INVALID_POINTER);
2351
2352 PDRVHOSTDSOUND pThis = PDMIHOSTAUDIO_2_DRVHOSTDSOUND(pInterface);
2353 PDSOUNDSTREAM pStreamDS = (PDSOUNDSTREAM)pStream;
2354
2355 int rc;
2356 if (pStreamDS->Cfg.enmDir == PDMAUDIODIR_IN)
2357 rc = dsoundDestroyStreamIn(pThis, pStreamDS);
2358 else
2359 rc = dsoundDestroyStreamOut(pThis, pStreamDS);
2360
2361 if (RT_SUCCESS(rc))
2362 {
2363 if (RTCritSectIsInitialized(&pStreamDS->CritSect))
2364 rc = RTCritSectDelete(&pStreamDS->CritSect);
2365 }
2366
2367 return rc;
2368}
2369
2370/**
2371 * @interface_method_impl{PDMIHOSTAUDIO,pfnStreamControl}
2372 */
2373static DECLCALLBACK(int) drvHostDSoundStreamControl(PPDMIHOSTAUDIO pInterface,
2374 PPDMAUDIOBACKENDSTREAM pStream, PDMAUDIOSTREAMCMD enmStreamCmd)
2375{
2376 AssertPtrReturn(pInterface, VERR_INVALID_POINTER);
2377 AssertPtrReturn(pStream, VERR_INVALID_POINTER);
2378
2379 PDRVHOSTDSOUND pThis = PDMIHOSTAUDIO_2_DRVHOSTDSOUND(pInterface);
2380 PDSOUNDSTREAM pStreamDS = (PDSOUNDSTREAM)pStream;
2381
2382 int rc;
2383 if (pStreamDS->Cfg.enmDir == PDMAUDIODIR_IN)
2384 rc = dsoundControlStreamIn(pThis, pStreamDS, enmStreamCmd);
2385 else
2386 rc = dsoundControlStreamOut(pThis, pStreamDS, enmStreamCmd);
2387
2388 return rc;
2389}
2390
2391/**
2392 * @interface_method_impl{PDMIHOSTAUDIO,pfnStreamGetReadable}
2393 */
2394static DECLCALLBACK(uint32_t) drvHostDSoundStreamGetReadable(PPDMIHOSTAUDIO pInterface, PPDMAUDIOBACKENDSTREAM pStream)
2395{
2396 RT_NOREF(pInterface);
2397 AssertPtrReturn(pStream, PDMAUDIOSTREAMSTS_FLAG_NONE);
2398
2399 PDSOUNDSTREAM pStreamDS = (PDSOUNDSTREAM)pStream;
2400
2401 if ( pStreamDS->fEnabled
2402 && pStreamDS->pCircBuf)
2403 {
2404 return (uint32_t)RTCircBufUsed(pStreamDS->pCircBuf);
2405 }
2406
2407 return 0;
2408}
2409
2410/**
2411 * @interface_method_impl{PDMIHOSTAUDIO,pfnStreamGetWritable}
2412 */
2413static DECLCALLBACK(uint32_t) drvHostDSoundStreamGetWritable(PPDMIHOSTAUDIO pInterface, PPDMAUDIOBACKENDSTREAM pStream)
2414{
2415 AssertPtrReturn(pInterface, PDMAUDIOSTREAMSTS_FLAG_NONE);
2416 AssertPtrReturn(pStream, PDMAUDIOSTREAMSTS_FLAG_NONE);
2417
2418 PDSOUNDSTREAM pStreamDS = (PDSOUNDSTREAM)pStream;
2419
2420 if (pStreamDS->fEnabled)
2421 return (uint32_t)RTCircBufFree(pStreamDS->pCircBuf);
2422
2423 return 0;
2424}
2425
2426/**
2427 * @interface_method_impl{PDMIHOSTAUDIO,pfnStreamGetPending}
2428 */
2429static DECLCALLBACK(uint32_t) drvHostDSoundStreamGetPending(PPDMIHOSTAUDIO pInterface, PPDMAUDIOBACKENDSTREAM pStream)
2430{
2431 RT_NOREF(pInterface);
2432 AssertPtrReturn(pStream, 0);
2433
2434 PDSOUNDSTREAM pStreamDS = (PDSOUNDSTREAM)pStream;
2435
2436 if (pStreamDS->Cfg.enmDir == PDMAUDIODIR_OUT)
2437 {
2438 uint32_t cbPending = 0;
2439
2440 /* Any uncommitted data left? */
2441 if (pStreamDS->pCircBuf)
2442 cbPending = (uint32_t)RTCircBufUsed(pStreamDS->pCircBuf);
2443
2444 /* Check if we have committed data which still needs to be played by
2445 * by DirectSound's streaming buffer. */
2446 if (!cbPending)
2447 {
2448 const uint64_t diffLastTransferredMs = RTTimeMilliTS() - pStreamDS->Out.tsLastTransferredMs;
2449 const uint64_t uLastTranserredChunkMs = DrvAudioHlpBytesToMilli(pStreamDS->Out.cbLastTransferred, &pStreamDS->Cfg.Props);
2450 if ( uLastTranserredChunkMs
2451 && diffLastTransferredMs < uLastTranserredChunkMs)
2452 cbPending = 1;
2453
2454 Log3Func(("diffLastTransferredMs=%RU64ms, uLastTranserredChunkMs=%RU64ms (%RU32 bytes) -> cbPending=%RU32\n",
2455 diffLastTransferredMs, uLastTranserredChunkMs, pStreamDS->Out.cbLastTransferred, cbPending));
2456 }
2457 else
2458 Log3Func(("cbPending=%RU32\n", cbPending));
2459
2460 return cbPending;
2461 }
2462 /* Note: For input streams we never have pending data left. */
2463
2464 return 0;
2465}
2466
2467/**
2468 * @interface_method_impl{PDMIHOSTAUDIO,pfnStreamGetStatus}
2469 */
2470static DECLCALLBACK(PDMAUDIOSTREAMSTS) drvHostDSoundStreamGetStatus(PPDMIHOSTAUDIO pInterface, PPDMAUDIOBACKENDSTREAM pStream)
2471{
2472 RT_NOREF(pInterface);
2473 AssertPtrReturn(pStream, PDMAUDIOSTREAMSTS_FLAG_NONE);
2474
2475 PDSOUNDSTREAM pStreamDS = (PDSOUNDSTREAM)pStream;
2476
2477 PDMAUDIOSTREAMSTS strmSts = PDMAUDIOSTREAMSTS_FLAG_INITIALIZED;
2478
2479 if (pStreamDS->fEnabled)
2480 strmSts |= PDMAUDIOSTREAMSTS_FLAG_ENABLED;
2481
2482 return strmSts;
2483}
2484
2485/**
2486 * @interface_method_impl{PDMIHOSTAUDIO,pfnStreamIterate}
2487 */
2488static DECLCALLBACK(int) drvHostDSoundStreamIterate(PPDMIHOSTAUDIO pInterface, PPDMAUDIOBACKENDSTREAM pStream)
2489{
2490 AssertPtrReturn(pInterface, VERR_INVALID_POINTER);
2491 AssertPtrReturn(pStream, VERR_INVALID_POINTER);
2492
2493 PDRVHOSTDSOUND pThis = PDMIHOSTAUDIO_2_DRVHOSTDSOUND(pInterface);
2494 PDSOUNDSTREAM pStreamDS = (PDSOUNDSTREAM)pStream;
2495
2496 if (pStreamDS->Cfg.enmDir == PDMAUDIODIR_IN)
2497 {
2498 return dsoundCaptureTransfer(pThis, pStreamDS);
2499 }
2500 else if (pStreamDS->Cfg.enmDir == PDMAUDIODIR_OUT)
2501 {
2502 return dsoundPlayTransfer(pThis, pStreamDS);
2503 }
2504
2505 return VINF_SUCCESS;
2506}
2507
2508#ifdef VBOX_WITH_AUDIO_CALLBACKS
2509/**
2510 * @interface_method_impl{PDMIHOSTAUDIO,pfnSetCallback}
2511 */
2512static DECLCALLBACK(int) drvHostDSoundSetCallback(PPDMIHOSTAUDIO pInterface, PFNPDMHOSTAUDIOCALLBACK pfnCallback)
2513{
2514 AssertPtrReturn(pInterface, VERR_INVALID_POINTER);
2515 /* pfnCallback will be handled below. */
2516
2517 PDRVHOSTDSOUND pThis = PDMIHOSTAUDIO_2_DRVHOSTDSOUND(pInterface);
2518
2519 int rc = RTCritSectEnter(&pThis->CritSect);
2520 if (RT_SUCCESS(rc))
2521 {
2522 LogFunc(("pfnCallback=%p\n", pfnCallback));
2523
2524 if (pfnCallback) /* Register. */
2525 {
2526 Assert(pThis->pfnCallback == NULL);
2527 pThis->pfnCallback = pfnCallback;
2528
2529#ifdef VBOX_WITH_AUDIO_MMNOTIFICATION_CLIENT
2530 if (pThis->m_pNotificationClient)
2531 pThis->m_pNotificationClient->RegisterCallback(pThis->pDrvIns, pfnCallback);
2532#endif
2533 }
2534 else /* Unregister. */
2535 {
2536 if (pThis->pfnCallback)
2537 pThis->pfnCallback = NULL;
2538
2539#ifdef VBOX_WITH_AUDIO_MMNOTIFICATION_CLIENT
2540 if (pThis->m_pNotificationClient)
2541 pThis->m_pNotificationClient->UnregisterCallback();
2542#endif
2543 }
2544
2545 int rc2 = RTCritSectLeave(&pThis->CritSect);
2546 AssertRC(rc2);
2547 }
2548
2549 return rc;
2550}
2551#endif
2552
2553
2554/*********************************************************************************************************************************
2555* PDMDRVINS::IBase Interface *
2556*********************************************************************************************************************************/
2557
2558/**
2559 * @callback_method_impl{PDMIBASE,pfnQueryInterface}
2560 */
2561static DECLCALLBACK(void *) drvHostDSoundQueryInterface(PPDMIBASE pInterface, const char *pszIID)
2562{
2563 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
2564 PDRVHOSTDSOUND pThis = PDMINS_2_DATA(pDrvIns, PDRVHOSTDSOUND);
2565
2566 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pDrvIns->IBase);
2567 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIHOSTAUDIO, &pThis->IHostAudio);
2568 return NULL;
2569}
2570
2571
2572/*********************************************************************************************************************************
2573* PDMDRVREG Interface *
2574*********************************************************************************************************************************/
2575
2576/**
2577 * @callback_method_impl{FNPDMDRVDESTRUCT, pfnDestruct}
2578 */
2579static DECLCALLBACK(void) drvHostDSoundDestruct(PPDMDRVINS pDrvIns)
2580{
2581 PDRVHOSTDSOUND pThis = PDMINS_2_DATA(pDrvIns, PDRVHOSTDSOUND);
2582 PDMDRV_CHECK_VERSIONS_RETURN_VOID(pDrvIns);
2583
2584 LogFlowFuncEnter();
2585
2586#ifdef VBOX_WITH_AUDIO_MMNOTIFICATION_CLIENT
2587 if (pThis->m_pNotificationClient)
2588 {
2589 pThis->m_pNotificationClient->Dispose();
2590 pThis->m_pNotificationClient->Release();
2591
2592 pThis->m_pNotificationClient = NULL;
2593 }
2594#endif
2595
2596 DrvAudioHlpDeviceEnumFree(&pThis->DeviceEnum);
2597
2598 if (pThis->pDrvIns)
2599 CoUninitialize();
2600
2601 int rc2 = RTCritSectDelete(&pThis->CritSect);
2602 AssertRC(rc2);
2603
2604 LogFlowFuncLeave();
2605}
2606
2607/**
2608 * @callback_method_impl{FNPDMDRVCONSTRUCT,
2609 * Construct a DirectSound Audio driver instance.}
2610 */
2611static DECLCALLBACK(int) drvHostDSoundConstruct(PPDMDRVINS pDrvIns, PCFGMNODE pCfg, uint32_t fFlags)
2612{
2613 RT_NOREF(fFlags);
2614 PDRVHOSTDSOUND pThis = PDMINS_2_DATA(pDrvIns, PDRVHOSTDSOUND);
2615
2616 LogRel(("Audio: Initializing DirectSound audio driver\n"));
2617
2618 PDMDRV_CHECK_VERSIONS_RETURN(pDrvIns);
2619
2620 HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
2621 if (FAILED(hr))
2622 {
2623 DSLOGREL(("DSound: CoInitializeEx failed with %Rhrc\n", hr));
2624 return VERR_NOT_SUPPORTED;
2625 }
2626
2627 /*
2628 * Init basic data members and interfaces.
2629 */
2630 pThis->pDrvIns = pDrvIns;
2631 /* IBase */
2632 pDrvIns->IBase.pfnQueryInterface = drvHostDSoundQueryInterface;
2633 /* IHostAudio */
2634 PDMAUDIO_IHOSTAUDIO_CALLBACKS(drvHostDSound);
2635 pThis->IHostAudio.pfnStreamGetPending = drvHostDSoundStreamGetPending;
2636
2637 /* This backend supports device enumeration. */
2638 pThis->IHostAudio.pfnGetDevices = drvHostDSoundGetDevices;
2639
2640#ifdef VBOX_WITH_AUDIO_CALLBACKS
2641 /* This backend supports host audio callbacks. */
2642 pThis->IHostAudio.pfnSetCallback = drvHostDSoundSetCallback;
2643 pThis->pfnCallback = NULL;
2644#endif
2645
2646 /*
2647 * Init the static parts.
2648 */
2649 DrvAudioHlpDeviceEnumInit(&pThis->DeviceEnum);
2650
2651 pThis->fEnabledIn = false;
2652 pThis->fEnabledOut = false;
2653
2654 int rc = VINF_SUCCESS;
2655
2656#ifdef VBOX_WITH_AUDIO_MMNOTIFICATION_CLIENT
2657 bool fUseNotificationClient = false;
2658
2659 char szOSVersion[32];
2660 rc = RTSystemQueryOSInfo(RTSYSOSINFO_RELEASE, szOSVersion, sizeof(szOSVersion));
2661 if (RT_SUCCESS(rc))
2662 {
2663 /* IMMNotificationClient is available starting at Windows Vista. */
2664 if (RTStrVersionCompare(szOSVersion, "6.0") >= 0)
2665 fUseNotificationClient = true;
2666 }
2667
2668 if (fUseNotificationClient)
2669 {
2670 try
2671 {
2672 pThis->m_pNotificationClient = new VBoxMMNotificationClient();
2673
2674 HRESULT hr = pThis->m_pNotificationClient->Initialize();
2675 if (FAILED(hr))
2676 rc = VERR_AUDIO_BACKEND_INIT_FAILED;
2677 }
2678 catch (std::bad_alloc &ex)
2679 {
2680 NOREF(ex);
2681 rc = VERR_NO_MEMORY;
2682 }
2683 }
2684
2685 LogRel2(("DSound: Notification client is %s\n", fUseNotificationClient ? "enabled" : "disabled"));
2686#endif
2687
2688 if (RT_SUCCESS(rc))
2689 {
2690 /*
2691 * Initialize configuration values.
2692 */
2693 rc = dsoundConfigInit(pThis, pCfg);
2694 if (RT_SUCCESS(rc))
2695 rc = RTCritSectInit(&pThis->CritSect);
2696 }
2697
2698 return rc;
2699}
2700
2701
2702/**
2703 * PDM driver registration.
2704 */
2705const PDMDRVREG g_DrvHostDSound =
2706{
2707 /* u32Version */
2708 PDM_DRVREG_VERSION,
2709 /* szName */
2710 "DSoundAudio",
2711 /* szRCMod */
2712 "",
2713 /* szR0Mod */
2714 "",
2715 /* pszDescription */
2716 "DirectSound Audio host driver",
2717 /* fFlags */
2718 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
2719 /* fClass. */
2720 PDM_DRVREG_CLASS_AUDIO,
2721 /* cMaxInstances */
2722 ~0U,
2723 /* cbInstance */
2724 sizeof(DRVHOSTDSOUND),
2725 /* pfnConstruct */
2726 drvHostDSoundConstruct,
2727 /* pfnDestruct */
2728 drvHostDSoundDestruct,
2729 /* pfnRelocate */
2730 NULL,
2731 /* pfnIOCtl */
2732 NULL,
2733 /* pfnPowerOn */
2734 NULL,
2735 /* pfnReset */
2736 NULL,
2737 /* pfnSuspend */
2738 NULL,
2739 /* pfnResume */
2740 NULL,
2741 /* pfnAttach */
2742 NULL,
2743 /* pfnDetach */
2744 NULL,
2745 /* pfnPowerOff */
2746 NULL,
2747 /* pfnSoftReset */
2748 NULL,
2749 /* u32EndVersion */
2750 PDM_DRVREG_VERSION
2751};
Note: See TracBrowser for help on using the repository browser.

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