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 snprintf(pname, 30, "SXEmacs out_%d", i);
199 sjsd->ports[i] = jack_port_register(
201 JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0);
202 if (!sjsd->ports[i]) {
203 message(GETTEXT("audio-jack: "
204 "not enough ports available."));
210 sjsd->port_ptrs = ports;
212 return (ad_device_data*)sjsd;
216 sound_jack_play(audio_job_t aj)
219 mtype_audio_properties *mtap;
220 Lisp_Media_Stream *ms;
221 media_substream *mss;
224 Lisp_Audio_Device *lad = NULL;
225 sound_jack_data_t *sjd = NULL;
226 sound_jack_aj_data_t *sjsd = NULL;
229 SOUND_UNPACK_MT(aj, device, ms, mss, lad, sjd, mtap);
231 /* get jack device */
232 JACK_DEBUG("creating subthread.\n");
233 if ((sjsd = sound_jack_subthread_create()) == NULL) {
234 message(GETTEXT("audio-jack: "
235 "cannot create connection to jack server."));
239 /* initialise our callback semaphore */
240 SXE_SEMAPH_INIT(&(sjsd->sem));
242 if (SETJMP(jack_server_sig)) {
243 JACK_CRITICAL("Caught a lethal signal.\n");
246 GETTEXT("Jack daemon died or "
247 "send us a lethal signal! "
248 "This instance might have become a total mess! "
249 "Consider a restart."));
253 /* rewind the stream */
254 media_stream_meth(ms, rewind)(mss);
255 SXE_MUTEX_LOCK(&aj->mtx);
256 aj->buffer = xmalloc_atomic(SOUND_MAX_AUDIO_FRAME_SIZE);
257 aj->buffer_alloc_size = SOUND_MAX_AUDIO_FRAME_SIZE;
258 aj->resolution = (mtap->samplerate * MTPSTATE_REACT_TIME) / 1000000;
260 audio_job_device_data(aj) = sjsd;
261 sjsd->samplerate = mtap->samplerate;
262 sjsd->framesize = (sjsd->channels = mtap->channels) * sizeof(int32_t);
263 sjsd->demux_fun = demux_internal;
265 sjsd->ringbufcnt = SOUND_MAX_AUDIO_FRAME_SIZE >> 10;
266 sjsd->readpos = sjsd->writepos = sjsd->overfill = 0;
267 SXE_MUTEX_UNLOCK(&aj->mtx);
269 JACK_DEBUG("setting callback.\n");
270 jack_set_process_callback(sjsd->client, sound_jack_process, aj);
271 jack_set_error_function(sound_jack_error);
272 jack_on_shutdown(sjsd->client, sound_jack_shutdown_cbfun, aj);
275 if (jack_activate(sjsd->client)) {
276 message(GETTEXT("audio-jack: "
277 "activate failed."));
281 for (i = 0; i < sjsd->num_ports; i++) {
282 if (jack_connect(sjsd->client,
283 jack_port_name(sjsd->ports[i]),
284 sjsd->port_ptrs[i])) {
285 message(GETTEXT("audio-jack: "
286 "connecting failed."));
291 JACK_DEBUG("SEMAPHORE WAIT: 0x%x@0x%x@0x%x\n",
292 (unsigned int)sem, (unsigned int)sjsd, (unsigned int)aj);
293 SXE_SEMAPH_SYNCH(&(sjsd->sem));
295 /* close and shutdown */
297 JACK_DEBUG("finish.\n");
299 jack_client_t *cli = sjsd->client;
300 JACK_DEBUG("DISC.\n");
302 for (i = 0; i < sjsd->num_ports; i++) {
304 jack_port_name(sjsd->ports[i]),
307 JACK_DEBUG("CLOSE.\n");
308 jack_client_close(cli);
311 SXE_SEMAPH_FINI(&(sjsd->sem));
313 SXE_MUTEX_LOCK(&aj->mtx);
322 aj->state = MTSTATE_FINISHED;
323 SXE_MUTEX_UNLOCK(&aj->mtx);
329 /* pull one channel out of a multi-channel stream */
331 demux_internal(float *dst, char *src,
332 size_t n, int chan, sound_jack_aj_data_t *f)
334 /* dst: destination buffer */
335 /* src: source buffer */
336 /* n: number of samples */
337 /* chan: channel to frob */
338 int off = sizeof(int32_t)*chan;
339 int sr = f->samplerate;
340 int fs = f->framesize;
342 for (sxe_index_t i = 0; i < n; i++) {
343 /* compute frame number to serve */
344 int frame = i * sr/48000 * f->ratetrafo;
345 int srcp = frame*fs + off;
346 dst[i] = ((float)(*(int32_t*)(src+srcp)) / SAMPLE_MAX_24BIT)
350 /* actually read frames were n * samplerate / 48000 */
351 return n * sr/48000 * f->ratetrafo;
358 sound_jack_error(const char *errmsg)
360 JACK_CRITICAL("Strange things happened.\n"
361 "Error message: %s\n",
364 LONGJMP(jack_server_sig, 1);
369 /* shutdown callback */
371 sound_jack_shutdown_cbfun(void *arg)
373 JACK_CRITICAL("Shutdown: 0x%x\n", (unsigned int)arg);
375 LONGJMP(jack_server_sig, 1);
382 sound_jack_change_volume(audio_job_t aj, audio_job_event_args_t args)
384 SXE_MUTEX_LOCK(&aj->mtx);
385 aj->volume = args->volume_args;
386 SXE_MUTEX_UNLOCK(&aj->mtx);
390 sound_jack_change_rate(audio_job_t aj, audio_job_event_args_t args)
392 SXE_MUTEX_LOCK(&aj->mtx);
393 aj->ratetrafo = args->rate_args;
394 SXE_MUTEX_UNLOCK(&aj->mtx);
398 sound_jack_change_state(audio_job_t aj, audio_job_event_args_t args)
400 SXE_MUTEX_LOCK(&aj->mtx);
401 switch (args->state_args) {
403 JACK_DEBUG_AJ("->pause state\n");
404 aj->play_state = MTPSTATE_PAUSE;
407 JACK_DEBUG_AJ("->resume state\n");
408 aj->play_state = MTPSTATE_RUN;
411 JACK_DEBUG_AJ("->start state\n");
414 JACK_DEBUG_AJ("->stop state\n");
415 aj->play_state = MTPSTATE_STOP;
418 case no_audio_job_change_states:
420 JACK_DEBUG_AJ("->unknown state\n");
423 SXE_MUTEX_UNLOCK(&aj->mtx);
427 sound_jack_handle_aj_events(audio_job_t aj)
428 __attribute__((always_inline));
430 sound_jack_handle_aj_events(audio_job_t aj)
432 sound_jack_aj_data_t *sasd;
433 audio_job_event_t ev = NULL;
436 assert(audio_job_queue(aj));
439 SXE_MUTEX_LOCK(&aj->mtx);
440 sasd = audio_job_device_data(aj);
441 if ((ev = eq_noseeum_dequeue(audio_job_queue(aj))) == NULL) {
442 SXE_MUTEX_UNLOCK(&aj->mtx);
445 SXE_MUTEX_UNLOCK(&aj->mtx);
447 JACK_DEBUG_AJ("Event 0x%lx\n", (long unsigned int)ev);
448 switch (audio_job_event_kind(ev)) {
449 case aj_change_state:
450 JACK_DEBUG_AJ("change state event\n");
451 sound_jack_change_state(aj, &audio_job_event_args(ev));
453 case aj_change_volume:
454 JACK_DEBUG_AJ("change volume event\n");
455 sound_jack_change_volume(aj, &audio_job_event_args(ev));
458 JACK_DEBUG_AJ("change rate event\n");
459 sound_jack_change_rate(aj, &audio_job_event_args(ev));
462 case no_audio_job_event_kinds:
464 JACK_CRITICAL("unknown event\n");
467 free_audio_job_event(ev);
469 #endif /* EF_USE_ASYNEQ */
472 * JACK Callback function
473 * - nframes number of frames to fill into buffers
474 * - arg contains the media subthread to operate on
477 sound_jack_process(jack_nframes_t nframes, void *userdata)
479 audio_job_t aj = NULL;
480 sound_jack_aj_data_t *sjsd = NULL;
481 media_substream *mss = NULL;
483 media_thread_play_state mtp;
484 float *bufs[MAX_CHANS];
489 sjsd = audio_job_device_data(aj);
493 /* stuff on the event queue? */
494 if (audio_job_queue(aj)) {
495 sound_jack_handle_aj_events(aj);
499 /* Set the playback volume of the stream */
500 if ((curvol = aj->volume) != sjsd->volume) {
501 sjsd->fvol = (float)curvol / MEDIA_SAMPLE_VOLUME_NORM;
502 sjsd->volume = curvol;
505 if (aj->ratetrafo != sjsd->ratetrafo) {
506 sjsd->ratetrafo = aj->ratetrafo;
509 for (int i = 0; i < sjsd->num_ports; i++) {
510 bufs[i] = jack_port_get_buffer(sjsd->ports[i], nframes);
513 mtp = aj->play_state;
516 sound_jack_write(bufs, nframes, aj);
519 sound_jack_silence(bufs, nframes, sjsd);
522 case MTPSTATE_UNKNOWN:
524 case NUMBER_OF_MEDIA_THREAD_PLAY_STATES:
526 JACK_DEBUG_S("DRAIN.\n");
527 SXE_SEMAPH_TRIGGER(&(sjsd->sem));
534 * fill the buffers with silence
535 * - bufs num_bufs float buffers, each will contain the data of one channel
536 * - cnt number of samples in each buffer
537 * - num_bufs number of buffers
540 sound_jack_silence(float **bufs, int cnt, sound_jack_aj_data_t *sjsd)
543 for (i = 0; i < cnt; i++)
544 for (j = 0; j < sjsd->num_ports; j++)
549 sound_jack_write(float **bufs, jack_nframes_t nframes, audio_job_t aj)
551 sound_jack_aj_data_t *sjsd = audio_job_device_data(aj);
552 size_t len = 0, tmplen = 0, tmpcnt = 0;
553 sound_jack_demux_fun dmx = sjsd->demux_fun;
554 ms_read_fun __read = media_stream_meth(aj->substream->up, read);
556 /* cleanup buffer, move the frame overfill to the beginning */
557 if (sjsd->writepos < aj->buffer_alloc_size >> 1 &&
558 sjsd->underrun < 4) {
559 memcpy(aj->buffer, aj->buffer+sjsd->readpos,
560 sjsd->writepos - sjsd->readpos);
561 sjsd->writepos -= sjsd->readpos;
564 len = __read(aj->substream, aj->buffer+sjsd->writepos, nframes);
569 sjsd->overfill += len;
570 sjsd->writepos += len*sjsd->framesize;
572 /* increase underrun counter to detect the end */
575 } else if (sjsd->overfill > nframes << 2 ||
576 sjsd->underrun >= 4) {
577 JACK_DEBUG("having a rest\n");
579 JACK_DEBUG("resetting write position.\n");
580 memcpy(aj->buffer, aj->buffer+sjsd->readpos,
581 sjsd->writepos - sjsd->readpos);
582 sjsd->writepos -= sjsd->readpos;
586 JACK_DEBUG_S("req:%d p, got:%d p, readpos %d, writepos %d, "
587 "overfill: %d, framesize: %d, sr: %d\n",
588 nframes, len, sjsd->readpos, sjsd->writepos,
589 sjsd->overfill, sjsd->framesize, sjsd->samplerate);
591 /* care for buffer underruns */
592 if (nframes > sjsd->overfill)
593 tmplen = sjsd->overfill;
597 /* output, i loops over the number of ports we have to fill,
598 * while j loops over the actual channels */
599 for (int i = 0, j = 0; i < sjsd->num_ports; i++) {
601 bufs[i], aj->buffer+sjsd->readpos, tmplen, j, sjsd);
602 if (j < sjsd->channels) {
606 /* fill the rest with silence */
607 tmplen = nframes - tmplen;
609 JACK_DEBUG_S("fill up with silence\n");
610 sound_jack_silence(bufs, tmplen, sjsd);
613 /* modify readposition and overfill */
614 sjsd->readpos += tmpcnt * sjsd->framesize;
615 sjsd->overfill -= tmpcnt;
617 /* detect end of track */
618 if (sjsd->underrun >= 4 && sjsd->overfill < 64)
619 aj->play_state = MTPSTATE_STOP;
627 /* sound-jack.c ends here */