Git init
[framework/multimedia/pulseaudio.git] / src / modules / jack / 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 for the sink> "
71         "sink_properties=<properties  for the card> "
72         "server_name=<jack server name> "
73         "client_name=<jack client name> "
74         "channels=<number of channels> "
75         "channel_map=<channel map> "
76         "connect=<connect ports?>");
77
78 #define DEFAULT_SINK_NAME "jack_out"
79
80 struct userdata {
81     pa_core *core;
82     pa_module *module;
83     pa_sink *sink;
84
85     unsigned channels;
86
87     jack_port_t* port[PA_CHANNELS_MAX];
88     jack_client_t *client;
89
90     void *buffer[PA_CHANNELS_MAX];
91
92     pa_thread_mq thread_mq;
93     pa_asyncmsgq *jack_msgq;
94     pa_rtpoll *rtpoll;
95     pa_rtpoll_item *rtpoll_item;
96
97     pa_thread *thread;
98
99     jack_nframes_t frames_in_buffer;
100     jack_nframes_t saved_frame_time;
101     pa_bool_t saved_frame_time_valid;
102 };
103
104 static const char* const valid_modargs[] = {
105     "sink_name",
106     "sink_properties",
107     "server_name",
108     "client_name",
109     "channels",
110     "channel_map",
111     "connect",
112     NULL
113 };
114
115 enum {
116     SINK_MESSAGE_RENDER = PA_SINK_MESSAGE_MAX,
117     SINK_MESSAGE_BUFFER_SIZE,
118     SINK_MESSAGE_ON_SHUTDOWN
119 };
120
121 static int sink_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *memchunk) {
122     struct userdata *u = PA_SINK(o)->userdata;
123
124     switch (code) {
125
126         case SINK_MESSAGE_RENDER:
127
128             /* Handle the request from the JACK thread */
129
130             if (u->sink->thread_info.state == PA_SINK_RUNNING) {
131                 pa_memchunk chunk;
132                 size_t nbytes;
133                 void *p;
134
135                 pa_assert(offset > 0);
136                 nbytes = (size_t) offset * pa_frame_size(&u->sink->sample_spec);
137
138                 pa_sink_render_full(u->sink, nbytes, &chunk);
139
140                 p = (uint8_t*) pa_memblock_acquire(chunk.memblock) + chunk.index;
141                 pa_deinterleave(p, u->buffer, u->channels, sizeof(float), (unsigned) offset);
142                 pa_memblock_release(chunk.memblock);
143
144                 pa_memblock_unref(chunk.memblock);
145             } else {
146                 unsigned c;
147                 pa_sample_spec ss;
148
149                 /* Humm, we're not RUNNING, hence let's write some silence */
150
151                 ss = u->sink->sample_spec;
152                 ss.channels = 1;
153
154                 for (c = 0; c < u->channels; c++)
155                     pa_silence_memory(u->buffer[c], (size_t) offset * pa_sample_size(&ss), &ss);
156             }
157
158             u->frames_in_buffer = (jack_nframes_t) offset;
159             u->saved_frame_time = * (jack_nframes_t*) data;
160             u->saved_frame_time_valid = TRUE;
161
162             return 0;
163
164         case SINK_MESSAGE_BUFFER_SIZE:
165             pa_sink_set_max_request_within_thread(u->sink, (size_t) offset * pa_frame_size(&u->sink->sample_spec));
166             return 0;
167
168         case SINK_MESSAGE_ON_SHUTDOWN:
169             pa_asyncmsgq_post(u->thread_mq.outq, PA_MSGOBJECT(u->core), PA_CORE_MESSAGE_UNLOAD_MODULE, u->module, 0, NULL, NULL);
170             return 0;
171
172         case PA_SINK_MESSAGE_GET_LATENCY: {
173             jack_nframes_t l, ft, d;
174             size_t n;
175
176             /* This is the "worst-case" latency */
177             l = jack_port_get_total_latency(u->client, u->port[0]) + u->frames_in_buffer;
178
179             if (u->saved_frame_time_valid) {
180                 /* Adjust the worst case latency by the time that
181                  * passed since we last handed data to JACK */
182
183                 ft = jack_frame_time(u->client);
184                 d = ft > u->saved_frame_time ? ft - u->saved_frame_time : 0;
185                 l = l > d ? l - d : 0;
186             }
187
188             /* Convert it to usec */
189             n = l * pa_frame_size(&u->sink->sample_spec);
190             *((pa_usec_t*) data) = pa_bytes_to_usec(n, &u->sink->sample_spec);
191
192             return 0;
193         }
194
195     }
196
197     return pa_sink_process_msg(o, code, data, offset, memchunk);
198 }
199
200 static int jack_process(jack_nframes_t nframes, void *arg) {
201     struct userdata *u = arg;
202     unsigned c;
203     jack_nframes_t frame_time;
204     pa_assert(u);
205
206     /* We just forward the request to our other RT thread */
207
208     for (c = 0; c < u->channels; c++)
209         pa_assert_se(u->buffer[c] = jack_port_get_buffer(u->port[c], nframes));
210
211     frame_time = jack_frame_time(u->client);
212
213     pa_assert_se(pa_asyncmsgq_send(u->jack_msgq, PA_MSGOBJECT(u->sink), SINK_MESSAGE_RENDER, &frame_time, nframes, NULL) == 0);
214     return 0;
215 }
216
217 static void thread_func(void *userdata) {
218     struct userdata *u = userdata;
219
220     pa_assert(u);
221
222     pa_log_debug("Thread starting up");
223
224     if (u->core->realtime_scheduling)
225         pa_make_realtime(u->core->realtime_priority);
226
227     pa_thread_mq_install(&u->thread_mq);
228
229     for (;;) {
230         int ret;
231
232         if (PA_SINK_IS_OPENED(u->sink->thread_info.state))
233             if (u->sink->thread_info.rewind_requested)
234                 pa_sink_process_rewind(u->sink, 0);
235
236         if ((ret = pa_rtpoll_run(u->rtpoll, TRUE)) < 0)
237             goto fail;
238
239         if (ret == 0)
240             goto finish;
241     }
242
243 fail:
244     /* If this was no regular exit from the loop we have to continue
245      * processing messages until we received PA_MESSAGE_SHUTDOWN */
246     pa_asyncmsgq_post(u->thread_mq.outq, PA_MSGOBJECT(u->core), PA_CORE_MESSAGE_UNLOAD_MODULE, u->module, 0, NULL, NULL);
247     pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
248
249 finish:
250     pa_log_debug("Thread shutting down");
251 }
252
253 static void jack_error_func(const char*t) {
254     char *s;
255
256     s = pa_xstrndup(t, strcspn(t, "\n\r"));
257     pa_log_warn("JACK error >%s<", s);
258     pa_xfree(s);
259 }
260
261 static void jack_init(void *arg) {
262     struct userdata *u = arg;
263
264     pa_log_info("JACK thread starting up.");
265
266     if (u->core->realtime_scheduling)
267         pa_make_realtime(u->core->realtime_priority+4);
268 }
269
270 static void jack_shutdown(void* arg) {
271     struct userdata *u = arg;
272
273     pa_log_info("JACK thread shutting down.");
274     pa_asyncmsgq_post(u->jack_msgq, PA_MSGOBJECT(u->sink), SINK_MESSAGE_ON_SHUTDOWN, NULL, 0, NULL, NULL);
275 }
276
277 static int jack_buffer_size(jack_nframes_t nframes, void *arg) {
278     struct userdata *u = arg;
279
280     pa_log_info("JACK buffer size changed.");
281     pa_asyncmsgq_post(u->jack_msgq, PA_MSGOBJECT(u->sink), SINK_MESSAGE_BUFFER_SIZE, NULL, nframes, NULL, NULL);
282     return 0;
283 }
284
285 int pa__init(pa_module*m) {
286     struct userdata *u = NULL;
287     pa_sample_spec ss;
288     pa_channel_map map;
289     pa_modargs *ma = NULL;
290     jack_status_t status;
291     const char *server_name, *client_name;
292     uint32_t channels = 0;
293     pa_bool_t do_connect = TRUE;
294     unsigned i;
295     const char **ports = NULL, **p;
296     pa_sink_new_data data;
297
298     pa_assert(m);
299
300     jack_set_error_function(jack_error_func);
301
302     if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
303         pa_log("Failed to parse module arguments.");
304         goto fail;
305     }
306
307     if (pa_modargs_get_value_boolean(ma, "connect", &do_connect) < 0) {
308         pa_log("Failed to parse connect= argument.");
309         goto fail;
310     }
311
312     server_name = pa_modargs_get_value(ma, "server_name", NULL);
313     client_name = pa_modargs_get_value(ma, "client_name", "PulseAudio JACK Sink");
314
315     m->userdata = u = pa_xnew0(struct userdata, 1);
316     u->core = m->core;
317     u->module = m;
318     u->saved_frame_time_valid = FALSE;
319     u->rtpoll = pa_rtpoll_new();
320     pa_thread_mq_init(&u->thread_mq, m->core->mainloop, u->rtpoll);
321
322     /* The queue linking the JACK thread and our RT thread */
323     u->jack_msgq = pa_asyncmsgq_new(0);
324
325     /* The msgq from the JACK RT thread should have an even higher
326      * priority than the normal message queues, to match the guarantee
327      * all other drivers make: supplying the audio device with data is
328      * the top priority -- and as long as that is possible we don't do
329      * anything else */
330     u->rtpoll_item = pa_rtpoll_item_new_asyncmsgq_read(u->rtpoll, PA_RTPOLL_EARLY-1, u->jack_msgq);
331
332     if (!(u->client = jack_client_open(client_name, server_name ? JackServerName : JackNullOption, &status, server_name))) {
333         pa_log("jack_client_open() failed.");
334         goto fail;
335     }
336
337     ports = jack_get_ports(u->client, NULL, JACK_DEFAULT_AUDIO_TYPE, JackPortIsPhysical|JackPortIsInput);
338
339     channels = 0;
340     for (p = ports; *p; p++)
341         channels++;
342
343     if (!channels)
344         channels = m->core->default_sample_spec.channels;
345
346     if (pa_modargs_get_value_u32(ma, "channels", &channels) < 0 ||
347         channels <= 0 ||
348         channels > PA_CHANNELS_MAX) {
349         pa_log("Failed to parse channels= argument.");
350         goto fail;
351     }
352
353     if (channels == m->core->default_channel_map.channels)
354         map = m->core->default_channel_map;
355     else
356         pa_channel_map_init_extend(&map, channels, PA_CHANNEL_MAP_ALSA);
357
358     if (pa_modargs_get_channel_map(ma, NULL, &map) < 0 || map.channels != channels) {
359         pa_log("Failed to parse channel_map= argument.");
360         goto fail;
361     }
362
363     pa_log_info("Successfully connected as '%s'", jack_get_client_name(u->client));
364
365     u->channels = ss.channels = (uint8_t) channels;
366     ss.rate = jack_get_sample_rate(u->client);
367     ss.format = PA_SAMPLE_FLOAT32NE;
368
369     pa_assert(pa_sample_spec_valid(&ss));
370
371     for (i = 0; i < ss.channels; i++) {
372         if (!(u->port[i] = jack_port_register(u->client, pa_channel_position_to_string(map.map[i]), JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput|JackPortIsTerminal, 0))) {
373             pa_log("jack_port_register() failed.");
374             goto fail;
375         }
376     }
377
378     pa_sink_new_data_init(&data);
379     data.driver = __FILE__;
380     data.module = m;
381     pa_sink_new_data_set_name(&data, pa_modargs_get_value(ma, "sink_name", DEFAULT_SINK_NAME));
382     pa_sink_new_data_set_sample_spec(&data, &ss);
383     pa_sink_new_data_set_channel_map(&data, &map);
384     pa_proplist_sets(data.proplist, PA_PROP_DEVICE_API, "jack");
385     if (server_name)
386         pa_proplist_sets(data.proplist, PA_PROP_DEVICE_STRING, server_name);
387     pa_proplist_setf(data.proplist, PA_PROP_DEVICE_DESCRIPTION, "Jack sink (%s)", jack_get_client_name(u->client));
388     pa_proplist_sets(data.proplist, "jack.client_name", jack_get_client_name(u->client));
389
390     if (pa_modargs_get_proplist(ma, "sink_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
391         pa_log("Invalid properties");
392         pa_sink_new_data_done(&data);
393         goto fail;
394     }
395
396     u->sink = pa_sink_new(m->core, &data, PA_SINK_LATENCY);
397     pa_sink_new_data_done(&data);
398
399     if (!u->sink) {
400         pa_log("Failed to create sink.");
401         goto fail;
402     }
403
404     u->sink->parent.process_msg = sink_process_msg;
405     u->sink->userdata = u;
406
407     pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
408     pa_sink_set_rtpoll(u->sink, u->rtpoll);
409     pa_sink_set_max_request(u->sink, jack_get_buffer_size(u->client) * pa_frame_size(&u->sink->sample_spec));
410
411     jack_set_process_callback(u->client, jack_process, u);
412     jack_on_shutdown(u->client, jack_shutdown, u);
413     jack_set_thread_init_callback(u->client, jack_init, u);
414     jack_set_buffer_size_callback(u->client, jack_buffer_size, u);
415
416     if (!(u->thread = pa_thread_new(thread_func, u))) {
417         pa_log("Failed to create thread.");
418         goto fail;
419     }
420
421     if (jack_activate(u->client)) {
422         pa_log("jack_activate() failed");
423         goto fail;
424     }
425
426     if (do_connect) {
427         for (i = 0, p = ports; i < ss.channels; i++, p++) {
428
429             if (!*p) {
430                 pa_log("Not enough physical output ports, leaving unconnected.");
431                 break;
432             }
433
434             pa_log_info("Connecting %s to %s", jack_port_name(u->port[i]), *p);
435
436             if (jack_connect(u->client, jack_port_name(u->port[i]), *p)) {
437                 pa_log("Failed to connect %s to %s, leaving unconnected.", jack_port_name(u->port[i]), *p);
438                 break;
439             }
440         }
441     }
442
443     pa_sink_put(u->sink);
444
445     free(ports);
446     pa_modargs_free(ma);
447
448     return 0;
449
450 fail:
451     if (ma)
452         pa_modargs_free(ma);
453
454     free(ports);
455
456     pa__done(m);
457
458     return -1;
459 }
460
461 int pa__get_n_used(pa_module *m) {
462     struct userdata *u;
463
464     pa_assert(m);
465     pa_assert_se(u = m->userdata);
466
467     return pa_sink_linked_by(u->sink);
468 }
469
470 void pa__done(pa_module*m) {
471     struct userdata *u;
472
473     pa_assert(m);
474
475     if (!(u = m->userdata))
476         return;
477
478     if (u->client)
479         jack_client_close(u->client);
480
481     if (u->sink)
482         pa_sink_unlink(u->sink);
483
484     if (u->thread) {
485         pa_asyncmsgq_send(u->thread_mq.inq, NULL, PA_MESSAGE_SHUTDOWN, NULL, 0, NULL);
486         pa_thread_free(u->thread);
487     }
488
489     pa_thread_mq_done(&u->thread_mq);
490
491     if (u->sink)
492         pa_sink_unref(u->sink);
493
494     if (u->rtpoll_item)
495         pa_rtpoll_item_free(u->rtpoll_item);
496
497     if (u->jack_msgq)
498         pa_asyncmsgq_unref(u->jack_msgq);
499
500     if (u->rtpoll)
501         pa_rtpoll_free(u->rtpoll);
502
503     pa_xfree(u);
504 }