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