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