1 /*
2     TiMidity++ -- MIDI to WAVE converter and player
3     Copyright (C) 1999-2002 Masanao Izumo <mo@goice.co.jp>
4     Copyright (C) 1995 Tuukka Toivonen <tt@cgs.fi>
5 
6     jack_a.c - Copyright (C) 2003 Takashi Iwai <tiwai@suse.de>
7 
8     This program is free software; you can redistribute it and/or modify
9     it under the terms of the GNU General Public License as published by
10     the Free Software Foundation; either version 2 of the License, or
11     (at your option) any later version.
12 
13     This program is distributed in the hope that it will be useful,
14     but WITHOUT ANY WARRANTY; without even the implied warranty of
15     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16     GNU General Public License for more details.
17 
18     You should have received a copy of the GNU General Public License
19     along with this program; if not, write to the Free Software
20     Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21 
22     jack_a.c
23 
24     Functions to play sound on the JACK system
25 
26 
27     Since the model of JACK (so-called "pull" model) doesn't match
28     with the current model of TiMidity ("push" model), this audio
29     driver is implemented with another intermediate ring buffer.
30 
31     The audio data from timidity (S16 or U8 PCM) is converted to
32     JACK audio stream(s) in float and stored once on the ring buffer,
33     which is read eventually in the client's process callback and
34     copied to the JACK buffers.  Note that this buffer is independent
35     from the audio-queue.  (Yes, it's re-invention of wheels, but we
36     cannot handle dynamic memory allocation in JACK's process thread.)
37 
38     The buffer size options (-B) specify the size of the ring buffer.
39     To get the best perfomance, you'll need to set up them to match
40     with the parameter of JACK server.
41 
42 */
43 
44 #ifdef HAVE_CONFIG_H
45 #include "config.h"
46 #endif /* HAVE_CONFIG_H */
47 
48 #include <stdio.h>
49 #include <stdlib.h>
50 #ifdef HAVE_UNISTD_H
51 #include <unistd.h>
52 #endif
53 
54 #ifndef NO_STRING_H /* for memmove */
55 #include <string.h>
56 #else
57 #include <strings.h>
58 #endif
59 
60 #include <jack/jack.h>
61 
62 #include "timidity.h"
63 #include "common.h"
64 #include "output.h"
65 #include "controls.h"
66 #include "timer.h"
67 #include "instrum.h"
68 #include "playmidi.h"
69 #include "miditrace.h"
70 
71 /*
72  */
73 static int open_jack(void);
74 static void close_jack(void);
75 static int write_jack(char *buf, int32 nbytes);
76 static int actl_jack(int request, void *arg);
77 static int detect(void);
78 
79 
80 /*
81  */
82 
83 #define dpm jack_play_mode
84 
85 PlayMode dpm = {
86 	DEFAULT_RATE,
87 	PE_16BIT|PE_SIGNED,
88 	PF_PCM_STREAM|PF_CAN_TRACE|PF_BUFF_FRAGM_OPT,
89 	-1,
90 	{0},
91 	"JACK device", 'j',
92 	NULL,
93 	open_jack,
94 	close_jack,
95 	write_jack,
96 	actl_jack,
97 	detect
98 };
99 
100 /*
101  * simple ring-buffer
102  */
103 
104 struct tm_ringbuf {
105 	long rdptr, wrptr;	/* read, write pointers (not bound in ringbuffer size!) */
106 	int size;		/* ring buffer size */
107 	jack_default_audio_sample_t *buf[2];	/* left, right buffers */
108 };
109 
ringbuf_init(struct tm_ringbuf * rbuf,int size,int channels)110 static void ringbuf_init(struct tm_ringbuf *rbuf, int size, int channels)
111 {
112 	int i;
113 
114 	memset(rbuf, 0, sizeof(*rbuf));
115 	rbuf->size = size;
116 	for (i = 0; i < channels; i++)
117 		rbuf->buf[i] = (jack_default_audio_sample_t *)safe_malloc(sizeof(jack_default_audio_sample_t) * size);
118 	rbuf->rdptr = rbuf->wrptr = 0;
119 }
120 
ringbuf_destroy(struct tm_ringbuf * rbuf)121 static void ringbuf_destroy(struct tm_ringbuf *rbuf)
122 {
123 	int i;
124 	for (i = 0; i < 2; i++) {
125 		free(rbuf->buf[i]);
126 		rbuf->buf[i] = NULL;
127 	}
128 	rbuf->rdptr = rbuf->wrptr = 0;
129 }
130 
131 /* get avaialble samples for read */
ringbuf_get_available(struct tm_ringbuf * rbuf)132 inline static int ringbuf_get_available(struct tm_ringbuf *rbuf)
133 {
134 	return rbuf->wrptr - rbuf->rdptr;
135 }
136 
137 /* get empty sample spaces for write */
ringbuf_get_empty(struct tm_ringbuf * rbuf)138 inline static int ringbuf_get_empty(struct tm_ringbuf *rbuf)
139 {
140 	return rbuf->size - ringbuf_get_available(rbuf);
141 }
142 
ringbuf_bound_readable(struct tm_ringbuf * rbuf,int size)143 static int ringbuf_bound_readable(struct tm_ringbuf *rbuf, int size)
144 {
145 	int rdptr = rbuf->rdptr % rbuf->size;
146 	if (rdptr + size >= rbuf->size)
147 		size = rbuf->size - rdptr;
148 	return size;
149 }
150 
151 inline static jack_default_audio_sample_t *
ringbuf_get_readbuf(struct tm_ringbuf * rbuf,int c)152 ringbuf_get_readbuf(struct tm_ringbuf *rbuf, int c)
153 {
154 	return rbuf->buf[c] + (rbuf->rdptr % rbuf->size);
155 }
156 
ringbuf_read_advance(struct tm_ringbuf * rbuf,int size)157 inline static void ringbuf_read_advance(struct tm_ringbuf *rbuf, int size)
158 {
159 	rbuf->rdptr += size;
160 }
161 
ringbuf_bound_writable(struct tm_ringbuf * rbuf,int size)162 static int ringbuf_bound_writable(struct tm_ringbuf *rbuf, int size)
163 {
164 	int wrptr = rbuf->wrptr % rbuf->size;
165 	if (wrptr + size >= rbuf->size)
166 		size = rbuf->size - wrptr;
167 	return size;
168 }
169 
170 inline static jack_default_audio_sample_t *
ringbuf_get_writebuf(struct tm_ringbuf * rbuf,int c)171 ringbuf_get_writebuf(struct tm_ringbuf *rbuf, int c)
172 {
173 	return rbuf->buf[c] + (rbuf->wrptr % rbuf->size);
174 }
175 
ringbuf_write_advance(struct tm_ringbuf * rbuf,int size)176 inline static void ringbuf_write_advance(struct tm_ringbuf *rbuf, int size)
177 {
178 	rbuf->wrptr += size;
179 }
180 
ringbuf_clear(struct tm_ringbuf * rbuf)181 inline static void ringbuf_clear(struct tm_ringbuf *rbuf)
182 {
183 	rbuf->wrptr = rbuf->rdptr = 0;
184 }
185 
186 
187 /*
188  * jack control context
189  */
190 struct tm_jack {
191 	jack_client_t *client;
192 	jack_port_t *ports[2];
193 
194 	int channels;		/* number of channels */
195 	int sample_16bit;	/* 16bit sample */
196 	int shift;		/* sample bit shift */
197 	int frag_size;		/* buffer fragment size (in samples) */
198 	int frags;		/* buffer fragments */
199 
200 	pthread_cond_t cond;
201 	pthread_mutex_t lock;
202 	int running;
203 	int shutdown;
204 
205 	struct tm_ringbuf rbuf;
206 };
207 
208 
209 /*
210  * jack process callback.
211  * here we only copy the stream data from the ring buffer.
212  */
213 
transfer_callback(jack_nframes_t nframes,void * arg)214 static int transfer_callback(jack_nframes_t nframes, void *arg)
215 {
216 	struct tm_jack *ctx = (struct tm_jack *)arg;
217 	int i;
218 	int size;
219 	jack_default_audio_sample_t *outbuf[2];
220 
221 	for (i = 0; i < ctx->channels; i++)
222 		outbuf[i] = (jack_default_audio_sample_t *)jack_port_get_buffer(ctx->ports[i], nframes);
223 
224 	if (! ctx->running) {
225 		/* not running yet, set silence and quit */
226 		for (i = 0; i < ctx->channels; i++)
227 			memset(outbuf[i], 0, sizeof(jack_default_audio_sample_t) * nframes);
228 		return 0;
229 	}
230 
231 	size = ringbuf_get_available(&ctx->rbuf);
232 	if (size > nframes)
233 		size = nframes;
234 
235 	while (size > 0) {
236 		int size1 = ringbuf_bound_readable(&ctx->rbuf, size);
237 		for (i = 0; i < ctx->channels; i++) {
238 			memcpy(outbuf[i], ringbuf_get_readbuf(&ctx->rbuf, i),
239 			       size1 * sizeof(jack_default_audio_sample_t));
240 			outbuf[i] += size1;
241 		}
242 		ringbuf_read_advance(&ctx->rbuf, size1);
243 		size -= size1;
244 	}
245 	/* wake up the main thread */
246 	pthread_cond_signal(&ctx->cond);
247 	return 0;
248 }
249 
shutdown_callback(void * arg)250 static void shutdown_callback(void *arg)
251 {
252 	struct tm_jack *ctx = (struct tm_jack *)arg;
253 	if (! ctx->shutdown)
254 		safe_exit(1);
255 }
256 
257 
258 /*
259  */
260 
261 static struct tm_jack jack_ctx;
262 
263 #define TIMIDITY_JACK_CLIENT_NAME	"TiMidity"
264 #define TIMIDITY_JACK_PORT_NAME		"port_%d"
265 
detect(void)266 static int detect(void)
267 {
268 	jack_client_t *client;
269 	client = jack_client_new(TIMIDITY_JACK_CLIENT_NAME);
270 	if (! client)
271 		return 0;
272 	jack_client_close(client);
273 	return 1; /* found */
274 }
275 
open_jack(void)276 static int open_jack(void)
277 {
278 	int i, rate;
279 	int ret_val = 0;
280 	struct tm_jack *ctx = &jack_ctx;
281 	const char **dst_ports;
282 
283 	memset(ctx, 0, sizeof(*ctx));
284 
285 	ctx->client = jack_client_new(TIMIDITY_JACK_CLIENT_NAME);
286 	if (! ctx->client)
287 		return -1;
288 
289 	jack_set_process_callback(ctx->client, transfer_callback, ctx);
290 	jack_on_shutdown(ctx->client, shutdown_callback, ctx);
291 
292 	dpm.encoding &= ~(PE_ULAW|PE_ALAW|PE_BYTESWAP);
293 	/* check channels */
294 	if (dpm.encoding & PE_MONO)
295 		ctx->channels = 1;
296 	else
297 		ctx->channels = 2;
298 
299 	/* sample bit check */
300 	ctx->sample_16bit = (dpm.encoding & PE_16BIT) ? 1 : 0;
301 	if (ctx->sample_16bit)
302 		dpm.encoding |= PE_SIGNED; /* S16 only */
303 	else
304 		dpm.encoding &= ~PE_SIGNED; /* U8 only */
305 
306 	/* check sample bit shift */
307 	ctx->shift = 0;
308 	if (ctx->channels > 1)
309 		ctx->shift++;
310 	if (ctx->sample_16bit)
311 		ctx->shift++;
312 
313 	for (i = 0; i < ctx->channels; i++) {
314 		char name[32];
315 		sprintf(name, TIMIDITY_JACK_PORT_NAME, i + 1);
316 		ctx->ports[i] = jack_port_register(ctx->client, name,
317 						   JACK_DEFAULT_AUDIO_TYPE,
318 						   JackPortIsOutput, 0);
319 		if (! ctx->ports[i]) {
320 			ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
321 				  "Cannot register a JACK port '%s'", name);
322 			jack_client_close(ctx->client);
323 			return -1;
324 		}
325 	}
326 
327 	/* check the sample rate.
328 	 * if not match, correct the rate
329 	 */
330 	rate = jack_get_sample_rate(ctx->client);
331 	if (rate != dpm.rate) {
332 		dpm.rate = rate;
333 		ret_val = 1;
334 	}
335 
336 	/* get the buffer sizes */
337 	if (dpm.extra_param[1] != 0)
338 		ctx->frag_size = dpm.extra_param[1];
339 	else
340 		ctx->frag_size = audio_buffer_size;
341 	if (dpm.extra_param[0] == 0)
342 		ctx->frags = 2;
343 	else
344 		ctx->frags = dpm.extra_param[0];
345 
346 	/* initialize rest stuffs */
347 	pthread_cond_init(&ctx->cond, NULL);
348 	pthread_mutex_init(&ctx->lock, NULL);
349 	ringbuf_init(&ctx->rbuf, ctx->frag_size * ctx->frags, ctx->channels);
350 	ctx->running = 0;
351 
352 	/* rock it baby */
353 	if (jack_activate(ctx->client) < 0) {
354 		ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "Cannot activate JACK engine");
355 		jack_client_close(ctx->client);
356 		ctx->client = NULL;
357 		return -1;
358 	}
359 
360 	/*
361 	 * it seems the JACK port connection must be done after
362 	 * activating jack client...
363 	 */
364 	/* detect destination ports */
365 	dst_ports = jack_get_ports(ctx->client, NULL, NULL,
366 				   JackPortIsInput|JackPortIsPhysical);
367 	if (dst_ports) {
368 		/* connect them */
369 		for (i = 0; dst_ports[i] && i < ctx->channels; i++) {
370 			if (jack_connect(ctx->client, jack_port_name(ctx->ports[i]), dst_ports[i]))
371 				break;
372 		}
373 		free(dst_ports);
374 	}
375 
376 	return ret_val;
377 }
378 
379 /*
380  * close callback
381  */
close_jack(void)382 static void close_jack(void)
383 {
384 	struct tm_jack *ctx = &jack_ctx;
385 	if (ctx->client) {
386 		ctx->shutdown = 1;
387 		ctx->running = 0;
388 		jack_deactivate(ctx->client);
389 		sleep(2);
390 		jack_client_close(ctx->client);
391 		sleep(2);
392 		ringbuf_destroy(&ctx->rbuf);
393 		pthread_cond_destroy(&ctx->cond);
394 	}
395 }
396 
397 /*
398  * convert 16bit PCM to JACK float [-1,1]
399  */
convert_stream_16(struct tm_jack * ctx,int c,int size,short * buf)400 static void convert_stream_16(struct tm_jack *ctx, int c, int size, short *buf)
401 {
402 	int i;
403 	jack_default_audio_sample_t *inbuf = ringbuf_get_writebuf(&ctx->rbuf, c);
404 	for (i = 0; i < size; i++, buf += ctx->channels, inbuf++) {
405 		/* well, we can use ftol() in C99 but here let's leave
406 		 * the optimization for the compiler...
407 		 */
408 		jack_default_audio_sample_t val;
409 		val = (jack_default_audio_sample_t)*buf / 32768.0;
410 		*inbuf = val;
411 	}
412 }
413 
414 /*
415  * convert 8bit PCM to JACK float [-1,1]
416  */
convert_stream_8(struct tm_jack * ctx,int c,int size,char * buf)417 static void convert_stream_8(struct tm_jack *ctx, int c, int size, char *buf)
418 {
419 	int i;
420 	jack_default_audio_sample_t *inbuf = ringbuf_get_writebuf(&ctx->rbuf, c);
421 	for (i = 0; i < size; i++, buf += ctx->channels, inbuf++) {
422 		signed char cval = *buf ^ 0x80; /* to signed char */
423 		*inbuf = (jack_default_audio_sample_t)cval / 128.0;
424 	}
425 }
426 
427 /*
428  * write callback
429  */
write_jack(char * buf,int32 nbytes)430 static int write_jack(char *buf, int32 nbytes)
431 {
432 	struct tm_jack *ctx = &jack_ctx;
433 	int nframes;
434 	int i;
435 
436 	nframes = nbytes >> ctx->shift;
437 	if (nframes <= 0)
438 		return 0;
439 
440 	for (;;) {
441 		int size = ringbuf_get_empty(&ctx->rbuf);
442 		if (size > nframes)
443 			size = nframes;
444 		while (size > 0) {
445 			int size1 = ringbuf_bound_writable(&ctx->rbuf, size);
446 			if (ctx->sample_16bit) {
447 				short *sbuf = (short *)buf;
448 				for (i = 0; i < ctx->channels; i++, sbuf++)
449 					convert_stream_16(ctx, i, size1, sbuf);
450 			} else {
451 				char *sbuf = (char *)buf;
452 				for (i = 0; i < ctx->channels; i++, sbuf++)
453 					convert_stream_8(ctx, i, size1, sbuf);
454 			}
455 			ringbuf_write_advance(&ctx->rbuf, size1);
456 			/* set running flag */
457 			ctx->running = 1;
458 			nframes -= size1;
459 			if (! nframes)
460 				return 0;
461 			buf += size1 << ctx->shift;
462 			size -= size1;
463 		}
464 
465 		/* blocking behavior: sleep until the process thread
466 		 * wakes up...
467 		 */
468 		pthread_cond_wait(&ctx->cond, &ctx->lock);
469 	}
470 }
471 
472 
473 /*
474  * audio control callback
475  */
actl_jack(int request,void * arg)476 static int actl_jack(int request, void *arg)
477 {
478 	struct tm_jack *ctx = &jack_ctx;
479 
480 	switch (request) {
481 	case PM_REQ_GETFRAGSIZ:
482 		if (ctx->frag_size == 0)
483 			return -1;
484 		*((int *)arg) = ctx->frag_size;
485 		return 0;
486 
487 	case PM_REQ_GETQSIZ:
488 		if (ctx->frag_size == -1)
489 			return -1;
490 		*((int *)arg) = ctx->frag_size * ctx->frags;
491 		return 0;
492 
493 	case PM_REQ_GETFILLABLE:
494 		*((int *)arg) = ringbuf_get_empty(&ctx->rbuf);
495 		return 0;
496 
497 	case PM_REQ_GETFILLED:
498 		*((int *)arg) = ringbuf_get_available(&ctx->rbuf);
499 		return 0;
500 
501 	case PM_REQ_GETSAMPLES:
502 		*((int *)arg) = ctx->rbuf.rdptr;
503 		return 0;
504 
505 	case PM_REQ_FLUSH:
506 		if (ctx->running) {
507 			while (ringbuf_get_available(&ctx->rbuf) > 0)
508 				pthread_cond_wait(&ctx->cond, &ctx->lock);
509 		}
510 		/* fallthrough */
511 	case PM_REQ_DISCARD:
512 		ctx->running = 0;
513 		ringbuf_clear(&ctx->rbuf);
514 		return 0;
515 
516 	}
517 	return -1;
518 }
519 
520