Debian Codegraph @

src/libout123/modules/jack.c

raw
1 /*
2 jack: audio output via JACK Audio Connection Kit
3
4 copyright 2006-2023 by the mpg123 project - free software under the terms of the LGPL 2.1
5 see COPYING and AUTHORS files in distribution or http://mpg123.org
6 initially written by Nicholas J. Humfrey
7
8 I reworked the processing logic. Only one ringbuffer, deinterleaving in the
9 processing callback. A semaphore to avoid using usleep() for waiting. Up
10 to 99 channels. Only float input (ensures that libmpg123 selects f32
11 encoding). This is still a hack to shoehorn the JACK API into our model.
12
13 Damn. I'm wary of he semaphore. I'm sure I constructed a deadlock there.
14 There's always a deadlock. --ThOr
15 */
16
17 #include "../out123_int.h"
18
19 #include <math.h>
20
21 #include <jack/jack.h>
22 #include <jack/ringbuffer.h>
23 /* Using some pthread to provide synchronization between process callback
24 and writer part. The JACK API is not meant for this. Libpthread is
25 pulled in as libjack dependency anyway. */
26 #include <semaphore.h>
27 #include <sys/errno.h>
28
29 #include "../../common/debug.h"
30
31 typedef struct {
32 int alive;
33 sem_t sem; /* semaphore to avoid busy waiting */
34 int channels;
35 int encoding;
36 int framesize;
37 jack_default_audio_sample_t **ports_buf;
38 jack_port_t **ports;
39 jack_ringbuffer_t *rb;
40 size_t rb_size; /* in bytes */
41 jack_client_t *client;
42 char *procbuf;
43 size_t procbuf_frames; /* in PCM frames */
44 } jack_handle_t, *jack_handle_ptr;
45
46 static jack_handle_t* alloc_jack_handle(out123_handle *ao)
47 {
48 jack_handle_t *handle=NULL;
49 int i;
50
51 handle = malloc(sizeof(jack_handle_t));
52 if (!handle)
53 return NULL;
54 handle->channels = ao->channels;
55 handle->encoding = ao->format;
56 handle->framesize = ao->framesize;
57 handle->rb = NULL;
58 handle->ports_buf = malloc( sizeof(jack_default_audio_sample_t*)
59 * ao->channels );
60 handle->ports = malloc(sizeof(jack_port_t*)*ao->channels);
61 if(!handle->ports_buf || !handle->ports)
62 {
63 if(handle->ports_buf)
64 free(handle->ports_buf);
65 if(handle->ports)
66 free(handle->ports);
67 free(handle);
68 return NULL;
69 }
70 for(i=0; i<ao->channels; ++i)
71 {
72 handle->ports_buf[i] = NULL;
73 handle->ports[i] = NULL;
74 }
75 if(sem_init(&handle->sem, 0, 0))
76 {
77 if(!AOQUIET)
78 error("Semaphore init failed.");
79 free(handle->ports_buf);
80 free(handle->ports);
81 free(handle);
82 return NULL;
83 }
84 handle->alive = 0;
85 handle->client = NULL;
86 handle->procbuf = NULL;
87 handle->rb_size = 0;
88 handle->procbuf_frames = 0;
89
90 return handle;
91 }
92
93
94 static void free_jack_handle( jack_handle_t* handle )
95 {
96 int i;
97
98 if(handle->ports)
99 {
100 if(handle->client)
101 for(i=0; i<handle->channels; i++)
102 {
103 /* Close the port for channel*/
104 if(handle->ports[i])
105 jack_port_unregister(handle->client, handle->ports[i]);
106 }
107 free(handle->ports);
108 }
109 if(handle->ports_buf)
110 free(handle->ports_buf);
111 /* Free up the ring buffer for channel*/
112 if(handle->rb)
113 jack_ringbuffer_free(handle->rb);
114 if (handle->client)
115 jack_client_close(handle->client);
116 if (handle->procbuf)
117 free(handle->procbuf);
118 sem_destroy(&handle->sem);
119 free(handle);
120 }
121
122
123 static int process_callback( jack_nframes_t nframes, void *arg )
124 {
125 int c;
126 jack_handle_t* handle = (jack_handle_t*)arg;
127 size_t to_read = nframes;
128
129 for(c=0; c<handle->channels; ++c)
130 handle->ports_buf[c] =
131 jack_port_get_buffer(handle->ports[c], nframes);
132
133 /* One ringbuffer to rule them all, getting interleaved data piecewise
134 and appending to non-interleaved buffers. */
135 while(to_read)
136 {
137 /* Need to read into temporary storage, then deinterleave to JACK
138 buffers. */
139 size_t got_piece;
140 size_t avail_piece;
141 size_t piece = to_read > handle->procbuf_frames
142 ? handle->procbuf_frames
143 : to_read;
144 /* Ensure we get only full PCM frames by checking available byte count
145 and reducing expectation. */
146 avail_piece = jack_ringbuffer_read_space(handle->rb)/handle->framesize;
147 got_piece = jack_ringbuffer_read( handle->rb
148 , handle->procbuf, (avail_piece > piece ? piece : avail_piece)
149 * handle->framesize ) / handle->framesize;
150 debug2("fetched %zu frames from ringbuffer (wanted %zu)", got_piece, piece);
151 /* If this is the last piece, fill up, not time to wait. */
152 if(to_read > piece)
153 piece = got_piece; /* We got further loop cycle(s) to get the rest. */
154 else
155 {
156 if(piece > got_piece)
157 {
158 debug("filling up with zeros");
159 bzero( handle->procbuf+got_piece*handle->framesize
160 , (piece-got_piece)*handle->framesize );
161 }
162 }
163 /* Now extract the pieces for the channels. */
164 for (c=0; c < handle->channels; ++c)
165 {
166 size_t n;
167 jack_default_audio_sample_t *dst = handle->ports_buf[c];
168 if(handle->encoding == MPG123_ENC_FLOAT_32)
169 {
170 float* src = (float*)handle->procbuf;
171 for(n=0; n<piece; ++n)
172 *(dst++) = src[(n*handle->channels)+c];
173 }
174 else /* MPG123_ENC_FLOAT_64 */
175 {
176 double* src = (double*)handle->procbuf;
177 for(n=0; n<piece; ++n)
178 *(dst++) = src[(n*handle->channels)+c];
179 }
180 /* Store output buffer offset. */
181 handle->ports_buf[c] = dst;
182 }
183 /* Give the writer a hint about the time passed. */
184 sem_post(&handle->sem);
185 to_read -= piece;
186 }
187 /* Success*/
188 return 0;
189 }
190
191 /* This is triggered on server shutdown and very much necessary to avoid
192 out123 hanging on the processor semaphore. */
193 static void shutdown_callback(void *arg)
194 {
195 jack_handle_t* handle = (jack_handle_t*)arg;
196 handle->alive = 0;
197 sem_post(&handle->sem);
198 debug("shutdown_callback()");
199 }
200
201 /* connect to jack ports named in the NULL-terminated wishlist */
202 static int real_connect_jack_ports(out123_handle *ao
203 , jack_handle_t* handle, const char** wishlist)
204 {
205 const char **wish = wishlist;
206 int ch, err;
207 int ch_wrap = 0, wish_wrap = 0;
208
209 if(!wish)
210 return 0;
211 if(wish != NULL && *wish == NULL)
212 return 1; /* success, nothing connected as wanted */
213 ch=0;
214 /* Connect things as long as there are sources or sinks left. */
215 while(!wish_wrap || !ch_wrap)
216 {
217 const char* in = jack_port_name(handle->ports[ch]);
218
219 if((err = jack_connect(handle->client, in, *wish)) != 0 && err != EEXIST)
220 {
221 if(!AOQUIET)
222 error4( "connect_jack_ports(): failed to jack_connect() ch%i (%s) to %s: %d"
223 , ch, in ? in : "<nil>", *wish, err );
224 return 0;
225 }
226 /*
227 Increment channel and wishlist, both possibly wrapping around, to
228 ensure we connected all channels to some output port and provided
229 some input to all ports in the wishlist. Both cases of less channels
230 than output ports (splitting) and more channels than output ports
231 (downmix) are sensible.
232 */
233 if(++ch == handle->channels)
234 {
235 ch = 0;
236 ++ch_wrap;
237 }
238 if(!*(++wish))
239 {
240 wish = wishlist;
241 ++wish_wrap;
242 }
243 }
244
245 return 1;
246 }
247
248 /* crude way of automatically connecting up jack ports */
249 /* 0 on error */
250 static int autoconnect_jack_ports(out123_handle *ao, jack_handle_t* handle)
251 {
252 const char **all_ports;
253 unsigned int ch=0;
254 int err,i;
255
256 /* Get a list of all the jack ports*/
257 all_ports = jack_get_ports (handle->client, NULL, NULL, JackPortIsInput);
258 if(!all_ports)
259 {
260 if(!AOQUIET)
261 error("connect_jack_ports(): jack_get_ports() returned NULL.");
262 return 0;
263 }
264 /* Step through each port name*/
265 for (i = 0; all_ports[i]; ++i)
266 {
267 const char* in = jack_port_name( handle->ports[ch] );
268 const char* out = all_ports[i];
269
270 if ((err = jack_connect(handle->client, in, out)) != 0 && err != EEXIST)
271 {
272 if(!AOQUIET)
273 error1("connect_jack_ports(): failed to jack_connect() ports: %d",err);
274 return 0;
275 }
276
277 /* Found enough ports ?*/
278 if (++ch >= handle->channels) break;
279 }
280 jack_free(all_ports);
281 return 1;
282 }
283
284
285 static int connect_jack_ports(out123_handle *ao
286 , jack_handle_t* handle)
287 {
288 debug1("connect_jack_ports with dev=%s", ao->device ? ao->device : "<nil>");
289 if(ao->device==NULL || strcmp(ao->device, "auto")==0)
290 return autoconnect_jack_ports(ao, handle);
291 else
292 {
293 /* Parse device for a set of ports, comma separated. */
294 const char** wishlist; /* Channels and end marker. */
295 int wish_channels = 1; /* Numper of entries in wishlist. */
296 char *devcopy, *chr;
297 int ret;
298 int c;
299 size_t len;
300 len = strlen(ao->device);
301 /* We connect as many JACK ports as desired, possibly duplicating. */
302 for(chr=ao->device; *chr; ++chr)
303 if(*chr == ',')
304 ++wish_channels;
305 debug1("wish_channels: %i", wish_channels);
306 wishlist = malloc(sizeof(char*)*(wish_channels+1));
307 devcopy = INT123_compat_strdup(ao->device);
308 if(devcopy == NULL || wishlist == NULL)
309 {
310 if(devcopy)
311 free(devcopy);
312 if(wishlist)
313 free(wishlist);
314 if(!AOQUIET)
315 error("OOM");
316 return 0;
317 }
318
319 for(c=0;c<=wish_channels;++c)
320 wishlist[c] = NULL;
321 if(len && strcmp(devcopy, "none"))
322 {
323 size_t i=0;
324 wishlist[0] = devcopy;
325 for(c=0;c<wish_channels;++c)
326 {
327 while(devcopy[i] != 0 && devcopy[i] != ',') ++i;
328 debug2("devcopy[%zu]=%i", i, devcopy[i]);
329 if(devcopy[i] == ',')
330 {
331 /* Terminate previous port name, assign next one. */
332 devcopy[i++] = 0;
333 debug2("terminaled wish %i: %s", c, wishlist[c]);
334 if(c+1 < wish_channels)
335 wishlist[c+1] = devcopy+i;
336 }
337 else
338 break;
339 }
340 }
341 if(wishlist[0] == NULL && !AOQUIET)
342 warning("Not connecting up jack ports as requested.");
343
344 ret = real_connect_jack_ports(ao, handle, wishlist);
345 free(devcopy);
346 free(wishlist);
347 return ret;
348 }
349 return 1;
350 }
351
352 static void drain_jack(out123_handle *ao)
353 {
354 jack_handle_t *handle = (jack_handle_t*)ao->userptr;
355
356 debug("drain_jack().");
357
358 do errno = 0;
359 while(sem_trywait(&handle->sem) == 0 || errno == EINTR);
360 /* For some reason, a single byte is reserved by JACK?! */
361 while( handle && handle->alive && handle->rb
362 && jack_ringbuffer_write_space(handle->rb)+1 < handle->rb_size )
363 {
364 debug2( "JACK close wait %zu < %zu\n"
365 , jack_ringbuffer_write_space(handle->rb)
366 , handle->rb_size );
367 sem_wait(&handle->sem);
368 }
369 }
370
371 static int close_jack(out123_handle *ao)
372 {
373 jack_handle_t *handle = (jack_handle_t*)ao->userptr;
374
375 debug("close_jack().");
376 /* Close and shutdown*/
377 if(handle)
378 {
379 free_jack_handle(handle);
380 ao->userptr = NULL;
381 }
382 return 0;
383 }
384
385
386 static int open_jack(out123_handle *ao)
387 {
388 jack_handle_t *handle=NULL;
389 jack_options_t jopt = JackNullOption|JackNoStartServer;
390 jack_status_t jstat = 0;
391 unsigned int i;
392 char *realname;
393
394 debug("jack open");
395 if(!ao)
396 return -1;
397
398 /* Return if already open*/
399 if(ao->userptr)
400 {
401 if(!AOQUIET)
402 error("audio device is already open.");
403 return -1;
404 }
405
406 /* The initial open lets me choose the settings. */
407 if (ao->format==-1)
408 {
409 ao->format = MPG123_ENC_FLOAT_32;
410 ao->channels = 2;
411 /* Really need a framesize defined for callback. */
412 ao->framesize = 2*4;
413 }
414 else if(!(ao->format & MPG123_ENC_FLOAT))
415 {
416 if(!AOQUIET)
417 error("JACK only wants float!");
418 return -1;
419 }
420
421 /* Create some storage for ourselves*/
422 if((handle = alloc_jack_handle(ao)) == NULL)
423 return -1;
424 ao->userptr = (void*)handle;
425
426 /* Register with Jack*/
427 if((handle->client = jack_client_open(ao->name, jopt, &jstat)) == 0)
428 {
429 if(!AOQUIET)
430 error1("Failed to open jack client: 0x%x", jstat);
431 close_jack(ao);
432 return -1;
433 }
434
435 realname = jack_get_client_name(handle->client);
436 /* Display the unique client name allocated to us */
437 if(AOVERBOSE(1))
438 fprintf( stderr, "Registered as JACK client %s.\n"
439 , realname ? realname : "<nil>" );
440
441 /* Just make sure. */
442 ao->rate = jack_get_sample_rate(handle->client);
443
444 /* Check the sample rate is correct*/
445 if (jack_get_sample_rate( handle->client ) != (jack_nframes_t)ao->rate)
446 {
447 if(!AOQUIET)
448 error("JACK Sample Rate is different to sample rate of file.");
449 close_jack(ao);
450 return -1;
451 }
452
453 /* Register ports with Jack*/
454 if(handle->channels > 0 && handle->channels < 100)
455 {
456 for(i=0;i<handle->channels;++i)
457 {
458 char numbuf[3]; /* two digits, zero byte */
459 sprintf(numbuf, "%d", i+1);
460 if( !(handle->ports[i] = jack_port_register( handle->client
461 , numbuf, JACK_DEFAULT_AUDIO_TYPE
462 , JackPortIsOutput, 0 )) )
463 {
464 if(!AOQUIET)
465 error1("Cannot register JACK output port '%s'.", numbuf);
466 close_jack(ao);
467 return -1;
468 }
469 }
470 }
471 else
472 {
473 if(!AOQUIET)
474 error1("excessive number of output channels (%d).", handle->channels);
475 close_jack(ao);
476 return -1;
477 }
478
479 /* Use device_buffer parameter for ring buffer, but ensure that two
480 JACK buffers fit in there. We do not support that buffer increasing
481 later on. */
482 handle->rb_size = (size_t)( ao->device_buffer
483 * jack_get_sample_rate(handle->client)
484 + 0.5 ); /* PCM frames */
485 handle->procbuf_frames = jack_get_buffer_size(handle->client);
486 if(handle->rb_size < 2*handle->procbuf_frames)
487 handle->rb_size = 2*handle->procbuf_frames;
488 debug1("JACK ringbuffer for %zu PCM frames", handle->rb_size);
489 /* Convert to bytes. */
490 handle->rb_size *= handle->framesize;
491 handle->rb = jack_ringbuffer_create(handle->rb_size);
492 handle->procbuf = malloc(handle->procbuf_frames*handle->framesize);
493 if(!handle->rb || !handle->procbuf)
494 {
495 if(!AOQUIET)
496 error("failed to allocate buffers");
497 close_jack(ao);
498 return -1;
499 }
500
501 /* Set the callbacks*/
502 jack_set_process_callback(handle->client, process_callback, (void*)handle);
503 jack_on_shutdown(handle->client, shutdown_callback, (void*)handle);
504 handle->alive = 1;
505 /* Activate client*/
506 if(jack_activate(handle->client))
507 {
508 if(!AOQUIET)
509 error("Can't activate client.");
510 close_jack(ao);
511 return -1;
512 }
513
514 /* Connect up the portsm, return */
515 if(!connect_jack_ports(ao, handle))
516 {
517 /* deregistering of ports will not work but should just fail, then,
518 and let the rest clean up */
519 close_jack(ao);
520 return -1;
521 }
522
523 debug("Jack open successful.\n");
524 ao->realname = INT123_compat_strdup(realname);
525 return 0;
526 }
527
528
529 /* Jack prefers floats, I actually assume it does _only_ float/double
530 (as it is nowadays)! */
531 static int get_formats_jack(out123_handle *ao)
532 {
533 jack_handle_t *handle = (jack_handle_t*)ao->userptr;
534
535 if(jack_get_sample_rate(handle->client) != (jack_nframes_t)ao->rate)
536 return 0;
537 else
538 return MPG123_ENC_FLOAT_32|MPG123_ENC_FLOAT_64;
539 }
540
541 static int write_jack(out123_handle *ao, unsigned char *buf, int len)
542 {
543 jack_handle_t *handle = (jack_handle_t*)ao->userptr;
544 size_t bytes_left;
545 unsigned int strike = 0;
546
547 bytes_left = len;
548 while(bytes_left && handle->alive)
549 {
550 size_t piece;
551
552 debug("writing to ringbuffer");
553 /* No help: piece1 = jack_ringbuffer_write_space(handle->rb); */
554 piece = jack_ringbuffer_write(handle->rb, (char*)buf, bytes_left);
555 debug1("wrote %zu B", piece);
556 buf += piece;
557 bytes_left -= piece;
558 /* Allow nothing being written some times, but not too often.
559 Don't know how often in a row that would be supposed to happen. */
560 if(!piece)
561 {
562 if(++strike > 100)
563 {
564 if(!AOQUIET)
565 error("Cannot write to ringbuffer.");
566 break;
567 }
568 /* Avoid busy waiting and semaphore accumulation:
569 Wait once on the semaphore, then clear it. We count on it being
570 posted by the process callback and we are going to push new data
571 so that that one gets the chance. */
572 sem_wait(&handle->sem);
573 do errno = 0;
574 while(sem_trywait(&handle->sem) == 0 || errno == EINTR);
575 }
576 else
577 strike = 0;
578 }
579
580 return len-bytes_left;
581 }
582
583 static void flush_jack(out123_handle *ao)
584 {
585 jack_handle_t *handle = (jack_handle_t*)ao->userptr;
586 /* Reset the ring buffers*/
587 jack_ringbuffer_reset(handle->rb);
588 }
589
590 static int init_jack(out123_handle* ao)
591 {
592 if (ao==NULL)
593 return -1;
594 /* Set callbacks */
595 ao->open = open_jack;
596 ao->flush = flush_jack;
597 ao->drain = drain_jack;
598 ao->write = write_jack;
599 ao->get_formats = get_formats_jack;
600 ao->close = close_jack;
601 ao->propflags |= OUT123_PROP_PERSISTENT;
602 /* Success */
603 return 0;
604 }
605
606 /*
607 Module information data structure
608 */
609 mpg123_module_t mpg123_output_module_info = {
610 /* api_version */ MPG123_MODULE_API_VERSION,
611 /* name */ "jack",
612 /* description */ "Output audio using JACK (JACK Audio Connection Kit).",
613 /* revision */ "$Rev:$",
614 /* handle */ NULL,
615
616 /* init_output */ init_jack
617 };