]> git.proxmox.com Git - qemu.git/blobdiff - audio/audio.c
slirp: Fix restricted mode
[qemu.git] / audio / audio.c
index 1a3925d4e957a951c3ed40d8accfcd2137c93074..50d2b6438ca9a8377641d0905a5e8f69baf9ec91 100644 (file)
  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  * THE SOFTWARE.
  */
-#include "vl.h"
+#include "hw/hw.h"
+#include "audio.h"
+#include "monitor.h"
+#include "qemu-timer.h"
+#include "sysemu.h"
 
 #define AUDIO_CAP "audio"
 #include "audio_int.h"
 
-static void audio_pcm_hw_fini_in (HWVoiceIn *hw);
-static void audio_pcm_hw_fini_out (HWVoiceOut *hw);
-
-static LIST_HEAD (hw_in_listhead, HWVoiceIn) hw_head_in;
-static LIST_HEAD (hw_out_listhead, HWVoiceOut) hw_head_out;
-
 /* #define DEBUG_PLIVE */
 /* #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
 };
 
-AudioState audio_state = {
-    /* Out */
-    1,                          /* use fixed settings */
-    44100,                      /* fixed frequency */
-    2,                          /* fixed channels */
-    AUD_FMT_S16,                /* fixed format */
-    1,                          /* number of hw voices */
-    1,                          /* greedy */
-
-    /* In */
-    1,                          /* use fixed settings */
-    44100,                      /* fixed frequency */
-    2,                          /* fixed channels */
-    AUD_FMT_S16,                /* fixed format */
-    1,                          /* number of hw voices */
-    1,                          /* greedy */
-
-    NULL,                       /* driver opaque */
-    NULL,                       /* driver */
-
-    NULL,                       /* timer handle */
-    { 0 },                      /* period */
-    0                           /* plive */
+struct fixed_settings {
+    int enabled;
+    int nb_voices;
+    int greedy;
+    struct audsettings settings;
+};
+
+static struct {
+    struct fixed_settings fixed_out;
+    struct fixed_settings fixed_in;
+    union {
+        int hertz;
+        int64_t ticks;
+    } period;
+    int plive;
+    int log_to_monitor;
+    int try_poll_in;
+    int try_poll_out;
+} conf = {
+    .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,
+        }
+    },
+
+    .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,
+        }
+    },
+
+    .period = { .hertz = 250 },
+    .plive = 0,
+    .log_to_monitor = 0,
+    .try_poll_in = 1,
+    .try_poll_out = 1,
 };
 
-volume_t nominal_volume = {
-    0,
+static AudioState glob_audio_state;
+
+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) {
         static int shown;
 
-        AUD_log (NULL, "Error a bug that was just triggered in %s\n", funcname);
+        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");
 
@@ -148,11 +160,50 @@ int audio_bug (const char *funcname, int cond)
 }
 #endif
 
