VirtualBox

source: vbox/trunk/src/VBox/Devices/Audio/DrvHostAudioPulseAudio.cpp@ 89258

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

Audio: Added PDMIHOSTAUDIO::pfnSetDevice with implementation for CoreAudio. Added CoreAudio config values OutputDeviceID and InputDeviceID for the same purpose. bugref:9890

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 78.3 KB
Line 
1/* $Id: DrvHostAudioPulseAudio.cpp 89258 2021-05-25 09:58:08Z vboxsync $ */
2/** @file
3 * Host audio driver - Pulse Audio.
4 */
5
6/*
7 * Copyright (C) 2006-2021 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18
19/*********************************************************************************************************************************
20* Header Files *
21*********************************************************************************************************************************/
22#define LOG_GROUP LOG_GROUP_DRV_HOST_AUDIO
23#include <VBox/log.h>
24#include <VBox/vmm/pdmaudioifs.h>
25#include <VBox/vmm/pdmaudioinline.h>
26#include <VBox/vmm/pdmaudiohostenuminline.h>
27
28#include <stdio.h>
29
30#include <iprt/alloc.h>
31#include <iprt/mem.h>
32#include <iprt/uuid.h>
33#include <iprt/semaphore.h>
34
35#include "DrvHostAudioPulseAudioStubsMangling.h"
36#include "DrvHostAudioPulseAudioStubs.h"
37
38#include <pulse/pulseaudio.h>
39#ifndef PA_STREAM_NOFLAGS
40# define PA_STREAM_NOFLAGS (pa_context_flags_t)0x0000U /* since 0.9.19 */
41#endif
42#ifndef PA_CONTEXT_NOFLAGS
43# define PA_CONTEXT_NOFLAGS (pa_context_flags_t)0x0000U /* since 0.9.19 */
44#endif
45
46#include "VBoxDD.h"
47
48
49/*********************************************************************************************************************************
50* Defines *
51*********************************************************************************************************************************/
52/** Max number of errors reported by drvHostAudioPaError per instance.
53 * @todo Make this configurable thru driver config. */
54#define VBOX_PULSEAUDIO_MAX_LOG_REL_ERRORS 99
55
56
57/** @name PULSEAUDIOENUMCBFLAGS_XXX
58 * @{ */
59/** No flags specified. */
60#define PULSEAUDIOENUMCBFLAGS_NONE 0
61/** (Release) log found devices. */
62#define PULSEAUDIOENUMCBFLAGS_LOG RT_BIT(0)
63/** Only do default devices. */
64#define PULSEAUDIOENUMCBFLAGS_DEFAULT_ONLY RT_BIT(1)
65/** @} */
66
67
68/*********************************************************************************************************************************
69* Structures *
70*********************************************************************************************************************************/
71/** Pointer to the instance data for a pulse audio host audio driver. */
72typedef struct DRVHOSTPULSEAUDIO *PDRVHOSTPULSEAUDIO;
73
74
75/**
76 * Callback context for the server init context state changed callback.
77 */
78typedef struct PULSEAUDIOSTATECHGCTX
79{
80 /** The event semaphore. */
81 RTSEMEVENT hEvtInit;
82 /** The returned context state. */
83 pa_context_state_t volatile enmCtxState;
84} PULSEAUDIOSTATECHGCTX;
85/** Pointer to a server init context state changed callback context. */
86typedef PULSEAUDIOSTATECHGCTX *PPULSEAUDIOSTATECHGCTX;
87
88
89/**
90 * Enumeration callback context used by the pfnGetConfig code.
91 */
92typedef struct PULSEAUDIOENUMCBCTX
93{
94 /** Pointer to PulseAudio's threaded main loop. */
95 pa_threaded_mainloop *pMainLoop;
96 /** Enumeration flags, PULSEAUDIOENUMCBFLAGS_XXX. */
97 uint32_t fFlags;
98 /** VBox status code for the operation.
99 * The caller sets this to VERR_AUDIO_ENUMERATION_FAILED, the callback never
100 * uses that status code. */
101 int32_t rcEnum;
102 /** Name of default sink being used. Must be free'd using RTStrFree(). */
103 char *pszDefaultSink;
104 /** Name of default source being used. Must be free'd using RTStrFree(). */
105 char *pszDefaultSource;
106 /** The device enumeration to fill, NULL if pfnGetConfig context. */
107 PPDMAUDIOHOSTENUM pDeviceEnum;
108} PULSEAUDIOENUMCBCTX;
109/** Pointer to an enumeration callback context. */
110typedef PULSEAUDIOENUMCBCTX *PPULSEAUDIOENUMCBCTX;
111
112
113/**
114 * Pulse audio device enumeration entry.
115 */
116typedef struct PULSEAUDIODEVENTRY
117{
118 /** The part we share with others. */
119 PDMAUDIOHOSTDEV Core;
120 /** The pulse audio name.
121 * @note Kind of must use fixed size field here as that allows
122 * PDMAudioHostDevDup() and PDMAudioHostEnumCopy() to work. */
123 RT_FLEXIBLE_ARRAY_EXTENSION
124 char szPulseName[RT_FLEXIBLE_ARRAY];
125} PULSEAUDIODEVENTRY;
126/** Pointer to a pulse audio device enumeration entry. */
127typedef PULSEAUDIODEVENTRY *PPULSEAUDIODEVENTRY;
128
129
130/**
131 * Pulse audio stream data.
132 */
133typedef struct PULSEAUDIOSTREAM
134{
135 /** Common part. */
136 PDMAUDIOBACKENDSTREAM Core;
137 /** The stream's acquired configuration. */
138 PDMAUDIOSTREAMCFG Cfg;
139 /** Pointer to driver instance. */
140 PDRVHOSTPULSEAUDIO pDrv;
141 /** Pointer to opaque PulseAudio stream. */
142 pa_stream *pStream;
143 /** Pulse sample format and attribute specification. */
144 pa_sample_spec SampleSpec;
145 /** Pulse playback and buffer metrics. */
146 pa_buffer_attr BufAttr;
147 /** Input: Pointer to Pulse sample peek buffer. */
148 const uint8_t *pbPeekBuf;
149 /** Input: Current size (in bytes) of peeked data in buffer. */
150 size_t cbPeekBuf;
151 /** Input: Our offset (in bytes) in peek data buffer. */
152 size_t offPeekBuf;
153 /** Output: Asynchronous drain operation. This is used as an indicator of
154 * whether we're currently draining the stream (will be cleaned up before
155 * resume/re-enable). */
156 pa_operation *pDrainOp;
157 /** Asynchronous cork/uncork operation.
158 * (This solely for cancelling before destroying the stream, so the callback
159 * won't do any after-freed accesses.) */
160 pa_operation *pCorkOp;
161 /** Asynchronous trigger operation.
162 * (This solely for cancelling before destroying the stream, so the callback
163 * won't do any after-freed accesses.) */
164 pa_operation *pTriggerOp;
165 /** Output: Current latency (in microsecs). */
166 uint64_t cUsLatency;
167#ifdef LOG_ENABLED
168 /** Creation timestamp (in microsecs) of stream playback / recording. */
169 pa_usec_t tsStartUs;
170 /** Timestamp (in microsecs) when last read from / written to the stream. */
171 pa_usec_t tsLastReadWrittenUs;
172#endif
173#ifdef DEBUG
174 /** Number of occurred audio data underflows. */
175 uint32_t cUnderflows;
176#endif
177} PULSEAUDIOSTREAM;
178/** Pointer to pulse audio stream data. */
179typedef PULSEAUDIOSTREAM *PPULSEAUDIOSTREAM;
180
181
182/**
183 * Pulse audio host audio driver instance data.
184 * @implements PDMIAUDIOCONNECTOR
185 */
186typedef struct DRVHOSTPULSEAUDIO
187{
188 /** Pointer to the driver instance structure. */
189 PPDMDRVINS pDrvIns;
190 /** Pointer to PulseAudio's threaded main loop. */
191 pa_threaded_mainloop *pMainLoop;
192 /**
193 * Pointer to our PulseAudio context.
194 * @note We use a pMainLoop in a separate thread (pContext).
195 * So either use callback functions or protect these functions
196 * by pa_threaded_mainloop_lock() / pa_threaded_mainloop_unlock().
197 */
198 pa_context *pContext;
199 /** Shutdown indicator. */
200 volatile bool fAbortLoop;
201 /** Error count for not flooding the release log.
202 * Specify UINT32_MAX for unlimited logging. */
203 uint32_t cLogErrors;
204 /** The stream (base) name; needed for distinguishing
205 * streams in the PulseAudio mixer controls if multiple
206 * VMs are running at the same time. */
207 char szStreamName[64];
208 /** Don't want to put this on the stack... */
209 PULSEAUDIOSTATECHGCTX InitStateChgCtx;
210 /** Pointer to host audio interface. */
211 PDMIHOSTAUDIO IHostAudio;
212} DRVHOSTPULSEAUDIO;
213
214
215
216/*
217 * Glue to make the code work systems with PulseAudio < 0.9.11.
218 */
219#if !defined(PA_CONTEXT_IS_GOOD) && PA_API_VERSION < 12 /* 12 = 0.9.11 where PA_STREAM_IS_GOOD was added */
220DECLINLINE(bool) PA_CONTEXT_IS_GOOD(pa_context_state_t enmState)
221{
222 return enmState == PA_CONTEXT_CONNECTING
223 || enmState == PA_CONTEXT_AUTHORIZING
224 || enmState == PA_CONTEXT_SETTING_NAME
225 || enmState == PA_CONTEXT_READY;
226}
227#endif
228
229#if !defined(PA_STREAM_IS_GOOD) && PA_API_VERSION < 12 /* 12 = 0.9.11 where PA_STREAM_IS_GOOD was added */
230DECLINLINE(bool) PA_STREAM_IS_GOOD(pa_stream_state_t enmState)
231{
232 return enmState == PA_STREAM_CREATING
233 || enmState == PA_STREAM_READY;
234}
235#endif
236
237
238/**
239 * Converts a pulse audio error to a VBox status.
240 *
241 * @returns VBox status code.
242 * @param rcPa The error code to convert.
243 */
244static int drvHostAudioPaErrorToVBox(int rcPa)
245{
246 /** @todo Implement some PulseAudio -> VBox mapping here. */
247 RT_NOREF(rcPa);
248 return VERR_GENERAL_FAILURE;
249}
250
251
252/**
253 * Logs a pulse audio (from context) and converts it to VBox status.
254 *
255 * @returns VBox status code.
256 * @param pThis Our instance data.
257 * @param pszFormat The format string for the release log (no newline) .
258 * @param ... Format string arguments.
259 */
260static int drvHostAudioPaError(PDRVHOSTPULSEAUDIO pThis, const char *pszFormat, ...)
261{
262 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
263 AssertPtr(pszFormat);
264
265 int const rcPa = pa_context_errno(pThis->pContext);
266 int const rcVBox = drvHostAudioPaErrorToVBox(rcPa);
267
268 if ( pThis->cLogErrors < VBOX_PULSEAUDIO_MAX_LOG_REL_ERRORS
269 && LogRelIs2Enabled())
270 {
271 va_list va;
272 va_start(va, pszFormat);
273 LogRel(("PulseAudio: %N: %s (%d, %Rrc)\n", pszFormat, &va, pa_strerror(rcPa), rcPa, rcVBox));
274 va_end(va);
275
276 if (++pThis->cLogErrors == VBOX_PULSEAUDIO_MAX_LOG_REL_ERRORS)
277 LogRel(("PulseAudio: muting errors (max %u)\n", VBOX_PULSEAUDIO_MAX_LOG_REL_ERRORS));
278 }
279
280 return rcVBox;
281}
282
283
284/**
285 * Signal the main loop to abort. Just signalling isn't sufficient as the
286 * mainloop might not have been entered yet.
287 */
288static void drvHostAudioPaSignalWaiter(PDRVHOSTPULSEAUDIO pThis)
289{
290 if (pThis)
291 {
292 pThis->fAbortLoop = true;
293 pa_threaded_mainloop_signal(pThis->pMainLoop, 0);
294 }
295}
296
297
298/**
299 * Wrapper around pa_threaded_mainloop_wait().
300 */
301static void drvHostAudioPaMainloopWait(PDRVHOSTPULSEAUDIO pThis)
302{
303 /** @todo r=bird: explain this logic. */
304 if (!pThis->fAbortLoop)
305 pa_threaded_mainloop_wait(pThis->pMainLoop);
306 pThis->fAbortLoop = false;
307}
308
309
310/**
311 * Pulse audio callback for context status changes, init variant.
312 */
313static void drvHostAudioPaCtxCallbackStateChanged(pa_context *pCtx, void *pvUser)
314{
315 AssertPtrReturnVoid(pCtx);
316
317 PDRVHOSTPULSEAUDIO pThis = (PDRVHOSTPULSEAUDIO)pvUser;
318 AssertPtrReturnVoid(pThis);
319
320 switch (pa_context_get_state(pCtx))
321 {
322 case PA_CONTEXT_READY:
323 case PA_CONTEXT_TERMINATED:
324 case PA_CONTEXT_FAILED:
325 drvHostAudioPaSignalWaiter(pThis);
326 break;
327
328 default:
329 break;
330 }
331}
332
333
334/**
335 * Synchronously wait until an operation completed.
336 *
337 * This will consume the pOperation reference.
338 */
339static int drvHostAudioPaWaitForEx(PDRVHOSTPULSEAUDIO pThis, pa_operation *pOperation, RTMSINTERVAL cMsTimeout)
340{
341 AssertPtrReturn(pOperation, VERR_INVALID_POINTER);
342
343 uint64_t const msStart = RTTimeMilliTS();
344 pa_operation_state_t enmOpState;
345 while ((enmOpState = pa_operation_get_state(pOperation)) == PA_OPERATION_RUNNING)
346 {
347 if (!pThis->fAbortLoop) /** @todo r=bird: I do _not_ get the logic behind this fAbortLoop mechanism, it looks more
348 * than a little mixed up and too much generalized see drvHostAudioPaSignalWaiter. */
349 {
350 AssertPtr(pThis->pMainLoop);
351 pa_threaded_mainloop_wait(pThis->pMainLoop);
352 if ( !pThis->pContext
353 || pa_context_get_state(pThis->pContext) != PA_CONTEXT_READY)
354 {
355 pa_operation_cancel(pOperation);
356 pa_operation_unref(pOperation);
357 LogRel(("PulseAudio: pa_context_get_state context not ready\n"));
358 return VERR_INVALID_STATE;
359 }
360 }
361 pThis->fAbortLoop = false;
362
363 /*
364 * Note! This timeout business is a bit bogus as pa_threaded_mainloop_wait is indefinite.
365 */
366 if (RTTimeMilliTS() - msStart >= cMsTimeout)
367 {
368 enmOpState = pa_operation_get_state(pOperation);
369 if (enmOpState != PA_OPERATION_RUNNING)
370 break;
371 pa_operation_cancel(pOperation);
372 pa_operation_unref(pOperation);
373 return VERR_TIMEOUT;
374 }
375 }
376
377 pa_operation_unref(pOperation);
378 if (enmOpState == PA_OPERATION_DONE)
379 return VINF_SUCCESS;
380 return VERR_CANCELLED;
381}
382
383
384static int drvHostAudioPaWaitFor(PDRVHOSTPULSEAUDIO pThis, pa_operation *pOP)
385{
386 return drvHostAudioPaWaitForEx(pThis, pOP, 10 * RT_MS_1SEC);
387}
388
389
390
391/*********************************************************************************************************************************
392* PDMIHOSTAUDIO *
393*********************************************************************************************************************************/
394
395/**
396 * Worker for drvHostAudioPaEnumSourceCallback() and
397 * drvHostAudioPaEnumSinkCallback() that adds an entry to the enumeration
398 * result.
399 */
400static void drvHostAudioPaEnumAddDevice(PPULSEAUDIOENUMCBCTX pCbCtx, PDMAUDIODIR enmDir, const char *pszName,
401 const char *pszDesc, uint8_t cChannelsInput, uint8_t cChannelsOutput,
402 const char *pszDefaultName)
403{
404 size_t const cchName = strlen(pszName);
405 PPULSEAUDIODEVENTRY pDev = (PPULSEAUDIODEVENTRY)PDMAudioHostDevAlloc(RT_UOFFSETOF(PULSEAUDIODEVENTRY, szPulseName)
406 + RT_ALIGN_Z(cchName + 1, 16));
407 if (pDev != NULL)
408 {
409 memcpy(pDev->szPulseName, pszName, cchName);
410 pDev->szPulseName[cchName] = '\0';
411
412 pDev->Core.enmUsage = enmDir;
413 pDev->Core.enmType = RTStrIStr(pszDesc, "built-in") != NULL
414 ? PDMAUDIODEVICETYPE_BUILTIN : PDMAUDIODEVICETYPE_UNKNOWN;
415 if (RTStrCmp(pszName, pszDefaultName) != 0)
416 pDev->Core.fFlags = PDMAUDIOHOSTDEV_F_NONE;
417 else
418 pDev->Core.fFlags = enmDir == PDMAUDIODIR_IN ? PDMAUDIOHOSTDEV_F_DEFAULT_IN : PDMAUDIOHOSTDEV_F_DEFAULT_OUT;
419 pDev->Core.cMaxInputChannels = cChannelsInput;
420 pDev->Core.cMaxOutputChannels = cChannelsOutput;
421 RTStrCopy(pDev->Core.szName, sizeof(pDev->Core.szName),
422 pszDesc && *pszDesc ? pszDesc : pszName);
423
424 PDMAudioHostEnumAppend(pCbCtx->pDeviceEnum, &pDev->Core);
425 }
426 else
427 pCbCtx->rcEnum = VERR_NO_MEMORY;
428}
429
430
431/**
432 * Enumeration callback - source info.
433 *
434 * @param pCtx The context (DRVHOSTPULSEAUDIO::pContext).
435 * @param pInfo The info. NULL when @a eol is not zero.
436 * @param eol Error-or-last indicator or something like that:
437 * - 0: Normal call with info.
438 * - 1: End of list, no info.
439 * - -1: Error callback, no info.
440 * @param pvUserData Pointer to our PULSEAUDIOENUMCBCTX structure.
441 */
442static void drvHostAudioPaEnumSourceCallback(pa_context *pCtx, const pa_source_info *pInfo, int eol, void *pvUserData)
443{
444 LogFlowFunc(("pCtx=%p pInfo=%p eol=%d pvUserData=%p\n", pCtx, pInfo, eol, pvUserData));
445 PPULSEAUDIOENUMCBCTX pCbCtx = (PPULSEAUDIOENUMCBCTX)pvUserData;
446 AssertPtrReturnVoid(pCbCtx);
447 Assert((pInfo == NULL) == (eol != 0));
448 RT_NOREF(pCtx);
449
450 if (eol == 0 && pInfo != NULL)
451 {
452 LogRel2(("Pulse Audio: Source #%u: %u Hz %uch format=%u name='%s' desc='%s' driver='%s' flags=%#x\n",
453 pInfo->index, pInfo->sample_spec.rate, pInfo->sample_spec.channels, pInfo->sample_spec.format,
454 pInfo->name, pInfo->description, pInfo->driver, pInfo->flags));
455 drvHostAudioPaEnumAddDevice(pCbCtx, PDMAUDIODIR_IN, pInfo->name, pInfo->description,
456 pInfo->sample_spec.channels, 0 /*cChannelsOutput*/, pCbCtx->pszDefaultSource);
457 }
458 else if (eol == 1 && !pInfo && pCbCtx->rcEnum == VERR_AUDIO_ENUMERATION_FAILED)
459 pCbCtx->rcEnum = VINF_SUCCESS;
460
461 /* Wake up the calling thread when done: */
462 if (eol != 0)
463 pa_threaded_mainloop_signal(pCbCtx->pMainLoop, 0);
464}
465
466
467/**
468 * Enumeration callback - sink info.
469 *
470 * @param pCtx The context (DRVHOSTPULSEAUDIO::pContext).
471 * @param pInfo The info. NULL when @a eol is not zero.
472 * @param eol Error-or-last indicator or something like that:
473 * - 0: Normal call with info.
474 * - 1: End of list, no info.
475 * - -1: Error callback, no info.
476 * @param pvUserData Pointer to our PULSEAUDIOENUMCBCTX structure.
477 */
478static void drvHostAudioPaEnumSinkCallback(pa_context *pCtx, const pa_sink_info *pInfo, int eol, void *pvUserData)
479{
480 LogFlowFunc(("pCtx=%p pInfo=%p eol=%d pvUserData=%p\n", pCtx, pInfo, eol, pvUserData));
481 PPULSEAUDIOENUMCBCTX pCbCtx = (PPULSEAUDIOENUMCBCTX)pvUserData;
482 AssertPtrReturnVoid(pCbCtx);
483 Assert((pInfo == NULL) == (eol != 0));
484 RT_NOREF(pCtx);
485
486 if (eol == 0 && pInfo != NULL)
487 {
488 LogRel2(("Pulse Audio: Sink #%u: %u Hz %uch format=%u name='%s' desc='%s' driver='%s' flags=%#x\n",
489 pInfo->index, pInfo->sample_spec.rate, pInfo->sample_spec.channels, pInfo->sample_spec.format,
490 pInfo->name, pInfo->description, pInfo->driver, pInfo->flags));
491 drvHostAudioPaEnumAddDevice(pCbCtx, PDMAUDIODIR_OUT, pInfo->name, pInfo->description,
492 0 /*cChannelsInput*/, pInfo->sample_spec.channels, pCbCtx->pszDefaultSink);
493 }
494 else if (eol == 1 && !pInfo && pCbCtx->rcEnum == VERR_AUDIO_ENUMERATION_FAILED)
495 pCbCtx->rcEnum = VINF_SUCCESS;
496
497 /* Wake up the calling thread when done: */
498 if (eol != 0)
499 pa_threaded_mainloop_signal(pCbCtx->pMainLoop, 0);
500}
501
502
503/**
504 * Enumeration callback - service info.
505 *
506 * Copy down the default names.
507 */
508static void drvHostAudioPaEnumServerCallback(pa_context *pCtx, const pa_server_info *pInfo, void *pvUserData)
509{
510 LogFlowFunc(("pCtx=%p pInfo=%p pvUserData=%p\n", pCtx, pInfo, pvUserData));
511 PPULSEAUDIOENUMCBCTX pCbCtx = (PPULSEAUDIOENUMCBCTX)pvUserData;
512 AssertPtrReturnVoid(pCbCtx);
513 RT_NOREF(pCtx);
514
515 if (pInfo)
516 {
517 LogRel2(("PulseAudio: Server info: user=%s host=%s ver=%s name=%s defsink=%s defsrc=%s spec: %d %uHz %uch\n",
518 pInfo->user_name, pInfo->host_name, pInfo->server_version, pInfo->server_name,
519 pInfo->default_sink_name, pInfo->default_source_name,
520 pInfo->sample_spec.format, pInfo->sample_spec.rate, pInfo->sample_spec.channels));
521
522 Assert(!pCbCtx->pszDefaultSink);
523 Assert(!pCbCtx->pszDefaultSource);
524 Assert(pCbCtx->rcEnum == VERR_AUDIO_ENUMERATION_FAILED);
525 pCbCtx->rcEnum = VINF_SUCCESS;
526
527 if (pInfo->default_sink_name)
528 {
529 Assert(RTStrIsValidEncoding(pInfo->default_sink_name));
530 pCbCtx->pszDefaultSink = RTStrDup(pInfo->default_sink_name);
531 AssertStmt(pCbCtx->pszDefaultSink, pCbCtx->rcEnum = VERR_NO_STR_MEMORY);
532 }
533
534 if (pInfo->default_source_name)
535 {
536 Assert(RTStrIsValidEncoding(pInfo->default_source_name));
537 pCbCtx->pszDefaultSource = RTStrDup(pInfo->default_source_name);
538 AssertStmt(pCbCtx->pszDefaultSource, pCbCtx->rcEnum = VERR_NO_STR_MEMORY);
539 }
540 }
541 else
542 pCbCtx->rcEnum = VERR_INVALID_POINTER;
543
544 pa_threaded_mainloop_signal(pCbCtx->pMainLoop, 0);
545}
546
547
548/**
549 * @note Called with the PA main loop locked.
550 */
551static int drvHostAudioPaEnumerate(PDRVHOSTPULSEAUDIO pThis, uint32_t fEnum, PPDMAUDIOHOSTENUM pDeviceEnum)
552{
553 PULSEAUDIOENUMCBCTX CbCtx = { pThis->pMainLoop, fEnum, VERR_AUDIO_ENUMERATION_FAILED, NULL, NULL, pDeviceEnum };
554 bool const fLog = (fEnum & PULSEAUDIOENUMCBFLAGS_LOG);
555 bool const fOnlyDefault = (fEnum & PULSEAUDIOENUMCBFLAGS_DEFAULT_ONLY);
556 int rc;
557
558 /*
559 * Check if server information is available and bail out early if it isn't.
560 * This should give us a default (playback) sink and (recording) source.
561 */
562 LogRel(("PulseAudio: Retrieving server information ...\n"));
563 CbCtx.rcEnum = VERR_AUDIO_ENUMERATION_FAILED;
564 pa_operation *paOpServerInfo = pa_context_get_server_info(pThis->pContext, drvHostAudioPaEnumServerCallback, &CbCtx);
565 if (paOpServerInfo)
566 rc = drvHostAudioPaWaitFor(pThis, paOpServerInfo);
567 else
568 {
569 LogRel(("PulseAudio: Server information not available, skipping enumeration.\n"));
570 return VINF_SUCCESS;
571 }
572 if (RT_SUCCESS(rc))
573 rc = CbCtx.rcEnum;
574 if (RT_FAILURE(rc))
575 {
576 if (fLog)
577 LogRel(("PulseAudio: Error enumerating PulseAudio server properties: %Rrc\n", rc));
578 return rc;
579 }
580
581 /*
582 * Get info about the playback sink.
583 */
584 if (fLog && CbCtx.pszDefaultSink)
585 LogRel2(("PulseAudio: Default output sink is '%s'\n", CbCtx.pszDefaultSink));
586 else if (fLog)
587 LogRel2(("PulseAudio: No default output sink found\n"));
588
589 if (CbCtx.pszDefaultSink || !fOnlyDefault)
590 {
591 CbCtx.rcEnum = VERR_AUDIO_ENUMERATION_FAILED;
592 if (!fOnlyDefault)
593 rc = drvHostAudioPaWaitFor(pThis,
594 pa_context_get_sink_info_list(pThis->pContext, drvHostAudioPaEnumSinkCallback, &CbCtx));
595 else
596 rc = drvHostAudioPaWaitFor(pThis, pa_context_get_sink_info_by_name(pThis->pContext, CbCtx.pszDefaultSink,
597 drvHostAudioPaEnumSinkCallback, &CbCtx));
598 if (RT_SUCCESS(rc))
599 rc = CbCtx.rcEnum;
600 if (fLog && RT_FAILURE(rc))
601 LogRel(("PulseAudio: Error enumerating properties for default output sink '%s': %Rrc\n",
602 CbCtx.pszDefaultSink, rc));
603 }
604
605 /*
606 * Get info about the recording source.
607 */
608 if (fLog && CbCtx.pszDefaultSource)
609 LogRel2(("PulseAudio: Default input source is '%s'\n", CbCtx.pszDefaultSource));
610 else if (fLog)
611 LogRel2(("PulseAudio: No default input source found\n"));
612 if (CbCtx.pszDefaultSource || !fOnlyDefault)
613 {
614 CbCtx.rcEnum = VERR_AUDIO_ENUMERATION_FAILED;
615 int rc2;
616 if (!fOnlyDefault)
617 rc2 = drvHostAudioPaWaitFor(pThis, pa_context_get_source_info_list(pThis->pContext,
618 drvHostAudioPaEnumSourceCallback, &CbCtx));
619 else
620 rc2 = drvHostAudioPaWaitFor(pThis, pa_context_get_source_info_by_name(pThis->pContext, CbCtx.pszDefaultSource,
621 drvHostAudioPaEnumSourceCallback, &CbCtx));
622 if (RT_SUCCESS(rc2))
623 rc2 = CbCtx.rcEnum;
624 if (fLog && RT_FAILURE(rc2))
625 LogRel(("PulseAudio: Error enumerating properties for default input source '%s': %Rrc\n",
626 CbCtx.pszDefaultSource, rc));
627 if (RT_SUCCESS(rc))
628 rc = rc2;
629 }
630
631 /* clean up */
632 RTStrFree(CbCtx.pszDefaultSink);
633 RTStrFree(CbCtx.pszDefaultSource);
634
635 LogFlowFuncLeaveRC(rc);
636 return rc;
637}
638
639
640/**
641 * @interface_method_impl{PDMIHOSTAUDIO,pfnGetConfig}
642 */
643static DECLCALLBACK(int) drvHostAudioPaHA_GetConfig(PPDMIHOSTAUDIO pInterface, PPDMAUDIOBACKENDCFG pBackendCfg)
644{
645 PDRVHOSTPULSEAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVHOSTPULSEAUDIO, IHostAudio);
646 AssertPtrReturn(pBackendCfg, VERR_INVALID_POINTER);
647
648 /*
649 * The configuration.
650 */
651 RTStrCopy(pBackendCfg->szName, sizeof(pBackendCfg->szName), "PulseAudio");
652 pBackendCfg->cbStream = sizeof(PULSEAUDIOSTREAM);
653 pBackendCfg->fFlags = 0;
654 pBackendCfg->cMaxStreamsOut = UINT32_MAX;
655 pBackendCfg->cMaxStreamsIn = UINT32_MAX;
656
657#if 0
658 /*
659 * In case we want to gather info about default devices, we can do this:
660 */
661 PDMAUDIOHOSTENUM DeviceEnum;
662 PDMAudioHostEnumInit(&DeviceEnum);
663 pa_threaded_mainloop_lock(pThis->pMainLoop);
664 int rc = drvHostAudioPaEnumerate(pThis, PULSEAUDIOENUMCBFLAGS_DEFAULT_ONLY | PULSEAUDIOENUMCBFLAGS_LOG, &DeviceEnum);
665 pa_threaded_mainloop_unlock(pThis->pMainLoop);
666 AssertRCReturn(rc, rc);
667 /** @todo do stuff with DeviceEnum. */
668 PDMAudioHostEnumDelete(&DeviceEnum);
669#else
670 RT_NOREF(pThis);
671#endif
672 return VINF_SUCCESS;
673}
674
675
676/**
677 * @interface_method_impl{PDMIHOSTAUDIO,pfnGetDevices}
678 */
679static DECLCALLBACK(int) drvHostAudioPaHA_GetDevices(PPDMIHOSTAUDIO pInterface, PPDMAUDIOHOSTENUM pDeviceEnum)
680{
681 PDRVHOSTPULSEAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVHOSTPULSEAUDIO, IHostAudio);
682 AssertPtrReturn(pDeviceEnum, VERR_INVALID_POINTER);
683 PDMAudioHostEnumInit(pDeviceEnum);
684
685 /* Refine it or something (currently only some LogRel2 stuff): */
686 pa_threaded_mainloop_lock(pThis->pMainLoop);
687 int rc = drvHostAudioPaEnumerate(pThis, PULSEAUDIOENUMCBFLAGS_NONE, pDeviceEnum);
688 pa_threaded_mainloop_unlock(pThis->pMainLoop);
689 return rc;
690}
691
692
693/**
694 * @interface_method_impl{PDMIHOSTAUDIO,pfnGetStatus}
695 */
696static DECLCALLBACK(PDMAUDIOBACKENDSTS) drvHostAudioPaHA_GetStatus(PPDMIHOSTAUDIO pInterface, PDMAUDIODIR enmDir)
697{
698 RT_NOREF(pInterface, enmDir);
699 return PDMAUDIOBACKENDSTS_RUNNING;
700}
701
702
703/**
704 * Stream status changed.
705 */
706static void drvHostAudioPaStreamStateChangedCallback(pa_stream *pStream, void *pvUser)
707{
708 AssertPtrReturnVoid(pStream);
709
710 PDRVHOSTPULSEAUDIO pThis = (PDRVHOSTPULSEAUDIO)pvUser;
711 AssertPtrReturnVoid(pThis);
712
713 switch (pa_stream_get_state(pStream))
714 {
715 case PA_STREAM_READY:
716 case PA_STREAM_FAILED:
717 case PA_STREAM_TERMINATED:
718 drvHostAudioPaSignalWaiter(pThis);
719 break;
720
721 default:
722 break;
723 }
724}
725
726#ifdef DEBUG
727
728/**
729 * Debug PA callback: Need data to output.
730 */
731static void drvHostAudioPaStreamReqWriteDebugCallback(pa_stream *pStream, size_t cbLen, void *pvContext)
732{
733 RT_NOREF(cbLen, pvContext);
734 pa_usec_t cUsLatency = 0;
735 int fNegative = 0;
736 int rcPa = pa_stream_get_latency(pStream, &cUsLatency, &fNegative);
737 Log2Func(("Requesting %zu bytes; Latency: %'RU64 us%s\n",
738 cbLen, cUsLatency, rcPa == 0 ? " - pa_stream_get_latency failed!" : ""));
739}
740
741
742/**
743 * Debug PA callback: Underflow. This may happen when draing/corking.
744 */
745static void drvHostAudioPaStreamUnderflowDebugCallback(pa_stream *pStream, void *pvContext)
746{
747 PPULSEAUDIOSTREAM pStrm = (PPULSEAUDIOSTREAM)pvContext;
748 AssertPtrReturnVoid(pStrm);
749
750 pStrm->cUnderflows++;
751
752 LogRel2(("PulseAudio: Warning: Hit underflow #%RU32\n", pStrm->cUnderflows));
753
754 if ( pStrm->cUnderflows >= 6 /** @todo Make this check configurable. */
755 && pStrm->cUsLatency < 2U*RT_US_1SEC)
756 {
757 pStrm->cUsLatency = pStrm->cUsLatency * 3 / 2;
758 LogRel2(("PulseAudio: Increasing output latency to %'RU64 us\n", pStrm->cUsLatency));
759
760 pStrm->BufAttr.maxlength = pa_usec_to_bytes(pStrm->cUsLatency, &pStrm->SampleSpec);
761 pStrm->BufAttr.tlength = pa_usec_to_bytes(pStrm->cUsLatency, &pStrm->SampleSpec);
762 pa_operation *pOperation = pa_stream_set_buffer_attr(pStream, &pStrm->BufAttr, NULL, NULL);
763 if (pOperation)
764 pa_operation_unref(pOperation);
765 else
766 LogRel2(("pa_stream_set_buffer_attr failed!\n"));
767
768 pStrm->cUnderflows = 0;
769 }
770
771 pa_usec_t cUsLatency = 0;
772 int fNegative = 0;
773 pa_stream_get_latency(pStream, &cUsLatency, &fNegative);
774 LogRel2(("PulseAudio: Latency now is %'RU64 us\n", cUsLatency));
775
776# ifdef LOG_ENABLED
777 if (LogIs2Enabled())
778 {
779 const pa_timing_info *pTInfo = pa_stream_get_timing_info(pStream);
780 AssertReturnVoid(pTInfo);
781 const pa_sample_spec *pSpec = pa_stream_get_sample_spec(pStream);
782 AssertReturnVoid(pSpec);
783 Log2Func(("writepos=%'RU64 us, readpost=%'RU64 us, age=%'RU64 us, latency=%'RU64 us (%RU32Hz %RU8ch)\n",
784 pa_bytes_to_usec(pTInfo->write_index, pSpec), pa_bytes_to_usec(pTInfo->read_index, pSpec),
785 pa_rtclock_now() - pStrm->tsStartUs, cUsLatency, pSpec->rate, pSpec->channels));
786 }
787# endif
788}
789
790
791/**
792 * Debug PA callback: Overflow. This may happen when draing/corking.
793 */
794static void drvHostAudioPaStreamOverflowDebugCallback(pa_stream *pStream, void *pvContext)
795{
796 RT_NOREF(pStream, pvContext);
797 Log2Func(("Warning: Hit overflow\n"));
798}
799
800#endif /* DEBUG */
801
802/**
803 * Converts from PDM PCM properties to pulse audio format.
804 *
805 * Worker for the stream creation code.
806 *
807 * @returns PA format.
808 * @retval PA_SAMPLE_INVALID if format not supported.
809 * @param pProps The PDM audio source properties.
810 */
811static pa_sample_format_t drvHostAudioPaPropsToPulse(PCPDMAUDIOPCMPROPS pProps)
812{
813 switch (PDMAudioPropsSampleSize(pProps))
814 {
815 case 1:
816 if (!PDMAudioPropsIsSigned(pProps))
817 return PA_SAMPLE_U8;
818 break;
819
820 case 2:
821 if (PDMAudioPropsIsSigned(pProps))
822 return PDMAudioPropsIsLittleEndian(pProps) ? PA_SAMPLE_S16LE : PA_SAMPLE_S16BE;
823 break;
824
825#ifdef PA_SAMPLE_S32LE
826 case 4:
827 if (PDMAudioPropsIsSigned(pProps))
828 return PDMAudioPropsIsLittleEndian(pProps) ? PA_SAMPLE_S32LE : PA_SAMPLE_S32BE;
829 break;
830#endif
831 }
832
833 AssertMsgFailed(("%RU8%s not supported\n", PDMAudioPropsSampleSize(pProps), PDMAudioPropsIsSigned(pProps) ? "S" : "U"));
834 return PA_SAMPLE_INVALID;
835}
836
837
838/**
839 * Converts from pulse audio sample specification to PDM PCM audio properties.
840 *
841 * Worker for the stream creation code.
842 *
843 * @returns VBox status code.
844 * @param pProps The PDM audio source properties.
845 * @param enmPulseFmt The PA format.
846 * @param cChannels The number of channels.
847 * @param uHz The frequency.
848 */
849static int drvHostAudioPaToAudioProps(PPDMAUDIOPCMPROPS pProps, pa_sample_format_t enmPulseFmt, uint8_t cChannels, uint32_t uHz)
850{
851 AssertReturn(cChannels > 0, VERR_INVALID_PARAMETER);
852 AssertReturn(cChannels < 16, VERR_INVALID_PARAMETER);
853
854 switch (enmPulseFmt)
855 {
856 case PA_SAMPLE_U8:
857 PDMAudioPropsInit(pProps, 1 /*8-bit*/, false /*signed*/, cChannels, uHz);
858 break;
859
860 case PA_SAMPLE_S16LE:
861 PDMAudioPropsInitEx(pProps, 2 /*16-bit*/, true /*signed*/, cChannels, uHz, true /*fLittleEndian*/, false /*fRaw*/);
862 break;
863
864 case PA_SAMPLE_S16BE:
865 PDMAudioPropsInitEx(pProps, 2 /*16-bit*/, true /*signed*/, cChannels, uHz, false /*fLittleEndian*/, false /*fRaw*/);
866 break;
867
868#ifdef PA_SAMPLE_S32LE
869 case PA_SAMPLE_S32LE:
870 PDMAudioPropsInitEx(pProps, 4 /*32-bit*/, true /*signed*/, cChannels, uHz, true /*fLittleEndian*/, false /*fRaw*/);
871 break;
872#endif
873
874#ifdef PA_SAMPLE_S32BE
875 case PA_SAMPLE_S32BE:
876 PDMAudioPropsInitEx(pProps, 4 /*32-bit*/, true /*signed*/, cChannels, uHz, false /*fLittleEndian*/, false /*fRaw*/);
877 break;
878#endif
879
880 default:
881 AssertLogRelMsgFailed(("PulseAudio: Format (%d) not supported\n", enmPulseFmt));
882 return VERR_NOT_SUPPORTED;
883 }
884
885 return VINF_SUCCESS;
886}
887
888
889/**
890 * Worker that does the actual creation of an PA stream.
891 *
892 * @returns VBox status code.
893 * @param pThis Our driver instance data.
894 * @param pStreamPA Our stream data.
895 * @param pszName How we name the stream.
896 * @param pCfgAcq The requested stream properties, the Props member is
897 * updated upon successful return.
898 *
899 * @note Caller owns the mainloop lock.
900 */
901static int drvHostAudioPaStreamCreateLocked(PDRVHOSTPULSEAUDIO pThis, PPULSEAUDIOSTREAM pStreamPA,
902 const char *pszName, PPDMAUDIOSTREAMCFG pCfgAcq)
903{
904 /*
905 * Create the stream.
906 */
907 pa_stream *pStream = pa_stream_new(pThis->pContext, pszName, &pStreamPA->SampleSpec, NULL /* pa_channel_map */);
908 if (!pStream)
909 {
910 LogRel(("PulseAudio: Failed to create stream '%s': %s (%d)\n",
911 pszName, pa_strerror(pa_context_errno(pThis->pContext)), pa_context_errno(pThis->pContext)));
912 return VERR_AUDIO_STREAM_COULD_NOT_CREATE;
913 }
914
915 /*
916 * Set the state callback, and in debug builds a few more...
917 */
918#ifdef DEBUG
919 pa_stream_set_write_callback( pStream, drvHostAudioPaStreamReqWriteDebugCallback, pStreamPA);
920 pa_stream_set_underflow_callback( pStream, drvHostAudioPaStreamUnderflowDebugCallback, pStreamPA);
921 if (pCfgAcq->enmDir == PDMAUDIODIR_OUT)
922 pa_stream_set_overflow_callback(pStream, drvHostAudioPaStreamOverflowDebugCallback, pStreamPA);
923#endif
924 pa_stream_set_state_callback( pStream, drvHostAudioPaStreamStateChangedCallback, pThis);
925
926 /*
927 * Connect the stream.
928 */
929 int rc;
930 unsigned const fFlags = PA_STREAM_START_CORKED /* Require explicit starting (uncorking). */
931 /* For using pa_stream_get_latency() and pa_stream_get_time(). */
932 | PA_STREAM_INTERPOLATE_TIMING | PA_STREAM_AUTO_TIMING_UPDATE
933#if PA_API_VERSION >= 12
934 | PA_STREAM_ADJUST_LATENCY
935#endif
936 ;
937 if (pCfgAcq->enmDir == PDMAUDIODIR_IN)
938 {
939 LogFunc(("Input stream attributes: maxlength=%d fragsize=%d\n",
940 pStreamPA->BufAttr.maxlength, pStreamPA->BufAttr.fragsize));
941 rc = pa_stream_connect_record(pStream, NULL /*dev*/, &pStreamPA->BufAttr, (pa_stream_flags_t)fFlags);
942 }
943 else
944 {
945 LogFunc(("Output buffer attributes: maxlength=%d tlength=%d prebuf=%d minreq=%d\n",
946 pStreamPA->BufAttr.maxlength, pStreamPA->BufAttr.tlength, pStreamPA->BufAttr.prebuf, pStreamPA->BufAttr.minreq));
947 rc = pa_stream_connect_playback(pStream, NULL /*dev*/, &pStreamPA->BufAttr, (pa_stream_flags_t)fFlags,
948 NULL /*volume*/, NULL /*sync_stream*/);
949 }
950 if (rc >= 0)
951 {
952 /*
953 * Wait for the stream to become ready.
954 */
955 uint64_t const nsStart = RTTimeNanoTS();
956 pa_stream_state_t enmStreamState;
957 while ( (enmStreamState = pa_stream_get_state(pStream)) != PA_STREAM_READY
958 && PA_STREAM_IS_GOOD(enmStreamState)
959 && RTTimeNanoTS() - nsStart < RT_NS_10SEC /* not really timed */ )
960 drvHostAudioPaMainloopWait(pThis);
961 if (enmStreamState == PA_STREAM_READY)
962 {
963 LogFunc(("Connecting stream took %'RU64 ns\n", RTTimeNanoTS() - nsStart));
964#ifdef LOG_ENABLED
965 pStreamPA->tsStartUs = pa_rtclock_now();
966#endif
967 /*
968 * Update the buffer attributes.
969 */
970 const pa_buffer_attr *pBufAttribs = pa_stream_get_buffer_attr(pStream);
971 AssertPtr(pBufAttribs);
972 if (pBufAttribs)
973 {
974 pStreamPA->BufAttr = *pBufAttribs;
975 LogFunc(("Obtained %s buffer attributes: maxlength=%RU32 tlength=%RU32 prebuf=%RU32 minreq=%RU32 fragsize=%RU32\n",
976 pCfgAcq->enmDir == PDMAUDIODIR_IN ? "input" : "output", pBufAttribs->maxlength, pBufAttribs->tlength,
977 pBufAttribs->prebuf, pBufAttribs->minreq, pBufAttribs->fragsize));
978
979 /*
980 * Convert the sample spec back to PDM speak.
981 * Note! This isn't strictly speaking needed as SampleSpec has *not* been
982 * modified since the caller converted it from pCfgReq.
983 */
984 rc = drvHostAudioPaToAudioProps(&pCfgAcq->Props, pStreamPA->SampleSpec.format,
985 pStreamPA->SampleSpec.channels, pStreamPA->SampleSpec.rate);
986 if (RT_SUCCESS(rc))
987 {
988 pStreamPA->pStream = pStream;
989 LogFlowFunc(("returns VINF_SUCCESS\n"));
990 return VINF_SUCCESS;
991 }
992 }
993 else
994 {
995 LogRelMax(99, ("PulseAudio: Failed to get buffer attribs for stream '%s': %s (%d)\n",
996 pszName, pa_strerror(pa_context_errno(pThis->pContext)), pa_context_errno(pThis->pContext)));
997 rc = VERR_AUDIO_STREAM_COULD_NOT_CREATE;
998 }
999 }
1000 else
1001 {
1002 LogRelMax(99, ("PulseAudio: Failed to initialize stream '%s': state=%d, waited %'RU64 ns\n",
1003 pszName, enmStreamState, RTTimeNanoTS() - nsStart));
1004 rc = VERR_AUDIO_STREAM_COULD_NOT_CREATE;
1005 }
1006 pa_stream_disconnect(pStream);
1007 }
1008 else
1009 {
1010 LogRelMax(99, ("PulseAudio: Could not connect %s stream '%s': %s (%d/%d)\n",
1011 pCfgAcq->enmDir == PDMAUDIODIR_IN ? "input" : "output",
1012 pszName, pa_strerror(pa_context_errno(pThis->pContext)), pa_context_errno(pThis->pContext), rc));
1013 rc = VERR_AUDIO_STREAM_COULD_NOT_CREATE;
1014 }
1015
1016 pa_stream_unref(pStream);
1017 Assert(RT_FAILURE_NP(rc));
1018 LogFlowFunc(("returns %Rrc\n", rc));
1019 return rc;
1020}
1021
1022
1023/**
1024 * @interface_method_impl{PDMIHOSTAUDIO,pfnStreamCreate}
1025 */
1026static DECLCALLBACK(int) drvHostAudioPaHA_StreamCreate(PPDMIHOSTAUDIO pInterface, PPDMAUDIOBACKENDSTREAM pStream,
1027 PPDMAUDIOSTREAMCFG pCfgReq, PPDMAUDIOSTREAMCFG pCfgAcq)
1028{
1029 PDRVHOSTPULSEAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVHOSTPULSEAUDIO, IHostAudio);
1030 PPULSEAUDIOSTREAM pStreamPA = (PPULSEAUDIOSTREAM)pStream;
1031 AssertPtrReturn(pStreamPA, VERR_INVALID_POINTER);
1032 AssertPtrReturn(pCfgReq, VERR_INVALID_POINTER);
1033 AssertPtrReturn(pCfgAcq, VERR_INVALID_POINTER);
1034 AssertReturn(pCfgReq->enmDir == PDMAUDIODIR_IN || pCfgReq->enmDir == PDMAUDIODIR_OUT, VERR_INVALID_PARAMETER);
1035 Assert(PDMAudioStrmCfgEquals(pCfgReq, pCfgAcq));
1036 int rc;
1037
1038 /*
1039 * Prepare name, sample spec and the stream instance data.
1040 */
1041 char szName[256];
1042 RTStrPrintf(szName, sizeof(szName), "VirtualBox %s [%s]", PDMAudioPathGetName(pCfgReq->enmPath), pThis->szStreamName);
1043
1044 pStreamPA->pDrv = pThis;
1045 pStreamPA->pDrainOp = NULL;
1046 pStreamPA->pbPeekBuf = NULL;
1047 pStreamPA->SampleSpec.rate = PDMAudioPropsHz(&pCfgReq->Props);
1048 pStreamPA->SampleSpec.channels = PDMAudioPropsChannels(&pCfgReq->Props);
1049 pStreamPA->SampleSpec.format = drvHostAudioPaPropsToPulse(&pCfgReq->Props);
1050
1051 LogFunc(("Opening '%s', rate=%dHz, channels=%d, format=%s\n", szName, pStreamPA->SampleSpec.rate,
1052 pStreamPA->SampleSpec.channels, pa_sample_format_to_string(pStreamPA->SampleSpec.format)));
1053
1054 if (pa_sample_spec_valid(&pStreamPA->SampleSpec))
1055 {
1056 /*
1057 * Set up buffer attributes according to the stream type.
1058 *
1059 * For output streams we configure pre-buffering as requested, since
1060 * there is little point in using a different size than DrvAudio. This
1061 * assumes that a 'drain' request will override the prebuf size.
1062 */
1063 pStreamPA->BufAttr.maxlength = UINT32_MAX; /* Let the PulseAudio server choose the biggest size it can handle. */
1064 if (pCfgReq->enmDir == PDMAUDIODIR_IN)
1065 {
1066 pStreamPA->BufAttr.fragsize = PDMAudioPropsFramesToBytes(&pCfgReq->Props, pCfgReq->Backend.cFramesPeriod);
1067 LogFunc(("Requesting: BufAttr: fragsize=%RU32\n", pStreamPA->BufAttr.fragsize));
1068 /* (rlength, minreq and prebuf are playback only) */
1069 }
1070 else
1071 {
1072 pStreamPA->cUsLatency = PDMAudioPropsFramesToMicro(&pCfgReq->Props, pCfgReq->Backend.cFramesBufferSize);
1073 pStreamPA->BufAttr.tlength = pa_usec_to_bytes(pStreamPA->cUsLatency, &pStreamPA->SampleSpec);
1074 pStreamPA->BufAttr.minreq = PDMAudioPropsFramesToBytes(&pCfgReq->Props, pCfgReq->Backend.cFramesPeriod);
1075 pStreamPA->BufAttr.prebuf = pa_usec_to_bytes(PDMAudioPropsFramesToMicro(&pCfgReq->Props,
1076 pCfgReq->Backend.cFramesPreBuffering),
1077 &pStreamPA->SampleSpec);
1078 /* (fragsize is capture only) */
1079 LogRel2(("PulseAudio: Initial output latency is %RU64 us (%RU32 bytes)\n",
1080 pStreamPA->cUsLatency, pStreamPA->BufAttr.tlength));
1081 LogFunc(("Requesting: BufAttr: tlength=%RU32 maxLength=%RU32 minReq=%RU32 maxlength=-1\n",
1082 pStreamPA->BufAttr.tlength, pStreamPA->BufAttr.maxlength, pStreamPA->BufAttr.minreq));
1083 }
1084
1085 /*
1086 * Do the actual PA stream creation.
1087 */
1088 pa_threaded_mainloop_lock(pThis->pMainLoop);
1089 rc = drvHostAudioPaStreamCreateLocked(pThis, pStreamPA, szName, pCfgAcq);
1090 pa_threaded_mainloop_unlock(pThis->pMainLoop);
1091 if (RT_SUCCESS(rc))
1092 {
1093 /*
1094 * Set the acquired stream config according to the actual buffer
1095 * attributes we got and the stream type.
1096 */
1097 if (pCfgReq->enmDir == PDMAUDIODIR_IN)
1098 {
1099 pCfgAcq->Backend.cFramesPeriod = PDMAudioPropsBytesToFrames(&pCfgAcq->Props, pStreamPA->BufAttr.fragsize);
1100 pCfgAcq->Backend.cFramesBufferSize = pStreamPA->BufAttr.maxlength != UINT32_MAX /* paranoia */
1101 ? PDMAudioPropsBytesToFrames(&pCfgAcq->Props, pStreamPA->BufAttr.maxlength)
1102 : pCfgAcq->Backend.cFramesPeriod * 2 /* whatever */;
1103 pCfgAcq->Backend.cFramesPreBuffering = pCfgAcq->Backend.cFramesPeriod;
1104 }
1105 else
1106 {
1107 pCfgAcq->Backend.cFramesPeriod = PDMAudioPropsBytesToFrames(&pCfgAcq->Props, pStreamPA->BufAttr.minreq);
1108 pCfgAcq->Backend.cFramesBufferSize = PDMAudioPropsBytesToFrames(&pCfgAcq->Props, pStreamPA->BufAttr.tlength);
1109 pCfgAcq->Backend.cFramesPreBuffering = pCfgReq->Backend.cFramesPreBuffering
1110 * pCfgAcq->Backend.cFramesBufferSize
1111 / RT_MAX(pCfgReq->Backend.cFramesBufferSize, 1);
1112 }
1113 PDMAudioStrmCfgCopy(&pStreamPA->Cfg, pCfgAcq);
1114 }
1115 }
1116 else
1117 {
1118 LogRel(("PulseAudio: Unsupported sample specification for stream '%s'\n", szName));
1119 rc = VERR_AUDIO_STREAM_COULD_NOT_CREATE;
1120 }
1121
1122 LogFlowFuncLeaveRC(rc);
1123 return rc;
1124}
1125
1126/**
1127 * Cancel and release any pending stream requests (drain and cork/uncork).
1128 *
1129 * @note Caller has locked the mainloop.
1130 */
1131static void drvHostAudioPaStreamCancelAndReleaseOperations(PPULSEAUDIOSTREAM pStreamPA)
1132{
1133 if (pStreamPA->pDrainOp)
1134 {
1135 LogFlowFunc(("drain operation (%p) status: %d\n", pStreamPA->pDrainOp, pa_operation_get_state(pStreamPA->pDrainOp)));
1136 pa_operation_cancel(pStreamPA->pDrainOp);
1137 pa_operation_unref(pStreamPA->pDrainOp);
1138 pStreamPA->pDrainOp = NULL;
1139 }
1140
1141 if (pStreamPA->pCorkOp)
1142 {
1143 LogFlowFunc(("cork operation (%p) status: %d\n", pStreamPA->pCorkOp, pa_operation_get_state(pStreamPA->pCorkOp)));
1144 pa_operation_cancel(pStreamPA->pCorkOp);
1145 pa_operation_unref(pStreamPA->pCorkOp);
1146 pStreamPA->pCorkOp = NULL;
1147 }
1148
1149 if (pStreamPA->pTriggerOp)
1150 {
1151 LogFlowFunc(("trigger operation (%p) status: %d\n", pStreamPA->pTriggerOp, pa_operation_get_state(pStreamPA->pTriggerOp)));
1152 pa_operation_cancel(pStreamPA->pTriggerOp);
1153 pa_operation_unref(pStreamPA->pTriggerOp);
1154 pStreamPA->pTriggerOp = NULL;
1155 }
1156}
1157
1158
1159/**
1160 * @interface_method_impl{PDMIHOSTAUDIO,pfnStreamDestroy}
1161 */
1162static DECLCALLBACK(int) drvHostAudioPaHA_StreamDestroy(PPDMIHOSTAUDIO pInterface, PPDMAUDIOBACKENDSTREAM pStream,
1163 bool fImmediate)
1164{
1165 PDRVHOSTPULSEAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVHOSTPULSEAUDIO, IHostAudio);
1166 PPULSEAUDIOSTREAM pStreamPA = (PPULSEAUDIOSTREAM)pStream;
1167 AssertPtrReturn(pStreamPA, VERR_INVALID_POINTER);
1168 RT_NOREF(fImmediate);
1169
1170 if (pStreamPA->pStream)
1171 {
1172 pa_threaded_mainloop_lock(pThis->pMainLoop);
1173
1174 drvHostAudioPaStreamCancelAndReleaseOperations(pStreamPA);
1175 pa_stream_disconnect(pStreamPA->pStream);
1176
1177 pa_stream_unref(pStreamPA->pStream);
1178 pStreamPA->pStream = NULL;
1179
1180 pa_threaded_mainloop_unlock(pThis->pMainLoop);
1181 }
1182
1183 return VINF_SUCCESS;
1184}
1185
1186
1187/**
1188 * Common worker for the cork/uncork completion callbacks.
1189 * @note This is fully async, so nobody is waiting for this.
1190 */
1191static void drvHostAudioPaStreamCorkUncorkCommon(PPULSEAUDIOSTREAM pStreamPA, int fSuccess, const char *pszOperation)
1192{
1193 AssertPtrReturnVoid(pStreamPA);
1194 LogFlowFunc(("%s '%s': fSuccess=%RTbool\n", pszOperation, pStreamPA->Cfg.szName, fSuccess));
1195
1196 if (!fSuccess)
1197 drvHostAudioPaError(pStreamPA->pDrv, "%s stream '%s' failed", pszOperation, pStreamPA->Cfg.szName);
1198
1199 if (pStreamPA->pCorkOp)
1200 {
1201 pa_operation_unref(pStreamPA->pCorkOp);
1202 pStreamPA->pCorkOp = NULL;
1203 }
1204}
1205
1206
1207/**
1208 * Completion callback used with pa_stream_cork(,false,).
1209 */
1210static void drvHostAudioPaStreamUncorkCompletionCallback(pa_stream *pStream, int fSuccess, void *pvUser)
1211{
1212 RT_NOREF(pStream);
1213 drvHostAudioPaStreamCorkUncorkCommon((PPULSEAUDIOSTREAM)pvUser, fSuccess, "Uncorking");
1214}
1215
1216
1217/**
1218 * Completion callback used with pa_stream_cork(,true,).
1219 */
1220static void drvHostAudioPaStreamCorkCompletionCallback(pa_stream *pStream, int fSuccess, void *pvUser)
1221{
1222 RT_NOREF(pStream);
1223 drvHostAudioPaStreamCorkUncorkCommon((PPULSEAUDIOSTREAM)pvUser, fSuccess, "Corking");
1224}
1225
1226
1227/**
1228 * @ interface_method_impl{PDMIHOSTAUDIO,pfnStreamEnable}
1229 */
1230static DECLCALLBACK(int) drvHostAudioPaHA_StreamEnable(PPDMIHOSTAUDIO pInterface, PPDMAUDIOBACKENDSTREAM pStream)
1231{
1232 PDRVHOSTPULSEAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVHOSTPULSEAUDIO, IHostAudio);
1233 PPULSEAUDIOSTREAM pStreamPA = (PPULSEAUDIOSTREAM)pStream;
1234 LogFlowFunc(("\n"));
1235
1236 /*
1237 * Uncork (start or resume playback/capture) the stream.
1238 */
1239 pa_threaded_mainloop_lock(pThis->pMainLoop);
1240
1241 drvHostAudioPaStreamCancelAndReleaseOperations(pStreamPA);
1242 pStreamPA->pCorkOp = pa_stream_cork(pStreamPA->pStream, 0 /*uncork it*/,
1243 drvHostAudioPaStreamUncorkCompletionCallback, pStreamPA);
1244 LogFlowFunc(("Uncorking '%s': %p (async)\n", pStreamPA->Cfg.szName, pStreamPA->pCorkOp));
1245 int const rc = pStreamPA->pCorkOp ? VINF_SUCCESS
1246 : drvHostAudioPaError(pThis, "pa_stream_cork('%s', 0 /*uncork it*/,,) failed", pStreamPA->Cfg.szName);
1247
1248
1249 pa_threaded_mainloop_unlock(pThis->pMainLoop);
1250
1251 LogFlowFunc(("returns %Rrc\n", rc));
1252 return rc;
1253}
1254
1255
1256/**
1257 * @ interface_method_impl{PDMIHOSTAUDIO,pfnStreamDisable}
1258 */
1259static DECLCALLBACK(int) drvHostAudioPaHA_StreamDisable(PPDMIHOSTAUDIO pInterface, PPDMAUDIOBACKENDSTREAM pStream)
1260{
1261 PDRVHOSTPULSEAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVHOSTPULSEAUDIO, IHostAudio);
1262 PPULSEAUDIOSTREAM pStreamPA = (PPULSEAUDIOSTREAM)pStream;
1263 LogFlowFunc(("\n"));
1264
1265 pa_threaded_mainloop_lock(pThis->pMainLoop);
1266
1267 /*
1268 * For output streams, we will ignore the request if there is a pending drain
1269 * as it will cork the stream in the end.
1270 */
1271 if (pStreamPA->Cfg.enmDir == PDMAUDIODIR_OUT)
1272 {
1273 if (pStreamPA->pDrainOp)
1274 {
1275 pa_operation_state_t const enmOpState = pa_operation_get_state(pStreamPA->pDrainOp);
1276 if (enmOpState == PA_OPERATION_RUNNING)
1277 {
1278/** @todo consider corking it immediately instead, as that's what the caller
1279 * wants now... */
1280 LogFlowFunc(("Drain (%p) already running on '%s', skipping.\n", pStreamPA->pDrainOp, pStreamPA->Cfg.szName));
1281 pa_threaded_mainloop_unlock(pThis->pMainLoop);
1282 return VINF_SUCCESS;
1283 }
1284 LogFlowFunc(("Drain (%p) not running: %d\n", pStreamPA->pDrainOp, enmOpState));
1285 }
1286 }
1287 /*
1288 * For input stream we always cork it, but we clean up the peek buffer first.
1289 */
1290 /** @todo r=bird: It is (probably) not technically be correct to drop the peek buffer
1291 * here when we're only pausing the stream (VM paused) as it means we'll
1292 * risk underruns when later resuming. */
1293 else if (pStreamPA->pbPeekBuf) /** @todo Do we need to drop the peek buffer?*/
1294 {
1295 pStreamPA->pbPeekBuf = NULL;
1296 pStreamPA->cbPeekBuf = 0;
1297 pa_stream_drop(pStreamPA->pStream);
1298 }
1299
1300 /*
1301 * Cork (pause playback/capture) the stream.
1302 */
1303 drvHostAudioPaStreamCancelAndReleaseOperations(pStreamPA);
1304 pStreamPA->pCorkOp = pa_stream_cork(pStreamPA->pStream, 1 /* cork it */,
1305 drvHostAudioPaStreamCorkCompletionCallback, pStreamPA);
1306 LogFlowFunc(("Corking '%s': %p (async)\n", pStreamPA->Cfg.szName, pStreamPA->pCorkOp));
1307 int const rc = pStreamPA->pCorkOp ? VINF_SUCCESS
1308 : drvHostAudioPaError(pThis, "pa_stream_cork('%s', 1 /*cork*/,,) failed", pStreamPA->Cfg.szName);
1309
1310 pa_threaded_mainloop_unlock(pThis->pMainLoop);
1311 LogFlowFunc(("returns %Rrc\n", rc));
1312 return rc;
1313}
1314
1315
1316/**
1317 * @ interface_method_impl{PDMIHOSTAUDIO,pfnStreamPause}
1318 */
1319static DECLCALLBACK(int) drvHostAudioPaHA_StreamPause(PPDMIHOSTAUDIO pInterface, PPDMAUDIOBACKENDSTREAM pStream)
1320{
1321 /* Same as disable. */
1322 return drvHostAudioPaHA_StreamDisable(pInterface, pStream);
1323}
1324
1325
1326/**
1327 * @ interface_method_impl{PDMIHOSTAUDIO,pfnStreamResume}
1328 */
1329static DECLCALLBACK(int) drvHostAudioPaHA_StreamResume(PPDMIHOSTAUDIO pInterface, PPDMAUDIOBACKENDSTREAM pStream)
1330{
1331 /* Same as enable. */
1332 return drvHostAudioPaHA_StreamEnable(pInterface, pStream);
1333}
1334
1335
1336/**
1337 * Pulse audio pa_stream_drain() completion callback.
1338 * @note This is fully async, so nobody is waiting for this.
1339 */
1340static void drvHostAudioPaStreamDrainCompletionCallback(pa_stream *pStream, int fSuccess, void *pvUser)
1341{
1342 PPULSEAUDIOSTREAM pStreamPA = (PPULSEAUDIOSTREAM)pvUser;
1343 AssertPtrReturnVoid(pStreamPA);
1344 Assert(pStreamPA->pStream == pStream);
1345 LogFlowFunc(("'%s': fSuccess=%RTbool\n", pStreamPA->Cfg.szName, fSuccess));
1346
1347 if (!fSuccess)
1348 drvHostAudioPaError(pStreamPA->pDrv, "Draining stream '%s' failed", pStreamPA->Cfg.szName);
1349
1350 /* Now cork the stream (doing it unconditionally atm). */
1351 if (pStreamPA->pCorkOp)
1352 {
1353 LogFlowFunc(("Cancelling & releasing cork/uncork operation %p (state: %d)\n",
1354 pStreamPA->pCorkOp, pa_operation_get_state(pStreamPA->pCorkOp)));
1355 pa_operation_cancel(pStreamPA->pCorkOp);
1356 pa_operation_unref(pStreamPA->pCorkOp);
1357 }
1358
1359 pStreamPA->pCorkOp = pa_stream_cork(pStream, 1 /* cork it*/, drvHostAudioPaStreamCorkCompletionCallback, pStreamPA);
1360 if (pStreamPA->pCorkOp)
1361 LogFlowFunc(("Started cork operation %p of %s (following drain)\n", pStreamPA->pCorkOp, pStreamPA->Cfg.szName));
1362 else
1363 drvHostAudioPaError(pStreamPA->pDrv, "pa_stream_cork failed on '%s' (following drain)", pStreamPA->Cfg.szName);
1364}
1365
1366
1367/**
1368 * Callback used with pa_stream_tigger(), starts draining.
1369 */
1370static void drvHostAudioPaStreamTriggerCompletionCallback(pa_stream *pStream, int fSuccess, void *pvUser)
1371{
1372 PPULSEAUDIOSTREAM pStreamPA = (PPULSEAUDIOSTREAM)pvUser;
1373 AssertPtrReturnVoid(pStreamPA);
1374 RT_NOREF(pStream);
1375 LogFlowFunc(("'%s': fSuccess=%RTbool\n", pStreamPA->Cfg.szName, fSuccess));
1376
1377 if (!fSuccess)
1378 drvHostAudioPaError(pStreamPA->pDrv, "Forcing playback before drainig '%s' failed", pStreamPA->Cfg.szName);
1379
1380 if (pStreamPA->pTriggerOp)
1381 {
1382 pa_operation_unref(pStreamPA->pTriggerOp);
1383 pStreamPA->pTriggerOp = NULL;
1384 }
1385}
1386
1387
1388/**
1389 * @ interface_method_impl{PDMIHOSTAUDIO,pfnStreamDrain}
1390 */
1391static DECLCALLBACK(int) drvHostAudioPaHA_StreamDrain(PPDMIHOSTAUDIO pInterface, PPDMAUDIOBACKENDSTREAM pStream)
1392{
1393 PDRVHOSTPULSEAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVHOSTPULSEAUDIO, IHostAudio);
1394 PPULSEAUDIOSTREAM pStreamPA = (PPULSEAUDIOSTREAM)pStream;
1395 AssertReturn(pStreamPA->Cfg.enmDir == PDMAUDIODIR_OUT, VERR_INVALID_PARAMETER);
1396 LogFlowFunc(("\n"));
1397
1398 pa_threaded_mainloop_lock(pThis->pMainLoop);
1399
1400 /*
1401 * If there is a drain running already, don't try issue another as pulse
1402 * doesn't support more than one concurrent drain per stream.
1403 */
1404 if (pStreamPA->pDrainOp)
1405 {
1406 if (pa_operation_get_state(pStreamPA->pDrainOp) == PA_OPERATION_RUNNING)
1407 {
1408 pa_threaded_mainloop_unlock(pThis->pMainLoop);
1409 LogFlowFunc(("returns VINF_SUCCESS (drain already running)\n"));
1410 return VINF_SUCCESS;
1411 }
1412 LogFlowFunc(("Releasing drain operation %p (state: %d)\n", pStreamPA->pDrainOp, pa_operation_get_state(pStreamPA->pDrainOp)));
1413 pa_operation_unref(pStreamPA->pDrainOp);
1414 pStreamPA->pDrainOp = NULL;
1415 }
1416
1417 /*
1418 * Make sure pre-buffered data is played before we drain it.
1419 *
1420 * ASSUMES that the async stream requests are executed in the order they're
1421 * issued here, so that we avoid waiting for the trigger request to complete.
1422 */
1423 int rc = VINF_SUCCESS;
1424 if (true /** @todo skip this if we're already playing or haven't written any data to the stream since xxxx. */)
1425 {
1426 if (pStreamPA->pTriggerOp)
1427 {
1428 LogFlowFunc(("Cancelling & releasing trigger operation %p (state: %d)\n",
1429 pStreamPA->pTriggerOp, pa_operation_get_state(pStreamPA->pTriggerOp)));
1430 pa_operation_cancel(pStreamPA->pTriggerOp);
1431 pa_operation_unref(pStreamPA->pTriggerOp);
1432 }
1433 pStreamPA->pTriggerOp = pa_stream_trigger(pStreamPA->pStream, drvHostAudioPaStreamTriggerCompletionCallback, pStreamPA);
1434 if (pStreamPA->pTriggerOp)
1435 LogFlowFunc(("Started tigger operation %p on %s\n", pStreamPA->pTriggerOp, pStreamPA->Cfg.szName));
1436 else
1437 rc = drvHostAudioPaError(pStreamPA->pDrv, "pa_stream_trigger failed on '%s'", pStreamPA->Cfg.szName);
1438 }
1439
1440 /*
1441 * Initiate the draining (async), will cork the stream when it completes.
1442 */
1443 pStreamPA->pDrainOp = pa_stream_drain(pStreamPA->pStream, drvHostAudioPaStreamDrainCompletionCallback, pStreamPA);
1444 if (pStreamPA->pDrainOp)
1445 LogFlowFunc(("Started drain operation %p of %s\n", pStreamPA->pDrainOp, pStreamPA->Cfg.szName));
1446 else
1447 rc = drvHostAudioPaError(pStreamPA->pDrv, "pa_stream_drain failed on '%s'", pStreamPA->Cfg.szName);
1448
1449 pa_threaded_mainloop_unlock(pThis->pMainLoop);
1450 LogFlowFunc(("returns %Rrc\n", rc));
1451 return rc;
1452}
1453
1454
1455/**
1456 * @interface_method_impl{PDMIHOSTAUDIO,pfnStreamControl}
1457 */
1458static DECLCALLBACK(int) drvHostAudioPaHA_StreamControl(PPDMIHOSTAUDIO pInterface,
1459 PPDMAUDIOBACKENDSTREAM pStream, PDMAUDIOSTREAMCMD enmStreamCmd)
1460{
1461 /** @todo r=bird: I'd like to get rid of this pfnStreamControl method,
1462 * replacing it with individual StreamXxxx methods. That would save us
1463 * potentally huge switches and more easily see which drivers implement
1464 * which operations (grep for pfnStreamXxxx). */
1465 switch (enmStreamCmd)
1466 {
1467 case PDMAUDIOSTREAMCMD_ENABLE:
1468 return drvHostAudioPaHA_StreamEnable(pInterface, pStream);
1469 case PDMAUDIOSTREAMCMD_DISABLE:
1470 return drvHostAudioPaHA_StreamDisable(pInterface, pStream);
1471 case PDMAUDIOSTREAMCMD_PAUSE:
1472 return drvHostAudioPaHA_StreamPause(pInterface, pStream);
1473 case PDMAUDIOSTREAMCMD_RESUME:
1474 return drvHostAudioPaHA_StreamResume(pInterface, pStream);
1475 case PDMAUDIOSTREAMCMD_DRAIN:
1476 return drvHostAudioPaHA_StreamDrain(pInterface, pStream);
1477
1478 case PDMAUDIOSTREAMCMD_END:
1479 case PDMAUDIOSTREAMCMD_32BIT_HACK:
1480 case PDMAUDIOSTREAMCMD_INVALID:
1481 /* no default*/
1482 break;
1483 }
1484 return VERR_NOT_SUPPORTED;
1485}
1486
1487
1488/**
1489 * @interface_method_impl{PDMIHOSTAUDIO,pfnStreamGetReadable}
1490 */
1491static DECLCALLBACK(uint32_t) drvHostAudioPaHA_StreamGetReadable(PPDMIHOSTAUDIO pInterface, PPDMAUDIOBACKENDSTREAM pStream)
1492{
1493 PDRVHOSTPULSEAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVHOSTPULSEAUDIO, IHostAudio);
1494 PPULSEAUDIOSTREAM pStreamPA = (PPULSEAUDIOSTREAM)pStream;
1495 uint32_t cbReadable = 0;
1496 if (pStreamPA->Cfg.enmDir == PDMAUDIODIR_IN)
1497 {
1498 pa_threaded_mainloop_lock(pThis->pMainLoop);
1499
1500 pa_stream_state_t const enmState = pa_stream_get_state(pStreamPA->pStream);
1501 if (PA_STREAM_IS_GOOD(enmState))
1502 {
1503 size_t cbReadablePa = pa_stream_readable_size(pStreamPA->pStream);
1504 if (cbReadablePa != (size_t)-1)
1505 cbReadable = (uint32_t)cbReadablePa;
1506 else
1507 drvHostAudioPaError(pThis, "pa_stream_readable_size failed on '%s'", pStreamPA->Cfg.szName);
1508 }
1509 else
1510 LogFunc(("non-good stream state: %d\n", enmState));
1511
1512 pa_threaded_mainloop_unlock(pThis->pMainLoop);
1513 }
1514 Log3Func(("returns %#x (%u)\n", cbReadable, cbReadable));
1515 return cbReadable;
1516}
1517
1518
1519/**
1520 * @interface_method_impl{PDMIHOSTAUDIO,pfnStreamGetWritable}
1521 */
1522static DECLCALLBACK(uint32_t) drvHostAudioPaHA_StreamGetWritable(PPDMIHOSTAUDIO pInterface, PPDMAUDIOBACKENDSTREAM pStream)
1523{
1524 PDRVHOSTPULSEAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVHOSTPULSEAUDIO, IHostAudio);
1525 PPULSEAUDIOSTREAM pStreamPA = (PPULSEAUDIOSTREAM)pStream;
1526 uint32_t cbWritable = 0;
1527 if (pStreamPA->Cfg.enmDir == PDMAUDIODIR_OUT)
1528 {
1529 pa_threaded_mainloop_lock(pThis->pMainLoop);
1530
1531 pa_stream_state_t const enmState = pa_stream_get_state(pStreamPA->pStream);
1532 if (PA_STREAM_IS_GOOD(enmState))
1533 {
1534 size_t cbWritablePa = pa_stream_writable_size(pStreamPA->pStream);
1535 if (cbWritablePa != (size_t)-1)
1536 cbWritable = cbWritablePa <= UINT32_MAX ? (uint32_t)cbWritablePa : UINT32_MAX;
1537 else
1538 drvHostAudioPaError(pThis, "pa_stream_writable_size failed on '%s'", pStreamPA->Cfg.szName);
1539 }
1540 else
1541 LogFunc(("non-good stream state: %d\n", enmState));
1542
1543 pa_threaded_mainloop_unlock(pThis->pMainLoop);
1544 }
1545 Log3Func(("returns %#x (%u) [max=%#RX32 min=%#RX32]\n",
1546 cbWritable, cbWritable, pStreamPA->BufAttr.maxlength, pStreamPA->BufAttr.minreq));
1547 return cbWritable;
1548}
1549
1550
1551/**
1552 * @interface_method_impl{PDMIHOSTAUDIO,pfnStreamGetState}
1553 */
1554static DECLCALLBACK(PDMHOSTAUDIOSTREAMSTATE) drvHostAudioPaHA_StreamGetState(PPDMIHOSTAUDIO pInterface,
1555 PPDMAUDIOBACKENDSTREAM pStream)
1556{
1557 PDRVHOSTPULSEAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVHOSTPULSEAUDIO, IHostAudio);
1558 AssertPtrReturn(pStream, PDMHOSTAUDIOSTREAMSTATE_INVALID);
1559 PPULSEAUDIOSTREAM pStreamPA = (PPULSEAUDIOSTREAM)pStream;
1560 AssertPtrReturn(pStreamPA, PDMHOSTAUDIOSTREAMSTATE_INVALID);
1561
1562 /* Check PulseAudio's general status. */
1563 PDMHOSTAUDIOSTREAMSTATE enmBackendStreamState = PDMHOSTAUDIOSTREAMSTATE_NOT_WORKING;
1564 if (pThis->pContext)
1565 {
1566 pa_context_state_t const enmPaCtxState = pa_context_get_state(pThis->pContext);
1567 if (PA_CONTEXT_IS_GOOD(enmPaCtxState))
1568 {
1569 pa_stream_state_t const enmPaStreamState = pa_stream_get_state(pStreamPA->pStream);
1570 if (PA_STREAM_IS_GOOD(enmPaStreamState))
1571 {
1572 if (enmPaStreamState != PA_STREAM_CREATING)
1573 {
1574 if ( pStreamPA->Cfg.enmDir != PDMAUDIODIR_OUT
1575 || pStreamPA->pDrainOp == NULL
1576 || pa_operation_get_state(pStreamPA->pDrainOp) != PA_OPERATION_RUNNING)
1577 enmBackendStreamState = PDMHOSTAUDIOSTREAMSTATE_OKAY;
1578 else
1579 enmBackendStreamState = PDMHOSTAUDIOSTREAMSTATE_DRAINING;
1580 }
1581 else
1582 enmBackendStreamState = PDMHOSTAUDIOSTREAMSTATE_INITIALIZING;
1583 }
1584 else
1585 LogFunc(("non-good PA stream state: %d\n", enmPaStreamState));
1586 }
1587 else
1588 LogFunc(("non-good PA context state: %d\n", enmPaCtxState));
1589 }
1590 else
1591 LogFunc(("No context!\n"));
1592 LogFlowFunc(("returns %s for stream '%s'\n", PDMHostAudioStreamStateGetName(enmBackendStreamState), pStreamPA->Cfg.szName));
1593 return enmBackendStreamState;
1594}
1595
1596
1597/**
1598 * @interface_method_impl{PDMIHOSTAUDIO,pfnStreamPlay}
1599 */
1600static DECLCALLBACK(int) drvHostAudioPaHA_StreamPlay(PPDMIHOSTAUDIO pInterface, PPDMAUDIOBACKENDSTREAM pStream,
1601 const void *pvBuf, uint32_t cbBuf, uint32_t *pcbWritten)
1602{
1603 PDRVHOSTPULSEAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVHOSTPULSEAUDIO, IHostAudio);
1604 PPULSEAUDIOSTREAM pStreamPA = (PPULSEAUDIOSTREAM)pStream;
1605 AssertPtrReturn(pStreamPA, VERR_INVALID_POINTER);
1606 AssertPtrReturn(pcbWritten, VERR_INVALID_POINTER);
1607 if (cbBuf)
1608 AssertPtrReturn(pvBuf, VERR_INVALID_POINTER);
1609 else
1610 {
1611 /* Fend off draining calls. */
1612 *pcbWritten = 0;
1613 return VINF_SUCCESS;
1614 }
1615
1616 pa_threaded_mainloop_lock(pThis->pMainLoop);
1617
1618#ifdef LOG_ENABLED
1619 const pa_usec_t tsNowUs = pa_rtclock_now();
1620 Log3Func(("play delta: %'RU64 us; cbBuf=%#x\n", tsNowUs - pStreamPA->tsLastReadWrittenUs, cbBuf));
1621 pStreamPA->tsLastReadWrittenUs = tsNowUs;
1622#endif
1623
1624 /*
1625 * Using a loop here so we can take maxlength into account when writing.
1626 */
1627 int rc = VINF_SUCCESS;
1628 uint32_t cbTotalWritten = 0;
1629 uint32_t iLoop;
1630 for (iLoop = 0; ; iLoop++)
1631 {
1632 size_t const cbWriteable = pa_stream_writable_size(pStreamPA->pStream);
1633 if ( cbWriteable != (size_t)-1
1634 && cbWriteable >= PDMAudioPropsFrameSize(&pStreamPA->Cfg.Props))
1635 {
1636 uint32_t cbToWrite = (uint32_t)RT_MIN(RT_MIN(cbWriteable, pStreamPA->BufAttr.maxlength), cbBuf);
1637 cbToWrite = PDMAudioPropsFloorBytesToFrame(&pStreamPA->Cfg.Props, cbToWrite);
1638 if (pa_stream_write(pStreamPA->pStream, pvBuf, cbToWrite, NULL /*pfnFree*/, 0 /*offset*/, PA_SEEK_RELATIVE) >= 0)
1639 {
1640 cbTotalWritten += cbToWrite;
1641 cbBuf -= cbToWrite;
1642 if (!cbBuf)
1643 break;
1644 pvBuf = (uint8_t const *)pvBuf + cbToWrite;
1645 Log3Func(("%#x left to write\n", cbBuf));
1646 }
1647 else
1648 {
1649 rc = drvHostAudioPaError(pStreamPA->pDrv, "Failed to write to output stream");
1650 break;
1651 }
1652 }
1653 else
1654 {
1655 if (cbWriteable == (size_t)-1)
1656 rc = drvHostAudioPaError(pStreamPA->pDrv, "pa_stream_writable_size failed on '%s'", pStreamPA->Cfg.szName);
1657 break;
1658 }
1659 }
1660
1661 pa_threaded_mainloop_unlock(pThis->pMainLoop);
1662
1663 *pcbWritten = cbTotalWritten;
1664 if (RT_SUCCESS(rc) || cbTotalWritten == 0)
1665 { /* likely */ }
1666 else
1667 {
1668 LogFunc(("Supressing %Rrc because we wrote %#x bytes\n", rc, cbTotalWritten));
1669 rc = VINF_SUCCESS;
1670 }
1671 Log3Func(("returns %Rrc *pcbWritten=%#x iLoop=%u\n", rc, cbTotalWritten, iLoop));
1672 return rc;
1673}
1674
1675
1676/**
1677 * @interface_method_impl{PDMIHOSTAUDIO,pfnStreamCapture}
1678 */
1679static DECLCALLBACK(int) drvHostAudioPaHA_StreamCapture(PPDMIHOSTAUDIO pInterface, PPDMAUDIOBACKENDSTREAM pStream,
1680 void *pvBuf, uint32_t cbBuf, uint32_t *pcbRead)
1681{
1682 PDRVHOSTPULSEAUDIO pThis = RT_FROM_MEMBER(pInterface, DRVHOSTPULSEAUDIO, IHostAudio);
1683 PPULSEAUDIOSTREAM pStreamPA = (PPULSEAUDIOSTREAM)pStream;
1684 AssertPtrReturn(pStreamPA, VERR_INVALID_POINTER);
1685 AssertPtrReturn(pvBuf, VERR_INVALID_POINTER);
1686 AssertReturn(cbBuf, VERR_INVALID_PARAMETER);
1687 AssertPtrReturn(pcbRead, VERR_INVALID_POINTER);
1688
1689#ifdef LOG_ENABLED
1690 const pa_usec_t tsNowUs = pa_rtclock_now();
1691 Log3Func(("capture delta: %'RU64 us; cbBuf=%#x\n", tsNowUs - pStreamPA->tsLastReadWrittenUs, cbBuf));
1692 pStreamPA->tsLastReadWrittenUs = tsNowUs;
1693#endif
1694
1695 /*
1696 * If we have left over peek buffer space from the last call,
1697 * copy out the data from there.
1698 */
1699 uint32_t cbTotalRead = 0;
1700 if ( pStreamPA->pbPeekBuf
1701 && pStreamPA->offPeekBuf < pStreamPA->cbPeekBuf)
1702 {
1703 uint32_t cbToCopy = pStreamPA->cbPeekBuf - pStreamPA->offPeekBuf;
1704 if (cbToCopy >= cbBuf)
1705 {
1706 memcpy(pvBuf, &pStreamPA->pbPeekBuf[pStreamPA->offPeekBuf], cbBuf);
1707 pStreamPA->offPeekBuf += cbBuf;
1708 *pcbRead = cbBuf;
1709 if (cbToCopy == cbBuf)
1710 {
1711 pa_threaded_mainloop_lock(pThis->pMainLoop);
1712 pStreamPA->pbPeekBuf = NULL;
1713 pStreamPA->cbPeekBuf = 0;
1714 pa_stream_drop(pStreamPA->pStream);
1715 pa_threaded_mainloop_unlock(pThis->pMainLoop);
1716 }
1717 Log3Func(("returns *pcbRead=%#x from prev peek buf (%#x/%#x)\n", cbBuf, pStreamPA->offPeekBuf, pStreamPA->cbPeekBuf));
1718 return VINF_SUCCESS;
1719 }
1720
1721 memcpy(pvBuf, &pStreamPA->pbPeekBuf[pStreamPA->offPeekBuf], cbToCopy);
1722 cbBuf -= cbToCopy;
1723 pvBuf = (uint8_t *)pvBuf + cbToCopy;
1724 cbTotalRead += cbToCopy;
1725 pStreamPA->offPeekBuf = pStreamPA->cbPeekBuf;
1726 }
1727
1728 /*
1729 * Copy out what we can.
1730 */
1731 int rc = VINF_SUCCESS;
1732 pa_threaded_mainloop_lock(pThis->pMainLoop);
1733 while (cbBuf > 0)
1734 {
1735 /*
1736 * Drop the old peek buffer first, if we have one.
1737 */
1738 if (pStreamPA->pbPeekBuf)
1739 {
1740 Assert(pStreamPA->offPeekBuf >= pStreamPA->cbPeekBuf);
1741 pStreamPA->pbPeekBuf = NULL;
1742 pStreamPA->cbPeekBuf = 0;
1743 pa_stream_drop(pStreamPA->pStream);
1744 }
1745
1746 /*
1747 * Check if there is anything to read, the get the peek buffer for it.
1748 */
1749 size_t cbAvail = pa_stream_readable_size(pStreamPA->pStream);
1750 if (cbAvail > 0 && cbAvail != (size_t)-1)
1751 {
1752 pStreamPA->pbPeekBuf = NULL;
1753 pStreamPA->cbPeekBuf = 0;
1754 int rcPa = pa_stream_peek(pStreamPA->pStream, (const void **)&pStreamPA->pbPeekBuf, &pStreamPA->cbPeekBuf);
1755 if (rcPa == 0)
1756 {
1757 if (pStreamPA->cbPeekBuf)
1758 {
1759 if (pStreamPA->pbPeekBuf)
1760 {
1761 /*
1762 * We got data back. Copy it into the return buffer, return if it's full.
1763 */
1764 if (cbBuf < pStreamPA->cbPeekBuf)
1765 {
1766 memcpy(pvBuf, pStreamPA->pbPeekBuf, cbBuf);
1767 cbTotalRead += cbBuf;
1768 pStreamPA->offPeekBuf = cbBuf;
1769 cbBuf = 0;
1770 break;
1771 }
1772 memcpy(pvBuf, pStreamPA->pbPeekBuf, pStreamPA->cbPeekBuf);
1773 cbBuf -= pStreamPA->cbPeekBuf;
1774 pvBuf = (uint8_t *)pvBuf + pStreamPA->cbPeekBuf;
1775 cbTotalRead += pStreamPA->cbPeekBuf;
1776
1777 pStreamPA->pbPeekBuf = NULL;
1778 }
1779 else
1780 {
1781 /*
1782 * We got a hole (drop needed). We will skip it as we leave it to
1783 * the device's DMA engine to fill in buffer gaps with silence.
1784 */
1785 LogFunc(("pa_stream_peek returned a %#zx (%zu) byte hole - skipping.\n",
1786 pStreamPA->cbPeekBuf, pStreamPA->cbPeekBuf));
1787 }
1788 pStreamPA->cbPeekBuf = 0;
1789 pa_stream_drop(pStreamPA->pStream);
1790 }
1791 else
1792 {
1793 Assert(!pStreamPA->pbPeekBuf);
1794 LogFunc(("pa_stream_peek returned empty buffer\n"));
1795 break;
1796 }
1797 }
1798 else
1799 {
1800 rc = drvHostAudioPaError(pStreamPA->pDrv, "pa_stream_peek failed on '%s' (%d)", pStreamPA->Cfg.szName, rcPa);
1801 pStreamPA->pbPeekBuf = NULL;
1802 pStreamPA->cbPeekBuf = 0;
1803 break;
1804 }
1805 }
1806 else
1807 {
1808 if (cbAvail != (size_t)-1)
1809 rc = drvHostAudioPaError(pStreamPA->pDrv, "pa_stream_readable_size failed on '%s'", pStreamPA->Cfg.szName);
1810 break;
1811 }
1812 }
1813 pa_threaded_mainloop_unlock(pThis->pMainLoop);
1814
1815 *pcbRead = cbTotalRead;
1816 if (RT_SUCCESS(rc) || cbTotalRead == 0)
1817 { /* likely */ }
1818 else
1819 {
1820 LogFunc(("Supressing %Rrc because we're returning %#x bytes\n", rc, cbTotalRead));
1821 rc = VINF_SUCCESS;
1822 }
1823 Log3Func(("returns %Rrc *pcbRead=%#x (%#x left, peek %#x/%#x)\n",
1824 rc, cbTotalRead, cbBuf, pStreamPA->offPeekBuf, pStreamPA->cbPeekBuf));
1825 return rc;
1826}
1827
1828
1829/*********************************************************************************************************************************
1830* PDMIBASE *
1831*********************************************************************************************************************************/
1832
1833/**
1834 * @interface_method_impl{PDMIBASE,pfnQueryInterface}
1835 */
1836static DECLCALLBACK(void *) drvHostAudioPaQueryInterface(PPDMIBASE pInterface, const char *pszIID)
1837{
1838 AssertPtrReturn(pInterface, NULL);
1839 AssertPtrReturn(pszIID, NULL);
1840
1841 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
1842 PDRVHOSTPULSEAUDIO pThis = PDMINS_2_DATA(pDrvIns, PDRVHOSTPULSEAUDIO);
1843 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pDrvIns->IBase);
1844 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIHOSTAUDIO, &pThis->IHostAudio);
1845
1846 return NULL;
1847}
1848
1849
1850/*********************************************************************************************************************************
1851* PDMDRVREG *
1852*********************************************************************************************************************************/
1853
1854/**
1855 * Destructs a PulseAudio Audio driver instance.
1856 *
1857 * @copydoc FNPDMDRVDESTRUCT
1858 */
1859static DECLCALLBACK(void) drvHostAudioPaDestruct(PPDMDRVINS pDrvIns)
1860{
1861 PDMDRV_CHECK_VERSIONS_RETURN_VOID(pDrvIns);
1862 PDRVHOSTPULSEAUDIO pThis = PDMINS_2_DATA(pDrvIns, PDRVHOSTPULSEAUDIO);
1863 LogFlowFuncEnter();
1864
1865 if (pThis->pMainLoop)
1866 pa_threaded_mainloop_stop(pThis->pMainLoop);
1867
1868 if (pThis->pContext)
1869 {
1870 pa_context_disconnect(pThis->pContext);
1871 pa_context_unref(pThis->pContext);
1872 pThis->pContext = NULL;
1873 }
1874
1875 if (pThis->pMainLoop)
1876 {
1877 pa_threaded_mainloop_free(pThis->pMainLoop);
1878 pThis->pMainLoop = NULL;
1879 }
1880
1881 LogFlowFuncLeave();
1882}
1883
1884
1885/**
1886 * Pulse audio callback for context status changes, init variant.
1887 *
1888 * Signalls our event semaphore so we can do a timed wait from
1889 * drvHostAudioPaConstruct().
1890 */
1891static void drvHostAudioPaCtxCallbackStateChangedInit(pa_context *pCtx, void *pvUser)
1892{
1893 AssertPtrReturnVoid(pCtx);
1894 PPULSEAUDIOSTATECHGCTX pStateChgCtx = (PPULSEAUDIOSTATECHGCTX)pvUser;
1895 pa_context_state_t enmCtxState = pa_context_get_state(pCtx);
1896 switch (enmCtxState)
1897 {
1898 case PA_CONTEXT_READY:
1899 case PA_CONTEXT_TERMINATED:
1900 case PA_CONTEXT_FAILED:
1901 AssertPtrReturnVoid(pStateChgCtx);
1902 pStateChgCtx->enmCtxState = enmCtxState;
1903 RTSemEventSignal(pStateChgCtx->hEvtInit);
1904 break;
1905
1906 default:
1907 break;
1908 }
1909}
1910
1911
1912/**
1913 * Constructs a PulseAudio Audio driver instance.
1914 *
1915 * @copydoc FNPDMDRVCONSTRUCT
1916 */
1917static DECLCALLBACK(int) drvHostAudioPaConstruct(PPDMDRVINS pDrvIns, PCFGMNODE pCfg, uint32_t fFlags)
1918{
1919 RT_NOREF(pCfg, fFlags);
1920 PDMDRV_CHECK_VERSIONS_RETURN(pDrvIns);
1921 PDRVHOSTPULSEAUDIO pThis = PDMINS_2_DATA(pDrvIns, PDRVHOSTPULSEAUDIO);
1922 LogRel(("Audio: Initializing PulseAudio driver\n"));
1923
1924 /*
1925 * Initialize instance data.
1926 */
1927 pThis->pDrvIns = pDrvIns;
1928 /* IBase */
1929 pDrvIns->IBase.pfnQueryInterface = drvHostAudioPaQueryInterface;
1930 /* IHostAudio */
1931 pThis->IHostAudio.pfnGetConfig = drvHostAudioPaHA_GetConfig;
1932 pThis->IHostAudio.pfnGetDevices = drvHostAudioPaHA_GetDevices;
1933 pThis->IHostAudio.pfnSetDevice = NULL;
1934 pThis->IHostAudio.pfnGetStatus = drvHostAudioPaHA_GetStatus;
1935 pThis->IHostAudio.pfnDoOnWorkerThread = NULL;
1936 pThis->IHostAudio.pfnStreamConfigHint = NULL;
1937 pThis->IHostAudio.pfnStreamCreate = drvHostAudioPaHA_StreamCreate;
1938 pThis->IHostAudio.pfnStreamInitAsync = NULL;
1939 pThis->IHostAudio.pfnStreamDestroy = drvHostAudioPaHA_StreamDestroy;
1940 pThis->IHostAudio.pfnStreamNotifyDeviceChanged = NULL;
1941 pThis->IHostAudio.pfnStreamControl = drvHostAudioPaHA_StreamControl;
1942 pThis->IHostAudio.pfnStreamGetReadable = drvHostAudioPaHA_StreamGetReadable;
1943 pThis->IHostAudio.pfnStreamGetWritable = drvHostAudioPaHA_StreamGetWritable;
1944 pThis->IHostAudio.pfnStreamGetPending = NULL;
1945 pThis->IHostAudio.pfnStreamGetState = drvHostAudioPaHA_StreamGetState;
1946 pThis->IHostAudio.pfnStreamPlay = drvHostAudioPaHA_StreamPlay;
1947 pThis->IHostAudio.pfnStreamCapture = drvHostAudioPaHA_StreamCapture;
1948
1949 /*
1950 * Read configuration.
1951 */
1952 int rc2 = CFGMR3QueryString(pCfg, "VmName", pThis->szStreamName, sizeof(pThis->szStreamName));
1953 AssertMsgRCReturn(rc2, ("Confguration error: No/bad \"VmName\" value, rc=%Rrc\n", rc2), rc2);
1954
1955 /*
1956 * Load the pulse audio library.
1957 */
1958 int rc = audioLoadPulseLib();
1959 if (RT_SUCCESS(rc))
1960 LogRel(("PulseAudio: Using version %s\n", pa_get_library_version()));
1961 else
1962 {
1963 LogRel(("PulseAudio: Failed to load the PulseAudio shared library! Error %Rrc\n", rc));
1964 return rc;
1965 }
1966
1967 /*
1968 * Set up the basic pulse audio bits (remember the destructore is always called).
1969 */
1970 //pThis->fAbortLoop = false;
1971 pThis->pMainLoop = pa_threaded_mainloop_new();
1972 if (!pThis->pMainLoop)
1973 {
1974 LogRel(("PulseAudio: Failed to allocate main loop: %s\n", pa_strerror(pa_context_errno(pThis->pContext))));
1975 return VERR_NO_MEMORY;
1976 }
1977
1978 pThis->pContext = pa_context_new(pa_threaded_mainloop_get_api(pThis->pMainLoop), "VirtualBox");
1979 if (!pThis->pContext)
1980 {
1981 LogRel(("PulseAudio: Failed to allocate context: %s\n", pa_strerror(pa_context_errno(pThis->pContext))));
1982 return VERR_NO_MEMORY;
1983 }
1984
1985 if (pa_threaded_mainloop_start(pThis->pMainLoop) < 0)
1986 {
1987 LogRel(("PulseAudio: Failed to start threaded mainloop: %s\n", pa_strerror(pa_context_errno(pThis->pContext))));
1988 return VERR_AUDIO_BACKEND_INIT_FAILED;
1989 }
1990
1991 /*
1992 * Connect to the pulse audio server.
1993 *
1994 * We install an init state callback so we can do a timed wait in case
1995 * connecting to the pulseaudio server should take too long.
1996 */
1997 pThis->InitStateChgCtx.hEvtInit = NIL_RTSEMEVENT;
1998 pThis->InitStateChgCtx.enmCtxState = PA_CONTEXT_UNCONNECTED;
1999 rc = RTSemEventCreate(&pThis->InitStateChgCtx.hEvtInit);
2000 AssertLogRelRCReturn(rc, rc);
2001
2002 pa_threaded_mainloop_lock(pThis->pMainLoop);
2003 pa_context_set_state_callback(pThis->pContext, drvHostAudioPaCtxCallbackStateChangedInit, &pThis->InitStateChgCtx);
2004 if (!pa_context_connect(pThis->pContext, NULL /* pszServer */, PA_CONTEXT_NOFLAGS, NULL))
2005 {
2006 pa_threaded_mainloop_unlock(pThis->pMainLoop);
2007
2008 rc = RTSemEventWait(pThis->InitStateChgCtx.hEvtInit, RT_MS_10SEC); /* 10 seconds should be plenty. */
2009 if (RT_SUCCESS(rc))
2010 {
2011 if (pThis->InitStateChgCtx.enmCtxState == PA_CONTEXT_READY)
2012 {
2013 /* Install the main state changed callback to know if something happens to our acquired context. */
2014 pa_threaded_mainloop_lock(pThis->pMainLoop);
2015 pa_context_set_state_callback(pThis->pContext, drvHostAudioPaCtxCallbackStateChanged, pThis /* pvUserData */);
2016 pa_threaded_mainloop_unlock(pThis->pMainLoop);
2017 }
2018 else
2019 {
2020 LogRel(("PulseAudio: Failed to initialize context (state %d, rc=%Rrc)\n", pThis->InitStateChgCtx.enmCtxState, rc));
2021 rc = VERR_AUDIO_BACKEND_INIT_FAILED;
2022 }
2023 }
2024 else
2025 {
2026 LogRel(("PulseAudio: Waiting for context to become ready failed: %Rrc\n", rc));
2027 rc = VERR_AUDIO_BACKEND_INIT_FAILED;
2028 }
2029 }
2030 else
2031 {
2032 pa_threaded_mainloop_unlock(pThis->pMainLoop);
2033 LogRel(("PulseAudio: Failed to connect to server: %s\n", pa_strerror(pa_context_errno(pThis->pContext))));
2034 rc = VERR_AUDIO_BACKEND_INIT_FAILED; /* bird: This used to be VINF_SUCCESS. */
2035 }
2036
2037 RTSemEventDestroy(pThis->InitStateChgCtx.hEvtInit);
2038 pThis->InitStateChgCtx.hEvtInit = NIL_RTSEMEVENT;
2039
2040 return rc;
2041}
2042
2043
2044/**
2045 * Pulse audio driver registration record.
2046 */
2047const PDMDRVREG g_DrvHostPulseAudio =
2048{
2049 /* u32Version */
2050 PDM_DRVREG_VERSION,
2051 /* szName */
2052 "PulseAudio",
2053 /* szRCMod */
2054 "",
2055 /* szR0Mod */
2056 "",
2057 /* pszDescription */
2058 "Pulse Audio host driver",
2059 /* fFlags */
2060 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
2061 /* fClass. */
2062 PDM_DRVREG_CLASS_AUDIO,
2063 /* cMaxInstances */
2064 ~0U,
2065 /* cbInstance */
2066 sizeof(DRVHOSTPULSEAUDIO),
2067 /* pfnConstruct */
2068 drvHostAudioPaConstruct,
2069 /* pfnDestruct */
2070 drvHostAudioPaDestruct,
2071 /* pfnRelocate */
2072 NULL,
2073 /* pfnIOCtl */
2074 NULL,
2075 /* pfnPowerOn */
2076 NULL,
2077 /* pfnReset */
2078 NULL,
2079 /* pfnSuspend */
2080 NULL,
2081 /* pfnResume */
2082 NULL,
2083 /* pfnAttach */
2084 NULL,
2085 /* pfnDetach */
2086 NULL,
2087 /* pfnPowerOff */
2088 NULL,
2089 /* pfnSoftReset */
2090 NULL,
2091 /* u32EndVersion */
2092 PDM_DRVREG_VERSION
2093};
2094
Note: See TracBrowser for help on using the repository browser.

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