bluetooth: be a bit more verbose if we exit due to bad poll() revents flag
[profile/ivi/pulseaudio-panda.git] / src / modules / module-jack-sink.c
1 /***
2   This file is part of PulseAudio.
3
4   Copyright 2006 Lennart Poettering
5
6   PulseAudio is free software; you can redistribute it and/or modify
7   it under the terms of the GNU Lesser General Public License as published
8   by the Free Software Foundation; either version 2.1 of the License,
9   or (at your option) any later version.
10
11   PulseAudio is distributed in the hope that it will be useful, but
12   WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14   General Public License for more details.
15
16   You should have received a copy of the GNU Lesser General Public License
17   along with PulseAudio; if not, write to the Free Software
18   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
19   USA.
20 ***/
21
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25
26 #include <stdlib.h>
27 #include <sys/stat.h>
28 #include <stdio.h>
29 #include <errno.h>
30 #include <string.h>
31 #include <fcntl.h>
32 #include <unistd.h>
33 #include <limits.h>
34
35 #include <jack/jack.h>
36
37 #include <pulse/xmalloc.h>
38
39 #include <pulsecore/core-error.h>
40 #include <pulsecore/sink.h>
41 #include <pulsecore/module.h>
42 #include <pulsecore/core-util.h>
43 #include <pulsecore/modargs.h>
44 #include <pulsecore/log.h>
45 #include <pulsecore/thread.h>
46 #include <pulsecore/thread-mq.h>
47 #include <pulsecore/rtpoll.h>
48 #include <pulsecore/sample-util.h>
49
50 #include "module-jack-sink-symdef.h"
51
52 /* General overview:
53  *
54  * Because JACK has a very unflexible event loop management which
55  * doesn't allow us to add our own event sources to the event thread
56  * we cannot use the JACK real-time thread for dispatching our PA
57  * work. Instead, we run an additional RT thread which does most of
58  * the PA handling, and have the JACK RT thread request data from it
59  * via pa_asyncmsgq. The cost is an additional context switch which
60  * should hopefully not be that expensive if RT scheduling is
61  * enabled. A better fix would only be possible with additional event
62  * source support in JACK.
63  */
64
65 PA_MODULE_AUTHOR("Lennart Poettering");
66 PA_MODULE_DESCRIPTION("JACK Sink");
67 PA_MODULE_LOAD_ONCE(TRUE);
68 PA_MODULE_VERSION(PACKAGE_VERSION);
69 PA_MODULE_USAGE(
70         "sink_name=<name of sink> "
71         "server_name=<jack server name> "
72         "client_name=<jack client name> "
73         "channels=<number of channels> "
74         "connect=<connect ports?> "
75         "channel_map=<channel map>");
76
77 #define DEFAULT_SINK_NAME "jack_out"
78
79 struct userdata {
80     pa_core *core;
81     pa_module *module;
82     pa_sink *sink;
83
84     unsigned channels;
85
86     jack_port_t* port[PA_CHANNELS_MAX];
87     jack_client_t *client;
88
89     void *buffer[PA_CHANNELS_MAX];
90
91     pa_thread_mq thread_mq;
92     pa_asyncmsgq *jack_msgq;
93     pa_rtpoll *rtpoll;
94     pa_rtpoll_item *rtpoll_item;
95
96     pa_thread *thread;
97
98     jack_nframes_t frames_in_buffer;
99     jack_nframes_t saved_frame_time;
100     pa_bool_t saved_frame_time_valid;
101 };
102
103 static const char* const valid_modargs[] = {
104     "sink_name",
105     "server_name",
106     "client_name",
107     "channels",
108     "connect",
109     "channel_map",
110     NULL
111 };
112
113 enum {
114     SINK_MESSAGE_RENDER = PA_SINK_MESSAGE_MAX,
115     SINK_MESSAGE_BUFFER_SIZE,
116     SINK_MESSAGE_ON_SHUTDOWN
117 };
118
119 static int sink_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *memchunk) {
120     struct userdata *u = PA_SINK(o)->userdata;
121
122     switch (code) {
123
124         case SINK_MESSAGE_RENDER:
125
126             /* Handle the request from the JACK thread */
127
128             if (u->sink->thread_info.state == PA_SINK_RUNNING) {
129                 pa_memchunk chunk;
130                 size_t nbytes;
131                 void *p;
132
133                 pa_assert(offset > 0);
134                 nbytes = (size_t) offset * pa_frame_size(&u->sink->sample_spec);
135
136                 pa_sink_render_full(u->sink, nbytes, &chunk);
137
138                 p = (uint8_t*) pa_memblock_acquire(chunk.memblock) + chunk.index;
139                 pa_deinterleave(p, u->buffer, u->channels, sizeof(float), (unsigned) offset);
140                 pa_memblock_release(chunk.memblock);
141
142                 pa_memblock_unref(chunk.memblock);
143             } else {
144                 unsigned c;
145                 pa_sample_spec ss;
146
147                 /* Humm, we're not RUNNING, hence let's write some silence */
148
149                 ss = u->sink->sample_spec;
150                 ss.channels = 1;
151
152                 for (c = 0; c < u->channels; c++)
153                     pa_silence_memory(u->buffer[c], (size_t) offset * pa_sample_size(&ss), &ss);
154             }
155
156             u->frames_in_buffer = (jack_nframes_t) offset;
157             u->saved_frame_time = * (jack_nframes_t*) data;
158             u->saved_frame_time_valid = TRUE;
159
160             return 0;
161
162         case SINK_MESSAGE_BUFFER_SIZE:
163             pa_sink_set_max_request_within_thread(u->sink, (size_t) offset * pa_frame_size(&u->sink->sample_spec));
164             return 0;
165
166         case SINK_MESSAGE_ON_SHUTDOWN:
167             pa_asyncmsgq_post(u->thread_mq.outq, PA_MSGOBJECT(u->core), PA_CORE_MESSAGE_UNLOAD_MODULE, u->module, 0, NULL, NULL);
168             return 0;
169
170         case PA_SINK_MESSAGE_GET_LATENCY: {
171             jack_nframes_t l, ft, d;
172             size_t n;
173
174             /* This is the "worst-case" latency */
175             l = jack_port_get_total_latency(u->client, u->port[0]) + u->frames_in_buffer;
176
177             if (u->saved_frame_time_valid) {
178                 /* Adjust the worst case latency by the time that
179                  * passed since we last handed data to JACK */
180
181                 ft = jack_frame_time(u->client);
182                 d = ft > u->saved_frame_time ? ft - u->saved_frame_time : 0;
183                 l = l > d ? l - d : 0;
184             }
185
186             /* Convert it to usec */
187             n = l * pa_frame_size(&u->sink->sample_spec);
188             *((pa_usec_t*) data) = pa_bytes_to_usec(n, &u->sink->sample_spec);
189
190             return 0;
191         }
192
193     }
194
195     return pa_sink_process_msg(o, code, data, offset, memchunk);
196 }
197
198 static int jack_process(jack_nframes_t nframes, void *arg) {
199     struct userdata *u = arg;
200     unsigned c;
201     jack_nframes_t frame_time;
202     pa_assert(u);
203
204     /* We just forward the request to our other RT thread */
205
206     for (c = 0; c < u->channels; c++)
207         pa_assert_se(u->buffer[c] = jack_port_get_buffer(u->port[c], nframes));
208
209     frame_time = jack_frame_time(u->client);
210
211     pa_assert_se(pa_asyncmsgq_send(u->jack_msgq, PA_MSGOBJECT(u->sink), SINK_MESSAGE_RENDER, &frame_time, nframes, NULL) == 0);
212     return 0;
213 }
214
215 static void thread_func(void *userdata) {
216     struct userdata *u = userdata;
217
218     pa_assert(u);
219
220     pa_log_debug("Thread starting up");
221
222     if (u->core->realtime_scheduling)
223         pa_make_realtime(u->core->realtime_priority);
224
225     pa_thread_mq_install(&u->thread_mq);
226     pa_rtpoll_install(u->rtpoll);
227
228     for (;;) {
229         int ret;
230
231         if (PA_SINK_IS_OPENED(u->sink->thread_info.state))
232             if (u->sink->thread_info.rewind_requested)
233                 pa_sink_process_rewind(u->sink, 0);
234
235         if ((ret = pa_rtpoll_run(u->rtpoll, TRUE)) < 0)
236             goto fail;
237
238         if (ret == 0)
239             goto finish;
240     }
241
242 fail:
243     /* If this was no regular exit from the loop we have to continue
244      * processing messages until we received PA_MESSAGE_SHUTDOWN */
245     pa_asyncmsgq_post(u->thread_mq.outq, PA_MSGOBJECT(u->core), PA_CORE_MESSAGE_UNLOAD_MODULE, u->module, 0, NULL, NULL);
246     pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
247
248 finish:
249     pa_log_debug("Thread shutting down");
250 }
251
252 static void jack_error_func(const char*t) {
253     char *s;
254
255     s = pa_xstrndup(t, strcspn(t, "\n\r"));
256     pa_log_warn("JACK error >%s<", s);
257     pa_xfree(s);
258 }
259
260 static void jack_init(void *arg) {
261     struct userdata *u = arg;
262
263     pa_log_info("JACK thread starting up.");
264
265     if (u->core->realtime_scheduling)
266         pa_make_realtime(u->core->realtime_priority+4);
267 }
268
269 static void jack_shutdown(void* arg) {
270     struct userdata *u = arg;
271
272     pa_log_info("JACK thread shutting down.");
273     pa_asyncmsgq_post(u->jack_msgq, PA_MSGOBJECT(u->sink), SINK_MESSAGE_ON_SHUTDOWN, NULL, 0, NULL, NULL);
274 }
275
276 static int jack_buffer_size(jack_nframes_t nframes, void *arg) {
277     struct userdata *u = arg;
278
279     pa_log_info("JACK buffer size changed.");
280     pa_asyncmsgq_post(u->jack_msgq, PA_MSGOBJECT(u->sink), SINK_MESSAGE_BUFFER_SIZE, NULL, nframes, NULL, NULL);
281     return 0;
282 }
283
284 int pa__init(pa_module*m) {
285     struct userdata *u = NULL;
286     pa_sample_spec ss;
287     pa_channel_map map;
288     pa_modargs *ma = NULL;
289     jack_status_t status;
290     const char *server_name, *client_name;
291     uint32_t channels = 0;
292     pa_bool_t do_connect = TRUE;
293     unsigned i;
294     const char **ports = NULL, **p;
295     pa_sink_new_data data;
296
297     pa_assert(m);
298
299     jack_set_error_function(jack_error_func);
300
301     if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
302         pa_log("Failed to parse module arguments.");
303         goto fail;
304     }
305
306     if (pa_modargs_get_value_boolean(ma, "connect", &do_connect) < 0) {
307         pa_log("Failed to parse connect= argument.");
308         goto fail;
309     }
310
311     server_name = pa_modargs_get_value(ma, "server_name", NULL);
312     client_name = pa_modargs_get_value(ma, "client_name", "PulseAudio JACK Sink");
313
314     m->userdata = u = pa_xnew0(struct userdata, 1);
315     u->core = m->core;
316     u->module = m;
317     u->saved_frame_time_valid = FALSE;
318     u->rtpoll = pa_rtpoll_new();
319     pa_thread_mq_init(&u->thread_mq, m->core->mainloop, u->rtpoll);
320
321     /* The queue linking the JACK thread and our RT thread */
322     u->jack_msgq = pa_asyncmsgq_new(0);
323
324     /* The msgq from the JACK RT thread should have an even higher
325      * priority than the normal message queues, to match the guarantee
326      * all other drivers make: supplying the audio device with data is
327      * the top priority -- and as long as that is possible we don't do
328      * anything else */
329     u->rtpoll_item = pa_rtpoll_item_new_asyncmsgq_read(u->rtpoll, PA_RTPOLL_EARLY-1, u->jack_msgq);
330
331     if (!(u->client = jack_client_open(client_name, server_name ? JackServerName : JackNullOption, &status, server_name))) {
332         pa_log("jack_client_open() failed.");
333         goto fail;
334     }
335
336     ports = jack_get_ports(u->client, NULL, NULL, JackPortIsPhysical|JackPortIsInput);
337
338     channels = 0;
339     for (p = ports; *p; p++)
340         channels++;
341
342     if (!channels)
343         channels = m->core->default_sample_spec.channels;
344
345     if (pa_modargs_get_value_u32(ma, "channels", &channels) < 0 ||
346         channels <= 0 ||
347         channels > PA_CHANNELS_MAX) {
348         pa_log("Failed to parse channels= argument.");
349         goto fail;
350     }
351
352     if (channels == m->core->default_channel_map.channels)
353         map = m->core->default_channel_map;
354     else
355         pa_channel_map_init_extend(&map, channels, PA_CHANNEL_MAP_ALSA);
356
357     if (pa_modargs_get_channel_map(ma, NULL, &map) < 0 || map.channels != channels) {
358         pa_log("Failed to parse channel_map= argument.");
359         goto fail;
360     }
361
362     pa_log_info("Successfully connected as '%s'", jack_get_client_name(u->client));
363
364     u->channels = ss.channels = (uint8_t) channels;
365     ss.rate = jack_get_sample_rate(u->client);
366     ss.format = PA_SAMPLE_FLOAT32NE;
367
368     pa_assert(pa_sample_spec_valid(&ss));
369
370     for (i = 0; i < ss.channels; i++) {
371         if (!(u->port[i] = jack_port_register(u->client, pa_channel_position_to_string(map.map[i]), JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput|JackPortIsTerminal, 0))) {
372             pa_log("jack_port_register() failed.");
373             goto fail;
374         }
375     }
376
377     pa_sink_new_data_init(&data);
378     data.driver = __FILE__;
379     data.module = m;
380     pa_sink_new_data_set_name(&data, pa_modargs_get_value(ma, "sink_name", DEFAULT_SINK_NAME));
381     pa_sink_new_data_set_sample_spec(&data, &ss);
382     pa_sink_new_data_set_channel_map(&data, &map);
383     pa_proplist_sets(data.proplist, PA_PROP_DEVICE_API, "jack");
384     if (server_name)
385         pa_proplist_sets(data.proplist, PA_PROP_DEVICE_STRING, server_name);
386     pa_proplist_setf(data.proplist, PA_PROP_DEVICE_DESCRIPTION, "Jack sink (%s)", jack_get_client_name(u->client));
387     pa_proplist_sets(data.proplist, "jack.client_name", jack_get_client_name(u->client));
388
389     u->sink = pa_sink_new(m->core, &data, PA_SINK_LATENCY);
390     pa_sink_new_data_done(&data);
391
392     if (!u->sink) {
393         pa_log("Failed to create sink.");
394         goto fail;
395     }
396
397     u->sink->parent.process_msg = sink_process_msg;
398     u->sink->userdata = u;
399
400     pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
401     pa_sink_set_rtpoll(u->sink, u->rtpoll);
402     pa_sink_set_max_request(u->sink, jack_get_buffer_size(u->client) * pa_frame_size(&u->sink->sample_spec));
403
404     jack_set_process_callback(u->client, jack_process, u);
405     jack_on_shutdown(u->client, jack_shutdown, u);
406     jack_set_thread_init_callback(u->client, jack_init, u);
407     jack_set_buffer_size_callback(u->client, jack_buffer_size, u);
408
409     if (!(u->thread = pa_thread_new(thread_func, u))) {
410         pa_log("Failed to create thread.");
411         goto fail;
412     }
413
414     if (jack_activate(u->client)) {
415         pa_log("jack_activate() failed");
416         goto fail;
417     }
418
419     if (do_connect) {
420         for (i = 0, p = ports; i < ss.channels; i++, p++) {
421
422             if (!*p) {
423                 pa_log("Not enough physical output ports, leaving unconnected.");
424                 break;
425             }
426
427             pa_log_info("Connecting %s to %s", jack_port_name(u->port[i]), *p);
428
429             if (jack_connect(u->client, jack_port_name(u->port[i]), *p)) {
430                 pa_log("Failed to connect %s to %s, leaving unconnected.", jack_port_name(u->port[i]), *p);
431                 break;
432             }
433         }
434     }
435
436     pa_sink_put(u->sink);
437
438     free(ports);
439     pa_modargs_free(ma);
440
441     return 0;
442
443 fail:
444     if (ma)
445         pa_modargs_free(ma);
446
447     free(ports);
448
449     pa__done(m);
450
451     return -1;
452 }
453
454 int pa__get_n_used(pa_module *m) {
455     struct userdata *u;
456
457     pa_assert(m);
458     pa_assert_se(u = m->userdata);
459
460     return pa_sink_linked_by(u->sink);
461 }
462
463 void pa__done(pa_module*m) {
464     struct userdata *u;
465
466     pa_assert(m);
467
468     if (!(u = m->userdata))
469         return;
470
471     if (u->client)
472         jack_client_close(u->client);
473
474     if (u->sink)
475         pa_sink_unlink(u->sink);
476
477     if (u->thread) {
478         pa_asyncmsgq_send(u->thread_mq.inq, NULL, PA_MESSAGE_SHUTDOWN, NULL, 0, NULL);
479         pa_thread_free(u->thread);
480     }
481
482     pa_thread_mq_done(&u->thread_mq);
483
484     if (u->sink)
485         pa_sink_unref(u->sink);
486
487     if (u->rtpoll_item)
488         pa_rtpoll_item_free(u->rtpoll_item);
489
490     if (u->jack_msgq)
491         pa_asyncmsgq_unref(u->jack_msgq);
492
493     if (u->rtpoll)
494         pa_rtpoll_free(u->rtpoll);
495
496     pa_xfree(u);
497 }