+static inline int audio_bits_to_index (int bits)
+{
+    switch (bits) {
+    case 8:
+        return 0;
+
+    case 16:
+        return 1;
+
+    case 32:
+        return 2;
+
+    default:
+        audio_bug ("bits_to_index", 1);
+        AUD_log (NULL, "invalid bits %d\n", bits);
+        return 0;
+    }
+}
+
+void *audio_calloc (const char *funcname, int nmemb, size_t size)
+{
+    int cond;
+    size_t len;
+
+    len = nmemb * size;
+    cond = !nmemb || !size;
+    cond |= nmemb < 0;
+    cond |= len < size;
+
+    if (audio_bug ("audio_calloc", cond)) {
+        AUD_log (NULL, "%s passed invalid arguments to audio_calloc\n",
+                 funcname);
+        AUD_log (NULL, "nmemb=%d size=%zu (len=%zu)\n", nmemb, size, len);
+        return NULL;
+    }
+
+    return qemu_mallocz (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;
@@ -161,21 +212,19 @@ static char *audio_alloc_prefix (const char *s)
     len = strlen (s);
     r = qemu_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;
 }
 
-const char *audio_audfmt_to_string (audfmt_e fmt)
+static const char *audio_audfmt_to_string (audfmt_e fmt)
 {
     switch (fmt) {
     case AUD_FMT_U8:
@@ -189,13 +238,20 @@ const char *audio_audfmt_to_string (audfmt_e fmt)
 
     case AUD_FMT_S16:
         return "S16";
+
+    case AUD_FMT_U32:
+        return "U32";
+
+    case AUD_FMT_S32:
+        return "S32";
     }
 
     dolog ("Bogus audfmt %d returning S16\n", fmt);
     return "S16";
 }
 
-audfmt_e audio_string_to_audfmt (const char *s, audfmt_e defval, int *defaultp)
+static audfmt_e audio_string_to_audfmt (const char *s, audfmt_e defval,
+                                        int *defaultp)
 {
     if (!strcasecmp (s, "u8")) {
         *defaultp = 0;
@@ -205,6 +261,10 @@ audfmt_e audio_string_to_audfmt (const char *s, audfmt_e defval, int *defaultp)
         *defaultp = 0;
         return AUD_FMT_U16;
     }
+    else if (!strcasecmp (s, "u32")) {
+        *defaultp = 0;
+        return AUD_FMT_U32;
+    }
     else if (!strcasecmp (s, "s8")) {
         *defaultp = 0;
         return AUD_FMT_S8;
@@ -213,6 +273,10 @@ audfmt_e audio_string_to_audfmt (const char *s, audfmt_e defval, int *defaultp)
         *defaultp = 0;
         return AUD_FMT_S16;
     }
+    else if (!strcasecmp (s, "s32")) {
+        *defaultp = 0;
+        return AUD_FMT_S32;
+    }
     else {
         dolog ("Bogus audio format `%s' using %s\n",
                s, audio_audfmt_to_string (defval));
@@ -265,23 +329,31 @@ static const char *audio_get_conf_str (const char *key,
     }
 }
 
-void AUD_log (const char *cap, const char *fmt, ...)
+void AUD_vlog (const char *cap, const char *fmt, va_list ap)
 {
-    va_list ap;
-    if (cap) {
-        fprintf (stderr, "%s: ", cap);
+    if (conf.log_to_monitor) {
+        if (cap) {
+            monitor_printf(default_mon, "%s: ", cap);
+        }
+
+        monitor_vprintf(default_mon, fmt, ap);
+    }
+    else {
+        if (cap) {
+            fprintf (stderr, "%s: ", cap);
+        }
+
+        vfprintf (stderr, fmt, ap);
     }
-    va_start (ap, fmt);
-    vfprintf (stderr, fmt, ap);
-    va_end (ap);
 }
 
-void AUD_vlog (const char *cap, const char *fmt, va_list ap)
+void AUD_log (const char *cap, const char *fmt, ...)
 {
-    if (cap) {
-        fprintf (stderr, "%s: ", cap);
-    }
-    vfprintf (stderr, fmt, ap);
+    va_list ap;
+
+    va_start (ap, fmt);
+    AUD_vlog (cap, fmt, ap);
+    va_end (ap);
 }
 
 static void audio_print_options (const char *prefix,
@@ -305,7 +377,7 @@ static void audio_print_options (const char *prefix,
         const char *state = "default";
         printf ("  %s_%s: ", uprefix, opt->name);
 
-        if (opt->overridenp && *opt->overridenp) {
+        if (opt->overriddenp && *opt->overriddenp) {
             state = "current";
         }
 
@@ -328,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)
                     );
@@ -361,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");
@@ -386,19 +458,20 @@ static void audio_process_options (const char *prefix,
         }
 
         len = strlen (opt->name);
-        optname = qemu_malloc (len + preflen + sizeof (qemu_prefix) + 1);
-        if (!optname) {
-            dolog ("Can not allocate memory for option name `%s'\n",
-                   opt->name);
-            continue;
-        }
+        /* len of opt->name + len of prefix + size of qemu_prefix
+         * (includes trailing zero) + zero + underscore (on behalf of
+         * sizeof) */
+        optlen = len + preflen + sizeof (qemu_prefix) + 1;
+        optname = qemu_malloc (optlen);
+
+        pstrcpy (optname, optlen, qemu_prefix);
 
-        strcpy (optname, 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) {
@@ -430,20 +503,86 @@ static void audio_process_options (const char *prefix,
             break;
         }
 
-        if (!opt->overridenp) {
-            opt->overridenp = &opt->overriden;
+        if (!opt->overriddenp) {
+            opt->overriddenp = &opt->overridden;
         }
-        *opt->overridenp = !def;
+        *opt->overriddenp = !def;
         qemu_free (optname);
     }
 }
 
-static int audio_pcm_info_eq (struct audio_pcm_info *info, int freq,
-                              int nchannels, audfmt_e fmt)
+static void audio_print_settings (struct audsettings *as)
+{
+    dolog ("frequency=%d nchannels=%d fmt=", as->freq, as->nchannels);
+
+    switch (as->fmt) {
+    case AUD_FMT_S8:
+        AUD_log (NULL, "S8");
+        break;
+    case AUD_FMT_U8:
+        AUD_log (NULL, "U8");
+        break;
+    case AUD_FMT_S16:
+        AUD_log (NULL, "S16");
+        break;
+    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;
+    }
+
+    AUD_log (NULL, " endianness=");
+    switch (as->endianness) {
+    case 0:
+        AUD_log (NULL, "little");
+        break;
+    case 1:
+        AUD_log (NULL, "big");
+        break;
+    default:
+        AUD_log (NULL, "invalid");
+        break;
+    }
+    AUD_log (NULL, "\n");
+}
+
+static int audio_validate_settings (struct audsettings *as)
+{
+    int invalid;
+
+    invalid = as->nchannels != 1 && as->nchannels != 2;
+    invalid |= as->endianness != 0 && as->endianness != 1;
+
+    switch (as->fmt) {
+    case AUD_FMT_S8:
+    case AUD_FMT_U8:
+    case AUD_FMT_S16:
+    case AUD_FMT_U16:
+    case AUD_FMT_S32:
+    case AUD_FMT_U32:
+        break;
+    default:
+        invalid = 1;
+        break;
+    }
+
+    invalid |= as->freq <= 0;
+    return invalid ? -1 : 0;
+}
+
+static int audio_pcm_info_eq (struct audio_pcm_info *info, struct audsettings *as)
 {
     int bits = 8, sign = 0;
 
-    switch (fmt) {
+    switch (as->fmt) {
     case AUD_FMT_S8:
         sign = 1;
     case AUD_FMT_U8:
@@ -454,19 +593,25 @@ static int audio_pcm_info_eq (struct audio_pcm_info *info, int freq,
     case AUD_FMT_U16:
         bits = 16;
         break;
+
+    case AUD_FMT_S32:
+        sign = 1;
+    case AUD_FMT_U32:
+        bits = 32;
+        break;
     }
-    return info->freq == freq
-        && info->nchannels == nchannels
+    return info->freq == as->freq
+        && info->nchannels == as->nchannels
         && info->sign == sign
-        && info->bits == bits;
+        && info->bits == bits
+        && info->swap_endianness == (as->endianness != AUDIO_HOST_ENDIANNESS);
 }
 
-void audio_pcm_init_info (struct audio_pcm_info *info, int freq,
-                          int nchannels, audfmt_e fmt, int swap_endian)
+void audio_pcm_init_info (struct audio_pcm_info *info, struct audsettings *as)
 {
-    int bits = 8, sign = 0;
+    int bits = 8, sign = 0, shift = 0;
 
-    switch (fmt) {
+    switch (as->fmt) {
     case AUD_FMT_S8:
         sign = 1;
     case AUD_FMT_U8:
@@ -476,17 +621,25 @@ void audio_pcm_init_info (struct audio_pcm_info *info, int freq,
         sign = 1;
     case AUD_FMT_U16:
         bits = 16;
+        shift = 1;
+        break;
+
+    case AUD_FMT_S32:
+        sign = 1;
+    case AUD_FMT_U32:
+        bits = 32;
+        shift = 2;
         break;
     }
 
-    info->freq = freq;
+    info->freq = as->freq;
     info->bits = bits;
     info->sign = sign;
-    info->nchannels = nchannels;
-    info->shift = (nchannels == 2) + (bits == 16);
+    info->nchannels = as->nchannels;
+    info->shift = (as->nchannels == 2) + shift;
     info->align = (1 << info->shift) - 1;
     info->bytes_per_second = info->freq << info->shift;
-    info->swap_endian = swap_endian;
+    info->swap_endianness = (as->endianness != AUDIO_HOST_ENDIANNESS);
 }
 
 void audio_pcm_info_clear_buf (struct audio_pcm_info *info, void *buf, int len)
@@ -496,74 +649,196 @@ void audio_pcm_info_clear_buf (struct audio_pcm_info *info, void *buf, int len)
     }
 
     if (info->sign) {
-        memset (buf, len << info->shift, 0x00);
+        memset (buf, 0x00, len << info->shift);
     }
     else {
-        if (info->bits == 8) {
-            memset (buf, len << info->shift, 0x80);
-        }
-        else {
-            int i;
-            uint16_t *p = buf;
-            int shift = info->nchannels - 1;
-            short s = INT16_MAX;
+        switch (info->bits) {
+        case 8:
+            memset (buf, 0x80, len << info->shift);
+            break;
+
+        case 16:
+            {
+                int i;
+                uint16_t *p = buf;
+                int shift = info->nchannels - 1;
+                short s = INT16_MAX;
 
-            if (info->swap_endian) {
-                s = bswap16 (s);
+                if (info->swap_endianness) {
+                    s = bswap16 (s);
+                }
+
+                for (i = 0; i < len << shift; i++) {
+                    p[i] = s;
+                }
             }
+            break;
 
-            for (i = 0; i < len << shift; i++) {
-                p[i] = s;
+        case 32:
+            {
+                int i;
+                uint32_t *p = buf;
+                int shift = info->nchannels - 1;
+                int32_t s = INT32_MAX;
+
+                if (info->swap_endianness) {
+                    s = bswap32 (s);
+                }
+
+                for (i = 0; i < len << shift; i++) {
+                    p[i] = s;
+                }
             }
+            break;
+
+        default:
+            AUD_log (NULL, "audio_pcm_info_clear_buf: invalid bits %d\n",
+                     info->bits);
+            break;
         }
     }
 }
 
 /*
- * Hard voice (capture)
+ * Capture
  */
-static void audio_pcm_hw_free_resources_in (HWVoiceIn *hw)
+static void noop_conv (struct st_sample *dst, const void *src, int samples)
+{
+    (void) src;
+    (void) dst;
+    (void) samples;
+}
+
+static CaptureVoiceOut *audio_pcm_capture_find_specific (
+    struct audsettings *as
+    )
 {
-    if (hw->conv_buf) {
-        qemu_free (hw->conv_buf);
+    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)) {
+            return cap;
+        }
     }
-    hw->conv_buf = NULL;
+    return NULL;
 }
 
-static int audio_pcm_hw_alloc_resources_in (HWVoiceIn *hw)
+static void audio_notify_capture (CaptureVoiceOut *cap, audcnotification_e cmd)
 {
-    hw->conv_buf = qemu_mallocz (hw->samples * sizeof (st_sample_t));
-    if (!hw->conv_buf) {
-        return -1;
+    struct capture_callback *cb;
+
+#ifdef DEBUG_CAPTURE
+    dolog ("notification %d sent\n", cmd);
+#endif
+    for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
+        cb->ops.notify (cb->opaque, cmd);
     }
-    return 0;
 }
 
-static int audio_pcm_hw_init_in (HWVoiceIn *hw, int freq, int nchannels, audfmt_e fmt)
+static void audio_capture_maybe_changed (CaptureVoiceOut *cap, int enabled)
 {
-    audio_pcm_hw_fini_in (hw);
+    if (cap->hw.enabled != enabled) {
+        audcnotification_e cmd;
+        cap->hw.enabled = enabled;
+        cmd = enabled ? AUD_CNOTIFY_ENABLE : AUD_CNOTIFY_DISABLE;
+        audio_notify_capture (cap, cmd);
+    }
+}
 
-    if (hw->pcm_ops->init_in (hw, freq, nchannels, fmt)) {
-        memset (hw, 0, audio_state.drv->voice_size_in);
-        return -1;
+static void audio_recalc_and_notify_capture (CaptureVoiceOut *cap)
+{
+    HWVoiceOut *hw = &cap->hw;
+    SWVoiceOut *sw;
+    int enabled = 0;
+
+    for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
+        if (sw->active) {
+            enabled = 1;
+            break;
+        }
     }
-    LIST_INIT (&hw->sw_head);
-    hw->active = 1;
-    hw->samples = hw->bufsize >> hw->info.shift;
-    hw->conv =
-        mixeng_conv
-        [nchannels == 2]
-        [hw->info.sign]
-        [hw->info.swap_endian]
-        [hw->info.bits == 16];
-    if (audio_pcm_hw_alloc_resources_in (hw)) {
-        audio_pcm_hw_free_resources_in (hw);
-        return -1;
+    audio_capture_maybe_changed (cap, enabled);
+}
+
+static void audio_detach_capture (HWVoiceOut *hw)
+{
+    SWVoiceCap *sc = hw->cap_head.lh_first;
+
+    while (sc) {
+        SWVoiceCap *sc1 = sc->entries.le_next;
+        SWVoiceOut *sw = &sc->sw;
+        CaptureVoiceOut *cap = sc->cap;
+        int was_active = sw->active;
+
+        if (sw->rate) {
+            st_rate_stop (sw->rate);
+            sw->rate = NULL;
+        }
+
+        QLIST_REMOVE (sw, entries);
+        QLIST_REMOVE (sc, entries);
+        qemu_free (sc);
+        if (was_active) {
+            /* We have removed soft voice from the capture:
+               this might have changed the overall status of the capture
+               since this might have been the only active voice */
+            audio_recalc_and_notify_capture (cap);
+        }
+        sc = sc1;
+    }
+}
+
+static int audio_attach_capture (HWVoiceOut *hw)
+{
+    AudioState *s = &glob_audio_state;
+    CaptureVoiceOut *cap;
+
+    audio_detach_capture (hw);
+    for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
+        SWVoiceCap *sc;
+        SWVoiceOut *sw;
+        HWVoiceOut *hw_cap = &cap->hw;
+
+        sc = audio_calloc (AUDIO_FUNC, 1, sizeof (*sc));
+        if (!sc) {
+            dolog ("Could not allocate soft capture voice (%zu bytes)\n",
+                   sizeof (*sc));
+            return -1;
+        }
+
+        sc->cap = cap;
+        sw = &sc->sw;
+        sw->hw = hw_cap;
+        sw->info = hw->info;
+        sw->empty = 1;
+        sw->active = hw->enabled;
+        sw->conv = noop_conv;
+        sw->ratio = ((int64_t) hw_cap->info.freq << 32) / sw->info.freq;
+        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);
+            return -1;
+        }
+        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);
+        dolog ("Added %s active = %d\n", sw->name, sw->active);
+#endif
+        if (sw->active) {
+            audio_capture_maybe_changed (cap, 1);
+        }
     }
     return 0;
 }
 
-static uint64_t audio_pcm_hw_find_min_in (HWVoiceIn *hw)
+/*
+ * Hard voice (capture)
+ */
+static int audio_pcm_hw_find_min_in (HWVoiceIn *hw)
 {
     SWVoiceIn *sw;
     int m = hw->total_samples_captured;
@@ -586,62 +861,31 @@ int audio_pcm_hw_get_live_in (HWVoiceIn *hw)
     return live;
 }
 
-/*
- * Soft voice (capture)
- */
-static void audio_pcm_sw_free_resources_in (SWVoiceIn *sw)
+int audio_pcm_hw_clip_out (HWVoiceOut *hw, void *pcm_buf,
+                           int live, int pending)
 {
-    if (sw->conv_buf) {
-        qemu_free (sw->conv_buf);
-    }
-
-    if (sw->rate) {
-        st_rate_stop (sw->rate);
-    }
+    int left = hw->samples - pending;
+    int len = audio_MIN (left, live);
+    int clipped = 0;
 
-    sw->conv_buf = NULL;
-    sw->rate = NULL;
-}
+    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);
 
-static int audio_pcm_sw_alloc_resources_in (SWVoiceIn *sw)
-{
-    int samples = ((int64_t) sw->hw->samples << 32) / sw->ratio;
-    sw->conv_buf = qemu_mallocz (samples * sizeof (st_sample_t));
-    if (!sw->conv_buf) {
-        return -1;
-    }
+        hw->clip (dst, src, samples_to_clip);
 
-    sw->rate = st_rate_start (sw->hw->info.freq, sw->info.freq);
-    if (!sw->rate) {
-        qemu_free (sw->conv_buf);
-        sw->conv_buf = NULL;
-        return -1;
+        hw->rpos = (hw->rpos + samples_to_clip) % hw->samples;
+        len -= samples_to_clip;
+        clipped += samples_to_clip;
     }
-    return 0;
-}
-
-static int audio_pcm_sw_init_in (SWVoiceIn *sw, HWVoiceIn *hw, const char *name,
-                           int freq, int nchannels, audfmt_e fmt)
-{
-    audio_pcm_init_info (&sw->info, freq, nchannels, fmt,
-                         /* None of the cards emulated by QEMU are big-endian
-                            hence following shortcut */
-                         audio_need_to_swap_endian (0));
-    sw->hw = hw;
-    sw->ratio = ((int64_t) sw->info.freq << 32) / sw->hw->info.freq;
-
-    sw->clip =
-        mixeng_clip
-        [nchannels == 2]
-        [sw->info.sign]
-        [sw->info.swap_endian]
-        [sw->info.bits == 16];
-
-    sw->name = qemu_strdup (name);
-    audio_pcm_sw_free_resources_in (sw);
-    return audio_pcm_sw_alloc_resources_in (sw);
+    return clipped;
 }
 
+/*
+ * Soft voice (capture)
+ */
 static int audio_pcm_sw_get_rpos_in (SWVoiceIn *sw)
 {
     HWVoiceIn *hw = sw->hw;
@@ -666,7 +910,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->conv_buf;
+    struct st_sample *src, *dst = sw->buf;
 
     rpos = audio_pcm_sw_get_rpos_in (sw) % hw->samples;
 
@@ -699,6 +943,7 @@ int audio_pcm_sw_read (SWVoiceIn *sw, void *buf, int size)
 
         if (audio_bug (AUDIO_FUNC, osamp < 0)) {
             dolog ("osamp=%d\n", osamp);
+            return 0;
         }
 
         st_rate_flow (sw->rate, src, dst, &isamp, &osamp);
@@ -709,7 +954,9 @@ int audio_pcm_sw_read (SWVoiceIn *sw, void *buf, int size)
         total += isamp;
     }
 
-    sw->clip (buf, sw->conv_buf, ret);
+    mixeng_volume (sw->buf, ret, &sw->vol);
+
+    sw->clip (buf, sw->buf, ret);
     sw->total_hw_samples_acquired += total;
     return ret << sw->info.shift;
 }
@@ -734,60 +981,17 @@ static int audio_pcm_hw_find_min_out (HWVoiceOut *hw, int *nb_livep)
     return m;
 }
 
-static void audio_pcm_hw_free_resources_out (HWVoiceOut *hw)
-{
-    if (hw->mix_buf) {
-        qemu_free (hw->mix_buf);
-    }
-
-    hw->mix_buf = NULL;
-}
-
-static int audio_pcm_hw_alloc_resources_out (HWVoiceOut *hw)
-{
-    hw->mix_buf = qemu_mallocz (hw->samples * sizeof (st_sample_t));
-    if (!hw->mix_buf) {
-        return -1;
-    }
-
-    return 0;
-}
-
-static int audio_pcm_hw_init_out (HWVoiceOut *hw, int freq,
-                            int nchannels, audfmt_e fmt)
-{
-    audio_pcm_hw_fini_out (hw);
-    if (hw->pcm_ops->init_out (hw, freq, nchannels, fmt)) {
-        memset (hw, 0, audio_state.drv->voice_size_out);
-        return -1;
-    }
-
-    LIST_INIT (&hw->sw_head);
-    hw->active = 1;
-    hw->samples = hw->bufsize >> hw->info.shift;
-    hw->clip =
-        mixeng_clip
-        [nchannels == 2]
-        [hw->info.sign]
-        [hw->info.swap_endian]
-        [hw->info.bits == 16];
-    if (audio_pcm_hw_alloc_resources_out (hw)) {
-        audio_pcm_hw_fini_out (hw);
-        return -1;
-    }
-    return 0;
-}
-
-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)) {
@@ -796,80 +1000,12 @@ 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;
 }
 
 /*
  * Soft voice (playback)
  */
