Debian Codegraph @

3rdparty/iaxclient/lib/portaudio/src/hostapi/alsa/pa_linux_alsa.c

raw symbols SCIP
1 /*
2 * $Id: pa_linux_alsa.c,v 1.1 2006/06/10 21:30:55 dmazzoni Exp $
3 * PortAudio Portable Real-Time Audio Library
4 * Latest Version at: http://www.portaudio.com
5 * ALSA implementation by Joshua Haberman and Arve Knudsen
6 *
7 * Copyright (c) 2002 Joshua Haberman <[email protected]>
8 * Copyright (c) 2005-2006 Arve Knudsen <[email protected]>
9 *
10 * Based on the Open Source API proposed by Ross Bencina
11 * Copyright (c) 1999-2002 Ross Bencina, Phil Burk
12 *
13 * Permission is hereby granted, free of charge, to any person obtaining
14 * a copy of this software and associated documentation files
15 * (the "Software"), to deal in the Software without restriction,
16 * including without limitation the rights to use, copy, modify, merge,
17 * publish, distribute, sublicense, and/or sell copies of the Software,
18 * and to permit persons to whom the Software is furnished to do so,
19 * subject to the following conditions:
20 *
21 * The above copyright notice and this permission notice shall be
22 * included in all copies or substantial portions of the Software.
23 *
24 * Any person wishing to distribute modifications to the Software is
25 * requested to send the modifications to the original developer so that
26 * they can be incorporated into the canonical version.
27 *
28 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
29 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
30 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
31 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
32 * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
33 * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
34 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
35 */
36
37 #define ALSA_PCM_NEW_HW_PARAMS_API
38 #define ALSA_PCM_NEW_SW_PARAMS_API
39 #include <alsa/asoundlib.h>
40 #undef ALSA_PCM_NEW_HW_PARAMS_API
41 #undef ALSA_PCM_NEW_SW_PARAMS_API
42
43 #include <sys/poll.h>
44 #include <string.h> /* strlen() */
45 #include <limits.h>
46 #include <math.h>
47 #include <pthread.h>
48 #include <signal.h>
49 #include <time.h>
50 #include <sys/mman.h>
51 #include <signal.h> /* For sig_atomic_t */
52
53 #include "portaudio.h"
54 #include "pa_util.h"
55 #include "pa_unix_util.h"
56 #include "pa_allocation.h"
57 #include "pa_hostapi.h"
58 #include "pa_stream.h"
59 #include "pa_cpuload.h"
60 #include "pa_process.h"
61
62 #include "pa_linux_alsa.h"
63
64 /* Check return value of ALSA function, and map it to PaError */
65 #define ENSURE_(expr, code) \
66 do { \
67 if( UNLIKELY( (aErr_ = (expr)) < 0 ) ) \
68 { \
69 /* PaUtil_SetLastHostErrorInfo should only be used in the main thread */ \
70 if( (code) == paUnanticipatedHostError && pthread_equal( pthread_self(), paUnixMainThread) ) \
71 { \
72 PaUtil_SetLastHostErrorInfo( paALSA, aErr_, snd_strerror( aErr_ ) ); \
73 } \
74 PaUtil_DebugPrint( "Expression '" #expr "' failed in '" __FILE__ "', line: " STRINGIZE( __LINE__ ) "\n" ); \
75 if( (code) == paUnanticipatedHostError ) \
76 PA_DEBUG(( "Host error description: %s\n", snd_strerror( aErr_ ) )); \
77 result = (code); \
78 goto error; \
79 } \
80 } while( 0 );
81
82 #define ASSERT_CALL_(expr, success) \
83 aErr_ = (expr); \
84 assert( success == aErr_ );
85
86 static int aErr_; /* Used with ENSURE_ */
87
88 typedef enum
89 {
90 StreamDirection_In,
91 StreamDirection_Out
92 } StreamDirection;
93
94 typedef struct
95 {
96 PaSampleFormat hostSampleFormat;
97 unsigned long framesPerBuffer;
98 int numUserChannels, numHostChannels;
99 int userInterleaved, hostInterleaved;
100
101 snd_pcm_t *pcm;
102 snd_pcm_uframes_t bufferSize;
103 snd_pcm_format_t nativeFormat;
104 unsigned int nfds;
105 int ready; /* Marked ready from poll */
106 void **userBuffers;
107 snd_pcm_uframes_t offset;
108 StreamDirection streamDir;
109
110 snd_pcm_channel_area_t *channelAreas; /* Needed for channel adaption */
111 } PaAlsaStreamComponent;
112
113 /* Implementation specific stream structure */
114 typedef struct PaAlsaStream
115 {
116 PaUtilStreamRepresentation streamRepresentation;
117 PaUtilCpuLoadMeasurer cpuLoadMeasurer;
118 PaUtilBufferProcessor bufferProcessor;
119 PaUnixThread thread;
120
121 unsigned long framesPerUserBuffer, maxFramesPerHostBuffer;
122
123 int primeBuffers;
124 int callbackMode; /* bool: are we running in callback mode? */
125 int pcmsSynced; /* Have we successfully synced pcms */
126
127 /* the callback thread uses these to poll the sound device(s), waiting
128 * for data to be ready/available */
129 struct pollfd* pfds;
130 int pollTimeout;
131
132 /* Used in communication between threads */
133 volatile sig_atomic_t callback_finished; /* bool: are we in the "callback finished" state? */
134 volatile sig_atomic_t callbackAbort; /* Drop frames? */
135 volatile sig_atomic_t isActive; /* Is stream in active state? (Between StartStream and StopStream || !paContinue) */
136 PaUnixMutex stateMtx; /* Used to synchronize access to stream state */
137
138 int neverDropInput;
139
140 PaTime underrun;
141 PaTime overrun;
142
143 PaAlsaStreamComponent capture, playback;
144 }
145 PaAlsaStream;
146
147 /* PaAlsaHostApiRepresentation - host api datastructure specific to this implementation */
148
149 typedef struct PaAlsaHostApiRepresentation
150 {
151 PaUtilHostApiRepresentation baseHostApiRep;
152 PaUtilStreamInterface callbackStreamInterface;
153 PaUtilStreamInterface blockingStreamInterface;
154
155 PaUtilAllocationGroup *allocations;
156
157 PaHostApiIndex hostApiIndex;
158 }
159 PaAlsaHostApiRepresentation;
160
161 typedef struct PaAlsaDeviceInfo
162 {
163 PaDeviceInfo baseDeviceInfo;
164 char *alsaName;
165 int isPlug;
166 int minInputChannels;
167 int minOutputChannels;
168 }
169 PaAlsaDeviceInfo;
170
171 /* prototypes for functions declared in this file */
172
173 static void Terminate( struct PaUtilHostApiRepresentation *hostApi );
174 static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
175 const PaStreamParameters *inputParameters,
176 const PaStreamParameters *outputParameters,
177 double sampleRate );
178 static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
179 PaStream** s,
180 const PaStreamParameters *inputParameters,
181 const PaStreamParameters *outputParameters,
182 double sampleRate,
183 unsigned long framesPerBuffer,
184 PaStreamFlags streamFlags,
185 PaStreamCallback *callback,
186 void *userData );
187 static PaError CloseStream( PaStream* stream );
188 static PaError StartStream( PaStream *stream );
189 static PaError StopStream( PaStream *stream );
190 static PaError AbortStream( PaStream *stream );
191 static PaError IsStreamStopped( PaStream *s );
192 static PaError IsStreamActive( PaStream *stream );
193 static PaTime GetStreamTime( PaStream *stream );
194 static double GetStreamCpuLoad( PaStream* stream );
195 static PaError BuildDeviceList( PaAlsaHostApiRepresentation *hostApi );
196 static int SetApproximateSampleRate( snd_pcm_t *pcm, snd_pcm_hw_params_t *hwParams, double sampleRate );
197 static int GetExactSampleRate( snd_pcm_hw_params_t *hwParams, double *sampleRate );
198
199 /* Callback prototypes */
200 static void *CallbackThreadFunc( void *userData );
201
202 /* Blocking prototypes */
203 static signed long GetStreamReadAvailable( PaStream* s );
204 static signed long GetStreamWriteAvailable( PaStream* s );
205 static PaError ReadStream( PaStream* stream, void *buffer, unsigned long frames );
206 static PaError WriteStream( PaStream* stream, const void *buffer, unsigned long frames );
207
208
209 static const PaAlsaDeviceInfo *GetDeviceInfo( const PaUtilHostApiRepresentation *hostApi, int device )
210 {
211 return (const PaAlsaDeviceInfo *)hostApi->deviceInfos[device];
212 }
213
214 static void AlsaErrorHandler(const char *file, int line, const char *function, int err, const char *fmt, ...)
215 {
216 }
217
218 PaError PaAlsa_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex )
219 {
220 PaError result = paNoError;
221 PaAlsaHostApiRepresentation *alsaHostApi = NULL;
222
223 PA_UNLESS( alsaHostApi = (PaAlsaHostApiRepresentation*) PaUtil_AllocateMemory(
224 sizeof(PaAlsaHostApiRepresentation) ), paInsufficientMemory );
225 PA_UNLESS( alsaHostApi->allocations = PaUtil_CreateAllocationGroup(), paInsufficientMemory );
226 alsaHostApi->hostApiIndex = hostApiIndex;
227
228 *hostApi = (PaUtilHostApiRepresentation*)alsaHostApi;
229 (*hostApi)->info.structVersion = 1;
230 (*hostApi)->info.type = paALSA;
231 (*hostApi)->info.name = "ALSA";
232
233 (*hostApi)->Terminate = Terminate;
234 (*hostApi)->OpenStream = OpenStream;
235 (*hostApi)->IsFormatSupported = IsFormatSupported;
236
237 ENSURE_( snd_lib_error_set_handler(AlsaErrorHandler), paUnanticipatedHostError );
238
239 PA_ENSURE( BuildDeviceList( alsaHostApi ) );
240
241 PaUtil_InitializeStreamInterface( &alsaHostApi->callbackStreamInterface,
242 CloseStream, StartStream,
243 StopStream, AbortStream,
244 IsStreamStopped, IsStreamActive,
245 GetStreamTime, GetStreamCpuLoad,
246 PaUtil_DummyRead, PaUtil_DummyWrite,
247 PaUtil_DummyGetReadAvailable,
248 PaUtil_DummyGetWriteAvailable );
249
250 PaUtil_InitializeStreamInterface( &alsaHostApi->blockingStreamInterface,
251 CloseStream, StartStream,
252 StopStream, AbortStream,
253 IsStreamStopped, IsStreamActive,
254 GetStreamTime, PaUtil_DummyGetCpuLoad,
255 ReadStream, WriteStream,
256 GetStreamReadAvailable,
257 GetStreamWriteAvailable );
258
259 PA_ENSURE( PaUnixThreading_Initialize() );
260
261 return result;
262
263 error:
264 if( alsaHostApi )
265 {
266 if( alsaHostApi->allocations )
267 {
268 PaUtil_FreeAllAllocations( alsaHostApi->allocations );
269 PaUtil_DestroyAllocationGroup( alsaHostApi->allocations );
270 }
271
272 PaUtil_FreeMemory( alsaHostApi );
273 }
274
275 return result;
276 }
277
278 static void Terminate( struct PaUtilHostApiRepresentation *hostApi )
279 {
280 PaAlsaHostApiRepresentation *alsaHostApi = (PaAlsaHostApiRepresentation*)hostApi;
281
282 assert( hostApi );
283
284 if( alsaHostApi->allocations )
285 {
286 PaUtil_FreeAllAllocations( alsaHostApi->allocations );
287 PaUtil_DestroyAllocationGroup( alsaHostApi->allocations );
288 }
289
290 PaUtil_FreeMemory( alsaHostApi );
291 snd_config_update_free_global();
292 }
293
294 /** Determine max channels and default latencies.
295 *
296 * This function provides functionality to grope an opened (might be opened for capture or playback) pcm device for
297 * traits like max channels, suitable default latencies and default sample rate. Upon error, max channels is set to zero,
298 * and a suitable result returned. The device is closed before returning.
299 */
300 static PaError GropeDevice( snd_pcm_t* pcm, int isPlug, StreamDirection mode, int openBlocking,
301 PaAlsaDeviceInfo* devInfo, int* canMmap )
302 {
303 PaError result = paNoError;
304 snd_pcm_hw_params_t *hwParams;
305 snd_pcm_uframes_t lowLatency = 512, highLatency = 2048;
306 unsigned int minChans, maxChans;
307 int* minChannels, * maxChannels;
308 double * defaultLowLatency, * defaultHighLatency, * defaultSampleRate =
309 &devInfo->baseDeviceInfo.defaultSampleRate;
310 double defaultSr = *defaultSampleRate;
311
312 assert( pcm );
313
314 if( StreamDirection_In == mode )
315 {
316 minChannels = &devInfo->minInputChannels;
317 maxChannels = &devInfo->baseDeviceInfo.maxInputChannels;
318 defaultLowLatency = &devInfo->baseDeviceInfo.defaultLowInputLatency;
319 defaultHighLatency = &devInfo->baseDeviceInfo.defaultHighInputLatency;
320 }
321 else
322 {
323 minChannels = &devInfo->minOutputChannels;
324 maxChannels = &devInfo->baseDeviceInfo.maxOutputChannels;
325 defaultLowLatency = &devInfo->baseDeviceInfo.defaultLowOutputLatency;
326 defaultHighLatency = &devInfo->baseDeviceInfo.defaultHighOutputLatency;
327 }
328
329 ENSURE_( snd_pcm_nonblock( pcm, 0 ), paUnanticipatedHostError );
330
331 snd_pcm_hw_params_alloca( &hwParams );
332 snd_pcm_hw_params_any( pcm, hwParams );
333
334 *canMmap = snd_pcm_hw_params_test_access( pcm, hwParams, SND_PCM_ACCESS_MMAP_INTERLEAVED ) >= 0 ||
335 snd_pcm_hw_params_test_access( pcm, hwParams, SND_PCM_ACCESS_MMAP_NONINTERLEAVED ) >= 0;
336
337 if( defaultSr >= 0 )
338 {
339 /* Could be that the device opened in one mode supports samplerates that the other mode wont have,
340 * so try again .. */
341 if( SetApproximateSampleRate( pcm, hwParams, defaultSr ) < 0 )
342 {
343 defaultSr = -1.;
344 PA_DEBUG(( "%s: Original default samplerate failed, trying again ..\n", __FUNCTION__ ));
345 }
346 }
347
348 if( defaultSr < 0. ) /* Default sample rate not set */
349 {
350 unsigned int sampleRate = 44100; /* Will contain approximate rate returned by alsa-lib */
351 if( snd_pcm_hw_params_set_rate_near( pcm, hwParams, &sampleRate, NULL ) < 0)
352 {
353 result = paUnanticipatedHostError;
354 goto error;
355 }
356 ENSURE_( GetExactSampleRate( hwParams, &defaultSr ), paUnanticipatedHostError );
357 }
358
359 ENSURE_( snd_pcm_hw_params_get_channels_min( hwParams, &minChans ), paUnanticipatedHostError );
360 ENSURE_( snd_pcm_hw_params_get_channels_max( hwParams, &maxChans ), paUnanticipatedHostError );
361 assert( maxChans <= INT_MAX );
362 assert( maxChans > 0 ); /* Weird linking issue could cause wrong version of ALSA symbols to be called,
363 resulting in zeroed values */
364
365 /* XXX: Limit to sensible number (ALSA plugins accept a crazy amount of channels)? */
366 if( isPlug && maxChans > 128 )
367 {
368 maxChans = 128;
369 PA_DEBUG(( "%s: Limiting number of plugin channels to %u\n", __FUNCTION__, maxChans ));
370 }
371
372 /* TWEAKME:
373 *
374 * Giving values for default min and max latency is not
375 * straightforward. Here are our objectives:
376 *
377 * * for low latency, we want to give the lowest value
378 * that will work reliably. This varies based on the
379 * sound card, kernel, CPU, etc. I think it is better
380 * to give sub-optimal latency than to give a number
381 * too low and cause dropouts. My conservative
382 * estimate at this point is to base it on 4096-sample
383 * latency at 44.1 kHz, which gives a latency of 23ms.
384 * * for high latency we want to give a large enough
385 * value that dropouts are basically impossible. This
386 * doesn't really require as much tweaking, since
387 * providing too large a number will just cause us to
388 * select the nearest setting that will work at stream
389 * config time.
390 */
391 ENSURE_( snd_pcm_hw_params_set_buffer_size_near( pcm, hwParams, &lowLatency ), paUnanticipatedHostError );
392
393 /* Have to reset hwParams, to set new buffer size */
394 ENSURE_( snd_pcm_hw_params_any( pcm, hwParams ), paUnanticipatedHostError );
395 ENSURE_( snd_pcm_hw_params_set_buffer_size_near( pcm, hwParams, &highLatency ), paUnanticipatedHostError );
396
397 *minChannels = (int)minChans;
398 *maxChannels = (int)maxChans;
399 *defaultSampleRate = defaultSr;
400 *defaultLowLatency = (double) lowLatency / *defaultSampleRate;
401 *defaultHighLatency = (double) highLatency / *defaultSampleRate;
402
403 end:
404 snd_pcm_close( pcm );
405 return result;
406
407 error:
408 goto end;
409 }
410
411 /* Initialize device info with invalid values (maxInputChannels and maxOutputChannels are set to zero since these indicate
412 * wether input/output is available) */
413 static void InitializeDeviceInfo( PaDeviceInfo *deviceInfo )
414 {
415 deviceInfo->structVersion = -1;
416 deviceInfo->name = NULL;
417 deviceInfo->hostApi = -1;
418 deviceInfo->maxInputChannels = 0;
419 deviceInfo->maxOutputChannels = 0;
420 deviceInfo->defaultLowInputLatency = -1.;
421 deviceInfo->defaultLowOutputLatency = -1.;
422 deviceInfo->defaultHighInputLatency = -1.;
423 deviceInfo->defaultHighOutputLatency = -1.;
424 deviceInfo->defaultSampleRate = -1.;
425 }
426
427 /* Helper struct */
428 typedef struct
429 {
430 char *alsaName;
431 char *name;
432 int isPlug;
433 int hasPlayback;
434 int hasCapture;
435 } DeviceNames;
436
437 static PaError PaAlsa_StrDup( PaAlsaHostApiRepresentation *alsaApi,
438 char **dst,
439 const char *src)
440 {
441 PaError result = paNoError;
442 int len = strlen( src ) + 1;
443
444 /* PA_DEBUG(("PaStrDup %s %d\n", src, len)); */
445
446 PA_UNLESS( *dst = (char *)PaUtil_GroupAllocateMemory( alsaApi->allocations, len ),
447 paInsufficientMemory );
448 strncpy( *dst, src, len );
449
450 error:
451 return result;
452 }
453
454 /* Disregard some standard plugins
455 */
456 static int IgnorePlugin( const char *pluginId )
457 {
458 /* XXX: dmix and default ignored because after opening and closing, they seem to keep hogging resources.
459 */
460 static const char *ignoredPlugins[] = {"hw", "plughw", "plug", "dsnoop", "tee",
461 "file", "null", "shm", "cards", "dmix", "default", NULL};
462 int i = 0;
463 while( ignoredPlugins[i] )
464 {
465 if( !strcmp( pluginId, ignoredPlugins[i] ) )
466 {
467 return 1;
468 }
469 ++i;
470 }
471
472 return 0;
473 }
474
475 /* Build PaDeviceInfo list, ignore devices for which we cannot determine capabilities (possibly busy, sigh) */
476 static PaError BuildDeviceList( PaAlsaHostApiRepresentation *alsaApi )
477 {
478 PaUtilHostApiRepresentation *baseApi = &alsaApi->baseHostApiRep;
479 PaAlsaDeviceInfo *deviceInfoArray;
480 int cardIdx = -1, devIdx = 0;
481 snd_ctl_card_info_t *cardInfo;
482 PaError result = paNoError;
483 size_t numDeviceNames = 0, maxDeviceNames = 1, i;
484 DeviceNames *deviceNames = NULL;
485 snd_config_t *topNode = NULL;
486 snd_pcm_info_t *pcmInfo;
487 int res;
488 int blocking = SND_PCM_NONBLOCK;
489 char alsaCardName[50];
490 if( getenv( "PA_ALSA_INITIALIZE_BLOCK" ) && atoi( getenv( "PA_ALSA_INITIALIZE_BLOCK" ) ) )
491 blocking = 0;
492
493 /* These two will be set to the first working input and output device, respectively */
494 baseApi->info.defaultInputDevice = paNoDevice;
495 baseApi->info.defaultOutputDevice = paNoDevice;
496
497 /* count the devices by enumerating all the card numbers */
498
499 /* snd_card_next() modifies the integer passed to it to be:
500 * the index of the first card if the parameter is -1
501 * the index of the next card if the parameter is the index of a card
502 * -1 if there are no more cards
503 *
504 * The function itself returns 0 if it succeeded. */
505 cardIdx = -1;
506 snd_ctl_card_info_alloca( &cardInfo );
507 snd_pcm_info_alloca( &pcmInfo );
508 while( snd_card_next( &cardIdx ) == 0 && cardIdx >= 0 )
509 {
510 char *cardName;
511 int devIdx = -1;
512 snd_ctl_t *ctl;
513 char buf[50];
514
515 snprintf( alsaCardName, sizeof (alsaCardName), "hw:%d", cardIdx );
516
517 /* Acquire name of card */
518 if( snd_ctl_open( &ctl, alsaCardName, 0 ) < 0 )
519 {
520 /* Unable to open card :( */
521 continue;
522 }
523 snd_ctl_card_info( ctl, cardInfo );
524
525 PA_ENSURE( PaAlsa_StrDup( alsaApi, &cardName, snd_ctl_card_info_get_name( cardInfo )) );
526
527 while( snd_ctl_pcm_next_device( ctl, &devIdx ) == 0 && devIdx >= 0 )
528 {
529 char *alsaDeviceName, *deviceName;
530 size_t len;
531 int hasPlayback = 0, hasCapture = 0;
532 snprintf( buf, sizeof (buf), "%s:%d,%d", "hw", cardIdx, devIdx );
533
534 /* Obtain info about this particular device */
535 snd_pcm_info_set_device( pcmInfo, devIdx );
536 snd_pcm_info_set_subdevice( pcmInfo, 0 );
537 snd_pcm_info_set_stream( pcmInfo, SND_PCM_STREAM_CAPTURE );
538 if( snd_ctl_pcm_info( ctl, pcmInfo ) >= 0 )
539 {
540 hasCapture = 1;
541 }
542
543 snd_pcm_info_set_stream( pcmInfo, SND_PCM_STREAM_PLAYBACK );
544 if( snd_ctl_pcm_info( ctl, pcmInfo ) >= 0 )
545 {
546 hasPlayback = 1;
547 }
548
549 if( !hasPlayback && !hasCapture )
550 {
551 continue; /* Error */
552 }
553
554 /* The length of the string written by snprintf plus terminating 0 */
555 len = snprintf( NULL, 0, "%s: %s (%s)", cardName, snd_pcm_info_get_name( pcmInfo ), buf ) + 1;
556 PA_UNLESS( deviceName = (char *)PaUtil_GroupAllocateMemory( alsaApi->allocations, len ),
557 paInsufficientMemory );
558 snprintf( deviceName, len, "%s: %s (%s)", cardName,
559 snd_pcm_info_get_name( pcmInfo ), buf );
560
561 ++numDeviceNames;
562 if( !deviceNames || numDeviceNames > maxDeviceNames )
563 {
564 maxDeviceNames *= 2;
565 PA_UNLESS( deviceNames = (DeviceNames *) realloc( deviceNames, maxDeviceNames * sizeof (DeviceNames) ),
566 paInsufficientMemory );
567 }
568
569 PA_ENSURE( PaAlsa_StrDup( alsaApi, &alsaDeviceName, buf ) );
570
571 deviceNames[ numDeviceNames - 1 ].alsaName = alsaDeviceName;
572 deviceNames[ numDeviceNames - 1 ].name = deviceName;
573 deviceNames[ numDeviceNames - 1 ].isPlug = 0;
574 deviceNames[ numDeviceNames - 1 ].hasPlayback = hasPlayback;
575 deviceNames[ numDeviceNames - 1 ].hasCapture = hasCapture;
576 }
577 snd_ctl_close( ctl );
578 }
579
580 /* Iterate over plugin devices */
581 if( NULL == snd_config )
582 {
583 /* snd_config_update is called implicitly by some functions, if this hasn't happened snd_config will be NULL (bleh) */
584 ENSURE_( snd_config_update(), paUnanticipatedHostError );
585 PA_DEBUG(( "Updating snd_config\n" ));
586 }
587 assert( snd_config );
588 if( (res = snd_config_search( snd_config, "pcm", &topNode )) >= 0 )
589 {
590 snd_config_iterator_t i, next;
591
592 snd_config_for_each( i, next, topNode )
593 {
594 const char *tpStr = "unknown", *idStr = NULL;
595 int err = 0;
596
597 char *alsaDeviceName, *deviceName;
598 snd_config_t *n = snd_config_iterator_entry( i ), * tp = NULL;;
599
600 if( (err = snd_config_search( n, "type", &tp )) < 0 )
601 {
602 if( -ENOENT != err )
603 {
604 ENSURE_(err, paUnanticipatedHostError);
605 }
606 }
607 else
608 {
609 ENSURE_( snd_config_get_string( tp, &tpStr ), paUnanticipatedHostError );
610 }
611 ENSURE_( snd_config_get_id( n, &idStr ), paUnanticipatedHostError );
612 if( IgnorePlugin( idStr ) )
613 {
614 PA_DEBUG(( "%s: Ignoring ALSA plugin device %s of type %s\n", __FUNCTION__, idStr, tpStr ));
615 continue;
616 }
617 PA_DEBUG(( "%s: Found plugin %s of type %s\n", __FUNCTION__, idStr, tpStr ));
618
619 PA_UNLESS( alsaDeviceName = (char*)PaUtil_GroupAllocateMemory( alsaApi->allocations,
620 strlen(idStr) + 6 ), paInsufficientMemory );
621 strcpy( alsaDeviceName, idStr );
622 PA_UNLESS( deviceName = (char*)PaUtil_GroupAllocateMemory( alsaApi->allocations,
623 strlen(idStr) + 1 ), paInsufficientMemory );
624 strcpy( deviceName, idStr );
625
626 ++numDeviceNames;
627 if( !deviceNames || numDeviceNames > maxDeviceNames )
628 {
629 maxDeviceNames *= 2;
630 PA_UNLESS( deviceNames = (DeviceNames *) realloc( deviceNames, maxDeviceNames * sizeof (DeviceNames) ),
631 paInsufficientMemory );
632 }
633
634 deviceNames[numDeviceNames - 1].alsaName = alsaDeviceName;
635 deviceNames[numDeviceNames - 1].name = deviceName;
636 deviceNames[numDeviceNames - 1].isPlug = 1;
637 deviceNames[numDeviceNames - 1].hasPlayback = 1;
638 deviceNames[numDeviceNames - 1].hasCapture = 1;
639 }
640 }
641 else
642 PA_DEBUG(( "%s: Iterating over ALSA plugins failed: %s\n", __FUNCTION__, snd_strerror( res ) ));
643
644 /* allocate deviceInfo memory based on the number of devices */
645 PA_UNLESS( baseApi->deviceInfos = (PaDeviceInfo**)PaUtil_GroupAllocateMemory(
646 alsaApi->allocations, sizeof(PaDeviceInfo*) * (numDeviceNames) ), paInsufficientMemory );
647
648 /* allocate all device info structs in a contiguous block */
649 PA_UNLESS( deviceInfoArray = (PaAlsaDeviceInfo*)PaUtil_GroupAllocateMemory(
650 alsaApi->allocations, sizeof(PaAlsaDeviceInfo) * numDeviceNames ), paInsufficientMemory );
651
652 /* Loop over list of cards, filling in info, if a device is deemed unavailable (can't get name),
653 * it's ignored.
654 */
655 /* while( snd_card_next( &cardIdx ) == 0 && cardIdx >= 0 ) */
656 for( i = 0, devIdx = 0; i < numDeviceNames; ++i )
657 {
658 snd_pcm_t *pcm;
659 PaAlsaDeviceInfo *deviceInfo = &deviceInfoArray[devIdx];
660 PaDeviceInfo *baseDeviceInfo = &deviceInfo->baseDeviceInfo;
661 int canMmap = -1;
662
663 /* Zero fields */
664 InitializeDeviceInfo( baseDeviceInfo );
665
666 /* to determine device capabilities, we must open the device and query the
667 * hardware parameter configuration space */
668
669 /* Query capture */
670 if( deviceNames[i].hasCapture &&
671 snd_pcm_open( &pcm, deviceNames[i].alsaName, SND_PCM_STREAM_CAPTURE, blocking ) >= 0 )
672 {
673 if( GropeDevice( pcm, deviceNames[i].isPlug, StreamDirection_In, blocking, deviceInfo,
674 &canMmap ) != paNoError )
675 {
676 /* Error */
677 PA_DEBUG(("%s: Failed groping %s for capture\n", __FUNCTION__, deviceNames[i].alsaName));
678 continue;
679 }
680 }
681
682 /* Query playback */
683 if( deviceNames[i].hasPlayback &&
684 snd_pcm_open( &pcm, deviceNames[i].alsaName, SND_PCM_STREAM_PLAYBACK, blocking ) >= 0 )
685 {
686 if( GropeDevice( pcm, deviceNames[i].isPlug, StreamDirection_Out, blocking, deviceInfo,
687 &canMmap ) != paNoError )
688 {
689 /* Error */
690 PA_DEBUG(("%s: Failed groping %s for playback\n", __FUNCTION__, deviceNames[i].alsaName));
691 continue;
692 }
693 }
694
695 if( 0 == canMmap )
696 {
697 PA_DEBUG(("%s: Device %s doesn't support mmap\n", __FUNCTION__, deviceNames[i].alsaName));
698 continue;
699 }
700
701 baseDeviceInfo->structVersion = 2;
702 baseDeviceInfo->hostApi = alsaApi->hostApiIndex;
703 baseDeviceInfo->name = deviceNames[i].name;
704 deviceInfo->alsaName = deviceNames[i].alsaName;
705 deviceInfo->isPlug = deviceNames[i].isPlug;
706
707 /* A: Storing pointer to PaAlsaDeviceInfo object as pointer to PaDeviceInfo object.
708 * Should now be safe to add device info, unless the device supports neither capture nor playback
709 */
710 if( baseDeviceInfo->maxInputChannels > 0 || baseDeviceInfo->maxOutputChannels > 0 )
711 {
712 if( baseApi->info.defaultInputDevice == paNoDevice && baseDeviceInfo->maxInputChannels > 0 )
713 baseApi->info.defaultInputDevice = devIdx;
714 if( baseApi->info.defaultOutputDevice == paNoDevice && baseDeviceInfo->maxOutputChannels > 0 )
715 baseApi->info.defaultOutputDevice = devIdx;
716 PA_DEBUG(("%s: Adding device %s\n", __FUNCTION__, deviceNames[i].name));
717 baseApi->deviceInfos[devIdx++] = (PaDeviceInfo *) deviceInfo;
718 }
719 }
720 free( deviceNames );
721
722 baseApi->info.deviceCount = devIdx; /* Number of successfully queried devices */
723
724 end:
725 return result;
726
727 error:
728 /* No particular action */
729 goto end;
730 }
731
732 /* Check against known device capabilities */
733 static PaError ValidateParameters( const PaStreamParameters *parameters, PaUtilHostApiRepresentation *hostApi, StreamDirection mode )
734 {
735 PaError result = paNoError;
736 int maxChans;
737 const PaAlsaDeviceInfo *deviceInfo = NULL;
738 assert( parameters );
739
740 if( parameters->device != paUseHostApiSpecificDeviceSpecification )
741 {
742 assert( parameters->device < hostApi->info.deviceCount );
743 PA_UNLESS( parameters->hostApiSpecificStreamInfo == NULL, paBadIODeviceCombination );
744 deviceInfo = GetDeviceInfo( hostApi, parameters->device );
745 }
746 else
747 {
748 const PaAlsaStreamInfo *streamInfo = parameters->hostApiSpecificStreamInfo;
749
750 PA_UNLESS( parameters->device == paUseHostApiSpecificDeviceSpecification, paInvalidDevice );
751 PA_UNLESS( streamInfo->size == sizeof (PaAlsaStreamInfo) && streamInfo->version == 1,
752 paIncompatibleHostApiSpecificStreamInfo );
753 PA_UNLESS( streamInfo->deviceString != NULL, paInvalidDevice );
754
755 /* Skip further checking */
756 return paNoError;
757 }
758
759 assert( deviceInfo );
760 assert( parameters->hostApiSpecificStreamInfo == NULL );
761 maxChans = (StreamDirection_In == mode ? deviceInfo->baseDeviceInfo.maxInputChannels :
762 deviceInfo->baseDeviceInfo.maxOutputChannels);
763 PA_UNLESS( parameters->channelCount <= maxChans, paInvalidChannelCount );
764
765 error:
766 return result;
767 }
768
769 /* Given an open stream, what sample formats are available? */
770 static PaSampleFormat GetAvailableFormats( snd_pcm_t *pcm )
771 {
772 PaSampleFormat available = 0;
773 snd_pcm_hw_params_t *hwParams;
774 snd_pcm_hw_params_alloca( &hwParams );
775
776 snd_pcm_hw_params_any( pcm, hwParams );
777
778 if( snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_FLOAT ) >= 0)
779 available |= paFloat32;
780
781 if( snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_S32 ) >= 0)
782 available |= paInt32;
783
784 if( snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_S24 ) >= 0)
785 available |= paInt24;
786
787 if( snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_S16 ) >= 0)
788 available |= paInt16;
789
790 if( snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_U8 ) >= 0)
791 available |= paUInt8;
792
793 if( snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_S8 ) >= 0)
794 available |= paInt8;
795
796 return available;
797 }
798
799 static snd_pcm_format_t Pa2AlsaFormat( PaSampleFormat paFormat )
800 {
801 switch( paFormat )
802 {
803 case paFloat32:
804 return SND_PCM_FORMAT_FLOAT;
805
806 case paInt16:
807 return SND_PCM_FORMAT_S16;
808
809 case paInt24:
810 return SND_PCM_FORMAT_S24;
811
812 case paInt32:
813 return SND_PCM_FORMAT_S32;
814
815 case paInt8:
816 return SND_PCM_FORMAT_S8;
817
818 case paUInt8:
819 return SND_PCM_FORMAT_U8;
820
821 default:
822 return SND_PCM_FORMAT_UNKNOWN;
823 }
824 }
825
826 /** Open an ALSA pcm handle.
827 *
828 * The device to be open can be specified in a custom PaAlsaStreamInfo struct, or it will be a device number. In case of a
829 * device number, it maybe specified through an env variable (PA_ALSA_PLUGHW) that we should open the corresponding plugin
830 * device.
831 */
832 static PaError AlsaOpen( const PaUtilHostApiRepresentation *hostApi, const PaStreamParameters *params, StreamDirection
833 streamDir, snd_pcm_t **pcm )
834 {
835 PaError result = paNoError;
836 int ret;
837 const char *deviceName = alloca( 50 );
838 const PaAlsaDeviceInfo *deviceInfo = NULL;
839 PaAlsaStreamInfo *streamInfo = (PaAlsaStreamInfo *)params->hostApiSpecificStreamInfo;
840
841 if( !streamInfo )
842 {
843 int usePlug = 0;
844 deviceInfo = GetDeviceInfo( hostApi, params->device );
845
846 /* If device name starts with hw: and PA_ALSA_PLUGHW is 1, we open the plughw device instead */
847 if( !strncmp( "hw:", deviceInfo->alsaName, 3 ) && getenv( "PA_ALSA_PLUGHW" ) )
848 usePlug = atoi( getenv( "PA_ALSA_PLUGHW" ) );
849 if( usePlug )
850 snprintf( (char *) deviceName, 50, "plug%s", deviceInfo->alsaName );
851 else
852 deviceName = deviceInfo->alsaName;
853 }
854 else
855 deviceName = streamInfo->deviceString;
856
857 PA_DEBUG(( "%s: Opening device %s\n", __FUNCTION__, deviceName ));
858 if( (ret = snd_pcm_open( pcm, deviceName, streamDir == StreamDirection_In ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
859 SND_PCM_NONBLOCK )) < 0 )
860 {
861 /* Not to be closed */
862 *pcm = NULL;
863 ENSURE_( ret, ret == -EBUSY ? paDeviceUnavailable : paBadIODeviceCombination );
864 }
865 ENSURE_( snd_pcm_nonblock( *pcm, 0 ), paUnanticipatedHostError );
866
867 end:
868 return result;
869
870 error:
871 goto end;
872 }
873
874 static PaError TestParameters( const PaUtilHostApiRepresentation *hostApi, const PaStreamParameters *parameters,
875 double sampleRate, StreamDirection streamDir )
876 {
877 PaError result = paNoError;
878 snd_pcm_t *pcm = NULL;
879 PaSampleFormat availableFormats;
880 /* We are able to adapt to a number of channels less than what the device supports */
881 unsigned int numHostChannels;
882 PaSampleFormat hostFormat;
883 snd_pcm_hw_params_t *hwParams;
884 snd_pcm_hw_params_alloca( &hwParams );
885
886 if( !parameters->hostApiSpecificStreamInfo )
887 {
888 const PaAlsaDeviceInfo *devInfo = GetDeviceInfo( hostApi, parameters->device );
889 numHostChannels = PA_MAX( parameters->channelCount, StreamDirection_In == streamDir ?
890 devInfo->minInputChannels : devInfo->minOutputChannels );
891 }
892 else
893 numHostChannels = parameters->channelCount;
894
895 PA_ENSURE( AlsaOpen( hostApi, parameters, streamDir, &pcm ) );
896
897 snd_pcm_hw_params_any( pcm, hwParams );
898
899 if( SetApproximateSampleRate( pcm, hwParams, sampleRate ) < 0 )
900 {
901 result = paInvalidSampleRate;
902 goto error;
903 }
904
905 if( snd_pcm_hw_params_set_channels( pcm, hwParams, numHostChannels ) < 0 )
906 {
907 result = paInvalidChannelCount;
908 goto error;
909 }
910
911 /* See if we can find a best possible match */
912 availableFormats = GetAvailableFormats( pcm );
913 PA_ENSURE( hostFormat = PaUtil_SelectClosestAvailableFormat( availableFormats, parameters->sampleFormat ) );
914 ENSURE_( snd_pcm_hw_params_set_format( pcm, hwParams, Pa2AlsaFormat( hostFormat ) ), paUnanticipatedHostError );
915
916 {
917 /* It happens that this call fails because the device is busy */
918 int ret = 0;
919 if( (ret = snd_pcm_hw_params( pcm, hwParams )) < 0)
920 {
921 ENSURE_( ret, ret == -EBUSY ? paDeviceUnavailable : paUnanticipatedHostError );
922 }
923 }
924
925 end:
926 if( pcm )
927 {
928 snd_pcm_close( pcm );
929 }
930 return result;
931
932 error:
933 goto end;
934 }
935
936 static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
937 const PaStreamParameters *inputParameters,
938 const PaStreamParameters *outputParameters,
939 double sampleRate )
940 {
941 int inputChannelCount = 0, outputChannelCount = 0;
942 PaSampleFormat inputSampleFormat, outputSampleFormat;
943 PaError result = paFormatIsSupported;
944
945 if( inputParameters )
946 {
947 PA_ENSURE( ValidateParameters( inputParameters, hostApi, StreamDirection_In ) );
948
949 inputChannelCount = inputParameters->channelCount;
950 inputSampleFormat = inputParameters->sampleFormat;
951 }
952
953 if( outputParameters )
954 {
955 PA_ENSURE( ValidateParameters( outputParameters, hostApi, StreamDirection_Out ) );
956
957 outputChannelCount = outputParameters->channelCount;
958 outputSampleFormat = outputParameters->sampleFormat;
959 }
960
961 if( inputChannelCount )
962 {
963 if( (result = TestParameters( hostApi, inputParameters, sampleRate, StreamDirection_In ))
964 != paNoError )
965 goto error;
966 }
967 if ( outputChannelCount )
968 {
969 if( (result = TestParameters( hostApi, outputParameters, sampleRate, StreamDirection_Out ))
970 != paNoError )
971 goto error;
972 }
973
974 return paFormatIsSupported;
975
976 error:
977 return result;
978 }
979
980 static PaError PaAlsaStreamComponent_Initialize( PaAlsaStreamComponent *self, PaAlsaHostApiRepresentation *alsaApi,
981 const PaStreamParameters *params, StreamDirection streamDir, int callbackMode )
982 {
983 PaError result = paNoError;
984 PaSampleFormat userSampleFormat = params->sampleFormat, hostSampleFormat;
985 assert( params->channelCount > 0 );
986
987 /* Make sure things have an initial value */
988 memset( self, 0, sizeof (PaAlsaStreamComponent) );
989
990 if( NULL == params->hostApiSpecificStreamInfo )
991 {
992 const PaAlsaDeviceInfo *devInfo = GetDeviceInfo( &alsaApi->baseHostApiRep, params->device );
993 self->numHostChannels = PA_MAX( params->channelCount, StreamDirection_In == streamDir ? devInfo->minInputChannels
994 : devInfo->minOutputChannels );
995 }
996 else
997 {
998 /* We're blissfully unaware of the minimum channelCount */
999 self->numHostChannels = params->channelCount;
1000 }
1001
1002 PA_ENSURE( AlsaOpen( &alsaApi->baseHostApiRep, params, streamDir, &self->pcm ) );
1003 self->nfds = snd_pcm_poll_descriptors_count( self->pcm );
1004 hostSampleFormat = PaUtil_SelectClosestAvailableFormat( GetAvailableFormats( self->pcm ), userSampleFormat );
1005
1006 self->hostSampleFormat = hostSampleFormat;
1007 self->nativeFormat = Pa2AlsaFormat( hostSampleFormat );
1008 self->hostInterleaved = self->userInterleaved = !(userSampleFormat & paNonInterleaved);
1009 self->numUserChannels = params->channelCount;
1010 self->streamDir = streamDir;
1011
1012 if( !callbackMode && !self->userInterleaved )
1013 {
1014 /* Pre-allocate non-interleaved user provided buffers */
1015 PA_UNLESS( self->userBuffers = PaUtil_AllocateMemory( sizeof (void *) * self->numUserChannels ),
1016 paInsufficientMemory );
1017 }
1018
1019 error:
1020 return result;
1021 }
1022
1023 static void PaAlsaStreamComponent_Terminate( PaAlsaStreamComponent *self )
1024 {
1025 snd_pcm_close( self->pcm );
1026 if( self->userBuffers )
1027 PaUtil_FreeMemory( self->userBuffers );
1028 }
1029
1030 int nearbyint_(float value) {
1031 if( value - (int)value > .5 )
1032 return (int)ceil( value );
1033 return (int)floor( value );
1034 }
1035
1036 /** Initiate configuration, preparing for determining a period size suitable for both capture and playback components.
1037 *
1038 */
1039 static PaError PaAlsaStreamComponent_InitialConfigure( PaAlsaStreamComponent *self, const PaStreamParameters *params,
1040 int primeBuffers, snd_pcm_hw_params_t *hwParams, double *sampleRate )
1041 {
1042 /* Configuration consists of setting all of ALSA's parameters.
1043 * These parameters come in two flavors: hardware parameters
1044 * and software paramters. Hardware parameters will affect
1045 * the way the device is initialized, software parameters
1046 * affect the way ALSA interacts with me, the user-level client.
1047 */
1048
1049 PaError result = paNoError;
1050 snd_pcm_access_t accessMode, alternateAccessMode;
1051 int dir = 0;
1052 snd_pcm_t *pcm = self->pcm;
1053 double sr = *sampleRate;
1054 unsigned int minPeriods = 2;
1055
1056 /* self->framesPerBuffer = framesPerHostBuffer; */
1057
1058 /* ... fill up the configuration space with all possibile
1059 * combinations of parameters this device will accept */
1060 ENSURE_( snd_pcm_hw_params_any( pcm, hwParams ), paUnanticipatedHostError );
1061
1062 ENSURE_( snd_pcm_hw_params_set_periods_integer( pcm, hwParams ), paUnanticipatedHostError );
1063 /* I think there should be at least 2 periods (even though ALSA doesn't appear to enforce this) */
1064 dir = 0;
1065 ENSURE_( snd_pcm_hw_params_set_periods_min( pcm, hwParams, &minPeriods, &dir ), paUnanticipatedHostError );
1066
1067 if( self->userInterleaved )
1068 {
1069 accessMode = SND_PCM_ACCESS_MMAP_INTERLEAVED;
1070 alternateAccessMode = SND_PCM_ACCESS_MMAP_NONINTERLEAVED;
1071 }
1072 else
1073 {
1074 accessMode = SND_PCM_ACCESS_MMAP_NONINTERLEAVED;
1075 alternateAccessMode = SND_PCM_ACCESS_MMAP_INTERLEAVED;
1076 }
1077 /* If requested access mode fails, try alternate mode */
1078 if( snd_pcm_hw_params_set_access( pcm, hwParams, accessMode ) < 0 )
1079 {
1080 int err = 0;
1081 if( (err = snd_pcm_hw_params_set_access( pcm, hwParams, alternateAccessMode )) < 0)
1082 {
1083 result = paUnanticipatedHostError;
1084 if( -EINVAL == err )
1085 {
1086 PaUtil_SetLastHostErrorInfo( paALSA, err, "PA ALSA requires that a device supports mmap access" );
1087 }
1088 else
1089 {
1090 PaUtil_SetLastHostErrorInfo( paALSA, err, snd_strerror( err ) );
1091 }
1092 goto error;
1093 }
1094 /* Flip mode */
1095 self->hostInterleaved = !self->userInterleaved;
1096 }
1097
1098 ENSURE_( snd_pcm_hw_params_set_format( pcm, hwParams, self->nativeFormat ), paUnanticipatedHostError );
1099
1100 ENSURE_( SetApproximateSampleRate( pcm, hwParams, sr ), paInvalidSampleRate );
1101 ENSURE_( GetExactSampleRate( hwParams, &sr ), paUnanticipatedHostError );
1102 /* reject if there's no sample rate within 1% of the one requested */
1103 if( (fabs( *sampleRate - sr ) / *sampleRate) > 0.01 )
1104 {
1105 PA_DEBUG(("%s: Wanted %f, closest sample rate was %d\n", __FUNCTION__, sampleRate, sr ));
1106 PA_ENSURE( paInvalidSampleRate );
1107 }
1108
1109 ENSURE_( snd_pcm_hw_params_set_channels( pcm, hwParams, self->numHostChannels ), paInvalidChannelCount );
1110
1111 *sampleRate = sr;
1112
1113 end:
1114 return result;
1115
1116 error:
1117 /* No particular action */
1118 goto end;
1119 }
1120
1121 /** Finish the configuration of the component's ALSA device.
1122 *
1123 * As part of this method, the component's bufferSize attribute will be set.
1124 * @param latency: The latency for this component.
1125 */
1126 static PaError PaAlsaStreamComponent_FinishConfigure( PaAlsaStreamComponent *self, snd_pcm_hw_params_t* hwParams,
1127 const PaStreamParameters *params, int primeBuffers, double sampleRate, PaTime* latency )
1128 {
1129 PaError result = paNoError;
1130 snd_pcm_sw_params_t* swParams;
1131 snd_pcm_uframes_t bufSz = 0;
1132 *latency = -1.;
1133
1134 snd_pcm_sw_params_alloca( &swParams );
1135
1136 bufSz = (params->suggestedLatency * sampleRate) + self->framesPerBuffer; /* One period does not count as latency */
1137 ENSURE_( snd_pcm_hw_params_set_buffer_size_near( self->pcm, hwParams, &bufSz ), paUnanticipatedHostError );
1138
1139 /* Set the parameters! */
1140 ENSURE_( snd_pcm_hw_params( self->pcm, hwParams ), paUnanticipatedHostError );
1141 ENSURE_( snd_pcm_hw_params_get_buffer_size( hwParams, &self->bufferSize ), paUnanticipatedHostError );
1142 /* Latency in seconds, one period is not counted as latency */
1143 *latency = (self->bufferSize - self->framesPerBuffer) / sampleRate;
1144
1145 /* Now software parameters... */
1146 ENSURE_( snd_pcm_sw_params_current( self->pcm, swParams ), paUnanticipatedHostError );
1147
1148 ENSURE_( snd_pcm_sw_params_set_start_threshold( self->pcm, swParams, self->framesPerBuffer ), paUnanticipatedHostError );
1149 ENSURE_( snd_pcm_sw_params_set_stop_threshold( self->pcm, swParams, self->bufferSize ), paUnanticipatedHostError );
1150
1151 /* Silence buffer in the case of underrun */
1152 if( !primeBuffers ) /* XXX: Make sense? */
1153 {
1154 snd_pcm_uframes_t boundary;
1155 ENSURE_( snd_pcm_sw_params_get_boundary( swParams, &boundary ), paUnanticipatedHostError );
1156 ENSURE_( snd_pcm_sw_params_set_silence_threshold( self->pcm, swParams, 0 ), paUnanticipatedHostError );
1157 ENSURE_( snd_pcm_sw_params_set_silence_size( self->pcm, swParams, boundary ), paUnanticipatedHostError );
1158 }
1159
1160 ENSURE_( snd_pcm_sw_params_set_avail_min( self->pcm, swParams, self->framesPerBuffer ), paUnanticipatedHostError );
1161 ENSURE_( snd_pcm_sw_params_set_xfer_align( self->pcm, swParams, 1 ), paUnanticipatedHostError );
1162 ENSURE_( snd_pcm_sw_params_set_tstamp_mode( self->pcm, swParams, SND_PCM_TSTAMP_MMAP ), paUnanticipatedHostError );
1163
1164 /* Set the parameters! */
1165 ENSURE_( snd_pcm_sw_params( self->pcm, swParams ), paUnanticipatedHostError );
1166
1167 error:
1168 return result;
1169 }
1170
1171 static PaError PaAlsaStream_Initialize( PaAlsaStream *self, PaAlsaHostApiRepresentation *alsaApi, const PaStreamParameters *inParams,
1172 const PaStreamParameters *outParams, double sampleRate, unsigned long framesPerUserBuffer, PaStreamCallback callback,
1173 PaStreamFlags streamFlags, void *userData )
1174 {
1175 PaError result = paNoError;
1176 assert( self );
1177
1178 memset( self, 0, sizeof (PaAlsaStream) );
1179
1180 if( NULL != callback )
1181 {
1182 PaUtil_InitializeStreamRepresentation( &self->streamRepresentation,
1183 &alsaApi->callbackStreamInterface,
1184 callback, userData );
1185 self->callbackMode = 1;
1186 }
1187 else
1188 {
1189 PaUtil_InitializeStreamRepresentation( &self->streamRepresentation,
1190 &alsaApi->blockingStreamInterface,
1191 NULL, userData );
1192 }
1193
1194 self->framesPerUserBuffer = framesPerUserBuffer;
1195 self->neverDropInput = streamFlags & paNeverDropInput;
1196 /* XXX: Ignore paPrimeOutputBuffersUsingStreamCallback untill buffer priming is fully supported in pa_process.c */
1197 /*
1198 if( outParams & streamFlags & paPrimeOutputBuffersUsingStreamCallback )
1199 self->primeBuffers = 1;
1200 */
1201 memset( &self->capture, 0, sizeof (PaAlsaStreamComponent) );
1202 memset( &self->playback, 0, sizeof (PaAlsaStreamComponent) );
1203 if( inParams )
1204 {
1205 PA_ENSURE( PaAlsaStreamComponent_Initialize( &self->capture, alsaApi, inParams, StreamDirection_In, NULL != callback ) );
1206 }
1207 if( outParams )
1208 {
1209 PA_ENSURE( PaAlsaStreamComponent_Initialize( &self->playback, alsaApi, outParams, StreamDirection_Out, NULL != callback ) );
1210 }
1211
1212 assert( self->capture.nfds || self->playback.nfds );
1213
1214 PA_UNLESS( self->pfds = (struct pollfd*)PaUtil_AllocateMemory( (self->capture.nfds +
1215 self->playback.nfds) * sizeof (struct pollfd) ), paInsufficientMemory );
1216
1217 PaUtil_InitializeCpuLoadMeasurer( &self->cpuLoadMeasurer, sampleRate );
1218 ASSERT_CALL_( PaUnixMutex_Initialize( &self->stateMtx ), paNoError );
1219
1220 error:
1221 return result;
1222 }
1223
1224 /** Free resources associated with stream, and eventually stream itself.
1225 *
1226 * Frees allocated memory, and terminates individual StreamComponents.
1227 */
1228 static void PaAlsaStream_Terminate( PaAlsaStream *self )
1229 {
1230 assert( self );
1231
1232 if( self->capture.pcm )
1233 {
1234 PaAlsaStreamComponent_Terminate( &self->capture );
1235 }
1236 if( self->playback.pcm )
1237 {
1238 PaAlsaStreamComponent_Terminate( &self->playback );
1239 }
1240
1241 PaUtil_FreeMemory( self->pfds );
1242 ASSERT_CALL_( PaUnixMutex_Terminate( &self->stateMtx ), paNoError );
1243
1244 PaUtil_FreeMemory( self );
1245 }
1246
1247 /** Calculate polling timeout
1248 *
1249 * @param frames Time to wait
1250 * @return Polling timeout in milliseconds
1251 */
1252 static int CalculatePollTimeout( const PaAlsaStream *stream, unsigned long frames )
1253 {
1254 assert( stream->streamRepresentation.streamInfo.sampleRate > 0.0 );
1255 /* Period in msecs, rounded up */
1256 return (int)ceil( 1000 * frames / stream->streamRepresentation.streamInfo.sampleRate );
1257 }
1258
1259 /** Determine size per host buffer.
1260 *
1261 * During this method call, the component's framesPerBuffer attribute gets computed, and the corresponding period size
1262 * gets configured for the device.
1263 * @param accurate: If the configured period size is non-integer, this will be set to 0.
1264 */
1265 static PaError PaAlsaStreamComponent_DetermineFramesPerBuffer( PaAlsaStreamComponent* self, const PaStreamParameters* params,
1266 unsigned long framesPerUserBuffer, double sampleRate, snd_pcm_hw_params_t* hwParams, int* accurate )
1267 {
1268 PaError result = paNoError;
1269 unsigned long bufferSize = params->suggestedLatency * sampleRate, framesPerHostBuffer;
1270 int dir = 0;
1271
1272 {
1273 snd_pcm_uframes_t tmp;
1274 snd_pcm_hw_params_get_buffer_size_min( hwParams, &tmp );
1275 bufferSize = PA_MAX( bufferSize, tmp );
1276 snd_pcm_hw_params_get_buffer_size_max( hwParams, &tmp );
1277 bufferSize = PA_MIN( bufferSize, tmp );
1278 }
1279
1280 assert( bufferSize > 0 );
1281
1282 if( framesPerUserBuffer != paFramesPerBufferUnspecified )
1283 {
1284 /* Preferably the host buffer size should be a multiple of the user buffer size */
1285
1286 if( bufferSize > framesPerUserBuffer )
1287 {
1288 snd_pcm_uframes_t remainder = bufferSize % framesPerUserBuffer;
1289 if( remainder > framesPerUserBuffer / 2. )
1290 bufferSize += framesPerUserBuffer - remainder;
1291 else
1292 bufferSize -= remainder;
1293
1294 assert( bufferSize % framesPerUserBuffer == 0 );
1295 }
1296 else if( framesPerUserBuffer % bufferSize != 0 )
1297 {
1298 /* Find a good compromise between user specified latency and buffer size */
1299 if( bufferSize > framesPerUserBuffer * .75 )
1300 {
1301 bufferSize = framesPerUserBuffer;
1302 }
1303 else
1304 {
1305 snd_pcm_uframes_t newSz = framesPerUserBuffer;
1306 while( newSz / 2 >= bufferSize )
1307 {
1308 if( framesPerUserBuffer % (newSz / 2) != 0 )
1309 {
1310 /* No use dividing any further */
1311 break;
1312 }
1313 newSz /= 2;
1314 }
1315 bufferSize = newSz;
1316 }
1317
1318 assert( framesPerUserBuffer % bufferSize == 0 );
1319 }
1320 }
1321
1322 /* Using 5 as a base number of periods, we try to approximate the suggested latency (+1 period),
1323 finding a combination of period/buffer size which best fits these constraints */
1324 {
1325 unsigned numPeriods = 4, maxPeriods = 0;
1326 /* It may be that the device only supports 2 periods for instance */
1327 dir = 0;
1328 ENSURE_( snd_pcm_hw_params_get_periods_max( hwParams, &maxPeriods, &dir ), paUnanticipatedHostError );
1329 assert( maxPeriods > 1 );
1330 /* One period is not counted as latency */
1331 maxPeriods -= 1;
1332 numPeriods = PA_MIN( maxPeriods, numPeriods );
1333
1334 if( framesPerUserBuffer != paFramesPerBufferUnspecified )
1335 {
1336 framesPerHostBuffer = framesPerUserBuffer;
1337 if( framesPerHostBuffer < bufferSize )
1338 {
1339 while( bufferSize / framesPerHostBuffer > numPeriods )
1340 {
1341 framesPerHostBuffer *= 2;
1342 }
1343 }
1344 else
1345 {
1346 while( bufferSize / framesPerHostBuffer < numPeriods )
1347 {
1348 if( framesPerUserBuffer % (framesPerHostBuffer / 2) != 0 )
1349 {
1350 /* Can't be divided any further */
1351 break;
1352 }
1353 framesPerHostBuffer /= 2;
1354 }
1355 }
1356
1357 if( framesPerHostBuffer < framesPerUserBuffer )
1358 {
1359 assert( framesPerUserBuffer % framesPerHostBuffer == 0 );
1360 if( snd_pcm_hw_params_test_period_size( self->pcm, hwParams, framesPerHostBuffer, 0 ) < 0 )
1361 {
1362 if( snd_pcm_hw_params_test_period_size( self->pcm, hwParams, framesPerHostBuffer * 2, 0 ) == 0 )
1363 framesPerHostBuffer *= 2;
1364 else if( snd_pcm_hw_params_test_period_size( self->pcm, hwParams, framesPerHostBuffer / 2, 0 ) == 0 )
1365 framesPerHostBuffer /= 2;
1366 }
1367 }
1368 else
1369 {
1370 assert( framesPerHostBuffer % framesPerUserBuffer == 0 );
1371 if( snd_pcm_hw_params_test_period_size( self->pcm, hwParams, framesPerHostBuffer, 0 ) < 0 )
1372 {
1373 if( snd_pcm_hw_params_test_period_size( self->pcm, hwParams, framesPerHostBuffer + framesPerUserBuffer, 0 ) == 0 )
1374 framesPerHostBuffer += framesPerUserBuffer;
1375 else if( snd_pcm_hw_params_test_period_size( self->pcm, hwParams, framesPerHostBuffer - framesPerUserBuffer, 0 ) == 0 )
1376 framesPerHostBuffer -= framesPerUserBuffer;
1377 }
1378 }
1379 }
1380 else
1381 {
1382 framesPerHostBuffer = bufferSize / numPeriods;
1383 }
1384 }
1385
1386 assert( framesPerHostBuffer > 0 );
1387 {
1388 snd_pcm_uframes_t min = 0, max = 0;
1389 ENSURE_( snd_pcm_hw_params_get_period_size_min( hwParams, &min, NULL ), paUnanticipatedHostError );
1390 ENSURE_( snd_pcm_hw_params_get_period_size_max( hwParams, &max, NULL ), paUnanticipatedHostError );
1391
1392 if( framesPerHostBuffer < min )
1393 {
1394 framesPerHostBuffer = min;
1395 PA_DEBUG(( "%s: The determined period size (%lu) is less than minimum (%lu)\n", __FUNCTION__,
1396 framesPerHostBuffer, min ));
1397 }
1398 else if( framesPerHostBuffer > max )
1399 {
1400 framesPerHostBuffer = max;
1401 PA_DEBUG(( "%s: The determined period size (%lu) is greater than maximum (%lu)\n", __FUNCTION__,
1402 framesPerHostBuffer, max ));
1403 }
1404
1405 assert( framesPerHostBuffer >= min && framesPerHostBuffer <= max );
1406 dir = 0;
1407 ENSURE_( snd_pcm_hw_params_set_period_size_near( self->pcm, hwParams, &framesPerHostBuffer, &dir ),
1408 paUnanticipatedHostError );
1409 if( dir != 0 )
1410 {
1411 PA_DEBUG(( "%s: The configured period size is non-integer.\n", __FUNCTION__, dir ));
1412 *accurate = 0;
1413 }
1414 }
1415 self->framesPerBuffer = framesPerHostBuffer;
1416
1417 error:
1418 return result;
1419 }
1420
1421 /* We need to determine how many frames per host buffer (period) to use. Our
1422 * goals are to provide the best possible performance, but also to
1423 * honor the requested latency settings as closely as we can. Therefore this
1424 * decision is based on:
1425 *
1426 * - the period sizes that playback and/or capture support. The
1427 * host buffer size has to be one of these.
1428 * - the number of periods that playback and/or capture support.
1429 *
1430 * We want to make period_size*(num_periods-1) to be as close as possible
1431 * to latency*rate for both playback and capture.
1432 *
1433 * This method will determine suitable period sizes for capture and playback handles, and report the maximum number of
1434 * frames per host buffer. The latter is relevant, in case we should be so unfortunate that the period size differs
1435 * between capture and playback. If this should happen, the stream's hostBufferSizeMode attribute will be set to
1436 * paUtilBoundedHostBufferSize, because the best we can do is limit the size of individual host buffers to the upper
1437 * bound. The size of host buffers scheduled for processing should only matter if the user has specified a buffer size,
1438 * but when he/she does we must strive for an optimal configuration. By default we'll opt for a fixed host buffer size,
1439 * which should be fine if the period size is the same for capture and playback. In general, if there is a specified user
1440 * buffer size, this method tries it best to determine a period size which is a multiple of the user buffer size.
1441 *
1442 * The framesPerBuffer attributes of the individual capture and playback components of the stream are set to corresponding
1443 * values determined here. Since these should be reported as
1444 *
1445 * This is one of those blocks of code that will just take a lot of
1446 * refinement to be any good.
1447 *
1448 * In the full-duplex case it is possible that the routine was unable
1449 * to find a number of frames per buffer acceptable to both devices
1450 * TODO: Implement an algorithm to find the value closest to acceptance
1451 * by both devices, to minimize difference between period sizes?
1452 *
1453 * @param determinedFramesPerHostBuffer: The determined host buffer size.
1454 */
1455 static PaError PaAlsaStream_DetermineFramesPerBuffer( PaAlsaStream* self, double sampleRate, const PaStreamParameters* inputParameters,
1456 const PaStreamParameters* outputParameters, unsigned long framesPerUserBuffer, snd_pcm_hw_params_t* hwParamsCapture,
1457 snd_pcm_hw_params_t* hwParamsPlayback, PaUtilHostBufferSizeMode* hostBufferSizeMode )
1458 {
1459 PaError result = paNoError;
1460 unsigned long framesPerHostBuffer = 0;
1461 int dir = 0;
1462 int accurate = 1;
1463
1464 if( self->capture.pcm && self->playback.pcm )
1465 {
1466 if( framesPerUserBuffer == paFramesPerBufferUnspecified )
1467 {
1468 snd_pcm_uframes_t desiredLatency, e, minPeriodSize, maxPeriodSize, optimalPeriodSize, periodSize,
1469 minCapture, minPlayback, maxCapture, maxPlayback;
1470
1471 /* Come up with a common desired latency */
1472
1473 dir = 0;
1474 ENSURE_( snd_pcm_hw_params_get_period_size_min( hwParamsCapture, &minCapture, &dir ), paUnanticipatedHostError );
1475 dir = 0;
1476 ENSURE_( snd_pcm_hw_params_get_period_size_min( hwParamsPlayback, &minPlayback, &dir ), paUnanticipatedHostError );
1477 dir = 0;
1478 ENSURE_( snd_pcm_hw_params_get_period_size_max( hwParamsCapture, &maxCapture, &dir ), paUnanticipatedHostError );
1479 dir = 0;
1480 ENSURE_( snd_pcm_hw_params_get_period_size_max( hwParamsPlayback, &maxPlayback, &dir ), paUnanticipatedHostError );
1481 minPeriodSize = PA_MAX( minPlayback, minCapture );
1482 maxPeriodSize = PA_MIN( maxPlayback, maxCapture );
1483 PA_UNLESS( minPeriodSize <= maxPeriodSize, paBadIODeviceCombination );
1484
1485 desiredLatency = (snd_pcm_uframes_t)(PA_MIN( outputParameters->suggestedLatency, inputParameters->suggestedLatency )
1486 * sampleRate);
1487 /* Clamp desiredLatency */
1488 {
1489 snd_pcm_uframes_t maxBufferSize;
1490 snd_pcm_uframes_t maxBufferSizeCapture, maxBufferSizePlayback;
1491 ENSURE_( snd_pcm_hw_params_get_buffer_size_max( hwParamsCapture, &maxBufferSizeCapture ), paUnanticipatedHostError );
1492 ENSURE_( snd_pcm_hw_params_get_buffer_size_max( hwParamsPlayback, &maxBufferSizePlayback ), paUnanticipatedHostError );
1493 maxBufferSize = PA_MIN( maxBufferSizeCapture, maxBufferSizePlayback );
1494
1495 desiredLatency = PA_MIN( desiredLatency, maxBufferSize );
1496 }
1497
1498 /* Find the closest power of 2 */
1499 e = ilogb( minPeriodSize );
1500 if( minPeriodSize & (minPeriodSize - 1) )
1501 e += 1;
1502 periodSize = (snd_pcm_uframes_t)pow( 2, e );
1503
1504 while( periodSize <= maxPeriodSize )
1505 {
1506 if( snd_pcm_hw_params_test_period_size( self->playback.pcm, hwParamsPlayback, periodSize, 0 ) >= 0 &&
1507 snd_pcm_hw_params_test_period_size( self->capture.pcm, hwParamsCapture, periodSize, 0 ) >= 0 )
1508 break; /* Ok! */
1509
1510 periodSize *= 2;
1511 }
1512
1513 /* 4 periods considered optimal */
1514 optimalPeriodSize = PA_MAX( desiredLatency / 4, minPeriodSize );
1515 optimalPeriodSize = PA_MIN( optimalPeriodSize, maxPeriodSize );
1516
1517 /* Find the closest power of 2 */
1518 e = ilogb( optimalPeriodSize );
1519 if( optimalPeriodSize & (optimalPeriodSize - 1) )
1520 e += 1;
1521 optimalPeriodSize = (snd_pcm_uframes_t)pow( 2, e );
1522
1523 while( optimalPeriodSize >= periodSize )
1524 {
1525 if( snd_pcm_hw_params_test_period_size( self->capture.pcm, hwParamsCapture, optimalPeriodSize, 0 ) < 0 )
1526 continue;
1527 if( snd_pcm_hw_params_test_period_size( self->playback.pcm, hwParamsPlayback, optimalPeriodSize, 0 ) >= 0 )
1528 break;
1529 optimalPeriodSize /= 2;
1530 }
1531 if( optimalPeriodSize > periodSize )
1532 periodSize = optimalPeriodSize;
1533
1534 if( periodSize <= maxPeriodSize )
1535 {
1536 /* Looks good, the periodSize _should_ be acceptable by both devices */
1537 ENSURE_( snd_pcm_hw_params_set_period_size( self->capture.pcm, hwParamsCapture, periodSize, 0 ),
1538 paUnanticipatedHostError );
1539 ENSURE_( snd_pcm_hw_params_set_period_size( self->playback.pcm, hwParamsPlayback, periodSize, 0 ),
1540 paUnanticipatedHostError );
1541 self->capture.framesPerBuffer = self->playback.framesPerBuffer = periodSize;
1542 framesPerHostBuffer = periodSize;
1543 }
1544 else
1545 {
1546 /* Unable to find a common period size, oh well */
1547 optimalPeriodSize = PA_MAX( desiredLatency / 4, minPeriodSize );
1548 optimalPeriodSize = PA_MIN( optimalPeriodSize, maxPeriodSize );
1549
1550 self->capture.framesPerBuffer = optimalPeriodSize;
1551 dir = 0;
1552 ENSURE_( snd_pcm_hw_params_set_period_size_near( self->capture.pcm, hwParamsCapture, &self->capture.framesPerBuffer, &dir ),
1553 paUnanticipatedHostError );
1554 self->playback.framesPerBuffer = optimalPeriodSize;
1555 dir = 0;
1556 ENSURE_( snd_pcm_hw_params_set_period_size_near( self->playback.pcm, hwParamsPlayback, &self->playback.framesPerBuffer, &dir ),
1557 paUnanticipatedHostError );
1558 framesPerHostBuffer = PA_MAX( self->capture.framesPerBuffer, self->playback.framesPerBuffer );
1559 *hostBufferSizeMode = paUtilBoundedHostBufferSize;
1560 }
1561 }
1562 else
1563 {
1564 /* We choose the simple route and determine a suitable number of frames per buffer for one component of
1565 * the stream, then we hope that this will work for the other component too (it should!).
1566 */
1567
1568 unsigned maxPeriods = 0;
1569 PaAlsaStreamComponent* first = &self->capture, * second = &self->playback;
1570 const PaStreamParameters* firstStreamParams = inputParameters;
1571 snd_pcm_hw_params_t* firstHwParams = hwParamsCapture, * secondHwParams = hwParamsPlayback;
1572
1573 dir = 0;
1574 ENSURE_( snd_pcm_hw_params_get_periods_max( hwParamsPlayback, &maxPeriods, &dir ), paUnanticipatedHostError );
1575 if( maxPeriods < 4 )
1576 {
1577 /* The playback component is trickier to get right, try that first */
1578 first = &self->playback;
1579 second = &self->capture;
1580 firstStreamParams = outputParameters;
1581 firstHwParams = hwParamsPlayback;
1582 secondHwParams = hwParamsCapture;
1583 }
1584
1585 PA_ENSURE( PaAlsaStreamComponent_DetermineFramesPerBuffer( first, firstStreamParams, framesPerUserBuffer,
1586 sampleRate, firstHwParams, &accurate ) );
1587
1588 second->framesPerBuffer = first->framesPerBuffer;
1589 dir = 0;
1590 ENSURE_( snd_pcm_hw_params_set_period_size_near( second->pcm, secondHwParams, &second->framesPerBuffer, &dir ),
1591 paUnanticipatedHostError );
1592 if( self->capture.framesPerBuffer == self->playback.framesPerBuffer )
1593 {
1594 framesPerHostBuffer = self->capture.framesPerBuffer;
1595 }
1596 else
1597 {
1598 framesPerHostBuffer = PA_MAX( self->capture.framesPerBuffer, self->playback.framesPerBuffer );
1599 *hostBufferSizeMode = paUtilBoundedHostBufferSize;
1600 }
1601 }
1602 }
1603 else /* half-duplex is a slightly simpler case */
1604 {
1605 if( self->capture.pcm )
1606 {
1607 PA_ENSURE( PaAlsaStreamComponent_DetermineFramesPerBuffer( &self->capture, inputParameters, framesPerUserBuffer,
1608 sampleRate, hwParamsCapture, &accurate) );
1609 framesPerHostBuffer = self->capture.framesPerBuffer;
1610 }
1611 else
1612 {
1613 assert( self->playback.pcm );
1614 PA_ENSURE( PaAlsaStreamComponent_DetermineFramesPerBuffer( &self->playback, outputParameters, framesPerUserBuffer,
1615 sampleRate, hwParamsPlayback, &accurate ) );
1616 framesPerHostBuffer = self->playback.framesPerBuffer;
1617 }
1618 }
1619
1620 PA_UNLESS( framesPerHostBuffer != 0, paInternalError );
1621 self->maxFramesPerHostBuffer = framesPerHostBuffer;
1622
1623 if( !accurate )
1624 {
1625 /* Don't know the exact size per host buffer */
1626 *hostBufferSizeMode = paUtilBoundedHostBufferSize;
1627 /* Raise upper bound */
1628 ++self->maxFramesPerHostBuffer;
1629 }
1630
1631 error:
1632 return result;
1633 }
1634
1635 /** Set up ALSA stream parameters.
1636 *
1637 */
1638 static PaError PaAlsaStream_Configure( PaAlsaStream *self, const PaStreamParameters *inParams, const PaStreamParameters*
1639 outParams, double sampleRate, unsigned long framesPerUserBuffer, double* inputLatency, double* outputLatency,
1640 PaUtilHostBufferSizeMode* hostBufferSizeMode )
1641 {
1642 PaError result = paNoError;
1643 double realSr = sampleRate;
1644 snd_pcm_hw_params_t* hwParamsCapture, * hwParamsPlayback;
1645
1646 snd_pcm_hw_params_alloca( &hwParamsCapture );
1647 snd_pcm_hw_params_alloca( &hwParamsPlayback );
1648
1649 if( self->capture.pcm )
1650 PA_ENSURE( PaAlsaStreamComponent_InitialConfigure( &self->capture, inParams, self->primeBuffers, hwParamsCapture,
1651 &realSr ) );
1652 if( self->playback.pcm )
1653 PA_ENSURE( PaAlsaStreamComponent_InitialConfigure( &self->playback, outParams, self->primeBuffers, hwParamsPlayback,
1654 &realSr ) );
1655
1656 PA_ENSURE( PaAlsaStream_DetermineFramesPerBuffer( self, realSr, inParams, outParams, framesPerUserBuffer,
1657 hwParamsCapture, hwParamsPlayback, hostBufferSizeMode ) );
1658
1659 if( self->capture.pcm )
1660 {
1661 assert( self->capture.framesPerBuffer != 0 );
1662 PA_ENSURE( PaAlsaStreamComponent_FinishConfigure( &self->capture, hwParamsCapture, inParams, self->primeBuffers, realSr,
1663 inputLatency ) );
1664 PA_DEBUG(( "%s: Capture period size: %lu, latency: %f\n", __FUNCTION__, self->capture.framesPerBuffer, *inputLatency ));
1665 }
1666 if( self->playback.pcm )
1667 {
1668 assert( self->playback.framesPerBuffer != 0 );
1669 PA_ENSURE( PaAlsaStreamComponent_FinishConfigure( &self->playback, hwParamsPlayback, outParams, self->primeBuffers, realSr,
1670 outputLatency ) );
1671 PA_DEBUG(( "%s: Playback period size: %lu, latency: %f\n", __FUNCTION__, self->playback.framesPerBuffer, *outputLatency ));
1672 }
1673
1674 /* Should be exact now */
1675 self->streamRepresentation.streamInfo.sampleRate = realSr;
1676
1677 /* this will cause the two streams to automatically start/stop/prepare in sync.
1678 * We only need to execute these operations on one of the pair.
1679 * A: We don't want to do this on a blocking stream.
1680 */
1681 if( self->callbackMode && self->capture.pcm && self->playback.pcm )
1682 {
1683 int err = snd_pcm_link( self->capture.pcm, self->playback.pcm );
1684 if( err == 0 )
1685 self->pcmsSynced = 1;
1686 else
1687 PA_DEBUG(( "%s: Unable to sync pcms: %s\n", __FUNCTION__, snd_strerror( err ) ));
1688 }
1689
1690 {
1691 unsigned long minFramesPerHostBuffer = PA_MIN( self->capture.pcm ? self->capture.framesPerBuffer : ULONG_MAX,
1692 self->playback.pcm ? self->playback.framesPerBuffer : ULONG_MAX );
1693 self->pollTimeout = CalculatePollTimeout( self, minFramesPerHostBuffer ); /* Period in msecs, rounded up */
1694
1695 /* Time before watchdog unthrottles realtime thread == 1/4 of period time in msecs */
1696 /* self->threading.throttledSleepTime = (unsigned long) (minFramesPerHostBuffer / sampleRate / 4 * 1000); */
1697 }
1698
1699 if( self->callbackMode )
1700 {
1701 /* If the user expects a certain number of frames per callback we will either have to rely on block adaption
1702 * (framesPerHostBuffer is not an integer multiple of framesPerBuffer) or we can simply align the number
1703 * of host buffer frames with what the user specified */
1704 if( self->framesPerUserBuffer != paFramesPerBufferUnspecified )
1705 {
1706 /* self->alignFrames = 1; */
1707
1708 /* Unless the ratio between number of host and user buffer frames is an integer we will have to rely
1709 * on block adaption */
1710 /*
1711 if( framesPerHostBuffer % framesPerBuffer != 0 || (self->capture.pcm && self->playback.pcm &&
1712 self->capture.framesPerBuffer != self->playback.framesPerBuffer) )
1713 self->useBlockAdaption = 1;
1714 else
1715 self->alignFrames = 1;
1716 */
1717 }
1718 }
1719
1720 error:
1721 return result;
1722 }
1723
1724 static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
1725 PaStream** s,
1726 const PaStreamParameters *inputParameters,
1727 const PaStreamParameters *outputParameters,
1728 double sampleRate,
1729 unsigned long framesPerBuffer,
1730 PaStreamFlags streamFlags,
1731 PaStreamCallback* callback,
1732 void *userData )
1733 {
1734 PaError result = paNoError;
1735 PaAlsaHostApiRepresentation *alsaHostApi = (PaAlsaHostApiRepresentation*)hostApi;
1736 PaAlsaStream *stream = NULL;
1737 PaSampleFormat hostInputSampleFormat = 0, hostOutputSampleFormat = 0;
1738 PaSampleFormat inputSampleFormat = 0, outputSampleFormat = 0;
1739 int numInputChannels = 0, numOutputChannels = 0;
1740 PaTime inputLatency, outputLatency;
1741 /* Operate with fixed host buffer size by default, since other modes will invariably lead to block adaption */
1742 /* XXX: Use Bounded by default? Output tends to get stuttery with Fixed ... */
1743 PaUtilHostBufferSizeMode hostBufferSizeMode = paUtilFixedHostBufferSize;
1744
1745 if( (streamFlags & paPlatformSpecificFlags) != 0 )
1746 return paInvalidFlag;
1747
1748 if( inputParameters )
1749 {
1750 PA_ENSURE( ValidateParameters( inputParameters, hostApi, StreamDirection_In ) );
1751
1752 numInputChannels = inputParameters->channelCount;
1753 inputSampleFormat = inputParameters->sampleFormat;
1754 }
1755 if( outputParameters )
1756 {
1757 PA_ENSURE( ValidateParameters( outputParameters, hostApi, StreamDirection_Out ) );
1758
1759 numOutputChannels = outputParameters->channelCount;
1760 outputSampleFormat = outputParameters->sampleFormat;
1761 }
1762
1763 /* XXX: Why do we support this anyway? */
1764 if( framesPerBuffer == paFramesPerBufferUnspecified && getenv( "PA_ALSA_PERIODSIZE" ) != NULL )
1765 {
1766 PA_DEBUG(( "%s: Getting framesPerBuffer from environment\n", __FUNCTION__ ));
1767 framesPerBuffer = atoi( getenv("PA_ALSA_PERIODSIZE") );
1768 }
1769
1770 PA_UNLESS( stream = (PaAlsaStream*)PaUtil_AllocateMemory( sizeof(PaAlsaStream) ), paInsufficientMemory );
1771 PA_ENSURE( PaAlsaStream_Initialize( stream, alsaHostApi, inputParameters, outputParameters, sampleRate,
1772 framesPerBuffer, callback, streamFlags, userData ) );
1773
1774 PA_ENSURE( PaAlsaStream_Configure( stream, inputParameters, outputParameters, sampleRate, framesPerBuffer,
1775 &inputLatency, &outputLatency, &hostBufferSizeMode ) );
1776 hostInputSampleFormat = stream->capture.hostSampleFormat;
1777 hostOutputSampleFormat = stream->playback.hostSampleFormat;
1778
1779 PA_ENSURE( PaUtil_InitializeBufferProcessor( &stream->bufferProcessor,
1780 numInputChannels, inputSampleFormat, hostInputSampleFormat,
1781 numOutputChannels, outputSampleFormat, hostOutputSampleFormat,
1782 sampleRate, streamFlags, framesPerBuffer, stream->maxFramesPerHostBuffer,
1783 hostBufferSizeMode, callback, userData ) );
1784
1785 /* Ok, buffer processor is initialized, now we can deduce it's latency */
1786 if( numInputChannels > 0 )
1787 stream->streamRepresentation.streamInfo.inputLatency = inputLatency + PaUtil_GetBufferProcessorInputLatency(
1788 &stream->bufferProcessor );
1789 if( numOutputChannels > 0 )
1790 stream->streamRepresentation.streamInfo.outputLatency = outputLatency + PaUtil_GetBufferProcessorOutputLatency(
1791 &stream->bufferProcessor );
1792
1793 *s = (PaStream*)stream;
1794
1795 return result;
1796
1797 error:
1798 if( stream )
1799 {
1800 PA_DEBUG(( "%s: Stream in error, terminating\n", __FUNCTION__ ));
1801 PaAlsaStream_Terminate( stream );
1802 }
1803
1804 return result;
1805 }
1806
1807 static PaError CloseStream( PaStream* s )
1808 {
1809 PaError result = paNoError;
1810 PaAlsaStream *stream = (PaAlsaStream*)s;
1811
1812 PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );
1813 PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation );
1814
1815 PaAlsaStream_Terminate( stream );
1816
1817 return result;
1818 }
1819
1820 static void SilenceBuffer( PaAlsaStream *stream )
1821 {
1822 const snd_pcm_channel_area_t *areas;
1823 snd_pcm_uframes_t frames = (snd_pcm_uframes_t)snd_pcm_avail_update( stream->playback.pcm ), offset;
1824
1825 snd_pcm_mmap_begin( stream->playback.pcm, &areas, &offset, &frames );
1826 snd_pcm_areas_silence( areas, offset, stream->playback.numHostChannels, frames, stream->playback.nativeFormat );
1827 snd_pcm_mmap_commit( stream->playback.pcm, offset, frames );
1828 }
1829
1830 /** Start/prepare pcm(s) for streaming.
1831 *
1832 * Depending on wether the stream is in callback or blocking mode, we will respectively start or simply
1833 * prepare the playback pcm. If the buffer has _not_ been primed, we will in callback mode prepare and
1834 * silence the buffer before starting playback. In blocking mode we simply prepare, as the playback will
1835 * be started automatically as the user writes to output.
1836 *
1837 * The capture pcm, however, will simply be prepared and started.
1838 */
1839 static PaError AlsaStart( PaAlsaStream *stream, int priming )
1840 {
1841 PaError result = paNoError;
1842
1843 if( stream->playback.pcm )
1844 {
1845 if( stream->callbackMode )
1846 {
1847 if( !priming )
1848 {
1849 /* Buffer isn't primed, so prepare and silence */
1850 ENSURE_( snd_pcm_prepare( stream->playback.pcm ), paUnanticipatedHostError );
1851 SilenceBuffer( stream );
1852 }
1853 ENSURE_( snd_pcm_start( stream->playback.pcm ), paUnanticipatedHostError );
1854 }
1855 else
1856 ENSURE_( snd_pcm_prepare( stream->playback.pcm ), paUnanticipatedHostError );
1857 }
1858 if( stream->capture.pcm && !stream->pcmsSynced )
1859 {
1860 ENSURE_( snd_pcm_prepare( stream->capture.pcm ), paUnanticipatedHostError );
1861 /* For a blocking stream we want to start capture as well, since nothing will happen otherwise */
1862 ENSURE_( snd_pcm_start( stream->capture.pcm ), paUnanticipatedHostError );
1863 }
1864
1865 end:
1866 return result;
1867 error:
1868 goto end;
1869 }
1870
1871 /** Utility function for determining if pcms are in running state.
1872 *
1873 */
1874 #if 0
1875 static int IsRunning( PaAlsaStream *stream )
1876 {
1877 int result = 0;
1878
1879 PA_ENSURE( PaUnixMutex_Lock( &stream->stateMtx ) );
1880 if( stream->capture.pcm )
1881 {
1882 snd_pcm_state_t capture_state = snd_pcm_state( stream->capture.pcm );
1883
1884 if( capture_state == SND_PCM_STATE_RUNNING || capture_state == SND_PCM_STATE_XRUN
1885 || capture_state == SND_PCM_STATE_DRAINING )
1886 {
1887 result = 1;
1888 goto end;
1889 }
1890 }
1891
1892 if( stream->playback.pcm )
1893 {
1894 snd_pcm_state_t playback_state = snd_pcm_state( stream->playback.pcm );
1895
1896 if( playback_state == SND_PCM_STATE_RUNNING || playback_state == SND_PCM_STATE_XRUN
1897 || playback_state == SND_PCM_STATE_DRAINING )
1898 {
1899 result = 1;
1900 goto end;
1901 }
1902 }
1903
1904 end:
1905 ASSERT_CALL_( PaUnixMutex_Unlock( &stream->stateMtx ), paNoError );
1906 return result;
1907 error:
1908 goto error;
1909 }
1910 #endif
1911
1912 static PaError StartStream( PaStream *s )
1913 {
1914 PaError result = paNoError;
1915 PaAlsaStream* stream = (PaAlsaStream*)s;
1916 int streamStarted = 0; /* So we can know wether we need to take the stream down */
1917
1918 /* Ready the processor */
1919 PaUtil_ResetBufferProcessor( &stream->bufferProcessor );
1920
1921 /* Set now, so we can test for activity further down */
1922 stream->isActive = 1;
1923
1924 if( stream->callbackMode )
1925 {
1926 PA_ENSURE( PaUnixThread_New( &stream->thread, &CallbackThreadFunc, stream, 1. ) );
1927 }
1928 else
1929 {
1930 PA_ENSURE( AlsaStart( stream, 0 ) );
1931 streamStarted = 1;
1932 }
1933
1934 end:
1935 return result;
1936 error:
1937 if( streamStarted )
1938 {
1939 AbortStream( stream );
1940 }
1941 stream->isActive = 0;
1942
1943 goto end;
1944 }
1945
1946 /** Stop PCM handle, either softly or abruptly.
1947 */
1948 static PaError AlsaStop( PaAlsaStream *stream, int abort )
1949 {
1950 PaError result = paNoError;
1951
1952 if( abort )
1953 {
1954 if( stream->playback.pcm )
1955 {
1956 ENSURE_( snd_pcm_drop( stream->playback.pcm ), paUnanticipatedHostError );
1957 }
1958 if( stream->capture.pcm && !stream->pcmsSynced )
1959 {
1960 ENSURE_( snd_pcm_drop( stream->capture.pcm ), paUnanticipatedHostError );
1961 }
1962
1963 PA_DEBUG(( "%s: Dropped frames\n", __FUNCTION__ ));
1964 }
1965 else
1966 {
1967 if( stream->playback.pcm )
1968 {
1969 ENSURE_( snd_pcm_nonblock( stream->playback.pcm, 0 ), paUnanticipatedHostError );
1970 if( snd_pcm_drain( stream->playback.pcm ) < 0 )
1971 {
1972 PA_DEBUG(( "%s: Draining playback handle failed!\n", __FUNCTION__ ));
1973 }
1974 }
1975 if( stream->capture.pcm && !stream->pcmsSynced )
1976 {
1977 /* We don't need to retrieve any remaining frames */
1978 if( snd_pcm_drop( stream->capture.pcm ) < 0 )
1979 {
1980 PA_DEBUG(( "%s: Draining capture handle failed!\n", __FUNCTION__ ));
1981 }
1982 }
1983 }
1984
1985 end:
1986 return result;
1987 error:
1988 goto end;
1989 }
1990
1991 /** Stop or abort stream.
1992 *
1993 * If a stream is in callback mode we will have to inspect wether the background thread has
1994 * finished, or we will have to take it out. In either case we join the thread before
1995 * returning. In blocking mode, we simply tell ALSA to stop abruptly (abort) or finish
1996 * buffers (drain)
1997 *
1998 * Stream will be considered inactive (!PaAlsaStream::isActive) after a call to this function
1999 */
2000 static PaError RealStop( PaAlsaStream *stream, int abort )
2001 {
2002 PaError result = paNoError;
2003
2004 /* First deal with the callback thread, cancelling and/or joining
2005 * it if necessary
2006 */
2007 if( stream->callbackMode )
2008 {
2009 PaError threadRes;
2010 stream->callbackAbort = abort;
2011
2012 if( !abort )
2013 {
2014 PA_DEBUG(( "Stopping callback\n" ));
2015 }
2016 PA_ENSURE( PaUnixThread_Terminate( &stream->thread, !abort, &threadRes ) );
2017 if( threadRes != paNoError )
2018 {
2019 PA_DEBUG(( "Callback thread returned: %d\n", threadRes ));
2020 }
2021 #if 0
2022 if( watchdogRes != paNoError )
2023 PA_DEBUG(( "Watchdog thread returned: %d\n", watchdogRes ));
2024 #endif
2025
2026 stream->callback_finished = 0;
2027 }
2028 else
2029 {
2030 PA_ENSURE( AlsaStop( stream, abort ) );
2031 }
2032
2033 stream->isActive = 0;
2034
2035 end:
2036 return result;
2037
2038 error:
2039 goto end;
2040 }
2041
2042 static PaError StopStream( PaStream *s )
2043 {
2044 return RealStop( (PaAlsaStream *) s, 0 );
2045 }
2046
2047 static PaError AbortStream( PaStream *s )
2048 {
2049 return RealStop( (PaAlsaStream * ) s, 1 );
2050 }
2051
2052 /** The stream is considered stopped before StartStream, or AFTER a call to Abort/StopStream (callback
2053 * returning !paContinue is not considered)
2054 *
2055 */
2056 static PaError IsStreamStopped( PaStream *s )
2057 {
2058 PaAlsaStream *stream = (PaAlsaStream *)s;
2059
2060 /* callback_finished indicates we need to join callback thread (ie. in Abort/StopStream) */
2061 return !IsStreamActive( s ) && !stream->callback_finished;
2062 }
2063
2064 static PaError IsStreamActive( PaStream *s )
2065 {
2066 PaAlsaStream *stream = (PaAlsaStream*)s;
2067 return stream->isActive;
2068 }
2069
2070 static PaTime GetStreamTime( PaStream *s )
2071 {
2072 PaAlsaStream *stream = (PaAlsaStream*)s;
2073
2074 snd_timestamp_t timestamp;
2075 snd_pcm_status_t* status;
2076 snd_pcm_status_alloca( &status );
2077
2078 /* TODO: what if we have both? does it really matter? */
2079
2080 /* TODO: if running in callback mode, this will mean
2081 * libasound routines are being called from multiple threads.
2082 * need to verify that libasound is thread-safe. */
2083
2084 if( stream->capture.pcm )
2085 {
2086 snd_pcm_status( stream->capture.pcm, status );
2087 }
2088 else if( stream->playback.pcm )
2089 {
2090 snd_pcm_status( stream->playback.pcm, status );
2091 }
2092
2093 snd_pcm_status_get_tstamp( status, &timestamp );
2094 return timestamp.tv_sec + (PaTime)timestamp.tv_usec / 1e6;
2095 }
2096
2097 static double GetStreamCpuLoad( PaStream* s )
2098 {
2099 PaAlsaStream *stream = (PaAlsaStream*)s;
2100
2101 return PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer );
2102 }
2103
2104 static int SetApproximateSampleRate( snd_pcm_t *pcm, snd_pcm_hw_params_t *hwParams, double sampleRate )
2105 {
2106 unsigned long approx = (unsigned long) sampleRate;
2107 int dir = 0;
2108 double fraction = sampleRate - approx;
2109
2110 assert( pcm && hwParams );
2111
2112 if( fraction > 0.0 )
2113 {
2114 if( fraction > 0.5 )
2115 {
2116 ++approx;
2117 dir = -1;
2118 }
2119 else
2120 dir = 1;
2121 }
2122
2123 return snd_pcm_hw_params_set_rate( pcm, hwParams, approx, dir );
2124 }
2125
2126 /* Return exact sample rate in param sampleRate */
2127 static int GetExactSampleRate( snd_pcm_hw_params_t *hwParams, double *sampleRate )
2128 {
2129 unsigned int num, den;
2130 int err;
2131
2132 assert( hwParams );
2133
2134 err = snd_pcm_hw_params_get_rate_numden( hwParams, &num, &den );
2135 *sampleRate = (double) num / den;
2136
2137 return err;
2138 }
2139
2140 /* Utility functions for blocking/callback interfaces */
2141
2142 /* Atomic restart of stream (we don't want the intermediate state visible) */
2143 static PaError AlsaRestart( PaAlsaStream *stream )
2144 {
2145 PaError result = paNoError;
2146
2147 PA_ENSURE( PaUnixMutex_Lock( &stream->stateMtx ) );
2148 PA_ENSURE( AlsaStop( stream, 0 ) );
2149 PA_ENSURE( AlsaStart( stream, 0 ) );
2150
2151 PA_DEBUG(( "%s: Restarted audio\n", __FUNCTION__ ));
2152
2153 error:
2154 PA_ENSURE( PaUnixMutex_Unlock( &stream->stateMtx ) );
2155
2156 return result;
2157 }
2158
2159 /** Recover from xrun state.
2160 *
2161 */
2162 static PaError PaAlsaStream_HandleXrun( PaAlsaStream *self )
2163 {
2164 PaError result = paNoError;
2165 snd_pcm_status_t *st;
2166 PaTime now = PaUtil_GetTime();
2167 snd_timestamp_t t;
2168
2169 snd_pcm_status_alloca( &st );
2170
2171 if( self->playback.pcm )
2172 {
2173 snd_pcm_status( self->playback.pcm, st );
2174 if( snd_pcm_status_get_state( st ) == SND_PCM_STATE_XRUN )
2175 {
2176 snd_pcm_status_get_trigger_tstamp( st, &t );
2177 self->underrun = now * 1000 - ((PaTime) t.tv_sec * 1000 + (PaTime) t.tv_usec / 1000);
2178 }
2179 }
2180 if( self->capture.pcm )
2181 {
2182 snd_pcm_status( self->capture.pcm, st );
2183 if( snd_pcm_status_get_state( st ) == SND_PCM_STATE_XRUN )
2184 {
2185 snd_pcm_status_get_trigger_tstamp( st, &t );
2186 self->overrun = now * 1000 - ((PaTime) t.tv_sec * 1000 + (PaTime) t.tv_usec / 1000);
2187 }
2188 }
2189
2190 PA_ENSURE( AlsaRestart( self ) );
2191
2192 end:
2193 return result;
2194 error:
2195 goto end;
2196 }
2197
2198 /** Decide if we should continue polling for specified direction, eventually adjust the poll timeout.
2199 *
2200 */
2201 static PaError ContinuePoll( const PaAlsaStream *stream, StreamDirection streamDir, int *pollTimeout, int *continuePoll )
2202 {
2203 PaError result = paNoError;
2204 snd_pcm_sframes_t delay, margin;
2205 int err;
2206 const PaAlsaStreamComponent *component = NULL, *otherComponent = NULL;
2207
2208 *continuePoll = 1;
2209
2210 if( StreamDirection_In == streamDir )
2211 {
2212 component = &stream->capture;
2213 otherComponent = &stream->playback;
2214 }
2215 else
2216 {
2217 component = &stream->playback;
2218 otherComponent = &stream->capture;
2219 }
2220
2221 /* ALSA docs say that negative delay should indicate xrun, but in my experience snd_pcm_delay returns -EPIPE */
2222 if( (err = snd_pcm_delay( otherComponent->pcm, &delay )) < 0 )
2223 {
2224 if( err == -EPIPE )
2225 {
2226 /* Xrun */
2227 *continuePoll = 0;
2228 goto error;
2229 }
2230
2231 ENSURE_( err, paUnanticipatedHostError );
2232 }
2233
2234 if( StreamDirection_Out == streamDir )
2235 {
2236 /* Number of eligible frames before capture overrun */
2237 delay = otherComponent->bufferSize - delay;
2238 }
2239 margin = delay - otherComponent->framesPerBuffer / 2;
2240
2241 if( margin < 0 )
2242 {
2243 PA_DEBUG(( "%s: Stopping poll for %s\n", __FUNCTION__, StreamDirection_In == streamDir ? "capture" : "playback" ));
2244 *continuePoll = 0;
2245 }
2246 else if( margin < otherComponent->framesPerBuffer )
2247 {
2248 *pollTimeout = CalculatePollTimeout( stream, margin );
2249 PA_DEBUG(( "%s: Trying to poll again for %s frames, pollTimeout: %d\n",
2250 __FUNCTION__, StreamDirection_In == streamDir ? "capture" : "playback", *pollTimeout ));
2251 }
2252
2253 error:
2254 return result;
2255 }
2256
2257 /* Callback interface */
2258
2259 static void OnExit( void *data )
2260 {
2261 PaAlsaStream *stream = (PaAlsaStream *) data;
2262
2263 assert( data );
2264
2265 PaUtil_ResetCpuLoadMeasurer( &stream->cpuLoadMeasurer );
2266
2267 stream->callback_finished = 1; /* Let the outside world know stream was stopped in callback */
2268 PA_DEBUG(( "%s: Stopping ALSA handles\n", __FUNCTION__ ));
2269 AlsaStop( stream, stream->callbackAbort );
2270
2271 PA_DEBUG(( "%s: Stoppage\n", __FUNCTION__ ));
2272
2273 /* Eventually notify user all buffers have played */
2274 if( stream->streamRepresentation.streamFinishedCallback )
2275 {
2276 stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData );
2277 }
2278 stream->isActive = 0;
2279 }
2280
2281 static void CalculateTimeInfo( PaAlsaStream *stream, PaStreamCallbackTimeInfo *timeInfo )
2282 {
2283 snd_pcm_status_t *capture_status, *playback_status;
2284 snd_timestamp_t capture_timestamp, playback_timestamp;
2285 PaTime capture_time = 0., playback_time = 0.;
2286
2287 snd_pcm_status_alloca( &capture_status );
2288 snd_pcm_status_alloca( &playback_status );
2289
2290 if( stream->capture.pcm )
2291 {
2292 snd_pcm_sframes_t capture_delay;
2293
2294 snd_pcm_status( stream->capture.pcm, capture_status );
2295 snd_pcm_status_get_tstamp( capture_status, &capture_timestamp );
2296
2297 capture_time = capture_timestamp.tv_sec +
2298 ((PaTime)capture_timestamp.tv_usec / 1000000.0);
2299 timeInfo->currentTime = capture_time;
2300
2301 capture_delay = snd_pcm_status_get_delay( capture_status );
2302 timeInfo->inputBufferAdcTime = timeInfo->currentTime -
2303 (PaTime)capture_delay / stream->streamRepresentation.streamInfo.sampleRate;
2304 }
2305 if( stream->playback.pcm )
2306 {
2307 snd_pcm_sframes_t playback_delay;
2308
2309 snd_pcm_status( stream->playback.pcm, playback_status );
2310 snd_pcm_status_get_tstamp( playback_status, &playback_timestamp );
2311
2312 playback_time = playback_timestamp.tv_sec +
2313 ((PaTime)playback_timestamp.tv_usec / 1000000.0);
2314
2315 if( stream->capture.pcm ) /* Full duplex */
2316 {
2317 /* Hmm, we have both a playback and a capture timestamp.
2318 * Hopefully they are the same... */
2319 if( fabs( capture_time - playback_time ) > 0.01 )
2320 PA_DEBUG(("Capture time and playback time differ by %f\n", fabs(capture_time-playback_time)));
2321 }
2322 else
2323 timeInfo->currentTime = playback_time;
2324
2325 playback_delay = snd_pcm_status_get_delay( playback_status );
2326 timeInfo->outputBufferDacTime = timeInfo->currentTime +
2327 (PaTime)playback_delay / stream->streamRepresentation.streamInfo.sampleRate;
2328 }
2329 }
2330
2331 /** Called after buffer processing is finished.
2332 *
2333 * A number of mmapped frames is committed, it is possible that an xrun has occurred in the meantime.
2334 *
2335 * @param numFrames The number of frames that has been processed
2336 * @param xrun Return whether an xrun has occurred
2337 */
2338 static PaError PaAlsaStreamComponent_EndProcessing( PaAlsaStreamComponent *self, unsigned long numFrames, int *xrun )
2339 {
2340 PaError result = paNoError;
2341 int res;
2342
2343 /* @concern FullDuplex It is possible that only one direction is marked ready after polling, and processed
2344 * afterwards
2345 */
2346 if( !self->ready )
2347 goto end;
2348
2349 res = snd_pcm_mmap_commit( self->pcm, self->offset, numFrames );
2350 if( res == -EPIPE || res == -ESTRPIPE )
2351 {
2352 *xrun = 1;
2353 }
2354 else
2355 {
2356 ENSURE_( res, paUnanticipatedHostError );
2357 }
2358
2359 end:
2360 error:
2361 return result;
2362 }
2363
2364 /* Extract buffer from channel area */
2365 static unsigned char *ExtractAddress( const snd_pcm_channel_area_t *area, snd_pcm_uframes_t offset )
2366 {
2367 return (unsigned char *) area->addr + (area->first + offset * area->step) / 8;
2368 }
2369
2370 /** Do necessary adaption between user and host channels.
2371 *
2372 @concern ChannelAdaption Adapting between user and host channels can involve silencing unused channels and
2373 duplicating mono information if host outputs come in pairs.
2374 */
2375 static PaError PaAlsaStreamComponent_DoChannelAdaption( PaAlsaStreamComponent *self, PaUtilBufferProcessor *bp, int numFrames )
2376 {
2377 PaError result = paNoError;
2378 unsigned char *p;
2379 int i;
2380 int unusedChans = self->numHostChannels - self->numUserChannels;
2381 unsigned char *src, *dst;
2382 int convertMono = (self->numHostChannels % 2) == 0 && (self->numUserChannels % 2) != 0;
2383
2384 assert( StreamDirection_Out == self->streamDir );
2385
2386 if( self->hostInterleaved )
2387 {
2388 int swidth = snd_pcm_format_size( self->nativeFormat, 1 );
2389 unsigned char *buffer = ExtractAddress( self->channelAreas, self->offset );
2390
2391 /* Start after the last user channel */
2392 p = buffer + self->numUserChannels * swidth;
2393
2394 if( convertMono )
2395 {
2396 /* Convert the last user channel into stereo pair */
2397 src = buffer + (self->numUserChannels - 1) * swidth;
2398 for( i = 0; i < numFrames; ++i )
2399 {
2400 dst = src + swidth;
2401 memcpy( dst, src, swidth );
2402 src += self->numHostChannels * swidth;
2403 }
2404
2405 /* Don't touch the channel we just wrote to */
2406 p += swidth;
2407 --unusedChans;
2408 }
2409
2410 if( unusedChans > 0 )
2411 {
2412 /* Silence unused output channels */
2413 for( i = 0; i < numFrames; ++i )
2414 {
2415 memset( p, 0, swidth * unusedChans );
2416 p += self->numHostChannels * swidth;
2417 }
2418 }
2419 }
2420 else
2421 {
2422 /* We extract the last user channel */
2423 if( convertMono )
2424 {
2425 ENSURE_( snd_pcm_area_copy( self->channelAreas + self->numUserChannels, self->offset, self->channelAreas +
2426 (self->numUserChannels - 1), self->offset, numFrames, self->nativeFormat ), paUnanticipatedHostError );
2427 --unusedChans;
2428 }
2429 if( unusedChans > 0 )
2430 {
2431 snd_pcm_areas_silence( self->channelAreas + (self->numHostChannels - unusedChans), self->offset, unusedChans, numFrames,
2432 self->nativeFormat );
2433 }
2434 }
2435
2436 error:
2437 return result;
2438 }
2439
2440 static PaError PaAlsaStream_EndProcessing( PaAlsaStream *self, unsigned long numFrames, int *xrunOccurred )
2441 {
2442 PaError result = paNoError;
2443 int xrun = 0;
2444
2445 if( self->capture.pcm )
2446 {
2447 PA_ENSURE( PaAlsaStreamComponent_EndProcessing( &self->capture, numFrames, &xrun ) );
2448 }
2449 if( self->playback.pcm )
2450 {
2451 if( self->playback.numHostChannels > self->playback.numUserChannels )
2452 {
2453 PA_ENSURE( PaAlsaStreamComponent_DoChannelAdaption( &self->playback, &self->bufferProcessor, numFrames ) );
2454 }
2455 PA_ENSURE( PaAlsaStreamComponent_EndProcessing( &self->playback, numFrames, &xrun ) );
2456 }
2457
2458 error:
2459 *xrunOccurred = xrun;
2460 return result;
2461 }
2462
2463 /** Update the number of available frames.
2464 *
2465 */
2466 static PaError PaAlsaStreamComponent_GetAvailableFrames( PaAlsaStreamComponent *self, unsigned long *numFrames, int *xrunOccurred )
2467 {
2468 PaError result = paNoError;
2469 snd_pcm_sframes_t framesAvail = snd_pcm_avail_update( self->pcm );
2470 *xrunOccurred = 0;
2471
2472 if( -EPIPE == framesAvail )
2473 {
2474 *xrunOccurred = 1;
2475 framesAvail = 0;
2476 }
2477 else
2478 {
2479 ENSURE_( framesAvail, paUnanticipatedHostError );
2480 }
2481
2482 *numFrames = framesAvail;
2483
2484 error:
2485 return result;
2486 }
2487
2488 /** Fill in pollfd objects.
2489 */
2490 static PaError PaAlsaStreamComponent_BeginPolling( PaAlsaStreamComponent* self, struct pollfd* pfds )
2491 {
2492 PaError result = paNoError;
2493 int ret = snd_pcm_poll_descriptors( self->pcm, pfds, self->nfds );
2494 (void)ret; /* Prevent unused variable warning if asserts are turned off */
2495 assert( ret == self->nfds );
2496
2497 self->ready = 0;
2498
2499 return result;
2500 }
2501
2502 /** Examine results from poll().
2503 *
2504 * @param pfds pollfds to inspect
2505 * @param shouldPoll Should we continue to poll
2506 * @param xrun Has an xrun occurred
2507 */
2508 static PaError PaAlsaStreamComponent_EndPolling( PaAlsaStreamComponent* self, struct pollfd* pfds, int* shouldPoll, int* xrun )
2509 {
2510 PaError result = paNoError;
2511 unsigned short revents;
2512
2513 ENSURE_( snd_pcm_poll_descriptors_revents( self->pcm, pfds, self->nfds, &revents ), paUnanticipatedHostError );
2514 if( revents != 0 )
2515 {
2516 if( revents & POLLERR )
2517 {
2518 *xrun = 1;
2519 }
2520 else
2521 self->ready = 1;
2522
2523 *shouldPoll = 0;
2524 }
2525
2526 error:
2527 return result;
2528 }
2529
2530 /** Return the number of available frames for this stream.
2531 *
2532 * @concern FullDuplex The minimum available for the two directions is calculated, it might be desirable to ignore
2533 * one direction however (not marked ready from poll), so this is controlled by queryCapture and queryPlayback.
2534 *
2535 * @param queryCapture Check available for capture
2536 * @param queryPlayback Check available for playback
2537 * @param available The returned number of frames
2538 * @param xrunOccurred Return whether an xrun has occurred
2539 */
2540 static PaError PaAlsaStream_GetAvailableFrames( PaAlsaStream *self, int queryCapture, int queryPlayback, unsigned long
2541 *available, int *xrunOccurred )
2542 {
2543 PaError result = paNoError;
2544 unsigned long captureFrames, playbackFrames;
2545 *xrunOccurred = 0;
2546
2547 assert( queryCapture || queryPlayback );
2548
2549 if( queryCapture )
2550 {
2551 assert( self->capture.pcm );
2552 PA_ENSURE( PaAlsaStreamComponent_GetAvailableFrames( &self->capture, &captureFrames, xrunOccurred ) );
2553 if( *xrunOccurred )
2554 {
2555 goto end;
2556 }
2557 }
2558 if( queryPlayback )
2559 {
2560 assert( self->playback.pcm );
2561 PA_ENSURE( PaAlsaStreamComponent_GetAvailableFrames( &self->playback, &playbackFrames, xrunOccurred ) );
2562 if( *xrunOccurred )
2563 {
2564 goto end;
2565 }
2566 }
2567
2568 if( queryCapture && queryPlayback )
2569 {
2570 *available = PA_MIN( captureFrames, playbackFrames );
2571 /*PA_DEBUG(("capture: %lu, playback: %lu, combined: %lu\n", captureFrames, playbackFrames, *available));*/
2572 }
2573 else if( queryCapture )
2574 {
2575 *available = captureFrames;
2576 }
2577 else
2578 {
2579 *available = playbackFrames;
2580 }
2581
2582 end:
2583 error:
2584 return result;
2585 }
2586
2587 /** Wait for and report available buffer space from ALSA.
2588 *
2589 * Unless ALSA reports a minimum of frames available for I/O, we poll the ALSA filedescriptors for more.
2590 * Both of these operations can uncover xrun conditions.
2591 *
2592 * @concern Xruns Both polling and querying available frames can report an xrun condition.
2593 *
2594 * @param framesAvail Return the number of available frames
2595 * @param xrunOccurred Return whether an xrun has occurred
2596 */
2597 static PaError PaAlsaStream_WaitForFrames( PaAlsaStream *self, unsigned long *framesAvail, int *xrunOccurred )
2598 {
2599 PaError result = paNoError;
2600 int pollPlayback = self->playback.pcm != NULL, pollCapture = self->capture.pcm != NULL;
2601 int pollTimeout = self->pollTimeout;
2602 int xrun = 0;
2603
2604 assert( self );
2605 assert( framesAvail );
2606
2607 if( !self->callbackMode )
2608 {
2609 /* In blocking mode we will only wait if necessary */
2610 PA_ENSURE( PaAlsaStream_GetAvailableFrames( self, self->capture.pcm != NULL, self->playback.pcm != NULL,
2611 framesAvail, &xrun ) );
2612 if( xrun )
2613 {
2614 goto end;
2615 }
2616
2617 if( *framesAvail > 0 )
2618 {
2619 /* Mark pcms ready from poll */
2620 if( self->capture.pcm )
2621 self->capture.ready = 1;
2622 if( self->playback.pcm )
2623 self->playback.ready = 1;
2624
2625 goto end;
2626 }
2627 }
2628
2629 while( pollPlayback || pollCapture )
2630 {
2631 int totalFds = 0;
2632 struct pollfd *capturePfds = NULL, *playbackPfds = NULL;
2633
2634 pthread_testcancel();
2635
2636 if( pollCapture )
2637 {
2638 capturePfds = self->pfds;
2639 PA_ENSURE( PaAlsaStreamComponent_BeginPolling( &self->capture, capturePfds ) );
2640 totalFds += self->capture.nfds;
2641 }
2642 if( pollPlayback )
2643 {
2644 playbackPfds = self->pfds + (self->capture.pcm ? self->capture.nfds : 0);
2645 PA_ENSURE( PaAlsaStreamComponent_BeginPolling( &self->playback, playbackPfds ) );
2646 totalFds += self->playback.nfds;
2647 }
2648
2649 if( poll( self->pfds, totalFds, pollTimeout ) < 0 )
2650 {
2651 /* XXX: Depend on preprocessor condition? */
2652 if( errno == EINTR )
2653 {
2654 /* gdb */
2655 continue;
2656 }
2657
2658 /* TODO: Add macro for checking system calls */
2659 PA_ENSURE( paInternalError );
2660 }
2661
2662 /* check the return status of our pfds */
2663 if( pollCapture )
2664 {
2665 PA_ENSURE( PaAlsaStreamComponent_EndPolling( &self->capture, capturePfds, &pollCapture, &xrun ) );
2666 }
2667 if( pollPlayback )
2668 {
2669 PA_ENSURE( PaAlsaStreamComponent_EndPolling( &self->playback, playbackPfds, &pollPlayback, &xrun ) );
2670 }
2671 if( xrun )
2672 {
2673 break;
2674 }
2675
2676 /* @concern FullDuplex If only one of two pcms is ready we may want to compromise between the two.
2677 * If there is less than half a period's worth of samples left of frames in the other pcm's buffer we will
2678 * stop polling.
2679 */
2680 if( self->capture.pcm && self->playback.pcm )
2681 {
2682 if( pollCapture && !pollPlayback )
2683 {
2684 PA_ENSURE( ContinuePoll( self, StreamDirection_In, &pollTimeout, &pollCapture ) );
2685 }
2686 else if( pollPlayback && !pollCapture )
2687 {
2688 PA_ENSURE( ContinuePoll( self, StreamDirection_Out, &pollTimeout, &pollPlayback ) );
2689 }
2690 }
2691 }
2692
2693 if( !xrun )
2694 {
2695 /* Get the number of available frames for the pcms that are marked ready.
2696 * @concern FullDuplex If only one direction is marked ready (from poll), the number of frames available for
2697 * the other direction is returned. Output is normally preferred over capture however, so capture frames may be
2698 * discarded to avoid overrun unless paNeverDropInput is specified.
2699 */
2700 int captureReady = self->capture.pcm ? self->capture.ready : 0,
2701 playbackReady = self->playback.pcm ? self->playback.ready : 0;
2702 PA_ENSURE( PaAlsaStream_GetAvailableFrames( self, captureReady, playbackReady, framesAvail, &xrun ) );
2703
2704 if( self->capture.pcm && self->playback.pcm )
2705 {
2706 if( !self->playback.ready && !self->neverDropInput )
2707 {
2708 /* Drop input, a period's worth */
2709 assert( self->capture.ready );
2710 PaAlsaStreamComponent_EndProcessing( &self->capture, PA_MIN( self->capture.framesPerBuffer,
2711 *framesAvail ), &xrun );
2712 *framesAvail = 0;
2713 self->capture.ready = 0;
2714 }
2715 }
2716 else if( self->capture.pcm )
2717 assert( self->capture.ready );
2718 else
2719 assert( self->playback.ready );
2720 }
2721
2722 end:
2723 error:
2724 if( xrun )
2725 {
2726 /* Recover from the xrun state */
2727 PA_ENSURE( PaAlsaStream_HandleXrun( self ) );
2728 *framesAvail = 0;
2729 }
2730 else
2731 {
2732 if( 0 != *framesAvail )
2733 {
2734 /* If we're reporting frames eligible for processing, one of the handles better be ready */
2735 PA_UNLESS( self->capture.ready || self->playback.ready, paInternalError );
2736 }
2737 }
2738 *xrunOccurred = xrun;
2739
2740 return result;
2741 }
2742
2743 /** Register per-channel ALSA buffer information with buffer processor.
2744 *
2745 * Mmapped buffer space is acquired from ALSA, and registered with the buffer processor. Differences between the
2746 * number of host and user channels is taken into account.
2747 *
2748 * @param numFrames On entrance the number of requested frames, on exit the number of contiguously accessible frames.
2749 */
2750 static PaError PaAlsaStreamComponent_RegisterChannels( PaAlsaStreamComponent* self, PaUtilBufferProcessor* bp,
2751 unsigned long* numFrames, int* xrun )
2752 {
2753 PaError result = paNoError;
2754 const snd_pcm_channel_area_t *areas, *area;
2755 void (*setChannel)(PaUtilBufferProcessor *, unsigned int, void *, unsigned int) =
2756 StreamDirection_In == self->streamDir ? PaUtil_SetInputChannel : PaUtil_SetOutputChannel;
2757 unsigned char *buffer, *p;
2758 int i;
2759 unsigned long framesAvail;
2760
2761 /* This _must_ be called before mmap_begin */
2762 PA_ENSURE( PaAlsaStreamComponent_GetAvailableFrames( self, &framesAvail, xrun ) );
2763 if( *xrun )
2764 {
2765 *numFrames = 0;
2766 goto end;
2767 }
2768
2769 ENSURE_( snd_pcm_mmap_begin( self->pcm, &areas, &self->offset, numFrames ), paUnanticipatedHostError );
2770
2771 if( self->hostInterleaved )
2772 {
2773 int swidth = snd_pcm_format_size( self->nativeFormat, 1 );
2774
2775 p = buffer = ExtractAddress( areas, self->offset );
2776 for( i = 0; i < self->numUserChannels; ++i )
2777 {
2778 /* We're setting the channels up to userChannels, but the stride will be hostChannels samples */
2779 setChannel( bp, i, p, self->numHostChannels );
2780 p += swidth;
2781 }
2782 }
2783 else
2784 {
2785 for( i = 0; i < self->numUserChannels; ++i )
2786 {
2787 area = areas + i;
2788 buffer = ExtractAddress( area, self->offset );
2789 setChannel( bp, i, buffer, 1 );
2790 }
2791 }
2792
2793 /* @concern ChannelAdaption Buffer address is recorded so we can do some channel adaption later */
2794 self->channelAreas = (snd_pcm_channel_area_t *)areas;
2795
2796 end:
2797 error:
2798 return result;
2799 }
2800
2801 /** Initiate buffer processing.
2802 *
2803 * ALSA buffers are registered with the PA buffer processor and the buffer size (in frames) set.
2804 *
2805 * @concern FullDuplex If both directions are being processed, the minimum amount of frames for the two directions is
2806 * calculated.
2807 *
2808 * @param numFrames On entrance the number of available frames, on exit the number of received frames
2809 * @param xrunOccurred Return whether an xrun has occurred
2810 */
2811 static PaError PaAlsaStream_SetUpBuffers( PaAlsaStream* self, unsigned long* numFrames, int* xrunOccurred )
2812 {
2813 PaError result = paNoError;
2814 unsigned long captureFrames = ULONG_MAX, playbackFrames = ULONG_MAX, commonFrames = 0;
2815 int xrun = 0;
2816
2817 if( *xrunOccurred )
2818 {
2819 *numFrames = 0;
2820 return result;
2821 }
2822 /* If we got here at least one of the pcm's should be marked ready */
2823 PA_UNLESS( self->capture.ready || self->playback.ready, paInternalError );
2824
2825 /* Extract per-channel ALSA buffer pointers and register them with the buffer processor.
2826 * It is possible that a direction is not marked ready however, because it is out of sync with the other.
2827 */
2828 if( self->capture.pcm && self->capture.ready )
2829 {
2830 captureFrames = *numFrames;
2831 PA_ENSURE( PaAlsaStreamComponent_RegisterChannels( &self->capture, &self->bufferProcessor, &captureFrames,
2832 &xrun ) );
2833 }
2834 if( self->playback.pcm && self->playback.ready )
2835 {
2836 playbackFrames = *numFrames;
2837 PA_ENSURE( PaAlsaStreamComponent_RegisterChannels( &self->playback, &self->bufferProcessor, &playbackFrames,
2838 &xrun ) );
2839 }
2840 if( xrun )
2841 {
2842 /* Nothing more to do */
2843 assert( 0 == commonFrames );
2844 goto end;
2845 }
2846
2847 commonFrames = PA_MIN( captureFrames, playbackFrames );
2848 /* assert( commonFrames <= *numFrames ); */
2849 if( commonFrames > *numFrames )
2850 {
2851 /* Hmmm ... how come there are more frames available than we requested!? Blah. */
2852 PA_DEBUG(( "%s: Common available frames are reported to be more than number requested: %lu, %lu, callbackMode: %d\n", __FUNCTION__,
2853 commonFrames, *numFrames, self->callbackMode ));
2854 if( self->capture.pcm )
2855 {
2856 PA_DEBUG(( "%s: captureFrames: %lu, capture.ready: %d\n", __FUNCTION__, captureFrames, self->capture.ready ));
2857 }
2858 if( self->playback.pcm )
2859 {
2860 PA_DEBUG(( "%s: playbackFrames: %lu, playback.ready: %d\n", __FUNCTION__, playbackFrames, self->playback.ready ));
2861 }
2862
2863 commonFrames = 0;
2864 goto end;
2865 }
2866
2867 /* Inform PortAudio of the number of frames we got.
2868 * @concern FullDuplex We might be experiencing underflow in either end; if its an input underflow, we go on
2869 * with output. If its output underflow however, depending on the paNeverDropInput flag, we may want to simply
2870 * discard the excess input or call the callback with paOutputOverflow flagged.
2871 */
2872 if( self->capture.pcm )
2873 {
2874 if( self->capture.ready )
2875 {
2876 PaUtil_SetInputFrameCount( &self->bufferProcessor, commonFrames );
2877 }
2878 else
2879 {
2880 /* We have input underflow */
2881 PaUtil_SetNoInput( &self->bufferProcessor );
2882 }
2883 }
2884 if( self->playback.pcm )
2885 {
2886 if( self->playback.ready )
2887 {
2888 PaUtil_SetOutputFrameCount( &self->bufferProcessor, commonFrames );
2889 }
2890 else
2891 {
2892 /* We have output underflow, but keeping input data (paNeverDropInput) */
2893 assert( self->neverDropInput );
2894 assert( self->capture.pcm != NULL );
2895 PA_DEBUG(( "%s: Setting output buffers to NULL\n", __FUNCTION__ ));
2896 PaUtil_SetNoOutput( &self->bufferProcessor );
2897 }
2898 }
2899
2900 end:
2901 *numFrames = commonFrames;
2902 error:
2903 if( xrun )
2904 {
2905 PA_ENSURE( PaAlsaStream_HandleXrun( self ) );
2906 *numFrames = 0;
2907 }
2908 *xrunOccurred = xrun;
2909
2910 return result;
2911 }
2912
2913 /** Callback thread's function.
2914 *
2915 * Roughly, the workflow can be described in the following way: The number of available frames that can be processed
2916 * directly is obtained from ALSA, we then request as much directly accessible memory as possible within this amount
2917 * from ALSA. The buffer memory is registered with the PA buffer processor and processing is carried out with
2918 * PaUtil_EndBufferProcessing. Finally, the number of processed frames is reported to ALSA. The processing can
2919 * happen in several iterations untill we have consumed the known number of available frames (or an xrun is detected).
2920 */
2921 static void *CallbackThreadFunc( void *userData )
2922 {
2923 PaError result = paNoError;
2924 PaAlsaStream *stream = (PaAlsaStream*) userData;
2925 PaStreamCallbackTimeInfo timeInfo = {0, 0, 0};
2926 snd_pcm_sframes_t startThreshold = 0;
2927 int callbackResult = paContinue;
2928 PaStreamCallbackFlags cbFlags = 0; /* We might want to keep state across iterations */
2929 int streamStarted = 0;
2930
2931 assert( stream );
2932
2933 /* Execute OnExit when exiting */
2934 pthread_cleanup_push( &OnExit, stream );
2935
2936 /* Not implemented */
2937 assert( !stream->primeBuffers );
2938
2939 /* @concern StreamStart If the output is being primed the output pcm needs to be prepared, otherwise the
2940 * stream is started immediately. The latter involves signaling the waiting main thread.
2941 */
2942 if( stream->primeBuffers )
2943 {
2944 snd_pcm_sframes_t avail;
2945
2946 if( stream->playback.pcm )
2947 ENSURE_( snd_pcm_prepare( stream->playback.pcm ), paUnanticipatedHostError );
2948 if( stream->capture.pcm && !stream->pcmsSynced )
2949 ENSURE_( snd_pcm_prepare( stream->capture.pcm ), paUnanticipatedHostError );
2950
2951 /* We can't be certain that the whole ring buffer is available for priming, but there should be
2952 * at least one period */
2953 avail = snd_pcm_avail_update( stream->playback.pcm );
2954 startThreshold = avail - (avail % stream->playback.framesPerBuffer);
2955 assert( startThreshold >= stream->playback.framesPerBuffer );
2956 }
2957 else
2958 {
2959 PA_ENSURE( PaUnixThread_PrepareNotify( &stream->thread ) );
2960 /* Buffer will be zeroed */
2961 PA_ENSURE( AlsaStart( stream, 0 ) );
2962 PA_ENSURE( PaUnixThread_NotifyParent( &stream->thread ) );
2963
2964 streamStarted = 1;
2965 }
2966
2967 while( 1 )
2968 {
2969 unsigned long framesAvail, framesGot;
2970 int xrun = 0;
2971
2972 pthread_testcancel();
2973
2974 /* @concern StreamStop if the main thread has requested a stop and the stream has not been effectively
2975 * stopped we signal this condition by modifying callbackResult (we'll want to flush buffered output).
2976 */
2977 if( PaUnixThread_StopRequested( &stream->thread ) && paContinue == callbackResult )
2978 {
2979 PA_DEBUG(( "Setting callbackResult to paComplete\n" ));
2980 callbackResult = paComplete;
2981 }
2982
2983 if( paContinue != callbackResult )
2984 {
2985 stream->callbackAbort = (paAbort == callbackResult);
2986 if( stream->callbackAbort ||
2987 /** @concern BlockAdaption: Go on if adaption buffers are empty */
2988 PaUtil_IsBufferProcessorOutputEmpty( &stream->bufferProcessor ) )
2989 {
2990 goto end;
2991 }
2992
2993 PA_DEBUG(( "%s: Flushing buffer processor\n", __FUNCTION__ ));
2994 /* There is still buffered output that needs to be processed */
2995 }
2996
2997 /* Wait for data to become available, this comes down to polling the ALSA file descriptors untill we have
2998 * a number of available frames.
2999 */
3000 PA_ENSURE( PaAlsaStream_WaitForFrames( stream, &framesAvail, &xrun ) );
3001 if( xrun )
3002 {
3003 assert( 0 == framesAvail );
3004 continue;
3005
3006 /* XXX: Report xruns to the user? A situation is conceivable where the callback is never invoked due
3007 * to constant xruns, it might be desirable to notify the user of this.
3008 */
3009 }
3010
3011 /* Consume buffer space. Once we have a number of frames available for consumption we must retrieve the
3012 * mmapped buffers from ALSA, this is contiguously accessible memory however, so we may receive smaller
3013 * portions at a time than is available as a whole. Therefore we should be prepared to process several
3014 * chunks successively. The buffers are passed to the PA buffer processor.
3015 */
3016 while( framesAvail > 0 )
3017 {
3018 xrun = 0;
3019
3020 pthread_testcancel();
3021
3022 /** @concern Xruns Under/overflows are to be reported to the callback */
3023 if( stream->underrun > 0.0 )
3024 {
3025 cbFlags |= paOutputUnderflow;
3026 stream->underrun = 0.0;
3027 }
3028 if( stream->overrun > 0.0 )
3029 {
3030 cbFlags |= paInputOverflow;
3031 stream->overrun = 0.0;
3032 }
3033 if( stream->capture.pcm && stream->playback.pcm )
3034 {
3035 /** @concern FullDuplex It's possible that only one direction is being processed to avoid an
3036 * under- or overflow, this should be reported correspondingly */
3037 if( !stream->capture.ready )
3038 {
3039 cbFlags |= paInputUnderflow;
3040 PA_DEBUG(( "%s: Input underflow\n", __FUNCTION__ ));
3041 }
3042 else if( !stream->playback.ready )
3043 {
3044 cbFlags |= paOutputOverflow;
3045 PA_DEBUG(( "%s: Output overflow\n", __FUNCTION__ ));
3046 }
3047 }
3048
3049 #if 0
3050 CallbackUpdate( &stream->threading );
3051 #endif
3052 CalculateTimeInfo( stream, &timeInfo );
3053 PaUtil_BeginBufferProcessing( &stream->bufferProcessor, &timeInfo, cbFlags );
3054 cbFlags = 0;
3055
3056 /* CPU load measurement should include processing activivity external to the stream callback */
3057 PaUtil_BeginCpuLoadMeasurement( &stream->cpuLoadMeasurer );
3058
3059 framesGot = framesAvail;
3060 if( paUtilFixedHostBufferSize == stream->bufferProcessor.hostBufferSizeMode )
3061 {
3062 /* We've committed to a fixed host buffer size, stick to that */
3063 framesGot = framesGot >= stream->maxFramesPerHostBuffer ? stream->maxFramesPerHostBuffer : 0;
3064 }
3065 else
3066 {
3067 /* We've committed to an upper bound on the size of host buffers */
3068 assert( paUtilBoundedHostBufferSize == stream->bufferProcessor.hostBufferSizeMode );
3069 framesGot = PA_MIN( framesGot, stream->maxFramesPerHostBuffer );
3070 }
3071 PA_ENSURE( PaAlsaStream_SetUpBuffers( stream, &framesGot, &xrun ) );
3072 /* Check the host buffer size against the buffer processor configuration */
3073 framesAvail -= framesGot;
3074
3075 if( framesGot > 0 )
3076 {
3077 assert( !xrun );
3078 PaUtil_EndBufferProcessing( &stream->bufferProcessor, &callbackResult );
3079 PA_ENSURE( PaAlsaStream_EndProcessing( stream, framesGot, &xrun ) );
3080 }
3081 PaUtil_EndCpuLoadMeasurement( &stream->cpuLoadMeasurer, framesGot );
3082
3083 if( 0 == framesGot )
3084 {
3085 /* Go back to polling for more frames */
3086 break;
3087
3088 }
3089
3090 if( paContinue != callbackResult )
3091 break;
3092 }
3093 }
3094
3095 /* Match pthread_cleanup_push */
3096 pthread_cleanup_pop( 1 );
3097
3098 end:
3099 PA_DEBUG(( "%s: Thread %d exiting\n ", __FUNCTION__, pthread_self() ));
3100 PaUnixThreading_EXIT( result );
3101 error:
3102 goto end;
3103 }
3104
3105 /* Blocking interface */
3106
3107 static PaError ReadStream( PaStream* s, void *buffer, unsigned long frames )
3108 {
3109 PaError result = paNoError;
3110 PaAlsaStream *stream = (PaAlsaStream*)s;
3111 unsigned long framesGot, framesAvail;
3112 void *userBuffer;
3113 snd_pcm_t *save = stream->playback.pcm;
3114
3115 assert( stream );
3116
3117 PA_UNLESS( stream->capture.pcm, paCanNotReadFromAnOutputOnlyStream );
3118
3119 /* Disregard playback */
3120 stream->playback.pcm = NULL;
3121
3122 if( stream->overrun > 0. )
3123 {
3124 result = paInputOverflowed;
3125 stream->overrun = 0.0;
3126 }
3127
3128 if( stream->capture.userInterleaved )
3129 {
3130 userBuffer = buffer;
3131 }
3132 else
3133 {
3134 /* Copy channels into local array */
3135 userBuffer = stream->capture.userBuffers;
3136 memcpy( userBuffer, buffer, sizeof (void *) * stream->capture.numUserChannels );
3137 }
3138
3139 /* Start stream if in prepared state */
3140 if( snd_pcm_state( stream->capture.pcm ) == SND_PCM_STATE_PREPARED )
3141 {
3142 ENSURE_( snd_pcm_start( stream->capture.pcm ), paUnanticipatedHostError );
3143 }
3144
3145 while( frames > 0 )
3146 {
3147 int xrun = 0;
3148 PA_ENSURE( PaAlsaStream_WaitForFrames( stream, &framesAvail, &xrun ) );
3149 framesGot = PA_MIN( framesAvail, frames );
3150
3151 PA_ENSURE( PaAlsaStream_SetUpBuffers( stream, &framesGot, &xrun ) );
3152 if( framesGot > 0 )
3153 {
3154 framesGot = PaUtil_CopyInput( &stream->bufferProcessor, &userBuffer, framesGot );
3155 PA_ENSURE( PaAlsaStream_EndProcessing( stream, framesGot, &xrun ) );
3156 frames -= framesGot;
3157 }
3158 }
3159
3160 end:
3161 stream->playback.pcm = save;
3162 return result;
3163 error:
3164 goto end;
3165 }
3166
3167 static PaError WriteStream( PaStream* s, const void *buffer, unsigned long frames )
3168 {
3169 PaError result = paNoError;
3170 signed long err;
3171 PaAlsaStream *stream = (PaAlsaStream*)s;
3172 snd_pcm_uframes_t framesGot, framesAvail;
3173 const void *userBuffer;
3174 snd_pcm_t *save = stream->capture.pcm;
3175
3176 assert( stream );
3177
3178 PA_UNLESS( stream->playback.pcm, paCanNotWriteToAnInputOnlyStream );
3179
3180 /* Disregard capture */
3181 stream->capture.pcm = NULL;
3182
3183 if( stream->underrun > 0. )
3184 {
3185 result = paOutputUnderflowed;
3186 stream->underrun = 0.0;
3187 }
3188
3189 if( stream->playback.userInterleaved )
3190 userBuffer = buffer;
3191 else /* Copy channels into local array */
3192 {
3193 userBuffer = stream->playback.userBuffers;
3194 memcpy( (void *)userBuffer, buffer, sizeof (void *) * stream->playback.numUserChannels );
3195 }
3196
3197 while( frames > 0 )
3198 {
3199 int xrun = 0;
3200 snd_pcm_uframes_t hwAvail;
3201
3202 PA_ENSURE( PaAlsaStream_WaitForFrames( stream, &framesAvail, &xrun ) );
3203 framesGot = PA_MIN( framesAvail, frames );
3204
3205 PA_ENSURE( PaAlsaStream_SetUpBuffers( stream, &framesGot, &xrun ) );
3206 if( framesGot > 0 )
3207 {
3208 framesGot = PaUtil_CopyOutput( &stream->bufferProcessor, &userBuffer, framesGot );
3209 PA_ENSURE( PaAlsaStream_EndProcessing( stream, framesGot, &xrun ) );
3210 frames -= framesGot;
3211 }
3212
3213 /* Start stream after one period of samples worth */
3214
3215 /* Frames residing in buffer */
3216 PA_ENSURE( err = GetStreamWriteAvailable( stream ) );
3217 framesAvail = err;
3218 hwAvail = stream->playback.bufferSize - framesAvail;
3219
3220 if( snd_pcm_state( stream->playback.pcm ) == SND_PCM_STATE_PREPARED &&
3221 hwAvail >= stream->playback.framesPerBuffer )
3222 {
3223 ENSURE_( snd_pcm_start( stream->playback.pcm ), paUnanticipatedHostError );
3224 }
3225 }
3226
3227 end:
3228 stream->capture.pcm = save;
3229 return result;
3230 error:
3231 goto end;
3232 }
3233
3234 /* Return frames available for reading. In the event of an overflow, the capture pcm will be restarted */
3235 static signed long GetStreamReadAvailable( PaStream* s )
3236 {
3237 PaError result = paNoError;
3238 PaAlsaStream *stream = (PaAlsaStream*)s;
3239 unsigned long avail;
3240 int xrun;
3241
3242 PA_ENSURE( PaAlsaStreamComponent_GetAvailableFrames( &stream->capture, &avail, &xrun ) );
3243 if( xrun )
3244 {
3245 PA_ENSURE( PaAlsaStream_HandleXrun( stream ) );
3246 PA_ENSURE( PaAlsaStreamComponent_GetAvailableFrames( &stream->capture, &avail, &xrun ) );
3247 if( xrun )
3248 PA_ENSURE( paInputOverflowed );
3249 }
3250
3251 return (signed long)avail;
3252
3253 error:
3254 return result;
3255 }
3256
3257 static signed long GetStreamWriteAvailable( PaStream* s )
3258 {
3259 PaError result = paNoError;
3260 PaAlsaStream *stream = (PaAlsaStream*)s;
3261 unsigned long avail;
3262 int xrun;
3263
3264 PA_ENSURE( PaAlsaStreamComponent_GetAvailableFrames( &stream->playback, &avail, &xrun ) );
3265 if( xrun )
3266 {
3267 snd_pcm_sframes_t savail;
3268
3269 PA_ENSURE( PaAlsaStream_HandleXrun( stream ) );
3270 savail = snd_pcm_avail_update( stream->playback.pcm );
3271
3272 /* savail should not contain -EPIPE now, since PaAlsaStream_HandleXrun will only prepare the pcm */
3273 ENSURE_( savail, paUnanticipatedHostError );
3274
3275 avail = (unsigned long) savail;
3276 }
3277
3278 return (signed long)avail;
3279
3280 error:
3281 return result;
3282 }
3283
3284 /* Extensions */
3285
3286 /* Initialize host api specific structure */
3287 void PaAlsa_InitializeStreamInfo( PaAlsaStreamInfo *info )
3288 {
3289 info->size = sizeof (PaAlsaStreamInfo);
3290 info->hostApiType = paALSA;
3291 info->version = 1;
3292 info->deviceString = NULL;
3293 }
3294
3295 void PaAlsa_EnableRealtimeScheduling( PaStream *s, int enable )
3296 {
3297 #if 0
3298 PaAlsaStream *stream = (PaAlsaStream *) s;
3299 stream->threading.rtSched = enable;
3300 #endif
3301 }
3302
3303 void PaAlsa_EnableWatchdog( PaStream *s, int enable )
3304 {
3305 #if 0
3306 PaAlsaStream *stream = (PaAlsaStream *) s;
3307 stream->threading.useWatchdog = enable;
3308 #endif
3309 }