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