]> git.proxmox.com Git - qemu.git/blobdiff - audio/audio.c
Merge remote-tracking branch 'kwolf/for-anthony' into staging
[qemu.git] / audio / audio.c
index 5e9d88bb1a1ea42ee6a0a7c50ede1473b206a088..1c7738930b639964b8020411579bc7b95b2b979e 100644 (file)
@@ -23,7 +23,7 @@
  */
 #include "hw/hw.h"
 #include "audio.h"
-#include "console.h"
+#include "monitor.h"
 #include "qemu-timer.h"
 #include "sysemu.h"
 
 /* #define DEBUG_LIVE */
 /* #define DEBUG_OUT */
 /* #define DEBUG_CAPTURE */
+/* #define DEBUG_POLL */
 
 #define SW_NAME(sw) (sw)->name ? (sw)->name : "unknown"
 
+
+/* Order of CONFIG_AUDIO_DRIVERS is import.
+   The 1st one is the one used by default, that is the reason
+    that we generate the list.
+*/
 static struct audio_driver *drvtab[] = {
-#ifdef CONFIG_OSS
-    &oss_audio_driver,
-#endif
-#ifdef CONFIG_ALSA
-    &alsa_audio_driver,
-#endif
-#ifdef CONFIG_COREAUDIO
-    &coreaudio_audio_driver,
-#endif
-#ifdef CONFIG_DSOUND
-    &dsound_audio_driver,
-#endif
-#ifdef CONFIG_FMOD
-    &fmod_audio_driver,
-#endif
-#ifdef CONFIG_SDL
-    &sdl_audio_driver,
+#ifdef CONFIG_SPICE
+    &spice_audio_driver,
 #endif
+    CONFIG_AUDIO_DRIVERS
     &no_audio_driver,
     &wav_audio_driver
 };
