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