-static void audio_pcm_sw_free_resources_out (SWVoiceOut *sw)
-{
-    if (sw->buf) {
-        qemu_free (sw->buf);
-    }
-
-    if (sw->rate) {
-        st_rate_stop (sw->rate);
-    }
-
-    sw->buf = NULL;
-    sw->rate = NULL;
-}
-
-static int audio_pcm_sw_alloc_resources_out (SWVoiceOut *sw)
-{
-    sw->buf = qemu_mallocz (sw->hw->samples * sizeof (st_sample_t));
-    if (!sw->buf) {
-        return -1;
-    }
-
-    sw->rate = st_rate_start (sw->info.freq, sw->hw->info.freq);
-    if (!sw->rate) {
-        qemu_free (sw->buf);
-        sw->buf = NULL;
-        return -1;
-    }
-    return 0;
-}
-
-static int audio_pcm_sw_init_out (SWVoiceOut *sw, HWVoiceOut *hw,
-                            const char *name, int freq,
-                            int nchannels, audfmt_e fmt)
-{
-    audio_pcm_init_info (&sw->info, freq, nchannels, fmt,
-                         /* None of the cards emulated by QEMU are big-endian
-                            hence following shortcut */
-                         audio_need_to_swap_endian (0));
-    sw->hw = hw;
-    sw->empty = 1;
-    sw->active = 0;
-    sw->ratio = ((int64_t) sw->hw->info.freq << 32) / sw->info.freq;
-    sw->total_hw_samples_mixed = 0;
-
-    sw->conv =
-        mixeng_conv
-        [nchannels == 2]
-        [sw->info.sign]
-        [sw->info.swap_endian]
-        [sw->info.bits == 16];
-    sw->name = qemu_strdup (name);
-
-    audio_pcm_sw_free_resources_out (sw);
-    return audio_pcm_sw_alloc_resources_out (sw);
-}
-
 int audio_pcm_sw_write (SWVoiceOut *sw, void *buf, int size)
 {
     int hwsamples, samples, isamp, osamp, wpos, live, dead, left, swlim, blck;
@@ -888,6 +1024,9 @@ int audio_pcm_sw_write (SWVoiceOut *sw, void *buf, int size)
     }
 
     if (live == hwsamples) {
+#ifdef DEBUG_OUT
+        dolog ("%s is full %d\n", sw->name, live);
+#endif
         return 0;
     }
 