@@ -64,81 +56,71 @@ struct fixed_settings {
     int enabled;
     int nb_voices;
     int greedy;
-    audsettings_t settings;
+    struct audsettings settings;
 };
 
 static struct {
     struct fixed_settings fixed_out;
     struct fixed_settings fixed_in;
     union {
-        int hz;
+        int hertz;
         int64_t ticks;
     } period;
     int plive;
     int log_to_monitor;
+    int try_poll_in;
+    int try_poll_out;
 } conf = {
-    {                           /* DAC fixed settings */
-        1,                      /* enabled */
-        1,                      /* nb_voices */
-        1,                      /* greedy */
-        {
-            44100,              /* freq */
-            2,                  /* nchannels */
-            AUD_FMT_S16,        /* fmt */
-            AUDIO_HOST_ENDIANNESS
+    .fixed_out = { /* DAC fixed settings */
+        .enabled = 1,
+        .nb_voices = 1,
+        .greedy = 1,
+        .settings = {
+            .freq = 44100,
+            .nchannels = 2,
+            .fmt = AUD_FMT_S16,
+            .endianness =  AUDIO_HOST_ENDIANNESS,
         }
     },
 
-    {                           /* ADC fixed settings */
-        1,                      /* enabled */
-        1,                      /* nb_voices */
-        1,                      /* greedy */
-        {
-            44100,              /* freq */
-            2,                  /* nchannels */
-            AUD_FMT_S16,        /* fmt */
-            AUDIO_HOST_ENDIANNESS
+    .fixed_in = { /* ADC fixed settings */
+        .enabled = 1,
+        .nb_voices = 1,
+        .greedy = 1,
+        .settings = {
+            .freq = 44100,
+            .nchannels = 2,
+            .fmt = AUD_FMT_S16,
+            .endianness = AUDIO_HOST_ENDIANNESS,
         }
     },
 
-    { 0 },                      /* period */
-    0,                          /* plive */
-    0                           /* log_to_monitor */
+    .period = { .hertz = 250 },
+    .plive = 0,
+    .log_to_monitor = 0,
+    .try_poll_in = 1,
+    .try_poll_out = 1,
 };
 
 static AudioState glob_audio_state;
 
-volume_t nominal_volume = {
-    0,
+const struct mixeng_volume nominal_volume = {
+    .mute = 0,
 #ifdef FLOAT_MIXENG
-    1.0,
-    1.0
+    .r = 1.0,
+    .l = 1.0,
 #else
-    UINT_MAX,
-    UINT_MAX
+    .r = 1ULL << 32,
+    .l = 1ULL << 32,
 #endif
 };
 
-/* http://www.df.lth.se/~john_e/gems/gem002d.html */
-/* http://www.multi-platforms.com/Tips/PopCount.htm */
-uint32_t popcount (uint32_t u)
-{
-    u = ((u&0x55555555) + ((u>>1)&0x55555555));
-    u = ((u&0x33333333) + ((u>>2)&0x33333333));
-    u = ((u&0x0f0f0f0f) + ((u>>4)&0x0f0f0f0f));
-    u = ((u&0x00ff00ff) + ((u>>8)&0x00ff00ff));
-    u = ( u&0x0000ffff) + (u>>16);
-    return u;
-}
-
-inline uint32_t lsbindex (uint32_t u)
-{
-    return popcount ((u&-u)-1);
-}
-
 #ifdef AUDIO_IS_FLAWLESS_AND_NO_CHECKS_ARE_REQURIED
 #error No its not
 #else
+static void audio_print_options (const char *prefix,
+                                 struct audio_option *opt);
+
 int audio_bug (const char *funcname, int cond)
 {
     if (cond) {
@@ -146,10 +128,16 @@ int audio_bug (const char *funcname, int cond)
 
         AUD_log (NULL, "A bug was just triggered in %s\n", funcname);
         if (!shown) {
+            struct audio_driver *d;
+
             shown = 1;
             AUD_log (NULL, "Save all your work and restart without audio\n");
-            AUD_log (NULL, "Please send bug report to malc@pulsesoft.com\n");
+            AUD_log (NULL, "Please send bug report to av1474@comtv.ru\n");
             AUD_log (NULL, "I am sorry\n");
+            d = glob_audio_state.drv;
+            if (d) {
+                audio_print_options (d->name, d->options);
+            }
         }
         AUD_log (NULL, "Context:\n");
 
@@ -208,33 +196,31 @@ void *audio_calloc (const char *funcname, int nmemb, size_t size)
         return NULL;
     }
 
-    return qemu_mallocz (len);
+    return g_malloc0 (len);
 }
 
 static char *audio_alloc_prefix (const char *s)
 {
     const char qemu_prefix[] = "QEMU_";
-    size_t len;
-    char *r;
+    size_t len, i;
+    char *r, *u;
 
     if (!s) {
         return NULL;
     }
 
     len = strlen (s);
-    r = qemu_malloc (len + sizeof (qemu_prefix));
+    r = g_malloc (len + sizeof (qemu_prefix));
 
-    if (r) {
-        size_t i;
-        char *u = r + sizeof (qemu_prefix) - 1;
+    u = r + sizeof (qemu_prefix) - 1;
 
-        strcpy (r, qemu_prefix);
-        strcat (r, s);
+    pstrcpy (r, len + sizeof (qemu_prefix), qemu_prefix);
+    pstrcat (r, len + sizeof (qemu_prefix), s);
 
-        for (i = 0; i < len; ++i) {
-            u[i] = toupper (u[i]);
-        }
+    for (i = 0; i < len; ++i) {
+        u[i] = qemu_toupper(u[i]);
     }
+
     return r;
 }
 
@@ -347,10 +333,10 @@ void AUD_vlog (const char *cap, const char *fmt, va_list ap)
 {
     if (conf.log_to_monitor) {
         if (cap) {
-            term_printf ("%s: ", cap);
+            monitor_printf(default_mon, "%s: ", cap);
         }
 
-        term_vprintf (fmt, ap);
+        monitor_vprintf(default_mon, fmt, ap);
     }
     else {
         if (cap) {
@@ -414,7 +400,7 @@ static void audio_print_options (const char *prefix,
             {
                 audfmt_e *fmtp = opt->valp;
                 printf (
-                    "format, %s = %s, (one of: U8 S8 U16 S16)\n",
+                    "format, %s = %s, (one of: U8 S8 U16 S16 U32 S32)\n",
                     state,
                     audio_audfmt_to_string (*fmtp)
                     );
@@ -439,7 +425,7 @@ static void audio_print_options (const char *prefix,
         printf ("    %s\n", opt->descr);
     }
 
-    qemu_free (uprefix);
+    g_free (uprefix);
 }
 
 static void audio_process_options (const char *prefix,
@@ -447,7 +433,7 @@ static void audio_process_options (const char *prefix,
 {
     char *optname;
     const char qemu_prefix[] = "QEMU_";
-    size_t preflen;
+    size_t preflen, optlen;
 
     if (audio_bug (AUDIO_FUNC, !prefix)) {
         dolog ("prefix = NULL\n");
@@ -475,21 +461,17 @@ static void audio_process_options (const char *prefix,
         /* len of opt->name + len of prefix + size of qemu_prefix
          * (includes trailing zero) + zero + underscore (on behalf of
          * sizeof) */
-        optname = qemu_malloc (len + preflen + sizeof (qemu_prefix) + 1);
-        if (!optname) {
-            dolog ("Could not allocate memory for option name `%s'\n",
-                   opt->name);
-            continue;
-        }
+        optlen = len + preflen + sizeof (qemu_prefix) + 1;
+        optname = g_malloc (optlen);
 
-        strcpy (optname, qemu_prefix);
+        pstrcpy (optname, optlen, qemu_prefix);
 
         /* copy while upper-casing, including trailing zero */
         for (i = 0; i <= preflen; ++i) {
-            optname[i + sizeof (qemu_prefix) - 1] = toupper (prefix[i]);
+            optname[i + sizeof (qemu_prefix) - 1] = qemu_toupper(prefix[i]);
         }
-        strcat (optname, "_");
-        strcat (optname, opt->name);
+        pstrcat (optname, optlen, "_");
+        pstrcat (optname, optlen, opt->name);
 
         def = 1;
         switch (opt->tag) {
@@ -525,11 +507,11 @@ static void audio_process_options (const char *prefix,
             opt->overriddenp = &opt->overridden;
         }
         *opt->overriddenp = !def;
-        qemu_free (optname);
+        g_free (optname);
     }
 }
 
-static void audio_print_settings (audsettings_t *as)
+static void audio_print_settings (struct audsettings *as)
 {
     dolog ("frequency=%d nchannels=%d fmt=", as->freq, as->nchannels);
 
@@ -546,6 +528,12 @@ static void audio_print_settings (audsettings_t *as)
     case AUD_FMT_U16:
         AUD_log (NULL, "U16");
         break;
+    case AUD_FMT_S32:
+        AUD_log (NULL, "S32");
+        break;
+    case AUD_FMT_U32:
+        AUD_log (NULL, "U32");
+        break;
     default:
         AUD_log (NULL, "invalid(%d)", as->fmt);
         break;
@@ -566,7 +554,7 @@ static void audio_print_settings (audsettings_t *as)
     AUD_log (NULL, "\n");
 }
 
-static int audio_validate_settings (audsettings_t *as)
+static int audio_validate_settings (struct audsettings *as)
 {
     int invalid;
 
@@ -590,24 +578,27 @@ static int audio_validate_settings (audsettings_t *as)
     return invalid ? -1 : 0;
 }
 
-static int audio_pcm_info_eq (struct audio_pcm_info *info, audsettings_t *as)
+static int audio_pcm_info_eq (struct audio_pcm_info *info, struct audsettings *as)
 {
     int bits = 8, sign = 0;
 
     switch (as->fmt) {
     case AUD_FMT_S8:
         sign = 1;
+        /* fall through */
     case AUD_FMT_U8:
         break;
 
     case AUD_FMT_S16:
         sign = 1;
+        /* fall through */
     case AUD_FMT_U16:
         bits = 16;
         break;
 
     case AUD_FMT_S32:
         sign = 1;
+        /* fall through */
     case AUD_FMT_U32:
         bits = 32;
         break;
@@ -619,7 +610,7 @@ static int audio_pcm_info_eq (struct audio_pcm_info *info, audsettings_t *as)
         && info->swap_endianness == (as->endianness != AUDIO_HOST_ENDIANNESS);
 }
 
-void audio_pcm_init_info (struct audio_pcm_info *info, audsettings_t *as)
+void audio_pcm_init_info (struct audio_pcm_info *info, struct audsettings *as)
 {
     int bits = 8, sign = 0, shift = 0;
 
@@ -714,21 +705,19 @@ void audio_pcm_info_clear_buf (struct audio_pcm_info *info, void *buf, int len)
 /*
  * Capture
  */
-static void noop_conv (st_sample_t *dst, const void *src,
-                       int samples, volume_t *vol)
+static void noop_conv (struct st_sample *dst, const void *src, int samples)
 {
     (void) src;
     (void) dst;
     (void) samples;
-    (void) vol;
 }
 
 static CaptureVoiceOut *audio_pcm_capture_find_specific (
-    AudioState *s,
-    audsettings_t *as
+    struct audsettings *as
     )
 {
     CaptureVoiceOut *cap;
+    AudioState *s = &glob_audio_state;
 
     for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
         if (audio_pcm_info_eq (&cap->hw.info, as)) {
@@ -790,9 +779,9 @@ static void audio_detach_capture (HWVoiceOut *hw)
             sw->rate = NULL;
         }
 
-        LIST_REMOVE (sw, entries);
-        LIST_REMOVE (sc, entries);
-        qemu_free (sc);
+        QLIST_REMOVE (sw, entries);
+        QLIST_REMOVE (sc, entries);
+        g_free (sc);
         if (was_active) {
             /* We have removed soft voice from the capture:
                this might have changed the overall status of the capture
@@ -803,8 +792,9 @@ static void audio_detach_capture (HWVoiceOut *hw)
     }
 }
 
-static int audio_attach_capture (AudioState *s, HWVoiceOut *hw)
+static int audio_attach_capture (HWVoiceOut *hw)
 {
+    AudioState *s = &glob_audio_state;
     CaptureVoiceOut *cap;
 
     audio_detach_capture (hw);
@@ -828,14 +818,15 @@ static int audio_attach_capture (AudioState *s, HWVoiceOut *hw)
         sw->active = hw->enabled;
         sw->conv = noop_conv;
         sw->ratio = ((int64_t) hw_cap->info.freq << 32) / sw->info.freq;
+        sw->vol = nominal_volume;
         sw->rate = st_rate_start (sw->info.freq, hw_cap->info.freq);
         if (!sw->rate) {
             dolog ("Could not start rate conversion for `%s'\n", SW_NAME (sw));
-            qemu_free (sw);
+            g_free (sw);
             return -1;
         }
-        LIST_INSERT_HEAD (&hw_cap->sw_head, sw, entries);
-        LIST_INSERT_HEAD (&hw->cap_head, sc, entries);
+        QLIST_INSERT_HEAD (&hw_cap->sw_head, sw, entries);
+        QLIST_INSERT_HEAD (&hw->cap_head, sc, entries);
 #ifdef DEBUG_CAPTURE
         asprintf (&sw->name, "for %p %d,%d,%d",
                   hw, sw->info.freq, sw->info.bits, sw->info.nchannels);
@@ -874,6 +865,28 @@ int audio_pcm_hw_get_live_in (HWVoiceIn *hw)
     return live;
 }
 
+int audio_pcm_hw_clip_out (HWVoiceOut *hw, void *pcm_buf,
+                           int live, int pending)
+{
+    int left = hw->samples - pending;
+    int len = audio_MIN (left, live);
+    int clipped = 0;
+
+    while (len) {
+        struct st_sample *src = hw->mix_buf + hw->rpos;
+        uint8_t *dst = advance (pcm_buf, hw->rpos << hw->info.shift);
+        int samples_till_end_of_buf = hw->samples - hw->rpos;
+        int samples_to_clip = audio_MIN (len, samples_till_end_of_buf);
+
+        hw->clip (dst, src, samples_to_clip);
+
+        hw->rpos = (hw->rpos + samples_to_clip) % hw->samples;
+        len -= samples_to_clip;
+        clipped += samples_to_clip;
+    }
+    return clipped;
+}
+
 /*
  * Soft voice (capture)
  */
@@ -901,7 +914,7 @@ int audio_pcm_sw_read (SWVoiceIn *sw, void *buf, int size)
 {
     HWVoiceIn *hw = sw->hw;
     int samples, live, ret = 0, swlim, isamp, osamp, rpos, total = 0;
-    st_sample_t *src, *dst = sw->buf;
+    struct st_sample *src, *dst = sw->buf;
 
     rpos = audio_pcm_sw_get_rpos_in (sw) % hw->samples;
 
@@ -945,6 +958,10 @@ int audio_pcm_sw_read (SWVoiceIn *sw, void *buf, int size)
         total += isamp;
     }
 
+    if (!(hw->ctl_caps & VOICE_VOLUME_CAP)) {
+        mixeng_volume (sw->buf, ret, &sw->vol);
+    }
+
     sw->clip (buf, sw->buf, ret);
     sw->total_hw_samples_acquired += total;
     return ret << sw->info.shift;
@@ -970,16 +987,17 @@ static int audio_pcm_hw_find_min_out (HWVoiceOut *hw, int *nb_livep)
     return m;
 }
 
-int audio_pcm_hw_get_live_out2 (HWVoiceOut *hw, int *nb_live)
+static int audio_pcm_hw_get_live_out (HWVoiceOut *hw, int *nb_live)
 {
     int smin;
+    int nb_live1;
 
-    smin = audio_pcm_hw_find_min_out (hw, nb_live);
-
-    if (!*nb_live) {
-        return 0;
+    smin = audio_pcm_hw_find_min_out (hw, &nb_live1);
+    if (nb_live) {
+        *nb_live = nb_live1;
     }
-    else {
+
+    if (nb_live1) {
         int live = smin;
 
         if (audio_bug (AUDIO_FUNC, live < 0 || live > hw->samples)) {
@@ -988,19 +1006,7 @@ int audio_pcm_hw_get_live_out2 (HWVoiceOut *hw, int *nb_live)
         }
         return live;
     }
-}
-
-int audio_pcm_hw_get_live_out (HWVoiceOut *hw)
-{
-    int nb_live;
-    int live;
-
-    live = audio_pcm_hw_get_live_out2 (hw, &nb_live);
-    if (audio_bug (AUDIO_FUNC, live < 0 || live > hw->samples)) {
-        dolog ("live=%d hw->samples=%d\n", live, hw->samples);
-        return 0;
-    }
-    return live;
+    return 0;
 }
 
 /*
@@ -1037,7 +1043,11 @@ int audio_pcm_sw_write (SWVoiceOut *sw, void *buf, int size)
     swlim = ((int64_t) dead << 32) / sw->ratio;
     swlim = audio_MIN (swlim, samples);
     if (swlim) {
-        sw->conv (sw->buf, buf, swlim, &sw->vol);
+        sw->conv (sw->buf, buf, swlim);
+
+        if (!(sw->hw->ctl_caps & VOICE_VOLUME_CAP)) {
+            mixeng_volume (sw->buf, swlim, &sw->vol);
+        }
     }
 
     while (swlim) {
@@ -1093,6 +1103,42 @@ static void audio_pcm_print_info (const char *cap, struct audio_pcm_info *info)
 #undef DAC
 #include "audio_template.h"
 
+/*
+ * Timer
+ */
+static int audio_is_timer_needed (void)
+{
+    HWVoiceIn *hwi = NULL;
+    HWVoiceOut *hwo = NULL;
+
+    while ((hwo = audio_pcm_hw_find_any_enabled_out (hwo))) {
+        if (!hwo->poll_mode) return 1;
+    }
+    while ((hwi = audio_pcm_hw_find_any_enabled_in (hwi))) {
+        if (!hwi->poll_mode) return 1;
+    }
+    return 0;
+}
+
+static void audio_reset_timer (AudioState *s)
+{
+    if (audio_is_timer_needed ()) {
+        qemu_mod_timer (s->ts, qemu_get_clock_ns (vm_clock) + 1);
+    }
+    else {
+        qemu_del_timer (s->ts);
+    }
+}
+
+static void audio_timer (void *opaque)
+{
+    audio_run ("timer");
+    audio_reset_timer (opaque);
+}
+
+/*
+ * Public API
+ */
 int AUD_write (SWVoiceOut *sw, void *buf, int size)
 {
     int bytes;
@@ -1144,6 +1190,7 @@ void AUD_set_active_out (SWVoiceOut *sw, int on)
 
     hw = sw->hw;
     if (sw->active != on) {
+        AudioState *s = &glob_audio_state;
         SWVoiceOut *temp_sw;
         SWVoiceCap *sc;
 
@@ -1151,7 +1198,10 @@ void AUD_set_active_out (SWVoiceOut *sw, int on)
             hw->pending_disable = 0;
             if (!hw->enabled) {
                 hw->enabled = 1;
-                hw->pcm_ops->ctl_out (hw, VOICE_ENABLE);
+                if (s->vm_running) {
+                    hw->pcm_ops->ctl_out (hw, VOICE_ENABLE, conf.try_poll_out);
+                    audio_reset_timer (s);
+                }
             }
         }
         else {
@@ -1187,12 +1237,16 @@ void AUD_set_active_in (SWVoiceIn *sw, int on)
 
     hw = sw->hw;
     if (sw->active != on) {
+        AudioState *s = &glob_audio_state;
         SWVoiceIn *temp_sw;
 
         if (on) {
             if (!hw->enabled) {
                 hw->enabled = 1;
-                hw->pcm_ops->ctl_in (hw, VOICE_ENABLE);
+                if (s->vm_running) {
+                    hw->pcm_ops->ctl_in (hw, VOICE_ENABLE, conf.try_poll_in);
+                    audio_reset_timer (s);
+                }
             }
             sw->total_hw_samples_acquired = hw->total_samples_captured;
         }
@@ -1306,11 +1360,11 @@ static void audio_run_out (AudioState *s)
     HWVoiceOut *hw = NULL;
     SWVoiceOut *sw;
 
-    while ((hw = audio_pcm_hw_find_any_enabled_out (s, hw))) {
+    while ((hw = audio_pcm_hw_find_any_enabled_out (hw))) {
         int played;
         int live, free, nb_live, cleanup_required, prev_rpos;
 
-        live = audio_pcm_hw_get_live_out2 (hw, &nb_live);
+        live = audio_pcm_hw_get_live_out (hw, &nb_live);
         if (!nb_live) {
             live = 0;
         }
@@ -1348,7 +1402,7 @@ static void audio_run_out (AudioState *s)
         }
 
         prev_rpos = hw->rpos;
-        played = hw->pcm_ops->run_out (hw);
+        played = hw->pcm_ops->run_out (hw, live);
         if (audio_bug (AUDIO_FUNC, hw->rpos >= hw->samples)) {
             dolog ("hw->rpos=%d hw->samples=%d played=%d\n",
                    hw->rpos, hw->samples, played);
@@ -1401,7 +1455,7 @@ static void audio_run_out (AudioState *s)
 #ifdef DEBUG_PLIVE
                     dolog ("Finishing with old voice\n");
 #endif
-                    audio_close_out (s, sw);
+                    audio_close_out (sw);
                 }
                 sw = sw1;
             }
@@ -1413,7 +1467,7 @@ static void audio_run_in (AudioState *s)
 {
     HWVoiceIn *hw = NULL;
 
-    while ((hw = audio_pcm_hw_find_any_enabled_in (s, hw))) {
+    while ((hw = audio_pcm_hw_find_any_enabled_in (hw))) {
         SWVoiceIn *sw;
         int captured, min;
 
@@ -1447,12 +1501,12 @@ static void audio_run_capture (AudioState *s)
         HWVoiceOut *hw = &cap->hw;
         SWVoiceOut *sw;
 
-        captured = live = audio_pcm_hw_get_live_out (hw);
+        captured = live = audio_pcm_hw_get_live_out (hw, NULL);
         rpos = hw->rpos;
         while (live) {
             int left = hw->samples - rpos;
             int to_capture = audio_MIN (live, left);
-            st_sample_t *src;
+            struct st_sample *src;
             struct capture_callback *cb;
 
             src = hw->mix_buf + rpos;
@@ -1485,61 +1539,126 @@ static void audio_run_capture (AudioState *s)
     }
 }
 
-static void audio_timer (void *opaque)
+void audio_run (const char *msg)
 {
-    AudioState *s = opaque;
+    AudioState *s = &glob_audio_state;
 
     audio_run_out (s);
     audio_run_in (s);
     audio_run_capture (s);
+#ifdef DEBUG_POLL
+    {
+        static double prevtime;
+        double currtime;
+        struct timeval tv;
+
+        if (gettimeofday (&tv, NULL)) {
+            perror ("audio_run: gettimeofday");
+            return;
+        }
 
-    qemu_mod_timer (s->ts, qemu_get_clock (vm_clock) + conf.period.ticks);
+        currtime = tv.tv_sec + tv.tv_usec * 1e-6;
+        dolog ("Elapsed since last %s: %f\n", msg, currtime - prevtime);
+        prevtime = currtime;
+    }
+#endif
 }
 
 static struct audio_option audio_options[] = {
     /* DAC */
-    {"DAC_FIXED_SETTINGS", AUD_OPT_BOOL, &conf.fixed_out.enabled,
-     "Use fixed settings for host DAC", NULL, 0},
-
-    {"DAC_FIXED_FREQ", AUD_OPT_INT, &conf.fixed_out.settings.freq,
-     "Frequency for fixed host DAC", NULL, 0},
-
-    {"DAC_FIXED_FMT", AUD_OPT_FMT, &conf.fixed_out.settings.fmt,
-     "Format for fixed host DAC", NULL, 0},
-
-    {"DAC_FIXED_CHANNELS", AUD_OPT_INT, &conf.fixed_out.settings.nchannels,
-     "Number of channels for fixed DAC (1 - mono, 2 - stereo)", NULL, 0},
-
-    {"DAC_VOICES", AUD_OPT_INT, &conf.fixed_out.nb_voices,
-     "Number of voices for DAC", NULL, 0},
-
+    {
+        .name  = "DAC_FIXED_SETTINGS",
+        .tag   = AUD_OPT_BOOL,
+        .valp  = &conf.fixed_out.enabled,
+        .descr = "Use fixed settings for host DAC"
+    },
+    {
+        .name  = "DAC_FIXED_FREQ",
+        .tag   = AUD_OPT_INT,
+        .valp  = &conf.fixed_out.settings.freq,
+        .descr = "Frequency for fixed host DAC"
+    },
+    {
+        .name  = "DAC_FIXED_FMT",
+        .tag   = AUD_OPT_FMT,
+        .valp  = &conf.fixed_out.settings.fmt,
+        .descr = "Format for fixed host DAC"
+    },
+    {
+        .name  = "DAC_FIXED_CHANNELS",
+        .tag   = AUD_OPT_INT,
+        .valp  = &conf.fixed_out.settings.nchannels,
+        .descr = "Number of channels for fixed DAC (1 - mono, 2 - stereo)"
+    },
+    {
+        .name  = "DAC_VOICES",
+        .tag   = AUD_OPT_INT,
+        .valp  = &conf.fixed_out.nb_voices,
+        .descr = "Number of voices for DAC"
+    },
+    {
+        .name  = "DAC_TRY_POLL",
+        .tag   = AUD_OPT_BOOL,
+        .valp  = &conf.try_poll_out,
+        .descr = "Attempt using poll mode for DAC"
+    },
     /* ADC */
-    {"ADC_FIXED_SETTINGS", AUD_OPT_BOOL, &conf.fixed_in.enabled,
-     "Use fixed settings for host ADC", NULL, 0},
-
-    {"ADC_FIXED_FREQ", AUD_OPT_INT, &conf.fixed_in.settings.freq,
-     "Frequency for fixed host ADC", NULL, 0},
-
-    {"ADC_FIXED_FMT", AUD_OPT_FMT, &conf.fixed_in.settings.fmt,
-     "Format for fixed host ADC", NULL, 0},
-
-    {"ADC_FIXED_CHANNELS", AUD_OPT_INT, &conf.fixed_in.settings.nchannels,
-     "Number of channels for fixed ADC (1 - mono, 2 - stereo)", NULL, 0},
-
-    {"ADC_VOICES", AUD_OPT_INT, &conf.fixed_in.nb_voices,
-     "Number of voices for ADC", NULL, 0},
-
+    {
+        .name  = "ADC_FIXED_SETTINGS",
+        .tag   = AUD_OPT_BOOL,
+        .valp  = &conf.fixed_in.enabled,
+        .descr = "Use fixed settings for host ADC"
+    },
+    {
+        .name  = "ADC_FIXED_FREQ",
+        .tag   = AUD_OPT_INT,
+        .valp  = &conf.fixed_in.settings.freq,
+        .descr = "Frequency for fixed host ADC"
+    },
+    {
+        .name  = "ADC_FIXED_FMT",
+        .tag   = AUD_OPT_FMT,
+        .valp  = &conf.fixed_in.settings.fmt,
+        .descr = "Format for fixed host ADC"
+    },
+    {
+        .name  = "ADC_FIXED_CHANNELS",
+        .tag   = AUD_OPT_INT,
+        .valp  = &conf.fixed_in.settings.nchannels,
+        .descr = "Number of channels for fixed ADC (1 - mono, 2 - stereo)"
+    },
+    {
+        .name  = "ADC_VOICES",
+        .tag   = AUD_OPT_INT,
+        .valp  = &conf.fixed_in.nb_voices,
+        .descr = "Number of voices for ADC"
+    },
+    {
+        .name  = "ADC_TRY_POLL",
+        .tag   = AUD_OPT_BOOL,
+        .valp  = &conf.try_poll_in,
+        .descr = "Attempt using poll mode for ADC"
+    },
     /* Misc */
-    {"TIMER_PERIOD", AUD_OPT_INT, &conf.period.hz,
-     "Timer period in HZ (0 - use lowest possible)", NULL, 0},
-
-    {"PLIVE", AUD_OPT_BOOL, &conf.plive,
-     "(undocumented)", NULL, 0},
-
-    {"LOG_TO_MONITOR", AUD_OPT_BOOL, &conf.log_to_monitor,
-     "print logging messages to montior instead of stderr", NULL, 0},
-
-    {NULL, 0, NULL, NULL, NULL, 0}
+    {
+        .name  = "TIMER_PERIOD",
+        .tag   = AUD_OPT_INT,
+        .valp  = &conf.period.hertz,
+        .descr = "Timer period in HZ (0 - use lowest possible)"
+    },
+    {
+        .name  = "PLIVE",
+        .tag   = AUD_OPT_BOOL,
+        .valp  = &conf.plive,
+        .descr = "(undocumented)"
+    },
+    {
+        .name  = "LOG_TO_MONITOR",
+        .tag   = AUD_OPT_BOOL,
+        .valp  = &conf.log_to_monitor,
+        .descr = "Print logging messages to monitor instead of stderr"
+    },
+    { /* End of list */ }
 };
 
 static void audio_pp_nb_voices (const char *typ, int nb)
@@ -1555,7 +1674,7 @@ static void audio_pp_nb_voices (const char *typ, int nb)
         printf ("Theoretically supports many %s voices\n", typ);
         break;
     default:
-        printf ("Theoretically supports upto %d %s voices\n", nb, typ);
+        printf ("Theoretically supports up to %d %s voices\n", nb, typ);
         break;
     }
 
@@ -1566,7 +1685,7 @@ void AUD_help (void)
     size_t i;
 
     audio_process_options ("AUDIO", audio_options);
-    for (i = 0; i < sizeof (drvtab) / sizeof (drvtab[0]); i++) {
+    for (i = 0; i < ARRAY_SIZE (drvtab); i++) {
         struct audio_driver *d = drvtab[i];
         if (d->options) {
             audio_process_options (d->name, d->options);
@@ -1579,7 +1698,7 @@ void AUD_help (void)
 
     printf ("Available drivers:\n");
 
-    for (i = 0; i < sizeof (drvtab) / sizeof (drvtab[0]); i++) {
+    for (i = 0; i < ARRAY_SIZE (drvtab); i++) {
         struct audio_driver *d = drvtab[i];
 
         printf ("Name: %s\n", d->name);
@@ -1621,8 +1740,8 @@ static int audio_driver_init (AudioState *s, struct audio_driver *drv)
     s->drv_opaque = drv->init ();
 
     if (s->drv_opaque) {
-        audio_init_nb_voices_out (s, drv);
-        audio_init_nb_voices_in (s, drv);
+        audio_init_nb_voices_out (drv);
+        audio_init_nb_voices_in (drv);
         s->drv = drv;
         return 0;
     }
@@ -1632,20 +1751,23 @@ static int audio_driver_init (AudioState *s, struct audio_driver *drv)
     }
 }
 
-static void audio_vm_change_state_handler (void *opaque, int running)
+static void audio_vm_change_state_handler (void *opaque, int running,
+                                           RunState state)
 {
     AudioState *s = opaque;
     HWVoiceOut *hwo = NULL;
     HWVoiceIn *hwi = NULL;
     int op = running ? VOICE_ENABLE : VOICE_DISABLE;
 
-    while ((hwo = audio_pcm_hw_find_any_enabled_out (s, hwo))) {
-        hwo->pcm_ops->ctl_out (hwo, op);
+    s->vm_running = running;
+    while ((hwo = audio_pcm_hw_find_any_enabled_out (hwo))) {
+        hwo->pcm_ops->ctl_out (hwo, op, conf.try_poll_out);
     }
 
-    while ((hwi = audio_pcm_hw_find_any_enabled_in (s, hwi))) {
-        hwi->pcm_ops->ctl_in (hwi, op);
+    while ((hwi = audio_pcm_hw_find_any_enabled_in (hwi))) {
+        hwi->pcm_ops->ctl_in (hwi, op, conf.try_poll_in);
     }
+    audio_reset_timer (s);
 }
 
 static void audio_atexit (void)
@@ -1654,10 +1776,12 @@ static void audio_atexit (void)
     HWVoiceOut *hwo = NULL;
     HWVoiceIn *hwi = NULL;
 
-    while ((hwo = audio_pcm_hw_find_any_enabled_out (s, hwo))) {
+    while ((hwo = audio_pcm_hw_find_any_out (hwo))) {
         SWVoiceCap *sc;
 
-        hwo->pcm_ops->ctl_out (hwo, VOICE_DISABLE);
+        if (hwo->enabled) {
+            hwo->pcm_ops->ctl_out (hwo, VOICE_DISABLE);
+        }
         hwo->pcm_ops->fini_out (hwo);
 
         for (sc = hwo->cap_head.lh_first; sc; sc = sc->entries.le_next) {
@@ -1670,8 +1794,10 @@ static void audio_atexit (void)
         }
     }
 
-    while ((hwi = audio_pcm_hw_find_any_enabled_in (s, hwi))) {
-        hwi->pcm_ops->ctl_in (hwi, VOICE_DISABLE);
+    while ((hwi = audio_pcm_hw_find_any_in (hwi))) {
+        if (hwi->enabled) {
+            hwi->pcm_ops->ctl_in (hwi, VOICE_DISABLE);
+        }
         hwi->pcm_ops->fini_in (hwi);
     }
 
@@ -1680,55 +1806,36 @@ static void audio_atexit (void)
     }
 }
 
-static void audio_save (QEMUFile *f, void *opaque)
-{
-    (void) f;
-    (void) opaque;
-}
-
-static int audio_load (QEMUFile *f, void *opaque, int version_id)
-{
-    (void) f;
-    (void) opaque;
-
-    if (version_id != 1) {
-        return -EINVAL;
+static const VMStateDescription vmstate_audio = {
+    .name = "audio",
+    .version_id = 1,
+    .minimum_version_id = 1,
+    .minimum_version_id_old = 1,
+    .fields      = (VMStateField []) {
+        VMSTATE_END_OF_LIST()
     }
+};
 
-    return 0;
-}
-
-void AUD_register_card (AudioState *s, const char *name, QEMUSoundCard *card)
-{
-    card->audio = s;
-    card->name = qemu_strdup (name);
-    memset (&card->entries, 0, sizeof (card->entries));
-    LIST_INSERT_HEAD (&s->card_head, card, entries);
-}
-
-void AUD_remove_card (QEMUSoundCard *card)
-{
-    LIST_REMOVE (card, entries);
-    card->audio = NULL;
-    qemu_free (card->name);
-}
-
-AudioState *AUD_init (void)
+static void audio_init (void)
 {
     size_t i;
     int done = 0;
     const char *drvname;
+    VMChangeStateEntry *e;
     AudioState *s = &glob_audio_state;
 
-    LIST_INIT (&s->hw_head_out);
-    LIST_INIT (&s->hw_head_in);
-    LIST_INIT (&s->cap_head);
+    if (s->drv) {
+        return;
+    }
+
+    QLIST_INIT (&s->hw_head_out);
+    QLIST_INIT (&s->hw_head_in);
+    QLIST_INIT (&s->cap_head);
     atexit (audio_atexit);
 
-    s->ts = qemu_new_timer (vm_clock, audio_timer, s);
+    s->ts = qemu_new_timer_ns (vm_clock, audio_timer, s);
     if (!s->ts) {
-        dolog ("Could not create audio timer\n");
-        return NULL;
+        hw_error("Could not create audio timer\n");
     }
 
     audio_process_options ("AUDIO", audio_options);
@@ -1756,7 +1863,7 @@ AudioState *AUD_init (void)
     if (drvname) {
         int found = 0;
 
-        for (i = 0; i < sizeof (drvtab) / sizeof (drvtab[0]); i++) {
+        for (i = 0; i < ARRAY_SIZE (drvtab); i++) {
             if (!strcmp (drvname, drvtab[i]->name)) {
                 done = !audio_driver_init (s, drvtab[i]);
                 found = 1;
@@ -1771,7 +1878,7 @@ AudioState *AUD_init (void)
     }
 
     if (!done) {
-        for (i = 0; !done && i < sizeof (drvtab) / sizeof (drvtab[0]); i++) {
+        for (i = 0; !done && i < ARRAY_SIZE (drvtab); i++) {
             if (drvtab[i]->can_be_default) {
                 done = !audio_driver_init (s, drvtab[i]);
             }
@@ -1781,60 +1888,60 @@ AudioState *AUD_init (void)
     if (!done) {
         done = !audio_driver_init (s, &no_audio_driver);
         if (!done) {
-            dolog ("Could not initialize audio subsystem\n");
+            hw_error("Could not initialize audio subsystem\n");
         }
         else {
             dolog ("warning: Using timer based audio emulation\n");
         }
     }
 
-    if (done) {
-        VMChangeStateEntry *e;
-
-        if (conf.period.hz <= 0) {
-            if (conf.period.hz < 0) {
-                dolog ("warning: Timer period is negative - %d "
-                       "treating as zero\n",
-                       conf.period.hz);
-            }
-            conf.period.ticks = 1;
-        }
-        else {
-            conf.period.ticks = ticks_per_sec / conf.period.hz;
-        }
-
-        e = qemu_add_vm_change_state_handler (audio_vm_change_state_handler, s);
-        if (!e) {
-            dolog ("warning: Could not register change state handler\n"
-                   "(Audio can continue looping even after stopping the VM)\n");
+    if (conf.period.hertz <= 0) {
+        if (conf.period.hertz < 0) {
+            dolog ("warning: Timer period is negative - %d "
+                   "treating as zero\n",
+                   conf.period.hertz);
         }
+        conf.period.ticks = 1;
+    } else {
+        conf.period.ticks =
+            muldiv64 (1, get_ticks_per_sec (), conf.period.hertz);
     }
-    else {
-        qemu_del_timer (s->ts);
-        return NULL;
+
+    e = qemu_add_vm_change_state_handler (audio_vm_change_state_handler, s);
+    if (!e) {
+        dolog ("warning: Could not register change state handler\n"
+               "(Audio can continue looping even after stopping the VM)\n");
     }
 
-    LIST_INIT (&s->card_head);
-    register_savevm ("audio", 0, 1, audio_save, audio_load, s);
-    qemu_mod_timer (s->ts, qemu_get_clock (vm_clock) + conf.period.ticks);
-    return s;
+    QLIST_INIT (&s->card_head);
+    vmstate_register (NULL, 0, &vmstate_audio, s);
+}
+
+void AUD_register_card (const char *name, QEMUSoundCard *card)
+{
+    audio_init ();
+    card->name = g_strdup (name);
+    memset (&card->entries, 0, sizeof (card->entries));
+    QLIST_INSERT_HEAD (&glob_audio_state.card_head, card, entries);
+}
+
+void AUD_remove_card (QEMUSoundCard *card)
+{
+    QLIST_REMOVE (card, entries);
+    g_free (card->name);
 }
 
+
 CaptureVoiceOut *AUD_add_capture (
-    AudioState *s,
-    audsettings_t *as,
+    struct audsettings *as,
     struct audio_capture_ops *ops,
     void *cb_opaque
     )
 {
+    AudioState *s = &glob_audio_state;
     CaptureVoiceOut *cap;
     struct capture_callback *cb;
 
-    if (!s) {
-        /* XXX suppress */
-        s = &glob_audio_state;
-    }
-
     if (audio_validate_settings (as)) {
         dolog ("Invalid settings were passed when trying to add capture\n");
         audio_print_settings (as);
@@ -1850,9 +1957,9 @@ CaptureVoiceOut *AUD_add_capture (
     cb->ops = *ops;
     cb->opaque = cb_opaque;
 
-    cap = audio_pcm_capture_find_specific (s, as);
+    cap = audio_pcm_capture_find_specific (as);
     if (cap) {
-        LIST_INSERT_HEAD (&cap->cb_head, cb, entries);
+        QLIST_INSERT_HEAD (&cap->cb_head, cb, entries);
         return cap;
     }
     else {
@@ -1867,13 +1974,13 @@ CaptureVoiceOut *AUD_add_capture (
         }
 
         hw = &cap->hw;
-        LIST_INIT (&hw->sw_head);
-        LIST_INIT (&cap->cb_head);
+        QLIST_INIT (&hw->sw_head);
+        QLIST_INIT (&cap->cb_head);
 
         /* XXX find a more elegant way */
         hw->samples = 4096 * 4;
         hw->mix_buf = audio_calloc (AUDIO_FUNC, hw->samples,
-                                    sizeof (st_sample_t));
+                                    sizeof (struct st_sample));
         if (!hw->mix_buf) {
             dolog ("Could not allocate capture mix buffer (%d samples)\n",
                    hw->samples);
@@ -1896,21 +2003,21 @@ CaptureVoiceOut *AUD_add_capture (
             [hw->info.swap_endianness]
             [audio_bits_to_index (hw->info.bits)];
 
-        LIST_INSERT_HEAD (&s->cap_head, cap, entries);
-        LIST_INSERT_HEAD (&cap->cb_head, cb, entries);
+        QLIST_INSERT_HEAD (&s->cap_head, cap, entries);
+        QLIST_INSERT_HEAD (&cap->cb_head, cb, entries);
 
         hw = NULL;
-        while ((hw = audio_pcm_hw_find_any_out (s, hw))) {
-            audio_attach_capture (s, hw);
+        while ((hw = audio_pcm_hw_find_any_out (hw))) {
+            audio_attach_capture (hw);
         }
         return cap;
 
     err3:
-        qemu_free (cap->hw.mix_buf);
+        g_free (cap->hw.mix_buf);
     err2:
-        qemu_free (cap);
+        g_free (cap);
     err1:
-        qemu_free (cb);
+        g_free (cb);
     err0:
         return NULL;
     }
@@ -1923,8 +2030,8 @@ void AUD_del_capture (CaptureVoiceOut *cap, void *cb_opaque)
     for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
         if (cb->opaque == cb_opaque) {
             cb->ops.destroy (cb_opaque);
-            LIST_REMOVE (cb, entries);
-            qemu_free (cb);
+            QLIST_REMOVE (cb, entries);
+            g_free (cb);
 
             if (!cap->cb_head.lh_first) {
                 SWVoiceOut *sw = cap->hw.sw_head.lh_first, *sw1;
@@ -1940,15 +2047,45 @@ void AUD_del_capture (CaptureVoiceOut *cap, void *cb_opaque)
                         st_rate_stop (sw->rate);
                         sw->rate = NULL;
                     }
-                    LIST_REMOVE (sw, entries);
-                    LIST_REMOVE (sc, entries);
-                    qemu_free (sc);
+                    QLIST_REMOVE (sw, entries);
+                    QLIST_REMOVE (sc, entries);
+                    g_free (sc);
                     sw = sw1;
                 }
-                LIST_REMOVE (cap, entries);
-                qemu_free (cap);
+                QLIST_REMOVE (cap, entries);
+                g_free (cap);
             }
             return;
         }
     }
 }
+
+void AUD_set_volume_out (SWVoiceOut *sw, int mute, uint8_t lvol, uint8_t rvol)
+{
+    if (sw) {
+        HWVoiceOut *hw = sw->hw;
+
+        sw->vol.mute = mute;
+        sw->vol.l = nominal_volume.l * lvol / 255;
+        sw->vol.r = nominal_volume.r * rvol / 255;
+
+        if (hw->pcm_ops->ctl_out) {
+            hw->pcm_ops->ctl_out (hw, VOICE_VOLUME, sw);
+        }
+    }
+}
+
+void AUD_set_volume_in (SWVoiceIn *sw, int mute, uint8_t lvol, uint8_t rvol)
+{
+    if (sw) {
+        HWVoiceIn *hw = sw->hw;
+
+        sw->vol.mute = mute;
+        sw->vol.l = nominal_volume.l * lvol / 255;
+        sw->vol.r = nominal_volume.r * rvol / 255;
+
+        if (hw->pcm_ops->ctl_in) {
+            hw->pcm_ops->ctl_in (hw, VOICE_VOLUME, sw);
+        }
+    }
+}