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