VirtualBox

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

Last change on this file since 83967 was 83812, checked in by vboxsync, 5 years ago

Devices/Audio: VC++ 14.1 warnings. bugref:8498

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