@@ -898,7 +1037,8 @@ 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);
+        mixeng_volume (sw->buf, swlim, &sw->vol);
     }
 
     while (swlim) {
@@ -930,12 +1070,11 @@ int audio_pcm_sw_write (SWVoiceOut *sw, void *buf, int size)
 
 #ifdef DEBUG_OUT
     dolog (
-        "%s: write size %d ret %d total sw %d, hw %d\n",
-        sw->name,
+        "%s: write size %d ret %d total sw %d\n",
+        SW_NAME (sw),
         size >> sw->info.shift,
         ret,
-        sw->total_hw_samples_mixed,
-        sw->hw->total_samples_played
+        sw->total_hw_samples_mixed
         );
 #endif
 
@@ -955,6 +1094,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;
@@ -965,7 +1140,7 @@ int AUD_write (SWVoiceOut *sw, void *buf, int size)
     }
 
     if (!sw->hw->enabled) {
-        dolog ("Writing to disabled voice %s\n", sw->name);
+        dolog ("Writing to disabled voice %s\n", SW_NAME (sw));
         return 0;
     }
 
@@ -983,7 +1158,7 @@ int AUD_read (SWVoiceIn *sw, void *buf, int size)
     }
 
     if (!sw->hw->enabled) {
-        dolog ("Reading from disabled voice %s\n", sw->name);
+        dolog ("Reading from disabled voice %s\n", SW_NAME (sw));
         return 0;
     }
 
