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, see <http://www.gnu.org/licenses/>.
18***/
19
20#ifdef HAVE_CONFIG_H
21#include <config.h>
22#endif
23
24#include <stdlib.h>
25#include <stdio.h>
26#include <errno.h>
27#include <string.h>
28#include <unistd.h>
29
30#include <jack/jack.h>
31#include <jack/metadata.h>
32#include <jack/uuid.h>
33
34#include <pulse/util.h>
35#include <pulse/xmalloc.h>
36
37#include <pulsecore/sink.h>
38#include <pulsecore/module.h>
39#include <pulsecore/core-util.h>
40#include <pulsecore/modargs.h>
41#include <pulsecore/log.h>
42#include <pulsecore/thread.h>
43#include <pulsecore/thread-mq.h>
44#include <pulsecore/rtpoll.h>
45#include <pulsecore/sample-util.h>
46
47/* General overview:
48 *
49 * Because JACK has a very inflexible event loop management which
50 * doesn't allow us to add our own event sources to the event thread
51 * we cannot use the JACK real-time thread for dispatching our PA
52 * work. Instead, we run an additional RT thread which does most of
53 * the PA handling, and have the JACK RT thread request data from it
54 * via pa_asyncmsgq. The cost is an additional context switch which
55 * should hopefully not be that expensive if RT scheduling is
56 * enabled. A better fix would only be possible with additional event
57 * source support in JACK.
58 */
59
60PA_MODULE_AUTHOR("Lennart Poettering");
61PA_MODULE_DESCRIPTION("JACK Sink");
62PA_MODULE_LOAD_ONCE(false);
63PA_MODULE_VERSION(PACKAGE_VERSION);
64PA_MODULE_USAGE(
65        "sink_name=<name for the sink> "
66        "sink_properties=<properties for the card> "
67        "server_name=<jack server name> "
68        "client_name=<jack client name> "
69        "channels=<number of channels> "
70        "channel_map=<channel map> "
71        "connect=<connect ports?>");
72
73#define DEFAULT_SINK_NAME "jack_out"
74#define METADATA_TYPE_INT "http://www.w3.org/2001/XMLSchema#int"
75#define METADATA_KEY_ORDER "http://jackaudio.org/metadata/order"
76
77struct userdata {
78    pa_core *core;
79    pa_module *module;
80    pa_sink *sink;
81
82    unsigned channels;
83
84    jack_port_t* port[PA_CHANNELS_MAX];
85    jack_client_t *client;
86
87    void *buffer[PA_CHANNELS_MAX];
88
89    pa_thread_mq thread_mq;
90    pa_asyncmsgq *jack_msgq;
91    pa_rtpoll *rtpoll;
92    pa_rtpoll_item *rtpoll_item;
93
94    pa_thread *thread;
95
96    jack_nframes_t frames_in_buffer;
97    jack_nframes_t saved_frame_time;
98    bool saved_frame_time_valid;
99};
100
101static const char* const valid_modargs[] = {
102    "sink_name",
103    "sink_properties",
104    "server_name",
105    "client_name",
106    "channels",
107    "channel_map",
108    "connect",
109    NULL
110};
111
112enum {
113    SINK_MESSAGE_RENDER = PA_SINK_MESSAGE_MAX,
114    SINK_MESSAGE_BUFFER_SIZE,
115    SINK_MESSAGE_ON_SHUTDOWN
116};
117
118static int sink_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *memchunk) {
119    struct userdata *u = PA_SINK(o)->userdata;
120
121    switch (code) {
122
123        case SINK_MESSAGE_RENDER:
124
125            /* Handle the request from the JACK thread */
126
127            if (u->sink->thread_info.state == PA_SINK_RUNNING) {
128                pa_memchunk chunk;
129                size_t nbytes;
130                void *p;
131
132                pa_assert(offset > 0);
133                nbytes = (size_t) offset * pa_frame_size(&u->sink->sample_spec);
134
135                pa_sink_render_full(u->sink, nbytes, &chunk);
136
137                p = pa_memblock_acquire_chunk(&chunk);
138                pa_deinterleave(p, u->buffer, u->channels, sizeof(float), (unsigned) offset);
139                pa_memblock_release(chunk.memblock);
140
141                pa_memblock_unref(chunk.memblock);
142            } else {
143                unsigned c;
144                pa_sample_spec ss;
145
146                /* Humm, we're not RUNNING, hence let's write some silence */
147                /* This can happen if we're paused, or during shutdown (when we're unlinked but jack is still running). */
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 ft, d;
172            jack_latency_range_t r;
173            size_t n;
174            int32_t number_of_frames;
175
176            /* This is the "worst-case" latency */
177            jack_port_get_latency_range(u->port[0], JackPlaybackLatency, &r);
178            number_of_frames = r.max + u->frames_in_buffer;
179
180            if (u->saved_frame_time_valid) {
181                /* Adjust the worst case latency by the time that
182                 * passed since we last handed data to JACK */
183
184                ft = jack_frame_time(u->client);
185                d = ft > u->saved_frame_time ? ft - u->saved_frame_time : 0;
186                number_of_frames -= d;
187            }
188
189            /* Convert it to usec */
190            if (number_of_frames > 0) {
191                n = number_of_frames * pa_frame_size(&u->sink->sample_spec);
192                *((int64_t*) data) = pa_bytes_to_usec(n, &u->sink->sample_spec);
193            } else {
194                n = - number_of_frames * pa_frame_size(&u->sink->sample_spec);
195                *((int64_t*) data) = - (int64_t)pa_bytes_to_usec(n, &u->sink->sample_spec);
196            }
197
198            return 0;
199        }
200
201    }
202
203    return pa_sink_process_msg(o, code, data, offset, memchunk);
204}
205
206/* JACK Callback: This is called when JACK needs some data */
207static int jack_process(jack_nframes_t nframes, void *arg) {
208    struct userdata *u = arg;
209    unsigned c;
210    jack_nframes_t frame_time;
211    pa_assert(u);
212
213    /* We just forward the request to our other RT thread */
214
215    for (c = 0; c < u->channels; c++)
216        pa_assert_se(u->buffer[c] = jack_port_get_buffer(u->port[c], nframes));
217
218    frame_time = jack_frame_time(u->client);
219
220    pa_assert_se(pa_asyncmsgq_send(u->jack_msgq, PA_MSGOBJECT(u->sink), SINK_MESSAGE_RENDER, &frame_time, nframes, NULL) == 0);
221    return 0;
222}
223
224static void thread_func(void *userdata) {
225    struct userdata *u = userdata;
226
227    pa_assert(u);
228
229    pa_log_debug("Thread starting up");
230
231    if (u->core->realtime_scheduling)
232        pa_thread_make_realtime(u->core->realtime_priority);
233
234    pa_thread_mq_install(&u->thread_mq);
235
236    for (;;) {
237        int ret;
238
239        if (PA_UNLIKELY(u->sink->thread_info.rewind_requested))
240            pa_sink_process_rewind(u->sink, 0);
241
242        if ((ret = pa_rtpoll_run(u->rtpoll)) < 0)
243            goto fail;
244
245        if (ret == 0)
246            goto finish;
247    }
248
249fail:
250    /* If this was no regular exit from the loop we have to continue
251     * processing messages until we received PA_MESSAGE_SHUTDOWN */
252    pa_asyncmsgq_post(u->thread_mq.outq, PA_MSGOBJECT(u->core), PA_CORE_MESSAGE_UNLOAD_MODULE, u->module, 0, NULL, NULL);
253    pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
254
255finish:
256    pa_log_debug("Thread shutting down");
257}
258
259/* JACK Callback: This is called when JACK triggers an error */
260static void jack_error_func(const char*t) {
261    char *s;
262
263    s = pa_xstrndup(t, strcspn(t, "\n\r"));
264    pa_log_warn("JACK error >%s<", s);
265    pa_xfree(s);
266}
267
268/* JACK Callback: This is called when JACK is set up */
269static void jack_init(void *arg) {
270    struct userdata *u = arg;
271
272    pa_log_info("JACK thread starting up.");
273
274    if (u->core->realtime_scheduling)
275        pa_thread_make_realtime(u->core->realtime_priority+4);
276}
277
278/* JACK Callback: This is called when JACK kicks us */
279static void jack_shutdown(void* arg) {
280    struct userdata *u = arg;
281
282    pa_log_info("JACK thread shutting down.");
283    pa_asyncmsgq_post(u->jack_msgq, PA_MSGOBJECT(u->sink), SINK_MESSAGE_ON_SHUTDOWN, NULL, 0, NULL, NULL);
284}
285
286/* JACK Callback: This is called when JACK changes the buffer size */
287static int jack_buffer_size(jack_nframes_t nframes, void *arg) {
288    struct userdata *u = arg;
289
290    pa_log_info("JACK buffer size changed.");
291    pa_asyncmsgq_post(u->jack_msgq, PA_MSGOBJECT(u->sink), SINK_MESSAGE_BUFFER_SIZE, NULL, nframes, NULL, NULL);
292    return 0;
293}
294
295int pa__init(pa_module*m) {
296    struct userdata *u = NULL;
297    pa_sample_spec ss;
298    pa_channel_map map;
299    pa_modargs *ma = NULL;
300    jack_status_t status;
301    const char *server_name, *client_name;
302    uint32_t channels = 0;
303    bool do_connect = true;
304    unsigned i;
305    const char **ports = NULL, **p;
306    pa_sink_new_data data;
307    jack_latency_range_t r;
308    jack_uuid_t port_uuid;
309    char port_order[4];
310    size_t n;
311
312    pa_assert(m);
313
314    jack_set_error_function(jack_error_func);
315
316    if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
317        pa_log("Failed to parse module arguments.");
318        goto fail;
319    }
320
321    if (pa_modargs_get_value_boolean(ma, "connect", &do_connect) < 0) {
322        pa_log("Failed to parse connect= argument.");
323        goto fail;
324    }
325
326    server_name = pa_modargs_get_value(ma, "server_name", NULL);
327    client_name = pa_modargs_get_value(ma, "client_name", "PulseAudio JACK Sink");
328
329    m->userdata = u = pa_xnew0(struct userdata, 1);
330    u->core = m->core;
331    u->module = m;
332    u->saved_frame_time_valid = false;
333    u->rtpoll = pa_rtpoll_new();
334
335    if (pa_thread_mq_init(&u->thread_mq, m->core->mainloop, u->rtpoll) < 0) {
336        pa_log("pa_thread_mq_init() failed.");
337        goto fail;
338    }
339
340    /* The queue linking the JACK thread and our RT thread */
341    u->jack_msgq = pa_asyncmsgq_new(0);
342    if (!u->jack_msgq) {
343        pa_log("pa_asyncmsgq_new() failed.");
344        goto fail;
345    }
346
347    /* The msgq from the JACK RT thread should have an even higher
348     * priority than the normal message queues, to match the guarantee
349     * all other drivers make: supplying the audio device with data is
350     * the top priority -- and as long as that is possible we don't do
351     * anything else */
352    u->rtpoll_item = pa_rtpoll_item_new_asyncmsgq_read(u->rtpoll, PA_RTPOLL_EARLY-1, u->jack_msgq);
353
354    if (!(u->client = jack_client_open(client_name, server_name ? JackServerName : JackNullOption, &status, server_name))) {
355        pa_log("jack_client_open() failed.");
356        goto fail;
357    }
358
359    ports = jack_get_ports(u->client, NULL, JACK_DEFAULT_AUDIO_TYPE, JackPortIsPhysical|JackPortIsInput);
360
361    channels = 0;
362    if (ports)
363        for (p = ports; *p; p++)
364            channels++;
365
366    if (!channels)
367        channels = m->core->default_sample_spec.channels;
368
369    if (pa_modargs_get_value_u32(ma, "channels", &channels) < 0 ||
370        !pa_channels_valid(channels)) {
371        pa_log("Failed to parse channels= argument.");
372        goto fail;
373    }
374
375    if (channels == m->core->default_channel_map.channels)
376        map = m->core->default_channel_map;
377    else
378        pa_channel_map_init_extend(&map, channels, PA_CHANNEL_MAP_ALSA);
379
380    if (pa_modargs_get_channel_map(ma, NULL, &map) < 0 || map.channels != channels) {
381        pa_log("Failed to parse channel_map= argument.");
382        goto fail;
383    }
384
385    pa_log_info("Successfully connected as '%s'", jack_get_client_name(u->client));
386
387    u->channels = ss.channels = (uint8_t) channels;
388    ss.rate = jack_get_sample_rate(u->client);
389    ss.format = PA_SAMPLE_FLOAT32NE;
390
391    pa_assert(pa_sample_spec_valid(&ss));
392
393    for (i = 0; i < ss.channels; i++) {
394        if (!(u->port[i] = jack_port_register(u->client, pa_channel_position_to_string(map.map[i]), JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput|JackPortIsTerminal, 0))) {
395            pa_log("jack_port_register() failed.");
396            goto fail;
397        }
398
399        /* Set order of ports as JACK metadata, if possible. */
400        /* See: https://jackaudio.org/api/group__Metadata.html */
401        port_uuid = jack_port_uuid(u->port[i]);
402
403        if (!jack_uuid_empty(port_uuid)) {
404            if (snprintf(port_order, 4, "%d", i+1) >= 4)
405                pa_log("Port order metadata value > 999 truncated.");
406            if (jack_set_property(u->client, port_uuid, METADATA_KEY_ORDER, port_order, METADATA_TYPE_INT) != 0)
407                pa_log("jack_set_property() failed.");
408        }
409    }
410
411    pa_sink_new_data_init(&data);
412    data.driver = __FILE__;
413    data.module = m;
414    pa_sink_new_data_set_name(&data, pa_modargs_get_value(ma, "sink_name", DEFAULT_SINK_NAME));
415    pa_sink_new_data_set_sample_spec(&data, &ss);
416    pa_sink_new_data_set_channel_map(&data, &map);
417    pa_proplist_sets(data.proplist, PA_PROP_DEVICE_API, "jack");
418    if (server_name)
419        pa_proplist_sets(data.proplist, PA_PROP_DEVICE_STRING, server_name);
420    pa_proplist_setf(data.proplist, PA_PROP_DEVICE_DESCRIPTION, "JACK sink (%s)", jack_get_client_name(u->client));
421    pa_proplist_sets(data.proplist, "jack.client_name", jack_get_client_name(u->client));
422
423    if (pa_modargs_get_proplist(ma, "sink_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
424        pa_log("Invalid properties");
425        pa_sink_new_data_done(&data);
426        goto fail;
427    }
428
429    u->sink = pa_sink_new(m->core, &data, PA_SINK_LATENCY);
430    pa_sink_new_data_done(&data);
431
432    if (!u->sink) {
433        pa_log("Failed to create sink.");
434        goto fail;
435    }
436
437    u->sink->parent.process_msg = sink_process_msg;
438    u->sink->userdata = u;
439
440    pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
441    pa_sink_set_rtpoll(u->sink, u->rtpoll);
442    pa_sink_set_max_request(u->sink, jack_get_buffer_size(u->client) * pa_frame_size(&u->sink->sample_spec));
443
444    jack_set_process_callback(u->client, jack_process, u);
445    jack_on_shutdown(u->client, jack_shutdown, u);
446    jack_set_thread_init_callback(u->client, jack_init, u);
447    jack_set_buffer_size_callback(u->client, jack_buffer_size, u);
448
449    if (!(u->thread = pa_thread_new("jack-sink", thread_func, u))) {
450        pa_log("Failed to create thread.");
451        goto fail;
452    }
453
454    if (jack_activate(u->client)) {
455        pa_log("jack_activate() failed");
456        goto fail;
457    }
458
459    if (do_connect) {
460        for (i = 0, p = ports; i < ss.channels; i++, p++) {
461
462            if (!p || !*p) {
463                pa_log("Not enough physical output ports, leaving unconnected.");
464                break;
465            }
466
467            pa_log_info("Connecting %s to %s", jack_port_name(u->port[i]), *p);
468
469            if (jack_connect(u->client, jack_port_name(u->port[i]), *p)) {
470                pa_log("Failed to connect %s to %s, leaving unconnected.", jack_port_name(u->port[i]), *p);
471                break;
472            }
473        }
474    }
475
476    jack_port_get_latency_range(u->port[0], JackPlaybackLatency, &r);
477    n = r.max * pa_frame_size(&u->sink->sample_spec);
478    pa_sink_set_fixed_latency(u->sink, pa_bytes_to_usec(n, &u->sink->sample_spec));
479    pa_sink_put(u->sink);
480
481    if (ports)
482        jack_free(ports);
483    pa_modargs_free(ma);
484
485    return 0;
486
487fail:
488    if (ma)
489        pa_modargs_free(ma);
490
491    if (ports)
492        jack_free(ports);
493
494    pa__done(m);
495
496    return -1;
497}
498
499int pa__get_n_used(pa_module *m) {
500    struct userdata *u;
501
502    pa_assert(m);
503    pa_assert_se(u = m->userdata);
504
505    return pa_sink_linked_by(u->sink);
506}
507
508void pa__done(pa_module*m) {
509    struct userdata *u;
510
511    pa_assert(m);
512
513    if (!(u = m->userdata))
514        return;
515
516    if (u->sink)
517        pa_sink_unlink(u->sink);
518
519    if (u->client)
520        jack_client_close(u->client);
521
522    if (u->thread) {
523        pa_asyncmsgq_send(u->thread_mq.inq, NULL, PA_MESSAGE_SHUTDOWN, NULL, 0, NULL);
524        pa_thread_free(u->thread);
525    }
526
527    pa_thread_mq_done(&u->thread_mq);
528
529    if (u->sink)
530        pa_sink_unref(u->sink);
531
532    if (u->rtpoll_item)
533        pa_rtpoll_item_free(u->rtpoll_item);
534
535    if (u->jack_msgq)
536        pa_asyncmsgq_unref(u->jack_msgq);
537
538    if (u->rtpoll)
539        pa_rtpoll_free(u->rtpoll);
540
541    pa_xfree(u);
542}
543