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