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