VirtualBox

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

Last change on this file since 82453 was 82255, checked in by vboxsync, 5 years ago

vmm/pdmaudioifs.h: More of the same. bugref:9218

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