VirtualBox

source: vbox/trunk/src/VBox/Devices/Audio/DrvAudio.cpp@ 87159

Last change on this file since 87159 was 87159, checked in by vboxsync, 4 years ago

Audio: Enable/disable streams using PDMIAUDIOCONNECTOR::pfnStreamControl() instead of PDMIAUDIOCONNECTOR::pfnEnable(). bugref:9882

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 134.6 KB
Line 
1/* $Id: DrvAudio.cpp 87159 2021-01-04 11:38:37Z vboxsync $ */
2/** @file
3 * Intermediate audio driver header.
4 *
5 * @remarks Intermediate audio driver for connecting the audio device emulation
6 * with the host backend.
7 */
8
9/*
10 * Copyright (C) 2006-2020 Oracle Corporation
11 *
12 * This file is part of VirtualBox Open Source Edition (OSE), as
13 * available from http://www.virtualbox.org. This file is free software;
14 * you can redistribute it and/or modify it under the terms of the GNU
15 * General Public License (GPL) as published by the Free Software
16 * Foundation, in version 2 as it comes in the "COPYING" file of the
17 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
18 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
19 */
20
21#define LOG_GROUP LOG_GROUP_DRV_AUDIO
22#include <VBox/log.h>
23#include <VBox/vmm/pdm.h>
24#include <VBox/err.h>
25#include <VBox/vmm/mm.h>
26#include <VBox/vmm/pdmaudioifs.h>
27
28#include <iprt/alloc.h>
29#include <iprt/asm-math.h>
30#include <iprt/assert.h>
31#include <iprt/circbuf.h>
32#include <iprt/string.h>
33#include <iprt/uuid.h>
34
35#include "VBoxDD.h"
36
37#include <ctype.h>
38#include <stdlib.h>
39
40#include "DrvAudio.h"
41#include "AudioMixBuffer.h"
42
43#ifdef VBOX_WITH_AUDIO_ENUM
44static int drvAudioDevicesEnumerateInternal(PDRVAUDIO pThis, bool fLog, PPDMAUDIODEVICEENUM pDevEnum);
45#endif
46
47static DECLCALLBACK(int) drvAudioStreamDestroy(PPDMIAUDIOCONNECTOR pInterface, PPDMAUDIOSTREAM pStream);
48static int drvAudioStreamControlInternalBackend(PDRVAUDIO pThis, PPDMAUDIOSTREAM pStream, PDMAUDIOSTREAMCMD enmStreamCmd);
49static int drvAudioStreamControlInternal(PDRVAUDIO pThis, PPDMAUDIOSTREAM pStream, PDMAUDIOSTREAMCMD enmStreamCmd);
50static int drvAudioStreamCreateInternalBackend(PDRVAUDIO pThis, PPDMAUDIOSTREAM pStream, PPDMAUDIOSTREAMCFG pCfgReq, PPDMAUDIOSTREAMCFG pCfgAcq);
51static int drvAudioStreamDestroyInternalBackend(PDRVAUDIO pThis, PPDMAUDIOSTREAM pStream);
52static void drvAudioStreamFree(PPDMAUDIOSTREAM pStream);
53static int drvAudioStreamUninitInternal(PDRVAUDIO pThis, PPDMAUDIOSTREAM pStream);
54static int drvAudioStreamIterateInternal(PDRVAUDIO pThis, PPDMAUDIOSTREAM pStream);
55static int drvAudioStreamReInitInternal(PDRVAUDIO pThis, PPDMAUDIOSTREAM pStream);
56static void drvAudioStreamDropInternal(PDRVAUDIO pThis, PPDMAUDIOSTREAM pStream);
57static void drvAudioStreamResetInternal(PDRVAUDIO pThis, PPDMAUDIOSTREAM pStream);
58
59#ifndef VBOX_AUDIO_TESTCASE
60
61# if 0 /* unused */
62
63static PDMAUDIOFMT drvAudioGetConfFormat(PCFGMNODE pCfgHandle, const char *pszKey,
64 PDMAUDIOFMT enmDefault, bool *pfDefault)
65{
66 if ( pCfgHandle == NULL
67 || pszKey == NULL)
68 {
69 *pfDefault = true;
70 return enmDefault;
71 }
72
73 char *pszValue = NULL;
74 int rc = CFGMR3QueryStringAlloc(pCfgHandle, pszKey, &pszValue);
75 if (RT_FAILURE(rc))
76 {
77 *pfDefault = true;
78 return enmDefault;
79 }
80
81 PDMAUDIOFMT fmt = DrvAudioHlpStrToAudFmt(pszValue);
82 if (fmt == PDMAUDIOFMT_INVALID)
83 {
84 *pfDefault = true;
85 return enmDefault;
86 }
87
88 *pfDefault = false;
89 return fmt;
90}
91
92static int drvAudioGetConfInt(PCFGMNODE pCfgHandle, const char *pszKey,
93 int iDefault, bool *pfDefault)
94{
95
96 if ( pCfgHandle == NULL
97 || pszKey == NULL)
98 {
99 *pfDefault = true;
100 return iDefault;
101 }
102
103 uint64_t u64Data = 0;
104 int rc = CFGMR3QueryInteger(pCfgHandle, pszKey, &u64Data);
105 if (RT_FAILURE(rc))
106 {
107 *pfDefault = true;
108 return iDefault;
109
110 }
111
112 *pfDefault = false;
113 return u64Data;
114}
115
116static const char *drvAudioGetConfStr(PCFGMNODE pCfgHandle, const char *pszKey,
117 const char *pszDefault, bool *pfDefault)
118{
119 if ( pCfgHandle == NULL
120 || pszKey == NULL)
121 {
122 *pfDefault = true;
123 return pszDefault;
124 }
125
126 char *pszValue = NULL;
127 int rc = CFGMR3QueryStringAlloc(pCfgHandle, pszKey, &pszValue);
128 if (RT_FAILURE(rc))
129 {
130 *pfDefault = true;
131 return pszDefault;
132 }
133
134 *pfDefault = false;
135 return pszValue;
136}
137
138# endif /* unused */
139
140#ifdef LOG_ENABLED
141/**
142 * Converts an audio stream status to a string.
143 *
144 * @returns Stringified stream status flags. Must be free'd with RTStrFree().
145 * "NONE" if no flags set.
146 * @param fStatus Stream status flags to convert.
147 */
148static char *dbgAudioStreamStatusToStr(PDMAUDIOSTREAMSTS fStatus)
149{
150#define APPEND_FLAG_TO_STR(_aFlag) \
151 if (fStatus & PDMAUDIOSTREAMSTS_FLAGS_##_aFlag) \
152 { \
153 if (pszFlags) \
154 { \
155 rc2 = RTStrAAppend(&pszFlags, " "); \
156 if (RT_FAILURE(rc2)) \
157 break; \
158 } \
159 \
160 rc2 = RTStrAAppend(&pszFlags, #_aFlag); \
161 if (RT_FAILURE(rc2)) \
162 break; \
163 } \
164
165 char *pszFlags = NULL;
166 int rc2 = VINF_SUCCESS;
167
168 do
169 {
170 APPEND_FLAG_TO_STR(INITIALIZED );
171 APPEND_FLAG_TO_STR(ENABLED );
172 APPEND_FLAG_TO_STR(PAUSED );
173 APPEND_FLAG_TO_STR(PENDING_DISABLE);
174 APPEND_FLAG_TO_STR(PENDING_REINIT );
175 } while (0);
176
177 if (!pszFlags)
178 rc2 = RTStrAAppend(&pszFlags, "NONE");
179
180 if ( RT_FAILURE(rc2)
181 && pszFlags)
182 {
183 RTStrFree(pszFlags);
184 pszFlags = NULL;
185 }
186
187#undef APPEND_FLAG_TO_STR
188
189 return pszFlags;
190}
191#endif /* defined(VBOX_STRICT) || defined(LOG_ENABLED) */
192
193# if 0 /* unused */
194static int drvAudioProcessOptions(PCFGMNODE pCfgHandle, const char *pszPrefix, audio_option *paOpts, size_t cOpts)
195{
196 AssertPtrReturn(pCfgHandle, VERR_INVALID_POINTER);
197 AssertPtrReturn(pszPrefix, VERR_INVALID_POINTER);
198 /* oaOpts and cOpts are optional. */
199
200 PCFGMNODE pCfgChildHandle = NULL;
201 PCFGMNODE pCfgChildChildHandle = NULL;
202
203 /* If pCfgHandle is NULL, let NULL be passed to get int and get string functions..
204 * The getter function will return default values.
205 */
206 if (pCfgHandle != NULL)
207 {
208 /* If its audio general setting, need to traverse to one child node.
209 * /Devices/ichac97/0/LUN#0/Config/Audio
210 */
211 if(!strncmp(pszPrefix, "AUDIO", 5)) /** @todo Use a \#define */
212 {
213 pCfgChildHandle = CFGMR3GetFirstChild(pCfgHandle);
214 if(pCfgChildHandle)
215 pCfgHandle = pCfgChildHandle;
216 }
217 else
218 {
219 /* If its driver specific configuration , then need to traverse two level deep child
220 * child nodes. for eg. in case of DirectSoundConfiguration item
221 * /Devices/ichac97/0/LUN#0/Config/Audio/DirectSoundConfig
222 */
223 pCfgChildHandle = CFGMR3GetFirstChild(pCfgHandle);
224 if (pCfgChildHandle)
225 {
226 pCfgChildChildHandle = CFGMR3GetFirstChild(pCfgChildHandle);
227 if (pCfgChildChildHandle)
228 pCfgHandle = pCfgChildChildHandle;
229 }
230 }
231 }
232
233 for (size_t i = 0; i < cOpts; i++)
234 {
235 audio_option *pOpt = &paOpts[i];
236 if (!pOpt->valp)
237 {
238 LogFlowFunc(("Option value pointer for `%s' is not set\n", pOpt->name));
239 continue;
240 }
241
242 bool fUseDefault;
243
244 switch (pOpt->tag)
245 {
246 case AUD_OPT_BOOL:
247 case AUD_OPT_INT:
248 {
249 int *intp = (int *)pOpt->valp;
250 *intp = drvAudioGetConfInt(pCfgHandle, pOpt->name, *intp, &fUseDefault);
251
252 break;
253 }
254
255 case AUD_OPT_FMT:
256 {
257 PDMAUDIOFMT *fmtp = (PDMAUDIOFMT *)pOpt->valp;
258 *fmtp = drvAudioGetConfFormat(pCfgHandle, pOpt->name, *fmtp, &fUseDefault);
259
260 break;
261 }
262
263 case AUD_OPT_STR:
264 {
265 const char **strp = (const char **)pOpt->valp;
266 *strp = drvAudioGetConfStr(pCfgHandle, pOpt->name, *strp, &fUseDefault);
267
268 break;
269 }
270
271 default:
272 LogFlowFunc(("Bad value tag for option `%s' - %d\n", pOpt->name, pOpt->tag));
273 fUseDefault = false;
274 break;
275 }
276
277 if (!pOpt->overridenp)
278 pOpt->overridenp = &pOpt->overriden;
279
280 *pOpt->overridenp = !fUseDefault;
281 }
282
283 return VINF_SUCCESS;
284}
285# endif /* unused */
286#endif /* !VBOX_AUDIO_TESTCASE */
287
288/**
289 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnStreamControl}
290 */
291static DECLCALLBACK(int) drvAudioStreamControl(PPDMIAUDIOCONNECTOR pInterface,
292 PPDMAUDIOSTREAM pStream, PDMAUDIOSTREAMCMD enmStreamCmd)
293{
294 AssertPtrReturn(pInterface, VERR_INVALID_POINTER);
295
296 if (!pStream)
297 return VINF_SUCCESS;
298
299 PDRVAUDIO pThis = PDMIAUDIOCONNECTOR_2_DRVAUDIO(pInterface);
300
301 int rc = RTCritSectEnter(&pThis->CritSect);
302 if (RT_FAILURE(rc))
303 return rc;
304
305 LogFlowFunc(("[%s] enmStreamCmd=%s\n", pStream->szName, DrvAudioHlpStreamCmdToStr(enmStreamCmd)));
306
307 rc = drvAudioStreamControlInternal(pThis, pStream, enmStreamCmd);
308
309 int rc2 = RTCritSectLeave(&pThis->CritSect);
310 if (RT_SUCCESS(rc))
311 rc = rc2;
312
313 return rc;
314}
315
316/**
317 * Controls an audio stream.
318 *
319 * @returns IPRT status code.
320 * @param pThis Pointer to driver instance.
321 * @param pStream Stream to control.
322 * @param enmStreamCmd Control command.
323 */
324static int drvAudioStreamControlInternal(PDRVAUDIO pThis, PPDMAUDIOSTREAM pStream, PDMAUDIOSTREAMCMD enmStreamCmd)
325{
326 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
327 AssertPtrReturn(pStream, VERR_INVALID_POINTER);
328
329 LogFunc(("[%s] enmStreamCmd=%s\n", pStream->szName, DrvAudioHlpStreamCmdToStr(enmStreamCmd)));
330
331#ifdef LOG_ENABLED
332 char *pszStreamSts = dbgAudioStreamStatusToStr(pStream->fStatus);
333 LogFlowFunc(("fStatus=%s\n", pszStreamSts));
334 RTStrFree(pszStreamSts);
335#endif /* LOG_ENABLED */
336
337 int rc = VINF_SUCCESS;
338
339 switch (enmStreamCmd)
340 {
341 case PDMAUDIOSTREAMCMD_ENABLE:
342 {
343 if (!(pStream->fStatus & PDMAUDIOSTREAMSTS_FLAGS_ENABLED))
344 {
345 /* Is a pending disable outstanding? Then disable first. */
346 if (pStream->fStatus & PDMAUDIOSTREAMSTS_FLAGS_PENDING_DISABLE)
347 rc = drvAudioStreamControlInternalBackend(pThis, pStream, PDMAUDIOSTREAMCMD_DISABLE);
348
349 if (RT_SUCCESS(rc))
350 rc = drvAudioStreamControlInternalBackend(pThis, pStream, PDMAUDIOSTREAMCMD_ENABLE);
351
352 if (RT_SUCCESS(rc))
353 pStream->fStatus |= PDMAUDIOSTREAMSTS_FLAGS_ENABLED;
354 }
355 break;
356 }
357
358 case PDMAUDIOSTREAMCMD_DISABLE:
359 {
360 if (pStream->fStatus & PDMAUDIOSTREAMSTS_FLAGS_ENABLED)
361 {
362 /*
363 * For playback (output) streams first mark the host stream as pending disable,
364 * so that the rest of the remaining audio data will be played first before
365 * closing the stream.
366 */
367 if (pStream->enmDir == PDMAUDIODIR_OUT)
368 {
369 LogFunc(("[%s] Pending disable/pause\n", pStream->szName));
370 pStream->fStatus |= PDMAUDIOSTREAMSTS_FLAGS_PENDING_DISABLE;
371 }
372
373 /* Can we close the host stream as well (not in pending disable mode)? */
374 if (!(pStream->fStatus & PDMAUDIOSTREAMSTS_FLAGS_PENDING_DISABLE))
375 {
376 rc = drvAudioStreamControlInternalBackend(pThis, pStream, PDMAUDIOSTREAMCMD_DISABLE);
377 if (RT_SUCCESS(rc))
378 drvAudioStreamResetInternal(pThis, pStream);
379 }
380 }
381 break;
382 }
383
384 case PDMAUDIOSTREAMCMD_PAUSE:
385 {
386 if (!(pStream->fStatus & PDMAUDIOSTREAMSTS_FLAGS_PAUSED))
387 {
388 rc = drvAudioStreamControlInternalBackend(pThis, pStream, PDMAUDIOSTREAMCMD_PAUSE);
389 if (RT_SUCCESS(rc))
390 pStream->fStatus |= PDMAUDIOSTREAMSTS_FLAGS_PAUSED;
391 }
392 break;
393 }
394
395 case PDMAUDIOSTREAMCMD_RESUME:
396 {
397 if (pStream->fStatus & PDMAUDIOSTREAMSTS_FLAGS_PAUSED)
398 {
399 rc = drvAudioStreamControlInternalBackend(pThis, pStream, PDMAUDIOSTREAMCMD_RESUME);
400 if (RT_SUCCESS(rc))
401 pStream->fStatus &= ~PDMAUDIOSTREAMSTS_FLAGS_PAUSED;
402 }
403 break;
404 }
405
406 case PDMAUDIOSTREAMCMD_DROP:
407 {
408 rc = drvAudioStreamControlInternalBackend(pThis, pStream, PDMAUDIOSTREAMCMD_DROP);
409 if (RT_SUCCESS(rc))
410 {
411 drvAudioStreamDropInternal(pThis, pStream);
412 }
413 break;
414 }
415
416 default:
417 rc = VERR_NOT_IMPLEMENTED;
418 break;
419 }
420
421 if (RT_FAILURE(rc))
422 LogFunc(("[%s] Failed with %Rrc\n", pStream->szName, rc));
423
424 return rc;
425}
426
427/**
428 * Controls a stream's backend.
429 * If the stream has no backend available, VERR_NOT_FOUND is returned.
430 *
431 * @returns IPRT status code.
432 * @param pThis Pointer to driver instance.
433 * @param pStream Stream to control.
434 * @param enmStreamCmd Control command.
435 */
436static int drvAudioStreamControlInternalBackend(PDRVAUDIO pThis, PPDMAUDIOSTREAM pStream, PDMAUDIOSTREAMCMD enmStreamCmd)
437{
438 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
439 AssertPtrReturn(pStream, VERR_INVALID_POINTER);
440
441#ifdef LOG_ENABLED
442 char *pszStreamSts = dbgAudioStreamStatusToStr(pStream->fStatus);
443 LogFlowFunc(("[%s] enmStreamCmd=%s, fStatus=%s\n", pStream->szName, DrvAudioHlpStreamCmdToStr(enmStreamCmd), pszStreamSts));
444 RTStrFree(pszStreamSts);
445#endif /* LOG_ENABLED */
446
447 if (!pThis->pHostDrvAudio) /* If not lower driver is configured, bail out. */
448 return VINF_SUCCESS;
449
450 int rc = VINF_SUCCESS;
451
452 /*
453 * Whether to propagate commands down to the backend.
454 *
455 * This is needed for critical operations like recording audio if audio input is disabled on a per-driver level.
456 *
457 * Note that not all commands will be covered by this, such as operations like stopping, draining and droppping,
458 * which are considered uncritical and sometimes even are required for certain backends (like DirectSound on Windows).
459 *
460 * The actual stream state will be untouched to not make the state machine handling more complicated than
461 * it already is.
462 *
463 * See #9882.
464 */
465 const bool fEnabled = ( pStream->enmDir == PDMAUDIODIR_IN
466 && pThis->In.fEnabled)
467 || ( pStream->enmDir == PDMAUDIODIR_OUT
468 && pThis->Out.fEnabled);
469
470 LogRel2(("Audio: %s stream '%s' in backend (%s is %s)\n", DrvAudioHlpStreamCmdToStr(enmStreamCmd), pStream->szName,
471 DrvAudioHlpAudDirToStr(pStream->enmDir),
472 fEnabled ? "enabled" : "disabled"));
473 switch (enmStreamCmd)
474 {
475 case PDMAUDIOSTREAMCMD_ENABLE:
476 {
477 if (fEnabled)
478 rc = pThis->pHostDrvAudio->pfnStreamControl(pThis->pHostDrvAudio, pStream->pvBackend, PDMAUDIOSTREAMCMD_ENABLE);
479 break;
480 }
481
482 case PDMAUDIOSTREAMCMD_DISABLE:
483 {
484 rc = pThis->pHostDrvAudio->pfnStreamControl(pThis->pHostDrvAudio, pStream->pvBackend, PDMAUDIOSTREAMCMD_DISABLE);
485 break;
486 }
487
488 case PDMAUDIOSTREAMCMD_PAUSE:
489 {
490 if (fEnabled) /* Needed, as resume below also is being checked for. */
491 rc = pThis->pHostDrvAudio->pfnStreamControl(pThis->pHostDrvAudio, pStream->pvBackend, PDMAUDIOSTREAMCMD_PAUSE);
492 break;
493 }
494
495 case PDMAUDIOSTREAMCMD_RESUME:
496 {
497 if (fEnabled)
498 rc = pThis->pHostDrvAudio->pfnStreamControl(pThis->pHostDrvAudio, pStream->pvBackend, PDMAUDIOSTREAMCMD_RESUME);
499 break;
500 }
501
502 case PDMAUDIOSTREAMCMD_DRAIN:
503 {
504 rc = pThis->pHostDrvAudio->pfnStreamControl(pThis->pHostDrvAudio, pStream->pvBackend, PDMAUDIOSTREAMCMD_DRAIN);
505 break;
506 }
507
508 case PDMAUDIOSTREAMCMD_DROP:
509 {
510 rc = pThis->pHostDrvAudio->pfnStreamControl(pThis->pHostDrvAudio, pStream->pvBackend, PDMAUDIOSTREAMCMD_DROP);
511 break;
512 }
513
514 default:
515 {
516 AssertMsgFailed(("Command %RU32 not implemented\n", enmStreamCmd));
517 rc = VERR_NOT_IMPLEMENTED;
518 break;
519 }
520 }
521
522 if (RT_FAILURE(rc))
523 {
524 if ( rc != VERR_NOT_IMPLEMENTED
525 && rc != VERR_NOT_SUPPORTED
526 && rc != VERR_AUDIO_STREAM_NOT_READY)
527 {
528 LogRel(("Audio: %s stream '%s' failed with %Rrc\n", DrvAudioHlpStreamCmdToStr(enmStreamCmd), pStream->szName, rc));
529 }
530
531 LogFunc(("[%s] %s failed with %Rrc\n", pStream->szName, DrvAudioHlpStreamCmdToStr(enmStreamCmd), rc));
532 }
533
534 return rc;
535}
536
537/**
538 * Initializes an audio stream with a given host and guest stream configuration.
539 *
540 * @returns IPRT status code.
541 * @param pThis Pointer to driver instance.
542 * @param pStream Stream to initialize.
543 * @param pCfgHost Stream configuration to use for the host side (backend).
544 * @param pCfgGuest Stream configuration to use for the guest side.
545 */
546static int drvAudioStreamInitInternal(PDRVAUDIO pThis,
547 PPDMAUDIOSTREAM pStream, PPDMAUDIOSTREAMCFG pCfgHost, PPDMAUDIOSTREAMCFG pCfgGuest)
548{
549 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
550 AssertPtrReturn(pStream, VERR_INVALID_POINTER);
551 AssertPtrReturn(pCfgHost, VERR_INVALID_POINTER);
552 AssertPtrReturn(pCfgGuest, VERR_INVALID_POINTER);
553
554 /*
555 * Init host stream.
556 */
557
558 /* Set the host's default audio data layout. */
559 pCfgHost->enmLayout = PDMAUDIOSTREAMLAYOUT_NON_INTERLEAVED;
560
561#ifdef LOG_ENABLED
562 LogFunc(("[%s] Requested host format:\n", pStream->szName));
563 DrvAudioHlpStreamCfgPrint(pCfgHost);
564#endif
565
566 LogRel2(("Audio: Creating stream '%s'\n", pStream->szName));
567 LogRel2(("Audio: Guest %s format for '%s': %RU32Hz, %u%s, %RU8 %s\n",
568 pCfgGuest->enmDir == PDMAUDIODIR_IN ? "recording" : "playback", pStream->szName,
569 pCfgGuest->Props.uHz, pCfgGuest->Props.cbSample * 8, pCfgGuest->Props.fSigned ? "S" : "U",
570 pCfgGuest->Props.cChannels, pCfgGuest->Props.cChannels == 1 ? "Channel" : "Channels"));
571 LogRel2(("Audio: Requested host %s format for '%s': %RU32Hz, %u%s, %RU8 %s\n",
572 pCfgHost->enmDir == PDMAUDIODIR_IN ? "recording" : "playback", pStream->szName,
573 pCfgHost->Props.uHz, pCfgHost->Props.cbSample * 8, pCfgHost->Props.fSigned ? "S" : "U",
574 pCfgHost->Props.cChannels, pCfgHost->Props.cChannels == 1 ? "Channel" : "Channels"));
575
576 PDMAUDIOSTREAMCFG CfgHostAcq;
577 int rc = drvAudioStreamCreateInternalBackend(pThis, pStream, pCfgHost, &CfgHostAcq);
578 if (RT_FAILURE(rc))
579 return rc;
580
581#ifdef LOG_ENABLED
582 LogFunc(("[%s] Acquired host format:\n", pStream->szName));
583 DrvAudioHlpStreamCfgPrint(&CfgHostAcq);
584#endif
585
586 LogRel2(("Audio: Acquired host %s format for '%s': %RU32Hz, %u%s, %RU8 %s\n",
587 CfgHostAcq.enmDir == PDMAUDIODIR_IN ? "recording" : "playback", pStream->szName,
588 CfgHostAcq.Props.uHz, CfgHostAcq.Props.cbSample * 8, CfgHostAcq.Props.fSigned ? "S" : "U",
589 CfgHostAcq.Props.cChannels, CfgHostAcq.Props.cChannels == 1 ? "Channel" : "Channels"));
590
591 /* Let the user know if the backend changed some of the tweakable values. */
592 if (CfgHostAcq.Backend.cFramesBufferSize != pCfgHost->Backend.cFramesBufferSize)
593 LogRel2(("Audio: Backend changed buffer size from %RU64ms (%RU32 frames) to %RU64ms (%RU32 frames)\n",
594 DrvAudioHlpFramesToMilli(pCfgHost->Backend.cFramesBufferSize, &pCfgHost->Props), pCfgHost->Backend.cFramesBufferSize,
595 DrvAudioHlpFramesToMilli(CfgHostAcq.Backend.cFramesBufferSize, &CfgHostAcq.Props), CfgHostAcq.Backend.cFramesBufferSize));
596
597 if (CfgHostAcq.Backend.cFramesPeriod != pCfgHost->Backend.cFramesPeriod)
598 LogRel2(("Audio: Backend changed period size from %RU64ms (%RU32 frames) to %RU64ms (%RU32 frames)\n",
599 DrvAudioHlpFramesToMilli(pCfgHost->Backend.cFramesPeriod, &pCfgHost->Props), pCfgHost->Backend.cFramesPeriod,
600 DrvAudioHlpFramesToMilli(CfgHostAcq.Backend.cFramesPeriod, &CfgHostAcq.Props), CfgHostAcq.Backend.cFramesPeriod));
601
602 if (CfgHostAcq.Backend.cFramesPreBuffering != pCfgHost->Backend.cFramesPreBuffering)
603 LogRel2(("Audio: Backend changed pre-buffering size from %RU64ms (%RU32 frames) to %RU64ms (%RU32 frames)\n",
604 DrvAudioHlpFramesToMilli(pCfgHost->Backend.cFramesPreBuffering, &pCfgHost->Props), pCfgHost->Backend.cFramesPreBuffering,
605 DrvAudioHlpFramesToMilli(CfgHostAcq.Backend.cFramesPreBuffering, &CfgHostAcq.Props), CfgHostAcq.Backend.cFramesPreBuffering));
606 /*
607 * Configure host buffers.
608 */
609
610 /* Check if the backend did return sane values and correct if necessary.
611 * Should never happen with our own backends, but you never know ... */
612 if (CfgHostAcq.Backend.cFramesBufferSize < CfgHostAcq.Backend.cFramesPreBuffering)
613 {
614 LogRel2(("Audio: Warning: Pre-buffering size (%RU32 frames) of stream '%s' does not match buffer size (%RU32 frames), "
615 "setting pre-buffering size to %RU32 frames\n",
616 CfgHostAcq.Backend.cFramesPreBuffering, pStream->szName, CfgHostAcq.Backend.cFramesBufferSize, CfgHostAcq.Backend.cFramesBufferSize));
617 CfgHostAcq.Backend.cFramesPreBuffering = CfgHostAcq.Backend.cFramesBufferSize;
618 }
619
620 if (CfgHostAcq.Backend.cFramesPeriod > CfgHostAcq.Backend.cFramesBufferSize)
621 {
622 LogRel2(("Audio: Warning: Period size (%RU32 frames) of stream '%s' does not match buffer size (%RU32 frames), setting to %RU32 frames\n",
623 CfgHostAcq.Backend.cFramesPeriod, pStream->szName, CfgHostAcq.Backend.cFramesBufferSize, CfgHostAcq.Backend.cFramesBufferSize));
624 CfgHostAcq.Backend.cFramesPeriod = CfgHostAcq.Backend.cFramesBufferSize;
625 }
626
627 uint64_t msBufferSize = DrvAudioHlpFramesToMilli(CfgHostAcq.Backend.cFramesBufferSize, &CfgHostAcq.Props);
628
629 LogRel2(("Audio: Buffer size of stream '%s' is %RU64ms (%RU32 frames)\n",
630 pStream->szName, msBufferSize, CfgHostAcq.Backend.cFramesBufferSize));
631
632 /* If no own pre-buffer is set, let the backend choose. */
633 uint64_t msPreBuf = DrvAudioHlpFramesToMilli(CfgHostAcq.Backend.cFramesPreBuffering, &CfgHostAcq.Props);
634 LogRel2(("Audio: Pre-buffering size of stream '%s' is %RU64ms (%RU32 frames)\n",
635 pStream->szName, msPreBuf, CfgHostAcq.Backend.cFramesPreBuffering));
636
637 /* Make sure the configured buffer size by the backend at least can hold the configured latency. */
638 const uint32_t msPeriod = DrvAudioHlpFramesToMilli(CfgHostAcq.Backend.cFramesPeriod, &CfgHostAcq.Props);
639
640 LogRel2(("Audio: Period size of stream '%s' is %RU64ms (%RU32 frames)\n",
641 pStream->szName, msPeriod, CfgHostAcq.Backend.cFramesPeriod));
642
643 if ( pCfgGuest->Device.cMsSchedulingHint /* Any scheduling hint set? */
644 && pCfgGuest->Device.cMsSchedulingHint > msPeriod) /* This might lead to buffer underflows. */
645 {
646 LogRel(("Audio: Warning: Scheduling hint of stream '%s' is bigger (%RU64ms) than used period size (%RU64ms)\n",
647 pStream->szName, pCfgGuest->Device.cMsSchedulingHint, msPeriod));
648 }
649
650 /* Destroy any former mixing buffer. */
651 AudioMixBufDestroy(&pStream->Host.MixBuf);
652
653 /* Make sure to (re-)set the host buffer's shift size. */
654 CfgHostAcq.Props.cShift = PDMAUDIOPCMPROPS_MAKE_SHIFT_PARMS(CfgHostAcq.Props.cbSample, CfgHostAcq.Props.cChannels);
655
656 rc = AudioMixBufInit(&pStream->Host.MixBuf, pStream->szName, &CfgHostAcq.Props, CfgHostAcq.Backend.cFramesBufferSize);
657 AssertRC(rc);
658
659 /* Make a copy of the acquired host stream configuration. */
660 rc = DrvAudioHlpStreamCfgCopy(&pStream->Host.Cfg, &CfgHostAcq);
661 AssertRC(rc);
662
663 /*
664 * Init guest stream.
665 */
666
667 if (pCfgGuest->Device.cMsSchedulingHint)
668 LogRel2(("Audio: Stream '%s' got a scheduling hint of %RU32ms (%RU32 bytes)\n",
669 pStream->szName, pCfgGuest->Device.cMsSchedulingHint,
670 DrvAudioHlpMilliToBytes(pCfgGuest->Device.cMsSchedulingHint, &pCfgGuest->Props)));
671
672 /* Destroy any former mixing buffer. */
673 AudioMixBufDestroy(&pStream->Guest.MixBuf);
674
675 /* Set the guests's default audio data layout. */
676 pCfgGuest->enmLayout = PDMAUDIOSTREAMLAYOUT_NON_INTERLEAVED;
677
678 /* Make sure to (re-)set the guest buffer's shift size. */
679 pCfgGuest->Props.cShift = PDMAUDIOPCMPROPS_MAKE_SHIFT_PARMS(pCfgGuest->Props.cbSample, pCfgGuest->Props.cChannels);
680
681 rc = AudioMixBufInit(&pStream->Guest.MixBuf, pStream->szName, &pCfgGuest->Props, CfgHostAcq.Backend.cFramesBufferSize);
682 AssertRC(rc);
683
684 /* Make a copy of the guest stream configuration. */
685 rc = DrvAudioHlpStreamCfgCopy(&pStream->Guest.Cfg, pCfgGuest);
686 AssertRC(rc);
687
688 if (RT_FAILURE(rc))
689 LogRel(("Audio: Creating stream '%s' failed with %Rrc\n", pStream->szName, rc));
690
691 if (pCfgGuest->enmDir == PDMAUDIODIR_IN)
692 {
693 /* Host (Parent) -> Guest (Child). */
694 rc = AudioMixBufLinkTo(&pStream->Host.MixBuf, &pStream->Guest.MixBuf);
695 AssertRC(rc);
696 }
697 else
698 {
699 /* Guest (Parent) -> Host (Child). */
700 rc = AudioMixBufLinkTo(&pStream->Guest.MixBuf, &pStream->Host.MixBuf);
701 AssertRC(rc);
702 }
703
704#ifdef VBOX_WITH_STATISTICS
705 char szStatName[255];
706
707 if (pCfgGuest->enmDir == PDMAUDIODIR_IN)
708 {
709 RTStrPrintf(szStatName, sizeof(szStatName), "Guest/%s/TotalFramesCaptured", pStream->szName);
710 PDMDrvHlpSTAMRegCounterEx(pThis->pDrvIns, &pStream->In.Stats.TotalFramesCaptured,
711 szStatName, STAMUNIT_COUNT, "Total frames played.");
712 RTStrPrintf(szStatName, sizeof(szStatName), "Guest/%s/TotalTimesCaptured", pStream->szName);
713 PDMDrvHlpSTAMRegCounterEx(pThis->pDrvIns, &pStream->In.Stats.TotalTimesCaptured,
714 szStatName, STAMUNIT_COUNT, "Total number of playbacks.");
715 RTStrPrintf(szStatName, sizeof(szStatName), "Guest/%s/TotalFramesRead", pStream->szName);
716 PDMDrvHlpSTAMRegCounterEx(pThis->pDrvIns, &pStream->In.Stats.TotalFramesRead,
717 szStatName, STAMUNIT_COUNT, "Total frames read.");
718 RTStrPrintf(szStatName, sizeof(szStatName), "Guest/%s/TotalTimesRead", pStream->szName);
719 PDMDrvHlpSTAMRegCounterEx(pThis->pDrvIns, &pStream->In.Stats.TotalTimesRead,
720 szStatName, STAMUNIT_COUNT, "Total number of reads.");
721 }
722 else if (pCfgGuest->enmDir == PDMAUDIODIR_OUT)
723 {
724 RTStrPrintf(szStatName, sizeof(szStatName), "Guest/%s/TotalFramesPlayed", pStream->szName);
725 PDMDrvHlpSTAMRegCounterEx(pThis->pDrvIns, &pStream->Out.Stats.TotalFramesPlayed,
726 szStatName, STAMUNIT_COUNT, "Total frames played.");
727
728 RTStrPrintf(szStatName, sizeof(szStatName), "Guest/%s/TotalTimesPlayed", pStream->szName);
729 PDMDrvHlpSTAMRegCounterEx(pThis->pDrvIns, &pStream->Out.Stats.TotalTimesPlayed,
730 szStatName, STAMUNIT_COUNT, "Total number of playbacks.");
731 RTStrPrintf(szStatName, sizeof(szStatName), "Guest/%s/TotalFramesWritten", pStream->szName);
732 PDMDrvHlpSTAMRegCounterEx(pThis->pDrvIns, &pStream->Out.Stats.TotalFramesWritten,
733 szStatName, STAMUNIT_COUNT, "Total frames written.");
734
735 RTStrPrintf(szStatName, sizeof(szStatName), "Guest/%s/TotalTimesWritten", pStream->szName);
736 PDMDrvHlpSTAMRegCounterEx(pThis->pDrvIns, &pStream->Out.Stats.TotalTimesWritten,
737 szStatName, STAMUNIT_COUNT, "Total number of writes.");
738 }
739 else
740 AssertFailed();
741#endif
742
743 LogFlowFunc(("[%s] Returning %Rrc\n", pStream->szName, rc));
744 return rc;
745}
746
747/**
748 * Frees an audio stream and its allocated resources.
749 *
750 * @param pStream Audio stream to free.
751 * After this call the pointer will not be valid anymore.
752 */
753static void drvAudioStreamFree(PPDMAUDIOSTREAM pStream)
754{
755 if (!pStream)
756 return;
757
758 LogFunc(("[%s]\n", pStream->szName));
759
760 if (pStream->pvBackend)
761 {
762 Assert(pStream->cbBackend);
763 RTMemFree(pStream->pvBackend);
764 pStream->pvBackend = NULL;
765 }
766
767 RTMemFree(pStream);
768 pStream = NULL;
769}
770
771#ifdef VBOX_WITH_AUDIO_CALLBACKS
772/**
773 * Schedules a re-initialization of all current audio streams.
774 * The actual re-initialization will happen at some later point in time.
775 *
776 * @returns IPRT status code.
777 * @param pThis Pointer to driver instance.
778 */
779static int drvAudioScheduleReInitInternal(PDRVAUDIO pThis)
780{
781 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
782
783 LogFunc(("\n"));
784
785 /* Mark all host streams to re-initialize. */
786 PPDMAUDIOSTREAM pStream;
787 RTListForEach(&pThis->lstStreams, pStream, PDMAUDIOSTREAM, Node)
788 {
789 pStream->fStatus |= PDMAUDIOSTREAMSTS_FLAGS_PENDING_REINIT;
790 pStream->cTriesReInit = 0;
791 pStream->tsLastReInitNs = 0;
792 }
793
794# ifdef VBOX_WITH_AUDIO_ENUM
795 /* Re-enumerate all host devices as soon as possible. */
796 pThis->fEnumerateDevices = true;
797# endif
798
799 return VINF_SUCCESS;
800}
801#endif /* VBOX_WITH_AUDIO_CALLBACKS */
802
803/**
804 * Re-initializes an audio stream with its existing host and guest stream configuration.
805 * This might be the case if the backend told us we need to re-initialize because something
806 * on the host side has changed.
807 *
808 * Note: Does not touch the stream's status flags.
809 *
810 * @returns IPRT status code.
811 * @param pThis Pointer to driver instance.
812 * @param pStream Stream to re-initialize.
813 */
814static int drvAudioStreamReInitInternal(PDRVAUDIO pThis, PPDMAUDIOSTREAM pStream)
815{
816 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
817 AssertPtrReturn(pStream, VERR_INVALID_POINTER);
818
819 LogFlowFunc(("[%s]\n", pStream->szName));
820
821 /*
822 * Gather current stream status.
823 */
824 const bool fIsEnabled = RT_BOOL(pStream->fStatus & PDMAUDIOSTREAMSTS_FLAGS_ENABLED); /* Stream is enabled? */
825
826 /*
827 * Destroy and re-create stream on backend side.
828 */
829 int rc = drvAudioStreamControlInternalBackend(pThis, pStream, PDMAUDIOSTREAMCMD_DISABLE);
830 if (RT_SUCCESS(rc))
831 {
832 rc = drvAudioStreamDestroyInternalBackend(pThis, pStream);
833 if (RT_SUCCESS(rc))
834 {
835 PDMAUDIOSTREAMCFG CfgHostAcq;
836 rc = drvAudioStreamCreateInternalBackend(pThis, pStream, &pStream->Host.Cfg, &CfgHostAcq);
837 /** @todo Validate (re-)acquired configuration with pStream->Host.Cfg? */
838 if (RT_SUCCESS(rc))
839 {
840#ifdef LOG_ENABLED
841 LogFunc(("[%s] Acquired host format:\n", pStream->szName));
842 DrvAudioHlpStreamCfgPrint(&CfgHostAcq);
843#endif
844 }
845 }
846 }
847
848 /* Drop all old data. */
849 drvAudioStreamDropInternal(pThis, pStream);
850
851 /*
852 * Restore previous stream state.
853 */
854 if (fIsEnabled)
855 rc = drvAudioStreamControlInternalBackend(pThis, pStream, PDMAUDIOSTREAMCMD_ENABLE);
856
857 if (RT_FAILURE(rc))
858 LogRel(("Audio: Re-initializing stream '%s' failed with %Rrc\n", pStream->szName, rc));
859
860 LogFunc(("[%s] Returning %Rrc\n", pStream->szName, rc));
861 return rc;
862}
863
864/**
865 * Drops all audio data (and associated state) of a stream.
866 *
867 * @param pThis Pointer to driver instance.
868 * @param pStream Stream to drop data for.
869 */
870static void drvAudioStreamDropInternal(PDRVAUDIO pThis, PPDMAUDIOSTREAM pStream)
871{
872 RT_NOREF(pThis);
873
874 LogFunc(("[%s]\n", pStream->szName));
875
876 AudioMixBufReset(&pStream->Guest.MixBuf);
877 AudioMixBufReset(&pStream->Host.MixBuf);
878
879 pStream->tsLastIteratedNs = 0;
880 pStream->tsLastPlayedCapturedNs = 0;
881 pStream->tsLastReadWrittenNs = 0;
882
883 pStream->fThresholdReached = false;
884}
885
886/**
887 * Resets a given audio stream.
888 *
889 * @param pThis Pointer to driver instance.
890 * @param pStream Stream to reset.
891 */
892static void drvAudioStreamResetInternal(PDRVAUDIO pThis, PPDMAUDIOSTREAM pStream)
893{
894 drvAudioStreamDropInternal(pThis, pStream);
895
896 LogFunc(("[%s]\n", pStream->szName));
897
898 pStream->fStatus = PDMAUDIOSTREAMSTS_FLAGS_INITIALIZED;
899#ifdef VBOX_WITH_STATISTICS
900 /*
901 * Reset statistics.
902 */
903 if (pStream->enmDir == PDMAUDIODIR_IN)
904 {
905 STAM_COUNTER_RESET(&pStream->In.Stats.TotalFramesCaptured);
906 STAM_COUNTER_RESET(&pStream->In.Stats.TotalFramesRead);
907 STAM_COUNTER_RESET(&pStream->In.Stats.TotalTimesCaptured);
908 STAM_COUNTER_RESET(&pStream->In.Stats.TotalTimesRead);
909 }
910 else if (pStream->enmDir == PDMAUDIODIR_OUT)
911 {
912 STAM_COUNTER_RESET(&pStream->Out.Stats.TotalFramesPlayed);
913 STAM_COUNTER_RESET(&pStream->Out.Stats.TotalFramesWritten);
914 STAM_COUNTER_RESET(&pStream->Out.Stats.TotalTimesPlayed);
915 STAM_COUNTER_RESET(&pStream->Out.Stats.TotalTimesWritten);
916 }
917 else
918 AssertFailed();
919#endif
920}
921
922/**
923 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnStreamWrite}
924 */
925static DECLCALLBACK(int) drvAudioStreamWrite(PPDMIAUDIOCONNECTOR pInterface, PPDMAUDIOSTREAM pStream,
926 const void *pvBuf, uint32_t cbBuf, uint32_t *pcbWritten)
927{
928 AssertPtrReturn(pInterface, VERR_INVALID_POINTER);
929 AssertPtrReturn(pStream, VERR_INVALID_POINTER);
930 AssertPtrReturn(pvBuf, VERR_INVALID_POINTER);
931 AssertReturn(cbBuf, VERR_INVALID_PARAMETER);
932 /* pcbWritten is optional. */
933
934 PDRVAUDIO pThis = PDMIAUDIOCONNECTOR_2_DRVAUDIO(pInterface);
935
936 AssertMsg(pStream->enmDir == PDMAUDIODIR_OUT,
937 ("Stream '%s' is not an output stream and therefore cannot be written to (direction is '%s')\n",
938 pStream->szName, DrvAudioHlpAudDirToStr(pStream->enmDir)));
939
940 AssertMsg(DrvAudioHlpBytesIsAligned(cbBuf, &pStream->Guest.Cfg.Props),
941 ("Stream '%s' got a non-frame-aligned write (%RU32 bytes)\n", pStream->szName, cbBuf));
942
943 uint32_t cbWrittenTotal = 0;
944
945 int rc = RTCritSectEnter(&pThis->CritSect);
946 if (RT_FAILURE(rc))
947 return rc;
948
949#ifdef VBOX_WITH_STATISTICS
950 STAM_PROFILE_ADV_START(&pThis->Stats.DelayOut, out);
951#endif
952
953#ifdef LOG_ENABLED
954 char *pszStreamSts = dbgAudioStreamStatusToStr(pStream->fStatus);
955 AssertPtr(pszStreamSts);
956#endif
957
958 /* Whether to discard the incoming data or not. */
959 bool fToBitBucket = false;
960
961 do
962 {
963 if (!DrvAudioHlpStreamStatusIsReady(pStream->fStatus))
964 {
965 rc = VERR_AUDIO_STREAM_NOT_READY;
966 break;
967 }
968
969 /* If output is disabled on a per-driver level, send data to the bit bucket instead. See #9882. */
970 if (!pThis->Out.fEnabled)
971 {
972 fToBitBucket = true;
973 break;
974 }
975
976 if (pThis->pHostDrvAudio)
977 {
978 /* If the backend's stream is not writable, all written data goes to /dev/null. */
979 if (!DrvAudioHlpStreamStatusCanWrite(
980 pThis->pHostDrvAudio->pfnStreamGetStatus(pThis->pHostDrvAudio, pStream->pvBackend)))
981 {
982 fToBitBucket = true;
983 break;
984 }
985 }
986
987 const uint32_t cbFree = AudioMixBufFreeBytes(&pStream->Host.MixBuf);
988 if (cbFree < cbBuf)
989 LogRel2(("Audio: Lost audio output (%RU64ms, %RU32 free but needs %RU32) due to full host stream buffer '%s'\n",
990 DrvAudioHlpBytesToMilli(cbBuf - cbFree, &pStream->Host.Cfg.Props), cbFree, cbBuf, pStream->szName));
991
992 uint32_t cbToWrite = RT_MIN(cbBuf, cbFree);
993 if (!cbToWrite)
994 {
995 rc = VERR_BUFFER_OVERFLOW;
996 break;
997 }
998
999 /* We use the guest side mixing buffer as an intermediate buffer to do some
1000 * (first) processing (if needed), so always write the incoming data at offset 0. */
1001 uint32_t cfGstWritten = 0;
1002 rc = AudioMixBufWriteAt(&pStream->Guest.MixBuf, 0 /* offFrames */, pvBuf, cbToWrite, &cfGstWritten);
1003 if ( RT_FAILURE(rc)
1004 || !cfGstWritten)
1005 {
1006 AssertMsgFailed(("[%s] Write failed: cbToWrite=%RU32, cfWritten=%RU32, rc=%Rrc\n",
1007 pStream->szName, cbToWrite, cfGstWritten, rc));
1008 break;
1009 }
1010
1011 if (pThis->Out.Cfg.Dbg.fEnabled)
1012 DrvAudioHlpFileWrite(pStream->Out.Dbg.pFileStreamWrite, pvBuf, cbToWrite, 0 /* fFlags */);
1013
1014 uint32_t cfGstMixed = 0;
1015 if (cfGstWritten)
1016 {
1017 int rc2 = AudioMixBufMixToParentEx(&pStream->Guest.MixBuf, 0 /* cSrcOffset */, cfGstWritten /* cSrcFrames */,
1018 &cfGstMixed /* pcSrcMixed */);
1019 if (RT_FAILURE(rc2))
1020 {
1021 AssertMsgFailed(("[%s] Mixing failed: cbToWrite=%RU32, cfWritten=%RU32, cfMixed=%RU32, rc=%Rrc\n",
1022 pStream->szName, cbToWrite, cfGstWritten, cfGstMixed, rc2));
1023 }
1024 else
1025 {
1026 const uint64_t tsNowNs = RTTimeNanoTS();
1027
1028 Log3Func(("[%s] Writing %RU32 frames (%RU64ms)\n",
1029 pStream->szName, cfGstWritten, DrvAudioHlpFramesToMilli(cfGstWritten, &pStream->Guest.Cfg.Props)));
1030
1031 Log3Func(("[%s] Last written %RU64ns (%RU64ms), now filled with %RU64ms -- %RU8%%\n",
1032 pStream->szName, tsNowNs - pStream->tsLastReadWrittenNs,
1033 (tsNowNs - pStream->tsLastReadWrittenNs) / RT_NS_1MS,
1034 DrvAudioHlpFramesToMilli(AudioMixBufUsed(&pStream->Host.MixBuf), &pStream->Host.Cfg.Props),
1035 AudioMixBufUsed(&pStream->Host.MixBuf) * 100 / AudioMixBufSize(&pStream->Host.MixBuf)));
1036
1037 pStream->tsLastReadWrittenNs = tsNowNs;
1038 /* Keep going. */
1039 }
1040
1041 if (RT_SUCCESS(rc))
1042 rc = rc2;
1043
1044 cbWrittenTotal = AUDIOMIXBUF_F2B(&pStream->Guest.MixBuf, cfGstWritten);
1045
1046#ifdef VBOX_WITH_STATISTICS
1047 STAM_COUNTER_ADD(&pThis->Stats.TotalFramesWritten, cfGstWritten);
1048 STAM_COUNTER_ADD(&pThis->Stats.TotalFramesMixedOut, cfGstMixed);
1049 Assert(cfGstWritten >= cfGstMixed);
1050 STAM_COUNTER_ADD(&pThis->Stats.TotalFramesLostOut, cfGstWritten - cfGstMixed);
1051 STAM_COUNTER_ADD(&pThis->Stats.TotalBytesWritten, cbWrittenTotal);
1052
1053 STAM_COUNTER_ADD(&pStream->Out.Stats.TotalFramesWritten, cfGstWritten);
1054 STAM_COUNTER_INC(&pStream->Out.Stats.TotalTimesWritten);
1055#endif
1056 }
1057
1058 Log3Func(("[%s] Dbg: cbBuf=%RU32, cbToWrite=%RU32, cfHstUsed=%RU32, cfHstfLive=%RU32, cfGstWritten=%RU32, "
1059 "cfGstMixed=%RU32, cbWrittenTotal=%RU32, rc=%Rrc\n",
1060 pStream->szName, cbBuf, cbToWrite, AudioMixBufUsed(&pStream->Host.MixBuf),
1061 AudioMixBufLive(&pStream->Host.MixBuf), cfGstWritten, cfGstMixed, cbWrittenTotal, rc));
1062
1063 } while (0);
1064
1065#ifdef LOG_ENABLED
1066 RTStrFree(pszStreamSts);
1067#endif
1068
1069 int rc2 = RTCritSectLeave(&pThis->CritSect);
1070 if (RT_SUCCESS(rc))
1071 rc = rc2;
1072
1073 if (RT_SUCCESS(rc))
1074 {
1075 if (fToBitBucket)
1076 {
1077 Log3Func(("[%s] Backend stream not ready (yet), discarding written data\n", pStream->szName));
1078 cbWrittenTotal = cbBuf; /* Report all data as being written to the caller. */
1079 }
1080
1081 if (pcbWritten)
1082 *pcbWritten = cbWrittenTotal;
1083 }
1084
1085 return rc;
1086}
1087
1088/**
1089 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnStreamRetain}
1090 */
1091static DECLCALLBACK(uint32_t) drvAudioStreamRetain(PPDMIAUDIOCONNECTOR pInterface, PPDMAUDIOSTREAM pStream)
1092{
1093 AssertPtrReturn(pInterface, UINT32_MAX);
1094 AssertPtrReturn(pStream, UINT32_MAX);
1095
1096 NOREF(pInterface);
1097
1098 return ++pStream->cRefs;
1099}
1100
1101/**
1102 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnStreamRelease}
1103 */
1104static DECLCALLBACK(uint32_t) drvAudioStreamRelease(PPDMIAUDIOCONNECTOR pInterface, PPDMAUDIOSTREAM pStream)
1105{
1106 AssertPtrReturn(pInterface, UINT32_MAX);
1107 AssertPtrReturn(pStream, UINT32_MAX);
1108
1109 NOREF(pInterface);
1110
1111 if (pStream->cRefs > 1) /* 1 reference always is kept by this audio driver. */
1112 pStream->cRefs--;
1113
1114 return pStream->cRefs;
1115}
1116
1117/**
1118 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnStreamIterate}
1119 */
1120static DECLCALLBACK(int) drvAudioStreamIterate(PPDMIAUDIOCONNECTOR pInterface, PPDMAUDIOSTREAM pStream)
1121{
1122 AssertPtrReturn(pInterface, VERR_INVALID_POINTER);
1123 AssertPtrReturn(pStream, VERR_INVALID_POINTER);
1124
1125 PDRVAUDIO pThis = PDMIAUDIOCONNECTOR_2_DRVAUDIO(pInterface);
1126
1127 int rc = RTCritSectEnter(&pThis->CritSect);
1128 if (RT_FAILURE(rc))
1129 return rc;
1130
1131 rc = drvAudioStreamIterateInternal(pThis, pStream);
1132
1133 int rc2 = RTCritSectLeave(&pThis->CritSect);
1134 if (RT_SUCCESS(rc))
1135 rc = rc2;
1136
1137 if (RT_FAILURE(rc))
1138 LogFlowFuncLeaveRC(rc);
1139
1140 return rc;
1141}
1142
1143/**
1144 * Re-initializes the given stream if it is scheduled for this operation.
1145 *
1146 * @note This caller must have entered the critical section of the driver instance,
1147 * needed for the host device (re-)enumeration.
1148 *
1149 * @param pThis Pointer to driver instance.
1150 * @param pStream Stream to check and maybe re-initialize.
1151 */
1152static void drvAudioStreamMaybeReInit(PDRVAUDIO pThis, PPDMAUDIOSTREAM pStream)
1153{
1154 if (pStream->fStatus & PDMAUDIOSTREAMSTS_FLAGS_PENDING_REINIT)
1155 {
1156 const unsigned cMaxTries = 3; /** @todo Make this configurable? */
1157 const uint64_t tsNowNs = RTTimeNanoTS();
1158
1159 /* Throttle re-initializing streams on failure. */
1160 if ( pStream->cTriesReInit < cMaxTries
1161 && tsNowNs - pStream->tsLastReInitNs >= RT_NS_1SEC * pStream->cTriesReInit) /** @todo Ditto. */
1162 {
1163#ifdef VBOX_WITH_AUDIO_ENUM
1164 if (pThis->fEnumerateDevices)
1165 {
1166 /* Make sure to leave the driver's critical section before enumerating host stuff. */
1167 int rc2 = RTCritSectLeave(&pThis->CritSect);
1168 AssertRC(rc2);
1169
1170 /* Re-enumerate all host devices. */
1171 drvAudioDevicesEnumerateInternal(pThis, true /* fLog */, NULL /* pDevEnum */);
1172
1173 /* Re-enter the critical section again. */
1174 rc2 = RTCritSectEnter(&pThis->CritSect);
1175 AssertRC(rc2);
1176
1177 pThis->fEnumerateDevices = false;
1178 }
1179#endif /* VBOX_WITH_AUDIO_ENUM */
1180
1181 int rc = drvAudioStreamReInitInternal(pThis, pStream);
1182 if (RT_FAILURE(rc))
1183 {
1184 pStream->cTriesReInit++;
1185 pStream->tsLastReInitNs = tsNowNs;
1186 }
1187 else
1188 {
1189 /* Remove the pending re-init flag on success. */
1190 pStream->fStatus &= ~PDMAUDIOSTREAMSTS_FLAGS_PENDING_REINIT;
1191 }
1192 }
1193 else
1194 {
1195 /* Did we exceed our tries re-initializing the stream?
1196 * Then this one is dead-in-the-water, so disable it for further use. */
1197 if (pStream->cTriesReInit == cMaxTries)
1198 {
1199 LogRel(("Audio: Re-initializing stream '%s' exceeded maximum retries (%u), leaving as disabled\n",
1200 pStream->szName, cMaxTries));
1201
1202 /* Don't try to re-initialize anymore and mark as disabled. */
1203 pStream->fStatus &= ~(PDMAUDIOSTREAMSTS_FLAGS_PENDING_REINIT | PDMAUDIOSTREAMSTS_FLAGS_ENABLED);
1204
1205 /* Note: Further writes to this stream go to / will be read from the bit bucket (/dev/null) from now on. */
1206 }
1207 }
1208
1209#ifdef LOG_ENABLED
1210 char *pszStreamSts = dbgAudioStreamStatusToStr(pStream->fStatus);
1211 Log3Func(("[%s] fStatus=%s\n", pStream->szName, pszStreamSts));
1212 RTStrFree(pszStreamSts);
1213#endif /* LOG_ENABLED */
1214
1215 }
1216}
1217
1218/**
1219 * Does one iteration of an audio stream.
1220 * This function gives the backend the chance of iterating / altering data and
1221 * does the actual mixing between the guest <-> host mixing buffers.
1222 *
1223 * @returns IPRT status code.
1224 * @param pThis Pointer to driver instance.
1225 * @param pStream Stream to iterate.
1226 */
1227static int drvAudioStreamIterateInternal(PDRVAUDIO pThis, PPDMAUDIOSTREAM pStream)
1228{
1229 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
1230
1231 if (!pThis->pHostDrvAudio)
1232 return VINF_SUCCESS;
1233
1234 if (!pStream)
1235 return VINF_SUCCESS;
1236
1237 /* Is the stream scheduled for re-initialization? Do so now. */
1238 drvAudioStreamMaybeReInit(pThis, pStream);
1239
1240#ifdef LOG_ENABLED
1241 char *pszStreamSts = dbgAudioStreamStatusToStr(pStream->fStatus);
1242 Log3Func(("[%s] fStatus=%s\n", pStream->szName, pszStreamSts));
1243 RTStrFree(pszStreamSts);
1244#endif /* LOG_ENABLED */
1245
1246 /* Not enabled or paused? Skip iteration. */
1247 if ( !(pStream->fStatus & PDMAUDIOSTREAMSTS_FLAGS_ENABLED)
1248 || (pStream->fStatus & PDMAUDIOSTREAMSTS_FLAGS_PAUSED))
1249 {
1250 return VINF_SUCCESS;
1251 }
1252
1253 /* Whether to try closing a pending to close stream. */
1254 bool fTryClosePending = false;
1255
1256 int rc;
1257
1258 do
1259 {
1260 rc = pThis->pHostDrvAudio->pfnStreamIterate(pThis->pHostDrvAudio, pStream->pvBackend);
1261 if (RT_FAILURE(rc))
1262 break;
1263
1264 if (pStream->enmDir == PDMAUDIODIR_OUT)
1265 {
1266 /* No audio frames to transfer from guest to host (anymore)?
1267 * Then try closing this stream if marked so in the next block. */
1268 const uint32_t cFramesLive = AudioMixBufLive(&pStream->Host.MixBuf);
1269 fTryClosePending = cFramesLive == 0;
1270 Log3Func(("[%s] fTryClosePending=%RTbool, cFramesLive=%RU32\n", pStream->szName, fTryClosePending, cFramesLive));
1271 }
1272
1273 /* Has the host stream marked as pending to disable?
1274 * Try disabling the stream then. */
1275 if ( pStream->fStatus & PDMAUDIOSTREAMSTS_FLAGS_PENDING_DISABLE
1276 && fTryClosePending)
1277 {
1278 /* Tell the backend to drain the stream, that is, play the remaining (buffered) data
1279 * on the backend side. */
1280 rc = drvAudioStreamControlInternalBackend(pThis, pStream, PDMAUDIOSTREAMCMD_DRAIN);
1281 if (rc == VERR_NOT_SUPPORTED) /* Not all backends support draining. */
1282 rc = VINF_SUCCESS;
1283
1284 if (RT_SUCCESS(rc))
1285 {
1286 if (pThis->pHostDrvAudio->pfnStreamGetPending) /* Optional to implement. */
1287 {
1288 const uint32_t cxPending = pThis->pHostDrvAudio->pfnStreamGetPending(pThis->pHostDrvAudio, pStream->pvBackend);
1289 Log3Func(("[%s] cxPending=%RU32\n", pStream->szName, cxPending));
1290
1291 /* Only try close pending if no audio data is pending on the backend-side anymore. */
1292 fTryClosePending = cxPending == 0;
1293 }
1294
1295 if (fTryClosePending)
1296 {
1297 LogFunc(("[%s] Closing pending stream\n", pStream->szName));
1298 rc = drvAudioStreamControlInternalBackend(pThis, pStream, PDMAUDIOSTREAMCMD_DISABLE);
1299 if (RT_SUCCESS(rc))
1300 {
1301 pStream->fStatus &= ~(PDMAUDIOSTREAMSTS_FLAGS_ENABLED | PDMAUDIOSTREAMSTS_FLAGS_PENDING_DISABLE);
1302 drvAudioStreamDropInternal(pThis, pStream);
1303 }
1304 else
1305 LogFunc(("[%s] Backend vetoed against closing pending input stream, rc=%Rrc\n", pStream->szName, rc));
1306 }
1307 }
1308 }
1309
1310 } while (0);
1311
1312 /* Update timestamps. */
1313 pStream->tsLastIteratedNs = RTTimeNanoTS();
1314
1315 if (RT_FAILURE(rc))
1316 LogFunc(("[%s] Failed with %Rrc\n", pStream->szName, rc));
1317
1318 return rc;
1319}
1320
1321/**
1322 * Plays an audio host output stream which has been configured for non-interleaved (layout) data.
1323 *
1324 * @return IPRT status code.
1325 * @param pThis Pointer to driver instance.
1326 * @param pStream Stream to play.
1327 * @param cfToPlay Number of audio frames to play.
1328 * @param pcfPlayed Returns number of audio frames played. Optional.
1329 */
1330static int drvAudioStreamPlayNonInterleaved(PDRVAUDIO pThis,
1331 PPDMAUDIOSTREAM pStream, uint32_t cfToPlay, uint32_t *pcfPlayed)
1332{
1333 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
1334 AssertPtrReturn(pStream, VERR_INVALID_POINTER);
1335 /* pcfPlayed is optional. */
1336
1337 if (!cfToPlay)
1338 {
1339 if (pcfPlayed)
1340 *pcfPlayed = 0;
1341 return VINF_SUCCESS;
1342 }
1343
1344 /* Sanity. */
1345 Assert(pStream->enmDir == PDMAUDIODIR_OUT);
1346 Assert(pStream->Host.Cfg.enmLayout == PDMAUDIOSTREAMLAYOUT_NON_INTERLEAVED);
1347
1348 int rc = VINF_SUCCESS;
1349
1350 uint32_t cfPlayedTotal = 0;
1351
1352 uint8_t auBuf[256]; /** @todo Get rid of this here. */
1353
1354 uint32_t cfLeft = cfToPlay;
1355 uint32_t cbChunk = sizeof(auBuf);
1356
1357 while (cfLeft)
1358 {
1359 uint32_t cfRead = 0;
1360 rc = AudioMixBufAcquireReadBlock(&pStream->Host.MixBuf,
1361 auBuf, RT_MIN(cbChunk, AUDIOMIXBUF_F2B(&pStream->Host.MixBuf, cfLeft)),
1362 &cfRead);
1363 if (RT_FAILURE(rc))
1364 break;
1365
1366 uint32_t cbRead = AUDIOMIXBUF_F2B(&pStream->Host.MixBuf, cfRead);
1367 Assert(cbRead <= cbChunk);
1368
1369 uint32_t cfPlayed = 0;
1370 uint32_t cbPlayed = 0;
1371 rc = pThis->pHostDrvAudio->pfnStreamPlay(pThis->pHostDrvAudio, pStream->pvBackend,
1372 auBuf, cbRead, &cbPlayed);
1373 if ( RT_SUCCESS(rc)
1374 && cbPlayed)
1375 {
1376 if (pThis->Out.Cfg.Dbg.fEnabled)
1377 DrvAudioHlpFileWrite(pStream->Out.Dbg.pFilePlayNonInterleaved, auBuf, cbPlayed, 0 /* fFlags */);
1378
1379 if (cbRead != cbPlayed)
1380 LogRel2(("Audio: Host stream '%s' played wrong amount (%RU32 bytes read but played %RU32)\n",
1381 pStream->szName, cbRead, cbPlayed));
1382
1383 cfPlayed = AUDIOMIXBUF_B2F(&pStream->Host.MixBuf, cbPlayed);
1384 cfPlayedTotal += cfPlayed;
1385
1386 Assert(cfLeft >= cfPlayed);
1387 cfLeft -= cfPlayed;
1388 }
1389
1390 AudioMixBufReleaseReadBlock(&pStream->Host.MixBuf, cfPlayed);
1391
1392 if (RT_FAILURE(rc))
1393 break;
1394 }
1395
1396 Log3Func(("[%s] Played %RU32/%RU32 frames, rc=%Rrc\n", pStream->szName, cfPlayedTotal, cfToPlay, rc));
1397
1398 if (RT_SUCCESS(rc))
1399 {
1400 if (pcfPlayed)
1401 *pcfPlayed = cfPlayedTotal;
1402 }
1403
1404 return rc;
1405}
1406
1407/**
1408 * Plays an audio host output stream which has been configured for raw audio (layout) data.
1409 *
1410 * @return IPRT status code.
1411 * @param pThis Pointer to driver instance.
1412 * @param pStream Stream to play.
1413 * @param cfToPlay Number of audio frames to play.
1414 * @param pcfPlayed Returns number of audio frames played. Optional.
1415 */
1416static int drvAudioStreamPlayRaw(PDRVAUDIO pThis,
1417 PPDMAUDIOSTREAM pStream, uint32_t cfToPlay, uint32_t *pcfPlayed)
1418{
1419 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
1420 AssertPtrReturn(pStream, VERR_INVALID_POINTER);
1421 /* pcfPlayed is optional. */
1422
1423 /* Sanity. */
1424 Assert(pStream->enmDir == PDMAUDIODIR_OUT);
1425 Assert(pStream->Host.Cfg.enmLayout == PDMAUDIOSTREAMLAYOUT_RAW);
1426
1427 if (!cfToPlay)
1428 {
1429 if (pcfPlayed)
1430 *pcfPlayed = 0;
1431 return VINF_SUCCESS;
1432 }
1433
1434 int rc = VINF_SUCCESS;
1435
1436 uint32_t cfPlayedTotal = 0;
1437
1438 PDMAUDIOFRAME aFrameBuf[_4K]; /** @todo Get rid of this here. */
1439
1440 uint32_t cfLeft = cfToPlay;
1441 while (cfLeft)
1442 {
1443 uint32_t cfRead = 0;
1444 rc = AudioMixBufPeek(&pStream->Host.MixBuf, cfLeft, aFrameBuf,
1445 RT_MIN(cfLeft, RT_ELEMENTS(aFrameBuf)), &cfRead);
1446
1447 if (RT_SUCCESS(rc))
1448 {
1449 if (cfRead)
1450 {
1451 uint32_t cfPlayed;
1452
1453 /* Note: As the stream layout is RPDMAUDIOSTREAMLAYOUT_RAW, operate on audio frames
1454 * rather on bytes. */
1455 Assert(cfRead <= RT_ELEMENTS(aFrameBuf));
1456 rc = pThis->pHostDrvAudio->pfnStreamPlay(pThis->pHostDrvAudio, pStream->pvBackend,
1457 aFrameBuf, cfRead, &cfPlayed);
1458 if ( RT_FAILURE(rc)
1459 || !cfPlayed)
1460 {
1461 break;
1462 }
1463
1464 cfPlayedTotal += cfPlayed;
1465 Assert(cfPlayedTotal <= cfToPlay);
1466
1467 Assert(cfLeft >= cfRead);
1468 cfLeft -= cfRead;
1469 }
1470 else
1471 {
1472 if (rc == VINF_AUDIO_MORE_DATA_AVAILABLE) /* Do another peeking round if there is more data available. */
1473 continue;
1474
1475 break;
1476 }
1477 }
1478 else if (RT_FAILURE(rc))
1479 break;
1480 }
1481
1482 Log3Func(("[%s] Played %RU32/%RU32 frames, rc=%Rrc\n", pStream->szName, cfPlayedTotal, cfToPlay, rc));
1483
1484 if (RT_SUCCESS(rc))
1485 {
1486 if (pcfPlayed)
1487 *pcfPlayed = cfPlayedTotal;
1488
1489 }
1490
1491 return rc;
1492}
1493
1494/**
1495 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnStreamPlay}
1496 */
1497static DECLCALLBACK(int) drvAudioStreamPlay(PPDMIAUDIOCONNECTOR pInterface,
1498 PPDMAUDIOSTREAM pStream, uint32_t *pcFramesPlayed)
1499{
1500 AssertPtrReturn(pInterface, VERR_INVALID_POINTER);
1501 AssertPtrReturn(pStream, VERR_INVALID_POINTER);
1502 /* pcFramesPlayed is optional. */
1503
1504 PDRVAUDIO pThis = PDMIAUDIOCONNECTOR_2_DRVAUDIO(pInterface);
1505
1506 int rc = RTCritSectEnter(&pThis->CritSect);
1507 if (RT_FAILURE(rc))
1508 return rc;
1509
1510 AssertMsg(pStream->enmDir == PDMAUDIODIR_OUT,
1511 ("Stream '%s' is not an output stream and therefore cannot be played back (direction is 0x%x)\n",
1512 pStream->szName, pStream->enmDir));
1513
1514 uint32_t cfPlayedTotal = 0;
1515
1516 PDMAUDIOSTREAMSTS fStrmStatus = pStream->fStatus;
1517#ifdef LOG_ENABLED
1518 char *pszStreamSts = dbgAudioStreamStatusToStr(fStrmStatus);
1519 Log3Func(("[%s] Start fStatus=%s\n", pStream->szName, pszStreamSts));
1520 RTStrFree(pszStreamSts);
1521#endif /* LOG_ENABLED */
1522
1523 do
1524 {
1525 if (!pThis->pHostDrvAudio)
1526 {
1527 rc = VERR_PDM_NO_ATTACHED_DRIVER;
1528 break;
1529 }
1530
1531 if ( !pThis->Out.fEnabled
1532 || !DrvAudioHlpStreamStatusIsReady(fStrmStatus))
1533 {
1534 rc = VERR_AUDIO_STREAM_NOT_READY;
1535 break;
1536 }
1537
1538 const uint32_t cFramesLive = AudioMixBufLive(&pStream->Host.MixBuf);
1539#ifdef LOG_ENABLED
1540 const uint8_t uLivePercent = (100 * cFramesLive) / AudioMixBufSize(&pStream->Host.MixBuf);
1541#endif
1542 const uint64_t tsDeltaPlayedCapturedNs = RTTimeNanoTS() - pStream->tsLastPlayedCapturedNs;
1543 const uint32_t cfPassedReal = DrvAudioHlpNanoToFrames(tsDeltaPlayedCapturedNs, &pStream->Host.Cfg.Props);
1544
1545 const uint32_t cFramesPeriod = pStream->Host.Cfg.Backend.cFramesPeriod;
1546
1547 Log3Func(("[%s] Last played %RU64ns (%RU64ms), filled with %RU64ms (%RU8%%) total (fThresholdReached=%RTbool)\n",
1548 pStream->szName, tsDeltaPlayedCapturedNs, tsDeltaPlayedCapturedNs / RT_NS_1MS_64,
1549 DrvAudioHlpFramesToMilli(cFramesLive, &pStream->Host.Cfg.Props), uLivePercent, pStream->fThresholdReached));
1550
1551 if ( pStream->fThresholdReached /* Has the treshold been reached (e.g. are we in playing stage) ... */
1552 && cFramesLive == 0) /* ... and we now have no live samples to process? */
1553 {
1554 LogRel2(("Audio: Buffer underrun for stream '%s' occurred (%RU64ms passed)\n",
1555 pStream->szName, DrvAudioHlpFramesToMilli(cfPassedReal, &pStream->Host.Cfg.Props)));
1556
1557 if (pStream->Host.Cfg.Backend.cFramesPreBuffering) /* Any pre-buffering configured? */
1558 {
1559 /* Enter pre-buffering stage again. */
1560 pStream->fThresholdReached = false;
1561 }
1562 }
1563
1564 bool fDoPlay = pStream->fThresholdReached;
1565 bool fJustStarted = false;
1566 if (!fDoPlay)
1567 {
1568 /* Did we reach the backend's playback (pre-buffering) threshold? Can be 0 if no threshold set. */
1569 if (cFramesLive >= pStream->Host.Cfg.Backend.cFramesPreBuffering)
1570 {
1571 LogRel2(("Audio: Stream '%s' buffering complete\n", pStream->szName));
1572 Log3Func(("[%s] Dbg: Buffering complete\n", pStream->szName));
1573 fDoPlay = true;
1574 }
1575 /* Some audio files are shorter than the pre-buffering level (e.g. the "click" Explorer sounds on some Windows guests),
1576 * so make sure that we also play those by checking if the stream already is pending disable mode, even if we didn't
1577 * hit the pre-buffering watermark yet.
1578 *
1579 * To reproduce, use "Windows Navigation Start.wav" on Windows 7 (2824 samples). */
1580 else if ( cFramesLive
1581 && pStream->fStatus & PDMAUDIOSTREAMSTS_FLAGS_PENDING_DISABLE)
1582 {
1583 LogRel2(("Audio: Stream '%s' buffering complete (short sound)\n", pStream->szName));
1584 Log3Func(("[%s] Dbg: Buffering complete (short)\n", pStream->szName));
1585 fDoPlay = true;
1586 }
1587
1588 if (fDoPlay)
1589 {
1590 pStream->fThresholdReached = true;
1591 fJustStarted = true;
1592 LogRel2(("Audio: Stream '%s' started playing\n", pStream->szName));
1593 Log3Func(("[%s] Dbg: started playing\n", pStream->szName));
1594 }
1595 else /* Not yet, so still buffering audio data. */
1596 LogRel2(("Audio: Stream '%s' is buffering (%RU8%% complete)\n",
1597 pStream->szName, (100 * cFramesLive) / pStream->Host.Cfg.Backend.cFramesPreBuffering));
1598 }
1599
1600 if (fDoPlay)
1601 {
1602 uint32_t cfWritable = PDMAUDIOPCMPROPS_B2F(&pStream->Host.Cfg.Props,
1603 pThis->pHostDrvAudio->pfnStreamGetWritable(pThis->pHostDrvAudio, pStream->pvBackend));
1604
1605 uint32_t cfToPlay = 0;
1606 if (fJustStarted)
1607 cfToPlay = RT_MIN(cfWritable, cFramesPeriod);
1608
1609 if (!cfToPlay)
1610 {
1611 /* Did we reach/pass (in real time) the device scheduling slot?
1612 * Play as much as we can write to the backend then. */
1613 if (cfPassedReal >= DrvAudioHlpMilliToFrames(pStream->Guest.Cfg.Device.cMsSchedulingHint, &pStream->Host.Cfg.Props))
1614 cfToPlay = cfWritable;
1615 }
1616
1617 if (cfToPlay > cFramesLive) /* Don't try to play more than available. */
1618 cfToPlay = cFramesLive;
1619#ifdef DEBUG
1620 Log3Func(("[%s] Playing %RU32 frames (%RU64ms), now filled with %RU64ms -- %RU8%%\n",
1621 pStream->szName, cfToPlay, DrvAudioHlpFramesToMilli(cfToPlay, &pStream->Host.Cfg.Props),
1622 DrvAudioHlpFramesToMilli(AudioMixBufUsed(&pStream->Host.MixBuf), &pStream->Host.Cfg.Props),
1623 AudioMixBufUsed(&pStream->Host.MixBuf) * 100 / AudioMixBufSize(&pStream->Host.MixBuf)));
1624#endif
1625 if (cfToPlay)
1626 {
1627 if (pThis->pHostDrvAudio->pfnStreamPlayBegin)
1628 pThis->pHostDrvAudio->pfnStreamPlayBegin(pThis->pHostDrvAudio, pStream->pvBackend);
1629
1630 if (RT_LIKELY(pStream->Host.Cfg.enmLayout == PDMAUDIOSTREAMLAYOUT_NON_INTERLEAVED))
1631 {
1632 rc = drvAudioStreamPlayNonInterleaved(pThis, pStream, cfToPlay, &cfPlayedTotal);
1633 }
1634 else if (pStream->Host.Cfg.enmLayout == PDMAUDIOSTREAMLAYOUT_RAW)
1635 {
1636 rc = drvAudioStreamPlayRaw(pThis, pStream, cfToPlay, &cfPlayedTotal);
1637 }
1638 else
1639 AssertFailedStmt(rc = VERR_NOT_IMPLEMENTED);
1640
1641 if (pThis->pHostDrvAudio->pfnStreamPlayEnd)
1642 pThis->pHostDrvAudio->pfnStreamPlayEnd(pThis->pHostDrvAudio, pStream->pvBackend);
1643
1644 pStream->tsLastPlayedCapturedNs = RTTimeNanoTS();
1645 }
1646
1647 Log3Func(("[%s] Dbg: fJustStarted=%RTbool, cfSched=%RU32 (%RU64ms), cfPassedReal=%RU32 (%RU64ms), "
1648 "cFramesLive=%RU32 (%RU64ms), cFramesPeriod=%RU32 (%RU64ms), cfWritable=%RU32 (%RU64ms), "
1649 "-> cfToPlay=%RU32 (%RU64ms), cfPlayed=%RU32 (%RU64ms)\n",
1650 pStream->szName, fJustStarted,
1651 DrvAudioHlpMilliToFrames(pStream->Guest.Cfg.Device.cMsSchedulingHint, &pStream->Host.Cfg.Props),
1652 pStream->Guest.Cfg.Device.cMsSchedulingHint,
1653 cfPassedReal, DrvAudioHlpFramesToMilli(cfPassedReal, &pStream->Host.Cfg.Props),
1654 cFramesLive, DrvAudioHlpFramesToMilli(cFramesLive, &pStream->Host.Cfg.Props),
1655 cFramesPeriod, DrvAudioHlpFramesToMilli(cFramesPeriod, &pStream->Host.Cfg.Props),
1656 cfWritable, DrvAudioHlpFramesToMilli(cfWritable, &pStream->Host.Cfg.Props),
1657 cfToPlay, DrvAudioHlpFramesToMilli(cfToPlay, &pStream->Host.Cfg.Props),
1658 cfPlayedTotal, DrvAudioHlpFramesToMilli(cfPlayedTotal, &pStream->Host.Cfg.Props)));
1659 }
1660
1661 if (RT_SUCCESS(rc))
1662 {
1663 AudioMixBufFinish(&pStream->Host.MixBuf, cfPlayedTotal);
1664
1665#ifdef VBOX_WITH_STATISTICS
1666 STAM_COUNTER_ADD (&pThis->Stats.TotalFramesOut, cfPlayedTotal);
1667 STAM_PROFILE_ADV_STOP(&pThis->Stats.DelayOut, out);
1668
1669 STAM_COUNTER_ADD (&pStream->Out.Stats.TotalFramesPlayed, cfPlayedTotal);
1670 STAM_COUNTER_INC (&pStream->Out.Stats.TotalTimesPlayed);
1671#endif
1672 }
1673
1674 } while (0);
1675
1676#ifdef LOG_ENABLED
1677 uint32_t cFramesLive = AudioMixBufLive(&pStream->Host.MixBuf);
1678 pszStreamSts = dbgAudioStreamStatusToStr(fStrmStatus);
1679 Log3Func(("[%s] End fStatus=%s, cFramesLive=%RU32, cfPlayedTotal=%RU32, rc=%Rrc\n",
1680 pStream->szName, pszStreamSts, cFramesLive, cfPlayedTotal, rc));
1681 RTStrFree(pszStreamSts);
1682#endif /* LOG_ENABLED */
1683
1684 int rc2 = RTCritSectLeave(&pThis->CritSect);
1685 if (RT_SUCCESS(rc))
1686 rc = rc2;
1687
1688 if (RT_SUCCESS(rc))
1689 {
1690 if (pcFramesPlayed)
1691 *pcFramesPlayed = cfPlayedTotal;
1692 }
1693
1694 if (RT_FAILURE(rc))
1695 LogFlowFunc(("[%s] Failed with %Rrc\n", pStream->szName, rc));
1696
1697 return rc;
1698}
1699
1700/**
1701 * Captures non-interleaved input from a host stream.
1702 *
1703 * @returns IPRT status code.
1704 * @param pThis Driver instance.
1705 * @param pStream Stream to capture from.
1706 * @param pcfCaptured Number of (host) audio frames captured. Optional.
1707 */
1708static int drvAudioStreamCaptureNonInterleaved(PDRVAUDIO pThis, PPDMAUDIOSTREAM pStream, uint32_t *pcfCaptured)
1709{
1710 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
1711 AssertPtrReturn(pStream, VERR_INVALID_POINTER);
1712 /* pcfCaptured is optional. */
1713
1714 /* Sanity. */
1715 Assert(pStream->enmDir == PDMAUDIODIR_IN);
1716 Assert(pStream->Host.Cfg.enmLayout == PDMAUDIOSTREAMLAYOUT_NON_INTERLEAVED);
1717
1718 int rc = VINF_SUCCESS;
1719
1720 uint32_t cfCapturedTotal = 0;
1721
1722 AssertPtr(pThis->pHostDrvAudio->pfnStreamGetReadable);
1723
1724 uint8_t auBuf[_1K]; /** @todo Get rid of this. */
1725 uint32_t cbBuf = sizeof(auBuf);
1726
1727 uint32_t cbReadable = pThis->pHostDrvAudio->pfnStreamGetReadable(pThis->pHostDrvAudio, pStream->pvBackend);
1728 if (!cbReadable)
1729 Log2Func(("[%s] No readable data available\n", pStream->szName));
1730
1731 uint32_t cbFree = AudioMixBufFreeBytes(&pStream->Guest.MixBuf); /* Parent */
1732 if (!cbFree)
1733 Log2Func(("[%s] Buffer full\n", pStream->szName));
1734
1735 if (cbReadable > cbFree) /* More data readable than we can store at the moment? Limit. */
1736 cbReadable = cbFree;
1737
1738 while (cbReadable)
1739 {
1740 uint32_t cbCaptured;
1741 rc = pThis->pHostDrvAudio->pfnStreamCapture(pThis->pHostDrvAudio, pStream->pvBackend,
1742 auBuf, RT_MIN(cbReadable, cbBuf), &cbCaptured);
1743 if (RT_FAILURE(rc))
1744 {
1745 int rc2 = drvAudioStreamControlInternalBackend(pThis, pStream, PDMAUDIOSTREAMCMD_DISABLE);
1746 AssertRC(rc2);
1747
1748 break;
1749 }
1750
1751 Assert(cbCaptured <= cbBuf);
1752 if (cbCaptured > cbBuf) /* Paranoia. */
1753 cbCaptured = cbBuf;
1754
1755 if (!cbCaptured) /* Nothing captured? Take a shortcut. */
1756 break;
1757
1758 /* We use the host side mixing buffer as an intermediate buffer to do some
1759 * (first) processing (if needed), so always write the incoming data at offset 0. */
1760 uint32_t cfHstWritten = 0;
1761 rc = AudioMixBufWriteAt(&pStream->Host.MixBuf, 0 /* offFrames */, auBuf, cbCaptured, &cfHstWritten);
1762 if ( RT_FAILURE(rc)
1763 || !cfHstWritten)
1764 {
1765 AssertMsgFailed(("[%s] Write failed: cbCaptured=%RU32, cfHstWritten=%RU32, rc=%Rrc\n",
1766 pStream->szName, cbCaptured, cfHstWritten, rc));
1767 break;
1768 }
1769
1770 if (pThis->In.Cfg.Dbg.fEnabled)
1771 DrvAudioHlpFileWrite(pStream->In.Dbg.pFileCaptureNonInterleaved, auBuf, cbCaptured, 0 /* fFlags */);
1772
1773 uint32_t cfHstMixed = 0;
1774 if (cfHstWritten)
1775 {
1776 int rc2 = AudioMixBufMixToParentEx(&pStream->Host.MixBuf, 0 /* cSrcOffset */, cfHstWritten /* cSrcFrames */,
1777 &cfHstMixed /* pcSrcMixed */);
1778 Log3Func(("[%s] cbCaptured=%RU32, cfWritten=%RU32, cfMixed=%RU32, rc=%Rrc\n",
1779 pStream->szName, cbCaptured, cfHstWritten, cfHstMixed, rc2));
1780 AssertRC(rc2);
1781 }
1782
1783 Assert(cbReadable >= cbCaptured);
1784 cbReadable -= cbCaptured;
1785 cfCapturedTotal += cfHstMixed;
1786 }
1787
1788 if (RT_SUCCESS(rc))
1789 {
1790 if (cfCapturedTotal)
1791 Log2Func(("[%s] %RU32 frames captured, rc=%Rrc\n", pStream->szName, cfCapturedTotal, rc));
1792 }
1793 else
1794 LogFunc(("[%s] Capturing failed with rc=%Rrc\n", pStream->szName, rc));
1795
1796 if (pcfCaptured)
1797 *pcfCaptured = cfCapturedTotal;
1798
1799 return rc;
1800}
1801
1802/**
1803 * Captures raw input from a host stream.
1804 * Raw input means that the backend directly operates on PDMAUDIOFRAME structs without
1805 * no data layout processing done in between.
1806 *
1807 * Needed for e.g. the VRDP audio backend (in Main).
1808 *
1809 * @returns IPRT status code.
1810 * @param pThis Driver instance.
1811 * @param pStream Stream to capture from.
1812 * @param pcfCaptured Number of (host) audio frames captured. Optional.
1813 */
1814static int drvAudioStreamCaptureRaw(PDRVAUDIO pThis, PPDMAUDIOSTREAM pStream, uint32_t *pcfCaptured)
1815{
1816 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
1817 AssertPtrReturn(pStream, VERR_INVALID_POINTER);
1818 /* pcfCaptured is optional. */
1819
1820 /* Sanity. */
1821 Assert(pStream->enmDir == PDMAUDIODIR_IN);
1822 Assert(pStream->Host.Cfg.enmLayout == PDMAUDIOSTREAMLAYOUT_RAW);
1823
1824 int rc = VINF_SUCCESS;
1825
1826 uint32_t cfCapturedTotal = 0;
1827
1828 AssertPtr(pThis->pHostDrvAudio->pfnStreamGetReadable);
1829
1830 /* Note: Raw means *audio frames*, not bytes! */
1831 uint32_t cfReadable = pThis->pHostDrvAudio->pfnStreamGetReadable(pThis->pHostDrvAudio, pStream->pvBackend);
1832 if (!cfReadable)
1833 Log2Func(("[%s] No readable data available\n", pStream->szName));
1834
1835 const uint32_t cfFree = AudioMixBufFree(&pStream->Guest.MixBuf); /* Parent */
1836 if (!cfFree)
1837 Log2Func(("[%s] Buffer full\n", pStream->szName));
1838
1839 if (cfReadable > cfFree) /* More data readable than we can store at the moment? Limit. */
1840 cfReadable = cfFree;
1841
1842 while (cfReadable)
1843 {
1844 PPDMAUDIOFRAME paFrames;
1845 uint32_t cfWritable;
1846 rc = AudioMixBufPeekMutable(&pStream->Host.MixBuf, cfReadable, &paFrames, &cfWritable);
1847 if ( RT_FAILURE(rc)
1848 || !cfWritable)
1849 {
1850 break;
1851 }
1852
1853 uint32_t cfCaptured;
1854 rc = pThis->pHostDrvAudio->pfnStreamCapture(pThis->pHostDrvAudio, pStream->pvBackend,
1855 paFrames, cfWritable, &cfCaptured);
1856 if (RT_FAILURE(rc))
1857 {
1858 int rc2 = drvAudioStreamControlInternalBackend(pThis, pStream, PDMAUDIOSTREAMCMD_DISABLE);
1859 AssertRC(rc2);
1860
1861 break;
1862 }
1863
1864 Assert(cfCaptured <= cfWritable);
1865 if (cfCaptured > cfWritable) /* Paranoia. */
1866 cfCaptured = cfWritable;
1867
1868 Assert(cfReadable >= cfCaptured);
1869 cfReadable -= cfCaptured;
1870 cfCapturedTotal += cfCaptured;
1871 }
1872
1873 Log2Func(("[%s] %RU32 frames captured, rc=%Rrc\n", pStream->szName, cfCapturedTotal, rc));
1874
1875 if (pcfCaptured)
1876 *pcfCaptured = cfCapturedTotal;
1877
1878 return rc;
1879}
1880
1881/**
1882 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnStreamCapture}
1883 */
1884static DECLCALLBACK(int) drvAudioStreamCapture(PPDMIAUDIOCONNECTOR pInterface,
1885 PPDMAUDIOSTREAM pStream, uint32_t *pcFramesCaptured)
1886{
1887 PDRVAUDIO pThis = PDMIAUDIOCONNECTOR_2_DRVAUDIO(pInterface);
1888
1889 int rc = RTCritSectEnter(&pThis->CritSect);
1890 if (RT_FAILURE(rc))
1891 return rc;
1892
1893 AssertMsg(pStream->enmDir == PDMAUDIODIR_IN,
1894 ("Stream '%s' is not an input stream and therefore cannot be captured (direction is 0x%x)\n",
1895 pStream->szName, pStream->enmDir));
1896
1897 uint32_t cfCaptured = 0;
1898
1899#ifdef LOG_ENABLED
1900 char *pszStreamSts = dbgAudioStreamStatusToStr(pStream->fStatus);
1901 Log3Func(("[%s] fStatus=%s\n", pStream->szName, pszStreamSts));
1902 RTStrFree(pszStreamSts);
1903#endif /* LOG_ENABLED */
1904
1905 do
1906 {
1907 if (!pThis->pHostDrvAudio)
1908 {
1909 rc = VERR_PDM_NO_ATTACHED_DRIVER;
1910 break;
1911 }
1912
1913 if ( !pThis->In.fEnabled
1914 || !DrvAudioHlpStreamStatusCanRead(pStream->fStatus))
1915 {
1916 rc = VERR_AUDIO_STREAM_NOT_READY;
1917 break;
1918 }
1919
1920 /*
1921 * Do the actual capturing.
1922 */
1923
1924 if (pThis->pHostDrvAudio->pfnStreamCaptureBegin)
1925 pThis->pHostDrvAudio->pfnStreamCaptureBegin(pThis->pHostDrvAudio, pStream->pvBackend);
1926
1927 if (RT_LIKELY(pStream->Host.Cfg.enmLayout == PDMAUDIOSTREAMLAYOUT_NON_INTERLEAVED))
1928 {
1929 rc = drvAudioStreamCaptureNonInterleaved(pThis, pStream, &cfCaptured);
1930 }
1931 else if (pStream->Host.Cfg.enmLayout == PDMAUDIOSTREAMLAYOUT_RAW)
1932 {
1933 rc = drvAudioStreamCaptureRaw(pThis, pStream, &cfCaptured);
1934 }
1935 else
1936 AssertFailedStmt(rc = VERR_NOT_IMPLEMENTED);
1937
1938 if (pThis->pHostDrvAudio->pfnStreamCaptureEnd)
1939 pThis->pHostDrvAudio->pfnStreamCaptureEnd(pThis->pHostDrvAudio, pStream->pvBackend);
1940
1941 if (RT_SUCCESS(rc))
1942 {
1943 Log3Func(("[%s] %RU32 frames captured, rc=%Rrc\n", pStream->szName, cfCaptured, rc));
1944
1945#ifdef VBOX_WITH_STATISTICS
1946 STAM_COUNTER_ADD(&pThis->Stats.TotalFramesIn, cfCaptured);
1947
1948 STAM_COUNTER_ADD(&pStream->In.Stats.TotalFramesCaptured, cfCaptured);
1949#endif
1950 }
1951 else if (RT_UNLIKELY(RT_FAILURE(rc)))
1952 {
1953 LogRel(("Audio: Capturing stream '%s' failed with %Rrc\n", pStream->szName, rc));
1954 }
1955
1956 } while (0);
1957
1958 if (pcFramesCaptured)
1959 *pcFramesCaptured = cfCaptured;
1960
1961 int rc2 = RTCritSectLeave(&pThis->CritSect);
1962 if (RT_SUCCESS(rc))
1963 rc = rc2;
1964
1965 if (RT_FAILURE(rc))
1966 LogFlowFuncLeaveRC(rc);
1967
1968 return rc;
1969}
1970
1971#ifdef VBOX_WITH_AUDIO_CALLBACKS
1972/**
1973 * Duplicates an audio callback.
1974 *
1975 * @returns Pointer to duplicated callback, or NULL on failure.
1976 * @param pCB Callback to duplicate.
1977 */
1978static PPDMAUDIOCBRECORD drvAudioCallbackDuplicate(PPDMAUDIOCBRECORD pCB)
1979{
1980 AssertPtrReturn(pCB, NULL);
1981
1982 PPDMAUDIOCBRECORD pCBCopy = (PPDMAUDIOCBRECORD)RTMemDup((void *)pCB, sizeof(PDMAUDIOCBRECORD));
1983 if (!pCBCopy)
1984 return NULL;
1985
1986 if (pCB->pvCtx)
1987 {
1988 pCBCopy->pvCtx = RTMemDup(pCB->pvCtx, pCB->cbCtx);
1989 if (!pCBCopy->pvCtx)
1990 {
1991 RTMemFree(pCBCopy);
1992 return NULL;
1993 }
1994
1995 pCBCopy->cbCtx = pCB->cbCtx;
1996 }
1997
1998 return pCBCopy;
1999}
2000
2001/**
2002 * Destroys a given callback.
2003 *
2004 * @param pCB Callback to destroy.
2005 */
2006static void drvAudioCallbackDestroy(PPDMAUDIOCBRECORD pCB)
2007{
2008 if (!pCB)
2009 return;
2010
2011 RTListNodeRemove(&pCB->Node);
2012 if (pCB->pvCtx)
2013 {
2014 Assert(pCB->cbCtx);
2015 RTMemFree(pCB->pvCtx);
2016 }
2017 RTMemFree(pCB);
2018}
2019
2020/**
2021 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnRegisterCallbacks}
2022 */
2023static DECLCALLBACK(int) drvAudioRegisterCallbacks(PPDMIAUDIOCONNECTOR pInterface,
2024 PPDMAUDIOCBRECORD paCallbacks, size_t cCallbacks)
2025{
2026 AssertPtrReturn(pInterface, VERR_INVALID_POINTER);
2027 AssertPtrReturn(paCallbacks, VERR_INVALID_POINTER);
2028 AssertReturn(cCallbacks, VERR_INVALID_PARAMETER);
2029
2030 PDRVAUDIO pThis = PDMIAUDIOCONNECTOR_2_DRVAUDIO(pInterface);
2031
2032 int rc = RTCritSectEnter(&pThis->CritSect);
2033 if (RT_FAILURE(rc))
2034 return rc;
2035
2036 for (size_t i = 0; i < cCallbacks; i++)
2037 {
2038 PPDMAUDIOCBRECORD pCB = drvAudioCallbackDuplicate(&paCallbacks[i]);
2039 if (!pCB)
2040 {
2041 rc = VERR_NO_MEMORY;
2042 break;
2043 }
2044
2045 switch (pCB->enmSource)
2046 {
2047 case PDMAUDIOCBSOURCE_DEVICE:
2048 {
2049 switch (pCB->Device.enmType)
2050 {
2051 case PDMAUDIODEVICECBTYPE_DATA_INPUT:
2052 RTListAppend(&pThis->In.lstCB, &pCB->Node);
2053 break;
2054
2055 case PDMAUDIODEVICECBTYPE_DATA_OUTPUT:
2056 RTListAppend(&pThis->Out.lstCB, &pCB->Node);
2057 break;
2058
2059 default:
2060 AssertMsgFailed(("Not supported\n"));
2061 break;
2062 }
2063
2064 break;
2065 }
2066
2067 default:
2068 AssertMsgFailed(("Not supported\n"));
2069 break;
2070 }
2071 }
2072
2073 /** @todo Undo allocations on error. */
2074
2075 int rc2 = RTCritSectLeave(&pThis->CritSect);
2076 if (RT_SUCCESS(rc))
2077 rc = rc2;
2078
2079 return rc;
2080}
2081#endif /* VBOX_WITH_AUDIO_CALLBACKS */
2082
2083#ifdef VBOX_WITH_AUDIO_CALLBACKS
2084/**
2085 * @callback_method_impl{FNPDMHOSTAUDIOCALLBACK, Backend callback implementation.}
2086 *
2087 * @par Important:
2088 * No calls back to the backend within this function, as the backend
2089 * might hold any locks / critical sections while executing this
2090 * callback. Will result in some ugly deadlocks (or at least locking
2091 * order violations) then.
2092 */
2093static DECLCALLBACK(int) drvAudioBackendCallback(PPDMDRVINS pDrvIns, PDMAUDIOBACKENDCBTYPE enmType, void *pvUser, size_t cbUser)
2094{
2095 AssertPtrReturn(pDrvIns, VERR_INVALID_POINTER);
2096 RT_NOREF(pvUser, cbUser);
2097 /* pvUser and cbUser are optional. */
2098
2099 /* Get the upper driver (PDMIAUDIOCONNECTOR). */
2100 AssertPtr(pDrvIns->pUpBase);
2101 PPDMIAUDIOCONNECTOR pInterface = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMIAUDIOCONNECTOR);
2102 AssertPtr(pInterface);
2103 PDRVAUDIO pThis = PDMIAUDIOCONNECTOR_2_DRVAUDIO(pInterface);
2104
2105 int rc = RTCritSectEnter(&pThis->CritSect);
2106 AssertRCReturn(rc, rc);
2107
2108 LogFunc(("pThis=%p, enmType=%RU32, pvUser=%p, cbUser=%zu\n", pThis, enmType, pvUser, cbUser));
2109
2110 switch (enmType)
2111 {
2112 case PDMAUDIOBACKENDCBTYPE_DEVICES_CHANGED:
2113 LogRel(("Audio: Device configuration of driver '%s' has changed\n", pThis->szName));
2114 rc = drvAudioScheduleReInitInternal(pThis);
2115 break;
2116
2117 default:
2118 AssertMsgFailed(("Not supported\n"));
2119 break;
2120 }
2121
2122 int rc2 = RTCritSectLeave(&pThis->CritSect);
2123 if (RT_SUCCESS(rc))
2124 rc = rc2;
2125
2126 LogFlowFunc(("Returning %Rrc\n", rc));
2127 return rc;
2128}
2129#endif /* VBOX_WITH_AUDIO_CALLBACKS */
2130
2131#ifdef VBOX_WITH_AUDIO_ENUM
2132/**
2133 * Enumerates all host audio devices.
2134 *
2135 * This functionality might not be implemented by all backends and will return
2136 * VERR_NOT_SUPPORTED if not being supported.
2137 *
2138 * @note Must not hold the driver's critical section!
2139 *
2140 * @returns IPRT status code.
2141 * @param pThis Driver instance to be called.
2142 * @param fLog Whether to print the enumerated device to the release log or not.
2143 * @param pDevEnum Where to store the device enumeration.
2144 */
2145static int drvAudioDevicesEnumerateInternal(PDRVAUDIO pThis, bool fLog, PPDMAUDIODEVICEENUM pDevEnum)
2146{
2147 AssertReturn(RTCritSectIsOwned(&pThis->CritSect) == false, VERR_WRONG_ORDER);
2148
2149 int rc;
2150
2151 /*
2152 * If the backend supports it, do a device enumeration.
2153 */
2154 if (pThis->pHostDrvAudio->pfnGetDevices)
2155 {
2156 PDMAUDIODEVICEENUM DevEnum;
2157 rc = pThis->pHostDrvAudio->pfnGetDevices(pThis->pHostDrvAudio, &DevEnum);
2158 if (RT_SUCCESS(rc))
2159 {
2160 if (fLog)
2161 LogRel(("Audio: Found %RU16 devices for driver '%s'\n", DevEnum.cDevices, pThis->szName));
2162
2163 PPDMAUDIODEVICE pDev;
2164 RTListForEach(&DevEnum.lstDevices, pDev, PDMAUDIODEVICE, Node)
2165 {
2166 if (fLog)
2167 {
2168 char *pszFlags = DrvAudioHlpAudDevFlagsToStrA(pDev->fFlags);
2169
2170 LogRel(("Audio: Device '%s':\n", pDev->szName));
2171 LogRel(("Audio: \tUsage = %s\n", DrvAudioHlpAudDirToStr(pDev->enmUsage)));
2172 LogRel(("Audio: \tFlags = %s\n", pszFlags ? pszFlags : "<NONE>"));
2173 LogRel(("Audio: \tInput channels = %RU8\n", pDev->cMaxInputChannels));
2174 LogRel(("Audio: \tOutput channels = %RU8\n", pDev->cMaxOutputChannels));
2175
2176 if (pszFlags)
2177 RTStrFree(pszFlags);
2178 }
2179 }
2180
2181 if (pDevEnum)
2182 rc = DrvAudioHlpDeviceEnumCopy(pDevEnum, &DevEnum);
2183
2184 DrvAudioHlpDeviceEnumFree(&DevEnum);
2185 }
2186 else
2187 {
2188 if (fLog)
2189 LogRel(("Audio: Device enumeration for driver '%s' failed with %Rrc\n", pThis->szName, rc));
2190 /* Not fatal. */
2191 }
2192 }
2193 else
2194 {
2195 rc = VERR_NOT_SUPPORTED;
2196
2197 if (fLog)
2198 LogRel2(("Audio: Host driver '%s' does not support audio device enumeration, skipping\n", pThis->szName));
2199 }
2200
2201 LogFunc(("Returning %Rrc\n", rc));
2202 return rc;
2203}
2204#endif /* VBOX_WITH_AUDIO_ENUM */
2205
2206/**
2207 * Initializes the host backend and queries its initial configuration.
2208 * If the host backend fails, VERR_AUDIO_BACKEND_INIT_FAILED will be returned.
2209 *
2210 * Note: As this routine is called when attaching to the device LUN in the
2211 * device emulation, we either check for success or VERR_AUDIO_BACKEND_INIT_FAILED.
2212 * Everything else is considered as fatal and must be handled separately in
2213 * the device emulation!
2214 *
2215 * @return IPRT status code.
2216 * @param pThis Driver instance to be called.
2217 * @param pCfgHandle CFGM configuration handle to use for this driver.
2218 */
2219static int drvAudioHostInit(PDRVAUDIO pThis, PCFGMNODE pCfgHandle)
2220{
2221 /* pCfgHandle is optional. */
2222 NOREF(pCfgHandle);
2223 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
2224
2225 LogFlowFuncEnter();
2226
2227 AssertPtr(pThis->pHostDrvAudio);
2228 int rc = pThis->pHostDrvAudio->pfnInit(pThis->pHostDrvAudio);
2229 if (RT_FAILURE(rc))
2230 {
2231 LogRel(("Audio: Initialization of host driver '%s' failed with %Rrc\n", pThis->szName, rc));
2232 return VERR_AUDIO_BACKEND_INIT_FAILED;
2233 }
2234
2235 /*
2236 * Get the backend configuration.
2237 */
2238 rc = pThis->pHostDrvAudio->pfnGetConfig(pThis->pHostDrvAudio, &pThis->BackendCfg);
2239 if (RT_FAILURE(rc))
2240 {
2241 LogRel(("Audio: Getting configuration for driver '%s' failed with %Rrc\n", pThis->szName, rc));
2242 return VERR_AUDIO_BACKEND_INIT_FAILED;
2243 }
2244
2245 pThis->In.cStreamsFree = pThis->BackendCfg.cMaxStreamsIn;
2246 pThis->Out.cStreamsFree = pThis->BackendCfg.cMaxStreamsOut;
2247
2248 LogFlowFunc(("cStreamsFreeIn=%RU8, cStreamsFreeOut=%RU8\n", pThis->In.cStreamsFree, pThis->Out.cStreamsFree));
2249
2250 LogRel2(("Audio: Host driver '%s' supports %RU32 input streams and %RU32 output streams at once\n",
2251 pThis->szName,
2252 /* Clamp for logging. Unlimited streams are defined by UINT32_MAX. */
2253 RT_MIN(64, pThis->In.cStreamsFree), RT_MIN(64, pThis->Out.cStreamsFree)));
2254
2255#ifdef VBOX_WITH_AUDIO_ENUM
2256 int rc2 = drvAudioDevicesEnumerateInternal(pThis, true /* fLog */, NULL /* pDevEnum */);
2257 if (rc2 != VERR_NOT_SUPPORTED) /* Some backends don't implement device enumeration. */
2258 AssertRC(rc2);
2259
2260 RT_NOREF(rc2);
2261 /* Ignore rc. */
2262#endif
2263
2264#ifdef VBOX_WITH_AUDIO_CALLBACKS
2265 /*
2266 * If the backend supports it, offer a callback to this connector.
2267 */
2268 if (pThis->pHostDrvAudio->pfnSetCallback)
2269 {
2270 rc2 = pThis->pHostDrvAudio->pfnSetCallback(pThis->pHostDrvAudio, drvAudioBackendCallback);
2271 if (RT_FAILURE(rc2))
2272 LogRel(("Audio: Error registering callback for host driver '%s', rc=%Rrc\n", pThis->szName, rc2));
2273 /* Not fatal. */
2274 }
2275#endif
2276
2277 LogFlowFuncLeave();
2278 return VINF_SUCCESS;
2279}
2280
2281/**
2282 * Handles state changes for all audio streams.
2283 *
2284 * @param pDrvIns Pointer to driver instance.
2285 * @param enmCmd Stream command to set for all streams.
2286 */
2287static void drvAudioStateHandler(PPDMDRVINS pDrvIns, PDMAUDIOSTREAMCMD enmCmd)
2288{
2289 PDMDRV_CHECK_VERSIONS_RETURN_VOID(pDrvIns);
2290 PDRVAUDIO pThis = PDMINS_2_DATA(pDrvIns, PDRVAUDIO);
2291
2292 LogFlowFunc(("enmCmd=%s\n", DrvAudioHlpStreamCmdToStr(enmCmd)));
2293
2294 int rc2 = RTCritSectEnter(&pThis->CritSect);
2295 AssertRC(rc2);
2296
2297 if (pThis->pHostDrvAudio)
2298 {
2299 PPDMAUDIOSTREAM pStream;
2300 RTListForEach(&pThis->lstStreams, pStream, PDMAUDIOSTREAM, Node)
2301 drvAudioStreamControlInternal(pThis, pStream, enmCmd);
2302 }
2303
2304 rc2 = RTCritSectLeave(&pThis->CritSect);
2305 AssertRC(rc2);
2306}
2307
2308/**
2309 * Retrieves an audio configuration from the specified CFGM node.
2310 *
2311 * @return VBox status code.
2312 * @param pThis Driver instance to be called.
2313 * @param pCfg Where to store the retrieved audio configuration to.
2314 * @param pNode Where to get the audio configuration from.
2315 */
2316static int drvAudioGetCfgFromCFGM(PDRVAUDIO pThis, PDRVAUDIOCFG pCfg, PCFGMNODE pNode)
2317{
2318 RT_NOREF(pThis);
2319
2320 /* Debug stuff. */
2321 CFGMR3QueryBoolDef(pNode, "DebugEnabled", &pCfg->Dbg.fEnabled, false);
2322 int rc2 = CFGMR3QueryString(pNode, "DebugPathOut", pCfg->Dbg.szPathOut, sizeof(pCfg->Dbg.szPathOut));
2323 if ( RT_FAILURE(rc2)
2324 || !strlen(pCfg->Dbg.szPathOut))
2325 {
2326 RTStrPrintf(pCfg->Dbg.szPathOut, sizeof(pCfg->Dbg.szPathOut), VBOX_AUDIO_DEBUG_DUMP_PCM_DATA_PATH);
2327 }
2328
2329 if (pCfg->Dbg.fEnabled)
2330 LogRel(("Audio: Debugging for driver '%s' enabled (audio data written to '%s')\n", pThis->szName, pCfg->Dbg.szPathOut));
2331
2332 /* Buffering stuff. */
2333 CFGMR3QueryU32Def(pNode, "PeriodSizeMs", &pCfg->uPeriodSizeMs, 0);
2334 CFGMR3QueryU32Def(pNode, "BufferSizeMs", &pCfg->uBufferSizeMs, 0);
2335 CFGMR3QueryU32Def(pNode, "PreBufferSizeMs", &pCfg->uPreBufSizeMs, UINT32_MAX /* No custom value set */);
2336
2337 LogFunc(("pCfg=%p, uPeriodSizeMs=%RU32, uBufferSizeMs=%RU32, uPreBufSizeMs=%RU32\n",
2338 pCfg, pCfg->uPeriodSizeMs, pCfg->uBufferSizeMs, pCfg->uPreBufSizeMs));
2339
2340 return VINF_SUCCESS;
2341}
2342
2343/**
2344 * Intializes an audio driver instance.
2345 *
2346 * @returns IPRT status code.
2347 * @param pDrvIns Pointer to driver instance.
2348 * @param pCfgHandle CFGM handle to use for configuration.
2349 */
2350static int drvAudioInit(PPDMDRVINS pDrvIns, PCFGMNODE pCfgHandle)
2351{
2352 AssertPtrReturn(pCfgHandle, VERR_INVALID_POINTER);
2353 AssertPtrReturn(pDrvIns, VERR_INVALID_POINTER);
2354
2355 PDRVAUDIO pThis = PDMINS_2_DATA(pDrvIns, PDRVAUDIO);
2356
2357 int rc = RTCritSectInit(&pThis->CritSect);
2358 AssertRCReturn(rc, rc);
2359
2360 /*
2361 * Configure driver from CFGM.
2362 */
2363#ifdef DEBUG
2364 CFGMR3Dump(pCfgHandle);
2365#endif
2366
2367 pThis->fTerminate = false;
2368 pThis->pCFGMNode = pCfgHandle;
2369
2370 int rc2 = CFGMR3QueryString(pThis->pCFGMNode, "DriverName", pThis->szName, sizeof(pThis->szName));
2371 if (RT_FAILURE(rc2))
2372 RTStrPrintf(pThis->szName, sizeof(pThis->szName), "Untitled");
2373
2374 /* By default we don't enable anything if wrongly / not set-up. */
2375 CFGMR3QueryBoolDef(pThis->pCFGMNode, "InputEnabled", &pThis->In.fEnabled, false);
2376 CFGMR3QueryBoolDef(pThis->pCFGMNode, "OutputEnabled", &pThis->Out.fEnabled, false);
2377
2378 LogRel2(("Audio: Verbose logging for driver '%s' enabled\n", pThis->szName));
2379
2380 LogRel2(("Audio: Initial status for driver '%s' is: input is %s, output is %s\n",
2381 pThis->szName, pThis->In.fEnabled ? "enabled" : "disabled", pThis->Out.fEnabled ? "enabled" : "disabled"));
2382
2383 /*
2384 * Load configurations.
2385 */
2386 rc = drvAudioGetCfgFromCFGM(pThis, &pThis->In.Cfg, pThis->pCFGMNode);
2387 if (RT_SUCCESS(rc))
2388 rc = drvAudioGetCfgFromCFGM(pThis, &pThis->Out.Cfg, pThis->pCFGMNode);
2389
2390 LogFunc(("[%s] rc=%Rrc\n", pThis->szName, rc));
2391 return rc;
2392}
2393
2394/**
2395 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnStreamRead}
2396 */
2397static DECLCALLBACK(int) drvAudioStreamRead(PPDMIAUDIOCONNECTOR pInterface, PPDMAUDIOSTREAM pStream,
2398 void *pvBuf, uint32_t cbBuf, uint32_t *pcbRead)
2399{
2400 PDRVAUDIO pThis = PDMIAUDIOCONNECTOR_2_DRVAUDIO(pInterface);
2401 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
2402
2403 AssertPtrReturn(pStream, VERR_INVALID_POINTER);
2404 AssertPtrReturn(pvBuf, VERR_INVALID_POINTER);
2405 AssertReturn(cbBuf, VERR_INVALID_PARAMETER);
2406 /* pcbRead is optional. */
2407
2408 AssertMsg(pStream->enmDir == PDMAUDIODIR_IN,
2409 ("Stream '%s' is not an input stream and therefore cannot be read from (direction is 0x%x)\n",
2410 pStream->szName, pStream->enmDir));
2411
2412 uint32_t cbReadTotal = 0;
2413
2414 int rc = RTCritSectEnter(&pThis->CritSect);
2415 if (RT_FAILURE(rc))
2416 return rc;
2417
2418 do
2419 {
2420 uint32_t cfReadTotal = 0;
2421
2422 const uint32_t cfBuf = AUDIOMIXBUF_B2F(&pStream->Guest.MixBuf, cbBuf);
2423
2424 if (pThis->In.fEnabled) /* Input for this audio driver enabled? See #9822. */
2425 {
2426 if (!DrvAudioHlpStreamStatusCanRead(pStream->fStatus))
2427 {
2428 rc = VERR_AUDIO_STREAM_NOT_READY;
2429 break;
2430 }
2431
2432 /*
2433 * Read from the parent buffer (that is, the guest buffer) which
2434 * should have the audio data in the format the guest needs.
2435 */
2436 uint32_t cfToRead = RT_MIN(cfBuf, AudioMixBufLive(&pStream->Guest.MixBuf));
2437 while (cfToRead)
2438 {
2439 uint32_t cfRead;
2440 rc = AudioMixBufAcquireReadBlock(&pStream->Guest.MixBuf,
2441 (uint8_t *)pvBuf + AUDIOMIXBUF_F2B(&pStream->Guest.MixBuf, cfReadTotal),
2442 AUDIOMIXBUF_F2B(&pStream->Guest.MixBuf, cfToRead), &cfRead);
2443 if (RT_FAILURE(rc))
2444 break;
2445
2446#ifdef VBOX_WITH_STATISTICS
2447 const uint32_t cbRead = AUDIOMIXBUF_F2B(&pStream->Guest.MixBuf, cfRead);
2448
2449 STAM_COUNTER_ADD(&pThis->Stats.TotalBytesRead, cbRead);
2450
2451 STAM_COUNTER_ADD(&pStream->In.Stats.TotalFramesRead, cfRead);
2452 STAM_COUNTER_INC(&pStream->In.Stats.TotalTimesRead);
2453#endif
2454 Assert(cfToRead >= cfRead);
2455 cfToRead -= cfRead;
2456
2457 cfReadTotal += cfRead;
2458
2459 AudioMixBufReleaseReadBlock(&pStream->Guest.MixBuf, cfRead);
2460 }
2461
2462 if (cfReadTotal)
2463 {
2464 if (pThis->In.Cfg.Dbg.fEnabled)
2465 DrvAudioHlpFileWrite(pStream->In.Dbg.pFileStreamRead,
2466 pvBuf, AUDIOMIXBUF_F2B(&pStream->Guest.MixBuf, cfReadTotal), 0 /* fFlags */);
2467
2468 AudioMixBufFinish(&pStream->Guest.MixBuf, cfReadTotal);
2469 }
2470 }
2471
2472 /* If we were not able to read as much data as requested, fill up the returned
2473 * data with silence.
2474 *
2475 * This is needed to keep the device emulation DMA transfers up and running at a constant rate. */
2476 if (cfReadTotal < cfBuf)
2477 {
2478 Log3Func(("[%s] Filling in silence (%RU64ms / %RU64ms)\n", pStream->szName,
2479 DrvAudioHlpFramesToMilli(cfBuf - cfReadTotal, &pStream->Guest.Cfg.Props),
2480 DrvAudioHlpFramesToMilli(cfBuf, &pStream->Guest.Cfg.Props)));
2481
2482 DrvAudioHlpClearBuf(&pStream->Guest.Cfg.Props,
2483 (uint8_t *)pvBuf + AUDIOMIXBUF_F2B(&pStream->Guest.MixBuf, cfReadTotal),
2484 AUDIOMIXBUF_F2B(&pStream->Guest.MixBuf, cfBuf - cfReadTotal),
2485 cfBuf - cfReadTotal);
2486
2487 cfReadTotal = cfBuf;
2488 }
2489
2490 cbReadTotal = AUDIOMIXBUF_F2B(&pStream->Guest.MixBuf, cfReadTotal);
2491
2492 pStream->tsLastReadWrittenNs = RTTimeNanoTS();
2493
2494 Log3Func(("[%s] fEnabled=%RTbool, cbReadTotal=%RU32, rc=%Rrc\n", pStream->szName, pThis->In.fEnabled, cbReadTotal, rc));
2495
2496 } while (0);
2497
2498
2499 int rc2 = RTCritSectLeave(&pThis->CritSect);
2500 if (RT_SUCCESS(rc))
2501 rc = rc2;
2502
2503 if (RT_SUCCESS(rc))
2504 {
2505 if (pcbRead)
2506 *pcbRead = cbReadTotal;
2507 }
2508
2509 return rc;
2510}
2511
2512/**
2513 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnStreamCreate}
2514 */
2515static DECLCALLBACK(int) drvAudioStreamCreate(PPDMIAUDIOCONNECTOR pInterface,
2516 PPDMAUDIOSTREAMCFG pCfgHost, PPDMAUDIOSTREAMCFG pCfgGuest,
2517 PPDMAUDIOSTREAM *ppStream)
2518{
2519 AssertPtrReturn(pInterface, VERR_INVALID_POINTER);
2520 AssertPtrReturn(pCfgHost, VERR_INVALID_POINTER);
2521 AssertPtrReturn(pCfgGuest, VERR_INVALID_POINTER);
2522 AssertPtrReturn(ppStream, VERR_INVALID_POINTER);
2523
2524 PDRVAUDIO pThis = PDMIAUDIOCONNECTOR_2_DRVAUDIO(pInterface);
2525
2526 int rc = RTCritSectEnter(&pThis->CritSect);
2527 if (RT_FAILURE(rc))
2528 return rc;
2529
2530 LogFlowFunc(("Host=%s, Guest=%s\n", pCfgHost->szName, pCfgGuest->szName));
2531#ifdef DEBUG
2532 DrvAudioHlpStreamCfgPrint(pCfgHost);
2533 DrvAudioHlpStreamCfgPrint(pCfgGuest);
2534#endif
2535
2536 PPDMAUDIOSTREAM pStream = NULL;
2537
2538#define RC_BREAK(x) { rc = x; break; }
2539
2540 do
2541 {
2542 if ( !DrvAudioHlpStreamCfgIsValid(pCfgHost)
2543 || !DrvAudioHlpStreamCfgIsValid(pCfgGuest))
2544 {
2545 RC_BREAK(VERR_INVALID_PARAMETER);
2546 }
2547
2548 /* Make sure that both configurations actually intend the same thing. */
2549 if (pCfgHost->enmDir != pCfgGuest->enmDir)
2550 {
2551 AssertMsgFailed(("Stream configuration directions do not match\n"));
2552 RC_BREAK(VERR_INVALID_PARAMETER);
2553 }
2554
2555 /* Note: cbHstStrm will contain the size of the data the backend needs to operate on. */
2556 size_t cbHstStrm;
2557 if (pCfgHost->enmDir == PDMAUDIODIR_IN)
2558 {
2559 if (!pThis->In.cStreamsFree)
2560 {
2561 LogFlowFunc(("Maximum number of host input streams reached\n"));
2562 RC_BREAK(VERR_AUDIO_NO_FREE_INPUT_STREAMS);
2563 }
2564
2565 cbHstStrm = pThis->BackendCfg.cbStreamIn;
2566 }
2567 else /* Out */
2568 {
2569 if (!pThis->Out.cStreamsFree)
2570 {
2571 LogFlowFunc(("Maximum number of host output streams reached\n"));
2572 RC_BREAK(VERR_AUDIO_NO_FREE_OUTPUT_STREAMS);
2573 }
2574
2575 cbHstStrm = pThis->BackendCfg.cbStreamOut;
2576 }
2577
2578 /*
2579 * Allocate and initialize common state.
2580 */
2581
2582 pStream = (PPDMAUDIOSTREAM)RTMemAllocZ(sizeof(PDMAUDIOSTREAM));
2583 AssertPtrBreakStmt(pStream, rc = VERR_NO_MEMORY);
2584
2585 /* Retrieve host driver name for easier identification. */
2586 AssertPtr(pThis->pHostDrvAudio);
2587 PPDMDRVINS pDrvAudioInst = PDMIBASE_2_PDMDRV(pThis->pDrvIns->pDownBase);
2588 AssertPtr(pDrvAudioInst);
2589 AssertPtr(pDrvAudioInst->pReg);
2590
2591 Assert(pDrvAudioInst->pReg->szName[0] != '\0');
2592 RTStrPrintf(pStream->szName, RT_ELEMENTS(pStream->szName), "[%s] %s",
2593 pDrvAudioInst->pReg->szName[0] != '\0' ? pDrvAudioInst->pReg->szName : "Untitled",
2594 pCfgHost->szName[0] != '\0' ? pCfgHost->szName : "<Untitled>");
2595
2596 pStream->enmDir = pCfgHost->enmDir;
2597
2598 /*
2599 * Allocate and init backend-specific data.
2600 */
2601
2602 if (cbHstStrm) /* High unlikely that backends do not have an own space for data, but better check. */
2603 {
2604 pStream->pvBackend = RTMemAllocZ(cbHstStrm);
2605 AssertPtrBreakStmt(pStream->pvBackend, rc = VERR_NO_MEMORY);
2606
2607 pStream->cbBackend = cbHstStrm;
2608 }
2609
2610 /*
2611 * Try to init the rest.
2612 */
2613
2614 rc = drvAudioStreamInitInternal(pThis, pStream, pCfgHost, pCfgGuest);
2615 if (RT_FAILURE(rc))
2616 break;
2617
2618 } while (0);
2619
2620#undef RC_BREAK
2621
2622 if (RT_FAILURE(rc))
2623 {
2624 Log(("drvAudioStreamCreate: failed - %Rrc\n", rc));
2625 if (pStream)
2626 {
2627 int rc2 = drvAudioStreamUninitInternal(pThis, pStream);
2628 if (RT_SUCCESS(rc2))
2629 {
2630 drvAudioStreamFree(pStream);
2631 pStream = NULL;
2632 }
2633 }
2634 }
2635 else
2636 {
2637 /* Append the stream to our stream list. */
2638 RTListAppend(&pThis->lstStreams, &pStream->Node);
2639
2640 /* Set initial reference counts. */
2641 pStream->cRefs = 1;
2642
2643 char szFile[RTPATH_MAX];
2644 if (pCfgHost->enmDir == PDMAUDIODIR_IN)
2645 {
2646 if (pThis->In.Cfg.Dbg.fEnabled)
2647 {
2648 int rc2 = DrvAudioHlpFileNameGet(szFile, sizeof(szFile), pThis->In.Cfg.Dbg.szPathOut, "CaptureNonInterleaved",
2649 pThis->pDrvIns->iInstance, PDMAUDIOFILETYPE_WAV, PDMAUDIOFILENAME_FLAGS_NONE);
2650 if (RT_SUCCESS(rc2))
2651 {
2652 rc2 = DrvAudioHlpFileCreate(PDMAUDIOFILETYPE_WAV, szFile, PDMAUDIOFILE_FLAGS_NONE,
2653 &pStream->In.Dbg.pFileCaptureNonInterleaved);
2654 if (RT_SUCCESS(rc2))
2655 rc2 = DrvAudioHlpFileOpen(pStream->In.Dbg.pFileCaptureNonInterleaved, PDMAUDIOFILE_DEFAULT_OPEN_FLAGS,
2656 &pStream->Host.Cfg.Props);
2657 }
2658
2659 if (RT_SUCCESS(rc2))
2660 {
2661 rc2 = DrvAudioHlpFileNameGet(szFile, sizeof(szFile), pThis->In.Cfg.Dbg.szPathOut, "StreamRead",
2662 pThis->pDrvIns->iInstance, PDMAUDIOFILETYPE_WAV, PDMAUDIOFILENAME_FLAGS_NONE);
2663 if (RT_SUCCESS(rc2))
2664 {
2665 rc2 = DrvAudioHlpFileCreate(PDMAUDIOFILETYPE_WAV, szFile, PDMAUDIOFILE_FLAGS_NONE,
2666 &pStream->In.Dbg.pFileStreamRead);
2667 if (RT_SUCCESS(rc2))
2668 rc2 = DrvAudioHlpFileOpen(pStream->In.Dbg.pFileStreamRead, PDMAUDIOFILE_DEFAULT_OPEN_FLAGS,
2669 &pStream->Host.Cfg.Props);
2670 }
2671 }
2672 }
2673
2674 if (pThis->In.cStreamsFree)
2675 pThis->In.cStreamsFree--;
2676 }
2677 else /* Out */
2678 {
2679 if (pThis->Out.Cfg.Dbg.fEnabled)
2680 {
2681 int rc2 = DrvAudioHlpFileNameGet(szFile, sizeof(szFile), pThis->Out.Cfg.Dbg.szPathOut, "PlayNonInterleaved",
2682 pThis->pDrvIns->iInstance, PDMAUDIOFILETYPE_WAV, PDMAUDIOFILENAME_FLAGS_NONE);
2683 if (RT_SUCCESS(rc2))
2684 {
2685 rc2 = DrvAudioHlpFileCreate(PDMAUDIOFILETYPE_WAV, szFile, PDMAUDIOFILE_FLAGS_NONE,
2686 &pStream->Out.Dbg.pFilePlayNonInterleaved);
2687 if (RT_SUCCESS(rc2))
2688 rc = DrvAudioHlpFileOpen(pStream->Out.Dbg.pFilePlayNonInterleaved, PDMAUDIOFILE_DEFAULT_OPEN_FLAGS,
2689 &pStream->Host.Cfg.Props);
2690 }
2691
2692 if (RT_SUCCESS(rc2))
2693 {
2694 rc2 = DrvAudioHlpFileNameGet(szFile, sizeof(szFile), pThis->Out.Cfg.Dbg.szPathOut, "StreamWrite",
2695 pThis->pDrvIns->iInstance, PDMAUDIOFILETYPE_WAV, PDMAUDIOFILENAME_FLAGS_NONE);
2696 if (RT_SUCCESS(rc2))
2697 {
2698 rc2 = DrvAudioHlpFileCreate(PDMAUDIOFILETYPE_WAV, szFile, PDMAUDIOFILE_FLAGS_NONE,
2699 &pStream->Out.Dbg.pFileStreamWrite);
2700 if (RT_SUCCESS(rc2))
2701 rc2 = DrvAudioHlpFileOpen(pStream->Out.Dbg.pFileStreamWrite, PDMAUDIOFILE_DEFAULT_OPEN_FLAGS,
2702 &pStream->Host.Cfg.Props);
2703 }
2704 }
2705 }
2706
2707 if (pThis->Out.cStreamsFree)
2708 pThis->Out.cStreamsFree--;
2709 }
2710
2711#ifdef VBOX_WITH_STATISTICS
2712 STAM_COUNTER_ADD(&pThis->Stats.TotalStreamsCreated, 1);
2713#endif
2714 *ppStream = pStream;
2715 }
2716
2717 int rc2 = RTCritSectLeave(&pThis->CritSect);
2718 if (RT_SUCCESS(rc))
2719 rc = rc2;
2720
2721 LogFlowFuncLeaveRC(rc);
2722 return rc;
2723}
2724
2725/**
2726 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnEnable}
2727 */
2728static DECLCALLBACK(int) drvAudioEnable(PPDMIAUDIOCONNECTOR pInterface, PDMAUDIODIR enmDir, bool fEnable)
2729{
2730 AssertPtrReturn(pInterface, VERR_INVALID_POINTER);
2731
2732 PDRVAUDIO pThis = PDMIAUDIOCONNECTOR_2_DRVAUDIO(pInterface);
2733
2734 int rc = RTCritSectEnter(&pThis->CritSect);
2735 if (RT_FAILURE(rc))
2736 return rc;
2737
2738 bool *pfEnabled;
2739 if (enmDir == PDMAUDIODIR_IN)
2740 pfEnabled = &pThis->In.fEnabled;
2741 else if (enmDir == PDMAUDIODIR_OUT)
2742 pfEnabled = &pThis->Out.fEnabled;
2743 else
2744 AssertFailedReturn(VERR_INVALID_PARAMETER);
2745
2746 if (fEnable != *pfEnabled)
2747 {
2748 LogRel(("Audio: %s %s for driver '%s'\n",
2749 fEnable ? "Enabling" : "Disabling", enmDir == PDMAUDIODIR_IN ? "input" : "output", pThis->szName));
2750
2751 /* Update the status first, as this will be checked for in drvAudioStreamControlInternalBackend() below. */
2752 *pfEnabled = fEnable;
2753
2754 PPDMAUDIOSTREAM pStream;
2755 RTListForEach(&pThis->lstStreams, pStream, PDMAUDIOSTREAM, Node)
2756 {
2757 if (pStream->enmDir != enmDir) /* Skip unwanted streams. */
2758 continue;
2759
2760 /* Note: Only enable / disable the backend, do *not* change the stream's internal status.
2761 * Callers (device emulation, mixer, ...) from outside will not see any status or behavior change,
2762 * to not confuse the rest of the state machine.
2763 *
2764 * When disabling:
2765 * - playing back audo data would go to /dev/null
2766 * - recording audio data would return silence instead
2767 *
2768 * See #9882.
2769 */
2770 int rc2 = drvAudioStreamControlInternalBackend(pThis, pStream,
2771 fEnable ? PDMAUDIOSTREAMCMD_ENABLE : PDMAUDIOSTREAMCMD_DISABLE);
2772 if (RT_FAILURE(rc2))
2773 {
2774 if (rc2 == VERR_AUDIO_STREAM_NOT_READY)
2775 {
2776 LogRel(("Audio: Stream '%s' not available\n", pStream->szName));
2777 }
2778 else
2779 LogRel(("Audio: Failed to %s %s stream '%s', rc=%Rrc\n",
2780 fEnable ? "enable" : "disable", enmDir == PDMAUDIODIR_IN ? "input" : "output", pStream->szName, rc2));
2781 }
2782
2783 if (RT_SUCCESS(rc))
2784 rc = rc2;
2785
2786 /* Keep going. */
2787 }
2788 }
2789
2790 int rc3 = RTCritSectLeave(&pThis->CritSect);
2791 if (RT_SUCCESS(rc))
2792 rc = rc3;
2793
2794 LogFlowFuncLeaveRC(rc);
2795 return rc;
2796}
2797
2798/**
2799 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnIsEnabled}
2800 */
2801static DECLCALLBACK(bool) drvAudioIsEnabled(PPDMIAUDIOCONNECTOR pInterface, PDMAUDIODIR enmDir)
2802{
2803 AssertPtrReturn(pInterface, false);
2804
2805 PDRVAUDIO pThis = PDMIAUDIOCONNECTOR_2_DRVAUDIO(pInterface);
2806
2807 int rc2 = RTCritSectEnter(&pThis->CritSect);
2808 if (RT_FAILURE(rc2))
2809 return false;
2810
2811 bool *pfEnabled;
2812 if (enmDir == PDMAUDIODIR_IN)
2813 pfEnabled = &pThis->In.fEnabled;
2814 else if (enmDir == PDMAUDIODIR_OUT)
2815 pfEnabled = &pThis->Out.fEnabled;
2816 else
2817 AssertFailedReturn(false);
2818
2819 const bool fIsEnabled = *pfEnabled;
2820
2821 rc2 = RTCritSectLeave(&pThis->CritSect);
2822 AssertRC(rc2);
2823
2824 return fIsEnabled;
2825}
2826
2827/**
2828 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnGetConfig}
2829 */
2830static DECLCALLBACK(int) drvAudioGetConfig(PPDMIAUDIOCONNECTOR pInterface, PPDMAUDIOBACKENDCFG pCfg)
2831{
2832 AssertPtrReturn(pInterface, VERR_INVALID_POINTER);
2833 AssertPtrReturn(pCfg, VERR_INVALID_POINTER);
2834
2835 PDRVAUDIO pThis = PDMIAUDIOCONNECTOR_2_DRVAUDIO(pInterface);
2836
2837 int rc = RTCritSectEnter(&pThis->CritSect);
2838 if (RT_FAILURE(rc))
2839 return rc;
2840
2841 if (pThis->pHostDrvAudio)
2842 {
2843 if (pThis->pHostDrvAudio->pfnGetConfig)
2844 rc = pThis->pHostDrvAudio->pfnGetConfig(pThis->pHostDrvAudio, pCfg);
2845 else
2846 rc = VERR_NOT_SUPPORTED;
2847 }
2848 else
2849 rc = VERR_PDM_NO_ATTACHED_DRIVER;
2850
2851 int rc2 = RTCritSectLeave(&pThis->CritSect);
2852 if (RT_SUCCESS(rc))
2853 rc = rc2;
2854
2855 LogFlowFuncLeaveRC(rc);
2856 return rc;
2857}
2858
2859/**
2860 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnGetStatus}
2861 */
2862static DECLCALLBACK(PDMAUDIOBACKENDSTS) drvAudioGetStatus(PPDMIAUDIOCONNECTOR pInterface, PDMAUDIODIR enmDir)
2863{
2864 AssertPtrReturn(pInterface, PDMAUDIOBACKENDSTS_UNKNOWN);
2865
2866 PDRVAUDIO pThis = PDMIAUDIOCONNECTOR_2_DRVAUDIO(pInterface);
2867
2868 PDMAUDIOBACKENDSTS backendSts = PDMAUDIOBACKENDSTS_UNKNOWN;
2869
2870 int rc = RTCritSectEnter(&pThis->CritSect);
2871 if (RT_SUCCESS(rc))
2872 {
2873 if (pThis->pHostDrvAudio)
2874 {
2875 if (pThis->pHostDrvAudio->pfnGetStatus)
2876 backendSts = pThis->pHostDrvAudio->pfnGetStatus(pThis->pHostDrvAudio, enmDir);
2877 }
2878 else
2879 backendSts = PDMAUDIOBACKENDSTS_NOT_ATTACHED;
2880
2881 int rc2 = RTCritSectLeave(&pThis->CritSect);
2882 if (RT_SUCCESS(rc))
2883 rc = rc2;
2884 }
2885
2886 LogFlowFuncLeaveRC(rc);
2887 return backendSts;
2888}
2889
2890/**
2891 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnStreamGetReadable}
2892 */
2893static DECLCALLBACK(uint32_t) drvAudioStreamGetReadable(PPDMIAUDIOCONNECTOR pInterface, PPDMAUDIOSTREAM pStream)
2894{
2895 AssertPtrReturn(pInterface, 0);
2896 AssertPtrReturn(pStream, 0);
2897
2898 PDRVAUDIO pThis = PDMIAUDIOCONNECTOR_2_DRVAUDIO(pInterface);
2899
2900 int rc2 = RTCritSectEnter(&pThis->CritSect);
2901 AssertRC(rc2);
2902
2903 AssertMsg(pStream->enmDir == PDMAUDIODIR_IN, ("Can't read from a non-input stream\n"));
2904
2905 uint32_t cbReadable = 0;
2906
2907 /* All input streams for this driver disabled? See #9882. */
2908 const bool fDisabled = !pThis->In.fEnabled;
2909
2910 if ( pThis->pHostDrvAudio
2911 && ( DrvAudioHlpStreamStatusCanRead(pStream->fStatus)
2912 || fDisabled)
2913 )
2914 {
2915 const uint32_t cfReadable = AudioMixBufLive(&pStream->Guest.MixBuf);
2916
2917 cbReadable = AUDIOMIXBUF_F2B(&pStream->Guest.MixBuf, cfReadable);
2918
2919 if (!cbReadable)
2920 {
2921 /*
2922 * If nothing is readable, check if the stream on the backend side is ready to be read from.
2923 * If it isn't, return the number of bytes readable since the last read from this stream.
2924 *
2925 * This is needed for backends (e.g. VRDE) which do not provide any input data in certain
2926 * situations, but the device emulation needs input data to keep the DMA transfers moving.
2927 * Reading the actual data from a stream then will return silence then.
2928 */
2929 if ( !DrvAudioHlpStreamStatusCanRead(
2930 pThis->pHostDrvAudio->pfnStreamGetStatus(pThis->pHostDrvAudio, pStream->pvBackend)
2931 || fDisabled))
2932 {
2933 cbReadable = DrvAudioHlpNanoToBytes(RTTimeNanoTS() - pStream->tsLastReadWrittenNs,
2934 &pStream->Host.Cfg.Props);
2935 Log3Func(("[%s] Backend stream not ready or driver has disabled audio input, returning silence\n", pStream->szName));
2936 }
2937 }
2938
2939 /* Make sure to align the readable size to the guest's frame size. */
2940 cbReadable = DrvAudioHlpBytesAlign(cbReadable, &pStream->Guest.Cfg.Props);
2941 }
2942
2943 Log3Func(("[%s] cbReadable=%RU32 (%RU64ms)\n",
2944 pStream->szName, cbReadable, DrvAudioHlpBytesToMilli(cbReadable, &pStream->Host.Cfg.Props)));
2945
2946 rc2 = RTCritSectLeave(&pThis->CritSect);
2947 AssertRC(rc2);
2948
2949 /* Return bytes instead of audio frames. */
2950 return cbReadable;
2951}
2952
2953/**
2954 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnStreamGetWritable}
2955 */
2956static DECLCALLBACK(uint32_t) drvAudioStreamGetWritable(PPDMIAUDIOCONNECTOR pInterface, PPDMAUDIOSTREAM pStream)
2957{
2958 AssertPtrReturn(pInterface, 0);
2959 AssertPtrReturn(pStream, 0);
2960
2961 PDRVAUDIO pThis = PDMIAUDIOCONNECTOR_2_DRVAUDIO(pInterface);
2962
2963 int rc2 = RTCritSectEnter(&pThis->CritSect);
2964 AssertRC(rc2);
2965
2966 AssertMsg(pStream->enmDir == PDMAUDIODIR_OUT, ("Can't write to a non-output stream\n"));
2967
2968 uint32_t cbWritable = 0;
2969
2970 /* Note: We don't propage the backend stream's status to the outside -- it's the job of this
2971 * audio connector to make sense of it. */
2972 if (DrvAudioHlpStreamStatusCanWrite(pStream->fStatus))
2973 {
2974 cbWritable = AudioMixBufFreeBytes(&pStream->Host.MixBuf);
2975
2976 /* Make sure to align the writable size to the host's frame size. */
2977 cbWritable = DrvAudioHlpBytesAlign(cbWritable, &pStream->Host.Cfg.Props);
2978 }
2979
2980 Log3Func(("[%s] cbWritable=%RU32 (%RU64ms)\n",
2981 pStream->szName, cbWritable, DrvAudioHlpBytesToMilli(cbWritable, &pStream->Host.Cfg.Props)));
2982
2983 rc2 = RTCritSectLeave(&pThis->CritSect);
2984 AssertRC(rc2);
2985
2986 return cbWritable;
2987}
2988
2989/**
2990 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnStreamGetStatus}
2991 */
2992static DECLCALLBACK(PDMAUDIOSTREAMSTS) drvAudioStreamGetStatus(PPDMIAUDIOCONNECTOR pInterface, PPDMAUDIOSTREAM pStream)
2993{
2994 AssertPtrReturn(pInterface, false);
2995
2996 if (!pStream)
2997 return PDMAUDIOSTREAMSTS_FLAGS_NONE;
2998
2999 PDRVAUDIO pThis = PDMIAUDIOCONNECTOR_2_DRVAUDIO(pInterface);
3000
3001 int rc2 = RTCritSectEnter(&pThis->CritSect);
3002 AssertRC(rc2);
3003
3004 /* Is the stream scheduled for re-initialization? Do so now. */
3005 drvAudioStreamMaybeReInit(pThis, pStream);
3006
3007 PDMAUDIOSTREAMSTS fStrmStatus = pStream->fStatus;
3008
3009#ifdef LOG_ENABLED
3010 char *pszStreamSts = dbgAudioStreamStatusToStr(fStrmStatus);
3011 Log3Func(("[%s] %s\n", pStream->szName, pszStreamSts));
3012 RTStrFree(pszStreamSts);
3013#endif
3014
3015 rc2 = RTCritSectLeave(&pThis->CritSect);
3016 AssertRC(rc2);
3017
3018 return fStrmStatus;
3019}
3020
3021/**
3022 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnStreamSetVolume}
3023 */
3024static DECLCALLBACK(int) drvAudioStreamSetVolume(PPDMIAUDIOCONNECTOR pInterface, PPDMAUDIOSTREAM pStream, PPDMAUDIOVOLUME pVol)
3025{
3026 AssertPtrReturn(pInterface, VERR_INVALID_POINTER);
3027 AssertPtrReturn(pStream, VERR_INVALID_POINTER);
3028 AssertPtrReturn(pVol, VERR_INVALID_POINTER);
3029
3030 LogFlowFunc(("[%s] volL=%RU32, volR=%RU32, fMute=%RTbool\n", pStream->szName, pVol->uLeft, pVol->uRight, pVol->fMuted));
3031
3032 AudioMixBufSetVolume(&pStream->Guest.MixBuf, pVol);
3033 AudioMixBufSetVolume(&pStream->Host.MixBuf, pVol);
3034
3035 return VINF_SUCCESS;
3036}
3037
3038/**
3039 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnStreamDestroy}
3040 */
3041static DECLCALLBACK(int) drvAudioStreamDestroy(PPDMIAUDIOCONNECTOR pInterface, PPDMAUDIOSTREAM pStream)
3042{
3043 AssertPtrReturn(pInterface, VERR_INVALID_POINTER);
3044 AssertPtrReturn(pStream, VERR_INVALID_POINTER);
3045
3046 PDRVAUDIO pThis = PDMIAUDIOCONNECTOR_2_DRVAUDIO(pInterface);
3047
3048 int rc = RTCritSectEnter(&pThis->CritSect);
3049 AssertRC(rc);
3050
3051 LogRel2(("Audio: Destroying stream '%s'\n", pStream->szName));
3052
3053 LogFlowFunc(("[%s] cRefs=%RU32\n", pStream->szName, pStream->cRefs));
3054 if (pStream->cRefs > 1)
3055 rc = VERR_WRONG_ORDER;
3056
3057 if (RT_SUCCESS(rc))
3058 {
3059 rc = drvAudioStreamUninitInternal(pThis, pStream);
3060 if (RT_FAILURE(rc))
3061 LogRel(("Audio: Uninitializing stream '%s' failed with %Rrc\n", pStream->szName, rc));
3062 }
3063
3064 if (RT_SUCCESS(rc))
3065 {
3066 if (pStream->enmDir == PDMAUDIODIR_IN)
3067 {
3068 pThis->In.cStreamsFree++;
3069 }
3070 else /* Out */
3071 {
3072 pThis->Out.cStreamsFree++;
3073 }
3074
3075 RTListNodeRemove(&pStream->Node);
3076
3077 drvAudioStreamFree(pStream);
3078 pStream = NULL;
3079 }
3080
3081 int rc2 = RTCritSectLeave(&pThis->CritSect);
3082 if (RT_SUCCESS(rc))
3083 rc = rc2;
3084
3085 LogFlowFuncLeaveRC(rc);
3086 return rc;
3087}
3088
3089/**
3090 * Creates an audio stream on the backend side.
3091 *
3092 * @returns IPRT status code.
3093 * @param pThis Pointer to driver instance.
3094 * @param pStream Audio stream to create the backend side for.
3095 * @param pCfgReq Requested audio stream configuration to use for stream creation.
3096 * @param pCfgAcq Acquired audio stream configuration returned by the backend.
3097 *
3098 * @note Configuration precedence for requested audio stream configuration (first has highest priority, if set):
3099 * - per global extra-data
3100 * - per-VM extra-data
3101 * - requested configuration (by pCfgReq)
3102 * - default value
3103 */
3104static int drvAudioStreamCreateInternalBackend(PDRVAUDIO pThis,
3105 PPDMAUDIOSTREAM pStream, PPDMAUDIOSTREAMCFG pCfgReq, PPDMAUDIOSTREAMCFG pCfgAcq)
3106{
3107 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
3108 AssertPtrReturn(pStream, VERR_INVALID_POINTER);
3109 AssertPtrReturn(pCfgReq, VERR_INVALID_POINTER);
3110 AssertPtrReturn(pCfgAcq, VERR_INVALID_POINTER);
3111
3112 AssertMsg((pStream->fStatus & PDMAUDIOSTREAMSTS_FLAGS_INITIALIZED) == 0,
3113 ("Stream '%s' already initialized in backend\n", pStream->szName));
3114
3115 /* Get the right configuration for the stream to be created. */
3116 PDRVAUDIOCFG pDrvCfg = pCfgReq->enmDir == PDMAUDIODIR_IN ? &pThis->In.Cfg : &pThis->Out.Cfg;
3117
3118 /* Fill in the tweakable parameters into the requested host configuration.
3119 * All parameters in principle can be changed and returned by the backend via the acquired configuration. */
3120
3121 char szWhat[64]; /* Log where a value came from. */
3122
3123 /*
3124 * Period size
3125 */
3126 if (pDrvCfg->uPeriodSizeMs)
3127 {
3128 pCfgReq->Backend.cFramesPeriod = DrvAudioHlpMilliToFrames(pDrvCfg->uPeriodSizeMs, &pCfgReq->Props);
3129 RTStrPrintf(szWhat, sizeof(szWhat), "global / per-VM");
3130 }
3131
3132 if (!pCfgReq->Backend.cFramesPeriod) /* Set default period size if nothing explicitly is set. */
3133 {
3134 pCfgReq->Backend.cFramesPeriod = DrvAudioHlpMilliToFrames(50 /* ms */, &pCfgReq->Props);
3135 RTStrPrintf(szWhat, sizeof(szWhat), "default");
3136 }
3137 else
3138 RTStrPrintf(szWhat, sizeof(szWhat), "device-specific");
3139
3140 LogRel2(("Audio: Using %s period size (%RU64ms, %RU32 frames) for stream '%s'\n",
3141 szWhat,
3142 DrvAudioHlpFramesToMilli(pCfgReq->Backend.cFramesPeriod, &pCfgReq->Props), pCfgReq->Backend.cFramesPeriod, pStream->szName));
3143
3144 /*
3145 * Buffer size
3146 */
3147 if (pDrvCfg->uBufferSizeMs)
3148 {
3149 pCfgReq->Backend.cFramesBufferSize = DrvAudioHlpMilliToFrames(pDrvCfg->uBufferSizeMs, &pCfgReq->Props);
3150 RTStrPrintf(szWhat, sizeof(szWhat), "global / per-VM");
3151 }
3152
3153 if (!pCfgReq->Backend.cFramesBufferSize) /* Set default buffer size if nothing explicitly is set. */
3154 {
3155 pCfgReq->Backend.cFramesBufferSize = DrvAudioHlpMilliToFrames(250 /* ms */, &pCfgReq->Props);
3156 RTStrPrintf(szWhat, sizeof(szWhat), "default");
3157 }
3158 else
3159 RTStrPrintf(szWhat, sizeof(szWhat), "device-specific");
3160
3161 LogRel2(("Audio: Using %s buffer size (%RU64ms, %RU32 frames) for stream '%s'\n",
3162 szWhat,
3163 DrvAudioHlpFramesToMilli(pCfgReq->Backend.cFramesBufferSize, &pCfgReq->Props), pCfgReq->Backend.cFramesBufferSize, pStream->szName));
3164
3165 /*
3166 * Pre-buffering size
3167 */
3168 if (pDrvCfg->uPreBufSizeMs != UINT32_MAX) /* Anything set via global / per-VM extra-data? */
3169 {
3170 pCfgReq->Backend.cFramesPreBuffering = DrvAudioHlpMilliToFrames(pDrvCfg->uPreBufSizeMs, &pCfgReq->Props);
3171 RTStrPrintf(szWhat, sizeof(szWhat), "global / per-VM");
3172 }
3173 else /* No, then either use the default or device-specific settings (if any). */
3174 {
3175 if (pCfgReq->Backend.cFramesPreBuffering == UINT32_MAX) /* Set default pre-buffering size if nothing explicitly is set. */
3176 {
3177 /* For pre-buffering to finish the buffer at least must be full one time. */
3178 pCfgReq->Backend.cFramesPreBuffering = pCfgReq->Backend.cFramesBufferSize;
3179 RTStrPrintf(szWhat, sizeof(szWhat), "default");
3180 }
3181 else
3182 RTStrPrintf(szWhat, sizeof(szWhat), "device-specific");
3183 }
3184
3185 LogRel2(("Audio: Using %s pre-buffering size (%RU64ms, %RU32 frames) for stream '%s'\n",
3186 szWhat,
3187 DrvAudioHlpFramesToMilli(pCfgReq->Backend.cFramesPreBuffering, &pCfgReq->Props), pCfgReq->Backend.cFramesPreBuffering, pStream->szName));
3188
3189 /*
3190 * Validate input.
3191 */
3192 if (pCfgReq->Backend.cFramesBufferSize < pCfgReq->Backend.cFramesPeriod)
3193 {
3194 LogRel(("Audio: Error for stream '%s': Buffering size (%RU64ms) must not be smaller than the period size (%RU64ms)\n",
3195 pStream->szName, DrvAudioHlpFramesToMilli(pCfgReq->Backend.cFramesBufferSize, &pCfgReq->Props),
3196 DrvAudioHlpFramesToMilli(pCfgReq->Backend.cFramesPeriod, &pCfgReq->Props)));
3197 return VERR_INVALID_PARAMETER;
3198 }
3199
3200 if ( pCfgReq->Backend.cFramesPreBuffering != UINT32_MAX /* Custom pre-buffering set? */
3201 && pCfgReq->Backend.cFramesPreBuffering)
3202 {
3203 if (pCfgReq->Backend.cFramesBufferSize < pCfgReq->Backend.cFramesPreBuffering)
3204 {
3205 LogRel(("Audio: Error for stream '%s': Buffering size (%RU64ms) must not be smaller than the pre-buffering size (%RU64ms)\n",
3206 pStream->szName, DrvAudioHlpFramesToMilli(pCfgReq->Backend.cFramesPreBuffering, &pCfgReq->Props),
3207 DrvAudioHlpFramesToMilli(pCfgReq->Backend.cFramesBufferSize, &pCfgReq->Props)));
3208 return VERR_INVALID_PARAMETER;
3209 }
3210 }
3211
3212 /* Make the acquired host configuration the requested host configuration initially,
3213 * in case the backend does not report back an acquired configuration. */
3214 int rc = DrvAudioHlpStreamCfgCopy(pCfgAcq, pCfgReq);
3215 if (RT_FAILURE(rc))
3216 {
3217 LogRel(("Audio: Creating stream '%s' with an invalid backend configuration not possible, skipping\n",
3218 pStream->szName));
3219 return rc;
3220 }
3221
3222 rc = pThis->pHostDrvAudio->pfnStreamCreate(pThis->pHostDrvAudio, pStream->pvBackend, pCfgReq, pCfgAcq);
3223 if (RT_FAILURE(rc))
3224 {
3225 if (rc == VERR_NOT_SUPPORTED)
3226 LogRel2(("Audio: Creating stream '%s' in backend not supported\n", pStream->szName));
3227 else if (rc == VERR_AUDIO_STREAM_COULD_NOT_CREATE)
3228 LogRel2(("Audio: Stream '%s' could not be created in backend because of missing hardware / drivers\n", pStream->szName));
3229 else
3230 LogRel(("Audio: Creating stream '%s' in backend failed with %Rrc\n", pStream->szName, rc));
3231
3232 return rc;
3233 }
3234
3235 /* Validate acquired configuration. */
3236 if (!DrvAudioHlpStreamCfgIsValid(pCfgAcq))
3237 {
3238 LogRel(("Audio: Creating stream '%s' returned an invalid backend configuration, skipping\n", pStream->szName));
3239 return VERR_INVALID_PARAMETER;
3240 }
3241
3242 /* Let the user know that the backend changed one of the values requested above. */
3243 if (pCfgAcq->Backend.cFramesBufferSize != pCfgReq->Backend.cFramesBufferSize)
3244 LogRel2(("Audio: Buffer size overwritten by backend for stream '%s' (now %RU64ms, %RU32 frames)\n",
3245 pStream->szName, DrvAudioHlpFramesToMilli(pCfgAcq->Backend.cFramesBufferSize, &pCfgAcq->Props), pCfgAcq->Backend.cFramesBufferSize));
3246
3247 if (pCfgAcq->Backend.cFramesPeriod != pCfgReq->Backend.cFramesPeriod)
3248 LogRel2(("Audio: Period size overwritten by backend for stream '%s' (now %RU64ms, %RU32 frames)\n",
3249 pStream->szName, DrvAudioHlpFramesToMilli(pCfgAcq->Backend.cFramesPeriod, &pCfgAcq->Props), pCfgAcq->Backend.cFramesPeriod));
3250
3251 /* Was pre-buffering requested, but the acquired configuration from the backend told us something else? */
3252 if ( pCfgReq->Backend.cFramesPreBuffering
3253 && pCfgAcq->Backend.cFramesPreBuffering != pCfgReq->Backend.cFramesPreBuffering)
3254 {
3255 LogRel2(("Audio: Pre-buffering size overwritten by backend for stream '%s' (now %RU64ms, %RU32 frames)\n",
3256 pStream->szName, DrvAudioHlpFramesToMilli(pCfgAcq->Backend.cFramesPreBuffering, &pCfgAcq->Props), pCfgAcq->Backend.cFramesPreBuffering));
3257 }
3258 else if (pCfgReq->Backend.cFramesPreBuffering == 0) /* Was the pre-buffering requested as being disabeld? Tell the users. */
3259 {
3260 LogRel2(("Audio: Pre-buffering is disabled for stream '%s'\n", pStream->szName));
3261 pCfgAcq->Backend.cFramesPreBuffering = 0;
3262 }
3263
3264 /* Sanity for detecting buggy backends. */
3265 AssertMsgReturn(pCfgAcq->Backend.cFramesPeriod < pCfgAcq->Backend.cFramesBufferSize,
3266 ("Acquired period size must be smaller than buffer size\n"),
3267 VERR_INVALID_PARAMETER);
3268 AssertMsgReturn(pCfgAcq->Backend.cFramesPreBuffering <= pCfgAcq->Backend.cFramesBufferSize,
3269 ("Acquired pre-buffering size must be smaller or as big as the buffer size\n"),
3270 VERR_INVALID_PARAMETER);
3271
3272 pStream->fStatus |= PDMAUDIOSTREAMSTS_FLAGS_INITIALIZED;
3273
3274 return VINF_SUCCESS;
3275}
3276
3277/**
3278 * Calls the backend to give it the chance to destroy its part of the audio stream.
3279 *
3280 * @returns IPRT status code.
3281 * @param pThis Pointer to driver instance.
3282 * @param pStream Audio stream destruct backend for.
3283 */
3284static int drvAudioStreamDestroyInternalBackend(PDRVAUDIO pThis, PPDMAUDIOSTREAM pStream)
3285{
3286 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
3287 AssertPtrReturn(pStream, VERR_INVALID_POINTER);
3288
3289 int rc = VINF_SUCCESS;
3290
3291#ifdef LOG_ENABLED
3292 char *pszStreamSts = dbgAudioStreamStatusToStr(pStream->fStatus);
3293 LogFunc(("[%s] fStatus=%s\n", pStream->szName, pszStreamSts));
3294#endif
3295
3296 if (pStream->fStatus & PDMAUDIOSTREAMSTS_FLAGS_INITIALIZED)
3297 {
3298 AssertPtr(pStream->pvBackend);
3299
3300 /* Check if the pointer to the host audio driver is still valid.
3301 * It can be NULL if we were called in drvAudioDestruct, for example. */
3302 if (pThis->pHostDrvAudio)
3303 rc = pThis->pHostDrvAudio->pfnStreamDestroy(pThis->pHostDrvAudio, pStream->pvBackend);
3304
3305 pStream->fStatus &= ~PDMAUDIOSTREAMSTS_FLAGS_INITIALIZED;
3306 }
3307
3308#ifdef LOG_ENABLED
3309 RTStrFree(pszStreamSts);
3310#endif
3311
3312 LogFlowFunc(("[%s] Returning %Rrc\n", pStream->szName, rc));
3313 return rc;
3314}
3315
3316/**
3317 * Uninitializes an audio stream.
3318 *
3319 * @returns IPRT status code.
3320 * @param pThis Pointer to driver instance.
3321 * @param pStream Pointer to audio stream to uninitialize.
3322 */
3323static int drvAudioStreamUninitInternal(PDRVAUDIO pThis, PPDMAUDIOSTREAM pStream)
3324{
3325 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
3326 AssertPtrReturn(pStream, VERR_INVALID_POINTER);
3327
3328 LogFlowFunc(("[%s] cRefs=%RU32\n", pStream->szName, pStream->cRefs));
3329
3330 AssertMsgReturn(pStream->cRefs <= 1,
3331 ("Stream '%s' still has %RU32 references held when uninitializing\n", pStream->szName, pStream->cRefs),
3332 VERR_WRONG_ORDER);
3333
3334 int rc = drvAudioStreamControlInternal(pThis, pStream, PDMAUDIOSTREAMCMD_DISABLE);
3335 if (RT_SUCCESS(rc))
3336 rc = drvAudioStreamDestroyInternalBackend(pThis, pStream);
3337
3338 /* Destroy mixing buffers. */
3339 AudioMixBufDestroy(&pStream->Guest.MixBuf);
3340 AudioMixBufDestroy(&pStream->Host.MixBuf);
3341
3342 if (RT_SUCCESS(rc))
3343 {
3344#ifdef LOG_ENABLED
3345 if (pStream->fStatus != PDMAUDIOSTREAMSTS_FLAGS_NONE)
3346 {
3347 char *pszStreamSts = dbgAudioStreamStatusToStr(pStream->fStatus);
3348 LogFunc(("[%s] Warning: Still has %s set when uninitializing\n", pStream->szName, pszStreamSts));
3349 RTStrFree(pszStreamSts);
3350 }
3351#endif
3352 pStream->fStatus = PDMAUDIOSTREAMSTS_FLAGS_NONE;
3353 }
3354
3355 if (pStream->enmDir == PDMAUDIODIR_IN)
3356 {
3357#ifdef VBOX_WITH_STATISTICS
3358 PDMDrvHlpSTAMDeregister(pThis->pDrvIns, &pStream->In.Stats.TotalFramesCaptured);
3359 PDMDrvHlpSTAMDeregister(pThis->pDrvIns, &pStream->In.Stats.TotalTimesCaptured);
3360 PDMDrvHlpSTAMDeregister(pThis->pDrvIns, &pStream->In.Stats.TotalFramesRead);
3361 PDMDrvHlpSTAMDeregister(pThis->pDrvIns, &pStream->In.Stats.TotalTimesRead);
3362#endif
3363 if (pThis->In.Cfg.Dbg.fEnabled)
3364 {
3365 DrvAudioHlpFileDestroy(pStream->In.Dbg.pFileCaptureNonInterleaved);
3366 pStream->In.Dbg.pFileCaptureNonInterleaved = NULL;
3367
3368 DrvAudioHlpFileDestroy(pStream->In.Dbg.pFileStreamRead);
3369 pStream->In.Dbg.pFileStreamRead = NULL;
3370 }
3371 }
3372 else if (pStream->enmDir == PDMAUDIODIR_OUT)
3373 {
3374#ifdef VBOX_WITH_STATISTICS
3375 PDMDrvHlpSTAMDeregister(pThis->pDrvIns, &pStream->Out.Stats.TotalFramesPlayed);
3376 PDMDrvHlpSTAMDeregister(pThis->pDrvIns, &pStream->Out.Stats.TotalTimesPlayed);
3377 PDMDrvHlpSTAMDeregister(pThis->pDrvIns, &pStream->Out.Stats.TotalFramesWritten);
3378 PDMDrvHlpSTAMDeregister(pThis->pDrvIns, &pStream->Out.Stats.TotalTimesWritten);
3379#endif
3380 if (pThis->Out.Cfg.Dbg.fEnabled)
3381 {
3382 DrvAudioHlpFileDestroy(pStream->Out.Dbg.pFilePlayNonInterleaved);
3383 pStream->Out.Dbg.pFilePlayNonInterleaved = NULL;
3384
3385 DrvAudioHlpFileDestroy(pStream->Out.Dbg.pFileStreamWrite);
3386 pStream->Out.Dbg.pFileStreamWrite = NULL;
3387 }
3388 }
3389 else
3390 AssertFailed();
3391
3392 LogFlowFunc(("Returning %Rrc\n", rc));
3393 return rc;
3394}
3395
3396/**
3397 * Does the actual backend driver attaching and queries the backend's interface.
3398 *
3399 * @return VBox status code.
3400 * @param pThis Pointer to driver instance.
3401 * @param fFlags Attach flags; see PDMDrvHlpAttach().
3402 */
3403static int drvAudioDoAttachInternal(PDRVAUDIO pThis, uint32_t fFlags)
3404{
3405 Assert(pThis->pHostDrvAudio == NULL); /* No nested attaching. */
3406
3407 /*
3408 * Attach driver below and query its connector interface.
3409 */
3410 PPDMIBASE pDownBase;
3411 int rc = PDMDrvHlpAttach(pThis->pDrvIns, fFlags, &pDownBase);
3412 if (RT_SUCCESS(rc))
3413 {
3414 pThis->pHostDrvAudio = PDMIBASE_QUERY_INTERFACE(pDownBase, PDMIHOSTAUDIO);
3415 if (!pThis->pHostDrvAudio)
3416 {
3417 LogRel(("Audio: Failed to query interface for underlying host driver '%s'\n", pThis->szName));
3418 rc = PDMDRV_SET_ERROR(pThis->pDrvIns, VERR_PDM_MISSING_INTERFACE_BELOW,
3419 N_("Host audio backend missing or invalid"));
3420 }
3421 }
3422
3423 if (RT_SUCCESS(rc))
3424 {
3425 /*
3426 * If everything went well, initialize the lower driver.
3427 */
3428 AssertPtr(pThis->pCFGMNode);
3429 rc = drvAudioHostInit(pThis, pThis->pCFGMNode);
3430 }
3431
3432 LogFunc(("[%s] rc=%Rrc\n", pThis->szName, rc));
3433 return rc;
3434}
3435
3436
3437/********************************************************************/
3438
3439/**
3440 * @interface_method_impl{PDMIBASE,pfnQueryInterface}
3441 */
3442static DECLCALLBACK(void *) drvAudioQueryInterface(PPDMIBASE pInterface, const char *pszIID)
3443{
3444 LogFlowFunc(("pInterface=%p, pszIID=%s\n", pInterface, pszIID));
3445
3446 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
3447 PDRVAUDIO pThis = PDMINS_2_DATA(pDrvIns, PDRVAUDIO);
3448
3449 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pDrvIns->IBase);
3450 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIAUDIOCONNECTOR, &pThis->IAudioConnector);
3451
3452 return NULL;
3453}
3454
3455/**
3456 * Power Off notification.
3457 *
3458 * @param pDrvIns The driver instance data.
3459 */
3460static DECLCALLBACK(void) drvAudioPowerOff(PPDMDRVINS pDrvIns)
3461{
3462 PDRVAUDIO pThis = PDMINS_2_DATA(pDrvIns, PDRVAUDIO);
3463
3464 LogFlowFuncEnter();
3465
3466 if (!pThis->pHostDrvAudio) /* If not lower driver is configured, bail out. */
3467 return;
3468
3469 /* Just destroy the host stream on the backend side.
3470 * The rest will either be destructed by the device emulation or
3471 * in drvAudioDestruct(). */
3472 PPDMAUDIOSTREAM pStream;
3473 RTListForEach(&pThis->lstStreams, pStream, PDMAUDIOSTREAM, Node)
3474 {
3475 drvAudioStreamControlInternalBackend(pThis, pStream, PDMAUDIOSTREAMCMD_DISABLE);
3476 drvAudioStreamDestroyInternalBackend(pThis, pStream);
3477 }
3478
3479 /*
3480 * Last call for the driver below us.
3481 * Let it know that we reached end of life.
3482 */
3483 if (pThis->pHostDrvAudio->pfnShutdown)
3484 pThis->pHostDrvAudio->pfnShutdown(pThis->pHostDrvAudio);
3485
3486 pThis->pHostDrvAudio = NULL;
3487
3488 LogFlowFuncLeave();
3489}
3490
3491/**
3492 * Constructs an audio driver instance.
3493 *
3494 * @copydoc FNPDMDRVCONSTRUCT
3495 */
3496static DECLCALLBACK(int) drvAudioConstruct(PPDMDRVINS pDrvIns, PCFGMNODE pCfg, uint32_t fFlags)
3497{
3498 LogFlowFunc(("pDrvIns=%#p, pCfgHandle=%#p, fFlags=%x\n", pDrvIns, pCfg, fFlags));
3499
3500 PDRVAUDIO pThis = PDMINS_2_DATA(pDrvIns, PDRVAUDIO);
3501 PDMDRV_CHECK_VERSIONS_RETURN(pDrvIns);
3502
3503 RTListInit(&pThis->lstStreams);
3504#ifdef VBOX_WITH_AUDIO_CALLBACKS
3505 RTListInit(&pThis->In.lstCB);
3506 RTListInit(&pThis->Out.lstCB);
3507#endif
3508
3509 /*
3510 * Init the static parts.
3511 */
3512 pThis->pDrvIns = pDrvIns;
3513 /* IBase. */
3514 pDrvIns->IBase.pfnQueryInterface = drvAudioQueryInterface;
3515 /* IAudioConnector. */
3516 pThis->IAudioConnector.pfnEnable = drvAudioEnable;
3517 pThis->IAudioConnector.pfnIsEnabled = drvAudioIsEnabled;
3518 pThis->IAudioConnector.pfnGetConfig = drvAudioGetConfig;
3519 pThis->IAudioConnector.pfnGetStatus = drvAudioGetStatus;
3520 pThis->IAudioConnector.pfnStreamCreate = drvAudioStreamCreate;
3521 pThis->IAudioConnector.pfnStreamDestroy = drvAudioStreamDestroy;
3522 pThis->IAudioConnector.pfnStreamRetain = drvAudioStreamRetain;
3523 pThis->IAudioConnector.pfnStreamRelease = drvAudioStreamRelease;
3524 pThis->IAudioConnector.pfnStreamControl = drvAudioStreamControl;
3525 pThis->IAudioConnector.pfnStreamRead = drvAudioStreamRead;
3526 pThis->IAudioConnector.pfnStreamWrite = drvAudioStreamWrite;
3527 pThis->IAudioConnector.pfnStreamIterate = drvAudioStreamIterate;
3528 pThis->IAudioConnector.pfnStreamGetReadable = drvAudioStreamGetReadable;
3529 pThis->IAudioConnector.pfnStreamGetWritable = drvAudioStreamGetWritable;
3530 pThis->IAudioConnector.pfnStreamGetStatus = drvAudioStreamGetStatus;
3531 pThis->IAudioConnector.pfnStreamSetVolume = drvAudioStreamSetVolume;
3532 pThis->IAudioConnector.pfnStreamPlay = drvAudioStreamPlay;
3533 pThis->IAudioConnector.pfnStreamCapture = drvAudioStreamCapture;
3534#ifdef VBOX_WITH_AUDIO_CALLBACKS
3535 pThis->IAudioConnector.pfnRegisterCallbacks = drvAudioRegisterCallbacks;
3536#endif
3537
3538 int rc = drvAudioInit(pDrvIns, pCfg);
3539 if (RT_SUCCESS(rc))
3540 {
3541#ifdef VBOX_WITH_STATISTICS
3542 PDMDrvHlpSTAMRegCounterEx(pDrvIns, &pThis->Stats.TotalStreamsActive, "TotalStreamsActive",
3543 STAMUNIT_COUNT, "Total active audio streams.");
3544 PDMDrvHlpSTAMRegCounterEx(pDrvIns, &pThis->Stats.TotalStreamsCreated, "TotalStreamsCreated",
3545 STAMUNIT_COUNT, "Total created audio streams.");
3546 PDMDrvHlpSTAMRegCounterEx(pDrvIns, &pThis->Stats.TotalFramesRead, "TotalFramesRead",
3547 STAMUNIT_COUNT, "Total frames read by device emulation.");
3548 PDMDrvHlpSTAMRegCounterEx(pDrvIns, &pThis->Stats.TotalFramesWritten, "TotalFramesWritten",
3549 STAMUNIT_COUNT, "Total frames written by device emulation ");
3550 PDMDrvHlpSTAMRegCounterEx(pDrvIns, &pThis->Stats.TotalFramesMixedIn, "TotalFramesMixedIn",
3551 STAMUNIT_COUNT, "Total input frames mixed.");
3552 PDMDrvHlpSTAMRegCounterEx(pDrvIns, &pThis->Stats.TotalFramesMixedOut, "TotalFramesMixedOut",
3553 STAMUNIT_COUNT, "Total output frames mixed.");
3554 PDMDrvHlpSTAMRegCounterEx(pDrvIns, &pThis->Stats.TotalFramesLostIn, "TotalFramesLostIn",
3555 STAMUNIT_COUNT, "Total input frames lost.");
3556 PDMDrvHlpSTAMRegCounterEx(pDrvIns, &pThis->Stats.TotalFramesLostOut, "TotalFramesLostOut",
3557 STAMUNIT_COUNT, "Total output frames lost.");
3558 PDMDrvHlpSTAMRegCounterEx(pDrvIns, &pThis->Stats.TotalFramesOut, "TotalFramesOut",
3559 STAMUNIT_COUNT, "Total frames played by backend.");
3560 PDMDrvHlpSTAMRegCounterEx(pDrvIns, &pThis->Stats.TotalFramesIn, "TotalFramesIn",
3561 STAMUNIT_COUNT, "Total frames captured by backend.");
3562 PDMDrvHlpSTAMRegCounterEx(pDrvIns, &pThis->Stats.TotalBytesRead, "TotalBytesRead",
3563 STAMUNIT_BYTES, "Total bytes read.");
3564 PDMDrvHlpSTAMRegCounterEx(pDrvIns, &pThis->Stats.TotalBytesWritten, "TotalBytesWritten",
3565 STAMUNIT_BYTES, "Total bytes written.");
3566
3567 PDMDrvHlpSTAMRegProfileAdvEx(pDrvIns, &pThis->Stats.DelayIn, "DelayIn",
3568 STAMUNIT_NS_PER_CALL, "Profiling of input data processing.");
3569 PDMDrvHlpSTAMRegProfileAdvEx(pDrvIns, &pThis->Stats.DelayOut, "DelayOut",
3570 STAMUNIT_NS_PER_CALL, "Profiling of output data processing.");
3571#endif
3572 }
3573
3574 rc = drvAudioDoAttachInternal(pThis, fFlags);
3575 if (RT_FAILURE(rc))
3576 {
3577 /* No lower attached driver (yet)? Not a failure, might get attached later at runtime, just skip. */
3578 if (rc == VERR_PDM_NO_ATTACHED_DRIVER)
3579 rc = VINF_SUCCESS;
3580 }
3581
3582 LogFlowFuncLeaveRC(rc);
3583 return rc;
3584}
3585
3586/**
3587 * Destructs an audio driver instance.
3588 *
3589 * @copydoc FNPDMDRVDESTRUCT
3590 */
3591static DECLCALLBACK(void) drvAudioDestruct(PPDMDRVINS pDrvIns)
3592{
3593 PDMDRV_CHECK_VERSIONS_RETURN_VOID(pDrvIns);
3594 PDRVAUDIO pThis = PDMINS_2_DATA(pDrvIns, PDRVAUDIO);
3595
3596 LogFlowFuncEnter();
3597
3598 int rc2;
3599
3600 if (RTCritSectIsInitialized(&pThis->CritSect))
3601 {
3602 rc2 = RTCritSectEnter(&pThis->CritSect);
3603 AssertRC(rc2);
3604 }
3605
3606 /*
3607 * Note: No calls here to the driver below us anymore,
3608 * as PDM already has destroyed it.
3609 * If you need to call something from the host driver,
3610 * do this in drvAudioPowerOff() instead.
3611 */
3612
3613 /* Thus, NULL the pointer to the host audio driver first,
3614 * so that routines like drvAudioStreamDestroyInternal() don't call the driver(s) below us anymore. */
3615 pThis->pHostDrvAudio = NULL;
3616
3617 PPDMAUDIOSTREAM pStream, pStreamNext;
3618 RTListForEachSafe(&pThis->lstStreams, pStream, pStreamNext, PDMAUDIOSTREAM, Node)
3619 {
3620 rc2 = drvAudioStreamUninitInternal(pThis, pStream);
3621 if (RT_SUCCESS(rc2))
3622 {
3623 RTListNodeRemove(&pStream->Node);
3624
3625 drvAudioStreamFree(pStream);
3626 pStream = NULL;
3627 }
3628 }
3629
3630 /* Sanity. */
3631 Assert(RTListIsEmpty(&pThis->lstStreams));
3632
3633#ifdef VBOX_WITH_AUDIO_CALLBACKS
3634 /*
3635 * Destroy callbacks, if any.
3636 */
3637 PPDMAUDIOCBRECORD pCB, pCBNext;
3638 RTListForEachSafe(&pThis->In.lstCB, pCB, pCBNext, PDMAUDIOCBRECORD, Node)
3639 drvAudioCallbackDestroy(pCB);
3640
3641 RTListForEachSafe(&pThis->Out.lstCB, pCB, pCBNext, PDMAUDIOCBRECORD, Node)
3642 drvAudioCallbackDestroy(pCB);
3643#endif
3644
3645 if (RTCritSectIsInitialized(&pThis->CritSect))
3646 {
3647 rc2 = RTCritSectLeave(&pThis->CritSect);
3648 AssertRC(rc2);
3649
3650 rc2 = RTCritSectDelete(&pThis->CritSect);
3651 AssertRC(rc2);
3652 }
3653
3654#ifdef VBOX_WITH_STATISTICS
3655 PDMDrvHlpSTAMDeregister(pThis->pDrvIns, &pThis->Stats.TotalStreamsActive);
3656 PDMDrvHlpSTAMDeregister(pThis->pDrvIns, &pThis->Stats.TotalStreamsCreated);
3657 PDMDrvHlpSTAMDeregister(pThis->pDrvIns, &pThis->Stats.TotalFramesRead);
3658 PDMDrvHlpSTAMDeregister(pThis->pDrvIns, &pThis->Stats.TotalFramesWritten);
3659 PDMDrvHlpSTAMDeregister(pThis->pDrvIns, &pThis->Stats.TotalFramesMixedIn);
3660 PDMDrvHlpSTAMDeregister(pThis->pDrvIns, &pThis->Stats.TotalFramesMixedOut);
3661 PDMDrvHlpSTAMDeregister(pThis->pDrvIns, &pThis->Stats.TotalFramesLostIn);
3662 PDMDrvHlpSTAMDeregister(pThis->pDrvIns, &pThis->Stats.TotalFramesLostOut);
3663 PDMDrvHlpSTAMDeregister(pThis->pDrvIns, &pThis->Stats.TotalFramesOut);
3664 PDMDrvHlpSTAMDeregister(pThis->pDrvIns, &pThis->Stats.TotalFramesIn);
3665 PDMDrvHlpSTAMDeregister(pThis->pDrvIns, &pThis->Stats.TotalBytesRead);
3666 PDMDrvHlpSTAMDeregister(pThis->pDrvIns, &pThis->Stats.TotalBytesWritten);
3667 PDMDrvHlpSTAMDeregister(pThis->pDrvIns, &pThis->Stats.DelayIn);
3668 PDMDrvHlpSTAMDeregister(pThis->pDrvIns, &pThis->Stats.DelayOut);
3669#endif
3670
3671 LogFlowFuncLeave();
3672}
3673
3674/**
3675 * Suspend notification.
3676 *
3677 * @param pDrvIns The driver instance data.
3678 */
3679static DECLCALLBACK(void) drvAudioSuspend(PPDMDRVINS pDrvIns)
3680{
3681 drvAudioStateHandler(pDrvIns, PDMAUDIOSTREAMCMD_PAUSE);
3682}
3683
3684/**
3685 * Resume notification.
3686 *
3687 * @param pDrvIns The driver instance data.
3688 */
3689static DECLCALLBACK(void) drvAudioResume(PPDMDRVINS pDrvIns)
3690{
3691 drvAudioStateHandler(pDrvIns, PDMAUDIOSTREAMCMD_RESUME);
3692}
3693
3694/**
3695 * Attach notification.
3696 *
3697 * @param pDrvIns The driver instance data.
3698 * @param fFlags Attach flags.
3699 */
3700static DECLCALLBACK(int) drvAudioAttach(PPDMDRVINS pDrvIns, uint32_t fFlags)
3701{
3702 RT_NOREF(fFlags);
3703
3704 PDMDRV_CHECK_VERSIONS_RETURN(pDrvIns);
3705 PDRVAUDIO pThis = PDMINS_2_DATA(pDrvIns, PDRVAUDIO);
3706
3707 int rc2 = RTCritSectEnter(&pThis->CritSect);
3708 AssertRC(rc2);
3709
3710 LogFunc(("%s\n", pThis->szName));
3711
3712 int rc = drvAudioDoAttachInternal(pThis, fFlags);
3713
3714 rc2 = RTCritSectLeave(&pThis->CritSect);
3715 if (RT_SUCCESS(rc))
3716 rc = rc2;
3717
3718 return rc;
3719}
3720
3721/**
3722 * Detach notification.
3723 *
3724 * @param pDrvIns The driver instance data.
3725 * @param fFlags Detach flags.
3726 */
3727static DECLCALLBACK(void) drvAudioDetach(PPDMDRVINS pDrvIns, uint32_t fFlags)
3728{
3729 RT_NOREF(fFlags);
3730
3731 PDMDRV_CHECK_VERSIONS_RETURN_VOID(pDrvIns);
3732 PDRVAUDIO pThis = PDMINS_2_DATA(pDrvIns, PDRVAUDIO);
3733
3734 int rc2 = RTCritSectEnter(&pThis->CritSect);
3735 AssertRC(rc2);
3736
3737 pThis->pHostDrvAudio = NULL;
3738
3739 LogFunc(("%s\n", pThis->szName));
3740
3741 rc2 = RTCritSectLeave(&pThis->CritSect);
3742 AssertRC(rc2);
3743}
3744
3745/**
3746 * Audio driver registration record.
3747 */
3748const PDMDRVREG g_DrvAUDIO =
3749{
3750 /* u32Version */
3751 PDM_DRVREG_VERSION,
3752 /* szName */
3753 "AUDIO",
3754 /* szRCMod */
3755 "",
3756 /* szR0Mod */
3757 "",
3758 /* pszDescription */
3759 "Audio connector driver",
3760 /* fFlags */
3761 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
3762 /* fClass */
3763 PDM_DRVREG_CLASS_AUDIO,
3764 /* cMaxInstances */
3765 UINT32_MAX,
3766 /* cbInstance */
3767 sizeof(DRVAUDIO),
3768 /* pfnConstruct */
3769 drvAudioConstruct,
3770 /* pfnDestruct */
3771 drvAudioDestruct,
3772 /* pfnRelocate */
3773 NULL,
3774 /* pfnIOCtl */
3775 NULL,
3776 /* pfnPowerOn */
3777 NULL,
3778 /* pfnReset */
3779 NULL,
3780 /* pfnSuspend */
3781 drvAudioSuspend,
3782 /* pfnResume */
3783 drvAudioResume,
3784 /* pfnAttach */
3785 drvAudioAttach,
3786 /* pfnDetach */
3787 drvAudioDetach,
3788 /* pfnPowerOff */
3789 drvAudioPowerOff,
3790 /* pfnSoftReset */
3791 NULL,
3792 /* u32EndVersion */
3793 PDM_DRVREG_VERSION
3794};
3795
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