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