VirtualBox

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

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

Audio: Reworking the capture (recording) code path, part 4: Combine PDMIAUDIOCONNECTOR::pfnStreamCapture and PDMIAUDIOCONNECTOR::pfnStreamRead, remove PDMIAUDIOCONNECTOR::pfnStreamSetVoplume, eliminate mixer buffers in DrvAudio. Added pre-buffering of input streams (delay fetching samples from the backend till we've reached the desired buffer fill there). [build fix + cleanup] bugref:9890

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 207.2 KB
Line 
1/* $Id: DrvAudio.cpp 89329 2021-05-28 00:26:17Z vboxsync $ */
2/** @file
3 * Intermediate audio driver - Connects the audio device emulation with the host backend.
4 */
5
6/*
7 * Copyright (C) 2006-2020 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18
19/*********************************************************************************************************************************
20* Header Files *
21*********************************************************************************************************************************/
22#define LOG_GROUP LOG_GROUP_DRV_AUDIO
23#include <VBox/log.h>
24#include <VBox/vmm/pdm.h>
25#include <VBox/err.h>
26#include <VBox/vmm/mm.h>
27#include <VBox/vmm/pdmaudioifs.h>
28#include <VBox/vmm/pdmaudioinline.h>
29#include <VBox/vmm/pdmaudiohostenuminline.h>
30
31#include <iprt/alloc.h>
32#include <iprt/asm-math.h>
33#include <iprt/assert.h>
34#include <iprt/circbuf.h>
35#include <iprt/req.h>
36#include <iprt/string.h>
37#include <iprt/thread.h>
38#include <iprt/uuid.h>
39
40#include "VBoxDD.h"
41
42#include <ctype.h>
43#include <stdlib.h>
44
45#include "AudioHlp.h"
46#include "AudioMixBuffer.h"
47
48
49/*********************************************************************************************************************************
50* Defined Constants And Macros *
51*********************************************************************************************************************************/
52/** @name PDMAUDIOSTREAM_STS_XXX - Used internally by DRVAUDIOSTREAM::fStatus.
53 * @{ */
54/** No flags being set. */
55#define PDMAUDIOSTREAM_STS_NONE UINT32_C(0)
56/** Set if the stream is enabled, clear if disabled. */
57#define PDMAUDIOSTREAM_STS_ENABLED RT_BIT_32(0)
58/** Set if the stream is paused.
59 * Requires the ENABLED status to be set when used. */
60#define PDMAUDIOSTREAM_STS_PAUSED RT_BIT_32(1)
61/** Output only: Set when the stream is draining.
62 * Requires the ENABLED status to be set when used. */
63#define PDMAUDIOSTREAM_STS_PENDING_DISABLE RT_BIT_32(2)
64
65/** Set if the backend for the stream has been created.
66 *
67 * This is generally always set after stream creation, but
68 * can be cleared if the re-initialization of the stream fails later on.
69 * Asynchronous init may still be incomplete, see
70 * PDMAUDIOSTREAM_STS_BACKEND_READY. */
71#define PDMAUDIOSTREAM_STS_BACKEND_CREATED RT_BIT_32(3)
72/** The backend is ready (PDMIHOSTAUDIO::pfnStreamInitAsync is done).
73 * Requires the BACKEND_CREATED status to be set. */
74#define PDMAUDIOSTREAM_STS_BACKEND_READY RT_BIT_32(4)
75/** Set if the stream needs to be re-initialized by the device (i.e. call
76 * PDMIAUDIOCONNECTOR::pfnStreamReInit). (The other status bits are preserved
77 * and are worked as normal while in this state, so that the stream can
78 * resume operation where it left off.) */
79#define PDMAUDIOSTREAM_STS_NEED_REINIT RT_BIT_32(5)
80/** Validation mask for PDMIAUDIOCONNECTOR. */
81#define PDMAUDIOSTREAM_STS_VALID_MASK UINT32_C(0x0000003f)
82/** Asserts the validity of the given stream status mask for PDMIAUDIOCONNECTOR. */
83#define PDMAUDIOSTREAM_STS_ASSERT_VALID(a_fStreamStatus) do { \
84 AssertMsg(!((a_fStreamStatus) & ~PDMAUDIOSTREAM_STS_VALID_MASK), ("%#x\n", (a_fStreamStatus))); \
85 Assert(!((a_fStreamStatus) & PDMAUDIOSTREAM_STS_PAUSED) || ((a_fStreamStatus) & PDMAUDIOSTREAM_STS_ENABLED)); \
86 Assert(!((a_fStreamStatus) & PDMAUDIOSTREAM_STS_PENDING_DISABLE) || ((a_fStreamStatus) & PDMAUDIOSTREAM_STS_ENABLED)); \
87 Assert(!((a_fStreamStatus) & PDMAUDIOSTREAM_STS_BACKEND_READY) || ((a_fStreamStatus) & PDMAUDIOSTREAM_STS_BACKEND_CREATED)); \
88 } while (0)
89
90/** @} */
91
92
93/*********************************************************************************************************************************
94* Structures and Typedefs *
95*********************************************************************************************************************************/
96/**
97 * Audio stream context.
98 *
99 * Needed for separating data from the guest and host side (per stream).
100 */
101typedef struct DRVAUDIOSTREAMCTX
102{
103 /** The stream's audio configuration. */
104 PDMAUDIOSTREAMCFG Cfg;
105} DRVAUDIOSTREAMCTX;
106
107/**
108 * Capture state of a stream wrt backend.
109 */
110typedef enum DRVAUDIOCAPTURESTATE
111{
112 /** Invalid zero value. */
113 DRVAUDIOCAPTURESTATE_INVALID = 0,
114 /** No capturing or pre-buffering. */
115 DRVAUDIOCAPTURESTATE_NO_CAPTURE,
116 /** Regular capturing. */
117 DRVAUDIOCAPTURESTATE_CAPTURING,
118 /** Returning silence till the backend buffer has reched the configured
119 * pre-buffering level. */
120 DRVAUDIOCAPTURESTATE_PREBUF,
121 /** End of valid values. */
122 DRVAUDIOCAPTURESTATE_END
123} DRVAUDIOCAPTURESTATE;
124
125/**
126 * Play state of a stream wrt backend.
127 */
128typedef enum DRVAUDIOPLAYSTATE
129{
130 /** Invalid zero value. */
131 DRVAUDIOPLAYSTATE_INVALID = 0,
132 /** No playback or pre-buffering. */
133 DRVAUDIOPLAYSTATE_NOPLAY,
134 /** Playing w/o any prebuffering. */
135 DRVAUDIOPLAYSTATE_PLAY,
136 /** Parallel pre-buffering prior to a device switch (i.e. we're outputting to
137 * the old device and pre-buffering the same data in parallel). */
138 DRVAUDIOPLAYSTATE_PLAY_PREBUF,
139 /** Initial pre-buffering or the pre-buffering for a device switch (if it
140 * the device setup took less time than filling up the pre-buffer). */
141 DRVAUDIOPLAYSTATE_PREBUF,
142 /** The device initialization is taking too long, pre-buffering wraps around
143 * and drops samples. */
144 DRVAUDIOPLAYSTATE_PREBUF_OVERDUE,
145 /** Same as play-prebuf, but we don't have a working output device any more. */
146 DRVAUDIOPLAYSTATE_PREBUF_SWITCHING,
147 /** Working on committing the pre-buffered data.
148 * We'll typically leave this state immediately and go to PLAY, however if
149 * the backend cannot handle all the pre-buffered data at once, we'll stay
150 * here till it does. */
151 DRVAUDIOPLAYSTATE_PREBUF_COMMITTING,
152 /** End of valid values. */
153 DRVAUDIOPLAYSTATE_END
154} DRVAUDIOPLAYSTATE;
155
156
157/**
158 * Extended stream structure.
159 */
160typedef struct DRVAUDIOSTREAM
161{
162 /** The publicly visible bit. */
163 PDMAUDIOSTREAM Core;
164
165 /** Just an extra magic to verify that we allocated the stream rather than some
166 * faked up stuff from the device (DRVAUDIOSTREAM_MAGIC). */
167 uintptr_t uMagic;
168
169 /** List entry in DRVAUDIO::LstStreams. */
170 RTLISTNODE ListEntry;
171
172 /** Number of references to this stream.
173 * Only can be destroyed when the reference count reaches 0. */
174 uint32_t volatile cRefs;
175 /** Stream status - PDMAUDIOSTREAM_STS_XXX. */
176 uint32_t fStatus;
177
178 /** Data to backend-specific stream data.
179 * This data block will be casted by the backend to access its backend-dependent data.
180 *
181 * That way the backends do not have access to the audio connector's data. */
182 PPDMAUDIOBACKENDSTREAM pBackend;
183
184 /** Set if pfnStreamCreate returned VINF_AUDIO_STREAM_ASYNC_INIT_NEEDED. */
185 bool fNeedAsyncInit;
186 /** The fImmediate parameter value for pfnStreamDestroy. */
187 bool fDestroyImmediate;
188 bool afPadding[2];
189
190 /** Number of (re-)tries while re-initializing the stream. */
191 uint32_t cTriesReInit;
192
193 /** The last backend state we saw.
194 * This is used to detect state changes (for what that is worth). */
195 PDMHOSTAUDIOSTREAMSTATE enmLastBackendState;
196
197 /** The pre-buffering threshold expressed in bytes. */
198 uint32_t cbPreBufThreshold;
199
200 /** The pfnStreamInitAsync request handle. */
201 PRTREQ hReqInitAsync;
202
203 /** @todo The guest and host fields only contains the stream config now that
204 * the mixing buffer is gone, so we can probably combine them into a
205 * single Cfg member. */
206 /** The guest side of the stream. */
207 DRVAUDIOSTREAMCTX Guest;
208 /** The host side of the stream. */
209 DRVAUDIOSTREAMCTX Host;
210
211
212 /** The nanosecond timestamp when the stream was started. */
213 uint64_t nsStarted;
214 /** Internal stream position (as per pfnStreamPlay/pfnStreamCapture). */
215 uint64_t offInternal;
216
217 /** Timestamp (in ns) since last trying to re-initialize.
218 * Might be 0 if has not been tried yet. */
219 uint64_t nsLastReInit;
220 /** Timestamp (in ns) since last iteration. */
221 uint64_t nsLastIterated;
222 /** Timestamp (in ns) since last playback / capture. */
223 uint64_t nsLastPlayedCaptured;
224 /** Timestamp (in ns) since last read (input streams) or
225 * write (output streams). */
226 uint64_t nsLastReadWritten;
227
228
229 /** Union for input/output specifics depending on enmDir. */
230 union
231 {
232 /**
233 * The specifics for an audio input stream.
234 */
235 struct
236 {
237 /** The capture state. */
238 DRVAUDIOCAPTURESTATE enmCaptureState;
239
240 struct
241 {
242 /** File for writing non-interleaved captures. */
243 PAUDIOHLPFILE pFileCapture;
244 } Dbg;
245 struct
246 {
247 uint32_t cbBackendReadableBefore;
248 uint32_t cbBackendReadableAfter;
249
250 STAMCOUNTER TotalFramesCaptured;
251 STAMCOUNTER AvgFramesCaptured;
252 STAMCOUNTER TotalTimesCaptured;
253 STAMCOUNTER TotalFramesRead;
254 STAMCOUNTER AvgFramesRead;
255 STAMCOUNTER TotalTimesRead;
256 } Stats;
257 } In;
258
259 /**
260 * The specifics for an audio output stream.
261 */
262 struct
263 {
264 struct
265 {
266 /** File for writing stream playback. */
267 PAUDIOHLPFILE pFilePlay;
268 } Dbg;
269 struct
270 {
271 uint32_t cbBackendWritableBefore;
272 uint32_t cbBackendWritableAfter;
273 } Stats;
274
275 /** Space for pre-buffering. */
276 uint8_t *pbPreBuf;
277 /** The size of the pre-buffer allocation (in bytes). */
278 uint32_t cbPreBufAlloc;
279 /** The current pre-buffering read offset. */
280 uint32_t offPreBuf;
281 /** Number of bytes we've pre-buffered. */
282 uint32_t cbPreBuffered;
283 /** The play state. */
284 DRVAUDIOPLAYSTATE enmPlayState;
285 } Out;
286 } RT_UNION_NM(u);
287} DRVAUDIOSTREAM;
288/** Pointer to an extended stream structure. */
289typedef DRVAUDIOSTREAM *PDRVAUDIOSTREAM;
290
291/** Value for DRVAUDIOSTREAM::uMagic (Johann Sebastian Bach). */
292#define DRVAUDIOSTREAM_MAGIC UINT32_C(0x16850331)
293/** Value for DRVAUDIOSTREAM::uMagic after destruction */
294#define DRVAUDIOSTREAM_MAGIC_DEAD UINT32_C(0x17500728)
295
296
297/**
298 * Audio driver configuration data, tweakable via CFGM.
299 */
300typedef struct DRVAUDIOCFG
301{
302 /** PCM properties to use. */
303 PDMAUDIOPCMPROPS Props;
304 /** Whether using signed sample data or not.
305 * Needed in order to know whether there is a custom value set in CFGM or not.
306 * By default set to UINT8_MAX if not set to a custom value. */
307 uint8_t uSigned;
308 /** Whether swapping endianess of sample data or not.
309 * Needed in order to know whether there is a custom value set in CFGM or not.
310 * By default set to UINT8_MAX if not set to a custom value. */
311 uint8_t uSwapEndian;
312 /** Configures the period size (in ms).
313 * This value reflects the time in between each hardware interrupt on the
314 * backend (host) side. */
315 uint32_t uPeriodSizeMs;
316 /** Configures the (ring) buffer size (in ms). Often is a multiple of uPeriodMs. */
317 uint32_t uBufferSizeMs;
318 /** Configures the pre-buffering size (in ms).
319 * Time needed in buffer before the stream becomes active (pre buffering).
320 * The bigger this value is, the more latency for the stream will occur.
321 * Set to 0 to disable pre-buffering completely.
322 * By default set to UINT32_MAX if not set to a custom value. */
323 uint32_t uPreBufSizeMs;
324 /** The driver's debugging configuration. */
325 struct
326 {
327 /** Whether audio debugging is enabled or not. */
328 bool fEnabled;
329 /** Where to store the debugging files. */
330 char szPathOut[RTPATH_MAX];
331 } Dbg;
332} DRVAUDIOCFG;
333/** Pointer to tweakable audio configuration. */
334typedef DRVAUDIOCFG *PDRVAUDIOCFG;
335/** Pointer to const tweakable audio configuration. */
336typedef DRVAUDIOCFG const *PCDRVAUDIOCFG;
337
338
339/**
340 * Audio driver instance data.
341 *
342 * @implements PDMIAUDIOCONNECTOR
343 */
344typedef struct DRVAUDIO
345{
346 /** Read/Write critical section for guarding changes to pHostDrvAudio and
347 * BackendCfg during deteach/attach. Mostly taken in shared mode.
348 * @note Locking order: Must be entered after CritSectGlobals.
349 * @note Locking order: Must be entered after PDMAUDIOSTREAM::CritSect. */
350 RTCRITSECTRW CritSectHotPlug;
351 /** Critical section for protecting:
352 * - LstStreams
353 * - cStreams
354 * - In.fEnabled
355 * - In.cStreamsFree
356 * - Out.fEnabled
357 * - Out.cStreamsFree
358 * @note Locking order: Must be entered before PDMAUDIOSTREAM::CritSect.
359 * @note Locking order: Must be entered before CritSectHotPlug. */
360 RTCRITSECTRW CritSectGlobals;
361 /** List of audio streams (DRVAUDIOSTREAM). */
362 RTLISTANCHOR LstStreams;
363 /** Number of streams in the list. */
364 size_t cStreams;
365 struct
366 {
367 /** Whether this driver's input streams are enabled or not.
368 * This flag overrides all the attached stream statuses. */
369 bool fEnabled;
370 /** Max. number of free input streams.
371 * UINT32_MAX for unlimited streams. */
372 uint32_t cStreamsFree;
373 } In;
374 struct
375 {
376 /** Whether this driver's output streams are enabled or not.
377 * This flag overrides all the attached stream statuses. */
378 bool fEnabled;
379 /** Max. number of free output streams.
380 * UINT32_MAX for unlimited streams. */
381 uint32_t cStreamsFree;
382 } Out;
383
384 /** Audio configuration settings retrieved from the backend.
385 * The szName field is used for the DriverName config value till we get the
386 * authoritative name from the backend (only for logging). */
387 PDMAUDIOBACKENDCFG BackendCfg;
388 /** Our audio connector interface. */
389 PDMIAUDIOCONNECTOR IAudioConnector;
390 /** Interface used by the host backend. */
391 PDMIHOSTAUDIOPORT IHostAudioPort;
392 /** Pointer to the driver instance. */
393 PPDMDRVINS pDrvIns;
394 /** Pointer to audio driver below us. */
395 PPDMIHOSTAUDIO pHostDrvAudio;
396
397 /** Request pool if the backend needs it for async stream creation. */
398 RTREQPOOL hReqPool;
399
400#ifdef VBOX_WITH_STATISTICS
401 /** Statistics. */
402 struct
403 {
404 STAMCOUNTER TotalStreamsActive;
405 STAMCOUNTER TotalStreamsCreated;
406 STAMCOUNTER TotalFramesRead;
407 STAMCOUNTER TotalFramesIn;
408 STAMCOUNTER TotalBytesRead;
409 } Stats;
410#endif
411
412#ifdef VBOX_WITH_AUDIO_ENUM
413 /** Handle to the timer for delayed re-enumeration of backend devices. */
414 TMTIMERHANDLE hEnumTimer;
415 /** Unique name for the the disable-iteration timer. */
416 char szEnumTimerName[24];
417#endif
418
419 /** Input audio configuration values (static). */
420 DRVAUDIOCFG CfgIn;
421 /** Output audio configuration values (static). */
422 DRVAUDIOCFG CfgOut;
423} DRVAUDIO;
424/** Pointer to the instance data of an audio driver. */
425typedef DRVAUDIO *PDRVAUDIO;
426/** Pointer to const instance data of an audio driver. */
427typedef DRVAUDIO const *PCDRVAUDIO;
428
429
430/*********************************************************************************************************************************
431* Internal Functions *
432*********************************************************************************************************************************/
433static int drvAudioStreamControlInternalBackend(PDRVAUDIO pThis, PDRVAUDIOSTREAM pStreamEx, PDMAUDIOSTREAMCMD enmStreamCmd);
434static int drvAudioStreamControlInternal(PDRVAUDIO pThis, PDRVAUDIOSTREAM pStreamEx, PDMAUDIOSTREAMCMD enmStreamCmd);
435static int drvAudioStreamUninitInternal(PDRVAUDIO pThis, PDRVAUDIOSTREAM pStreamEx);
436static uint32_t drvAudioStreamRetainInternal(PDRVAUDIOSTREAM pStreamEx);
437static uint32_t drvAudioStreamReleaseInternal(PDRVAUDIO pThis, PDRVAUDIOSTREAM pStreamEx, bool fMayDestroy);
438static void drvAudioStreamResetInternal(PDRVAUDIOSTREAM pStreamEx);
439
440
441/** Buffer size for drvAudioStreamStatusToStr. */
442# define DRVAUDIO_STATUS_STR_MAX sizeof("BACKEND_CREATED BACKEND_READY ENABLED PAUSED PENDING_DISABLED NEED_REINIT 0x12345678")
443
444/**
445 * Converts an audio stream status to a string.
446 *
447 * @returns pszDst
448 * @param pszDst Buffer to convert into, at least minimum size is
449 * DRVAUDIO_STATUS_STR_MAX.
450 * @param fStatus Stream status flags to convert.
451 */
452static const char *drvAudioStreamStatusToStr(char pszDst[DRVAUDIO_STATUS_STR_MAX], uint32_t fStatus)
453{
454 static const struct
455 {
456 const char *pszMnemonic;
457 uint32_t cchMnemnonic;
458 uint32_t fFlag;
459 } s_aFlags[] =
460 {
461 { RT_STR_TUPLE("BACKEND_CREATED "), PDMAUDIOSTREAM_STS_BACKEND_CREATED },
462 { RT_STR_TUPLE("BACKEND_READY "), PDMAUDIOSTREAM_STS_BACKEND_READY },
463 { RT_STR_TUPLE("ENABLED "), PDMAUDIOSTREAM_STS_ENABLED },
464 { RT_STR_TUPLE("PAUSED "), PDMAUDIOSTREAM_STS_PAUSED },
465 { RT_STR_TUPLE("PENDING_DISABLE "), PDMAUDIOSTREAM_STS_PENDING_DISABLE },
466 { RT_STR_TUPLE("NEED_REINIT "), PDMAUDIOSTREAM_STS_NEED_REINIT },
467 };
468 if (!fStatus)
469 strcpy(pszDst, "NONE");
470 else
471 {
472 char *psz = pszDst;
473 for (size_t i = 0; i < RT_ELEMENTS(s_aFlags); i++)
474 if (fStatus & s_aFlags[i].fFlag)
475 {
476 memcpy(psz, s_aFlags[i].pszMnemonic, s_aFlags[i].cchMnemnonic);
477 psz += s_aFlags[i].cchMnemnonic;
478 fStatus &= ~s_aFlags[i].fFlag;
479 if (!fStatus)
480 break;
481 }
482 if (fStatus == 0)
483 psz[-1] = '\0';
484 else
485 psz += RTStrPrintf(psz, DRVAUDIO_STATUS_STR_MAX - (psz - pszDst), "%#x", fStatus);
486 Assert((uintptr_t)(psz - pszDst) <= DRVAUDIO_STATUS_STR_MAX);
487 }
488 return pszDst;
489}
490
491
492/**
493 * Get play state name string.
494 */
495static const char *drvAudioPlayStateName(DRVAUDIOPLAYSTATE enmState)
496{
497 switch (enmState)
498 {
499 case DRVAUDIOPLAYSTATE_INVALID: return "INVALID";
500 case DRVAUDIOPLAYSTATE_NOPLAY: return "NOPLAY";
501 case DRVAUDIOPLAYSTATE_PLAY: return "PLAY";
502 case DRVAUDIOPLAYSTATE_PLAY_PREBUF: return "PLAY_PREBUF";
503 case DRVAUDIOPLAYSTATE_PREBUF: return "PREBUF";
504 case DRVAUDIOPLAYSTATE_PREBUF_OVERDUE: return "PREBUF_OVERDUE";
505 case DRVAUDIOPLAYSTATE_PREBUF_SWITCHING: return "PREBUF_SWITCHING";
506 case DRVAUDIOPLAYSTATE_PREBUF_COMMITTING: return "PREBUF_COMMITTING";
507 case DRVAUDIOPLAYSTATE_END:
508 break;
509 }
510 return "BAD";
511}
512
513#ifdef LOG_ENABLED
514/**
515 * Get capture state name string.
516 */
517static const char *drvAudioCaptureStateName(DRVAUDIOCAPTURESTATE enmState)
518{
519 switch (enmState)
520 {
521 case DRVAUDIOCAPTURESTATE_INVALID: return "INVALID";
522 case DRVAUDIOCAPTURESTATE_NO_CAPTURE: return "NO_CAPTURE";
523 case DRVAUDIOCAPTURESTATE_CAPTURING: return "CAPTURING";
524 case DRVAUDIOCAPTURESTATE_PREBUF: return "PREBUF";
525 case DRVAUDIOCAPTURESTATE_END:
526 break;
527 }
528 return "BAD";
529}
530#endif
531
532/**
533 * Checks if the stream status is one that can be read from.
534 *
535 * @returns @c true if ready to be read from, @c false if not.
536 * @param fStatus Stream status to evaluate, PDMAUDIOSTREAM_STS_XXX.
537 * @note Not for backend statuses (use PDMAudioStrmStatusBackendCanRead)!
538 */
539DECLINLINE(bool) PDMAudioStrmStatusCanRead(uint32_t fStatus)
540{
541 PDMAUDIOSTREAM_STS_ASSERT_VALID(fStatus);
542 AssertReturn(!(fStatus & ~PDMAUDIOSTREAM_STS_VALID_MASK), false);
543 return (fStatus & ( PDMAUDIOSTREAM_STS_BACKEND_CREATED
544 | PDMAUDIOSTREAM_STS_ENABLED
545 | PDMAUDIOSTREAM_STS_PAUSED
546 | PDMAUDIOSTREAM_STS_NEED_REINIT))
547 == ( PDMAUDIOSTREAM_STS_BACKEND_CREATED
548 | PDMAUDIOSTREAM_STS_ENABLED);
549}
550
551/**
552 * Checks if the stream status is one that can be written to.
553 *
554 * @returns @c true if ready to be written to, @c false if not.
555 * @param fStatus Stream status to evaluate, PDMAUDIOSTREAM_STS_XXX.
556 * @note Not for backend statuses (use PDMAudioStrmStatusBackendCanWrite)!
557 */
558DECLINLINE(bool) PDMAudioStrmStatusCanWrite(uint32_t fStatus)
559{
560 PDMAUDIOSTREAM_STS_ASSERT_VALID(fStatus);
561 AssertReturn(!(fStatus & ~PDMAUDIOSTREAM_STS_VALID_MASK), false);
562 return (fStatus & ( PDMAUDIOSTREAM_STS_BACKEND_CREATED
563 | PDMAUDIOSTREAM_STS_ENABLED
564 | PDMAUDIOSTREAM_STS_PAUSED
565 | PDMAUDIOSTREAM_STS_PENDING_DISABLE
566 | PDMAUDIOSTREAM_STS_NEED_REINIT))
567 == ( PDMAUDIOSTREAM_STS_BACKEND_CREATED
568 | PDMAUDIOSTREAM_STS_ENABLED);
569}
570
571/**
572 * Checks if the stream status is a ready-to-operate one.
573 *
574 * @returns @c true if ready to operate, @c false if not.
575 * @param fStatus Stream status to evaluate, PDMAUDIOSTREAM_STS_XXX.
576 * @note Not for backend statuses!
577 */
578DECLINLINE(bool) PDMAudioStrmStatusIsReady(uint32_t fStatus)
579{
580 PDMAUDIOSTREAM_STS_ASSERT_VALID(fStatus);
581 AssertReturn(!(fStatus & ~PDMAUDIOSTREAM_STS_VALID_MASK), false);
582 return (fStatus & ( PDMAUDIOSTREAM_STS_BACKEND_CREATED
583 | PDMAUDIOSTREAM_STS_ENABLED
584 | PDMAUDIOSTREAM_STS_NEED_REINIT))
585 == ( PDMAUDIOSTREAM_STS_BACKEND_CREATED
586 | PDMAUDIOSTREAM_STS_ENABLED);
587}
588
589
590/**
591 * Wrapper around PDMIHOSTAUDIO::pfnStreamGetStatus and checks the result.
592 *
593 * @returns A PDMHOSTAUDIOSTREAMSTATE value.
594 * @param pThis Pointer to the DrvAudio instance data.
595 * @param pStreamEx The stream to get the backend status for.
596 */
597DECLINLINE(PDMHOSTAUDIOSTREAMSTATE) drvAudioStreamGetBackendState(PDRVAUDIO pThis, PDRVAUDIOSTREAM pStreamEx)
598{
599 if (pThis->pHostDrvAudio)
600 {
601 PDMHOSTAUDIOSTREAMSTATE enmState = pThis->pHostDrvAudio->pfnStreamGetState(pThis->pHostDrvAudio, pStreamEx->pBackend);
602 Log9Func(("%s: %s\n", pStreamEx->Core.szName, PDMHostAudioStreamStateGetName(enmState) ));
603 Assert( enmState > PDMHOSTAUDIOSTREAMSTATE_INVALID
604 && enmState < PDMHOSTAUDIOSTREAMSTATE_END
605 && (enmState != PDMHOSTAUDIOSTREAMSTATE_DRAINING || pStreamEx->Guest.Cfg.enmDir == PDMAUDIODIR_OUT));
606 return enmState;
607 }
608 Log9Func(("%s: not-working\n", pStreamEx->Core.szName));
609 return PDMHOSTAUDIOSTREAMSTATE_NOT_WORKING;
610}
611
612
613/**
614 * Worker for drvAudioStreamProcessBackendStateChange that completes draining.
615 */
616DECLINLINE(void) drvAudioStreamProcessBackendStateChangeWasDraining(PDRVAUDIOSTREAM pStreamEx)
617{
618 Log(("drvAudioStreamProcessBackendStateChange: Stream '%s': Done draining - disabling stream.\n", pStreamEx->Core.szName));
619 pStreamEx->fStatus &= ~(PDMAUDIOSTREAM_STS_ENABLED | PDMAUDIOSTREAM_STS_PENDING_DISABLE);
620 drvAudioStreamResetInternal(pStreamEx);
621}
622
623
624/**
625 * Processes backend state change.
626 *
627 * @returns the new state value.
628 */
629static PDMHOSTAUDIOSTREAMSTATE drvAudioStreamProcessBackendStateChange(PDRVAUDIOSTREAM pStreamEx,
630 PDMHOSTAUDIOSTREAMSTATE enmNewState,
631 PDMHOSTAUDIOSTREAMSTATE enmOldState)
632{
633 PDMAUDIODIR const enmDir = pStreamEx->Guest.Cfg.enmDir;
634#ifdef LOG_ENABLED
635 DRVAUDIOPLAYSTATE const enmPlayState = enmDir == PDMAUDIODIR_OUT
636 ? pStreamEx->Out.enmPlayState : DRVAUDIOPLAYSTATE_INVALID;
637 DRVAUDIOCAPTURESTATE const enmCaptureState = enmDir == PDMAUDIODIR_OUT
638 ? pStreamEx->In.enmCaptureState : DRVAUDIOCAPTURESTATE_INVALID;
639#endif
640 Assert(enmNewState != enmOldState);
641 Assert(enmOldState > PDMHOSTAUDIOSTREAMSTATE_INVALID && enmOldState < PDMHOSTAUDIOSTREAMSTATE_END);
642 AssertReturn(enmNewState > PDMHOSTAUDIOSTREAMSTATE_INVALID && enmNewState < PDMHOSTAUDIOSTREAMSTATE_END, enmOldState);
643
644 /*
645 * Figure out what happend and how that reflects on the playback state and stuff.
646 */
647 switch (enmNewState)
648 {
649 case PDMHOSTAUDIOSTREAMSTATE_INITIALIZING:
650 /* Guess we're switching device. Nothing to do because the backend will tell us, right? */
651 break;
652
653 case PDMHOSTAUDIOSTREAMSTATE_NOT_WORKING:
654 case PDMHOSTAUDIOSTREAMSTATE_INACTIVE:
655 /* The stream has stopped working or is inactive. Switch stop any draining & to noplay mode. */
656 if (pStreamEx->fStatus & PDMAUDIOSTREAM_STS_PENDING_DISABLE)
657 drvAudioStreamProcessBackendStateChangeWasDraining(pStreamEx);
658 if (enmDir == PDMAUDIODIR_OUT)
659 pStreamEx->Out.enmPlayState = DRVAUDIOPLAYSTATE_NOPLAY;
660 else
661 pStreamEx->In.enmCaptureState = DRVAUDIOCAPTURESTATE_NO_CAPTURE;
662 break;
663
664 case PDMHOSTAUDIOSTREAMSTATE_OKAY:
665 switch (enmOldState)
666 {
667 case PDMHOSTAUDIOSTREAMSTATE_INITIALIZING:
668 /* Should be taken care of elsewhere, so do nothing. */
669 break;
670
671 case PDMHOSTAUDIOSTREAMSTATE_NOT_WORKING:
672 case PDMHOSTAUDIOSTREAMSTATE_INACTIVE:
673 /* Go back to pre-buffering/playing depending on whether it is enabled
674 or not, resetting the stream state. */
675 drvAudioStreamResetInternal(pStreamEx);
676 break;
677
678 case PDMHOSTAUDIOSTREAMSTATE_DRAINING:
679 /* Complete the draining. May race the iterate code. */
680 if (pStreamEx->fStatus & PDMAUDIOSTREAM_STS_PENDING_DISABLE)
681 drvAudioStreamProcessBackendStateChangeWasDraining(pStreamEx);
682 break;
683
684 /* no default: */
685 case PDMHOSTAUDIOSTREAMSTATE_OKAY: /* impossible */
686 case PDMHOSTAUDIOSTREAMSTATE_INVALID:
687 case PDMHOSTAUDIOSTREAMSTATE_END:
688 case PDMHOSTAUDIOSTREAMSTATE_32BIT_HACK:
689 break;
690 }
691 break;
692
693 case PDMHOSTAUDIOSTREAMSTATE_DRAINING:
694 /* We do all we need to do when issuing the DRAIN command. */
695 Assert(pStreamEx->fStatus & PDMAUDIOSTREAM_STS_PENDING_DISABLE);
696 break;
697
698 /* no default: */
699 case PDMHOSTAUDIOSTREAMSTATE_INVALID:
700 case PDMHOSTAUDIOSTREAMSTATE_END:
701 case PDMHOSTAUDIOSTREAMSTATE_32BIT_HACK:
702 break;
703 }
704
705 if (enmDir == PDMAUDIODIR_OUT)
706 LogFunc(("Output stream '%s': %s/%s -> %s/%s\n", pStreamEx->Core.szName,
707 PDMHostAudioStreamStateGetName(enmOldState), drvAudioPlayStateName(enmPlayState),
708 PDMHostAudioStreamStateGetName(enmNewState), drvAudioPlayStateName(pStreamEx->Out.enmPlayState) ));
709 else
710 LogFunc(("Input stream '%s': %s/%s -> %s/%s\n", pStreamEx->Core.szName,
711 PDMHostAudioStreamStateGetName(enmOldState), drvAudioCaptureStateName(enmCaptureState),
712 PDMHostAudioStreamStateGetName(enmNewState), drvAudioCaptureStateName(pStreamEx->In.enmCaptureState) ));
713
714 pStreamEx->enmLastBackendState = enmNewState;
715 return enmNewState;
716}
717
718
719/**
720 * This gets the backend state and handles changes compared to
721 * DRVAUDIOSTREAM::enmLastBackendState (updated).
722 *
723 * @returns A PDMHOSTAUDIOSTREAMSTATE value.
724 * @param pThis Pointer to the DrvAudio instance data.
725 * @param pStreamEx The stream to get the backend status for.
726 */
727DECLINLINE(PDMHOSTAUDIOSTREAMSTATE) drvAudioStreamGetBackendStateAndProcessChanges(PDRVAUDIO pThis, PDRVAUDIOSTREAM pStreamEx)
728{
729 PDMHOSTAUDIOSTREAMSTATE const enmBackendState = drvAudioStreamGetBackendState(pThis, pStreamEx);
730 if (pStreamEx->enmLastBackendState == enmBackendState)
731 return enmBackendState;
732 return drvAudioStreamProcessBackendStateChange(pStreamEx, enmBackendState, pStreamEx->enmLastBackendState);
733}
734
735
736#ifdef VBOX_WITH_AUDIO_ENUM
737/**
738 * Enumerates all host audio devices.
739 *
740 * This functionality might not be implemented by all backends and will return
741 * VERR_NOT_SUPPORTED if not being supported.
742 *
743 * @note Must not hold the driver's critical section!
744 *
745 * @returns VBox status code.
746 * @param pThis Driver instance to be called.
747 * @param fLog Whether to print the enumerated device to the release log or not.
748 * @param pDevEnum Where to store the device enumeration.
749 *
750 * @remarks This is currently ONLY used for release logging.
751 */
752static DECLCALLBACK(int) drvAudioDevicesEnumerateInternal(PDRVAUDIO pThis, bool fLog, PPDMAUDIOHOSTENUM pDevEnum)
753{
754 RTCritSectRwEnterShared(&pThis->CritSectHotPlug);
755
756 int rc;
757
758 /*
759 * If the backend supports it, do a device enumeration.
760 */
761 if (pThis->pHostDrvAudio->pfnGetDevices)
762 {
763 PDMAUDIOHOSTENUM DevEnum;
764 rc = pThis->pHostDrvAudio->pfnGetDevices(pThis->pHostDrvAudio, &DevEnum);
765 if (RT_SUCCESS(rc))
766 {
767 if (fLog)
768 {
769 LogRel(("Audio: Found %RU16 devices for driver '%s'\n", DevEnum.cDevices, pThis->BackendCfg.szName));
770
771 PPDMAUDIOHOSTDEV pDev;
772 RTListForEach(&DevEnum.LstDevices, pDev, PDMAUDIOHOSTDEV, ListEntry)
773 {
774 char szFlags[PDMAUDIOHOSTDEV_MAX_FLAGS_STRING_LEN];
775 LogRel(("Audio: Device '%s'%s%s%s:\n"
776 "Audio: Usage = %s\n"
777 "Audio: Flags = %s\n"
778 "Audio: Input channels = %RU8\n"
779 "Audio: Output channels = %RU8\n",
780 pDev->szName, pDev->pszId ? " (ID '" : "", pDev->pszId ? pDev->pszId : "", pDev->pszId ? "')" : "",
781 PDMAudioDirGetName(pDev->enmUsage), PDMAudioHostDevFlagsToString(szFlags, pDev->fFlags),
782 pDev->cMaxInputChannels, pDev->cMaxOutputChannels));
783 }
784 }
785
786 if (pDevEnum)
787 rc = PDMAudioHostEnumCopy(pDevEnum, &DevEnum, PDMAUDIODIR_INVALID /*all*/, true /*fOnlyCoreData*/);
788
789 PDMAudioHostEnumDelete(&DevEnum);
790 }
791 else
792 {
793 if (fLog)
794 LogRel(("Audio: Device enumeration for driver '%s' failed with %Rrc\n", pThis->BackendCfg.szName, rc));
795 /* Not fatal. */
796 }
797 }
798 else
799 {
800 rc = VERR_NOT_SUPPORTED;
801
802 if (fLog)
803 LogRel2(("Audio: Host driver '%s' does not support audio device enumeration, skipping\n", pThis->BackendCfg.szName));
804 }
805
806 RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
807 LogFunc(("Returning %Rrc\n", rc));
808 return rc;
809}
810#endif /* VBOX_WITH_AUDIO_ENUM */
811
812
813/*********************************************************************************************************************************
814* PDMIAUDIOCONNECTOR *
815*********************************************************************************************************************************/
816
817/**
818 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnEnable}
819 */
820static DECLCALLBACK(int) drvAudioEnable(PPDMIAUDIOCONNECTOR pInterface, PDMAUDIODIR enmDir, bool fEnable)
821{
822 PDRVAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVAUDIO, IAudioConnector);
823 AssertPtr(pThis);
824 LogFlowFunc(("enmDir=%s fEnable=%d\n", PDMAudioDirGetName(enmDir), fEnable));
825
826 /*
827 * Figure which status flag variable is being updated.
828 */
829 bool *pfEnabled;
830 if (enmDir == PDMAUDIODIR_IN)
831 pfEnabled = &pThis->In.fEnabled;
832 else if (enmDir == PDMAUDIODIR_OUT)
833 pfEnabled = &pThis->Out.fEnabled;
834 else
835 AssertFailedReturn(VERR_INVALID_PARAMETER);
836
837 /*
838 * Grab the driver wide lock and check it. Ignore call if no change.
839 */
840 int rc = RTCritSectRwEnterExcl(&pThis->CritSectGlobals);
841 AssertRCReturn(rc, rc);
842
843 if (fEnable != *pfEnabled)
844 {
845 LogRel(("Audio: %s %s for driver '%s'\n",
846 fEnable ? "Enabling" : "Disabling", enmDir == PDMAUDIODIR_IN ? "input" : "output", pThis->BackendCfg.szName));
847
848 /*
849 * When enabling, we must update flag before calling drvAudioStreamControlInternalBackend.
850 */
851 if (fEnable)
852 *pfEnabled = true;
853
854 /*
855 * Update the backend status for the streams in the given direction.
856 *
857 * The pThis->Out.fEnable / pThis->In.fEnable status flags only reflect in the
858 * direction of the backend, drivers and devices above us in the chain does not
859 * know about this. When disabled playback goes to /dev/null and we capture
860 * only silence. This means pStreamEx->fStatus holds the nominal status
861 * and we'll use it to restore the operation. (See also @bugref{9882}.)
862 */
863 PDRVAUDIOSTREAM pStreamEx;
864 RTListForEach(&pThis->LstStreams, pStreamEx, DRVAUDIOSTREAM, ListEntry)
865 {
866 if (pStreamEx->Core.enmDir == enmDir)
867 {
868 /*
869 * When (re-)enabling a stream, clear the disabled warning bit again.
870 */
871 if (fEnable)
872 pStreamEx->Core.fWarningsShown &= ~PDMAUDIOSTREAM_WARN_FLAGS_DISABLED;
873
874 /*
875 * We don't need to do anything unless the stream is enabled.
876 * Paused includes enabled, as does draining, but we only want the former.
877 */
878 uint32_t const fStatus = pStreamEx->fStatus;
879 if (fStatus & PDMAUDIOSTREAM_STS_ENABLED)
880 {
881 const char *pszOperation;
882 int rc2;
883 if (fEnable)
884 {
885 if (!(fStatus & PDMAUDIOSTREAM_STS_PENDING_DISABLE))
886 {
887 /** @todo r=bird: We need to redo pre-buffering OR switch to
888 * DRVAUDIOPLAYSTATE_PREBUF_SWITCHING playback mode when disabling
889 * output streams. The former is preferred if associated with
890 * reporting the stream as INACTIVE. */
891 rc2 = drvAudioStreamControlInternalBackend(pThis, pStreamEx, PDMAUDIOSTREAMCMD_ENABLE);
892 pszOperation = "enable";
893 if (RT_SUCCESS(rc2) && (fStatus & PDMAUDIOSTREAM_STS_PAUSED))
894 {
895 rc2 = drvAudioStreamControlInternalBackend(pThis, pStreamEx, PDMAUDIOSTREAMCMD_PAUSE);
896 pszOperation = "pause";
897 }
898 }
899 else
900 {
901 rc2 = VINF_SUCCESS;
902 pszOperation = NULL;
903 }
904 }
905 else
906 {
907 rc2 = drvAudioStreamControlInternalBackend(pThis, pStreamEx, PDMAUDIOSTREAMCMD_DISABLE);
908 pszOperation = "disable";
909 }
910 if (RT_FAILURE(rc2))
911 {
912 LogRel(("Audio: Failed to %s %s stream '%s': %Rrc\n",
913 pszOperation, enmDir == PDMAUDIODIR_IN ? "input" : "output", pStreamEx->Core.szName, rc2));
914 if (RT_SUCCESS(rc))
915 rc = rc2; /** @todo r=bird: This isn't entirely helpful to the caller since we'll update the status
916 * regardless of the status code we return. And anyway, there is nothing that can be done
917 * about individual stream by the caller... */
918 }
919 }
920 }
921 }
922
923 /*
924 * When disabling, we must update the status flag after the
925 * drvAudioStreamControlInternalBackend(DISABLE) calls.
926 */
927 *pfEnabled = fEnable;
928 }
929
930 RTCritSectRwLeaveExcl(&pThis->CritSectGlobals);
931 LogFlowFuncLeaveRC(rc);
932 return rc;
933}
934
935
936/**
937 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnIsEnabled}
938 */
939static DECLCALLBACK(bool) drvAudioIsEnabled(PPDMIAUDIOCONNECTOR pInterface, PDMAUDIODIR enmDir)
940{
941 PDRVAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVAUDIO, IAudioConnector);
942 AssertPtr(pThis);
943 int rc = RTCritSectRwEnterShared(&pThis->CritSectGlobals);
944 AssertRCReturn(rc, false);
945
946 bool fEnabled;
947 if (enmDir == PDMAUDIODIR_IN)
948 fEnabled = pThis->In.fEnabled;
949 else if (enmDir == PDMAUDIODIR_OUT)
950 fEnabled = pThis->Out.fEnabled;
951 else
952 AssertFailedStmt(fEnabled = false);
953
954 RTCritSectRwLeaveShared(&pThis->CritSectGlobals);
955 return fEnabled;
956}
957
958
959/**
960 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnGetConfig}
961 */
962static DECLCALLBACK(int) drvAudioGetConfig(PPDMIAUDIOCONNECTOR pInterface, PPDMAUDIOBACKENDCFG pCfg)
963{
964 PDRVAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVAUDIO, IAudioConnector);
965 AssertPtr(pThis);
966 AssertPtrReturn(pCfg, VERR_INVALID_POINTER);
967 int rc = RTCritSectRwEnterShared(&pThis->CritSectHotPlug);
968 AssertRCReturn(rc, rc);
969
970 if (pThis->pHostDrvAudio)
971 rc = pThis->pHostDrvAudio->pfnGetConfig(pThis->pHostDrvAudio, pCfg);
972 else
973 rc = VERR_PDM_NO_ATTACHED_DRIVER;
974
975 RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
976 LogFlowFuncLeaveRC(rc);
977 return rc;
978}
979
980
981/**
982 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnGetStatus}
983 */
984static DECLCALLBACK(PDMAUDIOBACKENDSTS) drvAudioGetStatus(PPDMIAUDIOCONNECTOR pInterface, PDMAUDIODIR enmDir)
985{
986 PDRVAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVAUDIO, IAudioConnector);
987 AssertPtr(pThis);
988 int rc = RTCritSectRwEnterShared(&pThis->CritSectHotPlug);
989 AssertRCReturn(rc, PDMAUDIOBACKENDSTS_UNKNOWN);
990
991 PDMAUDIOBACKENDSTS fBackendStatus;
992 if (pThis->pHostDrvAudio)
993 {
994 if (pThis->pHostDrvAudio->pfnGetStatus)
995 fBackendStatus = pThis->pHostDrvAudio->pfnGetStatus(pThis->pHostDrvAudio, enmDir);
996 else
997 fBackendStatus = PDMAUDIOBACKENDSTS_UNKNOWN;
998 }
999 else
1000 fBackendStatus = PDMAUDIOBACKENDSTS_NOT_ATTACHED;
1001
1002 RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
1003 LogFlowFunc(("LEAVE - %#x\n", fBackendStatus));
1004 return fBackendStatus;
1005}
1006
1007
1008/**
1009 * Frees an audio stream and its allocated resources.
1010 *
1011 * @param pStreamEx Audio stream to free. After this call the pointer will
1012 * not be valid anymore.
1013 */
1014static void drvAudioStreamFree(PDRVAUDIOSTREAM pStreamEx)
1015{
1016 if (pStreamEx)
1017 {
1018 LogFunc(("[%s]\n", pStreamEx->Core.szName));
1019 Assert(pStreamEx->Core.uMagic == PDMAUDIOSTREAM_MAGIC);
1020 Assert(pStreamEx->uMagic == DRVAUDIOSTREAM_MAGIC);
1021
1022 pStreamEx->Core.uMagic = ~PDMAUDIOSTREAM_MAGIC;
1023 pStreamEx->pBackend = NULL;
1024 pStreamEx->uMagic = DRVAUDIOSTREAM_MAGIC_DEAD;
1025
1026 RTCritSectDelete(&pStreamEx->Core.CritSect);
1027
1028 RTMemFree(pStreamEx);
1029 }
1030}
1031
1032
1033/**
1034 * Adjusts the request stream configuration, applying our settings.
1035 *
1036 * This also does some basic validations.
1037 *
1038 * Used by both the stream creation and stream configuration hinting code.
1039 *
1040 * @returns VBox status code.
1041 * @param pThis Pointer to the DrvAudio instance data.
1042 * @param pCfgReq The request configuration that should be adjusted.
1043 * @param pszName Stream name to use when logging warnings and errors.
1044 */
1045static int drvAudioStreamAdjustConfig(PCDRVAUDIO pThis, PPDMAUDIOSTREAMCFG pCfgReq, const char *pszName)
1046{
1047 /* Get the right configuration for the stream to be created. */
1048 PCDRVAUDIOCFG pDrvCfg = pCfgReq->enmDir == PDMAUDIODIR_IN ? &pThis->CfgIn: &pThis->CfgOut;
1049
1050 /* Fill in the tweakable parameters into the requested host configuration.
1051 * All parameters in principle can be changed and returned by the backend via the acquired configuration. */
1052
1053 /*
1054 * PCM
1055 */
1056 if (PDMAudioPropsSampleSize(&pDrvCfg->Props) != 0) /* Anything set via custom extra-data? */
1057 {
1058 PDMAudioPropsSetSampleSize(&pCfgReq->Props, PDMAudioPropsSampleSize(&pDrvCfg->Props));
1059 LogRel2(("Audio: Using custom sample size of %RU8 bytes for stream '%s'\n",
1060 PDMAudioPropsSampleSize(&pCfgReq->Props), pszName));
1061 }
1062
1063 if (pDrvCfg->Props.uHz) /* Anything set via custom extra-data? */
1064 {
1065 pCfgReq->Props.uHz = pDrvCfg->Props.uHz;
1066 LogRel2(("Audio: Using custom Hz rate %RU32 for stream '%s'\n", pCfgReq->Props.uHz, pszName));
1067 }
1068
1069 if (pDrvCfg->uSigned != UINT8_MAX) /* Anything set via custom extra-data? */
1070 {
1071 pCfgReq->Props.fSigned = RT_BOOL(pDrvCfg->uSigned);
1072 LogRel2(("Audio: Using custom %s sample format for stream '%s'\n",
1073 pCfgReq->Props.fSigned ? "signed" : "unsigned", pszName));
1074 }
1075
1076 if (pDrvCfg->uSwapEndian != UINT8_MAX) /* Anything set via custom extra-data? */
1077 {
1078 pCfgReq->Props.fSwapEndian = RT_BOOL(pDrvCfg->uSwapEndian);
1079 LogRel2(("Audio: Using custom %s endianess for samples of stream '%s'\n",
1080 pCfgReq->Props.fSwapEndian ? "swapped" : "original", pszName));
1081 }
1082
1083 if (PDMAudioPropsChannels(&pDrvCfg->Props) != 0) /* Anything set via custom extra-data? */
1084 {
1085 PDMAudioPropsSetChannels(&pCfgReq->Props, PDMAudioPropsChannels(&pDrvCfg->Props));
1086 LogRel2(("Audio: Using custom %RU8 channel(s) for stream '%s'\n", PDMAudioPropsChannels(&pDrvCfg->Props), pszName));
1087 }
1088
1089 /* Validate PCM properties. */
1090 if (!AudioHlpPcmPropsAreValid(&pCfgReq->Props))
1091 {
1092 LogRel(("Audio: Invalid custom PCM properties set for stream '%s', cannot create stream\n", pszName));
1093 return VERR_INVALID_PARAMETER;
1094 }
1095
1096 /*
1097 * Period size
1098 */
1099 const char *pszWhat = "device-specific";
1100 if (pDrvCfg->uPeriodSizeMs)
1101 {
1102 pCfgReq->Backend.cFramesPeriod = PDMAudioPropsMilliToFrames(&pCfgReq->Props, pDrvCfg->uPeriodSizeMs);
1103 pszWhat = "custom";
1104 }
1105
1106 if (!pCfgReq->Backend.cFramesPeriod) /* Set default period size if nothing explicitly is set. */
1107 {
1108 pCfgReq->Backend.cFramesPeriod = PDMAudioPropsMilliToFrames(&pCfgReq->Props, 150 /*ms*/);
1109 pszWhat = "default";
1110 }
1111
1112 LogRel2(("Audio: Using %s period size %RU64 ms / %RU32 frames for stream '%s'\n",
1113 pszWhat, PDMAudioPropsFramesToMilli(&pCfgReq->Props, pCfgReq->Backend.cFramesPeriod),
1114 pCfgReq->Backend.cFramesPeriod, pszName));
1115
1116 /*
1117 * Buffer size
1118 */
1119 pszWhat = "device-specific";
1120 if (pDrvCfg->uBufferSizeMs)
1121 {
1122 pCfgReq->Backend.cFramesBufferSize = PDMAudioPropsMilliToFrames(&pCfgReq->Props, pDrvCfg->uBufferSizeMs);
1123 pszWhat = "custom";
1124 }
1125
1126 if (!pCfgReq->Backend.cFramesBufferSize) /* Set default buffer size if nothing explicitly is set. */
1127 {
1128 pCfgReq->Backend.cFramesBufferSize = PDMAudioPropsMilliToFrames(&pCfgReq->Props, 300 /*ms*/);
1129 pszWhat = "default";
1130 }
1131
1132 LogRel2(("Audio: Using %s buffer size %RU64 ms / %RU32 frames for stream '%s'\n",
1133 pszWhat, PDMAudioPropsFramesToMilli(&pCfgReq->Props, pCfgReq->Backend.cFramesBufferSize),
1134 pCfgReq->Backend.cFramesBufferSize, pszName));
1135
1136 /*
1137 * Pre-buffering size
1138 */
1139 pszWhat = "device-specific";
1140 if (pDrvCfg->uPreBufSizeMs != UINT32_MAX) /* Anything set via global / per-VM extra-data? */
1141 {
1142 pCfgReq->Backend.cFramesPreBuffering = PDMAudioPropsMilliToFrames(&pCfgReq->Props, pDrvCfg->uPreBufSizeMs);
1143 pszWhat = "custom";
1144 }
1145 else /* No, then either use the default or device-specific settings (if any). */
1146 {
1147 if (pCfgReq->Backend.cFramesPreBuffering == UINT32_MAX) /* Set default pre-buffering size if nothing explicitly is set. */
1148 {
1149 /* Pre-buffer 66% of the buffer for output streams, but only 50% for input. Capping both at 200ms. */
1150 if (pCfgReq->enmDir == PDMAUDIODIR_OUT)
1151 pCfgReq->Backend.cFramesPreBuffering = pCfgReq->Backend.cFramesBufferSize * 2 / 3;
1152 else
1153 pCfgReq->Backend.cFramesPreBuffering = pCfgReq->Backend.cFramesBufferSize / 2;
1154 uint32_t const cFramesMax = PDMAudioPropsMilliToFrames(&pCfgReq->Props, 200);
1155 pCfgReq->Backend.cFramesPreBuffering = RT_MIN(pCfgReq->Backend.cFramesPreBuffering, cFramesMax);
1156 pszWhat = "default";
1157 }
1158 }
1159
1160 LogRel2(("Audio: Using %s pre-buffering size %RU64 ms / %RU32 frames for stream '%s'\n",
1161 pszWhat, PDMAudioPropsFramesToMilli(&pCfgReq->Props, pCfgReq->Backend.cFramesPreBuffering),
1162 pCfgReq->Backend.cFramesPreBuffering, pszName));
1163
1164 /*
1165 * Validate input.
1166 */
1167 if (pCfgReq->Backend.cFramesBufferSize < pCfgReq->Backend.cFramesPeriod)
1168 {
1169 LogRel(("Audio: Error for stream '%s': Buffering size (%RU64ms) must not be smaller than the period size (%RU64ms)\n",
1170 pszName, PDMAudioPropsFramesToMilli(&pCfgReq->Props, pCfgReq->Backend.cFramesBufferSize),
1171 PDMAudioPropsFramesToMilli(&pCfgReq->Props, pCfgReq->Backend.cFramesPeriod)));
1172 return VERR_INVALID_PARAMETER;
1173 }
1174
1175 if ( pCfgReq->Backend.cFramesPreBuffering != UINT32_MAX /* Custom pre-buffering set? */
1176 && pCfgReq->Backend.cFramesPreBuffering)
1177 {
1178 if (pCfgReq->Backend.cFramesBufferSize < pCfgReq->Backend.cFramesPreBuffering)
1179 {
1180 LogRel(("Audio: Error for stream '%s': Buffering size (%RU64ms) must not be smaller than the pre-buffering size (%RU64ms)\n",
1181 pszName, PDMAudioPropsFramesToMilli(&pCfgReq->Props, pCfgReq->Backend.cFramesPreBuffering),
1182 PDMAudioPropsFramesToMilli(&pCfgReq->Props, pCfgReq->Backend.cFramesBufferSize)));
1183 return VERR_INVALID_PARAMETER;
1184 }
1185 }
1186
1187 return VINF_SUCCESS;
1188}
1189
1190
1191/**
1192 * Worker thread function for drvAudioStreamConfigHint that's used when
1193 * PDMAUDIOBACKEND_F_ASYNC_HINT is in effect.
1194 */
1195static DECLCALLBACK(void) drvAudioStreamConfigHintWorker(PDRVAUDIO pThis, PPDMAUDIOSTREAMCFG pCfg)
1196{
1197 LogFlowFunc(("pThis=%p pCfg=%p\n", pThis, pCfg));
1198 AssertPtrReturnVoid(pCfg);
1199 int rc = RTCritSectRwEnterShared(&pThis->CritSectHotPlug);
1200 AssertRCReturnVoid(rc);
1201
1202 PPDMIHOSTAUDIO const pHostDrvAudio = pThis->pHostDrvAudio;
1203 if (pHostDrvAudio)
1204 {
1205 AssertPtr(pHostDrvAudio->pfnStreamConfigHint);
1206 if (pHostDrvAudio->pfnStreamConfigHint)
1207 pHostDrvAudio->pfnStreamConfigHint(pHostDrvAudio, pCfg);
1208 }
1209 PDMAudioStrmCfgFree(pCfg);
1210
1211 RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
1212 LogFlowFunc(("returns\n"));
1213}
1214
1215
1216/**
1217 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnStreamConfigHint}
1218 */
1219static DECLCALLBACK(void) drvAudioStreamConfigHint(PPDMIAUDIOCONNECTOR pInterface, PPDMAUDIOSTREAMCFG pCfg)
1220{
1221 PDRVAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVAUDIO, IAudioConnector);
1222 AssertReturnVoid(pCfg->enmDir == PDMAUDIODIR_IN || pCfg->enmDir == PDMAUDIODIR_OUT);
1223
1224 int rc = RTCritSectRwEnterShared(&pThis->CritSectHotPlug);
1225 AssertRCReturnVoid(rc);
1226
1227 /*
1228 * Don't do anything unless the backend has a pfnStreamConfigHint method
1229 * and the direction is currently enabled.
1230 */
1231 if ( pThis->pHostDrvAudio
1232 && pThis->pHostDrvAudio->pfnStreamConfigHint)
1233 {
1234 if (pCfg->enmDir == PDMAUDIODIR_OUT ? pThis->Out.fEnabled : pThis->In.fEnabled)
1235 {
1236 /*
1237 * Adjust the configuration (applying out settings) then call the backend driver.
1238 */
1239 rc = drvAudioStreamAdjustConfig(pThis, pCfg, pCfg->szName);
1240 AssertLogRelRC(rc);
1241 if (RT_SUCCESS(rc))
1242 {
1243 rc = VERR_CALLBACK_RETURN;
1244 if (pThis->BackendCfg.fFlags & PDMAUDIOBACKEND_F_ASYNC_HINT)
1245 {
1246 PPDMAUDIOSTREAMCFG pDupCfg = PDMAudioStrmCfgDup(pCfg);
1247 if (pDupCfg)
1248 {
1249 rc = RTReqPoolCallVoidNoWait(pThis->hReqPool, (PFNRT)drvAudioStreamConfigHintWorker, 2, pThis, pDupCfg);
1250 if (RT_SUCCESS(rc))
1251 LogFlowFunc(("Asynchronous call running on worker thread.\n"));
1252 else
1253 PDMAudioStrmCfgFree(pDupCfg);
1254 }
1255 }
1256 if (RT_FAILURE_NP(rc))
1257 {
1258 LogFlowFunc(("Doing synchronous call...\n"));
1259 pThis->pHostDrvAudio->pfnStreamConfigHint(pThis->pHostDrvAudio, pCfg);
1260 }
1261 }
1262 }
1263 else
1264 LogFunc(("Ignoring hint because direction is not currently enabled\n"));
1265 }
1266 else
1267 LogFlowFunc(("Ignoring hint because backend has no pfnStreamConfigHint method.\n"));
1268
1269 RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
1270}
1271
1272
1273/**
1274 * Common worker for synchronizing the ENABLED and PAUSED status bits with the
1275 * backend after it becomes ready.
1276 *
1277 * Used by async init and re-init.
1278 *
1279 * @note Is sometimes called w/o having entered DRVAUDIO::CritSectHotPlug.
1280 * Caller must however own the stream critsect.
1281 */
1282static int drvAudioStreamUpdateBackendOnStatus(PDRVAUDIO pThis, PDRVAUDIOSTREAM pStreamEx, const char *pszWhen)
1283{
1284 int rc = VINF_SUCCESS;
1285 if (pStreamEx->fStatus & PDMAUDIOSTREAM_STS_ENABLED)
1286 {
1287 rc = drvAudioStreamControlInternalBackend(pThis, pStreamEx, PDMAUDIOSTREAMCMD_ENABLE);
1288 if (RT_SUCCESS(rc))
1289 {
1290 if (pStreamEx->fStatus & PDMAUDIOSTREAM_STS_PAUSED)
1291 {
1292 rc = drvAudioStreamControlInternalBackend(pThis, pStreamEx, PDMAUDIOSTREAMCMD_PAUSE);
1293 if (RT_FAILURE(rc))
1294 LogRelMax(64, ("Audio: Failed to pause stream '%s' after %s: %Rrc\n", pStreamEx->Core.szName, pszWhen, rc));
1295 }
1296 }
1297 else
1298 LogRelMax(64, ("Audio: Failed to enable stream '%s' after %s: %Rrc\n", pStreamEx->Core.szName, pszWhen, rc));
1299 }
1300 return rc;
1301}
1302
1303
1304/**
1305 * For performing PDMIHOSTAUDIO::pfnStreamInitAsync on a worker thread.
1306 *
1307 * @param pThis Pointer to the DrvAudio instance data.
1308 * @param pStreamEx The stream. One reference for us to release.
1309 */
1310static DECLCALLBACK(void) drvAudioStreamInitAsync(PDRVAUDIO pThis, PDRVAUDIOSTREAM pStreamEx)
1311{
1312 LogFlow(("pThis=%p pStreamEx=%p (%s)\n", pThis, pStreamEx, pStreamEx->Core.szName));
1313
1314 int rc = RTCritSectRwEnterShared(&pThis->CritSectHotPlug);
1315 AssertRCReturnVoid(rc);
1316
1317 /*
1318 * Do the init job.
1319 */
1320 bool fDestroyed;
1321 PPDMIHOSTAUDIO pIHostDrvAudio = pThis->pHostDrvAudio;
1322 AssertPtr(pIHostDrvAudio);
1323 if (pIHostDrvAudio && pIHostDrvAudio->pfnStreamInitAsync)
1324 {
1325 fDestroyed = pStreamEx->cRefs <= 1;
1326 rc = pIHostDrvAudio->pfnStreamInitAsync(pIHostDrvAudio, pStreamEx->pBackend, fDestroyed);
1327 LogFlow(("pfnStreamInitAsync returns %Rrc (on %p, fDestroyed=%d)\n", rc, pStreamEx, fDestroyed));
1328 }
1329 else
1330 {
1331 fDestroyed = true;
1332 rc = VERR_AUDIO_STREAM_COULD_NOT_CREATE;
1333 }
1334
1335 RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
1336 RTCritSectEnter(&pStreamEx->Core.CritSect);
1337
1338 /*
1339 * On success, update the backend on the stream status and mark it ready for business.
1340 */
1341 if (RT_SUCCESS(rc) && !fDestroyed)
1342 {
1343 RTCritSectRwEnterShared(&pThis->CritSectHotPlug);
1344
1345 /*
1346 * Update the backend state.
1347 */
1348 pStreamEx->fStatus |= PDMAUDIOSTREAM_STS_BACKEND_READY; /* before the backend control call! */
1349
1350 rc = drvAudioStreamUpdateBackendOnStatus(pThis, pStreamEx, "asynchronous initialization completed");
1351
1352 /*
1353 * Modify the play state if output stream.
1354 */
1355 if (pStreamEx->Core.enmDir == PDMAUDIODIR_OUT)
1356 {
1357 DRVAUDIOPLAYSTATE const enmPlayState = pStreamEx->Out.enmPlayState;
1358 switch (enmPlayState)
1359 {
1360 case DRVAUDIOPLAYSTATE_PREBUF:
1361 case DRVAUDIOPLAYSTATE_PREBUF_SWITCHING:
1362 break;
1363 case DRVAUDIOPLAYSTATE_PREBUF_OVERDUE:
1364 pStreamEx->Out.enmPlayState = DRVAUDIOPLAYSTATE_PREBUF_COMMITTING;
1365 break;
1366 case DRVAUDIOPLAYSTATE_NOPLAY:
1367 pStreamEx->Out.enmPlayState = DRVAUDIOPLAYSTATE_PREBUF;
1368 break;
1369 case DRVAUDIOPLAYSTATE_PLAY:
1370 case DRVAUDIOPLAYSTATE_PLAY_PREBUF:
1371 case DRVAUDIOPLAYSTATE_PREBUF_COMMITTING:
1372 AssertFailedBreak();
1373 /* no default */
1374 case DRVAUDIOPLAYSTATE_END:
1375 case DRVAUDIOPLAYSTATE_INVALID:
1376 break;
1377 }
1378 LogFunc(("enmPlayState: %s -> %s\n", drvAudioPlayStateName(enmPlayState),
1379 drvAudioPlayStateName(pStreamEx->Out.enmPlayState) ));
1380 }
1381
1382 /*
1383 * Update the last backend state.
1384 */
1385 pStreamEx->enmLastBackendState = drvAudioStreamGetBackendState(pThis, pStreamEx);
1386
1387 RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
1388 }
1389 /*
1390 * Don't quite know what to do on failure...
1391 */
1392 else if (!fDestroyed)
1393 {
1394 LogRelMax(64, ("Audio: Failed to initialize stream '%s': %Rrc\n", pStreamEx->Core.szName, rc));
1395 }
1396
1397 /*
1398 * Release the request handle, must be done while inside the critical section.
1399 */
1400 if (pStreamEx->hReqInitAsync != NIL_RTREQ)
1401 {
1402 LogFlowFunc(("Releasing hReqInitAsync=%p\n", pStreamEx->hReqInitAsync));
1403 RTReqRelease(pStreamEx->hReqInitAsync);
1404 pStreamEx->hReqInitAsync = NIL_RTREQ;
1405 }
1406
1407 RTCritSectLeave(&pStreamEx->Core.CritSect);
1408
1409 /*
1410 * Release our stream reference.
1411 */
1412 uint32_t cRefs = drvAudioStreamReleaseInternal(pThis, pStreamEx, true /*fMayDestroy*/);
1413 LogFlowFunc(("returns (fDestroyed=%d, cRefs=%u)\n", fDestroyed, cRefs)); RT_NOREF(cRefs);
1414}
1415
1416
1417/**
1418 * Worker for drvAudioStreamInitInternal and drvAudioStreamReInitInternal that
1419 * creates the backend (host driver) side of an audio stream.
1420 *
1421 * @returns VBox status code.
1422 * @param pThis Pointer to driver instance.
1423 * @param pStreamEx Audio stream to create the backend side for.
1424 * @param pCfgReq Requested audio stream configuration to use for
1425 * stream creation.
1426 * @param pCfgAcq Acquired audio stream configuration returned by
1427 * the backend.
1428 *
1429 * @note Configuration precedence for requested audio stream configuration (first has highest priority, if set):
1430 * - per global extra-data
1431 * - per-VM extra-data
1432 * - requested configuration (by pCfgReq)
1433 * - default value
1434 */
1435static int drvAudioStreamCreateInternalBackend(PDRVAUDIO pThis, PDRVAUDIOSTREAM pStreamEx,
1436 PPDMAUDIOSTREAMCFG pCfgReq, PPDMAUDIOSTREAMCFG pCfgAcq)
1437{
1438 AssertMsg((pStreamEx->fStatus & PDMAUDIOSTREAM_STS_BACKEND_CREATED) == 0,
1439 ("Stream '%s' already initialized in backend\n", pStreamEx->Core.szName));
1440
1441 /*
1442 * Adjust the requested stream config, applying our settings.
1443 */
1444 int rc = drvAudioStreamAdjustConfig(pThis, pCfgReq, pStreamEx->Core.szName);
1445 if (RT_FAILURE(rc))
1446 return rc;
1447
1448 /*
1449 * Make the acquired host configuration the requested host configuration initially,
1450 * in case the backend does not report back an acquired configuration.
1451 */
1452 /** @todo r=bird: This is conveniently not documented in the interface... */
1453 rc = PDMAudioStrmCfgCopy(pCfgAcq, pCfgReq);
1454 if (RT_FAILURE(rc))
1455 {
1456 LogRel(("Audio: Creating stream '%s' with an invalid backend configuration not possible, skipping\n",
1457 pStreamEx->Core.szName));
1458 return rc;
1459 }
1460
1461 /*
1462 * Call the host driver to create the stream.
1463 */
1464 RTCritSectRwEnterShared(&pThis->CritSectHotPlug);
1465
1466 AssertLogRelMsgStmt(RT_VALID_PTR(pThis->pHostDrvAudio),
1467 ("Audio: %p\n", pThis->pHostDrvAudio), rc = VERR_PDM_NO_ATTACHED_DRIVER);
1468 if (RT_SUCCESS(rc))
1469 AssertLogRelMsgStmt(pStreamEx->Core.cbBackend == pThis->BackendCfg.cbStream,
1470 ("Audio: Backend changed? cbBackend changed from %#x to %#x\n",
1471 pStreamEx->Core.cbBackend, pThis->BackendCfg.cbStream),
1472 rc = VERR_STATE_CHANGED);
1473 if (RT_SUCCESS(rc))
1474 rc = pThis->pHostDrvAudio->pfnStreamCreate(pThis->pHostDrvAudio, pStreamEx->pBackend, pCfgReq, pCfgAcq);
1475 if (RT_SUCCESS(rc))
1476 {
1477 pStreamEx->enmLastBackendState = drvAudioStreamGetBackendState(pThis, pStreamEx);
1478
1479 RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
1480
1481 AssertLogRelReturn(pStreamEx->pBackend->uMagic == PDMAUDIOBACKENDSTREAM_MAGIC, VERR_INTERNAL_ERROR_3);
1482 AssertLogRelReturn(pStreamEx->pBackend->pStream == &pStreamEx->Core, VERR_INTERNAL_ERROR_3);
1483
1484 /* Must set the backend-initialized flag now or the backend won't be
1485 destroyed (this used to be done at the end of this function, with
1486 several possible early return paths before it). */
1487 pStreamEx->fStatus |= PDMAUDIOSTREAM_STS_BACKEND_CREATED;
1488 }
1489 else
1490 {
1491 RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
1492 if (rc == VERR_NOT_SUPPORTED)
1493 LogRel2(("Audio: Creating stream '%s' in backend not supported\n", pStreamEx->Core.szName));
1494 else if (rc == VERR_AUDIO_STREAM_COULD_NOT_CREATE)
1495 LogRel2(("Audio: Stream '%s' could not be created in backend because of missing hardware / drivers\n", pStreamEx->Core.szName));
1496 else
1497 LogRel(("Audio: Creating stream '%s' in backend failed with %Rrc\n", pStreamEx->Core.szName, rc));
1498 return rc;
1499 }
1500
1501 /* Remember if we need to call pfnStreamInitAsync. */
1502 pStreamEx->fNeedAsyncInit = rc == VINF_AUDIO_STREAM_ASYNC_INIT_NEEDED;
1503 AssertStmt(rc != VINF_AUDIO_STREAM_ASYNC_INIT_NEEDED || pThis->pHostDrvAudio->pfnStreamInitAsync != NULL,
1504 pStreamEx->fNeedAsyncInit = false);
1505 AssertMsg( rc != VINF_AUDIO_STREAM_ASYNC_INIT_NEEDED
1506 || pStreamEx->enmLastBackendState == PDMHOSTAUDIOSTREAMSTATE_INITIALIZING,
1507 ("rc=%Rrc %s\n", rc, PDMHostAudioStreamStateGetName(pStreamEx->enmLastBackendState)));
1508
1509 /* Validate acquired configuration. */
1510 char szTmp[PDMAUDIOPROPSTOSTRING_MAX];
1511 AssertLogRelMsgReturn(AudioHlpStreamCfgIsValid(pCfgAcq),
1512 ("Audio: Creating stream '%s' returned an invalid backend configuration (%s), skipping\n",
1513 pStreamEx->Core.szName, PDMAudioPropsToString(&pCfgAcq->Props, szTmp, sizeof(szTmp))),
1514 VERR_INVALID_PARAMETER);
1515
1516 /* Let the user know that the backend changed one of the values requested above. */
1517 if (pCfgAcq->Backend.cFramesBufferSize != pCfgReq->Backend.cFramesBufferSize)
1518 LogRel2(("Audio: Buffer size overwritten by backend for stream '%s' (now %RU64ms, %RU32 frames)\n",
1519 pStreamEx->Core.szName, PDMAudioPropsFramesToMilli(&pCfgAcq->Props, pCfgAcq->Backend.cFramesBufferSize), pCfgAcq->Backend.cFramesBufferSize));
1520
1521 if (pCfgAcq->Backend.cFramesPeriod != pCfgReq->Backend.cFramesPeriod)
1522 LogRel2(("Audio: Period size overwritten by backend for stream '%s' (now %RU64ms, %RU32 frames)\n",
1523 pStreamEx->Core.szName, PDMAudioPropsFramesToMilli(&pCfgAcq->Props, pCfgAcq->Backend.cFramesPeriod), pCfgAcq->Backend.cFramesPeriod));
1524
1525 /* Was pre-buffering requested, but the acquired configuration from the backend told us something else? */
1526 if (pCfgReq->Backend.cFramesPreBuffering)
1527 {
1528 if (pCfgAcq->Backend.cFramesPreBuffering != pCfgReq->Backend.cFramesPreBuffering)
1529 LogRel2(("Audio: Pre-buffering size overwritten by backend for stream '%s' (now %RU64ms, %RU32 frames)\n",
1530 pStreamEx->Core.szName, PDMAudioPropsFramesToMilli(&pCfgAcq->Props, pCfgAcq->Backend.cFramesPreBuffering), pCfgAcq->Backend.cFramesPreBuffering));
1531
1532 if (pCfgAcq->Backend.cFramesPreBuffering > pCfgAcq->Backend.cFramesBufferSize)
1533 {
1534 pCfgAcq->Backend.cFramesPreBuffering = pCfgAcq->Backend.cFramesBufferSize;
1535 LogRel2(("Audio: Pre-buffering size bigger than buffer size for stream '%s', adjusting to %RU64ms (%RU32 frames)\n",
1536 pStreamEx->Core.szName, PDMAudioPropsFramesToMilli(&pCfgAcq->Props, pCfgAcq->Backend.cFramesPreBuffering), pCfgAcq->Backend.cFramesPreBuffering));
1537 }
1538 }
1539 else if (pCfgReq->Backend.cFramesPreBuffering == 0) /* Was the pre-buffering requested as being disabeld? Tell the users. */
1540 {
1541 LogRel2(("Audio: Pre-buffering is disabled for stream '%s'\n", pStreamEx->Core.szName));
1542 pCfgAcq->Backend.cFramesPreBuffering = 0;
1543 }
1544
1545 /* Sanity for detecting buggy backends. */
1546 AssertMsgReturn(pCfgAcq->Backend.cFramesPeriod < pCfgAcq->Backend.cFramesBufferSize,
1547 ("Acquired period size must be smaller than buffer size\n"),
1548 VERR_INVALID_PARAMETER);
1549 AssertMsgReturn(pCfgAcq->Backend.cFramesPreBuffering <= pCfgAcq->Backend.cFramesBufferSize,
1550 ("Acquired pre-buffering size must be smaller or as big as the buffer size\n"),
1551 VERR_INVALID_PARAMETER);
1552
1553 return VINF_SUCCESS;
1554}
1555
1556
1557/**
1558 * Worker for drvAudioStreamCreate that initializes the audio stream.
1559 *
1560 * @returns VBox status code.
1561 * @param pThis Pointer to driver instance.
1562 * @param pStreamEx Stream to initialize.
1563 * @param pCfgHost Stream configuration to use for the host side (backend).
1564 * @param pCfgGuest Stream configuration to use for the guest side.
1565 */
1566static int drvAudioStreamInitInternal(PDRVAUDIO pThis, PDRVAUDIOSTREAM pStreamEx,
1567 PPDMAUDIOSTREAMCFG pCfgHost, PPDMAUDIOSTREAMCFG pCfgGuest)
1568{
1569 /*
1570 * Init host stream.
1571 */
1572 pStreamEx->Core.uMagic = PDMAUDIOSTREAM_MAGIC;
1573
1574 /* Set the host's default audio data layout. */
1575/** @todo r=bird: Why, oh why? OTOH, the layout stuff is non-sense anyway. */
1576 pCfgHost->enmLayout = PDMAUDIOSTREAMLAYOUT_NON_INTERLEAVED;
1577
1578#ifdef LOG_ENABLED
1579 LogFunc(("[%s] Requested host format:\n", pStreamEx->Core.szName));
1580 PDMAudioStrmCfgLog(pCfgHost);
1581#endif
1582
1583 LogRel2(("Audio: Creating stream '%s'\n", pStreamEx->Core.szName));
1584 LogRel2(("Audio: Guest %s format for '%s': %RU32Hz, %u%s, %RU8 channel%s\n",
1585 pCfgGuest->enmDir == PDMAUDIODIR_IN ? "recording" : "playback", pStreamEx->Core.szName,
1586 pCfgGuest->Props.uHz, PDMAudioPropsSampleBits(&pCfgGuest->Props), pCfgGuest->Props.fSigned ? "S" : "U",
1587 PDMAudioPropsChannels(&pCfgGuest->Props), PDMAudioPropsChannels(&pCfgGuest->Props) == 1 ? "" : "s"));
1588 LogRel2(("Audio: Requested host %s format for '%s': %RU32Hz, %u%s, %RU8 channel%s\n",
1589 pCfgHost->enmDir == PDMAUDIODIR_IN ? "recording" : "playback", pStreamEx->Core.szName,
1590 pCfgHost->Props.uHz, PDMAudioPropsSampleBits(&pCfgHost->Props), pCfgHost->Props.fSigned ? "S" : "U",
1591 PDMAudioPropsChannels(&pCfgHost->Props), PDMAudioPropsChannels(&pCfgHost->Props) == 1 ? "" : "s"));
1592
1593 PDMAUDIOSTREAMCFG CfgHostAcq;
1594 int rc = drvAudioStreamCreateInternalBackend(pThis, pStreamEx, pCfgHost, &CfgHostAcq);
1595 if (RT_FAILURE(rc))
1596 return rc;
1597
1598 LogFunc(("[%s] Acquired host format:\n", pStreamEx->Core.szName));
1599 PDMAudioStrmCfgLog(&CfgHostAcq);
1600 LogRel2(("Audio: Acquired host %s format for '%s': %RU32Hz, %u%s, %RU8 channel%s\n",
1601 CfgHostAcq.enmDir == PDMAUDIODIR_IN ? "recording" : "playback", pStreamEx->Core.szName,
1602 CfgHostAcq.Props.uHz, PDMAudioPropsSampleBits(&CfgHostAcq.Props), CfgHostAcq.Props.fSigned ? "S" : "U",
1603 PDMAudioPropsChannels(&CfgHostAcq.Props), PDMAudioPropsChannels(&CfgHostAcq.Props) == 1 ? "" : "s"));
1604 Assert(PDMAudioPropsAreValid(&CfgHostAcq.Props));
1605
1606 /* Set the stream properties. */
1607 pStreamEx->Core.Props = CfgHostAcq.Props;
1608
1609 /* Let the user know if the backend changed some of the tweakable values. */
1610 if (CfgHostAcq.Backend.cFramesBufferSize != pCfgHost->Backend.cFramesBufferSize)
1611 LogRel2(("Audio: Backend changed buffer size from %RU64ms (%RU32 frames) to %RU64ms (%RU32 frames)\n",
1612 PDMAudioPropsFramesToMilli(&pCfgHost->Props, pCfgHost->Backend.cFramesBufferSize), pCfgHost->Backend.cFramesBufferSize,
1613 PDMAudioPropsFramesToMilli(&CfgHostAcq.Props, CfgHostAcq.Backend.cFramesBufferSize), CfgHostAcq.Backend.cFramesBufferSize));
1614
1615 if (CfgHostAcq.Backend.cFramesPeriod != pCfgHost->Backend.cFramesPeriod)
1616 LogRel2(("Audio: Backend changed period size from %RU64ms (%RU32 frames) to %RU64ms (%RU32 frames)\n",
1617 PDMAudioPropsFramesToMilli(&pCfgHost->Props, pCfgHost->Backend.cFramesPeriod), pCfgHost->Backend.cFramesPeriod,
1618 PDMAudioPropsFramesToMilli(&CfgHostAcq.Props, CfgHostAcq.Backend.cFramesPeriod), CfgHostAcq.Backend.cFramesPeriod));
1619
1620 if (CfgHostAcq.Backend.cFramesPreBuffering != pCfgHost->Backend.cFramesPreBuffering)
1621 LogRel2(("Audio: Backend changed pre-buffering size from %RU64ms (%RU32 frames) to %RU64ms (%RU32 frames)\n",
1622 PDMAudioPropsFramesToMilli(&pCfgHost->Props, pCfgHost->Backend.cFramesPreBuffering), pCfgHost->Backend.cFramesPreBuffering,
1623 PDMAudioPropsFramesToMilli(&CfgHostAcq.Props, CfgHostAcq.Backend.cFramesPreBuffering), CfgHostAcq.Backend.cFramesPreBuffering));
1624
1625 /*
1626 * Check if the backend did return sane values and correct if necessary.
1627 * Should never happen with our own backends, but you never know ...
1628 */
1629 uint32_t const cFramesPreBufferingMax = CfgHostAcq.Backend.cFramesBufferSize - RT_MIN(16, CfgHostAcq.Backend.cFramesBufferSize);
1630 if (CfgHostAcq.Backend.cFramesPreBuffering > cFramesPreBufferingMax)
1631 {
1632 LogRel2(("Audio: Warning: Pre-buffering size of %RU32 frames for stream '%s' is too close to or larger than the %RU32 frames buffer size, reducing it to %RU32 frames!\n",
1633 CfgHostAcq.Backend.cFramesPreBuffering, pStreamEx->Core.szName, CfgHostAcq.Backend.cFramesBufferSize, cFramesPreBufferingMax));
1634 AssertFailed();
1635 CfgHostAcq.Backend.cFramesPreBuffering = cFramesPreBufferingMax;
1636 }
1637
1638 if (CfgHostAcq.Backend.cFramesPeriod > CfgHostAcq.Backend.cFramesBufferSize)
1639 {
1640 LogRel2(("Audio: Warning: Period size of %RU32 frames for stream '%s' is larger than the %RU32 frames buffer size, reducing it to %RU32 frames!\n",
1641 CfgHostAcq.Backend.cFramesPeriod, pStreamEx->Core.szName, CfgHostAcq.Backend.cFramesBufferSize, CfgHostAcq.Backend.cFramesBufferSize / 2));
1642 AssertFailed();
1643 CfgHostAcq.Backend.cFramesPeriod = CfgHostAcq.Backend.cFramesBufferSize / 2;
1644 }
1645
1646 LogRel2(("Audio: Buffer size of stream '%s' is %RU64 ms / %RU32 frames\n", pStreamEx->Core.szName,
1647 PDMAudioPropsFramesToMilli(&CfgHostAcq.Props, CfgHostAcq.Backend.cFramesBufferSize), CfgHostAcq.Backend.cFramesBufferSize));
1648 LogRel2(("Audio: Pre-buffering size of stream '%s' is %RU64 ms / %RU32 frames\n", pStreamEx->Core.szName,
1649 PDMAudioPropsFramesToMilli(&CfgHostAcq.Props, CfgHostAcq.Backend.cFramesPreBuffering), CfgHostAcq.Backend.cFramesPreBuffering));
1650
1651 /* Make sure the configured buffer size by the backend at least can hold the configured latency. */
1652 const uint32_t msPeriod = PDMAudioPropsFramesToMilli(&CfgHostAcq.Props, CfgHostAcq.Backend.cFramesPeriod);
1653 LogRel2(("Audio: Period size of stream '%s' is %RU64 ms / %RU32 frames\n",
1654 pStreamEx->Core.szName, msPeriod, CfgHostAcq.Backend.cFramesPeriod));
1655
1656 if ( pCfgGuest->Device.cMsSchedulingHint /* Any scheduling hint set? */
1657 && pCfgGuest->Device.cMsSchedulingHint > msPeriod) /* This might lead to buffer underflows. */
1658 LogRel(("Audio: Warning: Scheduling hint of stream '%s' is bigger (%RU64ms) than used period size (%RU64ms)\n",
1659 pStreamEx->Core.szName, pCfgGuest->Device.cMsSchedulingHint, msPeriod));
1660
1661 /*
1662 * Make a copy of the acquired host stream configuration and the guest side one.
1663 */
1664 rc = PDMAudioStrmCfgCopy(&pStreamEx->Host.Cfg, &CfgHostAcq);
1665 AssertRC(rc);
1666
1667 /* Set the guests's default audio data layout. */
1668 pCfgGuest->enmLayout = PDMAUDIOSTREAMLAYOUT_NON_INTERLEAVED; /** @todo r=bird: WTF DO WE DO THIS? It's input and probably should've been const... */
1669 rc = PDMAudioStrmCfgCopy(&pStreamEx->Guest.Cfg, pCfgGuest);
1670 AssertRC(rc);
1671
1672 /*
1673 * Configure host buffers.
1674 */
1675 Assert(pStreamEx->cbPreBufThreshold == 0);
1676 if (CfgHostAcq.Backend.cFramesPreBuffering != 0)
1677 pStreamEx->cbPreBufThreshold = PDMAudioPropsFramesToBytes(&CfgHostAcq.Props, CfgHostAcq.Backend.cFramesPreBuffering);
1678
1679 /* Allocate space for pre-buffering of output stream w/o mixing buffers. */
1680 if (pCfgHost->enmDir == PDMAUDIODIR_OUT)
1681 {
1682 Assert(pStreamEx->Out.cbPreBufAlloc == 0);
1683 Assert(pStreamEx->Out.cbPreBuffered == 0);
1684 Assert(pStreamEx->Out.offPreBuf == 0);
1685 if (CfgHostAcq.Backend.cFramesPreBuffering != 0)
1686 {
1687 pStreamEx->Out.cbPreBufAlloc = PDMAudioPropsFramesToBytes(&CfgHostAcq.Props,
1688 CfgHostAcq.Backend.cFramesBufferSize - 2);
1689 pStreamEx->Out.cbPreBufAlloc = RT_MIN(RT_ALIGN_32(pStreamEx->cbPreBufThreshold + _8K, _4K),
1690 pStreamEx->Out.cbPreBufAlloc);
1691 pStreamEx->Out.pbPreBuf = (uint8_t *)RTMemAllocZ(pStreamEx->Out.cbPreBufAlloc);
1692 AssertReturn(pStreamEx->Out.pbPreBuf, VERR_NO_MEMORY);
1693 }
1694 pStreamEx->Out.enmPlayState = DRVAUDIOPLAYSTATE_NOPLAY; /* Changed upon enable. */
1695 }
1696
1697 /*
1698 * Init guest stream.
1699 */
1700 if (pCfgGuest->Device.cMsSchedulingHint)
1701 LogRel2(("Audio: Stream '%s' got a scheduling hint of %RU32ms (%RU32 bytes)\n",
1702 pStreamEx->Core.szName, pCfgGuest->Device.cMsSchedulingHint,
1703 PDMAudioPropsMilliToBytes(&pCfgGuest->Props, pCfgGuest->Device.cMsSchedulingHint)));
1704
1705 /*
1706 * Register statistics.
1707 */
1708 PPDMDRVINS const pDrvIns = pThis->pDrvIns;
1709 /** @todo expose config and more. */
1710 PDMDrvHlpSTAMRegisterF(pDrvIns, &pStreamEx->Host.Cfg.Backend.cFramesBufferSize, STAMTYPE_U32, STAMVISIBILITY_USED, STAMUNIT_NONE,
1711 "Host side: The size of the backend buffer (in frames)", "%s/0-HostBackendBufSize", pStreamEx->Core.szName);
1712 if (pCfgGuest->enmDir == PDMAUDIODIR_IN)
1713 {
1714 /** @todo later? */
1715 }
1716 else
1717 {
1718 PDMDrvHlpSTAMRegisterF(pDrvIns, &pStreamEx->Out.Stats.cbBackendWritableBefore, STAMTYPE_U32, STAMVISIBILITY_USED, STAMUNIT_NONE,
1719 "Host side: Free space in backend buffer before play", "%s/0-HostBackendBufFreeBefore", pStreamEx->Core.szName);
1720 PDMDrvHlpSTAMRegisterF(pDrvIns, &pStreamEx->Out.Stats.cbBackendWritableAfter, STAMTYPE_U32, STAMVISIBILITY_USED, STAMUNIT_NONE,
1721 "Host side: Free space in backend buffer after play", "%s/0-HostBackendBufFreeAfter", pStreamEx->Core.szName);
1722 }
1723
1724#ifdef VBOX_WITH_STATISTICS
1725 if (pCfgGuest->enmDir == PDMAUDIODIR_IN)
1726 {
1727 PDMDrvHlpSTAMRegisterF(pDrvIns, &pStreamEx->In.Stats.TotalFramesCaptured, STAMTYPE_COUNTER, STAMVISIBILITY_USED, STAMUNIT_NONE,
1728 "Total frames played.", "%s/TotalFramesCaptured", pStreamEx->Core.szName);
1729 PDMDrvHlpSTAMRegisterF(pDrvIns, &pStreamEx->In.Stats.TotalTimesCaptured, STAMTYPE_COUNTER, STAMVISIBILITY_USED, STAMUNIT_NONE,
1730 "Total number of playbacks.", "%s/TotalTimesCaptured", pStreamEx->Core.szName);
1731 PDMDrvHlpSTAMRegisterF(pDrvIns, &pStreamEx->In.Stats.TotalTimesRead, STAMTYPE_COUNTER, STAMVISIBILITY_USED, STAMUNIT_NONE,
1732 "Total number of reads.", "%s/TotalTimesRead", pStreamEx->Core.szName);
1733 }
1734 else
1735 {
1736 Assert(pCfgGuest->enmDir == PDMAUDIODIR_OUT);
1737 }
1738#endif /* VBOX_WITH_STATISTICS */
1739
1740 LogFlowFunc(("[%s] Returning %Rrc\n", pStreamEx->Core.szName, rc));
1741 return rc;
1742}
1743
1744
1745/**
1746 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnStreamCreate}
1747 */
1748static DECLCALLBACK(int) drvAudioStreamCreate(PPDMIAUDIOCONNECTOR pInterface, uint32_t fFlags, PPDMAUDIOSTREAMCFG pCfgHost,
1749 PPDMAUDIOSTREAMCFG pCfgGuest, PPDMAUDIOSTREAM *ppStream)
1750{
1751 PDRVAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVAUDIO, IAudioConnector);
1752 AssertPtr(pThis);
1753
1754 /*
1755 * Assert sanity.
1756 */
1757 AssertReturn(!(fFlags & ~PDMAUDIOSTREAM_CREATE_F_NO_MIXBUF), VERR_INVALID_FLAGS);
1758 AssertPtrReturn(pCfgHost, VERR_INVALID_POINTER);
1759 AssertPtrReturn(pCfgGuest, VERR_INVALID_POINTER);
1760 AssertPtrReturn(ppStream, VERR_INVALID_POINTER);
1761 LogFlowFunc(("Host=%s, Guest=%s\n", pCfgHost->szName, pCfgGuest->szName));
1762#ifdef LOG_ENABLED
1763 PDMAudioStrmCfgLog(pCfgHost);
1764 PDMAudioStrmCfgLog(pCfgGuest);
1765#endif
1766 AssertReturn(AudioHlpStreamCfgIsValid(pCfgHost), VERR_INVALID_PARAMETER);
1767 AssertReturn(AudioHlpStreamCfgIsValid(pCfgGuest), VERR_INVALID_PARAMETER);
1768 AssertReturn(pCfgHost->enmDir == pCfgGuest->enmDir, VERR_MISMATCH);
1769 AssertReturn(pCfgHost->enmDir == PDMAUDIODIR_IN || pCfgHost->enmDir == PDMAUDIODIR_OUT, VERR_NOT_SUPPORTED);
1770
1771 /*
1772 * Grab a free stream count now.
1773 */
1774 int rc = RTCritSectRwEnterExcl(&pThis->CritSectGlobals);
1775 AssertRCReturn(rc, rc);
1776
1777 uint32_t * const pcFreeStreams = pCfgHost->enmDir == PDMAUDIODIR_IN ? &pThis->In.cStreamsFree : &pThis->Out.cStreamsFree;
1778 if (*pcFreeStreams > 0)
1779 *pcFreeStreams -= 1;
1780 else
1781 {
1782 RTCritSectRwLeaveExcl(&pThis->CritSectGlobals);
1783 LogFlowFunc(("Maximum number of host %s streams reached\n", PDMAudioDirGetName(pCfgHost->enmDir) ));
1784 return pCfgHost->enmDir == PDMAUDIODIR_IN ? VERR_AUDIO_NO_FREE_INPUT_STREAMS : VERR_AUDIO_NO_FREE_OUTPUT_STREAMS;
1785 }
1786
1787 RTCritSectRwLeaveExcl(&pThis->CritSectGlobals);
1788
1789 /*
1790 * Get and check the backend size.
1791 *
1792 * Since we'll have to leave the hot-plug lock before we call the backend,
1793 * we'll have revalidate the size at that time.
1794 */
1795 RTCritSectRwEnterShared(&pThis->CritSectHotPlug);
1796
1797 size_t const cbHstStrm = pThis->BackendCfg.cbStream;
1798 AssertStmt(cbHstStrm >= sizeof(PDMAUDIOBACKENDSTREAM), rc = VERR_OUT_OF_RANGE);
1799 AssertStmt(cbHstStrm < _16M, rc = VERR_OUT_OF_RANGE);
1800
1801 RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
1802 if (RT_SUCCESS(rc))
1803 {
1804 /*
1805 * Allocate and initialize common state.
1806 */
1807 PDRVAUDIOSTREAM pStreamEx = (PDRVAUDIOSTREAM)RTMemAllocZ(sizeof(DRVAUDIOSTREAM) + RT_ALIGN_Z(cbHstStrm, 64));
1808 if (pStreamEx)
1809 {
1810 rc = RTCritSectInit(&pStreamEx->Core.CritSect); /* (drvAudioStreamFree assumes it's initailized) */
1811 if (RT_SUCCESS(rc))
1812 {
1813 PPDMAUDIOBACKENDSTREAM pBackend = (PPDMAUDIOBACKENDSTREAM)(pStreamEx + 1);
1814 pBackend->uMagic = PDMAUDIOBACKENDSTREAM_MAGIC;
1815 pBackend->pStream = &pStreamEx->Core;
1816
1817 pStreamEx->pBackend = pBackend;
1818 pStreamEx->Core.enmDir = pCfgHost->enmDir;
1819 pStreamEx->Core.cbBackend = (uint32_t)cbHstStrm;
1820 pStreamEx->fDestroyImmediate = true;
1821 pStreamEx->hReqInitAsync = NIL_RTREQ;
1822 pStreamEx->uMagic = DRVAUDIOSTREAM_MAGIC;
1823
1824 /* Make a unqiue stream name including the host (backend) driver name. */
1825 AssertPtr(pThis->pHostDrvAudio);
1826 size_t cchName = RTStrPrintf(pStreamEx->Core.szName, RT_ELEMENTS(pStreamEx->Core.szName), "[%s] %s:0",
1827 pThis->BackendCfg.szName, pCfgHost->szName[0] != '\0' ? pCfgHost->szName : "<NoName>");
1828 if (cchName < sizeof(pStreamEx->Core.szName))
1829 {
1830 RTCritSectRwEnterShared(&pThis->CritSectGlobals);
1831 for (uint32_t i = 0; i < 256; i++)
1832 {
1833 bool fDone = true;
1834 PDRVAUDIOSTREAM pIt;
1835 RTListForEach(&pThis->LstStreams, pIt, DRVAUDIOSTREAM, ListEntry)
1836 {
1837 if (strcmp(pIt->Core.szName, pStreamEx->Core.szName) == 0)
1838 {
1839 RTStrPrintf(pStreamEx->Core.szName, RT_ELEMENTS(pStreamEx->Core.szName), "[%s] %s:%u",
1840 pThis->BackendCfg.szName, pCfgHost->szName[0] != '\0' ? pCfgHost->szName : "<NoName>",
1841 i);
1842 fDone = false;
1843 break;
1844 }
1845 }
1846 if (fDone)
1847 break;
1848 }
1849 RTCritSectRwLeaveShared(&pThis->CritSectGlobals);
1850 }
1851
1852 /*
1853 * Try to init the rest.
1854 */
1855 rc = drvAudioStreamInitInternal(pThis, pStreamEx, pCfgHost, pCfgGuest);
1856 if (RT_SUCCESS(rc))
1857 {
1858 /* Set initial reference counts. */
1859 pStreamEx->cRefs = pStreamEx->fNeedAsyncInit ? 2 : 1;
1860
1861 /* Add it to the list. */
1862 RTCritSectRwEnterExcl(&pThis->CritSectGlobals);
1863
1864 RTListAppend(&pThis->LstStreams, &pStreamEx->ListEntry);
1865 pThis->cStreams++;
1866 STAM_COUNTER_INC(&pThis->Stats.TotalStreamsCreated);
1867
1868 RTCritSectRwLeaveExcl(&pThis->CritSectGlobals);
1869
1870 /*
1871 * Init debug stuff if enabled (ignore failures).
1872 */
1873 if (pCfgHost->enmDir == PDMAUDIODIR_IN)
1874 {
1875 if (pThis->CfgIn.Dbg.fEnabled)
1876 AudioHlpFileCreateAndOpen(&pStreamEx->In.Dbg.pFileCapture, pThis->CfgIn.Dbg.szPathOut,
1877 "DrvAudioCapture", pThis->pDrvIns->iInstance, &pStreamEx->Host.Cfg.Props);
1878 }
1879 else /* Out */
1880 {
1881 if (pThis->CfgOut.Dbg.fEnabled)
1882 AudioHlpFileCreateAndOpen(&pStreamEx->Out.Dbg.pFilePlay, pThis->CfgOut.Dbg.szPathOut,
1883 "DrvAudioPlay", pThis->pDrvIns->iInstance, &pStreamEx->Host.Cfg.Props);
1884 }
1885
1886 /*
1887 * Kick off the asynchronous init.
1888 */
1889 if (!pStreamEx->fNeedAsyncInit)
1890 {
1891 pStreamEx->fStatus |= PDMAUDIOSTREAM_STS_BACKEND_READY;
1892 PDMAUDIOSTREAM_STS_ASSERT_VALID(pStreamEx->fStatus);
1893 }
1894 else
1895 {
1896 int rc2 = RTReqPoolCallEx(pThis->hReqPool, 0 /*cMillies*/, &pStreamEx->hReqInitAsync,
1897 RTREQFLAGS_VOID | RTREQFLAGS_NO_WAIT,
1898 (PFNRT)drvAudioStreamInitAsync, 2, pThis, pStreamEx);
1899 LogFlowFunc(("hReqInitAsync=%p rc2=%Rrc\n", pStreamEx->hReqInitAsync, rc2));
1900 AssertRCStmt(rc2, drvAudioStreamInitAsync(pThis, pStreamEx));
1901 }
1902
1903#ifdef VBOX_STRICT
1904 /*
1905 * Assert lock order to make sure the lock validator picks up on it.
1906 */
1907 RTCritSectRwEnterShared(&pThis->CritSectGlobals);
1908 RTCritSectEnter(&pStreamEx->Core.CritSect);
1909 RTCritSectRwEnterShared(&pThis->CritSectHotPlug);
1910 RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
1911 RTCritSectLeave(&pStreamEx->Core.CritSect);
1912 RTCritSectRwLeaveShared(&pThis->CritSectGlobals);
1913#endif
1914
1915 *ppStream = &pStreamEx->Core;
1916 LogFlowFunc(("returns VINF_SUCCESS (pStreamEx=%p)\n", pStreamEx));
1917 return VINF_SUCCESS;
1918 }
1919
1920 LogFunc(("drvAudioStreamInitInternal failed: %Rrc\n", rc));
1921 int rc2 = drvAudioStreamUninitInternal(pThis, pStreamEx);
1922 AssertRC(rc2);
1923 drvAudioStreamFree(pStreamEx);
1924 }
1925 else
1926 RTMemFree(pStreamEx);
1927 }
1928 else
1929 rc = VERR_NO_MEMORY;
1930 }
1931
1932 /*
1933 * Give back the stream count, we couldn't use it after all.
1934 */
1935 RTCritSectRwEnterExcl(&pThis->CritSectGlobals);
1936 *pcFreeStreams += 1;
1937 RTCritSectRwLeaveExcl(&pThis->CritSectGlobals);
1938
1939 LogFlowFuncLeaveRC(rc);
1940 return rc;
1941}
1942
1943
1944/**
1945 * Calls the backend to give it the chance to destroy its part of the audio stream.
1946 *
1947 * Called from drvAudioPowerOff, drvAudioStreamUninitInternal and
1948 * drvAudioStreamReInitInternal.
1949 *
1950 * @returns VBox status code.
1951 * @param pThis Pointer to driver instance.
1952 * @param pStreamEx Audio stream destruct backend for.
1953 */
1954static int drvAudioStreamDestroyInternalBackend(PDRVAUDIO pThis, PDRVAUDIOSTREAM pStreamEx)
1955{
1956 AssertPtr(pThis);
1957 AssertPtr(pStreamEx);
1958
1959 int rc = VINF_SUCCESS;
1960
1961#ifdef LOG_ENABLED
1962 char szStreamSts[DRVAUDIO_STATUS_STR_MAX];
1963#endif
1964 LogFunc(("[%s] fStatus=%s\n", pStreamEx->Core.szName, drvAudioStreamStatusToStr(szStreamSts, pStreamEx->fStatus)));
1965
1966 if (pStreamEx->fStatus & PDMAUDIOSTREAM_STS_BACKEND_CREATED)
1967 {
1968 AssertPtr(pStreamEx->pBackend);
1969
1970 /* Check if the pointer to the host audio driver is still valid.
1971 * It can be NULL if we were called in drvAudioDestruct, for example. */
1972 RTCritSectRwEnterShared(&pThis->CritSectHotPlug); /** @todo needed? */
1973 if (pThis->pHostDrvAudio)
1974 rc = pThis->pHostDrvAudio->pfnStreamDestroy(pThis->pHostDrvAudio, pStreamEx->pBackend, pStreamEx->fDestroyImmediate);
1975 RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
1976
1977 pStreamEx->fStatus &= ~(PDMAUDIOSTREAM_STS_BACKEND_CREATED | PDMAUDIOSTREAM_STS_BACKEND_READY);
1978 PDMAUDIOSTREAM_STS_ASSERT_VALID(pStreamEx->fStatus);
1979 }
1980
1981 LogFlowFunc(("[%s] Returning %Rrc\n", pStreamEx->Core.szName, rc));
1982 return rc;
1983}
1984
1985
1986/**
1987 * Uninitializes an audio stream - worker for drvAudioStreamDestroy,
1988 * drvAudioDestruct and drvAudioStreamCreate.
1989 *
1990 * @returns VBox status code.
1991 * @param pThis Pointer to driver instance.
1992 * @param pStreamEx Pointer to audio stream to uninitialize.
1993 */
1994static int drvAudioStreamUninitInternal(PDRVAUDIO pThis, PDRVAUDIOSTREAM pStreamEx)
1995{
1996 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
1997 AssertMsgReturn(pStreamEx->cRefs <= 1,
1998 ("Stream '%s' still has %RU32 references held when uninitializing\n", pStreamEx->Core.szName, pStreamEx->cRefs),
1999 VERR_WRONG_ORDER);
2000 LogFlowFunc(("[%s] cRefs=%RU32\n", pStreamEx->Core.szName, pStreamEx->cRefs));
2001
2002 RTCritSectEnter(&pStreamEx->Core.CritSect);
2003
2004 /*
2005 * ...
2006 */
2007 if (pStreamEx->fDestroyImmediate)
2008 drvAudioStreamControlInternal(pThis, pStreamEx, PDMAUDIOSTREAMCMD_DISABLE);
2009 int rc = drvAudioStreamDestroyInternalBackend(pThis, pStreamEx);
2010
2011 /* Free pre-buffer space. */
2012 if ( pStreamEx->Core.enmDir == PDMAUDIODIR_OUT
2013 && pStreamEx->Out.pbPreBuf)
2014 {
2015 RTMemFree(pStreamEx->Out.pbPreBuf);
2016 pStreamEx->Out.pbPreBuf = NULL;
2017 pStreamEx->Out.cbPreBufAlloc = 0;
2018 pStreamEx->Out.cbPreBuffered = 0;
2019 pStreamEx->Out.offPreBuf = 0;
2020 }
2021
2022 if (RT_SUCCESS(rc))
2023 {
2024#ifdef LOG_ENABLED
2025 if (pStreamEx->fStatus != PDMAUDIOSTREAM_STS_NONE)
2026 {
2027 char szStreamSts[DRVAUDIO_STATUS_STR_MAX];
2028 LogFunc(("[%s] Warning: Still has %s set when uninitializing\n",
2029 pStreamEx->Core.szName, drvAudioStreamStatusToStr(szStreamSts, pStreamEx->fStatus)));
2030 }
2031#endif
2032 pStreamEx->fStatus = PDMAUDIOSTREAM_STS_NONE;
2033 }
2034
2035 PPDMDRVINS const pDrvIns = pThis->pDrvIns;
2036 PDMDrvHlpSTAMDeregisterByPrefix(pDrvIns, pStreamEx->Core.szName);
2037
2038 if (pStreamEx->Core.enmDir == PDMAUDIODIR_IN)
2039 {
2040 if (pThis->CfgIn.Dbg.fEnabled)
2041 {
2042 AudioHlpFileDestroy(pStreamEx->In.Dbg.pFileCapture);
2043 pStreamEx->In.Dbg.pFileCapture = NULL;
2044 }
2045 }
2046 else
2047 {
2048 Assert(pStreamEx->Core.enmDir == PDMAUDIODIR_OUT);
2049 if (pThis->CfgOut.Dbg.fEnabled)
2050 {
2051 AudioHlpFileDestroy(pStreamEx->Out.Dbg.pFilePlay);
2052 pStreamEx->Out.Dbg.pFilePlay = NULL;
2053 }
2054 }
2055
2056 RTCritSectLeave(&pStreamEx->Core.CritSect);
2057 LogFlowFunc(("Returning %Rrc\n", rc));
2058 return rc;
2059}
2060
2061
2062/**
2063 * Internal release function.
2064 *
2065 * @returns New reference count, UINT32_MAX if bad stream.
2066 * @param pThis Pointer to the DrvAudio instance data.
2067 * @param pStreamEx The stream to reference.
2068 * @param fMayDestroy Whether the caller is allowed to implicitly destroy
2069 * the stream or not.
2070 */
2071static uint32_t drvAudioStreamReleaseInternal(PDRVAUDIO pThis, PDRVAUDIOSTREAM pStreamEx, bool fMayDestroy)
2072{
2073 AssertPtrReturn(pStreamEx, UINT32_MAX);
2074 AssertReturn(pStreamEx->Core.uMagic == PDMAUDIOSTREAM_MAGIC, UINT32_MAX);
2075 AssertReturn(pStreamEx->uMagic == DRVAUDIOSTREAM_MAGIC, UINT32_MAX);
2076 Assert(!RTCritSectIsOwner(&pStreamEx->Core.CritSect));
2077
2078 uint32_t cRefs = ASMAtomicDecU32(&pStreamEx->cRefs);
2079 if (cRefs != 0)
2080 Assert(cRefs < _1K);
2081 else if (fMayDestroy)
2082 {
2083/** @todo r=bird: Caching one stream in each direction for some time,
2084 * depending on the time it took to create it. drvAudioStreamCreate can use it
2085 * if the configuration matches, otherwise it'll throw it away. This will
2086 * provide a general speedup independ of device (HDA used to do this, but
2087 * doesn't) and backend implementation. Ofc, the backend probably needs an
2088 * opt-out here. */
2089 int rc = drvAudioStreamUninitInternal(pThis, pStreamEx);
2090 if (RT_SUCCESS(rc))
2091 {
2092 RTCritSectRwEnterExcl(&pThis->CritSectGlobals);
2093
2094 if (pStreamEx->Core.enmDir == PDMAUDIODIR_IN)
2095 pThis->In.cStreamsFree++;
2096 else /* Out */
2097 pThis->Out.cStreamsFree++;
2098 pThis->cStreams--;
2099
2100 RTListNodeRemove(&pStreamEx->ListEntry);
2101
2102 RTCritSectRwLeaveExcl(&pThis->CritSectGlobals);
2103
2104 drvAudioStreamFree(pStreamEx);
2105 }
2106 else
2107 {
2108 LogRel(("Audio: Uninitializing stream '%s' failed with %Rrc\n", pStreamEx->Core.szName, rc));
2109 /** @todo r=bird: What's the plan now? */
2110 }
2111 }
2112 else
2113 {
2114 cRefs = ASMAtomicIncU32(&pStreamEx->cRefs);
2115 AssertFailed();
2116 }
2117
2118 Log12Func(("returns %u (%s)\n", cRefs, cRefs > 0 ? pStreamEx->Core.szName : "destroyed"));
2119 return cRefs;
2120}
2121
2122
2123/**
2124 * Asynchronous worker for drvAudioStreamDestroy.
2125 *
2126 * Does DISABLE and releases reference, possibly destroying the stream.
2127 *
2128 * @param pThis Pointer to the DrvAudio instance data.
2129 * @param pStreamEx The stream. One reference for us to release.
2130 * @param fImmediate How to treat draining streams.
2131 */
2132static DECLCALLBACK(void) drvAudioStreamDestroyAsync(PDRVAUDIO pThis, PDRVAUDIOSTREAM pStreamEx, bool fImmediate)
2133{
2134 LogFlowFunc(("pThis=%p pStreamEx=%p (%s) fImmediate=%RTbool\n", pThis, pStreamEx, pStreamEx->Core.szName, fImmediate));
2135#ifdef LOG_ENABLED
2136 uint64_t const nsStart = RTTimeNanoTS();
2137#endif
2138 RTCritSectEnter(&pStreamEx->Core.CritSect);
2139
2140 pStreamEx->fDestroyImmediate = fImmediate; /* Do NOT adjust for draining status, just pass it as-is. CoreAudio needs this. */
2141
2142 if (!fImmediate && (pStreamEx->fStatus & PDMAUDIOSTREAM_STS_PENDING_DISABLE))
2143 LogFlowFunc(("No DISABLE\n"));
2144 else
2145 {
2146 int rc2 = drvAudioStreamControlInternal(pThis, pStreamEx, PDMAUDIOSTREAMCMD_DISABLE);
2147 LogFlowFunc(("DISABLE done: %Rrc\n", rc2));
2148 AssertRC(rc2);
2149 }
2150
2151 RTCritSectLeave(&pStreamEx->Core.CritSect);
2152
2153 drvAudioStreamReleaseInternal(pThis, pStreamEx, true /*fMayDestroy*/);
2154
2155 LogFlowFunc(("returning (after %'RU64 ns)\n", RTTimeNanoTS() - nsStart));
2156}
2157
2158
2159/**
2160 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnStreamDestroy}
2161 */
2162static DECLCALLBACK(int) drvAudioStreamDestroy(PPDMIAUDIOCONNECTOR pInterface, PPDMAUDIOSTREAM pStream, bool fImmediate)
2163{
2164 PDRVAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVAUDIO, IAudioConnector);
2165 AssertPtr(pThis);
2166
2167 /* Ignore NULL streams. */
2168 if (!pStream)
2169 return VINF_SUCCESS;
2170
2171 PDRVAUDIOSTREAM pStreamEx = (PDRVAUDIOSTREAM)pStream; /* Note! Do not touch pStream after this! */
2172 AssertPtrReturn(pStreamEx, VERR_INVALID_POINTER);
2173 LogFlowFunc(("ENTER - %p (%s) fImmediate=%RTbool\n", pStreamEx, pStreamEx->Core.szName, fImmediate));
2174 AssertReturn(pStreamEx->Core.uMagic == PDMAUDIOSTREAM_MAGIC, VERR_INVALID_MAGIC);
2175 AssertReturn(pStreamEx->uMagic == DRVAUDIOSTREAM_MAGIC, VERR_INVALID_MAGIC);
2176 AssertReturn(pStreamEx->pBackend && pStreamEx->pBackend->uMagic == PDMAUDIOBACKENDSTREAM_MAGIC, VERR_INVALID_MAGIC);
2177
2178 /*
2179 * The main difference from a regular release is that this will disable
2180 * (or drain if we could) the stream and we can cancel any pending
2181 * pfnStreamInitAsync call.
2182 */
2183 int rc = RTCritSectEnter(&pStreamEx->Core.CritSect);
2184 AssertRCReturn(rc, rc);
2185
2186 if (pStreamEx->uMagic == DRVAUDIOSTREAM_MAGIC)
2187 {
2188 if (pStreamEx->cRefs > 0 && pStreamEx->cRefs < UINT32_MAX / 4)
2189 {
2190 char szStatus[DRVAUDIO_STATUS_STR_MAX];
2191 LogRel2(("Audio: Destroying stream '%s': cRefs=%u; status: %s; backend: %s; hReqInitAsync=%p\n",
2192 pStreamEx->Core.szName, pStreamEx->cRefs, drvAudioStreamStatusToStr(szStatus, pStreamEx->fStatus),
2193 PDMHostAudioStreamStateGetName(drvAudioStreamGetBackendState(pThis, pStreamEx)),
2194 pStreamEx->hReqInitAsync));
2195
2196 /* Try cancel pending async init request and release the it. */
2197 if (pStreamEx->hReqInitAsync != NIL_RTREQ)
2198 {
2199 Assert(pStreamEx->cRefs >= 2);
2200 int rc2 = RTReqCancel(pStreamEx->hReqInitAsync);
2201
2202 RTReqRelease(pStreamEx->hReqInitAsync);
2203 pStreamEx->hReqInitAsync = NIL_RTREQ;
2204
2205 RTCritSectLeave(&pStreamEx->Core.CritSect); /* (exit before releasing the stream to avoid assertion) */
2206
2207 if (RT_SUCCESS(rc2))
2208 {
2209 LogFlowFunc(("Successfully cancelled pending pfnStreamInitAsync call (hReqInitAsync=%p).\n",
2210 pStreamEx->hReqInitAsync));
2211 drvAudioStreamReleaseInternal(pThis, pStreamEx, true /*fMayDestroy*/);
2212 }
2213 else
2214 {
2215 LogFlowFunc(("Failed to cancel pending pfnStreamInitAsync call (hReqInitAsync=%p): %Rrc\n",
2216 pStreamEx->hReqInitAsync, rc2));
2217 Assert(rc2 == VERR_RT_REQUEST_STATE);
2218 }
2219 }
2220 else
2221 RTCritSectLeave(&pStreamEx->Core.CritSect);
2222
2223 /*
2224 * Now, if the backend requests asynchronous disabling and destruction
2225 * push the disabling and destroying over to a worker thread.
2226 *
2227 * This is a general offloading feature that all backends should make use of,
2228 * however it's rather precarious on macs where stopping an already draining
2229 * stream may take 8-10ms which naturally isn't something we should be doing
2230 * on an EMT.
2231 */
2232 if (!(pThis->BackendCfg.fFlags & PDMAUDIOBACKEND_F_ASYNC_STREAM_DESTROY))
2233 drvAudioStreamDestroyAsync(pThis, pStreamEx, fImmediate);
2234 else
2235 {
2236 int rc2 = RTReqPoolCallEx(pThis->hReqPool, 0 /*cMillies*/, NULL /*phReq*/,
2237 RTREQFLAGS_VOID | RTREQFLAGS_NO_WAIT,
2238 (PFNRT)drvAudioStreamDestroyAsync, 3, pThis, pStreamEx, fImmediate);
2239 LogFlowFunc(("hReqInitAsync=%p rc2=%Rrc\n", pStreamEx->hReqInitAsync, rc2));
2240 AssertRCStmt(rc2, drvAudioStreamDestroyAsync(pThis, pStreamEx, fImmediate));
2241 }
2242 }
2243 else
2244 {
2245 AssertLogRelMsgFailedStmt(("%p cRefs=%#x\n", pStreamEx, pStreamEx->cRefs), rc = VERR_CALLER_NO_REFERENCE);
2246 RTCritSectLeave(&pStreamEx->Core.CritSect); /*??*/
2247 }
2248 }
2249 else
2250 {
2251 AssertLogRelMsgFailedStmt(("%p uMagic=%#x\n", pStreamEx, pStreamEx->uMagic), rc = VERR_INVALID_MAGIC);
2252 RTCritSectLeave(&pStreamEx->Core.CritSect); /*??*/
2253 }
2254
2255 LogFlowFuncLeaveRC(rc);
2256 return rc;
2257}
2258
2259
2260/**
2261 * Drops all audio data (and associated state) of a stream.
2262 *
2263 * Used by drvAudioStreamIterateInternal(), drvAudioStreamResetOnDisable(), and
2264 * drvAudioStreamReInitInternal().
2265 *
2266 * @param pStreamEx Stream to drop data for.
2267 */
2268static void drvAudioStreamResetInternal(PDRVAUDIOSTREAM pStreamEx)
2269{
2270 LogFunc(("[%s]\n", pStreamEx->Core.szName));
2271 Assert(RTCritSectIsOwner(&pStreamEx->Core.CritSect));
2272
2273 pStreamEx->nsLastIterated = 0;
2274 pStreamEx->nsLastPlayedCaptured = 0;
2275 pStreamEx->nsLastReadWritten = 0;
2276 if (pStreamEx->Host.Cfg.enmDir == PDMAUDIODIR_OUT)
2277 {
2278 pStreamEx->Out.cbPreBuffered = 0;
2279 pStreamEx->Out.offPreBuf = 0;
2280 pStreamEx->Out.enmPlayState = pStreamEx->cbPreBufThreshold > 0
2281 ? DRVAUDIOPLAYSTATE_PREBUF : DRVAUDIOPLAYSTATE_PLAY;
2282 }
2283 else
2284 pStreamEx->In.enmCaptureState = pStreamEx->cbPreBufThreshold > 0
2285 ? DRVAUDIOCAPTURESTATE_PREBUF : DRVAUDIOCAPTURESTATE_CAPTURING;
2286}
2287
2288
2289/**
2290 * Re-initializes an audio stream with its existing host and guest stream
2291 * configuration.
2292 *
2293 * This might be the case if the backend told us we need to re-initialize
2294 * because something on the host side has changed.
2295 *
2296 * @note Does not touch the stream's status flags.
2297 *
2298 * @returns VBox status code.
2299 * @param pThis Pointer to driver instance.
2300 * @param pStreamEx Stream to re-initialize.
2301 */
2302static int drvAudioStreamReInitInternal(PDRVAUDIO pThis, PDRVAUDIOSTREAM pStreamEx)
2303{
2304 char szTmp[RT_MAX(PDMAUDIOSTRMCFGTOSTRING_MAX, DRVAUDIO_STATUS_STR_MAX)];
2305 LogFlowFunc(("[%s] status: %s\n", pStreamEx->Core.szName, drvAudioStreamStatusToStr(szTmp, pStreamEx->fStatus) ));
2306 Assert(RTCritSectIsOwner(&pStreamEx->Core.CritSect));
2307 RTCritSectRwEnterShared(&pThis->CritSectHotPlug);
2308
2309 /*
2310 * Destroy and re-create stream on backend side.
2311 */
2312 if ( (pStreamEx->fStatus & (PDMAUDIOSTREAM_STS_ENABLED | PDMAUDIOSTREAM_STS_BACKEND_CREATED | PDMAUDIOSTREAM_STS_BACKEND_READY))
2313 == (PDMAUDIOSTREAM_STS_ENABLED | PDMAUDIOSTREAM_STS_BACKEND_CREATED | PDMAUDIOSTREAM_STS_BACKEND_READY))
2314 drvAudioStreamControlInternalBackend(pThis, pStreamEx, PDMAUDIOSTREAMCMD_DISABLE);
2315
2316 if (pStreamEx->fStatus & PDMAUDIOSTREAM_STS_BACKEND_CREATED)
2317 drvAudioStreamDestroyInternalBackend(pThis, pStreamEx);
2318
2319 int rc = VERR_AUDIO_STREAM_NOT_READY;
2320 if (!(pStreamEx->fStatus & PDMAUDIOSTREAM_STS_BACKEND_CREATED))
2321 {
2322 drvAudioStreamResetInternal(pStreamEx);
2323
2324/** @todo
2325 * We need to zero the backend storage here!!
2326 * We need to zero the backend storage here!!
2327 * We need to zero the backend storage here!!
2328 * We need to zero the backend storage here!!
2329 * We need to zero the backend storage here!!
2330 * We need to zero the backend storage here!!
2331 * We need to zero the backend storage here!!
2332 * */
2333 PDMAUDIOSTREAMCFG CfgHostAcq;
2334 rc = drvAudioStreamCreateInternalBackend(pThis, pStreamEx, &pStreamEx->Host.Cfg, &CfgHostAcq);
2335 if (RT_SUCCESS(rc))
2336 {
2337 LogFunc(("[%s] Acquired host format: %s\n",
2338 pStreamEx->Core.szName, PDMAudioStrmCfgToString(&CfgHostAcq, szTmp, sizeof(szTmp)) ));
2339 /** @todo Validate (re-)acquired configuration with pStreamEx->Core.Host.Cfg?
2340 * drvAudioStreamInitInternal() does some setup and a bunch of
2341 * validations + adjustments of the stream config, so this surely is quite
2342 * optimistic. */
2343 if (true)
2344 {
2345 /*
2346 * Kick off the asynchronous init.
2347 */
2348 if (!pStreamEx->fNeedAsyncInit)
2349 {
2350 pStreamEx->fStatus |= PDMAUDIOSTREAM_STS_BACKEND_READY;
2351 PDMAUDIOSTREAM_STS_ASSERT_VALID(pStreamEx->fStatus);
2352 }
2353 else
2354 {
2355 drvAudioStreamRetainInternal(pStreamEx);
2356 int rc2 = RTReqPoolCallEx(pThis->hReqPool, 0 /*cMillies*/, &pStreamEx->hReqInitAsync,
2357 RTREQFLAGS_VOID | RTREQFLAGS_NO_WAIT,
2358 (PFNRT)drvAudioStreamInitAsync, 2, pThis, pStreamEx);
2359 LogFlowFunc(("hReqInitAsync=%p rc2=%Rrc\n", pStreamEx->hReqInitAsync, rc2));
2360 AssertRCStmt(rc2, drvAudioStreamInitAsync(pThis, pStreamEx));
2361 }
2362
2363 /*
2364 * Update the backend on the stream state if it's ready, otherwise
2365 * let the worker thread do it after the async init has completed.
2366 */
2367 if ( (pStreamEx->fStatus & (PDMAUDIOSTREAM_STS_BACKEND_READY | PDMAUDIOSTREAM_STS_BACKEND_CREATED))
2368 == (PDMAUDIOSTREAM_STS_BACKEND_READY | PDMAUDIOSTREAM_STS_BACKEND_CREATED))
2369 {
2370 rc = drvAudioStreamUpdateBackendOnStatus(pThis, pStreamEx, "re-initializing");
2371 /** @todo not sure if we really need to care about this status code... */
2372 }
2373 else if (pStreamEx->fStatus & PDMAUDIOSTREAM_STS_BACKEND_CREATED)
2374 {
2375 Assert(pStreamEx->hReqInitAsync != NIL_RTREQ);
2376 LogFunc(("Asynchronous stream init (%p) ...\n", pStreamEx->hReqInitAsync));
2377 }
2378 else
2379 {
2380 LogRel(("Audio: Re-initializing stream '%s' somehow failed, status: %s\n", pStreamEx->Core.szName,
2381 drvAudioStreamStatusToStr(szTmp, pStreamEx->fStatus) ));
2382 AssertFailed();
2383 rc = VERR_AUDIO_STREAM_COULD_NOT_CREATE;
2384 }
2385 }
2386 }
2387 else
2388 LogRel(("Audio: Re-initializing stream '%s' failed with %Rrc\n", pStreamEx->Core.szName, rc));
2389 }
2390 else
2391 {
2392 LogRel(("Audio: Re-initializing stream '%s' failed to destroy previous backend.\n", pStreamEx->Core.szName));
2393 AssertFailed();
2394 }
2395
2396 RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
2397 LogFunc(("[%s] Returning %Rrc\n", pStreamEx->Core.szName, rc));
2398 return rc;
2399}
2400
2401
2402/**
2403 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnStreamReInit}
2404 */
2405static DECLCALLBACK(int) drvAudioStreamReInit(PPDMIAUDIOCONNECTOR pInterface, PPDMAUDIOSTREAM pStream)
2406{
2407 PDRVAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVAUDIO, IAudioConnector);
2408 PDRVAUDIOSTREAM pStreamEx = (PDRVAUDIOSTREAM)pStream;
2409 AssertPtrReturn(pStreamEx, VERR_INVALID_POINTER);
2410 AssertReturn(pStreamEx->Core.uMagic == PDMAUDIOSTREAM_MAGIC, VERR_INVALID_MAGIC);
2411 AssertReturn(pStreamEx->uMagic == DRVAUDIOSTREAM_MAGIC, VERR_INVALID_MAGIC);
2412 AssertReturn(pStreamEx->fStatus & PDMAUDIOSTREAM_STS_NEED_REINIT, VERR_INVALID_STATE);
2413 LogFlowFunc(("\n"));
2414
2415 int rc = RTCritSectEnter(&pStreamEx->Core.CritSect);
2416 AssertRCReturn(rc, rc);
2417
2418 if (pStreamEx->fStatus & PDMAUDIOSTREAM_STS_NEED_REINIT)
2419 {
2420 const unsigned cMaxTries = 5;
2421 const uint64_t nsNow = RTTimeNanoTS();
2422
2423 /* Throttle re-initializing streams on failure. */
2424 if ( pStreamEx->cTriesReInit < cMaxTries
2425 && pStreamEx->hReqInitAsync == NIL_RTREQ
2426 && ( pStreamEx->nsLastReInit == 0
2427 || nsNow - pStreamEx->nsLastReInit >= RT_NS_1SEC * pStreamEx->cTriesReInit))
2428 {
2429 rc = drvAudioStreamReInitInternal(pThis, pStreamEx);
2430 if (RT_SUCCESS(rc))
2431 {
2432 /* Remove the pending re-init flag on success. */
2433 pStreamEx->fStatus &= ~PDMAUDIOSTREAM_STS_NEED_REINIT;
2434 PDMAUDIOSTREAM_STS_ASSERT_VALID(pStreamEx->fStatus);
2435 }
2436 else
2437 {
2438 pStreamEx->nsLastReInit = nsNow;
2439 pStreamEx->cTriesReInit++;
2440
2441 /* Did we exceed our tries re-initializing the stream?
2442 * Then this one is dead-in-the-water, so disable it for further use. */
2443 if (pStreamEx->cTriesReInit >= cMaxTries)
2444 {
2445 LogRel(("Audio: Re-initializing stream '%s' exceeded maximum retries (%u), leaving as disabled\n",
2446 pStreamEx->Core.szName, cMaxTries));
2447
2448 /* Don't try to re-initialize anymore and mark as disabled. */
2449 /** @todo should mark it as not-initialized too, shouldn't we? */
2450 pStreamEx->fStatus &= ~(PDMAUDIOSTREAM_STS_NEED_REINIT | PDMAUDIOSTREAM_STS_ENABLED);
2451 PDMAUDIOSTREAM_STS_ASSERT_VALID(pStreamEx->fStatus);
2452
2453 /* Note: Further writes to this stream go to / will be read from the bit bucket (/dev/null) from now on. */
2454 }
2455 }
2456 }
2457 else
2458 Log8Func(("cTriesReInit=%d hReqInitAsync=%p nsLast=%RU64 nsNow=%RU64 nsDelta=%RU64\n", pStreamEx->cTriesReInit,
2459 pStreamEx->hReqInitAsync, pStreamEx->nsLastReInit, nsNow, nsNow - pStreamEx->nsLastReInit));
2460
2461#ifdef LOG_ENABLED
2462 char szStreamSts[DRVAUDIO_STATUS_STR_MAX];
2463#endif
2464 Log3Func(("[%s] fStatus=%s\n", pStreamEx->Core.szName, drvAudioStreamStatusToStr(szStreamSts, pStreamEx->fStatus)));
2465 }
2466 else
2467 {
2468 AssertFailed();
2469 rc = VERR_INVALID_STATE;
2470 }
2471
2472 RTCritSectLeave(&pStreamEx->Core.CritSect);
2473
2474 LogFlowFuncLeaveRC(rc);
2475 return rc;
2476}
2477
2478
2479/**
2480 * Internal retain function.
2481 *
2482 * @returns New reference count, UINT32_MAX if bad stream.
2483 * @param pStreamEx The stream to reference.
2484 */
2485static uint32_t drvAudioStreamRetainInternal(PDRVAUDIOSTREAM pStreamEx)
2486{
2487 AssertPtrReturn(pStreamEx, UINT32_MAX);
2488 AssertReturn(pStreamEx->Core.uMagic == PDMAUDIOSTREAM_MAGIC, UINT32_MAX);
2489 AssertReturn(pStreamEx->uMagic == DRVAUDIOSTREAM_MAGIC, UINT32_MAX);
2490
2491 uint32_t const cRefs = ASMAtomicIncU32(&pStreamEx->cRefs);
2492 Assert(cRefs > 1);
2493 Assert(cRefs < _1K);
2494
2495 Log12Func(("returns %u (%s)\n", cRefs, pStreamEx->Core.szName));
2496 return cRefs;
2497}
2498
2499
2500/**
2501 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnStreamRetain}
2502 */
2503static DECLCALLBACK(uint32_t) drvAudioStreamRetain(PPDMIAUDIOCONNECTOR pInterface, PPDMAUDIOSTREAM pStream)
2504{
2505 RT_NOREF(pInterface);
2506 return drvAudioStreamRetainInternal((PDRVAUDIOSTREAM)pStream);
2507}
2508
2509
2510/**
2511 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnStreamRelease}
2512 */
2513static DECLCALLBACK(uint32_t) drvAudioStreamRelease(PPDMIAUDIOCONNECTOR pInterface, PPDMAUDIOSTREAM pStream)
2514{
2515 return drvAudioStreamReleaseInternal(RT_FROM_MEMBER(pInterface, DRVAUDIO, IAudioConnector),
2516 (PDRVAUDIOSTREAM)pStream,
2517 false /*fMayDestroy*/);
2518}
2519
2520
2521/**
2522 * Controls a stream's backend.
2523 *
2524 * @returns VBox status code.
2525 * @param pThis Pointer to driver instance.
2526 * @param pStreamEx Stream to control.
2527 * @param enmStreamCmd Control command.
2528 *
2529 * @note Caller has entered the critical section of the stream.
2530 * @note Can be called w/o having entered DRVAUDIO::CritSectHotPlug.
2531 */
2532static int drvAudioStreamControlInternalBackend(PDRVAUDIO pThis, PDRVAUDIOSTREAM pStreamEx, PDMAUDIOSTREAMCMD enmStreamCmd)
2533{
2534 AssertPtr(pThis);
2535 AssertPtr(pStreamEx);
2536 Assert(RTCritSectIsOwner(&pStreamEx->Core.CritSect));
2537
2538 int rc = RTCritSectRwEnterShared(&pThis->CritSectHotPlug);
2539 AssertRCReturn(rc, rc);
2540
2541 /*
2542 * Whether to propagate commands down to the backend.
2543 *
2544 * 1. If the stream direction is disabled on the driver level, we should
2545 * obviously not call the backend. Our stream status will reflect the
2546 * actual state so drvAudioEnable() can tell the backend if the user
2547 * re-enables the stream direction.
2548 *
2549 * 2. If the backend hasn't finished initializing yet, don't try call
2550 * it to start/stop/pause/whatever the stream. (Better to do it here
2551 * than to replicate this in the relevant backends.) When the backend
2552 * finish initializing the stream, we'll update it about the stream state.
2553 */
2554 bool const fDirEnabled = pStreamEx->Core.enmDir == PDMAUDIODIR_IN
2555 ? pThis->In.fEnabled : pThis->Out.fEnabled;
2556 PDMHOSTAUDIOSTREAMSTATE const enmBackendState = drvAudioStreamGetBackendState(pThis, pStreamEx);
2557 /* ^^^ (checks pThis->pHostDrvAudio != NULL too) */
2558
2559 char szStreamSts[DRVAUDIO_STATUS_STR_MAX];
2560 LogRel2(("Audio: %s stream '%s' backend (%s is %s; status: %s; backend-status: %s)\n",
2561 PDMAudioStrmCmdGetName(enmStreamCmd), pStreamEx->Core.szName, PDMAudioDirGetName(pStreamEx->Core.enmDir),
2562 fDirEnabled ? "enabled" : "disabled", drvAudioStreamStatusToStr(szStreamSts, pStreamEx->fStatus),
2563 PDMHostAudioStreamStateGetName(enmBackendState) ));
2564
2565 if (fDirEnabled)
2566 {
2567 if ( (pStreamEx->fStatus & PDMAUDIOSTREAM_STS_BACKEND_READY /* don't really need this check, do we? */)
2568 && ( enmBackendState == PDMHOSTAUDIOSTREAMSTATE_OKAY
2569 || enmBackendState == PDMHOSTAUDIOSTREAMSTATE_DRAINING) )
2570 {
2571 /** @todo Backend will change to explicit methods here, so please don't simplify
2572 * the switch. */
2573 switch (enmStreamCmd)
2574 {
2575 case PDMAUDIOSTREAMCMD_ENABLE:
2576 rc = pThis->pHostDrvAudio->pfnStreamControl(pThis->pHostDrvAudio, pStreamEx->pBackend,
2577 PDMAUDIOSTREAMCMD_ENABLE);
2578 break;
2579
2580 case PDMAUDIOSTREAMCMD_DISABLE:
2581 rc = pThis->pHostDrvAudio->pfnStreamControl(pThis->pHostDrvAudio, pStreamEx->pBackend,
2582 PDMAUDIOSTREAMCMD_DISABLE);
2583 break;
2584
2585 case PDMAUDIOSTREAMCMD_PAUSE:
2586 rc = pThis->pHostDrvAudio->pfnStreamControl(pThis->pHostDrvAudio, pStreamEx->pBackend,
2587 PDMAUDIOSTREAMCMD_PAUSE);
2588 break;
2589
2590 case PDMAUDIOSTREAMCMD_RESUME:
2591 rc = pThis->pHostDrvAudio->pfnStreamControl(pThis->pHostDrvAudio, pStreamEx->pBackend,
2592 PDMAUDIOSTREAMCMD_RESUME);
2593 break;
2594
2595 case PDMAUDIOSTREAMCMD_DRAIN:
2596 rc = pThis->pHostDrvAudio->pfnStreamControl(pThis->pHostDrvAudio, pStreamEx->pBackend,
2597 PDMAUDIOSTREAMCMD_DRAIN);
2598 break;
2599
2600 default:
2601 AssertMsgFailedBreakStmt(("Command %RU32 not implemented\n", enmStreamCmd), rc = VERR_INTERNAL_ERROR_2);
2602 }
2603 if (RT_SUCCESS(rc))
2604 Log2Func(("[%s] %s succeeded (%Rrc)\n", pStreamEx->Core.szName, PDMAudioStrmCmdGetName(enmStreamCmd), rc));
2605 else
2606 {
2607 LogFunc(("[%s] %s failed with %Rrc\n", pStreamEx->Core.szName, PDMAudioStrmCmdGetName(enmStreamCmd), rc));
2608 if ( rc != VERR_NOT_IMPLEMENTED
2609 && rc != VERR_NOT_SUPPORTED
2610 && rc != VERR_AUDIO_STREAM_NOT_READY)
2611 LogRel(("Audio: %s stream '%s' failed with %Rrc\n", PDMAudioStrmCmdGetName(enmStreamCmd), pStreamEx->Core.szName, rc));
2612 }
2613 }
2614 else
2615 LogFlowFunc(("enmBackendStat(=%s) != OKAY || !(fStatus(=%#x) & BACKEND_READY)\n",
2616 PDMHostAudioStreamStateGetName(enmBackendState), pStreamEx->fStatus));
2617 }
2618 else
2619 LogFlowFunc(("fDirEnabled=false\n"));
2620
2621 RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
2622 return rc;
2623}
2624
2625
2626/**
2627 * Resets the given audio stream.
2628 *
2629 * @param pStreamEx Stream to reset.
2630 */
2631static void drvAudioStreamResetOnDisable(PDRVAUDIOSTREAM pStreamEx)
2632{
2633 drvAudioStreamResetInternal(pStreamEx);
2634
2635 LogFunc(("[%s]\n", pStreamEx->Core.szName));
2636
2637 pStreamEx->fStatus &= PDMAUDIOSTREAM_STS_BACKEND_CREATED | PDMAUDIOSTREAM_STS_BACKEND_READY;
2638 pStreamEx->Core.fWarningsShown = PDMAUDIOSTREAM_WARN_FLAGS_NONE;
2639
2640#ifdef VBOX_WITH_STATISTICS
2641 /*
2642 * Reset statistics.
2643 */
2644 if (pStreamEx->Core.enmDir == PDMAUDIODIR_IN)
2645 {
2646 STAM_COUNTER_RESET(&pStreamEx->In.Stats.TotalFramesCaptured);
2647 STAM_COUNTER_RESET(&pStreamEx->In.Stats.TotalTimesCaptured);
2648 STAM_COUNTER_RESET(&pStreamEx->In.Stats.TotalTimesRead);
2649 }
2650 else if (pStreamEx->Core.enmDir == PDMAUDIODIR_OUT)
2651 {
2652 }
2653 else
2654 AssertFailed();
2655#endif
2656}
2657
2658
2659/**
2660 * Controls an audio stream.
2661 *
2662 * @returns VBox status code.
2663 * @param pThis Pointer to driver instance.
2664 * @param pStreamEx Stream to control.
2665 * @param enmStreamCmd Control command.
2666 */
2667static int drvAudioStreamControlInternal(PDRVAUDIO pThis, PDRVAUDIOSTREAM pStreamEx, PDMAUDIOSTREAMCMD enmStreamCmd)
2668{
2669 AssertPtr(pThis);
2670 AssertPtr(pStreamEx);
2671 Assert(RTCritSectIsOwner(&pStreamEx->Core.CritSect));
2672
2673#ifdef LOG_ENABLED
2674 char szStreamSts[DRVAUDIO_STATUS_STR_MAX];
2675#endif
2676 LogFunc(("[%s] enmStreamCmd=%s fStatus=%s\n", pStreamEx->Core.szName, PDMAudioStrmCmdGetName(enmStreamCmd),
2677 drvAudioStreamStatusToStr(szStreamSts, pStreamEx->fStatus)));
2678
2679 int rc = VINF_SUCCESS;
2680
2681 switch (enmStreamCmd)
2682 {
2683 case PDMAUDIOSTREAMCMD_ENABLE:
2684 if (!(pStreamEx->fStatus & PDMAUDIOSTREAM_STS_ENABLED))
2685 {
2686 /* Are we still draining this stream? Then we must disable it first. */
2687 if (pStreamEx->fStatus & PDMAUDIOSTREAM_STS_PENDING_DISABLE)
2688 {
2689 LogFunc(("Stream '%s' is still draining - disabling...\n", pStreamEx->Core.szName));
2690 rc = drvAudioStreamControlInternalBackend(pThis, pStreamEx, PDMAUDIOSTREAMCMD_DISABLE);
2691 AssertRC(rc);
2692 if (drvAudioStreamGetBackendState(pThis, pStreamEx) != PDMHOSTAUDIOSTREAMSTATE_DRAINING)
2693 {
2694 pStreamEx->fStatus &= ~(PDMAUDIOSTREAM_STS_ENABLED | PDMAUDIOSTREAM_STS_PENDING_DISABLE);
2695 drvAudioStreamResetInternal(pStreamEx);
2696 rc = VINF_SUCCESS;
2697 }
2698 }
2699
2700 if (RT_SUCCESS(rc))
2701 {
2702 /* Reset the state before we try to start. */
2703 PDMHOSTAUDIOSTREAMSTATE const enmBackendState = drvAudioStreamGetBackendState(pThis, pStreamEx);
2704 pStreamEx->enmLastBackendState = enmBackendState;
2705 pStreamEx->offInternal = 0;
2706
2707 if (pStreamEx->Core.enmDir == PDMAUDIODIR_OUT)
2708 {
2709 pStreamEx->Out.cbPreBuffered = 0;
2710 pStreamEx->Out.offPreBuf = 0;
2711 pStreamEx->Out.enmPlayState = DRVAUDIOPLAYSTATE_NOPLAY;
2712 switch (enmBackendState)
2713 {
2714 case PDMHOSTAUDIOSTREAMSTATE_INITIALIZING:
2715 if (pStreamEx->cbPreBufThreshold > 0)
2716 pStreamEx->Out.enmPlayState = DRVAUDIOPLAYSTATE_PREBUF;
2717 break;
2718 case PDMHOSTAUDIOSTREAMSTATE_DRAINING:
2719 AssertFailed();
2720 RT_FALL_THROUGH();
2721 case PDMHOSTAUDIOSTREAMSTATE_OKAY:
2722 pStreamEx->Out.enmPlayState = pStreamEx->cbPreBufThreshold > 0
2723 ? DRVAUDIOPLAYSTATE_PREBUF : DRVAUDIOPLAYSTATE_PLAY;
2724 break;
2725 case PDMHOSTAUDIOSTREAMSTATE_NOT_WORKING:
2726 case PDMHOSTAUDIOSTREAMSTATE_INACTIVE:
2727 break;
2728 /* no default */
2729 case PDMHOSTAUDIOSTREAMSTATE_INVALID:
2730 case PDMHOSTAUDIOSTREAMSTATE_END:
2731 case PDMHOSTAUDIOSTREAMSTATE_32BIT_HACK:
2732 break;
2733 }
2734 LogFunc(("ENABLE: enmBackendState=%s enmPlayState=%s\n", PDMHostAudioStreamStateGetName(enmBackendState),
2735 drvAudioPlayStateName(pStreamEx->Out.enmPlayState)));
2736 }
2737 else
2738 {
2739 pStreamEx->In.enmCaptureState = DRVAUDIOCAPTURESTATE_NO_CAPTURE;
2740 switch (enmBackendState)
2741 {
2742 case PDMHOSTAUDIOSTREAMSTATE_INITIALIZING:
2743 pStreamEx->In.enmCaptureState = DRVAUDIOCAPTURESTATE_PREBUF;
2744 break;
2745 case PDMHOSTAUDIOSTREAMSTATE_DRAINING:
2746 AssertFailed();
2747 RT_FALL_THROUGH();
2748 case PDMHOSTAUDIOSTREAMSTATE_OKAY:
2749 pStreamEx->In.enmCaptureState = pStreamEx->cbPreBufThreshold > 0
2750 ? DRVAUDIOCAPTURESTATE_PREBUF : DRVAUDIOCAPTURESTATE_CAPTURING;
2751 break;
2752 case PDMHOSTAUDIOSTREAMSTATE_NOT_WORKING:
2753 case PDMHOSTAUDIOSTREAMSTATE_INACTIVE:
2754 break;
2755 /* no default */
2756 case PDMHOSTAUDIOSTREAMSTATE_INVALID:
2757 case PDMHOSTAUDIOSTREAMSTATE_END:
2758 case PDMHOSTAUDIOSTREAMSTATE_32BIT_HACK:
2759 break;
2760 }
2761 LogFunc(("ENABLE: enmBackendState=%s enmCaptureState=%s\n", PDMHostAudioStreamStateGetName(enmBackendState),
2762 drvAudioCaptureStateName(pStreamEx->In.enmCaptureState)));
2763 }
2764
2765 rc = drvAudioStreamControlInternalBackend(pThis, pStreamEx, PDMAUDIOSTREAMCMD_ENABLE);
2766 if (RT_SUCCESS(rc))
2767 {
2768 pStreamEx->nsStarted = RTTimeNanoTS();
2769 pStreamEx->fStatus |= PDMAUDIOSTREAM_STS_ENABLED;
2770 PDMAUDIOSTREAM_STS_ASSERT_VALID(pStreamEx->fStatus);
2771 }
2772 }
2773 }
2774 break;
2775
2776 case PDMAUDIOSTREAMCMD_DISABLE:
2777 if (pStreamEx->fStatus & PDMAUDIOSTREAM_STS_ENABLED)
2778 {
2779 rc = drvAudioStreamControlInternalBackend(pThis, pStreamEx, PDMAUDIOSTREAMCMD_DISABLE);
2780 LogFunc(("DISABLE '%s': Backend DISABLE -> %Rrc\n", pStreamEx->Core.szName, rc));
2781 if (RT_SUCCESS(rc)) /** @todo ignore this and reset it anyway? */
2782 drvAudioStreamResetOnDisable(pStreamEx);
2783 }
2784 break;
2785
2786 case PDMAUDIOSTREAMCMD_PAUSE:
2787 if ((pStreamEx->fStatus & (PDMAUDIOSTREAM_STS_ENABLED | PDMAUDIOSTREAM_STS_PAUSED)) == PDMAUDIOSTREAM_STS_ENABLED)
2788 {
2789 rc = drvAudioStreamControlInternalBackend(pThis, pStreamEx, PDMAUDIOSTREAMCMD_PAUSE);
2790 if (RT_SUCCESS(rc))
2791 {
2792 pStreamEx->fStatus |= PDMAUDIOSTREAM_STS_PAUSED;
2793 PDMAUDIOSTREAM_STS_ASSERT_VALID(pStreamEx->fStatus);
2794 }
2795 }
2796 break;
2797
2798 case PDMAUDIOSTREAMCMD_RESUME:
2799 if (pStreamEx->fStatus & PDMAUDIOSTREAM_STS_PAUSED)
2800 {
2801 Assert(pStreamEx->fStatus & PDMAUDIOSTREAM_STS_ENABLED);
2802 rc = drvAudioStreamControlInternalBackend(pThis, pStreamEx, PDMAUDIOSTREAMCMD_RESUME);
2803 if (RT_SUCCESS(rc))
2804 {
2805 pStreamEx->fStatus &= ~PDMAUDIOSTREAM_STS_PAUSED;
2806 PDMAUDIOSTREAM_STS_ASSERT_VALID(pStreamEx->fStatus);
2807 }
2808 }
2809 break;
2810
2811 case PDMAUDIOSTREAMCMD_DRAIN:
2812 /*
2813 * Only for output streams and we don't want this command more than once.
2814 */
2815 AssertReturn(pStreamEx->Core.enmDir == PDMAUDIODIR_OUT, VERR_INVALID_FUNCTION);
2816 AssertBreak(!(pStreamEx->fStatus & PDMAUDIOSTREAM_STS_PENDING_DISABLE));
2817 if (pStreamEx->fStatus & PDMAUDIOSTREAM_STS_ENABLED)
2818 {
2819 rc = VERR_INTERNAL_ERROR_2;
2820 switch (pStreamEx->Out.enmPlayState)
2821 {
2822 case DRVAUDIOPLAYSTATE_PREBUF:
2823 if (pStreamEx->Out.cbPreBuffered > 0)
2824 {
2825 LogFunc(("DRAIN '%s': Initiating draining of pre-buffered data...\n", pStreamEx->Core.szName));
2826 pStreamEx->Out.enmPlayState = DRVAUDIOPLAYSTATE_PREBUF_COMMITTING;
2827 pStreamEx->fStatus |= PDMAUDIOSTREAM_STS_PENDING_DISABLE;
2828 PDMAUDIOSTREAM_STS_ASSERT_VALID(pStreamEx->fStatus);
2829 rc = VINF_SUCCESS;
2830 break;
2831 }
2832 RT_FALL_THROUGH();
2833 case DRVAUDIOPLAYSTATE_NOPLAY:
2834 case DRVAUDIOPLAYSTATE_PREBUF_SWITCHING:
2835 case DRVAUDIOPLAYSTATE_PREBUF_OVERDUE:
2836 LogFunc(("DRAIN '%s': Nothing to drain (enmPlayState=%s)\n",
2837 pStreamEx->Core.szName, drvAudioPlayStateName(pStreamEx->Out.enmPlayState)));
2838 rc = drvAudioStreamControlInternalBackend(pThis, pStreamEx, PDMAUDIOSTREAMCMD_DISABLE);
2839 AssertRC(rc);
2840 drvAudioStreamResetOnDisable(pStreamEx);
2841 break;
2842
2843 case DRVAUDIOPLAYSTATE_PLAY:
2844 case DRVAUDIOPLAYSTATE_PLAY_PREBUF:
2845 LogFunc(("DRAIN '%s': Initiating backend draining (enmPlayState=%s -> NOPLAY) ...\n",
2846 pStreamEx->Core.szName, drvAudioPlayStateName(pStreamEx->Out.enmPlayState)));
2847 pStreamEx->Out.enmPlayState = DRVAUDIOPLAYSTATE_NOPLAY;
2848 rc = drvAudioStreamControlInternalBackend(pThis, pStreamEx, PDMAUDIOSTREAMCMD_DRAIN);
2849 if (RT_SUCCESS(rc))
2850 {
2851 pStreamEx->fStatus |= PDMAUDIOSTREAM_STS_PENDING_DISABLE;
2852 PDMAUDIOSTREAM_STS_ASSERT_VALID(pStreamEx->fStatus);
2853 }
2854 else
2855 {
2856 LogFunc(("DRAIN '%s': Backend DRAIN failed with %Rrc, disabling the stream instead...\n",
2857 pStreamEx->Core.szName, rc));
2858 rc = drvAudioStreamControlInternalBackend(pThis, pStreamEx, PDMAUDIOSTREAMCMD_DISABLE);
2859 AssertRC(rc);
2860 drvAudioStreamResetOnDisable(pStreamEx);
2861 }
2862 break;
2863
2864 case DRVAUDIOPLAYSTATE_PREBUF_COMMITTING:
2865 LogFunc(("DRAIN '%s': Initiating draining of pre-buffered data (already committing)...\n",
2866 pStreamEx->Core.szName));
2867 pStreamEx->fStatus |= PDMAUDIOSTREAM_STS_PENDING_DISABLE;
2868 PDMAUDIOSTREAM_STS_ASSERT_VALID(pStreamEx->fStatus);
2869 rc = VINF_SUCCESS;
2870 break;
2871
2872 /* no default */
2873 case DRVAUDIOPLAYSTATE_INVALID:
2874 case DRVAUDIOPLAYSTATE_END:
2875 AssertFailedBreak();
2876 }
2877 }
2878 break;
2879
2880 default:
2881 rc = VERR_NOT_IMPLEMENTED;
2882 break;
2883 }
2884
2885 if (RT_FAILURE(rc))
2886 LogFunc(("[%s] Failed with %Rrc\n", pStreamEx->Core.szName, rc));
2887
2888 return rc;
2889}
2890
2891
2892/**
2893 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnStreamControl}
2894 */
2895static DECLCALLBACK(int) drvAudioStreamControl(PPDMIAUDIOCONNECTOR pInterface,
2896 PPDMAUDIOSTREAM pStream, PDMAUDIOSTREAMCMD enmStreamCmd)
2897{
2898 PDRVAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVAUDIO, IAudioConnector);
2899 AssertPtr(pThis);
2900
2901 /** @todo r=bird: why? It's not documented to ignore NULL streams. */
2902 if (!pStream)
2903 return VINF_SUCCESS;
2904 PDRVAUDIOSTREAM pStreamEx = (PDRVAUDIOSTREAM)pStream;
2905 AssertPtrReturn(pStreamEx, VERR_INVALID_POINTER);
2906 AssertReturn(pStreamEx->Core.uMagic == PDMAUDIOSTREAM_MAGIC, VERR_INVALID_MAGIC);
2907 AssertReturn(pStreamEx->uMagic == DRVAUDIOSTREAM_MAGIC, VERR_INVALID_MAGIC);
2908
2909 int rc = RTCritSectEnter(&pStreamEx->Core.CritSect);
2910 AssertRCReturn(rc, rc);
2911
2912 LogFlowFunc(("[%s] enmStreamCmd=%s\n", pStream->szName, PDMAudioStrmCmdGetName(enmStreamCmd)));
2913
2914 rc = drvAudioStreamControlInternal(pThis, pStreamEx, enmStreamCmd);
2915
2916 RTCritSectLeave(&pStreamEx->Core.CritSect);
2917 return rc;
2918}
2919
2920
2921/**
2922 * Copy data to the pre-buffer, ring-buffer style.
2923 *
2924 * The @a cbMax parameter is almost always set to the threshold size, the
2925 * exception is when commiting the buffer and we want to top it off to reduce
2926 * the number of transfers to the backend (the first transfer may start
2927 * playback, so more data is better).
2928 */
2929static int drvAudioStreamPreBuffer(PDRVAUDIOSTREAM pStreamEx, const uint8_t *pbBuf, uint32_t cbBuf, uint32_t cbMax)
2930{
2931 uint32_t const cbAlloc = pStreamEx->Out.cbPreBufAlloc;
2932 AssertReturn(cbAlloc >= cbMax, VERR_INTERNAL_ERROR_3);
2933 AssertReturn(cbAlloc >= 8, VERR_INTERNAL_ERROR_4);
2934 AssertReturn(cbMax >= 8, VERR_INTERNAL_ERROR_5);
2935
2936 uint32_t offRead = pStreamEx->Out.offPreBuf;
2937 uint32_t cbCur = pStreamEx->Out.cbPreBuffered;
2938 AssertStmt(offRead < cbAlloc, offRead %= cbAlloc);
2939 AssertStmt(cbCur <= cbMax, offRead = (offRead + cbCur - cbMax) % cbAlloc; cbCur = cbMax);
2940
2941 /*
2942 * First chunk.
2943 */
2944 uint32_t offWrite = (offRead + cbCur) % cbAlloc;
2945 uint32_t cbToCopy = RT_MIN(cbAlloc - offWrite, cbBuf);
2946 memcpy(&pStreamEx->Out.pbPreBuf[offWrite], pbBuf, cbToCopy);
2947
2948 /* Advance. */
2949 offWrite = (offWrite + cbToCopy) % cbAlloc;
2950 for (;;)
2951 {
2952 pbBuf += cbToCopy;
2953 cbCur += cbToCopy;
2954 if (cbCur > cbMax)
2955 offRead = (offRead + cbCur - cbMax) % cbAlloc;
2956 cbBuf -= cbToCopy;
2957 if (!cbBuf)
2958 break;
2959
2960 /*
2961 * Second+ chunk, from the start of the buffer.
2962 *
2963 * Note! It is assumed very unlikely that we will ever see a cbBuf larger than
2964 * cbMax, so we don't waste space on clipping cbBuf here (can happen with
2965 * custom pre-buffer sizes).
2966 */
2967 Assert(offWrite == 0);
2968 cbToCopy = RT_MIN(cbAlloc, cbBuf);
2969 memcpy(pStreamEx->Out.pbPreBuf, pbBuf, cbToCopy);
2970 }
2971
2972 /*
2973 * Update the pre-buffering size and position.
2974 */
2975 pStreamEx->Out.cbPreBuffered = RT_MIN(cbCur, cbMax);
2976 pStreamEx->Out.offPreBuf = offRead;
2977 return VINF_SUCCESS;
2978}
2979
2980
2981/**
2982 * Worker for drvAudioStreamPlay() and drvAudioStreamPreBufComitting().
2983 *
2984 * Caller owns the lock.
2985 */
2986static int drvAudioStreamPlayLocked(PDRVAUDIO pThis, PDRVAUDIOSTREAM pStreamEx,
2987 const uint8_t *pbBuf, uint32_t cbBuf, uint32_t *pcbWritten)
2988{
2989 Log3Func(("%s: @%#RX64: cbBuf=%#x\n", pStreamEx->Core.szName, pStreamEx->offInternal, cbBuf));
2990
2991 uint32_t cbWritable = pThis->pHostDrvAudio->pfnStreamGetWritable(pThis->pHostDrvAudio, pStreamEx->pBackend);
2992 pStreamEx->Out.Stats.cbBackendWritableBefore = cbWritable;
2993
2994 uint32_t cbWritten = 0;
2995 int rc = VINF_SUCCESS;
2996 uint8_t const cbFrame = PDMAudioPropsFrameSize(&pStreamEx->Core.Props);
2997 while (cbBuf >= cbFrame && cbWritable >= cbFrame)
2998 {
2999 uint32_t const cbToWrite = PDMAudioPropsFloorBytesToFrame(&pStreamEx->Core.Props, RT_MIN(cbBuf, cbWritable));
3000 uint32_t cbWrittenNow = 0;
3001 rc = pThis->pHostDrvAudio->pfnStreamPlay(pThis->pHostDrvAudio, pStreamEx->pBackend, pbBuf, cbToWrite, &cbWrittenNow);
3002 if (RT_SUCCESS(rc))
3003 {
3004 if (cbWrittenNow != cbToWrite)
3005 Log3Func(("%s: @%#RX64: Wrote fewer bytes than requested: %#x, requested %#x\n",
3006 pStreamEx->Core.szName, pStreamEx->offInternal, cbWrittenNow, cbToWrite));
3007#ifdef DEBUG_bird
3008 Assert(cbWrittenNow == cbToWrite);
3009#endif
3010 AssertStmt(cbWrittenNow <= cbToWrite, cbWrittenNow = cbToWrite);
3011 cbWritten += cbWrittenNow;
3012 cbBuf -= cbWrittenNow;
3013 pbBuf += cbWrittenNow;
3014 pStreamEx->offInternal += cbWrittenNow;
3015 }
3016 else
3017 {
3018 *pcbWritten = cbWritten;
3019 LogFunc(("%s: @%#RX64: pfnStreamPlay failed writing %#x bytes (%#x previous written, %#x writable): %Rrc\n",
3020 pStreamEx->Core.szName, pStreamEx->offInternal, cbToWrite, cbWritten, cbWritable, rc));
3021 return cbWritten ? VINF_SUCCESS : rc;
3022 }
3023
3024 cbWritable = pThis->pHostDrvAudio->pfnStreamGetWritable(pThis->pHostDrvAudio, pStreamEx->pBackend);
3025 }
3026
3027 *pcbWritten = cbWritten;
3028 pStreamEx->Out.Stats.cbBackendWritableAfter = cbWritable;
3029 if (cbWritten)
3030 pStreamEx->nsLastPlayedCaptured = RTTimeNanoTS();
3031
3032 Log3Func(("%s: @%#RX64: Wrote %#x bytes (%#x bytes left)\n", pStreamEx->Core.szName, pStreamEx->offInternal, cbWritten, cbBuf));
3033 return rc;
3034}
3035
3036
3037/**
3038 * Worker for drvAudioStreamPlay() and drvAudioStreamPreBufComitting().
3039 */
3040static int drvAudioStreamPlayToPreBuffer(PDRVAUDIOSTREAM pStreamEx, const void *pvBuf, uint32_t cbBuf, uint32_t cbMax,
3041 uint32_t *pcbWritten)
3042{
3043 int rc = drvAudioStreamPreBuffer(pStreamEx, (uint8_t const *)pvBuf, cbBuf, cbMax);
3044 if (RT_SUCCESS(rc))
3045 {
3046 *pcbWritten = cbBuf;
3047 pStreamEx->offInternal += cbBuf;
3048 Log3Func(("[%s] Pre-buffering (%s): wrote %#x bytes => %#x bytes / %u%%\n",
3049 pStreamEx->Core.szName, drvAudioPlayStateName(pStreamEx->Out.enmPlayState), cbBuf, pStreamEx->Out.cbPreBuffered,
3050 pStreamEx->Out.cbPreBuffered * 100 / RT_MAX(pStreamEx->cbPreBufThreshold, 1)));
3051
3052 }
3053 else
3054 *pcbWritten = 0;
3055 return rc;
3056}
3057
3058
3059/**
3060 * Used when we're committing (transfering) the pre-buffered bytes to the
3061 * device.
3062 *
3063 * This is called both from drvAudioStreamPlay() and
3064 * drvAudioStreamIterateInternal().
3065 *
3066 * @returns VBox status code.
3067 * @param pThis Pointer to the DrvAudio instance data.
3068 * @param pStreamEx The stream to commit the pre-buffering for.
3069 * @param pbBuf Buffer with new bytes to write. Can be NULL when called
3070 * in the PENDING_DISABLE state from
3071 * drvAudioStreamIterateInternal().
3072 * @param cbBuf Number of new bytes. Can be zero.
3073 * @param pcbWritten Where to return the number of bytes written.
3074 *
3075 * @note Locking: Stream critsect and hot-plug in shared mode.
3076 */
3077static int drvAudioStreamPreBufComitting(PDRVAUDIO pThis, PDRVAUDIOSTREAM pStreamEx,
3078 const uint8_t *pbBuf, uint32_t cbBuf, uint32_t *pcbWritten)
3079{
3080 /*
3081 * First, top up the buffer with new data from pbBuf.
3082 */
3083 *pcbWritten = 0;
3084 if (cbBuf > 0)
3085 {
3086 uint32_t const cbToCopy = RT_MIN(pStreamEx->Out.cbPreBufAlloc - pStreamEx->Out.cbPreBuffered, cbBuf);
3087 if (cbToCopy > 0)
3088 {
3089 int rc = drvAudioStreamPlayToPreBuffer(pStreamEx, pbBuf, cbBuf, pStreamEx->Out.cbPreBufAlloc, pcbWritten);
3090 AssertRCReturn(rc, rc);
3091 pbBuf += cbToCopy;
3092 cbBuf -= cbToCopy;
3093 }
3094 }
3095
3096 AssertReturn(pThis->pHostDrvAudio, VERR_AUDIO_BACKEND_NOT_ATTACHED);
3097
3098 /*
3099 * Write the pre-buffered chunk.
3100 */
3101 int rc = VINF_SUCCESS;
3102 uint32_t const cbAlloc = pStreamEx->Out.cbPreBufAlloc;
3103 AssertReturn(cbAlloc > 0, VERR_INTERNAL_ERROR_2);
3104 uint32_t off = pStreamEx->Out.offPreBuf;
3105 AssertStmt(off < pStreamEx->Out.cbPreBufAlloc, off %= cbAlloc);
3106 uint32_t cbLeft = pStreamEx->Out.cbPreBuffered;
3107 while (cbLeft > 0)
3108 {
3109 uint32_t const cbToWrite = RT_MIN(cbAlloc - off, cbLeft);
3110 Assert(cbToWrite > 0);
3111
3112 uint32_t cbPreBufWritten = 0;
3113 rc = pThis->pHostDrvAudio->pfnStreamPlay(pThis->pHostDrvAudio, pStreamEx->pBackend, &pStreamEx->Out.pbPreBuf[off],
3114 cbToWrite, &cbPreBufWritten);
3115 AssertRCBreak(rc);
3116 if (!cbPreBufWritten)
3117 break;
3118 AssertStmt(cbPreBufWritten <= cbToWrite, cbPreBufWritten = cbToWrite);
3119 off = (off + cbPreBufWritten) % cbAlloc;
3120 cbLeft -= cbPreBufWritten;
3121 }
3122
3123 if (cbLeft == 0)
3124 {
3125 LogFunc(("@%#RX64: Wrote all %#x bytes of pre-buffered audio data. %s -> PLAY\n", pStreamEx->offInternal,
3126 pStreamEx->Out.cbPreBuffered, drvAudioPlayStateName(pStreamEx->Out.enmPlayState) ));
3127 pStreamEx->Out.cbPreBuffered = 0;
3128 pStreamEx->Out.offPreBuf = 0;
3129 pStreamEx->Out.enmPlayState = DRVAUDIOPLAYSTATE_PLAY;
3130
3131 if (cbBuf > 0)
3132 {
3133 uint32_t cbWritten2 = 0;
3134 rc = drvAudioStreamPlayLocked(pThis, pStreamEx, pbBuf, cbBuf, &cbWritten2);
3135 if (RT_SUCCESS(rc))
3136 *pcbWritten += cbWritten2;
3137 }
3138 else
3139 pStreamEx->nsLastPlayedCaptured = RTTimeNanoTS();
3140 }
3141 else
3142 {
3143 if (cbLeft != pStreamEx->Out.cbPreBuffered)
3144 pStreamEx->nsLastPlayedCaptured = RTTimeNanoTS();
3145
3146 LogRel2(("Audio: @%#RX64: Stream '%s' pre-buffering commit problem: wrote %#x out of %#x + %#x - rc=%Rrc *pcbWritten=%#x %s -> PREBUF_COMMITTING\n",
3147 pStreamEx->offInternal, pStreamEx->Core.szName, pStreamEx->Out.cbPreBuffered - cbLeft,
3148 pStreamEx->Out.cbPreBuffered, cbBuf, rc, *pcbWritten, drvAudioPlayStateName(pStreamEx->Out.enmPlayState) ));
3149 AssertMsg( pStreamEx->Out.enmPlayState == DRVAUDIOPLAYSTATE_PREBUF_COMMITTING
3150 || pStreamEx->Out.enmPlayState == DRVAUDIOPLAYSTATE_PREBUF
3151 || RT_FAILURE(rc),
3152 ("Buggy host driver buffer reporting? cbLeft=%#x cbPreBuffered=%#x enmPlayState=%s\n",
3153 cbLeft, pStreamEx->Out.cbPreBuffered, drvAudioPlayStateName(pStreamEx->Out.enmPlayState) ));
3154
3155 pStreamEx->Out.cbPreBuffered = cbLeft;
3156 pStreamEx->Out.offPreBuf = off;
3157 pStreamEx->Out.enmPlayState = DRVAUDIOPLAYSTATE_PREBUF_COMMITTING;
3158 }
3159
3160 return *pcbWritten ? VINF_SUCCESS : rc;
3161}
3162
3163
3164/**
3165 * Does one iteration of an audio stream.
3166 *
3167 * This function gives the backend the chance of iterating / altering data and
3168 * does the actual mixing between the guest <-> host mixing buffers.
3169 *
3170 * @returns VBox status code.
3171 * @param pThis Pointer to driver instance.
3172 * @param pStreamEx Stream to iterate.
3173 */
3174static int drvAudioStreamIterateInternal(PDRVAUDIO pThis, PDRVAUDIOSTREAM pStreamEx)
3175{
3176 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
3177
3178#ifdef LOG_ENABLED
3179 char szStreamSts[DRVAUDIO_STATUS_STR_MAX];
3180#endif
3181 Log3Func(("[%s] fStatus=%s\n", pStreamEx->Core.szName, drvAudioStreamStatusToStr(szStreamSts, pStreamEx->fStatus)));
3182
3183 /* Not enabled or paused? Skip iteration. */
3184 if ((pStreamEx->fStatus & (PDMAUDIOSTREAM_STS_ENABLED | PDMAUDIOSTREAM_STS_PAUSED)) != PDMAUDIOSTREAM_STS_ENABLED)
3185 return VINF_SUCCESS;
3186
3187 /*
3188 * Pending disable is really what we're here for.
3189 *
3190 * This only happens to output streams. We ASSUME the caller (MixerBuffer)
3191 * implements a timeout on the draining, so we skip that here.
3192 */
3193 if (!(pStreamEx->fStatus & PDMAUDIOSTREAM_STS_PENDING_DISABLE))
3194 { /* likely until we get to the end of the stream at least. */ }
3195 else
3196 {
3197 AssertReturn(pStreamEx->Core.enmDir == PDMAUDIODIR_OUT, VINF_SUCCESS);
3198 RTCritSectRwEnterShared(&pThis->CritSectHotPlug);
3199
3200 /*
3201 * Move pre-buffered samples to the backend.
3202 */
3203 if (pStreamEx->Out.enmPlayState == DRVAUDIOPLAYSTATE_PREBUF_COMMITTING)
3204 {
3205 if (pStreamEx->Out.cbPreBuffered > 0)
3206 {
3207 uint32_t cbIgnored = 0;
3208 drvAudioStreamPreBufComitting(pThis, pStreamEx, NULL, 0, &cbIgnored);
3209 Log3Func(("Stream '%s': Transferred %#x bytes\n", pStreamEx->Core.szName, cbIgnored));
3210 }
3211 if (pStreamEx->Out.cbPreBuffered == 0)
3212 {
3213 Log3Func(("Stream '%s': No more pre-buffered data -> NOPLAY + backend DRAIN\n", pStreamEx->Core.szName));
3214 pStreamEx->Out.enmPlayState = DRVAUDIOPLAYSTATE_NOPLAY;
3215
3216 int rc = drvAudioStreamControlInternalBackend(pThis, pStreamEx, PDMAUDIOSTREAMCMD_DRAIN);
3217 if (RT_FAILURE(rc))
3218 {
3219 LogFunc(("Stream '%s': Backend DRAIN failed with %Rrc, disabling the stream instead...\n",
3220 pStreamEx->Core.szName, rc));
3221 rc = drvAudioStreamControlInternalBackend(pThis, pStreamEx, PDMAUDIOSTREAMCMD_DISABLE);
3222 AssertRC(rc);
3223 drvAudioStreamResetOnDisable(pStreamEx);
3224 }
3225 }
3226 }
3227 else
3228 Assert(pStreamEx->Out.enmPlayState == DRVAUDIOPLAYSTATE_NOPLAY);
3229
3230 /*
3231 * Check the backend status to see if it's still draining and to
3232 * update our status when it stops doing so.
3233 */
3234 PDMHOSTAUDIOSTREAMSTATE const enmBackendState = drvAudioStreamGetBackendState(pThis, pStreamEx);
3235 if (enmBackendState == PDMHOSTAUDIOSTREAMSTATE_DRAINING)
3236 {
3237 uint32_t cbIgnored = 0;
3238 pThis->pHostDrvAudio->pfnStreamPlay(pThis->pHostDrvAudio, pStreamEx->pBackend, NULL, 0, &cbIgnored);
3239 }
3240 else
3241 {
3242 LogFunc(("Stream '%s': Backend finished draining.\n", pStreamEx->Core.szName));
3243 drvAudioStreamResetOnDisable(pStreamEx);
3244 }
3245
3246 RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
3247 }
3248
3249 /* Update timestamps. */
3250 pStreamEx->nsLastIterated = RTTimeNanoTS();
3251
3252 return VINF_SUCCESS; /** @todo r=bird: What can the caller do with an error status here? */
3253}
3254
3255
3256/**
3257 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnStreamIterate}
3258 */
3259static DECLCALLBACK(int) drvAudioStreamIterate(PPDMIAUDIOCONNECTOR pInterface, PPDMAUDIOSTREAM pStream)
3260{
3261 PDRVAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVAUDIO, IAudioConnector);
3262 AssertPtr(pThis);
3263 PDRVAUDIOSTREAM pStreamEx = (PDRVAUDIOSTREAM)pStream;
3264 AssertPtrReturn(pStreamEx, VERR_INVALID_POINTER);
3265 AssertReturn(pStreamEx->Core.uMagic == PDMAUDIOSTREAM_MAGIC, VERR_INVALID_MAGIC);
3266 AssertReturn(pStreamEx->uMagic == DRVAUDIOSTREAM_MAGIC, VERR_INVALID_MAGIC);
3267
3268 int rc = RTCritSectEnter(&pStreamEx->Core.CritSect);
3269 AssertRCReturn(rc, rc);
3270
3271 rc = drvAudioStreamIterateInternal(pThis, pStreamEx);
3272
3273 RTCritSectLeave(&pStreamEx->Core.CritSect);
3274
3275 if (RT_FAILURE(rc))
3276 LogFlowFuncLeaveRC(rc);
3277 return rc;
3278}
3279
3280
3281/**
3282 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnStreamGetState}
3283 */
3284static DECLCALLBACK(PDMAUDIOSTREAMSTATE) drvAudioStreamGetState(PPDMIAUDIOCONNECTOR pInterface, PPDMAUDIOSTREAM pStream)
3285{
3286 PDRVAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVAUDIO, IAudioConnector);
3287 PDRVAUDIOSTREAM pStreamEx = (PDRVAUDIOSTREAM)pStream;
3288 AssertPtrReturn(pStreamEx, PDMAUDIOSTREAMSTATE_INVALID);
3289 AssertReturn(pStreamEx->Core.uMagic == PDMAUDIOSTREAM_MAGIC, PDMAUDIOSTREAMSTATE_INVALID);
3290 AssertReturn(pStreamEx->uMagic == DRVAUDIOSTREAM_MAGIC, PDMAUDIOSTREAMSTATE_INVALID);
3291
3292 /*
3293 * Get the status mask.
3294 */
3295 int rc = RTCritSectEnter(&pStreamEx->Core.CritSect);
3296 AssertRCReturn(rc, PDMAUDIOSTREAMSTATE_INVALID);
3297 RTCritSectRwEnterShared(&pThis->CritSectHotPlug);
3298
3299 PDMHOSTAUDIOSTREAMSTATE const enmBackendState = drvAudioStreamGetBackendStateAndProcessChanges(pThis, pStreamEx);
3300 uint32_t const fStrmStatus = pStreamEx->fStatus;
3301 PDMAUDIODIR const enmDir = pStreamEx->Guest.Cfg.enmDir;
3302 Assert(enmDir == PDMAUDIODIR_IN || enmDir == PDMAUDIODIR_OUT);
3303
3304 RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
3305 RTCritSectLeave(&pStreamEx->Core.CritSect);
3306
3307 /*
3308 * Translate it to state enum value.
3309 */
3310 PDMAUDIOSTREAMSTATE enmState;
3311 if (!(fStrmStatus & PDMAUDIOSTREAM_STS_NEED_REINIT))
3312 {
3313 if (fStrmStatus & PDMAUDIOSTREAM_STS_BACKEND_CREATED)
3314 {
3315 if ( (fStrmStatus & PDMAUDIOSTREAM_STS_ENABLED)
3316 && (enmDir == PDMAUDIODIR_IN ? pThis->In.fEnabled : pThis->Out.fEnabled)
3317 && ( enmBackendState == PDMHOSTAUDIOSTREAMSTATE_OKAY
3318 || enmBackendState == PDMHOSTAUDIOSTREAMSTATE_DRAINING
3319 || enmBackendState == PDMHOSTAUDIOSTREAMSTATE_INITIALIZING ))
3320 enmState = enmDir == PDMAUDIODIR_IN ? PDMAUDIOSTREAMSTATE_ENABLED_READABLE : PDMAUDIOSTREAMSTATE_ENABLED_WRITABLE;
3321 else
3322 enmState = PDMAUDIOSTREAMSTATE_INACTIVE;
3323 }
3324 else
3325 enmState = PDMAUDIOSTREAMSTATE_NOT_WORKING;
3326 }
3327 else
3328 enmState = PDMAUDIOSTREAMSTATE_NEED_REINIT;
3329
3330#ifdef LOG_ENABLED
3331 char szStreamSts[DRVAUDIO_STATUS_STR_MAX];
3332#endif
3333 Log3Func(("[%s] returns %s (status: %s)\n", pStreamEx->Core.szName, PDMAudioStreamStateGetName(enmState),
3334 drvAudioStreamStatusToStr(szStreamSts, fStrmStatus)));
3335 return enmState;
3336}
3337
3338
3339/**
3340 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnStreamGetWritable}
3341 */
3342static DECLCALLBACK(uint32_t) drvAudioStreamGetWritable(PPDMIAUDIOCONNECTOR pInterface, PPDMAUDIOSTREAM pStream)
3343{
3344 PDRVAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVAUDIO, IAudioConnector);
3345 AssertPtr(pThis);
3346 PDRVAUDIOSTREAM pStreamEx = (PDRVAUDIOSTREAM)pStream;
3347 AssertPtrReturn(pStreamEx, 0);
3348 AssertReturn(pStreamEx->Core.uMagic == PDMAUDIOSTREAM_MAGIC, 0);
3349 AssertReturn(pStreamEx->uMagic == DRVAUDIOSTREAM_MAGIC, 0);
3350 AssertMsgReturn(pStreamEx->Core.enmDir == PDMAUDIODIR_OUT, ("Can't write to a non-output stream\n"), 0);
3351
3352 int rc = RTCritSectEnter(&pStreamEx->Core.CritSect);
3353 AssertRCReturn(rc, 0);
3354 RTCritSectRwEnterShared(&pThis->CritSectHotPlug);
3355
3356 /*
3357 * Use the playback and backend states to determin how much can be written, if anything.
3358 */
3359 uint32_t cbWritable = 0;
3360 DRVAUDIOPLAYSTATE const enmPlayMode = pStreamEx->Out.enmPlayState;
3361 PDMHOSTAUDIOSTREAMSTATE const enmBackendState = drvAudioStreamGetBackendState(pThis, pStreamEx);
3362 if ( PDMAudioStrmStatusCanWrite(pStreamEx->fStatus)
3363 && pThis->pHostDrvAudio != NULL
3364 && enmBackendState != PDMHOSTAUDIOSTREAMSTATE_DRAINING)
3365 {
3366 switch (enmPlayMode)
3367 {
3368 /*
3369 * Whatever the backend can hold.
3370 */
3371 case DRVAUDIOPLAYSTATE_PLAY:
3372 case DRVAUDIOPLAYSTATE_PLAY_PREBUF:
3373 Assert(pStreamEx->fStatus & PDMAUDIOSTREAM_STS_BACKEND_READY);
3374 Assert(enmBackendState == PDMHOSTAUDIOSTREAMSTATE_OKAY /* potential unplug race */);
3375 cbWritable = pThis->pHostDrvAudio->pfnStreamGetWritable(pThis->pHostDrvAudio, pStreamEx->pBackend);
3376 break;
3377
3378 /*
3379 * Whatever we've got of available space in the pre-buffer.
3380 * Note! For the last round when we pass the pre-buffering threshold, we may
3381 * report fewer bytes than what a DMA timer period for the guest device
3382 * typically produces, however that should be transfered in the following
3383 * round that goes directly to the backend buffer.
3384 */
3385 case DRVAUDIOPLAYSTATE_PREBUF:
3386 cbWritable = pStreamEx->Out.cbPreBufAlloc - pStreamEx->Out.cbPreBuffered;
3387 if (!cbWritable)
3388 cbWritable = PDMAudioPropsFramesToBytes(&pStreamEx->Core.Props, 2);
3389 break;
3390
3391 /*
3392 * These are slightly more problematic and can go wrong if the pre-buffer is
3393 * manually configured to be smaller than the output of a typeical DMA timer
3394 * period for the guest device. So, to overcompensate, we just report back
3395 * the backend buffer size (the pre-buffer is circular, so no overflow issue).
3396 */
3397 case DRVAUDIOPLAYSTATE_PREBUF_OVERDUE:
3398 case DRVAUDIOPLAYSTATE_PREBUF_SWITCHING:
3399 cbWritable = PDMAudioPropsFramesToBytes(&pStreamEx->Core.Props,
3400 RT_MAX(pStreamEx->Host.Cfg.Backend.cFramesBufferSize,
3401 pStreamEx->Host.Cfg.Backend.cFramesPreBuffering));
3402 break;
3403
3404 case DRVAUDIOPLAYSTATE_PREBUF_COMMITTING:
3405 {
3406 /* Buggy backend: We weren't able to copy all the pre-buffered data to it
3407 when reaching the threshold. Try escape this situation, or at least
3408 keep the extra buffering to a minimum. We must try write something
3409 as long as there is space for it, as we need the pfnStreamWrite call
3410 to move the data. */
3411 Assert(pStreamEx->fStatus & PDMAUDIOSTREAM_STS_BACKEND_READY);
3412 Assert(enmBackendState == PDMHOSTAUDIOSTREAMSTATE_OKAY /* potential unplug race */);
3413 uint32_t const cbMin = PDMAudioPropsFramesToBytes(&pStreamEx->Core.Props, 8);
3414 cbWritable = pThis->pHostDrvAudio->pfnStreamGetWritable(pThis->pHostDrvAudio, pStreamEx->pBackend);
3415 if (cbWritable >= pStreamEx->Out.cbPreBuffered + cbMin)
3416 cbWritable -= pStreamEx->Out.cbPreBuffered + cbMin / 2;
3417 else
3418 cbWritable = RT_MIN(cbMin, pStreamEx->Out.cbPreBufAlloc - pStreamEx->Out.cbPreBuffered);
3419 AssertLogRel(cbWritable);
3420 break;
3421 }
3422
3423 case DRVAUDIOPLAYSTATE_NOPLAY:
3424 break;
3425 case DRVAUDIOPLAYSTATE_INVALID:
3426 case DRVAUDIOPLAYSTATE_END:
3427 AssertFailed();
3428 break;
3429 }
3430
3431 /* Make sure to align the writable size to the host's frame size. */
3432 cbWritable = PDMAudioPropsFloorBytesToFrame(&pStreamEx->Host.Cfg.Props, cbWritable);
3433 }
3434
3435 RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
3436 RTCritSectLeave(&pStreamEx->Core.CritSect);
3437 Log3Func(("[%s] cbWritable=%#RX32 (%RU64ms) enmPlayMode=%s enmBackendState=%s\n",
3438 pStreamEx->Core.szName, cbWritable, PDMAudioPropsBytesToMilli(&pStreamEx->Host.Cfg.Props, cbWritable),
3439 drvAudioPlayStateName(enmPlayMode), PDMHostAudioStreamStateGetName(enmBackendState) ));
3440 return cbWritable;
3441}
3442
3443
3444/**
3445 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnStreamPlay}
3446 */
3447static DECLCALLBACK(int) drvAudioStreamPlay(PPDMIAUDIOCONNECTOR pInterface, PPDMAUDIOSTREAM pStream,
3448 const void *pvBuf, uint32_t cbBuf, uint32_t *pcbWritten)
3449{
3450 PDRVAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVAUDIO, IAudioConnector);
3451 AssertPtr(pThis);
3452
3453 /*
3454 * Check input and sanity.
3455 */
3456 AssertPtrReturn(pInterface, VERR_INVALID_POINTER);
3457 PDRVAUDIOSTREAM pStreamEx = (PDRVAUDIOSTREAM)pStream;
3458 AssertPtrReturn(pStreamEx, VERR_INVALID_POINTER);
3459 AssertPtrReturn(pvBuf, VERR_INVALID_POINTER);
3460 AssertReturn(cbBuf, VERR_INVALID_PARAMETER);
3461 uint32_t uTmp;
3462 if (pcbWritten)
3463 AssertPtrReturn(pcbWritten, VERR_INVALID_PARAMETER);
3464 else
3465 pcbWritten = &uTmp;
3466
3467 AssertReturn(pStreamEx->Core.uMagic == PDMAUDIOSTREAM_MAGIC, VERR_INVALID_MAGIC);
3468 AssertReturn(pStreamEx->uMagic == DRVAUDIOSTREAM_MAGIC, VERR_INVALID_MAGIC);
3469 AssertMsgReturn(pStreamEx->Core.enmDir == PDMAUDIODIR_OUT,
3470 ("Stream '%s' is not an output stream and therefore cannot be written to (direction is '%s')\n",
3471 pStreamEx->Core.szName, PDMAudioDirGetName(pStreamEx->Core.enmDir)), VERR_ACCESS_DENIED);
3472
3473 AssertMsg(PDMAudioPropsIsSizeAligned(&pStreamEx->Guest.Cfg.Props, cbBuf),
3474 ("Stream '%s' got a non-frame-aligned write (%#RX32 bytes)\n", pStreamEx->Core.szName, cbBuf));
3475
3476 int rc = RTCritSectEnter(&pStreamEx->Core.CritSect);
3477 AssertRCReturn(rc, rc);
3478
3479 /*
3480 * First check that we can write to the stream, and if not,
3481 * whether to just drop the input into the bit bucket.
3482 */
3483 if (PDMAudioStrmStatusIsReady(pStreamEx->fStatus))
3484 {
3485 RTCritSectRwEnterShared(&pThis->CritSectHotPlug);
3486 if ( pThis->Out.fEnabled /* (see @bugref{9882}) */
3487 && pThis->pHostDrvAudio != NULL)
3488 {
3489 /*
3490 * Get the backend state and process changes to it since last time we checked.
3491 */
3492 PDMHOSTAUDIOSTREAMSTATE const enmBackendState = drvAudioStreamGetBackendStateAndProcessChanges(pThis, pStreamEx);
3493
3494 /*
3495 * Do the transfering.
3496 */
3497 switch (pStreamEx->Out.enmPlayState)
3498 {
3499 case DRVAUDIOPLAYSTATE_PLAY:
3500 Assert(pStreamEx->fStatus & PDMAUDIOSTREAM_STS_BACKEND_READY);
3501 Assert(enmBackendState == PDMHOSTAUDIOSTREAMSTATE_OKAY);
3502 rc = drvAudioStreamPlayLocked(pThis, pStreamEx, (uint8_t const *)pvBuf, cbBuf, pcbWritten);
3503 break;
3504
3505 case DRVAUDIOPLAYSTATE_PLAY_PREBUF:
3506 Assert(pStreamEx->fStatus & PDMAUDIOSTREAM_STS_BACKEND_READY);
3507 Assert(enmBackendState == PDMHOSTAUDIOSTREAMSTATE_OKAY);
3508 rc = drvAudioStreamPlayLocked(pThis, pStreamEx, (uint8_t const *)pvBuf, cbBuf, pcbWritten);
3509 drvAudioStreamPreBuffer(pStreamEx, (uint8_t const *)pvBuf, *pcbWritten, pStreamEx->cbPreBufThreshold);
3510 break;
3511
3512 case DRVAUDIOPLAYSTATE_PREBUF:
3513 if (cbBuf + pStreamEx->Out.cbPreBuffered < pStreamEx->cbPreBufThreshold)
3514 rc = drvAudioStreamPlayToPreBuffer(pStreamEx, pvBuf, cbBuf, pStreamEx->cbPreBufThreshold, pcbWritten);
3515 else if ( enmBackendState == PDMHOSTAUDIOSTREAMSTATE_OKAY
3516 && (pStreamEx->fStatus & PDMAUDIOSTREAM_STS_BACKEND_READY))
3517 {
3518 Log3Func(("[%s] Pre-buffering completing: cbBuf=%#x cbPreBuffered=%#x => %#x vs cbPreBufThreshold=%#x\n",
3519 pStreamEx->Core.szName, cbBuf, pStreamEx->Out.cbPreBuffered,
3520 cbBuf + pStreamEx->Out.cbPreBuffered, pStreamEx->cbPreBufThreshold));
3521 rc = drvAudioStreamPreBufComitting(pThis, pStreamEx, (uint8_t const *)pvBuf, cbBuf, pcbWritten);
3522 }
3523 else
3524 {
3525 Log3Func(("[%s] Pre-buffering completing but device not ready: cbBuf=%#x cbPreBuffered=%#x => %#x vs cbPreBufThreshold=%#x; PREBUF -> PREBUF_OVERDUE\n",
3526 pStreamEx->Core.szName, cbBuf, pStreamEx->Out.cbPreBuffered,
3527 cbBuf + pStreamEx->Out.cbPreBuffered, pStreamEx->cbPreBufThreshold));
3528 pStreamEx->Out.enmPlayState = DRVAUDIOPLAYSTATE_PREBUF_OVERDUE;
3529 rc = drvAudioStreamPlayToPreBuffer(pStreamEx, pvBuf, cbBuf, pStreamEx->cbPreBufThreshold, pcbWritten);
3530 }
3531 break;
3532
3533 case DRVAUDIOPLAYSTATE_PREBUF_OVERDUE:
3534 Assert( !(pStreamEx->fStatus & PDMAUDIOSTREAM_STS_BACKEND_READY)
3535 || enmBackendState != PDMHOSTAUDIOSTREAMSTATE_OKAY);
3536 RT_FALL_THRU();
3537 case DRVAUDIOPLAYSTATE_PREBUF_SWITCHING:
3538 rc = drvAudioStreamPlayToPreBuffer(pStreamEx, pvBuf, cbBuf, pStreamEx->cbPreBufThreshold, pcbWritten);
3539 break;
3540
3541 case DRVAUDIOPLAYSTATE_PREBUF_COMMITTING:
3542 Assert(pStreamEx->fStatus & PDMAUDIOSTREAM_STS_BACKEND_READY);
3543 Assert(enmBackendState == PDMHOSTAUDIOSTREAMSTATE_OKAY);
3544 rc = drvAudioStreamPreBufComitting(pThis, pStreamEx, (uint8_t const *)pvBuf, cbBuf, pcbWritten);
3545 break;
3546
3547 case DRVAUDIOPLAYSTATE_NOPLAY:
3548 *pcbWritten = cbBuf;
3549 pStreamEx->offInternal += cbBuf;
3550 Log3Func(("[%s] Discarding the data, backend state: %s\n", pStreamEx->Core.szName,
3551 PDMHostAudioStreamStateGetName(enmBackendState) ));
3552 break;
3553
3554 default:
3555 *pcbWritten = cbBuf;
3556 AssertMsgFailedBreak(("%d; cbBuf=%#x\n", pStreamEx->Out.enmPlayState, cbBuf));
3557 }
3558
3559 if (!pThis->CfgOut.Dbg.fEnabled || RT_FAILURE(rc))
3560 { /* likely */ }
3561 else
3562 AudioHlpFileWrite(pStreamEx->Out.Dbg.pFilePlay, pvBuf, *pcbWritten, 0 /* fFlags */);
3563 }
3564 else
3565 {
3566 *pcbWritten = cbBuf;
3567 pStreamEx->offInternal += cbBuf;
3568 Log3Func(("[%s] Backend stream %s, discarding the data\n", pStreamEx->Core.szName,
3569 !pThis->Out.fEnabled ? "disabled" : !pThis->pHostDrvAudio ? "not attached" : "not ready yet"));
3570 }
3571 RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
3572 }
3573 else
3574 rc = VERR_AUDIO_STREAM_NOT_READY;
3575
3576 RTCritSectLeave(&pStreamEx->Core.CritSect);
3577 return rc;
3578}
3579
3580
3581/**
3582 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnStreamGetReadable}
3583 */
3584static DECLCALLBACK(uint32_t) drvAudioStreamGetReadable(PPDMIAUDIOCONNECTOR pInterface, PPDMAUDIOSTREAM pStream)
3585{
3586 PDRVAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVAUDIO, IAudioConnector);
3587 AssertPtr(pThis);
3588 PDRVAUDIOSTREAM pStreamEx = (PDRVAUDIOSTREAM)pStream;
3589 AssertPtrReturn(pStreamEx, 0);
3590 AssertReturn(pStreamEx->Core.uMagic == PDMAUDIOSTREAM_MAGIC, 0);
3591 AssertReturn(pStreamEx->uMagic == DRVAUDIOSTREAM_MAGIC, 0);
3592 AssertMsg(pStreamEx->Core.enmDir == PDMAUDIODIR_IN, ("Can't read from a non-input stream\n"));
3593
3594
3595 int rc = RTCritSectEnter(&pStreamEx->Core.CritSect);
3596 AssertRCReturn(rc, 0);
3597 RTCritSectRwEnterShared(&pThis->CritSectHotPlug);
3598
3599 /*
3600 * Use the capture state to determin how much can be written, if anything.
3601 */
3602 uint32_t cbReadable = 0;
3603 DRVAUDIOCAPTURESTATE const enmCaptureState = pStreamEx->In.enmCaptureState;
3604 PDMHOSTAUDIOSTREAMSTATE const enmBackendState = drvAudioStreamGetBackendState(pThis, pStreamEx); RT_NOREF(enmBackendState);
3605 if ( PDMAudioStrmStatusCanRead(pStreamEx->fStatus)
3606 && pThis->pHostDrvAudio != NULL)
3607 {
3608 switch (enmCaptureState)
3609 {
3610 /*
3611 * Whatever the backend has to offer when in capture mode.
3612 */
3613 case DRVAUDIOCAPTURESTATE_CAPTURING:
3614 Assert(pStreamEx->fStatus & PDMAUDIOSTREAM_STS_BACKEND_READY);
3615 Assert(enmBackendState == PDMHOSTAUDIOSTREAMSTATE_OKAY /* potential unplug race */);
3616 cbReadable = pThis->pHostDrvAudio->pfnStreamGetReadable(pThis->pHostDrvAudio, pStreamEx->pBackend);
3617 break;
3618
3619 /*
3620 * Same calculation as in drvAudioStreamCaptureSilence, only we cap it
3621 * at the pre-buffering threshold so we don't get into trouble when we
3622 * switch to capture mode between now and pfnStreamCapture.
3623 */
3624 case DRVAUDIOCAPTURESTATE_PREBUF:
3625 {
3626 uint64_t const cNsStream = RTTimeNanoTS() - pStreamEx->nsStarted;
3627 uint64_t const offCur = PDMAudioPropsNanoToBytes64(&pStreamEx->Guest.Cfg.Props, cNsStream);
3628 if (offCur > pStreamEx->offInternal)
3629 {
3630 uint64_t const cbUnread = offCur - pStreamEx->offInternal;
3631 cbReadable = (uint32_t)RT_MIN(pStreamEx->cbPreBufThreshold, cbUnread);
3632 }
3633 break;
3634 }
3635
3636 case DRVAUDIOCAPTURESTATE_NO_CAPTURE:
3637 break;
3638
3639 case DRVAUDIOCAPTURESTATE_INVALID:
3640 case DRVAUDIOCAPTURESTATE_END:
3641 AssertFailed();
3642 break;
3643 }
3644
3645 /* Make sure to align the readable size to the host's frame size. */
3646 cbReadable = PDMAudioPropsFloorBytesToFrame(&pStreamEx->Host.Cfg.Props, cbReadable);
3647 }
3648
3649 RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
3650 RTCritSectLeave(&pStreamEx->Core.CritSect);
3651 Log3Func(("[%s] cbReadable=%#RX32 (%RU64ms) enmCaptureMode=%s enmBackendState=%s\n",
3652 pStreamEx->Core.szName, cbReadable, PDMAudioPropsBytesToMilli(&pStreamEx->Host.Cfg.Props, cbReadable),
3653 drvAudioCaptureStateName(enmCaptureState), PDMHostAudioStreamStateGetName(enmBackendState) ));
3654 return cbReadable;
3655}
3656
3657
3658/**
3659 * Worker for drvAudioStreamCapture that returns silence.
3660 *
3661 * The amount of silence returned is a function of how long the stream has been
3662 * enabled.
3663 *
3664 * @returns VINF_SUCCESS
3665 * @param pStreamEx The stream to commit the pre-buffering for.
3666 * @param pbBuf The output buffer.
3667 * @param cbBuf The size of the output buffer.
3668 * @param pcbRead Where to return the number of bytes actually read.
3669 */
3670static int drvAudioStreamCaptureSilence(PDRVAUDIOSTREAM pStreamEx, uint8_t *pbBuf, uint32_t cbBuf, uint32_t *pcbRead)
3671{
3672 /** @todo Does not take paused time into account... */
3673 uint64_t const cNsStream = RTTimeNanoTS() - pStreamEx->nsStarted;
3674 uint64_t const offCur = PDMAudioPropsNanoToBytes64(&pStreamEx->Guest.Cfg.Props, cNsStream);
3675 if (offCur > pStreamEx->offInternal)
3676 {
3677 uint64_t const cbUnread = offCur - pStreamEx->offInternal;
3678 uint32_t const cbToClear = (uint32_t)RT_MIN(cbBuf, cbUnread);
3679 *pcbRead = cbToClear;
3680 pStreamEx->offInternal += cbToClear;
3681 cbBuf -= cbToClear;
3682 PDMAudioPropsClearBuffer(&pStreamEx->Guest.Cfg.Props, pbBuf, cbToClear,
3683 PDMAudioPropsBytesToFrames(&pStreamEx->Guest.Cfg.Props, cbToClear));
3684 }
3685 else
3686 *pcbRead = 0;
3687 Log4Func(("%s: @%#RX64: Read %#x bytes of silence (%#x bytes left)\n",
3688 pStreamEx->Core.szName, pStreamEx->offInternal, *pcbRead, cbBuf));
3689 return VINF_SUCCESS;
3690}
3691
3692
3693/**
3694 * Worker for drvAudioStreamCapture.
3695 */
3696static int drvAudioStreamCaptureLocked(PDRVAUDIO pThis, PDRVAUDIOSTREAM pStreamEx,
3697 uint8_t *pbBuf, uint32_t cbBuf, uint32_t *pcbRead)
3698{
3699 Log4Func(("%s: @%#RX64: cbBuf=%#x\n", pStreamEx->Core.szName, pStreamEx->offInternal, cbBuf));
3700
3701 uint32_t cbReadable = pThis->pHostDrvAudio->pfnStreamGetReadable(pThis->pHostDrvAudio, pStreamEx->pBackend);
3702 pStreamEx->In.Stats.cbBackendReadableBefore = cbReadable;
3703
3704 uint32_t cbRead = 0;
3705 int rc = VINF_SUCCESS;
3706 uint8_t const cbFrame = PDMAudioPropsFrameSize(&pStreamEx->Core.Props);
3707 while (cbBuf >= cbFrame && cbReadable >= cbFrame)
3708 {
3709 uint32_t const cbToRead = PDMAudioPropsFloorBytesToFrame(&pStreamEx->Core.Props, RT_MIN(cbBuf, cbReadable));
3710 uint32_t cbReadNow = 0;
3711 rc = pThis->pHostDrvAudio->pfnStreamCapture(pThis->pHostDrvAudio, pStreamEx->pBackend, pbBuf, cbToRead, &cbReadNow);
3712 if (RT_SUCCESS(rc))
3713 {
3714 if (cbReadNow != cbToRead)
3715 Log4Func(("%s: @%#RX64: Read fewer bytes than requested: %#x, requested %#x\n",
3716 pStreamEx->Core.szName, pStreamEx->offInternal, cbReadNow, cbToRead));
3717#ifdef DEBUG_bird
3718 Assert(cbReadNow == cbToRead);
3719#endif
3720 AssertStmt(cbReadNow <= cbToRead, cbReadNow = cbToRead);
3721 cbRead += cbReadNow;
3722 cbBuf -= cbReadNow;
3723 pbBuf += cbReadNow;
3724 pStreamEx->offInternal += cbReadNow;
3725 }
3726 else
3727 {
3728 *pcbRead = cbRead;
3729 LogFunc(("%s: @%#RX64: pfnStreamCapture failed read %#x bytes (%#x previous read, %#x readable): %Rrc\n",
3730 pStreamEx->Core.szName, pStreamEx->offInternal, cbToRead, cbRead, cbReadable, rc));
3731 return cbRead ? VINF_SUCCESS : rc;
3732 }
3733
3734 cbReadable = pThis->pHostDrvAudio->pfnStreamGetReadable(pThis->pHostDrvAudio, pStreamEx->pBackend);
3735 }
3736
3737 *pcbRead = cbRead;
3738 pStreamEx->In.Stats.cbBackendReadableAfter = cbReadable;
3739 if (cbRead)
3740 pStreamEx->nsLastPlayedCaptured = RTTimeNanoTS();
3741
3742 Log4Func(("%s: @%#RX64: Read %#x bytes (%#x bytes left)\n", pStreamEx->Core.szName, pStreamEx->offInternal, cbRead, cbBuf));
3743 return rc;
3744}
3745
3746
3747/**
3748 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnStreamCapture}
3749 */
3750static DECLCALLBACK(int) drvAudioStreamCapture(PPDMIAUDIOCONNECTOR pInterface, PPDMAUDIOSTREAM pStream,
3751 void *pvBuf, uint32_t cbBuf, uint32_t *pcbRead)
3752{
3753 PDRVAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVAUDIO, IAudioConnector);
3754 AssertPtr(pThis);
3755
3756 /*
3757 * Check input and sanity.
3758 */
3759 AssertPtrReturn(pInterface, VERR_INVALID_POINTER);
3760 PDRVAUDIOSTREAM pStreamEx = (PDRVAUDIOSTREAM)pStream;
3761 AssertPtrReturn(pStreamEx, VERR_INVALID_POINTER);
3762 AssertPtrReturn(pvBuf, VERR_INVALID_POINTER);
3763 AssertReturn(cbBuf, VERR_INVALID_PARAMETER);
3764 uint32_t uTmp;
3765 if (pcbRead)
3766 AssertPtrReturn(pcbRead, VERR_INVALID_PARAMETER);
3767 else
3768 pcbRead = &uTmp;
3769
3770 AssertReturn(pStreamEx->Core.uMagic == PDMAUDIOSTREAM_MAGIC, VERR_INVALID_MAGIC);
3771 AssertReturn(pStreamEx->uMagic == DRVAUDIOSTREAM_MAGIC, VERR_INVALID_MAGIC);
3772 AssertMsgReturn(pStreamEx->Core.enmDir == PDMAUDIODIR_IN,
3773 ("Stream '%s' is not an input stream and therefore cannot be read from (direction is '%s')\n",
3774 pStreamEx->Core.szName, PDMAudioDirGetName(pStreamEx->Core.enmDir)), VERR_ACCESS_DENIED);
3775
3776 AssertMsg(PDMAudioPropsIsSizeAligned(&pStreamEx->Guest.Cfg.Props, cbBuf),
3777 ("Stream '%s' got a non-frame-aligned write (%#RX32 bytes)\n", pStreamEx->Core.szName, cbBuf));
3778
3779 int rc = RTCritSectEnter(&pStreamEx->Core.CritSect);
3780 AssertRCReturn(rc, rc);
3781
3782 /*
3783 * First check that we can read from the stream, and if not,
3784 * whether to just drop the input into the bit bucket.
3785 */
3786 if (PDMAudioStrmStatusIsReady(pStreamEx->fStatus))
3787 {
3788 RTCritSectRwEnterShared(&pThis->CritSectHotPlug);
3789 if ( pThis->In.fEnabled /* (see @bugref{9882}) */
3790 && pThis->pHostDrvAudio != NULL)
3791 {
3792 /*
3793 * Get the backend state and process changes to it since last time we checked.
3794 */
3795 PDMHOSTAUDIOSTREAMSTATE const enmBackendState = drvAudioStreamGetBackendStateAndProcessChanges(pThis, pStreamEx);
3796
3797 /*
3798 * Do the transfering.
3799 */
3800 switch (pStreamEx->In.enmCaptureState)
3801 {
3802 case DRVAUDIOCAPTURESTATE_CAPTURING:
3803 Assert(pStreamEx->fStatus & PDMAUDIOSTREAM_STS_BACKEND_READY);
3804 Assert(enmBackendState == PDMHOSTAUDIOSTREAMSTATE_OKAY);
3805 rc = drvAudioStreamCaptureLocked(pThis, pStreamEx, (uint8_t *)pvBuf, cbBuf, pcbRead);
3806 break;
3807
3808 case DRVAUDIOCAPTURESTATE_PREBUF:
3809 if (enmBackendState == PDMHOSTAUDIOSTREAMSTATE_OKAY)
3810 {
3811 uint32_t const cbReadable = pThis->pHostDrvAudio->pfnStreamGetReadable(pThis->pHostDrvAudio,
3812 pStreamEx->pBackend);
3813 if (cbReadable >= pStreamEx->cbPreBufThreshold)
3814 {
3815 Log4Func(("[%s] Pre-buffering completed: cbReadable=%#x vs cbPreBufThreshold=%#x (cbBuf=%#x)\n",
3816 pStreamEx->Core.szName, cbReadable, pStreamEx->cbPreBufThreshold, cbBuf));
3817 pStreamEx->In.enmCaptureState = DRVAUDIOCAPTURESTATE_CAPTURING;
3818 rc = drvAudioStreamCaptureLocked(pThis, pStreamEx, (uint8_t *)pvBuf, cbBuf, pcbRead);
3819 break;
3820 }
3821 pStreamEx->In.Stats.cbBackendReadableBefore = cbReadable;
3822 pStreamEx->In.Stats.cbBackendReadableAfter = cbReadable;
3823 Log4Func(("[%s] Pre-buffering: Got %#x out of %#x\n",
3824 pStreamEx->Core.szName, cbReadable, pStreamEx->cbPreBufThreshold));
3825 }
3826 else
3827 Log4Func(("[%s] Pre-buffering: Backend status %s\n",
3828 pStreamEx->Core.szName, PDMHostAudioStreamStateGetName(enmBackendState) ));
3829 drvAudioStreamCaptureSilence(pStreamEx, (uint8_t *)pvBuf, cbBuf, pcbRead);
3830 break;
3831
3832 case DRVAUDIOCAPTURESTATE_NO_CAPTURE:
3833 *pcbRead = 0;
3834 Log4Func(("[%s] Not capturing - backend state: %s\n",
3835 pStreamEx->Core.szName, PDMHostAudioStreamStateGetName(enmBackendState) ));
3836 break;
3837
3838 default:
3839 *pcbRead = 0;
3840 AssertMsgFailedBreak(("%d; cbBuf=%#x\n", pStreamEx->In.enmCaptureState, cbBuf));
3841 }
3842
3843 if (!pThis->CfgIn.Dbg.fEnabled || RT_FAILURE(rc))
3844 { /* likely */ }
3845 else
3846 AudioHlpFileWrite(pStreamEx->In.Dbg.pFileCapture, pvBuf, *pcbRead, 0 /* fFlags */);
3847 }
3848 else
3849 {
3850 *pcbRead = 0;
3851 Log4Func(("[%s] Backend stream %s, returning no data\n", pStreamEx->Core.szName,
3852 !pThis->Out.fEnabled ? "disabled" : !pThis->pHostDrvAudio ? "not attached" : "not ready yet"));
3853 }
3854 RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
3855 }
3856 else
3857 rc = VERR_AUDIO_STREAM_NOT_READY;
3858
3859 RTCritSectLeave(&pStreamEx->Core.CritSect);
3860 return rc;
3861}
3862
3863
3864/*********************************************************************************************************************************
3865* PDMIHOSTAUDIOPORT interface implementation. *
3866*********************************************************************************************************************************/
3867
3868/**
3869 * Worker for drvAudioHostPort_DoOnWorkerThread with stream argument, called on
3870 * worker thread.
3871 */
3872static DECLCALLBACK(void) drvAudioHostPort_DoOnWorkerThreadStreamWorker(PDRVAUDIO pThis, PDRVAUDIOSTREAM pStreamEx,
3873 uintptr_t uUser, void *pvUser)
3874{
3875 LogFlowFunc(("pThis=%p uUser=%#zx pvUser=%p\n", pThis, uUser, pvUser));
3876 AssertPtrReturnVoid(pThis);
3877 AssertPtrReturnVoid(pStreamEx);
3878 AssertReturnVoid(pStreamEx->uMagic == DRVAUDIOSTREAM_MAGIC);
3879
3880 /*
3881 * The CritSectHotPlug lock should not be needed here as detach will destroy
3882 * the thread pool. So, we'll leave taking the stream lock to the worker we're
3883 * calling as there are no lock order concerns.
3884 */
3885 PPDMIHOSTAUDIO const pIHostDrvAudio = pThis->pHostDrvAudio;
3886 AssertPtrReturnVoid(pIHostDrvAudio);
3887 AssertPtrReturnVoid(pIHostDrvAudio->pfnDoOnWorkerThread);
3888 pIHostDrvAudio->pfnDoOnWorkerThread(pIHostDrvAudio, pStreamEx->pBackend, uUser, pvUser);
3889
3890 drvAudioStreamReleaseInternal(pThis, pStreamEx, true /*fMayDestroy*/);
3891 LogFlowFunc(("returns\n"));
3892}
3893
3894
3895/**
3896 * Worker for drvAudioHostPort_DoOnWorkerThread without stream argument, called
3897 * on worker thread.
3898 *
3899 * This wrapper isn't technically required, but it helps with logging and a few
3900 * extra sanity checks.
3901 */
3902static DECLCALLBACK(void) drvAudioHostPort_DoOnWorkerThreadWorker(PDRVAUDIO pThis, uintptr_t uUser, void *pvUser)
3903{
3904 LogFlowFunc(("pThis=%p uUser=%#zx pvUser=%p\n", pThis, uUser, pvUser));
3905 AssertPtrReturnVoid(pThis);
3906
3907 /*
3908 * The CritSectHotPlug lock should not be needed here as detach will destroy
3909 * the thread pool.
3910 */
3911 PPDMIHOSTAUDIO const pIHostDrvAudio = pThis->pHostDrvAudio;
3912 AssertPtrReturnVoid(pIHostDrvAudio);
3913 AssertPtrReturnVoid(pIHostDrvAudio->pfnDoOnWorkerThread);
3914
3915 pIHostDrvAudio->pfnDoOnWorkerThread(pIHostDrvAudio, NULL, uUser, pvUser);
3916
3917 LogFlowFunc(("returns\n"));
3918}
3919
3920
3921/**
3922 * @interface_method_impl{PDMIHOSTAUDIOPORT,pfnDoOnWorkerThread}
3923 */
3924static DECLCALLBACK(int) drvAudioHostPort_DoOnWorkerThread(PPDMIHOSTAUDIOPORT pInterface, PPDMAUDIOBACKENDSTREAM pStream,
3925 uintptr_t uUser, void *pvUser)
3926{
3927 PDRVAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVAUDIO, IHostAudioPort);
3928 LogFlowFunc(("pStream=%p uUser=%#zx pvUser=%p\n", pStream, uUser, pvUser));
3929
3930 /*
3931 * Assert some sanity.
3932 */
3933 PDRVAUDIOSTREAM pStreamEx;
3934 if (!pStream)
3935 pStreamEx = NULL;
3936 else
3937 {
3938 AssertPtrReturn(pStream, VERR_INVALID_POINTER);
3939 AssertReturn(pStream->uMagic == PDMAUDIOBACKENDSTREAM_MAGIC, VERR_INVALID_MAGIC);
3940 pStreamEx = (PDRVAUDIOSTREAM)pStream->pStream;
3941 AssertPtrReturn(pStreamEx, VERR_INVALID_POINTER);
3942 AssertReturn(pStreamEx->uMagic == DRVAUDIOSTREAM_MAGIC, VERR_INVALID_MAGIC);
3943 AssertReturn(pStreamEx->Core.uMagic == PDMAUDIOSTREAM_MAGIC, VERR_INVALID_MAGIC);
3944 }
3945
3946 int rc = RTCritSectRwEnterShared(&pThis->CritSectHotPlug);
3947 AssertRCReturn(rc, rc);
3948
3949 Assert(pThis->hReqPool != NIL_RTREQPOOL);
3950 AssertPtr(pThis->pHostDrvAudio);
3951 if ( pThis->hReqPool != NIL_RTREQPOOL
3952 && pThis->pHostDrvAudio != NULL)
3953 {
3954 AssertPtr(pThis->pHostDrvAudio->pfnDoOnWorkerThread);
3955 if (pThis->pHostDrvAudio->pfnDoOnWorkerThread)
3956 {
3957 /*
3958 * Try do the work.
3959 */
3960 if (!pStreamEx)
3961 {
3962 rc = RTReqPoolCallEx(pThis->hReqPool, 0 /*cMillies*/, NULL /*phReq*/, RTREQFLAGS_VOID | RTREQFLAGS_NO_WAIT,
3963 (PFNRT)drvAudioHostPort_DoOnWorkerThreadWorker, 3, pThis, uUser, pvUser);
3964 AssertRC(rc);
3965 }
3966 else
3967 {
3968 uint32_t cRefs = drvAudioStreamRetainInternal(pStreamEx);
3969 if (cRefs != UINT32_MAX)
3970 {
3971 rc = RTReqPoolCallEx(pThis->hReqPool, 0 /*cMillies*/, NULL, RTREQFLAGS_VOID | RTREQFLAGS_NO_WAIT,
3972 (PFNRT)drvAudioHostPort_DoOnWorkerThreadStreamWorker,
3973 4, pThis, pStreamEx, uUser, pvUser);
3974 AssertRC(rc);
3975 if (RT_FAILURE(rc))
3976 {
3977 RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
3978 drvAudioStreamReleaseInternal(pThis, pStreamEx, true /*fMayDestroy*/);
3979 RTCritSectRwEnterShared(&pThis->CritSectHotPlug);
3980 }
3981 }
3982 else
3983 rc = VERR_INVALID_PARAMETER;
3984 }
3985 }
3986 else
3987 rc = VERR_INVALID_FUNCTION;
3988 }
3989 else
3990 rc = VERR_INVALID_STATE;
3991
3992 RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
3993 LogFlowFunc(("returns %Rrc\n", rc));
3994 return rc;
3995}
3996
3997
3998/**
3999 * Marks a stream for re-init.
4000 */
4001static void drvAudioStreamMarkNeedReInit(PDRVAUDIOSTREAM pStreamEx, const char *pszCaller)
4002{
4003 LogFlow((LOG_FN_FMT ": Flagging %s for re-init.\n", pszCaller, pStreamEx->Core.szName)); RT_NOREF(pszCaller);
4004 Assert(RTCritSectIsOwner(&pStreamEx->Core.CritSect));
4005
4006 pStreamEx->fStatus |= PDMAUDIOSTREAM_STS_NEED_REINIT;
4007 PDMAUDIOSTREAM_STS_ASSERT_VALID(pStreamEx->fStatus);
4008 pStreamEx->cTriesReInit = 0;
4009 pStreamEx->nsLastReInit = 0;
4010}
4011
4012
4013/**
4014 * @interface_method_impl{PDMIHOSTAUDIOPORT,pfnNotifyDeviceChanged}
4015 */
4016static DECLCALLBACK(void) drvAudioHostPort_NotifyDeviceChanged(PPDMIHOSTAUDIOPORT pInterface, PDMAUDIODIR enmDir, void *pvUser)
4017{
4018 PDRVAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVAUDIO, IHostAudioPort);
4019 AssertReturnVoid(enmDir == PDMAUDIODIR_IN || enmDir == PDMAUDIODIR_OUT);
4020 LogRel(("Audio: The %s device for %s is changing.\n", enmDir == PDMAUDIODIR_IN ? "input" : "output", pThis->BackendCfg.szName));
4021
4022 /*
4023 * Grab the list lock in shared mode and do the work.
4024 */
4025 int rc = RTCritSectRwEnterShared(&pThis->CritSectGlobals);
4026 AssertRCReturnVoid(rc);
4027
4028 PDRVAUDIOSTREAM pStreamEx;
4029 RTListForEach(&pThis->LstStreams, pStreamEx, DRVAUDIOSTREAM, ListEntry)
4030 {
4031 if (pStreamEx->Core.enmDir == enmDir)
4032 {
4033 RTCritSectEnter(&pStreamEx->Core.CritSect);
4034 RTCritSectRwEnterShared(&pThis->CritSectHotPlug);
4035
4036 if (pThis->pHostDrvAudio->pfnStreamNotifyDeviceChanged)
4037 {
4038 LogFlowFunc(("Calling pfnStreamNotifyDeviceChanged on %s, old backend state: %s...\n", pStreamEx->Core.szName,
4039 PDMHostAudioStreamStateGetName(drvAudioStreamGetBackendState(pThis, pStreamEx)) ));
4040 pThis->pHostDrvAudio->pfnStreamNotifyDeviceChanged(pThis->pHostDrvAudio, pStreamEx->pBackend, pvUser);
4041 LogFlowFunc(("New stream backend state: %s\n",
4042 PDMHostAudioStreamStateGetName(drvAudioStreamGetBackendState(pThis, pStreamEx)) ));
4043 }
4044 else
4045 drvAudioStreamMarkNeedReInit(pStreamEx, __PRETTY_FUNCTION__);
4046
4047 RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
4048 RTCritSectLeave(&pStreamEx->Core.CritSect);
4049 }
4050 }
4051
4052 RTCritSectRwLeaveShared(&pThis->CritSectGlobals);
4053}
4054
4055
4056/**
4057 * @interface_method_impl{PDMIHOSTAUDIOPORT,pfnStreamNotifyPreparingDeviceSwitch}
4058 */
4059static DECLCALLBACK(void) drvAudioHostPort_StreamNotifyPreparingDeviceSwitch(PPDMIHOSTAUDIOPORT pInterface,
4060 PPDMAUDIOBACKENDSTREAM pStream)
4061{
4062 RT_NOREF(pInterface);
4063
4064 /*
4065 * Backend stream to validated DrvAudio stream:
4066 */
4067 AssertPtrReturnVoid(pStream);
4068 AssertReturnVoid(pStream->uMagic == PDMAUDIOBACKENDSTREAM_MAGIC);
4069 PDRVAUDIOSTREAM pStreamEx = (PDRVAUDIOSTREAM)pStream->pStream;
4070 AssertPtrReturnVoid(pStreamEx);
4071 AssertReturnVoid(pStreamEx->Core.uMagic == PDMAUDIOSTREAM_MAGIC);
4072 AssertReturnVoid(pStreamEx->uMagic == DRVAUDIOSTREAM_MAGIC);
4073 LogFlowFunc(("pStreamEx=%p '%s'\n", pStreamEx, pStreamEx->Core.szName));
4074
4075 /*
4076 * Grab the lock and do switch the state (only needed for output streams for now).
4077 */
4078 RTCritSectEnter(&pStreamEx->Core.CritSect);
4079 AssertReturnVoidStmt(pStreamEx->uMagic == DRVAUDIOSTREAM_MAGIC, RTCritSectLeave(&pStreamEx->Core.CritSect)); /* paranoia */
4080
4081 if (pStreamEx->Core.enmDir == PDMAUDIODIR_OUT)
4082 {
4083 if (pStreamEx->cbPreBufThreshold > 0)
4084 {
4085 DRVAUDIOPLAYSTATE const enmPlayState = pStreamEx->Out.enmPlayState;
4086 switch (enmPlayState)
4087 {
4088 case DRVAUDIOPLAYSTATE_PREBUF:
4089 case DRVAUDIOPLAYSTATE_PREBUF_OVERDUE:
4090 case DRVAUDIOPLAYSTATE_NOPLAY:
4091 case DRVAUDIOPLAYSTATE_PREBUF_COMMITTING: /* simpler */
4092 pStreamEx->Out.enmPlayState = DRVAUDIOPLAYSTATE_PREBUF_SWITCHING;
4093 break;
4094 case DRVAUDIOPLAYSTATE_PLAY:
4095 pStreamEx->Out.enmPlayState = DRVAUDIOPLAYSTATE_PLAY_PREBUF;
4096 break;
4097 case DRVAUDIOPLAYSTATE_PREBUF_SWITCHING:
4098 case DRVAUDIOPLAYSTATE_PLAY_PREBUF:
4099 break;
4100 /* no default */
4101 case DRVAUDIOPLAYSTATE_END:
4102 case DRVAUDIOPLAYSTATE_INVALID:
4103 break;
4104 }
4105 LogFunc(("%s -> %s\n", drvAudioPlayStateName(enmPlayState), drvAudioPlayStateName(pStreamEx->Out.enmPlayState) ));
4106 }
4107 else
4108 LogFunc(("No pre-buffering configured.\n"));
4109 }
4110 else
4111 LogFunc(("input stream, nothing to do.\n"));
4112
4113 RTCritSectLeave(&pStreamEx->Core.CritSect);
4114}
4115
4116
4117/**
4118 * @interface_method_impl{PDMIHOSTAUDIOPORT,pfnStreamNotifyDeviceChanged}
4119 */
4120static DECLCALLBACK(void) drvAudioHostPort_StreamNotifyDeviceChanged(PPDMIHOSTAUDIOPORT pInterface,
4121 PPDMAUDIOBACKENDSTREAM pStream, bool fReInit)
4122{
4123 PDRVAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVAUDIO, IHostAudioPort);
4124
4125 /*
4126 * Backend stream to validated DrvAudio stream:
4127 */
4128 AssertPtrReturnVoid(pStream);
4129 AssertReturnVoid(pStream->uMagic == PDMAUDIOBACKENDSTREAM_MAGIC);
4130 PDRVAUDIOSTREAM pStreamEx = (PDRVAUDIOSTREAM)pStream->pStream;
4131 AssertPtrReturnVoid(pStreamEx);
4132 AssertReturnVoid(pStreamEx->Core.uMagic == PDMAUDIOSTREAM_MAGIC);
4133 AssertReturnVoid(pStreamEx->uMagic == DRVAUDIOSTREAM_MAGIC);
4134
4135 /*
4136 * Grab the lock and do the requested work.
4137 */
4138 RTCritSectEnter(&pStreamEx->Core.CritSect);
4139 AssertReturnVoidStmt(pStreamEx->uMagic == DRVAUDIOSTREAM_MAGIC, RTCritSectLeave(&pStreamEx->Core.CritSect)); /* paranoia */
4140
4141 if (fReInit)
4142 drvAudioStreamMarkNeedReInit(pStreamEx, __PRETTY_FUNCTION__);
4143 else
4144 {
4145 /*
4146 * Adjust the stream state now that the device has (perhaps finally) been switched.
4147 *
4148 * For enabled output streams, we must update the play state. We could try commit
4149 * pre-buffered data here, but it's really not worth the hazzle and risk (don't
4150 * know which thread we're on, do we now).
4151 */
4152 AssertStmt(!(pStreamEx->fStatus & PDMAUDIOSTREAM_STS_NEED_REINIT),
4153 pStreamEx->fStatus &= ~PDMAUDIOSTREAM_STS_NEED_REINIT);
4154
4155
4156 if (pStreamEx->Core.enmDir == PDMAUDIODIR_OUT)
4157 {
4158 DRVAUDIOPLAYSTATE const enmPlayState = pStreamEx->Out.enmPlayState;
4159 pStreamEx->Out.enmPlayState = DRVAUDIOPLAYSTATE_PREBUF;
4160 LogFunc(("%s: %s -> %s\n", pStreamEx->Core.szName, drvAudioPlayStateName(enmPlayState),
4161 drvAudioPlayStateName(pStreamEx->Out.enmPlayState) ));
4162 RT_NOREF(enmPlayState);
4163 }
4164
4165 /* Disable and then fully resync. */
4166 /** @todo This doesn't work quite reliably if we're in draining mode
4167 * (PENDING_DISABLE, so the backend needs to take care of that prior to calling
4168 * us. Sigh. The idea was to avoid extra state mess in the backend... */
4169 drvAudioStreamControlInternalBackend(pThis, pStreamEx, PDMAUDIOSTREAMCMD_DISABLE);
4170 drvAudioStreamUpdateBackendOnStatus(pThis, pStreamEx, "device changed");
4171 }
4172
4173 RTCritSectLeave(&pStreamEx->Core.CritSect);
4174}
4175
4176
4177#ifdef VBOX_WITH_AUDIO_ENUM
4178/**
4179 * @callback_method_impl{FNTMTIMERDRV, Re-enumerate backend devices.}
4180 *
4181 * Used to do/trigger re-enumeration of backend devices with a delay after we
4182 * got notification as there can be further notifications following shortly
4183 * after the first one. Also good to get it of random COM/whatever threads.
4184 */
4185static DECLCALLBACK(void) drvAudioEnumerateTimer(PPDMDRVINS pDrvIns, TMTIMERHANDLE hTimer, void *pvUser)
4186{
4187 PDRVAUDIO pThis = PDMINS_2_DATA(pDrvIns, PDRVAUDIO);
4188 RT_NOREF(hTimer, pvUser);
4189
4190 /* Try push the work over to the thread-pool if we've got one. */
4191 RTCritSectRwEnterShared(&pThis->CritSectHotPlug);
4192 if (pThis->hReqPool != NIL_RTREQPOOL)
4193 {
4194 int rc = RTReqPoolCallEx(pThis->hReqPool, 0 /*cMillies*/, NULL, RTREQFLAGS_VOID | RTREQFLAGS_NO_WAIT,
4195 (PFNRT)drvAudioDevicesEnumerateInternal,
4196 3, pThis, true /*fLog*/, (PPDMAUDIOHOSTENUM)NULL /*pDevEnum*/);
4197 LogFunc(("RTReqPoolCallEx: %Rrc\n", rc));
4198 RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
4199 if (RT_SUCCESS(rc))
4200 return;
4201 }
4202 else
4203 RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
4204
4205 LogFunc(("Calling drvAudioDevicesEnumerateInternal...\n"));
4206 drvAudioDevicesEnumerateInternal(pThis, true /* fLog */, NULL /* pDevEnum */);
4207}
4208#endif /* VBOX_WITH_AUDIO_ENUM */
4209
4210
4211/**
4212 * @interface_method_impl{PDMIHOSTAUDIOPORT,pfnNotifyDevicesChanged}
4213 */
4214static DECLCALLBACK(void) drvAudioHostPort_NotifyDevicesChanged(PPDMIHOSTAUDIOPORT pInterface)
4215{
4216 PDRVAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVAUDIO, IHostAudioPort);
4217 LogRel(("Audio: Device configuration of driver '%s' has changed\n", pThis->BackendCfg.szName));
4218
4219#ifdef RT_OS_DARWIN /** @todo Remove legacy behaviour: */
4220 /* Mark all host streams to re-initialize. */
4221 int rc2 = RTCritSectRwEnterShared(&pThis->CritSectGlobals);
4222 AssertRCReturnVoid(rc2);
4223 PDRVAUDIOSTREAM pStreamEx;
4224 RTListForEach(&pThis->LstStreams, pStreamEx, DRVAUDIOSTREAM, ListEntry)
4225 {
4226 RTCritSectEnter(&pStreamEx->Core.CritSect);
4227 drvAudioStreamMarkNeedReInit(pStreamEx, __PRETTY_FUNCTION__);
4228 RTCritSectLeave(&pStreamEx->Core.CritSect);
4229 }
4230 RTCritSectRwLeaveShared(&pThis->CritSectGlobals);
4231#endif
4232
4233#ifdef VBOX_WITH_AUDIO_ENUM
4234 /*
4235 * Re-enumerate all host devices with a tiny delay to avoid re-doing this
4236 * when a bunch of changes happens at once (they typically do on windows).
4237 * We'll keep postponing it till it quiesces for a fraction of a second.
4238 */
4239 int rc = PDMDrvHlpTimerSetMillies(pThis->pDrvIns, pThis->hEnumTimer, RT_MS_1SEC / 3);
4240 AssertRC(rc);
4241#endif
4242}
4243
4244
4245/*********************************************************************************************************************************
4246* PDMIBASE interface implementation. *
4247*********************************************************************************************************************************/
4248
4249/**
4250 * @interface_method_impl{PDMIBASE,pfnQueryInterface}
4251 */
4252static DECLCALLBACK(void *) drvAudioQueryInterface(PPDMIBASE pInterface, const char *pszIID)
4253{
4254 LogFlowFunc(("pInterface=%p, pszIID=%s\n", pInterface, pszIID));
4255
4256 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
4257 PDRVAUDIO pThis = PDMINS_2_DATA(pDrvIns, PDRVAUDIO);
4258
4259 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pDrvIns->IBase);
4260 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIAUDIOCONNECTOR, &pThis->IAudioConnector);
4261 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIHOSTAUDIOPORT, &pThis->IHostAudioPort);
4262
4263 return NULL;
4264}
4265
4266
4267/*********************************************************************************************************************************
4268* PDMDRVREG interface implementation. *
4269*********************************************************************************************************************************/
4270
4271/**
4272 * Power Off notification.
4273 *
4274 * @param pDrvIns The driver instance data.
4275 */
4276static DECLCALLBACK(void) drvAudioPowerOff(PPDMDRVINS pDrvIns)
4277{
4278 PDRVAUDIO pThis = PDMINS_2_DATA(pDrvIns, PDRVAUDIO);
4279
4280 LogFlowFuncEnter();
4281
4282 /** @todo locking? */
4283 if (pThis->pHostDrvAudio) /* If not lower driver is configured, bail out. */
4284 {
4285 /*
4286 * Just destroy the host stream on the backend side.
4287 * The rest will either be destructed by the device emulation or
4288 * in drvAudioDestruct().
4289 */
4290 int rc = RTCritSectRwEnterShared(&pThis->CritSectGlobals);
4291 AssertRCReturnVoid(rc);
4292
4293 PDRVAUDIOSTREAM pStreamEx;
4294 RTListForEach(&pThis->LstStreams, pStreamEx, DRVAUDIOSTREAM, ListEntry)
4295 {
4296 RTCritSectEnter(&pStreamEx->Core.CritSect);
4297 drvAudioStreamControlInternalBackend(pThis, pStreamEx, PDMAUDIOSTREAMCMD_DISABLE);
4298 RTCritSectLeave(&pStreamEx->Core.CritSect);
4299 }
4300
4301 RTCritSectRwLeaveShared(&pThis->CritSectGlobals);
4302 }
4303
4304 LogFlowFuncLeave();
4305}
4306
4307
4308/**
4309 * Detach notification.
4310 *
4311 * @param pDrvIns The driver instance data.
4312 * @param fFlags Detach flags.
4313 */
4314static DECLCALLBACK(void) drvAudioDetach(PPDMDRVINS pDrvIns, uint32_t fFlags)
4315{
4316 PDMDRV_CHECK_VERSIONS_RETURN_VOID(pDrvIns);
4317 PDRVAUDIO pThis = PDMINS_2_DATA(pDrvIns, PDRVAUDIO);
4318 RT_NOREF(fFlags);
4319
4320 int rc = RTCritSectRwEnterExcl(&pThis->CritSectHotPlug);
4321 AssertLogRelRCReturnVoid(rc);
4322
4323 LogFunc(("%s (detached %p, hReqPool=%p)\n", pThis->BackendCfg.szName, pThis->pHostDrvAudio, pThis->hReqPool));
4324
4325 /*
4326 * Must first destroy the thread pool first so we are certain no threads
4327 * are still using the instance being detached. Release lock while doing
4328 * this as the thread functions may need to take it to complete.
4329 */
4330 if (pThis->pHostDrvAudio && pThis->hReqPool != NIL_RTREQPOOL)
4331 {
4332 RTREQPOOL hReqPool = pThis->hReqPool;
4333 pThis->hReqPool = NIL_RTREQPOOL;
4334
4335 RTCritSectRwLeaveExcl(&pThis->CritSectHotPlug);
4336
4337 RTReqPoolRelease(hReqPool);
4338
4339 RTCritSectRwEnterExcl(&pThis->CritSectHotPlug);
4340 }
4341
4342 /*
4343 * Now we can safely set pHostDrvAudio to NULL.
4344 */
4345 pThis->pHostDrvAudio = NULL;
4346
4347 RTCritSectRwLeaveExcl(&pThis->CritSectHotPlug);
4348}
4349
4350
4351/**
4352 * Initializes the host backend and queries its initial configuration.
4353 *
4354 * @returns VBox status code.
4355 * @param pThis Driver instance to be called.
4356 */
4357static int drvAudioHostInit(PDRVAUDIO pThis)
4358{
4359 LogFlowFuncEnter();
4360
4361 /*
4362 * Check the function pointers, make sure the ones we define as
4363 * mandatory are present.
4364 */
4365 PPDMIHOSTAUDIO pIHostDrvAudio = pThis->pHostDrvAudio;
4366 AssertPtrReturn(pIHostDrvAudio, VERR_INVALID_POINTER);
4367 AssertPtrReturn(pIHostDrvAudio->pfnGetConfig, VERR_INVALID_POINTER);
4368 AssertPtrNullReturn(pIHostDrvAudio->pfnGetDevices, VERR_INVALID_POINTER);
4369 AssertPtrNullReturn(pIHostDrvAudio->pfnSetDevice, VERR_INVALID_POINTER);
4370 AssertPtrNullReturn(pIHostDrvAudio->pfnGetStatus, VERR_INVALID_POINTER);
4371 AssertPtrNullReturn(pIHostDrvAudio->pfnDoOnWorkerThread, VERR_INVALID_POINTER);
4372 AssertPtrNullReturn(pIHostDrvAudio->pfnStreamConfigHint, VERR_INVALID_POINTER);
4373 AssertPtrReturn(pIHostDrvAudio->pfnStreamCreate, VERR_INVALID_POINTER);
4374 AssertPtrNullReturn(pIHostDrvAudio->pfnStreamInitAsync, VERR_INVALID_POINTER);
4375 AssertPtrReturn(pIHostDrvAudio->pfnStreamDestroy, VERR_INVALID_POINTER);
4376 AssertPtrNullReturn(pIHostDrvAudio->pfnStreamNotifyDeviceChanged, VERR_INVALID_POINTER);
4377 AssertPtrReturn(pIHostDrvAudio->pfnStreamControl, VERR_INVALID_POINTER);
4378 AssertPtrReturn(pIHostDrvAudio->pfnStreamGetReadable, VERR_INVALID_POINTER);
4379 AssertPtrReturn(pIHostDrvAudio->pfnStreamGetWritable, VERR_INVALID_POINTER);
4380 AssertPtrNullReturn(pIHostDrvAudio->pfnStreamGetPending, VERR_INVALID_POINTER);
4381 AssertPtrReturn(pIHostDrvAudio->pfnStreamGetState, VERR_INVALID_POINTER);
4382 AssertPtrReturn(pIHostDrvAudio->pfnStreamPlay, VERR_INVALID_POINTER);
4383 AssertPtrReturn(pIHostDrvAudio->pfnStreamCapture, VERR_INVALID_POINTER);
4384
4385 /*
4386 * Get the backend configuration.
4387 *
4388 * Note! Limit the number of streams to max 128 in each direction to
4389 * prevent wasting resources.
4390 * Note! Take care not to wipe the DriverName config value on failure.
4391 */
4392 PDMAUDIOBACKENDCFG BackendCfg;
4393 RT_ZERO(BackendCfg);
4394 int rc = pIHostDrvAudio->pfnGetConfig(pIHostDrvAudio, &BackendCfg);
4395 if (RT_SUCCESS(rc))
4396 {
4397 if (LogIsEnabled() && strcmp(BackendCfg.szName, pThis->BackendCfg.szName) != 0)
4398 LogFunc(("BackendCfg.szName: '%s' -> '%s'\n", pThis->BackendCfg.szName, BackendCfg.szName));
4399 pThis->BackendCfg = BackendCfg;
4400 pThis->In.cStreamsFree = RT_MIN(BackendCfg.cMaxStreamsIn, 128);
4401 pThis->Out.cStreamsFree = RT_MIN(BackendCfg.cMaxStreamsOut, 128);
4402
4403 LogFlowFunc(("cStreamsFreeIn=%RU8, cStreamsFreeOut=%RU8\n", pThis->In.cStreamsFree, pThis->Out.cStreamsFree));
4404 }
4405 else
4406 {
4407 LogRel(("Audio: Getting configuration for driver '%s' failed with %Rrc\n", pThis->BackendCfg.szName, rc));
4408 return VERR_AUDIO_BACKEND_INIT_FAILED;
4409 }
4410
4411 LogRel2(("Audio: Host driver '%s' supports %RU32 input streams and %RU32 output streams at once.\n",
4412 pThis->BackendCfg.szName, pThis->In.cStreamsFree, pThis->Out.cStreamsFree));
4413
4414#ifdef VBOX_WITH_AUDIO_ENUM
4415 int rc2 = drvAudioDevicesEnumerateInternal(pThis, true /* fLog */, NULL /* pDevEnum */);
4416 if (rc2 != VERR_NOT_SUPPORTED) /* Some backends don't implement device enumeration. */
4417 AssertRC(rc2);
4418 /* Ignore rc2. */
4419#endif
4420
4421 /*
4422 * Create a thread pool if stream creation can be asynchronous.
4423 *
4424 * The pool employs no pushback as the caller is typically EMT and
4425 * shouldn't be delayed.
4426 *
4427 * The number of threads limits and the device implementations use
4428 * of pfnStreamDestroy limits the number of streams pending async
4429 * init. We use RTReqCancel in drvAudioStreamDestroy to allow us
4430 * to release extra reference held by the pfnStreamInitAsync call
4431 * if successful. Cancellation will only be possible if the call
4432 * hasn't been picked up by a worker thread yet, so the max number
4433 * of threads in the pool defines how many destroyed streams that
4434 * can be lingering. (We must keep this under control, otherwise
4435 * an evil guest could just rapidly trigger stream creation and
4436 * destruction to consume host heap and hog CPU resources for
4437 * configuring audio backends.)
4438 */
4439 if ( pThis->hReqPool == NIL_RTREQPOOL
4440 && ( pIHostDrvAudio->pfnStreamInitAsync
4441 || pIHostDrvAudio->pfnDoOnWorkerThread
4442 || (pThis->BackendCfg.fFlags & (PDMAUDIOBACKEND_F_ASYNC_HINT | PDMAUDIOBACKEND_F_ASYNC_STREAM_DESTROY)) ))
4443 {
4444 char szName[16];
4445 RTStrPrintf(szName, sizeof(szName), "Aud%uWr", pThis->pDrvIns->iInstance);
4446 RTREQPOOL hReqPool = NIL_RTREQPOOL;
4447 rc = RTReqPoolCreate(3 /*cMaxThreads*/, RT_MS_30SEC /*cMsMinIdle*/, UINT32_MAX /*cThreadsPushBackThreshold*/,
4448 1 /*cMsMaxPushBack*/, szName, &hReqPool);
4449 LogFlowFunc(("Creating thread pool '%s': %Rrc, hReqPool=%p\n", szName, rc, hReqPool));
4450 AssertRCReturn(rc, rc);
4451
4452 rc = RTReqPoolSetCfgVar(hReqPool, RTREQPOOLCFGVAR_THREAD_FLAGS, RTTHREADFLAGS_COM_MTA);
4453 AssertRCReturnStmt(rc, RTReqPoolRelease(hReqPool), rc);
4454
4455 rc = RTReqPoolSetCfgVar(hReqPool, RTREQPOOLCFGVAR_MIN_THREADS, 1);
4456 AssertRC(rc); /* harmless */
4457
4458 pThis->hReqPool = hReqPool;
4459 }
4460 else
4461 LogFlowFunc(("No thread pool.\n"));
4462
4463 LogFlowFuncLeave();
4464 return VINF_SUCCESS;
4465}
4466
4467
4468/**
4469 * Does the actual backend driver attaching and queries the backend's interface.
4470 *
4471 * This is a worker for both drvAudioAttach and drvAudioConstruct.
4472 *
4473 * @returns VBox status code.
4474 * @param pDrvIns The driver instance.
4475 * @param pThis Pointer to driver instance.
4476 * @param fFlags Attach flags; see PDMDrvHlpAttach().
4477 */
4478static int drvAudioDoAttachInternal(PPDMDRVINS pDrvIns, PDRVAUDIO pThis, uint32_t fFlags)
4479{
4480 Assert(pThis->pHostDrvAudio == NULL); /* No nested attaching. */
4481
4482 /*
4483 * Attach driver below and query its connector interface.
4484 */
4485 PPDMIBASE pDownBase;
4486 int rc = PDMDrvHlpAttach(pDrvIns, fFlags, &pDownBase);
4487 if (RT_SUCCESS(rc))
4488 {
4489 pThis->pHostDrvAudio = PDMIBASE_QUERY_INTERFACE(pDownBase, PDMIHOSTAUDIO);
4490 if (pThis->pHostDrvAudio)
4491 {
4492 /*
4493 * If everything went well, initialize the lower driver.
4494 */
4495 rc = drvAudioHostInit(pThis);
4496 if (RT_FAILURE(rc))
4497 pThis->pHostDrvAudio = NULL;
4498 }
4499 else
4500 {
4501 LogRel(("Audio: Failed to query interface for underlying host driver '%s'\n", pThis->BackendCfg.szName));
4502 rc = PDMDRV_SET_ERROR(pThis->pDrvIns, VERR_PDM_MISSING_INTERFACE_BELOW,
4503 N_("The host audio driver does not implement PDMIHOSTAUDIO!"));
4504 }
4505 }
4506 /*
4507 * If the host driver below us failed to construct for some beningn reason,
4508 * we'll report it as a runtime error and replace it with the Null driver.
4509 *
4510 * Note! We do NOT change anything in PDM (or CFGM), so pDrvIns->pDownBase
4511 * will remain NULL in this case.
4512 */
4513 else if ( rc == VERR_AUDIO_BACKEND_INIT_FAILED
4514 || rc == VERR_MODULE_NOT_FOUND
4515 || rc == VERR_SYMBOL_NOT_FOUND
4516 || rc == VERR_FILE_NOT_FOUND
4517 || rc == VERR_PATH_NOT_FOUND)
4518 {
4519 /* Complain: */
4520 LogRel(("DrvAudio: Host audio driver '%s' init failed with %Rrc. Switching to the NULL driver for now.\n",
4521 pThis->BackendCfg.szName, rc));
4522 PDMDrvHlpVMSetRuntimeError(pDrvIns, 0 /*fFlags*/, "HostAudioNotResponding",
4523 N_("Host audio backend (%s) initialization has failed. Selecting the NULL audio backend with the consequence that no sound is audible"),
4524 pThis->BackendCfg.szName);
4525
4526 /* Replace with null audio: */
4527 pThis->pHostDrvAudio = (PPDMIHOSTAUDIO)&g_DrvHostAudioNull;
4528 RTStrCopy(pThis->BackendCfg.szName, sizeof(pThis->BackendCfg.szName), "NULL");
4529 rc = drvAudioHostInit(pThis);
4530 AssertRC(rc);
4531 }
4532
4533 LogFunc(("[%s] rc=%Rrc\n", pThis->BackendCfg.szName, rc));
4534 return rc;
4535}
4536
4537
4538/**
4539 * Attach notification.
4540 *
4541 * @param pDrvIns The driver instance data.
4542 * @param fFlags Attach flags.
4543 */
4544static DECLCALLBACK(int) drvAudioAttach(PPDMDRVINS pDrvIns, uint32_t fFlags)
4545{
4546 PDMDRV_CHECK_VERSIONS_RETURN(pDrvIns);
4547 PDRVAUDIO pThis = PDMINS_2_DATA(pDrvIns, PDRVAUDIO);
4548 LogFunc(("%s\n", pThis->BackendCfg.szName));
4549
4550 int rc = RTCritSectRwEnterExcl(&pThis->CritSectHotPlug);
4551 AssertRCReturn(rc, rc);
4552
4553 rc = drvAudioDoAttachInternal(pDrvIns, pThis, fFlags);
4554
4555 RTCritSectRwLeaveExcl(&pThis->CritSectHotPlug);
4556 return rc;
4557}
4558
4559
4560/**
4561 * Handles state changes for all audio streams.
4562 *
4563 * @param pDrvIns Pointer to driver instance.
4564 * @param enmCmd Stream command to set for all streams.
4565 */
4566static void drvAudioStateHandler(PPDMDRVINS pDrvIns, PDMAUDIOSTREAMCMD enmCmd)
4567{
4568 PDMDRV_CHECK_VERSIONS_RETURN_VOID(pDrvIns);
4569 PDRVAUDIO pThis = PDMINS_2_DATA(pDrvIns, PDRVAUDIO);
4570 LogFlowFunc(("enmCmd=%s\n", PDMAudioStrmCmdGetName(enmCmd)));
4571
4572 int rc2 = RTCritSectRwEnterShared(&pThis->CritSectGlobals);
4573 AssertRCReturnVoid(rc2);
4574
4575 PDRVAUDIOSTREAM pStreamEx;
4576 RTListForEach(&pThis->LstStreams, pStreamEx, DRVAUDIOSTREAM, ListEntry)
4577 {
4578 RTCritSectEnter(&pStreamEx->Core.CritSect);
4579 drvAudioStreamControlInternal(pThis, pStreamEx, enmCmd);
4580 RTCritSectLeave(&pStreamEx->Core.CritSect);
4581 }
4582
4583 RTCritSectRwLeaveShared(&pThis->CritSectGlobals);
4584}
4585
4586
4587/**
4588 * Resume notification.
4589 *
4590 * @param pDrvIns The driver instance data.
4591 */
4592static DECLCALLBACK(void) drvAudioResume(PPDMDRVINS pDrvIns)
4593{
4594 drvAudioStateHandler(pDrvIns, PDMAUDIOSTREAMCMD_RESUME);
4595}
4596
4597
4598/**
4599 * Suspend notification.
4600 *
4601 * @param pDrvIns The driver instance data.
4602 */
4603static DECLCALLBACK(void) drvAudioSuspend(PPDMDRVINS pDrvIns)
4604{
4605 drvAudioStateHandler(pDrvIns, PDMAUDIOSTREAMCMD_PAUSE);
4606}
4607
4608
4609/**
4610 * Destructs an audio driver instance.
4611 *
4612 * @copydoc FNPDMDRVDESTRUCT
4613 */
4614static DECLCALLBACK(void) drvAudioDestruct(PPDMDRVINS pDrvIns)
4615{
4616 PDMDRV_CHECK_VERSIONS_RETURN_VOID(pDrvIns);
4617 PDRVAUDIO pThis = PDMINS_2_DATA(pDrvIns, PDRVAUDIO);
4618
4619 LogFlowFuncEnter();
4620
4621 /*
4622 * Note: No calls here to the driver below us anymore,
4623 * as PDM already has destroyed it.
4624 * If you need to call something from the host driver,
4625 * do this in drvAudioPowerOff() instead.
4626 */
4627
4628 /* Thus, NULL the pointer to the host audio driver first,
4629 * so that routines like drvAudioStreamDestroyInternal() don't call the driver(s) below us anymore. */
4630 if (RTCritSectRwIsInitialized(&pThis->CritSectHotPlug))
4631 {
4632 RTCritSectRwEnterExcl(&pThis->CritSectHotPlug);
4633 pThis->pHostDrvAudio = NULL;
4634 RTCritSectRwLeaveExcl(&pThis->CritSectHotPlug);
4635 }
4636 else
4637 {
4638 Assert(pThis->pHostDrvAudio == NULL);
4639 pThis->pHostDrvAudio = NULL;
4640 }
4641
4642 if (RTCritSectRwIsInitialized(&pThis->CritSectGlobals))
4643 {
4644 RTCritSectRwEnterExcl(&pThis->CritSectGlobals);
4645
4646 PDRVAUDIOSTREAM pStreamEx, pStreamExNext;
4647 RTListForEachSafe(&pThis->LstStreams, pStreamEx, pStreamExNext, DRVAUDIOSTREAM, ListEntry)
4648 {
4649 int rc = drvAudioStreamUninitInternal(pThis, pStreamEx);
4650 if (RT_SUCCESS(rc))
4651 {
4652 RTListNodeRemove(&pStreamEx->ListEntry);
4653 drvAudioStreamFree(pStreamEx);
4654 }
4655 }
4656
4657 RTCritSectRwLeaveExcl(&pThis->CritSectGlobals);
4658 RTCritSectRwDelete(&pThis->CritSectGlobals);
4659 }
4660
4661
4662 /* Sanity. */
4663 Assert(RTListIsEmpty(&pThis->LstStreams));
4664
4665 if (RTCritSectRwIsInitialized(&pThis->CritSectHotPlug))
4666 RTCritSectRwDelete(&pThis->CritSectHotPlug);
4667
4668#ifdef VBOX_WITH_STATISTICS
4669 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->Stats.TotalStreamsActive);
4670 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->Stats.TotalStreamsCreated);
4671 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->Stats.TotalFramesRead);
4672 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->Stats.TotalFramesIn);
4673 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->Stats.TotalBytesRead);
4674#endif
4675
4676 if (pThis->hReqPool != NIL_RTREQPOOL)
4677 {
4678 uint32_t cRefs = RTReqPoolRelease(pThis->hReqPool);
4679 Assert(cRefs == 0); RT_NOREF(cRefs);
4680 pThis->hReqPool = NIL_RTREQPOOL;
4681 }
4682
4683 LogFlowFuncLeave();
4684}
4685
4686
4687/**
4688 * Constructs an audio driver instance.
4689 *
4690 * @copydoc FNPDMDRVCONSTRUCT
4691 */
4692static DECLCALLBACK(int) drvAudioConstruct(PPDMDRVINS pDrvIns, PCFGMNODE pCfg, uint32_t fFlags)
4693{
4694 PDMDRV_CHECK_VERSIONS_RETURN(pDrvIns);
4695 PDRVAUDIO pThis = PDMINS_2_DATA(pDrvIns, PDRVAUDIO);
4696 LogFlowFunc(("pDrvIns=%#p, pCfgHandle=%#p, fFlags=%x\n", pDrvIns, pCfg, fFlags));
4697
4698 /*
4699 * Basic instance init.
4700 */
4701 RTListInit(&pThis->LstStreams);
4702 pThis->hReqPool = NIL_RTREQPOOL;
4703
4704 /*
4705 * Read configuration.
4706 */
4707 PDMDRV_VALIDATE_CONFIG_RETURN(pDrvIns,
4708 "DriverName|"
4709 "InputEnabled|"
4710 "OutputEnabled|"
4711 "DebugEnabled|"
4712 "DebugPathOut|"
4713 /* Deprecated: */
4714 "PCMSampleBitIn|"
4715 "PCMSampleBitOut|"
4716 "PCMSampleHzIn|"
4717 "PCMSampleHzOut|"
4718 "PCMSampleSignedIn|"
4719 "PCMSampleSignedOut|"
4720 "PCMSampleSwapEndianIn|"
4721 "PCMSampleSwapEndianOut|"
4722 "PCMSampleChannelsIn|"
4723 "PCMSampleChannelsOut|"
4724 "PeriodSizeMsIn|"
4725 "PeriodSizeMsOut|"
4726 "BufferSizeMsIn|"
4727 "BufferSizeMsOut|"
4728 "PreBufferSizeMsIn|"
4729 "PreBufferSizeMsOut",
4730 "In|Out");
4731
4732 int rc = CFGMR3QueryStringDef(pCfg, "DriverName", pThis->BackendCfg.szName, sizeof(pThis->BackendCfg.szName), "Untitled");
4733 AssertLogRelRCReturn(rc, rc);
4734
4735 /* Neither input nor output by default for security reasons. */
4736 rc = CFGMR3QueryBoolDef(pCfg, "InputEnabled", &pThis->In.fEnabled, false);
4737 AssertLogRelRCReturn(rc, rc);
4738
4739 rc = CFGMR3QueryBoolDef(pCfg, "OutputEnabled", &pThis->Out.fEnabled, false);
4740 AssertLogRelRCReturn(rc, rc);
4741
4742 /* Debug stuff (same for both directions). */
4743 rc = CFGMR3QueryBoolDef(pCfg, "DebugEnabled", &pThis->CfgIn.Dbg.fEnabled, false);
4744 AssertLogRelRCReturn(rc, rc);
4745
4746 rc = CFGMR3QueryStringDef(pCfg, "DebugPathOut", pThis->CfgIn.Dbg.szPathOut, sizeof(pThis->CfgIn.Dbg.szPathOut), "");
4747 AssertLogRelRCReturn(rc, rc);
4748 if (pThis->CfgIn.Dbg.szPathOut[0] == '\0')
4749 {
4750 rc = RTPathTemp(pThis->CfgIn.Dbg.szPathOut, sizeof(pThis->CfgIn.Dbg.szPathOut));
4751 if (RT_FAILURE(rc))
4752 {
4753 LogRel(("Audio: Warning! Failed to retrieve temporary directory: %Rrc - disabling debugging.\n", rc));
4754 pThis->CfgIn.Dbg.szPathOut[0] = '\0';
4755 pThis->CfgIn.Dbg.fEnabled = false;
4756 }
4757 }
4758 if (pThis->CfgIn.Dbg.fEnabled)
4759 LogRel(("Audio: Debugging for driver '%s' enabled (audio data written to '%s')\n",
4760 pThis->BackendCfg.szName, pThis->CfgIn.Dbg.szPathOut));
4761
4762 /* Copy debug setup to the output direction. */
4763 pThis->CfgOut.Dbg = pThis->CfgIn.Dbg;
4764
4765 LogRel2(("Audio: Verbose logging for driver '%s' is probably enabled too.\n", pThis->BackendCfg.szName));
4766 /* This ^^^^^^^ is the *WRONG* place for that kind of statement. Verbose logging might only be enabled for DrvAudio. */
4767 LogRel2(("Audio: Initial status for driver '%s' is: input is %s, output is %s\n",
4768 pThis->BackendCfg.szName, pThis->In.fEnabled ? "enabled" : "disabled", pThis->Out.fEnabled ? "enabled" : "disabled"));
4769
4770 /*
4771 * Per direction configuration. A bit complicated as
4772 * these wasn't originally in sub-nodes.
4773 */
4774 for (unsigned iDir = 0; iDir < 2; iDir++)
4775 {
4776 char szNm[48];
4777 PDRVAUDIOCFG pAudioCfg = iDir == 0 ? &pThis->CfgIn : &pThis->CfgOut;
4778 const char *pszDir = iDir == 0 ? "In" : "Out";
4779
4780#define QUERY_VAL_RET(a_Width, a_szName, a_pValue, a_uDefault, a_ExprValid, a_szValidRange) \
4781 do { \
4782 rc = RT_CONCAT(CFGMR3QueryU,a_Width)(pDirNode, strcpy(szNm, a_szName), a_pValue); \
4783 if (rc == VERR_CFGM_VALUE_NOT_FOUND || rc == VERR_CFGM_NO_PARENT) \
4784 { \
4785 rc = RT_CONCAT(CFGMR3QueryU,a_Width)(pCfg, strcat(szNm, pszDir), a_pValue); \
4786 if (rc == VERR_CFGM_VALUE_NOT_FOUND || rc == VERR_CFGM_NO_PARENT) \
4787 { \
4788 *(a_pValue) = a_uDefault; \
4789 rc = VINF_SUCCESS; \
4790 } \
4791 else \
4792 LogRel(("DrvAudio: Warning! Please use '%s/" a_szName "' instead of '%s' for your VBoxInternal hacks\n", pszDir, szNm)); \
4793 } \
4794 AssertRCReturn(rc, PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, \
4795 N_("Configuration error: Failed to read %s config value '%s'"), pszDir, szNm)); \
4796 if (!(a_ExprValid)) \
4797 return PDMDrvHlpVMSetError(pDrvIns, VERR_OUT_OF_RANGE, RT_SRC_POS, \
4798 N_("Configuration error: Unsupported %s value %u. " a_szValidRange), szNm, *(a_pValue)); \
4799 } while (0)
4800
4801 PCFGMNODE const pDirNode = CFGMR3GetChild(pCfg, pszDir);
4802 rc = CFGMR3ValidateConfig(pDirNode, iDir == 0 ? "In/" : "Out/",
4803 "PCMSampleBit|"
4804 "PCMSampleHz|"
4805 "PCMSampleSigned|"
4806 "PCMSampleSwapEndian|"
4807 "PCMSampleChannels|"
4808 "PeriodSizeMs|"
4809 "BufferSizeMs|"
4810 "PreBufferSizeMs",
4811 "", pDrvIns->pReg->szName, pDrvIns->iInstance);
4812 AssertRCReturn(rc, rc);
4813
4814 uint8_t cSampleBits = 0;
4815 QUERY_VAL_RET(8, "PCMSampleBit", &cSampleBits, 0,
4816 cSampleBits == 0
4817 || cSampleBits == 8
4818 || cSampleBits == 16
4819 || cSampleBits == 32
4820 || cSampleBits == 64,
4821 "Must be either 0, 8, 16, 32 or 64");
4822 if (cSampleBits)
4823 PDMAudioPropsSetSampleSize(&pAudioCfg->Props, cSampleBits / 8);
4824
4825 uint8_t cChannels;
4826 QUERY_VAL_RET(8, "PCMSampleChannels", &cChannels, 0, cChannels <= 16, "Max 16");
4827 if (cChannels)
4828 PDMAudioPropsSetChannels(&pAudioCfg->Props, cChannels);
4829
4830 QUERY_VAL_RET(32, "PCMSampleHz", &pAudioCfg->Props.uHz, 0,
4831 pAudioCfg->Props.uHz == 0 || (pAudioCfg->Props.uHz >= 6000 && pAudioCfg->Props.uHz <= 768000),
4832 "In the range 6000 thru 768000, or 0");
4833
4834 QUERY_VAL_RET(8, "PCMSampleSigned", &pAudioCfg->uSigned, UINT8_MAX,
4835 pAudioCfg->uSigned == 0 || pAudioCfg->uSigned == 1 || pAudioCfg->uSigned == UINT8_MAX,
4836 "Must be either 0, 1, or 255");
4837
4838 QUERY_VAL_RET(8, "PCMSampleSwapEndian", &pAudioCfg->uSwapEndian, UINT8_MAX,
4839 pAudioCfg->uSwapEndian == 0 || pAudioCfg->uSwapEndian == 1 || pAudioCfg->uSwapEndian == UINT8_MAX,
4840 "Must be either 0, 1, or 255");
4841
4842 QUERY_VAL_RET(32, "PeriodSizeMs", &pAudioCfg->uPeriodSizeMs, 0,
4843 pAudioCfg->uPeriodSizeMs <= RT_MS_1SEC, "Max 1000");
4844
4845 QUERY_VAL_RET(32, "BufferSizeMs", &pAudioCfg->uBufferSizeMs, 0,
4846 pAudioCfg->uBufferSizeMs <= RT_MS_5SEC, "Max 5000");
4847
4848 QUERY_VAL_RET(32, "PreBufferSizeMs", &pAudioCfg->uPreBufSizeMs, UINT32_MAX,
4849 pAudioCfg->uPreBufSizeMs <= RT_MS_1SEC || pAudioCfg->uPreBufSizeMs == UINT32_MAX,
4850 "Max 1000, or 0xffffffff");
4851#undef QUERY_VAL_RET
4852 }
4853
4854 /*
4855 * Init the rest of the driver instance data.
4856 */
4857 rc = RTCritSectRwInit(&pThis->CritSectHotPlug);
4858 AssertRCReturn(rc, rc);
4859 rc = RTCritSectRwInit(&pThis->CritSectGlobals);
4860 AssertRCReturn(rc, rc);
4861#ifdef VBOX_STRICT
4862 /* Define locking order: */
4863 RTCritSectRwEnterExcl(&pThis->CritSectGlobals);
4864 RTCritSectRwEnterExcl(&pThis->CritSectHotPlug);
4865 RTCritSectRwLeaveExcl(&pThis->CritSectHotPlug);
4866 RTCritSectRwLeaveExcl(&pThis->CritSectGlobals);
4867#endif
4868
4869 pThis->pDrvIns = pDrvIns;
4870 /* IBase. */
4871 pDrvIns->IBase.pfnQueryInterface = drvAudioQueryInterface;
4872 /* IAudioConnector. */
4873 pThis->IAudioConnector.pfnEnable = drvAudioEnable;
4874 pThis->IAudioConnector.pfnIsEnabled = drvAudioIsEnabled;
4875 pThis->IAudioConnector.pfnGetConfig = drvAudioGetConfig;
4876 pThis->IAudioConnector.pfnGetStatus = drvAudioGetStatus;
4877 pThis->IAudioConnector.pfnStreamConfigHint = drvAudioStreamConfigHint;
4878 pThis->IAudioConnector.pfnStreamCreate = drvAudioStreamCreate;
4879 pThis->IAudioConnector.pfnStreamDestroy = drvAudioStreamDestroy;
4880 pThis->IAudioConnector.pfnStreamReInit = drvAudioStreamReInit;
4881 pThis->IAudioConnector.pfnStreamRetain = drvAudioStreamRetain;
4882 pThis->IAudioConnector.pfnStreamRelease = drvAudioStreamRelease;
4883 pThis->IAudioConnector.pfnStreamControl = drvAudioStreamControl;
4884 pThis->IAudioConnector.pfnStreamIterate = drvAudioStreamIterate;
4885 pThis->IAudioConnector.pfnStreamGetState = drvAudioStreamGetState;
4886 pThis->IAudioConnector.pfnStreamGetWritable = drvAudioStreamGetWritable;
4887 pThis->IAudioConnector.pfnStreamPlay = drvAudioStreamPlay;
4888 pThis->IAudioConnector.pfnStreamGetReadable = drvAudioStreamGetReadable;
4889 pThis->IAudioConnector.pfnStreamCapture = drvAudioStreamCapture;
4890 /* IHostAudioPort */
4891 pThis->IHostAudioPort.pfnDoOnWorkerThread = drvAudioHostPort_DoOnWorkerThread;
4892 pThis->IHostAudioPort.pfnNotifyDeviceChanged = drvAudioHostPort_NotifyDeviceChanged;
4893 pThis->IHostAudioPort.pfnStreamNotifyPreparingDeviceSwitch = drvAudioHostPort_StreamNotifyPreparingDeviceSwitch;
4894 pThis->IHostAudioPort.pfnStreamNotifyDeviceChanged = drvAudioHostPort_StreamNotifyDeviceChanged;
4895 pThis->IHostAudioPort.pfnNotifyDevicesChanged = drvAudioHostPort_NotifyDevicesChanged;
4896
4897 /*
4898 * Statistics.
4899 */
4900#ifdef VBOX_WITH_STATISTICS
4901 PDMDrvHlpSTAMRegCounterEx(pDrvIns, &pThis->Stats.TotalStreamsActive, "TotalStreamsActive",
4902 STAMUNIT_COUNT, "Total active audio streams.");
4903 PDMDrvHlpSTAMRegCounterEx(pDrvIns, &pThis->Stats.TotalStreamsCreated, "TotalStreamsCreated",
4904 STAMUNIT_COUNT, "Total created audio streams.");
4905 PDMDrvHlpSTAMRegCounterEx(pDrvIns, &pThis->Stats.TotalFramesRead, "TotalFramesRead",
4906 STAMUNIT_COUNT, "Total frames read by device emulation.");
4907 PDMDrvHlpSTAMRegCounterEx(pDrvIns, &pThis->Stats.TotalFramesIn, "TotalFramesIn",
4908 STAMUNIT_COUNT, "Total frames captured by backend.");
4909 PDMDrvHlpSTAMRegCounterEx(pDrvIns, &pThis->Stats.TotalBytesRead, "TotalBytesRead",
4910 STAMUNIT_BYTES, "Total bytes read.");
4911#endif
4912
4913#ifdef VBOX_WITH_AUDIO_ENUM
4914 /*
4915 * Create a timer to trigger delayed device enumeration on device changes.
4916 */
4917 RTStrPrintf(pThis->szEnumTimerName, sizeof(pThis->szEnumTimerName), "AudioEnum-%u", pDrvIns->iInstance);
4918 rc = PDMDrvHlpTMTimerCreate(pDrvIns, TMCLOCK_REAL, drvAudioEnumerateTimer, NULL /*pvUser*/,
4919 0 /*fFlags*/, pThis->szEnumTimerName, &pThis->hEnumTimer);
4920 AssertRCReturn(rc, rc);
4921#endif
4922
4923 /*
4924 * Attach the host driver, if present.
4925 */
4926 rc = drvAudioDoAttachInternal(pDrvIns, pThis, fFlags);
4927 if (rc == VERR_PDM_NO_ATTACHED_DRIVER)
4928 rc = VINF_SUCCESS;
4929
4930 LogFlowFuncLeaveRC(rc);
4931 return rc;
4932}
4933
4934/**
4935 * Audio driver registration record.
4936 */
4937const PDMDRVREG g_DrvAUDIO =
4938{
4939 /* u32Version */
4940 PDM_DRVREG_VERSION,
4941 /* szName */
4942 "AUDIO",
4943 /* szRCMod */
4944 "",
4945 /* szR0Mod */
4946 "",
4947 /* pszDescription */
4948 "Audio connector driver",
4949 /* fFlags */
4950 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
4951 /* fClass */
4952 PDM_DRVREG_CLASS_AUDIO,
4953 /* cMaxInstances */
4954 UINT32_MAX,
4955 /* cbInstance */
4956 sizeof(DRVAUDIO),
4957 /* pfnConstruct */
4958 drvAudioConstruct,
4959 /* pfnDestruct */
4960 drvAudioDestruct,
4961 /* pfnRelocate */
4962 NULL,
4963 /* pfnIOCtl */
4964 NULL,
4965 /* pfnPowerOn */
4966 NULL,
4967 /* pfnReset */
4968 NULL,
4969 /* pfnSuspend */
4970 drvAudioSuspend,
4971 /* pfnResume */
4972 drvAudioResume,
4973 /* pfnAttach */
4974 drvAudioAttach,
4975 /* pfnDetach */
4976 drvAudioDetach,
4977 /* pfnPowerOff */
4978 drvAudioPowerOff,
4979 /* pfnSoftReset */
4980 NULL,
4981 /* u32EndVersion */
4982 PDM_DRVREG_VERSION
4983};
4984
Note: See TracBrowser for help on using the repository browser.

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