@@ -993,7 +1168,7 @@ int AUD_read (SWVoiceIn *sw, void *buf, int size)
 
 int AUD_get_buffer_size_out (SWVoiceOut *sw)
 {
-    return sw->hw->bufsize;
+    return sw->hw->samples << sw->hw->info.shift;
 }
 
 void AUD_set_active_out (SWVoiceOut *sw, int on)
@@ -1006,19 +1181,18 @@ 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;
 
         if (on) {
-            int total;
-
             hw->pending_disable = 0;
             if (!hw->enabled) {
                 hw->enabled = 1;
-                hw->pcm_ops->ctl_out (hw, VOICE_ENABLE);
-            }
-
-            if (sw->empty) {
-                total = 0;
+                if (s->vm_running) {
+                    hw->pcm_ops->ctl_out (hw, VOICE_ENABLE, conf.try_poll_out);
+                    audio_reset_timer (s);
+                }
             }
         }
         else {
@@ -1033,6 +1207,13 @@ void AUD_set_active_out (SWVoiceOut *sw, int on)
                 hw->pending_disable = nb_active == 1;
             }
         }
+
+        for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
+            sc->sw.active = hw->enabled;
+            if (hw->enabled) {
+                audio_capture_maybe_changed (sc->cap, 1);
+            }
+        }
         sw->active = on;
     }
 }
@@ -1047,12 +1228,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;
         }
@@ -1090,8 +1275,8 @@ static int audio_get_avail (SWVoiceIn *sw)
     }
 
     ldebug (
-        "%s: get_avail live %d ret %lld\n",
-        sw->name,
+        "%s: get_avail live %d ret %" PRId64 "\n",
+        SW_NAME (sw),
         live, (((int64_t) live << 32) / sw->ratio) << sw->info.shift
         );
 
@@ -1110,43 +1295,88 @@ static int audio_get_free (SWVoiceOut *sw)
 
     if (audio_bug (AUDIO_FUNC, live < 0 || live > sw->hw->samples)) {
         dolog ("live=%d sw->hw->samples=%d\n", live, sw->hw->samples);
+        return 0;
     }
 
     dead = sw->hw->samples - live;
 
 #ifdef DEBUG_OUT
-    dolog ("%s: get_free live %d dead %d ret %lld\n",
-           sw->name,
+    dolog ("%s: get_free live %d dead %d ret %" PRId64 "\n",
+           SW_NAME (sw),
            live, dead, (((int64_t) dead << 32) / sw->ratio) << sw->info.shift);
 #endif
 
     return (((int64_t) dead << 32) / sw->ratio) << sw->info.shift;
 }
 
-static void audio_run_out (void)
+static void audio_capture_mix_and_clear (HWVoiceOut *hw, int rpos, int samples)
+{
+    int n;
+
+    if (hw->enabled) {
+        SWVoiceCap *sc;
+
+        for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
+            SWVoiceOut *sw = &sc->sw;
+            int rpos2 = rpos;
+
+            n = samples;
+            while (n) {
+                int till_end_of_hw = hw->samples - rpos2;
+                int to_write = audio_MIN (till_end_of_hw, n);
+                int bytes = to_write << hw->info.shift;
+                int written;
+
+                sw->buf = hw->mix_buf + rpos2;
+                written = audio_pcm_sw_write (sw, NULL, bytes);
+                if (written - bytes) {
+                    dolog ("Could not mix %d bytes into a capture "
+                           "buffer, mixed %d\n",
+                           bytes, written);
+                    break;
+                }
+                n -= to_write;
+                rpos2 = (rpos2 + to_write) % hw->samples;
+            }
+        }
+    }
+
+    n = audio_MIN (samples, hw->samples - rpos);
+    mixeng_clear (hw->mix_buf + rpos, n);
+    mixeng_clear (hw->mix_buf, samples - n);
+}
+
+static void audio_run_out (AudioState *s)
 {
     HWVoiceOut *hw = NULL;
     SWVoiceOut *sw;
 
-    while ((hw = audio_pcm_hw_find_any_active_enabled_out (hw))) {
+    while ((hw = audio_pcm_hw_find_any_enabled_out (hw))) {
         int played;
-        int live, free, nb_live;
+        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;
         }
+
         if (audio_bug (AUDIO_FUNC, live < 0 || live > hw->samples)) {
             dolog ("live=%d hw->samples=%d\n", live, hw->samples);
+            continue;
         }
 
         if (hw->pending_disable && !nb_live) {
+            SWVoiceCap *sc;
 #ifdef DEBUG_OUT
             dolog ("Disabling voice\n");
 #endif
             hw->enabled = 0;
             hw->pending_disable = 0;
             hw->pcm_ops->ctl_out (hw, VOICE_DISABLE);
+            for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
+                sc->sw.active = 0;
+                audio_recalc_and_notify_capture (sc->cap);
+            }
             continue;
         }
 
@@ -1162,7 +1392,8 @@ static void audio_run_out (void)
             continue;
         }
 
-        played = hw->pcm_ops->run_out (hw);
+        prev_rpos = hw->rpos;
+        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);
@@ -1170,15 +1401,16 @@ static void audio_run_out (void)
         }
 
 #ifdef DEBUG_OUT
-        dolog ("played = %d total %d\n", played, hw->total_samples_played);
+        dolog ("played=%d\n", played);
 #endif
 
         if (played) {
             hw->ts_helper += played;
+            audio_capture_mix_and_clear (hw, prev_rpos, played);
         }
 
+        cleanup_required = 0;
         for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
-        again:
             if (!sw->active && sw->empty) {
                 continue;
             }
@@ -1193,22 +1425,7 @@ static void audio_run_out (void)
 
             if (!sw->total_hw_samples_mixed) {
                 sw->empty = 1;
-
-                if (!sw->active && !sw->callback.fn) {
-                    SWVoiceOut *temp = sw->entries.le_next;
-
-#ifdef DEBUG_PLIVE
-                    dolog ("Finishing with old voice\n");
-#endif
-                    AUD_close_out (sw);
-                    sw = temp;
-                    if (sw) {
-                        goto again;
-                    }
-                    else {
-                        break;
-                    }
-                }
+                cleanup_required |= !sw->active && !sw->callback.fn;
             }
 
             if (sw->active) {
@@ -1218,14 +1435,30 @@ static void audio_run_out (void)
                 }
             }
         }
+
+        if (cleanup_required) {
+            SWVoiceOut *sw1;
+
+            sw = hw->sw_head.lh_first;
+            while (sw) {
+                sw1 = sw->entries.le_next;
+                if (!sw->active && !sw->callback.fn) {
+#ifdef DEBUG_PLIVE
+                    dolog ("Finishing with old voice\n");
+#endif
+                    audio_close_out (sw);
+                }
+                sw = sw1;
+            }
+        }
     }
 }
 
