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/source.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/* See module-jack-sink for a few comments how this module basically
48 * works */
49
50PA_MODULE_AUTHOR("Lennart Poettering");
51PA_MODULE_DESCRIPTION("JACK Source");
52PA_MODULE_VERSION(PACKAGE_VERSION);
53PA_MODULE_LOAD_ONCE(false);
54PA_MODULE_USAGE(
55        "source_name=<name for the source> "
56        "source_properties=<properties for the source> "
57        "server_name=<jack server name> "
58        "client_name=<jack client name> "
59        "channels=<number of channels> "
60        "channel_map=<channel map> "
61        "connect=<connect ports?>");
62
63#define DEFAULT_SOURCE_NAME "jack_in"
64#define METADATA_TYPE_INT "http://www.w3.org/2001/XMLSchema#int"
65#define METADATA_KEY_ORDER "http://jackaudio.org/metadata/order"
66
67struct userdata {
68    pa_core *core;
69    pa_module *module;
70    pa_source *source;
71
72    unsigned channels;
73
74    jack_port_t* port[PA_CHANNELS_MAX];
75    jack_client_t *client;
76
77    pa_thread_mq thread_mq;
78    pa_asyncmsgq *jack_msgq;
79    pa_rtpoll *rtpoll;
80    pa_rtpoll_item *rtpoll_item;
81
82    pa_thread *thread;
83
84    jack_nframes_t saved_frame_time;
85    bool saved_frame_time_valid;
86};
87
88static const char* const valid_modargs[] = {
89    "source_name",
90    "source_properties",
91    "server_name",
92    "client_name",
93    "channels",
94    "channel_map",
95    "connect",
96    NULL
97};
98
99enum {
100    SOURCE_MESSAGE_POST = PA_SOURCE_MESSAGE_MAX,
101    SOURCE_MESSAGE_ON_SHUTDOWN
102};
103
104static int source_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
105    struct userdata *u = PA_SOURCE(o)->userdata;
106
107    switch (code) {
108
109        case SOURCE_MESSAGE_POST:
110
111            /* Handle the new block from the JACK thread */
112            pa_assert(chunk);
113            pa_assert(chunk->length > 0);
114
115            if (u->source->thread_info.state == PA_SOURCE_RUNNING)
116                pa_source_post(u->source, chunk);
117
118            u->saved_frame_time = (jack_nframes_t) offset;
119            u->saved_frame_time_valid = true;
120
121            return 0;
122
123        case SOURCE_MESSAGE_ON_SHUTDOWN:
124            pa_asyncmsgq_post(u->thread_mq.outq, PA_MSGOBJECT(u->core), PA_CORE_MESSAGE_UNLOAD_MODULE, u->module, 0, NULL, NULL);
125            return 0;
126
127        case PA_SOURCE_MESSAGE_GET_LATENCY: {
128            jack_latency_range_t r;
129            jack_nframes_t l, ft, d;
130            size_t n;
131
132            /* This is the "worst-case" latency */
133            jack_port_get_latency_range(u->port[0], JackCaptureLatency, &r);
134            l = r.max;
135
136            if (u->saved_frame_time_valid) {
137                /* Adjust the worst case latency by the time that
138                 * passed since we last handed data to JACK */
139
140                ft = jack_frame_time(u->client);
141                d = ft > u->saved_frame_time ? ft - u->saved_frame_time : 0;
142                l += d;
143            }
144
145            /* Convert it to usec */
146            n = l * pa_frame_size(&u->source->sample_spec);
147            *((int64_t*) data) = pa_bytes_to_usec(n, &u->source->sample_spec);
148
149            return 0;
150        }
151    }
152
153    return pa_source_process_msg(o, code, data, offset, chunk);
154}
155
156static int jack_process(jack_nframes_t nframes, void *arg) {
157    unsigned c;
158    struct userdata *u = arg;
159    const void *buffer[PA_CHANNELS_MAX];
160    void *p;
161    jack_nframes_t frame_time;
162    pa_memchunk chunk;
163
164    pa_assert(u);
165
166    for (c = 0; c < u->channels; c++)
167        pa_assert_se(buffer[c] = jack_port_get_buffer(u->port[c], nframes));
168
169    /* We interleave the data and pass it on to the other RT thread */
170
171    pa_memchunk_reset(&chunk);
172    chunk.length = nframes * pa_frame_size(&u->source->sample_spec);
173    chunk.memblock = pa_memblock_new(u->core->mempool, chunk.length);
174    p = pa_memblock_acquire(chunk.memblock);
175    pa_interleave(buffer, u->channels, p, sizeof(float), nframes);
176    pa_memblock_release(chunk.memblock);
177
178    frame_time = jack_frame_time(u->client);
179
180    pa_asyncmsgq_post(u->jack_msgq, PA_MSGOBJECT(u->source), SOURCE_MESSAGE_POST, NULL, frame_time, &chunk, NULL);
181
182    pa_memblock_unref(chunk.memblock);
183
184    return 0;
185}
186
187static void thread_func(void *userdata) {
188    struct userdata *u = userdata;
189
190    pa_assert(u);
191
192    pa_log_debug("Thread starting up");
193
194    if (u->core->realtime_scheduling)
195        pa_thread_make_realtime(u->core->realtime_priority);
196
197    pa_thread_mq_install(&u->thread_mq);
198
199    for (;;) {
200        int ret;
201
202        if ((ret = pa_rtpoll_run(u->rtpoll)) < 0)
203            goto fail;
204
205        if (ret == 0)
206            goto finish;
207    }
208
209fail:
210    /* If this was no regular exit from the loop we have to continue
211     * processing messages until we received PA_MESSAGE_SHUTDOWN */
212    pa_asyncmsgq_post(u->thread_mq.outq, PA_MSGOBJECT(u->core), PA_CORE_MESSAGE_UNLOAD_MODULE, u->module, 0, NULL, NULL);
213    pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
214
215finish:
216    pa_log_debug("Thread shutting down");
217}
218
219static void jack_error_func(const char*t) {
220    char *s;
221
222    s = pa_xstrndup(t, strcspn(t, "\n\r"));
223    pa_log_warn("JACK error >%s<", s);
224    pa_xfree(s);
225}
226
227static void jack_init(void *arg) {
228    struct userdata *u = arg;
229
230    pa_log_info("JACK thread starting up.");
231
232    if (u->core->realtime_scheduling)
233        pa_thread_make_realtime(u->core->realtime_priority+4);
234}
235
236static void jack_shutdown(void* arg) {
237    struct userdata *u = arg;
238
239    pa_log_info("JACK thread shutting down..");
240    pa_asyncmsgq_post(u->jack_msgq, PA_MSGOBJECT(u->source), SOURCE_MESSAGE_ON_SHUTDOWN, NULL, 0, NULL, NULL);
241}
242
243int pa__init(pa_module*m) {
244    struct userdata *u = NULL;
245    pa_sample_spec ss;
246    pa_channel_map map;
247    pa_modargs *ma = NULL;
248    jack_status_t status;
249    const char *server_name, *client_name;
250    uint32_t channels = 0;
251    bool do_connect = true;
252    unsigned i;
253    const char **ports = NULL, **p;
254    pa_source_new_data data;
255    jack_latency_range_t r;
256    jack_uuid_t port_uuid;
257    char port_order[4];
258    size_t n;
259
260    pa_assert(m);
261
262    jack_set_error_function(jack_error_func);
263
264    if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
265        pa_log("Failed to parse module arguments.");
266        goto fail;
267    }
268
269    if (pa_modargs_get_value_boolean(ma, "connect", &do_connect) < 0) {
270        pa_log("Failed to parse connect= argument.");
271        goto fail;
272    }
273
274    server_name = pa_modargs_get_value(ma, "server_name", NULL);
275    client_name = pa_modargs_get_value(ma, "client_name", "PulseAudio JACK Source");
276
277    m->userdata = u = pa_xnew0(struct userdata, 1);
278    u->core = m->core;
279    u->module = m;
280    u->saved_frame_time_valid = false;
281    u->rtpoll = pa_rtpoll_new();
282
283    if (pa_thread_mq_init(&u->thread_mq, m->core->mainloop, u->rtpoll) < 0) {
284        pa_log("pa_thread_mq_init() failed.");
285        goto fail;
286    }
287
288    u->jack_msgq = pa_asyncmsgq_new(0);
289    if (!u->jack_msgq) {
290        pa_log("pa_asyncmsgq_new() failed.");
291        goto fail;
292    }
293
294    u->rtpoll_item = pa_rtpoll_item_new_asyncmsgq_read(u->rtpoll, PA_RTPOLL_EARLY-1, u->jack_msgq);
295
296    if (!(u->client = jack_client_open(client_name, server_name ? JackServerName : JackNullOption, &status, server_name))) {
297        pa_log("jack_client_open() failed.");
298        goto fail;
299    }
300
301    ports = jack_get_ports(u->client, NULL, JACK_DEFAULT_AUDIO_TYPE, JackPortIsPhysical|JackPortIsOutput);
302
303    channels = 0;
304    if (ports)
305        for (p = ports; *p; p++)
306            channels++;
307
308    if (!channels)
309        channels = m->core->default_sample_spec.channels;
310
311    if (pa_modargs_get_value_u32(ma, "channels", &channels) < 0 ||
312        !pa_channels_valid(channels)) {
313        pa_log("failed to parse channels= argument.");
314        goto fail;
315    }
316
317    if (channels == m->core->default_channel_map.channels)
318        map = m->core->default_channel_map;
319    else
320        pa_channel_map_init_extend(&map, channels, PA_CHANNEL_MAP_ALSA);
321
322    if (pa_modargs_get_channel_map(ma, NULL, &map) < 0 || map.channels != channels) {
323        pa_log("failed to parse channel_map= argument.");
324        goto fail;
325    }
326
327    pa_log_info("Successfully connected as '%s'", jack_get_client_name(u->client));
328
329    u->channels = ss.channels = (uint8_t) channels;
330    ss.rate = jack_get_sample_rate(u->client);
331    ss.format = PA_SAMPLE_FLOAT32NE;
332
333    pa_assert(pa_sample_spec_valid(&ss));
334
335    for (i = 0; i < ss.channels; i++) {
336        if (!(u->port[i] = jack_port_register(u->client, pa_channel_position_to_string(map.map[i]), JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput|JackPortIsTerminal, 0))) {
337            pa_log("jack_port_register() failed.");
338            goto fail;
339        }
340
341        /* Set order of ports as JACK metadata, if possible. */
342        /* See: https://jackaudio.org/api/group__Metadata.html */
343        port_uuid = jack_port_uuid(u->port[i]);
344
345        if (!jack_uuid_empty(port_uuid)) {
346            if (snprintf(port_order, 4, "%d", i+1) >= 4)
347                pa_log("Port order metadata value > 999 truncated.");
348            if (jack_set_property(u->client, port_uuid, METADATA_KEY_ORDER, port_order, METADATA_TYPE_INT) != 0)
349                pa_log("jack_set_property() failed.");
350        }
351    }
352
353    pa_source_new_data_init(&data);
354    data.driver = __FILE__;
355    data.module = m;
356    pa_source_new_data_set_name(&data, pa_modargs_get_value(ma, "source_name", DEFAULT_SOURCE_NAME));
357    pa_source_new_data_set_sample_spec(&data, &ss);
358    pa_source_new_data_set_channel_map(&data, &map);
359    pa_proplist_sets(data.proplist, PA_PROP_DEVICE_API, "jack");
360    if (server_name)
361        pa_proplist_sets(data.proplist, PA_PROP_DEVICE_STRING, server_name);
362    pa_proplist_setf(data.proplist, PA_PROP_DEVICE_DESCRIPTION, "JACK source (%s)", jack_get_client_name(u->client));
363    pa_proplist_sets(data.proplist, "jack.client_name", jack_get_client_name(u->client));
364
365    if (pa_modargs_get_proplist(ma, "source_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
366        pa_log("Invalid properties");
367        pa_source_new_data_done(&data);
368        goto fail;
369    }
370
371    u->source = pa_source_new(m->core, &data, PA_SOURCE_LATENCY);
372    pa_source_new_data_done(&data);
373
374    if (!u->source) {
375        pa_log("Failed to create source.");
376        goto fail;
377    }
378
379    u->source->parent.process_msg = source_process_msg;
380    u->source->userdata = u;
381
382    pa_source_set_asyncmsgq(u->source, u->thread_mq.inq);
383    pa_source_set_rtpoll(u->source, u->rtpoll);
384
385    jack_set_process_callback(u->client, jack_process, u);
386    jack_on_shutdown(u->client, jack_shutdown, u);
387    jack_set_thread_init_callback(u->client, jack_init, u);
388
389    if (!(u->thread = pa_thread_new("jack-source", thread_func, u))) {
390        pa_log("Failed to create thread.");
391        goto fail;
392    }
393
394    if (jack_activate(u->client)) {
395        pa_log("jack_activate() failed");
396        goto fail;
397    }
398
399    if (do_connect) {
400        for (i = 0, p = ports; i < ss.channels; i++, p++) {
401
402            if (!p || !*p) {
403                pa_log("Not enough physical output ports, leaving unconnected.");
404                break;
405            }
406
407            pa_log_info("Connecting %s to %s", jack_port_name(u->port[i]), *p);
408
409            if (jack_connect(u->client, *p, jack_port_name(u->port[i]))) {
410                pa_log("Failed to connect %s to %s, leaving unconnected.", jack_port_name(u->port[i]), *p);
411                break;
412            }
413        }
414
415    }
416
417    jack_port_get_latency_range(u->port[0], JackCaptureLatency, &r);
418    n = r.max * pa_frame_size(&u->source->sample_spec);
419    pa_source_set_fixed_latency(u->source, pa_bytes_to_usec(n, &u->source->sample_spec));
420    pa_source_put(u->source);
421
422    if (ports)
423        jack_free(ports);
424    pa_modargs_free(ma);
425
426    return 0;
427
428fail:
429    if (ma)
430        pa_modargs_free(ma);
431
432    if (ports)
433        jack_free(ports);
434
435    pa__done(m);
436
437    return -1;
438}
439
440int pa__get_n_used(pa_module *m) {
441    struct userdata *u;
442
443    pa_assert(m);
444    pa_assert_se(u = m->userdata);
445
446    return pa_source_linked_by(u->source);
447}
448
449void pa__done(pa_module*m) {
450    struct userdata *u;
451    pa_assert(m);
452
453    if (!(u = m->userdata))
454        return;
455
456    if (u->source)
457        pa_source_unlink(u->source);
458
459    if (u->client)
460        jack_client_close(u->client);
461
462    if (u->thread) {
463        pa_asyncmsgq_send(u->thread_mq.inq, NULL, PA_MESSAGE_SHUTDOWN, NULL, 0, NULL);
464        pa_thread_free(u->thread);
465    }
466
467    pa_thread_mq_done(&u->thread_mq);
468
469    if (u->source)
470        pa_source_unref(u->source);
471
472    if (u->rtpoll_item)
473        pa_rtpoll_item_free(u->rtpoll_item);
474
475    if (u->jack_msgq)
476        pa_asyncmsgq_unref(u->jack_msgq);
477
478    if (u->rtpoll)
479        pa_rtpoll_free(u->rtpoll);
480
481    pa_xfree(u);
482}
483