xref: /openbmc/qemu/audio/audio.c (revision 7520462bc1eeda2f724ec84ff16338053b728920)
1 /*
2  * QEMU Audio subsystem
3  *
4  * Copyright (c) 2003-2005 Vassili Karpov (malc)
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 "audio.h"
27 #include "migration/vmstate.h"
28 #include "monitor/monitor.h"
29 #include "qemu/timer.h"
30 #include "qapi/error.h"
31 #include "qapi/qobject-input-visitor.h"
32 #include "qapi/qapi-visit-audio.h"
33 #include "qemu/cutils.h"
34 #include "qemu/module.h"
35 #include "sysemu/replay.h"
36 #include "sysemu/runstate.h"
37 #include "trace.h"
38 
39 #define AUDIO_CAP "audio"
40 #include "audio_int.h"
41 
42 /* #define DEBUG_LIVE */
43 /* #define DEBUG_OUT */
44 /* #define DEBUG_CAPTURE */
45 /* #define DEBUG_POLL */
46 
47 #define SW_NAME(sw) (sw)->name ? (sw)->name : "unknown"
48 
49 
50 /* Order of CONFIG_AUDIO_DRIVERS is import.
51    The 1st one is the one used by default, that is the reason
52     that we generate the list.
53 */
54 const char *audio_prio_list[] = {
55     "spice",
56     CONFIG_AUDIO_DRIVERS
57     "none",
58     "wav",
59     NULL
60 };
61 
62 static QLIST_HEAD(, audio_driver) audio_drivers;
63 static AudiodevListHead audiodevs = QSIMPLEQ_HEAD_INITIALIZER(audiodevs);
64 
65 void audio_driver_register(audio_driver *drv)
66 {
67     QLIST_INSERT_HEAD(&audio_drivers, drv, next);
68 }
69 
70 audio_driver *audio_driver_lookup(const char *name)
71 {
72     struct audio_driver *d;
73 
74     QLIST_FOREACH(d, &audio_drivers, next) {
75         if (strcmp(name, d->name) == 0) {
76             return d;
77         }
78     }
79 
80     audio_module_load_one(name);
81     QLIST_FOREACH(d, &audio_drivers, next) {
82         if (strcmp(name, d->name) == 0) {
83             return d;
84         }
85     }
86 
87     return NULL;
88 }
89 
90 static QTAILQ_HEAD(AudioStateHead, AudioState) audio_states =
91     QTAILQ_HEAD_INITIALIZER(audio_states);
92 
93 const struct mixeng_volume nominal_volume = {
94     .mute = 0,
95 #ifdef FLOAT_MIXENG
96     .r = 1.0,
97     .l = 1.0,
98 #else
99     .r = 1ULL << 32,
100     .l = 1ULL << 32,
101 #endif
102 };
103 
104 static bool legacy_config = true;
105 
106 #ifdef AUDIO_IS_FLAWLESS_AND_NO_CHECKS_ARE_REQURIED
107 #error No its not
108 #else
109 int audio_bug (const char *funcname, int cond)
110 {
111     if (cond) {
112         static int shown;
113 
114         AUD_log (NULL, "A bug was just triggered in %s\n", funcname);
115         if (!shown) {
116             shown = 1;
117             AUD_log (NULL, "Save all your work and restart without audio\n");
118             AUD_log (NULL, "I am sorry\n");
119         }
120         AUD_log (NULL, "Context:\n");
121 
122 #if defined AUDIO_BREAKPOINT_ON_BUG
123 #  if defined HOST_I386
124 #    if defined __GNUC__
125         __asm__ ("int3");
126 #    elif defined _MSC_VER
127         _asm _emit 0xcc;
128 #    else
129         abort ();
130 #    endif
131 #  else
132         abort ();
133 #  endif
134 #endif
135     }
136 
137     return cond;
138 }
139 #endif
140 
141 static inline int audio_bits_to_index (int bits)
142 {
143     switch (bits) {
144     case 8:
145         return 0;
146 
147     case 16:
148         return 1;
149 
150     case 32:
151         return 2;
152 
153     default:
154         audio_bug ("bits_to_index", 1);
155         AUD_log (NULL, "invalid bits %d\n", bits);
156         return 0;
157     }
158 }
159 
160 void *audio_calloc (const char *funcname, int nmemb, size_t size)
161 {
162     int cond;
163     size_t len;
164 
165     len = nmemb * size;
166     cond = !nmemb || !size;
167     cond |= nmemb < 0;
168     cond |= len < size;
169 
170     if (audio_bug ("audio_calloc", cond)) {
171         AUD_log (NULL, "%s passed invalid arguments to audio_calloc\n",
172                  funcname);
173         AUD_log (NULL, "nmemb=%d size=%zu (len=%zu)\n", nmemb, size, len);
174         return NULL;
175     }
176 
177     return g_malloc0 (len);
178 }
179 
180 void AUD_vlog (const char *cap, const char *fmt, va_list ap)
181 {
182     if (cap) {
183         fprintf(stderr, "%s: ", cap);
184     }
185 
186     vfprintf(stderr, fmt, ap);
187 }
188 
189 void AUD_log (const char *cap, const char *fmt, ...)
190 {
191     va_list ap;
192 
193     va_start (ap, fmt);
194     AUD_vlog (cap, fmt, ap);
195     va_end (ap);
196 }
197 
198 static void audio_print_settings (struct audsettings *as)
199 {
200     dolog ("frequency=%d nchannels=%d fmt=", as->freq, as->nchannels);
201 
202     switch (as->fmt) {
203     case AUDIO_FORMAT_S8:
204         AUD_log (NULL, "S8");
205         break;
206     case AUDIO_FORMAT_U8:
207         AUD_log (NULL, "U8");
208         break;
209     case AUDIO_FORMAT_S16:
210         AUD_log (NULL, "S16");
211         break;
212     case AUDIO_FORMAT_U16:
213         AUD_log (NULL, "U16");
214         break;
215     case AUDIO_FORMAT_S32:
216         AUD_log (NULL, "S32");
217         break;
218     case AUDIO_FORMAT_U32:
219         AUD_log (NULL, "U32");
220         break;
221     default:
222         AUD_log (NULL, "invalid(%d)", as->fmt);
223         break;
224     }
225 
226     AUD_log (NULL, " endianness=");
227     switch (as->endianness) {
228     case 0:
229         AUD_log (NULL, "little");
230         break;
231     case 1:
232         AUD_log (NULL, "big");
233         break;
234     default:
235         AUD_log (NULL, "invalid");
236         break;
237     }
238     AUD_log (NULL, "\n");
239 }
240 
241 static int audio_validate_settings (struct audsettings *as)
242 {
243     int invalid;
244 
245     invalid = as->nchannels != 1 && as->nchannels != 2;
246     invalid |= as->endianness != 0 && as->endianness != 1;
247 
248     switch (as->fmt) {
249     case AUDIO_FORMAT_S8:
250     case AUDIO_FORMAT_U8:
251     case AUDIO_FORMAT_S16:
252     case AUDIO_FORMAT_U16:
253     case AUDIO_FORMAT_S32:
254     case AUDIO_FORMAT_U32:
255         break;
256     default:
257         invalid = 1;
258         break;
259     }
260 
261     invalid |= as->freq <= 0;
262     return invalid ? -1 : 0;
263 }
264 
265 static int audio_pcm_info_eq (struct audio_pcm_info *info, struct audsettings *as)
266 {
267     int bits = 8, sign = 0;
268 
269     switch (as->fmt) {
270     case AUDIO_FORMAT_S8:
271         sign = 1;
272         /* fall through */
273     case AUDIO_FORMAT_U8:
274         break;
275 
276     case AUDIO_FORMAT_S16:
277         sign = 1;
278         /* fall through */
279     case AUDIO_FORMAT_U16:
280         bits = 16;
281         break;
282 
283     case AUDIO_FORMAT_S32:
284         sign = 1;
285         /* fall through */
286     case AUDIO_FORMAT_U32:
287         bits = 32;
288         break;
289 
290     default:
291         abort();
292     }
293     return info->freq == as->freq
294         && info->nchannels == as->nchannels
295         && info->sign == sign
296         && info->bits == bits
297         && info->swap_endianness == (as->endianness != AUDIO_HOST_ENDIANNESS);
298 }
299 
300 void audio_pcm_init_info (struct audio_pcm_info *info, struct audsettings *as)
301 {
302     int bits = 8, sign = 0, shift = 0;
303 
304     switch (as->fmt) {
305     case AUDIO_FORMAT_S8:
306         sign = 1;
307     case AUDIO_FORMAT_U8:
308         break;
309 
310     case AUDIO_FORMAT_S16:
311         sign = 1;
312         /* fall through */
313     case AUDIO_FORMAT_U16:
314         bits = 16;
315         shift = 1;
316         break;
317 
318     case AUDIO_FORMAT_S32:
319         sign = 1;
320         /* fall through */
321     case AUDIO_FORMAT_U32:
322         bits = 32;
323         shift = 2;
324         break;
325 
326     default:
327         abort();
328     }
329 
330     info->freq = as->freq;
331     info->bits = bits;
332     info->sign = sign;
333     info->nchannels = as->nchannels;
334     info->shift = (as->nchannels == 2) + shift;
335     info->align = (1 << info->shift) - 1;
336     info->bytes_per_second = info->freq << info->shift;
337     info->swap_endianness = (as->endianness != AUDIO_HOST_ENDIANNESS);
338 }
339 
340 void audio_pcm_info_clear_buf (struct audio_pcm_info *info, void *buf, int len)
341 {
342     if (!len) {
343         return;
344     }
345 
346     if (info->sign) {
347         memset (buf, 0x00, len << info->shift);
348     }
349     else {
350         switch (info->bits) {
351         case 8:
352             memset (buf, 0x80, len << info->shift);
353             break;
354 
355         case 16:
356             {
357                 int i;
358                 uint16_t *p = buf;
359                 int shift = info->nchannels - 1;
360                 short s = INT16_MAX;
361 
362                 if (info->swap_endianness) {
363                     s = bswap16 (s);
364                 }
365 
366                 for (i = 0; i < len << shift; i++) {
367                     p[i] = s;
368                 }
369             }
370             break;
371 
372         case 32:
373             {
374                 int i;
375                 uint32_t *p = buf;
376                 int shift = info->nchannels - 1;
377                 int32_t s = INT32_MAX;
378 
379                 if (info->swap_endianness) {
380                     s = bswap32 (s);
381                 }
382 
383                 for (i = 0; i < len << shift; i++) {
384                     p[i] = s;
385                 }
386             }
387             break;
388 
389         default:
390             AUD_log (NULL, "audio_pcm_info_clear_buf: invalid bits %d\n",
391                      info->bits);
392             break;
393         }
394     }
395 }
396 
397 /*
398  * Capture
399  */
400 static void noop_conv (struct st_sample *dst, const void *src, int samples)
401 {
402     (void) src;
403     (void) dst;
404     (void) samples;
405 }
406 
407 static CaptureVoiceOut *audio_pcm_capture_find_specific(AudioState *s,
408                                                         struct audsettings *as)
409 {
410     CaptureVoiceOut *cap;
411 
412     for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
413         if (audio_pcm_info_eq (&cap->hw.info, as)) {
414             return cap;
415         }
416     }
417     return NULL;
418 }
419 
420 static void audio_notify_capture (CaptureVoiceOut *cap, audcnotification_e cmd)
421 {
422     struct capture_callback *cb;
423 
424 #ifdef DEBUG_CAPTURE
425     dolog ("notification %d sent\n", cmd);
426 #endif
427     for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
428         cb->ops.notify (cb->opaque, cmd);
429     }
430 }
431 
432 static void audio_capture_maybe_changed (CaptureVoiceOut *cap, int enabled)
433 {
434     if (cap->hw.enabled != enabled) {
435         audcnotification_e cmd;
436         cap->hw.enabled = enabled;
437         cmd = enabled ? AUD_CNOTIFY_ENABLE : AUD_CNOTIFY_DISABLE;
438         audio_notify_capture (cap, cmd);
439     }
440 }
441 
442 static void audio_recalc_and_notify_capture (CaptureVoiceOut *cap)
443 {
444     HWVoiceOut *hw = &cap->hw;
445     SWVoiceOut *sw;
446     int enabled = 0;
447 
448     for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
449         if (sw->active) {
450             enabled = 1;
451             break;
452         }
453     }
454     audio_capture_maybe_changed (cap, enabled);
455 }
456 
457 static void audio_detach_capture (HWVoiceOut *hw)
458 {
459     SWVoiceCap *sc = hw->cap_head.lh_first;
460 
461     while (sc) {
462         SWVoiceCap *sc1 = sc->entries.le_next;
463         SWVoiceOut *sw = &sc->sw;
464         CaptureVoiceOut *cap = sc->cap;
465         int was_active = sw->active;
466 
467         if (sw->rate) {
468             st_rate_stop (sw->rate);
469             sw->rate = NULL;
470         }
471 
472         QLIST_REMOVE (sw, entries);
473         QLIST_REMOVE (sc, entries);
474         g_free (sc);
475         if (was_active) {
476             /* We have removed soft voice from the capture:
477                this might have changed the overall status of the capture
478                since this might have been the only active voice */
479             audio_recalc_and_notify_capture (cap);
480         }
481         sc = sc1;
482     }
483 }
484 
485 static int audio_attach_capture (HWVoiceOut *hw)
486 {
487     AudioState *s = hw->s;
488     CaptureVoiceOut *cap;
489 
490     audio_detach_capture (hw);
491     for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
492         SWVoiceCap *sc;
493         SWVoiceOut *sw;
494         HWVoiceOut *hw_cap = &cap->hw;
495 
496         sc = g_malloc0(sizeof(*sc));
497 
498         sc->cap = cap;
499         sw = &sc->sw;
500         sw->hw = hw_cap;
501         sw->info = hw->info;
502         sw->empty = 1;
503         sw->active = hw->enabled;
504         sw->conv = noop_conv;
505         sw->ratio = ((int64_t) hw_cap->info.freq << 32) / sw->info.freq;
506         sw->vol = nominal_volume;
507         sw->rate = st_rate_start (sw->info.freq, hw_cap->info.freq);
508         if (!sw->rate) {
509             dolog ("Could not start rate conversion for `%s'\n", SW_NAME (sw));
510             g_free (sw);
511             return -1;
512         }
513         QLIST_INSERT_HEAD (&hw_cap->sw_head, sw, entries);
514         QLIST_INSERT_HEAD (&hw->cap_head, sc, entries);
515 #ifdef DEBUG_CAPTURE
516         sw->name = g_strdup_printf ("for %p %d,%d,%d",
517                                     hw, sw->info.freq, sw->info.bits,
518                                     sw->info.nchannels);
519         dolog ("Added %s active = %d\n", sw->name, sw->active);
520 #endif
521         if (sw->active) {
522             audio_capture_maybe_changed (cap, 1);
523         }
524     }
525     return 0;
526 }
527 
528 /*
529  * Hard voice (capture)
530  */
531 static size_t audio_pcm_hw_find_min_in (HWVoiceIn *hw)
532 {
533     SWVoiceIn *sw;
534     size_t m = hw->total_samples_captured;
535 
536     for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
537         if (sw->active) {
538             m = MIN (m, sw->total_hw_samples_acquired);
539         }
540     }
541     return m;
542 }
543 
544 size_t audio_pcm_hw_get_live_in(HWVoiceIn *hw)
545 {
546     size_t live = hw->total_samples_captured - audio_pcm_hw_find_min_in (hw);
547     if (audio_bug(__func__, live > hw->samples)) {
548         dolog("live=%zu hw->samples=%zu\n", live, hw->samples);
549         return 0;
550     }
551     return live;
552 }
553 
554 size_t audio_pcm_hw_clip_out(HWVoiceOut *hw, void *pcm_buf,
555                              size_t live, size_t pending)
556 {
557     size_t left = hw->samples - pending;
558     size_t len = MIN (left, live);
559     size_t clipped = 0;
560 
561     while (len) {
562         struct st_sample *src = hw->mix_buf + hw->rpos;
563         uint8_t *dst = advance (pcm_buf, hw->rpos << hw->info.shift);
564         size_t samples_till_end_of_buf = hw->samples - hw->rpos;
565         size_t samples_to_clip = MIN (len, samples_till_end_of_buf);
566 
567         hw->clip (dst, src, samples_to_clip);
568 
569         hw->rpos = (hw->rpos + samples_to_clip) % hw->samples;
570         len -= samples_to_clip;
571         clipped += samples_to_clip;
572     }
573     return clipped;
574 }
575 
576 /*
577  * Soft voice (capture)
578  */
579 static size_t audio_pcm_sw_get_rpos_in(SWVoiceIn *sw)
580 {
581     HWVoiceIn *hw = sw->hw;
582     ssize_t live = hw->total_samples_captured - sw->total_hw_samples_acquired;
583     ssize_t rpos;
584 
585     if (audio_bug(__func__, live < 0 || live > hw->samples)) {
586         dolog("live=%zu hw->samples=%zu\n", live, hw->samples);
587         return 0;
588     }
589 
590     rpos = hw->wpos - live;
591     if (rpos >= 0) {
592         return rpos;
593     }
594     else {
595         return hw->samples + rpos;
596     }
597 }
598 
599 static size_t audio_pcm_sw_read(SWVoiceIn *sw, void *buf, size_t size)
600 {
601     HWVoiceIn *hw = sw->hw;
602     size_t samples, live, ret = 0, swlim, isamp, osamp, rpos, total = 0;
603     struct st_sample *src, *dst = sw->buf;
604 
605     rpos = audio_pcm_sw_get_rpos_in (sw) % hw->samples;
606 
607     live = hw->total_samples_captured - sw->total_hw_samples_acquired;
608     if (audio_bug(__func__, live > hw->samples)) {
609         dolog("live_in=%zu hw->samples=%zu\n", live, hw->samples);
610         return 0;
611     }
612 
613     samples = size >> sw->info.shift;
614     if (!live) {
615         return 0;
616     }
617 
618     swlim = (live * sw->ratio) >> 32;
619     swlim = MIN (swlim, samples);
620 
621     while (swlim) {
622         src = hw->conv_buf + rpos;
623         if (hw->wpos > rpos) {
624             isamp = hw->wpos - rpos;
625         } else {
626             isamp = hw->samples - rpos;
627         }
628 
629         if (!isamp) {
630             break;
631         }
632         osamp = swlim;
633 
634         st_rate_flow (sw->rate, src, dst, &isamp, &osamp);
635         swlim -= osamp;
636         rpos = (rpos + isamp) % hw->samples;
637         dst += osamp;
638         ret += osamp;
639         total += isamp;
640     }
641 
642     if (!(hw->ctl_caps & VOICE_VOLUME_CAP)) {
643         mixeng_volume (sw->buf, ret, &sw->vol);
644     }
645 
646     sw->clip (buf, sw->buf, ret);
647     sw->total_hw_samples_acquired += total;
648     return ret << sw->info.shift;
649 }
650 
651 /*
652  * Hard voice (playback)
653  */
654 static size_t audio_pcm_hw_find_min_out (HWVoiceOut *hw, int *nb_livep)
655 {
656     SWVoiceOut *sw;
657     size_t m = SIZE_MAX;
658     int nb_live = 0;
659 
660     for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
661         if (sw->active || !sw->empty) {
662             m = MIN (m, sw->total_hw_samples_mixed);
663             nb_live += 1;
664         }
665     }
666 
667     *nb_livep = nb_live;
668     return m;
669 }
670 
671 static size_t audio_pcm_hw_get_live_out (HWVoiceOut *hw, int *nb_live)
672 {
673     size_t smin;
674     int nb_live1;
675 
676     smin = audio_pcm_hw_find_min_out (hw, &nb_live1);
677     if (nb_live) {
678         *nb_live = nb_live1;
679     }
680 
681     if (nb_live1) {
682         size_t live = smin;
683 
684         if (audio_bug(__func__, live > hw->samples)) {
685             dolog("live=%zu hw->samples=%zu\n", live, hw->samples);
686             return 0;
687         }
688         return live;
689     }
690     return 0;
691 }
692 
693 /*
694  * Soft voice (playback)
695  */
696 static size_t audio_pcm_sw_write(SWVoiceOut *sw, void *buf, size_t size)
697 {
698     size_t hwsamples, samples, isamp, osamp, wpos, live, dead, left, swlim, blck;
699     size_t ret = 0, pos = 0, total = 0;
700 
701     if (!sw) {
702         return size;
703     }
704 
705     hwsamples = sw->hw->samples;
706 
707     live = sw->total_hw_samples_mixed;
708     if (audio_bug(__func__, live > hwsamples)) {
709         dolog("live=%zu hw->samples=%zu\n", live, hwsamples);
710         return 0;
711     }
712 
713     if (live == hwsamples) {
714 #ifdef DEBUG_OUT
715         dolog ("%s is full %d\n", sw->name, live);
716 #endif
717         return 0;
718     }
719 
720     wpos = (sw->hw->rpos + live) % hwsamples;
721     samples = size >> sw->info.shift;
722 
723     dead = hwsamples - live;
724     swlim = ((int64_t) dead << 32) / sw->ratio;
725     swlim = MIN (swlim, samples);
726     if (swlim) {
727         sw->conv (sw->buf, buf, swlim);
728 
729         if (!(sw->hw->ctl_caps & VOICE_VOLUME_CAP)) {
730             mixeng_volume (sw->buf, swlim, &sw->vol);
731         }
732     }
733 
734     while (swlim) {
735         dead = hwsamples - live;
736         left = hwsamples - wpos;
737         blck = MIN (dead, left);
738         if (!blck) {
739             break;
740         }
741         isamp = swlim;
742         osamp = blck;
743         st_rate_flow_mix (
744             sw->rate,
745             sw->buf + pos,
746             sw->hw->mix_buf + wpos,
747             &isamp,
748             &osamp
749             );
750         ret += isamp;
751         swlim -= isamp;
752         pos += isamp;
753         live += osamp;
754         wpos = (wpos + osamp) % hwsamples;
755         total += osamp;
756     }
757 
758     sw->total_hw_samples_mixed += total;
759     sw->empty = sw->total_hw_samples_mixed == 0;
760 
761 #ifdef DEBUG_OUT
762     dolog (
763         "%s: write size %zu ret %zu total sw %zu\n",
764         SW_NAME (sw),
765         size >> sw->info.shift,
766         ret,
767         sw->total_hw_samples_mixed
768         );
769 #endif
770 
771     return ret << sw->info.shift;
772 }
773 
774 #ifdef DEBUG_AUDIO
775 static void audio_pcm_print_info (const char *cap, struct audio_pcm_info *info)
776 {
777     dolog ("%s: bits %d, sign %d, freq %d, nchan %d\n",
778            cap, info->bits, info->sign, info->freq, info->nchannels);
779 }
780 #endif
781 
782 #define DAC
783 #include "audio_template.h"
784 #undef DAC
785 #include "audio_template.h"
786 
787 /*
788  * Timer
789  */
790 static int audio_is_timer_needed(AudioState *s)
791 {
792     HWVoiceIn *hwi = NULL;
793     HWVoiceOut *hwo = NULL;
794 
795     while ((hwo = audio_pcm_hw_find_any_enabled_out(s, hwo))) {
796         if (!hwo->poll_mode) return 1;
797     }
798     while ((hwi = audio_pcm_hw_find_any_enabled_in(s, hwi))) {
799         if (!hwi->poll_mode) return 1;
800     }
801     return 0;
802 }
803 
804 static void audio_reset_timer (AudioState *s)
805 {
806     if (audio_is_timer_needed(s)) {
807         timer_mod_anticipate_ns(s->ts,
808             qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + s->period_ticks);
809         if (!s->timer_running) {
810             s->timer_running = true;
811             s->timer_last = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
812             trace_audio_timer_start(s->period_ticks / SCALE_MS);
813         }
814     } else {
815         timer_del(s->ts);
816         if (s->timer_running) {
817             s->timer_running = false;
818             trace_audio_timer_stop();
819         }
820     }
821 }
822 
823 static void audio_timer (void *opaque)
824 {
825     int64_t now, diff;
826     AudioState *s = opaque;
827 
828     now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
829     diff = now - s->timer_last;
830     if (diff > s->period_ticks * 3 / 2) {
831         trace_audio_timer_delayed(diff / SCALE_MS);
832     }
833     s->timer_last = now;
834 
835     audio_run(s, "timer");
836     audio_reset_timer(s);
837 }
838 
839 /*
840  * Public API
841  */
842 size_t AUD_write(SWVoiceOut *sw, void *buf, size_t size)
843 {
844     if (!sw) {
845         /* XXX: Consider options */
846         return size;
847     }
848 
849     if (!sw->hw->enabled) {
850         dolog ("Writing to disabled voice %s\n", SW_NAME (sw));
851         return 0;
852     }
853 
854     return audio_pcm_sw_write(sw, buf, size);
855 }
856 
857 size_t AUD_read(SWVoiceIn *sw, void *buf, size_t size)
858 {
859     if (!sw) {
860         /* XXX: Consider options */
861         return size;
862     }
863 
864     if (!sw->hw->enabled) {
865         dolog ("Reading from disabled voice %s\n", SW_NAME (sw));
866         return 0;
867     }
868 
869     return audio_pcm_sw_read(sw, buf, size);
870 }
871 
872 int AUD_get_buffer_size_out (SWVoiceOut *sw)
873 {
874     return sw->hw->samples << sw->hw->info.shift;
875 }
876 
877 void AUD_set_active_out (SWVoiceOut *sw, int on)
878 {
879     HWVoiceOut *hw;
880 
881     if (!sw) {
882         return;
883     }
884 
885     hw = sw->hw;
886     if (sw->active != on) {
887         AudioState *s = sw->s;
888         SWVoiceOut *temp_sw;
889         SWVoiceCap *sc;
890 
891         if (on) {
892             hw->pending_disable = 0;
893             if (!hw->enabled) {
894                 hw->enabled = 1;
895                 if (s->vm_running) {
896                     hw->pcm_ops->ctl_out(hw, VOICE_ENABLE);
897                     audio_reset_timer (s);
898                 }
899             }
900         }
901         else {
902             if (hw->enabled) {
903                 int nb_active = 0;
904 
905                 for (temp_sw = hw->sw_head.lh_first; temp_sw;
906                      temp_sw = temp_sw->entries.le_next) {
907                     nb_active += temp_sw->active != 0;
908                 }
909 
910                 hw->pending_disable = nb_active == 1;
911             }
912         }
913 
914         for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
915             sc->sw.active = hw->enabled;
916             if (hw->enabled) {
917                 audio_capture_maybe_changed (sc->cap, 1);
918             }
919         }
920         sw->active = on;
921     }
922 }
923 
924 void AUD_set_active_in (SWVoiceIn *sw, int on)
925 {
926     HWVoiceIn *hw;
927 
928     if (!sw) {
929         return;
930     }
931 
932     hw = sw->hw;
933     if (sw->active != on) {
934         AudioState *s = sw->s;
935         SWVoiceIn *temp_sw;
936 
937         if (on) {
938             if (!hw->enabled) {
939                 hw->enabled = 1;
940                 if (s->vm_running) {
941                     hw->pcm_ops->ctl_in(hw, VOICE_ENABLE);
942                     audio_reset_timer (s);
943                 }
944             }
945             sw->total_hw_samples_acquired = hw->total_samples_captured;
946         }
947         else {
948             if (hw->enabled) {
949                 int nb_active = 0;
950 
951                 for (temp_sw = hw->sw_head.lh_first; temp_sw;
952                      temp_sw = temp_sw->entries.le_next) {
953                     nb_active += temp_sw->active != 0;
954                 }
955 
956                 if (nb_active == 1) {
957                     hw->enabled = 0;
958                     hw->pcm_ops->ctl_in (hw, VOICE_DISABLE);
959                 }
960             }
961         }
962         sw->active = on;
963     }
964 }
965 
966 static size_t audio_get_avail (SWVoiceIn *sw)
967 {
968     size_t live;
969 
970     if (!sw) {
971         return 0;
972     }
973 
974     live = sw->hw->total_samples_captured - sw->total_hw_samples_acquired;
975     if (audio_bug(__func__, live > sw->hw->samples)) {
976         dolog("live=%zu sw->hw->samples=%zu\n", live, sw->hw->samples);
977         return 0;
978     }
979 
980     ldebug (
981         "%s: get_avail live %d ret %" PRId64 "\n",
982         SW_NAME (sw),
983         live, (((int64_t) live << 32) / sw->ratio) << sw->info.shift
984         );
985 
986     return (((int64_t) live << 32) / sw->ratio) << sw->info.shift;
987 }
988 
989 static size_t audio_get_free(SWVoiceOut *sw)
990 {
991     size_t live, dead;
992 
993     if (!sw) {
994         return 0;
995     }
996 
997     live = sw->total_hw_samples_mixed;
998 
999     if (audio_bug(__func__, live > sw->hw->samples)) {
1000         dolog("live=%zu sw->hw->samples=%zu\n", live, sw->hw->samples);
1001         return 0;
1002     }
1003 
1004     dead = sw->hw->samples - live;
1005 
1006 #ifdef DEBUG_OUT
1007     dolog ("%s: get_free live %d dead %d ret %" PRId64 "\n",
1008            SW_NAME (sw),
1009            live, dead, (((int64_t) dead << 32) / sw->ratio) << sw->info.shift);
1010 #endif
1011 
1012     return (((int64_t) dead << 32) / sw->ratio) << sw->info.shift;
1013 }
1014 
1015 static void audio_capture_mix_and_clear(HWVoiceOut *hw, size_t rpos,
1016                                         size_t samples)
1017 {
1018     size_t n;
1019 
1020     if (hw->enabled) {
1021         SWVoiceCap *sc;
1022 
1023         for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
1024             SWVoiceOut *sw = &sc->sw;
1025             int rpos2 = rpos;
1026 
1027             n = samples;
1028             while (n) {
1029                 size_t till_end_of_hw = hw->samples - rpos2;
1030                 size_t to_write = MIN(till_end_of_hw, n);
1031                 size_t bytes = to_write << hw->info.shift;
1032                 size_t written;
1033 
1034                 sw->buf = hw->mix_buf + rpos2;
1035                 written = audio_pcm_sw_write (sw, NULL, bytes);
1036                 if (written - bytes) {
1037                     dolog("Could not mix %zu bytes into a capture "
1038                           "buffer, mixed %zu\n",
1039                           bytes, written);
1040                     break;
1041                 }
1042                 n -= to_write;
1043                 rpos2 = (rpos2 + to_write) % hw->samples;
1044             }
1045         }
1046     }
1047 
1048     n = MIN(samples, hw->samples - rpos);
1049     mixeng_clear(hw->mix_buf + rpos, n);
1050     mixeng_clear(hw->mix_buf, samples - n);
1051 }
1052 
1053 static void audio_run_out (AudioState *s)
1054 {
1055     HWVoiceOut *hw = NULL;
1056     SWVoiceOut *sw;
1057 
1058     while ((hw = audio_pcm_hw_find_any_enabled_out(s, hw))) {
1059         size_t played, live, prev_rpos, free;
1060         int nb_live, cleanup_required;
1061 
1062         live = audio_pcm_hw_get_live_out (hw, &nb_live);
1063         if (!nb_live) {
1064             live = 0;
1065         }
1066 
1067         if (audio_bug(__func__, live > hw->samples)) {
1068             dolog ("live=%zu hw->samples=%zu\n", live, hw->samples);
1069             continue;
1070         }
1071 
1072         if (hw->pending_disable && !nb_live) {
1073             SWVoiceCap *sc;
1074 #ifdef DEBUG_OUT
1075             dolog ("Disabling voice\n");
1076 #endif
1077             hw->enabled = 0;
1078             hw->pending_disable = 0;
1079             hw->pcm_ops->ctl_out (hw, VOICE_DISABLE);
1080             for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
1081                 sc->sw.active = 0;
1082                 audio_recalc_and_notify_capture (sc->cap);
1083             }
1084             continue;
1085         }
1086 
1087         if (!live) {
1088             for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1089                 if (sw->active) {
1090                     free = audio_get_free (sw);
1091                     if (free > 0) {
1092                         sw->callback.fn (sw->callback.opaque, free);
1093                     }
1094                 }
1095             }
1096             continue;
1097         }
1098 
1099         prev_rpos = hw->rpos;
1100         played = hw->pcm_ops->run_out (hw, live);
1101         replay_audio_out(&played);
1102         if (audio_bug(__func__, hw->rpos >= hw->samples)) {
1103             dolog("hw->rpos=%zu hw->samples=%zu played=%zu\n",
1104                   hw->rpos, hw->samples, played);
1105             hw->rpos = 0;
1106         }
1107 
1108 #ifdef DEBUG_OUT
1109         dolog("played=%zu\n", played);
1110 #endif
1111 
1112         if (played) {
1113             hw->ts_helper += played;
1114             audio_capture_mix_and_clear (hw, prev_rpos, played);
1115         }
1116 
1117         cleanup_required = 0;
1118         for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1119             if (!sw->active && sw->empty) {
1120                 continue;
1121             }
1122 
1123             if (audio_bug(__func__, played > sw->total_hw_samples_mixed)) {
1124                 dolog("played=%zu sw->total_hw_samples_mixed=%zu\n",
1125                       played, sw->total_hw_samples_mixed);
1126                 played = sw->total_hw_samples_mixed;
1127             }
1128 
1129             sw->total_hw_samples_mixed -= played;
1130 
1131             if (!sw->total_hw_samples_mixed) {
1132                 sw->empty = 1;
1133                 cleanup_required |= !sw->active && !sw->callback.fn;
1134             }
1135 
1136             if (sw->active) {
1137                 free = audio_get_free (sw);
1138                 if (free > 0) {
1139                     sw->callback.fn (sw->callback.opaque, free);
1140                 }
1141             }
1142         }
1143 
1144         if (cleanup_required) {
1145             SWVoiceOut *sw1;
1146 
1147             sw = hw->sw_head.lh_first;
1148             while (sw) {
1149                 sw1 = sw->entries.le_next;
1150                 if (!sw->active && !sw->callback.fn) {
1151                     audio_close_out (sw);
1152                 }
1153                 sw = sw1;
1154             }
1155         }
1156     }
1157 }
1158 
1159 static void audio_run_in (AudioState *s)
1160 {
1161     HWVoiceIn *hw = NULL;
1162 
1163     while ((hw = audio_pcm_hw_find_any_enabled_in(s, hw))) {
1164         SWVoiceIn *sw;
1165         size_t captured = 0, min;
1166 
1167         if (replay_mode != REPLAY_MODE_PLAY) {
1168             captured = hw->pcm_ops->run_in(hw);
1169         }
1170         replay_audio_in(&captured, hw->conv_buf, &hw->wpos, hw->samples);
1171 
1172         min = audio_pcm_hw_find_min_in (hw);
1173         hw->total_samples_captured += captured - min;
1174         hw->ts_helper += captured;
1175 
1176         for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1177             sw->total_hw_samples_acquired -= min;
1178 
1179             if (sw->active) {
1180                 size_t avail;
1181 
1182                 avail = audio_get_avail (sw);
1183                 if (avail > 0) {
1184                     sw->callback.fn (sw->callback.opaque, avail);
1185                 }
1186             }
1187         }
1188     }
1189 }
1190 
1191 static void audio_run_capture (AudioState *s)
1192 {
1193     CaptureVoiceOut *cap;
1194 
1195     for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
1196         size_t live, rpos, captured;
1197         HWVoiceOut *hw = &cap->hw;
1198         SWVoiceOut *sw;
1199 
1200         captured = live = audio_pcm_hw_get_live_out (hw, NULL);
1201         rpos = hw->rpos;
1202         while (live) {
1203             size_t left = hw->samples - rpos;
1204             size_t to_capture = MIN(live, left);
1205             struct st_sample *src;
1206             struct capture_callback *cb;
1207 
1208             src = hw->mix_buf + rpos;
1209             hw->clip (cap->buf, src, to_capture);
1210             mixeng_clear (src, to_capture);
1211 
1212             for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
1213                 cb->ops.capture (cb->opaque, cap->buf,
1214                                  to_capture << hw->info.shift);
1215             }
1216             rpos = (rpos + to_capture) % hw->samples;
1217             live -= to_capture;
1218         }
1219         hw->rpos = rpos;
1220 
1221         for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1222             if (!sw->active && sw->empty) {
1223                 continue;
1224             }
1225 
1226             if (audio_bug(__func__, captured > sw->total_hw_samples_mixed)) {
1227                 dolog("captured=%zu sw->total_hw_samples_mixed=%zu\n",
1228                       captured, sw->total_hw_samples_mixed);
1229                 captured = sw->total_hw_samples_mixed;
1230             }
1231 
1232             sw->total_hw_samples_mixed -= captured;
1233             sw->empty = sw->total_hw_samples_mixed == 0;
1234         }
1235     }
1236 }
1237 
1238 void audio_run(AudioState *s, const char *msg)
1239 {
1240     audio_run_out(s);
1241     audio_run_in(s);
1242     audio_run_capture(s);
1243 
1244 #ifdef DEBUG_POLL
1245     {
1246         static double prevtime;
1247         double currtime;
1248         struct timeval tv;
1249 
1250         if (gettimeofday (&tv, NULL)) {
1251             perror ("audio_run: gettimeofday");
1252             return;
1253         }
1254 
1255         currtime = tv.tv_sec + tv.tv_usec * 1e-6;
1256         dolog ("Elapsed since last %s: %f\n", msg, currtime - prevtime);
1257         prevtime = currtime;
1258     }
1259 #endif
1260 }
1261 
1262 static int audio_driver_init(AudioState *s, struct audio_driver *drv,
1263                              bool msg, Audiodev *dev)
1264 {
1265     s->drv_opaque = drv->init(dev);
1266 
1267     if (s->drv_opaque) {
1268         audio_init_nb_voices_out(s, drv);
1269         audio_init_nb_voices_in(s, drv);
1270         s->drv = drv;
1271         return 0;
1272     }
1273     else {
1274         if (msg) {
1275             dolog("Could not init `%s' audio driver\n", drv->name);
1276         }
1277         return -1;
1278     }
1279 }
1280 
1281 static void audio_vm_change_state_handler (void *opaque, int running,
1282                                            RunState state)
1283 {
1284     AudioState *s = opaque;
1285     HWVoiceOut *hwo = NULL;
1286     HWVoiceIn *hwi = NULL;
1287     int op = running ? VOICE_ENABLE : VOICE_DISABLE;
1288 
1289     s->vm_running = running;
1290     while ((hwo = audio_pcm_hw_find_any_enabled_out(s, hwo))) {
1291         hwo->pcm_ops->ctl_out(hwo, op);
1292     }
1293 
1294     while ((hwi = audio_pcm_hw_find_any_enabled_in(s, hwi))) {
1295         hwi->pcm_ops->ctl_in(hwi, op);
1296     }
1297     audio_reset_timer (s);
1298 }
1299 
1300 static bool is_cleaning_up;
1301 
1302 bool audio_is_cleaning_up(void)
1303 {
1304     return is_cleaning_up;
1305 }
1306 
1307 static void free_audio_state(AudioState *s)
1308 {
1309     HWVoiceOut *hwo, *hwon;
1310     HWVoiceIn *hwi, *hwin;
1311 
1312     QLIST_FOREACH_SAFE(hwo, &s->hw_head_out, entries, hwon) {
1313         SWVoiceCap *sc;
1314 
1315         if (hwo->enabled) {
1316             hwo->pcm_ops->ctl_out (hwo, VOICE_DISABLE);
1317         }
1318         hwo->pcm_ops->fini_out (hwo);
1319 
1320         for (sc = hwo->cap_head.lh_first; sc; sc = sc->entries.le_next) {
1321             CaptureVoiceOut *cap = sc->cap;
1322             struct capture_callback *cb;
1323 
1324             for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
1325                 cb->ops.destroy (cb->opaque);
1326             }
1327         }
1328         QLIST_REMOVE(hwo, entries);
1329     }
1330 
1331     QLIST_FOREACH_SAFE(hwi, &s->hw_head_in, entries, hwin) {
1332         if (hwi->enabled) {
1333             hwi->pcm_ops->ctl_in (hwi, VOICE_DISABLE);
1334         }
1335         hwi->pcm_ops->fini_in (hwi);
1336         QLIST_REMOVE(hwi, entries);
1337     }
1338 
1339     if (s->drv) {
1340         s->drv->fini (s->drv_opaque);
1341         s->drv = NULL;
1342     }
1343 
1344     if (s->dev) {
1345         qapi_free_Audiodev(s->dev);
1346         s->dev = NULL;
1347     }
1348     g_free(s);
1349 }
1350 
1351 void audio_cleanup(void)
1352 {
1353     is_cleaning_up = true;
1354     while (!QTAILQ_EMPTY(&audio_states)) {
1355         AudioState *s = QTAILQ_FIRST(&audio_states);
1356         QTAILQ_REMOVE(&audio_states, s, list);
1357         free_audio_state(s);
1358     }
1359 }
1360 
1361 static const VMStateDescription vmstate_audio = {
1362     .name = "audio",
1363     .version_id = 1,
1364     .minimum_version_id = 1,
1365     .fields = (VMStateField[]) {
1366         VMSTATE_END_OF_LIST()
1367     }
1368 };
1369 
1370 static void audio_validate_opts(Audiodev *dev, Error **errp);
1371 
1372 static AudiodevListEntry *audiodev_find(
1373     AudiodevListHead *head, const char *drvname)
1374 {
1375     AudiodevListEntry *e;
1376     QSIMPLEQ_FOREACH(e, head, next) {
1377         if (strcmp(AudiodevDriver_str(e->dev->driver), drvname) == 0) {
1378             return e;
1379         }
1380     }
1381 
1382     return NULL;
1383 }
1384 
1385 /*
1386  * if we have dev, this function was called because of an -audiodev argument =>
1387  *   initialize a new state with it
1388  * if dev == NULL => legacy implicit initialization, return the already created
1389  *   state or create a new one
1390  */
1391 static AudioState *audio_init(Audiodev *dev, const char *name)
1392 {
1393     static bool atexit_registered;
1394     size_t i;
1395     int done = 0;
1396     const char *drvname = NULL;
1397     VMChangeStateEntry *e;
1398     AudioState *s;
1399     struct audio_driver *driver;
1400     /* silence gcc warning about uninitialized variable */
1401     AudiodevListHead head = QSIMPLEQ_HEAD_INITIALIZER(head);
1402 
1403     if (dev) {
1404         /* -audiodev option */
1405         legacy_config = false;
1406         drvname = AudiodevDriver_str(dev->driver);
1407     } else if (!QTAILQ_EMPTY(&audio_states)) {
1408         if (!legacy_config) {
1409             dolog("You must specify an audiodev= for the device %s\n", name);
1410             exit(1);
1411         }
1412         return QTAILQ_FIRST(&audio_states);
1413     } else {
1414         /* legacy implicit initialization */
1415         head = audio_handle_legacy_opts();
1416         /*
1417          * In case of legacy initialization, all Audiodevs in the list will have
1418          * the same configuration (except the driver), so it does't matter which
1419          * one we chose.  We need an Audiodev to set up AudioState before we can
1420          * init a driver.  Also note that dev at this point is still in the
1421          * list.
1422          */
1423         dev = QSIMPLEQ_FIRST(&head)->dev;
1424         audio_validate_opts(dev, &error_abort);
1425     }
1426 
1427     s = g_malloc0(sizeof(AudioState));
1428     s->dev = dev;
1429 
1430     QLIST_INIT (&s->hw_head_out);
1431     QLIST_INIT (&s->hw_head_in);
1432     QLIST_INIT (&s->cap_head);
1433     if (!atexit_registered) {
1434         atexit(audio_cleanup);
1435         atexit_registered = true;
1436     }
1437     QTAILQ_INSERT_TAIL(&audio_states, s, list);
1438 
1439     s->ts = timer_new_ns(QEMU_CLOCK_VIRTUAL, audio_timer, s);
1440 
1441     s->nb_hw_voices_out = audio_get_pdo_out(dev)->voices;
1442     s->nb_hw_voices_in = audio_get_pdo_in(dev)->voices;
1443 
1444     if (s->nb_hw_voices_out <= 0) {
1445         dolog ("Bogus number of playback voices %d, setting to 1\n",
1446                s->nb_hw_voices_out);
1447         s->nb_hw_voices_out = 1;
1448     }
1449 
1450     if (s->nb_hw_voices_in <= 0) {
1451         dolog ("Bogus number of capture voices %d, setting to 0\n",
1452                s->nb_hw_voices_in);
1453         s->nb_hw_voices_in = 0;
1454     }
1455 
1456     if (drvname) {
1457         driver = audio_driver_lookup(drvname);
1458         if (driver) {
1459             done = !audio_driver_init(s, driver, true, dev);
1460         } else {
1461             dolog ("Unknown audio driver `%s'\n", drvname);
1462         }
1463     } else {
1464         for (i = 0; audio_prio_list[i]; i++) {
1465             AudiodevListEntry *e = audiodev_find(&head, audio_prio_list[i]);
1466             driver = audio_driver_lookup(audio_prio_list[i]);
1467 
1468             if (e && driver) {
1469                 s->dev = dev = e->dev;
1470                 audio_validate_opts(dev, &error_abort);
1471                 done = !audio_driver_init(s, driver, false, dev);
1472                 if (done) {
1473                     e->dev = NULL;
1474                     break;
1475                 }
1476             }
1477         }
1478     }
1479     audio_free_audiodev_list(&head);
1480 
1481     if (!done) {
1482         driver = audio_driver_lookup("none");
1483         done = !audio_driver_init(s, driver, false, dev);
1484         assert(done);
1485         dolog("warning: Using timer based audio emulation\n");
1486     }
1487 
1488     if (dev->timer_period <= 0) {
1489         s->period_ticks = 1;
1490     } else {
1491         s->period_ticks = dev->timer_period * SCALE_US;
1492     }
1493 
1494     e = qemu_add_vm_change_state_handler (audio_vm_change_state_handler, s);
1495     if (!e) {
1496         dolog ("warning: Could not register change state handler\n"
1497                "(Audio can continue looping even after stopping the VM)\n");
1498     }
1499 
1500     QLIST_INIT (&s->card_head);
1501     vmstate_register (NULL, 0, &vmstate_audio, s);
1502     return s;
1503 }
1504 
1505 void audio_free_audiodev_list(AudiodevListHead *head)
1506 {
1507     AudiodevListEntry *e;
1508     while ((e = QSIMPLEQ_FIRST(head))) {
1509         QSIMPLEQ_REMOVE_HEAD(head, next);
1510         qapi_free_Audiodev(e->dev);
1511         g_free(e);
1512     }
1513 }
1514 
1515 void AUD_register_card (const char *name, QEMUSoundCard *card)
1516 {
1517     if (!card->state) {
1518         card->state = audio_init(NULL, name);
1519     }
1520 
1521     card->name = g_strdup (name);
1522     memset (&card->entries, 0, sizeof (card->entries));
1523     QLIST_INSERT_HEAD(&card->state->card_head, card, entries);
1524 }
1525 
1526 void AUD_remove_card (QEMUSoundCard *card)
1527 {
1528     QLIST_REMOVE (card, entries);
1529     g_free (card->name);
1530 }
1531 
1532 
1533 CaptureVoiceOut *AUD_add_capture(
1534     AudioState *s,
1535     struct audsettings *as,
1536     struct audio_capture_ops *ops,
1537     void *cb_opaque
1538     )
1539 {
1540     CaptureVoiceOut *cap;
1541     struct capture_callback *cb;
1542 
1543     if (!s) {
1544         if (!legacy_config) {
1545             dolog("You must specify audiodev when trying to capture\n");
1546             return NULL;
1547         }
1548         s = audio_init(NULL, NULL);
1549     }
1550 
1551     if (audio_validate_settings (as)) {
1552         dolog ("Invalid settings were passed when trying to add capture\n");
1553         audio_print_settings (as);
1554         return NULL;
1555     }
1556 
1557     cb = g_malloc0(sizeof(*cb));
1558     cb->ops = *ops;
1559     cb->opaque = cb_opaque;
1560 
1561     cap = audio_pcm_capture_find_specific(s, as);
1562     if (cap) {
1563         QLIST_INSERT_HEAD (&cap->cb_head, cb, entries);
1564         return cap;
1565     }
1566     else {
1567         HWVoiceOut *hw;
1568         CaptureVoiceOut *cap;
1569 
1570         cap = g_malloc0(sizeof(*cap));
1571 
1572         hw = &cap->hw;
1573         hw->s = s;
1574         QLIST_INIT (&hw->sw_head);
1575         QLIST_INIT (&cap->cb_head);
1576 
1577         /* XXX find a more elegant way */
1578         hw->samples = 4096 * 4;
1579         hw->mix_buf = g_new0(struct st_sample, hw->samples);
1580 
1581         audio_pcm_init_info (&hw->info, as);
1582 
1583         cap->buf = g_malloc0_n(hw->samples, 1 << hw->info.shift);
1584 
1585         hw->clip = mixeng_clip
1586             [hw->info.nchannels == 2]
1587             [hw->info.sign]
1588             [hw->info.swap_endianness]
1589             [audio_bits_to_index (hw->info.bits)];
1590 
1591         QLIST_INSERT_HEAD (&s->cap_head, cap, entries);
1592         QLIST_INSERT_HEAD (&cap->cb_head, cb, entries);
1593 
1594         QLIST_FOREACH(hw, &s->hw_head_out, entries) {
1595             audio_attach_capture (hw);
1596         }
1597         return cap;
1598     }
1599 }
1600 
1601 void AUD_del_capture (CaptureVoiceOut *cap, void *cb_opaque)
1602 {
1603     struct capture_callback *cb;
1604 
1605     for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
1606         if (cb->opaque == cb_opaque) {
1607             cb->ops.destroy (cb_opaque);
1608             QLIST_REMOVE (cb, entries);
1609             g_free (cb);
1610 
1611             if (!cap->cb_head.lh_first) {
1612                 SWVoiceOut *sw = cap->hw.sw_head.lh_first, *sw1;
1613 
1614                 while (sw) {
1615                     SWVoiceCap *sc = (SWVoiceCap *) sw;
1616 #ifdef DEBUG_CAPTURE
1617                     dolog ("freeing %s\n", sw->name);
1618 #endif
1619 
1620                     sw1 = sw->entries.le_next;
1621                     if (sw->rate) {
1622                         st_rate_stop (sw->rate);
1623                         sw->rate = NULL;
1624                     }
1625                     QLIST_REMOVE (sw, entries);
1626                     QLIST_REMOVE (sc, entries);
1627                     g_free (sc);
1628                     sw = sw1;
1629                 }
1630                 QLIST_REMOVE (cap, entries);
1631                 g_free (cap->hw.mix_buf);
1632                 g_free (cap->buf);
1633                 g_free (cap);
1634             }
1635             return;
1636         }
1637     }
1638 }
1639 
1640 void AUD_set_volume_out (SWVoiceOut *sw, int mute, uint8_t lvol, uint8_t rvol)
1641 {
1642     if (sw) {
1643         HWVoiceOut *hw = sw->hw;
1644 
1645         sw->vol.mute = mute;
1646         sw->vol.l = nominal_volume.l * lvol / 255;
1647         sw->vol.r = nominal_volume.r * rvol / 255;
1648 
1649         if (hw->pcm_ops->ctl_out) {
1650             hw->pcm_ops->ctl_out (hw, VOICE_VOLUME, sw);
1651         }
1652     }
1653 }
1654 
1655 void AUD_set_volume_in (SWVoiceIn *sw, int mute, uint8_t lvol, uint8_t rvol)
1656 {
1657     if (sw) {
1658         HWVoiceIn *hw = sw->hw;
1659 
1660         sw->vol.mute = mute;
1661         sw->vol.l = nominal_volume.l * lvol / 255;
1662         sw->vol.r = nominal_volume.r * rvol / 255;
1663 
1664         if (hw->pcm_ops->ctl_in) {
1665             hw->pcm_ops->ctl_in (hw, VOICE_VOLUME, sw);
1666         }
1667     }
1668 }
1669 
1670 void audio_create_pdos(Audiodev *dev)
1671 {
1672     switch (dev->driver) {
1673 #define CASE(DRIVER, driver, pdo_name)                              \
1674     case AUDIODEV_DRIVER_##DRIVER:                                  \
1675         if (!dev->u.driver.has_in) {                                \
1676             dev->u.driver.in = g_malloc0(                           \
1677                 sizeof(Audiodev##pdo_name##PerDirectionOptions));   \
1678             dev->u.driver.has_in = true;                            \
1679         }                                                           \
1680         if (!dev->u.driver.has_out) {                               \
1681             dev->u.driver.out = g_malloc0(                          \
1682                 sizeof(AudiodevAlsaPerDirectionOptions));           \
1683             dev->u.driver.has_out = true;                           \
1684         }                                                           \
1685         break
1686 
1687         CASE(NONE, none, );
1688         CASE(ALSA, alsa, Alsa);
1689         CASE(COREAUDIO, coreaudio, Coreaudio);
1690         CASE(DSOUND, dsound, );
1691         CASE(OSS, oss, Oss);
1692         CASE(PA, pa, Pa);
1693         CASE(SDL, sdl, );
1694         CASE(SPICE, spice, );
1695         CASE(WAV, wav, );
1696 
1697     case AUDIODEV_DRIVER__MAX:
1698         abort();
1699     };
1700 }
1701 
1702 static void audio_validate_per_direction_opts(
1703     AudiodevPerDirectionOptions *pdo, Error **errp)
1704 {
1705     if (!pdo->has_fixed_settings) {
1706         pdo->has_fixed_settings = true;
1707         pdo->fixed_settings = true;
1708     }
1709     if (!pdo->fixed_settings &&
1710         (pdo->has_frequency || pdo->has_channels || pdo->has_format)) {
1711         error_setg(errp,
1712                    "You can't use frequency, channels or format with fixed-settings=off");
1713         return;
1714     }
1715 
1716     if (!pdo->has_frequency) {
1717         pdo->has_frequency = true;
1718         pdo->frequency = 44100;
1719     }
1720     if (!pdo->has_channels) {
1721         pdo->has_channels = true;
1722         pdo->channels = 2;
1723     }
1724     if (!pdo->has_voices) {
1725         pdo->has_voices = true;
1726         pdo->voices = 1;
1727     }
1728     if (!pdo->has_format) {
1729         pdo->has_format = true;
1730         pdo->format = AUDIO_FORMAT_S16;
1731     }
1732 }
1733 
1734 static void audio_validate_opts(Audiodev *dev, Error **errp)
1735 {
1736     Error *err = NULL;
1737 
1738     audio_create_pdos(dev);
1739 
1740     audio_validate_per_direction_opts(audio_get_pdo_in(dev), &err);
1741     if (err) {
1742         error_propagate(errp, err);
1743         return;
1744     }
1745 
1746     audio_validate_per_direction_opts(audio_get_pdo_out(dev), &err);
1747     if (err) {
1748         error_propagate(errp, err);
1749         return;
1750     }
1751 
1752     if (!dev->has_timer_period) {
1753         dev->has_timer_period = true;
1754         dev->timer_period = 10000; /* 100Hz -> 10ms */
1755     }
1756 }
1757 
1758 void audio_parse_option(const char *opt)
1759 {
1760     AudiodevListEntry *e;
1761     Audiodev *dev = NULL;
1762 
1763     Visitor *v = qobject_input_visitor_new_str(opt, "driver", &error_fatal);
1764     visit_type_Audiodev(v, NULL, &dev, &error_fatal);
1765     visit_free(v);
1766 
1767     audio_validate_opts(dev, &error_fatal);
1768 
1769     e = g_malloc0(sizeof(AudiodevListEntry));
1770     e->dev = dev;
1771     QSIMPLEQ_INSERT_TAIL(&audiodevs, e, next);
1772 }
1773 
1774 void audio_init_audiodevs(void)
1775 {
1776     AudiodevListEntry *e;
1777 
1778     QSIMPLEQ_FOREACH(e, &audiodevs, next) {
1779         audio_init(e->dev, NULL);
1780     }
1781 }
1782 
1783 audsettings audiodev_to_audsettings(AudiodevPerDirectionOptions *pdo)
1784 {
1785     return (audsettings) {
1786         .freq = pdo->frequency,
1787         .nchannels = pdo->channels,
1788         .fmt = pdo->format,
1789         .endianness = AUDIO_HOST_ENDIANNESS,
1790     };
1791 }
1792 
1793 int audioformat_bytes_per_sample(AudioFormat fmt)
1794 {
1795     switch (fmt) {
1796     case AUDIO_FORMAT_U8:
1797     case AUDIO_FORMAT_S8:
1798         return 1;
1799 
1800     case AUDIO_FORMAT_U16:
1801     case AUDIO_FORMAT_S16:
1802         return 2;
1803 
1804     case AUDIO_FORMAT_U32:
1805     case AUDIO_FORMAT_S32:
1806         return 4;
1807 
1808     case AUDIO_FORMAT__MAX:
1809         ;
1810     }
1811     abort();
1812 }
1813 
1814 
1815 /* frames = freq * usec / 1e6 */
1816 int audio_buffer_frames(AudiodevPerDirectionOptions *pdo,
1817                         audsettings *as, int def_usecs)
1818 {
1819     uint64_t usecs = pdo->has_buffer_length ? pdo->buffer_length : def_usecs;
1820     return (as->freq * usecs + 500000) / 1000000;
1821 }
1822 
1823 /* samples = channels * frames = channels * freq * usec / 1e6 */
1824 int audio_buffer_samples(AudiodevPerDirectionOptions *pdo,
1825                          audsettings *as, int def_usecs)
1826 {
1827     return as->nchannels * audio_buffer_frames(pdo, as, def_usecs);
1828 }
1829 
1830 /*
1831  * bytes = bytes_per_sample * samples =
1832  *     bytes_per_sample * channels * freq * usec / 1e6
1833  */
1834 int audio_buffer_bytes(AudiodevPerDirectionOptions *pdo,
1835                        audsettings *as, int def_usecs)
1836 {
1837     return audio_buffer_samples(pdo, as, def_usecs) *
1838         audioformat_bytes_per_sample(as->fmt);
1839 }
1840 
1841 AudioState *audio_state_by_name(const char *name)
1842 {
1843     AudioState *s;
1844     QTAILQ_FOREACH(s, &audio_states, list) {
1845         assert(s->dev);
1846         if (strcmp(name, s->dev->id) == 0) {
1847             return s;
1848         }
1849     }
1850     return NULL;
1851 }
1852 
1853 const char *audio_get_id(QEMUSoundCard *card)
1854 {
1855     if (card->state) {
1856         assert(card->state->dev);
1857         return card->state->dev->id;
1858     } else {
1859         return "";
1860     }
1861 }
1862