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