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