Index: trunk/src/VBox/Devices/Audio/DrvAudio.c
===================================================================
--- trunk/src/VBox/Devices/Audio/audio.c	(revision 44021)
+++ trunk/src/VBox/Devices/Audio/DrvAudio.c	(revision 50680)
@@ -1,3 +1,24 @@
+/* $Id$ */
+/** @file
+ * Intermedia audio driver..
+ *
+ * @remarks Intermediate audio driver having audio device as one of the sink and
+ *          host backend as other..
+ */
+
 /*
+ * Copyright (C) 2006-2014 Oracle Corporation
+ *
+ * This file is part of VirtualBox Open Source Edition (OSE), as
+ * available from http://www.virtualbox.org. This file is free software;
+ * you can redistribute it and/or modify it under the terms of the GNU
+ * General Public License (GPL) as published by the Free Software
+ * Foundation, in version 2 as it comes in the "COPYING" file of the
+ * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
+ * hope that it will be1 useful, but WITHOUT ANY WARRANTY of any kind.
+ * --------------------------------------------------------------------
+ *
+ * This code is based on: audio.c from QEMU AUDIO subsystem.
+ *
  * QEMU Audio subsystem
  *
@@ -22,8 +43,11 @@
  * THE SOFTWARE.
  */
+
+
 #define LOG_GROUP LOG_GROUP_DEV_AUDIO
 #include <VBox/vmm/pdm.h>
 #include <VBox/err.h>
 #include <VBox/vmm/mm.h>
+#include <VBox/vmm/pdmaudioifs.h>
 
 #include <VBox/log.h>
@@ -41,28 +65,9 @@
 
 #define AUDIO_CAP "audio"
-#include "audio.h"
-#include "audio_int.h"
+#include "DrvAudio.h"
 
 #ifdef RT_OS_WINDOWS
 #define strcasecmp stricmp
 #endif
-
-/* #define DEBUG_PLIVE */
-/* #define DEBUG_LIVE */
-/* #define DEBUG_OUT */
-/* #define DEBUG_CAPTURE */
-
-#define SW_NAME(sw) (sw)->name ? (sw)->name : "unknown"
-
-/**
- * @implements PDMIAUDIOCONNECTOR
- */
-typedef struct DRVAUDIO
-{
-    /** The audio interface. */
-    PDMIAUDIOCONNECTOR      IAudioConnector;
-    /** Pointer to the driver instance. */
-    PPDMDRVINS              pDrvIns;
-} DRVAUDIO, *PDRVAUDIO;
 
 static struct audio_driver *drvtab[] = {
@@ -98,4 +103,9 @@
 };
 
+extern t_sample *convAudio;
+extern f_sample *clipAudio;
+
+extern t_sample *convAudioIn;
+extern f_sample *clipAudioIn;
 static char *audio_streamname;
 
@@ -104,48 +114,4 @@
     return audio_streamname;
 }
-
-struct fixed_settings {
-    int enabled;
-    int nb_voices;
-    int greedy;
-    audsettings_t settings;
-};
-
-static struct {
-    struct fixed_settings fixed_out;
-    struct fixed_settings fixed_in;
-    union {
-        int hz;
-        int64_t ticks;
-    } period;
-    int plive;
-} conf = {
-    {                           /* DAC fixed settings */
-        1,                      /* enabled */
-        1,                      /* nb_voices */
-        1,                      /* greedy */
-        {
-            44100,              /* freq */
-            2,                  /* nchannels */
-            AUD_FMT_S16         /* fmt */
-        }
-    },
-
-    {                           /* ADC fixed settings */
-        1,                      /* enabled */
-        1,                      /* nb_voices */
-        1,                      /* greedy */
-        {
-            44100,              /* freq */
-            2,                  /* nchannels */
-            AUD_FMT_S16         /* fmt */
-        }
-    },
-
-    { 200 },                    /* frequency (in Hz) */
-    0,                          /* plive */
-};
-
-static AudioState glob_audio_state;
 
 volume_t nominal_volume = {
@@ -165,5 +131,4 @@
 };
 
-#ifdef VBOX
 volume_t sum_out_volume =
 {
@@ -190,5 +155,139 @@
     INT_MAX
 };
-#endif
+
+
+/***************** ring buffer Hanlding section **************/
+static void IORingBufferCreate(PIORINGBUFFER *ppBuffer, uint32_t cSize)
+{
+    PIORINGBUFFER pTmpBuffer;
+
+    AssertPtr(ppBuffer);
+
+    *ppBuffer = NULL;
+    pTmpBuffer = RTMemAllocZ(sizeof(IORINGBUFFER));
+    if (pTmpBuffer)
+    {
+        pTmpBuffer->pBuffer = RTMemAlloc(cSize);
+        if(pTmpBuffer->pBuffer)
+        {
+            pTmpBuffer->cBufSize = cSize;
+            *ppBuffer = pTmpBuffer;
+        }
+        else
+            RTMemFree(pTmpBuffer);
+    }
+}
+
+static void IORingBufferDestroy(PIORINGBUFFER pBuffer)
+{
+    if (pBuffer)
+    {
+        if (pBuffer->pBuffer)
+            RTMemFree(pBuffer->pBuffer);
+        RTMemFree(pBuffer);
+    }
+}
+
+DECL_FORCE_INLINE(void) IORingBufferReset(PIORINGBUFFER pBuffer)
+{
+    AssertPtr(pBuffer);
+
+    pBuffer->uReadPos = 0;
+    pBuffer->uWritePos = 0;
+    pBuffer->cBufferUsed = 0;
+}
+
+DECL_FORCE_INLINE(uint32_t) IORingBufferFree(PIORINGBUFFER pBuffer)
+{
+    AssertPtr(pBuffer);
+    return pBuffer->cBufSize - ASMAtomicReadU32(&pBuffer->cBufferUsed);
+}
+
+DECL_FORCE_INLINE(uint32_t) IORingBufferUsed(PIORINGBUFFER pBuffer)
+{
+    AssertPtr(pBuffer);
+    return ASMAtomicReadU32(&pBuffer->cBufferUsed);
+}
+
+DECL_FORCE_INLINE(uint32_t) IORingBufferSize(PIORINGBUFFER pBuffer)
+{
+    AssertPtr(pBuffer);
+    return pBuffer->cBufSize;
+}
+
+static void IORingBufferAquireReadBlock(PIORINGBUFFER pBuffer, uint32_t cReqSize, char **ppStart, uint32_t *pcSize)
+{
+    uint32_t uUsed = 0;
+    uint32_t uSize = 0;
+
+    AssertPtr(pBuffer);
+
+    *ppStart = 0;
+    *pcSize = 0;
+
+    /* How much is in use? */
+    uUsed = ASMAtomicReadU32(&pBuffer->cBufferUsed);
+    if (uUsed > 0)
+    {
+        /* Get the size out of the requested size, the read block till the end
+         * of the buffer & the currently used size. */
+        uSize = RT_MIN(cReqSize, RT_MIN(pBuffer->cBufSize - pBuffer->uReadPos, uUsed));
+        if (uSize > 0)
+        {
+            /* Return the pointer address which point to the current read
+             * position. */
+            *ppStart = pBuffer->pBuffer + pBuffer->uReadPos;
+            *pcSize = uSize;
+        }
+    }
+}
+
+DECL_FORCE_INLINE(void) IORingBufferReleaseReadBlock(PIORINGBUFFER pBuffer, uint32_t cSize)
+{
+    AssertPtr(pBuffer);
+
+    /* Split at the end of the buffer. */
+    pBuffer->uReadPos = (pBuffer->uReadPos + cSize) % pBuffer->cBufSize;
+    ASMAtomicSubU32(&pBuffer->cBufferUsed, cSize);
+}
+
+static void IORingBufferAquireWriteBlock(PIORINGBUFFER pBuffer, uint32_t cReqSize, char **ppStart, uint32_t *pcSize)
+{
+    uint32_t uFree;
+    uint32_t uSize;
+
+    AssertPtr(pBuffer);
+
+    *ppStart = 0;
+    *pcSize = 0;
+
+    /* How much is free? */
+    uFree = pBuffer->cBufSize - ASMAtomicReadU32(&pBuffer->cBufferUsed);
+    if (uFree > 0)
+    {
+        /* Get the size out of the requested size, the write block till the end
+         * of the buffer & the currently free size. */
+        uSize = RT_MIN(cReqSize, RT_MIN(pBuffer->cBufSize - pBuffer->uWritePos, uFree));
+        if (uSize > 0)
+        {
+            /* Return the pointer address which point to the current write
+             * position. */
+            *ppStart = pBuffer->pBuffer + pBuffer->uWritePos;
+            *pcSize = uSize;
+        }
+    }
+}
+
+DECL_FORCE_INLINE(void) IORingBufferReleaseWriteBlock(PIORINGBUFFER pBuffer, uint32_t cSize)
+{
+    AssertPtr(pBuffer);
+
+    /* Split at the end of the buffer. */
+    pBuffer->uWritePos = (pBuffer->uWritePos + cSize) % pBuffer->cBufSize;
+
+    ASMAtomicAddU32(&pBuffer->cBufferUsed, cSize);
+}
+
+/****************** Ring Buffer Function Ends *****************/
 
 /* http://www.df.lth.se/~john_e/gems/gem002d.html */
@@ -203,63 +302,18 @@
     return u;
 }
-
 uint32_t lsbindex (uint32_t u)
 {
     return popcount ((u&-u)-1);
 }
-
 uint64_t audio_get_clock (void)
 {
-    AudioState *s;
-
-    s = &glob_audio_state;
-    return PDMDrvHlpTMGetVirtualTime (s->pDrvIns);
-}
-
+    return PDMDrvHlpTMGetVirtualTime (gpDrvIns);
+}
 uint64_t audio_get_ticks_per_sec (void)
 {
-    AudioState *s;
-
-    s = &glob_audio_state;
-    return PDMDrvHlpTMGetVirtualFreq (s->pDrvIns);
-}
-
-#ifdef AUDIO_IS_FLAWLESS_AND_NO_CHECKS_ARE_REQURIED
-#error No its not
-#else
-int audio_bug (const char *funcname, int cond)
-{
-    if (cond) {
-        static int shown;
-
-        AUD_log (NULL, "A bug was just triggered in %s\n", funcname);
-        if (!shown) {
-            shown = 1;
-            AUD_log (NULL, "Save all your work and restart without audio\n");
-            AUD_log (NULL, "Please send a bug, see www.virtualbox.org\n");
-            AUD_log (NULL, "I am sorry\n");
-        }
-        AUD_log (NULL, "Context:\n");
-
-#if defined AUDIO_BREAKPOINT_ON_BUG
-#  if defined HOST_I386
-#    if defined __GNUC__
-        __asm__ ("int3");
-#    elif defined _MSC_VER
-        _asm _emit 0xcc;
-#    else
-        abort ();
-#    endif
-#  else
-        abort ();
-#  endif
-#endif
-    }
-
-    return cond;
-}
-#endif
-
-static inline int audio_bits_to_index (int bits)
+    return PDMDrvHlpTMGetVirtualFreq (gpDrvIns);
+}
+
+inline int audio_bits_to_index (int bits)
 {
     switch (bits) {
@@ -274,29 +328,7 @@
 
     default:
-        audio_bug ("bits_to_index", 1);
-        AUD_log (NULL, "invalid bits %d\n", bits);
+        LogFlow(("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=%" FMTZ "u (len=%" FMTZ "u)\n",
-                 nmemb, size, len);
-        return NULL;
-    }
-
-    return qemu_mallocz (len);
 }
 
@@ -323,10 +355,9 @@
     }
 
-    dolog ("Bogus audfmt %d returning S16\n", fmt);
+    LogFlow(("Bogus audfmt %d returning S16\n", fmt));
     return "S16";
 }
 
-static 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")) {
@@ -355,6 +386,6 @@
     }
     else {
-        dolog ("Bogus audio format `%s' using %s\n",
-               s, audio_audfmt_to_string (defval));
+        LogFlow(("Bogus audio format `%s' using %s\n",
+                  s, audio_audfmt_to_string (defval)));
         *defaultp = 1;
         return defval;
@@ -362,7 +393,5 @@
 }
 
-static audfmt_e audio_get_conf_fmt (PCFGMNODE pCfgHandle, const char *envname,
-                                    audfmt_e defval,
-                                    int *defaultp)
+static audfmt_e drvAudioGetConfFormat(PCFGMNODE pCfgHandle, const char *envname, audfmt_e defval, int *defaultp)
 {
     char *var = NULL;
@@ -382,5 +411,5 @@
 }
 
-static int audio_get_conf_int (PCFGMNODE  pCfgHandle, const char *key, int defval, int *defaultp)
+static int drvAudioGetConfInt(PCFGMNODE pCfgHandle, const char *key, int defval, int *defaultp)
 {
     int rc;
@@ -407,7 +436,5 @@
 }
 
-static const char *audio_get_conf_str (PCFGMNODE  pCfgHandle, const char *key,
-                                       const char *defval,
-                                       int *defaultp)
+static const char *drvAudioGetConfStr(PCFGMNODE  pCfgHandle, const char *key, const char *defval, int *defaultp)
 {
     char *val = NULL;
@@ -429,28 +456,5 @@
 }
 