-static void audio_run_in (void)
+static void audio_run_in (AudioState *s)
 {
     HWVoiceIn *hw = NULL;
 
-    while ((hw = audio_pcm_hw_find_any_active_enabled_in (hw))) {
+    while ((hw = audio_pcm_hw_find_any_enabled_in (hw))) {
         SWVoiceIn *sw;
         int captured, min;
 
@@ -1250,55 +1483,200 @@ static void audio_run_in (void)
     }
 }
 
-static struct audio_option audio_options[] = {
-    /* DAC */
-    {"DAC_FIXED_SETTINGS", AUD_OPT_BOOL, &audio_state.fixed_settings_out,
-     "Use fixed settings for host DAC", NULL, 0},
-
-    {"DAC_FIXED_FREQ", AUD_OPT_INT, &audio_state.fixed_freq_out,
-     "Frequency for fixed host DAC", NULL, 0},
-
-    {"DAC_FIXED_FMT", AUD_OPT_FMT, &audio_state.fixed_fmt_out,
-     "Format for fixed host DAC", NULL, 0},
+static void audio_run_capture (AudioState *s)
+{
+    CaptureVoiceOut *cap;
+
+    for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
+        int live, rpos, captured;
+        HWVoiceOut *hw = &cap->hw;
+        SWVoiceOut *sw;
+
+        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);
+            struct st_sample *src;
+            struct capture_callback *cb;
+
+            src = hw->mix_buf + rpos;
+            hw->clip (cap->buf, src, to_capture);
+            mixeng_clear (src, to_capture);
+
+            for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
+                cb->ops.capture (cb->opaque, cap->buf,
+                                 to_capture << hw->info.shift);
+            }
+            rpos = (rpos + to_capture) % hw->samples;
+            live -= to_capture;
+        }
+        hw->rpos = rpos;
 
-    {"DAC_FIXED_CHANNELS", AUD_OPT_INT, &audio_state.fixed_channels_out,
-     "Number of channels for fixed DAC (1 - mono, 2 - stereo)", NULL, 0},
+        for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
+            if (!sw->active && sw->empty) {
+                continue;
+            }
 
-    {"DAC_VOICES", AUD_OPT_INT, &audio_state.nb_hw_voices_out,
-     "Number of voices for DAC", NULL, 0},
+            if (audio_bug (AUDIO_FUNC, captured > sw->total_hw_samples_mixed)) {
+                dolog ("captured=%d sw->total_hw_samples_mixed=%d\n",
+                       captured, sw->total_hw_samples_mixed);
+                captured = sw->total_hw_samples_mixed;
+            }
 
-    /* ADC */
-    {"ADC_FIXED_SETTINGS", AUD_OPT_BOOL, &audio_state.fixed_settings_out,
-     "Use fixed settings for host ADC", NULL, 0},
+            sw->total_hw_samples_mixed -= captured;
+            sw->empty = sw->total_hw_samples_mixed == 0;
+        }
+    }
+}
 
-    {"ADC_FIXED_FREQ", AUD_OPT_INT, &audio_state.fixed_freq_out,
-     "Frequency for fixed ADC", NULL, 0},
+void audio_run (const char *msg)
+{
+    AudioState *s = &glob_audio_state;
 
-    {"ADC_FIXED_FMT", AUD_OPT_FMT, &audio_state.fixed_fmt_out,
-     "Format for fixed ADC", NULL, 0},
+    audio_run_out (s);
+    audio_run_in (s);
+    audio_run_capture (s);
+#ifdef DEBUG_POLL
+    {
+        static double prevtime;
+        double currtime;
+        struct timeval tv;
 
-    {"ADC_FIXED_CHANNELS", AUD_OPT_INT, &audio_state.fixed_channels_in,
-     "Number of channels for fixed ADC (1 - mono, 2 - stereo)", NULL, 0},
+        if (gettimeofday (&tv, NULL)) {
+            perror ("audio_run: gettimeofday");
+            return;
+        }
 
-    {"ADC_VOICES", AUD_OPT_INT, &audio_state.nb_hw_voices_out,
-     "Number of voices for ADC", NULL, 0},
+        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 */
+    {
+        .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 */
+    {
+        .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, &audio_state.period.usec,
-     "Timer period in microseconds (0 - try lowest possible)", 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 */ }
+};
 
-    {"PLIVE", AUD_OPT_BOOL, &audio_state.plive,
-     "(undocumented)", NULL, 0},
+static void audio_pp_nb_voices (const char *typ, int nb)
+{
+    switch (nb) {
+    case 0:
+        printf ("Does not support %s\n", typ);
+        break;
+    case 1:
+        printf ("One %s voice\n", typ);
+        break;
+    case INT_MAX:
+        printf ("Theoretically supports many %s voices\n", typ);
+        break;
+    default:
+        printf ("Theoretically supports upto %d %s voices\n", nb, typ);
+        break;
+    }
 
-    {NULL, 0, NULL, NULL, NULL, 0}
-};
+}
 
 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);
@@ -1311,43 +1689,14 @@ 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);
         printf ("Description: %s\n", d->descr);
 
-        switch (d->max_voices_out) {
-        case 0:
-            printf ("Does not support DAC\n");
-            break;
-        case 1:
-            printf ("One DAC voice\n");
-            break;
-        case INT_MAX:
-            printf ("Theoretically supports many DAC voices\n");
-            break;
-        default:
-            printf ("Theoretically supports upto %d DAC voices\n",
-                     d->max_voices_out);
-            break;
-        }
-
-        switch (d->max_voices_in) {
-        case 0:
-            printf ("Does not support ADC\n");
-            break;
-        case 1:
-            printf ("One ADC voice\n");
-            break;
-        case INT_MAX:
-            printf ("Theoretically supports many ADC voices\n");
-            break;
-        default:
-            printf ("Theoretically supports upto %d ADC voices\n",
-                     d->max_voices_in);
-            break;
-        }
+        audio_pp_nb_voices ("playback", d->max_voices_out);
+        audio_pp_nb_voices ("capture", d->max_voices_in);
 
         if (d->options) {
             printf ("Options:\n");
@@ -1364,7 +1713,7 @@ void AUD_help (void)
         "Example:\n"
 #ifdef _WIN32
         "  set QEMU_AUDIO_DRV=wav\n"
-        "  set QEMU_WAV_PATH=c:/tune.wav\n"
+        "  set QEMU_WAV_PATH=c:\\tune.wav\n"
 #else
         "  export QEMU_AUDIO_DRV=wav\n"
         "  export QEMU_WAV_PATH=$HOME/tune.wav\n"
@@ -1374,119 +1723,17 @@ void AUD_help (void)
         );
 }
 
