1 /* sound-jack.c - play a sound over the Jack Audio Server
3 Copyright (C) 2006 Sebastian Freundt
5 This file is part of SXEmacs
7 SXEmacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 SXEmacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
21 /* Synched up with: Not in FSF. */
36 #include "sound-jack.h"
40 #define MYSELF ADRIVER_JACK
41 #define SAMPLE_MAX_32BIT 2147483647.0f
42 #define SAMPLE_MAX_24BIT 8388607.0f
43 #define SAMPLE_MAX_16BIT 32767.0f
44 #define SAMPLE_MAX_8BIT 255.0f
46 static JMP_BUF jack_server_sig;
47 static int sound_jack_process(jack_nframes_t, void*);
48 static void sound_jack_shutdown_cbfun(void*);
49 static void sound_jack_error(const char*);
50 static void sound_jack_silence(float**, int, sound_jack_aj_data_t*);
51 static int sound_jack_write(float**, jack_nframes_t, audio_job_t);
52 static size_t demux_internal();
54 #define __JACK_DEBUG__(args...) fprintf(stderr, "JACK " args)
55 #ifndef JACK_DEBUG_FLAG
56 #define JACK_DEBUG(args...)
58 #define JACK_DEBUG(args...) __JACK_DEBUG__(args)
60 #define JACK_DEBUG_S(args...) JACK_DEBUG("[stream]: " args)
61 #define JACK_DEBUG_AJ(args...) JACK_DEBUG("[audio-job]: " args)
62 #define JACK_CRITICAL(args...) __JACK_DEBUG__("CRITICAL: " args)
65 DECLARE_AUDIO_DEVICE_SIMPLE_METHS(sound_jack);
66 DEFINE_AUDIO_DEVICE_SIMPLE(sound_jack);
70 sound_jack_mark(ad_device_data *devdata)
72 sound_jack_data_t *sjd = devdata;
74 mark_object(sjd->options);
75 mark_object(sjd->server);
81 sound_jack_print(Lisp_Object device, Lisp_Object pcfun, int ef)
83 sound_jack_data_t *sjd = NULL;
85 sjd = get_audio_device_data(device);
86 /* cannot use incomplete or corrupt audio devices */
87 if (XAUDIO_DEVICE_DRIVER(device) != MYSELF || sjd == NULL) {
88 write_c_string(" VOID", pcfun);
89 /* now that we are here, mark AO device as dead */
90 XAUDIO_DEVICE_STATE(device) = ASTATE_DEAD;
94 /* info about the connected output plugin */
95 write_c_string(" :server ", pcfun);
96 if (NILP(sjd->server))
97 write_c_string("#default", pcfun);
99 print_internal(sjd->server, pcfun, ef);
101 write_c_string(" :client ", pcfun);
102 if (NILP(sjd->client))
103 write_c_string("SXEmacs", pcfun);
105 print_internal(sjd->client, pcfun, ef);
111 static ad_device_data *
112 sound_jack_create(Lisp_Object jack_options)
115 sound_jack_data_t *sjd = NULL;
116 /* option keywords */
117 Lisp_Object opt_server = Qnil;
118 Lisp_Object opt_client = Qnil;
121 opt_server = Fplist_get(jack_options, intern(":server"), Qnil);
122 if (!NILP(opt_server) && !STRINGP(opt_server)) {
123 wrong_type_argument(Qstringp, opt_server);
127 opt_client = Fplist_get(jack_options, intern(":client"), Qnil);
128 if (!NILP(opt_client) && !STRINGP(opt_client)) {
129 wrong_type_argument(Qstringp, opt_client);
133 /* initialise and fill */
134 sjd = xnew_and_zero(sound_jack_data_t);
135 sjd->options = jack_options;
136 sjd->server = opt_server;
137 sjd->client = opt_client;
140 return (ad_device_data*)sjd;
144 sound_jack_finish(ad_device_data *data)
146 sound_jack_data_t *sjd = data;
155 static ad_device_data *
156 sound_jack_subthread_create(void)
159 sound_jack_aj_data_t *sjsd = NULL;
161 jack_client_t *client = NULL;
163 const char **ports = NULL;
166 /* Create a new playback client */
167 client = jack_client_open("SXEmacs", 0, NULL);
169 message(GETTEXT("audio-jack: "
170 "cannot open server."));
174 /* initialise and fill */
175 sjsd = xnew_and_zero(sound_jack_aj_data_t);
176 sjsd->client = client;
178 /* list matching ports */
179 port_flags |= JackPortIsInput;
180 port_flags |= JackPortIsPhysical;
181 ports = jack_get_ports(client, NULL, NULL, port_flags);
182 for (sjsd->num_ports = 0; ports && ports[sjsd->num_ports];
183 sjsd->num_ports++); /* just count */
184 if (!sjsd->num_ports) {
185 message(GETTEXT("audio-jack: "
186 "no physical ports available."));
191 JACK_DEBUG("initialised %d ports\n", sjsd->num_ports);
193 /* if (mtap->channels > sjsd->num_ports); */
195 /* create out output ports */
196 for (i = 0; i < sjsd->num_ports; i++) {
198 int sz = snprintf(pname, sizeof(pname), "SXEmacs out_%d", i);
199 assert(sz>=0 && sz<sizeof(pname));
200 sjsd->ports[i] = jack_port_register(
202 JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0);
203 if (!sjsd->ports[i]) {
204 message(GETTEXT("audio-jack: "
205 "not enough ports available."));
211 sjsd->port_ptrs = ports;
213 return (ad_device_data*)sjsd;
217 sound_jack_play(audio_job_t aj)
220 mtype_audio_properties *mtap;
221 Lisp_Media_Stream *ms;
222 media_substream *mss;
225 Lisp_Audio_Device *lad = NULL;
226 sound_jack_data_t *sjd = NULL;
227 sound_jack_aj_data_t *sjsd = NULL;
230 SOUND_UNPACK_MT(aj, device, ms, mss, lad, sjd, mtap);
232 /* get jack device */
233 JACK_DEBUG("creating subthread.\n");
234 if ((sjsd = sound_jack_subthread_create()) == NULL) {
235 message(GETTEXT("audio-jack: "
236 "cannot create connection to jack server."));
240 /* initialise our callback semaphore */
241 SXE_SEMAPH_INIT(&(sjsd->sem));
243 if (SETJMP(jack_server_sig)) {
244 JACK_CRITICAL("Caught a lethal signal.\n");
247 GETTEXT("Jack daemon died or "
248 "send us a lethal signal! "
249 "This instance might have become a total mess! "
250 "Consider a restart."));
254 /* rewind the stream */
255 media_stream_meth(ms, rewind)(mss);
256 SXE_MUTEX_LOCK(&aj->mtx);
257 aj->buffer = xmalloc_atomic(SOUND_MAX_AUDIO_FRAME_SIZE);
258 aj->buffer_alloc_size = SOUND_MAX_AUDIO_FRAME_SIZE;
259 aj->resolution = (mtap->samplerate * MTPSTATE_REACT_TIME) / 1000000;
261 audio_job_device_data(aj) = sjsd;
262 sjsd->samplerate = mtap->samplerate;
263 sjsd->framesize = (sjsd->channels = mtap->channels) * sizeof(int32_t);
264 sjsd->demux_fun = demux_internal;
266 sjsd->ringbufcnt = SOUND_MAX_AUDIO_FRAME_SIZE >> 10;
267 sjsd->readpos = sjsd->writepos = sjsd->overfill = 0;
268 SXE_MUTEX_UNLOCK(&aj->mtx);
270 JACK_DEBUG("setting callback.\n");
271 jack_set_process_callback(sjsd->client, sound_jack_process, aj);
272 jack_set_error_function(sound_jack_error);
273 jack_on_shutdown(sjsd->client, sound_jack_shutdown_cbfun, aj);
276 if (jack_activate(sjsd->client)) {
277 message(GETTEXT("audio-jack: "
278 "activate failed."));
282 for (i = 0; i < sjsd->num_ports; i++) {
283 if (jack_connect(sjsd->client,
284 jack_port_name(sjsd->ports[i]),
285 sjsd->port_ptrs[i])) {
286 message(GETTEXT("audio-jack: "
287 "connecting failed."));
292 JACK_DEBUG("SEMAPHORE WAIT: 0x%x@0x%x@0x%x\n",
293 (unsigned int)sem, (unsigned int)sjsd, (unsigned int)aj);
294 SXE_SEMAPH_SYNCH(&(sjsd->sem));
296 /* close and shutdown */
298 JACK_DEBUG("finish.\n");
300 jack_client_t *cli = sjsd->client;
301 JACK_DEBUG("DISC.\n");
303 for (i = 0; i < sjsd->num_ports; i++) {
305 jack_port_name(sjsd->ports[i]),
308 JACK_DEBUG("CLOSE.\n");
309 jack_client_close(cli);
312 SXE_SEMAPH_FINI(&(sjsd->sem));
314 SXE_MUTEX_LOCK(&aj->mtx);
323 aj->state = MTSTATE_FINISHED;
324 SXE_MUTEX_UNLOCK(&aj->mtx);
330 /* pull one channel out of a multi-channel stream */
332 demux_internal(float *dst, char *src,
333 size_t n, int chan, sound_jack_aj_data_t *f)
335 /* dst: destination buffer */
336 /* src: source buffer */
337 /* n: number of samples */
338 /* chan: channel to frob */
339 int off = sizeof(int32_t)*chan;
340 int sr = f->samplerate;
341 int fs = f->framesize;
343 for (sxe_index_t i = 0; i < n; i++) {
344 /* compute frame number to serve */
345 int frame = i * sr/48000 * f->ratetrafo;
346 int srcp = frame*fs + off;
347 dst[i] = ((float)(*(int32_t*)(src+srcp)) / SAMPLE_MAX_24BIT)
351 /* actually read frames were n * samplerate / 48000 */
352 return n * sr/48000 * f->ratetrafo;
359 sound_jack_error(const char *errmsg)
361 JACK_CRITICAL("Strange things happened.\n"
362 "Error message: %s\n",
365 LONGJMP(jack_server_sig, 1);
370 /* shutdown callback */
372 sound_jack_shutdown_cbfun(void *arg)
374 JACK_CRITICAL("Shutdown: %p\n", arg);
376 LONGJMP(jack_server_sig, 1);
383 sound_jack_change_volume(audio_job_t aj, audio_job_event_args_t args)
385 SXE_MUTEX_LOCK(&aj->mtx);
386 aj->volume = args->volume_args;
387 SXE_MUTEX_UNLOCK(&aj->mtx);
391 sound_jack_change_rate(audio_job_t aj, audio_job_event_args_t args)
393 SXE_MUTEX_LOCK(&aj->mtx);
394 aj->ratetrafo = args->rate_args;
395 SXE_MUTEX_UNLOCK(&aj->mtx);
399 sound_jack_change_state(audio_job_t aj, audio_job_event_args_t args)
401 SXE_MUTEX_LOCK(&aj->mtx);
402 switch (args->state_args) {
404 JACK_DEBUG_AJ("->pause state\n");
405 aj->play_state = MTPSTATE_PAUSE;
408 JACK_DEBUG_AJ("->resume state\n");
409 aj->play_state = MTPSTATE_RUN;
412 JACK_DEBUG_AJ("->start state\n");
415 JACK_DEBUG_AJ("->stop state\n");
416 aj->play_state = MTPSTATE_STOP;
419 case no_audio_job_change_states:
421 JACK_DEBUG_AJ("->unknown state\n");
424 SXE_MUTEX_UNLOCK(&aj->mtx);
428 sound_jack_handle_aj_events(audio_job_t aj)
429 __attribute__((always_inline));
431 sound_jack_handle_aj_events(audio_job_t aj)
433 sound_jack_aj_data_t *sasd;
434 audio_job_event_t ev = NULL;
437 assert(audio_job_queue(aj));
440 SXE_MUTEX_LOCK(&aj->mtx);
441 sasd = audio_job_device_data(aj);
442 if ((ev = eq_noseeum_dequeue(audio_job_queue(aj))) == NULL) {
443 SXE_MUTEX_UNLOCK(&aj->mtx);
446 SXE_MUTEX_UNLOCK(&aj->mtx);
448 JACK_DEBUG_AJ("Event 0x%lx\n", (long unsigned int)ev);
449 switch (audio_job_event_kind(ev)) {
450 case aj_change_state:
451 JACK_DEBUG_AJ("change state event\n");
452 sound_jack_change_state(aj, &audio_job_event_args(ev));
454 case aj_change_volume:
455 JACK_DEBUG_AJ("change volume event\n");
456 sound_jack_change_volume(aj, &audio_job_event_args(ev));
459 JACK_DEBUG_AJ("change rate event\n");
460 sound_jack_change_rate(aj, &audio_job_event_args(ev));
463 case no_audio_job_event_kinds:
465 JACK_CRITICAL("unknown event\n");
468 free_audio_job_event(ev);
470 #endif /* EF_USE_ASYNEQ */
473 * JACK Callback function
474 * - nframes number of frames to fill into buffers
475 * - arg contains the media subthread to operate on
478 sound_jack_process(jack_nframes_t nframes, void *userdata)
480 audio_job_t aj = NULL;
481 sound_jack_aj_data_t *sjsd = NULL;
482 media_substream *mss = NULL;
484 media_thread_play_state mtp;
485 float *bufs[MAX_CHANS];
490 sjsd = audio_job_device_data(aj);
494 /* stuff on the event queue? */
495 if (audio_job_queue(aj)) {
496 sound_jack_handle_aj_events(aj);
500 /* Set the playback volume of the stream */
501 if ((curvol = aj->volume) != sjsd->volume) {
502 sjsd->fvol = (float)curvol / MEDIA_SAMPLE_VOLUME_NORM;
503 sjsd->volume = curvol;
506 if (aj->ratetrafo != sjsd->ratetrafo) {
507 sjsd->ratetrafo = aj->ratetrafo;
510 for (int i = 0; i < sjsd->num_ports; i++) {
511 bufs[i] = jack_port_get_buffer(sjsd->ports[i], nframes);
514 mtp = aj->play_state;
517 sound_jack_write(bufs, nframes, aj);
520 sound_jack_silence(bufs, nframes, sjsd);
523 case MTPSTATE_UNKNOWN:
525 case NUMBER_OF_MEDIA_THREAD_PLAY_STATES:
527 JACK_DEBUG_S("DRAIN.\n");
528 SXE_SEMAPH_TRIGGER(&(sjsd->sem));
535 * fill the buffers with silence
536 * - bufs num_bufs float buffers, each will contain the data of one channel
537 * - cnt number of samples in each buffer
538 * - num_bufs number of buffers
541 sound_jack_silence(float **bufs, int cnt, sound_jack_aj_data_t *sjsd)
544 for (i = 0; i < cnt; i++)
545 for (j = 0; j < sjsd->num_ports; j++)
550 sound_jack_write(float **bufs, jack_nframes_t nframes, audio_job_t aj)
552 sound_jack_aj_data_t *sjsd = audio_job_device_data(aj);
553 size_t len = 0, tmplen = 0, tmpcnt = 0;
554 sound_jack_demux_fun dmx = sjsd->demux_fun;
555 ms_read_fun __read = media_stream_meth(aj->substream->up, read);
557 /* cleanup buffer, move the frame overfill to the beginning */
558 if (sjsd->writepos < aj->buffer_alloc_size >> 1 &&
559 sjsd->underrun < 4) {
560 memcpy(aj->buffer, aj->buffer+sjsd->readpos,
561 sjsd->writepos - sjsd->readpos);
562 sjsd->writepos -= sjsd->readpos;
565 len = __read(aj->substream, aj->buffer+sjsd->writepos, nframes);
570 sjsd->overfill += len;
571 sjsd->writepos += len*sjsd->framesize;
573 /* increase underrun counter to detect the end */
576 } else if (sjsd->overfill > nframes << 2 ||
577 sjsd->underrun >= 4) {
578 JACK_DEBUG("having a rest\n");
580 JACK_DEBUG("resetting write position.\n");
581 memcpy(aj->buffer, aj->buffer+sjsd->readpos,
582 sjsd->writepos - sjsd->readpos);
583 sjsd->writepos -= sjsd->readpos;
587 JACK_DEBUG_S("req:%d p, got:%d p, readpos %d, writepos %d, "
588 "overfill: %d, framesize: %d, sr: %d\n",
589 nframes, len, sjsd->readpos, sjsd->writepos,
590 sjsd->overfill, sjsd->framesize, sjsd->samplerate);
592 /* care for buffer underruns */
593 if (nframes > sjsd->overfill)
594 tmplen = sjsd->overfill;
598 /* output, i loops over the number of ports we have to fill,
599 * while j loops over the actual channels */
600 for (int i = 0, j = 0; i < sjsd->num_ports; i++) {
602 bufs[i], aj->buffer+sjsd->readpos, tmplen, j, sjsd);
603 if (j < sjsd->channels) {
607 /* fill the rest with silence */
608 tmplen = nframes - tmplen;
610 JACK_DEBUG_S("fill up with silence\n");
611 sound_jack_silence(bufs, tmplen, sjsd);
614 /* modify readposition and overfill */
615 sjsd->readpos += tmpcnt * sjsd->framesize;
616 sjsd->overfill -= tmpcnt;
618 /* detect end of track */
619 if (sjsd->underrun >= 4 && sjsd->overfill < 64)
620 aj->play_state = MTPSTATE_STOP;
628 /* sound-jack.c ends here */