-void AUD_vlog (const char *cap, const char *fmt, va_list va)
-{
-    va_list va2;
-    va_copy (va2, va); /* Have to make a copy here or GCC will break. */
-    if (cap) {
-        Log (("%s: %N", cap, fmt, &va2));
-    }
-    else {
-        Log (("%N", fmt, &va2));
-    }
-    va_end (va2);
-}
-
-void AUD_log (const char *cap, const char *fmt, ...)
-{
-    va_list va;
-
-    va_start (va, fmt);
-    AUD_vlog (cap, fmt, va);
-    va_end (va);
-}
-
-static void audio_process_options (PCFGMNODE pCfgHandle, const char *prefix,
-                                   struct audio_option *opt)
+static void drvAudioProcessOptions(PCFGMNODE pCfgHandle, const char *prefix, struct audio_option *opt)
 {
     int def;
@@ -458,11 +462,7 @@
     PCFGMNODE pCfgChildChildHandle = NULL;
 
-    if (audio_bug (AUDIO_FUNC, !prefix)) {
-        dolog ("prefix = NULL\n");
-        return;
-    }
-
-    if (audio_bug (AUDIO_FUNC, !opt)) {
-        dolog ("opt = NULL\n");
+    if (!prefix || !opt)
+    {
+        LogFlow(("prefix = NULL OR opt = NULL\n"));
         return;
     }
@@ -471,5 +471,6 @@
     * The getter function will return default values.
     */
-   if(pCfgHandle != NULL) {
+    if(pCfgHandle != NULL)
+    {
        /* If its audio general setting, need to traverse to one child node.
         * /Devices/ichac97/0/LUN#0/Config/Audio
@@ -499,7 +500,9 @@
 
     for (; opt->name; opt++) {
+            LogFlow(("Option value pointer for `%s' is not set\n",
+                   opt->name));
         if (!opt->valp) {
-            dolog ("Option value pointer for `%s' is not set\n",
-                   opt->name);
+            LogFlow(("Option value pointer for `%s' is not set\n",
+                   opt->name));
             continue;
         }
@@ -510,5 +513,5 @@
             {
                 int *intp = opt->valp;
-                *intp =   audio_get_conf_int(pCfgHandle, opt->name, *intp, &def);
+                *intp =   drvAudioGetConfInt(pCfgHandle, opt->name, *intp, &def);
             }
             break;
@@ -517,5 +520,5 @@
             {
                 audfmt_e *fmtp = opt->valp;
-                *fmtp = audio_get_conf_fmt (pCfgHandle, opt->name, *fmtp, &def);
+                *fmtp = drvAudioGetConfFormat(pCfgHandle, opt->name, *fmtp, &def);
             }
             break;
@@ -524,11 +527,11 @@
             {
                 const char **strp = opt->valp;
-                *strp = audio_get_conf_str (pCfgHandle, opt->name, *strp, &def);
+                *strp = drvAudioGetConfStr(pCfgHandle, opt->name, *strp, &def);
             }
             break;
 
         default:
-            dolog ("Bad value tag for option `%s' - %d\n",
-                   opt->name, opt->tag);
+            LogFlow(("Bad value tag for option `%s' - %d\n",
+                   opt->name, opt->tag));
             break;
         }
@@ -541,48 +544,48 @@
 }
 
-static void audio_print_settings (audsettings_t *as)
-{
-    dolog ("frequency=%d nchannels=%d fmt=", as->freq, as->nchannels);
+static void drvAudioPrintSettings(audsettings_t *as)
+{
+    LogFlow(("frequency=%d nchannels=%d fmt=", as->freq, as->nchannels));
 
     switch (as->fmt) {
     case AUD_FMT_S8:
-        AUD_log (NULL, "S8");
+        LogFlow(("S8\n"));
         break;
     case AUD_FMT_U8:
-        AUD_log (NULL, "U8");
+        LogFlow(("U8\n"));
         break;
     case AUD_FMT_S16:
-        AUD_log (NULL, "S16");
+        LogFlow(("S16\n"));
         break;
     case AUD_FMT_U16:
-        AUD_log (NULL, "U16");
+        LogFlow(("U16\n"));
         break;
     case AUD_FMT_S32:
-        AUD_log (NULL, "S32");
+        LogFlow(("S32\n"));
         break;
     case AUD_FMT_U32:
-        AUD_log (NULL, "U32");
+        LogFlow(("U32\n"));
         break;
     default:
-        AUD_log (NULL, "invalid(%d)", as->fmt);
+        LogFlow(("invalid(%d)\n", as->fmt));
         break;
     }
 
-    AUD_log (NULL, " endianness=");
-    switch (as->endianness) {
+    LogFlow(("endianness=\n"));
+    switch (as->endianness)
+    {
     case 0:
-        AUD_log (NULL, "little");
+        LogFlow(("little\n"));
         break;
     case 1:
-        AUD_log (NULL, "big");
+        LogFlow(("big\n"));
         break;
     default:
-        AUD_log (NULL, "invalid");
+        LogFlow(("invalid\n"));
         break;
     }
-    AUD_log (NULL, "\n");
-}
-
-static int audio_validate_settings (audsettings_t *as)
+}
+
+static int drvAudioValidateSettings(audsettings_t *as)
 {
     int invalid;
@@ -608,5 +611,5 @@
 }
 
-static int audio_pcm_info_eq (struct audio_pcm_info *info, audsettings_t *as)
+int drvAudioPcmInfoEq(PDMPCMPROPERTIES * pProps, audsettings_t *as)
 {
     int bits = 8, sign = 0;
@@ -630,12 +633,12 @@
         break;
     }
-    return info->freq == as->freq
-        && info->nchannels == as->nchannels
-        && info->sign == sign
-        && info->bits == bits
-        && info->swap_endianness == (as->endianness != AUDIO_HOST_ENDIANNESS);
-}
-
-void audio_pcm_init_info (struct audio_pcm_info *info, audsettings_t *as)
+    return pProps->uFrequency == as->freq
+        && pProps->cChannels == as->nchannels
+        && pProps->fSigned == sign
+        && pProps->cBits == bits
+        && pProps->fSwapEndian == (as->endianness != AUDIO_HOST_ENDIANNESS);
+}
+
+void drvAudioPcmInitInfo(PDMPCMPROPERTIES * pProps, audsettings_t *as)
 {
     int bits = 8, sign = 0, shift = 0;
@@ -662,12 +665,12 @@
     }
 
-    info->freq = as->freq;
-    info->bits = bits;
-    info->sign = sign;
-    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_endianness = (as->endianness != AUDIO_HOST_ENDIANNESS);
+    pProps->uFrequency = as->freq;
+    pProps->cBits = bits;
+    pProps->fSigned = sign;
+    pProps->cChannels = as->nchannels;
+    pProps->cShift = (as->nchannels == 2) + shift;
+    pProps->fAlign = (1 << pProps->cShift) - 1;
+    pProps->cbPerSec = pProps->uFrequency << pProps->cShift;
+    pProps->fSwapEndian = (as->endianness != AUDIO_HOST_ENDIANNESS);
 }
 
@@ -722,6 +725,5 @@
 
         default:
-            AUD_log (NULL, "audio_pcm_info_clear_buf: invalid bits %d\n",
-                     info->bits);
+            LogFlow(("audio_pcm_info_clear_buf: invalid bits %d\n", info->bits));
             break;
         }
@@ -732,6 +734,5 @@
  * Capture
  */
-static void noop_conv (st_sample_t *dst, const void *src,
-                       int samples, volume_t *vol)
+static void noop_conv (st_sample_t *dst, const void *src, int samples, volume_t *vol)
 {
     (void) src;
@@ -741,49 +742,27 @@
 }
 
-static CaptureVoiceOut *audio_pcm_capture_find_specific (
-    AudioState *s,
-    audsettings_t *as
-    )
-{
-    CaptureVoiceOut *cap;
-
-    for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
-        if (audio_pcm_info_eq (&cap->hw.info, as)) {
-            return cap;
-        }
-    }
-    return NULL;
-}
-
-static void audio_notify_capture (CaptureVoiceOut *cap, audcnotification_e cmd)
-{
-    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);
-    }
-}
-
 static void audio_capture_maybe_changed (CaptureVoiceOut *cap, int enabled)
 {
-    if (cap->hw.enabled != enabled) {
+    if (cap->hw.fEnabled != enabled)
+    {
         audcnotification_e cmd;
-        cap->hw.enabled = enabled;
+        cap->hw.fEnabled = enabled;
         cmd = enabled ? AUD_CNOTIFY_ENABLE : AUD_CNOTIFY_DISABLE;
-        audio_notify_capture (cap, cmd);
-    }
-}
-
-static void audio_recalc_and_notify_capture (CaptureVoiceOut *cap)
-{
-    HWVoiceOut *hw = &cap->hw;
-    SWVoiceOut *sw;
+    }
+}
+
+static void drvAudioRecalcAndNotifyCapture(CaptureVoiceOut *cap)
+{
+    PPDMHOSTVOICEOUT hw = &cap->hw;
+    PPDMGSTVOICEOUT sw;
+    PPDMGSTVOICEOUT pIter;
     int enabled = 0;
-
-    for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
-        if (sw->active) {
+    LogFlow(("drvAudioRecalcAndNotifyCaptuer \n"));
+
+    RTListForEach(&hw->HeadGstVoiceOut, pIter, PDMGSTVOICEOUT, ListGstVoiceOut)
+    {
+        sw = pIter;
+        LogFlow(("1\n"));
+        if (sw->State.fActive) {
             enabled = 1;
             break;
@@ -793,71 +772,82 @@
 }
 
-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;
+void drvAudioDetachCapture(PPDMHOSTVOICEOUT pHostVoiceOut)
+{
+    SWVoiceCap * sc;
+    SWVoiceCap *pIter;
+    LogFlow(("drvAudioDetachCapture \n"));
+    RTListForEach(&pHostVoiceOut->HeadCapturedVoice, pIter, SWVoiceCap, ListCapturedVoice)
+    {
+        sc = pIter;
+        PPDMGSTVOICEOUT sw = &sc->sw;
         CaptureVoiceOut *cap = sc->cap;
-        int was_active = sw->active;
-
-        if (sw->rate) {
-            st_rate_stop (sw->rate);
-            sw->rate = NULL;
-        }
-
-        LIST_REMOVE (sw, entries);
-        LIST_REMOVE (sc, entries);
-        qemu_free (sc);
+        int was_active = sw->State.fActive;
+
+        if (sw->State.rate) {
+            st_rate_stop (sw->State.rate);
+            sw->State.rate = NULL;
+        }
+
+        while (!RTListIsEmpty(&sw->ListGstVoiceOut))
+        {
+            PPDMGSTVOICEOUT pIterTmp = RTListGetFirst(&sw->ListGstVoiceOut, PDMGSTVOICEOUT, ListGstVoiceOut);
+            RTListNodeRemove(&pIterTmp->ListGstVoiceOut);
+        }
+
+        while (!RTListIsEmpty(&sc->ListCapturedVoice))
+        {
+            SWVoiceCap * pIterTmp = RTListGetFirst(&sc->ListCapturedVoice, SWVoiceCap, ListCapturedVoice);
+            RTListNodeRemove(&pIterTmp->ListCapturedVoice);
+        }
+
         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 (AudioState *s, HWVoiceOut *hw)
+            drvAudioRecalcAndNotifyCapture(cap);
+        }
+    }
+}
+
+int drvAudioAttachCapture(PDRVAUDIO pDrvAudio, PPDMHOSTVOICEOUT pHostVoiceOut)
 {
     CaptureVoiceOut *cap;
-
-    audio_detach_capture (hw);
-    for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
+    CaptureVoiceOut *pIter;
+
+    drvAudioDetachCapture(pHostVoiceOut);
+    RTListForEach(&pDrvAudio->HeadCapturedVoice, pIter, CaptureVoiceOut, ListCapturedVoice)
+    {
         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 (%u bytes)\n",
-                   sizeof (*sc));
+        PPDMGSTVOICEOUT pGstVoiceOut;
+        cap = pIter;
+        PPDMHOSTVOICEOUT hw_cap = &cap->hw;
+        sc = (SWVoiceCap*) RTMemAllocZ(1 * sizeof (SWVoiceCap));
+        if (!sc)
+        {
+            LogFlow(("Could not allocate soft capture voice (%u 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);
+        pGstVoiceOut = &sc->sw;
+        pGstVoiceOut->pHostVoiceOut = hw_cap;
+        pGstVoiceOut->Props = pHostVoiceOut->Props;
+        pGstVoiceOut->State.fEmpty = 1;
+        pGstVoiceOut->State.fActive = pHostVoiceOut->fEnabled;
+        LogFlow(("DrvAudio: setting gstvoiceout ratio. Freq=%d and Frew=%d",
+                 hw_cap->Props.uFrequency,  pGstVoiceOut->Props.uFrequency ));
+        pGstVoiceOut->State.ratio = ((int64_t) hw_cap->Props.uFrequency << 32) / pGstVoiceOut->Props.uFrequency;
+        pGstVoiceOut->State.rate = st_rate_start (pGstVoiceOut->Props.uFrequency, hw_cap->Props.uFrequency);
+        if (!pGstVoiceOut->State.rate)
+        {
+            LogFlow(("Error Could not start rate conversion \n"));
+            RTMemFree(pGstVoiceOut);
             return -1;
         }
-        LIST_INSERT_HEAD (&hw_cap->sw_head, sw, entries);
-        LIST_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) {
+        RTListPrepend(&hw_cap->HeadGstVoiceOut, &pGstVoiceOut->ListGstVoiceOut);
+        RTListPrepend(&pHostVoiceOut->HeadCapturedVoice, &sc->ListCapturedVoice);
+        if (pGstVoiceOut->State.fActive)
+        {
             audio_capture_maybe_changed (cap, 1);
         }
@@ -869,12 +859,17 @@
  * Hard voice (capture)
  */
-static int audio_pcm_hw_find_min_in (HWVoiceIn *hw)
-{
-    SWVoiceIn *sw;
-    int m = hw->total_samples_captured;
-
-    for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
-        if (sw->active) {
-            m = audio_MIN (m, sw->total_hw_samples_acquired);
+static int audio_pcm_hw_find_min_in (PPDMHOSTVOICEIN hw)
+{
+    PPDMGSTVOICEIN pIter = NULL;
+    PPDMGSTVOICEIN pGstVoiceIn = NULL;
+    int m = hw->cSamplesCaptured;
+
+    RTListForEach(&hw->HeadGstVoiceIn, pIter, PDMGSTVOICEIN, ListGstVoiceIn)
+    {
+        pGstVoiceIn = pIter;
+        LogFlow(("DrvAudio: pGstVioceIn = %p\n", pGstVoiceIn));
+        if (pGstVoiceIn->State.fActive)
+        {
+            m = audio_MIN (m, pGstVoiceIn->cHostSamplesAcquired);
         }
     }
@@ -882,9 +877,10 @@
 }
 
-int audio_pcm_hw_get_live_in (HWVoiceIn *hw)
-{
-    int live = hw->total_samples_captured - audio_pcm_hw_find_min_in (hw);
-    if (audio_bug (AUDIO_FUNC, live < 0 || live > hw->samples)) {
-        dolog ("live=%d hw->samples=%d\n", live, hw->samples);
+int audio_pcm_hw_get_live_in (PPDMHOSTVOICEIN hw)
+{
+    int live = hw->cSamplesCaptured - audio_pcm_hw_find_min_in (hw);
+    if (live < 0 || live > hw->cSamples)
+    {
+        LogFlow(("Error: live=%d hw->samples=%d\n", live, hw->cSamples));
         return 0;
     }
@@ -895,61 +891,83 @@
  * Soft voice (capture)
  */
-static int audio_pcm_sw_get_rpos_in (SWVoiceIn *sw)
-{
-    HWVoiceIn *hw = sw->hw;
-    int live = hw->total_samples_captured - sw->total_hw_samples_acquired;
+static int audio_pcm_sw_get_rpos_in (PPDMGSTVOICEIN sw)
+{
+    PPDMHOSTVOICEIN hw = sw->hw;
+    int live = hw->cSamplesCaptured - sw->cHostSamplesAcquired;
     int rpos;
 
-    if (audio_bug (AUDIO_FUNC, live < 0 || live > hw->samples)) {
-        dolog ("live=%d hw->samples=%d\n", live, hw->samples);
+    if (live < 0 || live > hw->cSamples)
+    {
+        LogFlow(("Error: live=%d hw->samples=%d\n", live, hw->cSamples));
         return 0;
     }
 
-    rpos = hw->wpos - live;
+    rpos = hw->offWrite - live;
     if (rpos >= 0) {
         return rpos;
     }
     else {
-        return hw->samples + rpos;
-    }
-}
-
-int audio_pcm_sw_read (SWVoiceIn *sw, void *buf, int size)
-{
-    HWVoiceIn *hw = sw->hw;
+        return hw->cSamples + rpos;
+    }
+}
+
+int audio_pcm_sw_read (PDRVAUDIO pThis, PPDMGSTVOICEIN sw, PPDMHOSTSTEREOSAMPLE buf, int size)
+{
+    PPDMHOSTVOICEIN hw = sw->hw;
     int samples, live, ret = 0, swlim, isamp, osamp, rpos, total = 0;
-    st_sample_t *src, *dst = sw->buf;
-
-    rpos = audio_pcm_sw_get_rpos_in (sw) % hw->samples;
-
-    live = hw->total_samples_captured - sw->total_hw_samples_acquired;
-    if (audio_bug (AUDIO_FUNC, live < 0 || live > hw->samples)) {
-        dolog ("live_in=%d hw->samples=%d\n", live, hw->samples);
+    PPDMHOSTSTEREOSAMPLE src, dst = sw->buf;
+    PPDMHOSTSTEREOSAMPLE tmp = sw->buf;
+    PPDMHOSTSTEREOSAMPLE pSampleBuf;
+    char *pcDst = NULL;
+    char *pcSrc = NULL;
+    uint32_t cbToWrite;
+    uint32_t csAvail = 0;
+    uint32_t cSamplesRead = 0;
+    uint32_t cbToRead = 0;
+    uint32_t csWritten = 0;
+    uint32_t cSamplesInRingBuffer = 0;
+    uint32_t csToWrite;
+    uint32_t csLimit;
+
+    /* Max capacity to hold 1000 PDMHOSTSTERESAMPLE type samples. */
+    pSampleBuf = (PPDMHOSTSTEREOSAMPLE) RTMemAlloc(1000 * sizeof(PDMHOSTSTEREOSAMPLE));
+    rpos = audio_pcm_sw_get_rpos_in (sw) % hw->cSamples;
+
+    /* difference between how many samples have be captured/read by the host and how
+     * many have been transferred to guest (guest physical memory) to be utilized by the guest
+     * eg skype on guest or saving samples in file in guest.
+     */
+    live = hw->cSamplesCaptured - sw->cHostSamplesAcquired;
+    if (live < 0 || live > hw->cSamples)
+    {
+        LogFlow(("Error: live_in=%d hw->samples=%d\n", live, hw->cSamples));
         return 0;
     }
 
-    samples = size >> sw->info.shift;
-    if (!live) {
+    samples = size >> sw->Props.cShift;
+    if (!live)
+    {
+        LogFlow(("DrvAudio: Error: No Live data \n"));
         return 0;
     }
 
-    swlim = (live * sw->ratio) >> 32;
+    swlim = (live * sw->State.ratio) >> 32;
+    csLimit = swlim;
     swlim = audio_MIN (swlim, samples);
-
-    while (swlim) {
-        src = hw->conv_buf + rpos;
-        isamp = hw->wpos - rpos;
+    while (swlim)
+    {
+        src = hw->pConversionBuf + rpos;
+        isamp = hw->offWrite - rpos;
         /* XXX: <= ? */
-        if (isamp <= 0) {
-            isamp = hw->samples - rpos;
-        }
-
-        if (!isamp) {
+        if (isamp <= 0)
+            isamp = hw->cSamples - rpos;
+
+        if (!isamp)
             break;
-        }
+
         osamp = swlim;
-
-        if (audio_bug (AUDIO_FUNC, osamp < 0)) {
-            dolog ("osamp=%d\n", osamp);
+        if (osamp < 0)
+        {
+            LogFlow(("Error: osamp=%d\n", osamp));
             return 0;
         }
@@ -958,17 +976,88 @@
             Log(("audio_pcm_sw_read: buffer overflow!! ret = %d, osamp = %d, buf_samples = %d\n",
                   ret, osamp, sw->buf_samples));
-        st_rate_flow (sw->rate, src, dst, &isamp, &osamp);
+        st_rate_flow (sw->State.rate, src, dst, &isamp, &osamp);
         swlim -= osamp;
-        rpos = (rpos + isamp) % hw->samples;
+        rpos = (rpos + isamp) % hw->cSamples;
         dst += osamp;
         ret += osamp;
         total += isamp;
     }
-
-    if (ret > sw->buf_samples)
-        Log(("audio_pcm_sw_read: buffer overflow!! ret = %d, buf_samples = %d\n", ret, sw->buf_samples));
-    sw->clip (buf, sw->buf, ret);
-    sw->total_hw_samples_acquired += total;
-    return ret << sw->info.shift;
+    sw->cHostSamplesAcquired = sw->cHostSamplesAcquired + total;
+    if (csLimit >= samples)
+    {
+        /* read audio that is there in the ring buffer */
+        cSamplesInRingBuffer = IORingBufferUsed(pThis->pAudioReadBuf) / sizeof(PDMHOSTSTEREOSAMPLE);
+        if (cSamplesInRingBuffer >= 45000) /* 750 K Buffer / sizeof(PDMHOSTSTEREOSAMPLE)*/
+        {
+            IORingBufferReset(pThis->pAudioReadBuf);
+            cSamplesInRingBuffer = 0;
+        }
+        if (cSamplesInRingBuffer > samples)
+            cSamplesInRingBuffer = samples;
+        cSamplesRead = 0, cbToRead = 0;
+        while (cSamplesRead < cSamplesInRingBuffer)
+        {
+            cbToRead = cSamplesInRingBuffer * sizeof(PDMHOSTSTEREOSAMPLE);
+            IORingBufferAquireReadBlock(pThis->pAudioReadBuf, cbToRead,
+                                         &pcSrc, &cbToRead);
+            if (!cbToRead)
+                LogFlow(("DrvAudio: There are no audio in queue to be written. \n"));
+            memcpy((uint8_t *)pSampleBuf, pcSrc, cbToRead);
+            cSamplesRead = cSamplesRead + (cbToRead / sizeof(PDMHOSTSTEREOSAMPLE));
+            /* Release the read buffer, so it could be used for new data. */
+            IORingBufferReleaseReadBlock(pThis->pAudioReadBuf, cbToRead);
+        }
+        memcpy((uint8_t *)pSampleBuf + cbToRead, (uint8_t *)sw->buf,
+               (samples - cSamplesRead) * sizeof(PDMHOSTSTEREOSAMPLE));
+
+        memcpy((uint8_t *)buf, (uint8_t *)pSampleBuf, samples * sizeof(PDMHOSTSTEREOSAMPLE));
+
+        csToWrite = ret - (samples - cSamplesRead);
+        csAvail = IORingBufferFree(pThis->pAudioReadBuf) / sizeof(PDMHOSTSTEREOSAMPLE);
+        csWritten = 0;
+        while (csWritten < csToWrite)
+        {
+            cbToWrite = csToWrite * sizeof(PDMHOSTSTEREOSAMPLE);
+            IORingBufferAquireWriteBlock(pThis->pAudioReadBuf, cbToWrite, &pcDst, &cbToWrite);
+
+            csToWrite = cbToWrite / sizeof(PDMHOSTSTEREOSAMPLE);
+            if (RT_UNLIKELY(csToWrite == 0))
+            {
+                IORingBufferReleaseWriteBlock(pThis->pAudioReadBuf, cbToWrite);
+                IORingBufferReset(pThis->pAudioReadBuf);
+                LogFlow(("DrvAudio: NO space in Ring buffer. Not doing anything, just discarding samples.\n"));
+            }
+
+            /* copy the audio data not accepted by the backend to the ring buffer */
+            memcpy(pcDst, (uint8_t*)sw->buf + ((samples - cSamplesRead) * sizeof(PDMHOSTSTEREOSAMPLE)) +
+                   (csWritten * sizeof(PDMHOSTSTEREOSAMPLE)), cbToWrite);
+            IORingBufferReleaseWriteBlock(pThis->pAudioReadBuf, cbToWrite);
+            csWritten += csToWrite;
+        }
+        return samples << sw->Props.cShift;
+    }
+    else if (csLimit < samples && csLimit != 0)
+    {
+        csAvail = IORingBufferFree(pThis->pAudioReadBuf) / sizeof(PDMHOSTSTEREOSAMPLE);
+        csWritten = 0;
+        while (csWritten < ret)
+        {
+            csToWrite = ret - csWritten;
+            cbToWrite = csToWrite * sizeof(PDMHOSTSTEREOSAMPLE);
+            IORingBufferAquireWriteBlock(pThis->pAudioReadBuf, cbToWrite, &pcDst, &cbToWrite);
+
+            csToWrite = cbToWrite / sizeof(PDMHOSTSTEREOSAMPLE);
+            if (RT_UNLIKELY(csToWrite == 0))
+                LogFlow(("DrvAudio: NO space in Ring buffer. Not doing anything, just discarding samples.\n"));
+
+            /* copy the audio data not accepted by the backend to the ring buffer */
+            memcpy(pcDst, (uint8_t*)sw->buf + (csWritten * sizeof(PDMHOSTSTEREOSAMPLE)), cbToWrite);
+            IORingBufferReleaseWriteBlock(pThis->pAudioReadBuf, cbToWrite);
+            csWritten += csToWrite;
+        }
+        memcpy(buf, pSampleBuf, 0);
+        return 0;
+    }
+    return 0;
 }
 
@@ -976,13 +1065,18 @@
  * Hard voice (playback)
  */
-static int audio_pcm_hw_find_min_out (HWVoiceOut *hw, int *nb_livep)
-{
-    SWVoiceOut *sw;
+static int audio_pcm_hw_find_min_out (PPDMHOSTVOICEOUT hw, int *nb_livep)
+{
+    PPDMGSTVOICEOUT sw;
+    PPDMGSTVOICEOUT pIter;
     int m = INT_MAX;
     int nb_live = 0;
-
-    for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
-        if (sw->active || !sw->empty) {
-            m = audio_MIN (m, sw->total_hw_samples_mixed);
+    LogFlow(("Hard Voice Playback \n"));
+
+    RTListForEach(&hw->HeadGstVoiceOut, pIter, PDMGSTVOICEOUT, ListGstVoiceOut)
+    {
+        sw = pIter;
+        if (sw->State.fActive || !sw->State.fEmpty)
+        {
+            m = audio_MIN (m, sw->cSamplesMixed);
             nb_live += 1;
         }
@@ -993,5 +1087,5 @@
 }
 
-int audio_pcm_hw_get_live_out2 (HWVoiceOut *hw, int *nb_live)
+int audio_pcm_hw_get_live_out2 (PPDMHOSTVOICEOUT hw, int *nb_live)
 {
     int smin;
@@ -1002,9 +1096,11 @@
         return 0;
     }
-    else {
+    else
+    {
         int live = smin;
 
-        if (audio_bug (AUDIO_FUNC, live < 0 || live > hw->samples)) {
-            dolog ("live=%d hw->samples=%d\n", live, hw->samples);
+        if (live < 0 || live > hw->cSamples)
+        {
+            LogFlow(("Error: live=%d hw->samples=%d\n", live, hw->cSamples));
             return 0;
         }
@@ -1013,5 +1109,5 @@
 }
 
-int audio_pcm_hw_get_live_out (HWVoiceOut *hw)
+int audio_pcm_hw_get_live_out (PPDMHOSTVOICEOUT hw)
 {
     int nb_live;
@@ -1019,6 +1115,7 @@
 
     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);
+    if (live < 0 || live > hw->cSamples)
+    {
+        LogFlow(("Error: live=%d hw->samples=%d\n", live, hw->cSamples));
         return 0;
     }
@@ -1026,49 +1123,48 @@
 }
 
+#if 0
 /*
  * Soft voice (playback)
  */
-int audio_pcm_sw_write (SWVoiceOut *sw, void *buf, int size)
+int audio_pcm_sw_write (PDRVAUDIO pThis,PPDMGSTVOICEOUT pGstVoiceOut, void *buf, int size)
 {
     int hwsamples, samples, isamp, osamp, wpos, live, dead, left, swlim, blck;
     int ret = 0, pos = 0, total = 0;
 
-    if (!sw) {
+    if (!pGstVoiceOut) {
         return size;
     }
 
-    hwsamples = sw->hw->samples;
-
-    live = sw->total_hw_samples_mixed;
-    if (audio_bug (AUDIO_FUNC, live < 0 || live > hwsamples)){
-        dolog ("live=%d hw->samples=%d\n", live, hwsamples);
-        return 0;
+    hwsamples = pGstVoiceOut->pHostVoiceOut->cSamples;
+    LogFlow(("DrvAudio: hwSamples = %d\n", hwsamples));
+
+    live = pGstVoiceOut->cSamplesMixed;
+    if (live < 0 || live > hwsamples)
+    {
+        LogFlow(("Error: live=%d hw->samples=%d\n", live, hwsamples));
+        return size;
     }
 
     if (live == hwsamples) {
-#ifdef DEBUG_OUT
-        dolog ("%s is full %d\n", sw->name, live);
-#endif
-        return 0;
-    }
-
-    wpos = (sw->hw->rpos + live) % hwsamples;
-    samples = size >> sw->info.shift;
+        LogFlow(("DrvAudio: full %d\n", live));
+        return size;
+    }
+
+    wpos = (pGstVoiceOut->pHostVoiceOut->offRead + live) % hwsamples;
+    samples = size >> pGstVoiceOut->Props.cShift;
 
     dead = hwsamples - live;
-    swlim = ((int64_t) dead << 32) / sw->ratio;
+    swlim = ((int64_t) dead << 32) / pGstVoiceOut->State.ratio;
     swlim = audio_MIN (swlim, samples);
-    if (swlim > sw->buf_samples)
+    if (swlim > pGstVoiceOut->cSamples)
         Log(("audio_pcm_sw_write: buffer overflow!! swlim = %d, buf_samples = %d\n",
-             swlim, pos, sw->buf_samples));
+             swlim, pos, pGstVoiceOut->cSamples));
+    //swlim = samples;
     if (swlim) {
-#ifndef VBOX
-        sw->conv (sw->buf, buf, swlim, &sw->vol);
-#else
-        sw->conv (sw->buf, buf, swlim, &sum_out_volume);
-#endif
-    }
-
-    while (swlim) {
+        convAudio (pGstVoiceOut->buf, buf, swlim, &sum_out_volume);
+    }
+
+    while (swlim)
+    {
         dead = hwsamples - live;
         left = hwsamples - wpos;
@@ -1079,11 +1175,12 @@
         isamp = swlim;
         osamp = blck;
-        if (pos + isamp > sw->buf_samples)
+        //osamp = left;
+        if (pos + isamp > pGstVoiceOut->cSamples)
             Log(("audio_pcm_sw_write: buffer overflow!! isamp = %d, pos = %d, buf_samples = %d\n",
-                 isamp, pos, sw->buf_samples));
+                 isamp, pos, pGstVoiceOut->cSamples));
         st_rate_flow_mix (
-            sw->rate,
-            sw->buf + pos,
-            sw->hw->mix_buf + wpos,
+            pGstVoiceOut->State.rate,
+            pGstVoiceOut->buf + pos,
+            pGstVoiceOut->pHostVoiceOut->pHostSterioSampleBuf + wpos,
             &isamp,
             &osamp
@@ -1097,18 +1194,201 @@
     }
 
-    sw->total_hw_samples_mixed += total;
-    sw->empty = sw->total_hw_samples_mixed == 0;
-
-#ifdef DEBUG_OUT
-    dolog (
-        "%s: write size %d ret %d total sw %d\n",
-        SW_NAME (sw),
-        size >> sw->info.shift,
+    pGstVoiceOut->cSamplesMixed += total;
+    pGstVoiceOut->State.fEmpty = pGstVoiceOut->cSamplesMixed == 0;
+
+    LogFlow((
+        "write size %d ret %d total sw %d\n",
+        size >> pGstVoiceOut->Props.cShift,
         ret,
-        sw->total_hw_samples_mixed
-        );
+        pGstVoiceOut->cSamplesMixed
+        ));
+
+    //return ret << pGstVoiceOut->Props.cShift;
+    return size;
+}
 #endif
 
-    return ret << sw->info.shift;
+/*
+ * Soft voice (playback)
+ */
+int audio_pcm_sw_write(PDRVAUDIO pThis, PPDMGSTVOICEOUT pGstVoiceOut, void *buf, int size)
+{
+    int hwsamples, samples, isamp, osamp, wpos, live, dead, left, swlim, blck;
+    int ret = 0, pos = 0, total = 0;
+    uint8_t *pcDst = NULL;
+    uint8_t *pcSrc = NULL;
+    uint32_t cbToWrite;
+    uint32_t cSamplesInQueue = 0;
+    uint32_t cbSamplesInQueue = 0;
+    uint32_t cbTotalSamples = 0;
+    uint32_t cTotalSamples = 0;
+    uint32_t cSamplesAccepted = 0;
+    /* sample buf to hold the samples that have been passed from Device and to hold samples from the queue
+     * 500 KB.
+     */
+    uint8_t SampleBuf[512000];
+    PDMHOSTSTEREOSAMPLE pdmSampleBuf[5120];
+    uint32_t cSamplesLeft;
+
+    if (!pGstVoiceOut)
+    {
+        LogFlow(("DrvAudio: GstVoiceOut NULL \n"));
+       return size;
+    }
+    LogFlow(("DrvAudio: size to write = %d\n", size));
+
+    hwsamples = pGstVoiceOut->pHostVoiceOut->cSamples;
+
+    live = pGstVoiceOut->cSamplesMixed;
+    if (live < 0 || live > hwsamples)
+    {
+        /* save all the samples in the ring buffer, and return as if all the samples have been accepted.
+         * Saving in ring buffer as host buffer is full and can't take any more samples.
+         */
+        cbToWrite = size;
+        LogFlow(("DrvAudio: Error: live=%d hw->samples=%d\n", live, hwsamples));
+        //return 0
+        IORingBufferAquireWriteBlock(pThis->pAudioWriteBuf, cbToWrite, &pcDst, &cbToWrite);
+        if (RT_UNLIKELY(cbToWrite == 0))
+            LogFlow(("DrvAudio: NO space in Ring buffer. Not doing anything, just discarding samples.\n"));
+
+        /* copy the audio data not accepted by the backend to the ring buffer */
+        memcpy(pcDst, (uint8_t*)buf , cbToWrite);
+
+        /* Rlease the ring buffer */
+        IORingBufferReleaseWriteBlock(pThis->pAudioWriteBuf, cbToWrite);
+        return size;
+    }
+
+    if (live == hwsamples)
+    {
+        /* save all the samples in the ring buffer, and return as if all the samples have been accepted.
+         * Saving in ring buffer as host buffer is full and can't take any more samples.
+         */
+        LogFlow(("DrvAudio: full %d\n", live));
+        //return 0;
+        cbToWrite = size;
+        IORingBufferAquireWriteBlock(pThis->pAudioWriteBuf, cbToWrite, &pcDst, &cbToWrite);
+        if (RT_UNLIKELY(cbToWrite == 0))
+            LogFlow(("DrvAudio: NO space in Ring buffer. Not doing anything, just discarding samples.\n"));
+
+        /* copy the audio data not accepted by the backend to the ring buffer */
+        memcpy(pcDst, (uint8_t*)buf, cbToWrite);
+
+        /* Rlease the ring buffer */
+        IORingBufferReleaseWriteBlock(pThis->pAudioWriteBuf, cbToWrite);
+        return size;
+    }
+
+    wpos = (pGstVoiceOut->pHostVoiceOut->offRead + live) % hwsamples;
+    /* @todo check it. to convert size to num of samples */
+    //samples = cbTotalSamples >> pGstVoiceOut->Props.cShift;
+    samples = size >> pGstVoiceOut->Props.cShift;
+
+    dead = hwsamples - live;
+    /* swlim is upper limit of max no. of samples that can be transferred in this cycle to backend */
+    swlim = ((int64_t) dead << 32) / pGstVoiceOut->State.ratio;
+    swlim = audio_MIN (swlim, samples);
+
+    LogFlow(("DrvAudio: swlim = %d\n", swlim));
+
+    if (swlim > pGstVoiceOut->cSamples)
+        Log(("audio_pcm_sw_write: buffer overflow!! swlim = %d, buf_samples = %d\n",
+             swlim, pos, pGstVoiceOut->cSamples));
+    cSamplesAccepted = swlim;
+     /* find out how much of the queue is full. */
+    cbSamplesInQueue = IORingBufferUsed(pThis->pAudioWriteBuf);
+    /* if ring buffer hold samples > 100 KB, discard samples */
+    if (cbSamplesInQueue > 102400)
+    {
+        LogFlow(("DrvAudio: Samples in ring buffer > 300 KB. Discarding \n"));
+        cbSamplesInQueue = 0;
+        IORingBufferReset(pThis->pAudioWriteBuf);
+    }
+    /* read only that much samples as requried to be processed */
+    if (cbSamplesInQueue > (cSamplesAccepted << pGstVoiceOut->Props.cShift))
+        cbSamplesInQueue = (cSamplesAccepted << pGstVoiceOut->Props.cShift);
+
+    LogFlow(("DrvAudio: Samples in queue =%d and its size=%d\n",
+              cbSamplesInQueue >> pGstVoiceOut->Props.cShift, cbSamplesInQueue));
+
+    /* read all the samples that are there in the queue and copy them to SampleBuf .
+     * Reading all samples from the ring buffer as we need to send these samples first
+     * and then add the samples received in this iteration to the ring buffer.
+     */
+    IORingBufferAquireReadBlock(pThis->pAudioWriteBuf, cbSamplesInQueue, &pcSrc, &cbSamplesInQueue);
+    if (!cbSamplesInQueue)
+        LogFlow(("DrvAudio: There are no audio in queue to be written. \n"));
+
+
+    memcpy(SampleBuf, pcSrc, cbSamplesInQueue);
+    /* Append the buf to samples that were there in the queue. SampBuf holds all the data to transfer */
+    memcpy(SampleBuf + cbSamplesInQueue, buf, size);
+    /* Release the read buffer, so it could be used for new data. */
+    IORingBufferReleaseReadBlock(pThis->pAudioWriteBuf, cbSamplesInQueue);
+
+    /* reset the ring buffer to accept new data. */
+
+    /* cbTotalSamples = size of samples passed from the device + size of samples in the queue */
+    cbTotalSamples = size + cbSamplesInQueue;
+    LogFlow(("DrvAudio: size of samples read = %d and sz of samples recd = %d\n",
+              cbSamplesInQueue, size));
+    LogFlow(("DrvAudio: TotalSamples = %d\n", cbTotalSamples >> pGstVoiceOut->Props.cShift));
+    if (swlim) {
+        /* conversion engine: dest, source, num of samples, volume */
+        convAudio (pGstVoiceOut->buf, SampleBuf, swlim, &sum_out_volume);
+    }
+
+    while (swlim)
+    {
+        dead = hwsamples - live;
+        left = hwsamples - wpos;
+        blck = audio_MIN (dead, left);
+        if (!blck) {
+            break;
+        }
+        isamp = swlim;
+        osamp = blck;
+        if (pos + isamp > pGstVoiceOut->cSamples)
+            Log(("audio_pcm_sw_write: buffer overflow!! isamp = %d, pos = %d, buf_samples = %d\n",
+                 isamp, pos, pGstVoiceOut->cSamples));
+        /* mix and write to the host buffer to be read by the host during playout */
+        st_rate_flow_mix (
+            pGstVoiceOut->State.rate,
+            pGstVoiceOut->buf + pos,
+            pGstVoiceOut->pHostVoiceOut->pHostSterioSampleBuf + wpos,
+            &isamp,
+            &osamp
+            );
+        ret += isamp;
+        swlim -= isamp;
+        pos += isamp;
+        live += osamp;
+        wpos = (wpos + osamp) % hwsamples;
+        total += osamp;
+    }
+
+    pGstVoiceOut->cSamplesMixed += total;
+    pGstVoiceOut->State.fEmpty = pGstVoiceOut->cSamplesMixed == 0;
+
+    cSamplesLeft = (cbTotalSamples >>  pGstVoiceOut->Props.cShift) - cSamplesAccepted ;
+    LogFlow(("DrvAudio: cSamplesLeft = %d\n", cSamplesLeft));
+    if (cSamplesLeft > 0)
+    {
+        cbToWrite = cSamplesLeft << pGstVoiceOut->Props.cShift;
+        /* max capacity of ring buffer is 516196 */
+        //cbToWrite = audio_MIN(cbToWrite, 516196);
+        IORingBufferAquireWriteBlock(pThis->pAudioWriteBuf, cbToWrite, &pcDst, &cbToWrite);
+        if (RT_UNLIKELY(cbToWrite == 0))
+            LogFlow(("DrvAudio: NO space in Ring buffer. Not doing anything, just discarding samples.\n"));
+
+        /* copy the audio data not accepted by the backend to the ring buffer */
+        memcpy(pcDst, (uint8_t*)SampleBuf + (cSamplesAccepted << pGstVoiceOut->Props.cShift), cbToWrite);
+
+        /* Rlease the ring buffer */
+        IORingBufferReleaseWriteBlock(pThis->pAudioWriteBuf, cbToWrite);
+    }
+    /* convert no of samples to bytes */
+    return size;
 }
 
@@ -1116,18 +1396,644 @@
 static void audio_pcm_print_info (const char *cap, struct audio_pcm_info *info)
 {
-    dolog ("%s: bits %d, sign %d, freq %d, nchan %d\n",
-           cap, info->bits, info->sign, info->freq, info->nchannels);
+    LogFlow(("%s: bits %d, sign %d, freq %d, nchan %d\n",
+           cap, info->bits, info->sign, info->freq, info->nchannels));
 }
 #endif
 
-#define DAC
-#include "audio_template.h"
-#undef DAC
-#include "audio_template.h"
-
-int AUD_write (SWVoiceOut *sw, void *buf, int size)
+int AUD_get_buffer_size_out (PPDMGSTVOICEOUT sw)
+{
+    return sw->pHostVoiceOut->cSamples << sw->pHostVoiceOut->Props.cShift;
+}
+
+static int audio_get_avail (PPDMGSTVOICEIN sw)
+{
+    int live;
+
+    if (!sw)
+    {
+        LogFlow(("Error Voice Input Stream NUL \n"));
+        return 0;
+    }
+
+    live = sw->hw->cSamplesCaptured - sw->cHostSamplesAcquired;
+    if (live < 0 || live > sw->hw->cSamples)
+    {
+        LogFlow(("DrvAudio: Error, live=%d sw->hw->samples=%d\n", live, sw->hw->cSamples));
+        return 0;
+    }
+    return (((int64_t) live << 32) / sw->State.ratio) << sw->Props.cShift;
+}
+
+static int audio_get_free(PPDMGSTVOICEOUT sw)
+{
+    int live, dead;
+
+    if (!sw)
+    {
+        LogFlow(("DrvAudio: Error, guest voice output stream null \n"));
+        return 0;
+    }
+
+    live = sw->cSamplesMixed;
+
+    if (live < 0 || live > sw->pHostVoiceOut->cSamples)
+    {
+        LogFlow(("DrvAudio: Error, live=%d sw->hw->samples=%d\n", live, sw->pHostVoiceOut->cSamples));
+        return 0;
+    }
+    dead = sw->pHostVoiceOut->cSamples - live;
+    return (((int64_t) dead << 32) / sw->State.ratio) << sw->Props.cShift;
+}
+
+static void audio_capture_mix_and_clear (PDRVAUDIO pThis, PPDMHOSTVOICEOUT hw, int rpos, int samples)
+{
+    int n;
+    LogFlow(("audio_capture_mix_and_clear \n"));
+    if (hw->fEnabled)
+    {
+        SWVoiceCap *sc;
+        SWVoiceCap *pIter;
+
+        RTListForEach(&hw->HeadCapturedVoice, pIter, SWVoiceCap, ListCapturedVoice)
+        {
+            sc = pIter;
+            PPDMGSTVOICEOUT sw = &sc->sw;
+            int rpos2 = rpos;
+
+            n = samples;
+            while (n)
+            {
+                int till_end_of_hw = hw->cSamples - rpos2;
+                int to_write = audio_MIN (till_end_of_hw, n);
+                int bytes = to_write << hw->Props.cShift;
+                int written;
+
+                sw->buf = hw->pHostSterioSampleBuf + rpos2;
+                written = audio_pcm_sw_write (pThis, sw, NULL, bytes);
+                if (written - bytes) {
+                    LogFlow(("Could not mix %d bytes into a capture "
+                           "buffer, mixed %d\n",
+                           bytes, written));
+                    break;
+                }
+                n -= to_write;
+                rpos2 = (rpos2 + to_write) % hw->cSamples;
+            }
+        }
+    }
+
+    n = audio_MIN (samples, hw->cSamples - rpos);
+    mixeng_sniff_and_clear (hw, hw->pHostSterioSampleBuf + rpos, n);
+    mixeng_sniff_and_clear (hw, hw->pHostSterioSampleBuf, samples - n);
+}
+
+static void drvAudioPlayOut(PDRVAUDIO pThis)
+{
+    PPDMHOSTVOICEOUT hw = NULL;
+    PPDMGSTVOICEOUT sw;
+    PPDMGSTVOICEOUT pIter;
+    PPDMGSTVOICEOUT pIter1;
+
+    while ((hw = drvAudioHlpPcmHwFindAnyEnabledOut(pThis, hw)))
+    {
+        int played;
+        int live, myfree, nb_live, cleanup_required, prev_rpos;
+
+        live = audio_pcm_hw_get_live_out2 (hw, &nb_live);
+        if (!nb_live)
+        {
+            LogFlow(("DrvAudio: Live samples 0\n"));
+            live = 0;
+        }
+
+        if (live < 0 || live > hw->cSamples)
+        {
+            LogFlow(("DrvAudio: live=%d hw->samples=%d\n", live, hw->cSamples));
+            continue;
+        }
+
+        if (hw->pending_disable && !nb_live)
+        {
+            SWVoiceCap *sc;
+            SWVoiceCap *pIter;
+            hw->fEnabled = 0;
+            hw->pending_disable = 0;
+            pThis->pHostDrvAudio->pfnDisableEnableOut(pThis->pHostDrvAudio, hw, VOICE_DISABLE);
+            RTListForEach(&hw->HeadCapturedVoice, pIter, SWVoiceCap , ListCapturedVoice)
+            {
+                sc = pIter;
+                sc->sw.State.fActive = 0;
+                drvAudioRecalcAndNotifyCapture(sc->cap);
+            }
+            continue;
+        }
+
+        if (!live)
+        {
+            RTListForEach(&hw->HeadGstVoiceOut, pIter, PDMGSTVOICEOUT, ListGstVoiceOut)
+            {
+                sw = pIter;
+                if (sw->State.fActive)
+                {
+                    myfree = audio_get_free (sw);
+                    if (myfree > 0)
+                        sw->callback.fn (sw->callback.opaque, myfree);
+                }
+            }
+            continue;
+        }
+
+        prev_rpos = hw->offRead;
+        played = pThis->pHostDrvAudio->pfnPlayOut(pThis->pHostDrvAudio, hw);
+        if (hw->offRead >= hw->cSamples)
+        {
+            LogFlow(("DrvAudio: hw->rpos=%d hw->samples=%d played=%d\n",
+                   hw->offRead, hw->cSamples, played));
+            hw->offRead = 0;
+        }
+        /* I think this code relates to the point to accomodate no of audio samples
+         * that have got accumulated during the above call of pfnplayout. So , it basically
+         * tries to mix the old samples that have already been played, new samples that have
+         * been gathered in due time of playing. Mix them up and send it to audiosniffer for
+         * to be sent to VRDP server to be played on the client.
+         */
+        if (played) {
+            audio_capture_mix_and_clear (pThis, hw, prev_rpos, played);
+        }
+
+        cleanup_required = 0;
+        RTListForEach(&hw->HeadGstVoiceOut, pIter1, PDMGSTVOICEOUT, ListGstVoiceOut)
+        {
+            sw = pIter1;
+            if (!sw->State.fActive && sw->State.fEmpty)
+                continue;
+
+            if (played > sw->cSamplesMixed)
+            {
+                LogFlow(("DrvAudio: played=%d sw->total_hw_samples_mixed=%d\n",
+                       played, sw->cSamplesMixed));
+                played = sw->cSamplesMixed;
+            }
+
+            sw->cSamplesMixed -= played;
+
+            if (!sw->cSamplesMixed)
+            {
+                sw->State.fEmpty = 1;
+                cleanup_required |= !sw->State.fActive && !sw->callback.fn;
+            }
+
+            if (sw->State.fActive)
+            {
+                myfree = audio_get_free (sw);
+                if (myfree > 0)
+                    sw->callback.fn (sw->callback.opaque, myfree);
+            }
+        }
+
+        if (cleanup_required)
+        {
+            PPDMGSTVOICEOUT sw1;
+            RTListForEach(&hw->HeadGstVoiceOut, pIter, PDMGSTVOICEOUT, ListGstVoiceOut)
+            {
+                sw = pIter;
+                if (!sw->State.fActive && !sw->callback.fn)
+                    drvAudioHlpCloseOut(pThis, &pThis->qemuSoundCard, sw);
+            }
+        }
+    }
+}
+
+static void drvAudioPlayIn(PDRVAUDIO pThis)
+{
+    PPDMHOSTVOICEIN hw = NULL;
+
+    while ((hw = drvAudioHlpPcmHwFindAnyEnabledIn(pThis, hw)))
+    {
+        PPDMGSTVOICEIN pIter;
+        int captured, min;
+        captured = pThis->pHostDrvAudio->pfnPlayIn(pThis->pHostDrvAudio, hw);
+
+        min = audio_pcm_hw_find_min_in (hw);
+        hw->cSamplesCaptured += captured - min;
+        hw->ts_helper += captured;
+
+        RTListForEach(&hw->HeadGstVoiceIn, pIter, PDMGSTVOICEIN, ListGstVoiceIn)
+        {
+            pIter->cHostSamplesAcquired -= min;
+
+            if (pIter->State.fActive)
+            {
+                int avail;
+                avail = audio_get_avail (pIter);
+                if (avail > 0)
+                {
+                    pIter->callback.fn(pIter->callback.opaque, avail);
+                }
+            }
+        }
+    }
+}
+
+static void drvAudioCapture(PDRVAUDIO pThis)
+{
+    CaptureVoiceOut *cap;
+    CaptureVoiceOut *pIter;
+
+    RTListForEach(&pThis->HeadCapturedVoice, pIter, CaptureVoiceOut, ListCapturedVoice)
+    {
+        cap = pIter;
+        int live, rpos, captured;
+        PPDMHOSTVOICEOUT hw = &cap->hw;
+        PPDMGSTVOICEOUT sw;
+        PPDMGSTVOICEOUT pIter;
+
+        captured = live = audio_pcm_hw_get_live_out (hw);
+        rpos = hw->offRead;
+        while (live)
+        {
+            int left = hw->cSamples - rpos;
+            int to_capture = audio_MIN (live, left);
+            st_sample_t *src;
+            struct capture_callback *cb;
+
+            src = hw->pHostSterioSampleBuf + rpos;
+            clipAudio (cap->buf, src, to_capture);
+            mixeng_sniff_and_clear (hw, src, to_capture);
+
+            rpos = (rpos + to_capture) % hw->cSamples;
+            live -= to_capture;
+        }
+        hw->offRead = rpos;
+
+        RTListForEach(&hw->HeadGstVoiceOut, pIter, PDMGSTVOICEOUT, ListGstVoiceOut)
+        {
+            sw = pIter;
+            LogFlow(("6\n"));
+            if (!sw->State.fActive && sw->State.fEmpty) {
+                continue;
+            }
+
+            if (captured > sw->cSamplesMixed)
+            {
+                LogFlow(("DrvAudio: captured=%d sw->total_hw_samples_mixed=%d\n",
+                       captured, sw->cSamplesMixed));
+                captured = sw->cSamplesMixed;
+            }
+
+            sw->cSamplesMixed -= captured;
+            sw->State.fEmpty = sw->cSamplesMixed == 0;
+        }
+    }
+}
+static void drvAudioTimer(PDRVAUDIO pThis)
+{
+        drvAudioPlayOut(pThis);
+        drvAudioPlayIn(pThis);
+        drvAudioCapture(pThis);
+        TMTimerSet (pThis->pTimer, TMTimerGet (pThis->pTimer) + pThis->ticks);
+}
+
+static int audio_driver_init (PCFGMNODE pCfgHandle, PDRVAUDIO pThis, struct audio_driver *drv)
+{
+    int max_voices;
+    int voice_size;
+    if (drv->options)
+    {
+        drvAudioProcessOptions(pCfgHandle, drv->name, drv->options);
+    }
+    if (!pThis->pHostDrvAudio->pfnInit(pThis->pHostDrvAudio))
+    {
+        LogFlow(("DrvAudio: Could not init audio driver %p\n", pThis));
+        return VERR_GENERAL_FAILURE;
+    }
+
+    max_voices = pThis->AudioConf.MaxHostVoicesOut;
+    voice_size = pThis->AudioConf.szHostVoiceOut;
+    pThis->cHostOutVoices = 1;
+    if (pThis->cHostOutVoices > max_voices)
+    {
+        if (!max_voices)
+            LogFlow(("Driver `%s' does not support \n", drv->name));
+        else
+            LogFlow(("Driver `%s' does not support %d   voices, max %d\n",
+                   drv->name,
+                   pThis->cHostOutVoices,
+                   max_voices));
+        pThis->cHostOutVoices = 1;//max_voices;
+    }
+
+    if (!voice_size && max_voices)
+    {
+        LogFlow(("drv=`%s' voice_size=0 max_voices=%d\n",
+               drv->name, max_voices));
+        pThis->cHostOutVoices = 0;
+    }
+
+    if (voice_size && !max_voices)
+    {
+        LogFlow(("drv=`%s' voice_size=%d max_voices=0\n",
+               drv->name, voice_size));
+    }
+
+
+    max_voices = pThis->AudioConf.MaxHostVoicesIn;
+    voice_size = pThis->AudioConf.szHostVoiceIn;
+
+    LogFlow(("DrvAudio: voice_size =%d max_voices=%d cHostInVoices=%d\n", voice_size, max_voices, pThis->cHostInVoices));
+    //pThis->cHostInVoices = 1; //@todo handle this
+    if (pThis->cHostInVoices > max_voices)
+    {
+        if (!max_voices)
+            LogFlow(("Driver `%s' does not support \n", drv->name));
+        else
+            LogFlow(("Driver `%s' does not support %d   voices, max %d\n",
+                   drv->name,
+                   pThis->cHostOutVoices,
+                   max_voices));
+        pThis->cHostInVoices = max_voices;
+    }
+
+    if (!voice_size && max_voices)
+    {
+        LogFlow(("drv=`%s' voice_size=0 max_voices=%d\n",
+               drv->name, max_voices));
+        //@todo in original code its 0, but I have made it 1 to avoid crash
+        pThis->cHostInVoices = 0;
+    }
+
+    if (voice_size && !max_voices)
+    {
+        LogFlow(("drv=`%s' voice_size=%d max_voices=0\n",
+               drv->name, voice_size));
+    }
+    return VINF_SUCCESS;
+}
+
+static void audio_vm_change_state_handler (PPDMDRVINS pDrvIns,/* void *opaque,*/ int running)
+{
+    PPDMHOSTVOICEOUT hwo = NULL;
+    PPDMHOSTVOICEIN hwi = NULL;
+    PDRVAUDIO  pThis   = PDMINS_2_DATA(pDrvIns, PDRVAUDIO);
+    int op = running ? VOICE_ENABLE : VOICE_DISABLE;
+
+    while ((hwo = drvAudioHlpPcmHwFindAnyEnabledOut(pThis, hwo))) {
+        pThis->pHostDrvAudio->pfnDisableEnableOut(pThis->pHostDrvAudio, hwo, op);
+    }
+
+    while ((hwi = drvAudioHlpPcmHwFindAnyEnabledIn(pThis, hwi))) {
+        pThis->pHostDrvAudio->pfnDisableEnableIn(pThis->pHostDrvAudio, hwi, op);
+    }
+}
+
+static void drvAudioExit(PPDMDRVINS pDrvIns)
+{
+    PPDMHOSTVOICEOUT hwo = NULL;
+    PPDMHOSTVOICEIN hwi = NULL;
+    PDRVAUDIO  pThis   = PDMINS_2_DATA(pDrvIns, PDRVAUDIO);
+    /* VBox change: audio_pcm_hw_find_any_enabled_out => audio_pcm_hw_find_any_out */
+    while ((hwo = drvAudioHlpPcmHwFindAnyOut(pThis, hwo)))
+    {
+        SWVoiceCap *sc;
+        SWVoiceCap *pIter;
+
+        pThis->pHostDrvAudio->pfnDisableEnableOut(pThis->pHostDrvAudio, hwo, VOICE_DISABLE);
+        pThis->pHostDrvAudio->pfnFiniOut(pThis->pHostDrvAudio, hwo);
+
+        RTListForEach(&hwo->HeadCapturedVoice, pIter, SWVoiceCap, ListCapturedVoice)
+        {
+            sc = pIter;
+            CaptureVoiceOut *cap = sc->cap;
+            struct capture_callback *cb;
+        }
+    }
+
+    /* VBox change: audio_pcm_hw_find_any_enabled_in => audio_pcm_hw_find_any_in */
+    while ((hwi = drvAudioHlpPcmHwFindAnyIn(pThis, hwi)))
+    {
+        pThis->pHostDrvAudio->pfnDisableEnableIn(pThis->pHostDrvAudio, hwi, VOICE_DISABLE);
+        pThis->pHostDrvAudio->pfnFiniIn(pThis->pHostDrvAudio, hwi);
+    }
+}
+
+static DECLCALLBACK(void) audio_timer_helper (PPDMDRVINS pDrvIns, PTMTIMER pTimer, void *pvUser)
+{
+    PDRVAUDIO  pThis   = PDMINS_2_DATA(pDrvIns, PDRVAUDIO);
+    drvAudioTimer(pThis);
+}
+
+static struct audio_option audio_options[] =
+{
+    /* DAC */
+    {"DACFixedSettings", AUD_OPT_BOOL, &conf.fixed_out.enabled,
+     "Use fixed settings for host DAC", NULL, 0},
+
+    {"DACFixedFreq", AUD_OPT_INT, &conf.fixed_out.settings.freq,
+     "Frequency for fixed host DAC", NULL, 0},
+
+    {"DACFixedFmt", AUD_OPT_FMT, &conf.fixed_out.settings.fmt,
+     "Format for fixed host DAC", NULL, 0},
+
+    {"DACFixedChannels", AUD_OPT_INT, &conf.fixed_out.settings.nchannels,
+     "Number of channels for fixed DAC (1 - mono, 2 - stereo)", NULL, 0},
+
+    {"DACVoices", AUD_OPT_INT, &conf.fixed_out.nb_voices,
+     "Number of voices for DAC", NULL, 0},
+
+    /* ADC */
+    {"ADCFixedSettings", AUD_OPT_BOOL, &conf.fixed_in.enabled,
+     "Use fixed settings for host ADC", NULL, 0},
+
+    {"ADCFixedFreq", AUD_OPT_INT, &conf.fixed_in.settings.freq,
+     "Frequency for fixed host ADC", NULL, 0},
+
+    {"ADCFixedFmt", AUD_OPT_FMT, &conf.fixed_in.settings.fmt,
+     "Format for fixed host ADC", NULL, 0},
+
+    {"ADCFixedChannels", AUD_OPT_INT, &conf.fixed_in.settings.nchannels,
+     "Number of channels for fixed ADC (1 - mono, 2 - stereo)", NULL, 0},
+
+    {"ADCVoices", AUD_OPT_INT, &conf.fixed_in.nb_voices,
+     "Number of voices for ADC", NULL, 0},
+
+    /* Misc */
+    {"TimerFreq", AUD_OPT_INT, &conf.period.hz,
+     "Timer frequency in Hz (0 - use lowest possible)", NULL, 0},
+
+    {"PLIVE", AUD_OPT_BOOL, &conf.plive,
+     "(undocumented)", NULL, 0},
+
+    {NULL, 0, NULL, NULL, NULL, 0}
+};
+
+static DECLCALLBACK (void) drvAudioRegisterCard(PPDMIAUDIOCONNECTOR pInterface, const char *name)
+{
+    PDRVAUDIO pThis = PDMIAUDIOCONNECTOR_2_DRVAUDIO(pInterface);
+    LogFlow(("DrvAudio: drvAudioRegisterCard \n"));
+    pThis->qemuSoundCard.name = RTStrDup(name);
+}
+
+static DECLCALLBACK(int) drvAudioInit(PCFGMNODE pCfgHandle, PPDMDRVINS pDrvIns, const char *drvname, PDRVAUDIO  pDrvAudio)
+{
+    size_t i;
+    int done = 0;
+    int rc;
+    PDRVAUDIO  pThis  = PDMINS_2_DATA(pDrvIns, PDRVAUDIO);
+    LogFlow(("DrvAudio: drvAudioInit pDrvAudio=%p and pDrvIns=%p\n", pDrvAudio, pDrvIns));
+
+    RTListInit(&pDrvAudio->HeadHostVoiceOut);
+    RTListInit(&pDrvAudio->HeadHostVoiceIn);
+    RTListInit(&pDrvAudio->HeadHostVoiceIn);
+    RTListInit(&pDrvAudio->HeadCapturedVoice);
+
+    /* get the configuration data from the backend */
+    pDrvAudio->pHostDrvAudio->pfnGetConf(pDrvAudio->pHostDrvAudio, &pDrvAudio->AudioConf);
+
+    rc = PDMDrvHlpTMTimerCreate (pDrvIns, TMCLOCK_VIRTUAL, audio_timer_helper,
+                                 pThis, 0, "Audio timer", &pDrvAudio->pTimer);
+    if (RT_FAILURE (rc))
+    {
+        LogRel(("DrvAudio: Failed to create timer \n"));
+        return rc;
+   }
+
+    drvAudioProcessOptions(pCfgHandle, "AUDIO", audio_options);
+
+    pDrvAudio->cHostOutVoices = conf.fixed_out.nb_voices;
+    pDrvAudio->cHostInVoices = conf.fixed_in.nb_voices;
+
+    pDrvAudio->ticks = 200; /* initialization of ticks */
+
+    /* initialization of audio buffer. Create ring buffer of around 200 KB each . */
+    IORingBufferCreate(&pDrvAudio->pAudioWriteBuf, 512000); /* 500 KB */
+
+    /* allocating space for about 500 msec of audio data 48KHz, 128 bit sample
+     * (guest format - PDMHOSTSTEREOSAMPLE) and dual channel
+     */
+    IORingBufferCreate(&pDrvAudio->pAudioReadBuf, 768000); /* 750 KB */
+
+
+    if (pDrvAudio->cHostOutVoices <= 0)
+    {
+        LogFlow(("Bogus number of playback voices %d, setting to 1\n", pDrvAudio->cHostOutVoices));
+        pDrvAudio->cHostOutVoices = 1;
+    }
+
+    if (pDrvAudio->cHostInVoices <= 0)
+    {
+        LogFlow(("Bogus number of capture voices %d, setting to 0\n", pDrvAudio->cHostInVoices));
+        //@todo in original code its set to 0 currently being set to 1 to ensure atleas 1 voice IN
+        pDrvAudio->cHostInVoices = 1;
+    }
+    LogFlow(("Audio: Trying driver '%s'.\n", drvname));
+
+    if (drvname)
+    {
+        int found = 0;
+        for (i = 0; i < sizeof (drvtab) / sizeof (drvtab[0]); i++)
+        {
+            /* @todo: audioVRDE name wont be visible here. So hardcoding */
+            if (!strcmp (drvname, drvtab[i]->name) || !strcmp(drvname, "AudioVRDE"))
+            {
+                if (!strcmp(drvname, "AudioVRDE"))
+                {
+                    struct audio_driver vrde_audio_driver =
+                    {
+                        INIT_FIELD (name           = ) "AudioVRDE",
+                        INIT_FIELD (descr          = ) "AudioVRDE http://www.pulseaudio.org",
+                        INIT_FIELD (options        = ) NULL,
+                    };
+                    struct audio_driver *drvtabAudioVRDE = &vrde_audio_driver;
+                        done = !audio_driver_init (pCfgHandle, pDrvAudio, drvtabAudioVRDE);
+                }
+                else
+                {
+                    done = !audio_driver_init (pCfgHandle, pDrvAudio, drvtab[i]);
+                }
+                found = 1;
+                break;
+            }
+        }
+
+        if (!found)
+        {
+            LogFlow(("Audio: Unknown audio driver `%s'\n", drvname));
+        }
+    }
+
+    if (!done)
+    {
+        for (i = 0; !done && i < sizeof (drvtab) / sizeof (drvtab[0]); i++) {
+            if (drvtab[i]->can_be_default) {
+                LogRel(("Audio: Initialization of driver '%s' failed, trying '%s'.\n",drvname, drvtab[i]->name));
+                drvname = drvtab[i]->name;
+                done = !audio_driver_init (pCfgHandle, pDrvAudio, drvtab[i]);
+            }
+        }
+    }
+
+    if (!done) {
+        done = !audio_driver_init (pCfgHandle, pThis, &no_audio_driver);
+        if (!done) {
+            LogFlow(("Could not initialize audio subsystem\n"));
+        }
+        else {
+            LogRel(("Audio: Initialization of driver '%s' failed, using NULL driver.\n", drvname));
+            LogFlow(("warning: Using timer based audio emulation\n"));
+        }
+    }
+    if (done)
+    {
+        if (conf.period.hz <= 0)
+        {
+            if (conf.period.hz < 0)
+            {
+                LogFlow(("warning: Timer period is negative - %d "
+                       "treating as zero\n",
+                       conf.period.hz));
+            }
+            pDrvAudio->ticks = 1;
+        }
+        else
+        {
+            pDrvAudio->ticks =  PDMDrvHlpTMGetVirtualFreq(pDrvIns) / conf.period.hz;
+        }
+    }
+    else {
+        /* XXX */
+        rc = TMR3TimerDestroy (pDrvAudio->pTimer);
+        return rc;
+    }
+    TMTimerSet (pDrvAudio->pTimer, TMTimerGet (pDrvAudio->pTimer) + pDrvAudio->ticks);
+    return VINF_SUCCESS;
+}
+static DECLCALLBACK(int) drvAudioInitNull(PPDMIAUDIOCONNECTOR pInterface)
+{
+    PDRVAUDIO pThis = PDMIAUDIOCONNECTOR_2_DRVAUDIO(pInterface);
+    return audio_driver_init(NULL, pThis, &no_audio_driver);
+}
+
+static DECLCALLBACK(int) drvAudioWrite(PPDMIAUDIOCONNECTOR pInterface, PPDMGSTVOICEOUT sw, void *buf, int size)
 {
     int bytes;
-
+    PDRVAUDIO pThis = PDMIAUDIOCONNECTOR_2_DRVAUDIO(pInterface);
+    if (!sw || size < 0)
+    {
+        LogFlow(("DrvAudio: GstVoiceOut is NULL \n"));
+        /* XXX: Consider options */
+        return size;
+    }
+
+    if (!sw->pHostVoiceOut->fEnabled) {
+        return 0;
+    }
+    bytes = audio_pcm_sw_write(pThis, sw, buf, size);
+    return bytes;
+}
+
+static DECLCALLBACK(int) drvAudioRead(PPDMIAUDIOCONNECTOR pInterface, PPDMGSTVOICEIN sw, void *buf, int size)
+{
+    int bytes;
+    PDRVAUDIO pThis = PDMIAUDIOCONNECTOR_2_DRVAUDIO(pInterface);
     if (!sw) {
         /* XXX: Consider options */
@@ -1136,62 +2042,75 @@
 
     if (!sw->hw->enabled) {
-        dolog ("Writing to disabled voice %s\n", SW_NAME (sw));
+        LogFlow(("DrvAudio: Reading from disabled voice \n"));
         return 0;
     }
-
-    bytes = sw->hw->pcm_ops->write (sw, buf, size);
+    bytes = audio_pcm_sw_read(pThis, sw, (PPDMHOSTSTEREOSAMPLE)buf, size);
     return bytes;
 }
 
-int AUD_read (SWVoiceIn *sw, void *buf, int size)
-{
-    int bytes;
-
-    if (!sw) {
-        /* XXX: Consider options */
-        return size;
-    }
-
-    if (!sw->hw->enabled) {
-        dolog ("Reading from disabled voice %s\n", SW_NAME (sw));
-        return 0;
-    }
-
-    bytes = sw->hw->pcm_ops->read (sw, buf, size);
-    return bytes;
-}
-
-int AUD_get_buffer_size_out (SWVoiceOut *sw)
-{
-    return sw->hw->samples << sw->hw->info.shift;
-}
-
-void AUD_set_active_out (SWVoiceOut *sw, int on)
-{
-    HWVoiceOut *hw;
-
-    if (!sw) {
+static DECLCALLBACK(void) drvAudioIsSetOutVolume (PPDMIAUDIOCONNECTOR pInterface, PPDMGSTVOICEOUT sw, int mute, uint8_t lvol, uint8_t rvol)
+{
+    if (sw)
+    {
+        sw->State.uVolumeMute = mute;
+        sw->State.uVolumeLeft    = (uint32_t)lvol * 0x808080; /* maximum is INT_MAX = 0x7fffffff */
+        sw->State.uVolumeRight    = (uint32_t)rvol * 0x808080; /* maximum is INT_MAX = 0x7fffffff */
+    }
+}
+
+
+static DECLCALLBACK(void) drvAudioSetVolume (PPDMIAUDIOCONNECTOR pInterface, int *mute, uint8_t *lvol, uint8_t *rvol)
+{
+    volume_t vol;
+    const char *name;
+
+    uint32_t u32VolumeLeft  = (uint32_t)*lvol;
+    uint32_t u32VolumeRight = (uint32_t)*rvol;
+    /* 0x00..0xff => 0x01..0x100 */
+    if (u32VolumeLeft)
+        u32VolumeLeft++;
+    if (u32VolumeRight)
+        u32VolumeRight++;
+    vol.mute  = *mute;
+    vol.l     = u32VolumeLeft  * 0x800000; /* maximum is 0x80000000 */
+    vol.r     = u32VolumeRight * 0x800000; /* maximum is 0x80000000 */
+    sum_out_volume.mute = 0;
+    sum_out_volume.l    = ASMMultU64ByU32DivByU32(INT_MAX, INT_MAX, 0x80000000U);
+    sum_out_volume.r    = ASMMultU64ByU32DivByU32(INT_MAX, INT_MAX, 0x80000000U);
+}
+
+static DECLCALLBACK(void) drvAudioEnableOut (PPDMIAUDIOCONNECTOR pInterface, PPDMGSTVOICEOUT sw, int on)
+{
+    PPDMHOSTVOICEOUT hw;
+    PDRVAUDIO pThis = PDMIAUDIOCONNECTOR_2_DRVAUDIO(pInterface);
+
+    if (!sw)
         return;
-    }
-
-    hw = sw->hw;
-    if (sw->active != on) {
-        SWVoiceOut *temp_sw;
+
+    hw = sw->pHostVoiceOut;
+    if (sw->State.fActive != on)
+    {
+        PPDMGSTVOICEOUT pIter;
         SWVoiceCap *sc;
-
-        if (on) {
+        SWVoiceCap *pIterCap;
+
+        if (on)
+        {
             hw->pending_disable = 0;
-            if (!hw->enabled) {
-                hw->enabled = 1;
-                hw->pcm_ops->ctl_out (hw, VOICE_ENABLE);
+            if (!hw->fEnabled)
+            {
+                hw->fEnabled = 1;
+                pThis->pHostDrvAudio->pfnDisableEnableOut(pThis->pHostDrvAudio, hw, VOICE_ENABLE);
             }
         }
-        else {
-            if (hw->enabled) {
+        else
+        {
+            if (hw->fEnabled)
+            {
                 int nb_active = 0;
 
-                for (temp_sw = hw->sw_head.lh_first; temp_sw;
-                     temp_sw = temp_sw->entries.le_next) {
-                    nb_active += temp_sw->active != 0;
+                RTListForEach(&hw->HeadGstVoiceOut, pIter, PDMGSTVOICEOUT, ListGstVoiceOut)
+                {
+                    nb_active += pIter->State.fActive != 0;
                 }
 
@@ -1200,793 +2119,340 @@
         }
 
-        for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
-            sc->sw.active = hw->enabled;
-            if (hw->enabled) {
+        RTListForEach(&hw->HeadCapturedVoice, pIterCap, SWVoiceCap, ListCapturedVoice)
+        {
+            sc = pIterCap;
+            sc->sw.State.fActive = hw->fEnabled;
+            if (hw->fEnabled) {
                 audio_capture_maybe_changed (sc->cap, 1);
             }
         }
-        sw->active = on;
-    }
-}
-
-void AUD_set_active_in (SWVoiceIn *sw, int on)
-{
-    HWVoiceIn *hw;
-
+        sw->State.fActive = on;
+    }
+}
+
+static DECLCALLBACK(void) drvAudioEnableIn(PPDMIAUDIOCONNECTOR pInterface, PPDMGSTVOICEIN sw , int on)
+{
+    PPDMHOSTVOICEIN hw;
+    PDRVAUDIO pThis = PDMIAUDIOCONNECTOR_2_DRVAUDIO(pInterface);
     if (!sw) {
+        LogFlow(("DrvAudio: NO GuestVoiceIn. Returning 0\n"));
         return;
     }
 
     hw = sw->hw;
-    if (sw->active != on) {
-        SWVoiceIn *temp_sw;
-
-        if (on) {
-            if (!hw->enabled) {
+    if (sw->State.fActive != on)
+    {
+        PPDMGSTVOICEIN pIter;
+
+        if (on)
+        {
+            if (!hw->enabled)
+            {
                 hw->enabled = 1;
-                hw->pcm_ops->ctl_in (hw, VOICE_ENABLE);
+                pThis->pHostDrvAudio->pfnDisableEnableIn(pThis->pHostDrvAudio, hw, VOICE_ENABLE);
             }
-            sw->total_hw_samples_acquired = hw->total_samples_captured;
-        }
-        else {
-            if (hw->enabled) {
+            sw->cHostSamplesAcquired = hw->cSamplesCaptured;
+        }
+        else
+        {
+            if (hw->enabled)
+            {
                 int nb_active = 0;
 
-                for (temp_sw = hw->sw_head.lh_first; temp_sw;
-                     temp_sw = temp_sw->entries.le_next) {
-                    nb_active += temp_sw->active != 0;
+                RTListForEach(&hw->HeadGstVoiceIn, pIter, PDMGSTVOICEIN, ListGstVoiceIn)
+                {
+                    nb_active += pIter->State.fActive != 0;
                 }
 
                 if (nb_active == 1) {
                     hw->enabled = 0;
-                    hw->pcm_ops->ctl_in (hw, VOICE_DISABLE);
+                    pThis->pHostDrvAudio->pfnDisableEnableIn(pThis->pHostDrvAudio, hw, VOICE_DISABLE);
                 }
             }
         }
-        sw->active = on;
-    }
-}
-
-static int audio_get_avail (SWVoiceIn *sw)
-{
-    int live;
-
-    if (!sw) {
-        return 0;
-    }
-
-    live = sw->hw->total_samples_captured - sw->total_hw_samples_acquired;
-    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;
-    }
-
-    ldebug (
-        "%s: get_avail live %d ret %lld\n",
-        SW_NAME (sw),
-        live, (((int64_t) live << 32) / sw->ratio) << sw->info.shift
-        );
-
-    return (((int64_t) live << 32) / sw->ratio) << sw->info.shift;
-}
-
-static int audio_get_free (SWVoiceOut *sw)
-{
-    int live, dead;
-
-    if (!sw) {
-        return 0;
-    }
-
-    live = sw->total_hw_samples_mixed;
-
-    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 (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_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_sniff_and_clear (hw, hw->mix_buf + rpos, n);
-    mixeng_sniff_and_clear (hw, hw->mix_buf, samples - n);
-}
-
-static void audio_run_out (AudioState *s)
-{
-    HWVoiceOut *hw = NULL;
-    SWVoiceOut *sw;
-
-    while ((hw = audio_pcm_hw_find_any_enabled_out (s, hw))) {
-        int played;
-        int live, myfree, nb_live, cleanup_required, prev_rpos;
-
-        live = audio_pcm_hw_get_live_out2 (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;
-        }
-
-        if (!live) {
-            for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
-                if (sw->active) {
-                    myfree = audio_get_free (sw);
-                    if (myfree > 0) {
-                        sw->callback.fn (sw->callback.opaque, myfree);
-                    }
-                }
-            }
-            continue;
-        }
-
-        prev_rpos = hw->rpos;
-        played = hw->pcm_ops->run_out (hw);
-        if (audio_bug (AUDIO_FUNC, hw->rpos >= hw->samples)) {
-            dolog ("hw->rpos=%d hw->samples=%d played=%d\n",
-                   hw->rpos, hw->samples, played);
-            hw->rpos = 0;
-        }
-
-#ifdef DEBUG_OUT
-        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) {
-            if (!sw->active && sw->empty) {
-                continue;
-            }
-
-            if (audio_bug (AUDIO_FUNC, played > sw->total_hw_samples_mixed)) {
-                dolog ("played=%d sw->total_hw_samples_mixed=%d\n",
-                       played, sw->total_hw_samples_mixed);
-                played = sw->total_hw_samples_mixed;
-            }
-
-            sw->total_hw_samples_mixed -= played;
-
-            if (!sw->total_hw_samples_mixed) {
-                sw->empty = 1;
-                cleanup_required |= !sw->active && !sw->callback.fn;
-            }
-
-            if (sw->active) {
-                myfree = audio_get_free (sw);
-                if (myfree > 0) {
-                    sw->callback.fn (sw->callback.opaque, myfree);
-                }
-            }
-        }
-
-        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 (s, sw);
-                }
-                sw = sw1;
-            }
-        }
-    }
-}
-
-static void audio_run_in (AudioState *s)
-{
-    HWVoiceIn *hw = NULL;
-
-    while ((hw = audio_pcm_hw_find_any_enabled_in (s, hw))) {
-        SWVoiceIn *sw;
-        int captured, min;
-
-        captured = hw->pcm_ops->run_in (hw);
-
-        min = audio_pcm_hw_find_min_in (hw);
-        hw->total_samples_captured += captured - min;
-        hw->ts_helper += captured;
-
-        for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
-            sw->total_hw_samples_acquired -= min;
-
-            if (sw->active) {
-                int avail;
-
-                avail = audio_get_avail (sw);
-                if (avail > 0) {
-                    sw->callback.fn (sw->callback.opaque, avail);
-                }
-            }
-        }
-    }
-}
-
-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);
-        rpos = hw->rpos;
-        while (live) {
-            int left = hw->samples - rpos;
-            int to_capture = audio_MIN (live, left);
-            st_sample_t *src;
-            struct capture_callback *cb;
-
-            src = hw->mix_buf + rpos;
-            hw->clip (cap->buf, src, to_capture);
-            mixeng_sniff_and_clear (hw, 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;
-
-        for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
-            if (!sw->active && sw->empty) {
-                continue;
-            }
-
-            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;
-            }
-
-            sw->total_hw_samples_mixed -= captured;
-            sw->empty = sw->total_hw_samples_mixed == 0;
-        }
-    }
-}
-
-static void audio_timer (void *opaque)
-{
-    AudioState *s = opaque;
-
-    audio_run_out (s);
-    audio_run_in (s);
-    audio_run_capture (s);
-
-    TMTimerSet (s->ts, TMTimerGet (s->ts) + conf.period.ticks);
-}
-
-static struct audio_option audio_options[] = {
-    /* DAC */
-    {"DACFixedSettings", AUD_OPT_BOOL, &conf.fixed_out.enabled,
-     "Use fixed settings for host DAC", NULL, 0},
-
-    {"DACFixedFreq", AUD_OPT_INT, &conf.fixed_out.settings.freq,
-     "Frequency for fixed host DAC", NULL, 0},
-
-    {"DACFixedFmt", AUD_OPT_FMT, &conf.fixed_out.settings.fmt,
-     "Format for fixed host DAC", NULL, 0},
-
-    {"DACFixedChannels", AUD_OPT_INT, &conf.fixed_out.settings.nchannels,
-     "Number of channels for fixed DAC (1 - mono, 2 - stereo)", NULL, 0},
-
-    {"DACVoices", AUD_OPT_INT, &conf.fixed_out.nb_voices,
-     "Number of voices for DAC", NULL, 0},
-
-    /* ADC */
-    {"ADCFixedSettings", AUD_OPT_BOOL, &conf.fixed_in.enabled,
-     "Use fixed settings for host ADC", NULL, 0},
-
-    {"ADCFixedFreq", AUD_OPT_INT, &conf.fixed_in.settings.freq,
-     "Frequency for fixed host ADC", NULL, 0},
-
-    {"ADCFixedFmt", AUD_OPT_FMT, &conf.fixed_in.settings.fmt,
-     "Format for fixed host ADC", NULL, 0},
-
-    {"ADCFixedChannels", AUD_OPT_INT, &conf.fixed_in.settings.nchannels,
-     "Number of channels for fixed ADC (1 - mono, 2 - stereo)", NULL, 0},
-
-    {"ADCVoices", AUD_OPT_INT, &conf.fixed_in.nb_voices,
-     "Number of voices for ADC", NULL, 0},
-
-    /* Misc */
-    {"TimerFreq", AUD_OPT_INT, &conf.period.hz,
-     "Timer frequency in Hz (0 - use lowest possible)", NULL, 0},
-
-    {"PLIVE", AUD_OPT_BOOL, &conf.plive,
-     "(undocumented)", NULL, 0},
-
-    {NULL, 0, NULL, NULL, NULL, 0}
-};
-
-static int audio_driver_init (PCFGMNODE pCfgHandle, AudioState *s, struct audio_driver *drv)
-{
-    if (drv->options) {
-        audio_process_options (pCfgHandle, drv->name, drv->options);
-    }
-    s->drv_opaque = drv->init ();
-
-    if (s->drv_opaque) {
-        /* Filter must be installed before initializing voices. */
-        drv = filteraudio_install(drv, s->drv_opaque);
-        audio_init_nb_voices_out (s, drv);
-        audio_init_nb_voices_in (s, drv);
-        s->drv = drv;
-        return 0;
-    }
-    else {
-        dolog ("Could not init `%s' audio driver\n", drv->name);
-        return -1;
-    }
-}
-
-static void audio_vm_change_state_handler (void *opaque, int running)
-{
-    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);
-    }
-
-    while ((hwi = audio_pcm_hw_find_any_enabled_in (s, hwi))) {
-        hwi->pcm_ops->ctl_in (hwi, op);
-    }
-}
-
-static void audio_atexit (void)
-{
-    AudioState *s = &glob_audio_state;
-    HWVoiceOut *hwo = NULL;
-    HWVoiceIn *hwi = NULL;
-
-    /* VBox change: audio_pcm_hw_find_any_enabled_out => audio_pcm_hw_find_any_out */
-    while ((hwo = audio_pcm_hw_find_any_out (s, hwo))) {
-        SWVoiceCap *sc;
-
-        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) {
-            CaptureVoiceOut *cap = sc->cap;
-            struct capture_callback *cb;
-
-            for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
-                cb->ops.destroy (cb->opaque);
-            }
-        }
-    }
-
-    /* VBox change: audio_pcm_hw_find_any_enabled_in => audio_pcm_hw_find_any_in */
-    while ((hwi = audio_pcm_hw_find_any_in (s, hwi))) {
-        hwi->pcm_ops->ctl_in (hwi, VOICE_DISABLE);
-        hwi->pcm_ops->fini_in (hwi);
-    }
-
-    if (s->drv) {
-        s->drv->fini (s->drv_opaque);
-    }
-}
-
-void AUD_register_card (const char *name, QEMUSoundCard *card)
-{
-    AudioState *s = &glob_audio_state;
-    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);
-}
-
-static DECLCALLBACK(void) audio_timer_helper (PPDMDRVINS pDrvIns, PTMTIMER pTimer, void *pvUser)
-{
-    AudioState *s = (AudioState *)pvUser;
-    audio_timer (s);
-}
-
-static int AUD_init (PCFGMNODE pCfgHandle, PPDMDRVINS pDrvIns, const char *drvname)
-{
-    size_t i;
-    int done = 0;
-    AudioState *s = &glob_audio_state;
-    int rc;
-
-    LIST_INIT (&s->hw_head_out);
-    LIST_INIT (&s->hw_head_in);
-    LIST_INIT (&s->cap_head);
-
-    rc = PDMDrvHlpTMTimerCreate (pDrvIns, TMCLOCK_VIRTUAL, audio_timer_helper,
-                                 &glob_audio_state, 0, "Audio timer", &s->ts);
-    if (RT_FAILURE (rc))
-        return rc;
-
-    audio_process_options (pCfgHandle, "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 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 capture voices %d, setting to 0\n",
-               s->nb_hw_voices_in);
-        s->nb_hw_voices_in = 0;
-    }
-
-    LogRel(("Audio: Trying driver '%s'.\n", drvname));
-
-    if (drvname) {
-        int found = 0;
-
-        for (i = 0; i < sizeof (drvtab) / sizeof (drvtab[0]); i++) {
-            if (!strcmp (drvname, drvtab[i]->name)) {
-                done = !audio_driver_init (pCfgHandle, s, drvtab[i]);
-                found = 1;
-                break;
-            }
-        }
-
-        if (!found) {
-            dolog ("Unknown audio driver `%s'\n", drvname);
-        }
-    }
-
-    if (!done) {
-        for (i = 0; !done && i < sizeof (drvtab) / sizeof (drvtab[0]); i++) {
-            if (drvtab[i]->can_be_default) {
-                LogRel(("Audio: Initialization of driver '%s' failed, trying '%s'.\n",
-                       drvname, drvtab[i]->name));
-                drvname = drvtab[i]->name;
-                done = !audio_driver_init (pCfgHandle, s, drvtab[i]);
-            }
-        }
-    }
-
-    if (!done) {
-        done = !audio_driver_init (pCfgHandle, s, &no_audio_driver);
-        if (!done) {
-            dolog ("Could not initialize audio subsystem\n");
-        }
-        else {
-            LogRel(("Audio: Initialization of driver '%s' failed, using NULL driver.\n", drvname));
-            dolog ("warning: Using timer based audio emulation\n");
-        }
-    }
-
-    if (done) {
-        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 = PDMDrvHlpTMGetVirtualFreq (pDrvIns)
-                / conf.period.hz;
-        }
-    }
-    else {
-        /* XXX */
-        rc = TMR3TimerDestroy (s->ts);
-        return rc;
-    }
-
-    LIST_INIT (&s->card_head);
-    TMTimerSet (s->ts, TMTimerGet (s->ts) + conf.period.ticks);
-    return VINF_SUCCESS;
-}
-
-int AUD_init_null(void)
-{
-    AudioState *s = &glob_audio_state;
-
-#ifdef VBOX
-    if (s->drv)
-        s->drv->fini (s->drv_opaque);
-#endif
-
-    LogRel(("Audio: Using NULL audio driver\n"));
-    return audio_driver_init (NULL, s, &no_audio_driver);
-}
-
-CaptureVoiceOut *AUD_add_capture (
-    AudioState *s,
-    audsettings_t *as,
-    struct audio_capture_ops *ops,
-    void *cb_opaque
-    )
-{
-    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);
-        goto err0;
-    }
-
-    cb = audio_calloc (AUDIO_FUNC, 1, sizeof (*cb));
-    if (!cb) {
-        dolog ("Could not allocate capture callback information, size %u\n",
-               sizeof (*cb));
-        goto err0;
-    }
-    cb->ops = *ops;
-    cb->opaque = cb_opaque;
-
-    cap = audio_pcm_capture_find_specific (s, as);
-    if (cap) {
-        LIST_INSERT_HEAD (&cap->cb_head, cb, entries);
-        return cap;
-    }
-    else {
-        HWVoiceOut *hw;
-#ifndef VBOX
-        CaptureVoiceOut *cap;
-#endif
-
-        cap = audio_calloc (AUDIO_FUNC, 1, sizeof (*cap));
-        if (!cap) {
-            dolog ("Could not allocate capture voice, size %u\n",
-                   sizeof (*cap));
-            goto err1;
-        }
-
-        hw = &cap->hw;
-        LIST_INIT (&hw->sw_head);
-        LIST_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));
-        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)];
-
-        LIST_INSERT_HEAD (&s->cap_head, cap, entries);
-        LIST_INSERT_HEAD (&cap->cb_head, cb, entries);
-
-        hw = NULL;
-        while ((hw = audio_pcm_hw_find_any_out (s, hw))) {
-            audio_attach_capture (s, 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);
-            LIST_REMOVE (cb, entries);
-            qemu_free (cb);
-
-            if (!cap->cb_head.lh_first) {
-                SWVoiceOut *sw = cap->hw.sw_head.lh_first, *sw1;
-
-                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;
-                    }
-                    LIST_REMOVE (sw, entries);
-                    LIST_REMOVE (sc, entries);
-                    qemu_free (sc);
-                    sw = sw1;
-                }
-                LIST_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    = (uint32_t)lvol * 0x808080; /* maximum is INT_MAX = 0x7fffffff */
-        sw->vol.r    = (uint32_t)rvol * 0x808080; /* maximum is INT_MAX = 0x7fffffff */
-    }
-}
-
-void AUD_set_volume (audmixerctl_t mt, int *mute, uint8_t *lvol, uint8_t *rvol)
-{
-    volume_t *vol = NULL;
-    const char *name;
-
-    switch (mt)
-    {
-        case AUD_MIXER_VOLUME:
-            name = "MASTER";
-            vol  = &master_out_volume;
-            break;
-        case AUD_MIXER_PCM:
-            name = "PCM_OUT";
-            vol  = &pcm_out_volume;
-            break;
-        case AUD_MIXER_LINE_IN:
-            name = "LINE_IN";
-            vol  = &pcm_in_volume;
-            break;
-        default:
-            return;
-
-    }
-
-    if (vol)
-    {
-        uint32_t u32VolumeLeft  = (uint32_t)*lvol;
-        uint32_t u32VolumeRight = (uint32_t)*rvol;
-        /* 0x00..0xff => 0x01..0x100 */
-        if (u32VolumeLeft)
-            u32VolumeLeft++;
-        if (u32VolumeRight)
-            u32VolumeRight++;
-        vol->mute  = *mute;
-        vol->l     = u32VolumeLeft  * 0x800000; /* maximum is 0x80000000 */
-        vol->r     = u32VolumeRight * 0x800000; /* maximum is 0x80000000 */
-    }
-    sum_out_volume.mute = master_out_volume.mute || pcm_out_volume.mute;
-    sum_out_volume.l    = ASMMultU64ByU32DivByU32(master_out_volume.l, pcm_out_volume.l, 0x80000000U);
-    sum_out_volume.r    = ASMMultU64ByU32DivByU32(master_out_volume.r, pcm_out_volume.r, 0x80000000U);
-}
-
-void AUD_set_record_source (audrecsource_t *ars, audrecsource_t *als)
-{
-    LogRel(("Audio: set_record_source ars=%d als=%d (not implemented)\n", *ars, *als));
-}
-
-int AUD_is_host_voice_in_ok(SWVoiceIn *sw)
-{
-    AudioState *s = &glob_audio_state;
-
+        sw->State.fActive = on;
+    }
+}
+
+static DECLCALLBACK(int) drvAudioIsHostVoiceInOK(PPDMIAUDIOCONNECTOR pInterface, PPDMGSTVOICEIN sw)
+{
     if (sw == NULL) {
         return 0;
     }
-
-    return filteraudio_is_host_voice_in_ok(s->drv, sw->hw);
-}
-
-int AUD_is_host_voice_out_ok(SWVoiceOut *sw)
-{
-    AudioState *s = &glob_audio_state;
-
+    return 1;
+}
+
+static DECLCALLBACK(int) drvAudioIsHostVoiceOutOK(PPDMIAUDIOCONNECTOR pInterface, PPDMGSTVOICEOUT sw)
+{
     if (sw == NULL) {
         return 0;
     }
-
-    return filteraudio_is_host_voice_out_ok(s->drv, sw->hw);
-}
+    return 1;
+}
+
+static DECLCALLBACK(int) drvAudioOpenIn(PPDMIAUDIOCONNECTOR pInterface, PPDMGSTVOICEIN *ppGstVoiceIn,
+                                        const char *name, void *callback_opaque , audio_callback_fn_t callback_fn,
+                                        uint32_t uFrequency, uint32_t cChannels, audfmt_e Format, uint32_t Endian)
+{
+    PDRVAUDIO pThis = PDMIAUDIOCONNECTOR_2_DRVAUDIO(pInterface);
+    audsettings_t AudioSettings;
+    AudioSettings.freq = uFrequency;
+    AudioSettings.nchannels = cChannels;
+    AudioSettings.fmt = Format;
+    AudioSettings.endianness = Endian;
+    LogFlow(("DrvAudio: open IN %s, freq %d, nchannels %d, fmt %d\n",
+             name, AudioSettings.freq, AudioSettings.nchannels, AudioSettings.fmt));
+
+    if (drvAudioValidateSettings(&AudioSettings))
+    {
+        LogRel(("Audio: Audio Settings Validation failed \n"));
+        drvAudioPrintSettings(&AudioSettings);
+        drvAudioHlpCloseIn(pThis, &pThis->qemuSoundCard, *ppGstVoiceIn);
+        *ppGstVoiceIn = (PPDMGSTVOICEIN)NULL;
+        return VERR_GENERAL_FAILURE;
+    }
+
+    if (*ppGstVoiceIn && drvAudioPcmInfoEq(&(*ppGstVoiceIn)->Props, &AudioSettings))
+        return VINF_SUCCESS;
+
+    if (!conf.fixed_in.enabled && *ppGstVoiceIn)
+    {
+        drvAudioHlpCloseIn(pThis, &pThis->qemuSoundCard, *ppGstVoiceIn);
+        *ppGstVoiceIn = (PPDMGSTVOICEIN )NULL;
+    }
+
+    if (*ppGstVoiceIn)
+    {
+        PPDMHOSTVOICEIN pHostVoiceIn = (*ppGstVoiceIn)->hw;
+
+        if (!pHostVoiceIn)
+        {
+            LogFlow(("Internal logic error voice has no hardware store\n"));
+            drvAudioHlpCloseIn(pThis, &pThis->qemuSoundCard, *ppGstVoiceIn);
+            *ppGstVoiceIn = (PPDMGSTVOICEIN)NULL;
+            return VERR_GENERAL_FAILURE;
+        }
+
+        drvAudioHlpPcmSwFinishedIn(*ppGstVoiceIn);
+        if (drvAudioHlpPcmSwInitIn(*ppGstVoiceIn, pHostVoiceIn, name, &AudioSettings))
+        {
+            drvAudioHlpCloseIn(pThis, &pThis->qemuSoundCard, *ppGstVoiceIn);
+            *ppGstVoiceIn = (PPDMGSTVOICEIN)NULL;
+            return VERR_GENERAL_FAILURE;
+        }
+    }
+    else
+    {
+        *ppGstVoiceIn = drvAudioHlpPcmCreateVoicePairIn(pThis, name, &AudioSettings);
+        if (!(*ppGstVoiceIn))
+        {
+            LogFlow(("Failed to create voice `%s'\n", name));
+            *ppGstVoiceIn = (PPDMGSTVOICEIN)NULL;
+            return VERR_GENERAL_FAILURE;
+        }
+    }
+
+    if (*ppGstVoiceIn)
+    {
+        (*ppGstVoiceIn)->State.uVolumeLeft = nominal_volume.l;
+        (*ppGstVoiceIn)->State.uVolumeRight = nominal_volume.r;
+        (*ppGstVoiceIn)->State.uVolumeMute = nominal_volume.mute;
+        (*ppGstVoiceIn)->callback.fn = callback_fn;
+        (*ppGstVoiceIn)->callback.opaque = callback_opaque;
+    }
+    return VINF_SUCCESS;
+}
+
+
+static DECLCALLBACK(int) drvAudioOpenOut(PPDMIAUDIOCONNECTOR pInterface, PPDMGSTVOICEOUT *ppGstVoiceOut, const char *name,
+                                         void *callback_opaque, audio_callback_fn_t callback_fn,
+                                         uint32_t uFrequency, uint32_t cChannels, audfmt_e Format, uint32_t Endian)
+{
+    int cLiveSamples = 0;
+    AudioState *s;
+    int rc;
+    PPDMGSTVOICEOUT pOldGstVoiceOut;
+    PDRVAUDIO pThis = PDMIAUDIOCONNECTOR_2_DRVAUDIO(pInterface);
+    audsettings_t AudioSettings;
+    AudioSettings.freq = uFrequency;
+    AudioSettings.nchannels = cChannels;
+    AudioSettings.fmt = Format;
+    AudioSettings.endianness = Endian;
+
+    LogFlow(("DrvAudio: open OUT %s, freq %d, nchannels %d, fmt %d\n",
+            name, AudioSettings.freq, AudioSettings.nchannels, AudioSettings.fmt));
+
+    if (drvAudioValidateSettings(&AudioSettings))
+    {
+        LogRel(("DrvAudio: Audio Settings Validation failed \n"));
+        drvAudioPrintSettings(&AudioSettings);
+        drvAudioHlpCloseOut(pThis, &pThis->qemuSoundCard, *ppGstVoiceOut);
+        *ppGstVoiceOut = (PPDMGSTVOICEOUT)NULL;
+        return VERR_GENERAL_FAILURE;
+    }
+
+    if (*ppGstVoiceOut && drvAudioPcmInfoEq(&(*ppGstVoiceOut)->Props, &AudioSettings))
+        return VINF_SUCCESS;
+
+    if (  conf.plive && *ppGstVoiceOut
+        && (!(*ppGstVoiceOut)->State.fActive
+        && !(*ppGstVoiceOut)->State.fEmpty)
+       )
+    {
+        cLiveSamples = (*ppGstVoiceOut)->cSamplesMixed;
+        if(cLiveSamples)
+        {
+            pOldGstVoiceOut = *ppGstVoiceOut;
+            *ppGstVoiceOut = NULL;
+        }
+    }
+
+    if (!conf.fixed_out.enabled && *ppGstVoiceOut)
+    {
+        drvAudioHlpCloseOut(pThis, &pThis->qemuSoundCard, *ppGstVoiceOut);
+        *ppGstVoiceOut = (PPDMGSTVOICEOUT *)NULL;
+    }
+
+    if (*ppGstVoiceOut)
+    {
+        PPDMHOSTVOICEOUT pHostVoiceOut = (*ppGstVoiceOut)->pHostVoiceOut;
+        if (!pHostVoiceOut)
+        {
+            LogFlow(("Guest Voice Stream has no Host voice stream in store\n"));
+            return VERR_GENERAL_FAILURE;
+        }
+
+        drvAudioHlpPcmSwFinishedOut(*ppGstVoiceOut);
+        rc = drvAudioHlpPcmSwInitOut(*ppGstVoiceOut, pHostVoiceOut, name, &AudioSettings);
+        if (RT_FAILURE(rc))
+            return rc;
+    }
+    else
+    {
+        (*ppGstVoiceOut) = drvAudioHlpPcmCreateVoicePairOut(pThis, s, name, &AudioSettings);
+        if (!(*ppGstVoiceOut))
+        {
+            LogFlow(("Failed to create voice `%s'\n", name));
+            *ppGstVoiceOut = (PPDMGSTVOICEOUT)NULL;
+            return VERR_GENERAL_FAILURE;
+        }
+    }
+
+    if (*ppGstVoiceOut)
+    {
+        (*ppGstVoiceOut)->State.uVolumeLeft = nominal_volume.l;
+        (*ppGstVoiceOut)->State.uVolumeRight = nominal_volume.r;
+        (*ppGstVoiceOut)->State.uVolumeMute = nominal_volume.mute;
+        (*ppGstVoiceOut)->callback.fn = callback_fn;
+        (*ppGstVoiceOut)->callback.opaque = callback_opaque;
+        if (cLiveSamples)
+        {
+            int mixed =
+                (cLiveSamples << pOldGstVoiceOut->Props.cShift)
+                * pOldGstVoiceOut->Props.cbPerSec
+                / (*ppGstVoiceOut)->Props.cbPerSec;
+
+            (*ppGstVoiceOut)->cSamplesMixed += mixed;
+        }
+    }
+
+    return VINF_SUCCESS;
+}
+
+static DECLCALLBACK(int) drvAudioIsActiveIn(PPDMIAUDIOCONNECTOR pInterface, PPDMGSTVOICEIN pGstVoiceIn)
+{
+    return pGstVoiceIn ? pGstVoiceIn->State.fActive : 0;
+}
+
+static DECLCALLBACK(int) drvAudioIsActiveOut(PPDMIAUDIOCONNECTOR pInterface, PPDMGSTVOICEOUT pGstVoiceOut)
+{
+    return pGstVoiceOut ? pGstVoiceOut->State.fActive : 0;
+}
+
+static DECLCALLBACK(t_sample *)drvAudioConvDevFmtToStSample(PPDMIAUDIOCONNECTOR pInterface, uint32_t cChannels,
+                                                     uint32_t fSign, uint32_t uEndian, uint32_t ubitIdx)
+{
+    LogFlow(("DrvAudio: drvAudioConvStSamplToFmt \n"));
+    return   mixeng_conv[cChannels] /* stereo */
+                         [fSign]     /* sign */
+                         [uEndian]   /* big endian */
+                         [ubitIdx];  /* bits */
+
+}
+
+static DECLCALLBACK(f_sample *)drvAudioConvStSampleToDevFmt(PPDMIAUDIOCONNECTOR pInterface, void *buf,
+                                                            PPDMHOSTSTEREOSAMPLE pSampleBuf, uint32_t samples)
+{
+    /*@todo handle ths properly*/
+    clipAudioIn (buf, pSampleBuf, samples);
+}
+
+
+static DECLCALLBACK(void *)drvAudioPrepareAudioConversion(PPDMIAUDIOCONNECTOR pInterface, uint32_t uSampleFreq, uint32_t uTgtFreq)
+{
+    return st_rate_start (uSampleFreq, uTgtFreq);
+}
+
+static DECLCALLBACK(void)drvAudioEndAudioConversion(PPDMIAUDIOCONNECTOR pInterface, void * pRate)
+{
+    AssertPtr(pRate);
+    st_rate_stop (pRate);
+}
+
+static DECLCALLBACK(void)drvAudioDoRateConversion(PPDMIAUDIOCONNECTOR pInterface, void * pRate,
+                                                  PPDMHOSTSTEREOSAMPLE pHostStereoSampleBuf,
+                                                  PPDMHOSTSTEREOSAMPLE pConvertedSampleBuf,
+                                                  uint32_t * pcSampleSrc, uint32_t *pcConvertedSamples)
+{
+    AssertPtr(pRate);
+    st_rate_flow(pRate, pHostStereoSampleBuf, pConvertedSampleBuf, pcSampleSrc, pcConvertedSamples);
+
+}
+
+static DECLCALLBACK(void)drvAudioDoRateConvAndMix(PPDMIAUDIOCONNECTOR pInterface, void * pRate,
+                                                  PPDMHOSTSTEREOSAMPLE pSourceSampleBuf,
+                                                  PPDMHOSTSTEREOSAMPLE pTargetMixedSampleBuf,
+                                                  uint32_t * pcSampleSrc, uint32_t *pcMixedSamples)
+{
+    st_rate_flow_mix(pRate, pSourceSampleBuf, pTargetMixedSampleBuf, pcSampleSrc, pcMixedSamples);
+
+}
+
+/****************************************************************/
+
+static DECLCALLBACK(void) drvAudioCloseIn(PPDMIAUDIOCONNECTOR pInterface, PPDMGSTVOICEIN pGstVoiceIn)
+{
+    PDRVAUDIO pThis = PDMIAUDIOCONNECTOR_2_DRVAUDIO(pInterface);
+    if (pGstVoiceIn)
+    {
+        if (!&pThis->qemuSoundCard || !pThis->qemuSoundCard.audio)
+        {
+            LogFlow(("DrvAudio: Error, card=%p card->audio=%p\n",
+                   (void *) &pThis->qemuSoundCard, &pThis->qemuSoundCard ? (void *) pThis->qemuSoundCard.audio : NULL));
+            return;
+        }
+        drvAudioHlpCloseIn(pThis, pThis->qemuSoundCard.audio, pGstVoiceIn);
+    }
+}
+
+DECLCALLBACK(void) drvAudioCloseOut(PPDMIAUDIOCONNECTOR pInterface, PPDMGSTVOICEOUT pGstVoiceOut)
+{
+    PDRVAUDIO pThis = PDMIAUDIOCONNECTOR_2_DRVAUDIO(pInterface);
+    if (pGstVoiceOut) {
+        if (!&pThis->qemuSoundCard || !pThis->qemuSoundCard.audio)
+        {
+            LogFlow(("DrvAudio: Error, card=%p card->audio=%p\n",
+                   (void *) &pThis->qemuSoundCard, &pThis->qemuSoundCard ? (void *) pThis->qemuSoundCard.audio : NULL));
+            return;
+        }
+
+        drvAudioHlpCloseOut(pThis, pThis->qemuSoundCard.audio, pGstVoiceOut);
+    }
+}
+
+
+/********************************************************************/
+
+
 
 /**
@@ -2009,6 +2475,5 @@
 static DECLCALLBACK(void) drvAudioPowerOff(PPDMDRVINS pDrvIns)
 {
-    AudioState *s = &glob_audio_state;
-    audio_vm_change_state_handler (s, 0);
+    audio_vm_change_state_handler (pDrvIns, 0);
 }
 
@@ -2031,7 +2496,7 @@
         audio_streamname = NULL;
     }
-
-    audio_atexit ();
-}
+    drvAudioExit(pDrvIns);
+}
+
 
 /**
@@ -2044,14 +2509,8 @@
     PDRVAUDIO   pThis = PDMINS_2_DATA(pDrvIns, PDRVAUDIO);
     char       *drvname;
-    int         rc;
-
-    LogFlow(("drvAUDIOConstruct:\n"));
+    int         rc = 0;
+    PPDMIBASE pBase;
+
     PDMDRV_CHECK_VERSIONS_RETURN(pDrvIns);
-
-    /*
-     * Validate the config.
-     */
-    if (!CFGMR3AreValuesValid(pCfgHandle, "AudioDriver\0StreamName\0"))
-        return VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES;
 
     /*
@@ -2062,17 +2521,58 @@
     pDrvIns->IBase.pfnQueryInterface  = drvAudioQueryInterface;
     /* IAudio */
-    /* pThis->IAudioConnector.pfn; */
-
-    glob_audio_state.pDrvIns = pDrvIns;
-
+    pThis->IAudioConnector.pfnRead             = drvAudioRead;
+    pThis->IAudioConnector.pfnWrite            = drvAudioWrite;
+    pThis->IAudioConnector.pfnRegisterCard     = drvAudioRegisterCard;
+    pThis->IAudioConnector.pfnIsHostVoiceInOK  = drvAudioIsHostVoiceInOK;
+    pThis->IAudioConnector.pfnIsHostVoiceOutOK = drvAudioIsHostVoiceOutOK;
+    pThis->IAudioConnector.pfnInitNull         = drvAudioInitNull;
+    pThis->IAudioConnector.pfnIsSetOutVolume   = drvAudioIsSetOutVolume;
+    pThis->IAudioConnector.pfnSetVolume        = drvAudioSetVolume;
+    pThis->IAudioConnector.pfnEnableOut        = drvAudioEnableOut;
+    pThis->IAudioConnector.pfnEnableIn         = drvAudioEnableIn;
+    pThis->IAudioConnector.pfnCloseIn          = drvAudioCloseIn;
+    pThis->IAudioConnector.pfnCloseOut         = drvAudioCloseOut;
+    pThis->IAudioConnector.pfnOpenIn           = drvAudioOpenIn;
+    pThis->IAudioConnector.pfnOpenOut          = drvAudioOpenOut;
+    pThis->IAudioConnector.pfnIsActiveIn       = drvAudioIsActiveIn;
+    pThis->IAudioConnector.pfnIsActiveOut      = drvAudioIsActiveOut;
+    /* Mixer/Conversion */
+    pThis->IAudioConnector.pfnConvDevFmtToStSample   = drvAudioConvDevFmtToStSample;
+    pThis->IAudioConnector.pfnConvStSampleToDevFmt   = drvAudioConvStSampleToDevFmt;
+    pThis->IAudioConnector.pfnPrepareAudioConversion = drvAudioPrepareAudioConversion;
+    pThis->IAudioConnector.pfnEndAudioConversion     = drvAudioEndAudioConversion;
+    pThis->IAudioConnector.pfnDoRateConversion       = drvAudioDoRateConversion;
+    pThis->IAudioConnector.pfnDoRateConvAndMix       = drvAudioDoRateConvAndMix;
+
+    rc = PDMDrvHlpAttach(pDrvIns, fFlags, &pBase);
+    if (RT_FAILURE(rc))
+    {
+        LogRel(("Failed to attach  the audio device rc = %d \n", rc));
+        return rc;
+    }
+    pThis->pHostDrvAudio = PDMIBASE_QUERY_INTERFACE(pBase, PDMIHOSTAUDIO);
+    if (!pThis->pHostDrvAudio)
+    {
+        LogRel(("Audio: Failed to attach to underlying host driver \n"));
+        return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_MISSING_INTERFACE_BELOW,
+                                N_("No media or async media interface below"));
+    }
+
+    pThis->pDrvIns = pDrvIns;
+    gpDrvIns = pThis->pDrvIns;
     rc = CFGMR3QueryStringAlloc (pCfgHandle, "AudioDriver", &drvname);
     if (RT_FAILURE (rc))
+    {
+        LogFlow(("Failed to get AudioDriver from CFGM\n"));
         return rc;
+    }
 
     rc = CFGMR3QueryStringAlloc (pCfgHandle, "StreamName", &audio_streamname);
     if (RT_FAILURE (rc))
+    {
+        LogFlow(("Failed to get SteamName from CFGM \n"));
         audio_streamname = NULL;
-
-    rc = AUD_init (pCfgHandle, pDrvIns, drvname);
+    }
+    rc = drvAudioInit(pCfgHandle, pDrvIns, drvname, pThis);
     if (RT_FAILURE (rc))
         return rc;
@@ -2091,6 +2591,5 @@
 static DECLCALLBACK(void) drvAudioSuspend(PPDMDRVINS pDrvIns)
 {
-    AudioState *s = &glob_audio_state;
-    audio_vm_change_state_handler (s, 0);
+    audio_vm_change_state_handler(pDrvIns, 0);
 }
 
@@ -2103,6 +2602,5 @@
 static DECLCALLBACK(void) audioResume(PPDMDRVINS pDrvIns)
 {
-    AudioState *s = &glob_audio_state;
-    audio_vm_change_state_handler (s, 1);
+    audio_vm_change_state_handler(pDrvIns, 1);
 }
 
@@ -2127,5 +2625,5 @@
     PDM_DRVREG_CLASS_AUDIO,
     /* cMaxInstances */
-    1,
+    2,
     /* cbInstance */
     sizeof(DRVAUDIO),
@@ -2158,2 +2656,3 @@
 };
 
+
