Debian Codegraph @

3rdparty/iaxclient/lib/portaudio/src/hostapi/jack/pa_jack.c

raw symbols SCIP
1 /*
2 * $Id: pa_jack.c,v 1.1 2006/06/10 21:30:56 dmazzoni Exp $
3 * PortAudio Portable Real-Time Audio Library
4 * Latest Version at: http://www.portaudio.com
5 * JACK Implementation by Joshua Haberman
6 *
7 * Copyright (c) 2004 Stefan Westerfeld <[email protected]>
8 * Copyright (c) 2004 Arve Knudsen <[email protected]>
9 * Copyright (c) 2002 Joshua Haberman <[email protected]>
10 *
11 * Based on the Open Source API proposed by Ross Bencina
12 * Copyright (c) 1999-2002 Ross Bencina, Phil Burk
13 *
14 * Permission is hereby granted, free of charge, to any person obtaining
15 * a copy of this software and associated documentation files
16 * (the "Software"), to deal in the Software without restriction,
17 * including without limitation the rights to use, copy, modify, merge,
18 * publish, distribute, sublicense, and/or sell copies of the Software,
19 * and to permit persons to whom the Software is furnished to do so,
20 * subject to the following conditions:
21 *
22 * The above copyright notice and this permission notice shall be
23 * included in all copies or substantial portions of the Software.
24 *
25 * Any person wishing to distribute modifications to the Software is
26 * requested to send the modifications to the original developer so that
27 * they can be incorporated into the canonical version.
28 *
29 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
30 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
31 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
32 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
33 * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
34 * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
35 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
36 */
37
38 #include <string.h>
39 #include <regex.h>
40 #include <stdlib.h>
41 #include <stdio.h>
42 #include <assert.h>
43 #include <sys/types.h>
44 #include <unistd.h>
45 #include <errno.h> /* EBUSY */
46 #include <signal.h> /* sig_atomic_t */
47 #include <math.h>
48 #include <semaphore.h>
49
50 #include <jack/types.h>
51 #include <jack/jack.h>
52
53 #include "pa_util.h"
54 #include "pa_hostapi.h"
55 #include "pa_stream.h"
56 #include "pa_process.h"
57 #include "pa_allocation.h"
58 #include "pa_cpuload.h"
59 #include "../pablio/ringbuffer.c"
60
61 static int aErr_;
62 static PaError paErr_; /* For use with ENSURE_PA */
63 static pthread_t mainThread_;
64 static char *jackErr_ = NULL;
65
66 #define STRINGIZE_HELPER(expr) #expr
67 #define STRINGIZE(expr) STRINGIZE_HELPER(expr)
68
69 /* Check PaError */
70 #define ENSURE_PA(expr) \
71 do { \
72 if( (paErr_ = (expr)) < paNoError ) \
73 { \
74 if( (paErr_) == paUnanticipatedHostError && pthread_self() == mainThread_ ) \
75 { \
76 assert( jackErr_ ); \
77 PaUtil_SetLastHostErrorInfo( paJACK, -1, jackErr_ ); \
78 } \
79 PaUtil_DebugPrint(( "Expression '" #expr "' failed in '" __FILE__ "', line: " STRINGIZE( __LINE__ ) "\n" )); \
80 result = paErr_; \
81 goto error; \
82 } \
83 } while( 0 )
84
85 #define UNLESS(expr, code) \
86 do { \
87 if( (expr) == 0 ) \
88 { \
89 if( (code) == paUnanticipatedHostError && pthread_self() == mainThread_ ) \
90 { \
91 assert( jackErr_ ); \
92 PaUtil_SetLastHostErrorInfo( paJACK, -1, jackErr_ ); \
93 } \
94 PaUtil_DebugPrint(( "Expression '" #expr "' failed in '" __FILE__ "', line: " STRINGIZE( __LINE__ ) "\n" )); \
95 result = (code); \
96 goto error; \
97 } \
98 } while( 0 )
99
100 #define ASSERT_CALL(expr, success) \
101 aErr_ = (expr); \
102 assert( aErr_ == success );
103
104 /*
105 * Functions that directly map to the PortAudio stream interface
106 */
107
108 static void Terminate( struct PaUtilHostApiRepresentation *hostApi );
109 static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
110 const PaStreamParameters *inputParameters,
111 const PaStreamParameters *outputParameters,
112 double sampleRate );
113 static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
114 PaStream** s,
115 const PaStreamParameters *inputParameters,
116 const PaStreamParameters *outputParameters,
117 double sampleRate,
118 unsigned long framesPerBuffer,
119 PaStreamFlags streamFlags,
120 PaStreamCallback *streamCallback,
121 void *userData );
122 static PaError CloseStream( PaStream* stream );
123 static PaError StartStream( PaStream *stream );
124 static PaError StopStream( PaStream *stream );
125 static PaError AbortStream( PaStream *stream );
126 static PaError IsStreamStopped( PaStream *s );
127 static PaError IsStreamActive( PaStream *stream );
128 /*static PaTime GetStreamInputLatency( PaStream *stream );*/
129 /*static PaTime GetStreamOutputLatency( PaStream *stream );*/
130 static PaTime GetStreamTime( PaStream *stream );
131 static double GetStreamCpuLoad( PaStream* stream );
132
133
134 /*
135 * Data specific to this API
136 */
137
138 struct PaJackStream;
139
140 typedef struct
141 {
142 PaUtilHostApiRepresentation commonHostApiRep;
143 PaUtilStreamInterface callbackStreamInterface;
144 PaUtilStreamInterface blockingStreamInterface;
145
146 PaUtilAllocationGroup *deviceInfoMemory;
147
148 jack_client_t *jack_client;
149 int jack_buffer_size;
150 PaHostApiIndex hostApiIndex;
151
152 pthread_mutex_t mtx;
153 pthread_cond_t cond;
154 unsigned long inputBase, outputBase;
155
156 /* For dealing with the process thread */
157 volatile int xrun; /* Received xrun notification from JACK? */
158 struct PaJackStream * volatile toAdd, * volatile toRemove;
159 struct PaJackStream *processQueue;
160 volatile sig_atomic_t jackIsDown;
161 }
162 PaJackHostApiRepresentation;
163
164 /* PaJackStream - a stream data structure specifically for this implementation */
165
166 typedef struct PaJackStream
167 {
168 PaUtilStreamRepresentation streamRepresentation;
169 PaUtilBufferProcessor bufferProcessor;
170 PaUtilCpuLoadMeasurer cpuLoadMeasurer;
171 PaJackHostApiRepresentation *hostApi;
172
173 /* our input and output ports */
174 jack_port_t **local_input_ports;
175 jack_port_t **local_output_ports;
176
177 /* the input and output ports of the client we are connecting to */
178 jack_port_t **remote_input_ports;
179 jack_port_t **remote_output_ports;
180
181 int num_incoming_connections;
182 int num_outgoing_connections;
183
184 jack_client_t *jack_client;
185
186 /* The stream is running if it's still producing samples.
187 * The stream is active if samples it produced are still being heard.
188 */
189 volatile sig_atomic_t is_running;
190 volatile sig_atomic_t is_active;
191 /* Used to signal processing thread that stream should start or stop, respectively */
192 volatile sig_atomic_t doStart, doStop, doAbort;
193
194 jack_nframes_t t0;
195
196 PaUtilAllocationGroup *stream_memory;
197
198 /* These are useful in the process callback */
199
200 int callbackResult;
201 int isSilenced;
202 int xrun;
203
204 /* These are useful for the blocking API */
205
206 int isBlockingStream;
207 RingBuffer inFIFO;
208 RingBuffer outFIFO;
209 volatile sig_atomic_t data_available;
210 sem_t data_semaphore;
211 int bytesPerFrame;
212 int samplesPerFrame;
213
214 struct PaJackStream *next;
215 }
216 PaJackStream;
217
218 #define TRUE 1
219 #define FALSE 0
220
221 /*
222 * Functions specific to this API
223 */
224
225 static int JackCallback( jack_nframes_t frames, void *userData );
226
227
228 /*
229 *
230 * Implementation
231 *
232 */
233
234 /* ---- blocking emulation layer ---- */
235
236 /* Allocate buffer. */
237 static PaError BlockingInitFIFO( RingBuffer *rbuf, long numFrames, long bytesPerFrame )
238 {
239 long numBytes = numFrames * bytesPerFrame;
240 char *buffer = (char *) malloc( numBytes );
241 if( buffer == NULL ) return paInsufficientMemory;
242 memset( buffer, 0, numBytes );
243 return (PaError) RingBuffer_Init( rbuf, numBytes, buffer );
244 }
245
246 /* Free buffer. */
247 static PaError BlockingTermFIFO( RingBuffer *rbuf )
248 {
249 if( rbuf->buffer ) free( rbuf->buffer );
250 rbuf->buffer = NULL;
251 return paNoError;
252 }
253
254 static int
255 BlockingCallback( const void *inputBuffer,
256 void *outputBuffer,
257 unsigned long framesPerBuffer,
258 const PaStreamCallbackTimeInfo* timeInfo,
259 PaStreamCallbackFlags statusFlags,
260 void *userData )
261 {
262 struct PaJackStream *stream = (PaJackStream *)userData;
263 long numBytes = stream->bytesPerFrame * framesPerBuffer;
264
265 /* This may get called with NULL inputBuffer during initial setup. */
266 if( inputBuffer != NULL )
267 {
268 RingBuffer_Write( &stream->inFIFO, inputBuffer, numBytes );
269 }
270 if( outputBuffer != NULL )
271 {
272 int numRead = RingBuffer_Read( &stream->outFIFO, outputBuffer, numBytes );
273 /* Zero out remainder of buffer if we run out of data. */
274 memset( (char *)outputBuffer + numRead, 0, numBytes - numRead );
275 }
276
277 if( !stream->data_available )
278 {
279 stream->data_available = 1;
280 sem_post( &stream->data_semaphore );
281 }
282 return paContinue;
283 }
284
285 static PaError
286 BlockingBegin( PaJackStream *stream, int minimum_buffer_size )
287 {
288 long doRead = 0;
289 long doWrite = 0;
290 PaError result = paNoError;
291 long numFrames;
292
293 doRead = stream->local_input_ports != NULL;
294 doWrite = stream->local_output_ports != NULL;
295 /* <FIXME> */
296 stream->samplesPerFrame = 2;
297 stream->bytesPerFrame = sizeof(float) * stream->samplesPerFrame;
298 /* </FIXME> */
299 numFrames = 32;
300 while (numFrames < minimum_buffer_size)
301 numFrames *= 2;
302
303 if( doRead )
304 {
305 ENSURE_PA( BlockingInitFIFO( &stream->inFIFO, numFrames, stream->bytesPerFrame ) );
306 }
307 if( doWrite )
308 {
309 long numBytes;
310
311 ENSURE_PA( BlockingInitFIFO( &stream->outFIFO, numFrames, stream->bytesPerFrame ) );
312
313 /* Make Write FIFO appear full initially. */
314 numBytes = RingBuffer_GetWriteAvailable( &stream->outFIFO );
315 RingBuffer_AdvanceWriteIndex( &stream->outFIFO, numBytes );
316 }
317
318 stream->data_available = 0;
319 sem_init( &stream->data_semaphore, 0, 0 );
320
321 error:
322 return result;
323 }
324
325 static void
326 BlockingEnd( PaJackStream *stream )
327 {
328 BlockingTermFIFO( &stream->inFIFO );
329 BlockingTermFIFO( &stream->outFIFO );
330
331 sem_destroy( &stream->data_semaphore );
332 }
333
334 static PaError BlockingReadStream( PaStream* s, void *data, unsigned long numFrames )
335 {
336 PaError result = paNoError;
337 PaJackStream *stream = (PaJackStream *)s;
338
339 long bytesRead;
340 char *p = (char *) data;
341 long numBytes = stream->bytesPerFrame * numFrames;
342 while( numBytes > 0 )
343 {
344 bytesRead = RingBuffer_Read( &stream->inFIFO, p, numBytes );
345 numBytes -= bytesRead;
346 p += bytesRead;
347 if( numBytes > 0 )
348 {
349 /* see write for an explanation */
350 if( stream->data_available )
351 stream->data_available = 0;
352 else
353 sem_wait( &stream->data_semaphore );
354 }
355 }
356
357 return result;
358 }
359
360 static PaError BlockingWriteStream( PaStream* s, const void *data, unsigned long numFrames )
361 {
362 PaError result = paNoError;
363 PaJackStream *stream = (PaJackStream *)s;
364 long bytesWritten;
365 char *p = (char *) data;
366 long numBytes = stream->bytesPerFrame * numFrames;
367 while( numBytes > 0 )
368 {
369 bytesWritten = RingBuffer_Write( &stream->outFIFO, p, numBytes );
370 numBytes -= bytesWritten;
371 p += bytesWritten;
372 if( numBytes > 0 )
373 {
374 /* we use the following algorithm:
375 * (1) write data
376 * (2) if some data didn't fit into the ringbuffer, set data_available to 0
377 * to indicate to the audio that if space becomes available, we want to know
378 * (3) retry to write data (because it might be that between (1) and (2)
379 * new space in the buffer became available)
380 * (4) if this failed, we are sure that the buffer is really empty and
381 * we will definitely receive a notification when it becomes available
382 * thus we can safely sleep
383 *
384 * if the algorithm bailed out in step (3) before, it leaks a count of 1
385 * on the semaphore; however, it doesn't matter, because if we block in (4),
386 * we also do it in a loop
387 */
388 if( stream->data_available )
389 stream->data_available = 0;
390 else
391 sem_wait( &stream->data_semaphore );
392 }
393 }
394
395 return result;
396 }
397
398 static signed long
399 BlockingGetStreamReadAvailable( PaStream* s )
400 {
401 PaJackStream *stream = (PaJackStream *)s;
402
403 int bytesFull = RingBuffer_GetReadAvailable( &stream->inFIFO );
404 return bytesFull / stream->bytesPerFrame;
405 }
406
407 static signed long
408 BlockingGetStreamWriteAvailable( PaStream* s )
409 {
410 PaJackStream *stream = (PaJackStream *)s;
411
412 int bytesEmpty = RingBuffer_GetWriteAvailable( &stream->outFIFO );
413 return bytesEmpty / stream->bytesPerFrame;
414 }
415
416 static PaError
417 BlockingWaitEmpty( PaStream *s )
418 {
419 PaJackStream *stream = (PaJackStream *)s;
420
421 while( RingBuffer_GetReadAvailable( &stream->outFIFO ) > 0 )
422 {
423 stream->data_available = 0;
424 sem_wait( &stream->data_semaphore );
425 }
426 return 0;
427 }
428
429 /* ---- jack driver ---- */
430
431 /* BuildDeviceList():
432 *
433 * The process of determining a list of PortAudio "devices" from
434 * JACK's client/port system is fairly involved, so it is separated
435 * into its own routine.
436 */
437
438 static PaError BuildDeviceList( PaJackHostApiRepresentation *jackApi )
439 {
440 /* Utility macros for the repetitive process of allocating memory */
441
442 /* ... MALLOC: allocate memory as part of the device list
443 * allocation group */
444 #define MALLOC(size) \
445 (PaUtil_GroupAllocateMemory( jackApi->deviceInfoMemory, (size) ))
446
447 /* JACK has no concept of a device. To JACK, there are clients
448 * which have an arbitrary number of ports. To make this
449 * intelligible to PortAudio clients, we will group each JACK client
450 * into a device, and make each port of that client a channel */
451
452 PaError result = paNoError;
453 PaUtilHostApiRepresentation *commonApi = &jackApi->commonHostApiRep;
454
455 const char **jack_ports = NULL;
456 char **client_names = NULL;
457 char *regex_pattern = alloca( jack_client_name_size() + 3 );
458 int port_index, client_index, i;
459 double globalSampleRate;
460 regex_t port_regex;
461 unsigned long numClients = 0, numPorts = 0;
462 char *tmp_client_name = alloca( jack_client_name_size() );
463
464 commonApi->info.defaultInputDevice = paNoDevice;
465 commonApi->info.defaultOutputDevice = paNoDevice;
466 commonApi->info.deviceCount = 0;
467
468 /* Parse the list of ports, using a regex to grab the client names */
469 ASSERT_CALL( regcomp( &port_regex, "^[^:]*", REG_EXTENDED ), 0 );
470
471 /* since we are rebuilding the list of devices, free all memory
472 * associated with the previous list */
473 PaUtil_FreeAllAllocations( jackApi->deviceInfoMemory );
474
475 /* We can only retrieve the list of clients indirectly, by first
476 * asking for a list of all ports, then parsing the port names
477 * according to the client_name:port_name convention (which is
478 * enforced by jackd)
479 * A: If jack_get_ports returns NULL, there's nothing for us to do */
480 UNLESS( (jack_ports = jack_get_ports( jackApi->jack_client, "", "", 0 )) && jack_ports[0], paNoError );
481 /* Find number of ports */
482 while( jack_ports[numPorts] )
483 ++numPorts;
484 /* At least there will be one port per client :) */
485 UNLESS( client_names = alloca( numPorts * sizeof (char *) ), paInsufficientMemory );
486
487 /* Build a list of clients from the list of ports */
488 for( numClients = 0, port_index = 0; jack_ports[port_index] != NULL; port_index++ )
489 {
490 int client_seen = FALSE;
491 regmatch_t match_info;
492 const char *port = jack_ports[port_index];
493
494 /* extract the client name from the port name, using a regex
495 * that parses the clientname:portname syntax */
496 UNLESS( !regexec( &port_regex, port, 1, &match_info, 0 ), paInternalError );
497 assert(match_info.rm_eo - match_info.rm_so < jack_client_name_size());
498 memcpy( tmp_client_name, port + match_info.rm_so,
499 match_info.rm_eo - match_info.rm_so );
500 tmp_client_name[match_info.rm_eo - match_info.rm_so] = '\0';
501
502 /* do we know about this port's client yet? */
503 for( i = 0; i < numClients; i++ )
504 {
505 if( strcmp( tmp_client_name, client_names[i] ) == 0 )
506 client_seen = TRUE;
507 }
508
509 if (client_seen)
510 continue; /* A: Nothing to see here, move along */
511
512 UNLESS( client_names[numClients] = (char*)MALLOC(strlen(tmp_client_name) + 1), paInsufficientMemory );
513
514 /* The alsa_pcm client should go in spot 0. If this
515 * is the alsa_pcm client AND we are NOT about to put
516 * it in spot 0 put it in spot 0 and move whatever
517 * was already in spot 0 to the end. */
518 if( strcmp( "alsa_pcm", tmp_client_name ) == 0 && numClients > 0 )
519 {
520 /* alsa_pcm goes in spot 0 */
521 strcpy( client_names[ numClients ], client_names[0] );
522 strcpy( client_names[0], tmp_client_name );
523 }
524 else
525 {
526 /* put the new client at the end of the client list */
527 strcpy( client_names[ numClients ], tmp_client_name );
528 }
529 ++numClients;
530 }
531
532 /* Now we have a list of clients, which will become the list of
533 * PortAudio devices. */
534
535 /* there is one global sample rate all clients must conform to */
536
537 globalSampleRate = jack_get_sample_rate( jackApi->jack_client );
538 UNLESS( commonApi->deviceInfos = (PaDeviceInfo**)MALLOC( sizeof(PaDeviceInfo*) *
539 numClients ), paInsufficientMemory );
540
541 assert( commonApi->info.deviceCount == 0 );
542
543 /* Create a PaDeviceInfo structure for every client */
544 for( client_index = 0; client_index < numClients; client_index++ )
545 {
546 PaDeviceInfo *curDevInfo;
547 const char **clientPorts = NULL;
548
549 UNLESS( curDevInfo = (PaDeviceInfo*)MALLOC( sizeof(PaDeviceInfo) ), paInsufficientMemory );
550 UNLESS( curDevInfo->name = (char*)MALLOC( strlen(client_names[client_index]) + 1 ), paInsufficientMemory );
551 strcpy( (char *)curDevInfo->name, client_names[client_index] );
552
553 curDevInfo->structVersion = 2;
554 curDevInfo->hostApi = jackApi->hostApiIndex;
555
556 /* JACK is very inflexible: there is one sample rate the whole
557 * system must run at, and all clients must speak IEEE float. */
558 curDevInfo->defaultSampleRate = globalSampleRate;
559
560 /* To determine how many input and output channels are available,
561 * we re-query jackd with more specific parameters. */
562
563 sprintf( regex_pattern, "%s:.*", client_names[client_index] );
564
565 /* ... what are your output ports (that we could input from)? */
566 clientPorts = jack_get_ports( jackApi->jack_client, regex_pattern,
567 NULL, JackPortIsOutput);
568 curDevInfo->maxInputChannels = 0;
569 curDevInfo->defaultLowInputLatency = 0.;
570 curDevInfo->defaultHighInputLatency = 0.;
571 if( clientPorts )
572 {
573 jack_port_t *p = jack_port_by_name( jackApi->jack_client, clientPorts[0] );
574 curDevInfo->defaultLowInputLatency = curDevInfo->defaultHighInputLatency =
575 jack_port_get_latency( p ) / globalSampleRate;
576
577 for( i = 0; clientPorts[i] != NULL; i++)
578 {
579 /* The number of ports returned is the number of output channels.
580 * We don't care what they are, we just care how many */
581 curDevInfo->maxInputChannels++;
582 }
583 free(clientPorts);
584 }
585
586 /* ... what are your input ports (that we could output to)? */
587 clientPorts = jack_get_ports( jackApi->jack_client, regex_pattern,
588 NULL, JackPortIsInput);
589 curDevInfo->maxOutputChannels = 0;
590 curDevInfo->defaultLowOutputLatency = 0.;
591 curDevInfo->defaultHighOutputLatency = 0.;
592 if( clientPorts )
593 {
594 jack_port_t *p = jack_port_by_name( jackApi->jack_client, clientPorts[0] );
595 curDevInfo->defaultLowOutputLatency = curDevInfo->defaultHighOutputLatency =
596 jack_port_get_latency( p ) / globalSampleRate;
597
598 for( i = 0; clientPorts[i] != NULL; i++)
599 {
600 /* The number of ports returned is the number of input channels.
601 * We don't care what they are, we just care how many */
602 curDevInfo->maxOutputChannels++;
603 }
604 free(clientPorts);
605 }
606
607 /* Add this client to the list of devices */
608 commonApi->deviceInfos[client_index] = curDevInfo;
609 ++commonApi->info.deviceCount;
610 if( commonApi->info.defaultInputDevice == paNoDevice && curDevInfo->maxInputChannels > 0 )
611 commonApi->info.defaultInputDevice = client_index;
612 if( commonApi->info.defaultOutputDevice == paNoDevice && curDevInfo->maxOutputChannels > 0 )
613 commonApi->info.defaultOutputDevice = client_index;
614 }
615
616 error:
617 regfree( &port_regex );
618 free( jack_ports );
619 return result;
620 }
621 #undef MALLOC
622
623 static void UpdateSampleRate( PaJackStream *stream, double sampleRate )
624 {
625 /* XXX: Maybe not the cleanest way of going about this? */
626 stream->cpuLoadMeasurer.samplingPeriod = stream->bufferProcessor.samplePeriod = 1. / sampleRate;
627 stream->streamRepresentation.streamInfo.sampleRate = sampleRate;
628 }
629
630 static void JackErrorCallback( const char *msg )
631 {
632 if( pthread_self() == mainThread_ )
633 {
634 assert( msg );
635 free( jackErr_ );
636 jackErr_ = malloc( strlen( msg ) );
637 sprintf( jackErr_, msg );
638 }
639 }
640
641 static void JackOnShutdown( void *arg )
642 {
643 PaJackHostApiRepresentation *jackApi = (PaJackHostApiRepresentation *)arg;
644 PaJackStream *stream = jackApi->processQueue;
645
646 PA_DEBUG(( "%s: JACK server is shutting down\n", __FUNCTION__ ));
647 for( ; stream; stream = stream->next )
648 {
649 stream->is_active = 0;
650 }
651
652 /* Make sure that the main thread doesn't get stuck waiting on the condition */
653 ASSERT_CALL( pthread_mutex_lock( &jackApi->mtx ), 0 );
654 jackApi->jackIsDown = 1;
655 ASSERT_CALL( pthread_cond_signal( &jackApi->cond ), 0 );
656 ASSERT_CALL( pthread_mutex_unlock( &jackApi->mtx ), 0 );
657
658 }
659
660 static int JackSrCb( jack_nframes_t nframes, void *arg )
661 {
662 PaJackHostApiRepresentation *jackApi = (PaJackHostApiRepresentation *)arg;
663 double sampleRate = (double)nframes;
664 PaJackStream *stream = jackApi->processQueue;
665
666 /* Update all streams in process queue */
667 PA_DEBUG(( "%s: Acting on change in JACK samplerate: %f\n", __FUNCTION__, sampleRate ));
668 for( ; stream; stream = stream->next )
669 {
670 if( stream->streamRepresentation.streamInfo.sampleRate != sampleRate )
671 {
672 PA_DEBUG(( "%s: Updating samplerate\n", __FUNCTION__ ));
673 UpdateSampleRate( stream, sampleRate );
674 }
675 }
676
677 return 0;
678 }
679
680 static int JackXRunCb(void *arg) {
681 PaJackHostApiRepresentation *hostApi = (PaJackHostApiRepresentation *)arg;
682 assert( hostApi );
683 hostApi->xrun = TRUE;
684 PA_DEBUG(( "%s: JACK signalled xrun\n", __FUNCTION__ ));
685 return 0;
686 }
687
688 PaError PaJack_Initialize( PaUtilHostApiRepresentation **hostApi,
689 PaHostApiIndex hostApiIndex )
690 {
691 PaError result = paNoError;
692 PaJackHostApiRepresentation *jackHostApi;
693 int activated = 0;
694 char *clientName;
695 int written;
696 *hostApi = NULL; /* Initialize to NULL */
697
698 UNLESS( jackHostApi = (PaJackHostApiRepresentation*)
699 PaUtil_AllocateMemory( sizeof(PaJackHostApiRepresentation) ), paInsufficientMemory );
700 jackHostApi->deviceInfoMemory = NULL;
701
702 mainThread_ = pthread_self();
703 ASSERT_CALL( pthread_mutex_init( &jackHostApi->mtx, NULL ), 0 );
704 ASSERT_CALL( pthread_cond_init( &jackHostApi->cond, NULL ), 0 );
705
706 /* Try to become a client of the JACK server. If we cannot do
707 * this, then this API cannot be used. */
708
709 clientName = alloca( jack_client_name_size() );
710 written = snprintf( clientName, jack_client_name_size(), "PortAudio-%d", getpid() );
711 assert( written < jack_client_name_size() );
712 jackHostApi->jack_client = jack_client_new( clientName );
713 if( jackHostApi->jack_client == NULL )
714 {
715 /* the V19 development docs say that if an implementation
716 * detects that it cannot be used, it should return a NULL
717 * interface and paNoError */
718 result = paNoError;
719 goto error;
720 }
721
722 UNLESS( jackHostApi->deviceInfoMemory = PaUtil_CreateAllocationGroup(), paInsufficientMemory );
723 jackHostApi->hostApiIndex = hostApiIndex;
724
725 *hostApi = &jackHostApi->commonHostApiRep;
726 (*hostApi)->info.structVersion = 1;
727 (*hostApi)->info.type = paJACK;
728 (*hostApi)->info.name = "JACK Audio Connection Kit";
729
730 /* Build a device list by querying the JACK server */
731
732 ENSURE_PA( BuildDeviceList( jackHostApi ) );
733
734 /* Register functions */
735
736 (*hostApi)->Terminate = Terminate;
737 (*hostApi)->OpenStream = OpenStream;
738 (*hostApi)->IsFormatSupported = IsFormatSupported;
739
740 PaUtil_InitializeStreamInterface( &jackHostApi->callbackStreamInterface,
741 CloseStream, StartStream,
742 StopStream, AbortStream,
743 IsStreamStopped, IsStreamActive,
744 GetStreamTime, GetStreamCpuLoad,
745 PaUtil_DummyRead, PaUtil_DummyWrite,
746 PaUtil_DummyGetReadAvailable,
747 PaUtil_DummyGetWriteAvailable );
748
749 PaUtil_InitializeStreamInterface( &jackHostApi->blockingStreamInterface, CloseStream, StartStream,
750 StopStream, AbortStream, IsStreamStopped, IsStreamActive,
751 GetStreamTime, PaUtil_DummyGetCpuLoad,
752 BlockingReadStream, BlockingWriteStream,
753 BlockingGetStreamReadAvailable, BlockingGetStreamWriteAvailable );
754
755 jackHostApi->inputBase = jackHostApi->outputBase = 0;
756 jackHostApi->xrun = 0;
757 jackHostApi->toAdd = jackHostApi->toRemove = NULL;
758 jackHostApi->processQueue = NULL;
759 jackHostApi->jackIsDown = 0;
760
761 jack_on_shutdown( jackHostApi->jack_client, JackOnShutdown, jackHostApi );
762 jack_set_error_function( JackErrorCallback );
763 jackHostApi->jack_buffer_size = jack_get_buffer_size ( jackHostApi->jack_client );
764 UNLESS( !jack_set_sample_rate_callback( jackHostApi->jack_client, JackSrCb, jackHostApi ), paUnanticipatedHostError );
765 UNLESS( !jack_set_xrun_callback( jackHostApi->jack_client, JackXRunCb, jackHostApi ), paUnanticipatedHostError );
766 UNLESS( !jack_set_process_callback( jackHostApi->jack_client, JackCallback, jackHostApi ), paUnanticipatedHostError );
767 UNLESS( !jack_activate( jackHostApi->jack_client ), paUnanticipatedHostError );
768 activated = 1;
769
770 return result;
771
772 error:
773 if( activated )
774 ASSERT_CALL( jack_deactivate( jackHostApi->jack_client ), 0 );
775
776 if( jackHostApi )
777 {
778 if( jackHostApi->jack_client )
779 ASSERT_CALL( jack_client_close( jackHostApi->jack_client ), 0 );
780
781 if( jackHostApi->deviceInfoMemory )
782 {
783 PaUtil_FreeAllAllocations( jackHostApi->deviceInfoMemory );
784 PaUtil_DestroyAllocationGroup( jackHostApi->deviceInfoMemory );
785 }
786
787 PaUtil_FreeMemory( jackHostApi );
788 }
789 return result;
790 }
791
792
793 static void Terminate( struct PaUtilHostApiRepresentation *hostApi )
794 {
795 PaJackHostApiRepresentation *jackHostApi = (PaJackHostApiRepresentation*)hostApi;
796
797 /* note: this automatically disconnects all ports, since a deactivated
798 * client is not allowed to have any ports connected */
799 ASSERT_CALL( jack_deactivate( jackHostApi->jack_client ), 0 );
800
801 ASSERT_CALL( pthread_mutex_destroy( &jackHostApi->mtx ), 0 );
802 //ASSERT_CALL( pthread_cond_destroy( &jackHostApi->cond ), 0 );
803
804 ASSERT_CALL( jack_client_close( jackHostApi->jack_client ), 0 );
805
806 if( jackHostApi->deviceInfoMemory )
807 {
808 PaUtil_FreeAllAllocations( jackHostApi->deviceInfoMemory );
809 PaUtil_DestroyAllocationGroup( jackHostApi->deviceInfoMemory );
810 }
811
812 PaUtil_FreeMemory( jackHostApi );
813
814 free( jackErr_ );
815 }
816
817 static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
818 const PaStreamParameters *inputParameters,
819 const PaStreamParameters *outputParameters,
820 double sampleRate )
821 {
822 int inputChannelCount = 0, outputChannelCount = 0;
823 PaSampleFormat inputSampleFormat, outputSampleFormat;
824
825 if( inputParameters )
826 {
827 inputChannelCount = inputParameters->channelCount;
828 inputSampleFormat = inputParameters->sampleFormat;
829
830 /* unless alternate device specification is supported, reject the use of
831 paUseHostApiSpecificDeviceSpecification */
832
833 if( inputParameters->device == paUseHostApiSpecificDeviceSpecification )
834 return paInvalidDevice;
835
836 /* check that input device can support inputChannelCount */
837 if( inputChannelCount > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels )
838 return paInvalidChannelCount;
839
840 /* validate inputStreamInfo */
841 if( inputParameters->hostApiSpecificStreamInfo )
842 return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */
843 }
844 else
845 {
846 inputChannelCount = 0;
847 }
848
849 if( outputParameters )
850 {
851 outputChannelCount = outputParameters->channelCount;
852 outputSampleFormat = outputParameters->sampleFormat;
853
854 /* unless alternate device specification is supported, reject the use of
855 paUseHostApiSpecificDeviceSpecification */
856
857 if( outputParameters->device == paUseHostApiSpecificDeviceSpecification )
858 return paInvalidDevice;
859
860 /* check that output device can support inputChannelCount */
861 if( outputChannelCount > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels )
862 return paInvalidChannelCount;
863
864 /* validate outputStreamInfo */
865 if( outputParameters->hostApiSpecificStreamInfo )
866 return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */
867 }
868 else
869 {
870 outputChannelCount = 0;
871 }
872
873 /*
874 The following check is not necessary for JACK.
875
876 - if a full duplex stream is requested, check that the combination
877 of input and output parameters is supported
878
879
880 Because the buffer adapter handles conversion between all standard
881 sample formats, the following checks are only required if paCustomFormat
882 is implemented, or under some other unusual conditions.
883
884 - check that input device can support inputSampleFormat, or that
885 we have the capability to convert from outputSampleFormat to
886 a native format
887
888 - check that output device can support outputSampleFormat, or that
889 we have the capability to convert from outputSampleFormat to
890 a native format
891 */
892
893 /* check that the device supports sampleRate */
894
895 #define ABS(x) ( (x) > 0 ? (x) : -(x) )
896 if( ABS(sampleRate - jack_get_sample_rate(((PaJackHostApiRepresentation *) hostApi)->jack_client )) > 1 )
897 return paInvalidSampleRate;
898 #undef ABS
899
900 return paFormatIsSupported;
901 }
902
903 /* Basic stream initialization */
904 static PaError InitializeStream( PaJackStream *stream, PaJackHostApiRepresentation *hostApi, int numInputChannels,
905 int numOutputChannels )
906 {
907 PaError result = paNoError;
908 assert( stream );
909
910 memset( stream, 0, sizeof (PaJackStream) );
911 UNLESS( stream->stream_memory = PaUtil_CreateAllocationGroup(), paInsufficientMemory );
912 stream->jack_client = hostApi->jack_client;
913 stream->hostApi = hostApi;
914
915 if( numInputChannels > 0 )
916 {
917 UNLESS( stream->local_input_ports =
918 (jack_port_t**) PaUtil_GroupAllocateMemory( stream->stream_memory, sizeof(jack_port_t*) * numInputChannels ),
919 paInsufficientMemory );
920 memset( stream->local_input_ports, 0, sizeof(jack_port_t*) * numInputChannels );
921 UNLESS( stream->remote_output_ports =
922 (jack_port_t**) PaUtil_GroupAllocateMemory( stream->stream_memory, sizeof(jack_port_t*) * numInputChannels ),
923 paInsufficientMemory );
924 memset( stream->remote_output_ports, 0, sizeof(jack_port_t*) * numInputChannels );
925 }
926 if( numOutputChannels > 0 )
927 {
928 UNLESS( stream->local_output_ports =
929 (jack_port_t**) PaUtil_GroupAllocateMemory( stream->stream_memory, sizeof(jack_port_t*) * numOutputChannels ),
930 paInsufficientMemory );
931 memset( stream->local_output_ports, 0, sizeof(jack_port_t*) * numOutputChannels );
932 UNLESS( stream->remote_input_ports =
933 (jack_port_t**) PaUtil_GroupAllocateMemory( stream->stream_memory, sizeof(jack_port_t*) * numOutputChannels ),
934 paInsufficientMemory );
935 memset( stream->remote_input_ports, 0, sizeof(jack_port_t*) * numOutputChannels );
936 }
937
938 stream->num_incoming_connections = numInputChannels;
939 stream->num_outgoing_connections = numOutputChannels;
940
941 error:
942 return result;
943 }
944
945 /*!
946 * Free resources associated with stream, and eventually stream itself.
947 *
948 * Frees allocated memory, and closes opened pcms.
949 */
950 static void CleanUpStream( PaJackStream *stream, int terminateStreamRepresentation, int terminateBufferProcessor )
951 {
952 int i;
953 assert( stream );
954
955 if( stream->isBlockingStream )
956 BlockingEnd( stream );
957
958 for( i = 0; i < stream->num_incoming_connections; ++i )
959 {
960 if( stream->local_input_ports[i] )
961 ASSERT_CALL( jack_port_unregister( stream->jack_client, stream->local_input_ports[i] ), 0 );
962 }
963 for( i = 0; i < stream->num_outgoing_connections; ++i )
964 {
965 if( stream->local_output_ports[i] )
966 ASSERT_CALL( jack_port_unregister( stream->jack_client, stream->local_output_ports[i] ), 0 );
967 }
968
969 if( terminateStreamRepresentation )
970 PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation );
971 if( terminateBufferProcessor )
972 PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );
973
974 if( stream->stream_memory )
975 {
976 PaUtil_FreeAllAllocations( stream->stream_memory );
977 PaUtil_DestroyAllocationGroup( stream->stream_memory );
978 }
979 PaUtil_FreeMemory( stream );
980 }
981
982 static PaError WaitCondition( PaJackHostApiRepresentation *hostApi )
983 {
984 PaError result = paNoError;
985 int err = 0;
986 PaTime pt = PaUtil_GetTime();
987 struct timespec ts;
988
989 ts.tv_sec = (time_t) floor( pt + 1 );
990 ts.tv_nsec = (long) ((pt - floor( pt )) * 1000000000);
991 /* XXX: Best enclose in loop, in case of spurious wakeups? */
992 err = pthread_cond_timedwait( &hostApi->cond, &hostApi->mtx, &ts );
993
994 /* Make sure we didn't time out */
995 UNLESS( err != ETIMEDOUT, paTimedOut );
996 UNLESS( !err, paInternalError );
997
998 error:
999 return result;
1000 }
1001
1002 static PaError AddStream( PaJackStream *stream )
1003 {
1004 PaError result = paNoError;
1005 PaJackHostApiRepresentation *hostApi = stream->hostApi;
1006 /* Add to queue of streams that should be processed */
1007 ASSERT_CALL( pthread_mutex_lock( &hostApi->mtx ), 0 );
1008 if( !hostApi->jackIsDown )
1009 {
1010 hostApi->toAdd = stream;
1011 /* Unlock mutex and await signal from processing thread */
1012 result = WaitCondition( stream->hostApi );
1013 }
1014 ASSERT_CALL( pthread_mutex_unlock( &hostApi->mtx ), 0 );
1015 ENSURE_PA( result );
1016
1017 UNLESS( !hostApi->jackIsDown, paDeviceUnavailable );
1018
1019 error:
1020 return result;
1021 }
1022
1023 /* Remove stream from processing queue */
1024 static PaError RemoveStream( PaJackStream *stream )
1025 {
1026 PaError result = paNoError;
1027 PaJackHostApiRepresentation *hostApi = stream->hostApi;
1028
1029 /* Add to queue over streams that should be processed */
1030 ASSERT_CALL( pthread_mutex_lock( &hostApi->mtx ), 0 );
1031 if( !hostApi->jackIsDown )
1032 {
1033 hostApi->toRemove = stream;
1034 /* Unlock mutex and await signal from processing thread */
1035 result = WaitCondition( stream->hostApi );
1036 }
1037 ASSERT_CALL( pthread_mutex_unlock( &hostApi->mtx ), 0 );
1038 ENSURE_PA( result );
1039
1040 error:
1041 return result;
1042 }
1043
1044 /* Add stream to processing queue */
1045 static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
1046 PaStream** s,
1047 const PaStreamParameters *inputParameters,
1048 const PaStreamParameters *outputParameters,
1049 double sampleRate,
1050 unsigned long framesPerBuffer,
1051 PaStreamFlags streamFlags,
1052 PaStreamCallback *streamCallback,
1053 void *userData )
1054 {
1055 PaError result = paNoError;
1056 PaJackHostApiRepresentation *jackHostApi = (PaJackHostApiRepresentation*)hostApi;
1057 PaJackStream *stream = NULL;
1058 char *port_string = alloca( jack_port_name_size() );
1059 unsigned long regexSz = jack_client_name_size() + 3;
1060 char *regex_pattern = alloca( regexSz );
1061 const char **jack_ports = NULL;
1062 /* int jack_max_buffer_size = jack_get_buffer_size( jackHostApi->jack_client ); */
1063 int i;
1064 int inputChannelCount, outputChannelCount;
1065 const double jackSr = jack_get_sample_rate( jackHostApi->jack_client );
1066 PaSampleFormat inputSampleFormat = 0, outputSampleFormat = 0;
1067 int bpInitialized = 0, srInitialized = 0; /* Initialized buffer processor and stream representation? */
1068 unsigned long ofs;
1069
1070 /* validate platform specific flags */
1071 if( (streamFlags & paPlatformSpecificFlags) != 0 )
1072 return paInvalidFlag; /* unexpected platform specific flag */
1073 if( (streamFlags & paPrimeOutputBuffersUsingStreamCallback) != 0 )
1074 {
1075 streamFlags &= ~paPrimeOutputBuffersUsingStreamCallback;
1076 /*return paInvalidFlag;*/ /* This implementation does not support buffer priming */
1077 }
1078
1079 if( framesPerBuffer != paFramesPerBufferUnspecified )
1080 {
1081 /* Jack operates with power of two buffers, and we don't support non-integer buffer adaption (yet) */
1082 /*UNLESS( !(framesPerBuffer & (framesPerBuffer - 1)), paBufferTooBig );*/ /* TODO: Add descriptive error code? */
1083 }
1084
1085 /* Preliminary checks */
1086
1087 if( inputParameters )
1088 {
1089 inputChannelCount = inputParameters->channelCount;
1090 inputSampleFormat = inputParameters->sampleFormat;
1091
1092 /* unless alternate device specification is supported, reject the use of
1093 paUseHostApiSpecificDeviceSpecification */
1094
1095 if( inputParameters->device == paUseHostApiSpecificDeviceSpecification )
1096 return paInvalidDevice;
1097
1098 /* check that input device can support inputChannelCount */
1099 if( inputChannelCount > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels )
1100 return paInvalidChannelCount;
1101
1102 /* validate inputStreamInfo */
1103 if( inputParameters->hostApiSpecificStreamInfo )
1104 return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */
1105 }
1106 else
1107 {
1108 inputChannelCount = 0;
1109 }
1110
1111 if( outputParameters )
1112 {
1113 outputChannelCount = outputParameters->channelCount;
1114 outputSampleFormat = outputParameters->sampleFormat;
1115
1116 /* unless alternate device specification is supported, reject the use of
1117 paUseHostApiSpecificDeviceSpecification */
1118
1119 if( outputParameters->device == paUseHostApiSpecificDeviceSpecification )
1120 return paInvalidDevice;
1121
1122 /* check that output device can support inputChannelCount */
1123 if( outputChannelCount > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels )
1124 return paInvalidChannelCount;
1125
1126 /* validate outputStreamInfo */
1127 if( outputParameters->hostApiSpecificStreamInfo )
1128 return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */
1129 }
1130 else
1131 {
1132 outputChannelCount = 0;
1133 }
1134
1135 /* ... check that the sample rate exactly matches the ONE acceptable rate
1136 * A: This rate isn't necessarily constant though? */
1137
1138 #define ABS(x) ( (x) > 0 ? (x) : -(x) )
1139 if( ABS(sampleRate - jackSr) > 1 )
1140 return paInvalidSampleRate;
1141 #undef ABS
1142
1143 UNLESS( stream = (PaJackStream*)PaUtil_AllocateMemory( sizeof(PaJackStream) ), paInsufficientMemory );
1144 ENSURE_PA( InitializeStream( stream, jackHostApi, inputChannelCount, outputChannelCount ) );
1145
1146 /* the blocking emulation, if necessary */
1147 stream->isBlockingStream = !streamCallback;
1148 if( stream->isBlockingStream )
1149 {
1150 float latency = 0.001; /* 1ms is the absolute minimum we support */
1151 int minimum_buffer_frames = 0;
1152
1153 if( inputParameters && inputParameters->suggestedLatency > latency )
1154 latency = inputParameters->suggestedLatency;
1155 else if( outputParameters && outputParameters->suggestedLatency > latency )
1156 latency = outputParameters->suggestedLatency;
1157
1158 /* the latency the user asked for indicates the minimum buffer size in frames */
1159 minimum_buffer_frames = (int) (latency * jack_get_sample_rate( jackHostApi->jack_client ));
1160
1161 /* we also need to be able to store at least three full jack buffers to avoid dropouts */
1162 if( jackHostApi->jack_buffer_size * 3 > minimum_buffer_frames )
1163 minimum_buffer_frames = jackHostApi->jack_buffer_size * 3;
1164
1165 /* setup blocking API data structures (FIXME: can fail) */
1166 BlockingBegin( stream, minimum_buffer_frames );
1167
1168 /* install our own callback for the blocking API */
1169 streamCallback = BlockingCallback;
1170 userData = stream;
1171
1172 PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,
1173 &jackHostApi->blockingStreamInterface, streamCallback, userData );
1174 }
1175 else
1176 {
1177 PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,
1178 &jackHostApi->callbackStreamInterface, streamCallback, userData );
1179 }
1180 srInitialized = 1;
1181 PaUtil_InitializeCpuLoadMeasurer( &stream->cpuLoadMeasurer, jackSr );
1182
1183 /* create the JACK ports. We cannot connect them until audio
1184 * processing begins */
1185
1186 /* Register a unique set of ports for this stream
1187 * TODO: Robust allocation of new port names */
1188
1189 ofs = jackHostApi->inputBase;
1190 for( i = 0; i < inputChannelCount; i++ )
1191 {
1192 snprintf( port_string, jack_port_name_size(), "in_%lu", ofs + i );
1193 UNLESS( stream->local_input_ports[i] = jack_port_register(
1194 jackHostApi->jack_client, port_string,
1195 JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0 ), paInsufficientMemory );
1196 }
1197 jackHostApi->inputBase += inputChannelCount;
1198
1199 ofs = jackHostApi->outputBase;
1200 for( i = 0; i < outputChannelCount; i++ )
1201 {
1202 snprintf( port_string, jack_port_name_size(), "out_%lu", ofs + i );
1203 UNLESS( stream->local_output_ports[i] = jack_port_register(
1204 jackHostApi->jack_client, port_string,
1205 JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0 ), paInsufficientMemory );
1206 }
1207 jackHostApi->outputBase += outputChannelCount;
1208
1209 /* look up the jack_port_t's for the remote ports. We could do
1210 * this at stream start time, but doing it here ensures the
1211 * name lookup only happens once. */
1212
1213 if( inputChannelCount > 0 )
1214 {
1215 int err = 0;
1216
1217 /* ... remote output ports (that we input from) */
1218 snprintf( regex_pattern, regexSz, "%s:.*", hostApi->deviceInfos[ inputParameters->device ]->name );
1219 UNLESS( jack_ports = jack_get_ports( jackHostApi->jack_client, regex_pattern,
1220 NULL, JackPortIsOutput ), paUnanticipatedHostError );
1221 for( i = 0; i < inputChannelCount && jack_ports[i]; i++ )
1222 {
1223 if( (stream->remote_output_ports[i] = jack_port_by_name(
1224 jackHostApi->jack_client, jack_ports[i] )) == NULL )
1225 {
1226 err = 1;
1227 break;
1228 }
1229 }
1230 free( jack_ports );
1231 UNLESS( !err, paInsufficientMemory );
1232
1233 /* Fewer ports than expected? */
1234 UNLESS( i == inputChannelCount, paInternalError );
1235 }
1236
1237 if( outputChannelCount > 0 )
1238 {
1239 int err = 0;
1240
1241 /* ... remote input ports (that we output to) */
1242 snprintf( regex_pattern, regexSz, "%s:.*", hostApi->deviceInfos[ outputParameters->device ]->name );
1243 UNLESS( jack_ports = jack_get_ports( jackHostApi->jack_client, regex_pattern,
1244 NULL, JackPortIsInput ), paUnanticipatedHostError );
1245 for( i = 0; i < outputChannelCount && jack_ports[i]; i++ )
1246 {
1247 if( (stream->remote_input_ports[i] = jack_port_by_name(
1248 jackHostApi->jack_client, jack_ports[i] )) == 0 )
1249 {
1250 err = 1;
1251 break;
1252 }
1253 }
1254 free( jack_ports );
1255 UNLESS( !err , paInsufficientMemory );
1256
1257 /* Fewer ports than expected? */
1258 UNLESS( i == outputChannelCount, paInternalError );
1259 }
1260
1261 ENSURE_PA( PaUtil_InitializeBufferProcessor(
1262 &stream->bufferProcessor,
1263 inputChannelCount,
1264 inputSampleFormat,
1265 paFloat32, /* hostInputSampleFormat */
1266 outputChannelCount,
1267 outputSampleFormat,
1268 paFloat32, /* hostOutputSampleFormat */
1269 jackSr,
1270 streamFlags,
1271 framesPerBuffer,
1272 0, /* Ignored */
1273 paUtilUnknownHostBufferSize, /* Buffer size may vary on JACK's discretion */
1274 streamCallback,
1275 userData ) );
1276 bpInitialized = 1;
1277
1278 if( stream->num_incoming_connections > 0 )
1279 stream->streamRepresentation.streamInfo.inputLatency = (jack_port_get_latency( stream->remote_output_ports[0] )
1280 - jack_get_buffer_size( jackHostApi->jack_client ) /* One buffer is not counted as latency */
1281 + PaUtil_GetBufferProcessorInputLatency( &stream->bufferProcessor )) / sampleRate;
1282 if( stream->num_outgoing_connections > 0 )
1283 stream->streamRepresentation.streamInfo.outputLatency = (jack_port_get_latency( stream->remote_input_ports[0] )
1284 - jack_get_buffer_size( jackHostApi->jack_client ) /* One buffer is not counted as latency */
1285 + PaUtil_GetBufferProcessorOutputLatency( &stream->bufferProcessor )) / sampleRate;
1286
1287 stream->streamRepresentation.streamInfo.sampleRate = jackSr;
1288 stream->t0 = jack_frame_time( jackHostApi->jack_client ); /* A: Time should run from Pa_OpenStream */
1289
1290 ENSURE_PA( AddStream( stream ) ); /* Add to queue over opened streams */
1291
1292 *s = (PaStream*)stream;
1293
1294 return result;
1295
1296 error:
1297 if( stream )
1298 CleanUpStream( stream, srInitialized, bpInitialized );
1299
1300 return result;
1301 }
1302
1303 /*
1304 When CloseStream() is called, the multi-api layer ensures that
1305 the stream has already been stopped or aborted.
1306 */
1307 static PaError CloseStream( PaStream* s )
1308 {
1309 PaError result = paNoError;
1310 PaJackStream *stream = (PaJackStream*)s;
1311
1312 /* Remove this stream from the processing queue */
1313 ENSURE_PA( RemoveStream( stream ) );
1314
1315 error:
1316 CleanUpStream( stream, 1, 1 );
1317 return result;
1318 }
1319
1320 static PaError RealProcess( PaJackStream *stream, jack_nframes_t frames )
1321 {
1322 PaError result = paNoError;
1323 PaStreamCallbackTimeInfo timeInfo = {0,0,0};
1324 int chn;
1325 int framesProcessed;
1326 const double sr = jack_get_sample_rate( stream->jack_client ); /* Shouldn't change during the process callback */
1327 PaStreamCallbackFlags cbFlags = 0;
1328
1329 /* If the user has returned !paContinue from the callback we'll want to flush the internal buffers,
1330 * when these are empty we can finally mark the stream as inactive */
1331 if( stream->callbackResult != paContinue &&
1332 PaUtil_IsBufferProcessorOutputEmpty( &stream->bufferProcessor ) )
1333 {
1334 stream->is_active = 0;
1335 if( stream->streamRepresentation.streamFinishedCallback )
1336 stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData );
1337 PA_DEBUG(( "%s: Callback finished\n", __FUNCTION__ ));
1338
1339 goto end;
1340 }
1341
1342 timeInfo.currentTime = (jack_frame_time( stream->jack_client ) - stream->t0) / sr;
1343 if( stream->num_incoming_connections > 0 )
1344 timeInfo.inputBufferAdcTime = timeInfo.currentTime - jack_port_get_latency( stream->remote_output_ports[0] )
1345 / sr;
1346 if( stream->num_outgoing_connections > 0 )
1347 timeInfo.outputBufferDacTime = timeInfo.currentTime + jack_port_get_latency( stream->remote_input_ports[0] )
1348 / sr;
1349
1350 PaUtil_BeginCpuLoadMeasurement( &stream->cpuLoadMeasurer );
1351
1352 if( stream->xrun )
1353 {
1354 /* XXX: Any way to tell which of these occurred? */
1355 cbFlags = paOutputUnderflow | paInputOverflow;
1356 stream->xrun = FALSE;
1357 }
1358 PaUtil_BeginBufferProcessing( &stream->bufferProcessor, &timeInfo,
1359 cbFlags );
1360
1361 if( stream->num_incoming_connections > 0 )
1362 PaUtil_SetInputFrameCount( &stream->bufferProcessor, frames );
1363 if( stream->num_outgoing_connections > 0 )
1364 PaUtil_SetOutputFrameCount( &stream->bufferProcessor, frames );
1365
1366 for( chn = 0; chn < stream->num_incoming_connections; chn++ )
1367 {
1368 jack_default_audio_sample_t *channel_buf = (jack_default_audio_sample_t*)
1369 jack_port_get_buffer( stream->local_input_ports[chn],
1370 frames );
1371
1372 PaUtil_SetNonInterleavedInputChannel( &stream->bufferProcessor,
1373 chn,
1374 channel_buf );
1375 }
1376
1377 for( chn = 0; chn < stream->num_outgoing_connections; chn++ )
1378 {
1379 jack_default_audio_sample_t *channel_buf = (jack_default_audio_sample_t*)
1380 jack_port_get_buffer( stream->local_output_ports[chn],
1381 frames );
1382
1383 PaUtil_SetNonInterleavedOutputChannel( &stream->bufferProcessor,
1384 chn,
1385 channel_buf );
1386 }
1387
1388 framesProcessed = PaUtil_EndBufferProcessing( &stream->bufferProcessor,
1389 &stream->callbackResult );
1390 /* We've specified a host buffer size mode where every frame should be consumed by the buffer processor */
1391 assert( framesProcessed == frames );
1392
1393 PaUtil_EndCpuLoadMeasurement( &stream->cpuLoadMeasurer, framesProcessed );
1394
1395 end:
1396 return result;
1397 }
1398
1399 /* Alter the processing queue if necessary */
1400 static PaError UpdateQueue( PaJackHostApiRepresentation *hostApi )
1401 {
1402 PaError result = paNoError;
1403 int queueModified = 0;
1404 const double jackSr = jack_get_sample_rate( hostApi->jack_client );
1405 int err;
1406
1407 if( (err = pthread_mutex_trylock( &hostApi->mtx )) != 0 )
1408 {
1409 assert( err == EBUSY );
1410 return paNoError;
1411 }
1412
1413 if( hostApi->toAdd )
1414 {
1415 if( hostApi->processQueue )
1416 {
1417 PaJackStream *node = hostApi->processQueue;
1418 /* Advance to end of queue */
1419 while( node->next )
1420 node = node->next;
1421
1422 node->next = hostApi->toAdd;
1423 }
1424 else
1425 hostApi->processQueue = (PaJackStream *)hostApi->toAdd;
1426
1427 /* If necessary, update stream state */
1428 if( hostApi->toAdd->streamRepresentation.streamInfo.sampleRate != jackSr )
1429 UpdateSampleRate( hostApi->toAdd, jackSr );
1430
1431 hostApi->toAdd = NULL;
1432 queueModified = 1;
1433 }
1434 if( hostApi->toRemove )
1435 {
1436 int removed = 0;
1437 PaJackStream *node = hostApi->processQueue, *prev = NULL;
1438 assert( hostApi->processQueue );
1439
1440 while( node )
1441 {
1442 if( node == hostApi->toRemove )
1443 {
1444 if( prev )
1445 prev->next = node->next;
1446 else
1447 hostApi->processQueue = (PaJackStream *)node->next;
1448
1449 removed = 1;
1450 break;
1451 }
1452
1453 prev = node;
1454 node = node->next;
1455 }
1456 UNLESS( removed, paInternalError );
1457 hostApi->toRemove = NULL;
1458 PA_DEBUG(( "%s: Removed stream from processing queue\n", __FUNCTION__ ));
1459 queueModified = 1;
1460 }
1461
1462 if( queueModified )
1463 {
1464 /* Signal that we've done what was asked of us */
1465 ASSERT_CALL( pthread_cond_signal( &hostApi->cond ), 0 );
1466 }
1467
1468 error:
1469 ASSERT_CALL( pthread_mutex_unlock( &hostApi->mtx ), 0 );
1470
1471 return result;
1472 }
1473
1474 static int JackCallback( jack_nframes_t frames, void *userData )
1475 {
1476 PaError result = paNoError;
1477 PaJackHostApiRepresentation *hostApi = (PaJackHostApiRepresentation *)userData;
1478 PaJackStream *stream = NULL;
1479 int xrun = hostApi->xrun;
1480 hostApi->xrun = 0;
1481
1482 assert( hostApi );
1483
1484 ENSURE_PA( UpdateQueue( hostApi ) );
1485
1486 /* Process each stream */
1487 stream = hostApi->processQueue;
1488 for( ; stream; stream = stream->next )
1489 {
1490 if( xrun ) /* Don't override if already set */
1491 stream->xrun = 1;
1492
1493 /* See if this stream is to be started */
1494 if( stream->doStart )
1495 {
1496 /* If we can't obtain a lock, we'll try next time */
1497 int err = pthread_mutex_trylock( &stream->hostApi->mtx );
1498 if( !err )
1499 {
1500 if( stream->doStart ) /* Could potentially change before obtaining the lock */
1501 {
1502 stream->is_active = 1;
1503 stream->doStart = 0;
1504 PA_DEBUG(( "%s: Starting stream\n", __FUNCTION__ ));
1505 ASSERT_CALL( pthread_cond_signal( &stream->hostApi->cond ), 0 );
1506 stream->callbackResult = paContinue;
1507 stream->isSilenced = 0;
1508 }
1509
1510 ASSERT_CALL( pthread_mutex_unlock( &stream->hostApi->mtx ), 0 );
1511 }
1512 else
1513 assert( err == EBUSY );
1514 }
1515 else if( stream->doStop || stream->doAbort ) /* Should we stop/abort stream? */
1516 {
1517 if( stream->callbackResult == paContinue ) /* Ok, make it stop */
1518 {
1519 PA_DEBUG(( "%s: Stopping stream\n", __FUNCTION__ ));
1520 stream->callbackResult = stream->doStop ? paComplete : paAbort;
1521 }
1522 }
1523
1524 if( stream->is_active )
1525 ENSURE_PA( RealProcess( stream, frames ) );
1526 /* If we have just entered inactive state, silence output */
1527 if( !stream->is_active && !stream->isSilenced )
1528 {
1529 int i;
1530
1531 /* Silence buffer after entering inactive state */
1532 PA_DEBUG(( "Silencing the output\n" ));
1533 for( i = 0; i < stream->num_outgoing_connections; ++i )
1534 {
1535 jack_default_audio_sample_t *buffer = jack_port_get_buffer( stream->local_output_ports[i], frames );
1536 memset( buffer, 0, sizeof (jack_default_audio_sample_t) * frames );
1537 }
1538
1539 stream->isSilenced = 1;
1540 }
1541
1542 if( stream->doStop || stream->doAbort )
1543 {
1544 /* See if RealProcess has acted on the request */
1545 if( !stream->is_active ) /* Ok, signal to the main thread that we've carried out the operation */
1546 {
1547 /* If we can't obtain a lock, we'll try next time */
1548 int err = pthread_mutex_trylock( &stream->hostApi->mtx );
1549 if( !err )
1550 {
1551 stream->doStop = stream->doAbort = 0;
1552 ASSERT_CALL( pthread_cond_signal( &stream->hostApi->cond ), 0 );
1553 ASSERT_CALL( pthread_mutex_unlock( &stream->hostApi->mtx ), 0 );
1554 }
1555 else
1556 assert( err == EBUSY );
1557 }
1558 }
1559 }
1560
1561 return 0;
1562 error:
1563 return -1;
1564 }
1565
1566 static PaError StartStream( PaStream *s )
1567 {
1568 PaError result = paNoError;
1569 PaJackStream *stream = (PaJackStream*)s;
1570 int i;
1571
1572 /* Ready the processor */
1573 PaUtil_ResetBufferProcessor( &stream->bufferProcessor );
1574
1575 /* connect the ports */
1576
1577 /* NOTE: I would rather use jack_port_connect which uses jack_port_t's
1578 * instead of port names, but it is not implemented yet. */
1579 if( stream->num_incoming_connections > 0 )
1580 {
1581 for( i = 0; i < stream->num_incoming_connections; i++ )
1582 UNLESS( jack_connect( stream->jack_client,
1583 jack_port_name( stream->remote_output_ports[i] ),
1584 jack_port_name( stream->local_input_ports[i] ) ) == 0, paUnanticipatedHostError );
1585 }
1586
1587 if( stream->num_outgoing_connections > 0 )
1588 {
1589 for( i = 0; i < stream->num_outgoing_connections; i++ )
1590 UNLESS( jack_connect( stream->jack_client,
1591 jack_port_name( stream->local_output_ports[i] ),
1592 jack_port_name( stream->remote_input_ports[i] ) ) == 0, paUnanticipatedHostError );
1593 }
1594
1595 stream->xrun = FALSE;
1596
1597 /* Enable processing */
1598
1599 ASSERT_CALL( pthread_mutex_lock( &stream->hostApi->mtx ), 0 );
1600 stream->doStart = 1;
1601
1602 /* Wait for stream to be started */
1603 result = WaitCondition( stream->hostApi );
1604 /*
1605 do
1606 {
1607 err = pthread_cond_timedwait( &stream->hostApi->cond, &stream->hostApi->mtx, &ts );
1608 } while( !stream->is_active && !err );
1609 */
1610 if( result != paNoError ) /* Something went wrong, call off the stream start */
1611 {
1612 stream->doStart = 0;
1613 stream->is_active = 0; /* Cancel any processing */
1614 }
1615 ASSERT_CALL( pthread_mutex_unlock( &stream->hostApi->mtx ), 0 );
1616
1617 ENSURE_PA( result );
1618
1619 stream->is_running = TRUE;
1620 PA_DEBUG(( "%s: Stream started\n", __FUNCTION__ ));
1621
1622 error:
1623 return result;
1624 }
1625
1626 static PaError RealStop( PaJackStream *stream, int abort )
1627 {
1628 PaError result = paNoError;
1629 int i;
1630
1631 if( stream->isBlockingStream )
1632 BlockingWaitEmpty ( stream );
1633
1634 ASSERT_CALL( pthread_mutex_lock( &stream->hostApi->mtx ), 0 );
1635 if( abort )
1636 stream->doAbort = 1;
1637 else
1638 stream->doStop = 1;
1639
1640 /* Wait for stream to be stopped */
1641 result = WaitCondition( stream->hostApi );
1642 ASSERT_CALL( pthread_mutex_unlock( &stream->hostApi->mtx ), 0 );
1643 ENSURE_PA( result );
1644
1645 UNLESS( !stream->is_active, paInternalError );
1646
1647 PA_DEBUG(( "%s: Stream stopped\n", __FUNCTION__ ));
1648
1649 error:
1650 stream->is_running = FALSE;
1651
1652 /* Disconnect ports belonging to this stream */
1653
1654 if( !stream->hostApi->jackIsDown ) /* XXX: Well? */
1655 {
1656 if( stream->num_incoming_connections > 0 )
1657 {
1658 int failed = 0;
1659 for( i = 0; i < stream->num_incoming_connections; i++ )
1660 {
1661 if( jack_port_disconnect( stream->jack_client, stream->local_input_ports[i] ) )
1662 {
1663 failed = 1;
1664 }
1665 }
1666 if( failed )
1667 {
1668 PA_DEBUG(( "%s: Failed to disconnect input, already done externally?\n", __FUNCTION__ ));
1669 }
1670 }
1671 if( stream->num_outgoing_connections > 0 )
1672 {
1673 int failed = 0;
1674 for( i = 0; i < stream->num_outgoing_connections; i++ )
1675 {
1676 if( jack_port_disconnect( stream->jack_client, stream->local_output_ports[i] ) )
1677 {
1678 failed = 1;
1679 }
1680 }
1681 if( failed )
1682 {
1683 PA_DEBUG(( "%s: Failed to disconnect output, already done externally?\n", __FUNCTION__ ));
1684 }
1685 }
1686 }
1687
1688 return result;
1689 }
1690
1691 static PaError StopStream( PaStream *s )
1692 {
1693 assert(s);
1694 return RealStop( (PaJackStream *)s, 0 );
1695 }
1696
1697 static PaError AbortStream( PaStream *s )
1698 {
1699 assert(s);
1700 return RealStop( (PaJackStream *)s, 1 );
1701 }
1702
1703 static PaError IsStreamStopped( PaStream *s )
1704 {
1705 PaJackStream *stream = (PaJackStream*)s;
1706 return !stream->is_running;
1707 }
1708
1709
1710 static PaError IsStreamActive( PaStream *s )
1711 {
1712 PaJackStream *stream = (PaJackStream*)s;
1713 return stream->is_active;
1714 }
1715
1716
1717 static PaTime GetStreamTime( PaStream *s )
1718 {
1719 PaJackStream *stream = (PaJackStream*)s;
1720
1721 /* A: Is this relevant?? --> TODO: what if we're recording-only? */
1722 return (jack_frame_time( stream->jack_client ) - stream->t0) / (PaTime)jack_get_sample_rate( stream->jack_client );
1723 }
1724
1725
1726 static double GetStreamCpuLoad( PaStream* s )
1727 {
1728 PaJackStream *stream = (PaJackStream*)s;
1729 return PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer );
1730 }