VirtualBox

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

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

DrvAudio: Use pStreamEx->Core.Props instead of pStream->Guest.Cfg.Props and pStream->Host.Cfg.Props. The former is actually very wrong as it's what the mixer requested, not the actual properties of the stream. bugref:9890

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 206.7 KB
Line 
1/* $Id: DrvAudio.cpp 89445 2021-06-01 20:58:25Z 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 * This will be adjusted.
1565 * @param pCfgGuest Stream configuration to use for the guest side.
1566 */
1567static int drvAudioStreamInitInternal(PDRVAUDIO pThis, PDRVAUDIOSTREAM pStreamEx,
1568 PPDMAUDIOSTREAMCFG pCfgHost, PCPDMAUDIOSTREAMCFG pCfgGuest)
1569{
1570 /*
1571 * Init host stream.
1572 */
1573 pStreamEx->Core.uMagic = PDMAUDIOSTREAM_MAGIC;
1574
1575#ifdef LOG_ENABLED
1576 LogFunc(("[%s] Requested host format:\n", pStreamEx->Core.szName));
1577 PDMAudioStrmCfgLog(pCfgHost);
1578#endif
1579
1580 LogRel2(("Audio: Creating stream '%s'\n", pStreamEx->Core.szName));
1581 LogRel2(("Audio: Guest %s format for '%s': %RU32Hz, %u%s, %RU8 channel%s\n",
1582 pCfgGuest->enmDir == PDMAUDIODIR_IN ? "recording" : "playback", pStreamEx->Core.szName,
1583 pCfgGuest->Props.uHz, PDMAudioPropsSampleBits(&pCfgGuest->Props), pCfgGuest->Props.fSigned ? "S" : "U",
1584 PDMAudioPropsChannels(&pCfgGuest->Props), PDMAudioPropsChannels(&pCfgGuest->Props) == 1 ? "" : "s"));
1585 LogRel2(("Audio: Requested host %s format for '%s': %RU32Hz, %u%s, %RU8 channel%s\n",
1586 pCfgHost->enmDir == PDMAUDIODIR_IN ? "recording" : "playback", pStreamEx->Core.szName,
1587 pCfgHost->Props.uHz, PDMAudioPropsSampleBits(&pCfgHost->Props), pCfgHost->Props.fSigned ? "S" : "U",
1588 PDMAudioPropsChannels(&pCfgHost->Props), PDMAudioPropsChannels(&pCfgHost->Props) == 1 ? "" : "s"));
1589
1590 PDMAUDIOSTREAMCFG CfgHostAcq;
1591 int rc = drvAudioStreamCreateInternalBackend(pThis, pStreamEx, pCfgHost, &CfgHostAcq);
1592 if (RT_FAILURE(rc))
1593 return rc;
1594
1595 LogFunc(("[%s] Acquired host format:\n", pStreamEx->Core.szName));
1596 PDMAudioStrmCfgLog(&CfgHostAcq);
1597 LogRel2(("Audio: Acquired host %s format for '%s': %RU32Hz, %u%s, %RU8 channel%s\n",
1598 CfgHostAcq.enmDir == PDMAUDIODIR_IN ? "recording" : "playback", pStreamEx->Core.szName,
1599 CfgHostAcq.Props.uHz, PDMAudioPropsSampleBits(&CfgHostAcq.Props), CfgHostAcq.Props.fSigned ? "S" : "U",
1600 PDMAudioPropsChannels(&CfgHostAcq.Props), PDMAudioPropsChannels(&CfgHostAcq.Props) == 1 ? "" : "s"));
1601 Assert(PDMAudioPropsAreValid(&CfgHostAcq.Props));
1602
1603 /* Set the stream properties. */
1604 pStreamEx->Core.Props = CfgHostAcq.Props;
1605
1606 /* Let the user know if the backend changed some of the tweakable values. */
1607 if (CfgHostAcq.Backend.cFramesBufferSize != pCfgHost->Backend.cFramesBufferSize)
1608 LogRel2(("Audio: Backend changed buffer size from %RU64ms (%RU32 frames) to %RU64ms (%RU32 frames)\n",
1609 PDMAudioPropsFramesToMilli(&pCfgHost->Props, pCfgHost->Backend.cFramesBufferSize), pCfgHost->Backend.cFramesBufferSize,
1610 PDMAudioPropsFramesToMilli(&CfgHostAcq.Props, CfgHostAcq.Backend.cFramesBufferSize), CfgHostAcq.Backend.cFramesBufferSize));
1611
1612 if (CfgHostAcq.Backend.cFramesPeriod != pCfgHost->Backend.cFramesPeriod)
1613 LogRel2(("Audio: Backend changed period size from %RU64ms (%RU32 frames) to %RU64ms (%RU32 frames)\n",
1614 PDMAudioPropsFramesToMilli(&pCfgHost->Props, pCfgHost->Backend.cFramesPeriod), pCfgHost->Backend.cFramesPeriod,
1615 PDMAudioPropsFramesToMilli(&CfgHostAcq.Props, CfgHostAcq.Backend.cFramesPeriod), CfgHostAcq.Backend.cFramesPeriod));
1616
1617 if (CfgHostAcq.Backend.cFramesPreBuffering != pCfgHost->Backend.cFramesPreBuffering)
1618 LogRel2(("Audio: Backend changed pre-buffering size from %RU64ms (%RU32 frames) to %RU64ms (%RU32 frames)\n",
1619 PDMAudioPropsFramesToMilli(&pCfgHost->Props, pCfgHost->Backend.cFramesPreBuffering), pCfgHost->Backend.cFramesPreBuffering,
1620 PDMAudioPropsFramesToMilli(&CfgHostAcq.Props, CfgHostAcq.Backend.cFramesPreBuffering), CfgHostAcq.Backend.cFramesPreBuffering));
1621
1622 /*
1623 * Check if the backend did return sane values and correct if necessary.
1624 * Should never happen with our own backends, but you never know ...
1625 */
1626 uint32_t const cFramesPreBufferingMax = CfgHostAcq.Backend.cFramesBufferSize - RT_MIN(16, CfgHostAcq.Backend.cFramesBufferSize);
1627 if (CfgHostAcq.Backend.cFramesPreBuffering > cFramesPreBufferingMax)
1628 {
1629 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",
1630 CfgHostAcq.Backend.cFramesPreBuffering, pStreamEx->Core.szName, CfgHostAcq.Backend.cFramesBufferSize, cFramesPreBufferingMax));
1631 AssertFailed();
1632 CfgHostAcq.Backend.cFramesPreBuffering = cFramesPreBufferingMax;
1633 }
1634
1635 if (CfgHostAcq.Backend.cFramesPeriod > CfgHostAcq.Backend.cFramesBufferSize)
1636 {
1637 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",
1638 CfgHostAcq.Backend.cFramesPeriod, pStreamEx->Core.szName, CfgHostAcq.Backend.cFramesBufferSize, CfgHostAcq.Backend.cFramesBufferSize / 2));
1639 AssertFailed();
1640 CfgHostAcq.Backend.cFramesPeriod = CfgHostAcq.Backend.cFramesBufferSize / 2;
1641 }
1642
1643 LogRel2(("Audio: Buffer size of stream '%s' is %RU64 ms / %RU32 frames\n", pStreamEx->Core.szName,
1644 PDMAudioPropsFramesToMilli(&CfgHostAcq.Props, CfgHostAcq.Backend.cFramesBufferSize), CfgHostAcq.Backend.cFramesBufferSize));
1645 LogRel2(("Audio: Pre-buffering size of stream '%s' is %RU64 ms / %RU32 frames\n", pStreamEx->Core.szName,
1646 PDMAudioPropsFramesToMilli(&CfgHostAcq.Props, CfgHostAcq.Backend.cFramesPreBuffering), CfgHostAcq.Backend.cFramesPreBuffering));
1647
1648 /* Make sure the configured buffer size by the backend at least can hold the configured latency. */
1649 const uint32_t msPeriod = PDMAudioPropsFramesToMilli(&CfgHostAcq.Props, CfgHostAcq.Backend.cFramesPeriod);
1650 LogRel2(("Audio: Period size of stream '%s' is %RU64 ms / %RU32 frames\n",
1651 pStreamEx->Core.szName, msPeriod, CfgHostAcq.Backend.cFramesPeriod));
1652
1653 if ( pCfgGuest->Device.cMsSchedulingHint /* Any scheduling hint set? */
1654 && pCfgGuest->Device.cMsSchedulingHint > msPeriod) /* This might lead to buffer underflows. */
1655 LogRel(("Audio: Warning: Scheduling hint of stream '%s' is bigger (%RU64ms) than used period size (%RU64ms)\n",
1656 pStreamEx->Core.szName, pCfgGuest->Device.cMsSchedulingHint, msPeriod));
1657
1658 /*
1659 * Make a copy of the acquired host stream configuration and the guest side one.
1660 */
1661 rc = PDMAudioStrmCfgCopy(&pStreamEx->Host.Cfg, &CfgHostAcq);
1662 AssertRC(rc);
1663
1664 rc = PDMAudioStrmCfgCopy(&pStreamEx->Guest.Cfg, pCfgGuest);
1665 AssertRC(rc);
1666
1667 /*
1668 * Configure host buffers.
1669 */
1670 Assert(pStreamEx->cbPreBufThreshold == 0);
1671 if (CfgHostAcq.Backend.cFramesPreBuffering != 0)
1672 pStreamEx->cbPreBufThreshold = PDMAudioPropsFramesToBytes(&CfgHostAcq.Props, CfgHostAcq.Backend.cFramesPreBuffering);
1673
1674 /* Allocate space for pre-buffering of output stream w/o mixing buffers. */
1675 if (pCfgHost->enmDir == PDMAUDIODIR_OUT)
1676 {
1677 Assert(pStreamEx->Out.cbPreBufAlloc == 0);
1678 Assert(pStreamEx->Out.cbPreBuffered == 0);
1679 Assert(pStreamEx->Out.offPreBuf == 0);
1680 if (CfgHostAcq.Backend.cFramesPreBuffering != 0)
1681 {
1682 pStreamEx->Out.cbPreBufAlloc = PDMAudioPropsFramesToBytes(&CfgHostAcq.Props,
1683 CfgHostAcq.Backend.cFramesBufferSize - 2);
1684 pStreamEx->Out.cbPreBufAlloc = RT_MIN(RT_ALIGN_32(pStreamEx->cbPreBufThreshold + _8K, _4K),
1685 pStreamEx->Out.cbPreBufAlloc);
1686 pStreamEx->Out.pbPreBuf = (uint8_t *)RTMemAllocZ(pStreamEx->Out.cbPreBufAlloc);
1687 AssertReturn(pStreamEx->Out.pbPreBuf, VERR_NO_MEMORY);
1688 }
1689 pStreamEx->Out.enmPlayState = DRVAUDIOPLAYSTATE_NOPLAY; /* Changed upon enable. */
1690 }
1691
1692 /*
1693 * Init guest stream.
1694 */
1695 if (pCfgGuest->Device.cMsSchedulingHint)
1696 LogRel2(("Audio: Stream '%s' got a scheduling hint of %RU32ms (%RU32 bytes)\n",
1697 pStreamEx->Core.szName, pCfgGuest->Device.cMsSchedulingHint,
1698 PDMAudioPropsMilliToBytes(&pCfgGuest->Props, pCfgGuest->Device.cMsSchedulingHint)));
1699
1700 /*
1701 * Register statistics.
1702 */
1703 PPDMDRVINS const pDrvIns = pThis->pDrvIns;
1704 /** @todo expose config and more. */
1705 PDMDrvHlpSTAMRegisterF(pDrvIns, &pStreamEx->Host.Cfg.Backend.cFramesBufferSize, STAMTYPE_U32, STAMVISIBILITY_USED, STAMUNIT_NONE,
1706 "Host side: The size of the backend buffer (in frames)", "%s/0-HostBackendBufSize", pStreamEx->Core.szName);
1707 if (pCfgGuest->enmDir == PDMAUDIODIR_IN)
1708 {
1709 /** @todo later? */
1710 }
1711 else
1712 {
1713 PDMDrvHlpSTAMRegisterF(pDrvIns, &pStreamEx->Out.Stats.cbBackendWritableBefore, STAMTYPE_U32, STAMVISIBILITY_USED, STAMUNIT_NONE,
1714 "Host side: Free space in backend buffer before play", "%s/0-HostBackendBufFreeBefore", pStreamEx->Core.szName);
1715 PDMDrvHlpSTAMRegisterF(pDrvIns, &pStreamEx->Out.Stats.cbBackendWritableAfter, STAMTYPE_U32, STAMVISIBILITY_USED, STAMUNIT_NONE,
1716 "Host side: Free space in backend buffer after play", "%s/0-HostBackendBufFreeAfter", pStreamEx->Core.szName);
1717 }
1718
1719#ifdef VBOX_WITH_STATISTICS
1720 if (pCfgGuest->enmDir == PDMAUDIODIR_IN)
1721 {
1722 PDMDrvHlpSTAMRegisterF(pDrvIns, &pStreamEx->In.Stats.TotalFramesCaptured, STAMTYPE_COUNTER, STAMVISIBILITY_USED, STAMUNIT_NONE,
1723 "Total frames played.", "%s/TotalFramesCaptured", pStreamEx->Core.szName);
1724 PDMDrvHlpSTAMRegisterF(pDrvIns, &pStreamEx->In.Stats.TotalTimesCaptured, STAMTYPE_COUNTER, STAMVISIBILITY_USED, STAMUNIT_NONE,
1725 "Total number of playbacks.", "%s/TotalTimesCaptured", pStreamEx->Core.szName);
1726 PDMDrvHlpSTAMRegisterF(pDrvIns, &pStreamEx->In.Stats.TotalTimesRead, STAMTYPE_COUNTER, STAMVISIBILITY_USED, STAMUNIT_NONE,
1727 "Total number of reads.", "%s/TotalTimesRead", pStreamEx->Core.szName);
1728 }
1729 else
1730 {
1731 Assert(pCfgGuest->enmDir == PDMAUDIODIR_OUT);
1732 }
1733#endif /* VBOX_WITH_STATISTICS */
1734
1735 LogFlowFunc(("[%s] Returning %Rrc\n", pStreamEx->Core.szName, rc));
1736 return rc;
1737}
1738
1739
1740/**
1741 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnStreamCreate}
1742 */
1743static DECLCALLBACK(int) drvAudioStreamCreate(PPDMIAUDIOCONNECTOR pInterface, uint32_t fFlags, PPDMAUDIOSTREAMCFG pCfgHost,
1744 PPDMAUDIOSTREAMCFG pCfgGuest, PPDMAUDIOSTREAM *ppStream)
1745{
1746 PDRVAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVAUDIO, IAudioConnector);
1747 AssertPtr(pThis);
1748
1749 /*
1750 * Assert sanity.
1751 */
1752 AssertReturn(!(fFlags & ~PDMAUDIOSTREAM_CREATE_F_NO_MIXBUF), VERR_INVALID_FLAGS);
1753 AssertPtrReturn(pCfgHost, VERR_INVALID_POINTER);
1754 AssertPtrReturn(pCfgGuest, VERR_INVALID_POINTER);
1755 AssertPtrReturn(ppStream, VERR_INVALID_POINTER);
1756 LogFlowFunc(("Host=%s, Guest=%s\n", pCfgHost->szName, pCfgGuest->szName));
1757#ifdef LOG_ENABLED
1758 PDMAudioStrmCfgLog(pCfgHost);
1759 PDMAudioStrmCfgLog(pCfgGuest);
1760#endif
1761 AssertReturn(AudioHlpStreamCfgIsValid(pCfgHost), VERR_INVALID_PARAMETER);
1762 AssertReturn(AudioHlpStreamCfgIsValid(pCfgGuest), VERR_INVALID_PARAMETER);
1763 AssertReturn(pCfgHost->enmDir == pCfgGuest->enmDir, VERR_MISMATCH);
1764 AssertReturn(pCfgHost->enmDir == PDMAUDIODIR_IN || pCfgHost->enmDir == PDMAUDIODIR_OUT, VERR_NOT_SUPPORTED);
1765
1766 /*
1767 * Grab a free stream count now.
1768 */
1769 int rc = RTCritSectRwEnterExcl(&pThis->CritSectGlobals);
1770 AssertRCReturn(rc, rc);
1771
1772 uint32_t * const pcFreeStreams = pCfgHost->enmDir == PDMAUDIODIR_IN ? &pThis->In.cStreamsFree : &pThis->Out.cStreamsFree;
1773 if (*pcFreeStreams > 0)
1774 *pcFreeStreams -= 1;
1775 else
1776 {
1777 RTCritSectRwLeaveExcl(&pThis->CritSectGlobals);
1778 LogFlowFunc(("Maximum number of host %s streams reached\n", PDMAudioDirGetName(pCfgHost->enmDir) ));
1779 return pCfgHost->enmDir == PDMAUDIODIR_IN ? VERR_AUDIO_NO_FREE_INPUT_STREAMS : VERR_AUDIO_NO_FREE_OUTPUT_STREAMS;
1780 }
1781
1782 RTCritSectRwLeaveExcl(&pThis->CritSectGlobals);
1783
1784 /*
1785 * Get and check the backend size.
1786 *
1787 * Since we'll have to leave the hot-plug lock before we call the backend,
1788 * we'll have revalidate the size at that time.
1789 */
1790 RTCritSectRwEnterShared(&pThis->CritSectHotPlug);
1791
1792 size_t const cbHstStrm = pThis->BackendCfg.cbStream;
1793 AssertStmt(cbHstStrm >= sizeof(PDMAUDIOBACKENDSTREAM), rc = VERR_OUT_OF_RANGE);
1794 AssertStmt(cbHstStrm < _16M, rc = VERR_OUT_OF_RANGE);
1795
1796 RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
1797 if (RT_SUCCESS(rc))
1798 {
1799 /*
1800 * Allocate and initialize common state.
1801 */
1802 PDRVAUDIOSTREAM pStreamEx = (PDRVAUDIOSTREAM)RTMemAllocZ(sizeof(DRVAUDIOSTREAM) + RT_ALIGN_Z(cbHstStrm, 64));
1803 if (pStreamEx)
1804 {
1805 rc = RTCritSectInit(&pStreamEx->Core.CritSect); /* (drvAudioStreamFree assumes it's initailized) */
1806 if (RT_SUCCESS(rc))
1807 {
1808 PPDMAUDIOBACKENDSTREAM pBackend = (PPDMAUDIOBACKENDSTREAM)(pStreamEx + 1);
1809 pBackend->uMagic = PDMAUDIOBACKENDSTREAM_MAGIC;
1810 pBackend->pStream = &pStreamEx->Core;
1811
1812 pStreamEx->pBackend = pBackend;
1813 pStreamEx->Core.enmDir = pCfgHost->enmDir;
1814 pStreamEx->Core.cbBackend = (uint32_t)cbHstStrm;
1815 pStreamEx->fDestroyImmediate = true;
1816 pStreamEx->hReqInitAsync = NIL_RTREQ;
1817 pStreamEx->uMagic = DRVAUDIOSTREAM_MAGIC;
1818
1819 /* Make a unqiue stream name including the host (backend) driver name. */
1820 AssertPtr(pThis->pHostDrvAudio);
1821 size_t cchName = RTStrPrintf(pStreamEx->Core.szName, RT_ELEMENTS(pStreamEx->Core.szName), "[%s] %s:0",
1822 pThis->BackendCfg.szName, pCfgHost->szName[0] != '\0' ? pCfgHost->szName : "<NoName>");
1823 if (cchName < sizeof(pStreamEx->Core.szName))
1824 {
1825 RTCritSectRwEnterShared(&pThis->CritSectGlobals);
1826 for (uint32_t i = 0; i < 256; i++)
1827 {
1828 bool fDone = true;
1829 PDRVAUDIOSTREAM pIt;
1830 RTListForEach(&pThis->LstStreams, pIt, DRVAUDIOSTREAM, ListEntry)
1831 {
1832 if (strcmp(pIt->Core.szName, pStreamEx->Core.szName) == 0)
1833 {
1834 RTStrPrintf(pStreamEx->Core.szName, RT_ELEMENTS(pStreamEx->Core.szName), "[%s] %s:%u",
1835 pThis->BackendCfg.szName, pCfgHost->szName[0] != '\0' ? pCfgHost->szName : "<NoName>",
1836 i);
1837 fDone = false;
1838 break;
1839 }
1840 }
1841 if (fDone)
1842 break;
1843 }
1844 RTCritSectRwLeaveShared(&pThis->CritSectGlobals);
1845 }
1846
1847 /*
1848 * Try to init the rest.
1849 */
1850 rc = drvAudioStreamInitInternal(pThis, pStreamEx, pCfgHost, pCfgGuest);
1851 if (RT_SUCCESS(rc))
1852 {
1853 /* Set initial reference counts. */
1854 pStreamEx->cRefs = pStreamEx->fNeedAsyncInit ? 2 : 1;
1855
1856 /* Add it to the list. */
1857 RTCritSectRwEnterExcl(&pThis->CritSectGlobals);
1858
1859 RTListAppend(&pThis->LstStreams, &pStreamEx->ListEntry);
1860 pThis->cStreams++;
1861 STAM_COUNTER_INC(&pThis->Stats.TotalStreamsCreated);
1862
1863 RTCritSectRwLeaveExcl(&pThis->CritSectGlobals);
1864
1865 /*
1866 * Init debug stuff if enabled (ignore failures).
1867 */
1868 if (pCfgHost->enmDir == PDMAUDIODIR_IN)
1869 {
1870 if (pThis->CfgIn.Dbg.fEnabled)
1871 AudioHlpFileCreateAndOpen(&pStreamEx->In.Dbg.pFileCapture, pThis->CfgIn.Dbg.szPathOut,
1872 "DrvAudioCapture", pThis->pDrvIns->iInstance, &pStreamEx->Host.Cfg.Props);
1873 }
1874 else /* Out */
1875 {
1876 if (pThis->CfgOut.Dbg.fEnabled)
1877 AudioHlpFileCreateAndOpen(&pStreamEx->Out.Dbg.pFilePlay, pThis->CfgOut.Dbg.szPathOut,
1878 "DrvAudioPlay", pThis->pDrvIns->iInstance, &pStreamEx->Host.Cfg.Props);
1879 }
1880
1881 /*
1882 * Kick off the asynchronous init.
1883 */
1884 if (!pStreamEx->fNeedAsyncInit)
1885 {
1886 pStreamEx->fStatus |= PDMAUDIOSTREAM_STS_BACKEND_READY;
1887 PDMAUDIOSTREAM_STS_ASSERT_VALID(pStreamEx->fStatus);
1888 }
1889 else
1890 {
1891 int rc2 = RTReqPoolCallEx(pThis->hReqPool, 0 /*cMillies*/, &pStreamEx->hReqInitAsync,
1892 RTREQFLAGS_VOID | RTREQFLAGS_NO_WAIT,
1893 (PFNRT)drvAudioStreamInitAsync, 2, pThis, pStreamEx);
1894 LogFlowFunc(("hReqInitAsync=%p rc2=%Rrc\n", pStreamEx->hReqInitAsync, rc2));
1895 AssertRCStmt(rc2, drvAudioStreamInitAsync(pThis, pStreamEx));
1896 }
1897
1898#ifdef VBOX_STRICT
1899 /*
1900 * Assert lock order to make sure the lock validator picks up on it.
1901 */
1902 RTCritSectRwEnterShared(&pThis->CritSectGlobals);
1903 RTCritSectEnter(&pStreamEx->Core.CritSect);
1904 RTCritSectRwEnterShared(&pThis->CritSectHotPlug);
1905 RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
1906 RTCritSectLeave(&pStreamEx->Core.CritSect);
1907 RTCritSectRwLeaveShared(&pThis->CritSectGlobals);
1908#endif
1909
1910 *ppStream = &pStreamEx->Core;
1911 LogFlowFunc(("returns VINF_SUCCESS (pStreamEx=%p)\n", pStreamEx));
1912 return VINF_SUCCESS;
1913 }
1914
1915 LogFunc(("drvAudioStreamInitInternal failed: %Rrc\n", rc));
1916 int rc2 = drvAudioStreamUninitInternal(pThis, pStreamEx);
1917 AssertRC(rc2);
1918 drvAudioStreamFree(pStreamEx);
1919 }
1920 else
1921 RTMemFree(pStreamEx);
1922 }
1923 else
1924 rc = VERR_NO_MEMORY;
1925 }
1926
1927 /*
1928 * Give back the stream count, we couldn't use it after all.
1929 */
1930 RTCritSectRwEnterExcl(&pThis->CritSectGlobals);
1931 *pcFreeStreams += 1;
1932 RTCritSectRwLeaveExcl(&pThis->CritSectGlobals);
1933
1934 LogFlowFuncLeaveRC(rc);
1935 return rc;
1936}
1937
1938
1939/**
1940 * Calls the backend to give it the chance to destroy its part of the audio stream.
1941 *
1942 * Called from drvAudioPowerOff, drvAudioStreamUninitInternal and
1943 * drvAudioStreamReInitInternal.
1944 *
1945 * @returns VBox status code.
1946 * @param pThis Pointer to driver instance.
1947 * @param pStreamEx Audio stream destruct backend for.
1948 */
1949static int drvAudioStreamDestroyInternalBackend(PDRVAUDIO pThis, PDRVAUDIOSTREAM pStreamEx)
1950{
1951 AssertPtr(pThis);
1952 AssertPtr(pStreamEx);
1953
1954 int rc = VINF_SUCCESS;
1955
1956#ifdef LOG_ENABLED
1957 char szStreamSts[DRVAUDIO_STATUS_STR_MAX];
1958#endif
1959 LogFunc(("[%s] fStatus=%s\n", pStreamEx->Core.szName, drvAudioStreamStatusToStr(szStreamSts, pStreamEx->fStatus)));
1960
1961 if (pStreamEx->fStatus & PDMAUDIOSTREAM_STS_BACKEND_CREATED)
1962 {
1963 AssertPtr(pStreamEx->pBackend);
1964
1965 /* Check if the pointer to the host audio driver is still valid.
1966 * It can be NULL if we were called in drvAudioDestruct, for example. */
1967 RTCritSectRwEnterShared(&pThis->CritSectHotPlug); /** @todo needed? */
1968 if (pThis->pHostDrvAudio)
1969 rc = pThis->pHostDrvAudio->pfnStreamDestroy(pThis->pHostDrvAudio, pStreamEx->pBackend, pStreamEx->fDestroyImmediate);
1970 RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
1971
1972 pStreamEx->fStatus &= ~(PDMAUDIOSTREAM_STS_BACKEND_CREATED | PDMAUDIOSTREAM_STS_BACKEND_READY);
1973 PDMAUDIOSTREAM_STS_ASSERT_VALID(pStreamEx->fStatus);
1974 }
1975
1976 LogFlowFunc(("[%s] Returning %Rrc\n", pStreamEx->Core.szName, rc));
1977 return rc;
1978}
1979
1980
1981/**
1982 * Uninitializes an audio stream - worker for drvAudioStreamDestroy,
1983 * drvAudioDestruct and drvAudioStreamCreate.
1984 *
1985 * @returns VBox status code.
1986 * @param pThis Pointer to driver instance.
1987 * @param pStreamEx Pointer to audio stream to uninitialize.
1988 */
1989static int drvAudioStreamUninitInternal(PDRVAUDIO pThis, PDRVAUDIOSTREAM pStreamEx)
1990{
1991 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
1992 AssertMsgReturn(pStreamEx->cRefs <= 1,
1993 ("Stream '%s' still has %RU32 references held when uninitializing\n", pStreamEx->Core.szName, pStreamEx->cRefs),
1994 VERR_WRONG_ORDER);
1995 LogFlowFunc(("[%s] cRefs=%RU32\n", pStreamEx->Core.szName, pStreamEx->cRefs));
1996
1997 RTCritSectEnter(&pStreamEx->Core.CritSect);
1998
1999 /*
2000 * ...
2001 */
2002 if (pStreamEx->fDestroyImmediate)
2003 drvAudioStreamControlInternal(pThis, pStreamEx, PDMAUDIOSTREAMCMD_DISABLE);
2004 int rc = drvAudioStreamDestroyInternalBackend(pThis, pStreamEx);
2005
2006 /* Free pre-buffer space. */
2007 if ( pStreamEx->Core.enmDir == PDMAUDIODIR_OUT
2008 && pStreamEx->Out.pbPreBuf)
2009 {
2010 RTMemFree(pStreamEx->Out.pbPreBuf);
2011 pStreamEx->Out.pbPreBuf = NULL;
2012 pStreamEx->Out.cbPreBufAlloc = 0;
2013 pStreamEx->Out.cbPreBuffered = 0;
2014 pStreamEx->Out.offPreBuf = 0;
2015 }
2016
2017 if (RT_SUCCESS(rc))
2018 {
2019#ifdef LOG_ENABLED
2020 if (pStreamEx->fStatus != PDMAUDIOSTREAM_STS_NONE)
2021 {
2022 char szStreamSts[DRVAUDIO_STATUS_STR_MAX];
2023 LogFunc(("[%s] Warning: Still has %s set when uninitializing\n",
2024 pStreamEx->Core.szName, drvAudioStreamStatusToStr(szStreamSts, pStreamEx->fStatus)));
2025 }
2026#endif
2027 pStreamEx->fStatus = PDMAUDIOSTREAM_STS_NONE;
2028 }
2029
2030 PPDMDRVINS const pDrvIns = pThis->pDrvIns;
2031 PDMDrvHlpSTAMDeregisterByPrefix(pDrvIns, pStreamEx->Core.szName);
2032
2033 if (pStreamEx->Core.enmDir == PDMAUDIODIR_IN)
2034 {
2035 if (pThis->CfgIn.Dbg.fEnabled)
2036 {
2037 AudioHlpFileDestroy(pStreamEx->In.Dbg.pFileCapture);
2038 pStreamEx->In.Dbg.pFileCapture = NULL;
2039 }
2040 }
2041 else
2042 {
2043 Assert(pStreamEx->Core.enmDir == PDMAUDIODIR_OUT);
2044 if (pThis->CfgOut.Dbg.fEnabled)
2045 {
2046 AudioHlpFileDestroy(pStreamEx->Out.Dbg.pFilePlay);
2047 pStreamEx->Out.Dbg.pFilePlay = NULL;
2048 }
2049 }
2050
2051 RTCritSectLeave(&pStreamEx->Core.CritSect);
2052 LogFlowFunc(("Returning %Rrc\n", rc));
2053 return rc;
2054}
2055
2056
2057/**
2058 * Internal release function.
2059 *
2060 * @returns New reference count, UINT32_MAX if bad stream.
2061 * @param pThis Pointer to the DrvAudio instance data.
2062 * @param pStreamEx The stream to reference.
2063 * @param fMayDestroy Whether the caller is allowed to implicitly destroy
2064 * the stream or not.
2065 */
2066static uint32_t drvAudioStreamReleaseInternal(PDRVAUDIO pThis, PDRVAUDIOSTREAM pStreamEx, bool fMayDestroy)
2067{
2068 AssertPtrReturn(pStreamEx, UINT32_MAX);
2069 AssertReturn(pStreamEx->Core.uMagic == PDMAUDIOSTREAM_MAGIC, UINT32_MAX);
2070 AssertReturn(pStreamEx->uMagic == DRVAUDIOSTREAM_MAGIC, UINT32_MAX);
2071 Assert(!RTCritSectIsOwner(&pStreamEx->Core.CritSect));
2072
2073 uint32_t cRefs = ASMAtomicDecU32(&pStreamEx->cRefs);
2074 if (cRefs != 0)
2075 Assert(cRefs < _1K);
2076 else if (fMayDestroy)
2077 {
2078/** @todo r=bird: Caching one stream in each direction for some time,
2079 * depending on the time it took to create it. drvAudioStreamCreate can use it
2080 * if the configuration matches, otherwise it'll throw it away. This will
2081 * provide a general speedup independ of device (HDA used to do this, but
2082 * doesn't) and backend implementation. Ofc, the backend probably needs an
2083 * opt-out here. */
2084 int rc = drvAudioStreamUninitInternal(pThis, pStreamEx);
2085 if (RT_SUCCESS(rc))
2086 {
2087 RTCritSectRwEnterExcl(&pThis->CritSectGlobals);
2088
2089 if (pStreamEx->Core.enmDir == PDMAUDIODIR_IN)
2090 pThis->In.cStreamsFree++;
2091 else /* Out */
2092 pThis->Out.cStreamsFree++;
2093 pThis->cStreams--;
2094
2095 RTListNodeRemove(&pStreamEx->ListEntry);
2096
2097 RTCritSectRwLeaveExcl(&pThis->CritSectGlobals);
2098
2099 drvAudioStreamFree(pStreamEx);
2100 }
2101 else
2102 {
2103 LogRel(("Audio: Uninitializing stream '%s' failed with %Rrc\n", pStreamEx->Core.szName, rc));
2104 /** @todo r=bird: What's the plan now? */
2105 }
2106 }
2107 else
2108 {
2109 cRefs = ASMAtomicIncU32(&pStreamEx->cRefs);
2110 AssertFailed();
2111 }
2112
2113 Log12Func(("returns %u (%s)\n", cRefs, cRefs > 0 ? pStreamEx->Core.szName : "destroyed"));
2114 return cRefs;
2115}
2116
2117
2118/**
2119 * Asynchronous worker for drvAudioStreamDestroy.
2120 *
2121 * Does DISABLE and releases reference, possibly destroying the stream.
2122 *
2123 * @param pThis Pointer to the DrvAudio instance data.
2124 * @param pStreamEx The stream. One reference for us to release.
2125 * @param fImmediate How to treat draining streams.
2126 */
2127static DECLCALLBACK(void) drvAudioStreamDestroyAsync(PDRVAUDIO pThis, PDRVAUDIOSTREAM pStreamEx, bool fImmediate)
2128{
2129 LogFlowFunc(("pThis=%p pStreamEx=%p (%s) fImmediate=%RTbool\n", pThis, pStreamEx, pStreamEx->Core.szName, fImmediate));
2130#ifdef LOG_ENABLED
2131 uint64_t const nsStart = RTTimeNanoTS();
2132#endif
2133 RTCritSectEnter(&pStreamEx->Core.CritSect);
2134
2135 pStreamEx->fDestroyImmediate = fImmediate; /* Do NOT adjust for draining status, just pass it as-is. CoreAudio needs this. */
2136
2137 if (!fImmediate && (pStreamEx->fStatus & PDMAUDIOSTREAM_STS_PENDING_DISABLE))
2138 LogFlowFunc(("No DISABLE\n"));
2139 else
2140 {
2141 int rc2 = drvAudioStreamControlInternal(pThis, pStreamEx, PDMAUDIOSTREAMCMD_DISABLE);
2142 LogFlowFunc(("DISABLE done: %Rrc\n", rc2));
2143 AssertRC(rc2);
2144 }
2145
2146 RTCritSectLeave(&pStreamEx->Core.CritSect);
2147
2148 drvAudioStreamReleaseInternal(pThis, pStreamEx, true /*fMayDestroy*/);
2149
2150 LogFlowFunc(("returning (after %'RU64 ns)\n", RTTimeNanoTS() - nsStart));
2151}
2152
2153
2154/**
2155 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnStreamDestroy}
2156 */
2157static DECLCALLBACK(int) drvAudioStreamDestroy(PPDMIAUDIOCONNECTOR pInterface, PPDMAUDIOSTREAM pStream, bool fImmediate)
2158{
2159 PDRVAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVAUDIO, IAudioConnector);
2160 AssertPtr(pThis);
2161
2162 /* Ignore NULL streams. */
2163 if (!pStream)
2164 return VINF_SUCCESS;
2165
2166 PDRVAUDIOSTREAM pStreamEx = (PDRVAUDIOSTREAM)pStream; /* Note! Do not touch pStream after this! */
2167 AssertPtrReturn(pStreamEx, VERR_INVALID_POINTER);
2168 LogFlowFunc(("ENTER - %p (%s) fImmediate=%RTbool\n", pStreamEx, pStreamEx->Core.szName, fImmediate));
2169 AssertReturn(pStreamEx->Core.uMagic == PDMAUDIOSTREAM_MAGIC, VERR_INVALID_MAGIC);
2170 AssertReturn(pStreamEx->uMagic == DRVAUDIOSTREAM_MAGIC, VERR_INVALID_MAGIC);
2171 AssertReturn(pStreamEx->pBackend && pStreamEx->pBackend->uMagic == PDMAUDIOBACKENDSTREAM_MAGIC, VERR_INVALID_MAGIC);
2172
2173 /*
2174 * The main difference from a regular release is that this will disable
2175 * (or drain if we could) the stream and we can cancel any pending
2176 * pfnStreamInitAsync call.
2177 */
2178 int rc = RTCritSectEnter(&pStreamEx->Core.CritSect);
2179 AssertRCReturn(rc, rc);
2180
2181 if (pStreamEx->uMagic == DRVAUDIOSTREAM_MAGIC)
2182 {
2183 if (pStreamEx->cRefs > 0 && pStreamEx->cRefs < UINT32_MAX / 4)
2184 {
2185 char szStatus[DRVAUDIO_STATUS_STR_MAX];
2186 LogRel2(("Audio: Destroying stream '%s': cRefs=%u; status: %s; backend: %s; hReqInitAsync=%p\n",
2187 pStreamEx->Core.szName, pStreamEx->cRefs, drvAudioStreamStatusToStr(szStatus, pStreamEx->fStatus),
2188 PDMHostAudioStreamStateGetName(drvAudioStreamGetBackendState(pThis, pStreamEx)),
2189 pStreamEx->hReqInitAsync));
2190
2191 /* Try cancel pending async init request and release the it. */
2192 if (pStreamEx->hReqInitAsync != NIL_RTREQ)
2193 {
2194 Assert(pStreamEx->cRefs >= 2);
2195 int rc2 = RTReqCancel(pStreamEx->hReqInitAsync);
2196
2197 RTReqRelease(pStreamEx->hReqInitAsync);
2198 pStreamEx->hReqInitAsync = NIL_RTREQ;
2199
2200 RTCritSectLeave(&pStreamEx->Core.CritSect); /* (exit before releasing the stream to avoid assertion) */
2201
2202 if (RT_SUCCESS(rc2))
2203 {
2204 LogFlowFunc(("Successfully cancelled pending pfnStreamInitAsync call (hReqInitAsync=%p).\n",
2205 pStreamEx->hReqInitAsync));
2206 drvAudioStreamReleaseInternal(pThis, pStreamEx, true /*fMayDestroy*/);
2207 }
2208 else
2209 {
2210 LogFlowFunc(("Failed to cancel pending pfnStreamInitAsync call (hReqInitAsync=%p): %Rrc\n",
2211 pStreamEx->hReqInitAsync, rc2));
2212 Assert(rc2 == VERR_RT_REQUEST_STATE);
2213 }
2214 }
2215 else
2216 RTCritSectLeave(&pStreamEx->Core.CritSect);
2217
2218 /*
2219 * Now, if the backend requests asynchronous disabling and destruction
2220 * push the disabling and destroying over to a worker thread.
2221 *
2222 * This is a general offloading feature that all backends should make use of,
2223 * however it's rather precarious on macs where stopping an already draining
2224 * stream may take 8-10ms which naturally isn't something we should be doing
2225 * on an EMT.
2226 */
2227 if (!(pThis->BackendCfg.fFlags & PDMAUDIOBACKEND_F_ASYNC_STREAM_DESTROY))
2228 drvAudioStreamDestroyAsync(pThis, pStreamEx, fImmediate);
2229 else
2230 {
2231 int rc2 = RTReqPoolCallEx(pThis->hReqPool, 0 /*cMillies*/, NULL /*phReq*/,
2232 RTREQFLAGS_VOID | RTREQFLAGS_NO_WAIT,
2233 (PFNRT)drvAudioStreamDestroyAsync, 3, pThis, pStreamEx, fImmediate);
2234 LogFlowFunc(("hReqInitAsync=%p rc2=%Rrc\n", pStreamEx->hReqInitAsync, rc2));
2235 AssertRCStmt(rc2, drvAudioStreamDestroyAsync(pThis, pStreamEx, fImmediate));
2236 }
2237 }
2238 else
2239 {
2240 AssertLogRelMsgFailedStmt(("%p cRefs=%#x\n", pStreamEx, pStreamEx->cRefs), rc = VERR_CALLER_NO_REFERENCE);
2241 RTCritSectLeave(&pStreamEx->Core.CritSect); /*??*/
2242 }
2243 }
2244 else
2245 {
2246 AssertLogRelMsgFailedStmt(("%p uMagic=%#x\n", pStreamEx, pStreamEx->uMagic), rc = VERR_INVALID_MAGIC);
2247 RTCritSectLeave(&pStreamEx->Core.CritSect); /*??*/
2248 }
2249
2250 LogFlowFuncLeaveRC(rc);
2251 return rc;
2252}
2253
2254
2255/**
2256 * Drops all audio data (and associated state) of a stream.
2257 *
2258 * Used by drvAudioStreamIterateInternal(), drvAudioStreamResetOnDisable(), and
2259 * drvAudioStreamReInitInternal().
2260 *
2261 * @param pStreamEx Stream to drop data for.
2262 */
2263static void drvAudioStreamResetInternal(PDRVAUDIOSTREAM pStreamEx)
2264{
2265 LogFunc(("[%s]\n", pStreamEx->Core.szName));
2266 Assert(RTCritSectIsOwner(&pStreamEx->Core.CritSect));
2267
2268 pStreamEx->nsLastIterated = 0;
2269 pStreamEx->nsLastPlayedCaptured = 0;
2270 pStreamEx->nsLastReadWritten = 0;
2271 if (pStreamEx->Host.Cfg.enmDir == PDMAUDIODIR_OUT)
2272 {
2273 pStreamEx->Out.cbPreBuffered = 0;
2274 pStreamEx->Out.offPreBuf = 0;
2275 pStreamEx->Out.enmPlayState = pStreamEx->cbPreBufThreshold > 0
2276 ? DRVAUDIOPLAYSTATE_PREBUF : DRVAUDIOPLAYSTATE_PLAY;
2277 }
2278 else
2279 pStreamEx->In.enmCaptureState = pStreamEx->cbPreBufThreshold > 0
2280 ? DRVAUDIOCAPTURESTATE_PREBUF : DRVAUDIOCAPTURESTATE_CAPTURING;
2281}
2282
2283
2284/**
2285 * Re-initializes an audio stream with its existing host and guest stream
2286 * configuration.
2287 *
2288 * This might be the case if the backend told us we need to re-initialize
2289 * because something on the host side has changed.
2290 *
2291 * @note Does not touch the stream's status flags.
2292 *
2293 * @returns VBox status code.
2294 * @param pThis Pointer to driver instance.
2295 * @param pStreamEx Stream to re-initialize.
2296 */
2297static int drvAudioStreamReInitInternal(PDRVAUDIO pThis, PDRVAUDIOSTREAM pStreamEx)
2298{
2299 char szTmp[RT_MAX(PDMAUDIOSTRMCFGTOSTRING_MAX, DRVAUDIO_STATUS_STR_MAX)];
2300 LogFlowFunc(("[%s] status: %s\n", pStreamEx->Core.szName, drvAudioStreamStatusToStr(szTmp, pStreamEx->fStatus) ));
2301 Assert(RTCritSectIsOwner(&pStreamEx->Core.CritSect));
2302 RTCritSectRwEnterShared(&pThis->CritSectHotPlug);
2303
2304 /*
2305 * Destroy and re-create stream on backend side.
2306 */
2307 if ( (pStreamEx->fStatus & (PDMAUDIOSTREAM_STS_ENABLED | PDMAUDIOSTREAM_STS_BACKEND_CREATED | PDMAUDIOSTREAM_STS_BACKEND_READY))
2308 == (PDMAUDIOSTREAM_STS_ENABLED | PDMAUDIOSTREAM_STS_BACKEND_CREATED | PDMAUDIOSTREAM_STS_BACKEND_READY))
2309 drvAudioStreamControlInternalBackend(pThis, pStreamEx, PDMAUDIOSTREAMCMD_DISABLE);
2310
2311 if (pStreamEx->fStatus & PDMAUDIOSTREAM_STS_BACKEND_CREATED)
2312 drvAudioStreamDestroyInternalBackend(pThis, pStreamEx);
2313
2314 int rc = VERR_AUDIO_STREAM_NOT_READY;
2315 if (!(pStreamEx->fStatus & PDMAUDIOSTREAM_STS_BACKEND_CREATED))
2316 {
2317 drvAudioStreamResetInternal(pStreamEx);
2318
2319/** @todo
2320 * We need to zero the backend storage here!!
2321 * We need to zero the backend storage here!!
2322 * We need to zero the backend storage here!!
2323 * We need to zero the backend storage here!!
2324 * We need to zero the backend storage here!!
2325 * We need to zero the backend storage here!!
2326 * We need to zero the backend storage here!!
2327 * */
2328 PDMAUDIOSTREAMCFG CfgHostAcq;
2329 rc = drvAudioStreamCreateInternalBackend(pThis, pStreamEx, &pStreamEx->Host.Cfg, &CfgHostAcq);
2330 if (RT_SUCCESS(rc))
2331 {
2332 LogFunc(("[%s] Acquired host format: %s\n",
2333 pStreamEx->Core.szName, PDMAudioStrmCfgToString(&CfgHostAcq, szTmp, sizeof(szTmp)) ));
2334 /** @todo Validate (re-)acquired configuration with pStreamEx->Core.Host.Cfg?
2335 * drvAudioStreamInitInternal() does some setup and a bunch of
2336 * validations + adjustments of the stream config, so this surely is quite
2337 * optimistic. */
2338 if (true)
2339 {
2340 /*
2341 * Kick off the asynchronous init.
2342 */
2343 if (!pStreamEx->fNeedAsyncInit)
2344 {
2345 pStreamEx->fStatus |= PDMAUDIOSTREAM_STS_BACKEND_READY;
2346 PDMAUDIOSTREAM_STS_ASSERT_VALID(pStreamEx->fStatus);
2347 }
2348 else
2349 {
2350 drvAudioStreamRetainInternal(pStreamEx);
2351 int rc2 = RTReqPoolCallEx(pThis->hReqPool, 0 /*cMillies*/, &pStreamEx->hReqInitAsync,
2352 RTREQFLAGS_VOID | RTREQFLAGS_NO_WAIT,
2353 (PFNRT)drvAudioStreamInitAsync, 2, pThis, pStreamEx);
2354 LogFlowFunc(("hReqInitAsync=%p rc2=%Rrc\n", pStreamEx->hReqInitAsync, rc2));
2355 AssertRCStmt(rc2, drvAudioStreamInitAsync(pThis, pStreamEx));
2356 }
2357
2358 /*
2359 * Update the backend on the stream state if it's ready, otherwise
2360 * let the worker thread do it after the async init has completed.
2361 */
2362 if ( (pStreamEx->fStatus & (PDMAUDIOSTREAM_STS_BACKEND_READY | PDMAUDIOSTREAM_STS_BACKEND_CREATED))
2363 == (PDMAUDIOSTREAM_STS_BACKEND_READY | PDMAUDIOSTREAM_STS_BACKEND_CREATED))
2364 {
2365 rc = drvAudioStreamUpdateBackendOnStatus(pThis, pStreamEx, "re-initializing");
2366 /** @todo not sure if we really need to care about this status code... */
2367 }
2368 else if (pStreamEx->fStatus & PDMAUDIOSTREAM_STS_BACKEND_CREATED)
2369 {
2370 Assert(pStreamEx->hReqInitAsync != NIL_RTREQ);
2371 LogFunc(("Asynchronous stream init (%p) ...\n", pStreamEx->hReqInitAsync));
2372 }
2373 else
2374 {
2375 LogRel(("Audio: Re-initializing stream '%s' somehow failed, status: %s\n", pStreamEx->Core.szName,
2376 drvAudioStreamStatusToStr(szTmp, pStreamEx->fStatus) ));
2377 AssertFailed();
2378 rc = VERR_AUDIO_STREAM_COULD_NOT_CREATE;
2379 }
2380 }
2381 }
2382 else
2383 LogRel(("Audio: Re-initializing stream '%s' failed with %Rrc\n", pStreamEx->Core.szName, rc));
2384 }
2385 else
2386 {
2387 LogRel(("Audio: Re-initializing stream '%s' failed to destroy previous backend.\n", pStreamEx->Core.szName));
2388 AssertFailed();
2389 }
2390
2391 RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
2392 LogFunc(("[%s] Returning %Rrc\n", pStreamEx->Core.szName, rc));
2393 return rc;
2394}
2395
2396
2397/**
2398 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnStreamReInit}
2399 */
2400static DECLCALLBACK(int) drvAudioStreamReInit(PPDMIAUDIOCONNECTOR pInterface, PPDMAUDIOSTREAM pStream)
2401{
2402 PDRVAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVAUDIO, IAudioConnector);
2403 PDRVAUDIOSTREAM pStreamEx = (PDRVAUDIOSTREAM)pStream;
2404 AssertPtrReturn(pStreamEx, VERR_INVALID_POINTER);
2405 AssertReturn(pStreamEx->Core.uMagic == PDMAUDIOSTREAM_MAGIC, VERR_INVALID_MAGIC);
2406 AssertReturn(pStreamEx->uMagic == DRVAUDIOSTREAM_MAGIC, VERR_INVALID_MAGIC);
2407 AssertReturn(pStreamEx->fStatus & PDMAUDIOSTREAM_STS_NEED_REINIT, VERR_INVALID_STATE);
2408 LogFlowFunc(("\n"));
2409
2410 int rc = RTCritSectEnter(&pStreamEx->Core.CritSect);
2411 AssertRCReturn(rc, rc);
2412
2413 if (pStreamEx->fStatus & PDMAUDIOSTREAM_STS_NEED_REINIT)
2414 {
2415 const unsigned cMaxTries = 5;
2416 const uint64_t nsNow = RTTimeNanoTS();
2417
2418 /* Throttle re-initializing streams on failure. */
2419 if ( pStreamEx->cTriesReInit < cMaxTries
2420 && pStreamEx->hReqInitAsync == NIL_RTREQ
2421 && ( pStreamEx->nsLastReInit == 0
2422 || nsNow - pStreamEx->nsLastReInit >= RT_NS_1SEC * pStreamEx->cTriesReInit))
2423 {
2424 rc = drvAudioStreamReInitInternal(pThis, pStreamEx);
2425 if (RT_SUCCESS(rc))
2426 {
2427 /* Remove the pending re-init flag on success. */
2428 pStreamEx->fStatus &= ~PDMAUDIOSTREAM_STS_NEED_REINIT;
2429 PDMAUDIOSTREAM_STS_ASSERT_VALID(pStreamEx->fStatus);
2430 }
2431 else
2432 {
2433 pStreamEx->nsLastReInit = nsNow;
2434 pStreamEx->cTriesReInit++;
2435
2436 /* Did we exceed our tries re-initializing the stream?
2437 * Then this one is dead-in-the-water, so disable it for further use. */
2438 if (pStreamEx->cTriesReInit >= cMaxTries)
2439 {
2440 LogRel(("Audio: Re-initializing stream '%s' exceeded maximum retries (%u), leaving as disabled\n",
2441 pStreamEx->Core.szName, cMaxTries));
2442
2443 /* Don't try to re-initialize anymore and mark as disabled. */
2444 /** @todo should mark it as not-initialized too, shouldn't we? */
2445 pStreamEx->fStatus &= ~(PDMAUDIOSTREAM_STS_NEED_REINIT | PDMAUDIOSTREAM_STS_ENABLED);
2446 PDMAUDIOSTREAM_STS_ASSERT_VALID(pStreamEx->fStatus);
2447
2448 /* Note: Further writes to this stream go to / will be read from the bit bucket (/dev/null) from now on. */
2449 }
2450 }
2451 }
2452 else
2453 Log8Func(("cTriesReInit=%d hReqInitAsync=%p nsLast=%RU64 nsNow=%RU64 nsDelta=%RU64\n", pStreamEx->cTriesReInit,
2454 pStreamEx->hReqInitAsync, pStreamEx->nsLastReInit, nsNow, nsNow - pStreamEx->nsLastReInit));
2455
2456#ifdef LOG_ENABLED
2457 char szStreamSts[DRVAUDIO_STATUS_STR_MAX];
2458#endif
2459 Log3Func(("[%s] fStatus=%s\n", pStreamEx->Core.szName, drvAudioStreamStatusToStr(szStreamSts, pStreamEx->fStatus)));
2460 }
2461 else
2462 {
2463 AssertFailed();
2464 rc = VERR_INVALID_STATE;
2465 }
2466
2467 RTCritSectLeave(&pStreamEx->Core.CritSect);
2468
2469 LogFlowFuncLeaveRC(rc);
2470 return rc;
2471}
2472
2473
2474/**
2475 * Internal retain function.
2476 *
2477 * @returns New reference count, UINT32_MAX if bad stream.
2478 * @param pStreamEx The stream to reference.
2479 */
2480static uint32_t drvAudioStreamRetainInternal(PDRVAUDIOSTREAM pStreamEx)
2481{
2482 AssertPtrReturn(pStreamEx, UINT32_MAX);
2483 AssertReturn(pStreamEx->Core.uMagic == PDMAUDIOSTREAM_MAGIC, UINT32_MAX);
2484 AssertReturn(pStreamEx->uMagic == DRVAUDIOSTREAM_MAGIC, UINT32_MAX);
2485
2486 uint32_t const cRefs = ASMAtomicIncU32(&pStreamEx->cRefs);
2487 Assert(cRefs > 1);
2488 Assert(cRefs < _1K);
2489
2490 Log12Func(("returns %u (%s)\n", cRefs, pStreamEx->Core.szName));
2491 return cRefs;
2492}
2493
2494
2495/**
2496 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnStreamRetain}
2497 */
2498static DECLCALLBACK(uint32_t) drvAudioStreamRetain(PPDMIAUDIOCONNECTOR pInterface, PPDMAUDIOSTREAM pStream)
2499{
2500 RT_NOREF(pInterface);
2501 return drvAudioStreamRetainInternal((PDRVAUDIOSTREAM)pStream);
2502}
2503
2504
2505/**
2506 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnStreamRelease}
2507 */
2508static DECLCALLBACK(uint32_t) drvAudioStreamRelease(PPDMIAUDIOCONNECTOR pInterface, PPDMAUDIOSTREAM pStream)
2509{
2510 return drvAudioStreamReleaseInternal(RT_FROM_MEMBER(pInterface, DRVAUDIO, IAudioConnector),
2511 (PDRVAUDIOSTREAM)pStream,
2512 false /*fMayDestroy*/);
2513}
2514
2515
2516/**
2517 * Controls a stream's backend.
2518 *
2519 * @returns VBox status code.
2520 * @param pThis Pointer to driver instance.
2521 * @param pStreamEx Stream to control.
2522 * @param enmStreamCmd Control command.
2523 *
2524 * @note Caller has entered the critical section of the stream.
2525 * @note Can be called w/o having entered DRVAUDIO::CritSectHotPlug.
2526 */
2527static int drvAudioStreamControlInternalBackend(PDRVAUDIO pThis, PDRVAUDIOSTREAM pStreamEx, PDMAUDIOSTREAMCMD enmStreamCmd)
2528{
2529 AssertPtr(pThis);
2530 AssertPtr(pStreamEx);
2531 Assert(RTCritSectIsOwner(&pStreamEx->Core.CritSect));
2532
2533 int rc = RTCritSectRwEnterShared(&pThis->CritSectHotPlug);
2534 AssertRCReturn(rc, rc);
2535
2536 /*
2537 * Whether to propagate commands down to the backend.
2538 *
2539 * 1. If the stream direction is disabled on the driver level, we should
2540 * obviously not call the backend. Our stream status will reflect the
2541 * actual state so drvAudioEnable() can tell the backend if the user
2542 * re-enables the stream direction.
2543 *
2544 * 2. If the backend hasn't finished initializing yet, don't try call
2545 * it to start/stop/pause/whatever the stream. (Better to do it here
2546 * than to replicate this in the relevant backends.) When the backend
2547 * finish initializing the stream, we'll update it about the stream state.
2548 */
2549 bool const fDirEnabled = pStreamEx->Core.enmDir == PDMAUDIODIR_IN
2550 ? pThis->In.fEnabled : pThis->Out.fEnabled;
2551 PDMHOSTAUDIOSTREAMSTATE const enmBackendState = drvAudioStreamGetBackendState(pThis, pStreamEx);
2552 /* ^^^ (checks pThis->pHostDrvAudio != NULL too) */
2553
2554 char szStreamSts[DRVAUDIO_STATUS_STR_MAX];
2555 LogRel2(("Audio: %s stream '%s' backend (%s is %s; status: %s; backend-status: %s)\n",
2556 PDMAudioStrmCmdGetName(enmStreamCmd), pStreamEx->Core.szName, PDMAudioDirGetName(pStreamEx->Core.enmDir),
2557 fDirEnabled ? "enabled" : "disabled", drvAudioStreamStatusToStr(szStreamSts, pStreamEx->fStatus),
2558 PDMHostAudioStreamStateGetName(enmBackendState) ));
2559
2560 if (fDirEnabled)
2561 {
2562 if ( (pStreamEx->fStatus & PDMAUDIOSTREAM_STS_BACKEND_READY /* don't really need this check, do we? */)
2563 && ( enmBackendState == PDMHOSTAUDIOSTREAMSTATE_OKAY
2564 || enmBackendState == PDMHOSTAUDIOSTREAMSTATE_DRAINING) )
2565 {
2566 /** @todo Backend will change to explicit methods here, so please don't simplify
2567 * the switch. */
2568 switch (enmStreamCmd)
2569 {
2570 case PDMAUDIOSTREAMCMD_ENABLE:
2571 rc = pThis->pHostDrvAudio->pfnStreamControl(pThis->pHostDrvAudio, pStreamEx->pBackend,
2572 PDMAUDIOSTREAMCMD_ENABLE);
2573 break;
2574
2575 case PDMAUDIOSTREAMCMD_DISABLE:
2576 rc = pThis->pHostDrvAudio->pfnStreamControl(pThis->pHostDrvAudio, pStreamEx->pBackend,
2577 PDMAUDIOSTREAMCMD_DISABLE);
2578 break;
2579
2580 case PDMAUDIOSTREAMCMD_PAUSE:
2581 rc = pThis->pHostDrvAudio->pfnStreamControl(pThis->pHostDrvAudio, pStreamEx->pBackend,
2582 PDMAUDIOSTREAMCMD_PAUSE);
2583 break;
2584
2585 case PDMAUDIOSTREAMCMD_RESUME:
2586 rc = pThis->pHostDrvAudio->pfnStreamControl(pThis->pHostDrvAudio, pStreamEx->pBackend,
2587 PDMAUDIOSTREAMCMD_RESUME);
2588 break;
2589
2590 case PDMAUDIOSTREAMCMD_DRAIN:
2591 rc = pThis->pHostDrvAudio->pfnStreamControl(pThis->pHostDrvAudio, pStreamEx->pBackend,
2592 PDMAUDIOSTREAMCMD_DRAIN);
2593 break;
2594
2595 default:
2596 AssertMsgFailedBreakStmt(("Command %RU32 not implemented\n", enmStreamCmd), rc = VERR_INTERNAL_ERROR_2);
2597 }
2598 if (RT_SUCCESS(rc))
2599 Log2Func(("[%s] %s succeeded (%Rrc)\n", pStreamEx->Core.szName, PDMAudioStrmCmdGetName(enmStreamCmd), rc));
2600 else
2601 {
2602 LogFunc(("[%s] %s failed with %Rrc\n", pStreamEx->Core.szName, PDMAudioStrmCmdGetName(enmStreamCmd), rc));
2603 if ( rc != VERR_NOT_IMPLEMENTED
2604 && rc != VERR_NOT_SUPPORTED
2605 && rc != VERR_AUDIO_STREAM_NOT_READY)
2606 LogRel(("Audio: %s stream '%s' failed with %Rrc\n", PDMAudioStrmCmdGetName(enmStreamCmd), pStreamEx->Core.szName, rc));
2607 }
2608 }
2609 else
2610 LogFlowFunc(("enmBackendStat(=%s) != OKAY || !(fStatus(=%#x) & BACKEND_READY)\n",
2611 PDMHostAudioStreamStateGetName(enmBackendState), pStreamEx->fStatus));
2612 }
2613 else
2614 LogFlowFunc(("fDirEnabled=false\n"));
2615
2616 RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
2617 return rc;
2618}
2619
2620
2621/**
2622 * Resets the given audio stream.
2623 *
2624 * @param pStreamEx Stream to reset.
2625 */
2626static void drvAudioStreamResetOnDisable(PDRVAUDIOSTREAM pStreamEx)
2627{
2628 drvAudioStreamResetInternal(pStreamEx);
2629
2630 LogFunc(("[%s]\n", pStreamEx->Core.szName));
2631
2632 pStreamEx->fStatus &= PDMAUDIOSTREAM_STS_BACKEND_CREATED | PDMAUDIOSTREAM_STS_BACKEND_READY;
2633 pStreamEx->Core.fWarningsShown = PDMAUDIOSTREAM_WARN_FLAGS_NONE;
2634
2635#ifdef VBOX_WITH_STATISTICS
2636 /*
2637 * Reset statistics.
2638 */
2639 if (pStreamEx->Core.enmDir == PDMAUDIODIR_IN)
2640 {
2641 STAM_COUNTER_RESET(&pStreamEx->In.Stats.TotalFramesCaptured);
2642 STAM_COUNTER_RESET(&pStreamEx->In.Stats.TotalTimesCaptured);
2643 STAM_COUNTER_RESET(&pStreamEx->In.Stats.TotalTimesRead);
2644 }
2645 else if (pStreamEx->Core.enmDir == PDMAUDIODIR_OUT)
2646 {
2647 }
2648 else
2649 AssertFailed();
2650#endif
2651}
2652
2653
2654/**
2655 * Controls an audio stream.
2656 *
2657 * @returns VBox status code.
2658 * @param pThis Pointer to driver instance.
2659 * @param pStreamEx Stream to control.
2660 * @param enmStreamCmd Control command.
2661 */
2662static int drvAudioStreamControlInternal(PDRVAUDIO pThis, PDRVAUDIOSTREAM pStreamEx, PDMAUDIOSTREAMCMD enmStreamCmd)
2663{
2664 AssertPtr(pThis);
2665 AssertPtr(pStreamEx);
2666 Assert(RTCritSectIsOwner(&pStreamEx->Core.CritSect));
2667
2668#ifdef LOG_ENABLED
2669 char szStreamSts[DRVAUDIO_STATUS_STR_MAX];
2670#endif
2671 LogFunc(("[%s] enmStreamCmd=%s fStatus=%s\n", pStreamEx->Core.szName, PDMAudioStrmCmdGetName(enmStreamCmd),
2672 drvAudioStreamStatusToStr(szStreamSts, pStreamEx->fStatus)));
2673
2674 int rc = VINF_SUCCESS;
2675
2676 switch (enmStreamCmd)
2677 {
2678 case PDMAUDIOSTREAMCMD_ENABLE:
2679 if (!(pStreamEx->fStatus & PDMAUDIOSTREAM_STS_ENABLED))
2680 {
2681 /* Are we still draining this stream? Then we must disable it first. */
2682 if (pStreamEx->fStatus & PDMAUDIOSTREAM_STS_PENDING_DISABLE)
2683 {
2684 LogFunc(("Stream '%s' is still draining - disabling...\n", pStreamEx->Core.szName));
2685 rc = drvAudioStreamControlInternalBackend(pThis, pStreamEx, PDMAUDIOSTREAMCMD_DISABLE);
2686 AssertRC(rc);
2687 if (drvAudioStreamGetBackendState(pThis, pStreamEx) != PDMHOSTAUDIOSTREAMSTATE_DRAINING)
2688 {
2689 pStreamEx->fStatus &= ~(PDMAUDIOSTREAM_STS_ENABLED | PDMAUDIOSTREAM_STS_PENDING_DISABLE);
2690 drvAudioStreamResetInternal(pStreamEx);
2691 rc = VINF_SUCCESS;
2692 }
2693 }
2694
2695 if (RT_SUCCESS(rc))
2696 {
2697 /* Reset the state before we try to start. */
2698 PDMHOSTAUDIOSTREAMSTATE const enmBackendState = drvAudioStreamGetBackendState(pThis, pStreamEx);
2699 pStreamEx->enmLastBackendState = enmBackendState;
2700 pStreamEx->offInternal = 0;
2701
2702 if (pStreamEx->Core.enmDir == PDMAUDIODIR_OUT)
2703 {
2704 pStreamEx->Out.cbPreBuffered = 0;
2705 pStreamEx->Out.offPreBuf = 0;
2706 pStreamEx->Out.enmPlayState = DRVAUDIOPLAYSTATE_NOPLAY;
2707 switch (enmBackendState)
2708 {
2709 case PDMHOSTAUDIOSTREAMSTATE_INITIALIZING:
2710 if (pStreamEx->cbPreBufThreshold > 0)
2711 pStreamEx->Out.enmPlayState = DRVAUDIOPLAYSTATE_PREBUF;
2712 break;
2713 case PDMHOSTAUDIOSTREAMSTATE_DRAINING:
2714 AssertFailed();
2715 RT_FALL_THROUGH();
2716 case PDMHOSTAUDIOSTREAMSTATE_OKAY:
2717 pStreamEx->Out.enmPlayState = pStreamEx->cbPreBufThreshold > 0
2718 ? DRVAUDIOPLAYSTATE_PREBUF : DRVAUDIOPLAYSTATE_PLAY;
2719 break;
2720 case PDMHOSTAUDIOSTREAMSTATE_NOT_WORKING:
2721 case PDMHOSTAUDIOSTREAMSTATE_INACTIVE:
2722 break;
2723 /* no default */
2724 case PDMHOSTAUDIOSTREAMSTATE_INVALID:
2725 case PDMHOSTAUDIOSTREAMSTATE_END:
2726 case PDMHOSTAUDIOSTREAMSTATE_32BIT_HACK:
2727 break;
2728 }
2729 LogFunc(("ENABLE: enmBackendState=%s enmPlayState=%s\n", PDMHostAudioStreamStateGetName(enmBackendState),
2730 drvAudioPlayStateName(pStreamEx->Out.enmPlayState)));
2731 }
2732 else
2733 {
2734 pStreamEx->In.enmCaptureState = DRVAUDIOCAPTURESTATE_NO_CAPTURE;
2735 switch (enmBackendState)
2736 {
2737 case PDMHOSTAUDIOSTREAMSTATE_INITIALIZING:
2738 pStreamEx->In.enmCaptureState = DRVAUDIOCAPTURESTATE_PREBUF;
2739 break;
2740 case PDMHOSTAUDIOSTREAMSTATE_DRAINING:
2741 AssertFailed();
2742 RT_FALL_THROUGH();
2743 case PDMHOSTAUDIOSTREAMSTATE_OKAY:
2744 pStreamEx->In.enmCaptureState = pStreamEx->cbPreBufThreshold > 0
2745 ? DRVAUDIOCAPTURESTATE_PREBUF : DRVAUDIOCAPTURESTATE_CAPTURING;
2746 break;
2747 case PDMHOSTAUDIOSTREAMSTATE_NOT_WORKING:
2748 case PDMHOSTAUDIOSTREAMSTATE_INACTIVE:
2749 break;
2750 /* no default */
2751 case PDMHOSTAUDIOSTREAMSTATE_INVALID:
2752 case PDMHOSTAUDIOSTREAMSTATE_END:
2753 case PDMHOSTAUDIOSTREAMSTATE_32BIT_HACK:
2754 break;
2755 }
2756 LogFunc(("ENABLE: enmBackendState=%s enmCaptureState=%s\n", PDMHostAudioStreamStateGetName(enmBackendState),
2757 drvAudioCaptureStateName(pStreamEx->In.enmCaptureState)));
2758 }
2759
2760 rc = drvAudioStreamControlInternalBackend(pThis, pStreamEx, PDMAUDIOSTREAMCMD_ENABLE);
2761 if (RT_SUCCESS(rc))
2762 {
2763 pStreamEx->nsStarted = RTTimeNanoTS();
2764 pStreamEx->fStatus |= PDMAUDIOSTREAM_STS_ENABLED;
2765 PDMAUDIOSTREAM_STS_ASSERT_VALID(pStreamEx->fStatus);
2766 }
2767 }
2768 }
2769 break;
2770
2771 case PDMAUDIOSTREAMCMD_DISABLE:
2772 if (pStreamEx->fStatus & PDMAUDIOSTREAM_STS_ENABLED)
2773 {
2774 rc = drvAudioStreamControlInternalBackend(pThis, pStreamEx, PDMAUDIOSTREAMCMD_DISABLE);
2775 LogFunc(("DISABLE '%s': Backend DISABLE -> %Rrc\n", pStreamEx->Core.szName, rc));
2776 if (RT_SUCCESS(rc)) /** @todo ignore this and reset it anyway? */
2777 drvAudioStreamResetOnDisable(pStreamEx);
2778 }
2779 break;
2780
2781 case PDMAUDIOSTREAMCMD_PAUSE:
2782 if ((pStreamEx->fStatus & (PDMAUDIOSTREAM_STS_ENABLED | PDMAUDIOSTREAM_STS_PAUSED)) == PDMAUDIOSTREAM_STS_ENABLED)
2783 {
2784 rc = drvAudioStreamControlInternalBackend(pThis, pStreamEx, PDMAUDIOSTREAMCMD_PAUSE);
2785 if (RT_SUCCESS(rc))
2786 {
2787 pStreamEx->fStatus |= PDMAUDIOSTREAM_STS_PAUSED;
2788 PDMAUDIOSTREAM_STS_ASSERT_VALID(pStreamEx->fStatus);
2789 }
2790 }
2791 break;
2792
2793 case PDMAUDIOSTREAMCMD_RESUME:
2794 if (pStreamEx->fStatus & PDMAUDIOSTREAM_STS_PAUSED)
2795 {
2796 Assert(pStreamEx->fStatus & PDMAUDIOSTREAM_STS_ENABLED);
2797 rc = drvAudioStreamControlInternalBackend(pThis, pStreamEx, PDMAUDIOSTREAMCMD_RESUME);
2798 if (RT_SUCCESS(rc))
2799 {
2800 pStreamEx->fStatus &= ~PDMAUDIOSTREAM_STS_PAUSED;
2801 PDMAUDIOSTREAM_STS_ASSERT_VALID(pStreamEx->fStatus);
2802 }
2803 }
2804 break;
2805
2806 case PDMAUDIOSTREAMCMD_DRAIN:
2807 /*
2808 * Only for output streams and we don't want this command more than once.
2809 */
2810 AssertReturn(pStreamEx->Core.enmDir == PDMAUDIODIR_OUT, VERR_INVALID_FUNCTION);
2811 AssertBreak(!(pStreamEx->fStatus & PDMAUDIOSTREAM_STS_PENDING_DISABLE));
2812 if (pStreamEx->fStatus & PDMAUDIOSTREAM_STS_ENABLED)
2813 {
2814 rc = VERR_INTERNAL_ERROR_2;
2815 switch (pStreamEx->Out.enmPlayState)
2816 {
2817 case DRVAUDIOPLAYSTATE_PREBUF:
2818 if (pStreamEx->Out.cbPreBuffered > 0)
2819 {
2820 LogFunc(("DRAIN '%s': Initiating draining of pre-buffered data...\n", pStreamEx->Core.szName));
2821 pStreamEx->Out.enmPlayState = DRVAUDIOPLAYSTATE_PREBUF_COMMITTING;
2822 pStreamEx->fStatus |= PDMAUDIOSTREAM_STS_PENDING_DISABLE;
2823 PDMAUDIOSTREAM_STS_ASSERT_VALID(pStreamEx->fStatus);
2824 rc = VINF_SUCCESS;
2825 break;
2826 }
2827 RT_FALL_THROUGH();
2828 case DRVAUDIOPLAYSTATE_NOPLAY:
2829 case DRVAUDIOPLAYSTATE_PREBUF_SWITCHING:
2830 case DRVAUDIOPLAYSTATE_PREBUF_OVERDUE:
2831 LogFunc(("DRAIN '%s': Nothing to drain (enmPlayState=%s)\n",
2832 pStreamEx->Core.szName, drvAudioPlayStateName(pStreamEx->Out.enmPlayState)));
2833 rc = drvAudioStreamControlInternalBackend(pThis, pStreamEx, PDMAUDIOSTREAMCMD_DISABLE);
2834 AssertRC(rc);
2835 drvAudioStreamResetOnDisable(pStreamEx);
2836 break;
2837
2838 case DRVAUDIOPLAYSTATE_PLAY:
2839 case DRVAUDIOPLAYSTATE_PLAY_PREBUF:
2840 LogFunc(("DRAIN '%s': Initiating backend draining (enmPlayState=%s -> NOPLAY) ...\n",
2841 pStreamEx->Core.szName, drvAudioPlayStateName(pStreamEx->Out.enmPlayState)));
2842 pStreamEx->Out.enmPlayState = DRVAUDIOPLAYSTATE_NOPLAY;
2843 rc = drvAudioStreamControlInternalBackend(pThis, pStreamEx, PDMAUDIOSTREAMCMD_DRAIN);
2844 if (RT_SUCCESS(rc))
2845 {
2846 pStreamEx->fStatus |= PDMAUDIOSTREAM_STS_PENDING_DISABLE;
2847 PDMAUDIOSTREAM_STS_ASSERT_VALID(pStreamEx->fStatus);
2848 }
2849 else
2850 {
2851 LogFunc(("DRAIN '%s': Backend DRAIN failed with %Rrc, disabling the stream instead...\n",
2852 pStreamEx->Core.szName, rc));
2853 rc = drvAudioStreamControlInternalBackend(pThis, pStreamEx, PDMAUDIOSTREAMCMD_DISABLE);
2854 AssertRC(rc);
2855 drvAudioStreamResetOnDisable(pStreamEx);
2856 }
2857 break;
2858
2859 case DRVAUDIOPLAYSTATE_PREBUF_COMMITTING:
2860 LogFunc(("DRAIN '%s': Initiating draining of pre-buffered data (already committing)...\n",
2861 pStreamEx->Core.szName));
2862 pStreamEx->fStatus |= PDMAUDIOSTREAM_STS_PENDING_DISABLE;
2863 PDMAUDIOSTREAM_STS_ASSERT_VALID(pStreamEx->fStatus);
2864 rc = VINF_SUCCESS;
2865 break;
2866
2867 /* no default */
2868 case DRVAUDIOPLAYSTATE_INVALID:
2869 case DRVAUDIOPLAYSTATE_END:
2870 AssertFailedBreak();
2871 }
2872 }
2873 break;
2874
2875 default:
2876 rc = VERR_NOT_IMPLEMENTED;
2877 break;
2878 }
2879
2880 if (RT_FAILURE(rc))
2881 LogFunc(("[%s] Failed with %Rrc\n", pStreamEx->Core.szName, rc));
2882
2883 return rc;
2884}
2885
2886
2887/**
2888 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnStreamControl}
2889 */
2890static DECLCALLBACK(int) drvAudioStreamControl(PPDMIAUDIOCONNECTOR pInterface,
2891 PPDMAUDIOSTREAM pStream, PDMAUDIOSTREAMCMD enmStreamCmd)
2892{
2893 PDRVAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVAUDIO, IAudioConnector);
2894 AssertPtr(pThis);
2895
2896 /** @todo r=bird: why? It's not documented to ignore NULL streams. */
2897 if (!pStream)
2898 return VINF_SUCCESS;
2899 PDRVAUDIOSTREAM pStreamEx = (PDRVAUDIOSTREAM)pStream;
2900 AssertPtrReturn(pStreamEx, VERR_INVALID_POINTER);
2901 AssertReturn(pStreamEx->Core.uMagic == PDMAUDIOSTREAM_MAGIC, VERR_INVALID_MAGIC);
2902 AssertReturn(pStreamEx->uMagic == DRVAUDIOSTREAM_MAGIC, VERR_INVALID_MAGIC);
2903
2904 int rc = RTCritSectEnter(&pStreamEx->Core.CritSect);
2905 AssertRCReturn(rc, rc);
2906
2907 LogFlowFunc(("[%s] enmStreamCmd=%s\n", pStream->szName, PDMAudioStrmCmdGetName(enmStreamCmd)));
2908
2909 rc = drvAudioStreamControlInternal(pThis, pStreamEx, enmStreamCmd);
2910
2911 RTCritSectLeave(&pStreamEx->Core.CritSect);
2912 return rc;
2913}
2914
2915
2916/**
2917 * Copy data to the pre-buffer, ring-buffer style.
2918 *
2919 * The @a cbMax parameter is almost always set to the threshold size, the
2920 * exception is when commiting the buffer and we want to top it off to reduce
2921 * the number of transfers to the backend (the first transfer may start
2922 * playback, so more data is better).
2923 */
2924static int drvAudioStreamPreBuffer(PDRVAUDIOSTREAM pStreamEx, const uint8_t *pbBuf, uint32_t cbBuf, uint32_t cbMax)
2925{
2926 uint32_t const cbAlloc = pStreamEx->Out.cbPreBufAlloc;
2927 AssertReturn(cbAlloc >= cbMax, VERR_INTERNAL_ERROR_3);
2928 AssertReturn(cbAlloc >= 8, VERR_INTERNAL_ERROR_4);
2929 AssertReturn(cbMax >= 8, VERR_INTERNAL_ERROR_5);
2930
2931 uint32_t offRead = pStreamEx->Out.offPreBuf;
2932 uint32_t cbCur = pStreamEx->Out.cbPreBuffered;
2933 AssertStmt(offRead < cbAlloc, offRead %= cbAlloc);
2934 AssertStmt(cbCur <= cbMax, offRead = (offRead + cbCur - cbMax) % cbAlloc; cbCur = cbMax);
2935
2936 /*
2937 * First chunk.
2938 */
2939 uint32_t offWrite = (offRead + cbCur) % cbAlloc;
2940 uint32_t cbToCopy = RT_MIN(cbAlloc - offWrite, cbBuf);
2941 memcpy(&pStreamEx->Out.pbPreBuf[offWrite], pbBuf, cbToCopy);
2942
2943 /* Advance. */
2944 offWrite = (offWrite + cbToCopy) % cbAlloc;
2945 for (;;)
2946 {
2947 pbBuf += cbToCopy;
2948 cbCur += cbToCopy;
2949 if (cbCur > cbMax)
2950 offRead = (offRead + cbCur - cbMax) % cbAlloc;
2951 cbBuf -= cbToCopy;
2952 if (!cbBuf)
2953 break;
2954
2955 /*
2956 * Second+ chunk, from the start of the buffer.
2957 *
2958 * Note! It is assumed very unlikely that we will ever see a cbBuf larger than
2959 * cbMax, so we don't waste space on clipping cbBuf here (can happen with
2960 * custom pre-buffer sizes).
2961 */
2962 Assert(offWrite == 0);
2963 cbToCopy = RT_MIN(cbAlloc, cbBuf);
2964 memcpy(pStreamEx->Out.pbPreBuf, pbBuf, cbToCopy);
2965 }
2966
2967 /*
2968 * Update the pre-buffering size and position.
2969 */
2970 pStreamEx->Out.cbPreBuffered = RT_MIN(cbCur, cbMax);
2971 pStreamEx->Out.offPreBuf = offRead;
2972 return VINF_SUCCESS;
2973}
2974
2975
2976/**
2977 * Worker for drvAudioStreamPlay() and drvAudioStreamPreBufComitting().
2978 *
2979 * Caller owns the lock.
2980 */
2981static int drvAudioStreamPlayLocked(PDRVAUDIO pThis, PDRVAUDIOSTREAM pStreamEx,
2982 const uint8_t *pbBuf, uint32_t cbBuf, uint32_t *pcbWritten)
2983{
2984 Log3Func(("%s: @%#RX64: cbBuf=%#x\n", pStreamEx->Core.szName, pStreamEx->offInternal, cbBuf));
2985
2986 uint32_t cbWritable = pThis->pHostDrvAudio->pfnStreamGetWritable(pThis->pHostDrvAudio, pStreamEx->pBackend);
2987 pStreamEx->Out.Stats.cbBackendWritableBefore = cbWritable;
2988
2989 uint32_t cbWritten = 0;
2990 int rc = VINF_SUCCESS;
2991 uint8_t const cbFrame = PDMAudioPropsFrameSize(&pStreamEx->Core.Props);
2992 while (cbBuf >= cbFrame && cbWritable >= cbFrame)
2993 {
2994 uint32_t const cbToWrite = PDMAudioPropsFloorBytesToFrame(&pStreamEx->Core.Props, RT_MIN(cbBuf, cbWritable));
2995 uint32_t cbWrittenNow = 0;
2996 rc = pThis->pHostDrvAudio->pfnStreamPlay(pThis->pHostDrvAudio, pStreamEx->pBackend, pbBuf, cbToWrite, &cbWrittenNow);
2997 if (RT_SUCCESS(rc))
2998 {
2999 if (cbWrittenNow != cbToWrite)
3000 Log3Func(("%s: @%#RX64: Wrote fewer bytes than requested: %#x, requested %#x\n",
3001 pStreamEx->Core.szName, pStreamEx->offInternal, cbWrittenNow, cbToWrite));
3002#ifdef DEBUG_bird
3003 Assert(cbWrittenNow == cbToWrite);
3004#endif
3005 AssertStmt(cbWrittenNow <= cbToWrite, cbWrittenNow = cbToWrite);
3006 cbWritten += cbWrittenNow;
3007 cbBuf -= cbWrittenNow;
3008 pbBuf += cbWrittenNow;
3009 pStreamEx->offInternal += cbWrittenNow;
3010 }
3011 else
3012 {
3013 *pcbWritten = cbWritten;
3014 LogFunc(("%s: @%#RX64: pfnStreamPlay failed writing %#x bytes (%#x previous written, %#x writable): %Rrc\n",
3015 pStreamEx->Core.szName, pStreamEx->offInternal, cbToWrite, cbWritten, cbWritable, rc));
3016 return cbWritten ? VINF_SUCCESS : rc;
3017 }
3018
3019 cbWritable = pThis->pHostDrvAudio->pfnStreamGetWritable(pThis->pHostDrvAudio, pStreamEx->pBackend);
3020 }
3021
3022 *pcbWritten = cbWritten;
3023 pStreamEx->Out.Stats.cbBackendWritableAfter = cbWritable;
3024 if (cbWritten)
3025 pStreamEx->nsLastPlayedCaptured = RTTimeNanoTS();
3026
3027 Log3Func(("%s: @%#RX64: Wrote %#x bytes (%#x bytes left)\n", pStreamEx->Core.szName, pStreamEx->offInternal, cbWritten, cbBuf));
3028 return rc;
3029}
3030
3031
3032/**
3033 * Worker for drvAudioStreamPlay() and drvAudioStreamPreBufComitting().
3034 */
3035static int drvAudioStreamPlayToPreBuffer(PDRVAUDIOSTREAM pStreamEx, const void *pvBuf, uint32_t cbBuf, uint32_t cbMax,
3036 uint32_t *pcbWritten)
3037{
3038 int rc = drvAudioStreamPreBuffer(pStreamEx, (uint8_t const *)pvBuf, cbBuf, cbMax);
3039 if (RT_SUCCESS(rc))
3040 {
3041 *pcbWritten = cbBuf;
3042 pStreamEx->offInternal += cbBuf;
3043 Log3Func(("[%s] Pre-buffering (%s): wrote %#x bytes => %#x bytes / %u%%\n",
3044 pStreamEx->Core.szName, drvAudioPlayStateName(pStreamEx->Out.enmPlayState), cbBuf, pStreamEx->Out.cbPreBuffered,
3045 pStreamEx->Out.cbPreBuffered * 100 / RT_MAX(pStreamEx->cbPreBufThreshold, 1)));
3046
3047 }
3048 else
3049 *pcbWritten = 0;
3050 return rc;
3051}
3052
3053
3054/**
3055 * Used when we're committing (transfering) the pre-buffered bytes to the
3056 * device.
3057 *
3058 * This is called both from drvAudioStreamPlay() and
3059 * drvAudioStreamIterateInternal().
3060 *
3061 * @returns VBox status code.
3062 * @param pThis Pointer to the DrvAudio instance data.
3063 * @param pStreamEx The stream to commit the pre-buffering for.
3064 * @param pbBuf Buffer with new bytes to write. Can be NULL when called
3065 * in the PENDING_DISABLE state from
3066 * drvAudioStreamIterateInternal().
3067 * @param cbBuf Number of new bytes. Can be zero.
3068 * @param pcbWritten Where to return the number of bytes written.
3069 *
3070 * @note Locking: Stream critsect and hot-plug in shared mode.
3071 */
3072static int drvAudioStreamPreBufComitting(PDRVAUDIO pThis, PDRVAUDIOSTREAM pStreamEx,
3073 const uint8_t *pbBuf, uint32_t cbBuf, uint32_t *pcbWritten)
3074{
3075 /*
3076 * First, top up the buffer with new data from pbBuf.
3077 */
3078 *pcbWritten = 0;
3079 if (cbBuf > 0)
3080 {
3081 uint32_t const cbToCopy = RT_MIN(pStreamEx->Out.cbPreBufAlloc - pStreamEx->Out.cbPreBuffered, cbBuf);
3082 if (cbToCopy > 0)
3083 {
3084 int rc = drvAudioStreamPlayToPreBuffer(pStreamEx, pbBuf, cbBuf, pStreamEx->Out.cbPreBufAlloc, pcbWritten);
3085 AssertRCReturn(rc, rc);
3086 pbBuf += cbToCopy;
3087 cbBuf -= cbToCopy;
3088 }
3089 }
3090
3091 AssertReturn(pThis->pHostDrvAudio, VERR_AUDIO_BACKEND_NOT_ATTACHED);
3092
3093 /*
3094 * Write the pre-buffered chunk.
3095 */
3096 int rc = VINF_SUCCESS;
3097 uint32_t const cbAlloc = pStreamEx->Out.cbPreBufAlloc;
3098 AssertReturn(cbAlloc > 0, VERR_INTERNAL_ERROR_2);
3099 uint32_t off = pStreamEx->Out.offPreBuf;
3100 AssertStmt(off < pStreamEx->Out.cbPreBufAlloc, off %= cbAlloc);
3101 uint32_t cbLeft = pStreamEx->Out.cbPreBuffered;
3102 while (cbLeft > 0)
3103 {
3104 uint32_t const cbToWrite = RT_MIN(cbAlloc - off, cbLeft);
3105 Assert(cbToWrite > 0);
3106
3107 uint32_t cbPreBufWritten = 0;
3108 rc = pThis->pHostDrvAudio->pfnStreamPlay(pThis->pHostDrvAudio, pStreamEx->pBackend, &pStreamEx->Out.pbPreBuf[off],
3109 cbToWrite, &cbPreBufWritten);
3110 AssertRCBreak(rc);
3111 if (!cbPreBufWritten)
3112 break;
3113 AssertStmt(cbPreBufWritten <= cbToWrite, cbPreBufWritten = cbToWrite);
3114 off = (off + cbPreBufWritten) % cbAlloc;
3115 cbLeft -= cbPreBufWritten;
3116 }
3117
3118 if (cbLeft == 0)
3119 {
3120 LogFunc(("@%#RX64: Wrote all %#x bytes of pre-buffered audio data. %s -> PLAY\n", pStreamEx->offInternal,
3121 pStreamEx->Out.cbPreBuffered, drvAudioPlayStateName(pStreamEx->Out.enmPlayState) ));
3122 pStreamEx->Out.cbPreBuffered = 0;
3123 pStreamEx->Out.offPreBuf = 0;
3124 pStreamEx->Out.enmPlayState = DRVAUDIOPLAYSTATE_PLAY;
3125
3126 if (cbBuf > 0)
3127 {
3128 uint32_t cbWritten2 = 0;
3129 rc = drvAudioStreamPlayLocked(pThis, pStreamEx, pbBuf, cbBuf, &cbWritten2);
3130 if (RT_SUCCESS(rc))
3131 *pcbWritten += cbWritten2;
3132 }
3133 else
3134 pStreamEx->nsLastPlayedCaptured = RTTimeNanoTS();
3135 }
3136 else
3137 {
3138 if (cbLeft != pStreamEx->Out.cbPreBuffered)
3139 pStreamEx->nsLastPlayedCaptured = RTTimeNanoTS();
3140
3141 LogRel2(("Audio: @%#RX64: Stream '%s' pre-buffering commit problem: wrote %#x out of %#x + %#x - rc=%Rrc *pcbWritten=%#x %s -> PREBUF_COMMITTING\n",
3142 pStreamEx->offInternal, pStreamEx->Core.szName, pStreamEx->Out.cbPreBuffered - cbLeft,
3143 pStreamEx->Out.cbPreBuffered, cbBuf, rc, *pcbWritten, drvAudioPlayStateName(pStreamEx->Out.enmPlayState) ));
3144 AssertMsg( pStreamEx->Out.enmPlayState == DRVAUDIOPLAYSTATE_PREBUF_COMMITTING
3145 || pStreamEx->Out.enmPlayState == DRVAUDIOPLAYSTATE_PREBUF
3146 || RT_FAILURE(rc),
3147 ("Buggy host driver buffer reporting? cbLeft=%#x cbPreBuffered=%#x enmPlayState=%s\n",
3148 cbLeft, pStreamEx->Out.cbPreBuffered, drvAudioPlayStateName(pStreamEx->Out.enmPlayState) ));
3149
3150 pStreamEx->Out.cbPreBuffered = cbLeft;
3151 pStreamEx->Out.offPreBuf = off;
3152 pStreamEx->Out.enmPlayState = DRVAUDIOPLAYSTATE_PREBUF_COMMITTING;
3153 }
3154
3155 return *pcbWritten ? VINF_SUCCESS : rc;
3156}
3157
3158
3159/**
3160 * Does one iteration of an audio stream.
3161 *
3162 * This function gives the backend the chance of iterating / altering data and
3163 * does the actual mixing between the guest <-> host mixing buffers.
3164 *
3165 * @returns VBox status code.
3166 * @param pThis Pointer to driver instance.
3167 * @param pStreamEx Stream to iterate.
3168 */
3169static int drvAudioStreamIterateInternal(PDRVAUDIO pThis, PDRVAUDIOSTREAM pStreamEx)
3170{
3171 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
3172
3173#ifdef LOG_ENABLED
3174 char szStreamSts[DRVAUDIO_STATUS_STR_MAX];
3175#endif
3176 Log3Func(("[%s] fStatus=%s\n", pStreamEx->Core.szName, drvAudioStreamStatusToStr(szStreamSts, pStreamEx->fStatus)));
3177
3178 /* Not enabled or paused? Skip iteration. */
3179 if ((pStreamEx->fStatus & (PDMAUDIOSTREAM_STS_ENABLED | PDMAUDIOSTREAM_STS_PAUSED)) != PDMAUDIOSTREAM_STS_ENABLED)
3180 return VINF_SUCCESS;
3181
3182 /*
3183 * Pending disable is really what we're here for.
3184 *
3185 * This only happens to output streams. We ASSUME the caller (MixerBuffer)
3186 * implements a timeout on the draining, so we skip that here.
3187 */
3188 if (!(pStreamEx->fStatus & PDMAUDIOSTREAM_STS_PENDING_DISABLE))
3189 { /* likely until we get to the end of the stream at least. */ }
3190 else
3191 {
3192 AssertReturn(pStreamEx->Core.enmDir == PDMAUDIODIR_OUT, VINF_SUCCESS);
3193 RTCritSectRwEnterShared(&pThis->CritSectHotPlug);
3194
3195 /*
3196 * Move pre-buffered samples to the backend.
3197 */
3198 if (pStreamEx->Out.enmPlayState == DRVAUDIOPLAYSTATE_PREBUF_COMMITTING)
3199 {
3200 if (pStreamEx->Out.cbPreBuffered > 0)
3201 {
3202 uint32_t cbIgnored = 0;
3203 drvAudioStreamPreBufComitting(pThis, pStreamEx, NULL, 0, &cbIgnored);
3204 Log3Func(("Stream '%s': Transferred %#x bytes\n", pStreamEx->Core.szName, cbIgnored));
3205 }
3206 if (pStreamEx->Out.cbPreBuffered == 0)
3207 {
3208 Log3Func(("Stream '%s': No more pre-buffered data -> NOPLAY + backend DRAIN\n", pStreamEx->Core.szName));
3209 pStreamEx->Out.enmPlayState = DRVAUDIOPLAYSTATE_NOPLAY;
3210
3211 int rc = drvAudioStreamControlInternalBackend(pThis, pStreamEx, PDMAUDIOSTREAMCMD_DRAIN);
3212 if (RT_FAILURE(rc))
3213 {
3214 LogFunc(("Stream '%s': Backend DRAIN failed with %Rrc, disabling the stream instead...\n",
3215 pStreamEx->Core.szName, rc));
3216 rc = drvAudioStreamControlInternalBackend(pThis, pStreamEx, PDMAUDIOSTREAMCMD_DISABLE);
3217 AssertRC(rc);
3218 drvAudioStreamResetOnDisable(pStreamEx);
3219 }
3220 }
3221 }
3222 else
3223 Assert(pStreamEx->Out.enmPlayState == DRVAUDIOPLAYSTATE_NOPLAY);
3224
3225 /*
3226 * Check the backend status to see if it's still draining and to
3227 * update our status when it stops doing so.
3228 */
3229 PDMHOSTAUDIOSTREAMSTATE const enmBackendState = drvAudioStreamGetBackendState(pThis, pStreamEx);
3230 if (enmBackendState == PDMHOSTAUDIOSTREAMSTATE_DRAINING)
3231 {
3232 uint32_t cbIgnored = 0;
3233 pThis->pHostDrvAudio->pfnStreamPlay(pThis->pHostDrvAudio, pStreamEx->pBackend, NULL, 0, &cbIgnored);
3234 }
3235 else
3236 {
3237 LogFunc(("Stream '%s': Backend finished draining.\n", pStreamEx->Core.szName));
3238 drvAudioStreamResetOnDisable(pStreamEx);
3239 }
3240
3241 RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
3242 }
3243
3244 /* Update timestamps. */
3245 pStreamEx->nsLastIterated = RTTimeNanoTS();
3246
3247 return VINF_SUCCESS; /** @todo r=bird: What can the caller do with an error status here? */
3248}
3249
3250
3251/**
3252 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnStreamIterate}
3253 */
3254static DECLCALLBACK(int) drvAudioStreamIterate(PPDMIAUDIOCONNECTOR pInterface, PPDMAUDIOSTREAM pStream)
3255{
3256 PDRVAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVAUDIO, IAudioConnector);
3257 AssertPtr(pThis);
3258 PDRVAUDIOSTREAM pStreamEx = (PDRVAUDIOSTREAM)pStream;
3259 AssertPtrReturn(pStreamEx, VERR_INVALID_POINTER);
3260 AssertReturn(pStreamEx->Core.uMagic == PDMAUDIOSTREAM_MAGIC, VERR_INVALID_MAGIC);
3261 AssertReturn(pStreamEx->uMagic == DRVAUDIOSTREAM_MAGIC, VERR_INVALID_MAGIC);
3262
3263 int rc = RTCritSectEnter(&pStreamEx->Core.CritSect);
3264 AssertRCReturn(rc, rc);
3265
3266 rc = drvAudioStreamIterateInternal(pThis, pStreamEx);
3267
3268 RTCritSectLeave(&pStreamEx->Core.CritSect);
3269
3270 if (RT_FAILURE(rc))
3271 LogFlowFuncLeaveRC(rc);
3272 return rc;
3273}
3274
3275
3276/**
3277 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnStreamGetState}
3278 */
3279static DECLCALLBACK(PDMAUDIOSTREAMSTATE) drvAudioStreamGetState(PPDMIAUDIOCONNECTOR pInterface, PPDMAUDIOSTREAM pStream)
3280{
3281 PDRVAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVAUDIO, IAudioConnector);
3282 PDRVAUDIOSTREAM pStreamEx = (PDRVAUDIOSTREAM)pStream;
3283 AssertPtrReturn(pStreamEx, PDMAUDIOSTREAMSTATE_INVALID);
3284 AssertReturn(pStreamEx->Core.uMagic == PDMAUDIOSTREAM_MAGIC, PDMAUDIOSTREAMSTATE_INVALID);
3285 AssertReturn(pStreamEx->uMagic == DRVAUDIOSTREAM_MAGIC, PDMAUDIOSTREAMSTATE_INVALID);
3286
3287 /*
3288 * Get the status mask.
3289 */
3290 int rc = RTCritSectEnter(&pStreamEx->Core.CritSect);
3291 AssertRCReturn(rc, PDMAUDIOSTREAMSTATE_INVALID);
3292 RTCritSectRwEnterShared(&pThis->CritSectHotPlug);
3293
3294 PDMHOSTAUDIOSTREAMSTATE const enmBackendState = drvAudioStreamGetBackendStateAndProcessChanges(pThis, pStreamEx);
3295 uint32_t const fStrmStatus = pStreamEx->fStatus;
3296 PDMAUDIODIR const enmDir = pStreamEx->Guest.Cfg.enmDir;
3297 Assert(enmDir == PDMAUDIODIR_IN || enmDir == PDMAUDIODIR_OUT);
3298
3299 RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
3300 RTCritSectLeave(&pStreamEx->Core.CritSect);
3301
3302 /*
3303 * Translate it to state enum value.
3304 */
3305 PDMAUDIOSTREAMSTATE enmState;
3306 if (!(fStrmStatus & PDMAUDIOSTREAM_STS_NEED_REINIT))
3307 {
3308 if (fStrmStatus & PDMAUDIOSTREAM_STS_BACKEND_CREATED)
3309 {
3310 if ( (fStrmStatus & PDMAUDIOSTREAM_STS_ENABLED)
3311 && (enmDir == PDMAUDIODIR_IN ? pThis->In.fEnabled : pThis->Out.fEnabled)
3312 && ( enmBackendState == PDMHOSTAUDIOSTREAMSTATE_OKAY
3313 || enmBackendState == PDMHOSTAUDIOSTREAMSTATE_DRAINING
3314 || enmBackendState == PDMHOSTAUDIOSTREAMSTATE_INITIALIZING ))
3315 enmState = enmDir == PDMAUDIODIR_IN ? PDMAUDIOSTREAMSTATE_ENABLED_READABLE : PDMAUDIOSTREAMSTATE_ENABLED_WRITABLE;
3316 else
3317 enmState = PDMAUDIOSTREAMSTATE_INACTIVE;
3318 }
3319 else
3320 enmState = PDMAUDIOSTREAMSTATE_NOT_WORKING;
3321 }
3322 else
3323 enmState = PDMAUDIOSTREAMSTATE_NEED_REINIT;
3324
3325#ifdef LOG_ENABLED
3326 char szStreamSts[DRVAUDIO_STATUS_STR_MAX];
3327#endif
3328 Log3Func(("[%s] returns %s (status: %s)\n", pStreamEx->Core.szName, PDMAudioStreamStateGetName(enmState),
3329 drvAudioStreamStatusToStr(szStreamSts, fStrmStatus)));
3330 return enmState;
3331}
3332
3333
3334/**
3335 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnStreamGetWritable}
3336 */
3337static DECLCALLBACK(uint32_t) drvAudioStreamGetWritable(PPDMIAUDIOCONNECTOR pInterface, PPDMAUDIOSTREAM pStream)
3338{
3339 PDRVAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVAUDIO, IAudioConnector);
3340 AssertPtr(pThis);
3341 PDRVAUDIOSTREAM pStreamEx = (PDRVAUDIOSTREAM)pStream;
3342 AssertPtrReturn(pStreamEx, 0);
3343 AssertReturn(pStreamEx->Core.uMagic == PDMAUDIOSTREAM_MAGIC, 0);
3344 AssertReturn(pStreamEx->uMagic == DRVAUDIOSTREAM_MAGIC, 0);
3345 AssertMsgReturn(pStreamEx->Core.enmDir == PDMAUDIODIR_OUT, ("Can't write to a non-output stream\n"), 0);
3346
3347 int rc = RTCritSectEnter(&pStreamEx->Core.CritSect);
3348 AssertRCReturn(rc, 0);
3349 RTCritSectRwEnterShared(&pThis->CritSectHotPlug);
3350
3351 /*
3352 * Use the playback and backend states to determin how much can be written, if anything.
3353 */
3354 uint32_t cbWritable = 0;
3355 DRVAUDIOPLAYSTATE const enmPlayMode = pStreamEx->Out.enmPlayState;
3356 PDMHOSTAUDIOSTREAMSTATE const enmBackendState = drvAudioStreamGetBackendState(pThis, pStreamEx);
3357 if ( PDMAudioStrmStatusCanWrite(pStreamEx->fStatus)
3358 && pThis->pHostDrvAudio != NULL
3359 && enmBackendState != PDMHOSTAUDIOSTREAMSTATE_DRAINING)
3360 {
3361 switch (enmPlayMode)
3362 {
3363 /*
3364 * Whatever the backend can hold.
3365 */
3366 case DRVAUDIOPLAYSTATE_PLAY:
3367 case DRVAUDIOPLAYSTATE_PLAY_PREBUF:
3368 Assert(pStreamEx->fStatus & PDMAUDIOSTREAM_STS_BACKEND_READY);
3369 Assert(enmBackendState == PDMHOSTAUDIOSTREAMSTATE_OKAY /* potential unplug race */);
3370 cbWritable = pThis->pHostDrvAudio->pfnStreamGetWritable(pThis->pHostDrvAudio, pStreamEx->pBackend);
3371 break;
3372
3373 /*
3374 * Whatever we've got of available space in the pre-buffer.
3375 * Note! For the last round when we pass the pre-buffering threshold, we may
3376 * report fewer bytes than what a DMA timer period for the guest device
3377 * typically produces, however that should be transfered in the following
3378 * round that goes directly to the backend buffer.
3379 */
3380 case DRVAUDIOPLAYSTATE_PREBUF:
3381 cbWritable = pStreamEx->Out.cbPreBufAlloc - pStreamEx->Out.cbPreBuffered;
3382 if (!cbWritable)
3383 cbWritable = PDMAudioPropsFramesToBytes(&pStreamEx->Core.Props, 2);
3384 break;
3385
3386 /*
3387 * These are slightly more problematic and can go wrong if the pre-buffer is
3388 * manually configured to be smaller than the output of a typeical DMA timer
3389 * period for the guest device. So, to overcompensate, we just report back
3390 * the backend buffer size (the pre-buffer is circular, so no overflow issue).
3391 */
3392 case DRVAUDIOPLAYSTATE_PREBUF_OVERDUE:
3393 case DRVAUDIOPLAYSTATE_PREBUF_SWITCHING:
3394 cbWritable = PDMAudioPropsFramesToBytes(&pStreamEx->Core.Props,
3395 RT_MAX(pStreamEx->Host.Cfg.Backend.cFramesBufferSize,
3396 pStreamEx->Host.Cfg.Backend.cFramesPreBuffering));
3397 break;
3398
3399 case DRVAUDIOPLAYSTATE_PREBUF_COMMITTING:
3400 {
3401 /* Buggy backend: We weren't able to copy all the pre-buffered data to it
3402 when reaching the threshold. Try escape this situation, or at least
3403 keep the extra buffering to a minimum. We must try write something
3404 as long as there is space for it, as we need the pfnStreamWrite call
3405 to move the data. */
3406 Assert(pStreamEx->fStatus & PDMAUDIOSTREAM_STS_BACKEND_READY);
3407 Assert(enmBackendState == PDMHOSTAUDIOSTREAMSTATE_OKAY /* potential unplug race */);
3408 uint32_t const cbMin = PDMAudioPropsFramesToBytes(&pStreamEx->Core.Props, 8);
3409 cbWritable = pThis->pHostDrvAudio->pfnStreamGetWritable(pThis->pHostDrvAudio, pStreamEx->pBackend);
3410 if (cbWritable >= pStreamEx->Out.cbPreBuffered + cbMin)
3411 cbWritable -= pStreamEx->Out.cbPreBuffered + cbMin / 2;
3412 else
3413 cbWritable = RT_MIN(cbMin, pStreamEx->Out.cbPreBufAlloc - pStreamEx->Out.cbPreBuffered);
3414 AssertLogRel(cbWritable);
3415 break;
3416 }
3417
3418 case DRVAUDIOPLAYSTATE_NOPLAY:
3419 break;
3420 case DRVAUDIOPLAYSTATE_INVALID:
3421 case DRVAUDIOPLAYSTATE_END:
3422 AssertFailed();
3423 break;
3424 }
3425
3426 /* Make sure to align the writable size to the host's frame size. */
3427 cbWritable = PDMAudioPropsFloorBytesToFrame(&pStreamEx->Core.Props, cbWritable);
3428 }
3429
3430 RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
3431 RTCritSectLeave(&pStreamEx->Core.CritSect);
3432 Log3Func(("[%s] cbWritable=%#RX32 (%RU64ms) enmPlayMode=%s enmBackendState=%s\n",
3433 pStreamEx->Core.szName, cbWritable, PDMAudioPropsBytesToMilli(&pStreamEx->Core.Props, cbWritable),
3434 drvAudioPlayStateName(enmPlayMode), PDMHostAudioStreamStateGetName(enmBackendState) ));
3435 return cbWritable;
3436}
3437
3438
3439/**
3440 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnStreamPlay}
3441 */
3442static DECLCALLBACK(int) drvAudioStreamPlay(PPDMIAUDIOCONNECTOR pInterface, PPDMAUDIOSTREAM pStream,
3443 const void *pvBuf, uint32_t cbBuf, uint32_t *pcbWritten)
3444{
3445 PDRVAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVAUDIO, IAudioConnector);
3446 AssertPtr(pThis);
3447
3448 /*
3449 * Check input and sanity.
3450 */
3451 AssertPtrReturn(pInterface, VERR_INVALID_POINTER);
3452 PDRVAUDIOSTREAM pStreamEx = (PDRVAUDIOSTREAM)pStream;
3453 AssertPtrReturn(pStreamEx, VERR_INVALID_POINTER);
3454 AssertPtrReturn(pvBuf, VERR_INVALID_POINTER);
3455 AssertReturn(cbBuf, VERR_INVALID_PARAMETER);
3456 uint32_t uTmp;
3457 if (pcbWritten)
3458 AssertPtrReturn(pcbWritten, VERR_INVALID_PARAMETER);
3459 else
3460 pcbWritten = &uTmp;
3461
3462 AssertReturn(pStreamEx->Core.uMagic == PDMAUDIOSTREAM_MAGIC, VERR_INVALID_MAGIC);
3463 AssertReturn(pStreamEx->uMagic == DRVAUDIOSTREAM_MAGIC, VERR_INVALID_MAGIC);
3464 AssertMsgReturn(pStreamEx->Core.enmDir == PDMAUDIODIR_OUT,
3465 ("Stream '%s' is not an output stream and therefore cannot be written to (direction is '%s')\n",
3466 pStreamEx->Core.szName, PDMAudioDirGetName(pStreamEx->Core.enmDir)), VERR_ACCESS_DENIED);
3467
3468 AssertMsg(PDMAudioPropsIsSizeAligned(&pStreamEx->Core.Props, cbBuf),
3469 ("Stream '%s' got a non-frame-aligned write (%#RX32 bytes)\n", pStreamEx->Core.szName, cbBuf));
3470
3471 int rc = RTCritSectEnter(&pStreamEx->Core.CritSect);
3472 AssertRCReturn(rc, rc);
3473
3474 /*
3475 * First check that we can write to the stream, and if not,
3476 * whether to just drop the input into the bit bucket.
3477 */
3478 if (PDMAudioStrmStatusIsReady(pStreamEx->fStatus))
3479 {
3480 RTCritSectRwEnterShared(&pThis->CritSectHotPlug);
3481 if ( pThis->Out.fEnabled /* (see @bugref{9882}) */
3482 && pThis->pHostDrvAudio != NULL)
3483 {
3484 /*
3485 * Get the backend state and process changes to it since last time we checked.
3486 */
3487 PDMHOSTAUDIOSTREAMSTATE const enmBackendState = drvAudioStreamGetBackendStateAndProcessChanges(pThis, pStreamEx);
3488
3489 /*
3490 * Do the transfering.
3491 */
3492 switch (pStreamEx->Out.enmPlayState)
3493 {
3494 case DRVAUDIOPLAYSTATE_PLAY:
3495 Assert(pStreamEx->fStatus & PDMAUDIOSTREAM_STS_BACKEND_READY);
3496 Assert(enmBackendState == PDMHOSTAUDIOSTREAMSTATE_OKAY);
3497 rc = drvAudioStreamPlayLocked(pThis, pStreamEx, (uint8_t const *)pvBuf, cbBuf, pcbWritten);
3498 break;
3499
3500 case DRVAUDIOPLAYSTATE_PLAY_PREBUF:
3501 Assert(pStreamEx->fStatus & PDMAUDIOSTREAM_STS_BACKEND_READY);
3502 Assert(enmBackendState == PDMHOSTAUDIOSTREAMSTATE_OKAY);
3503 rc = drvAudioStreamPlayLocked(pThis, pStreamEx, (uint8_t const *)pvBuf, cbBuf, pcbWritten);
3504 drvAudioStreamPreBuffer(pStreamEx, (uint8_t const *)pvBuf, *pcbWritten, pStreamEx->cbPreBufThreshold);
3505 break;
3506
3507 case DRVAUDIOPLAYSTATE_PREBUF:
3508 if (cbBuf + pStreamEx->Out.cbPreBuffered < pStreamEx->cbPreBufThreshold)
3509 rc = drvAudioStreamPlayToPreBuffer(pStreamEx, pvBuf, cbBuf, pStreamEx->cbPreBufThreshold, pcbWritten);
3510 else if ( enmBackendState == PDMHOSTAUDIOSTREAMSTATE_OKAY
3511 && (pStreamEx->fStatus & PDMAUDIOSTREAM_STS_BACKEND_READY))
3512 {
3513 Log3Func(("[%s] Pre-buffering completing: cbBuf=%#x cbPreBuffered=%#x => %#x vs cbPreBufThreshold=%#x\n",
3514 pStreamEx->Core.szName, cbBuf, pStreamEx->Out.cbPreBuffered,
3515 cbBuf + pStreamEx->Out.cbPreBuffered, pStreamEx->cbPreBufThreshold));
3516 rc = drvAudioStreamPreBufComitting(pThis, pStreamEx, (uint8_t const *)pvBuf, cbBuf, pcbWritten);
3517 }
3518 else
3519 {
3520 Log3Func(("[%s] Pre-buffering completing but device not ready: cbBuf=%#x cbPreBuffered=%#x => %#x vs cbPreBufThreshold=%#x; PREBUF -> PREBUF_OVERDUE\n",
3521 pStreamEx->Core.szName, cbBuf, pStreamEx->Out.cbPreBuffered,
3522 cbBuf + pStreamEx->Out.cbPreBuffered, pStreamEx->cbPreBufThreshold));
3523 pStreamEx->Out.enmPlayState = DRVAUDIOPLAYSTATE_PREBUF_OVERDUE;
3524 rc = drvAudioStreamPlayToPreBuffer(pStreamEx, pvBuf, cbBuf, pStreamEx->cbPreBufThreshold, pcbWritten);
3525 }
3526 break;
3527
3528 case DRVAUDIOPLAYSTATE_PREBUF_OVERDUE:
3529 Assert( !(pStreamEx->fStatus & PDMAUDIOSTREAM_STS_BACKEND_READY)
3530 || enmBackendState != PDMHOSTAUDIOSTREAMSTATE_OKAY);
3531 RT_FALL_THRU();
3532 case DRVAUDIOPLAYSTATE_PREBUF_SWITCHING:
3533 rc = drvAudioStreamPlayToPreBuffer(pStreamEx, pvBuf, cbBuf, pStreamEx->cbPreBufThreshold, pcbWritten);
3534 break;
3535
3536 case DRVAUDIOPLAYSTATE_PREBUF_COMMITTING:
3537 Assert(pStreamEx->fStatus & PDMAUDIOSTREAM_STS_BACKEND_READY);
3538 Assert(enmBackendState == PDMHOSTAUDIOSTREAMSTATE_OKAY);
3539 rc = drvAudioStreamPreBufComitting(pThis, pStreamEx, (uint8_t const *)pvBuf, cbBuf, pcbWritten);
3540 break;
3541
3542 case DRVAUDIOPLAYSTATE_NOPLAY:
3543 *pcbWritten = cbBuf;
3544 pStreamEx->offInternal += cbBuf;
3545 Log3Func(("[%s] Discarding the data, backend state: %s\n", pStreamEx->Core.szName,
3546 PDMHostAudioStreamStateGetName(enmBackendState) ));
3547 break;
3548
3549 default:
3550 *pcbWritten = cbBuf;
3551 AssertMsgFailedBreak(("%d; cbBuf=%#x\n", pStreamEx->Out.enmPlayState, cbBuf));
3552 }
3553
3554 if (!pThis->CfgOut.Dbg.fEnabled || RT_FAILURE(rc))
3555 { /* likely */ }
3556 else
3557 AudioHlpFileWrite(pStreamEx->Out.Dbg.pFilePlay, pvBuf, *pcbWritten, 0 /* fFlags */);
3558 }
3559 else
3560 {
3561 *pcbWritten = cbBuf;
3562 pStreamEx->offInternal += cbBuf;
3563 Log3Func(("[%s] Backend stream %s, discarding the data\n", pStreamEx->Core.szName,
3564 !pThis->Out.fEnabled ? "disabled" : !pThis->pHostDrvAudio ? "not attached" : "not ready yet"));
3565 }
3566 RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
3567 }
3568 else
3569 rc = VERR_AUDIO_STREAM_NOT_READY;
3570
3571 RTCritSectLeave(&pStreamEx->Core.CritSect);
3572 return rc;
3573}
3574
3575
3576/**
3577 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnStreamGetReadable}
3578 */
3579static DECLCALLBACK(uint32_t) drvAudioStreamGetReadable(PPDMIAUDIOCONNECTOR pInterface, PPDMAUDIOSTREAM pStream)
3580{
3581 PDRVAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVAUDIO, IAudioConnector);
3582 AssertPtr(pThis);
3583 PDRVAUDIOSTREAM pStreamEx = (PDRVAUDIOSTREAM)pStream;
3584 AssertPtrReturn(pStreamEx, 0);
3585 AssertReturn(pStreamEx->Core.uMagic == PDMAUDIOSTREAM_MAGIC, 0);
3586 AssertReturn(pStreamEx->uMagic == DRVAUDIOSTREAM_MAGIC, 0);
3587 AssertMsg(pStreamEx->Core.enmDir == PDMAUDIODIR_IN, ("Can't read from a non-input stream\n"));
3588
3589
3590 int rc = RTCritSectEnter(&pStreamEx->Core.CritSect);
3591 AssertRCReturn(rc, 0);
3592 RTCritSectRwEnterShared(&pThis->CritSectHotPlug);
3593
3594 /*
3595 * Use the capture state to determin how much can be written, if anything.
3596 */
3597 uint32_t cbReadable = 0;
3598 DRVAUDIOCAPTURESTATE const enmCaptureState = pStreamEx->In.enmCaptureState;
3599 PDMHOSTAUDIOSTREAMSTATE const enmBackendState = drvAudioStreamGetBackendState(pThis, pStreamEx); RT_NOREF(enmBackendState);
3600 if ( PDMAudioStrmStatusCanRead(pStreamEx->fStatus)
3601 && pThis->pHostDrvAudio != NULL)
3602 {
3603 switch (enmCaptureState)
3604 {
3605 /*
3606 * Whatever the backend has to offer when in capture mode.
3607 */
3608 case DRVAUDIOCAPTURESTATE_CAPTURING:
3609 Assert(pStreamEx->fStatus & PDMAUDIOSTREAM_STS_BACKEND_READY);
3610 Assert(enmBackendState == PDMHOSTAUDIOSTREAMSTATE_OKAY /* potential unplug race */);
3611 cbReadable = pThis->pHostDrvAudio->pfnStreamGetReadable(pThis->pHostDrvAudio, pStreamEx->pBackend);
3612 break;
3613
3614 /*
3615 * Same calculation as in drvAudioStreamCaptureSilence, only we cap it
3616 * at the pre-buffering threshold so we don't get into trouble when we
3617 * switch to capture mode between now and pfnStreamCapture.
3618 */
3619 case DRVAUDIOCAPTURESTATE_PREBUF:
3620 {
3621 uint64_t const cNsStream = RTTimeNanoTS() - pStreamEx->nsStarted;
3622 uint64_t const offCur = PDMAudioPropsNanoToBytes64(&pStreamEx->Core.Props, cNsStream);
3623 if (offCur > pStreamEx->offInternal)
3624 {
3625 uint64_t const cbUnread = offCur - pStreamEx->offInternal;
3626 cbReadable = (uint32_t)RT_MIN(pStreamEx->cbPreBufThreshold, cbUnread);
3627 }
3628 break;
3629 }
3630
3631 case DRVAUDIOCAPTURESTATE_NO_CAPTURE:
3632 break;
3633
3634 case DRVAUDIOCAPTURESTATE_INVALID:
3635 case DRVAUDIOCAPTURESTATE_END:
3636 AssertFailed();
3637 break;
3638 }
3639
3640 /* Make sure to align the readable size to the host's frame size. */
3641 cbReadable = PDMAudioPropsFloorBytesToFrame(&pStreamEx->Core.Props, cbReadable);
3642 }
3643
3644 RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
3645 RTCritSectLeave(&pStreamEx->Core.CritSect);
3646 Log3Func(("[%s] cbReadable=%#RX32 (%RU64ms) enmCaptureMode=%s enmBackendState=%s\n",
3647 pStreamEx->Core.szName, cbReadable, PDMAudioPropsBytesToMilli(&pStreamEx->Core.Props, cbReadable),
3648 drvAudioCaptureStateName(enmCaptureState), PDMHostAudioStreamStateGetName(enmBackendState) ));
3649 return cbReadable;
3650}
3651
3652
3653/**
3654 * Worker for drvAudioStreamCapture that returns silence.
3655 *
3656 * The amount of silence returned is a function of how long the stream has been
3657 * enabled.
3658 *
3659 * @returns VINF_SUCCESS
3660 * @param pStreamEx The stream to commit the pre-buffering for.
3661 * @param pbBuf The output buffer.
3662 * @param cbBuf The size of the output buffer.
3663 * @param pcbRead Where to return the number of bytes actually read.
3664 */
3665static int drvAudioStreamCaptureSilence(PDRVAUDIOSTREAM pStreamEx, uint8_t *pbBuf, uint32_t cbBuf, uint32_t *pcbRead)
3666{
3667 /** @todo Does not take paused time into account... */
3668 uint64_t const cNsStream = RTTimeNanoTS() - pStreamEx->nsStarted;
3669 uint64_t const offCur = PDMAudioPropsNanoToBytes64(&pStreamEx->Core.Props, cNsStream);
3670 if (offCur > pStreamEx->offInternal)
3671 {
3672 uint64_t const cbUnread = offCur - pStreamEx->offInternal;
3673 uint32_t const cbToClear = (uint32_t)RT_MIN(cbBuf, cbUnread);
3674 *pcbRead = cbToClear;
3675 pStreamEx->offInternal += cbToClear;
3676 cbBuf -= cbToClear;
3677 PDMAudioPropsClearBuffer(&pStreamEx->Core.Props, pbBuf, cbToClear,
3678 PDMAudioPropsBytesToFrames(&pStreamEx->Core.Props, cbToClear));
3679 }
3680 else
3681 *pcbRead = 0;
3682 Log4Func(("%s: @%#RX64: Read %#x bytes of silence (%#x bytes left)\n",
3683 pStreamEx->Core.szName, pStreamEx->offInternal, *pcbRead, cbBuf));
3684 return VINF_SUCCESS;
3685}
3686
3687
3688/**
3689 * Worker for drvAudioStreamCapture.
3690 */
3691static int drvAudioStreamCaptureLocked(PDRVAUDIO pThis, PDRVAUDIOSTREAM pStreamEx,
3692 uint8_t *pbBuf, uint32_t cbBuf, uint32_t *pcbRead)
3693{
3694 Log4Func(("%s: @%#RX64: cbBuf=%#x\n", pStreamEx->Core.szName, pStreamEx->offInternal, cbBuf));
3695
3696 uint32_t cbReadable = pThis->pHostDrvAudio->pfnStreamGetReadable(pThis->pHostDrvAudio, pStreamEx->pBackend);
3697 pStreamEx->In.Stats.cbBackendReadableBefore = cbReadable;
3698
3699 uint32_t cbRead = 0;
3700 int rc = VINF_SUCCESS;
3701 uint8_t const cbFrame = PDMAudioPropsFrameSize(&pStreamEx->Core.Props);
3702 while (cbBuf >= cbFrame && cbReadable >= cbFrame)
3703 {
3704 uint32_t const cbToRead = PDMAudioPropsFloorBytesToFrame(&pStreamEx->Core.Props, RT_MIN(cbBuf, cbReadable));
3705 uint32_t cbReadNow = 0;
3706 rc = pThis->pHostDrvAudio->pfnStreamCapture(pThis->pHostDrvAudio, pStreamEx->pBackend, pbBuf, cbToRead, &cbReadNow);
3707 if (RT_SUCCESS(rc))
3708 {
3709 if (cbReadNow != cbToRead)
3710 Log4Func(("%s: @%#RX64: Read fewer bytes than requested: %#x, requested %#x\n",
3711 pStreamEx->Core.szName, pStreamEx->offInternal, cbReadNow, cbToRead));
3712#ifdef DEBUG_bird
3713 Assert(cbReadNow == cbToRead);
3714#endif
3715 AssertStmt(cbReadNow <= cbToRead, cbReadNow = cbToRead);
3716 cbRead += cbReadNow;
3717 cbBuf -= cbReadNow;
3718 pbBuf += cbReadNow;
3719 pStreamEx->offInternal += cbReadNow;
3720 }
3721 else
3722 {
3723 *pcbRead = cbRead;
3724 LogFunc(("%s: @%#RX64: pfnStreamCapture failed read %#x bytes (%#x previous read, %#x readable): %Rrc\n",
3725 pStreamEx->Core.szName, pStreamEx->offInternal, cbToRead, cbRead, cbReadable, rc));
3726 return cbRead ? VINF_SUCCESS : rc;
3727 }
3728
3729 cbReadable = pThis->pHostDrvAudio->pfnStreamGetReadable(pThis->pHostDrvAudio, pStreamEx->pBackend);
3730 }
3731
3732 *pcbRead = cbRead;
3733 pStreamEx->In.Stats.cbBackendReadableAfter = cbReadable;
3734 if (cbRead)
3735 pStreamEx->nsLastPlayedCaptured = RTTimeNanoTS();
3736
3737 Log4Func(("%s: @%#RX64: Read %#x bytes (%#x bytes left)\n", pStreamEx->Core.szName, pStreamEx->offInternal, cbRead, cbBuf));
3738 return rc;
3739}
3740
3741
3742/**
3743 * @interface_method_impl{PDMIAUDIOCONNECTOR,pfnStreamCapture}
3744 */
3745static DECLCALLBACK(int) drvAudioStreamCapture(PPDMIAUDIOCONNECTOR pInterface, PPDMAUDIOSTREAM pStream,
3746 void *pvBuf, uint32_t cbBuf, uint32_t *pcbRead)
3747{
3748 PDRVAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVAUDIO, IAudioConnector);
3749 AssertPtr(pThis);
3750
3751 /*
3752 * Check input and sanity.
3753 */
3754 AssertPtrReturn(pInterface, VERR_INVALID_POINTER);
3755 PDRVAUDIOSTREAM pStreamEx = (PDRVAUDIOSTREAM)pStream;
3756 AssertPtrReturn(pStreamEx, VERR_INVALID_POINTER);
3757 AssertPtrReturn(pvBuf, VERR_INVALID_POINTER);
3758 AssertReturn(cbBuf, VERR_INVALID_PARAMETER);
3759 uint32_t uTmp;
3760 if (pcbRead)
3761 AssertPtrReturn(pcbRead, VERR_INVALID_PARAMETER);
3762 else
3763 pcbRead = &uTmp;
3764
3765 AssertReturn(pStreamEx->Core.uMagic == PDMAUDIOSTREAM_MAGIC, VERR_INVALID_MAGIC);
3766 AssertReturn(pStreamEx->uMagic == DRVAUDIOSTREAM_MAGIC, VERR_INVALID_MAGIC);
3767 AssertMsgReturn(pStreamEx->Core.enmDir == PDMAUDIODIR_IN,
3768 ("Stream '%s' is not an input stream and therefore cannot be read from (direction is '%s')\n",
3769 pStreamEx->Core.szName, PDMAudioDirGetName(pStreamEx->Core.enmDir)), VERR_ACCESS_DENIED);
3770
3771 AssertMsg(PDMAudioPropsIsSizeAligned(&pStreamEx->Core.Props, cbBuf),
3772 ("Stream '%s' got a non-frame-aligned write (%#RX32 bytes)\n", pStreamEx->Core.szName, cbBuf));
3773
3774 int rc = RTCritSectEnter(&pStreamEx->Core.CritSect);
3775 AssertRCReturn(rc, rc);
3776
3777 /*
3778 * First check that we can read from the stream, and if not,
3779 * whether to just drop the input into the bit bucket.
3780 */
3781 if (PDMAudioStrmStatusIsReady(pStreamEx->fStatus))
3782 {
3783 RTCritSectRwEnterShared(&pThis->CritSectHotPlug);
3784 if ( pThis->In.fEnabled /* (see @bugref{9882}) */
3785 && pThis->pHostDrvAudio != NULL)
3786 {
3787 /*
3788 * Get the backend state and process changes to it since last time we checked.
3789 */
3790 PDMHOSTAUDIOSTREAMSTATE const enmBackendState = drvAudioStreamGetBackendStateAndProcessChanges(pThis, pStreamEx);
3791
3792 /*
3793 * Do the transfering.
3794 */
3795 switch (pStreamEx->In.enmCaptureState)
3796 {
3797 case DRVAUDIOCAPTURESTATE_CAPTURING:
3798 Assert(pStreamEx->fStatus & PDMAUDIOSTREAM_STS_BACKEND_READY);
3799 Assert(enmBackendState == PDMHOSTAUDIOSTREAMSTATE_OKAY);
3800 rc = drvAudioStreamCaptureLocked(pThis, pStreamEx, (uint8_t *)pvBuf, cbBuf, pcbRead);
3801 break;
3802
3803 case DRVAUDIOCAPTURESTATE_PREBUF:
3804 if (enmBackendState == PDMHOSTAUDIOSTREAMSTATE_OKAY)
3805 {
3806 uint32_t const cbReadable = pThis->pHostDrvAudio->pfnStreamGetReadable(pThis->pHostDrvAudio,
3807 pStreamEx->pBackend);
3808 if (cbReadable >= pStreamEx->cbPreBufThreshold)
3809 {
3810 Log4Func(("[%s] Pre-buffering completed: cbReadable=%#x vs cbPreBufThreshold=%#x (cbBuf=%#x)\n",
3811 pStreamEx->Core.szName, cbReadable, pStreamEx->cbPreBufThreshold, cbBuf));
3812 pStreamEx->In.enmCaptureState = DRVAUDIOCAPTURESTATE_CAPTURING;
3813 rc = drvAudioStreamCaptureLocked(pThis, pStreamEx, (uint8_t *)pvBuf, cbBuf, pcbRead);
3814 break;
3815 }
3816 pStreamEx->In.Stats.cbBackendReadableBefore = cbReadable;
3817 pStreamEx->In.Stats.cbBackendReadableAfter = cbReadable;
3818 Log4Func(("[%s] Pre-buffering: Got %#x out of %#x\n",
3819 pStreamEx->Core.szName, cbReadable, pStreamEx->cbPreBufThreshold));
3820 }
3821 else
3822 Log4Func(("[%s] Pre-buffering: Backend status %s\n",
3823 pStreamEx->Core.szName, PDMHostAudioStreamStateGetName(enmBackendState) ));
3824 drvAudioStreamCaptureSilence(pStreamEx, (uint8_t *)pvBuf, cbBuf, pcbRead);
3825 break;
3826
3827 case DRVAUDIOCAPTURESTATE_NO_CAPTURE:
3828 *pcbRead = 0;
3829 Log4Func(("[%s] Not capturing - backend state: %s\n",
3830 pStreamEx->Core.szName, PDMHostAudioStreamStateGetName(enmBackendState) ));
3831 break;
3832
3833 default:
3834 *pcbRead = 0;
3835 AssertMsgFailedBreak(("%d; cbBuf=%#x\n", pStreamEx->In.enmCaptureState, cbBuf));
3836 }
3837
3838 if (!pThis->CfgIn.Dbg.fEnabled || RT_FAILURE(rc))
3839 { /* likely */ }
3840 else
3841 AudioHlpFileWrite(pStreamEx->In.Dbg.pFileCapture, pvBuf, *pcbRead, 0 /* fFlags */);
3842 }
3843 else
3844 {
3845 *pcbRead = 0;
3846 Log4Func(("[%s] Backend stream %s, returning no data\n", pStreamEx->Core.szName,
3847 !pThis->Out.fEnabled ? "disabled" : !pThis->pHostDrvAudio ? "not attached" : "not ready yet"));
3848 }
3849 RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
3850 }
3851 else
3852 rc = VERR_AUDIO_STREAM_NOT_READY;
3853
3854 RTCritSectLeave(&pStreamEx->Core.CritSect);
3855 return rc;
3856}
3857
3858
3859/*********************************************************************************************************************************
3860* PDMIHOSTAUDIOPORT interface implementation. *
3861*********************************************************************************************************************************/
3862
3863/**
3864 * Worker for drvAudioHostPort_DoOnWorkerThread with stream argument, called on
3865 * worker thread.
3866 */
3867static DECLCALLBACK(void) drvAudioHostPort_DoOnWorkerThreadStreamWorker(PDRVAUDIO pThis, PDRVAUDIOSTREAM pStreamEx,
3868 uintptr_t uUser, void *pvUser)
3869{
3870 LogFlowFunc(("pThis=%p uUser=%#zx pvUser=%p\n", pThis, uUser, pvUser));
3871 AssertPtrReturnVoid(pThis);
3872 AssertPtrReturnVoid(pStreamEx);
3873 AssertReturnVoid(pStreamEx->uMagic == DRVAUDIOSTREAM_MAGIC);
3874
3875 /*
3876 * The CritSectHotPlug lock should not be needed here as detach will destroy
3877 * the thread pool. So, we'll leave taking the stream lock to the worker we're
3878 * calling as there are no lock order concerns.
3879 */
3880 PPDMIHOSTAUDIO const pIHostDrvAudio = pThis->pHostDrvAudio;
3881 AssertPtrReturnVoid(pIHostDrvAudio);
3882 AssertPtrReturnVoid(pIHostDrvAudio->pfnDoOnWorkerThread);
3883 pIHostDrvAudio->pfnDoOnWorkerThread(pIHostDrvAudio, pStreamEx->pBackend, uUser, pvUser);
3884
3885 drvAudioStreamReleaseInternal(pThis, pStreamEx, true /*fMayDestroy*/);
3886 LogFlowFunc(("returns\n"));
3887}
3888
3889
3890/**
3891 * Worker for drvAudioHostPort_DoOnWorkerThread without stream argument, called
3892 * on worker thread.
3893 *
3894 * This wrapper isn't technically required, but it helps with logging and a few
3895 * extra sanity checks.
3896 */
3897static DECLCALLBACK(void) drvAudioHostPort_DoOnWorkerThreadWorker(PDRVAUDIO pThis, uintptr_t uUser, void *pvUser)
3898{
3899 LogFlowFunc(("pThis=%p uUser=%#zx pvUser=%p\n", pThis, uUser, pvUser));
3900 AssertPtrReturnVoid(pThis);
3901
3902 /*
3903 * The CritSectHotPlug lock should not be needed here as detach will destroy
3904 * the thread pool.
3905 */
3906 PPDMIHOSTAUDIO const pIHostDrvAudio = pThis->pHostDrvAudio;
3907 AssertPtrReturnVoid(pIHostDrvAudio);
3908 AssertPtrReturnVoid(pIHostDrvAudio->pfnDoOnWorkerThread);
3909
3910 pIHostDrvAudio->pfnDoOnWorkerThread(pIHostDrvAudio, NULL, uUser, pvUser);
3911
3912 LogFlowFunc(("returns\n"));
3913}
3914
3915
3916/**
3917 * @interface_method_impl{PDMIHOSTAUDIOPORT,pfnDoOnWorkerThread}
3918 */
3919static DECLCALLBACK(int) drvAudioHostPort_DoOnWorkerThread(PPDMIHOSTAUDIOPORT pInterface, PPDMAUDIOBACKENDSTREAM pStream,
3920 uintptr_t uUser, void *pvUser)
3921{
3922 PDRVAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVAUDIO, IHostAudioPort);
3923 LogFlowFunc(("pStream=%p uUser=%#zx pvUser=%p\n", pStream, uUser, pvUser));
3924
3925 /*
3926 * Assert some sanity.
3927 */
3928 PDRVAUDIOSTREAM pStreamEx;
3929 if (!pStream)
3930 pStreamEx = NULL;
3931 else
3932 {
3933 AssertPtrReturn(pStream, VERR_INVALID_POINTER);
3934 AssertReturn(pStream->uMagic == PDMAUDIOBACKENDSTREAM_MAGIC, VERR_INVALID_MAGIC);
3935 pStreamEx = (PDRVAUDIOSTREAM)pStream->pStream;
3936 AssertPtrReturn(pStreamEx, VERR_INVALID_POINTER);
3937 AssertReturn(pStreamEx->uMagic == DRVAUDIOSTREAM_MAGIC, VERR_INVALID_MAGIC);
3938 AssertReturn(pStreamEx->Core.uMagic == PDMAUDIOSTREAM_MAGIC, VERR_INVALID_MAGIC);
3939 }
3940
3941 int rc = RTCritSectRwEnterShared(&pThis->CritSectHotPlug);
3942 AssertRCReturn(rc, rc);
3943
3944 Assert(pThis->hReqPool != NIL_RTREQPOOL);
3945 AssertPtr(pThis->pHostDrvAudio);
3946 if ( pThis->hReqPool != NIL_RTREQPOOL
3947 && pThis->pHostDrvAudio != NULL)
3948 {
3949 AssertPtr(pThis->pHostDrvAudio->pfnDoOnWorkerThread);
3950 if (pThis->pHostDrvAudio->pfnDoOnWorkerThread)
3951 {
3952 /*
3953 * Try do the work.
3954 */
3955 if (!pStreamEx)
3956 {
3957 rc = RTReqPoolCallEx(pThis->hReqPool, 0 /*cMillies*/, NULL /*phReq*/, RTREQFLAGS_VOID | RTREQFLAGS_NO_WAIT,
3958 (PFNRT)drvAudioHostPort_DoOnWorkerThreadWorker, 3, pThis, uUser, pvUser);
3959 AssertRC(rc);
3960 }
3961 else
3962 {
3963 uint32_t cRefs = drvAudioStreamRetainInternal(pStreamEx);
3964 if (cRefs != UINT32_MAX)
3965 {
3966 rc = RTReqPoolCallEx(pThis->hReqPool, 0 /*cMillies*/, NULL, RTREQFLAGS_VOID | RTREQFLAGS_NO_WAIT,
3967 (PFNRT)drvAudioHostPort_DoOnWorkerThreadStreamWorker,
3968 4, pThis, pStreamEx, uUser, pvUser);
3969 AssertRC(rc);
3970 if (RT_FAILURE(rc))
3971 {
3972 RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
3973 drvAudioStreamReleaseInternal(pThis, pStreamEx, true /*fMayDestroy*/);
3974 RTCritSectRwEnterShared(&pThis->CritSectHotPlug);
3975 }
3976 }
3977 else
3978 rc = VERR_INVALID_PARAMETER;
3979 }
3980 }
3981 else
3982 rc = VERR_INVALID_FUNCTION;
3983 }
3984 else
3985 rc = VERR_INVALID_STATE;
3986
3987 RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
3988 LogFlowFunc(("returns %Rrc\n", rc));
3989 return rc;
3990}
3991
3992
3993/**
3994 * Marks a stream for re-init.
3995 */
3996static void drvAudioStreamMarkNeedReInit(PDRVAUDIOSTREAM pStreamEx, const char *pszCaller)
3997{
3998 LogFlow((LOG_FN_FMT ": Flagging %s for re-init.\n", pszCaller, pStreamEx->Core.szName)); RT_NOREF(pszCaller);
3999 Assert(RTCritSectIsOwner(&pStreamEx->Core.CritSect));
4000
4001 pStreamEx->fStatus |= PDMAUDIOSTREAM_STS_NEED_REINIT;
4002 PDMAUDIOSTREAM_STS_ASSERT_VALID(pStreamEx->fStatus);
4003 pStreamEx->cTriesReInit = 0;
4004 pStreamEx->nsLastReInit = 0;
4005}
4006
4007
4008/**
4009 * @interface_method_impl{PDMIHOSTAUDIOPORT,pfnNotifyDeviceChanged}
4010 */
4011static DECLCALLBACK(void) drvAudioHostPort_NotifyDeviceChanged(PPDMIHOSTAUDIOPORT pInterface, PDMAUDIODIR enmDir, void *pvUser)
4012{
4013 PDRVAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVAUDIO, IHostAudioPort);
4014 AssertReturnVoid(enmDir == PDMAUDIODIR_IN || enmDir == PDMAUDIODIR_OUT);
4015 LogRel(("Audio: The %s device for %s is changing.\n", enmDir == PDMAUDIODIR_IN ? "input" : "output", pThis->BackendCfg.szName));
4016
4017 /*
4018 * Grab the list lock in shared mode and do the work.
4019 */
4020 int rc = RTCritSectRwEnterShared(&pThis->CritSectGlobals);
4021 AssertRCReturnVoid(rc);
4022
4023 PDRVAUDIOSTREAM pStreamEx;
4024 RTListForEach(&pThis->LstStreams, pStreamEx, DRVAUDIOSTREAM, ListEntry)
4025 {
4026 if (pStreamEx->Core.enmDir == enmDir)
4027 {
4028 RTCritSectEnter(&pStreamEx->Core.CritSect);
4029 RTCritSectRwEnterShared(&pThis->CritSectHotPlug);
4030
4031 if (pThis->pHostDrvAudio->pfnStreamNotifyDeviceChanged)
4032 {
4033 LogFlowFunc(("Calling pfnStreamNotifyDeviceChanged on %s, old backend state: %s...\n", pStreamEx->Core.szName,
4034 PDMHostAudioStreamStateGetName(drvAudioStreamGetBackendState(pThis, pStreamEx)) ));
4035 pThis->pHostDrvAudio->pfnStreamNotifyDeviceChanged(pThis->pHostDrvAudio, pStreamEx->pBackend, pvUser);
4036 LogFlowFunc(("New stream backend state: %s\n",
4037 PDMHostAudioStreamStateGetName(drvAudioStreamGetBackendState(pThis, pStreamEx)) ));
4038 }
4039 else
4040 drvAudioStreamMarkNeedReInit(pStreamEx, __PRETTY_FUNCTION__);
4041
4042 RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
4043 RTCritSectLeave(&pStreamEx->Core.CritSect);
4044 }
4045 }
4046
4047 RTCritSectRwLeaveShared(&pThis->CritSectGlobals);
4048}
4049
4050
4051/**
4052 * @interface_method_impl{PDMIHOSTAUDIOPORT,pfnStreamNotifyPreparingDeviceSwitch}
4053 */
4054static DECLCALLBACK(void) drvAudioHostPort_StreamNotifyPreparingDeviceSwitch(PPDMIHOSTAUDIOPORT pInterface,
4055 PPDMAUDIOBACKENDSTREAM pStream)
4056{
4057 RT_NOREF(pInterface);
4058
4059 /*
4060 * Backend stream to validated DrvAudio stream:
4061 */
4062 AssertPtrReturnVoid(pStream);
4063 AssertReturnVoid(pStream->uMagic == PDMAUDIOBACKENDSTREAM_MAGIC);
4064 PDRVAUDIOSTREAM pStreamEx = (PDRVAUDIOSTREAM)pStream->pStream;
4065 AssertPtrReturnVoid(pStreamEx);
4066 AssertReturnVoid(pStreamEx->Core.uMagic == PDMAUDIOSTREAM_MAGIC);
4067 AssertReturnVoid(pStreamEx->uMagic == DRVAUDIOSTREAM_MAGIC);
4068 LogFlowFunc(("pStreamEx=%p '%s'\n", pStreamEx, pStreamEx->Core.szName));
4069
4070 /*
4071 * Grab the lock and do switch the state (only needed for output streams for now).
4072 */
4073 RTCritSectEnter(&pStreamEx->Core.CritSect);
4074 AssertReturnVoidStmt(pStreamEx->uMagic == DRVAUDIOSTREAM_MAGIC, RTCritSectLeave(&pStreamEx->Core.CritSect)); /* paranoia */
4075
4076 if (pStreamEx->Core.enmDir == PDMAUDIODIR_OUT)
4077 {
4078 if (pStreamEx->cbPreBufThreshold > 0)
4079 {
4080 DRVAUDIOPLAYSTATE const enmPlayState = pStreamEx->Out.enmPlayState;
4081 switch (enmPlayState)
4082 {
4083 case DRVAUDIOPLAYSTATE_PREBUF:
4084 case DRVAUDIOPLAYSTATE_PREBUF_OVERDUE:
4085 case DRVAUDIOPLAYSTATE_NOPLAY:
4086 case DRVAUDIOPLAYSTATE_PREBUF_COMMITTING: /* simpler */
4087 pStreamEx->Out.enmPlayState = DRVAUDIOPLAYSTATE_PREBUF_SWITCHING;
4088 break;
4089 case DRVAUDIOPLAYSTATE_PLAY:
4090 pStreamEx->Out.enmPlayState = DRVAUDIOPLAYSTATE_PLAY_PREBUF;
4091 break;
4092 case DRVAUDIOPLAYSTATE_PREBUF_SWITCHING:
4093 case DRVAUDIOPLAYSTATE_PLAY_PREBUF:
4094 break;
4095 /* no default */
4096 case DRVAUDIOPLAYSTATE_END:
4097 case DRVAUDIOPLAYSTATE_INVALID:
4098 break;
4099 }
4100 LogFunc(("%s -> %s\n", drvAudioPlayStateName(enmPlayState), drvAudioPlayStateName(pStreamEx->Out.enmPlayState) ));
4101 }
4102 else
4103 LogFunc(("No pre-buffering configured.\n"));
4104 }
4105 else
4106 LogFunc(("input stream, nothing to do.\n"));
4107
4108 RTCritSectLeave(&pStreamEx->Core.CritSect);
4109}
4110
4111
4112/**
4113 * @interface_method_impl{PDMIHOSTAUDIOPORT,pfnStreamNotifyDeviceChanged}
4114 */
4115static DECLCALLBACK(void) drvAudioHostPort_StreamNotifyDeviceChanged(PPDMIHOSTAUDIOPORT pInterface,
4116 PPDMAUDIOBACKENDSTREAM pStream, bool fReInit)
4117{
4118 PDRVAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVAUDIO, IHostAudioPort);
4119
4120 /*
4121 * Backend stream to validated DrvAudio stream:
4122 */
4123 AssertPtrReturnVoid(pStream);
4124 AssertReturnVoid(pStream->uMagic == PDMAUDIOBACKENDSTREAM_MAGIC);
4125 PDRVAUDIOSTREAM pStreamEx = (PDRVAUDIOSTREAM)pStream->pStream;
4126 AssertPtrReturnVoid(pStreamEx);
4127 AssertReturnVoid(pStreamEx->Core.uMagic == PDMAUDIOSTREAM_MAGIC);
4128 AssertReturnVoid(pStreamEx->uMagic == DRVAUDIOSTREAM_MAGIC);
4129
4130 /*
4131 * Grab the lock and do the requested work.
4132 */
4133 RTCritSectEnter(&pStreamEx->Core.CritSect);
4134 AssertReturnVoidStmt(pStreamEx->uMagic == DRVAUDIOSTREAM_MAGIC, RTCritSectLeave(&pStreamEx->Core.CritSect)); /* paranoia */
4135
4136 if (fReInit)
4137 drvAudioStreamMarkNeedReInit(pStreamEx, __PRETTY_FUNCTION__);
4138 else
4139 {
4140 /*
4141 * Adjust the stream state now that the device has (perhaps finally) been switched.
4142 *
4143 * For enabled output streams, we must update the play state. We could try commit
4144 * pre-buffered data here, but it's really not worth the hazzle and risk (don't
4145 * know which thread we're on, do we now).
4146 */
4147 AssertStmt(!(pStreamEx->fStatus & PDMAUDIOSTREAM_STS_NEED_REINIT),
4148 pStreamEx->fStatus &= ~PDMAUDIOSTREAM_STS_NEED_REINIT);
4149
4150
4151 if (pStreamEx->Core.enmDir == PDMAUDIODIR_OUT)
4152 {
4153 DRVAUDIOPLAYSTATE const enmPlayState = pStreamEx->Out.enmPlayState;
4154 pStreamEx->Out.enmPlayState = DRVAUDIOPLAYSTATE_PREBUF;
4155 LogFunc(("%s: %s -> %s\n", pStreamEx->Core.szName, drvAudioPlayStateName(enmPlayState),
4156 drvAudioPlayStateName(pStreamEx->Out.enmPlayState) ));
4157 RT_NOREF(enmPlayState);
4158 }
4159
4160 /* Disable and then fully resync. */
4161 /** @todo This doesn't work quite reliably if we're in draining mode
4162 * (PENDING_DISABLE, so the backend needs to take care of that prior to calling
4163 * us. Sigh. The idea was to avoid extra state mess in the backend... */
4164 drvAudioStreamControlInternalBackend(pThis, pStreamEx, PDMAUDIOSTREAMCMD_DISABLE);
4165 drvAudioStreamUpdateBackendOnStatus(pThis, pStreamEx, "device changed");
4166 }
4167
4168 RTCritSectLeave(&pStreamEx->Core.CritSect);
4169}
4170
4171
4172#ifdef VBOX_WITH_AUDIO_ENUM
4173/**
4174 * @callback_method_impl{FNTMTIMERDRV, Re-enumerate backend devices.}
4175 *
4176 * Used to do/trigger re-enumeration of backend devices with a delay after we
4177 * got notification as there can be further notifications following shortly
4178 * after the first one. Also good to get it of random COM/whatever threads.
4179 */
4180static DECLCALLBACK(void) drvAudioEnumerateTimer(PPDMDRVINS pDrvIns, TMTIMERHANDLE hTimer, void *pvUser)
4181{
4182 PDRVAUDIO pThis = PDMINS_2_DATA(pDrvIns, PDRVAUDIO);
4183 RT_NOREF(hTimer, pvUser);
4184
4185 /* Try push the work over to the thread-pool if we've got one. */
4186 RTCritSectRwEnterShared(&pThis->CritSectHotPlug);
4187 if (pThis->hReqPool != NIL_RTREQPOOL)
4188 {
4189 int rc = RTReqPoolCallEx(pThis->hReqPool, 0 /*cMillies*/, NULL, RTREQFLAGS_VOID | RTREQFLAGS_NO_WAIT,
4190 (PFNRT)drvAudioDevicesEnumerateInternal,
4191 3, pThis, true /*fLog*/, (PPDMAUDIOHOSTENUM)NULL /*pDevEnum*/);
4192 LogFunc(("RTReqPoolCallEx: %Rrc\n", rc));
4193 RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
4194 if (RT_SUCCESS(rc))
4195 return;
4196 }
4197 else
4198 RTCritSectRwLeaveShared(&pThis->CritSectHotPlug);
4199
4200 LogFunc(("Calling drvAudioDevicesEnumerateInternal...\n"));
4201 drvAudioDevicesEnumerateInternal(pThis, true /* fLog */, NULL /* pDevEnum */);
4202}
4203#endif /* VBOX_WITH_AUDIO_ENUM */
4204
4205
4206/**
4207 * @interface_method_impl{PDMIHOSTAUDIOPORT,pfnNotifyDevicesChanged}
4208 */
4209static DECLCALLBACK(void) drvAudioHostPort_NotifyDevicesChanged(PPDMIHOSTAUDIOPORT pInterface)
4210{
4211 PDRVAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVAUDIO, IHostAudioPort);
4212 LogRel(("Audio: Device configuration of driver '%s' has changed\n", pThis->BackendCfg.szName));
4213
4214#ifdef RT_OS_DARWIN /** @todo Remove legacy behaviour: */
4215 /* Mark all host streams to re-initialize. */
4216 int rc2 = RTCritSectRwEnterShared(&pThis->CritSectGlobals);
4217 AssertRCReturnVoid(rc2);
4218 PDRVAUDIOSTREAM pStreamEx;
4219 RTListForEach(&pThis->LstStreams, pStreamEx, DRVAUDIOSTREAM, ListEntry)
4220 {
4221 RTCritSectEnter(&pStreamEx->Core.CritSect);
4222 drvAudioStreamMarkNeedReInit(pStreamEx, __PRETTY_FUNCTION__);
4223 RTCritSectLeave(&pStreamEx->Core.CritSect);
4224 }
4225 RTCritSectRwLeaveShared(&pThis->CritSectGlobals);
4226#endif
4227
4228#ifdef VBOX_WITH_AUDIO_ENUM
4229 /*
4230 * Re-enumerate all host devices with a tiny delay to avoid re-doing this
4231 * when a bunch of changes happens at once (they typically do on windows).
4232 * We'll keep postponing it till it quiesces for a fraction of a second.
4233 */
4234 int rc = PDMDrvHlpTimerSetMillies(pThis->pDrvIns, pThis->hEnumTimer, RT_MS_1SEC / 3);
4235 AssertRC(rc);
4236#endif
4237}
4238
4239
4240/*********************************************************************************************************************************
4241* PDMIBASE interface implementation. *
4242*********************************************************************************************************************************/
4243
4244/**
4245 * @interface_method_impl{PDMIBASE,pfnQueryInterface}
4246 */
4247static DECLCALLBACK(void *) drvAudioQueryInterface(PPDMIBASE pInterface, const char *pszIID)
4248{
4249 LogFlowFunc(("pInterface=%p, pszIID=%s\n", pInterface, pszIID));
4250
4251 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
4252 PDRVAUDIO pThis = PDMINS_2_DATA(pDrvIns, PDRVAUDIO);
4253
4254 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pDrvIns->IBase);
4255 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIAUDIOCONNECTOR, &pThis->IAudioConnector);
4256 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIHOSTAUDIOPORT, &pThis->IHostAudioPort);
4257
4258 return NULL;
4259}
4260
4261
4262/*********************************************************************************************************************************
4263* PDMDRVREG interface implementation. *
4264*********************************************************************************************************************************/
4265
4266/**
4267 * Power Off notification.
4268 *
4269 * @param pDrvIns The driver instance data.
4270 */
4271static DECLCALLBACK(void) drvAudioPowerOff(PPDMDRVINS pDrvIns)
4272{
4273 PDRVAUDIO pThis = PDMINS_2_DATA(pDrvIns, PDRVAUDIO);
4274
4275 LogFlowFuncEnter();
4276
4277 /** @todo locking? */
4278 if (pThis->pHostDrvAudio) /* If not lower driver is configured, bail out. */
4279 {
4280 /*
4281 * Just destroy the host stream on the backend side.
4282 * The rest will either be destructed by the device emulation or
4283 * in drvAudioDestruct().
4284 */
4285 int rc = RTCritSectRwEnterShared(&pThis->CritSectGlobals);
4286 AssertRCReturnVoid(rc);
4287
4288 PDRVAUDIOSTREAM pStreamEx;
4289 RTListForEach(&pThis->LstStreams, pStreamEx, DRVAUDIOSTREAM, ListEntry)
4290 {
4291 RTCritSectEnter(&pStreamEx->Core.CritSect);
4292 drvAudioStreamControlInternalBackend(pThis, pStreamEx, PDMAUDIOSTREAMCMD_DISABLE);
4293 RTCritSectLeave(&pStreamEx->Core.CritSect);
4294 }
4295
4296 RTCritSectRwLeaveShared(&pThis->CritSectGlobals);
4297 }
4298
4299 LogFlowFuncLeave();
4300}
4301
4302
4303/**
4304 * Detach notification.
4305 *
4306 * @param pDrvIns The driver instance data.
4307 * @param fFlags Detach flags.
4308 */
4309static DECLCALLBACK(void) drvAudioDetach(PPDMDRVINS pDrvIns, uint32_t fFlags)
4310{
4311 PDMDRV_CHECK_VERSIONS_RETURN_VOID(pDrvIns);
4312 PDRVAUDIO pThis = PDMINS_2_DATA(pDrvIns, PDRVAUDIO);
4313 RT_NOREF(fFlags);
4314
4315 int rc = RTCritSectRwEnterExcl(&pThis->CritSectHotPlug);
4316 AssertLogRelRCReturnVoid(rc);
4317
4318 LogFunc(("%s (detached %p, hReqPool=%p)\n", pThis->BackendCfg.szName, pThis->pHostDrvAudio, pThis->hReqPool));
4319
4320 /*
4321 * Must first destroy the thread pool first so we are certain no threads
4322 * are still using the instance being detached. Release lock while doing
4323 * this as the thread functions may need to take it to complete.
4324 */
4325 if (pThis->pHostDrvAudio && pThis->hReqPool != NIL_RTREQPOOL)
4326 {
4327 RTREQPOOL hReqPool = pThis->hReqPool;
4328 pThis->hReqPool = NIL_RTREQPOOL;
4329
4330 RTCritSectRwLeaveExcl(&pThis->CritSectHotPlug);
4331
4332 RTReqPoolRelease(hReqPool);
4333
4334 RTCritSectRwEnterExcl(&pThis->CritSectHotPlug);
4335 }
4336
4337 /*
4338 * Now we can safely set pHostDrvAudio to NULL.
4339 */
4340 pThis->pHostDrvAudio = NULL;
4341
4342 RTCritSectRwLeaveExcl(&pThis->CritSectHotPlug);
4343}
4344
4345
4346/**
4347 * Initializes the host backend and queries its initial configuration.
4348 *
4349 * @returns VBox status code.
4350 * @param pThis Driver instance to be called.
4351 */
4352static int drvAudioHostInit(PDRVAUDIO pThis)
4353{
4354 LogFlowFuncEnter();
4355
4356 /*
4357 * Check the function pointers, make sure the ones we define as
4358 * mandatory are present.
4359 */
4360 PPDMIHOSTAUDIO pIHostDrvAudio = pThis->pHostDrvAudio;
4361 AssertPtrReturn(pIHostDrvAudio, VERR_INVALID_POINTER);
4362 AssertPtrReturn(pIHostDrvAudio->pfnGetConfig, VERR_INVALID_POINTER);
4363 AssertPtrNullReturn(pIHostDrvAudio->pfnGetDevices, VERR_INVALID_POINTER);
4364 AssertPtrNullReturn(pIHostDrvAudio->pfnSetDevice, VERR_INVALID_POINTER);
4365 AssertPtrNullReturn(pIHostDrvAudio->pfnGetStatus, VERR_INVALID_POINTER);
4366 AssertPtrNullReturn(pIHostDrvAudio->pfnDoOnWorkerThread, VERR_INVALID_POINTER);
4367 AssertPtrNullReturn(pIHostDrvAudio->pfnStreamConfigHint, VERR_INVALID_POINTER);
4368 AssertPtrReturn(pIHostDrvAudio->pfnStreamCreate, VERR_INVALID_POINTER);
4369 AssertPtrNullReturn(pIHostDrvAudio->pfnStreamInitAsync, VERR_INVALID_POINTER);
4370 AssertPtrReturn(pIHostDrvAudio->pfnStreamDestroy, VERR_INVALID_POINTER);
4371 AssertPtrNullReturn(pIHostDrvAudio->pfnStreamNotifyDeviceChanged, VERR_INVALID_POINTER);
4372 AssertPtrReturn(pIHostDrvAudio->pfnStreamControl, VERR_INVALID_POINTER);
4373 AssertPtrReturn(pIHostDrvAudio->pfnStreamGetReadable, VERR_INVALID_POINTER);
4374 AssertPtrReturn(pIHostDrvAudio->pfnStreamGetWritable, VERR_INVALID_POINTER);
4375 AssertPtrNullReturn(pIHostDrvAudio->pfnStreamGetPending, VERR_INVALID_POINTER);
4376 AssertPtrReturn(pIHostDrvAudio->pfnStreamGetState, VERR_INVALID_POINTER);
4377 AssertPtrReturn(pIHostDrvAudio->pfnStreamPlay, VERR_INVALID_POINTER);
4378 AssertPtrReturn(pIHostDrvAudio->pfnStreamCapture, VERR_INVALID_POINTER);
4379
4380 /*
4381 * Get the backend configuration.
4382 *
4383 * Note! Limit the number of streams to max 128 in each direction to
4384 * prevent wasting resources.
4385 * Note! Take care not to wipe the DriverName config value on failure.
4386 */
4387 PDMAUDIOBACKENDCFG BackendCfg;
4388 RT_ZERO(BackendCfg);
4389 int rc = pIHostDrvAudio->pfnGetConfig(pIHostDrvAudio, &BackendCfg);
4390 if (RT_SUCCESS(rc))
4391 {
4392 if (LogIsEnabled() && strcmp(BackendCfg.szName, pThis->BackendCfg.szName) != 0)
4393 LogFunc(("BackendCfg.szName: '%s' -> '%s'\n", pThis->BackendCfg.szName, BackendCfg.szName));
4394 pThis->BackendCfg = BackendCfg;
4395 pThis->In.cStreamsFree = RT_MIN(BackendCfg.cMaxStreamsIn, 128);
4396 pThis->Out.cStreamsFree = RT_MIN(BackendCfg.cMaxStreamsOut, 128);
4397
4398 LogFlowFunc(("cStreamsFreeIn=%RU8, cStreamsFreeOut=%RU8\n", pThis->In.cStreamsFree, pThis->Out.cStreamsFree));
4399 }
4400 else
4401 {
4402 LogRel(("Audio: Getting configuration for driver '%s' failed with %Rrc\n", pThis->BackendCfg.szName, rc));
4403 return VERR_AUDIO_BACKEND_INIT_FAILED;
4404 }
4405
4406 LogRel2(("Audio: Host driver '%s' supports %RU32 input streams and %RU32 output streams at once.\n",
4407 pThis->BackendCfg.szName, pThis->In.cStreamsFree, pThis->Out.cStreamsFree));
4408
4409#ifdef VBOX_WITH_AUDIO_ENUM
4410 int rc2 = drvAudioDevicesEnumerateInternal(pThis, true /* fLog */, NULL /* pDevEnum */);
4411 if (rc2 != VERR_NOT_SUPPORTED) /* Some backends don't implement device enumeration. */
4412 AssertRC(rc2);
4413 /* Ignore rc2. */
4414#endif
4415
4416 /*
4417 * Create a thread pool if stream creation can be asynchronous.
4418 *
4419 * The pool employs no pushback as the caller is typically EMT and
4420 * shouldn't be delayed.
4421 *
4422 * The number of threads limits and the device implementations use
4423 * of pfnStreamDestroy limits the number of streams pending async
4424 * init. We use RTReqCancel in drvAudioStreamDestroy to allow us
4425 * to release extra reference held by the pfnStreamInitAsync call
4426 * if successful. Cancellation will only be possible if the call
4427 * hasn't been picked up by a worker thread yet, so the max number
4428 * of threads in the pool defines how many destroyed streams that
4429 * can be lingering. (We must keep this under control, otherwise
4430 * an evil guest could just rapidly trigger stream creation and
4431 * destruction to consume host heap and hog CPU resources for
4432 * configuring audio backends.)
4433 */
4434 if ( pThis->hReqPool == NIL_RTREQPOOL
4435 && ( pIHostDrvAudio->pfnStreamInitAsync
4436 || pIHostDrvAudio->pfnDoOnWorkerThread
4437 || (pThis->BackendCfg.fFlags & (PDMAUDIOBACKEND_F_ASYNC_HINT | PDMAUDIOBACKEND_F_ASYNC_STREAM_DESTROY)) ))
4438 {
4439 char szName[16];
4440 RTStrPrintf(szName, sizeof(szName), "Aud%uWr", pThis->pDrvIns->iInstance);
4441 RTREQPOOL hReqPool = NIL_RTREQPOOL;
4442 rc = RTReqPoolCreate(3 /*cMaxThreads*/, RT_MS_30SEC /*cMsMinIdle*/, UINT32_MAX /*cThreadsPushBackThreshold*/,
4443 1 /*cMsMaxPushBack*/, szName, &hReqPool);
4444 LogFlowFunc(("Creating thread pool '%s': %Rrc, hReqPool=%p\n", szName, rc, hReqPool));
4445 AssertRCReturn(rc, rc);
4446
4447 rc = RTReqPoolSetCfgVar(hReqPool, RTREQPOOLCFGVAR_THREAD_FLAGS, RTTHREADFLAGS_COM_MTA);
4448 AssertRCReturnStmt(rc, RTReqPoolRelease(hReqPool), rc);
4449
4450 rc = RTReqPoolSetCfgVar(hReqPool, RTREQPOOLCFGVAR_MIN_THREADS, 1);
4451 AssertRC(rc); /* harmless */
4452
4453 pThis->hReqPool = hReqPool;
4454 }
4455 else
4456 LogFlowFunc(("No thread pool.\n"));
4457
4458 LogFlowFuncLeave();
4459 return VINF_SUCCESS;
4460}
4461
4462
4463/**
4464 * Does the actual backend driver attaching and queries the backend's interface.
4465 *
4466 * This is a worker for both drvAudioAttach and drvAudioConstruct.
4467 *
4468 * @returns VBox status code.
4469 * @param pDrvIns The driver instance.
4470 * @param pThis Pointer to driver instance.
4471 * @param fFlags Attach flags; see PDMDrvHlpAttach().
4472 */
4473static int drvAudioDoAttachInternal(PPDMDRVINS pDrvIns, PDRVAUDIO pThis, uint32_t fFlags)
4474{
4475 Assert(pThis->pHostDrvAudio == NULL); /* No nested attaching. */
4476
4477 /*
4478 * Attach driver below and query its connector interface.
4479 */
4480 PPDMIBASE pDownBase;
4481 int rc = PDMDrvHlpAttach(pDrvIns, fFlags, &pDownBase);
4482 if (RT_SUCCESS(rc))
4483 {
4484 pThis->pHostDrvAudio = PDMIBASE_QUERY_INTERFACE(pDownBase, PDMIHOSTAUDIO);
4485 if (pThis->pHostDrvAudio)
4486 {
4487 /*
4488 * If everything went well, initialize the lower driver.
4489 */
4490 rc = drvAudioHostInit(pThis);
4491 if (RT_FAILURE(rc))
4492 pThis->pHostDrvAudio = NULL;
4493 }
4494 else
4495 {
4496 LogRel(("Audio: Failed to query interface for underlying host driver '%s'\n", pThis->BackendCfg.szName));
4497 rc = PDMDRV_SET_ERROR(pThis->pDrvIns, VERR_PDM_MISSING_INTERFACE_BELOW,
4498 N_("The host audio driver does not implement PDMIHOSTAUDIO!"));
4499 }
4500 }
4501 /*
4502 * If the host driver below us failed to construct for some beningn reason,
4503 * we'll report it as a runtime error and replace it with the Null driver.
4504 *
4505 * Note! We do NOT change anything in PDM (or CFGM), so pDrvIns->pDownBase
4506 * will remain NULL in this case.
4507 */
4508 else if ( rc == VERR_AUDIO_BACKEND_INIT_FAILED
4509 || rc == VERR_MODULE_NOT_FOUND
4510 || rc == VERR_SYMBOL_NOT_FOUND
4511 || rc == VERR_FILE_NOT_FOUND
4512 || rc == VERR_PATH_NOT_FOUND)
4513 {
4514 /* Complain: */
4515 LogRel(("DrvAudio: Host audio driver '%s' init failed with %Rrc. Switching to the NULL driver for now.\n",
4516 pThis->BackendCfg.szName, rc));
4517 PDMDrvHlpVMSetRuntimeError(pDrvIns, 0 /*fFlags*/, "HostAudioNotResponding",
4518 N_("Host audio backend (%s) initialization has failed. Selecting the NULL audio backend with the consequence that no sound is audible"),
4519 pThis->BackendCfg.szName);
4520
4521 /* Replace with null audio: */
4522 pThis->pHostDrvAudio = (PPDMIHOSTAUDIO)&g_DrvHostAudioNull;
4523 RTStrCopy(pThis->BackendCfg.szName, sizeof(pThis->BackendCfg.szName), "NULL");
4524 rc = drvAudioHostInit(pThis);
4525 AssertRC(rc);
4526 }
4527
4528 LogFunc(("[%s] rc=%Rrc\n", pThis->BackendCfg.szName, rc));
4529 return rc;
4530}
4531
4532
4533/**
4534 * Attach notification.
4535 *
4536 * @param pDrvIns The driver instance data.
4537 * @param fFlags Attach flags.
4538 */
4539static DECLCALLBACK(int) drvAudioAttach(PPDMDRVINS pDrvIns, uint32_t fFlags)
4540{
4541 PDMDRV_CHECK_VERSIONS_RETURN(pDrvIns);
4542 PDRVAUDIO pThis = PDMINS_2_DATA(pDrvIns, PDRVAUDIO);
4543 LogFunc(("%s\n", pThis->BackendCfg.szName));
4544
4545 int rc = RTCritSectRwEnterExcl(&pThis->CritSectHotPlug);
4546 AssertRCReturn(rc, rc);
4547
4548 rc = drvAudioDoAttachInternal(pDrvIns, pThis, fFlags);
4549
4550 RTCritSectRwLeaveExcl(&pThis->CritSectHotPlug);
4551 return rc;
4552}
4553
4554
4555/**
4556 * Handles state changes for all audio streams.
4557 *
4558 * @param pDrvIns Pointer to driver instance.
4559 * @param enmCmd Stream command to set for all streams.
4560 */
4561static void drvAudioStateHandler(PPDMDRVINS pDrvIns, PDMAUDIOSTREAMCMD enmCmd)
4562{
4563 PDMDRV_CHECK_VERSIONS_RETURN_VOID(pDrvIns);
4564 PDRVAUDIO pThis = PDMINS_2_DATA(pDrvIns, PDRVAUDIO);
4565 LogFlowFunc(("enmCmd=%s\n", PDMAudioStrmCmdGetName(enmCmd)));
4566
4567 int rc2 = RTCritSectRwEnterShared(&pThis->CritSectGlobals);
4568 AssertRCReturnVoid(rc2);
4569
4570 PDRVAUDIOSTREAM pStreamEx;
4571 RTListForEach(&pThis->LstStreams, pStreamEx, DRVAUDIOSTREAM, ListEntry)
4572 {
4573 RTCritSectEnter(&pStreamEx->Core.CritSect);
4574 drvAudioStreamControlInternal(pThis, pStreamEx, enmCmd);
4575 RTCritSectLeave(&pStreamEx->Core.CritSect);
4576 }
4577
4578 RTCritSectRwLeaveShared(&pThis->CritSectGlobals);
4579}
4580
4581
4582/**
4583 * Resume notification.
4584 *
4585 * @param pDrvIns The driver instance data.
4586 */
4587static DECLCALLBACK(void) drvAudioResume(PPDMDRVINS pDrvIns)
4588{
4589 drvAudioStateHandler(pDrvIns, PDMAUDIOSTREAMCMD_RESUME);
4590}
4591
4592
4593/**
4594 * Suspend notification.
4595 *
4596 * @param pDrvIns The driver instance data.
4597 */
4598static DECLCALLBACK(void) drvAudioSuspend(PPDMDRVINS pDrvIns)
4599{
4600 drvAudioStateHandler(pDrvIns, PDMAUDIOSTREAMCMD_PAUSE);
4601}
4602
4603
4604/**
4605 * Destructs an audio driver instance.
4606 *
4607 * @copydoc FNPDMDRVDESTRUCT
4608 */
4609static DECLCALLBACK(void) drvAudioDestruct(PPDMDRVINS pDrvIns)
4610{
4611 PDMDRV_CHECK_VERSIONS_RETURN_VOID(pDrvIns);
4612 PDRVAUDIO pThis = PDMINS_2_DATA(pDrvIns, PDRVAUDIO);
4613
4614 LogFlowFuncEnter();
4615
4616 /*
4617 * We must start by setting pHostDrvAudio to NULL here as the anything below
4618 * us has already been destroyed at this point.
4619 */
4620 if (RTCritSectRwIsInitialized(&pThis->CritSectHotPlug))
4621 {
4622 RTCritSectRwEnterExcl(&pThis->CritSectHotPlug);
4623 pThis->pHostDrvAudio = NULL;
4624 RTCritSectRwLeaveExcl(&pThis->CritSectHotPlug);
4625 }
4626 else
4627 {
4628 Assert(pThis->pHostDrvAudio == NULL);
4629 pThis->pHostDrvAudio = NULL;
4630 }
4631
4632 /*
4633 * Make sure the thread pool is out of the picture before we terminate all the streams.
4634 */
4635 if (pThis->hReqPool != NIL_RTREQPOOL)
4636 {
4637 uint32_t cRefs = RTReqPoolRelease(pThis->hReqPool);
4638 Assert(cRefs == 0); RT_NOREF(cRefs);
4639 pThis->hReqPool = NIL_RTREQPOOL;
4640 }
4641
4642 /*
4643 * Destroy all streams.
4644 */
4645 if (RTCritSectRwIsInitialized(&pThis->CritSectGlobals))
4646 {
4647 RTCritSectRwEnterExcl(&pThis->CritSectGlobals);
4648
4649 PDRVAUDIOSTREAM pStreamEx, pStreamExNext;
4650 RTListForEachSafe(&pThis->LstStreams, pStreamEx, pStreamExNext, DRVAUDIOSTREAM, ListEntry)
4651 {
4652 int rc = drvAudioStreamUninitInternal(pThis, pStreamEx);
4653 if (RT_SUCCESS(rc))
4654 {
4655 RTListNodeRemove(&pStreamEx->ListEntry);
4656 drvAudioStreamFree(pStreamEx);
4657 }
4658 }
4659
4660 RTCritSectRwLeaveExcl(&pThis->CritSectGlobals);
4661 RTCritSectRwDelete(&pThis->CritSectGlobals);
4662 }
4663
4664
4665 /* Sanity. */
4666 Assert(RTListIsEmpty(&pThis->LstStreams));
4667
4668 if (RTCritSectRwIsInitialized(&pThis->CritSectHotPlug))
4669 RTCritSectRwDelete(&pThis->CritSectHotPlug);
4670
4671#ifdef VBOX_WITH_STATISTICS
4672 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->Stats.TotalStreamsActive);
4673 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->Stats.TotalStreamsCreated);
4674 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->Stats.TotalFramesRead);
4675 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->Stats.TotalFramesIn);
4676 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->Stats.TotalBytesRead);
4677#endif
4678
4679 LogFlowFuncLeave();
4680}
4681
4682
4683/**
4684 * Constructs an audio driver instance.
4685 *
4686 * @copydoc FNPDMDRVCONSTRUCT
4687 */
4688static DECLCALLBACK(int) drvAudioConstruct(PPDMDRVINS pDrvIns, PCFGMNODE pCfg, uint32_t fFlags)
4689{
4690 PDMDRV_CHECK_VERSIONS_RETURN(pDrvIns);
4691 PDRVAUDIO pThis = PDMINS_2_DATA(pDrvIns, PDRVAUDIO);
4692 LogFlowFunc(("pDrvIns=%#p, pCfgHandle=%#p, fFlags=%x\n", pDrvIns, pCfg, fFlags));
4693
4694 /*
4695 * Basic instance init.
4696 */
4697 RTListInit(&pThis->LstStreams);
4698 pThis->hReqPool = NIL_RTREQPOOL;
4699
4700 /*
4701 * Read configuration.
4702 */
4703 PDMDRV_VALIDATE_CONFIG_RETURN(pDrvIns,
4704 "DriverName|"
4705 "InputEnabled|"
4706 "OutputEnabled|"
4707 "DebugEnabled|"
4708 "DebugPathOut|"
4709 /* Deprecated: */
4710 "PCMSampleBitIn|"
4711 "PCMSampleBitOut|"
4712 "PCMSampleHzIn|"
4713 "PCMSampleHzOut|"
4714 "PCMSampleSignedIn|"
4715 "PCMSampleSignedOut|"
4716 "PCMSampleSwapEndianIn|"
4717 "PCMSampleSwapEndianOut|"
4718 "PCMSampleChannelsIn|"
4719 "PCMSampleChannelsOut|"
4720 "PeriodSizeMsIn|"
4721 "PeriodSizeMsOut|"
4722 "BufferSizeMsIn|"
4723 "BufferSizeMsOut|"
4724 "PreBufferSizeMsIn|"
4725 "PreBufferSizeMsOut",
4726 "In|Out");
4727
4728 int rc = CFGMR3QueryStringDef(pCfg, "DriverName", pThis->BackendCfg.szName, sizeof(pThis->BackendCfg.szName), "Untitled");
4729 AssertLogRelRCReturn(rc, rc);
4730
4731 /* Neither input nor output by default for security reasons. */
4732 rc = CFGMR3QueryBoolDef(pCfg, "InputEnabled", &pThis->In.fEnabled, false);
4733 AssertLogRelRCReturn(rc, rc);
4734
4735 rc = CFGMR3QueryBoolDef(pCfg, "OutputEnabled", &pThis->Out.fEnabled, false);
4736 AssertLogRelRCReturn(rc, rc);
4737
4738 /* Debug stuff (same for both directions). */
4739 rc = CFGMR3QueryBoolDef(pCfg, "DebugEnabled", &pThis->CfgIn.Dbg.fEnabled, false);
4740 AssertLogRelRCReturn(rc, rc);
4741
4742 rc = CFGMR3QueryStringDef(pCfg, "DebugPathOut", pThis->CfgIn.Dbg.szPathOut, sizeof(pThis->CfgIn.Dbg.szPathOut), "");
4743 AssertLogRelRCReturn(rc, rc);
4744 if (pThis->CfgIn.Dbg.szPathOut[0] == '\0')
4745 {
4746 rc = RTPathTemp(pThis->CfgIn.Dbg.szPathOut, sizeof(pThis->CfgIn.Dbg.szPathOut));
4747 if (RT_FAILURE(rc))
4748 {
4749 LogRel(("Audio: Warning! Failed to retrieve temporary directory: %Rrc - disabling debugging.\n", rc));
4750 pThis->CfgIn.Dbg.szPathOut[0] = '\0';
4751 pThis->CfgIn.Dbg.fEnabled = false;
4752 }
4753 }
4754 if (pThis->CfgIn.Dbg.fEnabled)
4755 LogRel(("Audio: Debugging for driver '%s' enabled (audio data written to '%s')\n",
4756 pThis->BackendCfg.szName, pThis->CfgIn.Dbg.szPathOut));
4757
4758 /* Copy debug setup to the output direction. */
4759 pThis->CfgOut.Dbg = pThis->CfgIn.Dbg;
4760
4761 LogRel2(("Audio: Verbose logging for driver '%s' is probably enabled too.\n", pThis->BackendCfg.szName));
4762 /* This ^^^^^^^ is the *WRONG* place for that kind of statement. Verbose logging might only be enabled for DrvAudio. */
4763 LogRel2(("Audio: Initial status for driver '%s' is: input is %s, output is %s\n",
4764 pThis->BackendCfg.szName, pThis->In.fEnabled ? "enabled" : "disabled", pThis->Out.fEnabled ? "enabled" : "disabled"));
4765
4766 /*
4767 * Per direction configuration. A bit complicated as
4768 * these wasn't originally in sub-nodes.
4769 */
4770 for (unsigned iDir = 0; iDir < 2; iDir++)
4771 {
4772 char szNm[48];
4773 PDRVAUDIOCFG pAudioCfg = iDir == 0 ? &pThis->CfgIn : &pThis->CfgOut;
4774 const char *pszDir = iDir == 0 ? "In" : "Out";
4775
4776#define QUERY_VAL_RET(a_Width, a_szName, a_pValue, a_uDefault, a_ExprValid, a_szValidRange) \
4777 do { \
4778 rc = RT_CONCAT(CFGMR3QueryU,a_Width)(pDirNode, strcpy(szNm, a_szName), a_pValue); \
4779 if (rc == VERR_CFGM_VALUE_NOT_FOUND || rc == VERR_CFGM_NO_PARENT) \
4780 { \
4781 rc = RT_CONCAT(CFGMR3QueryU,a_Width)(pCfg, strcat(szNm, pszDir), a_pValue); \
4782 if (rc == VERR_CFGM_VALUE_NOT_FOUND || rc == VERR_CFGM_NO_PARENT) \
4783 { \
4784 *(a_pValue) = a_uDefault; \
4785 rc = VINF_SUCCESS; \
4786 } \
4787 else \
4788 LogRel(("DrvAudio: Warning! Please use '%s/" a_szName "' instead of '%s' for your VBoxInternal hacks\n", pszDir, szNm)); \
4789 } \
4790 AssertRCReturn(rc, PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, \
4791 N_("Configuration error: Failed to read %s config value '%s'"), pszDir, szNm)); \
4792 if (!(a_ExprValid)) \
4793 return PDMDrvHlpVMSetError(pDrvIns, VERR_OUT_OF_RANGE, RT_SRC_POS, \
4794 N_("Configuration error: Unsupported %s value %u. " a_szValidRange), szNm, *(a_pValue)); \
4795 } while (0)
4796
4797 PCFGMNODE const pDirNode = CFGMR3GetChild(pCfg, pszDir);
4798 rc = CFGMR3ValidateConfig(pDirNode, iDir == 0 ? "In/" : "Out/",
4799 "PCMSampleBit|"
4800 "PCMSampleHz|"
4801 "PCMSampleSigned|"
4802 "PCMSampleSwapEndian|"
4803 "PCMSampleChannels|"
4804 "PeriodSizeMs|"
4805 "BufferSizeMs|"
4806 "PreBufferSizeMs",
4807 "", pDrvIns->pReg->szName, pDrvIns->iInstance);
4808 AssertRCReturn(rc, rc);
4809
4810 uint8_t cSampleBits = 0;
4811 QUERY_VAL_RET(8, "PCMSampleBit", &cSampleBits, 0,
4812 cSampleBits == 0
4813 || cSampleBits == 8
4814 || cSampleBits == 16
4815 || cSampleBits == 32
4816 || cSampleBits == 64,
4817 "Must be either 0, 8, 16, 32 or 64");
4818 if (cSampleBits)
4819 PDMAudioPropsSetSampleSize(&pAudioCfg->Props, cSampleBits / 8);
4820
4821 uint8_t cChannels;
4822 QUERY_VAL_RET(8, "PCMSampleChannels", &cChannels, 0, cChannels <= 16, "Max 16");
4823 if (cChannels)
4824 PDMAudioPropsSetChannels(&pAudioCfg->Props, cChannels);
4825
4826 QUERY_VAL_RET(32, "PCMSampleHz", &pAudioCfg->Props.uHz, 0,
4827 pAudioCfg->Props.uHz == 0 || (pAudioCfg->Props.uHz >= 6000 && pAudioCfg->Props.uHz <= 768000),
4828 "In the range 6000 thru 768000, or 0");
4829
4830 QUERY_VAL_RET(8, "PCMSampleSigned", &pAudioCfg->uSigned, UINT8_MAX,
4831 pAudioCfg->uSigned == 0 || pAudioCfg->uSigned == 1 || pAudioCfg->uSigned == UINT8_MAX,
4832 "Must be either 0, 1, or 255");
4833
4834 QUERY_VAL_RET(8, "PCMSampleSwapEndian", &pAudioCfg->uSwapEndian, UINT8_MAX,
4835 pAudioCfg->uSwapEndian == 0 || pAudioCfg->uSwapEndian == 1 || pAudioCfg->uSwapEndian == UINT8_MAX,
4836 "Must be either 0, 1, or 255");
4837
4838 QUERY_VAL_RET(32, "PeriodSizeMs", &pAudioCfg->uPeriodSizeMs, 0,
4839 pAudioCfg->uPeriodSizeMs <= RT_MS_1SEC, "Max 1000");
4840
4841 QUERY_VAL_RET(32, "BufferSizeMs", &pAudioCfg->uBufferSizeMs, 0,
4842 pAudioCfg->uBufferSizeMs <= RT_MS_5SEC, "Max 5000");
4843
4844 QUERY_VAL_RET(32, "PreBufferSizeMs", &pAudioCfg->uPreBufSizeMs, UINT32_MAX,
4845 pAudioCfg->uPreBufSizeMs <= RT_MS_1SEC || pAudioCfg->uPreBufSizeMs == UINT32_MAX,
4846 "Max 1000, or 0xffffffff");
4847#undef QUERY_VAL_RET
4848 }
4849
4850 /*
4851 * Init the rest of the driver instance data.
4852 */
4853 rc = RTCritSectRwInit(&pThis->CritSectHotPlug);
4854 AssertRCReturn(rc, rc);
4855 rc = RTCritSectRwInit(&pThis->CritSectGlobals);
4856 AssertRCReturn(rc, rc);
4857#ifdef VBOX_STRICT
4858 /* Define locking order: */
4859 RTCritSectRwEnterExcl(&pThis->CritSectGlobals);
4860 RTCritSectRwEnterExcl(&pThis->CritSectHotPlug);
4861 RTCritSectRwLeaveExcl(&pThis->CritSectHotPlug);
4862 RTCritSectRwLeaveExcl(&pThis->CritSectGlobals);
4863#endif
4864
4865 pThis->pDrvIns = pDrvIns;
4866 /* IBase. */
4867 pDrvIns->IBase.pfnQueryInterface = drvAudioQueryInterface;
4868 /* IAudioConnector. */
4869 pThis->IAudioConnector.pfnEnable = drvAudioEnable;
4870 pThis->IAudioConnector.pfnIsEnabled = drvAudioIsEnabled;
4871 pThis->IAudioConnector.pfnGetConfig = drvAudioGetConfig;
4872 pThis->IAudioConnector.pfnGetStatus = drvAudioGetStatus;
4873 pThis->IAudioConnector.pfnStreamConfigHint = drvAudioStreamConfigHint;
4874 pThis->IAudioConnector.pfnStreamCreate = drvAudioStreamCreate;
4875 pThis->IAudioConnector.pfnStreamDestroy = drvAudioStreamDestroy;
4876 pThis->IAudioConnector.pfnStreamReInit = drvAudioStreamReInit;
4877 pThis->IAudioConnector.pfnStreamRetain = drvAudioStreamRetain;
4878 pThis->IAudioConnector.pfnStreamRelease = drvAudioStreamRelease;
4879 pThis->IAudioConnector.pfnStreamControl = drvAudioStreamControl;
4880 pThis->IAudioConnector.pfnStreamIterate = drvAudioStreamIterate;
4881 pThis->IAudioConnector.pfnStreamGetState = drvAudioStreamGetState;
4882 pThis->IAudioConnector.pfnStreamGetWritable = drvAudioStreamGetWritable;
4883 pThis->IAudioConnector.pfnStreamPlay = drvAudioStreamPlay;
4884 pThis->IAudioConnector.pfnStreamGetReadable = drvAudioStreamGetReadable;
4885 pThis->IAudioConnector.pfnStreamCapture = drvAudioStreamCapture;
4886 /* IHostAudioPort */
4887 pThis->IHostAudioPort.pfnDoOnWorkerThread = drvAudioHostPort_DoOnWorkerThread;
4888 pThis->IHostAudioPort.pfnNotifyDeviceChanged = drvAudioHostPort_NotifyDeviceChanged;
4889 pThis->IHostAudioPort.pfnStreamNotifyPreparingDeviceSwitch = drvAudioHostPort_StreamNotifyPreparingDeviceSwitch;
4890 pThis->IHostAudioPort.pfnStreamNotifyDeviceChanged = drvAudioHostPort_StreamNotifyDeviceChanged;
4891 pThis->IHostAudioPort.pfnNotifyDevicesChanged = drvAudioHostPort_NotifyDevicesChanged;
4892
4893 /*
4894 * Statistics.
4895 */
4896#ifdef VBOX_WITH_STATISTICS
4897 PDMDrvHlpSTAMRegCounterEx(pDrvIns, &pThis->Stats.TotalStreamsActive, "TotalStreamsActive",
4898 STAMUNIT_COUNT, "Total active audio streams.");
4899 PDMDrvHlpSTAMRegCounterEx(pDrvIns, &pThis->Stats.TotalStreamsCreated, "TotalStreamsCreated",
4900 STAMUNIT_COUNT, "Total created audio streams.");
4901 PDMDrvHlpSTAMRegCounterEx(pDrvIns, &pThis->Stats.TotalFramesRead, "TotalFramesRead",
4902 STAMUNIT_COUNT, "Total frames read by device emulation.");
4903 PDMDrvHlpSTAMRegCounterEx(pDrvIns, &pThis->Stats.TotalFramesIn, "TotalFramesIn",
4904 STAMUNIT_COUNT, "Total frames captured by backend.");
4905 PDMDrvHlpSTAMRegCounterEx(pDrvIns, &pThis->Stats.TotalBytesRead, "TotalBytesRead",
4906 STAMUNIT_BYTES, "Total bytes read.");
4907#endif
4908
4909#ifdef VBOX_WITH_AUDIO_ENUM
4910 /*
4911 * Create a timer to trigger delayed device enumeration on device changes.
4912 */
4913 RTStrPrintf(pThis->szEnumTimerName, sizeof(pThis->szEnumTimerName), "AudioEnum-%u", pDrvIns->iInstance);
4914 rc = PDMDrvHlpTMTimerCreate(pDrvIns, TMCLOCK_REAL, drvAudioEnumerateTimer, NULL /*pvUser*/,
4915 0 /*fFlags*/, pThis->szEnumTimerName, &pThis->hEnumTimer);
4916 AssertRCReturn(rc, rc);
4917#endif
4918
4919 /*
4920 * Attach the host driver, if present.
4921 */
4922 rc = drvAudioDoAttachInternal(pDrvIns, pThis, fFlags);
4923 if (rc == VERR_PDM_NO_ATTACHED_DRIVER)
4924 rc = VINF_SUCCESS;
4925
4926 LogFlowFuncLeaveRC(rc);
4927 return rc;
4928}
4929
4930/**
4931 * Audio driver registration record.
4932 */
4933const PDMDRVREG g_DrvAUDIO =
4934{
4935 /* u32Version */
4936 PDM_DRVREG_VERSION,
4937 /* szName */
4938 "AUDIO",
4939 /* szRCMod */
4940 "",
4941 /* szR0Mod */
4942 "",
4943 /* pszDescription */
4944 "Audio connector driver",
4945 /* fFlags */
4946 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
4947 /* fClass */
4948 PDM_DRVREG_CLASS_AUDIO,
4949 /* cMaxInstances */
4950 UINT32_MAX,
4951 /* cbInstance */
4952 sizeof(DRVAUDIO),
4953 /* pfnConstruct */
4954 drvAudioConstruct,
4955 /* pfnDestruct */
4956 drvAudioDestruct,
4957 /* pfnRelocate */
4958 NULL,
4959 /* pfnIOCtl */
4960 NULL,
4961 /* pfnPowerOn */
4962 NULL,
4963 /* pfnReset */
4964 NULL,
4965 /* pfnSuspend */
4966 drvAudioSuspend,
4967 /* pfnResume */
4968 drvAudioResume,
4969 /* pfnAttach */
4970 drvAudioAttach,
4971 /* pfnDetach */
4972 drvAudioDetach,
4973 /* pfnPowerOff */
4974 drvAudioPowerOff,
4975 /* pfnSoftReset */
4976 NULL,
4977 /* u32EndVersion */
4978 PDM_DRVREG_VERSION
4979};
4980
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