VirtualBox

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

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

ValKit/Audio: Eliminated VBoxDDVKAT.h. Made some progress getting the PulseAudio driver to work (integer overflow now due to invalid config). bugref:10008

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