-void audio_timer (void *opaque)
-{
-    AudioState *s = opaque;
-
-    audio_run_out ();
-    audio_run_in ();
-
-    qemu_mod_timer (s->ts, qemu_get_clock (vm_clock) + s->period.ticks);
-}
-
-static int audio_driver_init (struct audio_driver *drv)
+static int audio_driver_init (AudioState *s, struct audio_driver *drv)
 {
     if (drv->options) {
         audio_process_options (drv->name, drv->options);
     }
-    audio_state.opaque = drv->init ();
-
-    if (audio_state.opaque) {
-        int i;
-        HWVoiceOut *hwo;
-        HWVoiceIn *hwi;
-
-        if (audio_state.nb_hw_voices_out > drv->max_voices_out) {
-            if (!drv->max_voices_out) {
-                dolog ("`%s' does not support DAC\n", drv->name);
-            }
-            else {
-                dolog (
-                    "`%s' does not support %d multiple DAC voicess\n"
-                    "Resetting to %d\n",
-                    drv->name,
-                    audio_state.nb_hw_voices_out,
-                    drv->max_voices_out
-                    );
-            }
-            audio_state.nb_hw_voices_out = drv->max_voices_out;
-        }
-
-        LIST_INIT (&hw_head_out);
-        hwo = qemu_mallocz (audio_state.nb_hw_voices_out * drv->voice_size_out);
-        if (!hwo) {
-            dolog (
-                "Not enough memory for %d `%s' DAC voices (each %d bytes)\n",
-                audio_state.nb_hw_voices_out,
-                drv->name,
-                drv->voice_size_out
-                );
-            drv->fini (audio_state.opaque);
-            return -1;
-        }
-
-        for (i = 0; i < audio_state.nb_hw_voices_out; ++i) {
-            LIST_INSERT_HEAD (&hw_head_out, hwo, entries);
-            hwo = advance (hwo, drv->voice_size_out);
-        }
-
-        if (!drv->voice_size_in && drv->max_voices_in) {
-            ldebug ("warning: No ADC voice size defined for `%s'\n",
-                    drv->name);
-            drv->max_voices_in = 0;
-        }
-
-        if (!drv->voice_size_out && drv->max_voices_out) {
-            ldebug ("warning: No DAC voice size defined for `%s'\n",
-                    drv->name);
-        }
-
-        if (drv->voice_size_in && !drv->max_voices_in) {
-            ldebug ("warning: ADC voice size is %d for ADC less driver `%s'\n",
-                    drv->voice_size_out, drv->name);
-        }
-
-        if (drv->voice_size_out && !drv->max_voices_out) {
-            ldebug ("warning: DAC voice size is %d for DAC less driver `%s'\n",
-                    drv->voice_size_in, drv->name);
-        }
-
-        if (audio_state.nb_hw_voices_in > drv->max_voices_in) {
-            if (!drv->max_voices_in) {
-                ldebug ("`%s' does not support ADC\n", drv->name);
-            }
-            else {
-                dolog (
-                    "`%s' does not support %d multiple ADC voices\n"
-                    "Resetting to %d\n",
-                    drv->name,
-                    audio_state.nb_hw_voices_in,
-                    drv->max_voices_in
-                    );
-            }
-            audio_state.nb_hw_voices_in = drv->max_voices_in;
-        }
-
-        LIST_INIT (&hw_head_in);
-        hwi = qemu_mallocz (audio_state.nb_hw_voices_in * drv->voice_size_in);
-        if (!hwi) {
-            dolog (
-                "Not enough memory for %d `%s' ADC voices (each %d bytes)\n",
-                audio_state.nb_hw_voices_in,
-                drv->name,
-                drv->voice_size_in
-                );
-            qemu_free (hwo);
-            drv->fini (audio_state.opaque);
-            return -1;
-        }
+    s->drv_opaque = drv->init ();
 
-        for (i = 0; i < audio_state.nb_hw_voices_in; ++i) {
-            LIST_INSERT_HEAD (&hw_head_in, hwi, entries);
-            hwi = advance (hwi, drv->voice_size_in);
-        }
-
-        audio_state.drv = drv;
+    if (s->drv_opaque) {
+        audio_init_nb_voices_out (drv);
+        audio_init_nb_voices_in (drv);
+        s->drv = drv;
         return 0;
     }
     else {
@@ -1495,100 +1742,104 @@ static int audio_driver_init (struct audio_driver *drv)
     }
 }
 
-static void audio_vm_stop_handler (void *opaque, int reason)
+static void audio_vm_change_state_handler (void *opaque, int running,
+                                           int reason)
 {
+    AudioState *s = opaque;
     HWVoiceOut *hwo = NULL;
     HWVoiceIn *hwi = NULL;
-    int op = reason ? VOICE_ENABLE : VOICE_DISABLE;
-
-    (void) opaque;
-    while ((hwo = audio_pcm_hw_find_any_out (hwo))) {
-        if (!hwo->pcm_ops) {
-            continue;
-        }
+    int op = running ? VOICE_ENABLE : VOICE_DISABLE;
 
-        if (hwo->enabled != reason) {
-            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_in (hwi))) {
-        if (!hwi->pcm_ops) {
-            continue;
-        }
-
-        if (hwi->enabled != reason) {
-            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)
 {
+    AudioState *s = &glob_audio_state;
     HWVoiceOut *hwo = NULL;
     HWVoiceIn *hwi = NULL;
 
-    while ((hwo = audio_pcm_hw_find_any_out (hwo))) {
-        if (!hwo->pcm_ops) {
-            continue;
-        }
+    while ((hwo = audio_pcm_hw_find_any_enabled_out (hwo))) {
+        SWVoiceCap *sc;
 
-        if (hwo->enabled) {
-            hwo->pcm_ops->ctl_out (hwo, VOICE_DISABLE);
-        }
+        hwo->pcm_ops->ctl_out (hwo, VOICE_DISABLE);
         hwo->pcm_ops->fini_out (hwo);
-    }
 
-    while ((hwi = audio_pcm_hw_find_any_in (hwi))) {
-        if (!hwi->pcm_ops) {
-            continue;
-        }
+        for (sc = hwo->cap_head.lh_first; sc; sc = sc->entries.le_next) {
+            CaptureVoiceOut *cap = sc->cap;
+            struct capture_callback *cb;
 
-        if (hwi->enabled) {
-            hwi->pcm_ops->ctl_in (hwi, VOICE_DISABLE);
+            for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
+                cb->ops.destroy (cb->opaque);
+            }
         }
+    }
+
+    while ((hwi = audio_pcm_hw_find_any_enabled_in (hwi))) {
+        hwi->pcm_ops->ctl_in (hwi, VOICE_DISABLE);
         hwi->pcm_ops->fini_in (hwi);
     }
-    audio_state.drv->fini (audio_state.opaque);
-}
 
-static void audio_save (QEMUFile *f, void *opaque)
-{
-    (void) f;
-    (void) opaque;
+    if (s->drv) {
+        s->drv->fini (s->drv_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_init (void)
+static void audio_init (void)
 {
     size_t i;
     int done = 0;
     const char *drvname;
-    AudioState *s = &audio_state;
+    VMChangeStateEntry *e;
+    AudioState *s = &glob_audio_state;
+
+    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_ns (vm_clock, audio_timer, s);
+    if (!s->ts) {
+        hw_error("Could not create audio timer\n");
+    }
 
     audio_process_options ("AUDIO", audio_options);
 
+    s->nb_hw_voices_out = conf.fixed_out.nb_voices;
+    s->nb_hw_voices_in = conf.fixed_in.nb_voices;
+
     if (s->nb_hw_voices_out <= 0) {
-        dolog ("Bogus number of DAC voices %d\n",
+        dolog ("Bogus number of playback voices %d, setting to 1\n",
                s->nb_hw_voices_out);
         s->nb_hw_voices_out = 1;
     }
 
     if (s->nb_hw_voices_in <= 0) {
-        dolog ("Bogus number of ADC voices %d\n",
+        dolog ("Bogus number of capture voices %d, setting to 0\n",
                s->nb_hw_voices_in);
-        s->nb_hw_voices_in = 1;
+        s->nb_hw_voices_in = 0;
     }
 
     {
@@ -1596,18 +1847,12 @@ void AUD_init (void)
         drvname = audio_get_conf_str ("QEMU_AUDIO_DRV", NULL, &def);
     }
 
-    s->ts = qemu_new_timer (vm_clock, audio_timer, s);
-    if (!s->ts) {
-        dolog ("Can not create audio timer\n");
-        return;
-    }
-
     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 (drvtab[i]);
+                done = !audio_driver_init (s, drvtab[i]);
                 found = 1;
                 break;
             }
@@ -1619,37 +1864,203 @@ void AUD_init (void)
         }
     }
 
-    qemu_add_vm_stop_handler (audio_vm_stop_handler, NULL);
-    atexit (audio_atexit);
-
     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 (drvtab[i]);
+                done = !audio_driver_init (s, drvtab[i]);
             }
         }
     }
 
-    register_savevm ("audio", 0, 1, audio_save, audio_load, NULL);
     if (!done) {
-        if (audio_driver_init (&no_audio_driver)) {
-            dolog ("Can not initialize audio subsystem\n");
+        done = !audio_driver_init (s, &no_audio_driver);
+        if (!done) {
+            hw_error("Could not initialize audio subsystem\n");
         }
         else {
-            dolog ("warning: using timer based audio emulation\n");
+            dolog ("warning: Using timer based audio emulation\n");
         }
     }
 
-    if (s->period.usec <= 0) {
-        if (s->period.usec < 0) {
-            dolog ("warning: timer period is negative - %d treating as zero\n",
-                   s->period.usec);
+    if (conf.period.hertz <= 0) {
+        if (conf.period.hertz < 0) {
+            dolog ("warning: Timer period is negative - %d "
+                   "treating as zero\n",
+                   conf.period.hertz);
         }
-        s->period.ticks = 1;
+        conf.period.ticks = 1;
+    } else {
+        conf.period.ticks =
+            muldiv64 (1, get_ticks_per_sec (), conf.period.hertz);
+    }
+
+    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");
+    }
+
+    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 = qemu_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);
+    qemu_free (card->name);
+}
+
+
+CaptureVoiceOut *AUD_add_capture (
+    struct audsettings *as,
+    struct audio_capture_ops *ops,
+    void *cb_opaque
+    )
+{
+    AudioState *s = &glob_audio_state;
+    CaptureVoiceOut *cap;
+    struct capture_callback *cb;
+
+    if (audio_validate_settings (as)) {
+        dolog ("Invalid settings were passed when trying to add capture\n");
+        audio_print_settings (as);
+        goto err0;
+    }
+
+    cb = audio_calloc (AUDIO_FUNC, 1, sizeof (*cb));
+    if (!cb) {
+        dolog ("Could not allocate capture callback information, size %zu\n",
+               sizeof (*cb));
+        goto err0;
+    }
+    cb->ops = *ops;
+    cb->opaque = cb_opaque;
+
+    cap = audio_pcm_capture_find_specific (as);
+    if (cap) {
+        QLIST_INSERT_HEAD (&cap->cb_head, cb, entries);
+        return cap;
     }
     else {
-        s->period.ticks = (ticks_per_sec * s->period.usec) / 1000000;
+        HWVoiceOut *hw;
+        CaptureVoiceOut *cap;
+
+        cap = audio_calloc (AUDIO_FUNC, 1, sizeof (*cap));
+        if (!cap) {
+            dolog ("Could not allocate capture voice, size %zu\n",
+                   sizeof (*cap));
+            goto err1;
+        }
+
+        hw = &cap->hw;
+        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 (struct st_sample));
+        if (!hw->mix_buf) {
+            dolog ("Could not allocate capture mix buffer (%d samples)\n",
+                   hw->samples);
+            goto err2;
+        }
+
+        audio_pcm_init_info (&hw->info, as);
+
+        cap->buf = audio_calloc (AUDIO_FUNC, hw->samples, 1 << hw->info.shift);
+        if (!cap->buf) {
+            dolog ("Could not allocate capture buffer "
+                   "(%d samples, each %d bytes)\n",
+                   hw->samples, 1 << hw->info.shift);
+            goto err3;
+        }
+
+        hw->clip = mixeng_clip
+            [hw->info.nchannels == 2]
+            [hw->info.sign]
+            [hw->info.swap_endianness]
+            [audio_bits_to_index (hw->info.bits)];
+
+        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 (hw))) {
+            audio_attach_capture (hw);
+        }
+        return cap;
+
+    err3:
+        qemu_free (cap->hw.mix_buf);
+    err2:
+        qemu_free (cap);
+    err1:
+        qemu_free (cb);
+    err0:
+        return NULL;
     }
+}
+
+void AUD_del_capture (CaptureVoiceOut *cap, void *cb_opaque)
+{
+    struct capture_callback *cb;
+
+    for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
+        if (cb->opaque == cb_opaque) {
+            cb->ops.destroy (cb_opaque);
+            QLIST_REMOVE (cb, entries);
+            qemu_free (cb);
+
+            if (!cap->cb_head.lh_first) {
+                SWVoiceOut *sw = cap->hw.sw_head.lh_first, *sw1;
 
-    qemu_mod_timer (s->ts, qemu_get_clock (vm_clock) + s->period.ticks);
+                while (sw) {
+                    SWVoiceCap *sc = (SWVoiceCap *) sw;
+#ifdef DEBUG_CAPTURE
+                    dolog ("freeing %s\n", sw->name);
+#endif
+
+                    sw1 = sw->entries.le_next;
+                    if (sw->rate) {
+                        st_rate_stop (sw->rate);
+                        sw->rate = NULL;
+                    }
+                    QLIST_REMOVE (sw, entries);
+                    QLIST_REMOVE (sc, entries);
+                    qemu_free (sc);
+                    sw = sw1;
+                }
+                QLIST_REMOVE (cap, entries);
+                qemu_free (cap);
+            }
+            return;
+        }
+    }
+}
+
+void AUD_set_volume_out (SWVoiceOut *sw, int mute, uint8_t lvol, uint8_t rvol)
+{
+    if (sw) {
+        sw->vol.mute = mute;
+        sw->vol.l = nominal_volume.l * lvol / 255;
+        sw->vol.r = nominal_volume.r * rvol / 255;
+    }
+}
+
+void AUD_set_volume_in (SWVoiceIn *sw, int mute, uint8_t lvol, uint8_t rvol)
+{
+    if (sw) {
+        sw->vol.mute = mute;
+        sw->vol.l = nominal_volume.l * lvol / 255;
+        sw->vol.r = nominal_volume.r * rvol / 255;
+    }
 }