2 * QEMU JACK Audio Connection Kit Client
4 * Copyright (c) 2020 Geoffrey McRae (gnif)
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 #include "qemu/osdep.h"
26 #include "qemu/module.h"
27 #include "qemu/atomic.h"
28 #include "qemu-common.h"
31 #define AUDIO_CAP "jack"
32 #include "audio_int.h"
34 #include <jack/jack.h>
35 #include <jack/thread.h>
39 typedef enum QJackState {
40 QJACK_STATE_DISCONNECTED,
47 typedef struct QJackBuffer {
56 typedef struct QJackClient {
57 AudiodevJackPerDirectionOptions *opt;
65 jack_client_t *client;
76 typedef struct QJackOut {
82 typedef struct QJackIn {
88 static int qjack_client_init(QJackClient *c);
89 static void qjack_client_connect_ports(QJackClient *c);
90 static void qjack_client_fini(QJackClient *c);
92 static void qjack_buffer_create(QJackBuffer *buffer, int channels, int frames)
94 buffer->channels = channels;
95 buffer->frames = frames;
99 buffer->data = g_malloc(channels * sizeof(float *));
100 for (int i = 0; i < channels; ++i) {
101 buffer->data[i] = g_malloc(frames * sizeof(float));
105 static void qjack_buffer_clear(QJackBuffer *buffer)
107 assert(buffer->data);
108 atomic_store_release(&buffer->used, 0);
113 static void qjack_buffer_free(QJackBuffer *buffer)
119 for (int i = 0; i < buffer->channels; ++i) {
120 g_free(buffer->data[i]);
123 g_free(buffer->data);
127 /* write PCM interleaved */
128 static int qjack_buffer_write(QJackBuffer *buffer, float *data, int size)
130 assert(buffer->data);
131 const int samples = size / sizeof(float);
132 int frames = samples / buffer->channels;
133 const int avail = buffer->frames - atomic_load_acquire(&buffer->used);
135 if (frames > avail) {
140 int wptr = buffer->wptr;
144 for (int c = 0; c < buffer->channels; ++c) {
145 buffer->data[c][wptr] = *data++;
148 if (++wptr == buffer->frames) {
157 atomic_add(&buffer->used, frames);
158 return frames * buffer->channels * sizeof(float);
161 /* write PCM linear */
162 static int qjack_buffer_write_l(QJackBuffer *buffer, float **dest, int frames)
164 assert(buffer->data);
165 const int avail = buffer->frames - atomic_load_acquire(&buffer->used);
166 int wptr = buffer->wptr;
168 if (frames > avail) {
172 int right = buffer->frames - wptr;
173 if (right > frames) {
177 const int left = frames - right;
178 for (int c = 0; c < buffer->channels; ++c) {
179 memcpy(buffer->data[c] + wptr, dest[c] , right * sizeof(float));
180 memcpy(buffer->data[c] , dest[c] + right, left * sizeof(float));
184 if (wptr >= buffer->frames) {
185 wptr -= buffer->frames;
189 atomic_add(&buffer->used, frames);
193 /* read PCM interleaved */
194 static int qjack_buffer_read(QJackBuffer *buffer, float *dest, int size)
196 assert(buffer->data);
197 const int samples = size / sizeof(float);
198 int frames = samples / buffer->channels;
199 const int avail = atomic_load_acquire(&buffer->used);
201 if (frames > avail) {
206 int rptr = buffer->rptr;
210 for (int c = 0; c < buffer->channels; ++c) {
211 *dest++ = buffer->data[c][rptr];
214 if (++rptr == buffer->frames) {
223 atomic_sub(&buffer->used, frames);
224 return frames * buffer->channels * sizeof(float);
227 /* read PCM linear */
228 static int qjack_buffer_read_l(QJackBuffer *buffer, float **dest, int frames)
230 assert(buffer->data);
232 const int used = atomic_load_acquire(&buffer->used);
233 int rptr = buffer->rptr;
239 int right = buffer->frames - rptr;
244 const int left = copy - right;
245 for (int c = 0; c < buffer->channels; ++c) {
246 memcpy(dest[c] , buffer->data[c] + rptr, right * sizeof(float));
247 memcpy(dest[c] + right, buffer->data[c] , left * sizeof(float));
251 if (rptr >= buffer->frames) {
252 rptr -= buffer->frames;
256 atomic_sub(&buffer->used, copy);
260 static int qjack_process(jack_nframes_t nframes, void *arg)
262 QJackClient *c = (QJackClient *)arg;
264 if (c->state != QJACK_STATE_RUNNING) {
268 /* get the buffers for the ports */
269 float *buffers[c->nchannels];
270 for (int i = 0; i < c->nchannels; ++i) {
271 buffers[i] = jack_port_get_buffer(c->port[i], nframes);
275 qjack_buffer_read_l(&c->fifo, buffers, nframes);
277 qjack_buffer_write_l(&c->fifo, buffers, nframes);
283 static void qjack_port_registration(jack_port_id_t port, int reg, void *arg)
286 QJackClient *c = (QJackClient *)arg;
287 c->connect_ports = true;
291 static int qjack_xrun(void *arg)
293 QJackClient *c = (QJackClient *)arg;
294 if (c->state != QJACK_STATE_RUNNING) {
298 qjack_buffer_clear(&c->fifo);
302 static void qjack_shutdown(void *arg)
304 QJackClient *c = (QJackClient *)arg;
305 c->state = QJACK_STATE_SHUTDOWN;
308 static void qjack_client_recover(QJackClient *c)
310 if (c->state == QJACK_STATE_SHUTDOWN) {
311 qjack_client_fini(c);
314 /* packets is used simply to throttle this */
315 if (c->state == QJACK_STATE_DISCONNECTED &&
316 c->packets % 100 == 0) {
318 /* if not finished then attempt to recover */
320 dolog("attempting to reconnect to server\n");
321 qjack_client_init(c);
326 static size_t qjack_write(HWVoiceOut *hw, void *buf, size_t len)
328 QJackOut *jo = (QJackOut *)hw;
331 if (jo->c.state != QJACK_STATE_RUNNING) {
332 qjack_client_recover(&jo->c);
336 qjack_client_connect_ports(&jo->c);
337 return qjack_buffer_write(&jo->c.fifo, buf, len);
340 static size_t qjack_read(HWVoiceIn *hw, void *buf, size_t len)
342 QJackIn *ji = (QJackIn *)hw;
345 if (ji->c.state != QJACK_STATE_RUNNING) {
346 qjack_client_recover(&ji->c);
350 qjack_client_connect_ports(&ji->c);
351 return qjack_buffer_read(&ji->c.fifo, buf, len);
354 static void qjack_client_connect_ports(QJackClient *c)
356 if (!c->connect_ports || !c->opt->connect_ports) {
360 c->connect_ports = false;
362 ports = jack_get_ports(c->client, c->opt->connect_ports, NULL,
363 c->out ? JackPortIsInput : JackPortIsOutput);
369 for (int i = 0; i < c->nchannels && ports[i]; ++i) {
370 const char *p = jack_port_name(c->port[i]);
371 if (jack_port_connected_to(c->port[i], ports[i])) {
376 dolog("connect %s -> %s\n", p, ports[i]);
377 jack_connect(c->client, p, ports[i]);
379 dolog("connect %s -> %s\n", ports[i], p);
380 jack_connect(c->client, ports[i], p);
385 static int qjack_client_init(QJackClient *c)
387 jack_status_t status;
388 char client_name[jack_client_name_size()];
389 jack_options_t options = JackNullOption;
392 c->connect_ports = true;
394 snprintf(client_name, sizeof(client_name), "%s-%s",
395 c->out ? "out" : "in",
396 c->opt->client_name ? c->opt->client_name : qemu_get_vm_name());
398 if (c->opt->exact_name) {
399 options |= JackUseExactName;
402 if (!c->opt->start_server) {
403 options |= JackNoStartServer;
406 if (c->opt->server_name) {
407 options |= JackServerName;
410 c->client = jack_client_open(client_name, options, &status,
411 c->opt->server_name);
413 if (c->client == NULL) {
414 dolog("jack_client_open failed: status = 0x%2.0x\n", status);
415 if (status & JackServerFailed) {
416 dolog("unable to connect to JACK server\n");
421 c->freq = jack_get_sample_rate(c->client);
423 if (status & JackServerStarted) {
424 dolog("JACK server started\n");
427 if (status & JackNameNotUnique) {
428 dolog("JACK unique name assigned %s\n",
429 jack_get_client_name(c->client));
432 jack_set_process_callback(c->client, qjack_process , c);
433 jack_set_port_registration_callback(c->client, qjack_port_registration, c);
434 jack_set_xrun_callback(c->client, qjack_xrun, c);
435 jack_on_shutdown(c->client, qjack_shutdown, c);
438 * ensure the buffersize is no smaller then 512 samples, some (all?) qemu
439 * virtual devices do not work correctly otherwise
441 if (c->buffersize < 512) {
445 /* create a 2 period buffer */
446 qjack_buffer_create(&c->fifo, c->nchannels, c->buffersize * 2);
448 /* allocate and register the ports */
449 c->port = g_malloc(sizeof(jack_port_t *) * c->nchannels);
450 for (int i = 0; i < c->nchannels; ++i) {
456 c->out ? "output %d" : "input %d",
459 c->port[i] = jack_port_register(
462 JACK_DEFAULT_AUDIO_TYPE,
463 c->out ? JackPortIsOutput : JackPortIsInput,
467 /* activate the session */
468 jack_activate(c->client);
469 c->buffersize = jack_get_buffer_size(c->client);
471 qjack_client_connect_ports(c);
472 c->state = QJACK_STATE_RUNNING;
476 static int qjack_init_out(HWVoiceOut *hw, struct audsettings *as,
479 QJackOut *jo = (QJackOut *)hw;
480 Audiodev *dev = (Audiodev *)drv_opaque;
482 if (jo->c.state != QJACK_STATE_DISCONNECTED) {
487 jo->c.nchannels = as->nchannels;
488 jo->c.opt = dev->u.jack.out;
489 int ret = qjack_client_init(&jo->c);
494 /* report the buffer size to qemu */
495 hw->samples = jo->c.buffersize;
497 /* report the audio format we support */
498 struct audsettings os = {
500 .nchannels = jo->c.nchannels,
501 .fmt = AUDIO_FORMAT_F32,
504 audio_pcm_init_info(&hw->info, &os);
506 dolog("JACK output configured for %dHz (%d samples)\n",
507 jo->c.freq, jo->c.buffersize);
512 static int qjack_init_in(HWVoiceIn *hw, struct audsettings *as,
515 QJackIn *ji = (QJackIn *)hw;
516 Audiodev *dev = (Audiodev *)drv_opaque;
518 if (ji->c.state != QJACK_STATE_DISCONNECTED) {
523 ji->c.nchannels = as->nchannels;
524 ji->c.opt = dev->u.jack.in;
525 int ret = qjack_client_init(&ji->c);
530 /* report the buffer size to qemu */
531 hw->samples = ji->c.buffersize;
533 /* report the audio format we support */
534 struct audsettings is = {
536 .nchannels = ji->c.nchannels,
537 .fmt = AUDIO_FORMAT_F32,
540 audio_pcm_init_info(&hw->info, &is);
542 dolog("JACK input configured for %dHz (%d samples)\n",
543 ji->c.freq, ji->c.buffersize);
548 static void qjack_client_fini(QJackClient *c)
551 case QJACK_STATE_RUNNING:
554 case QJACK_STATE_STOPPED:
555 for (int i = 0; i < c->nchannels; ++i) {
556 jack_port_unregister(c->client, c->port[i]);
558 jack_deactivate(c->client);
561 case QJACK_STATE_SHUTDOWN:
562 jack_client_close(c->client);
565 case QJACK_STATE_DISCONNECTED:
569 qjack_buffer_free(&c->fifo);
572 c->state = QJACK_STATE_DISCONNECTED;
575 static void qjack_fini_out(HWVoiceOut *hw)
577 QJackOut *jo = (QJackOut *)hw;
578 jo->c.finished = true;
579 qjack_client_fini(&jo->c);
582 static void qjack_fini_in(HWVoiceIn *hw)
584 QJackIn *ji = (QJackIn *)hw;
585 ji->c.finished = true;
586 qjack_client_fini(&ji->c);
589 static void qjack_enable_out(HWVoiceOut *hw, bool enable)
593 static void qjack_enable_in(HWVoiceIn *hw, bool enable)
597 static int qjack_thread_creator(jack_native_thread_t *thread,
598 const pthread_attr_t *attr, void *(*function)(void *), void *arg)
600 int ret = pthread_create(thread, attr, function, arg);
605 /* set the name of the thread */
606 pthread_setname_np(*thread, "jack-client");
611 static void *qjack_init(Audiodev *dev)
613 assert(dev->driver == AUDIODEV_DRIVER_JACK);
615 dev->u.jack.has_in = false;
620 static void qjack_fini(void *opaque)
624 static struct audio_pcm_ops jack_pcm_ops = {
625 .init_out = qjack_init_out,
626 .fini_out = qjack_fini_out,
627 .write = qjack_write,
628 .run_buffer_out = audio_generic_run_buffer_out,
629 .enable_out = qjack_enable_out,
631 .init_in = qjack_init_in,
632 .fini_in = qjack_fini_in,
634 .enable_in = qjack_enable_in
637 static struct audio_driver jack_driver = {
639 .descr = "JACK Audio Connection Kit Client",
642 .pcm_ops = &jack_pcm_ops,
644 .max_voices_out = INT_MAX,
645 .max_voices_in = INT_MAX,
646 .voice_size_out = sizeof(QJackOut),
647 .voice_size_in = sizeof(QJackIn)
650 static void qjack_error(const char *msg)
652 dolog("E: %s\n", msg);
655 static void qjack_info(const char *msg)
657 dolog("I: %s\n", msg);
660 static void register_audio_jack(void)
662 audio_driver_register(&jack_driver);
663 jack_set_thread_creator(qjack_thread_creator);
664 jack_set_error_function(qjack_error);
665 jack_set_info_function(qjack_info);
667 type_init(register_audio_jack);