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