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