xref: /openbmc/qemu/audio/jackaudio.c (revision 0c4e9931)
1 /*
2  * QEMU JACK Audio Connection Kit Client
3  *
4  * Copyright (c) 2020 Geoffrey McRae (gnif)
5  *
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:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
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
22  * THE SOFTWARE.
23  */
24 
25 #include "qemu/osdep.h"
26 #include "qemu/module.h"
27 #include "qemu/atomic.h"
28 #include "qemu-common.h"
29 #include "audio.h"
30 
31 #define AUDIO_CAP "jack"
32 #include "audio_int.h"
33 
34 #include <jack/jack.h>
35 #include <jack/thread.h>
36 
37 struct QJack;
38 
39 typedef enum QJackState {
40     QJACK_STATE_DISCONNECTED,
41     QJACK_STATE_STOPPED,
42     QJACK_STATE_RUNNING,
43     QJACK_STATE_SHUTDOWN
44 }
45 QJackState;
46 
47 typedef struct QJackBuffer {
48     int          channels;
49     int          frames;
50     uint32_t     used;
51     int          rptr, wptr;
52     float      **data;
53 }
54 QJackBuffer;
55 
56 typedef struct QJackClient {
57     AudiodevJackPerDirectionOptions *opt;
58 
59     bool out;
60     bool finished;
61     bool connect_ports;
62     int  packets;
63 
64     QJackState      state;
65     jack_client_t  *client;
66     jack_nframes_t  freq;
67 
68     struct QJack   *j;
69     int             nchannels;
70     int             buffersize;
71     jack_port_t   **port;
72     QJackBuffer     fifo;
73 }
74 QJackClient;
75 
76 typedef struct QJackOut {
77     HWVoiceOut  hw;
78     QJackClient c;
79 }
80 QJackOut;
81 
82 typedef struct QJackIn {
83     HWVoiceIn   hw;
84     QJackClient c;
85 }
86 QJackIn;
87 
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);
91 
92 static void qjack_buffer_create(QJackBuffer *buffer, int channels, int frames)
93 {
94     buffer->channels = channels;
95     buffer->frames   = frames;
96     buffer->used     = 0;
97     buffer->rptr     = 0;
98     buffer->wptr     = 0;
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));
102     }
103 }
104 
105 static void qjack_buffer_clear(QJackBuffer *buffer)
106 {
107     assert(buffer->data);
108     atomic_store_release(&buffer->used, 0);
109     buffer->rptr = 0;
110     buffer->wptr = 0;
111 }
112 
113 static void qjack_buffer_free(QJackBuffer *buffer)
114 {
115     if (!buffer->data) {
116         return;
117     }
118 
119     for (int i = 0; i < buffer->channels; ++i) {
120         g_free(buffer->data[i]);
121     }
122 
123     g_free(buffer->data);
124     buffer->data = NULL;
125 }
126 
127 /* write PCM interleaved */
128 static int qjack_buffer_write(QJackBuffer *buffer, float *data, int size)
129 {
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);
134 
135     if (frames > avail) {
136         frames = avail;
137     }
138 
139     int copy = frames;
140     int wptr = buffer->wptr;
141 
142     while (copy) {
143 
144         for (int c = 0; c < buffer->channels; ++c) {
145             buffer->data[c][wptr] = *data++;
146         }
147 
148         if (++wptr == buffer->frames) {
149             wptr = 0;
150         }
151 
152         --copy;
153     }
154 
155     buffer->wptr = wptr;
156 
157     atomic_add(&buffer->used, frames);
158     return frames * buffer->channels * sizeof(float);
159 };
160 
161 /* write PCM linear */
162 static int qjack_buffer_write_l(QJackBuffer *buffer, float **dest, int frames)
163 {
164     assert(buffer->data);
165     const int avail   = buffer->frames - atomic_load_acquire(&buffer->used);
166     int wptr = buffer->wptr;
167 
168     if (frames > avail) {
169         frames = avail;
170     }
171 
172     int right = buffer->frames - wptr;
173     if (right > frames) {
174         right = frames;
175     }
176 
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));
181     }
182 
183     wptr += frames;
184     if (wptr >= buffer->frames) {
185         wptr -= buffer->frames;
186     }
187     buffer->wptr = wptr;
188 
189     atomic_add(&buffer->used, frames);
190     return frames;
191 }
192 
193 /* read PCM interleaved */
194 static int qjack_buffer_read(QJackBuffer *buffer, float *dest, int size)
195 {
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);
200 
201     if (frames > avail) {
202         frames = avail;
203     }
204 
205     int copy = frames;
206     int rptr = buffer->rptr;
207 
208     while (copy) {
209 
210         for (int c = 0; c < buffer->channels; ++c) {
211             *dest++ = buffer->data[c][rptr];
212         }
213 
214         if (++rptr == buffer->frames) {
215             rptr = 0;
216         }
217 
218         --copy;
219     }
220 
221     buffer->rptr = rptr;
222 
223     atomic_sub(&buffer->used, frames);
224     return frames * buffer->channels * sizeof(float);
225 }
226 
227 /* read PCM linear */
228 static int qjack_buffer_read_l(QJackBuffer *buffer, float **dest, int frames)
229 {
230     assert(buffer->data);
231     int copy       = frames;
232     const int used = atomic_load_acquire(&buffer->used);
233     int rptr       = buffer->rptr;
234 
235     if (copy > used) {
236         copy = used;
237     }
238 
239     int right = buffer->frames - rptr;
240     if (right > copy) {
241         right = copy;
242     }
243 
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));
248     }
249 
250     rptr += copy;
251     if (rptr >= buffer->frames) {
252         rptr -= buffer->frames;
253     }
254     buffer->rptr = rptr;
255 
256     atomic_sub(&buffer->used, copy);
257     return copy;
258 }
259 
260 static int qjack_process(jack_nframes_t nframes, void *arg)
261 {
262     QJackClient *c = (QJackClient *)arg;
263 
264     if (c->state != QJACK_STATE_RUNNING) {
265         return 0;
266     }
267 
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);
272     }
273 
274     if (c->out) {
275         qjack_buffer_read_l(&c->fifo, buffers, nframes);
276     } else {
277         qjack_buffer_write_l(&c->fifo, buffers, nframes);
278     }
279 
280     return 0;
281 }
282 
283 static void qjack_port_registration(jack_port_id_t port, int reg, void *arg)
284 {
285     if (reg) {
286         QJackClient *c = (QJackClient *)arg;
287         c->connect_ports = true;
288     }
289 }
290 
291 static int qjack_xrun(void *arg)
292 {
293     QJackClient *c = (QJackClient *)arg;
294     if (c->state != QJACK_STATE_RUNNING) {
295         return 0;
296     }
297 
298     qjack_buffer_clear(&c->fifo);
299     return 0;
300 }
301 
302 static void qjack_shutdown(void *arg)
303 {
304     QJackClient *c = (QJackClient *)arg;
305     c->state = QJACK_STATE_SHUTDOWN;
306 }
307 
308 static void qjack_client_recover(QJackClient *c)
309 {
310     if (c->state == QJACK_STATE_SHUTDOWN) {
311         qjack_client_fini(c);
312     }
313 
314     /* packets is used simply to throttle this */
315     if (c->state == QJACK_STATE_DISCONNECTED &&
316         c->packets % 100 == 0) {
317 
318         /* if not finished then attempt to recover */
319         if (!c->finished) {
320             dolog("attempting to reconnect to server\n");
321             qjack_client_init(c);
322         }
323     }
324 }
325 
326 static size_t qjack_write(HWVoiceOut *hw, void *buf, size_t len)
327 {
328     QJackOut *jo = (QJackOut *)hw;
329     ++jo->c.packets;
330 
331     if (jo->c.state != QJACK_STATE_RUNNING) {
332         qjack_client_recover(&jo->c);
333         return len;
334     }
335 
336     qjack_client_connect_ports(&jo->c);
337     return qjack_buffer_write(&jo->c.fifo, buf, len);
338 }
339 
340 static size_t qjack_read(HWVoiceIn *hw, void *buf, size_t len)
341 {
342     QJackIn *ji = (QJackIn *)hw;
343     ++ji->c.packets;
344 
345     if (ji->c.state != QJACK_STATE_RUNNING) {
346         qjack_client_recover(&ji->c);
347         return len;
348     }
349 
350     qjack_client_connect_ports(&ji->c);
351     return qjack_buffer_read(&ji->c.fifo, buf, len);
352 }
353 
354 static void qjack_client_connect_ports(QJackClient *c)
355 {
356     if (!c->connect_ports || !c->opt->connect_ports) {
357         return;
358     }
359 
360     c->connect_ports = false;
361     const char **ports;
362     ports = jack_get_ports(c->client, c->opt->connect_ports, NULL,
363         c->out ? JackPortIsInput : JackPortIsOutput);
364 
365     if (!ports) {
366         return;
367     }
368 
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])) {
372             continue;
373         }
374 
375         if (c->out) {
376             dolog("connect %s -> %s\n", p, ports[i]);
377             jack_connect(c->client, p, ports[i]);
378         } else {
379             dolog("connect %s -> %s\n", ports[i], p);
380             jack_connect(c->client, ports[i], p);
381         }
382     }
383 }
384 
385 static int qjack_client_init(QJackClient *c)
386 {
387     jack_status_t status;
388     char client_name[jack_client_name_size()];
389     jack_options_t options = JackNullOption;
390 
391     c->finished      = false;
392     c->connect_ports = true;
393 
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());
397 
398     if (c->opt->exact_name) {
399         options |= JackUseExactName;
400     }
401 
402     if (!c->opt->start_server) {
403         options |= JackNoStartServer;
404     }
405 
406     if (c->opt->server_name) {
407         options |= JackServerName;
408     }
409 
410     c->client = jack_client_open(client_name, options, &status,
411       c->opt->server_name);
412 
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");
417         }
418         return -1;
419     }
420 
421     c->freq = jack_get_sample_rate(c->client);
422 
423     if (status & JackServerStarted) {
424         dolog("JACK server started\n");
425     }
426 
427     if (status & JackNameNotUnique) {
428         dolog("JACK unique name assigned %s\n",
429           jack_get_client_name(c->client));
430     }
431 
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);
436 
437     /*
438      * ensure the buffersize is no smaller then 512 samples, some (all?) qemu
439      * virtual devices do not work correctly otherwise
440      */
441     if (c->buffersize < 512) {
442         c->buffersize = 512;
443     }
444 
445     /* create a 2 period buffer */
446     qjack_buffer_create(&c->fifo, c->nchannels, c->buffersize * 2);
447 
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) {
451 
452         char port_name[16];
453         snprintf(
454             port_name,
455             sizeof(port_name),
456             c->out ? "output %d" : "input %d",
457             i);
458 
459         c->port[i] = jack_port_register(
460             c->client,
461             port_name,
462             JACK_DEFAULT_AUDIO_TYPE,
463             c->out ? JackPortIsOutput : JackPortIsInput,
464             0);
465     }
466 
467     /* activate the session */
468     jack_activate(c->client);
469     c->buffersize = jack_get_buffer_size(c->client);
470 
471     qjack_client_connect_ports(c);
472     c->state = QJACK_STATE_RUNNING;
473     return 0;
474 }
475 
476 static int qjack_init_out(HWVoiceOut *hw, struct audsettings *as,
477     void *drv_opaque)
478 {
479     QJackOut *jo  = (QJackOut *)hw;
480     Audiodev *dev = (Audiodev *)drv_opaque;
481 
482     if (jo->c.state != QJACK_STATE_DISCONNECTED) {
483         return 0;
484     }
485 
486     jo->c.out       = true;
487     jo->c.nchannels = as->nchannels;
488     jo->c.opt       = dev->u.jack.out;
489     int ret = qjack_client_init(&jo->c);
490     if (ret != 0) {
491         return ret;
492     }
493 
494     /* report the buffer size to qemu */
495     hw->samples = jo->c.buffersize;
496 
497     /* report the audio format we support */
498     struct audsettings os = {
499         .freq       = jo->c.freq,
500         .nchannels  = jo->c.nchannels,
501         .fmt        = AUDIO_FORMAT_F32,
502         .endianness = 0
503     };
504     audio_pcm_init_info(&hw->info, &os);
505 
506     dolog("JACK output configured for %dHz (%d samples)\n",
507         jo->c.freq, jo->c.buffersize);
508 
509     return 0;
510 }
511 
512 static int qjack_init_in(HWVoiceIn *hw, struct audsettings *as,
513     void *drv_opaque)
514 {
515     QJackIn  *ji  = (QJackIn *)hw;
516     Audiodev *dev = (Audiodev *)drv_opaque;
517 
518     if (ji->c.state != QJACK_STATE_DISCONNECTED) {
519         return 0;
520     }
521 
522     ji->c.out       = false;
523     ji->c.nchannels = as->nchannels;
524     ji->c.opt       = dev->u.jack.in;
525     int ret = qjack_client_init(&ji->c);
526     if (ret != 0) {
527         return ret;
528     }
529 
530     /* report the buffer size to qemu */
531     hw->samples = ji->c.buffersize;
532 
533     /* report the audio format we support */
534     struct audsettings is = {
535         .freq       = ji->c.freq,
536         .nchannels  = ji->c.nchannels,
537         .fmt        = AUDIO_FORMAT_F32,
538         .endianness = 0
539     };
540     audio_pcm_init_info(&hw->info, &is);
541 
542     dolog("JACK input configured for %dHz (%d samples)\n",
543         ji->c.freq, ji->c.buffersize);
544 
545     return 0;
546 }
547 
548 static void qjack_client_fini(QJackClient *c)
549 {
550     switch (c->state) {
551     case QJACK_STATE_RUNNING:
552         /* fallthrough */
553 
554     case QJACK_STATE_STOPPED:
555         for (int i = 0; i < c->nchannels; ++i) {
556             jack_port_unregister(c->client, c->port[i]);
557         }
558         jack_deactivate(c->client);
559         /* fallthrough */
560 
561     case QJACK_STATE_SHUTDOWN:
562         jack_client_close(c->client);
563         /* fallthrough */
564 
565     case QJACK_STATE_DISCONNECTED:
566         break;
567     }
568 
569     qjack_buffer_free(&c->fifo);
570     g_free(c->port);
571 
572     c->state = QJACK_STATE_DISCONNECTED;
573 }
574 
575 static void qjack_fini_out(HWVoiceOut *hw)
576 {
577     QJackOut *jo = (QJackOut *)hw;
578     jo->c.finished = true;
579     qjack_client_fini(&jo->c);
580 }
581 
582 static void qjack_fini_in(HWVoiceIn *hw)
583 {
584     QJackIn *ji = (QJackIn *)hw;
585     ji->c.finished = true;
586     qjack_client_fini(&ji->c);
587 }
588 
589 static void qjack_enable_out(HWVoiceOut *hw, bool enable)
590 {
591 }
592 
593 static void qjack_enable_in(HWVoiceIn *hw, bool enable)
594 {
595 }
596 
597 static int qjack_thread_creator(jack_native_thread_t *thread,
598     const pthread_attr_t *attr, void *(*function)(void *), void *arg)
599 {
600     int ret = pthread_create(thread, attr, function, arg);
601     if (ret != 0) {
602         return ret;
603     }
604 
605     /* set the name of the thread */
606     pthread_setname_np(*thread, "jack-client");
607 
608     return ret;
609 }
610 
611 static void *qjack_init(Audiodev *dev)
612 {
613     assert(dev->driver == AUDIODEV_DRIVER_JACK);
614 
615     dev->u.jack.has_in = false;
616 
617     return dev;
618 }
619 
620 static void qjack_fini(void *opaque)
621 {
622 }
623 
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,
630 
631     .init_in        = qjack_init_in,
632     .fini_in        = qjack_fini_in,
633     .read           = qjack_read,
634     .enable_in      = qjack_enable_in
635 };
636 
637 static struct audio_driver jack_driver = {
638     .name           = "jack",
639     .descr          = "JACK Audio Connection Kit Client",
640     .init           = qjack_init,
641     .fini           = qjack_fini,
642     .pcm_ops        = &jack_pcm_ops,
643     .can_be_default = 1,
644     .max_voices_out = INT_MAX,
645     .max_voices_in  = INT_MAX,
646     .voice_size_out = sizeof(QJackOut),
647     .voice_size_in  = sizeof(QJackIn)
648 };
649 
650 static void qjack_error(const char *msg)
651 {
652     dolog("E: %s\n", msg);
653 }
654 
655 static void qjack_info(const char *msg)
656 {
657     dolog("I: %s\n", msg);
658 }
659 
660 static void register_audio_jack(void)
661 {
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);
666 }
667 type_init(register_audio_jack);
668