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