xref: /openbmc/qemu/audio/audio.c (revision b000325a)
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 #include "qemu/osdep.h"
25 #include "hw/hw.h"
26 #include "audio.h"
27 #include "monitor/monitor.h"
28 #include "qemu/timer.h"
29 #include "sysemu/sysemu.h"
30 #include "qemu/cutils.h"
31 #include "sysemu/replay.h"
32 
33 #define AUDIO_CAP "audio"
34 #include "audio_int.h"
35 
36 /* #define DEBUG_LIVE */
37 /* #define DEBUG_OUT */
38 /* #define DEBUG_CAPTURE */
39 /* #define DEBUG_POLL */
40 
41 #define SW_NAME(sw) (sw)->name ? (sw)->name : "unknown"
42 
43 
44 /* Order of CONFIG_AUDIO_DRIVERS is import.
45    The 1st one is the one used by default, that is the reason
46     that we generate the list.
47 */
48 static const char *audio_prio_list[] = {
49     "spice",
50     CONFIG_AUDIO_DRIVERS
51     "none",
52     "wav",
53 };
54 
55 static QLIST_HEAD(, audio_driver) audio_drivers;
56 
57 void audio_driver_register(audio_driver *drv)
58 {
59     QLIST_INSERT_HEAD(&audio_drivers, drv, next);
60 }
61 
62 audio_driver *audio_driver_lookup(const char *name)
63 {
64     struct audio_driver *d;
65 
66     QLIST_FOREACH(d, &audio_drivers, next) {
67         if (strcmp(name, d->name) == 0) {
68             return d;
69         }
70     }
71 
72     audio_module_load_one(name);
73     QLIST_FOREACH(d, &audio_drivers, next) {
74         if (strcmp(name, d->name) == 0) {
75             return d;
76         }
77     }
78 
79     return NULL;
80 }
81 
82 static void audio_module_load_all(void)
83 {
84     int i;
85 
86     for (i = 0; i < ARRAY_SIZE(audio_prio_list); i++) {
87         audio_driver_lookup(audio_prio_list[i]);
88     }
89 }
90 
91 struct fixed_settings {
92     int enabled;
93     int nb_voices;
94     int greedy;
95     struct audsettings settings;
96 };
97 
98 static struct {
99     struct fixed_settings fixed_out;
100     struct fixed_settings fixed_in;
101     union {
102         int hertz;
103         int64_t ticks;
104     } period;
105     int try_poll_in;
106     int try_poll_out;
107 } conf = {
108     .fixed_out = { /* DAC fixed settings */
109         .enabled = 1,
110         .nb_voices = 1,
111         .greedy = 1,
112         .settings = {
113             .freq = 44100,
114             .nchannels = 2,
115             .fmt = AUD_FMT_S16,
116             .endianness =  AUDIO_HOST_ENDIANNESS,
117         }
118     },
119 
120     .fixed_in = { /* ADC fixed settings */
121         .enabled = 1,
122         .nb_voices = 1,
123         .greedy = 1,
124         .settings = {
125             .freq = 44100,
126             .nchannels = 2,
127             .fmt = AUD_FMT_S16,
128             .endianness = AUDIO_HOST_ENDIANNESS,
129         }
130     },
131 
132     .period = { .hertz = 100 },
133     .try_poll_in = 1,
134     .try_poll_out = 1,
135 };
136 
137 static AudioState glob_audio_state;
138 
139 const struct mixeng_volume nominal_volume = {
140     .mute = 0,
141 #ifdef FLOAT_MIXENG
142     .r = 1.0,
143     .l = 1.0,
144 #else
145     .r = 1ULL << 32,
146     .l = 1ULL << 32,
147 #endif
148 };
149 
150 #ifdef AUDIO_IS_FLAWLESS_AND_NO_CHECKS_ARE_REQURIED
151 #error No its not
152 #else
153 static void audio_print_options (const char *prefix,
154                                  struct audio_option *opt);
155 
156 int audio_bug (const char *funcname, int cond)
157 {
158     if (cond) {
159         static int shown;
160 
161         AUD_log (NULL, "A bug was just triggered in %s\n", funcname);
162         if (!shown) {
163             struct audio_driver *d;
164 
165             shown = 1;
166             AUD_log (NULL, "Save all your work and restart without audio\n");
167             AUD_log (NULL, "Please send bug report to av1474@comtv.ru\n");
168             AUD_log (NULL, "I am sorry\n");
169             d = glob_audio_state.drv;
170             if (d) {
171                 audio_print_options (d->name, d->options);
172             }
173         }
174         AUD_log (NULL, "Context:\n");
175 
176 #if defined AUDIO_BREAKPOINT_ON_BUG
177 #  if defined HOST_I386
178 #    if defined __GNUC__
179         __asm__ ("int3");
180 #    elif defined _MSC_VER
181         _asm _emit 0xcc;
182 #    else
183         abort ();
184 #    endif
185 #  else
186         abort ();
187 #  endif
188 #endif
189     }
190 
191     return cond;
192 }
193 #endif
194 
195 static inline int audio_bits_to_index (int bits)
196 {
197     switch (bits) {
198     case 8:
199         return 0;
200 
201     case 16:
202         return 1;
203 
204     case 32:
205         return 2;
206 
207     default:
208         audio_bug ("bits_to_index", 1);
209         AUD_log (NULL, "invalid bits %d\n", bits);
210         return 0;
211     }
212 }
213 
214 void *audio_calloc (const char *funcname, int nmemb, size_t size)
215 {
216     int cond;
217     size_t len;
218 
219     len = nmemb * size;
220     cond = !nmemb || !size;
221     cond |= nmemb < 0;
222     cond |= len < size;
223 
224     if (audio_bug ("audio_calloc", cond)) {
225         AUD_log (NULL, "%s passed invalid arguments to audio_calloc\n",
226                  funcname);
227         AUD_log (NULL, "nmemb=%d size=%zu (len=%zu)\n", nmemb, size, len);
228         return NULL;
229     }
230 
231     return g_malloc0 (len);
232 }
233 
234 static char *audio_alloc_prefix (const char *s)
235 {
236     const char qemu_prefix[] = "QEMU_";
237     size_t len, i;
238     char *r, *u;
239 
240     if (!s) {
241         return NULL;
242     }
243 
244     len = strlen (s);
245     r = g_malloc (len + sizeof (qemu_prefix));
246 
247     u = r + sizeof (qemu_prefix) - 1;
248 
249     pstrcpy (r, len + sizeof (qemu_prefix), qemu_prefix);
250     pstrcat (r, len + sizeof (qemu_prefix), s);
251 
252     for (i = 0; i < len; ++i) {
253         u[i] = qemu_toupper(u[i]);
254     }
255 
256     return r;
257 }
258 
259 static const char *audio_audfmt_to_string (audfmt_e fmt)
260 {
261     switch (fmt) {
262     case AUD_FMT_U8:
263         return "U8";
264 
265     case AUD_FMT_U16:
266         return "U16";
267 
268     case AUD_FMT_S8:
269         return "S8";
270 
271     case AUD_FMT_S16:
272         return "S16";
273 
274     case AUD_FMT_U32:
275         return "U32";
276 
277     case AUD_FMT_S32:
278         return "S32";
279     }
280 
281     dolog ("Bogus audfmt %d returning S16\n", fmt);
282     return "S16";
283 }
284 
285 static audfmt_e audio_string_to_audfmt (const char *s, audfmt_e defval,
286                                         int *defaultp)
287 {
288     if (!strcasecmp (s, "u8")) {
289         *defaultp = 0;
290         return AUD_FMT_U8;
291     }
292     else if (!strcasecmp (s, "u16")) {
293         *defaultp = 0;
294         return AUD_FMT_U16;
295     }
296     else if (!strcasecmp (s, "u32")) {
297         *defaultp = 0;
298         return AUD_FMT_U32;
299     }
300     else if (!strcasecmp (s, "s8")) {
301         *defaultp = 0;
302         return AUD_FMT_S8;
303     }
304     else if (!strcasecmp (s, "s16")) {
305         *defaultp = 0;
306         return AUD_FMT_S16;
307     }
308     else if (!strcasecmp (s, "s32")) {
309         *defaultp = 0;
310         return AUD_FMT_S32;
311     }
312     else {
313         dolog ("Bogus audio format `%s' using %s\n",
314                s, audio_audfmt_to_string (defval));
315         *defaultp = 1;
316         return defval;
317     }
318 }
319 
320 static audfmt_e audio_get_conf_fmt (const char *envname,
321                                     audfmt_e defval,
322                                     int *defaultp)
323 {
324     const char *var = getenv (envname);
325     if (!var) {
326         *defaultp = 1;
327         return defval;
328     }
329     return audio_string_to_audfmt (var, defval, defaultp);
330 }
331 
332 static int audio_get_conf_int (const char *key, int defval, int *defaultp)
333 {
334     int val;
335     char *strval;
336 
337     strval = getenv (key);
338     if (strval && !qemu_strtoi(strval, NULL, 10, &val)) {
339         *defaultp = 0;
340         return val;
341     }
342     else {
343         *defaultp = 1;
344         return defval;
345     }
346 }
347 
348 static const char *audio_get_conf_str (const char *key,
349                                        const char *defval,
350                                        int *defaultp)
351 {
352     const char *val = getenv (key);
353     if (!val) {
354         *defaultp = 1;
355         return defval;
356     }
357     else {
358         *defaultp = 0;
359         return val;
360     }
361 }
362 
363 void AUD_vlog (const char *cap, const char *fmt, va_list ap)
364 {
365     if (cap) {
366         fprintf(stderr, "%s: ", cap);
367     }
368 
369     vfprintf(stderr, fmt, ap);
370 }
371 
372 void AUD_log (const char *cap, const char *fmt, ...)
373 {
374     va_list ap;
375 
376     va_start (ap, fmt);
377     AUD_vlog (cap, fmt, ap);
378     va_end (ap);
379 }
380 
381 static void audio_print_options (const char *prefix,
382                                  struct audio_option *opt)
383 {
384     char *uprefix;
385 
386     if (!prefix) {
387         dolog ("No prefix specified\n");
388         return;
389     }
390 
391     if (!opt) {
392         dolog ("No options\n");
393         return;
394     }
395 
396     uprefix = audio_alloc_prefix (prefix);
397 
398     for (; opt->name; opt++) {
399         const char *state = "default";
400         printf ("  %s_%s: ", uprefix, opt->name);
401 
402         if (opt->overriddenp && *opt->overriddenp) {
403             state = "current";
404         }
405 
406         switch (opt->tag) {
407         case AUD_OPT_BOOL:
408             {
409                 int *intp = opt->valp;
410                 printf ("boolean, %s = %d\n", state, *intp ? 1 : 0);
411             }
412             break;
413 
414         case AUD_OPT_INT:
415             {
416                 int *intp = opt->valp;
417                 printf ("integer, %s = %d\n", state, *intp);
418             }
419             break;
420 
421         case AUD_OPT_FMT:
422             {
423                 audfmt_e *fmtp = opt->valp;
424                 printf (
425                     "format, %s = %s, (one of: U8 S8 U16 S16 U32 S32)\n",
426                     state,
427                     audio_audfmt_to_string (*fmtp)
428                     );
429             }
430             break;
431 
432         case AUD_OPT_STR:
433             {
434                 const char **strp = opt->valp;
435                 printf ("string, %s = %s\n",
436                         state,
437                         *strp ? *strp : "(not set)");
438             }
439             break;
440 
441         default:
442             printf ("???\n");
443             dolog ("Bad value tag for option %s_%s %d\n",
444                    uprefix, opt->name, opt->tag);
445             break;
446         }
447         printf ("    %s\n", opt->descr);
448     }
449 
450     g_free (uprefix);
451 }
452 
453 static void audio_process_options (const char *prefix,
454                                    struct audio_option *opt)
455 {
456     char *optname;
457     const char qemu_prefix[] = "QEMU_";
458     size_t preflen, optlen;
459 
460     if (audio_bug(__func__, !prefix)) {
461         dolog ("prefix = NULL\n");
462         return;
463     }
464 
465     if (audio_bug(__func__, !opt)) {
466         dolog ("opt = NULL\n");
467         return;
468     }
469 
470     preflen = strlen (prefix);
471 
472     for (; opt->name; opt++) {
473         size_t len, i;
474         int def;
475 
476         if (!opt->valp) {
477             dolog ("Option value pointer for `%s' is not set\n",
478                    opt->name);
479             continue;
480         }
481 
482         len = strlen (opt->name);
483         /* len of opt->name + len of prefix + size of qemu_prefix
484          * (includes trailing zero) + zero + underscore (on behalf of
485          * sizeof) */
486         optlen = len + preflen + sizeof (qemu_prefix) + 1;
487         optname = g_malloc (optlen);
488 
489         pstrcpy (optname, optlen, qemu_prefix);
490 
491         /* copy while upper-casing, including trailing zero */
492         for (i = 0; i <= preflen; ++i) {
493             optname[i + sizeof (qemu_prefix) - 1] = qemu_toupper(prefix[i]);
494         }
495         pstrcat (optname, optlen, "_");
496         pstrcat (optname, optlen, opt->name);
497 
498         def = 1;
499         switch (opt->tag) {
500         case AUD_OPT_BOOL:
501         case AUD_OPT_INT:
502             {
503                 int *intp = opt->valp;
504                 *intp = audio_get_conf_int (optname, *intp, &def);
505             }
506             break;
507 
508         case AUD_OPT_FMT:
509             {
510                 audfmt_e *fmtp = opt->valp;
511                 *fmtp = audio_get_conf_fmt (optname, *fmtp, &def);
512             }
513             break;
514 
515         case AUD_OPT_STR:
516             {
517                 const char **strp = opt->valp;
518                 *strp = audio_get_conf_str (optname, *strp, &def);
519             }
520             break;
521 
522         default:
523             dolog ("Bad value tag for option `%s' - %d\n",
524                    optname, opt->tag);
525             break;
526         }
527 
528         if (!opt->overriddenp) {
529             opt->overriddenp = &opt->overridden;
530         }
531         *opt->overriddenp = !def;
532         g_free (optname);
533     }
534 }
535 
536 static void audio_print_settings (struct audsettings *as)
537 {
538     dolog ("frequency=%d nchannels=%d fmt=", as->freq, as->nchannels);
539 
540     switch (as->fmt) {
541     case AUD_FMT_S8:
542         AUD_log (NULL, "S8");
543         break;
544     case AUD_FMT_U8:
545         AUD_log (NULL, "U8");
546         break;
547     case AUD_FMT_S16:
548         AUD_log (NULL, "S16");
549         break;
550     case AUD_FMT_U16:
551         AUD_log (NULL, "U16");
552         break;
553     case AUD_FMT_S32:
554         AUD_log (NULL, "S32");
555         break;
556     case AUD_FMT_U32:
557         AUD_log (NULL, "U32");
558         break;
559     default:
560         AUD_log (NULL, "invalid(%d)", as->fmt);
561         break;
562     }
563 
564     AUD_log (NULL, " endianness=");
565     switch (as->endianness) {
566     case 0:
567         AUD_log (NULL, "little");
568         break;
569     case 1:
570         AUD_log (NULL, "big");
571         break;
572     default:
573         AUD_log (NULL, "invalid");
574         break;
575     }
576     AUD_log (NULL, "\n");
577 }
578 
579 static int audio_validate_settings (struct audsettings *as)
580 {
581     int invalid;
582 
583     invalid = as->nchannels != 1 && as->nchannels != 2;
584     invalid |= as->endianness != 0 && as->endianness != 1;
585 
586     switch (as->fmt) {
587     case AUD_FMT_S8:
588     case AUD_FMT_U8:
589     case AUD_FMT_S16:
590     case AUD_FMT_U16:
591     case AUD_FMT_S32:
592     case AUD_FMT_U32:
593         break;
594     default:
595         invalid = 1;
596         break;
597     }
598 
599     invalid |= as->freq <= 0;
600     return invalid ? -1 : 0;
601 }
602 
603 static int audio_pcm_info_eq (struct audio_pcm_info *info, struct audsettings *as)
604 {
605     int bits = 8, sign = 0;
606 
607     switch (as->fmt) {
608     case AUD_FMT_S8:
609         sign = 1;
610         /* fall through */
611     case AUD_FMT_U8:
612         break;
613 
614     case AUD_FMT_S16:
615         sign = 1;
616         /* fall through */
617     case AUD_FMT_U16:
618         bits = 16;
619         break;
620 
621     case AUD_FMT_S32:
622         sign = 1;
623         /* fall through */
624     case AUD_FMT_U32:
625         bits = 32;
626         break;
627     }
628     return info->freq == as->freq
629         && info->nchannels == as->nchannels
630         && info->sign == sign
631         && info->bits == bits
632         && info->swap_endianness == (as->endianness != AUDIO_HOST_ENDIANNESS);
633 }
634 
635 void audio_pcm_init_info (struct audio_pcm_info *info, struct audsettings *as)
636 {
637     int bits = 8, sign = 0, shift = 0;
638 
639     switch (as->fmt) {
640     case AUD_FMT_S8:
641         sign = 1;
642     case AUD_FMT_U8:
643         break;
644 
645     case AUD_FMT_S16:
646         sign = 1;
647     case AUD_FMT_U16:
648         bits = 16;
649         shift = 1;
650         break;
651 
652     case AUD_FMT_S32:
653         sign = 1;
654     case AUD_FMT_U32:
655         bits = 32;
656         shift = 2;
657         break;
658     }
659 
660     info->freq = as->freq;
661     info->bits = bits;
662     info->sign = sign;
663     info->nchannels = as->nchannels;
664     info->shift = (as->nchannels == 2) + shift;
665     info->align = (1 << info->shift) - 1;
666     info->bytes_per_second = info->freq << info->shift;
667     info->swap_endianness = (as->endianness != AUDIO_HOST_ENDIANNESS);
668 }
669 
670 void audio_pcm_info_clear_buf (struct audio_pcm_info *info, void *buf, int len)
671 {
672     if (!len) {
673         return;
674     }
675 
676     if (info->sign) {
677         memset (buf, 0x00, len << info->shift);
678     }
679     else {
680         switch (info->bits) {
681         case 8:
682             memset (buf, 0x80, len << info->shift);
683             break;
684 
685         case 16:
686             {
687                 int i;
688                 uint16_t *p = buf;
689                 int shift = info->nchannels - 1;
690                 short s = INT16_MAX;
691 
692                 if (info->swap_endianness) {
693                     s = bswap16 (s);
694                 }
695 
696                 for (i = 0; i < len << shift; i++) {
697                     p[i] = s;
698                 }
699             }
700             break;
701 
702         case 32:
703             {
704                 int i;
705                 uint32_t *p = buf;
706                 int shift = info->nchannels - 1;
707                 int32_t s = INT32_MAX;
708 
709                 if (info->swap_endianness) {
710                     s = bswap32 (s);
711                 }
712 
713                 for (i = 0; i < len << shift; i++) {
714                     p[i] = s;
715                 }
716             }
717             break;
718 
719         default:
720             AUD_log (NULL, "audio_pcm_info_clear_buf: invalid bits %d\n",
721                      info->bits);
722             break;
723         }
724     }
725 }
726 
727 /*
728  * Capture
729  */
730 static void noop_conv (struct st_sample *dst, const void *src, int samples)
731 {
732     (void) src;
733     (void) dst;
734     (void) samples;
735 }
736 
737 static CaptureVoiceOut *audio_pcm_capture_find_specific (
738     struct audsettings *as
739     )
740 {
741     CaptureVoiceOut *cap;
742     AudioState *s = &glob_audio_state;
743 
744     for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
745         if (audio_pcm_info_eq (&cap->hw.info, as)) {
746             return cap;
747         }
748     }
749     return NULL;
750 }
751 
752 static void audio_notify_capture (CaptureVoiceOut *cap, audcnotification_e cmd)
753 {
754     struct capture_callback *cb;
755 
756 #ifdef DEBUG_CAPTURE
757     dolog ("notification %d sent\n", cmd);
758 #endif
759     for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
760         cb->ops.notify (cb->opaque, cmd);
761     }
762 }
763 
764 static void audio_capture_maybe_changed (CaptureVoiceOut *cap, int enabled)
765 {
766     if (cap->hw.enabled != enabled) {
767         audcnotification_e cmd;
768         cap->hw.enabled = enabled;
769         cmd = enabled ? AUD_CNOTIFY_ENABLE : AUD_CNOTIFY_DISABLE;
770         audio_notify_capture (cap, cmd);
771     }
772 }
773 
774 static void audio_recalc_and_notify_capture (CaptureVoiceOut *cap)
775 {
776     HWVoiceOut *hw = &cap->hw;
777     SWVoiceOut *sw;
778     int enabled = 0;
779 
780     for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
781         if (sw->active) {
782             enabled = 1;
783             break;
784         }
785     }
786     audio_capture_maybe_changed (cap, enabled);
787 }
788 
789 static void audio_detach_capture (HWVoiceOut *hw)
790 {
791     SWVoiceCap *sc = hw->cap_head.lh_first;
792 
793     while (sc) {
794         SWVoiceCap *sc1 = sc->entries.le_next;
795         SWVoiceOut *sw = &sc->sw;
796         CaptureVoiceOut *cap = sc->cap;
797         int was_active = sw->active;
798 
799         if (sw->rate) {
800             st_rate_stop (sw->rate);
801             sw->rate = NULL;
802         }
803 
804         QLIST_REMOVE (sw, entries);
805         QLIST_REMOVE (sc, entries);
806         g_free (sc);
807         if (was_active) {
808             /* We have removed soft voice from the capture:
809                this might have changed the overall status of the capture
810                since this might have been the only active voice */
811             audio_recalc_and_notify_capture (cap);
812         }
813         sc = sc1;
814     }
815 }
816 
817 static int audio_attach_capture (HWVoiceOut *hw)
818 {
819     AudioState *s = &glob_audio_state;
820     CaptureVoiceOut *cap;
821 
822     audio_detach_capture (hw);
823     for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
824         SWVoiceCap *sc;
825         SWVoiceOut *sw;
826         HWVoiceOut *hw_cap = &cap->hw;
827 
828         sc = audio_calloc(__func__, 1, sizeof(*sc));
829         if (!sc) {
830             dolog ("Could not allocate soft capture voice (%zu bytes)\n",
831                    sizeof (*sc));
832             return -1;
833         }
834 
835         sc->cap = cap;
836         sw = &sc->sw;
837         sw->hw = hw_cap;
838         sw->info = hw->info;
839         sw->empty = 1;
840         sw->active = hw->enabled;
841         sw->conv = noop_conv;
842         sw->ratio = ((int64_t) hw_cap->info.freq << 32) / sw->info.freq;
843         sw->vol = nominal_volume;
844         sw->rate = st_rate_start (sw->info.freq, hw_cap->info.freq);
845         if (!sw->rate) {
846             dolog ("Could not start rate conversion for `%s'\n", SW_NAME (sw));
847             g_free (sw);
848             return -1;
849         }
850         QLIST_INSERT_HEAD (&hw_cap->sw_head, sw, entries);
851         QLIST_INSERT_HEAD (&hw->cap_head, sc, entries);
852 #ifdef DEBUG_CAPTURE
853         sw->name = g_strdup_printf ("for %p %d,%d,%d",
854                                     hw, sw->info.freq, sw->info.bits,
855                                     sw->info.nchannels);
856         dolog ("Added %s active = %d\n", sw->name, sw->active);
857 #endif
858         if (sw->active) {
859             audio_capture_maybe_changed (cap, 1);
860         }
861     }
862     return 0;
863 }
864 
865 /*
866  * Hard voice (capture)
867  */
868 static int audio_pcm_hw_find_min_in (HWVoiceIn *hw)
869 {
870     SWVoiceIn *sw;
871     int m = hw->total_samples_captured;
872 
873     for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
874         if (sw->active) {
875             m = audio_MIN (m, sw->total_hw_samples_acquired);
876         }
877     }
878     return m;
879 }
880 
881 int audio_pcm_hw_get_live_in (HWVoiceIn *hw)
882 {
883     int live = hw->total_samples_captured - audio_pcm_hw_find_min_in (hw);
884     if (audio_bug(__func__, live < 0 || live > hw->samples)) {
885         dolog ("live=%d hw->samples=%d\n", live, hw->samples);
886         return 0;
887     }
888     return live;
889 }
890 
891 int audio_pcm_hw_clip_out (HWVoiceOut *hw, void *pcm_buf,
892                            int live, int pending)
893 {
894     int left = hw->samples - pending;
895     int len = audio_MIN (left, live);
896     int clipped = 0;
897 
898     while (len) {
899         struct st_sample *src = hw->mix_buf + hw->rpos;
900         uint8_t *dst = advance (pcm_buf, hw->rpos << hw->info.shift);
901         int samples_till_end_of_buf = hw->samples - hw->rpos;
902         int samples_to_clip = audio_MIN (len, samples_till_end_of_buf);
903 
904         hw->clip (dst, src, samples_to_clip);
905 
906         hw->rpos = (hw->rpos + samples_to_clip) % hw->samples;
907         len -= samples_to_clip;
908         clipped += samples_to_clip;
909     }
910     return clipped;
911 }
912 
913 /*
914  * Soft voice (capture)
915  */
916 static int audio_pcm_sw_get_rpos_in (SWVoiceIn *sw)
917 {
918     HWVoiceIn *hw = sw->hw;
919     int live = hw->total_samples_captured - sw->total_hw_samples_acquired;
920     int rpos;
921 
922     if (audio_bug(__func__, live < 0 || live > hw->samples)) {
923         dolog ("live=%d hw->samples=%d\n", live, hw->samples);
924         return 0;
925     }
926 
927     rpos = hw->wpos - live;
928     if (rpos >= 0) {
929         return rpos;
930     }
931     else {
932         return hw->samples + rpos;
933     }
934 }
935 
936 int audio_pcm_sw_read (SWVoiceIn *sw, void *buf, int size)
937 {
938     HWVoiceIn *hw = sw->hw;
939     int samples, live, ret = 0, swlim, isamp, osamp, rpos, total = 0;
940     struct st_sample *src, *dst = sw->buf;
941 
942     rpos = audio_pcm_sw_get_rpos_in (sw) % hw->samples;
943 
944     live = hw->total_samples_captured - sw->total_hw_samples_acquired;
945     if (audio_bug(__func__, live < 0 || live > hw->samples)) {
946         dolog ("live_in=%d hw->samples=%d\n", live, hw->samples);
947         return 0;
948     }
949 
950     samples = size >> sw->info.shift;
951     if (!live) {
952         return 0;
953     }
954 
955     swlim = (live * sw->ratio) >> 32;
956     swlim = audio_MIN (swlim, samples);
957 
958     while (swlim) {
959         src = hw->conv_buf + rpos;
960         isamp = hw->wpos - rpos;
961         /* XXX: <= ? */
962         if (isamp <= 0) {
963             isamp = hw->samples - rpos;
964         }
965 
966         if (!isamp) {
967             break;
968         }
969         osamp = swlim;
970 
971         if (audio_bug(__func__, osamp < 0)) {
972             dolog ("osamp=%d\n", osamp);
973             return 0;
974         }
975 
976         st_rate_flow (sw->rate, src, dst, &isamp, &osamp);
977         swlim -= osamp;
978         rpos = (rpos + isamp) % hw->samples;
979         dst += osamp;
980         ret += osamp;
981         total += isamp;
982     }
983 
984     if (!(hw->ctl_caps & VOICE_VOLUME_CAP)) {
985         mixeng_volume (sw->buf, ret, &sw->vol);
986     }
987 
988     sw->clip (buf, sw->buf, ret);
989     sw->total_hw_samples_acquired += total;
990     return ret << sw->info.shift;
991 }
992 
993 /*
994  * Hard voice (playback)
995  */
996 static int audio_pcm_hw_find_min_out (HWVoiceOut *hw, int *nb_livep)
997 {
998     SWVoiceOut *sw;
999     int m = INT_MAX;
1000     int nb_live = 0;
1001 
1002     for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1003         if (sw->active || !sw->empty) {
1004             m = audio_MIN (m, sw->total_hw_samples_mixed);
1005             nb_live += 1;
1006         }
1007     }
1008 
1009     *nb_livep = nb_live;
1010     return m;
1011 }
1012 
1013 static int audio_pcm_hw_get_live_out (HWVoiceOut *hw, int *nb_live)
1014 {
1015     int smin;
1016     int nb_live1;
1017 
1018     smin = audio_pcm_hw_find_min_out (hw, &nb_live1);
1019     if (nb_live) {
1020         *nb_live = nb_live1;
1021     }
1022 
1023     if (nb_live1) {
1024         int live = smin;
1025 
1026         if (audio_bug(__func__, live < 0 || live > hw->samples)) {
1027             dolog ("live=%d hw->samples=%d\n", live, hw->samples);
1028             return 0;
1029         }
1030         return live;
1031     }
1032     return 0;
1033 }
1034 
1035 /*
1036  * Soft voice (playback)
1037  */
1038 int audio_pcm_sw_write (SWVoiceOut *sw, void *buf, int size)
1039 {
1040     int hwsamples, samples, isamp, osamp, wpos, live, dead, left, swlim, blck;
1041     int ret = 0, pos = 0, total = 0;
1042 
1043     if (!sw) {
1044         return size;
1045     }
1046 
1047     hwsamples = sw->hw->samples;
1048 
1049     live = sw->total_hw_samples_mixed;
1050     if (audio_bug(__func__, live < 0 || live > hwsamples)) {
1051         dolog ("live=%d hw->samples=%d\n", live, hwsamples);
1052         return 0;
1053     }
1054 
1055     if (live == hwsamples) {
1056 #ifdef DEBUG_OUT
1057         dolog ("%s is full %d\n", sw->name, live);
1058 #endif
1059         return 0;
1060     }
1061 
1062     wpos = (sw->hw->rpos + live) % hwsamples;
1063     samples = size >> sw->info.shift;
1064 
1065     dead = hwsamples - live;
1066     swlim = ((int64_t) dead << 32) / sw->ratio;
1067     swlim = audio_MIN (swlim, samples);
1068     if (swlim) {
1069         sw->conv (sw->buf, buf, swlim);
1070 
1071         if (!(sw->hw->ctl_caps & VOICE_VOLUME_CAP)) {
1072             mixeng_volume (sw->buf, swlim, &sw->vol);
1073         }
1074     }
1075 
1076     while (swlim) {
1077         dead = hwsamples - live;
1078         left = hwsamples - wpos;
1079         blck = audio_MIN (dead, left);
1080         if (!blck) {
1081             break;
1082         }
1083         isamp = swlim;
1084         osamp = blck;
1085         st_rate_flow_mix (
1086             sw->rate,
1087             sw->buf + pos,
1088             sw->hw->mix_buf + wpos,
1089             &isamp,
1090             &osamp
1091             );
1092         ret += isamp;
1093         swlim -= isamp;
1094         pos += isamp;
1095         live += osamp;
1096         wpos = (wpos + osamp) % hwsamples;
1097         total += osamp;
1098     }
1099 
1100     sw->total_hw_samples_mixed += total;
1101     sw->empty = sw->total_hw_samples_mixed == 0;
1102 
1103 #ifdef DEBUG_OUT
1104     dolog (
1105         "%s: write size %d ret %d total sw %d\n",
1106         SW_NAME (sw),
1107         size >> sw->info.shift,
1108         ret,
1109         sw->total_hw_samples_mixed
1110         );
1111 #endif
1112 
1113     return ret << sw->info.shift;
1114 }
1115 
1116 #ifdef DEBUG_AUDIO
1117 static void audio_pcm_print_info (const char *cap, struct audio_pcm_info *info)
1118 {
1119     dolog ("%s: bits %d, sign %d, freq %d, nchan %d\n",
1120            cap, info->bits, info->sign, info->freq, info->nchannels);
1121 }
1122 #endif
1123 
1124 #define DAC
1125 #include "audio_template.h"
1126 #undef DAC
1127 #include "audio_template.h"
1128 
1129 /*
1130  * Timer
1131  */
1132 static int audio_is_timer_needed (void)
1133 {
1134     HWVoiceIn *hwi = NULL;
1135     HWVoiceOut *hwo = NULL;
1136 
1137     while ((hwo = audio_pcm_hw_find_any_enabled_out (hwo))) {
1138         if (!hwo->poll_mode) return 1;
1139     }
1140     while ((hwi = audio_pcm_hw_find_any_enabled_in (hwi))) {
1141         if (!hwi->poll_mode) return 1;
1142     }
1143     return 0;
1144 }
1145 
1146 static void audio_reset_timer (AudioState *s)
1147 {
1148     if (audio_is_timer_needed ()) {
1149         timer_mod_anticipate_ns(s->ts,
1150             qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + conf.period.ticks);
1151     }
1152     else {
1153         timer_del (s->ts);
1154     }
1155 }
1156 
1157 static void audio_timer (void *opaque)
1158 {
1159     audio_run ("timer");
1160     audio_reset_timer (opaque);
1161 }
1162 
1163 /*
1164  * Public API
1165  */
1166 int AUD_write (SWVoiceOut *sw, void *buf, int size)
1167 {
1168     if (!sw) {
1169         /* XXX: Consider options */
1170         return size;
1171     }
1172 
1173     if (!sw->hw->enabled) {
1174         dolog ("Writing to disabled voice %s\n", SW_NAME (sw));
1175         return 0;
1176     }
1177 
1178     return sw->hw->pcm_ops->write(sw, buf, size);
1179 }
1180 
1181 int AUD_read (SWVoiceIn *sw, void *buf, int size)
1182 {
1183     if (!sw) {
1184         /* XXX: Consider options */
1185         return size;
1186     }
1187 
1188     if (!sw->hw->enabled) {
1189         dolog ("Reading from disabled voice %s\n", SW_NAME (sw));
1190         return 0;
1191     }
1192 
1193     return sw->hw->pcm_ops->read(sw, buf, size);
1194 }
1195 
1196 int AUD_get_buffer_size_out (SWVoiceOut *sw)
1197 {
1198     return sw->hw->samples << sw->hw->info.shift;
1199 }
1200 
1201 void AUD_set_active_out (SWVoiceOut *sw, int on)
1202 {
1203     HWVoiceOut *hw;
1204 
1205     if (!sw) {
1206         return;
1207     }
1208 
1209     hw = sw->hw;
1210     if (sw->active != on) {
1211         AudioState *s = &glob_audio_state;
1212         SWVoiceOut *temp_sw;
1213         SWVoiceCap *sc;
1214 
1215         if (on) {
1216             hw->pending_disable = 0;
1217             if (!hw->enabled) {
1218                 hw->enabled = 1;
1219                 if (s->vm_running) {
1220                     hw->pcm_ops->ctl_out (hw, VOICE_ENABLE, conf.try_poll_out);
1221                     audio_reset_timer (s);
1222                 }
1223             }
1224         }
1225         else {
1226             if (hw->enabled) {
1227                 int nb_active = 0;
1228 
1229                 for (temp_sw = hw->sw_head.lh_first; temp_sw;
1230                      temp_sw = temp_sw->entries.le_next) {
1231                     nb_active += temp_sw->active != 0;
1232                 }
1233 
1234                 hw->pending_disable = nb_active == 1;
1235             }
1236         }
1237 
1238         for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
1239             sc->sw.active = hw->enabled;
1240             if (hw->enabled) {
1241                 audio_capture_maybe_changed (sc->cap, 1);
1242             }
1243         }
1244         sw->active = on;
1245     }
1246 }
1247 
1248 void AUD_set_active_in (SWVoiceIn *sw, int on)
1249 {
1250     HWVoiceIn *hw;
1251 
1252     if (!sw) {
1253         return;
1254     }
1255 
1256     hw = sw->hw;
1257     if (sw->active != on) {
1258         AudioState *s = &glob_audio_state;
1259         SWVoiceIn *temp_sw;
1260 
1261         if (on) {
1262             if (!hw->enabled) {
1263                 hw->enabled = 1;
1264                 if (s->vm_running) {
1265                     hw->pcm_ops->ctl_in (hw, VOICE_ENABLE, conf.try_poll_in);
1266                     audio_reset_timer (s);
1267                 }
1268             }
1269             sw->total_hw_samples_acquired = hw->total_samples_captured;
1270         }
1271         else {
1272             if (hw->enabled) {
1273                 int nb_active = 0;
1274 
1275                 for (temp_sw = hw->sw_head.lh_first; temp_sw;
1276                      temp_sw = temp_sw->entries.le_next) {
1277                     nb_active += temp_sw->active != 0;
1278                 }
1279 
1280                 if (nb_active == 1) {
1281                     hw->enabled = 0;
1282                     hw->pcm_ops->ctl_in (hw, VOICE_DISABLE);
1283                 }
1284             }
1285         }
1286         sw->active = on;
1287     }
1288 }
1289 
1290 static int audio_get_avail (SWVoiceIn *sw)
1291 {
1292     int live;
1293 
1294     if (!sw) {
1295         return 0;
1296     }
1297 
1298     live = sw->hw->total_samples_captured - sw->total_hw_samples_acquired;
1299     if (audio_bug(__func__, live < 0 || live > sw->hw->samples)) {
1300         dolog ("live=%d sw->hw->samples=%d\n", live, sw->hw->samples);
1301         return 0;
1302     }
1303 
1304     ldebug (
1305         "%s: get_avail live %d ret %" PRId64 "\n",
1306         SW_NAME (sw),
1307         live, (((int64_t) live << 32) / sw->ratio) << sw->info.shift
1308         );
1309 
1310     return (((int64_t) live << 32) / sw->ratio) << sw->info.shift;
1311 }
1312 
1313 static int audio_get_free (SWVoiceOut *sw)
1314 {
1315     int live, dead;
1316 
1317     if (!sw) {
1318         return 0;
1319     }
1320 
1321     live = sw->total_hw_samples_mixed;
1322 
1323     if (audio_bug(__func__, live < 0 || live > sw->hw->samples)) {
1324         dolog ("live=%d sw->hw->samples=%d\n", live, sw->hw->samples);
1325         return 0;
1326     }
1327 
1328     dead = sw->hw->samples - live;
1329 
1330 #ifdef DEBUG_OUT
1331     dolog ("%s: get_free live %d dead %d ret %" PRId64 "\n",
1332            SW_NAME (sw),
1333            live, dead, (((int64_t) dead << 32) / sw->ratio) << sw->info.shift);
1334 #endif
1335 
1336     return (((int64_t) dead << 32) / sw->ratio) << sw->info.shift;
1337 }
1338 
1339 static void audio_capture_mix_and_clear (HWVoiceOut *hw, int rpos, int samples)
1340 {
1341     int n;
1342 
1343     if (hw->enabled) {
1344         SWVoiceCap *sc;
1345 
1346         for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
1347             SWVoiceOut *sw = &sc->sw;
1348             int rpos2 = rpos;
1349 
1350             n = samples;
1351             while (n) {
1352                 int till_end_of_hw = hw->samples - rpos2;
1353                 int to_write = audio_MIN (till_end_of_hw, n);
1354                 int bytes = to_write << hw->info.shift;
1355                 int written;
1356 
1357                 sw->buf = hw->mix_buf + rpos2;
1358                 written = audio_pcm_sw_write (sw, NULL, bytes);
1359                 if (written - bytes) {
1360                     dolog ("Could not mix %d bytes into a capture "
1361                            "buffer, mixed %d\n",
1362                            bytes, written);
1363                     break;
1364                 }
1365                 n -= to_write;
1366                 rpos2 = (rpos2 + to_write) % hw->samples;
1367             }
1368         }
1369     }
1370 
1371     n = audio_MIN (samples, hw->samples - rpos);
1372     mixeng_clear (hw->mix_buf + rpos, n);
1373     mixeng_clear (hw->mix_buf, samples - n);
1374 }
1375 
1376 static void audio_run_out (AudioState *s)
1377 {
1378     HWVoiceOut *hw = NULL;
1379     SWVoiceOut *sw;
1380 
1381     while ((hw = audio_pcm_hw_find_any_enabled_out (hw))) {
1382         int played;
1383         int live, free, nb_live, cleanup_required, prev_rpos;
1384 
1385         live = audio_pcm_hw_get_live_out (hw, &nb_live);
1386         if (!nb_live) {
1387             live = 0;
1388         }
1389 
1390         if (audio_bug(__func__, live < 0 || live > hw->samples)) {
1391             dolog ("live=%d hw->samples=%d\n", live, hw->samples);
1392             continue;
1393         }
1394 
1395         if (hw->pending_disable && !nb_live) {
1396             SWVoiceCap *sc;
1397 #ifdef DEBUG_OUT
1398             dolog ("Disabling voice\n");
1399 #endif
1400             hw->enabled = 0;
1401             hw->pending_disable = 0;
1402             hw->pcm_ops->ctl_out (hw, VOICE_DISABLE);
1403             for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
1404                 sc->sw.active = 0;
1405                 audio_recalc_and_notify_capture (sc->cap);
1406             }
1407             continue;
1408         }
1409 
1410         if (!live) {
1411             for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1412                 if (sw->active) {
1413                     free = audio_get_free (sw);
1414                     if (free > 0) {
1415                         sw->callback.fn (sw->callback.opaque, free);
1416                     }
1417                 }
1418             }
1419             continue;
1420         }
1421 
1422         prev_rpos = hw->rpos;
1423         played = hw->pcm_ops->run_out (hw, live);
1424         replay_audio_out(&played);
1425         if (audio_bug(__func__, hw->rpos >= hw->samples)) {
1426             dolog ("hw->rpos=%d hw->samples=%d played=%d\n",
1427                    hw->rpos, hw->samples, played);
1428             hw->rpos = 0;
1429         }
1430 
1431 #ifdef DEBUG_OUT
1432         dolog ("played=%d\n", played);
1433 #endif
1434 
1435         if (played) {
1436             hw->ts_helper += played;
1437             audio_capture_mix_and_clear (hw, prev_rpos, played);
1438         }
1439 
1440         cleanup_required = 0;
1441         for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1442             if (!sw->active && sw->empty) {
1443                 continue;
1444             }
1445 
1446             if (audio_bug(__func__, played > sw->total_hw_samples_mixed)) {
1447                 dolog ("played=%d sw->total_hw_samples_mixed=%d\n",
1448                        played, sw->total_hw_samples_mixed);
1449                 played = sw->total_hw_samples_mixed;
1450             }
1451 
1452             sw->total_hw_samples_mixed -= played;
1453 
1454             if (!sw->total_hw_samples_mixed) {
1455                 sw->empty = 1;
1456                 cleanup_required |= !sw->active && !sw->callback.fn;
1457             }
1458 
1459             if (sw->active) {
1460                 free = audio_get_free (sw);
1461                 if (free > 0) {
1462                     sw->callback.fn (sw->callback.opaque, free);
1463                 }
1464             }
1465         }
1466 
1467         if (cleanup_required) {
1468             SWVoiceOut *sw1;
1469 
1470             sw = hw->sw_head.lh_first;
1471             while (sw) {
1472                 sw1 = sw->entries.le_next;
1473                 if (!sw->active && !sw->callback.fn) {
1474                     audio_close_out (sw);
1475                 }
1476                 sw = sw1;
1477             }
1478         }
1479     }
1480 }
1481 
1482 static void audio_run_in (AudioState *s)
1483 {
1484     HWVoiceIn *hw = NULL;
1485 
1486     while ((hw = audio_pcm_hw_find_any_enabled_in (hw))) {
1487         SWVoiceIn *sw;
1488         int captured = 0, min;
1489 
1490         if (replay_mode != REPLAY_MODE_PLAY) {
1491             captured = hw->pcm_ops->run_in(hw);
1492         }
1493         replay_audio_in(&captured, hw->conv_buf, &hw->wpos, hw->samples);
1494 
1495         min = audio_pcm_hw_find_min_in (hw);
1496         hw->total_samples_captured += captured - min;
1497         hw->ts_helper += captured;
1498 
1499         for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1500             sw->total_hw_samples_acquired -= min;
1501 
1502             if (sw->active) {
1503                 int avail;
1504 
1505                 avail = audio_get_avail (sw);
1506                 if (avail > 0) {
1507                     sw->callback.fn (sw->callback.opaque, avail);
1508                 }
1509             }
1510         }
1511     }
1512 }
1513 
1514 static void audio_run_capture (AudioState *s)
1515 {
1516     CaptureVoiceOut *cap;
1517 
1518     for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
1519         int live, rpos, captured;
1520         HWVoiceOut *hw = &cap->hw;
1521         SWVoiceOut *sw;
1522 
1523         captured = live = audio_pcm_hw_get_live_out (hw, NULL);
1524         rpos = hw->rpos;
1525         while (live) {
1526             int left = hw->samples - rpos;
1527             int to_capture = audio_MIN (live, left);
1528             struct st_sample *src;
1529             struct capture_callback *cb;
1530 
1531             src = hw->mix_buf + rpos;
1532             hw->clip (cap->buf, src, to_capture);
1533             mixeng_clear (src, to_capture);
1534 
1535             for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
1536                 cb->ops.capture (cb->opaque, cap->buf,
1537                                  to_capture << hw->info.shift);
1538             }
1539             rpos = (rpos + to_capture) % hw->samples;
1540             live -= to_capture;
1541         }
1542         hw->rpos = rpos;
1543 
1544         for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1545             if (!sw->active && sw->empty) {
1546                 continue;
1547             }
1548 
1549             if (audio_bug(__func__, captured > sw->total_hw_samples_mixed)) {
1550                 dolog ("captured=%d sw->total_hw_samples_mixed=%d\n",
1551                        captured, sw->total_hw_samples_mixed);
1552                 captured = sw->total_hw_samples_mixed;
1553             }
1554 
1555             sw->total_hw_samples_mixed -= captured;
1556             sw->empty = sw->total_hw_samples_mixed == 0;
1557         }
1558     }
1559 }
1560 
1561 void audio_run (const char *msg)
1562 {
1563     AudioState *s = &glob_audio_state;
1564 
1565     audio_run_out (s);
1566     audio_run_in (s);
1567     audio_run_capture (s);
1568 #ifdef DEBUG_POLL
1569     {
1570         static double prevtime;
1571         double currtime;
1572         struct timeval tv;
1573 
1574         if (gettimeofday (&tv, NULL)) {
1575             perror ("audio_run: gettimeofday");
1576             return;
1577         }
1578 
1579         currtime = tv.tv_sec + tv.tv_usec * 1e-6;
1580         dolog ("Elapsed since last %s: %f\n", msg, currtime - prevtime);
1581         prevtime = currtime;
1582     }
1583 #endif
1584 }
1585 
1586 static struct audio_option audio_options[] = {
1587     /* DAC */
1588     {
1589         .name  = "DAC_FIXED_SETTINGS",
1590         .tag   = AUD_OPT_BOOL,
1591         .valp  = &conf.fixed_out.enabled,
1592         .descr = "Use fixed settings for host DAC"
1593     },
1594     {
1595         .name  = "DAC_FIXED_FREQ",
1596         .tag   = AUD_OPT_INT,
1597         .valp  = &conf.fixed_out.settings.freq,
1598         .descr = "Frequency for fixed host DAC"
1599     },
1600     {
1601         .name  = "DAC_FIXED_FMT",
1602         .tag   = AUD_OPT_FMT,
1603         .valp  = &conf.fixed_out.settings.fmt,
1604         .descr = "Format for fixed host DAC"
1605     },
1606     {
1607         .name  = "DAC_FIXED_CHANNELS",
1608         .tag   = AUD_OPT_INT,
1609         .valp  = &conf.fixed_out.settings.nchannels,
1610         .descr = "Number of channels for fixed DAC (1 - mono, 2 - stereo)"
1611     },
1612     {
1613         .name  = "DAC_VOICES",
1614         .tag   = AUD_OPT_INT,
1615         .valp  = &conf.fixed_out.nb_voices,
1616         .descr = "Number of voices for DAC"
1617     },
1618     {
1619         .name  = "DAC_TRY_POLL",
1620         .tag   = AUD_OPT_BOOL,
1621         .valp  = &conf.try_poll_out,
1622         .descr = "Attempt using poll mode for DAC"
1623     },
1624     /* ADC */
1625     {
1626         .name  = "ADC_FIXED_SETTINGS",
1627         .tag   = AUD_OPT_BOOL,
1628         .valp  = &conf.fixed_in.enabled,
1629         .descr = "Use fixed settings for host ADC"
1630     },
1631     {
1632         .name  = "ADC_FIXED_FREQ",
1633         .tag   = AUD_OPT_INT,
1634         .valp  = &conf.fixed_in.settings.freq,
1635         .descr = "Frequency for fixed host ADC"
1636     },
1637     {
1638         .name  = "ADC_FIXED_FMT",
1639         .tag   = AUD_OPT_FMT,
1640         .valp  = &conf.fixed_in.settings.fmt,
1641         .descr = "Format for fixed host ADC"
1642     },
1643     {
1644         .name  = "ADC_FIXED_CHANNELS",
1645         .tag   = AUD_OPT_INT,
1646         .valp  = &conf.fixed_in.settings.nchannels,
1647         .descr = "Number of channels for fixed ADC (1 - mono, 2 - stereo)"
1648     },
1649     {
1650         .name  = "ADC_VOICES",
1651         .tag   = AUD_OPT_INT,
1652         .valp  = &conf.fixed_in.nb_voices,
1653         .descr = "Number of voices for ADC"
1654     },
1655     {
1656         .name  = "ADC_TRY_POLL",
1657         .tag   = AUD_OPT_BOOL,
1658         .valp  = &conf.try_poll_in,
1659         .descr = "Attempt using poll mode for ADC"
1660     },
1661     /* Misc */
1662     {
1663         .name  = "TIMER_PERIOD",
1664         .tag   = AUD_OPT_INT,
1665         .valp  = &conf.period.hertz,
1666         .descr = "Timer period in HZ (0 - use lowest possible)"
1667     },
1668     { /* End of list */ }
1669 };
1670 
1671 static void audio_pp_nb_voices (const char *typ, int nb)
1672 {
1673     switch (nb) {
1674     case 0:
1675         printf ("Does not support %s\n", typ);
1676         break;
1677     case 1:
1678         printf ("One %s voice\n", typ);
1679         break;
1680     case INT_MAX:
1681         printf ("Theoretically supports many %s voices\n", typ);
1682         break;
1683     default:
1684         printf ("Theoretically supports up to %d %s voices\n", nb, typ);
1685         break;
1686     }
1687 
1688 }
1689 
1690 void AUD_help (void)
1691 {
1692     struct audio_driver *d;
1693 
1694     /* make sure we print the help text for modular drivers too */
1695     audio_module_load_all();
1696 
1697     audio_process_options ("AUDIO", audio_options);
1698     QLIST_FOREACH(d, &audio_drivers, next) {
1699         if (d->options) {
1700             audio_process_options (d->name, d->options);
1701         }
1702     }
1703 
1704     printf ("Audio options:\n");
1705     audio_print_options ("AUDIO", audio_options);
1706     printf ("\n");
1707 
1708     printf ("Available drivers:\n");
1709 
1710     QLIST_FOREACH(d, &audio_drivers, next) {
1711 
1712         printf ("Name: %s\n", d->name);
1713         printf ("Description: %s\n", d->descr);
1714 
1715         audio_pp_nb_voices ("playback", d->max_voices_out);
1716         audio_pp_nb_voices ("capture", d->max_voices_in);
1717 
1718         if (d->options) {
1719             printf ("Options:\n");
1720             audio_print_options (d->name, d->options);
1721         }
1722         else {
1723             printf ("No options\n");
1724         }
1725         printf ("\n");
1726     }
1727 
1728     printf (
1729         "Options are settable through environment variables.\n"
1730         "Example:\n"
1731 #ifdef _WIN32
1732         "  set QEMU_AUDIO_DRV=wav\n"
1733         "  set QEMU_WAV_PATH=c:\\tune.wav\n"
1734 #else
1735         "  export QEMU_AUDIO_DRV=wav\n"
1736         "  export QEMU_WAV_PATH=$HOME/tune.wav\n"
1737         "(for csh replace export with setenv in the above)\n"
1738 #endif
1739         "  qemu ...\n\n"
1740         );
1741 }
1742 
1743 static int audio_driver_init (AudioState *s, struct audio_driver *drv)
1744 {
1745     if (drv->options) {
1746         audio_process_options (drv->name, drv->options);
1747     }
1748     s->drv_opaque = drv->init ();
1749 
1750     if (s->drv_opaque) {
1751         audio_init_nb_voices_out (drv);
1752         audio_init_nb_voices_in (drv);
1753         s->drv = drv;
1754         return 0;
1755     }
1756     else {
1757         dolog ("Could not init `%s' audio driver\n", drv->name);
1758         return -1;
1759     }
1760 }
1761 
1762 static void audio_vm_change_state_handler (void *opaque, int running,
1763                                            RunState state)
1764 {
1765     AudioState *s = opaque;
1766     HWVoiceOut *hwo = NULL;
1767     HWVoiceIn *hwi = NULL;
1768     int op = running ? VOICE_ENABLE : VOICE_DISABLE;
1769 
1770     s->vm_running = running;
1771     while ((hwo = audio_pcm_hw_find_any_enabled_out (hwo))) {
1772         hwo->pcm_ops->ctl_out (hwo, op, conf.try_poll_out);
1773     }
1774 
1775     while ((hwi = audio_pcm_hw_find_any_enabled_in (hwi))) {
1776         hwi->pcm_ops->ctl_in (hwi, op, conf.try_poll_in);
1777     }
1778     audio_reset_timer (s);
1779 }
1780 
1781 static bool is_cleaning_up;
1782 
1783 bool audio_is_cleaning_up(void)
1784 {
1785     return is_cleaning_up;
1786 }
1787 
1788 void audio_cleanup(void)
1789 {
1790     AudioState *s = &glob_audio_state;
1791     HWVoiceOut *hwo, *hwon;
1792     HWVoiceIn *hwi, *hwin;
1793 
1794     is_cleaning_up = true;
1795     QLIST_FOREACH_SAFE(hwo, &glob_audio_state.hw_head_out, entries, hwon) {
1796         SWVoiceCap *sc;
1797 
1798         if (hwo->enabled) {
1799             hwo->pcm_ops->ctl_out (hwo, VOICE_DISABLE);
1800         }
1801         hwo->pcm_ops->fini_out (hwo);
1802 
1803         for (sc = hwo->cap_head.lh_first; sc; sc = sc->entries.le_next) {
1804             CaptureVoiceOut *cap = sc->cap;
1805             struct capture_callback *cb;
1806 
1807             for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
1808                 cb->ops.destroy (cb->opaque);
1809             }
1810         }
1811         QLIST_REMOVE(hwo, entries);
1812     }
1813 
1814     QLIST_FOREACH_SAFE(hwi, &glob_audio_state.hw_head_in, entries, hwin) {
1815         if (hwi->enabled) {
1816             hwi->pcm_ops->ctl_in (hwi, VOICE_DISABLE);
1817         }
1818         hwi->pcm_ops->fini_in (hwi);
1819         QLIST_REMOVE(hwi, entries);
1820     }
1821 
1822     if (s->drv) {
1823         s->drv->fini (s->drv_opaque);
1824         s->drv = NULL;
1825     }
1826 }
1827 
1828 static const VMStateDescription vmstate_audio = {
1829     .name = "audio",
1830     .version_id = 1,
1831     .minimum_version_id = 1,
1832     .fields = (VMStateField[]) {
1833         VMSTATE_END_OF_LIST()
1834     }
1835 };
1836 
1837 static void audio_init (void)
1838 {
1839     size_t i;
1840     int done = 0;
1841     const char *drvname;
1842     VMChangeStateEntry *e;
1843     AudioState *s = &glob_audio_state;
1844     struct audio_driver *driver;
1845 
1846     if (s->drv) {
1847         return;
1848     }
1849 
1850     QLIST_INIT (&s->hw_head_out);
1851     QLIST_INIT (&s->hw_head_in);
1852     QLIST_INIT (&s->cap_head);
1853     atexit(audio_cleanup);
1854 
1855     s->ts = timer_new_ns(QEMU_CLOCK_VIRTUAL, audio_timer, s);
1856 
1857     audio_process_options ("AUDIO", audio_options);
1858 
1859     s->nb_hw_voices_out = conf.fixed_out.nb_voices;
1860     s->nb_hw_voices_in = conf.fixed_in.nb_voices;
1861 
1862     if (s->nb_hw_voices_out <= 0) {
1863         dolog ("Bogus number of playback voices %d, setting to 1\n",
1864                s->nb_hw_voices_out);
1865         s->nb_hw_voices_out = 1;
1866     }
1867 
1868     if (s->nb_hw_voices_in <= 0) {
1869         dolog ("Bogus number of capture voices %d, setting to 0\n",
1870                s->nb_hw_voices_in);
1871         s->nb_hw_voices_in = 0;
1872     }
1873 
1874     {
1875         int def;
1876         drvname = audio_get_conf_str ("QEMU_AUDIO_DRV", NULL, &def);
1877     }
1878 
1879     if (drvname) {
1880         driver = audio_driver_lookup(drvname);
1881         if (driver) {
1882             done = !audio_driver_init(s, driver);
1883         } else {
1884             dolog ("Unknown audio driver `%s'\n", drvname);
1885             dolog ("Run with -audio-help to list available drivers\n");
1886         }
1887     }
1888 
1889     if (!done) {
1890         for (i = 0; !done && i < ARRAY_SIZE(audio_prio_list); i++) {
1891             driver = audio_driver_lookup(audio_prio_list[i]);
1892             if (driver && driver->can_be_default) {
1893                 done = !audio_driver_init(s, driver);
1894             }
1895         }
1896     }
1897 
1898     if (!done) {
1899         driver = audio_driver_lookup("none");
1900         done = !audio_driver_init(s, driver);
1901         assert(done);
1902         dolog("warning: Using timer based audio emulation\n");
1903     }
1904 
1905     if (conf.period.hertz <= 0) {
1906         if (conf.period.hertz < 0) {
1907             dolog ("warning: Timer period is negative - %d "
1908                    "treating as zero\n",
1909                    conf.period.hertz);
1910         }
1911         conf.period.ticks = 1;
1912     } else {
1913         conf.period.ticks = NANOSECONDS_PER_SECOND / conf.period.hertz;
1914     }
1915 
1916     e = qemu_add_vm_change_state_handler (audio_vm_change_state_handler, s);
1917     if (!e) {
1918         dolog ("warning: Could not register change state handler\n"
1919                "(Audio can continue looping even after stopping the VM)\n");
1920     }
1921 
1922     QLIST_INIT (&s->card_head);
1923     vmstate_register (NULL, 0, &vmstate_audio, s);
1924 }
1925 
1926 void AUD_register_card (const char *name, QEMUSoundCard *card)
1927 {
1928     audio_init ();
1929     card->name = g_strdup (name);
1930     memset (&card->entries, 0, sizeof (card->entries));
1931     QLIST_INSERT_HEAD (&glob_audio_state.card_head, card, entries);
1932 }
1933 
1934 void AUD_remove_card (QEMUSoundCard *card)
1935 {
1936     QLIST_REMOVE (card, entries);
1937     g_free (card->name);
1938 }
1939 
1940 
1941 CaptureVoiceOut *AUD_add_capture (
1942     struct audsettings *as,
1943     struct audio_capture_ops *ops,
1944     void *cb_opaque
1945     )
1946 {
1947     AudioState *s = &glob_audio_state;
1948     CaptureVoiceOut *cap;
1949     struct capture_callback *cb;
1950 
1951     if (audio_validate_settings (as)) {
1952         dolog ("Invalid settings were passed when trying to add capture\n");
1953         audio_print_settings (as);
1954         goto err0;
1955     }
1956 
1957     cb = audio_calloc(__func__, 1, sizeof(*cb));
1958     if (!cb) {
1959         dolog ("Could not allocate capture callback information, size %zu\n",
1960                sizeof (*cb));
1961         goto err0;
1962     }
1963     cb->ops = *ops;
1964     cb->opaque = cb_opaque;
1965 
1966     cap = audio_pcm_capture_find_specific (as);
1967     if (cap) {
1968         QLIST_INSERT_HEAD (&cap->cb_head, cb, entries);
1969         return cap;
1970     }
1971     else {
1972         HWVoiceOut *hw;
1973         CaptureVoiceOut *cap;
1974 
1975         cap = audio_calloc(__func__, 1, sizeof(*cap));
1976         if (!cap) {
1977             dolog ("Could not allocate capture voice, size %zu\n",
1978                    sizeof (*cap));
1979             goto err1;
1980         }
1981 
1982         hw = &cap->hw;
1983         QLIST_INIT (&hw->sw_head);
1984         QLIST_INIT (&cap->cb_head);
1985 
1986         /* XXX find a more elegant way */
1987         hw->samples = 4096 * 4;
1988         hw->mix_buf = audio_calloc(__func__, hw->samples,
1989                                    sizeof(struct st_sample));
1990         if (!hw->mix_buf) {
1991             dolog ("Could not allocate capture mix buffer (%d samples)\n",
1992                    hw->samples);
1993             goto err2;
1994         }
1995 
1996         audio_pcm_init_info (&hw->info, as);
1997 
1998         cap->buf = audio_calloc(__func__, hw->samples, 1 << hw->info.shift);
1999         if (!cap->buf) {
2000             dolog ("Could not allocate capture buffer "
2001                    "(%d samples, each %d bytes)\n",
2002                    hw->samples, 1 << hw->info.shift);
2003             goto err3;
2004         }
2005 
2006         hw->clip = mixeng_clip
2007             [hw->info.nchannels == 2]
2008             [hw->info.sign]
2009             [hw->info.swap_endianness]
2010             [audio_bits_to_index (hw->info.bits)];
2011 
2012         QLIST_INSERT_HEAD (&s->cap_head, cap, entries);
2013         QLIST_INSERT_HEAD (&cap->cb_head, cb, entries);
2014 
2015         QLIST_FOREACH(hw, &glob_audio_state.hw_head_out, entries) {
2016             audio_attach_capture (hw);
2017         }
2018         return cap;
2019 
2020     err3:
2021         g_free (cap->hw.mix_buf);
2022     err2:
2023         g_free (cap);
2024     err1:
2025         g_free (cb);
2026     err0:
2027         return NULL;
2028     }
2029 }
2030 
2031 void AUD_del_capture (CaptureVoiceOut *cap, void *cb_opaque)
2032 {
2033     struct capture_callback *cb;
2034 
2035     for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
2036         if (cb->opaque == cb_opaque) {
2037             cb->ops.destroy (cb_opaque);
2038             QLIST_REMOVE (cb, entries);
2039             g_free (cb);
2040 
2041             if (!cap->cb_head.lh_first) {
2042                 SWVoiceOut *sw = cap->hw.sw_head.lh_first, *sw1;
2043 
2044                 while (sw) {
2045                     SWVoiceCap *sc = (SWVoiceCap *) sw;
2046 #ifdef DEBUG_CAPTURE
2047                     dolog ("freeing %s\n", sw->name);
2048 #endif
2049 
2050                     sw1 = sw->entries.le_next;
2051                     if (sw->rate) {
2052                         st_rate_stop (sw->rate);
2053                         sw->rate = NULL;
2054                     }
2055                     QLIST_REMOVE (sw, entries);
2056                     QLIST_REMOVE (sc, entries);
2057                     g_free (sc);
2058                     sw = sw1;
2059                 }
2060                 QLIST_REMOVE (cap, entries);
2061                 g_free (cap->hw.mix_buf);
2062                 g_free (cap->buf);
2063                 g_free (cap);
2064             }
2065             return;
2066         }
2067     }
2068 }
2069 
2070 void AUD_set_volume_out (SWVoiceOut *sw, int mute, uint8_t lvol, uint8_t rvol)
2071 {
2072     if (sw) {
2073         HWVoiceOut *hw = sw->hw;
2074 
2075         sw->vol.mute = mute;
2076         sw->vol.l = nominal_volume.l * lvol / 255;
2077         sw->vol.r = nominal_volume.r * rvol / 255;
2078 
2079         if (hw->pcm_ops->ctl_out) {
2080             hw->pcm_ops->ctl_out (hw, VOICE_VOLUME, sw);
2081         }
2082     }
2083 }
2084 
2085 void AUD_set_volume_in (SWVoiceIn *sw, int mute, uint8_t lvol, uint8_t rvol)
2086 {
2087     if (sw) {
2088         HWVoiceIn *hw = sw->hw;
2089 
2090         sw->vol.mute = mute;
2091         sw->vol.l = nominal_volume.l * lvol / 255;
2092         sw->vol.r = nominal_volume.r * rvol / 255;
2093 
2094         if (hw->pcm_ops->ctl_in) {
2095             hw->pcm_ops->ctl_in (hw, VOICE_VOLUME, sw);
2096         }
2097     }
2098 }
2099