85b934b066ea67c5d37f94bbf785540d93aa431c
[sxemacs] / src / media / sound-jack.c
1 /* sound-jack.c - play a sound over the Jack Audio Server
2
3    Copyright (C) 2006 Sebastian Freundt
4
5 This file is part of SXEmacs
6
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.
11
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.
16
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/>. */
19
20
21 /* Synched up with: Not in FSF. */
22
23 #ifdef HAVE_CONFIG_H
24 #include <config.h>
25 #endif
26
27 #include "lisp.h"
28
29 #include <unistd.h>
30 #include <fcntl.h>
31 #include <stdio.h>
32 #include <errno.h>
33 #include <string.h>
34
35 #include "media.h"
36 #include "sound-jack.h"
37
38 Lisp_Object Qjack;
39
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
45
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();
53
54 #define __JACK_DEBUG__(args...)         fprintf(stderr, "JACK " args)
55 #ifndef JACK_DEBUG_FLAG
56 #define JACK_DEBUG(args...)
57 #else
58 #define JACK_DEBUG(args...)             __JACK_DEBUG__(args)
59 #endif
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)
63
64 \f
65 DECLARE_AUDIO_DEVICE_SIMPLE_METHS(sound_jack);
66 DEFINE_AUDIO_DEVICE_SIMPLE(sound_jack);
67
68 \f
69 static Lisp_Object
70 sound_jack_mark(ad_device_data *devdata)
71 {
72         sound_jack_data_t *sjd = devdata;
73
74         mark_object(sjd->options);
75         mark_object(sjd->server);
76
77         return Qnil;
78 }
79
80 static void
81 sound_jack_print(Lisp_Object device, Lisp_Object pcfun, int ef)
82 {
83         sound_jack_data_t *sjd = NULL;
84
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;
91                 return;
92         }
93
94         /* info about the connected output plugin */
95         write_c_string(" :server ", pcfun);
96         if (NILP(sjd->server))
97                 write_c_string("#default", pcfun);
98         else
99                 print_internal(sjd->server, pcfun, ef);
100
101         write_c_string(" :client ", pcfun);
102         if (NILP(sjd->client))
103                 write_c_string("SXEmacs", pcfun);
104         else
105                 print_internal(sjd->client, pcfun, ef);
106
107         return;
108 }
109
110 \f
111 static ad_device_data *
112 sound_jack_create(Lisp_Object jack_options)
113 {
114         /* result */
115         sound_jack_data_t *sjd = NULL;
116         /* option keywords */
117         Lisp_Object opt_server = Qnil;
118         Lisp_Object opt_client = Qnil;
119
120         /* parse options */
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);
124                 return NULL;
125         }
126
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);
130                 return NULL;
131         }
132
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;
138         sjd->num_ports = 0;
139
140         return (ad_device_data*)sjd;
141 }
142
143 static void
144 sound_jack_finish(ad_device_data *data)
145 {
146         sound_jack_data_t *sjd = data;
147         if (sjd != NULL) {
148                 ;
149         }
150
151         return;
152 }
153
154 \f
155 static ad_device_data *
156 sound_jack_subthread_create(void)
157 {
158         /* result */
159         sound_jack_aj_data_t *sjsd = NULL;
160         /* jack stuff */
161         jack_client_t *client = NULL;
162         int port_flags = 0;
163         const char **ports = NULL;
164         int i;
165
166         /* Create a new playback client */
167         client = jack_client_open("SXEmacs", 0, NULL);
168         if (!client) {
169                 message(GETTEXT("audio-jack: "
170                                 "cannot open server."));
171                 return NULL;
172         }
173
174         /* initialise and fill */
175         sjsd = xnew_and_zero(sound_jack_aj_data_t);
176         sjsd->client = client;
177
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."));
187                 xfree(sjsd);
188                 return NULL;
189         }
190
191         JACK_DEBUG("initialised %d ports\n", sjsd->num_ports);
192
193         /* if (mtap->channels > sjsd->num_ports); */
194
195         /* create out output ports */
196         for (i = 0; i < sjsd->num_ports; i++) {
197                 char pname[30];
198                 snprintf(pname, 30, "SXEmacs out_%d", i);
199                 sjsd->ports[i] = jack_port_register(
200                         client, pname,
201                         JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0);
202                 if (!sjsd->ports[i]) {
203                         message(GETTEXT("audio-jack: "
204                                         "not enough ports available."));
205                         xfree(sjsd);
206                         return NULL;
207                 }
208         }
209
210         sjsd->port_ptrs = ports;
211
212         return (ad_device_data*)sjsd;
213 }
214
215 static int
216 sound_jack_play(audio_job_t aj)
217 {
218         /* stream stuff */
219         mtype_audio_properties *mtap;
220         Lisp_Media_Stream *ms;
221         media_substream *mss;
222         /* device stuff */
223         Lisp_Object device;
224         Lisp_Audio_Device *lad = NULL;
225         sound_jack_data_t *sjd = NULL;
226         sound_jack_aj_data_t *sjsd = NULL;
227         int i;
228
229         SOUND_UNPACK_MT(aj, device, ms, mss, lad, sjd, mtap);
230
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."));
236                 return 0;
237         }
238
239         /* initialise our callback semaphore */
240         SXE_SEMAPH_INIT(&(sjsd->sem));
241
242         if (SETJMP(jack_server_sig)) {
243                 JACK_CRITICAL("Caught a lethal signal.\n");
244                 warn_when_safe(
245                         Qjack, Qerror,
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."));
250                 return 1;
251         }
252
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;
259
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;
264
265         sjsd->ringbufcnt = SOUND_MAX_AUDIO_FRAME_SIZE >> 10;
266         sjsd->readpos = sjsd->writepos = sjsd->overfill = 0;
267         SXE_MUTEX_UNLOCK(&aj->mtx);
268
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);
273
274         /* now activate */
275         if (jack_activate(sjsd->client)) {
276                 message(GETTEXT("audio-jack: "
277                                 "activate failed."));
278                 goto finish;
279         }
280
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."));
287                         goto finish;
288                 }
289         }
290
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));
294
295         /* close and shutdown */
296 finish:
297         JACK_DEBUG("finish.\n");
298         if (sjsd->client) {
299                 jack_client_t *cli = sjsd->client;
300                 JACK_DEBUG("DISC.\n");
301                 sjsd->client = NULL;
302                 for (i = 0; i < sjsd->num_ports; i++) {
303                         jack_disconnect(cli,
304                                         jack_port_name(sjsd->ports[i]),
305                                         sjsd->port_ptrs[i]);
306                 }
307                 JACK_DEBUG("CLOSE.\n");
308                 jack_client_close(cli);
309         }
310
311         SXE_SEMAPH_FINI(&(sjsd->sem));
312
313         SXE_MUTEX_LOCK(&aj->mtx);
314         if (aj->buffer)
315                 xfree(aj->buffer);
316         aj->buffer = NULL;
317
318         if (sjsd)
319                 xfree(sjsd);
320         sjsd = NULL;
321
322         aj->state = MTSTATE_FINISHED;
323         SXE_MUTEX_UNLOCK(&aj->mtx);
324
325         return 1;
326 }
327
328 \f
329 /* pull one channel out of a multi-channel stream */
330 static size_t
331 demux_internal(float *dst, char *src,
332                size_t n, int chan, sound_jack_aj_data_t *f)
333 {
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;
341
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)
347                         * f->fvol;
348         }
349
350         /* actually read frames were n * samplerate / 48000 */
351         return n * sr/48000 * f->ratetrafo;
352 }
353
354 /**
355  * error callback
356  **/
357 static void
358 sound_jack_error(const char *errmsg)
359 {
360         JACK_CRITICAL("Strange things happened.\n"
361                       "Error message: %s\n",
362                       errmsg);
363
364         LONGJMP(jack_server_sig, 1);
365
366         return;
367 }
368
369 /* shutdown callback */
370 static void
371 sound_jack_shutdown_cbfun(void *arg)
372 {
373         JACK_CRITICAL("Shutdown: 0x%x\n", (unsigned int)arg);
374
375         LONGJMP(jack_server_sig, 1);
376
377         return;
378 }
379
380 #ifdef EF_USE_ASYNEQ
381 static inline void
382 sound_jack_change_volume(audio_job_t aj, audio_job_event_args_t args)
383 {
384         SXE_MUTEX_LOCK(&aj->mtx);
385         aj->volume = args->volume_args;
386         SXE_MUTEX_UNLOCK(&aj->mtx);
387 }
388
389 static inline void
390 sound_jack_change_rate(audio_job_t aj, audio_job_event_args_t args)
391 {
392         SXE_MUTEX_LOCK(&aj->mtx);
393         aj->ratetrafo = args->rate_args;
394         SXE_MUTEX_UNLOCK(&aj->mtx);
395 }
396
397 static inline void
398 sound_jack_change_state(audio_job_t aj, audio_job_event_args_t args)
399 {
400         SXE_MUTEX_LOCK(&aj->mtx);
401         switch (args->state_args) {
402         case aj_pause:
403                 JACK_DEBUG_AJ("->pause state\n");
404                 aj->play_state = MTPSTATE_PAUSE;
405                 break;
406         case aj_resume:
407                 JACK_DEBUG_AJ("->resume state\n");
408                 aj->play_state = MTPSTATE_RUN;
409                 break;
410         case aj_start:
411                 JACK_DEBUG_AJ("->start state\n");
412                 break;
413         case aj_stop:
414                 JACK_DEBUG_AJ("->stop state\n");
415                 aj->play_state = MTPSTATE_STOP;
416                 break;
417
418         case no_audio_job_change_states:
419         default:
420                 JACK_DEBUG_AJ("->unknown state\n");
421                 break;
422         }
423         SXE_MUTEX_UNLOCK(&aj->mtx);
424 }
425
426 static inline void
427 sound_jack_handle_aj_events(audio_job_t aj)
428         __attribute__((always_inline));
429 static inline void
430 sound_jack_handle_aj_events(audio_job_t aj)
431 {
432         sound_jack_aj_data_t *sasd;
433         audio_job_event_t ev = NULL;
434
435 #if 0
436         assert(audio_job_queue(aj));
437 #endif
438
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);
443                 return;
444         }
445         SXE_MUTEX_UNLOCK(&aj->mtx);
446
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));
452                 break;
453         case aj_change_volume:
454                 JACK_DEBUG_AJ("change volume event\n");
455                 sound_jack_change_volume(aj, &audio_job_event_args(ev));
456                 break;
457         case aj_change_rate:
458                 JACK_DEBUG_AJ("change rate event\n");
459                 sound_jack_change_rate(aj, &audio_job_event_args(ev));
460                 break;
461
462         case no_audio_job_event_kinds:
463         default:
464                 JACK_CRITICAL("unknown event\n");
465                 break;
466         }
467         free_audio_job_event(ev);
468 }
469 #endif  /* EF_USE_ASYNEQ */
470
471 /**
472  * JACK Callback function
473  * - nframes number of frames to fill into buffers
474  * - arg contains the media subthread to operate on
475  */
476 static int
477 sound_jack_process(jack_nframes_t nframes, void *userdata)
478 {
479         audio_job_t aj = NULL;
480         sound_jack_aj_data_t *sjsd = NULL;
481         media_substream *mss = NULL;
482         char *buffer = NULL;
483         media_thread_play_state mtp;
484         float *bufs[MAX_CHANS];
485         int curvol;
486
487         aj = userdata;
488         mss = aj->substream;
489         sjsd = audio_job_device_data(aj);
490         buffer = aj->buffer;
491
492 #ifdef EF_USE_ASYNEQ
493         /* stuff on the event queue? */
494         if (audio_job_queue(aj)) {
495                 sound_jack_handle_aj_events(aj);
496         }
497 #endif
498
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;
503         }
504
505         if (aj->ratetrafo != sjsd->ratetrafo) {
506                 sjsd->ratetrafo = aj->ratetrafo;
507         }
508
509         for (int i = 0; i < sjsd->num_ports; i++) {
510                 bufs[i] = jack_port_get_buffer(sjsd->ports[i], nframes);
511         }
512
513         mtp = aj->play_state;
514         switch (mtp) {
515         case MTPSTATE_RUN:
516                 sound_jack_write(bufs, nframes, aj);
517                 break;
518         case MTPSTATE_PAUSE:
519                 sound_jack_silence(bufs, nframes, sjsd);
520                 break;
521
522         case MTPSTATE_UNKNOWN:
523         case MTPSTATE_STOP:
524         case NUMBER_OF_MEDIA_THREAD_PLAY_STATES:
525         default:
526                 JACK_DEBUG_S("DRAIN.\n");
527                 SXE_SEMAPH_TRIGGER(&(sjsd->sem));
528                 break;
529         }
530         return 0;
531 }
532
533 /**
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
538  */
539 static void
540 sound_jack_silence(float **bufs, int cnt, sound_jack_aj_data_t *sjsd)
541 {
542         int i, j;
543         for (i = 0; i < cnt; i++)
544                 for (j = 0; j < sjsd->num_ports; j++)
545                         bufs[j][i] = 0.0f;
546 }
547
548 static int
549 sound_jack_write(float **bufs, jack_nframes_t nframes, audio_job_t aj)
550 {
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);
555
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;
562                 sjsd->readpos = 0;
563
564                 len = __read(aj->substream, aj->buffer+sjsd->writepos, nframes);
565                 if (len == -1UL) {
566                         len = 0;
567                 }
568
569                 sjsd->overfill += len;
570                 sjsd->writepos += len*sjsd->framesize;
571
572                 /* increase underrun counter to detect the end */
573                 if (len == 0)
574                         sjsd->underrun++;
575         } else if (sjsd->overfill > nframes << 2 ||
576                    sjsd->underrun >= 4) {
577                 JACK_DEBUG("having a rest\n");
578         } else {
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;
583                 sjsd->readpos = 0;
584         }
585
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);
590
591         /* care for buffer underruns */
592         if (nframes > sjsd->overfill)
593                 tmplen = sjsd->overfill;
594         else
595                 tmplen = nframes;
596
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++) {
600                 tmpcnt = dmx(
601                         bufs[i], aj->buffer+sjsd->readpos, tmplen, j, sjsd);
602                 if (j < sjsd->channels) {
603                         j++;
604                 }
605         }
606         /* fill the rest with silence */
607         tmplen = nframes - tmplen;
608         if (tmplen > 0) {
609                 JACK_DEBUG_S("fill up with silence\n");
610                 sound_jack_silence(bufs, tmplen, sjsd);
611         }
612
613         /* modify readposition and overfill */
614         sjsd->readpos += tmpcnt * sjsd->framesize;
615         sjsd->overfill -= tmpcnt;
616
617         /* detect end of track */
618         if (sjsd->underrun >= 4 && sjsd->overfill < 64)
619                 aj->play_state = MTPSTATE_STOP;
620
621         return 0;
622 }
623
624
625 #undef MYSELF
626
627 /* sound-jack.c ends here */